16 · 可靠委托:证据、账本与失败语义
第 15 章已经证明:child 的整个搜索过程,可以缩成 parent 收到的一条 tool result。但“能委托”不等于“委托回来的结果能用”。现在还有四个问题:
- child 的自然语言报告可能一条证据都没有。
done之外的停止原因,仍被当成普通文本交回去。- child 花的 token 只显示在诊断信息里。
/cost只能先停用。
本章不增加更多 agent。它只收紧现有 Task Tool 的返回协议。这里的模式叫 orchestrator-worker(主 agent 派活、worker 干活再交回),交回的那一段文本叫 handoff(交接)。本章要让这次交接在四件事上都有明确规则:什么算成功、什么算失败、花了多少钱、取消时怎么办。
能力边界与控制流
parent task tool_use
→ per-run Task budget
├─ 已启动 2 个 child:error ToolResult,不再调用模型
└─ 仍有额度:child runAgent
(fresh messages / Read+Grep / maxTurns=6 / no compaction)
→ child RunResult { reason, messages, usageDelta }
├─ aborted:error ToolResult + usageDelta;parent 随同一 signal settle
├─ failed / max_turns / no_progress:error ToolResult + usageDelta
├─ done 但 final text 为空:error ToolResult + usageDelta
├─ done 但没有 file:line / command output:error ToolResult + usageDelta
└─ done + 非空 + evidence:有界 success ToolResult + usageDelta
→ parent runAgent 把 ToolResult.usageDelta 加入本 run 一次
→ parent 独立 Read/Grep 复查引用后再行动
→ Session 只 merge parent RunResult.usageDelta 一次
成功条件是 done + 非空 final text + 至少一条可定位证据。
这道检查只是 lint(只看格式的静态检查)。它能让模型少省略证据,但证明不了内容是真的:
- 编一个
src/foo.ts:1,能过正则。 - 甚至
example.com:8080这种长得像路径的东西,也可能过正则。
所以 parent 仍要自己重新 Read 或 Grep。目前“必须复查”只写在工具 description 里,再靠真实验收来检查,runtime 没有强制。
报告能复查,降低了“只能相信一段流畅文字”的风险。但它没有解决 prompt injection(文件内容里藏着诱导模型的指令)。仓库文件仍是不可信输入。child 可能引用一段真实存在、却带着诱导指令的文本。
账本怎样不重不漏
ToolResult 第一次带上一个可选字段 usageDelta。原因是 Task 是唯一一个会在工具执行期间再去调用模型的 Tool。父 run 的用量公式是:
parent RunResult.usageDelta
= parent 自己所有已完成的主模型调用
+ parent compaction 的 summary 调用
+ 每个 Task child RunResult.usageDelta(各加一次)
关于这个公式,有三点要说明:
- 本书里 child 的 compaction 是关掉的。以后如果打开,child 的
RunResult.usageDelta已经包含 child 的总结用量,父层仍然只加一次 child 的总数。 - CLI 最后只把 parent 的
RunResult.usageDeltamerge 进SessionState.usageTotals。 - Task 报告会成为 parent 下一次请求的输入,这会产生新的 token。那是另一次真实的模型计算,应该算进 parent 后续那次 response 的 usage。这不是把 child 重复算了一遍。
Task 报告不是确定性 memory
第 14 章的 Todo 在父层 compaction 时有固定槽位,还有 4,000 字符的摘录。Task 报告不享受这个待遇。原因是两者的可信度不同:
- Todo 是 runtime 已经确认的当前状态。
- 通过证据检查的 Task 报告,仍然只是父层没复核过的模型报告。
如果把 Task 报告永久放进 CompactionDetails,就等于把一段不可信的陈述抬成了确定事实。
Task 报告的保留过程是这样的:
- Task 刚返回时,完整报告还在 recent messages 里。parent 有机会立刻复查。
- 复查得到的 Read/Grep tool result、因此产生的代码修改、Todo 状态,才进入可以长期依赖的证据链。
- 报告变旧之后,可以走通用的 800 字符摘录,甚至被 24 条事实窗口淘汰。
所以成功结果始终带 Unverified 前缀。这不是忘了处理,而是按可信度决定留不留。
bounded explorer 的预算不是一张空白支票
bounded explorer 指的是有上限的只读调查 child。child 的限制如下:
- 沿用第 10 章的单个工具结果截断。
maxTurns: 6。- 本章新加:最终报告最多 12,000 字符。
- 不进入有损的 compaction。
父 run 再加一条 maxTasks: 2。不管模型在一次响应里批量发出多少个 Task,也不管它收到 isError 后是否继续重派,实际启动的 child 最多两个。
当前 parent loop 按 tool use 的顺序执行。所以同一响应里的两个 Task 是一个接一个跑的,不是并行 fan-out(同时派出多个任务)。由此可以算出:
- 每个 child 最多六轮模型调用。
- child 逻辑轮的总上限是
2 × 6。 - 一轮内部仍可能有有限次重试,所以底层请求次数不能直接按十二次算。
- 第三个 Task 返回
isError,没有 child usage。 - 取消第一个 Task 时,同一个 signal 会在下一个准备好的调用执行前终止 parent,余下的委托不再启动。
“并行调度器明确延后”不是说模型不会批量生成 Task。模型会批量生成,只是 runtime 目前只给这些调用串行、有上限的语义。
这些仍是粗粒度的预算,不是精确的美元硬上限。每轮 input 会随历史变长,最终花费仍以 usage 为准。本章做的是这几件事:
- 限制每个 child 的逻辑轮数。
- 限制每个 parent run 能启动的 child 数。
- 限制单次工具结果和 handoff 文本的大小。
- 拿到完整 usage 的消耗,全部归账。
没返回完整用量的失败请求,仍需要另外对账。
EXPLORER_SYSTEM 在不同 Task 之间是同一段文字。但 Read/Grep 的工具定义加上这段 system,远短于 Haiku 4.5 最低可缓存前缀的 4,096 token。所以单独给 system 加 breakpoint(缓存断点)只会被静默跳过。
child 的历史在后面几轮里涨过这条最低线之后,顶层 automatic caching 才有可能命中,而且仍要看 cache usage 字段来确认。child 也读不到 parent 的 cache,因为两边的 tools、system 和 messages 前缀都不一样。
完整代码增量
先改 src/tools.ts,让内部 Tool 结果能带嵌套的 usage。模型能看到的部分仍是第 08 章的判别联合(用一个字段区分成功和失败两种形状)。usageDelta 只在 runtime 内部往上汇总,不进 prompt:
import type { Usage } from './usage.js'
export type ToolResult = ToolVisibleResult & {
usageDelta?: Usage
}
再改 src/agent.ts 的工具执行段。
第 10 章的 afterToolCall 返回完整的 ToolVisibleResult。它可以改写模型看到的成功或失败,但不能伪造或删掉成本记录。所以派发函数会保留执行阶段产生的原始 usageDelta,等 hook 处理完,再由 parent 汇总一次。
这样,下面几种情况下,已经完成的模型调用都不会漏记:
- child 最终是
aborted。 - child 报错。
- 后置 hook 自己失败。
// executeToolCall 内:保留 execute 之前的 signal.throwIfAborted();
// 从原来的 let result 开始,到原来的 afterToolCall 返回处,替换为:
let rawResult: ToolResult
try {
rawResult = await prepared.execute(opts.env, opts.signal)
} catch (error) {
rawResult = errorResult(
opts.signal.aborted ? 'TOOL_ABORTED' : 'TOOL_EXECUTION_FAILED',
errorMessage(error),
)
}
// 从这里到 return 不能再 throwIfAborted,否则会丢掉已经产生的 child usage。
let visibleResult: ToolVisibleResult
try {
visibleResult = opts.signal.aborted
? errorResult('TOOL_ABORTED', 'Tool was cancelled after execution.')
: await opts.afterToolCall(context, rawResult, opts.signal)
} catch (error) {
visibleResult = errorResult(
'AFTER_TOOL_CALL_FAILED',
errorMessage(error),
)
}
if (opts.signal.aborted) {
visibleResult = errorResult('TOOL_ABORTED', 'Tool was cancelled after execution.')
}
return {
...visibleResult,
...(rawResult.usageDelta
? { usageDelta: rawResult.usageDelta }
: {}),
}
// 第 15 章工具批次内,所有 result 分支汇合后、tool_end 之前插入:
// repeatGuard、warn/stop、补齐 skipped 结果与末尾 no_progress 出口全部保留。
if (result.usageDelta) {
addUsage(usageDelta, result.usageDelta)
}
// 后面沿用 tool_end、toolResults.push 与成对 messages 提交。
这里不写 toolUse.name === 'task' 这种特判。机制只认一件事:一个 ToolResult 可能带嵌套的 usageDelta。什么时候带,由 Task 决定;MCP 和本地工具仍然不带。
tool_end 和模型看到的,都是 after hook 处理后的完整判别联合。只有 usageDelta 是 runtime 从原始结果里取回来的。
然后替换 src/task-tool.ts。上一章的输入解析、assistantText 和 createReadOnlyTools 保留不动。新增下面的证据检查、输出上限和生命周期事件,并用新版 createTaskTool 替换旧的工厂函数:
import type { RunOutcome } from './agent.js'
import type {
AfterToolCall,
AgentEvent,
} from './agent.js'
import type { AgentError } from './errors.js'
const MAX_TASK_REPORT_CHARS = 12_000
const MAX_EVIDENCE_LINES = 12
const MAX_EVIDENCE_LINE_CHARS = 240
const DEFAULT_MAX_TASKS_PER_RUN = 2
const FILE_LINE_REFERENCE =
/(?:^|[\s`[(])(?:\.{0,2}\/)?[A-Za-z0-9_.-]+(?:\/[A-Za-z0-9_.-]+)*:[1-9]\d*\b/
export type TaskLifecycleEvent =
| {
type: 'task_start'
taskId: string
description: string
}
| {
type: 'task_child_event'
taskId: string
event: AgentEvent
}
| {
type: 'task_end'
taskId: string
reason: RunOutcome['reason']
accepted: boolean
evidenceCount: number
truncated: boolean
usageDelta: Usage
}
type TaskDetailsBase = {
kind: 'task'
taskId: string
truncated: boolean
}
export type TaskDetails = TaskDetailsBase & (
| {
accepted: true
reason: 'done'
evidence: [string, ...string[]]
}
| {
accepted: false
reason: RunOutcome['reason']
evidence: string[]
error: AgentError
}
)
type CreateTaskToolOptions = {
callModel: CallModel
countInputTokens: CountInputTokens
readOnlyTools: Tool[]
afterToolCall: AfterToolCall
maxTurns?: number
maxTasks?: number
onTaskEvent?(event: TaskLifecycleEvent): void
}
export function extractEvidence(report: string): string[] {
return report
.split('\n')
.map((line) => line.trim())
.filter((line) =>
FILE_LINE_REFERENCE.test(line) ||
/^(?:command|grep) output:\s*\S/i.test(line),
)
.map((line) => line.slice(0, MAX_EVIDENCE_LINE_CHARS))
.slice(0, MAX_EVIDENCE_LINES)
}
export function boundTaskReport(
taskId: string,
report: string,
evidence: string[],
): { content: string; truncated: boolean } {
const prefix = `Unverified explorer ${taskId} report:\n`
if (prefix.length + report.length <= MAX_TASK_REPORT_CHARS) {
return {
content: prefix + report,
truncated: false,
}
}
const evidenceBlock = evidence.join('\n')
const markerReserve = 200
const suffix = `\n\nEvidence retained:\n${evidenceBlock}`
const headLength = Math.max(
0,
MAX_TASK_REPORT_CHARS -
prefix.length - suffix.length - markerReserve,
)
const omitted = report.length - headLength
const marker =
`\n\n[task report truncated: ${omitted} characters omitted]`
if (marker.length > markerReserve) {
throw new Error('task truncation marker exceeded reserve')
}
return {
content:
prefix + report.slice(0, headLength) + marker + suffix,
truncated: true,
}
}
function failureText(
taskId: string,
result: Awaited<ReturnType<typeof runAgent>>,
report: string,
evidence: string[],
): string {
if (result.reason === 'aborted') {
return `Explorer ${taskId} was aborted.`
}
if (result.reason !== 'done') {
const detail = result.reason === 'failed'
? `${result.error.code}: ${result.error.message}`
: 'the bounded investigation did not finish'
return `Explorer ${taskId} stopped with ${result.reason}: ${detail}`
}
if (report === '') {
return `Explorer ${taskId} returned no final text.`
}
if (evidence.length === 0) {
return `Explorer ${taskId} returned an unverified report. ` +
'Retry with file:line or labeled command output evidence.'
}
throw new Error('failureText called for an accepted task')
}
function failureError(
result: Awaited<ReturnType<typeof runAgent>>,
report: string,
evidence: string[],
): AgentError {
if (result.reason === 'failed') return result.error
if (result.reason === 'aborted') {
return { code: 'TASK_ABORTED', message: 'Explorer was cancelled' }
}
if (result.reason === 'no_progress') {
return { code: 'TASK_NO_PROGRESS', message: 'Explorer stopped after repeated tool failures' }
}
if (result.reason === 'max_turns') {
return { code: 'TASK_MAX_TURNS', message: 'Explorer reached its turn limit' }
}
if (report === '') {
return { code: 'TASK_EMPTY_REPORT', message: 'Explorer returned no final text' }
}
if (evidence.length === 0) {
return { code: 'TASK_MISSING_EVIDENCE', message: 'Explorer report has no evidence' }
}
throw new Error('failureError called for an accepted task')
}
export function createTaskTool(
opts: CreateTaskToolOptions,
): Tool {
const maxTasks = opts.maxTasks ?? DEFAULT_MAX_TASKS_PER_RUN
if (!Number.isInteger(maxTasks) || maxTasks < 1) {
throw new Error('maxTasks must be a positive integer')
}
let startedTasks = 0
let nextTaskId = 1
return {
definition: {
name: 'task',
description: `Delegate one focused repository investigation to a
read-only explorer. Before acting on its report, independently verify the
cited file:line or command-output evidence with Read or Grep. At most two
explorer tasks can start in one parent run. The prompt must include the
objective, scope, known facts, required evidence, and non-goals.`,
input_schema: {
type: 'object',
properties: {
description: { type: 'string' },
prompt: {
type: 'string',
description:
'Self-contained objective, scope, known facts, evidence needed, and non-goals.',
},
},
required: ['description', 'prompt'],
additionalProperties: false,
},
},
prepare(input) {
if (!isRecord(input)) {
throw new Error('task input must be an object')
}
const description = requiredString(input, 'description')
const prompt = requiredString(input, 'prompt')
return {
execute: async (env, signal) => {
if (startedTasks >= maxTasks) {
return {
isError: true,
error: {
code: 'TASK_LIMIT_REACHED',
message: `This parent run already started ${maxTasks} explorer tasks.`,
},
content:
`Task limit reached: this parent run already started ` +
`${maxTasks} explorer tasks. Continue with existing ` +
`evidence or investigate directly.`,
}
}
startedTasks += 1
const taskId = `task-${nextTaskId++}`
opts.onTaskEvent?.({
type: 'task_start',
taskId,
description,
})
const result = await runAgent({
messages: [{ role: 'user', content: prompt }],
rootTask: prompt,
system: EXPLORER_SYSTEM,
callModel: opts.callModel,
countInputTokens: opts.countInputTokens,
tools: opts.readOnlyTools,
env,
signal,
afterToolCall: opts.afterToolCall,
maxTurns: opts.maxTurns ?? 6,
onEvent: (event) => {
opts.onTaskEvent?.({
type: 'task_child_event',
taskId,
event,
})
},
// 短命 explorer 使用截断 + turn budget,不传 compaction。
})
const report = assistantText(result.messages)
const evidence = extractEvidence(report)
const acceptedEvidence = evidence.length > 0
? evidence as [string, ...string[]]
: undefined
const accepted = result.reason === 'done' &&
report !== '' && acceptedEvidence !== undefined
const bounded = accepted
? boundTaskReport(taskId, report, evidence)
: { content: '', truncated: false }
const details: TaskDetails = accepted
? {
kind: 'task',
taskId,
reason: 'done',
accepted: true,
evidence: acceptedEvidence!,
truncated: bounded.truncated,
}
: {
kind: 'task',
taskId,
reason: result.reason,
accepted: false,
evidence,
truncated: false,
error: failureError(result, report, evidence),
}
opts.onTaskEvent?.({
type: 'task_end',
taskId,
reason: result.reason,
accepted,
evidenceCount: evidence.length,
truncated: bounded.truncated,
usageDelta: result.usageDelta,
})
return accepted
? {
isError: false,
content: bounded.content,
details,
usageDelta: result.usageDelta,
}
: {
isError: true,
error: failureError(result, report, evidence),
content: failureText(taskId, result, report, evidence),
details,
usageDelta: result.usageDelta,
}
},
}
},
}
}
abort 时,Task 会返回一个带 usageDelta 和结构化错误的结果,而不是先调用 throwIfAborted() 抛异常。这样父 loop 能按顺序做三件事:
- 把已完成的 child usage 汇总上来。
- 提交一个配对完整的
tool_result。 - 在下一轮开头发现同一个 signal 已经取消,以
aborted状态结束。
外部文件和命令已经产生的副作用,仍然不会回滚。
max_turns、no_progress 和 failed 这三种情况,即使已经找到了部分 file:line,也仍然返回错误,不把部分报告交给 parent 用。理由是:
- 钱必须照实入账。
- 但没做完的调查,不能冒充做完的交接。
details 可以给终端看诊断。模型如果还需要这些线索,有两条路:在剩余的 Task 额度里收窄范围重试,或者由 parent 自己调查。
接着改 src/cli.ts:恢复第 13 章的 /cost 分支,并给 child 事件加上 task id。下面只列出新增的 renderer(把事件画到终端上的函数)。它不会把 child event 原样塞进 parent 的 renderer:
import { truncateToolCallResult } from './context.js'
import type { TaskLifecycleEvent } from './task-tool.js'
function renderTaskEvent(event: TaskLifecycleEvent): void {
if (event.type === 'task_start') {
console.log(`\ntask[${event.taskId}]> ${event.description}`)
return
}
if (event.type === 'task_end') {
console.log(
`\ntask[${event.taskId}]> ${event.reason}; ` +
`${event.evidenceCount} evidence; ` +
`${event.usageDelta.inputTokens} in / ` +
`${event.usageDelta.outputTokens} out`,
)
return
}
const child = event.event
if (child.type === 'text_delta') {
process.stdout.write(`[${event.taskId}] ${child.text}`)
} else if (child.type === 'tool_start') {
console.log(
`\ntask[${event.taskId}] tool_use> ` +
`${child.name}: ${JSON.stringify(child.input)}`,
)
} else if (child.type === 'tool_end') {
console.log(
`task[${event.taskId}] tool_result> ` +
child.result.content,
)
}
}
const readOnlyTools = createReadOnlyTools(tools)
// 每个普通 prompt 内、调用 runAgent 前重新创建:
const taskTool = createTaskTool({
callModel,
countInputTokens: countInputTokensAnthropic,
readOnlyTools,
afterToolCall: truncateToolCallResult,
maxTurns: 6,
maxTasks: 2,
onTaskEvent: renderTaskEvent,
})
const parentTools = [
...tools,
todoWriteTool,
...planTools,
taskTool,
]
const result = await runAgent({
// 其余参数不变
tools: parentTools,
})
第 15 章把 Task Tool 建在 REPL 外面。本章必须把工厂移到每个普通 prompt 里面。这样计数器才是每个 run 一份,而不是整个 CLI 进程共用一份。
只有真正启动的 child 才占额度。参数不合法时,仍由 prepare 交给第 08 章的错误处理,额度不变。
模型请求、工具事件和 run_end 都带 task[task-N] 标签。如果觉得 child 的 text delta 太吵,可以不显示。但不能把它当成 parent 的文本,不带标签混着输出。
完整 trace、跨 task 查询和长期存储,本章明确不做。
自动化测试与故障注入
沿用第 15 章的 no_progress 批次配对测试,并检查 TASK_NO_PROGRESS 这几点:
- 保留了 child 的完整 usage。
accepted: false。- 保留了原始停止原因。
- 没有落进“空报告”或“缺证据”的分支。
另外,parent 的 Plan mode 不传给 child。child 那张固定的只读工具表里,也没有切换模式的工具。
先在 src/agent.test.ts 加一条最小的账本测试。一个 fake Tool 返回嵌套 usage,parent 的两次模型调用各有自己的 usage。最后每个价格桶都只加一次:
test('rolls nested tool usage into the parent RunResult exactly once', async () => {
const childUsage = emptyUsage()
childUsage.inputTokens = 100
childUsage.outputTokens = 20
childUsage.cacheReadInputTokens = 300
childUsage.cacheCreationInputTokens = 400
childUsage.cacheCreation5mInputTokens = 250
childUsage.cacheCreation1hInputTokens = 150
const nestedTool: Tool = {
definition: {
name: 'nested',
description: 'test nested usage',
input_schema: { type: 'object', properties: {} },
},
prepare: () => ({
execute: async () => ({
isError: false,
content: 'child report src/a.ts:1',
usageDelta: childUsage,
}),
}),
}
let calls = 0
const result = await runAgent({
messages: [{ role: 'user', content: 'delegate' }],
rootTask: 'delegate',
system: [{ type: 'text', text: 'test' }],
tools: [nestedTool],
env,
signal: new AbortController().signal,
afterToolCall: truncateToolCallResult,
countInputTokens: async () => 10,
callModel: async () => {
calls += 1
return {
content: calls === 1
? [{
type: 'tool_use', id: 'nested-1', name: 'nested', input: {},
}]
: [{ type: 'text', text: 'done' }],
stop_reason: calls === 1 ? 'tool_use' : 'end_turn',
usage: {
input_tokens: 10,
output_tokens: 2,
cache_read_input_tokens: 0,
cache_creation_input_tokens: 0,
cache_creation: {
ephemeral_5m_input_tokens: 0,
ephemeral_1h_input_tokens: 0,
},
},
}
},
})
assert.equal(result.usageDelta.inputTokens, 120)
assert.equal(result.usageDelta.outputTokens, 24)
assert.equal(result.usageDelta.cacheReadInputTokens, 300)
assert.equal(result.usageDelta.cacheCreationInputTokens, 400)
assert.equal(result.usageDelta.cacheCreation5mInputTokens, 250)
assert.equal(result.usageDelta.cacheCreation1hInputTokens, 150)
})
在 src/task-tool.test.ts 里,先直接守住证据检查和 handoff 长度上限:
- 空的 command 标签不算证据。
- 即使唯一一条引用在超长报告的末尾,最终 ToolResult 也不超过 12,000 字符。
import type { Tool } from './tools.js'
import {
boundTaskReport,
extractEvidence,
} from './task-tool.js'
test('requires non-empty evidence and bounds the complete handoff', () => {
assert.deepEqual(extractEvidence('command output:'), [])
assert.deepEqual(
extractEvidence('claim: src/cache.ts:42'),
['claim: src/cache.ts:42'],
)
const report = `${'x'.repeat(13_000)}\nsrc/cache.ts:42`
const evidence = extractEvidence(report)
const bounded = boundTaskReport('task-1', report, evidence)
assert.equal(bounded.truncated, true)
assert.ok(bounded.content.length <= 12_000)
assert.match(bounded.content, /^Unverified explorer task-1 report:/)
assert.match(bounded.content, /task report truncated/)
assert.match(bounded.content, /src\/cache\.ts:42/)
const longEvidence = extractEvidence(
`command output: ${'y'.repeat(1_000)}`,
)
assert.equal(longEvidence[0]!.length, 240)
})
再让 parent 在一次响应里批量发出三个 Task。这条测试要说明:“模型可以批量请求”和“runtime 会并行启动”不是一回事。当前 loop 会依次执行前两个,第三个拿到限额错误。两个 child 和两次 parent 请求的 usage 各加一次:
test('starts at most two explorer tasks in one parent run', async () => {
let parentCalls = 0
let childCalls = 0
const callModel: CallModel = async (request) => {
const isParent = request.tools.some(
(tool) => tool.name === 'task',
)
if (!isParent) {
childCalls += 1
return {
content: [{
type: 'text',
text: `finding src/task-${childCalls}.ts:1`,
}],
stop_reason: 'end_turn',
usage: {
input_tokens: 100,
output_tokens: 5,
cache_read_input_tokens: 0,
cache_creation_input_tokens: 0,
cache_creation: {
ephemeral_5m_input_tokens: 0,
ephemeral_1h_input_tokens: 0,
},
},
}
}
parentCalls += 1
if (parentCalls === 1) {
return {
content: [1, 2, 3].map((number) => ({
type: 'tool_use' as const,
id: `parent-task-${number}`,
name: 'task',
input: {
description: `investigation ${number}`,
prompt:
`Find item ${number} in src; cite file:line; ` +
`do not modify files.`,
},
})),
stop_reason: 'tool_use',
usage,
}
}
return {
content: [{ type: 'text', text: 'done' }],
stop_reason: 'end_turn',
usage,
}
}
const taskTool = createTaskTool({
callModel,
countInputTokens: async () => 10,
readOnlyTools: [],
afterToolCall: truncateToolCallResult,
maxTasks: 2,
})
const result = await runAgent({
messages: [{ role: 'user', content: 'Investigate three items.' }],
rootTask: 'Investigate three items.',
system: [{ type: 'text', text: 'parent' }],
callModel,
countInputTokens: async () => 10,
tools: [taskTool],
env: {} as ExecutionEnv,
signal: new AbortController().signal,
afterToolCall: truncateToolCallResult,
})
assert.equal(result.reason, 'done')
assert.equal(parentCalls, 2)
assert.equal(childCalls, 2)
assert.equal(result.usageDelta.inputTokens, 220)
assert.match(
JSON.stringify(result.messages),
/Task limit reached/,
)
})
完整的取消账本测试也要保留。过程如下:
- child 完成一次模型调用后,进入一个会阻塞的 Grep。
- fake env 在执行时触发同一个 controller。
- 随后它像真实的进程适配器一样,以 abort 拒绝。
parent 必须先收到 child usage,再以 aborted 结束。已经提交的 Task tool use 和 result 仍要成对:
test('rolls up child usage before parent settles aborted', async () => {
const controller = new AbortController()
const grepTool: Tool = {
definition: {
name: 'grep',
description: 'blocking grep for cancellation test',
input_schema: { type: 'object', properties: {} },
},
prepare: () => ({
execute: async (env, signal) =>
await env.execFile('grep', ['needle', '.'], signal)
.then((result) => ({
isError: false,
content: result.stdout,
})),
}),
}
const env = {
execFile: async (
_file: string,
_args: string[],
signal: AbortSignal,
) => await new Promise<never>((_resolve, reject) => {
signal.addEventListener(
'abort',
() => reject(signal.reason),
{ once: true },
)
controller.abort(new Error('cancel task'))
}),
} as ExecutionEnv
let parentCalls = 0
const callModel: CallModel = async (request) => {
if (request.tools.some((tool) => tool.name === 'grep')) {
return {
content: [{
type: 'tool_use',
id: 'child-grep',
name: 'grep',
input: {},
}],
stop_reason: 'tool_use',
usage: {
input_tokens: 100,
output_tokens: 5,
cache_read_input_tokens: 0,
cache_creation_input_tokens: 0,
cache_creation: {
ephemeral_5m_input_tokens: 0,
ephemeral_1h_input_tokens: 0,
},
},
}
}
parentCalls += 1
return {
content: [{
type: 'tool_use',
id: 'parent-task',
name: 'task',
input: {
description: 'find needle',
prompt: 'Find the needle.',
},
}],
stop_reason: 'tool_use',
usage,
}
}
const taskTool = createTaskTool({
callModel,
countInputTokens: async () => 10,
readOnlyTools: [grepTool],
afterToolCall: truncateToolCallResult,
})
const result = await runAgent({
messages: [{ role: 'user', content: 'Investigate.' }],
rootTask: 'Investigate.',
system: [{ type: 'text', text: 'parent' }],
callModel,
countInputTokens: async () => 10,
tools: [taskTool],
env,
signal: controller.signal,
afterToolCall: truncateToolCallResult,
})
assert.equal(result.reason, 'aborted')
assert.equal(parentCalls, 1)
assert.equal(result.usageDelta.inputTokens, 110)
const transcript = JSON.stringify(result.messages)
assert.match(transcript, /"id":"parent-task"/)
assert.match(transcript, /"tool_use_id":"parent-task"/)
})
最后,用表格测试补齐 Task 的其余后置条件:
done + 非空 + src/file.ts:42:success,usageDelta存在。done + 空文本:isError。done + 无引用的流畅结论:isError。max_turns/no_progress/failed:isError、结构化 error 与usageDelta都存在。- 每个
task_child_event、task_end都带同一个 task id。 - 低阈值 compaction 中,旧的
UNVERIFIED_TASK_CLAIM可以退出确定性 facts;parent 随后 Read/Grep 得到的VERIFIED_PARENT_EVIDENCE必须保留。
真实取消要用一个放在 PATH 里的慢 grep shim(一个冒充真命令的小脚本):
#!/usr/bin/env bash
set -euo pipefail
: "${BYOAA_TEST_PID_FILE:?}"
sleep 60 &
child_pid=$!
printf '%s %s\n' "$$" "$child_pid" > "$BYOAA_TEST_PID_FILE"
wait "$child_pid"
chmod +x fixtures/slow-bin/grep
BYOAA_TEST_PID_FILE=/tmp/byoaa-task-pids \
PATH="$PWD/fixtures/slow-bin:$PATH" npm run dev
# 让 parent 派 explorer grep;看到 task[task-1] tool_use 后按 Ctrl+C
read shell_pid child_pid < /tmp/byoaa-task-pids
kill -0 "$shell_pid" 2>/dev/null && echo 'orphan shell'
kill -0 "$child_pid" 2>/dev/null && echo 'orphan child'
通过条件:
- 两次
kill -0都失败。 - parent 以
aborted结束。 - 重启后 Session 可以继续。
/cost等于主请求、主 compaction 和 child usage 按桶相加的和。
测试结束后手动清理 /tmp/byoaa-task-pids。不要把这个临时文件写进项目状态。
Part 4 的真实仓库验收,用一个“先调查、再修改”的任务。步骤如下:
- parent 先把调查项标成
in_progress。 - parent 派 explorer 去找 compaction 的触发点、cut 的选择逻辑和相关测试。
- Task 报告必须给出 file:line。
- parent 必须自己再 Read/Grep 这些引用,之后才允许完成 Todo、写文件。
- 保存 parent 的 JSONL(每行一条 JSON 的日志)。确认 child 中间的 tool pair 不在主 messages 里,而 Task 报告和复核调用在。
- 触发低阈值 compaction。旧的 Task 陈述可以消失,但复核证据和当前 Todo 必须保留。
- 把 API usage 的原始字段和
/cost按桶逐一对账。
再用父子两层真实 loop,验证新的结束路径和取消时的账本:
import assert from 'node:assert/strict'
import test from 'node:test'
import { runAgent } from './agent.js'
import { createTaskTool, createReadOnlyTools } from './task-tool.js'
import type { ExecutionEnv } from './env.js'
import type { Tool, ToolResult } from './tools.js'
import type { ModelResponse } from './model.js'
const usage = {
input_tokens: 7, output_tokens: 2,
cache_read_input_tokens: 0, cache_creation_input_tokens: 0,
cache_creation: { ephemeral_5m_input_tokens: 0, ephemeral_1h_input_tokens: 0 },
}
const call = (id: string, name: string, input: unknown = {}) => ({ type: 'tool_use' as const, id, name, input })
const response = (content: ModelResponse['content'], done = false): ModelResponse => ({
content, stop_reason: done ? 'end_turn' : 'tool_use', usage,
})
const identity = async (_context: unknown, result: Readonly<ToolResult>) => result
test('child no_progress is an error and its full usage reaches the parent once', async () => {
let childTurns = 0
let parentTurns = 0
const local: Tool[] = ['read_file', 'grep'].map((name) => ({
definition: { name, input_schema: { type: 'object', properties: {} } },
prepare: () => ({ execute: () => ({
isError: true, content: 'missing', error: { code: 'FIXTURE_MISSING', message: 'missing' },
}) }),
}))
const task = createTaskTool({
callModel: async () => response([call(`read-${++childTurns}`, 'read_file')]),
countInputTokens: async () => 1,
readOnlyTools: createReadOnlyTools(local),
afterToolCall: identity,
})
const result = await runAgent({
messages: [{ role: 'user', content: 'fixture' }], rootTask: 'fixture', system: [],
tools: [task], env: {} as ExecutionEnv, signal: new AbortController().signal,
countInputTokens: async () => 1, afterToolCall: identity,
callModel: async ({ messages }) => {
if (++parentTurns === 1) return response([call('task-1', 'task', { description: 'inspect', prompt: 'Find a.ts:1' })])
assert.match(JSON.stringify(messages.at(-1)), /no_progress/)
return response([{ type: 'text', text: 'Investigation incomplete.' }], true)
},
onEvent(event) {
if (event.type === 'tool_end') {
assert.equal(event.result.isError, true)
if (event.result.isError) assert.equal(event.result.error.code, 'TASK_NO_PROGRESS')
assert.equal(event.result.usageDelta?.inputTokens, 28)
}
},
})
assert.equal(childTurns, 4)
assert.equal(result.usageDelta.inputTokens, 42)
assert.equal(result.usageDelta.outputTokens, 12)
})
test('abort after execution retains nested usage even when the post hook is skipped', async () => {
const controller = new AbortController()
const nested = { inputTokens: 30, outputTokens: 4, cacheReadInputTokens: 0,
cacheCreationInputTokens: 0, cacheCreation5mInputTokens: 0, cacheCreation1hInputTokens: 0 }
const tool: Tool = {
definition: { name: 'nested', input_schema: { type: 'object', properties: {} } },
prepare: () => ({ execute: () => {
controller.abort()
return { content: 'partial', isError: false, usageDelta: nested }
} }),
}
const result = await runAgent({
messages: [{ role: 'user', content: 'fixture' }], rootTask: 'fixture', system: [],
env: {} as ExecutionEnv, signal: controller.signal, tools: [tool],
countInputTokens: async () => 1,
callModel: async () => response([call('nested', 'nested')]),
afterToolCall: async () => { throw new Error('must not run after abort') },
})
assert.equal(result.reason, 'aborted')
assert.equal(result.usageDelta.inputTokens, 37)
})
已验证的边界
- D5 parent 报 2,603,explorer 实烧 26,639,漏账接近九成。
ToolResult.usageDelta上卷;outer RunResult 与 Session 各只 merge 一次。 - explorer 把 compaction 错说在 README 与 node_modules,parent 无从复查。success 至少要求可定位证据;父 transcript 必须出现独立 Read/Grep 复核。
下一部分先按需加载 Skills,再把 stdio MCP 工具接进同一张 Tool Map。两者都沿用现有的 runAgent。