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,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,456 @@
|
|
|
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
|
+
...(body.title === undefined ? {} : { title: body.title }),
|
|
216
|
+
overrides: body.overrides,
|
|
217
|
+
...(continueFromTaskId === undefined ? {} : { continueFromTaskId }),
|
|
218
|
+
});
|
|
219
|
+
sendJson(res, 202, { ok: true, task });
|
|
220
|
+
return;
|
|
221
|
+
}
|
|
222
|
+
const authorization = body.authorization === 'session' ? 'session' : 'task';
|
|
223
|
+
if (authorization === 'task' && typeof body.grantId !== 'string') {
|
|
224
|
+
throw new HttpError(400, 'GRANT_ID_REQUIRED', 'grantId is required for a single-task submission');
|
|
225
|
+
}
|
|
226
|
+
const task = await deps.engine.start({
|
|
227
|
+
// The connection identity comes from the verified token, never from the body.
|
|
228
|
+
connectionId: connection.connectionId,
|
|
229
|
+
grantId: body.grantId,
|
|
230
|
+
authorization,
|
|
231
|
+
workspacePath: body.workspacePath,
|
|
232
|
+
prompt: body.prompt,
|
|
233
|
+
...(body.title === undefined ? {} : { title: body.title }),
|
|
234
|
+
overrides: body.overrides,
|
|
235
|
+
...(continueFromTaskId === undefined ? {} : { continueFromTaskId }),
|
|
236
|
+
});
|
|
237
|
+
sendJson(res, 202, { ok: true, task });
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
async function listTasks({ res, connection, deps }) {
|
|
241
|
+
sendJson(res, 200, { ok: true, tasks: deps.engine.list({ connectionId: connection.connectionId }) });
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
async function getTask({ req, res, connection, deps }) {
|
|
245
|
+
const body = await readJsonBody(req);
|
|
246
|
+
if (typeof body.taskId !== 'string') {
|
|
247
|
+
throw new HttpError(400, 'TASK_ID_REQUIRED', 'taskId is required');
|
|
248
|
+
}
|
|
249
|
+
const task = deps.engine.get(body.taskId);
|
|
250
|
+
if (task.connectionId !== connection.connectionId) {
|
|
251
|
+
// Cross-connection reads are reported as absent, not as forbidden: a
|
|
252
|
+
// distinct code would confirm that a task id exists.
|
|
253
|
+
throw new HttpError(404, 'JOB_TASK_NOT_FOUND', 'no such task for this connection');
|
|
254
|
+
}
|
|
255
|
+
sendJson(res, 200, { ok: true, task });
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
async function cancelTask({ req, res, connection, deps }) {
|
|
259
|
+
const body = await readJsonBody(req);
|
|
260
|
+
if (typeof body.taskId !== 'string') {
|
|
261
|
+
throw new HttpError(400, 'TASK_ID_REQUIRED', 'taskId is required');
|
|
262
|
+
}
|
|
263
|
+
const existing = deps.engine.get(body.taskId);
|
|
264
|
+
if (existing.connectionId !== connection.connectionId) {
|
|
265
|
+
throw new HttpError(404, 'JOB_TASK_NOT_FOUND', 'no such task for this connection');
|
|
266
|
+
}
|
|
267
|
+
const task = await deps.engine.cancel(body.taskId, 'connection');
|
|
268
|
+
sendJson(res, 200, { ok: true, task });
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
/**
|
|
272
|
+
* Decide one pending per-call permission request of one task.
|
|
273
|
+
*
|
|
274
|
+
* The connection identity comes from authentication, never from the body, and it
|
|
275
|
+
* is the same identity that owns the task: the engine reports a task of another
|
|
276
|
+
* connection — and an unknown one — as `JOB_TASK_NOT_FOUND`, one answer with one
|
|
277
|
+
* set of details, so a decision call cannot be used to learn which task ids or
|
|
278
|
+
* pending requests exist elsewhere.
|
|
279
|
+
*
|
|
280
|
+
* The body is validated here (not only in the MCP server) because this route is
|
|
281
|
+
* reachable by any local caller: an unknown field, a decision outside the closed
|
|
282
|
+
* vocabulary, or a reason that is not a string is refused before the engine reads
|
|
283
|
+
* anything.
|
|
284
|
+
* @param {object} context - `req`, `res`, `connection`, `deps`.
|
|
285
|
+
* @returns {Promise<void>} resolves after the answer is sent.
|
|
286
|
+
*/
|
|
287
|
+
async function decidePermission({ req, res, connection, deps }) {
|
|
288
|
+
const body = await readJsonBody(req);
|
|
289
|
+
if (typeof body.taskId !== 'string' || body.taskId.trim() === '') {
|
|
290
|
+
throw new HttpError(400, 'TASK_ID_REQUIRED', 'taskId is required');
|
|
291
|
+
}
|
|
292
|
+
if (typeof body.requestId !== 'string' || body.requestId.trim() === '') {
|
|
293
|
+
throw new HttpError(400, 'PERMISSION_REQUEST_ID_REQUIRED', 'requestId is required');
|
|
294
|
+
}
|
|
295
|
+
if (body.decision !== 'allow-once' && body.decision !== 'reject') {
|
|
296
|
+
throw new HttpError(400, 'PERMISSION_DECISION_INVALID', 'decision must be allow-once or reject');
|
|
297
|
+
}
|
|
298
|
+
if (body.reason !== undefined && body.reason !== null && typeof body.reason !== 'string') {
|
|
299
|
+
throw new HttpError(400, 'PERMISSION_REASON_INVALID', 'reason must be a string when present');
|
|
300
|
+
}
|
|
301
|
+
if (body.fingerprint !== undefined && body.fingerprint !== null && typeof body.fingerprint !== 'string') {
|
|
302
|
+
throw new HttpError(400, 'PERMISSION_FINGERPRINT_INVALID', 'fingerprint must be a string when present');
|
|
303
|
+
}
|
|
304
|
+
const result = await deps.engine.decidePermission({
|
|
305
|
+
// The verified connection, not `body.connectionId`: a caller cannot name an owner.
|
|
306
|
+
connectionId: connection.connectionId,
|
|
307
|
+
taskId: body.taskId,
|
|
308
|
+
requestId: body.requestId,
|
|
309
|
+
decision: body.decision,
|
|
310
|
+
...(typeof body.reason === 'string' ? { reason: body.reason } : {}),
|
|
311
|
+
...(typeof body.fingerprint === 'string' ? { fingerprint: body.fingerprint } : {}),
|
|
312
|
+
});
|
|
313
|
+
sendJson(res, 200, { ok: true, ...result });
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
/**
|
|
317
|
+
* Report a bounded observation of one task of this connection.
|
|
318
|
+
*
|
|
319
|
+
* The route is a *read with a deadline*, not a write: it creates no task, consumes
|
|
320
|
+
* no grant, allocates no slot, decides no permission and changes no switch. What it
|
|
321
|
+
* adds over `/tasks/get` is that the answer may arrive later, and that it arrives
|
|
322
|
+
* as soon as the task reaches a state a host must act on — a permission request, a
|
|
323
|
+
* finished run, a failure, a cancellation — instead of forcing a client to poll.
|
|
324
|
+
*
|
|
325
|
+
* Three properties are enforced here rather than left to the MCP adapter:
|
|
326
|
+
*
|
|
327
|
+
* 1. **Ownership is proven by the same rule as `/tasks/get`**: an unknown task and
|
|
328
|
+
* another connection's task produce one answer, so an observation cannot be
|
|
329
|
+
* used to learn that a task id exists elsewhere.
|
|
330
|
+
* 2. **The wait is bounded** at {@link MAX_OBSERVE_WAIT_MS}, and a negative or
|
|
331
|
+
* non-integer `waitMs` is refused rather than clamped into something the caller
|
|
332
|
+
* did not ask for.
|
|
333
|
+
* 3. **Abandonment ends only this observer.** When the requesting connection goes
|
|
334
|
+
* away the wait is aborted with an `AbortSignal`; the worker keeps running and
|
|
335
|
+
* nothing about the task is changed. A normal request that has already been
|
|
336
|
+
* fully read is NOT an abandonment: after the body is consumed, `req` emits
|
|
337
|
+
* `close` for every request, so only a real `aborted`/stream error or a
|
|
338
|
+
* premature response close counts.
|
|
339
|
+
* @param {object} context - `req`, `res`, `connection`, `deps`.
|
|
340
|
+
* @returns {Promise<void>} resolves after the answer is sent (or after abandonment).
|
|
341
|
+
*/
|
|
342
|
+
async function observeTask({ req, res, connection, deps }) {
|
|
343
|
+
const body = await readJsonBody(req);
|
|
344
|
+
for (const key of Object.keys(body)) {
|
|
345
|
+
if (!OBSERVE_FIELDS.includes(key)) {
|
|
346
|
+
throw new HttpError(400, 'OBSERVE_ARGUMENT_UNKNOWN', `tasks/observe does not accept ${JSON.stringify(key)}`);
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
if (typeof body.taskId !== 'string' || body.taskId.trim() === '') {
|
|
350
|
+
throw new HttpError(400, 'TASK_ID_REQUIRED', 'taskId is required');
|
|
351
|
+
}
|
|
352
|
+
let waitMs = MAX_OBSERVE_WAIT_MS;
|
|
353
|
+
if (body.waitMs !== undefined && body.waitMs !== null) {
|
|
354
|
+
if (!Number.isInteger(body.waitMs) || body.waitMs < 0) {
|
|
355
|
+
throw new HttpError(400, 'OBSERVE_WAIT_INVALID', 'waitMs must be a non-negative integer');
|
|
356
|
+
}
|
|
357
|
+
waitMs = Math.min(body.waitMs, MAX_OBSERVE_WAIT_MS);
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
const abandonment = createAbandonment(req, res);
|
|
361
|
+
try {
|
|
362
|
+
const observation = await deps.engine.observeTask(body.taskId, {
|
|
363
|
+
// The verified connection, never a body field: a caller cannot name an owner.
|
|
364
|
+
connectionId: connection.connectionId,
|
|
365
|
+
waitMs,
|
|
366
|
+
signal: abandonment.signal,
|
|
367
|
+
});
|
|
368
|
+
// The reader left while the engine was settling: there is nothing to answer,
|
|
369
|
+
// and writing to a closed response would only throw into the refusal path.
|
|
370
|
+
if (abandonment.abandoned() || !isWritable(res)) return;
|
|
371
|
+
sendJson(res, 200, { ok: true, ...observation });
|
|
372
|
+
} finally {
|
|
373
|
+
abandonment.dispose();
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
/**
|
|
378
|
+
* Watch one request/response pair for a real, premature disconnect.
|
|
379
|
+
*
|
|
380
|
+
* A node `IncomingMessage` emits `close` after the body has been consumed on every
|
|
381
|
+
* request, including a perfectly normal one whose handler is still working. So
|
|
382
|
+
* `close` on the request is only treated as abandonment while the body has NOT been
|
|
383
|
+
* fully read; once it has, the only evidence of abandonment is `aborted` on the
|
|
384
|
+
* request, an error on its stream, or the response being closed before it finished.
|
|
385
|
+
*
|
|
386
|
+
* Every listener registered here is removed by {@link dispose}, so a completed
|
|
387
|
+
* observation leaves no accumulating listeners behind on a request object the
|
|
388
|
+
* caller may keep.
|
|
389
|
+
* @param {import('node:http').IncomingMessage} req - request.
|
|
390
|
+
* @param {import('node:http').ServerResponse} res - response.
|
|
391
|
+
* @returns {{ signal: AbortSignal, abandoned: () => boolean, dispose: () => void }} watcher.
|
|
392
|
+
*/
|
|
393
|
+
function createAbandonment(req, res) {
|
|
394
|
+
const controller = new AbortController();
|
|
395
|
+
let gone = false;
|
|
396
|
+
const mark = (reason) => {
|
|
397
|
+
if (gone) return;
|
|
398
|
+
gone = true;
|
|
399
|
+
controller.abort(Object.assign(new Error(reason), { name: 'AbortError', code: reason }));
|
|
400
|
+
};
|
|
401
|
+
const onRequestAborted = () => mark('OBSERVE_CLIENT_ABORTED');
|
|
402
|
+
const onRequestError = () => mark('OBSERVE_CLIENT_ABORTED');
|
|
403
|
+
const onRequestClose = () => {
|
|
404
|
+
// `readableEnded` is the fact that separates "the body was consumed" from "the
|
|
405
|
+
// caller vanished mid-wait". Without this distinction every normal request
|
|
406
|
+
// would abort its own observation the moment the body finished.
|
|
407
|
+
if (req.readableEnded !== true) mark('OBSERVE_CLIENT_ABORTED');
|
|
408
|
+
};
|
|
409
|
+
const onResponseClose = () => {
|
|
410
|
+
// A response is closed only after it finished, or because the socket died.
|
|
411
|
+
if (res.writableFinished !== true) mark('OBSERVE_CLIENT_ABORTED');
|
|
412
|
+
};
|
|
413
|
+
req.once?.('aborted', onRequestAborted);
|
|
414
|
+
req.once?.('error', onRequestError);
|
|
415
|
+
req.once?.('close', onRequestClose);
|
|
416
|
+
res.once?.('close', onResponseClose);
|
|
417
|
+
|
|
418
|
+
return {
|
|
419
|
+
signal: controller.signal,
|
|
420
|
+
abandoned: () => gone,
|
|
421
|
+
dispose() {
|
|
422
|
+
req.off?.('aborted', onRequestAborted);
|
|
423
|
+
req.off?.('error', onRequestError);
|
|
424
|
+
req.off?.('close', onRequestClose);
|
|
425
|
+
res.off?.('close', onResponseClose);
|
|
426
|
+
},
|
|
427
|
+
};
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
/**
|
|
431
|
+
* Report what a workspace looks like and which isolation it implies.
|
|
432
|
+
*
|
|
433
|
+
* Deliberately *not* gated on the switch or on the concurrency cap: this answers a
|
|
434
|
+
* question about the filesystem, so it must be usable while delegation is off
|
|
435
|
+
* (that is when a coordinator decides whether dispatch is worthwhile) and while
|
|
436
|
+
* every slot is busy. It is still behind the same transport fence and the same
|
|
437
|
+
* connection identity as every other route, and it consumes nothing: no grant, no
|
|
438
|
+
* slot, no task, no commit, no worktree.
|
|
439
|
+
*
|
|
440
|
+
* The `engine` is given the runner the workspace layer already uses
|
|
441
|
+
* (`deps.runGit`), so the preflight measures with the same seam, the same timeout
|
|
442
|
+
* and the same failure classification the job itself would.
|
|
443
|
+
* @param {object} context - `req`, `res`, `deps`.
|
|
444
|
+
* @returns {Promise<void>} resolves after the answer is sent.
|
|
445
|
+
*/
|
|
446
|
+
async function preflight({ req, res, deps }) {
|
|
447
|
+
const body = await readJsonBody(req);
|
|
448
|
+
if (typeof body.workspacePath !== 'string' || body.workspacePath.trim() === '') {
|
|
449
|
+
throw new HttpError(400, 'WORKSPACE_PATH_REQUIRED', 'workspacePath is required');
|
|
450
|
+
}
|
|
451
|
+
const result = await preflightWorkspace({ runGit: deps.runGit }, {
|
|
452
|
+
workspacePath: body.workspacePath,
|
|
453
|
+
allowShared: body.allowShared === true,
|
|
454
|
+
});
|
|
455
|
+
sendJson(res, 200, result);
|
|
456
|
+
}
|