dsh-lean-router 2.1.0 → 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.
@@ -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
+ });
@@ -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, 8, "8 个顶层操作");
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
  });
@@ -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
+ });
@@ -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: { type: 'object', properties: {} },
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 full parameter schemas for ranked hits', async () => {
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].parameters, { type: 'object', properties: {} });
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; }
@@ -148,6 +148,23 @@ 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\]\.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');
166
+ });
167
+
151
168
  test('buildCodemodeSectionText degrades cleanly with nothing hidden', () => {
152
169
  const text = buildCodemodeSectionText({});
153
170
  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
+ });