dsh-lean-router 2.0.0 → 2.1.0
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/docs/adr/0001-token-ledger-durable-usage.md +11 -0
- package/docs/changelog.en.md +18 -1
- package/docs/changelog.md +18 -1
- package/lib/bands.js +4 -2
- package/lib/token-ledger/index.js +147 -0
- package/lib/token-ledger/live.js +184 -0
- package/package.json +4 -2
- package/test/router-bands.test.mjs +26 -0
- package/test/token-ledger-live.test.mjs +351 -0
- package/test/token-ledger.test.mjs +264 -0
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
---
|
|
2
|
+
status: accepted
|
|
3
|
+
---
|
|
4
|
+
|
|
5
|
+
# Token 账本以 durable session/event 为真相源
|
|
6
|
+
|
|
7
|
+
cost-meter 的 `ledger.json` 是按天、会话和模型聚合的快照,没有逐 request 记录;lean-router 又需要把真实 Usage 与 RequestSnapshot、任务结果关联起来做回放。因此第一版不修改宿主:以 `session/event` 的 durable `assistant/message` 作为 Usage 主账本,`llm/stream` 只提供实时辅助,costMeter Remote 用于对账;Usage 保留宿主原始字段并显式计算 `prompt = input + cacheRead + cacheWrite`。
|
|
8
|
+
|
|
9
|
+
第一版只做 durable Usage 回放,不重跑模型。RequestSnapshot 用于归因,不产出 token 真值;live shadow A/B 被推迟到账本可信之后。这样能先验证字段、去重、对账和任务结果关联,但暂不能证明新压缩策略的 token 节省。
|
|
10
|
+
|
|
11
|
+
当前实现增量先落地为独立库与 fixture adapter,用来验证 Usage 归一化、快照隐私边界、显式断言与报表契约;实时 `session/event`/`llm/stream`/costMeter adapter 与真机 E2E 不属于本增量,待库契约稳定后接入。
|
package/docs/changelog.en.md
CHANGED
|
@@ -1,6 +1,23 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
-
> English version of [changelog.md](./changelog.md). Versions follow package.json (currently 2.
|
|
3
|
+
> English version of [changelog.md](./changelog.md). Versions follow package.json (currently 2.1.0).
|
|
4
|
+
|
|
5
|
+
## 2.1.0 (2026-11-29)
|
|
6
|
+
|
|
7
|
+
### Added
|
|
8
|
+
|
|
9
|
+
- **Standalone token ledger** under `lib/token-ledger/`: `createMemoryUsageAdapter` (dedupe and sort by session/turn/step/seq, range reads and subscriptions), `captureRequestSnapshot` (metadata and hashes only; raw prompts and tool output are rejected) and `createTokenReport` (real Usage kept apart from attribution, explicit assertions produce `pass`/`successRate`/`reasons`).
|
|
10
|
+
- **Live Usage adapter** in `lib/token-ledger/live.js`: subscribes to the host's `session/event` and keeps only `assistant/message` events that carry `usage`; `hydrate` backfills through the half-open `snapshotEvents` range; missing services, logger failures and subscription errors all degrade to skip, and `dispose` is idempotent.
|
|
11
|
+
- **Package exports** `./token-ledger` and `./token-ledger/live`.
|
|
12
|
+
|
|
13
|
+
### Changed
|
|
14
|
+
|
|
15
|
+
- **Band-specific reasoning opener**: the spec `guideText` now asks reasoning and the first reply to start with "We need …" and name the gap before acting; react asks to start with "I'm doing …" and name the action; weak adds no forced opener. `personaText`, `ROUTER_PROMPT` and the preset shards are untouched.
|
|
16
|
+
|
|
17
|
+
### Notes
|
|
18
|
+
|
|
19
|
+
- The ledger only replays durable Usage and never re-runs a model; the live adapter is not mounted in the preset yet, so nothing is captured at runtime.
|
|
20
|
+
- Host 0.2.2-rc.5 has no costMeter service, so per-request Usage must come from `session/event`, never from cost-meter aggregates.
|
|
4
21
|
|
|
5
22
|
## 2.0.0 (2026-11-29)
|
|
6
23
|
|
package/docs/changelog.md
CHANGED
|
@@ -1,6 +1,23 @@
|
|
|
1
1
|
# 变更记录(changelog)
|
|
2
2
|
|
|
3
|
-
> 中文为主,英文版:[changelog.en.md](./changelog.en.md)。版本号遵循 package.json(当前 2.
|
|
3
|
+
> 中文为主,英文版:[changelog.en.md](./changelog.en.md)。版本号遵循 package.json(当前 2.1.0)。
|
|
4
|
+
|
|
5
|
+
## 2.1.0 (2026-11-29)
|
|
6
|
+
|
|
7
|
+
### 新增
|
|
8
|
+
|
|
9
|
+
- **独立 token 账本库** `lib/token-ledger/`:`createMemoryUsageAdapter`(按 session/turn/step/seq 去重排序、范围读取与订阅)、`captureRequestSnapshot`(只保留元数据与哈希,拒绝原始 prompt 与工具输出)、`createTokenReport`(真实 Usage 与归因分离,显式断言产出 `pass`/`successRate`/`reasons`)。
|
|
10
|
+
- **live Usage adapter** `lib/token-ledger/live.js`:订阅宿主 `session/event`,只收带 `usage` 的 `assistant/message`;`hydrate` 用 `snapshotEvents` 半开区间补录;服务缺失、logger 异常与订阅失败均降级跳过,`dispose` 幂等。
|
|
11
|
+
- **包导出** `./token-ledger` 与 `./token-ledger/live`。
|
|
12
|
+
|
|
13
|
+
### 变更
|
|
14
|
+
|
|
15
|
+
- **思考句式按 band 分流**:spec 带 `guideText` 末尾要求推理与回复第一句以 "We need …" 开头并先陈述缺口;react 带要求以 "I'm doing …" 开头并直接说明动作;weak 不加强制句式。`personaText`、`ROUTER_PROMPT` 与分片未改动。
|
|
16
|
+
|
|
17
|
+
### 说明
|
|
18
|
+
|
|
19
|
+
- 账本当前只做 durable Usage 回放,不重跑模型;live adapter 尚未挂载到预设,运行时不会自动采集。
|
|
20
|
+
- 本机宿主 0.2.2-rc.5 无 costMeter 服务,历史记录不得以 cost-meter 聚合数据充当逐请求 Usage。
|
|
4
21
|
|
|
5
22
|
## 2.0.0 (2026-11-29)
|
|
6
23
|
|
package/lib/bands.js
CHANGED
|
@@ -35,7 +35,8 @@ export const BANDS = {
|
|
|
35
35
|
GUIDE_TAIL,
|
|
36
36
|
guideText:
|
|
37
37
|
"Near-field guide (inspect-and-plan): you are working a fix/inspection task. Read and locate before changing; state the plan when your information is complete, then apply the smallest safe change and verify it. " +
|
|
38
|
-
GUIDE_TAIL
|
|
38
|
+
GUIDE_TAIL +
|
|
39
|
+
' Start reasoning and your first reply with "We need …", naming the gap before acting.',
|
|
39
40
|
},
|
|
40
41
|
react: {
|
|
41
42
|
id: "react",
|
|
@@ -46,7 +47,8 @@ export const BANDS = {
|
|
|
46
47
|
GUIDE_TAIL,
|
|
47
48
|
guideText:
|
|
48
49
|
"Near-field guide (hands-on production): you are working a build task. Produce the next working increment now; verify by running it before claiming progress. " +
|
|
49
|
-
GUIDE_TAIL
|
|
50
|
+
GUIDE_TAIL +
|
|
51
|
+
' Start reasoning and your first reply with "I\'m doing …", naming the action you take.',
|
|
50
52
|
},
|
|
51
53
|
weak: {
|
|
52
54
|
id: "weak",
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
function definedFields(source, keys) {
|
|
2
|
+
const result = {};
|
|
3
|
+
for (const key of keys) {
|
|
4
|
+
if (source[key] !== undefined) result[key] = source[key];
|
|
5
|
+
}
|
|
6
|
+
return result;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export function captureRequestSnapshot(input) {
|
|
10
|
+
for (const field of ['prompt', 'body', 'toolOutput']) {
|
|
11
|
+
if (Object.hasOwn(input, field)) {
|
|
12
|
+
throw new Error('RequestSnapshot: raw field "' + field + '" is not allowed');
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
const snapshot = definedFields(input, ['sessionId', 'turn', 'step', 'seq', 'headerHash']);
|
|
16
|
+
if (input.tools !== undefined) {
|
|
17
|
+
snapshot.tools = input.tools.map((tool) => definedFields(tool, ['name', 'schemaHash']));
|
|
18
|
+
}
|
|
19
|
+
if (input.partitionChars !== undefined) {
|
|
20
|
+
snapshot.partitionChars = { ...input.partitionChars };
|
|
21
|
+
}
|
|
22
|
+
if (input.taskResult !== undefined) {
|
|
23
|
+
snapshot.taskResult = definedFields(input.taskResult, ['terminal', 'artifacts', 'errors']);
|
|
24
|
+
}
|
|
25
|
+
return snapshot;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function compareUsageRecords(left, right) {
|
|
29
|
+
return left.turn - right.turn
|
|
30
|
+
|| left.step - right.step
|
|
31
|
+
|| left.seq - right.seq;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
const USAGE_FIELDS = ['inputTokens', 'outputTokens', 'cacheReadTokens', 'cacheWriteTokens', 'reasoningTokens'];
|
|
35
|
+
|
|
36
|
+
function normalizeUsage(usage) {
|
|
37
|
+
const normalized = {};
|
|
38
|
+
for (const field of USAGE_FIELDS) normalized[field] = usage[field] ?? 0;
|
|
39
|
+
normalized.prompt = normalized.inputTokens + normalized.cacheReadTokens + normalized.cacheWriteTokens;
|
|
40
|
+
return normalized;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function snapshotKey(snapshot) {
|
|
44
|
+
return JSON.stringify([snapshot.sessionId, snapshot.turn, snapshot.step, snapshot.seq]);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export function createTokenReport({
|
|
48
|
+
records = [],
|
|
49
|
+
snapshots = [],
|
|
50
|
+
taskResult = {},
|
|
51
|
+
assertions = {},
|
|
52
|
+
} = {}) {
|
|
53
|
+
const attributionByKey = new Map(snapshots.map((snapshot) => [snapshotKey(snapshot), snapshot]));
|
|
54
|
+
const entries = [...records].sort(compareUsageRecords).map((record) => ({
|
|
55
|
+
...definedFields(record, ['sessionId', 'turn', 'step', 'seq', 'provider', 'model', 'atMs']),
|
|
56
|
+
usage: normalizeUsage(record.usage),
|
|
57
|
+
snapshot: attributionByKey.get(snapshotKey(record)) ?? null,
|
|
58
|
+
}));
|
|
59
|
+
const usage = normalizeUsage({});
|
|
60
|
+
for (const entry of entries) {
|
|
61
|
+
for (const field of USAGE_FIELDS) usage[field] += entry.usage[field];
|
|
62
|
+
}
|
|
63
|
+
usage.prompt = usage.inputTokens + usage.cacheReadTokens + usage.cacheWriteTokens;
|
|
64
|
+
|
|
65
|
+
const toolNames = new Set((taskResult.toolCalls ?? []).map((call) => typeof call === 'string' ? call : call.name));
|
|
66
|
+
const artifacts = new Set(taskResult.artifacts ?? []);
|
|
67
|
+
const errors = new Set(taskResult.errors ?? []);
|
|
68
|
+
const reasons = [];
|
|
69
|
+
if (assertions.expectedTerminal !== undefined && taskResult.terminal !== assertions.expectedTerminal) {
|
|
70
|
+
reasons.push('expected terminal "' + assertions.expectedTerminal + '", got "' + taskResult.terminal + '"');
|
|
71
|
+
}
|
|
72
|
+
for (const tool of assertions.requiredTools ?? []) {
|
|
73
|
+
if (!toolNames.has(tool)) reasons.push('missing required tool "' + tool + '"');
|
|
74
|
+
}
|
|
75
|
+
for (const artifact of assertions.requiredArtifacts ?? []) {
|
|
76
|
+
if (!artifacts.has(artifact)) reasons.push('missing required artifact "' + artifact + '"');
|
|
77
|
+
}
|
|
78
|
+
for (const error of assertions.forbiddenErrors ?? []) {
|
|
79
|
+
if (errors.has(error)) reasons.push('forbidden error "' + error + '"');
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
const pass = reasons.length === 0;
|
|
83
|
+
return {
|
|
84
|
+
entries,
|
|
85
|
+
requestSnapshots: snapshots,
|
|
86
|
+
usage,
|
|
87
|
+
taskResult,
|
|
88
|
+
assertions,
|
|
89
|
+
pass,
|
|
90
|
+
successRate: pass ? 1 : 0,
|
|
91
|
+
reasons,
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function usageKey(record) {
|
|
96
|
+
return JSON.stringify([record.sessionId, record.turn, record.step, record.seq]);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
export function createMemoryUsageAdapter(initialRecords = []) {
|
|
100
|
+
const records = new Map();
|
|
101
|
+
const watchers = new Set();
|
|
102
|
+
for (const record of initialRecords) {
|
|
103
|
+
const key = usageKey(record);
|
|
104
|
+
if (!records.has(key)) records.set(key, record);
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function selectRecords(candidates, sessionId, afterSeq, toSeq) {
|
|
108
|
+
return [...candidates]
|
|
109
|
+
.filter((record) => record.sessionId === sessionId
|
|
110
|
+
&& record.seq > afterSeq
|
|
111
|
+
&& (toSeq === undefined || record.seq <= toSeq))
|
|
112
|
+
.sort(compareUsageRecords);
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function read(sessionId, afterSeq = 0, toSeq) {
|
|
116
|
+
return selectRecords(records.values(), sessionId, afterSeq, toSeq);
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
return {
|
|
120
|
+
read,
|
|
121
|
+
|
|
122
|
+
append(...newRecords) {
|
|
123
|
+
const addedKeys = new Set();
|
|
124
|
+
for (const record of newRecords) {
|
|
125
|
+
const key = usageKey(record);
|
|
126
|
+
if (records.has(key)) continue;
|
|
127
|
+
records.set(key, record);
|
|
128
|
+
addedKeys.add(key);
|
|
129
|
+
}
|
|
130
|
+
for (const watcher of watchers) {
|
|
131
|
+
const pending = selectRecords(
|
|
132
|
+
[...addedKeys].map((key) => records.get(key)),
|
|
133
|
+
watcher.sessionId,
|
|
134
|
+
watcher.afterSeq,
|
|
135
|
+
);
|
|
136
|
+
for (const record of pending) watcher.callback(record);
|
|
137
|
+
}
|
|
138
|
+
},
|
|
139
|
+
|
|
140
|
+
watch(sessionId, afterSeq, callback) {
|
|
141
|
+
const watcher = { sessionId, afterSeq, callback };
|
|
142
|
+
watchers.add(watcher);
|
|
143
|
+
for (const record of read(sessionId, afterSeq)) callback(record);
|
|
144
|
+
return () => watchers.delete(watcher);
|
|
145
|
+
},
|
|
146
|
+
};
|
|
147
|
+
}
|
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
import { createMemoryUsageAdapter } from './index.js';
|
|
2
|
+
|
|
3
|
+
function usageKey(record) {
|
|
4
|
+
return JSON.stringify([record.sessionId, record.turn, record.step, record.seq]);
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
function describeError(error) {
|
|
8
|
+
if (error && typeof error.message === 'string') return error.message;
|
|
9
|
+
return String(error);
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Map one `session/event` payload onto a Usage Record, or explain why it is not
|
|
14
|
+
* part of the durable Usage ledger. Only `assistant/message` events that carry
|
|
15
|
+
* `data.usage` participate; every other event is skipped without inventing
|
|
16
|
+
* provider, model, or token values.
|
|
17
|
+
*/
|
|
18
|
+
function recordFromEvent(session, event) {
|
|
19
|
+
if (!event || typeof event !== 'object') {
|
|
20
|
+
return { skip: true, reason: 'event is not an object' };
|
|
21
|
+
}
|
|
22
|
+
if (event.type !== 'assistant/message') return { skip: true };
|
|
23
|
+
if (!Number.isFinite(event.seq)) {
|
|
24
|
+
return { skip: true, reason: 'assistant/message has no numeric seq' };
|
|
25
|
+
}
|
|
26
|
+
if (!Number.isFinite(event.time)) {
|
|
27
|
+
return { skip: true, reason: 'assistant/message has no numeric time' };
|
|
28
|
+
}
|
|
29
|
+
const data = event.data;
|
|
30
|
+
if (!data || typeof data !== 'object') {
|
|
31
|
+
return { skip: true, reason: 'assistant/message has no data' };
|
|
32
|
+
}
|
|
33
|
+
const usage = data.usage;
|
|
34
|
+
if (!usage || typeof usage !== 'object' || Array.isArray(usage)) return { skip: true };
|
|
35
|
+
if (!Number.isFinite(data.turn) || !Number.isFinite(data.step)) {
|
|
36
|
+
return { skip: true, reason: 'assistant/message has no numeric turn/step' };
|
|
37
|
+
}
|
|
38
|
+
const sessionId = session && session.id;
|
|
39
|
+
if (typeof sessionId !== 'string' || sessionId.length === 0) {
|
|
40
|
+
return { skip: true, reason: 'event has no session id' };
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
const record = {
|
|
44
|
+
sessionId,
|
|
45
|
+
turn: data.turn,
|
|
46
|
+
step: data.step,
|
|
47
|
+
seq: event.seq,
|
|
48
|
+
atMs: event.time,
|
|
49
|
+
usage,
|
|
50
|
+
};
|
|
51
|
+
const source = data.message && typeof data.message === 'object' ? data.message.source : undefined;
|
|
52
|
+
if (source && typeof source === 'object') {
|
|
53
|
+
if (typeof source.provider === 'string') record.provider = source.provider;
|
|
54
|
+
if (typeof source.model === 'string') record.model = source.model;
|
|
55
|
+
}
|
|
56
|
+
return { skip: false, record };
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Live Usage adapter over the durable `session/event` feed.
|
|
61
|
+
*
|
|
62
|
+
* Subscribes once to the context's `session/event` emit hook and appends the
|
|
63
|
+
* Usage Record of every `assistant/message` event that carries `usage`.
|
|
64
|
+
* `read`/`watch` keep the semantics of {@link createMemoryUsageAdapter}, and
|
|
65
|
+
* `hydrate` backfills events the subscription missed through
|
|
66
|
+
* `session.snapshotEvents`. Every failure path degrades to "skip and warn":
|
|
67
|
+
* usage capture must never break the host's append publication.
|
|
68
|
+
*
|
|
69
|
+
* @param ctx - plugin context; only `on` and `logger` are used.
|
|
70
|
+
* @param options - optional logger override (`options.logger ?? ctx.logger`).
|
|
71
|
+
* @returns `{ read, watch, hydrate, dispose }`.
|
|
72
|
+
*/
|
|
73
|
+
export function createLiveUsageAdapter(ctx = {}, options = {}) {
|
|
74
|
+
const context = ctx && typeof ctx === 'object' ? ctx : {};
|
|
75
|
+
const settings = options && typeof options === 'object' ? options : {};
|
|
76
|
+
const logger = settings.logger ?? context.logger;
|
|
77
|
+
const adapter = createMemoryUsageAdapter();
|
|
78
|
+
const committed = new Set();
|
|
79
|
+
let disposed = false;
|
|
80
|
+
let unsubscribe = null;
|
|
81
|
+
|
|
82
|
+
function warn(message) {
|
|
83
|
+
if (!logger || typeof logger.warn !== 'function') return;
|
|
84
|
+
try {
|
|
85
|
+
logger.warn('[token-ledger] ' + message);
|
|
86
|
+
} catch {
|
|
87
|
+
// A logger must never break usage capture.
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function commit(record) {
|
|
92
|
+
const key = usageKey(record);
|
|
93
|
+
if (committed.has(key)) return false;
|
|
94
|
+
try {
|
|
95
|
+
adapter.append(record);
|
|
96
|
+
} catch (error) {
|
|
97
|
+
warn('usage watcher failed: ' + describeError(error));
|
|
98
|
+
}
|
|
99
|
+
committed.add(key);
|
|
100
|
+
return true;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function handleEvent(session, event) {
|
|
104
|
+
if (disposed) return;
|
|
105
|
+
const mapped = recordFromEvent(session, event);
|
|
106
|
+
if (mapped.skip) {
|
|
107
|
+
if (mapped.reason) warn('skipped session/event: ' + mapped.reason);
|
|
108
|
+
return;
|
|
109
|
+
}
|
|
110
|
+
commit(mapped.record);
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
if (typeof context.on === 'function') {
|
|
114
|
+
try {
|
|
115
|
+
const disposer = context.on('session/event', handleEvent);
|
|
116
|
+
if (typeof disposer === 'function') unsubscribe = disposer;
|
|
117
|
+
} catch (error) {
|
|
118
|
+
warn('could not subscribe to session/event: ' + describeError(error));
|
|
119
|
+
}
|
|
120
|
+
} else {
|
|
121
|
+
warn('ctx.on is unavailable; live usage capture disabled');
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* Backfill Usage Records from a session's event log.
|
|
126
|
+
*
|
|
127
|
+
* @param session - the session whose log is read; skipped when it cannot
|
|
128
|
+
* enumerate events.
|
|
129
|
+
* @param afterSeq - last sequence number already known; only later events are
|
|
130
|
+
* read. Omitted or non-numeric means "from the start of the log".
|
|
131
|
+
* @returns the number of newly recorded Usage Records.
|
|
132
|
+
*/
|
|
133
|
+
function hydrate(session, afterSeq) {
|
|
134
|
+
if (disposed) return 0;
|
|
135
|
+
if (!session || typeof session.snapshotEvents !== 'function') {
|
|
136
|
+
warn('hydrate skipped: session.snapshotEvents is unavailable');
|
|
137
|
+
return 0;
|
|
138
|
+
}
|
|
139
|
+
const from = typeof afterSeq === 'number' && Number.isFinite(afterSeq) && afterSeq >= 0
|
|
140
|
+
? afterSeq + 1
|
|
141
|
+
: undefined;
|
|
142
|
+
let events;
|
|
143
|
+
try {
|
|
144
|
+
events = from === undefined ? session.snapshotEvents() : session.snapshotEvents(from);
|
|
145
|
+
} catch (error) {
|
|
146
|
+
warn('hydrate failed: ' + describeError(error));
|
|
147
|
+
return 0;
|
|
148
|
+
}
|
|
149
|
+
if (!Array.isArray(events)) {
|
|
150
|
+
warn('hydrate skipped: snapshotEvents returned no event list');
|
|
151
|
+
return 0;
|
|
152
|
+
}
|
|
153
|
+
let added = 0;
|
|
154
|
+
for (const event of events) {
|
|
155
|
+
const mapped = recordFromEvent(session, event);
|
|
156
|
+
if (mapped.skip) {
|
|
157
|
+
if (mapped.reason) warn('hydrate skipped session/event: ' + mapped.reason);
|
|
158
|
+
continue;
|
|
159
|
+
}
|
|
160
|
+
if (commit(mapped.record)) added += 1;
|
|
161
|
+
}
|
|
162
|
+
return added;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
function dispose() {
|
|
166
|
+
if (disposed) return;
|
|
167
|
+
disposed = true;
|
|
168
|
+
const stop = unsubscribe;
|
|
169
|
+
unsubscribe = null;
|
|
170
|
+
if (typeof stop !== 'function') return;
|
|
171
|
+
try {
|
|
172
|
+
stop();
|
|
173
|
+
} catch (error) {
|
|
174
|
+
warn('dispose failed: ' + describeError(error));
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
return {
|
|
179
|
+
read: adapter.read,
|
|
180
|
+
watch: adapter.watch,
|
|
181
|
+
hydrate,
|
|
182
|
+
dispose,
|
|
183
|
+
};
|
|
184
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-lean-router",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.1.0",
|
|
4
4
|
"description": "lean 省 token × 思考链路由 × code_run 工具遮蔽的 DSH cordis 插件(单 bundle:预设)",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "lib/index.js",
|
|
@@ -10,7 +10,9 @@
|
|
|
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/tool-concurrency": "./lib/lean/tool-concurrency.js"
|
|
13
|
+
"./lean/tool-concurrency": "./lib/lean/tool-concurrency.js",
|
|
14
|
+
"./token-ledger": "./lib/token-ledger/index.js",
|
|
15
|
+
"./token-ledger/live": "./lib/token-ledger/live.js"
|
|
14
16
|
},
|
|
15
17
|
"files": [
|
|
16
18
|
"lib",
|
|
@@ -33,6 +33,32 @@ test("BANDS 三带形状:id/label/personaText/guideText 齐备且工具面宽
|
|
|
33
33
|
assert.equal(BANDS.weak.toolsWide, false);
|
|
34
34
|
});
|
|
35
35
|
|
|
36
|
+
test("思考句式:spec/react 引导带固定开头句式,weak 不强制,persona 保持原样", () => {
|
|
37
|
+
// spec:先陈述缺口(We need …)再行动。
|
|
38
|
+
assert.ok(BANDS.spec.guideText.includes("We need"), "spec 引导含 We need 句式");
|
|
39
|
+
assert.ok(BANDS.spec.guideText.includes("reasoning"), "spec 引导覆盖内部推理");
|
|
40
|
+
assert.ok(BANDS.spec.guideText.includes("first reply"), "spec 引导覆盖回复第一句");
|
|
41
|
+
assert.ok(!BANDS.spec.guideText.includes("I'm doing"), "spec 不混入 react 句式");
|
|
42
|
+
// react:直接说明正在做的动作(I'm doing …)。
|
|
43
|
+
assert.ok(BANDS.react.guideText.includes("I'm doing"), "react 引导含 I'm doing 句式");
|
|
44
|
+
assert.ok(BANDS.react.guideText.includes("reasoning"), "react 引导覆盖内部推理");
|
|
45
|
+
assert.ok(BANDS.react.guideText.includes("first reply"), "react 引导覆盖回复第一句");
|
|
46
|
+
assert.ok(!BANDS.react.guideText.includes("We need"), "react 不混入 spec 句式");
|
|
47
|
+
// weak:交给模型自判,不加任何强制句式。
|
|
48
|
+
assert.ok(!BANDS.weak.guideText.includes("We need"), "weak 不强制 spec 句式");
|
|
49
|
+
assert.ok(!BANDS.weak.guideText.includes("I'm doing"), "weak 不强制 react 句式");
|
|
50
|
+
// 固定前缀与固定基调不变(GUIDE_TAIL 仍保留)。
|
|
51
|
+
for (const id of BAND_IDS) {
|
|
52
|
+
assert.ok(BANDS[id].guideText.startsWith("Near-field guide"), id + " 引导固定前缀");
|
|
53
|
+
assert.ok(BANDS[id].guideText.includes("Recall what you have already done"), id + " 保留 GUIDE_TAIL");
|
|
54
|
+
}
|
|
55
|
+
// personaText 当前无运行时消费者:保持原样,不新增句式。
|
|
56
|
+
for (const id of BAND_IDS) {
|
|
57
|
+
assert.ok(!BANDS[id].personaText.includes("We need"), id + " persona 不含新句式");
|
|
58
|
+
assert.ok(!BANDS[id].personaText.includes("I'm doing"), id + " persona 不含新句式");
|
|
59
|
+
}
|
|
60
|
+
});
|
|
61
|
+
|
|
36
62
|
test("classifyTask:build -> react,fix -> spec,平票/无匹配/空 -> weak", () => {
|
|
37
63
|
assert.equal(classifyTask("帮我开发一个新的贪吃蛇网页游戏"), "react");
|
|
38
64
|
assert.equal(classifyTask("Create a new CLI tool from scratch"), "react");
|
|
@@ -0,0 +1,351 @@
|
|
|
1
|
+
import test from 'node:test';
|
|
2
|
+
import assert from 'node:assert/strict';
|
|
3
|
+
|
|
4
|
+
import { createLiveUsageAdapter } from 'dsh-lean-router/token-ledger/live';
|
|
5
|
+
|
|
6
|
+
const BASE_USAGE = {
|
|
7
|
+
inputTokens: 10,
|
|
8
|
+
outputTokens: 3,
|
|
9
|
+
cacheReadTokens: 2,
|
|
10
|
+
cacheWriteTokens: 1,
|
|
11
|
+
reasoningTokens: 1,
|
|
12
|
+
};
|
|
13
|
+
|
|
14
|
+
function usage(overrides = {}) {
|
|
15
|
+
return { ...BASE_USAGE, ...overrides };
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function createLogger() {
|
|
19
|
+
const warnings = [];
|
|
20
|
+
return {
|
|
21
|
+
warnings,
|
|
22
|
+
warn(message) {
|
|
23
|
+
warnings.push(message);
|
|
24
|
+
},
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function createFakeCtx({ on = true, logger } = {}) {
|
|
29
|
+
const listeners = new Map();
|
|
30
|
+
const disposals = [];
|
|
31
|
+
const ctx = {
|
|
32
|
+
get: () => ({ create: () => undefined }),
|
|
33
|
+
logger,
|
|
34
|
+
disposals,
|
|
35
|
+
};
|
|
36
|
+
if (on) {
|
|
37
|
+
ctx.on = (name, listener) => {
|
|
38
|
+
const set = listeners.get(name) ?? new Set();
|
|
39
|
+
set.add(listener);
|
|
40
|
+
listeners.set(name, set);
|
|
41
|
+
return () => {
|
|
42
|
+
disposals.push(name);
|
|
43
|
+
set.delete(listener);
|
|
44
|
+
};
|
|
45
|
+
};
|
|
46
|
+
ctx.emit = (name, ...args) => {
|
|
47
|
+
for (const listener of [...(listeners.get(name) ?? [])]) listener(...args);
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
ctx.listenerCount = (name) => (listeners.get(name) ?? new Set()).size;
|
|
51
|
+
return ctx;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function createSession(events = []) {
|
|
55
|
+
const calls = [];
|
|
56
|
+
return {
|
|
57
|
+
id: 'session-a',
|
|
58
|
+
calls,
|
|
59
|
+
snapshotEvents(fromSeq, toSeqExclusive) {
|
|
60
|
+
calls.push([...arguments]);
|
|
61
|
+
const list = typeof events === 'function' ? events() : events;
|
|
62
|
+
return list
|
|
63
|
+
.filter((event) => fromSeq === undefined || event.seq >= fromSeq)
|
|
64
|
+
.filter((event) => toSeqExclusive === undefined || event.seq < toSeqExclusive);
|
|
65
|
+
},
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function assistantEvent({
|
|
70
|
+
seq,
|
|
71
|
+
turn = 1,
|
|
72
|
+
step = 2,
|
|
73
|
+
time = 1_700_000_000_000 + seq,
|
|
74
|
+
usage: eventUsage = usage(),
|
|
75
|
+
source = { kind: 'model', provider: 'fixture', model: 'fixture-model' },
|
|
76
|
+
message = { role: 'assistant', source },
|
|
77
|
+
data,
|
|
78
|
+
type = 'assistant/message',
|
|
79
|
+
} = {}) {
|
|
80
|
+
return {
|
|
81
|
+
type,
|
|
82
|
+
seq,
|
|
83
|
+
time,
|
|
84
|
+
data: data ?? { turn, step, message, stream: [], usage: eventUsage },
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
test('live adapter maps assistant/message usage into a Usage Record', () => {
|
|
89
|
+
const logger = createLogger();
|
|
90
|
+
const ctx = createFakeCtx({ logger });
|
|
91
|
+
const adapter = createLiveUsageAdapter(ctx, { logger });
|
|
92
|
+
const session = createSession();
|
|
93
|
+
|
|
94
|
+
ctx.emit('session/event', session, assistantEvent({ seq: 7, turn: 2, step: 3 }));
|
|
95
|
+
|
|
96
|
+
assert.equal(ctx.listenerCount('session/event'), 1);
|
|
97
|
+
assert.deepEqual(adapter.read('session-a', 0), [{
|
|
98
|
+
sessionId: 'session-a',
|
|
99
|
+
turn: 2,
|
|
100
|
+
step: 3,
|
|
101
|
+
seq: 7,
|
|
102
|
+
provider: 'fixture',
|
|
103
|
+
model: 'fixture-model',
|
|
104
|
+
atMs: 1_700_000_000_007,
|
|
105
|
+
usage: usage(),
|
|
106
|
+
}]);
|
|
107
|
+
assert.deepEqual(logger.warnings, []);
|
|
108
|
+
});
|
|
109
|
+
|
|
110
|
+
test('live adapter ignores unrelated events and messages without usage', () => {
|
|
111
|
+
const logger = createLogger();
|
|
112
|
+
const ctx = createFakeCtx({ logger });
|
|
113
|
+
const adapter = createLiveUsageAdapter(ctx, { logger });
|
|
114
|
+
const session = createSession();
|
|
115
|
+
|
|
116
|
+
ctx.emit('session/event', session, assistantEvent({ seq: 1, type: 'tool/result' }));
|
|
117
|
+
ctx.emit('session/event', session, assistantEvent({ seq: 2, type: 'assistant/attempt' }));
|
|
118
|
+
ctx.emit('session/event', session, {
|
|
119
|
+
type: 'assistant/message',
|
|
120
|
+
seq: 3,
|
|
121
|
+
time: 1_700_000_000_003,
|
|
122
|
+
data: { turn: 1, step: 2, message: { role: 'assistant' }, stream: [] },
|
|
123
|
+
});
|
|
124
|
+
ctx.emit('session/event', session, {
|
|
125
|
+
type: 'assistant/message',
|
|
126
|
+
seq: 4,
|
|
127
|
+
time: 1_700_000_000_004,
|
|
128
|
+
data: { turn: 1, step: 2, message: { role: 'assistant' }, stream: [], usage: null },
|
|
129
|
+
});
|
|
130
|
+
|
|
131
|
+
assert.deepEqual(adapter.read('session-a', 0), []);
|
|
132
|
+
assert.deepEqual(logger.warnings, []);
|
|
133
|
+
});
|
|
134
|
+
|
|
135
|
+
test('live adapter keeps provider and model undefined when the source does not carry them', () => {
|
|
136
|
+
const logger = createLogger();
|
|
137
|
+
const ctx = createFakeCtx({ logger });
|
|
138
|
+
const adapter = createLiveUsageAdapter(ctx, { logger });
|
|
139
|
+
const session = createSession();
|
|
140
|
+
|
|
141
|
+
ctx.emit('session/event', session, assistantEvent({ seq: 1, message: { role: 'assistant' } }));
|
|
142
|
+
ctx.emit('session/event', session, assistantEvent({
|
|
143
|
+
seq: 2,
|
|
144
|
+
message: { role: 'assistant', source: { kind: 'tool', callId: 'call-1' } },
|
|
145
|
+
}));
|
|
146
|
+
|
|
147
|
+
const records = adapter.read('session-a', 0);
|
|
148
|
+
assert.equal(records.length, 2);
|
|
149
|
+
for (const record of records) {
|
|
150
|
+
assert.equal(Object.hasOwn(record, 'provider'), false);
|
|
151
|
+
assert.equal(Object.hasOwn(record, 'model'), false);
|
|
152
|
+
}
|
|
153
|
+
assert.deepEqual(logger.warnings, []);
|
|
154
|
+
});
|
|
155
|
+
|
|
156
|
+
test('live adapter skips malformed event shapes with a warning and never throws', () => {
|
|
157
|
+
const logger = createLogger();
|
|
158
|
+
const ctx = createFakeCtx({ logger });
|
|
159
|
+
const adapter = createLiveUsageAdapter(ctx, { logger });
|
|
160
|
+
const session = createSession();
|
|
161
|
+
|
|
162
|
+
assert.doesNotThrow(() => {
|
|
163
|
+
ctx.emit('session/event', session, null);
|
|
164
|
+
ctx.emit('session/event', session, 'not-an-event');
|
|
165
|
+
ctx.emit('session/event', session, {
|
|
166
|
+
type: 'assistant/message',
|
|
167
|
+
seq: 1,
|
|
168
|
+
time: 1_700_000_000_001,
|
|
169
|
+
data: { turn: 'one', step: 2, message: { role: 'assistant' }, stream: [], usage: usage() },
|
|
170
|
+
});
|
|
171
|
+
ctx.emit('session/event', session, {
|
|
172
|
+
type: 'assistant/message',
|
|
173
|
+
time: 1_700_000_000_002,
|
|
174
|
+
data: { turn: 1, step: 2, message: { role: 'assistant' }, stream: [], usage: usage() },
|
|
175
|
+
});
|
|
176
|
+
});
|
|
177
|
+
|
|
178
|
+
assert.deepEqual(adapter.read('session-a', 0), []);
|
|
179
|
+
assert.equal(logger.warnings.length, 4);
|
|
180
|
+
for (const message of logger.warnings) assert.match(message, /session\/event/);
|
|
181
|
+
});
|
|
182
|
+
|
|
183
|
+
test('live adapter requires a session id and skips events without one', () => {
|
|
184
|
+
const logger = createLogger();
|
|
185
|
+
const ctx = createFakeCtx({ logger });
|
|
186
|
+
const adapter = createLiveUsageAdapter(ctx, { logger });
|
|
187
|
+
|
|
188
|
+
ctx.emit('session/event', undefined, assistantEvent({ seq: 1 }));
|
|
189
|
+
ctx.emit('session/event', {}, assistantEvent({ seq: 2 }));
|
|
190
|
+
|
|
191
|
+
assert.deepEqual(adapter.read('session-a', 0), []);
|
|
192
|
+
assert.equal(logger.warnings.length, 2);
|
|
193
|
+
});
|
|
194
|
+
|
|
195
|
+
test('live adapter deduplicates a re-delivered event and keeps the first usage', () => {
|
|
196
|
+
const logger = createLogger();
|
|
197
|
+
const ctx = createFakeCtx({ logger });
|
|
198
|
+
const adapter = createLiveUsageAdapter(ctx, { logger });
|
|
199
|
+
const session = createSession();
|
|
200
|
+
const seen = [];
|
|
201
|
+
adapter.watch('session-a', 0, (record) => seen.push(record.seq));
|
|
202
|
+
|
|
203
|
+
ctx.emit('session/event', session, assistantEvent({ seq: 5, usage: usage({ inputTokens: 10 }) }));
|
|
204
|
+
ctx.emit('session/event', session, assistantEvent({ seq: 5, usage: usage({ inputTokens: 999 }) }));
|
|
205
|
+
|
|
206
|
+
const records = adapter.read('session-a', 0);
|
|
207
|
+
assert.equal(records.length, 1);
|
|
208
|
+
assert.equal(records[0].usage.inputTokens, 10);
|
|
209
|
+
assert.deepEqual(seen, [5]);
|
|
210
|
+
});
|
|
211
|
+
|
|
212
|
+
test('live adapter watch replays sorted records and streams new ones', () => {
|
|
213
|
+
const logger = createLogger();
|
|
214
|
+
const ctx = createFakeCtx({ logger });
|
|
215
|
+
const adapter = createLiveUsageAdapter(ctx, { logger });
|
|
216
|
+
const session = createSession();
|
|
217
|
+
const seen = [];
|
|
218
|
+
|
|
219
|
+
ctx.emit('session/event', session, assistantEvent({ seq: 2 }));
|
|
220
|
+
ctx.emit('session/event', session, assistantEvent({ seq: 1 }));
|
|
221
|
+
const stop = adapter.watch('session-a', 0, (record) => seen.push(record.seq));
|
|
222
|
+
ctx.emit('session/event', session, assistantEvent({ seq: 3 }));
|
|
223
|
+
|
|
224
|
+
assert.deepEqual(seen, [1, 2, 3]);
|
|
225
|
+
assert.deepEqual(adapter.read('session-a', 2).map((record) => record.seq), [3]);
|
|
226
|
+
|
|
227
|
+
stop();
|
|
228
|
+
ctx.emit('session/event', session, assistantEvent({ seq: 4 }));
|
|
229
|
+
assert.deepEqual(seen, [1, 2, 3]);
|
|
230
|
+
assert.deepEqual(adapter.read('session-a', 3).map((record) => record.seq), [4]);
|
|
231
|
+
});
|
|
232
|
+
|
|
233
|
+
test('live adapter hydrate backfills events strictly after afterSeq', () => {
|
|
234
|
+
const logger = createLogger();
|
|
235
|
+
const ctx = createFakeCtx({ logger });
|
|
236
|
+
const adapter = createLiveUsageAdapter(ctx, { logger });
|
|
237
|
+
const events = [
|
|
238
|
+
assistantEvent({ seq: 3, type: 'tool/result' }),
|
|
239
|
+
assistantEvent({ seq: 4 }),
|
|
240
|
+
{
|
|
241
|
+
type: 'assistant/message',
|
|
242
|
+
seq: 5,
|
|
243
|
+
time: 1_700_000_000_005,
|
|
244
|
+
data: { turn: 1, step: 2, message: { role: 'assistant' }, stream: [] },
|
|
245
|
+
},
|
|
246
|
+
assistantEvent({ seq: 6 }),
|
|
247
|
+
];
|
|
248
|
+
const session = createSession(events);
|
|
249
|
+
|
|
250
|
+
assert.equal(adapter.hydrate(session, 4), 1);
|
|
251
|
+
assert.deepEqual(session.calls, [[5]]);
|
|
252
|
+
assert.deepEqual(adapter.read('session-a', 0).map((record) => record.seq), [6]);
|
|
253
|
+
|
|
254
|
+
assert.equal(adapter.hydrate(session), 1);
|
|
255
|
+
assert.deepEqual(session.calls[1], []);
|
|
256
|
+
assert.deepEqual(adapter.read('session-a', 0).map((record) => record.seq), [4, 6]);
|
|
257
|
+
assert.deepEqual(logger.warnings, []);
|
|
258
|
+
});
|
|
259
|
+
|
|
260
|
+
test('live adapter hydrate does not duplicate events already delivered live', () => {
|
|
261
|
+
const logger = createLogger();
|
|
262
|
+
const ctx = createFakeCtx({ logger });
|
|
263
|
+
const adapter = createLiveUsageAdapter(ctx, { logger });
|
|
264
|
+
const session = createSession();
|
|
265
|
+
const seen = [];
|
|
266
|
+
adapter.watch('session-a', 0, (record) => seen.push(record.seq));
|
|
267
|
+
|
|
268
|
+
ctx.emit('session/event', session, assistantEvent({ seq: 5 }));
|
|
269
|
+
const replay = createSession([assistantEvent({ seq: 5 }), assistantEvent({ seq: 6 })]);
|
|
270
|
+
|
|
271
|
+
assert.equal(adapter.hydrate(replay, 4), 1);
|
|
272
|
+
assert.deepEqual(seen, [5, 6]);
|
|
273
|
+
assert.deepEqual(adapter.read('session-a', 0).map((record) => record.seq), [5, 6]);
|
|
274
|
+
});
|
|
275
|
+
|
|
276
|
+
test('live adapter degrades when the context cannot subscribe', () => {
|
|
277
|
+
const logger = createLogger();
|
|
278
|
+
const ctx = createFakeCtx({ on: false, logger });
|
|
279
|
+
const adapter = createLiveUsageAdapter(ctx, { logger });
|
|
280
|
+
|
|
281
|
+
assert.equal(typeof adapter.read, 'function');
|
|
282
|
+
assert.equal(typeof adapter.watch, 'function');
|
|
283
|
+
assert.equal(typeof adapter.hydrate, 'function');
|
|
284
|
+
assert.equal(typeof adapter.dispose, 'function');
|
|
285
|
+
assert.deepEqual(adapter.read('session-a', 0), []);
|
|
286
|
+
assert.equal(logger.warnings.length, 1);
|
|
287
|
+
assert.match(logger.warnings[0], /ctx\.on/);
|
|
288
|
+
assert.doesNotThrow(() => adapter.dispose());
|
|
289
|
+
assert.doesNotThrow(() => adapter.dispose());
|
|
290
|
+
|
|
291
|
+
assert.doesNotThrow(() => {
|
|
292
|
+
const bare = createLiveUsageAdapter(null);
|
|
293
|
+
assert.deepEqual(bare.read('session-a', 0), []);
|
|
294
|
+
bare.dispose();
|
|
295
|
+
createLiveUsageAdapter(undefined, null).dispose();
|
|
296
|
+
});
|
|
297
|
+
});
|
|
298
|
+
|
|
299
|
+
test('live adapter falls back to ctx.logger when options.logger is absent', () => {
|
|
300
|
+
const ctxLogger = createLogger();
|
|
301
|
+
const ctx = createFakeCtx({ logger: ctxLogger });
|
|
302
|
+
createLiveUsageAdapter(ctx);
|
|
303
|
+
|
|
304
|
+
ctx.emit('session/event', createSession(), null);
|
|
305
|
+
assert.equal(ctxLogger.warnings.length, 1);
|
|
306
|
+
});
|
|
307
|
+
|
|
308
|
+
test('live adapter hydrate degrades on missing or hostile sessions', () => {
|
|
309
|
+
const logger = createLogger();
|
|
310
|
+
const ctx = createFakeCtx({ logger });
|
|
311
|
+
const adapter = createLiveUsageAdapter(ctx, { logger });
|
|
312
|
+
|
|
313
|
+
assert.equal(adapter.hydrate(undefined), 0);
|
|
314
|
+
assert.equal(adapter.hydrate({}), 0);
|
|
315
|
+
assert.equal(adapter.hydrate({
|
|
316
|
+
id: 'session-a',
|
|
317
|
+
snapshotEvents() {
|
|
318
|
+
throw new Error('boom');
|
|
319
|
+
},
|
|
320
|
+
}), 0);
|
|
321
|
+
assert.equal(adapter.hydrate({ id: 'session-a', snapshotEvents: () => 'not-an-array' }), 0);
|
|
322
|
+
|
|
323
|
+
assert.equal(logger.warnings.length, 4);
|
|
324
|
+
for (const message of logger.warnings) assert.match(message, /hydrate/);
|
|
325
|
+
});
|
|
326
|
+
|
|
327
|
+
test('live adapter dispose unsubscribes, is idempotent and tolerates a throwing disposer', () => {
|
|
328
|
+
const logger = createLogger();
|
|
329
|
+
const ctx = createFakeCtx({ logger });
|
|
330
|
+
const adapter = createLiveUsageAdapter(ctx, { logger });
|
|
331
|
+
const session = createSession();
|
|
332
|
+
|
|
333
|
+
ctx.emit('session/event', session, assistantEvent({ seq: 1 }));
|
|
334
|
+
adapter.dispose();
|
|
335
|
+
|
|
336
|
+
assert.deepEqual(ctx.disposals, ['session/event']);
|
|
337
|
+
assert.equal(ctx.listenerCount('session/event'), 0);
|
|
338
|
+
ctx.emit('session/event', session, assistantEvent({ seq: 2 }));
|
|
339
|
+
assert.deepEqual(adapter.read('session-a', 0).map((record) => record.seq), [1]);
|
|
340
|
+
|
|
341
|
+
assert.doesNotThrow(() => adapter.dispose());
|
|
342
|
+
assert.deepEqual(ctx.disposals, ['session/event']);
|
|
343
|
+
|
|
344
|
+
const hostile = createFakeCtx({ logger });
|
|
345
|
+
hostile.on = () => () => {
|
|
346
|
+
throw new Error('dispose boom');
|
|
347
|
+
};
|
|
348
|
+
const hostileAdapter = createLiveUsageAdapter(hostile, { logger });
|
|
349
|
+
assert.doesNotThrow(() => hostileAdapter.dispose());
|
|
350
|
+
assert.doesNotThrow(() => hostileAdapter.dispose());
|
|
351
|
+
});
|
|
@@ -0,0 +1,264 @@
|
|
|
1
|
+
import test from 'node:test';
|
|
2
|
+
import assert from 'node:assert/strict';
|
|
3
|
+
|
|
4
|
+
import { captureRequestSnapshot, createMemoryUsageAdapter, createTokenReport } from 'dsh-lean-router/token-ledger';
|
|
5
|
+
|
|
6
|
+
function usage(seq, inputTokens = 10) {
|
|
7
|
+
return {
|
|
8
|
+
sessionId: 'session-a',
|
|
9
|
+
turn: 1,
|
|
10
|
+
step: 2,
|
|
11
|
+
seq,
|
|
12
|
+
provider: 'fixture',
|
|
13
|
+
model: 'fixture-model',
|
|
14
|
+
atMs: 1_700_000_000_000 + seq,
|
|
15
|
+
usage: {
|
|
16
|
+
inputTokens,
|
|
17
|
+
outputTokens: 3,
|
|
18
|
+
cacheReadTokens: 2,
|
|
19
|
+
cacheWriteTokens: 1,
|
|
20
|
+
reasoningTokens: 1,
|
|
21
|
+
},
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
test('UsageAdapter.read deduplicates, sorts and applies after/to bounds', () => {
|
|
26
|
+
const adapter = createMemoryUsageAdapter([
|
|
27
|
+
usage(4, 40),
|
|
28
|
+
usage(2, 20),
|
|
29
|
+
usage(3, 30),
|
|
30
|
+
usage(2, 999),
|
|
31
|
+
{ ...usage(1, 10), turn: 2 },
|
|
32
|
+
{ ...usage(1, 11), step: 1 },
|
|
33
|
+
]);
|
|
34
|
+
|
|
35
|
+
assert.deepEqual(adapter.read('session-a', 0).map((entry) => [entry.turn, entry.step, entry.seq]), [
|
|
36
|
+
[1, 1, 1],
|
|
37
|
+
[1, 2, 2],
|
|
38
|
+
[1, 2, 3],
|
|
39
|
+
[1, 2, 4],
|
|
40
|
+
[2, 2, 1],
|
|
41
|
+
]);
|
|
42
|
+
assert.equal(adapter.read('session-a', 0).find((entry) => entry.turn === 1 && entry.step === 2 && entry.seq === 2).usage.inputTokens, 20);
|
|
43
|
+
assert.deepEqual(adapter.read('session-a', 2, 3).map((entry) => entry.seq), [3]);
|
|
44
|
+
assert.deepEqual(adapter.read('session-b', 0), []);
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
test('UsageAdapter.watch replays afterSeq and streams sorted unique records', () => {
|
|
48
|
+
const adapter = createMemoryUsageAdapter([usage(2, 20), usage(1, 10)]);
|
|
49
|
+
const seen = [];
|
|
50
|
+
const stop = adapter.watch('session-a', 0, (record) => seen.push(record.seq));
|
|
51
|
+
|
|
52
|
+
assert.deepEqual(seen, [1, 2]);
|
|
53
|
+
adapter.append(usage(4, 40), usage(3, 30), usage(3, 999));
|
|
54
|
+
adapter.append({ ...usage(9, 90), sessionId: 'session-b' });
|
|
55
|
+
assert.deepEqual(seen, [1, 2, 3, 4]);
|
|
56
|
+
assert.equal(adapter.read('session-a', 0).find((record) => record.seq === 3).usage.inputTokens, 30);
|
|
57
|
+
|
|
58
|
+
stop();
|
|
59
|
+
adapter.append(usage(5, 50));
|
|
60
|
+
assert.deepEqual(seen, [1, 2, 3, 4]);
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
test('UsageAdapter keeps first writes and never pushes duplicate appends', () => {
|
|
64
|
+
const first = usage(1, 10);
|
|
65
|
+
const adapter = createMemoryUsageAdapter([first, usage(1, 999)]);
|
|
66
|
+
const seen = [];
|
|
67
|
+
const stop = adapter.watch('session-a', 0, (record) => seen.push(record));
|
|
68
|
+
|
|
69
|
+
assert.deepEqual(seen, [first]);
|
|
70
|
+
const next = usage(2, 20);
|
|
71
|
+
adapter.append(next, usage(2, 999), usage(1, 999));
|
|
72
|
+
|
|
73
|
+
assert.deepEqual(seen, [first, next]);
|
|
74
|
+
assert.deepEqual(adapter.read('session-a', 0), [first, next]);
|
|
75
|
+
stop();
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
test('RequestSnapshot captures metadata without request or tool definition content', () => {
|
|
79
|
+
const snapshot = captureRequestSnapshot({
|
|
80
|
+
sessionId: 'session-a',
|
|
81
|
+
turn: 1,
|
|
82
|
+
step: 2,
|
|
83
|
+
seq: 7,
|
|
84
|
+
headerHash: 'sha256:header',
|
|
85
|
+
messages: ['raw prompt'],
|
|
86
|
+
tools: [
|
|
87
|
+
{ name: 'read', schemaHash: 'sha256:read', description: 'raw tool description' },
|
|
88
|
+
{ name: 'edit', schemaHash: 'sha256:edit', parameters: { type: 'object' } },
|
|
89
|
+
],
|
|
90
|
+
partitionChars: { system: 100, context: 200, toolOutput: 300 },
|
|
91
|
+
taskResult: {
|
|
92
|
+
terminal: 'success',
|
|
93
|
+
artifacts: ['lib/token-ledger/index.js'],
|
|
94
|
+
errors: [],
|
|
95
|
+
output: 'raw task output',
|
|
96
|
+
},
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
assert.deepEqual(snapshot, {
|
|
100
|
+
sessionId: 'session-a',
|
|
101
|
+
turn: 1,
|
|
102
|
+
step: 2,
|
|
103
|
+
seq: 7,
|
|
104
|
+
headerHash: 'sha256:header',
|
|
105
|
+
tools: [
|
|
106
|
+
{ name: 'read', schemaHash: 'sha256:read' },
|
|
107
|
+
{ name: 'edit', schemaHash: 'sha256:edit' },
|
|
108
|
+
],
|
|
109
|
+
partitionChars: { system: 100, context: 200, toolOutput: 300 },
|
|
110
|
+
taskResult: {
|
|
111
|
+
terminal: 'success',
|
|
112
|
+
artifacts: ['lib/token-ledger/index.js'],
|
|
113
|
+
errors: [],
|
|
114
|
+
},
|
|
115
|
+
});
|
|
116
|
+
});
|
|
117
|
+
|
|
118
|
+
test('RequestSnapshot rejects raw prompt, body and toolOutput fields', () => {
|
|
119
|
+
for (const field of ['prompt', 'body', 'toolOutput']) {
|
|
120
|
+
assert.throws(
|
|
121
|
+
() => captureRequestSnapshot({ sessionId: 'session-a', seq: 1, [field]: 'raw secret' }),
|
|
122
|
+
new RegExp('raw field "' + field + '"'),
|
|
123
|
+
);
|
|
124
|
+
}
|
|
125
|
+
});
|
|
126
|
+
|
|
127
|
+
test('TokenReport associates snapshots by session, turn, step and seq', () => {
|
|
128
|
+
const records = [
|
|
129
|
+
{ ...usage(7, 10), turn: 2, step: 3 },
|
|
130
|
+
{ ...usage(7, 20), turn: 2, step: 4 },
|
|
131
|
+
{ ...usage(7, 30), turn: 1, step: 3 },
|
|
132
|
+
];
|
|
133
|
+
const snapshots = records.map((record) => captureRequestSnapshot({
|
|
134
|
+
sessionId: record.sessionId,
|
|
135
|
+
turn: record.turn,
|
|
136
|
+
step: record.step,
|
|
137
|
+
seq: record.seq,
|
|
138
|
+
headerHash: `sha256:${record.turn}-${record.step}`,
|
|
139
|
+
}));
|
|
140
|
+
const report = createTokenReport({ records, snapshots });
|
|
141
|
+
|
|
142
|
+
assert.deepEqual(report.entries.map((entry) => [
|
|
143
|
+
entry.turn,
|
|
144
|
+
entry.step,
|
|
145
|
+
entry.seq,
|
|
146
|
+
entry.snapshot.headerHash,
|
|
147
|
+
]), [
|
|
148
|
+
[1, 3, 7, 'sha256:1-3'],
|
|
149
|
+
[2, 3, 7, 'sha256:2-3'],
|
|
150
|
+
[2, 4, 7, 'sha256:2-4'],
|
|
151
|
+
]);
|
|
152
|
+
});
|
|
153
|
+
|
|
154
|
+
test('TokenReport totals host Usage and keeps requestSnapshots separate', () => {
|
|
155
|
+
const snapshot = captureRequestSnapshot({
|
|
156
|
+
sessionId: 'session-a',
|
|
157
|
+
turn: 1,
|
|
158
|
+
step: 2,
|
|
159
|
+
seq: 1,
|
|
160
|
+
headerHash: 'sha256:header',
|
|
161
|
+
partitionChars: { context: 120 },
|
|
162
|
+
});
|
|
163
|
+
const taskResult = {
|
|
164
|
+
terminal: 'success',
|
|
165
|
+
toolCalls: ['read', { name: 'edit' }],
|
|
166
|
+
artifacts: ['lib/token-ledger/index.js'],
|
|
167
|
+
errors: [],
|
|
168
|
+
};
|
|
169
|
+
const report = createTokenReport({
|
|
170
|
+
records: [usage(2, 20), usage(1, 10)],
|
|
171
|
+
snapshots: [snapshot],
|
|
172
|
+
taskResult,
|
|
173
|
+
assertions: {
|
|
174
|
+
expectedTerminal: 'success',
|
|
175
|
+
requiredTools: ['read'],
|
|
176
|
+
requiredArtifacts: ['lib/token-ledger/index.js'],
|
|
177
|
+
forbiddenErrors: ['TIMEOUT'],
|
|
178
|
+
},
|
|
179
|
+
});
|
|
180
|
+
|
|
181
|
+
assert.equal(report.pass, true);
|
|
182
|
+
assert.deepEqual(report.reasons, []);
|
|
183
|
+
assert.deepEqual(report.usage, {
|
|
184
|
+
inputTokens: 30,
|
|
185
|
+
outputTokens: 6,
|
|
186
|
+
cacheReadTokens: 4,
|
|
187
|
+
cacheWriteTokens: 2,
|
|
188
|
+
reasoningTokens: 2,
|
|
189
|
+
prompt: 36,
|
|
190
|
+
});
|
|
191
|
+
assert.equal(Object.hasOwn(report.usage, 'promptTokens'), false);
|
|
192
|
+
assert.equal(Object.hasOwn(report.usage, 'freshTokens'), false);
|
|
193
|
+
assert.deepEqual(report.entries[0].usage, {
|
|
194
|
+
inputTokens: 10,
|
|
195
|
+
outputTokens: 3,
|
|
196
|
+
cacheReadTokens: 2,
|
|
197
|
+
cacheWriteTokens: 1,
|
|
198
|
+
reasoningTokens: 1,
|
|
199
|
+
prompt: 13,
|
|
200
|
+
});
|
|
201
|
+
assert.deepEqual(report.entries[0].snapshot, snapshot);
|
|
202
|
+
assert.deepEqual(report.entries[1].snapshot, null);
|
|
203
|
+
assert.deepEqual(report.entries.map((entry) => [entry.seq, entry.atMs]), [
|
|
204
|
+
[1, 1_700_000_000_001],
|
|
205
|
+
[2, 1_700_000_000_002],
|
|
206
|
+
]);
|
|
207
|
+
assert.deepEqual(report.requestSnapshots, [snapshot]);
|
|
208
|
+
assert.equal(Object.hasOwn(report, 'attribution'), false);
|
|
209
|
+
assert.deepEqual(report.taskResult, taskResult);
|
|
210
|
+
});
|
|
211
|
+
|
|
212
|
+
test('TokenReport fails only on explicit assertion mismatches and explains each reason', () => {
|
|
213
|
+
const report = createTokenReport({
|
|
214
|
+
records: [usage(1)],
|
|
215
|
+
snapshots: [],
|
|
216
|
+
taskResult: {
|
|
217
|
+
terminal: 'failed',
|
|
218
|
+
toolCalls: [{ name: 'edit' }],
|
|
219
|
+
artifacts: ['other.js'],
|
|
220
|
+
errors: ['TIMEOUT'],
|
|
221
|
+
},
|
|
222
|
+
assertions: {
|
|
223
|
+
expectedTerminal: 'success',
|
|
224
|
+
requiredTools: ['read'],
|
|
225
|
+
requiredArtifacts: ['lib/token-ledger/index.js'],
|
|
226
|
+
forbiddenErrors: ['TIMEOUT'],
|
|
227
|
+
},
|
|
228
|
+
});
|
|
229
|
+
|
|
230
|
+
assert.equal(report.pass, false);
|
|
231
|
+
assert.deepEqual(report.reasons, [
|
|
232
|
+
'expected terminal "success", got "failed"',
|
|
233
|
+
'missing required tool "read"',
|
|
234
|
+
'missing required artifact "lib/token-ledger/index.js"',
|
|
235
|
+
'forbidden error "TIMEOUT"',
|
|
236
|
+
]);
|
|
237
|
+
});
|
|
238
|
+
|
|
239
|
+
test('TokenReport derives successRate from explicit assertions', () => {
|
|
240
|
+
const passing = createTokenReport({
|
|
241
|
+
records: [usage(1)],
|
|
242
|
+
taskResult: { terminal: 'success' },
|
|
243
|
+
assertions: { expectedTerminal: 'success' },
|
|
244
|
+
});
|
|
245
|
+
assert.equal(passing.pass, true);
|
|
246
|
+
assert.deepEqual(passing.reasons, []);
|
|
247
|
+
assert.equal(passing.successRate, 1);
|
|
248
|
+
|
|
249
|
+
const failing = createTokenReport({
|
|
250
|
+
records: [usage(1)],
|
|
251
|
+
taskResult: { terminal: 'failed' },
|
|
252
|
+
assertions: { expectedTerminal: 'success' },
|
|
253
|
+
});
|
|
254
|
+
assert.equal(failing.pass, false);
|
|
255
|
+
assert.deepEqual(failing.reasons, ['expected terminal "success", got "failed"']);
|
|
256
|
+
assert.equal(failing.successRate, 0);
|
|
257
|
+
});
|
|
258
|
+
|
|
259
|
+
test('package exposes the token-ledger subpath', async () => {
|
|
260
|
+
const publicModule = await import('dsh-lean-router/token-ledger');
|
|
261
|
+
assert.equal(typeof publicModule.createMemoryUsageAdapter, 'function');
|
|
262
|
+
assert.equal(typeof publicModule.captureRequestSnapshot, 'function');
|
|
263
|
+
assert.equal(typeof publicModule.createTokenReport, 'function');
|
|
264
|
+
});
|