feat(wechat): migrate schedule and sync handlers into wechat package
Extract schedule, greeting/status/connectivity replies, chat-general prompt, and display-name helpers from wechat-mp.mjs. Route sync intents via classifyWechatIntent and add channel isolation CI check. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -0,0 +1,37 @@
|
||||
export function looksLikeScheduleConfirmation(text) {
|
||||
const compact = String(text ?? '').replace(/\s+/g, '');
|
||||
if (!compact) return false;
|
||||
if (/(没有|没能|未能|无法|不能|失败|需要你|请补充|请告诉)/.test(compact)) return false;
|
||||
return /(已经|已|现在).{0,12}(设置|安排|记录|加上|添加|创建).{0,12}(待办|提醒|日程|安排|闹钟)|设置好了|已经设置好了|已经加上/.test(
|
||||
compact,
|
||||
);
|
||||
}
|
||||
|
||||
export async function guardScheduleConfirmationReply({
|
||||
replyText,
|
||||
scheduleService,
|
||||
userId,
|
||||
sourceMessageId,
|
||||
logger,
|
||||
}) {
|
||||
if (!scheduleService || !looksLikeScheduleConfirmation(replyText)) return replyText;
|
||||
const messageId = String(sourceMessageId ?? '').trim();
|
||||
if (!messageId || typeof scheduleService.listItemsBySourceMessage !== 'function') {
|
||||
return replyText;
|
||||
}
|
||||
const items = await scheduleService
|
||||
.listItemsBySourceMessage({
|
||||
userId,
|
||||
sourceMessageId: messageId,
|
||||
limit: 5,
|
||||
})
|
||||
.catch((err) => {
|
||||
logger?.warn?.('Schedule confirmation guard failed:', err);
|
||||
return [];
|
||||
});
|
||||
if (items.length > 0) return replyText;
|
||||
return [
|
||||
'我刚才没有确认到待办/提醒已经写入系统,所以这次不能算设置成功。',
|
||||
'请再发一次完整安排,比如“明天早上 6 点跑步,5 点半提醒我”。我会在工具写入成功后再确认。',
|
||||
].join('\n');
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
import { isScheduleIntent, parseScheduleIntent } from '../../schedule-intent.mjs';
|
||||
|
||||
export async function handleWechatScheduleIntent({ intent, user, scheduleService }) {
|
||||
if (!scheduleService) return null;
|
||||
const scheduleIntent = parseScheduleIntent(intent.agentText);
|
||||
if (!isScheduleIntent(scheduleIntent)) return null;
|
||||
|
||||
const timezone = process.env.H5_DEFAULT_TIMEZONE || 'Asia/Shanghai';
|
||||
|
||||
if (scheduleIntent.action === 'create_todo') {
|
||||
if (scheduleIntent.needsClarification?.includes('todo_title')) {
|
||||
return '可以。你想让我记哪一条待办?例如“帮我记一下 跟段吃饭”。';
|
||||
}
|
||||
const item = await scheduleService.createItem({
|
||||
userId: user.userId,
|
||||
kind: 'task',
|
||||
title: scheduleIntent.title,
|
||||
timezone,
|
||||
sourceChannel: 'wechat',
|
||||
sourceMessageId: intent.msgId || null,
|
||||
sourceText: intent.agentText,
|
||||
metadata: {
|
||||
source: 'wechat_mp',
|
||||
},
|
||||
});
|
||||
return `已记录到待办列表:${item.title},未设置提醒。`;
|
||||
}
|
||||
|
||||
if (scheduleIntent.action === 'create_daily_todo_digest') {
|
||||
if (scheduleIntent.needsClarification?.includes('digest_time')) {
|
||||
return '可以。你想每天几点收到当天待办记录?比如“每天早上 7 点发给我”。';
|
||||
}
|
||||
const subscription = await scheduleService.createDailyTodoDigest({
|
||||
userId: user.userId,
|
||||
hour: scheduleIntent.hour,
|
||||
minute: scheduleIntent.minute,
|
||||
timezone,
|
||||
channel: 'wechat',
|
||||
sourceChannel: 'wechat',
|
||||
sourceMessageId: intent.msgId || null,
|
||||
sourceText: intent.agentText,
|
||||
});
|
||||
const minuteText = subscription.minute === 0 ? '' : `${String(subscription.minute).padStart(2, '0')}分`;
|
||||
return `已设置:我会每天早上 ${subscription.hour}点${minuteText} 通过服务号把当天待办记录发给你。`;
|
||||
}
|
||||
|
||||
if (scheduleIntent.action === 'create_balance_alert') {
|
||||
if (scheduleIntent.needsClarification?.includes('threshold')) {
|
||||
return '可以。你想在余额低于多少时提醒我?例如“余额低于 20 元提醒我”。';
|
||||
}
|
||||
const subscription = await scheduleService.createBalanceLowAlert({
|
||||
userId: user.userId,
|
||||
thresholdCents: scheduleIntent.thresholdCents,
|
||||
channel: 'wechat',
|
||||
sourceChannel: 'wechat',
|
||||
sourceMessageId: intent.msgId || null,
|
||||
sourceText: intent.agentText,
|
||||
});
|
||||
return `已设置:当余额低于 ${(subscription.thresholdCents / 100).toFixed(2)} 元时,我会通过服务号提醒你。`;
|
||||
}
|
||||
|
||||
if (scheduleIntent.action === 'query_schedule') {
|
||||
return scheduleService.buildTodoDigestText({
|
||||
userId: user.userId,
|
||||
timezone,
|
||||
});
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import { resolveWechatAddressName } from '../user/display-name.mjs';
|
||||
|
||||
export function buildGreetingText(user) {
|
||||
const name = resolveWechatAddressName(user);
|
||||
return name ? `你好,${name}!我在呢,有什么需要?` : '你好!我在呢,有什么需要?';
|
||||
}
|
||||
|
||||
export function buildStatusText(user, fallbackText) {
|
||||
const name = resolveWechatAddressName(user);
|
||||
if (!name) return fallbackText;
|
||||
return `我在这边,${name}。上一条如果还没完成,我会继续把结果发给你;你也可以直接补一句要求。`;
|
||||
}
|
||||
|
||||
export function buildConnectivityTestReply(user) {
|
||||
const name = resolveWechatAddressName(user);
|
||||
return name
|
||||
? `${name},公众号消息通道正常,我收到你的测试了。`
|
||||
: '公众号消息通道正常,我收到你的测试了。';
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve an immediate sync XML reply for lightweight intents.
|
||||
* @returns {string|null}
|
||||
*/
|
||||
export function resolveSyncReply(wechatIntent, user, { statusFallbackText = '' } = {}) {
|
||||
switch (wechatIntent?.kind) {
|
||||
case 'status.probe':
|
||||
return buildStatusText(user, statusFallbackText);
|
||||
case 'greeting':
|
||||
return buildGreetingText(user);
|
||||
case 'connectivity.test':
|
||||
return buildConnectivityTestReply(user);
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether this intent should be answered synchronously before agent dispatch.
|
||||
*/
|
||||
export function shouldHandleSyncReply(intent, wechatIntent) {
|
||||
const msgType = String(intent?.msgType ?? '').toLowerCase();
|
||||
if (wechatIntent?.kind === 'connectivity.test') {
|
||||
return msgType === 'text' || msgType === 'voice';
|
||||
}
|
||||
if (wechatIntent?.kind === 'status.probe' || wechatIntent?.kind === 'greeting') {
|
||||
return msgType === 'text';
|
||||
}
|
||||
return false;
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
import { buildAutoChatSkillPrefix } from '../../chat-skills.mjs';
|
||||
import { shouldUseScheduleAssistant } from '../../schedule-intent.mjs';
|
||||
import { buildCurrentTimeAgentPrefix } from '../../user-memory-profile.mjs';
|
||||
import { isPageGenerateText, wantsDocxDownload } from '../intent/patterns.mjs';
|
||||
|
||||
export function buildWechatAgentPrompt(intent, { grantedSkills = [] } = {}) {
|
||||
const msgType = String(intent?.msgType ?? 'text');
|
||||
const agentText = intent?.agentText ?? intent?.content ?? '';
|
||||
const autoSkillPrefix =
|
||||
msgType === 'text' || msgType === 'voice'
|
||||
? buildAutoChatSkillPrefix(agentText, grantedSkills)
|
||||
: '';
|
||||
const docxDownloadHint =
|
||||
isPageGenerateText(agentText) && wantsDocxDownload(agentText)
|
||||
? [
|
||||
'【Word 下载要求】用户明确要求页面里可下载 Word / docx。',
|
||||
'开始前必须先调用 `load_skill` → `docx-generate`,并按技能说明生成目标 `public/*.docx`。',
|
||||
'生成后必须确认目标 `.docx` 已存在,再调用 `load_skill` → `static-page-publish` 写 `public/*.html`。',
|
||||
'HTML 中只能用同目录相对路径链接该文档;禁止只写下载按钮却没有先把 `.docx` 落盘。',
|
||||
'',
|
||||
].join('\n')
|
||||
: '';
|
||||
const pagePublishHint = isPageGenerateText(agentText)
|
||||
? [
|
||||
'【页面发布技能要求】这条消息是在生成可访问 HTML 页面。',
|
||||
'开始前必须先调用 `load_skill` → `static-page-publish`,不能省略,也不能写完页面后再补调。',
|
||||
'随后必须用 sandbox-fs 的 `write_file` / `edit_file` 写入 `public/*.html`。',
|
||||
'禁止用 shell / cat / heredoc / echo / cp 写入 HTML:shell 在容器内执行,文件不会出现在公网 MindSpace 路径,用户会收到「文件不存在」。',
|
||||
'在回复用户前,确认 `public/` 下目标 HTML 已通过 write_file 落盘;没有落盘就不要发送链接或说「已发布」。',
|
||||
'最终只给用户一个正式域名的唯一正确链接;不要输出错误域名、备用链接或让用户手动保存文件。',
|
||||
'',
|
||||
].join('\n')
|
||||
: '';
|
||||
const scheduleTimezone = process.env.H5_DEFAULT_TIMEZONE || 'Asia/Shanghai';
|
||||
const currentTimeHint = buildCurrentTimeAgentPrefix({ timezone: scheduleTimezone });
|
||||
const scheduleAssistantHint = shouldUseScheduleAssistant(agentText)
|
||||
? [
|
||||
'【日程技能要求】这条消息涉及待办、提醒或日程。',
|
||||
'开始前先加载 `schedule-assistant` skill,并严格按 skill 里的边界执行。',
|
||||
'写入工具时优先使用 startLocal / endLocal / remindLocal(YYYY-MM-DD HH:mm),不要自行估算 Unix 毫秒。',
|
||||
'只有在 `schedule_create_item` / `schedule_create_reminder` 等工具成功返回后,才能告诉用户“已经设置好了”。',
|
||||
intent?.msgId ? `调用 schedule_create_item 时必须传入 sourceMessageId: ${intent.msgId}` : '',
|
||||
'',
|
||||
].filter(Boolean).join('\n')
|
||||
: '';
|
||||
|
||||
if (msgType === 'voice') {
|
||||
return [
|
||||
docxDownloadHint,
|
||||
currentTimeHint,
|
||||
scheduleAssistantHint,
|
||||
'【微信服务号语音消息】用户通过语音输入,以下是微信识别结果。',
|
||||
'',
|
||||
`用户语音识别文本:${autoSkillPrefix}${String(agentText).trim()}`,
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join('\n');
|
||||
}
|
||||
if (msgType === 'image') {
|
||||
return [
|
||||
docxDownloadHint,
|
||||
currentTimeHint,
|
||||
scheduleAssistantHint,
|
||||
'【微信服务号图片消息】用户发送了图片。',
|
||||
'如用户没有明确要求,请先根据图片内容给出简短理解,并询问下一步。',
|
||||
'',
|
||||
String(agentText).trim(),
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join('\n');
|
||||
}
|
||||
if (msgType === 'location') {
|
||||
const location = intent?.location ?? {};
|
||||
return [
|
||||
currentTimeHint,
|
||||
scheduleAssistantHint,
|
||||
'【微信服务号位置消息】用户发送了当前位置。',
|
||||
location.label ? `地址:${location.label}` : '',
|
||||
location.latitude !== null && location.latitude !== undefined
|
||||
? `纬度:${location.latitude}`
|
||||
: '',
|
||||
location.longitude !== null && location.longitude !== undefined
|
||||
? `经度:${location.longitude}`
|
||||
: '',
|
||||
'请结合位置回答用户可能的路线、附近、行程或提醒需求;如果意图不明确,先简短询问。',
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join('\n');
|
||||
}
|
||||
if (msgType === 'link') {
|
||||
const link = intent?.link ?? {};
|
||||
return [
|
||||
currentTimeHint,
|
||||
scheduleAssistantHint,
|
||||
'【微信服务号链接消息】用户分享了链接。',
|
||||
link.title ? `标题:${link.title}` : '',
|
||||
link.description ? `描述:${link.description}` : '',
|
||||
link.url ? `URL:${link.url}` : '',
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join('\n');
|
||||
}
|
||||
const content = String(agentText).trim();
|
||||
const lines = [currentTimeHint];
|
||||
if (docxDownloadHint) lines.push(docxDownloadHint);
|
||||
if (pagePublishHint) lines.push(pagePublishHint);
|
||||
if (scheduleAssistantHint) lines.push(scheduleAssistantHint);
|
||||
lines.push(
|
||||
'【微信服务号新消息】请只回答下面这条用户消息,不要主动延续无关的历史话题。',
|
||||
'若用户只是在测试连通性,请一句话确认收到即可,不要展开旧任务。',
|
||||
'',
|
||||
`用户消息:${autoSkillPrefix}${content}`,
|
||||
);
|
||||
return lines.join('\n');
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
export function normalizeWechatName(value) {
|
||||
const name = String(value ?? '').trim();
|
||||
if (!name || /^wx_[a-z0-9_]{4,64}$/i.test(name)) return '';
|
||||
return name;
|
||||
}
|
||||
|
||||
export function resolveWechatAddressName(user) {
|
||||
return normalizeWechatName(user?.nickname) || normalizeWechatName(user?.displayName) || '';
|
||||
}
|
||||
@@ -10,7 +10,10 @@ import {
|
||||
selectSendableHtmlArtifacts,
|
||||
verifyPageArtifactContent,
|
||||
} from './verify/page-artifact.mjs';
|
||||
import { guardScheduleConfirmationReply, looksLikeScheduleConfirmation } from './handlers/schedule-guard.mjs';
|
||||
import { resolvePageGenerateOutcome } from './handlers/page-generate.mjs';
|
||||
import { buildGreetingText, resolveSyncReply } from './handlers/sync-replies.mjs';
|
||||
import { buildWechatAgentPrompt } from './prompts/chat-general.mjs';
|
||||
|
||||
test('classifyWechatIntent detects page.generate', () => {
|
||||
const intent = classifyWechatIntent({
|
||||
@@ -50,6 +53,42 @@ test('selectSendableHtmlArtifacts never returns stub html', () => {
|
||||
assert.equal(isStubPublicHtmlContent('<html>服务号自动补出简版页面</html>'), true);
|
||||
});
|
||||
|
||||
test('resolveSyncReply handles greeting and status probes', () => {
|
||||
const user = { nickname: '唐' };
|
||||
assert.match(
|
||||
resolveSyncReply(classifyWechatIntent({ msgType: 'text', agentText: '你好' }), user, {
|
||||
statusFallbackText: '处理中',
|
||||
}),
|
||||
/唐/,
|
||||
);
|
||||
assert.match(
|
||||
resolveSyncReply(classifyWechatIntent({ msgType: 'text', agentText: '??' }), user, {
|
||||
statusFallbackText: '处理中',
|
||||
}),
|
||||
/我在这边/,
|
||||
);
|
||||
});
|
||||
|
||||
test('buildWechatAgentPrompt lives in wechat prompts package', () => {
|
||||
const prompt = buildWechatAgentPrompt({
|
||||
msgType: 'text',
|
||||
agentText: '明天早上 6 点跑步,5 点半提醒我',
|
||||
});
|
||||
assert.match(prompt, /schedule-assistant/);
|
||||
});
|
||||
|
||||
test('schedule confirmation guard blocks false positives', async () => {
|
||||
assert.equal(looksLikeScheduleConfirmation('已经帮你设置好了待办提醒'), true);
|
||||
const guarded = await guardScheduleConfirmationReply({
|
||||
replyText: '已经帮你设置好了待办提醒',
|
||||
scheduleService: { listItemsBySourceMessage: async () => [] },
|
||||
userId: 'user-1',
|
||||
sourceMessageId: 'msg-1',
|
||||
logger: null,
|
||||
});
|
||||
assert.match(guarded, /不能算设置成功/);
|
||||
});
|
||||
|
||||
test('resolvePageGenerateOutcome fails when only stub artifacts exist', () => {
|
||||
const outcome = resolvePageGenerateOutcome({
|
||||
reply: { text: '页面已生成 https://m.tkmind.cn/MindSpace/u/public/tang-poem.html' },
|
||||
|
||||
Reference in New Issue
Block a user