@thincoder/core 0.11.1 → 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 (382) hide show
  1. package/CHANGELOG.md +64 -2
  2. package/advisor/compaction.mjs +7 -5
  3. package/advisor/convergence.mjs +34 -3
  4. package/advisor/history.mjs +24 -11
  5. package/advisor/loop.mjs +49 -12
  6. package/advisor/messages.mjs +114 -33
  7. package/advisor/project-context.mjs +171 -42
  8. package/advisor/run.mjs +24 -10
  9. package/advisor.mjs +36 -46
  10. package/agent/batch-attribution.mjs +87 -0
  11. package/agent/batch-changed-surface.mjs +129 -0
  12. package/agent/chat-call.mjs +14 -9
  13. package/agent/completion.mjs +70 -41
  14. package/agent/continue-decision.mjs +14 -8
  15. package/agent/digest-account.mjs +133 -59
  16. package/agent/dispatch-gates.mjs +6 -0
  17. package/agent/dispatch-run.mjs +1 -1
  18. package/agent/dispatch.mjs +10 -4
  19. package/agent/family-tools.mjs +37 -23
  20. package/agent/helpers.mjs +139 -73
  21. package/agent/image-heal.mjs +18 -4
  22. package/agent/offload.mjs +25 -29
  23. package/agent/post-turn.mjs +36 -35
  24. package/agent/record-results.mjs +39 -7
  25. package/agent/run-stages.mjs +132 -52
  26. package/agent/run-start.mjs +150 -78
  27. package/agent/setup-reminders.mjs +194 -91
  28. package/agent/setup.mjs +219 -140
  29. package/agent/spawn-child.mjs +40 -3
  30. package/agent/suspension.mjs +43 -15
  31. package/agent/timers.mjs +9 -4
  32. package/agent/turn-domain-text.mjs +105 -0
  33. package/agent/turn-loop.mjs +84 -27
  34. package/agent/turn-projection.mjs +286 -0
  35. package/agent/turn-task-state.mjs +274 -0
  36. package/agent/turn-tool-process.mjs +163 -0
  37. package/agent/write-gate-ledger.mjs +569 -0
  38. package/agent/write-gate.mjs +29 -352
  39. package/agent-tools/advisor-async.mjs +35 -172
  40. package/agent-tools/advisor-launch.mjs +178 -0
  41. package/agent-tools/advisor-settle.mjs +28 -1
  42. package/agent-tools/advisor.mjs +37 -48
  43. package/agent-tools/async-discard.mjs +7 -2
  44. package/agent-tools/async-settle.mjs +18 -12
  45. package/agent-tools/audit-block.mjs +6 -6
  46. package/agent-tools/bash-async.mjs +5 -2
  47. package/agent-tools/batch-closeout.mjs +223 -35
  48. package/agent-tools/batch-gate.mjs +142 -342
  49. package/agent-tools/batch-ledger-bind.mjs +240 -20
  50. package/agent-tools/batch-ledger-view.mjs +109 -0
  51. package/agent-tools/batch-lifecycle.mjs +197 -48
  52. package/agent-tools/batch-paths.mjs +29 -8
  53. package/agent-tools/batch-read.mjs +151 -4
  54. package/agent-tools/batch-record-write.mjs +417 -0
  55. package/agent-tools/batch-regions.mjs +215 -0
  56. package/agent-tools/batch-reopen.mjs +23 -11
  57. package/agent-tools/batch-segment-vocab.mjs +459 -0
  58. package/agent-tools/batch-skeleton.mjs +196 -239
  59. package/agent-tools/batch-supersede.mjs +232 -0
  60. package/agent-tools/batch-tier-gate.mjs +214 -0
  61. package/agent-tools/batch.mjs +192 -439
  62. package/agent-tools/browser-async.mjs +5 -2
  63. package/agent-tools/consult.mjs +17 -11
  64. package/agent-tools/context.mjs +76 -33
  65. package/agent-tools/design-review-record.mjs +225 -0
  66. package/agent-tools/design-slots.mjs +1 -1
  67. package/agent-tools/design-token.mjs +279 -81
  68. package/agent-tools/digest-budget.mjs +10 -9
  69. package/agent-tools/doc-check.mjs +43 -33
  70. package/agent-tools/doc-graph.mjs +140 -0
  71. package/agent-tools/eng.mjs +12 -12
  72. package/agent-tools/escalate-async.mjs +5 -5
  73. package/agent-tools/goal.mjs +5 -2
  74. package/agent-tools/judge-domain.mjs +347 -0
  75. package/agent-tools/manifest.mjs +34 -18
  76. package/agent-tools/parent-channel.mjs +6 -3
  77. package/agent-tools/plan.mjs +11 -10
  78. package/agent-tools/read-history.mjs +112 -11
  79. package/agent-tools/review-facts.mjs +19 -6
  80. package/agent-tools/settings.mjs +23 -2
  81. package/agent-tools/skill.mjs +7 -8
  82. package/agent-tools/spawn-gates.mjs +14 -24
  83. package/agent-tools/ssh-session.mjs +8 -5
  84. package/agent-tools/ssh-text.mjs +155 -0
  85. package/agent-tools/ssh-transfer.mjs +1 -1
  86. package/agent-tools/ssh-transport.mjs +19 -148
  87. package/agent-tools/subagent-actions-query.mjs +10 -6
  88. package/agent-tools/subagent-actions.mjs +2 -2
  89. package/agent-tools/subagent-async.mjs +19 -17
  90. package/agent-tools/subagent-brief.mjs +76 -0
  91. package/agent-tools/subagent-design-token.mjs +168 -0
  92. package/agent-tools/subagent-run.mjs +1 -1
  93. package/agent-tools/subagent-scheduler.mjs +13 -13
  94. package/agent-tools/subagent-spawn.mjs +92 -112
  95. package/agent-tools/subagent.mjs +16 -28
  96. package/agent-tools/task.mjs +0 -8
  97. package/agent-tools/taskbook-block.mjs +94 -0
  98. package/agent-tools/timer.mjs +12 -8
  99. package/agent-tools/verify.mjs +13 -4
  100. package/agent-tools.mjs +7 -3
  101. package/agent.mjs +26 -7
  102. package/attachments.mjs +3 -3
  103. package/auto-think.mjs +5 -2
  104. package/browser/actions.mjs +9 -3
  105. package/browser/cdp.mjs +45 -17
  106. package/browser/launch.mjs +25 -43
  107. package/browser/pool.mjs +299 -0
  108. package/browser/queue.mjs +2 -0
  109. package/browser/session-state.mjs +450 -0
  110. package/browser/session.mjs +127 -151
  111. package/browser/snapshot.mjs +89 -0
  112. package/client-identity.mjs +1 -1
  113. package/compaction-work-state.mjs +230 -0
  114. package/compress-form.mjs +41 -6
  115. package/config-defaults.mjs +7 -3
  116. package/config-migrate.mjs +40 -0
  117. package/config-normalize.mjs +28 -2
  118. package/config-reload.mjs +59 -0
  119. package/config.mjs +110 -110
  120. package/context-degrade.mjs +93 -34
  121. package/context-echo.mjs +6 -15
  122. package/context-push.mjs +328 -31
  123. package/context.mjs +298 -170
  124. package/conventions.mjs +11 -9
  125. package/declaration.mjs +126 -22
  126. package/declared-repos.mjs +94 -0
  127. package/doc-check/doc-names.mjs +73 -0
  128. package/doc-check/doc-tokens.mjs +110 -0
  129. package/doc-check/existence.mjs +160 -0
  130. package/doc-check/index.mjs +309 -213
  131. package/doc-check/line-refs.mjs +27 -101
  132. package/doc-check/paragraph.mjs +218 -102
  133. package/doc-graph/anchors.mjs +474 -0
  134. package/doc-graph/doc-batch-face.mjs +59 -0
  135. package/doc-graph/doc-suffix.mjs +27 -0
  136. package/doc-graph/graph-tokens.mjs +160 -0
  137. package/doc-graph.mjs +778 -0
  138. package/escape.mjs +6 -5
  139. package/explore-distill.mjs +41 -8
  140. package/generate-title.mjs +10 -1
  141. package/i18n.mjs +1 -1
  142. package/instance-inbox-watch.mjs +272 -0
  143. package/instance-inbox.mjs +218 -0
  144. package/instance-registry.mjs +179 -0
  145. package/knowledge/README.md +3 -0
  146. package/knowledge/prompt-resources.md +10 -0
  147. package/ledger-close-proof.mjs +100 -49
  148. package/ledger-close.mjs +188 -0
  149. package/ledger-cmd.mjs +47 -91
  150. package/ledger-consistency.mjs +113 -0
  151. package/ledger-db.mjs +47 -15
  152. package/ledger-executors.mjs +1 -1
  153. package/ledger-tools.mjs +121 -62
  154. package/ledger-write-ops.mjs +162 -46
  155. package/ledger.mjs +1 -1
  156. package/manifest-discovery.mjs +3 -1
  157. package/manifest-schema.mjs +27 -5
  158. package/memory/docs.mjs +51 -15
  159. package/memory/file-list.mjs +6 -0
  160. package/memory/schema.mjs +2 -2
  161. package/model-specs.mjs +87 -21
  162. package/origin-guard.mjs +190 -0
  163. package/package.json +3 -1
  164. package/path-resolve.mjs +338 -57
  165. package/prompt-files.mjs +114 -2
  166. package/prompt-overlays.mjs +21 -11
  167. package/prompts/advisor-design.md +96 -36
  168. package/prompts/advisor-round1.md +48 -4
  169. package/prompts/advisor-round2.md +54 -10
  170. package/prompts/advisor-round3.md +53 -9
  171. package/prompts/common.md +99 -434
  172. package/prompts/consult-base.md +7 -4
  173. package/prompts/discipline-engineering.md +504 -295
  174. package/prompts/discipline-normal.md +106 -281
  175. package/prompts/knowledge/business-gates.md +30 -0
  176. package/prompts/knowledge/decision-quality.md +21 -0
  177. package/prompts/knowledge/doc-lookup.md +30 -0
  178. package/prompts/knowledge/document-writing.md +33 -0
  179. package/prompts/knowledge/documentation-evaluation.md +48 -0
  180. package/prompts/knowledge/evidence-discipline.md +38 -0
  181. package/prompts/knowledge/normal-coding-workflow.md +110 -0
  182. package/prompts/knowledge/normal-delivery-collaboration.md +124 -0
  183. package/prompts/knowledge/normal-work-management.md +60 -0
  184. package/prompts/knowledge/product-security.md +28 -0
  185. package/prompts/knowledge/project-records.md +73 -0
  186. package/prompts/knowledge/tool-advisor.md +29 -0
  187. package/prompts/knowledge/tool-apply-patch.md +17 -0
  188. package/prompts/knowledge/tool-bash.md +48 -0
  189. package/prompts/knowledge/tool-batch-eng-coder.md +19 -0
  190. package/prompts/knowledge/tool-batch-eng-designer.md +20 -0
  191. package/prompts/knowledge/tool-batch-review.md +18 -0
  192. package/prompts/knowledge/tool-batch.md +94 -0
  193. package/prompts/knowledge/tool-browser.md +68 -0
  194. package/prompts/knowledge/tool-code-search.md +4 -0
  195. package/prompts/knowledge/tool-consult-start.md +12 -0
  196. package/prompts/knowledge/tool-consult-stop.md +6 -0
  197. package/prompts/knowledge/tool-context.md +6 -0
  198. package/prompts/knowledge/tool-delete.md +21 -0
  199. package/prompts/knowledge/tool-doc-check.md +71 -0
  200. package/prompts/knowledge/tool-doc-graph-read.md +20 -0
  201. package/prompts/knowledge/tool-doc-graph.md +49 -0
  202. package/prompts/knowledge/tool-doc-search.md +6 -0
  203. package/prompts/knowledge/tool-edit.md +41 -0
  204. package/prompts/knowledge/tool-eng.md +2 -0
  205. package/prompts/knowledge/tool-execute.md +21 -0
  206. package/prompts/knowledge/tool-fetch.md +18 -0
  207. package/prompts/knowledge/tool-file-ops.md +21 -0
  208. package/prompts/knowledge/tool-get-current-time.md +7 -0
  209. package/prompts/knowledge/tool-git-read.md +21 -0
  210. package/prompts/knowledge/tool-git.md +29 -0
  211. package/prompts/knowledge/tool-glob.md +17 -0
  212. package/prompts/knowledge/tool-goal.md +8 -0
  213. package/prompts/knowledge/tool-grep.md +21 -0
  214. package/prompts/knowledge/tool-hashline-edit.md +16 -0
  215. package/prompts/knowledge/tool-insert-after.md +17 -0
  216. package/prompts/knowledge/tool-instance-list.md +6 -0
  217. package/prompts/knowledge/tool-instance-send.md +10 -0
  218. package/prompts/knowledge/tool-knowledge.md +18 -0
  219. package/prompts/knowledge/tool-ledger-read.md +28 -0
  220. package/prompts/knowledge/tool-ledger.md +46 -0
  221. package/prompts/knowledge/tool-lint.md +16 -0
  222. package/prompts/knowledge/tool-ls.md +15 -0
  223. package/prompts/knowledge/tool-lsp.md +11 -0
  224. package/prompts/knowledge/tool-main-history.md +2 -0
  225. package/prompts/knowledge/tool-manifest-read.md +14 -0
  226. package/prompts/knowledge/tool-manifest.md +34 -0
  227. package/prompts/knowledge/tool-memory-read.md +20 -0
  228. package/prompts/knowledge/tool-memory.md +19 -0
  229. package/prompts/knowledge/tool-notify-parent.md +12 -0
  230. package/prompts/knowledge/tool-operations.md +102 -0
  231. package/prompts/knowledge/tool-peer-instances.md +2 -0
  232. package/prompts/knowledge/tool-plan.md +5 -0
  233. package/prompts/knowledge/tool-process-read.md +13 -0
  234. package/prompts/knowledge/tool-process.md +15 -0
  235. package/prompts/knowledge/tool-question.md +16 -0
  236. package/prompts/knowledge/tool-read-history-batch.md +22 -0
  237. package/prompts/knowledge/tool-read-history.md +35 -0
  238. package/prompts/knowledge/tool-read-image.md +11 -0
  239. package/prompts/knowledge/tool-read.md +22 -0
  240. package/prompts/knowledge/tool-recent-changes.md +6 -0
  241. package/prompts/knowledge/tool-repo-outline.md +4 -0
  242. package/prompts/knowledge/tool-settings-read.md +12 -0
  243. package/prompts/knowledge/tool-settings.md +17 -0
  244. package/prompts/knowledge/tool-skill.md +6 -0
  245. package/prompts/knowledge/tool-ssh.md +74 -0
  246. package/prompts/knowledge/tool-subagent.md +57 -0
  247. package/prompts/knowledge/tool-task.md +14 -0
  248. package/prompts/knowledge/tool-team-ledger-read.md +11 -0
  249. package/prompts/knowledge/tool-team-ledger.md +15 -0
  250. package/prompts/knowledge/tool-timer.md +23 -0
  251. package/prompts/knowledge/tool-tree.md +16 -0
  252. package/prompts/knowledge/tool-verify.md +19 -0
  253. package/prompts/knowledge/tool-wait-for.md +25 -0
  254. package/prompts/knowledge/tool-websearch.md +19 -0
  255. package/prompts/knowledge/tool-write.md +12 -0
  256. package/prompts/knowledge/upstream-protocol.md +45 -0
  257. package/prompts/persona-coder.md +1 -3
  258. package/prompts/persona-eng-coder.md +24 -6
  259. package/prompts/persona-eng-designer.md +150 -171
  260. package/prompts/persona-engineering.md +531 -442
  261. package/prompts/persona-explore.md +1 -3
  262. package/prompts/persona-normal.md +17 -9
  263. package/prompts/persona-plan.md +5 -3
  264. package/prompts/persona-tester.md +0 -2
  265. package/prompts/subagent-base.md +2 -2
  266. package/provider/anthropic.mjs +10 -6
  267. package/provider/core.mjs +8 -5
  268. package/provider/errors.mjs +63 -4
  269. package/provider/google.mjs +29 -10
  270. package/provider/reasoning-echo.mjs +16 -0
  271. package/provider/responses.mjs +7 -3
  272. package/provider/sse.mjs +11 -6
  273. package/provider-flows.mjs +2 -2
  274. package/rules.mjs +11 -10
  275. package/session-index-build.mjs +1 -1
  276. package/session-index-pass.mjs +1 -1
  277. package/session-index-query.mjs +1 -1
  278. package/session-index.mjs +1 -1
  279. package/session-lifecycle.mjs +131 -42
  280. package/session-slot-write.mjs +38 -6
  281. package/session.mjs +30 -11
  282. package/shell-identity.mjs +129 -22
  283. package/skip-dirs.mjs +26 -2
  284. package/team-ledger.mjs +34 -30
  285. package/text-budget.mjs +1 -1
  286. package/think-off.mjs +27 -0
  287. package/token-ttl.mjs +74 -5
  288. package/token-window.mjs +371 -47
  289. package/tool-docs/advisor.md +2 -27
  290. package/tool-docs/apply_patch.md +1 -15
  291. package/tool-docs/bash.md +2 -43
  292. package/tool-docs/batch-eng-coder.md +3 -0
  293. package/tool-docs/batch-eng-designer.md +3 -0
  294. package/tool-docs/batch-review.md +3 -0
  295. package/tool-docs/batch.md +2 -84
  296. package/tool-docs/browser.md +2 -49
  297. package/tool-docs/code_search.md +2 -2
  298. package/tool-docs/consult_start.md +2 -8
  299. package/tool-docs/consult_stop.md +2 -4
  300. package/tool-docs/context.md +1 -5
  301. package/tool-docs/delete.md +2 -17
  302. package/tool-docs/doc_check.md +2 -107
  303. package/tool-docs/doc_graph-read.md +3 -0
  304. package/tool-docs/doc_graph.md +3 -0
  305. package/tool-docs/doc_search.md +2 -4
  306. package/tool-docs/edit.md +1 -38
  307. package/tool-docs/eng.md +3 -1
  308. package/tool-docs/execute.md +2 -18
  309. package/tool-docs/fetch.md +2 -14
  310. package/tool-docs/file_ops.md +2 -18
  311. package/tool-docs/get_current_time.md +1 -6
  312. package/tool-docs/git-read.md +3 -0
  313. package/tool-docs/git.md +2 -35
  314. package/tool-docs/glob.md +2 -10
  315. package/tool-docs/goal.md +1 -6
  316. package/tool-docs/grep.md +2 -18
  317. package/tool-docs/hashline_edit.md +2 -15
  318. package/tool-docs/insert_after.md +2 -16
  319. package/tool-docs/instance_list.md +3 -0
  320. package/tool-docs/instance_send.md +3 -0
  321. package/tool-docs/knowledge.md +3 -0
  322. package/tool-docs/ledger-read.md +3 -0
  323. package/tool-docs/ledger.md +3 -8
  324. package/tool-docs/lint.md +2 -10
  325. package/tool-docs/ls.md +2 -11
  326. package/tool-docs/lsp.md +2 -9
  327. package/tool-docs/main_history.md +3 -1
  328. package/tool-docs/manifest-read.md +2 -8
  329. package/tool-docs/manifest.md +2 -35
  330. package/tool-docs/memory-read.md +3 -0
  331. package/tool-docs/memory.md +2 -20
  332. package/tool-docs/notify_parent.md +2 -13
  333. package/tool-docs/peer_instances.md +3 -1
  334. package/tool-docs/plan.md +1 -5
  335. package/tool-docs/process-read.md +3 -0
  336. package/tool-docs/process.md +2 -13
  337. package/tool-docs/question.md +3 -17
  338. package/tool-docs/read.md +2 -19
  339. package/tool-docs/read_history-batch.md +3 -0
  340. package/tool-docs/read_history.md +2 -18
  341. package/tool-docs/read_image.md +2 -9
  342. package/tool-docs/recent_changes.md +2 -2
  343. package/tool-docs/repo_outline.md +2 -2
  344. package/tool-docs/settings-read.md +3 -0
  345. package/tool-docs/settings.md +1 -12
  346. package/tool-docs/skill.md +2 -6
  347. package/tool-docs/ssh.md +1 -62
  348. package/tool-docs/subagent.md +2 -100
  349. package/tool-docs/task.md +1 -7
  350. package/tool-docs/team_ledger-read.md +3 -0
  351. package/tool-docs/team_ledger.md +3 -9
  352. package/tool-docs/timer.md +2 -19
  353. package/tool-docs/tree.md +2 -13
  354. package/tool-docs/verify.md +2 -12
  355. package/tool-docs/wait_for.md +2 -32
  356. package/tool-docs/websearch.md +2 -19
  357. package/tool-docs/write.md +2 -12
  358. package/tools/browser.mjs +54 -9
  359. package/tools/doc-write-gate.mjs +73 -0
  360. package/tools/edit-batch.mjs +170 -92
  361. package/tools/edit-diff.mjs +78 -62
  362. package/tools/edit-receipt.mjs +39 -0
  363. package/tools/execute.mjs +3 -3
  364. package/tools/file.mjs +28 -14
  365. package/tools/git.mjs +36 -21
  366. package/tools/index.mjs +6 -0
  367. package/tools/knowledge.mjs +143 -0
  368. package/tools/linter.mjs +3 -3
  369. package/tools/ops.mjs +5 -3
  370. package/tools/patch.mjs +124 -44
  371. package/tools/process-doc-mark.mjs +33 -4
  372. package/tools/repomap.mjs +25 -3
  373. package/tools/search.mjs +74 -26
  374. package/tools/shared.mjs +29 -27
  375. package/tools/ssh.mjs +5 -5
  376. package/tools/tree.mjs +32 -10
  377. package/tools/web-deepseek.mjs +1 -1
  378. package/tools/web.mjs +2 -2
  379. package/tools/write-gate-params.mjs +31 -0
  380. package/tools/write-path.mjs +16 -4
  381. package/window-policy.mjs +243 -0
  382. package/doc-check/anchors.mjs +0 -235
package/config.mjs CHANGED
@@ -14,7 +14,7 @@
14
14
  import { existsSync, readFileSync } from "node:fs"
15
15
  import { parseModelRef, resolveChannelModel, resolveProviderPlan, resolveRuntimeProvider, defaultModelReason } from "./model-ref.mjs"
16
16
  // 老形态迁移核(M7 v2——纯函数零依赖——本文件超 500 行硬限拆分,VSC 同构文件)
17
- import { migrateLegacyModelFields } from "./config-migrate.mjs"
17
+ import { migrateLegacyModelFields, resolveWorkMode } from "./config-migrate.mjs"
18
18
  import { expandHome } from "./expand-home.mjs"
19
19
  // 核内单一读写面 + 预设表(§2.5 #129 / #131——拆档以容纳 500 行硬限)
20
20
  import {
@@ -23,6 +23,7 @@ import {
23
23
  } from "./config-io.mjs"
24
24
 
25
25
  export { parseModelRef, resolveChannelModel, resolveProviderPlan, resolveRuntimeProvider, defaultModelReason, migrateLegacyModelFields }
26
+ export { WORK_MODES, resolveWorkMode, resolveSessionWorkMode, setConfigWorkMode } from "./config-migrate.mjs"
26
27
  export { PROVIDER_PRESETS, presetToEntry, configDir, configPath, _setConfigPathForTest, _resetConfigPathForTest }
27
28
  // 核内单一写盘执行体(已迁 `config-io.mjs`)——本档 re-export 保持既有导入面(§2.5 #131)。
28
29
  export { writeConfigAtomic }
@@ -37,100 +38,25 @@ export { DEFAULTS }
37
38
  // Model capability table + spec lookup live in model-specs.mjs (2026-08-31
38
39
  // extract — config.mjs had grown past the 300-line advisory). Re-exported here
39
40
  // so the 23 existing importers keep their import paths.
40
- import { specForModel, providerSpec, providerSpecResolution, specMatch, formatContextK, assistantToolCallMessage } from "./model-specs.mjs"
41
- export { specForModel, providerSpec, providerSpecResolution, specMatch, formatContextK, assistantToolCallMessage }
41
+ import { specForModel, providerSpec, providerSpecResolution, specMatch, formatContextK, assistantEchoMessage, assistantTextMessage } from "./model-specs.mjs"
42
+ export { specForModel, providerSpec, providerSpecResolution, specMatch, formatContextK, assistantEchoMessage, assistantTextMessage }
43
+ // 有效思考模式的单点判定住 `think-off.mjs`(与 `thinkOffPath` 同档:off 形族与 off 路径本是一件事)。
44
+ // 转口给核内五个构造点调用方——`isThinkingRequest` 只有一个所有者,本档不复制判据。
45
+ import { isThinkingRequest } from "./think-off.mjs"
46
+ export { isThinkingRequest }
42
47
  // 上下文解析链的取值校验单点(PROVIDER.md §6.15):装载归一与读面共用一个谓词。
43
48
  import { positiveInt, warnContextOnce } from "./model-context.mjs"
44
49
 
45
50
 
46
- // Window utilization ratio (CONTEXT-COMPACTION.md §6.2 / D-CC30 / §6.17 / D-CC32): auto threshold =
47
- // min(usableWindow(window, reserve), ⌊window × COMPACT_RATIO⌋) — reserve is the output budget
48
- // ACTUALLY sent as max_tokens (uncapped; §6.17 requestBudget is the single source). Rows with
49
- // reserve < 40% of the window land on the ratio term (line = 60.0% of the window); larger
50
- // reservations pull the line down to window − reserve — overflow-free outranks the ratio (the two
51
- // are mathematically exclusive once reserve ≥ 40%, §6.2). Headroom above the line absorbs injected
52
- // context (directory tree, git context, outline, project instructions, memory/doc search — 30–50K).
53
- const COMPACT_RATIO = 0.6
54
-
55
- /** Output reservation counted against the window: the value ACTUALLY sent as max_tokens —
56
- * explicit `provider.maxTokens` when set (the transport faces send it verbatim), else the spec
57
- * `maxOutput`, else 0. NOT capped: the old 25% cap reopened a residual band between the counted
58
- * reservation and the real output budget — messages could cross the true window while still below
59
- * the compaction line (2026-10-18 overflow 400: budget counted 250_000, 393_216 actually sent).
60
- * Single source = §6.17 requestBudget; this is its reserve face (advisor budget reuses it). */
61
- export function outputReserve(provider, spec) {
62
- const explicit = provider?.maxTokens
63
- return Number.isFinite(explicit) && explicit > 0 ? explicit : spec?.maxOutput ?? 0
64
- }
65
-
66
- /** Usable input window = window − output reservation. Degenerate guard: a reservation
67
- * ≥ the window is non-physical (no input could ever fit — e.g. `doubao-seed-2-1-turbo-260628`:
68
- * 256_000 window / 256_000 `maxOutput` (官方口径) ∥ the test harness&apos;s 1K window vs the
69
- * default spec); collapsing the budget to 0 would be instant `context_limit` death — the very
70
- * failure the reservation fold exists to prevent. Fall back to half the window.
71
- * (2026-10-06——收口核验捕获:advisor-loop-split B5a 红。) */
72
- export function usableWindow(context, reserve) {
73
- const ctx = context ?? 0
74
- const usable = ctx - reserve
75
- return usable > 0 ? usable : Math.floor(ctx / 2)
76
- }
77
-
78
- /** Request budget — single source for window ∥ actually-sent max_tokens ∥ compaction threshold ∥
79
- * overflow guard (CONTEXT-COMPACTION.md §6.17 / D-CC32). One formula, four consumer faces:
80
- * threshold (resolveCompactThreshold / per-run setup), the four transport faces (read ONLY
81
- * maxTokens), the stats budget line (agent-tools/context.mjs), the pre-send guard
82
- * (agent/run-stages.mjs). transport derives from provider.format ("anthropic" | "google" |
83
- * "responses" | default = OpenAI-compatible). Fields:
84
- * - window / windowSource: spec.context (the §6.15 chain — modelContext / legacy context /
85
- * /models self-report / static table / default — already resolved by providerSpec);
86
- * source = providerSpecResolution(provider).source — closed set { modelContext |
87
- * provider-override | list | spec | default }, passed through verbatim (no class merging).
88
- * - maxTokens / maxTokensSource: the value THIS transport writes into the request body —
89
- * anthropic always sends it (explicit ?? spec.maxOutput); the other three faces send only an
90
- * explicit provider.maxTokens, absent ⇒ undefined / "absent". Never a guard criterion
91
- * (undefined ⇒ NaN — §6.17 guard); the guard reads limit instead.
92
- * - reserve: maxTokens ?? spec.maxOutput — uncapped, always a number.
93
- * - usable: usableWindow(window, reserve) (degenerate half-window guard).
94
- * - threshold: min(usable, ⌊window × COMPACT_RATIO⌋) — the compaction trigger line.
95
- * - limit: window − reserve — hard prompt ceiling; the guard's ONLY numeric criterion field
96
- * (always a number; negative = any prompt overflows). `absent` rows (the transport sends no
97
- * max_tokens) take the floor max(window − reserve, threshold): only the degenerate
98
- * reserve ≥ window rows move (bare value 0 ⇒ every prompt would be rejected), and for
99
- * reserve < window threshold ≤ usable = window − reserve makes the floor a no-op. */
100
- export function requestBudget(provider, spec) {
101
- // windowSource = 五级链的同一次遍历出口(§6.15)——L1 / L3 命中也会如实报来源,不再二值猜。
102
- // 调用方传 spec(core.mjs 已算过 providerSpec)时窗口值用它,来源仍读 resolution(恒等映射,不并类)。
103
- const resolution = providerSpecResolution(provider)
104
- const resolved = spec ?? resolution.spec
105
- const window = resolved?.context ?? 0
106
- const windowSource = resolution.source
107
- const explicitRaw = Number(provider?.maxTokens)
108
- const explicit = Number.isFinite(explicitRaw) && explicitRaw > 0 ? explicitRaw : undefined
109
- const anthropicAlwaysSends = provider?.format === "anthropic"
110
- const maxTokens = explicit ?? (anthropicAlwaysSends ? resolved?.maxOutput ?? 0 : undefined)
111
- const maxTokensSource = explicit != null ? "explicit" : anthropicAlwaysSends ? "spec" : "absent"
112
- const reserve = maxTokens ?? resolved?.maxOutput ?? 0
113
- const usable = usableWindow(window, reserve)
114
- const threshold = Math.min(usable, Math.floor(window * COMPACT_RATIO))
115
- const bare = window - reserve
116
- return {
117
- window, windowSource, maxTokens, maxTokensSource, reserve, usable, threshold,
118
- // §6.17 地板:absent 档 reserve 可能 ≥ window(退化行,bare ≤ 0)——裸式下任何 prompt 都判真、
119
- // 该档永久发不出去;地板把它抬到 ≤ ⌊w/2⌋。非 absent 档逐位不变(仍是 bare)。
120
- limit: maxTokensSource === "absent" ? Math.max(bare, threshold) : bare,
121
- }
122
- }
123
-
124
- /** Derive compaction threshold; explicit is the value explicitly set in config file (takes priority),
125
- * otherwise auto = requestBudget().threshold (§6.17 single source — min(usable, ⌊window × 0.6⌋),
126
- * reserve uncapped). Second param accepts EITHER a model name string (pure spec lookup — compat shape,
127
- * no caller passes a string today) OR a provider object (providerSpec — the providers[].context
128
- * override in K units is honored, PROVIDER.md §15 T-C2). */
129
- export function resolveCompactThreshold(explicit, modelOrProvider) {
130
- if (explicit != null) return { value: explicit, auto: false }
131
- const provider = typeof modelOrProvider === "string" ? { model: modelOrProvider } : (modelOrProvider ?? {})
132
- return { value: requestBudget(provider).threshold, auto: true }
133
- }
51
+ // 预算族(`outputReserve` ∥ `usableWindow` ∥ `requestBudget` ∥ `policyBudget` ∥ `effectiveWindow` ∥
52
+ // `resolveCompactThreshold` ∥ `COMPACT_RATIO` ∥ 两个注入余量常量)居 `window-policy.mjs`——`CONTEXT-COMPACTION.md` §2.1 ∥
53
+ // §2.2 把「窗口事实」与「窗口策略」两件事分开,本档越 500 行硬限按设计给的候选线抽出;以下 re-export
54
+ // 保既有导入面(同 `model-specs.mjs` 拆分形态)。`resolveCompactThreshold` 在本档装载期自用
55
+ // (auto 档派生 `compactThresholdResolved`——按在用渠道的模型窗口现算),故先 import 再转口。
56
+ import { nonNegativeIntValue, resolveCompactThreshold } from "./window-policy.mjs"
57
+ export {
58
+ COMPACT_RATIO, INJECT_HEADROOM_MAX_TOKENS, INJECT_HEADROOM_RATIO, effectiveWindow, outputReserve, usableWindow, requestBudget, policyBudget, resolveCompactThreshold,
59
+ } from "./window-policy.mjs"
134
60
 
135
61
  /**
136
62
  * Bailian (阿里云百炼) host check — enable_thinking is a Bailian-only extension parameter;
@@ -142,7 +68,7 @@ export function isBailianHost(baseURL) {
142
68
  }
143
69
 
144
70
  /**
145
- * Resolve the Bailian `enable_thinking` switch for qwen hybrid-thinking models (PROVIDER.md §12).
71
+ * Resolve the Bailian `enable_thinking` switch for qwen hybrid-thinking models (`docs/core/design/PROVIDER.md` §6.12).
146
72
  * qwen3.x on Bailian defaults to thinking ON, so an explicit off must send enable_thinking:false
147
73
  * or the server silently keeps thinking. Whitelist: model name starts with "qwen" (excluding the
148
74
  * non-thinking qwen3-coder line) AND the provider points at a Bailian host.
@@ -160,7 +86,7 @@ export function resolveEnableThinking(provider, spec) {
160
86
  if (!isBailianHost(provider?.baseURL)) return undefined
161
87
  // 一致性分支(#1659):effort 档位有值且非 "none" ⇒ effort 赢(thinking on)。
162
88
  // 百炼约束:enable_thinking:false 时 reasoning_effort 必须为 "none",互斥即 400。
163
- // 压缩下行(context.mjs:203)显式 thinking:null 但继承 effort(v3 同源裁定)——
89
+ // 压缩下行(context.mjs 的 compressIfNeeded)显式 thinking:null 但继承 effort(v3 同源裁定)——
164
90
  // 无此分支则发出 {enable_thinking:false, reasoning_effort:"medium"} ⇒ 400 ⇒ 压缩三连败。
165
91
  if (provider.reasoningEffort && provider.reasoningEffort !== "none") return true
166
92
  if (provider.thinking === null) return false
@@ -169,17 +95,33 @@ export function resolveEnableThinking(provider, spec) {
169
95
  }
170
96
 
171
97
  // 加载期归一 / 清洗纯函数族已迁 `config-normalize.mjs`(§6.16.9 —— C1)——四个公共函数经本档
172
- // re-export 保持既有导入面;其余四个(sanitizeProviderHeaders ∥ sanitizeConsultModels ∥ 两枚
173
- // 一次性警告旗)只由 loadConfig 消费。
98
+ // re-export 保持既有导入面;其余六个(sanitizeProviderHeaders ∥ sanitizeConsultModels ∥
99
+ // isUsableProviderEntry ∥ providerDropReason ∥ 两枚一次性警告旗)只由 loadConfig 消费
100
+ // (`reloadProviders` 经 loadConfig 共用同一次判定,本档只转交,不另调)。
174
101
  import {
175
102
  sanitizeConsultModels, warnConsultModelsFiltered, sanitizeSubagentModel, sanitizeSubagentModels,
176
- warnSubagentModelsFiltered, sanitizeProviderHeaders, normalizeProxy, normalizeTeamSection,
103
+ warnSubagentModelsFiltered, sanitizeProviderHeaders, normalizeProxy, normalizeTeamSection, isUsableProviderEntry, providerDropReason,
177
104
  } from "./config-normalize.mjs"
178
105
  export { sanitizeSubagentModel, sanitizeSubagentModels, normalizeProxy, normalizeTeamSection }
179
106
 
180
107
  /** Module-level one-time warn dedupe for invalid providers[].context (PROVIDER.md §15 D-C1). */
181
108
  const warnedContextProviders = new Set()
182
109
 
110
+ /**
111
+ * 计数值配置键的装载期一次性告警(§1「保留窗与跨轮清理」∥ §2.2):去重键 = 键名,一个进程内同一个键只响一条。
112
+ * 报文点名键名、取值与该项的缺省语义——读的人要能据此改对文件,而不是只被告知「有一个值不对」。
113
+ * 只报不管:清键由调用点做(那一处才知道该键的缺省语义落到哪个值上),本函数不碰配置对象。
114
+ */
115
+ const warnedConfigCounts = new Set()
116
+ function warnConfigCountOnce(key, raw) {
117
+ if (warnedConfigCounts.has(key)) return
118
+ warnedConfigCounts.add(key)
119
+ const semantics = key === "compactThreshold"
120
+ ? "留空或 0 = 按当前窗口派生压缩线"
121
+ : "留空或 0 = 全部轮次保留"
122
+ console.warn(`[config] agent.${key} must be a non-negative integer — got ${JSON.stringify(raw)} — ignored: ${semantics}`)
123
+ }
124
+
183
125
  /**
184
126
  * Find provider by name in providers[].
185
127
  * Throws if name is non-empty but not found — a typo in the caller-supplied name (e.g. `defaultModel`) silently falling to the first provider would use the wrong key on the wrong endpoint.
@@ -209,6 +151,17 @@ export function promoteAgentViews(config) {
209
151
  return config
210
152
  }
211
153
 
154
+ /**
155
+ * 丢弃记录一句一条(`docs/core/design/PROVIDER.md` §6.29「丢弃要看得见」):`providers[18]: null`。
156
+ * 只有盘上下标 + 原因闭集四值之一——**绝不带条目内容**:载体是数据层,会进日志 ∥ 报错 ∥ 调试输出,
157
+ * 一条「有 apiKey 却缺 name」的条目若取 JSON,`sk-…` 就原样写进不需要它的地方。原因由
158
+ * `providerDropReason`(`thincoder-core/config-normalize.mjs`)给出——与准入判据同源,同一条目不会
159
+ * 在这里和装载分支各判出一种说法;下标让用户能找到要改的那一条。
160
+ */
161
+ function providerDropLine(index, reason) {
162
+ return `providers[${index}]: ${reason}`
163
+ }
164
+
212
165
  /**
213
166
  * Load configuration.
214
167
  * No env-var overrides — config.json is the single source of truth
@@ -237,13 +190,28 @@ export function loadConfig() {
237
190
  }
238
191
  }
239
192
 
193
+ // 渠道条目准入过滤(`docs/core/design/PROVIDER.md` §6.29):无名条目不进使用面——`name` 是渠道
194
+ // 唯一句柄(findProvider ∥ parseModelRef ∥ 会话槽 ∥ 选择器全按 name 匹配),无名条目既不可寻址
195
+ // 也不可被发送,留着只会让读它的地方失真:`/model` 的 `${p.name.padEnd(12)}` 直接抛
196
+ // `Cannot read properties of undefined (reading 'padEnd')`,19 个正常渠道被 1 条空条目连累。
197
+ // 过滤在整表别名 `merged.providersList = merged.providers` **之前**:别名之后没有第二个汇聚点,
198
+ // 漏一处就留一条不可寻址的条目在运行面。判据单源 = `isUsableProviderEntry`(装载 ∥ 重读共用)。
199
+ // 盘面处置 = 不重写被丢弃的那条(同节「零写盘」:它可能携用户已填的 apiKey ∥ baseURL)。
200
+ // 丢弃记录只写盘上下标 + 原因闭集(条目内容不进载体——载体是数据层,会进日志与调试输出)。
201
+ const droppedProviders = []
202
+ const providers = Array.isArray(config.providers)
203
+ ? config.providers.flatMap((p, index) => {
204
+ if (isUsableProviderEntry(p)) return [sanitizeProviderHeaders({ ...p })]
205
+ droppedProviders.push(providerDropLine(index, providerDropReason(p)))
206
+ return []
207
+ })
208
+ : []
209
+
240
210
  const merged = {
241
211
  ...DEFAULTS,
242
212
  ...config,
243
213
  defaultModel: typeof config.defaultModel === "string" && config.defaultModel.trim() ? config.defaultModel : null,
244
- providers: Array.isArray(config.providers)
245
- ? config.providers.map((p) => sanitizeProviderHeaders({ ...p }))
246
- : [],
214
+ providers,
247
215
  agent: { ...DEFAULTS.agent, ...config.agent },
248
216
  memory: { ...DEFAULTS.memory, ...config.memory },
249
217
  embedding: { ...DEFAULTS.embedding, ...config.embedding },
@@ -252,6 +220,17 @@ export function loadConfig() {
252
220
  diagnostics: { ...DEFAULTS.diagnostics },
253
221
  }
254
222
 
223
+ // Work mode is normalized from the raw input: a valid mode wins; legacy engineering is read
224
+ // only when mode is absent. The old boolean remains a derived runtime view, never a second authority.
225
+ merged.agent.mode = resolveWorkMode(config.agent)
226
+ merged.agent.engineering = merged.agent.mode === "engineering"
227
+
228
+ // 丢弃要看得见(同节「丢弃要看得见 · 数据面载体」):载体只在有丢弃时有值(无丢弃 ⇒ undefined,
229
+ // 与 `[]` 同义)。一条一句挂数据层;出词归消费面——本批唯一消费方 = `/model` L1 列表首行
230
+ // (`thincoder-cli/src/tui/provider-entries.mjs`),故不走 console。无条件写一次:载体是派生值,
231
+ // 而 `merged` 先摊平了盘上原文(`...config`),条件赋值会把盘上手写的同名键原样放进数据层。
232
+ merged.providersDropped = droppedProviders.length ? droppedProviders : undefined
233
+
255
234
  // 家目录展开(第 29 批):config 路径字段单一规范化点——只读归一(磁盘原文保留)
256
235
  merged.memory.dbPath = expandHome(merged.memory.dbPath)
257
236
  merged.memory.projectDir = expandHome(merged.memory.projectDir)
@@ -353,24 +332,41 @@ export function loadConfig() {
353
332
  ? null
354
333
  : plan.reason ?? defaultModelReason(merged.providers, merged.defaultModel)
355
334
 
356
- // Compaction threshold 三档落值(CONTEXT-COMPACTION.md §6.17):数值在场 = 显式(原样,不猜来源);
357
- // 不在场 = auto——派生值只进 compactThresholdResolved,永不写 agent.compactThreshold、不落盘。
358
- const explicitThreshold = config.agent?.compactThreshold
359
- if (explicitThreshold != null) {
360
- merged.agent.compactThreshold = explicitThreshold
361
- merged.agent.compactThresholdResolved = explicitThreshold
362
- merged.agent.compactThresholdAuto = false
335
+ // Compaction threshold 三档落值(CONTEXT-COMPACTION.md §2.2):过同一个取值域谓词与同一个解析函数——
336
+ // 「显式」= 有限正数。正数 ⇒ 原样落 `compactThreshold`;0 ∥ 缺省 ∥ 手改的非法值 ⇒ auto 支,
337
+ // 键清出内存镜像(`delete`,与下面 `keepToolTurns` 同一做法),派生值只进 `compactThresholdResolved`、不落盘。
338
+ // 非法值(负数 ∥ 小数 ∥ 非数字)与 0 在内存镜像里同形(键不存 + `auto: true`),另告警一条点名键与取值:
339
+ // 磁盘上的 0 是用户的选择,磁盘上的 -1 是笔误,两者取值相同但只有后者该被说出来。
340
+ const rawThreshold = config.agent?.compactThreshold
341
+ const thresholdValue = nonNegativeIntValue(rawThreshold)
342
+ const thresholdResolved = resolveCompactThreshold(thresholdValue, merged.provider)
343
+ if (thresholdResolved.auto) delete merged.agent.compactThreshold
344
+ else merged.agent.compactThreshold = thresholdResolved.value
345
+ merged.agent.compactThresholdResolved = thresholdResolved.value
346
+ merged.agent.compactThresholdAuto = thresholdResolved.auto
347
+ if (rawThreshold != null && rawThreshold !== "" && thresholdValue === null) warnConfigCountOnce("compactThreshold", rawThreshold)
348
+
349
+ // 保留窗宽(CONTEXT-COMPACTION.md §1「保留窗与跨轮清理」):合法值归一成数字写回内存镜像,一个字节不动磁盘;
350
+ // 空值(缺省 ∥ `null` ∥ 空串)= 全部轮次保留,键不进镜像;非法值(负数 ∥ 小数 ∥ 非数字)清出镜像并按缺省
351
+ // 语义取值(0 = 全部保留),同一条一次性告警。进程不因手改文件的笔误被挡在门外。
352
+ const rawKeep = config.agent?.keepToolTurns
353
+ if (rawKeep == null || rawKeep === "") {
354
+ delete merged.agent.keepToolTurns
363
355
  } else {
364
- merged.agent.compactThreshold = undefined
365
- merged.agent.compactThresholdResolved = resolveCompactThreshold(null, merged.provider).value
366
- merged.agent.compactThresholdAuto = true
356
+ const keep = nonNegativeIntValue(rawKeep)
357
+ if (keep === null) {
358
+ delete merged.agent.keepToolTurns
359
+ warnConfigCountOnce("keepToolTurns", rawKeep)
360
+ } else {
361
+ merged.agent.keepToolTurns = keep
362
+ }
367
363
  }
368
364
 
369
365
  // Write back to merged for convenient access by upper layers
370
366
  // fetch 超时可配置(2026-09-01:agent.fetchTimeoutMs——provider/core.mjs effectiveFetchTimeoutMs 消费)
371
367
  merged.provider.fetchTimeoutMs = Number.isFinite(merged.agent?.fetchTimeoutMs) && merged.agent.fetchTimeoutMs > 0
372
368
  ? merged.agent.fetchTimeoutMs : undefined
373
- // body 阶段空闲超时同形提升(TIMEOUT-DIGEST.md §2.1 —— provider/core.mjs effectiveBodyIdleMs 消费):
369
+ // body 阶段空闲超时同形提升(TIMEOUT-DIGEST.md §1.1 —— provider/core.mjs effectiveBodyIdleMs 消费):
374
370
  // 非法 ∥ 缺省 ⇒ undefined ⇒ 回退 DEFAULT_BODY_IDLE_MS(不静默禁用保护)
375
371
  merged.provider.bodyIdleTimeoutMs = Number.isFinite(merged.agent?.bodyIdleTimeoutMs) && merged.agent.bodyIdleTimeoutMs > 0
376
372
  ? merged.agent.bodyIdleTimeoutMs : undefined
@@ -380,6 +376,10 @@ export function loadConfig() {
380
376
  return merged
381
377
  }
382
378
 
379
+ // 运行中重读盘上渠道表本体居 `config-reload.mjs`(`docs/core/design/PROVIDER.md` §6.30)——本档已过
380
+ // 500 行后按设计指的候选线抽出,以下 re-export 保持既有导入面(同 config-io.mjs 拆分形态)。
381
+ export { reloadProviders } from "./config-reload.mjs"
382
+
383
383
  /**
384
384
  * MCP.md §5 D-3 (2026-09-01): re-read config.json and replace ONLY the agent's mcp section
385
385
  * — the agent 代配 closed loop (agent edits config.json with its edit tool, /mcp picks it
@@ -4,21 +4,49 @@
4
4
  * `shrinkOversized`(splitHistory 无中间段时的单条超限收缩)——迁出块逐字。
5
5
  * 原档 `context.mjs` 经 `export { … } from` 转口保名(消费面 / 单元测试档 import 面零改);
6
6
  * 跨档被引的原私有面(`shrinkOversized`)补 `export` 关键字。
7
+ *
8
+ * 2026-11-17(机读线按轮嵌套 · `docs/core/design/CONTEXT-COMPACTION.md` §1.1「读面」):两处编辑都量在
9
+ * 拍平视图上、写在结构上——`retentionWindowStart` 给的是位置 `{ turn, msg }`,本档换算一次拍平下标;
10
+ * 命中项直接改那一轮自己的内层元素(外层数组与内层数组的引用都不换)。
7
11
  */
8
- import { collectStaleToolOutputs } from "./token-window.mjs"
12
+ import { collectStaleToolOutputs, contextUsage, estimateTokens, rebaseMeasured, tokenRatioOf } from "./token-window.mjs"
13
+ // 保护尾跟着**有效窗口**走(`CONTEXT-COMPACTION.md` §2.1 / §4):有效窗口恒等于模型窗口,档位不是入参。
14
+ // 保留窗起点(#2431):prune 的合格集与压缩同一个切点——保留窗内那几轮的工具输出不被选中(§1.2)。
15
+ import { retentionWindowStart } from "./agent/turn-projection.mjs"
16
+ // 拍平投影与两向换算(写面单点档):本档只读投影、只改结构。
17
+ import { flattenHistory, flatIndexOf } from "./context-push.mjs"
9
18
 
10
19
  /** prune stub 逐字(§6.16.3):只给「已清理 + 原长度 + 重跑路径」——prune 是**删**不是摘要,不声称可复原。 */
11
20
  const pruneStub = (chars) => `[pruned: stale tool output dropped (${chars} chars) — re-run the tool if you need it again.]`
12
21
 
22
+ /** 保留窗起点 → 拍平下标(取不到 ⇒ 拍平条数 = 不收紧)。 */
23
+ function protectFromOf(agent, flat) {
24
+ const pos = retentionWindowStart(agent)
25
+ return pos ? flatIndexOf(agent.history, pos) : flat.length
26
+ }
27
+
28
+ /** 实测基线覆盖到的拍平下标(`_usageAt` 位置之后的消息从没被量过,减它们就是减错账)。 */
29
+ function measuredEndOf(agent, flat) {
30
+ return agent?._usageAt ? flatIndexOf(agent.history, agent._usageAt) : flat.length
31
+ }
32
+
13
33
  /**
14
34
  * 陈旧工具输出清理(F-CC3 · §6.16.3):合格集 = `token-window.mjs` 单源(保护尾外 ∧ `role:"tool"` ∧ ≥ 门槛);
15
- * 命中项**原位换「内容」**(`history[i] = { ...m, content: stub }`——数组引用 / 长度 / 索引 / `tool_call_id` 全不变
16
- * ⇒ 配对**结构上不可能被拆**)。记录面零改(copy-on-write:消息对象与人读线共享);基线失效同 `shrinkOversized` 先例。
35
+ * 命中项**原位换「内容」**(该轮内层那个元素换成 `{ ...m, content: stub }`——外层数组引用、内层条数、
36
+ * 顺序、`tool_call_id` 全不变 ⇒ 配对**结构上不可能被拆**)。记录面零改(copy-on-write:消息对象与人读线共享)。
37
+ * 基线按 §3.1 **重定,不归零**:原位替换 ⇒ `_usageAt` 位置原样,`_lastPromptTokens` 只扣那一截的估算差。
38
+ * `fixedOverhead` ∥ `ratio` 的来处 = §2.3 表(`contextUsage(agent, agent._ctxBasis?.overhead ?? {}).fixed − .compactionSummary` ·
39
+ * `tokenRatioOf(agent)`)——非对话面的底数只有 `fixed − compactionSummary` 一个。
17
40
  * @returns {{pruned:number, freed:number, candidates:number, tailKept:number, belowMin:number}}
18
41
  */
19
42
  export function pruneStaleToolOutputs(agent) {
20
- const history = agent.history
21
- const stale = collectStaleToolOutputs(history, agent.provider)
43
+ const flat = flattenHistory(agent.history)
44
+ // 非对话面底数 = `fixed − compactionSummary`(§2.3 表):与压缩链、`post` 同一个测度。
45
+ const usage = contextUsage(agent, agent?._ctxBasis?.overhead ?? {})
46
+ const stale = collectStaleToolOutputs(
47
+ flat, agent.provider, protectFromOf(agent, flat),
48
+ usage.fixed - usage.compactionSummary, tokenRatioOf(agent),
49
+ )
22
50
  const counts = {
23
51
  pruned: stale.indexes.length,
24
52
  freed: stale.tokens,
@@ -27,14 +55,27 @@ export function pruneStaleToolOutputs(agent) {
27
55
  belowMin: stale.belowMin,
28
56
  }
29
57
  if (counts.pruned === 0) return counts
30
- for (const i of stale.indexes) {
31
- const m = history[i]
32
- // 多模态 tool 结果(content 数组)整体替换为 stub ⇒ 图像 part 丢弃(不可再取——prune 是删;回执只给重跑路径)
33
- const chars = typeof m.content === "string" ? m.content.length : JSON.stringify(m.content ?? "").length
34
- history[i] = { ...m, content: pruneStub(chars) }
58
+ const measuredEnd = measuredEndOf(agent, flat)
59
+ const hits = new Set(stale.indexes)
60
+ let estBefore = 0
61
+ let estAfter = 0
62
+ let at = 0
63
+ for (const turn of agent.history) {
64
+ const messages = Array.isArray(turn?.messages) ? turn.messages : []
65
+ for (let k = 0; k < messages.length; k++, at++) {
66
+ if (!hits.has(at)) continue
67
+ const m = messages[k]
68
+ const before = at < measuredEnd ? estimateTokens([m]) : 0
69
+ // 多模态 tool 结果(content 数组)整体替换为 stub ⇒ 图像 part 丢弃(不可再取——prune 是删;回执只给重跑路径)
70
+ const chars = typeof m.content === "string" ? m.content.length : JSON.stringify(m.content ?? "").length
71
+ messages[k] = { ...m, content: pruneStub(chars) }
72
+ if (at < measuredEnd) {
73
+ estBefore += before
74
+ estAfter += estimateTokens([messages[k]])
75
+ }
76
+ }
35
77
  }
36
- agent._lastPromptTokens = null
37
- agent._usageAtLen = null
78
+ rebaseMeasured(agent, estBefore, estAfter, { inPlace: true })
38
79
  return counts
39
80
  }
40
81
 
@@ -45,37 +86,55 @@ const OVERSIZE_CONTENT_LIMIT = 8_000
45
86
  * Deterministic shrinking: last resort when splitHistory can't find a middle section (history too short) but threshold is exceeded. No LLM call.
46
87
  * Truncates user/tool message bodies exceeding OVERSIZE_CONTENT_LIMIT to a stub (keeps head + tail);
47
88
  * does not touch reasoning_content (DeepSeek/Kimi echo protocol) or tool_calls pairing structure — no protocol 400
48
- * risk from this path (this module's echo-safety face is `applyCompression`: the compaction placeholder is never
49
- * committed as a separate reasoning-less assistant next to another assistant — D-CC18, 2026-09-16 batch).
89
+ * risk from this path (this module's echo-safety face is `applyCompression`: the compaction summary now rides
90
+ * `agent._inject` and never lands on the machine line — D-CC18, 2026-09-16 batch).
50
91
  * Only called after compressIfNeeded determines threshold is exceeded. Returns whether any message was truncated.
92
+ *
93
+ * 射程止于保留窗起点之前(`CONTEXT-COMPACTION.md` §1.1 ∥ §4):`retentionWindowStart(agent)` 之后的
94
+ * 消息一条不改——保留窗承诺的那两轮工具过程原文逐字留着。取不到起点(等于拍平条数)时等于不收紧。
95
+ * 代价写明:那一轮离开前,一条超大消息可能让压缩无事可做,由越窗守卫如实报错(§4 的已知边界)。
51
96
  */
52
97
  export function shrinkOversized(agent, limit = OVERSIZE_CONTENT_LIMIT) {
98
+ const flat = flattenHistory(agent.history)
99
+ const protectFrom = protectFromOf(agent, flat)
53
100
  let shrunk = false
54
- // Copy-on-write: build a NEW array and replace only truncated entries. pushReal stores the SAME
101
+ const measuredEnd = measuredEndOf(agent, flat)
102
+ let estBefore = 0
103
+ let estAfter = 0
104
+ // Copy-on-write: replace only truncated entries. pushReal stores the SAME
55
105
  // message object in both `agent.history` (machine line) and `agent._fullHistory` (human/persistence
56
106
  // line), so in-place `m.content = ...` would ALSO truncate the never-compacted human line and lose
57
107
  // the original pasted content on session persist (session.mjs persists _fullHistory). VS Code port
58
108
  // already copies (`history.map(m => ({ ...m }))`); this brings CLI to parity.
59
- const next = agent.history.map((m) => {
60
- if ((m.role !== "user" && m.role !== "tool") || typeof m.content !== "string") return m
61
- if (m.content.length <= limit) return m
62
- // Truncate keeping head + tail, insert stub in between; keepHead/keepTail proportional but not exceeding 50%/25% of limit
63
- const keepHead = Math.min(Math.floor(limit * 0.5), 4000)
64
- const keepTail = Math.min(Math.floor(limit * 0.25), 2000)
65
- shrunk = true
66
- return {
67
- ...m,
68
- content:
69
- m.content.slice(0, keepHead) +
70
- `\n[... ${m.content.length - keepHead - keepTail} chars truncated — single message too large for context window ...]\n` +
71
- m.content.slice(-keepTail),
109
+ let at = 0
110
+ for (const turn of agent.history) {
111
+ const messages = Array.isArray(turn?.messages) ? turn.messages : []
112
+ for (let k = 0; k < messages.length; k++, at++) {
113
+ if (at >= protectFrom) continue
114
+ const m = messages[k]
115
+ if ((m.role !== "user" && m.role !== "tool") || typeof m.content !== "string") continue
116
+ if (m.content.length <= limit) continue
117
+ // Truncate keeping head + tail, insert stub in between; keepHead/keepTail proportional but not exceeding 50%/25% of limit
118
+ const keepHead = Math.min(Math.floor(limit * 0.5), 4000)
119
+ const keepTail = Math.min(Math.floor(limit * 0.25), 2000)
120
+ shrunk = true
121
+ const truncated = {
122
+ ...m,
123
+ content:
124
+ m.content.slice(0, keepHead) +
125
+ `\n[... ${m.content.length - keepHead - keepTail} chars truncated — single message too large for context window ...]\n` +
126
+ m.content.slice(-keepTail),
127
+ }
128
+ if (at < measuredEnd) {
129
+ estBefore += estimateTokens([m])
130
+ estAfter += estimateTokens([truncated])
131
+ }
132
+ messages[k] = truncated
72
133
  }
73
- })
134
+ }
74
135
  if (shrunk) {
75
- agent.history = next
76
- // Same as compaction: measured token baseline is invalidated by the changed history, fall back to estimation until next response
77
- agent._lastPromptTokens = null
78
- agent._usageAtLen = null
136
+ // 基线按 §3.1 **重定,不归零**:截断是原位替换(内层条数与顺序不变)⇒ `_usageAt` 位置原样。
137
+ rebaseMeasured(agent, estBefore, estAfter, { inPlace: true })
79
138
  }
80
139
  return shrunk
81
- }
140
+ }
package/context-echo.mjs CHANGED
@@ -1,14 +1,13 @@
1
1
  /**
2
2
  * context-echo.mjs — 回声安全面(D-CC18 ∥ D-CC19 恢复面归并 · 自 `context.mjs` 迁出 · 2026-10-01 core 拆分批 #755 ∥ #786)。
3
- * 内容 = `COMPACTION_PLACEHOLDER` ∥ 前缀器族(`prefixContent` / `withPlaceholderPrefix`)∥ 回声对归并
4
- * (`isAssistantEchoPair` / `contentTextOf` / `absorbEchoContent` / `mergeAdjacentAssistantEchoes`)——迁出块逐字。
5
- * 原档 `context.mjs` 经 `export { … } from` 转口保名(消费面 / 单元测试档 import 面零改);
6
- * 跨档被引的原私有面(`COMPACTION_PLACEHOLDER` ∥ `withPlaceholderPrefix`)补 `export` 关键字。
3
+ * 内容 = 前缀器 `prefixContent`(归并时把被吸收的那条文本接到下一条之前)∥ 回声对归并
4
+ * (`isAssistantEchoPair` / `contentTextOf` / `absorbEchoContent` / `mergeAdjacentAssistantEchoes`)。
5
+ * 原档 `context.mjs` 经 `export { … } from` 转口保名(消费面 / 单元测试档 import 面零改)。
6
+ *
7
+ * 压缩摘要不带任何固定文本(设计档 §6.1「压缩摘要的文本 = 摘要正文本身」):成功路径的压缩摘要就是摘要正文本身,
8
+ * 本档因此没有一条前缀常量,只剩回声归并一族。
7
9
  */
8
10
 
9
- /** Placeholder assistant reply committed right after compaction (D9); D-CC18 merges it into an adjacent tail assistant instead of emitting it as a separate message */
10
- export const COMPACTION_PLACEHOLDER = "Understood. I'll continue from these notes, re-verifying anything transient."
11
-
12
11
  /**
13
12
  * Content-shape-safe prefixing (D-CC18, generalized for D-CC19 merge reuse):
14
13
  * string → text + blank line + original; multimodal array → text part prepended;
@@ -20,14 +19,6 @@ function prefixContent(content, text) {
20
19
  return text
21
20
  }
22
21
 
23
- /**
24
- * D-CC18 echo safety: prefix the placeholder onto an existing assistant message's content.
25
- * Thin wrapper over prefixContent (behavioral semantics unchanged).
26
- */
27
- export function withPlaceholderPrefix(content) {
28
- return prefixContent(content, COMPACTION_PLACEHOLDER)
29
- }
30
-
31
22
  /**
32
23
  * D-CC19 restore-path echo merge (2026-09-16 ENGINE-DEBT 批 ED-1): persisted `contextHistory`
33
24
  * is loaded back VERBATIM on session restore, so the D-CC18 pathological shape (an assistant