thincoder 0.12.62 → 0.12.63

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 (228) hide show
  1. package/CHANGELOG.md +9 -0
  2. package/README.md +13 -12
  3. package/bin/thincoder.mjs +53 -27
  4. package/package.json +6 -5
  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 +240 -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 +59 -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 +25 -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-reindex.mjs +1 -1
  31. package/src/tui/cmd-restore.mjs +2 -2
  32. package/src/tui/cmd-session.mjs +24 -1
  33. package/src/tui/cmd-skills.mjs +1 -1
  34. package/src/tui/cmd-think.mjs +22 -9
  35. package/src/tui/config-helpers.mjs +1 -1
  36. package/src/tui/display-budget.mjs +33 -11
  37. package/src/tui/index.mjs +9 -9
  38. package/src/tui/interaction.mjs +16 -7
  39. package/src/tui/key-modes.mjs +9 -4
  40. package/src/tui/ledger-surface.mjs +26 -10
  41. package/src/tui/model-catalog.mjs +4 -4
  42. package/src/tui/model-picker.mjs +8 -7
  43. package/src/tui/mouse.mjs +11 -6
  44. package/src/tui/pickers.mjs +15 -2
  45. package/src/tui/render-conversation.mjs +1 -1
  46. package/src/tui/render-frame.mjs +10 -5
  47. package/src/tui/render-loop.mjs +1 -1
  48. package/src/tui/render-segments.mjs +3 -1
  49. package/src/tui/slash-commands.mjs +1 -1
  50. package/src/tui/startup.mjs +14 -14
  51. package/src/tui/subagent-blocks.mjs +20 -3
  52. package/src/tui/subagent-freeze.mjs +73 -2
  53. package/src/tui/suspension-drive.mjs +46 -22
  54. package/src/tui/tool-events.mjs +11 -8
  55. package/src/tui/wizard.mjs +3 -3
  56. package/src/abort-provenance.mjs +0 -116
  57. package/src/advisor/citations.mjs +0 -139
  58. package/src/advisor/compaction.mjs +0 -174
  59. package/src/advisor/convergence.mjs +0 -80
  60. package/src/advisor/history.mjs +0 -77
  61. package/src/advisor/loop.mjs +0 -293
  62. package/src/advisor/messages.mjs +0 -299
  63. package/src/advisor/project-context.mjs +0 -194
  64. package/src/advisor/repos.mjs +0 -150
  65. package/src/advisor/run.mjs +0 -293
  66. package/src/advisor/truncate.mjs +0 -57
  67. package/src/advisor.mjs +0 -290
  68. package/src/agent/completion.mjs +0 -146
  69. package/src/agent/dispatch.mjs +0 -489
  70. package/src/agent/helpers.mjs +0 -384
  71. package/src/agent/post-turn.mjs +0 -70
  72. package/src/agent/record-results.mjs +0 -174
  73. package/src/agent/relay-prefix.mjs +0 -39
  74. package/src/agent/run-stages.mjs +0 -244
  75. package/src/agent/setup-reminders.mjs +0 -69
  76. package/src/agent/setup.mjs +0 -354
  77. package/src/agent/spawn-child.mjs +0 -243
  78. package/src/agent-tools/advisor-async.mjs +0 -346
  79. package/src/agent-tools/advisor-settle.mjs +0 -231
  80. package/src/agent-tools/advisor.mjs +0 -260
  81. package/src/agent-tools/async-settle.mjs +0 -204
  82. package/src/agent-tools/batch-segment.mjs +0 -195
  83. package/src/agent-tools/consult.mjs +0 -473
  84. package/src/agent-tools/design-token.mjs +0 -117
  85. package/src/agent-tools/digest-budget.mjs +0 -76
  86. package/src/agent-tools/eng.mjs +0 -67
  87. package/src/agent-tools/escalate-async.mjs +0 -295
  88. package/src/agent-tools/goal.mjs +0 -119
  89. package/src/agent-tools/plan.mjs +0 -81
  90. package/src/agent-tools/read-history.mjs +0 -309
  91. package/src/agent-tools/recent-changes.mjs +0 -24
  92. package/src/agent-tools/review-streak.mjs +0 -93
  93. package/src/agent-tools/settings.mjs +0 -265
  94. package/src/agent-tools/skill.mjs +0 -47
  95. package/src/agent-tools/subagent-actions.mjs +0 -482
  96. package/src/agent-tools/subagent-async.mjs +0 -434
  97. package/src/agent-tools/subagent-panel.mjs +0 -160
  98. package/src/agent-tools/subagent-run.mjs +0 -205
  99. package/src/agent-tools/subagent-scheduler.mjs +0 -392
  100. package/src/agent-tools/subagent-spawn.mjs +0 -459
  101. package/src/agent-tools/subagent.mjs +0 -404
  102. package/src/agent-tools/task.mjs +0 -87
  103. package/src/agent-tools/timer.mjs +0 -46
  104. package/src/agent-tools/verify.mjs +0 -271
  105. package/src/agent-tools.mjs +0 -17
  106. package/src/agent.mjs +0 -417
  107. package/src/auto-think.mjs +0 -115
  108. package/src/config-migrate.mjs +0 -70
  109. package/src/config.mjs +0 -496
  110. package/src/context.mjs +0 -392
  111. package/src/conventions.mjs +0 -223
  112. package/src/embedding.mjs +0 -120
  113. package/src/escape.mjs +0 -152
  114. package/src/expand-home.mjs +0 -16
  115. package/src/explore-distill.mjs +0 -155
  116. package/src/generate-title.mjs +0 -88
  117. package/src/git/checkpoint.mjs +0 -448
  118. package/src/git/gitmem.mjs +0 -100
  119. package/src/hooks.mjs +0 -97
  120. package/src/ledger.mjs +0 -227
  121. package/src/log.mjs +0 -195
  122. package/src/markdown.mjs +0 -106
  123. package/src/mcp/helpers.mjs +0 -51
  124. package/src/mcp/transport-http.mjs +0 -248
  125. package/src/mcp/transport-stdio.mjs +0 -140
  126. package/src/mcp/transport-ws.mjs +0 -122
  127. package/src/mcp.mjs +0 -295
  128. package/src/memory/code-index.mjs +0 -219
  129. package/src/memory/code-sync.mjs +0 -415
  130. package/src/memory/core.mjs +0 -299
  131. package/src/memory/delete.mjs +0 -236
  132. package/src/memory/docs.mjs +0 -419
  133. package/src/memory/file-walk.mjs +0 -109
  134. package/src/memory/scan.mjs +0 -95
  135. package/src/memory/schema.mjs +0 -452
  136. package/src/memory.mjs +0 -21
  137. package/src/model-ref.mjs +0 -66
  138. package/src/model-specs.mjs +0 -179
  139. package/src/peer-domains.mjs +0 -265
  140. package/src/peer-instances.mjs +0 -231
  141. package/src/prompt-overlays.mjs +0 -82
  142. package/src/prompts/advisor-design.md +0 -41
  143. package/src/prompts/advisor-round1.md +0 -41
  144. package/src/prompts/advisor-round2.md +0 -46
  145. package/src/prompts/advisor-round3.md +0 -42
  146. package/src/prompts/common.md +0 -115
  147. package/src/prompts/consult-base.md +0 -19
  148. package/src/prompts/discipline-engineering.md +0 -258
  149. package/src/prompts/discipline-normal.md +0 -185
  150. package/src/prompts/persona-coder.md +0 -21
  151. package/src/prompts/persona-eng-coder.md +0 -37
  152. package/src/prompts/persona-eng-designer.md +0 -60
  153. package/src/prompts/persona-engineering.md +0 -55
  154. package/src/prompts/persona-explore.md +0 -15
  155. package/src/prompts/persona-normal.md +0 -27
  156. package/src/prompts/persona-plan.md +0 -26
  157. package/src/provider/anthropic.mjs +0 -225
  158. package/src/provider/core.mjs +0 -476
  159. package/src/provider/errors.mjs +0 -101
  160. package/src/provider/google.mjs +0 -257
  161. package/src/provider/index.mjs +0 -7
  162. package/src/provider/list-models.mjs +0 -93
  163. package/src/provider/normalize.mjs +0 -81
  164. package/src/provider/rate.mjs +0 -108
  165. package/src/provider/responses.mjs +0 -495
  166. package/src/provider/retry.mjs +0 -88
  167. package/src/provider/sse.mjs +0 -264
  168. package/src/proxy.mjs +0 -261
  169. package/src/rules.mjs +0 -53
  170. package/src/session-gc.mjs +0 -221
  171. package/src/session-guard.mjs +0 -59
  172. package/src/session-migrate.mjs +0 -48
  173. package/src/session-rename.mjs +0 -38
  174. package/src/session-segments.mjs +0 -100
  175. package/src/session-slots.mjs +0 -492
  176. package/src/session-store.mjs +0 -441
  177. package/src/session.mjs +0 -492
  178. package/src/skills.mjs +0 -153
  179. package/src/text-budget.mjs +0 -46
  180. package/src/token-ttl.mjs +0 -274
  181. package/src/tools/apply_patch.md +0 -15
  182. package/src/tools/bash.md +0 -37
  183. package/src/tools/bash.mjs +0 -268
  184. package/src/tools/checklist-sync.mjs +0 -181
  185. package/src/tools/checklist.md +0 -13
  186. package/src/tools/checklist.mjs +0 -299
  187. package/src/tools/delete.md +0 -13
  188. package/src/tools/edit-batch.mjs +0 -191
  189. package/src/tools/edit-diff.mjs +0 -348
  190. package/src/tools/edit.md +0 -30
  191. package/src/tools/execute.md +0 -21
  192. package/src/tools/execute.mjs +0 -228
  193. package/src/tools/fetch.md +0 -12
  194. package/src/tools/file.mjs +0 -469
  195. package/src/tools/file_ops.md +0 -17
  196. package/src/tools/get_current_time.md +0 -8
  197. package/src/tools/git-checkpoint.mjs +0 -143
  198. package/src/tools/git-ext.mjs +0 -173
  199. package/src/tools/git.md +0 -54
  200. package/src/tools/git.mjs +0 -356
  201. package/src/tools/glob-dialect.mjs +0 -130
  202. package/src/tools/glob.md +0 -11
  203. package/src/tools/grep.md +0 -19
  204. package/src/tools/hashline_edit.md +0 -14
  205. package/src/tools/index.mjs +0 -36
  206. package/src/tools/insert_after.md +0 -15
  207. package/src/tools/lint.md +0 -10
  208. package/src/tools/linter.mjs +0 -128
  209. package/src/tools/ls.md +0 -12
  210. package/src/tools/lsp.md +0 -10
  211. package/src/tools/lsp.mjs +0 -316
  212. package/src/tools/ops.mjs +0 -299
  213. package/src/tools/patch.mjs +0 -282
  214. package/src/tools/process.md +0 -10
  215. package/src/tools/question.md +0 -16
  216. package/src/tools/question.mjs +0 -26
  217. package/src/tools/read.md +0 -20
  218. package/src/tools/read_image.md +0 -8
  219. package/src/tools/repomap.mjs +0 -314
  220. package/src/tools/search.mjs +0 -236
  221. package/src/tools/shared.mjs +0 -446
  222. package/src/tools/tree.md +0 -14
  223. package/src/tools/tree.mjs +0 -66
  224. package/src/tools/wait_for.md +0 -22
  225. package/src/tools/web.mjs +0 -224
  226. package/src/tools/websearch.md +0 -16
  227. package/src/tools/write.md +0 -11
  228. package/src/traces/trace-store.mjs +0 -355
@@ -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
- }