@vicary/pi-subagents 0.86.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 (122) hide show
  1. package/CHANGELOG.md +59 -0
  2. package/bundle/agents.js +3 -3
  3. package/bundle/child-tool-plan.js +2 -2
  4. package/bundle/{chunk-PYOAIN3V.js → chunk-2DIEL4WG.js} +2 -2
  5. package/bundle/{chunk-GJGTMLPE.js → chunk-3DT5X2QC.js} +483 -477
  6. package/bundle/{chunk-374MZFF4.js → chunk-3MFYKBKI.js} +23 -13
  7. package/bundle/{chunk-77ASNIEM.js → chunk-47ZN7NKR.js} +1 -1
  8. package/bundle/{chunk-QGO6HXHG.js → chunk-4MVDMA5C.js} +88 -64
  9. package/bundle/{chunk-3RKFH2UZ.js → chunk-6EUQPQY7.js} +31 -14
  10. package/bundle/{chunk-6VD7BGIC.js → chunk-6PR44R7E.js} +7 -2
  11. package/bundle/{chunk-DD22RXYJ.js → chunk-AOSILI5R.js} +200 -64
  12. package/bundle/{chunk-WHC2XHGF.js → chunk-BW5JLKIU.js} +174 -56
  13. package/bundle/{chunk-7ZUFN6ME.js → chunk-CKLZ5FGU.js} +2 -2
  14. package/bundle/{chunk-ZPY5QZCS.js → chunk-CYKNHFXB.js} +1 -1
  15. package/bundle/{chunk-YK3QYNLE.js → chunk-GDR2ILWY.js} +1 -1
  16. package/bundle/{chunk-7QA7ZA46.js → chunk-IZEKQEY4.js} +9 -9
  17. package/bundle/{chunk-CJHFDQFJ.js → chunk-JYHTDTOZ.js} +10 -6
  18. package/bundle/{chunk-NAFLUJ26.js → chunk-KXW62VBU.js} +1 -1
  19. package/bundle/{chunk-S2Q75LP3.js → chunk-L4YY2TOE.js} +1 -1
  20. package/bundle/{chunk-2DITXA3H.js → chunk-NVGQE2H2.js} +12 -12
  21. package/bundle/{chunk-BU6PFPVX.js → chunk-PJSOS2Q4.js} +12 -7
  22. package/bundle/{chunk-UR7OW5S7.js → chunk-RHYVKQQL.js} +11 -5
  23. package/bundle/{chunk-BGXEAYUM.js → chunk-SVIXQDIV.js} +20 -5
  24. package/bundle/{chunk-GLVJMI6R.js → chunk-TDJKY2NE.js} +14 -5
  25. package/bundle/{chunk-XOFYXQKZ.js → chunk-V7SZMS6W.js} +2 -2
  26. package/bundle/{chunk-NF7IEKBH.js → chunk-W2BZS6UC.js} +27 -13
  27. package/bundle/{chunk-5H4BICQZ.js → chunk-W6HIYD2Z.js} +1 -1
  28. package/bundle/{chunk-LGINOOY5.js → chunk-XIA5GSEU.js} +2 -2
  29. package/bundle/{chunk-QFLPV64W.js → chunk-XZXYPZUT.js} +46 -32
  30. package/bundle/chunk-YDZ7BZD5.js +523 -0
  31. package/bundle/{chunk-WN2E5XHN.js → chunk-YZPVALSQ.js} +30 -5
  32. package/bundle/control-channel.js +2 -2
  33. package/bundle/index.js +1 -1
  34. package/bundle/intercom-bridge.js +2 -2
  35. package/bundle/preflight.js +12 -10
  36. package/bundle/project-panes.js +3 -3
  37. package/bundle/workflow-resources.js +1 -1
  38. package/docs/agents.md +4 -4
  39. package/docs/configuration.md +14 -4
  40. package/docs/extension-api.md +2 -0
  41. package/docs/models.md +6 -2
  42. package/docs/observability.md +2 -0
  43. package/docs/tool-reference.md +5 -1
  44. package/package.json +3 -3
  45. package/skills/pi-subagents/SKILL.md +15 -6
  46. package/skills/pi-subagents/references/prompting-and-roles.md +1 -0
  47. package/src/agents/agent-management.d.ts +1 -0
  48. package/src/agents/agent-management.js +22 -10
  49. package/src/agents/agent-serializer.d.ts +2 -0
  50. package/src/agents/agent-serializer.js +1 -1
  51. package/src/agents/agents.d.ts +1 -0
  52. package/src/agents/agents.js +39 -14
  53. package/src/api/preflight.d.ts +3 -1
  54. package/src/api/preflight.js +2 -0
  55. package/src/extension/config.d.ts +9 -0
  56. package/src/extension/config.js +13 -0
  57. package/src/extension/index.js +8 -5
  58. package/src/extension/schemas.d.ts +4 -0
  59. package/src/extension/schemas.js +2 -0
  60. package/src/extension/tool-activation.js +20 -3
  61. package/src/runs/background/async-execution.d.ts +2 -1
  62. package/src/runs/background/async-execution.js +4 -2
  63. package/src/runs/background/async-resume.js +2 -1
  64. package/src/runs/background/async-retention.d.ts +0 -2
  65. package/src/runs/background/async-retention.js +11 -5
  66. package/src/runs/background/async-status.d.ts +2 -0
  67. package/src/runs/background/async-status.js +4 -0
  68. package/src/runs/background/run-child-session.d.ts +2 -2
  69. package/src/runs/background/run-child-session.js +4 -7
  70. package/src/runs/background/runner-aliases.js +15 -0
  71. package/src/runs/background/steering.d.ts +2 -11
  72. package/src/runs/background/steering.js +11 -6
  73. package/src/runs/background/subagent-runner.d.ts +0 -2
  74. package/src/runs/background/subagent-runner.js +73 -58
  75. package/src/runs/background/wait-subscriptions.js +124 -12
  76. package/src/runs/foreground/async-steering-action.js +24 -9
  77. package/src/runs/foreground/async-stop-action.d.ts +1 -1
  78. package/src/runs/foreground/async-stop-action.js +9 -1
  79. package/src/runs/foreground/execution.js +33 -15
  80. package/src/runs/foreground/prompt-audit.js +1 -0
  81. package/src/runs/foreground/subagent-executor.d.ts +2 -8
  82. package/src/runs/foreground/subagent-executor.js +57 -23
  83. package/src/runs/shared/async-status-projection.d.ts +2 -0
  84. package/src/runs/shared/async-status-projection.js +10 -0
  85. package/src/runs/shared/child-session.d.ts +5 -4
  86. package/src/runs/shared/child-session.js +64 -36
  87. package/src/runs/shared/herdr-placed-run.js +3 -2
  88. package/src/runs/shared/mcp-config-sources.d.ts +4 -1
  89. package/src/runs/shared/mcp-config-sources.js +1 -1
  90. package/src/runs/shared/mcp-direct-tool-allowlist.d.ts +0 -3
  91. package/src/runs/shared/mcp-direct-tool-allowlist.js +26 -17
  92. package/src/runs/shared/model-resolution.d.ts +19 -4
  93. package/src/runs/shared/model-resolution.js +50 -51
  94. package/src/runs/shared/subagent-prompt-runtime.js +14 -2
  95. package/src/runs/shared/supervisor-wait-timer.d.ts +16 -0
  96. package/src/runs/shared/supervisor-wait-timer.js +61 -0
  97. package/src/shared/artifacts.d.ts +1 -0
  98. package/src/shared/artifacts.js +132 -22
  99. package/src/shared/pruned-fork.js +2 -2
  100. package/src/shared/reported-progress.d.ts +1 -0
  101. package/src/shared/reported-progress.js +12 -0
  102. package/src/shared/status-format.d.ts +1 -0
  103. package/src/shared/status-format.js +1 -1
  104. package/src/shared/types.d.ts +23 -0
  105. package/src/shared/utils.d.ts +3 -1
  106. package/src/shared/utils.js +4 -0
  107. package/src/tui/render.js +33 -2
  108. package/src/watchdog/model-selection.js +2 -2
  109. package/src/watchdog/permission-arbiter.js +1 -0
  110. package/src/watchdog/review.d.ts +0 -5
  111. package/src/watchdog/review.js +4 -3
  112. package/src/workflows/scripted-workflow.d.ts +2 -0
  113. package/src/workflows/scripted-workflow.js +103 -39
  114. package/src/workflows/structured-workflow-scripts.d.ts +4 -3
  115. package/src/workflows/structured-workflow-scripts.js +32 -11
  116. package/src/workflows/workflow-resources.js +4 -4
  117. package/src/workflows/workflow-resume-claim.d.ts +2 -0
  118. package/src/workflows/workflow-resume-claim.js +1 -1
  119. package/src/workflows/workflow-resume.d.ts +1 -1
  120. package/src/workflows/workflow-resume.js +3 -1
  121. package/src/workflows/workflow-script-worker.js +3 -1
  122. package/bundle/chunk-GRJHIXYF.js +0 -235
@@ -1,12 +1,16 @@
1
1
  import * as fs from "node:fs";
2
2
  import * as path from "node:path";
3
- import { randomUUID } from "node:crypto";
3
+ import { createHash, randomUUID } from "node:crypto";
4
4
  import { listAsyncRuns } from "./async-status.js";
5
5
  import { formatResumeFirstFailedRunDetail } from "./resume-guidance.js";
6
6
  import { readCompletionReplay } from "./completion-replay.js";
7
7
  import { writeAtomicJson } from "../../shared/atomic-json.js";
8
8
  import { COMPLETION_ACTION, STATUS_ACTION } from "../../shared/parent-wake.js";
9
9
  import { DIRS, INTERCOM_DETACH_REQUEST_EVENT, SUBAGENT_ASYNC_COMPLETE_EVENT, SUBAGENT_CONTROL_EVENT, SUBAGENT_CONTROL_INTERCOM_EVENT, SUBAGENT_FOREGROUND_COMPLETE_EVENT, SUBAGENT_RESULT_INTERCOM_EVENT, } from "../../shared/types.js";
10
+ import { currentBootId, currentRecordedPid } from "./boot-id.js";
11
+ import { currentPidNamespaceScope } from "./pid-namespace.js";
12
+ import { checkRecordedPidLiveness, isRecordedPid } from "./stale-run-reconciler.js";
13
+ import { createClaimFile } from "../../workflows/workflow-resume-claim.js";
10
14
  const SUBSCRIPTION_VERSION = 1;
11
15
  // Outcomes that report no saved results, so the notice points the parent at the run status instead.
12
16
  const STATUS_OUTCOMES = new Set(["timed out", "could not be reconciled", "needs attention", "reconciliation failed"]);
@@ -36,6 +40,8 @@ function parseRecord(value) {
36
40
  || typeof record.token !== "string"
37
41
  || !/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(record.token)
38
42
  || typeof record.sessionId !== "string"
43
+ || (record.completionOwnerId !== undefined && typeof record.completionOwnerId !== "string")
44
+ || (record.completionOwnerProcess !== undefined && !isRecordedPid(record.completionOwnerProcess))
39
45
  || (record.targetKind !== "async" && record.targetKind !== "foreground")
40
46
  || typeof record.runId !== "string"
41
47
  || typeof record.requestedId !== "string"
@@ -50,6 +56,40 @@ function needsAttention(run) {
50
56
  function subscriptionFile(dir, token) {
51
57
  return path.join(dir, `${token}.json`);
52
58
  }
59
+ /**
60
+ * Takeover claims are `<token>.claim-<owner hash>.<generation>`, not `.json`, so record scans skip them.
61
+ * Each generation is created exclusively, so one process takes over from a dead owner per generation;
62
+ * a dead claimant's generation is superseded by the next one.
63
+ */
64
+ function claimPrefix(token, replacedOwnerId) {
65
+ return `${token}.claim-${createHash("sha256").update(replacedOwnerId).digest("hex").slice(0, 16)}.`;
66
+ }
67
+ function latestClaimGeneration(files, prefix) {
68
+ let latest = 0;
69
+ for (const file of files) {
70
+ const generation = file.startsWith(prefix) ? file.slice(prefix.length) : "";
71
+ // Exact digits only: leftover `<claim>.<pid>.<uuid>.tmp` files from a crashed create are not generations.
72
+ if (/^[1-9][0-9]*$/.test(generation))
73
+ latest = Math.max(latest, Number(generation));
74
+ }
75
+ return latest;
76
+ }
77
+ /**
78
+ * Call only after the record file is gone, so a late claimer that wins a freed claim finds no record to bring back.
79
+ * Never throws: a leftover claim cannot bring a removed record back.
80
+ */
81
+ function removeClaimFiles(dir, token) {
82
+ try {
83
+ for (const file of fs.readdirSync(dir)) {
84
+ if (file.startsWith(`${token}.claim-`))
85
+ fs.rmSync(path.join(dir, file), { force: true });
86
+ }
87
+ }
88
+ catch (error) {
89
+ if (!isNotFound(error))
90
+ console.error(`Failed to remove claims of wait subscription '${token}':`, error);
91
+ }
92
+ }
53
93
  export function formatWaitSubscriptions(state, now = Date.now()) {
54
94
  const subscriptions = [...(state.waitSubscriptions?.values() ?? [])].sort((left, right) => left.createdAt - right.createdAt);
55
95
  if (subscriptions.length === 0)
@@ -71,6 +111,64 @@ export function createWaitSubscriptionManager(pi, state, options = {}) {
71
111
  let disposed = false;
72
112
  let interval;
73
113
  let lastForeignSweepAt = 0;
114
+ const readRecordFile = (filePath) => {
115
+ try {
116
+ return parseRecord(JSON.parse(fs.readFileSync(filePath, "utf-8")));
117
+ }
118
+ catch (error) {
119
+ if (isNotFound(error))
120
+ return undefined;
121
+ throw error;
122
+ }
123
+ };
124
+ const isDead = (recorded) => recorded !== undefined && checkRecordedPidLiveness(recorded, {
125
+ observedScope: currentPidNamespaceScope(),
126
+ observedBootId: currentBootId(),
127
+ kill: options.kill,
128
+ }) === "dead";
129
+ const latestClaimantHolds = (claimPath) => {
130
+ let body;
131
+ try {
132
+ body = JSON.parse(fs.readFileSync(claimPath, "utf-8"));
133
+ }
134
+ catch (error) {
135
+ // Claims are created whole, so a body that does not parse is damage; a claim that cannot be read counts as held.
136
+ return !(error instanceof SyntaxError);
137
+ }
138
+ const claimant = body?.process;
139
+ return isRecordedPid(claimant) && !isDead(claimant);
140
+ };
141
+ // Two Pi processes can share one session. The arming process owns the wake while it lives;
142
+ // after it dies, the next process to open the session claims the record and becomes its owner.
143
+ const claimRecord = (filePath, record) => {
144
+ if (!record.completionOwnerId || record.completionOwnerId === state.completionOwnerId)
145
+ return record;
146
+ if (!isDead(record.completionOwnerProcess))
147
+ return undefined;
148
+ if (!state.completionOwnerId)
149
+ return record;
150
+ const prefix = claimPrefix(record.token, record.completionOwnerId);
151
+ const latest = latestClaimGeneration(fs.readdirSync(subscriptionsDir), prefix);
152
+ if (latest > 0 && latestClaimantHolds(path.join(subscriptionsDir, `${prefix}${latest}`)))
153
+ return undefined;
154
+ const claimPath = path.join(subscriptionsDir, `${prefix}${latest + 1}`);
155
+ if (!createClaimFile(claimPath, { ownerId: state.completionOwnerId, process: currentRecordedPid() }))
156
+ return undefined;
157
+ try {
158
+ // The record may have been settled (and its claims removed) after this process first read it.
159
+ if (readRecordFile(filePath)?.completionOwnerId !== record.completionOwnerId) {
160
+ fs.rmSync(claimPath, { force: true });
161
+ return undefined;
162
+ }
163
+ const claimed = { ...record, completionOwnerId: state.completionOwnerId, completionOwnerProcess: currentRecordedPid() };
164
+ writeAtomicJson(filePath, claimed);
165
+ return claimed;
166
+ }
167
+ catch (error) {
168
+ fs.rmSync(claimPath, { force: true });
169
+ throw error;
170
+ }
171
+ };
74
172
  /**
75
173
  * Remove expired records armed by another session.
76
174
  *
@@ -109,7 +207,7 @@ export function createWaitSubscriptionManager(pi, state, options = {}) {
109
207
  const filePath = path.join(subscriptionsDir, file);
110
208
  let record;
111
209
  try {
112
- record = parseRecord(JSON.parse(fs.readFileSync(filePath, "utf-8")));
210
+ record = readRecordFile(filePath);
113
211
  }
114
212
  catch (error) {
115
213
  console.error(`Ignoring invalid wait subscription '${filePath}':`, error);
@@ -130,27 +228,36 @@ export function createWaitSubscriptionManager(pi, state, options = {}) {
130
228
  // Losing this race is harmless: another session may have swept the
131
229
  // same expired record. Anything else is reported and retried on the
132
230
  // next sweep rather than interrupting the caller.
133
- if (!isNotFound(error))
231
+ if (!isNotFound(error)) {
134
232
  console.error(`Failed to remove expired wait subscription '${filePath}':`, error);
233
+ continue;
234
+ }
135
235
  }
236
+ removeClaimFiles(subscriptionsDir, record.token);
136
237
  }
137
238
  };
138
239
  const remove = (record) => {
240
+ let removed = true;
139
241
  try {
140
242
  fs.unlinkSync(subscriptionFile(subscriptionsDir, record.token));
141
243
  }
142
244
  catch (error) {
143
245
  if (!isNotFound(error))
144
246
  throw error;
247
+ removed = false;
145
248
  }
146
249
  subscriptions.delete(record.token);
147
250
  unresolvedRestoredForegroundTokens.delete(record.token);
251
+ removeClaimFiles(subscriptionsDir, record.token);
252
+ return removed;
148
253
  };
149
254
  const settle = (record, outcome, detail, completion) => {
150
255
  if (disposed || state.currentSessionId !== record.sessionId)
151
256
  return;
152
257
  try {
153
- remove(record);
258
+ // Only the process that removes the record may deliver its wake.
259
+ if (!remove(record))
260
+ return;
154
261
  }
155
262
  catch (error) {
156
263
  console.error(`Failed to clear wait subscription '${record.token}'; it remains armed:`, error);
@@ -274,6 +381,7 @@ export function createWaitSubscriptionManager(pi, state, options = {}) {
274
381
  version: SUBSCRIPTION_VERSION,
275
382
  token: randomUUID(),
276
383
  sessionId,
384
+ ...(state.completionOwnerId ? { completionOwnerId: state.completionOwnerId, completionOwnerProcess: currentRecordedPid() } : {}),
277
385
  targetKind: input.targetKind,
278
386
  runId: input.runId,
279
387
  requestedId: input.requestedId,
@@ -303,19 +411,23 @@ export function createWaitSubscriptionManager(pi, state, options = {}) {
303
411
  throw error;
304
412
  }
305
413
  for (const file of files) {
414
+ const filePath = path.join(subscriptionsDir, file);
415
+ let record;
306
416
  try {
307
- const record = parseRecord(JSON.parse(fs.readFileSync(path.join(subscriptionsDir, file), "utf-8")));
308
- if (!record || file !== `${record.token}.json`)
417
+ const found = readRecordFile(filePath);
418
+ if (!found || file !== `${found.token}.json` || found.sessionId !== state.currentSessionId)
309
419
  continue;
310
- if (record.sessionId === state.currentSessionId) {
311
- subscriptions.set(record.token, record);
312
- if (record.targetKind === "foreground" && !state.foregroundRuns?.has(record.runId))
313
- unresolvedRestoredForegroundTokens.add(record.token);
314
- }
420
+ record = claimRecord(filePath, found);
315
421
  }
316
422
  catch (error) {
317
- console.error(`Ignoring invalid wait subscription '${path.join(subscriptionsDir, file)}':`, error);
423
+ console.error(`Failed to restore wait subscription '${filePath}':`, error);
424
+ continue;
318
425
  }
426
+ if (!record)
427
+ continue;
428
+ subscriptions.set(record.token, record);
429
+ if (record.targetKind === "foreground" && !state.foregroundRuns?.has(record.runId))
430
+ unresolvedRestoredForegroundTokens.add(record.token);
319
431
  }
320
432
  reconcile();
321
433
  },
@@ -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
  }
@@ -10,4 +10,4 @@ export declare function stopAsyncRun(state: SubagentState, runId: string | undef
10
10
  asyncDir: string | null;
11
11
  resolvedId?: string;
12
12
  reattachedRunId?: string;
13
- }, childId?: string): AgentToolResult<Details> | null;
13
+ }, childId?: string, drain?: boolean): AgentToolResult<Details> | null;
@@ -130,7 +130,7 @@ export function deliverAsyncRunStop(input) {
130
130
  if (pausedWholeRun)
131
131
  return sealPausedRun(delivery.asyncDir, status, resultsDir);
132
132
  }
133
- export function stopAsyncRun(state, runId, kill, location, childId) {
133
+ export function stopAsyncRun(state, runId, kill, location, childId, drain) {
134
134
  const target = getAsyncStopTarget(state, runId, location);
135
135
  // An async workflow runs in this process: it has no runner to read a stop request, so stop it through its controller.
136
136
  const workflowRunId = target?.asyncId ?? runId;
@@ -139,6 +139,14 @@ export function stopAsyncRun(state, runId, kill, location, childId) {
139
139
  const workflowStatus = workflowAsyncDir ? readStatus(workflowAsyncDir) : undefined;
140
140
  // Controllers outlive a session switch; a workflow owned by another session falls through to the ownership check below.
141
141
  const foreignWorkflow = Boolean(state.currentSessionId && workflowStatus && workflowStatus.sessionId !== state.currentSessionId);
142
+ if (drain) {
143
+ const drained = workflowController && workflowRunId && !foreignWorkflow && !workflowController.signal.aborted ? state.workflowDrains?.get(workflowRunId)?.() : undefined;
144
+ if (!drained)
145
+ return { content: [{ type: "text", text: `drain applies only to live async workflows in this session; '${runId ?? "current"}' is not one.` }], isError: true, details: { mode: "management", results: [] } };
146
+ if (!drained.ok)
147
+ return { content: [{ type: "text", text: `Could not save the drain request for '${workflowRunId}'; nothing was stopped. Retry, or use stop without drain.` }], isError: true, details: { mode: "management", results: [] } };
148
+ return { content: [{ type: "text", text: `Drain requested for async workflow ${workflowRunId}: no new children will start; ${drained.started} started child(ren) will finish.` }], details: { mode: "management", results: [] } };
149
+ }
142
150
  if (workflowController && workflowRunId && !foreignWorkflow) {
143
151
  if (workflowStatus)
144
152
  stopStoppableAsyncStatusChildren(workflowStatus, state.workflowChildStops?.get(workflowRunId), "Workflow stopped.");
@@ -5,9 +5,10 @@ import { alignForkedSessionCwd } from "../../shared/fork-session-cwd.js";
5
5
  import { buildEffectiveSystemPrompt } from "../shared/effective-system-prompt.js";
6
6
  import { ensureArtifactsDir, formatOutputArtifactContent, getArtifactPaths, writeArtifact, writeMetadata, } from "../../shared/artifacts.js";
7
7
  import { createChildTranscriptWriter } from "../../shared/child-transcript.js";
8
+ import { extractReportedProgress } from "../../shared/reported-progress.js";
8
9
  import { DEFAULT_MAX_OUTPUT, INTERCOM_DETACH_REQUEST_EVENT, INTERCOM_DETACH_RESPONSE_EVENT, truncateOutput, } from "../../shared/types.js";
9
10
  import { DEFAULT_CONTROL_CONFIG, buildControlEvent, claimControlNotification, deriveActivityState, shouldEmitOpenToolAttention, shouldNotifyControlEvent, } from "../shared/subagent-control.js";
10
- import { getFinalOutput, findLatestSessionFile, detectSubagentError, hasEmptyTerminalAssistantResponse, formatEmptyTerminalAssistantResponseError, extractToolArgsPreview, assistantMessageError, extractTextFromContent, MAX_STREAMED_RECENT_TOOLS, boundStreamedRecentTools, boundStreamedRecentOutput, boundStreamedToolCalls, } from "../../shared/utils.js";
11
+ import { getFinalOutput, findLatestSessionFile, detectSubagentError, hasEmptyTerminalAssistantResponse, formatEmptyTerminalAssistantResponseError, getTerminalAssistantStopReason, TRUNCATED_RESPONSE_ERROR, extractToolArgsPreview, assistantMessageError, extractTextFromContent, MAX_STREAMED_RECENT_TOOLS, boundStreamedRecentTools, boundStreamedRecentOutput, boundStreamedToolCalls, } from "../../shared/utils.js";
11
12
  import { resolveSkillsWithFallback } from "../../agents/skills.js";
12
13
  import { createPartialOutputTracker, formatPartialOutput } from "../shared/partial-output.js";
13
14
  import { effectiveToolTimeoutMs, formatToolTimeoutMessage, resolveToolTimeoutMs, toolTimeoutCallKey, toolTimeoutFromEnv } from "../shared/tool-timeout.js";
@@ -44,6 +45,7 @@ import { childSessionFactory, childSessionHasQueuedMessages, projectChildSession
44
45
  import { reconcileAttemptUsage } from "../shared/usage-reconciliation.js";
45
46
  import { clearProviderRetry, observeProviderDiagnostics, snapshotProviderDiagnostics } from "../../shared/provider-diagnostics.js";
46
47
  import { isRexLocalMachine } from "../shared/rex-machine.js";
48
+ import { pauseForSupervisorWait, startPausableTimer } from "../shared/supervisor-wait-timer.js";
47
49
  const artifactOutputByResult = new WeakMap();
48
50
  const acceptanceOutputByResult = new WeakMap();
49
51
  function emptyUsage() {
@@ -205,6 +207,8 @@ function captureStructuredDelegationProgressState(progress, result) {
205
207
  recentOutput: [...progress.recentOutput],
206
208
  recentTools: progress.recentTools.slice(-MAX_STREAMED_RECENT_TOOLS).map(({ tool, args }) => ({ tool, args })),
207
209
  activityState: progress.activityState,
210
+ progressText: progress.progressText,
211
+ progressUpdatedAt: progress.progressUpdatedAt,
208
212
  model: progress.model ?? result.model,
209
213
  toolCount: progress.toolCount,
210
214
  tokens: progress.tokens,
@@ -217,6 +221,8 @@ function structuredDelegationProgressChanged(previous, progress, result) {
217
221
  || previous.currentTool !== progress.currentTool
218
222
  || previous.currentToolArgs !== progress.currentToolArgs
219
223
  || previous.activityState !== progress.activityState
224
+ || previous.progressText !== progress.progressText
225
+ || previous.progressUpdatedAt !== progress.progressUpdatedAt
220
226
  || previous.model !== (progress.model ?? result.model)
221
227
  || previous.toolCount !== progress.toolCount
222
228
  || previous.tokens !== progress.tokens
@@ -243,6 +249,7 @@ function isCompleteUsageCounter(value) {
243
249
  }
244
250
  const STOPPED_BEFORE_COMPLETION_ERROR = "Subagent stopped before completion.";
245
251
  const AFTER_COMPACTION_SETTLEMENT = Symbol("afterCompactionSettlement");
252
+ const REMAINING_TIMEOUT_MS = Symbol("remainingTimeoutMs");
246
253
  async function runSingleAttempt(runtimeCwd, agent, task, model, options, shared) {
247
254
  const effectiveThinking = options.thinkingOverride ?? agent.thinking;
248
255
  const modelArg = applyThinkingSuffix(model, effectiveThinking, options.thinkingOverride !== undefined);
@@ -447,6 +454,7 @@ async function runSingleAttempt(runtimeCwd, agent, task, model, options, shared)
447
454
  let toolAvailabilityError;
448
455
  let abortedBySignal = options.signal?.aborted === true;
449
456
  let afterCompactionSettlement = false;
457
+ let remainingTimeoutMs;
450
458
  if (options.workflowChildPermitLaunch) {
451
459
  const permitError = consumeWorkflowChildPermit(options.workflowChildPermitLaunch.permit, {
452
460
  workflowRunId: options.workflowChildPermitLaunch.workflowRunId,
@@ -486,7 +494,8 @@ async function runSingleAttempt(runtimeCwd, agent, task, model, options, shared)
486
494
  let timeoutHardFinishTimer;
487
495
  const clearTimeoutTimers = () => {
488
496
  if (timeoutTimer) {
489
- clearTimeout(timeoutTimer);
497
+ remainingTimeoutMs = timeoutTimer.remainingMs();
498
+ timeoutTimer.clear();
490
499
  timeoutTimer = undefined;
491
500
  }
492
501
  if (timeoutHardFinishTimer) {
@@ -1020,6 +1029,7 @@ async function runSingleAttempt(runtimeCwd, agent, task, model, options, shared)
1020
1029
  progress.durationMs = now - startTime;
1021
1030
  progress.lastActivityAt = now;
1022
1031
  updateActivityState(now);
1032
+ pauseForSupervisorWait(timeoutTimer, evt);
1023
1033
  if (evt.type === "tool_execution_start") {
1024
1034
  const toolArgs = evt.args && typeof evt.args === "object" && !Array.isArray(evt.args)
1025
1035
  ? evt.args
@@ -1039,7 +1049,7 @@ async function runSingleAttempt(runtimeCwd, agent, task, model, options, shared)
1039
1049
  result.toolBudget = toolBudgetState(options.toolBudget, progress.toolCount, result.toolBudget?.blockedTool);
1040
1050
  }
1041
1051
  const mutates = isMutatingTool(evt.toolName, toolArgs, agent.mutationTools);
1042
- pendingToolResult = { tool: evt.toolName ?? "tool", path: activeTool?.path, mutates, startedAt: now };
1052
+ pendingToolResult = { tool: evt.toolName ?? "tool", path: activeTool?.path, mutates, startedAt: now, progressText: extractReportedProgress(evt.toolName ?? "", evt.args) };
1043
1053
  if (typeof evt.toolCallId === "string" && evt.toolCallId)
1044
1054
  pendingToolResultsByCallId.set(evt.toolCallId, pendingToolResult);
1045
1055
  fireUpdate();
@@ -1140,6 +1150,10 @@ async function runSingleAttempt(runtimeCwd, agent, task, model, options, shared)
1140
1150
  result.toolBudget = toolBudgetState(options.toolBudget, Math.max(progress.toolCount, options.toolBudget.hard + 1), blockedTool);
1141
1151
  }
1142
1152
  appendRecentOutput(progress, resultText.split("\n").slice(-10));
1153
+ if (evt.message.isError !== true && resultToolName === toolSnapshot?.tool && toolSnapshot?.progressText) {
1154
+ progress.progressText = toolSnapshot.progressText;
1155
+ progress.progressUpdatedAt = now;
1156
+ }
1143
1157
  // A budget block has its own signal; it is not a failing mutation.
1144
1158
  if (toolSnapshot?.mutates && !budgetBlocked && didMutatingToolFail(evt.message)) {
1145
1159
  recordMutatingFailure(mutatingFailures, {
@@ -1180,7 +1194,7 @@ async function runSingleAttempt(runtimeCwd, agent, task, model, options, shared)
1180
1194
  activityTimer.unref?.();
1181
1195
  }
1182
1196
  if (attemptTimeout) {
1183
- timeoutTimer = setTimeout(() => {
1197
+ timeoutTimer = startPausableTimer(attemptTimeout.remainingMs, () => {
1184
1198
  if (sessionSettled || lifecycleFinished || interruptedByControl || result.timedOut)
1185
1199
  return;
1186
1200
  result.timedOut = true;
@@ -1199,8 +1213,7 @@ async function runSingleAttempt(runtimeCwd, agent, task, model, options, shared)
1199
1213
  settle(undefined, true);
1200
1214
  }, 4000);
1201
1215
  timeoutHardFinishTimer.unref?.();
1202
- }, attemptTimeout.remainingMs);
1203
- timeoutTimer.unref?.();
1216
+ });
1204
1217
  }
1205
1218
  let toolTimeoutSequence = 0;
1206
1219
  const activeToolTimeouts = new Map();
@@ -1240,7 +1253,7 @@ async function runSingleAttempt(runtimeCwd, agent, task, model, options, shared)
1240
1253
  const terminateForToolTimeout = (message) => {
1241
1254
  if (sessionSettled || lifecycleFinished || interruptedByControl || result.timedOut)
1242
1255
  return;
1243
- clearTimeout(timeoutTimer);
1256
+ timeoutTimer?.clear();
1244
1257
  result.timedOut = true;
1245
1258
  timeoutCause = message;
1246
1259
  result.error = message;
@@ -1261,10 +1274,6 @@ async function runSingleAttempt(runtimeCwd, agent, task, model, options, shared)
1261
1274
  const timeoutForTool = effectiveToolTimeoutMs(event.toolName, options.toolTimeoutMs);
1262
1275
  if (timeoutForTool === undefined)
1263
1276
  return;
1264
- const elapsed = Date.now() - startTime;
1265
- const runRemaining = attemptTimeout ? Math.max(0, attemptTimeout.remainingMs - elapsed) : undefined;
1266
- if (runRemaining !== undefined && timeoutForTool >= runRemaining)
1267
- return;
1268
1277
  const key = toolTimeoutCallKey(event, ++toolTimeoutSequence);
1269
1278
  const toolName = event.toolName;
1270
1279
  const timer = setTimeout(() => {
@@ -1413,14 +1422,14 @@ async function runSingleAttempt(runtimeCwd, agent, task, model, options, shared)
1413
1422
  const steer = created.steer.bind(created);
1414
1423
  const followUp = created.followUp.bind(created);
1415
1424
  created.steer = async (text) => {
1425
+ await steer(text);
1416
1426
  if (cleanTerminalAssistantStopReceived || agentSettledReceived)
1417
1427
  queuedDrainHold = true;
1418
- return steer(text);
1419
1428
  };
1420
1429
  created.followUp = async (text) => {
1430
+ await followUp(text);
1421
1431
  if (cleanTerminalAssistantStopReceived || agentSettledReceived)
1422
1432
  queuedDrainHold = true;
1423
- return followUp(text);
1424
1433
  };
1425
1434
  created.detached = detached;
1426
1435
  unsubscribe = created.subscribe((event) => processEvent(event));
@@ -1469,9 +1478,9 @@ async function runSingleAttempt(runtimeCwd, agent, task, model, options, shared)
1469
1478
  result.exitCode = exitCode;
1470
1479
  result.providerDiagnostics = clearProviderRetry(result.providerDiagnostics);
1471
1480
  progress.providerDiagnostics = result.providerDiagnostics;
1472
- if (afterCompactionSettlement) {
1481
+ if (afterCompactionSettlement)
1473
1482
  result[AFTER_COMPACTION_SETTLEMENT] = true;
1474
- }
1483
+ result[REMAINING_TIMEOUT_MS] = remainingTimeoutMs;
1475
1484
  if (interruptedByControl) {
1476
1485
  result.exitCode = 0;
1477
1486
  result.interrupted = true;
@@ -1546,6 +1555,10 @@ async function runSingleAttempt(runtimeCwd, agent, task, model, options, shared)
1546
1555
  ? `${errInfo.errorType} failed (exit ${errInfo.exitCode}): ${errInfo.details}`
1547
1556
  : `${errInfo.errorType} failed with exit code ${errInfo.exitCode}`;
1548
1557
  }
1558
+ else if (!validatedStructuredOutput && getTerminalAssistantStopReason(messages) === "length") {
1559
+ result.exitCode = 1;
1560
+ result.error = TRUNCATED_RESPONSE_ERROR;
1561
+ }
1549
1562
  }
1550
1563
  progress.status = result.exitCode === 0 ? "completed" : "failed";
1551
1564
  progress.durationMs = Date.now() - startTime;
@@ -1796,6 +1809,7 @@ async function runSyncCompletionInner(runtimeCwd, agents, agentName, task, optio
1796
1809
  scope: options.modelScope,
1797
1810
  primaryModelFromParent: options.modelOverrideFromParent,
1798
1811
  origin: options.modelOrigin ?? (options.modelOverrideFromParent ? "inherited" : "configured"),
1812
+ knownProviders: options.knownProviders,
1799
1813
  });
1800
1814
  try {
1801
1815
  const model = applyThinkingSuffix(selectedModel, options.thinkingOverride ?? agent.thinking, options.thinkingOverride !== undefined);
@@ -1944,6 +1958,10 @@ async function runSyncCompletionInner(runtimeCwd, agents, agentName, task, optio
1944
1958
  });
1945
1959
  if (recovery.action === "resume") {
1946
1960
  recoveryPrompt = recovery.prompt;
1961
+ // The retry gets the budget the first attempt left, so that attempt's supervisor waits stay uncounted.
1962
+ const remainingMs = attemptResult[REMAINING_TIMEOUT_MS];
1963
+ if (remainingMs !== undefined)
1964
+ attemptOptions.deadlineAt = Date.now() + remainingMs;
1947
1965
  attemptNotes.push("[abort-recovery] compaction abort after useful progress; resuming the retained child session once on the same model.");
1948
1966
  continue;
1949
1967
  }
@@ -49,6 +49,7 @@ export async function rewritePromptWithGuidance(input) {
49
49
  });
50
50
  const ctxThinking = input.ctx.getThinkingLevel?.();
51
51
  const agent = new Agent({
52
+ sessionId,
52
53
  initialState: {
53
54
  systemPrompt: [
54
55
  "Rewrite one subagent authored task from Prompt Audit context.",
@@ -47,6 +47,7 @@ export interface SubagentParamsLike {
47
47
  index?: number;
48
48
  toolCallId?: string;
49
49
  childId?: string;
50
+ drain?: boolean;
50
51
  view?: "fleet" | "transcript";
51
52
  lines?: number;
52
53
  topic?: string;
@@ -57,6 +58,7 @@ export interface SubagentParamsLike {
57
58
  agent?: string;
58
59
  task?: string;
59
60
  capabilities?: boolean;
61
+ search?: string;
60
62
  extensionBindings?: ExtensionBindings;
61
63
  /** Retained async child run id. Valid only on workflow runs.run items. */
62
64
  resume?: string;
@@ -210,14 +212,6 @@ export declare function shouldSuppressRoutineResultIntercom(input: {
210
212
  suppressRoutineResultIntercom?: boolean;
211
213
  results: SingleResult[];
212
214
  }): boolean;
213
- /**
214
- * Resolve the optional global default runtime deadline from extension config
215
- * (`config.timeoutMs`). Returns undefined for unset or invalid values so callers
216
- * use no configured deadline. "Invalid" covers non-positive-integer
217
- * values and values above `MAX_TIMER_DELAY_MS`; the latter would overflow the
218
- * Node.js timer and expire the run almost immediately instead of running long.
219
- */
220
- export declare function resolveConfigDefaultTimeoutMs(raw: unknown): number | undefined;
221
215
  export declare function resolveForegroundTimeout(params: SubagentParamsLike, defaultTimeoutMs?: number): {
222
216
  timeoutMs?: number;
223
217
  error?: string;