dsh-lean-router 0.0.0-stage → 0.2.4

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 (91) 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 +279 -0
  15. package/docs/changelog.md +282 -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/desc-slim.js +140 -0
  45. package/lib/toolface/discovery.js +297 -0
  46. package/lib/toolface/executor.js +333 -0
  47. package/lib/toolface/index.js +250 -0
  48. package/lib/toolface/pool.js +160 -0
  49. package/lib/toolface/retention.js +187 -0
  50. package/lib/toolface/rules.js +435 -0
  51. package/lib/toolface/scope.js +188 -0
  52. package/lib/toolface/transport.js +335 -0
  53. package/package.json +65 -4
  54. package/presets/base/frag-lean.patch.yml +459 -0
  55. package/presets/base/frag-preset.patch.yml +274 -0
  56. package/presets/base/frag-router.patch.yml +17 -0
  57. package/presets/base/frag-toolface.patch.yml +73 -0
  58. package/presets/base/lean-router.patch.yml +44 -0
  59. package/scripts/build-bundle.mjs +45 -0
  60. package/scripts/doctor.mjs +35 -0
  61. package/scripts/install-profile.mjs +113 -0
  62. package/scripts/install.mjs +20 -0
  63. package/scripts/integrate-preset.mjs +107 -0
  64. package/scripts/release.mjs +146 -0
  65. package/scripts/verify.mjs +8 -0
  66. package/test/build.test.mjs +7 -0
  67. package/test/history-budget.test.mjs +210 -0
  68. package/test/history-downgrade.test.mjs +379 -0
  69. package/test/integration-preset.test.mjs +59 -0
  70. package/test/lean-compaction.test.mjs +47 -0
  71. package/test/lean-concurrency.test.mjs +117 -0
  72. package/test/lean-delivery-gate.test.mjs +75 -0
  73. package/test/lean-frag.test.mjs +132 -0
  74. package/test/lean-modules.test.mjs +112 -0
  75. package/test/lean-pruner.test.mjs +42 -0
  76. package/test/output-slim.test.mjs +212 -0
  77. package/test/package.test.mjs +20 -0
  78. package/test/patch-yaml.test.mjs +45 -0
  79. package/test/plugin-entry.test.mjs +26 -0
  80. package/test/router-bands.test.mjs +98 -0
  81. package/test/router.test.mjs +215 -0
  82. package/test/token-ledger-live.test.mjs +351 -0
  83. package/test/token-ledger.test.mjs +264 -0
  84. package/test/toolface-desc-slim.test.mjs +255 -0
  85. package/test/toolface-executor.test.mjs +302 -0
  86. package/test/toolface-mask.test.mjs +258 -0
  87. package/test/toolface-rules.test.mjs +177 -0
  88. package/test/toolface-runtime.test.mjs +466 -0
  89. package/test/toolface-wiring.test.mjs +272 -0
  90. package/test/usage-ledger-inject.test.mjs +50 -0
  91. package/test/usage-ledger.test.mjs +399 -0
@@ -0,0 +1,335 @@
1
+ /**
2
+ * [vendored @ upstream dsh-codemode 0.3.x main f9758ec1061a9a0af4f1dfefbacc19c5987b11d1]
3
+ * Source: upstream lib/transport.js (dsh-codemode 0.3.0, main @ f9758ec).
4
+ * Vendored for dsh-lean-router ticket-04, file-for-file unchanged; the code_run transport, its nested-signal marking and the pool abandon/drain are unchanged.
5
+ *
6
+ * The plugin-owned PTC transport.
7
+ *
8
+ * DSH 0.2.1-alpha.5 removed the `both` presentation mode, so "native tools plus
9
+ * the reserved `run_code`" is no longer composable from configuration. This
10
+ * module rebuilds that surface out of public API instead of reaching into the
11
+ * registry:
12
+ *
13
+ * - the preset presents natively, so the standard tools stay directly
14
+ * callable and this package's discovery tools stay in the registry;
15
+ * - this tool is the only extra schema the model sees;
16
+ * - its sub-calls go through the registry's public `execute()`, so they keep
17
+ * the full built-in pipeline — pre-policy, guards, allow/deny/ask and
18
+ * approval, around-dispatch, and post-execute — and are marked as nested by
19
+ * the public `parent` token, the same way the built-in transport marks them.
20
+ * They are NOT durably recorded, though: `execute()` only emits the
21
+ * `tools/result` event, and the `tool/result` session entry is appended by
22
+ * the agent loop for the calls it scheduled itself, not by the registry.
23
+ * The built-in transport writes `tool/ptc-dispatch` events of its own; this
24
+ * one does not (see the README's limitations); and
25
+ * - the program's deadline is enforced by the runtime, which clamps
26
+ * `timeoutMs` against its configured default and maximum.
27
+ *
28
+ * Program-level `sandbox_permissions` escalation is deliberately not offered:
29
+ * the built-in approval helper is module-private, and omitting the parameters
30
+ * keeps every program on the standing policy while each individual sub-call
31
+ * still runs its own built-in approval.
32
+ *
33
+ * @module dsh-codemode/transport
34
+ */
35
+
36
+ import { markNested } from './executor.js';
37
+ import { createPool, normalizeMaxParallel } from './pool.js';
38
+
39
+ /** Permissive canonical output: the transport returns a JSON object. */
40
+ const OUTPUT_SCHEMA = { type: 'object', additionalProperties: true };
41
+
42
+ /** Raised when the program itself failed; the message carries the runtime's taxonomy. */
43
+ export class ProgramFailedError extends Error {
44
+ constructor(message) {
45
+ super(message);
46
+ this.name = 'ProgramFailedError';
47
+ }
48
+ }
49
+
50
+ /**
51
+ * Raised when a sub-call the program made failed. Carries the tool name so a
52
+ * program's `catch` can tell which call it was, matching the contract the
53
+ * built-in transport exposes through `ToolCallError`.
54
+ */
55
+ export class ToolCallFailedError extends Error {
56
+ constructor(message, toolName) {
57
+ super(message);
58
+ this.name = 'ToolCallError';
59
+ this.toolName = toolName;
60
+ }
61
+ }
62
+
63
+ /**
64
+ * Serialize one program sub-call's arguments.
65
+ *
66
+ * The registry's batch input carries the model-facing JSON text, not a value:
67
+ * it parses and validates it in its own pipeline, which is exactly the path a
68
+ * program sub-call must take so it keeps validation, policy and approval.
69
+ */
70
+ function stringifyArguments(rawArgs) {
71
+ if (typeof rawArgs === 'string') return rawArgs;
72
+ if (rawArgs === undefined || rawArgs === null) return '{}';
73
+ return JSON.stringify(rawArgs);
74
+ }
75
+
76
+ /**
77
+ * The signal a program sub-call runs under.
78
+ *
79
+ * A fresh controller, because the nesting marker has to be an object this
80
+ * plugin created — forwarding the outer `exec.signal` directly would mean
81
+ * marking a signal the caller owns. Cancellation is chained instead: aborting
82
+ * the outer call aborts every sub-call, which is the behaviour the built-in
83
+ * transport gets for free by passing its own signal through.
84
+ *
85
+ * @param outer - the enclosing execution's signal, when there is one.
86
+ * @returns the signal to hand the registry.
87
+ */
88
+ function nestedSignal(outer) {
89
+ const controller = new AbortController();
90
+ if (outer !== undefined && outer !== null) {
91
+ if (outer.aborted) controller.abort(outer.reason);
92
+ else outer.addEventListener('abort', () => controller.abort(outer.reason), { once: true });
93
+ }
94
+ return controller.signal;
95
+ }
96
+
97
+ /**
98
+ * Classify one sub-call's scheduling mode through the registry.
99
+ *
100
+ * DSH 0.2.2 removed `tools.executionMode()`; the classifier now lives on the
101
+ * per-executor pipeline. A plugin-owned transport has no pipeline of its own,
102
+ * so the mode is derived from the tool definition the registry resolves —
103
+ * which is the same predicate (`isConcurrencySafe`) the pipeline would read.
104
+ *
105
+ * @returns `'parallel'` or `'exclusive'`; unknown or throwing classifiers fail
106
+ * closed to exclusive, matching the pipeline's own contract.
107
+ */
108
+ function classify(ctx, name, agent) {
109
+ try {
110
+ const definition = ctx.tools.get?.(name, agent);
111
+ if (definition === undefined || typeof definition.isConcurrencySafe !== 'function') return 'exclusive';
112
+ return definition.isConcurrencySafe({}) === true ? 'parallel' : 'exclusive';
113
+ } catch {
114
+ return 'exclusive';
115
+ }
116
+ }
117
+
118
+ /** Render a JSON value as one text block. */
119
+ function renderJson(value) {
120
+ return [{ type: 'text', text: typeof value === 'string' ? value : JSON.stringify(value, null, 2) }];
121
+ }
122
+
123
+ /**
124
+ * The `code` parameter text, which is the one place the program syntax is
125
+ * visible besides the prompt section. A retained REPL has no top-level
126
+ * `return`, so advertising "the body of an async function" there would be
127
+ * wrong — the runtime reports which one it is through `programFormat`.
128
+ */
129
+ function codeParameter(programFormat) {
130
+ return programFormat === 'repl'
131
+ ? {
132
+ type: 'string',
133
+ description: 'A TypeScript REPL program: top-level declarations, `await`, and a final expression; no top-level `return`.',
134
+ }
135
+ : {
136
+ type: 'string',
137
+ description: 'The body of an async TypeScript function: erasable syntax, top-level `await` and `return` work.',
138
+ };
139
+ }
140
+
141
+ /**
142
+ * Build the tool's parameter schema. `timeoutMs` is advertised only when the
143
+ * runtime reports a descriptor, mirroring how the built-in tool derives its
144
+ * control parameters, so the model is never offered a knob the runtime cannot
145
+ * honour.
146
+ */
147
+ export function parameterSchema(runtime) {
148
+ const timeout = runtime?.timeout;
149
+ return {
150
+ type: 'object',
151
+ additionalProperties: false,
152
+ properties: {
153
+ code: codeParameter(runtime?.programFormat),
154
+ description: {
155
+ type: 'string',
156
+ description: '5-10 words on what this program does (shown in the UI).',
157
+ },
158
+ ...timeout === undefined ? {} : {
159
+ timeoutMs: {
160
+ type: 'number',
161
+ description: `Positive millisecond budget for the whole program, nested waits included. Default ${timeout.defaultMs}; capped at ${timeout.maxMs}.`,
162
+ },
163
+ },
164
+ },
165
+ required: ['code', 'description'],
166
+ };
167
+ }
168
+
169
+ /** Resolve the agent's working directory through the host service, as the built-in transport does. */
170
+ async function resolveWorkingDirectory(ctx, agent, signal) {
171
+ if (agent === undefined) return undefined;
172
+ const directories = ctx.get?.('workingDirectory');
173
+ if (directories === undefined) {
174
+ throw new Error('dsh-codemode: code execution for an agent requires the workingDirectory service (composed by @deepseek-ai/dsh-tool-fs)');
175
+ }
176
+ return directories.ensure(agent, signal);
177
+ }
178
+
179
+ /** Resolve the standing file policy for the program, when the deployment has one. */
180
+ function resolveSandboxPolicy(ctx, agent) {
181
+ const policy = ctx.get?.('sandboxPolicy');
182
+ if (policy === undefined) return undefined;
183
+ return policy.resolve(agent === undefined ? {} : { session: agent.session });
184
+ }
185
+
186
+ /**
187
+ * Build the transport tool definition.
188
+ * @param ctx - the plugin's scoped context.
189
+ * @param options - normalized plugin config.
190
+ * @param hooks - `retention` owns the retained-environment lifecycle; `code` names the tool in messages.
191
+ * @returns a registry-ready tool definition.
192
+ */
193
+ export function createTransportTool(ctx, options, hooks = {}) {
194
+ const runToolName = options.runToolName;
195
+ const maxParallel = normalizeMaxParallel(options.maxParallelSubCalls);
196
+
197
+ const definition = {
198
+ name: runToolName,
199
+ description:
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.',
203
+ output: { schema: OUTPUT_SCHEMA, render: (_args, value) => renderJson(value) },
204
+ // Programs mutate state and are ordered as a unit, so they never overlap
205
+ // with a sibling call in the same model step.
206
+ isConcurrencySafe: () => false,
207
+
208
+ async execute(args, exec) {
209
+ if (typeof args?.code !== 'string' || args.code.trim().length === 0) {
210
+ throw new Error(`invalid code: ${runToolName} expects a non-empty program`);
211
+ }
212
+ if (typeof args?.description !== 'string' || args.description.trim().length === 0) {
213
+ throw new Error('invalid description: expected a non-empty string');
214
+ }
215
+ if (args.timeoutMs !== undefined && (!Number.isFinite(args.timeoutMs) || args.timeoutMs <= 0)) {
216
+ throw new Error('invalid timeoutMs: expected a positive finite number');
217
+ }
218
+
219
+ const runtime = ctx.get?.('ptcRuntime');
220
+ if (runtime === undefined) {
221
+ throw new Error(`dsh-codemode: ${runToolName} requires a PTC runtime service (compose @deepseek-ai/dsh-ptc-runtime-node)`);
222
+ }
223
+ // Mirror the built-in: never forward a deadline a runtime cannot honour.
224
+ // This package registers a raw definition, so the registry does no schema
225
+ // validation of its own and this check is load-bearing.
226
+ if (args.timeoutMs !== undefined && runtime.timeout === undefined) {
227
+ throw new Error('timeoutMs is not available for this PTC runtime');
228
+ }
229
+
230
+ const agent = exec?.agent;
231
+ const cwd = await resolveWorkingDirectory(ctx, agent, exec?.signal);
232
+ const sandboxPolicy = resolveSandboxPolicy(ctx, agent);
233
+ // The ONLY place a stateOwner is produced; see lib/retention.js. An
234
+ // agentless call is checked here as well as there: with no agent there is
235
+ // no lifetime to bind a retained environment to, so the decision must not
236
+ // depend on the registry's own discipline.
237
+ const owner = agent === undefined ? undefined : hooks.retention?.ownerFor(agent, runtime);
238
+
239
+ const pool = createPool(maxParallel);
240
+ let dispatches = 0;
241
+
242
+ /**
243
+ * Dispatch one program sub-call through the registry's public batch entry
244
+ * point.
245
+ *
246
+ * DSH 0.2.2 takes a batch (`{ calls, agent, signal }`) and mints execution
247
+ * tokens inside its own pipeline, so a plugin-owned transport cannot pass
248
+ * an opaque `parent`. The sub-call is therefore marked on the `signal`
249
+ * instead — an object the model cannot fabricate — which is what both the
250
+ * executor's denial check and the pool's classifier read. The `:ptc:`
251
+ * call id is kept as the second, belt-and-braces signal.
252
+ */
253
+ const dispatch = async (name, schema, rawArgs) => {
254
+ const callId = `${String(exec.callId)}:ptc:${++dispatches}`;
255
+ const call = {
256
+ id: callId,
257
+ name,
258
+ schema,
259
+ type: 'tool-call',
260
+ arguments: stringifyArguments(rawArgs),
261
+ };
262
+ const outcome = await ctx.tools.execute({
263
+ calls: [call],
264
+ ...(agent === undefined ? {} : { agent }),
265
+ signal: markNested(nestedSignal(exec.signal)),
266
+ });
267
+ const settled = outcome?.results?.[0]?.result;
268
+ if (settled === undefined) {
269
+ throw new Error(`tool "${name}" produced no result`);
270
+ }
271
+ if (settled.isError) {
272
+ throw new ToolCallFailedError(`tool "${name}" failed: ${settled.error?.message ?? 'unknown error'}`, name);
273
+ }
274
+ return settled.value;
275
+ };
276
+
277
+ const functions = Object.create(null);
278
+ for (const schema of ctx.tools.schemas?.(agent) ?? []) {
279
+ if (schema?.name === undefined || schema.name === runToolName) continue;
280
+ Object.defineProperty(functions, schema.name, {
281
+ enumerable: true,
282
+ value: (rawArgs) => {
283
+ // Classify through the registry so the pool reproduces the same
284
+ // parallel/exclusive contract the loop's scheduler would apply.
285
+ const kind = classify(ctx, schema.name, agent);
286
+ return pool.run(() => dispatch(schema.name, schema, rawArgs), kind);
287
+ },
288
+ });
289
+ }
290
+
291
+ try {
292
+ const result = await runtime.run(runtime.resolve({
293
+ program: args.code,
294
+ ...(owner === undefined ? {} : { stateOwner: owner }),
295
+ bindings: [{
296
+ global: 'tools',
297
+ functions,
298
+ errorClass: { name: 'ToolCallError', memberNameProperty: 'toolName' },
299
+ }],
300
+ signal: exec.signal,
301
+ ...(cwd === undefined ? {} : { cwd }),
302
+ ...(sandboxPolicy === undefined ? {} : { sandboxPolicy }),
303
+ ...(args.timeoutMs === undefined ? {} : { timeoutMs: args.timeoutMs }),
304
+ }));
305
+
306
+ if (result.error) {
307
+ const logsText = result.logs.length > 0 ? `\nCaptured output:\n${result.logs.join('\n')}` : '';
308
+ throw new ProgramFailedError(`code run failed (${result.error.kind}): ${result.error.message}${logsText}`);
309
+ }
310
+ return {
311
+ logs: result.logs,
312
+ ...result.sandbox === undefined ? {} : { sandbox: result.sandbox },
313
+ ...result.value === undefined ? {} : { result: result.value },
314
+ };
315
+ } finally {
316
+ // The program is over: a sub-call it queued but never reached must not
317
+ // run after the fact. In-flight calls still finish, and the outer
318
+ // result only leaves once they have.
319
+ pool.abandon();
320
+ await pool.drain();
321
+ }
322
+ },
323
+ };
324
+
325
+ // The parameter schema depends on the mounted runtime, which is resolved at
326
+ // use time and never injected (a static inject would hold the whole tool
327
+ // registry hostage to a PTC runtime existing). The getter mirrors the
328
+ // built-in transport so the descriptor is read fresh per projection.
329
+ Object.defineProperty(definition, 'parameters', {
330
+ enumerable: true,
331
+ get: () => parameterSchema(ctx.get?.('ptcRuntime')),
332
+ });
333
+
334
+ return definition;
335
+ }
package/package.json CHANGED
@@ -1,6 +1,67 @@
1
1
  {
2
2
  "name": "dsh-lean-router",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.4",
4
+ "description": "lean 省 token × 思考链路由 × code_run 工具遮蔽的 DSH cordis 插件(单 bundle:预设)",
5
+ "type": "module",
6
+ "main": "lib/index.js",
7
+ "exports": {
8
+ ".": "./lib/index.js",
9
+ "./package.json": "./package.json",
10
+ "./router": "./lib/router.js",
11
+ "./toolface": "./lib/toolface/index.js",
12
+ "./lean/delivery-gate": "./lib/lean/delivery-gate.js",
13
+ "./lean/history-downgrade": "./lib/lean/history-downgrade.js",
14
+ "./lean/tool-concurrency": "./lib/lean/tool-concurrency.js",
15
+ "./lean/usage-ledger": "./lib/lean/usage-ledger.js",
16
+ "./token-ledger": "./lib/token-ledger/index.js",
17
+ "./token-ledger/live": "./lib/token-ledger/live.js"
18
+ },
19
+ "files": [
20
+ "lib",
21
+ "presets",
22
+ "docs",
23
+ "cordis.patch.yml",
24
+ "scripts",
25
+ "test",
26
+ "README.md",
27
+ "README.en.md",
28
+ "NOTICE.md",
29
+ "LICENSE"
30
+ ],
31
+ "license": "MIT",
32
+ "author": "ShawnSun-debug",
33
+ "repository": {
34
+ "type": "git",
35
+ "url": "git+https://github.com/ShawnSun-Debug/dsh-lean-router.git"
36
+ },
37
+ "engines": {
38
+ "dsh": ">=0.2.1-rc.5 <0.2.4-0"
39
+ },
40
+ "scripts": {
41
+ "test": "node --test \"test/*.test.mjs\"",
42
+ "build": "node scripts/build-bundle.mjs",
43
+ "doctor": "node scripts/doctor.mjs",
44
+ "verify": "node scripts/verify.mjs"
45
+ },
46
+ "dsh": {
47
+ "bundle": {
48
+ "patch": "./cordis.patch.yml"
49
+ }
50
+ },
51
+ "keywords": [
52
+ "dsh",
53
+ "agent-preset",
54
+ "lean",
55
+ "router",
56
+ "codemode"
57
+ ],
58
+ "dependencies": {
59
+ "@deepseek-ai/dsh-tool-executor-native": ">=0.2.2-alpha.3 <0.2.4-0"
60
+ },
61
+ "peerDependencies": {
62
+ "@deepseek-ai/cordis": ">=4.1.0-0 <4.3.0-0"
63
+ },
64
+ "devDependencies": {
65
+ "js-yaml": "^4.1.0"
66
+ }
67
+ }