dsh-taskbridge 1.3.2 → 1.4.0

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.
@@ -1,175 +1,179 @@
1
- // Shared HTTP plumbing for both delegation planes.
2
- //
3
- // The helpers here are deliberately dumb: they parse a bounded JSON body, emit
4
- // a JSON response, and translate refusals into status codes. Every decision
5
- // about *whether* a request may proceed lives in the plane that owns the route.
6
-
7
- /** Bound on a request body. A control request is small by nature. */
8
- export const MAX_BODY_BYTES = 512 * 1024;
9
-
10
- /**
11
- * Read a bounded JSON body from a node request stream.
12
- * @param {import('node:http').IncomingMessage} req - request.
13
- * @param {number} [limit] - byte bound.
14
- * @returns {Promise<object>} parsed body, or an empty object when absent.
15
- */
16
- export async function readJsonBody(req, limit = MAX_BODY_BYTES) {
17
- const chunks = [];
18
- let size = 0;
19
- for await (const chunk of req) {
20
- size += chunk.length;
21
- if (size > limit) {
22
- throw new HttpError(413, 'BODY_TOO_LARGE', `request body exceeds ${limit} bytes`);
23
- }
24
- chunks.push(chunk);
25
- }
26
- if (chunks.length === 0) return {};
27
- const text = Buffer.concat(chunks).toString('utf8').trim();
28
- if (text === '') return {};
29
- try {
30
- const parsed = JSON.parse(text);
31
- if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
32
- throw new HttpError(400, 'BODY_NOT_OBJECT', 'request body must be a JSON object');
33
- }
34
- return parsed;
35
- } catch (error) {
36
- if (error instanceof HttpError) throw error;
37
- throw new HttpError(400, 'BODY_INVALID_JSON', 'request body is not valid JSON');
38
- }
39
- }
40
-
41
- /**
42
- * Read a bounded JSON body from a WHATWG Request.
43
- * @param {Request} request - fetch-style request.
44
- * @param {number} [limit] - byte bound.
45
- * @returns {Promise<object>} parsed body, or an empty object when absent.
46
- */
47
- export async function readJsonRequest(request, limit = MAX_BODY_BYTES) {
48
- const text = await request.text();
49
- if (Buffer.byteLength(text, 'utf8') > limit) {
50
- throw new HttpError(413, 'BODY_TOO_LARGE', `request body exceeds ${limit} bytes`);
51
- }
52
- if (text.trim() === '') return {};
53
- try {
54
- const parsed = JSON.parse(text);
55
- if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
56
- throw new HttpError(400, 'BODY_NOT_OBJECT', 'request body must be a JSON object');
57
- }
58
- return parsed;
59
- } catch (error) {
60
- if (error instanceof HttpError) throw error;
61
- throw new HttpError(400, 'BODY_INVALID_JSON', 'request body is not valid JSON');
62
- }
63
- }
64
-
65
- /** An HTTP-level refusal with a stable code. */
66
- export class HttpError extends Error {
67
- /**
68
- * @param {number} status - HTTP status.
69
- * @param {string} code - stable machine code.
70
- * @param {string} message - explanation.
71
- * @param {object} [details] - bounded details.
72
- */
73
- constructor(status, code, message, details = {}) {
74
- super(message);
75
- this.name = 'HttpError';
76
- this.status = status;
77
- this.code = code;
78
- this.details = details;
79
- }
80
- }
81
-
82
- /**
83
- * Emit a JSON response on a node response object.
84
- * @param {import('node:http').ServerResponse} res - response.
85
- * @param {number} status - status code.
86
- * @param {unknown} payload - JSON payload.
87
- * @param {Record<string, string>} [headers] - extra headers.
88
- * @returns {void}
89
- */
90
- export function sendJson(res, status, payload, headers = {}) {
91
- const body = Buffer.from(`${JSON.stringify(payload)}\n`, 'utf8');
92
- res.writeHead(status, {
93
- 'content-type': 'application/json; charset=utf-8',
94
- 'content-length': String(body.byteLength),
95
- // These responses carry authorization state; they must never be cached or
96
- // sniffed into another context.
97
- 'cache-control': 'no-store',
98
- 'x-content-type-options': 'nosniff',
99
- ...headers,
100
- });
101
- res.end(body);
102
- }
103
-
104
- /**
105
- * Build a WHATWG JSON response for a fetch-style route.
106
- * @param {number} status - status code.
107
- * @param {unknown} payload - JSON payload.
108
- * @param {Record<string, string>} [headers] - extra headers.
109
- * @returns {Response} response.
110
- */
111
- export function jsonResponse(status, payload, headers = {}) {
112
- return new Response(`${JSON.stringify(payload)}\n`, {
113
- status,
114
- headers: {
115
- 'content-type': 'application/json; charset=utf-8',
116
- 'cache-control': 'no-store',
117
- 'x-content-type-options': 'nosniff',
118
- ...headers,
119
- },
120
- });
121
- }
122
-
123
- /**
124
- * Map a thrown value onto a status/code pair without leaking internals.
125
- *
126
- * Known refusals keep their own code so a caller can act on it; anything
127
- * unrecognized becomes a generic 500 with no message from the original error.
128
- * @param {unknown} error - thrown value.
129
- * @returns {{ status: number, code: string, message: string, details: object }} mapping.
130
- */
131
- export function classifyError(error) {
132
- if (error instanceof HttpError) {
133
- return { status: error.status, code: error.code, message: error.message, details: error.details ?? {} };
134
- }
135
- const code = typeof error?.code === 'string' ? error.code : null;
136
- const details = error?.details !== null && typeof error?.details === 'object' ? error.details : {};
137
- const message = typeof error?.message === 'string' ? error.message : 'the request could not be completed';
138
- if (code === null) {
139
- return { status: 500, code: 'INTERNAL_ERROR', message: 'the request could not be completed', details: {} };
140
- }
141
- return { status: statusForCode(code), code, message, details };
142
- }
143
-
144
- function statusForCode(code) {
145
- if (code === AUTH_UNAUTHENTICATED) return 401;
146
- if (code.startsWith('USER_PLANE_') || code.startsWith('CONNECTION_')) return 403;
147
- if (code.endsWith('_NOT_FOUND') || code === 'GRANT_UNKNOWN' || code === 'CONNECTION_UNKNOWN') return 404;
148
- if (code.startsWith('SETTINGS_') || code.startsWith('PROVIDER_') || code.startsWith('MODEL_')) return 400;
149
- if (code.startsWith('SELECTION_')) return 409;
150
- if (code.startsWith('GRANT_')) return 409;
151
- if (code === 'WORKSPACE_BUSY') return 409;
152
- if (code.startsWith('ROUTING_')) return 409;
153
- if (code.startsWith('AUDIT_')) return 409;
154
- // An archived task is not a request error: the task exists, but only as a
155
- // durable record, so the action conflicts with the task's real state.
156
- if (code === 'JOB_ARCHIVED_TASK') return 409;
157
- if (code.startsWith('JOB_')) return 409;
158
- // The credential seam is a separate service. "It is not installed here" is a
159
- // capability gap (503), "the backend refused the write" is an upstream failure
160
- // (502), and "the caller sent no usable value" is the caller's mistake (400).
161
- if (code === 'CREDENTIAL_SEAM_UNAVAILABLE') return 503;
162
- if (code === 'CREDENTIAL_OPERATION_FAILED' || code === 'CREDENTIAL_READ_ONLY') return 502;
163
- if (code === 'CREDENTIAL_VALUE_REQUIRED' || code === 'CREDENTIAL_VALUE_TOO_LARGE' || code === 'CREDENTIAL_REF_INVALID') return 400;
164
- if (code.startsWith('CREDENTIAL_')) return 409;
165
- // Codex integration: the operator's own Codex home/config is the subject, so a
166
- // refusal to touch it is a state conflict, and a malformed request a 400.
167
- if (code === 'CODEX_INTEGRATION_UNAVAILABLE') return 503;
168
- if (code === 'CODEX_HOME_INVALID' || code === 'CODEX_ACTION_INVALID') return 400;
169
- if (code.startsWith('CODEX_') || code.startsWith('MCP_') || code.startsWith('AGENT_')) return 409;
170
- if (code === 'BODY_TOO_LARGE') return 413;
171
- if (code === 'BODY_INVALID_JSON' || code === 'BODY_NOT_OBJECT') return 400;
172
- return 400;
173
- }
174
-
175
- const AUTH_UNAUTHENTICATED = 'USER_PLANE_UNAUTHENTICATED';
1
+ // Shared HTTP plumbing for both delegation planes.
2
+ //
3
+ // The helpers here are deliberately dumb: they parse a bounded JSON body, emit
4
+ // a JSON response, and translate refusals into status codes. Every decision
5
+ // about *whether* a request may proceed lives in the plane that owns the route.
6
+
7
+ /** Bound on a request body. A control request is small by nature. */
8
+ export const MAX_BODY_BYTES = 512 * 1024;
9
+
10
+ /**
11
+ * Read a bounded JSON body from a node request stream.
12
+ * @param {import('node:http').IncomingMessage} req - request.
13
+ * @param {number} [limit] - byte bound.
14
+ * @returns {Promise<object>} parsed body, or an empty object when absent.
15
+ */
16
+ export async function readJsonBody(req, limit = MAX_BODY_BYTES) {
17
+ const chunks = [];
18
+ let size = 0;
19
+ for await (const chunk of req) {
20
+ size += chunk.length;
21
+ if (size > limit) {
22
+ throw new HttpError(413, 'BODY_TOO_LARGE', `request body exceeds ${limit} bytes`);
23
+ }
24
+ chunks.push(chunk);
25
+ }
26
+ if (chunks.length === 0) return {};
27
+ const text = Buffer.concat(chunks).toString('utf8').trim();
28
+ if (text === '') return {};
29
+ try {
30
+ const parsed = JSON.parse(text);
31
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
32
+ throw new HttpError(400, 'BODY_NOT_OBJECT', 'request body must be a JSON object');
33
+ }
34
+ return parsed;
35
+ } catch (error) {
36
+ if (error instanceof HttpError) throw error;
37
+ throw new HttpError(400, 'BODY_INVALID_JSON', 'request body is not valid JSON');
38
+ }
39
+ }
40
+
41
+ /**
42
+ * Read a bounded JSON body from a WHATWG Request.
43
+ * @param {Request} request - fetch-style request.
44
+ * @param {number} [limit] - byte bound.
45
+ * @returns {Promise<object>} parsed body, or an empty object when absent.
46
+ */
47
+ export async function readJsonRequest(request, limit = MAX_BODY_BYTES) {
48
+ const text = await request.text();
49
+ if (Buffer.byteLength(text, 'utf8') > limit) {
50
+ throw new HttpError(413, 'BODY_TOO_LARGE', `request body exceeds ${limit} bytes`);
51
+ }
52
+ if (text.trim() === '') return {};
53
+ try {
54
+ const parsed = JSON.parse(text);
55
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
56
+ throw new HttpError(400, 'BODY_NOT_OBJECT', 'request body must be a JSON object');
57
+ }
58
+ return parsed;
59
+ } catch (error) {
60
+ if (error instanceof HttpError) throw error;
61
+ throw new HttpError(400, 'BODY_INVALID_JSON', 'request body is not valid JSON');
62
+ }
63
+ }
64
+
65
+ /** An HTTP-level refusal with a stable code. */
66
+ export class HttpError extends Error {
67
+ /**
68
+ * @param {number} status - HTTP status.
69
+ * @param {string} code - stable machine code.
70
+ * @param {string} message - explanation.
71
+ * @param {object} [details] - bounded details.
72
+ */
73
+ constructor(status, code, message, details = {}) {
74
+ super(message);
75
+ this.name = 'HttpError';
76
+ this.status = status;
77
+ this.code = code;
78
+ this.details = details;
79
+ }
80
+ }
81
+
82
+ /**
83
+ * Emit a JSON response on a node response object.
84
+ * @param {import('node:http').ServerResponse} res - response.
85
+ * @param {number} status - status code.
86
+ * @param {unknown} payload - JSON payload.
87
+ * @param {Record<string, string>} [headers] - extra headers.
88
+ * @returns {void}
89
+ */
90
+ export function sendJson(res, status, payload, headers = {}) {
91
+ const body = Buffer.from(`${JSON.stringify(payload)}\n`, 'utf8');
92
+ res.writeHead(status, {
93
+ 'content-type': 'application/json; charset=utf-8',
94
+ 'content-length': String(body.byteLength),
95
+ // These responses carry authorization state; they must never be cached or
96
+ // sniffed into another context.
97
+ 'cache-control': 'no-store',
98
+ 'x-content-type-options': 'nosniff',
99
+ ...headers,
100
+ });
101
+ res.end(body);
102
+ }
103
+
104
+ /**
105
+ * Build a WHATWG JSON response for a fetch-style route.
106
+ * @param {number} status - status code.
107
+ * @param {unknown} payload - JSON payload.
108
+ * @param {Record<string, string>} [headers] - extra headers.
109
+ * @returns {Response} response.
110
+ */
111
+ export function jsonResponse(status, payload, headers = {}) {
112
+ return new Response(`${JSON.stringify(payload)}\n`, {
113
+ status,
114
+ headers: {
115
+ 'content-type': 'application/json; charset=utf-8',
116
+ 'cache-control': 'no-store',
117
+ 'x-content-type-options': 'nosniff',
118
+ ...headers,
119
+ },
120
+ });
121
+ }
122
+
123
+ /**
124
+ * Map a thrown value onto a status/code pair without leaking internals.
125
+ *
126
+ * Known refusals keep their own code so a caller can act on it; anything
127
+ * unrecognized becomes a generic 500 with no message from the original error.
128
+ * @param {unknown} error - thrown value.
129
+ * @returns {{ status: number, code: string, message: string, details: object }} mapping.
130
+ */
131
+ export function classifyError(error) {
132
+ if (error instanceof HttpError) {
133
+ return { status: error.status, code: error.code, message: error.message, details: error.details ?? {} };
134
+ }
135
+ const code = typeof error?.code === 'string' ? error.code : null;
136
+ const details = error?.details !== null && typeof error?.details === 'object' ? error.details : {};
137
+ const message = typeof error?.message === 'string' ? error.message : 'the request could not be completed';
138
+ if (code === null) {
139
+ return { status: 500, code: 'INTERNAL_ERROR', message: 'the request could not be completed', details: {} };
140
+ }
141
+ return { status: statusForCode(code), code, message, details };
142
+ }
143
+
144
+ function statusForCode(code) {
145
+ if (code === AUTH_UNAUTHENTICATED) return 401;
146
+ if (code.startsWith('USER_PLANE_') || code.startsWith('CONNECTION_')) return 403;
147
+ if (code.endsWith('_NOT_FOUND') || code === 'GRANT_UNKNOWN' || code === 'CONNECTION_UNKNOWN') return 404;
148
+ if (code.startsWith('SETTINGS_') || code.startsWith('PROVIDER_') || code.startsWith('MODEL_')) return 400;
149
+ if (code.startsWith('SELECTION_')) return 409;
150
+ if (code.startsWith('GRANT_')) return 409;
151
+ if (code === 'WORKSPACE_BUSY') return 409;
152
+ if (code.startsWith('ROUTING_')) return 409;
153
+ if (code.startsWith('AUDIT_')) return 409;
154
+ // An archived task is not a request error: the task exists, but only as a
155
+ // durable record, so the action conflicts with the task's real state.
156
+ if (code === 'JOB_ARCHIVED_TASK') return 409;
157
+ // A malformed review request is the caller's mistake; an unpersisted one is an
158
+ // upstream failure; "this task cannot be reviewed (now)" conflicts with its state.
159
+ if (code === 'JOB_REVIEW_INVALID') return 400;
160
+ if (code === 'JOB_REVIEW_NOT_PERSISTED') return 502;
161
+ if (code.startsWith('JOB_')) return 409;
162
+ // The credential seam is a separate service. "It is not installed here" is a
163
+ // capability gap (503), "the backend refused the write" is an upstream failure
164
+ // (502), and "the caller sent no usable value" is the caller's mistake (400).
165
+ if (code === 'CREDENTIAL_SEAM_UNAVAILABLE') return 503;
166
+ if (code === 'CREDENTIAL_OPERATION_FAILED' || code === 'CREDENTIAL_READ_ONLY') return 502;
167
+ if (code === 'CREDENTIAL_VALUE_REQUIRED' || code === 'CREDENTIAL_VALUE_TOO_LARGE' || code === 'CREDENTIAL_REF_INVALID') return 400;
168
+ if (code.startsWith('CREDENTIAL_')) return 409;
169
+ // Codex integration: the operator's own Codex home/config is the subject, so a
170
+ // refusal to touch it is a state conflict, and a malformed request a 400.
171
+ if (code === 'CODEX_INTEGRATION_UNAVAILABLE') return 503;
172
+ if (code === 'CODEX_HOME_INVALID' || code === 'CODEX_ACTION_INVALID') return 400;
173
+ if (code.startsWith('CODEX_') || code.startsWith('MCP_') || code.startsWith('AGENT_')) return 409;
174
+ if (code === 'BODY_TOO_LARGE') return 413;
175
+ if (code === 'BODY_INVALID_JSON' || code === 'BODY_NOT_OBJECT') return 400;
176
+ return 400;
177
+ }
178
+
179
+ const AUTH_UNAUTHENTICATED = 'USER_PLANE_UNAUTHENTICATED';
package/src/index.d.ts CHANGED
@@ -226,6 +226,17 @@ export interface DelegateTaskActivity {
226
226
  /** The thresholds this task froze at admission. */
227
227
  selfCheckSeconds: number;
228
228
  attentionSeconds: number;
229
+ /**
230
+ * The repeated-failure reminder: how many consecutive identical tool failures are
231
+ * reported once (`0` = off), and the bounded trail of episodes already reported.
232
+ *
233
+ * Optional and nullable: a record stored by an older build has no such field, and
234
+ * `repeatFailureOf` projects one as `null`, so a stored history row may omit it.
235
+ */
236
+ repeatFailure?: {
237
+ threshold: number;
238
+ reported: DelegateRepeatedFailure[];
239
+ } | null;
229
240
  /**
230
241
  * `null` while the run is live. Once the task ended it holds the recorded end, and
231
242
  * every elapsed value above is measured against it — a stored or queried record
@@ -242,6 +253,40 @@ export interface DelegateTaskActivity {
242
253
  interruptedTool?: { name: string | null; callId: string | null; startedAt: number | null; elapsedMs: number | null } | null;
243
254
  }
244
255
 
256
+ /**
257
+ * One reported repeated-failure episode.
258
+ *
259
+ * Only identifiers, a digest and counts: the native tool arguments, the result content,
260
+ * the error's free text and any model output are never retained, so nothing here can
261
+ * carry them.
262
+ */
263
+ export interface DelegateRepeatedFailure {
264
+ /** Fixed discriminator, so a client can tell this apart from a silence report. */
265
+ kind: 'repeated-tool-failure';
266
+ /** The native tool name. */
267
+ toolName: string;
268
+ /**
269
+ * A recognized common tool failure code (for example `ENOENT`, `EACCES`, `TIMEOUT`), or
270
+ * `TOOL_ERROR` for anything this build does not positively recognize. An arbitrary
271
+ * `error.code`/`error.name` is never echoed: it is free text that can carry a path or a
272
+ * token.
273
+ */
274
+ failureCode: string;
275
+ /** 16-hex digest of the operation, never the operation itself. */
276
+ operationDigest: string;
277
+ /** How many identical failures were counted when the reminder fired. */
278
+ consecutive: number;
279
+ /** The threshold in force for this task. */
280
+ threshold: number;
281
+ /**
282
+ * When the FIRST failure of this episode happened, not when the threshold was reached:
283
+ * the episode is older than the reminder.
284
+ */
285
+ firstSeenAt: number;
286
+ /** When the failure that completed the threshold happened. */
287
+ lastSeenAt: number;
288
+ }
289
+
245
290
  /** Why one observation of a running task returned. */
246
291
  export type DelegateObserveReason =
247
292
  | 'heartbeat'
@@ -274,12 +319,61 @@ export interface DelegateObservationSummary {
274
319
  model: string | null;
275
320
  reasoningEffort: string | null;
276
321
  isolation: string | null;
277
- monitoring: { selfCheckSeconds: number | null; attentionSeconds: number | null };
322
+ monitoring: {
323
+ selfCheckSeconds: number | null;
324
+ attentionSeconds: number | null;
325
+ repeatFailureThreshold: number | null;
326
+ };
278
327
  } | null;
279
328
  connectionId: string | null;
280
329
  /** Always false: execution completion is not host acceptance. */
281
330
  selfApproved: false;
282
- hostAcceptance: null;
331
+ /** The commander's recorded delivery review, or null while none exists. */
332
+ hostAcceptance: DelegateHostAcceptance | null;
333
+ }
334
+
335
+ /**
336
+ * A replayed (idempotent) review request and its answer.
337
+ *
338
+ * `decision` is the closed vocabulary the review verb accepts; a note is required and
339
+ * bounded. Repeating the same decision with the same note is a no-op; a different
340
+ * conclusion is refused.
341
+ */
342
+ export interface DelegateReviewRequest {
343
+ taskId: string;
344
+ decision: 'accepted' | 'changes-requested';
345
+ /** Required, non-empty, at most 1000 characters; stored redacted. */
346
+ note: string;
347
+ }
348
+
349
+ /** Answer of one recorded delivery review. */
350
+ export interface DelegateReviewResult {
351
+ /**
352
+ * The public task view after the decision. Its `state` stays `awaiting-host-review`
353
+ * (that is the compatible underlying state); the conclusion is `hostAcceptance`.
354
+ */
355
+ task: { taskId: string; state: string; phase: string; hostAcceptance: DelegateHostAcceptance | null };
356
+ hostAcceptance: DelegateHostAcceptance;
357
+ }
358
+
359
+ /**
360
+ * The commander's recorded delivery review of one finished task.
361
+ *
362
+ * This is the ONLY record that turns "execution finished" into a host conclusion. It is
363
+ * written by the review verb, never derived from a task's state, and the first decision is
364
+ * final for that task.
365
+ */
366
+ export interface DelegateHostAcceptance {
367
+ /** True only when the recorded decision was `accepted`. */
368
+ accepted: boolean;
369
+ /** The recorded conclusion. */
370
+ state: 'accepted' | 'changes-requested';
371
+ /** When the decision was recorded, in epoch milliseconds. */
372
+ acceptedAt: number;
373
+ /** Fixed marker for who recorded it; never a caller-supplied name. */
374
+ by: string;
375
+ /** The redacted, bounded conclusion. */
376
+ note: string;
283
377
  }
284
378
 
285
379
  /** Result of one bounded observation of a delegated task. */
@@ -292,6 +386,12 @@ export interface DelegateObservation {
292
386
  * never shortened into an undecidable summary.
293
387
  */
294
388
  permission: DelegatePendingPermission | null;
389
+ /**
390
+ * Present only when `reason` is `attention` AND the reminder is about repeated
391
+ * failures rather than silence. `null`/absent for an ordinary silence report, which
392
+ * keeps the two distinguishable without a new reason value.
393
+ */
394
+ failure?: DelegateRepeatedFailure | null;
295
395
  activity: DelegateTaskActivity | null;
296
396
  selfCheck: { episode: number | null; checkedAt: number | null; verdict: string | null } | null;
297
397
  /**
package/src/index.js CHANGED
@@ -511,7 +511,7 @@ export async function apply(ctx, config = {}) {
511
511
  }
512
512
 
513
513
  /** Version reported by the runtime facts block. Mirrors `package.json`. */
514
- const PLUGIN_VERSION = '1.3.2';
514
+ const PLUGIN_VERSION = '1.4.0';
515
515
 
516
516
  /**
517
517
  * Read the native approval service without turning absence into a throw.