import { z } from 'zod'; import { researchPage } from '../agent/research.js'; import type { Tool, ToolCallContext, ToolResult } from '../../types.js'; import { toToolParameters } from '../../utils/zodToJson.js'; import { DEFAULT_MAX_RESULT_SIZE_CHARS } from '../types.js'; import { getBackgroundTask, readTaskLog, type BackgroundTaskState, } from './backgroundTaskService.js'; import { processExecutionMetadata } from './processEvidence.js'; import { getLiveAgentTask, loadAgentRecord, waitAgentCompletion, } from '../agent/agentTaskService.js'; const inputSchema = z.object({ task_id: z.string().regex(/^(?:proc_|agent_)?[0-9a-f-]{36}$/i), handoff: z.boolean().optional().describe('仅 Agent:读取结构化接力包、验收状态和当前 attempt_id'), finding_offset: z.number().int().nonnegative().optional().describe('仅 Agent:分页读取结构化问题清单,nextFindingOffset 续读。空清单不等于没有报告/问题;改用 handoff=true 读交接,不能据此验收。'), evidence_offset: z.number().int().nonnegative().optional() .describe('仅 Agent:按条目偏移分页读取宿主记录的阅读证据;0 为第一页'), offset: z .number() .int() .nonnegative() .optional() .describe('从该字节偏移读取;使用上次返回的 next_offset 增量读取'), tail_chars: z .number() .int() .min(1) .max(DEFAULT_MAX_RESULT_SIZE_CHARS) .optional(), block: z .boolean() .optional() .describe('任务仍运行时,是否等待新输出或任务结束'), timeout: z .number() .int() .min(1) .max(120_000) .optional() .describe('block=true 时的最长等待毫秒数'), }); type TaskOutputInput = z.infer; async function waitForChange( task: NonNullable>, offset: number, timeout: number, signal?: AbortSignal, ): Promise { signal?.throwIfAborted(); if ( task.status !== 'running' || readTaskLog(task, offset, 1).totalBytes > offset ) return; await new Promise((resolvePromise) => { const done = () => { clearTimeout(timer); task.events.off('change', done); signal?.removeEventListener('abort', done); resolvePromise(); }; const timer = setTimeout(done, timeout); timer.unref?.(); task.events.once('change', done); signal?.addEventListener('abort', done, { once: true }); if ( signal?.aborted || task.status !== 'running' || readTaskLog(task, offset, 1).totalBytes > offset ) done(); }); } async function call( input: TaskOutputInput, state: BackgroundTaskState | undefined, context?: ToolCallContext, signal?: AbortSignal, ): Promise { if (signal?.aborted) return { ok: false, error: 'aborted' }; if (input.task_id.startsWith('agent_') && context) { const live = getLiveAgentTask( context.sessionState?.agentTasks, input.task_id, ); const record = live ?? (await loadAgentRecord(context, input.task_id)); if (!record) return { ok: false, error: `当前会话中不存在 Agent ${input.task_id}` }; if (input.block && live?.status === 'running') { const wake = context.steering?.signal(); try { await waitAgentCompletion(live, input.timeout ?? 30_000, wake ? AbortSignal.any([...(signal ? [signal] : []), wake]) : signal); } catch (error) { if (signal?.aborted || !wake?.aborted || (error as Error).name !== 'AbortError') throw error; // Mailbox wake: return current state, not a failed or cancelled worker. } } const current = getLiveAgentTask(context.sessionState?.agentTasks, input.task_id) ?? (await loadAgentRecord(context, input.task_id)) ?? record; if (input.finding_offset !== undefined) return { ok: true, content: JSON.stringify({ agent_id: current.id, attempt_id: current.attemptId, status: current.status, summary: current.handoff?.summary ?? (current.result?.ok ? current.result.content.slice(0, 1200) : current.progress), needed: current.handoff?.needed, error: current.result && !current.result.ok ? current.result.error : undefined, ...researchPage(current.handoff?.findings ?? [], input.finding_offset), notice: current.handoff?.findings?.length ? '子任务分析不是用户决定;版本与读取范围以 readingEvidence 为准。' : '未提交结构化问题清单,不等于没有报告或没有发现问题。请用 TaskOutput(handoff=true) 读取完整交接;有缺口则续接、提问或由主 Agent 接管,不得据此验收。', }) }; if (input.handoff) return { ok: true, content: JSON.stringify({ agent_id: current.id, attempt_id: current.attemptId ?? String(current.createdAt), status: current.status, required: current.required === true, provenance: current.provenance ?? { mode: 'private', visibility: 'owner-private' }, contract: current.input, handoff: current.handoff ? { ...current.handoff, ...(current.handoff.findings ? researchPage(current.handoff.findings) : {}) } : undefined, resolution: current.resolution, metrics: current.result?.metadata?.kind === 'agent' ? current.result.metadata.researchMetrics : undefined, worktree: current.worktree, pendingMessages: current.inbox, result: current.result ? (current.result.ok ? current.result.content : current.result.error) : current.progress, }) }; if (input.evidence_offset !== undefined) { const metadata = current.result?.metadata; const evidence = metadata?.kind === 'agent' ? metadata.readingEvidence ?? [] : []; const start = Math.min(input.evidence_offset, evidence.length); const page = []; let chars = 0; for (const entry of evidence.slice(start, start + 20)) { const size = JSON.stringify(entry).length; if (page.length && chars + size > 12000) break; page.push(entry); chars += size; } return { ok: true, content: JSON.stringify({ agent_id: current.id, status: current.status, evidence: page, total: evidence.length, next_evidence_offset: start + page.length < evidence.length ? start + page.length : null, notice: '仅本次执行的观察记录;缺少 observation 不证明全文覆盖。旧版本不代表当前文件,不能代替修改前读取。', }) }; } const body = current.result ? current.result.ok ? current.result.content : current.result.error : (current.progress ?? ''); return { ok: true, content: `${body}\n\n[agent ${current.id}: ${current.status}]`, metadata: current.result?.metadata, }; } if (input.evidence_offset !== undefined) return { ok: false, error: 'evidence_offset 仅适用于 Agent 任务。' }; const task = getBackgroundTask(input.task_id, state); if (!task) return { ok: false, error: `当前会话中不存在后台任务 ${input.task_id}` }; const offset = input.offset ?? 0; const wake = context?.steering?.signal(); if (input.block && !wake?.aborted) await waitForChange(task, offset, input.timeout ?? 30_000, wake ? AbortSignal.any([...(signal ? [signal] : []), wake]) : signal); if (signal?.aborted) return { ok: false, error: 'aborted' }; let output: ReturnType; try { output = readTaskLog(task, offset, input.tail_chars ?? 20_000); } catch (error) { return { ok: false, error: `后台任务 ${task.id} 日志读取失败:${(error as Error).message}` + (task.result ? `\n保留的操作回执:${task.result.ok ? task.result.content : task.result.error}` : ''), metadata: task.result?.metadata }; } const text = task.logError && task.result ? `[日志写入失败:${task.logError}]\n保留的操作回执:${task.result.ok ? task.result.content : task.result.error}` : output.text || ''; return { ok: true, content: `${text}\n\n[task ${task.id}: ${task.status}; exit=${task.shell === 'download' ? 'n/a' : task.exitCode ?? (task.status === 'running' ? 'pending' : 'none')}; next_offset=${output.nextOffset}; total_bytes=${output.totalBytes}${task.outputSha256 ? `; sha256=${task.outputSha256}; complete=${task.complete}` : ''}; log=${task.logPath}]`, metadata: task.shell === 'download' ? task.result?.metadata : processExecutionMetadata({ shell: task.shell, mode: 'background', command: task.command, taskId: task.id, status: task.status === 'completed' ? 'completed' : task.status === 'failed' ? 'failed' : task.status === 'stopped' ? 'stopped' : 'running', exitCode: task.exitCode, }), }; } export const taskOutputTool: Tool = { name: 'TaskOutput', description: 'Reads incremental output from a background download or Bash/PowerShell process, or progress/results from an Agent task in the current session. Use block=true to wait efficiently instead of polling repeatedly. Reading output does not acknowledge the original delivery goal.', inputSchema, parameters: toToolParameters(inputSchema), isReadOnly: true, isConcurrencySafe: true, maxResultSizeChars: DEFAULT_MAX_RESULT_SIZE_CHARS, call: (input, signal) => call(input, undefined, undefined, signal), callWithContext: (input, signal, context: ToolCallContext) => call(input, context.sessionState?.backgroundTasks, context, signal), };