thincoder 0.12.62 → 0.12.64

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 (231) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/README.md +46 -49
  3. package/bin/thincoder.mjs +68 -34
  4. package/package.json +7 -6
  5. package/src/acp/bridge.mjs +35 -15
  6. package/src/acp/client-caps.mjs +86 -0
  7. package/src/acp/ext.mjs +86 -0
  8. package/src/acp/handlers-session.mjs +257 -0
  9. package/src/acp/handlers-slots.mjs +196 -0
  10. package/src/acp/login.mjs +48 -0
  11. package/src/acp/session.mjs +6 -4
  12. package/src/acp.mjs +67 -379
  13. package/src/cli/distill-command.mjs +3 -3
  14. package/src/cli/make-agent.mjs +60 -17
  15. package/src/cli/memory-command.mjs +3 -3
  16. package/src/cli/permission.mjs +4 -48
  17. package/src/cli/setup-wizard.mjs +1 -1
  18. package/src/completions.mjs +3 -1
  19. package/src/crash-reports.mjs +1 -1
  20. package/src/distill.mjs +4 -4
  21. package/src/heap-watch.mjs +1 -1
  22. package/src/prompt-injections.mjs +20 -0
  23. package/src/tui/agent-turn.mjs +40 -9
  24. package/src/tui/cmd-advisor.mjs +5 -5
  25. package/src/tui/cmd-config.mjs +8 -8
  26. package/src/tui/cmd-eng.mjs +35 -9
  27. package/src/tui/cmd-mcp.mjs +9 -8
  28. package/src/tui/cmd-model.mjs +1 -1
  29. package/src/tui/cmd-new.mjs +6 -5
  30. package/src/tui/cmd-plan.mjs +9 -0
  31. package/src/tui/cmd-reindex.mjs +1 -1
  32. package/src/tui/cmd-restore.mjs +2 -2
  33. package/src/tui/cmd-session.mjs +24 -1
  34. package/src/tui/cmd-skills.mjs +1 -1
  35. package/src/tui/cmd-think.mjs +22 -9
  36. package/src/tui/config-helpers.mjs +1 -1
  37. package/src/tui/display-budget.mjs +33 -11
  38. package/src/tui/index.mjs +18 -10
  39. package/src/tui/interaction.mjs +16 -7
  40. package/src/tui/key-modes.mjs +9 -4
  41. package/src/tui/ledger-surface.mjs +22 -59
  42. package/src/tui/model-catalog.mjs +4 -4
  43. package/src/tui/model-picker.mjs +8 -7
  44. package/src/tui/mouse.mjs +11 -6
  45. package/src/tui/pickers.mjs +15 -2
  46. package/src/tui/render-conversation.mjs +1 -1
  47. package/src/tui/render-frame.mjs +15 -6
  48. package/src/tui/render-loop.mjs +1 -1
  49. package/src/tui/render-segments.mjs +3 -1
  50. package/src/tui/slash-commands.mjs +1 -1
  51. package/src/tui/startup.mjs +14 -14
  52. package/src/tui/subagent-blocks.mjs +20 -3
  53. package/src/tui/subagent-freeze.mjs +73 -2
  54. package/src/tui/suspension-drive.mjs +57 -23
  55. package/src/tui/tool-events.mjs +11 -8
  56. package/src/tui/tui-lifecycle.mjs +9 -0
  57. package/src/tui/wizard.mjs +3 -3
  58. package/src/tui/wrapped-spawn.mjs +6 -2
  59. package/src/abort-provenance.mjs +0 -116
  60. package/src/advisor/citations.mjs +0 -139
  61. package/src/advisor/compaction.mjs +0 -174
  62. package/src/advisor/convergence.mjs +0 -80
  63. package/src/advisor/history.mjs +0 -77
  64. package/src/advisor/loop.mjs +0 -293
  65. package/src/advisor/messages.mjs +0 -299
  66. package/src/advisor/project-context.mjs +0 -194
  67. package/src/advisor/repos.mjs +0 -150
  68. package/src/advisor/run.mjs +0 -293
  69. package/src/advisor/truncate.mjs +0 -57
  70. package/src/advisor.mjs +0 -290
  71. package/src/agent/completion.mjs +0 -146
  72. package/src/agent/dispatch.mjs +0 -489
  73. package/src/agent/helpers.mjs +0 -384
  74. package/src/agent/post-turn.mjs +0 -70
  75. package/src/agent/record-results.mjs +0 -174
  76. package/src/agent/relay-prefix.mjs +0 -39
  77. package/src/agent/run-stages.mjs +0 -244
  78. package/src/agent/setup-reminders.mjs +0 -69
  79. package/src/agent/setup.mjs +0 -354
  80. package/src/agent/spawn-child.mjs +0 -243
  81. package/src/agent-tools/advisor-async.mjs +0 -346
  82. package/src/agent-tools/advisor-settle.mjs +0 -231
  83. package/src/agent-tools/advisor.mjs +0 -260
  84. package/src/agent-tools/async-settle.mjs +0 -204
  85. package/src/agent-tools/batch-segment.mjs +0 -195
  86. package/src/agent-tools/consult.mjs +0 -473
  87. package/src/agent-tools/design-token.mjs +0 -117
  88. package/src/agent-tools/digest-budget.mjs +0 -76
  89. package/src/agent-tools/eng.mjs +0 -67
  90. package/src/agent-tools/escalate-async.mjs +0 -295
  91. package/src/agent-tools/goal.mjs +0 -119
  92. package/src/agent-tools/plan.mjs +0 -81
  93. package/src/agent-tools/read-history.mjs +0 -309
  94. package/src/agent-tools/recent-changes.mjs +0 -24
  95. package/src/agent-tools/review-streak.mjs +0 -93
  96. package/src/agent-tools/settings.mjs +0 -265
  97. package/src/agent-tools/skill.mjs +0 -47
  98. package/src/agent-tools/subagent-actions.mjs +0 -482
  99. package/src/agent-tools/subagent-async.mjs +0 -434
  100. package/src/agent-tools/subagent-panel.mjs +0 -160
  101. package/src/agent-tools/subagent-run.mjs +0 -205
  102. package/src/agent-tools/subagent-scheduler.mjs +0 -392
  103. package/src/agent-tools/subagent-spawn.mjs +0 -459
  104. package/src/agent-tools/subagent.mjs +0 -404
  105. package/src/agent-tools/task.mjs +0 -87
  106. package/src/agent-tools/timer.mjs +0 -46
  107. package/src/agent-tools/verify.mjs +0 -271
  108. package/src/agent-tools.mjs +0 -17
  109. package/src/agent.mjs +0 -417
  110. package/src/auto-think.mjs +0 -115
  111. package/src/config-migrate.mjs +0 -70
  112. package/src/config.mjs +0 -496
  113. package/src/context.mjs +0 -392
  114. package/src/conventions.mjs +0 -223
  115. package/src/embedding.mjs +0 -120
  116. package/src/escape.mjs +0 -152
  117. package/src/expand-home.mjs +0 -16
  118. package/src/explore-distill.mjs +0 -155
  119. package/src/generate-title.mjs +0 -88
  120. package/src/git/checkpoint.mjs +0 -448
  121. package/src/git/gitmem.mjs +0 -100
  122. package/src/hooks.mjs +0 -97
  123. package/src/ledger.mjs +0 -227
  124. package/src/log.mjs +0 -195
  125. package/src/markdown.mjs +0 -106
  126. package/src/mcp/helpers.mjs +0 -51
  127. package/src/mcp/transport-http.mjs +0 -248
  128. package/src/mcp/transport-stdio.mjs +0 -140
  129. package/src/mcp/transport-ws.mjs +0 -122
  130. package/src/mcp.mjs +0 -295
  131. package/src/memory/code-index.mjs +0 -219
  132. package/src/memory/code-sync.mjs +0 -415
  133. package/src/memory/core.mjs +0 -299
  134. package/src/memory/delete.mjs +0 -236
  135. package/src/memory/docs.mjs +0 -419
  136. package/src/memory/file-walk.mjs +0 -109
  137. package/src/memory/scan.mjs +0 -95
  138. package/src/memory/schema.mjs +0 -452
  139. package/src/memory.mjs +0 -21
  140. package/src/model-ref.mjs +0 -66
  141. package/src/model-specs.mjs +0 -179
  142. package/src/peer-domains.mjs +0 -265
  143. package/src/peer-instances.mjs +0 -231
  144. package/src/prompt-overlays.mjs +0 -82
  145. package/src/prompts/advisor-design.md +0 -41
  146. package/src/prompts/advisor-round1.md +0 -41
  147. package/src/prompts/advisor-round2.md +0 -46
  148. package/src/prompts/advisor-round3.md +0 -42
  149. package/src/prompts/common.md +0 -115
  150. package/src/prompts/consult-base.md +0 -19
  151. package/src/prompts/discipline-engineering.md +0 -258
  152. package/src/prompts/discipline-normal.md +0 -185
  153. package/src/prompts/persona-coder.md +0 -21
  154. package/src/prompts/persona-eng-coder.md +0 -37
  155. package/src/prompts/persona-eng-designer.md +0 -60
  156. package/src/prompts/persona-engineering.md +0 -55
  157. package/src/prompts/persona-explore.md +0 -15
  158. package/src/prompts/persona-normal.md +0 -27
  159. package/src/prompts/persona-plan.md +0 -26
  160. package/src/provider/anthropic.mjs +0 -225
  161. package/src/provider/core.mjs +0 -476
  162. package/src/provider/errors.mjs +0 -101
  163. package/src/provider/google.mjs +0 -257
  164. package/src/provider/index.mjs +0 -7
  165. package/src/provider/list-models.mjs +0 -93
  166. package/src/provider/normalize.mjs +0 -81
  167. package/src/provider/rate.mjs +0 -108
  168. package/src/provider/responses.mjs +0 -495
  169. package/src/provider/retry.mjs +0 -88
  170. package/src/provider/sse.mjs +0 -264
  171. package/src/proxy.mjs +0 -261
  172. package/src/rules.mjs +0 -53
  173. package/src/session-gc.mjs +0 -221
  174. package/src/session-guard.mjs +0 -59
  175. package/src/session-migrate.mjs +0 -48
  176. package/src/session-rename.mjs +0 -38
  177. package/src/session-segments.mjs +0 -100
  178. package/src/session-slots.mjs +0 -492
  179. package/src/session-store.mjs +0 -441
  180. package/src/session.mjs +0 -492
  181. package/src/skills.mjs +0 -153
  182. package/src/text-budget.mjs +0 -46
  183. package/src/token-ttl.mjs +0 -274
  184. package/src/tools/apply_patch.md +0 -15
  185. package/src/tools/bash.md +0 -37
  186. package/src/tools/bash.mjs +0 -268
  187. package/src/tools/checklist-sync.mjs +0 -181
  188. package/src/tools/checklist.md +0 -13
  189. package/src/tools/checklist.mjs +0 -299
  190. package/src/tools/delete.md +0 -13
  191. package/src/tools/edit-batch.mjs +0 -191
  192. package/src/tools/edit-diff.mjs +0 -348
  193. package/src/tools/edit.md +0 -30
  194. package/src/tools/execute.md +0 -21
  195. package/src/tools/execute.mjs +0 -228
  196. package/src/tools/fetch.md +0 -12
  197. package/src/tools/file.mjs +0 -469
  198. package/src/tools/file_ops.md +0 -17
  199. package/src/tools/get_current_time.md +0 -8
  200. package/src/tools/git-checkpoint.mjs +0 -143
  201. package/src/tools/git-ext.mjs +0 -173
  202. package/src/tools/git.md +0 -54
  203. package/src/tools/git.mjs +0 -356
  204. package/src/tools/glob-dialect.mjs +0 -130
  205. package/src/tools/glob.md +0 -11
  206. package/src/tools/grep.md +0 -19
  207. package/src/tools/hashline_edit.md +0 -14
  208. package/src/tools/index.mjs +0 -36
  209. package/src/tools/insert_after.md +0 -15
  210. package/src/tools/lint.md +0 -10
  211. package/src/tools/linter.mjs +0 -128
  212. package/src/tools/ls.md +0 -12
  213. package/src/tools/lsp.md +0 -10
  214. package/src/tools/lsp.mjs +0 -316
  215. package/src/tools/ops.mjs +0 -299
  216. package/src/tools/patch.mjs +0 -282
  217. package/src/tools/process.md +0 -10
  218. package/src/tools/question.md +0 -16
  219. package/src/tools/question.mjs +0 -26
  220. package/src/tools/read.md +0 -20
  221. package/src/tools/read_image.md +0 -8
  222. package/src/tools/repomap.mjs +0 -314
  223. package/src/tools/search.mjs +0 -236
  224. package/src/tools/shared.mjs +0 -446
  225. package/src/tools/tree.md +0 -14
  226. package/src/tools/tree.mjs +0 -66
  227. package/src/tools/wait_for.md +0 -22
  228. package/src/tools/web.mjs +0 -224
  229. package/src/tools/websearch.md +0 -16
  230. package/src/tools/write.md +0 -11
  231. package/src/traces/trace-store.mjs +0 -355
@@ -1,146 +0,0 @@
1
- /**
2
- * agent/completion.mjs — handle model response with no tool calls
3
- *
4
- * Checks: pending tasks, verify guard, advisor guard.
5
- * Returns { action: 'continue' | 'done', content?, guardPushbacks, honestReminderInjected, advisorPushbacks }
6
- */
7
- import { hasCodeMutations } from "../advisor/repos.mjs"
8
- import { pushReal } from "../context.mjs"
9
- import { MAX_ADVISOR_ROUNDS } from "../advisor/run.mjs"
10
- import { advisorReviewPending, effectiveAdvisorRound } from "../agent-tools/advisor-async.mjs"
11
-
12
- const MAX_VERIFY_PUSHBACKS = 2
13
- const MAX_VERIFY_RETRIES = 3
14
- const MAX_ADVISOR_PUSHBACKS = 3
15
- const MAX_EMPTY_RETRIES = 2
16
-
17
- /**
18
- * Handle a model turn with zero tool calls. May push back (verify/advisor/pending tasks)
19
- * or accept the completion.
20
- *
21
- * @param {object} agent
22
- * @param {object} response - chat response with .content, .toolCalls
23
- * @param {number} depth - agent nesting depth (0 = top-level)
24
- * @param {number} turn - current turn index
25
- * @param {number} guardPushbacks - verify guard pushback count (mutated)
26
- * @param {boolean} honestReminderInjected - whether exhausted-verify reminder was already sent (mutated)
27
- * @param {number} advisorPushbacks - advisor guard pushback count (mutated)
28
- * @param {object} callbacks - { onTurnEnd }
29
- */
30
- export function handleCompletion(agent, response, depth, turn, guardPushbacks, honestReminderInjected, advisorPushbacks, callbacks) {
31
- if (!response.content) {
32
- // Transient empty response (reasoning exhausted / output truncated): instead of
33
- // aborting the whole turn, inject a reminder and let the model respond again.
34
- // Bounded — after MAX_EMPTY_RETRIES consecutive empties, surface the original error.
35
- const retries = agent._emptyRetries ?? 0
36
- if (retries < MAX_EMPTY_RETRIES) {
37
- agent._emptyRetries = retries + 1
38
- agent.history.push({
39
- role: "user",
40
- content: "[System reminder: your last response was empty — the provider returned no content (likely reasoning was exhausted or output was truncated). Respond again, continuing your work from where you left off.]",
41
- })
42
- callbacks.onTurnEnd?.(agent, turn)
43
- return { action: "continue", guardPushbacks, honestReminderInjected, advisorPushbacks }
44
- }
45
- throw new Error(
46
- "LLM returned empty response (likely reasoning exhausted or output truncated). " +
47
- "Try lowering reasoning effort if this persists (/think in TUI). " +
48
- `Provider: ${agent.provider.model}`
49
- )
50
- }
51
-
52
- // Pending tasks: remind the model ONCE before it declares itself done.
53
- // Deliberately capped at one pushback (reported pain: unbounded looping when a
54
- // pending item can't be resolved). After the single reminder the model is free
55
- // to finish — updating the task list (task tool) resets the budget, so a fresh
56
- // list state earns one fresh reminder.
57
- if (depth === 0 && agent.tasks.some((t) => t.status === "pending") && (agent._taskPushbacks ?? 0) < 1) {
58
- agent._taskPushbacks = (agent._taskPushbacks ?? 0) + 1
59
- const pending = agent.tasks.filter((t) => t.status === "pending").map((t) => t.title).join(", ")
60
- pushReal(agent, { role: "assistant", content: response.content })
61
- agent.history.push({
62
- role: "user",
63
- content: `[System reminder: you still have pending tasks: ${pending}. Update their status with the task tool before finishing — if they're done, mark them done; if they're not applicable, remove them. (This is your only reminder — if you choose not to, finish anyway.)]`,
64
- })
65
- callbacks.onTurnEnd?.(agent, turn)
66
- return { action: "continue", guardPushbacks, honestReminderInjected, advisorPushbacks }
67
- }
68
-
69
- // --- verify guard: push model to verify mutated files before completion ---
70
- // OPT-IN ONLY (verifyGuard: true). Engineering mode is excluded because it
71
- // uses flow-driven review, not per-turn mechanical pushback (ENGINEERING-MODE.md §2.3).
72
- // Backward compat: also accept root-level verifyGuard
73
- const verifyGuard = agent.config?.agent?.verifyGuard ?? agent.config?.verifyGuard
74
- if (depth === 0 && verifyGuard === true && !agent.config?.agent?.engineering) {
75
- // Not verified yet → pushback to run verify
76
- if (agent._mutatedThisRun && !agent._verifiedThisRun && hasCodeMutations(agent) && guardPushbacks < MAX_VERIFY_PUSHBACKS) {
77
- guardPushbacks++
78
- pushReal(agent, { role: "assistant", content: response.content })
79
- agent.history.push({
80
- role: "user",
81
- content: "[System reminder: you modified files in this run but have not verified the changes. Before finishing: run the project's verification yourself (per its AGENTS.md test method), then call verify declaring the outcome via verification.status. verify mechanically gates on your declaration. If verification is genuinely impossible here, say so explicitly in your reply.]",
82
- })
83
- callbacks.onTurnEnd?.(agent, turn)
84
- return { action: "continue", guardPushbacks, honestReminderInjected, advisorPushbacks }
85
- }
86
- // Verified but not passed → pushback to fix/complete (up to MAX_VERIFY_RETRIES).
87
- // _verifyPassed === false means the declaration was failed, skipped without a
88
- // reason, or not declared — not necessarily that a test failed.
89
- if (agent._verifiedThisRun && agent._verifyPassed === false && agent._verifyRetries < MAX_VERIFY_RETRIES) {
90
- agent._verifyRetries++
91
- pushReal(agent, { role: "assistant", content: response.content })
92
- agent.history.push({
93
- role: "user",
94
- content: `[System reminder: (retry ${agent._verifyRetries}/${MAX_VERIFY_RETRIES}) verify was not passed — either your verification declared failed, was skipped without a reason, or was not declared. Fix or complete your verification, then call verify again declaring the outcome. If you cannot fix after ${MAX_VERIFY_RETRIES} attempts, explain honestly what's blocking you.]`,
95
- })
96
- callbacks.onTurnEnd?.(agent, turn)
97
- return { action: "continue", guardPushbacks, honestReminderInjected, advisorPushbacks }
98
- }
99
- // Exhausted retries — inject honesty reminder once
100
- if (agent._verifiedThisRun && agent._verifyPassed === false && agent._verifyRetries >= MAX_VERIFY_RETRIES) {
101
- if (honestReminderInjected) {
102
- pushReal(agent, { role: "assistant", content: response.content })
103
- return { action: "done", content: response.content, guardPushbacks, honestReminderInjected, advisorPushbacks }
104
- }
105
- honestReminderInjected = true
106
- pushReal(agent, { role: "assistant", content: response.content })
107
- agent.history.push({
108
- role: "user",
109
- content: `[System reminder: ${MAX_VERIFY_RETRIES} verify attempts exhausted. You have not passed verification. Either state explicitly that your verification could not be completed, or run verify again once it is. If your verification could not be completed, say so explicitly in your reply to the user — state what you tried and what you believe is blocking you, and do not present the work as complete; the user needs to know it is unfinished.]`,
110
- })
111
- callbacks.onTurnEnd?.(agent, turn)
112
- return { action: "continue", guardPushbacks, honestReminderInjected, advisorPushbacks }
113
- }
114
- }
115
-
116
- // --- advisor guard: review of mutated files before completion ---
117
- // OPT-IN ONLY (advisor.guard === true, default OFF — 2026-08-21 semantic
118
- // refactor), and NEVER in engineering mode. The advisor tool itself is always
119
- // available; this guard only controls whether completion is pushed back.
120
- const cfg = agent.config?.advisor
121
- const advisorReview = cfg?.guard === true
122
- if (depth === 0 && advisorReview && !agent.config?.agent?.engineering) {
123
- // §11.2 D-24b (T-24b4 — guard timing): an async review that is still in flight
124
- // (or queued in the advisor pool) means the review was launched — the guard
125
- // does NOT push back while it is pending (未决不算未评审); once it settles
126
- // non-stale it marks _calledAdvisorThisRun, and a STALE settle leaves the
127
- // mark unset so the guard pushes back here again (fix #2 — no silent skip).
128
- const pending = advisorReviewPending(agent)
129
- const rounds = effectiveAdvisorRound(agent)
130
- if (!pending && agent._mutatedThisRun && !agent._calledAdvisorThisRun && hasCodeMutations(agent)
131
- && advisorPushbacks < MAX_ADVISOR_PUSHBACKS
132
- && rounds < MAX_ADVISOR_ROUNDS) {
133
- advisorPushbacks++
134
- pushReal(agent, { role: "assistant", content: response.content })
135
- agent.history.push({
136
- role: "user",
137
- content: `[System reminder: you changed code in this run and MUST get an advisor review before finishing (round ${rounds + 1}). Call the \`advisor\` tool now. This is required, not optional — do not skip it even if you believe the changes are trivial — the review will be quick either way. After the review, produce a response table for every issue found (see discipline rules for format).]`,
138
- })
139
- callbacks.onTurnEnd?.(agent, turn)
140
- return { action: "continue", guardPushbacks, honestReminderInjected, advisorPushbacks }
141
- }
142
- }
143
-
144
- pushReal(agent, { role: "assistant", content: response.content })
145
- return { action: "done", content: response.content, guardPushbacks, honestReminderInjected, advisorPushbacks }
146
- }
@@ -1,489 +0,0 @@
1
- /**
2
- * agent/dispatch.mjs — two-phase tool call execution
3
- */
4
- import { logEvent, errText, headText } from "../log.mjs"
5
- import { offloadToolResult, FILE_MUTATORS } from "./helpers.mjs"
6
- import { runHooks } from "../hooks.mjs"
7
- import { snapshotForUndo } from "../tui/cmd-undo.mjs"
8
- import { isCodePath, loadConventions } from "../conventions.mjs"
9
- // R10 L3 (MULTI-INSTANCE-COLLAB §2a.5 D-L3b):写工具钩子——peerCollabNote(执行前冲突
10
- // 检测——软提示不阻止)+ recordPeerWrites(成功后累积本回合写足迹——回合末 flush)。
11
- import { PEER_WRITE_TOOLS, peerCollabNote, recordPeerWrites } from "../peer-domains.mjs"
12
- import { writeFileSync, mkdirSync, existsSync } from "node:fs"
13
- import { join, resolve, relative } from "node:path"
14
- import { homedir } from "node:os"
15
- // §29 fix A(AGENT-LOOP.md §29——2026-09-07):FILE_MUTATORS 的 mutation-seq 记账从
16
- // 批后提交(record-results noteMutations)移到执行成功即刻——唯一记账点(取代批后段
17
- // + agent.mjs 中断分支记账——不双计)——同消息 [写 + async advisor launch] 时 launch 前
18
- // 完成的写在 launchSeq 之前落地 → settle 不再误判 stale(§29 症状根因)。
19
- import { noteMutations, inflightDesignReviewConflict } from "../agent-tools/advisor-async.mjs"
20
- import { anyLiveDesignSlot } from "../token-ttl.mjs"
21
-
22
- const ERRORS_DIR = join(homedir(), ".thincoder", "tool-errors")
23
-
24
- /**
25
- * Persist a tool error to ~/.thincoder/tool-errors/YYYY-MM-DD/HHmmss-toolName.log
26
- * Only called for actual execution failures and malformed invocations.
27
- * Skipped for intentional denials (plan mode, user reject).
28
- */
29
- function logToolError(toolName, args, error) {
30
- try {
31
- const now = new Date()
32
- const ymd = now.toISOString().slice(0, 10)
33
- const ts = now.toISOString().replace(/:/g, "").replace(/\..+/, "").replace("T", "-")
34
- const dir = join(ERRORS_DIR, ymd)
35
- if (!existsSync(dir)) mkdirSync(dir, { recursive: true })
36
- const file = join(dir, `${ts}-${toolName.replace(/[/\\]/g, "_")}.log`)
37
- const entry = [
38
- `time: ${now.toISOString()}`,
39
- `tool: ${toolName}`,
40
- `args: ${JSON.stringify(args, null, 2).slice(0, 2000)}${JSON.stringify(args, null, 2).length > 2000 ? "… (truncated)" : ""}`,
41
- `error: ${error?.message ?? String(error)}`,
42
- error?.stack ? `stack:\n${error.stack}` : "",
43
- ].filter(Boolean).join("\n") + "\n"
44
- writeFileSync(file, entry, "utf8")
45
- } catch {
46
- // Log failure itself must not crash the agent
47
- }
48
- }
49
-
50
- /**
51
- * §19 action-level classification (AGENT-LOOP.md §19 D-M1): the merged subagent
52
- * tool expresses spawn (side effect) and status (read-only query) through
53
- * its `action` parameter — the tool-level readonly flag can no longer express both.
54
- * dispatch Phase-1/Phase-2 classifies per action: status behaves as readonly
55
- * (planMode pass / no permission ask / batchable), spawn keeps its non-readonly
56
- * gates, escalate runs non-readonly AND serially (the retired escalate tool had no
57
- * parallel flag — zero behavior change under the merged surface).
58
- * §19.5 cancel (19.5.2b round2 #4): CONTROL-class exemption — cancel only
59
- * stops, never starts. isSubagentControlAction feeds the SAME two gate sites as
60
- * readonly (planMode pass / no permission ask — never joins a batch approval
61
- * group / no handler → not denied — digest 内 cancel 放行).
62
- * §19.6 panel (round1 #5): view 面归只读类(同 status——planMode 放行、免
63
- * 审批、可批并行);freeze 面归控制类(同 cancel——planMode 放行、免权限审批、
64
- * 批审批不入组、digest 内放行)。freeze 存在(非空 key)即控制类——否则只读类。
65
- */
66
- function isSubagentReadonlyAction(toolName, args) {
67
- // §6 memory 工具面重构(MEMORY.md §6 D-M5):memory search/list 是只读动作——与
68
- // subagent status 同分类(planMode 放行/免审批——Phase-2 批并行只认工具级
69
- // readonly/parallel,memory 无 parallel → 按非只读串行,见 MEMORY.md §6.4 实现注)。
70
- // 动作级判定——不能按工具名(同一 memory 工具的 put/delete/clear 保持侧效门)。
71
- if (toolName === "memory") {
72
- const action = args?.action
73
- return action === "search" || action === "list"
74
- }
75
- // SETTINGS-TOOL.md(2026-09-05):settings list/get 是只读动作(memory search/list 同分类——
76
- // planMode 放行/免审批);set 保持侧效门。
77
- if (toolName === "settings") {
78
- const action = args?.action
79
- return action === "list" || action === "get"
80
- }
81
- if (toolName !== "subagent" || !args || typeof args !== "object") return false
82
- const action = args.action
83
- // §19.8: check 动作已删除——只读面仅剩 status(planMode 放行/免权限审批/可批并行)
84
- if (action === "status") return true
85
- // SUBAGENT-OBSERVE-SEND:observe = readonly 查询(同 status——digest/planMode 放行)
86
- if (action === "observe") return true
87
- // §19.6 panel view 面(freeze 缺省/空 = 视图请求——readonly;非空 freeze 归控制类)
88
- if (action === "panel" && (args.freeze === undefined || args.freeze === null || String(args.freeze) === "")) return true
89
- return false
90
- }
91
- function isSubagentControlAction(toolName, args) {
92
- if (toolName !== "subagent") return false
93
- if (args?.action === "cancel") return true
94
- // SUBAGENT-OBSERVE-SEND:send = 控制类豁免(同 cancel——父回合内显式调用即授权——
95
- // 写子输入队列属父对子轻量引导,非产品代码写——免审批、planMode 放行、digest 内放行)
96
- if (args?.action === "send") return true
97
- // §19.6 panel freeze 面(D-P3 门控在 executor——只读/控制分类在此)
98
- if (args?.action === "panel" && args.freeze !== undefined && args.freeze !== null && String(args.freeze) !== "") return true
99
- return false
100
- }
101
- /**
102
- * §2.6 token 链终消费制(2026-09-07——评审 #7d dispatch 分类):consume-design =
103
- * 非只读控制动作——planMode 拒绝(不入 readonly/control 豁免——与其他非只读动作同门)、
104
- * 免权限审批、不入批审批分组(无文件写——控制类直行——只停既有状态不起新副作用)。
105
- * 与 cancel 的不同:cancel 是控制类豁免(planMode 放行),consume-design 按设计
106
- * planMode 拒绝——故不并入 isSubagentControlAction,单独谓词只接权限豁免位。
107
- */
108
- function isSubagentConsumeDesignAction(toolName, args) {
109
- return toolName === "subagent" && args?.action === "consume-design"
110
- }
111
- function isSubagentEscalateAction(toolName, args) {
112
- return toolName === "subagent" && args?.action === "escalate"
113
- }
114
-
115
- /**
116
- * §29 fix A — 唯一记账点:FILE_MUTATORS 工具执行成功即刻记 mutation seq(abs 路径)。
117
- * 取代 record-results 批后段 + agent.mjs 中断分支的 noteMutations(不双计——中断+同批
118
- * launch 场景 seq 单计,AGENT-LOOP.md §29 T-A1i)。调用时机 = 写执行成功(非 Error 前缀
119
- * 结果——recordPeerWrites 同款门);routed(M2 ACP 客户端执行)成功同样记账。
120
- */
121
- function noteExecutedMutation(agent, tool, args) {
122
- let paths
123
- try {
124
- paths = tool.touchedPaths ? tool.touchedPaths(args ?? {}) : [args?.path]
125
- } catch { return }
126
- const abs = (paths ?? [])
127
- .filter((p) => typeof p === "string" && p)
128
- .map((p) => resolve(agent.cwd, p))
129
- if (abs.length > 0) noteMutations(agent, abs)
130
- }
131
-
132
- /**
133
- * Two-phase execution:
134
- * Phase 1 (serial): parse args one by one + planMode check + permission confirmation (side-effecting tools)
135
- * Phase 2 (order-preserving): strictly preserve model call order — consecutive readonly/parallel tools run as concurrent batches,
136
- * side-effecting tools run serially in their original position (if a batch writes-then-reads the same file, the read must see the post-write content).
137
- * Returns a results array in call order (each entry has an ok flag indicating success/failure).
138
- */
139
- export async function executeToolCalls(agent, toolByName, toolCalls, callbacks, depth = 0, signal) {
140
- // ---- Phase 1: serial preparation ----
141
- // Pre-gates run per tool (parse/planMode/engineering gates); non-readonly tools
142
- // that REACH the permission stage are collected into one batch — a single merged
143
- // ask covers the whole toolCalls array (§16 D-B1, "approve all / one by one /
144
- // deny"). Tools stopped by a pre-gate never join the batch (review #7).
145
- const prepared = []
146
- const permPending = [] // { toolCall, tool, args } — reached the permission stage
147
- for (const toolCall of toolCalls) {
148
- const tool = toolByName.get(toolCall.name)
149
- let args
150
- try {
151
- args = JSON.parse(toolCall.arguments || "{}")
152
- } catch {
153
- logToolError(toolCall.name, { arguments: toolCall.arguments }, new Error("Invalid JSON arguments"))
154
- prepared.push({ toolCall, tool: null, error: `Invalid tool arguments JSON: ${toolCall.arguments}` })
155
- continue
156
- }
157
-
158
- if (!tool) {
159
- logToolError(toolCall.name, {}, new Error(`Unknown tool: ${toolCall.name}`))
160
- prepared.push({ toolCall, tool: null, error: `Unknown tool: ${toolCall.name}` })
161
- continue
162
- }
163
-
164
- if (agent.planMode && !tool.readonly && !isSubagentReadonlyAction(toolCall.name, args) && !isSubagentControlAction(toolCall.name, args)) {
165
- prepared.push({ toolCall, tool, denied: true, reason: "plan mode" })
166
- continue
167
- }
168
-
169
- // Engineering coder hard gate: no file modification before the design review passed.
170
- // The design review is the eng-coder's mandatory pre-coding gate — advisor(type="design")
171
- // must run (and be accepted) before the first write/edit/apply_patch/hashline_edit/insert_after/delete.
172
- if (agent._role === "eng-coder" && agent.config?.agent?.engineering
173
- && !agent._engDesignReviewed && FILE_MUTATORS.has(toolCall.name)) {
174
- prepared.push({
175
- toolCall, tool, denied: true,
176
- reason: "engineering design gate",
177
- 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.",
178
- })
179
- continue
180
- }
181
-
182
- // Engineering mode PARENT gate: the parent agent must not touch code files
183
- // before the design review passed. Signaled by a live design slot (design-review
184
- // approval — persists in the session slot, survives across turns; _engDesignReviewed
185
- // is eng-coder-only and reset per run). Exemptions = the non-code classes of
186
- // src/conventions.mjs (documentation and temp scratch files) — writing a design
187
- // document IS the design step. Anything inside a declared code segment (default:
188
- // src — incl. src/prompts/*.md) is product code, not documentation, and needs a
189
- // design token. The project can declare its own code paths (.thincoder/
190
- // conventions.json) so a non-src layout is not silently exempted. Mechanically
191
- // blocks "talk then code".
192
- // DESIGN-TOKEN-SETTLEMENT D3(2026-09-08):资格判据 = 权威槽"任一活槽存在"
193
- // (anyLiveDesignSlot——查内存 Map,miss 回读槽文件——单值镜像 `_engDesignToken`
194
- // 已退役,门禁不再读镜像——AC4)。
195
- if (agent.config?.agent?.engineering && depth === 0
196
- && !anyLiveDesignSlot(agent)
197
- && FILE_MUTATORS.has(toolCall.name)) {
198
- const paths = tool.touchedPaths ? tool.touchedPaths(args) : [args.path]
199
- const conv = loadConventions(agent.cwd)
200
- // Unknown/missing paths (non-string, e.g. no path argument) are treated
201
- // as code — cannot tell what they touch, so block conservatively. Known
202
- // paths go through the single shared classifier: a declared code segment
203
- // (default: "src") at ANY depth, else anything that is not documentation.
204
- const touchesCode = paths.some((p) => typeof p !== "string" || isCodePath(p, conv))
205
- if (touchesCode) {
206
- // Undeclared project → point at the declaration file (§4.3 降级可见契约).
207
- const convNote = conv.declared
208
- ? ""
209
- : ` — this path was classified as product code by the default conventions (code paths: ${conv.codePaths.join(", ")}); declare project conventions in .thincoder/conventions.json to adjust.`
210
- prepared.push({
211
- toolCall, tool, denied: true,
212
- reason: "engineering design gate",
213
- 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}`,
214
- })
215
- continue
216
- }
217
- }
218
-
219
- // E(第 11 批·F17/§14.14 E-3d):D5 冻结窗口写前拦截——设计评审在途(点火 → 结算)期间,
220
- // 父侧对被审文件集(声明文档集 + 批次档)的写入会被拒绝:在途写使本轮结算 stale——pass 轮
221
- // = token 直接丢失(实证:第 10 批 id=20 整轮作废)。工具面 = FILE_MUTATORS(与变更记账
222
- // 同集——不记入日志的写面既不判 stale 也不拦);判据与 reviewIsStale 同源
223
- // (inflightDesignReviewConflict——同 docAbs / 同 normAbs;仅扫 running 未取消的设计条目)。
224
- // 位置:只读 / autoApprove 短路之前——审批不得绕过冻结;拒绝 = 可见 denied + 逃生门
225
- // (先 cancel → 改 → 重发)。
226
- if (FILE_MUTATORS.has(toolCall.name)) {
227
- let touched = []
228
- try { touched = tool.touchedPaths ? tool.touchedPaths(args) : [args.path] } catch { touched = [] }
229
- const absPaths = (touched ?? [])
230
- .filter((p) => typeof p === "string" && p)
231
- .map((p) => resolve(agent.cwd, p))
232
- const conflict = inflightDesignReviewConflict(agent, absPaths)
233
- if (conflict) {
234
- prepared.push({
235
- toolCall, tool, denied: true,
236
- reason: "d5 freeze window",
237
- 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.`,
238
- })
239
- continue
240
- }
241
- }
242
-
243
- // Readonly tools (and autoApprove — the short-circuit, unchanged for the
244
- // whole batch too) skip the permission stage entirely.
245
- // §18 D-E3 task-domain authorization (spawn-time): an eng-coder child's
246
- // tools skip the permission ASK stage exactly like autoApprove — granted by
247
- // the parent spawn (approved design + task = authorization; subagent.mjs
248
- // sets _engTaskAuthorized on the child). Everything EARLIER in Phase 1
249
- // (JSON parse / unknown tool / planMode / design-token gates) ran unchanged
250
- // — the exemption never widens what reaches this stage (round4 #3, T-E14).
251
- // PreToolUse hooks still run below. Non-eng-coder children keep the manual
252
- // parent ask (human in the loop).
253
- if (tool.readonly || isSubagentReadonlyAction(toolCall.name, args) || isSubagentControlAction(toolCall.name, args) || isSubagentConsumeDesignAction(toolCall.name, args) || agent.autoApprove || agent._engTaskAuthorized) {
254
- if (!(await runHooks("PreToolUse", { agent, toolName: toolCall.name, toolArgs: args }))) {
255
- prepared.push({ toolCall, tool, denied: true, reason: "blocked by PreToolUse hook" })
256
- continue
257
- }
258
- // Panel area abolished — all tools now stream inline via onToolOutput.
259
- callbacks.onToolCall?.(toolCall.name, args, toolCall.id)
260
- prepared.push({ toolCall, tool, args })
261
- continue
262
- }
263
- permPending.push({ toolCall, tool, args })
264
- }
265
-
266
- // ---- Permission stage: one merged ask for the whole batch (§16 D-B1) ----
267
- // >1 non-readonly tools in the same toolCalls array → a single
268
- // onBatchPermissionRequest({ tools, count }) ask; verdicts:
269
- // "approveAll" → batch-scope allowance (autoApprove style, NOT persistent)
270
- // "deny" → the whole batch is rejected, no second ask
271
- // "oneByOne" (or anything else / no handler) → the existing per-item
272
- // onPermissionRequest channel, signature unchanged (NF-B1: ACP bridge /
273
- // headless / old versions without the new callback are never harmed).
274
- if (permPending.length > 0) {
275
- let batchAllowed = null // true = approveAll, false = deny, null = per-item fallback
276
- if (permPending.length > 1 && callbacks.onBatchPermissionRequest) {
277
- const verdict = await callbacks.onBatchPermissionRequest({
278
- tools: permPending.map((p) => ({ name: p.toolCall.name, args: p.args })),
279
- count: permPending.length,
280
- })
281
- if (verdict === "approveAll") batchAllowed = true
282
- else if (verdict === "deny") batchAllowed = false
283
- // anything else (oneByOne/unknown) → fall through to the per-item channel
284
- }
285
- for (const p of permPending) {
286
- let allowed
287
- if (batchAllowed === true) allowed = true
288
- else if (batchAllowed === false) allowed = false
289
- else if (callbacks.onPermissionRequest) {
290
- allowed = await (async () => {
291
- // D2 (AGENT-LOOP.md §7.2): announce the wait BEFORE prompting — the TUI
292
- // subagent block header flips to "等待审批" so a waiting child is visibly
293
- // different from a stalled one. Depth>0 only (the parent TUI shows its own
294
- // permission panel). turn n/max = the child's live turn counters.
295
- if (depth > 0) {
296
- callbacks.onToken?.(`⟦ev⟧approval\x1e${agent._currentTurn ?? 0}\x1e${agent._maxTurns ?? 0}\x1eapproval\x1e${String(p.toolCall.name).slice(0, 40)}`)
297
- }
298
- return await callbacks.onPermissionRequest(p.toolCall.name, p.args)
299
- })()
300
- } else allowed = false
301
- if (!allowed) {
302
- prepared.push({
303
- toolCall: p.toolCall, tool: p.tool, denied: true,
304
- reason: (callbacks.onPermissionRequest || batchAllowed === false) ? "denied by user" : "no permission handler",
305
- })
306
- continue
307
- }
308
-
309
- // PreToolUse hooks: allow user scripts to gate tool execution
310
- if (!(await runHooks("PreToolUse", { agent, toolName: p.toolCall.name, toolArgs: p.args }))) {
311
- prepared.push({ toolCall: p.toolCall, tool: p.tool, denied: true, reason: "blocked by PreToolUse hook" })
312
- continue
313
- }
314
-
315
- // Panel area abolished — all tools now stream inline via onToolOutput.
316
- callbacks.onToolCall?.(p.toolCall.name, p.args, p.toolCall.id)
317
- prepared.push({ toolCall: p.toolCall, tool: p.tool, args: p.args })
318
- }
319
- }
320
-
321
- // ---- Phase 2: order-preserving execution ----
322
- const runOne = async (item) => {
323
- if (item.error) return { ...item, result: `Error: ${item.error}`, ok: false }
324
- if (item.denied) {
325
- const reason = item.reason === "plan mode"
326
- ? "Error: plan mode is active — only read-only tools are allowed. Exit plan mode first."
327
- : item.reason === "engineering design gate"
328
- ? `Error: design review required before any file modification. ${item.hint}`
329
- : item.reason === "d5 freeze window"
330
- ? `Error: ${item.hint}`
331
- : item.reason === "denied by user"
332
- ? "Error: permission denied by user"
333
- : item.reason === "blocked by PreToolUse hook"
334
- ? "Error: blocked by PreToolUse hook"
335
- : "Error: no permission handler configured — this tool requires user approval but the current context doesn't support interaction (e.g. subagent or non-TUI mode)"
336
- return { ...item, result: reason, ok: false }
337
- }
338
- // 2026-08-31 工具顺手度(用户批准"做吧"):dispatch 拦截工具执行期间的
339
- // console.log/console.error——工具的探查/调试输出(原本只到终端、模型看不到)
340
- // 收集后附在工具结果后回显给模型。bash 工具的输出走子进程回显(onOutput),
341
- // 不走 dispatch console——拦截安全。嵌套 dispatch(subagent)各自拦截/恢复,
342
- // 捕获分离(父恢复原始后子的拦截期间父捕获停止、子恢复后父继续)——正确。
343
- // 声明在 try 之外:catch 块(异常路径)也要访问(报错前的探查输出回显)。
344
- const capturedConsole = []
345
- // LOGGING(LOGGING.md):tool:* 事件——仅真实执行(pre-gate 拦截项在下方早退分支不入事件)。
346
- // 参数值永不落盘(NF-L3——工具事件不记 args);child=子代理 id(agent._logId,spawn 时 stamp)。
347
- const toolT0 = Date.now()
348
- const toolName = item.toolCall.name
349
- logEvent("tool:call", { tool: toolName, child: agent?._logId })
350
- try {
351
- // R10 L3 (MULTI-INSTANCE-COLLAB §2a.5 D-L3b):结构化写工具执行前查 conflicts
352
- // (命中他实例 hot 域 → 结果附软提示——决策⑥ A 不阻止;一次目录 stat——N3 度量);
353
- // 足迹累积(D-L3a——"检测+记录一次完成")延后到执行成功(实际写过的文件)。
354
- const isPeerWriteTool = PEER_WRITE_TOOLS.has(toolName)
355
- const peerNote = isPeerWriteTool ? peerCollabNote(agent.cwd, item.tool, item.args) : null
356
- // Snapshot for undo before side-effect tools (setupOutputPanel already fired in Phase 1)
357
- if (!item.tool?.readonly && item.args) {
358
- snapshotForUndo(agent, item.toolCall.name, item.args, agent.cwd)
359
- }
360
- // M2 ACP: route fs tools through the client (IDE buffer / diff review).
361
- // toolRouter returns { handled: true, result } to short-circuit execution.
362
- if (callbacks.toolRouter) {
363
- const routed = await callbacks.toolRouter(item.toolCall.name, item.args)
364
- if (routed?.handled) {
365
- const routedOk = !String(routed.result).startsWith("Error:")
366
- const routedResult = peerNote && routedOk ? `${routed.result}\n${peerNote}` : routed.result
367
- if (isPeerWriteTool && routedOk) recordPeerWrites(agent, item.tool, item.args)
368
- // §29 fix A:routed 写成功(客户端执行)同样执行期即刻记账(唯一记账点)
369
- if (routedOk && FILE_MUTATORS.has(toolName)) noteExecutedMutation(agent, item.tool, item.args)
370
- callbacks.onToolResult?.(item.toolCall.name, routedResult, item.toolCall.id)
371
- logEvent("tool:done", { tool: toolName, ms: Date.now() - toolT0, head: headText(routedResult, 200), child: agent?._logId })
372
- return { ...item, result: routedResult, ok: true }
373
- }
374
- }
375
- const origConsoleLog = console.log
376
- const origConsoleErr = console.error
377
- console.log = (...a) => capturedConsole.push(a.map(String).join(" "))
378
- console.error = (...a) => capturedConsole.push("[err] " + a.map(String).join(" "))
379
- let rawResult
380
- // ctx 对象提升为变量(§7.2.3):subagent 阻塞 execute 返回前在 ctx 上留
381
- // _subagentKey(relayPrefix 去尾)——runOne 在 execute 返回后读它作 onToolResult
382
- // 第 4 参(普通工具/错误路径无此字段——undefined 兼容既有签名)。每次工具调用
383
- // 独立 ctx——并行同名工具(批并行 runOne)各自带自己的 key,互不串扰。
384
- const toolCtx = {
385
- cwd: agent.cwd,
386
- agent,
387
- depth,
388
- signal,
389
- callbacks,
390
- // §11.2 D-24b: per-call id — the advisor tool marker-keys its launch so
391
- // recordToolResults can split async-ack accounting from sync settles.
392
- _toolCallId: item.toolCall.id,
393
- onOutput: (chunk) => callbacks.onToolOutput?.(item.toolCall.name, chunk, item.toolCall.id),
394
- onQuestion: callbacks.onQuestion,
395
- onPermissionRequest: callbacks.onPermissionRequest,
396
- }
397
- try {
398
- // SUBAGENT-OBSERVE-SEND D1(评审 #1):in-flight 当前工具记账——工具执行期间在
399
- // agent 上留 _inflightTools Set(子代理 observe 从 dispatch 状态读——卡在长工具
400
- // 调用时 history 无新回合、恰需此信号);finally 清除。批并行工具同入 Set(observe
401
- // 如实返回多个在跑工具)。主会话同样记账——无害(无人读)。
402
- const inflight = agent._inflightTools ?? (agent._inflightTools = new Set())
403
- inflight.add(toolName)
404
- try {
405
- rawResult = await item.tool.execute(item.args, toolCtx)
406
- } finally {
407
- inflight.delete(toolName)
408
- }
409
- } finally {
410
- console.log = origConsoleLog
411
- console.error = origConsoleErr
412
- }
413
- if (rawResult === undefined) throw new Error(`Tool "${item.toolCall.name}" returned undefined — all tools must return a string value`)
414
- const raw = String(rawResult)
415
- // 写成功(非 "Error:" 字符串结果)→ 足迹计入本回合集合(flush 在 finalizeAgentTurn)
416
- if (isPeerWriteTool && !raw.startsWith("Error:")) {
417
- recordPeerWrites(agent, item.tool, item.args)
418
- }
419
- // §29 fix A:FILE_MUTATORS 执行成功即刻记账(唯一记账点——取代 record-results 批后
420
- // 段 + agent.mjs 中断分支——不双计)——同批 launch 前的写在 launchSeq 之前落地 →
421
- // async advisor settle 不误判 stale(同批 launch 后写仍保守 stale——T-A2/T-24b9)。
422
- if (FILE_MUTATORS.has(toolName) && !raw.startsWith("Error:")) {
423
- noteExecutedMutation(agent, item.tool, item.args)
424
- }
425
- // Multimodal tools keep the raw result (base64 images ride the multimodal
426
- // channel); everything else offloads oversized text to disk. Flag-driven, not
427
- // name-driven (consult P3, 2026-08-30).
428
- const result = item.tool?.multimodal ? raw : await offloadToolResult(raw, item.toolCall.id)
429
- // 2026-08-31:工具执行期间捕获的 console 输出附在结果后回显(模型视野)
430
- const resultWithConsole = capturedConsole.length > 0
431
- ? `${result}\n[console during ${item.toolCall.name}]\n${capturedConsole.join("\n")}`
432
- : result
433
- // R10 L3:冲突软提示附在工具结果末尾(模型可见——不阻止写)
434
- const resultForModel = peerNote && !raw.startsWith("Error:")
435
- ? `${resultWithConsole}\n${peerNote}`
436
- : resultWithConsole
437
- callbacks.onToolResult?.(item.toolCall.name, resultForModel, item.toolCall.id, toolCtx._subagentKey)
438
- // PostToolUse hooks: fire-and-forget (result not awaited on hook failure)
439
- runHooks("PostToolUse", { agent, toolName: item.toolCall.name, toolArgs: item.args, result: raw }).catch(() => {})
440
- logEvent("tool:done", { tool: toolName, ms: Date.now() - toolT0, head: headText(resultForModel, 200), child: agent?._logId })
441
- return { ...item, result: resultForModel, ok: true }
442
- } catch (error) {
443
- // Persist to ~/.thincoder/tool-errors/ for post-mortem; only pass message to the model (stack traces confuse LLMs and may leak paths)
444
- logToolError(item.toolCall.name, item.args, error)
445
- // User interrupt (Ctrl+C / Ctrl+I) must propagate, not become a tool error:
446
- // swallowing it here would make the parent keep looping while the user
447
- // asked to stop — worst case with subagents, where the child runs its
448
- // whole turn budget and the interrupt appears to do nothing.
449
- if (signal?.aborted) throw error
450
- // LOGGING(2026-09-03 code review #4):中止先于事件——用户停不落 tool:error
451
- //(vscode execute-tools parity;阻塞子代理 child:error 同款抑制)
452
- logEvent("tool:error", { tool: toolName, ms: Date.now() - toolT0, err: errText(error, 200), child: agent?._logId })
453
- runHooks("PostToolUseFailure", { agent, toolName: item.toolCall.name, toolArgs: item.args, error }).catch(() => {})
454
- // Build contextual error: tool name + key args so the model can reason about what went wrong
455
- const ctxParts = []
456
- if (item.args.path) ctxParts.push(`path=${item.args.path}`)
457
- if (item.args.pattern) ctxParts.push(`pattern=${item.args.pattern}`)
458
- if (item.args.command) ctxParts.push(`cmd=${item.args.command.slice(0, 80)}`)
459
- const ctx = ctxParts.length > 0 ? ` [${ctxParts.join(", ")}]` : ""
460
- // 2026-08-31:异常路径同样回显捕获的 console(工具报错前的探查输出最有价值)
461
- const consolePart = capturedConsole.length > 0
462
- ? `\n[console during ${item.toolCall.name}]\n${capturedConsole.join("\n")}`
463
- : ""
464
- return { ...item, result: `Error: ${error.message}${ctx}${consolePart}`, ok: false }
465
- }
466
- }
467
-
468
- const results = []
469
- let batch = []
470
- const flush = async () => {
471
- if (batch.length === 0) return
472
- results.push(...await Promise.all(batch.map(runOne)))
473
- batch = []
474
- }
475
- for (const item of prepared) {
476
- // escalate action keeps the retired escalate tool's serial placement (no
477
- // parallel flag): it flushes the batch and runs alone in call order (§19 —
478
- // spawn stays parallel; status classifies as readonly and batch freely).
479
- if (item.tool && !item.tool.readonly
480
- && (!item.tool.parallel || isSubagentEscalateAction(item.tool.name, item.args))) {
481
- await flush()
482
- results.push(await runOne(item))
483
- } else {
484
- batch.push(item)
485
- }
486
- }
487
- await flush()
488
- return results
489
- }