import { z } from 'zod'; import { hasUserWrittenQuote } from '../../memory/userWritten.js'; import { sourceAnchor } from '../../memory/automaticPolicy.js'; import { recallExperiences, experienceContext } from '../../memory/experienceStore.js'; import { recallProjectKnowledge, projectKnowledgeContext } from '../../memory/projectKnowledge.js'; import { readConversationEpisode, searchConversationPage } from '../../memory/episodicMemory.js'; import { memoryRecordPath } from '../../memory/fileStore.js'; import { type MemoryCategory, type MemoryScope, memoryService, settleCandidatesAfterUpdate, } from '../../memory/memoryService.js'; import type { Tool } from '../../types.js'; import { toToolParameters } from '../../utils/zodToJson.js'; import { DEFAULT_MAX_RESULT_SIZE_CHARS } from '../types.js'; import { explicitCrossWorkspaceSearch, explicitForget, explicitSave, declinesMemoryMutation, hasAuthoredMemoryContext, explicitPersonaChange, confirmSensitiveMemory, confirmMemoryCorrection, denyUnlessLocalOwner, requireCurrentEvidence, memoryEvidenceContext, } from './policy.js'; const scopeSchema = z.enum(['personal', 'workspace']); const categorySchema = z.enum([ 'profile', 'preference', 'topic', 'person', 'project', 'decision', ]); function formatRecord( record: Awaited>[number], version?: string, ): string { const workspace = record.workspaceId ? ` workspace=${record.workspaceId}` : ''; const lifecycle = ` status=${record.status ?? 'active'} revision=${record.revision ?? 1}`; return `- [${record.id}] scope=${record.scope} ${record.category}/${record.subject}${workspace}${lifecycle}${version ? ` version=${version}` : ''}: ${record.statement}(${record.evidence},${new Date(record.updatedAt).toISOString()})${record.status === 'needs_review' && record.confirmationContext ? `\n复核线索(非事实):${record.confirmationContext}` : ''}`; } function diagnosticSuffix( diagnostics: Array<{ path: string; message: string }>, ): string { if (!diagnostics.length) return ''; return `\n\n警告:有 ${diagnostics.length} 个 Markdown 记忆文件无法解析,已跳过;首个错误:${diagnostics[0]!.path}:${diagnostics[0]!.message}`; } const recallSchema = z.object({ query: z .string() .max(500) .optional() .describe('要回忆的主题、人物、项目或偏好;省略时返回最近记忆'), limit: z.number().int().min(1).max(20).optional(), }); export const recallMemoryTool: Tool> = { name: 'RecallMemory', description: '按主题读取个人记忆、当前工作区项目事实和项目经验。项目事实包含架构/技术栈/测试/部署依据;返回内容仍需结合当前用户消息与代码验证,当前消息优先。', inputSchema: recallSchema, parameters: toToolParameters(recallSchema), isReadOnly: true, isConcurrencySafe: true, maxResultSizeChars: DEFAULT_MAX_RESULT_SIZE_CHARS, call: async () => ({ ok: false, error: 'RecallMemory 需要本机会话上下文' }), callWithContext: async (input, _signal, ctx) => { const denied = denyUnlessLocalOwner(ctx, 'read'); if (denied) return denied; const { records, snapshot } = await memoryService.recallDetailed( input.query ?? '', ctx.workspaceId, input.limit ?? 8, ); let suffix = diagnosticSuffix(snapshot.diagnostics); if (ctx.workspaceId) { try { suffix += '\n\n' + projectKnowledgeContext(await recallProjectKnowledge(ctx.workspaceId, input.query ?? '', input.limit ?? 5)); } catch (error) { suffix += `\n项目事实库读取失败:${(error as Error).message}`; } try { suffix += '\n\n' + experienceContext(await recallExperiences(ctx.workspaceId, input.query ?? '', input.limit ?? 5), true); } catch (error) { suffix += `\n经验库读取失败:${(error as Error).message}`; } } return { ok: true, metadata: { kind: 'memory_references', ids: records.map(record => record.id) }, content: `${records.length ? records.map((record) => formatRecord(record, snapshot.versions[record.id])).join('\n') : '没有匹配的长期记忆。'}${suffix}`, }; }, }; const rememberSchema = z.object({ scope: scopeSchema.describe('personal 跨本机会话;workspace 仅当前工作区'), category: categorySchema, subject: z.string().min(1).max(120), statement: z .string() .min(1) .max(1000) .describe('只记录用户明确表达的稳定事实、偏好或决定,不记录推断'), evidenceQuote: z .string() .min(1) .max(1000) .describe('当前用户消息中的逐字证据片段'), sensitivity: z.enum(['normal', 'sensitive']).optional(), aliases: z.array(z.string().min(1).max(120)).max(20).optional(), }); export const rememberMemoryTool: Tool> = { name: 'RememberMemory', description: '响应本机主人明确要求记住的稳定事实、偏好或决定;普通陈述交由已启用的后台提炼,不重复调用。自动记忆关闭时也只能响应明确保存要求。evidenceQuote 必须逐字来自当前用户消息;不得保存推断、搜索结果、代码事实、短期状态或任何凭据。敏感内容必须由交互宿主再次确认。', inputSchema: rememberSchema, parameters: toToolParameters(rememberSchema), isReadOnly: false, isConcurrencySafe: false, maxResultSizeChars: DEFAULT_MAX_RESULT_SIZE_CHARS, call: async () => ({ ok: false, error: 'RememberMemory 需要本机会话上下文' }), callWithContext: async (input, signal, ctx) => { ctx = memoryEvidenceContext(ctx, input.evidenceQuote); const denied = denyUnlessLocalOwner(ctx); if (denied) return denied; const current = ctx.currentUserInput ?? ''; const invalidEvidence = requireCurrentEvidence(ctx, input.evidenceQuote); if (invalidEvidence) return invalidEvidence; if (input.scope === 'workspace' && !ctx.workspaceId) { return { ok: false, error: '当前会话没有稳定 workspaceId,不能保存工作区记忆', }; } const sensitivity = input.sensitivity ?? 'normal'; if ( sensitivity === 'sensitive' && input.statement.trim() === input.evidenceQuote.trim() ) { return { ok: false, error: '敏感内容不得逐字保存;请先概括、去除不必要细节后再请求确认', }; } let evidence: 'user_stated' | 'user_confirmed' = 'user_stated'; // 显式保存入口始终要求明确保存意图,与自动记忆开关无关:自动记忆开启时, // 普通陈述本就由后台事实提炼管线处理;模型误调用本工具不应直接落盘一条 // 未经用户要求的记忆。关闭自动记忆时,显式意图还把证据等级提为 user_confirmed。 if (!explicitSave(current)) { return { ok: false, error: '只有用户在当前消息中明确要求记住/保存记忆时才能调用 RememberMemory;' + '普通陈述由后台自动提炼处理,不要代为显式保存', }; } if (!(await memoryService.settings()).autoRemember) { evidence = 'user_confirmed'; } if (sensitivity === 'sensitive') { const confirmed = await confirmSensitiveMemory( input.statement, sensitivity, signal, ); if (!confirmed) return { ok: false, error: '敏感记忆需要交互确认,且只能保存概括后的内容', }; evidence = confirmed; } const record = await memoryService.remember({ scope: input.scope as MemoryScope, ...(input.scope === 'workspace' ? { workspaceId: ctx.workspaceId } : {}), category: input.category as MemoryCategory, subject: input.subject, statement: input.statement, evidence, evidenceQuote: input.evidenceQuote, sourceSessionId: ctx.sessionId ?? 'unknown', sourceMessageId: ctx.userMessageId ?? 'unknown', sourceAnchor: sourceAnchor(ctx.sessionId ?? '', ctx.userMessageId ?? '', input.evidenceQuote, current), sensitivity, ...(input.aliases ? { aliases: input.aliases } : {}), }); return { ok: true, metadata: { kind: 'memory_references', ids: [record.id] }, content: `已保存本机${record.scope === 'personal' ? '个人' : '工作区'}记忆:${record.subject}\n文件:${memoryRecordPath(record)}\nid=${record.id}`, }; }, }; const updateSchema = z.object({ action: z.enum(['update', 'review', 'confirm']).optional().describe('默认 update:当前用户原话纠正;review:仅标记待复核,不改事实;confirm:通过宿主向用户确认拟更新内容后保存'), reason: z.string().min(1).max(1000).optional().describe('review/confirm 必填:冲突或纠正依据,注明来源;不得伪造用户陈述'), id: z.string().uuid(), scope: scopeSchema, category: categorySchema.optional(), subject: z.string().min(1).max(120).optional(), statement: z.string().min(1).max(1000).optional(), evidenceQuote: z .string() .min(1) .max(1000) .optional() .describe('当前用户消息中的逐字证据片段'), sensitivity: z.enum(['normal', 'sensitive']).optional(), aliases: z.array(z.string().min(1).max(120)).max(20).optional(), supersedesIds: z .array(z.string().uuid()) .max(20) .optional() .describe('明确解决同主题冲突时被此记录替代的 ID'), expectedVersion: z .string() .regex(/^[0-9a-f]{64}$/i) .optional() .describe( 'RecallMemory/read 返回的文件版本;提供后可防止覆盖手工或并发修改', ), }); export const updateMemoryTool: Tool> = { name: 'UpdateMemory', description: '纠正用户事实记忆:先 RecallMemory 读取 ID/version。默认 update 需要 statement 与当前用户原话 evidenceQuote;review 需要 reason,仅标记待复核、保留原事实与证据;confirm 需要 statement/reason,通过宿主展示新旧内容并取得用户确认再更新。拒绝或无法交互不写入。项目知识和经验走 MemoryMaintenance,不伪造用户证据。', inputSchema: updateSchema, parameters: toToolParameters(updateSchema), isReadOnly: false, isConcurrencySafe: false, maxResultSizeChars: DEFAULT_MAX_RESULT_SIZE_CHARS, call: async () => ({ ok: false, error: 'UpdateMemory 需要本机会话上下文' }), callWithContext: async (input, signal, ctx) => { ctx = memoryEvidenceContext(ctx, input.evidenceQuote); const denied = denyUnlessLocalOwner(ctx); if (denied) return denied; const current = ctx.currentUserInput ?? ''; const action = input.action ?? 'update'; if (declinesMemoryMutation(current)) return { ok: false, error: '本轮用户拒绝记忆写入,未更新、标记或请求确认。' }; if (!hasAuthoredMemoryContext(current)) return { ok: false, error: '本轮没有引用区外的用户陈述,未更新、标记或请求确认。' }; if (action === 'review' && (input.statement !== undefined || input.evidenceQuote !== undefined)) { return { ok: false, error: 'review 仅提交 reason,不提交 statement/evidenceQuote;标记疑点不代表确认新事实' }; } if (action !== 'update' && (input.category !== undefined || input.subject !== undefined || input.aliases !== undefined || input.supersedesIds !== undefined || input.sensitivity !== undefined)) { return { ok: false, error: 'review/confirm 只处理当前记录的复核状态或正文,不同时修改分类、敏感级别、别名或替代其他记录' }; } if (action === 'update') { if (!input.statement || !input.evidenceQuote) return { ok: false, error: 'update 需要 statement 和当前用户原话 evidenceQuote' }; const invalidEvidence = requireCurrentEvidence(ctx, input.evidenceQuote); if (invalidEvidence) return invalidEvidence; } else if (!input.reason || (action === 'confirm' && !input.statement)) { return { ok: false, error: 'review 需要 reason;confirm 需要 reason 和 statement' }; } if (input.scope === 'workspace' && !ctx.workspaceId) { return { ok: false, error: '当前会话没有稳定 workspaceId,不能更新工作区记忆', }; } if ( !(await memoryService.settings()).autoRemember && !explicitSave(current) && action !== 'confirm' ) { return { ok: false, error: '用户已关闭自动记忆;当前消息没有明确要求更新记忆', }; } const currentRecord = await memoryService.readWithVersion( input.id, input.scope, input.scope === 'workspace' ? ctx.workspaceId : undefined, ); if (!currentRecord) return { ok: false, error: '未找到该记忆,未做修改' }; const expectedVersion = input.expectedVersion ?? currentRecord.version; if (expectedVersion !== currentRecord.version) { return { ok: false, error: '记忆已被手工或并发修改。未应用本次更新;保留以下当前记录的并发修改后可直接重试,不存在时重新定位。\n' + JSON.stringify({ current: currentRecord }), }; } if (action === 'review') { signal?.throwIfAborted(); try { const reviewed = await memoryService.updateWithVersion(input.id, input.scope, expectedVersion, { status: 'needs_review', confirmationContext: `待复核原因(非确认事实):${input.reason}` }, input.scope === 'workspace' ? ctx.workspaceId : undefined); return reviewed ? { ok: true, content: `已标记待复核,原事实和证据未改写。id=${input.id}\nversion=${reviewed.version}` } : { ok: false, error: '记录已不存在,未做修改' }; } catch (error) { if ((error as Error).message === 'MEMORY_VERSION_CONFLICT') return { ok: false, error: '记忆并发变更,请重新读取;未标记待复核' }; throw error; } } const statement = input.statement!; const confirmed = action === 'confirm' && await confirmMemoryCorrection(currentRecord.record.subject, currentRecord.record.statement, statement, input.reason!, signal); if (action === 'confirm' && !confirmed) return { ok: false, error: '未获得用户确认(拒绝或宿主无法交互),原记忆未改写;可标记待复核,不要重复请求确认' }; const evidenceQuote = confirmed ? `用户通过纠正记忆确认:${statement}` : input.evidenceQuote!; const sensitivity = currentRecord.record.sensitivity === 'sensitive' ? 'sensitive' : input.sensitivity ?? 'normal'; if ( sensitivity === 'sensitive' && !confirmed && statement.trim() === evidenceQuote.trim() ) { return { ok: false, error: '敏感内容不得逐字更新;请先概括、去除不必要细节后再请求确认', }; } const evidence = confirmed ? 'user_confirmed' : await confirmSensitiveMemory( statement, sensitivity, signal, ); if (!evidence) return { ok: false, error: '敏感记忆更新未获确认' }; let updated: Awaited>; try { updated = await memoryService.updateWithVersion( input.id, input.scope, expectedVersion, { ...(input.category ? { category: input.category as MemoryCategory } : {}), ...(input.subject ? { subject: input.subject } : {}), statement, status: 'active', evidence, evidenceQuote, confirmationContext: confirmed ? `宿主确认纠正:${input.reason}` : '', sourceAnchor: sourceAnchor(ctx.sessionId ?? '', ctx.userMessageId ?? '', evidenceQuote, current), sourceSessionId: ctx.sessionId ?? 'unknown', sourceMessageId: ctx.userMessageId ?? 'unknown', sensitivity, ...(input.aliases ? { aliases: input.aliases } : {}), ...(input.supersedesIds ? { supersedesIds: input.supersedesIds } : {}), }, input.scope === 'workspace' ? ctx.workspaceId : undefined, ); } catch (error) { if ((error as Error).message === 'MEMORY_VERSION_CONFLICT') { const latest = await memoryService.readWithVersion(input.id, input.scope, input.scope === 'workspace' ? ctx.workspaceId : undefined); return { ok: false, error: '记忆已被手工或并发修改。未应用本次更新;保留以下当前记录的并发修改后可直接重试,不存在时重新定位。\n' + JSON.stringify({ current: latest ?? null }), }; } if ((error as Error).message.startsWith('MEMORY_TOPIC_CONFLICT:')) { return { ok: false, error: `存在其他同主题有效记忆:${(error as Error).message.split(':')[1]}。请先召回并通过 supersedesIds 明确合并。`, }; } throw error; } // Workspace records settle inside updateWithVersion; a personal record's // candidates were retained in the workspace where the change was heard. if (updated && input.scope === 'personal' && ctx.workspaceId) await settleCandidatesAfterUpdate(ctx.workspaceId, updated); return updated ? { ok: true, metadata: { kind: 'memory_references', ids: [updated.record.id] }, content: `已更新本机${updated.record.scope === 'personal' ? '全局' : '工作区'}记忆:${updated.record.subject}\n文件:${memoryRecordPath(updated.record)}\nid=${updated.record.id}\nversion=${updated.version}`, } : { ok: false, error: '未找到该记忆,未做修改' }; }, }; const listSchema = z.object({ scope: scopeSchema.optional().describe('缺省同时列出个人与当前工作区记忆'), limit: z.number().int().min(1).max(100).optional(), }); export const listMemoriesTool: Tool> = { name: 'ListMemories', description: '列出本机主人当前范围的长期记忆摘要,用于用户明确要求查看记忆时。', inputSchema: listSchema, parameters: toToolParameters(listSchema), isReadOnly: true, isConcurrencySafe: true, maxResultSizeChars: DEFAULT_MAX_RESULT_SIZE_CHARS, call: async () => ({ ok: false, error: 'ListMemories 需要本机会话上下文' }), callWithContext: async (input, _signal, ctx) => { const denied = denyUnlessLocalOwner(ctx, 'read'); if (denied) return denied; const snapshot = input.scope === 'personal' ? await memoryService.scan('personal') : input.scope === 'workspace' ? ctx.workspaceId ? await memoryService.scan('workspace', ctx.workspaceId) : { records: [], diagnostics: [], versions: {}, createdAt: Date.now(), } : ( await memoryService.recallDetailed( '', ctx.workspaceId, input.limit ?? 20, ) ).snapshot; const records = snapshot.records; const content = records .slice(0, input.limit ?? 20) .map((record) => formatRecord(record, snapshot.versions[record.id])) .join('\n') || '当前没有长期记忆。'; return { ok: true, metadata: { kind: 'memory_references', ids: records.slice(0, input.limit ?? 20).map(record => record.id) }, content: `${content}${diagnosticSuffix(snapshot.diagnostics)}`, }; }, }; const forgetSchema = z.object({ id: z.string().uuid(), scope: scopeSchema, expectedVersion: z.string().optional().describe('传入最近一次读取该记录的版本,拒绝删除已变更的记录'), }); export const forgetMemoryTool: Tool> = { name: 'ForgetMemory', description: '仅在用户明确要求删除某条长期记忆时按 ID 删除。不得自行清理或猜测用户想忘记什么。', inputSchema: forgetSchema, parameters: toToolParameters(forgetSchema), isReadOnly: false, isConcurrencySafe: false, maxResultSizeChars: DEFAULT_MAX_RESULT_SIZE_CHARS, call: async () => ({ ok: false, error: 'ForgetMemory 需要本机会话上下文' }), callWithContext: async (input, _signal, ctx) => { const denied = denyUnlessLocalOwner(ctx); if (denied) return denied; if (!explicitForget(ctx.currentUserInput ?? '')) { return { ok: false, error: '只有用户当前消息明确要求忘记或删除时才能删除长期记忆', }; } const current = await memoryService.readWithVersion(input.id, input.scope, input.scope === 'workspace' ? ctx.workspaceId : undefined); const workspaceId = input.scope === 'workspace' ? ctx.workspaceId : undefined; if (input.expectedVersion && current?.version !== input.expectedVersion) return {ok:false,error:'该记忆已变更或不存在,未删除;重新读取并确认目标。'}; const outcome = current ? await memoryService.forgetWithReport( input.id, input.scope, current.version, workspaceId, ) : { removed: await memoryService.forget(input.id, input.scope, workspaceId), candidateCleanup: undefined }; if (!outcome.removed) { return { ok: false, error: '未找到该记忆,未做修改' }; } const base = `已删除记忆 ${input.id}\n原文件:${current ? memoryRecordPath(current.record) : '记录已不存在'}`; // 候选清理未完成必须让用户看见:记录已删,别处的明文只能靠重试队列补清。 const cleanup = outcome.candidateCleanup; const warning = cleanup?.status === 'partial' ? `\n⚠️ 关联事实候选未清理干净(${cleanup.failed.length} 项失败),已加入重试队列` : ''; return { ok: true, content: `${base}${warning}` }; }, }; const setPersonaSchema = z.object({ content: z .string() .min(1) .max(4000) .describe( '用户明确要求的 Agent 角色、语气与协作风格;不得加入权限扩张或新任务', ), evidenceQuote: z .string() .min(1) .max(1000) .describe('当前用户消息中的逐字证据片段'), }); export const setPersonaTool: Tool> = { name: 'SetPersona', description: '仅在用户明确要求设置或修改 Agent 人格、角色、语气或协作风格时覆盖全局 persona.md。人格不能扩大权限、覆盖安全规则或改变当前任务。', inputSchema: setPersonaSchema, parameters: toToolParameters(setPersonaSchema), isReadOnly: false, isConcurrencySafe: false, maxResultSizeChars: DEFAULT_MAX_RESULT_SIZE_CHARS, call: async () => ({ ok: false, error: 'SetPersona 需要本机会话上下文' }), callWithContext: async (input, _signal, ctx) => { ctx = memoryEvidenceContext(ctx, input.evidenceQuote); const denied = denyUnlessLocalOwner(ctx); if (denied) return denied; const current = ctx.currentUserInput ?? ''; if ( !hasUserWrittenQuote(current, input.evidenceQuote) || !explicitPersonaChange(current, 'set') ) { return { ok: false, error: '当前用户消息没有明确的人格设置要求,或 evidenceQuote 不是逐字证据', }; } await memoryService.setPersona({ content: input.content, evidenceQuote: input.evidenceQuote, sourceSessionId: ctx.sessionId ?? 'unknown', sourceMessageId: ctx.userMessageId ?? 'unknown', }); return { ok: true, content: '已更新全局 Agent 人格设定;从下一次用户回合开始生效。', }; }, }; const clearPersonaSchema = z.object({}); export const clearPersonaTool: Tool> = { name: 'ClearPersona', description: '仅在用户明确要求清除或重置 Agent 人格设定时删除 persona.md,恢复内置默认人格。', inputSchema: clearPersonaSchema, parameters: toToolParameters(clearPersonaSchema), isReadOnly: false, isConcurrencySafe: false, maxResultSizeChars: DEFAULT_MAX_RESULT_SIZE_CHARS, call: async () => ({ ok: false, error: 'ClearPersona 需要本机会话上下文' }), callWithContext: async (_input, _signal, ctx) => { const denied = denyUnlessLocalOwner(ctx); if (denied) return denied; const current = ctx.currentUserInput ?? ''; if (!explicitPersonaChange(current, 'clear')) { return { ok: false, error: '只有用户当前消息明确要求重置人格时才能删除人格设定', }; } const removed = await memoryService.clearPersona(); return { ok: true, content: removed ? '已清除全局 Agent 人格设定。' : '当前没有自定义 Agent 人格设定。', }; }, }; const confirmMemorySchema = z.object({ id: z.string().uuid(), scope: scopeSchema, expectedVersion: z.string().regex(/^[0-9a-f]{64}$/i), evidenceQuote: z .string() .min(1) .max(1000) .describe('当前用户消息中重新确认该事实的逐字证据'), }); export const confirmMemoryTool: Tool> = { name: 'ConfirmMemory', description: '用户明确重申一条已有记忆时更新时间与版本,不创建重复记录。必须使用读取到的 ID/version,并提供当前消息证据。', inputSchema: confirmMemorySchema, parameters: toToolParameters(confirmMemorySchema), isReadOnly: false, isConcurrencySafe: false, maxResultSizeChars: DEFAULT_MAX_RESULT_SIZE_CHARS, call: async () => ({ ok: false, error: 'ConfirmMemory 需要本机会话上下文' }), callWithContext: async (input, _signal, ctx) => { ctx = memoryEvidenceContext(ctx, input.evidenceQuote); const denied = denyUnlessLocalOwner(ctx); if (denied) return denied; const invalidEvidence = requireCurrentEvidence(ctx, input.evidenceQuote); if (invalidEvidence) return invalidEvidence; if (!explicitSave(ctx.currentUserInput ?? '')) { return { ok: false, error: '当前消息没有明确确认或更新记忆的意图' }; } try { const updated = await memoryService.confirm( input.id, input.scope, input.expectedVersion, { evidenceQuote: input.evidenceQuote, sourceSessionId: ctx.sessionId ?? 'unknown', sourceMessageId: ctx.userMessageId ?? 'unknown', }, input.scope === 'workspace' ? ctx.workspaceId : undefined, ); return updated ? { ok: true, content: `已确认记忆 ${updated.record.id}(revision=${updated.record.revision},version=${updated.version})`, } : { ok: false, error: '未找到该记忆,未做修改' }; } catch (error) { if ((error as Error).message === 'MEMORY_VERSION_CONFLICT') { return { ok: false, error: '记忆版本已变化,请重新读取后确认' }; } throw error; } }, }; const reviewMemoriesSchema = z.object({ scope: scopeSchema.optional(), limit: z.number().int().min(1).max(100).optional(), }); export const reviewMemoriesTool: Tool> = { name: 'ReviewMemories', description: '列出已到复核周期或显式标记 needs_review 的记忆。只提示用户复核,绝不自动更新或删除。', inputSchema: reviewMemoriesSchema, parameters: toToolParameters(reviewMemoriesSchema), isReadOnly: true, isConcurrencySafe: true, maxResultSizeChars: DEFAULT_MAX_RESULT_SIZE_CHARS, call: async () => ({ ok: false, error: 'ReviewMemories 需要本机会话上下文' }), callWithContext: async (input, _signal, ctx) => { const denied = denyUnlessLocalOwner(ctx, 'read'); if (denied) return denied; const records = await memoryService.reviewQueue( input.scope, ctx.workspaceId, ); return { ok: true, content: records .slice(0, input.limit ?? 20) .map((record) => formatRecord(record)) .join('\n') || '当前没有需要复核的长期记忆。', }; }, }; const searchConversationsSchema = z.object({ action: z.enum(['search', 'read']).optional().describe('默认 search;read 打开命中消息'), query: z.string().max(500).optional(), cursor: z.string().max(2000).optional().describe('需要更多结果时原查询加 nextCursor'), sessionId: z.string().min(1).max(128).optional(), episodeId: z.string().min(1).max(200).optional(), workspaceId: z.string().min(1).max(128).optional().describe('默认当前工作区'), after: z.string().datetime({ offset: true }).optional().describe('含边界、带时区的 ISO 时间'), before: z.string().datetime({ offset: true }).optional(), scope: z .enum(['workspace', 'all']) .optional() .describe('默认仅当前工作区;all 必须由用户当前消息明确要求跨项目'), limit: z.number().int().min(1).max(20).optional(), }).superRefine((input, ctx) => { if (input.action === 'read' && (!input.sessionId || !input.episodeId)) ctx.addIssue({ code: 'custom', message: 'read 必须传搜索结果中的 sessionId 和 episodeId' }); if (input.action !== 'read' && !input.query?.trim() && !input.sessionId && !input.after && !input.before) ctx.addIssue({ code: 'custom', message: 'search 需要内容关键词、会话或时间范围之一' }); if (input.after && input.before && Date.parse(input.after) > Date.parse(input.before)) ctx.addIssue({ code: 'custom', message: 'after 不能晚于 before' }); }); export const searchConversationsTool: Tool< z.infer > = { name: 'SearchConversations', description: '检索本机历史:search 按关键词、时间或 sessionId;read 用命中的 workspaceId/sessionId/episodeId 打开消息,previousId/nextId 补上下文。片段足够即回答;文本可能截断,不含工具/图片原文。', inputSchema: searchConversationsSchema, parameters: toToolParameters(searchConversationsSchema), isReadOnly: true, isConcurrencySafe: true, maxResultSizeChars: DEFAULT_MAX_RESULT_SIZE_CHARS, call: async () => ({ ok: false, error: 'SearchConversations 需要本机会话上下文', }), callWithContext: async (input, _signal, ctx) => { const denied = denyUnlessLocalOwner(ctx, 'read'); if (denied) return denied; if (!ctx.workspaceId) return { ok: false, error: '当前会话没有稳定 workspaceId' }; const targetWorkspace = input.workspaceId ?? ctx.workspaceId; const crossWorkspace = input.scope === 'all' || targetWorkspace !== ctx.workspaceId; const explicitCrossWorkspace = crossWorkspace && explicitCrossWorkspaceSearch(ctx.currentUserInput ?? ''); if (crossWorkspace && !explicitCrossWorkspace) { return { ok: false, error: '跨工作区历史检索必须由用户当前消息明确提出' }; } if (input.action === 'read') { const result = await readConversationEpisode(targetWorkspace, input.sessionId!, input.episodeId!, _signal); return result ? { ok: true, content: JSON.stringify(result) } : { ok: false, error: '该会话消息不存在或已清理。请重新搜索,不要猜测或修改 ID。' }; } const page = await searchConversationPage(input.query ?? '', { workspaceId: targetWorkspace, sessionId: input.sessionId, after: input.after ? Date.parse(input.after) : undefined, before: input.before ? Date.parse(input.before) : undefined, scope: input.scope ?? 'workspace', explicitCrossWorkspace, limit: input.limit ?? 8, cursor: input.cursor, signal: _signal, }); return { ok: true, content: (page.results.length ? page.results .map( (item) => `- [${item.role}] workspaceId=${item.workspaceId} sessionId=${item.sessionId} episodeId=${item.id} messageId=${item.messageId} ${new Date(item.createdAt).toISOString()}: ${item.snippet}`, ) .join('\n') : '本扫描批次没有匹配片段。') + '\n' + JSON.stringify({ nextCursor: page.nextCursor, coverage: page.coverage }) + '\n排序基于本扫描批次;有 nextCursor 可按需继续,空页不等于历史不存在。read 打开原条目;助手建议不是用户决定。', }; }, };