dsh-taskbridge 0.0.0-stage → 1.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/CHANGELOG.md +754 -0
  2. package/LICENSE +21 -0
  3. package/README.md +624 -3
  4. package/bin/dsh-delegate-codex-agent.js +115 -0
  5. package/bin/dsh-delegate-control.d.ts +90 -0
  6. package/bin/dsh-delegate-control.js +450 -0
  7. package/bin/dsh-delegate-mcp.d.ts +121 -0
  8. package/bin/dsh-delegate-mcp.js +273 -0
  9. package/codex/dsh-delegate.toml +245 -0
  10. package/cordis.patch.yml +6 -0
  11. package/docs/INTRODUCTION.md +15 -0
  12. package/docs/INTRODUCTION.zh.md +32 -0
  13. package/docs/auth-contract.md +138 -0
  14. package/docs/claude-code.md +31 -0
  15. package/docs/codex-integration.md +922 -0
  16. package/docs/contracts-stage-b.md +443 -0
  17. package/docs/conversation-placement.md +293 -0
  18. package/docs/plugin-market.md +30 -0
  19. package/docs/redaction-contract.md +127 -0
  20. package/docs/runtime-compatibility.md +220 -0
  21. package/docs/silent-wait.md +191 -0
  22. package/docs/taskbridge-upgrade.md +28 -0
  23. package/docs/taskdispatch-upgrade.md +25 -0
  24. package/docs/worker-permissions.md +347 -0
  25. package/docs/workspace-contract.md +538 -0
  26. package/icon.svg +1 -0
  27. package/lib/client.d.ts +118 -0
  28. package/lib/client.js +3232 -0
  29. package/locale/en.json +7 -0
  30. package/locale/zh.json +7 -0
  31. package/package.json +135 -4
  32. package/src/auth/fence.js +361 -0
  33. package/src/auth/grants.js +789 -0
  34. package/src/client/api.js +2322 -0
  35. package/src/client/index.jsx +2333 -0
  36. package/src/client/styles.js +251 -0
  37. package/src/codex/installer.js +3260 -0
  38. package/src/codex/seam.js +429 -0
  39. package/src/codex/toml.js +784 -0
  40. package/src/config/defaults.js +164 -0
  41. package/src/config/redact.js +184 -0
  42. package/src/config/settings.js +629 -0
  43. package/src/config/store.js +186 -0
  44. package/src/config/validate.js +763 -0
  45. package/src/credentials/seam.js +202 -0
  46. package/src/http/execution-plane.js +454 -0
  47. package/src/http/respond.js +175 -0
  48. package/src/http/user-plane.js +1122 -0
  49. package/src/index.d.ts +332 -0
  50. package/src/index.js +657 -0
  51. package/src/jobs/activity.js +1008 -0
  52. package/src/jobs/engine.js +3609 -0
  53. package/src/jobs/history.js +1467 -0
  54. package/src/mcp/server.js +1820 -0
  55. package/src/mcp/wait.js +536 -0
  56. package/src/model/connectivity.js +371 -0
  57. package/src/model/discovery.js +582 -0
  58. package/src/model/native-catalog.js +68 -0
  59. package/src/model/openai-adapter.js +671 -0
  60. package/src/model/probe.js +264 -0
  61. package/src/model/providers.js +756 -0
  62. package/src/model/routing.js +321 -0
  63. package/src/review/preset.js +868 -0
  64. package/src/review/prompts.js +126 -0
  65. package/src/review/reviewer.js +933 -0
  66. package/src/runtime/agent-runner.js +1738 -0
  67. package/src/runtime/endpoint-discovery.js +118 -0
  68. package/src/runtime/permissions.js +1429 -0
  69. package/src/runtime/sandbox.js +358 -0
  70. package/src/runtime/session-placement.js +1103 -0
  71. package/src/workspace/audit.js +775 -0
  72. package/src/workspace/locks.js +167 -0
  73. package/src/workspace/preflight.js +424 -0
  74. package/src/workspace/worktrees.js +613 -0
@@ -0,0 +1,202 @@
1
+ // Credential seam gateway.
2
+ //
3
+ // The plugin never stores a secret and never reads one back into a projection.
4
+ // It talks to the native DSH credential seam (`ctx.credentials`) for exactly four
5
+ // operations and nothing else:
6
+ //
7
+ // * `describe(ref)` — presence/source/writability, safe for a settings UI;
8
+ // * `resolve(ref)` — the value, for the native adapter inside a stream call;
9
+ // * `set(ref, value)` — write one value the operator pasted;
10
+ // * `unset(ref)` — remove it.
11
+ //
12
+ // The seam is reached through a *lazy* accessor rather than a captured reference.
13
+ // Two reasons, both about load order:
14
+ //
15
+ // 1. this plugin deliberately does not inject the credential service, so it
16
+ // loads and reports state in a harness that has none (the UI then says
17
+ // "host provides no credential interface" instead of the plugin refusing to
18
+ // start); and
19
+ // 2. the seam documents a per-operation resolve so a rotated credential reaches
20
+ // the next operation without a restart — capturing the service object once
21
+ // would still be fine, but capturing the *value* would not, and the lazy
22
+ // read makes that mistake impossible to write here.
23
+ //
24
+ // A failed seam call is reported with its own code and a bounded `cause` code.
25
+ // The provider's message is never forwarded: a credential backend is free to echo
26
+ // what it was given, and this is the one place in the plugin where that would be
27
+ // a disclosure.
28
+
29
+ /** Stable refusal codes for every credential operation. */
30
+ export const CREDENTIAL_CODES = Object.freeze({
31
+ seamUnavailable: 'CREDENTIAL_SEAM_UNAVAILABLE',
32
+ operationFailed: 'CREDENTIAL_OPERATION_FAILED',
33
+ readOnly: 'CREDENTIAL_READ_ONLY',
34
+ valueRequired: 'CREDENTIAL_VALUE_REQUIRED',
35
+ valueTooLarge: 'CREDENTIAL_VALUE_TOO_LARGE',
36
+ refInvalid: 'CREDENTIAL_REF_INVALID',
37
+ });
38
+
39
+ /** Bound on a pasted secret. A provider key is far shorter than this. */
40
+ export const MAX_CREDENTIAL_VALUE_CHARS = 8192;
41
+
42
+ /** A credential refusal with a stable machine code. */
43
+ export class CredentialSeamError extends Error {
44
+ /**
45
+ * @param {string} code - stable machine code.
46
+ * @param {string} message - human-readable explanation.
47
+ * @param {object} [details] - bounded, non-secret details.
48
+ */
49
+ constructor(code, message, details = {}) {
50
+ super(message);
51
+ this.name = 'CredentialSeamError';
52
+ this.code = code;
53
+ this.details = details;
54
+ }
55
+ }
56
+
57
+ /** Methods the seam must expose for this plugin to act at all. */
58
+ const REQUIRED_METHODS = Object.freeze({
59
+ resolve: 'resolve',
60
+ describe: 'describe',
61
+ set: 'set',
62
+ unset: 'unset',
63
+ });
64
+
65
+ /**
66
+ * Create the credential gateway over one native service accessor.
67
+ * @param {() => unknown} getService - returns the current `ctx.credentials`, or a
68
+ * nullish value while the service is absent.
69
+ * @returns {{ available: () => boolean, describe: Function, resolve: Function, set: Function, unset: Function }} gateway.
70
+ */
71
+ export function createCredentialGateway(getService) {
72
+ if (typeof getService !== 'function') {
73
+ throw new TypeError('createCredentialGateway needs a service accessor');
74
+ }
75
+
76
+ /**
77
+ * Read the seam, refusing rather than returning null so a caller can never
78
+ * mistake "no service" for "no credential".
79
+ * @param {string} operation - seam method being attempted, for the refusal.
80
+ * @returns {object} the native service.
81
+ */
82
+ function requireSeam(operation) {
83
+ let service;
84
+ try {
85
+ service = getService();
86
+ } catch (error) {
87
+ // A host whose accessor throws is a refusal, not a crash inside a route.
88
+ throw new CredentialSeamError(CREDENTIAL_CODES.seamUnavailable,
89
+ 'the DSH credential service could not be read in this harness',
90
+ { operation, cause: typeof error?.code === 'string' ? error.code : null });
91
+ }
92
+ if (service === null || typeof service !== 'object') {
93
+ throw new CredentialSeamError(CREDENTIAL_CODES.seamUnavailable,
94
+ 'this harness exposes no credential service; a pasted secret cannot be stored',
95
+ { operation });
96
+ }
97
+ const method = REQUIRED_METHODS[operation];
98
+ if (typeof service[method] !== 'function') {
99
+ throw new CredentialSeamError(CREDENTIAL_CODES.seamUnavailable,
100
+ `the credential service does not implement ${method}()`,
101
+ { operation });
102
+ }
103
+ return service;
104
+ }
105
+
106
+ /**
107
+ * Run one seam call, translating a provider failure into a bounded refusal.
108
+ * @param {string} operation - seam method name.
109
+ * @param {string} ref - credential reference, echoed as a name only.
110
+ * @param {(service: object) => Promise<unknown>} work - the call.
111
+ * @returns {Promise<unknown>} the seam result.
112
+ */
113
+ async function attempt(operation, ref, work) {
114
+ const service = requireSeam(operation);
115
+ try {
116
+ return await work(service);
117
+ } catch (error) {
118
+ if (error instanceof CredentialSeamError) throw error;
119
+ // Only the code survives: the message may quote the value or a path.
120
+ throw new CredentialSeamError(CREDENTIAL_CODES.operationFailed,
121
+ `the credential service refused ${operation}() for ${ref}`,
122
+ { operation, reference: ref, cause: typeof error?.code === 'string' ? error.code : null });
123
+ }
124
+ }
125
+
126
+ return {
127
+ /**
128
+ * Whether the seam is present at all, for status reporting.
129
+ * @returns {boolean} true when `resolve` is callable.
130
+ */
131
+ available() {
132
+ try {
133
+ requireSeam('resolve');
134
+ return true;
135
+ } catch {
136
+ return false;
137
+ }
138
+ },
139
+
140
+ /**
141
+ * Presence/source/writability for one reference. The returned view has no
142
+ * slot a value could ride in, and this function does not add one.
143
+ * @param {string} ref - credential reference name.
144
+ * @returns {Promise<{ configured: boolean, source?: string, writable: boolean }>} seam view.
145
+ */
146
+ async describe(ref) {
147
+ const info = await attempt('describe', ref, (service) => service.describe(ref));
148
+ if (info === null || typeof info !== 'object') {
149
+ throw new CredentialSeamError(CREDENTIAL_CODES.operationFailed,
150
+ `the credential service returned no usable description for ${ref}`,
151
+ { operation: 'describe', reference: ref });
152
+ }
153
+ return {
154
+ configured: info.configured === true,
155
+ ...(typeof info.source === 'string' && info.source !== '' ? { source: info.source } : {}),
156
+ writable: info.writable === true,
157
+ };
158
+ },
159
+
160
+ /**
161
+ * Resolve one reference to its current value. Called only by the native
162
+ * adapter inside a stream operation; the value is returned to pi-ai and to
163
+ * nothing else.
164
+ * @param {string} ref - credential reference name.
165
+ * @returns {Promise<{ value: string, source: string } | undefined>} value, or undefined.
166
+ */
167
+ async resolve(ref) {
168
+ return await attempt('resolve', ref, (service) => service.resolve(ref));
169
+ },
170
+
171
+ /**
172
+ * Store one pasted value. Refuses an empty value (that is `unset`) and a
173
+ * value no provider key could be.
174
+ * @param {string} ref - credential reference name.
175
+ * @param {string} value - the literal secret.
176
+ * @returns {Promise<void>} resolves after the seam committed the write.
177
+ */
178
+ async set(ref, value) {
179
+ if (typeof value !== 'string' || value.trim() === '') {
180
+ throw new CredentialSeamError(CREDENTIAL_CODES.valueRequired,
181
+ 'a credential value is required; use clear to remove one', { reference: ref });
182
+ }
183
+ if (value.length > MAX_CREDENTIAL_VALUE_CHARS) {
184
+ throw new CredentialSeamError(CREDENTIAL_CODES.valueTooLarge,
185
+ 'the credential value exceeds the accepted bound',
186
+ { reference: ref, limit: MAX_CREDENTIAL_VALUE_CHARS });
187
+ }
188
+ // The literal is not trimmed: a trailing space would be a different secret,
189
+ // and silently altering what the operator pasted would be a hidden failure.
190
+ await attempt('set', ref, (service) => service.set(ref, value));
191
+ },
192
+
193
+ /**
194
+ * Remove one stored value. Removing an absent value is a no-op in the seam.
195
+ * @param {string} ref - credential reference name.
196
+ * @returns {Promise<void>} resolves after the seam committed the removal.
197
+ */
198
+ async unset(ref) {
199
+ await attempt('unset', ref, (service) => service.unset(ref));
200
+ },
201
+ };
202
+ }
@@ -0,0 +1,454 @@
1
+ // Execution plane: the bounded surface an external connection uses to submit
2
+ // and observe delegated work.
3
+ //
4
+ // This plane is NOT an authorization surface. It cannot create a connection, it
5
+ // cannot issue a grant, and it cannot change settings. Those actions exist only
6
+ // on the authenticated user plane. What this plane can do is exercise an
7
+ // authorization the operator already created, which means every request here
8
+ // needs two independent facts:
9
+ //
10
+ // 1. a connection token, issued by the operator plane and stored only as a
11
+ // hash; and
12
+ // 2. a grant for that connection and this exact workspace.
13
+ //
14
+ // The transport fence (loopback socket, loopback Host, same-origin browser
15
+ // marker) is applied first. It is a necessary condition, never a sufficient
16
+ // one: an Origin string is trivially forged by any local program, so it is
17
+ // treated as a filter, not as proof of anything.
18
+
19
+ import { fenceExternalConnection } from '../auth/fence.js';
20
+ import { AUTH_CODES } from '../auth/grants.js';
21
+ import { classifyError, HttpError, readJsonBody, sendJson } from '../http/respond.js';
22
+ import { preflightWorkspace } from '../workspace/preflight.js';
23
+
24
+ /** Route prefix owned by this plane. Deliberately not under `/api`. */
25
+ export const EXECUTION_PREFIX = '/dsh-delegate/x';
26
+
27
+ /**
28
+ * Upper bound on one observation request, in milliseconds.
29
+ *
30
+ * A caller may ask for less, never for more. The bound exists so one HTTP request
31
+ * is always answerable: a connection that has gone away cannot pin a handler open
32
+ * for an unbounded time, and a long host-side wait is composed out of these
33
+ * bounded observations rather than being one unbounded request.
34
+ */
35
+ export const MAX_OBSERVE_WAIT_MS = 25_000;
36
+
37
+ /** Body fields `POST /tasks/observe` accepts. Everything else is refused. */
38
+ const OBSERVE_FIELDS = Object.freeze(['taskId', 'waitMs']);
39
+
40
+ /**
41
+ * Build a node-style handler for the execution plane.
42
+ *
43
+ * Routing is exact-match on method plus path, so an unmatched path is a 404 and
44
+ * never falls through to something more permissive.
45
+ * @param {object} deps - `engine`, `auth`, `settings`, `logger`, `getBindHost`.
46
+ * @returns {(req: import('node:http').IncomingMessage, res: import('node:http').ServerResponse) => Promise<void>} handler.
47
+ */
48
+ export function createExecutionHandler(deps) {
49
+ const routes = new Map([
50
+ ['GET /status', status],
51
+ ['POST /tasks', submitTask],
52
+ ['GET /tasks', listTasks],
53
+ ['POST /tasks/get', getTask],
54
+ ['POST /tasks/cancel', cancelTask],
55
+ // A bounded long-poll read. It creates, settles and authorizes nothing: it
56
+ // reports what a task looks like now, or returns when something about it that a
57
+ // host must act on changes. Read availability follows `/tasks/get` exactly, so
58
+ // it stays answerable while the switch is off.
59
+ ['POST /tasks/observe', observeTask],
60
+ // The one per-call permission decision a commander may take. It is NOT a
61
+ // control-plane write: it consumes an already pending native approval request
62
+ // that this task's own worker raised, cannot create or widen any grant, cannot
63
+ // change settings/credentials/the switch, and cannot approve a future call.
64
+ // The switch gate below applies to it exactly as it does to a submission,
65
+ // because a decision is an authorization exercise like any other.
66
+ ['POST /tasks/permission', decidePermission],
67
+ // Read-only workspace inspection for a dispatcher: the facts and the isolation
68
+ // recommendation that used to be discovered only when a job admitted. It is a
69
+ // separate route — not a field on `/tasks` — because it neither authorizes nor
70
+ // creates anything, so it must remain answerable when `submit` is refused.
71
+ ['POST /workspace/preflight', preflight],
72
+ ]);
73
+
74
+ return async function handleExecution(req, res) {
75
+ try {
76
+ const fence = fenceExternalConnection(req);
77
+ if (fence.ok !== true) {
78
+ sendJson(res, fence.status, { ok: false, error: { code: fence.code, message: 'request refused by the transport fence' } });
79
+ return;
80
+ }
81
+ const bind = deps.getBindHost?.();
82
+ if (bind !== undefined && bind !== '127.0.0.1') {
83
+ // A non-loopback bind invalidates the only locality evidence this plane
84
+ // has. Refuse outright rather than trust a Host header.
85
+ sendJson(res, 403, {
86
+ ok: false,
87
+ error: {
88
+ code: 'EXECUTION_BIND_NOT_LOOPBACK',
89
+ message: 'the execution plane requires the harness webserver to listen on 127.0.0.1',
90
+ },
91
+ });
92
+ return;
93
+ }
94
+
95
+ const url = new URL(req.url ?? '/', 'http://localhost');
96
+ const path = url.pathname.startsWith(EXECUTION_PREFIX)
97
+ ? url.pathname.slice(EXECUTION_PREFIX.length) || '/'
98
+ : null;
99
+ if (path === null) {
100
+ sendJson(res, 404, { ok: false, error: { code: 'EXECUTION_PATH_UNKNOWN', message: 'unknown path' } });
101
+ return;
102
+ }
103
+ const key = `${String(req.method ?? 'GET').toUpperCase()} ${path}`;
104
+ const handler = routes.get(key);
105
+ if (handler === undefined) {
106
+ sendJson(res, 404, { ok: false, error: { code: 'EXECUTION_ROUTE_UNKNOWN', message: `no route for ${key}` } });
107
+ return;
108
+ }
109
+
110
+ let connection;
111
+ if (deps.engine.authorizationMode === 'switch') {
112
+ // Both AUTHORIZING verbs need the switch: a submission creates work and a
113
+ // decision releases a paused call. Reads, cancel and preflight stay
114
+ // answerable while the switch is off, so an operator can always observe and
115
+ // stop what already exists.
116
+ const gated = key === 'POST /tasks' || key === 'POST /tasks/permission';
117
+ if (gated && deps.engine.posture().authorized !== true) {
118
+ sendJson(res, 403, {
119
+ ok: false,
120
+ error: { code: 'DELEGATION_DISABLED', message: 'delegation is disabled in DSH settings' },
121
+ });
122
+ return;
123
+ }
124
+ connection = { connectionId: 'local-mcp', label: 'Local MCP' };
125
+ } else {
126
+ connection = authenticateRequest(deps, req);
127
+ }
128
+ if (connection === null) {
129
+ // One refusal for every authentication failure: distinguishing "no token"
130
+ // from "bad token" from "revoked connection" would help an attacker and
131
+ // help an operator very little.
132
+ sendJson(res, 401, {
133
+ ok: false,
134
+ error: { code: AUTH_CODES.connectionUnknown, message: 'a valid connection token is required' },
135
+ });
136
+ return;
137
+ }
138
+
139
+ await handler({ req, res, url, connection, deps });
140
+ } catch (error) {
141
+ const mapped = classifyError(error);
142
+ deps.logger?.warn?.('dsh-delegate: execution plane refusal', mapped.code);
143
+ if (res.headersSent !== true && isWritable(res)) {
144
+ sendJson(res, mapped.status, {
145
+ ok: false,
146
+ error: { code: mapped.code, message: mapped.message, details: mapped.details },
147
+ });
148
+ }
149
+ }
150
+ };
151
+ }
152
+
153
+ /**
154
+ * Whether a response can still be written to.
155
+ *
156
+ * A long observation can outlive its own connection: a poller that gave up closes
157
+ * the socket, and this plane only finds out when it tries to answer. `sendJson` on
158
+ * a destroyed response throws from `writeHead` with an opaque socket error, which
159
+ * the refusal path would then report as an internal failure of a request nobody is
160
+ * listening to. The check is deliberately narrow — `writableEnded`,
161
+ * `writableFinished` (or its property form) and a destroyed socket — and it treats
162
+ * an unknown response shape as writable, so it never suppresses an answer.
163
+ * @param {import('node:http').ServerResponse} res - response object.
164
+ * @returns {boolean} true when writing is still meaningful.
165
+ */
166
+ function isWritable(res) {
167
+ if (res === null || typeof res !== 'object') return false;
168
+ if (res.writableEnded === true || res.writableFinished === true) return false;
169
+ if (res.destroyed === true || res.socket?.destroyed === true) return false;
170
+ return true;
171
+ }
172
+
173
+ /**
174
+ * Authenticate the presented connection token.
175
+ * @param {object} deps - dependency object.
176
+ * @param {import('node:http').IncomingMessage} req - request.
177
+ * @returns {object | null} the connection record, or null.
178
+ */
179
+ export function authenticateRequest(deps, req) {
180
+ const header = req.headers?.authorization;
181
+ if (typeof header !== 'string') return null;
182
+ const match = /^Bearer\s+(\S+)$/i.exec(header.trim());
183
+ if (match === null) return null;
184
+ return deps.auth.authenticate(match[1]);
185
+ }
186
+
187
+ async function status({ res, connection, deps }) {
188
+ sendJson(res, 200, {
189
+ ok: true,
190
+ connection: { connectionId: connection.connectionId, label: connection.label },
191
+ // The external caller is told which workspaces it may act on, and nothing
192
+ // about models, providers, credentials or other connections.
193
+ grants: deps.engine.authorizationMode === 'switch' ? [] : deps.auth.listGrants(connection.connectionId).filter((grant) => {
194
+ if (grant.revokedAt !== null) return false;
195
+ return grant.kind === 'session' ? true : grant.consumedAt === null;
196
+ }),
197
+ delegation: deps.engine.posture(),
198
+ });
199
+ }
200
+
201
+ async function submitTask({ req, res, connection, deps }) {
202
+ const body = await readJsonBody(req);
203
+ // The continuation identity, or `undefined` for a new task conversation. It is
204
+ // passed through as a value, never inferred from the workspace or from earlier
205
+ // submissions: only the caller knows whether this is a follow-up, and the engine
206
+ // validates it fail-closed.
207
+ const continueFromTaskId = body.continueFromTaskId === undefined || body.continueFromTaskId === null
208
+ ? undefined
209
+ : body.continueFromTaskId;
210
+ if (deps.engine.authorizationMode === 'switch') {
211
+ const task = await deps.engine.start({
212
+ connectionId: connection.connectionId,
213
+ workspacePath: body.workspacePath,
214
+ prompt: body.prompt,
215
+ overrides: body.overrides,
216
+ ...(continueFromTaskId === undefined ? {} : { continueFromTaskId }),
217
+ });
218
+ sendJson(res, 202, { ok: true, task });
219
+ return;
220
+ }
221
+ const authorization = body.authorization === 'session' ? 'session' : 'task';
222
+ if (authorization === 'task' && typeof body.grantId !== 'string') {
223
+ throw new HttpError(400, 'GRANT_ID_REQUIRED', 'grantId is required for a single-task submission');
224
+ }
225
+ const task = await deps.engine.start({
226
+ // The connection identity comes from the verified token, never from the body.
227
+ connectionId: connection.connectionId,
228
+ grantId: body.grantId,
229
+ authorization,
230
+ workspacePath: body.workspacePath,
231
+ prompt: body.prompt,
232
+ overrides: body.overrides,
233
+ ...(continueFromTaskId === undefined ? {} : { continueFromTaskId }),
234
+ });
235
+ sendJson(res, 202, { ok: true, task });
236
+ }
237
+
238
+ async function listTasks({ res, connection, deps }) {
239
+ sendJson(res, 200, { ok: true, tasks: deps.engine.list({ connectionId: connection.connectionId }) });
240
+ }
241
+
242
+ async function getTask({ req, res, connection, deps }) {
243
+ const body = await readJsonBody(req);
244
+ if (typeof body.taskId !== 'string') {
245
+ throw new HttpError(400, 'TASK_ID_REQUIRED', 'taskId is required');
246
+ }
247
+ const task = deps.engine.get(body.taskId);
248
+ if (task.connectionId !== connection.connectionId) {
249
+ // Cross-connection reads are reported as absent, not as forbidden: a
250
+ // distinct code would confirm that a task id exists.
251
+ throw new HttpError(404, 'JOB_TASK_NOT_FOUND', 'no such task for this connection');
252
+ }
253
+ sendJson(res, 200, { ok: true, task });
254
+ }
255
+
256
+ async function cancelTask({ req, res, connection, deps }) {
257
+ const body = await readJsonBody(req);
258
+ if (typeof body.taskId !== 'string') {
259
+ throw new HttpError(400, 'TASK_ID_REQUIRED', 'taskId is required');
260
+ }
261
+ const existing = deps.engine.get(body.taskId);
262
+ if (existing.connectionId !== connection.connectionId) {
263
+ throw new HttpError(404, 'JOB_TASK_NOT_FOUND', 'no such task for this connection');
264
+ }
265
+ const task = await deps.engine.cancel(body.taskId, 'connection');
266
+ sendJson(res, 200, { ok: true, task });
267
+ }
268
+
269
+ /**
270
+ * Decide one pending per-call permission request of one task.
271
+ *
272
+ * The connection identity comes from authentication, never from the body, and it
273
+ * is the same identity that owns the task: the engine reports a task of another
274
+ * connection — and an unknown one — as `JOB_TASK_NOT_FOUND`, one answer with one
275
+ * set of details, so a decision call cannot be used to learn which task ids or
276
+ * pending requests exist elsewhere.
277
+ *
278
+ * The body is validated here (not only in the MCP server) because this route is
279
+ * reachable by any local caller: an unknown field, a decision outside the closed
280
+ * vocabulary, or a reason that is not a string is refused before the engine reads
281
+ * anything.
282
+ * @param {object} context - `req`, `res`, `connection`, `deps`.
283
+ * @returns {Promise<void>} resolves after the answer is sent.
284
+ */
285
+ async function decidePermission({ req, res, connection, deps }) {
286
+ const body = await readJsonBody(req);
287
+ if (typeof body.taskId !== 'string' || body.taskId.trim() === '') {
288
+ throw new HttpError(400, 'TASK_ID_REQUIRED', 'taskId is required');
289
+ }
290
+ if (typeof body.requestId !== 'string' || body.requestId.trim() === '') {
291
+ throw new HttpError(400, 'PERMISSION_REQUEST_ID_REQUIRED', 'requestId is required');
292
+ }
293
+ if (body.decision !== 'allow-once' && body.decision !== 'reject') {
294
+ throw new HttpError(400, 'PERMISSION_DECISION_INVALID', 'decision must be allow-once or reject');
295
+ }
296
+ if (body.reason !== undefined && body.reason !== null && typeof body.reason !== 'string') {
297
+ throw new HttpError(400, 'PERMISSION_REASON_INVALID', 'reason must be a string when present');
298
+ }
299
+ if (body.fingerprint !== undefined && body.fingerprint !== null && typeof body.fingerprint !== 'string') {
300
+ throw new HttpError(400, 'PERMISSION_FINGERPRINT_INVALID', 'fingerprint must be a string when present');
301
+ }
302
+ const result = await deps.engine.decidePermission({
303
+ // The verified connection, not `body.connectionId`: a caller cannot name an owner.
304
+ connectionId: connection.connectionId,
305
+ taskId: body.taskId,
306
+ requestId: body.requestId,
307
+ decision: body.decision,
308
+ ...(typeof body.reason === 'string' ? { reason: body.reason } : {}),
309
+ ...(typeof body.fingerprint === 'string' ? { fingerprint: body.fingerprint } : {}),
310
+ });
311
+ sendJson(res, 200, { ok: true, ...result });
312
+ }
313
+
314
+ /**
315
+ * Report a bounded observation of one task of this connection.
316
+ *
317
+ * The route is a *read with a deadline*, not a write: it creates no task, consumes
318
+ * no grant, allocates no slot, decides no permission and changes no switch. What it
319
+ * adds over `/tasks/get` is that the answer may arrive later, and that it arrives
320
+ * as soon as the task reaches a state a host must act on — a permission request, a
321
+ * finished run, a failure, a cancellation — instead of forcing a client to poll.
322
+ *
323
+ * Three properties are enforced here rather than left to the MCP adapter:
324
+ *
325
+ * 1. **Ownership is proven by the same rule as `/tasks/get`**: an unknown task and
326
+ * another connection's task produce one answer, so an observation cannot be
327
+ * used to learn that a task id exists elsewhere.
328
+ * 2. **The wait is bounded** at {@link MAX_OBSERVE_WAIT_MS}, and a negative or
329
+ * non-integer `waitMs` is refused rather than clamped into something the caller
330
+ * did not ask for.
331
+ * 3. **Abandonment ends only this observer.** When the requesting connection goes
332
+ * away the wait is aborted with an `AbortSignal`; the worker keeps running and
333
+ * nothing about the task is changed. A normal request that has already been
334
+ * fully read is NOT an abandonment: after the body is consumed, `req` emits
335
+ * `close` for every request, so only a real `aborted`/stream error or a
336
+ * premature response close counts.
337
+ * @param {object} context - `req`, `res`, `connection`, `deps`.
338
+ * @returns {Promise<void>} resolves after the answer is sent (or after abandonment).
339
+ */
340
+ async function observeTask({ req, res, connection, deps }) {
341
+ const body = await readJsonBody(req);
342
+ for (const key of Object.keys(body)) {
343
+ if (!OBSERVE_FIELDS.includes(key)) {
344
+ throw new HttpError(400, 'OBSERVE_ARGUMENT_UNKNOWN', `tasks/observe does not accept ${JSON.stringify(key)}`);
345
+ }
346
+ }
347
+ if (typeof body.taskId !== 'string' || body.taskId.trim() === '') {
348
+ throw new HttpError(400, 'TASK_ID_REQUIRED', 'taskId is required');
349
+ }
350
+ let waitMs = MAX_OBSERVE_WAIT_MS;
351
+ if (body.waitMs !== undefined && body.waitMs !== null) {
352
+ if (!Number.isInteger(body.waitMs) || body.waitMs < 0) {
353
+ throw new HttpError(400, 'OBSERVE_WAIT_INVALID', 'waitMs must be a non-negative integer');
354
+ }
355
+ waitMs = Math.min(body.waitMs, MAX_OBSERVE_WAIT_MS);
356
+ }
357
+
358
+ const abandonment = createAbandonment(req, res);
359
+ try {
360
+ const observation = await deps.engine.observeTask(body.taskId, {
361
+ // The verified connection, never a body field: a caller cannot name an owner.
362
+ connectionId: connection.connectionId,
363
+ waitMs,
364
+ signal: abandonment.signal,
365
+ });
366
+ // The reader left while the engine was settling: there is nothing to answer,
367
+ // and writing to a closed response would only throw into the refusal path.
368
+ if (abandonment.abandoned() || !isWritable(res)) return;
369
+ sendJson(res, 200, { ok: true, ...observation });
370
+ } finally {
371
+ abandonment.dispose();
372
+ }
373
+ }
374
+
375
+ /**
376
+ * Watch one request/response pair for a real, premature disconnect.
377
+ *
378
+ * A node `IncomingMessage` emits `close` after the body has been consumed on every
379
+ * request, including a perfectly normal one whose handler is still working. So
380
+ * `close` on the request is only treated as abandonment while the body has NOT been
381
+ * fully read; once it has, the only evidence of abandonment is `aborted` on the
382
+ * request, an error on its stream, or the response being closed before it finished.
383
+ *
384
+ * Every listener registered here is removed by {@link dispose}, so a completed
385
+ * observation leaves no accumulating listeners behind on a request object the
386
+ * caller may keep.
387
+ * @param {import('node:http').IncomingMessage} req - request.
388
+ * @param {import('node:http').ServerResponse} res - response.
389
+ * @returns {{ signal: AbortSignal, abandoned: () => boolean, dispose: () => void }} watcher.
390
+ */
391
+ function createAbandonment(req, res) {
392
+ const controller = new AbortController();
393
+ let gone = false;
394
+ const mark = (reason) => {
395
+ if (gone) return;
396
+ gone = true;
397
+ controller.abort(Object.assign(new Error(reason), { name: 'AbortError', code: reason }));
398
+ };
399
+ const onRequestAborted = () => mark('OBSERVE_CLIENT_ABORTED');
400
+ const onRequestError = () => mark('OBSERVE_CLIENT_ABORTED');
401
+ const onRequestClose = () => {
402
+ // `readableEnded` is the fact that separates "the body was consumed" from "the
403
+ // caller vanished mid-wait". Without this distinction every normal request
404
+ // would abort its own observation the moment the body finished.
405
+ if (req.readableEnded !== true) mark('OBSERVE_CLIENT_ABORTED');
406
+ };
407
+ const onResponseClose = () => {
408
+ // A response is closed only after it finished, or because the socket died.
409
+ if (res.writableFinished !== true) mark('OBSERVE_CLIENT_ABORTED');
410
+ };
411
+ req.once?.('aborted', onRequestAborted);
412
+ req.once?.('error', onRequestError);
413
+ req.once?.('close', onRequestClose);
414
+ res.once?.('close', onResponseClose);
415
+
416
+ return {
417
+ signal: controller.signal,
418
+ abandoned: () => gone,
419
+ dispose() {
420
+ req.off?.('aborted', onRequestAborted);
421
+ req.off?.('error', onRequestError);
422
+ req.off?.('close', onRequestClose);
423
+ res.off?.('close', onResponseClose);
424
+ },
425
+ };
426
+ }
427
+
428
+ /**
429
+ * Report what a workspace looks like and which isolation it implies.
430
+ *
431
+ * Deliberately *not* gated on the switch or on the concurrency cap: this answers a
432
+ * question about the filesystem, so it must be usable while delegation is off
433
+ * (that is when a coordinator decides whether dispatch is worthwhile) and while
434
+ * every slot is busy. It is still behind the same transport fence and the same
435
+ * connection identity as every other route, and it consumes nothing: no grant, no
436
+ * slot, no task, no commit, no worktree.
437
+ *
438
+ * The `engine` is given the runner the workspace layer already uses
439
+ * (`deps.runGit`), so the preflight measures with the same seam, the same timeout
440
+ * and the same failure classification the job itself would.
441
+ * @param {object} context - `req`, `res`, `deps`.
442
+ * @returns {Promise<void>} resolves after the answer is sent.
443
+ */
444
+ async function preflight({ req, res, deps }) {
445
+ const body = await readJsonBody(req);
446
+ if (typeof body.workspacePath !== 'string' || body.workspacePath.trim() === '') {
447
+ throw new HttpError(400, 'WORKSPACE_PATH_REQUIRED', 'workspacePath is required');
448
+ }
449
+ const result = await preflightWorkspace({ runGit: deps.runGit }, {
450
+ workspacePath: body.workspacePath,
451
+ allowShared: body.allowShared === true,
452
+ });
453
+ sendJson(res, 200, result);
454
+ }