import type { Message } from '../types.js'; import { isSystemEventMessage } from '../runtime/systemEvents.js'; import { searchTerms } from './searchIndex.js'; /** * A message that is nothing but a continuation. Anchored at both ends: "为什么 * Redis 连接超时" or "详细说明部署流程" start the same way but carry their own * topic, so treating them as follow-ups would skip them and recall against an * older request instead. (The advisor has a looser prefix check of its own; a * false positive there is harmless, here it points recall at the wrong topic.) */ const BARE_FOLLOW_UP = /^(?:继续|接着(?:说|来|做)?|然后呢|展开(?:说说|讲讲)?|详细(?:点|说说)?|深入(?:点|说说)?|再说(?:说)?|还有呢|为什么|为啥|怎么说|第[一二三四五六七八九十\d]+[点条项个]|go on|continue|elaborate|more detail|why)[\s,,。.!!??~呢吧啊]*$/i; export function isFollowUpRequest(text: string): boolean { return BARE_FOLLOW_UP.test(text.trim()); } /** Non-bare references need a fallback, not unconditional mixing of topics. */ export const refersToEarlier = (text: string): boolean => /(?:上次|之前|刚才|上面|前面|刚刚)(?:那[个条种项套份]|的?(?:方案|办法|规则|做法|约定|那条))|(?:that|the previous) (?:approach|rule|decision|setting)/i.test(text); export function referenceFallback(current: string, previous?: string): string | undefined { if (!previous || !refersToEarlier(current)) return; // A deictic phrase can coexist with a new named topic. Only borrow the // previous query if no topic remains or the named topic corroborates it. const topic = current.replace(/还是|继续|按照|按|使用|采用|沿用|上次|之前|刚才|上面|前面|刚刚|那[个条种项套份]|方案|办法|规则|做法|约定|处理|执行|的|就|吧|来|用|please|use|that|the previous|approach|rule|decision|setting/gi,' '); const terms = searchTerms(topic); const prev = previous.slice(0,500).normalize('NFKC').toLowerCase(); return !terms.length || terms.some(t => prev.includes(t)) ? previous.slice(0,500) : undefined; } /** Only trust IDs from the last real user turn's successful memory tool outputs. * Assistant prose and pasted tool-looking text confer no identity or authority. */ export function priorMemoryIds(history: readonly Message[] = []): string[] { const names = new Set(), ids = new Set(); let last = history.length - 1; while (last >= 0 && history[last]?.role !== 'user') last--; if (last < 0) return []; for (const m of history.slice(last + 1)) { if (m.role === 'assistant') for (const call of m.tool_calls ?? []) if (['ListMemories','RecallMemory','RememberMemory','UpdateMemory'].includes(call.function.name)) names.add(call.id); // Record bodies, diagnostic messages and suffixes are free text. An id // printed inside any of them is not a tool-authored record reference. if (m.role === 'tool' && m.display_ok === true && names.has(m.tool_call_id) && m.display_metadata?.kind === 'memory_references') { for (const id of m.display_metadata.ids) ids.add(id); } } return [...ids].slice(0, 8); } /** Enough of the earlier request to carry its topic, not its whole paste. */ const PREVIOUS_QUERY_CHARS = 500; /** "继续" after "继续" still continues the request before it; bound the walk. */ const MAX_FOLLOW_UP_HOPS = 4; function userText(message: Message): string { if (typeof message.content === 'string') return message.content; if (!Array.isArray(message.content)) return ''; return message.content .filter((part): part is Extract => part.type === 'text') .map(part => part.text) .join('\n'); } /** * The most recent user request before the current one, walking past bare * follow-ups so "继续" → "为什么" still resolves to the request that named the * topic. Hosts call this with the history as it stood before the new message. */ export function previousUserRequest(history: readonly Message[] | undefined): string | undefined { if (!history) return undefined; let hops = 0; for (let index = history.length - 1; index >= 0; index -= 1) { const message = history[index]!; if (message.role !== 'user' || isSystemEventMessage(message)) continue; const text = userText(message).trim(); if (!text) continue; if (isFollowUpRequest(text) && (hops += 1) < MAX_FOLLOW_UP_HOPS) continue; return text.slice(0, PREVIOUS_QUERY_CHARS); } return undefined; } /** * What memory is searched with. A pure follow-up ("继续", "为什么") has no * topic words of its own, so recall against the request it continues; any * other message is its own query. Recall only — what the current message * corrects or overrides is still decided from the current message alone. */ export function recallQueryFor(current: string, previous: string | undefined): string { return previous && isFollowUpRequest(current) ? `${previous}\n${current}` : current; }