pi-subagents 0.87.0 → 0.88.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 (91) hide show
  1. package/CHANGELOG.md +32 -0
  2. package/bundle/agents.js +3 -3
  3. package/bundle/child-tool-plan.js +2 -2
  4. package/bundle/{chunk-3CVOAS77.js → chunk-2DIEL4WG.js} +2 -2
  5. package/bundle/{chunk-PGU4TZV3.js → chunk-3DT5X2QC.js} +406 -447
  6. package/bundle/{chunk-SIAQXPJ4.js → chunk-3MFYKBKI.js} +18 -6
  7. package/bundle/{chunk-AIL46SZU.js → chunk-47GJDBIK.js} +6 -4
  8. package/bundle/{chunk-ESWW6XSX.js → chunk-47ZN7NKR.js} +1 -1
  9. package/bundle/{chunk-C3KWLXDH.js → chunk-4MVDMA5C.js} +9 -1
  10. package/bundle/{chunk-DGTZKYIE.js → chunk-4PM6RDE5.js} +42 -29
  11. package/bundle/{chunk-EYGBK6CE.js → chunk-4UGWHREQ.js} +45 -15
  12. package/bundle/{chunk-HDICKROY.js → chunk-6EUQPQY7.js} +31 -14
  13. package/bundle/{chunk-LFKMM3UH.js → chunk-6OWNDN7R.js} +2 -2
  14. package/bundle/{chunk-M2VBGET6.js → chunk-6PR44R7E.js} +7 -2
  15. package/bundle/{chunk-OOE3R7IQ.js → chunk-CKLZ5FGU.js} +2 -2
  16. package/bundle/{chunk-W52LJANO.js → chunk-CYKNHFXB.js} +1 -1
  17. package/bundle/{chunk-6O7YH2QV.js → chunk-GDR2ILWY.js} +1 -1
  18. package/bundle/{chunk-2D2DQGC2.js → chunk-IZEKQEY4.js} +9 -9
  19. package/bundle/{chunk-C5QWQSSM.js → chunk-KXW62VBU.js} +1 -1
  20. package/bundle/{chunk-BFF6YDK6.js → chunk-L4YY2TOE.js} +1 -1
  21. package/bundle/{chunk-JLDQ6YUR.js → chunk-MTPICU4A.js} +11 -11
  22. package/bundle/{chunk-YEXKJJVS.js → chunk-PJSOS2Q4.js} +4 -4
  23. package/bundle/{chunk-2NY5PCKQ.js → chunk-RHYVKQQL.js} +4 -4
  24. package/bundle/{chunk-XV7RTWTS.js → chunk-SVIXQDIV.js} +20 -5
  25. package/bundle/{chunk-OTLDAYEQ.js → chunk-UVDLJXL6.js} +14 -5
  26. package/bundle/{chunk-VFUFOZBU.js → chunk-W6HIYD2Z.js} +1 -1
  27. package/bundle/{chunk-OZCPYJEY.js → chunk-XAOHLFJO.js} +118 -42
  28. package/bundle/{chunk-USRX7QXD.js → chunk-XIA5GSEU.js} +2 -2
  29. package/bundle/chunk-YDZ7BZD5.js +523 -0
  30. package/bundle/{chunk-LZKVUWIY.js → chunk-YZPVALSQ.js} +30 -5
  31. package/bundle/control-channel.js +2 -2
  32. package/bundle/index.js +1 -1
  33. package/bundle/intercom-bridge.js +2 -2
  34. package/bundle/preflight.js +8 -8
  35. package/bundle/project-panes.js +3 -3
  36. package/docs/agents.md +1 -1
  37. package/docs/configuration.md +7 -3
  38. package/docs/observability.md +2 -0
  39. package/docs/tool-reference.md +4 -1
  40. package/package.json +2 -2
  41. package/skills/pi-subagents/SKILL.md +8 -2
  42. package/src/agents/agent-management.d.ts +1 -0
  43. package/src/agents/agent-management.js +12 -4
  44. package/src/agents/agents.d.ts +1 -0
  45. package/src/agents/agents.js +2 -2
  46. package/src/extension/config.d.ts +1 -0
  47. package/src/extension/config.js +6 -0
  48. package/src/extension/index.js +4 -3
  49. package/src/extension/schemas.d.ts +2 -0
  50. package/src/extension/schemas.js +1 -0
  51. package/src/extension/tool-activation.js +20 -3
  52. package/src/runs/background/async-resume.js +2 -1
  53. package/src/runs/background/async-retention.d.ts +0 -2
  54. package/src/runs/background/async-retention.js +11 -5
  55. package/src/runs/background/async-status.d.ts +2 -0
  56. package/src/runs/background/async-status.js +4 -0
  57. package/src/runs/background/run-child-session.d.ts +2 -2
  58. package/src/runs/background/run-child-session.js +4 -7
  59. package/src/runs/background/steering.d.ts +2 -11
  60. package/src/runs/background/steering.js +11 -6
  61. package/src/runs/background/subagent-runner.d.ts +0 -2
  62. package/src/runs/background/subagent-runner.js +73 -58
  63. package/src/runs/foreground/async-steering-action.js +24 -9
  64. package/src/runs/foreground/execution.js +32 -15
  65. package/src/runs/foreground/prompt-audit.js +1 -0
  66. package/src/runs/foreground/subagent-executor.d.ts +1 -8
  67. package/src/runs/foreground/subagent-executor.js +6 -15
  68. package/src/runs/shared/async-status-projection.d.ts +2 -0
  69. package/src/runs/shared/async-status-projection.js +10 -0
  70. package/src/runs/shared/child-session.js +21 -3
  71. package/src/runs/shared/mcp-config-sources.d.ts +2 -0
  72. package/src/runs/shared/mcp-direct-tool-allowlist.d.ts +0 -2
  73. package/src/runs/shared/mcp-direct-tool-allowlist.js +21 -11
  74. package/src/runs/shared/subagent-prompt-runtime.js +14 -2
  75. package/src/runs/shared/supervisor-wait-timer.d.ts +16 -0
  76. package/src/runs/shared/supervisor-wait-timer.js +61 -0
  77. package/src/shared/artifacts.d.ts +1 -0
  78. package/src/shared/artifacts.js +107 -9
  79. package/src/shared/reported-progress.d.ts +1 -0
  80. package/src/shared/reported-progress.js +12 -0
  81. package/src/shared/status-format.d.ts +1 -0
  82. package/src/shared/status-format.js +1 -1
  83. package/src/shared/types.d.ts +9 -0
  84. package/src/shared/utils.d.ts +3 -1
  85. package/src/shared/utils.js +4 -0
  86. package/src/tui/render.js +33 -2
  87. package/src/watchdog/permission-arbiter.js +1 -0
  88. package/src/watchdog/review.d.ts +0 -5
  89. package/src/watchdog/review.js +2 -1
  90. package/src/workflows/workflow-script-worker.js +3 -1
  91. package/bundle/chunk-XSDYTXHF.js +0 -242
@@ -1,7 +1,5 @@
1
1
  import type { AsyncStatus, ResolvedToolBudget, SteerActionResult, SteeringRecoveryDescriptor, SteeringRequestStatus, SteeringStatus, SteeringTargetState, SteeringTargetStatus } from "../../shared/types.ts";
2
2
  import type { SteerDeliveryMode } from "./control-channel.ts";
3
- export declare const MAX_STEERING_REQUESTS = 20;
4
- export declare const STEERING_MESSAGE_PREVIEW_LIMIT = 160;
5
3
  export declare function steeringMessagePreview(message: string): string;
6
4
  /** FIFO match of one accepted steer to an emitted user message; equal text claims the oldest entry. */
7
5
  export declare function takeMatchingAcceptedSteer<T extends {
@@ -17,16 +15,10 @@ export declare function recordSteeringRequest(status: SteeringStatus, input: {
17
15
  requestedAt: number;
18
16
  source?: string;
19
17
  message: string;
20
- targets: Array<{
21
- index: number;
22
- state: SteeringTargetState;
23
- reason?: string;
24
- }>;
18
+ targets: Array<Pick<SteeringTargetStatus, "index" | "state" | "reason" | "failureKind">>;
25
19
  }): SteeringRequestStatus;
26
- export declare function updateSteeringTarget(status: SteeringStatus, requestId: string, index: number, state: SteeringTargetState, now: number, fields?: Pick<SteeringTargetStatus, "reason" | "replacementRunId">): SteeringTargetStatus | undefined;
27
- export declare function findSteeringRequest(status: SteeringStatus, requestId: string): SteeringRequestStatus | undefined;
20
+ export declare function updateSteeringTarget(status: SteeringStatus, requestId: string, index: number, state: SteeringTargetState, now: number, fields?: Pick<SteeringTargetStatus, "reason" | "replacementRunId" | "failureKind">): SteeringTargetStatus | undefined;
28
21
  export declare function actionResultFromSteeringStatus(status: SteeringStatus, sourceRunId: string, requestId: string, replacementRunId?: string): SteerActionResult | undefined;
29
- export declare function steeringActionIsTerminal(result: SteerActionResult | undefined): boolean;
30
22
  export declare function terminalSteeringNoticeState(status: SteeringStatus, requestId: string): "failed" | "partial" | undefined;
31
23
  export declare function claimSteeringRecovery(asyncDir: string, input: {
32
24
  requestId: string;
@@ -36,7 +28,6 @@ export declare function claimSteeringRecovery(asyncDir: string, input: {
36
28
  claimPath: string;
37
29
  markerPath: string;
38
30
  };
39
- export declare function readSteeringStatus(asyncDir: string): SteeringStatus | undefined;
40
31
  export declare function remainingSteeringRecoveryLimits(descriptor: Pick<SteeringRecoveryDescriptor, "absoluteDeadlineAt" | "initialToolBudget">, status: Pick<AsyncStatus, "toolBudget" | "toolCount">, now?: number): {
41
32
  timeoutMs?: number;
42
33
  absoluteDeadlineAt?: number;
@@ -4,8 +4,8 @@ import { writePrivateAtomicJson } from "../../shared/atomic-json.js";
4
4
  import { readStatus } from "../../shared/utils.js";
5
5
  import { previewDisplayText } from "../../shared/display-text.js";
6
6
  import { redactSecretValues } from "../shared/permissions.js";
7
- export const MAX_STEERING_REQUESTS = 20;
8
- export const STEERING_MESSAGE_PREVIEW_LIMIT = 160;
7
+ const MAX_STEERING_REQUESTS = 20;
8
+ const STEERING_MESSAGE_PREVIEW_LIMIT = 160;
9
9
  export function steeringMessagePreview(message) {
10
10
  return previewDisplayText(redactSecretValues(message), STEERING_MESSAGE_PREVIEW_LIMIT);
11
11
  }
@@ -44,7 +44,7 @@ export function recordSteeringRequest(status, input) {
44
44
  requestedAt: input.requestedAt,
45
45
  ...(input.source ? { source: input.source } : {}),
46
46
  messagePreview: steeringMessagePreview(input.message),
47
- targets: input.targets.map((target) => ({ index: target.index, state: target.state, ...(target.reason ? { reason: target.reason } : {}) })),
47
+ targets: input.targets.map((target) => ({ index: target.index, state: target.state, ...(target.reason ? { reason: target.reason } : {}), ...(target.failureKind ? { failureKind: target.failureKind } : {}) })),
48
48
  };
49
49
  status.requested++;
50
50
  status.lastRequestedAt = input.requestedAt;
@@ -70,6 +70,10 @@ export function updateSteeringTarget(status, requestId, index, state, now, field
70
70
  const target = request?.targets.find((candidate) => candidate.index === index);
71
71
  if (!target)
72
72
  return undefined;
73
+ if (state !== "failed")
74
+ delete target.failureKind;
75
+ else if (fields.failureKind)
76
+ target.failureKind = fields.failureKind;
73
77
  if (state === "late" && target.state === "recovered") {
74
78
  if (target.lateDeliveredAt === undefined) {
75
79
  target.lateDeliveredAt = now;
@@ -120,7 +124,7 @@ export function updateSteeringTarget(status, requestId, index, state, now, field
120
124
  incrementStateCount(status, state);
121
125
  return target;
122
126
  }
123
- export function findSteeringRequest(status, requestId) {
127
+ function findSteeringRequest(status, requestId) {
124
128
  return status.recent.find((request) => request.id === requestId);
125
129
  }
126
130
  export function actionResultFromSteeringStatus(status, sourceRunId, requestId, replacementRunId) {
@@ -133,6 +137,7 @@ export function actionResultFromSteeringStatus(status, sourceRunId, requestId, r
133
137
  ...(target.deliveredAt !== undefined ? { deliveredAt: target.deliveredAt } : {}),
134
138
  ...(target.lateDeliveredAt !== undefined ? { lateDeliveredAt: target.lateDeliveredAt } : {}),
135
139
  ...(target.reason ? { reason: target.reason } : {}),
140
+ ...(target.failureKind ? { failureKind: target.failureKind } : {}),
136
141
  ...(target.replacementRunId ? { replacementRunId: target.replacementRunId } : {}),
137
142
  }));
138
143
  const states = targets.map((target) => target.state);
@@ -151,7 +156,7 @@ export function actionResultFromSteeringStatus(status, sourceRunId, requestId, r
151
156
  const deliveryStatus = states.length > 0 && states.every((candidate) => candidate === "delivered" || candidate === "recovered") ? "delivered" : "queued";
152
157
  return { requestId, state, deliveryStatus, sourceRunId, ...(effectiveReplacementRunId ? { replacementRunId: effectiveReplacementRunId } : {}), targets };
153
158
  }
154
- export function steeringActionIsTerminal(result) {
159
+ function steeringActionIsTerminal(result) {
155
160
  return (result?.targets.length ?? 0) > 0 && result?.targets.every((target) => target.state === "queued" || target.state === "delivered") === true
156
161
  || result?.state === "delivered" || result?.state === "scheduled" || result?.state === "partial" || result?.state === "recovered" || result?.state === "failed";
157
162
  }
@@ -204,7 +209,7 @@ export function claimSteeringRecovery(asyncDir, input) {
204
209
  }
205
210
  return { claimPath, markerPath };
206
211
  }
207
- export function readSteeringStatus(asyncDir) {
212
+ function readSteeringStatus(asyncDir) {
208
213
  return readStatus(asyncDir)?.steering;
209
214
  }
210
215
  export function remainingSteeringRecoveryLimits(descriptor, status, now = Date.now()) {
@@ -174,8 +174,6 @@ interface SingleStepContext {
174
174
  stopMessage?: string;
175
175
  /** Resolved configured hard per-tool-call timeout (ms); fast tools still have a default when undefined. */
176
176
  toolTimeoutMs?: number;
177
- /** Effective step deadline (Date.now() + effective timeout) when a run budget exists. */
178
- deadlineAt?: number;
179
177
  childIntercomTarget?: string;
180
178
  orchestratorIntercomTarget?: string;
181
179
  nestedRoute?: NestedRouteInfo;
@@ -13,6 +13,7 @@ import { performance } from "node:perf_hooks";
13
13
  import { pathToFileURL } from "node:url";
14
14
  import { installRunnerHttpDispatcher } from "./runner-http-dispatcher.js";
15
15
  import { writeAtomicJson } from "../../shared/atomic-json.js";
16
+ import { extractReportedProgress } from "../../shared/reported-progress.js";
16
17
  import { withResultRunLease, writeAsyncResultFile, writePendingAsyncResultFile } from "./result-files.js";
17
18
  import { createFileCoalescer } from "../../shared/file-coalescer.js";
18
19
  import { createCapacityResilientJsonWriter } from "../../shared/capacity-resilient-json.js";
@@ -34,6 +35,7 @@ import { retainsChildCommand } from "../shared/child-commands.js";
34
35
  import { buildRunnerChildLaunch } from "./runner-child-launch.js";
35
36
  import { normalizeExtensionBindings } from "../shared/extension-bindings.js";
36
37
  import { runChildSession } from "./run-child-session.js";
38
+ import { isBlockingSupervisorTool, pauseForSupervisorWait, startPausableTimer } from "../shared/supervisor-wait-timer.js";
37
39
  import { loadRunnerChildSessionFactory } from "./runner-child-sessions.js";
38
40
  import { SUBAGENT_CHILD_ENV, SUBAGENT_RUNNER_PID_ENV } from "../shared/child-runtime-config.js";
39
41
  import { deriveChildSessionName } from "../../shared/child-session-name.js";
@@ -51,7 +53,7 @@ import { processTerminalPath, writeProcessTerminalCandidate } from "./process-te
51
53
  import { persistRunnerStartupFailure } from "./runner-startup-failure.js";
52
54
  import { currentRecordedPid } from "./boot-id.js";
53
55
  import { createSteeringStatus, recordSteeringRequest, steeringStatus, terminalSteeringNoticeState, unconsumedSteerReason, updateSteeringTarget } from "./steering.js";
54
- import { PROMPT_REDACTED, SUBAGENT_STOPPED_MESSAGE, SUBAGENT_TIMED_OUT_MESSAGE, detectSubagentError, extractTextFromContent, extractToolArgsPreview, formatEmptyTerminalAssistantResponseError, getAgentDir, hasEmptyTerminalAssistantResponse, readStatus } from "../../shared/utils.js";
56
+ import { PROMPT_REDACTED, SUBAGENT_STOPPED_MESSAGE, SUBAGENT_TIMED_OUT_MESSAGE, TRUNCATED_RESPONSE_ERROR, detectSubagentError, extractTextFromContent, extractToolArgsPreview, formatEmptyTerminalAssistantResponseError, getAgentDir, getTerminalAssistantStopReason, hasEmptyTerminalAssistantResponse, readStatus } from "../../shared/utils.js";
55
57
  import { planAbortRecovery } from "../shared/abort-recovery.js";
56
58
  import { createMutatingFailureState, didMutatingToolFail, isMutatingTool, nextLongRunningTrigger, recordMutatingFailure, resetMutatingFailureState, resolveCurrentPath, shouldEscalateMutatingFailures, summarizeRecentMutatingFailures, } from "../shared/long-running-guard.js";
57
59
  import { parseSessionTokens } from "../../shared/session-tokens.js";
@@ -176,15 +178,6 @@ function appendDiagnosticJsonl(filePath, line, droppedEventType) {
176
178
  }
177
179
  state.diagnosticsTruncated = true;
178
180
  }
179
- function isBlockingSupervisorTool(toolName, args) {
180
- if (!args || typeof args !== "object" || Array.isArray(args))
181
- return false;
182
- if (toolName === "contact_supervisor") {
183
- const reason = args.reason;
184
- return reason === "need_decision" || reason === "interview_request";
185
- }
186
- return toolName === "intercom" && args.action === "ask";
187
- }
188
181
  function findLatestSessionFile(sessionDir) {
189
182
  try {
190
183
  const files = fs
@@ -935,7 +928,6 @@ export async function runSingleStepInner(step, ctx) {
935
928
  onContextWindow: (contextLimit) => ctx.onAttemptStart?.({ ...attemptModel, contextLimit }),
936
929
  transcriptWriter,
937
930
  toolTimeoutMs: ctx.toolTimeoutMs,
938
- runDeadlineAt: ctx.deadlineAt,
939
931
  expectedModelForVerification,
940
932
  modelVerificationRegistry: step.modelVerificationRegistry,
941
933
  modelResponseAliases: step.modelResponseAliases,
@@ -1011,6 +1003,10 @@ export async function runSingleStepInner(step, ctx) {
1011
1003
  && (!hiddenError?.hasError || hasEmptyTerminalAssistantResponse(run.messages))
1012
1004
  ? formatEmptyTerminalAssistantResponseError(run.messages)
1013
1005
  : undefined;
1006
+ // Earlier errors in the chains below win, so only the hidden-error gate needs restating.
1007
+ const truncatedResponseError = hiddenError && !hiddenError.hasError && !validatedStructuredOutput && getTerminalAssistantStopReason(run.messages) === "length"
1008
+ ? TRUNCATED_RESPONSE_ERROR
1009
+ : undefined;
1014
1010
  const remoteGitChanged = run.nativeMachine?.initialGit && run.nativeMachine.finalGit ? run.nativeMachine.initialGit.head !== run.nativeMachine.finalGit.head || run.nativeMachine.initialGit.dirty !== run.nativeMachine.finalGit.dirty : undefined;
1015
1011
  const mutationEvidence = run.nativeMachine && !isRexLocalMachine(step.machine) ? { source: "tracked-files", trackedOnly: true, changedFiles: [], attemptedMutation: remoteGitChanged === true, ...(remoteGitChanged === undefined ? { unavailable: "Remote Git before/after evidence was incomplete." } : {}) } : await collectTrackedMutationEvidence(mutationSnapshot, step.cwd ?? ctx.cwd);
1016
1012
  finalMutationEvidence = mutationEvidence;
@@ -1028,7 +1024,7 @@ export async function runSingleStepInner(step, ctx) {
1028
1024
  finalRequiredOutputMissing = requiredOutput?.missing;
1029
1025
  const missingRequiredOutputError = terminalDiagnosticsEligible ? formatRequiredOutputError(requiredOutput) : undefined;
1030
1026
  const missingRequiredOutputAfterMutation = Boolean(missingRequiredOutputError) && (mutationAttemptObserved || Boolean(mutationEvidence.changedFiles.length));
1031
- const effectiveExitCode = toolAvailabilityError || midToolExitError || structuredError || emptyOutputError || missingRequiredOutputError
1027
+ const effectiveExitCode = toolAvailabilityError || midToolExitError || structuredError || truncatedResponseError || emptyOutputError || missingRequiredOutputError
1032
1028
  ? 1
1033
1029
  : hiddenError?.hasError
1034
1030
  ? (hiddenError.exitCode ?? 1)
@@ -1040,6 +1036,7 @@ export async function runSingleStepInner(step, ctx) {
1040
1036
  ?? structuredError
1041
1037
  ?? run.error
1042
1038
  ?? emptyOutputError
1039
+ ?? truncatedResponseError
1043
1040
  ?? (missingRequiredOutputAfterMutation ? missingRequiredOutputError : undefined)
1044
1041
  ?? (hiddenError?.hasError
1045
1042
  ? hiddenError.details
@@ -1468,17 +1465,12 @@ function combinedAbortSignal(signals) {
1468
1465
  }
1469
1466
  return controller.signal;
1470
1467
  }
1471
- async function runSingleStepWithTimeout(step, ctx, parentDeadlineAt) {
1472
- if (step.timeoutMs === undefined)
1473
- return runSingleStep(step, parentDeadlineAt === undefined ? ctx : {
1474
- ...ctx,
1475
- deadlineAt: ctx.deadlineAt === undefined ? parentDeadlineAt : Math.min(ctx.deadlineAt, parentDeadlineAt),
1476
- });
1477
- const parentRemainingMs = parentDeadlineAt === undefined ? undefined : Math.max(0, parentDeadlineAt - Date.now());
1478
- const timeoutMs = parentRemainingMs === undefined ? step.timeoutMs : Math.min(step.timeoutMs, parentRemainingMs);
1479
- const timeoutMessage = parentRemainingMs !== undefined && parentRemainingMs <= step.timeoutMs
1480
- ? ctx.timeoutMessage
1481
- : `Subagent timed out after ${step.timeoutMs}ms.`;
1468
+ async function runSingleStepWithTimeout(step, ctx, runRemainingMs) {
1469
+ const runRemainingAtStart = runRemainingMs();
1470
+ // When the run deadline comes first, the run timer ends this child; it also pauses for a sibling's supervisor wait.
1471
+ if (step.timeoutMs === undefined || (runRemainingAtStart !== undefined && runRemainingAtStart <= step.timeoutMs)) {
1472
+ return runSingleStep(step, ctx);
1473
+ }
1482
1474
  const timeoutController = new AbortController();
1483
1475
  let timeoutAction;
1484
1476
  let timeoutTriggered = false;
@@ -1495,19 +1487,21 @@ async function runSingleStepWithTimeout(step, ctx, parentDeadlineAt) {
1495
1487
  if (action && timeoutTriggered)
1496
1488
  action();
1497
1489
  };
1498
- const timer = setTimeout(triggerTimeout, timeoutMs);
1499
- timer.unref?.();
1490
+ const timer = startPausableTimer(step.timeoutMs, triggerTimeout);
1500
1491
  try {
1501
1492
  return await runSingleStep(step, {
1502
1493
  ...ctx,
1503
1494
  registerTimeout,
1504
- deadlineAt: Date.now() + timeoutMs,
1495
+ onChildEvent: (event) => {
1496
+ pauseForSupervisorWait(timer, event);
1497
+ ctx.onChildEvent?.(event);
1498
+ },
1505
1499
  timeoutSignal: combinedAbortSignal([ctx.timeoutSignal, timeoutController.signal]),
1506
- timeoutMessage,
1500
+ timeoutMessage: `Subagent timed out after ${step.timeoutMs}ms.`,
1507
1501
  });
1508
1502
  }
1509
1503
  finally {
1510
- clearTimeout(timer);
1504
+ timer.clear();
1511
1505
  ctx.registerTimeout?.(undefined);
1512
1506
  }
1513
1507
  }
@@ -1541,6 +1535,13 @@ export async function runSubagent(config, childSessions) {
1541
1535
  let activityTimer;
1542
1536
  let timeoutTimer;
1543
1537
  let checkpointTimer;
1538
+ // The run deadline moves later by the time its children spent blocked on a supervisor reply.
1539
+ const runRemainingMs = () => timeoutTimer?.remainingMs();
1540
+ const runDeadlineAt = () => {
1541
+ const remainingMs = runRemainingMs();
1542
+ return remainingMs === undefined ? undefined : Date.now() + remainingMs;
1543
+ };
1544
+ const runDeadlineExpired = () => runRemainingMs() === 0;
1544
1545
  let timedOut = false;
1545
1546
  let stopped = false;
1546
1547
  let usageBudgetExceeded = false;
@@ -2652,9 +2653,11 @@ export async function runSubagent(config, childSessions) {
2652
2653
  const target = request?.targets.find((candidate) => candidate.index === index);
2653
2654
  if (!request || !target)
2654
2655
  return;
2655
- if (target.state === "delivered" || target.state === "late" || target.state === "failed")
2656
+ if (target.state === "delivered" || target.state === "late")
2657
+ return;
2658
+ if (target.state === "failed" && !(target.failureKind === "unconsumed" && delivery.failureKind === "rejected"))
2656
2659
  return;
2657
- if (target.state === delivery.state)
2660
+ if (target.state === delivery.state && target.failureKind === delivery.failureKind)
2658
2661
  return;
2659
2662
  const late = fs.existsSync(steeringMarkerPath(requestId));
2660
2663
  const now = Date.now();
@@ -2668,7 +2671,7 @@ export async function runSubagent(config, childSessions) {
2668
2671
  }
2669
2672
  else {
2670
2673
  markSteeringAttention(index);
2671
- updateSteeringLifecycleTarget(requestId, index, "failed", now, { reason: delivery.message });
2674
+ updateSteeringLifecycleTarget(requestId, index, "failed", now, { reason: delivery.message, failureKind: delivery.failureKind ?? "rejected" });
2672
2675
  emitSteeringEvent("subagent.steer.failed", { type: "steer", id: requestId, ts: now, message: delivery.message }, index, { reason: delivery.message });
2673
2676
  }
2674
2677
  emitTerminalSteeringNotice(requestId, `Steering failed for run ${id}: ${delivery.message}`);
@@ -2709,9 +2712,19 @@ export async function runSubagent(config, childSessions) {
2709
2712
  statusPayload.lastUpdate = now;
2710
2713
  writeStatusPayload();
2711
2714
  };
2715
+ // Keyed by step, so a step that ends mid-ask never leaves the run timers paused.
2716
+ const pauseRunTimers = (flatIndex) => {
2717
+ timeoutTimer?.pause(String(flatIndex));
2718
+ checkpointTimer?.pause(String(flatIndex));
2719
+ };
2720
+ const resumeRunTimers = (flatIndex) => {
2721
+ timeoutTimer?.resume(String(flatIndex));
2722
+ checkpointTimer?.resume(String(flatIndex));
2723
+ };
2712
2724
  // The sequential and both parallel paths share it.
2713
2725
  const recordStepResult = (fi, singleResult, startedAt, endedAt, recordLaunchContractDigest = false) => {
2714
2726
  const step = requiredStatusStep(statusPayload, fi);
2727
+ resumeRunTimers(fi);
2715
2728
  const childStopped = singleResult.stopped === true;
2716
2729
  const childInterrupted = singleResult.interrupted === true;
2717
2730
  step.status = stopped || childStopped ? "stopped" : timedOut ? "failed" : childInterrupted ? "paused" : singleResult.execution?.status === "partial" ? "partial" : singleResult.exitCode === 0 ? "complete" : "failed";
@@ -2814,7 +2827,9 @@ export async function runSubagent(config, childSessions) {
2814
2827
  statusPayload.toolBudget = step.toolBudget;
2815
2828
  }
2816
2829
  recordActiveToolCall(flatIndex, { toolCallId: event.toolCallId, toolName: event.toolName }, { argsPreview, currentPath, blocksSupervisor, now });
2817
- const pending = omitUndefinedProperties({ tool: event.toolName, path: currentPath, mutates, startedAt: now });
2830
+ if (blocksSupervisor)
2831
+ pauseRunTimers(flatIndex);
2832
+ const pending = omitUndefinedProperties({ tool: event.toolName, path: currentPath, mutates, startedAt: now, progressText: extractReportedProgress(event.toolName, event.args) });
2818
2833
  pendingToolResults[flatIndex] = pending;
2819
2834
  const startedCallId = event.toolCallId;
2820
2835
  if (typeof startedCallId === "string" && startedCallId)
@@ -2857,6 +2872,8 @@ export async function runSubagent(config, childSessions) {
2857
2872
  const supervisorPreviousActivity = supervisorAttentionSteps.get(flatIndex);
2858
2873
  const stillBlockingSupervisor = [...(activeToolCalls[flatIndex]?.values() ?? [])].some((active) => active.blocksSupervisor);
2859
2874
  const clearedSupervisorAttention = endedTool?.blocksSupervisor && !stillBlockingSupervisor ? supervisorAttentionSteps.delete(flatIndex) : false;
2875
+ if (!stillBlockingSupervisor)
2876
+ resumeRunTimers(flatIndex);
2860
2877
  if (clearedSupervisorAttention && step.activityState === "needs_attention") {
2861
2878
  setOptionalProperty(step, "activityState", supervisorPreviousActivity);
2862
2879
  syncAggregateActivityState();
@@ -2875,6 +2892,10 @@ export async function runSubagent(config, childSessions) {
2875
2892
  pendingToolResults[flatIndex] = undefined;
2876
2893
  const resultText = extractTextFromContent(event.message.content);
2877
2894
  const resultToolName = event.message.toolName;
2895
+ if (event.message.isError !== true && resultToolName === toolSnapshot?.tool && toolSnapshot?.progressText) {
2896
+ step.progressText = toolSnapshot.progressText;
2897
+ step.progressUpdatedAt = now;
2898
+ }
2878
2899
  const blockedTool = (typeof resultToolName === "string" && resultToolName.length > 0 ? resultToolName : undefined) ?? toolSnapshot?.tool;
2879
2900
  const configuredToolBudget = flatSteps[flatIndex]?.toolBudget;
2880
2901
  const budgetBlocked = configuredToolBudget !== undefined && isToolBudgetBlockedMessage(configuredToolBudget, resultText, blockedTool);
@@ -3119,7 +3140,7 @@ export async function runSubagent(config, childSessions) {
3119
3140
  source: "async", cwd, stepIndex, flatStartIndex, setup, diffs: [], results: [], cleanup,
3120
3141
  });
3121
3142
  writeStatusPayload();
3122
- }, config.deadlineAt);
3143
+ }, runDeadlineAt());
3123
3144
  const interruptRunner = () => {
3124
3145
  consumeInterruptRequest(asyncDir);
3125
3146
  if (interrupted || statusPayload.state !== "running")
@@ -3247,23 +3268,22 @@ export async function runSubagent(config, childSessions) {
3247
3268
  });
3248
3269
  if (config.deadlineAt !== undefined) {
3249
3270
  const remainingMs = Math.max(0, config.deadlineAt - Date.now());
3250
- timeoutTimer = setTimeout(timeoutRunner, remainingMs);
3251
- timeoutTimer.unref?.();
3271
+ const runTimer = startPausableTimer(remainingMs, timeoutRunner);
3272
+ timeoutTimer = runTimer;
3252
3273
  // Route the pre-deadline checkpoint like any external steer so its lifecycle records the receipt.
3253
3274
  const checkpointBeforeDeadlineMs = config.checkpointBeforeDeadlineMs;
3254
3275
  const checkpointDelayMs = checkpointBeforeDeadlineMs === undefined || !Number.isInteger(checkpointBeforeDeadlineMs) || checkpointBeforeDeadlineMs <= 0
3255
3276
  ? undefined
3256
3277
  : remainingMs - checkpointBeforeDeadlineMs;
3257
3278
  if (checkpointDelayMs !== undefined && checkpointDelayMs >= 1_000) {
3258
- const deadlineAt = config.deadlineAt;
3259
- checkpointTimer = setTimeout(() => {
3279
+ checkpointTimer = startPausableTimer(checkpointDelayMs, () => {
3260
3280
  checkpointTimer = undefined;
3261
3281
  if (timedOut || stopped || interrupted)
3262
3282
  return;
3263
3283
  if (!statusPayload.steps.some((step) => step.status === "running"))
3264
3284
  return;
3265
3285
  const now = Date.now();
3266
- const seconds = Math.round(Math.max(0, deadlineAt - now) / 1000);
3286
+ const seconds = Math.round(runTimer.remainingMs() / 1000);
3267
3287
  deliverSteerRequest({
3268
3288
  type: "steer",
3269
3289
  id: `deadline-checkpoint-${now}`,
@@ -3272,8 +3292,7 @@ export async function runSubagent(config, childSessions) {
3272
3292
  source: "deadline-checkpoint",
3273
3293
  message: `Deadline checkpoint from the runner: this run is killed in about ${seconds} seconds. Finish the current tool call only, then stop and reply with a handoff: changed files, build/test state, remaining work, and commit/PR state. Do not start new work.`,
3274
3294
  });
3275
- }, checkpointDelayMs);
3276
- checkpointTimer.unref?.();
3295
+ });
3277
3296
  }
3278
3297
  }
3279
3298
  appendJsonl(eventsPath, JSON.stringify({
@@ -3618,7 +3637,7 @@ export async function runSubagent(config, childSessions) {
3618
3637
  usageBudgetExhausted: continuationUsageBudgetExhausted,
3619
3638
  usageBudget: config.usageBudget,
3620
3639
  orcaProgressTab,
3621
- }), config.deadlineAt);
3640
+ }), runRemainingMs);
3622
3641
  const taskEndTime = Date.now();
3623
3642
  const childInterrupted = singleResult.interrupted === true;
3624
3643
  const childStopped = singleResult.stopped === true;
@@ -3810,7 +3829,7 @@ export async function runSubagent(config, childSessions) {
3810
3829
  try {
3811
3830
  worktreeSetup = await createWorktrees(cwd, `${id}-s${stepIndex}`, group.parallel.length, omitUndefinedProperties({
3812
3831
  signal: setupSignal,
3813
- deadlineAt: config.deadlineAt,
3832
+ deadlineAt: runDeadlineAt(),
3814
3833
  agents: group.parallel.map((task) => task.agent),
3815
3834
  labels: group.parallel.map((task) => task.lane?.key ?? config.workflowKey ?? task.outputName ?? task.label),
3816
3835
  tasks: group.parallel.map((task) => task.task),
@@ -3843,7 +3862,7 @@ export async function runSubagent(config, childSessions) {
3843
3862
  writeStatusPayload();
3844
3863
  },
3845
3864
  }));
3846
- if (config.deadlineAt !== undefined && Date.now() >= config.deadlineAt)
3865
+ if (runDeadlineExpired())
3847
3866
  timeoutRunner();
3848
3867
  if (setupSignal.aborted)
3849
3868
  throw new Error(stopped ? stopMessage : timedOut ? timeoutMessage ?? SUBAGENT_TIMED_OUT_MESSAGE : "Subagent paused during worktree setup.");
@@ -3851,7 +3870,7 @@ export async function runSubagent(config, childSessions) {
3851
3870
  catch (error) {
3852
3871
  if (worktreeSetup)
3853
3872
  await cleanupRemainingWorktree(worktreeSetup, stepIndex, groupStartFlatIndex);
3854
- if (config.deadlineAt !== undefined && Date.now() >= config.deadlineAt)
3873
+ if (runDeadlineExpired())
3855
3874
  timeoutRunner();
3856
3875
  const setupError = error instanceof Error ? error.message : String(error);
3857
3876
  if (error instanceof WorktreeSetupError)
@@ -3998,7 +4017,7 @@ export async function runSubagent(config, childSessions) {
3998
4017
  usageBudgetExhausted: continuationUsageBudgetExhausted,
3999
4018
  usageBudget: config.usageBudget,
4000
4019
  orcaProgressTab,
4001
- }), config.deadlineAt);
4020
+ }), runRemainingMs);
4002
4021
  if (task.sessionFile) {
4003
4022
  latestSessionFile = task.sessionFile;
4004
4023
  }
@@ -4214,7 +4233,7 @@ export async function runSubagent(config, childSessions) {
4214
4233
  try {
4215
4234
  singleWorktreeSetup = await createWorktrees(cwd, `${id}-s${stepIndex}`, 1, omitUndefinedProperties({
4216
4235
  signal: setupSignal,
4217
- deadlineAt: config.deadlineAt,
4236
+ deadlineAt: runDeadlineAt(),
4218
4237
  agents: [seqStep.agent],
4219
4238
  labels: [seqStep.lane?.key ?? config.workflowKey ?? seqStep.outputName ?? seqStep.label],
4220
4239
  tasks: [seqStep.task],
@@ -4253,7 +4272,7 @@ export async function runSubagent(config, childSessions) {
4253
4272
  catch (error) {
4254
4273
  if (error instanceof WorktreeSetupError)
4255
4274
  publishSetupUnknown(error.snapshot);
4256
- if (config.deadlineAt !== undefined && Date.now() >= config.deadlineAt)
4275
+ if (runDeadlineExpired())
4257
4276
  timeoutRunner();
4258
4277
  const message = error instanceof Error ? error.message : String(error);
4259
4278
  if (childStopRequests.has(flatIndex))
@@ -4274,7 +4293,7 @@ export async function runSubagent(config, childSessions) {
4274
4293
  break;
4275
4294
  }
4276
4295
  }
4277
- if (singleWorktreeSetup && config.deadlineAt !== undefined && Date.now() >= config.deadlineAt)
4296
+ if (singleWorktreeSetup && runDeadlineExpired())
4278
4297
  timeoutRunner();
4279
4298
  if (singleWorktreeSetup && (timedOut || stopped || interrupted || childStopRequests.has(flatIndex))) {
4280
4299
  await cleanupRemainingWorktree(singleWorktreeSetup, stepIndex, flatIndex);
@@ -4350,7 +4369,7 @@ export async function runSubagent(config, childSessions) {
4350
4369
  usageBudgetExhausted: continuationUsageBudgetExhausted,
4351
4370
  usageBudget: config.usageBudget,
4352
4371
  orcaProgressTab,
4353
- }), config.deadlineAt);
4372
+ }), runRemainingMs);
4354
4373
  }
4355
4374
  catch (error) {
4356
4375
  if (singleWorktreeSetup)
@@ -4618,14 +4637,10 @@ export async function runSubagent(config, childSessions) {
4618
4637
  clearInterval(activityTimer);
4619
4638
  activityTimer = undefined;
4620
4639
  }
4621
- if (timeoutTimer) {
4622
- clearTimeout(timeoutTimer);
4623
- timeoutTimer = undefined;
4624
- }
4625
- if (checkpointTimer) {
4626
- clearTimeout(checkpointTimer);
4627
- checkpointTimer = undefined;
4628
- }
4640
+ timeoutTimer?.clear();
4641
+ timeoutTimer = undefined;
4642
+ checkpointTimer?.clear();
4643
+ checkpointTimer = undefined;
4629
4644
  if (!timedOut && !stopped && !interrupted && config.timeoutMs !== undefined && timeoutMessage !== undefined && results.some((result) => result.timedOut === true && result.error?.startsWith(timeoutMessage))) {
4630
4645
  timedOut = true;
4631
4646
  }
@@ -4664,7 +4679,7 @@ export async function runSubagent(config, childSessions) {
4664
4679
  continue;
4665
4680
  changed = true;
4666
4681
  const reason = target.state === "queued" ? unconsumedSteerReason() : "child terminated before steering delivery";
4667
- updateSteeringLifecycleTarget(request.id, target.index, "failed", Date.now(), { reason });
4682
+ updateSteeringLifecycleTarget(request.id, target.index, "failed", Date.now(), { reason, failureKind: "unconsumed" });
4668
4683
  markSteeringAttention(target.index);
4669
4684
  emitSteeringEvent("subagent.steer.failed", { type: "steer", id: request.id, ts: request.requestedAt, message: reason }, target.index, { reason });
4670
4685
  }
@@ -12,6 +12,9 @@ function steerTargetsAccepted(result) {
12
12
  const targets = result?.targets ?? [];
13
13
  return targets.length > 0 && targets.every((target) => target.state === "queued" || target.state === "delivered");
14
14
  }
15
+ function steerTargetsRejected(result) {
16
+ return result?.targets.some((target) => target.state === "failed" && target.failureKind === "rejected") === true;
17
+ }
15
18
  export function canQueueRetainedAsyncFollowUp(status, index) {
16
19
  const steps = status.steps ?? [];
17
20
  return status.state === "complete"
@@ -174,8 +177,10 @@ export async function steerAsyncRun(input) {
174
177
  if (input.signal?.aborted) {
175
178
  return { content: [{ type: "text", text: steeringReceipt(input.message, `Steering pending for async run ${status.runId} (request ${requestId}); caller aborted before recovery.`) }], details: { mode: "management", results: [], steering: result } };
176
179
  }
180
+ const projected = (current) => current?.steering ? actionResultFromSteeringStatus(current.steering, status.runId, requestId) : undefined;
181
+ const rejected = () => new Error(`Child rejected the guidance; continue it with action "resume" and id "${status.runId}".`);
177
182
  const finalStatus = readStatus(asyncDir);
178
- const finalResult = finalStatus?.steering ? actionResultFromSteeringStatus(finalStatus.steering, status.runId, requestId) : undefined;
183
+ const finalResult = projected(finalStatus);
179
184
  const acceptedReply = (accepted) => {
180
185
  const acceptedState = accepted.state === "delivered" ? "delivered" : "queued";
181
186
  return { content: [{ type: "text", text: steeringReceipt(input.message, `Steering ${acceptedState} for async run ${status.runId} (request ${requestId}).`) }], details: { mode: "management", results: [], steering: accepted } };
@@ -184,7 +189,7 @@ export async function steerAsyncRun(input) {
184
189
  return acceptedReply(finalResult);
185
190
  const running = (finalStatus?.steps ?? status.steps ?? []).filter((step) => step.status === "running");
186
191
  const recoveryAllowed = (input.mode ?? "steer") === "steer" && status.mode === "single" && status.isNested !== true && running.length === 1 && Boolean(finalStatus?.steering) && (input.index === undefined || input.index === 0);
187
- if (recoveryAllowed && finalResult?.state !== "scheduled" && input.recover) {
192
+ if (recoveryAllowed && finalResult?.state !== "scheduled" && !steerTargetsRejected(finalResult) && input.recover) {
188
193
  const appendSteeringNotice = (state, message) => {
189
194
  try {
190
195
  fs.appendFileSync(path.join(asyncDir, "events.jsonl"), `${JSON.stringify({ type: "subagent.steering.notice", ts: Date.now(), runId: status.runId, requestId, state, message, ...(status.sessionId ? { currentSessionId: status.sessionId } : {}) })}\n`);
@@ -194,21 +199,23 @@ export async function steerAsyncRun(input) {
194
199
  }
195
200
  };
196
201
  try {
197
- const latest = readStatus(asyncDir);
198
- const latestResult = latest?.steering ? actionResultFromSteeringStatus(latest.steering, status.runId, requestId) : undefined;
202
+ const latestResult = projected(readStatus(asyncDir));
199
203
  if (latestResult && steerTargetsAccepted(latestResult))
200
204
  return acceptedReply(latestResult);
205
+ if (steerTargetsRejected(latestResult))
206
+ throw rejected();
201
207
  const committedAt = Date.now();
202
208
  input.onBeforeRecoveryClaim?.(requestId, committedAt);
203
209
  const { claimPath, markerPath } = claimSteeringRecovery(asyncDir, { requestId, sourceRunId: status.runId, committedAt });
204
210
  input.onRecoveryCommitted?.(requestId, committedAt);
205
- const preCommitStatus = readStatus(asyncDir);
206
- const preCommitResult = preCommitStatus?.steering ? actionResultFromSteeringStatus(preCommitStatus.steering, status.runId, requestId) : undefined;
211
+ const preCommitResult = projected(readStatus(asyncDir));
207
212
  if (preCommitResult
208
- && preCommitResult.targets.length > 0
209
- && preCommitResult.targets.every((target) => target.state === "queued" || (target.deliveredAt !== undefined && target.deliveredAt <= committedAt))) {
213
+ && (steerTargetsRejected(preCommitResult) || (preCommitResult.targets.length > 0
214
+ && preCommitResult.targets.every((target) => target.state === "queued" || (target.deliveredAt !== undefined && target.deliveredAt <= committedAt))))) {
210
215
  fs.rmSync(markerPath, { force: true });
211
216
  fs.rmSync(claimPath, { force: true });
217
+ if (steerTargetsRejected(preCommitResult))
218
+ throw rejected();
212
219
  return acceptedReply(preCommitResult);
213
220
  }
214
221
  try {
@@ -228,6 +235,10 @@ export async function steerAsyncRun(input) {
228
235
  break;
229
236
  const candidate = readStatus(asyncDir);
230
237
  lastObservedState = candidate?.state;
238
+ if (steerTargetsRejected(projected(candidate))) {
239
+ fs.rmSync(claimPath, { force: true });
240
+ throw rejected();
241
+ }
231
242
  if (candidate?.state === "paused" && candidate.endedAt !== undefined) {
232
243
  paused = candidate;
233
244
  break;
@@ -252,6 +263,10 @@ export async function steerAsyncRun(input) {
252
263
  if (!recoveryTarget.recoveryDescriptor)
253
264
  throw new Error("Source run has no private recovery descriptor; it remains paused and is not safely resumable.");
254
265
  const limits = remainingSteeringRecoveryLimits(recoveryTarget.recoveryDescriptor, paused);
266
+ if (steerTargetsRejected(projected(readStatus(asyncDir)))) {
267
+ fs.rmSync(claimPath, { force: true });
268
+ throw rejected();
269
+ }
255
270
  const revived = await input.recover(limits);
256
271
  if (revived.isError || !revived.details.asyncId)
257
272
  throw new Error(revived.content[0]?.type === "text" ? revived.content[0].text : "Replacement launch failed; source run remains paused.");
@@ -279,7 +294,7 @@ export async function steerAsyncRun(input) {
279
294
  failedStatus.activityState = "needs_attention";
280
295
  writeAtomicJson(path.join(asyncDir, "status.json"), failedStatus);
281
296
  }
282
- const failed = failedStatus?.steering ? actionResultFromSteeringStatus(failedStatus.steering, status.runId, requestId) : undefined;
297
+ const failed = projected(failedStatus);
283
298
  appendSteeringNotice("failed", `Steering failed for run ${status.runId}: ${reason}`);
284
299
  return { content: [{ type: "text", text: steeringReceipt(input.message, `Steering failed for async run ${status.runId} (request ${requestId}): ${reason}`) }], isError: true, details: { mode: "management", results: [], steering: failed ?? { requestId, state: "failed", sourceRunId: status.runId, deliveryStatus: "queued", targets: [{ index: input.index ?? 0, state: "failed", reason }] } } };
285
300
  }