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,489 +0,0 @@
1
- /**
2
- * session-slots.mjs — slot / manifest 管理(2026-08-31 advisor round1 🔴 拆分:
3
- * session.mjs 曾超 500 行硬限;slot 所有权、认领、清单与核心读写分离,session.mjs
4
- * re-export 全部导出以保持既有 import 兼容)。
5
- *
6
- * 模型:每个项目(cwd hash)拥有无限编号 slot;manifest 记录 active 指针 + 每个
7
- * slot 的属主进程(slotSessions: slot → "pid-timestamp-random",CLI ↔ VS Code
8
- * 共享 manifest 以互斥认领)。属主判定用 PID 存活探测(isProcessAlive)。
9
- */
10
-
11
- import { createHash } from "node:crypto"
12
- import { mkdirSync, readFileSync, writeFileSync, renameSync, unlinkSync, existsSync } from "node:fs"
13
- import { join, dirname, basename } from "node:path"
14
- import { execSync } from "node:child_process"
15
- import { configDir } from "./config.mjs"
16
- import { migrateHashLength } from "./session-migrate.mjs"
17
- // §10 D-2(2026-09-05):resumeSlot 决策归本文件(slot/claim 层);data 层读(loadSlotFile/
18
- // legacy 过滤)属 session.mjs(500 行内不迁移)——静态环仅此一处:函数声明实例化期已初始化、
19
- // 只函数体内运行时使用(环安全);VS Code 端 session-slots ↔ session-io 同构镜像。
20
- import { loadSlotFile, isLegacyTransient } from "./session.mjs"
21
-
22
- let currentSessionId = null
23
-
24
- /** Generate unique session ID for this process */
25
- export function getSessionId() {
26
- if (!currentSessionId) {
27
- currentSessionId = `${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`
28
- }
29
- return currentSessionId
30
- }
31
-
32
- /** Normalize cwd for hashing: uppercase Windows drive letter so both ends
33
- * (CLI's process.cwd() vs VS Code's uri.fsPath, which lowercases it) agree. */
34
- export function normalizeCwd(cwd) {
35
- return cwd.replace(/^([a-z]):/, (_, d) => d.toUpperCase() + ":")
36
- }
37
-
38
- /** Full sha1 hex (40 chars), not truncated. Shared contract with the VS Code extension. */
39
- function cwdHash(cwd) {
40
- return createHash("sha1").update(normalizeCwd(cwd)).digest("hex")
41
- }
42
-
43
- /** sessions 根目录隔离缝(2026-09-08 DESIGN-TOKEN-SETTLEMENT 测试——VSC 端
44
- * _setSessionsDirForTest 同构):默认 null 走真实 configDir;测试指向临时目录
45
- * (beforeEach 设、afterEach 复位)。migrateHashLength 的 legacy 迁移仍查真实
46
- * 目录(temp 哈希无 legacy 文件——no-op 无害)。 */
47
- let sessionsDirOverride = null
48
- export function _setSessionsDirForTest(dir) { sessionsDirOverride = dir }
49
- export function _resetSessionsDirForTest() { sessionsDirOverride = null }
50
- function sessionsBase() { return sessionsDirOverride ?? join(configDir, "sessions") }
51
-
52
- /** Derive base session path from cwd hash. Migrates legacy short-hash files on first access. */
53
- export function sessionPath(cwd) {
54
- const hash = cwdHash(cwd)
55
- migrateHashLength(cwd, hash)
56
- return join(sessionsBase(), `${hash}.json`)
57
- }
58
-
59
- export function slotPath(cwd, n) { return sessionPath(cwd) + "." + n }
60
- export function manifestPath(cwd) { return sessionPath(cwd) + ".manifest" }
61
-
62
- // ========== end marker(SESSION.md §10 端分离恢复——本端"最后使用槽位"记录)==========
63
-
64
- /** 端常量:本端记录文件后缀——CLI 写 .cli、VS Code 写 .vscode,互不触碰
65
- * (NF1:本端记录是本端单写者文件——不新增跨端共享可变字段)。 */
66
- export const END = "cli"
67
-
68
- /** 本端记录路径:{manifest}.{END}(manifest 旁的独立小文件,非内嵌字段——NF1)。 */
69
- export function endMarkerPath(cwd) { return `${manifestPath(cwd)}.${END}` }
70
-
71
- /** 读本端记录:返回 { slot: <number|null>, updatedAt } 或 null。三态语义(D-1):
72
- * 文件缺失 = 从未记录(升级/首用迁移窗口——可能触发一次性继承);
73
- * JSON 解析失败/结构非法(损坏)= 按"缺失"降级——不 rename 不 unlink(幂等、不误伤,
74
- * T-M13);`slot: null` = 显式置空(删过本端记录槽——绝不触发继承,T-M4)。 */
75
- export function readEndMarker(cwd) {
76
- try {
77
- const p = endMarkerPath(cwd)
78
- if (!existsSync(p)) return null
79
- const m = JSON.parse(readFileSync(p, "utf8"))
80
- if (m && m.slot === null) return { slot: null, updatedAt: m.updatedAt ?? null }
81
- if (m && Number.isInteger(m.slot) && m.slot >= 1) return { slot: m.slot, updatedAt: m.updatedAt ?? null }
82
- return null
83
- } catch { return null }
84
- }
85
-
86
- /** 写本端记录(原子 .tmp+rename,复用 writeSessionFile):slot = 目标槽号或 null(显式置空)。
87
- * 失败容忍(NF2):写失败按无记录路径降级——不抛错,不影响会话数据(T-M14)。 */
88
- export function writeEndMarker(cwd, slot) {
89
- try {
90
- writeSessionFile(endMarkerPath(cwd), { slot, updatedAt: Date.now() })
91
- } catch { /* NF2:失败容忍 */ }
92
- }
93
-
94
- /** Path to the active slot's file */
95
- export function activePath(cwd) {
96
- return slotPath(cwd, activeSlot(cwd))
97
- }
98
-
99
- /** Atomic write: write to temp file then rename to replace, preventing truncated JSON from mid-write crash. */
100
- export function writeSessionFile(p, data) {
101
- mkdirSync(dirname(p), { recursive: true })
102
- const tmp = `${p}.tmp`
103
- writeFileSync(tmp, JSON.stringify(data), "utf8")
104
- try {
105
- renameSync(tmp, p)
106
- } catch {
107
- try { unlinkSync(p) } catch {}
108
- try {
109
- renameSync(tmp, p)
110
- try { unlinkSync(tmp) } catch {}
111
- } catch {
112
- writeFileSync(p, readFileSync(tmp, "utf8"), "utf8")
113
- }
114
- }
115
- }
116
-
117
- // ========== slot management ==========
118
-
119
- /** Detect a genuine user message (excludes system-reminder injected messages) */
120
- function isRealUserMsg(m) {
121
- return m.role === "user" && typeof m.content === "string" && !m.content.startsWith("[System reminder:")
122
- }
123
-
124
- /** Extract slot metadata from history (shared by slotDigest and loadSlotMeta) */
125
- function extractSlotMeta(history, activeProvider, updatedAt, title = "") {
126
- const userMsgs = history.filter(isRealUserMsg)
127
- const first = userMsgs[0]?.content ?? ""
128
- return {
129
- messageCount: history.length,
130
- turnCount: userMsgs.length,
131
- firstMessage: first.slice(0, 80),
132
- activeProvider: activeProvider ?? "",
133
- updatedAt: updatedAt ?? Date.now(),
134
- title,
135
- }
136
- }
137
-
138
- /** Extract preview summary from session data for manifest storage (with current timestamp)
139
- * MODEL-MERGE-SESSION:摘要升级带 activeModel——listSlots 合成显 "p:m"(双端同规则)。 */
140
- export function slotDigest(data) {
141
- const meta = extractSlotMeta(data.history ?? [], data.activeProvider, data.updatedAt, data.title ?? "")
142
- if (data.activeModel) meta.activeModel = data.activeModel
143
- return { ts: Date.now(), ...meta }
144
- }
145
-
146
- export function loadManifest(cwd) {
147
- try {
148
- const p = manifestPath(cwd)
149
- if (!existsSync(p)) return { slots: {}, sessionId: null }
150
- const m = JSON.parse(readFileSync(p, "utf8"))
151
- if (!m.slots) m.slots = {} // 2026-09-01 会诊 deepseek 🔵:损坏的 {} manifest 不再让调用方抛 TypeError
152
- if (!m.sessionId) m.sessionId = null
153
- return m
154
- } catch { return { slots: {}, sessionId: null } }
155
- }
156
-
157
- export function saveManifest(cwd, m, deletions = null, opts = {}) {
158
- // 2026-08-31 会诊 kimi/deepseek 🟡:写前重读并按"条目级"合并——原实现把"读时快照"
159
- // 整对象写回,另一进程在窗口内对 slots/slotSessions/active 的变更被覆盖抹除(被抹
160
- // 认领的槽变"文件在、无属主"→ 第三方可认领 → 双属主 → F2 互旋)。无锁文件无法
161
- // 完全原子,重读合并把丢失更新窗口缩到最小;删除意图经 deletions 参数显式表达
162
- // (deleteSlot:{ slots: [n], slotSessions: [n] })。
163
- // 2026-09-01 会诊 deepseek/kimi/glm 🟡:active 是单值——只有显式翻指针的调用方
164
- // (ensureActive 分支、newSession、switchToSlot、deleteSlot 删到 active 时)传
165
- // opts.setActive;其余调用方(saveSession/ACP 认领/死项清理)默认保留磁盘 fresh 的
166
- // active,否则毫秒窗口内会把并发方刚翻的 active 回滚(F1 防漂移的反向变体)。
167
- try {
168
- const fresh = JSON.parse(readFileSync(manifestPath(cwd), "utf8"))
169
- if (fresh && typeof fresh === "object" && fresh.slots && typeof fresh.slots === "object") {
170
- const merged = { ...fresh }
171
- if (opts.setActive) merged.active = m.active
172
- merged.slots = { ...fresh.slots, ...(m.slots ?? {}) }
173
- merged.slotSessions = { ...(fresh.slotSessions ?? {}), ...(m.slotSessions ?? {}) }
174
- if (m.sessionId) merged.sessionId = m.sessionId
175
- if (deletions) {
176
- for (const [section, keys] of Object.entries(deletions)) {
177
- for (const k of keys) delete merged[section]?.[k]
178
- }
179
- }
180
- m = merged
181
- }
182
- } catch {
183
- // 首次创建或 manifest 不可读:用传入对象。2026-09-01 advisor 🟡:解析失败时先改名
184
- // 保留现场(与 loadSlotFile 对 slot 文件的 .corrupted 原则一致)——否则覆盖后全部
185
- // 槽位元数据(digest/title/updatedAt)永久丢失,/session 列表变空。文件不存在时
186
- // rename 抛错被吞,无害。
187
- try { renameSync(manifestPath(cwd), `${manifestPath(cwd)}.corrupted`) } catch {}
188
- }
189
- m.sessionId = getSessionId()
190
- writeSessionFile(manifestPath(cwd), m)
191
- }
192
-
193
- /** 死主条目清理(2026-08-31 会诊 F4 + 2026-09-01 会诊 deepseek/kimi 🔴 语义原样抽取——
194
- * ensureActive/resumeSlot 共用):删除 owner 进程已死的 slotSessions 条目。死主判定必须跑
195
- * isProcessAlive——不能以"文件缺失"短路(活进程在"认领 → 首次保存"窗口文件暂缺,误删会
196
- * 致双进程同槽)。返回 deletions 计算函数(调用时按 m 当前状态过滤刚重新认领的槽——防删
197
- * 掉自己的新属主),无清理返回 null。删除须经 saveManifest 的 deletions 显式落盘——条目级
198
- * 合并会把磁盘死条目从 fresh 复活回写(N1 + 会诊 🔴)。 */
199
- function cleanDeadOwners(m) {
200
- const mySessionId = getSessionId()
201
- const deadSlots = []
202
- for (const [slot, owner] of Object.entries(m.slotSessions)) {
203
- if (owner && owner !== mySessionId) {
204
- const pid = parseInt(owner.split("-")[0])
205
- if (!pid || !isProcessAlive(pid)) {
206
- delete m.slotSessions[slot]
207
- deadSlots.push(slot)
208
- }
209
- }
210
- }
211
- return deadSlots.length === 0 ? null : () => ({ slotSessions: deadSlots.filter((s) => m.slotSessions[s] !== mySessionId) })
212
- }
213
-
214
- /**
215
- * Claim a slot for this process and set it as active. Idempotent.
216
- * Preference order:
217
- * 1. The current active slot, if it is unowned / ours / its owner is dead — reuse it.
218
- * 2. Any slot that is unowned or owned by a dead process (reclaim). → allocateFresh
219
- * 3. A brand-new slot when all are owned by live processes. → allocateFresh
220
- * The owner is recorded in m.slotSessions so other processes (CLI ↔ VS Code) can
221
- * see which slots are taken and avoid them.
222
- */
223
- function ensureActive(cwd, m) {
224
- const mySessionId = getSessionId()
225
- if (!m.slotSessions) m.slotSessions = {}
226
- // 顺手清理死主条目(见 cleanDeadOwners)。ensureActive 因 F1 粘性每次进程只跑几次,
227
- // 全量 tasklist 成本可接受;清理结果必须落盘——早退 + 分支 1/2/3 全部传 deletions。
228
- const deadParam = cleanDeadOwners(m)
229
-
230
- // Already own the active slot — nothing to do.
231
- // 2026-08-31 advisor round2 🔵:清理结果此时落盘(否则死项清理只在内存生效,早退
232
- // 路径永不持久化——死条目一直滞留到其他路径保存才消失)。
233
- if (m.active && m.slotSessions[m.active] === mySessionId) {
234
- if (deadParam) saveManifest(cwd, m, deadParam())
235
- return
236
- }
237
-
238
- const isFree = (slot) => {
239
- const owner = m.slotSessions[slot]
240
- if (!owner || owner === mySessionId) return true
241
- return !isProcessAlive(parseInt(owner.split("-")[0]))
242
- }
243
-
244
- // 1. Prefer the current active slot if we can take it (preserves "resume where you left off").
245
- if (m.active && m.slots[m.active] && isFree(m.active)) {
246
- m.slotSessions[m.active] = mySessionId
247
- saveManifest(cwd, m, deadParam?.() ?? null, { setActive: true })
248
- return
249
- }
250
-
251
- // 2/3. 分支 2/3 已抽取为 allocateFresh(2026-09-05 §10 D-2——resumeSlot 全新分配复用)。
252
- allocateFresh(cwd, m, deadParam)
253
- }
254
-
255
- /**
256
- * Allocate a slot with ensureActive 分支 2/3 语义(2026-09-05 §10 D-2 抽取——resumeSlot
257
- * 步骤③"其余一切 → 全新分配"复用;与 newSession 选号语义对齐):
258
- * 2. Reclaim a manifest slot whose FILE does not exist (never held a session);
259
- * 3. A brand-new slot when none is free / all numbers are taken.
260
- * 记录所有权 + active 指针(setActive)并落盘。返回分配的槽号。
261
- */
262
- export function allocateFresh(cwd, m, deadParam = null) {
263
- const mySessionId = getSessionId()
264
- if (!m.slotSessions) m.slotSessions = {}
265
- const isFree = (slot) => {
266
- const owner = m.slotSessions[slot]
267
- if (!owner || owner === mySessionId) return true
268
- return !isProcessAlive(parseInt(owner.split("-")[0]))
269
- }
270
-
271
- // 2. Reclaim a slot whose FILE does not exist (never held a session). 2026-08-31 会诊 F4:
272
- // 原实现认领"编号最小的空闲 slot"——死主的旧 slot 文件仍在,新进程会 resume 进
273
- // 陌生会话("会话乱了"实锤)且退出时覆盖它。只有文件缺失的空 slot 才允许回收。
274
- const allSlots = Object.keys(m.slots).filter((n) => /^\d+$/.test(n)).map(Number).sort((a, b) => a - b)
275
- for (const slot of allSlots) {
276
- if (isFree(slot) && !existsSync(slotPath(cwd, slot))) {
277
- m.active = slot
278
- m.slotSessions[slot] = mySessionId
279
- saveManifest(cwd, m, deadParam?.() ?? null, { setActive: true })
280
- return slot
281
- }
282
- }
283
-
284
- // 3. All slots owned by live processes — allocate a new one (no limit).
285
- // 2026-08-31 advisor round2 🟡:新号从 max+1 起逐号跳过"已被活进程认领但尚未落盘"
286
- // 的号(认领→首次保存窗口:slotSessions 有条目、m.slots 无条目、文件不存在——
287
- // 仅凭 m.slots/existsSync 查不到 → 双进程认领同一号 → 同槽双写/互旋)。
288
- // 2026-09-01 会诊 kimi 🟡:同时跳过文件仍存在的号(与 newSession 对齐)——manifest
289
- // 条目丢失/损坏时 max+1 会撞上孤儿槽文件 → F2 把真会话轮转成不可见的 .bak。
290
- // 另:allSlots 已升序,取 max 用 allSlots[allSlots.length-1](数万槽位时 Math.max
291
- // spread 有 RangeError 风险)。
292
- const liveClaimed = (n) => {
293
- const owner = m.slotSessions?.[n]
294
- return !!(owner && owner !== mySessionId && isProcessAlive(parseInt(owner.split("-")[0])))
295
- }
296
- let newSlot = allSlots.length > 0 ? allSlots[allSlots.length - 1] + 1 : 1
297
- while (liveClaimed(newSlot) || existsSync(slotPath(cwd, newSlot))) newSlot++
298
- m.active = newSlot
299
- m.slotSessions[newSlot] = mySessionId
300
- saveManifest(cwd, m, deadParam?.() ?? null, { setActive: true })
301
- return newSlot
302
- }
303
-
304
- /** 认领指定槽为本进程所有并置为 active(2026-09-05 §10 D-2 resumeSlot 认领路径——调用方
305
- * 已按"属主 空/死/本进程"判据校验可用性;幂等)。manifest active 保留为共享指针(D-6:
306
- * 旧版端/ACP 恢复依据 + 无记录端一次性继承源 + 列表回退高亮——不再作本端恢复第一依据)。
307
- * deadParam 在写入所有权之后求值(防 deletions 删掉本调用刚认领的槽——ensureActive
308
- * deadParam 同型过滤)。 */
309
- export function claimSlot(cwd, slot, m = loadManifest(cwd), deadParam = null) {
310
- m.slotSessions ??= {}
311
- m.slotSessions[slot] = getSessionId()
312
- m.active = slot // 认领即翻共享指针(setActive 写 m.active——不更新则落快照旧值)
313
- saveManifest(cwd, m, deadParam?.() ?? null, { setActive: true })
314
- }
315
-
316
- /**
317
- * Check if a process with given PID is still alive.
318
- * Returns false if process doesn't exist or we can't determine.
319
- */
320
- export function isProcessAlive(pid) {
321
- if (!pid || isNaN(pid)) return false
322
- try {
323
- // On Windows: tasklist /FI "PID eq <pid>" /NH
324
- // On Unix: kill(pid, 0) or check /proc/<pid>
325
- if (process.platform === 'win32') {
326
- // 2026-08-31 会诊 F4 + advisor round1 🔵:/FI 已按 PID 过滤;用 CSV 格式解析 PID
327
- // 列(第 2 列),避免旧 includes() 误报活、新行解析在罕见镜像名(含"数字+空格")
328
- // 下误报死。
329
- const output = execSync(`tasklist /FO CSV /FI "PID eq ${pid}" /NH`, { encoding: 'utf8', stdio: 'pipe' })
330
- return output.split(/\r?\n/).some((line) => {
331
- const m = line.match(/^"([^"]*)","(\d+)"/)
332
- return m && m[2] === String(pid)
333
- })
334
- } else {
335
- // Unix: try to send signal 0 (doesn't kill, just checks)
336
- process.kill(pid, 0)
337
- return true
338
- }
339
- } catch {
340
- return false
341
- }
342
- }
343
-
344
- /** Return the active slot number for this process, claiming one if necessary */
345
- export function activeSlot(cwd) {
346
- const m = loadManifest(cwd)
347
- ensureActive(cwd, m)
348
- return m.active
349
- }
350
-
351
- /** Lazy-load slot metadata from slot file (for old-format manifest entries that lack metadata) */
352
- function loadSlotMeta(cwd, slot, v) {
353
- if (typeof v === "object" && v !== null && "ts" in v) return v
354
- const ts = typeof v === "number" ? v : 0
355
- try {
356
- const p = slotPath(cwd, slot)
357
- if (!existsSync(p)) return { ts }
358
- const data = JSON.parse(readFileSync(p, "utf8"))
359
- const history = data.history ?? []
360
- const meta = extractSlotMeta(history, data.activeProvider, data.updatedAt ?? ts, data.title ?? "")
361
- if (data.activeModel) meta.activeModel = data.activeModel
362
- return { ts, ...meta }
363
- } catch {
364
- return { ts }
365
- }
366
- }
367
-
368
- /** List all slots, newest first. Includes isActive flag.
369
- * 2026-09-01 会诊 🟢:只读操作不认领——原实现 active 缺失时调 activeSlot(写 manifest
370
- * 副作用,ACP session/list 可触发)。m.active 缺失时全部 isActive=false,由下一次
371
- * activeSlot 正常认领。 */
372
- export function listSlots(cwd) {
373
- const m = loadManifest(cwd)
374
- const active = m.active ?? null
375
- return Object.entries(m.slots)
376
- .filter(([n]) => /^\d+$/.test(n))
377
- .map(([n, v]) => {
378
- const meta = loadSlotMeta(cwd, Number(n), v)
379
- return {
380
- slot: Number(n),
381
- isActive: Number(n) === active,
382
- timestamp: meta.ts,
383
- date: new Date(meta.ts).toLocaleString(),
384
- messageCount: meta.messageCount ?? 0,
385
- turnCount: meta.turnCount ?? 0,
386
- firstMessage: meta.firstMessage ?? "",
387
- // MODEL-MERGE-SESSION 摘要 "p:m":activeProvider 保持裸渠道名——列表消费面显复合
388
- // (旧摘要无 activeModel → 回退裸渠道名——新老兼容;cmd-session/VSC sessions 行免改)
389
- activeProvider: meta.activeProvider ? (meta.activeModel ? `${meta.activeProvider}:${meta.activeModel}` : meta.activeProvider) : "",
390
- updatedAt: meta.updatedAt ?? meta.ts,
391
- updatedDate: new Date(meta.updatedAt ?? meta.ts).toLocaleString(),
392
- title: meta.title ?? "",
393
- }
394
- })
395
- .sort((a, b) => b.updatedAt - a.updatedAt)
396
- }
397
-
398
- /** Delete a slot: remove its file and manifest entry. Deleting the active slot
399
- * resets the manifest active pointer (the next claim re-creates one). */
400
- export function deleteSlot(cwd, slot) {
401
- const n = Number(slot)
402
- if (!Number.isInteger(n) || n < 1) return false
403
- const m = loadManifest(cwd)
404
- if (!m.slots[n]) return false
405
- delete m.slots[n]
406
- delete m.slotSessions?.[n] // orphan session-id entries bloat the manifest forever
407
- try { unlinkSync(slotPath(cwd, n)) } catch { /* missing file is fine */ }
408
- if (m.active === n) delete m.active
409
- // setActive: true —— 显式表达"删到 active 时 active 置空"的意图(saveManifest 默认
410
- // 保留 fresh.active,2026-09-01 会诊三家 🟡)
411
- saveManifest(cwd, m, { slots: [n], slotSessions: [n] }, { setActive: true })
412
- // 2026-09-05 §10 D-4/F4:删到本端记录槽 → 记录显式置空(文件保留 + slot:null——下次全新起步,不复活——T-M4/T-M8)
413
- if (readEndMarker(cwd)?.slot === n) writeEndMarker(cwd, null)
414
- return true
415
- }
416
-
417
- // renameSlot 已拆至 session-rename.mjs(2026-09-06 §12.2.5 契约改使本文件超 500 行硬限,
418
- // §12.3 授权拆分);session.mjs re-export 保持调用点不变。
419
-
420
- // ========== resumeSlot(SESSION.md §10 D-2——端分离恢复决策)==========
421
-
422
- /** 本端记录槽可用判据(D-2):slot ∈ m.slots + 槽文件在盘 + 属主 空/死/本进程。 */
423
- function usableSlot(cwd, m, slot) {
424
- if (!m.slots[slot] || !existsSync(slotPath(cwd, slot))) return false
425
- const owner = m.slotSessions?.[slot]
426
- if (!owner || owner === getSessionId()) return true
427
- const pid = parseInt(owner.split("-")[0])
428
- return !pid || !isProcessAlive(pid)
429
- }
430
-
431
- /** legacy 单文件兜底(v1/v2 单会话 {hash}.json——迁移前残留;仅 data 层——2026-09-05 §10
432
- * D-2:恢复数据兜底不改变 claim 落点,T-M10)。纪律与 loadSlotFile 一致:cwd 不匹配(别人的文件)
433
- * 直接 null 不改名;坏结构改名 .unreadable 保留(version>2 不动);解析失败 .corrupted 保留。 */
434
- function loadLegacyFile(cwd) {
435
- const legacy = sessionPath(cwd)
436
- try {
437
- if (existsSync(legacy)) {
438
- const data = JSON.parse(readFileSync(legacy, "utf8"))
439
- // cwd 不匹配是别人的文件——与 loadSlotFile 一致直接 return null 不改名
440
- // ("别人的文件不动"原则,2026-08-31 advisor round2 🟡)
441
- if (data.cwd && data.cwd.toLowerCase() !== cwd.toLowerCase()) return null
442
- if ((data?.version === 1 || data?.version === 2) && Array.isArray(data.history)) {
443
- data.history = data.history.filter((m) => !isLegacyTransient(m))
444
- return data
445
- }
446
- // 结构不匹配:保留现场(version>2 的新版文件不动)
447
- if (!(typeof data?.version === "number" && data.version > 2)) {
448
- try { renameSync(legacy, `${legacy}.unreadable`) } catch {}
449
- console.error(`[session] legacy file ${legacy}: invalid structure — preserved as ${basename(legacy)}.unreadable`)
450
- }
451
- }
452
- } catch (e) {
453
- console.error(`[session] failed to load legacy ${legacy}: ${e.message}`)
454
- try { renameSync(legacy, `${legacy}.corrupted`) } catch {}
455
- }
456
- return null
457
- }
458
-
459
- /**
460
- * 恢复决策(SESSION.md §10 D-2)——TUI 启动的本端恢复入口(VS Code 面板同构镜像)。
461
- * 返回 { slot, data }(data 可为 null——全新起步或读槽失败)。判据:
462
- * ① 本端记录可用(slot ≠ null 且 ∈ m.slots 且槽文件在盘 且属主 空/死/本进程)→ claimSlot;
463
- * ② 记录缺失(从未记录 = 升级/首用迁移窗口):②a active 属主 = 本进程(同进程重入——
464
- * ensureActive 早退语义镜像:认领后尚未写 slots 条目/文件的窗口)→ 直接沿用;
465
- * ②b 否则一次性继承 manifest.active(同判据;活属主绝不继承——全新槽起步,T-M3);
466
- * ③ 其余一切(slot:null 显式置空 / 槽被删 / 属主为活外人 / 继承失败)→ allocateFresh。
467
- * 每次落点都写本端记录;claim 后读槽失败(.corrupted/.unreadable——loadSlotFile 既有改名
468
- * 保全语义)→ 保持已 claim 槽 + data:null——不改 marker——下次保存原地重建(T-M15)。
469
- */
470
- export function resumeSlot(cwd) {
471
- const m = loadManifest(cwd)
472
- m.slotSessions ??= {}
473
- // 与 ensureActive 同型的死主清理(认领路径持久化——F5a 纪律:仅传 m 等于没删)
474
- const deadParam = cleanDeadOwners(m)
475
- const rec = readEndMarker(cwd) // null = 缺失/损坏;{slot:null|N} = 文件在(D-1)
476
- let slot = null
477
- if (rec?.slot != null && usableSlot(cwd, m, rec.slot)) slot = rec.slot // ① 本端记录可用
478
- else if (rec === null) {
479
- if (m.active && m.slotSessions?.[m.active] === getSessionId()) slot = m.active // ②a 同进程重入
480
- else if (m.active && usableSlot(cwd, m, m.active)) slot = m.active // ②b 一次性继承
481
- }
482
- if (slot !== null) claimSlot(cwd, slot, m, deadParam)
483
- else slot = allocateFresh(cwd, m, deadParam) // ③ 全新分配(slot:null 绝不继承——T-M4)
484
- // data 层:读已认领槽(loadSlotFile 自 session.mjs——环 import 见文件头);读失败/槽文件不在 → legacy 单文件兜底(仅 data)
485
- let data = loadSlotFile(cwd, slot)
486
- if (!data) data = loadLegacyFile(cwd)
487
- writeEndMarker(cwd, slot)
488
- return { slot, data }
489
- }