import { z } from 'zod'; import type { Tool, ToolCallContext, ToolResult } from '../../types.js'; import { toToolParameters } from '../../utils/zodToJson.js'; import { runManagedAgentTask } from './agent.js'; import { type AgentTaskRecord, appendAgentEvent, enqueueAgentMessage, getLiveAgentTask, listAgentRecords, loadAgentRecord, saveAgentRecord, waitAgentCompletion, type LiveAgentTask, } from './agentTaskService.js'; async function deliverMessage(context: ToolCallContext, task: LiveAgentTask, message: string, phase: string): Promise { if (context.steering && !context.steering.pending()) task.steeringAcknowledgedRevision = context.steering.revision(); enqueueAgentMessage(task, message); try { await saveAgentRecord(context, task); await appendAgentEvent(context, task.id, { phase, message }); return { ok: true, content: `消息已发送给 ${task.id},将在下一个模型边界生效。` }; } catch (error) { // The running agent can consume its inbox during either disk await. Delivery // cannot be rolled back safely, so do not invite a duplicate retry. return { ok: true, content: `消息已交给 ${task.id},不要重复发送。持久化/审计失败:${(error as Error).message};进程重启后不保证恢复该消息,请核实子任务进展。` }; } } const agentId = z.string().regex(/^agent_[0-9a-f-]{36}$/i); function needsContext(context: ToolCallContext): ToolResult | undefined { if (!context.sessionState) return { ok: false, error: 'Agent 控制工具需要当前 Session 运行状态。' }; return undefined; } function snapshot(record: AgentTaskRecord) { return { preview: true, agent_id: record.id, status: record.status, description: record.description, progress: record.progress?.slice(0, 200), created_at: record.createdAt, updated_at: record.updatedAt, attempt_id: record.attemptId ?? String(record.createdAt), handoff: record.handoff && { kind: record.handoff.kind, summary: record.handoff.summary.slice(0, 400), needed: record.handoff.needed?.slice(0, 200), finding_count: record.handoff.findings?.length }, resolution: record.resolution && { action: record.resolution.action, summary: record.resolution.summary.slice(0, 200), coverage: record.resolution.coverage, supersededBy: record.resolution.supersededBy }, required: record.required === true, full_result_tool: `TaskOutput(task_id="${record.id}", handoff=true)`, pending_messages: record.inbox?.length ?? 0, // A child may have reported before the execution layer failed. Never let // that older packet hide the actual terminal error. result: record.result && (!record.handoff || !record.result.ok) ? record.result.ok ? record.result.content.slice(0, 400) : `Error: ${record.result.error.slice(0, 400)}` : undefined, }; } const messageSchema = z.object({ agent_id: agentId, message: z.string().min(1).max(100_000), }); export const agentMessageTool: Tool> = { name: 'AgentMessage', description: 'Sends additional context or a correction to one running sub-agent by stable agent_id. ' + 'The message is inserted at the next model boundary without cancelling its current tool call. ' + 'Use AgentFollowup instead when the agent is already idle or completed.', inputSchema: messageSchema, parameters: toToolParameters(messageSchema), isReadOnly: false, isConcurrencySafe: true, call: async () => ({ ok: false, error: 'AgentMessage requires session context', }), callWithContext: async (input, _signal, context) => { const missing = needsContext(context); if (missing) return missing; const task = getLiveAgentTask( context.sessionState!.agentTasks, input.agent_id, ); if (!task || task.status !== 'running') { const saved = await loadAgentRecord(context, input.agent_id); return saved ? { ok: false, error: `Agent ${input.agent_id} 当前为 ${saved.status};请使用 AgentFollowup 启动后续回合。`, } : { ok: false, error: `当前 Session 中不存在 Agent ${input.agent_id}` }; } return deliverMessage(context, task, input.message, 'message'); }, }; const listSchema = z.object({ include_completed: z.boolean().optional(), }); export const agentListTool: Tool> = { name: 'AgentList', description: 'Lists sub-agents owned by the current Session, including stable IDs, status and latest progress.', inputSchema: listSchema, parameters: toToolParameters(listSchema), isReadOnly: true, isConcurrencySafe: true, call: async () => ({ ok: false, error: 'AgentList requires session context', }), callWithContext: async (input, _signal, context) => { const missing = needsContext(context); if (missing) return missing; const records = (await listAgentRecords(context)).filter( (record) => input.include_completed !== false || record.status === 'running', ); return { ok: true, content: records.length ? JSON.stringify(records.map(snapshot)) : '当前 Session 没有符合条件的子 Agent。', }; }, }; const waitSchema = z.object({ agent_ids: z.array(agentId).min(1).max(8), timeout_ms: z.number().int().min(0).max(120_000).optional(), }); export const agentWaitTool: Tool> = { name: 'AgentWait', description: 'Waits until any selected running sub-agent finishes, sends a new handoff, or the timeout expires; returns snapshots for all selected IDs. timeout_ms=0 reads immediately. A wake-up is not proof of completion.', inputSchema: waitSchema, parameters: toToolParameters(waitSchema), isReadOnly: true, isConcurrencySafe: true, interruptBehavior: () => 'cancel', call: async () => ({ ok: false, error: 'AgentWait requires session context', }), callWithContext: async (input, signal, context) => { if (signal?.aborted) return { ok: false, error: 'aborted' }; const missing = needsContext(context); if (missing) return missing; const live = input.agent_ids .map((id) => getLiveAgentTask(context.sessionState!.agentTasks, id)) .filter((task): task is NonNullable => Boolean(task?.status === 'running'), ); const timeoutMs = input.timeout_ms ?? 30_000; // Steering wakes this wait without aborting the owning turn or its children. const waitSignal = context.steering ? AbortSignal.any([...(signal ? [signal] : []), context.steering.signal()]) : signal; if (live.length && timeoutMs > 0) { const listeners: Array<() => void> = []; const handoffs = live.map((task) => new Promise((resolve) => { const revision = task.handoffRevision ?? 0; const changed = () => { if ((task.handoffRevision ?? 0) > revision) resolve(); }; task.events.on('change', changed); listeners.push(() => task.events.off('change', changed)); })); let timer: ReturnType | undefined; let onAbort: (() => void) | undefined; const timeout = new Promise((resolve) => { timer = setTimeout(resolve, timeoutMs); timer.unref?.(); }); const aborted = new Promise((resolve) => { if (!waitSignal) return; onAbort = () => resolve(); if (waitSignal.aborted) resolve(); else waitSignal.addEventListener('abort', onAbort, { once: true }); }); await Promise.race([ ...live.map((task) => task.completion), ...handoffs, timeout, aborted, ]); listeners.forEach((remove) => remove()); if (timer) clearTimeout(timer); if (waitSignal && onAbort) waitSignal.removeEventListener('abort', onAbort); if (signal?.aborted) return { ok: false, error: 'aborted' }; } const records: AgentTaskRecord[] = []; const missingIds: string[] = []; for (const id of input.agent_ids) { const record = getLiveAgentTask(context.sessionState!.agentTasks, id) ?? (await loadAgentRecord(context, id)); if (record) records.push(record); else missingIds.push(id); } return { ok: true, content: JSON.stringify( { agents: records.map(snapshot), missing: missingIds }, ), }; }, }; const interruptSchema = z.object({ agent_id: agentId }); export const agentInterruptTool: Tool> = { name: 'AgentInterrupt', description: 'Requests interruption of one running sub-agent owned by this Session. Check the returned status; exit may still be in progress. Private history and progress remain available to AgentFollowup; unchanged worktrees may be cleaned up.', inputSchema: interruptSchema, parameters: toToolParameters(interruptSchema), isReadOnly: false, isConcurrencySafe: true, call: async () => ({ ok: false, error: 'AgentInterrupt requires session context', }), callWithContext: async (input, _signal, context) => { const missing = needsContext(context); if (missing) return missing; const live = getLiveAgentTask( context.sessionState!.agentTasks, input.agent_id, ); if (!live || live.status !== 'running') { const saved = await loadAgentRecord(context, input.agent_id); return saved ? { ok: true, content: `Agent ${input.agent_id} 已经是 ${saved.status},未执行中断。`, } : { ok: false, error: `当前 Session 中不存在 Agent ${input.agent_id}` }; } const previous = live.status; live.abort.abort(new Error('interrupted-by-parent-agent')); await waitAgentCompletion(live, 5000); return { ok: true, content: `${live.status === 'running' ? '已请求中断,仍在退出中' : '已中断'} ${live.id}(先前状态:${previous};当前状态:${live.status})。`, }; }, }; const followupSchema = z.object({ agent_id: agentId, message: z.string().min(1).max(100_000), run_in_background: z.boolean().optional(), }); export const agentFollowupTool: Tool> = { name: 'AgentFollowup', description: 'Adds a follow-up task to a stable sub-agent. If it is running, delivers the message at the next model boundary; if idle, resumes its persisted private history and starts a new turn.', inputSchema: followupSchema, parameters: toToolParameters(followupSchema), isReadOnly: false, isConcurrencySafe: true, interruptBehavior: () => 'block', call: async () => ({ ok: false, error: 'AgentFollowup requires session context', }), callWithContext: async (input, signal, context) => { const missing = needsContext(context); if (missing) return missing; const live = getLiveAgentTask( context.sessionState!.agentTasks, input.agent_id, ); if (live?.status === 'running') { return deliverMessage(context, live, input.message, 'followup'); } const saved = await loadAgentRecord(context, input.agent_id); if (!saved) return { ok: false, error: `当前 Session 中不存在 Agent ${input.agent_id}`, }; return runManagedAgentTask( { description: saved.description, prompt: input.message, resume_agent_id: input.agent_id, run_in_background: input.run_in_background ?? true, }, signal, context, ); }, };