dsh-lean-router 2.1.1 → 2.2.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/cordis.patch.yml +62 -60
- package/docs/agents/release.md +18 -0
- package/docs/agents/verification.md +18 -0
- package/docs/changelog.en.md +17 -1
- package/docs/changelog.md +17 -1
- package/lib/lean/persona-text.js +34 -37
- package/lib/lean/usage-ledger.js +246 -0
- package/lib/toolface/discovery.js +26 -11
- package/lib/toolface/rules.js +5 -4
- package/package.json +2 -1
- package/presets/base/frag-lean.patch.yml +37 -30
- package/presets/base/frag-preset.patch.yml +25 -30
- package/scripts/release.mjs +138 -0
- package/test/lean-frag.test.mjs +3 -3
- package/test/lean-modules.test.mjs +7 -7
- package/test/patch-yaml.test.mjs +1 -1
- package/test/toolface-mask.test.mjs +47 -6
- package/test/toolface-rules.test.mjs +3 -1
- package/test/usage-ledger.test.mjs +208 -0
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// 发布一条命令:node scripts/release.mjs <version> [--dry-run]
|
|
3
|
+
//
|
|
4
|
+
// 只做机械步骤:校验 -> 测试 -> 改版本号 -> 提交 -> 官方向发布 -> 等可见 -> 临时目录安装验证。
|
|
5
|
+
// changelog 正文必须人工先写(脚本只校验两个语言文件里已有 `## <version>` 标题)。
|
|
6
|
+
//
|
|
7
|
+
// 本机陷阱(见 docs/agents/release.md):默认 registry 是 npmmirror,发布一律显式
|
|
8
|
+
// --registry https://registry.npmjs.org;npm 的 notice 走 stderr,别据此判失败。
|
|
9
|
+
|
|
10
|
+
import { execFileSync } from 'node:child_process';
|
|
11
|
+
import { mkdtempSync, readFileSync, writeFileSync } from 'node:fs';
|
|
12
|
+
import { tmpdir } from 'node:os';
|
|
13
|
+
import { join } from 'node:path';
|
|
14
|
+
|
|
15
|
+
const REGISTRY = 'https://registry.npmjs.org';
|
|
16
|
+
const NPM = process.platform === 'win32' ? 'npm.cmd' : 'npm';
|
|
17
|
+
const VISIBILITY_TIMEOUT_MS = 5 * 60 * 1000;
|
|
18
|
+
const POLL_INTERVAL_MS = 10 * 1000;
|
|
19
|
+
|
|
20
|
+
const argv = process.argv.slice(2);
|
|
21
|
+
const dryRun = argv.includes('--dry-run');
|
|
22
|
+
const version = argv.find((arg) => !arg.startsWith('--'));
|
|
23
|
+
|
|
24
|
+
function fail(message) {
|
|
25
|
+
console.error('[release] ' + message);
|
|
26
|
+
process.exit(1);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function run(command, args, options = {}) {
|
|
30
|
+
return execFileSync(command, args, {
|
|
31
|
+
encoding: 'utf8',
|
|
32
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
33
|
+
...options,
|
|
34
|
+
}).trim();
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function npm(args, options = {}) {
|
|
38
|
+
// Windows 上 Node 不能直接 spawn .cmd(EINVAL),必须经 shell 执行;
|
|
39
|
+
// 这里的参数都不含空格,所以 shell 拼接是安全的。
|
|
40
|
+
// npm 的 notice/progress 走 stderr,stdout 才是结果;统一只看退出码与 stdout。
|
|
41
|
+
return execFileSync(NPM, args, {
|
|
42
|
+
encoding: 'utf8',
|
|
43
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
44
|
+
shell: process.platform === 'win32',
|
|
45
|
+
...options,
|
|
46
|
+
}).trim();
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function sleep(ms) {
|
|
50
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function compareVersions(left, right) {
|
|
54
|
+
const parse = (value) => value.split('-')[0].split('.').map(Number);
|
|
55
|
+
const a = parse(left);
|
|
56
|
+
const b = parse(right);
|
|
57
|
+
for (let index = 0; index < 3; index += 1) {
|
|
58
|
+
if ((a[index] ?? 0) !== (b[index] ?? 0)) return (a[index] ?? 0) - (b[index] ?? 0);
|
|
59
|
+
}
|
|
60
|
+
return 0;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
if (!version) fail('用法:node scripts/release.mjs <version> [--dry-run]');
|
|
64
|
+
if (!/^\d+\.\d+\.\d+$/.test(version)) fail('版本号必须是 x.y.z:' + version);
|
|
65
|
+
|
|
66
|
+
const packageJson = JSON.parse(readFileSync('package.json', 'utf8'));
|
|
67
|
+
if (compareVersions(version, packageJson.version) <= 0) {
|
|
68
|
+
fail('新版本必须大于当前版本 ' + packageJson.version);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
for (const file of ['docs/changelog.md', 'docs/changelog.en.md']) {
|
|
72
|
+
const body = readFileSync(file, 'utf8');
|
|
73
|
+
if (!body.includes('## ' + version)) {
|
|
74
|
+
fail(file + ' 缺少 "## ' + version + '" 条目,先人工写 changelog 再发布');
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
const dirty = run('git', ['status', '--porcelain'])
|
|
79
|
+
.split('\n')
|
|
80
|
+
.filter((line) => line.trim().length > 0)
|
|
81
|
+
.filter((line) => !/\.agent-master\/$/.test(line));
|
|
82
|
+
if (dirty.length > 0) {
|
|
83
|
+
fail('工作树不干净,先提交或清理:\n' + dirty.join('\n'));
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
console.log('[release] 目标版本 ' + version + (dryRun ? '(dry-run)' : ''));
|
|
87
|
+
|
|
88
|
+
console.log('[release] 跑测试');
|
|
89
|
+
npm(['test']);
|
|
90
|
+
console.log('[release] 跑 verify');
|
|
91
|
+
npm(['run', 'verify']);
|
|
92
|
+
|
|
93
|
+
if (dryRun) {
|
|
94
|
+
console.log('[release] dry-run 结束:测试与 verify 通过,未改版本、未发布');
|
|
95
|
+
process.exit(0);
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
writeFileSync(
|
|
99
|
+
'package.json',
|
|
100
|
+
JSON.stringify({ ...packageJson, version }, null, 2) + '\n',
|
|
101
|
+
'utf8',
|
|
102
|
+
);
|
|
103
|
+
run('git', ['add', 'package.json']);
|
|
104
|
+
run('git', ['commit', '-m', 'chore(release): ' + version]);
|
|
105
|
+
console.log('[release] 已提交版本号变更');
|
|
106
|
+
|
|
107
|
+
console.log('[release] 发布到官方 registry');
|
|
108
|
+
npm(['publish', '--registry', REGISTRY]);
|
|
109
|
+
|
|
110
|
+
console.log('[release] 等待 registry 可见(最长 5 分钟)');
|
|
111
|
+
const deadline = Date.now() + VISIBILITY_TIMEOUT_MS;
|
|
112
|
+
let visible = false;
|
|
113
|
+
while (Date.now() < deadline) {
|
|
114
|
+
await sleep(POLL_INTERVAL_MS);
|
|
115
|
+
try {
|
|
116
|
+
const published = npm(['view', packageJson.name + '@' + version, 'version', '--registry', REGISTRY]);
|
|
117
|
+
if (published === version) {
|
|
118
|
+
visible = true;
|
|
119
|
+
break;
|
|
120
|
+
}
|
|
121
|
+
} catch {
|
|
122
|
+
// 还没传播,继续等。
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
if (!visible) fail('5 分钟内 registry 仍未可见,稍后手工 npm view 复核');
|
|
126
|
+
|
|
127
|
+
console.log('[release] 下载验证');
|
|
128
|
+
const dir = mkdtempSync(join(tmpdir(), 'lean-router-release-'));
|
|
129
|
+
writeFileSync(
|
|
130
|
+
join(dir, 'package.json'),
|
|
131
|
+
JSON.stringify({ name: 'release-check', private: true, type: 'module' }, null, 2),
|
|
132
|
+
'utf8',
|
|
133
|
+
);
|
|
134
|
+
npm(['install', packageJson.name + '@' + version, '--registry', REGISTRY, '--no-audit', '--no-fund', '--ignore-scripts'], { cwd: dir });
|
|
135
|
+
const installed = JSON.parse(readFileSync(join(dir, 'node_modules', packageJson.name, 'package.json'), 'utf8'));
|
|
136
|
+
if (installed.version !== version) fail('下载到的版本不符:' + installed.version + ' != ' + version);
|
|
137
|
+
|
|
138
|
+
console.log('[release] 完成:' + packageJson.name + '@' + version + ' 已发布并通过下载验证');
|
package/test/lean-frag.test.mjs
CHANGED
|
@@ -14,8 +14,8 @@ test('分片存在且顶层为 YAML 块序列续项(首个非注释行为顶
|
|
|
14
14
|
assert.ok(firstLine.startsWith('- '), '首个非注释行必须是顶层块序列项(- 开头),got: ' + firstLine);
|
|
15
15
|
// 所有顶层项都在 0 列
|
|
16
16
|
const topLevel = frag.split('\n').filter((l) => /^- /.test(l) || /^-insert/.test(l));
|
|
17
|
-
assert.ok(topLevel.length >=
|
|
18
|
-
assert.equal(frag.split('\n').filter((l) => l.startsWith('- ')).length,
|
|
17
|
+
assert.ok(topLevel.length >= 5, '至少 5 个顶层项(裸覆写行 + 4 个 insert 块)');
|
|
18
|
+
assert.equal(frag.split('\n').filter((l) => l.startsWith('- ')).length, 5, '顶层项恰好 5 个:裸行 + balance + delivery-gate + concurrency + usage-ledger');
|
|
19
19
|
});
|
|
20
20
|
|
|
21
21
|
test('裸覆写行重声明 preset-lean-router 完整 config(dsh-app-boot config 整键替换形态)', async () => {
|
|
@@ -121,7 +121,7 @@ test('(宿主 yaml 可用时)合并后整文件可解析且行形态符合
|
|
|
121
121
|
const base = await readFile(basePath, 'utf8');
|
|
122
122
|
const frag = await readFile(fragPath, 'utf8');
|
|
123
123
|
const doc = yaml.parse(base + (frag.endsWith('\n') ? frag : frag + '\n'), { schema: 'core' });
|
|
124
|
-
assert.equal(doc.length,
|
|
124
|
+
assert.equal(doc.length, 6, '合并后顶层 6 项:base insert + 裸覆写 + balance + delivery-gate + concurrency + usage-ledger');
|
|
125
125
|
const override = doc.find((d) => d.id === 'preset-lean-router');
|
|
126
126
|
assert.equal(override.config.plugins.length, 20);
|
|
127
127
|
const deleg = override.config.plugins.find((p) => p.id === 'delegation');
|
|
@@ -26,19 +26,19 @@ test('disabled.js 独立加载:6 件清单与上游一致', async () => {
|
|
|
26
26
|
assert.equal(m.DISABLED_PLUGIN_ROWS.every((r) => r.disabled === true), true);
|
|
27
27
|
});
|
|
28
28
|
|
|
29
|
-
test('persona-text.js 独立加载:lean 13 条 +
|
|
29
|
+
test('persona-text.js 独立加载:lean 13 条 + 2 软门 + 自检题钩子 + balance 3 条 + 拼接占位', async () => {
|
|
30
30
|
const m = await mod('persona-text.js');
|
|
31
31
|
const leanRules = m.LEAN_PERSONA_SUFFIX.match(/^\d+\./gm) || [];
|
|
32
32
|
assert.equal(leanRules.length, 13);
|
|
33
33
|
assert.equal((m.BALANCE_PERSONA_SUFFIX.match(/^\d+\./gm) || []).length, 3);
|
|
34
|
-
assert.equal(m.LEAN_SOFT_GATES.length,
|
|
35
|
-
assert.equal(m.LEAN_SELF_CHECK_HOOKS.length,
|
|
36
|
-
//
|
|
34
|
+
assert.equal(m.LEAN_SOFT_GATES.length, 2);
|
|
35
|
+
assert.equal(m.LEAN_SELF_CHECK_HOOKS.length, 1);
|
|
36
|
+
// 2 软门:澄清/计划(交付门已由规则 4 覆盖,不再单列)
|
|
37
37
|
assert.ok(m.LEAN_PERSONA_SUFFIX.includes('CLARIFY:'));
|
|
38
38
|
assert.ok(m.LEAN_PERSONA_SUFFIX.includes('PLAN:'));
|
|
39
|
-
assert.ok(m.LEAN_PERSONA_SUFFIX.includes('DELIVER:'));
|
|
40
|
-
//
|
|
41
|
-
assert.ok(m.LEAN_PERSONA_SUFFIX.includes('Diligence (~every 10 turns):'));
|
|
39
|
+
assert.ok(!m.LEAN_PERSONA_SUFFIX.includes('DELIVER:'), '交付门不得与规则 4 重复');
|
|
40
|
+
// 自检题钩子:只留合卷(勤勉自检已并入规则 1)
|
|
41
|
+
assert.ok(!m.LEAN_PERSONA_SUFFIX.includes('Diligence (~every 10 turns):'), '勤勉自检不得与规则 1 重复');
|
|
42
42
|
assert.ok(m.LEAN_PERSONA_SUFFIX.includes('Close-the-book:'));
|
|
43
43
|
// 票 05 拼接占位(两个 suffix 都要有;不写任何路由内容)
|
|
44
44
|
for (const s of [m.LEAN_PERSONA_SUFFIX, m.BALANCE_PERSONA_SUFFIX]) {
|
package/test/patch-yaml.test.mjs
CHANGED
|
@@ -20,7 +20,7 @@ function parseFile(path) {
|
|
|
20
20
|
test("cordis.patch.yml 可被 dsh 等价解析器装载", () => {
|
|
21
21
|
const doc = parseFile(join(root, "cordis.patch.yml"));
|
|
22
22
|
assert.ok(Array.isArray(doc), "顶层必须是操作数组");
|
|
23
|
-
assert.equal(doc.length,
|
|
23
|
+
assert.equal(doc.length, 9, "9 个顶层操作");
|
|
24
24
|
const rows = doc.flatMap((op) => op.insert ?? []);
|
|
25
25
|
assert.ok(rows.some((row) => row.id === "preset-lean-router"), "含 preset-lean-router 行");
|
|
26
26
|
});
|
|
@@ -11,9 +11,20 @@ const SCOPE_TAG = Symbol('dsh.scope');
|
|
|
11
11
|
/** A fake three-layer registry: get(name) global, get(name, scope) adds the preset layer. */
|
|
12
12
|
const LAYERS = {
|
|
13
13
|
preset: ['pwsh', 'code_run', 'code_tools_list', 'code_tools_search', 'code_tools_describe', 'code_debug'],
|
|
14
|
-
global: ['mcp_probe', 'mcp__fake__get_ticker', 'load_workspace_dependencies'],
|
|
14
|
+
global: ['mcp_probe', 'mcp__fake__get_ticker', 'mcp__fake__open_anything', 'load_workspace_dependencies'],
|
|
15
15
|
agent: ['spawn_teammate'],
|
|
16
16
|
};
|
|
17
|
+
/** Named parameters: search reports only the names, describe the whole schema. */
|
|
18
|
+
const TICKER_PARAMETERS = {
|
|
19
|
+
type: 'object',
|
|
20
|
+
properties: {
|
|
21
|
+
symbol: { type: 'string', description: 'Ticker symbol, e.g. BTC-USDT.' },
|
|
22
|
+
market: { type: 'string', description: 'Market type, e.g. spot.' },
|
|
23
|
+
},
|
|
24
|
+
required: ['symbol'],
|
|
25
|
+
};
|
|
26
|
+
/** Free-form arguments: no `properties`, so search can only say `noParams`. */
|
|
27
|
+
const FREE_FORM_PARAMETERS = { type: 'object', additionalProperties: true };
|
|
17
28
|
const DEFINITIONS = new Map();
|
|
18
29
|
for (const layer of Object.keys(LAYERS)) {
|
|
19
30
|
for (const name of LAYERS[layer]) {
|
|
@@ -21,7 +32,11 @@ for (const layer of Object.keys(LAYERS)) {
|
|
|
21
32
|
DEFINITIONS.set(name, {
|
|
22
33
|
name,
|
|
23
34
|
description: 'fixture tool ' + name,
|
|
24
|
-
parameters:
|
|
35
|
+
parameters: name === 'mcp__fake__get_ticker'
|
|
36
|
+
? TICKER_PARAMETERS
|
|
37
|
+
: name === 'mcp__fake__open_anything'
|
|
38
|
+
? FREE_FORM_PARAMETERS
|
|
39
|
+
: { type: 'object', properties: {} },
|
|
25
40
|
...(name === 'pwsh' ? { isConcurrencySafe: () => true } : {}),
|
|
26
41
|
});
|
|
27
42
|
}
|
|
@@ -157,15 +172,41 @@ test('list supports a namespace filter', async () => {
|
|
|
157
172
|
assert.ok(native.tools.some(r => r.name === 'pwsh'));
|
|
158
173
|
});
|
|
159
174
|
|
|
160
|
-
test('search returns
|
|
175
|
+
test('search returns parameter names, never the full schema', async () => {
|
|
161
176
|
const { tools, exec } = discoveryHarness({ scopeKey: true });
|
|
162
|
-
const out = await tools[1].execute({ query: 'ticker' }, exec);
|
|
177
|
+
const out = await tools[1].execute({ query: 'ticker', namespace: 'fake' }, exec);
|
|
163
178
|
assert.equal(out.query, 'ticker');
|
|
164
179
|
assert.equal(out.tools[0].name, 'mcp__fake__get_ticker');
|
|
165
|
-
assert.deepEqual(out.tools[0].
|
|
180
|
+
assert.deepEqual(out.tools[0].params, ['symbol', 'market'], 'declaration order, names only');
|
|
181
|
+
assert.equal('parameters' in out.tools[0], false, 'the full parameter schema is not inlined');
|
|
182
|
+
assert.equal('output' in out.tools[0], false, 'nor the output schema');
|
|
166
183
|
assert.ok(out.tools.length <= 8, 'default searchLimit caps the page');
|
|
167
184
|
});
|
|
168
185
|
|
|
186
|
+
test('search reports noParams for a tool that declares no properties', async () => {
|
|
187
|
+
const { tools, exec } = discoveryHarness({ scopeKey: true });
|
|
188
|
+
const out = await tools[1].execute({ query: 'open_anything', namespace: 'fake' }, exec);
|
|
189
|
+
const row = out.tools.find(r => r.name === 'mcp__fake__open_anything');
|
|
190
|
+
assert.equal(row.noParams, true);
|
|
191
|
+
assert.equal('params' in row, false, 'an empty list would read as "takes no arguments"');
|
|
192
|
+
});
|
|
193
|
+
|
|
194
|
+
test('describe still returns the complete parameter schema', async () => {
|
|
195
|
+
const { tools, exec } = discoveryHarness({ scopeKey: true });
|
|
196
|
+
const hit = await tools[2].execute({ name: 'mcp__fake__get_ticker' }, exec);
|
|
197
|
+
assert.deepEqual(hit.parameters, TICKER_PARAMETERS);
|
|
198
|
+
const free = await tools[2].execute({ name: 'mcp__fake__open_anything' }, exec);
|
|
199
|
+
assert.deepEqual(free.parameters, FREE_FORM_PARAMETERS, 'free-form schemas survive describe');
|
|
200
|
+
});
|
|
201
|
+
|
|
202
|
+
test('the search tool documents the describe follow-up', () => {
|
|
203
|
+
const { tools } = discoveryHarness({ scopeKey: true });
|
|
204
|
+
const doc = tools[1].description;
|
|
205
|
+
assert.match(doc, /parameter NAMES/);
|
|
206
|
+
assert.match(doc, /code_tools_describe/);
|
|
207
|
+
assert.doesNotMatch(doc, /WITH their full JSON parameter schemas/);
|
|
208
|
+
});
|
|
209
|
+
|
|
169
210
|
test('search validates its query argument', async () => {
|
|
170
211
|
const { tools, exec } = discoveryHarness();
|
|
171
212
|
await assert.rejects(() => tools[1].execute({}, exec), /query/);
|
|
@@ -206,7 +247,7 @@ test('the listing flags out-of-preset tools the same way the request masking doe
|
|
|
206
247
|
const view = resolveScopeViewFromListing(out);
|
|
207
248
|
assert.equal(typeof view, 'undefined', 'the listing itself is judged, not the view');
|
|
208
249
|
const mcp = out.tools.filter(r => isMaskedName(r.name, normalizeConfig({}), { enabled: true, globalNames: new Set(LAYERS.global), presetNames: new Set(LAYERS.preset), agentNames: new Set([...LAYERS.global, ...LAYERS.preset, ...LAYERS.agent]) }));
|
|
209
|
-
assert.deepEqual(mcp.map(r => r.name).sort(), ['mcp__fake__get_ticker', 'mcp_probe', 'spawn_teammate', 'load_workspace_dependencies', 'code_tools_list', 'code_tools_search', 'code_tools_describe', 'code_debug'].sort().filter(n => isMasked(n, LAYERS)));
|
|
250
|
+
assert.deepEqual(mcp.map(r => r.name).sort(), ['mcp__fake__get_ticker', 'mcp__fake__open_anything', 'mcp_probe', 'spawn_teammate', 'load_workspace_dependencies', 'code_tools_list', 'code_tools_search', 'code_tools_describe', 'code_debug'].sort().filter(n => isMasked(n, LAYERS)));
|
|
210
251
|
});
|
|
211
252
|
|
|
212
253
|
function resolveScopeViewFromListing() { return undefined; }
|
|
@@ -160,7 +160,9 @@ test('the section keeps the model-critical contract after the prose trim', () =>
|
|
|
160
160
|
assert.match(text, /is rejected by the harness/, 'the model-direct denial stays advertised');
|
|
161
161
|
assert.match(text, /only callable from inside/, 'discovery tools stay program-only');
|
|
162
162
|
assert.match(text, /Never guess a masked tool's name or arguments/, 'the search-first rule stays advertised');
|
|
163
|
-
assert.match(text, /hits\[0\]\.
|
|
163
|
+
assert.match(text, /hits\[0\]\.name/, 'the describe step points at the matched name');
|
|
164
|
+
assert.match(text, /const \{ parameters \} = await tools\.code_tools_describe/, 'the full schema comes from describe');
|
|
165
|
+
assert.doesNotMatch(text, /ranked matches with full parameter schemas/, 'search no longer claims to return schemas');
|
|
164
166
|
});
|
|
165
167
|
|
|
166
168
|
test('buildCodemodeSectionText degrades cleanly with nothing hidden', () => {
|
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
// test/usage-ledger.test.mjs —— 加料件:live Usage 账本挂载(订阅、token-report、降级与卸载)
|
|
2
|
+
import test from 'node:test';
|
|
3
|
+
import assert from 'node:assert/strict';
|
|
4
|
+
|
|
5
|
+
import { apply, __internals } from 'dsh-lean-router/lean/usage-ledger';
|
|
6
|
+
|
|
7
|
+
const BASE_USAGE = {
|
|
8
|
+
inputTokens: 10,
|
|
9
|
+
outputTokens: 3,
|
|
10
|
+
cacheReadTokens: 2,
|
|
11
|
+
cacheWriteTokens: 1,
|
|
12
|
+
reasoningTokens: 1,
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
function usage(overrides = {}) {
|
|
16
|
+
return { ...BASE_USAGE, ...overrides };
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function createLogger() {
|
|
20
|
+
const warnings = [];
|
|
21
|
+
return {
|
|
22
|
+
warnings,
|
|
23
|
+
warn(message) {
|
|
24
|
+
warnings.push(message);
|
|
25
|
+
},
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** 最小假 ctx:on / commands.register 可观测;与 token-ledger-live.test.mjs 同风格。 */
|
|
30
|
+
function createFakeCtx({ on = true, commands = true, logger } = {}) {
|
|
31
|
+
const listeners = new Map();
|
|
32
|
+
const disposals = [];
|
|
33
|
+
const registered = [];
|
|
34
|
+
const ctx = { logger, disposals, registered };
|
|
35
|
+
if (on) {
|
|
36
|
+
ctx.on = (name, listener) => {
|
|
37
|
+
const set = listeners.get(name) ?? new Set();
|
|
38
|
+
set.add(listener);
|
|
39
|
+
listeners.set(name, set);
|
|
40
|
+
return () => {
|
|
41
|
+
disposals.push(name);
|
|
42
|
+
set.delete(listener);
|
|
43
|
+
};
|
|
44
|
+
};
|
|
45
|
+
ctx.emit = (name, ...args) => {
|
|
46
|
+
for (const listener of [...(listeners.get(name) ?? [])]) listener(...args);
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
if (commands) {
|
|
50
|
+
ctx.commands = {
|
|
51
|
+
register(definition) {
|
|
52
|
+
registered.push(definition);
|
|
53
|
+
return () => {};
|
|
54
|
+
},
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
ctx.listenerCount = (name) => (listeners.get(name) ?? new Set()).size;
|
|
58
|
+
return ctx;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function assistantEvent({
|
|
62
|
+
seq,
|
|
63
|
+
turn = 1,
|
|
64
|
+
step = 2,
|
|
65
|
+
time = 1_700_000_000_000 + seq,
|
|
66
|
+
usage: eventUsage = usage(),
|
|
67
|
+
message = { role: 'assistant', source: { kind: 'model', provider: 'fixture', model: 'fixture-model' } },
|
|
68
|
+
} = {}) {
|
|
69
|
+
return {
|
|
70
|
+
type: 'assistant/message',
|
|
71
|
+
seq,
|
|
72
|
+
time,
|
|
73
|
+
data: { turn, step, message, stream: [], usage: eventUsage },
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function commandOf(ctx) {
|
|
78
|
+
const definition = ctx.registered.find((entry) => entry.name === 'token-report');
|
|
79
|
+
assert.ok(definition, 'token-report 命令已注册');
|
|
80
|
+
return definition;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function invocation(sessionId, rawInput = '') {
|
|
84
|
+
return { agent: { session: { id: sessionId } }, rawInput };
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
test('订阅 session/event 后 adapter.read 拿到一条 assistant/message usage 记录', () => {
|
|
88
|
+
const logger = createLogger();
|
|
89
|
+
const ctx = createFakeCtx({ logger });
|
|
90
|
+
const ledger = __internals.createUsageLedger(ctx);
|
|
91
|
+
|
|
92
|
+
ctx.emit('session/event', { id: 'session-a' }, assistantEvent({ seq: 7, turn: 2, step: 3 }));
|
|
93
|
+
|
|
94
|
+
const records = ledger.adapter.read('session-a', 0);
|
|
95
|
+
assert.equal(records.length, 1);
|
|
96
|
+
assert.equal(records[0].seq, 7);
|
|
97
|
+
assert.deepEqual(records[0].usage, usage());
|
|
98
|
+
// 适配器与 /token-report all 的会话跟踪各一条订阅
|
|
99
|
+
assert.equal(ctx.listenerCount('session/event'), 2);
|
|
100
|
+
assert.deepEqual(logger.warnings, []);
|
|
101
|
+
});
|
|
102
|
+
|
|
103
|
+
test('token-report 返回 success,文本含记录数、prompt 总量与五项分项、最近一条 turn/step/seq', () => {
|
|
104
|
+
const ctx = createFakeCtx({ logger: createLogger() });
|
|
105
|
+
apply(ctx);
|
|
106
|
+
const definition = commandOf(ctx);
|
|
107
|
+
assert.equal(definition.input.hint, '[session|all]');
|
|
108
|
+
|
|
109
|
+
ctx.emit('session/event', { id: 'session-a' }, assistantEvent({ seq: 7, turn: 2, step: 3 }));
|
|
110
|
+
const result = definition.handler(invocation('session-a'));
|
|
111
|
+
|
|
112
|
+
assert.equal(result.kind, 'success');
|
|
113
|
+
for (const needle of [
|
|
114
|
+
'记录 1 条',
|
|
115
|
+
'prompt 总量 13',
|
|
116
|
+
'input 10',
|
|
117
|
+
'output 3',
|
|
118
|
+
'cacheRead 2',
|
|
119
|
+
'cacheWrite 1',
|
|
120
|
+
'reasoning 1',
|
|
121
|
+
'turn 2',
|
|
122
|
+
'step 3',
|
|
123
|
+
'seq 7',
|
|
124
|
+
]) {
|
|
125
|
+
assert.ok(result.text.includes(needle), '命令文本缺 "' + needle + '":' + result.text);
|
|
126
|
+
}
|
|
127
|
+
});
|
|
128
|
+
|
|
129
|
+
test('没有任何记录时返回 success 并提示尚未采集', () => {
|
|
130
|
+
const ctx = createFakeCtx({ logger: createLogger() });
|
|
131
|
+
apply(ctx);
|
|
132
|
+
|
|
133
|
+
const result = commandOf(ctx).handler(invocation('session-a'));
|
|
134
|
+
|
|
135
|
+
assert.equal(result.kind, 'success');
|
|
136
|
+
assert.ok(result.text.includes('记录 0 条'), result.text);
|
|
137
|
+
assert.ok(
|
|
138
|
+
result.text.includes('尚未采集到 usage,可能本会话还没有 assistant/message 事件'),
|
|
139
|
+
result.text,
|
|
140
|
+
);
|
|
141
|
+
});
|
|
142
|
+
|
|
143
|
+
test('enabled: false 时既不订阅也不注册命令', () => {
|
|
144
|
+
const ctx = createFakeCtx({ logger: createLogger() });
|
|
145
|
+
apply(ctx, { enabled: false });
|
|
146
|
+
|
|
147
|
+
assert.equal(ctx.listenerCount('session/event'), 0);
|
|
148
|
+
assert.equal(ctx.listenerCount('dispose'), 0);
|
|
149
|
+
assert.equal(ctx.registered.length, 0);
|
|
150
|
+
});
|
|
151
|
+
|
|
152
|
+
test('ctx 缺少 commands 或 on 时不抛异常,命令仍可读到空账本', () => {
|
|
153
|
+
const logger = createLogger();
|
|
154
|
+
const noCommands = createFakeCtx({ commands: false, logger });
|
|
155
|
+
assert.doesNotThrow(() => apply(noCommands));
|
|
156
|
+
assert.equal(noCommands.listenerCount('session/event'), 2, '缺 commands 仍应订阅');
|
|
157
|
+
assert.ok(logger.warnings.some((message) => message.includes('ctx.commands')));
|
|
158
|
+
|
|
159
|
+
const noOn = createFakeCtx({ on: false, logger });
|
|
160
|
+
assert.doesNotThrow(() => apply(noOn));
|
|
161
|
+
assert.equal(noOn.registered.length, 1, '缺 on 仍注册命令(报告显示尚未采集)');
|
|
162
|
+
const result = commandOf(noOn).handler(invocation('session-a'));
|
|
163
|
+
assert.equal(result.kind, 'success');
|
|
164
|
+
assert.match(result.text, /尚未采集到 usage/);
|
|
165
|
+
|
|
166
|
+
assert.doesNotThrow(() => apply(null));
|
|
167
|
+
assert.doesNotThrow(() => apply(undefined, undefined));
|
|
168
|
+
});
|
|
169
|
+
|
|
170
|
+
test('/token-report all 汇总已跟踪的多个会话', () => {
|
|
171
|
+
const ctx = createFakeCtx({ logger: createLogger() });
|
|
172
|
+
apply(ctx);
|
|
173
|
+
|
|
174
|
+
ctx.emit('session/event', { id: 'session-a' }, assistantEvent({ seq: 1, turn: 1, step: 1 }));
|
|
175
|
+
ctx.emit('session/event', { id: 'session-b' }, assistantEvent({ seq: 2, turn: 2, step: 1 }));
|
|
176
|
+
|
|
177
|
+
const result = commandOf(ctx).handler(invocation('session-a', 'all'));
|
|
178
|
+
assert.equal(result.kind, 'success');
|
|
179
|
+
assert.ok(result.text.includes('记录 2 条'), result.text);
|
|
180
|
+
assert.ok(result.text.includes('2 个会话'), result.text);
|
|
181
|
+
assert.ok(result.text.includes('prompt 总量 26'), result.text);
|
|
182
|
+
});
|
|
183
|
+
|
|
184
|
+
test('未知范围返回 error 且不抛', () => {
|
|
185
|
+
const ctx = createFakeCtx({ logger: createLogger() });
|
|
186
|
+
apply(ctx);
|
|
187
|
+
|
|
188
|
+
const result = commandOf(ctx).handler(invocation('session-a', 'bogus'));
|
|
189
|
+
assert.equal(result.kind, 'error');
|
|
190
|
+
assert.match(result.text, /session\|all/);
|
|
191
|
+
});
|
|
192
|
+
|
|
193
|
+
test('宿主 dispose 后卸载适配器与跟踪订阅,重复卸载幂等', () => {
|
|
194
|
+
const ctx = createFakeCtx({ logger: createLogger() });
|
|
195
|
+
apply(ctx);
|
|
196
|
+
ctx.emit('session/event', { id: 'session-a' }, assistantEvent({ seq: 1 }));
|
|
197
|
+
assert.equal(ctx.listenerCount('session/event'), 2);
|
|
198
|
+
|
|
199
|
+
ctx.emit('dispose');
|
|
200
|
+
assert.equal(ctx.listenerCount('session/event'), 0);
|
|
201
|
+
assert.deepEqual(
|
|
202
|
+
ctx.disposals.filter((name) => name === 'session/event').length,
|
|
203
|
+
2,
|
|
204
|
+
'适配器与跟踪订阅都被卸载',
|
|
205
|
+
);
|
|
206
|
+
|
|
207
|
+
assert.doesNotThrow(() => ctx.emit('dispose'));
|
|
208
|
+
});
|