@thincoder/core 0.11.4 → 0.12.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (199) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/abort-provenance.mjs +23 -0
  3. package/advisor/citations.mjs +5 -1
  4. package/advisor/compaction.mjs +13 -10
  5. package/advisor/history.mjs +6 -1
  6. package/advisor/loop.mjs +35 -10
  7. package/advisor/messages.mjs +31 -43
  8. package/advisor/project-context.mjs +49 -45
  9. package/advisor/run.mjs +82 -26
  10. package/advisor.mjs +40 -11
  11. package/agent/assemble.mjs +5 -5
  12. package/agent/chat-call.mjs +21 -1
  13. package/agent/completion.mjs +1 -20
  14. package/agent/dispatch-gates.mjs +8 -3
  15. package/agent/dispatch-run.mjs +131 -20
  16. package/agent/dispatch.mjs +23 -22
  17. package/agent/family-tools.mjs +4 -7
  18. package/agent/goal-judge.mjs +99 -0
  19. package/agent/goal-state.mjs +96 -0
  20. package/agent/helpers.mjs +13 -4
  21. package/agent/offload.mjs +1 -1
  22. package/agent/planning-graph-guardrail.mjs +224 -0
  23. package/agent/planning-prompt.mjs +179 -0
  24. package/agent/planning-step.mjs +460 -173
  25. package/agent/post-turn.mjs +23 -33
  26. package/agent/record-results.mjs +8 -5
  27. package/agent/run-stages.mjs +22 -41
  28. package/agent/run-start.mjs +26 -19
  29. package/agent/setup-reminders.mjs +16 -14
  30. package/agent/setup.mjs +3 -2
  31. package/agent/spawn-child.mjs +17 -4
  32. package/agent/suspension.mjs +42 -21
  33. package/agent/task-lifecycle.mjs +165 -52
  34. package/agent/timers.mjs +9 -1
  35. package/agent/turn-loop.mjs +160 -69
  36. package/agent/turn-projection.mjs +26 -15
  37. package/agent/turn-task-state.mjs +4 -4
  38. package/agent/write-gate-ledger.mjs +1 -1
  39. package/agent/write-gate.mjs +14 -11
  40. package/agent-tools/advisor-async.mjs +2 -0
  41. package/agent-tools/advisor-launch.mjs +27 -13
  42. package/agent-tools/advisor-settle.mjs +19 -18
  43. package/agent-tools/advisor.mjs +90 -13
  44. package/agent-tools/bash-async.mjs +3 -3
  45. package/agent-tools/batch-ledger-bind.mjs +8 -5
  46. package/agent-tools/batch-read.mjs +42 -0
  47. package/agent-tools/batch-record-write.mjs +20 -12
  48. package/agent-tools/batch-segment-vocab.mjs +6 -4
  49. package/agent-tools/batch-skeleton.mjs +43 -12
  50. package/agent-tools/consult.mjs +5 -1
  51. package/agent-tools/context.mjs +5 -4
  52. package/agent-tools/design-slots.mjs +7 -4
  53. package/agent-tools/design-token.mjs +3 -2
  54. package/agent-tools/doc-graph.mjs +257 -95
  55. package/agent-tools/escalate-async.mjs +4 -1
  56. package/agent-tools/goal.mjs +28 -95
  57. package/agent-tools/plan.mjs +1 -1
  58. package/agent-tools/review-facts.mjs +56 -7
  59. package/agent-tools/settings.mjs +35 -1
  60. package/agent-tools/ssh-transport.mjs +23 -22
  61. package/agent-tools/step.mjs +24 -4
  62. package/agent-tools/subagent-actions.mjs +6 -2
  63. package/agent-tools/subagent-async.mjs +4 -2
  64. package/agent-tools/subagent.mjs +1 -1
  65. package/agent-tools/task.mjs +73 -65
  66. package/agent-tools.mjs +3 -3
  67. package/agent.mjs +12 -3
  68. package/auto-think.mjs +16 -3
  69. package/browser/actions.mjs +5 -1
  70. package/browser/cdp.mjs +1 -1
  71. package/browser/pool.mjs +110 -17
  72. package/compaction-work-state.mjs +103 -13
  73. package/compress-form.mjs +29 -3
  74. package/config-defaults.mjs +27 -3
  75. package/config-io.mjs +3 -14
  76. package/config-normalize.mjs +24 -4
  77. package/config-presets.mjs +40 -26
  78. package/config-warn.mjs +30 -0
  79. package/config.mjs +139 -63
  80. package/context-degrade.mjs +4 -4
  81. package/context-push.mjs +20 -9
  82. package/context.mjs +65 -20
  83. package/doc-graph/anchors.mjs +39 -40
  84. package/doc-graph/clusters.mjs +49 -0
  85. package/doc-graph/code-parsers.mjs +494 -0
  86. package/doc-graph/context-pack.mjs +392 -0
  87. package/doc-graph/dir-signals.mjs +228 -0
  88. package/doc-graph/edges.mjs +231 -0
  89. package/doc-graph/format.mjs +70 -0
  90. package/doc-graph/gc-cmd.mjs +104 -0
  91. package/doc-graph/gc.mjs +112 -0
  92. package/doc-graph/glob-work-graph.mjs +307 -0
  93. package/doc-graph/golden-set.mjs +131 -0
  94. package/doc-graph/ls-work-graph.mjs +534 -0
  95. package/doc-graph/outline.mjs +377 -0
  96. package/doc-graph/output-annotations.mjs +85 -0
  97. package/doc-graph/process-docs.mjs +68 -0
  98. package/doc-graph/read-work-graph.mjs +91 -0
  99. package/doc-graph/rebuild-cmd.mjs +75 -0
  100. package/doc-graph/resolvers.mjs +322 -0
  101. package/doc-graph/roots.mjs +86 -0
  102. package/doc-graph/schema.mjs +110 -0
  103. package/doc-graph/search-augment.mjs +418 -0
  104. package/doc-graph/store.mjs +231 -0
  105. package/doc-graph/target-resolve.mjs +352 -0
  106. package/doc-graph/walk.mjs +87 -0
  107. package/doc-graph.mjs +583 -707
  108. package/explore-distill.mjs +52 -17
  109. package/generate-title.mjs +7 -4
  110. package/ledger-close.mjs +6 -6
  111. package/ledger-cmd.mjs +3 -3
  112. package/ledger-consistency.mjs +8 -6
  113. package/ledger-db.mjs +45 -10
  114. package/ledger-migrate.mjs +25 -10
  115. package/ledger-read.mjs +1 -1
  116. package/ledger-write-ops.mjs +6 -6
  117. package/ledger.mjs +2 -2
  118. package/model-context.mjs +54 -18
  119. package/model-specs.mjs +86 -67
  120. package/package.json +1 -1
  121. package/prompt-overlays.mjs +3 -3
  122. package/prompts/advisor-round1.md +6 -5
  123. package/prompts/common.md +16 -6
  124. package/prompts/consult-base.md +2 -1
  125. package/prompts/discipline-engineering.md +1 -1
  126. package/prompts/discipline-normal.md +12 -8
  127. package/prompts/knowledge/doc-lookup.md +2 -2
  128. package/prompts/knowledge/normal-batch-discipline.md +2 -2
  129. package/prompts/knowledge/normal-delivery-collaboration.md +3 -3
  130. package/prompts/knowledge/tool-advisor.md +2 -2
  131. package/prompts/knowledge/tool-apply-patch.md +1 -1
  132. package/prompts/knowledge/tool-bash.md +2 -2
  133. package/prompts/knowledge/tool-batch.md +4 -4
  134. package/prompts/knowledge/tool-glob.md +9 -2
  135. package/prompts/knowledge/tool-goal.md +9 -6
  136. package/prompts/knowledge/tool-grep.md +7 -2
  137. package/prompts/knowledge/tool-ls.md +11 -5
  138. package/prompts/knowledge/tool-lsp.md +1 -1
  139. package/prompts/knowledge/tool-operations.md +3 -2
  140. package/prompts/knowledge/tool-plan.md +1 -1
  141. package/prompts/knowledge/tool-read.md +7 -6
  142. package/prompts/knowledge/tool-repo-graph-read.md +12 -0
  143. package/prompts/knowledge/tool-repo-graph.md +12 -0
  144. package/prompts/knowledge/tool-step.md +1 -1
  145. package/prompts/knowledge/tool-subagent.md +2 -2
  146. package/prompts/knowledge/tool-task.md +10 -9
  147. package/prompts/knowledge/tool-tree.md +7 -1
  148. package/prompts/persona-eng-coder.md +1 -1
  149. package/prompts/persona-eng-designer.md +1 -1
  150. package/prompts/persona-engineering.md +2 -1
  151. package/prompts/persona-explore.md +1 -1
  152. package/prompts/persona-normal.md +7 -6
  153. package/prompts/persona-plan.md +2 -2
  154. package/prompts/planning-next-moves.md +7 -8
  155. package/provider/anthropic.mjs +53 -51
  156. package/provider/core.mjs +85 -34
  157. package/provider/errors.mjs +33 -10
  158. package/provider/google.mjs +244 -37
  159. package/provider/list-models.mjs +28 -14
  160. package/provider/responses-request.mjs +15 -9
  161. package/provider/responses.mjs +10 -8
  162. package/provider/sse.mjs +3 -6
  163. package/proxy-transport.mjs +228 -119
  164. package/rules-file.mjs +79 -0
  165. package/rules.mjs +13 -51
  166. package/session-lifecycle.mjs +32 -20
  167. package/team-ledger.mjs +7 -7
  168. package/think-off.mjs +37 -18
  169. package/token-window.mjs +48 -31
  170. package/tool-args.mjs +8 -8
  171. package/tool-docs/bash.md +1 -1
  172. package/tool-docs/glob.md +3 -1
  173. package/tool-docs/goal.md +2 -2
  174. package/tool-docs/grep.md +3 -1
  175. package/tool-docs/ls.md +7 -1
  176. package/tool-docs/read.md +1 -1
  177. package/tool-docs/repo_graph-read.md +3 -0
  178. package/tool-docs/repo_graph.md +3 -0
  179. package/tool-docs/tree.md +1 -1
  180. package/tools/bash.mjs +53 -8
  181. package/tools/browser.mjs +4 -4
  182. package/tools/file.mjs +34 -7
  183. package/tools/glob-dialect.mjs +57 -7
  184. package/tools/index.mjs +3 -7
  185. package/tools/patch.mjs +8 -7
  186. package/tools/process-doc-mark.mjs +13 -0
  187. package/tools/search.mjs +152 -37
  188. package/tools/shared.mjs +6 -0
  189. package/tools/tree.mjs +211 -8
  190. package/window-policy.mjs +205 -126
  191. package/prompts/knowledge/tool-doc-graph-read.md +0 -20
  192. package/prompts/knowledge/tool-doc-graph.md +0 -49
  193. package/prompts/knowledge/tool-peek.md +0 -10
  194. package/prompts/knowledge/tool-repo-outline.md +0 -4
  195. package/tool-docs/doc_graph-read.md +0 -3
  196. package/tool-docs/doc_graph.md +0 -3
  197. package/tool-docs/peek.md +0 -3
  198. package/tool-docs/repo_outline.md +0 -3
  199. package/tools/peek.mjs +0 -447
@@ -7,11 +7,98 @@
7
7
  * ——零环。
8
8
  */
9
9
  import { logEvent, errText, headText } from "../log.mjs"
10
- import { offloadToolResult, FILE_MUTATORS } from "./helpers.mjs"
10
+ import { offloadToolResult, FILE_MUTATORS, toolTouchPaths } from "./helpers.mjs"
11
11
  import { runHooks } from "../hooks.mjs"
12
12
  import { snapshotForUndo } from "../undo-stack.mjs"
13
13
  import { PEER_WRITE_TOOLS, peerCollabNote, recordPeerWrites, markClaimNoted } from "../peer-domains.mjs"
14
14
  import { logToolError, noteExecutedMutation } from "./dispatch-gates.mjs"
15
+ import { AsyncLocalStorage } from "node:async_hooks"
16
+ import { isAbsolute, relative, resolve } from "node:path"
17
+
18
+ // 并发安全 console 捕获(AsyncLocalStorage + 引用计数 hook):并发工具各自持有独立 sink,
19
+ // 乱序完成绝不互踩或永久劫持全局 console.log/console.error;非工具上下文调用原样转发。
20
+ const consoleCaptureStore = new AsyncLocalStorage()
21
+ let consoleHookDepth = 0
22
+ let realConsoleLog = null
23
+ let realConsoleError = null
24
+
25
+ function acquireConsoleHook() {
26
+ if (consoleHookDepth === 0) {
27
+ realConsoleLog = console.log
28
+ realConsoleError = console.error
29
+ console.log = (...a) => {
30
+ const sink = consoleCaptureStore.getStore()
31
+ if (sink) sink.log(...a)
32
+ else realConsoleLog(...a)
33
+ }
34
+ console.error = (...a) => {
35
+ const sink = consoleCaptureStore.getStore()
36
+ if (sink) sink.error(...a)
37
+ else realConsoleError(...a)
38
+ }
39
+ }
40
+ consoleHookDepth += 1
41
+ }
42
+
43
+ function releaseConsoleHook() {
44
+ consoleHookDepth -= 1
45
+ if (consoleHookDepth <= 0) {
46
+ consoleHookDepth = 0
47
+ if (realConsoleLog) console.log = realConsoleLog
48
+ if (realConsoleError) console.error = realConsoleError
49
+ realConsoleLog = null
50
+ realConsoleError = null
51
+ }
52
+ }
53
+
54
+ const GRAPH_CODE_FILE_RE = /\.(?:m?js|cjs|jsx?|tsx?|py|go|rs|cs|java|kt|cpp|c|h|hpp|rb|php|swift|sh|ps1)$/i
55
+ const GRAPH_DOC_FILE_RE = /\.(?:md|markdown|txt)$/i
56
+ function normGraphRel(rawPath, cwd) {
57
+ const s = String(rawPath ?? "").trim()
58
+ if (!s) return ""
59
+ const rel = cwd && isAbsolute(s) ? relative(cwd, s) : s
60
+ return rel.replace(/\\/g, "/").replace(/^\.\//, "")
61
+ }
62
+
63
+ function recordSessionGraphRead(agent, args) {
64
+ const rawPath = String(args?.path ?? args?.filePath ?? "").trim()
65
+ if (!rawPath || !agent) return
66
+ const norm = normGraphRel(rawPath, agent.cwd)
67
+ if (!norm) return
68
+ const set = agent._graphFullReadFiles instanceof Set
69
+ ? agent._graphFullReadFiles
70
+ : (agent._graphFullReadFiles = new Set())
71
+ const isFullRead = args?.offset === undefined && args?.limit === undefined
72
+ if (GRAPH_DOC_FILE_RE.test(rawPath)) {
73
+ if (isFullRead) set.add(norm)
74
+ return
75
+ }
76
+ if (GRAPH_CODE_FILE_RE.test(rawPath) && isFullRead) set.add(norm)
77
+ }
78
+
79
+ async function computeEditGraphNote(agent, tool, args) {
80
+ if (!agent?.cwd) return null
81
+ const rawPaths = toolTouchPaths(tool, args)
82
+ const codePaths = rawPaths
83
+ .filter((p) => typeof p === "string" && GRAPH_CODE_FILE_RE.test(p))
84
+ .map((p) => normGraphRel(p, agent.cwd))
85
+ .filter(Boolean)
86
+ if (codePaths.length === 0) return null
87
+ try {
88
+ const readSet = agent._graphFullReadFiles instanceof Set ? agent._graphFullReadFiles : new Set()
89
+ const noted = agent._graphNotedPaths instanceof Set
90
+ ? agent._graphNotedPaths
91
+ : (agent._graphNotedPaths = new Set())
92
+ const { getEditGraphNote } = await import("../doc-graph.mjs")
93
+ const note = await getEditGraphNote(agent.cwd, codePaths, readSet, noted)
94
+ if (note && Array.isArray(note.notedKeys)) {
95
+ for (const k of note.notedKeys) noted.add(k)
96
+ }
97
+ return note?.text ?? null
98
+ } catch {
99
+ return null
100
+ }
101
+ }
15
102
 
16
103
  /** console 回显预算(AGENT-LOOP.md §5.3 结果 · #863):采集端 cap = 与 helpers.mjs `TOOL_RESULT_OFFLOAD_LIMIT`
17
104
  * 同值(65536 字符)——累计到限停收(超出丢弃);发生丢弃 ⇒ 回显段尾恰一行截断标记(逐字——两路径同款)。 */
@@ -75,20 +162,25 @@ export async function runPreparedItem(item, agent, depth, signal, callbacks) {
75
162
  const routed = await callbacks.toolRouter(item.toolCall.name, item.args)
76
163
  if (routed?.handled) {
77
164
  const routedOk = !String(routed.result).startsWith("Error:")
78
- const routedResult = peerNote && routedOk ? `${routed.result}\n${peerNote.text}` : routed.result
165
+ if (routedOk && toolName === "read") recordSessionGraphRead(agent, item.args)
166
+ const routedGraphNote = routedOk && FILE_MUTATORS.has(toolName)
167
+ ? await computeEditGraphNote(agent, item.tool, item.args)
168
+ : null
169
+ const routedNotes = [peerNote && routedOk ? peerNote.text : null, routedGraphNote].filter(Boolean)
170
+ const routedResult = routedNotes.length > 0 ? `${routed.result}\n${routedNotes.join("\n")}` : routed.result
79
171
  if (peerNote && routedOk) markClaimNoted(agent, peerNote.keys) // 提示已附加 ⇒ 落去重标记
80
172
  if (isPeerWriteTool && routedOk) recordPeerWrites(agent, item.tool, item.args)
81
173
  // fix A:routed 写成功(客户端执行)同样执行期即刻记账(唯一记账点)
82
174
  if (routedOk && FILE_MUTATORS.has(toolName)) noteExecutedMutation(agent, item.tool, item.args)
83
175
  callbacks.onToolResult?.(item.toolCall.name, routedResult, item.toolCall.id)
84
176
  logEvent("tool:done", { tool: toolName, ms: Date.now() - toolT0, head: headText(routedResult, 200), child: agent?._logId })
85
- return { ...item, result: routedResult, ok: true }
177
+ return { ...item, result: routedResult, ok: routedOk }
86
178
  }
87
179
  }
88
- const origConsoleLog = console.log
89
- const origConsoleErr = console.error
90
- console.log = (...a) => capturedPush(a.map(String).join(" "))
91
- console.error = (...a) => capturedPush("[err] " + a.map(String).join(" "))
180
+ const consoleSink = {
181
+ log: (...a) => capturedPush(a.map(String).join(" ")),
182
+ error: (...a) => capturedPush("[err] " + a.map(String).join(" ")),
183
+ }
92
184
  let rawResult
93
185
  // ctx 对象提升为变量(docs/cli/design/TUI.md §6.8):subagent 阻塞 execute 返回前在 ctx 上留
94
186
  // _subagentKey(relayPrefix 去尾)——runOne 在 execute 返回后读它作 onToolResult
@@ -108,33 +200,51 @@ export async function runPreparedItem(item, agent, depth, signal, callbacks) {
108
200
  onSecretInput: callbacks.onSecretInput,
109
201
  onPermissionRequest: callbacks.onPermissionRequest,
110
202
  }
203
+ acquireConsoleHook()
111
204
  try {
112
205
  // SUBAGENT-OBSERVE-SEND D1(评审 #1):in-flight 当前工具记账——工具执行期间在
113
206
  // agent 上留 _inflightTools Set(子代理 observe 从 dispatch 状态读——卡在长工具
114
- // 调用时 history 无新回合、恰需此信号);finally 清除。批并行工具同入 Set(observe
115
- // 如实返回多个在跑工具)。主会话同样记账——无害(无人读)。
207
+ // 调用时 history 无新回合、恰需此信号);搭配 `_inflightToolCounts` 引用计数,
208
+ // 并发同名工具先完成者不误删仍在运行的同名项。
116
209
  const inflight = agent._inflightTools ?? (agent._inflightTools = new Set())
210
+ const inflightCounts = agent._inflightToolCounts ?? (agent._inflightToolCounts = new Map())
211
+ inflightCounts.set(toolName, (inflightCounts.get(toolName) ?? 0) + 1)
117
212
  inflight.add(toolName)
118
213
  try {
119
- rawResult = await item.tool.execute(item.args, toolCtx)
214
+ rawResult = await consoleCaptureStore.run(consoleSink, () => item.tool.execute(item.args, toolCtx))
120
215
  } finally {
121
- inflight.delete(toolName)
216
+ const nextCount = (inflightCounts.get(toolName) ?? 1) - 1
217
+ if (nextCount <= 0) {
218
+ inflightCounts.delete(toolName)
219
+ inflight.delete(toolName)
220
+ } else {
221
+ inflightCounts.set(toolName, nextCount)
222
+ }
122
223
  }
123
224
  } finally {
124
- console.log = origConsoleLog
125
- console.error = origConsoleErr
225
+ releaseConsoleHook()
126
226
  }
127
227
  if (rawResult === undefined) throw new Error(`Tool "${item.toolCall.name}" returned undefined — all tools must return a string value`)
128
228
  const raw = String(rawResult)
229
+ // bash / execute 带合法 filter 时返回纯匹配行(日志首行可能恰好以 "Error:" 开头),不误判为工具执行失败。
230
+ const isFilteredLineOutput = (toolName === "bash" || toolName === "execute")
231
+ && Boolean(item.args?.filter)
232
+ && !raw.startsWith("Error: filter regex invalid:")
233
+ const execOk = !raw.startsWith("Error:") || isFilteredLineOutput
129
234
  // 写成功(非 "Error:" 字符串结果)→ 足迹计入本回合集合(flush 在 finalizeAgentTurn)
130
- if (isPeerWriteTool && !raw.startsWith("Error:")) {
235
+ if (isPeerWriteTool && execOk) {
131
236
  recordPeerWrites(agent, item.tool, item.args)
132
237
  }
238
+ if (toolName === "read" && execOk) {
239
+ recordSessionGraphRead(agent, item.args)
240
+ }
133
241
  // fix A:FILE_MUTATORS 执行成功即刻记账(唯一记账点——取代 record-results 批后
134
242
  // 段 + agent.mjs 中断分支——不双计)——同批 launch 前的写在 launchSeq 之前落地 →
135
243
  // async advisor settle 不误判 stale(同批 launch 后写仍保守 stale——T-A2/T-24b9)。
136
- if (FILE_MUTATORS.has(toolName) && !raw.startsWith("Error:")) {
244
+ let editGraphNote = null
245
+ if (FILE_MUTATORS.has(toolName) && execOk) {
137
246
  noteExecutedMutation(agent, item.tool, item.args)
247
+ editGraphNote = await computeEditGraphNote(agent, item.tool, item.args)
138
248
  }
139
249
  // 2026-08-31 工具输出回显 ∥ #863:console 段 ∥ 结果本体拼接先于 offload——并入 64K 判定
140
250
  // (超限 ⇒ 落盘 + 预览);采集端发生过丢弃 ⇒ 段尾恰一行截断标记(逐字——错误路径同款)。
@@ -146,17 +256,18 @@ export async function runPreparedItem(item, agent, depth, signal, callbacks) {
146
256
  // channel); everything else offloads oversized text to disk. Flag-driven, not
147
257
  // name-driven (consult P3, 2026-08-30).
148
258
  const result = item.tool?.multimodal ? spliced : await offloadToolResult(spliced, item.toolCall.id)
149
- // R10 L3:冲突 / 认领软提示附在工具结果末尾(模型可见——不阻止写;提示附加成功才落去重标记)
150
- const notedOk = Boolean(peerNote) && !raw.startsWith("Error:")
259
+ // R10 L3 + Context Graph v2:冲突 / 认领与图谱未读关键上下文软提示附在工具结果末尾(模型可见、不阻断、每路径会话内去重)
260
+ const notedOk = Boolean(peerNote) && execOk
151
261
  if (notedOk) markClaimNoted(agent, peerNote.keys)
152
- const resultForModel = notedOk
153
- ? `${result}\n${peerNote.text}`
262
+ const softNotes = [notedOk ? peerNote.text : null, editGraphNote].filter(Boolean)
263
+ const resultForModel = softNotes.length > 0
264
+ ? `${result}\n${softNotes.join("\n")}`
154
265
  : result
155
266
  callbacks.onToolResult?.(item.toolCall.name, resultForModel, item.toolCall.id, toolCtx._subagentKey)
156
267
  // PostToolUse hooks: fire-and-forget (result not awaited on hook failure)
157
268
  runHooks("PostToolUse", { agent, toolName: item.toolCall.name, toolArgs: item.args, result: raw }).catch(() => {})
158
269
  logEvent("tool:done", { tool: toolName, ms: Date.now() - toolT0, head: headText(resultForModel, 200), child: agent?._logId })
159
- return { ...item, result: resultForModel, ok: true }
270
+ return { ...item, result: resultForModel, ok: execOk }
160
271
  } catch (error) {
161
272
  // Persist to ~/.thincoder/tool-errors/ for post-mortem; only pass message to the model (stack traces confuse LLMs and may leak paths)
162
273
  logToolError(item.toolCall.name, item.args, error)
@@ -41,27 +41,28 @@ export async function executeToolCalls(agent, toolByName, toolCalls, callbacks,
41
41
  // that REACH the permission stage are collected into one batch — a single merged
42
42
  // ask covers the whole toolCalls array (D-B1, "approve all / one by one /
43
43
  // deny"). Tools stopped by a pre-gate never join the batch (review #7).
44
- const prepared = []
45
- const permPending = [] // { toolCall, tool, args } — reached the permission stage
46
- for (const toolCall of toolCalls) {
44
+ const prepared = new Array(toolCalls.length)
45
+ const permPending = [] // { index, toolCall, tool, args } — reached the permission stage
46
+ for (let i = 0; i < toolCalls.length; i++) {
47
+ const toolCall = toolCalls[i]
47
48
  const tool = toolByName.get(toolCall.name)
48
49
  let args
49
50
  try {
50
51
  args = JSON.parse(toolCall.arguments || "{}")
51
52
  } catch {
52
53
  logToolError(toolCall.name, { arguments: toolCall.arguments }, new Error("Invalid JSON arguments"))
53
- prepared.push({ toolCall, tool: null, error: `Invalid tool arguments JSON: ${toolCall.arguments}` })
54
+ prepared[i] = { toolCall, tool: null, error: `Invalid tool arguments JSON: ${toolCall.arguments}` }
54
55
  continue
55
56
  }
56
57
 
57
58
  if (!tool) {
58
59
  logToolError(toolCall.name, {}, new Error(`Unknown tool: ${toolCall.name}`))
59
- prepared.push({ toolCall, tool: null, error: `Unknown tool: ${toolCall.name}` })
60
+ prepared[i] = { toolCall, tool: null, error: `Unknown tool: ${toolCall.name}` }
60
61
  continue
61
62
  }
62
63
 
63
64
  if (agent.planMode && !tool.readonly && !readonlyActionOf(tool, toolCall.name, args) && !controlActionOf(tool, toolCall.name, args)) {
64
- prepared.push({ toolCall, tool, denied: true, reason: "plan mode" })
65
+ prepared[i] = { toolCall, tool, denied: true, reason: "plan mode" }
65
66
  continue
66
67
  }
67
68
 
@@ -70,11 +71,11 @@ export async function executeToolCalls(agent, toolByName, toolCalls, callbacks,
70
71
  // must run (and be accepted) before the first write/edit/apply_patch/hashline_edit/insert_after/delete.
71
72
  if (agent._role === "eng-coder" && agent.config?.agent?.engineering
72
73
  && !agent._engDesignReviewed && FILE_MUTATORS.has(toolCall.name)) {
73
- prepared.push({
74
+ prepared[i] = {
74
75
  toolCall, tool, denied: true,
75
76
  reason: "engineering design gate",
76
77
  hint: "Call advisor with type='design' to review the design document before any file modification. If the review found issues, report them to the parent agent.",
77
- })
78
+ }
78
79
  continue
79
80
  }
80
81
 
@@ -120,11 +121,11 @@ export async function executeToolCalls(agent, toolByName, toolCalls, callbacks,
120
121
  const convNote = noteConv
121
122
  ? ` — this path fell through to product code (no code segment is declared: code paths are empty); declare project conventions in ${manifestFilePath(noteConv.root)} to adjust.`
122
123
  : ""
123
- prepared.push({
124
+ prepared[i] = {
124
125
  toolCall, tool, denied: true,
125
126
  reason: "engineering design gate",
126
127
  hint: `Engineering mode: write the design document first(location per your project's document conventions), then call advisor with type='design' to review it, and wait for user approval. Implementation is done by eng-coder subagents.${convNote}`,
127
- })
128
+ }
128
129
  continue
129
130
  }
130
131
  }
@@ -147,17 +148,17 @@ export async function executeToolCalls(agent, toolByName, toolCalls, callbacks,
147
148
  if (FILE_MUTATORS.has(toolCall.name)) {
148
149
  const crossBatch = batchRecordWriteConflict(agent, depth, absPaths)
149
150
  if (crossBatch) {
150
- prepared.push({ toolCall, tool, denied: true, reason: "cross-batch record write", hint: crossBatch.message })
151
+ prepared[i] = { toolCall, tool, denied: true, reason: "cross-batch record write", hint: crossBatch.message }
151
152
  continue
152
153
  }
153
154
  }
154
155
  const conflict = freezeWindowConflict(agent, absPaths)
155
156
  if (conflict) {
156
- prepared.push({
157
+ prepared[i] = {
157
158
  toolCall, tool, denied: true,
158
159
  reason: "d5 freeze window",
159
160
  hint: `write refused — design review #${conflict.id} is in flight over ${relative(agent.cwd, conflict.path)} (D5 freeze window). A write now would settle it stale — no token for a pass (the round is lost). Wait for the report, or cancel the review first (subagent action:'cancel' id:'${conflict.id}') and re-launch after the change.`,
160
- })
161
+ }
161
162
  continue
162
163
  }
163
164
  }
@@ -173,7 +174,7 @@ export async function executeToolCalls(agent, toolByName, toolCalls, callbacks,
173
174
  // 路径集与 `args.ledger` 由判据函数自己取(调形只传 tool + toolName + args)。
174
175
  const ledgerConflict = await ledgerBindWriteConflict(agent, depth, tool, toolCall.name, args)
175
176
  if (ledgerConflict) {
176
- prepared.push({ toolCall, tool, denied: true, reason: "ledger binding", hint: ledgerConflict.message })
177
+ prepared[i] = { toolCall, tool, denied: true, reason: "ledger binding", hint: ledgerConflict.message }
177
178
  continue
178
179
  }
179
180
 
@@ -189,15 +190,15 @@ export async function executeToolCalls(agent, toolByName, toolCalls, callbacks,
189
190
  // parent ask (human in the loop).
190
191
  if (tool.readonly || readonlyActionOf(tool, toolCall.name, args) || controlActionOf(tool, toolCall.name, args) || isSubagentConsumeDesignAction(toolCall.name, args) || agent.autoApprove || agent._engTaskAuthorized) {
191
192
  if (!(await runHooks("PreToolUse", { agent, toolName: toolCall.name, toolArgs: args }))) {
192
- prepared.push({ toolCall, tool, denied: true, reason: "blocked by PreToolUse hook" })
193
+ prepared[i] = { toolCall, tool, denied: true, reason: "blocked by PreToolUse hook" }
193
194
  continue
194
195
  }
195
196
  // Panel area abolished — all tools now stream inline via onToolOutput.
196
197
  callbacks.onToolCall?.(toolCall.name, args, toolCall.id)
197
- prepared.push({ toolCall, tool, args })
198
+ prepared[i] = { toolCall, tool, args }
198
199
  continue
199
200
  }
200
- permPending.push({ toolCall, tool, args })
201
+ permPending.push({ index: i, toolCall, tool, args })
201
202
  }
202
203
 
203
204
  // ---- Permission stage: one merged ask for the whole batch (D-B1) ----
@@ -236,22 +237,22 @@ export async function executeToolCalls(agent, toolByName, toolCalls, callbacks,
236
237
  })()
237
238
  } else allowed = false
238
239
  if (!allowed) {
239
- prepared.push({
240
+ prepared[p.index] = {
240
241
  toolCall: p.toolCall, tool: p.tool, denied: true,
241
242
  reason: (callbacks.onPermissionRequest || batchAllowed === false) ? "denied by user" : "no permission handler",
242
- })
243
+ }
243
244
  continue
244
245
  }
245
246
 
246
247
  // PreToolUse hooks: allow user scripts to gate tool execution
247
248
  if (!(await runHooks("PreToolUse", { agent, toolName: p.toolCall.name, toolArgs: p.args }))) {
248
- prepared.push({ toolCall: p.toolCall, tool: p.tool, denied: true, reason: "blocked by PreToolUse hook" })
249
+ prepared[p.index] = { toolCall: p.toolCall, tool: p.tool, denied: true, reason: "blocked by PreToolUse hook" }
249
250
  continue
250
251
  }
251
252
 
252
253
  // Panel area abolished — all tools now stream inline via onToolOutput.
253
254
  callbacks.onToolCall?.(p.toolCall.name, p.args, p.toolCall.id)
254
- prepared.push({ toolCall: p.toolCall, tool: p.tool, args: p.args })
255
+ prepared[p.index] = { toolCall: p.toolCall, tool: p.tool, args: p.args }
255
256
  }
256
257
  }
257
258
 
@@ -276,7 +277,7 @@ export async function executeToolCalls(agent, toolByName, toolCalls, callbacks,
276
277
  // escalate action keeps the retired escalate tool's serial placement (no
277
278
  // parallel flag): it flushes the batch and runs alone in call order (AGENT-LOOP-SUBAGENT.md §6.7 —
278
279
  // spawn stays parallel; status classifies as readonly and batch freely).
279
- if (item.tool && !item.tool.readonly
280
+ if (!item.error && !item.denied && item.tool && !item.tool.readonly
280
281
  && (!(item.tool.parallel || item.tool.isParallelAction?.(item.args)) || isSubagentEscalateAction(item.tool.name, item.args))) {
281
282
  await flush()
282
283
  results.push(await runPreparedItem(item, agent, depth, signal, callbacks))
@@ -151,10 +151,9 @@ export async function assembleFamilyTools({
151
151
  ? [decorate?.consultStart ?? withPool(consultStartTool), decorate?.consultStop ?? consultStopTool]
152
152
  : []
153
153
 
154
- // 文档工具面(`AGENT-LOOP-SUBAGENT.md` §6.60.1 · 需求 `docs/core/requirements/DOC-GRAPH.md` §4 AC-10):
155
- // **一处写、五处展开**——`doc_check` 本就只读(无写 action 可收窄)⇒ 本体直挂;`doc_graph` 挂只读变体
156
- // (三动作、无 `scan`:子代理段的台账是只读变体,扫由父侧做——D-DT1)。五段各写一遍字面就是五份会各自漂的
157
- // 单子(D-DT4);并成一段又会抹掉各段真实差异。depth-0 段不展开本组:那边挂的是全量 `docGraphTool` + `docCheckTool`。
154
+ // 文档与项目图谱工具面(`AGENT-LOOP-SUBAGENT.md` · 需求 `docs/core/requirements/REPO-GRAPH.md`):
155
+ // **一处写、五处展开**——`doc_check` 与 `repo_graph`(六动作全只读)同挂全部 depth>0 角色段;
156
+ // depth-0 段由下方直挂。
158
157
  const docTools = [docCheckTool, docGraphReadTool]
159
158
  // 同步阻塞子代理(sync=true)期间父代理被 await 阻塞无法响应 send,不挂载 notify_parent
160
159
  // (避免子代理白耗一轮发 ask 并污染 _childUpstream 触发幽灵唤醒);待裁项随最终报告同步返回。
@@ -173,9 +172,7 @@ export async function assembleFamilyTools({
173
172
  // 文档纪律机检(`DOC-DISCIPLINE.md` §3.20 条目 S):只读报告态——depth-0 主 agent 段挂本体;
174
173
  // 全部 depth>0 角色段由下方 `docTools` 展开供给(`AGENT-LOOP-SUBAGENT.md` §6.60)。
175
174
  docCheckTool,
176
- // 文档锚点图(`DOC-GRAPH.md` §2.5 · 需求 F1–F6):**两变体互斥装配**——本段(depth-0)挂全量四动作;
177
- // 全部 depth>0 角色段挂只读变体(三动作、无 `scan`,契约 = `DOC-GRAPH.md` §2.5.5,装配矩阵单源 =
178
- // `AGENT-LOOP-SUBAGENT.md` §6.60.2)。位置与 `docCheckTool` 同段(同一族:文档纪律面)。
175
+ // 项目知识图谱 `repo_graph`(`docs/core/design/REPO-GRAPH.md`):全只读五动作,depth-0 与全部子代理同享。
179
176
  docGraphTool,
180
177
  // 端差(decorate.settings——VSC depth-0 主 agent 面;缺省不追加):核默认形态里
181
178
  // settings 住**基础集**(`tools/index.mjs` `assembleBuiltinTools`),端侧自持清单
@@ -0,0 +1,99 @@
1
+ /**
2
+ * agent/goal-judge.mjs — goal mode 独立裁判
3
+ * 设计 = `docs/core/design/GOAL.md` §2;需求 = `docs/core/requirements/GOAL.md` §4。
4
+ * 裁判独立于被评模型:单独配置的模型,只看对话记录,不调工具。
5
+ */
6
+ import { flattenHistory } from "../context.mjs"
7
+
8
+ export const GOAL_JUDGE_TIMEOUT_MS = 30_000
9
+ export const GOAL_JUDGE_VERDICTS = Object.freeze(["not_yet", "met", "impossible"])
10
+
11
+ /** 裁判模型名:goalJudgeModel → subagentModel → null(= 会话模型)。 */
12
+ export function resolveJudgeModelName(agent) {
13
+ const cfg = agent.config?.agent ?? {}
14
+ return cfg.goalJudgeModel ?? cfg.subagentModel ?? null
15
+ }
16
+
17
+ /** 裁判 provider:与子代理同一套模型解析(`"provider:model"` / 裸模型名 / `default` 别名)。
18
+ * 单源 = `agent-tools/subagent-async.mjs` 的 `resolveChildProvider`——动态 import 避开 `agent → agent-tools` 静态环。 */
19
+ export async function resolveJudgeProvider(agent) {
20
+ const { resolveChildProvider } = await import("../agent-tools/subagent-async.mjs")
21
+ return resolveChildProvider(agent, resolveJudgeModelName(agent))
22
+ }
23
+
24
+ /** 最近对话记录(用户真实指示 + assistant 文本 + 工具调用名与结果摘要,截断到窗口内)。 */
25
+ function transcriptOf(agent, { maxChars = 12_000 } = {}) {
26
+ const flat = flattenHistory(agent.history)
27
+ const lines = []
28
+ for (const m of flat) {
29
+ if (m.role === "user") {
30
+ const raw = typeof m.content === "string"
31
+ ? m.content
32
+ : Array.isArray(m.content)
33
+ ? m.content.map((p) => (typeof p?.text === "string" ? p.text : "")).filter(Boolean).join("\n")
34
+ : ""
35
+ const text = raw.trim()
36
+ if (text && !/^\[System reminder:/i.test(text)) lines.push(`user: ${text.slice(0, 1000)}`)
37
+ } else if (m.role === "assistant") {
38
+ const text = typeof m.content === "string" ? m.content : ""
39
+ if (text) lines.push(`assistant: ${text.slice(0, 1500)}`)
40
+ for (const tc of m.tool_calls ?? []) {
41
+ const name = tc.function?.name ?? tc.name ?? "?"
42
+ const args = String(tc.function?.arguments ?? tc.arguments ?? "").slice(0, 200)
43
+ lines.push(`tool-call: ${name} ${args}`)
44
+ }
45
+ } else if (m.role === "tool") {
46
+ const text = typeof m.content === "string" ? m.content : ""
47
+ lines.push(`tool-result: ${text.slice(0, 400)}`)
48
+ }
49
+ }
50
+ const joined = lines.join("\n")
51
+ return joined.length > maxChars ? joined.slice(-maxChars) : joined
52
+ }
53
+
54
+ /** 判一次:`{ verdict, reason }`;失败抛错(调用方计数,不放行)。 */
55
+ export async function judgeGoal(agent, { signal } = {}) {
56
+ const goal = agent.goal
57
+ if (!goal) throw new Error("goal-judge: no goal")
58
+ const { chat } = await import("../provider/index.mjs")
59
+ const provider = await resolveJudgeProvider(agent)
60
+ const timeout = AbortSignal.timeout(GOAL_JUDGE_TIMEOUT_MS)
61
+ const sig = signal ? AbortSignal.any([signal, timeout]) : timeout
62
+ const res = await chat(provider, {
63
+ // 模型语义参数(2026-12-03 批,台账 #133):判官调用的会话设置(不再是 provider 条目属性)。
64
+ modelParams: agent.modelParams,
65
+ // 会话设置(模型窗口声明 ∥ 档位上限)——判官调用的窗口封顶与会话同源(2026-12-03 批)。
66
+ settings: agent.config,
67
+ messages: [{
68
+ role: "user",
69
+ content: `You are an independent goal judge. Decide whether this goal's condition holds, based only on the transcript below.
70
+
71
+ Goal condition (what counts as done):
72
+ ${goal.condition}
73
+
74
+ Transcript (most recent last):
75
+ ${transcriptOf(agent) || "(no activity recorded)"}
76
+
77
+ Answer with exactly one verdict line, then one sentence of reason:
78
+ VERDICT: not_yet | met | impossible
79
+
80
+ - met: the condition's check has actually run and passed, and the transcript shows it.
81
+ - impossible: the goal cannot be reached (missing permission, contradictory requirement, external blocker).
82
+ - not_yet: anything else, including "looks close" or "planned but not run".`,
83
+ }],
84
+ tools: [],
85
+ signal: sig,
86
+ logCtx: {
87
+ stage: "goal", kind: "goal-judge",
88
+ role: agent._role ?? null, depth: 0,
89
+ session: agent._sessionStart ?? null, cwd: agent.cwd,
90
+ traces: agent.config?.traces?.enabled !== false,
91
+ },
92
+ })
93
+ const text = String(res.content ?? "").trim()
94
+ const m = /VERDICT:\s*(not_yet|met|impossible)/i.exec(text)
95
+ if (!m) throw new Error(`goal-judge: unparseable verdict "${text.slice(0, 200)}"`)
96
+ const verdict = m[1].toLowerCase()
97
+ const reason = text.slice(m.index + m[0].length).replace(/^[\s:—-]+/, "").trim() || null
98
+ return { verdict, reason }
99
+ }
@@ -0,0 +1,96 @@
1
+ /**
2
+ * agent/goal-state.mjs — goal mode 状态机单源
3
+ * 设计 = `docs/core/design/GOAL.md` §1;需求 = `docs/core/requirements/GOAL.md` §3。
4
+ * `/goal` 命令与 `goal` 工具都调本档,不各写一份规则。
5
+ */
6
+
7
+ export const GOAL_CONDITION_MAX = 4000
8
+ export const GOAL_STATUSES = Object.freeze(["active", "paused", "complete", "blocked"])
9
+
10
+ /** 设目标(覆盖已有目标:先清再建,不保留旧字段)。条件即判据。 */
11
+ export function setGoal(agent, { condition, source = "user" } = {}) {
12
+ const text = String(condition ?? "").trim()
13
+ if (!text) throw new Error("goal: condition is required — write what counts as done")
14
+ if (text.length > GOAL_CONDITION_MAX) {
15
+ throw new Error(`goal: condition is ${text.length} chars, over the ${GOAL_CONDITION_MAX} limit`)
16
+ }
17
+ agent.goal = {
18
+ condition: text,
19
+ status: "active",
20
+ source,
21
+ startedAt: Date.now(),
22
+ turnsEvaluated: 0,
23
+ tokensSpent: 0,
24
+ lastVerdict: null,
25
+ lastReason: null,
26
+ judgeFailures: 0,
27
+ noProgressTurns: 0,
28
+ }
29
+ return agent.goal
30
+ }
31
+
32
+ /** 暂停:只从 active。 */
33
+ export function pauseGoal(agent, reason = null) {
34
+ if (agent.goal?.status !== "active") {
35
+ throw new Error(`goal: cannot pause (current: ${agent.goal?.status ?? "none"})`)
36
+ }
37
+ agent.goal.status = "paused"
38
+ if (reason) agent.goal.lastReason = reason
39
+ return agent.goal
40
+ }
41
+
42
+ /** 恢复:只从 paused;重置计时 / 轮数 / token 基线。 */
43
+ export function resumeGoal(agent) {
44
+ if (agent.goal?.status !== "paused") {
45
+ throw new Error(`goal: cannot resume (current: ${agent.goal?.status ?? "none"})`)
46
+ }
47
+ agent.goal.status = "active"
48
+ agent.goal.startedAt = Date.now()
49
+ agent.goal.turnsEvaluated = 0
50
+ agent.goal.tokensSpent = 0
51
+ agent.goal.judgeFailures = 0
52
+ agent.goal.noProgressTurns = 0
53
+ return agent.goal
54
+ }
55
+
56
+ /** 清除:任意状态。 */
57
+ export function clearGoal(agent) {
58
+ agent.goal = null
59
+ }
60
+
61
+ /** 状态词(无目标 ⇒ null)。 */
62
+ export function goalStatusOf(agent) {
63
+ return agent.goal?.status ?? null
64
+ }
65
+
66
+ /** 裁判判决落账(单源——退出点钩子与工具面共用)。成功落账即清零连续失败计数。 */
67
+ export function recordVerdict(agent, { verdict, reason }) {
68
+ if (!agent.goal) return null
69
+ agent.goal.lastVerdict = verdict
70
+ agent.goal.lastReason = reason ?? null
71
+ agent.goal.turnsEvaluated = (agent.goal.turnsEvaluated ?? 0) + 1
72
+ agent.goal.judgeFailures = 0
73
+ if (verdict === "not_yet") agent.goal.noProgressTurns = (agent.goal.noProgressTurns ?? 0) + 1
74
+ else agent.goal.noProgressTurns = 0
75
+ if (verdict === "met") agent.goal.status = "complete"
76
+ else if (verdict === "impossible") agent.goal.status = "blocked"
77
+ return agent.goal
78
+ }
79
+
80
+ /** 裁判失败计数(不放行:达上限 ⇒ paused)。 */
81
+ export function recordJudgeFailure(agent, { limit = 3, reason = null } = {}) {
82
+ if (!agent.goal) return null
83
+ agent.goal.judgeFailures = (agent.goal.judgeFailures ?? 0) + 1
84
+ if (agent.goal.judgeFailures >= limit) {
85
+ agent.goal.status = "paused"
86
+ agent.goal.lastReason = reason ?? `judge unavailable ${agent.goal.judgeFailures} times`
87
+ }
88
+ return agent.goal
89
+ }
90
+
91
+ /** 目标期间累计 token(退出点钩子每轮调一次)。 */
92
+ export function addGoalTokens(agent, usage) {
93
+ if (!agent.goal || !usage) return
94
+ const n = Number(usage.prompt_tokens ?? 0) + Number(usage.completion_tokens ?? 0)
95
+ if (Number.isFinite(n) && n > 0) agent.goal.tokensSpent = (agent.goal.tokensSpent ?? 0) + n
96
+ }
package/agent/helpers.mjs CHANGED
@@ -37,7 +37,7 @@ const GIT_TIMEOUT_MS = 5000
37
37
  const MAX_GIT_CHANGES_DISPLAY = 20
38
38
 
39
39
  export const OUTLINE_INJECT_PREFIX = "[System reminder: project dependency outline:"
40
- export const FILE_MUTATORS = new Set(["write", "edit", "insert_after", "apply_patch", "delete", "hashline_edit"])
40
+ export const FILE_MUTATORS = new Set(["write", "edit", "insert_after", "apply_patch", "delete", "hashline_edit", "file_ops"])
41
41
 
42
42
  /**
43
43
  * 工具自报触达面提取**单源谓词**(`docs/core/design/TOOLS.md` §6.17 / D-TO12——批 GUARD-SCHEDULER ·
@@ -195,6 +195,11 @@ export function wroteSince(agent, mark) {
195
195
  return Number.isInteger(seq) ? seq !== mark : true
196
196
  }
197
197
 
198
+ /** 服务端内置工具(如 Responses API web_search)产生的 tool 消息无对应 assistant.tool_calls,配对修复须原样保留。 */
199
+ function isBuiltinToolCallId(id) {
200
+ return typeof id === "string" && id.startsWith("web_search_call_")
201
+ }
202
+
198
203
  /** Repair malformed conversation history: remove orphan tool messages and fill missing tool results */
199
204
  export function repairHistory(history) {
200
205
  const out = []
@@ -208,7 +213,8 @@ export function repairHistory(history) {
208
213
  continue
209
214
  }
210
215
  // orphan tool message: no matching assistant tool_calls declaration, discard
211
- if (m.role === "tool" && !knownIds.has(m.tool_call_id)) {
216
+ // (server-executed builtin tool results such as web_search_call_* have no assistant.tool_calls)
217
+ if (m.role === "tool" && !knownIds.has(m.tool_call_id) && !isBuiltinToolCallId(m.tool_call_id)) {
212
218
  dirty = true
213
219
  continue
214
220
  }
@@ -220,8 +226,11 @@ export function repairHistory(history) {
220
226
  const answered = new Set()
221
227
  let j = i + 1
222
228
  while (j < history.length && history[j].role === "tool") {
223
- if (knownIds.has(history[j].tool_call_id)) {
224
- answered.add(history[j].tool_call_id)
229
+ const tid = history[j].tool_call_id
230
+ if (knownIds.has(tid)) {
231
+ answered.add(tid)
232
+ out.push(history[j])
233
+ } else if (isBuiltinToolCallId(tid)) {
225
234
  out.push(history[j])
226
235
  } else {
227
236
  dirty = true // orphan tool result, discard
package/agent/offload.mjs CHANGED
@@ -74,7 +74,7 @@ export async function offloadToolResult(text, callId, dir = join(configDir, "too
74
74
  await writeFile(file, text, "utf8")
75
75
  if (!overLimit) return `${text}\n\n[... full content saved to: ${file}\nPage through it with the read tool (offset/limit) if you need the full text later.]`
76
76
  return buildDualEndPreview(text, TOOL_RESULT_PREVIEW) + `\n\n[... output too large (${text.length} chars total), full content saved to: ${file}\n` +
77
- `Page through it with the read tool (offset/limit) or sed -n 'START,ENDp' — do NOT re-run the tool blindly.]`
77
+ `Page through it with the read tool (offset/limit) — do NOT re-run the tool blindly.]`
78
78
  } catch {
79
79
  // 写盘失败不吞报告:>LIMIT 走双端预览 + 原文案;≤LIMIT 正文整段在前(不谎称 truncated)
80
80
  const body = overLimit ? buildDualEndPreview(text, TOOL_RESULT_PREVIEW) : text