dsh-taskbridge 0.0.0-stage → 1.3.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.
Files changed (74) hide show
  1. package/CHANGELOG.md +754 -0
  2. package/LICENSE +21 -0
  3. package/README.md +624 -3
  4. package/bin/dsh-delegate-codex-agent.js +115 -0
  5. package/bin/dsh-delegate-control.d.ts +90 -0
  6. package/bin/dsh-delegate-control.js +450 -0
  7. package/bin/dsh-delegate-mcp.d.ts +121 -0
  8. package/bin/dsh-delegate-mcp.js +273 -0
  9. package/codex/dsh-delegate.toml +245 -0
  10. package/cordis.patch.yml +6 -0
  11. package/docs/INTRODUCTION.md +15 -0
  12. package/docs/INTRODUCTION.zh.md +32 -0
  13. package/docs/auth-contract.md +138 -0
  14. package/docs/claude-code.md +31 -0
  15. package/docs/codex-integration.md +922 -0
  16. package/docs/contracts-stage-b.md +443 -0
  17. package/docs/conversation-placement.md +293 -0
  18. package/docs/plugin-market.md +30 -0
  19. package/docs/redaction-contract.md +127 -0
  20. package/docs/runtime-compatibility.md +220 -0
  21. package/docs/silent-wait.md +191 -0
  22. package/docs/taskbridge-upgrade.md +28 -0
  23. package/docs/taskdispatch-upgrade.md +25 -0
  24. package/docs/worker-permissions.md +347 -0
  25. package/docs/workspace-contract.md +538 -0
  26. package/icon.svg +1 -0
  27. package/lib/client.d.ts +118 -0
  28. package/lib/client.js +3232 -0
  29. package/locale/en.json +7 -0
  30. package/locale/zh.json +7 -0
  31. package/package.json +135 -4
  32. package/src/auth/fence.js +361 -0
  33. package/src/auth/grants.js +789 -0
  34. package/src/client/api.js +2322 -0
  35. package/src/client/index.jsx +2333 -0
  36. package/src/client/styles.js +251 -0
  37. package/src/codex/installer.js +3260 -0
  38. package/src/codex/seam.js +429 -0
  39. package/src/codex/toml.js +784 -0
  40. package/src/config/defaults.js +164 -0
  41. package/src/config/redact.js +184 -0
  42. package/src/config/settings.js +629 -0
  43. package/src/config/store.js +186 -0
  44. package/src/config/validate.js +763 -0
  45. package/src/credentials/seam.js +202 -0
  46. package/src/http/execution-plane.js +454 -0
  47. package/src/http/respond.js +175 -0
  48. package/src/http/user-plane.js +1122 -0
  49. package/src/index.d.ts +332 -0
  50. package/src/index.js +657 -0
  51. package/src/jobs/activity.js +1008 -0
  52. package/src/jobs/engine.js +3609 -0
  53. package/src/jobs/history.js +1467 -0
  54. package/src/mcp/server.js +1820 -0
  55. package/src/mcp/wait.js +536 -0
  56. package/src/model/connectivity.js +371 -0
  57. package/src/model/discovery.js +582 -0
  58. package/src/model/native-catalog.js +68 -0
  59. package/src/model/openai-adapter.js +671 -0
  60. package/src/model/probe.js +264 -0
  61. package/src/model/providers.js +756 -0
  62. package/src/model/routing.js +321 -0
  63. package/src/review/preset.js +868 -0
  64. package/src/review/prompts.js +126 -0
  65. package/src/review/reviewer.js +933 -0
  66. package/src/runtime/agent-runner.js +1738 -0
  67. package/src/runtime/endpoint-discovery.js +118 -0
  68. package/src/runtime/permissions.js +1429 -0
  69. package/src/runtime/sandbox.js +358 -0
  70. package/src/runtime/session-placement.js +1103 -0
  71. package/src/workspace/audit.js +775 -0
  72. package/src/workspace/locks.js +167 -0
  73. package/src/workspace/preflight.js +424 -0
  74. package/src/workspace/worktrees.js +613 -0
@@ -0,0 +1,1820 @@
1
+ // MCP server: the bounded external surface.
2
+ //
3
+ // Design rule taken from SPEC §10–11: an external MCP client may *exercise* an
4
+ // authorization the operator already created, and may do nothing else. So this
5
+ // server exposes seven tools and maps each one onto one execution-plane route:
6
+ //
7
+ // delegate_status → GET /dsh-delegate/x/status
8
+ // delegate_submit → POST /dsh-delegate/x/tasks
9
+ // delegate_result → POST /dsh-delegate/x/tasks/get
10
+ // delegate_wait → POST /dsh-delegate/x/tasks/observe (repeated)
11
+ // delegate_cancel → POST /dsh-delegate/x/tasks/cancel
12
+ // delegate_permission_decide → POST /dsh-delegate/x/tasks/permission
13
+ // delegate_preflight → POST /dsh-delegate/x/workspace/preflight
14
+ //
15
+ // `delegate_wait` is a read like `delegate_result`, and it is the one tool whose
16
+ // single call may take a long time: it composes several BOUNDED observation
17
+ // requests (each ≤ {@link OBSERVE_WAIT_MS}) into one host-visible wait, and returns
18
+ // as soon as the task reaches a state the host must act on — a permission request,
19
+ // a finished run, a failure, a cancellation — or when the caller's own deadline is
20
+ // reached. It never calls `delegate_result`: a wait answer is compact by design, and
21
+ // the full snapshot stays behind its own bounded projection.
22
+ //
23
+ // `delegate_permission_decide` is the one NARROW EXCEPTION to the sentence above,
24
+ // and it is narrow in exactly one way: it consumes an ALREADY PENDING per-call
25
+ // permission request that a delegated worker raised, and it can answer only
26
+ // `allow-once` or `reject` for that one exact tool call. It cannot create a
27
+ // connection, cannot issue, widen or extend a grant, cannot change settings, the
28
+ // switch, the provider/model or a credential, and cannot pre-approve any future
29
+ // operation: the request is bound to one Session, one tool call id and an exact
30
+ // fingerprint of the real arguments, and it is consumed by the decision. The
31
+ // worker's standing sandbox mode is never changed by it. This tool is NOT part of the
32
+ // native worker's declared tool catalog, so the worker's own model is never handed it —
33
+ // a real tool-surface restriction, but NOT a claim that a process running as the same OS
34
+ // user could not reach the shared local-MCP endpoint directly. See `runtime/permissions.js`.
35
+ //
36
+ // `delegate_preflight` is the one addition that is not an authorization at all: it
37
+ // is a read-only measurement of a workspace, and it exists so a dispatcher can
38
+ // learn before submitting that a checkout is dirty, is not a repository, or would
39
+ // need an isolation decision — instead of learning it from a failed job. It still
40
+ // cannot authorize, configure or write anything, and the execution plane does not
41
+ // gate it on the switch, so an answer is available while delegation is off.
42
+ //
43
+ // There is no tool that issues a connection, issues or widens a grant, changes
44
+ // settings, or touches a credential. Those actions live on the authenticated user
45
+ // plane, which is reachable only from the operator's own browser session.
46
+ //
47
+ // The connection token is read from the environment and is never placed in a
48
+ // tool result, an error, or a log line. Every answer is bounded and is the
49
+ // server's own already-redacted projection; this process adds no data of its own.
50
+ //
51
+ // The protocol is implemented directly rather than through
52
+ // `@modelcontextprotocol/server`, which is not installed in this environment (only
53
+ // `@modelcontextprotocol/client` and `@modelcontextprotocol/core` are). What that
54
+ // costs is stated in the README: this server speaks the `initialize` handshake and
55
+ // the tools capability only, and it is not a general-purpose MCP SDK.
56
+
57
+ // Only `diagnostic` is needed here, and it is imported from the redaction module
58
+ // rather than from `runtime/agent-runner.js`. That distinction is load-bearing:
59
+ // the agent runner statically imports `@deepseek-ai/dsh-llm` and
60
+ // `@deepseek-ai/dsh-agent`, which only a running DSH installation provides. This
61
+ // executable is spawned by an arbitrary MCP host, so reaching through the runner
62
+ // made it fail at link time with `ERR_MODULE_NOT_FOUND` before it could report
63
+ // anything at all.
64
+ import { diagnostic, redactText } from '../config/redact.js';
65
+ import { waitForTask } from './wait.js';
66
+
67
+ /** Protocol revisions this server can speak, newest first (as the SDK lists them). */
68
+ export const SUPPORTED_PROTOCOL_VERSIONS = Object.freeze([
69
+ '2025-11-25',
70
+ '2025-06-18',
71
+ '2025-03-26',
72
+ '2024-11-05',
73
+ ]);
74
+
75
+ /** The revision answered when a client asks for one this server does not know. */
76
+ export const LATEST_PROTOCOL_VERSION = SUPPORTED_PROTOCOL_VERSIONS[0];
77
+
78
+ /** Identifies this server in the handshake. */
79
+ export const SERVER_INFO = Object.freeze({ name: 'dsh-delegate', version: '1.3.1' });
80
+
81
+ /** Bound on a tool result's text. A task view can be large; a model's context cannot. */
82
+ export const MAX_TOOL_TEXT_CHARS = 20_000;
83
+
84
+ /** Bound on one execution-plane request. */
85
+ export const DEFAULT_REQUEST_TIMEOUT_MS = 30_000;
86
+
87
+ /**
88
+ * Longest single observation request `delegate_wait` issues, in milliseconds.
89
+ *
90
+ * Deliberately equal to the execution plane's own bound (`MAX_OBSERVE_WAIT_MS`):
91
+ * the plane clamps anything larger, so a longer value here would only make the
92
+ * client believe it had asked for something the server does not do.
93
+ */
94
+ export const OBSERVE_WAIT_MS = 25_000;
95
+
96
+ /** Default deadline of one `delegate_wait` call, in seconds (one hour). */
97
+ export const DEFAULT_WAIT_SECONDS = 3_600;
98
+
99
+ /** Longest deadline one `delegate_wait` call may ask for, in seconds (one hour). */
100
+ export const MAX_WAIT_SECONDS = 3_600;
101
+
102
+ /** Shortest deadline one `delegate_wait` call may ask for, in seconds. */
103
+ export const MIN_WAIT_SECONDS = 1;
104
+
105
+ /**
106
+ * How many requests may be in flight at once on the stdio transport.
107
+ *
108
+ * A request that takes minutes (a wait) must not stop the host from sending
109
+ * `tools/call` for a status read, a cancel or a permission decision. Concurrency is
110
+ * bounded anyway: each in-flight request holds a socket, a promise and its own
111
+ * encoded reply, and an unbounded number of those is a memory bound the host, not
112
+ * this server, controls. Beyond the cap the request is REFUSED explicitly rather
113
+ * than queued silently, so a host learns its situation instead of wondering.
114
+ */
115
+ export const MAX_INFLIGHT_REQUESTS = 32;
116
+
117
+ /** How many call records are retained for tests/diagnostics. */
118
+ export const MAX_CALL_LOG = 256;
119
+
120
+ /**
121
+ * Reasons on which `delegate_wait` returns to the host.
122
+ *
123
+ * `heartbeat` is deliberately absent: it is the engine's internal "nothing changed
124
+ * yet" signal, consumed by the wait loop and never surfaced as an answer.
125
+ */
126
+ export const ACTIONABLE_REASONS = Object.freeze(['attention', 'permission', 'ready', 'failed', 'cancelled', 'interrupted']);
127
+
128
+ /** The reason a wait that reached its own deadline reports. */
129
+ export const WAIT_LIMIT_REASON = 'wait-limit';
130
+
131
+ /** JSON-RPC error codes used here (the standard set, not invented ones). */
132
+ export const RPC_ERRORS = Object.freeze({
133
+ parse: -32700,
134
+ invalidRequest: -32600,
135
+ methodNotFound: -32601,
136
+ invalidParams: -32602,
137
+ internal: -32603,
138
+ });
139
+
140
+ /**
141
+ * A refusal this server produced itself. Distinct from a transport failure so a
142
+ * caller can tell "the harness said no" from "the harness could not be reached".
143
+ */
144
+ export class McpError extends Error {
145
+ /**
146
+ * @param {string} code - stable machine code, surfaced to the client as text.
147
+ * @param {string} message - explanation, already free of secrets.
148
+ * @param {object} [options] - `rpcCode` for a protocol-level refusal.
149
+ */
150
+ constructor(code, message, options = {}) {
151
+ super(message);
152
+ this.name = 'McpError';
153
+ this.code = code;
154
+ this.rpcCode = options.rpcCode ?? null;
155
+ }
156
+ }
157
+
158
+ /**
159
+ * Tool catalog.
160
+ *
161
+ * `inputSchema` is deliberately closed (`additionalProperties: false`): a model
162
+ * that invents a field gets a clear protocol error instead of a silently ignored
163
+ * argument, and no tool can grow an undeclared parameter by accident.
164
+ *
165
+ * Every tool also carries MCP `annotations` (`readOnlyHint` / `destructiveHint` /
166
+ * `idempotentHint` / `openWorldHint`). They are an accurate DESCRIPTION of what each
167
+ * tool does — a read is marked read-only, cancelling is marked destructive and not
168
+ * idempotent — and they let a concurrency-aware client know that a long wait is a
169
+ * read and must not be treated as a mutating call that blocks the session. They are
170
+ * not the fix for a serialising host: a client that forwards one call at a time
171
+ * ignores every annotation, which is exactly why the independent
172
+ * `bin/dsh-delegate-control.js` channel exists. Nothing here claims that annotations
173
+ * make a serial client concurrent.
174
+ */
175
+ export const TOOLS = Object.freeze([
176
+ Object.freeze({
177
+ name: 'delegate_status',
178
+ title: 'Delegation status',
179
+ description: 'Report whether delegation is enabled in DSH for this local MCP connection.',
180
+ // A pure read of the plane's own posture: no task, no grant, no write.
181
+ annotations: Object.freeze({
182
+ title: 'Delegation status',
183
+ readOnlyHint: true,
184
+ destructiveHint: false,
185
+ idempotentHint: true,
186
+ openWorldHint: false,
187
+ }),
188
+ inputSchema: Object.freeze({
189
+ type: 'object',
190
+ properties: {},
191
+ additionalProperties: false,
192
+ }),
193
+ }),
194
+ Object.freeze({
195
+ name: 'delegate_submit',
196
+ title: 'Submit delegated task',
197
+ description: 'Submit one prompt to run as a delegated task while the DSH delegation switch is enabled. '
198
+ + 'Returns the task identity and state; '
199
+ + 'it does not wait for the work to finish and it is not host approval. '
200
+ + 'workspacePath is the operator-authorized SOURCE repository or checkout the task runs against; '
201
+ + 'a source root may legitimately be a Git checkout or a Git worktree (subject to the usual preflight). '
202
+ + 'A follow-up keeps that same source path as the task it continues. '
203
+ + 'Omit continueFromTaskId to start a NEW task conversation (always a fresh DSH session, even in a '
204
+ + 'directory used before). Set it to the task id of the earlier delegated task this submission is a '
205
+ + 'follow-up to, to continue exactly that task thread (same DSH Workspace and Session): the plugin '
206
+ + 'reuses that task\u2019s recorded execution checkout and DSH Session internally, taking no execution '
207
+ + 'location from '
208
+ + 'the caller. An unknown, unfinished, removed or differently-sourced parent is refused rather than '
209
+ + 'started as a new conversation.',
210
+ // It creates work, so it is not a read; it is not destructive of anything the
211
+ // operator already has, and repeating it creates ANOTHER task (never idempotent).
212
+ annotations: Object.freeze({
213
+ title: 'Submit delegated task',
214
+ readOnlyHint: false,
215
+ destructiveHint: false,
216
+ idempotentHint: false,
217
+ openWorldHint: false,
218
+ }),
219
+ inputSchema: Object.freeze({
220
+ type: 'object',
221
+ properties: {
222
+ workspacePath: {
223
+ type: 'string',
224
+ description: 'Absolute path of the operator-authorized SOURCE repository or checkout \u2014 the path '
225
+ + 'the authorization names, not a location chosen while a task runs. A source root may itself be '
226
+ + 'a Git checkout or a Git worktree, which is not rejected for that reason; it still goes through '
227
+ + 'the same preflight as any other path. '
228
+ + 'For a continueFromTaskId follow-up, pass the SAME source path the parent task was submitted '
229
+ + 'with: the plugin reuses the parent\u2019s recorded execution checkout and DSH Session internally, so do not '
230
+ + 'send '
231
+ + 'an execution.workspacePath or any other internal execution location in its place, because a '
232
+ + 'different source path names a different repository and the continuation is refused.',
233
+ },
234
+ prompt: { type: 'string', description: 'The task to perform.' },
235
+ overrides: {
236
+ type: 'object',
237
+ description: 'Optional per-task overrides (model/effort/timeout). Validated by the harness.',
238
+ additionalProperties: true,
239
+ },
240
+ continueFromTaskId: {
241
+ type: 'string',
242
+ description: 'Task id of the earlier delegated task this submission continues. '
243
+ + 'Use it only for a follow-up change or retry that belongs to that same task; '
244
+ + 'omit it for an unrelated task. It names a task thread, not a directory: keep passing the '
245
+ + 'parent\u2019s original authorized source repository in workspacePath and do not send the parent\u2019s '
246
+ + 'execution location, because the plugin reuses the parent\u2019s recorded execution checkout and DSH Session '
247
+ + 'internally and pins the follow-up to the parent\u2019s recorded isolation; do not select a new '
248
+ + 'isolation override either. An unknown, still-running, removed or differently-sourced parent is '
249
+ + 'refused, never replaced by a new conversation.',
250
+ },
251
+ },
252
+ required: ['workspacePath', 'prompt'],
253
+ additionalProperties: false,
254
+ }),
255
+ }),
256
+ Object.freeze({
257
+ name: 'delegate_result',
258
+ title: 'Read task result',
259
+ description: 'Read one task this connection submitted: state, effective provider/model/effort, '
260
+ + 'changed-file summary, bounded diff, validation evidence and review outcome. '
261
+ + 'A finished execution is not host acceptance.',
262
+ // A read of a stored task: no work is created, changed or cancelled.
263
+ annotations: Object.freeze({
264
+ title: 'Read task result',
265
+ readOnlyHint: true,
266
+ destructiveHint: false,
267
+ idempotentHint: true,
268
+ openWorldHint: false,
269
+ }),
270
+ inputSchema: Object.freeze({
271
+ type: 'object',
272
+ properties: {
273
+ taskId: { type: 'string', description: 'Task identity returned by delegate_submit.' },
274
+ },
275
+ required: ['taskId'],
276
+ additionalProperties: false,
277
+ }),
278
+ }),
279
+ Object.freeze({
280
+ name: 'delegate_wait',
281
+ title: 'Wait for a task to need you',
282
+ description: 'Follow ONE task this connection submitted and return as soon as it needs the host. '
283
+ + 'A single call blocks for up to waitSeconds (default 3600) and returns a COMPACT answer: '
284
+ + '`reason` is `permission` (a per-call request is pending), `attention` (no activity for about ten '
285
+ + 'minutes, so the run may be stuck), `ready` (the run ended and is awaiting host review), `failed`, '
286
+ + '`cancelled` or `interrupted`. '
287
+ + '`reason: "wait-limit"` means the deadline was reached and NOTHING changed: call delegate_wait again '
288
+ + 'with the same taskId — do not review, resubmit or restart the task. '
289
+ + 'Heartbeats are internal to this call and are never returned. '
290
+ + 'This tool reads; it never submits, cancels or decides anything, and it does not fetch the task\u2019s '
291
+ + 'diff or full result (use delegate_result for that, after an actionable reason). '
292
+ + 'On `permission`, the returned `permission` block carries the pending request with its requestId, '
293
+ + 'its exact fingerprint and the full existing redacted operation, so delegate_permission_decide can '
294
+ + 'be sent without another read. '
295
+ + '`interrupted` does NOT mean the execution stopped. This call answers it immediately, once: '
296
+ + 'when the task is still pending or running the answer is `reason: "interrupted"` with '
297
+ + '`terminal: false` and the real task state, and YOU wait again on the same taskId. '
298
+ + '`terminal: true` with `state: "interrupted"` means the task record itself is a restart history '
299
+ + 'and will not resume. If the reason carried a settled state it is reported as that outcome '
300
+ + '(`ready`/`failed`/`cancelled`). A missing or unrecognized state is reported as '
301
+ + '`terminal: false` with nothing asserted: check before deciding.',
302
+ // A LONG read, and that is the point: `readOnlyHint` is what tells a
303
+ // concurrency-aware client this call may be held for an hour without being a
304
+ // mutating operation. A serialising host still ignores it; the independent
305
+ // `dsh-delegate-control` channel is the answer there.
306
+ annotations: Object.freeze({
307
+ title: 'Wait for a task to need you',
308
+ readOnlyHint: true,
309
+ destructiveHint: false,
310
+ idempotentHint: true,
311
+ openWorldHint: false,
312
+ }),
313
+ inputSchema: Object.freeze({
314
+ type: 'object',
315
+ properties: {
316
+ taskId: { type: 'string', description: 'Task identity returned by delegate_submit.' },
317
+ waitSeconds: {
318
+ type: 'integer',
319
+ minimum: MIN_WAIT_SECONDS,
320
+ maximum: MAX_WAIT_SECONDS,
321
+ description: 'How long this one call may wait, in seconds (default 3600). '
322
+ + 'A returned `wait-limit` means this deadline was reached, not that the task stalled.',
323
+ },
324
+ },
325
+ required: ['taskId'],
326
+ additionalProperties: false,
327
+ }),
328
+ }),
329
+ Object.freeze({
330
+ name: 'delegate_cancel',
331
+ title: 'Cancel task',
332
+ description: 'Ask the harness to stop one task this connection submitted, and return its state afterwards.',
333
+ // It stops running work: destructive of the run (never of the workspace), and a
334
+ // second call on an already-cancelled task changes nothing.
335
+ annotations: Object.freeze({
336
+ title: 'Cancel task',
337
+ readOnlyHint: false,
338
+ destructiveHint: true,
339
+ idempotentHint: true,
340
+ openWorldHint: false,
341
+ }),
342
+ inputSchema: Object.freeze({
343
+ type: 'object',
344
+ properties: {
345
+ taskId: { type: 'string', description: 'Task identity returned by delegate_submit.' },
346
+ },
347
+ required: ['taskId'],
348
+ additionalProperties: false,
349
+ }),
350
+ }),
351
+ Object.freeze({
352
+ name: 'delegate_permission_decide',
353
+ title: 'Decide a paused permission request',
354
+ description: 'Decide ONE per-call permission request that a delegated task is waiting on. '
355
+ + 'A delegated worker runs in its own workspace with a standing `workspace-write` sandbox; '
356
+ + 'when it asks to widen access for a single tool call, that call PAUSES and the request appears '
357
+ + 'in delegate_result as `permission.pending` (state stays `running`, phase `awaiting-permission`). '
358
+ + 'Read `permission.pending.arguments`/`argumentKeys` for the exact operation and `permission.pending.reason` '
359
+ + 'for the asker\u2019s claim — the claim is not the operation. Answer `allow-once` to let THAT ONE call '
360
+ + 'proceed, or `reject` to keep it denied; the worker then continues and a later escalation asks again. '
361
+ + 'This cannot grant an account, a workspace or a standing policy, cannot change settings, credentials, '
362
+ + 'the switch, the provider/model or the isolation, and cannot approve a future call. '
363
+ + '`allow-once` REQUIRES the pending request\u2019s `fingerprint` and is refused when `permission.pending.'
364
+ + 'completeness` is not `complete` (the operation was shortened by a bound, so an allow cannot be granted '
365
+ + 'on it). `reject` needs neither and is therefore always available.',
366
+ // It does not read and it does not write a configuration: it settles ONE paused
367
+ // call. A repeated decision for the same request is refused, so it is not
368
+ // idempotent — the second call is a different outcome by design.
369
+ annotations: Object.freeze({
370
+ title: 'Decide a paused permission request',
371
+ readOnlyHint: false,
372
+ destructiveHint: false,
373
+ idempotentHint: false,
374
+ openWorldHint: false,
375
+ }),
376
+ inputSchema: Object.freeze({
377
+ type: 'object',
378
+ properties: {
379
+ taskId: { type: 'string', description: 'Task identity returned by delegate_submit.' },
380
+ requestId: { type: 'string', description: 'The pending request\u2019s `requestId`, copied from delegate_result.' },
381
+ decision: {
382
+ type: 'string',
383
+ enum: ['allow-once', 'reject'],
384
+ description: 'allow-once permits exactly the paused call; reject keeps it denied.',
385
+ },
386
+ reason: {
387
+ type: 'string',
388
+ description: 'Optional bounded note recorded with the decision. It is evidence, never a grant.',
389
+ },
390
+ fingerprint: {
391
+ type: 'string',
392
+ description: 'The pending request\u2019s `fingerprint`. REQUIRED for `allow-once`: the decision must name '
393
+ + 'the exact operation it grants, and an allow that omits it is refused. Optional for `reject` (a '
394
+ + 'refusal is safe without it); when supplied, a request whose operation no longer matches is refused.',
395
+ },
396
+ },
397
+ required: ['taskId', 'requestId', 'decision'],
398
+ additionalProperties: false,
399
+ }),
400
+ }),
401
+ Object.freeze({
402
+ name: 'delegate_preflight',
403
+ title: 'Inspect workspace before dispatch',
404
+ description: 'Read-only preflight of one absolute workspace path: whether it is a git repository with a commit, '
405
+ + 'whether it is clean, how many files are changed (with a bounded path list), and the isolation to request '
406
+ + '(worktree / shared / block) with a stable reason code. '
407
+ + 'It creates no commit, stash, worktree or task and changes no setting; '
408
+ + 'passing allowShared acknowledges a dirty workspace but does not dispatch anything.',
409
+ // A read-only measurement of a directory: nothing is created or changed.
410
+ annotations: Object.freeze({
411
+ title: 'Inspect workspace before dispatch',
412
+ readOnlyHint: true,
413
+ destructiveHint: false,
414
+ idempotentHint: true,
415
+ openWorldHint: false,
416
+ }),
417
+ inputSchema: Object.freeze({
418
+ type: 'object',
419
+ properties: {
420
+ workspacePath: { type: 'string', description: 'Absolute path of the workspace to inspect.' },
421
+ allowShared: {
422
+ type: 'boolean',
423
+ description: 'Set only after deciding explicitly that a dirty workspace may run in place (shared isolation). '
424
+ + 'Omit it to be told that a decision is required instead.',
425
+ },
426
+ },
427
+ required: ['workspacePath'],
428
+ additionalProperties: false,
429
+ }),
430
+ }),
431
+ ]);
432
+
433
+ /** Tool name → the execution-plane call it makes. */
434
+ const TOOL_ROUTES = Object.freeze({
435
+ delegate_status: 'status',
436
+ delegate_submit: 'submit',
437
+ delegate_result: 'result',
438
+ delegate_wait: 'observe',
439
+ delegate_cancel: 'cancel',
440
+ delegate_permission_decide: 'permission',
441
+ delegate_preflight: 'preflight',
442
+ });
443
+
444
+ /**
445
+ * Validate one tool's arguments against its own schema.
446
+ *
447
+ * Written by hand rather than pulled from a schema validator because the shapes
448
+ * here are four small objects; a validator dependency would be the largest thing
449
+ * in this file for no extra safety.
450
+ * @param {object} tool - definition from {@link TOOLS}.
451
+ * @param {unknown} args - caller-supplied arguments.
452
+ * @returns {object} the arguments to forward.
453
+ */
454
+ function validateArgs(tool, args) {
455
+ const value = args === undefined || args === null ? {} : args;
456
+ if (typeof value !== 'object' || Array.isArray(value)) {
457
+ throw new McpError('MCP_ARGUMENTS_INVALID', `${tool.name} expects an object of arguments`);
458
+ }
459
+ const allowed = Object.keys(tool.inputSchema.properties ?? {});
460
+ for (const key of Object.keys(value)) {
461
+ if (!allowed.includes(key)) {
462
+ // An undeclared argument is a caller bug or an attempt to reach a parameter
463
+ // this surface does not have. Both are refused, and the message names the
464
+ // field so the caller can fix it.
465
+ throw new McpError('MCP_ARGUMENT_UNKNOWN', `${tool.name} does not accept argument ${JSON.stringify(key)}`);
466
+ }
467
+ }
468
+ for (const key of tool.inputSchema.required ?? []) {
469
+ const field = value[key];
470
+ if (typeof field !== 'string' || field.trim() === '') {
471
+ throw new McpError('MCP_ARGUMENT_REQUIRED', `${tool.name} requires a non-empty ${key}`);
472
+ }
473
+ }
474
+ const out = {};
475
+ for (const key of allowed) {
476
+ if (!(key in value)) continue;
477
+ const declared = tool.inputSchema.properties[key];
478
+ const field = value[key];
479
+ if (declared.type === 'string') {
480
+ if (typeof field !== 'string') throw new McpError('MCP_ARGUMENT_TYPE', `${tool.name}.${key} must be a string`);
481
+ out[key] = field;
482
+ } else if (declared.type === 'boolean') {
483
+ // Strict: a model that sends the string "true" gets a refusal naming the
484
+ // field instead of a silently truthy value reaching the plane.
485
+ if (typeof field !== 'boolean') throw new McpError('MCP_ARGUMENT_TYPE', `${tool.name}.${key} must be a boolean`);
486
+ out[key] = field;
487
+ } else if (declared.type === 'integer') {
488
+ // Strict for the same reason: `"3600"` and `3600.5` are refused with the
489
+ // field named rather than silently coerced into a deadline nobody chose.
490
+ if (!Number.isInteger(field)) throw new McpError('MCP_ARGUMENT_TYPE', `${tool.name}.${key} must be an integer`);
491
+ if (typeof declared.minimum === 'number' && field < declared.minimum) {
492
+ throw new McpError('MCP_ARGUMENT_RANGE', `${tool.name}.${key} must be at least ${declared.minimum}`);
493
+ }
494
+ if (typeof declared.maximum === 'number' && field > declared.maximum) {
495
+ throw new McpError('MCP_ARGUMENT_RANGE', `${tool.name}.${key} must be at most ${declared.maximum}`);
496
+ }
497
+ out[key] = field;
498
+ } else if (declared.type === 'object') {
499
+ if (field === null || typeof field !== 'object' || Array.isArray(field)) {
500
+ throw new McpError('MCP_ARGUMENT_TYPE', `${tool.name}.${key} must be an object`);
501
+ }
502
+ out[key] = field;
503
+ } else {
504
+ out[key] = field;
505
+ }
506
+ if (Array.isArray(declared.enum) && !declared.enum.includes(out[key])) {
507
+ throw new McpError('MCP_ARGUMENT_ENUM', `${tool.name}.${key} must be one of ${declared.enum.join(', ')}`);
508
+ }
509
+ }
510
+ return out;
511
+ }
512
+
513
+ // ---------------------------------------------------------------------------
514
+ // Bounded projection
515
+ // ---------------------------------------------------------------------------
516
+ //
517
+ // A tool result is consumed by `JSON.parse`, not by a human reading a wall of
518
+ // text. The previous implementation enforced the bound by slicing the raw
519
+ // serialized JSON and appending a plain note, which produced text that began as
520
+ // JSON and ended as prose: every `delegate_result` over the bound was unparsable,
521
+ // and a coordinator whose audit diff was large enough to cross it saw
522
+ // `JSON.parse` fail and had to abandon the delegation. An unparsable answer is
523
+ // worse than a smaller answer, so the bound is now enforced *before*
524
+ // serialization, on the structure itself.
525
+ //
526
+ // The projection is deliberately field-aware rather than generic. A truncated
527
+ // result must still let a caller act, so identity, state, phase, routing,
528
+ // refusal and acceptance status are always kept intact; heavy evidence
529
+ // (diff/evidence/prompt) is trimmed to a headline first, and bounded prose
530
+ // (execution and review text) second. Everything that was cut is listed by path
531
+ // under a top-level `truncation` object, so "this list is short" is never
532
+ // mistaken for "this list was short".
533
+ //
534
+ // If even that cannot fit — a single critical field too large to serialize — the
535
+ // result is not labelled full and is not silently returned: it becomes an
536
+ // explicit `MCP_RESULT_OVER_BUDGET` tool error that still carries the task
537
+ // identity, so a caller can tell "the content did not fit" from "no such task".
538
+
539
+ /** Fields trimmed first: evidence whose size is the caller's, not the answer's. */
540
+ const HEAVY_FIELDS = Object.freeze(['diff', 'evidence', 'prompt']);
541
+
542
+ /**
543
+ * Field-level caps that survive into a truncated answer. Each is a *ceiling*, not
544
+ * a target: a projection over the overall bound is shrunk further, in the order
545
+ * named above, until it fits.
546
+ */
547
+ const TRUNCATED_FIELD_CAPS = Object.freeze({
548
+ /** Diff patch text kept when the whole result does not fit (0 = headline only). */
549
+ diffPatchChars: 0,
550
+ /** Captured validation evidence kept per entry and overall. */
551
+ evidenceEntryChars: 160,
552
+ evidenceChars: 800,
553
+ evidenceEntries: 8,
554
+ /** The submitted prompt is never quoted in a truncated answer. */
555
+ promptChars: 0,
556
+ /** Bounded execution prose. */
557
+ executionTextChars: 1_200,
558
+ /** Bounded review prose. */
559
+ reviewTextChars: 1_200,
560
+ /** Per-entry cap for a list that is itself being cut (tasks, files, changes). */
561
+ listItemChars: 2_000,
562
+ });
563
+
564
+ /** How deep the projection descends before it states a depth limit. */
565
+ const MAX_PROJECTION_DEPTH = 10;
566
+ const DEPTH_LIMIT_MARKER = '[depth limit: nested value not projected]';
567
+
568
+ /**
569
+ * Whether a value can be serialized at all.
570
+ *
571
+ * `JSON.stringify` throws on a bigint and on a cycle, and silently turns a
572
+ * function into nothing. All three would make the projected answer describe
573
+ * something other than what was received, so they are checked up front and are
574
+ * what `MCP_RESULT_UNSERIALIZABLE` reports.
575
+ * @param {unknown} value - value to test.
576
+ * @returns {boolean} true when the value round-trips through JSON.
577
+ */
578
+ function isJsonProjectable(value) {
579
+ const stack = new Set();
580
+ const walk = (node) => {
581
+ if (node === null) return true;
582
+ const type = typeof node;
583
+ if (type === 'string' || type === 'boolean') return true;
584
+ if (type === 'number') return Number.isFinite(node);
585
+ if (type === 'bigint' || type === 'function' || type === 'symbol' || type === 'undefined') return false;
586
+ if (type !== 'object') return false;
587
+ if (stack.has(node)) return false;
588
+ stack.add(node);
589
+ const values = Array.isArray(node) ? node : Object.values(node);
590
+ const ok = values.every(walk);
591
+ stack.delete(node);
592
+ return ok;
593
+ };
594
+ return walk(value);
595
+ }
596
+
597
+ /**
598
+ * Serialize once, at one indentation. JSON's escaping rules do not depend on
599
+ * indentation, so a length measured compact is a valid upper bound for the same
600
+ * value measured pretty, and {@link fitsBound} accepts either encoding.
601
+ * @param {unknown} value - JSON value.
602
+ * @returns {string} compact JSON text.
603
+ */
604
+ function compactJson(value) {
605
+ return JSON.stringify(value);
606
+ }
607
+
608
+ /**
609
+ * Whether a projected value fits the tool-text bound in either encoding.
610
+ *
611
+ * The bound must hold for *both* the compact and the two-space encoding because
612
+ * the published answer alone is not the whole JSON a client parses: a client that
613
+ * re-serializes it, or a host that pretty-prints the envelope, must not be able to
614
+ * push past {@link MAX_TOOL_TEXT_CHARS}.
615
+ * @param {unknown} value - projected JSON value.
616
+ * @returns {boolean} true when the value fits.
617
+ */
618
+ function fitsBound(value) {
619
+ const compact = compactJson(value);
620
+ if (compact.length > MAX_TOOL_TEXT_CHARS) return false;
621
+ return JSON.stringify(value, null, 2).length <= MAX_TOOL_TEXT_CHARS;
622
+ }
623
+
624
+ /**
625
+ * Explain what was cut out of a container, in the index space of the returned
626
+ * list, so a reader is never left inferring that the short list was all there was.
627
+ * @param {string} path - JSON path of the container.
628
+ * @param {object} options - `total`, `omitted` (count), `detail` (extra note).
629
+ * @returns {object} truncation record.
630
+ */
631
+ function truncationRecord(path, options) {
632
+ const record = { path, field: 'list', omitted: options.omitted };
633
+ if (options.total !== undefined) record.total = options.total;
634
+ if (typeof options.detail === 'string') record.detail = options.detail;
635
+ return record;
636
+ }
637
+
638
+ /**
639
+ * Trim one string to a cap, stating the trim.
640
+ * @param {string} text - source text.
641
+ * @param {number} cap - characters to keep.
642
+ * @param {string} path - JSON path, for the truncation record.
643
+ * @param {object[]} out - records collected so far.
644
+ * @returns {string} kept text (possibly empty).
645
+ */
646
+ function boundedText(text, cap, path, out) {
647
+ if (text.length <= cap) return text;
648
+ out.push({ path, field: 'text', keptChars: cap, omittedChars: text.length - cap });
649
+ return text.slice(0, cap);
650
+ }
651
+
652
+ /**
653
+ * Recursively trim every string in a value to one cap, stating each cut.
654
+ *
655
+ * Used only by the terminal projection stage, where the answer is already
656
+ * skeletonized and this catches whatever prose is left (a path list, a refusal
657
+ * message). It is a safety net, not the primary strategy: field-aware trimming
658
+ * above keeps the actionable parts intact, and this runs after them.
659
+ * @param {unknown} value - value to trim.
660
+ * @param {string} path - JSON path.
661
+ * @param {number} cap - characters to keep per string.
662
+ * @param {object[]} collect - truncation records.
663
+ * @param {number} [depth] - recursion depth.
664
+ * @returns {unknown} trimmed value.
665
+ */
666
+ function trimAllStrings(value, path, cap, collect, depth = 0) {
667
+ if (typeof value === 'string') return boundedText(value, cap, path, collect);
668
+ if (value === null || typeof value !== 'object') return value;
669
+ if (depth > MAX_PROJECTION_DEPTH) {
670
+ collect.push({ path, field: 'value', detail: DEPTH_LIMIT_MARKER });
671
+ return null;
672
+ }
673
+ if (Array.isArray(value)) {
674
+ return value.map((entry, index) => trimAllStrings(entry, `${path}[${index}]`, cap, collect, depth + 1));
675
+ }
676
+ const out = {};
677
+ for (const [key, item] of Object.entries(value)) {
678
+ const childPath = path === '' ? key : `${path}.${key}`;
679
+ out[key] = trimAllStrings(item, childPath, cap, collect, depth + 1);
680
+ }
681
+ return out;
682
+ }
683
+
684
+ /**
685
+ * Replace one heavy field with a bounded summary that keeps its shape.
686
+ * @param {unknown} source - field value.
687
+ * @param {string} path - JSON path.
688
+ * @param {object[]} collect - truncation records.
689
+ * @returns {unknown} bounded replacement.
690
+ */
691
+ function reduceHeavy(source, path, collect) {
692
+ if (source === null || source === undefined) return source;
693
+ if (typeof source === 'string') {
694
+ return boundedText(source, 0, path, collect);
695
+ }
696
+ if (typeof source !== 'object') return source;
697
+ if (Array.isArray(source)) {
698
+ const keep = Math.min(source.length, TRUNCATED_FIELD_CAPS.evidenceEntries);
699
+ if (source.length > keep) collect.push(truncationRecord(path, { total: source.length, omitted: source.length - keep }));
700
+ return source.slice(0, keep).map((entry, index) => {
701
+ if (typeof entry === 'string') {
702
+ return boundedText(entry, TRUNCATED_FIELD_CAPS.evidenceEntryChars, `${path}[${index}]`, collect);
703
+ }
704
+ return entry;
705
+ });
706
+ }
707
+ const out = {};
708
+ // Recorded rather than assigned in the loop: `patchTruncated` normally precedes
709
+ // `patchText` in the source object, so an assignment made while visiting
710
+ // `patchText` would be overwritten by the original `false` a moment later.
711
+ let patchCut = false;
712
+ for (const [key, value] of Object.entries(source)) {
713
+ const childPath = `${path}.${key}`;
714
+ if (typeof value === 'string') {
715
+ const cap = key === 'patchText' ? TRUNCATED_FIELD_CAPS.diffPatchChars : TRUNCATED_FIELD_CAPS.evidenceEntryChars;
716
+ out[key] = boundedText(value, cap, childPath, collect);
717
+ if (key === 'patchText' && value.length > cap) patchCut = true;
718
+ continue;
719
+ }
720
+ if (Array.isArray(value)) {
721
+ const keep = Math.min(value.length, TRUNCATED_FIELD_CAPS.evidenceEntries);
722
+ if (value.length > keep) collect.push(truncationRecord(childPath, { total: value.length, omitted: value.length - keep }));
723
+ out[key] = value.slice(0, keep).map((entry, index) => (typeof entry === 'string'
724
+ ? boundedText(entry, TRUNCATED_FIELD_CAPS.evidenceEntryChars, `${childPath}[${index}]`, collect)
725
+ : entry));
726
+ continue;
727
+ }
728
+ out[key] = value;
729
+ }
730
+ // Only ever turns the flag on: the engine's own `patchTruncated` (a patch it had
731
+ // already cut) must not be cleared by this projection.
732
+ if (patchCut) out.patchTruncated = true;
733
+ return out;
734
+ }
735
+
736
+ /**
737
+ * Copy a value without losing JSON-compatible structure.
738
+ * @param {unknown} value - JSON value.
739
+ * @returns {unknown} independent copy.
740
+ */
741
+ function structuredCloneSafe(value) {
742
+ return JSON.parse(JSON.stringify(value));
743
+ }
744
+
745
+ /**
746
+ * Paths of the task-shaped objects inside one answer, keyed by identity.
747
+ * @param {object} value - answer.
748
+ * @returns {Map<object, string>} object → JSON path.
749
+ */
750
+ function pathsFor(value) {
751
+ const map = new Map();
752
+ if (value?.task !== null && typeof value?.task === 'object' && !Array.isArray(value.task)) map.set(value.task, 'task.');
753
+ if (Array.isArray(value?.tasks)) {
754
+ for (let index = 0; index < value.tasks.length; index += 1) {
755
+ const task = value.tasks[index];
756
+ if (task !== null && typeof task === 'object' && !Array.isArray(task)) map.set(task, `tasks[${index}].`);
757
+ }
758
+ }
759
+ return map;
760
+ }
761
+
762
+ /**
763
+ * Trim the projected answer until it fits the bound, in a fixed order that
764
+ * sacrifices the least actionable content last.
765
+ *
766
+ * Every stage keeps the task identity, state, phase, routing, refusal and
767
+ * acceptance fields; they differ only in how much evidence and prose survives.
768
+ * The first stage drops the patch text and the whole prompt (their file lists and
769
+ * counts remain); later stages shorten execution and review prose, then cap list
770
+ * lengths, and the last stage skeletonizes the task down to those critical fields
771
+ * with a short per-string cap. Every cut is stated in `truncation.fields`.
772
+ * @param {object} value - answer.
773
+ * @param {{executionText: number, reviewText: number, lists: number, skeletonChars?: number}} stage - caps.
774
+ * @param {object[]} collect - truncation records.
775
+ * @returns {unknown} projected answer.
776
+ */
777
+ function projectWithStage(value, stage, collect) {
778
+ const projected = structuredCloneSafe(value);
779
+ const targets = pathsFor(projected);
780
+ for (const [target, prefix] of targets) {
781
+ for (const key of HEAVY_FIELDS) {
782
+ if (!(key in target)) continue;
783
+ target[key] = reduceHeavy(target[key], `${prefix}${key}`, collect);
784
+ }
785
+ if (target.execution !== null && typeof target.execution === 'object' && typeof target.execution.text === 'string') {
786
+ target.execution.text = boundedText(
787
+ target.execution.text, stage.executionText, `${prefix}execution.text`, collect,
788
+ );
789
+ }
790
+ if (target.review !== null && typeof target.review === 'object' && typeof target.review.text === 'string') {
791
+ target.review.text = boundedText(target.review.text, stage.reviewText, `${prefix}review.text`, collect);
792
+ }
793
+ if (typeof target.reviewRouteError === 'string') {
794
+ target.reviewRouteError = boundedText(target.reviewRouteError, stage.skeletonChars ?? 400, `${prefix}reviewRouteError`, collect);
795
+ }
796
+ // The settled decision trail is HISTORY; the pending request is the thing the
797
+ // commander must act on NOW. Under a bound the history goes first, so a running
798
+ // task can never keep an outstanding request invisible behind old evidence.
799
+ const permission = target.permission;
800
+ if (permission !== null && typeof permission === 'object' && Array.isArray(permission.evidence)) {
801
+ const keep = Math.min(permission.evidence.length, stage.permissionEvidence);
802
+ if (permission.evidence.length > keep) {
803
+ collect.push(truncationRecord(`${prefix}permission.evidence`, {
804
+ total: permission.evidence.length,
805
+ omitted: permission.evidence.length - keep,
806
+ detail: 'the live pending request is prioritised over settled history',
807
+ }));
808
+ // `slice(-0)` keeps EVERY entry, so the zero-keep stage would claim a drop
809
+ // it did not perform and then still publish the history it said it removed.
810
+ permission.evidence = keep === 0 ? [] : permission.evidence.slice(-keep);
811
+ }
812
+ }
813
+ }
814
+ if (Array.isArray(projected.tasks) && projected.tasks.length > stage.lists) {
815
+ collect.push(truncationRecord('tasks', { total: projected.tasks.length, omitted: projected.tasks.length - stage.lists }));
816
+ projected.tasks = projected.tasks.slice(0, stage.lists);
817
+ }
818
+ if (stage.skeletonChars !== undefined) {
819
+ const cap = stage.skeletonChars;
820
+ if (projected.task !== undefined) projected.task = skeletonize(projected.task, 'task', cap, collect);
821
+ if (Array.isArray(projected.tasks)) {
822
+ projected.tasks = projected.tasks.map((task, index) => skeletonize(task, `tasks[${index}]`, cap, collect));
823
+ }
824
+ // Anything else at the top level (a status answer's grants, a list's extras)
825
+ // is trimmed rather than dropped, so nothing disappears unexplained. The
826
+ // exception is `permission`: a wait answer publishes the pending operation there,
827
+ // and a generic per-string cut would shorten the operation WITHOUT updating
828
+ // `argumentsComplete`/`allowBlocked`, publishing a shortened operation that still
829
+ // reads as complete. It is bounded by the permission rule instead.
830
+ for (const [key, item] of Object.entries(projected)) {
831
+ if (key === 'task' || key === 'tasks' || key === 'ok') continue;
832
+ projected[key] = key === 'permission'
833
+ ? boundPermissionBlock(item, key, collect)
834
+ : trimAllStrings(item, key, cap, collect);
835
+ }
836
+ }
837
+ return projected;
838
+ }
839
+
840
+ /**
841
+ * The identity, state, routing, refusal and acceptance block that is never
842
+ * dropped, renderable even when nothing else fits.
843
+ * @param {object} task - task view.
844
+ * @param {string} path - JSON path prefix.
845
+ * @param {number} cap - per-string cap.
846
+ * @param {object[]} collect - truncation records.
847
+ * @returns {object} skeleton.
848
+ */
849
+ function skeletonize(task, path, cap, collect) {
850
+ if (task === null || typeof task !== 'object' || Array.isArray(task)) return task ?? null;
851
+ const pick = (key) => (key in task ? boundValue(task[key], `${path}.${key}`, cap, collect) : undefined);
852
+ const out = {};
853
+ for (const key of ['taskId', 'state', 'phase', 'route', 'reviewRoute', 'reviewRouteError', 'execution', 'error',
854
+ 'hostAcceptance', 'selfApproved', 'cancelledBy', 'createdAt', 'endedAt']) {
855
+ const value = pick(key);
856
+ if (value === undefined) continue;
857
+ if (key === 'execution' && value !== null && typeof value === 'object') {
858
+ out.execution = {};
859
+ for (const field of ['outcome', 'reasoningOnly', 'usage', 'turnEnd', 'agentId', 'cancelCause', 'error']) {
860
+ if (field in value) out.execution[field] = boundValue(value[field], `${path}.execution.${field}`, cap, collect);
861
+ }
862
+ } else if (key === 'route' || key === 'reviewRoute') {
863
+ out[key] = value === null ? null : boundValue(value, `${path}.${key}`, cap, collect);
864
+ } else {
865
+ out[key] = value;
866
+ }
867
+ }
868
+ // The LIVE pending permission request is the one thing a commander must keep when
869
+ // everything else is trimmed: without its `requestId`/`fingerprint`/operation the
870
+ // task stays `awaiting-permission` and nothing can be decided. It gets its OWN,
871
+ // generous caps rather than the skeleton's per-string cap, so the identity and the
872
+ // operation survive, and its completeness flags are carried VERBATIM so a shortened
873
+ // operation can never read as complete.
874
+ const pending = pendingPermissionsOf(task, path, collect);
875
+ if (pending !== undefined) out.permission = pending;
876
+ out.truncation = { path, field: 'result', detail: 'only identity, state, routing, refusal, acceptance and the live pending permission request are shown' };
877
+ collect.push(out.truncation);
878
+ return out;
879
+ }
880
+
881
+ /**
882
+ * The live pending permission request of one task, bounded but never skeletal.
883
+ *
884
+ * Only `state === 'pending'` qualifies: settled evidence is history and is the first
885
+ * thing the bound gives up, while an outstanding request is the decision surface
886
+ * itself. The per-field caps are fixed and generous (identity and fingerprint are
887
+ * never cut; the argument blobs get their own cap), and `completeness` /
888
+ * `argumentsComplete` / `allowBlocked` are copied unchanged so a shortened operation
889
+ * cannot be presented as reviewable.
890
+ *
891
+ * Only FINAL cuts are recorded. The generic walk applies a small per-string cap to
892
+ * every field, and then the decision surface is restored to its real value (or its
893
+ * own 4000-character blob cap). A walk cut on a restored field no longer describes
894
+ * the output — the walk once left `truncation.fields` naming a phantom cut on a
895
+ * fully restored 1500-character operation — so the walk collects into a scratch list
896
+ * and only the cuts that survive into the published block are reported.
897
+ * `argumentsComplete: false` / `allowBlocked` still come from the engine, so a
898
+ * genuinely shortened operation can never read as complete.
899
+ * @param {object} task - task view.
900
+ * @param {string} path - JSON path prefix for truncation records.
901
+ * @param {object[]} collect - truncation records.
902
+ * @returns {object | undefined} the bounded pending block, or undefined when none.
903
+ */
904
+ function pendingPermissionsOf(task, path, collect) {
905
+ const permission = task?.permission;
906
+ if (permission === null || typeof permission !== 'object') return undefined;
907
+ const pending = permission.pending;
908
+ if (pending === null || typeof pending !== 'object' || pending.state !== 'pending') return undefined;
909
+ const prefix = `${path}.permission.pending`;
910
+ // Provisional cuts, discarded: every field they touch is restored or re-cut below.
911
+ const scratched = [];
912
+ const out = { ...boundValue(pending, prefix, 512, scratched) };
913
+ // Restore the decision surface EXACTLY after the generic walk.
914
+ for (const key of ['requestId', 'taskId', 'toolName', 'callId', 'fingerprint', 'sessionId']) {
915
+ if (pending[key] !== undefined) out[key] = pending[key];
916
+ }
917
+ for (const key of ['state', 'completeness', 'argumentsComplete', 'allowBlocked', 'reasonSource', 'boundsApplied', 'omitted', 'requestedAccess']) {
918
+ if (pending[key] !== undefined) out[key] = pending[key];
919
+ }
920
+ // The two blobs get their own cap, stated when it fires. This is the only cut for
921
+ // them, because the capped value is what is published.
922
+ for (const key of ['arguments', 'reason']) {
923
+ if (typeof pending[key] === 'string') out[key] = boundedText(pending[key], 4000, `${prefix}.${key}`, collect);
924
+ }
925
+ // One identified: the provisional cap still applies to it, so the scratch list
926
+ // holds no final cut to forward. Report the exception explicitly instead of a cut,
927
+ // so the record explains why an unexpected field may be shorter than the original.
928
+ if (scratched.length > 0) {
929
+ collect.push({
930
+ path: `${path}.permission.pending`,
931
+ field: 'detail',
932
+ keptChars: 512,
933
+ detail: 'fields other than the decision surface are bounded to 512 characters each',
934
+ });
935
+ }
936
+ return { bridged: permission.bridged === true, waiting: true, pending: out };
937
+ }
938
+
939
+ /**
940
+ * The keys of a pending permission request that a decision is bound to.
941
+ *
942
+ * A value under one of these keys is copied VERBATIM: cutting an identity would
943
+ * make the request undecidable, and cutting the `completeness` flags would let a
944
+ * shortened operation read as a decidable one — which is exactly the property the
945
+ * per-call permission boundary depends on.
946
+ */
947
+ const PERMISSION_IDENTITY_KEYS = Object.freeze([
948
+ 'requestId', 'taskId', 'sessionId', 'toolName', 'callId', 'state', 'completeness',
949
+ 'argumentsComplete', 'allowBlocked', 'reasonSource', 'boundsApplied', 'omitted',
950
+ 'requestedAccess', 'argumentKeys', 'argumentsRedacted', 'fingerprint', 'standingModeUnchanged',
951
+ ]);
952
+
953
+ /**
954
+ * The blobs of a pending permission request, and the cap applied to each.
955
+ *
956
+ * `reason` is the worker's claim and `arguments` is the operation; both are prose
957
+ * from a model, so both are bounded — but at a cap large enough for a real tool
958
+ * call. When the cap fires, `boundsApplied` gains this server's own marker and
959
+ * `argumentsComplete` is forced to `false` in {@link boundPermissionRequest}, so a
960
+ * shortened operation is never presented as complete.
961
+ */
962
+ const PERMISSION_BLOB_CAP = 4_000;
963
+
964
+ /**
965
+ * Bound one pending permission request without ever making it look decidable when
966
+ * it is not.
967
+ *
968
+ * The rule this encodes: `boundedJson` may shorten anything, but it may not change
969
+ * the MEANING of the permission surface. Identity fields and the completeness flags
970
+ * pass through untouched; the two prose blobs are capped, and a fired cap is
971
+ * recorded in `boundsApplied` and reflected in `argumentsComplete: false` /
972
+ * `allowBlocked`. The engine's own `completeness` label is left as it is (this
973
+ * projection never upgrades `truncated` to `complete`), and no path here can set any
974
+ * of those flags back to a permissive value.
975
+ * @param {object} pending - pending permission record.
976
+ * @param {string} path - JSON path for the truncation records.
977
+ * @param {object[]} collect - truncation records.
978
+ * @returns {object} bounded pending record.
979
+ */
980
+ function boundPermissionRequest(pending, path, collect) {
981
+ if (pending === null || typeof pending !== 'object' || Array.isArray(pending)) return pending ?? null;
982
+ const out = {};
983
+ const ownCuts = [];
984
+ for (const [key, value] of Object.entries(pending)) {
985
+ if (PERMISSION_IDENTITY_KEYS.includes(key)) {
986
+ out[key] = value;
987
+ continue;
988
+ }
989
+ if ((key === 'arguments' || key === 'reason') && typeof value === 'string' && value.length > PERMISSION_BLOB_CAP) {
990
+ out[key] = boundedText(value, PERMISSION_BLOB_CAP, `${path}.${key}`, collect);
991
+ ownCuts.push(key);
992
+ continue;
993
+ }
994
+ out[key] = boundValue(value, `${path}.${key}`, 512, collect);
995
+ }
996
+ if (ownCuts.length > 0) {
997
+ // Both flags are only ever made LESS permissive. `completeness` is downgraded
998
+ // because the published operation is no longer the whole one; `argumentsComplete`
999
+ // becomes false for the same reason; `allowBlocked` gains a reason when the
1000
+ // engine had not already supplied one.
1001
+ out.completeness = pending.completeness === 'complete' ? 'truncated' : (pending.completeness ?? 'truncated');
1002
+ out.argumentsComplete = false;
1003
+ if (out.allowBlocked === null || out.allowBlocked === undefined) {
1004
+ out.allowBlocked = 'the operation was shortened by the tool-text bound, so an allow cannot be granted on it';
1005
+ }
1006
+ const applied = Array.isArray(pending.boundsApplied) ? pending.boundsApplied.slice() : [];
1007
+ if (!applied.includes('mcp-text')) applied.push('mcp-text');
1008
+ out.boundsApplied = applied;
1009
+ collect.push({
1010
+ path: `${path}`,
1011
+ field: 'permission',
1012
+ detail: 'the published operation was shortened by the tool-text bound; it remains marked unapprovable',
1013
+ });
1014
+ }
1015
+ return out;
1016
+ }
1017
+
1018
+ /**
1019
+ * Whether a pending operation, as it stands, can be decided `allow-once`.
1020
+ *
1021
+ * One place, one rule: the answer a host reads and the flag this server publishes
1022
+ * must agree, so the rule is a function rather than a duplicated expression.
1023
+ * @param {object} pendingOperation - pending operation (possibly bounded).
1024
+ * @returns {boolean} true only for a whole, unblocked operation.
1025
+ */
1026
+ export function isPermissionDecidable(pendingOperation) {
1027
+ if (pendingOperation === null || typeof pendingOperation !== 'object') return false;
1028
+ if (pendingOperation.state !== undefined && pendingOperation.state !== 'pending') return false;
1029
+ if (pendingOperation.argumentsComplete !== true) return false;
1030
+ if (pendingOperation.allowBlocked !== null && pendingOperation.allowBlocked !== undefined) return false;
1031
+ if (pendingOperation.completeness !== undefined && pendingOperation.completeness !== 'complete') return false;
1032
+ return true;
1033
+ }
1034
+
1035
+ /**
1036
+ * Bound a leaf value for a skeleton.
1037
+ * @param {unknown} value - value.
1038
+ * @param {string} path - JSON path.
1039
+ * @param {number} cap - per-string cap.
1040
+ * @param {object[]} collect - records.
1041
+ * @returns {unknown} bounded value.
1042
+ */
1043
+ function boundValue(value, path, cap, collect) {
1044
+ if (typeof value === 'string') return boundedText(value, cap, path, collect);
1045
+ if (value === null || typeof value !== 'object') return value;
1046
+ if (Array.isArray(value)) {
1047
+ return value.slice(0, 8).map((entry, index) => boundValue(entry, `${path}[${index}]`, cap, collect));
1048
+ }
1049
+ const out = {};
1050
+ for (const [key, item] of Object.entries(value)) {
1051
+ // A pending permission request nested in ANY task-shaped record (a list answer,
1052
+ // a skeletonised task) still has to be decidable, so it is bounded by its own
1053
+ // rule rather than by the generic per-string cap. Recognising it here, at every
1054
+ // depth, is what makes the guarantee hold for every tool answer and not only
1055
+ // for the shapes this file happens to special-case.
1056
+ if (key === 'permission' && item !== null && typeof item === 'object' && !Array.isArray(item)) {
1057
+ out[key] = boundPermissionBlock(item, `${path}.permission`, collect);
1058
+ continue;
1059
+ } out[key] = boundValue(item, `${path}.${key}`, cap, collect);
1060
+ }
1061
+ return out;
1062
+ }
1063
+
1064
+ /**
1065
+ * Bound a task's permission block, preserving its live pending request.
1066
+ * @param {object} permission - permission block.
1067
+ * @param {string} path - JSON path.
1068
+ * @param {object[]} collect - truncation records.
1069
+ * @returns {object} bounded block.
1070
+ */
1071
+ function boundPermissionBlock(permission, path, collect) {
1072
+ // A bare pending operation (the shape a wait answer publishes, and the shape the
1073
+ // engine's `observeTask` contract describes) is bounded as a REQUEST, not as a
1074
+ // block: recognising it by its own identity fields means the same rule applies
1075
+ // however a particular answer happens to nest it.
1076
+ if (typeof permission.requestId === 'string' && typeof permission.state === 'string'
1077
+ && permission.state === 'pending') {
1078
+ return boundPermissionRequest(permission, path, collect);
1079
+ }
1080
+ const out = {};
1081
+ let preserved = false;
1082
+ for (const [key, value] of Object.entries(permission)) {
1083
+ if (key === 'pending' && value !== null && typeof value === 'object' && value.state === 'pending') {
1084
+ out[key] = boundPermissionRequest(value, `${path}.pending`, collect);
1085
+ preserved = true;
1086
+ // A preserved request is DECISION MATERIAL, not history. It is restored the
1087
+ // way the skeleton stage restores it: not reported as a cut merely because it
1088
+ // was bounded on its own terms.
1089
+ collect.push({
1090
+ path: `${path}.pending`,
1091
+ field: 'detail',
1092
+ detail: 'the live pending request is carried in full except for its own blob caps, and stays marked unapprovable when shortened',
1093
+ });
1094
+ continue;
1095
+ }
1096
+ out[key] = boundValue(value, `${path}.${key}`, 512, collect);
1097
+ }
1098
+ if (preserved) out.waiting = true;
1099
+ return out;
1100
+ }
1101
+
1102
+ /**
1103
+ * Build a structurally bounded, still-valid JSON answer.
1104
+ *
1105
+ * `ok` keeps its meaning: the payload is either the real answer or an explicit
1106
+ * failure object. A result that cannot be projected writes itself is never
1107
+ * returned as if it were complete, and never returned as truncated raw text.
1108
+ *
1109
+ * `isError` is true only when the answer could not be delivered at all
1110
+ * (`MCP_RESULT_UNSERIALIZABLE`, `MCP_RESULT_OVER_BUDGET`). A structurally trimmed
1111
+ * answer is *not* an error: it is a real answer with an explicit, machine-readable
1112
+ * `truncation` block, which lets a caller act on the parts that survived. The
1113
+ * distinction matters because a truncated result must never be presented as a
1114
+ * failure when the task itself succeeded.
1115
+ * @param {unknown} value - JSON-serializable answer.
1116
+ * @returns {{ text: string, isError: boolean }} bounded, valid JSON text.
1117
+ */
1118
+ function boundedJson(value) {
1119
+ if (!isJsonProjectable(value)) {
1120
+ return refuseResult('MCP_RESULT_UNSERIALIZABLE', 'the delegated call answered with a value that cannot be represented as JSON');
1121
+ }
1122
+ let compact;
1123
+ try {
1124
+ compact = compactJson(value);
1125
+ } catch {
1126
+ return refuseResult('MCP_RESULT_UNSERIALIZABLE', 'the delegated call answered with a value that could not be serialized');
1127
+ }
1128
+ if (fitsBound(value)) return { text: JSON.stringify(redactDeepStrings(value), null, 2), isError: false };
1129
+
1130
+ const stages = [
1131
+ { executionText: TRUNCATED_FIELD_CAPS.executionTextChars, reviewText: TRUNCATED_FIELD_CAPS.reviewTextChars, lists: 50, permissionEvidence: 8 },
1132
+ { executionText: 400, reviewText: 400, lists: 20, permissionEvidence: 4 },
1133
+ { executionText: 200, reviewText: 200, lists: 5, permissionEvidence: 2 },
1134
+ { executionText: 120, reviewText: 120, lists: 1, permissionEvidence: 1 },
1135
+ { executionText: 80, reviewText: 80, lists: 1, permissionEvidence: 0, skeletonChars: 240 },
1136
+ { executionText: 40, reviewText: 40, lists: 1, permissionEvidence: 0, skeletonChars: 96 },
1137
+ ];
1138
+ const apply = (stage) => {
1139
+ const records = [];
1140
+ const projected = projectWithStage(value, stage, records);
1141
+ projected.truncation = {
1142
+ truncated: true,
1143
+ reason: 'the full answer exceeded the tool-text bound',
1144
+ fullTextChars: compact.length,
1145
+ boundChars: MAX_TOOL_TEXT_CHARS,
1146
+ // Stated so a caller can tell a structurally trimmed answer from a short
1147
+ // one, and so "bounded" is never read as "complete".
1148
+ fullResultIncluded: false,
1149
+ fields: dedupeRecords(records),
1150
+ };
1151
+ // A wait answer publishes `permissionDecidable`, and a bound may have shortened
1152
+ // the operation it describes. Recomputing the flag from the PUBLISHED operation
1153
+ // is what stops a cut operation from being advertised as decidable.
1154
+ if (projected.permission !== undefined && projected.permission !== null) {
1155
+ projected.permissionDecidable = isPermissionDecidable(projected.permission);
1156
+ }
1157
+ return JSON.stringify(redactDeepStrings(projected), null, 2);
1158
+ };
1159
+ for (const stage of stages) {
1160
+ const text = apply(stage);
1161
+ if (text.length <= MAX_TOOL_TEXT_CHARS) return { text, isError: false };
1162
+ }
1163
+
1164
+ // The refusal path is reached only when nothing above fits. An answer that carries
1165
+ // a LIVE pending permission request is different from any other oversized answer:
1166
+ // dropping it would leave the task paused and undecidable from what the host was
1167
+ // told. So before refusing, the answer is reduced to those requests alone — with
1168
+ // their blobs re-capped to whatever the bound leaves — and published under an
1169
+ // explicit `permissionOnly` marker that states the rest was not included. When
1170
+ // even this does not fit, the refusal below stands: a trimmed request must never
1171
+ // be presented as an answer.
1172
+ const rescue = permissionRescue(value, compact.length);
1173
+ if (rescue !== null) {
1174
+ for (const cap of [4_000, 1_000, 400, 160, 0]) {
1175
+ const text = rescue(cap);
1176
+ if (text.length <= MAX_TOOL_TEXT_CHARS) return { text, isError: false };
1177
+ }
1178
+ }
1179
+
1180
+ // Nothing projected fits. The answer is refused as data, carrying the task
1181
+ // identity when it can: the caller learns which task the content belonged to
1182
+ // and why the result was not delivered, instead of receiving a cut fragment
1183
+ // that looks like an answer.
1184
+ const identity = {};
1185
+ if (value?.task !== null && typeof value?.task === 'object' && !Array.isArray(value.task)) {
1186
+ if (value.task.taskId !== undefined) identity.taskId = truncateScalar(value.task.taskId);
1187
+ if (value.task.state !== undefined) identity.state = truncateScalar(value.task.state);
1188
+ }
1189
+ if (Array.isArray(value?.tasks)) {
1190
+ identity.tasks = value.tasks.slice(0, 5).map((task) => ({ taskId: truncateScalar(task?.taskId) }));
1191
+ }
1192
+ return refuseResult(
1193
+ 'MCP_RESULT_OVER_BUDGET',
1194
+ 'the critical fields alone exceed the tool-text bound, so no usable projection could be produced',
1195
+ { ...identity, fullTextChars: compact.length, boundChars: MAX_TOOL_TEXT_CHARS },
1196
+ );
1197
+ }
1198
+
1199
+ /**
1200
+ * Build a last-resort projection that keeps only the live pending permission
1201
+ * requests of an oversized answer.
1202
+ *
1203
+ * The ORDER is fixed and the caps are tried by the caller: identity first, then a
1204
+ * smaller operation blob. `completeness`/`argumentsComplete`/`allowBlocked` are
1205
+ * always carried as the engine states them (or downgraded by the capping), so a
1206
+ * shortened request still cannot be allowed.
1207
+ * @param {unknown} value - the answer that did not fit.
1208
+ * @param {number} fullTextChars - size of the original answer, for the record.
1209
+ * @returns {((cap: number) => string) | null} renderer, or null when the answer
1210
+ * carries no live pending request.
1211
+ */
1212
+ function permissionRescue(value, fullTextChars) {
1213
+ const entries = [];
1214
+ const collectTask = (task, path) => {
1215
+ const block = task?.permission;
1216
+ const pending = block?.pending;
1217
+ if (pending === null || typeof pending !== 'object' || pending.state !== 'pending') return;
1218
+ entries.push({ path, taskId: task.taskId, state: task.state, phase: task.phase, block, pending });
1219
+ };
1220
+ if (value?.task !== null && typeof value?.task === 'object' && !Array.isArray(value.task)) collectTask(value.task, 'task');
1221
+ if (Array.isArray(value?.tasks)) value.tasks.forEach((task, index) => collectTask(task, `tasks[${index}]`));
1222
+ // A WAIT answer publishes the pending operation directly as `permission` rather
1223
+ // than under `task.permission.pending`. It is the one shape where the whole point
1224
+ // of the answer is the operation, so it earns the same rescue: shorten the
1225
+ // operation, never drop it and never let it read as complete.
1226
+ const bare = value?.permission;
1227
+ if (bare !== null && typeof bare === 'object' && bare.state === 'pending' && typeof bare.requestId === 'string') {
1228
+ entries.push({
1229
+ path: 'permission', taskId: value.taskId, state: value.state, phase: value.phase, block: null, pending: bare, bare: true,
1230
+ });
1231
+ }
1232
+ if (entries.length === 0) return null;
1233
+ return (cap) => {
1234
+ const records = [];
1235
+ const render = (entry) => {
1236
+ const pending = boundPermissionRequest(
1237
+ cap === 0 ? { ...entry.pending, arguments: '', reason: '' } : entry.pending,
1238
+ `${entry.path === 'permission' ? 'permission' : `${entry.path}.permission.pending`}`,
1239
+ records,
1240
+ );
1241
+ if (cap === 0) {
1242
+ pending.arguments = null;
1243
+ pending.argumentsComplete = false;
1244
+ pending.completeness = 'truncated';
1245
+ pending.allowBlocked = pending.allowBlocked ?? 'the operation could not be included within the tool-text bound';
1246
+ records.push({ path: 'permission.arguments', field: 'text', keptChars: 0, detail: 'the operation did not fit' });
1247
+ } else if (cap < 4_000 && typeof pending.arguments === 'string' && pending.arguments.length > cap) {
1248
+ pending.arguments = boundedText(pending.arguments, cap, 'permission.arguments', records);
1249
+ pending.argumentsComplete = false;
1250
+ pending.completeness = pending.completeness === 'complete' ? 'truncated' : pending.completeness;
1251
+ pending.allowBlocked = pending.allowBlocked ?? 'the operation was shortened by the tool-text bound, so an allow cannot be granted on it';
1252
+ }
1253
+ return pending;
1254
+ };
1255
+ if (entries.length === 1 && entries[0].bare === true) {
1256
+ const payload = {
1257
+ ok: value.ok,
1258
+ taskId: entries[0].taskId,
1259
+ state: entries[0].state,
1260
+ phase: entries[0].phase,
1261
+ reason: value.reason,
1262
+ actionable: true,
1263
+ permission: render(entries[0]),
1264
+ permissionDecidable: false,
1265
+ truncation: truncationBlock(records, fullTextChars, entries),
1266
+ };
1267
+ return JSON.stringify(redactDeepStrings(payload), null, 2);
1268
+ }
1269
+ const tasks = entries.map((entry) => {
1270
+ const pending = render(entry);
1271
+ const block = { bridged: entry.block?.bridged === true, waiting: true, pending };
1272
+ return {
1273
+ taskId: entry.taskId,
1274
+ state: entry.state,
1275
+ phase: entry.phase,
1276
+ permissionOnly: true,
1277
+ permission: block,
1278
+ };
1279
+ });
1280
+ const payload = entries.length === 1 && entries[0].path === 'task'
1281
+ ? { ok: value.ok, task: tasks[0], truncation: truncationBlock(records, fullTextChars, entries) }
1282
+ : { ok: value.ok, tasks, truncation: truncationBlock(records, fullTextChars, entries) };
1283
+ return JSON.stringify(redactDeepStrings(payload), null, 2);
1284
+ };
1285
+ }
1286
+
1287
+ /**
1288
+ * The truncation record of a permission-only answer.
1289
+ * @param {object[]} records - per-field cuts.
1290
+ * @param {number} fullTextChars - size of the original answer.
1291
+ * @param {object[]} entries - the requests that survived.
1292
+ * @returns {object} truncation block.
1293
+ */
1294
+ function truncationBlock(records, fullTextChars, entries) {
1295
+ return {
1296
+ truncated: true,
1297
+ reason: 'the answer exceeded the tool-text bound; only the live pending permission request(s) were returned',
1298
+ fullTextChars,
1299
+ boundChars: MAX_TOOL_TEXT_CHARS,
1300
+ fullResultIncluded: false,
1301
+ permissionOnly: true,
1302
+ tasksWithPendingPermission: entries.map((entry) => truncateScalar(entry.taskId)),
1303
+ fields: dedupeRecords(records),
1304
+ };
1305
+ }
1306
+
1307
+ /**
1308
+ * Run every string in a value through {@link redactText}.
1309
+ *
1310
+ * This server is the last hop before a model reads the answer, so it does not
1311
+ * rely solely on the plane having redacted first: a task view is assembled from
1312
+ * many sources (model prose, diff text, captured evidence), and one unredacted
1313
+ * string reaching a model is the failure this guard exists to prevent. Key-based
1314
+ * masking is not repeated here — the plane already masks secret-named fields, and
1315
+ * re-masking a field this module only forwards would change a value it did not
1316
+ * read.
1317
+ * @param {unknown} value - JSON value.
1318
+ * @param {number} [depth] - recursion depth guard.
1319
+ * @returns {unknown} copy with credential-shaped substrings masked.
1320
+ */
1321
+ function redactDeepStrings(value, depth = 0) {
1322
+ if (typeof value === 'string') return redactText(value);
1323
+ if (value === null || typeof value !== 'object' || depth > MAX_PROJECTION_DEPTH) return value;
1324
+ if (Array.isArray(value)) return value.map((entry) => redactDeepStrings(entry, depth + 1));
1325
+ const out = {};
1326
+ for (const [key, item] of Object.entries(value)) out[key] = redactDeepStrings(item, depth + 1);
1327
+ return out;
1328
+ }
1329
+
1330
+ /**
1331
+ * An answer this server could not deliver, as valid bounded JSON.
1332
+ * @param {string} code - stable failure code.
1333
+ * @param {string} message - explanation.
1334
+ * @param {object} [extra] - additional fields merged into the error object.
1335
+ * @returns {{ text: string, isError: true }} refusal payload.
1336
+ */
1337
+ function refuseResult(code, message, extra = {}) {
1338
+ const text = JSON.stringify(redactDeepStrings({
1339
+ ok: false,
1340
+ error: { code, message, ...extra },
1341
+ truncation: { truncated: true, fullResultIncluded: false },
1342
+ }), null, 2);
1343
+ if (text.length <= MAX_TOOL_TEXT_CHARS) return { text, isError: true };
1344
+ // The refusal itself is larger than the bound, which only happens if the bound
1345
+ // is configured absurdly small. This minimal form is still valid JSON and still
1346
+ // says the answer was refused rather than delivered.
1347
+ return {
1348
+ text: JSON.stringify({ ok: false, error: { code, truncated: true }, truncation: { truncated: true, fullResultIncluded: false } }, null, 2),
1349
+ isError: true,
1350
+ };
1351
+ }
1352
+
1353
+ /**
1354
+ * Keep a scalar leaf small enough to always serialize.
1355
+ * @param {unknown} value - scalar.
1356
+ * @returns {unknown} value or its first 200 characters.
1357
+ */
1358
+ function truncateScalar(value) {
1359
+ if (typeof value === 'string') return value.length > 200 ? `${value.slice(0, 200)}…` : value;
1360
+ if (typeof value === 'number' || typeof value === 'boolean' || value === null) return value;
1361
+ return null;
1362
+ }
1363
+
1364
+ /**
1365
+ * Remove duplicate truncation records for the same path and field.
1366
+ * @param {object[]} records - collected records.
1367
+ * @returns {object[]} deduplicated records.
1368
+ */
1369
+ function dedupeRecords(records) {
1370
+ const seen = new Map();
1371
+ for (const record of records) {
1372
+ const key = `${record.path}\u0000${record.field}`;
1373
+ if (!seen.has(key)) seen.set(key, record);
1374
+ }
1375
+ return [...seen.values()].slice(0, 64);
1376
+ }
1377
+
1378
+ /**
1379
+ * Create the MCP request handler.
1380
+ *
1381
+ * `callExecution` is injected so this module holds no transport knowledge and can
1382
+ * be tested without a socket: it receives `(route, payload, context?)` and resolves
1383
+ * to the execution plane's parsed `ok:true` body, throwing on any refusal.
1384
+ * `context.signal` is the caller's per-REQUEST cancellation, used by
1385
+ * `delegate_wait` so `notifications/cancelled` ends that wait and nothing else.
1386
+ *
1387
+ * `now` and `sleep` are seams, not configuration: a test drives a twenty-minute
1388
+ * wait in milliseconds by handing in its own clock, and production takes the real
1389
+ * ones. Nothing else about the wait depends on them.
1390
+ * @param {object} options - `callExecution`, optional `logger`, `now`, `sleep`.
1391
+ * @returns {{ handle: Function, tools: readonly object[], calls: object[], isInitialized: () => boolean }} server.
1392
+ */
1393
+ export function createMcpServer(options) {
1394
+ if (typeof options?.callExecution !== 'function') {
1395
+ throw new TypeError('createMcpServer needs a callExecution function');
1396
+ }
1397
+ const callExecution = options.callExecution;
1398
+ const logger = options.logger ?? null;
1399
+ const now = typeof options.now === 'function' ? options.now : () => Date.now();
1400
+ const sleep = typeof options.sleep === 'function'
1401
+ ? options.sleep
1402
+ : (ms) => new Promise((resolvePromise) => { setTimeout(resolvePromise, ms); });
1403
+ // Records what was asked for, so a test can prove which plane route a tool
1404
+ // reached instead of trusting the tool result. Bounded: a long session issues
1405
+ // thousands of calls, and an unbounded array here would be a memory leak that
1406
+ // only shows up in the field.
1407
+ const calls = [];
1408
+ let initialized = false;
1409
+
1410
+ /**
1411
+ * Remember one call without growing without bound.
1412
+ * @param {object} record - call record.
1413
+ * @returns {void}
1414
+ */
1415
+ function recordCall(record) {
1416
+ calls.push(record);
1417
+ if (calls.length > MAX_CALL_LOG) calls.splice(0, calls.length - MAX_CALL_LOG);
1418
+ }
1419
+ /**
1420
+ * Run one tool call and wrap the answer as MCP content.
1421
+ * @param {string} name - tool name.
1422
+ * @param {unknown} args - arguments.
1423
+ * @param {{ signal?: AbortSignal }} [context] - per-request cancellation.
1424
+ * @returns {Promise<object>} `{ content, isError? }`.
1425
+ */
1426
+ async function callTool(name, args, context = {}) {
1427
+ const route = TOOL_ROUTES[name];
1428
+ if (route === undefined) {
1429
+ throw new McpError('MCP_TOOL_UNKNOWN', `no tool named ${JSON.stringify(name)}`, {
1430
+ rpcCode: RPC_ERRORS.invalidParams,
1431
+ });
1432
+ }
1433
+ const tool = TOOLS.find((entry) => entry.name === name);
1434
+ let payload;
1435
+ try {
1436
+ payload = validateArgs(tool, args);
1437
+ } catch (error) {
1438
+ // A malformed argument is a *tool* error, not a protocol error: the client's
1439
+ // session is healthy, the call was wrong, and `isError` is how MCP says so.
1440
+ // The code and field name go back so a model can correct itself.
1441
+ const code = typeof error?.code === 'string' ? error.code : 'MCP_ARGUMENTS_INVALID';
1442
+ return {
1443
+ content: [{ type: 'text', text: boundedJson({ ok: false, error: { code, message: error?.message ?? 'invalid arguments' } }).text }],
1444
+ isError: true,
1445
+ };
1446
+ }
1447
+ recordCall({ tool: name, route, payload });
1448
+ try {
1449
+ const result = name === 'delegate_wait'
1450
+ ? await waitAnswer(payload, context)
1451
+ : await callExecution(route, payload);
1452
+ const bounded = boundedJson(result);
1453
+ // A structurally trimmed answer is a real answer, so `isError` stays unset;
1454
+ // only an answer that could not be delivered at all is reported as an error.
1455
+ return bounded.isError
1456
+ ? { content: [{ type: 'text', text: bounded.text }], isError: true }
1457
+ : { content: [{ type: 'text', text: bounded.text }] };
1458
+ } catch (error) {
1459
+ // A refusal is a tool-level error, not a protocol error: the client must see
1460
+ // the harness's stable code so it can act on it, and `isError` tells it the
1461
+ // call failed without tearing down the session.
1462
+ const code = typeof error?.code === 'string' ? error.code : 'MCP_CALL_FAILED';
1463
+ const message = diagnostic(error?.message ?? String(error), 400) ?? 'the delegated call was refused';
1464
+ logger?.warn?.('dsh-delegate-mcp: call refused', code);
1465
+ return {
1466
+ content: [{ type: 'text', text: boundedJson({ ok: false, error: { code, message } }).text }],
1467
+ isError: true,
1468
+ };
1469
+ }
1470
+ }
1471
+
1472
+ /**
1473
+ * One `delegate_wait` call: a bounded loop of internal observations.
1474
+ *
1475
+ * The loop lives in `./wait.js`, and this function only supplies the pieces the
1476
+ * loop must not own itself — the transport call, the clock and the caller's
1477
+ * cancellation — so the loop can be tested without a server and a test can drive
1478
+ * twenty minutes of activity in milliseconds.
1479
+ * @param {object} payload - validated arguments.
1480
+ * @param {{ signal?: AbortSignal }} context - per-request cancellation.
1481
+ * @returns {Promise<object>} `{ ok: true, ...answer }`.
1482
+ */
1483
+ async function waitAnswer(payload, context) {
1484
+ const waitSeconds = payload.waitSeconds ?? DEFAULT_WAIT_SECONDS;
1485
+ const result = await waitForTask({
1486
+ callExecution,
1487
+ taskId: payload.taskId,
1488
+ waitMs: waitSeconds * 1_000,
1489
+ signal: context?.signal,
1490
+ now,
1491
+ sleep,
1492
+ });
1493
+ if (result?.error !== undefined) {
1494
+ // The loop could not obtain an observation at all. That is a refusal with the
1495
+ // harness's own code, raised so the standard refusal path shapes it — never an
1496
+ // answer that would look like a task state.
1497
+ throw new McpError(result.error.code, result.error.message);
1498
+ }
1499
+ return { ok: true, ...result };
1500
+ }
1501
+
1502
+ /**
1503
+ * Answer one JSON-RPC message.
1504
+ *
1505
+ * Returns `null` for a notification (the protocol forbids a response) so the
1506
+ * transport writes nothing.
1507
+ *
1508
+ * `context.signal` cancels THIS request only. It is passed down to the one place
1509
+ * a request can be long — the wait loop — so a host that gives up on a wait stops
1510
+ * the observations it is making without touching the worker, the task or any
1511
+ * other request.
1512
+ * @param {unknown} message - parsed JSON-RPC message.
1513
+ * @param {{ signal?: AbortSignal }} [context] - per-request cancellation.
1514
+ * @returns {Promise<object | null>} response, or null.
1515
+ */
1516
+ async function handle(message, context = {}) {
1517
+ if (message === null || typeof message !== 'object' || Array.isArray(message)) {
1518
+ return errorResponse(null, RPC_ERRORS.invalidRequest, 'a JSON-RPC message must be an object');
1519
+ }
1520
+ const { id, method, params } = message;
1521
+ const isNotification = id === undefined || id === null;
1522
+ if (typeof method !== 'string' || method === '') {
1523
+ // A message with no method is a response to something this server never
1524
+ // asked; it is not an error the client must see.
1525
+ return isNotification ? null : errorResponse(id, RPC_ERRORS.invalidRequest, 'a JSON-RPC message needs a method');
1526
+ }
1527
+
1528
+ try {
1529
+ switch (method) {
1530
+ case 'initialize': {
1531
+ const requested = params?.protocolVersion;
1532
+ const version = SUPPORTED_PROTOCOL_VERSIONS.includes(requested) ? requested : LATEST_PROTOCOL_VERSION;
1533
+ initialized = true;
1534
+ return result(id, {
1535
+ protocolVersion: version,
1536
+ // Only what this server actually implements. Advertising `resources`
1537
+ // or `prompts` would invite calls that must then fail.
1538
+ capabilities: { tools: { listChanged: false } },
1539
+ serverInfo: SERVER_INFO,
1540
+ instructions: 'Delegated coding on the DSH host. Submission is allowed only while the operator '
1541
+ + 'has enabled the delegation switch in the authenticated DSH settings page. '
1542
+ + 'For delegate_submit, workspacePath is the operator-authorized SOURCE repository or checkout '
1543
+ + '(a Git checkout or an operator-authorized Git worktree are both legitimate), not a location a '
1544
+ + 'task execution ran in; delegate_preflight is a separate read-only inspection of a path. '
1545
+ + 'Every submission starts a new task conversation unless it passes continueFromTaskId naming the '
1546
+ + 'earlier delegated task it is a follow-up to; that explicit id is the only way to continue an '
1547
+ + 'existing task thread. A follow-up continues the parent\u2019s DSH Workspace and Session and reuses '
1548
+ + 'the parent\u2019s recorded execution checkout and DSH Session internally, so it passes the parent\u2019s original '
1549
+ + 'source path again and never substitutes an internal execution location for it. A parent that '
1550
+ + 'is unknown, still running, removed or belongs to another source repository is refused '
1551
+ + 'instead of starting a new conversation. A worker that needs wider access for ONE tool call '
1552
+ + 'pauses that call and reports it as `permission.pending` in delegate_result; while it waits the '
1553
+ + 'task stays `running` with phase `awaiting-permission`. Answer exactly one such request with '
1554
+ + 'delegate_permission_decide (`allow-once` or `reject`). That decision covers only that call, is '
1555
+ + 'never a standing grant, and cannot approve anything else. To follow a task without polling, use '
1556
+ + 'delegate_wait: one call blocks until the task needs you (permission, ready, failed, cancelled, '
1557
+ + 'interrupted) or until its deadline, in which case it answers reason "wait-limit" and you call '
1558
+ + 'it again with the same taskId instead of reviewing or resubmitting anything. '
1559
+ + '`interrupted` never means the execution stopped by itself: this call returns it at once '
1560
+ + 'with `terminal: false` while the task is still pending or running (wait again on the same '
1561
+ + 'taskId); only a task record that is itself interrupted (a restart history) is `terminal: true`. '
1562
+ + 'If a host serialises tool calls so that this '
1563
+ + 'connection is blocked by a long wait, the independently installed `dsh-delegate-control` '
1564
+ + 'binary can report or cancel one task from a separate process; it cannot submit, configure or '
1565
+ + 'change the switch.',
1566
+ });
1567
+ }
1568
+ case 'notifications/initialized':
1569
+ return null;
1570
+ case 'notifications/cancelled':
1571
+ // Handled by the transport, which owns the in-flight table: this server
1572
+ // cannot see a request that is still running from inside a handler.
1573
+ return null;
1574
+ case 'ping':
1575
+ return result(id, {});
1576
+ case 'tools/list': {
1577
+ if (!initialized) return errorResponse(id, RPC_ERRORS.invalidRequest, 'initialize must be sent before tools/list');
1578
+ // The JSON Schema objects are shared and never mutated, so the catalog is
1579
+ // returned by reference; a client cannot corrupt it because it only reads.
1580
+ return result(id, { tools: TOOLS.map((tool) => ({ ...tool })) });
1581
+ }
1582
+ case 'tools/call': {
1583
+ if (!initialized) return errorResponse(id, RPC_ERRORS.invalidRequest, 'initialize must be sent before tools/call');
1584
+ const name = params?.name;
1585
+ if (typeof name !== 'string' || name === '') {
1586
+ return errorResponse(id, RPC_ERRORS.invalidParams, 'tools/call requires a tool name');
1587
+ }
1588
+ return result(id, await callTool(name, params?.arguments, context));
1589
+ }
1590
+ default:
1591
+ return errorResponse(id, RPC_ERRORS.methodNotFound, `this server does not implement ${JSON.stringify(method)}`);
1592
+ }
1593
+ } catch (error) {
1594
+ if (error instanceof McpError && error.rpcCode !== null) {
1595
+ return errorResponse(id, error.rpcCode, error.message);
1596
+ }
1597
+ // An unexpected failure is reported with its code only: a stack or a
1598
+ // message may quote configuration this server must not disclose.
1599
+ const code = typeof error?.code === 'string' ? error.code : 'MCP_INTERNAL';
1600
+ return errorResponse(id, RPC_ERRORS.internal, `the delegation server failed (${code})`);
1601
+ }
1602
+ }
1603
+
1604
+ return { handle, tools: TOOLS, calls, isInitialized: () => initialized };
1605
+ }
1606
+
1607
+ /**
1608
+ * Build a JSON-RPC success response.
1609
+ * @param {unknown} id - request id.
1610
+ * @param {unknown} value - result.
1611
+ * @returns {object} response envelope.
1612
+ */
1613
+ function result(id, value) {
1614
+ return { jsonrpc: '2.0', id: id ?? null, result: value };
1615
+ }
1616
+
1617
+ /**
1618
+ * Build a JSON-RPC error response.
1619
+ * @param {unknown} id - request id.
1620
+ * @param {number} code - JSON-RPC error code.
1621
+ * @param {string} message - explanation.
1622
+ * @returns {object} response envelope.
1623
+ */
1624
+ function errorResponse(id, code, message) {
1625
+ return { jsonrpc: '2.0', id: id ?? null, error: { code, message } };
1626
+ }
1627
+
1628
+ /**
1629
+ * Run the newline-delimited JSON-RPC loop over a pair of streams.
1630
+ *
1631
+ * MCP's stdio transport is one JSON-RPC message per line: there is no
1632
+ * `Content-Length` framing here, and adding it would break the client. Malformed
1633
+ * input produces a parse error and the loop continues, because a single bad line
1634
+ * must not end a session the model is still using.
1635
+ *
1636
+ * Two properties of this loop are load-bearing and were added for `delegate_wait`:
1637
+ *
1638
+ * 1. **A request that takes minutes must not stop the others.** Each request is
1639
+ * dispatched and its reply written when it settles, so a host can send a
1640
+ * status read or a cancel while a wait is outstanding. Replies are written one
1641
+ * line at a time through a single writer, so two concurrent answers can never
1642
+ * interleave inside a line.
1643
+ * 2. **Cancellation is per request.** `notifications/cancelled` aborts exactly the
1644
+ * request it names: that request's wait ends, its reply is a normal refusal,
1645
+ * and every other request (including another wait on the same task) continues.
1646
+ *
1647
+ * The concurrency bound is a refusal, not a queue: a host that sends a 33rd
1648
+ * simultaneous request is told so explicitly. Stdin EOF stops accepting new work,
1649
+ * aborts nothing on the worker side, and the loop returns only once every
1650
+ * outstanding reply has been written, so nothing is truncated at shutdown.
1651
+ * @param {object} options - `input`, `output` streams, `server`, optional `onError`,
1652
+ * `maxInflight`.
1653
+ * @returns {Promise<void>} resolves when the input stream ends and replies are drained.
1654
+ */
1655
+ export async function serveStdio(options) {
1656
+ const { input, output, server } = options;
1657
+ const onError = options.onError ?? (() => {});
1658
+ const maxInflight = Number.isInteger(options.maxInflight) && options.maxInflight > 0
1659
+ ? options.maxInflight
1660
+ : MAX_INFLIGHT_REQUESTS;
1661
+
1662
+ /**
1663
+ * Serialize every write so a line is never split by another request's answer.
1664
+ *
1665
+ * Each write waits for the previous one, and also for `drain` when the stream
1666
+ * applies backpressure. A rejected write (a closed pipe) must not leave the queue
1667
+ * permanently blocked, which is why the chain continues even after a failure.
1668
+ * @param {object} payload - JSON-RPC message.
1669
+ * @returns {Promise<void>} resolves after this line is written (or fails to be).
1670
+ */
1671
+ let writeChain = Promise.resolve();
1672
+ const write = (payload) => {
1673
+ const line = `${JSON.stringify(payload)}\n`;
1674
+ writeChain = writeChain.then(() => new Promise((resolvePromise) => {
1675
+ let ok = true;
1676
+ try {
1677
+ ok = output.write(line) !== false;
1678
+ } catch (error) {
1679
+ onError(error);
1680
+ resolvePromise();
1681
+ return;
1682
+ }
1683
+ if (ok) {
1684
+ resolvePromise();
1685
+ return;
1686
+ }
1687
+ output.once('drain', resolvePromise);
1688
+ // A stream destroyed while waiting for `drain` never emits it; without this
1689
+ // the writer would wait forever and EOF would hang instead of draining.
1690
+ output.once('close', resolvePromise);
1691
+ }));
1692
+ return writeChain;
1693
+ };
1694
+
1695
+ /** Requests currently in flight, by the JSON-RPC id as a map key. */
1696
+ const inflight = new Map();
1697
+ /** Every outstanding request promise, so EOF can drain them all. */
1698
+ const pending = new Set();
1699
+ let inputEnded = false;
1700
+ /** Set once the transport is shutting down: no new work is accepted. */
1701
+ let closed = false;
1702
+
1703
+ /**
1704
+ * A stable map key for a request id. JSON-RPC ids are strings or numbers; a
1705
+ * string `"1"` and a number `1` are distinct ids, so the type is part of the key.
1706
+ * @param {unknown} id - request id.
1707
+ * @returns {string} map key.
1708
+ */
1709
+ const idKey = (id) => `${typeof id}:${String(id)}`;
1710
+
1711
+ /**
1712
+ * Ask one in-flight request to stop.
1713
+ * @param {unknown} requestId - the id named by the notification.
1714
+ * @returns {boolean} whether a request was actually cancelled.
1715
+ */
1716
+ const cancel = (requestId) => {
1717
+ const entry = inflight.get(idKey(requestId));
1718
+ if (entry === undefined) return false;
1719
+ const error = new Error('the request was cancelled by the host');
1720
+ error.name = 'AbortError';
1721
+ error.code = 'MCP_REQUEST_CANCELLED';
1722
+ entry.controller.abort(error);
1723
+ return true;
1724
+ };
1725
+
1726
+ /**
1727
+ * Handle one parsed line: a request is started, a notification is acted on.
1728
+ * @param {object} message - parsed JSON-RPC message.
1729
+ * @returns {void}
1730
+ */
1731
+ const dispatch = (message) => {
1732
+ if (message === null || typeof message !== 'object' || Array.isArray(message)) {
1733
+ void write(errorResponse(null, RPC_ERRORS.invalidRequest, 'a JSON-RPC message must be an object'));
1734
+ return;
1735
+ }
1736
+ const { id, method } = message;
1737
+ if (method === 'notifications/cancelled') {
1738
+ // Never answered: the protocol forbids a response to a notification. The
1739
+ // cancellation request id travels in `params.requestId`.
1740
+ cancel(message.params?.requestId);
1741
+ return;
1742
+ }
1743
+ if (id === undefined || id === null) {
1744
+ // Any other notification is handled for its effect only.
1745
+ void (async () => {
1746
+ try {
1747
+ await server.handle(message);
1748
+ } catch (error) {
1749
+ onError(error);
1750
+ }
1751
+ })();
1752
+ return;
1753
+ }
1754
+ const key = idKey(id);
1755
+ if (inflight.has(key)) {
1756
+ // Two live requests with one id would make the answers unassignable, and the
1757
+ // second would silently replace the first's cancellation handle. Refusing is
1758
+ // the only honest answer; the original request keeps running.
1759
+ void write(errorResponse(id, RPC_ERRORS.invalidRequest, 'a request with this id is already in flight'));
1760
+ return;
1761
+ }
1762
+ if (inflight.size >= maxInflight) {
1763
+ void write(errorResponse(id, RPC_ERRORS.invalidRequest, `too many requests in flight (limit ${maxInflight})`));
1764
+ return;
1765
+ }
1766
+
1767
+ const controller = new AbortController();
1768
+ inflight.set(key, { controller });
1769
+ const run = (async () => {
1770
+ let response = null;
1771
+ try {
1772
+ response = await server.handle(message, { signal: controller.signal });
1773
+ } catch (error) {
1774
+ onError(error);
1775
+ response = errorResponse(message?.id ?? null, RPC_ERRORS.internal, 'the request could not be handled');
1776
+ } finally {
1777
+ inflight.delete(key);
1778
+ }
1779
+ if (response !== null && response !== undefined) await write(response);
1780
+ })();
1781
+ pending.add(run);
1782
+ void run.finally(() => pending.delete(run));
1783
+ };
1784
+
1785
+ let buffer = '';
1786
+ try {
1787
+ for await (const chunk of input) {
1788
+ buffer += chunk.toString('utf8');
1789
+ let newline = buffer.indexOf('\n');
1790
+ while (newline !== -1) {
1791
+ const line = buffer.slice(0, newline).trim();
1792
+ buffer = buffer.slice(newline + 1);
1793
+ newline = buffer.indexOf('\n');
1794
+ if (line === '') continue;
1795
+ let message;
1796
+ try {
1797
+ message = JSON.parse(line);
1798
+ } catch {
1799
+ await write(errorResponse(null, RPC_ERRORS.parse, 'the message is not valid JSON'));
1800
+ continue;
1801
+ }
1802
+ // Awaited so the next line is not read before this one has been attributed,
1803
+ // but the request it starts is NOT awaited: that is what keeps a long wait
1804
+ // from blocking the transport.
1805
+ dispatch(message);
1806
+ }
1807
+ }
1808
+ } catch (error) {
1809
+ onError(error);
1810
+ }
1811
+ inputEnded = true;
1812
+ closed = true;
1813
+
1814
+ // Drain: every reply that was already being produced is written before the loop
1815
+ // returns. Readers are ended here, but nothing is aborted on the worker side — a
1816
+ // wait that ends because its host vanished is the host's decision, not a cancel.
1817
+ while (pending.size > 0) await Promise.allSettled([...pending]);
1818
+ await writeChain;
1819
+ return { inflight: inputEnded, closed, drained: pending.size === 0 };
1820
+ }