thincoder 0.12.61 → 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 (230) hide show
  1. package/CHANGELOG.md +34 -1
  2. package/README.md +13 -12
  3. package/bin/thincoder.mjs +63 -28
  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 -371
  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 +32 -10
  20. package/src/distill.mjs +4 -4
  21. package/src/heap-watch.mjs +88 -0
  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-clear.mjs +2 -0
  26. package/src/tui/cmd-config.mjs +8 -8
  27. package/src/tui/cmd-eng.mjs +25 -9
  28. package/src/tui/cmd-mcp.mjs +9 -8
  29. package/src/tui/cmd-model.mjs +1 -1
  30. package/src/tui/cmd-new.mjs +10 -5
  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 +31 -4
  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 +206 -0
  38. package/src/tui/index.mjs +40 -12
  39. package/src/tui/interaction.mjs +16 -7
  40. package/src/tui/key-handler-search.mjs +9 -1
  41. package/src/tui/key-modes.mjs +9 -4
  42. package/src/tui/ledger-surface.mjs +85 -0
  43. package/src/tui/model-catalog.mjs +4 -4
  44. package/src/tui/model-picker.mjs +8 -7
  45. package/src/tui/mouse.mjs +11 -6
  46. package/src/tui/pickers.mjs +15 -2
  47. package/src/tui/render-conversation.mjs +1 -1
  48. package/src/tui/render-frame.mjs +17 -6
  49. package/src/tui/render-loop.mjs +1 -1
  50. package/src/tui/render-segments.mjs +3 -1
  51. package/src/tui/slash-commands.mjs +1 -1
  52. package/src/tui/startup.mjs +49 -17
  53. package/src/tui/subagent-blocks.mjs +21 -3
  54. package/src/tui/subagent-children.mjs +86 -14
  55. package/src/tui/subagent-freeze.mjs +80 -3
  56. package/src/tui/suspension-drive.mjs +48 -22
  57. package/src/tui/tool-args.mjs +5 -2
  58. package/src/tui/tool-display.mjs +16 -2
  59. package/src/tui/tool-events.mjs +64 -22
  60. package/src/tui/tui-lifecycle.mjs +9 -2
  61. package/src/tui/wizard.mjs +3 -3
  62. package/src/tui/wrapped-spawn.mjs +21 -5
  63. package/src/abort-provenance.mjs +0 -116
  64. package/src/advisor/citations.mjs +0 -139
  65. package/src/advisor/compaction.mjs +0 -174
  66. package/src/advisor/convergence.mjs +0 -80
  67. package/src/advisor/history.mjs +0 -77
  68. package/src/advisor/loop.mjs +0 -293
  69. package/src/advisor/messages.mjs +0 -299
  70. package/src/advisor/project-context.mjs +0 -194
  71. package/src/advisor/repos.mjs +0 -150
  72. package/src/advisor/run.mjs +0 -293
  73. package/src/advisor/truncate.mjs +0 -57
  74. package/src/advisor.mjs +0 -290
  75. package/src/agent/completion.mjs +0 -146
  76. package/src/agent/dispatch.mjs +0 -489
  77. package/src/agent/helpers.mjs +0 -384
  78. package/src/agent/post-turn.mjs +0 -70
  79. package/src/agent/record-results.mjs +0 -174
  80. package/src/agent/relay-prefix.mjs +0 -39
  81. package/src/agent/run-stages.mjs +0 -242
  82. package/src/agent/setup-reminders.mjs +0 -69
  83. package/src/agent/setup.mjs +0 -354
  84. package/src/agent/spawn-child.mjs +0 -228
  85. package/src/agent-tools/advisor-async.mjs +0 -346
  86. package/src/agent-tools/advisor-settle.mjs +0 -231
  87. package/src/agent-tools/advisor.mjs +0 -260
  88. package/src/agent-tools/async-settle.mjs +0 -191
  89. package/src/agent-tools/batch-segment.mjs +0 -195
  90. package/src/agent-tools/consult.mjs +0 -468
  91. package/src/agent-tools/design-token.mjs +0 -117
  92. package/src/agent-tools/digest-budget.mjs +0 -76
  93. package/src/agent-tools/eng.mjs +0 -67
  94. package/src/agent-tools/escalate-async.mjs +0 -289
  95. package/src/agent-tools/goal.mjs +0 -119
  96. package/src/agent-tools/plan.mjs +0 -81
  97. package/src/agent-tools/read-history.mjs +0 -294
  98. package/src/agent-tools/recent-changes.mjs +0 -24
  99. package/src/agent-tools/review-streak.mjs +0 -93
  100. package/src/agent-tools/settings.mjs +0 -265
  101. package/src/agent-tools/skill.mjs +0 -47
  102. package/src/agent-tools/subagent-actions.mjs +0 -479
  103. package/src/agent-tools/subagent-async.mjs +0 -434
  104. package/src/agent-tools/subagent-panel.mjs +0 -160
  105. package/src/agent-tools/subagent-run.mjs +0 -205
  106. package/src/agent-tools/subagent-scheduler.mjs +0 -392
  107. package/src/agent-tools/subagent-spawn.mjs +0 -453
  108. package/src/agent-tools/subagent.mjs +0 -404
  109. package/src/agent-tools/task.mjs +0 -87
  110. package/src/agent-tools/timer.mjs +0 -46
  111. package/src/agent-tools/verify.mjs +0 -271
  112. package/src/agent-tools.mjs +0 -17
  113. package/src/agent.mjs +0 -413
  114. package/src/auto-think.mjs +0 -115
  115. package/src/config-migrate.mjs +0 -70
  116. package/src/config.mjs +0 -496
  117. package/src/context.mjs +0 -381
  118. package/src/conventions.mjs +0 -223
  119. package/src/embedding.mjs +0 -120
  120. package/src/escape.mjs +0 -152
  121. package/src/expand-home.mjs +0 -16
  122. package/src/explore-distill.mjs +0 -155
  123. package/src/generate-title.mjs +0 -83
  124. package/src/git/checkpoint.mjs +0 -448
  125. package/src/git/gitmem.mjs +0 -100
  126. package/src/hooks.mjs +0 -97
  127. package/src/log.mjs +0 -195
  128. package/src/markdown.mjs +0 -106
  129. package/src/mcp/helpers.mjs +0 -51
  130. package/src/mcp/transport-http.mjs +0 -248
  131. package/src/mcp/transport-stdio.mjs +0 -140
  132. package/src/mcp/transport-ws.mjs +0 -122
  133. package/src/mcp.mjs +0 -295
  134. package/src/memory/code-index.mjs +0 -219
  135. package/src/memory/code-sync.mjs +0 -413
  136. package/src/memory/core.mjs +0 -300
  137. package/src/memory/delete.mjs +0 -236
  138. package/src/memory/docs.mjs +0 -417
  139. package/src/memory/file-walk.mjs +0 -109
  140. package/src/memory/schema.mjs +0 -452
  141. package/src/memory.mjs +0 -21
  142. package/src/model-ref.mjs +0 -66
  143. package/src/model-specs.mjs +0 -179
  144. package/src/peer-domains.mjs +0 -265
  145. package/src/peer-instances.mjs +0 -231
  146. package/src/prompt-overlays.mjs +0 -82
  147. package/src/prompts/advisor-design.md +0 -41
  148. package/src/prompts/advisor-round1.md +0 -41
  149. package/src/prompts/advisor-round2.md +0 -46
  150. package/src/prompts/advisor-round3.md +0 -42
  151. package/src/prompts/common.md +0 -115
  152. package/src/prompts/consult-base.md +0 -19
  153. package/src/prompts/discipline-engineering.md +0 -217
  154. package/src/prompts/discipline-normal.md +0 -179
  155. package/src/prompts/persona-coder.md +0 -21
  156. package/src/prompts/persona-eng-coder.md +0 -37
  157. package/src/prompts/persona-eng-designer.md +0 -55
  158. package/src/prompts/persona-engineering.md +0 -54
  159. package/src/prompts/persona-explore.md +0 -15
  160. package/src/prompts/persona-normal.md +0 -27
  161. package/src/prompts/persona-plan.md +0 -26
  162. package/src/provider/anthropic.mjs +0 -225
  163. package/src/provider/core.mjs +0 -476
  164. package/src/provider/errors.mjs +0 -101
  165. package/src/provider/google.mjs +0 -257
  166. package/src/provider/index.mjs +0 -7
  167. package/src/provider/list-models.mjs +0 -93
  168. package/src/provider/normalize.mjs +0 -81
  169. package/src/provider/rate.mjs +0 -108
  170. package/src/provider/responses.mjs +0 -495
  171. package/src/provider/retry.mjs +0 -88
  172. package/src/provider/sse.mjs +0 -264
  173. package/src/proxy.mjs +0 -261
  174. package/src/rules.mjs +0 -53
  175. package/src/session-gc.mjs +0 -214
  176. package/src/session-guard.mjs +0 -47
  177. package/src/session-migrate.mjs +0 -48
  178. package/src/session-rename.mjs +0 -38
  179. package/src/session-slots.mjs +0 -489
  180. package/src/session.mjs +0 -475
  181. package/src/skills.mjs +0 -153
  182. package/src/token-ttl.mjs +0 -274
  183. package/src/tools/apply_patch.md +0 -15
  184. package/src/tools/bash.md +0 -37
  185. package/src/tools/bash.mjs +0 -268
  186. package/src/tools/checklist-sync.mjs +0 -181
  187. package/src/tools/checklist.md +0 -13
  188. package/src/tools/checklist.mjs +0 -299
  189. package/src/tools/delete.md +0 -13
  190. package/src/tools/edit-batch.mjs +0 -191
  191. package/src/tools/edit-diff.mjs +0 -348
  192. package/src/tools/edit.md +0 -30
  193. package/src/tools/execute.md +0 -21
  194. package/src/tools/execute.mjs +0 -228
  195. package/src/tools/fetch.md +0 -12
  196. package/src/tools/file.mjs +0 -469
  197. package/src/tools/file_ops.md +0 -17
  198. package/src/tools/get_current_time.md +0 -8
  199. package/src/tools/git-checkpoint.mjs +0 -143
  200. package/src/tools/git-ext.mjs +0 -173
  201. package/src/tools/git.md +0 -54
  202. package/src/tools/git.mjs +0 -356
  203. package/src/tools/glob-dialect.mjs +0 -130
  204. package/src/tools/glob.md +0 -11
  205. package/src/tools/grep.md +0 -19
  206. package/src/tools/hashline_edit.md +0 -14
  207. package/src/tools/index.mjs +0 -36
  208. package/src/tools/insert_after.md +0 -15
  209. package/src/tools/lint.md +0 -10
  210. package/src/tools/linter.mjs +0 -128
  211. package/src/tools/ls.md +0 -12
  212. package/src/tools/lsp.md +0 -10
  213. package/src/tools/lsp.mjs +0 -316
  214. package/src/tools/ops.mjs +0 -299
  215. package/src/tools/patch.mjs +0 -282
  216. package/src/tools/process.md +0 -10
  217. package/src/tools/question.md +0 -16
  218. package/src/tools/question.mjs +0 -26
  219. package/src/tools/read.md +0 -20
  220. package/src/tools/read_image.md +0 -8
  221. package/src/tools/repomap.mjs +0 -314
  222. package/src/tools/search.mjs +0 -236
  223. package/src/tools/shared.mjs +0 -446
  224. package/src/tools/tree.md +0 -14
  225. package/src/tools/tree.mjs +0 -66
  226. package/src/tools/wait_for.md +0 -22
  227. package/src/tools/web.mjs +0 -224
  228. package/src/tools/websearch.md +0 -16
  229. package/src/tools/write.md +0 -11
  230. package/src/traces/trace-store.mjs +0 -224
@@ -1,468 +0,0 @@
1
- /**
2
- * consult.mjs — multi-model consultation ("会诊", docs/design/CONSULTATION.md). CLI port.
3
- *
4
- * Two tools (AGENT-LOOP.md §25 D-R17a — R17, 2026-09-06): consult_start
5
- * (non-blocking spawn) / consult_stop (cancel a running session). consult_check
6
- * was RETIRED with the digest auto-injection: the mechanism does ZERO judging —
7
- * when every model of a session settles (pending 0), the session moves to the
8
- * pending single container (`_pendingAsyncResults` +role "consult"——
9
- * ASYNC-RESULT-CONTAINER.md D2——升格完整 entry) and the NEXT run start (user turn
10
- * or digest auto-turn) injects the full verdict text ("[System reminder:
11
- * consultation #id finished — N replies …]" — per-model status annotations on
12
- * partial/full failures) for the main agent to judge and act on in the digestion
13
- * round. A cancelled session (consult_stop) never reaches the stream.
14
- *
15
- * CLI adaptation (vs the VS Code plugin): the child runner is CLI's runAgent
16
- * (runAgent(child, input, callbacks, opts) — an agent object, not provider+cwd);
17
- * children are built with createAgent({ role: "consult", readonly tools,
18
- * CONSULT_BASE overlay }); activity streams to the parent TUI via the relay
19
- * prefix `consult#<childRelayN>/` (one per consultant child — the shared subagent
20
- * relay channel; the child relay number is NOT the session id — sessions key
21
- * their own `_consultIdCounter`), not onSubagent/onToolPanel.
22
- * Each child settles its own TUI block with a ⟦ev⟧done event at settle (R17 —
23
- * the old in-turn check consumption is gone).
24
- */
25
- import { createAgent, runAgent, readonlyToolNames } from "../agent.mjs"
26
- import { resolveChildProvider } from "./subagent.mjs"
27
- import { pushReal } from "../context.mjs"
28
- import { offloadToolResult, escapeXml } from "../agent/helpers.mjs"
29
- import { logEvent, errText } from "../log.mjs"
30
- import { deathLine } from "../abort-provenance.mjs"
31
- import { makeRelay, wrapChildCallbacks, runWithContinue, ensureChildApiKey, clampEffort } from "../agent/spawn-child.mjs"
32
- // ASYNC-RESULT-CONTAINER.md D2/D3/D6:pending 单容器停靠 + settle 公共收尾 + child signal 单点
33
- import { buildChildSignal, settleAsyncEntry } from "./async-settle.mjs"
34
- import { digestBudgetOver, persistOverflowReport } from "./digest-budget.mjs" // B5(群 B 批 §22 D-DG2):digest 注入预算单源
35
-
36
- // Named consult defaults (consult P2, 2026-08-30).
37
- const CONSULT_TIMEOUT_MS = 600_000 // default consult lifecycle timeout
38
- const CONSULT_TURNS = 40 // default per-child turn cap
39
-
40
-
41
- function consultLabel(m) {
42
- return `${m.provider}:${m.model}`
43
- }
44
-
45
- /** Narrow the configured consultModels pool to a requested subset.
46
- * Each selector is "provider:model", a bare provider name, or a bare model name
47
- * (case-insensitive). A trailing " (effort)" suffix is tolerated (round2 复核
48
- * 对齐 escalate 动作(subagent action:"escalate"):withPool 列表会带 " (high)" 后缀,模型照抄应可匹配).
49
- * Returns { models, error } — error set when a selector matches
50
- * nothing (surface the typo rather than silently dropping it). Absent/empty selectors
51
- * → the full pool. */
52
- function selectConsultModels(pool, selectors) {
53
- if (selectors == null || (Array.isArray(selectors) && selectors.length === 0)) return { models: pool, error: null }
54
- const list = Array.isArray(selectors) ? selectors : [selectors] // coerce a bare string → [string]
55
- const selected = []
56
- const seen = new Set()
57
- const unknowns = []
58
- for (const raw of list) {
59
- const s = String(raw).replace(/\s+\([^)]*\)\s*$/, "").trim().toLowerCase()
60
- const matches = pool.filter((m) =>
61
- consultLabel(m).toLowerCase() === s ||
62
- String(m.provider ?? "").toLowerCase() === s ||
63
- String(m.model ?? "").toLowerCase() === s,
64
- )
65
- if (matches.length === 0) unknowns.push(String(raw))
66
- else for (const m of matches) {
67
- const key = consultLabel(m)
68
- if (!seen.has(key)) { seen.add(key); selected.push(m) }
69
- }
70
- }
71
- if (unknowns.length > 0) {
72
- return { models: null, error: `unknown consult model selector(s): ${unknowns.join(", ")} — choose from: ${pool.map(consultLabel).join(", ")}` }
73
- }
74
- return { models: selected, error: null }
75
- }
76
-
77
- /** Read-only tool injected into consultation children (via createAgent's tools).
78
- * Lets the consultant pull the main agent's conversation history on demand —
79
- * the failure trail is first-class evidence, not a retelling. */
80
- export function makeMainHistoryTool(parentAgent) {
81
- return {
82
- name: "main_history",
83
- readonly: true,
84
- description:
85
- "Read the main agent's conversation history — what has been tried, the exact errors, recent context. " +
86
- "Use it to ground your analysis in the actual failure trail instead of guessing.\n" +
87
- "Parameters:\n" +
88
- "- limit: Number of recent messages to return (default 20, max 100)",
89
- parameters: {
90
- type: "object",
91
- properties: { limit: { type: "number", description: "Recent messages (default 20, max 100)" } },
92
- },
93
- async execute({ limit }) {
94
- const n = Math.min(Math.max(limit ?? 20, 1), 100)
95
- const h = parentAgent?.history ?? []
96
- const slice = h.slice(-n)
97
- if (slice.length === 0) return "(empty history)"
98
- const render = (m) => {
99
- let content
100
- if (typeof m.content === "string") content = m.content
101
- else if (Array.isArray(m.content)) {
102
- content = m.content.map((part) => {
103
- if (part?.type === "image_url" || part?.type === "image") return "[image omitted]"
104
- if (part?.type === "text") return part.text ?? ""
105
- return JSON.stringify(part)
106
- }).join("\n")
107
- } else content = m.content == null ? "" : JSON.stringify(m.content)
108
- const calls = Array.isArray(m.tool_calls)
109
- ? m.tool_calls.map((c) => `[tool: ${c.function?.name ?? c.name}(${String(c.function?.arguments ?? c.args ?? "").slice(0, 200)})]`).join("\n")
110
- : ""
111
- return `--- [${m.role}] ---\n${content}${calls ? "\n" + calls : ""}`
112
- }
113
- const BUDGET = 60_000 // per-consult token budget (tokens)
114
- let out = ""
115
- for (let i = slice.length - 1; i >= 0; i--) {
116
- const line = render(slice[i])
117
- if (out.length + line.length > BUDGET) {
118
- // A single message over the whole budget: truncate IT (it is the newest
119
- // and most relevant) instead of dropping everything with a misleading
120
- // "earlier messages trimmed" note. Older accumulation still trims.
121
- if (out === "") { out = line.slice(0, BUDGET) + "\n(… truncated — single message exceeded budget " + BUDGET + " chars)"; break }
122
- out = `(earlier messages trimmed — budget ${BUDGET} chars)\n\n` + out
123
- break
124
- }
125
- out = out ? line + "\n\n" + out : line
126
- }
127
- return out
128
- },
129
- }
130
- }
131
-
132
- /**
133
- * Full-session settle routing (R17 — AGENT-LOOP.md §25 D-R17a): a session whose
134
- * pending count reached 0 has no more replies coming — the session leaves
135
- * `_consultSessions` and, unless it was cancelled (consult_stop / turn-end
136
- * abort), moves into the pending single container (`_pendingAsyncResults` +role
137
- * "consult"——ASYNC-RESULT-CONTAINER.md D2——升格完整 entry:同 subagent/advisor/
138
- * escalate 的 `{id, role, report, done, ...}` 形态)whose report carries the full
139
- * per-model verdict text (composed here — all settle states are known,
140
- * partial/full failures annotated per model). The entry is injected at the next
141
- * run start (user turn or digest auto-turn — agent.mjs); the suspension driver
142
- * is woken (settle-event parity with the async pools) so an idle settle still
143
- * triggers the digestion round (T-R17j).
144
- * D3:公共收尾统一走 settleAsyncEntry 共享 helper(四族同机制)——consult 族参数:
145
- * 无池(会话池无条目——settle 即出池)、无 ctx(无 TUI 冻结事件——子块各自 settle 时
146
- * 已冻结)、无 onAccounting;helper 按 role "consult" 恒停靠 pending(非挂起期也停靠)。
147
- * Cancelled sessions produce no digest (T-R17c).
148
- */
149
- function sessionSettled(agent, session) {
150
- agent?._consultSessions?.delete(String(session.id))
151
- if (session.stopped) return // cancelled — no digest (T-R17c)
152
- const entry = {
153
- id: String(session.id),
154
- role: "consult",
155
- report: composeConsultDigest(session),
156
- error: null, done: true, status: "done", cancelled: false,
157
- relayPrefix: null, startedAt: null, _settle: null, _settleSeq: 0,
158
- }
159
- settleAsyncEntry(agent, entry, { pool: null, ctx: null })
160
- }
161
-
162
- /** Digest body for a fully-settled session — title + one annotated line per
163
- * reply (failed replies marked per-model — round2 #7; full text is injected
164
- * verbatim and may be >64K → offloaded with a preview at injection). */
165
- export function composeConsultDigest(session) {
166
- const replies = session.replies ?? []
167
- const parts = replies.map((r) =>
168
- r.failed
169
- ? `- [${r.model}] (failed): ${r.reply}`
170
- : `- [${r.model}]: ${r.reply}`)
171
- const counts = `${replies.length} of ${session.total} models replied (${session.failed} failed)`
172
- return `[System reminder: consultation #${session.id} finished — ${counts}]\n${parts.join("\n")}`
173
- }
174
-
175
- /**
176
- * Inject one settled consult family entry into the parent history as a
177
- * user-role reminder (run-start injection — agent.mjs; same shape rules as
178
- * injectAsyncResult: XML-escaped, >64K offloaded with preview + path). Consumed
179
- * = the caller splices the entry out of the pending single container
180
- * (_pendingAsyncResults——ASYNC-RESULT-CONTAINER.md D2——role 分发注入)。
181
- */
182
- export async function injectConsultResult(agent, entry) {
183
- const full = String(entry?.report ?? "(no consultation result)")
184
- // §22 D-DG3(群 B 批 B5):计入预算的 raw = 报告正文(标签行不计)——首行标签拆出;超限
185
- // 路径保留族标签行(与 VSC 镜像同形);落盘内容 = raw(与其余三族同口径)。
186
- const at = full.indexOf("\n")
187
- const label = at === -1 ? "" : full.slice(0, at + 1)
188
- const raw = at === -1 ? full : full.slice(at + 1)
189
- const over = digestBudgetOver(agent, raw.length)
190
- const saved = over ? await persistOverflowReport(raw, { tag: `consult-${entry?.id ?? "session"}` }) : null
191
- const preview = saved ? `${label}${saved}` : await offloadToolResult(full, `consult-${entry?.id ?? "session"}`)
192
- pushReal(agent, {
193
- role: "user",
194
- content: escapeXml(preview),
195
- })
196
- }
197
-
198
- function settleChild(agent, session, id, label, ok, payload, emitDone) {
199
- if (ok) {
200
- session.received++
201
- session.replies.push({ model: label, reply: payload })
202
- } else if (session.stopped) {
203
- session.terminated = (session.terminated ?? 0) + 1
204
- } else {
205
- session.failed++
206
- session.replies.push({ model: label, reply: `(consultation failed: ${payload})`, failed: true })
207
- }
208
- session.pending--
209
- emitDone?.() // per-child TUI block freeze at settle (R17 — child's activity card is done)
210
- if (session.pending === 0) sessionSettled(agent, session)
211
- }
212
-
213
- async function runConsultChild(ctx, session, id, m, problem, ctrl) {
214
- const agent = ctx.agent
215
- const timeoutMs = agent?.config?.agent?.consultTimeoutMs ?? CONSULT_TIMEOUT_MS
216
- let timedOut = false
217
- const armWatchdog = () => {
218
- const t = setTimeout(() => {
219
- timedOut = true
220
- // §20.3 站点 #12 信号面(第 24 批):watchdog 中止带 timeout reason
221
- try { ctrl.abort({ abortTrigger: "timeout", abortDetail: "consult-watchdog" }) } catch { /* already settled */ }
222
- }, timeoutMs)
223
- t.unref?.()
224
- return t
225
- }
226
- let watchdog = armWatchdog()
227
- const label = consultLabel(m)
228
- // LOGGING(LOGGING.md):child:*(consult)——logSettle 在函数作用域声明(外层 catch
229
- // 覆盖 spawn 前失败路径);spawn 事件在 relay 建立后发射(logArmed 翻转——provider/
230
- // 创建失败 = 从未启动,不落子事件、错误仅经 settleChild 进会话)。
231
- let childLogId = null
232
- let logT0 = 0
233
- let logArmed = false
234
- let logDone = false
235
- const logSettle = (kind, payload) => {
236
- if (!logArmed || logDone || !childLogId) return
237
- logDone = true
238
- const ms = Date.now() - logT0
239
- const base = { role: "consult", id: childLogId, ms }
240
- if (kind === "ok" || kind === "partial") logEvent("child:done", { ...base, kind })
241
- else logEvent("child:error", { ...base, err: errText(payload, 200) })
242
- }
243
- // R17: relay prefix assigned before the child runner arms — the per-child TUI
244
- // block freeze emits only when a block actually exists (relay established).
245
- let relayPrefix = null
246
- const settle = (ok, payload) => settleChild(agent, session, id, label, ok, payload, relayPrefix
247
- ? () => ctx.callbacks?.onToken?.(`${relayPrefix}⟦ev⟧done\x1e0\x1e0\x1edone\x1e`)
248
- : null)
249
- try {
250
- // Provider resolution: consultModels entries are { provider, model, effort? } — resolve
251
- // via the subagent's provider resolver ("provider:model" handles cross-provider picks).
252
- const provider = resolveChildProvider(agent, `${m.provider}:${m.model}`)
253
- if (!ensureChildApiKey(provider)) {
254
- // resolveChildProvider may still lack a key; fail loudly like the plugin precheck
255
- // (settleChild turns this message into a clear failed reply instead of a raw 401)
256
- throw new Error(`consult model ${label} has no API key — check providers[${m.provider}].apiKey in config.json`)
257
- }
258
- // Clamp the pool's effort to the model's reasoningEffortEnum — an out-of-enum
259
- // value makes provider/core throw on EVERY chat call (candidate dies on takeoff).
260
- // Symmetric with the escalate action (subagent action:"escalate"); 2026-08-16
261
- // a real consult died on qwen3.8-max effort "high" (enum is xhigh/medium/low).
262
- // Out-of-enum: DROP the effort entirely (the provider preset default may ALSO be
263
- // out-of-enum for this override model).
264
- clampEffort(provider, m.model, m.effort)
265
-
266
- // Read-only consultant: filter the parent tool set down to readonly tools + main_history.
267
- const allowed = readonlyToolNames(agent.tools ?? [])
268
- const tools = [
269
- ...(agent.tools ?? []).filter((t) => allowed.has(t.name)),
270
- makeMainHistoryTool(agent),
271
- ]
272
-
273
- const child = createAgent({
274
- provider,
275
- tools,
276
- config: agent.config,
277
- cwd: agent.cwd,
278
- memory: agent.memory,
279
- // No overlay: setup.mjs already selects CONSULT_BASE as the base prompt for
280
- // role "consult" (overlay + base would concatenate it twice).
281
- role: "consult",
282
- })
283
-
284
- // Activity relay via the unified spawn-child pipeline (§7.2 D3): `consult#<subId>/`
285
- // prefix (same channel subagent uses — parallel consultants stay independent) +
286
- // onToolOutput passthrough so the consultant's tool output lands in its TUI block.
287
- relayPrefix = makeRelay(agent, "consult", ctx.callbacks?.onToken, provider.model ?? "")
288
- // LOGGING:arm(spawn 事件——relay 建立后;子内事件归属 _logId)
289
- childLogId = relayPrefix.slice(0, -1)
290
- child._logId = childLogId
291
- logT0 = Date.now()
292
- logArmed = true
293
- logEvent("child:spawn", { role: "consult", id: childLogId, kind: "consult" })
294
- const childCallbacks = wrapChildCallbacks(relayPrefix, ctx.callbacks ?? {})
295
- let declined = false // review #1: guard against double-settle when onDeclined fired
296
-
297
- // Turn-cap continue loop (TURN-CAP-CONTINUE.md) via runWithContinue (§7.2 D3): hitting
298
- // the cap asks the user via the SAME y/n panel the main agent uses — unlimited
299
- // continues, each with a fresh turn budget AND a re-armed wall-clock watchdog (a
300
- // continue is a fresh budget, the clock restarts too). Parallel consultants serialize
301
- // their prompts through a session-level queue. Declined / headless → failed reply
302
- // (partial diagnosis).
303
- const runner = ctx.runAgent ?? runAgent
304
- try {
305
- const result = await runWithContinue(
306
- (childAgent, input, cbs, opts) => runner(childAgent, input, cbs, opts),
307
- child, "# Problem\n" + problem,
308
- childCallbacks,
309
- { depth: 1, maxTurns: agent?.config?.agent?.consultTurns ?? CONSULT_TURNS, signal: ctrl.signal },
310
- {
311
- askContinue: (e) => {
312
- if (!ctx.onPermissionRequest) return Promise.resolve(false)
313
- const ask = () => ctx.onPermissionRequest("continue", { turns: e.turn, agent: label })
314
- session.continueQueue = (session.continueQueue ?? Promise.resolve()).then(ask, ask)
315
- return session.continueQueue.then((go) => {
316
- if (go) {
317
- clearTimeout(watchdog)
318
- timedOut = false // fresh budget → fresh clock
319
- watchdog = armWatchdog()
320
- }
321
- return go
322
- })
323
- },
324
- onDeclined: (e) => {
325
- declined = true
326
- settle(false, `turn cap reached (${e.turn} turns) — stopped, diagnosis may be partial`)
327
- logSettle("partial", null)
328
- return undefined
329
- },
330
- },
331
- )
332
- // Review #1 fix: onDeclined already settled this child as a failed reply —
333
- // settling again here would push a phantom empty success reply and decrement
334
- // `pending` twice (negative pending would re-enter the settle routing).
335
- if (!declined) {
336
- settle(true, String(result ?? ""))
337
- logSettle("ok", null)
338
- }
339
- } catch (e) {
340
- // Runner errors (incl. the watchdog's abort) settle as a failed reply — the
341
- // continue/declined paths are already handled inside runWithContinue.
342
- const note = timedOut ? `consultation timed out after ${Math.round(timeoutMs / 60000)}min (agent.consultTimeoutMs)` : deathLine(e, ctrl?.signal)
343
- settle(false, note)
344
- logSettle("error", note)
345
- }
346
- } catch (e) {
347
- // Errors BEFORE the runner (provider resolution, createAgent) or a throwing
348
- // continue-prompt settle as failed replies — the runner's own errors are already
349
- // handled inside the loop above. relayPrefix is null on these paths — no TUI
350
- // block was ever opened, so no freeze event is emitted.
351
- const line = deathLine(e, ctrl?.signal)
352
- settle(false, line)
353
- logSettle("error", line)
354
- } finally {
355
- clearTimeout(watchdog)
356
- }
357
- }
358
-
359
- /** Turn-end / session-end abort cleanup (R17 — call sites: the Ctrl+C abort
360
- * branches of finalizeAgentTurn and the suspension driver). Consultation
361
- * sessions are now cross-turn background work (like async subagents): a NORMAL
362
- * turn end keeps them alive — this runs only when the user stops everything:
363
- * every leftover session is marked stopped (its settles never reach the digest
364
- * stream — T-R17c) and its controllers aborted. */
365
- export function cleanupConsultSessions(agent) {
366
- for (const s of agent._consultSessions?.values() ?? []) {
367
- s.stopped = true
368
- for (const c of s.controllers ?? []) { try { c.abort({ abortTrigger: "stop", abortDetail: "consult-cleanup" }) } catch { /* already settled */ } }
369
- }
370
- agent._consultSessions?.clear()
371
- }
372
-
373
- export const consultStartTool = {
374
- name: "consult_start",
375
- readonly: false,
376
- sideEffectExempt: true,
377
- description:
378
- "Start a parallel multi-model consultation (会诊) for a hard problem you are stuck on (repeated failures, no headway). " +
379
- "Call it directly when the user asks for 会诊 / consult — an explicit user request applies even if you are not 'stuck'. " +
380
- "Several configured models (agent.consultModels) analyze the same problem INDEPENDENTLY and in parallel. " +
381
- "Non-blocking: returns immediately with a consult id; the consultants keep running in the background across turns. " +
382
- "When EVERY model has replied (or failed), the full verdict text is delivered to you automatically — as a system " +
383
- "reminder at the next run start, or digested on its own while the session is idle — judge and adopt each opinion " +
384
- "yourself with your own tools (opinions are suggestions, not gates). To stop a session early (user changed their " +
385
- "mind / wants the tokens back), call consult_stop(id) — a stopped session delivers no digest.\n" +
386
- "Parameters:\n" +
387
- "- problem (required): a brief — the symptom, what you already tried (failure trail), and entry-point files. " +
388
- "Do NOT paste raw error logs; consultants pull the main session history themselves via their main_history tool.\n" +
389
- "- models (optional): subset of agent.consultModels to run — an array of \"provider:model\", bare provider, or bare model names (case-insensitive). Omit to run all.",
390
- parameters: {
391
- type: "object",
392
- properties: {
393
- problem: { type: "string", description: "Problem brief (symptom + failure trail + entry files)" },
394
- models: { type: "array", items: { type: "string" }, description: 'Optional subset of agent.consultModels to run (default: all). Each entry is "provider:model", a bare provider name, or a bare model name (case-insensitive).' },
395
- },
396
- required: ["problem"],
397
- },
398
- async execute({ problem, models }, ctx) {
399
- if (typeof problem !== "string" || !problem.trim()) return "Error: problem is required and must be a non-empty string"
400
- const agent = ctx.agent
401
- if (!agent) return "Error: consult requires an agent context"
402
- const pool = agent.config?.agent?.consultModels ?? []
403
- if (!Array.isArray(pool) || pool.length === 0)
404
- return "Consultation is not configured — add agent.consultModels ([{ provider, model }], up to 5) to ~/.thincoder/config.json"
405
- if (pool.length > 5) return `Error: consultModels supports at most 5 models (got ${pool.length})`
406
-
407
- // `models` (optional) narrows the pool to a subset; absent/empty → run the whole pool.
408
- const picked = selectConsultModels(pool, models)
409
- if (picked.error) return picked.error
410
- const run = picked.models
411
-
412
- agent._consultSessions ??= new Map()
413
- const id = String((agent._consultIdCounter = (agent._consultIdCounter ?? 0) + 1))
414
- const session = {
415
- id, controllers: [], replies: [], pending: 0,
416
- failed: 0, terminated: 0, stopped: false, received: 0, total: run.length,
417
- models: run.map(consultLabel),
418
- }
419
- agent._consultSessions.set(id, session)
420
-
421
- for (const m of run) {
422
- session.pending++
423
- const ctrl = new AbortController()
424
- session.controllers.push(ctrl)
425
- // D6 buildChildSignal 单点(ASYNC-RESULT-CONTAINER.md D5——consult 补 _sessionSignal
426
- // 兜底:挂起会话内的 consult children 持会话 signal,digest 自身 Ctrl+C 不误伤)。
427
- const baseSignal = buildChildSignal(agent, ctx)
428
- if (baseSignal) {
429
- // §20.3 站点 #10(第 24 批):hop 逐跳保 reason
430
- if (baseSignal.aborted) ctrl.abort(baseSignal.reason)
431
- else baseSignal.addEventListener("abort", () => ctrl.abort(baseSignal.reason), { once: true })
432
- }
433
- // Fire and forget — each child settles itself into the session; the session
434
- // routes to the pending single container when every child has settled (R17).
435
- runConsultChild(ctx, session, id, m, problem, ctrl)
436
- }
437
- return JSON.stringify({ id, models: session.models })
438
- },
439
- }
440
-
441
- export const consultStopTool = {
442
- name: "consult_stop",
443
- readonly: false,
444
- sideEffectExempt: true,
445
- description:
446
- "Cancel a still-running consultation session (会诊) — the user changed their mind, the problem resolved, or you want the tokens back. " +
447
- "Aborts every consultant that is still running; a stopped session delivers NO digest (R17 — its already-collected partial replies are dropped). " +
448
- "Sessions that finished on their own are no longer cancellable — their verdict text is delivered automatically.\n" +
449
- "Returns JSON {abandoned: <pending count>, cancelled: true} — or {error: \"unknown consult id\"} (already finished/cancelled).\n" +
450
- "Parameters:\n" +
451
- "- id (required): the consult id from consult_start",
452
- parameters: {
453
- type: "object",
454
- properties: {
455
- id: { type: "string", description: "Consult id" },
456
- },
457
- required: ["id"],
458
- },
459
- async execute({ id }, ctx) {
460
- const s = ctx.agent?._consultSessions?.get(String(id))
461
- if (!s) return JSON.stringify({ error: "unknown consult id" })
462
- const abandoned = s.pending
463
- s.stopped = true
464
- // §20.3 站点 #11(第 24 批):会话级停 = stop
465
- for (const c of s.controllers) { try { c.abort({ abortTrigger: "stop", abortDetail: "consult-stop" }) } catch { /* already settled */ } }
466
- return JSON.stringify({ abandoned, cancelled: true })
467
- },
468
- }
@@ -1,117 +0,0 @@
1
- /**
2
- * design-token.mjs — design-token utilities(2026-09-08 自 advisor-async.mjs 提取——
3
- * advisor-async 随 DESIGN-TOKEN-SETTLEMENT D1 落盘块再越 500 行硬限;本工具组 verbatim
4
- * 迁入,零语义变)。
5
- *
6
- * 沿革:初由 agent-tools/advisor.mjs 迁至 advisor-async.mjs(sync wrapper 与 async
7
- * settle 共享一套实现——无 wrapper↔runner 环),再由 advisor-async.mjs 迁入本文件。
8
- * 既有 import 面不变:advisor-async.mjs re-export 全部 7 个导出(advisor.mjs 与测试
9
- * 的 import 路径原样保留——advisor.mjs 再转发 validateDesignToken 给 spawn 门禁)。
10
- */
11
-
12
- import { randomUUID } from "node:crypto"
13
- import { tokenExpiryMs } from "../token-ttl.mjs"
14
-
15
- /**
16
- * F2c/F2e (§29.1 2026-09-07): the engine-generated Approved suffix — ONE builder
17
- * shared by the sync settle and the async settle (and the prior stores, which
18
- * strip it with stripApprovedSuffix — exact-suffix truncation, never a regex
19
- * guess, zero collateral). The slot count is a point-in-time snapshot taken at
20
- * settle time — the situation at spawn time may differ (F2d backs that up).
21
- */
22
- export function buildApprovedSuffix(designToken, designId, slotCount) {
23
- return `Approved. Pass this exact token to eng-coder (designToken parameter): ${designToken}\ndesignId: ${designId} (pass as the designId parameter when spawning eng-coder — optional while this session holds a single design; ${slotCount} approved design slot(s) held as of this approval, and the count may have changed since — with several designs the spawn gate refuses a missing designId and lists the held ids)`
24
- }
25
-
26
- /** F2e (§29.1): strip the engine-generated Approved suffix from a report before
27
- * it becomes a prior — the suffix is deterministic (buildApprovedSuffix), so the
28
- * truncation is exact; a text not ending in it passes through untouched. */
29
- export function stripApprovedSuffix(text, suffix) {
30
- if (typeof text !== "string" || !suffix) return text
31
- return text.endsWith(suffix) ? text.slice(0, text.length - suffix.length).trim() : text
32
- }
33
-
34
- const TOKEN_TTL_DEFAULT_MS = 7 * 24 * 3600 * 1000 // 7-day ceiling (v2 2026-08-25)
35
-
36
- /** Effective token TTL: config override with runtime validation (timeoutMs precedent). */
37
- export function effectiveTokenTtlMs(agent) {
38
- const cfg = agent?.config?.agent?.engTokenTtlMs
39
- return (Number.isFinite(cfg) && cfg > 0) ? cfg : TOKEN_TTL_DEFAULT_MS
40
- }
41
-
42
- /** Mint an unsigned design token with expiration (2026-09-06: HMAC layer removed —
43
- * the token is a FLOW credential: uuid:expiresAt, exact slot match + TTL only). */
44
- export function generateDesignToken(agent) {
45
- const uuid = randomUUID()
46
- const expiresAt = Math.floor(Date.now() + effectiveTokenTtlMs(agent))
47
- return `${uuid}:${expiresAt}`
48
- }
49
-
50
- /** Validate a design token: format + expiration — ALL fail-closed (v2 2026-08-25).
51
- * R16: format/expiry semantics live in token-ttl.mjs (tokenExpiryMs — single source
52
- * shared with restore filtering / enter cleanup / spawn-gate slot deletion — D-R16b). */
53
- export function validateDesignToken(token) {
54
- const expiry = tokenExpiryMs(token)
55
- return expiry !== null && expiry >= Date.now()
56
- }
57
-
58
- /** Build a [DESIGN-TOKEN:...] regex matching the FULL token (uuid:expiresAt). */
59
- export function makeDesignTokenRegex(token, flags = "") {
60
- const escaped = token.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")
61
- return new RegExp(
62
- `(?:^|\\s|\`|\\*)\\[DESIGN-TOKEN:\\s*${escaped}\\s*\\](?:\\s|$|\`|\\*)`,
63
- flags + "ms"
64
- )
65
- }
66
-
67
- /**
68
- * Shared design-review settlement (sync wrapper + async settle): the token echo
69
- * IS the verdict — the advisor echoes it only on approval. On echo: slot the
70
- * token under designId (+ eng-coder gate flag; single-value mirror retired per
71
- * DESIGN-TOKEN-SETTLEMENT D3) and return
72
- * the clean output with the Approved suffix; the review instance CLOSES (a
73
- * later review of the same doc-set starts a fresh full review). On non-echo:
74
- * strip every dead token occurrence and return the findings text — slots stay
75
- * untouched (方案 ②: a failed re-review revokes nothing).
76
- * @param {Object} [opts] — 第 11 批(A/F11):`opts.incomplete` = 宿主尾族判定 kind
77
- * (单谓词 `advisorIncompleteMarker`——结算方透传)。非空 ⇒ **一律不签发**(无论评审文本
78
- * 是否回显 token):剥除全部 token 回显 + 追加未签发提示(原因 + 恢复指引),不写槽、
79
- * 不关实例(可重评)。
80
- * @returns {{passed: boolean, output: string}}
81
- */
82
- export function settleDesignReview(agent, run, designToken, rawResult, opts = {}) {
83
- if (!designToken || typeof rawResult !== "string") {
84
- return { passed: false, output: rawResult ?? "" }
85
- }
86
- // A(F11/§14.3 消费点 1):未完成即不签发——判据与 code 完成守卫同源(单谓词)。
87
- const incomplete = opts?.incomplete ?? null
88
- if (incomplete) {
89
- const stripped = rawResult.replace(makeDesignTokenRegex(designToken, "g"), "").trim()
90
- return {
91
- passed: false,
92
- output: `${stripped}\n\n评审未完成——token 未签发 (review incomplete — no design token issued; reason: ${incomplete})\n以更小范围重跑设计评审(逐档 / 逐节拆分,或拆到两次评审),或调大 agent.advisor.timeoutMs 后重试;补充检查未完成的部分不得按已核处理。`.trim(),
93
- }
94
- }
95
- const tokenPattern = makeDesignTokenRegex(designToken)
96
- if (!tokenPattern.test(rawResult)) {
97
- const stripped = rawResult.replace(makeDesignTokenRegex(designToken, "g"), "").trim()
98
- return { passed: false, output: stripped || "Advisor: design review did not pass." }
99
- }
100
- // Echoed the token → review passed. Issue it to the parent for eng-coder.
101
- agent._engDesignTokens ??= new Map()
102
- agent._engDesignTokens.set(run.designId, designToken)
103
- // DESIGN-TOKEN-SETTLEMENT D3(2026-09-08):单值镜像 `_engDesignToken` 退役——
104
- // 只写多槽 Map(AC3 零镜像写);settle 落盘由调用方(settleAdvisorRun)当场做。
105
- // Unlock the dispatch design gate for eng-coder SELF-review (defense-in-depth —
106
- // see the sync wrapper's note: unreachable today, kept for parity).
107
- if (agent._role === "eng-coder") agent._engDesignReviewed = true
108
- run.open = false // approval closes this doc-set instance — next review is fresh
109
- const clean = rawResult.replace(makeDesignTokenRegex(designToken, "g"), "").trim()
110
- // F2c (§29.1): id echo + omission guidance + point-in-time slot snapshot — the
111
- // same suffix the F2e prior stores strip with (stored for the exact truncation).
112
- run.approvedSuffix = buildApprovedSuffix(designToken, run.designId, agent._engDesignTokens.size)
113
- return {
114
- passed: true,
115
- output: `${clean}\n\n${run.approvedSuffix}`,
116
- }
117
- }
@@ -1,76 +0,0 @@
1
- /**
2
- * digest-budget.mjs — digest 注入批量预算单源(群 B 批 B5——AGENT-LOOP.md §22 语义源)。
3
- * 原预算块居 subagent-async.mjs(只覆盖经 injectAsyncResult 的三族:subagent / advisor /
4
- * escalate),consult 族注入器(injectConsultResult)绕过 ⇒ 多族条目同轮合并注入时可累计
5
- * 超限(BATCH-3-STRUCTURE F-2 原始事故面 1.3MB 请求体)。本档把常量 / 判超 / 记账 / 落盘
6
- * 四处合一(D2 单源)+ 四族全接线(D-DG2)。
7
- *
8
- * 契约(D-DG1 三导出——CLI 面):
9
- * - `DIGEST_INJECT_BUDGET`(64×1024——与 offload 单条预览同量级);
10
- * - `digestBudgetOver(agent, size)`——判超 + 记账:`used > 0 && used + size > BUDGET`
11
- * 首条豁免保留(单条大报告 >64K 走 offload 预览照旧——预算只约束轮累计);轮界定
12
- * `agent.history.length !== r.len + 1` 语义逐字迁入(相邻注入间 history 无其他落史 = 同轮;
13
- * 每次注入 pushReal 恰 +1——他人落史 = 新请求窗口 → 预算复位);键 = agent(会话级复用
14
- * ——Map 常驻一两项)。
15
- * - `persistOverflowReport(raw, { tag })`——超限条目全量落盘(`configDir/tool-results` +
16
- * `cleanupOldToolResults` 轮转;落盘名 `<ts>-<tag>.log`(tag = 溯源标签:写入族 + 条目 id
17
- * ——非法字符归一 `_`))。返回清单行文本(inline = 仅此——不 inline 全文);落盘失败 →
18
- * null(调用方回退常规 inline 路径——offload 同款「失败不吞报告」语义)。
19
- *
20
- * 计数口径(D-DG3):计入预算的 raw = 报告 / 错误正文(不含 `[System reminder: …]` 标签行
21
- * ——与既有口径一致);错误条目同计同落盘。
22
- *
23
- * 兼容面(D-DG4):subagent-async.mjs 保留 `DIGEST_INJECT_BUDGET` +
24
- * `_setDigestOffloadDirForTest` re-export(测试导入面零改);单条 offload 预览路径零改。
25
- *
26
- * 模块图:import node:fs/promises + node:path + ../agent/helpers.mjs(cleanupOldToolResults)+
27
- * ../config.mjs(configDir)——叶子级;subagent-async / consult 单向 import 本档(无环)。
28
- */
29
- import { mkdir, writeFile } from "node:fs/promises"
30
- import { join } from "node:path"
31
- import { cleanupOldToolResults } from "../agent/helpers.mjs"
32
- import { configDir } from "../config.mjs"
33
-
34
- export const DIGEST_INJECT_BUDGET = 64 * 1024 // 64K——与 offload 单条预览同量级
35
-
36
- // 轮记账:agent → { len, used }(逐字自 subagent-async.mjs 迁入——语义零变)。
37
- const digestRounds = new Map()
38
- function digestRoundFor(agent) {
39
- const h = agent.history
40
- const r = digestRounds.get(agent)
41
- if (!r || h.length !== r.len + 1) {
42
- const fresh = { len: h.length, used: 0 }
43
- digestRounds.set(agent, fresh)
44
- return fresh
45
- }
46
- r.len = h.length
47
- return r
48
- }
49
-
50
- /** 判超 + 记账(size = 原始正文字符数——标签行不计;先判后记:首条恒豁免)。 */
51
- export function digestBudgetOver(agent, size) {
52
- const round = digestRoundFor(agent)
53
- const over = round.used > 0 && round.used + size > DIGEST_INJECT_BUDGET
54
- round.used += size
55
- return over
56
- }
57
-
58
- /** Test seam: 落盘目录重定向(单测沙箱——生产从不调用)。 */
59
- let _digestOffloadDirOverride = null
60
- export function _setDigestOffloadDirForTest(dir) { _digestOffloadDirOverride = dir }
61
-
62
- /** 超限条目全量落盘(返回清单行文本;失败 null——调用方回退 inline——结果零丢失)。
63
- * tag 入文件名(溯源:写入族 + 条目 id)。 */
64
- export async function persistOverflowReport(raw, { tag }) {
65
- try {
66
- const dir = _digestOffloadDirOverride ?? join(configDir, "tool-results")
67
- await cleanupOldToolResults(dir)
68
- await mkdir(dir, { recursive: true })
69
- const file = join(dir, `${Date.now()}-${String(tag).replace(/[^a-zA-Z0-9_-]/g, "_")}.log`)
70
- await writeFile(file, raw, "utf8")
71
- return `Report saved to disk (digest inject budget exceeded — full text not inlined): ${file}\nRead it with the read tool (offset/limit).`
72
- } catch (e) {
73
- console.warn(`[digest] report persist failed — falling back to inline (report not lost): ${e.message}`)
74
- return null
75
- }
76
- }