dsh-lean-router 2.2.5 → 2.2.7
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/cordis.patch.yml +19 -0
- package/docs/changelog.en.md +24 -1
- package/docs/changelog.md +24 -1
- package/lib/lean/history-downgrade.js +345 -0
- package/lib/lean/usage-ledger.js +204 -14
- package/lib/token-ledger/live.js +9 -0
- package/package.json +2 -1
- package/presets/base/frag-lean.patch.yml +12 -0
- package/presets/base/frag-preset.patch.yml +7 -0
- package/test/history-downgrade.test.mjs +379 -0
- package/test/integration-preset.test.mjs +2 -2
- package/test/lean-frag.test.mjs +1 -1
- package/test/usage-ledger.test.mjs +193 -2
package/cordis.patch.yml
CHANGED
|
@@ -286,6 +286,13 @@
|
|
|
286
286
|
name: 'dsh-lean-router/lean/usage-ledger'
|
|
287
287
|
config:
|
|
288
288
|
enabled: true
|
|
289
|
+
# 旧工具结果降级:agent/pre-step(waterfall,历史定稿前)把未降级 tool/result 攒到 >32 条时
|
|
290
|
+
# 批量换成一行占位符,最近 6 条永远保留原样;DSH_LEAN_ROUTER_DOWNGRADE=0 可关。
|
|
291
|
+
# 失败安全:钩子体全包 try/catch,异常只 warn 一次、绝不阻断 step;实现 = lib/lean/history-downgrade.js。
|
|
292
|
+
- id: lean-history-downgrade
|
|
293
|
+
name: 'dsh-lean-router/lean/history-downgrade'
|
|
294
|
+
config:
|
|
295
|
+
enabled: true
|
|
289
296
|
|
|
290
297
|
# ============ 新增行:preset-lean-router-balance(balance 档 3 条;上游双预设形态,flash-lean-ptc-v3-balance 同构)============
|
|
291
298
|
|
|
@@ -467,6 +474,11 @@
|
|
|
467
474
|
name: 'dsh-lean-router/lean/usage-ledger'
|
|
468
475
|
config:
|
|
469
476
|
enabled: true
|
|
477
|
+
# 旧工具结果降级(balance 档同挂):见 lean 档同名行说明。
|
|
478
|
+
- id: lean-history-downgrade
|
|
479
|
+
name: 'dsh-lean-router/lean/history-downgrade'
|
|
480
|
+
config:
|
|
481
|
+
enabled: true
|
|
470
482
|
|
|
471
483
|
# ============ 新增行:交付门(加料件)============
|
|
472
484
|
# 默认关闭(enabled: false):它会执行工作区里的验收脚本,要用户显式打开
|
|
@@ -817,6 +829,13 @@
|
|
|
817
829
|
name: 'dsh-lean-router/lean/usage-ledger'
|
|
818
830
|
config:
|
|
819
831
|
enabled: true
|
|
832
|
+
# 旧工具结果降级:agent/pre-step(waterfall,历史定稿前)把未降级 tool/result 攒到 >32 条时
|
|
833
|
+
# 批量换成一行占位符,最近 6 条永远保留原样;DSH_LEAN_ROUTER_DOWNGRADE=0 可关。
|
|
834
|
+
# 失败安全:钩子体全包 try/catch,异常只 warn 一次、绝不阻断 step;实现 = lib/lean/history-downgrade.js。
|
|
835
|
+
- id: lean-history-downgrade
|
|
836
|
+
name: 'dsh-lean-router/lean/history-downgrade'
|
|
837
|
+
config:
|
|
838
|
+
enabled: true
|
|
820
839
|
|
|
821
840
|
# ============ 新增行:preset-lean-router-balance(balance 档 3 条;上游双预设形态,flash-lean-ptc-v3-balance 同构)============
|
|
822
841
|
|
package/docs/changelog.en.md
CHANGED
|
@@ -1,6 +1,29 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
-
> English version of [changelog.md](./changelog.md). Versions follow package.json (currently 2.2.
|
|
3
|
+
> English version of [changelog.md](./changelog.md). Versions follow package.json (currently 2.2.7).
|
|
4
|
+
|
|
5
|
+
## 2.2.7 (2026-11-30)
|
|
6
|
+
|
|
7
|
+
### Added
|
|
8
|
+
|
|
9
|
+
- **Ledger snapshot on disk**: after recording one usage entry, the ledger atomically writes an aggregate to `<DSH_HOME>/storages/lean-router/token-report.json` (`DSH_HOME` defaults to `~/.dsh`; override with `config.snapshotPath`, disable with `config.snapshot: false`). The agent can now `read` the same data the command shows instead of asking the user to copy it. The snapshot holds totals plus per-session records/prompt/input/cacheRead/cacheWrite/output/reasoning and the latest turn/step/seq.
|
|
10
|
+
- **`/token-report json` scope**: the command gains `json`, which prints the snapshot file content byte for byte; a missing file yields `{"error":"snapshot missing","path":"..."}`. The `session` and `all` text formats are unchanged.
|
|
11
|
+
- Writes are atomic (`.tmp` then rename) and the directory is created on demand; any write failure warns once and never affects recording or the command.
|
|
12
|
+
|
|
13
|
+
### Tests
|
|
14
|
+
|
|
15
|
+
- 6 new cases (default path and config resolution, single-record shape, cross-session aggregation, disable switch, write failure not throwing, `json` matching the file bytes); the full suite is 269 tests, 268 passing, 0 failing, 1 skipped.
|
|
16
|
+
|
|
17
|
+
## 2.2.6 (2026-11-29)
|
|
18
|
+
|
|
19
|
+
### Added
|
|
20
|
+
|
|
21
|
+
- **Old tool-result downgrade**: new `lean-history-downgrade` plugin. On `agent/pre-step` (before history is finalized) it inspects the model-visible tool results and, once the number of un-downgraded ones strictly exceeds 32, downgrades them in one batch while always keeping the 6 most recent intact; error results and already-downgraded results are skipped. Rewrites go through `session.append` with `surfaceOp: replace`, so the original events stay in the log and remain replayable, paired with a `compaction/prune` record. The plugin is fail-safe end to end: the hook body is wrapped in try/catch, failures only warn once and never block a step; missing `surface` capabilities are skipped silently; nothing throws at construction; `DSH_LEAN_ROUTER_DOWNGRADE=0` disables it entirely.
|
|
22
|
+
- **Why 32/6**: recomputed against the measured ~155k-token prefix per turn and the cache price gap, 16/6 amortizes to roughly 30k tokens saved per turn (19%) while 32/6 yields about 52k (34%), so 32/6 was chosen. A real Session test downgraded 33 of 39 results (each 12000 chars), saving 391,974 characters in one batch with surface length and order unchanged, and a second run changed nothing.
|
|
23
|
+
|
|
24
|
+
### Tests
|
|
25
|
+
|
|
26
|
+
- 23 new cases (9 pure-function, 14 plugin); the full suite is 263 tests, 262 passing, 0 failing, 1 skipped, with `verify` passing.
|
|
4
27
|
|
|
5
28
|
## 2.2.5 (2026-11-29)
|
|
6
29
|
|
package/docs/changelog.md
CHANGED
|
@@ -1,6 +1,29 @@
|
|
|
1
1
|
# 变更记录(changelog)
|
|
2
2
|
|
|
3
|
-
> 中文为主,英文版:[changelog.en.md](./changelog.en.md)。版本号遵循 package.json(当前 2.2.
|
|
3
|
+
> 中文为主,英文版:[changelog.en.md](./changelog.en.md)。版本号遵循 package.json(当前 2.2.7)。
|
|
4
|
+
|
|
5
|
+
## 2.2.7 (2026-11-30)
|
|
6
|
+
|
|
7
|
+
### 新增
|
|
8
|
+
|
|
9
|
+
- **账本快照落盘**:账本每记录一条 usage,就把汇总原子写入 `<DSH_HOME>/storages/lean-router/token-report.json`(`DSH_HOME` 缺省为 `~/.dsh`;可用 `config.snapshotPath` 覆盖路径、`config.snapshot: false` 关闭)。这样代理用 `read` 就能直接读到与命令同源的数据,不必再由用户复制粘贴。快照含 totals 与按会话聚合的 records/prompt/input/cacheRead/cacheWrite/output/reasoning 及最近 turn/step/seq。
|
|
10
|
+
- **`/token-report json` 口径**:命令新增 `json`,直接输出快照文件内容(与文件字节一致);文件不存在时返回 `{"error":"snapshot missing","path":"..."}`。`session` 与 `all` 的文本格式不变。
|
|
11
|
+
- 写入是原子的(先写 `.tmp` 再 rename),目录自动创建;任何写入失败只 warn 一次,不影响记录与命令。
|
|
12
|
+
|
|
13
|
+
### 测试
|
|
14
|
+
|
|
15
|
+
- 新增 6 项(默认路径与配置解析、单条记录结构、跨会话聚合、关闭开关、写失败不抛、`json` 与文件字节一致);全量 269 项、268 通过、0 失败、1 skip。
|
|
16
|
+
|
|
17
|
+
## 2.2.6 (2026-11-29)
|
|
18
|
+
|
|
19
|
+
### 新增
|
|
20
|
+
|
|
21
|
+
- **旧工具结果降级**:新增 `lean-history-downgrade` 插件,在 `agent/pre-step`(历史定稿前)检查模型可见的工具结果——未降级条数严格超过 32 条时批量降级,最近 6 条永远保留原样,错误结果与已降级结果跳过。改写走 `session.append` 的 `surfaceOp: replace`,原始事件保留在日志里可重放,并配套写一条 `compaction/prune`。插件全链路失败安全:钩子体整体 try/catch,异常只 warn 一次、绝不阻断 step;缺少 `surface` 相关能力时静默跳过;构造期不抛任何异常;`DSH_LEAN_ROUTER_DOWNGRADE=0` 可整体关闭。
|
|
22
|
+
- **为什么是 32/6**:按实测前缀约 155k token/轮与缓存价差重算,16/6 摊销后净省约 30k/轮(19%),32/6 约 52k/轮(34%),因此取 32/6。真实 Session 复测:39 条 × 12000 字符 → 选中并降级 33 条,本批省 391,974 字符,surface 长度与顺序不变,二次运行零变更。
|
|
23
|
+
|
|
24
|
+
### 测试
|
|
25
|
+
|
|
26
|
+
- 新增 23 项(纯函数 9 项、插件 14 项);全量 263 项、262 通过、0 失败、1 skip,verify 全 PASS。
|
|
4
27
|
|
|
5
28
|
## 2.2.5 (2026-11-29)
|
|
6
29
|
|
|
@@ -0,0 +1,345 @@
|
|
|
1
|
+
// dsh-lean-router · lib/lean/history-downgrade.js —— 加料件 · 旧工具结果降级(改写「模型可见的历史」)
|
|
2
|
+
//
|
|
3
|
+
// 目标:会话变长后,早期工具结果(几万字符的读文件/命令输出)仍在 prefix 里,每轮都要为它们付
|
|
4
|
+
// prompt token;把它们换成一行占位符,模型需要时可以重新读/重跑。批与批之间前缀保持稳定:
|
|
5
|
+
// 只有「未降级的工具结果 > DOWNGRADE_TRIGGER」才动一次,且永远保留最近 DOWNGRADE_KEEP 条原样。
|
|
6
|
+
//
|
|
7
|
+
// 机制(照抄宿主 @deepseek-ai/dsh-compaction-tool-result-pruner 的写法,证据:
|
|
8
|
+
// .agent-master/pruner-index.md L137-191 pruneSession):
|
|
9
|
+
// 1. agent/pre-step 是 waterfall(dsh-agent/lib/types/runtime-types.d.ts L333-340):
|
|
10
|
+
// `(payload: { agent, messages, turn, step, signal, modelSelection }, next) => Promise<PreStepDecision>`,
|
|
11
|
+
// 每个 step 一次、历史定稿前;所以在这里改写 surface 会进入本次请求的 model-visible 历史。
|
|
12
|
+
// 2. 先 `session.append('compaction/prune', { shadowedRange, shadowedSeqs, shadowedTokenCount })`
|
|
13
|
+
// 记影子价格(事件 data 形状见宿主 SessionEventMap:
|
|
14
|
+
// `{ shadowedRange: { start, end }, shadowedSeqs: SessionSeq[], shadowedTokenCount: number }`;
|
|
15
|
+
// 本仓抽取稿 pruner-index.md L159-166 同形)。
|
|
16
|
+
// 3. 再 `session.append('tool/result', { ...event.data, message: 裁剪后的 message },
|
|
17
|
+
// { surfaceOp: { op: 'replace', startSeq: seq, endSeq: seq }, sourceEventSeqs: [seq] })`
|
|
18
|
+
// 覆盖旧节点。原事件留在 append-only 日志里,replacement 通过 sourceEventSeqs 引用它,可重放。
|
|
19
|
+
// 4. tool/result 的 data 形状:`{ turn, step, message, error?, meta? }`
|
|
20
|
+
// (dsh-session/lib/types/types.d.ts L382-396);append 校验只要求 data 是对象,且
|
|
21
|
+
// `error` 存在时 `message.isError === true`(dsh-session/lib/index.js L272-277)——
|
|
22
|
+
// 本模块跳过 isError 结果,因此不会触碰这条约束。
|
|
23
|
+
//
|
|
24
|
+
// 失败安全(本文件最重要的一条):钩子体全部包在 try/catch 里,异常只 warn 一次、绝不 throw、
|
|
25
|
+
// 绝不 return 会阻断 step 的东西;读不到 session.surface / eventAt / deriveEventMessage / append
|
|
26
|
+
// 任何一个依赖就静默跳过(feature-detect),不改任何行为。
|
|
27
|
+
//
|
|
28
|
+
// 不静态 import 宿主包(仓库约定,见 lib/lean/delivery-gate.js L8-10):
|
|
29
|
+
// - message 不需要 freezeMessage(它只是 deepFreeze(structuredClone(x)),dsh-llm/lib/index.js L30-32),
|
|
30
|
+
// session.append 自己会快照/冻结事件 data;这里用普通对象重建 message 即可。
|
|
31
|
+
// - tokenMeter 通过 `ctx.reflect.get('tokenMeter')` 可选读取;未提供时返回 undefined 而不是抛
|
|
32
|
+
// (cordis/lib/index.js L1347-1356),拿不到就跳过 compaction/prune 记录(不写假 token 数),
|
|
33
|
+
// 但替换照做 —— 模型可见历史变短这件事不依赖计价事件。
|
|
34
|
+
|
|
35
|
+
/** 未降级的工具结果超过这个条数才触发一次批量降级(严格大于)。 */
|
|
36
|
+
export const DOWNGRADE_TRIGGER = 32;
|
|
37
|
+
|
|
38
|
+
/** 无论阈值如何,最近这么多条工具结果永远保持原样(给模型留当前工作上下文)。 */
|
|
39
|
+
export const DOWNGRADE_KEEP = 6;
|
|
40
|
+
|
|
41
|
+
/** 已降级占位符的识别标记;占位符文本一定包含它,用于批与批之间跳过已处理的节点。 */
|
|
42
|
+
export const DOWNGRADE_MARK = '[... tool result downgraded to save context';
|
|
43
|
+
|
|
44
|
+
/** 插件名(preset 行 id / name 同源)。 */
|
|
45
|
+
export const name = 'lean-history-downgrade';
|
|
46
|
+
|
|
47
|
+
const TAG = '[lean-history-downgrade]';
|
|
48
|
+
|
|
49
|
+
/** 环境变量关闭开关:=0 时不注册钩子。 */
|
|
50
|
+
const ENV_OFF = 'DSH_LEAN_ROUTER_DOWNGRADE';
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* 模块级 warn 去重:钩子每 step 都会跑,同一个故障不该每 step 刷一行日志。
|
|
54
|
+
* 测试可用 `__internals.resetWarning()` 复位。
|
|
55
|
+
*/
|
|
56
|
+
let warnedOnce = false;
|
|
57
|
+
|
|
58
|
+
function describeError(error) {
|
|
59
|
+
if (error && typeof error.message === 'string') return error.message;
|
|
60
|
+
return String(error);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function warnOnce(ctx, message) {
|
|
64
|
+
if (warnedOnce) return;
|
|
65
|
+
warnedOnce = true;
|
|
66
|
+
const logger = ctx && typeof ctx === 'object' ? ctx.logger : undefined;
|
|
67
|
+
if (!logger || typeof logger.warn !== 'function') return;
|
|
68
|
+
try {
|
|
69
|
+
logger.warn(TAG + ' ' + message);
|
|
70
|
+
} catch {
|
|
71
|
+
// A logger must never break the step.
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** 按 Unicode 码点计数(与宿主 pruner 同口径,不拆代理对)。 */
|
|
76
|
+
function codePointLength(text) {
|
|
77
|
+
return Array.from(text).length;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* 占位符文本:一行,说明省掉了多少字符、以及怎么拿回原文。
|
|
82
|
+
* @param elidedChars - 被省掉的字符数(码点)。
|
|
83
|
+
* @returns 单行占位符。
|
|
84
|
+
*/
|
|
85
|
+
export function downgradeText(elidedChars) {
|
|
86
|
+
const chars = Number.isFinite(elidedChars) && elidedChars > 0 ? Math.floor(elidedChars) : 0;
|
|
87
|
+
return '[... tool result downgraded to save context: ' + chars
|
|
88
|
+
+ ' chars elided; re-run the tool or read the relevant slice if needed ...]';
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* tool-result message 的文本字符总量(非 text 块不计;与宿主 measureContent 同口径)。
|
|
93
|
+
* @param message - { content: ContentBlock[] } 形态的消息。
|
|
94
|
+
* @returns 文本码点数。
|
|
95
|
+
*/
|
|
96
|
+
export function messageChars(message) {
|
|
97
|
+
if (!message || !Array.isArray(message.content)) return 0;
|
|
98
|
+
let chars = 0;
|
|
99
|
+
for (const block of message.content) {
|
|
100
|
+
if (block && block.type === 'text' && typeof block.text === 'string') {
|
|
101
|
+
chars += codePointLength(block.text);
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
return chars;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* 该 message 是否已经是降级占位符。
|
|
109
|
+
* @param message - { content: ContentBlock[] } 形态的消息。
|
|
110
|
+
* @returns true 表示已经降级过(跳过,避免重复改写)。
|
|
111
|
+
*/
|
|
112
|
+
export function isDowngradedMessage(message) {
|
|
113
|
+
if (!message || !Array.isArray(message.content)) return false;
|
|
114
|
+
for (const block of message.content) {
|
|
115
|
+
if (block && block.type === 'text' && typeof block.text === 'string'
|
|
116
|
+
&& block.text.includes(DOWNGRADE_MARK)) {
|
|
117
|
+
return true;
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
return false;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** 选项归一化:非法值静默回落到默认(纯函数,构造期绝不抛)。 */
|
|
124
|
+
function nonNegativeInt(value, fallback) {
|
|
125
|
+
return Number.isInteger(value) && value >= 0 ? value : fallback;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function isResultLike(result) {
|
|
129
|
+
return !!result && typeof result === 'object' && Number.isSafeInteger(result.seq) && result.seq >= 0;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* 选出本次要降级的工具结果 seq(纯函数,可脱离宿主单测)。
|
|
134
|
+
*
|
|
135
|
+
* 规则(顺序固定):
|
|
136
|
+
* 1. 按 seq 升序;最后 keep 条(默认 6)永不降级 —— 这是「最近工作上下文」窗口。
|
|
137
|
+
* 2. keep 窗口之外,跳过 isError === true(错误结果保持原样)与 alreadyDowngraded === true
|
|
138
|
+
* (已降级的 surface 上已经变短,再动就是无谓改写)。
|
|
139
|
+
* 3. 剩下的「可降级条数」严格大于 trigger(默认 32)才触发;否则返回空数组。
|
|
140
|
+
* 4. 触发时返回窗口外全部尚未降级的 seq —— 一次批量降完,下一批要重新攒够阈值,
|
|
141
|
+
* 批与批之间前缀不变。
|
|
142
|
+
*
|
|
143
|
+
* @param results - [{ seq, chars?, isError?, alreadyDowngraded? }],顺序任意。
|
|
144
|
+
* @param options - { trigger?, keep? } 覆盖默认阈值/保留条数。
|
|
145
|
+
* @returns 按 seq 升序的待降级 seq 数组;不触发时为空数组。
|
|
146
|
+
*/
|
|
147
|
+
export function selectDowngradeTargets(results, options) {
|
|
148
|
+
const list = Array.isArray(results) ? results.filter(isResultLike) : [];
|
|
149
|
+
if (list.length === 0) return [];
|
|
150
|
+
const opts = options && typeof options === 'object' ? options : {};
|
|
151
|
+
const trigger = nonNegativeInt(opts.trigger, DOWNGRADE_TRIGGER);
|
|
152
|
+
const keep = nonNegativeInt(opts.keep, DOWNGRADE_KEEP);
|
|
153
|
+
const sorted = [...list].sort((a, b) => a.seq - b.seq);
|
|
154
|
+
const keepStart = Math.max(0, sorted.length - keep);
|
|
155
|
+
const targets = [];
|
|
156
|
+
for (let index = 0; index < sorted.length; index++) {
|
|
157
|
+
if (index >= keepStart) break;
|
|
158
|
+
const result = sorted[index];
|
|
159
|
+
if (result.isError === true) continue;
|
|
160
|
+
if (result.alreadyDowngraded === true) continue;
|
|
161
|
+
targets.push(result.seq);
|
|
162
|
+
}
|
|
163
|
+
return targets.length > trigger ? targets : [];
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/**
|
|
167
|
+
* 依赖探测:改历史需要的四件套齐了才动,缺任何一件静默跳过。
|
|
168
|
+
* @param session - payload.agent.session。
|
|
169
|
+
* @returns true 表示可以安全改写。
|
|
170
|
+
*/
|
|
171
|
+
export function isSupportedSession(session) {
|
|
172
|
+
if (!session || typeof session !== 'object') return false;
|
|
173
|
+
const surface = session.surface;
|
|
174
|
+
return !!surface && Array.isArray(surface.nodes)
|
|
175
|
+
&& typeof session.eventAt === 'function'
|
|
176
|
+
&& typeof session.append === 'function'
|
|
177
|
+
&& typeof session.deriveEventMessage === 'function';
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* 从当前 surface 收集工具结果(按 model-visible 顺序),只读。
|
|
182
|
+
* @param session - 已通过 isSupportedSession 的会话。
|
|
183
|
+
* @returns [{ seq, chars, isError, alreadyDowngraded, event, message }]
|
|
184
|
+
*/
|
|
185
|
+
export function collectToolResults(session) {
|
|
186
|
+
const results = [];
|
|
187
|
+
for (const seq of [...session.surface.nodes]) {
|
|
188
|
+
const event = session.eventAt(seq);
|
|
189
|
+
if (!event || event.type !== 'tool/result') continue;
|
|
190
|
+
const message = session.deriveEventMessage(event);
|
|
191
|
+
if (!message) continue;
|
|
192
|
+
results.push({
|
|
193
|
+
seq,
|
|
194
|
+
chars: messageChars(message),
|
|
195
|
+
isError: message.isError === true,
|
|
196
|
+
alreadyDowngraded: isDowngradedMessage(message),
|
|
197
|
+
event,
|
|
198
|
+
message,
|
|
199
|
+
});
|
|
200
|
+
}
|
|
201
|
+
return results;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/**
|
|
205
|
+
* 可选读取 tokenMeter:cordis 的 reflect.get 在服务未提供时返回 undefined(不抛),
|
|
206
|
+
* 因此不需要 inject 声明,也不会因为缺服务让插件不加载。
|
|
207
|
+
*/
|
|
208
|
+
function readTokenMeter(ctx) {
|
|
209
|
+
try {
|
|
210
|
+
const reflect = ctx && typeof ctx === 'object' ? ctx.reflect : undefined;
|
|
211
|
+
if (!reflect || typeof reflect.get !== 'function') return null;
|
|
212
|
+
const meter = reflect.get('tokenMeter');
|
|
213
|
+
return meter && typeof meter.estimateMessage === 'function' ? meter : null;
|
|
214
|
+
} catch {
|
|
215
|
+
return null;
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/** 影子价格:拿不到 token 计量就返回 null(宁可不记,也不写假数字)。 */
|
|
220
|
+
function estimateShadowTokens(meter, message) {
|
|
221
|
+
if (!meter) return null;
|
|
222
|
+
try {
|
|
223
|
+
const value = meter.estimateMessage(message);
|
|
224
|
+
return Number.isFinite(value) && value >= 0 ? Math.round(value) : null;
|
|
225
|
+
} catch {
|
|
226
|
+
return null;
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
/**
|
|
231
|
+
* 执行一次降级 pass(每 step 最多一批)。
|
|
232
|
+
*
|
|
233
|
+
* 只在上面的阈值满足时写日志;每个目标先记 compaction/prune 影子价格,再 append 替换事件。
|
|
234
|
+
* @param session - payload.agent.session。
|
|
235
|
+
* @param ctx - 插件上下文(可选 logger / reflect)。
|
|
236
|
+
* @param options - { trigger?, keep? }。
|
|
237
|
+
* @returns null(依赖不全,静默跳过)或 { targets, downgraded, charsRemoved }。
|
|
238
|
+
*/
|
|
239
|
+
export function downgradeSession(session, ctx, options) {
|
|
240
|
+
if (!isSupportedSession(session)) return null;
|
|
241
|
+
const opts = options && typeof options === 'object' ? options : {};
|
|
242
|
+
const results = collectToolResults(session);
|
|
243
|
+
const targets = selectDowngradeTargets(results, opts);
|
|
244
|
+
const report = { targets, downgraded: [], charsRemoved: 0 };
|
|
245
|
+
if (targets.length === 0) return report;
|
|
246
|
+
const bySeq = new Map(results.map((result) => [result.seq, result]));
|
|
247
|
+
const meter = readTokenMeter(ctx);
|
|
248
|
+
for (const seq of targets) {
|
|
249
|
+
const result = bySeq.get(seq);
|
|
250
|
+
if (!result || !result.event) continue;
|
|
251
|
+
const elided = result.chars;
|
|
252
|
+
const placeholder = downgradeText(elided);
|
|
253
|
+
const placeholderChars = codePointLength(placeholder);
|
|
254
|
+
// 占位符不比方短就毫无收益,跳过(不制造「降级后更长」的历史)。
|
|
255
|
+
if (elided <= 0 || placeholderChars >= elided) continue;
|
|
256
|
+
const message = { ...result.message, content: [{ type: 'text', text: placeholder }] };
|
|
257
|
+
const shadowTokens = estimateShadowTokens(meter, result.message);
|
|
258
|
+
if (shadowTokens !== null) {
|
|
259
|
+
session.append('compaction/prune', {
|
|
260
|
+
shadowedRange: { start: seq, end: seq },
|
|
261
|
+
shadowedSeqs: [seq],
|
|
262
|
+
shadowedTokenCount: shadowTokens,
|
|
263
|
+
});
|
|
264
|
+
}
|
|
265
|
+
session.append('tool/result', { ...result.event.data, message }, {
|
|
266
|
+
surfaceOp: { op: 'replace', startSeq: seq, endSeq: seq },
|
|
267
|
+
sourceEventSeqs: [seq],
|
|
268
|
+
});
|
|
269
|
+
report.downgraded.push(seq);
|
|
270
|
+
report.charsRemoved += elided - placeholderChars;
|
|
271
|
+
}
|
|
272
|
+
return report;
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
/**
|
|
276
|
+
* 插件配置归一化:只认 `{ enabled?, trigger?, keep? }`;非法值回落默认,绝不抛。
|
|
277
|
+
*/
|
|
278
|
+
export function resolveConfig(config) {
|
|
279
|
+
const source = config && typeof config === 'object' ? config : {};
|
|
280
|
+
return {
|
|
281
|
+
enabled: source.enabled !== false,
|
|
282
|
+
trigger: nonNegativeInt(source.trigger, DOWNGRADE_TRIGGER),
|
|
283
|
+
keep: nonNegativeInt(source.keep, DOWNGRADE_KEEP),
|
|
284
|
+
};
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
/**
|
|
288
|
+
* waterfall 体:任何异常都只 warn 一次,然后照常 `next()`,绝不阻断 step。
|
|
289
|
+
* @param ctx - 插件上下文(可选 logger / reflect)。
|
|
290
|
+
* @param payload - agent/pre-step payload。
|
|
291
|
+
* @param next - waterfall 的下一段(宿主提供)。
|
|
292
|
+
* @param options - { trigger?, keep? },来自 apply 已归一化的配置。
|
|
293
|
+
* @returns next() 的 PreStepDecision;next 不可调用时返回 undefined(不改决策)。
|
|
294
|
+
*/
|
|
295
|
+
export async function handlePreStep(ctx, payload, next, options) {
|
|
296
|
+
try {
|
|
297
|
+
const agent = payload && typeof payload === 'object' ? payload.agent : undefined;
|
|
298
|
+
const session = agent && typeof agent === 'object' ? agent.session : undefined;
|
|
299
|
+
if (session) downgradeSession(session, ctx, options);
|
|
300
|
+
} catch (error) {
|
|
301
|
+
warnOnce(ctx, 'history downgrade skipped this step: ' + describeError(error));
|
|
302
|
+
}
|
|
303
|
+
if (typeof next === 'function') return next();
|
|
304
|
+
return undefined;
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
/**
|
|
308
|
+
* 插件入口(形态与 lib/lean/usage-ledger.js 的 apply 一致):
|
|
309
|
+
* DSH_LEAN_ROUTER_DOWNGRADE=0 或 config.enabled === false 时不注册;构造期不抛任何异常。
|
|
310
|
+
*/
|
|
311
|
+
export function apply(ctx, config) {
|
|
312
|
+
const resolved = resolveConfig(config);
|
|
313
|
+
if (!resolved.enabled) return;
|
|
314
|
+
// 环境变量读取也防御:非 Node 宿主(无 process)不得在构造期抛。
|
|
315
|
+
const env = typeof process === 'object' && process ? process.env : undefined;
|
|
316
|
+
if (env && env[ENV_OFF] === '0') return;
|
|
317
|
+
const context = ctx && typeof ctx === 'object' ? ctx : {};
|
|
318
|
+
if (typeof context.on !== 'function') {
|
|
319
|
+
warnOnce(context, 'ctx.on is unavailable; ' + name + ' not registered');
|
|
320
|
+
return;
|
|
321
|
+
}
|
|
322
|
+
// 配置闭包进 handler,绝不往 ctx 上写字段(会污染宿主上下文,也可能破坏服务代理)。
|
|
323
|
+
const handlerConfig = { trigger: resolved.trigger, keep: resolved.keep };
|
|
324
|
+
try {
|
|
325
|
+
context.on('agent/pre-step', (payload, next) => handlePreStep(context, payload, next, handlerConfig));
|
|
326
|
+
} catch (error) {
|
|
327
|
+
warnOnce(context, 'could not register agent/pre-step: ' + describeError(error));
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
/** 默认导出(插件行兼容形态,与命名导出同体)。 */
|
|
332
|
+
export default { name, apply };
|
|
333
|
+
|
|
334
|
+
/** 测试与集成内用的内部实现出口。 */
|
|
335
|
+
export const __internals = {
|
|
336
|
+
TAG,
|
|
337
|
+
ENV_OFF,
|
|
338
|
+
probeTokenMeter: readTokenMeter,
|
|
339
|
+
resetWarning() {
|
|
340
|
+
warnedOnce = false;
|
|
341
|
+
},
|
|
342
|
+
isWarningLatched() {
|
|
343
|
+
return warnedOnce;
|
|
344
|
+
},
|
|
345
|
+
};
|