dsh-lean-router 2.0.0 → 2.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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
+ }
@@ -41,6 +41,76 @@
41
41
  */
42
42
 
43
43
  import { isMaskedName } from './rules.js';
44
+ import { slimContentBlocks } from '../lean/output-slim.js';
45
+
46
+ /**
47
+ * [dsh-lean-router ticket context_output_compactor] Proof that a definition's
48
+ * `finalizeContent` already carries this preset's wrapper.
49
+ *
50
+ * `describe()` runs once per request assembly, on the *same* definition objects
51
+ * the registry stores (`definitions()` hands out `registration.definition`), so
52
+ * the wrapper is installed in place. Without this flag the wrapper would nest
53
+ * once per assembly and compact the already-compacted text.
54
+ */
55
+ export const SLIM_FINALIZER_MARK = Symbol.for('dsh-lean-router.output-slim.finalizer');
56
+
57
+ /**
58
+ * Install the conservative output compactor on one definition's
59
+ * `finalizeContent` hook, in place.
60
+ *
61
+ * WHY THIS HOOK: `finalizeContent` is the last-mile content transform — the
62
+ * pipeline applies its return value to `result.content` only, so the canonical
63
+ * `value` (which a program's sub-call settles to) is never touched. `content` is
64
+ * what the model sees; that is the whole surface this ticket may change.
65
+ *
66
+ * Chaining rules, in order:
67
+ * 1. a tool that already has `finalizeContent` is called first, with the same
68
+ * `this` the pipeline would have given it, and its result is then compacted;
69
+ * 2. `undefined` from the original means "keep the renderer output", so the
70
+ * renderer's `result.content` is the text to compact;
71
+ * 3. when no block actually changes, the original return value is passed through
72
+ * untouched (including `undefined`), so a tool that did not compact behaves
73
+ * exactly as before;
74
+ * 4. an exception from the original is NOT caught: the pipeline already turns a
75
+ * throwing finalizer into an error result, and swallowing it here would turn
76
+ * a failing tool into a silently succeeding one.
77
+ *
78
+ * A frozen definition keeps its original finalizer: compaction must never be the
79
+ * reason a tool stops describing or running.
80
+ *
81
+ * @param definition - one visible tool definition.
82
+ * @returns the same definition, wrapped when possible.
83
+ */
84
+ export function wrapFinalizeContent(definition) {
85
+ if (definition === null || typeof definition !== 'object') return definition;
86
+ if (definition[SLIM_FINALIZER_MARK] === true) return definition;
87
+
88
+ const original = typeof definition.finalizeContent === 'function' ? definition.finalizeContent : undefined;
89
+ const wrapped = function finalizeContentWithSlimOutput(exec, result) {
90
+ const finalized = original === undefined ? undefined : original.call(this, exec, result);
91
+ const current = finalized === undefined ? result?.content : finalized;
92
+ const slimmed = slimContentBlocks(current);
93
+ if (slimmed === current) return finalized;
94
+ return slimmed;
95
+ };
96
+
97
+ try {
98
+ Object.defineProperty(definition, 'finalizeContent', {
99
+ value: wrapped,
100
+ enumerable: true,
101
+ configurable: true,
102
+ writable: true,
103
+ });
104
+ Object.defineProperty(definition, SLIM_FINALIZER_MARK, {
105
+ value: true,
106
+ enumerable: false,
107
+ configurable: true,
108
+ });
109
+ } catch {
110
+ /* frozen definition: keep the original behaviour rather than break describe() */
111
+ }
112
+ return definition;
113
+ }
44
114
 
45
115
  // [vendored dsh-lean-router 2026-11-18] The native executor module is loaded on
46
116
  // demand (a dynamic import inside loadNativeExecutorModule) instead of a
@@ -159,6 +229,12 @@ export function createCodemodeExecutor(ctx, options, hooks = {}) {
159
229
  masked: tools.map((tool) => tool?.name).filter((name) => isMaskedName(name, options, view)),
160
230
  view,
161
231
  });
232
+ // [dsh-lean-router ticket context_output_compactor] Conservative output
233
+ // compaction covers `code_run` and every preset-owned visible tool. It is
234
+ // installed on the definitions the registry stores (the same objects the
235
+ // execution pipeline snapshots `finalizeContent` from), and it touches
236
+ // `content` only — never `value`, so nested sub-calls settle unchanged.
237
+ for (const definition of visible) wrapFinalizeContent(definition);
162
238
  return native.describe(visible);
163
239
  },
164
240
 
@@ -330,33 +330,31 @@ export function buildCodemodeSectionText(input) {
330
330
 
331
331
  lines.push('## Code Mode');
332
332
  lines.push('');
333
- lines.push(`This session runs in Code Mode. Tools listed in your tool list are called directly, as usual. A second, larger set of tools — every tool this preset does not own, including every MCP tool and every tool contributed by a plugin outside the preset — is deliberately **not** in your context and is reachable only from inside \`${runToolName}\`.`);
333
+ lines.push(`Code Mode: tools in your list are called directly; everything else — MCP servers, outside plugins — is **not** in your context and is reachable only from inside \`${runToolName}\`.`);
334
334
  lines.push('');
335
- lines.push('### Calling tools from a program');
335
+ lines.push('### Calling tools');
336
336
  lines.push('');
337
337
  lines.push('```js');
338
- lines.push(`// standard tools and every masked tool alike`);
339
338
  lines.push('const files = await tools.glob({ pattern: "src/**/*.ts" })');
340
- lines.push('const rows = await Promise.all(files.map((f) => tools.read({ file_path: f })))');
341
339
  lines.push(retained
342
- ? 'rows.filter((r) => r.includes("TODO")).map((r) => r.split("\\n")[0])'
343
- : 'return rows.filter((r) => r.includes("TODO")).map((r) => r.split("\\n")[0])');
340
+ ? 'await Promise.all(files.map((f) => tools.read({ file_path: f })))'
341
+ : 'return Promise.all(files.map((f) => tools.read({ file_path: f })))');
344
342
  lines.push('```');
345
343
  lines.push('');
346
344
  if (retained) {
347
- lines.push('- A retained TypeScript REPL: top-level declarations, `await`, and a final expression. This program shares its variables, functions, and imported modules with your later programs in this session.');
348
- lines.push('- Only printed values and the final expression become program output; every intermediate result stays in the program, so filter and aggregate there instead of emitting raw payloads.');
345
+ lines.push('- A retained TypeScript REPL: later programs share its variables and imports; top-level declarations, `await` and a final expression, but no top-level `return`.');
346
+ lines.push('- Only printed values and the final expression reach the conversation; aggregate intermediate results inside the program.');
349
347
  } else {
350
348
  lines.push('- Erasable TypeScript, run as the body of an async function: top-level `await` and `return` work.');
351
- lines.push('- Only what you `return` or `console.log` reaches the conversation; every intermediate result stays in the program, so filter and aggregate there instead of returning raw payloads.');
349
+ lines.push('- Only what you return or print reaches the conversation; aggregate intermediate results inside the program.');
352
350
  }
353
351
  lines.push('- Independent read-only calls may overlap under `Promise.all`; mutating calls run alone, in submission order.');
354
- lines.push('- A failed sub-call rejects; `try/catch` or `Promise.allSettled` it to keep the calls that succeeded. Completed calls are real side effects and are not rolled back.');
352
+ lines.push('- A failed sub-call rejects; `try/catch` or `Promise.allSettled` it. Completed calls are real side effects, not rolled back.');
355
353
  lines.push('');
356
354
  if (hidden.total > 0) {
357
355
  lines.push('### Masked tools');
358
356
  lines.push('');
359
- lines.push(`${hidden.total} tool(s) are outside this preset's standard composition and are hidden from your context, by namespace:`);
357
+ lines.push(`${hidden.total} tool(s) are outside this preset's standard composition and hidden from your context, by namespace:`);
360
358
  lines.push('');
361
359
  for (const entry of hidden.namespaces) {
362
360
  lines.push(entry.kind === 'mcp'
@@ -364,34 +362,33 @@ export function buildCodemodeSectionText(input) {
364
362
  : `- \`${entry.namespace}\` (contributed by plugins outside this preset) — ${entry.count} tool(s), callable by exact name as \`tools.<name>({...})\``);
365
363
  }
366
364
  lines.push('');
367
- lines.push('Discover them from inside a program, then call them by exact name:');
365
+ lines.push('Find and call them by exact name from a program:');
368
366
  lines.push('');
369
367
  lines.push('```js');
370
368
  lines.push(`const { tools: hits } = await tools.${searchTool}({ query: "what you need", limit: ${searchLimit} })`);
371
- lines.push('// hits[0].name, hits[0].description, hits[0].parameters (full JSON Schema)');
372
369
  lines.push(retained
373
- ? 'await tools[hits[0].name]({ /* arguments matching hits[0].parameters */ })'
374
- : 'return await tools[hits[0].name]({ /* arguments matching hits[0].parameters */ })');
370
+ ? 'await tools[hits[0].name]({ /* args from hits[0].parameters */ })'
371
+ : 'return await tools[hits[0].name]({ /* args from hits[0].parameters */ })');
375
372
  lines.push('```');
376
373
  } else {
377
374
  lines.push('### Masked tools');
378
375
  lines.push('');
379
- lines.push('No masked tools are connected right now. If an MCP server or an out-of-preset plugin contributes one later, it appears here automatically and is reachable the same way.');
376
+ lines.push('No masked tools are connected right now. One that appears later shows up here automatically and is reachable the same way.');
380
377
  }
381
378
  lines.push('');
382
- lines.push('### Discovery API (all callable from inside a program)');
379
+ lines.push('### Discovery API');
383
380
  lines.push('');
384
- lines.push(`- \`tools.${listTool}({ namespace? })\` — every callable tool as \`{ name, description, namespace, hidden }\`, masked ones included.`);
385
- lines.push(`- \`tools.${searchTool}({ query, limit?, namespace? })\` — ranked matches with their full parameter schemas; this is the intended first step.`);
386
- lines.push(`- \`tools.${describeTool}({ name })\` — one tool's description and complete parameter schema.`);
381
+ lines.push(`- \`tools.${listTool}({ namespace? })\` — every callable tool, masked ones included: \`{ name, description, namespace, hidden }\`.`);
382
+ lines.push(`- \`tools.${searchTool}({ query, limit?, namespace? })\` — ranked matches with full parameter schemas; the intended first step.`);
383
+ lines.push(`- \`tools.${describeTool}({ name })\` — one tool's description and full parameter schema.`);
387
384
  if (metaTools.length > 3) {
388
- lines.push(`- \`tools.${metaTools[3]}({ limit? })\` — what Code Mode masked out of this session's request surface, for troubleshooting.`);
385
+ lines.push(`- \`tools.${metaTools[3]}({ limit? })\` — what Code Mode masked out of this session, for troubleshooting.`);
389
386
  }
390
387
  lines.push('');
391
388
  lines.push('### Hard rules');
392
389
  lines.push('');
393
- lines.push(`- Never guess a masked tool's name or arguments. Call \`${searchTool}\` first, read \`parameters\`, then call it inside the same or a later \`${runToolName}\` program.`);
394
- lines.push('- A direct call to a masked tool — one that does not come from inside a program — is rejected by the harness.');
395
- lines.push(`- The discovery tools are themselves only callable from inside \`${runToolName}\`; they are not part of your tool list.`);
390
+ lines.push(`- Never guess a masked tool's name or arguments: call \`${searchTool}\` first, read \`parameters\`, then call it inside a \`${runToolName}\` program.`);
391
+ lines.push('- A direct call to a masked tool from outside a program is rejected by the harness.');
392
+ lines.push(`- The discovery tools are only callable from inside \`${runToolName}\`; they are not in your tool list.`);
396
393
  return lines.join('\n');
397
394
  }
@@ -130,11 +130,11 @@ function codeParameter(programFormat) {
130
130
  return programFormat === 'repl'
131
131
  ? {
132
132
  type: 'string',
133
- description: 'The program to execute: a TypeScript REPL program. Top-level declarations, `await`, and a final expression are supported; a top-level `return` is not.',
133
+ description: 'A TypeScript REPL program: top-level declarations, `await`, and a final expression; no top-level `return`.',
134
134
  }
135
135
  : {
136
136
  type: 'string',
137
- description: 'The BODY of an async TypeScript function: erasable syntax only, with top-level `await` and `return` supported.',
137
+ description: 'The body of an async TypeScript function: erasable syntax, top-level `await` and `return` work.',
138
138
  };
139
139
  }
140
140
 
@@ -153,12 +153,12 @@ export function parameterSchema(runtime) {
153
153
  code: codeParameter(runtime?.programFormat),
154
154
  description: {
155
155
  type: 'string',
156
- description: 'Clear, concise description of what this program does, 5-10 words (shown in the UI).',
156
+ description: '5-10 words on what this program does (shown in the UI).',
157
157
  },
158
158
  ...timeout === undefined ? {} : {
159
159
  timeoutMs: {
160
160
  type: 'number',
161
- description: `Positive elapsed-time budget in milliseconds, including nested tool and approval waits. Default ${timeout.defaultMs}; capped at ${timeout.maxMs}.`,
161
+ description: `Positive millisecond budget for the whole program, nested waits included. Default ${timeout.defaultMs}; capped at ${timeout.maxMs}.`,
162
162
  },
163
163
  },
164
164
  },
@@ -197,11 +197,9 @@ export function createTransportTool(ctx, options, hooks = {}) {
197
197
  const definition = {
198
198
  name: runToolName,
199
199
  description:
200
- `Execute a TypeScript program against this session's tools. Takes two required arguments: \`code\` and `
201
- + '`description`. Call tools as `await tools.name(args)` — quoted access for exotic names: `tools["my-tool"](args)`. '
202
- + 'A failed tool call rejects with `ToolCallError`, whose `toolName` identifies the tool and whose `message` is '
203
- + 'human-readable. Only what the program prints or returns becomes program output; other intermediate results stay '
204
- + 'out of the conversation.',
200
+ `Execute a TypeScript program against this session's tools. Call tools as \`await tools.name(args)\`, or `
201
+ + '`tools["exotic-name"](args)` for names a dot cannot carry. A failed call rejects with `ToolCallError` '
202
+ + '(`toolName`, human-readable `message`). Only returned or printed values become program output.',
205
203
  output: { schema: OUTPUT_SCHEMA, render: (_args, value) => renderJson(value) },
206
204
  // Programs mutate state and are ordered as a unit, so they never overlap
207
205
  // with a sibling call in the same model step.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-lean-router",
3
- "version": "2.0.0",
3
+ "version": "2.1.1",
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",
@@ -0,0 +1,212 @@
1
+ // test/output-slim.test.mjs —— 机制 5:保守工具输出压缩(纯函数判据与 marker)
2
+ //
3
+ // 样本与期望串全部手写:期望值不从实现反算,只从「哪些行该保留、哪些该折叠」推出来。
4
+ import test from 'node:test';
5
+ import assert from 'node:assert/strict';
6
+
7
+ import {
8
+ COLLAPSE_MIN_LINES,
9
+ SLIM_THRESHOLD_CHARS,
10
+ slimContentBlocks,
11
+ slimToolOutput,
12
+ } from '../lib/lean/output-slim.js';
13
+
14
+ /** 60 字符的重复行:折叠收益远大于 marker 自身长度。 */
15
+ const RULE = 'a'.repeat(60);
16
+ /** 默认阈值下不会被改写的短输出:连 3 行相同也不折叠(阈值优先)。 */
17
+ const SMALL = 'line one\nline two\nline two\nline two\n';
18
+ /** 10 行相同 + 首尾两行:625 字符。 */
19
+ const REPEATED = ['first line', ...Array(10).fill(RULE), 'done'].join('\n');
20
+ /**
21
+ * 手写期望:保留第一行 + 折叠 marker(10 - 1 = 9 行)+ 结尾节省字符数 marker。
22
+ * 节省 = 10 行原文(600 字符 + 9 个换行 = 609) - (1 行 60 字符 + 1 换行 + 33 字符 marker)= 515。
23
+ */
24
+ const REPEATED_EXPECTED = 'first line\n' + RULE
25
+ + '\n[... 9 identical lines collapsed]\ndone\n[... output compacted: 515 chars saved ...]';
26
+
27
+ test('未超过阈值时原样返回:短输出一个字都不改', () => {
28
+ assert.equal(SLIM_THRESHOLD_CHARS, 2000);
29
+ assert.equal(COLLAPSE_MIN_LINES, 3);
30
+ assert.equal(slimToolOutput(SMALL), SMALL, '短输出里的 3 连相同行也不折叠');
31
+ assert.equal(slimToolOutput('x'.repeat(2000)), 'x'.repeat(2000), '正好等于阈值不启用');
32
+ assert.equal(slimToolOutput('x'), 'x');
33
+ });
34
+
35
+ test('超过阈值:10 行连续相同 → 保留一行 + 折叠 marker + 节省字符数 marker', () => {
36
+ const out = slimToolOutput(REPEATED, { thresholdChars: 100 });
37
+ assert.equal(out, REPEATED_EXPECTED);
38
+ assert.match(out, /\[\.\.\. 9 identical lines collapsed\]/, 'marker 文本按约定');
39
+ assert.match(out, /\[\.\.\. output compacted: 515 chars saved \.\.\.\]/, 'marker 报出节省的字符数');
40
+ assert.ok(REPEATED.length > out.length, '压缩前后字符数为正收益');
41
+ });
42
+
43
+ test('连续不足 3 行的重复不折叠', () => {
44
+ const twice = ['head', RULE, RULE, 'tail'].join('\n');
45
+ assert.equal(slimToolOutput(twice, { thresholdChars: 50 }), twice);
46
+ });
47
+
48
+ test('两段互不相邻的重复各自折叠、各带一个 marker', () => {
49
+ const twoRuns = [RULE, RULE, RULE, 'gap', RULE, RULE, RULE, 'tail'].join('\n');
50
+ const out = slimToolOutput(twoRuns, { thresholdChars: 50 });
51
+ assert.equal((out.match(/\[\.\.\. 2 identical lines collapsed\]/g) ?? []).length, 2);
52
+ assert.match(out, /gap/, '块之间的行保留');
53
+ assert.match(out, /tail/);
54
+ });
55
+
56
+ test('错误 / 异常 / 失败行永不折叠(连续 5 行也全部保留)', () => {
57
+ const failure = 'Error: ECONNREFUSED connect 127.0.0.1:5432 failed';
58
+ const mixed = [failure, failure, failure, failure, failure, 'pad', RULE, RULE, RULE, RULE, 'tail'].join('\n');
59
+ const out = slimToolOutput(mixed, { thresholdChars: 100 });
60
+ assert.equal((out.match(new RegExp(failure, 'g')) ?? []).length, 5, '5 行错误行一个不少');
61
+ assert.match(out, /\[\.\.\. 3 identical lines collapsed\]/, '同一份输出里的普通重复行仍然折叠');
62
+ assert.ok(out.length < mixed.length);
63
+ });
64
+
65
+ test('退出码 / traceback / 失败结论行同样受保护', () => {
66
+ const guarded = [
67
+ 'process exited with code 1',
68
+ 'Traceback (most recent call last):',
69
+ 'npm run build failed',
70
+ ];
71
+ const input = guarded.map((line) => Array(3).fill(line)).flat().join('\n');
72
+ assert.ok(input.length > 50);
73
+ assert.equal(slimToolOutput(input, { thresholdChars: 50 }), input, '全是受保护行时原样返回');
74
+ });
75
+
76
+ test('文件路径行永不折叠(Windows 与 POSIX 各 3 行全部保留)', () => {
77
+ const winPath = 'C:\\repo\\src\\lib\\toolface\\executor.js';
78
+ const posixPath = '/home/user/project/src/main.ts';
79
+ const input = [winPath, winPath, winPath, posixPath, posixPath, posixPath, RULE, RULE, RULE].join('\n');
80
+ const out = slimToolOutput(input, { thresholdChars: 50 });
81
+ assert.equal(out.split(winPath).length - 1, 3, 'Windows 路径全保留');
82
+ assert.equal(out.split(posixPath).length - 1, 3, 'POSIX 路径全保留');
83
+ assert.match(out, /\[\.\.\. 2 identical lines collapsed\]/, '普通重复行照常折叠');
84
+ });
85
+
86
+ test('非字符串与空串安全返回原值', () => {
87
+ assert.equal(slimToolOutput(undefined), undefined);
88
+ assert.equal(slimToolOutput(null), null);
89
+ assert.equal(slimToolOutput(42), 42);
90
+ assert.equal(slimToolOutput(''), '');
91
+ });
92
+
93
+ test('slimContentBlocks 只改 text 块、保留其余字段与未变化块的引用', () => {
94
+ const untouched = [{ type: 'image', source: { data: 'x' } }, { type: 'text', text: 'short' }];
95
+ assert.equal(slimContentBlocks(untouched), untouched, '无变化时返回原数组引用');
96
+
97
+ const blocks = [
98
+ { type: 'text', text: REPEATED, name: 'pwsh' },
99
+ { type: 'text', text: 'tail' },
100
+ ];
101
+ const slimmed = slimContentBlocks(blocks, { thresholdChars: 100 });
102
+ assert.notEqual(slimmed, blocks);
103
+ assert.equal(slimmed[0].text, REPEATED_EXPECTED);
104
+ assert.equal(slimmed[0].name, 'pwsh', '同一 block 的其他字段保留');
105
+ assert.equal(slimmed[1], blocks[1], '未变化的块保持原引用');
106
+ });
107
+
108
+ // ===== JSON 文档:GT-17「不改 JSON 结构」=====
109
+ // code_run 的 content 恒为 JSON 文本(transport.renderJson),所以 JSON 路径绝不能按行
110
+ // 折叠顶层,只能递归压缩字符串值内部:键、数组长度、类型必须一个不差。
111
+
112
+ /** 一份 JSON 字符串值内部可折叠的重复块:40 行 × 60 字符。 */
113
+ const REPEATED_LINES = Array(40).fill(RULE).join('\n');
114
+
115
+ test('code_run 风格 JSON:只有字符串值内部折叠,JSON 结构 / 键 / 数组长度 / 类型不变', () => {
116
+ const json = JSON.stringify({
117
+ logs: [REPEATED_LINES, 'Error: boom failed'],
118
+ result: { ok: true, count: 3 },
119
+ }, null, 2);
120
+
121
+ const out = slimToolOutput(json);
122
+ const parsed = JSON.parse(out); // 不是合法 JSON 时这里就抛错
123
+
124
+ assert.deepEqual(Object.keys(parsed), ['logs', 'result'], '键与顺序不变');
125
+ assert.equal(parsed.logs.length, 2, '没有相邻重复元素时数组长度不变');
126
+ assert.equal(parsed.logs[1], 'Error: boom failed', 'logs 内的错误行保留');
127
+ assert.equal(typeof parsed.logs[0], 'string');
128
+ assert.match(parsed.logs[0], /\[\.\.\. 39 identical lines collapsed\]/, 'marker 是字符串内容');
129
+ assert.equal(typeof parsed.result.ok, 'boolean');
130
+ assert.equal(parsed.result.count, 3, '数字类型与值不变');
131
+ assert.ok(out.length < json.length, '压缩后确实更短');
132
+
133
+ const bareMarker = out.split('\n').some((line) => /^\s*\[\.\.\. .*\]\s*$/.test(line));
134
+ assert.equal(bareMarker, false, '顶层不出现裸 marker 行(marker 只能在字符串内)');
135
+ });
136
+
137
+ test('嵌套数组 / 对象里的长字符串同样只压缩内部,容器形状不变', () => {
138
+ const json = JSON.stringify({ a: [{ b: REPEATED_LINES }], c: [[REPEATED_LINES]] }, null, 2);
139
+ const parsed = JSON.parse(slimToolOutput(json));
140
+ assert.equal(parsed.a.length, 1);
141
+ assert.equal(Array.isArray(parsed.a[0]), false);
142
+ assert.match(parsed.a[0].b, /identical lines collapsed/);
143
+ assert.equal(parsed.c.length, 1);
144
+ assert.equal(parsed.c[0].length, 1, '二维数组内层长度不变');
145
+ assert.match(parsed.c[0][0], /identical lines collapsed/);
146
+ });
147
+
148
+ test('JSON 里全是受保护行时不折叠,原文逐字返回', () => {
149
+ const errors = Array(40).fill('Error: boom failed').join('\n');
150
+ const json = JSON.stringify({ logs: errors }, null, 2);
151
+ assert.equal(slimToolOutput(json), json, '没有任何可折叠字符串时原样返回(不重排格式)');
152
+ });
153
+
154
+ test('没有可压缩字符串的 JSON 原样返回:不改缩进、不重排', () => {
155
+ const json = JSON.stringify({ note: 'x'.repeat(2100), n: 1 }); // 单行 JSON,超过阈值
156
+ assert.equal(slimToolOutput(json), json);
157
+ });
158
+
159
+ test('含超长整数 token 的 JSON 完全不碰(避免 JSON.parse 的精度损失)', () => {
160
+ const json = JSON.stringify({ big: 9223372036854775807, logs: [REPEATED_LINES] }, null, 2);
161
+ assert.equal(slimToolOutput(json), json);
162
+ });
163
+
164
+ // ===== 真实 code_run 形状:logs 是 string[],重复日志是数组里多个相同元素 =====
165
+
166
+ /** 一条普通日志:60 条相同元素就是当前设计的零压缩反例。 */
167
+ const LOG_LINE = '[dsh] polling workspace/index: no changes';
168
+ /** 一条错误日志:受保护,永不折叠。 */
169
+ const ERROR_LOG = 'Error: ECONNREFUSED 127.0.0.1:5432';
170
+
171
+ test('60 条相同 log:折叠为「一条 + marker 元素」,显著变短且仍是合法 JSON', () => {
172
+ const json = JSON.stringify({ logs: Array(60).fill(LOG_LINE), result: { ok: true } }, null, 2);
173
+ const out = slimToolOutput(json);
174
+ const parsed = JSON.parse(out);
175
+
176
+ assert.deepEqual(parsed.logs, [LOG_LINE, '[... 59 identical lines collapsed]'], '保留第一条 + marker 元素');
177
+ assert.deepEqual(Object.keys(parsed), ['logs', 'result'], '键不变');
178
+ assert.equal(parsed.result.ok, true, '类型不变');
179
+ assert.ok(out.length < json.length / 2, '显著变短(至少减半)');
180
+ assert.equal(out.split('\n').some((line) => /^\s*\[\.\.\. .*\]\s*$/.test(line)), false, '顶层无裸 marker 行');
181
+ });
182
+
183
+ test('重复的错误行元素永不折叠,普通重复日志照常折叠', () => {
184
+ const logs = [ERROR_LOG, ERROR_LOG, ERROR_LOG, ...Array(60).fill(LOG_LINE)];
185
+ const json = JSON.stringify({ logs }, null, 2);
186
+ const parsed = JSON.parse(slimToolOutput(json));
187
+
188
+ assert.equal(parsed.logs.filter((line) => line === ERROR_LOG).length, 3, '错误行元素一个不少');
189
+ assert.equal(parsed.logs.filter((line) => line === LOG_LINE).length, 1, '普通重复折叠为一条');
190
+ assert.ok(parsed.logs.includes('[... 59 identical lines collapsed]'), 'marker 元素存在');
191
+ assert.equal(parsed.logs.length, 5);
192
+ });
193
+
194
+ test('非重复的字符串数组原样返回(不重排、不改缩进)', () => {
195
+ const logs = Array.from({ length: 60 }, (_, index) => `log line ${index}`);
196
+ const json = JSON.stringify({ logs }, null, 2);
197
+ assert.equal(slimToolOutput(json), json);
198
+ });
199
+
200
+ test('只有 2 个相邻相同元素时不折叠(N >= 2 才折叠)', () => {
201
+ const logs = [LOG_LINE, LOG_LINE, ...Array.from({ length: 40 }, (_, index) => `unique line ${index}`)];
202
+ const json = JSON.stringify({ logs, note: 'y'.repeat(2100) }, null, 2);
203
+ const parsed = JSON.parse(slimToolOutput(json));
204
+ assert.equal(parsed.logs.length, 42, '数组长度保持');
205
+ assert.equal(parsed.logs.filter((line) => line === LOG_LINE).length, 2);
206
+ assert.equal(parsed.logs.some((line) => line.includes('collapsed')), false);
207
+ });
208
+
209
+ test('数组里的非字符串元素不参与折叠', () => {
210
+ const json = JSON.stringify({ items: [1, 1, 1, { a: 1 }, { a: 1 }], note: 'z'.repeat(2100) }, null, 2);
211
+ assert.equal(slimToolOutput(json), json);
212
+ });