import { isDeepStrictEqual } from 'node:util'; import { z } from 'zod'; import { researchFindingSchema } from './research.js'; import type { Message, Tool, ToolResult } from '../../types.js'; import { toToolParameters } from '../../utils/zodToJson.js'; import { BUILTIN_TOOL_PROMPT_GUIDES } from '../toolPromptGuides.js'; import { getLiveAgentTask, loadAgentRecord, saveAgentRecord, waitAgentCompletion } from './agentTaskService.js'; const lines = z.array(z.string().min(1).max(1000)).max(20); const reportSchema = z.object({ kind: z.enum(['help', 'blocked', 'result']), summary: z.string().min(1).max(4000).describe('第一句简短写出本次分工的结论或具体进展;范围、路径、限制放后面或 findings,不要让免责声明挤掉结论。'), completed: lines, attempted: lines, remaining: lines, parentNextSteps: lines.optional().describe('任务书预先约定由主 Agent 执行的集成、组合验证;不计为子任务未完成。不得用它转移自己未完成的必要工作。'), needed: z.string().min(1).max(2000).optional().describe('需要主 Agent 补充的输入或接管事项;一般验证限制写在 summary/findings,不当作求助。'), evidenceRefs: z.array(z.string().min(1).max(200)).max(40), findings: z.array(researchFindingSchema).max(24).optional(), }).superRefine((value, context) => { if (value.kind !== 'result' && !value.needed) context.addIssue({ code: 'custom', path: ['needed'], message: '求助必须说明需要主 Agent 提供什么或接管什么' }); if (value.kind === 'result' && value.remaining.length) context.addIssue({ code: 'custom', path: ['remaining'], message: '还有必需工作未完成时使用 blocked,不把缺口作为成功结果' }); }); /** Legacy error messages may be pre-execution denials. Without a receipt, fail closed. */ function hasExecutionReceipt(m: Extract): boolean { return m.toolResultDisposition === 'executed' || (m.toolResultDisposition === undefined && m.display_ok === true); } const WRITE_REVIEW_INSPECTION_TOOLS = new Set(['Read', 'Grep', 'Glob', 'LSP', 'Bash', 'PowerShell']); /** * 校验写任务验收证据:必须是主历史里本任务创建后、非 deferred 的检查类工具调用的 * tool_call_id。不通过时错误里说明**哪几个**引用不对、为什么,并列出当前可直接引用的 * 候选——此前只有一句泛泛的话,主 Agent 把后台进程句柄(proc_…,给 TaskOutput/TaskStop 用) * 当调用 ID 填进去后,既不知道错在哪,也没处查可用 ID。 */ export function writeReviewEvidenceError( history: readonly Message[], createdAt: number, refs: readonly string[], executed?: ReadonlyMap, ): string | null { const calls = new Map(); for (const m of history) if (m.role === 'assistant') for (const c of m.tool_calls ?? []) calls.set(c.id, c.function.name); const valid = new Map(); // 台账:压缩掉历史后,真实执行过的检查仍可引用。 for (const [id, entry] of executed ?? []) { if (!calls.has(id)) calls.set(id, entry.tool); if (entry.at >= createdAt && WRITE_REVIEW_INSPECTION_TOOLS.has(entry.tool)) valid.set(id, entry.tool); } for (const m of history) { if (m.role !== 'tool' || m.timestamp === undefined || m.timestamp < createdAt) continue; if (!hasExecutionReceipt(m)) continue; const name = calls.get(m.tool_call_id); if (name && WRITE_REVIEW_INSPECTION_TOOLS.has(name)) valid.set(m.tool_call_id, name); } const bad = refs.filter((ref) => !valid.has(ref)); if (!bad.length) return null; const reasons = bad.map((ref) => { if (/^proc_/i.test(ref)) return `${ref}(这是后台进程句柄,供 TaskOutput/TaskStop 使用,不是工具调用 ID)`; const name = calls.get(ref); if (name && !WRITE_REVIEW_INSPECTION_TOOLS.has(name)) return `${ref}(${name} 不是检查类工具)`; if (name) return `${ref}(该调用早于本任务创建,或结果仍是 deferred 占位)`; return `${ref}(当前主历史里没有这个调用,可能已被压缩)`; }); const candidates = [...valid].slice(-8).map(([id, name]) => `${id}(${name})`); return [ `writeReview 证据必须是当前主历史中本任务创建后的实际检查调用 ID(Read/Grep/Glob/LSP/Bash/PowerShell 的 tool_call_id),不能引用控制回执。无效:${reasons.join(';')}。`, candidates.length ? `当前可引用的最近检查调用:${candidates.join('、')}。` : '当前历史里没有可引用的检查调用;请先由主 Agent 亲自运行测试/读取改动,再登记。', ].join(''); } /** Private host control channel; not a workspace capability delegated by name. */ export const agentReportTool: Tool> = { get promptGuide() { return BUILTIN_TOOL_PROMPT_GUIDES.AgentReport; }, // private channel; not in ALL_TOOLS name: 'AgentReport', inputSchema: reportSchema, parameters: toToolParameters(reportSchema), description: '向主 Agent 交接。help=求助但继续独立工作;blocked=交回部分成果和必要缺口,停止本次执行;result=分工完成,不等于整体验收。先续读可用材料,不因摘要截断或约定由主 Agent 执行的测试而受阻。本工具不询问用户、不授予权限。remaining 只写自己的必需缺口,parentNextSteps 写预定的主 Agent 集成验证;有结论就填写 summary,问题级结论放 findings,并附真实证据 ID。', isReadOnly: true, isConcurrencySafe: false, call: async () => ({ ok: false, error: 'AgentReport requires a parent channel' }), callWithContext: async (input, _signal, ctx) => { if (!ctx.agentHandoff) return { ok: false, error: '当前没有主 Agent 交接通道' }; // 历史 ∪ 执行台账:长任务压缩掉旧工具消息后,真实做过的检查仍可引用。 const known = new Set([ ...(ctx.history?.filter((m) => m.role === 'tool').filter(hasExecutionReceipt).map((m) => m.tool_call_id) ?? []), ...(ctx.executedCalls?.keys() ?? []), ]); const refs = [...input.evidenceRefs, ...(input.findings ?? []).flatMap(finding => finding.evidenceRefs)]; if (refs.some((ref) => !known.has(ref))) { // Hand back real handles instead of making the model guess: only IDs the // kernel already recorded from its own tool results are citable. const available = [...known].slice(-8); return { ok: false, error: `存在不可定位的证据 ID;只引用当前子历史中的工具结果。可用的证据 ID 示例:${available.join('、') || '(当前还没有工具结果,先生成证据)'}`, }; } const questions = ctx.agentHandoff.questionIds; if (questions?.length && input.findings?.some(finding => !questions.includes(finding.questionId))) return { ok: false, error: 'findings 引用了任务书之外的问题 ID,不得扩大调查范围' }; if (questions?.length && input.kind === 'result' && questions.some(id => !input.findings?.some(finding => finding.questionId === id))) return { ok: false, error: '结果未覆盖所有委派问题;有必需缺口请提交 blocked,不伪造完整结果' }; await ctx.agentHandoff.report(input); return { ok: true, content: input.kind === 'help' ? '求助已记录;可继续独立工作,不能假定已收到答复。' : '交接已记录,本次执行结束,主 Agent 将核验或接力。' }; }, }; /** * The only definition of what a legal `waive` looks like. The Zod schema (model * input boundary) and `callWithContext` (direct callers) both use it, so the * wording and the rules cannot drift apart. */ function waiveViolation(value: { action: string; coverage?: string; superseded_by?: string; }): { path: 'coverage' | 'superseded_by'; message: string } | undefined { if (value.action !== 'waive') return undefined; if (!value.coverage) return { path: 'coverage', message: 'waive 必须说明责任去向(superseded/takeover/goal_changed/gap);只是放弃不能代表用户目标已覆盖' }; if (value.coverage === 'takeover') return { path: 'coverage', message: '接管不能通过 waive 形式化放行:请用 action=takeover 保留未完成责任,完成后再用 complete 收口' }; if (value.coverage === 'superseded' && !value.superseded_by) return { path: 'superseded_by', message: 'superseded 必须指明接替的 agent_id;没有可追踪的替代任务等于责任去向不明' }; return undefined; } const resolveSchema = z.object({ agent_id: z.string().regex(/^agent_[0-9a-f-]{36}$/i), attempt_id: z.string().min(1), action: z.enum(['accept', 'takeover', 'complete', 'waive']), summary: z.string().min(1).max(4000), coverage: z.enum(['superseded', 'takeover', 'goal_changed', 'gap']).optional() .describe('waive 必填:责任去向。superseded=有替代任务覆盖(须同时给 superseded_by);takeover 不允许用于 waive,请直接 action=takeover;goal_changed=用户明确改变目标(summary 必须写明依据);gap=保留为未完成缺口(仍会阻塞最终交付)'), superseded_by: z.string().regex(/^agent_[0-9a-f-]{36}$/i).optional() .describe('waive + superseded 必填:真正接替的 agent_id。该任务未收口时原责任仍然阻塞交付'), writeReview: z.object({ integration: z.string().min(1).max(2000).describe('主工作区已集成的改动及冲突处理;没有需要集成的改动则解释原因,不能只说子 worktree 已完成'), validation: z.string().min(1).max(2000).describe('主 Agent 对最终工作区的验证结果、未运行项及理由;尚有必需验证未完成不得收口'), evidenceRefs: z.array(z.string().min(1)).min(1).max(20).describe('主 Agent 本次任务创建后的实际检查工具调用 ID,不引用子报告代替验证'), }).optional(), }).superRefine((value, context) => { const violation = waiveViolation(value); if (violation) context.addIssue({ code: 'custom', path: [violation.path], message: violation.message }); }); export const agentResolveTool: Tool> = { name: 'AgentResolve', inputSchema: resolveSchema, parameters: toToolParameters(resolveSchema), description: '主 Agent 记录子任务收口:accept=已核验成功结果;takeover=停止子任务并接管未完成工作(接管后仍需 complete);complete=主 Agent 接管后已完成;waive=明确取消或不再需要,必须用 coverage 说明责任去向。waive 不允许 coverage=takeover;superseded 必须用 superseded_by 指明接替任务,且接替任务未收口时原责任仍阻塞。传当前 attempt_id,旧尝试不能验收。登记不证明验证通过,也不扩大授权。', isReadOnly: false, isConcurrencySafe: false, call: async () => ({ ok: false, error: 'AgentResolve requires session context' }), callWithContext: async (input, signal, ctx): Promise => { const state = ctx.sessionState?.agentTasks; if (!state) return { ok: false, error: '缺少 Session' }; const claims = state.claims ??= new Set(); if (claims.has(input.agent_id)) return { ok: false, error: '该任务正在恢复或收口,请稍后核对状态' }; claims.add(input.agent_id); try { const live = getLiveAgentTask(state, input.agent_id); const record = live ?? await loadAgentRecord(ctx, input.agent_id); if (!record || (record.attemptId ?? String(record.createdAt)) !== input.attempt_id) return { ok: false, error: '任务不存在或 attempt_id 已变化,请重新读取 AgentList' }; if (record.resolution?.action === input.action && record.resolution.summary === input.summary && record.resolution.coverage === input.coverage && record.resolution.supersededBy === input.superseded_by && isDeepStrictEqual(record.resolution.writeReview, input.writeReview)) return { ok: true, content: JSON.stringify({ agent_id: record.id, resolution: record.resolution }) }; if (record.resolution && ['accept', 'complete', 'waive'].includes(record.resolution.action)) return { ok: false, error: '本次尝试已收口;新增工作应 AgentFollowup 创建新的尝试' }; const violation = waiveViolation(input); if (violation) return { ok: false, error: violation.message }; if (input.action === 'waive' && input.coverage === 'superseded') { // waiveViolation has already guaranteed superseded_by is present. const replacementId = input.superseded_by!; if (replacementId === record.id) return { ok: false, error: '替代任务不能是自身' }; const replacement = getLiveAgentTask(state, replacementId) ?? (await loadAgentRecord(ctx, replacementId)); if (!replacement) return { ok: false, error: `替代任务 ${replacementId} 不存在;原责任仍然开放` }; } if (live?.status === 'running') { if (!['takeover', 'waive'].includes(input.action)) return { ok: false, error: '子任务仍在运行,不能验收' }; live.abort.abort(new Error('parent-takeover')); await waitAgentCompletion(live, 5000, signal); if (live.status === 'running') return { ok: false, error: '仍在退出,尚未转移执行责任;请等待后重试' }; } signal?.throwIfAborted(); if (input.action === 'accept' && record.status !== 'completed') return { ok: false, error: '仅 completed 结果可以 accept;其他情况请续接或接管' }; if (input.action === 'complete' && record.resolution?.action !== 'takeover') return { ok: false, error: '必须先接管,再登记主 Agent 已完成' }; if (record.input.agent_type === 'general' && ['accept', 'complete'].includes(input.action)) { if (!input.writeReview) return { ok: false, error: '写任务必须提供 writeReview:说明主工作区集成、最终验证和主 Agent 检查证据;子任务 completed 不等于集成完成' }; const evidenceError = writeReviewEvidenceError(ctx.history ?? [], record.createdAt, input.writeReview.evidenceRefs, ctx.executedCalls); if (evidenceError) return { ok: false, error: evidenceError }; } const previous = record.resolution; record.resolution = { action: input.action, summary: input.summary, at: Date.now(), ...(input.coverage ? { coverage: input.coverage } : {}), ...(input.superseded_by ? { supersededBy: input.superseded_by } : {}), ...(input.writeReview ? { writeReview: input.writeReview } : {}) }; record.updatedAt = Date.now(); try { await saveAgentRecord(ctx, record); } catch (error) { record.resolution = previous; throw error; } return { ok: true, content: JSON.stringify({ agent_id: record.id, attempt_id: record.attemptId, resolution: record.resolution, handoff: record.handoff, result: record.result }) }; } finally { claims.delete(input.agent_id); } }, };