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/wait.js CHANGED
@@ -40,6 +40,7 @@ import {
40
40
  OBSERVE_WAIT_MS,
41
41
  WAIT_LIMIT_REASON,
42
42
  isPermissionDecidable,
43
+ isQuestionAnswerable,
43
44
  } from './server.js';
44
45
  import { REPEATED_FAILURE_KIND } from '../jobs/diagnostics.js';
45
46
 
@@ -96,6 +97,11 @@ const TASK_FIELDS = Object.freeze([
96
97
  'selfApproved',
97
98
  'hostAcceptance',
98
99
  'cancelledBy',
100
+ // The Agent Teams decision and its outcome, so a wait answer alone says whether teams
101
+ // are on for this run (`applied`/`enabled`) or why they are not (`reason`) without
102
+ // reading the full result. Four booleans plus a bounded reason — no team content.
103
+ 'agentTeams',
104
+ 'team',
99
105
  ]);
100
106
 
101
107
  /**
@@ -107,6 +113,10 @@ const TERMINAL_REASONS = new Set(['ready', 'failed', 'cancelled', 'interrupted']
107
113
  /**
108
114
  * Reasons that ask the host to DO something about the task.
109
115
  *
116
+ * `question` is here for the same reason `permission` is: the worker is paused and only
117
+ * the host can release it by answering. Leaving it out would report a question as a
118
+ * non-actionable answer, which is exactly the confusion the acceptance run hit.
119
+ *
110
120
  * `wait-limit` is deliberately absent: it says only that this call's own budget ran
111
121
  * out while nothing changed, so the correct next action is to wait again — not to
112
122
  * review, decide, resubmit or cancel. Reporting it as actionable would invite a host
@@ -115,7 +125,9 @@ const TERMINAL_REASONS = new Set(['ready', 'failed', 'cancelled', 'interrupted']
115
125
  * that a host will or will not surface it to its own model.
116
126
  * @type {ReadonlySet<string>}
117
127
  */
118
- const ACTIONABLE_ANSWER_REASONS = new Set(['attention', 'permission', 'ready', 'failed', 'cancelled', 'interrupted']);
128
+ const ACTIONABLE_ANSWER_REASONS = new Set([
129
+ 'attention', 'permission', 'question', 'ready', 'failed', 'cancelled', 'interrupted',
130
+ ]);
119
131
 
120
132
  /**
121
133
  * Task states a live run can be in.
@@ -183,9 +195,33 @@ export function compactTask(task) {
183
195
  }
184
196
  if (task.reviewPersistence !== undefined) out.reviewPersistence = task.reviewPersistence;
185
197
  // Activity and self-check are small, bounded summaries the engine produced for
186
- // exactly this purpose; they are carried whole rather than re-projected here.
187
- if (task.activity !== undefined) out.activity = task.activity;
188
- if (task.selfCheck !== undefined) out.selfCheck = task.selfCheck;
198
+ // exactly this purpose; they are carried whole rather than re-projected here — EXCEPT
199
+ // the fields a wait must never carry whatever depth they arrive at. An engine (or a
200
+ // fixture) that nested a diff or execution prose inside `activity` would otherwise put
201
+ // evidence on the one answer that is supposed to be cheap, so evidence keys are
202
+ // dropped at any depth.
203
+ if (task.activity !== undefined) out.activity = stripEvidenceFields(task.activity);
204
+ if (task.selfCheck !== undefined) out.selfCheck = stripEvidenceFields(task.selfCheck);
205
+ return out;
206
+ }
207
+
208
+ /** Field names that are evidence, never a wait fact. Dropped wherever they appear. */
209
+ const EVIDENCE_FIELDS = Object.freeze(['diff', 'patchText', 'execution', 'review']);
210
+
211
+ /**
212
+ * Copy a value with every evidence field removed, at any depth.
213
+ * @param {unknown} value - value to copy.
214
+ * @param {number} [depth] - recursion guard.
215
+ * @returns {unknown} the copy without evidence fields.
216
+ */
217
+ export function stripEvidenceFields(value, depth = 0) {
218
+ if (value === null || typeof value !== 'object' || depth > 6) return value;
219
+ if (Array.isArray(value)) return value.map((entry) => stripEvidenceFields(entry, depth + 1));
220
+ const out = {};
221
+ for (const [key, item] of Object.entries(value)) {
222
+ if (EVIDENCE_FIELDS.includes(key)) continue;
223
+ out[key] = stripEvidenceFields(item, depth + 1);
224
+ }
189
225
  return out;
190
226
  }
191
227
 
@@ -353,8 +389,38 @@ export function resolveInterruption(observation) {
353
389
  * this function started", so an injected clock is the only thing that decides how
354
390
  * much time a wait takes. A loop driven by a fake clock therefore measures its own
355
391
  * elapsed time from the wait's real start, which is what a test asserts on.
392
+ *
393
+ * `waitMetrics` is the minimal accounting seam (a "continue waiting after a decision"
394
+ * call must be able to say WHAT it waited for, HOW it returned and HOW MUCH it handed
395
+ * back). It is an injected callback rather than a field on the answer, because the
396
+ * count belongs to the CALL: when the loop throws, there is no answer to put it on. The
397
+ * callback is invoked exactly once, on every exit path (answer, refusal, cancellation),
398
+ * and receives only counts, durations and a reason label — never task content or a size
399
+ * this loop could not know before the answer was bounded and redacted.
400
+ *
401
+ * `skipPermission` is the ONE hook the post-decision continuation needs, and it is
402
+ * deliberately a predicate rather than a second loop: after `allow-once` the engine may
403
+ * still report the settled request until the paused native call resumes, and answering
404
+ * that back to the host would present the commander's own decision as a new question.
405
+ * When the predicate says the observation describes the request already decided, the loop
406
+ * keeps waiting — with the same observation bound, the same early-heartbeat floor and the
407
+ * same deadline as any other turn — so there is exactly ONE wait loop in this program.
408
+ *
409
+ * `skipQuestion` is the same rollover for an ANSWERED question: the just-answered set can
410
+ * still occupy the engine's slot for a moment. A DIFFERENT request id is never skipped, so
411
+ * a genuinely new question returns at once.
412
+ *
413
+ * `ackFailureEventId` is the receiver's acknowledgment of ONE repeated-failure reminder
414
+ * observed earlier (by its `eventId`). It rides the FIRST internal observation; the
415
+ * engine's verdict (`failureAck`) is frozen at the first report and attached to every
416
+ * answer and every thrown refusal of this call, so the host always learns whether its
417
+ * acknowledgment landed. After a verdict exists the loop stops carrying the ack, so a
418
+ * disposed monitor or a settled task cannot answer a stale ack and overwrite the fact.
356
419
  * @param {object} options - `callExecution`, `taskId`, `waitMs` (deadline), `signal`,
357
- * `observeWaitMs` (per-request bound), `now`, `sleep`.
420
+ * `observeWaitMs` (per-request bound), `now`, `sleep`, optional `waitMetrics`
421
+ * (`(summary) => void`), optional `correlation` facts to echo back, optional
422
+ * `skipPermission` / `skipQuestion` (`(observation) => boolean`), optional
423
+ * `ackFailureEventId` (string).
358
424
  * @returns {Promise<object>} the compact wait answer (without `ok`).
359
425
  */
360
426
  export async function waitForTask(options) {
@@ -365,11 +431,73 @@ export async function waitForTask(options) {
365
431
  const signal = options.signal;
366
432
  const now = options.now ?? (() => Date.now());
367
433
  const sleep = options.sleep ?? ((ms) => new Promise((resolvePromise) => { setTimeout(resolvePromise, ms); }));
434
+ const waitMetrics = typeof options.waitMetrics === 'function' ? options.waitMetrics : null;
435
+ const skipPermission = typeof options.skipPermission === 'function' ? options.skipPermission : null;
436
+ const skipQuestion = typeof options.skipQuestion === 'function' ? options.skipQuestion : null;
437
+ // The receiver's ack, bound to the exact reminder it observed. Carried only until
438
+ // a verdict exists: the FIRST observation applies it, later observations of this
439
+ // call carry no ack field, and only a transport retry that has never seen a
440
+ // verdict still carries the same id.
441
+ const ackFailureEventId = typeof options.ackFailureEventId === 'string' && options.ackFailureEventId !== ''
442
+ ? options.ackFailureEventId
443
+ : null;
444
+ /**
445
+ * The ack verdict this call has learned, or `undefined` while none was reported.
446
+ *
447
+ * Once a verdict EXISTS it is frozen: the loop stops carrying the ack on later
448
+ * observations (so a disposed monitor or a settled task cannot answer a stale
449
+ * ack with `unknown-event` and overwrite a confirmed fact), and the stored
450
+ * verdict — confirmed, refused or uncertain, exactly as the engine stated it —
451
+ * is attached to every answer and every thrown error.
452
+ * @type {object | undefined}
453
+ */
454
+ let ackFailureResult;
455
+ /** Whether the caller asked this call to acknowledge at all. */
456
+ const ackRequested = ackFailureEventId !== null;
368
457
 
369
458
  const startedAt = now();
459
+
460
+ /** The reason the LAST answer carried, for the accounting summary. */
461
+ let returnedReason = null;
462
+ /** Set when the loop ends without producing a task answer (a refusal, or a cancel). */
463
+ let failureCode = null;
464
+
465
+ /**
466
+ * Report this wait's own accounting, exactly once, on every exit path.
467
+ * @param {string | null} endedReason - reason of the last answer, or null when none was produced.
468
+ * @returns {void}
469
+ */
470
+ const report = (endedReason) => {
471
+ if (waitMetrics === null) return;
472
+ const elapsedMs = Math.max(0, now() - startedAt);
473
+ // One flat shape, whether or not there is a correlation: `recordWait` reads
474
+ // `waitId`/`afterDecisionId`/`taskId`/`reason`/`durationMs` from here, so a plain wait
475
+ // and a post-decision wait are counted by exactly the same rule.
476
+ waitMetrics({
477
+ waitId: typeof options.correlation?.waitId === 'string' ? options.correlation.waitId : null,
478
+ afterDecisionId: typeof options.correlation?.afterDecisionId === 'string'
479
+ ? options.correlation.afterDecisionId
480
+ : null,
481
+ taskId: typeof taskId === 'string' ? taskId : null,
482
+ reason: endedReason,
483
+ returnReason: endedReason,
484
+ failureCode,
485
+ durationMs: elapsedMs,
486
+ observedMs,
487
+ observationRequests,
488
+ heartbeatsConsumed: heartbeats,
489
+ interruptedObservations: interruptions,
490
+ // Observations that described the request this call had already decided. Counted so
491
+ // the rollover is auditable; they are consumed internally, never surfaced.
492
+ settledRequestObservations: skipped,
493
+ waitReturns: endedReason === null ? 0 : 1,
494
+ });
495
+ };
370
496
  let observationRequests = 0;
371
497
  let heartbeats = 0;
372
498
  let interruptions = 0;
499
+ let skipped = 0;
500
+ let observedMs = 0;
373
501
  let lastObservation = null;
374
502
 
375
503
  /** Throw the local cancellation, so the caller sees a refusal and not an answer. */
@@ -381,73 +509,181 @@ export async function waitForTask(options) {
381
509
  throw error;
382
510
  };
383
511
 
384
- for (;;) {
385
- throwIfCancelled();
386
- const remaining = deadlineMs - (now() - startedAt);
387
- if (remaining <= 0) return answer(WAIT_LIMIT_REASON, lastObservation, { resolved: false });
388
- // One bounded observation. It never overruns the caller's deadline, so the wait
389
- // cannot answer later than it said it would.
390
- const perRequest = Math.min(observeWaitMs, remaining);
391
- observationRequests += 1;
392
- let observation;
393
- try {
394
- observation = await callExecution('observe', { taskId, waitMs: perRequest }, { signal });
395
- } catch (error) {
396
- if (error?.code === 'MCP_REQUEST_CANCELLED') throw error;
397
- // A refusal is the harness's own answer and is returned as such: an unknown
398
- // task must read as "no such task", never as an invented completion or as a
399
- // retry loop against a task that does not exist here.
400
- return {
401
- ...failureAnswer(error),
402
- wait: metrics(0),
403
- };
404
- }
405
- lastObservation = observation;
406
- const reason = reasonOf(observation);
407
- if (reason === 'interrupted') {
408
- // An interrupted OBSERVATION is not an interrupted RUN. This branch returns
409
- // IMMEDIATELY in every case — it never re-issues an observation in the same call.
410
- //
411
- // Re-issuing was the defect: when the observer itself is disposed (the engine was
412
- // torn down, the wait seam broke, the request's own signal aborted) every
413
- // re-issued observation came back `interrupted` at once, so one `delegate_wait`
414
- // call became an unbounded burst of HTTP requests. Returning lets the HOST decide
415
- // to wait again, which is one observation per call at worst.
416
- //
417
- // `resolveInterruption` reads the task record, so the answer is the real state:
418
- // a live task is reported as `interrupted` and NOT terminal, a restart history as
419
- // terminal, and a settled record as its real outcome (`ready`/`failed`/`cancelled`)
420
- // so a completed run still reaches review.
421
- interruptions += 1;
422
- const resolved = resolveInterruption(observation);
423
- return answer(resolved.reason, observation, {
424
- resolved: true,
425
- resolvedState: resolved.state,
426
- terminal: resolved.terminal,
427
- kind: resolved.kind,
428
- });
512
+ /**
513
+ * Account for one observation's own waited time.
514
+ * @param {object | null | undefined} observation - observation answer.
515
+ * @returns {void}
516
+ */
517
+ const countObserved = (observation) => {
518
+ const waited = observation?.wait?.waitedMs;
519
+ if (Number.isFinite(waited) && waited > 0) observedMs += waited;
520
+ };
521
+
522
+ /**
523
+ * Emit one answer, measuring it exactly once, then report and return it.
524
+ *
525
+ * The measurement is of the ANSWER OBJECT (the data the host receives), serialized
526
+ * once — the envelope a client prints has no bearing on how much data was handed
527
+ * back, and counting it here keeps `returnedBytes` and the published `metrics` in
528
+ * agreement. The engine's ack verdict (when this call carried an
529
+ * `ackFailureEventId` and an observation reported one) is attached here so EVERY
530
+ * answer shape — attention, wait-limit, ready, an interruption resolution —
531
+ * carries the same fact the host must see.
532
+ * @param {object} answerValue - the compact answer.
533
+ * @returns {object} the same answer.
534
+ */
535
+ const finish = (answerValue) => {
536
+ if (ackFailureResult !== undefined && answerValue !== null && typeof answerValue === 'object') {
537
+ answerValue.failureAck = ackFailureResult;
429
538
  }
430
- if (CONTINUING_REASONS.has(reason)) {
431
- heartbeats += 1;
432
- // A NORMAL heartbeat has already waited out its own `waitMs` inside the engine,
433
- // so nothing is slept here. This branch only fires for a heartbeat that came
434
- // back EARLY (a fake engine, or an engine that answers at once): a per-
435
- // observation floor keeps such a stream from becoming a request storm. The
436
- // pause is a slice of that floor, never the remaining deadline — sleeping the
437
- // remaining budget on the first early heartbeat would turn one observation into
438
- // the whole wait.
439
- const elapsed = now() - startedAt;
440
- // A duration, not an instant: `nextDueOffset` used to be an absolute clock value
441
- // and subtracting an elapsed duration from it produced a pause of
442
- // (startedAt + 1s), which swallowed the whole deadline on the first heartbeat.
443
- const nextDueOffset = observationRequests * EARLY_HEARTBEAT_INTERVAL_MS;
444
- if (elapsed < nextDueOffset) {
445
- const pause = Math.min(nextDueOffset - elapsed, remaining);
446
- if (pause > 0) await sleep(pause);
539
+ returnedReason = typeof answerValue.reason === 'string' ? answerValue.reason : null;
540
+ if (returnedReason === null) failureCode = answerValue.error?.code ?? 'MCP_CALL_FAILED';
541
+ report(returnedReason);
542
+ return answerValue;
543
+ };
544
+
545
+ try {
546
+ for (;;) {
547
+ throwIfCancelled();
548
+ const remaining = deadlineMs - (now() - startedAt);
549
+ if (remaining <= 0) return finish(answer(WAIT_LIMIT_REASON, lastObservation, { resolved: false }));
550
+ // One bounded observation. It never overruns the caller's deadline, so the wait
551
+ // cannot answer later than it said it would.
552
+ const perRequest = Math.min(observeWaitMs, remaining);
553
+ observationRequests += 1;
554
+ let observation;
555
+ try {
556
+ // The ack rides only until a verdict exists. Once the engine has reported
557
+ // one (confirmed, refused, or superseded), later observations in this call
558
+ // carry NO ack field: re-acking a settled/disposed monitor would answer
559
+ // `unknown-event` and overwrite an already-established fact with a worse
560
+ // one. Only a TRANSPORT retry that has never seen a verdict still carries
561
+ // the same id — that is the recovery path the redelivery exists for.
562
+ observation = await callExecution('observe', {
563
+ taskId,
564
+ waitMs: perRequest,
565
+ ...(ackFailureEventId === null || ackFailureResult !== undefined
566
+ ? {}
567
+ : { ackFailureEventId }),
568
+ }, { signal });
569
+ } catch (error) {
570
+ if (error?.code === 'MCP_REQUEST_CANCELLED') throw error;
571
+ // A refusal is the harness's own answer and is returned as such: an unknown
572
+ // task must read as "no such task", never as an invented completion or as a
573
+ // retry loop against a task that does not exist here. The ack verdict (when
574
+ // one exists) rides at the TOP LEVEL of this answer, exactly where the
575
+ // server's waitAnswer reads it.
576
+ return finish({
577
+ ...failureAnswer(error),
578
+ ...(ackFailureResult === undefined ? {} : { failureAck: ackFailureResult }),
579
+ wait: metrics(0),
580
+ });
581
+ }
582
+ lastObservation = observation;
583
+ countObserved(observation);
584
+ // The engine's ack verdict for THIS call's acknowledgment. The FIRST reported
585
+ // verdict is frozen — later observations carry no ack field (see above), so a
586
+ // disposed monitor or a settled task cannot answer a stale ack and overwrite
587
+ // a confirmed fact with `unknown-event`. Kept verbatim, never rewritten. The
588
+ // assignment is explicitly gated on `undefined` (not on "truthy"), so a later
589
+ // observation that unexpectedly carried SOME ack block could still not replace
590
+ // a verdict this call already holds.
591
+ if (ackFailureResult === undefined && observation?.failureAck !== undefined && observation?.failureAck !== null) {
592
+ ackFailureResult = observation.failureAck;
447
593
  }
448
- continue;
594
+ const reason = reasonOf(observation);
595
+ // The post-decision rollover: the request this call already decided may still occupy
596
+ // the engine's slot until the paused native call resumes. It is not a new question,
597
+ // and it is never answered (or decided) again — the loop simply keeps waiting on the
598
+ // SAME task, under the SAME deadline and the SAME observation bound. A DIFFERENT
599
+ // requestId (or a changed fingerprint) is NOT skipped: it falls through and is
600
+ // answered as a new request that needs its own decision.
601
+ if (reason === 'permission' && skipPermission !== null && skipPermission(observation) === true) {
602
+ skipped += 1;
603
+ // The skip still costs time, so an engine that answers instantly with the settled
604
+ // request cannot turn one call into a request storm (same floor as a heartbeat).
605
+ const elapsed = now() - startedAt;
606
+ const nextDueOffset = (observationRequests + skipped) * EARLY_HEARTBEAT_INTERVAL_MS;
607
+ if (elapsed < nextDueOffset) {
608
+ const pause = Math.min(nextDueOffset - elapsed, remaining);
609
+ if (pause > 0) await sleep(pause);
610
+ }
611
+ continue;
612
+ }
613
+ // The same rollover for a question this call just answered. Only the request that
614
+ // was actually answered is skipped; a new id falls through and is returned at once.
615
+ if (reason === 'question' && skipQuestion !== null && skipQuestion(observation) === true) {
616
+ skipped += 1;
617
+ const elapsed = now() - startedAt;
618
+ const nextDueOffset = (observationRequests + skipped) * EARLY_HEARTBEAT_INTERVAL_MS;
619
+ if (elapsed < nextDueOffset) {
620
+ const pause = Math.min(nextDueOffset - elapsed, remaining);
621
+ if (pause > 0) await sleep(pause);
622
+ }
623
+ continue;
624
+ }
625
+ if (reason === 'interrupted') {
626
+ // An interrupted OBSERVATION is not an interrupted RUN. This branch returns
627
+ // IMMEDIATELY in every case — it never re-issues an observation in the same call.
628
+ //
629
+ // Re-issuing was the defect: when the observer itself is disposed (the engine was
630
+ // torn down, the wait seam broke, the request's own signal aborted) every
631
+ // re-issued observation came back `interrupted` at once, so one `delegate_wait`
632
+ // call became an unbounded burst of HTTP requests. Returning lets the HOST decide
633
+ // to wait again, which is one observation per call at worst.
634
+ //
635
+ // `resolveInterruption` reads the task record, so the answer is the real state:
636
+ // a live task is reported as `interrupted` and NOT terminal, a restart history as
637
+ // terminal, and a settled record as its real outcome (`ready`/`failed`/`cancelled`)
638
+ // so a completed run still reaches review.
639
+ interruptions += 1;
640
+ const resolved = resolveInterruption(observation);
641
+ return finish(answer(resolved.reason, observation, {
642
+ resolved: true,
643
+ resolvedState: resolved.state,
644
+ terminal: resolved.terminal,
645
+ kind: resolved.kind,
646
+ }));
647
+ }
648
+ if (CONTINUING_REASONS.has(reason)) {
649
+ heartbeats += 1;
650
+ // A NORMAL heartbeat has already waited out its own `waitMs` inside the engine,
651
+ // so nothing is slept here. This branch only fires for a heartbeat that came
652
+ // back EARLY (a fake engine, or an engine that answers at once): a per-
653
+ // observation floor keeps such a stream from becoming a request storm. The
654
+ // pause is a slice of that floor, never the remaining deadline — sleeping the
655
+ // remaining budget on the first early heartbeat would turn one observation into
656
+ // the whole wait.
657
+ const elapsed = now() - startedAt;
658
+ // A duration, not an instant: `nextDueOffset` used to be an absolute clock value
659
+ // and subtracting an elapsed duration from it produced a pause of
660
+ // (startedAt + 1s), which swallowed the whole deadline on the first heartbeat.
661
+ const nextDueOffset = observationRequests * EARLY_HEARTBEAT_INTERVAL_MS;
662
+ if (elapsed < nextDueOffset) {
663
+ const pause = Math.min(nextDueOffset - elapsed, remaining);
664
+ if (pause > 0) await sleep(pause);
665
+ }
666
+ continue;
667
+ }
668
+ return finish(answer(reason, observation, { resolved: false }));
669
+ }
670
+ } catch (error) {
671
+ // A cancellation ends THIS observation and nothing else. The accounting is still
672
+ // reported, so the caller can tell a cancelled call (0 returns) from one that
673
+ // answered — and the error is rethrown untouched, so the refusal path stays the
674
+ // only thing that describes it.
675
+ //
676
+ // An ack verdict this call has already learned is attached to the rethrown error
677
+ // as `failureAck`: a wait that errors or is cancelled after a successful (or
678
+ // refused) acknowledgment still hands the host that fact, instead of leaving it
679
+ // to guess whether the ack landed. It is carried exactly as the engine stated it
680
+ // — never rewritten into a success.
681
+ if (ackFailureResult !== undefined && error !== null && typeof error === 'object') {
682
+ error.failureAck = ackFailureResult;
449
683
  }
450
- return answer(reason, observation, { resolved: false });
684
+ failureCode = typeof error?.code === 'string' ? error.code : 'MCP_CALL_FAILED';
685
+ report(null);
686
+ throw error;
451
687
  }
452
688
 
453
689
  /**
@@ -522,6 +758,25 @@ export async function waitForTask(options) {
522
758
  out.permissionDecidable = isPermissionDecidable(pendingOperation);
523
759
  }
524
760
  }
761
+ // The question block is carried WHOLE for the same reason the permission block is:
762
+ // the host must be able to ANSWER from this one answer. It carries the questions,
763
+ // their options, the identity a reply is bound to, and no reasoning stream or
764
+ // transcript — `questionAnswerable` states that answering this cannot grant access.
765
+ if (reason === 'question') {
766
+ const block = observation?.question;
767
+ const pendingQuestion = block !== null && typeof block === 'object' && block.questions === undefined
768
+ && block.pending !== undefined
769
+ ? block.pending
770
+ : block;
771
+ if (pendingQuestion !== null && typeof pendingQuestion === 'object') {
772
+ out.question = pendingQuestion;
773
+ // Derived from the ANSWER AS PUBLISHED, by the same rule the bounded projection
774
+ // uses, so a block replaced with an explicit omission is never advertised as
775
+ // answerable. A question is answerable and grants nothing.
776
+ out.questionAnswerable = isQuestionAnswerable(pendingQuestion);
777
+ out.grantsAccess = false;
778
+ }
779
+ }
525
780
  if (observation?.wait !== null && typeof observation?.wait === 'object') out.longPoll = observation.wait;
526
781
  return out;
527
782
  }
@@ -529,10 +784,17 @@ export async function waitForTask(options) {
529
784
  /**
530
785
  * Build the metrics block of one return.
531
786
  *
532
- * `totalWaitMs` is the time this call has spent following the task, which includes
533
- * the internal observations before the last one. It is separate from `elapsedMs`
534
- * so a host can tell "the last observation waited 25 s" from "this call has been
535
- * following the task for twenty minutes".
787
+ * `elapsedMs` is the time this call has spent following the task, which includes
788
+ * the internal observations before the last one. It is separate from
789
+ * `perRequestWaitMs` so a host can tell "the last observation waited 25 s" from "this
790
+ * call has been following the task for twenty minutes". `waitedMs` is the sum the
791
+ * engine itself reported for those observations.
792
+ *
793
+ * Deliberately ABSENT here: the size of the answer. A wait cannot measure its own
794
+ * serialized text before that text exists, and a value the answer carries about itself
795
+ * is self-referential. The MCP server measures the final bounded, redacted text with
796
+ * `Buffer.byteLength` and records it in the process census, which is the only place a
797
+ * byte count means "what the host was actually handed".
536
798
  * @param {number} waitReturns - how many answers the host has received (0 or 1).
537
799
  * @returns {object} metrics with no content and no credentials.
538
800
  */
@@ -544,8 +806,11 @@ export async function waitForTask(options) {
544
806
  // task reached a state. Counted separately from heartbeats so the two are never
545
807
  // read as the same event.
546
808
  interruptedObservations: interruptions,
809
+ // Observations that described a permission request this call had already decided.
810
+ settledRequestObservations: skipped,
547
811
  waitReturns,
548
812
  elapsedMs: Math.max(0, now() - startedAt),
813
+ waitedMs: observedMs,
549
814
  deadlineMs,
550
815
  perRequestWaitMs: observeWaitMs,
551
816
  };