@thincoder/core 0.11.2 → 0.11.3

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 (198) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/advisor/compaction.mjs +7 -5
  3. package/advisor/history.mjs +24 -11
  4. package/advisor/loop.mjs +13 -8
  5. package/advisor/messages.mjs +72 -8
  6. package/advisor/run.mjs +24 -13
  7. package/advisor.mjs +7 -3
  8. package/agent/chat-call.mjs +14 -9
  9. package/agent/completion.mjs +28 -40
  10. package/agent/continue-decision.mjs +14 -8
  11. package/agent/digest-account.mjs +133 -59
  12. package/agent/dispatch-run.mjs +1 -1
  13. package/agent/dispatch.mjs +2 -1
  14. package/agent/family-tools.mjs +12 -13
  15. package/agent/helpers.mjs +17 -72
  16. package/agent/image-heal.mjs +18 -4
  17. package/agent/post-turn.mjs +13 -26
  18. package/agent/record-results.mjs +21 -6
  19. package/agent/run-stages.mjs +72 -37
  20. package/agent/run-start.mjs +148 -113
  21. package/agent/setup-reminders.mjs +187 -91
  22. package/agent/setup.mjs +204 -138
  23. package/agent/spawn-child.mjs +2 -2
  24. package/agent/suspension.mjs +43 -15
  25. package/agent/timers.mjs +4 -1
  26. package/agent/turn-domain-text.mjs +105 -0
  27. package/agent/turn-loop.mjs +54 -22
  28. package/agent/turn-projection.mjs +127 -227
  29. package/agent/turn-tool-process.mjs +32 -37
  30. package/agent-tools/advisor-async.mjs +6 -3
  31. package/agent-tools/advisor-launch.mjs +5 -5
  32. package/agent-tools/advisor.mjs +1 -1
  33. package/agent-tools/async-discard.mjs +7 -2
  34. package/agent-tools/async-settle.mjs +18 -12
  35. package/agent-tools/bash-async.mjs +5 -2
  36. package/agent-tools/batch-closeout.mjs +12 -62
  37. package/agent-tools/batch-ledger-bind.mjs +19 -8
  38. package/agent-tools/batch-lifecycle.mjs +37 -11
  39. package/agent-tools/batch-read.mjs +151 -4
  40. package/agent-tools/batch-record-write.mjs +5 -5
  41. package/agent-tools/batch-segment-vocab.mjs +84 -4
  42. package/agent-tools/batch-skeleton.mjs +18 -14
  43. package/agent-tools/batch-supersede.mjs +1 -1
  44. package/agent-tools/batch-tier-gate.mjs +36 -119
  45. package/agent-tools/batch.mjs +30 -20
  46. package/agent-tools/browser-async.mjs +5 -2
  47. package/agent-tools/consult.mjs +10 -7
  48. package/agent-tools/context.mjs +47 -31
  49. package/agent-tools/digest-budget.mjs +10 -9
  50. package/agent-tools/eng.mjs +3 -4
  51. package/agent-tools/escalate-async.mjs +3 -3
  52. package/agent-tools/goal.mjs +5 -2
  53. package/agent-tools/judge-domain.mjs +347 -0
  54. package/agent-tools/manifest.mjs +2 -2
  55. package/agent-tools/parent-channel.mjs +6 -3
  56. package/agent-tools/plan.mjs +11 -10
  57. package/agent-tools/review-facts.mjs +9 -3
  58. package/agent-tools/skill.mjs +7 -8
  59. package/agent-tools/spawn-gates.mjs +5 -16
  60. package/agent-tools/ssh-session.mjs +6 -3
  61. package/agent-tools/ssh-transfer.mjs +1 -1
  62. package/agent-tools/subagent-actions.mjs +2 -2
  63. package/agent-tools/subagent-async.mjs +11 -8
  64. package/agent-tools/subagent-scheduler.mjs +9 -9
  65. package/agent-tools/subagent-spawn.mjs +2 -2
  66. package/agent-tools/subagent.mjs +5 -18
  67. package/agent-tools/task.mjs +0 -8
  68. package/agent.mjs +15 -15
  69. package/auto-think.mjs +5 -2
  70. package/compaction-work-state.mjs +230 -0
  71. package/compress-form.mjs +41 -6
  72. package/config-defaults.mjs +5 -2
  73. package/config.mjs +53 -17
  74. package/context-degrade.mjs +79 -48
  75. package/context-echo.mjs +6 -26
  76. package/context-push.mjs +328 -31
  77. package/context.mjs +203 -141
  78. package/conventions.mjs +1 -1
  79. package/declaration.mjs +95 -17
  80. package/escape.mjs +6 -5
  81. package/explore-distill.mjs +35 -8
  82. package/generate-title.mjs +10 -1
  83. package/knowledge/prompt-resources.md +5 -1
  84. package/ledger-tools.mjs +50 -50
  85. package/ledger-write-ops.mjs +43 -16
  86. package/memory/docs.mjs +51 -15
  87. package/memory/file-list.mjs +6 -0
  88. package/model-specs.mjs +87 -21
  89. package/origin-guard.mjs +190 -0
  90. package/package.json +1 -1
  91. package/prompt-files.mjs +33 -11
  92. package/prompt-overlays.mjs +12 -5
  93. package/prompts/advisor-design.md +55 -36
  94. package/prompts/advisor-round1.md +18 -7
  95. package/prompts/advisor-round2.md +18 -7
  96. package/prompts/advisor-round3.md +18 -7
  97. package/prompts/common.md +89 -51
  98. package/prompts/consult-base.md +2 -3
  99. package/prompts/discipline-engineering.md +474 -440
  100. package/prompts/discipline-normal.md +107 -31
  101. package/prompts/knowledge/business-gates.md +23 -15
  102. package/prompts/knowledge/decision-quality.md +16 -18
  103. package/prompts/knowledge/doc-lookup.md +22 -27
  104. package/prompts/knowledge/document-writing.md +31 -49
  105. package/prompts/knowledge/documentation-evaluation.md +37 -45
  106. package/prompts/knowledge/evidence-discipline.md +36 -55
  107. package/prompts/knowledge/normal-coding-workflow.md +27 -21
  108. package/prompts/knowledge/normal-delivery-collaboration.md +33 -17
  109. package/prompts/knowledge/normal-work-management.md +10 -7
  110. package/prompts/knowledge/product-security.md +22 -17
  111. package/prompts/knowledge/project-records.md +63 -52
  112. package/prompts/knowledge/tool-apply-patch.md +12 -13
  113. package/prompts/knowledge/tool-bash.md +13 -4
  114. package/prompts/knowledge/tool-batch-eng-coder.md +13 -6
  115. package/prompts/knowledge/tool-batch-eng-designer.md +14 -6
  116. package/prompts/knowledge/tool-batch-review.md +12 -6
  117. package/prompts/knowledge/tool-batch.md +76 -62
  118. package/prompts/knowledge/tool-browser.md +45 -34
  119. package/prompts/knowledge/tool-context.md +2 -2
  120. package/prompts/knowledge/tool-delete.md +5 -1
  121. package/prompts/knowledge/tool-doc-check.md +25 -24
  122. package/prompts/knowledge/tool-doc-graph-read.md +3 -3
  123. package/prompts/knowledge/tool-doc-graph.md +15 -15
  124. package/prompts/knowledge/tool-edit.md +26 -23
  125. package/prompts/knowledge/tool-execute.md +9 -4
  126. package/prompts/knowledge/tool-fetch.md +7 -1
  127. package/prompts/knowledge/tool-file-ops.md +6 -1
  128. package/prompts/knowledge/tool-git-read.md +3 -1
  129. package/prompts/knowledge/tool-git.md +1 -1
  130. package/prompts/knowledge/tool-glob.md +3 -1
  131. package/prompts/knowledge/tool-grep.md +5 -2
  132. package/prompts/knowledge/tool-hashline-edit.md +4 -2
  133. package/prompts/knowledge/tool-insert-after.md +3 -1
  134. package/prompts/knowledge/tool-ledger-read.md +6 -13
  135. package/prompts/knowledge/tool-ledger.md +14 -10
  136. package/prompts/knowledge/tool-ls.md +2 -0
  137. package/prompts/knowledge/tool-manifest.md +10 -7
  138. package/prompts/knowledge/tool-memory.md +15 -11
  139. package/prompts/knowledge/tool-operations.md +59 -71
  140. package/prompts/knowledge/tool-plan.md +1 -2
  141. package/prompts/knowledge/tool-process.md +1 -1
  142. package/prompts/knowledge/tool-read-history.md +6 -7
  143. package/prompts/knowledge/tool-read.md +1 -0
  144. package/prompts/knowledge/tool-settings.md +6 -7
  145. package/prompts/knowledge/tool-ssh.md +37 -15
  146. package/prompts/knowledge/tool-subagent.md +37 -39
  147. package/prompts/knowledge/tool-task.md +3 -1
  148. package/prompts/knowledge/tool-team-ledger.md +5 -1
  149. package/prompts/knowledge/tool-tree.md +2 -0
  150. package/prompts/knowledge/tool-wait-for.md +16 -16
  151. package/prompts/knowledge/tool-write.md +4 -1
  152. package/prompts/knowledge/upstream-protocol.md +39 -37
  153. package/prompts/persona-coder.md +1 -3
  154. package/prompts/persona-eng-coder.md +5 -5
  155. package/prompts/persona-eng-designer.md +34 -17
  156. package/prompts/persona-engineering.md +532 -501
  157. package/prompts/persona-explore.md +0 -2
  158. package/prompts/persona-normal.md +17 -9
  159. package/prompts/persona-plan.md +0 -2
  160. package/prompts/persona-tester.md +0 -2
  161. package/prompts/subagent-base.md +0 -2
  162. package/provider/anthropic.mjs +4 -2
  163. package/provider/core.mjs +5 -3
  164. package/provider/errors.mjs +41 -7
  165. package/provider/google.mjs +5 -3
  166. package/provider/reasoning-echo.mjs +16 -0
  167. package/provider/responses.mjs +4 -2
  168. package/provider/sse.mjs +11 -6
  169. package/rules.mjs +11 -10
  170. package/session-lifecycle.mjs +115 -81
  171. package/session-slot-write.mjs +1 -1
  172. package/session.mjs +23 -20
  173. package/shell-identity.mjs +129 -22
  174. package/skip-dirs.mjs +24 -0
  175. package/team-ledger.mjs +22 -22
  176. package/text-budget.mjs +1 -1
  177. package/think-off.mjs +27 -0
  178. package/token-ttl.mjs +1 -1
  179. package/token-window.mjs +278 -88
  180. package/tool-docs/bash.md +0 -2
  181. package/tool-docs/consult_start.md +2 -2
  182. package/tool-docs/consult_stop.md +2 -2
  183. package/tools/browser.mjs +8 -8
  184. package/tools/execute.mjs +2 -2
  185. package/tools/file.mjs +17 -11
  186. package/tools/git.mjs +12 -12
  187. package/tools/ops.mjs +2 -2
  188. package/tools/patch.mjs +1 -1
  189. package/tools/process-doc-mark.mjs +33 -4
  190. package/tools/repomap.mjs +25 -3
  191. package/tools/search.mjs +74 -26
  192. package/tools/shared.mjs +4 -3
  193. package/tools/ssh.mjs +5 -5
  194. package/tools/tree.mjs +32 -10
  195. package/tools/web-deepseek.mjs +1 -1
  196. package/tools/web.mjs +2 -2
  197. package/tools/write-gate-params.mjs +3 -3
  198. package/window-policy.mjs +118 -78
@@ -19,9 +19,12 @@
19
19
 
20
20
  import { existsSync } from "node:fs"
21
21
  // §6.17:auto 派生值只进显示面(compactThresholdResolved)——显式键 agent.compactThreshold 永不被改写
22
- import { resolveCompactThreshold, resolveSessionWorkMode, resolveWorkMode, setConfigWorkMode } from "./config.mjs"
22
+ import { resolveCompactThreshold, resolveSessionWorkMode, setConfigWorkMode } from "./config.mjs"
23
23
  // 槽面判据单源(#841 KD-841-2:槽渠道 key 门 + 模型面序——PROVIDER.md §6.22)。
24
24
  import { hasKey, resolveChannelModel, resolveProviderPlan } from "./model-ref.mjs"
25
+ // 旧线补来源(AGENT-LOOP.md §5.5.4 补行):槽 `activeProvider` 是非空字符串且与运行态不同时,给无标记的 assistant 消息补会话级来源。
26
+ import { fillOriginFromSlot } from "./origin-guard.mjs"
27
+
25
28
  import {
26
29
  slotPath, loadManifest, saveManifest, slotDigest, writeSessionFile, getSessionId,
27
30
  writeEndMarker, sessionEnd, ownerPid, ownerPids,
@@ -35,11 +38,12 @@ import { loadSlotFile } from "./session.mjs"
35
38
  // 全新槽首物化构造器单源(SLOT-END-PARAM 批 §6.20 判据句 4 写面:「`newSession` 并入」——
36
39
  // 与 VSC `newSlot` / `loadSlotForWrite` 全新分支同一构造器;环 import 同上,函数体内运行时使用)。
37
40
  import { newSlotData } from "./session-slot-write.mjs"
38
- import { mergeAdjacentAssistantEchoes } from "./context.mjs"
39
- // 跨轮机读投影(SESSION.md §2 恢复面 · 台账 #2395 ∥ #2397–#2401):`turns` 在场即以轮记录重建机读线(与
40
- // `beginRun` ∥ `saveSession` 同一投影函数);本档同时拿归一化面来回填 `agent._turns`,并把压缩状态
41
- // (检查点 ∥ 折叠身份标记)播种回 agent。
42
- import { normalizeCheckpoint, normalizeSlotTurns, restoreMachineFromTurns } from "./agent/turn-projection.mjs"
41
+ import { mergeAdjacentAssistantEchoes, setInject } from "./context.mjs"
42
+ // 拍平投影(读数在拍平视图上算,位置在结构上取):机读线按轮嵌套后,外层条数是轮数。
43
+ import { flattenHistory, normalizeMachineLine, setSessionHead } from "./context-push.mjs"
44
+ // 机读线装回(SESSION.md §2):槽里的 `contextHistory` 就是那条线,逐条原样装回——不从 `turns` 重拼、
45
+ // 不从 `history` 补;本档只用归一面回填 `agent._turns`,并把压缩检查点播种回 agent。
46
+ import { normalizeCheckpoint, normalizeSlotTurns } from "./agent/turn-projection.mjs"
43
47
  // 打开态读数公式(§6.24 判据句 2——与 CLI 状态行 / VSC 同一实现点的投影;零新公式,只组合)。
44
48
  import { historyPercent, restoreTokenSample, sampleRatio } from "./token-window.mjs"
45
49
  import { scheduleSessionGC } from "./session-gc.mjs"
@@ -80,22 +84,47 @@ function stripTruncatedToolArgs(m) {
80
84
  }
81
85
 
82
86
  /**
83
- * 压缩状态恢复播种(SESSION.md §2「恢复也把压缩状态播种回 agent」):只装回机读线而不播种,同一会话的
84
- * 第二次压缩只见到重启之后的轮,`turnsCovered` 被写小、被摘要的轮又整条投影回来。
87
+ * 压缩状态恢复播种(SESSION.md §2「恢复也把压缩状态播种回 agent」):机读线整条装回之后,压缩检查点仍随槽
88
+ * 回来——它决定下一回合压缩的起点与降级报告里的 `discardedTurns` 读数。
85
89
  * - `agent._compactCheckpoint` = 槽里的 `compactCheckpoint`;键缺 ∥ 形态坏 ⇒ 不设(与「本会话还没压过」同义);
86
- * - 折叠身份标记按恢复出的轮记录重建(载体 `agent._turnFoldMarks`,口径见 `CONTEXT-COMPACTION.md` §6):
87
- * 机读线上每条轮记录的那几条消息对象登记为已折叠——下一回合的折叠与压缩按身份判覆盖时,看到的仍是整本账。
90
+ * - 保留窗起点与覆盖条数不播种:两者都按外层轮元素结构现读(`SESSION.md` §2),
91
+ * 线与字段一起装回就够——盘上只有消息的文本,没有身份;不重建任何运行期账。
88
92
  * 播种的键缺失等同没有:不报错,也不回写槽。
89
93
  * @param {object} agent
90
94
  * @param {object} data — 槽数据
91
- * @param {{turns?: object[], marks?: object[][]}} restored — `restoreMachineFromTurns` 的出参
92
- * (归一后的轮记录 + 逐轮身份账,与装回线上的对象是同一批)
93
95
  */
94
- function seedCompressionState(agent, data, restored = {}) {
95
- const turns = Array.isArray(restored.turns) ? restored.turns : normalizeSlotTurns(data?.turns)
96
+ function seedCompressionState(agent, data) {
97
+ // 轮记录只解析一次:`agent._turns` 已在 `applySession` 里归一过,夹取与读同一个数组。
98
+ const turns = Array.isArray(agent?._turns) ? agent._turns : normalizeSlotTurns(data?.turns)
99
+ // 压缩摘要跟压缩成果一起回来(§1「压缩摘要的位置」:写 `_compactCheckpoint.compactionSummary` 的同时
100
+ // 写进 `_inject` 的 `compaction-summary` 格)。只播检查点而不播种压缩摘要,重开后的首条请求就少了那条
101
+ // 「前面已被摘要」的框定:压缩成果能活过重启(槽里装的是线)而它在请求里的位置丢了。
102
+ // 落 A 段 `compaction-summary` 格,装配时排在对话之前(唯一一格提前),不落槽、不进机读线。
96
103
  agent._compactCheckpoint = normalizeCheckpoint(data?.compactCheckpoint, turns.length)
97
- const marks = Array.isArray(restored.marks) ? restored.marks : []
98
- agent._turnFoldMarks = marks.map((msgs) => (Array.isArray(msgs) ? [...msgs] : []))
104
+ }
105
+
106
+ /**
107
+ * 槽里的机读线两形态归一(设计档 §1.1「槽与迁移」):
108
+ * - 已是嵌套轮(某个元素带 `messages` 数组)⇒ 逐元素归一,白名单只有 `messages`——**按原样装回,不筛不丢**;
109
+ * - 扁平消息数组(本批之前的槽)⇒ 按消息上的 `turn` 分组重建轮元素,随后删掉该字段;
110
+ * 没有 `turn` 的那批旧注入跟前面那一轮同轮、原样留下(不筛、不丢弃、不重建)。
111
+ * 空 ∥ 非数组 ⇒ 空数组(「槽里没有机读线」与「空机读线」在调用方同形)。
112
+ */
113
+ function normalizeContextHistory(raw) {
114
+ // 单源 = `context-push.mjs` 的 `normalizeMachineLine`(端侧 `thincoder-vscode/src/agent/setup.mjs` 同一实现)。
115
+ return normalizeMachineLine(raw)
116
+ }
117
+
118
+ /**
119
+ * 待发队(B 段)随槽回填:新键 `pendingInject`;旧键 `pendingReminders` 认一次——旧槽里那是纯字符串条目,
120
+ * 这里升级为消息 `{ role: "user", content }`(条目形只有一个:待发队里装的都是消息)。
121
+ * 非对象、非法形状的元素丢弃(队列是发送面的载体,坏条目送上去就是一个 provider 400)。
122
+ */
123
+ function normalizePendingInject(raw) {
124
+ const list = Array.isArray(raw) ? raw : []
125
+ return list
126
+ .map((m) => (typeof m === "string" ? { role: "user", content: m } : m))
127
+ .filter((m) => m && typeof m === "object" && !Array.isArray(m))
99
128
  }
100
129
 
101
130
  /** Apply loaded session data onto an agent object; returns `{ switched, droppedDesignTokens }`
@@ -113,55 +142,54 @@ function seedCompressionState(agent, data, restored = {}) {
113
142
  * 删旧支:"activeModel==null 清 stale override 回渠道默认"——前提 = 渠道默认字段——已随
114
143
  * 三旧层删除消失——双字段恒非空故不可能触发(评审 #7)。 */
115
144
  export function applySession(agent, data, opts = {}) {
116
- // 机读线语义(历史注释保留):data.history = FULL 未压缩记录(人读线);data.contextHistory =
117
- // 压缩后机器线——恢复各从其源(保留压缩收益——从完整 history 重建会塞回中间过程——实测
118
- // prompt 膨胀 283%)。v1 老文件(无 contextHistory)回退播种,剥离被 slimForDisplay 截断的
145
+ // 机读线语义(历史注释保留):data.history = FULL 未压缩记录(人读线);data.contextHistory = 机读线本身
146
+ // ——装回的只有它(保留压缩收益——从完整 history 重建会塞回中间过程——实测 prompt 膨胀 283%)。
147
+ // v1 老文件(无 contextHistory ∥ 空数组)回退播种,剥离被 slimForDisplay 截断的
119
148
  // tool_calls.arguments(… 结尾 → 置 {}——截断可劈断 \\uXXXX 产生 400 毒载荷)。length > 0 才
120
149
  // 当机读线(contextHistory: [] 是"无机读线"而非空机器线——空机器线静默丢全部上下文)。
121
150
  agent.config ??= {} // ACP test mocks may omit config; be defensive like the ??= below
122
151
  const full = Array.isArray(data.history) ? data.history : []
123
- // SESSION.md §6.11(2026-09-08——F2/F3):恢复事件按当前 data 重定——载入历史非空 = 会话
124
- // 恢复 → 下个 depth-0 回合 env-state resumed:yes 一次(pushEnvStateReminder 读即清——每次恢复
125
- // 一次)。/new 与空历史槽切换不武装(显式清 false)——无恢复事件恒 no(F3 伪触发消除——不再靠
126
- // _sessionStart != null 推断;已武装 agent 切到空历史槽也不残留上次恢复事件——评审 round2 🟡)。
127
- // _processRestartPending 不在此清——由启动路径(bin/thincoder.mjs)设、prepareRun 发句清
128
- // (N6——双信号独立:切槽不报进程重启)。
129
- // 跨端异名互指(结构债批 5 N7——双端同语义各自独立实现、命名不统一是刻意——SESSION.md
130
- // §6.11):VSC 端同机制载体异名 = agent._resumedPending(src/agent/setup.mjs hydrateRun——
131
- // restore:true 工厂 + fullHistory 非空时武装——每槽恢复一次)+ 模块级 restartDetectionDone
132
- // 一次性闸(src/agent/setup-reminders.mjs——process restarted 句的进程级信号)。
133
- agent._envResumed = full.length > 0
134
- const ch = data.contextHistory
135
- const fallbackLine = (Array.isArray(ch) && ch.length > 0) ? ch : full.map(stripTruncatedToolArgs)
136
- // 恢复权威顺序(SESSION.md §2 单点定义):`turns` 存在 ⇒ 以轮记录重建机读线(与 `beginRun` ∥
137
- // `saveSession` 同一投影函数);否则用 `contextHistory`;两者皆缺时由 `history` 播种。
138
- // 重建同时给出 `{ turns, marks }`(出参)——下面播种压缩状态要用同一批消息对象(不重投影:重投影产出新对象,
139
- // 身份对不上线上那条线)。
140
- const restoredLine = {}
141
- const machine = restoreMachineFromTurns(data, restoredLine) ?? fallbackLine
152
+ // SESSION.md §6.11(2026-09-08——F2/F3):`_processRestartPending` 不在这里清——由启动路径
153
+ // (bin/thincoder.mjs)设、`prepareRun` 发句清(N6——信号独立:切槽不报进程重启)。
154
+ // 机读线两形态归一(设计档 §1.1「槽与迁移」):已是嵌套轮 ⇒ 逐元素归一(白名单 `messages`,按原样装回、
155
+ // 不筛不丢);扁平旧槽 ⇒ 按消息上的 `turn` 重组轮,随后删字段(无 `turn` 的旧注入跟前面那一轮同轮)。
156
+ const ch = normalizeContextHistory(data.contextHistory)
157
+ // 恢复权威顺序(SESSION.md §2 单点定义,两步):`contextHistory` 非空 ⇒ 机读线 = 它,逐条原样装回
158
+ // (不从 `turns` 重拼、不从 `history` 补);否则由 `history` 播种(包成一个轮元素,旧语义逐条不动)。
159
+ // `sessionReading` 走同一顺序(同档末)。
160
+ const fallbackLine = ch.length > 0 ? ch : [{ messages: full.map(stripTruncatedToolArgs) }]
142
161
  // D-CC19 恢复面回声归并(CONTEXT-COMPACTION §6.10 #8):已落盘机读线原样装回会复活
143
162
  // D-CC18 病态形态(无 reasoning_content 的 assistant 紧邻 assistant ⇒ 首请求 400)——
144
- // machine 定线后、装线前扫描归并(干净输入返回同一引用——零拷贝零回归)。
145
- const machineMerged = mergeAdjacentAssistantEchoes(machine)
163
+ // 线定下后、装线前逐轮归并(调用与结果同轮,配对不跳轮界;干净输入返回同一引用——零拷贝零回归)。
164
+ // 空串 `reasoning_content` 是合法的「没有原文」编码(#2647):装回线原样保留,不清账。
165
+ const machineMerged = fallbackLine.map((turn) => ({ messages: mergeAdjacentAssistantEchoes(turn.messages) }))
146
166
  // 绑定态(opts.slot 在场):人读线 = 记录存储尾窗(下方绑定块填充)——不复制全量 JSON 数组
147
167
  agent._fullHistory = opts.slot != null ? [] : [...full]
148
- agent.history = [...machineMerged]
149
- // 轮记录随槽回填(SESSION §2):下一回合的折叠按同一本账续记;归零活动轮的三件临时载体——
150
- // 上一进程的中止 ∥ 未完成链不得跨进程“续折”(异常轮不折叠)。旧槽无 `turns` ⇒ 空账,
168
+ agent.history = machineMerged
169
+ // 轮记录随槽回填(SESSION §2):跨轮清理按「第 k 个轮元素」与这份数组的下标对应,重启前后同一套判据;
170
+ // 归零活动轮的两件临时载体——上一进程的中止 ∥ 未完成轮不得跟过来。旧槽无 `turns` ⇒ 空数组,
151
171
  // 机读线仍按上面的回退线走(旧槽零回归)。
152
- agent._turns = Array.isArray(restoredLine.turns) ? restoredLine.turns : normalizeSlotTurns(data.turns)
153
- // 压缩状态随槽播种(`compactCheckpoint` ∥ 折叠身份标记——见 `seedCompressionState`)。
154
- seedCompressionState(agent, data, restoredLine)
172
+ agent._turns = normalizeSlotTurns(data.turns)
173
+ // 压缩状态随槽播种(`compactCheckpoint` 播回;保留窗起点与覆盖条数不播种——按外层结构现读)。
174
+ seedCompressionState(agent, data)
155
175
  agent._turnLedger = null
156
- agent._turnPending = null
157
- agent._turnStartLen = null
158
- agent._turnResponseEnd = null
159
176
  agent.title = data.title ?? ""
160
177
  agent.tasks = data.tasks ?? []
161
178
  agent.planMode = data.planMode ?? false
162
179
  agent.autoApprove = data.autoApprove ?? false
163
180
  agent.goal = data.goal ?? null
164
- agent._pendingReminders = data.pendingReminders ?? []
181
+ agent._pendingInject = normalizePendingInject(data.pendingInject ?? data.pendingReminders)
182
+ // 注入三段里**不随槽走**的两段:B 段整段来自槽(上面一行),A 段格位与 C 段累积是「当前状态」,
183
+ // 由本会话的写入方按格写——切槽(`/session N` ∥ ACP 换槽)时上一个会话的压缩摘要 ∥ 任务表 ∥
184
+ // 工作状态块 ∥ 技能块 ∥ 会话头块不得跟着进新会话的请求。新会话(`resetSessionState`)同一处置。
185
+ agent._inject = []
186
+ agent._retained = []
187
+ setSessionHead(agent, "")
188
+ // 清场之后只播种**这个槽自己**的压缩摘要(不是上一个会话遗留的那份——上面已清):重开一个压过的会话,
189
+ // 首条请求仍带着「前面已被摘要」的框定,否则模型看到的是从中间开始的对话。
190
+ if (agent._compactCheckpoint?.compactionSummary) {
191
+ setInject(agent, "compaction-summary", agent._compactCheckpoint.compactionSummary)
192
+ }
165
193
  agent._sessionStart = data.sessionStart ?? null
166
194
  // R16 token 字段恢复(过期过滤——见 token-ttl.mjs restoreEngTokens);返回值 = 离开集计数(§3.2)
167
195
  const restored = restoreEngTokens(agent, data)
@@ -226,7 +254,7 @@ export function applySession(agent, data, opts = {}) {
226
254
  // §6.17:恢复后 auto 派生线随槽模型跟手——只刷新显示面 compactThresholdResolved(显式键不写;
227
255
  // 判定阈值本身由 setup.mjs 每 run 现算,不依赖本值)
228
256
  if (switched && agent.config?.agent?.compactThresholdAuto && typeof agent.provider.model === "string" && agent.provider.model) {
229
- agent.config.agent.compactThresholdResolved = resolveCompactThreshold(null, agent.provider, resolveWorkMode(agent.config?.agent)).value
257
+ agent.config.agent.compactThresholdResolved = resolveCompactThreshold(null, agent.provider).value
230
258
  }
231
259
  // 会话级档位施加(§6.21 判据句 4——在模型合并支之后,以**合并后**的 `provider.model` 判 spec;
232
260
  // 三端共用本施加面):`"off"` 记号 ⇒ 该模型有 off 路径才设关思考形(effort 族该形为 `null`
@@ -248,12 +276,25 @@ export function applySession(agent, data, opts = {}) {
248
276
  // §6.17.1 链二读面:估算校准样本随槽恢复——上行刚把 `provider` 按槽值落定,key 同源校验才有意义
249
277
  // (四条校验在 `restoreTokenSample`:形状 / est 版本 / key 同源 / 下界 1;不合格 ⇒ 未校准档)。
250
278
  restoreTokenSample(agent, data.estimateSample, agent.provider)
279
+ // 旧线补来源(AGENT-LOOP.md §5.5.4 补行 · 槽渠道解析之后、机读线装回之后):槽 `activeProvider` 是非空字符串且与运行态
280
+ // `agent.provider.name` 不同时,给无标记的 assistant 消息补会话级来源;空串与缺键(无会话级证据)一律不补。补来源是尽力而为,
281
+ // 不承诺逐条正确;这只限制跨来源字段隔离,缺回声退轮不读来源,旧会话完整历史仍由 §5.5.5 承接。
282
+ agent.history = fillOriginFromSlot(agent.history, {
283
+ slotProvider: data.activeProvider ?? null,
284
+ runtimeProviderName: agent.provider?.name,
285
+ })
251
286
  return { switched, droppedDesignTokens: restored.droppedDesignTokens }
252
287
  }
253
288
  // ② 槽无 key ∥ 不在册 → D-S3 保留——静默保持现状(落 config 链:config 统一解析产物已是
254
289
  // `agent.provider`;不报错不纠正——两方都无效由调用侧复验 validateProvider 弹重选)
255
290
  // §6.17.1 链二读面(B 支出口同 A 支):样本照旧随槽恢复(provider = config 链产物,key 同源校验照做)
256
291
  restoreTokenSample(agent, data.estimateSample, agent.provider)
292
+ // 旧线补来源(B 支,判据同 A 支 · AGENT-LOOP.md §5.5.4 补行):槽渠道没被采用(无 key / 不在册)时,槽 `activeProvider` 仍可能是写下这段历史的那个 provider;
293
+ // 只有它是非空字符串且与运行态 `agent.provider.name` 不同时才补,空串与缺键一律不补。
294
+ agent.history = fillOriginFromSlot(agent.history, {
295
+ slotProvider: data.activeProvider ?? null,
296
+ runtimeProviderName: agent.provider?.name,
297
+ })
257
298
  return { switched: false, droppedDesignTokens: restored.droppedDesignTokens }
258
299
  }
259
300
 
@@ -359,32 +400,30 @@ export function resetSessionState(agent) {
359
400
  agent._compressFailures = 0
360
401
  agent._verifyRetries = 0
361
402
  agent._verifyPassed = undefined
362
- agent._runStartHistoryLen = 0
363
- // 轮记录面(SESSION §2):新会话无轮记录、无活动账本、无待折叠轮——旧会话的
364
- // 轮记录不得跟新槽走(否则首回合折叠会把上一会话的账算进来);压缩状态(检查点 ∥ 折叠身份标记)
365
- // 同理:新会话没压过,旧检查点跟过去会让首回合的机读线被当成「已被摘要覆盖」。
403
+ // 轮记录面(SESSION §2):新会话无轮记录、无活动账本、无跨轮清理的坐标——旧会话的
404
+ // 轮记录不得跟新槽走(否则首回合的覆盖账会把上一会话的轮算进来);压缩状态同理:新会话没压过,
405
+ // 旧检查点跟过去会让首回合的机读线被当成「已被摘要覆盖」。
366
406
  agent._turns = []
367
- agent._turnFoldMarks = []
368
407
  agent._compactCheckpoint = null
369
408
  agent._turnLedger = null
370
- agent._turnPending = null
371
- agent._turnStartLen = null
372
- agent._turnResponseEnd = null
373
409
  agent._lastPromptTokens = null
374
- agent._usageAtLen = null
410
+ agent._usageAt = null
411
+ agent._usageFixedBase = null
375
412
  // §6.17 估算自校准:新会话无样本(比 = 1)——跨会话不继承旧模型的估算偏差
376
413
  agent._tok = null
377
414
  agent._tokRatio = 1
378
415
  agent.planMode = false
379
416
  agent.goal = null
380
- agent._pendingReminders = []
417
+ agent._pendingInject = []
418
+ agent._inject = []
419
+ agent._retained = []
381
420
  agent._slot = null
382
421
  agent._slotMtime = null
383
422
  agent._slotEffort = null // 新会话无档位(§6.21 判据句 5:全新槽规范形 = `effort: null`)
384
- agent._osReminderInjected = false
385
- // §6.11(2026-09-08):一次性注入标志换名——_restartReminderInjected 推断退役(F3——
386
- // _sessionStart != null 伪触发);/new 清零新标记——恢复武装/启动句标志不跨会话复活
387
- agent._envResumed = false
423
+ // 会话头块随新会话清空(与 `_inject` ∥ `_retained` 同组:旧会话的环境文本不带进新会话;
424
+ // run 起点会重建一份)——写入口仍只有 `setSessionHead` 一个(设计 §1.1「写入面」),不就地写字段。
425
+ setSessionHead(agent, "")
426
+ // §6.11(2026-09-08):/new 或切槽清零启动句标志——它不跨会话复活
388
427
  agent._processRestartPending = false
389
428
  agent._lastEngState = false
390
429
  // /new 或切换:记录存储解绑(新槽由 cmd-new / 首保存补绑重新挂载——§6.14 绑定与对账)
@@ -445,31 +484,26 @@ export function slotOccupancy(cwd, slot) {
445
484
 
446
485
  /** 打开态读数(SESSION.md §6.24 · 桌面残余批——恢复态播种的读数**单源**):槽数据 ⇒ 状态行上下文
447
486
  * 读数百分数(整数)。与 `applySession` 后读数**同源同式**(四事同判——组合既有件,零新公式):
448
- * ① 线选 = `turns` 在场按同一投影重建(同 applySession 恢复权威顺序),否则 `contextHistory` 非空取之,
449
- * 两皆缺时 `history` 经 `stripTruncatedToolArgs` 回退(同 applySession);
487
+ * ① 线选 = `contextHistory` 非空取之(同 applySession 恢复权威顺序;两形态归一后逐条就是装回的那条线),
488
+ * 否则 `history` 经 `stripTruncatedToolArgs` 回退(同 applySession);
450
489
  * ② 回声归并 = `mergeAdjacentAssistantEchoes`(同 applySession 装线前一步);
451
490
  * ③ 渠道合并 = `providers` 命中 `data.activeProvider` ⇒ 槽模型(串值 `activeModel`;非串 ∕ 空串 = 未登记
452
491
  * ⇒ 落链)∥ 无槽模型 ⇒ 现行模型链回落(`defaultModel` 属本渠道 ⇒ 其模型段;两档皆无 ⇒ `null`——
453
492
  * `resolveChannelModel`,2026-10-09 清除批:渠道单值模型退场,零静默回落);未命中 ⇒ `fallback`
454
493
  * (支 ②「静默保持现状」的装配口径 = `loadConfig().provider`);
455
494
  * ④ 公式 = 核 `historyPercent`(= `historyReading` 的 `pct` 薄转口;与 CLI ∥ VSC 同一实现点的投影);
456
- * 第三参 = 槽样本经 `sampleRatio` 取的校准比;第四参 = `opts.workMode`——**必填**(缺 ∥ 非法值由
457
- * `historyPercent` 拒绝并点名 `workMode`);本面只握槽数据与 provider、不握 agent,故档位由调用方
458
- * **当参透传**(`docs/core/design/CONTEXT-COMPACTION.md` §2.3 缺参即拒)。
459
- * 本函数自己不读槽里的 `mode`(纯投影面:档位取哪一档由调用方定,这里不做第二次判定)。
460
- * 调用方取**会话自己的槽档**——`openingSeed` 传 `resolveSessionWorkMode(data, config.agent)`:槽里的 `mode`
461
- * 是会话级权威档(`docs/core/design/SESSION.md` §8「mode 是会话级 tiny/normal/engineering 权威值」),
462
- * 打开态分母与该会话实跑同一档,同一会话不出现两个分母。需求 §2「切换档位即生效与解除,不落盘、
463
- * 不跨会话带走」说的是**有效窗口本身不是持久状态、每次按档位现算**,不是「槽里的档不作数」。
495
+ * 第三参 = 槽样本经 `sampleRatio` 取的校准比。档位不是入参(§2.1 ∥ §2.3):有效窗口恒等于模型窗口,
496
+ * 打开态分母因此只由渠道那一行决定,槽里的 `mode` 不参与读数。
464
497
  * **零副作用**:`data` / `providers` / `fallback` / `defaultModel` 皆入参(不读盘、不写盘、不改任何进程态);
465
498
  * `data` 非对象 ⇒ `0`(与空历史同值——「非正 ⇒ 零节点」显示门归端侧,沿 `historyPercent` 空历史口径)。 */
466
- export function sessionReading(data, { providers, fallback, defaultModel, workMode } = {}) {
499
+ export function sessionReading(data, { providers, fallback, defaultModel } = {}) {
467
500
  if (data === null || typeof data !== "object") return 0
468
501
  const full = Array.isArray(data.history) ? data.history : []
469
- const ch = data.contextHistory
470
- const fallbackLine = (Array.isArray(ch) && ch.length > 0) ? ch : full.map(stripTruncatedToolArgs)
471
- // 与 `applySession` 同尺(SESSION §2 恢复权威顺序):带 `turns` 的槽按同一投影读数。
472
- const line = mergeAdjacentAssistantEchoes(restoreMachineFromTurns(data) ?? fallbackLine)
502
+ const ch = normalizeContextHistory(data.contextHistory)
503
+ const fallbackLine = ch.length > 0 ? ch : [{ messages: full.map(stripTruncatedToolArgs) }]
504
+ // 与 `applySession` 同尺(SESSION §2 恢复权威顺序):打开态读的就是装回的那条线;
505
+ // 读数在拍平视图上算(外层条数是轮数,不是消息数);归并与空串清账同 `applySession` 一趟。
506
+ const line = flattenHistory(fallbackLine.map((turn) => ({ messages: mergeAdjacentAssistantEchoes(turn.messages) })))
473
507
  const entry = data.activeProvider ? providers?.find((pr) => pr.name === data.activeProvider && hasKey(pr)) : null
474
508
  // #638:非串 ∕ 空串 `activeModel` 归一(与 applySession 模型合并支 ① 同判)——脏值不达 `historyPercent`;
475
509
  // 未登记 ⇒ 落现行模型链(`defaultModel` 属本渠段 ∥ `null`——渠道单值退场,2026-10-09 清除批)。
@@ -477,5 +511,5 @@ export function sessionReading(data, { providers, fallback, defaultModel, workMo
477
511
  const provider = entry
478
512
  ? { ...entry, model: slotModel ?? resolveChannelModel(entry, defaultModel ?? null) }
479
513
  : fallback
480
- return historyPercent(line, provider, sampleRatio(data.estimateSample, provider), workMode)
514
+ return historyPercent(line, provider, sampleRatio(data.estimateSample, provider))
481
515
  }
@@ -56,7 +56,7 @@ export function newSlotData(cwd, mode) {
56
56
  history: [], contextHistory: [], tasks: [], turns: [],
57
57
  ...(mode !== undefined ? { mode } : {}),
58
58
  planMode: false, goal: null, autoApprove: false, advisor: null, effort: null,
59
- pendingReminders: [], sessionStart: null,
59
+ pendingInject: [], sessionStart: null,
60
60
  createdBy: sessionEnd(),
61
61
  }
62
62
  }
package/session.mjs CHANGED
@@ -29,9 +29,10 @@ import { guardForeignSlotFile } from "./session-guard.mjs"
29
29
  import { engTokenSlotFields } from "./token-ttl.mjs"
30
30
  // §6.17.1 链二写面(估算校准样本随会话槽走):本档只取写出值,读面在 `session-lifecycle.mjs`(applySession)。
31
31
  import { tokenSampleOf } from "./token-window.mjs"
32
- // 跨轮机读投影(CONTEXT-COMPACTION §1.1 ∥ SESSION §2 · 台账 #2395 ∥ #2397–#2401):槽机读线与恢复面同一实现
33
- // ——同一份轮记录投影出同一条线(在途/异常段原样陪跑),再叠压缩检查点(摘要注记 + 已覆盖条数)。
34
- import { activeTurnRaw, machineLineForSlot, normalizeCheckpoint, slotTurns } from "./agent/turn-projection.mjs"
32
+ // 槽键归一(轮记录 ∥ 压缩检查点):机读线整条落槽之后,投影面只剩折叠一处(`SESSION.md` §2)。
33
+ import { normalizeCheckpoint, slotTurns } from "./agent/turn-projection.mjs"
34
+ // 机读线按轮嵌套:`legacyHistory` 的回退支(无 `_fullHistory`)读的是拍平视图——外层条数是轮数,不是消息数。
35
+ import { flattenHistory } from "./context-push.mjs"
35
36
  // TUI-OOM-ROOTCAUSE 批(SESSION.md §6.14):人读线记录存储(磁盘为准 + 内存窗口)。
36
37
  // slimForDisplay/isLegacyTransient 迁入 store 模块(§6.14 记录存储)——本文件 re-export 保持
37
38
  // 既有 import 面(session-slots.mjs 引 isLegacyTransient)。依赖方向单向:store 零项目内依赖。
@@ -66,9 +67,12 @@ import { resumeSlot as lifecycleResumeSlot } from "./session-lifecycle.mjs"
66
67
  // (legacy transient 判定 + slimForDisplay 自本区迁至 session-store.mjs——§6.14;
67
68
  // 上方 re-export 保持既有 import 面。)
68
69
 
69
- /** 未绑定路径的人读线全量物化(模式 F——既有语义逐字保留)。 */
70
+ /** 未绑定路径的人读线全量物化(模式 F——既有语义逐字保留)。
71
+ * 人读线在(`_fullHistory`)⇒ 原样;回退那一支的机读线已按轮嵌套 ⇒ 先拍平再逐条读
72
+ * (拿嵌套外层当消息数组数,数到的是轮数)。 */
70
73
  function legacyHistory(agent) {
71
- return (agent._fullHistory ?? agent.history)
74
+ const line = Array.isArray(agent._fullHistory) ? agent._fullHistory : flattenHistory(agent.history)
75
+ return line
72
76
  .filter((m) => !m.transient && !isLegacyTransient(m))
73
77
  .map(slimForDisplay)
74
78
  }
@@ -118,23 +122,25 @@ function digestFromStore(fields, counters, mtimeMs) {
118
122
  export function saveSession(agent, opts = {}) {
119
123
  // _fullHistory is written at the source via pushReal — no flush needed here.
120
124
  // history = FULL, never-compacted (human-readable; VS Code panel & CLI resume read this)
121
- // contextHistory = 机读线副本(`turns` 的派生;恢复优先 `turns`,旧槽无 `turns` 时才读它)
122
125
  // Human line: transient machine injections never enter the readable record.
123
126
  // TUI-OOM-ROOTCAUSE 批(SESSION.md §6.14 追加时点):绑定记录存储后 `history` 字段由
124
127
  // saveProjectedSlot 流式拼接段原文生成(磁盘为准——不物化全量数组);未绑定
125
128
  // (模式 F:thincoder chat/测试/未覆盖路径)→ 既有全量物化路径逐字保留(D-SE26 模式 F 零回归)。
126
- // Machine line (contextHistory):机读线投影(SESSION.md §2 ∥ CONTEXT-COMPACTION.md §1.1)——三段按同一投影拼成:
127
- // 摘要注记(`compactCheckpoint` 在场时)+ 检查点之后那些轮记录的投影 + 在途 ∨ 异常段原文,再丢弃 `transient` 标记的消息。
128
- // 与 `applySession` 的重建面同一实现(保存 ∥ 恢复同尺),不在槽里重新写回完整工具过程;
129
- // 任务状态串已在 `turns` 里,副本再存一份没有读者(它不可作恢复依据:恢复优先 `turns`)。
129
+ // Machine line (contextHistory):机读线本身(SESSION.md §2)——保存当刻 `agent.history` 的嵌套形态,
130
+ // 逐元素归一(白名单只有 `messages`):外层每个元素是一轮,内层是该轮自己的消息。
131
+ // 注入不在线上(机读线上只有真实对话)⇒ 不再按 `transient` 滤一遍——有标记的就是旧槽带回来的注入,
132
+ // 按原样装回(设计档 §1.1「槽与迁移」)。恢复面逐条装回这条线,不按 `turns` 重投影。
130
133
  const turns = Array.isArray(agent._turns) ? agent._turns : []
131
134
  // 压缩检查点(SESSION §2 表行):内存载体 = `agent._compactCheckpoint`(`applyCompression` 产出);
132
135
  // 归一不过(无压缩 ∥ 形态坏)⇒ `null` ⇒ **键缺**(不写 `null`、不写空对象)。
133
136
  const compactCheckpoint = normalizeCheckpoint(agent._compactCheckpoint, turns.length)
134
- // 在途 ∥ 异常段(没有轮记录可依的那一段):`transient` 标记的消息落槽前丢弃(与 `contextHistory` 同一条过滤口径)。
135
- const activeRaw = activeTurnRaw(agent).filter((m) => !m?.transient && !isLegacyTransient(m))
136
- const contextHistory = machineLineForSlot(turns, { checkpoint: compactCheckpoint, activeRaw })
137
- .filter((m) => !m?.transient && !isLegacyTransient(m))
137
+ // 在途 ∥ 异常段不再单列键:它就是机读线的尾段,随 `contextHistory` 一起落槽、一起装回(SESSION.md §2)。
138
+ const contextHistory = (Array.isArray(agent.history) ? agent.history : []).map((turn, i) => {
139
+ if (!turn || typeof turn !== "object" || !Array.isArray(turn.messages)) {
140
+ throw new TypeError(`agent.history element ${i} is not a turn ({ messages: [...] })`)
141
+ }
142
+ return { messages: turn.messages }
143
+ })
138
144
  // fields = 槽 JSON 数据面(history 由投影插入——键序与既有 data 形态同序,history/contextHistory 居后)
139
145
  const fields = {
140
146
  version: 2,
@@ -152,18 +158,15 @@ export function saveSession(agent, opts = {}) {
152
158
  ...engTokenSlotFields(agent),
153
159
  goal: agent.goal ?? null,
154
160
  advisor: agent.config?.advisor ?? null,
155
- pendingReminders: agent._pendingReminders ?? [],
161
+ pendingInject: agent._pendingInject ?? [],
156
162
  sessionStart: agent._sessionStart ?? null,
157
163
  // §6.17.1 链二写面:估算校准样本 `{key,num,den,est}`——空样本落 null(不造空对象);
158
164
  // 只随回合尾保存走,不新增写路径、不逐样本落盘。
159
165
  estimateSample: tokenSampleOf(agent),
160
- // 轮记录(SESSION §2:每项形如 `{ userRequest, finalResponse, taskState }`)——
161
- // 机读线的**权威源**:恢复时 `turns` 在场即按同一投影重建(旧槽无该键 ⇒ 回退 `contextHistory`)。
166
+ // 轮记录(SESSION §2:每项形如 `{ userRequest, finalResponse, taskState }`)——人读回查、VSC 端恢复
167
+ // `_turns` 与折叠续记读它;不作机读线的恢复依据。
162
168
  ...(compactCheckpoint ? { compactCheckpoint } : {}),
163
169
  turns: slotTurns(turns),
164
- // 在途 ∥ 异常段原文:单列一键,不由 `contextHistory` 与投影长度的算术差推断(那份副本经 transient 过滤,
165
- // 长度不等于投影长度);`turns` 非空时恢复面只认 `turns`,这段因此必须自己能读回(#2401)。
166
- activeRaw,
167
170
  }
168
171
  // 2026-09-05 §6.10 D-4:首认领(_slot 为 null——如 /session 切换后首保存、“查看对方活槽 →
169
172
  // 保存 fork 新槽”的落盘槽跟随)写本端记录——marker = 端内最后认领者;粘性 _slot 期间
@@ -1,17 +1,21 @@
1
1
  /**
2
- * shell-identity.mjs — bash 工具**执行器身份**探测单源(bash-executor-face 批 · 台账 #922——
3
- * 设计权威 = `docs/core/design/BASH-EXECUTOR-FACE.md` §2 契约 + §3.1)。
2
+ * shell-identity.mjs — bash 工具**执行器身份与版本**探测单源(bash-executor-face 批 · 台账 #922——
3
+ * 设计权威 = `docs/core/design/BASH-EXECUTOR-FACE.md` §2「接口契约」)。
4
4
  *
5
5
  * 探测源 = **spawn 同链镜像**(`tools/bash.mjs` spawn 的 `shell` 参数计算式):
6
6
  * config.shell(trim 后非空即用)→ win32 %COMSPEC% → 兜底字面 `cmd.exe`;
7
7
  * 非 win32 = `process.env.SHELL` → 兜底 `/bin/sh`(Node `shell:true` 兜底的事实陈述,非平台推断)。
8
- * 探测值 = 实际执行器(不是环境快照);探测不到(识别表未命中知名字)⇒ `unknown` 中性句
9
- * (fail-open 零猜测——用户 2026-10-04 22:48 裁定③);**零静态平台默认**(裁定①)。
8
+ * 探测值 = 实际执行器(不是环境快照);识别表未命中知名字 ⇒ `kind: "unknown"`(fail-open 零猜测——
9
+ * 用户 2026-10-04 22:48 裁定③);**零静态平台默认**(裁定①)。
10
+ *
11
+ * 版本 = **执行器自报**(`probeShellVersion` 起子进程问它),不从可执行文件名推断;探不到只写名字
12
+ * (`shellVersionLine`),不回落任何版本号。身份写进会话头块那一行,工具描述不再带执行器声明。
10
13
  *
11
14
  * memo(进程生命周期 + 按配置值键控)先例 = `shell-candidates.mjs`(「shell 路径不热变化」同判据);
12
15
  * 配置值变化 ⇒ memo 未命中重探(K2 配置变更刷新 ∥ 裁定①零静态同时成立)。
13
16
  * 测试缝 `_setComSpecForTest` 先例 = `shell-candidates.mjs` `_setShellDetectForTest`。
14
17
  */
18
+ import { execFile } from "node:child_process"
15
19
 
16
20
  // 识别表(raw 尾段词 → 显示名 + 语法族)。匹配大小写不敏感,尾段词先剥 `.exe` 后缀(U3——
17
21
  // `bash.exe` ∥ `cmd.exe` ∥ `pwsh.exe` 均须命中);序 = 最特异优先:
@@ -76,32 +80,135 @@ export function resolveShellIdentity(configShell) {
76
80
  /** memo(进程生命周期 ∕ 按配置值键控——本档单点持有)。 */
77
81
  const _memo = { key: undefined, value: null }
78
82
 
79
- /** 测试缝:注入 %COMSPEC% 读数(undefined = 复位真实环境读数);注入即清 memo。 */
83
+ /** 版本探测的时间预算(ms):`probeShellVersion` 的硬上限。装配点原值传入,本常量只说预算。 */
84
+ export const SHELL_VERSION_TIMEOUT_MS = 1200
85
+
86
+ /** 版本串文法:首个 `<数字>(.<数字>)+`——`5.1.22621.6133` ∥ `v24.19.0` ∥ `10.0.22631.6199` 都取这一段。 */
87
+ const VERSION_TOKEN_RE = /\d+(?:\.\d+)+/
88
+
89
+ /** 版本串上限(设计档 §2「版本串收窄」:首个版本 token、去空白换行、上限 32 字符)。 */
90
+ const VERSION_MAX_CHARS = 32
91
+
92
+ /** 单个探测命令的输出上限。超出时 Node 以 `ERR_CHILD_PROCESS_STDIO_MAXBUFFER` 结束子进程 ⇒ 本次按失败处理。 */
93
+ const VERSION_MAX_BUFFER = 64 * 1024
94
+
95
+ /**
96
+ * kind ⇒ 探测命令的**参数**(可执行文件 = `identity.raw` 本身,不经 shell 拼串)。
97
+ * `cmd` 那一行取 `ver` 报的 Windows 版本号:cmd.exe 没有另一条自报版本的面(设计档 §2 探测表)。
98
+ * `unknown` 不在表内 ⇒ 不探测。
99
+ */
100
+ const PROBE_ARGS = Object.freeze({
101
+ powershell: Object.freeze(["-NoProfile", "-NonInteractive", "-Command", "$PSVersionTable.PSVersion.ToString()"]),
102
+ posix: Object.freeze(["--version"]),
103
+ cmd: Object.freeze(["/d", "/c", "ver"]),
104
+ })
105
+
106
+ /**
107
+ * 版本单槽缓存:`raw` 记这份版本属于哪个执行器(`null` = 还没探过),`version` = 探测值
108
+ * (探测失败同样缓存为 `null`——不为一条探不到的事实每回合重付一次代价)。
109
+ */
110
+ const _versionCache = { raw: null, version: null }
111
+
112
+ /** 测试缝注入的版本(`null` = 没注入)。注入值优先于缓存与子进程。 */
113
+ let _versionForTest = null
114
+
115
+ /** 测试缝:注入 %COMSPEC% 读数(undefined = 复位真实环境读数);注入即清两份缓存。 */
80
116
  let _comSpecOverride = null
81
117
  export function _setComSpecForTest(value) {
82
118
  _comSpecOverride = value === undefined ? null : value
83
119
  _memo.key = undefined
84
120
  _memo.value = null
121
+ // 同一条身份链上的事实:身份重探了,版本缓存也跟着失效(两者同源)。
122
+ _versionCache.raw = null
123
+ _versionCache.version = null
85
124
  }
86
125
 
87
126
  /**
88
- * kind ⇒ 注入值面(一行 Executor 声明 · 设计档 §2 值面表逐字)。powershell 族按 raw 尾段词
89
- * `/pwsh/i` 分流(pwsh 形 ∥ Windows PowerShell 5.x 形);identity.kind 为 unknown ⇒ 中性句。
90
- * @param {{ raw: string, name: string, kind: string, known: boolean }} identity resolveShellIdentity 出参
91
- * @returns {string}
127
+ * 探测执行器**自报**的版本(设计档 §2 探测表)。
128
+ *
129
+ * 硬上限 = `timeoutMs`:超时由 `execFile` 杀掉子进程、回调收到错误 ⇒ `null`。执行器启动失败、非零退出、
130
+ * 输出里没有版本串、`kind: "unknown"`(识别表未命中,不探测)⇒ 同样 `null`。**永不抛、永不拒绝**——
131
+ * 探测失败不该拦住一次 run;唯一抛出的情形是缺 `timeoutMs`(那是调用方的编码错误,不是探测失败)。
132
+ *
133
+ * 结果按 `identity.raw` 单槽缓存:同一个 raw 第二次调用零子进程。raw 变了 ⇒ 重探。
134
+ * @param {{ raw: string, name: string, kind: string, known: boolean }} identity `resolveShellIdentity` 出参
135
+ * @param {{ timeoutMs: number }} opts `timeoutMs` 必填、无默认(缺参即抛并点名该参数)
136
+ * @returns {Promise<string|null>} 版本串 / `null`(探不到)
92
137
  */
93
- export function executorLine(identity) {
94
- const { raw, name, kind } = identity
95
- switch (kind) {
96
- case "cmd":
97
- return "- Executor: the bash tool runs commands through Windows cmd.exe (%COMSPEC%). Use cmd syntax: && works; NUL not /dev/null; %VAR% not $VAR; no single-quote grouping. For complex logic prefer the execute tool (node)."
98
- case "powershell":
99
- return /pwsh/i.test(lastWord(raw))
100
- ? `- Executor: the bash tool runs commands through PowerShell (pwsh; ${raw}). && and || work; %VAR% does not expand (use $VAR); cmdlets differ (Remove-Item, Copy-Item). For complex logic prefer the execute tool (node).`
101
- : `- Executor: the bash tool runs commands through Windows PowerShell (${raw}). PS 5.1 has NO &&/|| (use ; or separate calls); redirection differs (2>/dev/null is invalid); cmdlets differ (Remove-Item, Copy-Item). For complex logic prefer the execute tool (node).`
102
- case "posix":
103
- return `- Executor: the bash tool runs commands through a POSIX shell (${raw}). Standard POSIX syntax applies ($(...), $VAR, ;, >/dev/null).`
104
- default:
105
- return `- Executor: the bash tool shell could not be identified (raw: ${raw}) — write portable commands and trust the command's own error output.`
138
+ export async function probeShellVersion(identity, { timeoutMs } = {}) {
139
+ if (typeof timeoutMs !== "number" || !Number.isFinite(timeoutMs) || timeoutMs <= 0) {
140
+ throw new Error(`probeShellVersion: \`timeoutMs\` is required (a positive number, no default) — pass SHELL_VERSION_TIMEOUT_MS; got ${JSON.stringify(timeoutMs)}`)
106
141
  }
142
+ if (_versionForTest !== null) return _versionForTest
143
+ const raw = rawOf(identity)
144
+ if (_versionCache.raw === raw) return _versionCache.version
145
+ const args = PROBE_ARGS[identity?.kind]
146
+ const version = args ? await runProbe(raw, args, timeoutMs) : null
147
+ _versionCache.raw = raw
148
+ _versionCache.version = version
149
+ return version
107
150
  }
151
+
152
+ /**
153
+ * 会话头那一行里 `Shell:` 的值(设计档 §2):`<name>` 或 `<name> <version>`。
154
+ * 同步、**只读缓存**(绝不起子进程——压缩后的头块重建走这里)。未探测 / 探测失败 /
155
+ * `kind: "unknown"` ⇒ 只有 `<name>`;`unknown` 的 name 就是 raw 本身,认不出的执行器照样写进会话头。
156
+ * @param {{ raw: string, name: string, kind: string, known: boolean }} identity `resolveShellIdentity` 出参
157
+ * @returns {string}
158
+ */
159
+ export function shellVersionLine(identity) {
160
+ const name = identity?.name == null ? rawOf(identity) : String(identity.name)
161
+ const version = cachedVersionFor(identity)
162
+ return version ? `${name} ${version}` : name
163
+ }
164
+
165
+ /**
166
+ * 测试缝:注入版本值(批旁单测用——不起子进程就能判 `shellVersionLine` 的两种形)。
167
+ * 传 `null`(或 `undefined`)即清,与 `_setComSpecForTest(undefined)` 同形;注入即清缓存。
168
+ */
169
+ export function _setShellVersionForTest(value) {
170
+ _versionForTest = value == null ? null : String(value)
171
+ _versionCache.raw = null
172
+ _versionCache.version = null
173
+ }
174
+
175
+ /** 身份里的 raw 原值(恒为字符串:`resolveShellIdentity` 的出参面)。 */
176
+ function rawOf(identity) {
177
+ return identity?.raw == null ? "" : String(identity.raw)
178
+ }
179
+
180
+ /** 缓存里属于这份身份的值(`raw` 相同才算同一个执行器);没探过就是 `null`。 */
181
+ function cachedVersionFor(identity) {
182
+ if (_versionForTest !== null) return _versionForTest
183
+ return _versionCache.raw === rawOf(identity) ? _versionCache.version : null
184
+ }
185
+
186
+ /**
187
+ * 执行一次探测命令并取版本串。`execFile` 不经 shell(`raw` 带空格的路径免引号);超时、非零退出、
188
+ * 输出超限都由回调收到错误 ⇒ `null`。`execFile` 对不可执行的目标还会**同步抛**(Windows 上
189
+ * `.cmd` 即 spawn `EINVAL`)⇒ 同一处置。本函数从不拒绝。
190
+ */
191
+ function runProbe(file, args, timeoutMs) {
192
+ return new Promise((resolve) => {
193
+ let settled = false
194
+ const finish = (value) => {
195
+ if (settled) return
196
+ settled = true
197
+ resolve(value)
198
+ }
199
+ try {
200
+ execFile(file, args, { timeout: timeoutMs, maxBuffer: VERSION_MAX_BUFFER, windowsHide: true }, (err, stdout) => {
201
+ finish(err ? null : firstVersionToken(stdout))
202
+ })
203
+ } catch {
204
+ finish(null)
205
+ }
206
+ })
207
+ }
208
+
209
+ /** 首个版本 token(设计档 §2「版本串收窄」);无匹配 ⇒ `null`。 */
210
+ function firstVersionToken(output) {
211
+ const hit = VERSION_TOKEN_RE.exec(String(output ?? ""))
212
+ if (!hit) return null
213
+ return hit[0].trim().slice(0, VERSION_MAX_CHARS) || null
214
+ }