@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.
- package/CHANGELOG.md +27 -0
- package/abort-provenance.mjs +23 -0
- package/advisor/citations.mjs +5 -1
- package/advisor/compaction.mjs +13 -10
- package/advisor/history.mjs +6 -1
- package/advisor/loop.mjs +35 -10
- package/advisor/messages.mjs +31 -43
- package/advisor/project-context.mjs +49 -45
- package/advisor/run.mjs +82 -26
- package/advisor.mjs +40 -11
- package/agent/assemble.mjs +5 -5
- package/agent/chat-call.mjs +21 -1
- package/agent/completion.mjs +1 -20
- package/agent/dispatch-gates.mjs +8 -3
- package/agent/dispatch-run.mjs +131 -20
- package/agent/dispatch.mjs +23 -22
- package/agent/family-tools.mjs +4 -7
- package/agent/goal-judge.mjs +99 -0
- package/agent/goal-state.mjs +96 -0
- package/agent/helpers.mjs +13 -4
- package/agent/offload.mjs +1 -1
- package/agent/planning-graph-guardrail.mjs +224 -0
- package/agent/planning-prompt.mjs +179 -0
- package/agent/planning-step.mjs +460 -173
- package/agent/post-turn.mjs +23 -33
- package/agent/record-results.mjs +8 -5
- package/agent/run-stages.mjs +18 -38
- package/agent/run-start.mjs +26 -19
- package/agent/setup-reminders.mjs +16 -14
- package/agent/setup.mjs +3 -2
- package/agent/spawn-child.mjs +17 -4
- package/agent/suspension.mjs +42 -21
- package/agent/task-lifecycle.mjs +165 -52
- package/agent/timers.mjs +9 -1
- package/agent/turn-loop.mjs +160 -69
- package/agent/turn-projection.mjs +26 -15
- package/agent/turn-task-state.mjs +4 -4
- package/agent/write-gate-ledger.mjs +1 -1
- package/agent/write-gate.mjs +14 -11
- package/agent-tools/advisor-async.mjs +2 -0
- package/agent-tools/advisor-launch.mjs +27 -13
- package/agent-tools/advisor-settle.mjs +19 -18
- package/agent-tools/advisor.mjs +90 -13
- package/agent-tools/bash-async.mjs +3 -3
- package/agent-tools/batch-ledger-bind.mjs +8 -5
- package/agent-tools/batch-read.mjs +42 -0
- package/agent-tools/batch-record-write.mjs +20 -12
- package/agent-tools/batch-segment-vocab.mjs +6 -4
- package/agent-tools/batch-skeleton.mjs +43 -12
- package/agent-tools/consult.mjs +5 -1
- package/agent-tools/context.mjs +5 -4
- package/agent-tools/design-slots.mjs +7 -4
- package/agent-tools/design-token.mjs +3 -2
- package/agent-tools/doc-graph.mjs +257 -95
- package/agent-tools/escalate-async.mjs +4 -1
- package/agent-tools/goal.mjs +28 -95
- package/agent-tools/plan.mjs +1 -1
- package/agent-tools/review-facts.mjs +56 -7
- package/agent-tools/settings.mjs +35 -1
- package/agent-tools/ssh-transport.mjs +23 -22
- package/agent-tools/step.mjs +24 -4
- package/agent-tools/subagent-actions.mjs +6 -2
- package/agent-tools/subagent-async.mjs +4 -2
- package/agent-tools/subagent.mjs +1 -1
- package/agent-tools/task.mjs +73 -65
- package/agent-tools.mjs +3 -3
- package/agent.mjs +12 -3
- package/auto-think.mjs +16 -3
- package/browser/actions.mjs +5 -1
- package/browser/cdp.mjs +1 -1
- package/browser/pool.mjs +110 -17
- package/compaction-work-state.mjs +103 -13
- package/compress-form.mjs +29 -3
- package/config-defaults.mjs +27 -3
- package/config-io.mjs +3 -14
- package/config-normalize.mjs +24 -4
- package/config-presets.mjs +40 -26
- package/config-warn.mjs +30 -0
- package/config.mjs +139 -63
- package/context-degrade.mjs +4 -4
- package/context-push.mjs +20 -9
- package/context.mjs +65 -20
- package/doc-graph/anchors.mjs +39 -40
- package/doc-graph/clusters.mjs +49 -0
- package/doc-graph/code-parsers.mjs +494 -0
- package/doc-graph/context-pack.mjs +392 -0
- package/doc-graph/dir-signals.mjs +228 -0
- package/doc-graph/edges.mjs +231 -0
- package/doc-graph/format.mjs +70 -0
- package/doc-graph/gc-cmd.mjs +104 -0
- package/doc-graph/gc.mjs +112 -0
- package/doc-graph/glob-work-graph.mjs +307 -0
- package/doc-graph/golden-set.mjs +131 -0
- package/doc-graph/ls-work-graph.mjs +534 -0
- package/doc-graph/outline.mjs +377 -0
- package/doc-graph/output-annotations.mjs +85 -0
- package/doc-graph/process-docs.mjs +68 -0
- package/doc-graph/read-work-graph.mjs +91 -0
- package/doc-graph/rebuild-cmd.mjs +75 -0
- package/doc-graph/resolvers.mjs +322 -0
- package/doc-graph/roots.mjs +86 -0
- package/doc-graph/schema.mjs +110 -0
- package/doc-graph/search-augment.mjs +418 -0
- package/doc-graph/store.mjs +231 -0
- package/doc-graph/target-resolve.mjs +352 -0
- package/doc-graph/walk.mjs +87 -0
- package/doc-graph.mjs +583 -707
- package/explore-distill.mjs +52 -17
- package/generate-title.mjs +7 -4
- package/ledger-close.mjs +6 -6
- package/ledger-cmd.mjs +3 -3
- package/ledger-consistency.mjs +8 -6
- package/ledger-db.mjs +45 -10
- package/ledger-migrate.mjs +25 -10
- package/ledger-read.mjs +1 -1
- package/ledger-write-ops.mjs +6 -6
- package/ledger.mjs +2 -2
- package/model-context.mjs +54 -18
- package/model-specs.mjs +86 -67
- package/package.json +1 -1
- package/prompt-overlays.mjs +3 -3
- package/prompts/advisor-round1.md +6 -5
- package/prompts/common.md +16 -6
- package/prompts/consult-base.md +2 -1
- package/prompts/discipline-engineering.md +1 -1
- package/prompts/discipline-normal.md +12 -8
- package/prompts/knowledge/doc-lookup.md +2 -2
- package/prompts/knowledge/normal-batch-discipline.md +2 -2
- package/prompts/knowledge/normal-delivery-collaboration.md +3 -3
- package/prompts/knowledge/tool-advisor.md +2 -2
- package/prompts/knowledge/tool-apply-patch.md +1 -1
- package/prompts/knowledge/tool-bash.md +2 -2
- package/prompts/knowledge/tool-batch.md +4 -4
- package/prompts/knowledge/tool-glob.md +9 -2
- package/prompts/knowledge/tool-goal.md +9 -6
- package/prompts/knowledge/tool-grep.md +7 -2
- package/prompts/knowledge/tool-ls.md +11 -5
- package/prompts/knowledge/tool-lsp.md +1 -1
- package/prompts/knowledge/tool-operations.md +3 -2
- package/prompts/knowledge/tool-plan.md +1 -1
- package/prompts/knowledge/tool-read.md +7 -6
- package/prompts/knowledge/tool-repo-graph-read.md +12 -0
- package/prompts/knowledge/tool-repo-graph.md +12 -0
- package/prompts/knowledge/tool-step.md +1 -1
- package/prompts/knowledge/tool-subagent.md +2 -2
- package/prompts/knowledge/tool-task.md +10 -9
- package/prompts/knowledge/tool-tree.md +7 -1
- package/prompts/persona-eng-coder.md +1 -1
- package/prompts/persona-eng-designer.md +1 -1
- package/prompts/persona-engineering.md +2 -1
- package/prompts/persona-explore.md +1 -1
- package/prompts/persona-normal.md +7 -6
- package/prompts/persona-plan.md +2 -2
- package/prompts/planning-next-moves.md +7 -8
- package/provider/anthropic.mjs +53 -51
- package/provider/core.mjs +85 -34
- package/provider/errors.mjs +33 -10
- package/provider/google.mjs +244 -37
- package/provider/list-models.mjs +28 -14
- package/provider/responses-request.mjs +15 -9
- package/provider/responses.mjs +10 -8
- package/provider/sse.mjs +3 -6
- package/proxy-transport.mjs +228 -119
- package/rules-file.mjs +79 -0
- package/rules.mjs +13 -51
- package/session-lifecycle.mjs +32 -20
- package/team-ledger.mjs +7 -7
- package/think-off.mjs +37 -18
- package/token-window.mjs +48 -31
- package/tool-args.mjs +8 -8
- package/tool-docs/bash.md +1 -1
- package/tool-docs/glob.md +3 -1
- package/tool-docs/goal.md +2 -2
- package/tool-docs/grep.md +3 -1
- package/tool-docs/ls.md +7 -1
- package/tool-docs/read.md +1 -1
- package/tool-docs/repo_graph-read.md +3 -0
- package/tool-docs/repo_graph.md +3 -0
- package/tool-docs/tree.md +1 -1
- package/tools/bash.mjs +53 -8
- package/tools/browser.mjs +4 -4
- package/tools/file.mjs +34 -7
- package/tools/glob-dialect.mjs +57 -7
- package/tools/index.mjs +3 -7
- package/tools/patch.mjs +8 -7
- package/tools/process-doc-mark.mjs +13 -0
- package/tools/search.mjs +152 -37
- package/tools/shared.mjs +6 -0
- package/tools/tree.mjs +211 -8
- package/window-policy.mjs +205 -126
- package/prompts/knowledge/tool-doc-graph-read.md +0 -20
- package/prompts/knowledge/tool-doc-graph.md +0 -49
- package/prompts/knowledge/tool-peek.md +0 -10
- package/prompts/knowledge/tool-repo-outline.md +0 -4
- package/tool-docs/doc_graph-read.md +0 -3
- package/tool-docs/doc_graph.md +0 -3
- package/tool-docs/peek.md +0 -3
- package/tool-docs/repo_outline.md +0 -3
- package/tools/peek.mjs +0 -447
package/config.mjs
CHANGED
|
@@ -14,8 +14,15 @@
|
|
|
14
14
|
import { existsSync, readFileSync } from "node:fs"
|
|
15
15
|
import { parseModelRef, resolveChannelModel, resolveProviderPlan, resolveRuntimeProvider, defaultModelReason } from "./model-ref.mjs"
|
|
16
16
|
// 老形态迁移核(M7 v2——纯函数零依赖——本文件超 500 行硬限拆分,VSC 同构文件)
|
|
17
|
-
import { migrateLegacyModelFields, resolveWorkMode } from "./config-migrate.mjs"
|
|
17
|
+
import { migrateLegacyModelFields, resolveWorkMode, WORK_MODES } from "./config-migrate.mjs"
|
|
18
18
|
import { expandHome } from "./expand-home.mjs"
|
|
19
|
+
// stream 规则合并 = 装载期归一(B7 3a):`.thincoder/rules/*.md` 文件规则并入 `agent.streamRules`。
|
|
20
|
+
// 2026-11-30 从 `agent/assemble.mjs` 移入本档——住在 `assembleAgent` 里时只有 CLI/桌面拿得到,
|
|
21
|
+
// VSC 端只能自己再合一遍(端差)。
|
|
22
|
+
// 2026-12-01:合并实体住**叶档** `./rules-file.mjs`,不经 `rules.mjs` —— 后者 import
|
|
23
|
+
// `agent/helpers.mjs`,而 `helpers` 再出口 `offload.mjs`(`configDir` 来自本档)⇒ 直连
|
|
24
|
+
// `rules.mjs` 会成环 `config → rules → helpers → offload → config`(实测 TDZ,5 个集成用例连带红)。
|
|
25
|
+
import { mergeFileRules } from "./rules-file.mjs"
|
|
19
26
|
// 核内单一读写面 + 预设表(§2.5 #129 / #131——拆档以容纳 500 行硬限)
|
|
20
27
|
import {
|
|
21
28
|
PROVIDER_PRESETS, presetToEntry, configDir, configPath, _setConfigPathForTest, _resetConfigPathForTest,
|
|
@@ -46,16 +53,18 @@ import { isThinkingRequest } from "./think-off.mjs"
|
|
|
46
53
|
export { isThinkingRequest }
|
|
47
54
|
// 上下文解析链的取值校验单点(PROVIDER.md §6.15):装载归一与读面共用一个谓词。
|
|
48
55
|
import { positiveInt, warnContextOnce } from "./model-context.mjs"
|
|
56
|
+
// 值告警的唯一出口(`CONFIG.md` §2.4):stderr 不是终端时静默——装载期告警的读者是改文件的人,
|
|
57
|
+
// 被当子进程拉起时它只是调用方回执里的噪声。
|
|
58
|
+
import { warnConfig } from "./config-warn.mjs"
|
|
49
59
|
|
|
50
60
|
|
|
51
|
-
// 预算族(`outputReserve` ∥ `usableWindow` ∥ `requestBudget` ∥ `policyBudget` ∥ `effectiveWindow` ∥
|
|
52
|
-
// `resolveCompactThreshold` ∥ `
|
|
61
|
+
// 预算族(`outputReserve` ∥ `scaledOutputReserve` ∥ `usableWindow` ∥ `requestBudget` ∥ `policyBudget` ∥ `effectiveWindow` ∥
|
|
62
|
+
// `resolveCompactThreshold` ∥ `COMPACT_TOTAL_RATIO` ∥ 两个注入余量常量)居 `window-policy.mjs`——`CONTEXT-COMPACTION.md` §2.1 ∥
|
|
53
63
|
// §2.2 把「窗口事实」与「窗口策略」两件事分开,本档越 500 行硬限按设计给的候选线抽出;以下 re-export
|
|
54
|
-
// 保既有导入面(同 `model-specs.mjs` 拆分形态)。`resolveCompactThreshold`
|
|
55
|
-
|
|
56
|
-
import { nonNegativeIntValue, resolveCompactThreshold } from "./window-policy.mjs"
|
|
64
|
+
// 保既有导入面(同 `model-specs.mjs` 拆分形态)。`resolveCompactThreshold` 在本档装载期自用(auto 档判定:显式值还是派生线),故先 import 再转口。
|
|
65
|
+
import { nonNegativeIntValue, positiveIntValue, resolveCompactThreshold, resolveContextCaps } from "./window-policy.mjs"
|
|
57
66
|
export {
|
|
58
|
-
|
|
67
|
+
COMPACT_TOTAL_RATIO, OUTPUT_RESERVE_FLOOR_TOKENS, INJECT_HEADROOM_MAX_TOKENS, INJECT_HEADROOM_RATIO, effectiveWindow, outputReserve, scaledOutputReserve, usableWindow, requestBudget, policyBudget, resolveCompactThreshold,
|
|
59
68
|
} from "./window-policy.mjs"
|
|
60
69
|
|
|
61
70
|
/**
|
|
@@ -72,14 +81,16 @@ export function isBailianHost(baseURL) {
|
|
|
72
81
|
* qwen3.x on Bailian defaults to thinking ON, so an explicit off must send enable_thinking:false
|
|
73
82
|
* or the server silently keeps thinking. Whitelist: model name starts with "qwen" (excluding the
|
|
74
83
|
* non-thinking qwen3-coder line) AND the provider points at a Bailian host.
|
|
75
|
-
*
|
|
76
|
-
*
|
|
84
|
+
* modelParams.thinking === null → false (explicit off: /think off, panel off — NF1 convention)
|
|
85
|
+
* modelParams.reasoningEffort → true (effort tier implies thinking on; rides with reasoning_effort)
|
|
77
86
|
* otherwise → undefined (field omitted — server default stays, no behavior change)
|
|
78
87
|
* NOTE: spec carries no model field today — the name comes from provider.model (spec?.model is
|
|
79
88
|
* a forward-compatible fallback). 非串 model(脏载 / 手工档)归一等价空串(未登记 ⇒ undefined)——
|
|
80
89
|
* 本函数恒 total、不因类型脏载抛(#638 查表族同归一)。
|
|
90
|
+
* `modelParams` = 本调用的模型语义参数(`chat()` 的 `opts.modelParams`;2026-12-03 批起模型参数
|
|
91
|
+
* 不再是 provider 条目属性——provider 只回答「哪条渠道」,模型参数由调用方逐调用下发)。
|
|
81
92
|
*/
|
|
82
|
-
export function resolveEnableThinking(provider, spec) {
|
|
93
|
+
export function resolveEnableThinking(provider, spec, modelParams) {
|
|
83
94
|
const raw = provider?.model ?? spec?.model ?? ""
|
|
84
95
|
const model = (typeof raw === "string" ? raw : "").toLowerCase()
|
|
85
96
|
if (!model.startsWith("qwen") || model.startsWith("qwen3-coder")) return undefined
|
|
@@ -88,9 +99,9 @@ export function resolveEnableThinking(provider, spec) {
|
|
|
88
99
|
// 百炼约束:enable_thinking:false 时 reasoning_effort 必须为 "none",互斥即 400。
|
|
89
100
|
// 压缩下行(context.mjs 的 compressIfNeeded)显式 thinking:null 但继承 effort(v3 同源裁定)——
|
|
90
101
|
// 无此分支则发出 {enable_thinking:false, reasoning_effort:"medium"} ⇒ 400 ⇒ 压缩三连败。
|
|
91
|
-
if (
|
|
92
|
-
if (
|
|
93
|
-
if (
|
|
102
|
+
if (modelParams?.reasoningEffort && modelParams?.reasoningEffort !== "none") return true
|
|
103
|
+
if (modelParams?.thinking === null) return false
|
|
104
|
+
if (modelParams?.reasoningEffort) return true
|
|
94
105
|
return undefined
|
|
95
106
|
}
|
|
96
107
|
|
|
@@ -101,11 +112,9 @@ export function resolveEnableThinking(provider, spec) {
|
|
|
101
112
|
import {
|
|
102
113
|
sanitizeConsultModels, warnConsultModelsFiltered, sanitizeSubagentModel, sanitizeSubagentModels,
|
|
103
114
|
warnSubagentModelsFiltered, sanitizeProviderHeaders, normalizeProxy, normalizeTeamSection, isUsableProviderEntry, providerDropReason,
|
|
115
|
+
normalizePlanningNextMoves,
|
|
104
116
|
} from "./config-normalize.mjs"
|
|
105
|
-
export { sanitizeSubagentModel, sanitizeSubagentModels, normalizeProxy, normalizeTeamSection }
|
|
106
|
-
|
|
107
|
-
/** Module-level one-time warn dedupe for invalid providers[].context (PROVIDER.md §15 D-C1). */
|
|
108
|
-
const warnedContextProviders = new Set()
|
|
117
|
+
export { sanitizeSubagentModel, sanitizeSubagentModels, normalizeProxy, normalizeTeamSection, normalizePlanningNextMoves }
|
|
109
118
|
|
|
110
119
|
/**
|
|
111
120
|
* 计数值配置键的装载期一次性告警(§1「保留窗与跨轮清理」∥ §2.2):去重键 = 键名,一个进程内同一个键只响一条。
|
|
@@ -113,13 +122,50 @@ const warnedContextProviders = new Set()
|
|
|
113
122
|
* 只报不管:清键由调用点做(那一处才知道该键的缺省语义落到哪个值上),本函数不碰配置对象。
|
|
114
123
|
*/
|
|
115
124
|
const warnedConfigCounts = new Set()
|
|
125
|
+
/** 档位上下文上限三键(`agent.contextCaps.*`)的装载期告警去重:一个进程内同一个键只响一条。 */
|
|
126
|
+
const warnedContextCaps = new Set()
|
|
127
|
+
/** 显式压缩线越上限(`agent.compactThreshold > policyBudget().limit`)的装载期告警去重:
|
|
128
|
+
* 去重键 = `取值:上限`——换了档位或换了模型,新的组合该单独响一条。 */
|
|
129
|
+
const warnedThresholdOverLimit = new Set()
|
|
130
|
+
/** 显式压缩线高过输入上限:装载期回落 auto,并被告知为什么(`resolveCompactThreshold` 交回的
|
|
131
|
+
* `overLimit` 读数)。不报不管:键由调用点清出内存镜像。 */
|
|
132
|
+
function warnThresholdOverLimit(resolved, raw) {
|
|
133
|
+
const key = `${resolved.overLimit.value}:${resolved.overLimit.limit}`
|
|
134
|
+
if (warnedThresholdOverLimit.has(key)) return
|
|
135
|
+
warnedThresholdOverLimit.add(key)
|
|
136
|
+
warnConfig(`[config] agent.compactThreshold = ${JSON.stringify(raw)} is above the input limit ${resolved.overLimit.limit} for the current window — ignored: a line above it never triggers (requests hit the limit first); using the derived line ${resolved.value}`)
|
|
137
|
+
}
|
|
116
138
|
function warnConfigCountOnce(key, raw) {
|
|
117
139
|
if (warnedConfigCounts.has(key)) return
|
|
118
140
|
warnedConfigCounts.add(key)
|
|
119
141
|
const semantics = key === "compactThreshold"
|
|
120
142
|
? "留空或 0 = 按当前窗口派生压缩线"
|
|
121
143
|
: "留空或 0 = 全部轮次保留"
|
|
122
|
-
|
|
144
|
+
warnConfig(`[config] agent.${key} must be a non-negative integer — got ${JSON.stringify(raw)} — ignored: ${semantics}`)
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* 模型上下文声明(`config.modelContext`——2026-12-03 批从 `providers[].modelContext` 搬到设置层顶层)的装载期归一。
|
|
149
|
+
* 键 = 模型 ID(末段归一等价——`qwen/ZHIPU/GLM-5.3` ≡ `glm-5.3`),值 = 正整数 K(`128` = 128K)。
|
|
150
|
+
* 形状不符 ⇒ 整表丢弃 + 告警一次;逐键值非法(0 / 负 / 非数 / 非整 / 布尔 / **数字字符串**)⇒ 该键视为未声明 + 告警一条。
|
|
151
|
+
* 数字字符串**不归一**:写面先 parse 再落盘,文件里的字符串是手改/笔误,静默转数会把「想写哪个单位」藏起来。
|
|
152
|
+
* 读面(`manualContextK`)仍逐次防御——归一不产新键,只清内存镜像(磁盘原文零变)。
|
|
153
|
+
*/
|
|
154
|
+
function normalizeModelContext(raw) {
|
|
155
|
+
if (raw === undefined) return {}
|
|
156
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
|
|
157
|
+
warnContextOnce("modelContext-shape",
|
|
158
|
+
`[config] modelContext must be an object of model ID → positive integer K (e.g. 128 = 128K) — got ${JSON.stringify(raw)} — ignored`)
|
|
159
|
+
return {}
|
|
160
|
+
}
|
|
161
|
+
const table = { ...raw }
|
|
162
|
+
for (const [key, value] of Object.entries(table)) {
|
|
163
|
+
if (positiveInt(value) !== null) continue
|
|
164
|
+
warnContextOnce(`modelContext-invalid\0${key}`,
|
|
165
|
+
`[config] modelContext["${key}"] must be a positive integer in K units (e.g. 128 = 128K) — got ${JSON.stringify(value)} — ignored, falling through to the list / model spec value`)
|
|
166
|
+
delete table[key]
|
|
167
|
+
}
|
|
168
|
+
return table
|
|
123
169
|
}
|
|
124
170
|
|
|
125
171
|
/**
|
|
@@ -151,6 +197,24 @@ export function promoteAgentViews(config) {
|
|
|
151
197
|
return config
|
|
152
198
|
}
|
|
153
199
|
|
|
200
|
+
/**
|
|
201
|
+
* 派生运行视图(CONFIG.md §2.3 · CONTEXT-COMPACTION.md §2.1「档位上限」):运行时 provider 带会话档位与档位上限表。
|
|
202
|
+
*
|
|
203
|
+
* 磁盘原文不带 `mode`——`providers[]` 一条是一张渠道,不是一份会话,档位随会话槽而不是随渠道。写链
|
|
204
|
+
* (`writeConfigAtomic`)只从磁盘 fresh raw 起算,派生键因此到不了盘上,`settings list` 里看到的值是运行面而不是用户原文。
|
|
205
|
+
* 档位上限表与模型窗口声明不再落 provider(2026-12-03 批):它们在设置层为 `config.agent.contextCaps` ∥ `config.modelContext`,
|
|
206
|
+
* 由各读面经 `settings` 尾参取——provider 形状的对象上不得再有这两个键。
|
|
207
|
+
*
|
|
208
|
+
* 调用点(闭集,新开一条重建 provider 的路径必须同调,否则封顶回落 normal 档缺省表——那是 512,tiny 会话会少封一半):
|
|
209
|
+
* `loadConfig`(运行面 provider)· `createAgent`(直接建 agent 的调用方与用例)· `applySession`(槽 provider 的拷贝)·
|
|
210
|
+
* `/config` 的 `reloadConfig` · `/model` 的 `selectModel`。`provider-admin.mjs` 那几条渠道管理流就地改键、不换对象,不在其列。
|
|
211
|
+
*/
|
|
212
|
+
export function bindProviderContextPolicy(provider, config) {
|
|
213
|
+
if (!provider || typeof provider !== "object") return provider
|
|
214
|
+
provider.mode = resolveWorkMode(config?.agent)
|
|
215
|
+
return provider
|
|
216
|
+
}
|
|
217
|
+
|
|
154
218
|
/**
|
|
155
219
|
* 丢弃记录一句一条(`docs/core/design/PROVIDER.md` §6.29「丢弃要看得见」):`providers[18]: null`。
|
|
156
220
|
* 只有盘上下标 + 原因闭集四值之一——**绝不带条目内容**:载体是数据层,会进日志 ∥ 报错 ∥ 调试输出,
|
|
@@ -169,7 +233,7 @@ function providerDropLine(index, reason) {
|
|
|
169
233
|
* loadConfig 内联迁移核已迁 config-migrate.mjs(500 行硬限拆分——VSC 同构)——
|
|
170
234
|
* migrateLegacyModelFields 纯函数 + 本文件 import/写回编排(折中 C 见其头注释)。
|
|
171
235
|
*/
|
|
172
|
-
export function loadConfig() {
|
|
236
|
+
export function loadConfig(cwd) {
|
|
173
237
|
let config = {}
|
|
174
238
|
const path = cfgPath()
|
|
175
239
|
if (existsSync(path)) {
|
|
@@ -220,17 +284,29 @@ export function loadConfig() {
|
|
|
220
284
|
diagnostics: { ...DEFAULTS.diagnostics },
|
|
221
285
|
}
|
|
222
286
|
|
|
287
|
+
// 模型语义参数(temperature ∥ thinking ∥ reasoningEffort)归一(2026-12-03 批):`config.modelParams`
|
|
288
|
+
// 是设置层(不再是 provider 条目属性),缺键回落 `DEFAULTS.modelParams`(空对象 = 三键都不设)。
|
|
289
|
+
// 这里只做合并——值域(温度钳制、effort 枚举)归发送点(`provider/core.mjs` 与四条 transport),
|
|
290
|
+
// 装载期不重复一遍判据。非对象形(手改 config.json 的畸形值)不展开(字符串 spread 会产出垃圾键)。
|
|
291
|
+
merged.modelParams = {
|
|
292
|
+
...DEFAULTS.modelParams,
|
|
293
|
+
...(config.modelParams && typeof config.modelParams === "object" && !Array.isArray(config.modelParams) ? config.modelParams : {}),
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
// 模型上下文声明(2026-12-03 批):住**设置层顶层 `config.modelContext`**,不再是 provider 条目的属性
|
|
297
|
+
// (用户裁定:「我他妈的自己部署的服务器我也不会写在provider上!」)。键 = 模型 ID,值 = 正整数 K。
|
|
298
|
+
// 值只收正整数,非法(0 / 负 / 非数 / 非整 / 布尔 / 数字字符串)⇒ 该键视为未声明(落下一层)+ 装载期告警一次。
|
|
299
|
+
// 数字字符串**不归一**(写面先 parse 再落盘,文件里的字符串是手改/笔误,静默转数会把「想写哪个单位」藏起来)。
|
|
300
|
+
// 读面(`manualContextK`)仍逐次防御——归一不产新键,只清内存镜像(磁盘原文零变)。
|
|
301
|
+
merged.modelContext = normalizeModelContext(config.modelContext)
|
|
302
|
+
|
|
223
303
|
// Work mode is normalized from the raw input: a valid mode wins; legacy engineering is read
|
|
224
304
|
// only when mode is absent. The old boolean remains a derived runtime view, never a second authority.
|
|
225
305
|
merged.agent.mode = resolveWorkMode(config.agent)
|
|
226
306
|
merged.agent.engineering = merged.agent.mode === "engineering"
|
|
227
307
|
// 独立「Planning next moves」规划步配置归一:支持布尔 false 简写或局部字段覆写(未写字段继承 DEFAULTS)。
|
|
228
|
-
|
|
229
|
-
merged.agent.planningNextMoves =
|
|
230
|
-
? { ...DEFAULTS.agent.planningNextMoves, enabled: false }
|
|
231
|
-
: rawPlan && typeof rawPlan === "object" && !Array.isArray(rawPlan)
|
|
232
|
-
? { ...DEFAULTS.agent.planningNextMoves, ...rawPlan }
|
|
233
|
-
: { ...DEFAULTS.agent.planningNextMoves }
|
|
308
|
+
// 规则单源 = `normalizePlanningNextMoves`(VSC `hydrateRun` 共用——端差修复 2026-11-30)。
|
|
309
|
+
merged.agent.planningNextMoves = normalizePlanningNextMoves(config.agent?.planningNextMoves)
|
|
234
310
|
|
|
235
311
|
// 丢弃要看得见(同节「丢弃要看得见 · 数据面载体」):载体只在有丢弃时有值(无丢弃 ⇒ undefined,
|
|
236
312
|
// 与 `[]` 同义)。一条一句挂数据层;出词归消费面——本批唯一消费方 = `/model` L1 列表首行
|
|
@@ -257,42 +333,12 @@ export function loadConfig() {
|
|
|
257
333
|
if (p.model !== undefined) delete p.model
|
|
258
334
|
}
|
|
259
335
|
|
|
260
|
-
// providers[].context
|
|
261
|
-
//
|
|
262
|
-
// per provider name (module-level dedupe, same precedent as warnedModels in model-specs.mjs).
|
|
263
|
-
for (const p of merged.providers) {
|
|
264
|
-
if (p.context === undefined) continue
|
|
265
|
-
if (Number.isInteger(Number(p.context)) && Number(p.context) > 0) { p.context = Number(p.context); continue } // 数字字符串("128")归一为数字——两端语义统一(code review #1)
|
|
266
|
-
if (!warnedContextProviders.has(p.name ?? "(unnamed)")) {
|
|
267
|
-
warnedContextProviders.add(p.name ?? "(unnamed)")
|
|
268
|
-
console.warn(`[config] provider "${p.name}" context must be a positive integer in K units (e.g. 128 = 128K) — got ${JSON.stringify(p.context)} — ignored, using the model spec value`)
|
|
269
|
-
}
|
|
270
|
-
delete p.context
|
|
271
|
-
}
|
|
336
|
+
// 旧键 `providers[].context`(渠道级 K 覆盖)已于 2026-11-29 退役(用户裁定):它不是窗口解析链的一层,
|
|
337
|
+
// 本档不再归一 ∥ 告警 ∥ 读取它。仍写在配置文件里的该键不参与任何计算——要声明窗口请用 `modelContext`。
|
|
272
338
|
|
|
273
|
-
// providers[].modelContext
|
|
274
|
-
//
|
|
275
|
-
//
|
|
276
|
-
// 手改/笔误,静默转数会把「想写哪个单位」藏起来(旧键两起 ×1024 事故的根因)。
|
|
277
|
-
// 读面(manualContextK)仍逐次防御——装载归一不产新键,只清内存镜像(磁盘原文零变)。
|
|
278
|
-
for (const p of merged.providers) {
|
|
279
|
-
if (p.modelContext === undefined) continue
|
|
280
|
-
const rawMC = p.modelContext
|
|
281
|
-
if (!rawMC || typeof rawMC !== "object" || Array.isArray(rawMC)) {
|
|
282
|
-
warnContextOnce(`modelContext-shape\0${p.name ?? ""}`,
|
|
283
|
-
`[config] provider "${p.name}" modelContext must be an object of model ID → positive integer K (e.g. 128 = 128K) — got ${JSON.stringify(rawMC)} — ignored`)
|
|
284
|
-
delete p.modelContext
|
|
285
|
-
continue
|
|
286
|
-
}
|
|
287
|
-
p.modelContext = { ...rawMC }
|
|
288
|
-
for (const [key, value] of Object.entries(p.modelContext)) {
|
|
289
|
-
if (positiveInt(value) !== null) continue
|
|
290
|
-
warnContextOnce(`modelContext-invalid\0${p.name ?? ""}\0${key}`,
|
|
291
|
-
`[config] provider "${p.name}" modelContext["${key}"] must be a positive integer in K units (e.g. 128 = 128K) — got ${JSON.stringify(value)} — ignored, falling through to the provider context / list / model spec value`)
|
|
292
|
-
delete p.modelContext[key]
|
|
293
|
-
}
|
|
294
|
-
if (Object.keys(p.modelContext).length === 0) delete p.modelContext // 不留空对象
|
|
295
|
-
}
|
|
339
|
+
// 旧键 `providers[].modelContext`(渠道级模型窗口声明)已于 2026-12-03 退役(用户裁定):模型窗口声明
|
|
340
|
+
// 不属于渠道,已搬设置层顶层 `config.modelContext`。仍写在 provider 条目上的该键不再参与任何计算
|
|
341
|
+
// (只停读、不归一、不剥键、不告警);要声明窗口请写顶层 `config.modelContext`。
|
|
296
342
|
|
|
297
343
|
// F-4 (IKCDMR) consultModels 软失败化——D-S1 范式(defaultModel 无效同族):非法条目
|
|
298
344
|
// 过滤不 throw(去 startup brick——无修复入口的硬崩消);一次性启动警告内嵌修复指引
|
|
@@ -341,18 +387,42 @@ export function loadConfig() {
|
|
|
341
387
|
|
|
342
388
|
// Compaction threshold 三档落值(CONTEXT-COMPACTION.md §2.2):过同一个取值域谓词与同一个解析函数——
|
|
343
389
|
// 「显式」= 有限正数。正数 ⇒ 原样落 `compactThreshold`;0 ∥ 缺省 ∥ 手改的非法值 ⇒ auto 支,
|
|
344
|
-
// 键清出内存镜像(`delete`,与下面 `keepToolTurns`
|
|
390
|
+
// 键清出内存镜像(`delete`,与下面 `keepToolTurns` 同一做法),派生值不落任何字段、也不落盘。
|
|
345
391
|
// 非法值(负数 ∥ 小数 ∥ 非数字)与 0 在内存镜像里同形(键不存 + `auto: true`),另告警一条点名键与取值:
|
|
346
392
|
// 磁盘上的 0 是用户的选择,磁盘上的 -1 是笔误,两者取值相同但只有后者该被说出来。
|
|
347
393
|
const rawThreshold = config.agent?.compactThreshold
|
|
348
394
|
const thresholdValue = nonNegativeIntValue(rawThreshold)
|
|
349
|
-
|
|
395
|
+
// ⑥ 越界判据按**会话档位**取上限:此刻 `merged.provider` 还没绑派生视图(`bindProviderContextPolicy` 在函数尾),
|
|
396
|
+
// 直接传档位与设置层(上限表 ∥ 模型窗口声明)——否则回落到 normal 缺省,tiny 档的越界值会静默放行(那正是这道门要接住的一格)。
|
|
397
|
+
const thresholdScope = { ...merged.provider, mode: resolveWorkMode(merged.agent) }
|
|
398
|
+
const thresholdResolved = resolveCompactThreshold(thresholdValue, thresholdScope, merged)
|
|
399
|
+
if (thresholdResolved.overLimit) warnThresholdOverLimit(thresholdResolved, thresholdValue)
|
|
350
400
|
if (thresholdResolved.auto) delete merged.agent.compactThreshold
|
|
351
401
|
else merged.agent.compactThreshold = thresholdResolved.value
|
|
352
|
-
|
|
402
|
+
// 派生线**不落字段**:显示面与判定面各自在读数上现算(`resolveCompactThreshold` / `policyBudget`)。
|
|
403
|
+
// 曾经缓存成 `compactThresholdResolved`,档位一换就停在旧档那条线上——`/config` 与状态行报两个数。
|
|
353
404
|
merged.agent.compactThresholdAuto = thresholdResolved.auto
|
|
354
405
|
if (rawThreshold != null && rawThreshold !== "" && thresholdValue === null) warnConfigCountOnce("compactThreshold", rawThreshold)
|
|
355
406
|
|
|
407
|
+
// 档位上下文上限(CONTEXT-COMPACTION.md §2.1,2026-11-28 用户裁决):三键只认正整数 K。
|
|
408
|
+
// 数字串("256")归一为数字——与 `config.modelContext` 的 K 值同口径,是手改文件的容错而不是写面;其余值(0 / 负数 / 小数 / 布尔 / 对象)清出内存镜像、回落 DEFAULTS 的同键,并告警一条点名键与取值。
|
|
409
|
+
// 空串与缺键同义(未配置),不告警。
|
|
410
|
+
const rawCaps = config.agent?.contextCaps
|
|
411
|
+
const rawCapsTable = rawCaps && typeof rawCaps === "object" && ! Array.isArray(rawCaps) ? rawCaps : null
|
|
412
|
+
for (const mode of WORK_MODES) {
|
|
413
|
+
if (!rawCapsTable || !Object.hasOwn(rawCapsTable, mode)) continue
|
|
414
|
+
const raw = rawCapsTable[mode]
|
|
415
|
+
if (raw == null || raw === "") continue
|
|
416
|
+
const k = positiveIntValue(raw) // 数字或十进制整数文本;装载期与读面同一份谓词
|
|
417
|
+
if (k !== null) continue
|
|
418
|
+
if (!warnedContextCaps.has(mode)) {
|
|
419
|
+
warnedContextCaps.add(mode)
|
|
420
|
+
warnConfig(`[config] agent.contextCaps.${mode} must be a positive integer in K (e.g. 256 = 256K) — got ${JSON.stringify(raw)} — ignored, using ${DEFAULTS.agent.contextCaps[mode]}K`)
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
// 归一一次:合法值(数字或十进制整数文本)写成数字进内存镜像,非法键清掉、回落该档缺省。
|
|
424
|
+
merged.agent.contextCaps = resolveContextCaps(config)
|
|
425
|
+
|
|
356
426
|
// 保留窗宽(CONTEXT-COMPACTION.md §1「保留窗与跨轮清理」):合法值归一成数字写回内存镜像,一个字节不动磁盘;
|
|
357
427
|
// 空值(缺省 ∥ `null` ∥ 空串)= 全部轮次保留,键不进镜像;非法值(负数 ∥ 小数 ∥ 非数字)清出镜像并按缺省
|
|
358
428
|
// 语义取值(0 = 全部保留),同一条一次性告警。进程不因手改文件的笔误被挡在门外。
|
|
@@ -378,7 +448,13 @@ export function loadConfig() {
|
|
|
378
448
|
merged.provider.bodyIdleTimeoutMs = Number.isFinite(merged.agent?.bodyIdleTimeoutMs) && merged.agent.bodyIdleTimeoutMs > 0
|
|
379
449
|
? merged.agent.bodyIdleTimeoutMs : undefined
|
|
380
450
|
merged.providersList = merged.providers
|
|
451
|
+
// stream 规则装配合并(B7 3a):`.thincoder/rules/*.md` 文件规则置前、config 规则按 `pattern` 去重。
|
|
452
|
+
// 只在给了 `cwd` 时合——没给 `cwd` 的调用面(设置面板、重读、测试)不碰文件系统,
|
|
453
|
+
// `agent.streamRules` 保持盘上数组原样。
|
|
454
|
+
if (typeof cwd === "string" && cwd) merged.agent.streamRules = mergeFileRules(merged.agent?.streamRules, cwd)
|
|
381
455
|
promoteAgentViews(merged) // agent.advisor → advisor promote for consistent access (decoupled copy)
|
|
456
|
+
// 运行时 provider 的派生视图(档位 + 档位上限表):新建会话起点那份与 `merged.provider` 是同一个渠道对象,绑一次即可。
|
|
457
|
+
bindProviderContextPolicy(merged.provider, merged)
|
|
382
458
|
|
|
383
459
|
return merged
|
|
384
460
|
}
|
package/context-degrade.mjs
CHANGED
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
* 命中项直接改那一轮自己的内层元素(外层数组与内层数组的引用都不换)。
|
|
11
11
|
*/
|
|
12
12
|
import { collectStaleToolOutputs, contextUsage, estimateTokens, rebaseMeasured, tokenRatioOf } from "./token-window.mjs"
|
|
13
|
-
// 保护尾跟着**有效窗口**走(`CONTEXT-COMPACTION.md` §2.1 / §4
|
|
13
|
+
// 保护尾跟着**有效窗口**走(`CONTEXT-COMPACTION.md` §2.1 / §4):有效窗口 = min(模型窗口, 档位上限)。
|
|
14
14
|
// 保留窗起点(#2431):prune 的合格集与压缩同一个切点——保留窗内那几轮的工具输出不被选中(§1.2)。
|
|
15
15
|
import { retentionWindowStart } from "./agent/turn-projection.mjs"
|
|
16
16
|
// 拍平投影与两向换算(写面单点档):本档只读投影、只改结构。
|
|
@@ -45,7 +45,7 @@ export function pruneStaleToolOutputs(agent) {
|
|
|
45
45
|
const usage = contextUsage(agent, agent?._ctxBasis?.overhead ?? {})
|
|
46
46
|
const stale = collectStaleToolOutputs(
|
|
47
47
|
flat, agent.provider, protectFromOf(agent, flat),
|
|
48
|
-
usage.fixed - usage.compactionSummary, tokenRatioOf(agent),
|
|
48
|
+
usage.fixed - usage.compactionSummary, tokenRatioOf(agent), agent.config,
|
|
49
49
|
)
|
|
50
50
|
const counts = {
|
|
51
51
|
pruned: stale.indexes.length,
|
|
@@ -94,9 +94,9 @@ const OVERSIZE_CONTENT_LIMIT = 8_000
|
|
|
94
94
|
* 消息一条不改——保留窗承诺的那两轮工具过程原文逐字留着。取不到起点(等于拍平条数)时等于不收紧。
|
|
95
95
|
* 代价写明:那一轮离开前,一条超大消息可能让压缩无事可做,由越窗守卫如实报错(§4 的已知边界)。
|
|
96
96
|
*/
|
|
97
|
-
export function shrinkOversized(agent, limit = OVERSIZE_CONTENT_LIMIT) {
|
|
97
|
+
export function shrinkOversized(agent, limit = OVERSIZE_CONTENT_LIMIT, { ignoreRetention = false } = {}) {
|
|
98
98
|
const flat = flattenHistory(agent.history)
|
|
99
|
-
const protectFrom = protectFromOf(agent, flat)
|
|
99
|
+
const protectFrom = ignoreRetention ? flat.length : protectFromOf(agent, flat)
|
|
100
100
|
let shrunk = false
|
|
101
101
|
const measuredEnd = measuredEndOf(agent, flat)
|
|
102
102
|
let estBefore = 0
|
package/context-push.mjs
CHANGED
|
@@ -227,14 +227,14 @@ export function positionOf(history, flatIndex) {
|
|
|
227
227
|
}
|
|
228
228
|
|
|
229
229
|
/**
|
|
230
|
-
*
|
|
230
|
+
* 会话头块的锚点判据(判据正文 = 设计档「会话头块」):这一条是不是「第一条真实用户消息」。
|
|
231
231
|
* `role === "user"`,且内容不是机器行——字符串形不以 `[System reminder:` 开头;分片数组形取第一个
|
|
232
232
|
* `type === "text"` 分片判同一前缀,一个 text 分片都没有的不合格。内容为空不参与判据(自动回合的用户
|
|
233
233
|
* 消息就是空串,它仍是这一轮的真实用户位置)。
|
|
234
|
-
*
|
|
235
|
-
*
|
|
234
|
+
* 导出供 `compress-form.mjs#buildCompressMessages` 共用,确保压缩/蒸馏请求与回合请求在完全同一条用户消息上
|
|
235
|
+
* 贴入 `_sessionHead`,逐字节对齐 KV Prefix Cache。
|
|
236
236
|
*/
|
|
237
|
-
function isSessionHeadAnchor(m) {
|
|
237
|
+
export function isSessionHeadAnchor(m) {
|
|
238
238
|
if (m?.role !== "user") return false
|
|
239
239
|
const content = m?.content
|
|
240
240
|
if (typeof content === "string") return !content.startsWith("[System reminder:")
|
|
@@ -246,17 +246,28 @@ function isSessionHeadAnchor(m) {
|
|
|
246
246
|
}
|
|
247
247
|
|
|
248
248
|
/**
|
|
249
|
-
* 在一段既有 `content`
|
|
249
|
+
* 在一段既有 `content` 末尾接一段文本(`text` 为空时原样返回)。内容两形各一贴法:
|
|
250
250
|
* 字符串 ⇒ 换行接一段;分片数组 ⇒ 末尾加一个 `{ type: "text", text }` 分片(不再拆合已有分片)。
|
|
251
|
-
* `
|
|
251
|
+
* 导出供 `compress-form.mjs#buildCompressMessages` 与本档 `assembleRequestMessages` 共用,保字节一致。
|
|
252
252
|
*/
|
|
253
|
-
function appendBlock(content, text) {
|
|
253
|
+
export function appendBlock(content, text) {
|
|
254
254
|
if (!text) return content
|
|
255
255
|
if (Array.isArray(content)) return [...content, { type: "text", text }]
|
|
256
256
|
if (typeof content === "string") return content ? `${content}\n${text}` : text
|
|
257
257
|
return text
|
|
258
258
|
}
|
|
259
259
|
|
|
260
|
+
/**
|
|
261
|
+
* A 段其余 9 格(除 `compaction-summary` 外,按 `INJECT_SLOTS` 次序)拼成一块。
|
|
262
|
+
* 导出供 `context.mjs` / `explore-distill.mjs` → `compress-form.mjs#buildCompressMessages` 共用,
|
|
263
|
+
* 保证蒸馏(及末条 user 落入中段的压缩)与回合请求在末条 `user` 消息副本上逐字节一致。
|
|
264
|
+
*/
|
|
265
|
+
export function turnBlockOf(agent) {
|
|
266
|
+
const summaryAt = INJECT_SLOTS.indexOf("compaction-summary")
|
|
267
|
+
const slots = Array.isArray(agent?._inject) ? agent._inject : []
|
|
268
|
+
return slots.filter((m, i) => i !== summaryAt && m).map((m) => m.content).join("\n")
|
|
269
|
+
}
|
|
270
|
+
|
|
260
271
|
/**
|
|
261
272
|
* assembleRequestMessages — 请求消息的**唯一构造点**(system → C → 压缩摘要 → 对话(头块贴首条用户消息)→ A 其余 9 格并成一块 → B)。
|
|
262
273
|
* `toolsDeclared` 是实际请求是否携带工具声明的必填布尔值;缺参或非布尔在入口点名抛错。它参与完整历史缺回声退轮,
|
|
@@ -296,12 +307,12 @@ export function assembleRequestMessages(agent, { systemPrompt, toolsDeclared } =
|
|
|
296
307
|
const { messages: line, reading } = quarantineForeignOrigin(flat, {
|
|
297
308
|
providerName: agent.provider?.name,
|
|
298
309
|
spec,
|
|
299
|
-
thinkingMode: isThinkingRequest(agent.
|
|
310
|
+
thinkingMode: isThinkingRequest(agent.modelParams ?? null, spec),
|
|
300
311
|
toolsDeclared,
|
|
301
312
|
})
|
|
302
313
|
logOriginQuarantine({ site: "turn-request", providerName: agent.provider?.name, reading })
|
|
303
314
|
// A 其余 9 格并成一块(格序即 `INJECT_SLOTS` 的次序)。
|
|
304
|
-
const turnBlock =
|
|
315
|
+
const turnBlock = turnBlockOf(agent)
|
|
305
316
|
// 两个锚点:头块贴第一条真实用户消息(判据见 `isSessionHeadAnchor`),每轮块贴最后一条用户消息。
|
|
306
317
|
const headAt = line.findIndex(isSessionHeadAnchor)
|
|
307
318
|
const turnAt = line.findLastIndex((m) => m?.role === "user")
|
package/context.mjs
CHANGED
|
@@ -15,7 +15,7 @@ import { chat } from "./provider/index.mjs"
|
|
|
15
15
|
import { buildCompressMessages } from "./compress-form.mjs"
|
|
16
16
|
import { contextUsage, estimateTokens, keepTailSize, splitHistory, COMPACTION_SUMMARY_TOKEN_ESTIMATE, rebaseMeasured, tailBudgetTokens, tokenRatioOf } from "./token-window.mjs"
|
|
17
17
|
// 写面单点(机器线按轮嵌套):压缩只做结构编辑,消息怎么进线归 `context-push.mjs`;三段回注住 A 段格位。
|
|
18
|
-
import { flattenHistory, flatIndexOf, positionOf, setInject } from "./context-push.mjs"
|
|
18
|
+
import { flattenHistory, flatIndexOf, positionOf, setInject, turnBlockOf } from "./context-push.mjs"
|
|
19
19
|
// 会话头块的两个单点(`CONTEXT-COMPACTION.md` §1.1「会话头块」):写入方 = `pushSessionHeadBlock`,
|
|
20
20
|
// 大纲正文 = `sessionOutlineOf`。压缩是本批的第二个刷新点——切走第一条真实用户消息所在轮之后重算一次,
|
|
21
21
|
// 下一次装配就贴到压缩边界后的新锚点上。
|
|
@@ -25,7 +25,7 @@ import { syncPlanSlot } from "./agent-tools/plan.mjs"
|
|
|
25
25
|
import { logEvent } from "./log.mjs"
|
|
26
26
|
// 压缩后回注的工作状态块(§6.1「工作状态的找回」):块怎么生成住 `compaction-work-state.mjs`;
|
|
27
27
|
// 本档只负责「注在哪」——三段回注的唯一落点是下面的 `reinjectAfterCompaction`。
|
|
28
|
-
import { workStateBlock } from "./compaction-work-state.mjs"
|
|
28
|
+
import { collectWorkStateHintPaths, workStateBlock } from "./compaction-work-state.mjs"
|
|
29
29
|
import { pruneStaleToolOutputs, shrinkOversized } from "./context-degrade.mjs"
|
|
30
30
|
// 固定开销越线判据的另一半(#2398):`limit` 单源 = `policyBudget`(有效窗口——与守卫面同一个数)。
|
|
31
31
|
import { policyBudget } from "./config.mjs"
|
|
@@ -96,7 +96,7 @@ const focusBlock = (focus, anchor) =>
|
|
|
96
96
|
function anchorText(agent) {
|
|
97
97
|
const lines = []
|
|
98
98
|
const g = agent?.goal
|
|
99
|
-
if (g?.
|
|
99
|
+
if (g?.condition) lines.push(`- goal [${g.status}] ${g.condition}`)
|
|
100
100
|
for (const t of agent?.tasks ?? []) lines.push(`- [${t.status}] ${t.title}`)
|
|
101
101
|
return lines.length > 0 ? lines.join("\n") : null
|
|
102
102
|
}
|
|
@@ -111,8 +111,12 @@ function anchorText(agent) {
|
|
|
111
111
|
* @param {string|null} workState — 已生成的工作状态块;`null` = 台账面读失败 ⇒ 整块不出现
|
|
112
112
|
*/
|
|
113
113
|
function reinjectAfterCompaction(agent, workState) {
|
|
114
|
-
|
|
115
|
-
|
|
114
|
+
// `tasks` 按同档既有约定读(`agent/turn-projection.mjs` 的 `buildTurnRecord` 同形):缺字段的 agent 就是
|
|
115
|
+
// 没有任务表,列表的空值是 `[]`——这不是「读失败」,也不是把失败的门变成成功(`tasks` 不是业务门)。
|
|
116
|
+
// 直接读 `.length` 会让一个缺字段的 agent 在切完线之后抛,而那一步的错会被读成「摘要失败」(见 `applyCompression`)。
|
|
117
|
+
const tasks = Array.isArray(agent.tasks) ? agent.tasks : []
|
|
118
|
+
setInject(agent, "tasks", tasks.length > 0
|
|
119
|
+
? `${TASK_REINJECT_PREFIX}\n${tasks.map((t) => `- [${t.status}] ${t.title}`).join("\n")}\nContinue from where you left off.]`
|
|
116
120
|
: null)
|
|
117
121
|
syncPlanSlot(agent)
|
|
118
122
|
setInject(agent, "work-state", workState)
|
|
@@ -191,7 +195,14 @@ export function applyCompression(agent, headEnd, tailStart, compactionSummary, w
|
|
|
191
195
|
agent.history = cutTurns(before, from, to)
|
|
192
196
|
setInject(agent, "compaction-summary", compactionSummary)
|
|
193
197
|
// 三段回注(任务表 → plan 提醒 → 工作状态块):顺序与落点在 `reinjectAfterCompaction` 一处。
|
|
194
|
-
|
|
198
|
+
// 与下面头块同一条纪律:它是压缩后的注入写入,不是压缩本体——它抛了只记一行日志。线已经切完,
|
|
199
|
+
// 此刻把错抛出去会被 `compressIfNeeded` 读成「摘要失败」,再走一遍 `compressFallback`:第二次切同一条线,
|
|
200
|
+
// 并把刚写好的摘要换成降级文本(实测形态 = 第二次切时 `_usageAt` 还停在切前的线上 ⇒ `flatIndexOf: invalid msg …`)。
|
|
201
|
+
try {
|
|
202
|
+
reinjectAfterCompaction(agent, workState)
|
|
203
|
+
} catch (err) {
|
|
204
|
+
logEvent("compaction:reinject-skip", { reason: err?.message ?? String(err) })
|
|
205
|
+
}
|
|
195
206
|
// 会话头块(§1.1「会话头块」):切完元素、`compaction-summary` 格也已写好——第一条真实用户消息所在轮
|
|
196
207
|
// 刚被切走,重算重存一次,下一次装配就贴到压缩边界后的新锚点上(不叠加第二处:整段替换)。
|
|
197
208
|
// 它是可选注入的写入,不是压缩本体:它抛了只记一行日志——不让一次头块写入失败把一次已成功的压缩
|
|
@@ -221,6 +232,25 @@ function postCompactionTotal(agent, usage, middle) {
|
|
|
221
232
|
return Math.round((usage.history - estimateTokens(middle) + COMPACTION_SUMMARY_TOKEN_ESTIMATE + (usage.fixed - usage.compactionSummary)) * ratio)
|
|
222
233
|
}
|
|
223
234
|
|
|
235
|
+
/**
|
|
236
|
+
* 压缩切分选点(保留窗优先、容量硬边界兜底):
|
|
237
|
+
* 1. 先按 `protectFrom`(`keepToolTurns` 保留窗起点)切分,保留窗未超载时完整保护最近 N 轮工具过程;
|
|
238
|
+
* 2. 若保留窗本身吃掉全部中段(如 `history.length === keep` 导致 `protectFrom === 0` → `split === null`),
|
|
239
|
+
* 或只压保留窗之前仍压不回 `threshold`(`post > threshold`),说明保留窗自身已撑爆压缩线;
|
|
240
|
+
* 此时放宽 `protectFrom = flat.length`,按 `keepTail` + `tailBudget` 切分,避免保留窗锁死压缩导致爆窗。
|
|
241
|
+
*/
|
|
242
|
+
function selectCompactionSplit(agent, flat, keepTail, tailBudget, usage, threshold) {
|
|
243
|
+
const protectFrom = protectFromOf(agent, flat)
|
|
244
|
+
const split = splitHistory(flat, keepTail, tailBudget, protectFrom)
|
|
245
|
+
if (protectFrom >= flat.length) return split
|
|
246
|
+
const blockedByRetention = !split
|
|
247
|
+
|| postCompactionTotal(agent, usage, flat.slice(split.headEnd, split.tailStart)) > threshold
|
|
248
|
+
if (!blockedByRetention) return split
|
|
249
|
+
const relaxed = splitHistory(flat, keepTail, tailBudget, flat.length)
|
|
250
|
+
if (!split) return relaxed
|
|
251
|
+
return relaxed && relaxed.tailStart > split.tailStart ? relaxed : split
|
|
252
|
+
}
|
|
253
|
+
|
|
224
254
|
/**
|
|
225
255
|
* 压缩链(`CONTEXT-COMPACTION.md` §5.1):越线不等于要付一次摘要请求——越线之后先做一次零成本、
|
|
226
256
|
* 确定性的 prune,再重测。裁 → 摘要 → 丢弃,三步串联,每步之后重测,够则停:
|
|
@@ -255,7 +285,7 @@ function postCompactionTotal(agent, usage, middle) {
|
|
|
255
285
|
export async function compressIfNeeded(agent, threshold, callbacks, extras, signal) {
|
|
256
286
|
// `extras` 必填、无缺省(§2.3 的同一纪律):本函数的每一次读数与每一条门都按 `fixed` 算,
|
|
257
287
|
// 缺这一段即 system ∥ tools 两段记 0——读数偏低而看起来正常。缺参在 `contextUsage` 那里抛出并点名。
|
|
258
|
-
// 窗口 =
|
|
288
|
+
// 窗口 = 有效窗口(= min(模型窗口, 档位上限),§2.1)——守卫、尾预算、固定开销判据都从它派生。
|
|
259
289
|
const ratio = tokenRatioOf(agent)
|
|
260
290
|
// 单源(§6.16.4):total 与 stats 面同一函数(既有内联式改调 contextUsage,判定语义零改)。
|
|
261
291
|
// ① 阈值早退(force 跳过)
|
|
@@ -263,23 +293,24 @@ export async function compressIfNeeded(agent, threshold, callbacks, extras, sign
|
|
|
263
293
|
if (!extras.force && usage.total <= threshold) return false
|
|
264
294
|
// ② 固定开销单独越线(#2398 · §5):history 归零后 `total` 仍等于固定开销 ⇒ 压缩无解。强压面也不放行
|
|
265
295
|
// (压一次白付一次摘要请求,压完仍抛同一个错)。判据是 `fixedFloor > limit`(有效窗口的装填上限)。
|
|
266
|
-
// `budgetOf` 把 `reserve`
|
|
296
|
+
// `budgetOf` 把 `reserve` 封在半窗(`floor(window ÷ 2)`)以下 ⇒ `limit ≥ threshold`,这道门与压缩线同源同面,
|
|
267
297
|
// 不再「先于压缩线开火」。算式的唯一实现是 `window-policy.mjs` 的 `compactLineOf`,这里不重写第二份。
|
|
268
|
-
if (usage.fixedFloor > policyBudget(agent.provider).limit) return false
|
|
298
|
+
if (usage.fixedFloor > policyBudget(agent.provider, undefined, undefined, agent.config).limit) return false
|
|
269
299
|
// ③ prune 一次 → 基线按 §3.1 重定(在 prune 内部)→ 重测
|
|
270
300
|
if (pruneStaleToolOutputs(agent).pruned > 0) usage = contextUsage(agent, extras)
|
|
271
301
|
// ④ 未 force 且重测后已够 ⇒ 停:prune 换来的线下,不必再付一次摘要请求
|
|
272
302
|
if (!extras.force && usage.total <= threshold) return false
|
|
273
303
|
const tokens = usage.total
|
|
274
304
|
|
|
275
|
-
// 切点在拍平视图上算(配对修复与 `suffixTokens`
|
|
305
|
+
// 切点在拍平视图上算(配对修复与 `suffixTokens` 都在拍平序),保留窗优先、超载时放宽避免锁死压缩。
|
|
276
306
|
const flat = flattenHistory(agent.history)
|
|
277
|
-
const keepTail = keepTailSize(agent.provider, flat.length)
|
|
278
|
-
const
|
|
307
|
+
const keepTail = keepTailSize(agent.provider, flat.length, agent.config)
|
|
308
|
+
const tailBudget = tailBudgetTokens(agent.provider, usage.fixed - usage.compactionSummary, ratio, threshold, agent.config)
|
|
309
|
+
const split = selectCompactionSplit(agent, flat, keepTail, tailBudget, usage, threshold)
|
|
279
310
|
if (!split) {
|
|
280
311
|
// History is too short (≤KEEP_HEAD+keepTail+1 messages) to find a middle section, but tokens exceed threshold — typically a single giant message
|
|
281
|
-
// (large paste / huge injection). When summarization has no room, degrade to deterministic shrinking to ensure context always reduces
|
|
282
|
-
return shrinkOversized(agent)
|
|
312
|
+
// (large paste / huge injection). When summarization has no room even after relaxing retention, degrade to deterministic shrinking to ensure context always reduces
|
|
313
|
+
return shrinkOversized(agent, undefined, { ignoreRetention: true })
|
|
283
314
|
}
|
|
284
315
|
|
|
285
316
|
const middle = flat.slice(split.headEnd, split.tailStart)
|
|
@@ -290,7 +321,12 @@ export async function compressIfNeeded(agent, threshold, callbacks, extras, sign
|
|
|
290
321
|
|
|
291
322
|
// 工作状态块(§6.1「消费者表」):计算点绑在可达性门之后、摘要请求之前——没压缩的回合零 I/O,
|
|
292
323
|
// 一次压缩只读一次盘、开一次库。第 ⑥ 步转 `compressFallback` 复用这个值,不重读;它不抛(降级给 `null`)。
|
|
293
|
-
|
|
324
|
+
// 多项目父工作区下透传本会话触达路径 `hintPaths`,在 `boundary` 内定位活跃子仓根,避免误跳 `no-project-root`。
|
|
325
|
+
const workState = await workStateBlock({
|
|
326
|
+
cwd: agent.cwd,
|
|
327
|
+
boundary: agent.cwd,
|
|
328
|
+
hintPaths: collectWorkStateHintPaths(agent, flat),
|
|
329
|
+
})
|
|
294
330
|
// 会话头块的依赖大纲同在这一刻重建(与 workState 同一处 I/O 面:压缩之后才付这份成本)。
|
|
295
331
|
const outline = await sessionOutlineOf(agent)
|
|
296
332
|
|
|
@@ -298,7 +334,9 @@ export async function compressIfNeeded(agent, threshold, callbacks, extras, sign
|
|
|
298
334
|
// array) + the previous summary right after system (§6.2) + the middle's verbatim messages + one tail instruction. 首现即复用回合所建前缀 ⟺ 带 tools 声明(无 tool_choice)
|
|
299
335
|
// 且 `reasoning_effort` 与回合侧同值——v2 探针复测:8 格 84–98%(读数详表见批次档 §5);不带 tools / 带 tool_choice:"none" / effort 异值 ⇒ 首现 0%(自建项复跑例外);无 extras.tools ⇒ 不发 tools。
|
|
300
336
|
// ⚠️ **不带 `tool_choice`**(设计 §6.14 备选② · 预注册判定规则「S3 <0.9 且 S4 ≥0.9 ⇒ 采纳 v2 减 tool_choice」启用——实测该参数使服务端丢弃 tools 区 ⇒ 首现命中 0%)。
|
|
301
|
-
// ⚠️ v3(父侧 2026-09-18 裁定):**随带与回合请求同源的 `reasoning_effort
|
|
337
|
+
// ⚠️ v3(父侧 2026-09-18 裁定):**随带与回合请求同源的 `reasoning_effort`**——下行不再覆盖会话设置
|
|
338
|
+
//(回合调用 `chat(agent.provider, { modelParams: agent.modelParams })` 同源;2026-12-03 批:模型语义参数
|
|
339
|
+
// 搬下 provider 克隆,改经 `opts.modelParams` 携带——本处克隆只改 `thinking` 一处,其余逐位继承会话设置)。
|
|
302
340
|
// 不硬编码、未配置 ⇒ 缺省同修前。实证:deepseek 同值 95.69% / 异值首现 0%;族差/窗差:百炼 qwen 另有 `enable_thinking` 派生差、autoThink 的 turn 0 有改写窗口——登记见批次档 §5 上抛)。
|
|
303
341
|
// Silent by design (D11): no onToken/onReasoning — the compaction process must not stream to the frontend.
|
|
304
342
|
// signal propagates user cancellation (Ctrl+C) to the in-flight summary call.
|
|
@@ -322,8 +360,9 @@ export async function compressIfNeeded(agent, threshold, callbacks, extras, sign
|
|
|
322
360
|
agent._compactCheckpoint?.compactionSummary ?? null,
|
|
323
361
|
agent.provider?.name,
|
|
324
362
|
spec,
|
|
325
|
-
isThinkingRequest({ ...agent.
|
|
363
|
+
isThinkingRequest({ ...(agent.modelParams ?? {}), thinking: null }, spec),
|
|
326
364
|
Array.isArray(extras?.tools) && extras.tools.length > 0,
|
|
365
|
+
{ sessionHead: agent._sessionHead, retained: agent._retained, turnBlock: turnBlockOf(agent) },
|
|
327
366
|
)
|
|
328
367
|
if (extras.focus) {
|
|
329
368
|
const last = messages.at(-1)
|
|
@@ -333,10 +372,15 @@ export async function compressIfNeeded(agent, threshold, callbacks, extras, sign
|
|
|
333
372
|
let summarized = false
|
|
334
373
|
let summaryError = null
|
|
335
374
|
try {
|
|
336
|
-
const summary = await chat({ ...agent.provider
|
|
375
|
+
const summary = await chat({ ...agent.provider }, {
|
|
337
376
|
messages,
|
|
338
377
|
tools: extras?.tools,
|
|
339
378
|
signal,
|
|
379
|
+
// 会话设置(模型窗口声明 ∥ 档位上限)随调用传——2026-12-03 批:不再拷到 provider 克隆上。
|
|
380
|
+
settings: agent.config,
|
|
381
|
+
// 压缩下行的模型语义参数(2026-12-03 批,台账 #133):逐位继承会话设置,仅强制 `thinking: null`
|
|
382
|
+
//(族别 off 标记;effort 族由载荷门补发 `reasoning_effort:"none"`)——不再是 provider 克隆上的字段。
|
|
383
|
+
modelParams: { ...(agent.modelParams ?? {}), thinking: null },
|
|
340
384
|
// TRACES.md §6.1 D-TR4:轨迹元数据增补——kind=compress(上下文构建面——agent 元数据透出;
|
|
341
385
|
// depth 经 extras.traceDepth——agent.mjs 主作用域传入——compress 调用点补齐)
|
|
342
386
|
logCtx: {
|
|
@@ -391,8 +435,9 @@ export function compressFallback(agent, workState, outline) {
|
|
|
391
435
|
// 本函数没有 extras 形参(调用点只有同档的 `compressIfNeeded`),非对话面就取本回合暂存那一份。
|
|
392
436
|
const usage = contextUsage(agent, agent?._ctxBasis?.overhead ?? {})
|
|
393
437
|
const flat = flattenHistory(agent.history)
|
|
394
|
-
const keepTail = keepTailSize(agent.provider, flat.length)
|
|
395
|
-
const
|
|
438
|
+
const keepTail = keepTailSize(agent.provider, flat.length, agent.config)
|
|
439
|
+
const tailBudget = tailBudgetTokens(agent.provider, usage.fixed - usage.compactionSummary, ratio, usage.threshold, agent.config)
|
|
440
|
+
const split = selectCompactionSplit(agent, flat, keepTail, tailBudget, usage, usage.threshold)
|
|
396
441
|
if (!split) return false
|
|
397
442
|
const tailMessages = flat.length - split.tailStart
|
|
398
443
|
const discardedMessages = split.tailStart - split.headEnd
|