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,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
- }
@@ -1,67 +0,0 @@
1
- /**
2
- * eng tool: enter/exit engineering mode.
3
- * In engineering mode the agent follows design-before-code methodology.
4
- * Toggled here at session level (in-memory flag; the session slot is the sole authority —
5
- * saveSession round-trips it at turn end; /eng writes the slot directly). The old ctx
6
- * state-persist hook was removed 2026-09-08 (ENG-SESSION-PROVIDER-CLEANUP D1.2): no
7
- * provider existed and its legacy payload keys were never read by applySession.
8
- * R16 (2026-09-06): design tokens are session-level flow credentials — mode toggles
9
- * do NOT clear them (ON→OFF keeps, OFF→ON does not require a fresh review); only TTL
10
- * expiry cleans tokens, at three points: restore filtering (session.mjs applySession) /
11
- * eng enter expired cleanup (below + cmd-eng ON) / spawn-gate expired rejection
12
- * (subagent-spawn.mjs). See docs/design/ENG-TOKEN-BINDING-TUNING.md §5/§5.1 (F-R16).
13
- */
14
- import { ENG_ON_REMINDER, ENG_OFF_REMINDER } from "../agent.mjs"
15
- import { purgeExpiredDesignTokens } from "../token-ttl.mjs"
16
-
17
- export const engTool = {
18
- name: "eng",
19
- description:
20
- "Enter or exit engineering mode. In engineering mode, follow design-before-code: write a design document, run advisor design review, get user approval, then implement via eng-coder subagents. " +
21
- "Returns the mode state — 'Engineering mode activated/exited' (an already-active state is acknowledged).",
22
- parameters: {
23
- type: "object",
24
- properties: {
25
- action: { type: "string", enum: ["enter", "exit"], description: "Enter or exit engineering mode" },
26
- },
27
- required: ["action"],
28
- },
29
- readonly: true,
30
- async execute(args, ctx) {
31
- ctx.agent.config.agent ??= {}
32
- if (args.action === "exit") {
33
- ctx.agent.config.agent.engineering = false
34
- // R16 (F-R16a): OFF 不清 token——有效 token 跨模式存活(设计评审过的产物不因
35
- // 开关重复烧)。过期清理跑在另外三处(恢复过滤 / 开模式 / spawn 门禁拒)。
36
- ctx.agent._advisorRound = 0 // reset convergence budget
37
- ctx.agent._advisorRuns = new Map() // §11.2 D-24b: per-review instances die with the mode (fresh cycles)
38
- ctx.agent._touchedFiles = [] // clear mutation tracking
39
- ctx.agent._lastEngState = false
40
- ctx.agent._pendingReminders = ctx.agent._pendingReminders ?? []
41
- ctx.agent._pendingReminders.push(ENG_OFF_REMINDER)
42
- return "Engineering mode exited. Standard discipline now applies. You may edit files directly."
43
- }
44
- if (args.action === "enter") {
45
- // Idempotent enter (v2 2026-08-25): already in engineering mode → pure no-op
46
- // (cleanup only runs on a real off→on transition — T-R16c precondition: first
47
- // exit/OFF, then enter; an already-on enter must not touch tokens at all).
48
- if (ctx.agent.config.agent.engineering) {
49
- return "Engineering mode already active. Existing design tokens stay valid."
50
- }
51
- ctx.agent.config.agent.engineering = true
52
- // R16 (F-R16b ②): off→on 不重评——只清过期 token(用户裁定"打开工程模式时
53
- // 应该清理"),有效 token 原样保留——遍历 Map 删过期,返回文案含清理个数。
54
- const cleared = purgeExpiredDesignTokens(ctx.agent)
55
- ctx.agent._advisorRuns = new Map() // §11.2 D-24b: per-review instances die with the mode (fresh cycles)
56
- ctx.agent._lastEngState = true
57
- ctx.agent._pendingReminders = ctx.agent._pendingReminders ?? []
58
- ctx.agent._pendingReminders.push(ENG_ON_REMINDER)
59
- let msg = "Engineering mode activated. Design-before-code enforced: write a design document first (location per your project's document conventions), run advisor with type='design', get user approval, then implement via eng-coder subagents."
60
- if (cleared > 0) {
61
- msg += ` Cleared ${cleared} expired design token${cleared === 1 ? "" : "s"} — 清 ${cleared} 个过期 token,有效 token 保留(TTL 内不重评)。`
62
- }
63
- return msg
64
- }
65
- return "Invalid action: expected 'enter' or 'exit'"
66
- },
67
- }
@@ -1,295 +0,0 @@
1
- /**
2
- * escalate-async.mjs — async 飞刀 runner (AGENT-LOOP.md §25 D-R17b — R17, 2026-09-06).
3
- *
4
- * The subagent action:"escalate" is DEFAULT-async at depth 0 (decision ③: the
5
- * depth-0-only escalate flips to async like every other background family;
6
- * `async: false` keeps the legacy synchronous flight). An async escalate runs in
7
- * the SHARED "other" pool domain (decision Q2 🅰 — the entry lives in
8
- * `_asyncSubagents` with role "escalate"/_pool "other", so it shares the 4-slot
9
- * other domain with explore/plan/coder spawns — capacity, queueing, refill,
10
- * status and cancel all come from the generic machinery):
11
- * - launch → ack {id, role:"escalate", status:"running"|"queued"[, position]};
12
- * the turn ends naturally, the session suspends (poolLive counts the entry).
13
- * - settle THREE-WAY classification (review #4): done → merge-all mutations back
14
- * into the parent's bookkeeping + overlap warning appended to the report
15
- * (report-level, not a gate — round2 #4); error (child failure / turn cap) →
16
- * partial mutations merged ONLY when the parent did not touch overlapping
17
- * files since launch (overlap → no merge + differences listed in the report);
18
- * cancelled → never reaches the digest stream (D-M6 — no merge, stopped
19
- * reminder).
20
- * - the classified report lands in `_pendingAsyncResults`(pending 单容器 +role——
21
- * ASYNC-RESULT-CONTAINER.md D2——挂起期 settle 移交)when the settle happens in a
22
- * suspension, or stays pooled for the turn-end collection otherwise;
23
- * injectAsyncResult's escalate
24
- * role branch delivers the digest ("报告已 merge——可继续处置" — the action
25
- * domain still follows the consuming turn's tier — no family exception).
26
- */
27
- import { relative, isAbsolute } from "node:path"
28
- import { runAgent, createAgent, DEFAULT_SUBAGENT_TURNS } from "../agent.mjs"
29
- import { runWithContinue, TURN_CAP_MARK, wrapChildCallbacks } from "../agent/spawn-child.mjs"
30
- // TUI-OOM-ROOTCAUSE §23.3.1:子代理人读线窗口常量(单源——store 零依赖)。
31
- import { RECORD_WINDOW_MESSAGES } from "../session-store.mjs"
32
- import { logEvent } from "../log.mjs"
33
- import { deathLine } from "../abort-provenance.mjs"
34
- import {
35
- mergeChildMutations, runningPoolCount, poolDomainOf, poolLimitsFor, ASYNC_POOL_LIMITS, enqueueAsk,
36
- } from "./subagent-async.mjs"
37
- import { refreshQueuedTokens, nextSubagentId } from "./subagent-scheduler.mjs"
38
- import { mutationSeqOf } from "./advisor-async.mjs"
39
- // ASYNC-RESULT-CONTAINER.md D3/D6:settle 公共收尾单点 + child signal 构建单点
40
- import { buildChildSignal, settleAsyncEntry } from "./async-settle.mjs"
41
-
42
- /** Parent-side mutations (absolute paths) committed AFTER the escalate launch —
43
- * the overlap scan feeds the settle classification (review #4/round2 #4: the
44
- * parent may have edited files while the flight ran). */
45
- function parentMutationsSince(parent, launchSeq) {
46
- const out = []
47
- for (const m of parent?._mutLog ?? []) {
48
- if (m.seq <= (launchSeq ?? -1)) continue
49
- for (const p of m.paths ?? []) if (!out.includes(p)) out.push(p)
50
- }
51
- return out
52
- }
53
-
54
- /** Files BOTH sides touched since launch (case-insensitive key on win32 —
55
- * filesOverlap precedent). */
56
- function overlapPaths(parent, launchSeq, childTouched) {
57
- const since = parentMutationsSince(parent, launchSeq)
58
- if (since.length === 0 || !childTouched?.length) return []
59
- const key = (p) => (process.platform === "win32" ? String(p).toLowerCase() : String(p))
60
- const sinceKeys = new Set(since.map(key))
61
- const hits = childTouched.filter((p) => sinceKeys.has(key(p)))
62
- // relative display form (touchedFilesNote precedent)
63
- const cwd = parent?.cwd ?? process.cwd()
64
- return hits.map((p) => {
65
- const r = relative(cwd, p)
66
- return r && !r.startsWith("..") && !isAbsolute(r) ? r : p
67
- })
68
- }
69
-
70
- /** Escalate-side touched files, relative display (or a placeholder). */
71
- function childTouchedDisplay(child, cwd) {
72
- const touched = child?._touchedFiles ?? []
73
- if (touched.length === 0) return "(none recorded)"
74
- const shown = touched.map((f) => {
75
- const r = relative(cwd ?? process.cwd(), f)
76
- return r && !r.startsWith("..") && !isAbsolute(r) ? r : f
77
- })
78
- return shown.join(", ")
79
- }
80
-
81
- /** Relative touched-file list (mirror of the sync path's note). */
82
- function touchedFilesNote(child, cwd) {
83
- const touched = child?._touchedFiles ?? []
84
- if (touched.length === 0) return ""
85
- const shown = touched.map((f) => {
86
- const r = relative(cwd ?? process.cwd(), f)
87
- return r && !r.startsWith("..") && !isAbsolute(r) ? r : f
88
- })
89
- return `\nTouched files: ${shown.join(", ")}`
90
- }
91
-
92
- /**
93
- * Async escalate settle — three-way classification (§25 D-R17b review #4):
94
- * - done: merge ALL mutations (the escalation's changes are the parent's —
95
- * verify/advisor guards must see them) + overlap warning into the report
96
- * (report-level hint — not a gate — round2 #4);
97
- * - error (child failure / turn cap): partial mutations merge ONLY without a
98
- * parent-side overlap — overlap → NO merge + differences listed (the report
99
- * carries both sides so the model can decide);
100
- * - cancelled: nothing merges, never reaches pending (D-M6 — stopped reminder).
101
- * Runs BEFORE the pending transfer / digest injection. Mutates entry.report /
102
- * entry.error into the FINAL digest body (the family wording rides
103
- * injectAsyncResult's escalate branch).
104
- */
105
- export function classifyEscalateSettle(parent, entry) {
106
- if (entry.cancelled) return { cancelled: true }
107
- // §23.3.1(TUI-OOM-ROOTCAUSE)——childAgent 语义面:settle 分类(touched 摘要/partial
108
- // merge)与 status/observe 摘要的读取源;**消化注入完成后由 `releaseSettledEntry`
109
- // (async-settle.mjs)置 null**(池内未消化窗口不释放——表 2 候选 2 否决)。
110
- const child = entry.childAgent
111
- const touched = child?._touchedFiles ?? []
112
- const overlap = overlapPaths(parent, entry.launchSeq, touched)
113
- const hasError = entry.error != null
114
- const raw = hasError ? entry.error : entry.report
115
- if (hasError) {
116
- // error branch (child failure / turn cap — review #4): partial mutations
117
- // merge ONLY when the parent did not touch overlapping files since launch.
118
- // childAgent may be null when the flight died before child creation (advisor
119
- // 复评 🟡2——防御:无 child 即无 partial mutations——不 merge 不崩)。
120
- const merged = child != null && overlap.length === 0 && mergeChildMutations(parent, child)
121
- let decision = ""
122
- if (merged) {
123
- decision = `\nPartial changes merged into the parent's bookkeeping (no parent-side overlap since launch).`
124
- } else if (overlap.length > 0) {
125
- decision = `\nPartial changes NOT merged — the parent changed overlapping files while this escalate ran: ${overlap.join(", ")}. Escalate-side changes: ${childTouchedDisplay(child, parent?.cwd)}. Review the conflict and decide what to keep (report-level — not a gate; AGENT-LOOP.md §25 D-R17b).`
126
- }
127
- // (nothing to merge + no overlap → the plain error report stands alone)
128
- entry.error = `${raw}${decision}`
129
- entry.report = null
130
- return { cancelled: false, merged, overlap }
131
- }
132
- // done — merge-all + overlap warning into the report (report-level — not a gate)
133
- const merged = mergeChildMutations(parent, child)
134
- const overlapNote = overlap.length > 0
135
- ? `\n⚠ Overlapping writes: the parent changed ${overlap.join(", ")} while this escalate ran — mutations merged all the same; review those files before building on the report (report-level warning — not a gate; AGENT-LOOP.md §25 D-R17b round2 #4).`
136
- : ""
137
- entry.report = `${raw}${overlapNote}`
138
- return { cancelled: false, merged, overlap }
139
- }
140
-
141
- /**
142
- * Launch the async escalate (preflights already passed in executeEscalateAction):
143
- * pool admission into the shared OTHER domain → entry in `_asyncSubagents`
144
- * (generic queue/refill/status/cancel machinery) → ack. The flight starts on
145
- * entry.start() (immediately, or later via maybeRefillAsync when a slot frees).
146
- */
147
- export function launchEscalateAsync(parent, ctx, launch) {
148
- const { task, provider, tag, effortNote } = launch
149
- parent._asyncSubagents ??= new Map()
150
- parent._asyncQueue ??= []
151
- // Async id allocation (AGENT-LOOP.md §15 D-A1 precedent): reserve the relay
152
- // counter at launch — the returned id stays stable while the entry sits queued.
153
- // The [model] token (TUI block creation) is DEFERRED to actual start so queued
154
- // flights don't paint an empty panel block (subagent-parity).
155
- // SUBAGENT-ID-COUNTER-AGENT(2026-09-09):取号统一走 nextSubagentId(池活续号
156
- // 兜底——counter 载体= agent 本体 _subAgentCounter——跨 run/跨压缩存活)。
157
- const id = nextSubagentId(parent)
158
- const relayPrefix = `escalate#${id}/`
159
- const entry = {
160
- id, role: "escalate", relayPrefix,
161
- _pool: poolDomainOf("escalate"), // other — shares the domain with explore/plan/coder (§11.1 D-24a)
162
- status: "queued",
163
- position: undefined,
164
- report: null, error: null, done: false, cancelled: false,
165
- promise: null, _settle: null, _settleSeq: 0,
166
- model: provider.model ?? null,
167
- startedAt: null,
168
- turn: 0, maxTurns: 0,
169
- controller: null,
170
- _files: undefined, _dependsOn: undefined,
171
- childAgent: null,
172
- tag, effortNote, launchSeq: mutationSeqOf(parent),
173
- }
174
- const limits = poolLimitsFor(parent)
175
- entry.status = runningPoolCount(parent, entry._pool) >= (limits[entry._pool] ?? ASYNC_POOL_LIMITS[entry._pool])
176
- ? "queued" : "running"
177
- entry.promise = new Promise((res) => { entry._settle = res })
178
- const ctrl = new AbortController()
179
- entry.controller = ctrl
180
- // D6 buildChildSignal 单点(ASYNC-RESULT-CONTAINER.md——D5 同款:_sessionSignal 兜底)。
181
- const baseSignal = buildChildSignal(parent, ctx)
182
- if (baseSignal) {
183
- // §20.3 站点 #10(第 24 批):hop 逐跳保 reason
184
- if (baseSignal.aborted) ctrl.abort(baseSignal.reason)
185
- else baseSignal.addEventListener("abort", () => ctrl.abort(baseSignal.reason), { once: true })
186
- }
187
- // Turn mirror (⟦ev⟧turn from the child runAgent → entry.turn/maxTurns — status parity).
188
- const flight = async () => {
189
- entry.status = "running"
190
- entry.position = undefined
191
- entry.startedAt = Date.now()
192
- ctx.callbacks?.onToken?.(relayPrefix + "⟦ev⟧async\x1e")
193
- ctx.callbacks?.onToken?.(relayPrefix + "[model]" + (provider.model ?? ""))
194
- const child = createAgent({
195
- provider,
196
- tools: parent.tools,
197
- config: parent.config,
198
- cwd: parent.cwd,
199
- memory: parent.memory,
200
- // G3(施工②):overlay 摘除——coder 人格槽由 assemblePrompt 场景表承载(G3 映射)。
201
- role: "coder",
202
- })
203
- entry.childAgent = child // settle 分类/status touched 摘要绑定(start 时刻)
204
- child._historyWindow = RECORD_WINDOW_MESSAGES // TUI-OOM-ROOTCAUSE §23.3.1:子代理人读线窗口(四处创建点同置)
205
- child._logId = relayPrefix.slice(0, -1)
206
- logEvent("child:spawn", { role: "escalate", id: child._logId, kind: "async", status: "running", ms: 0 })
207
- const childCallbacks = wrapChildCallbacks(relayPrefix, ctx.callbacks ?? {})
208
- const relayOnToken = childCallbacks.onToken
209
- if (relayOnToken) {
210
- childCallbacks.onToken = (t) => {
211
- const ev = String(t).match(/^⟦ev⟧turn\x1e(\d+)\x1e(\d+)\x1e/)
212
- if (ev) {
213
- entry.turn = Number(ev[1]) || 0
214
- entry.maxTurns = Number(ev[2]) || 0
215
- }
216
- return relayOnToken(t)
217
- }
218
- }
219
- const runner = ctx.runAgent ?? runAgent
220
- const runOpts = {
221
- depth: 1,
222
- maxTurns: parent.config?.agent?.subagentTurns ?? DEFAULT_SUBAGENT_TURNS,
223
- signal: entry.controller.signal,
224
- }
225
- // 权限按 async 子代理同款装配:AUTO 直放行;手动档经父 _permQueue(并行子代理
226
- // 审批不叠弹窗)——背景飞行撞门时无 handler → denied 不悬挂(D-S7 同规则)。
227
- const childPermission = parent.autoApprove
228
- ? async () => true
229
- : async (name, toolArgs) => {
230
- if (!ctx.onPermissionRequest) return false
231
- const ask = () => ctx.onPermissionRequest(`escalate/${name}`, toolArgs)
232
- return enqueueAsk(parent, "_permQueue", ask)
233
- }
234
- const report = await runWithContinue(
235
- (childAgent, input, cbs, opts) => runner(childAgent, input, cbs, opts),
236
- child, task,
237
- { ...childCallbacks, onPermissionRequest: childPermission },
238
- runOpts,
239
- {
240
- // 后台飞行不弹 continue 面板(D-A3 §15 例外同款):AUTO && engineering 自动
241
- // resume——escalate 只在 normal 模式可用(engineering 拒)——恒自动拒 → partial。
242
- askContinue: () => Promise.resolve(Boolean(parent.config?.agent?.engineering && parent.autoApprove)),
243
- onDeclined: (e, output) => `escalate (${tag})${entry.effortNote} ${TURN_CAP_MARK} (${e.turn} turns) — work may be partial; review recent_changes before deciding next steps.\nPartial output: ${output.slice(0, 2000)}`,
244
- },
245
- )
246
- // done: compose the post-op body (the settle classification appends the
247
- // overlap warning / merge notes afterwards)
248
- return `escalate (${tag})${entry.effortNote} post-op report:\n${report || (child._capturedOutput ?? "").slice(0, 4000)}${touchedFilesNote(child, parent.cwd)}`
249
- }
250
- entry.start = () => {
251
- flight()
252
- .then((report) => {
253
- // Turn-cap partial (runWithContinue auto-declined) classifies as the ERROR
254
- // branch (design: 撞 turn cap = error — partial-merge decision applies):
255
- // move it to entry.error so the classification + error digest wording fire.
256
- if (String(report).includes(TURN_CAP_MARK)) entry.error = report
257
- else entry.report = report
258
- })
259
- .catch((e) => {
260
- // 运行失败/中止:错误文本落 entry.error(子代理同款——cancel 分支忽略它;
261
- // Ctrl+I 中止的残条目由收尾消化带错误文本——不落空 "(no report)" digest)。
262
- const child = entry.childAgent
263
- // §20.3 第 3 条合成器(第 24 批):原 message 前缀逐字保留 + 来源后缀
264
- entry.error = `escalate (${tag}) error: ${deathLine(e, entry.controller?.signal)}\nPartial output: ${(child?._capturedOutput ?? "").slice(0, 2000)}`
265
- })
266
- .finally(() => {
267
- // settle 公共收尾单点(ASYNC-RESULT-CONTAINER.md D3——settleAsyncEntry):日志三连
268
- // /cancelled 分支(出池+墓碑+⟦ev⟧stopped+提醒)/挂起分流(pending 单容器+出池——
269
- // 统一守卫 !parentAborted——D4)/公共尾部(settleSeq/_settle/唤醒 waiter + 腾槽补位
270
- // ——helper 尾部恒补)统一走共享 helper。族特有 hook = 三分类 merge 决策
271
- // (classifyEscalateSettle——done/error 分类;cancelled 不经此——helper cancelled
272
- // 分支先行)。
273
- settleAsyncEntry(parent, entry, {
274
- pool: parent._asyncSubagents,
275
- ctx,
276
- onAccounting: () => {
277
- // Three-way settle classification (done/error/cancelled — review #4):
278
- // done → merge-all + 重叠警告;error → 无父侧重叠才 partial merge;
279
- // cancelled 不经此(helper cancelled 分支先行)。
280
- void classifyEscalateSettle(parent, entry)
281
- },
282
- })
283
- })
284
- }
285
- parent._asyncSubagents.set(String(id), entry)
286
- logEvent("child:spawn", { role: "escalate", id: `escalate#${id}`, kind: "async", status: entry.status, ms: 0 })
287
- if (entry.status === "queued") {
288
- parent._asyncQueue.push(entry)
289
- entry.position = parent._asyncQueue.length
290
- refreshQueuedTokens(parent, ctx.callbacks?.onToken)
291
- return JSON.stringify({ id: String(id), role: "escalate", status: "queued", position: entry.position })
292
- }
293
- entry.start()
294
- return JSON.stringify({ id: String(id), role: "escalate", status: "running" })
295
- }