cbcec96306
Memind CI / Test, build, and release guards (push) Has been cancelled
Bare “页面”, daily page titles, link requests, and short edits after a side question were leaving the original page task. Co-authored-by: Cursor <cursoragent@cursor.com>
185 lines
12 KiB
JavaScript
185 lines
12 KiB
JavaScript
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, MINDSPACE_PUBLIC_HTML_PATH_PATTERN } 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;
|
||
const DEFECT_EDIT = /(?:没有|没了|少了|缺少).{0,16}(?:按钮|音响|音乐|图片|封面|标题|背景)|(?:按钮|音响|音乐|图片|封面).{0,8}(?:没有|没了|不出|不显示)/u;
|
||
const FIELD_ANSWER = /^(?:店名|名称|活动名称|主题|地址|电话|联系电话|营业时间|时间|地点|价格|费用|报名方式|联系人|姓名|职位|公司|风格|配色|背景|标题|文案|颜色)(?:叫|是|为|用|[::])/u;
|
||
const RETURN_TO_PAGE = /(?:继续|回到|返回|接着).{0,10}(?:刚才|之前|上次|前面|那个|上面).{0,6}(?:页面|网页)|(?:刚才|之前|上次|前面|那个|上面).{0,6}(?:页面|网页).{0,10}(?:继续|改|修改|换|补充)/u;
|
||
const ASKS_FOR_FIELDS = /(?:请|需要|还缺|告诉我).{0,24}(?:店名|名称|地址|电话|时间|地点|价格|费用|姓名|风格|资料)|(?:店名|名称|地址|时间|地点).{0,12}(?:是什么|多少|哪里)/u;
|
||
|
||
function explicitPageTargets(text) {
|
||
const fullPaths = [...String(text).matchAll(new RegExp(MINDSPACE_PUBLIC_HTML_PATH_PATTERN.source, 'giu'))]
|
||
.map((match) => match[1]);
|
||
const relativePaths = [...String(text).matchAll(/(?:^|[\s::((])(?:文件[::]\s*)?(public\/[\w.-]+\.html)(?=$|[\s,。!?))])/giu)]
|
||
.map((match) => match[1]);
|
||
return [...new Set([...fullPaths, ...relativePaths])];
|
||
}
|
||
|
||
function visibleText(message) {
|
||
return typeof message?.content === 'string' ? message.content
|
||
: Array.isArray(message?.content)
|
||
? message.content.filter((part) => part?.type === 'text').map((part) => part.text ?? '').join('\n')
|
||
: String(message?.text ?? '');
|
||
}
|
||
|
||
function isEditQuestion(body) {
|
||
const command = body.replace(/https?:\/\/[^\s<>"'))]+/gu, '').trim();
|
||
return EDIT_QUESTION.test(command)
|
||
&& !/^(?:(?:请|麻烦|帮我)\s*)*(?:把|将|修改|调整|更新|更换|改|换)/u.test(command);
|
||
}
|
||
|
||
function isFieldAnswer(body) {
|
||
if (!FIELD_ANSWER.test(body) || /[??]\s*$/u.test(body)) return false;
|
||
const value = body.replace(FIELD_ANSWER, '').trim();
|
||
return value.length > 0 && !/^(?:什么|多少|哪里|哪儿)/u.test(value);
|
||
}
|
||
|
||
/** 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 recent = [...messages].reverse();
|
||
const last = recent.find((message) => message?.role === 'assistant' && message.metadata?.userVisible !== false && visibleText(message).trim());
|
||
const targets = explicitPageTargets(visibleText(last));
|
||
const lastUser = recent.find((message) => message?.role === 'user');
|
||
const run = lastUser?.metadata?.memindRun;
|
||
const pending = ['page.create', 'page.continue', 'page.from_context'].includes(run?.wechatTaskMode)
|
||
&& targets.length === 0 && ASKS_FOR_FIELDS.test(visibleText(last));
|
||
const previousPage = recent.find((message) => message?.role === 'assistant'
|
||
&& message.metadata?.userVisible !== false && explicitPageTargets(visibleText(message)).length);
|
||
return {
|
||
targetPaths: targets, resumeTargetPaths: explicitPageTargets(visibleText(previousPage)),
|
||
hasPage: targets.length > 0, hasConversation: messages.length > 0,
|
||
...(pending ? { pendingRequest: String(run.wechatTaskRequest ?? lastUser.metadata?.displayText ?? visibleText(lastUser)).slice(0, 2000) } : {}),
|
||
};
|
||
}
|
||
|
||
export function needsWechatTaskContext(wechatIntent, text) {
|
||
const body = parseWechatChannelPrefix(text).body;
|
||
return wechatIntent?.kind === 'page.generate' || FIELD_ANSWER.test(body) || RETURN_TO_PAGE.test(body) || (!explicitPageTargets(body).length && (
|
||
isWechatImmediateContextPageCreate(wechatIntent, body)
|
||
|| isWechatPageRetryText(body)
|
||
|| (EDIT.test(body) && (PAGE_SUBJECT.test(body) || VISUAL_EDIT.test(body) || POINTER_EDIT.test(body) || SHORT_EDIT.test(body)))
|
||
|| DEFECT_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 userTargets = explicitPageTargets(body);
|
||
const explicitTarget = userTargets[0];
|
||
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, requestText: body.slice(0, 2000) });
|
||
if (context.pendingRequest && isFieldAnswer(body)) {
|
||
return {
|
||
...result('page.continue', { requestText: context.pendingRequest }),
|
||
kind: 'page.generate', topic: body, wantsDocx: wantsDocxDownload(`${context.pendingRequest}\n${body}`),
|
||
};
|
||
}
|
||
const shortColloquialEdit = !isEditQuestion(body)
|
||
&& (VISUAL_EDIT.test(body) || SHORT_EDIT.test(body) || DEFECT_EDIT.test(body));
|
||
const editRequest = (explicitTarget && channel === WECHAT_CHANNEL_PREFIX.PAGE)
|
||
|| (isFieldAnswer(body) && context.hasPage)
|
||
|| shortColloquialEdit
|
||
|| (EDIT.test(body) && !isEditQuestion(body)
|
||
&& (PAGE_SUBJECT.test(body) || explicitTarget || POINTER_EDIT.test(body)));
|
||
const retry = isWechatPageRetryText(body);
|
||
if (editRequest || retry) {
|
||
const immediate = context.targetPaths ?? [];
|
||
const targets = userTargets.length ? userTargets
|
||
: RETURN_TO_PAGE.test(body) ? context.resumeTargetPaths ?? immediate
|
||
: (shortColloquialEdit && immediate.length === 0) ? context.resumeTargetPaths ?? []
|
||
: immediate;
|
||
if (targets.length === 1) {
|
||
return {
|
||
...result('page.edit', { targetPath: targets[0], source: explicitTarget ? 'user' : 'session' }),
|
||
kind: 'page.generate', topic: body, wantsDocx: wantsDocxDownload(body),
|
||
};
|
||
}
|
||
if (targets.length > 1 || PAGE_SUBJECT.test(body) || VISUAL_EDIT.test(body) || SHORT_EDIT.test(body) || DEFECT_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) && (isEditQuestion(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, requestText: body.slice(0, 2000) } : {});
|
||
}
|
||
|
||
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 === 'page.continue') {
|
||
return [
|
||
'【本轮任务边界:补充制作资料】用户正在回答上一轮页面任务的资料追问。',
|
||
`原始任务(用户资料):${JSON.stringify(taskRoute.requestText)}`,
|
||
'结合本轮补充继续同一个页面任务,不要当成闲聊,也不要替换为其他历史任务。',
|
||
'资料充分时完成 HTML 落盘并交付;仍缺关键信息时只询问缺失项。',
|
||
].join('\n');
|
||
}
|
||
if (taskRoute.mode === 'chat') {
|
||
return '【本轮任务边界:当前对话】只处理本条消息及其明确引用的上下文;不要因为旧页面任务自行创建或修改 HTML。';
|
||
}
|
||
return '';
|
||
}
|
||
|
||
/** A question for missing inputs is an intermediate result, never a successful page delivery. */
|
||
export function isWechatTaskInputQuestion(taskRoute, replyText, artifacts = []) {
|
||
if (!['page.create', 'page.continue'].includes(taskRoute?.mode) || artifacts.length) return false;
|
||
const text = String(replyText ?? '').trim();
|
||
return text.length > 0 && text.length <= 600 && ASKS_FOR_FIELDS.test(text)
|
||
&& !/(?:https?:\/\/|public\/|已(?:生成|完成|发布|制作)|错误|失败|error|tool_calls)/iu.test(text);
|
||
}
|
||
|
||
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;
|
||
}
|
||
}
|