dsh-lean-router 2.1.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.
@@ -1,6 +1,18 @@
1
1
  # Changelog
2
2
 
3
- > English version of [changelog.md](./changelog.md). Versions follow package.json (currently 2.1.0).
3
+ > English version of [changelog.md](./changelog.md). Versions follow package.json (currently 2.1.1).
4
+
5
+ ## 2.1.1 (2026-11-29)
6
+
7
+ ### Improved
8
+
9
+ - **Static tool surface slimmed**: the `code_run` description drops from 459 to 298 characters and the SDK explanation from 2340 to 1738, for 3346 to 2526 in total (-24.5%). Required fields, enums, property names and the conditional `timeoutMs` semantics are all locked by new structural contract assertions, cutting roughly 820 characters of per-turn resident injection.
10
+ - **Conservative tool-output compaction**: new `lib/lean/output-slim.js`, wired into `lib/toolface/executor.js` by wrapping each visible definition's `finalizeContent` in place. Compaction only engages above 2000 characters: adjacent duplicate lines collapse, and adjacent duplicate elements of a string array collapse to the first element plus one marker element. Error, exception, failure, exit-code, path and conclusion lines are never folded. JSON output stays parseable with unchanged keys and types, only the model-visible content changes, the program-visible value never does, and any pre-existing `finalizeContent` is chained rather than replaced.
11
+
12
+ ### Notes
13
+
14
+ - Both changes are static or output-side; real gains need a restart to be observed inside the host, and no device verification has been done yet.
15
+ - Compaction pays off on repetitive log output (example: 3788 to 172 characters) and is a no-op for output without repetition.
4
16
 
5
17
  ## 2.1.0 (2026-11-29)
6
18
 
package/docs/changelog.md CHANGED
@@ -1,6 +1,18 @@
1
1
  # 变更记录(changelog)
2
2
 
3
- > 中文为主,英文版:[changelog.en.md](./changelog.en.md)。版本号遵循 package.json(当前 2.1.0)。
3
+ > 中文为主,英文版:[changelog.en.md](./changelog.en.md)。版本号遵循 package.json(当前 2.1.1)。
4
+
5
+ ## 2.1.1 (2026-11-29)
6
+
7
+ ### 优化
8
+
9
+ - **静态工具面瘦身**:`code_run` 的 description 459→298 字符、SDK 说明 2340→1738,合计 3346→2526(-24.5%);required/enum/属性名与 `timeoutMs` 条件语义均由新增的结构契约断言锁定,每轮常驻注入因此减少约 820 字符。
10
+ - **工具输出保守压缩**:新增 `lib/lean/output-slim.js`,并在 `lib/toolface/executor.js` 的 `describe()` 里给每个可见工具就地包装 `finalizeContent`。压缩只在输出超过 2000 字符时启用:折叠相邻重复行,以及字符串数组里相邻重复元素(保留首个 + 一个 marker 元素);错误、异常、失败、退出码、路径与结论行永不折叠。JSON 输出保持可解析、键与类型不变,只改模型可见 content,不改程序内 value;原有 `finalizeContent` 会被串联而不是覆盖。
11
+
12
+ ### 说明
13
+
14
+ - 两项都是静态或输出侧的改动,真实收益需重启后在宿主里观察,尚未做真机验证。
15
+ - 输出压缩对重复日志类输出收益明显(示例 3788→172 字符),对无重复的输出不生效。
4
16
 
5
17
  ## 2.1.0 (2026-11-29)
6
18
 
@@ -0,0 +1,271 @@
1
+ // dsh-lean-router · lib/lean/output-slim.js —— 机制 5:工具输出的保守压缩(同步纯函数)
2
+ //
3
+ // 口径(ticket: context_output_compactor,GT-17「不改 JSON 结构」):
4
+ // - 只在文本超过阈值时启用,小输出一个字都不改;
5
+ // - 普通文本:只折叠「连续 >= 3 行完全相同」的块,保留一行并紧跟一行 marker;
6
+ // - 可 JSON.parse 的文本(code_run 的 content 恒为 JSON 文本):绝不按行折叠顶层。
7
+ // 改为两条保持结构的压缩:
8
+ // a) 字符串值内部做相邻重复行折叠(marker 作为字符串内容);
9
+ // b) 字符串数组折叠相邻相同元素——保留第一个,后面连续相同的 N 个(N >= 2)
10
+ // 替换为一个 marker 字符串,数组长度因此变短(预期行为)。
11
+ // 键与类型不变,再 JSON.stringify 输出;若 stringify 后不比原文短则返回原文;
12
+ // - 错误 / 异常 / 失败 / 退出码 / 文件路径 / 结论行永不折叠、永不删除(两种路径同判据);
13
+ // - 不做结构化摘要、不改值、不重排键。
14
+ //
15
+ // 与 lib/lean/pruner.js 的关系:pruner 按头 / 中 / 尾裁掉中段(宿主 pruner 的纯函数端口),
16
+ // 本模块只做「相邻重复行」的局部折叠,判据更保守,二者互不替代。
17
+ //
18
+ // 零依赖、同步、纯函数:不读会话、不碰 Cordis 上下文,可脱离宿主单测。
19
+ // 注意:本模块只产出「模型可见文本」,值的处理在其调用方(lib/toolface/executor.js)。
20
+
21
+ /** 启用压缩的最小文本长度(严格大于该值才启用,等于阈值不启用)。 */
22
+ export const SLIM_THRESHOLD_CHARS = 2000;
23
+
24
+ /** 连续相同行达到该数量才折叠;2 行重复保持原样。 */
25
+ export const COLLAPSE_MIN_LINES = 3;
26
+
27
+ /** 单次折叠的 marker 原文({collapsed} 为被折叠掉的行数,即 run 长度 - 1)。 */
28
+ export const COLLAPSE_MARKER = '[... {collapsed} identical lines collapsed]';
29
+
30
+ /** 压缩收益 marker 原文({saved} 为折叠本身节省的字符数,不含本 marker)。 */
31
+ export const SAVED_MARKER = '[... output compacted: {saved} chars saved ...]';
32
+
33
+ /**
34
+ * 受保护行的判据。任何命中一项的行都不折叠——宁可少折叠,也不把结论行吃掉。
35
+ * 覆盖:错误 / 异常 / 失败 / 退出码(含中文口径)、结论行、文件路径。
36
+ */
37
+ const PROTECTED_PATTERNS = [
38
+ // 错误 / 异常 / 失败 / 致命(含 stderr、非零退出等常见措辞)
39
+ /\b(?:error|errors|exception|exceptions|failed|failure|failures|fatal|panic|traceback|throw|throws|threw|stderr|denied|refused)\b/i,
40
+ // 退出码 / 退出状态
41
+ /\b(?:exit\s*(?:code|status))\b/i,
42
+ /\b(?:exited\s+with|non-?zero)\b/i,
43
+ // 中文口径的错误与结论
44
+ /(?:错误|异常|失败|退出码|结论|总结|原因|无法|抛出)/,
45
+ // 结论行:整行以结论词开头(大小写不敏感)
46
+ /^\s*(?:summary|conclusion|result|verdict|totals?)\b/i,
47
+ // 文件路径:盘符、UNC、POSIX 绝对路径、./ ../ 相对路径
48
+ /(?:^|[\s"'(<[=:])(?:[A-Za-z]:[\\/]|\\\\|\/|\.{1,2}\/)/,
49
+ // 文件路径:带已知扩展名的文件名
50
+ /(?:^|[\s"'(<[=:])[\w.@~+-]+\.(?:[cm]?[jt]sx?|jsonc?|py|rb|go|rs|java|kt|c|h|cc|cpp|hpp|cs|php|sh|bash|zsh|ps1|cmd|bat|md|markdown|txt|log|ya?ml|toml|ini|cfg|conf|xml|html?|css|scss|sql|db|lock|env|patch|diff)\b/i,
51
+ ];
52
+
53
+ /**
54
+ * 裸大整数 token(16 位以上):`JSON.parse` 会丢精度,遇到这类文档完全不碰,
55
+ * 宁可放弃这次压缩也不改写用户数据。
56
+ */
57
+ const BIG_INTEGER_TOKEN = /(?:^|[\s:,[{])-?\d{16,}(?=[\s,\]}]|$)/;
58
+
59
+ /** 解析阈值:非正数 / 非数字回落到默认值。 */
60
+ function resolveThreshold(options) {
61
+ const value = options?.thresholdChars;
62
+ return Number.isFinite(value) && value > 0 ? Math.floor(value) : SLIM_THRESHOLD_CHARS;
63
+ }
64
+
65
+ /** 该行是否必须原样保留。 */
66
+ export function isProtectedLine(line) {
67
+ return typeof line === 'string' && PROTECTED_PATTERNS.some((pattern) => pattern.test(line));
68
+ }
69
+
70
+ /** 折叠结果的可读 marker。 */
71
+ function collapseMarker(collapsed) {
72
+ return COLLAPSE_MARKER.replace('{collapsed}', String(collapsed));
73
+ }
74
+
75
+ /** 收益 marker。 */
76
+ function savedMarker(saved) {
77
+ return SAVED_MARKER.replace('{saved}', String(saved));
78
+ }
79
+
80
+ /**
81
+ * 按行折叠相邻重复块(不设阈值门、不加收益 marker):普通文本与 JSON 字符串值共用。
82
+ *
83
+ * @param text - 待折叠文本。
84
+ * @returns `{ eol, body, collapsedLines }`:换行风格、折叠正文、被折叠掉的总行数。
85
+ */
86
+ function foldLines(text) {
87
+ const eol = text.includes('\r\n') ? '\r\n' : '\n';
88
+ const lines = text.split(/\r?\n/);
89
+ const kept = [];
90
+ let collapsedLines = 0;
91
+
92
+ for (let index = 0; index < lines.length;) {
93
+ const line = lines[index];
94
+ let end = index + 1;
95
+ while (end < lines.length && lines[end] === line) end += 1;
96
+ const runLength = end - index;
97
+ // 受保护的行整段保留:连续相同的错误行也是每条都有信息。
98
+ if (runLength >= COLLAPSE_MIN_LINES && !isProtectedLine(line)) {
99
+ const collapsed = runLength - 1;
100
+ kept.push(line);
101
+ kept.push(collapseMarker(collapsed));
102
+ collapsedLines += collapsed;
103
+ } else {
104
+ for (let offset = index; offset < end; offset += 1) kept.push(line);
105
+ }
106
+ index = end;
107
+ }
108
+
109
+ return { eol, body: kept.join(eol), collapsedLines };
110
+ }
111
+
112
+ /**
113
+ * 折叠一段普通文本并在末尾补收益 marker;不值得改时返回原值。
114
+ * @param text - 已确认超过阈值的文本。
115
+ * @returns 折叠后的文本,或原值。
116
+ */
117
+ function slimPlainText(text) {
118
+ const folded = foldLines(text);
119
+ if (folded.collapsedLines === 0) return text;
120
+ const savedChars = text.length - folded.body.length;
121
+ // 负收益(折叠 marker 比省下的内容还长)就不动原文。
122
+ if (savedChars <= 0) return text;
123
+ return folded.body + folded.eol + savedMarker(savedChars);
124
+ }
125
+
126
+ /**
127
+ * 压缩 JSON 文档里的一个字符串值:只在字符串内部折叠相邻重复行。
128
+ * 未超过阈值的字符串(短值)不碰。
129
+ */
130
+ function slimJsonString(value, threshold) {
131
+ if (value.length <= threshold) return value;
132
+ const folded = foldLines(value);
133
+ if (folded.collapsedLines === 0) return value;
134
+ const savedChars = value.length - folded.body.length;
135
+ if (savedChars <= 0) return value;
136
+ return folded.body + folded.eol + savedMarker(savedChars);
137
+ }
138
+
139
+ /**
140
+ * 折叠字符串数组里相邻相同的元素:保留第一个,后面连续相同的 N 个(N >= 2)
141
+ * 替换成一个 marker 字符串。错误 / 路径 / 结论行元素永不折叠。
142
+ * 非字符串元素不参与折叠(类型与顺序都保持)。
143
+ *
144
+ * @param items - 已递归处理过的数组元素。
145
+ * @returns `{ items, collapsed }`:折叠后的数组与被折叠掉的元素总数。
146
+ */
147
+ function foldStringRuns(items) {
148
+ const kept = [];
149
+ let collapsed = 0;
150
+ for (let index = 0; index < items.length;) {
151
+ const item = items[index];
152
+ let end = index + 1;
153
+ if (typeof item === 'string') {
154
+ while (end < items.length && items[end] === item) end += 1;
155
+ }
156
+ const runLength = end - index;
157
+ // 保留首个,其余至少 2 个才折叠(单个 marker 才比被折叠的元素更短)。
158
+ if (typeof item === 'string' && runLength >= COLLAPSE_MIN_LINES && !isProtectedLine(item)) {
159
+ kept.push(item);
160
+ kept.push(collapseMarker(runLength - 1));
161
+ collapsed += runLength - 1;
162
+ } else {
163
+ for (let offset = index; offset < end; offset += 1) kept.push(items[offset]);
164
+ }
165
+ index = end;
166
+ }
167
+ return { items: kept, collapsed };
168
+ }
169
+
170
+ /**
171
+ * 递归压缩 JSON 值:字符串值内部折叠,字符串数组折叠相邻相同元素;键与类型不变。
172
+ * 数组长度可能变短(只在字符串数组的重复段上),这是预期行为。
173
+ * @returns `{ value, changed }`;`changed` 为 false 时 `value` 与入参结构等价。
174
+ */
175
+ function compactJsonStrings(node, threshold) {
176
+ let changed = false;
177
+ const walk = (current) => {
178
+ if (typeof current === 'string') {
179
+ const slimmed = slimJsonString(current, threshold);
180
+ if (slimmed === current) return current;
181
+ changed = true;
182
+ return slimmed;
183
+ }
184
+ if (Array.isArray(current)) {
185
+ const mapped = current.map(walk);
186
+ const folded = foldStringRuns(mapped);
187
+ if (folded.collapsed > 0) changed = true;
188
+ return folded.collapsed > 0 ? folded.items : mapped;
189
+ }
190
+ if (current !== null && typeof current === 'object') {
191
+ // Object.fromEntries 走 CreateDataProperty,`__proto__` 这类键不会被改写。
192
+ return Object.fromEntries(Object.entries(current).map(([key, child]) => [key, walk(child)]));
193
+ }
194
+ return current;
195
+ };
196
+ const value = walk(node);
197
+ return { value, changed };
198
+ }
199
+
200
+ /**
201
+ * JSON 文档路径:只压缩字符串值内部,结构不动。
202
+ *
203
+ * @param text - 已确认超过阈值的文本。
204
+ * @param threshold - 单字符串值启用折叠的长度阈值。
205
+ * @returns 压缩后的 JSON 文本;不是 JSON、无可压缩字符串、或 stringify 后不更短时返回原文。
206
+ */
207
+ function slimJsonDocument(text, threshold) {
208
+ const trimmed = text.trim();
209
+ if (!trimmed.startsWith('{') && !trimmed.startsWith('[')) return undefined;
210
+ if (BIG_INTEGER_TOKEN.test(text)) return text;
211
+ let parsed;
212
+ try {
213
+ parsed = JSON.parse(text);
214
+ } catch {
215
+ return undefined;
216
+ }
217
+ if (parsed === null || typeof parsed !== 'object') return undefined;
218
+ const { value, changed } = compactJsonStrings(parsed, threshold);
219
+ if (!changed) return text;
220
+ // 与 code_run 的 renderJson 同形(2 空格缩进),保证模型读到的排版一致。
221
+ const rendered = JSON.stringify(value, null, 2);
222
+ return rendered.length < text.length ? rendered : text;
223
+ }
224
+
225
+ /**
226
+ * 保守压缩一段模型可见文本。
227
+ *
228
+ * - 非字符串或空串:原样返回;
229
+ * - 未超过阈值:原样返回;
230
+ * - JSON 文本:递归压缩字符串值内部,并折叠字符串数组里相邻相同的元素(数组长度可变短),
231
+ * 键与类型不变;不短则原样返回;
232
+ * - 普通文本:行级折叠相邻重复块,受保护行不折叠。
233
+ *
234
+ * @param text - 待压缩文本。
235
+ * @param options - `thresholdChars` 覆盖阈值(仅供测试 / 预检)。
236
+ * @returns 压缩后的文本;任何情况下都不比原文长(JSON 路径保证),不需要压缩时返回原值。
237
+ */
238
+ export function slimToolOutput(text, options) {
239
+ if (typeof text !== 'string' || text.length === 0) return text;
240
+ const threshold = resolveThreshold(options);
241
+ if (text.length <= threshold) return text;
242
+
243
+ const json = slimJsonDocument(text, threshold);
244
+ if (json !== undefined) return json;
245
+
246
+ return slimPlainText(text);
247
+ }
248
+
249
+ /**
250
+ * 压缩一条 content 数组里的文本块。
251
+ *
252
+ * 只改 `type === 'text'` 且 `text` 是字符串的块,块上的其他字段原样保留;
253
+ * 非 text 块(图片等)与整段无变化时返回**原数组引用**,让调用方可以据此判断是否改动。
254
+ *
255
+ * @param blocks - 工具结果的内容块;非数组原样返回。
256
+ * @param options - 透传给 {@link slimToolOutput}。
257
+ * @returns 压缩后的数组,或未发生变化时的原数组。
258
+ */
259
+ export function slimContentBlocks(blocks, options) {
260
+ if (!Array.isArray(blocks)) return blocks;
261
+ let changed = false;
262
+ const next = blocks.map((block) => {
263
+ if (block === null || typeof block !== 'object') return block;
264
+ if (block.type !== 'text' || typeof block.text !== 'string') return block;
265
+ const slimmed = slimToolOutput(block.text, options);
266
+ if (slimmed === block.text) return block;
267
+ changed = true;
268
+ return { ...block, text: slimmed };
269
+ });
270
+ return changed ? next : blocks;
271
+ }
@@ -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.1.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",
@@ -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
+ });
@@ -205,3 +205,98 @@ test('a caller-provided native module builds the delegate through it', () => {
205
205
  executor.describe([{ name: 'pwsh' }]);
206
206
  assert.deepEqual(constructed, [ctx], 'one delegate instance is built on the provided module');
207
207
  });
208
+
209
+ // ===== 输出压缩(conservative output compaction)=====
210
+
211
+ /** 40 行相同、每行 60 字符 = 2439 字符,超过默认 2000 阈值。 */
212
+ const SLIM_RULE = 'a'.repeat(60);
213
+ const LONG_OUTPUT = Array(40).fill(SLIM_RULE).join('\n');
214
+
215
+ /** 定义一个工具,可选地带上原 finalizeContent。 */
216
+ function definitionWith(finalizeContent) {
217
+ const definition = { name: 'pwsh', description: 'd', parameters: {} };
218
+ if (finalizeContent !== undefined) definition.finalizeContent = finalizeContent;
219
+ return definition;
220
+ }
221
+
222
+ /** describe 一遍,让 executor 用包装后的定义替换掉原 finalizeContent。 */
223
+ function described(definition) {
224
+ const executor = createCodemodeExecutor(EXEC_CTX, options, { createDelegate: fakeDelegate });
225
+ assert.deepEqual(executor.describe([definition]).schemas.map((schema) => schema.name), ['pwsh'], '包装不改变请求面');
226
+ return definition;
227
+ }
228
+
229
+ test('output compaction: the original finalizeContent still runs, its content is compacted, value untouched', () => {
230
+ const seen = [];
231
+ const definition = described(definitionWith(function (exec, result) {
232
+ seen.push({ callId: exec.callId, content: result.content });
233
+ return [{ type: 'text', text: LONG_OUTPUT }];
234
+ }));
235
+ const result = { isError: false, value: { ok: true }, content: [{ type: 'text', text: 'renderer' }] };
236
+
237
+ const content = definition.finalizeContent({ callId: 'c1' }, result);
238
+
239
+ assert.equal(seen.length, 1, '原实现被调用且只调用一次');
240
+ assert.equal(seen[0].callId, 'c1', 'exec 原样透传');
241
+ assert.equal(content.length, 1);
242
+ assert.ok(content[0].text.length < LONG_OUTPUT.length, 'content 被压缩');
243
+ assert.match(content[0].text, /\[\.\.\. 39 identical lines collapsed\]/);
244
+ assert.match(content[0].text, /chars saved \.\.\.\]/);
245
+ assert.deepEqual(result.value, { ok: true }, 'value 不被压缩器改写');
246
+ });
247
+
248
+ test('output compaction: a short content passes through as the very array the original returned', () => {
249
+ const original = [{ type: 'text', text: 'short output' }];
250
+ const definition = described(definitionWith(() => original));
251
+ const result = { isError: false, value: 1, content: [{ type: 'text', text: 'renderer' }] };
252
+ assert.equal(definition.finalizeContent({ callId: 'c1' }, result), original, '无变化时原样返回原实现的数组');
253
+ });
254
+
255
+ test('output compaction: an undefined original return keeps the renderer content and compacts that', () => {
256
+ const definition = described(definitionWith(() => undefined));
257
+ const result = { isError: false, value: 1, content: [{ type: 'text', text: LONG_OUTPUT }] };
258
+ const content = definition.finalizeContent({ callId: 'c1' }, result);
259
+ assert.ok(Array.isArray(content), 'undefined 表示「保留渲染器输出」,压缩后必须显式返回新 content');
260
+ assert.match(content[0].text, /\[\.\.\. 39 identical lines collapsed\]/);
261
+ assert.deepEqual(result.value, 1);
262
+ });
263
+
264
+ test('output compaction: a tool without finalizeContent is compacted too, and returns undefined when nothing changes', () => {
265
+ const definition = described(definitionWith(undefined));
266
+ const long = { isError: false, value: { n: 1 }, content: [{ type: 'text', text: LONG_OUTPUT }] };
267
+ const compacted = definition.finalizeContent({ callId: 'c1' }, long);
268
+ assert.equal(compacted.length, 1);
269
+ assert.match(compacted[0].text, /identical lines collapsed/);
270
+ assert.deepEqual(long.value, { n: 1 });
271
+
272
+ const short = { isError: false, value: { n: 1 }, content: [{ type: 'text', text: 'short' }] };
273
+ assert.equal(definition.finalizeContent({ callId: 'c1' }, short), undefined, '未变化时返回 undefined 保留原 content');
274
+ });
275
+
276
+ test('output compaction: an original finalizer that throws still throws (never swallowed)', () => {
277
+ const definition = described(definitionWith(() => { throw new Error('finalizer boom'); }));
278
+ assert.throws(() => definition.finalizeContent({ callId: 'c1' }, { content: [] }), /finalizer boom/);
279
+ });
280
+
281
+ test('output compaction: repeated describe() wraps once (idempotent)', () => {
282
+ let calls = 0;
283
+ const definition = definitionWith(() => { calls += 1; return [{ type: 'text', text: LONG_OUTPUT }]; });
284
+ const executor = createCodemodeExecutor(EXEC_CTX, options, { createDelegate: fakeDelegate });
285
+ executor.describe([definition]);
286
+ executor.describe([definition]);
287
+ const content = definition.finalizeContent({ callId: 'c1' }, { content: [] });
288
+ assert.equal(calls, 1, '原实现每次执行只调用一次');
289
+ assert.equal((content[0].text.match(/identical lines collapsed/g) ?? []).length, 1, 'marker 不叠加');
290
+ });
291
+
292
+ test('output compaction: non-text blocks and other block fields survive untouched', () => {
293
+ const blocks = [
294
+ { type: 'image', source: { type: 'base64', data: 'AAAA' } },
295
+ { type: 'text', text: LONG_OUTPUT, name: 'pwsh' },
296
+ ];
297
+ const definition = described(definitionWith(() => blocks));
298
+ const content = definition.finalizeContent({ callId: 'c1' }, { content: [] });
299
+ assert.equal(content[0], blocks[0], '图片块原引用');
300
+ assert.equal(content[1].name, 'pwsh', 'text 块的其他字段保留');
301
+ assert.ok(content[1].text.length < LONG_OUTPUT.length);
302
+ });
@@ -148,6 +148,21 @@ test('buildCodemodeSectionText documents discovery without leaking hidden names'
148
148
  assert.doesNotMatch(text, /mcp__fake__get_ticker/, 'no hidden tool’s own name leaks into the section');
149
149
  });
150
150
 
151
+ test('the section keeps the model-critical contract after the prose trim', () => {
152
+ const text = buildCodemodeSectionText({
153
+ runToolName: 'code_run',
154
+ metaTools: DEFAULT_META_TOOLS,
155
+ hidden: { total: 3, namespaces: [{ namespace: 'fake', count: 3, kind: 'mcp' }] },
156
+ searchLimit: 8,
157
+ programFormat: 'function-body',
158
+ });
159
+ assert.match(text, /reaches the conversation/, 'the output rule stays advertised');
160
+ assert.match(text, /is rejected by the harness/, 'the model-direct denial stays advertised');
161
+ assert.match(text, /only callable from inside/, 'discovery tools stay program-only');
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\]\.parameters/, 'the parameter lookup step stays in the example');
164
+ });
165
+
151
166
  test('buildCodemodeSectionText degrades cleanly with nothing hidden', () => {
152
167
  const text = buildCodemodeSectionText({});
153
168
  assert.match(text, /No masked tools are connected right now/);
@@ -238,6 +238,78 @@ test('the transport registers under code_run, never the reserved run_code', () =
238
238
  assert.equal(normalizeConfig({ runToolName: 'run_code' }).runToolName, 'run_code', 'config is normalized; the registry itself rejects the reserved name at register time');
239
239
  });
240
240
 
241
+ /**
242
+ * The machine-readable contract, read off the real schema *before* the prose
243
+ * trim: property names, required list, types, and the absence of enums. Prose
244
+ * is deliberately not frozen here — only what a caller's arguments must match.
245
+ */
246
+ const SCHEMA_SHAPE = {
247
+ type: 'object',
248
+ additionalProperties: false,
249
+ required: ['code', 'description'],
250
+ properties: {
251
+ code: { type: 'string' },
252
+ description: { type: 'string' },
253
+ timeoutMs: { type: 'number' },
254
+ },
255
+ };
256
+
257
+ /** Project a schema onto its machine-readable shape, refusing any enum. */
258
+ function shapeOf(schema) {
259
+ const properties = {};
260
+ for (const [name, property] of Object.entries(schema.properties ?? {})) {
261
+ assert.equal(Object.hasOwn(property, 'enum'), false, `${name} carries no enum, before or after the trim`);
262
+ assert.deepEqual(Object.keys(property).sort(), ['description', 'type'], `${name} exposes exactly a type and a description`);
263
+ properties[name] = { type: property.type };
264
+ }
265
+ return {
266
+ type: schema.type,
267
+ additionalProperties: schema.additionalProperties,
268
+ required: [...(schema.required ?? [])],
269
+ properties,
270
+ };
271
+ }
272
+
273
+ test('the parameter schema contract is frozen: names, required, types, no enums', () => {
274
+ const full = parameterSchema({ programFormat: 'function-body', timeout: { defaultMs: 120000, maxMs: 600000 } });
275
+ assert.deepEqual(shapeOf(full), SCHEMA_SHAPE);
276
+ // The runtime's numbers are semantic defaults, not decoration.
277
+ assert.match(full.properties.timeoutMs.description, /Default 120000/);
278
+ assert.match(full.properties.timeoutMs.description, /capped at 600000/);
279
+
280
+ const bare = parameterSchema({ programFormat: 'function-body' });
281
+ assert.deepEqual(shapeOf(bare), {
282
+ ...SCHEMA_SHAPE,
283
+ properties: { code: { type: 'string' }, description: { type: 'string' } },
284
+ }, 'no descriptor, no timeoutMs — and nothing else moves');
285
+
286
+ const repl = parameterSchema({ programFormat: 'repl' });
287
+ assert.deepEqual(Object.keys(repl.properties), ['code', 'description']);
288
+ assert.match(repl.properties.code.description, /REPL/);
289
+ });
290
+
291
+ test('the transport description keeps the constraints a program depends on', () => {
292
+ const { tool } = buildTransport();
293
+ const description = tool.description;
294
+ // Call convention, including the quoted form for names a dot cannot carry.
295
+ assert.match(description, /tools\.name\(args\)/);
296
+ assert.match(description, /tools\["[^"]+"\]\(args\)/, 'quoted access for names a dot cannot carry');
297
+ // Failure surface: the error class and the property that names the call.
298
+ assert.match(description, /ToolCallError/);
299
+ assert.match(description, /toolName/);
300
+ // Output rule: only returned or printed values leave the program.
301
+ assert.match(description, /program output/);
302
+ });
303
+
304
+ test('the transport definition keeps its registry-facing shape', () => {
305
+ const { tool } = buildTransport();
306
+ assert.equal(tool.name, 'code_run');
307
+ assert.equal(tool.isConcurrencySafe(), false, 'programs stay exclusive');
308
+ assert.equal(tool.output.schema.type, 'object');
309
+ assert.deepEqual(Object.keys(tool.parameters).sort(), ['additionalProperties', 'properties', 'required', 'type']);
310
+ assert.equal(tool.execute.length, 2);
311
+ });
312
+
241
313
  test('parameterSchema advertises timeoutMs only when the runtime reports a descriptor', () => {
242
314
  const plain = parameterSchema({ programFormat: 'function-body' });
243
315
  assert.deepEqual(Object.keys(plain.properties).sort(), ['code', 'description']);
@@ -254,3 +254,19 @@ test('the built bundle would keep base then frag order (in-memory concat, no wri
254
254
  assert.equal(topOps[0], '- insert:', 'the base preset row leads');
255
255
  assert.ok(topOps.some(l => l === '- id: preset-lean-router'), 'the frag override follows as a sibling op');
256
256
  });
257
+
258
+ test('output compaction is wired onto the visible code_run definition (content only, value untouched)', async () => {
259
+ const { describeFor } = await harness();
260
+ describeFor();
261
+ const transport = DEFINITIONS.get('code_run');
262
+ assert.equal(typeof transport.finalizeContent, 'function', 'code_run 的可见定义获得了 finalizeContent 包装');
263
+
264
+ const long = Array(40).fill('a'.repeat(60)).join('\n');
265
+ const value = { logs: ['same line', 'same line', 'same line'], result: 1 };
266
+ const result = { isError: false, value, content: [{ type: 'text', text: long }] };
267
+ const content = transport.finalizeContent({ callId: 'c1' }, result);
268
+
269
+ assert.match(content[0].text, /\[\.\.\. 39 identical lines collapsed\]/, 'code_run 的输出被保守压缩');
270
+ assert.equal(content[0].text.length < long.length, true);
271
+ assert.equal(result.value, value, 'value 原引用未动,程序内子调用 settled.value 不受影响');
272
+ });