Files
memind/wechat/intent/task-route.mjs
T

122 lines
7.5 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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;
}
}