@xzzpig/pi-subagents 0.19.0 → 0.21.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 (153) hide show
  1. package/CHANGELOG.md +214 -0
  2. package/README.md +1 -1
  3. package/agents/oracle.md +8 -19
  4. package/agents/researcher.md +0 -3
  5. package/agents/reviewer.md +17 -61
  6. package/agents/scout.md +1 -4
  7. package/agents/worker.md +8 -25
  8. package/docs/agents.md +86 -11
  9. package/docs/configuration.md +68 -7
  10. package/docs/extension-api.md +37 -12
  11. package/docs/fork-extensions.md +1 -0
  12. package/docs/missions.md +48 -17
  13. package/docs/models.md +7 -3
  14. package/docs/observability.md +18 -8
  15. package/docs/tool-reference.md +138 -80
  16. package/docs/watchdog.md +8 -6
  17. package/docs/workflows.md +18 -9
  18. package/index.ts +5 -0
  19. package/package.json +5 -3
  20. package/prompts/council.md +1 -1
  21. package/skills/pi-subagents/SKILL.md +1 -1
  22. package/skills/pi-subagents/references/constraints-and-recipes.md +1 -1
  23. package/skills/pi-subagents/references/execution-controls.md +16 -16
  24. package/skills/pi-subagents/references/management-authoring-rpc.md +16 -12
  25. package/skills/pi-subagents/references/prompting-and-roles.md +3 -3
  26. package/src/agents/advertised-agent-prompt.ts +9 -1
  27. package/src/agents/agent-management.ts +4 -0
  28. package/src/agents/agent-memory.ts +3 -3
  29. package/src/agents/agent-scope.ts +4 -0
  30. package/src/agents/agent-serializer.ts +8 -1
  31. package/src/agents/agents.ts +224 -122
  32. package/src/api/preflight.ts +50 -5
  33. package/src/extension/config.ts +24 -2
  34. package/src/extension/context-injection.ts +6 -1
  35. package/src/extension/control-notices.ts +1 -9
  36. package/src/extension/declaration-pinning.ts +164 -0
  37. package/src/extension/doctor.ts +7 -10
  38. package/src/extension/fanout-child.ts +7 -8
  39. package/src/extension/index.ts +134 -145
  40. package/src/extension/public-execution.ts +3 -0
  41. package/src/extension/reply-workflow-script.ts +21 -12
  42. package/src/extension/rpc.ts +12 -7
  43. package/src/extension/schemas.ts +39 -33
  44. package/src/extension/subagent-guide.ts +86 -6
  45. package/src/extension/subagent-options.ts +47 -0
  46. package/src/extension/tool-activation.ts +3 -2
  47. package/src/extension/tool-description.ts +51 -68
  48. package/src/inspectors/actions.ts +37 -11
  49. package/src/inspectors/plugins.ts +3 -2
  50. package/src/inspectors/tmux/actions.ts +204 -0
  51. package/src/inspectors/tmux/client.ts +85 -0
  52. package/src/inspectors/tmux/plugin.ts +21 -0
  53. package/src/integrations/herdr-status.ts +18 -49
  54. package/src/integrations/program-status.ts +215 -0
  55. package/src/intercom/native-supervisor-channel.ts +77 -4
  56. package/src/intercom/result-intercom.ts +3 -2
  57. package/src/intercom/supervisor-ui.ts +2 -174
  58. package/src/missions/goal-driver.ts +44 -31
  59. package/src/missions/store.ts +35 -6
  60. package/src/profiles/profiles.ts +29 -23
  61. package/src/runs/background/active-async-capacity.ts +58 -8
  62. package/src/runs/background/async-execution.ts +231 -44
  63. package/src/runs/background/async-job-tracker.ts +12 -4
  64. package/src/runs/background/async-resume.ts +5 -2
  65. package/src/runs/background/await-async-run.ts +18 -11
  66. package/src/runs/background/binary-bootstrap.ts +2 -1
  67. package/src/runs/background/calendar-schedule.ts +90 -0
  68. package/src/runs/background/chain-root-attachment.ts +9 -5
  69. package/src/runs/background/control-channel.ts +43 -0
  70. package/src/runs/background/fleet-view.ts +5 -5
  71. package/src/runs/background/notify.ts +185 -12
  72. package/src/runs/background/result-files.ts +116 -5
  73. package/src/runs/background/result-watcher.ts +99 -66
  74. package/src/runs/background/resume-guidance.ts +2 -2
  75. package/src/runs/background/run-child-session.ts +29 -8
  76. package/src/runs/background/run-id-resolver.ts +8 -5
  77. package/src/runs/background/run-status.ts +21 -16
  78. package/src/runs/background/runner-aliases.ts +7 -4
  79. package/src/runs/background/runner-child-launch.ts +1 -0
  80. package/src/runs/background/runner-http-dispatcher.ts +3 -0
  81. package/src/runs/background/scheduled-runs.ts +282 -72
  82. package/src/runs/background/stale-run-reconciler.ts +13 -2
  83. package/src/runs/background/subagent-runner-bootstrap.ts +4 -1
  84. package/src/runs/background/subagent-runner.ts +75 -16
  85. package/src/runs/background/subagent-wait.ts +38 -19
  86. package/src/runs/background/terminal-run-index.ts +46 -1
  87. package/src/runs/background/wait-completions.ts +1 -0
  88. package/src/runs/background/wait-tool.ts +33 -23
  89. package/src/runs/background/workflow-terminal-proof.ts +39 -22
  90. package/src/runs/foreground/async-stop-action.ts +48 -22
  91. package/src/runs/foreground/command-action.ts +41 -0
  92. package/src/runs/foreground/execution.ts +109 -58
  93. package/src/runs/foreground/foreground-history.ts +1 -0
  94. package/src/runs/foreground/subagent-executor.ts +270 -89
  95. package/src/runs/shared/child-commands.ts +229 -0
  96. package/src/runs/shared/child-hooks.ts +4 -3
  97. package/src/runs/shared/child-launch.ts +3 -0
  98. package/src/runs/shared/child-session.ts +131 -40
  99. package/src/runs/shared/child-tool-plan.ts +14 -27
  100. package/src/runs/shared/claude-code-adapter.ts +157 -2
  101. package/src/runs/shared/dynamic-fanout.ts +2 -2
  102. package/src/runs/shared/external-cli-preflight.ts +54 -6
  103. package/src/runs/shared/external-cli-runner.ts +5 -1
  104. package/src/runs/shared/fork-command-result.ts +10 -0
  105. package/src/runs/shared/herdr-placed-run.ts +5 -4
  106. package/src/runs/shared/mcp-direct-tool-allowlist.ts +8 -5
  107. package/src/runs/shared/model-resolution-diagnostic.ts +25 -0
  108. package/src/runs/shared/model-resolution.ts +39 -2
  109. package/src/runs/shared/nested-events.ts +5 -0
  110. package/src/runs/shared/parallel-handoff.ts +56 -8
  111. package/src/runs/shared/parallel-utils.ts +4 -0
  112. package/src/runs/shared/partial-output.ts +48 -0
  113. package/src/runs/shared/run-history.ts +87 -0
  114. package/src/runs/shared/runner-launcher.ts +25 -0
  115. package/src/runs/shared/single-output.ts +53 -0
  116. package/src/runs/shared/structured-output.ts +14 -7
  117. package/src/runs/shared/subagent-control.ts +33 -18
  118. package/src/runs/shared/subagent-prompt-runtime.ts +59 -30
  119. package/src/runs/shared/workflow-async-child-guidance.ts +1 -1
  120. package/src/runs/shared/worktree-cleanup-apply.ts +160 -0
  121. package/src/runs/shared/worktree-cleanup-plan.ts +41 -19
  122. package/src/runs/shared/worktree-lock.ts +29 -0
  123. package/src/runs/shared/worktree.ts +12 -1
  124. package/src/shared/atomic-json.ts +4 -2
  125. package/src/shared/edit-distance.ts +33 -0
  126. package/src/shared/file-lease.ts +74 -0
  127. package/src/shared/formatters.ts +1 -5
  128. package/src/shared/model-info.ts +22 -0
  129. package/src/shared/package-version.ts +17 -0
  130. package/src/shared/parent-wake.ts +79 -0
  131. package/src/shared/pruned-fork.ts +7 -1
  132. package/src/shared/required-child-extensions.ts +39 -5
  133. package/src/shared/runtime-module-path.ts +19 -0
  134. package/src/shared/settings-file-lease.ts +36 -0
  135. package/src/shared/types.ts +42 -3
  136. package/src/shared/utils.ts +8 -6
  137. package/src/slash/slash-commands.ts +3 -3
  138. package/src/slash/subagent-cost.ts +9 -5
  139. package/src/slash/subagents-admin.ts +2 -1
  140. package/src/tui/fleet-native-transcript.ts +2 -0
  141. package/src/tui/fleet-transcript.ts +12 -3
  142. package/src/tui/fleet.ts +11 -8
  143. package/src/tui/render.ts +28 -20
  144. package/src/tui/subagent-messages.ts +305 -0
  145. package/src/watchdog/diff-tool.ts +2 -2
  146. package/src/watchdog/register-main.ts +2 -22
  147. package/src/watchdog/render.ts +2 -24
  148. package/src/watchdog/runtime.ts +6 -4
  149. package/src/watchdog/settings.ts +18 -13
  150. package/src/watchdog/tool-actions.ts +2 -2
  151. package/src/workflows/scripted-workflow.ts +20 -6
  152. package/src/workflows/workflow-receipt.ts +2 -2
  153. package/src/workflows/workflow-resources.ts +18 -4
@@ -23,7 +23,7 @@ import { projectNestedRegistryForRoot, sanitizeSummary } from "../shared/nested-
23
23
  import { resolveWatchPath } from "../../shared/utils.ts";
24
24
  import { recordWaitCompletion } from "./wait-completions.ts";
25
25
  import { MISSION_BINDING_FILE, syncMissionFromAsyncCompletion } from "../../missions/lifecycle.ts";
26
- import { missionObserverResultCandidateFiles, promotePendingResultFile, removeMissionObserverIndex, removeResultIndex, resultCandidateFilesForSession, resultPayloadPathForIndexedRun, resultPayloadPathForMissionObserverRun, resultPayloadPathForSessionRun, writeAsyncResultFile, writeResultIndexForData } from "./result-files.ts";
26
+ import { acknowledgeMissionObserverSnapshot, missionObserverResultCandidateFiles, promotePendingResultFile, readResultPayload, resultCandidateFilesForSession, resultPayloadPathForIndexedRun, resultPayloadPathForMissionObserverRun, resultPayloadPathForSessionRun, resultSnapshotReplaced, retireResultSnapshot, withResultRunLease, writeAsyncResultFile, writeResultIndexForData, type ResultSnapshot } from "./result-files.ts";
27
27
  import type { CompletionNotifier, CompletionNotification } from "./notify.ts";
28
28
  import type { ResultDeliveryOwnership } from "./result-delivery-ownership.ts";
29
29
 
@@ -45,7 +45,7 @@ type ResultWatcherTimers = {
45
45
  type ResultWatcherDeps = {
46
46
  fs?: ResultWatcherFs;
47
47
  timers?: ResultWatcherTimers;
48
- notifier?: Pick<CompletionNotifier, "deliver">;
48
+ notifier?: Pick<CompletionNotifier, "deliver"> & Partial<Pick<CompletionNotifier, "flush">>;
49
49
  /** Receives persisted completions before active-session delivery filtering. */
50
50
  observeCompletion?: (result: CompletionNotification & { runId: string }) => void;
51
51
  /** Returns cross-session run ids that the completion observer currently owns. */
@@ -63,6 +63,8 @@ type ResultWatcherDeps = {
63
63
  platform?: NodeJS.Platform;
64
64
  /** Shared current/predecessor session ownership used by the notifier. */
65
65
  ownership?: Pick<ResultDeliveryOwnership, "owns" | "claimedSessionIds">;
66
+ /** Called once the parent has this run's result: the notifier accepted it, or an earlier delivery already did. */
67
+ onResultDelivered?: (runId: string) => void;
66
68
  };
67
69
 
68
70
  type ResultFileChild = {
@@ -72,6 +74,7 @@ type ResultFileChild = {
72
74
  structuredOutput?: unknown;
73
75
  structuredOutputPath?: string;
74
76
  outputState?: SubagentOutputState;
77
+ outputPartial?: boolean;
75
78
  error?: string;
76
79
  success?: boolean;
77
80
  state?: string;
@@ -173,25 +176,18 @@ function hasDeliveredNotification(data: ResultFileData): boolean {
173
176
  return typeof data.notificationDeliveredAt === "number" && Number.isFinite(data.notificationDeliveredAt);
174
177
  }
175
178
 
176
- type PublicResultIdentity = {
177
- state?: string;
178
- timestamp?: number;
179
- };
180
-
181
- function resultPayloadWasReplaced(delivered: ResultFileData, disk: PublicResultIdentity | undefined): boolean {
182
- if (!disk) return false;
183
- const deliveredState = typeof delivered.state === "string" ? delivered.state : undefined;
184
- if (disk.state && deliveredState && disk.state !== deliveredState) return true;
185
- const deliveredTimestamp = typeof delivered.timestamp === "number" && Number.isFinite(delivered.timestamp)
186
- ? delivered.timestamp
187
- : undefined;
188
- return disk.timestamp !== undefined && deliveredTimestamp !== undefined && disk.timestamp !== deliveredTimestamp;
189
- }
190
-
191
- function markDeliveredNotification(resultPath: string, data: ResultFileData, runId: string, now: number): ResultFileData {
192
- const marked = { ...data, runId, notificationDeliveredAt: now };
193
- writeAsyncResultFile(resultPath, marked);
194
- return marked;
179
+ /** Marks the payload that was delivered, unless a newer payload replaced it (then returns undefined). */
180
+ function markDeliveredNotification(resultPath: string, data: ResultFileData, read: ResultSnapshot, now: number): { data: ResultFileData; read: ResultSnapshot } | undefined {
181
+ const marked = { ...data, runId: read.runId, notificationDeliveredAt: now };
182
+ return withResultRunLease(path.dirname(resultPath), read.runId, () => {
183
+ if (resultSnapshotReplaced(resultPath, read)) return undefined;
184
+ const { state } = writeAsyncResultFile(resultPath, marked);
185
+ // writeAsyncResultFile writes JSON.stringify(payload, null, 2). A denied promotion leaves the
186
+ // older public payload in place.
187
+ const snapshot = JSON.stringify(marked, null, 2);
188
+ const stalePublic = state === "pending" ? readResultPayload(resultPath) : undefined;
189
+ return { data: marked, read: { ...read, snapshot, stalePublic } };
190
+ });
195
191
  }
196
192
 
197
193
  /**
@@ -209,6 +205,7 @@ export function createResultWatcher(
209
205
  startResultWatcher: () => void;
210
206
  transitionResultDelivery: () => void;
211
207
  primeExistingResults: (options?: { triggerTurn?: boolean }) => void;
208
+ deliverPendingResults: () => Promise<void>;
212
209
  refreshResultDelivery: () => void;
213
210
  stopResultWatcher: () => void;
214
211
  } {
@@ -219,6 +216,9 @@ export function createResultWatcher(
219
216
  const deliverIntercomResults = deps.deliverIntercomResults !== false;
220
217
  const pendingTriggerTurn = new Map<string, boolean>();
221
218
  const processing = new Set<string>();
219
+ const handling = new Set<Promise<void>>();
220
+ // While deliverPendingResults runs, completions skip the batch delay.
221
+ let deliveringPending = 0;
222
222
  const identityCache = new Map<string, { signature: string; identity: ResultFileIdentity }>();
223
223
  let deliveryActive = true;
224
224
  let deliveryEpoch = 0;
@@ -327,18 +327,14 @@ export function createResultWatcher(
327
327
  return Boolean(deps.observeCompletion && !deps.observedCompletionRunIds);
328
328
  };
329
329
 
330
- const removeDeliveredResult = (file: string, sessionId: string, runId: string, toolCallId: string | undefined): boolean => {
330
+ const removeDeliveredResult = (file: string, triggerTurn: boolean, read: ResultSnapshot): void => {
331
+ identityCache.delete(file);
331
332
  try {
332
- if (publicResultFileExists(file)) fsApi.unlinkSync(publicResultPath(file));
333
- identityCache.delete(file);
334
- removeResultIndex(resultsDir, sessionId, runId, toolCallId);
335
- return true;
333
+ if (retireResultSnapshot(publicResultPath(file), read) === "replaced") scheduleResult(file, triggerTurn);
336
334
  } catch (error) {
337
- if (!isAbsentResultCandidate(error)) {
338
- console.error(`Failed to remove delivered subagent result '${publicResultPath(file)}'; will retry:`, error);
339
- return false;
340
- }
341
- return true;
335
+ if (isAbsentResultCandidate(error)) return;
336
+ console.error(`Failed to remove delivered subagent result '${publicResultPath(file)}'; will retry:`, error);
337
+ scheduleResult(file, triggerTurn, RETRY_DELAY_MS);
342
338
  }
343
339
  };
344
340
  const handleResult = async (file: string, triggerTurn: boolean) => {
@@ -359,30 +355,25 @@ export function createResultWatcher(
359
355
  processing.add(file);
360
356
  let rereadReplacedPayload = false;
361
357
  let resultPath = publicResultPath(file);
362
- const readPublicResultIdentity = (): PublicResultIdentity | undefined => {
363
- if (!publicResultFileExists(file)) return undefined;
364
- const parsed: unknown = JSON.parse(fsApi.readFileSync(publicResultPath(file), "utf-8"));
365
- if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return undefined;
366
- const record = parsed as Record<string, unknown>;
367
- const state = typeof record.state === "string" && record.state ? record.state : undefined;
368
- const timestamp = typeof record.timestamp === "number" && Number.isFinite(record.timestamp)
369
- ? record.timestamp
370
- : undefined;
371
- if (!state && timestamp === undefined) return undefined;
372
- return { state, timestamp };
358
+ // The public payload is read just before the payload itself, so anything published after the
359
+ // read differs from both.
360
+ let publicAtRead: string | undefined;
361
+ const readPayload = (payloadPath: string): string => {
362
+ publicAtRead = readResultPayload(publicResultPath(file));
363
+ return fsApi.readFileSync(payloadPath, "utf-8");
373
364
  };
374
365
  try {
375
366
  const payloadPath = resultPayloadPath(file, observed);
376
367
  if (!payloadPath) return;
377
368
  resultPath = payloadPath;
378
- let raw = fsApi.readFileSync(resultPath, "utf-8");
369
+ let raw = readPayload(resultPath);
379
370
  let identity = resultFileIdentity(raw, file);
380
371
  if (identity.sessionId && identity.runId) {
381
372
  const pendingState = promotePendingResultFile(resultsDir, identity.sessionId, identity.runId, file);
382
373
  if (pendingState === "promoted") {
383
374
  identityCache.delete(file);
384
375
  resultPath = publicResultPath(file);
385
- raw = fsApi.readFileSync(resultPath, "utf-8");
376
+ raw = readPayload(resultPath);
386
377
  identity = resultFileIdentity(raw, file);
387
378
  } else if (pendingState === "pending") {
388
379
  const pendingPath = resultPayloadPathForSessionRun(resultsDir, identity.sessionId, identity.runId);
@@ -391,30 +382,30 @@ export function createResultWatcher(
391
382
  return;
392
383
  }
393
384
  resultPath = pendingPath;
394
- raw = fsApi.readFileSync(resultPath, "utf-8");
385
+ raw = readPayload(resultPath);
395
386
  identity = resultFileIdentity(raw, file);
396
387
  }
397
388
  }
398
389
  let data = parseResult(raw);
390
+ if (typeof data.sessionId !== "string" || !data.sessionId) return;
391
+ const sessionId = data.sessionId;
392
+ const completionOwnerId = data.completionOwnerId;
393
+ const runId = typeof data.runId === "string" && data.runId
394
+ ? data.runId
395
+ : typeof data.id === "string" && data.id ? data.id : file.replace(/\.json$/i, "");
396
+ const toolCallId = typeof data.toolCallId === "string" ? data.toolCallId : undefined;
397
+ let read: ResultSnapshot = { runId, sessionId, toolCallId, snapshot: raw, ...(publicAtRead !== undefined && publicAtRead !== raw ? { stalePublic: publicAtRead } : {}) };
399
398
  const markReplacedPayload = (): boolean => {
400
399
  try {
401
- if (!resultPayloadWasReplaced(data, readPublicResultIdentity())) return false;
400
+ if (!resultSnapshotReplaced(publicResultPath(file), read)) return false;
402
401
  } catch (error) {
403
402
  if (isAccessDenied(error)) throw error;
404
- if (isAbsentResultCandidate(error)) return false;
405
403
  console.error(`Failed to re-read subagent result file '${publicResultPath(file)}':`, error);
406
404
  }
407
405
  identityCache.delete(file);
408
406
  rereadReplacedPayload = true;
409
407
  return true;
410
408
  };
411
- if (typeof data.sessionId !== "string" || !data.sessionId) return;
412
- const sessionId = data.sessionId;
413
- const completionOwnerId = data.completionOwnerId;
414
- const runId = typeof data.runId === "string" && data.runId
415
- ? data.runId
416
- : typeof data.id === "string" && data.id ? data.id : file.replace(/\.json$/i, "");
417
- const toolCallId = typeof data.toolCallId === "string" ? data.toolCallId : undefined;
418
409
  let observerSucceeded = true;
419
410
  try {
420
411
  syncMissionFromAsyncCompletion({ ...data, runId });
@@ -428,7 +419,14 @@ export function createResultWatcher(
428
419
  observerSucceeded = false;
429
420
  console.error(`Completion observer failed for '${resultPath}':`, error);
430
421
  }
431
- if (observerSucceeded) removeMissionObserverIndex(resultsDir, runId);
422
+ if (observerSucceeded) {
423
+ try {
424
+ if (acknowledgeMissionObserverSnapshot(publicResultPath(file), read) === "replaced") rereadReplacedPayload = true;
425
+ } catch (error) {
426
+ observerSucceeded = false;
427
+ console.error(`Failed to acknowledge the mission observer for '${resultPath}'; will retry:`, error);
428
+ }
429
+ }
432
430
  const epoch = deliveryEpoch;
433
431
  if (!ownsCompletion(sessionId, completionOwnerId, epoch)) return;
434
432
  // Recorded before dedupe and before the unlink below so bg_wait can
@@ -461,11 +459,12 @@ export function createResultWatcher(
461
459
  }
462
460
  if (!ownsCompletion(sessionId, completionOwnerId, epoch)) return;
463
461
  if (markReplacedPayload()) return;
462
+ deps.onResultDelivered?.(runId);
464
463
  if (!completionPersisted) {
465
464
  scheduleResult(file, triggerTurn, RETRY_DELAY_MS);
466
465
  return;
467
466
  }
468
- if (!removeDeliveredResult(file, sessionId, runId, toolCallId)) scheduleResult(file, triggerTurn, RETRY_DELAY_MS);
467
+ removeDeliveredResult(file, triggerTurn, read);
469
468
  return;
470
469
  }
471
470
 
@@ -505,6 +504,7 @@ export function createResultWatcher(
505
504
  outputState: result.outputState === "present" || result.outputState === "absent" || result.outputState === "unknown"
506
505
  ? result.outputState
507
506
  : "unknown",
507
+ ...(result.outputPartial === true ? { outputPartial: true } : {}),
508
508
  summary,
509
509
  index,
510
510
  artifactPath: result.artifactPaths?.outputPath,
@@ -522,11 +522,12 @@ export function createResultWatcher(
522
522
  }
523
523
  if (!ownsCompletion(sessionId, completionOwnerId, epoch)) return;
524
524
  if (markReplacedPayload()) return;
525
+ deps.onResultDelivered?.(runId);
525
526
  if (!completionPersisted) {
526
527
  scheduleResult(file, triggerTurn, RETRY_DELAY_MS);
527
528
  return;
528
529
  }
529
- if (!removeDeliveredResult(file, sessionId, runId, toolCallId)) scheduleResult(file, triggerTurn, RETRY_DELAY_MS);
530
+ removeDeliveredResult(file, triggerTurn, read);
530
531
  return;
531
532
  }
532
533
 
@@ -550,7 +551,7 @@ export function createResultWatcher(
550
551
  if (!intercomDelivered) console.error(`Subagent async grouped result intercom delivery was not acknowledged for '${resultPath}'.`);
551
552
  }
552
553
 
553
- const accepted = await notifier.deliver({
554
+ const delivery = notifier.deliver({
554
555
  ...data,
555
556
  id: data.id ?? runId,
556
557
  runId,
@@ -570,15 +571,24 @@ export function createResultWatcher(
570
571
  })) : [],
571
572
  } : {}),
572
573
  });
574
+ if (deliveringPending > 0) notifier.flush?.();
575
+ const accepted = await delivery;
573
576
  if (!ownsCompletion(sessionId, completionOwnerId, epoch)) return;
574
577
  if (!accepted) {
575
578
  scheduleResult(file, triggerTurn, RETRY_DELAY_MS);
576
579
  return;
577
580
  }
581
+ // A newer payload replaced this one; keep the hold until that one is delivered.
578
582
  if (markReplacedPayload()) return;
583
+ deps.onResultDelivered?.(runId);
579
584
  try {
580
- data = markDeliveredNotification(publicResultPath(file), data, runId, Date.now());
585
+ const marked = markDeliveredNotification(publicResultPath(file), data, read, Date.now());
581
586
  identityCache.delete(file);
587
+ if (!marked) {
588
+ rereadReplacedPayload = true;
589
+ return;
590
+ }
591
+ ({ data, read } = marked);
582
592
  } catch (error) {
583
593
  console.error(`Failed to mark subagent result notification delivered for '${resultPath}'; will retry:`, error);
584
594
  scheduleResult(file, triggerTurn, RETRY_DELAY_MS);
@@ -617,7 +627,7 @@ export function createResultWatcher(
617
627
  scheduleResult(file, triggerTurn, RETRY_DELAY_MS);
618
628
  return;
619
629
  }
620
- if (!removeDeliveredResult(file, sessionId, runId, toolCallId)) scheduleResult(file, triggerTurn, RETRY_DELAY_MS);
630
+ removeDeliveredResult(file, triggerTurn, read);
621
631
  } catch (error) {
622
632
  if (isAccessDenied(error)) {
623
633
  console.error(`Failed to process subagent result file '${resultPath}'; will retry:`, error);
@@ -629,11 +639,14 @@ export function createResultWatcher(
629
639
  }
630
640
  };
631
641
 
632
- state.resultFileCoalescer = createFileCoalescer((file) => {
642
+ const resultFileCoalescer = createFileCoalescer((file) => {
633
643
  const triggerTurn = pendingTriggerTurn.get(file) !== false;
634
644
  pendingTriggerTurn.delete(file);
635
- void handleResult(file, triggerTurn);
645
+ const run = handleResult(file, triggerTurn);
646
+ handling.add(run);
647
+ void run.finally(() => handling.delete(run));
636
648
  }, deps.coalesceDelayMs ?? 50);
649
+ state.resultFileCoalescer = resultFileCoalescer;
637
650
 
638
651
  const logScanStats = (stats: ResultScanStats) => {
639
652
  const elapsed = Date.now() - stats.startedAt;
@@ -658,9 +671,9 @@ export function createResultWatcher(
658
671
  for (const runId of observed) files.add(`${runId}.json`);
659
672
  return [...files];
660
673
  };
661
- const primeExistingResults = (options: { triggerTurn?: boolean } = {}) => {
674
+ const eligibleResultFiles = (): string[] => {
675
+ const files: string[] = [];
662
676
  try {
663
- const triggerTurn = options.triggerTurn !== false;
664
677
  const stats: ResultScanStats = { files: 0, scheduled: 0, startedAt: Date.now() };
665
678
  const observed = observedRunIds();
666
679
  for (const file of indexedResultCandidates(observed)) {
@@ -669,12 +682,32 @@ export function createResultWatcher(
669
682
  if (!signature) continue;
670
683
  if (!shouldProcessResult(file, observed, signature)) continue;
671
684
  stats.scheduled += 1;
672
- scheduleResult(file, triggerTurn);
685
+ files.push(file);
673
686
  }
674
687
  logScanStats(stats);
675
688
  } catch (error) {
676
689
  if (!isNotFound(error)) console.error(`Failed to scan subagent result index in '${resultsDir}':`, error);
677
690
  }
691
+ return files;
692
+ };
693
+ const primeExistingResults = (options: { triggerTurn?: boolean } = {}) => {
694
+ const triggerTurn = options.triggerTurn !== false;
695
+ for (const file of eligibleResultFiles()) scheduleResult(file, triggerTurn);
696
+ };
697
+ /** Hand every result that is already on disk to the notifier now, without coalescing or batch delays. */
698
+ const deliverPendingResults = async (): Promise<void> => {
699
+ if (!deliveryActive) return;
700
+ deliveringPending += 1;
701
+ try {
702
+ notifier.flush?.();
703
+ for (const file of eligibleResultFiles()) {
704
+ scheduleResult(file, true);
705
+ resultFileCoalescer.flush(file);
706
+ }
707
+ await Promise.allSettled([...handling]);
708
+ } finally {
709
+ deliveringPending -= 1;
710
+ }
678
711
  };
679
712
 
680
713
  const clearResultScan = () => {
@@ -805,5 +838,5 @@ export function createResultWatcher(
805
838
  identityCache.clear();
806
839
  };
807
840
 
808
- return { startResultWatcher, transitionResultDelivery, primeExistingResults, stopResultWatcher, refreshResultDelivery: () => { primeExistingResults(); startDemandPolling(); } };
841
+ return { startResultWatcher, transitionResultDelivery, primeExistingResults, deliverPendingResults, stopResultWatcher, refreshResultDelivery: () => { primeExistingResults(); startDemandPolling(); } };
809
842
  }
@@ -25,8 +25,8 @@ export function formatAsyncReviveCommand(run: AsyncRunSummary): string | undefin
25
25
  } catch {
26
26
  return undefined;
27
27
  }
28
- const index = run.steps.length === 1 ? "" : `, index: ${step.index}`;
29
- return `subagent({ action: "resume", id: "${run.id}"${index}, message: "Continue from the persisted child session and report the result." })`;
28
+ const index = run.steps.length === 1 ? "" : `, options: { index: ${step.index} }`;
29
+ return `subagent({ action: "resume", id: "${run.id}", message: "Continue from the persisted child session and report the result."${index} })`;
30
30
  }
31
31
 
32
32
  export function formatResumeFirstFailedRunDetail(run: AsyncRunSummary): string | undefined {
@@ -8,6 +8,7 @@
8
8
  import type { Message } from "@earendil-works/pi-ai";
9
9
  import type { ChildTranscriptWriter } from "../../shared/child-transcript.ts";
10
10
  import { extractTextFromContent, extractToolArgsPreview, getFinalOutput, hasEmptyTerminalAssistantResponse } from "../../shared/utils.ts";
11
+ import { qualifyModelWithProvider } from "../../shared/model-info.ts";
11
12
  import type { EffectsProjection, RuntimeAcknowledgedChildExtensions, SubagentOutputState, ToolBudgetState, Usage } from "../../shared/types.ts";
12
13
  import {
13
14
  acceptChildWatchdogEvent,
@@ -24,6 +25,7 @@ import { formatChildModelResolutionDiagnostic, isChildModelResolutionFailure } f
24
25
  import { isMutatingTool, resolveCurrentPath } from "../shared/long-running-guard.ts";
25
26
  import { effectiveToolTimeoutMs, formatToolTimeoutMessage, toolTimeoutCallKey } from "../shared/tool-timeout.ts";
26
27
  import { createReportedChildSessionInput, type InProcessChildLaunch } from "../shared/child-launch.ts";
28
+ import { createPartialOutputTracker, formatPartialOutput, type PartialOutputCause } from "../shared/partial-output.ts";
27
29
  import { childSessionHasQueuedMessages, projectChildSessionEventForJson, type ChildSession, type ChildSessionEvent, type ChildSessionFactory } from "../shared/child-session.ts";
28
30
  import { reconcileAttemptUsage } from "../shared/usage-reconciliation.ts";
29
31
  import { formatSteerMessage } from "../shared/subagent-prompt-runtime.ts";
@@ -114,6 +116,8 @@ export interface RunChildSessionResult {
114
116
  error?: string;
115
117
  finalOutput: string;
116
118
  outputState: SubagentOutputState;
119
+ /** Unfinished streamed text recovered after a timeout or child error. */
120
+ outputPartial?: boolean;
117
121
  interrupted?: boolean;
118
122
  timedOut?: boolean;
119
123
  stopped?: boolean;
@@ -175,6 +179,7 @@ export function runChildSession(input: RunChildSessionInput): Promise<RunChildSe
175
179
  let assistantError: string | undefined;
176
180
  let interrupted = false;
177
181
  let timedOut = false;
182
+ const partialOutput = createPartialOutputTracker();
178
183
  let stopped = false;
179
184
  let observedMutationAttempt = false;
180
185
  let structuredOutputToolInvoked = false;
@@ -411,6 +416,7 @@ export function runChildSession(input: RunChildSessionInput): Promise<RunChildSe
411
416
 
412
417
  const processEvent = (raw: ChildSessionEvent): void => {
413
418
  if (settled) return;
419
+ partialOutput.observe(raw);
414
420
  const event = raw as ChildSessionEvent & ChildEvent;
415
421
  appendChildEvent(projectChildSessionEventForJson(raw) as Record<string, unknown>);
416
422
  input.transcriptWriter?.writeChildEvent(projectChildSessionEventForJson(raw) as ChildEvent);
@@ -512,9 +518,9 @@ export function runChildSession(input: RunChildSessionInput): Promise<RunChildSe
512
518
  if (event.type !== "message_end" || event.message.role !== "assistant") return;
513
519
  const hasToolCall = assistantStartsToolCall(event.message);
514
520
  if (event.message.model) {
515
- model = event.message.model;
521
+ model = qualifyModelWithProvider(event.message.model, event.message.provider, input.modelVerificationRegistry) ?? event.message.model;
516
522
  if (input.expectedModelForVerification && !hasToolCall) {
517
- const modelVerificationError = formatSubagentModelVerificationError(input.expectedModelForVerification, event.message.model, input.modelVerificationRegistry, input.modelResponseAliases);
523
+ const modelVerificationError = formatSubagentModelVerificationError(input.expectedModelForVerification, event.message.model, input.modelVerificationRegistry, input.modelResponseAliases, session?.virtualModelId);
518
524
  if (modelVerificationError && !error) error = modelVerificationError;
519
525
  }
520
526
  }
@@ -545,7 +551,7 @@ export function runChildSession(input: RunChildSessionInput): Promise<RunChildSe
545
551
  };
546
552
 
547
553
  /** Stops observing the child and returns when its extensions have shut down. */
548
- const finish = (): Promise<void> => {
554
+ const finish = async (): Promise<string | undefined> => {
549
555
  clearFinalDrainTimers();
550
556
  clearWatchdogTailTimer();
551
557
  clearAllToolTimeouts();
@@ -559,7 +565,13 @@ export function runChildSession(input: RunChildSessionInput): Promise<RunChildSe
559
565
  input.registerSteer?.(undefined);
560
566
  input.registerWatchdogStatus?.(undefined);
561
567
  unsubscribe?.();
562
- return Promise.resolve().then(() => session?.dispose()).catch(() => undefined);
568
+ let commandError: string | undefined;
569
+ if (!interrupted && !timedOut && !stopped) {
570
+ try { await session?.finishCommands?.(); }
571
+ catch (error) { commandError = error instanceof Error ? error.message : String(error); }
572
+ }
573
+ await Promise.resolve().then(() => session?.dispose()).catch(() => undefined);
574
+ return commandError;
563
575
  };
564
576
 
565
577
  /** The child run ended (or was forced to end); fold in the outcome once the child's shutdown work is done. */
@@ -576,7 +588,14 @@ export function runChildSession(input: RunChildSessionInput): Promise<RunChildSe
576
588
  ? reconcileAttemptUsage(usage, session.messages, messageBaseline)
577
589
  : usage;
578
590
  const closed = finish();
579
- const finalOutput = getFinalOutput(messages);
591
+ const completedOutput = getFinalOutput(messages);
592
+ // Text still streaming at a timeout or thrown session error never reached a
593
+ // completed message; keep it, labeled. The run still fails.
594
+ const partialCause: PartialOutputCause | undefined = timedOut
595
+ ? "timeout"
596
+ : promptError !== undefined && !stopped && !interrupted ? "child error" : undefined;
597
+ const streamedPartial = partialCause ? partialOutput.text() : undefined;
598
+ const finalOutput = partialCause && streamedPartial ? formatPartialOutput(streamedPartial, partialCause) : completedOutput;
580
599
  let finalError = error ?? assistantError;
581
600
  const promptErrorMessage = promptError === undefined ? undefined : promptError instanceof Error ? promptError.message : String(promptError);
582
601
  if (!finalError && promptErrorMessage !== undefined) {
@@ -599,12 +618,13 @@ export function runChildSession(input: RunChildSessionInput): Promise<RunChildSe
599
618
  if (!finalError && forced && !forcedDrainAfterFinalSuccess && !interrupted && !timedOut && !stopped) {
600
619
  finalError = "Subagent session did not settle after it was aborted.";
601
620
  }
602
- const exitCode = timedOut || stopped
621
+ let exitCode = timedOut || stopped
603
622
  ? 1
604
623
  : interrupted || (forcedDrainAfterFinalSuccess && !forcedDrainAfterEmptyTerminal)
605
624
  ? 0
606
625
  : finalError || promptError !== undefined ? 1 : 0;
607
- void closed.then(() => {
626
+ void closed.then((commandError) => {
627
+ if (commandError) { finalError ??= commandError; exitCode = 1; }
608
628
  const result: RunChildSessionResult = omitUndefined({
609
629
  exitCode,
610
630
  messages,
@@ -613,9 +633,10 @@ export function runChildSession(input: RunChildSessionInput): Promise<RunChildSe
613
633
  durationMs: Date.now() - startedAt,
614
634
  model,
615
635
  nativeMachine: session?.machineEvidence ? { provider: "herdr", machineId: session.machineEvidence.machineId, ...(session.machineEvidence.initial ? { initialGit: session.machineEvidence.initial } : {}), ...(session.machineEvidence.final ? { finalGit: session.machineEvidence.final } : {}) } : undefined,
616
- error: stopped ? stopMessage() : timedOut ? (error ?? timeoutMessage()) : interrupted || (forcedDrainAfterFinalSuccess && !forcedDrainAfterEmptyTerminal) ? undefined : finalError,
636
+ error: stopped ? stopMessage() : timedOut ? (error ?? timeoutMessage()) : interrupted || (forcedDrainAfterFinalSuccess && !forcedDrainAfterEmptyTerminal && !commandError) ? undefined : finalError,
617
637
  finalOutput: (timedOut || stopped) && !finalOutput.trim() ? (stopped ? stopMessage() : error ?? timeoutMessage()) : finalOutput,
618
638
  outputState: finalOutput.trim() ? "present" : "absent",
639
+ outputPartial: partialCause && streamedPartial ? true : undefined,
619
640
  interrupted: interrupted || undefined,
620
641
  timedOut: timedOut || undefined,
621
642
  stopped: stopped || undefined,
@@ -5,6 +5,7 @@ import { readStatus } from "../../shared/utils.ts";
5
5
  import { findAsyncRunPrefixMatches, type AsyncRunLocation } from "./async-resume.ts";
6
6
  import { resultCandidateFilesForToolCall, resultFilePath, resultPayloadPathForIndexedRun } from "./result-files.ts";
7
7
  import { readActiveRunToolCallIndex } from "./active-run-index.ts";
8
+ import { readTerminalRunToolCallIndex } from "./terminal-run-index.ts";
8
9
  import { assertSafeNestedId, findNestedRunMatchesById, type NestedRoute, type NestedRunMatch, type NestedRunResolutionScope } from "../shared/nested-events.ts";
9
10
 
10
11
  export type ResolvedSubagentRunId =
@@ -66,7 +67,7 @@ function toolCallIdMatches(value: string | undefined, query: string): boolean {
66
67
 
67
68
  function indexedToolCallIdAsyncLocations(toolCallId: string, asyncDirRoot: string, resultsDir: string): AsyncRunMatch[] {
68
69
  const byId = new Map<string, AsyncRunLocation>();
69
- for (const entry of readActiveRunToolCallIndex(asyncDirRoot, toolCallId)) {
70
+ for (const entry of [...readActiveRunToolCallIndex(asyncDirRoot, toolCallId), ...readTerminalRunToolCallIndex(asyncDirRoot, toolCallId)]) {
70
71
  const asyncDir = path.join(asyncDirRoot, entry);
71
72
  const status = readStatus(asyncDir);
72
73
  if (!status || !toolCallIdMatches(status.toolCallId, toolCallId)) continue;
@@ -151,11 +152,13 @@ export function resolveSubagentRunId(id: string, deps: ResolveSubagentRunIdDeps
151
152
  if (hasExactForegroundId(deps.state, id)) return { kind: "foreground", id };
152
153
  const exactAsync = exactAsyncLocation(id, asyncDirRoot, resultsDir);
153
154
  if (exactAsync) return { kind: "async", id, location: exactAsync };
155
+ // A live run and a delivered run can share one alias; count both before deciding it is unique.
156
+ const toolCallMatches = new Map(indexedToolCallIdAsyncLocations(id, asyncDirRoot, resultsDir).map((match) => [match.id, match]));
154
157
  const exactLiveToolCallMatch = exactLiveAsyncToolCallMatch(deps.state, id, asyncDirRoot, resultsDir);
155
- if (exactLiveToolCallMatch) return { kind: "async", id: exactLiveToolCallMatch.id, location: exactLiveToolCallMatch.location };
156
- const exactToolCallIdMatches = indexedToolCallIdAsyncLocations(id, asyncDirRoot, resultsDir);
157
- if (exactToolCallIdMatches.length > 1) throw new Error(`Subagent tool-call id '${id}' is ambiguous across async runs. Use the returned asyncId instead.`);
158
- if (exactToolCallIdMatches[0]) return { kind: "async", id: exactToolCallIdMatches[0].id, location: exactToolCallIdMatches[0].location };
158
+ if (exactLiveToolCallMatch) toolCallMatches.set(exactLiveToolCallMatch.id, exactLiveToolCallMatch);
159
+ if (toolCallMatches.size > 1) throw new Error(`Subagent tool-call id '${id}' is ambiguous across async runs. Use the returned asyncId instead.`);
160
+ const [toolCallMatch] = toolCallMatches.values();
161
+ if (toolCallMatch) return { kind: "async", id: toolCallMatch.id, location: toolCallMatch.location };
159
162
  const nestedScope = deps.nested ?? nestedScopeFromState(deps.state);
160
163
  const exactNested = findNestedRunMatchesById(id, nestedScope ? { scope: nestedScope } : {});
161
164
  if (exactNested.length > 1) throw new Error(`Nested run id '${id}' is ambiguous across authorized registries. Provide the full id after stale registries are cleaned up.`);