dsh-taskbridge 1.4.2 → 1.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/CHANGELOG.md +34 -2
  2. package/README.md +10 -8
  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 +180 -16
  6. package/docs/INTRODUCTION.md +2 -2
  7. package/docs/INTRODUCTION.zh.md +2 -2
  8. package/docs/codex-integration.md +11 -13
  9. package/docs/conversation-placement.md +44 -7
  10. package/docs/plugin-market.md +1 -1
  11. package/docs/redaction-contract.md +47 -4
  12. package/docs/releases/1.5.0-token-benchmark.zh.md +73 -0
  13. package/docs/releases/1.5.0.zh.md +51 -0
  14. package/docs/releases/1.5.1.zh.md +70 -0
  15. package/docs/runtime-compatibility.md +4 -4
  16. package/docs/silent-wait.md +157 -3
  17. package/docs/taskbridge-upgrade.md +1 -1
  18. package/docs/worker-permissions.md +154 -17
  19. package/lib/client.js +298 -103
  20. package/package.json +9 -3
  21. package/src/client/api.js +315 -34
  22. package/src/client/index.jsx +151 -67
  23. package/src/codex/installer.js +251 -11
  24. package/src/config/redact.js +72 -11
  25. package/src/http/execution-plane.js +124 -10
  26. package/src/index.d.ts +347 -0
  27. package/src/index.js +88 -5
  28. package/src/jobs/activity.js +102 -9
  29. package/src/jobs/continuation-identity.js +283 -0
  30. package/src/jobs/engine.js +491 -55
  31. package/src/jobs/history.js +96 -0
  32. package/src/mcp/continuation.js +317 -0
  33. package/src/mcp/metrics.js +366 -0
  34. package/src/mcp/server.js +1203 -53
  35. package/src/mcp/wait.js +338 -73
  36. package/src/review/prompts.js +145 -126
  37. package/src/runtime/agent-runner.js +330 -0
  38. package/src/runtime/permissions.js +192 -2
  39. package/src/runtime/question-call.js +162 -0
  40. package/src/runtime/questions.js +909 -0
  41. package/src/runtime/sandbox.js +363 -358
  42. package/src/runtime/session-placement.js +1207 -1121
  43. package/src/version.js +121 -0
  44. package/src/workspace/worktrees.js +70 -4
package/src/mcp/server.js CHANGED
@@ -42,6 +42,17 @@
42
42
  // a model, the isolation or a credential, merge a diff, or create work; it also cannot
43
43
  // be reached by the worker's own catalog, for the same reason as above.
44
44
  //
45
+ // `delegate_metrics` is the one tool with NO plane route at all: it reports this MCP
46
+ // process's own bounded accounting (tool calls, wait answers and their reasons, durations,
47
+ // UTF-8 byte sizes, applied decisions and the waits that followed them). It is a read of
48
+ // a census this process kept — not of the host's model, whose turns, tokens and cost are
49
+ // reported as `not-integrated` rather than as zero.
50
+ //
51
+ // `delegate_permission_decide`'s optional `waitAfterDecision` is the one argument this
52
+ // surface adds for itself. It is a CONTROL field of the MCP call, stripped at this
53
+ // boundary and never sent to the plane; its continuation reuses the bounded observation
54
+ // loop in `./wait.js` through `./continuation.js` rather than growing a second one.
55
+ //
45
56
  // `delegate_preflight` is the one addition that is not an authorization at all: it
46
57
  // is a read-only measurement of a workspace, and it exists so a dispatcher can
47
58
  // learn before submitting that a checkout is dirty, is not a repository, or would
@@ -79,6 +90,20 @@ import {
79
90
  truncateCodePoints,
80
91
  } from '../jobs/review-note.js';
81
92
  import { waitForTask } from './wait.js';
93
+ import { QUESTION_ANSWER_KIND, createCallMetrics, correlationId } from './metrics.js';
94
+ // The engine's own per-call permission bounds. Imported rather than re-stated so this
95
+ // layer can never publish a SMALLER operation cap than the engine allowed: a smaller
96
+ // one here re-cuts an operation the engine already published whole and turns a
97
+ // reviewable request into an unapprovable one.
98
+ import { PERMISSION_BOUNDS } from '../runtime/permissions.js';
99
+ import { reportedVersion } from '../version.js';
100
+ // The question answer's own bounds, re-exported so the MCP schema and the runtime agree on
101
+ // the custom-text limit rather than restating it.
102
+ import { QUESTION_BOUNDS } from '../runtime/questions.js';
103
+ import {
104
+ decidedRequestMatcher,
105
+ decisionReceipt,
106
+ } from './continuation.js';
82
107
 
83
108
  /** Protocol revisions this server can speak, newest first (as the SDK lists them). */
84
109
  export const SUPPORTED_PROTOCOL_VERSIONS = Object.freeze([
@@ -91,8 +116,18 @@ export const SUPPORTED_PROTOCOL_VERSIONS = Object.freeze([
91
116
  /** The revision answered when a client asks for one this server does not know. */
92
117
  export const LATEST_PROTOCOL_VERSION = SUPPORTED_PROTOCOL_VERSIONS[0];
93
118
 
94
- /** Identifies this server in the handshake. */
95
- export const SERVER_INFO = Object.freeze({ name: 'dsh-delegate', version: '1.4.2' });
119
+ /**
120
+ * Identifies this server in the handshake.
121
+ *
122
+ * The version is read from the package manifest this file ships in, never written
123
+ * here: a literal is a second copy of the same fact and the two drift, so a
124
+ * pre-release tarball answered `initialize` with the last released number and a host
125
+ * could not tell which build it was talking to. `delegate_metrics` and the exit
126
+ * diagnostics report the same value through {@link reportedVersion}.
127
+ */
128
+ const REPORTED = reportedVersion();
129
+
130
+ export const SERVER_INFO = Object.freeze({ name: REPORTED.name, version: REPORTED.version });
96
131
 
97
132
  /** Bound on a tool result's text. A task view can be large; a model's context cannot. */
98
133
  export const MAX_TOOL_TEXT_CHARS = 20_000;
@@ -158,10 +193,17 @@ export const MAX_CALL_LOG = 256;
158
193
  /**
159
194
  * Reasons on which `delegate_wait` returns to the host.
160
195
  *
196
+ * `question` is here for the same reason `permission` is: the worker is PAUSED on an
197
+ * ordinary question it cannot answer itself, so the host must act now. Surfacing it only
198
+ * through the silence threshold is the acceptance defect this reason removes — a question
199
+ * asked at minute one used to be reported at minute ten.
200
+ *
161
201
  * `heartbeat` is deliberately absent: it is the engine's internal "nothing changed
162
202
  * yet" signal, consumed by the wait loop and never surfaced as an answer.
163
203
  */
164
- export const ACTIONABLE_REASONS = Object.freeze(['attention', 'permission', 'ready', 'failed', 'cancelled', 'interrupted']);
204
+ export const ACTIONABLE_REASONS = Object.freeze([
205
+ 'attention', 'permission', 'question', 'ready', 'failed', 'cancelled', 'interrupted',
206
+ ]);
165
207
 
166
208
  /** The reason a wait that reached its own deadline reports. */
167
209
  export const WAIT_LIMIT_REASON = 'wait-limit';
@@ -183,13 +225,16 @@ export class McpError extends Error {
183
225
  /**
184
226
  * @param {string} code - stable machine code, surfaced to the client as text.
185
227
  * @param {string} message - explanation, already free of secrets.
186
- * @param {object} [options] - `rpcCode` for a protocol-level refusal.
228
+ * @param {object} [options] - `rpcCode` for a protocol-level refusal, `details` for the
229
+ * bounded, already-redacted facts the refusal must carry (for example a decision
230
+ * receipt whose outcome is unknown). Details are published as `error.details`.
187
231
  */
188
232
  constructor(code, message, options = {}) {
189
233
  super(message);
190
234
  this.name = 'McpError';
191
235
  this.code = code;
192
236
  this.rpcCode = options.rpcCode ?? null;
237
+ this.details = options.details ?? null;
193
238
  }
194
239
  }
195
240
 
@@ -276,6 +321,17 @@ export const TOOLS = Object.freeze([
276
321
  description: 'Optional per-task overrides (model/effort/timeout). Validated by the harness.',
277
322
  additionalProperties: true,
278
323
  },
324
+ agentTeams: {
325
+ type: 'boolean',
326
+ description: 'OPTIONAL. Your Agent Teams decision for THIS task\u2019s own DSH Session: the same switch the '
327
+ + 'DSH model menu exposes as \u300cUse Agent Teams\u300d/\u300c\u542f\u7528\u667a\u80fd\u4f53\u56e2\u961f\u534f\u4f5c\u300d. '
328
+ + 'The plugin applies it to this run only and never opens a global default. Use `true` only when independent '
329
+ + 'modules can proceed in parallel and the gain covers the coordination cost; single-file work and '
330
+ + 'strongly ordered changes should stay `false`. Omit it to make no choice: the run then keeps whatever '
331
+ + 'selection the Session already has. Teams never replaces your approval or your final review, and this '
332
+ + 'flag never selects a model or an effort \u2014 those come from the task\u2019s frozen configuration. The task '
333
+ + 'record reports `agentTeams` (your request) and `team` (what DSH confirmed, or why it could not).',
334
+ },
279
335
  continueFromTaskId: {
280
336
  type: 'string',
281
337
  description: 'Task id of the earlier delegated task this submission continues. '
@@ -342,8 +398,10 @@ export const TOOLS = Object.freeze([
342
398
  + 'the configured inactivity threshold, ten minutes by default, so it may be stuck), `ready` (the run '
343
399
  + 'ended and is awaiting host review), `failed`, `cancelled` or `interrupted`. '
344
400
  + 'An `attention` answer may instead carry a `failure` block (kind `repeated-tool-failure`, with '
345
- + 'toolName/failureCode/consecutive): the worker repeated the SAME operation and failed the same way '
346
- + 'several times in a row. It is a question for the host, reported once; nothing is cancelled, retimed '
401
+ + 'a stable `eventId`, toolName/failureCode/consecutive): the worker repeated the SAME operation and failed the same way '
402
+ + 'several times in a row. It is a question for the host, and it is REDELIVERED until you acknowledge it with '
403
+ + '`ackFailureEventId` (the eventId you saw), so a lost answer is never a lost reminder; acknowledging stops the '
404
+ + 'redelivery and does not decide anything about the task. Nothing is cancelled, retimed '
347
405
  + 'or reconfigured automatically. '
348
406
  + '`reason: "wait-limit"` means only that this call\u2019s own budget ran out with nothing changed: it is '
349
407
  + 'reported with `actionable: false` and `terminal: false`. Call delegate_wait again with the same '
@@ -386,9 +444,15 @@ export const TOOLS = Object.freeze([
386
444
  // concurrency-aware client this call may be held for an hour without being a
387
445
  // mutating operation. A serialising host still ignores it; the independent
388
446
  // `dsh-delegate-control` channel is the answer there.
447
+ // A LONG read of the task that can also ACKNOWLEDGE a reminder: the
448
+ // `ackFailureEventId` argument clears the monitor's reminder state, which is a
449
+ // state change even though it never touches the task, a decision or a run — so
450
+ // `readOnlyHint` is FALSE and must stay false. `destructiveHint` stays false:
451
+ // acknowledging stops nothing, decides nothing and rewinds nothing. The
452
+ // annotations are a description of the tool, not an execution-permission guard.
389
453
  annotations: Object.freeze({
390
454
  title: 'Wait for a task to need you',
391
- readOnlyHint: true,
455
+ readOnlyHint: false,
392
456
  destructiveHint: false,
393
457
  idempotentHint: true,
394
458
  openWorldHint: false,
@@ -406,6 +470,17 @@ export const TOOLS = Object.freeze([
406
470
  + 'extend a wait beyond 3600. A returned `wait-limit` with `actionable: false` means this '
407
471
  + 'deadline was reached, not that the task stalled or ended.',
408
472
  },
473
+ ackFailureEventId: {
474
+ type: 'string',
475
+ minLength: 1,
476
+ maxLength: 64,
477
+ description: 'OPTIONAL. The `failure.eventId` from an earlier delegate_wait answer. A repeated-failure '
478
+ + 'reminder is redelivered until you acknowledge it: pass its eventId here to say you received it. '
479
+ + 'Acknowledging does not decide anything about the task and does not stop the run, but it DOES '
480
+ + 'clear the reminder state, which is why this tool is not announced read-only. A wrong eventId is '
481
+ + 'refused in the answer (`failureAck.acknowledged: false`) and changes nothing. An empty string is '
482
+ + 'refused, not ignored.',
483
+ },
409
484
  },
410
485
  required: ['taskId'],
411
486
  additionalProperties: false,
@@ -447,7 +522,17 @@ export const TOOLS = Object.freeze([
447
522
  + 'the switch, the provider/model or the isolation, and cannot approve a future call. '
448
523
  + '`allow-once` REQUIRES the pending request\u2019s `fingerprint` and is refused when `permission.pending.'
449
524
  + 'completeness` is not `complete` (the operation was shortened by a bound, so an allow cannot be granted '
450
- + 'on it). `reject` needs neither and is therefore always available.',
525
+ + 'on it). `reject` needs neither and is therefore always available. '
526
+ + 'OPTIONAL `waitAfterDecision` (default false) decides and then keeps following the SAME task inside this '
527
+ + 'same call, answering in the compact `delegate_wait` shape plus a `decisionReceipt`. Use it when your '
528
+ + 'channel supports it: deciding and then waiting is what resumes the task without a second call. The '
529
+ + 'receipt states what happened to the decision: `applied: true` ONLY when the harness confirmed the same '
530
+ + 'task, request and operation, and `applied: null` with `confirmation: "unknown"` when nothing was '
531
+ + 'established (the call failed before an answer, or the answer contradicted or lacked the evidence to '
532
+ + 'confirm it — then read the task with delegate_result before sending it again). An unconfirmed decision is '
533
+ + 'refused and never continued. A refused decision never waits, a new request is never inherited, and when '
534
+ + 'an APPLIED decision\'s follow-up wait fails or is cancelled this call still succeeds with the receipt, '
535
+ + '`reason: null` and a `waitError` block: the decision is never unsaid.',
451
536
  // It does not read and it does not write a configuration: it settles ONE paused
452
537
  // call. A repeated decision for the same request is refused, so it is not
453
538
  // idempotent — the second call is a different outcome by design.
@@ -478,11 +563,115 @@ export const TOOLS = Object.freeze([
478
563
  + 'the exact operation it grants, and an allow that omits it is refused. Optional for `reject` (a '
479
564
  + 'refusal is safe without it); when supplied, a request whose operation no longer matches is refused.',
480
565
  },
566
+ waitAfterDecision: {
567
+ type: 'boolean',
568
+ description: 'OPTIONAL, default false: the historical behaviour — decide only, and the answer is the '
569
+ + 'permission route\'s own reply, unchanged. Set it to true to keep following the SAME task inside this '
570
+ + 'same call after the decision is applied and confirmed. The answer is then the SAME compact shape '
571
+ + '`delegate_wait` returns — `reason`/`state`/`actionable`/`terminal`/`task`, and for a new request the '
572
+ + 'whole redacted `permission` operation with its `completeness` and `fingerprint` — plus '
573
+ + '`decisionReceipt` (taskId, requestId, decision, fingerprint, `applied`, `confirmation`, `outcome`). '
574
+ + '`applied: true` is claimed only when the harness confirmed the SAME task, request and operation; a '
575
+ + 'CONTRADICTED or evidence-free answer is `applied: null` with `confirmation: "unknown"`, which is '
576
+ + 'refused (MCP_DECISION_UNCONFIRMED) and never continued. The request you just decided is never asked '
577
+ + 'again and never re-approved: the wait continues past it. A NEW request id, or the same id with a '
578
+ + 'changed operation, is a new question and is NOT inherited. A decision that is refused never starts a '
579
+ + 'wait. When the decision IS applied but the following wait fails, is cancelled or is interrupted, '
580
+ + 'this call still SUCCEEDS with `decisionReceipt.applied: true`, `reason: null`, `actionable: false` '
581
+ + 'and a `waitError` block: the decision stands, only the waiting ended, the execution was not stopped, '
582
+ + 'and the decision must not be resent. For the same waiting rules as `delegate_wait`: omit '
583
+ + 'waitSeconds, expect `wait-limit` to mean "wait again on the same taskId", and never read intermediate '
584
+ + 'code while it waits.',
585
+ },
481
586
  },
482
587
  required: ['taskId', 'requestId', 'decision'],
483
588
  additionalProperties: false,
484
589
  }),
485
590
  }),
591
+ Object.freeze({
592
+ name: 'delegate_question_answer',
593
+ title: 'Answer a question a delegated worker asked',
594
+ description: 'Answer ONE ordinary question that a delegated task is waiting on. '
595
+ + 'A delegated worker may ask a human a question with the native `ask_user_question` tool — typically '
596
+ + 'because something is ambiguous, or because it needs a choice it must not make itself. That tool call '
597
+ + 'PAUSES, the task stays `running` with phase `awaiting-question`, and the question appears in '
598
+ + '`delegate_wait` as `reason: "question"` with the full `question` block: `requestId`, `taskId`, '
599
+ + '`sessionId`, `callId` and `questions[]` (`id`, `question`, `header`, `detail`, `options[]` with '
600
+ + '`label`/`description`, `multiSelect`). Nothing about the worker\u2019s reasoning or transcript is included. '
601
+ + 'Answer with `answers`: one entry per question, each naming that question\u2019s `id` exactly once, with '
602
+ + '`selected` (labels that question actually offered) and/or non-empty `custom` text. A single-select '
603
+ + 'question takes at most one offered label; every asked question must be answered; an unknown id or a label the '
604
+ + 'question did not offer is refused and the question STAYS PENDING so a correct answer can still be made. '
605
+ + 'This tool does NOT grant access. Answering a question is not an approval and creates no authorization, '
606
+ + 'sandbox widening, standing grant or policy change; a worker that needs wider access must still request '
607
+ + 'it through `delegate_permission_decide`, and a question that presents an approval (`intent` of '
608
+ + '`approval`) is REFUSED here with `QUESTION_APPROVAL_INTENT` — that channel is the only one that can '
609
+ + 'grant, and the refused question fails promptly instead of hanging. A `plan-review` question is an '
610
+ + 'information answer and grants nothing either. '
611
+ + 'An answer applies ONCE: repeating it is refused as `QUESTION_ALREADY_ANSWERED`, an expired or '
612
+ + 'cancelled question cannot be answered, and a question is never answerable across tasks or after a '
613
+ + 'restart. '
614
+ + 'OPTIONAL `waitAfterAnswer` (default false) answers and then keeps following the SAME task inside this '
615
+ + 'same call, answering in the compact `delegate_wait` shape plus an `answerReceipt`. When the answer IS '
616
+ + 'applied but the following wait fails, is cancelled or is interrupted, this call still SUCCEEDS with '
617
+ + '`answerReceipt.applied: true`, `reason: null` and a `waitError` block: the answer stands and must not be '
618
+ + 'sent again.',
619
+ // It settles ONE paused question. It cannot read a configuration, create work or grant
620
+ // anything, and a second answer to the same question is refused — so it is not
621
+ // idempotent by design.
622
+ annotations: Object.freeze({
623
+ title: 'Answer a question a delegated worker asked',
624
+ readOnlyHint: false,
625
+ destructiveHint: false,
626
+ idempotentHint: false,
627
+ openWorldHint: false,
628
+ }),
629
+ inputSchema: Object.freeze({
630
+ type: 'object',
631
+ properties: {
632
+ taskId: { type: 'string', description: 'Task identity returned by delegate_submit.' },
633
+ requestId: {
634
+ type: 'string',
635
+ description: 'The pending question\u2019s `requestId`, copied from the `question` block of delegate_wait.',
636
+ },
637
+ answers: {
638
+ type: 'array',
639
+ description: 'One entry per asked question, each naming that question\u2019s id exactly once.',
640
+ items: {
641
+ type: 'object',
642
+ properties: {
643
+ id: { type: 'string', description: 'The question id, copied from `questions[].id`.' },
644
+ selected: {
645
+ type: 'array',
646
+ items: { type: 'string' },
647
+ description: 'Labels this question actually offered. A single-select question takes at most one.',
648
+ },
649
+ custom: {
650
+ type: 'string',
651
+ maxLength: QUESTION_BOUNDS.customChars,
652
+ description: 'Optional free-text answer. Required when the question offers no options.',
653
+ },
654
+ },
655
+ required: ['id'],
656
+ additionalProperties: false,
657
+ },
658
+ },
659
+ waitAfterAnswer: {
660
+ type: 'boolean',
661
+ description: 'OPTIONAL, default false: answer only, and the answer is the question route\u2019s own reply. '
662
+ + 'Set it to true to keep following the SAME task inside this same call after the answer is applied. '
663
+ + 'The answer is then the SAME compact shape `delegate_wait` returns plus `answerReceipt` '
664
+ + '(taskId, requestId, `applied`, `confirmation`, answers). When the answer IS applied but the '
665
+ + 'following wait fails, is cancelled or is interrupted, this call still SUCCEEDS with '
666
+ + '`answerReceipt.applied: true`, `reason: null`, `actionable: false` and a `waitError` block: the '
667
+ + 'answer stands, only the waiting ended, and it must not be resent. A refused answer never starts a '
668
+ + 'wait.',
669
+ },
670
+ },
671
+ required: ['taskId', 'requestId', 'answers'],
672
+ additionalProperties: false,
673
+ }),
674
+ }),
486
675
  Object.freeze({
487
676
  name: 'delegate_review',
488
677
  title: 'Record the host review of a delivered task',
@@ -568,6 +757,54 @@ export const TOOLS = Object.freeze([
568
757
  additionalProperties: false,
569
758
  }),
570
759
  }),
760
+ Object.freeze({
761
+ name: 'delegate_metrics',
762
+ title: 'Read this MCP session\'s accounting',
763
+ description: 'Report bounded accounting for THIS MCP process only: how many times each tool was called, how '
764
+ + 'many wait answers were handed back and why, how much data they carried (UTF-8 bytes), how many PER-CALL '
765
+ + 'permission decisions were applied, and the wait that followed each decision with its own reason, '
766
+ + 'duration and size. '
767
+ + 'These are counts of the PROGRAM (this process and its internal observations), not of model activity: '
768
+ + 'the host model\u2019s own turns, token usage and cost are not observable from here and are returned as '
769
+ + '"not-integrated", never as 0. A read-only census of THIS connection with no task identity required; '
770
+ + 'it carries no tool arguments, no reasoning, no answer body, no credential and no task content, and it '
771
+ + 'cannot change anything. The counters live in memory and reset when this MCP process restarts.',
772
+ annotations: Object.freeze({
773
+ title: 'Read this MCP session\'s accounting',
774
+ readOnlyHint: true,
775
+ destructiveHint: false,
776
+ idempotentHint: true,
777
+ openWorldHint: false,
778
+ }),
779
+ inputSchema: Object.freeze({
780
+ type: 'object',
781
+ properties: {},
782
+ additionalProperties: false,
783
+ }),
784
+ }),
785
+ ]);
786
+
787
+ /**
788
+ * Refusal codes that mean "the harness never answered", so a decision's outcome is UNKNOWN.
789
+ *
790
+ * Every other code the permission route can produce (`PERMISSION_REQUEST_CHANGED`,
791
+ * `PERMISSION_EVIDENCE_INCOMPLETE`, `DELEGATION_DISABLED`, `JOB_TASK_NOT_FOUND`, …) is the
792
+ * harness's own verdict: the decision was definitely NOT applied. The distinction matters
793
+ * because a clean "failed" invites a resend, while an unconfirmed decision might already be
794
+ * in force — a resend there is a second authorization attempt, and the caller must read the
795
+ * task first.
796
+ * @type {ReadonlySet<string>}
797
+ */
798
+ const UNCONFIRMED_DECISION_CODES = new Set([
799
+ 'MCP_HARNESS_UNREACHABLE',
800
+ 'MCP_HARNESS_MALFORMED',
801
+ 'MCP_REQUEST_CANCELLED',
802
+ 'MCP_CALL_FAILED',
803
+ 'MCP_CONFIG_INVALID',
804
+ // The request outlived its own timeout. The plane may have applied the decision or
805
+ // answer before the connection was abandoned, so this is UNKNOWN in the same way as a
806
+ // dropped connection — not a clean refusal that invites a resend.
807
+ 'MCP_REQUEST_TIMEOUT',
571
808
  ]);
572
809
 
573
810
  /** Tool name → the execution-plane call it makes. */
@@ -578,16 +815,105 @@ const TOOL_ROUTES = Object.freeze({
578
815
  delegate_wait: 'observe',
579
816
  delegate_cancel: 'cancel',
580
817
  delegate_permission_decide: 'permission',
818
+ delegate_question_answer: 'question',
581
819
  delegate_review: 'review',
582
820
  delegate_preflight: 'preflight',
821
+ // No plane route: the census is this process's own and travels to no backend.
822
+ delegate_metrics: null,
583
823
  });
584
824
 
825
+ /**
826
+ * The one argument this surface adds to a request it forwards.
827
+ *
828
+ * `waitAfterDecision` is a CONTROL field of the MCP call: it tells this server to keep
829
+ * following the task after the decision. It is NOT part of the permission request, and
830
+ * the decision route validates a closed field set, so forwarding it would turn every such
831
+ * call into a refusal. It is stripped once — at the MCP boundary, in
832
+ * {@link validateArgs} — and never reintroduced anywhere else.
833
+ */
834
+ export const MCP_ONLY_ARGUMENTS = Object.freeze({
835
+ delegate_permission_decide: Object.freeze(['waitAfterDecision']),
836
+ delegate_question_answer: Object.freeze(['waitAfterAnswer']),
837
+ });
838
+
839
+ /**
840
+ * Validate one entry of a declared array argument.
841
+ *
842
+ * Handles exactly the item shapes this catalog declares — a string, or a closed object
843
+ * with `string` and `string[]` fields plus an optional bounded `custom` string — so an
844
+ * undeclared or wrong-typed entry is refused HERE, with its position named, instead of
845
+ * reaching the plane. That matters for the answer batch: an answer that silently lost
846
+ * or gained a label would be applied to a question it does not answer.
847
+ * @param {object} tool - tool definition.
848
+ * @param {string} key - the array argument's name.
849
+ * @param {object} items - declared item schema.
850
+ * @param {unknown} entry - one item.
851
+ * @param {number} index - its position.
852
+ * @returns {unknown} the validated item.
853
+ */
854
+ function validateArrayItem(tool, key, items, entry, index) {
855
+ const where = `${tool.name}.${key}[${index}]`;
856
+ if (items.type === 'string' || items.type === undefined) {
857
+ if (typeof entry !== 'string') throw new McpError('MCP_ARGUMENT_TYPE', `${where} must be a string`);
858
+ return entry;
859
+ }
860
+ if (items.type !== 'object') throw new McpError('MCP_ARGUMENT_TYPE', `${where} has an unsupported item shape`);
861
+ if (entry === null || typeof entry !== 'object' || Array.isArray(entry)) {
862
+ throw new McpError('MCP_ARGUMENT_TYPE', `${where} must be an object`);
863
+ }
864
+ const allowed = Object.keys(items.properties ?? {});
865
+ for (const field of Object.keys(entry)) {
866
+ if (!allowed.includes(field)) {
867
+ throw new McpError('MCP_ARGUMENT_UNKNOWN', `${where} does not accept field ${JSON.stringify(field)}`);
868
+ }
869
+ }
870
+ for (const field of items.required ?? []) {
871
+ if (typeof entry[field] !== 'string' || entry[field].trim() === '') {
872
+ throw new McpError('MCP_ARGUMENT_REQUIRED', `${where}.${field} must be a non-empty string`);
873
+ }
874
+ }
875
+ const out = {};
876
+ for (const field of allowed) {
877
+ if (!(field in entry)) continue;
878
+ const declared = items.properties[field];
879
+ const value = entry[field];
880
+ if (declared.type === 'string') {
881
+ if (typeof value !== 'string') throw new McpError('MCP_ARGUMENT_TYPE', `${where}.${field} must be a string`);
882
+ if (typeof declared.maxLength === 'number' && value.length > declared.maxLength) {
883
+ throw new McpError('MCP_ARGUMENT_RANGE',
884
+ `${where}.${field} must be at most ${declared.maxLength} characters`);
885
+ }
886
+ out[field] = value;
887
+ continue;
888
+ }
889
+ if (declared.type === 'array') {
890
+ const itemType = declared.items?.type ?? 'string';
891
+ if (!Array.isArray(value)) throw new McpError('MCP_ARGUMENT_TYPE', `${where}.${field} must be an array`);
892
+ for (const item of value) {
893
+ if (itemType === 'string' && typeof item !== 'string') {
894
+ throw new McpError('MCP_ARGUMENT_TYPE', `${where}.${field} must contain strings only`);
895
+ }
896
+ }
897
+ out[field] = [...value];
898
+ continue;
899
+ }
900
+ throw new McpError('MCP_ARGUMENT_TYPE', `${where}.${field} has an unsupported type`);
901
+ }
902
+ return out;
903
+ }
904
+
585
905
  /**
586
906
  * Validate one tool's arguments against its own schema.
587
907
  *
588
908
  * Written by hand rather than pulled from a schema validator because the shapes
589
909
  * here are four small objects; a validator dependency would be the largest thing
590
910
  * in this file for no extra safety.
911
+ *
912
+ * The returned object is the argument set this server will act on. Every declared
913
+ * field survives; nothing undeclared does. The MCP-only control fields listed in
914
+ * {@link MCP_ONLY_ARGUMENTS} stay in the object because they are declared — they are
915
+ * removed at the point where a body is forwarded to the plane, which is the boundary
916
+ * that must not see them.
591
917
  * @param {object} tool - definition from {@link TOOLS}.
592
918
  * @param {unknown} args - caller-supplied arguments.
593
919
  * @returns {object} the arguments to forward.
@@ -608,6 +934,20 @@ function validateArgs(tool, args) {
608
934
  }
609
935
  for (const key of tool.inputSchema.required ?? []) {
610
936
  const field = value[key];
937
+ const declared = tool.inputSchema.properties?.[key] ?? {};
938
+ if (declared.type === 'array') {
939
+ // An array argument is required when it is present AND non-empty: an empty answer
940
+ // batch is not an answer, and accepting one would settle a question with nothing.
941
+ // A NON-array value is a type error, which is a different fact from a missing one
942
+ // and is reported as such below by the per-field pass.
943
+ if (field === undefined || field === null) {
944
+ throw new McpError('MCP_ARGUMENT_REQUIRED', `${tool.name} requires a non-empty ${key}`);
945
+ }
946
+ if (Array.isArray(field) && field.length === 0) {
947
+ throw new McpError('MCP_ARGUMENT_REQUIRED', `${tool.name} requires a non-empty ${key}`);
948
+ }
949
+ continue;
950
+ }
611
951
  if (typeof field !== 'string' || field.trim() === '') {
612
952
  throw new McpError('MCP_ARGUMENT_REQUIRED', `${tool.name} requires a non-empty ${key}`);
613
953
  }
@@ -635,6 +975,12 @@ function validateArgs(tool, args) {
635
975
  } else if (typeof declared.maxLength === 'number' && field.length > declared.maxLength) {
636
976
  throw new McpError('MCP_ARGUMENT_RANGE', `${tool.name}.${key} must be at most ${declared.maxLength} characters`);
637
977
  }
978
+ // A declared minLength is enforced too: an empty string is REFUSED with the field
979
+ // named, never silently ignored — an ack whose id is empty is a caller bug, and
980
+ // letting it through would answer "nothing to acknowledge" instead of the truth.
981
+ if (typeof declared.minLength === 'number' && field.length < declared.minLength) {
982
+ throw new McpError('MCP_ARGUMENT_REQUIRED', `${tool.name}.${key} must not be empty`);
983
+ }
638
984
  out[key] = field;
639
985
  } else if (declared.type === 'boolean') {
640
986
  // Strict: a model that sends the string "true" gets a refusal naming the
@@ -657,6 +1003,13 @@ function validateArgs(tool, args) {
657
1003
  throw new McpError('MCP_ARGUMENT_TYPE', `${tool.name}.${key} must be an object`);
658
1004
  }
659
1005
  out[key] = field;
1006
+ } else if (declared.type === 'array') {
1007
+ // An array argument is validated ITEM BY ITEM against the declared item schema, so
1008
+ // a caller learns which entry is wrong instead of sending an object the plane must
1009
+ // then reject. Only the shapes this catalog declares are accepted: strings, or a
1010
+ // closed object with string/string-array fields and a bounded custom string.
1011
+ if (!Array.isArray(field)) throw new McpError('MCP_ARGUMENT_TYPE', `${tool.name}.${key} must be an array`);
1012
+ out[key] = field.map((entry, index) => validateArrayItem(tool, key, declared.items ?? {}, entry, index));
660
1013
  } else {
661
1014
  out[key] = field;
662
1015
  }
@@ -893,6 +1246,108 @@ function reduceHeavy(source, path, collect) {
893
1246
  return out;
894
1247
  }
895
1248
 
1249
+ /**
1250
+ * Bound the pending-question block of a wait answer, keeping it WHOLE or marking it unusable.
1251
+ *
1252
+ * A question is answerable only when the commander received it EXACTLY as the worker asked —
1253
+ * every question, header, detail, option label and description. A generic per-string cap
1254
+ * would shorten `question`/`detail` while the answer still advertised
1255
+ * `questionAnswerable: true`, so the commander could answer a question it never actually saw.
1256
+ * That is the defect this function exists to remove.
1257
+ *
1258
+ * The rule is therefore all-or-nothing on the block:
1259
+ *
1260
+ * * it fits at its real serialised width → published VERBATIM;
1261
+ * * it does not → published as an explicit omission (`questionsOmitted`, `questionAnswerable:
1262
+ * false`, `reason: 'question-too-large'`), with identity and the count of questions kept so
1263
+ * the host knows a question exists and must ask the worker to narrow it. No question text
1264
+ * is carried, because a shortened one is worse than none: it invites a wrong answer.
1265
+ *
1266
+ * `deadlineAt` is kept in both forms so a host can still see how long the wait has left.
1267
+ * @param {object} block - the pending question block from the engine.
1268
+ * @param {string} path - JSON path for truncation records.
1269
+ * @param {object[]} collect - truncation records.
1270
+ * @param {number} budget - characters the whole block may occupy.
1271
+ * @returns {object | null} the bounded block, or null when there is none.
1272
+ */
1273
+ function boundQuestionBlock(block, path, collect, budget) {
1274
+ if (block === null || block === undefined || typeof block !== 'object' || Array.isArray(block)) return null;
1275
+ if (block.pending !== null && typeof block.pending === 'object' && !Array.isArray(block.questions)) {
1276
+ if (Array.isArray(block.evidence) && block.evidence.length > 0) {
1277
+ collect.push(truncationRecord(`${path}.evidence`, { total: block.evidence.length, omitted: block.evidence.length }));
1278
+ }
1279
+ return {
1280
+ bridged: block.bridged === true,
1281
+ waiting: block.waiting === true,
1282
+ pending: boundQuestionBlock(block.pending, `${path}.pending`, collect, budget),
1283
+ evidence: [],
1284
+ pausedExecutionMs: block.pausedExecutionMs ?? 0,
1285
+ };
1286
+ }
1287
+ const dropped = truncationRecord(path, {
1288
+ total: Array.isArray(block.questions) ? block.questions.length : 0,
1289
+ omitted: Array.isArray(block.questions) ? block.questions.length : 0,
1290
+ detail: 'the question set did not fit the tool-text bound, so it is not published and cannot be answered',
1291
+ });
1292
+ let serialised;
1293
+ try {
1294
+ serialised = JSON.stringify(block);
1295
+ } catch {
1296
+ serialised = null;
1297
+ }
1298
+ if (serialised !== null && serialised.length <= budget) {
1299
+ // Whole: the exact questions the worker asked, untouched.
1300
+ return {
1301
+ ...block,
1302
+ questionsOmitted: block.questionsOmitted === true,
1303
+ };
1304
+ }
1305
+ collect.push(dropped);
1306
+ return {
1307
+ requestId: typeof block.requestId === 'string' ? block.requestId : null,
1308
+ taskId: typeof block.taskId === 'string' ? block.taskId : null,
1309
+ sessionId: typeof block.sessionId === 'string' ? block.sessionId : null,
1310
+ callId: typeof block.callId === 'string' ? block.callId : null,
1311
+ state: block.state ?? null,
1312
+ createdAt: block.createdAt ?? null,
1313
+ deadlineAt: block.deadlineAt ?? null,
1314
+ questionCount: Array.isArray(block.questions) ? block.questions.length : 0,
1315
+ // Stated three ways so no reader or older client can read this as answerable:
1316
+ questions: [],
1317
+ questionsOmitted: true,
1318
+ questionAnswerable: false,
1319
+ grantsAccess: false,
1320
+ reason: 'question-too-large',
1321
+ };
1322
+ }
1323
+
1324
+ /**
1325
+ * Whether a published pending question can actually be answered from what the host received.
1326
+ *
1327
+ * One rule, in one place, so the flag and the block can never disagree: the state must be
1328
+ * `pending`, the question list must be non-empty, and the block must NOT be an omission. An
1329
+ * omission (`questionsOmitted: true`) is explicitly not answerable even though it has a
1330
+ * `requestId` — the host has no question text to answer, and answering would guess.
1331
+ * @param {object} question - the published question block.
1332
+ * @returns {boolean} true only when the whole question set was published.
1333
+ */
1334
+ export function isQuestionAnswerable(question) {
1335
+ if (question === null || typeof question !== 'object') return false;
1336
+ if (!Array.isArray(question.questions) && question.pending !== undefined) return isQuestionAnswerable(question.pending);
1337
+ if (question.questionsOmitted === true) return false;
1338
+ if (question.state !== undefined && question.state !== 'pending') return false;
1339
+ return Array.isArray(question.questions) && question.questions.length > 0;
1340
+ }
1341
+
1342
+ /**
1343
+ * The character budget a pending question block may occupy in one answer.
1344
+ *
1345
+ * The engine refuses to accept a question set whose serialised form exceeds 12 000
1346
+ * characters, so a legitimate block always fits this; anything larger can only be a
1347
+ * projection artifact and is therefore published as an explicit omission.
1348
+ */
1349
+ const QUESTION_WIRE_BUDGET = 16_000;
1350
+
896
1351
  /**
897
1352
  * Copy a value without losing JSON-compatible structure.
898
1353
  * @param {unknown} value - JSON value.
@@ -936,6 +1391,21 @@ function pathsFor(value) {
936
1391
  */
937
1392
  function projectWithStage(value, stage, collect) {
938
1393
  const projected = structuredCloneSafe(value);
1394
+ // The acknowledgment verdict is a fact the engine already acted on. Whatever a stage
1395
+ // trims elsewhere, this trio is restored verbatim on every stage so a compressed or
1396
+ // skeletonised answer cannot turn an applied confirmation into an unknown outcome.
1397
+ const projectedAck = minimalFailureAck(projected.failureAck);
1398
+ if (projectedAck !== null) projected.failureAck = projectedAck;
1399
+ for (const key of ['decisionReceipt', 'answerReceipt']) {
1400
+ const receipt = minimalReceipt(projected[key]);
1401
+ if (receipt !== null) {
1402
+ projected[key] = receipt;
1403
+ collect.push({ path: key, field: 'receipt', detail: 'identity and application facts retained; bulky evidence omitted' });
1404
+ }
1405
+ }
1406
+ if (projected.question !== null && typeof projected.question === 'object') {
1407
+ projected.question = boundQuestionBlock(projected.question, 'question', collect, QUESTION_WIRE_BUDGET);
1408
+ }
939
1409
  const targets = pathsFor(projected);
940
1410
  for (const [target, prefix] of targets) {
941
1411
  for (const key of HEAVY_FIELDS) {
@@ -1002,6 +1472,15 @@ function projectWithStage(value, stage, collect) {
1002
1472
  projected[key] = boundPermissionBlock(item, key, collect);
1003
1473
  continue;
1004
1474
  }
1475
+ // A pending QUESTION is the other decision surface a wait answer publishes, and it is
1476
+ // held to the same rule: published whole, or explicitly unusable. A generic per-string
1477
+ // cut here would shorten `question`/`detail` while the answer still said
1478
+ // `questionAnswerable: true`, which is the defect this branch removes.
1479
+ if (key === 'question') {
1480
+ projected[key] = boundQuestionBlock(item, key, collect, stage.questionBudget ?? QUESTION_WIRE_BUDGET);
1481
+ continue;
1482
+ }
1483
+ if (key === 'answerReceipt' || key === 'decisionReceipt') continue;
1005
1484
  if (key === 'hostAcceptance' && item !== null && typeof item === 'object' && !Array.isArray(item)) {
1006
1485
  projected[key] = boundAcceptance(item, key, collect);
1007
1486
  continue;
@@ -1026,7 +1505,10 @@ function skeletonize(task, path, cap, collect) {
1026
1505
  const pick = (key) => (key in task ? boundValue(task[key], `${path}.${key}`, cap, collect) : undefined);
1027
1506
  const out = {};
1028
1507
  for (const key of ['taskId', 'state', 'phase', 'route', 'reviewRoute', 'reviewRouteError', 'execution', 'error',
1029
- 'hostAcceptance', 'selfApproved', 'cancelledBy', 'createdAt', 'endedAt']) {
1508
+ 'hostAcceptance', 'selfApproved', 'cancelledBy', 'createdAt', 'endedAt',
1509
+ // The Agent Teams verdict is four booleans and a short reason: it survives every
1510
+ // bound so a compressed answer still says whether teams are on for this run.
1511
+ 'agentTeams', 'team']) {
1030
1512
  const value = pick(key);
1031
1513
  if (value === undefined) continue;
1032
1514
  if (key === 'execution' && value !== null && typeof value === 'object') {
@@ -1054,6 +1536,9 @@ function skeletonize(task, path, cap, collect) {
1054
1536
  // operation can never read as complete.
1055
1537
  const pending = pendingPermissionsOf(task, path, collect);
1056
1538
  if (pending !== undefined) out.permission = pending;
1539
+ if (task.question?.pending !== null && typeof task.question?.pending === 'object') {
1540
+ out.question = boundQuestionBlock(task.question, `${path}.question`, collect, QUESTION_WIRE_BUDGET);
1541
+ }
1057
1542
  out.truncation = { path, field: 'result', detail: 'only identity, state, routing, refusal, acceptance and the live pending permission request are shown' };
1058
1543
  collect.push(out.truncation);
1059
1544
  return out;
@@ -1151,13 +1636,18 @@ function pendingPermissionsOf(task, path, collect) {
1151
1636
  for (const key of ['requestId', 'taskId', 'toolName', 'callId', 'fingerprint', 'sessionId']) {
1152
1637
  if (pending[key] !== undefined) out[key] = pending[key];
1153
1638
  }
1154
- for (const key of ['state', 'completeness', 'argumentsComplete', 'allowBlocked', 'reasonSource', 'boundsApplied', 'omitted', 'requestedAccess']) {
1639
+ for (const key of ['state', 'completeness', 'argumentsComplete', 'allowBlocked', 'reasonSource', 'boundsApplied', 'omitted', 'requestedAccess', 'argumentKeys']) {
1155
1640
  if (pending[key] !== undefined) out[key] = pending[key];
1156
1641
  }
1157
1642
  // The two blobs get their own cap, stated when it fires. This is the only cut for
1158
- // them, because the capped value is what is published.
1643
+ // them, because the capped value is what is published. `arguments` uses the
1644
+ // engine's own bound so this layer never re-cuts an operation the engine published
1645
+ // whole; `reason` is the worker's claim, not the operation, and keeps a smaller cap.
1159
1646
  for (const key of ['arguments', 'reason']) {
1160
- if (typeof pending[key] === 'string') out[key] = boundedText(pending[key], 4000, `${prefix}.${key}`, collect);
1647
+ if (typeof pending[key] === 'string') {
1648
+ const cap = key === 'arguments' ? PERMISSION_ARGUMENTS_CAP : PERMISSION_REASON_CAP;
1649
+ out[key] = boundedText(pending[key], cap, `${prefix}.${key}`, collect);
1650
+ }
1161
1651
  }
1162
1652
  // One identified: the provisional cap still applies to it, so the scratch list
1163
1653
  // holds no final cut to forward. Report the exception explicitly instead of a cut,
@@ -1195,8 +1685,16 @@ const PERMISSION_IDENTITY_KEYS = Object.freeze([
1195
1685
  * call. When the cap fires, `boundsApplied` gains this server's own marker and
1196
1686
  * `argumentsComplete` is forced to `false` in {@link boundPermissionRequest}, so a
1197
1687
  * shortened operation is never presented as complete.
1688
+ *
1689
+ * The argument cap is the ENGINE's own bound, not a second, smaller number. A
1690
+ * smaller value here silently re-cut an operation the engine had already published
1691
+ * whole, which turned a complete, reviewable request into an unapprovable one at the
1692
+ * last layer before the host saw it — the exact failure the engine's own bound was
1693
+ * raised to remove. `reason` keeps its separate, smaller cap: it is a claim, never
1694
+ * the operation.
1198
1695
  */
1199
- const PERMISSION_BLOB_CAP = 4_000;
1696
+ const PERMISSION_ARGUMENTS_CAP = PERMISSION_BOUNDS.argumentsChars;
1697
+ const PERMISSION_REASON_CAP = 4_000;
1200
1698
 
1201
1699
  /**
1202
1700
  * Bound one pending permission request without ever making it look decidable when
@@ -1223,9 +1721,18 @@ function boundPermissionRequest(pending, path, collect) {
1223
1721
  out[key] = value;
1224
1722
  continue;
1225
1723
  }
1226
- if ((key === 'arguments' || key === 'reason') && typeof value === 'string' && value.length > PERMISSION_BLOB_CAP) {
1227
- out[key] = boundedText(value, PERMISSION_BLOB_CAP, `${path}.${key}`, collect);
1228
- ownCuts.push(key);
1724
+ if (key === 'arguments' || key === 'reason') {
1725
+ if (typeof value !== 'string') {
1726
+ out[key] = value;
1727
+ continue;
1728
+ }
1729
+ const cap = key === 'arguments' ? PERMISSION_ARGUMENTS_CAP : PERMISSION_REASON_CAP;
1730
+ if (value.length > cap) {
1731
+ out[key] = boundedText(value, cap, `${path}.${key}`, collect);
1732
+ ownCuts.push(key);
1733
+ } else {
1734
+ out[key] = value;
1735
+ }
1229
1736
  continue;
1230
1737
  }
1231
1738
  out[key] = boundValue(value, `${path}.${key}`, 512, collect);
@@ -1396,6 +1903,14 @@ function boundedJson(value) {
1396
1903
  if (projected.permission !== undefined && projected.permission !== null) {
1397
1904
  projected.permissionDecidable = isPermissionDecidable(projected.permission);
1398
1905
  }
1906
+ // The same rule for a question, and for the same reason: the flag must describe what
1907
+ // was PUBLISHED. `boundQuestionBlock` either kept the questions whole or replaced them
1908
+ // with an explicit omission, so this is derived from the surviving block, never from the
1909
+ // pre-bound value.
1910
+ if (projected.question !== undefined && projected.question !== null) {
1911
+ projected.questionAnswerable = isQuestionAnswerable(projected.question);
1912
+ projected.grantsAccess = false;
1913
+ }
1399
1914
  return JSON.stringify(redactDeepStrings(projected), null, 2);
1400
1915
  };
1401
1916
  for (const stage of stages) {
@@ -1404,16 +1919,23 @@ function boundedJson(value) {
1404
1919
  }
1405
1920
 
1406
1921
  // The refusal path is reached only when nothing above fits. An answer that carries
1407
- // a LIVE pending permission request is different from any other oversized answer:
1408
- // dropping it would leave the task paused and undecidable from what the host was
1409
- // told. So before refusing, the answer is reduced to those requests alone — with
1410
- // their blobs re-capped to whatever the bound leaves — and published under an
1411
- // explicit `permissionOnly` marker that states the rest was not included. When
1412
- // even this does not fit, the refusal below stands: a trimmed request must never
1413
- // be presented as an answer.
1922
+ // a LIVE pending permission request — or a DECISION RECEIPT — is different from any
1923
+ // other oversized answer: dropping the request leaves the task paused and undecidable
1924
+ // from what the host was told, and dropping the receipt makes a coordinator believe an
1925
+ // authorization it applied never happened (or that it must be resent). So before
1926
+ // refusing, the answer is reduced to those alone — with their blobs re-capped to
1927
+ // whatever the bound leaves — and published under an explicit `permissionOnly` marker
1928
+ // that states the rest was not included. When even this does not fit, the refusal below
1929
+ // still carries the minimal receipt, so the refusal itself is never a lost decision.
1930
+ const questionRescue = rescueQuestion(value, compact.length);
1931
+ if (questionRescue !== null) return questionRescue;
1414
1932
  const rescue = permissionRescue(value, compact.length);
1415
1933
  if (rescue !== null) {
1416
- for (const cap of [4_000, 1_000, 400, 160, 0]) {
1934
+ // The first rung is the engine's own operation bound, so a request that the
1935
+ // engine published WHOLE is rescued whole whenever it fits at all; only an answer
1936
+ // that still does not fit steps down. Every rung below it re-cuts the operation
1937
+ // and marks the request unapprovable.
1938
+ for (const cap of [PERMISSION_ARGUMENTS_CAP, 4_000, 1_000, 400, 160, 0]) {
1417
1939
  const text = rescue(cap);
1418
1940
  if (text.length <= MAX_TOOL_TEXT_CHARS) return { text, isError: false };
1419
1941
  }
@@ -1422,7 +1944,9 @@ function boundedJson(value) {
1422
1944
  // Nothing projected fits. The answer is refused as data, carrying the task
1423
1945
  // identity when it can: the caller learns which task the content belonged to
1424
1946
  // and why the result was not delivered, instead of receiving a cut fragment
1425
- // that looks like an answer.
1947
+ // that looks like an answer. A decision receipt the refusal cannot carry in full
1948
+ // is carried minimally, because "the answer did not fit" must never mean "the
1949
+ // decision is lost".
1426
1950
  const identity = {};
1427
1951
  if (value?.task !== null && typeof value?.task === 'object' && !Array.isArray(value.task)) {
1428
1952
  if (value.task.taskId !== undefined) identity.taskId = truncateScalar(value.task.taskId);
@@ -1431,6 +1955,15 @@ function boundedJson(value) {
1431
1955
  if (Array.isArray(value?.tasks)) {
1432
1956
  identity.tasks = value.tasks.slice(0, 5).map((task) => ({ taskId: truncateScalar(task?.taskId) }));
1433
1957
  }
1958
+ const refusedReceipt = minimalReceipt(value?.decisionReceipt);
1959
+ if (refusedReceipt !== null) identity.decisionReceipt = refusedReceipt;
1960
+ const refusedAnswer = minimalReceipt(value?.answerReceipt);
1961
+ if (refusedAnswer !== null) identity.answerReceipt = refusedAnswer;
1962
+ // "The answer did not fit" must never mean "the acknowledgement is lost": the same
1963
+ // rule the decision receipt obeys above applies to the ack verdict, which the engine
1964
+ // has already acted on.
1965
+ const refusedAck = minimalFailureAck(value?.failureAck);
1966
+ if (refusedAck !== null) identity.failureAck = refusedAck;
1434
1967
  return refuseResult(
1435
1968
  'MCP_RESULT_OVER_BUDGET',
1436
1969
  'the critical fields alone exceed the tool-text bound, so no usable projection could be produced',
@@ -1439,17 +1972,137 @@ function boundedJson(value) {
1439
1972
  }
1440
1973
 
1441
1974
  /**
1442
- * Build a last-resort projection that keeps only the live pending permission
1443
- * requests of an oversized answer.
1975
+ * The minimum facts a failure acknowledgment must keep under ANY bound.
1976
+ *
1977
+ * A `failureAck` is the producer's verdict on the receiver's `ackFailureEventId`: the
1978
+ * reminder was cleared (or refused) at the engine, and the host that does not learn
1979
+ * this fact may resend the ack or assume an unknown outcome. So the exact `eventId`,
1980
+ * `acknowledged` and `reason` are carried VERBATIM — never rewritten, never invented —
1981
+ * and this projection is applied wherever an answer is compressed, refused or reduced
1982
+ * to its critical fields.
1983
+ * @param {object} ack - the engine's ack result.
1984
+ * @returns {object | null} the verbatim trio, or null when there is nothing to keep.
1985
+ */
1986
+ function minimalFailureAck(ack) {
1987
+ if (ack === null || typeof ack !== 'object' || Array.isArray(ack)) return null;
1988
+ const out = {
1989
+ acknowledged: ack.acknowledged === true,
1990
+ eventId: typeof ack.eventId === 'string' ? ack.eventId : null,
1991
+ reason: typeof ack.reason === 'string' ? ack.reason : null,
1992
+ };
1993
+ // A result with no verdict at all is not an acknowledgment fact: do not publish
1994
+ // a fabricated `acknowledged: false`.
1995
+ if (ack.acknowledged !== true && ack.acknowledged !== false) return null;
1996
+ return out;
1997
+ }
1998
+
1999
+ /**
2000
+ * The minimum facts a decision receipt must keep under ANY bound.
2001
+ *
2002
+ * A receipt is the one answer a coordinator cannot recover by asking again: a decision was
2003
+ * applied (or may have been), and losing the fact makes it either resend an authorization
2004
+ * or assume one that never happened. So this projection keeps identity, `applied` and
2005
+ * `confirmation` VERBATIM, and drops the bulky evidence (`verified`, `grant`, `outcome`) that
2006
+ * can be re-read from `delegate_result`. It states the omission rather than pretending the
2007
+ * receipt was complete, and it never invents a field: a value it did not receive is absent.
2008
+ * @param {object} receipt - the receipt as produced by the decision path.
2009
+ * @returns {object} a bounded receipt with its own identity intact.
2010
+ */
2011
+ function minimalReceipt(receipt) {
2012
+ if (receipt === null || typeof receipt !== 'object' || Array.isArray(receipt)) return null;
2013
+ const out = {};
2014
+ for (const key of ['receiptId', 'taskId', 'requestId', 'decision', 'fingerprint', 'applied', 'confirmation', 'outcome']) {
2015
+ if (receipt[key] !== undefined) out[key] = receipt[key];
2016
+ }
2017
+ // An ANSWER receipt also carries the answer batch, which can be huge; its identity and
2018
+ // verdict are what must survive, so the batch is replaced by its size. Stated, never
2019
+ // silently dropped: a coordinator can re-read the task.
2020
+ if (Array.isArray(receipt.answers)) {
2021
+ out.answerCount = receipt.answers.length;
2022
+ out.answersOmitted = true;
2023
+ }
2024
+ if (receipt.grantsAccess !== undefined) out.grantsAccess = receipt.grantsAccess === true;
2025
+ if (receipt.rejectionFeedback !== undefined) out.rejectionFeedback = feedbackDeliveryFact(receipt.rejectionFeedback);
2026
+ // `applied` and `confirmation` are the whole point; if the source lacked one, the
2027
+ // omission is stated rather than filled with a guess.
2028
+ if (!('applied' in out) || !('confirmation' in out)) return null;
2029
+ out.evidenceOmitted = true;
2030
+ return out;
2031
+ }
2032
+
2033
+ /** Keep the whole live question and both receipt identities when other result data is large. */
2034
+ function rescueQuestion(value, fullTextChars) {
2035
+ if (value?.question === null || typeof value?.question !== 'object') return null;
2036
+ for (const budget of [QUESTION_WIRE_BUDGET, 0]) {
2037
+ const records = [];
2038
+ const question = boundQuestionBlock(value.question, 'question', records, budget);
2039
+ const payload = {
2040
+ ok: value.ok,
2041
+ taskId: value.taskId ?? value.task?.taskId ?? null,
2042
+ state: value.state ?? value.task?.state ?? null,
2043
+ phase: value.phase ?? value.task?.phase ?? null,
2044
+ reason: value.reason,
2045
+ actionable: value.actionable,
2046
+ terminal: value.terminal,
2047
+ question,
2048
+ questionAnswerable: isQuestionAnswerable(question),
2049
+ grantsAccess: false,
2050
+ truncation: { truncated: true, fullResultIncluded: false, fullTextChars, boundChars: MAX_TOOL_TEXT_CHARS, fields: records },
2051
+ };
2052
+ for (const key of ['decisionReceipt', 'answerReceipt']) {
2053
+ const receipt = minimalReceipt(value[key]);
2054
+ if (receipt !== null) payload[key] = receipt;
2055
+ }
2056
+ // A long QUESTION answer can equally follow an applied acknowledgment: the rescue
2057
+ // must keep that verdict verbatim, or the host re-asks what already happened.
2058
+ const questionRescueAck = minimalFailureAck(value.failureAck);
2059
+ if (questionRescueAck !== null) {
2060
+ records.push({ path: 'failureAck', field: 'ack', detail: 'the acknowledgment verdict is retained verbatim' });
2061
+ payload.failureAck = questionRescueAck;
2062
+ }
2063
+ const redacted = redactDeepStrings(payload);
2064
+ const pretty = JSON.stringify(redacted, null, 2);
2065
+ if (pretty.length <= MAX_TOOL_TEXT_CHARS) return { text: pretty, isError: false };
2066
+ const compact = JSON.stringify(redacted);
2067
+ if (compact.length <= MAX_TOOL_TEXT_CHARS) return { text: compact, isError: false };
2068
+ }
2069
+ return null;
2070
+ }
2071
+
2072
+ /**
2073
+ * The short rejection-feedback DELIVERY FACT a decision receipt may carry.
2074
+ *
2075
+ * The full note text is already the worker's own message and is stored in history; repeating
2076
+ * it in every receipt would multiply the answer for no gain. What a receipt must state is
2077
+ * whether the reason actually reached the worker and, when it did not, why — the two fields
2078
+ * that make the delivery checkable instead of claimed.
2079
+ * @param {object | null} feedback - the settled `rejectionFeedback` record.
2080
+ * @returns {{ delivered: boolean, reason: string | null } | null} the short fact.
2081
+ */
2082
+ function feedbackDeliveryFact(feedback) {
2083
+ if (feedback === null || typeof feedback !== 'object' || Array.isArray(feedback)) return null;
2084
+ return {
2085
+ delivered: feedback.delivered === true,
2086
+ reason: typeof feedback.reason === 'string' ? feedback.reason : null,
2087
+ };
2088
+ }
2089
+
2090
+ /**
2091
+ * Build a last-resort projection that keeps the live pending permission request(s) of an
2092
+ * oversized answer — and the decision receipt, when the answer carries one.
1444
2093
  *
1445
2094
  * The ORDER is fixed and the caps are tried by the caller: identity first, then a
1446
2095
  * smaller operation blob. `completeness`/`argumentsComplete`/`allowBlocked` are
1447
2096
  * always carried as the engine states them (or downgraded by the capping), so a
1448
2097
  * shortened request still cannot be allowed.
2098
+ *
2099
+ * The receipt is projected by {@link minimalReceipt} for EVERY cap, including `cap === 0`:
2100
+ * a huge `grant` or `verified` blob can be dropped, but the receipt's identity and its
2101
+ * `applied`/`confirmation` survive, because this answer is the only place they exist.
1449
2102
  * @param {unknown} value - the answer that did not fit.
1450
2103
  * @param {number} fullTextChars - size of the original answer, for the record.
1451
- * @returns {((cap: number) => string) | null} renderer, or null when the answer
1452
- * carries no live pending request.
2104
+ * @returns {((cap: number) => string) | null} renderer, or null when the answer carries
2105
+ * neither a live pending request nor a decision receipt.
1453
2106
  */
1454
2107
  function permissionRescue(value, fullTextChars) {
1455
2108
  const entries = [];
@@ -1471,7 +2124,13 @@ function permissionRescue(value, fullTextChars) {
1471
2124
  path: 'permission', taskId: value.taskId, state: value.state, phase: value.phase, block: null, pending: bare, bare: true,
1472
2125
  });
1473
2126
  }
1474
- if (entries.length === 0) return null;
2127
+ const receipt = minimalReceipt(value?.decisionReceipt);
2128
+ const answerReceipt = minimalReceipt(value?.answerReceipt);
2129
+ // The acknowledgment verdict is critical for the same reason a receipt is: the engine
2130
+ // already acted on it, so a rescue that dropped it would report an applied confirmation
2131
+ // as unknown. It is kept verbatim and counted as part of what "survived".
2132
+ const failureAck = minimalFailureAck(value?.failureAck);
2133
+ if (entries.length === 0 && receipt === null && answerReceipt === null && failureAck === null) return null;
1475
2134
  return (cap) => {
1476
2135
  const records = [];
1477
2136
  const render = (entry) => {
@@ -1486,7 +2145,7 @@ function permissionRescue(value, fullTextChars) {
1486
2145
  pending.completeness = 'truncated';
1487
2146
  pending.allowBlocked = pending.allowBlocked ?? 'the operation could not be included within the tool-text bound';
1488
2147
  records.push({ path: 'permission.arguments', field: 'text', keptChars: 0, detail: 'the operation did not fit' });
1489
- } else if (cap < 4_000 && typeof pending.arguments === 'string' && pending.arguments.length > cap) {
2148
+ } else if (cap < PERMISSION_ARGUMENTS_CAP && typeof pending.arguments === 'string' && pending.arguments.length > cap) {
1490
2149
  pending.arguments = boundedText(pending.arguments, cap, 'permission.arguments', records);
1491
2150
  pending.argumentsComplete = false;
1492
2151
  pending.completeness = pending.completeness === 'complete' ? 'truncated' : pending.completeness;
@@ -1494,8 +2153,24 @@ function permissionRescue(value, fullTextChars) {
1494
2153
  }
1495
2154
  return pending;
1496
2155
  };
2156
+ /** Attach the receipt(s) and the failure acknowledgment, with the omission stated where it happened. */
2157
+ const withReceipt = (payload) => {
2158
+ for (const [key, item] of [['decisionReceipt', receipt], ['answerReceipt', answerReceipt]]) {
2159
+ if (item === null) continue;
2160
+ records.push({ path: key, field: 'receipt', detail: 'identity and application facts retained; bulky evidence omitted' });
2161
+ payload[key] = item;
2162
+ }
2163
+ // The ack verdict is a fact about what ALREADY happened at the producer. Losing it
2164
+ // here made the host believe an applied confirmation was unknown (TB151-01), so it
2165
+ // is carried verbatim at the same top-level place the normal answer publishes it.
2166
+ if (failureAck !== null) {
2167
+ records.push({ path: 'failureAck', field: 'ack', detail: 'the acknowledgment verdict is retained verbatim' });
2168
+ payload.failureAck = failureAck;
2169
+ }
2170
+ return payload;
2171
+ };
1497
2172
  if (entries.length === 1 && entries[0].bare === true) {
1498
- const payload = {
2173
+ const payload = withReceipt({
1499
2174
  ok: value.ok,
1500
2175
  taskId: entries[0].taskId,
1501
2176
  state: entries[0].state,
@@ -1505,7 +2180,21 @@ function permissionRescue(value, fullTextChars) {
1505
2180
  permission: render(entries[0]),
1506
2181
  permissionDecidable: false,
1507
2182
  truncation: truncationBlock(records, fullTextChars, entries),
1508
- };
2183
+ });
2184
+ return JSON.stringify(redactDeepStrings(payload), null, 2);
2185
+ }
2186
+ if (entries.length === 0) {
2187
+ // A RECEIPT-ONLY rescue: no live request survived to publish, but the decision must
2188
+ // not vanish with the rest of the answer.
2189
+ const payload = withReceipt({
2190
+ ok: value.ok,
2191
+ taskId: value.taskId ?? receipt?.taskId ?? answerReceipt?.taskId ?? null,
2192
+ state: value.state ?? null,
2193
+ phase: value.phase ?? null,
2194
+ reason: value.reason ?? null,
2195
+ actionable: true,
2196
+ truncation: truncationBlock(records, fullTextChars, entries),
2197
+ });
1509
2198
  return JSON.stringify(redactDeepStrings(payload), null, 2);
1510
2199
  }
1511
2200
  const tasks = entries.map((entry) => {
@@ -1519,9 +2208,9 @@ function permissionRescue(value, fullTextChars) {
1519
2208
  permission: block,
1520
2209
  };
1521
2210
  });
1522
- const payload = entries.length === 1 && entries[0].path === 'task'
2211
+ const payload = withReceipt(entries.length === 1 && entries[0].path === 'task'
1523
2212
  ? { ok: value.ok, task: tasks[0], truncation: truncationBlock(records, fullTextChars, entries) }
1524
- : { ok: value.ok, tasks, truncation: truncationBlock(records, fullTextChars, entries) };
2213
+ : { ok: value.ok, tasks, truncation: truncationBlock(records, fullTextChars, entries) });
1525
2214
  return JSON.stringify(redactDeepStrings(payload), null, 2);
1526
2215
  };
1527
2216
  }
@@ -1648,6 +2337,24 @@ export function createMcpServer(options) {
1648
2337
  // only shows up in the field.
1649
2338
  const calls = [];
1650
2339
  let initialized = false;
2340
+ // The per-process census behind `delegate_metrics` and the exit diagnostics line.
2341
+ // Counts, durations, byte sizes and closed-vocabulary reasons only.
2342
+ const metrics = createCallMetrics({
2343
+ now,
2344
+ limit: Number.isInteger(options.metricsSamples) && options.metricsSamples > 0 ? options.metricsSamples : 64,
2345
+ });
2346
+ /** Per-server sequence, so every wait chain has its own identifier. */
2347
+ let correlationSequence = 0;
2348
+
2349
+ /**
2350
+ * The identifier of the next wait chain in this process.
2351
+ * @param {string} prefix - `wait` or `decision`.
2352
+ * @returns {string} identifier.
2353
+ */
2354
+ function nextCorrelationId(prefix) {
2355
+ correlationSequence += 1;
2356
+ return correlationId(prefix, correlationSequence);
2357
+ }
1651
2358
 
1652
2359
  /**
1653
2360
  * Remember one call without growing without bound.
@@ -1658,6 +2365,7 @@ export function createMcpServer(options) {
1658
2365
  calls.push(record);
1659
2366
  if (calls.length > MAX_CALL_LOG) calls.splice(0, calls.length - MAX_CALL_LOG);
1660
2367
  }
2368
+
1661
2369
  /**
1662
2370
  * Run one tool call and wrap the answer as MCP content.
1663
2371
  * @param {string} name - tool name.
@@ -1687,14 +2395,35 @@ export function createMcpServer(options) {
1687
2395
  };
1688
2396
  }
1689
2397
  recordCall({ tool: name, route, payload });
2398
+ // Counted AFTER validation: a refused argument never reached the program, so it is
2399
+ // not evidence of what this surface was asked to do.
2400
+ metrics.recordToolCall(name);
2401
+ // Every answer this call produces is measured in ONE place, after it has been bounded
2402
+ // and redacted: `boundedJson` output IS the tool text the host parses, so its UTF-8
2403
+ // size is the only honest byte count. Measuring earlier (on the raw plane body, or on
2404
+ // the compact answer) would count something the host never receives, and measuring
2405
+ // inside the answer would be self-referential. Not a delivery receipt: this is the
2406
+ // size handed to the transport, not proof the host read it.
2407
+ let producedText = null;
1690
2408
  try {
1691
- const result = name === 'delegate_wait'
1692
- ? await waitAnswer(payload, context)
1693
- : await callExecution(route, payload);
2409
+ let result;
2410
+ if (name === 'delegate_wait') {
2411
+ result = await waitAnswer(payload, context);
2412
+ } else if (name === 'delegate_permission_decide') {
2413
+ result = await decidePermissionAnswer(payload, context);
2414
+ } else if (name === 'delegate_question_answer') {
2415
+ result = await answerQuestionCall(payload, context);
2416
+ } else if (name === 'delegate_metrics') {
2417
+ // A census of THIS process: no plane route, no task identity, nothing to change.
2418
+ result = { ok: true, metrics: metrics.snapshot() };
2419
+ } else {
2420
+ result = await callExecution(route, payload);
2421
+ }
1694
2422
  // A paged read of the review note returns only its slice: it is a different, small
1695
2423
  // ANSWER shape, not a projection of the big one.
1696
2424
  const page = name === 'delegate_result' ? reviewNotePage(payload, result) : null;
1697
2425
  const bounded = boundedJson(page ?? result);
2426
+ producedText = bounded.text;
1698
2427
  // A structurally trimmed answer is a real answer, so `isError` stays unset;
1699
2428
  // only an answer that could not be delivered at all is reported as an error.
1700
2429
  return bounded.isError
@@ -1707,10 +2436,36 @@ export function createMcpServer(options) {
1707
2436
  const code = typeof error?.code === 'string' ? error.code : 'MCP_CALL_FAILED';
1708
2437
  const message = diagnostic(error?.message ?? String(error), 400) ?? 'the delegated call was refused';
1709
2438
  logger?.warn?.('dsh-delegate-mcp: call refused', code);
2439
+ // A refusal that carries structured facts (a decision receipt whose outcome nobody
2440
+ // established) publishes them as `error.details`. The refusal still REFUSES — nothing
2441
+ // here turns it into a success — but a coordinator keeps the identity it needs to
2442
+ // query the task instead of resending blindly.
2443
+ const details = error instanceof McpError && error.details !== null && error.details !== undefined
2444
+ ? error.details
2445
+ : undefined;
2446
+ // An acknowledgment verdict the wait loop already learned survives this refusal:
2447
+ // whether the host's ack landed (or was refused) is a fact about the past that a
2448
+ // transport failure or a cancellation must not erase, and the host must never
2449
+ // have to resend an ack blindly. Attached verbatim as `details.failureAck`.
2450
+ const ackFact = error !== null && typeof error === 'object' && error.failureAck !== undefined
2451
+ ? error.failureAck
2452
+ : (details !== undefined && details.failureAck !== undefined ? details.failureAck : undefined);
2453
+ const boundedDetails = ackFact !== undefined
2454
+ ? { ...(details ?? {}), failureAck: ackFact }
2455
+ : details;
2456
+ producedText = boundedJson({
2457
+ ok: false,
2458
+ error: { code, message, ...(boundedDetails === undefined ? {} : { details: boundedDetails }) },
2459
+ }).text;
1710
2460
  return {
1711
- content: [{ type: 'text', text: boundedJson({ ok: false, error: { code, message } }).text }],
2461
+ content: [{ type: 'text', text: producedText }],
1712
2462
  isError: true,
1713
2463
  };
2464
+ } finally {
2465
+ // Counted for every outcome, including a refusal and a cancellation: the size is of
2466
+ // the text this process handed back, whatever that text said. `null` means no text
2467
+ // existed at all, which the census reports as an unmeasured return.
2468
+ metrics.recordReturn(producedText);
1714
2469
  }
1715
2470
  }
1716
2471
 
@@ -1725,8 +2480,18 @@ export function createMcpServer(options) {
1725
2480
  * @param {{ signal?: AbortSignal }} context - per-request cancellation.
1726
2481
  * @returns {Promise<object>} `{ ok: true, ...answer }`.
1727
2482
  */
1728
- async function waitAnswer(payload, context) {
2483
+ async function waitAnswer(payload, context, options = {}) {
1729
2484
  const waitSeconds = payload.waitSeconds ?? DEFAULT_WAIT_SECONDS;
2485
+ // The receiver's acknowledgment of an earlier reminder. It is consumed HERE and
2486
+ // forwarded to the internal observations; it never reaches the plane as part of
2487
+ // any other tool call.
2488
+ const ackFailureEventId = typeof payload.ackFailureEventId === 'string' && payload.ackFailureEventId !== ''
2489
+ ? payload.ackFailureEventId
2490
+ : null;
2491
+ const correlation = {
2492
+ waitId: nextCorrelationId('wait'),
2493
+ afterDecisionId: options.afterDecisionId ?? null,
2494
+ };
1730
2495
  const result = await waitForTask({
1731
2496
  callExecution,
1732
2497
  taskId: payload.taskId,
@@ -1734,16 +2499,370 @@ export function createMcpServer(options) {
1734
2499
  signal: context?.signal,
1735
2500
  now,
1736
2501
  sleep,
2502
+ correlation,
2503
+ skipPermission: options.skipPermission,
2504
+ skipQuestion: options.skipQuestion,
2505
+ ...(ackFailureEventId === null ? {} : { ackFailureEventId }),
2506
+ // The loop reports its own accounting once, on every exit path, so a wait that
2507
+ // threw is counted too. Counting lives HERE, not in the answer: a thrown call has
2508
+ // no answer to carry a count.
2509
+ waitMetrics: (summary) => metrics.recordWait(summary),
1737
2510
  });
1738
2511
  if (result?.error !== undefined) {
1739
2512
  // The loop could not obtain an observation at all. That is a refusal with the
1740
2513
  // harness's own code, raised so the standard refusal path shapes it — never an
1741
- // answer that would look like a task state.
2514
+ // answer that would look like a task state. An ack verdict the loop already
2515
+ // learned survives the refusal: the wait loop attaches it at the TOP LEVEL of
2516
+ // the refusal answer (`result.failureAck`); older shapes that carried it inside
2517
+ // `result.error.failureAck` are still honoured, so the host learns from the
2518
+ // refusal whether its acknowledgment landed instead of guessing.
2519
+ const ackFact = result.failureAck ?? result.error?.failureAck;
2520
+ if (ackFact !== null && ackFact !== undefined) {
2521
+ throw new McpError(result.error.code, result.error.message, { details: { failureAck: ackFact } });
2522
+ }
1742
2523
  throw new McpError(result.error.code, result.error.message);
1743
2524
  }
1744
2525
  return { ok: true, ...result };
1745
2526
  }
1746
2527
 
2528
+ /**
2529
+ * One `delegate_permission_decide` call.
2530
+ *
2531
+ * Two shapes, and the flag selects between them:
2532
+ *
2533
+ * * **`waitAfterDecision` absent or `false` — the historical call, unchanged.** The
2534
+ * permission route's answer is returned verbatim, with no receipt and no added
2535
+ * field, so an existing client sees exactly what it saw in 1.4.2. Only the internal
2536
+ * census knows the call happened.
2537
+ * * **`waitAfterDecision: true` — decide, then continue in the SAME call.** The answer
2538
+ * is the flat wait shape a `delegate_wait` returns (`reason`/`state`/`permission`/
2539
+ * `task` at the top level, the whole redacted pending operation with its
2540
+ * `completeness`/`fingerprint`) plus a `decisionReceipt`. That shape is deliberate:
2541
+ * it is the shape `boundedJson` already protects, so a very large answer still keeps
2542
+ * the receipt AND the live request — `minimalReceipt` guarantees the identity and
2543
+ * `applied`/`confirmation` survive even the last-resort rescue, while a cut operation
2544
+ * is explicitly marked unapprovable rather than silently shortened.
2545
+ *
2546
+ * Five invariants, in order:
2547
+ *
2548
+ * 1. **The decision goes to the existing permission route, unchanged.** It is the only
2549
+ * thing that can apply it, and it re-validates ownership, the switch, the deadline,
2550
+ * the fingerprint and the completeness flags. It is sent FIRST and alone, so a
2551
+ * refused decision issues no other request and raises the same refusal code it always
2552
+ * did.
2553
+ * 2. **`waitAfterDecision` never reaches the plane.** It is stripped here, at the MCP
2554
+ * boundary, and the decision route's existing unknown-field validation is the guard
2555
+ * for a caller that tries anyway. No route change is needed for this flag.
2556
+ * 3. **`applied` is only claimed from matching evidence.** The receipt is built by
2557
+ * `decisionReceipt`, which requires the answer to name the SAME task, the SAME request
2558
+ * and the SAME operation the decision was bound to, plus a settled `state` and the
2559
+ * `outcome` this decision asked for. An answer that is `ok: false`, that lacks that
2560
+ * evidence, or that CONTRADICTS the decision is `applied: null` with
2561
+ * `confirmation: "unknown"` — never a fabricated `false` and never a silent
2562
+ * substitution of the quoted fingerprint — and it is refused and NOT continued.
2563
+ * 4. **A new request is never inherited.** The shared wait loop skips an observation
2564
+ * that still describes the request this call decided, matching on requestId AND
2565
+ * fingerprint; anything else is answered as the new question it is.
2566
+ * 5. **An applied decision is never unsaid.** If the follow-up wait then fails, is
2567
+ * cancelled or is interrupted, this call still SUCCEEDS with the receipt,
2568
+ * `reason: null` and a `waitError` block, instead of falling into the generic refusal
2569
+ * path that would replace the answer with a bare error and swallow the receipt.
2570
+ * @param {object} payload - validated arguments (may carry `waitAfterDecision`).
2571
+ * @param {{ signal?: AbortSignal }} context - per-request cancellation.
2572
+ * @returns {Promise<object>} the permission answer, or the flat wait answer plus a receipt.
2573
+ */
2574
+ async function decidePermissionAnswer(payload, context) {
2575
+ const { waitAfterDecision, ...decisionBody } = payload;
2576
+ const receiptId = nextCorrelationId('decision');
2577
+ let result;
2578
+ try {
2579
+ result = await callExecution('permission', decisionBody);
2580
+ } catch (error) {
2581
+ // Nothing was confirmed. Two cases, and they are NOT the same fact:
2582
+ //
2583
+ // * the HARNESS answered with its own refusal code — the decision is definitely NOT
2584
+ // applied, which is the refusal every earlier client already handles;
2585
+ // * the call failed before an answer existed (transport, timeout, malformed body) —
2586
+ // whether it was applied is genuinely UNKNOWN, and that must never be reported as
2587
+ // a clean failure that invites a resend.
2588
+ const code = typeof error?.code === 'string' ? error.code : 'MCP_CALL_FAILED';
2589
+ const unconfirmed = UNCONFIRMED_DECISION_CODES.has(code);
2590
+ const receipt = {
2591
+ receiptId,
2592
+ ...decisionReceipt({
2593
+ taskId: decisionBody.taskId ?? null,
2594
+ requestId: decisionBody.requestId ?? null,
2595
+ decision: decisionBody.decision ?? null,
2596
+ fingerprint: typeof decisionBody.fingerprint === 'string' ? decisionBody.fingerprint : null,
2597
+ error: { code },
2598
+ refusedByHarness: !unconfirmed,
2599
+ }),
2600
+ };
2601
+ metrics.recordDecision({
2602
+ receiptId,
2603
+ taskId: receipt.taskId,
2604
+ requestId: receipt.requestId,
2605
+ decision: receipt.decision,
2606
+ fingerprint: receipt.fingerprint,
2607
+ applied: receipt.applied,
2608
+ confirmation: receipt.confirmation,
2609
+ });
2610
+ // The historical protocol is unchanged: without the flag the refusal is rethrown
2611
+ // exactly as before, with no added field.
2612
+ if (waitAfterDecision !== true) throw error;
2613
+ // With the flag, an UNCONFIRMED decision is still refused (nothing awaits it), but the
2614
+ // refusal now CARRIES its identity so a coordinator can query the task by name instead
2615
+ // of resending blindly. A harness refusal keeps its own code and its own shape.
2616
+ if (!unconfirmed) throw error;
2617
+ throw new McpError(code, `${error?.message ?? 'the decision could not be confirmed'} `
2618
+ + '(unknown whether it was applied; read the task with delegate_result before sending it again)', {
2619
+ details: { decisionReceipt: receipt },
2620
+ });
2621
+ }
2622
+ const receipt = { receiptId, ...decisionReceipt({
2623
+ taskId: decisionBody.taskId ?? null,
2624
+ requestId: decisionBody.requestId ?? null,
2625
+ decision: decisionBody.decision ?? null,
2626
+ fingerprint: typeof decisionBody.fingerprint === 'string' ? decisionBody.fingerprint : null,
2627
+ answer: result,
2628
+ }) };
2629
+ metrics.recordDecision({
2630
+ receiptId,
2631
+ taskId: receipt.taskId,
2632
+ requestId: receipt.requestId,
2633
+ decision: receipt.decision,
2634
+ fingerprint: receipt.fingerprint,
2635
+ applied: receipt.applied,
2636
+ confirmation: receipt.confirmation,
2637
+ });
2638
+ if (waitAfterDecision !== true) return result;
2639
+ // A decision that could not be CONFIRMED must never continue: the answer would look like
2640
+ // a running task whose state nobody established. It is refused with its identity instead.
2641
+ if (receipt.applied !== true) {
2642
+ throw new McpError('MCP_DECISION_UNCONFIRMED',
2643
+ `the decision was not confirmed by the harness (${receipt.reason ?? 'no usable confirmation evidence'}); `
2644
+ + 'read the task with delegate_result before deciding whether to send it again',
2645
+ { details: { decisionReceipt: receipt } });
2646
+ }
2647
+ // The same wait loop a plain `delegate_wait` uses: its default deadline, its 25-second
2648
+ // observation bound, its heartbeat handling and its interruption classification. The
2649
+ // ONLY addition is the rollover predicate.
2650
+ let answer;
2651
+ try {
2652
+ answer = await waitAnswer({ taskId: receipt.taskId }, context, {
2653
+ afterDecisionId: receipt.receiptId,
2654
+ skipPermission: decidedRequestMatcher(receipt),
2655
+ });
2656
+ } catch (error) {
2657
+ // The decision was ALREADY APPLIED. The general refusal path would replace this answer
2658
+ // with a bare error and swallow the receipt, which is exactly how a coordinator loses
2659
+ // track of an authorization that IS in force. So a follow-up failure — a transport
2660
+ // error, an abort, a spent deadline — is reported WITH the receipt, and says plainly
2661
+ // that only the waiting failed.
2662
+ const code = typeof error?.code === 'string' ? error.code : 'MCP_CALL_FAILED';
2663
+ const message = diagnostic(error?.message ?? String(error), 400) ?? 'the follow-up wait could not be completed';
2664
+ logger?.warn?.('dsh-delegate-mcp: decision applied, follow-up wait ended', code);
2665
+ return {
2666
+ ok: true,
2667
+ // A wait outcome, not a decision outcome: `reason: null` states that no task state was
2668
+ // observed, so nothing can be read as "still running" or "finished".
2669
+ reason: null,
2670
+ taskId: receipt.taskId,
2671
+ actionable: false,
2672
+ terminal: false,
2673
+ instruction: 'The decision WAS applied and stands — do not resend it. This call\'s follow-up wait '
2674
+ + 'failed or was interrupted; the execution was NOT stopped, cancelled or reassigned. Keep the taskId '
2675
+ + 'and call delegate_wait again on the SAME task to resume following it.',
2676
+ waitError: { code, message, phase: 'follow-up-wait' },
2677
+ decisionReceipt: receipt,
2678
+ };
2679
+ }
2680
+ return { ...answer, decisionReceipt: receipt };
2681
+ }
2682
+
2683
+ /**
2684
+ * The request id of a pending block, in either published shape.
2685
+ *
2686
+ * A wait answer may publish the block directly (`{ requestId, questions }`) or wrap it
2687
+ * (`{ pending: { requestId, questions } }`), and both are accepted everywhere else in this
2688
+ * file. Reading only one shape here would make the post-answer rollover skip nothing — the
2689
+ * answered question would be offered again as if it were new — so both are read in one place.
2690
+ * @param {unknown} block - the published question block.
2691
+ * @returns {string | null} the request id, or null.
2692
+ */
2693
+ function pendingRequestIdOf(block) {
2694
+ if (block === null || typeof block !== 'object') return null;
2695
+ const inner = block.questions === undefined && block.pending !== null && typeof block.pending === 'object'
2696
+ ? block.pending
2697
+ : block;
2698
+ return typeof inner?.requestId === 'string' && inner.requestId !== '' ? inner.requestId : null;
2699
+ }
2700
+
2701
+ /**
2702
+ * Whether a route's echoed answer batch is the one this call sent.
2703
+ *
2704
+ * Compared entry by entry, because a route that normalised an answer differently (dropped
2705
+ * a label, changed custom text, duplicated a question) did NOT apply what was sent. Order
2706
+ * is not significant: answers are identified by question id.
2707
+ * @param {unknown} echoed - the route's answers.
2708
+ * @param {unknown} sent - the answers this call sent.
2709
+ * @returns {boolean} true only when both batches are equal by id.
2710
+ */
2711
+ function sameAnswerBatch(echoed, sent) {
2712
+ if (!Array.isArray(echoed) || !Array.isArray(sent)) return false;
2713
+ if (echoed.length !== sent.length) return false;
2714
+ const byId = new Map();
2715
+ for (const entry of echoed) {
2716
+ if (entry === null || typeof entry !== 'object' || typeof entry.id !== 'string') return false;
2717
+ if (byId.has(entry.id)) return false;
2718
+ byId.set(entry.id, entry);
2719
+ }
2720
+ for (const entry of sent) {
2721
+ const other = byId.get(entry?.id);
2722
+ if (other === undefined) return false;
2723
+ const left = Array.isArray(other.selected) ? other.selected : [];
2724
+ const right = Array.isArray(entry.selected) ? entry.selected : [];
2725
+ if (left.length !== right.length || left.some((label, index) => label !== right[index])) return false;
2726
+ const leftCustom = typeof other.custom === 'string' ? other.custom : null;
2727
+ const rightCustom = typeof entry.custom === 'string' ? entry.custom : null;
2728
+ if (leftCustom !== rightCustom) return false;
2729
+ }
2730
+ return true;
2731
+ }
2732
+
2733
+ /**
2734
+ * One `delegate_question_answer` call.
2735
+ *
2736
+ * The same two shapes the permission decision has, for the same reasons:
2737
+ *
2738
+ * * **`waitAfterAnswer` absent or `false` — the plain call.** The question route's
2739
+ * answer is returned verbatim, so a client that only answers sees exactly the route
2740
+ * reply and nothing it must learn.
2741
+ * * **`waitAfterAnswer: true` — answer, then keep following in the SAME call.** The
2742
+ * answer is the flat wait shape plus an `answerReceipt`.
2743
+ *
2744
+ * Four invariants:
2745
+ *
2746
+ * 1. **The answer goes to the question route, unchanged.** It is the only thing that
2747
+ * can apply it: ownership, the switch, the deadline, the single-use rule and the
2748
+ * per-question validation all live behind it. It is sent FIRST and alone, so a
2749
+ * refused answer issues no other request.
2750
+ * 2. **`waitAfterAnswer` never reaches the plane.** It is stripped at this boundary.
2751
+ * 3. **The receipt is evidence, not optimism.** `applied: true` is claimed only when
2752
+ * the route answered `ok: true` AND its `answer.receiptId`/`requestId` match the
2753
+ * ones this call sent. A transport failure is `applied: null` with
2754
+ * `confirmation: "unknown"`, because whether it landed is genuinely unknown — and
2755
+ * the receipt then tells the caller to read the task rather than resend.
2756
+ * 4. **An applied answer is never unsaid.** A failed follow-up wait still SUCCEEDS
2757
+ * with the receipt, `reason: null` and a `waitError`, saying plainly that only the
2758
+ * waiting ended.
2759
+ * @param {object} payload - validated arguments (may carry `waitAfterAnswer`).
2760
+ * @param {{ signal?: AbortSignal }} context - per-request cancellation.
2761
+ * @returns {Promise<object>} the question answer, or the flat wait answer plus a receipt.
2762
+ */
2763
+ async function answerQuestionCall(payload, context) {
2764
+ const { waitAfterAnswer, ...answerBody } = payload;
2765
+ const receiptId = nextCorrelationId('answer');
2766
+ const receiptFor = (applied, confirmation, extra = {}) => ({
2767
+ receiptId,
2768
+ taskId: answerBody.taskId ?? null,
2769
+ requestId: answerBody.requestId ?? null,
2770
+ answers: Array.isArray(answerBody.answers)
2771
+ ? answerBody.answers.map((entry) => ({
2772
+ id: entry?.id ?? null,
2773
+ selected: Array.isArray(entry?.selected) ? [...entry.selected] : [],
2774
+ ...(typeof entry?.custom === 'string' ? { custom: entry.custom } : {}),
2775
+ }))
2776
+ : [],
2777
+ applied,
2778
+ confirmation,
2779
+ // Stated on every receipt so no reader can mistake this for an approval.
2780
+ grantsAccess: false,
2781
+ ...extra,
2782
+ });
2783
+ let result;
2784
+ try {
2785
+ result = await callExecution('question', answerBody);
2786
+ } catch (error) {
2787
+ const code = typeof error?.code === 'string' ? error.code : 'MCP_CALL_FAILED';
2788
+ const unconfirmed = UNCONFIRMED_DECISION_CODES.has(code);
2789
+ const receipt = receiptFor(
2790
+ unconfirmed ? null : false,
2791
+ unconfirmed ? 'unknown' : 'refused',
2792
+ { reason: code },
2793
+ );
2794
+ // The historical protocol is unchanged: without the flag the refusal is rethrown as
2795
+ // it is, with no added field.
2796
+ if (waitAfterAnswer !== true) throw error;
2797
+ if (!unconfirmed) throw error;
2798
+ throw new McpError(code, `${error?.message ?? 'the answer could not be confirmed'} `
2799
+ + '(unknown whether it was applied; read the task with delegate_result before sending it again)', {
2800
+ details: { answerReceipt: receipt },
2801
+ });
2802
+ }
2803
+ const answered = result?.answer ?? null;
2804
+ // Confirmation requires the route to echo the SAME task, request AND the answers it
2805
+ // actually normalised. A route that answers `ok: true` for a different request, or
2806
+ // whose stored answers differ from what was sent, established nothing about THIS
2807
+ // answer — so `applied` becomes `null` with `confirmation: "unknown"`, never `false`
2808
+ // (which would read as "definitely not applied" and invite a resend).
2809
+ const confirmed = result?.ok === true
2810
+ && answered !== null && typeof answered === 'object'
2811
+ && answered.requestId === answerBody.requestId
2812
+ && answered.taskId === answerBody.taskId
2813
+ && sameAnswerBatch(answered.answers, answerBody.answers);
2814
+ const receipt = receiptFor(confirmed ? true : null, confirmed ? 'confirmed' : 'unknown', {
2815
+ ...(confirmed ? {} : { reason: 'the route answered without matching this request and its answers' }),
2816
+ });
2817
+ metrics.recordDecision({
2818
+ receiptId,
2819
+ taskId: receipt.taskId,
2820
+ requestId: receipt.requestId,
2821
+ decision: QUESTION_ANSWER_KIND,
2822
+ fingerprint: null,
2823
+ applied: receipt.applied,
2824
+ confirmation: receipt.confirmation,
2825
+ });
2826
+ if (waitAfterAnswer !== true) return result;
2827
+ if (receipt.applied !== true) {
2828
+ throw new McpError('MCP_ANSWER_UNCONFIRMED',
2829
+ `the answer was not confirmed by the harness (${receipt.reason ?? 'no usable confirmation evidence'}); `
2830
+ + 'read the task with delegate_result before answering again',
2831
+ { details: { answerReceipt: receipt } });
2832
+ }
2833
+ let answer;
2834
+ try {
2835
+ answer = await waitAnswer({ taskId: receipt.taskId }, context, {
2836
+ afterDecisionId: receipt.receiptId,
2837
+ // The set this call just answered can occupy the engine's slot for a moment. Skip
2838
+ // exactly that request id; a different one is a NEW question and returns at once.
2839
+ // The id is read from the block directly AND from a `{ pending: … }` wrapper,
2840
+ // because a harness may publish either shape — a matcher that knew one would let the
2841
+ // answered question be re-offered as a new one.
2842
+ skipQuestion: (observation) => pendingRequestIdOf(observation?.question) === receipt.requestId,
2843
+ });
2844
+ } catch (error) {
2845
+ // The answer WAS applied. Reporting the generic refusal here would swallow the
2846
+ // receipt, which is how a coordinator loses track of an answer that is in force.
2847
+ const code = typeof error?.code === 'string' ? error.code : 'MCP_CALL_FAILED';
2848
+ const message = diagnostic(error?.message ?? String(error), 400) ?? 'the follow-up wait could not be completed';
2849
+ logger?.warn?.('dsh-delegate-mcp: answer applied, follow-up wait ended', code);
2850
+ return {
2851
+ ok: true,
2852
+ reason: null,
2853
+ taskId: receipt.taskId,
2854
+ actionable: false,
2855
+ terminal: false,
2856
+ instruction: 'The answer WAS applied and stands — do not resend it. This call\'s follow-up wait failed or '
2857
+ + 'was interrupted; the execution was NOT stopped, cancelled or reassigned. Keep the taskId and call '
2858
+ + 'delegate_wait again on the SAME task to resume following it.',
2859
+ waitError: { code, message, phase: 'follow-up-wait' },
2860
+ answerReceipt: receipt,
2861
+ };
2862
+ }
2863
+ return { ...answer, answerReceipt: receipt };
2864
+ }
2865
+
1747
2866
  /**
1748
2867
  * Answer one JSON-RPC message.
1749
2868
  *
@@ -1797,7 +2916,18 @@ export function createMcpServer(options) {
1797
2916
  + 'pauses that call and reports it as `permission.pending` in delegate_result; while it waits the '
1798
2917
  + 'task stays `running` with phase `awaiting-permission`. Answer exactly one such request with '
1799
2918
  + 'delegate_permission_decide (`allow-once` or `reject`). That decision covers only that call, is '
1800
- + 'never a standing grant, and cannot approve anything else. To follow a task without polling, use '
2919
+ + 'never a standing grant, and cannot approve anything else. When your channel supports it, pass '
2920
+ + '`waitAfterDecision: true`: the decision and the following wait then happen in ONE call, and the '
2921
+ + 'answer is the same compact shape delegate_wait returns plus `decisionReceipt`. Deciding and then '
2922
+ + 'waiting is what resumes the task; a client without the flag decides first and then calls '
2923
+ + 'delegate_wait on the same taskId. `decisionReceipt.applied: true` is claimed only when the harness '
2924
+ + 'confirmed the same task, request and operation. `applied: null` with `confirmation: "unknown"` '
2925
+ + 'means nothing was established — the call failed before an answer, or the answer contradicted or '
2926
+ + 'lacked the evidence to confirm it (the refusal carries `error.details.decisionReceipt`) — so read '
2927
+ + 'the task with delegate_result before sending the decision again, and never resend automatically. '
2928
+ + 'When an APPLIED decision\'s follow-up wait fails or is cancelled, the call still succeeds with that '
2929
+ + 'receipt, `reason: null` and a `waitError` block: only the waiting ended, the execution was not '
2930
+ + 'stopped, and the decision must not be resent. To follow a task without polling, use '
1801
2931
  + 'delegate_wait({ taskId }): one call blocks until the task needs you (permission, ready, failed, '
1802
2932
  + 'cancelled, interrupted) or until its own one-hour deadline, in which case it answers reason '
1803
2933
  + '`wait-limit` with `actionable: false` and you call it again with the same taskId instead of '
@@ -1810,24 +2940,35 @@ export function createMcpServer(options) {
1810
2940
  + 'own client tool timeout firing, does not prove the execution stopped or that it is alive: keep '
1811
2941
  + 'the taskId and check one compact fact if you need to, and never duplicate, restart or cancel a '
1812
2942
  + 'task merely because a wait or a client timeout ended. '
2943
+ + 'Four different things must not be confused. (a) `wait-limit` is this call\'s OWN deadline: nothing '
2944
+ + 'changed, wait again on the same taskId. (b) Your client handing the call back on its own tool/exec '
2945
+ + 'time limit is an OUTER limit: the observation did not end and the worker did not stop, so continue '
2946
+ + 'the SAME exec cell and ask for the longest yield the host supports (roughly 1200000 ms when a '
2947
+ + 'yield/pragmas parameter exists, not a minute) instead of re-issuing every second. (c) `attention` '
2948
+ + 'is genuine inactivity: no activity for the configured threshold (ten minutes by default) while the '
2949
+ + 'task still runs. (d) The task\'s total execution timeout is the worker\'s own budget, reported as a '
2950
+ + 'terminal state — it is not `wait-limit`, not `attention` and not a client-side event. A real '
2951
+ + 'failure is worth one de-duplicated reminder; an ordinary single failing test inside the worker is '
2952
+ + 'the worker\'s job to fix and is not a host event. '
1813
2953
  + '`interrupted` never means the execution stopped by itself: this call returns it at once '
1814
2954
  + 'with `terminal: false` while the task is still pending or running (wait again on the same '
1815
2955
  + 'taskId); only a task record that is itself interrupted (a restart history) is `terminal: true`. '
1816
- + 'A host that hands the wait back on its own tool/exec time limit is reporting an OUTER limit, '
1817
- + 'not a result: the MCP observation did not end and the worker did not stop. Continue the SAME '
1818
- + 'exec cell on the taskId you hold, ask for the longest yield the host supports (roughly 1200000 '
1819
- + 'ms when a yield/pragmas parameter exists, not a minute) rather than re-issuing every second, and '
1820
- + 'do not open a second wait, read delegate_result or submit a duplicate. A one-minute return is a '
1821
- + 'caller choice, not a documented hard limit, and not every client offers the same yield. This '
1822
- + 'plugin cannot create a background waiter or wake the agent, so a client with only a short yield '
1823
- + 'and no automatic continuation costs one resumed turn per yield window — state that plainly '
1824
- + 'instead of inventing a wake-up. An `attention` answer that carries a `failure` '
2956
+ + 'A one-minute return is a caller choice, not a documented hard limit, and not every client offers '
2957
+ + 'the same yield. This plugin cannot create a background waiter or wake the agent, so a client with '
2958
+ + 'only a short yield and no automatic continuation costs one resumed turn per yield window; there is '
2959
+ + 'no zero-wake guarantee across clients — state that plainly instead of inventing a wake-up. '
2960
+ + 'An `attention` answer that carries a `failure` '
1825
2961
  + 'block means the worker repeated the same failed operation several times while still running: '
1826
- + 'it is a question for the host, sent once, and nothing is cancelled or reconfigured for it. '
2962
+ + 'it is a question for the host, redelivered with the SAME eventId until you acknowledge it via '
2963
+ + '`ackFailureEventId`, and nothing is cancelled or reconfigured for it. '
1827
2964
  + 'If a host serialises tool calls so that this '
1828
2965
  + 'connection is blocked by a long wait, the independently installed `dsh-delegate-control` '
1829
2966
  + 'binary can report or cancel one task from a separate process; it cannot submit, configure or '
1830
2967
  + 'change the switch. '
2968
+ + '`delegate_metrics` is a read-only census of THIS MCP process: tool calls, wait returns and their '
2969
+ + 'reasons, the UTF-8 bytes of the tool text it returned, and applied decisions. It counts the '
2970
+ + 'PROGRAM, not the host model: the host\'s own turns, token usage and cost are reported as '
2971
+ + '`not-integrated` because this process cannot observe them. '
1831
2972
  + 'When a task reaches `ready`/`awaiting-host-review`, finish YOUR review and record it with '
1832
2973
  + 'delegate_review ({ taskId, decision: "accepted" | "changes-requested", note }): that call is the '
1833
2974
  + 'only thing that records host acceptance, and until it is made the task stays unreviewed. '
@@ -1872,7 +3013,16 @@ export function createMcpServer(options) {
1872
3013
  }
1873
3014
  }
1874
3015
 
1875
- return { handle, tools: TOOLS, calls, isInitialized: () => initialized };
3016
+ return {
3017
+ handle,
3018
+ tools: TOOLS,
3019
+ calls,
3020
+ isInitialized: () => initialized,
3021
+ /** The bounded census behind `delegate_metrics`; counts and sizes only. */
3022
+ metrics: () => metrics.snapshot(),
3023
+ /** One line for the exit diagnostics; counts and byte totals, no task content. */
3024
+ diagnosticsLine: () => metrics.diagnosticsLine(),
3025
+ };
1876
3026
  }
1877
3027
 
1878
3028
  /**