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,294 +0,0 @@
1
- /**
2
- * agent-tools/read-history.mjs — read_history tool (SESSION.md §9 + §13 R19 cross-session).
3
- *
4
- * Query message history — THIS session by default, any session on disk with `path`
5
- * (SESSION.md §13 R19): an explicit session file path deep-queries that file's
6
- * history line; "cwd:<dir>" discovers the sessions stored for that directory.
7
- *
8
- * Default (no path) — THIS session's full human-readable record (agent._fullHistory
9
- * — NEVER compacted, audit-complete). Use to recall what was said or done earlier:
10
- * design decisions, tool-call timing, past rulings.
11
- *
12
- * Filters AND together: role / keyword (message text) / tool (tool messages by
13
- * name + assistant messages that declared the call) / since-until (epoch ms
14
- * window, inclusive-inclusive, matches ONLY messages that carry ts) /
15
- * limit (default 50, clamped to 200) / direction (oldest/newest — which end of
16
- * the matched set the limit window is taken from).
17
- *
18
- * Returns a JSON array in chronological order. Every message without ts comes
19
- * back as ts:null and can never match a time window (legacy sessions). Content
20
- * is truncated to ~500 chars with an explicit marker — full text lives in the
21
- * session file. assistant tool_calls are summarized to a name list (arguments
22
- * never expanded).
23
- *
24
- * Cross-session (SESSION.md §13 D-R19a): path = a session file path (absolute, or
25
- * relative to the project cwd) → read that file's history line and apply the SAME
26
- * filter surface; path = "cwd:<dir>" → list every slot stored for that directory
27
- * (slot number + full file path + title/message count/updatedAt — no dead-slot
28
- * filtering, v1 decision). Single-file retrieval is guarded by a line-scan cap
29
- * (READ_HISTORY_SCAN_MAX — an oversized file is refused before it is read whole)
30
- * plus a message-count cap (READ_HISTORY_MAX_MESSAGES = 50,000 — L24 双保险第二道).
31
- *
32
- * readonly: true — planMode pass / no permission ask. Registered depth-0 only:
33
- * subagents get their own throwaway history, so querying "the session" from a
34
- * child would be semantically confusing (SESSION.md §9.5 refinement 1 + §13 T-R19.4).
35
- * §13 R19 extension mirrored per SESSION.md §13 — double-end isomorphic, no
36
- * cross-end byte test (thincoder-vscode/src/agent-tools/read-history.mjs).
37
- */
38
-
39
- import { openSync, readSync, closeSync, readFileSync, existsSync, statSync } from "node:fs"
40
- import { isAbsolute, resolve } from "node:path"
41
- import { listSlots, slotPath } from "../session-slots.mjs"
42
-
43
- const DEFAULT_LIMIT = 50
44
- const MAX_LIMIT = 200
45
- const CONTENT_CAP = 500
46
- const VALID_ROLES = new Set(["user", "assistant", "tool"])
47
-
48
- /** 单槽检索行扫护栏(SESSION.md §13 D-R19a——评审 #3 定稿:超限不再读全文,返回定稿错误文案)。 */
49
- export const READ_HISTORY_SCAN_MAX = 200_000
50
-
51
- /** L24 消息数预算(评审 #2 钉死——双保险第二道):行扫按物理 \n 行计——JSON 单行槽
52
- * 行扫不设防——parse 后 history 数组长度超限即拒(同款定稿文案——双端同常量同文案)。 */
53
- export const READ_HISTORY_MAX_MESSAGES = 50_000
54
-
55
- /** 超限错误文案(SESSION.md §13——逐字定稿——T-R19.7 断言)。 */
56
- const TOO_LARGE_ERROR = JSON.stringify({ error: "session too large — refine keyword or since/until" })
57
-
58
- /** 检索/记忆族消歧总纲(SESSION.md §13 D-R19b——逐字定稿——read_history 描述尾段——T-R19.5 锚)。 */
59
- const SEARCH_FAMILY_GUIDE =
60
- "检索/记忆族选哪个:查**本会话**说过/裁定过 → read_history(默认);查**别的会话/项目**旧对话 → read_history 带 path/cwd 参数;查**本 run 改过哪些文件** → recent_changes;查**跨会话已存知识/约定**(memory)→ memory search;查**项目设计文档** → doc_search;查**代码实现** → code_search;查 git 历史快照 → checkpoint cat/versions。read_history 只查会话消息——文件级改动用 recent_changes——知识与约定用 memory——互相不替代。"
61
-
62
- /** Message text for keyword matching + output: strings pass through; multimodal content arrays → text parts joined (never crashes, empty parts skipped, images ignored). */
63
- function messageText(m) {
64
- if (typeof m?.content === "string") return m.content
65
- if (Array.isArray(m?.content)) {
66
- return m.content
67
- .map((p) => (p && typeof p === "object" && p.type === "text" ? p.text ?? "" : ""))
68
- .filter((t) => t.length > 0)
69
- .join(" ")
70
- }
71
- return ""
72
- }
73
-
74
- /** Truncate long content (~500 chars) with an explicit marker. The cut never splits a UTF-16
75
- * surrogate pair (emoji etc.) — a lone high surrogate in tool output would be an eyesore at
76
- * minimum; the send layer sanitizes it anyway, but clean output costs nothing (setup.mjs
77
- * safeSliceUTF16 same rule). */
78
- function truncateContent(text) {
79
- const t = String(text ?? "")
80
- if (t.length <= CONTENT_CAP) return t
81
- let end = CONTENT_CAP
82
- if (t.charCodeAt(end - 1) >= 0xd800 && t.charCodeAt(end - 1) <= 0xdbff) end-- // high surrogate at the cut → step back
83
- return t.slice(0, end) + `\n… (truncated: ${t.length - end} chars — full text is in the session file)`
84
- }
85
-
86
- /** Tool name across both stored shapes ({function:{name}} and flat {name}). */
87
- function toolCallName(tc) {
88
- return tc?.function?.name ?? tc?.name ?? ""
89
- }
90
-
91
- /** Parse a ts window boundary (epoch ms number; numeric strings tolerated). Returns the number or an error string. */
92
- function parseTs(value, label) {
93
- if (value === undefined || value === null) return null
94
- const n = typeof value === "number" ? value : Number(value)
95
- if (!Number.isFinite(n)) return `Error: invalid ${label} "${value}" — must be epoch milliseconds (number)`
96
- return n
97
- }
98
-
99
- /** Map one matched message to its JSON entry shape. */
100
- function toEntry(m) {
101
- const entry = {
102
- ts: typeof m.ts === "number" ? m.ts : null,
103
- role: m.role ?? null,
104
- }
105
- if (m.name !== undefined) entry.name = m.name
106
- if (m.tool_call_id !== undefined) entry.tool_call_id = m.tool_call_id
107
- entry.content = truncateContent(messageText(m))
108
- if (Array.isArray(m.tool_calls) && m.tool_calls.length > 0) {
109
- entry.tool_calls = m.tool_calls.map(toolCallName).filter(Boolean)
110
- }
111
- return entry
112
- }
113
-
114
- /** AND-filter one history message (role/keyword/tool/since-until) — shared by the in-memory
115
- * default and the cross-session file query (SESSION.md §13 D-R19a: 同 filter 面应用). */
116
- function matches(m, { role, kwRe, tool, since, until }) {
117
- if (!m || typeof m !== "object") return false
118
- if (role !== undefined && m.role !== role) return false
119
- if (kwRe) {
120
- const text = messageText(m)
121
- if (!kwRe.test(text)) return false
122
- }
123
- if (tool) {
124
- const byName = m.role === "tool" && m.name === tool
125
- const byDeclaration = m.role === "assistant" && Array.isArray(m.tool_calls) && m.tool_calls.some((tc) => toolCallName(tc) === tool)
126
- if (!byName && !byDeclaration) return false
127
- }
128
- const ts = m.ts
129
- if (since !== null || until !== null) {
130
- if (typeof ts !== "number") return false // no ts → no time-window match
131
- if (since !== null && ts < since) return false
132
- if (until !== null && ts > until) return false
133
- }
134
- return true
135
- }
136
-
137
- /** Direction picks the END of the matched set; output stays chronological either way. */
138
- function formatMatches(matched, direction, limit) {
139
- const windowed = direction === "oldest" ? matched.slice(0, limit) : matched.slice(-limit)
140
- return JSON.stringify(windowed.map(toEntry))
141
- }
142
-
143
- /** Line-scan guard: stream-count physical newlines, bailing the moment the cap is crossed —
144
- * an oversized file is refused BEFORE it is read whole ("不再读全文"——SESSION.md §13 D-R19a). */
145
- function exceedsScanMax(file) {
146
- const CHUNK = 64 * 1024
147
- let fd = null
148
- try {
149
- fd = openSync(file, "r")
150
- const buf = Buffer.alloc(CHUNK)
151
- let newlines = 0
152
- for (;;) {
153
- const n = readSync(fd, buf, 0, CHUNK, null)
154
- if (n <= 0) break
155
- for (let i = 0; i < n; i++) {
156
- if (buf[i] === 0x0a) newlines++
157
- }
158
- if (newlines > READ_HISTORY_SCAN_MAX) return true
159
- }
160
- return false
161
- } catch {
162
- return false // 行扫失败 → 交由后续读取/解析路径给出真实错误
163
- } finally {
164
- if (fd !== null) {
165
- try { closeSync(fd) } catch { /* ignore */ }
166
- }
167
- }
168
- }
169
-
170
- /** Cross-session deep query: one session file, same filter surface (§13 D-R19a). */
171
- function querySessionFile(pathArg, { role, kwRe, tool, since, until, direction, limit }, baseCwd) {
172
- const file = isAbsolute(pathArg) ? pathArg : resolve(baseCwd ?? process.cwd(), pathArg)
173
- if (!existsSync(file)) return `Error: session file not found: ${file}`
174
- if (exceedsScanMax(file)) return TOO_LARGE_ERROR
175
- let text
176
- try {
177
- text = readFileSync(file, "utf8")
178
- } catch (e) {
179
- return `Error: failed to read session file ${file}: ${e.message}`
180
- }
181
- let data
182
- try {
183
- data = JSON.parse(text)
184
- } catch (e) {
185
- return `Error: ${file} is not a valid session file (corrupt JSON: ${e.message})`
186
- }
187
- if (!data || typeof data !== "object" || !Array.isArray(data.history)) {
188
- return `Error: ${file} is not a valid session file (no history array)`
189
- }
190
- if (data.history.length > READ_HISTORY_MAX_MESSAGES) {
191
- // L24 消息数第二道(parse 后——行扫按物理行、单行 JSON 槽行扫不设防——超限同款拒绝)。
192
- return TOO_LARGE_ERROR
193
- }
194
- const matched = data.history.filter((m) => matches(m, { role, kwRe, tool, since, until }))
195
- return formatMatches(matched, direction, limit)
196
- }
197
-
198
- /** Discovery surface (path = "cwd:<dir>"): list every slot stored for that directory, one line
199
- * per slot — slot number + FULL session file path + title/message count/updatedAt(§13 D-R19a
200
- * ——评审 #2:摘要必须含寻址字段——模型第二步深查 = 复制行内文件路径重调 path=)。 */
201
- function discoverCwd(raw, baseCwd) {
202
- const dir = resolve(baseCwd ?? process.cwd(), raw)
203
- let st = null
204
- try {
205
- st = statSync(dir)
206
- } catch { /* fallthrough to the explicit error below */ }
207
- if (st === null || !st.isDirectory()) {
208
- return `Error: unknown cwd "${raw}" — no session directory for this cwd (directory not found: ${dir})`
209
- }
210
- const slots = listSlots(dir) // 时间序(updatedAt 降序)——含 manifest 记录的全部槽(v1 不做死槽过滤)
211
- if (slots.length === 0) {
212
- return `(no session slots found for cwd: ${dir} — no sessions started there yet)`
213
- }
214
- const lines = slots.map((s) => {
215
- const title = s.title ? `"${s.title}"` : "(untitled)"
216
- return `slot ${s.slot}: ${slotPath(dir, s.slot)} — title: ${title}, messages: ${s.messageCount}, updatedAt: ${s.updatedAt}`
217
- })
218
- return `Session slots for cwd: ${dir} (newest first):\n${lines.join("\n")}`
219
- }
220
-
221
- export const readHistoryTool = {
222
- name: "read_history",
223
- description:
224
- "Query message history — THIS session by default, any session on disk with `path`. " +
225
- "Default (no path): THIS session's full record (never compacted, audit-complete) — recall what " +
226
- "was said or done earlier: design decisions, tool-call timing, past rulings. " +
227
- "Filters combine with AND: role / keyword (case-insensitive substring of message text) / " +
228
- "tool (tool result messages by name AND the assistant messages that declared the call — pair with tool_call_id / ts for timing) / " +
229
- "since-until (epoch ms time window; only messages with ts can match) / limit (default 50, clamped to 200) / direction (which end of the matches to take). " +
230
- "Returns a JSON array in chronological order: [{ts, role, name?, tool_call_id?, content (≈500 chars, truncated marker), tool_calls (names only)}]. " +
231
- "Messages without ts return ts:null. Content is truncated — the full text is in the session file. " +
232
- "Cross-session (path, optional): a session file path deep-queries THAT session's history with the same filters " +
233
- "(relative paths resolve against the project cwd); \"cwd:<dir>\" lists every session slot stored for that directory — " +
234
- "one line per slot: slot number + full session file path + title + message count + updatedAt; copy a listed file path into path= to deep-query it. " +
235
- "A session file over 50,000 messages or 200,000 lines is refused (\"session too large\") instead of being read whole.\n" +
236
- SEARCH_FAMILY_GUIDE,
237
- parameters: {
238
- type: "object",
239
- properties: {
240
- role: { type: "string", enum: ["user", "assistant", "tool"], description: "Only messages with this role." },
241
- keyword: { type: "string", description: "Case-insensitive substring of the message text (multimodal messages match on their text parts)." },
242
- tool: { type: "string", description: "Only messages for this tool: role=tool messages with name=tool, plus assistant messages that declared a call to it." },
243
- since: { type: "integer", description: "Earliest ts to match, epoch ms, INCLUSIVE. Messages without ts never match a time window." },
244
- until: { type: "integer", description: "Latest ts to match, epoch ms, INCLUSIVE. since > until yields an empty result." },
245
- limit: { type: "integer", description: "Maximum messages to return (default 50; larger values are clamped to 200)." },
246
- direction: { type: "string", enum: ["oldest", "newest"], description: "Take the limit window from the oldest or newest end of the matched set (default newest)." },
247
- path: { type: "string", description: "Optional — query another session instead of this one: a session file path (as listed by a \"cwd:<dir>\" call) deep-queries that session; \"cwd:<dir>\" lists that directory's session slots (slot number + full file path + title + message count + updatedAt)." },
248
- },
249
- },
250
- readonly: true,
251
- execute(args, ctx) {
252
- const a = args ?? {}
253
- if (a.path !== undefined && (typeof a.path !== "string" || a.path.trim().length === 0)) {
254
- return `Error: invalid path "${a.path}" — must be a session file path or "cwd:<dir>"`
255
- }
256
- const role = a.role
257
- if (role !== undefined && (typeof role !== "string" || !VALID_ROLES.has(role))) {
258
- return `Error: invalid role "${role}" — valid roles: user, assistant, tool`
259
- }
260
- const direction = a.direction ?? "newest"
261
- if (direction !== "oldest" && direction !== "newest") {
262
- return `Error: invalid direction "${direction}" — valid values: oldest, newest`
263
- }
264
- const since = parseTs(a.since, "since")
265
- if (typeof since === "string") return since
266
- const until = parseTs(a.until, "until")
267
- if (typeof until === "string") return until
268
- let limit = DEFAULT_LIMIT
269
- if (a.limit !== undefined) {
270
- limit = Math.floor(Number(a.limit))
271
- if (!Number.isFinite(limit)) return `Error: invalid limit "${a.limit}" — must be a number`
272
- limit = Math.min(Math.max(1, limit), MAX_LIMIT)
273
- }
274
- const keyword = typeof a.keyword === "string" && a.keyword.length > 0 ? a.keyword : null
275
- // Case-insensitive substring WITHOUT copying the full message text: the human line is
276
- // never compacted — single tool results can be hundreds of KB to MBs. Lowercase the
277
- // needle once and run a regex-i test over the haystack (escaping regex metachars so the
278
- // keyword stays a literal substring).
279
- const kwRe = keyword ? new RegExp(keyword.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "i") : null
280
- const tool = typeof a.tool === "string" && a.tool.length > 0 ? a.tool : null
281
- const baseCwd = ctx.agent?.cwd ?? process.cwd()
282
-
283
- const pathArg = typeof a.path === "string" && a.path.trim().length > 0 ? a.path.trim() : null
284
- if (pathArg !== null) {
285
- return pathArg.startsWith("cwd:")
286
- ? discoverCwd(pathArg.slice("cwd:".length), baseCwd)
287
- : querySessionFile(pathArg, { role, kwRe, tool, since, until, direction, limit }, baseCwd)
288
- }
289
-
290
- const history = Array.isArray(ctx.agent?._fullHistory) ? ctx.agent._fullHistory : []
291
- const matched = history.filter((m) => matches(m, { role, kwRe, tool, since, until }))
292
- return formatMatches(matched, direction, limit)
293
- },
294
- }
@@ -1,24 +0,0 @@
1
- /**
2
- * recent_changes tool: list files touched by this agent run (write/edit/insert_after/delete).
3
- * More precise than git status — only looks at this session's changes, independent of git tracking.
4
- * Helps the model recall what it already modified during long tasks.
5
- */
6
- export const recentChangesTool = {
7
- name: "recent_changes",
8
- description:
9
- "Show files modified in this agent run (write/edit/insert_after/delete). " +
10
- "Use when you need to remember which files you've already touched — during long multi-file tasks, " +
11
- "it's easy to lose track. This is scoped to the current run, unlike git status which shows all uncommitted changes. " +
12
- "For session-level history (what was said in a session), use read_history.",
13
- parameters: {
14
- type: "object",
15
- properties: {},
16
- },
17
- readonly: true,
18
- execute(args, ctx) {
19
- const files = ctx.agent._touchedFiles ?? []
20
- if (files.length === 0) return "(no files modified in this run yet)"
21
- const deduped = [...new Set(files)]
22
- return `Touched ${deduped.length} file(s) this run:\n${deduped.join("\n")}`
23
- },
24
- }
@@ -1,93 +0,0 @@
1
- /**
2
- * review-streak.mjs — design-review failure streak guard(第 33 批——2026-09-11)。
3
- *
4
- * 同一 doc-set 的 design 评审**连续**未产出可用结算(宿主截断尾五 kind + 陈旧结算 +
5
- * 凭证落盘失败 + 无报告结算)达 `MAX_DESIGN_REVIEW_STREAK` 次 ⇒ 后续发起被拒
6
- * (工具层预检 + `runAdvisorReview` 内防线两级——零 LLM / 不耗轮次 / 不置「评审已覆盖」)。
7
- * 设计权威 = `docs/design/ADVISOR-CONVERGENCE.md` §17(需求 = requirements 档 §12 F28/F29 + N20/N21)。
8
- *
9
- * 中立模块(**不 import 任何 src/ 模块**——打断潜在环,§17.5 模块图):
10
- * - `normAbs` 自 advisor-settle.mjs 迁入(原处 re-export——既有 import 面零变);
11
- * - `docSetKey` 自 advisor-async.mjs 迁入(原为私有——零 import 面)。
12
- * 分类单源:`designReviewOutcome` 为异步结算 / 同步面两计数点共用(D-SK8——防两处分类漂移)。
13
- * 载体 = 会话级内存 `agent._designReviewStreaks`(Map——不落盘、不进 session 文件;
14
- * eng 模式切换不清护栏——与 `_advisorRuns` 刻意不同步,§17.9 #5 定案)。
15
- */
16
- import { join } from "node:path"
17
-
18
- /** 连续未产出可用结算的阈值(三振——§17.2 表 1 选定 N=3;`MAX_ADVISOR_ROUNDS` 零改动)。 */
19
- export const MAX_DESIGN_REVIEW_STREAK = 3
20
-
21
- /** ABS 归一(cwd 相对 → cwd 拼接)——陈旧判定 / 冻结拦截 / doc-set 键同源(§14.14 E-4)。 */
22
- export function normAbs(p, cwd) {
23
- const s = String(p)
24
- return /^[a-zA-Z]:[\\/]/.test(s) || s.startsWith("/") || s.startsWith("\\\\") ? s : join(cwd, s)
25
- }
26
-
27
- /** Canonical scope key for design reviews — the document multi-set
28
- * (order-insensitive, ABS-path normalized — launch 与 continuation 的写法差异
29
- * ("./docs/x.md" vs "docs/x.md"、反斜杠) 不误建新实例).
30
- * 第 33 批自 advisor-async.mjs 逐字迁入(护栏与实例续跑同锚单源)。 */
31
- export function docSetKey(documents, cwd) {
32
- const list = [...new Set((documents ?? [])
33
- .filter((d) => typeof d === "string" && d.trim())
34
- .map((d) => normAbs(d, cwd)))]
35
- return JSON.stringify(list.sort())
36
- }
37
-
38
- /** 护栏适用的键判据:空清单(`[]` / `null` 的 `docSetKey` 产出 = "[]")不适用——不计数、
39
- * 不停止(§17.9 #3 登记;fail-open 于此面)。 */
40
- export function designReviewStreakApplies(key) {
41
- return typeof key === "string" && key.length > 0 && key !== "[]"
42
- }
43
-
44
- /**
45
- * 结算分类(纯函数单源——§17.3 优先级表,自上而下首个命中;输入 = 宿主可见事实,
46
- * **零 LLM 输出解析**,N20)。neutral = 无信息事件(取消 / 中断 / 拒发)——不打断连续计数。
47
- * @param {{launchRefused?: boolean, stale?: boolean, hasResult?: boolean,
48
- * incomplete?: string|null, persistFailed?: boolean}} input
49
- * @returns {{reset: boolean, count: string|null}} reset=true 计数复位;count=需加一的类名;
50
- * 两者皆空 = neutral(不动计数)。
51
- */
52
- export function designReviewOutcome(input) {
53
- const { launchRefused = false, stale = false, hasResult = true, incomplete = null, persistFailed = false } = input ?? {}
54
- if (launchRefused) return { reset: false, count: null } // 1. 未发起请求(无尝试发生——§14.4 既有语义)
55
- if (stale) return { reset: false, count: "stale" } // 2. 陈旧结算(未产出可用凭证)
56
- if (!hasResult) return { reset: false, count: "no_report" } // 3. 无报告(fail-closed)
57
- if (incomplete && incomplete !== "interrupted") return { reset: false, count: String(incomplete) } // 4. 宿主截断尾五 kind
58
- if (incomplete === "interrupted") return { reset: false, count: null } // 5. 用户 / 系统中断类(与 cancelled 同族)
59
- if (persistFailed) return { reset: false, count: "no_credential" } // 6. pass 但槽落盘失败(无可用凭证)
60
- return { reset: true, count: null } // 7. 可用判决(pass 且落盘成功 / changes-required)——连续链断点
61
- }
62
-
63
- /** 记录只读视图(停止判定与结论表的数据源);空清单键 / 无载体 ⇒ null。 */
64
- export function designReviewStreakRecord(agent, key) {
65
- if (!designReviewStreakApplies(key)) return null
66
- const streaks = agent?._designReviewStreaks
67
- return streaks instanceof Map ? (streaks.get(key) ?? null) : null
68
- }
69
-
70
- /** 计数落账(§17.4):reset ⇒ 删除该键记录;count ⇒ `{count: prev+1, log: […].slice(-N)}`;
71
- * neutral ⇒ 不动。载体懒初始化。 */
72
- export function noteDesignReviewOutcome(agent, key, outcome) {
73
- if (!agent || !designReviewStreakApplies(key) || !outcome) return
74
- if (outcome.reset) {
75
- if (agent._designReviewStreaks instanceof Map) agent._designReviewStreaks.delete(key)
76
- return
77
- }
78
- if (typeof outcome.count !== "string" || !outcome.count) return
79
- const streaks = agent._designReviewStreaks instanceof Map
80
- ? agent._designReviewStreaks
81
- : (agent._designReviewStreaks = new Map())
82
- const prev = streaks.get(key)
83
- streaks.set(key, {
84
- count: (prev?.count ?? 0) + 1,
85
- log: [...(prev?.log ?? []), outcome.count].slice(-MAX_DESIGN_REVIEW_STREAK),
86
- })
87
- }
88
-
89
- /** 停止判定:记录达阈值即停;空清单键恒 false。停止不可自解除(复位仅经可用判决——被拒后
90
- * 无法发生;会话结束随载体清零)。 */
91
- export function designReviewStreakStopped(agent, key) {
92
- return (designReviewStreakRecord(agent, key)?.count ?? 0) >= MAX_DESIGN_REVIEW_STREAK
93
- }