@thincoder/core 0.11.5 → 0.12.1

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 (199) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/abort-provenance.mjs +23 -0
  3. package/advisor/citations.mjs +5 -1
  4. package/advisor/compaction.mjs +13 -10
  5. package/advisor/history.mjs +6 -1
  6. package/advisor/loop.mjs +35 -10
  7. package/advisor/messages.mjs +31 -43
  8. package/advisor/project-context.mjs +49 -45
  9. package/advisor/run.mjs +82 -26
  10. package/advisor.mjs +40 -11
  11. package/agent/assemble.mjs +5 -5
  12. package/agent/chat-call.mjs +21 -1
  13. package/agent/completion.mjs +1 -20
  14. package/agent/dispatch-gates.mjs +8 -3
  15. package/agent/dispatch-run.mjs +131 -20
  16. package/agent/dispatch.mjs +23 -22
  17. package/agent/family-tools.mjs +4 -7
  18. package/agent/goal-judge.mjs +99 -0
  19. package/agent/goal-state.mjs +96 -0
  20. package/agent/helpers.mjs +13 -4
  21. package/agent/offload.mjs +1 -1
  22. package/agent/planning-graph-guardrail.mjs +224 -0
  23. package/agent/planning-prompt.mjs +179 -0
  24. package/agent/planning-step.mjs +460 -173
  25. package/agent/post-turn.mjs +23 -33
  26. package/agent/record-results.mjs +8 -5
  27. package/agent/run-stages.mjs +18 -38
  28. package/agent/run-start.mjs +26 -19
  29. package/agent/setup-reminders.mjs +16 -14
  30. package/agent/setup.mjs +3 -2
  31. package/agent/spawn-child.mjs +17 -4
  32. package/agent/suspension.mjs +42 -21
  33. package/agent/task-lifecycle.mjs +165 -52
  34. package/agent/timers.mjs +9 -1
  35. package/agent/turn-loop.mjs +160 -69
  36. package/agent/turn-projection.mjs +26 -15
  37. package/agent/turn-task-state.mjs +4 -4
  38. package/agent/write-gate-ledger.mjs +1 -1
  39. package/agent/write-gate.mjs +14 -11
  40. package/agent-tools/advisor-async.mjs +2 -0
  41. package/agent-tools/advisor-launch.mjs +27 -13
  42. package/agent-tools/advisor-settle.mjs +19 -18
  43. package/agent-tools/advisor.mjs +90 -13
  44. package/agent-tools/bash-async.mjs +3 -3
  45. package/agent-tools/batch-ledger-bind.mjs +8 -5
  46. package/agent-tools/batch-read.mjs +42 -0
  47. package/agent-tools/batch-record-write.mjs +20 -12
  48. package/agent-tools/batch-segment-vocab.mjs +6 -4
  49. package/agent-tools/batch-skeleton.mjs +43 -12
  50. package/agent-tools/consult.mjs +5 -1
  51. package/agent-tools/context.mjs +5 -4
  52. package/agent-tools/design-slots.mjs +7 -4
  53. package/agent-tools/design-token.mjs +3 -2
  54. package/agent-tools/doc-graph.mjs +257 -95
  55. package/agent-tools/escalate-async.mjs +4 -1
  56. package/agent-tools/goal.mjs +28 -95
  57. package/agent-tools/plan.mjs +1 -1
  58. package/agent-tools/review-facts.mjs +56 -7
  59. package/agent-tools/settings.mjs +35 -1
  60. package/agent-tools/ssh-transport.mjs +23 -22
  61. package/agent-tools/step.mjs +24 -4
  62. package/agent-tools/subagent-actions.mjs +6 -2
  63. package/agent-tools/subagent-async.mjs +4 -2
  64. package/agent-tools/subagent.mjs +1 -1
  65. package/agent-tools/task.mjs +73 -65
  66. package/agent-tools.mjs +3 -3
  67. package/agent.mjs +12 -3
  68. package/auto-think.mjs +16 -3
  69. package/browser/actions.mjs +5 -1
  70. package/browser/cdp.mjs +1 -1
  71. package/browser/pool.mjs +110 -17
  72. package/compaction-work-state.mjs +103 -13
  73. package/compress-form.mjs +29 -3
  74. package/config-defaults.mjs +27 -3
  75. package/config-io.mjs +3 -14
  76. package/config-normalize.mjs +24 -4
  77. package/config-presets.mjs +40 -26
  78. package/config-warn.mjs +30 -0
  79. package/config.mjs +139 -63
  80. package/context-degrade.mjs +4 -4
  81. package/context-push.mjs +20 -9
  82. package/context.mjs +65 -20
  83. package/doc-graph/anchors.mjs +39 -40
  84. package/doc-graph/clusters.mjs +49 -0
  85. package/doc-graph/code-parsers.mjs +494 -0
  86. package/doc-graph/context-pack.mjs +392 -0
  87. package/doc-graph/dir-signals.mjs +228 -0
  88. package/doc-graph/edges.mjs +231 -0
  89. package/doc-graph/format.mjs +70 -0
  90. package/doc-graph/gc-cmd.mjs +104 -0
  91. package/doc-graph/gc.mjs +112 -0
  92. package/doc-graph/glob-work-graph.mjs +307 -0
  93. package/doc-graph/golden-set.mjs +131 -0
  94. package/doc-graph/ls-work-graph.mjs +534 -0
  95. package/doc-graph/outline.mjs +377 -0
  96. package/doc-graph/output-annotations.mjs +85 -0
  97. package/doc-graph/process-docs.mjs +68 -0
  98. package/doc-graph/read-work-graph.mjs +91 -0
  99. package/doc-graph/rebuild-cmd.mjs +75 -0
  100. package/doc-graph/resolvers.mjs +322 -0
  101. package/doc-graph/roots.mjs +86 -0
  102. package/doc-graph/schema.mjs +110 -0
  103. package/doc-graph/search-augment.mjs +418 -0
  104. package/doc-graph/store.mjs +231 -0
  105. package/doc-graph/target-resolve.mjs +352 -0
  106. package/doc-graph/walk.mjs +87 -0
  107. package/doc-graph.mjs +583 -707
  108. package/explore-distill.mjs +52 -17
  109. package/generate-title.mjs +7 -4
  110. package/ledger-close.mjs +6 -6
  111. package/ledger-cmd.mjs +3 -3
  112. package/ledger-consistency.mjs +8 -6
  113. package/ledger-db.mjs +45 -10
  114. package/ledger-migrate.mjs +25 -10
  115. package/ledger-read.mjs +1 -1
  116. package/ledger-write-ops.mjs +6 -6
  117. package/ledger.mjs +2 -2
  118. package/model-context.mjs +54 -18
  119. package/model-specs.mjs +86 -67
  120. package/package.json +1 -1
  121. package/prompt-overlays.mjs +3 -3
  122. package/prompts/advisor-round1.md +6 -5
  123. package/prompts/common.md +16 -6
  124. package/prompts/consult-base.md +2 -1
  125. package/prompts/discipline-engineering.md +1 -1
  126. package/prompts/discipline-normal.md +12 -8
  127. package/prompts/knowledge/doc-lookup.md +2 -2
  128. package/prompts/knowledge/normal-batch-discipline.md +2 -2
  129. package/prompts/knowledge/normal-delivery-collaboration.md +3 -3
  130. package/prompts/knowledge/tool-advisor.md +2 -2
  131. package/prompts/knowledge/tool-apply-patch.md +1 -1
  132. package/prompts/knowledge/tool-bash.md +2 -2
  133. package/prompts/knowledge/tool-batch.md +4 -4
  134. package/prompts/knowledge/tool-glob.md +9 -2
  135. package/prompts/knowledge/tool-goal.md +9 -6
  136. package/prompts/knowledge/tool-grep.md +7 -2
  137. package/prompts/knowledge/tool-ls.md +11 -5
  138. package/prompts/knowledge/tool-lsp.md +1 -1
  139. package/prompts/knowledge/tool-operations.md +3 -2
  140. package/prompts/knowledge/tool-plan.md +1 -1
  141. package/prompts/knowledge/tool-read.md +7 -6
  142. package/prompts/knowledge/tool-repo-graph-read.md +12 -0
  143. package/prompts/knowledge/tool-repo-graph.md +12 -0
  144. package/prompts/knowledge/tool-step.md +1 -1
  145. package/prompts/knowledge/tool-subagent.md +2 -2
  146. package/prompts/knowledge/tool-task.md +10 -9
  147. package/prompts/knowledge/tool-tree.md +7 -1
  148. package/prompts/persona-eng-coder.md +1 -1
  149. package/prompts/persona-eng-designer.md +1 -1
  150. package/prompts/persona-engineering.md +2 -1
  151. package/prompts/persona-explore.md +1 -1
  152. package/prompts/persona-normal.md +7 -6
  153. package/prompts/persona-plan.md +2 -2
  154. package/prompts/planning-next-moves.md +7 -8
  155. package/provider/anthropic.mjs +53 -51
  156. package/provider/core.mjs +85 -34
  157. package/provider/errors.mjs +33 -10
  158. package/provider/google.mjs +244 -37
  159. package/provider/list-models.mjs +28 -14
  160. package/provider/responses-request.mjs +15 -9
  161. package/provider/responses.mjs +10 -8
  162. package/provider/sse.mjs +3 -6
  163. package/proxy-transport.mjs +228 -119
  164. package/rules-file.mjs +79 -0
  165. package/rules.mjs +13 -51
  166. package/session-lifecycle.mjs +32 -20
  167. package/team-ledger.mjs +7 -7
  168. package/think-off.mjs +37 -18
  169. package/token-window.mjs +48 -31
  170. package/tool-args.mjs +8 -8
  171. package/tool-docs/bash.md +1 -1
  172. package/tool-docs/glob.md +3 -1
  173. package/tool-docs/goal.md +2 -2
  174. package/tool-docs/grep.md +3 -1
  175. package/tool-docs/ls.md +7 -1
  176. package/tool-docs/read.md +1 -1
  177. package/tool-docs/repo_graph-read.md +3 -0
  178. package/tool-docs/repo_graph.md +3 -0
  179. package/tool-docs/tree.md +1 -1
  180. package/tools/bash.mjs +53 -8
  181. package/tools/browser.mjs +4 -4
  182. package/tools/file.mjs +34 -7
  183. package/tools/glob-dialect.mjs +57 -7
  184. package/tools/index.mjs +3 -7
  185. package/tools/patch.mjs +8 -7
  186. package/tools/process-doc-mark.mjs +13 -0
  187. package/tools/search.mjs +152 -37
  188. package/tools/shared.mjs +6 -0
  189. package/tools/tree.mjs +211 -8
  190. package/window-policy.mjs +205 -126
  191. package/prompts/knowledge/tool-doc-graph-read.md +0 -20
  192. package/prompts/knowledge/tool-doc-graph.md +0 -49
  193. package/prompts/knowledge/tool-peek.md +0 -10
  194. package/prompts/knowledge/tool-repo-outline.md +0 -4
  195. package/tool-docs/doc_graph-read.md +0 -3
  196. package/tool-docs/doc_graph.md +0 -3
  197. package/tool-docs/peek.md +0 -3
  198. package/tool-docs/repo_outline.md +0 -3
  199. package/tools/peek.mjs +0 -447
@@ -18,8 +18,8 @@
18
18
  */
19
19
 
20
20
  import { existsSync } from "node:fs"
21
- // §6.17:auto 派生值只进显示面(compactThresholdResolved)——显式键 agent.compactThreshold 永不被改写
22
- import { resolveCompactThreshold, resolveSessionWorkMode, setConfigWorkMode } from "./config.mjs"
21
+ // §6.17:显式键 `agent.compactThreshold` 永不被改写;auto 派生线在读数上现算,本档不缓存它。
22
+ import { bindProviderContextPolicy, resolveSessionWorkMode, setConfigWorkMode } from "./config.mjs"
23
23
  // 槽面判据单源(#841 KD-841-2:槽渠道 key 门 + 模型面序——PROVIDER.md §6.22)。
24
24
  import { hasKey, resolveChannelModel, resolveProviderPlan } from "./model-ref.mjs"
25
25
  // 旧线补来源(AGENT-LOOP.md §5.5.4 补行):槽 `activeProvider` 是非空字符串且与运行态不同时,给无标记的 assistant 消息补会话级来源。
@@ -135,8 +135,7 @@ function normalizePendingInject(raw) {
135
135
  * "三支"误读):
136
136
  * ① 槽 provider 存在 → provider/model 按槽值设(模型链 = 槽模型 → `defaultModel` 属本渠道 ⇒ 其模型段;
137
137
  * 两档皆无 ⇒ `null`——2026-10-09 清除批:原 `providers[].model` 回落退场;`defaultModel` 经
138
- * `resolveProviderPlan` 参与模型面)+ 刷新显示面
139
- * `compactThresholdResolved`(auto 时——按恢复后模型;显式键 `compactThreshold` 零改写);
138
+ * `resolveProviderPlan` 参与模型面;显式键 `compactThreshold` 零改写——派生线在读数上现算,不缓存);
140
139
  * ② 槽 provider 没了 → D-S3 保留——静默保持现状(config 有效则有效——两方都无效由调用侧
141
140
  * 复验 validateProvider 弹重选)。
142
141
  * 删旧支:"activeModel==null 清 stale override 回渠道默认"——前提 = 渠道默认字段——已随
@@ -197,6 +196,10 @@ export function applySession(agent, data, opts = {}) {
197
196
  // and a slot with neither field restores normal — config `agent.mode` is never a restore authority
198
197
  // (SESSION.md §8, CONFIG.md §5.4).
199
198
  setConfigWorkMode(agent.config, resolveSessionWorkMode(data))
199
+ // 槽档刚落进 config,运行时 provider 的派生视图(`mode` ∥ `contextCaps`)必须同拍跟上:下面槽 provider
200
+ // 可用时分支①会重绑自己的拷贝,不可用时 provider 仍是装配期那一份——不重绑它,窗口与压缩线会按上一个
201
+ // 档位算(`/config` 与状态行报两个数)。两处重绑同一对函数,不另写第二份判据。
202
+ bindProviderContextPolicy(agent.provider, agent.config)
200
203
  // ENG-PLAN-EXCLUSION(FR31 ③ / KD10——恢复点①·CLI `applySession`):工程模式 ⇒ planMode 恒
201
204
  // false(内存位 + 未注入的 plan 提示语)——防「工程纪律 × plan 只读」半状态随槽恢复复活。
202
205
  // **槽不就地回写**:内存值在下一次 `saveSession` 随 `planMode` 字段自然收正(`session.mjs`)。
@@ -251,12 +254,9 @@ export function applySession(agent, data, opts = {}) {
251
254
  agent.activeProvider = slotProvider.name
252
255
  agent.activeModel = slotModel
253
256
  agent.provider = { ...slotProvider }
257
+ // 派生视图(CONTEXT-COMPACTION.md §2.1 档位上限):这一行是拷贝,档位与档位上限表随拷贝重绑;槽的 mode 上一行刚由 setConfigWorkMode 落进 config。
258
+ bindProviderContextPolicy(agent.provider, agent.config)
254
259
  if (slotModel) agent.provider.model = slotModel
255
- // §6.17:恢复后 auto 派生线随槽模型跟手——只刷新显示面 compactThresholdResolved(显式键不写;
256
- // 判定阈值本身由 setup.mjs 每 run 现算,不依赖本值)
257
- if (switched && agent.config?.agent?.compactThresholdAuto && typeof agent.provider.model === "string" && agent.provider.model) {
258
- agent.config.agent.compactThresholdResolved = resolveCompactThreshold(null, agent.provider).value
259
- }
260
260
  // 会话级档位施加(§6.21 判据句 4——在模型合并支之后,以**合并后**的 `provider.model` 判 spec;
261
261
  // 三端共用本施加面):`"off"` 记号 ⇒ 该模型有 off 路径才设关思考形(effort 族该形为 `null`
262
262
  // ⇒ 另置 `reasoningEffort: "none"`——§16.4 载荷门,单源 = `think-off.mjs`);枚举字面 ⇒ 直置;
@@ -264,18 +264,22 @@ export function applySession(agent, data, opts = {}) {
264
264
  if (data.effort != null) {
265
265
  // 非串 model(外端脏载 / 手工档)按未登记归一——本块不因类型脏载抛(同 `resolveEffortPatch` 口径)
266
266
  const spec = specForModel(typeof agent.provider.model === "string" ? agent.provider.model : "")
267
+ // 2026-12-03 批(台账 #133):槽的 effort 恢复写**设置层会话视图**(`agent.modelParams`)——
268
+ // 不再是 `agent.provider` 上的字段(用户裁定「不应该有任何 provider 级别的模型参数」)。
269
+ agent.modelParams ??= {}
267
270
  if (data.effort === "off") {
268
271
  if (thinkOffPath(spec)) {
269
272
  const shape = thinkOffShape(spec)
270
- agent.provider.thinking = shape
271
- if (shape === null) agent.provider.reasoningEffort = "none"
273
+ agent.modelParams.thinking = shape
274
+ if (shape === null) agent.modelParams.reasoningEffort = "none"
272
275
  }
273
276
  } else if (spec?.reasoningEffortEnum?.includes(data.effort)) {
274
- agent.provider.reasoningEffort = data.effort
277
+ agent.modelParams.reasoningEffort = data.effort
275
278
  }
276
279
  }
277
280
  // §6.17.1 链二读面:估算校准样本随槽恢复——上行刚把 `provider` 按槽值落定,key 同源校验才有意义
278
- // (四条校验在 `restoreTokenSample`:形状 / est 版本 / key 同源 / 下界 1;不合格 ⇒ 未校准档)。
281
+ // (四条校验在 `restoreTokenSample`:形状 / est 版本 / key 同源 / 比值下界;不合格 ⇒ 未校准档)。比值下界
282
+ // 取 `token-window.mjs` 的 `TOKEN_RATIO_MIN`——不在这里写死数值(2026-12-03 由 1 放开,见 §3)。
279
283
  restoreTokenSample(agent, data.estimateSample, agent.provider)
280
284
  // 旧线补来源(AGENT-LOOP.md §5.5.4 补行 · 槽渠道解析之后、机读线装回之后):槽 `activeProvider` 是非空字符串且与运行态
281
285
  // `agent.provider.name` 不同时,给无标记的 assistant 消息补会话级来源;空串与缺键(无会话级证据)一律不补。补来源是尽力而为,
@@ -492,12 +496,15 @@ export function slotOccupancy(cwd, slot) {
492
496
  * ⇒ 落链)∥ 无槽模型 ⇒ 现行模型链回落(`defaultModel` 属本渠道 ⇒ 其模型段;两档皆无 ⇒ `null`——
493
497
  * `resolveChannelModel`,2026-10-09 清除批:渠道单值模型退场,零静默回落);未命中 ⇒ `fallback`
494
498
  * (支 ②「静默保持现状」的装配口径 = `loadConfig().provider`);
495
- * ④ 公式 = 核 `historyPercent`(= `historyReading` 的 `pct` 薄转口;与 CLI ∥ VSC 同一实现点的投影);
496
- * 第三参 = 槽样本经 `sampleRatio` 取的校准比。档位不是入参(§2.1 ∥ §2.3):有效窗口恒等于模型窗口,
497
- * 打开态分母因此只由渠道那一行决定,槽里的 `mode` 不参与读数。
498
- * **零副作用**:`data` / `providers` / `fallback` / `defaultModel` 皆入参(不读盘、不写盘、不改任何进程态);
499
+ * ④ 档位闸 = `bindProviderContextPolicy` 绑在**合并后那张拷贝**上(入参对象零改写):档位取槽 `mode`、
500
+ * 上限表取 `caps`(缺参 ⇒ DEFAULTS 那张表)。打开态分母与恢复后的状态行因此是同一个有效窗口
501
+ * `min(模型窗口, 槽档上限)`(§2.1,2026-11-28 用户裁决);
502
+ * ⑤ 公式 = 核 `historyPercent`(= `historyReading` 的 `pct` 薄转口;与 CLI ∥ VSC 同一实现点的投影);
503
+ * 第三参 = 槽样本经 `sampleRatio` 取的校准比;第四参 `settings` = `{ agent: { contextCaps: caps }, modelContext }`
504
+ * (模型窗口声明住设置层顶层——2026-12-03 批,不挂 provider)。
505
+ * **零副作用**:`data` / `providers` / `fallback` / `defaultModel` / `caps` / `modelContext` 皆入参(不读盘、不写盘、不改任何进程态);
499
506
  * `data` 非对象 ⇒ `0`(与空历史同值——「非正 ⇒ 零节点」显示门归端侧,沿 `historyPercent` 空历史口径)。 */
500
- export function sessionReading(data, { providers, fallback, defaultModel } = {}) {
507
+ export function sessionReading(data, { providers, fallback, defaultModel, caps, modelContext } = {}) {
501
508
  if (data === null || typeof data !== "object") return 0
502
509
  const full = Array.isArray(data.history) ? data.history : []
503
510
  const ch = normalizeContextHistory(data.contextHistory)
@@ -509,8 +516,13 @@ export function sessionReading(data, { providers, fallback, defaultModel } = {})
509
516
  // #638:非串 ∕ 空串 `activeModel` 归一(与 applySession 模型合并支 ① 同判)——脏值不达 `historyPercent`;
510
517
  // 未登记 ⇒ 落现行模型链(`defaultModel` 属本渠段 ∥ `null`——渠道单值退场,2026-10-09 清除批)。
511
518
  const slotModel = (typeof data.activeModel === "string" && data.activeModel) ? data.activeModel : null
512
- const provider = entry
519
+ const base = entry
513
520
  ? { ...entry, model: slotModel ?? resolveChannelModel(entry, defaultModel ?? null) }
514
521
  : fallback
515
- return historyPercent(line, provider, sampleRatio(data.estimateSample, provider))
522
+ // 档位闸(④):打开态分母与恢复后的状态行是同一个有效窗口 `min(模型窗口, 槽档上限)`。
523
+ // 绑在合并后那张拷贝上——`bindProviderContextPolicy` 改的是传入对象,入参(`providers` 表 / `fallback`)一个字节不动。
524
+ const provider = base && typeof base === "object"
525
+ ? bindProviderContextPolicy({ ...base }, { agent: { mode: resolveSessionWorkMode(data), contextCaps: caps } })
526
+ : base
527
+ return historyPercent(line, provider, sampleRatio(data.estimateSample, provider), { agent: { contextCaps: caps }, modelContext })
516
528
  }
package/team-ledger.mjs CHANGED
@@ -170,9 +170,9 @@ const ACTION_SPECS = {
170
170
  },
171
171
  update: {
172
172
  type: "object",
173
- required: ["id"],
173
+ required: ["uid"],
174
174
  properties: {
175
- id: { type: "number", description: "Row number (global)." },
175
+ uid: { type: "string", description: "Row identity (UUIDv7) — globally unique across machines." },
176
176
  title: { type: "string", description: "Title; omitted ⇒ unchanged." },
177
177
  detail: { type: "string", description: "Body; omitted ⇒ unchanged." },
178
178
  owner: { type: "string", description: "Owner — set it to hand the row over; omitted ⇒ unchanged." },
@@ -182,9 +182,9 @@ const ACTION_SPECS = {
182
182
  },
183
183
  close: {
184
184
  type: "object",
185
- required: ["id", "status"],
185
+ required: ["uid", "status"],
186
186
  properties: {
187
- id: { type: "number", description: "Row number (global)." },
187
+ uid: { type: "string", description: "Row identity (UUIDv7) — globally unique across machines." },
188
188
  status: { type: "string", enum: ["已核销", "已废弃"], description: "Target state: settle or withdraw." },
189
189
  },
190
190
  additionalProperties: false,
@@ -202,7 +202,7 @@ const UNION_PARAMETERS = {
202
202
  owner: { type: "string", description: "Owner: on query and count it filters (exact username); on add and update it sets the value." },
203
203
  title: { type: "string", description: "Title: required on add, changeable on update — trimmed non-empty and at most 200 characters." },
204
204
  detail: { type: "string", description: "Body: on add and update, optional, at most 4000 characters." },
205
- id: { type: "number", description: "Row number: required on update and close; the numbering is global." },
205
+ uid: { type: "string", description: "Row identity: required on update and close; the identity is a UUIDv7, globally unique across machines." },
206
206
  },
207
207
  additionalProperties: false,
208
208
  }
@@ -256,11 +256,11 @@ function makeTeamLedgerTool(actions, { readonly = false, writeFace = false } = {
256
256
  return JSON.stringify(payload, null, 2)
257
257
  }
258
258
  case "update": {
259
- const payload = await request(server, token, "PATCH", `/api/client/ledger/${encodeURIComponent(String(rest.id))}`, { title: rest.title, detail: rest.detail, owner: rest.owner, status: rest.status })
259
+ const payload = await request(server, token, "PATCH", `/api/client/ledger/${encodeURIComponent(String(rest.uid))}`, { title: rest.title, detail: rest.detail, owner: rest.owner, status: rest.status })
260
260
  return JSON.stringify(payload, null, 2)
261
261
  }
262
262
  case "close": {
263
- const payload = await request(server, token, "POST", `/api/client/ledger/${encodeURIComponent(String(rest.id))}/close`, { status: rest.status })
263
+ const payload = await request(server, token, "POST", `/api/client/ledger/${encodeURIComponent(String(rest.uid))}/close`, { status: rest.status })
264
264
  return JSON.stringify(payload, null, 2)
265
265
  }
266
266
  default:
package/think-off.mjs CHANGED
@@ -1,24 +1,41 @@
1
1
  /**
2
2
  * think-off.mjs — off 形族的单一实现源(叶档:零 import 纯函数)。
3
3
  *
4
- * 单一来源 = `docs/core/design/MODEL-SPECS.md`:写面取形 = §16.2 / §15.4-2 族别判据表;
5
- * 「有效 off 路径」判据 = §16.4。四处生产者(CLI `/think` · CLI `/advisor` · VSC 主模型面
6
- * `reasoning-mode.mjs` · VSC 面板写面 `settings-panel-write.mjs`)一律消费本档(端引核零副本——
7
- * 副本即漂移源:VSC 全族一形 `null` 与 CLI 自定义族支 `undefined` 两处漂移已实证,§16.1-③)。
4
+ * 单一来源 = `docs/core/design/MODEL-SPECS.md` §4「effort 与 off」:写面取形与「有效 off 路径」两判据同源;
5
+ * Google 的 wire 形态另由 `googleThinkingOff` 给出(本档内,形态单源)。四处生产者(CLI `/think` · CLI `/advisor` ·
6
+ * VSC 主模型面 `reasoning-mode.mjs` · VSC 面板写面 `settings-panel-write.mjs`)一律消费本档(端引核零副本——
7
+ * 副本即漂移源:VSC 全族一形 `null` 与 CLI 自定义族支 `undefined` 两处漂移已实证)。
8
8
  */
9
9
 
10
- /** 写面取形(§15.4-2 族别判据的单一实现):`spec → null | { type:"disabled" }`。
10
+ /** 写面取形(族别判据的单一实现,单源 = `docs/core/design/MODEL-SPECS.md` §4):`spec → null | { type:"disabled" }`。
11
11
  * effort 族(`thinkApi === "effort"`)⇒ `null`——载荷层 off 门首款要求 `thinking === null`
12
- * (单源 = `doc:PROVIDER.md:§6.12`;`{type:"disabled"}` 不开门 ⇒ 关思考静默失效);
12
+ * (判据住 `provider/core.mjs` 的载荷门;`{type:"disabled"}` 不开门 ⇒ 关思考静默失效);
13
13
  * 其余(type 族默认 / 自定义开值族)⇒ `{ type: "disabled" }`——type 机制原生 off 形。 */
14
14
  export function thinkOffShape(spec) {
15
15
  return spec?.thinkApi === "effort" ? null : { type: "disabled" }
16
16
  }
17
17
 
18
- /** 有效 off 路径(「何时可宣称 OFF」判据本体 = §16.4)——由 `thinkOffShape` 派生(防两处漂移):
18
+ /** Google 传输面的 off 形(wire 形)——**单源**:`provider/google.mjs` 的 generationConfig 与
19
+ * `generate-title.mjs` 的标题请求都引本函数(传输层不留判据副本;`MODEL-SPECS.md` §4「off 标记与枚举值按
20
+ * PROVIDER 的请求规则装配」)。**可宣称性不归本函数**——「能不能对用户宣称 OFF」由 `thinkOffPath` 判(CLI
21
+ * `/think` 与 VSC 徽标均读它);本函数只回答「已经要关时,Google 请求体放什么」。
22
+ * 2026-12-01 真实上游实测:`thinkingLevel:"none"` ⇒ 400 INVALID_ARGUMENT(枚举无 none——`gemini-2.5-pro` ∥
23
+ * `gemini-3-pro` ∥ `gemini-3.1-pro` ∥ `gemini-3.8-flash` 同判,模型 404 也先被它挡);`"minimal"` 在
24
+ * gemini-3.8-flash 上 ⇒ 400「not supported for this model」;`low`/`high` ⇒ 200;`thinkingBudget:0` ⇒ 200
25
+ * 但**不关闭**(缺省 158 thought token,budget:0 仍 34)。
26
+ * ⇒ 服务端强制族(`thinkAlwaysOn === true`)不发任何 thinkingConfig(关闭是 no-op);其余族发 `thinkingBudget:0`。
27
+ * **该支的受理读数缺口要说明白**:`thinkingBudget:0` 的受理只在 gemini-3.8-flash 上取到,而它属强制思考族、
28
+ * 永远不会收到这个字段;真正会收到的四条 pro/flash 行在 2026-12-01 当期 key 下均 404(不可达)⇒ 这一支的
29
+ * 受理**无真实上游读数**,与那四行的 off 宣称同属未验证,待可达时重测(台账续起)。 */
30
+ export function googleThinkingOff(spec) {
31
+ if (spec?.thinkAlwaysOn === true) return null
32
+ return { thinkingBudget: 0 }
33
+ }
34
+
35
+ /** 有效 off 路径(「何时可宣称 OFF」判据本体,单源 = `MODEL-SPECS.md` §4)——由 `thinkOffShape` 派生(防两处漂移):
19
36
  * `null` 形只有 effort 族的载荷门据它补发 `reasoning_effort:"none"` ⇒ 须枚举含 `"none"`
20
- * (无枚举 / 无 `none` ⇒ 形不发任何字段,§16.4 表「effort 族」行);`{type:"disabled"}` 形 ⇒ 达载荷层。
21
- * 两形共门 = `thinkAlwaysOn !== true`(服务端强制族:形被拒 / 恒思考 ⇒ 无效,§16.3 / §16.4 表「服务端强制族」行)。 */
37
+ * (无枚举 / 无 `none` ⇒ 形不发任何字段);`{type:"disabled"}` 形 ⇒ 达载荷层。
38
+ * 两形共门 = `thinkAlwaysOn !== true`(服务端强制族:形被拒 / 恒思考 ⇒ 无效)。 */
22
39
  export function thinkOffPath(spec) {
23
40
  if (spec?.thinkAlwaysOn === true) return false
24
41
  if (thinkOffShape(spec) === null) return (spec?.reasoningEffortEnum ?? []).includes("none")
@@ -27,7 +44,7 @@ export function thinkOffPath(spec) {
27
44
 
28
45
  /** 有效思考模式(判据本体 = `docs/core/design/AGENT-LOOP.md` §5.4 的判定次序):
29
46
  * 这一轮请求会不会真的带思考 —— 判据是「服务端的有效模式」,不是「UI 显成什么」。
30
- * 输入 `provider` = 该渠道的描述子(`thinking` ∥ `reasoningEffort` 两键的实际值)、`spec` = 核规格(可为 `null`)。
47
+ * 输入 `modelParams` = **设置层的模型语义参数**(`thinking` ∥ `reasoningEffort` 两键的实际值;2026-12-03 批起不再是渠道条目属性)、`spec` = 核规格(可为 `null`)。
31
48
  * 次序(自上而下,先命中先返回):
32
49
  * ① `thinkAlwaysOn === true` 或非空且非 `"none"` 的 `reasoningEffort` ⇒ `true`(显式要思考 / 服务端强制);
33
50
  * ② `reasoningEffort === "none"` ∥ `thinking.type === "disabled"` ⇒ `false`(两枚显式 off 形);
@@ -35,20 +52,22 @@ export function thinkOffPath(spec) {
35
52
  * ⇒ `false`——只有 effort 族有资格把 `null` 读成关闭:它的 off 形 = 置 `null` + 删 effort,且枚举含 `"none"`
36
53
  * 时载荷层才补发 `reasoning_effort:"none"`(`provider/core.mjs` 的支),此时它才是有效关闭;
37
54
  * ④ 其余 ⇒ `true`:没有任何 off 证据就不按「已关思考」静默省键(kimi 式 `thinking:null` 而枚举无 `none`、
38
- * 以及 type 族的 `thinking:null`——`null` 不是它的 off 形,载荷层的 `if (provider.thinking)` 会跳过它、
55
+ * 以及 type 族的 `thinking:null`——`null` 不是它的 off 形,载荷层的 `if (modelParams?.thinking)` 会跳过它、
39
56
  * 服务端默认照旧思考——两处都落这一支)。
40
- * 边界:两个参数都必须显式传入;`null` 是合法实参(没有渠道 ∥ 未声明族),`undefined` 点名报错,不补默认。 */
41
- export function isThinkingRequest(provider, spec) {
42
- if (provider === undefined) throw new Error("isThinkingRequest: provider is required — 传该渠道的描述子(没有渠道时传 null),本函数不替调用方补默认")
57
+ * 边界:两个参数都必须显式传入;`null` 是合法实参(没有设置对象 ∥ 未声明族),`undefined` 点名报错,不补默认。
58
+ * 2026-12-03 批(台账 #133):第一参 = **模型语义参数对象**(会话 `modelParams`),不再是 provider 渠道条目
59
+ * ——模型参数不再是渠道属性(用户裁定「不应该有任何 provider 级别的模型参数」)。 */
60
+ export function isThinkingRequest(modelParams, spec) {
61
+ if (modelParams === undefined) throw new Error("isThinkingRequest: modelParams is required — 传设置层的模型语义参数对象(没有时传 null),本函数不替调用方补默认")
43
62
  if (spec === undefined) throw new Error("isThinkingRequest: spec is required — 传该族的规格(未声明的族传 null),本函数不替调用方补默认")
44
- const effort = provider?.reasoningEffort
63
+ const effort = modelParams?.reasoningEffort
45
64
  if (spec?.thinkAlwaysOn === true) return true
46
65
  if (typeof effort === "string" && effort.trim() !== "" && effort !== "none") return true
47
66
  if (effort === "none") return false
48
- if (provider?.thinking?.type === "disabled") return false
67
+ if (modelParams?.thinking?.type === "disabled") return false
49
68
  // `null` 只有 effort 族读得成关闭(它的 off 形就是 null + 删 effort);type 族的 off 形是 {type:"disabled"},
50
- // 收到 null 只表示「没配」——载荷层 `if (provider.thinking)` 会跳过它、服务端照旧思考,不能据此判合规省键。
51
- if (provider?.thinking === null && spec?.thinkApi === "effort" && thinkOffPath(spec)) return false
69
+ // 收到 null 只表示「没配」——载荷层 `if (modelParams?.thinking)` 会跳过它、服务端照旧思考,不能据此判合规省键。
70
+ if (modelParams?.thinking === null && spec?.thinkApi === "effort" && thinkOffPath(spec)) return false
52
71
  return true
53
72
  }
54
73
 
package/token-window.mjs CHANGED
@@ -10,10 +10,12 @@
10
10
  * 消费面只剩打开态与无 agent 转口)· `overheadSegments`(非对话面六项的分段读法,越线报文两处共用)·
11
11
  * `collectStaleToolOutputs`(陈旧工具输出合格集)+ 门槛常量 `PRUNE_MIN_TOKENS`(**与合格集同住本档** ⇒ 消费方单向取用、零回指)·
12
12
  * `rebaseMeasured`(结构编辑后的实测基线重定,§3.1)。
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)。
13
+ * 窗口面(2026-11-14 · tiny 档上限批;2026-11-21 批;2026-11-28 档位上下文上限批):本档一切窗口读数取**有效窗口**
14
+ * `effectiveWindow`(`window-policy.mjs` §2.1)= min(模型窗口, 档位上限×1024),不再直读 `providerSpec().context`。
15
+ * 档位自 2026-11-28 起是入参(用户裁决:tiny 缺省 512K ∥ normal·engineering 1024K,2026-11-30 翻倍),本档消费的四个窗口入口
16
+ * (`keepTailSize` ∥ `tailBudgetTokens` ∥ `historyReading` ∥ `historyPercent`;`collectStaleToolOutputs` 同形)都收 provider + **尾参 `settings`**。
17
+ * 2026-12-03 批(用户裁定):模型窗口声明 ∥ 档位上限表均住设置层(`settings.modelContext` ∥ `settings.agent.contextCaps`),
18
+ * 不再挂到 provider 形状的对象上——provider 只留会话档位 `mode`;必填清单的单一出处 = §2.3)。
17
19
  * 保留窗面(2026-11-14 · tool-output-retention 批):`splitHistory` 的第四参 `protectFrom` 必填、无缺省——尾起点不晚于
18
20
  * 保留窗起点,压缩中段 ∥ prune 合格集 ∥ 尾部预算三面同源受益(`CONTEXT-COMPACTION.md` §1.2);起点由 `agent` 面的
19
21
  * `retentionWindowStart` 按消息身份当刻解析,本档只收这个下标(纯函数面不读 agent 状态)。
@@ -76,14 +78,15 @@ function assertTailArgs(fnName, fixedOverhead, ratio) {
76
78
  }
77
79
  }
78
80
 
79
- export function keepTailSize(provider, historyLen) {
81
+ export function keepTailSize(provider, historyLen, settings) {
80
82
  // provider is guaranteed at every call site (runAgent always builds one); the window below
81
83
  // degrades to DEFAULT_SPEC (256K) only if provider is somehow absent — acceptable
82
- // because the 40% history cap still bounds the tail. providers[].context override
83
- // (K units) is honored here (PROVIDER.md §6.15 T-C2: tail formula follows the window).
84
- // 窗口 = **有效窗口**(§2.1/§4)——它恒等于模型窗口,档位不参与(tiny 不再压窗口)。
84
+ // because the 40% history cap still bounds the tail. The modelContext override
85
+ // (K units) is honored here (PROVIDER.md §6.15: tail formula follows the window).
86
+ // 窗口 = **有效窗口**(§2.1/§4)= min(模型窗口, 档位上限)——它是尾预算的输入,档位参与。
87
+ // `settings` = 整份 config(读 `modelContext` ∥ `agent.contextCaps`)——2026-12-03 批起从会话源取,不读 provider 条目。
85
88
  // 它是**条数上限**,不是预算:一条消息的体量跨三个数量级,条数推不出容量(§4)。
86
- const ctxWindow = effectiveWindow(provider)
89
+ const ctxWindow = effectiveWindow(provider, settings)
87
90
  return Math.min(Math.max(10, Math.floor((ctxWindow / 100_000) * 30)), Math.floor(historyLen * 0.4))
88
91
  }
89
92
 
@@ -103,9 +106,11 @@ export function keepTailSize(provider, historyLen) {
103
106
  * 乘除 `ratio` 是必需的:`threshold` 是校准后的量,尾的估算要换到同一把尺上才可比。
104
107
  * `fixedOverhead` ∥ `ratio` 都必填无缺省(§2.3)。
105
108
  */
106
- export function tailBudgetTokens(provider, fixedOverhead, ratio) {
109
+ export function tailBudgetTokens(provider, fixedOverhead, ratio, thresholdOverride = null, settings) {
107
110
  assertTailArgs("tailBudgetTokens", fixedOverhead, ratio)
108
- const threshold = policyBudget(provider).threshold
111
+ const threshold = Number.isFinite(thresholdOverride) && thresholdOverride > 0
112
+ ? thresholdOverride
113
+ : policyBudget(provider, undefined, undefined, settings).threshold
109
114
  return Math.max(0, Math.floor(threshold / ratio) - fixedOverhead - SUMMARY_TOKEN_ESTIMATE)
110
115
  }
111
116
 
@@ -308,7 +313,7 @@ export function overheadSegments(usage) {
308
313
  * 机读线按轮嵌套:一切计量在拍平视图上算(外层条数是轮数,不是消息数);基线位置是 `{ turn, msg }`。
309
314
  * `threshold` = 该回合判定所用值(`agent._ctxBasis.threshold`——核 `agent.mjs` / VSC `checkAndCompact` 各一处暂存);
310
315
  * 缺省回退 `resolveCompactThreshold`(退化面①)。
311
- * `window` = **有效窗口** `effectiveWindow(agent.provider)`(§2.1)——它恒等于模型窗口,
316
+ * `window` = **有效窗口** `effectiveWindow(agent.provider)`(§2.1)= min(模型窗口, 档位上限),
312
317
  * 而这个值就是 stats 首行百分比的分母(agent 在场,不靠参数透传)。
313
318
  * `overhead` = `system + tools`(`fixed` 的子集,模型与参数预判面读它);压缩链读 `fixed − compactionSummary`,不读它。
314
319
  * @returns {{basis:"measured"|"estimated", total, history, system, tools, retained, inject, compactionSummary, sessionHead, pending, fixed, overhead, fixedFloor, threshold, window}}
@@ -346,8 +351,8 @@ export function contextUsage(agent, extras) {
346
351
  overhead: face.system + face.tools,
347
352
  fixedFloor: Math.round(((face.fixed - face.compactionSummary) + COMPACTION_SUMMARY_TOKEN_ESTIMATE) * ratio),
348
353
  threshold: agent?._ctxBasis?.threshold
349
- ?? resolveCompactThreshold(agent?.config?.agent?.compactThreshold, agent?.provider).value,
350
- window: effectiveWindow(agent?.provider),
354
+ ?? resolveCompactThreshold(agent?.config?.agent?.compactThreshold, agent?.provider, agent?.config).value,
355
+ window: effectiveWindow(agent?.provider, agent?.config),
351
356
  }
352
357
  }
353
358
 
@@ -356,6 +361,18 @@ export function tokenKey(provider) {
356
361
  return `${provider?.format ?? "openai"}:${provider?.model ?? ""}`
357
362
  }
358
363
 
364
+ /** 校准比下界(`CONTEXT-COMPACTION.md` §3,2026-12-03 越窗守卫统一测度批):偏差方向不预设,样本自己说话。
365
+ * 下界只挡退化样本(比 ≈ 0 会把全部估算支清零),不挡样本给出的纠偏方向:本机实测样本
366
+ * `num 4,710,952 ÷ den 5,617,511 ≈ 0.839`(估算**偏高**),旧下界 1 把这个方向整个关掉,
367
+ * 于是守卫按偏高的估算判、把装得下的请求拦在本地。±2 倍的带足以容下该实测值与各模型的真实偏差。 */
368
+ export const TOKEN_RATIO_MIN = 0.5
369
+
370
+ /** 校准比的钳位(两处共用):`num` / `den` 由 `validSample` 保证有限且 `den > 0`;
371
+ * 钳位只在下界侧——上界侧(估算偏低 ⇒ 比 > 1)方向安全(早压),不设帽。 */
372
+ function clampRatio(ratio) {
373
+ return Number.isFinite(ratio) && ratio > TOKEN_RATIO_MIN ? ratio : TOKEN_RATIO_MIN
374
+ }
375
+
359
376
  /**
360
377
  * 估算自校准采样(§6.17「估算自校准」)——池化比:`num += usage.prompt_tokens`、`den += estPrompt`
361
378
  * (分子分母同取输入侧口径;`estPrompt` 由发送面随 result 带回,与净判同一个值)。
@@ -372,9 +389,9 @@ export function recordTokenSample(agent, provider, estPrompt, usage) {
372
389
  if (agent._tok?.key !== key) agent._tok = { key, num: 0, den: 0, est: ESTIMATOR_VERSION }
373
390
  agent._tok.num += prompt
374
391
  agent._tok.den += estPrompt
375
- // 下界 = 1:已知偏差方向是估算偏低;比 < 1 会把全部估算支缩小、重开「该压没压」原始故障,
376
- // 保守方向不取(仅一侧校准,零新魔数)。
377
- agent._tokRatio = Math.max(1, agent._tok.num / agent._tok.den)
392
+ // 钳位到下界(`TOKEN_RATIO_MIN`):旧下界 1 假定估算偏低,而实测方向相反——那个下界把纠偏通道关掉,
393
+ // 全部估算支虚高、把装得下的请求拦在本地。方向交回样本,只留 ±2 倍的退化保护。
394
+ agent._tokRatio = clampRatio(agent._tok.num / agent._tok.den)
378
395
  }
379
396
 
380
397
  /**
@@ -395,7 +412,7 @@ export function tokenSampleOf(agent) {
395
412
  export function restoreTokenSample(agent, sample, provider) {
396
413
  const ok = validSample(sample, provider)
397
414
  agent._tok = ok
398
- agent._tokRatio = ok ? Math.max(1, ok.num / ok.den) : 1
415
+ agent._tokRatio = ok ? clampRatio(ok.num / ok.den) : 1
399
416
  return ok !== null
400
417
  }
401
418
 
@@ -404,7 +421,7 @@ export function restoreTokenSample(agent, sample, provider) {
404
421
  * 口径版本(`est === ESTIMATOR_VERSION`——口径变了,旧样本的 `den` 与新估算不同量纲)· 键匹配
405
422
  * (`key === tokenKey(provider)`——恢复后模型已换 ⇒ 不复用)。全过 ⇒ `{ key, num, den, est }`;任一不过 ⇒ `null`
406
423
  * (回到未校准档,不抛——坏样本不得拦住会话恢复 / 读数)。恢复面 `restoreTokenSample` 与读数面 `sampleRatio`
407
- * 同取本函数:同一判定,不写第二份。④ 比 < 1 不必单独判——由 `max(1, …)` 兜底。
424
+ * 同取本函数:同一判定,不写第二份。比值的钳位不在本函数——由 `clampRatio` 在下界处兜底。
408
425
  */
409
426
  function validSample(sample, provider) {
410
427
  if (!sample || typeof sample !== "object" || Array.isArray(sample)) return null
@@ -428,11 +445,11 @@ function validSample(sample, provider) {
428
445
  * 都把非正值读作「不显示」(CLI `ctxPct > 0` · VSC 分子为假回 `null` · 桌面 `usageFrameWanted` 不发帧)
429
446
  * ⇒ 读数**缺席**(不会是错数);给缺省 1 则相反——忘传处静默显示未校准读数,看着完全正常而差一整个校准比。
430
447
  * 两种形状里只有后者会被当作事实读走,所以宁可缺席。
431
- * `workMode` 不是入参(§2.3):分母的取法只有一种,窗口恒等于模型窗口,档位不参与预算。
448
+ * 档位经 `settings`(会话源)参与窗口(§2.1):分母取自 min(模型窗口, 上限×1024)。
432
449
  * 空历史 ⇒ 0(状态行的 `ctxPct > 0` 显示门在端侧,不入本函数面)。
433
450
  */
434
- export function historyReading(history, provider, ratio) {
435
- const budget = policyBudget(provider)
451
+ export function historyReading(history, provider, ratio, settings) {
452
+ const budget = policyBudget(provider, undefined, undefined, settings)
436
453
  const tokens = Math.round(estimateTokens(history ?? []) * ratio)
437
454
  return {
438
455
  tokens,
@@ -469,7 +486,7 @@ export function contextReading(agent, extras) {
469
486
  throw new Error("contextReading: `extras` is required (no default) — pass agent?._ctxBasis?.overhead ?? {}")
470
487
  }
471
488
  const usage = contextUsage(agent, extras)
472
- const budget = policyBudget(agent?.provider)
489
+ const budget = policyBudget(agent?.provider, undefined, undefined, agent?.config)
473
490
  return {
474
491
  tokens: usage.total,
475
492
  pct: Math.round((usage.total / budget.limit) * 100),
@@ -484,9 +501,9 @@ export function contextReading(agent, extras) {
484
501
 
485
502
  /** 状态行百分比薄转口(名面与 export 不变):`historyReading` 的 `pct`——打开态读数(`sessionReading`)
486
503
  * 与无 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
504
+ * 第三参 `ratio` 同 `historyReading`:无缺省;第四参 `settings` = 整份 config(会话源,读 `contextCaps`)——2026-12-03 批。 */
505
+ export function historyPercent(history, provider, ratio, settings) {
506
+ return historyReading(history, provider, ratio, settings).pct
490
507
  }
491
508
 
492
509
  /** 估算校准比(§6.17)——`agent._tokRatio` 的**唯一**读出点(中性值 1 的唯一出处):
@@ -497,10 +514,10 @@ export function tokenRatioOf(agent) {
497
514
  }
498
515
 
499
516
  /** 槽样本 ⇒ 校准比(§6.17.1 链二读数面):判定与 `restoreTokenSample`(恢复面)同一份 `validSample`,
500
- * 好样本 ⇒ `max(1, num / den)`,坏样本 ⇒ `1`(下界 1 与 `recordTokenSample` 同——偏差方向已知是估算偏低)。 */
517
+ * 好样本 ⇒ `clampRatio(num / den)`,坏样本 ⇒ `1`(钳位与 `recordTokenSample` 同——见 `TOKEN_RATIO_MIN`)。 */
501
518
  export function sampleRatio(sample, provider) {
502
519
  const s = validSample(sample, provider)
503
- return s ? Math.max(1, s.num / s.den) : 1
520
+ return s ? clampRatio(s.num / s.den) : 1
504
521
  }
505
522
 
506
523
  /** 陈旧工具输出门槛(§6.16.3 判据③):低于门槛的替换是净增 token(stub 本身有长度)——常量与合格集同住本档。 */
@@ -510,15 +527,15 @@ export const PRUNE_MIN_TOKENS = 200
510
527
  * 陈旧工具输出合格集(§6.16.3——三条件合取,单源实现):① `role === "tool"`;② **保护尾之外**(复用 `splitHistory` 的同一 `tailStart`——不新增第二处切割判据);③ 估算 ≥ `PRUNE_MIN_TOKENS`。
511
528
  * 返回逐条计数面(prune 回执 + stats 两处消费):`indexes` 合格索引(升序)· `tokens` 合格集估算和 · `candidates` 全史 tool 结果数 · `tailKept` 保护尾内保留数 · `belowMin` 门槛下跳过数 · `tailCount` 保护尾消息数。
512
529
  * **短历史(无中段)⇒ 合格集为空**(no-op——§6.16.3 边界)。
513
- * `workMode` 不是入参(§2.3):保护尾与压缩面同取有效窗口(恒等于模型窗口),档位不参与。
530
+ * 档位经 `settings`(会话源)参与窗口(§2.1):保护尾与压缩面同取有效窗口 = min(模型窗口, 档位上限)。
514
531
  * `protectFrom` 无缺省(`CONTEXT-COMPACTION.md` §1.2):保留窗起点,原样转给 `splitHistory` 的第四参。
515
532
  * 拿不到保留窗的调用方传 `history.length`(= 不收紧);留一个缺省就是把「保留窗内该不该被清」
516
533
  * 静默定给调用方——这一档正是本批要保护的格。
517
534
  * `fixedOverhead` ∥ `ratio` 无缺省(§2.3):尾预算的减法链要用它们;四个消费点各自算好再传(§2.3 表)。
518
535
  */
519
- export function collectStaleToolOutputs(history, provider, protectFrom, fixedOverhead, ratio) {
536
+ export function collectStaleToolOutputs(history, provider, protectFrom, fixedOverhead, ratio, settings) {
520
537
  const h = Array.isArray(history) ? history : []
521
- const split = splitHistory(h, keepTailSize(provider, h.length), tailBudgetTokens(provider, fixedOverhead, ratio), protectFrom)
538
+ const split = splitHistory(h, keepTailSize(provider, h.length, settings), tailBudgetTokens(provider, fixedOverhead, ratio, null, settings), protectFrom)
522
539
  // 无中段(短历史)⇒ 可摘要面为空 ⇒ **全史即保护尾**(tailStart = 0——合格集必为空,同压缩面 no-op)
523
540
  const tailStart = split ? split.tailStart : 0
524
541
  const r = { indexes: [], tokens: 0, candidates: 0, tailKept: 0, belowMin: 0, tailCount: h.length - tailStart }
package/tool-args.mjs CHANGED
@@ -47,13 +47,14 @@ export function describeToolArgs(name, args) {
47
47
  const ver = a.verify ? ` · verify: ${String(a.verify).replace(/\s+/g, " ").trim().slice(0, 32)}` : ""
48
48
  return `${tag}${head}${ver}`.trim()
49
49
  }
50
- case "peek": {
51
- const mode = a.mode ? String(a.mode) : "outline"
52
- const target = a.glob
53
- ? String(a.glob)
54
- : Array.isArray(a.paths) ? a.paths.slice(0, 2).join(", ") + (a.paths.length > 2 ? ` (+${a.paths.length - 2})` : "") : ""
55
- const q = a.query ? ` · /${String(a.query)}/` : ""
56
- return `${mode}${target ? " " + target : ""}${q}`.slice(0, 80)
50
+ case "repo_graph": {
51
+ const action = a.action ? String(a.action) : "context"
52
+ const target = a.query
53
+ ? String(a.query)
54
+ : a.glob
55
+ ? String(a.glob)
56
+ : Array.isArray(a.paths) ? a.paths.slice(0, 2).join(", ") + (a.paths.length > 2 ? ` (+${a.paths.length - 2})` : "") : ""
57
+ return `${action}${target ? " " + target : ""}`.slice(0, 80)
57
58
  }
58
59
  case "subagent": case "coder": case "explore": case "plan": case "eng-coder": case "eng-designer": {
59
60
  const task = String(a.task ?? "").replace(/\s+/g, " ").trim()
@@ -75,7 +76,6 @@ export function describeToolArgs(name, args) {
75
76
  return action || JSON.stringify(a)
76
77
  }
77
78
  case "lsp": return [a.subcommand, a.uri].filter(Boolean).map(String).join(" ")
78
- case "repo_outline": return a.path ? String(a.path) : ""
79
79
  case "checkpoint": return [a.checkpointAction ?? a.action, a.checkpointId, a.path].filter(Boolean).map(String).join(" ")
80
80
  case "git": return [a.action, a.ref, a.name, a.message].filter(Boolean).map(String).join(" ").slice(0, 60)
81
81
  case "batch": {
package/tool-docs/bash.md CHANGED
@@ -1,2 +1,2 @@
1
- Execute a shell command and return stdout+stderr.
1
+ Execute a shell command and return stdout+stderr. Do not use bash to read, search, or list repo source/doc files (use read, grep, glob, ls, or repo_graph instead).
2
2
  {{knowledge:tool-bash}}
package/tool-docs/glob.md CHANGED
@@ -1,3 +1,5 @@
1
- Find files by glob pattern and return the matching paths.
1
+ Find files by glob pattern: one summary line first (match count, orchestrator total with `(N shown)`, contracts, clusters), then the complete matching path list in original order. Each code row carries ` · ←N · →hits N` — how many source files import it repo-wide (the same number `ls` shows) and how many files inside this same match set it imports. `→hits 0` does not imply no dependencies outside the match set, so these two numbers do not establish that a file is isolated. The summary scales with match count (1–12: orchestrator total and sample, contracts, direct-import tests; 13–100: clusters with per-cluster file and internal-edge counts, all direct contracts with requirements/design pair paths, and direct-import tests; >100: also `architecture` and the shared-orchestrator sample, with only contracts filtered to shared coverage while direct-import tests remain). Every number in it is a total — a display sample is always labelled `(N shown)` and a truncation says `… N omitted`. No per-edge detail — use `repo_graph(context)` for that. Nothing ever hides or reorders matching paths.
2
+
3
+ For dependency, ownership, or impact questions rather than filename discovery, use `repo_graph`; for a repository-wide architecture survey, use `repo_graph(overview)`.
2
4
 
3
5
  {{knowledge:tool-glob}}
package/tool-docs/goal.md CHANGED
@@ -1,3 +1,3 @@
1
- Manage a long-running autonomous goal.
1
+ Set, cancel, or inspect a long-running goal.
2
2
 
3
- {{knowledge:tool-goal}}
3
+ {{knowledge:tool-goal}}
package/tool-docs/grep.md CHANGED
@@ -1,3 +1,5 @@
1
- Search file contents with a regex and return the matching lines with their file paths and line numbers.
1
+ Search file contents with a regex across a directory, file, or multiple paths; prefer over bash/Select-String. Use it for exact content locations; use `repo_graph` for ownership and dependency questions, `glob` for filename patterns, and `ls` for directory browsing.
2
+
3
+ The graph notes always land **on the hits themselves** (there is no on/off switch): each file's first hit is suffixed ` · ←N` (how many code files import it), and the largest N in this result set is additionally marked as the result set's most-imported (every tie is marked). A file with importers then carries one indented line naming up to three of them plus a remainder count (the line's label and that most-imported marker are rendered in Chinese), followed by a second indented line naming that file's direct authoritative/pair docs and direct-import tests. Those direct docs and tests cover **every hit file**, not just the first three, and use repository-relative paths; only full context-pack expansion remains capped at three anchors. The code-hit design label explicitly requires a full-file `read` before editing. Indirect or document-covered tests, upstream callers, siblings and deps are left to `repo_graph(context)`. There is no trailing recommendation block, and only degradation notices (graph unavailable) are appended. For a doc hit the group is labelled as related documents (doc-cites neighbours) rather than design/test.
2
4
 
3
5
  {{knowledge:tool-grep}}
package/tool-docs/ls.md CHANGED
@@ -1,3 +1,9 @@
1
- List directory contents with type, size, and modification time.
1
+ List directory contents with type, size, and modification time, with each entry's own imports, callers, direct-import tests or subdirectory signals noted on its row. Cross-entry relations close the normal listing in a trailing Relations block; `byDirectory` omits that file-level relation block because directory rows already carry the directory summary.
2
+
3
+ Directory rows always carry a size summary (`1640 code, 75 test (2 at this level)`) in both listing forms — with and without `byDirectory` — plus cross-directory inbound edges (`←`), internal edges (`⟳`) and top hubs with their inbound count. A directory with no indexed file says `no indexed files` and how many process docs were excluded there.
4
+
5
+ `recursive` descends into subdirectories; `byDirectory` drops the file rows, puts the recursive counts on each directory row, and omits the file-level Relations block. Graph folding never hides directory entries.
6
+
7
+ For a known file or symbol's ownership and impact, use `repo_graph(context)`; use `glob` for filename-pattern discovery.
2
8
 
3
9
  {{knowledge:tool-ls}}
package/tool-docs/read.md CHANGED
@@ -1,3 +1,3 @@
1
- Read a text file and return its numbered lines.
1
+ Read a text file and return its numbered lines (safe built-in truncation & total line count; prefer directly over probing file length via bash). Module panorama, location and pre-edit must-reads: `repo_graph` first.
2
2
 
3
3
  {{knowledge:tool-read}}
@@ -0,0 +1,3 @@
1
+ Primary multi-language CODE + DOC knowledge & architecture graph (read-only; JS/TS including monorepo workspaces & tsconfig paths, Python, C# including same-namespace & global using, Go, Rust, SQL + Markdown docs; auto-synced by mtime, zero manual scan). **Reach for it first** for structure, ownership, location, upstream/downstream and pre-edit must-reads: get a file/symbol/doc/topic-keyword's must-read context pack (`context`, supports Chinese/English concepts & space-separated multi-keywords via Markdown H1-H4 headings), check reverse change impact (`impact`), inspect repo architecture hubs & directory deps (`overview`), batch-inspect Markdown section outlines or extract matching doc sections (`outline`), list file/doc refs & broken links (`refs`), or trace one exported symbol's definition and all importers/citers (`symbol`). **High-leverage — one call replaces many rounds of grep/read**: `context` returns a file/symbol's must-read set in one shot, `overview` maps a whole repo, `outline` scans all matching docs without a file-count cap. `target` is optional (defaults to the session cwd) and works at any level, multi-project workspaces included.
2
+
3
+ {{knowledge:tool-repo-graph-read}}
@@ -0,0 +1,3 @@
1
+ Primary multi-language CODE + DOC knowledge & architecture graph (JS/TS including monorepo workspaces & tsconfig paths, Python, C# including same-namespace & global using, Go, Rust, SQL + Markdown docs; auto-synced by mtime, zero manual scan). **Reach for it first** for structure, ownership, location, upstream/downstream and pre-edit must-reads: get a file/symbol/doc/topic-keyword's must-read context pack (`context`, supports Chinese/English concepts & space-separated multi-keywords via Markdown H1-H4 headings), check reverse change impact (`impact`), inspect repo architecture hubs & directory deps (`overview`), batch-inspect Markdown section outlines or extract matching doc sections (`outline`), list file/doc refs & broken links (`refs`), or trace one exported symbol's definition and all importers/citers (`symbol`). **High-leverage — one call replaces many rounds of grep/read**: `context` returns a file/symbol's must-read set in one shot, `overview` maps a whole repo, `outline` scans all matching docs without a file-count cap. `target` is optional (defaults to the session cwd) and works at any level, multi-project workspaces included.
2
+
3
+ {{knowledge:tool-repo-graph}}
package/tool-docs/tree.md CHANGED
@@ -1,3 +1,3 @@
1
- Generate a directory tree of the codebase.
1
+ Generate a directory tree of the codebase, or a per-directory recursive file-count summary (`count`) — the summary also carries graph signals (cross-directory inbound edges, top hub, directory-level cycles, entry files; `n/a` when the graph is unavailable).
2
2
 
3
3
  {{knowledge:tool-tree}}