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.
@@ -4,11 +4,19 @@
4
4
  // 带 usage 的 assistant/message 并按 session/turn/step/seq 去重落账,但此前没有任何地方
5
5
  // 调用它,运行时完全不采集。本模块把它挂到宿主 preset:
6
6
  // 1. 创建 live adapter(订阅失败由适配器自己 warn 降级,绝不抛);
7
- // 2. 注册斜杠命令 token-report([session|all]),读账本 + createTokenReport 生成报告;
8
- // 3. 宿主 dispose 时卸载适配器与订阅,重复卸载幂等。
7
+ // 2. 注册斜杠命令 token-report([session|all|json]),读账本 + createTokenReport 生成报告;
8
+ // json 口径直接回放落盘快照,人和代理读到同一份数据;
9
+ // 3. 每真正记录一条 usage 就把「totals + 各会话聚合」原子写进
10
+ // <DSH_HOME>/storages/lean-router/token-report.json(config.snapshotPath 可改路径,
11
+ // config.snapshot === false 可关),写失败只 warn 一次,绝不影响采集与命令;
12
+ // 4. 宿主 dispose 时卸载适配器与订阅,重复卸载幂等。
9
13
  // 与 live.js 同口径:所有失败路径只 warn 不抛 —— 账本采集不得破坏宿主。
10
14
  // 数据同源:报告字段 = lib/token-ledger/index.js 的 createTokenReport
11
15
  // (usage.prompt = input + cacheRead + cacheWrite,五项分项由 normalizeUsage 补零)。
16
+ import { mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
17
+ import { homedir } from 'node:os';
18
+ import { dirname, isAbsolute, join, resolve } from 'node:path';
19
+
12
20
  import { createTokenReport } from '../token-ledger/index.js';
13
21
  import { createLiveUsageAdapter } from '../token-ledger/live.js';
14
22
 
@@ -22,10 +30,27 @@ export const inject = ['commands'];
22
30
 
23
31
  const TAG = '[lean-usage-ledger]';
24
32
  const COMMAND_NAME = 'token-report';
25
- const SCOPES = ['session', 'all'];
33
+ const SCOPES = ['session', 'all', 'json'];
26
34
  // 会话跟踪只服务于 /token-report all,上限与 delivery-gate 的 SESSION_CAP 同量级。
27
35
  const SESSION_CAP = 200;
28
36
  const EMPTY_HINT = '尚未采集到 usage,可能本会话还没有 assistant/message 事件';
37
+ const SNAPSHOT_SUBDIR = ['storages', 'lean-router'];
38
+ const SNAPSHOT_FILE = 'token-report.json';
39
+ const SNAPSHOT_TMP_SUFFIX = '.tmp';
40
+ // usage 分项 → 快照字段;prompt 恒为 input + cacheRead + cacheWrite(与 createTokenReport 同口径)。
41
+ const SNAPSHOT_FIELDS = [
42
+ ['input', 'inputTokens'],
43
+ ['cacheRead', 'cacheReadTokens'],
44
+ ['cacheWrite', 'cacheWriteTokens'],
45
+ ['output', 'outputTokens'],
46
+ ['reasoning', 'reasoningTokens'],
47
+ ];
48
+ // 写盘/读盘失败的告警按「用途 + 路径」模块级去重:一个坏路径只响一次,绝不随事件刷屏。
49
+ const warnedSnapshotFailures = new Set();
50
+
51
+ function toNumber(value) {
52
+ return typeof value === 'number' && Number.isFinite(value) ? value : 0;
53
+ }
29
54
 
30
55
  function describeError(error) {
31
56
  if (error && typeof error.message === 'string') return error.message;
@@ -42,13 +67,107 @@ function warn(ctx, message) {
42
67
  }
43
68
  }
44
69
 
70
+ /** 同一条失败只 warn 一次(模块级去重)。 */
71
+ function warnSnapshotOnce(ctx, key, message) {
72
+ if (warnedSnapshotFailures.has(key)) return;
73
+ warnedSnapshotFailures.add(key);
74
+ warn(ctx, message);
75
+ }
76
+
77
+ /** <DSH_HOME>:优先环境变量,退回 ~/.dsh;两者都拿不到时用相对目录,仍不抛。 */
78
+ function dshHome() {
79
+ const fromEnv = process.env.DSH_HOME;
80
+ if (typeof fromEnv === 'string' && fromEnv.trim().length > 0) return fromEnv.trim();
81
+ try {
82
+ return join(homedir(), '.dsh');
83
+ } catch {
84
+ return '.dsh';
85
+ }
86
+ }
87
+
88
+ /**
89
+ * 快照落盘路径:`config.snapshotPath`(非空字符串)优先,相对路径按 cwd 解析;
90
+ * 否则 `<DSH_HOME>/storages/lean-router/token-report.json`。读取时取值,便于测试与配置热改。
91
+ */
92
+ export function resolveSnapshotPath(configured) {
93
+ if (typeof configured === 'string' && configured.trim().length > 0) {
94
+ const raw = configured.trim();
95
+ return isAbsolute(raw) ? raw : resolve(raw);
96
+ }
97
+ return join(dshHome(), ...SNAPSHOT_SUBDIR, SNAPSHOT_FILE);
98
+ }
99
+
100
+ function emptyStats() {
101
+ return {
102
+ records: 0,
103
+ prompt: 0,
104
+ input: 0,
105
+ cacheRead: 0,
106
+ cacheWrite: 0,
107
+ output: 0,
108
+ reasoning: 0,
109
+ };
110
+ }
111
+
112
+ function compareRecords(left, right) {
113
+ return toNumber(left.turn) - toNumber(right.turn)
114
+ || toNumber(left.step) - toNumber(right.step)
115
+ || toNumber(left.seq) - toNumber(right.seq);
116
+ }
117
+
45
118
  /**
46
- * 归一化插件配置:只认 `{ enabled?: boolean }`,缺省开启;显式 false 才关闭。
119
+ * 把一个会话的记录聚合成快照里的一条 stats。
120
+ * 键序与快照契约一致(updatedAt 由 buildSnapshotPayload 追加);没有记录时 records 为 0。
121
+ */
122
+ export function summarizeRecords(records) {
123
+ const stats = emptyStats();
124
+ let latest = null;
125
+ for (const record of Array.isArray(records) ? records : []) {
126
+ if (!record || typeof record !== 'object') continue;
127
+ stats.records += 1;
128
+ const usage = record.usage && typeof record.usage === 'object' ? record.usage : {};
129
+ for (const [key, field] of SNAPSHOT_FIELDS) stats[key] += toNumber(usage[field]);
130
+ if (latest === null || compareRecords(record, latest) >= 0) latest = record;
131
+ }
132
+ stats.prompt = stats.input + stats.cacheRead + stats.cacheWrite;
133
+ const lastTurn = latest === null ? 0 : toNumber(latest.turn);
134
+ const lastStep = latest === null ? 0 : toNumber(latest.step);
135
+ const lastSeq = latest === null ? 0 : toNumber(latest.seq);
136
+ return { ...stats, lastTurn, lastStep, lastSeq };
137
+ }
138
+
139
+ /** 由各会话 stats 合成快照 payload:totals 为重算值,sessions 保留每会话聚合。 */
140
+ export function buildSnapshotPayload(statsById, updatedAt) {
141
+ const totals = emptyStats();
142
+ const sessions = {};
143
+ for (const [id, stats] of Object.entries(statsById ?? {})) {
144
+ sessions[id] = { ...stats, updatedAt };
145
+ totals.records += stats.records;
146
+ for (const [key] of SNAPSHOT_FIELDS) totals[key] += stats[key];
147
+ }
148
+ totals.prompt = totals.input + totals.cacheRead + totals.cacheWrite;
149
+ return { updatedAt, totals, sessions };
150
+ }
151
+
152
+ /** 原子写:先写 <path>.tmp 再 rename 覆盖,读者不会看到半截文件。目录缺失自动创建。 */
153
+ function writeSnapshotFile(file, payload) {
154
+ const tmp = file + SNAPSHOT_TMP_SUFFIX;
155
+ mkdirSync(dirname(file), { recursive: true });
156
+ writeFileSync(tmp, JSON.stringify(payload, null, 2) + '\n', 'utf8');
157
+ renameSync(tmp, file);
158
+ }
159
+
160
+ /**
161
+ * 归一化插件配置:只认 `{ enabled?, snapshot?, snapshotPath? }`,缺省全开;显式 false 才关闭。
47
162
  * 非对象 / 未知键不抛,按默认值继续(配置错误不该让宿主启动失败)。
48
163
  */
49
164
  export function resolveConfig(config) {
50
165
  const source = config && typeof config === 'object' ? config : {};
51
- return { enabled: source.enabled !== false };
166
+ return {
167
+ enabled: source.enabled !== false,
168
+ snapshot: source.snapshot !== false,
169
+ snapshotPath: resolveSnapshotPath(source.snapshotPath),
170
+ };
52
171
  }
53
172
 
54
173
  /** 从命令 invocation 里取当前会话 id(host 端 agent.session.id;测试可传裸对象)。 */
@@ -94,13 +213,16 @@ function formatReport(report, { scope = 'session', sessions = [] } = {}) {
94
213
  }
95
214
 
96
215
  /**
97
- * 账本运行时:live adapter + 会话跟踪 + token-report handler + dispose。
216
+ * 账本运行时:live adapter + 会话跟踪 + 快照落盘 + token-report handler + dispose。
98
217
  *
99
218
  * @param ctx - 插件上下文;只用 `on` 与 `logger`。缺 `on` 时适配器自身降级,本模块不抛。
100
- * @returns `{ adapter, handler, readRecords, dispose, seenSessions }`。
219
+ * @param config - 插件配置;这里只关心 `snapshot` / `snapshotPath`(`enabled` 由 apply 判断)。
220
+ * @returns `{ adapter, handler, readRecords, writeSnapshot, dispose, seenSessions, snapshotPath }`。
101
221
  */
102
- export function createUsageLedger(ctx) {
103
- const adapter = createLiveUsageAdapter(ctx);
222
+ export function createUsageLedger(ctx, config) {
223
+ const settings = resolveConfig(config);
224
+ const snapshotPath = settings.snapshotPath;
225
+ const snapshotEnabled = settings.snapshot;
104
226
  const seenSessions = [];
105
227
  const seen = new Set();
106
228
  let trackerOff = null;
@@ -124,6 +246,70 @@ export function createUsageLedger(ctx) {
124
246
  }
125
247
  }
126
248
 
249
+ // onRecord 只在 live.js 真正新增一条记录后回调,事件过滤口径与账本完全同源。
250
+ const adapter = createLiveUsageAdapter(ctx, {
251
+ onRecord: (record) => {
252
+ writeSnapshot(record);
253
+ },
254
+ });
255
+
256
+ /**
257
+ * 把账本汇总原子落盘,供代理自己读(`/token-report json` 与它同源)。
258
+ * 只在确实记录了一条 usage 时写;失败只 warn 一次,绝不抛、不影响记录与命令。
259
+ */
260
+ function writeSnapshot(trigger) {
261
+ if (!snapshotEnabled || disposed) return;
262
+ try {
263
+ const ids = [];
264
+ const push = (id) => {
265
+ if (typeof id === 'string' && id.length > 0 && !ids.includes(id)) ids.push(id);
266
+ };
267
+ for (const id of seenSessions) push(id);
268
+ // 新会话的首条事件里跟踪订阅可能还没跑(适配器先订阅),显式补上触发者。
269
+ if (trigger && typeof trigger === 'object') push(trigger.sessionId);
270
+
271
+ const updatedAt = new Date().toISOString();
272
+ const statsById = {};
273
+ for (const id of ids) {
274
+ let records = [];
275
+ try {
276
+ records = adapter.read(id, 0);
277
+ } catch (error) {
278
+ warn(ctx, 'snapshot read failed for session ' + id + ': ' + describeError(error));
279
+ continue;
280
+ }
281
+ const stats = summarizeRecords(records);
282
+ if (stats.records === 0) continue;
283
+ statsById[id] = stats;
284
+ }
285
+ writeSnapshotFile(snapshotPath, buildSnapshotPayload(statsById, updatedAt));
286
+ } catch (error) {
287
+ warnSnapshotOnce(
288
+ ctx,
289
+ 'write:' + snapshotPath,
290
+ 'snapshot write failed (' + snapshotPath + '): ' + describeError(error),
291
+ );
292
+ }
293
+ }
294
+
295
+ /** `json` 口径:回放落盘快照原文;缺失或读不出时给代理一个可解析的错误 JSON。 */
296
+ function readSnapshotText() {
297
+ try {
298
+ const text = readFileSync(snapshotPath, 'utf8');
299
+ if (typeof text === 'string' && text.trim().length > 0) return text;
300
+ } catch (error) {
301
+ // 文件还没写过是最常见的正常状态,不为 ENOENT 记告警。
302
+ if (!error || error.code !== 'ENOENT') {
303
+ warnSnapshotOnce(
304
+ ctx,
305
+ 'read:' + snapshotPath,
306
+ 'snapshot read failed (' + snapshotPath + '): ' + describeError(error),
307
+ );
308
+ }
309
+ }
310
+ return JSON.stringify({ error: 'snapshot missing', path: snapshotPath });
311
+ }
312
+
127
313
  /**
128
314
  * 按范围读记录:session = 当前会话(取不到会话时退回已跟踪集合);all = 已跟踪 ∪ 当前。
129
315
  * 单会话读失败只 warn 跳过,不让一条坏记录毁掉整份报告。
@@ -161,9 +347,10 @@ export function createUsageLedger(ctx) {
161
347
  : '';
162
348
  const scope = raw.length === 0 ? 'session' : raw;
163
349
  if (!SCOPES.includes(scope)) {
164
- warn(ctx, 'unknown scope "' + raw + '"; expected session or all');
165
- return { kind: 'error', text: '/' + COMMAND_NAME + ' 未知范围 "' + raw + '",用法:/' + COMMAND_NAME + ' [session|all]' };
350
+ warn(ctx, 'unknown scope "' + raw + '"; expected session, all or json');
351
+ return { kind: 'error', text: '/' + COMMAND_NAME + ' 未知范围 "' + raw + '",用法:/' + COMMAND_NAME + ' [session|all|json]' };
166
352
  }
353
+ if (scope === 'json') return { kind: 'success', text: readSnapshotText() };
167
354
  try {
168
355
  const collected = readRecords(invocation, scope);
169
356
  const report = createTokenReport({ records: collected.records });
@@ -192,7 +379,7 @@ export function createUsageLedger(ctx) {
192
379
  }
193
380
  }
194
381
 
195
- return { adapter, handler, readRecords, dispose, seenSessions };
382
+ return { adapter, handler, readRecords, writeSnapshot, dispose, seenSessions, snapshotPath };
196
383
  }
197
384
 
198
385
  /**
@@ -203,7 +390,7 @@ export function createUsageLedger(ctx) {
203
390
  export function apply(ctx, config) {
204
391
  const resolved = resolveConfig(config);
205
392
  if (!resolved.enabled) return;
206
- const ledger = createUsageLedger(ctx);
393
+ const ledger = createUsageLedger(ctx, resolved);
207
394
  const context = ctx && typeof ctx === 'object' ? ctx : {};
208
395
  const commands = context.commands;
209
396
 
@@ -212,7 +399,7 @@ export function apply(ctx, config) {
212
399
  commands.register({
213
400
  name: COMMAND_NAME,
214
401
  description: 'Report the live Usage ledger captured from assistant/message events',
215
- input: { hint: '[session|all]' },
402
+ input: { hint: '[session|all|json]' },
216
403
  handler: (invocation) => ledger.handler(invocation),
217
404
  });
218
405
  } catch (error) {
@@ -242,6 +429,9 @@ export default { name, inject, apply };
242
429
  /** 测试与集成内用的内部实现出口(不进公开契约文档)。 */
243
430
  export const __internals = {
244
431
  resolveConfig,
432
+ resolveSnapshotPath,
433
+ summarizeRecords,
434
+ buildSnapshotPayload,
245
435
  sessionIdOf,
246
436
  formatReport,
247
437
  createUsageLedger,
@@ -74,6 +74,8 @@ export function createLiveUsageAdapter(ctx = {}, options = {}) {
74
74
  const context = ctx && typeof ctx === 'object' ? ctx : {};
75
75
  const settings = options && typeof options === 'object' ? options : {};
76
76
  const logger = settings.logger ?? context.logger;
77
+ // 已落账通知:只在 commit 真正新增一条记录后触发,供上层同步派生视图(如 token 快照)。
78
+ const onRecord = typeof settings.onRecord === 'function' ? settings.onRecord : null;
77
79
  const adapter = createMemoryUsageAdapter();
78
80
  const committed = new Set();
79
81
  let disposed = false;
@@ -97,6 +99,13 @@ export function createLiveUsageAdapter(ctx = {}, options = {}) {
97
99
  warn('usage watcher failed: ' + describeError(error));
98
100
  }
99
101
  committed.add(key);
102
+ if (onRecord !== null) {
103
+ try {
104
+ onRecord(record);
105
+ } catch (error) {
106
+ warn('onRecord callback failed: ' + describeError(error));
107
+ }
108
+ }
100
109
  return true;
101
110
  }
102
111
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-lean-router",
3
- "version": "2.2.5",
3
+ "version": "2.2.7",
4
4
  "description": "lean 省 token × 思考链路由 × code_run 工具遮蔽的 DSH cordis 插件(单 bundle:预设)",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",
@@ -10,6 +10,7 @@
10
10
  "./router": "./lib/router.js",
11
11
  "./toolface": "./lib/toolface/index.js",
12
12
  "./lean/delivery-gate": "./lib/lean/delivery-gate.js",
13
+ "./lean/history-downgrade": "./lib/lean/history-downgrade.js",
13
14
  "./lean/tool-concurrency": "./lib/lean/tool-concurrency.js",
14
15
  "./lean/usage-ledger": "./lib/lean/usage-ledger.js",
15
16
  "./token-ledger": "./lib/token-ledger/index.js",
@@ -239,6 +239,13 @@
239
239
  name: 'dsh-lean-router/lean/usage-ledger'
240
240
  config:
241
241
  enabled: true
242
+ # 旧工具结果降级:agent/pre-step(waterfall,历史定稿前)把未降级 tool/result 攒到 >32 条时
243
+ # 批量换成一行占位符,最近 6 条永远保留原样;DSH_LEAN_ROUTER_DOWNGRADE=0 可关。
244
+ # 失败安全:钩子体全包 try/catch,异常只 warn 一次、绝不阻断 step;实现 = lib/lean/history-downgrade.js。
245
+ - id: lean-history-downgrade
246
+ name: 'dsh-lean-router/lean/history-downgrade'
247
+ config:
248
+ enabled: true
242
249
 
243
250
  # ============ 新增行:preset-lean-router-balance(balance 档 3 条;上游双预设形态,flash-lean-ptc-v3-balance 同构)============
244
251
 
@@ -420,6 +427,11 @@
420
427
  name: 'dsh-lean-router/lean/usage-ledger'
421
428
  config:
422
429
  enabled: true
430
+ # 旧工具结果降级(balance 档同挂):见 lean 档同名行说明。
431
+ - id: lean-history-downgrade
432
+ name: 'dsh-lean-router/lean/history-downgrade'
433
+ config:
434
+ enabled: true
423
435
 
424
436
  # ============ 新增行:交付门(加料件)============
425
437
  # 默认关闭(enabled: false):它会执行工作区里的验收脚本,要用户显式打开
@@ -233,6 +233,13 @@
233
233
  name: 'dsh-lean-router/lean/usage-ledger'
234
234
  config:
235
235
  enabled: true
236
+ # 旧工具结果降级:agent/pre-step(waterfall,历史定稿前)把未降级 tool/result 攒到 >32 条时
237
+ # 批量换成一行占位符,最近 6 条永远保留原样;DSH_LEAN_ROUTER_DOWNGRADE=0 可关。
238
+ # 失败安全:钩子体全包 try/catch,异常只 warn 一次、绝不阻断 step;实现 = lib/lean/history-downgrade.js。
239
+ - id: lean-history-downgrade
240
+ name: 'dsh-lean-router/lean/history-downgrade'
241
+ config:
242
+ enabled: true
236
243
 
237
244
  # ============ 新增行:preset-lean-router-balance(balance 档 3 条;上游双预设形态,flash-lean-ptc-v3-balance 同构)============
238
245