@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
package/token-window.mjs CHANGED
@@ -4,24 +4,29 @@
4
4
  * 迁出三族(语义零改——原档越限在即,本批按 §6.16.8 拆出):① 计量面(IMAGE_TOKEN_ESTIMATE + `estimateTokens`);
5
5
  * ② 尾族(KEEP_HEAD 头注 + SUMMARY_TOKEN_ESTIMATE / TAIL_FLOOR_MESSAGES + `keepTailSize` + `tailBudgetTokens`);
6
6
  * ③ 切分与配对修复族(`splitHistory` + `repairedTailStart` + `tightenTailByBudget`)。
7
- * 新增族:`contextUsage`(与 `compressIfNeeded` 的 token 判定**同一函数**)· `historyReading` / `historyPercent`(状态行
8
- * 百分比——与 CLI ∥ VSC **同源**:一个实现点,端侧零自算式,消费面全是本档的投影)·
7
+ * 新增族:`faceEstimate`(非对话面六项与对话面的**唯一**估算点,§2.5)· `contextUsage`(整量:装配面六段,
8
+ * 与 `compressIfNeeded` 的 token 判定**同一函数**)· `contextReading`(整量读数单点:状态行 ∥ stats ∥ Desktop ∥
9
+ * VSC 四个有 agent 的面全读它)· `historyReading` / `historyPercent`(仅对话那一段的估算,
10
+ * 消费面只剩打开态与无 agent 转口)· `overheadSegments`(非对话面六项的分段读法,越线报文两处共用)·
9
11
  * `collectStaleToolOutputs`(陈旧工具输出合格集)+ 门槛常量 `PRUNE_MIN_TOKENS`(**与合格集同住本档** ⇒ 消费方单向取用、零回指)·
10
12
  * `rebaseMeasured`(结构编辑后的实测基线重定,§3.1)。
11
- * 窗口面(2026-11-14 · tiny 档上限批):本档一切窗口读数取**有效窗口** `effectiveWindow`(`window-policy.mjs` §2.1),
12
- * 不再直读 `providerSpec().context`——`workMode` 无缺省(本档的窗口消费入口 `keepTailSize` ∥ `tailBudgetTokens` ∥
13
- * `historyReading` ∥ `historyPercent` 各自拒收,`collectStaleToolOutputs` 透传同一拒绝;必填清单的单一出处 = §2.3)。
13
+ * 窗口面(2026-11-14 · tiny 档上限批;2026-11-21 · 本批):本档一切窗口读数取**有效窗口** `effectiveWindow`
14
+ * (`window-policy.mjs` §2.1),不再直读 `providerSpec().context`——有效窗口恒等于模型窗口,档位不是入参
15
+ * (本档的窗口消费入口 `keepTailSize` ∥ `tailBudgetTokens` ∥ `historyReading` ∥ `historyPercent` 都只收 provider,
16
+ * `collectStaleToolOutputs` 同形;必填清单的单一出处 = §2.3)。
14
17
  * 保留窗面(2026-11-14 · tool-output-retention 批):`splitHistory` 的第四参 `protectFrom` 必填、无缺省——尾起点不晚于
15
18
  * 保留窗起点,压缩中段 ∥ prune 合格集 ∥ 尾部预算三面同源受益(`CONTEXT-COMPACTION.md` §1.2);起点由 `agent` 面的
16
19
  * `retentionWindowStart` 按消息身份当刻解析,本档只收这个下标(纯函数面不读 agent 状态)。
17
20
  * 尾预算面(2026-11-15 · window-reserve-and-baseline 批):`tailBudgetTokens` 由窗口比例改为**可用容量减法链**(§4)——
18
21
  * 尾的宽度从压缩线倒推,不取窗口的比例。
19
- * 依赖面 = `provider/rate.mjs`(`estimateText` / `ESTIMATOR_VERSION`)+ `config.mjs`(`resolveWorkMode` ∥ 有效窗口 ∥
20
- * 预算族转口)+ `context-echo.mjs`(压缩注记那对固定文本,`NOTE_ESTIMATE` 量它)——**零 import 环**。
22
+ * 依赖面 = `provider/rate.mjs`(`estimateText` / `ESTIMATOR_VERSION`)+ `config.mjs`(有效窗口 ∥
23
+ * 预算族转口)+ `context-push.mjs`(拍平投影与位置换算两向)——`context-push.mjs` 不回头 import 本档,
24
+ * **零 import 环**(压缩摘要不再带固定文本,本档因此不再 import `context-echo.mjs`)。
21
25
  */
22
26
  import { estimateText, ESTIMATOR_VERSION } from "./provider/rate.mjs"
23
- import { resolveWorkMode, effectiveWindow, resolveCompactThreshold, policyBudget } from "./config.mjs"
24
- import { COMPACTION_PREFIX, COMPACTION_PLACEHOLDER } from "./context-echo.mjs"
27
+ import { effectiveWindow, resolveCompactThreshold, policyBudget } from "./config.mjs"
28
+ // 拍平投影与位置换算(两向同住一档)——本档的读数、切点与基线重定都在拍平视图上算,位置只在结构上取。
29
+ import { flattenHistory, flatIndexOf, positionOf, INJECT_SLOTS } from "./context-push.mjs"
25
30
 
26
31
  const IMAGE_TOKEN_ESTIMATE = 2000 // rough estimate for image content tokens (CLI legacy 256 underestimated real image costs, delaying compaction)
27
32
 
@@ -51,37 +56,34 @@ const KEEP_HEAD = 0 // No dedicated head: earliest messages may be a COMPLETED e
51
56
  // at 40% of history; §6.4④ D-T1/D-T2 make the count only a CANDIDATE — the token budget
52
57
  // (`tailBudgetTokens`, §4) tightens it over pair-safe boundaries when compaction runs, never below
53
58
  // TAIL_FLOOR_MESSAGES; ordinary sessions never reach it (D-T4: the trigger line is §2.2's).
54
- export const SUMMARY_TOKEN_ESTIMATE = 1000 // §6.9: summary output target ~1K tokens — §6.17 可达性门的 `note` 项同取本常量
59
+ export const SUMMARY_TOKEN_ESTIMATE = 1000 // §6.9: summary output target ~1K tokens —— 压缩摘要的预留额同取本常量
55
60
  const TAIL_FLOOR_MESSAGES = 10 // §6.4④ D-T2: the tail keeps ≥10 verbatim messages — floor beats budget
56
61
 
57
- /** 注记 + 占位的估算(§4 减法链的末项,也是 §6.17 可达性门的 `note` 项):摘要正文取
58
- * `SUMMARY_TOKEN_ESTIMATE`(§6.9 的 ~1K 目标),注记前缀与占位句按 §6.3 估算式——
59
- * 零新常数、零新算式。两个固定文本的单源 = `context-echo.mjs`。 */
60
- export const NOTE_ESTIMATE = SUMMARY_TOKEN_ESTIMATE + estimateTokens([
61
- { role: "user", content: COMPACTION_PREFIX },
62
- { role: "assistant", content: COMPACTION_PLACEHOLDER },
63
- ])
62
+ /** 压缩摘要的估算(§4 减法链的末项,也是可达性门的 `compactionSummary` 项):只剩摘要正文这一项,取值即
63
+ * `SUMMARY_TOKEN_ESTIMATE`(§6.9 的 ~1K 目标)。两个量说的是两件事——摘要写多长 · 压缩摘要在请求面上占多少,
64
+ * 只是当前取值重合(设计档 §6.1「压缩摘要的文本 = 摘要正文本身」:成功路径的压缩摘要不带任何固定文本)。 */
65
+ export const COMPACTION_SUMMARY_TOKEN_ESTIMATE = SUMMARY_TOKEN_ESTIMATE
64
66
 
65
67
  /** 必填数值参数(§2.3 缺参即拒):无缺省,非法值在入口拒绝并点名参数。
66
68
  * `fixedOverhead` 缺省等于把「这份 run 的固定开销」静默定成 0,尾会按一个装不下的量去切;
67
69
  * `ratio` 缺省等于把校准后的阈值和未校准的估算放进同一次减法。 */
68
70
  function assertTailArgs(fnName, fixedOverhead, ratio) {
69
71
  if (!Number.isFinite(fixedOverhead) || fixedOverhead < 0) {
70
- throw new Error(`${fnName}: \`fixedOverhead\` is required (system + tools token estimate, no default) — got ${JSON.stringify(fixedOverhead)}`)
72
+ throw new Error(`${fnName}: \`fixedOverhead\` is required (the non-conversation face minus the compaction-summary slot, i.e. \`fixed − compactionSummary\`, no default) — got ${JSON.stringify(fixedOverhead)}`)
71
73
  }
72
74
  if (!Number.isFinite(ratio) || ratio <= 0) {
73
75
  throw new Error(`${fnName}: \`ratio\` is required (the calibration ratio from tokenRatioOf, no default) — got ${JSON.stringify(ratio)}`)
74
76
  }
75
77
  }
76
78
 
77
- export function keepTailSize(provider, historyLen, workMode) {
79
+ export function keepTailSize(provider, historyLen) {
78
80
  // provider is guaranteed at every call site (runAgent always builds one); the window below
79
- // degrades to DEFAULT_SPEC (128K) only if provider is somehow absent — acceptable
81
+ // degrades to DEFAULT_SPEC (256K) only if provider is somehow absent — acceptable
80
82
  // because the 40% history cap still bounds the tail. providers[].context override
81
83
  // (K units) is honored here (PROVIDER.md §6.15 T-C2: tail formula follows the window).
82
- // 窗口 = **有效窗口**(§2.1/§4):tiny 把窗口压小,尾部跟着变短,不另立一套尾部规则。
84
+ // 窗口 = **有效窗口**(§2.1/§4)——它恒等于模型窗口,档位不参与(tiny 不再压窗口)。
83
85
  // 它是**条数上限**,不是预算:一条消息的体量跨三个数量级,条数推不出容量(§4)。
84
- const ctxWindow = effectiveWindow(provider, workMode)
86
+ const ctxWindow = effectiveWindow(provider)
85
87
  return Math.min(Math.max(10, Math.floor((ctxWindow / 100_000) * 30)), Math.floor(historyLen * 0.4))
86
88
  }
87
89
 
@@ -89,21 +91,22 @@ export function keepTailSize(provider, historyLen, workMode) {
89
91
  * 尾预算(§4)——可用容量倒推,不由窗口比例决定:
90
92
  *
91
93
  * ```text
92
- * tailBudgetTokens(provider, workMode, fixedOverhead, ratio)
93
- * = max(0, floor(threshold / ratio) − fixedOverhead − SUMMARY_TOKEN_ESTIMATE − 注记与占位估算)
94
+ * tailBudgetTokens(provider, fixedOverhead, ratio)
95
+ * = max(0, floor(threshold / ratio) − fixedOverhead − SUMMARY_TOKEN_ESTIMATE)
94
96
  * ```
95
97
  *
96
- * `threshold` 取 §2.2 的压缩线(有效窗口上现推),`fixedOverhead` = system + tools 的估算,
97
- * `ratio` = 校准比(`tokenRatioOf`),末两项合并即 `NOTE_ESTIMATE`。
98
+ * `threshold` 取 §2.2 的压缩线(有效窗口上现推),`fixedOverhead` = 非对话面六项扣掉压缩摘要格(`fixed − compactionSummary`),
99
+ * `ratio` = 校准比(`tokenRatioOf`)。减掉的这一项就是压缩摘要:成功路径的它不带固定文本(§6.1),
100
+ * 只剩摘要正文一项,取值即 `SUMMARY_TOKEN_ESTIMATE`;`COMPACTION_SUMMARY_TOKEN_ESTIMATE` 仍供 `post` 与 `fixedFloor` 用(§2.5)。
98
101
  * 减法链把「压完之后落在 `threshold` 以下」写成构造而不是事后检查:压后的量是
99
- * `(tail + 注记 + 固定开销) × ratio`,尾按上式取,它就落在 `threshold` 以内。
102
+ * `(tail + 压缩摘要 + 固定开销) × ratio`,尾按上式取,它就落在 `threshold` 以内。
100
103
  * 乘除 `ratio` 是必需的:`threshold` 是校准后的量,尾的估算要换到同一把尺上才可比。
101
104
  * `fixedOverhead` ∥ `ratio` 都必填无缺省(§2.3)。
102
105
  */
103
- export function tailBudgetTokens(provider, workMode, fixedOverhead, ratio) {
106
+ export function tailBudgetTokens(provider, fixedOverhead, ratio) {
104
107
  assertTailArgs("tailBudgetTokens", fixedOverhead, ratio)
105
- const threshold = policyBudget(provider, undefined, workMode).threshold
106
- return Math.max(0, Math.floor(threshold / ratio) - fixedOverhead - SUMMARY_TOKEN_ESTIMATE - (NOTE_ESTIMATE - SUMMARY_TOKEN_ESTIMATE))
108
+ const threshold = policyBudget(provider).threshold
109
+ return Math.max(0, Math.floor(threshold / ratio) - fixedOverhead - SUMMARY_TOKEN_ESTIMATE)
107
110
  }
108
111
 
109
112
  /**
@@ -191,40 +194,160 @@ function tightenTailByBudget(history, start, floorStart, budgetTokens) {
191
194
  }
192
195
 
193
196
  /**
194
- * 上下文用量单源(§6.16.4「取自哪里」)——与 `compressIfNeeded` 的 token 判定**同一函数**:实测优先 =
195
- * `_lastPromptTokens + 增量(history.slice(_usageAtLen))`;无实测 = `estimateTokens(history) + system + tools`(固定开销面经 extras 随带)。
196
- * `threshold` = 该回合检查所用值(`agent._ctxBasis.threshold`——核 `agent.mjs` / VSC `checkAndCompact` 各一处暂存);缺省回退 `resolveCompactThreshold`(退化面①)。
197
- * `window` = **有效窗口** `effectiveWindow(agent.provider, 当前档)`(§2.1)——tiny 档下它就不是模型窗口了,
198
- * 而这个值就是 stats 首行百分比 ∥ `Segments` 行的分母;模式自 `agent.config` 现取(agent 在场,不靠参数透传)。
199
- * `fixedFloor` = 固定开销按当前估算比缩放(与 `total` 的估算支同一把尺)——固定开销单独越过 `limit` 的判据面
200
- * (`CONTEXT-COMPACTION.md` §5),两处消费:`enforceContextFit` 抛 typed error ∥ `compressIfNeeded` 的 `force` 支 no-op。
201
- * @returns {{basis:"measured"|"estimated", total, history, system, tools, overhead, fixedFloor, threshold, window}}
197
+ * 基线位置 → 拍平下标(实测支的后缀起点)。位置不成立(结构编辑漏了重定 §3.1)⇒ 取线尾,
198
+ * 与「基线为 null」同形:宁可少算后缀,也不把已计进真值的那一段再加一遍。
202
199
  */
203
- export function contextUsage(agent, extras = {}) {
204
- const history = Array.isArray(agent?.history) ? agent.history : []
200
+ function usageBaselineIndex(agent, flat) {
201
+ const pos = agent?._usageAt
202
+ if (!pos || typeof pos !== "object") return flat.length
203
+ try {
204
+ return flatIndexOf(agent.history, pos)
205
+ } catch {
206
+ return flat.length
207
+ }
208
+ }
209
+
210
+ /**
211
+ * 真值那一刻的非对话面估算(`_usageFixedBase`)的读侧唯一一处。
212
+ * 它与 `_lastPromptTokens` 同一个写点(`agent/turn-loop.mjs` 写真值的那一支)、同一批置 null 点;
213
+ * measured 支下缺它只可能是那个写点漏了,此时抛出并点名——不拿 0 顶上:拿 0 会把整个非对话面
214
+ * 再加一遍,正是 §2.5 要消灭的重复计数。
215
+ */
216
+ function usageFixedBaseOf(agent) {
217
+ const base = agent?._usageFixedBase
218
+ if (!Number.isFinite(base)) {
219
+ throw new Error("contextUsage: `_usageFixedBase` is missing while `_lastPromptTokens` is set — both are written at the same point (agent/turn-loop.mjs), and every null point clears both")
220
+ }
221
+ return base
222
+ }
223
+
224
+ /**
225
+ * 装配面六段里非对话面六项与对话面的**唯一**估算点(`CONTEXT-COMPACTION.md` §2.5)——
226
+ * 读数(`contextUsage`)与真值基线(`_usageFixedBase`)都从它取,不各自累加:
227
+ *
228
+ * ```text
229
+ * system = extras.systemPrompt 的估算 retained = agent._retained 各条目 message 的估算
230
+ * tools = extras.tools 的估算 inject = agent._inject 十格全部内容(compactionSummary 在它里面)
231
+ * pending = agent._pendingInject 的估算 sessionHead = agent._sessionHead 那一个字符串(未写过记 0)
232
+ * fixed = system + tools + retained + inject + sessionHead + pending
233
+ * history = 拍平线(对话面)的估算
234
+ * ```
235
+ *
236
+ * 五段(`retained` ∥ `inject` ∥ `sessionHead` ∥ `pending` ∥ `history`)由本函数自己从 agent 读,不经 extras;`extras` 必填、
237
+ * 无缺省——忘传即少算系统提示词与工具声明两段,读数偏低而看起来完全正常(与 §2.3 同一条纪律)。
238
+ * `compactionSummary` 是 `inject` 里压缩摘要那一格:压缩链先减掉它、再按 `COMPACTION_SUMMARY_TOKEN_ESTIMATE`
239
+ * 加回预留额,同一份不算两遍(§4 ∥ §5)。
240
+ */
241
+ export function faceEstimate(agent, extras) {
242
+ if (extras === undefined) {
243
+ throw new Error("faceEstimate: `extras` is required (no default) — pass agent?._ctxBasis?.overhead ?? {}")
244
+ }
205
245
  const system = extras.systemPrompt ? estimateText(extras.systemPrompt) : 0
206
246
  const tools = extras.tools ? estimateText(JSON.stringify(extras.tools)) : 0
207
- const overhead = system + tools
208
- const historyTokens = estimateTokens(history)
209
- const measured = agent?._lastPromptTokens != null
247
+ const retained = estimateTokens(
248
+ (Array.isArray(agent?._retained) ? agent._retained : []).map((e) => e?.message).filter(Boolean),
249
+ )
250
+ const slots = Array.isArray(agent?._inject) ? agent._inject : []
251
+ const inject = estimateTokens(slots.filter(Boolean))
252
+ const summarySlot = slots[INJECT_SLOTS.indexOf("compaction-summary")]
253
+ const compactionSummary = summarySlot ? estimateTokens([summarySlot]) : 0
254
+ const pending = estimateTokens((Array.isArray(agent?._pendingInject) ? agent._pendingInject : []).filter(Boolean))
255
+ // 会话头块(§2.5):不在 `_inject` 也不在 `_pendingInject`,却每条请求都在⇒不单算就是
256
+ // 「请求里在、读数里不在」(压缩判定偏晚、越窗守卫少算、状态行少报)。
257
+ const sessionHead = typeof agent?._sessionHead === "string" && agent._sessionHead ? estimateText(agent._sessionHead) : 0
258
+ const history = estimateTokens(flattenHistory(Array.isArray(agent?.history) ? agent.history : []))
259
+ return {
260
+ system,
261
+ tools,
262
+ retained,
263
+ inject,
264
+ compactionSummary,
265
+ pending,
266
+ sessionHead,
267
+ fixed: system + tools + retained + inject + sessionHead + pending,
268
+ history,
269
+ }
270
+ }
271
+
272
+ /**
273
+ * 非对话面六项的分段读法(`CONTEXT-COMPACTION.md` §2.5 的次序):越线报文两处共用——发送前守卫的 typed error
274
+ * (`provider/errors.mjs`)与 `context compact` 的 no-op 回执(`agent-tools/context.mjs`)。
275
+ * 六项的名字就是各自那一格的名字;`fixed` 是它们的和,不是第七段。字段缺了不补 0——报文里会印出
276
+ * `undefined`,比一个看起来正常的 0 更容易被发现。
277
+ */
278
+ export function overheadSegments(usage) {
279
+ return [
280
+ ["systemPrompt", usage?.system],
281
+ ["tools", usage?.tools],
282
+ ["_retained", usage?.retained],
283
+ ["_inject", usage?.inject],
284
+ ["_sessionHead", usage?.sessionHead],
285
+ ["_pendingInject", usage?.pending],
286
+ ]
287
+ }
288
+
289
+ /**
290
+ * 上下文用量单源(§2.5「显示与判定同基准」)——与 `compressIfNeeded` 的 token 判定**同一函数**:
291
+ *
292
+ * ```text
293
+ * 实测支 total = _lastPromptTokens
294
+ * + round(estimateTokens(_usageAt 之后的拍平线) × ratio)
295
+ * + round((fixed − _usageFixedBase) × ratio)
296
+ * 估算支 total = round((fixed + history) × ratio)
297
+ * fixedFloor = round(((fixed − compactionSummary) + COMPACTION_SUMMARY_TOKEN_ESTIMATE) × ratio)
298
+ * ```
299
+ *
300
+ * 整量 = 本回合请求的装配面(`faceEstimate` 的六段),与 `assembleRequestMessages` 拼出的那一条同面。
301
+ * 实测支的第二项补对话增量、第三项补非对话增量:压缩摘要落 `_inject` 的 `compaction-summary` 格、待发队进条目、编辑器上下文刷新,
302
+ * 改的都只是非对话面,不补就是读数比真实请求小一个量级;反过来无条件把 `fixed` 加上去,会把已含在真值里
303
+ * 的那一份算第二遍(常驻的压缩摘要接近一倍)。差可正可负。
304
+ * `fixedFloor` = 压掉全部对话后 `total` 的下界:压后非对话面 = `(fixed − compactionSummary) + COMPACTION_SUMMARY_TOKEN_ESTIMATE`,换成估算尺
305
+ * 即上式。§5.1 的 ②⑤⑦ 三道门、§4 的尾预算与 §5 的 `post` 都读这一个测度(定义只在 §2.5)。
306
+ * 压缩摘要按预留额计、不跟量到的 `compactionSummary` 走:那一格在「本会话还没压过」时为空、压过之后非空(重开一个压过的
307
+ * 会话时由槽里的检查点补回),两种状态都要为同一条压缩摘要留出同一份空间。
308
+ * 机读线按轮嵌套:一切计量在拍平视图上算(外层条数是轮数,不是消息数);基线位置是 `{ turn, msg }`。
309
+ * `threshold` = 该回合判定所用值(`agent._ctxBasis.threshold`——核 `agent.mjs` / VSC `checkAndCompact` 各一处暂存);
310
+ * 缺省回退 `resolveCompactThreshold`(退化面①)。
311
+ * `window` = **有效窗口** `effectiveWindow(agent.provider)`(§2.1)——它恒等于模型窗口,
312
+ * 而这个值就是 stats 首行百分比的分母(agent 在场,不靠参数透传)。
313
+ * `overhead` = `system + tools`(`fixed` 的子集,模型与参数预判面读它);压缩链读 `fixed − compactionSummary`,不读它。
314
+ * @returns {{basis:"measured"|"estimated", total, history, system, tools, retained, inject, compactionSummary, sessionHead, pending, fixed, overhead, fixedFloor, threshold, window}}
315
+ */
316
+ export function contextUsage(agent, extras) {
317
+ if (extras === undefined) {
318
+ throw new Error("contextUsage: `extras` is required (no default) — pass agent?._ctxBasis?.overhead ?? {}")
319
+ }
320
+ const face = faceEstimate(agent, extras)
210
321
  // §6.3 / §6.17 估算自校准:估算值乘 `_tokRatio`;`_lastPromptTokens` 是服务端真值,不乘。
211
322
  const ratio = tokenRatioOf(agent) // 取比单源(同下 `historyReading` 的第三参来源)
212
- // 档位只从 agent 现取(握有 agent 的面自己取模式,§2.3)——不存窗口位,不添第二个来源。
213
- const workMode = resolveWorkMode(agent?.config?.agent)
323
+ const measured = agent?._lastPromptTokens != null
324
+ let total
325
+ if (measured) {
326
+ const flat = flattenHistory(Array.isArray(agent?.history) ? agent.history : [])
327
+ const suffix = estimateTokens(flat.slice(usageBaselineIndex(agent, flat)))
328
+ total = agent._lastPromptTokens
329
+ + Math.round(suffix * ratio)
330
+ + Math.round((face.fixed - usageFixedBaseOf(agent)) * ratio)
331
+ } else {
332
+ total = Math.round((face.fixed + face.history) * ratio)
333
+ }
214
334
  return {
215
335
  basis: measured ? "measured" : "estimated",
216
- total: measured
217
- ? agent._lastPromptTokens + Math.round(estimateTokens(history.slice(agent._usageAtLen ?? history.length)) * ratio)
218
- : Math.round((historyTokens + overhead) * ratio),
219
- history: historyTokens,
220
- system,
221
- tools,
222
- overhead,
223
- // 固定开销单独越线的判据值(§5):与估算支同尺——压掉全部 history 后 total 只能落到这个量级。
224
- fixedFloor: Math.round(overhead * ratio),
336
+ total,
337
+ history: face.history,
338
+ system: face.system,
339
+ tools: face.tools,
340
+ retained: face.retained,
341
+ inject: face.inject,
342
+ compactionSummary: face.compactionSummary,
343
+ pending: face.pending,
344
+ sessionHead: face.sessionHead,
345
+ fixed: face.fixed,
346
+ overhead: face.system + face.tools,
347
+ fixedFloor: Math.round(((face.fixed - face.compactionSummary) + COMPACTION_SUMMARY_TOKEN_ESTIMATE) * ratio),
225
348
  threshold: agent?._ctxBasis?.threshold
226
- ?? resolveCompactThreshold(agent?.config?.agent?.compactThreshold, agent?.provider, workMode).value,
227
- window: effectiveWindow(agent?.provider, workMode),
349
+ ?? resolveCompactThreshold(agent?.config?.agent?.compactThreshold, agent?.provider).value,
350
+ window: effectiveWindow(agent?.provider),
228
351
  }
229
352
  }
230
353
 
@@ -293,22 +416,23 @@ function validSample(sample, provider) {
293
416
  }
294
417
 
295
418
  /**
296
- * 核读数(§6.16.4「与状态行 ctx% 的单源关系」· §2.5「显示与判定同基准」)——这个量**只有本函数一个实现点**,
297
- * 五处消费面全是它的投影:stats 第 6 行 · 打开态读数 · 桌面 `ev:usage` · VSC `specs.mjs` · CLI 状态行(经 `ctxCacheOf` 缓存)。
298
- * 一次读数出五个值(§2.5):`tokens` = 校准后的历史估算 `round(estimateTokens(history) × ratio)`;`window` / `limit` /
419
+ * 核读数(§6.16.4「与状态行 ctx% 的单源关系」)——**只量对话那一段**的行史估算,`.pct` 的消费面只剩两处(§2.5):
420
+ * 打开态读数(经 `historyPercent`)与无 agent 转口(VSC `specs.mjs` 的 `ctxUsageForHistory`)。
421
+ * 有 agent 的四个面(CLI 状态行 ∥ stats 第 6 行 ∥ Desktop `ev:usage` ∥ VSC 的 agent 面)一律读 `contextReading`——
422
+ * 它才是「整条请求」的量;本函数从此只回答「对话那一段大概多少」,不是状态行的分子。
423
+ * 一次读数出五个值:`tokens` = 校准后的历史估算 `round(estimateTokens(history) × ratio)`;`window` / `limit` /
299
424
  * `threshold` = 同一份 `policyBudget` 的三个字段(有效窗口那一边);`pct` = `round(tokens / limit × 100)`——
300
- * **分母 = `limit`**(用户实际可填的量):`window` 含输出预留,拿它当分母时 100% 永远到不了,读数只说明「窗口有多大」。
425
+ * **分母 = `limit`**(用户实际可填的量):`window` 含输出预留,拿它当分母时 100% 永远到不了。
301
426
  * `threshold` 随读带出,状态行的告警判据读它(`tokens >= threshold`),端侧不各发明一档阈值。
302
427
  * `ratio` **无缺省**:忘传 ⇒ `estimateTokens × undefined` = `NaN` ⇒ `tokens` / `pct` 皆 `NaN`。三面显示门
303
428
  * 都把非正值读作「不显示」(CLI `ctxPct > 0` · VSC 分子为假回 `null` · 桌面 `usageFrameWanted` 不发帧)
304
429
  * ⇒ 读数**缺席**(不会是错数);给缺省 1 则相反——忘传处静默显示未校准读数,看着完全正常而差一整个校准比。
305
430
  * 两种形状里只有后者会被当作事实读走,所以宁可缺席。
306
- * `workMode` **同无缺省**(§2.3):分母的取法只有一种,忘传就拒绝并点名参数——四个参数位次序 = (history, provider,
307
- * ratio, workMode),既有三参调用面只添末位,不前移。
431
+ * `workMode` 不是入参(§2.3):分母的取法只有一种,窗口恒等于模型窗口,档位不参与预算。
308
432
  * 空历史 ⇒ 0(状态行的 `ctxPct > 0` 显示门在端侧,不入本函数面)。
309
433
  */
310
- export function historyReading(history, provider, ratio, workMode) {
311
- const budget = policyBudget(provider, undefined, workMode)
434
+ export function historyReading(history, provider, ratio) {
435
+ const budget = policyBudget(provider)
312
436
  const tokens = Math.round(estimateTokens(history ?? []) * ratio)
313
437
  return {
314
438
  tokens,
@@ -318,11 +442,51 @@ export function historyReading(history, provider, ratio, workMode) {
318
442
  threshold: budget.threshold,
319
443
  }
320
444
  }
445
+ /**
446
+ * 整量读数单点(§2.5「显示与判定同基准」)——状态行 `context N% NNk` 的分子、stats 首行与第 6 行、
447
+ * 桌面 `ev:usage`、VSC 的 agent 面全读它一处:
448
+ *
449
+ * ```text
450
+ * tokens = contextUsage(agent, extras).total // 装配面六段:非对话面六项 + 对话面,实测优先
451
+ * pct = round(tokens / limit × 100)
452
+ * window ∥ limit = policyBudget(provider) 的两个字段
453
+ * threshold = contextUsage(agent, extras).threshold // 本回合判定所用的那条线
454
+ * basis = "measured" | "estimated"
455
+ * fixed = contextUsage(agent, extras).fixed // 非对话面六项(§5.1 ② 的门读 fixedFloor)
456
+ * compactionSummary = contextUsage(agent, extras).compactionSummary // 压缩摘要格当前内容(压缩链减掉它再加预留额)
457
+ * ```
458
+ *
459
+ * `threshold` 取 `contextUsage` 的那一个而不是 `policyBudget().threshold`:会话配了显式 `compactThreshold`
460
+ * 时后者是预算派生值、不是压缩线——显示与判定各读一条线,「同基准」当场破。
461
+ * 读数不封顶(`pct` 可大于 100):夹住就把「已越线多少」这个信息抹掉,而用户要判断的正是这件事。
462
+ *
463
+ * `extras` 必填、无缺省(同理 §2.3):忘传即静默退回仅对话的估算——正是本函数要消灭的那个量,
464
+ * 而它看起来完全正常。四个面都传 `agent?._ctxBasis?.overhead ?? {}`(`agent/turn-loop.mjs` 每回合暂存)。
465
+ * 例外两个:打开态(无 agent,走 `historyPercent`)与本进程还没跑过 run(空 extras + 无真值 ⇒ 仅对话的估算)。
466
+ */
467
+ export function contextReading(agent, extras) {
468
+ if (extras === undefined) {
469
+ throw new Error("contextReading: `extras` is required (no default) — pass agent?._ctxBasis?.overhead ?? {}")
470
+ }
471
+ const usage = contextUsage(agent, extras)
472
+ const budget = policyBudget(agent?.provider)
473
+ return {
474
+ tokens: usage.total,
475
+ pct: Math.round((usage.total / budget.limit) * 100),
476
+ window: budget.window,
477
+ limit: budget.limit,
478
+ threshold: usage.threshold,
479
+ basis: usage.basis,
480
+ fixed: usage.fixed,
481
+ compactionSummary: usage.compactionSummary,
482
+ }
483
+ }
321
484
 
322
- /** 状态行百分比薄转口(名面与 export 不变):`historyReading` 的 `pct`——与 stats ∥ CLI ∥ VSC **同源**
323
- * (各处全是这一实现点的投影,端侧零自算式)。第三参 `ratio` ∥ 第四参 `workMode` 同 `historyReading`:无缺省。 */
324
- export function historyPercent(history, provider, ratio, workMode) {
325
- return historyReading(history, provider, ratio, workMode).pct
485
+ /** 状态行百分比薄转口(名面与 export 不变):`historyReading` 的 `pct`——打开态读数(`sessionReading`)
486
+ * 与无 agent 转口两处用;有 agent 的四个面(CLI 状态行 ∥ stats ∥ Desktop ∥ VSC agent 面)一律读 `contextReading`。
487
+ * 第三参 `ratio` 同 `historyReading`:无缺省;档位不是入参。 */
488
+ export function historyPercent(history, provider, ratio) {
489
+ return historyReading(history, provider, ratio).pct
326
490
  }
327
491
 
328
492
  /** 估算校准比(§6.17)——`agent._tokRatio` 的**唯一**读出点(中性值 1 的唯一出处):
@@ -346,16 +510,15 @@ export const PRUNE_MIN_TOKENS = 200
346
510
  * 陈旧工具输出合格集(§6.16.3——三条件合取,单源实现):① `role === "tool"`;② **保护尾之外**(复用 `splitHistory` 的同一 `tailStart`——不新增第二处切割判据);③ 估算 ≥ `PRUNE_MIN_TOKENS`。
347
511
  * 返回逐条计数面(prune 回执 + stats 两处消费):`indexes` 合格索引(升序)· `tokens` 合格集估算和 · `candidates` 全史 tool 结果数 · `tailKept` 保护尾内保留数 · `belowMin` 门槛下跳过数 · `tailCount` 保护尾消息数。
348
512
  * **短历史(无中段)⇒ 合格集为空**(no-op——§6.16.3 边界)。
349
- * `workMode` 无缺省(§2.3):它向 `keepTailSize` ∥ `tailBudgetTokens` 透传——保护尾与压缩面同取有效窗口,
350
- * 否则 tiny 档下「可以 prune 的面」会比「会被摘掉的面」大一圈。
513
+ * `workMode` 不是入参(§2.3):保护尾与压缩面同取有效窗口(恒等于模型窗口),档位不参与。
351
514
  * `protectFrom` 无缺省(`CONTEXT-COMPACTION.md` §1.2):保留窗起点,原样转给 `splitHistory` 的第四参。
352
515
  * 拿不到保留窗的调用方传 `history.length`(= 不收紧);留一个缺省就是把「保留窗内该不该被清」
353
516
  * 静默定给调用方——这一档正是本批要保护的格。
354
517
  * `fixedOverhead` ∥ `ratio` 无缺省(§2.3):尾预算的减法链要用它们;四个消费点各自算好再传(§2.3 表)。
355
518
  */
356
- export function collectStaleToolOutputs(history, provider, workMode, protectFrom, fixedOverhead, ratio) {
519
+ export function collectStaleToolOutputs(history, provider, protectFrom, fixedOverhead, ratio) {
357
520
  const h = Array.isArray(history) ? history : []
358
- const split = splitHistory(h, keepTailSize(provider, h.length, workMode), tailBudgetTokens(provider, workMode, fixedOverhead, ratio), protectFrom)
521
+ const split = splitHistory(h, keepTailSize(provider, h.length), tailBudgetTokens(provider, fixedOverhead, ratio), protectFrom)
359
522
  // 无中段(短历史)⇒ 可摘要面为空 ⇒ **全史即保护尾**(tailStart = 0——合格集必为空,同压缩面 no-op)
360
523
  const tailStart = split ? split.tailStart : 0
361
524
  const r = { indexes: [], tokens: 0, candidates: 0, tailKept: 0, belowMin: 0, tailCount: h.length - tailStart }
@@ -377,20 +540,24 @@ export function collectStaleToolOutputs(history, provider, workMode, protectFrom
377
540
  *
378
541
  * ```text
379
542
  * _lastPromptTokens' = _lastPromptTokens − round((estBefore − estAfter) × ratio)
380
- * _usageAtLen' = 剪切后仍属于旧前缀的那些消息之后的第一个下标(就地替换 ⇒ 不变)
543
+ * _usageAt' = 剪切后仍属于旧前缀的那些消息之后的位置(就地替换 ⇒ 不变)
544
+ * _usageFixedBase' = 原样
381
545
  * ```
382
546
  *
383
547
  * `estBefore` / `estAfter` = 旧前缀里被改动的那一段、与它在编辑后对应的那一段,各取 `estimateTokens`。
384
548
  * 乘 `ratio` 与实测支对后缀的换算同一把尺:整条读数 = 「前缀的实测值」+「后缀的估算值 × ratio」。
385
- * 减到非正 ⇒ 基线不再描述任何东西,退回 `null`(与归零同形,但只在算不出来时走)。
549
+ * 减到非正 ⇒ 基线不再描述任何东西,退回 `null`(与归零同形,但只在算不出来时走);两个真值字段一起退回。
550
+ * `_usageFixedBase` 在正常路径上原样,理由不是「结构编辑只改对话面」:非对话面同样会动(压缩摘要重写、
551
+ * 待发队进出、编辑器上下文刷新)。它不动是因为那份变化已有承接方——实测支的第三项
552
+ * `(fixed − _usageFixedBase) × ratio` 量的就是非对话面与基线之差,重定基线等于把同一份变化扣两次。
386
553
  *
387
554
  * @param {object} agent
388
555
  * @param {number} estBefore 被改那一段的旧估算
389
556
  * @param {number} estAfter 它在编辑后对应那一段的估算
390
557
  * @param {{inPlace?: boolean, before?: object[], measuredEnd?: number}} [opts]
391
- * `inPlace` = 数组长度与下标不变(prune ∥ shrink 的原位替换)⇒ `_usageAtLen` 原样:被替换那条仍在
558
+ * `inPlace` = 结构不变(prune ∥ shrink 的原位替换)⇒ `_usageAt` 原样:被替换那条仍在
392
559
  * 前缀里,它的新估算已经由上面那笔减法折进基线,再进后缀就是重复计一次。
393
- * `before` / `measuredEnd` = 编辑前的数组与它被量到的长度(剪切类编辑按身份找回旧前缀的尾巴)。
560
+ * `before` = 编辑前的机读线(嵌套);`measuredEnd` = 它被量到的拍平下标(剪切类编辑按身份找回旧前缀的尾巴)。
394
561
  */
395
562
  export function rebaseMeasured(agent, estBefore, estAfter, { inPlace = false, before = null, measuredEnd = null } = {}) {
396
563
  if (agent?._lastPromptTokens == null) return
@@ -398,22 +565,45 @@ export function rebaseMeasured(agent, estBefore, estAfter, { inPlace = false, be
398
565
  const next = agent._lastPromptTokens - Math.round((estBefore - estAfter) * ratio)
399
566
  if (!(next > 0)) {
400
567
  agent._lastPromptTokens = null
401
- agent._usageAtLen = null
568
+ agent._usageAt = null
569
+ agent._usageFixedBase = null
402
570
  return
403
571
  }
404
572
  agent._lastPromptTokens = next
405
573
  if (inPlace) return
406
- const end = Number.isInteger(measuredEnd) ? measuredEnd : Array.isArray(before) ? before.length : null
407
- if (end == null) {
408
- agent._usageAtLen = null
409
- return
410
- }
411
- // 旧前缀的成员按**身份**取:压缩重建数组后下标会漂、身份不漂(与在途段起点同一条重定规则,§1.1)。
412
- const kept = new Set((before ?? agent.history).slice(0, end))
413
574
  const history = Array.isArray(agent.history) ? agent.history : []
414
- let at = 0
415
- for (let i = history.length - 1; i >= 0; i--) {
416
- if (kept.has(history[i])) { at = i + 1; break }
575
+ const source = Array.isArray(before) ? before : history
576
+ const limit = Number.isInteger(measuredEnd) ? measuredEnd : flatLengthOf(source)
577
+ // 旧前缀的成员按**身份**取:压缩重建数组后下标会漂、身份不漂(与在途段起点同一条重定规则,§1.1)。
578
+ const kept = new Set()
579
+ let seen = 0
580
+ for (const turn of source) {
581
+ for (const m of Array.isArray(turn?.messages) ? turn.messages : []) {
582
+ if (seen >= limit) break
583
+ kept.add(m)
584
+ seen++
585
+ }
586
+ if (seen >= limit) break
587
+ }
588
+ agent._usageAt = endPositionOf(history, kept)
589
+ }
590
+
591
+ /** 嵌套线的拍平条数(外层条数是轮数,不是消息数)。 */
592
+ function flatLengthOf(history) {
593
+ let n = 0
594
+ for (const turn of Array.isArray(history) ? history : []) {
595
+ n += Array.isArray(turn?.messages) ? turn.messages.length : 0
596
+ }
597
+ return n
598
+ }
599
+
600
+ /** 旧前缀最后一条仍在线上那一条之后的位置(找不到 ⇒ 线头)。 */
601
+ function endPositionOf(history, kept) {
602
+ for (let t = history.length - 1; t >= 0; t--) {
603
+ const messages = Array.isArray(history[t]?.messages) ? history[t].messages : []
604
+ for (let m = messages.length - 1; m >= 0; m--) {
605
+ if (kept.has(messages[m])) return { turn: t, msg: m + 1 }
606
+ }
417
607
  }
418
- agent._usageAtLen = at
608
+ return { turn: 0, msg: 0 }
419
609
  }
package/tool-docs/bash.md CHANGED
@@ -1,4 +1,2 @@
1
1
  Execute a shell command and return stdout+stderr.
2
- {{inject:bash-terminal-face}}
3
-
4
2
  {{knowledge:tool-bash}}
@@ -1,3 +1,3 @@
1
- Start a parallel multi-model consultation (会诊) of the configured consult models.
1
+ Start a parallel multi-model consultation of the configured consult models.
2
2
 
3
- {{knowledge:tool-consult-start}}
3
+ {{knowledge:tool-consult-start}}
@@ -1,3 +1,3 @@
1
- Cancel a still-running consultation session (会诊).
1
+ Cancel a still-running consultation session.
2
2
 
3
- {{knowledge:tool-consult-stop}}
3
+ {{knowledge:tool-consult-stop}}
package/tools/browser.mjs CHANGED
@@ -135,9 +135,9 @@ export const browserTool = {
135
135
  parameters: {
136
136
  type: "object",
137
137
  properties: {
138
- action: { type: "string", enum: BROWSER_ACTIONS, description: "Action to run (one per call): navigate | snapshot | click | type | evaluate | wait | screenshot | close | press | hover | wheel | mouse | drag | touch | insert | clipboard | cookies | storage." },
138
+ action: { type: "string", enum: BROWSER_ACTIONS, description: "The action to run." },
139
139
  url: { type: "string", description: "navigate: http/https URL to open — also the `wait` url predicate (substring of location.href)." },
140
- ref: { type: "string", description: "click / type / press / hover / wheel / mouse / touch / insert: element reference from the last snapshot (`e<N>`)." },
140
+ ref: { type: "string", description: "click / type / press / hover / wheel / mouse / touch / insert / clipboard: element reference from the last snapshot (`e<N>`). clipboard: only copy / paste take it, focusing the target before the accelerator keys go out; read / write ignore it. insert: focuses the target before the text goes in." },
141
141
  text: { type: "string", description: "type: text to enter — insert: text to insert; clipboard write: text to write; wait: the awaited visible text." },
142
142
  expression: { type: "string", description: "evaluate: JavaScript expression run in the PAGE context (no Node/host access)." },
143
143
  selector: { type: "string", description: "snapshot: CSS selector scoping the scan — also the `wait` selector predicate." },
@@ -146,8 +146,8 @@ export const browserTool = {
146
146
  networkIdle: { type: "boolean", description: "wait: true = wait until network activity is quiet for 500ms." },
147
147
  timeoutMs: { type: "number", description: "Budget override in ms: wait = the predicate timeout (default 30000, cap 120000); other actions = the whole-call budget (default per action table, hard cap 120000)." },
148
148
  fullPage: { type: "boolean", description: "screenshot: true = capture the whole page, false = viewport (default)." },
149
- headless: { type: "boolean", description: "The shared browser's first-open attribute (any action): default true. When another instance already started it, your value cannot be applied — the session reuses the running mode and the receipt carries a `[note: the shared browser is running headless=<actual> …]` line saying so. Switching modes needs every instance to release the browser first." },
150
- key: { type: "string", description: "press: key name (Enter, Escape, Tab, Backspace, Delete, Space, Insert, Home, End, PageUp, PageDown, Arrows, F1-F12, modifiers) or a single character. storage: the target key (get / clear address one key; storage set requires it)." },
149
+ headless: { type: "boolean", description: "First-open attribute of the shared browser (any action), default true. If another instance already started it, your value cannot be applied: the session reuses the running mode and the receipt carries a `[note: the shared browser is running headless=<actual> …]` line. Switching modes needs every instance to release the browser." },
150
+ key: { type: "string", description: "press: key name (Enter, Escape, Tab, Backspace, Delete, Space, Insert, Home, End, PageUp, PageDown, Arrows, F1-F12, modifiers) or a single US-layout printable character (a-z, 0-9, punctuation). storage: the key to read or clear; `set` requires it. A `storage` key that is not a string is an error, never treated as \"every key\"." },
151
151
  modifiers: { type: "array", items: { type: "string" }, description: "press: modifier keys held (and observed by the page) — Control | Alt | Shift | Meta, any combination." },
152
152
  phase: { type: "string", description: "press: press (default) | down | up. mouse: click (default) | down | up." },
153
153
  repeat: { type: "number", description: "press: auto-repeat count while the key is held (0-100, default 0)." },
@@ -165,11 +165,11 @@ export const browserTool = {
165
165
  scale: { type: "number", description: "touch pinch: scale factor (>1 zoom in, <1 zoom out)." },
166
166
  ime: { type: "string", description: "insert: IME composition text staged before the committed text is inserted." },
167
167
  op: { type: "string", description: "clipboard: read | write | copy | paste. cookies / storage: get | set | clear." },
168
- cookies: { type: "array", items: { type: "object" }, description: "cookies set: one or more cookies — { name, value, domain?, path?, expires?, httpOnly?, secure?, sameSite? }. Every declared field is type-checked before anything is written: `path` must be a string starting with \"/\", `expires` must be Unix seconds as a number (a string is rejected, never coerced), `httpOnly` and `secure` must be booleans, `sameSite` must be Strict | Lax | None. A value of the wrong type is an error naming the field, never silently defaulted — `httpOnly:\"true\"` would otherwise store a cookie that is not httpOnly while the receipt reported success. A given `domain` is written as-is: cross-domain writes are intentional (no switch, no approval), but it must be a bare host — a scheme, a path or a `host:port` pair (`localhost:3000`; cookie domains never carry a port) is an error, never treated as omitted. Omit `domain` to land on the current page's origin." },
169
- domain: { type: "string", description: "cookies: get = domain filter (subdomains included; an IP literal matches itself only); clear = scope. A value that is not a non-empty host string is an error, never treated as omitted — a `host:port` pair such as `localhost:3000` counts as one (cookie domains never carry a port, so it would filter to nothing and read as \"that domain has no cookies\"). Omit it on get ⇒ every cookie in the shared profile, on clear ⇒ the whole profile's cookies are wiped for every instance." },
170
- area: { type: "string", description: "storage: localStorage (default) | sessionStorage. The two areas are separate scopes and never bleed into each other. Any other value — null, a non-string, an empty string — is an error naming the value, never treated as omitted: only leaving it out selects the default." },
168
+ cookies: { type: "array", items: { type: "object" }, description: "Cookie objects: `{ name, value, domain?, path?, expires?, httpOnly?, secure?, sameSite? }`. Fields are type-checked, never silently defaulted — `path` starts with \"/\", `expires` is Unix seconds as a number, `httpOnly`/`secure` are booleans, `sameSite` is Strict|Lax|None. `domain` is written as given, cross-domain included, and must be a bare host — no scheme, no path, no port. Omit it for the current origin, which needs an http/https page." },
169
+ domain: { type: "string", description: "cookies: get = domain filter (subdomains included, an IP literal matches itself only); clear = scope. Must be a non-empty bare host — cookie domains carry no port, so `host:port` like `localhost:3000` is an error, never treated as omitted. Omit it: get ⇒ every cookie in the shared profile, clear ⇒ wipe the whole profile for every instance." },
170
+ area: { type: "string", description: "storage: localStorage (default) | sessionStorage. The two are separate scopes and never bleed into each other. Any other value — null, a non-string, an empty string — is an error naming the value; only leaving it out selects the default." },
171
171
  value: { type: "string", description: "storage set: the value (a string; a non-string is rejected, never silently stringified)." },
172
- async: { type: "boolean", description: "Run this action in the background (default false, depth-0 only): returns an ack at once (browser#<N> started (running) — <action> <subject>); the finished result arrives later as a system reminder summary. Use wait_for \"browser id:N done\" to wait; process {action:\"kill\", id:N} to cancel." },
172
+ async: { type: "boolean", description: "Run this action in the background (default false, depth-0 only): returns the ack `browser#<N> started (running) — <action> <subject>` at once; the result arrives later as a system reminder summary. Wait with `wait_for \"browser id:N done\"`; cancel with `process {action:\"kill\", id:N}`." },
173
173
  },
174
174
  required: ["action"],
175
175
  },
package/tools/execute.mjs CHANGED
@@ -174,11 +174,11 @@ export const executeTool = {
174
174
  properties: {
175
175
  code: {
176
176
  type: "string",
177
- description: "JavaScript code to execute (top-level await and dynamic import() supported). Pure node ESM — no preloaded globals; import node: modules (fs/path) yourself when needed. File reads/writes go through the dedicated read/ls/glob/grep/write/edit tools. Use this OR scriptFile.",
177
+ description: "JavaScript to run (top-level await and dynamic import() supported). Pure node ESM — no preloaded globals; import `node:` modules yourself when needed. File reads and writes go through the dedicated tools. Use this OR scriptFile.",
178
178
  },
179
179
  scriptFile: {
180
180
  type: "string",
181
- description: "Run a .mjs/.js file with node (self-contained — the file imports what it needs). Path relative to workdir — no directory restriction. Use this OR code. For `node <script>` / `node --test <file>` / `node --check <file>`.",
181
+ description: "Run a .mjs/.js file with node (self-contained — it imports what it needs). Path relative to workdir, no directory restriction. Use this OR code. For `node <script>` / `node --test <file>` / `node --check <file>`.",
182
182
  },
183
183
  nodeArgs: {
184
184
  type: "array",