fix(wechat): bind page follow-ups to explicit task targets
This commit is contained in:
@@ -0,0 +1,34 @@
|
||||
# 微信服务号任务路由与目标绑定
|
||||
|
||||
服务号已有规则分类、可选 LLM 分类、日程/定时任务处理器以及 Agent 工具执行链。
|
||||
`wechat/intent/task-route.mjs` 在既有分类之后增加本轮任务决策,修复改页追问和新任务之间的上下文串用。
|
||||
|
||||
## 决策与执行
|
||||
|
||||
- `chat`:处理本轮问题;显式聊天频道、不要生成页面、文字/密码/日程修改不能被页面分类覆盖。
|
||||
- `page.create`:新建页面。有现存对话时轮换 Agent 会话,不携带旧正文;本轮完整需求仍是唯一正文来源。
|
||||
- `page.from_context`:将紧邻诗文等内容排版成页面,保留原有即时上下文守卫。
|
||||
- `page.edit`:从用户提供的页面链接/文件路径,或当前会话最近 assistant 文本中的唯一页面链接绑定目标。
|
||||
- `clarify`:目标缺失或最近回复包含多个页面时直接询问链接,不启动 Agent,不扫描工作区猜文件。
|
||||
|
||||
编辑目标传入 Agent 提示和 `metadata.memindRun.wechatTaskTarget`;模式记入 `wechatTaskMode`。
|
||||
记忆编排必须保留本轮任务提示;普通执行、页面补写和异常重试均携带相同目标约束。
|
||||
正式发送编辑结果前,必须有目标页面产物,且产物/回复不得混入其他页面路径。
|
||||
|
||||
## 边界
|
||||
|
||||
这是现有执行链上的第一阶段约束,不是完整的多任务调度器,也未实现工具层文件写权限沙箱。
|
||||
交付检查能阻止错页链接被当作成功结果发送,不能撤销 Agent 已做出的错误写入。
|
||||
当前只使用紧邻 assistant 的页面链接;跨话题恢复旧页面须用户重发链接,不从长期记忆猜测。
|
||||
上下文读取失败时不猜编辑目标;已有真实 route 时间戳的新建请求仍轮换旧会话。
|
||||
没有数据库迁移,目标从已有会话恢复;不改变 H5、页面物化、Page Data 验收、图片隔离或定时任务确认机制。
|
||||
|
||||
## 验证
|
||||
|
||||
```bash
|
||||
node --test wechat/intent/task-route.test.mjs wechat-intent-router.test.mjs wechat-mp.test.mjs wechat-cursor-channel.test.mjs wechat/handlers/scheduled-task.test.mjs
|
||||
```
|
||||
|
||||
必须覆盖:视觉修改、显式链接优先、文字/账号/日程修改、缺失及多个目标澄清、
|
||||
新页面不携带旧正文、Agent 实际提示及 metadata、交付混入错页时阻断。
|
||||
生产发布仍需实际对话回放和原有发布闸门;本地测试通过不等于真实用户任务偏离已全部解决。
|
||||
+1
-1
File diff suppressed because one or more lines are too long
+75
-16
@@ -63,6 +63,13 @@ import {
|
||||
} from './wechat/subscribe-morning-reminder.mjs';
|
||||
import { stripWechatChannelPrefix, WECHAT_CHANNEL_PREFIX } from './wechat/intent/channel-prefix.mjs';
|
||||
import { classifyWechatIntent } from './wechat/intent/classifier.mjs';
|
||||
import {
|
||||
assertWechatTaskDeliveryTarget,
|
||||
buildWechatTaskRoutePrompt,
|
||||
needsWechatTaskContext,
|
||||
readWechatTaskContext,
|
||||
resolveWechatTaskRoute,
|
||||
} from './wechat/intent/task-route.mjs';
|
||||
import {
|
||||
isWechatSessionResetAction,
|
||||
resolveWechatSessionAction,
|
||||
@@ -71,7 +78,7 @@ import {
|
||||
extractMindSpacePublicHtmlPath,
|
||||
isWechatPageRefineRequestText,
|
||||
} from './wechat/page-refine-target.mjs';
|
||||
import { isPageGenerateText, isTopicResetText } from './wechat/intent/patterns.mjs';
|
||||
import { isPageGenerateText, isTopicResetText, PAGE_GENERATE_NEGATION_PATTERN } from './wechat/intent/patterns.mjs';
|
||||
import {
|
||||
isPageDataDevIntent,
|
||||
isPageDataIntent,
|
||||
@@ -1106,6 +1113,8 @@ export function shouldForceNewWechatAgentSession(wechatIntent, resetCandidate) {
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
if (wechatIntent?.taskRoute?.mode === 'page.create' && wechatIntent.taskRoute.forceNew) return true;
|
||||
if (wechatIntent?.taskRoute?.mode === 'page.edit') return false;
|
||||
if (wechatIntent?.kind !== 'page.generate') return false;
|
||||
const text = String(resetCandidate ?? wechatIntent?.topic ?? '').trim();
|
||||
if (isWechatSessionPageContinuation(wechatIntent, text)) return false;
|
||||
@@ -2294,6 +2303,7 @@ export function createWechatMpService({
|
||||
openid,
|
||||
forceNew = false,
|
||||
retainUnlinkedRoute = false,
|
||||
carryContext = true,
|
||||
userContext = null,
|
||||
}) => {
|
||||
const workingDir = await userAuth.resolveWorkingDir(userId);
|
||||
@@ -2305,10 +2315,10 @@ export function createWechatMpService({
|
||||
if (forceNew) {
|
||||
const routeBeforeForceNew = await userAuth.getWechatAgentRoute(config.appId, openid);
|
||||
if (routeBeforeForceNew?.agentSessionId) {
|
||||
carriedSessionContentForNewSession = await fetchLastSubstantiveAssistantFromSession(
|
||||
carriedSessionContentForNewSession = carryContext ? await fetchLastSubstantiveAssistantFromSession(
|
||||
fetchForSession,
|
||||
routeBeforeForceNew.agentSessionId,
|
||||
);
|
||||
) : '';
|
||||
rememberedWechatContexts.delete(routeBeforeForceNew.agentSessionId);
|
||||
}
|
||||
await userAuth.clearWechatAgentRoute(config.appId, openid);
|
||||
@@ -2680,6 +2690,10 @@ export function createWechatMpService({
|
||||
link: intent.link || null,
|
||||
memindRun: {
|
||||
...buildWechatImageRunMetadata(imagePolicy),
|
||||
...(intent.taskRoute ? {
|
||||
wechatTaskMode: intent.taskRoute.mode,
|
||||
...(intent.taskRoute.targetPath ? { wechatTaskTarget: intent.taskRoute.targetPath } : {}),
|
||||
} : {}),
|
||||
...(pgRequired ? { pgRequired: true } : {}),
|
||||
},
|
||||
};
|
||||
@@ -2857,12 +2871,23 @@ export function createWechatMpService({
|
||||
|
||||
const runIntentMessage = async ({ inbound, intent, user }) => {
|
||||
const wechatIntent = await resolveWechatIntent(intent, { openid: inbound.fromUserName });
|
||||
intent.taskRoute = wechatIntent.taskRoute;
|
||||
if (wechatIntent.taskRoute?.mode === 'clarify') {
|
||||
const delivery = await sendCustomerServiceText(inbound.fromUserName, wechatIntent.taskRoute.message, user, {
|
||||
deliveryPriority: 'formal_reply', sourceMsgId: intent.msgId,
|
||||
});
|
||||
if (delivery?.deferred) {
|
||||
throw markWechatUserNotified(markWechatDeliveryDeferred(new Error('任务澄清消息已排队发送')));
|
||||
}
|
||||
return { sessionId: null };
|
||||
}
|
||||
const mediaAnalysisEnabled = isWechatMediaGrayUser(user, config.mediaAnalysisGrayUsers);
|
||||
const agentReplyTimeoutMs = config.agentReplyTimeoutMs;
|
||||
const resetCandidate =
|
||||
intent.msgType === 'text' || intent.msgType === 'voice' ? intent.agentText : '';
|
||||
const isPageDataRequest = isWechatPageDataTask(resetCandidate);
|
||||
const htmlArtifactDeliveryExpected = shouldDeliverWechatHtmlArtifacts(wechatIntent, intent);
|
||||
const htmlArtifactDeliveryExpected = wechatIntent.taskRoute?.mode === 'chat'
|
||||
? false : shouldDeliverWechatHtmlArtifacts(wechatIntent, intent);
|
||||
const allowHtmlArtifactRecovery =
|
||||
htmlArtifactDeliveryExpected
|
||||
|| (
|
||||
@@ -2870,7 +2895,9 @@ export function createWechatMpService({
|
||||
&& wechatIntent?.llmShadow?.wouldChangeKind === true
|
||||
);
|
||||
const sessionPageContinuation =
|
||||
isWechatSessionPageContinuation(wechatIntent, resetCandidate);
|
||||
wechatIntent.taskRoute
|
||||
? ['page.edit', 'page.from_context'].includes(wechatIntent.taskRoute.mode)
|
||||
: isWechatSessionPageContinuation(wechatIntent, resetCandidate);
|
||||
const imagePolicy = resolveWechatImageGenerationPolicy({
|
||||
text: resetCandidate,
|
||||
isPageGenerate: wechatIntent.kind === 'page.generate',
|
||||
@@ -2886,10 +2913,12 @@ export function createWechatMpService({
|
||||
openid: inbound.fromUserName,
|
||||
userContext: user,
|
||||
forceNew,
|
||||
carryContext: wechatIntent.taskRoute?.mode !== 'page.create',
|
||||
retainUnlinkedRoute: sessionPageContinuation,
|
||||
});
|
||||
let sessionId = route.sessionId;
|
||||
let carriedSessionContent = String(route.carriedSessionContent ?? '').trim();
|
||||
let carriedSessionContent = wechatIntent.taskRoute?.mode === 'page.create'
|
||||
? '' : String(route.carriedSessionContent ?? '').trim();
|
||||
await ensureSessionProvider(sessionId, user.userId, { intentKind: wechatIntent.kind });
|
||||
if (wechatIntent.kind === 'session.reset') {
|
||||
await sendCustomerServiceText(
|
||||
@@ -2915,7 +2944,8 @@ export function createWechatMpService({
|
||||
isNewSession: pollutionRotation.isNewSession ?? true,
|
||||
};
|
||||
if (pollutionRotation.carriedSessionContent) {
|
||||
carriedSessionContent = pollutionRotation.carriedSessionContent;
|
||||
carriedSessionContent = wechatIntent.taskRoute?.mode === 'page.create'
|
||||
? '' : pollutionRotation.carriedSessionContent;
|
||||
}
|
||||
await ensureSessionProvider(sessionId, user.userId, { intentKind: wechatIntent.kind });
|
||||
await rememberWechatUserContext(sessionId, user, { forceBootstrap: true });
|
||||
@@ -2979,7 +3009,8 @@ export function createWechatMpService({
|
||||
try {
|
||||
const requestStartedAt = Date.now();
|
||||
userPublishDir = await userAuth.resolveWorkingDir(user.userId);
|
||||
const agentPrompt =
|
||||
const taskRoutePrompt = buildWechatTaskRoutePrompt(wechatIntent.taskRoute);
|
||||
const baseAgentPrompt =
|
||||
wechatIntent.kind === 'page.generate'
|
||||
? buildPageGenerateAgentPrompt(intent, {
|
||||
wantsDocx: wechatIntent.wantsDocx,
|
||||
@@ -2991,6 +3022,7 @@ export function createWechatMpService({
|
||||
imagePolicy,
|
||||
preferSessionPageContinuation: sessionPageContinuation,
|
||||
});
|
||||
const agentPrompt = [taskRoutePrompt, baseAgentPrompt].filter(Boolean).join('\n\n');
|
||||
const maxImmediateContextPageAttempts =
|
||||
wechatIntent.kind === 'page.generate' && sessionPageContinuation ? 2 : 1;
|
||||
let reply;
|
||||
@@ -3001,7 +3033,8 @@ export function createWechatMpService({
|
||||
let linkExistsForRequest = linkExists;
|
||||
for (let pageAttempt = 1; pageAttempt <= maxImmediateContextPageAttempts; pageAttempt += 1) {
|
||||
const activeAgentPrompt =
|
||||
pageAttempt === 1 ? agentPrompt : buildImmediateContextPageRepairPrompt(intent);
|
||||
pageAttempt === 1 ? agentPrompt
|
||||
: [taskRoutePrompt, buildImmediateContextPageRepairPrompt(intent)].filter(Boolean).join('\n\n');
|
||||
const activeRequestId = pageAttempt === 1 ? requestId : crypto.randomUUID();
|
||||
reply = null;
|
||||
let wechatCursorPolicy = null;
|
||||
@@ -3085,7 +3118,7 @@ export function createWechatMpService({
|
||||
userId: user.userId,
|
||||
sessionId,
|
||||
userMessage,
|
||||
preserveAgentPrompt: sessionPageContinuation,
|
||||
preserveAgentPrompt: Boolean(wechatIntent.taskRoute) || sessionPageContinuation,
|
||||
}),
|
||||
submitReply: submitSessionReply
|
||||
? ({ requestId: replyRequestId, userMessage }) =>
|
||||
@@ -3394,6 +3427,7 @@ export function createWechatMpService({
|
||||
if (shouldRefreshWechatSessionSnapshot(finalizedReply)) {
|
||||
scheduleWechatSessionSnapshotRefresh(sessionId, user.userId);
|
||||
}
|
||||
assertWechatTaskDeliveryTarget(wechatIntent.taskRoute, publishArtifacts, finalizedReply);
|
||||
const delivery = await sendCustomerServiceText(
|
||||
inbound.fromUserName,
|
||||
await guardScheduleReply(finalizedReply),
|
||||
@@ -3531,7 +3565,7 @@ export function createWechatMpService({
|
||||
(pathname, init) => fetchForSession(sessionId, pathname, init),
|
||||
sessionId,
|
||||
retryId,
|
||||
retryPrompt,
|
||||
[buildWechatTaskRoutePrompt(wechatIntent.taskRoute), retryPrompt].filter(Boolean).join('\n\n'),
|
||||
buildIntentMetadata(intent, {
|
||||
mediaAnalysisEnabled,
|
||||
imagePolicy,
|
||||
@@ -3542,7 +3576,7 @@ export function createWechatMpService({
|
||||
userId: user.userId,
|
||||
sessionId,
|
||||
userMessage,
|
||||
preserveAgentPrompt: retryPageContinuation,
|
||||
preserveAgentPrompt: Boolean(wechatIntent.taskRoute) || retryPageContinuation,
|
||||
}),
|
||||
submitReply: submitSessionReply
|
||||
? ({ requestId: replyRequestId, userMessage }) =>
|
||||
@@ -3785,6 +3819,7 @@ export function createWechatMpService({
|
||||
if (shouldRefreshWechatSessionSnapshot(finalizedReply)) {
|
||||
scheduleWechatSessionSnapshotRefresh(sessionId, user.userId);
|
||||
}
|
||||
assertWechatTaskDeliveryTarget(wechatIntent.taskRoute, publishArtifacts, finalizedReply);
|
||||
const retryDelivery = await sendCustomerServiceText(
|
||||
inbound.fromUserName,
|
||||
await guardScheduleReply(finalizedReply),
|
||||
@@ -3830,21 +3865,45 @@ export function createWechatMpService({
|
||||
...wechatIntent,
|
||||
sessionActionResult,
|
||||
};
|
||||
if (!wechatIntentRouter?.refineIntent) {
|
||||
return withSession;
|
||||
const resolveTask = async (candidate) => {
|
||||
let context = {};
|
||||
if (needsWechatTaskContext(candidate, intent.agentText) && openid) {
|
||||
try {
|
||||
const route = await userAuth.getWechatAgentRoute(config.appId, openid);
|
||||
if (route?.agentSessionId) {
|
||||
context = { hasConversation: Number(route.updatedAt) > 0 };
|
||||
const payload = await readJsonResponse(await fetchForSession(
|
||||
route.agentSessionId, `/sessions/${encodeURIComponent(route.agentSessionId)}`,
|
||||
));
|
||||
context = {
|
||||
...readWechatTaskContext(payload?.conversation ?? []),
|
||||
hasConversation: context.hasConversation || (payload?.conversation?.length ?? 0) > 0,
|
||||
};
|
||||
}
|
||||
} catch (error) {
|
||||
logger.warn?.('WeChat task context unavailable; refusing to guess edit target:', error.message);
|
||||
}
|
||||
}
|
||||
return resolveWechatTaskRoute({ wechatIntent: candidate, text: intent.agentText, context });
|
||||
};
|
||||
// Explicit channels and negation are user instructions, not suggestions for the LLM to override.
|
||||
if (!wechatIntentRouter?.refineIntent || withSession.channelPrefix
|
||||
|| PAGE_GENERATE_NEGATION_PATTERN.test(intent.agentText)) {
|
||||
return resolveTask(withSession);
|
||||
}
|
||||
try {
|
||||
return await wechatIntentRouter.refineIntent({
|
||||
const refined = await wechatIntentRouter.refineIntent({
|
||||
ruleIntent: withSession,
|
||||
text: intent.agentText,
|
||||
openid,
|
||||
});
|
||||
return resolveTask(refined);
|
||||
} catch (err) {
|
||||
logger.warn?.(
|
||||
'WeChat MP intent router refine skipped:',
|
||||
err instanceof Error ? err.message : err,
|
||||
);
|
||||
return withSession;
|
||||
return resolveTask(withSession);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -7352,3 +7352,94 @@ test('wechat mp standalone image intent sends a native image message and text',
|
||||
assert.equal(wechatPayloads[0].image.media_id, 'wx-generated-1');
|
||||
assert.match(wechatPayloads[1].text.content, /新图片已经生成/);
|
||||
});
|
||||
|
||||
test('wechat task routing asks for a missing page before starting any agent', async () => {
|
||||
const replies = [];
|
||||
let agentCalls = 0;
|
||||
const service = createBoundWechatService({
|
||||
sessionApiFetch: async (_id, pathname) => {
|
||||
assert.equal(pathname, '/sessions/session-1');
|
||||
return new Response(JSON.stringify({ conversation: [] }), { status: 200 });
|
||||
},
|
||||
startAgentSession: async () => { agentCalls += 1; throw new Error('must not start'); },
|
||||
submitSessionReply: async () => { agentCalls += 1; throw new Error('must not submit'); },
|
||||
wechatFetch: async (url, init) => {
|
||||
if (String(url).includes('/stable_token')) return new Response(JSON.stringify({ access_token: 'access-1', expires_in: 7200 }));
|
||||
if (String(url).includes('/custom/send')) {
|
||||
replies.push(JSON.parse(init.body).text.content);
|
||||
return new Response(JSON.stringify({ errcode: 0 }));
|
||||
}
|
||||
throw new Error('unexpected wechat call');
|
||||
},
|
||||
});
|
||||
const result = await service.handleInboundMessage(inboundXml({ content: '颜色换成绿色' }), {
|
||||
timestamp: '1710000000', nonce: 'nonce', signature: signatureFor('token', '1710000000', 'nonce'),
|
||||
});
|
||||
await result.task;
|
||||
assert.equal(agentCalls, 0);
|
||||
assert.ok(replies.some((text) => text.includes('请把要修改的页面链接发给我')));
|
||||
});
|
||||
|
||||
test('wechat task routing pins the actual agent prompt and metadata to the immediate page', async () => {
|
||||
let submitted = null;
|
||||
const service = createBoundWechatService({
|
||||
sessionApiFetch: async (_id, pathname) => {
|
||||
if (pathname === '/sessions/session-1') return new Response(JSON.stringify({ conversation: [
|
||||
{ role: 'assistant', content: [{ type: 'text', text: '页面已生成:https://example.com/MindSpace/user-1/public/coffee.html' }] },
|
||||
] }));
|
||||
if (pathname.endsWith('/extensions')) return new Response(JSON.stringify({ extensions: [
|
||||
{ type: 'platform', name: 'developer', available_tools: ['write'] },
|
||||
] }));
|
||||
return new Response('{}', { status: 200 });
|
||||
},
|
||||
submitSessionReply: async (input) => { submitted = input; throw new Error('stop after inspecting submitted request'); },
|
||||
wechatFetch: async (url) => new Response(JSON.stringify(String(url).includes('/stable_token')
|
||||
? { access_token: 'access-1', expires_in: 7200 } : { errcode: 0 })),
|
||||
});
|
||||
const result = await service.handleInboundMessage(inboundXml({ content: '地址加上苏州工业园区' }), {
|
||||
timestamp: '1710000000', nonce: 'nonce', signature: signatureFor('token', '1710000000', 'nonce'),
|
||||
});
|
||||
await result.task;
|
||||
assert.ok(submitted, 'must reach the agent with the resolved task');
|
||||
const prompt = submitted.userMessage.content.filter((part) => part.type === 'text').map((part) => part.text).join('\n');
|
||||
assert.match(prompt, /唯一目标文件:public\/coffee.html/);
|
||||
assert.match(prompt, /地址加上苏州工业园区/);
|
||||
assert.equal(submitted.userMessage.metadata.memindRun.wechatTaskMode, 'page.edit');
|
||||
assert.equal(submitted.userMessage.metadata.memindRun.wechatTaskTarget, 'public/coffee.html');
|
||||
});
|
||||
|
||||
test('wechat task routing isolates a new page from an existing task without carrying old prose', async () => {
|
||||
let activeSession = 'session-1';
|
||||
let cleared = 0;
|
||||
let submitted = null;
|
||||
const service = createBoundWechatService({
|
||||
userAuth: {
|
||||
async getWechatAgentRoute() { return activeSession ? { agentSessionId: activeSession, updatedAt: Date.now() } : null; },
|
||||
async clearWechatAgentRoute() { cleared += 1; activeSession = null; },
|
||||
async upsertWechatAgentRoute({ agentSessionId }) { activeSession = agentSessionId; },
|
||||
},
|
||||
startAgentSession: async () => ({ id: 'session-new-task' }),
|
||||
sessionApiFetch: async (_id, pathname) => {
|
||||
if (pathname === '/sessions/session-1') return new Response(JSON.stringify({ conversation: [
|
||||
{ role: 'assistant', content: [{ type: 'text', text: '旧任务正文:此前正在制作咖啡店介绍,不得作为旅行页面正文。' }] },
|
||||
] }));
|
||||
if (pathname.endsWith('/extensions')) return new Response(JSON.stringify({ extensions: [
|
||||
{ type: 'platform', name: 'developer', available_tools: ['write'] },
|
||||
] }));
|
||||
return new Response('{}');
|
||||
},
|
||||
submitSessionReply: async (input) => { submitted = input; throw new Error('stop after inspecting submitted request'); },
|
||||
wechatFetch: async (url) => new Response(JSON.stringify(String(url).includes('/stable_token')
|
||||
? { access_token: 'access-1', expires_in: 7200 } : { errcode: 0 })),
|
||||
});
|
||||
const result = await service.handleInboundMessage(inboundXml({ content: '帮我做一个周末旅行页面' }), {
|
||||
timestamp: '1710000000', nonce: 'nonce', signature: signatureFor('token', '1710000000', 'nonce'),
|
||||
});
|
||||
await result.task;
|
||||
assert.equal(cleared, 1);
|
||||
assert.equal(submitted?.sessionId, 'session-new-task');
|
||||
const prompt = submitted.userMessage.content.filter((part) => part.type === 'text').map((part) => part.text).join('\n');
|
||||
assert.match(prompt, /本轮任务边界:新建页面/);
|
||||
assert.match(prompt, /周末旅行/);
|
||||
assert.doesNotMatch(prompt, /旧任务正文|咖啡店介绍|待排版正文/);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
import { parseWechatChannelPrefix, WECHAT_CHANNEL_PREFIX } from './channel-prefix.mjs';
|
||||
import { isWechatImmediateContextPageCreate, isWechatPageRetryText, isWechatReportPageFollowup } from './page-continuation.mjs';
|
||||
import { PAGE_GENERATE_NEGATION_PATTERN, wantsDocxDownload } from './patterns.mjs';
|
||||
import { extractMindSpacePublicHtmlPath } from '../page-refine-target.mjs';
|
||||
|
||||
const PAGE_SUBJECT = /(?:页面|网页|html|攻略)/iu;
|
||||
const EDIT = /(?:改|调整|更新|换|优化|美化|补充|完善|添加|加上|删|去掉|缩短|加长|润色)/u;
|
||||
const VISUAL_EDIT = /(?:标题|背景|封面|页脚|字体|颜色|配色|排版|按钮|地址|电话|价格|报名|时间|地点|文案).{0,16}(?:改|调整|换|加|删|去掉)|(?:改|调整|换|加|删|去掉).{0,16}(?:标题|背景|封面|页脚|字体|颜色|配色|排版|按钮|地址|电话|价格|报名|时间|地点|文案)/u;
|
||||
const PROSE_EDIT = /(?:诗|文章|段落|句子|这段话|代码|密码|日程|提醒|定时任务)/u;
|
||||
const EDIT_QUESTION = /(?:怎么|如何|为什么|能不能教|可以教|什么意思|什么区别)/u;
|
||||
const POINTER_EDIT = /^(?:请|麻烦)?(?:把|将)?(?:这个|那个|刚才的|上面的|它).{0,8}(?:改|调整|换|优化|补充|完善)/u;
|
||||
const SHORT_EDIT = /^(?:请)?(?:改|换|调整)(?:成|为).{1,20}$/u;
|
||||
|
||||
function explicitPageTarget(text) {
|
||||
return extractMindSpacePublicHtmlPath(text)
|
||||
?? String(text).match(/(?:^|[\s::((])(?:文件[::]\s*)?(public\/[\w.-]+\.html)(?=$|[\s,。!?))])/u)?.[1]
|
||||
?? null;
|
||||
}
|
||||
|
||||
/** Only immediate assistant text can supply an implicit edit target; never scan the workspace. */
|
||||
export function readWechatTaskContext(conversation = []) {
|
||||
const messages = Array.isArray(conversation) ? conversation.slice(-12) : [];
|
||||
const last = messages.reverse().find((message) => message?.role === 'assistant');
|
||||
const text = typeof last?.content === 'string' ? last.content
|
||||
: Array.isArray(last?.content)
|
||||
? last.content.filter((part) => part?.type === 'text').map((part) => part.text ?? '').join('\n')
|
||||
: String(last?.text ?? '');
|
||||
const urls = text.match(/https?:\/\/[^\s<>"'))]+/gu) ?? [];
|
||||
const targets = [...new Set(urls.map(extractMindSpacePublicHtmlPath).filter(Boolean))];
|
||||
return { targetPaths: targets, hasPage: targets.length > 0, hasConversation: messages.length > 0 };
|
||||
}
|
||||
|
||||
export function needsWechatTaskContext(wechatIntent, text) {
|
||||
const body = parseWechatChannelPrefix(text).body;
|
||||
return wechatIntent?.kind === 'page.generate' || (!explicitPageTarget(body) && (
|
||||
isWechatImmediateContextPageCreate(wechatIntent, body)
|
||||
|| isWechatPageRetryText(body)
|
||||
|| (EDIT.test(body) && (PAGE_SUBJECT.test(body) || VISUAL_EDIT.test(body) || POINTER_EDIT.test(body) || SHORT_EDIT.test(body)))
|
||||
));
|
||||
}
|
||||
|
||||
/** A bounded task decision, independent of long-term memories or unverified workspace files. */
|
||||
export function resolveWechatTaskRoute({ wechatIntent, text, context = {} }) {
|
||||
const { body, channel } = parseWechatChannelPrefix(text);
|
||||
const result = (mode, extra = {}) => ({ ...wechatIntent, taskRoute: { mode, ...extra } });
|
||||
if (!['chat.general', 'page.generate'].includes(wechatIntent?.kind)) return wechatIntent;
|
||||
if (channel === WECHAT_CHANNEL_PREFIX.CHAT || channel === WECHAT_CHANNEL_PREFIX.SCHEDULED_TASK
|
||||
|| PAGE_GENERATE_NEGATION_PATTERN.test(body)) {
|
||||
return { ...result('chat'), kind: 'chat.general', text: body };
|
||||
}
|
||||
const explicitTarget = explicitPageTarget(body);
|
||||
if (!explicitTarget && !PAGE_SUBJECT.test(body) && PROSE_EDIT.test(body) && EDIT.test(body)
|
||||
&& channel !== WECHAT_CHANNEL_PREFIX.PAGE) {
|
||||
return { ...result('chat'), kind: 'chat.general', text: body };
|
||||
}
|
||||
const freshPage = /^(?:生成页面[::]\s*)?(?:(?:请|麻烦)\s*)?(?:帮我|给我)?\s*(?:新建|另外做|再做|创建|生成|制作|做)(?:一个|一张|一份|个|张|份)?\s*[^,。!?\n]{1,80}(?:页面|网页|html)/iu.test(body)
|
||||
&& !isWechatImmediateContextPageCreate(wechatIntent, body);
|
||||
if (freshPage && wechatIntent.kind === 'page.generate') return result('page.create', { forceNew: context.hasConversation === true });
|
||||
const editRequest = (explicitTarget && channel === WECHAT_CHANNEL_PREFIX.PAGE)
|
||||
|| (EDIT.test(body) && !EDIT_QUESTION.test(body)
|
||||
&& (PAGE_SUBJECT.test(body) || explicitTarget || VISUAL_EDIT.test(body) || POINTER_EDIT.test(body) || SHORT_EDIT.test(body)));
|
||||
const retry = isWechatPageRetryText(body);
|
||||
if (editRequest || retry) {
|
||||
const targets = explicitTarget ? [explicitTarget] : context.targetPaths ?? [];
|
||||
if (targets.length === 1) {
|
||||
return {
|
||||
...result('page.edit', { targetPath: targets[0], source: explicitTarget ? 'user' : 'session' }),
|
||||
kind: 'page.generate', topic: body, wantsDocx: wantsDocxDownload(body),
|
||||
};
|
||||
}
|
||||
if (PAGE_SUBJECT.test(body) || VISUAL_EDIT.test(body) || SHORT_EDIT.test(body) || retry || context.hasPage) {
|
||||
return result('clarify', {
|
||||
message: targets.length > 1
|
||||
? '刚才有多个页面,请把要修改的页面链接发给我,再告诉我要改哪里。'
|
||||
: '请把要修改的页面链接发给我,再告诉我要改哪里,我会修改原页面。',
|
||||
});
|
||||
}
|
||||
}
|
||||
if (isWechatImmediateContextPageCreate(wechatIntent, body)
|
||||
|| isWechatReportPageFollowup(wechatIntent, body)) return result('page.from_context');
|
||||
// Broad legacy edit patterns must not turn password/prose edits or how-to questions into HTML jobs.
|
||||
if (wechatIntent.kind === 'page.generate' && channel !== WECHAT_CHANNEL_PREFIX.PAGE
|
||||
&& EDIT.test(body) && (EDIT_QUESTION.test(body) || (PROSE_EDIT.test(body) && !PAGE_SUBJECT.test(body)))) {
|
||||
return { ...result('chat'), kind: 'chat.general', text: body };
|
||||
}
|
||||
return result(wechatIntent.kind === 'page.generate' ? 'page.create' : 'chat',
|
||||
wechatIntent.kind === 'page.generate' ? { forceNew: context.hasConversation === true } : {});
|
||||
}
|
||||
|
||||
export function buildWechatTaskRoutePrompt(taskRoute) {
|
||||
if (!taskRoute) return '';
|
||||
if (taskRoute.mode === 'page.edit') {
|
||||
return [
|
||||
'【本轮任务边界:修改已有页面】',
|
||||
`唯一目标文件:${taskRoute.targetPath}`,
|
||||
'先读取该文件,再按本轮要求用 edit_file 更新同一文件;不要另建页面或修改其他页面。',
|
||||
'目标不存在或无权访问时,说明原因并请求用户提供正确链接;禁止从历史任务或目录猜一个替代目标。',
|
||||
].join('\n');
|
||||
}
|
||||
if (taskRoute.mode === 'page.create') {
|
||||
return '【本轮任务边界:新建页面】只按本轮需求新建页面;不要修改历史页面,不要把旧会话主题、正文或长期记忆当成本轮正文。';
|
||||
}
|
||||
if (taskRoute.mode === 'chat') {
|
||||
return '【本轮任务边界:当前对话】只处理本条消息及其明确引用的上下文;不要因为旧页面任务自行创建或修改 HTML。';
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
export function assertWechatTaskDeliveryTarget(taskRoute, artifacts = [], replyText = '') {
|
||||
if (taskRoute?.mode !== 'page.edit') return;
|
||||
const targets = artifacts.map((artifact) => artifact.relativePath ?? artifact.relative_path
|
||||
?? extractMindSpacePublicHtmlPath(artifact.url)).filter(Boolean);
|
||||
const replyTargets = (String(replyText).match(/https?:\/\/[^\s<>"'))]+/gu) ?? [])
|
||||
.map(extractMindSpacePublicHtmlPath).filter(Boolean);
|
||||
if (!targets.includes(taskRoute.targetPath)
|
||||
|| [...targets, ...replyTargets].some((target) => target !== taskRoute.targetPath)) {
|
||||
const error = new Error('页面修改结果未能确认对应原页面,已停止发送其他页面链接。请重发原页面链接后重试。');
|
||||
error.code = 'WECHAT_TASK_TARGET_MISMATCH';
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { classifyWechatIntent } from './classifier.mjs';
|
||||
import {
|
||||
readWechatTaskContext, resolveWechatTaskRoute, buildWechatTaskRoutePrompt,
|
||||
assertWechatTaskDeliveryTarget,
|
||||
} from './task-route.mjs';
|
||||
|
||||
const page = 'https://m.tkmind.cn/MindSpace/user/public/coffee.html';
|
||||
const context = readWechatTaskContext([
|
||||
{ role: 'assistant', content: [{ type: 'text', text: `页面已生成:${page}` }] },
|
||||
]);
|
||||
const route = (text, previous = context) => resolveWechatTaskRoute({
|
||||
wechatIntent: classifyWechatIntent({ msgType: 'text', agentText: text }), text, context: previous,
|
||||
});
|
||||
|
||||
test('visual follow-ups bind the immediate page and select page editing', () => {
|
||||
for (const text of ['颜色换成绿色', '改成绿色', '地址加上苏州工业园区', '把页面标题改成咖啡时光', '重试上次页面']) {
|
||||
const decision = route(text);
|
||||
assert.equal(decision.kind, 'page.generate', text);
|
||||
assert.equal(decision.taskRoute.mode, 'page.edit', text);
|
||||
assert.equal(decision.taskRoute.targetPath, 'public/coffee.html', text);
|
||||
}
|
||||
});
|
||||
|
||||
test('explicit link overrides old page context and pins only the requested file', () => {
|
||||
const decision = route(`${page.replace('coffee.html', 'trip.html')} 把标题改成周末旅行`);
|
||||
assert.equal(decision.taskRoute.targetPath, 'public/trip.html');
|
||||
const prompt = buildWechatTaskRoutePrompt(decision.taskRoute);
|
||||
assert.match(prompt, /唯一目标文件:public\/trip.html/);
|
||||
assert.doesNotMatch(prompt, /coffee\.html/);
|
||||
assert.equal(route('【改页】public/demo.html 更详细').taskRoute.targetPath, 'public/demo.html');
|
||||
});
|
||||
|
||||
test('missing or ambiguous page targets clarify without guessing', () => {
|
||||
for (const previous of [{}, { targetPaths: ['public/a.html', 'public/b.html'], hasPage: true }]) {
|
||||
assert.equal(route('把页面标题改成新标题', previous).taskRoute.mode, 'clarify');
|
||||
}
|
||||
assert.equal(route('颜色换成绿色', {}).taskRoute.mode, 'clarify');
|
||||
});
|
||||
|
||||
test('context does not revive a page before an unrelated assistant answer or read user/tool links', () => {
|
||||
assert.deepEqual(readWechatTaskContext([
|
||||
{ role: 'assistant', content: `页面:${page}` },
|
||||
{ role: 'assistant', content: '苏州明天晴。' },
|
||||
{ role: 'user', content: page },
|
||||
{ role: 'tool', content: page },
|
||||
]).targetPaths, []);
|
||||
});
|
||||
|
||||
test('a new full page task stays new even when it includes editing requirements', () => {
|
||||
for (const text of ['帮我做一个旅行页面', '帮我做一个活动页面,添加报名按钮', '生成页面:咖啡店介绍']) {
|
||||
const decision = route(text);
|
||||
assert.equal(decision.taskRoute.mode, 'page.create', text);
|
||||
assert.equal(decision.taskRoute.targetPath, undefined);
|
||||
assert.equal(decision.taskRoute.forceNew, true);
|
||||
}
|
||||
});
|
||||
|
||||
test('turning current prose into a page preserves the existing immediate context flow', () => {
|
||||
assert.equal(route('把刚才的诗做成页面', {}).taskRoute.mode, 'page.from_context');
|
||||
assert.equal(route('解读详细报告,做成页面', {}).taskRoute.mode, 'page.from_context');
|
||||
});
|
||||
|
||||
test('prose, account edits and how-to questions do not become HTML work', () => {
|
||||
for (const text of ['修改密码', '把诗里第三段改长一点', '修改这篇文章的标题', '调整日程时间', '怎么修改页面标题', '苏州明天天气怎么样']) {
|
||||
const decision = route(text);
|
||||
assert.equal(decision.kind, 'chat.general', text);
|
||||
assert.equal(decision.taskRoute.mode, 'chat', text);
|
||||
}
|
||||
});
|
||||
|
||||
test('explicit chat and page negation cannot be overridden by a page classifier', () => {
|
||||
for (const text of ['【聊天】页面标题怎么改', '不要生成页面,只回答问题', '【定时任务】把页面每日发给我']) {
|
||||
const decision = resolveWechatTaskRoute({ wechatIntent: { kind: 'page.generate' }, text, context });
|
||||
assert.equal(decision.kind, 'chat.general');
|
||||
assert.equal(decision.taskRoute.mode, 'chat');
|
||||
}
|
||||
});
|
||||
|
||||
test('delivery rejects a different page or missing target, including mixed valid and unrelated pages', () => {
|
||||
const task = route('颜色换成绿色').taskRoute;
|
||||
for (const artifacts of [[], [{ url: page.replace('coffee', 'old') }], [{ url: page }, { url: page.replace('coffee', 'old') }]]) {
|
||||
assert.throws(() => assertWechatTaskDeliveryTarget(task, artifacts), { code: 'WECHAT_TASK_TARGET_MISMATCH' });
|
||||
}
|
||||
assert.doesNotThrow(() => assertWechatTaskDeliveryTarget(task, [{ url: page }]));
|
||||
assert.throws(() => assertWechatTaskDeliveryTarget(task, [{ url: page }], `原页面已改好,另外看 ${page.replace('coffee', 'old')}`), { code: 'WECHAT_TASK_TARGET_MISMATCH' });
|
||||
assert.doesNotThrow(() => assertWechatTaskDeliveryTarget(task, [{ relativePath: 'public/coffee.html' }]));
|
||||
});
|
||||
|
||||
test('control intents remain control intents', () => {
|
||||
assert.equal(route('换新会话').kind, 'session.reset');
|
||||
assert.equal(route('你好').kind, 'greeting');
|
||||
});
|
||||
Reference in New Issue
Block a user