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