dsh-taskbridge 1.4.2 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/CHANGELOG.md +16 -2
  2. package/README.md +8 -7
  3. package/bin/dsh-delegate-mcp.d.ts +20 -3
  4. package/bin/dsh-delegate-mcp.js +15 -0
  5. package/codex/dsh-taskbridge.toml +74 -5
  6. package/docs/INTRODUCTION.md +2 -2
  7. package/docs/INTRODUCTION.zh.md +2 -2
  8. package/docs/codex-integration.md +4 -2
  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/runtime-compatibility.md +4 -4
  15. package/docs/silent-wait.md +84 -0
  16. package/docs/taskbridge-upgrade.md +1 -1
  17. package/docs/worker-permissions.md +154 -17
  18. package/lib/client.js +3 -0
  19. package/package.json +4 -2
  20. package/src/client/api.js +26 -0
  21. package/src/codex/installer.js +15 -0
  22. package/src/config/redact.js +72 -11
  23. package/src/http/execution-plane.js +76 -5
  24. package/src/index.d.ts +285 -0
  25. package/src/index.js +72 -2
  26. package/src/jobs/activity.js +10 -0
  27. package/src/jobs/continuation-identity.js +278 -0
  28. package/src/jobs/engine.js +326 -36
  29. package/src/jobs/history.js +53 -0
  30. package/src/mcp/continuation.js +317 -0
  31. package/src/mcp/metrics.js +343 -0
  32. package/src/mcp/server.js +1079 -47
  33. package/src/mcp/wait.js +266 -74
  34. package/src/review/prompts.js +145 -126
  35. package/src/runtime/agent-runner.js +165 -0
  36. package/src/runtime/permissions.js +192 -2
  37. package/src/runtime/question-call.js +162 -0
  38. package/src/runtime/questions.js +909 -0
  39. package/src/runtime/session-placement.js +78 -5
  40. package/src/version.js +99 -0
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
 
@@ -107,6 +108,10 @@ const TERMINAL_REASONS = new Set(['ready', 'failed', 'cancelled', 'interrupted']
107
108
  /**
108
109
  * Reasons that ask the host to DO something about the task.
109
110
  *
111
+ * `question` is here for the same reason `permission` is: the worker is paused and only
112
+ * the host can release it by answering. Leaving it out would report a question as a
113
+ * non-actionable answer, which is exactly the confusion the acceptance run hit.
114
+ *
110
115
  * `wait-limit` is deliberately absent: it says only that this call's own budget ran
111
116
  * out while nothing changed, so the correct next action is to wait again — not to
112
117
  * review, decide, resubmit or cancel. Reporting it as actionable would invite a host
@@ -115,7 +120,9 @@ const TERMINAL_REASONS = new Set(['ready', 'failed', 'cancelled', 'interrupted']
115
120
  * that a host will or will not surface it to its own model.
116
121
  * @type {ReadonlySet<string>}
117
122
  */
118
- const ACTIONABLE_ANSWER_REASONS = new Set(['attention', 'permission', 'ready', 'failed', 'cancelled', 'interrupted']);
123
+ const ACTIONABLE_ANSWER_REASONS = new Set([
124
+ 'attention', 'permission', 'question', 'ready', 'failed', 'cancelled', 'interrupted',
125
+ ]);
119
126
 
120
127
  /**
121
128
  * Task states a live run can be in.
@@ -183,9 +190,33 @@ export function compactTask(task) {
183
190
  }
184
191
  if (task.reviewPersistence !== undefined) out.reviewPersistence = task.reviewPersistence;
185
192
  // 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;
193
+ // exactly this purpose; they are carried whole rather than re-projected here — EXCEPT
194
+ // the fields a wait must never carry whatever depth they arrive at. An engine (or a
195
+ // fixture) that nested a diff or execution prose inside `activity` would otherwise put
196
+ // evidence on the one answer that is supposed to be cheap, so evidence keys are
197
+ // dropped at any depth.
198
+ if (task.activity !== undefined) out.activity = stripEvidenceFields(task.activity);
199
+ if (task.selfCheck !== undefined) out.selfCheck = stripEvidenceFields(task.selfCheck);
200
+ return out;
201
+ }
202
+
203
+ /** Field names that are evidence, never a wait fact. Dropped wherever they appear. */
204
+ const EVIDENCE_FIELDS = Object.freeze(['diff', 'patchText', 'execution', 'review']);
205
+
206
+ /**
207
+ * Copy a value with every evidence field removed, at any depth.
208
+ * @param {unknown} value - value to copy.
209
+ * @param {number} [depth] - recursion guard.
210
+ * @returns {unknown} the copy without evidence fields.
211
+ */
212
+ export function stripEvidenceFields(value, depth = 0) {
213
+ if (value === null || typeof value !== 'object' || depth > 6) return value;
214
+ if (Array.isArray(value)) return value.map((entry) => stripEvidenceFields(entry, depth + 1));
215
+ const out = {};
216
+ for (const [key, item] of Object.entries(value)) {
217
+ if (EVIDENCE_FIELDS.includes(key)) continue;
218
+ out[key] = stripEvidenceFields(item, depth + 1);
219
+ }
189
220
  return out;
190
221
  }
191
222
 
@@ -353,8 +384,30 @@ export function resolveInterruption(observation) {
353
384
  * this function started", so an injected clock is the only thing that decides how
354
385
  * much time a wait takes. A loop driven by a fake clock therefore measures its own
355
386
  * elapsed time from the wait's real start, which is what a test asserts on.
387
+ *
388
+ * `waitMetrics` is the minimal accounting seam (a "continue waiting after a decision"
389
+ * call must be able to say WHAT it waited for, HOW it returned and HOW MUCH it handed
390
+ * back). It is an injected callback rather than a field on the answer, because the
391
+ * count belongs to the CALL: when the loop throws, there is no answer to put it on. The
392
+ * callback is invoked exactly once, on every exit path (answer, refusal, cancellation),
393
+ * and receives only counts, durations and a reason label — never task content or a size
394
+ * this loop could not know before the answer was bounded and redacted.
395
+ *
396
+ * `skipPermission` is the ONE hook the post-decision continuation needs, and it is
397
+ * deliberately a predicate rather than a second loop: after `allow-once` the engine may
398
+ * still report the settled request until the paused native call resumes, and answering
399
+ * that back to the host would present the commander's own decision as a new question.
400
+ * When the predicate says the observation describes the request already decided, the loop
401
+ * keeps waiting — with the same observation bound, the same early-heartbeat floor and the
402
+ * same deadline as any other turn — so there is exactly ONE wait loop in this program.
403
+ *
404
+ * `skipQuestion` is the same rollover for an ANSWERED question: the just-answered set can
405
+ * still occupy the engine's slot for a moment. A DIFFERENT request id is never skipped, so
406
+ * a genuinely new question returns at once.
356
407
  * @param {object} options - `callExecution`, `taskId`, `waitMs` (deadline), `signal`,
357
- * `observeWaitMs` (per-request bound), `now`, `sleep`.
408
+ * `observeWaitMs` (per-request bound), `now`, `sleep`, optional `waitMetrics`
409
+ * (`(summary) => void`), optional `correlation` facts to echo back, optional
410
+ * `skipPermission` / `skipQuestion` (`(observation) => boolean`).
358
411
  * @returns {Promise<object>} the compact wait answer (without `ok`).
359
412
  */
360
413
  export async function waitForTask(options) {
@@ -365,11 +418,53 @@ export async function waitForTask(options) {
365
418
  const signal = options.signal;
366
419
  const now = options.now ?? (() => Date.now());
367
420
  const sleep = options.sleep ?? ((ms) => new Promise((resolvePromise) => { setTimeout(resolvePromise, ms); }));
421
+ const waitMetrics = typeof options.waitMetrics === 'function' ? options.waitMetrics : null;
422
+ const skipPermission = typeof options.skipPermission === 'function' ? options.skipPermission : null;
423
+ const skipQuestion = typeof options.skipQuestion === 'function' ? options.skipQuestion : null;
368
424
 
369
425
  const startedAt = now();
426
+
427
+ /** The reason the LAST answer carried, for the accounting summary. */
428
+ let returnedReason = null;
429
+ /** Set when the loop ends without producing a task answer (a refusal, or a cancel). */
430
+ let failureCode = null;
431
+
432
+ /**
433
+ * Report this wait's own accounting, exactly once, on every exit path.
434
+ * @param {string | null} endedReason - reason of the last answer, or null when none was produced.
435
+ * @returns {void}
436
+ */
437
+ const report = (endedReason) => {
438
+ if (waitMetrics === null) return;
439
+ const elapsedMs = Math.max(0, now() - startedAt);
440
+ // One flat shape, whether or not there is a correlation: `recordWait` reads
441
+ // `waitId`/`afterDecisionId`/`taskId`/`reason`/`durationMs` from here, so a plain wait
442
+ // and a post-decision wait are counted by exactly the same rule.
443
+ waitMetrics({
444
+ waitId: typeof options.correlation?.waitId === 'string' ? options.correlation.waitId : null,
445
+ afterDecisionId: typeof options.correlation?.afterDecisionId === 'string'
446
+ ? options.correlation.afterDecisionId
447
+ : null,
448
+ taskId: typeof taskId === 'string' ? taskId : null,
449
+ reason: endedReason,
450
+ returnReason: endedReason,
451
+ failureCode,
452
+ durationMs: elapsedMs,
453
+ observedMs,
454
+ observationRequests,
455
+ heartbeatsConsumed: heartbeats,
456
+ interruptedObservations: interruptions,
457
+ // Observations that described the request this call had already decided. Counted so
458
+ // the rollover is auditable; they are consumed internally, never surfaced.
459
+ settledRequestObservations: skipped,
460
+ waitReturns: endedReason === null ? 0 : 1,
461
+ });
462
+ };
370
463
  let observationRequests = 0;
371
464
  let heartbeats = 0;
372
465
  let interruptions = 0;
466
+ let skipped = 0;
467
+ let observedMs = 0;
373
468
  let lastObservation = null;
374
469
 
375
470
  /** Throw the local cancellation, so the caller sees a refusal and not an answer. */
@@ -381,73 +476,141 @@ export async function waitForTask(options) {
381
476
  throw error;
382
477
  };
383
478
 
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
- });
429
- }
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);
479
+ /**
480
+ * Account for one observation's own waited time.
481
+ * @param {object | null | undefined} observation - observation answer.
482
+ * @returns {void}
483
+ */
484
+ const countObserved = (observation) => {
485
+ const waited = observation?.wait?.waitedMs;
486
+ if (Number.isFinite(waited) && waited > 0) observedMs += waited;
487
+ };
488
+
489
+ /**
490
+ * Emit one answer, measuring it exactly once, then report and return it.
491
+ *
492
+ * The measurement is of the ANSWER OBJECT (the data the host receives), serialized
493
+ * once — the envelope a client prints has no bearing on how much data was handed
494
+ * back, and counting it here keeps `returnedBytes` and the published `metrics` in
495
+ * agreement.
496
+ * @param {object} answerValue - the compact answer.
497
+ * @returns {object} the same answer.
498
+ */
499
+ const finish = (answerValue) => {
500
+ returnedReason = typeof answerValue.reason === 'string' ? answerValue.reason : null;
501
+ if (returnedReason === null) failureCode = answerValue.error?.code ?? 'MCP_CALL_FAILED';
502
+ report(returnedReason);
503
+ return answerValue;
504
+ };
505
+
506
+ try {
507
+ for (;;) {
508
+ throwIfCancelled();
509
+ const remaining = deadlineMs - (now() - startedAt);
510
+ if (remaining <= 0) return finish(answer(WAIT_LIMIT_REASON, lastObservation, { resolved: false }));
511
+ // One bounded observation. It never overruns the caller's deadline, so the wait
512
+ // cannot answer later than it said it would.
513
+ const perRequest = Math.min(observeWaitMs, remaining);
514
+ observationRequests += 1;
515
+ let observation;
516
+ try {
517
+ observation = await callExecution('observe', { taskId, waitMs: perRequest }, { signal });
518
+ } catch (error) {
519
+ if (error?.code === 'MCP_REQUEST_CANCELLED') throw error;
520
+ // A refusal is the harness's own answer and is returned as such: an unknown
521
+ // task must read as "no such task", never as an invented completion or as a
522
+ // retry loop against a task that does not exist here.
523
+ return finish({
524
+ ...failureAnswer(error),
525
+ wait: metrics(0),
526
+ });
447
527
  }
448
- continue;
528
+ lastObservation = observation;
529
+ countObserved(observation);
530
+ const reason = reasonOf(observation);
531
+ // The post-decision rollover: the request this call already decided may still occupy
532
+ // the engine's slot until the paused native call resumes. It is not a new question,
533
+ // and it is never answered (or decided) again — the loop simply keeps waiting on the
534
+ // SAME task, under the SAME deadline and the SAME observation bound. A DIFFERENT
535
+ // requestId (or a changed fingerprint) is NOT skipped: it falls through and is
536
+ // answered as a new request that needs its own decision.
537
+ if (reason === 'permission' && skipPermission !== null && skipPermission(observation) === true) {
538
+ skipped += 1;
539
+ // The skip still costs time, so an engine that answers instantly with the settled
540
+ // request cannot turn one call into a request storm (same floor as a heartbeat).
541
+ const elapsed = now() - startedAt;
542
+ const nextDueOffset = (observationRequests + skipped) * EARLY_HEARTBEAT_INTERVAL_MS;
543
+ if (elapsed < nextDueOffset) {
544
+ const pause = Math.min(nextDueOffset - elapsed, remaining);
545
+ if (pause > 0) await sleep(pause);
546
+ }
547
+ continue;
548
+ }
549
+ // The same rollover for a question this call just answered. Only the request that
550
+ // was actually answered is skipped; a new id falls through and is returned at once.
551
+ if (reason === 'question' && skipQuestion !== null && skipQuestion(observation) === true) {
552
+ skipped += 1;
553
+ const elapsed = now() - startedAt;
554
+ const nextDueOffset = (observationRequests + skipped) * EARLY_HEARTBEAT_INTERVAL_MS;
555
+ if (elapsed < nextDueOffset) {
556
+ const pause = Math.min(nextDueOffset - elapsed, remaining);
557
+ if (pause > 0) await sleep(pause);
558
+ }
559
+ continue;
560
+ }
561
+ if (reason === 'interrupted') {
562
+ // An interrupted OBSERVATION is not an interrupted RUN. This branch returns
563
+ // IMMEDIATELY in every case — it never re-issues an observation in the same call.
564
+ //
565
+ // Re-issuing was the defect: when the observer itself is disposed (the engine was
566
+ // torn down, the wait seam broke, the request's own signal aborted) every
567
+ // re-issued observation came back `interrupted` at once, so one `delegate_wait`
568
+ // call became an unbounded burst of HTTP requests. Returning lets the HOST decide
569
+ // to wait again, which is one observation per call at worst.
570
+ //
571
+ // `resolveInterruption` reads the task record, so the answer is the real state:
572
+ // a live task is reported as `interrupted` and NOT terminal, a restart history as
573
+ // terminal, and a settled record as its real outcome (`ready`/`failed`/`cancelled`)
574
+ // so a completed run still reaches review.
575
+ interruptions += 1;
576
+ const resolved = resolveInterruption(observation);
577
+ return finish(answer(resolved.reason, observation, {
578
+ resolved: true,
579
+ resolvedState: resolved.state,
580
+ terminal: resolved.terminal,
581
+ kind: resolved.kind,
582
+ }));
583
+ }
584
+ if (CONTINUING_REASONS.has(reason)) {
585
+ heartbeats += 1;
586
+ // A NORMAL heartbeat has already waited out its own `waitMs` inside the engine,
587
+ // so nothing is slept here. This branch only fires for a heartbeat that came
588
+ // back EARLY (a fake engine, or an engine that answers at once): a per-
589
+ // observation floor keeps such a stream from becoming a request storm. The
590
+ // pause is a slice of that floor, never the remaining deadline — sleeping the
591
+ // remaining budget on the first early heartbeat would turn one observation into
592
+ // the whole wait.
593
+ const elapsed = now() - startedAt;
594
+ // A duration, not an instant: `nextDueOffset` used to be an absolute clock value
595
+ // and subtracting an elapsed duration from it produced a pause of
596
+ // (startedAt + 1s), which swallowed the whole deadline on the first heartbeat.
597
+ const nextDueOffset = observationRequests * EARLY_HEARTBEAT_INTERVAL_MS;
598
+ if (elapsed < nextDueOffset) {
599
+ const pause = Math.min(nextDueOffset - elapsed, remaining);
600
+ if (pause > 0) await sleep(pause);
601
+ }
602
+ continue;
603
+ }
604
+ return finish(answer(reason, observation, { resolved: false }));
449
605
  }
450
- return answer(reason, observation, { resolved: false });
606
+ } catch (error) {
607
+ // A cancellation ends THIS observation and nothing else. The accounting is still
608
+ // reported, so the caller can tell a cancelled call (0 returns) from one that
609
+ // answered — and the error is rethrown untouched, so the refusal path stays the
610
+ // only thing that describes it.
611
+ failureCode = typeof error?.code === 'string' ? error.code : 'MCP_CALL_FAILED';
612
+ report(null);
613
+ throw error;
451
614
  }
452
615
 
453
616
  /**
@@ -522,6 +685,25 @@ export async function waitForTask(options) {
522
685
  out.permissionDecidable = isPermissionDecidable(pendingOperation);
523
686
  }
524
687
  }
688
+ // The question block is carried WHOLE for the same reason the permission block is:
689
+ // the host must be able to ANSWER from this one answer. It carries the questions,
690
+ // their options, the identity a reply is bound to, and no reasoning stream or
691
+ // transcript — `questionAnswerable` states that answering this cannot grant access.
692
+ if (reason === 'question') {
693
+ const block = observation?.question;
694
+ const pendingQuestion = block !== null && typeof block === 'object' && block.questions === undefined
695
+ && block.pending !== undefined
696
+ ? block.pending
697
+ : block;
698
+ if (pendingQuestion !== null && typeof pendingQuestion === 'object') {
699
+ out.question = pendingQuestion;
700
+ // Derived from the ANSWER AS PUBLISHED, by the same rule the bounded projection
701
+ // uses, so a block replaced with an explicit omission is never advertised as
702
+ // answerable. A question is answerable and grants nothing.
703
+ out.questionAnswerable = isQuestionAnswerable(pendingQuestion);
704
+ out.grantsAccess = false;
705
+ }
706
+ }
525
707
  if (observation?.wait !== null && typeof observation?.wait === 'object') out.longPoll = observation.wait;
526
708
  return out;
527
709
  }
@@ -529,10 +711,17 @@ export async function waitForTask(options) {
529
711
  /**
530
712
  * Build the metrics block of one return.
531
713
  *
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".
714
+ * `elapsedMs` is the time this call has spent following the task, which includes
715
+ * the internal observations before the last one. It is separate from
716
+ * `perRequestWaitMs` so a host can tell "the last observation waited 25 s" from "this
717
+ * call has been following the task for twenty minutes". `waitedMs` is the sum the
718
+ * engine itself reported for those observations.
719
+ *
720
+ * Deliberately ABSENT here: the size of the answer. A wait cannot measure its own
721
+ * serialized text before that text exists, and a value the answer carries about itself
722
+ * is self-referential. The MCP server measures the final bounded, redacted text with
723
+ * `Buffer.byteLength` and records it in the process census, which is the only place a
724
+ * byte count means "what the host was actually handed".
536
725
  * @param {number} waitReturns - how many answers the host has received (0 or 1).
537
726
  * @returns {object} metrics with no content and no credentials.
538
727
  */
@@ -544,8 +733,11 @@ export async function waitForTask(options) {
544
733
  // task reached a state. Counted separately from heartbeats so the two are never
545
734
  // read as the same event.
546
735
  interruptedObservations: interruptions,
736
+ // Observations that described a permission request this call had already decided.
737
+ settledRequestObservations: skipped,
547
738
  waitReturns,
548
739
  elapsedMs: Math.max(0, now() - startedAt),
740
+ waitedMs: observedMs,
549
741
  deadlineMs,
550
742
  perRequestWaitMs: observeWaitMs,
551
743
  };