dsh-taskbridge 1.5.0 → 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.
package/src/mcp/server.js CHANGED
@@ -321,6 +321,17 @@ export const TOOLS = Object.freeze([
321
321
  description: 'Optional per-task overrides (model/effort/timeout). Validated by the harness.',
322
322
  additionalProperties: true,
323
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
+ },
324
335
  continueFromTaskId: {
325
336
  type: 'string',
326
337
  description: 'Task id of the earlier delegated task this submission continues. '
@@ -387,8 +398,10 @@ export const TOOLS = Object.freeze([
387
398
  + 'the configured inactivity threshold, ten minutes by default, so it may be stuck), `ready` (the run '
388
399
  + 'ended and is awaiting host review), `failed`, `cancelled` or `interrupted`. '
389
400
  + 'An `attention` answer may instead carry a `failure` block (kind `repeated-tool-failure`, with '
390
- + 'toolName/failureCode/consecutive): the worker repeated the SAME operation and failed the same way '
391
- + '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 '
392
405
  + 'or reconfigured automatically. '
393
406
  + '`reason: "wait-limit"` means only that this call\u2019s own budget ran out with nothing changed: it is '
394
407
  + 'reported with `actionable: false` and `terminal: false`. Call delegate_wait again with the same '
@@ -431,9 +444,15 @@ export const TOOLS = Object.freeze([
431
444
  // concurrency-aware client this call may be held for an hour without being a
432
445
  // mutating operation. A serialising host still ignores it; the independent
433
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.
434
453
  annotations: Object.freeze({
435
454
  title: 'Wait for a task to need you',
436
- readOnlyHint: true,
455
+ readOnlyHint: false,
437
456
  destructiveHint: false,
438
457
  idempotentHint: true,
439
458
  openWorldHint: false,
@@ -451,6 +470,17 @@ export const TOOLS = Object.freeze([
451
470
  + 'extend a wait beyond 3600. A returned `wait-limit` with `actionable: false` means this '
452
471
  + 'deadline was reached, not that the task stalled or ended.',
453
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
+ },
454
484
  },
455
485
  required: ['taskId'],
456
486
  additionalProperties: false,
@@ -945,6 +975,12 @@ function validateArgs(tool, args) {
945
975
  } else if (typeof declared.maxLength === 'number' && field.length > declared.maxLength) {
946
976
  throw new McpError('MCP_ARGUMENT_RANGE', `${tool.name}.${key} must be at most ${declared.maxLength} characters`);
947
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
+ }
948
984
  out[key] = field;
949
985
  } else if (declared.type === 'boolean') {
950
986
  // Strict: a model that sends the string "true" gets a refusal naming the
@@ -1355,6 +1391,11 @@ function pathsFor(value) {
1355
1391
  */
1356
1392
  function projectWithStage(value, stage, collect) {
1357
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;
1358
1399
  for (const key of ['decisionReceipt', 'answerReceipt']) {
1359
1400
  const receipt = minimalReceipt(projected[key]);
1360
1401
  if (receipt !== null) {
@@ -1464,7 +1505,10 @@ function skeletonize(task, path, cap, collect) {
1464
1505
  const pick = (key) => (key in task ? boundValue(task[key], `${path}.${key}`, cap, collect) : undefined);
1465
1506
  const out = {};
1466
1507
  for (const key of ['taskId', 'state', 'phase', 'route', 'reviewRoute', 'reviewRouteError', 'execution', 'error',
1467
- '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']) {
1468
1512
  const value = pick(key);
1469
1513
  if (value === undefined) continue;
1470
1514
  if (key === 'execution' && value !== null && typeof value === 'object') {
@@ -1915,6 +1959,11 @@ function boundedJson(value) {
1915
1959
  if (refusedReceipt !== null) identity.decisionReceipt = refusedReceipt;
1916
1960
  const refusedAnswer = minimalReceipt(value?.answerReceipt);
1917
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;
1918
1967
  return refuseResult(
1919
1968
  'MCP_RESULT_OVER_BUDGET',
1920
1969
  'the critical fields alone exceed the tool-text bound, so no usable projection could be produced',
@@ -1922,6 +1971,31 @@ function boundedJson(value) {
1922
1971
  );
1923
1972
  }
1924
1973
 
1974
+ /**
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
+
1925
1999
  /**
1926
2000
  * The minimum facts a decision receipt must keep under ANY bound.
1927
2001
  *
@@ -1979,6 +2053,13 @@ function rescueQuestion(value, fullTextChars) {
1979
2053
  const receipt = minimalReceipt(value[key]);
1980
2054
  if (receipt !== null) payload[key] = receipt;
1981
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
+ }
1982
2063
  const redacted = redactDeepStrings(payload);
1983
2064
  const pretty = JSON.stringify(redacted, null, 2);
1984
2065
  if (pretty.length <= MAX_TOOL_TEXT_CHARS) return { text: pretty, isError: false };
@@ -2045,7 +2126,11 @@ function permissionRescue(value, fullTextChars) {
2045
2126
  }
2046
2127
  const receipt = minimalReceipt(value?.decisionReceipt);
2047
2128
  const answerReceipt = minimalReceipt(value?.answerReceipt);
2048
- if (entries.length === 0 && receipt === null && answerReceipt === null) return null;
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;
2049
2134
  return (cap) => {
2050
2135
  const records = [];
2051
2136
  const render = (entry) => {
@@ -2068,13 +2153,20 @@ function permissionRescue(value, fullTextChars) {
2068
2153
  }
2069
2154
  return pending;
2070
2155
  };
2071
- /** Attach the receipt, with the omission stated where it happened. */
2156
+ /** Attach the receipt(s) and the failure acknowledgment, with the omission stated where it happened. */
2072
2157
  const withReceipt = (payload) => {
2073
2158
  for (const [key, item] of [['decisionReceipt', receipt], ['answerReceipt', answerReceipt]]) {
2074
2159
  if (item === null) continue;
2075
2160
  records.push({ path: key, field: 'receipt', detail: 'identity and application facts retained; bulky evidence omitted' });
2076
2161
  payload[key] = item;
2077
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
+ }
2078
2170
  return payload;
2079
2171
  };
2080
2172
  if (entries.length === 1 && entries[0].bare === true) {
@@ -2351,9 +2443,19 @@ export function createMcpServer(options) {
2351
2443
  const details = error instanceof McpError && error.details !== null && error.details !== undefined
2352
2444
  ? error.details
2353
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;
2354
2456
  producedText = boundedJson({
2355
2457
  ok: false,
2356
- error: { code, message, ...(details === undefined ? {} : { details }) },
2458
+ error: { code, message, ...(boundedDetails === undefined ? {} : { details: boundedDetails }) },
2357
2459
  }).text;
2358
2460
  return {
2359
2461
  content: [{ type: 'text', text: producedText }],
@@ -2380,6 +2482,12 @@ export function createMcpServer(options) {
2380
2482
  */
2381
2483
  async function waitAnswer(payload, context, options = {}) {
2382
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;
2383
2491
  const correlation = {
2384
2492
  waitId: nextCorrelationId('wait'),
2385
2493
  afterDecisionId: options.afterDecisionId ?? null,
@@ -2394,6 +2502,7 @@ export function createMcpServer(options) {
2394
2502
  correlation,
2395
2503
  skipPermission: options.skipPermission,
2396
2504
  skipQuestion: options.skipQuestion,
2505
+ ...(ackFailureEventId === null ? {} : { ackFailureEventId }),
2397
2506
  // The loop reports its own accounting once, on every exit path, so a wait that
2398
2507
  // threw is counted too. Counting lives HERE, not in the answer: a thrown call has
2399
2508
  // no answer to carry a count.
@@ -2402,7 +2511,15 @@ export function createMcpServer(options) {
2402
2511
  if (result?.error !== undefined) {
2403
2512
  // The loop could not obtain an observation at all. That is a refusal with the
2404
2513
  // harness's own code, raised so the standard refusal path shapes it — never an
2405
- // 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
+ }
2406
2523
  throw new McpError(result.error.code, result.error.message);
2407
2524
  }
2408
2525
  return { ok: true, ...result };
@@ -2842,7 +2959,8 @@ export function createMcpServer(options) {
2842
2959
  + 'no zero-wake guarantee across clients — state that plainly instead of inventing a wake-up. '
2843
2960
  + 'An `attention` answer that carries a `failure` '
2844
2961
  + 'block means the worker repeated the same failed operation several times while still running: '
2845
- + '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. '
2846
2964
  + 'If a host serialises tool calls so that this '
2847
2965
  + 'connection is blocked by a long wait, the independently installed `dsh-delegate-control` '
2848
2966
  + 'binary can report or cancel one task from a separate process; it cannot submit, configure or '
package/src/mcp/wait.js CHANGED
@@ -97,6 +97,11 @@ const TASK_FIELDS = Object.freeze([
97
97
  'selfApproved',
98
98
  'hostAcceptance',
99
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',
100
105
  ]);
101
106
 
102
107
  /**
@@ -404,10 +409,18 @@ export function resolveInterruption(observation) {
404
409
  * `skipQuestion` is the same rollover for an ANSWERED question: the just-answered set can
405
410
  * still occupy the engine's slot for a moment. A DIFFERENT request id is never skipped, so
406
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.
407
419
  * @param {object} options - `callExecution`, `taskId`, `waitMs` (deadline), `signal`,
408
420
  * `observeWaitMs` (per-request bound), `now`, `sleep`, optional `waitMetrics`
409
421
  * (`(summary) => void`), optional `correlation` facts to echo back, optional
410
- * `skipPermission` / `skipQuestion` (`(observation) => boolean`).
422
+ * `skipPermission` / `skipQuestion` (`(observation) => boolean`), optional
423
+ * `ackFailureEventId` (string).
411
424
  * @returns {Promise<object>} the compact wait answer (without `ok`).
412
425
  */
413
426
  export async function waitForTask(options) {
@@ -421,6 +434,26 @@ export async function waitForTask(options) {
421
434
  const waitMetrics = typeof options.waitMetrics === 'function' ? options.waitMetrics : null;
422
435
  const skipPermission = typeof options.skipPermission === 'function' ? options.skipPermission : null;
423
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;
424
457
 
425
458
  const startedAt = now();
426
459
 
@@ -492,11 +525,17 @@ export async function waitForTask(options) {
492
525
  * The measurement is of the ANSWER OBJECT (the data the host receives), serialized
493
526
  * once — the envelope a client prints has no bearing on how much data was handed
494
527
  * back, and counting it here keeps `returnedBytes` and the published `metrics` in
495
- * agreement.
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.
496
532
  * @param {object} answerValue - the compact answer.
497
533
  * @returns {object} the same answer.
498
534
  */
499
535
  const finish = (answerValue) => {
536
+ if (ackFailureResult !== undefined && answerValue !== null && typeof answerValue === 'object') {
537
+ answerValue.failureAck = ackFailureResult;
538
+ }
500
539
  returnedReason = typeof answerValue.reason === 'string' ? answerValue.reason : null;
501
540
  if (returnedReason === null) failureCode = answerValue.error?.code ?? 'MCP_CALL_FAILED';
502
541
  report(returnedReason);
@@ -514,19 +553,44 @@ export async function waitForTask(options) {
514
553
  observationRequests += 1;
515
554
  let observation;
516
555
  try {
517
- observation = await callExecution('observe', { taskId, waitMs: perRequest }, { signal });
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 });
518
569
  } catch (error) {
519
570
  if (error?.code === 'MCP_REQUEST_CANCELLED') throw error;
520
571
  // A refusal is the harness's own answer and is returned as such: an unknown
521
572
  // 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.
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.
523
576
  return finish({
524
577
  ...failureAnswer(error),
578
+ ...(ackFailureResult === undefined ? {} : { failureAck: ackFailureResult }),
525
579
  wait: metrics(0),
526
580
  });
527
581
  }
528
582
  lastObservation = observation;
529
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;
593
+ }
530
594
  const reason = reasonOf(observation);
531
595
  // The post-decision rollover: the request this call already decided may still occupy
532
596
  // the engine's slot until the paused native call resumes. It is not a new question,
@@ -608,6 +672,15 @@ export async function waitForTask(options) {
608
672
  // reported, so the caller can tell a cancelled call (0 returns) from one that
609
673
  // answered — and the error is rethrown untouched, so the refusal path stays the
610
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;
683
+ }
611
684
  failureCode = typeof error?.code === 'string' ? error.code : 'MCP_CALL_FAILED';
612
685
  report(null);
613
686
  throw error;
@@ -653,6 +653,9 @@ export async function driveAgent(deps, request) {
653
653
  const state = {
654
654
  abortRequested: false,
655
655
  abortCause: null,
656
+ // The caller's own cancellation, so a pre-prompt step (the Agent Teams selection) can
657
+ // pass a real AbortSignal to the native service and honour the run's deadline/cancel.
658
+ signal: request?.signal ?? null,
656
659
  handle: null,
657
660
  handleDisposed: false,
658
661
  // A resolved Agent is driven through the same handle shape a created one
@@ -689,6 +692,9 @@ export async function driveAgent(deps, request) {
689
692
  // an armed permission bridge is why the Session asks instead of rejecting.
690
693
  // Reported as a verified fact, never as a configuration value.
691
694
  approval: null,
695
+ // The Agent Teams selection this run applied to its own root Session, or null when
696
+ // the caller made no team choice at all.
697
+ team: null,
692
698
  // Removes the `approval/request` answerer when the run ends. Null when the run
693
699
  // had no bridge, which is the ordinary worker run.
694
700
  permissionAnswerer: null,
@@ -855,6 +861,37 @@ export async function driveAgent(deps, request) {
855
861
  return finish(state, state.abortCause === 'timeout' ? RUN_OUTCOMES.timedOut : RUN_OUTCOMES.cancelled);
856
862
  }
857
863
 
864
+ // Agent Teams selection, applied to THIS run's own Session before any model step.
865
+ //
866
+ // DSH owns the switch: `ctx.agentTeams.setEnabled(rootAgent, enabled, signal)` appends
867
+ // the Session's `team/mode` selection and flushes it, which is exactly what the model
868
+ // menu's "Use Agent Teams" control does. The plugin never guesses the value (no
869
+ // keyword heuristics) and never opens the global default.
870
+ //
871
+ // A REQUESTED team mode that cannot be applied STOPS the run here, before the prompt:
872
+ // continuing with the Session's old mode would silently do the opposite of what the
873
+ // commander asked. Only an ABSENT choice (`null`) keeps the Session as it is.
874
+ state.team = await applyTeamSelection(deps, handle.agent, request?.agentTeams ?? null, state, { aborted });
875
+ if (state.team !== null && typeof state.team.refuseReason === 'string') {
876
+ // A requested mode that could not be applied is a REFUSAL, not a downgrade: the
877
+ // worker is released without ever receiving the prompt, so nothing runs under the
878
+ // Session's old mode while the commander believes teams are on. The failure is
879
+ // stated on the run so the task record explains WHY nothing executed. A run that
880
+ // was cancelled or timed out while waiting ends as cancelled/timedOut instead.
881
+ if (state.team.refuseReason === 'agent-teams-aborted') {
882
+ await releaseHandle(state, handle);
883
+ return finish(state, state.abortCause === 'timeout' ? RUN_OUTCOMES.timedOut : RUN_OUTCOMES.cancelled);
884
+ }
885
+ state.error = {
886
+ code: 'RUN_AGENT_TEAMS_UNAVAILABLE',
887
+ message: `Agent Teams could not be applied before the prompt (${state.team.refuseReason}); `
888
+ + 'the worker was not started under the Session\u2019s previous mode',
889
+ details: { team: state.team },
890
+ };
891
+ await releaseHandle(state, handle);
892
+ return finish(state, RUN_OUTCOMES.failed);
893
+ }
894
+
858
895
  handle.agent.followup(userMessage(prompt));
859
896
  await Promise.race([handle.agent.whenIdle(), aborted]);
860
897
 
@@ -1413,7 +1450,135 @@ export async function driveAgent(deps, request) {
1413
1450
  // armed bridge is the answerer behind it. `null` for a run that never had a
1414
1451
  // delegated policy installed (the review, an ordinary session).
1415
1452
  approval: target.approval ?? null,
1453
+ // The Agent Teams selection this run asked for and what actually happened.
1454
+ // `requested: null` means the caller made no choice (the run keeps whatever the
1455
+ // Session already had); `applied: true` is only claimed after the native service
1456
+ // confirmed the Session's saved selection. `refuseReason` is INTERNAL (the runner
1457
+ // branches on it before the prompt) and never leaves the run.
1458
+ team: state.team === null || state.team === undefined
1459
+ ? null
1460
+ : {
1461
+ requested: state.team.requested,
1462
+ supported: state.team.supported,
1463
+ applied: state.team.applied,
1464
+ enabled: state.team.enabled,
1465
+ reason: state.team.reason,
1466
+ },
1467
+ };
1468
+ }
1469
+
1470
+ /**
1471
+ * Apply the commander's Agent Teams choice to THIS run's own root Session.
1472
+ *
1473
+ * The switch is DSH's, not this plugin's: `ctx.agentTeams.setEnabled(agent, enabled)`
1474
+ * appends the Session's `team/mode` selection and flushes it — the same call the model
1475
+ * menu's「Use Agent Teams」control makes through `remote.agentTeams.setEnabled`. So:
1476
+ *
1477
+ * * the value is NEVER guessed. `null`/absent means "no choice": the Session keeps
1478
+ * whatever selection it already has and the run reports `requested: null`;
1479
+ * * nothing global is opened. Only this run's own root Session is written, so no
1480
+ * other conversation and no future task inherits it;
1481
+ * * a REQUESTED mode that cannot be applied stops the run BEFORE the prompt (the
1482
+ * caller treats `refuseReason` as terminal); an ABSENT choice never does;
1483
+ * * the wait is BOUNDED by the run itself: it races the caller's own `aborted` latch
1484
+ * (internal deadline or cancellation), so a service that never resolves cannot hold
1485
+ * the run past its budget, and a late settle never reaches the prompt.
1486
+ * @param {object} deps - run dependencies (`policyServices`).
1487
+ * @param {object} agent - the live root Agent this run drives.
1488
+ * @param {boolean | null} requested - the commander's choice, or null.
1489
+ * @param {object} state - the run state carrying the abort latch.
1490
+ * @param {{ aborted: Promise<string> }} hooks - the run's own abort latch promise.
1491
+ * @returns {Promise<object>} `{ requested, supported, applied, enabled, reason, refuseReason }`
1492
+ * where `refuseReason` is non-null exactly when the run must NOT proceed.
1493
+ */
1494
+ async function applyTeamSelection(deps, agent, requested, state, hooks = {}) {
1495
+ const base = {
1496
+ requested: requested === true ? true : requested === false ? false : null,
1497
+ supported: false,
1498
+ applied: false,
1499
+ enabled: null,
1500
+ reason: null,
1501
+ refuseReason: null,
1416
1502
  };
1503
+ // An ABSENT choice is fully compatible: nothing is written and the run proceeds with
1504
+ // the Session's own selection.
1505
+ if (base.requested === null) return { ...base, reason: 'not-requested' };
1506
+ const refuse = (reason, extra = {}) => ({
1507
+ ...base,
1508
+ ...extra,
1509
+ // The same word in both fields: `reason` is what a reader displays, `refuseReason`
1510
+ // is what the runner branches on. Keeping them identical avoids a record that says
1511
+ // "unavailable" in one place and nothing in the other.
1512
+ reason,
1513
+ refuseReason: reason,
1514
+ });
1515
+ let service = null;
1516
+ try {
1517
+ const services = typeof deps?.policyServices === 'function' ? deps.policyServices() : null;
1518
+ service = services?.agentTeams ?? null;
1519
+ } catch {
1520
+ service = null;
1521
+ }
1522
+ if (service === null || typeof service.setEnabled !== 'function') {
1523
+ return refuse('agent-teams-unavailable');
1524
+ }
1525
+ if (state.abortRequested === true) return refuse('agent-teams-aborted');
1526
+ // The real service accepts an AbortSignal. Both the caller's signal and the run's own
1527
+ // latch (internal deadline, disposal) abort it, so a slow persist is told to stop.
1528
+ const controller = new AbortController();
1529
+ const onAbort = () => { try { controller.abort(); } catch { /* idempotent */ } };
1530
+ const signal = state.signal;
1531
+ if (signal !== null && signal !== undefined) signal.addEventListener?.('abort', onAbort, { once: true });
1532
+ const latchPromise = hooks?.aborted;
1533
+ const latched = typeof latchPromise?.then === 'function' ? latchPromise.then(() => 'latched') : null;
1534
+ // NEVER leave a rejection unhandled: a late reject from a losing timer is swallowed
1535
+ // here, and the winner is decided by which of the two settles first.
1536
+ const settled = Promise.resolve()
1537
+ .then(() => service.setEnabled(agent, base.requested, controller.signal))
1538
+ .then(() => ({ ok: true }), (error) => ({ ok: false, error }));
1539
+ try {
1540
+ const winner = latched === null
1541
+ ? await settled
1542
+ : await Promise.race([settled, latched]);
1543
+ if (winner === 'latched') {
1544
+ // The run's own deadline or cancellation ended while the write was outstanding:
1545
+ // the native call is told to abort and this run must not continue to the prompt.
1546
+ onAbort();
1547
+ // Keep the abandoned promise observed so a late settle cannot become an
1548
+ // unhandled rejection; its result is ignored on purpose.
1549
+ void Promise.resolve(settled).catch(() => {});
1550
+ return refuse('agent-teams-aborted');
1551
+ }
1552
+ if (winner.ok === false) {
1553
+ if (state.abortRequested === true) return refuse('agent-teams-aborted');
1554
+ return refuse(`agent-teams-failed: ${diagnostic(winner.error?.message ?? String(winner.error), 200) ?? 'error'}`, {
1555
+ supported: true,
1556
+ });
1557
+ }
1558
+ } finally {
1559
+ signal?.removeEventListener?.('abort', onAbort);
1560
+ }
1561
+ // A run cancelled while the selection was being written must not continue either: the
1562
+ // caller already asked for it to stop, and the prompt must not be delivered late.
1563
+ if (state.abortRequested === true) return refuse('agent-teams-aborted');
1564
+ // Read back from the SERVICE, not from what we just asked for: `isEnabled` resolves
1565
+ // the runtime root and returns the saved projection, so this is the applied fact.
1566
+ let enabled = null;
1567
+ try {
1568
+ enabled = typeof service.isEnabled === 'function' ? service.isEnabled(agent) === true : null;
1569
+ } catch {
1570
+ enabled = null;
1571
+ }
1572
+ if (enabled === null) {
1573
+ return refuse('agent-teams-unconfirmed', { supported: true });
1574
+ }
1575
+ if (enabled !== base.requested) {
1576
+ return refuse(`agent-teams-mismatch: requested ${String(base.requested)}, session reports ${String(enabled)}`, {
1577
+ supported: true,
1578
+ enabled,
1579
+ });
1580
+ }
1581
+ return { ...base, supported: true, applied: true, enabled, reason: null };
1417
1582
  }
1418
1583
 
1419
1584
  /**