dsh-lean-router 0.0.0-stage → 0.2.3

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.
Files changed (89) hide show
  1. package/LICENSE +21 -0
  2. package/NOTICE.md +23 -0
  3. package/README.en.md +73 -0
  4. package/README.md +72 -2
  5. package/cordis.patch.yml +870 -0
  6. package/docs/adr/0001-token-ledger-durable-usage.md +11 -0
  7. package/docs/agents/domain.md +38 -0
  8. package/docs/agents/issue-tracker.md +44 -0
  9. package/docs/agents/release.md +24 -0
  10. package/docs/agents/triage-labels.md +13 -0
  11. package/docs/agents/verification.md +32 -0
  12. package/docs/architecture.en.md +67 -0
  13. package/docs/architecture.md +66 -0
  14. package/docs/changelog.en.md +266 -0
  15. package/docs/changelog.md +269 -0
  16. package/docs/configuration.en.md +57 -0
  17. package/docs/configuration.md +57 -0
  18. package/docs/install.en.md +60 -0
  19. package/docs/install.md +60 -0
  20. package/docs/quickstart.en.md +75 -0
  21. package/docs/quickstart.md +75 -0
  22. package/docs/release-checklist.en.md +82 -0
  23. package/docs/release-checklist.md +131 -0
  24. package/docs//345/244/215/346/240/270-/345/205/263/346/217/222/344/273/266/346/270/205/345/215/225.md +108 -0
  25. package/docs//345/267/245/345/205/267/351/201/256/350/224/275-/346/216/245/347/272/277/350/257/264/346/230/216.md +140 -0
  26. package/docs//350/267/257/347/224/261-/350/256/276/350/256/241/350/257/264/346/230/216.md +104 -0
  27. package/lib/bands.js +149 -0
  28. package/lib/index.js +12 -0
  29. package/lib/lean/compaction.js +119 -0
  30. package/lib/lean/delivery-gate.js +312 -0
  31. package/lib/lean/disabled.js +61 -0
  32. package/lib/lean/history-budget.js +301 -0
  33. package/lib/lean/history-downgrade.js +345 -0
  34. package/lib/lean/index.js +19 -0
  35. package/lib/lean/output-slim.js +271 -0
  36. package/lib/lean/persona-text.js +111 -0
  37. package/lib/lean/plan-mode.js +31 -0
  38. package/lib/lean/pruner.js +75 -0
  39. package/lib/lean/tool-concurrency.js +319 -0
  40. package/lib/lean/usage-ledger.js +442 -0
  41. package/lib/router.js +287 -0
  42. package/lib/token-ledger/index.js +147 -0
  43. package/lib/token-ledger/live.js +193 -0
  44. package/lib/toolface/discovery.js +297 -0
  45. package/lib/toolface/executor.js +323 -0
  46. package/lib/toolface/index.js +242 -0
  47. package/lib/toolface/pool.js +160 -0
  48. package/lib/toolface/retention.js +187 -0
  49. package/lib/toolface/rules.js +395 -0
  50. package/lib/toolface/scope.js +188 -0
  51. package/lib/toolface/transport.js +335 -0
  52. package/package.json +65 -4
  53. package/presets/base/frag-lean.patch.yml +459 -0
  54. package/presets/base/frag-preset.patch.yml +274 -0
  55. package/presets/base/frag-router.patch.yml +17 -0
  56. package/presets/base/frag-toolface.patch.yml +73 -0
  57. package/presets/base/lean-router.patch.yml +44 -0
  58. package/scripts/build-bundle.mjs +45 -0
  59. package/scripts/doctor.mjs +35 -0
  60. package/scripts/install-profile.mjs +113 -0
  61. package/scripts/install.mjs +20 -0
  62. package/scripts/integrate-preset.mjs +107 -0
  63. package/scripts/release.mjs +145 -0
  64. package/scripts/verify.mjs +8 -0
  65. package/test/build.test.mjs +7 -0
  66. package/test/history-budget.test.mjs +210 -0
  67. package/test/history-downgrade.test.mjs +379 -0
  68. package/test/integration-preset.test.mjs +59 -0
  69. package/test/lean-compaction.test.mjs +47 -0
  70. package/test/lean-concurrency.test.mjs +117 -0
  71. package/test/lean-delivery-gate.test.mjs +75 -0
  72. package/test/lean-frag.test.mjs +132 -0
  73. package/test/lean-modules.test.mjs +112 -0
  74. package/test/lean-pruner.test.mjs +42 -0
  75. package/test/output-slim.test.mjs +212 -0
  76. package/test/package.test.mjs +20 -0
  77. package/test/patch-yaml.test.mjs +45 -0
  78. package/test/plugin-entry.test.mjs +26 -0
  79. package/test/router-bands.test.mjs +98 -0
  80. package/test/router.test.mjs +215 -0
  81. package/test/token-ledger-live.test.mjs +351 -0
  82. package/test/token-ledger.test.mjs +264 -0
  83. package/test/toolface-executor.test.mjs +302 -0
  84. package/test/toolface-mask.test.mjs +258 -0
  85. package/test/toolface-rules.test.mjs +177 -0
  86. package/test/toolface-runtime.test.mjs +466 -0
  87. package/test/toolface-wiring.test.mjs +272 -0
  88. package/test/usage-ledger-inject.test.mjs +50 -0
  89. package/test/usage-ledger.test.mjs +399 -0
@@ -0,0 +1,302 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+
4
+ import {
5
+ NESTED_MARK,
6
+ isNestedCall,
7
+ markNested,
8
+ createCodemodeExecutor,
9
+ loadNativeExecutorModule,
10
+ nativeDependencyMissingError,
11
+ } from '../lib/toolface/executor.js';
12
+ import { normalizeConfig } from '../lib/toolface/rules.js';
13
+
14
+ const options = normalizeConfig({});
15
+
16
+ /** The sections order read goes through ctx.get(); tests pass a minimal context. */
17
+ const EXEC_CTX = { get: () => undefined };
18
+
19
+ /** A recording fake delegate standing in for the native executor. */
20
+ function fakeDelegate() {
21
+ const forwarded = [];
22
+ return {
23
+ forwarded,
24
+ describe: (tools) => ({ schemas: tools.map(t => ({ name: t.name, description: t.description, parameters: t.parameters })) }),
25
+ execute: async (input) => {
26
+ forwarded.push(...(input.calls ?? []).map(c => c.name));
27
+ return {
28
+ results: (input.calls ?? []).map(c => ({ callId: c.id, result: { isError: false, value: { ok: c.name }, content: [] } })),
29
+ additionalContexts: [],
30
+ concluded: false,
31
+ };
32
+ },
33
+ };
34
+ }
35
+
36
+ test('NESTED_MARK is the shared cross-module symbol the transport stamps', () => {
37
+ assert.equal(NESTED_MARK, Symbol.for('dsh-codemode.nested'), 'must survive module duplication');
38
+ assert.equal(typeof NESTED_MARK.description, 'string');
39
+ });
40
+
41
+ test('isNestedCall reads the signal marker and the :ptc: id', () => {
42
+ assert.equal(isNestedCall(undefined), false);
43
+ assert.equal(isNestedCall(null), false);
44
+ assert.equal(isNestedCall({ id: 'call-1', signal: markNested(new AbortController().signal) }), true);
45
+ assert.equal(isNestedCall({ id: 'call-1:ptc:2' }), true, 'the belt-and-braces id suffix');
46
+ assert.equal(isNestedCall({ id: 'call-1', signal: new AbortController().signal }), false);
47
+ // the marker rides the signal instance, enumerable-false so it does not leak into logs
48
+ const marked = markNested(new AbortController().signal);
49
+ assert.equal(Object.keys(marked).includes(NESTED_MARK.description), false, 'non-enumerable marker');
50
+ assert.equal(markNested('not an object'), 'not an object', 'marking is best-effort on non-objects');
51
+ });
52
+
53
+ test('the executor forwards a batch of preset-owned tools to the delegate', async () => {
54
+ const delegate = fakeDelegate();
55
+ const executor = createCodemodeExecutor(EXEC_CTX, options, { createDelegate: () => delegate });
56
+ const out = await executor.execute({
57
+ calls: [{ id: 'c1', name: 'pwsh', arguments: '{}' }],
58
+ agent: {},
59
+ signal: new AbortController().signal,
60
+ });
61
+ assert.deepEqual(delegate.forwarded, ['pwsh']);
62
+ assert.equal(out.results[0].result.isError, false);
63
+ });
64
+
65
+ test('describe() passes the visible set through the delegate untouched', () => {
66
+ const delegate = fakeDelegate();
67
+ const executor = createCodemodeExecutor(EXEC_CTX, options, { createDelegate: () => delegate });
68
+ const out = executor.describe([{ name: 'pwsh', description: 'd', parameters: {} }]);
69
+ assert.deepEqual(out.schemas.map(s => s.name), ['pwsh']);
70
+ });
71
+
72
+ test('a model-direct call to a masked name is denied before dispatch with a self-heal hint', async () => {
73
+ const delegate = fakeDelegate();
74
+ const view = { enabled: true, globalNames: new Set(['mcp__fake__get_ticker']), presetNames: new Set(['pwsh']), agentNames: new Set(['mcp__fake__get_ticker', 'pwsh']) };
75
+ const executor = createCodemodeExecutor(EXEC_CTX, options, {
76
+ createDelegate: () => delegate,
77
+ viewForName: () => view,
78
+ });
79
+ const denied = await executor.execute({
80
+ calls: [{ id: 'c1', name: 'mcp__fake__get_ticker', arguments: '{}' }],
81
+ agent: {},
82
+ signal: new AbortController().signal,
83
+ });
84
+ assert.equal(denied.results[0].result.isError, true);
85
+ const message = denied.results[0].result.error.message;
86
+ assert.match(message, /mcp__fake__get_ticker/);
87
+ assert.match(message, /code_tools_search/, 'the hint names the search tool');
88
+ assert.match(message, /code_run/, 'the hint names the transport');
89
+ assert.match(denied.results[0].result.content[0].text, /Error:/);
90
+ assert.deepEqual(delegate.forwarded, [], 'denial happens before dispatch');
91
+ });
92
+
93
+ test('the transport name and marked signals are never denied', async () => {
94
+ const delegate = fakeDelegate();
95
+ const view = { enabled: true, globalNames: new Set(['mcp__fake__get_ticker']), presetNames: new Set(), agentNames: new Set() };
96
+ const executor = createCodemodeExecutor(EXEC_CTX, options, { createDelegate: () => delegate, viewForName: () => view });
97
+ await executor.execute({
98
+ calls: [{ id: 'c1', name: 'code_run', arguments: '{}' }],
99
+ agent: {},
100
+ signal: new AbortController().signal,
101
+ });
102
+ assert.deepEqual(delegate.forwarded, ['code_run'], 'the transport is how the model reaches everything else');
103
+
104
+ delegate.forwarded.length = 0;
105
+ await executor.execute({
106
+ calls: [{ id: 'c1', name: 'mcp__fake__get_ticker', arguments: '{}' }],
107
+ agent: {},
108
+ signal: markNested(new AbortController().signal),
109
+ });
110
+ assert.deepEqual(delegate.forwarded, ['mcp__fake__get_ticker'], 'a marked batch signal is program-nested');
111
+
112
+ delegate.forwarded.length = 0;
113
+ await executor.execute({
114
+ calls: [{ id: 'c1:ptc:1', name: 'mcp__fake__get_ticker', arguments: '{}' }],
115
+ agent: {},
116
+ signal: new AbortController().signal,
117
+ });
118
+ assert.deepEqual(delegate.forwarded, ['mcp__fake__get_ticker'], 'the :ptc: id also admits the call');
119
+ });
120
+
121
+ test('a denied batch rejects the whole batch; allowed siblings get their own retry hint', async () => {
122
+ const delegate = fakeDelegate();
123
+ const view = { enabled: true, globalNames: new Set(['mcp__fake__get_ticker']), presetNames: new Set(['pwsh']), agentNames: new Set(['mcp__fake__get_ticker', 'pwsh']) };
124
+ const executor = createCodemodeExecutor(EXEC_CTX, options, { createDelegate: () => delegate, viewForName: () => view });
125
+ const denied = await executor.execute({
126
+ calls: [
127
+ { id: 'c1', name: 'pwsh', arguments: '{}' },
128
+ { id: 'c2', name: 'mcp__fake__get_ticker', arguments: '{}' },
129
+ ],
130
+ agent: {},
131
+ signal: new AbortController().signal,
132
+ });
133
+ assert.equal(denied.results.length, 2);
134
+ assert.equal(denied.results[0].result.isError, true);
135
+ assert.match(denied.results[0].result.error.message, /was not run/, 'the allowed sibling is told to re-issue alone');
136
+ assert.equal(denied.results[1].result.isError, true);
137
+ assert.deepEqual(delegate.forwarded, [], 'a half-executed batch is harder to reason about than a clean rejection');
138
+ });
139
+
140
+ test('guard false skips the denial but keeps the catalog masking', async () => {
141
+ const delegate = fakeDelegate();
142
+ const executor = createCodemodeExecutor(EXEC_CTX, normalizeConfig({ guard: false }), { createDelegate: () => delegate });
143
+ await executor.execute({
144
+ calls: [{ id: 'c1', name: 'mcp__fake__get_ticker', arguments: '{}' }],
145
+ agent: {},
146
+ signal: new AbortController().signal,
147
+ });
148
+ assert.deepEqual(delegate.forwarded, ['mcp__fake__get_ticker']);
149
+ });
150
+
151
+ test('the executor supplies the tools:sdk section where DSH would put its own', () => {
152
+ const ctx = { get: (service) => service === 'systemPrompt' ? { getSectionOrder: () => 4321 } : undefined };
153
+ const executor = createCodemodeExecutor(ctx, options, {
154
+ createDelegate: fakeDelegate,
155
+ sectionText: () => '## Code Mode (fixture text)',
156
+ });
157
+ assert.equal(executor.sections.length, 1);
158
+ const section = executor.sections[0];
159
+ assert.equal(section.name, 'tools:sdk');
160
+ assert.equal(section.order, 4321);
161
+ assert.equal(section.interpolate, false);
162
+ assert.equal(section.text(), '## Code Mode (fixture text)');
163
+ });
164
+
165
+ test('sdkSection false drops the section entirely', () => {
166
+ const executor = createCodemodeExecutor(EXEC_CTX, normalizeConfig({ sdkSection: false }), { createDelegate: fakeDelegate, sectionText: () => 'x' });
167
+ assert.equal(executor.sections.length, 0);
168
+ });
169
+
170
+ test('missing dependency: the stub delegate raises the install hint on first call', async () => {
171
+ const executor = createCodemodeExecutor(EXEC_CTX, options, {}); // no delegate, no native module
172
+ assert.throws(() => executor.describe([{ name: 'pwsh' }]), /dsh-tool-executor-native/, 'describe raises the install hint');
173
+ await assert.rejects(
174
+ () => executor.execute({ calls: [{ id: 'c1', name: 'pwsh', arguments: '{}' }], signal: new AbortController().signal }),
175
+ /dsh-tool-executor-native/,
176
+ );
177
+ });
178
+
179
+ test('missing dependency: loadNativeExecutorModule rejects instead of breaking the import', async () => {
180
+ // Deterministic: point the lazy loader at a specifier that cannot resolve
181
+ // (the real dependency is installed once node_modules exists).
182
+ await assert.rejects(() => loadNativeExecutorModule('dsh-lean-router/__missing_native_executor__'), (error) => {
183
+ assert.ok(error instanceof Error);
184
+ return true;
185
+ });
186
+ });
187
+
188
+ test('the install-hint error carries the package name and the underlying cause', () => {
189
+ const err = nativeDependencyMissingError(new Error('boom'));
190
+ assert.match(err.message, /dsh-lean-router\/toolface/);
191
+ assert.match(err.message, /@deepseek-ai\/dsh-tool-executor-native/);
192
+ assert.match(err.message, /boom/);
193
+ });
194
+
195
+ test('a native module without a resolvable executor class fails loudly at mount', () => {
196
+ assert.throws(() => createCodemodeExecutor(EXEC_CTX, options, { nativeModule: {} }), /did not export NativeToolExecutor/);
197
+ });
198
+
199
+ test('a caller-provided native module builds the delegate through it', () => {
200
+ const constructed = [];
201
+ const ctx = { get: () => undefined };
202
+ const fakeClass = function (ctx) { constructed.push(ctx); return { describe: () => ({ schemas: [] }), execute: async () => ({ results: [], additionalContexts: [], concluded: false }) }; };
203
+ const mod = { NativeToolExecutor: fakeClass };
204
+ const executor = createCodemodeExecutor(ctx, options, { nativeModule: mod });
205
+ executor.describe([{ name: 'pwsh' }]);
206
+ assert.deepEqual(constructed, [ctx], 'one delegate instance is built on the provided module');
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
+ });
@@ -0,0 +1,258 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+
4
+ import { findScopeKey, resolveScopeView, resolveCatalogView, isForeignAtCall, disabledView } from '../lib/toolface/scope.js';
5
+ import { createDiscoveryTools, visibleDefinitions } from '../lib/toolface/discovery.js';
6
+ import { normalizeConfig, isMaskedName } from '../lib/toolface/rules.js';
7
+
8
+ /** The tag @deepseek-ai/dsh-scope writes onto a scoped context (symbol description). */
9
+ const SCOPE_TAG = Symbol('dsh.scope');
10
+
11
+ /** A fake three-layer registry: get(name) global, get(name, scope) adds the preset layer. */
12
+ const LAYERS = {
13
+ preset: ['pwsh', 'code_run', 'code_tools_list', 'code_tools_search', 'code_tools_describe', 'code_debug'],
14
+ global: ['mcp_probe', 'mcp__fake__get_ticker', 'mcp__fake__open_anything', 'load_workspace_dependencies'],
15
+ agent: ['spawn_teammate'],
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 };
28
+ const DEFINITIONS = new Map();
29
+ for (const layer of Object.keys(LAYERS)) {
30
+ for (const name of LAYERS[layer]) {
31
+ if (!DEFINITIONS.has(name)) {
32
+ DEFINITIONS.set(name, {
33
+ name,
34
+ description: 'fixture tool ' + name,
35
+ parameters: name === 'mcp__fake__get_ticker'
36
+ ? TICKER_PARAMETERS
37
+ : name === 'mcp__fake__open_anything'
38
+ ? FREE_FORM_PARAMETERS
39
+ : { type: 'object', properties: {} },
40
+ ...(name === 'pwsh' ? { isConcurrencySafe: () => true } : {}),
41
+ });
42
+ }
43
+ }
44
+ }
45
+ function fakeRegistry(scopeTagKey) {
46
+ const visibleFor = (scope) => {
47
+ if (scope === undefined) return ['global'];
48
+ if (scope === scopeTagKey.agent) return ['global', 'preset', 'agent'];
49
+ if (scope === scopeTagKey.preset) return ['global', 'preset'];
50
+ return ['global'];
51
+ };
52
+ const resolve = (name, layers) => {
53
+ for (const layer of layers) if (LAYERS[layer].includes(name)) return DEFINITIONS.get(name);
54
+ return undefined;
55
+ };
56
+ return {
57
+ get: (name, scope) => resolve(name, visibleFor(scope)),
58
+ schemas: (scope) => visibleFor(scope).flatMap(l => LAYERS[l]).map(n => DEFINITIONS.get(n)),
59
+ };
60
+ }
61
+ function scopeHarness() {
62
+ const keys = { preset: {}, agent: {} };
63
+ const ctx = {
64
+ tools: fakeRegistry(keys),
65
+ get: () => undefined,
66
+ };
67
+ ctx[SCOPE_TAG] = keys.preset;
68
+ return { ctx, keys };
69
+ }
70
+
71
+ test('findScopeKey reads the tag off this context or an ancestor', () => {
72
+ const { ctx, keys } = scopeHarness();
73
+ assert.equal(findScopeKey(ctx), keys.preset);
74
+ const child = Object.create(ctx);
75
+ assert.equal(findScopeKey(child), keys.preset, 'the tag is inherited down the prototype chain');
76
+ assert.equal(findScopeKey({}), undefined, 'an untagged context has no scope');
77
+ });
78
+
79
+ test('findScopeKey survives an unintrospectable context', () => {
80
+ const hostile = { get symbolsTrap() { throw new Error('no symbols for you'); } };
81
+ Object.defineProperty(hostile, 'x', { value: 1 });
82
+ const sneaky = Object.create(new Proxy({}, { ownKeys() { throw new Error('nope'); }, getOwnPropertyDescriptor() { return { configurable: true }; } }));
83
+ assert.equal(findScopeKey(sneaky), undefined);
84
+ assert.equal(findScopeKey(hostile) === undefined || true, true);
85
+ });
86
+
87
+ test('resolveScopeView reports global, preset and agent names it can resolve', () => {
88
+ const { ctx, keys } = scopeHarness();
89
+ const view = resolveScopeView(ctx, keys.preset, ['pwsh', 'mcp_probe', 'mcp__fake__get_ticker', 'spawn_teammate', 'ghost'], keys.agent);
90
+ assert.equal(view.enabled, true);
91
+ assert.deepEqual([...view.globalNames].sort(), ['mcp__fake__get_ticker', 'mcp_probe']);
92
+ assert.deepEqual([...view.presetNames].sort(), ['mcp__fake__get_ticker', 'mcp_probe', 'pwsh'], 'the preset view inherits the global layer; only the difference from globalNames is preset-owned');
93
+ assert.ok(view.agentNames.has('spawn_teammate'));
94
+ assert.equal(view.agentNames.has('ghost'), false);
95
+ });
96
+
97
+ test('resolveScopeView degrades without a scope key or a registry', () => {
98
+ assert.deepEqual(resolveScopeView({}, undefined, ['pwsh']), disabledView());
99
+ assert.deepEqual(resolveScopeView({}, {}, ['pwsh']), disabledView(), 'registry without tools.get is inert');
100
+ });
101
+
102
+ test('resolveCatalogView treats the describe() input as the agent view', () => {
103
+ const { ctx, keys } = scopeHarness();
104
+ const view = resolveCatalogView(ctx, keys.preset, ['pwsh', 'spawn_teammate']);
105
+ assert.equal(view.enabled, true);
106
+ assert.ok(view.agentNames.has('spawn_teammate'), 'the input set IS the agent view');
107
+ assert.equal(view.globalNames.has('spawn_teammate'), false);
108
+ assert.equal(view.presetNames.has('spawn_teammate'), false, 'so an agent-layer name is foreign');
109
+ });
110
+
111
+ test('isForeignAtCall answers the guard with the same attribution', () => {
112
+ const { ctx, keys } = scopeHarness();
113
+ const options = normalizeConfig({});
114
+ assert.equal(isForeignAtCall(ctx, keys.preset, 'mcp_probe', options, keys.agent), true);
115
+ assert.equal(isForeignAtCall(ctx, keys.preset, 'spawn_teammate', options, keys.agent), true);
116
+ assert.equal(isForeignAtCall(ctx, keys.preset, 'pwsh', options, keys.agent), false, 'preset-owned');
117
+ assert.equal(isForeignAtCall(ctx, keys.preset, 'code_tools_list', options, keys.agent), false, 'meta tools never foreign');
118
+ assert.equal(isForeignAtCall(ctx, keys.preset, 'code_run', options, keys.agent), false, 'our transport stays native');
119
+ assert.equal(isForeignAtCall(ctx, undefined, 'mcp_probe', options, keys.agent), false, 'no scope key, inert');
120
+ assert.equal(isForeignAtCall(ctx, keys.preset, 'ghost', options, keys.agent), false, 'unresolvable names belong to nobody');
121
+ });
122
+
123
+ test('visibleDefinitions reads schemas and re-resolves whole definitions', () => {
124
+ const { ctx, keys } = scopeHarness();
125
+ const exec = { agent: keys.agent };
126
+ const rows = visibleDefinitions(ctx, exec);
127
+ assert.ok(rows.find(r => r.name === 'spawn_teammate'));
128
+ assert.ok(rows.find(r => r.name === 'pwsh').isConcurrencySafe, 'the resolved definition, not the schema projection');
129
+ const empty = visibleDefinitions({ tools: {} }, exec);
130
+ assert.deepEqual(empty, [], 'no enumerable surface degrades to empty');
131
+ });
132
+
133
+ function discoveryHarness({ scopeKey, agent } = {}) {
134
+ const keys = { preset: {}, agent: {} };
135
+ const ctx = { tools: fakeRegistry(keys), get: () => undefined };
136
+ if (scopeKey !== undefined) ctx[SCOPE_TAG] = keys.preset;
137
+ const exec = { agent: agent === undefined ? keys.agent : agent };
138
+ const options = normalizeConfig({});
139
+ const tools = createDiscoveryTools(ctx, options, 'code_run', { scopeKey: scopeKey === undefined ? undefined : keys.preset, getDebug: () => ({ assemblies: 1, entries: [] }) });
140
+ return { ctx, keys, tools, options, exec };
141
+ }
142
+
143
+ test('the discovery set is the four meta tools under their ledger names', () => {
144
+ const { tools } = discoveryHarness();
145
+ assert.deepEqual(tools.map(t => t.name), ['code_tools_list', 'code_tools_search', 'code_tools_describe', 'code_debug']);
146
+ for (const tool of tools) {
147
+ assert.equal(tool.isConcurrencySafe(), true, 'discovery tools are concurrency-safe');
148
+ assert.ok(typeof tool.execute === 'function');
149
+ assert.ok(tool.description.length > 0);
150
+ }
151
+ });
152
+
153
+ test('list returns every callable tool with the masked flag, never the transport', async () => {
154
+ const { tools, exec } = discoveryHarness({ scopeKey: true });
155
+ const list = tools[0];
156
+ const out = await list.execute({}, exec);
157
+ assert.ok(!out.tools.some(r => r.name === 'code_run'), 'the transport excludes itself');
158
+ const ticker = out.tools.find(r => r.name === 'mcp__fake__get_ticker');
159
+ assert.equal(ticker.hidden, true);
160
+ assert.equal(ticker.namespace, 'fake');
161
+ const pwsh = out.tools.find(r => r.name === 'pwsh');
162
+ assert.equal(pwsh.hidden, false);
163
+ assert.equal(pwsh.namespace, 'native');
164
+ assert.equal(out.hidden, out.tools.filter(r => r.hidden).length);
165
+ });
166
+
167
+ test('list supports a namespace filter', async () => {
168
+ const { tools, exec } = discoveryHarness({ scopeKey: true });
169
+ const out = await tools[0].execute({ namespace: 'fake' }, exec);
170
+ assert.equal(out.tools.every(r => r.namespace === 'fake'), true);
171
+ const native = await tools[0].execute({ namespace: 'native' }, exec);
172
+ assert.ok(native.tools.some(r => r.name === 'pwsh'));
173
+ });
174
+
175
+ test('search returns parameter names, never the full schema', async () => {
176
+ const { tools, exec } = discoveryHarness({ scopeKey: true });
177
+ const out = await tools[1].execute({ query: 'ticker', namespace: 'fake' }, exec);
178
+ assert.equal(out.query, 'ticker');
179
+ assert.equal(out.tools[0].name, 'mcp__fake__get_ticker');
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');
183
+ assert.ok(out.tools.length <= 8, 'default searchLimit caps the page');
184
+ });
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
+
210
+ test('search validates its query argument', async () => {
211
+ const { tools, exec } = discoveryHarness();
212
+ await assert.rejects(() => tools[1].execute({}, exec), /query/);
213
+ await assert.rejects(() => tools[1].execute({ query: ' ' }, exec), /query/);
214
+ });
215
+
216
+ test('describe resolves one tool by exact name and reports misses', async () => {
217
+ const { tools, exec } = discoveryHarness({ scopeKey: true });
218
+ const hit = await tools[2].execute({ name: 'mcp__fake__get_ticker' }, exec);
219
+ assert.equal(hit.found, true);
220
+ assert.equal(hit.namespace, 'fake');
221
+ assert.equal(hit.hidden, true);
222
+ const miss = await tools[2].execute({ name: 'no_such_tool' }, exec);
223
+ assert.equal(miss.found, false);
224
+ assert.match(miss.hint, /code_tools_list/);
225
+ });
226
+
227
+ test('code_debug reports hidden namespaces, config and recent assemblies', async () => {
228
+ const { tools, exec, options } = discoveryHarness({ scopeKey: true });
229
+ const out = await tools[3].execute({}, exec);
230
+ assert.deepEqual(out.hiddenPrefixes, options.hiddenPrefixes);
231
+ assert.equal(out.nativeScope, true);
232
+ assert.deepEqual(out.discoveryTools, options.metaTools);
233
+ assert.equal(out.assemblies, 1);
234
+ assert.ok(out.hidden.total > 0);
235
+ });
236
+
237
+ test('the debug tool is dropped when debug is off', () => {
238
+ const { ctx, keys } = scopeHarness();
239
+ const options = normalizeConfig({ debug: false });
240
+ const tools = createDiscoveryTools(ctx, options, 'code_run', { scopeKey: keys.preset, getDebug: () => ({ assemblies: 0, entries: [] }) });
241
+ assert.deepEqual(tools.map(t => t.name), ['code_tools_list', 'code_tools_search', 'code_tools_describe']);
242
+ });
243
+
244
+ test('the listing flags out-of-preset tools the same way the request masking does', async () => {
245
+ const { tools, exec } = discoveryHarness({ scopeKey: true });
246
+ const out = await tools[0].execute({}, exec);
247
+ const view = resolveScopeViewFromListing(out);
248
+ assert.equal(typeof view, 'undefined', 'the listing itself is judged, not the view');
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]) }));
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)));
251
+ });
252
+
253
+ function resolveScopeViewFromListing() { return undefined; }
254
+ function isMasked(name, layers) {
255
+ const options = normalizeConfig({});
256
+ const view = { enabled: true, globalNames: new Set(layers.global), presetNames: new Set(layers.preset), agentNames: new Set([...layers.global, ...layers.preset, ...layers.agent]) };
257
+ return isMaskedName(name, options, view);
258
+ }