thincoder 0.12.59 → 0.12.61

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 (192) hide show
  1. package/CHANGELOG.md +62 -4
  2. package/README.md +10 -8
  3. package/bin/thincoder.mjs +99 -133
  4. package/package.json +6 -4
  5. package/src/abort-provenance.mjs +116 -0
  6. package/src/acp/bridge.mjs +45 -21
  7. package/src/acp.mjs +6 -1
  8. package/src/advisor/citations.mjs +83 -21
  9. package/src/advisor/compaction.mjs +174 -0
  10. package/src/advisor/loop.mjs +293 -0
  11. package/src/advisor/messages.mjs +59 -137
  12. package/src/advisor/project-context.mjs +194 -0
  13. package/src/advisor/repos.mjs +17 -40
  14. package/src/advisor/run.mjs +156 -359
  15. package/src/advisor/truncate.mjs +57 -0
  16. package/src/advisor.mjs +27 -7
  17. package/src/agent/completion.mjs +17 -11
  18. package/src/agent/dispatch.mjs +145 -27
  19. package/src/agent/helpers.mjs +107 -13
  20. package/src/agent/record-results.mjs +55 -11
  21. package/src/agent/relay-prefix.mjs +39 -0
  22. package/src/agent/run-stages.mjs +242 -0
  23. package/src/agent/setup-reminders.mjs +69 -0
  24. package/src/agent/setup.mjs +107 -127
  25. package/src/agent/spawn-child.mjs +55 -13
  26. package/src/agent-tools/advisor-async.mjs +346 -0
  27. package/src/agent-tools/advisor-settle.mjs +231 -0
  28. package/src/agent-tools/advisor.mjs +167 -116
  29. package/src/agent-tools/async-settle.mjs +191 -0
  30. package/src/agent-tools/batch-segment.mjs +195 -0
  31. package/src/agent-tools/consult.mjs +139 -107
  32. package/src/agent-tools/design-token.mjs +117 -0
  33. package/src/agent-tools/digest-budget.mjs +76 -0
  34. package/src/agent-tools/eng.mjs +24 -29
  35. package/src/agent-tools/escalate-async.mjs +289 -0
  36. package/src/agent-tools/read-history.mjs +166 -32
  37. package/src/agent-tools/recent-changes.mjs +2 -1
  38. package/src/agent-tools/review-streak.mjs +93 -0
  39. package/src/agent-tools/settings.mjs +137 -34
  40. package/src/agent-tools/subagent-actions.mjs +180 -133
  41. package/src/agent-tools/subagent-async.mjs +184 -177
  42. package/src/agent-tools/subagent-panel.mjs +160 -0
  43. package/src/agent-tools/subagent-run.mjs +205 -0
  44. package/src/agent-tools/subagent-scheduler.mjs +100 -27
  45. package/src/agent-tools/subagent-spawn.mjs +453 -0
  46. package/src/agent-tools/subagent.mjs +256 -578
  47. package/src/agent-tools/verify.mjs +119 -292
  48. package/src/agent-tools.mjs +1 -0
  49. package/src/agent.mjs +89 -205
  50. package/src/cli/distill-command.mjs +12 -6
  51. package/src/cli/make-agent.mjs +26 -8
  52. package/src/cli/memory-command.mjs +4 -3
  53. package/src/cli/permission.mjs +2 -2
  54. package/src/cli/setup-wizard.mjs +42 -17
  55. package/src/completions.mjs +114 -0
  56. package/src/config-migrate.mjs +70 -0
  57. package/src/config.mjs +180 -63
  58. package/src/context.mjs +5 -147
  59. package/src/conventions.mjs +223 -0
  60. package/src/crash-reports.mjs +128 -0
  61. package/src/distill.mjs +11 -11
  62. package/src/expand-home.mjs +16 -0
  63. package/src/explore-distill.mjs +155 -0
  64. package/src/generate-title.mjs +1 -1
  65. package/src/hooks.mjs +7 -3
  66. package/src/memory/code-index.mjs +9 -3
  67. package/src/memory/code-sync.mjs +72 -32
  68. package/src/memory/core.mjs +6 -193
  69. package/src/memory/delete.mjs +236 -0
  70. package/src/memory/docs.mjs +68 -54
  71. package/src/memory/file-walk.mjs +109 -0
  72. package/src/memory/schema.mjs +15 -3
  73. package/src/memory.mjs +3 -1
  74. package/src/model-ref.mjs +66 -0
  75. package/src/model-specs.mjs +42 -8
  76. package/src/peer-domains.mjs +265 -0
  77. package/src/peer-instances.mjs +231 -0
  78. package/src/prompt-overlays.mjs +82 -0
  79. package/src/prompts/advisor-design.md +18 -75
  80. package/src/prompts/advisor-round1.md +14 -67
  81. package/src/prompts/advisor-round2.md +15 -51
  82. package/src/prompts/advisor-round3.md +15 -51
  83. package/src/prompts/common.md +115 -0
  84. package/src/prompts/consult-base.md +5 -23
  85. package/src/prompts/discipline-engineering.md +217 -0
  86. package/src/prompts/discipline-normal.md +179 -0
  87. package/src/prompts/persona-coder.md +21 -0
  88. package/src/prompts/persona-eng-coder.md +37 -0
  89. package/src/prompts/persona-eng-designer.md +55 -0
  90. package/src/prompts/persona-engineering.md +54 -0
  91. package/src/prompts/persona-explore.md +15 -0
  92. package/src/prompts/persona-normal.md +27 -0
  93. package/src/prompts/persona-plan.md +26 -0
  94. package/src/provider/anthropic.mjs +4 -4
  95. package/src/provider/core.mjs +18 -98
  96. package/src/provider/errors.mjs +101 -0
  97. package/src/provider/google.mjs +5 -6
  98. package/src/provider/index.mjs +2 -1
  99. package/src/provider/list-models.mjs +93 -0
  100. package/src/provider/rate.mjs +2 -1
  101. package/src/provider/responses.mjs +5 -3
  102. package/src/provider/retry.mjs +8 -45
  103. package/src/provider/sse.mjs +3 -4
  104. package/src/proxy.mjs +9 -14
  105. package/src/session-gc.mjs +214 -0
  106. package/src/session-guard.mjs +47 -0
  107. package/src/session-rename.mjs +38 -0
  108. package/src/session-slots.mjs +188 -60
  109. package/src/session.mjs +104 -124
  110. package/src/token-ttl.mjs +274 -0
  111. package/src/tools/{system.mjs → bash.mjs} +19 -221
  112. package/src/tools/checklist-sync.mjs +181 -0
  113. package/src/tools/checklist.mjs +52 -39
  114. package/src/tools/edit-batch.mjs +109 -10
  115. package/src/tools/edit-diff.mjs +110 -27
  116. package/src/tools/edit.md +17 -12
  117. package/src/tools/execute.mjs +31 -4
  118. package/src/tools/file.mjs +41 -16
  119. package/src/tools/git.md +1 -1
  120. package/src/tools/git.mjs +23 -34
  121. package/src/tools/glob-dialect.mjs +130 -0
  122. package/src/tools/glob.md +3 -3
  123. package/src/tools/grep.md +1 -1
  124. package/src/tools/index.mjs +9 -8
  125. package/src/tools/ops.mjs +188 -3
  126. package/src/tools/patch.mjs +3 -3
  127. package/src/tools/question.md +4 -0
  128. package/src/tools/question.mjs +26 -0
  129. package/src/tools/read.md +1 -2
  130. package/src/tools/read_image.md +1 -1
  131. package/src/tools/search.mjs +236 -0
  132. package/src/tools/shared.mjs +14 -13
  133. package/src/tools/wait_for.md +22 -0
  134. package/src/tui/agent-turn.mjs +36 -228
  135. package/src/tui/ansi.mjs +2 -0
  136. package/src/tui/clipboard.mjs +7 -1
  137. package/src/tui/cmd-advisor.mjs +3 -2
  138. package/src/tui/cmd-config.mjs +142 -30
  139. package/src/tui/cmd-eng.mjs +28 -40
  140. package/src/tui/cmd-exit.mjs +6 -8
  141. package/src/tui/cmd-mcp.mjs +8 -2
  142. package/src/tui/cmd-model.mjs +14 -12
  143. package/src/tui/cmd-new.mjs +3 -2
  144. package/src/tui/cmd-reindex.mjs +7 -0
  145. package/src/tui/cmd-session.mjs +19 -4
  146. package/src/tui/cmd-submodel.mjs +8 -5
  147. package/src/tui/cmd-think.mjs +10 -10
  148. package/src/tui/cmd-undo.mjs +4 -3
  149. package/src/tui/cmd-upgrade.mjs +19 -4
  150. package/src/tui/config-helpers.mjs +28 -16
  151. package/src/tui/distill-cmd.mjs +1 -1
  152. package/src/tui/index.mjs +40 -38
  153. package/src/tui/interaction.mjs +3 -3
  154. package/src/tui/key-handler.mjs +61 -17
  155. package/src/tui/key-modes.mjs +86 -8
  156. package/src/tui/layout.mjs +18 -10
  157. package/src/tui/model-catalog.mjs +89 -0
  158. package/src/tui/model-picker.mjs +498 -0
  159. package/src/tui/mouse.mjs +52 -9
  160. package/src/tui/pickers.mjs +28 -392
  161. package/src/tui/render-frame.mjs +32 -16
  162. package/src/tui/render-loop.mjs +2 -0
  163. package/src/tui/render-segments.mjs +12 -9
  164. package/src/tui/render.mjs +37 -5
  165. package/src/tui/slash-commands.mjs +2 -2
  166. package/src/tui/startup.mjs +4 -0
  167. package/src/tui/subagent-blocks.mjs +106 -295
  168. package/src/tui/subagent-children.mjs +162 -0
  169. package/src/tui/subagent-freeze.mjs +169 -0
  170. package/src/tui/subagent-panel.mjs +24 -31
  171. package/src/tui/suspension-drive.mjs +297 -0
  172. package/src/tui/tool-args.mjs +7 -5
  173. package/src/tui/tool-display.mjs +143 -0
  174. package/src/tui/tool-events.mjs +56 -185
  175. package/src/tui/tui-lifecycle.mjs +46 -4
  176. package/src/tui/update-notice.mjs +4 -0
  177. package/src/tui/wizard.mjs +61 -21
  178. package/src/tui/wrapped-spawn.mjs +38 -0
  179. package/src/prompts/coder.md +0 -56
  180. package/src/prompts/discipline.md +0 -102
  181. package/src/prompts/eng-coder.md +0 -44
  182. package/src/prompts/engineering-sub.md +0 -34
  183. package/src/prompts/engineering.md +0 -340
  184. package/src/prompts/explore.md +0 -21
  185. package/src/prompts/main.md +0 -56
  186. package/src/prompts/methodology-template.md +0 -58
  187. package/src/prompts/plan.md +0 -16
  188. package/src/prompts/system.md +0 -63
  189. package/src/tools/pdf-parse-text.mjs +0 -497
  190. package/src/tools/pdf-parse-xref.mjs +0 -499
  191. package/src/tools/pdf.mjs +0 -155
  192. package/src/tools/read_pdf.md +0 -21
@@ -0,0 +1,116 @@
1
+ /**
2
+ * abort-provenance.mjs — abort 来源标注词汇表(单一权威源——AGENT-LOOP.md §20.3 第 1/2 条)
3
+ *
4
+ * 子代理 / 评审 / 会诊死亡的可诊断性:产生点标注结构化来源(`err.abortInfo`)→
5
+ * controller 链 hop 逐跳保 reason(§20.3 第 4 条 #10)→ 结算 / 报告面用 `deathLine`
6
+ * 合成死亡行(原 message 前缀逐字保留 + 来源后缀)。
7
+ *
8
+ * 纯函数、零 import——任意层可引、无环(provider / proxy / agent / settle 族共用)。
9
+ * 词汇表:
10
+ * - trigger(5 值):`user`(reason.interrupt)· `timeout`(TimeoutError / 定时器面)·
11
+ * `cancel`(定向中止)· `stop`(整批 / 会话 / 回合级停)· `unknown`(残留 / 未标注——告警态)。
12
+ * - layer(3 值):`provider` / `agent` / `settle`;未标注错误回落 `unrecorded`(合成器 token)。
13
+ */
14
+
15
+ /** trigger 枚举权威(测试锁计数 5——AGENT-LOOP.md §20.3 第 1 条表)。 */
16
+ export const TRIGGERS = ["user", "timeout", "cancel", "stop", "unknown"]
17
+
18
+ /**
19
+ * trigger 判定(判据序 = §20.3 第 1 条表;signal.reason 四形态:
20
+ * ① `{interrupt:true(,message)}`(既有 user 面)② `TimeoutError`(原生——timeout 面)
21
+ * ③ `{abortTrigger:"cancel"|"stop"|"timeout"(,abortDetail)}`(新增——程序性中止)
22
+ * ④ 缺失 / 无已知键(→ unknown——诊断告警态,不得静默)。
23
+ */
24
+ export function triggerOf(signal) {
25
+ const reason = signal?.reason
26
+ if (reason == null) return "unknown"
27
+ if (reason.interrupt === true) return "user"
28
+ if (reason.name === "TimeoutError" || reason.abortTrigger === "timeout") return "timeout"
29
+ if (reason.abortTrigger === "cancel") return "cancel"
30
+ if (reason.abortTrigger === "stop") return "stop"
31
+ return "unknown"
32
+ }
33
+
34
+ /**
35
+ * 产生点错误(abort 面):AbortError + `reason` 透传 + `abortInfo` 标注。
36
+ * message 取既有通用文案(既有前缀断言零回归——死亡行前缀逐字保留)。
37
+ */
38
+ export function abortError(signal, layer, detail) {
39
+ const e = new DOMException("The operation was aborted", "AbortError")
40
+ e.reason = signal?.reason
41
+ e.abortInfo = { trigger: triggerOf(signal), layer, detail }
42
+ return e
43
+ }
44
+
45
+ /**
46
+ * 产生点错误(定时器面):自有 message + `abortInfo{trigger:"timeout"}`。
47
+ * name 保持 "Error"(既有分类谓词——`AbortError` 分支——零变化)。
48
+ */
49
+ export function timeoutError(message, layer, detail) {
50
+ const e = new Error(message)
51
+ e.abortInfo = { trigger: "timeout", layer, detail }
52
+ return e
53
+ }
54
+
55
+ /**
56
+ * 外部错误补标(undici / fetch 拒否等):缺 `abortInfo` 才补(不覆盖产生点标注);
57
+ * 不改 `name` / `message`(消费面零回归)。
58
+ * 第 4 参 detail 为站点名(站点表逐站点传——自由短串)。
59
+ */
60
+ export function annotateAbort(err, signal, layer, detail) {
61
+ if (err?.abortInfo) return err
62
+ try {
63
+ err.abortInfo = { trigger: triggerOf(signal), layer, detail: detail ?? "unrecorded" }
64
+ } catch { /* frozen error——保持未标注(合成器 unknown 告警兜底) */ }
65
+ return err
66
+ }
67
+
68
+ /** 死亡行长度上限(AGENT-LOOP.md §20.3 第 3 条——超长优先截 detail)。 */
69
+ const MAX_LEN = 300
70
+ /** unknown 形态 detail token(§20.3 第 3 条逐字)。 */
71
+ const NO_REASON = "no reason on signal"
72
+ /** 未标注回落 token(layer / detail 两面兜底)。 */
73
+ const UNRECORDED = "unrecorded"
74
+
75
+ /** 信号域 detail 回落(§20.3 第 1 条形态③——`abortDetail` 载站点名;错误未标注时仍可辨发起动作)。 */
76
+ const detailOf = (signal) => (typeof signal?.reason?.abortDetail === "string" ? signal.reason.abortDetail : null)
77
+
78
+ /** 求值链(§20.3 第 1 条:err.abortInfo → triggerOf(signal) → err.name 兜底)。 */
79
+ function resolveAbort(err, signal) {
80
+ const info = err?.abortInfo
81
+ if (info?.trigger) return { trigger: info.trigger, layer: info.layer ?? UNRECORDED, detail: info.detail || null }
82
+ const fromSignal = triggerOf(signal)
83
+ if (fromSignal !== "unknown") return { trigger: fromSignal, layer: UNRECORDED, detail: detailOf(signal) }
84
+ if (err?.name === "TimeoutError") return { trigger: "timeout", layer: UNRECORDED, detail: detailOf(signal) }
85
+ // AbortError / 无名——告警态(unknown 显式,空后缀即违规)
86
+ return { trigger: "unknown", layer: UNRECORDED, detail: NO_REASON }
87
+ }
88
+
89
+ /** detail 裁剪:优先截 detail(budget = 上限内剩余字符)。 */
90
+ function clipDetail(detail, budget) {
91
+ if (budget <= 0) return ""
92
+ return detail.length <= budget ? detail : detail.slice(0, Math.max(1, budget - 1)) + "…"
93
+ }
94
+
95
+ /**
96
+ * 死亡行合成器(§20.3 第 3 条——报告面单点):
97
+ * `<原 message>[ ← cause: <cause.message>][ · abort(<trigger>@<layer>:<detail>)]`
98
+ * - 原 message 前缀逐字保留(既有前缀 / 包含断言零回归);
99
+ * - 后缀出现条件 = `err.abortInfo` 存在 ∨ `signal?.aborted` ∨ `err.name ∈ {AbortError, TimeoutError}`;
100
+ * - cause 段(P1)独立于后缀("fetch failed" 类网络死亡真因同判);
101
+ * - 总长 ≤300 字符(超长先截 detail,仍超再截尾)。
102
+ */
103
+ export function deathLine(err, signal) {
104
+ let line = err?.message ?? String(err ?? "")
105
+ if (err?.cause?.message) line += ` ← cause: ${err.cause.message}`
106
+ const abortish = Boolean(err?.abortInfo) || Boolean(signal?.aborted) ||
107
+ err?.name === "AbortError" || err?.name === "TimeoutError"
108
+ if (abortish) {
109
+ const { trigger, layer, detail } = resolveAbort(err, signal)
110
+ const head = `${line} · abort(${trigger}@${layer}:`
111
+ // unknown 形态逐字用告警 token(§20.3 第 3 条——站点 detail 不进告警行);非串 detail 归一化
112
+ const text = trigger === "unknown" ? NO_REASON : (detail == null ? UNRECORDED : String(detail))
113
+ line = `${head}${clipDetail(text, MAX_LEN - head.length - 1)})`
114
+ }
115
+ return line.length > MAX_LEN ? line.slice(0, MAX_LEN - 1) + "…" : line
116
+ }
@@ -20,7 +20,9 @@
20
20
  * `{ stopReason: "end_turn" }` (kimi session.ts parity).
21
21
  */
22
22
  import { detectDanger, normalizeEOL, joinWithEol } from "../tools/shared.mjs"
23
- import { computeEditEntry, validateEditEntry, assertEditArgsExclusive } from "../tools/edit-diff.mjs"
23
+ import { computeEditEntry, validateEditEntry, assertEditArgsExclusive, hasLineParams } from "../tools/edit-diff.mjs"
24
+ // 第 27 批 §12.3①/③:relay 前缀文法单一权威(模块直连——不自持正则副本)。
25
+ import { parseRelayPath } from "../agent/relay-prefix.mjs"
24
26
 
25
27
  /** ACP ToolKind inference (schema v1 enum) — best-effort, clients render by kind. */
26
28
  function inferToolKind(name) {
@@ -92,7 +94,7 @@ export function buildAcpCallbacks({ sessionId, notify, request, log = () => {} }
92
94
  }
93
95
 
94
96
  // §15.1(TOOLS.md)D15.7 委派:edit 判定/应用单一权威 = 本地 computeEditEntry
95
- // (edit-diff.mjs——校验→判定序→应用:行级 LCS、零重叠→插入、replace_all 字面替换全部)。
97
+ // (edit-diff.mjs——校验→判定序→应用:行级 LCS、零重叠→替换即删、replace_all 字面替换全部)。
96
98
  // 桥只留「读 IDE 缓冲 → computeEditEntry → 写回 IDE 缓冲」——错误文本经抛错原样透传
97
99
  // ——与本地通道逐字一致(NF15.6b / AC15.10:not found / occurrences / 空 old / 空 new)。
98
100
  const EDIT_ABORT_PREFIX = "edit aborted (atomic — no files written): "
@@ -130,7 +132,7 @@ export function buildAcpCallbacks({ sessionId, notify, request, log = () => {} }
130
132
  const editBatch = async (args) => {
131
133
  const edits = args.edits
132
134
  if (!Array.isArray(edits) || edits.length === 0) {
133
- throw new Error("edits must be a non-empty array of {path, old_string, new_string}")
135
+ throw new Error("edits must be a non-empty array of {path, old_string | line/startLine+endLine, new_string}")
134
136
  }
135
137
  assertEditArgsExclusive(args)
136
138
  const groups = new Map() // path → { path, raw, content, edits }
@@ -167,26 +169,38 @@ export function buildAcpCallbacks({ sessionId, notify, request, log = () => {} }
167
169
 
168
170
  const callbacks = {
169
171
  onToken: (text) => {
170
- // Strip the subagent `[model]` metadata token (role#id/[model]<name>) — it's a
172
+ // 27 §12.3③ 1(R-A2.1):relay 前缀(role#id/——任意嵌套深度)零进显示面——
173
+ // 先剥前缀取 payload,信号判定与正文发送都作用在 payload 上。
174
+ const path = parseRelayPath(text)
175
+ const payload = path ? path.rest : text
176
+ // Strip the subagent `[model]` metadata token ([model]<name>) — it's a
171
177
  // TUI/webview display signal, not conversation content, and must not reach ACP clients.
172
- // §19.5 D-M8 (round2 #6): nested prefixes recurse — eng-coder#2/explore#1/[model]
173
- if (/^(?:[\w-]+#\d+\/)*\[model\]/.test(text)) return
174
- // D7 (AGENT-LOOP.md §7.2 + §19.5 round2 #6 + D-M7b): strip ⟦ev⟧ event tokens (bare or
175
- // any-depth prefixed variants turn/approval/done/settled/stopped/async async
176
- // = §19.5 D-M7b zero-field spawn marker) — they
177
- // carry RS control characters and are a TUI display signal; structured ACP
178
+ if (/^\[model\]/.test(payload)) return
179
+ // D7 (AGENT-LOOP.md §7.2 + §19.5 round2 #6 + D-M7b): strip ⟦ev⟧ event tokens (turn/
180
+ // approval/done/settled/stopped/async async = §19.5 D-M7b zero-field spawn marker)
181
+ // they carry RS control characters and are a TUI display signal; structured ACP
178
182
  // mapping (tool_call_update) is tracked separately in docs/TODO.md.
179
183
  // 有意为之:控制字符协议/转义序列剥离正则(ANSI/⟦ev⟧/SGR/history 双线分隔)
180
- if (/^(?:[\w-]+#\d+\/)*⟦ev⟧(?:turn|approval|done|settled|stopped|async)\x1e/.test(text)) return
181
- update("agent_message_chunk", { content: { type: "text", text } })
184
+ if (/^⟦ev⟧(?:turn|approval|done|settled|stopped|async)\x1e/.test(payload)) return
185
+ if (!payload) return // D6:剥后空载荷不发通知(防噪声空 chunk)
186
+ update("agent_message_chunk", { content: { type: "text", text: payload } })
187
+ },
188
+ onReasoning: (text) => {
189
+ // 第 27 批 §12.3③ 行 2:同 onToken 取 payload;空载荷不发(D6)。
190
+ const path = parseRelayPath(text)
191
+ const payload = path ? path.rest : text
192
+ if (!payload) return
193
+ update("agent_thought_chunk", { content: { type: "text", text: payload } })
182
194
  },
183
- onReasoning: (text) => update("agent_thought_chunk", { content: { type: "text", text } }),
184
195
  onUsage: (usage) => update("usage_update", { usage }),
185
196
  onWait: ({ phase, seconds }) => log(`[rate-limit] ${phase} waiting ~${seconds}s`),
186
197
  onCompress: () => log("[context] auto-compacted"),
187
198
 
188
199
  onToolCall: (name, args, toolId) => {
189
200
  const id = toolCallId()
201
+ // 第 27 批 §12.3③ 行 3:显示面剥前缀(title / kind);配对键 toolQueue 存原样 name(D3)。
202
+ const path = parseRelayPath(name)
203
+ const shown = path ? path.rest : name
190
204
  // D15.8(advisor 🔴#1 修复):模型级 id 每轮重置(sse.mjs finalizeToolCalls 内
191
205
  // seq=0——call_0 call_1… 跨轮/跨消息可重复——设计自注「跨 turn 不保证唯一」)。
192
206
  // 因此 push 前若队列已有同名同 toolId 条目,它必是结果永不回调的陈旧孤儿
@@ -200,8 +214,8 @@ export function buildAcpCallbacks({ sessionId, notify, request, log = () => {} }
200
214
  toolQueue.push({ name, id, toolId: toolId ?? null })
201
215
  update("tool_call", {
202
216
  toolCallId: id,
203
- title: name,
204
- kind: inferToolKind(name),
217
+ title: shown,
218
+ kind: inferToolKind(shown),
205
219
  status: "in_progress",
206
220
  rawInput: args ?? {},
207
221
  content: [contentBlock(JSON.stringify(args ?? {}))],
@@ -222,15 +236,19 @@ export function buildAcpCallbacks({ sessionId, notify, request, log = () => {} }
222
236
  * client. Any transport failure → reject (safety-first, kimi parity).
223
237
  */
224
238
  onPermissionRequest: async (name, args) => {
239
+ // 第 27 批 §12.3③ 行 4:显示面(请求文本 + toolCall.title)剥前缀;
240
+ // 危险基名判定与 peekToolId 照旧(配对键 = 原样名——D3)。
241
+ const path = parseRelayPath(name)
242
+ const shown = path ? path.rest : name
225
243
  // 危险命令标注(只提示不拦截):kimi 同款模式,帮助编辑器端用户审批
226
- const base = name.includes("/") ? name.split("/").pop() : name
244
+ const base = shown.includes("/") ? shown.split("/").pop() : shown
227
245
  const danger = base === "bash" ? detectDanger(args?.command ?? "") : undefined
228
- const content = [contentBlock(`Requesting approval to run ${name}`)]
246
+ const content = [contentBlock(`Requesting approval to run ${shown}`)]
229
247
  if (danger) content.push(contentBlock(`⚠️ Dangerous: ${danger}`))
230
248
  content.push(contentBlock(JSON.stringify(args ?? {})))
231
249
  const toolCall = {
232
- toolCallId: peekToolId(name) ?? toolCallId(), // D15.8:peek 不消费——result 仍要与自己的条目配对
233
- title: name,
250
+ toolCallId: peekToolId(name) ?? toolCallId(), // D15.8:peek 不消费(原样名键)——result 仍要与自己的条目配对
251
+ title: shown,
234
252
  content,
235
253
  }
236
254
  try {
@@ -269,7 +287,10 @@ export function buildAcpCallbacks({ sessionId, notify, request, log = () => {} }
269
287
  return { handled: true, result: `Error: fs/write_text_file failed: ${e.message}` }
270
288
  }
271
289
  }
272
- if (base === "edit" && (Array.isArray(args?.edits) || (path && typeof args?.old_string === "string" && typeof args?.new_string === "string"))) {
290
+ // 2026-09-08 D1:单形态按行号改(path + line/startLine/endLine + new_string——无
291
+ // old_string)同样走 IDE 缓冲通道(hasLineParams 判定)——否则回落本地写盘会与
292
+ // IDE 缓冲脱敏;editSingle → computeEditEntry 行号语义自动继承。
293
+ if (base === "edit" && (Array.isArray(args?.edits) || (path && typeof args?.new_string === "string" && (typeof args?.old_string === "string" || hasLineParams(args))))) {
273
294
  try {
274
295
  const text = Array.isArray(args?.edits) ? await editBatch(args) : await editSingle(path, args)
275
296
  return { handled: true, result: text }
@@ -325,7 +346,10 @@ export function replayHistory({ sessionId, notify, history, log = () => {} }) {
325
346
  // later tool_call_updates by toolCallId; an orphan update would be ignored.
326
347
  pendingToolCalls = calls.map((tc, i) => {
327
348
  const id = `t${++toolSeq}`
328
- const title = tc?.name ?? "tool"
349
+ // 27 §12.3③ 行 5(防御面——T18):历史工具名带前缀 → 剥;无前缀 → 零变化。
350
+ const raw = tc?.name ?? "tool"
351
+ const path = parseRelayPath(raw)
352
+ const title = path ? path.rest : raw
329
353
  update("tool_call", {
330
354
  toolCallId: id,
331
355
  title,
package/src/acp.mjs CHANGED
@@ -71,12 +71,17 @@ export function defaultIsConfigured() {
71
71
  }
72
72
  }
73
73
 
74
+ /** 第 27 批 §12.3⑤(R-A1.1):ACP 会话装配期剔除的工具。ACP 是 headless 通道——
75
+ * question 工具需要交互 UI(`src/tools/question.mjs` 无 `ctx.onQuestion` 即 throw),
76
+ * 模型可见即会调用、调用必错 → 装配期剔除(schema 直接少一条)。 */
77
+ export const ACP_EXCLUDED_TOOLS = ["question"]
78
+
74
79
  /** M1/M2 session factory: one agent per session, built from the process cwd (single-cwd model).
75
80
  * `id` is the ACP session id — it is baked into the callbacks at construction time
76
81
  * (buildAcpCallbacks closure), so it must be known BEFORE createAcpSession runs.
77
82
  * `request` is the transport's reverse-RPC channel (permissions + fs routing). */
78
83
  export async function defaultCreateSession({ id, notify, request, log }) {
79
- const agent = await assembleAgent()
84
+ const agent = await assembleAgent({ excludeTools: ACP_EXCLUDED_TOOLS })
80
85
  return createAcpSession({ id, agent, notify, request, log })
81
86
  }
82
87
 
@@ -4,9 +4,14 @@
4
4
  * a host fact: every `file:line: content` reference in a review is mechanically
5
5
  * checked against the CURRENT disk state; mismatches mark the finding
6
6
  * unverified and cannot support a push-back.
7
+ *
8
+ * 第 11 批(C / F14 / §14.5):解析候选 = cwd + **评审对象声明范围派生根**(声明仓根 /
9
+ * 声明文件目录 / 声明目录——纯路径派生,零扫描、零 git);命中判据三条件全中(围栏内 ∧
10
+ * 可读 ∧ 目标行含引文内容)⇒ 零新增假命中。失败原因三分(file unreadable /
11
+ * content mismatch @ path / path traversal)——父侧不再人肉复核。
7
12
  */
8
13
  import { readFileSync, realpathSync } from "node:fs"
9
- import { resolve, sep } from "node:path"
14
+ import { resolve, relative, dirname, extname, sep, isAbsolute, join } from "node:path"
10
15
 
11
16
  // `file:line: content` citations — the file group is narrowed to source/config
12
17
  // extensions so URLs (`example.com:8080: …`) don't become false-positive
@@ -25,48 +30,105 @@ export function extractCitations(text) {
25
30
  return out
26
31
  }
27
32
 
33
+ /** 候选解析根(§14.5——纯路径派生,候选顺序 = cwd → 各声明路径的派生根):
34
+ * 声明仓根(`cwd/<segs[0]>`)与 声明文件目录 / 声明目录本身。声明在 cwd 之外 → 不派生
35
+ * (relative 越出 cwd 或跨盘符——候选与声明脱节即假命中面)。 */
36
+ function citationRoots(cwd, scope) {
37
+ const base = resolve(cwd)
38
+ const roots = [base]
39
+ for (const s of Array.isArray(scope) ? scope : []) {
40
+ if (typeof s !== "string" || !s.trim()) continue
41
+ const abs = resolve(base, s)
42
+ const rel = relative(base, abs)
43
+ if (!rel || rel.startsWith("..") || isAbsolute(rel)) continue
44
+ const segs = rel.split(/[\\/]/).filter(Boolean)
45
+ if (segs.length === 0) continue
46
+ const repoRoot = join(base, segs[0])
47
+ const declaredDir = extname(abs) ? dirname(abs) : abs
48
+ for (const r of [repoRoot, declaredDir]) if (!roots.includes(r)) roots.push(r)
49
+ }
50
+ return roots
51
+ }
52
+
53
+ /** 单引文解析(§14.5):按候选顺序试 `resolve(root, file)`;三条件全中才算命中。
54
+ * @returns {{matched: true, root: string, resolved: string}|{matched: false, reason: string}} */
55
+ function resolveCitation(citation, roots, base) {
56
+ const fence = base + sep
57
+ let mismatch = null
58
+ let traversal = false
59
+ for (const root of roots) {
60
+ let real
61
+ try {
62
+ // Path confinement: citation paths are LLM-generated — never trust them.
63
+ // A hallucinated "../config.json" would otherwise read (and leak via the
64
+ // report) files outside the project, including API-key configs.
65
+ // realpathSync resolves symlinks too — a link inside the project that
66
+ // points outside must not pass the prefix check.
67
+ real = realpathSync(resolve(root, citation.file))
68
+ } catch {
69
+ continue // 该候选无此文件(或不可解析)——试下一候选
70
+ }
71
+ if (!real.startsWith(fence)) { traversal = true; continue }
72
+ let line = ""
73
+ try {
74
+ line = readFileSync(real, "utf8").split("\n")[citation.line - 1] ?? ""
75
+ } catch {
76
+ continue // 存在但读不了(目录等)——按未命中处理,试下一候选
77
+ }
78
+ if (line.includes(citation.content)) {
79
+ return { matched: true, root, resolved: relative(base, real).split(sep).join("/") }
80
+ }
81
+ mismatch ??= real
82
+ }
83
+ if (mismatch) return { matched: false, reason: `content mismatch @ ${relative(base, mismatch).split(sep).join("/")}` }
84
+ if (traversal) return { matched: false, reason: "path traversal" }
85
+ return { matched: false, reason: "file unreadable" }
86
+ }
87
+
28
88
  /**
29
89
  * Mechanically verify citations against the CURRENT file state: read the file,
30
90
  * take the exact line, check it CONTAINS the quoted content. Reports
31
91
  * N/M matched + the mismatches. Unverified citations cannot support a
32
92
  * push-back — the evidence rule becomes a host fact, not a prompt wish.
93
+ * @param {string} text — the review text
94
+ * @param {string} cwd — the agent's working directory (workspace root)
95
+ * @param {{scope?: string[]}} [opts] — scope = 评审对象声明路径(documents + paths);
96
+ * 省略 ⇒ 旧行为(仅 cwd 候选——签名向后兼容)。
33
97
  */
34
- export function verifyCitations(text, cwd) {
98
+ export function verifyCitations(text, cwd, opts = {}) {
35
99
  const citations = extractCitations(text)
36
100
  const matched = []
37
101
  const failed = []
38
- const root = resolve(cwd) + sep
102
+ const base = resolve(cwd)
103
+ const roots = citationRoots(cwd, opts?.scope)
39
104
  for (const c of citations) {
40
- try {
41
- // Path confinement: citation paths are LLM-generated — never trust them.
42
- // A hallucinated "../config.json" would otherwise read (and leak via the
43
- // report) files outside the project, including API-key configs.
44
- // realpathSync resolves symlinks too — a link inside the project that
45
- // points outside must not pass the prefix check.
46
- const resolved = realpathSync(resolve(cwd, c.file))
47
- if (!resolved.startsWith(root)) {
48
- failed.push({ ...c, reason: "path traversal" })
49
- continue
50
- }
51
- const line = readFileSync(resolved, "utf8").split("\n")[c.line - 1] ?? ""
52
- if (line.includes(c.content)) matched.push(c)
53
- else failed.push(c)
54
- } catch {
55
- failed.push({ ...c, reason: "file unreadable" })
105
+ const r = resolveCitation(c, roots, base)
106
+ if (r.matched) {
107
+ // 命中根记录(§14.5):经派生根解析(非 cwd 直解)的命中在报告中注明解析路径。
108
+ matched.push(r.root === base ? c : { ...c, root: r.root, resolved: r.resolved })
109
+ } else {
110
+ failed.push({ ...c, reason: r.reason })
56
111
  }
57
112
  }
58
113
  return { total: citations.length, matched, failed }
59
114
  }
60
115
 
61
116
  /** Append the verification report to the review text (visible to the parent agent). */
62
- export function appendCitationReport(text, cwd) {
63
- const { total, matched, failed } = verifyCitations(text, cwd)
117
+ export function appendCitationReport(text, cwd, opts = {}) {
118
+ const { total, matched, failed } = verifyCitations(text, cwd, opts)
64
119
  if (total === 0) return text // no citations — nothing to verify
65
120
  const lines = [
66
121
  "",
67
122
  "---",
68
123
  `[host-verified] ${matched.length}/${total} citations match current file state.`,
69
124
  ]
125
+ // 命中根透明(F14/§14.5):经声明范围派生根解析的命中逐条注明解析路径(cwd 直解的不列
126
+ // ——零噪音;列的正是修复前会被误报为 unreadable 的裸路径引用)。
127
+ const derived = matched.filter((c) => c.resolved)
128
+ if (derived.length > 0) {
129
+ lines.push("Citations resolved via the declared review scope (bare path — resolved root noted):")
130
+ for (const c of derived.slice(0, 10)) lines.push(`- ${c.file}:${c.line} → ${c.resolved}`)
131
+ }
70
132
  if (failed.length > 0) {
71
133
  lines.push("Citations that do NOT match the current file state (treat their claims as unverified):")
72
134
  for (const f of failed.slice(0, 10)) {
@@ -0,0 +1,174 @@
1
+ /**
2
+ * advisor/compaction.mjs — advisor review support (split out of advisor/run.mjs,
3
+ * 第 11 批 — run.mjs was 498/500 硬帽): context trimming + the review's resource
4
+ * limits + the terminal-state guards + the review-text assembler.
5
+ *
6
+ * estimateTokens / compactMessages moved VERBATIM (the only edit is the `pinned`
7
+ * re-attach — F13/§14.4 #3); renderTimeline moved verbatim too, so the tail
8
+ * GENERATOR and the tail CLASSIFIER stay in one file with the assembler they
9
+ * feed (§14.3 谓词 ↔ §14.6 结构化尾——同族单源)。拆分线 = 行数硬帽实测(见批次档 §5)。
10
+ */
11
+
12
+ import { providerSpec } from "../config.mjs" // 第 25 批:预算派生(与 loop.mjs:11 同源导入)
13
+ // B4(群 B 批,CLI §18.3——F32):CJK 加权单源(provider/rate.mjs 叶子向无环)
14
+ import { estimateText } from "../provider/rate.mjs"
15
+
16
+ export const MAX_ADVISOR_TURNS = 100
17
+ // NOTE: prompts/advisor-round{1,2,3}.md encourage the model to finish within
18
+ // ~30 tool turns — a prompt-level efficiency target, DISTINCT from the
19
+ // 100-turn mechanical hard cap (MAX_ADVISOR_TURNS above; pure runaway-loop
20
+ // guard). They serve different purposes; do NOT synchronize them.
21
+
22
+ // Context window limits
23
+ // 上下文预算(第 25 批——120K 硬编码退场):预算跟随评审模型窗口(providerSpec:
24
+ // 模型规格表 × provider 级 context 覆盖)。头寸用途 = chars/4 估算误差 + 响应/协议开销
25
+ // (内存不构成约束——设计 §16.4);判死线仍是宿主机自限线,服务端窗口约束不变。
26
+ export const CONTEXT_LIMIT_RATIO = 0.8 // 判死线 = 窗口 × 0.8
27
+ const COMPACT_TRIGGER_RATIO = 0.8 // 压缩触发 = 判死线 × 0.8(既有关系零改)
28
+
29
+ /** 评审上下文预算(纯函数——两档阈值可机测;provider 为 null 时退化默认规格)。 */
30
+ export function advisorContextBudget(provider) {
31
+ const limit = Math.floor(providerSpec(provider).context * CONTEXT_LIMIT_RATIO)
32
+ return { limit, compactAt: Math.floor(limit * COMPACT_TRIGGER_RATIO) }
33
+ }
34
+
35
+ export const TOOL_TIMEOUT_MS = 30_000 // single tool timeout
36
+ export const REVIEW_TIMEOUT_MS = 600_000 // whole review timeout (10 minutes)
37
+ export const MAX_RESULT_CHARS = 64 * 1024 // tool result truncation (line-aware; 64K, aligned with main offload limit)
38
+ const MAX_KEY_FILES_IN_COMPACTION = 5 // files named in the compaction summary
39
+
40
+ /** Estimate token count from messages(B4——群 B 批 CLI §18.3:扁平 chars/4 改 `estimateText`
41
+ * 加权式——ASCII/4 + 非 ASCII/1;纯 ASCII 与旧式逐值相等;CJK 低估 ~3-4× 修正;
42
+ * walker(content / tool_calls 两源)与计数口径零改)。 */
43
+ export function estimateTokens(messages) {
44
+ return messages.reduce((sum, msg) => {
45
+ const content = typeof msg.content === "string" ? msg.content : JSON.stringify(msg.content || "")
46
+ const toolCalls = msg.tool_calls ? JSON.stringify(msg.tool_calls) : ""
47
+ return sum + estimateText(content + toolCalls)
48
+ }, 0)
49
+ }
50
+
51
+ /** Compact early messages when context grows too large — LOCAL trimming only
52
+ * (no LLM summarization). MUTATES in place (splice) so the caller's array
53
+ * reference stays valid — a reassignment would leave the caller's logging
54
+ * (tool-call count, token estimate) reading a stale array. */
55
+ export function compactMessages(messages, pinned = null) {
56
+ // Keep: system prompt, last 20 messages (≈ 10 assistant+tool exchanges),
57
+ // user message — the rest is summarized.
58
+ if (messages.length <= 20) return
59
+
60
+ const system = messages[0]
61
+ const recent = messages.slice(-20)
62
+ const old = messages.slice(1, -20)
63
+
64
+ // Count actual tool messages (old.length counts user/assistant rows too)
65
+ const toolCount = old.filter((m) => m.role === "tool").length
66
+ const keyFiles = old
67
+ .filter((m) => m.role === "tool")
68
+ .map((m) => m.content?.split("\n")[0]?.slice(0, 50)) // first line of tool results typically names the file that was read/grepped
69
+ .filter(Boolean)
70
+ .slice(0, MAX_KEY_FILES_IN_COMPACTION)
71
+ const filesPart = keyFiles.length > 0 ? ` Key files examined: ${keyFiles.join(", ")}` : ""
72
+ const summary = `Earlier exploration: ${toolCount} tool calls completed.${filesPart}`
73
+
74
+ // F13(第 11 批 §14.4 #3):压缩丢掉的正是**首条 user 消息**(评审简报,含 token)——
75
+ // pinned 由评审参数构建(非模型输出),在本次压缩动作内作为一条 user 消息重挂(幂等可读:
76
+ // 重复压缩允许重复挂回,不做存在性判定)。
77
+ const pin = pinned ? [{ role: "user", content: pinned }] : []
78
+ messages.splice(0, messages.length,
79
+ system,
80
+ { role: "user", content: `[Context compacted] ${summary}` },
81
+ ...pin,
82
+ ...recent)
83
+ }
84
+
85
+ // ─────────────────────────────────────────────────────────────────────────────
86
+ // 不完整判定族(A / F16 共用单谓词——§14.3;六 kind = 宿主尾族)
87
+ // ─────────────────────────────────────────────────────────────────────────────
88
+
89
+ /** 宿主尾族六 kind 的块首行逐字前缀(§14.3 表)。变量段(token 数 / 秒数 / 工具轮数)
90
+ * 不入前缀——取各尾的固定字面部分;`review_failed` = run.mjs catch 的字符串 resolve
91
+ * 形态(不 throw),其余五条 = renderTimeline 尾(loop.mjs)。 */
92
+ const ADVISOR_INCOMPLETE_PREFIXES = [
93
+ ["context_limit", "Advisor: context window limit"],
94
+ ["turn_cap", "Advisor: stopped after"],
95
+ ["timeout", "Advisor: review timeout"],
96
+ ["empty", "Advisor: empty response"],
97
+ ["interrupted", "Advisor: interrupted."],
98
+ ["review_failed", "Advisor: review failed"],
99
+ ]
100
+
101
+ /** 单谓词(三消费点同源:design 结算 / code 完成守卫 / 报告提示)——**块首行扫描**(按空行
102
+ * 分块,逐块取首行 trim 后测前缀;时间线与尾以空行相接,六条尾均以块首行形态落地)。
103
+ * 负向精度(§14.3 修正轮):引文中同串的**非块首形态**(围栏内行 / 表格行 / 引用行)不判
104
+ * incomplete;块首裸行引用同串的残余误报方向安全(fail-closed——多付一轮重跑,如实登记)。
105
+ * @returns {string|null} kind 或 null */
106
+ export function advisorIncompleteMarker(text) {
107
+ for (const block of String(text ?? "").split(/\n\s*\n/)) {
108
+ const first = block.split("\n").find((l) => l.trim() !== "")
109
+ if (!first) continue
110
+ const line = first.trim()
111
+ for (const [kind, prefix] of ADVISOR_INCOMPLETE_PREFIXES) {
112
+ if (line.startsWith(prefix)) return kind
113
+ }
114
+ }
115
+ return null
116
+ }
117
+
118
+ // ─────────────────────────────────────────────────────────────────────────────
119
+ // 预算提示 + 结构化超时尾(D / F15——§14.6 #2/#3)
120
+ // ─────────────────────────────────────────────────────────────────────────────
121
+
122
+ /** 0.75 一次性预算提示判定(纯函数——阈值两侧可机测;每场评审至多一次)。 */
123
+ export function shouldBudgetNudge(elapsedMs, budgetMs, nudged) {
124
+ return !nudged && Number.isFinite(budgetMs) && budgetMs > 0 && elapsedMs >= budgetMs * 0.75
125
+ }
126
+
127
+ /** 预算提示文案(逐字——§14.6 #2;由循环注入一条 user 消息)。 */
128
+ export function budgetNudgeText(elapsedMs, budgetMs) {
129
+ const secs = (ms) => Math.round(ms / 100) / 10
130
+ const pct = Math.round((elapsedMs / budgetMs) * 100)
131
+ return `⏳ review budget: ~${pct}% consumed (${secs(elapsedMs)}s of ${secs(budgetMs)}s). Converge now: emit your findings table for the evidence you have verified, mark anything you could not verify explicitly as \`unverified\` (unverified evidence must not support a pass), and emit your verdict line.`
132
+ }
133
+
134
+ /** 结构化超时尾(§14.6 #3):族前缀 `Advisor: review timeout after {S}s.` 逐字保持
135
+ * (判定族字面依赖);其后 = 机读统计(rounds / tool calls / review text produced)
136
+ * + 可执行恢复指引(narrower scope / 调预算)。 */
137
+ export function timeoutTail(timeoutMs, rounds, toolCalls, producedText) {
138
+ const s = Math.round(timeoutMs / 1000)
139
+ return [
140
+ `Advisor: review timeout after ${s}s. Review incomplete — the wall-clock budget was exhausted; partial findings (if any) are above.`,
141
+ `- rounds: ${rounds} · tool calls: ${toolCalls} · review text produced: ${producedText ? "yes" : "no"}`,
142
+ `- budget: ${s}s (agent.advisor.timeoutMs) — re-run with a narrower scope (split the review across fewer documents) or raise the budget.`,
143
+ ].join("\n")
144
+ }
145
+
146
+ // ─────────────────────────────────────────────────────────────────────────────
147
+ // 评审文本装配(loop 的尾经此与时间线合流——与尾族同文件:生成 / 判定 / 装配单源)
148
+ // ─────────────────────────────────────────────────────────────────────────────
149
+
150
+ // The live "[thinking…]" wait indicator shares its exact text with the TUI
151
+ // cleanup regex (agent-turn.mjs strips it before flushing to history) — keep
152
+ // them in lockstep.
153
+ export const ADVISOR_THINKING_PLACEHOLDER = "\n[thinking…]\n"
154
+
155
+ /**
156
+ * Tool-call progress line summary delegates to the single source describeToolArgs
157
+ * (../tui/tool-args.mjs) — the same function main-agent tool blocks and subagent
158
+ * blocks use. 2026-08-31: replaced the local picker (action/path/pattern/command-only)
159
+ * so advisor progress lines show the quoted-path forms everywhere else.
160
+ */
161
+ /**
162
+ * Render the ordered review timeline — thinking / tool progress / final text
163
+ * interleaved EXACTLY as emitted, so the persisted record shows the review
164
+ * process at its real positions. A summary appended at the end would lose the
165
+ * order (the user-visible "no tool calls in the advisor record" gap). The
166
+ * live "[thinking…]" placeholder is stripped (wait indicator, not content).
167
+ */
168
+ export function renderTimeline(timeline, tail = "") {
169
+ const body = timeline
170
+ .map((b) => b.text.replaceAll(ADVISOR_THINKING_PLACEHOLDER, "").trim())
171
+ .filter(Boolean)
172
+ .join("\n\n")
173
+ return [body, tail].filter(Boolean).join("\n\n")
174
+ }