dsh-taskbridge 1.4.1 → 1.5.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.
Files changed (41) hide show
  1. package/CHANGELOG.md +22 -1
  2. package/README.md +10 -19
  3. package/bin/dsh-delegate-mcp.d.ts +20 -3
  4. package/bin/dsh-delegate-mcp.js +15 -0
  5. package/codex/dsh-taskbridge.toml +74 -5
  6. package/docs/INTRODUCTION.md +2 -2
  7. package/docs/INTRODUCTION.zh.md +2 -2
  8. package/docs/codex-integration.md +6 -3
  9. package/docs/conversation-placement.md +44 -7
  10. package/docs/plugin-market.md +2 -2
  11. package/docs/redaction-contract.md +47 -4
  12. package/docs/releases/1.4.2.zh.md +23 -0
  13. package/docs/releases/1.5.0-token-benchmark.zh.md +73 -0
  14. package/docs/releases/1.5.0.zh.md +51 -0
  15. package/docs/runtime-compatibility.md +30 -51
  16. package/docs/silent-wait.md +84 -0
  17. package/docs/taskbridge-upgrade.md +1 -1
  18. package/docs/worker-permissions.md +154 -17
  19. package/lib/client.js +3 -0
  20. package/package.json +11 -9
  21. package/src/client/api.js +26 -0
  22. package/src/codex/installer.js +18 -0
  23. package/src/config/redact.js +72 -11
  24. package/src/http/execution-plane.js +76 -5
  25. package/src/index.d.ts +285 -0
  26. package/src/index.js +72 -2
  27. package/src/jobs/activity.js +10 -0
  28. package/src/jobs/continuation-identity.js +278 -0
  29. package/src/jobs/engine.js +326 -36
  30. package/src/jobs/history.js +53 -0
  31. package/src/mcp/continuation.js +317 -0
  32. package/src/mcp/metrics.js +343 -0
  33. package/src/mcp/server.js +1079 -47
  34. package/src/mcp/wait.js +266 -74
  35. package/src/review/prompts.js +145 -126
  36. package/src/runtime/agent-runner.js +165 -0
  37. package/src/runtime/permissions.js +192 -2
  38. package/src/runtime/question-call.js +162 -0
  39. package/src/runtime/questions.js +909 -0
  40. package/src/runtime/session-placement.js +78 -5
  41. package/src/version.js +99 -0
@@ -12,16 +12,72 @@ const BEARER_PATTERN = /\bBearer\s+[A-Za-z0-9._~+/=-]{12,}/gi;
12
12
  const KEYLIKE_PATTERN = /\b(sk|pk|ak)-[A-Za-z0-9_-]{16,}\b/g;
13
13
  const ASSIGNMENT_PATTERN = /\b([A-Za-z0-9_]*(?:API_?KEY|SECRET|TOKEN|PASSWORD)[A-Za-z0-9_]*)\s*=\s*("[^"]*"|'[^']*'|\S+)/gi;
14
14
  /**
15
- * A profile key embedded in a *directory* name, the shape this repository's own
16
- * workspace has (`…/Local/Temp/dsh-SoexNz/…`, which held the local user id). It is
17
- * masked because it identifies an account; only a path-shaped key is matched, so
18
- * an ordinary hyphenated word in prose is untouched.
15
+ * A per-user profile directory under the OPERATING SYSTEM'S temporary root.
16
+ *
17
+ * The observed shape is `%TEMP%\dsh-VG1MVl\dsh-delegate-test-…` (and on some hosts
18
+ * `~/.cache/dsh-SoexNz/…`): the platform points `TEMP` at a per-profile directory
19
+ * whose six-character suffix is the account key. That suffix is exactly what is
20
+ * masked, and the marker is `dsh-`/`profile-` plus six characters plus digits —
21
+ * nothing more.
22
+ *
23
+ * Two earlier versions were wrong in opposite directions, so the rule is stated
24
+ * around what is PROVABLE instead of around what looks unusual:
25
+ *
26
+ * * the first masked every `dsh-`/`profile-` segment with six alphanumerics, so an
27
+ * ordinary repository or package name — this product's own `dsh-delegate` and its
28
+ * installed `dsh-taskbridge` — was rewritten in every published path;
29
+ * * the second tried to tell a profile key from a word by case and digit shape. That
30
+ * is a guess: a repository may be `v2-tools`, a package `dsh-Bridge2`. A masked
31
+ * path proves nothing, so a guess that fires wrongly disables continuation.
32
+ *
33
+ * A profile key is only recognised where it actually lives: directly under a
34
+ * temporary root ({@link TEMPORARY_ROOT}), or anywhere in such a path. An ordinary
35
+ * segment elsewhere, whatever its case or digits, keeps its readable path.
19
36
  *
20
37
  * The preceding separator is captured and re-emitted so a Windows path keeps its
21
- * backslash. A single combined character class would normalise `\` to `/` and
22
- * change a path an operator is trying to recognise.
38
+ * backslash; a combined character class would normalise `\` to `/`.
39
+ */
40
+ const PROFILE_SEGMENT = String.raw`(?:dsh|profile)-[A-Za-z0-9]{6}(?![A-Za-z0-9])`;
41
+
42
+ /**
43
+ * The directory names the platform's temporary root is reached through.
44
+ *
45
+ * `temp` is the Windows/POSIX temporary root; `tmp` and `.cache` cover the POSIX and
46
+ * per-user-cache spellings. They are matched as complete, case-insensitive segment
47
+ * names, so they anchor WHERE a profile key may appear rather than being redacted.
23
48
  */
24
- const PATH_KEY_PATTERN = /([\\/])(?:dsh|profile)-[A-Za-z0-9]{6,}(?=[\\/]|$)/g;
49
+ const TEMPORARY_ROOT = String.raw`(?:temp|tmp|\.cache)`;
50
+
51
+ /**
52
+ * Mask a profile key only where it is provably one: as a segment directly under a
53
+ * temporary root. Both the separator and the temp-root segment are kept; only the key
54
+ * is replaced, so `…\Temp\dsh-VG1MVl\work` becomes `…\Temp\<mask>\work` and the
55
+ * platform's own separator survives (`/home/u/.cache/<mask>/x`).
56
+ *
57
+ * Two anchored forms, because a stored path may start at the root or continue through
58
+ * it:
59
+ *
60
+ * 1. `…<sep><temp><sep><key>…` — separators are captured and re-emitted verbatim;
61
+ * 2. `^<temp><sep><key>…` — the path begins with the root, e.g. `temp\dsh-abc123\x`.
62
+ */
63
+ const PATH_KEY_PATTERN = new RegExp(
64
+ [
65
+ String.raw`([\\/])`,
66
+ `(${TEMPORARY_ROOT})`,
67
+ String.raw`([\\/])`,
68
+ // The placeholder itself is never rewritten again, so redaction is idempotent.
69
+ String.raw`(?!(?:dsh|profile)-mask)`,
70
+ PROFILE_SEGMENT,
71
+ String.raw`(?=[\\/]|$)`,
72
+ ].join(''),
73
+ 'gi',
74
+ );
75
+
76
+ /** The same rule for a path that STARTS with the temporary root (`temp\dsh-abc123\x`). */
77
+ const LEADING_TEMP_KEY_PATTERN = new RegExp(
78
+ [`^(${TEMPORARY_ROOT})`, String.raw`([\\/])`, PROFILE_SEGMENT, String.raw`(?=[\\/]|$)`].join(''),
79
+ 'i',
80
+ );
25
81
 
26
82
  /** What {@link PATH_KEY_PATTERN} replaces the identifying segment with. */
27
83
  const PATH_KEY_SEGMENT = 'masks-user-profile-segment';
@@ -100,10 +156,15 @@ export function redactText(text) {
100
156
  .replace(BEARER_PATTERN, `Bearer ${MASK}`)
101
157
  .replace(KEYLIKE_PATTERN, MASK)
102
158
  .replace(ASSIGNMENT_PATTERN, (_match, name) => `${name}=${MASK}`)
103
- // Last, and path-anchored: a workspace path reported by a preflight is shown
104
- // so an operator can recognise the repository, but the per-profile segment of
105
- // the platform temp path is not theirs to see.
106
- .replace(PATH_KEY_PATTERN, (_match, separator) => `${separator}${PATH_KEY_SEGMENT}`);
159
+ // Last, and path-anchored: an ordinary workspace path is shown so an operator can
160
+ // recognise the repository; only a profile key under a temporary root is masked.
161
+ // The leading-root form runs first. Each pass re-emits every separator and the
162
+ // temp-root segment it matched, so a POSIX `.cache` path keeps its `/`.
163
+ .replace(LEADING_TEMP_KEY_PATTERN, (_match, root, separator) => `${root}${separator}${PATH_KEY_SEGMENT}`)
164
+ .replace(
165
+ PATH_KEY_PATTERN,
166
+ (_match, before, root, separator) => `${before}${root}${separator}${PATH_KEY_SEGMENT}`,
167
+ );
107
168
  }
108
169
 
109
170
  /**
@@ -66,6 +66,9 @@ export function createExecutionHandler(deps) {
66
66
  // The switch gate below applies to it exactly as it does to a submission,
67
67
  // because a decision is an authorization exercise like any other.
68
68
  ['POST /tasks/permission', decidePermission],
69
+ // The ordinary-question answer. Registered beside the permission route because it is
70
+ // the other way a paused native tool call resumes.
71
+ ['POST /tasks/question', answerQuestion],
69
72
  // The commander's DELIVERY REVIEW of one finished task. It is the only write that
70
73
  // records `hostAcceptance`, and it is narrow on purpose: it decides no permission,
71
74
  // changes no switch/provider/model/isolation/credential, merges no file and creates
@@ -118,12 +121,13 @@ export function createExecutionHandler(deps) {
118
121
 
119
122
  let connection;
120
123
  if (deps.engine.authorizationMode === 'switch') {
121
- // Only the two AUTHORIZING verbs need the switch: a submission creates work and a
122
- // decision releases a paused call. A delivery REVIEW is not one of them: it records
123
- // a conclusion about an already-finished result, so it stays answerable with the
124
+ // Only the AUTHORIZING verbs need the switch: a submission creates work, and a
125
+ // decision (a permission decision or a question answer) releases a paused call
126
+ // whose work already exists. A delivery REVIEW is not one of them: it records a
127
+ // conclusion about an already-finished result, so it stays answerable with the
124
128
  // switch off, exactly like reading or cancelling a task. Reads, cancel and
125
129
  // preflight are equally unaffected.
126
- const gated = key === 'POST /tasks' || key === 'POST /tasks/permission';
130
+ const gated = key === 'POST /tasks' || key === 'POST /tasks/permission' || key === 'POST /tasks/question';
127
131
  if (gated && deps.engine.posture().authorized !== true) {
128
132
  sendJson(res, 403, {
129
133
  ok: false,
@@ -339,7 +343,74 @@ async function decidePermission({ req, res, connection, deps }) {
339
343
  sendJson(res, 200, { ok: true, ...result });
340
344
  }
341
345
 
342
- /** Body fields `POST /tasks/review` accepts. Everything else is refused. */
346
+ /**
347
+ * Answer one pending QUESTION for one owned task.
348
+ *
349
+ * Shaped like the permission route and for the same reasons: the connection identity is
350
+ * the authenticated one (never the body's), so a caller can only answer its OWN task, and
351
+ * the body is validated here because any local caller can reach this route. The answer
352
+ * batch itself is validated by the bridge against the questions the worker actually
353
+ * asked — this route only checks the shape, so a malformed batch is refused early.
354
+ *
355
+ * Nothing here can grant access: the engine settles a paused native question, and any
356
+ * widening still needs `POST /tasks/permission`.
357
+ * @param {object} context - `req`, `res`, `connection`, `deps`.
358
+ * @returns {Promise<void>} resolves after the answer is sent.
359
+ */
360
+ async function answerQuestion({ req, res, connection, deps }) {
361
+ const body = await readJsonBody(req);
362
+ // A closed top-level field set: an unknown field (including a transport CONTROL field
363
+ // such as `waitAfterAnswer`, which the MCP server strips and the route must not accept)
364
+ // is refused rather than silently dropped, so a caller never believes it changed
365
+ // something here.
366
+ for (const key of Object.keys(body)) {
367
+ if (!['taskId', 'requestId', 'answers'].includes(key)) {
368
+ throw new HttpError(400, 'QUESTION_FIELD_UNKNOWN', `unknown field ${JSON.stringify(key)}`);
369
+ }
370
+ }
371
+ if (typeof body.taskId !== 'string' || body.taskId.trim() === '') {
372
+ throw new HttpError(400, 'TASK_ID_REQUIRED', 'taskId is required');
373
+ }
374
+ if (typeof body.requestId !== 'string' || body.requestId.trim() === '') {
375
+ throw new HttpError(400, 'QUESTION_REQUEST_ID_REQUIRED', 'requestId is required');
376
+ }
377
+ if (!Array.isArray(body.answers)) {
378
+ throw new HttpError(400, 'QUESTION_ANSWERS_REQUIRED', 'answers must be an array');
379
+ }
380
+ for (const answer of body.answers) {
381
+ if (answer === null || typeof answer !== 'object' || Array.isArray(answer)) {
382
+ throw new HttpError(400, 'QUESTION_ANSWER_INVALID', 'each answer must be an object');
383
+ }
384
+ // Each answer is a closed shape too: an unknown field is refused, not ignored.
385
+ const allowed = ['id', 'selected', 'custom'];
386
+ for (const key of Object.keys(answer)) {
387
+ if (!allowed.includes(key)) {
388
+ throw new HttpError(400, 'QUESTION_ANSWER_INVALID', `unknown answer field ${JSON.stringify(key)}`);
389
+ }
390
+ }
391
+ if (typeof answer.id !== 'string' || answer.id === '') {
392
+ throw new HttpError(400, 'QUESTION_ANSWER_INVALID', 'each answer needs a question id');
393
+ }
394
+ if (answer.selected !== undefined && (!Array.isArray(answer.selected)
395
+ || answer.selected.some((label) => typeof label !== 'string'))) {
396
+ throw new HttpError(400, 'QUESTION_ANSWER_INVALID', 'selected must be an array of labels');
397
+ }
398
+ if (answer.custom !== undefined && answer.custom !== null && typeof answer.custom !== 'string') {
399
+ throw new HttpError(400, 'QUESTION_ANSWER_INVALID', 'custom must be a string when present');
400
+ }
401
+ }
402
+ const result = await deps.engine.decideQuestion({
403
+ connectionId: connection.connectionId,
404
+ taskId: body.taskId,
405
+ requestId: body.requestId,
406
+ answers: body.answers.map((answer) => ({
407
+ id: answer.id,
408
+ selected: Array.isArray(answer.selected) ? [...answer.selected] : [],
409
+ ...(typeof answer.custom === 'string' ? { custom: answer.custom } : {}),
410
+ })),
411
+ });
412
+ sendJson(res, 200, { ok: true, ...result });
413
+ }
343
414
  const REVIEW_FIELDS = Object.freeze(['taskId', 'decision', 'note']);
344
415
 
345
416
  /**
package/src/index.d.ts CHANGED
@@ -172,6 +172,8 @@ export interface DelegatePendingPermission {
172
172
  grant: { kind: 'allowed-once'; appliesTo: 'this-call-only'; callId: string; reusable: false } | null;
173
173
  /** Always true: a decision never changes the Session's standing mode. */
174
174
  standingModeUnchanged: true;
175
+ /** Present after a commander rejection; delivery is independent of the rejection outcome. */
176
+ rejectionFeedback?: { delivered: boolean; reason: string | null; text?: string } | null;
175
177
  }
176
178
 
177
179
  /** The per-call permission block every task view carries. */
@@ -196,6 +198,122 @@ export interface DelegateTaskPermission {
196
198
  interrupted?: true;
197
199
  }
198
200
 
201
+ /**
202
+ * One option a question offers.
203
+ */
204
+ export interface DelegateQuestionOption {
205
+ /** The label an answer selects. */
206
+ label: string;
207
+ /** Optional extra context for the option. */
208
+ description: string | null;
209
+ }
210
+
211
+ /**
212
+ * One question a delegated worker asked, as the task view publishes it.
213
+ *
214
+ * Nothing here is model output: these are the questions the worker composed with the
215
+ * native `ask_user_question` tool. No reasoning, transcript or tool argument has a field.
216
+ */
217
+ export interface DelegateQuestion {
218
+ /** Stable caller-provided id, echoed in the answer. */
219
+ id: string;
220
+ /** The question text. */
221
+ question: string;
222
+ /** Optional short heading. */
223
+ header: string | null;
224
+ /** Optional supporting detail, kept out of the option labels. */
225
+ detail: string | null;
226
+ /** Choices the question offered; empty when it expects free text. */
227
+ options: DelegateQuestionOption[];
228
+ /** Whether more than one option may be selected. */
229
+ multiSelect: boolean;
230
+ /**
231
+ * The caller's presentation intent, when it declared one.
232
+ *
233
+ * `'approval'` questions are REFUSED on this channel: a permission decision belongs to
234
+ * `delegate_permission_decide`, which binds one exact tool call. `'plan-review'` is an
235
+ * information answer and grants nothing either.
236
+ */
237
+ intent: 'plan-review' | 'approval' | null;
238
+ }
239
+
240
+ /** One pending ordinary question set. */
241
+ export interface DelegatePendingQuestion {
242
+ requestId: string;
243
+ taskId: string;
244
+ sessionId: string | null;
245
+ /** The native tool call the question is keyed by, when the harness supplied one. */
246
+ callId: string | null;
247
+ state: 'pending' | 'answered' | 'expired' | 'cancelled' | 'refused';
248
+ createdAt: number;
249
+ /** Finite absolute deadline; defaults to ten minutes after the question was published. */
250
+ deadlineAt: number;
251
+ questions: DelegateQuestion[];
252
+ /** An omitted question must never be answered using partial text. */
253
+ questionsOmitted?: boolean;
254
+ questionAnswerable?: boolean;
255
+ questionCount?: number;
256
+ /** Always `false`: answering a question never grants access. */
257
+ grantsAccess: false;
258
+ }
259
+
260
+ /** One answer the commander gave. */
261
+ export interface DelegateQuestionAnswerItem {
262
+ id: string;
263
+ /** Labels this question actually offered. */
264
+ selected: string[];
265
+ /** Optional free text; required when the question offered no options. */
266
+ custom?: string;
267
+ }
268
+
269
+ /** The ordinary-question block every task view carries. */
270
+ export interface DelegateTaskQuestion {
271
+ /** Whether this run was offered a question bridge at all. */
272
+ bridged: boolean;
273
+ /** Whether a question is outstanding right now. */
274
+ waiting: boolean;
275
+ pending: DelegatePendingQuestion | null;
276
+ /** Bounded settled trail, oldest first. */
277
+ evidence: {
278
+ requestId: string;
279
+ taskId: string;
280
+ callId: string | null;
281
+ state: string;
282
+ questions: { id: string; question: string }[];
283
+ answers: DelegateQuestionAnswerItem[] | null;
284
+ reason: string | null;
285
+ createdAt: number;
286
+ settledAt: number | null;
287
+ answeredAt: number | null;
288
+ }[];
289
+ /** Time the run spent waiting for an answer, NOT charged to the execution budget. */
290
+ pausedExecutionMs: number;
291
+ /** Always `false`, stated so no reader mistakes a question answer for a grant. */
292
+ grantsAccess: false;
293
+ }
294
+
295
+ /**
296
+ * The receipt of ONE question answer.
297
+ *
298
+ * `applied: true` is claimed only when the route confirmed the SAME task and request.
299
+ * `applied: null` with `confirmation: "unknown"` means nothing was established — read the
300
+ * task before answering again, and never resend automatically.
301
+ */
302
+ export interface DelegateAnswerReceipt {
303
+ receiptId: string;
304
+ taskId: string | null;
305
+ requestId: string | null;
306
+ answers?: DelegateQuestionAnswerItem[];
307
+ answersOmitted?: true;
308
+ answerCount?: number;
309
+ evidenceOmitted?: true;
310
+ applied: boolean | null;
311
+ confirmation: 'confirmed' | 'unknown' | 'refused';
312
+ /** Always `false`: an answer is not an authorization. */
313
+ grantsAccess: false;
314
+ reason?: string | null;
315
+ }
316
+
199
317
  /**
200
318
  * Bounded activity metadata for one task.
201
319
  *
@@ -292,6 +410,13 @@ export type DelegateObserveReason =
292
410
  | 'heartbeat'
293
411
  | 'attention'
294
412
  | 'permission'
413
+ /**
414
+ * The worker asked an ordinary question and is paused until it is answered.
415
+ *
416
+ * Reported IMMEDIATELY, not after a silence threshold, and it grants nothing: any
417
+ * widening still needs its own `permission` request.
418
+ */
419
+ | 'question'
295
420
  | 'ready'
296
421
  | 'failed'
297
422
  | 'cancelled'
@@ -430,6 +555,154 @@ export interface DelegateHostAcceptance {
430
555
  note: string;
431
556
  }
432
557
 
558
+ /**
559
+ * The receipt of ONE per-call permission decision.
560
+ *
561
+ * `applied` is the only field that answers "did this take effect", and it is deliberately
562
+ * three-valued: `null` with `confirmation: 'unknown'` means the decision could not be
563
+ * confirmed — the call failed before the harness answered, OR the answer lacked the identity
564
+ * and outcome evidence, OR it CONTRADICTED the request that was decided. Such a decision must
565
+ * never be resent without reading the task's real state first.
566
+ *
567
+ * `applied: true` is claimed ONLY from a permission answer that names the SAME task, the SAME
568
+ * request and the SAME operation fingerprint the decision was bound to, reports a settled
569
+ * `state`, and carries the outcome this decision asked for (`allowed-once` for an allow,
570
+ * `rejected` for a reject). An allow additionally needs its `verified` evidence; a reject
571
+ * needs none. The quoted fingerprint is never replaced by a conflicting backend value.
572
+ */
573
+ export interface DelegateDecisionReceipt {
574
+ taskId: string | null;
575
+ requestId: string | null;
576
+ decision: 'allow-once' | 'reject' | null;
577
+ /** The exact operation the decision was bound to; `null` when none could be proven. */
578
+ fingerprint: string | null;
579
+ /** `true` only for a confirmed decision; `false` for a harness refusal; `null` if unknown. */
580
+ applied: boolean | null;
581
+ confirmation: 'applied' | 'unknown' | 'refused';
582
+ /** The closed native outcome, when the harness reported one. */
583
+ outcome?: DelegatePendingPermission['outcome'];
584
+ /** Which checks an `allowed-once` actually passed. Absent for a reject. */
585
+ verified?: DelegatePendingPermission['verified'];
586
+ decidedAt?: number;
587
+ grant?: DelegatePendingPermission['grant'];
588
+ /** Whether the rejection reason reached the executor; the note itself is not repeated. */
589
+ rejectionFeedback?: { delivered: boolean; reason: string | null } | null;
590
+ /** Why the decision is not confirmed. Present only when `confirmation` is not `applied`. */
591
+ reason?: string;
592
+ /**
593
+ * The contradicting evidence, when the answer disagreed with what was decided. Present only
594
+ * for an `unknown` outcome, and bounded.
595
+ */
596
+ evidence?: Record<string, unknown>;
597
+ /** Present only when a bound forced the bulky evidence out of a rescued receipt. */
598
+ evidenceOmitted?: true;
599
+ /** Present only for an unconfirmed decision: the failure that prevented confirmation. */
600
+ error?: { code: string; message: string };
601
+ }
602
+
603
+ /**
604
+ * The answer of `delegate_permission_decide({ waitAfterDecision: true })`.
605
+ *
606
+ * It is the SAME flat shape {@link DelegateObservation} publishes for a wait — a plain
607
+ * `delegate_wait` answer plus `decisionReceipt` — so a host reads one vocabulary for both.
608
+ * There is no nested follow-up block: the top-level `permission` is the live pending
609
+ * operation, and `boundedJson` keeps it (and the receipt) even when the answer must be cut.
610
+ *
611
+ * When the decision WAS applied but the following wait failed, was interrupted or was
612
+ * cancelled, this is still a SUCCESS carrying `decisionReceipt` (`applied: true`) plus
613
+ * `reason: null`, `actionable: false` and a `waitError` block: the decision stands, only the
614
+ * waiting ended, and the execution was not stopped. The receipt is never swallowed.
615
+ */
616
+ export interface DelegateDecisionWithWait extends DelegateObservation {
617
+ decisionReceipt: DelegateDecisionReceipt;
618
+ /** Present only when the applied decision's follow-up wait ended in a refusal. */
619
+ waitError?: { code: string; message: string; phase: 'follow-up-wait' };
620
+ }
621
+
622
+ /**
623
+ * The refusal of a decision whose outcome nobody established or confirmed.
624
+ *
625
+ * `applied` is `null`, `confirmation` is `'unknown'`, and the caller must read the task with
626
+ * `delegate_result` before deciding whether to send the decision again. Nothing is retried
627
+ * automatically and no wait is started.
628
+ */
629
+ export interface DelegateUnconfirmedDecisionFacts {
630
+ decisionReceipt: DelegateDecisionReceipt;
631
+ }
632
+
633
+ /**
634
+ * One bounded accounting census of an MCP process.
635
+ *
636
+ * These are counts of the PROGRAM — the tool calls a host made and the waits it ran — never
637
+ * of the host model. The host's own turns, token usage and cost are not observable from this
638
+ * process and are reported as `'not-integrated'`, never as zero.
639
+ */
640
+ export interface DelegateMcpMetrics {
641
+ schemaVersion: 1;
642
+ definitions: Record<string, string>;
643
+ hostObservability: {
644
+ hostModelResponses: 'not-integrated';
645
+ hostTokenUsage: 'not-integrated';
646
+ hostCost: 'not-integrated';
647
+ reason: string;
648
+ };
649
+ tools: Record<string, number>;
650
+ returnedText: {
651
+ count: number;
652
+ /** UTF-8 bytes of the final bounded, redacted tool text. Not a delivery receipt. */
653
+ bytes: number;
654
+ /** Returns whose size could not be measured (no text, or unencodable). */
655
+ unmeasured: number;
656
+ unit: 'utf8-bytes-of-serialized-tool-text';
657
+ };
658
+ waits: {
659
+ count: number;
660
+ totalMs: number;
661
+ observations: number;
662
+ reasons: Record<string, number>;
663
+ };
664
+ decisions: {
665
+ count: number;
666
+ applied: number;
667
+ unknown: number;
668
+ refused: number;
669
+ allowed: number;
670
+ rejected: number;
671
+ };
672
+ questionAnswers: { count: number; applied: number; unknown: number; refused: number };
673
+ correlation: {
674
+ waitsAfterDecisions: number;
675
+ waitQuestionsAnswered: number;
676
+ recentWaits: Array<{
677
+ waitId: string | null;
678
+ afterDecisionId: string | null;
679
+ taskId: string | null;
680
+ reason: string;
681
+ durationMs: number;
682
+ observationRequests: number;
683
+ heartbeatsConsumed: number;
684
+ settledRequestObservations: number;
685
+ waitReturns: number;
686
+ at: number;
687
+ }>;
688
+ recentDecisions: Array<{
689
+ receiptId: string | null;
690
+ taskId: string | null;
691
+ requestId: string | null;
692
+ decision: 'allow-once' | 'reject' | 'question-answer' | null;
693
+ fingerprint: string | null;
694
+ /**
695
+ * The same three-valued fact the permission receipt publishes: `true` for `applied`,
696
+ * `false` for `refused`, `null` for `unknown`. An unconfirmed attempt is `null`, never
697
+ * `false`, so a reader cannot mistake it for an established refusal.
698
+ */
699
+ applied: boolean | null;
700
+ state: 'applied' | 'unknown' | 'refused';
701
+ at: number;
702
+ }>;
703
+ };
704
+ }
705
+
433
706
  /** Result of one bounded observation of a delegated task. */
434
707
  export interface DelegateObservation {
435
708
  task: DelegateObservationSummary;
@@ -440,6 +713,18 @@ export interface DelegateObservation {
440
713
  * never shortened into an undecidable summary.
441
714
  */
442
715
  permission: DelegatePendingPermission | null;
716
+ /**
717
+ * The FULL pending question set, present only for `reason: 'question'`.
718
+ *
719
+ * Carries the questions, their options, and the identity an answer is bound to, so one
720
+ * reply is enough to answer — exactly like the permission block. It never carries
721
+ * model text.
722
+ */
723
+ question: DelegatePendingQuestion | null;
724
+ /** Present only on a `question` answer: derived from the operation as published. */
725
+ questionAnswerable?: boolean;
726
+ /** Present only on a `question` answer: always `false`, restated where it matters. */
727
+ grantsAccess?: false;
443
728
  /**
444
729
  * Present only when `reason` is `attention` AND the reminder is about repeated
445
730
  * failures rather than silence. `null`/absent for an ordinary silence report, which
package/src/index.js CHANGED
@@ -59,7 +59,10 @@ import { resolveCodexActionSeam } from './codex/seam.js';
59
59
  import { ReviewPreset } from './review/preset.js';
60
60
  import { configureDelegatedSession, policyServicesOf } from './runtime/sandbox.js';
61
61
  import { PermissionBridge, PERMISSION_DEFAULT_TIMEOUT_MS } from './runtime/permissions.js';
62
+ import { QuestionBridge } from './runtime/questions.js';
62
63
  import { redactText, isSecretKey } from './config/redact.js';
64
+ import { approvalFeedbackMessage } from './runtime/agent-runner.js';
65
+ import { reportedVersion } from './version.js';
63
66
 
64
67
  /** Stable Cordis plugin name; also the settings/document namespace. */
65
68
  export const name = 'dsh-taskbridge';
@@ -256,6 +259,15 @@ export async function apply(ctx, config = {}) {
256
259
  getApprovalService: () => readOptionalApprovalService(ctx),
257
260
  logger,
258
261
  }),
262
+ // The ordinary-question bridge factory. It does NOT depend on the approval service:
263
+ // asking a question is not granting anything, so a run keeps its fail-closed `never`
264
+ // approval stance and may still ask. A question is only surfaced when the harness
265
+ // actually composes the native `userQuestions` seam; otherwise the factory returns
266
+ // null and nothing is registered, which is the safe default.
267
+ questionBridge: createQuestionBridgeFactory({
268
+ hasQuestionService: () => hasQuestionService(ctx),
269
+ logger,
270
+ }),
259
271
  };
260
272
 
261
273
  try {
@@ -510,8 +522,14 @@ export async function apply(ctx, config = {}) {
510
522
  });
511
523
  }
512
524
 
513
- /** Version reported by the runtime facts block. Mirrors `package.json`. */
514
- const PLUGIN_VERSION = '1.4.1';
525
+ /**
526
+ * Version reported by the runtime facts block.
527
+ *
528
+ * Read from the package manifest this build ships in, never written as a literal: two
529
+ * copies of one fact drift, and a host asking a pre-release build which version it is
530
+ * must not be told the last released number.
531
+ */
532
+ const PLUGIN_VERSION = reportedVersion().version;
515
533
 
516
534
  /**
517
535
  * Read the native approval service without turning absence into a throw.
@@ -570,6 +588,10 @@ function createPermissionBridgeFactory(options) {
570
588
  // because that secret carries no credential-shaped TEXT at all.
571
589
  redact: (text) => redactText(text),
572
590
  isSecretKey,
591
+ // The REAL native message factory. Without it the bridge would fall back to a
592
+ // locally built object, and the note reaching the worker would be a look-alike
593
+ // rather than a message the native inbox normalised.
594
+ createUserMessage: approvalFeedbackMessage,
573
595
  onPending: request?.onPending,
574
596
  onSettled: request?.onSettled,
575
597
  logger: options?.logger ?? null,
@@ -581,6 +603,54 @@ function createPermissionBridgeFactory(options) {
581
603
  };
582
604
  }
583
605
 
606
+ /**
607
+ * Whether this harness composes the native user-questions seam.
608
+ *
609
+ * Read live, per run, through the non-strict accessor: DSH may compose
610
+ * `ctx.userQuestions` after this plugin activated, and a missing seam is a fact (the
611
+ * worker's tool surface then simply has no `ask_user_question`), not a failure.
612
+ * @param {object} ctx - plugin context.
613
+ * @returns {boolean} true when the native service is present.
614
+ */
615
+ function hasQuestionService(ctx) {
616
+ if (ctx === null || ctx === undefined || typeof ctx.get !== 'function') return false;
617
+ try {
618
+ return ctx.get('userQuestions', false) !== undefined && ctx.get('userQuestions', false) !== null;
619
+ } catch {
620
+ // A service whose read is refused is treated as absent, never as present.
621
+ return false;
622
+ }
623
+ }
624
+
625
+ /**
626
+ * Build the ordinary-question bridge factory.
627
+ *
628
+ * A bridge is produced only when the harness composes the native question seam AND the
629
+ * Agent-scoped answerer can be registered, which is decided per run by the runner. The
630
+ * factory itself holds no task state: the observers belong to the engine, which is what
631
+ * records the phase and accounts the paused budget.
632
+ * @param {object} options - `hasQuestionService` (live predicate), `logger`.
633
+ * @returns {(request: object) => object | null} factory.
634
+ */
635
+ function createQuestionBridgeFactory(options) {
636
+ return function questionBridge(request) {
637
+ const present = typeof options?.hasQuestionService === 'function' ? options.hasQuestionService() : false;
638
+ if (present !== true) return null;
639
+ try {
640
+ return new QuestionBridge({
641
+ taskId: request?.taskId,
642
+ connectionId: request?.connectionId,
643
+ onPending: request?.onPending,
644
+ onSettled: request?.onSettled,
645
+ logger: options?.logger ?? null,
646
+ });
647
+ } catch (error) {
648
+ options?.logger?.warn?.('dsh-delegate: the question bridge could not be constructed', String(error?.code ?? ''));
649
+ return null;
650
+ }
651
+ };
652
+ }
653
+
584
654
  /**
585
655
  * Resolve the plugin's own data directory.
586
656
  *
@@ -741,6 +741,9 @@ export const OBSERVE_REASONS = Object.freeze({
741
741
  heartbeat: 'heartbeat',
742
742
  attention: 'attention',
743
743
  permission: 'permission',
744
+ // The worker asked a human an ordinary question. It is its own reason because answering
745
+ // it grants nothing, and it must be reported at once rather than as silence.
746
+ question: 'question',
744
747
  ready: 'ready',
745
748
  failed: 'failed',
746
749
  cancelled: 'cancelled',
@@ -1211,6 +1214,13 @@ export class TaskMonitor {
1211
1214
  if (this.task?.permission?.pending !== null && this.task?.permission?.pending !== undefined) {
1212
1215
  return this.outcome(OBSERVE_REASONS.permission, activitySinceWait, at - startedAt, selfCheck);
1213
1216
  }
1217
+ if (this.task?.question?.pending !== null && this.task?.question?.pending !== undefined) {
1218
+ // A question is checked with the same precedence as a permission (and AFTER it, so
1219
+ // the one wait that can grant is reported first): the worker is paused on a human
1220
+ // and the host must act now. The self-check above still runs, but it can never
1221
+ // turn this into `attention`.
1222
+ return this.outcome(OBSERVE_REASONS.question, activitySinceWait, at - startedAt, selfCheck);
1223
+ }
1214
1224
  // (3b) Repeated failures. Same reason as the silence report — it needs the
1215
1225
  // commander — but it carries its own typed diagnostic and is NOT gated on
1216
1226
  // silence: a busy run that keeps failing the same operation must still reach