pi-better-subagents 0.26.0 → 0.26.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.ts CHANGED
@@ -32,7 +32,7 @@ import {
32
32
  type BackgroundWorkRow,
33
33
  } from "./shared-navigator.ts";
34
34
  import { spawnDetached, killProcessTree, type SpawnResult } from "./spawn.ts";
35
- import { parseRun, readRunTranscript, resetParseRunCursor, type Usage } from "./parse.ts";
35
+ import { parseRun, parseRunForLifecycle, readRunTranscript, resetParseRunCursor, type Usage } from "./parse.ts";
36
36
  import { finalizeRun as finalizeRunCore } from "./finalization.ts";
37
37
  import { selectSessionByName } from "./session-selection.ts";
38
38
  import { isWithinWorkspace } from "./workspace-scope.ts";
@@ -74,6 +74,8 @@ import {
74
74
  runDir,
75
75
  recordTaskRuntimeProvenance,
76
76
  discardFailedLaunch,
77
+ recordLaunchAttempt,
78
+ clearLaunchAttempt,
77
79
  logPathFor,
78
80
  promptPathFor,
79
81
  nextRunId,
@@ -295,10 +297,18 @@ function verifiedOriginFromContext(ctx: ExtensionContext | undefined): RunCallba
295
297
  }
296
298
  }
297
299
 
300
+ /**
301
+ * Instance-local suppression: this module has no active session, not the run.
302
+ * A finalizer that runs after `/reload` (the process and its exit observer
303
+ * survive the session) can report this even though the replacing session owns
304
+ * the run, so it must never be written as a durable suppression (#625).
305
+ */
306
+ const NO_ACTIVE_SESSION_REASON = "active session identity is unavailable";
307
+
298
308
  function callbackSuppressionReason(meta: RunMeta, active: RunCallbackOrigin | undefined = activeCallbackOrigin): string | undefined {
299
309
  const origin = meta.callbackOrigin;
300
310
  if (origin) {
301
- if (!active) return "active session identity is unavailable";
311
+ if (!active) return NO_ACTIVE_SESSION_REASON;
302
312
  if (origin.cwd !== active.cwd) return `origin cwd ${origin.cwd} does not match active cwd ${active.cwd}`;
303
313
  if (origin.sessionId && origin.sessionId !== active.sessionId) {
304
314
  return `origin session ${origin.sessionId} does not match active session ${active.sessionId ?? "unknown"}`;
@@ -333,25 +343,104 @@ function hasSelfProcessIdentity(meta: RunMeta): boolean {
333
343
  return meta.pid === process.pid || meta.pgid === process.pid;
334
344
  }
335
345
 
336
- function stopCurrentSessionSubagents(ctx: ExtensionContext): void {
346
+ /**
347
+ * Runs this extension instance launched, so its in-memory exit observer is the
348
+ * authority that finalizes them. A run adopted after `/reload` is absent here:
349
+ * the instance that held the observer is gone, so supervision falls back to the
350
+ * child's own log (see `finalizeInterruptedRunFromLog`).
351
+ */
352
+ const directlySupervisedRunIds = new Set<string>();
353
+
354
+ /**
355
+ * Detach current-session live work instead of killing it (#625).
356
+ *
357
+ * Subagent children are detached process groups: they survive the foreground
358
+ * process dying. The previous shutdown loop therefore made every controlled
359
+ * `/reload` (and every clean quit) a silent, destructive end to in-flight work —
360
+ * no drain, no warning, and the run recorded `killed`. Shutdown now only records
361
+ * that this session's direct supervision ended; the child and all of its saved
362
+ * state stay untouched, and the next session of the same pi process resumes
363
+ * supervision and finalizes it from the child's own log.
364
+ *
365
+ * Returns the interrupted runs so the caller can warn the human.
366
+ */
367
+ function interruptCurrentSessionSubagents(reason: string, ctx: ExtensionContext): RunMeta[] {
337
368
  const origin = callbackOriginFromContext(ctx);
369
+ const now = Date.now();
370
+ const interrupted: RunMeta[] = [];
338
371
  for (const summary of listMetasForParent(process.pid)) {
339
372
  if (!ownedByThisParent(summary)) continue;
340
373
  if (summary.status !== "running" && summary.status !== "orphaned") continue;
341
374
  if (!belongsToOrigin(summary, origin)) continue;
342
- // Automatic shutdown cleanup must not let corrupt or synthetic metadata
343
- // signal the foreground Pi process itself.
375
+ // Corrupt or synthetic metadata must never point the interruption record
376
+ // (or any later signal) at the foreground Pi process itself.
344
377
  if (hasSelfProcessIdentity(summary)) continue;
345
- try { stopRun(summary.id); } catch { /* best-effort shutdown cleanup */ }
378
+ try {
379
+ // Re-read under the id: a run may have finished while shutdown ran.
380
+ const meta = readMeta(summary.id);
381
+ if (!meta || (meta.status !== "running" && meta.status !== "orphaned")) continue;
382
+ meta.supervisionInterruptedAt = now;
383
+ meta.supervisionInterruptedReason = reason;
384
+ writeMeta(meta);
385
+ interrupted.push(meta);
386
+ } catch { /* a failed marker must never kill or block the child */ }
346
387
  spendCache.delete(summary.id);
347
388
  healthLogCache.delete(summary.id);
348
389
  resetChildEventLogCursor(summary.id);
349
390
  }
391
+ return interrupted;
392
+ }
393
+
394
+ /** Warn the human that a shutdown/reload left delegated work running (#625). */
395
+ function warnInterruptedSubagents(ctx: ExtensionContext, interrupted: RunMeta[], reason: string): void {
396
+ if (interrupted.length === 0) return;
397
+ const count = interrupted.length;
398
+ const label = count === 1 ? "1 subagent run is" : `${count} subagent runs are`;
399
+ const ids = interrupted.slice(0, 3).map((meta) => meta.id).join(", ") + (count > 3 ? ", …" : "");
400
+ const verb = reason === "reload" ? "reload" : "session shutdown";
401
+ const guidance = reason === "reload"
402
+ ? "The reloaded session resumes supervision and reports the result; use subagent_stop to end it instead."
403
+ : "They keep running detached and stay readable with subagent_result/subagent_output; use subagent_stop to end one.";
404
+ try {
405
+ ctx.ui.notify(`Subagent ${label} still running (${ids}) — ${verb} no longer kills delegated work. ${guidance}`, "warning");
406
+ } catch { /* no UI available (print/RPC/quit) */ }
407
+ }
408
+
409
+ /**
410
+ * True once this extension instance's `session_shutdown` has run. A late child
411
+ * finalizer can still execute after `/reload` (the process and its exit
412
+ * observer survive the session), and such a finalizer must not restart
413
+ * supervision loops or durably suppress a callback just because THIS instance
414
+ * no longer has a session.
415
+ */
416
+ let sessionTornDown = false;
417
+
418
+ /**
419
+ * "The rightful conversation is not the active one", not "this notification is
420
+ * dead" (#625). These reasons only defer delivery to whoever owns the run, so
421
+ * they must never consume an interrupted run's owed completion.
422
+ */
423
+ function isConversationIdentityReason(reason: string): boolean {
424
+ return reason === NO_ACTIVE_SESSION_REASON
425
+ || reason.startsWith("origin session ")
426
+ || reason.startsWith("origin cwd ")
427
+ || reason.startsWith("legacy run cwd ");
350
428
  }
351
429
 
352
430
  function markCompletionCallbackSuppressed(id: string, reason: string, now: number = Date.now()): void {
431
+ // A finalizer that runs after this instance was torn down cannot name the
432
+ // session that owns the run now. Suppressing durably would erase the
433
+ // pending marker the replacing session recovers (#625), so leave it.
434
+ if (sessionTornDown && reason === NO_ACTIVE_SESSION_REASON) return;
353
435
  const meta = readMeta(id);
354
436
  if (!meta || meta.completionCallbackSentAt !== undefined || meta.completionCallbackSuppressedAt !== undefined) return;
437
+ // An explicitly interrupted run owes its completion to the conversation that
438
+ // launched it (#625, DEV-226 criterion 5). An unrelated session merely being
439
+ // active — B opening before the original A returns — drops this delivery
440
+ // attempt but must keep the obligation: the pending marker stays, and A
441
+ // recovers it when it comes back. Records that never lost supervision keep
442
+ // today's durable suppression, so legacy/foreign notifications stay dead.
443
+ if (meta.supervisionInterruptedAt !== undefined && isConversationIdentityReason(reason)) return;
355
444
  meta.completionCallbackSuppressedAt = now;
356
445
  meta.completionCallbackSuppressedReason = reason;
357
446
  writeMeta(meta);
@@ -401,12 +490,34 @@ function enqueueCompletionCallback(pi: ExtensionAPI, id: string): void {
401
490
  });
402
491
  }
403
492
 
404
- /** Recover only records explicitly marked pending; legacy terminal runs never replay. */
493
+ /**
494
+ * Recover only records explicitly marked pending; legacy terminal runs never replay.
495
+ *
496
+ * Current-parent records are recovered unconditionally (the owner decides, and the
497
+ * session gate still suppresses a different foreground session). A run an
498
+ * interrupted DEAD parent left behind is recovered only by the conversation that
499
+ * launched it: that session id is the ownership proof, so an unrelated session
500
+ * never adopts it. A foreign parent that is still alive keeps ownership — the
501
+ * same `isAbandonedByParent` proof the running-record supervision uses — so this
502
+ * path never takes a live pi's terminal callback (#625, DEV-226 criterion 5).
503
+ */
405
504
  function recoverCompletionCallbacks(pi: ExtensionAPI): void {
406
505
  for (const meta of listMetasForParent(process.pid)) {
407
506
  if (!ownedByThisParent(meta)) continue;
408
507
  enqueueCompletionCallback(pi, meta.id);
409
508
  }
509
+ const activeSessionId = activeCallbackOrigin?.sessionId;
510
+ if (!activeSessionId) return;
511
+ for (const summary of listMetas()) {
512
+ if (ownedByThisParent(summary) || summary.supervisionInterruptedAt === undefined) continue;
513
+ if (summary.status === "running" || summary.status === "orphaned") continue;
514
+ // A live foreign parent still owns its run's callback: never deliver for it.
515
+ if (!isAbandonedByParent(summary, realProcessProbe)) continue;
516
+ const meta = readMeta(summary.id);
517
+ if (!meta || meta.status === "running" || meta.status === "orphaned") continue;
518
+ if (meta.callbackOrigin?.sessionId !== activeSessionId) continue;
519
+ enqueueCompletionCallback(pi, meta.id);
520
+ }
410
521
  }
411
522
 
412
523
  function deliverFailureAttention(pi: ExtensionAPI | undefined, meta: RunMeta, now: number): void {
@@ -673,7 +784,9 @@ function childSteerExtensionPath(): string {
673
784
  function readProgress(meta: RunMeta): ProgressState {
674
785
  let entry = progressCache.get(meta.id);
675
786
  const read = readAppendedLines(logPathFor(meta.id), entry?.cursor);
676
- if (!entry || read.restarted) entry = { state: emptyProgress(meta.startedAt) };
787
+ // A fresh (or restarted) fold may have lost the start of a call that is still
788
+ // running: seed it from the durable record rather than reporting silence.
789
+ if (!entry || read.restarted) entry = { state: emptyProgress(meta.startedAt, meta.timing?.inFlight) };
677
790
  if (read.error === undefined) entry.cursor = read.cursor;
678
791
  for (const line of read.lines) {
679
792
  if (!isProgressRelevantLine(line)) continue;
@@ -755,6 +868,9 @@ function stopForTiming(pi: ExtensionAPI | undefined, id: string, reason: TimingS
755
868
  // it was finalized from its log): its own exit is the outcome, not a harness stop.
756
869
  patchTiming(id, { stopReason: undefined, stoppedAt: undefined });
757
870
  progressCache.delete(id);
871
+ // A log finalization is terminal evidence discovered here, not by the child
872
+ // exit handler, so this path still owes the one completion callback (#624).
873
+ if (pi && outcome.action === "finalized") enqueueCompletionCallback(pi, id);
758
874
  return outcome.action === "finalized";
759
875
  }
760
876
  const current = readMeta(id);
@@ -785,10 +901,24 @@ function enforceTiming(pi: ExtensionAPI | undefined, meta: RunMeta, now: number)
785
901
  return timing.ceilingAt !== undefined && now >= timing.ceilingAt ? stopForTiming(pi, meta.id, "ceiling", now) : false;
786
902
  }
787
903
  if (meta.status !== "running") return false;
788
- const needsProgress = timing.stuckMs !== undefined || (timing.deadlineAt !== undefined && now >= timing.deadlineAt);
904
+ // Progress is folded whenever a control can use it: the stuck window, or a deadline whose
905
+ // steer must be held behind a running call (the record of that call must exist before the
906
+ // deadline, not only after it).
907
+ const needsProgress = timing.stuckMs !== undefined || timing.deadlineAt !== undefined;
789
908
  const progress = needsProgress ? readProgress(meta) : undefined;
790
909
  const patch: Partial<NonNullable<RunMeta["timing"]>> = {};
791
910
  if (progress?.lastProgressAt !== undefined && progress.lastProgressAt > (timing.lastProgressAt ?? 0)) patch.lastProgressAt = progress.lastProgressAt;
911
+ if (progress) {
912
+ // Durable still-alive evidence: the call the child is waiting on. Survives a
913
+ // reload whose bounded log read no longer contains the call's start (#620).
914
+ const openId = progress.open.keys().next().value as string | undefined;
915
+ const since = progress.inFlightSince ?? progress.lastEventAt ?? meta.startedAt;
916
+ if (openId === undefined) {
917
+ if (timing.inFlight !== undefined) patch.inFlight = undefined;
918
+ } else if (timing.inFlight?.id !== openId || timing.inFlight.since !== since) {
919
+ patch.inFlight = { id: openId, since };
920
+ }
921
+ }
792
922
  if (timing.steerRequestedAt !== undefined && timing.steerDeliveredAt === undefined) {
793
923
  // The child's receipt for this run's steer; clamped so a skewed clock cannot move grace earlier than the request.
794
924
  const receipt = readSteerReceipt(steerPathFor(meta.id));
@@ -845,6 +975,14 @@ function reconcileHealth(): void {
845
975
  summary: meta.status === "lost" ? "Child supervision was lost; outcome is unknown" : "Child supervision interrupted; related work may still be alive" }], now);
846
976
  }
847
977
  deliverFailureAttention(pi, meta, now);
978
+ // Interrupted work whose child already exited is finalized from its own
979
+ // coherent log before any other verdict (and before timing can mislabel
980
+ // an already-finished run as stopped) (#625).
981
+ if (meta.status === "running" || meta.status === "orphaned") {
982
+ try {
983
+ if (finalizeInterruptedRunFromLog(pi, meta, now)) continue;
984
+ } catch { /* best-effort; the ordinary reconciliation below still runs */ }
985
+ }
848
986
  try {
849
987
  if (enforceTiming(pi, meta, now)) continue;
850
988
  } catch { /* timing is best-effort per tick; supervision below still runs */ }
@@ -882,6 +1020,19 @@ function reconcileHealth(): void {
882
1020
  deliverHealthCallback(pi, meta, meta.status, now);
883
1021
  }
884
1022
  }
1023
+ // A restart leaves an explicitly interrupted child whose owning pi is gone
1024
+ // (#625). Its record is foreign, so the owner-gated loops above never see it:
1025
+ // finalize it from its own coherent log once the child itself is gone. This
1026
+ // is the human's own interrupted work, not another session's live run, and
1027
+ // `finalizeInterruptedRunFromLog` still requires all process evidence to be
1028
+ // absent, so a live writer is never touched.
1029
+ for (const summary of listMetas()) {
1030
+ if (summary.status !== "running" && summary.status !== "orphaned") continue;
1031
+ if (ownedByThisParent(summary) || !ownsInterruptedSupervision(summary)) continue;
1032
+ const meta = readMeta(summary.id);
1033
+ if (!meta || (meta.status !== "running" && meta.status !== "orphaned")) continue;
1034
+ try { finalizeInterruptedRunFromLog(pi, meta, Date.now()); } catch { /* the next tick retries */ }
1035
+ }
885
1036
  // Completed runs can still have failed completion handoffs to retry.
886
1037
  for (const summary of listMetasForParent(process.pid)) {
887
1038
  if (!pi || !ownedByThisParent(summary) || summary.status === "running" || summary.status === "orphaned" || summary.status === "lost") continue;
@@ -905,6 +1056,11 @@ export function progressCacheIdsForTests(): string[] {
905
1056
  return [...progressCache.keys()];
906
1057
  }
907
1058
 
1059
+ /** Test seam: drop the in-memory progress fold, as a reloaded extension instance does. */
1060
+ export function forgetProgressCacheForTests(): void {
1061
+ progressCache.clear();
1062
+ }
1063
+
908
1064
  /**
909
1065
  * This pi's own start-identity token, recorded on every run it spawns so a later
910
1066
  * process can tell "my parent is gone" from "my parent's pid was recycled".
@@ -960,12 +1116,24 @@ function reconcileAbandonedRuns(now: number = Date.now()): number {
960
1116
 
961
1117
  /** Completion batches own their retry timer; only supervision keeps this one alive. */
962
1118
  function syncHealthTicker(): void {
963
- if (needsMonitoring(listMetasForParent(process.pid))) ensureHealthTicker();
1119
+ // A replaced instance never restarts supervision loops for a session it no
1120
+ // longer owns; the live instance runs its own. It must still STOP one that is
1121
+ // already armed: a run this instance launched before teardown can finish
1122
+ // afterwards, and returning early here left the interval supervising a
1123
+ // session that no longer exists (#625).
1124
+ if (sessionTornDown) {
1125
+ stopHealthTicker();
1126
+ return;
1127
+ }
1128
+ if (needsMonitoring(listMetasForParent(process.pid)) || needsInterruptedSupervision()) ensureHealthTicker();
964
1129
  else stopHealthTicker();
965
1130
  }
966
1131
 
967
1132
  /** Start the reconciliation loop if it isn't already running. */
968
1133
  function ensureHealthTicker(): void {
1134
+ // Not gated on `sessionTornDown`: a spawn always means the current session is
1135
+ // doing new work. Only `syncHealthTicker` — the path a late child finalizer
1136
+ // takes — stays closed in a replaced instance.
969
1137
  if (healthTicker) return;
970
1138
  healthTicker = setInterval(reconcileHealth, HEALTH_TICK_MS);
971
1139
  healthTicker.unref?.(); // never keep the process alive on our account
@@ -1108,6 +1276,10 @@ function navigatorCloseRun(id: string) {
1108
1276
  resetChildEventLogCursor(id);
1109
1277
  resetParseRunCursor(id);
1110
1278
  syncHealthTicker();
1279
+ // Close stops (or log-finalizes) the run, which is a terminal transition:
1280
+ // queue its one completion callback so no terminal state is silent (#624).
1281
+ // enqueueCompletionCallback is a no-op for runs that owe no callback.
1282
+ if (healthPi) enqueueCompletionCallback(healthPi, id);
1111
1283
  return outcome;
1112
1284
  }
1113
1285
 
@@ -1447,21 +1619,100 @@ function resolvePiBinary(): string {
1447
1619
  * first-party finalizer (finalization.ts) so tests can exercise the durable
1448
1620
  * path without importing the pi package.
1449
1621
  */
1450
- function finalizeRun(pi: ExtensionAPI, ctx: ExtensionContext, id: string, code: number | null): void {
1622
+ function finalizeRun(pi: ExtensionAPI, ctx: ExtensionContext | undefined, id: string, code: number | null): void {
1451
1623
  progressCache.delete(id);
1624
+ directlySupervisedRunIds.delete(id);
1452
1625
  // Host-facing wrapper around first-party finalizer (finalization.ts).
1453
1626
  // Coherent child-exit evidence may supersede provisional orphaned/lost
1454
1627
  // reconciliation; finalization.ts enforces canExitFinalize + lifecycle authority.
1455
1628
  finalizeRunCore(id, code, {
1456
1629
  renderWidget,
1457
1630
  notify: (message, level) => {
1458
- try { ctx.ui.notify(message, level); } catch { /* ignore */ }
1631
+ try { ctx?.ui.notify(message, level); } catch { /* ignore */ }
1459
1632
  },
1460
1633
  sendMessage: () => enqueueCompletionCallback(pi, id),
1461
1634
  });
1462
1635
  syncHealthTicker();
1463
1636
  }
1464
1637
 
1638
+ /**
1639
+ * Finalize a run whose supervision a previous session interrupted (`/reload`,
1640
+ * a session switch, or a quit) once its process evidence is gone (#625).
1641
+ *
1642
+ * The instance that held the in-memory exit observer is gone, so nothing else
1643
+ * reads the child's own log when the process disappears: health reconciliation
1644
+ * alone would record an interrupted-but-finished run `lost`, hiding a result
1645
+ * that is fully on disk. Only coherent terminal stream evidence is accepted
1646
+ * (`agent_end` with every tool call closed); anything else keeps the existing
1647
+ * reconciliation verdict, so no failure or completion is manufactured.
1648
+ *
1649
+ * Runs this instance launched are skipped: their exit observer finalizes them.
1650
+ */
1651
+ function finalizeInterruptedRunFromLog(
1652
+ pi: ExtensionAPI | undefined,
1653
+ meta: RunMeta,
1654
+ now: number,
1655
+ ): boolean {
1656
+ if (!pi) return false;
1657
+ if (directlySupervisedRunIds.has(meta.id)) return false;
1658
+ if (meta.supervisionInterruptedAt === undefined) return false;
1659
+ // Process evidence still exists: the child keeps running, nothing to finalize.
1660
+ if (reconcileRun(meta, realProcessProbe, now).status !== "lost") return false;
1661
+ let run;
1662
+ try { run = parseRunForLifecycle(meta.id); } catch { return false; }
1663
+ if (!run.sawEnd || run.unmatchedToolCalls.length > 0) return false;
1664
+ // Exit code is unknown after the observer is gone; the lifecycle authority
1665
+ // classifies from the coherent stream instead of inventing one.
1666
+ finalizeRun(pi, uiCtx, meta.id, null);
1667
+ return true;
1668
+ }
1669
+
1670
+ /**
1671
+ * Does this process have to supervise this explicit interruption record (#625)?
1672
+ *
1673
+ * A run this parent launched is this session's own (#625 reload). A run left by
1674
+ * a parent that is provably gone has no live owner at all — the restart case —
1675
+ * so its recorded interruption is the only thing that can recover it. Anything
1676
+ * else belongs to a live pi and is never adjudicated here.
1677
+ */
1678
+ function ownsInterruptedSupervision(summary: Pick<RunMeta, "spawnPid" | "spawnPidStartTime" | "supervisionInterruptedAt">): boolean {
1679
+ if (summary.supervisionInterruptedAt === undefined) return false;
1680
+ return ownedByThisParent(summary) || isAbandonedByParent(summary, realProcessProbe);
1681
+ }
1682
+
1683
+ /** True while an interrupted record still needs this process's supervision loop. */
1684
+ function needsInterruptedSupervision(): boolean {
1685
+ try {
1686
+ for (const summary of listMetas()) {
1687
+ if (summary.status !== "running" && summary.status !== "orphaned") continue;
1688
+ if (ownsInterruptedSupervision(summary)) return true;
1689
+ }
1690
+ } catch { /* best-effort scheduler gate */ }
1691
+ return false;
1692
+ }
1693
+
1694
+ /**
1695
+ * Attempt log-evidence finalization for every interrupted run this process has
1696
+ * to supervise: its own current-parent ones and the ones a dead parent left
1697
+ * behind. Live children are never finalized (`finalizeInterruptedRunFromLog`
1698
+ * requires the process evidence to be gone), so this only recovers a child that
1699
+ * already finished on its own.
1700
+ */
1701
+ function recoverInterruptedSubagents(pi: ExtensionAPI | undefined): number {
1702
+ let recovered = 0;
1703
+ const now = Date.now();
1704
+ for (const summary of listMetas()) {
1705
+ if (summary.status !== "running" && summary.status !== "orphaned") continue;
1706
+ if (!ownsInterruptedSupervision(summary)) continue;
1707
+ const meta = readMeta(summary.id);
1708
+ if (!meta || (meta.status !== "running" && meta.status !== "orphaned")) continue;
1709
+ try {
1710
+ if (finalizeInterruptedRunFromLog(pi, meta, now)) recovered += 1;
1711
+ } catch { /* best-effort at session start; the health ticker retries */ }
1712
+ }
1713
+ return recovered;
1714
+ }
1715
+
1465
1716
  /**
1466
1717
  * Re-prove a continuation's native history identity after its writer lease is held.
1467
1718
  *
@@ -1923,183 +2174,196 @@ export default function (pi: ExtensionAPI) {
1923
2174
  // A continuation never prepares another clone: the recipe's workspace already
1924
2175
  // holds the prior attempt's uncommitted work.
1925
2176
  const ownedCloneWorkspace = !resume && !p.sandbox_dir && sandboxEnabled && p.git_clone_workspace ? taskWorkspaceDir(id) : undefined;
1926
- if (!resume) mkdirSync(childSessionDir, { recursive: true });
1927
- mkdirSync(runDir(id), { recursive: true });
1928
-
1929
- const workspace = resume
1930
- ? { cwd: resume.recipe.cwd, requestedSandboxDir: resume.recipe.sandboxDir }
1931
- : resolveSubagentWorkspace({
1932
- ctxCwd: ctx.cwd,
1933
- cwd: p.cwd,
1934
- sandboxDir: p.sandbox_dir ?? ownedCloneWorkspace,
1935
- gitCloneWorkspace: p.git_clone_workspace,
1936
- runId: id,
1937
- runDirPath: runDir(id),
1938
- sandboxEnabled,
1939
- });
1940
- const cwd = workspace.cwd;
1941
- const requestedSandboxDir = workspace.requestedSandboxDir;
1942
-
1943
- if (requestedSandboxDir) mkdirSync(requestedSandboxDir, { recursive: true });
1944
- writeFileSync(promptPathFor(id), p.prompt);
1945
-
1946
- // A continuation keeps the recipe's launch intent; only current
1947
- // permission-driven adjustments are re-derived from it.
1948
- const requestedTools = resume ? resume.recipe.tools : p.tools;
1949
- const requestedExcludeTools = resume ? resume.recipe.excludeTools ?? "" : p.exclude_tools ?? "";
1950
- const clean = resume ? resume.recipe.clean : p.clean === true;
1951
- const allowNested = resume ? resume.recipe.allowNested : p.allow_nested === true;
1952
- const approve = resume ? resume.recipe.approve : p.approve === true;
1953
- const gitCloneWorkspace = resume ? resume.recipe.gitCloneWorkspace : p.git_clone_workspace === true;
1954
- const callbackEnabled = resume ? p.callback ?? resume.recipe.callback : p.callback !== false;
1955
- const launchName = resume ? resume.recipe.name : p.name;
1956
- // The frozen launch snapshot is the same shape a fresh spawn freezes.
1957
- const launchCatalog: RunMeta["catalog"] = resume
1958
- ? resume.recipe.catalog
1959
- : p.catalog as unknown as RunMeta["catalog"] | undefined;
1960
-
1961
- let allow = normalizeTools(
1962
- requestedTools ?? cfg.defaultTools ?? (clean ? SAFE_CLEAN_TOOLS : SAFE_DEFAULT_TOOLS),
1963
- );
1964
- if (allowNested) {
1965
- const have = new Set(allow.split(","));
1966
- allow = [...allow.split(","), ...SUBAGENT_TOOLS.filter((t) => !have.has(t))]
1967
- .filter(Boolean).join(",");
1968
- }
2177
+ // A launch attempt only becomes a run when `writeMeta` commits. Until
2178
+ // then everything it creates (prompt, control/, provenance, its own
2179
+ // session dir, clone workspace, task scratch) belongs to the attempt and
2180
+ // must go if it fails, so no unreadable record is left in the registry
2181
+ // (#325, #332, #623).
2182
+ let lease: ConversationLease | undefined;
2183
+ let spawned: ReturnType<typeof spawnDetached> | undefined;
2184
+ let launchScratch: string | undefined;
2185
+ let committed = false;
2186
+ try {
2187
+ if (!resume) mkdirSync(childSessionDir, { recursive: true });
2188
+ mkdirSync(runDir(id), { recursive: true });
2189
+ // Claim the directory before anything else is prepared. Until
2190
+ // `meta.json` exists this claim is the only ownership evidence, so a
2191
+ // concurrent purge can tell this live attempt from dead launch debris
2192
+ // (#623 R1). The outer catch drops the whole directory on failure.
2193
+ recordLaunchAttempt(id);
2194
+
2195
+ const workspace = resume
2196
+ ? { cwd: resume.recipe.cwd, requestedSandboxDir: resume.recipe.sandboxDir }
2197
+ : resolveSubagentWorkspace({
2198
+ ctxCwd: ctx.cwd,
2199
+ cwd: p.cwd,
2200
+ sandboxDir: p.sandbox_dir ?? ownedCloneWorkspace,
2201
+ gitCloneWorkspace: p.git_clone_workspace,
2202
+ runId: id,
2203
+ runDirPath: runDir(id),
2204
+ sandboxEnabled,
2205
+ });
2206
+ const cwd = workspace.cwd;
2207
+ const requestedSandboxDir = workspace.requestedSandboxDir;
2208
+
2209
+ if (requestedSandboxDir) mkdirSync(requestedSandboxDir, { recursive: true });
2210
+ writeFileSync(promptPathFor(id), p.prompt);
2211
+
2212
+ // A continuation keeps the recipe's launch intent; only current
2213
+ // permission-driven adjustments are re-derived from it.
2214
+ const requestedTools = resume ? resume.recipe.tools : p.tools;
2215
+ const requestedExcludeTools = resume ? resume.recipe.excludeTools ?? "" : p.exclude_tools ?? "";
2216
+ const clean = resume ? resume.recipe.clean : p.clean === true;
2217
+ const allowNested = resume ? resume.recipe.allowNested : p.allow_nested === true;
2218
+ const approve = resume ? resume.recipe.approve : p.approve === true;
2219
+ const gitCloneWorkspace = resume ? resume.recipe.gitCloneWorkspace : p.git_clone_workspace === true;
2220
+ const callbackEnabled = resume ? p.callback ?? resume.recipe.callback : p.callback !== false;
2221
+ const launchName = resume ? resume.recipe.name : p.name;
2222
+ // The frozen launch snapshot is the same shape a fresh spawn freezes.
2223
+ const launchCatalog: RunMeta["catalog"] = resume
2224
+ ? resume.recipe.catalog
2225
+ : p.catalog as unknown as RunMeta["catalog"] | undefined;
2226
+
2227
+ let allow = normalizeTools(
2228
+ requestedTools ?? cfg.defaultTools ?? (clean ? SAFE_CLEAN_TOOLS : SAFE_DEFAULT_TOOLS),
2229
+ );
2230
+ if (allowNested) {
2231
+ const have = new Set(allow.split(","));
2232
+ allow = [...allow.split(","), ...SUBAGENT_TOOLS.filter((t) => !have.has(t))]
2233
+ .filter(Boolean).join(",");
2234
+ }
1969
2235
 
1970
- // A confined child gets extension tools only through /sandbox Subagents · Tools (ADR 0009):
1971
- // the guarded apply_patch adapter, and trusted tools admitted by name and package.
1972
- const requestedExcludes = new Set(requestedExcludeTools.split(",").map((t) => t.trim()).filter(Boolean));
1973
- if (sandboxEnabled && !clean) {
1974
- const names = allow.split(",").filter(Boolean);
1975
- // Models reach for apply_patch whenever they may edit; ticked trusted tools join the default set.
1976
- if (permissionPlan.tools.applyPatch && names.some((name) => name === "edit" || name === "write")) names.push(APPLY_PATCH);
1977
- if (requestedTools === undefined) names.push(...permissionPlan.tools.trusted.map((entry) => entry.name));
1978
- allow = [...new Set(names)].join(",");
1979
- }
1980
- if (sandboxEnabled && requestedTools === undefined && permissionPlan.permissions?.processAccess === "read") {
1981
- allow = [...new Set([...allow.split(","), "process_list"])].join(",");
1982
- }
1983
- // Shell Off confines the child to directly launched applications: a requested bash
1984
- // becomes the guarded run_application builtin. Exclusions stay exclusions (an excluded
1985
- // run_application leaves bash out rather than restoring it), and a read-only loadout
1986
- // keeps no command capability at all.
1987
- const commandSettings = resolveCommandSettings(permissionPlan.permissions);
1988
- if (sandboxEnabled && !commandSettings.shell) {
1989
- allow = applyDirectApplicationLoadout(allow.split(",").filter(Boolean), {
1990
- shell: false, excluded: requestedExcludes,
1991
- }).tools.join(",");
1992
- }
1993
- const taskTools = sandboxEnabled ? planTaskTools({
1994
- requested: allow.split(",").filter((name) => name && !requestedExcludes.has(name)),
1995
- settings: permissionPlan.tools, network: permissionPlan.permissions?.network ?? true,
1996
- processAccess: permissionPlan.permissions?.processAccess ?? "off",
1997
- builtins: [...TASK_BUILTINS, "codemode"], registered: pi.getAllTools?.() ?? [],
1998
- toolExtensions: cfg.toolExtensions, resolvePath: resolveExtensionPath,
1999
- }) : undefined;
2000
- const resolution = resolveExtensions({
2001
- // Only SDK builtins reach `--tools` and extension resolution: process_list and run_application
2002
- // are task builtins that the mandatory guard installs and activates itself.
2003
- tools: sandboxEnabled ? allow.split(",").filter((name) => (SDK_BUILTIN_TOOLS as readonly string[]).includes(name)).join(",") : allow,
2004
- model, clean, allowNested: sandboxEnabled ? false : allowNested, config: cfg,
2005
- });
2006
- const { args: resolvedExtArgs, missing } = extensionArgs(resolution, resolveExtensionPath);
2007
- const trustedExtArgs = [...new Set(taskTools?.trusted.map((tool) => tool.loadPath) ?? [])]
2008
- .filter((path) => !resolvedExtArgs.includes(path)).flatMap((path) => ["--extension", path]);
2009
- // Harness child controls ride along in every mode, including clean and unsandboxed runs.
2010
- // They deliver deadline steers and keep external monitoring with the coordinator.
2011
- const codemodeArgs = !sandboxEnabled && allow.split(",").includes("codemode") && !requestedExcludes.has("codemode")
2012
- ? ["--extension", join(selfDir(), "child-codemode.ts")] : [];
2013
- const extArgs = [...resolvedExtArgs, ...trustedExtArgs, ...codemodeArgs,
2014
- "--extension", childSteerExtensionPath(), "--extension", join(selfDir(), "child-ownership.ts")]
2015
- .map((value, index, all) => sandboxEnabled && all[index - 1] === "--extension" ? canonicalizePath(value) : value);
2016
- const baseExtensionArgs = [...resolvedExtArgs, ...codemodeArgs,
2017
- "--extension", childSteerExtensionPath(), "--extension", join(selfDir(), "child-ownership.ts")]
2018
- .map((value, index, all) => sandboxEnabled && all[index - 1] === "--extension" ? canonicalizePath(value) : value);
2019
- if (resume?.recipe.extensionArgs) {
2020
- // A model escalation may change provider auth, but an unchanged tool
2021
- // must not silently switch implementations with current configuration.
2022
- const reference = model === resume.recipe.model ? resolution : resolveExtensions({
2236
+ // A confined child gets extension tools only through /sandbox Subagents · Tools (ADR 0009):
2237
+ // the guarded apply_patch adapter, and trusted tools admitted by name and package.
2238
+ const requestedExcludes = new Set(requestedExcludeTools.split(",").map((t) => t.trim()).filter(Boolean));
2239
+ if (sandboxEnabled && !clean) {
2240
+ const names = allow.split(",").filter(Boolean);
2241
+ // Models reach for apply_patch whenever they may edit; ticked trusted tools join the default set.
2242
+ if (permissionPlan.tools.applyPatch && names.some((name) => name === "edit" || name === "write")) names.push(APPLY_PATCH);
2243
+ if (requestedTools === undefined) names.push(...permissionPlan.tools.trusted.map((entry) => entry.name));
2244
+ allow = [...new Set(names)].join(",");
2245
+ }
2246
+ if (sandboxEnabled && requestedTools === undefined && permissionPlan.permissions?.processAccess === "read") {
2247
+ allow = [...new Set([...allow.split(","), "process_list"])].join(",");
2248
+ }
2249
+ // Shell Off confines the child to directly launched applications: a requested bash
2250
+ // becomes the guarded run_application builtin. Exclusions stay exclusions (an excluded
2251
+ // run_application leaves bash out rather than restoring it), and a read-only loadout
2252
+ // keeps no command capability at all.
2253
+ const commandSettings = resolveCommandSettings(permissionPlan.permissions);
2254
+ if (sandboxEnabled && !commandSettings.shell) {
2255
+ allow = applyDirectApplicationLoadout(allow.split(",").filter(Boolean), {
2256
+ shell: false, excluded: requestedExcludes,
2257
+ }).tools.join(",");
2258
+ }
2259
+ const taskTools = sandboxEnabled ? planTaskTools({
2260
+ requested: allow.split(",").filter((name) => name && !requestedExcludes.has(name)),
2261
+ settings: permissionPlan.tools, network: permissionPlan.permissions?.network ?? true,
2262
+ processAccess: permissionPlan.permissions?.processAccess ?? "off",
2263
+ builtins: [...TASK_BUILTINS, "codemode"], registered: pi.getAllTools?.() ?? [],
2264
+ toolExtensions: cfg.toolExtensions, resolvePath: resolveExtensionPath,
2265
+ }) : undefined;
2266
+ const resolution = resolveExtensions({
2267
+ // Only SDK builtins reach `--tools` and extension resolution: process_list and run_application
2268
+ // are task builtins that the mandatory guard installs and activates itself.
2023
2269
  tools: sandboxEnabled ? allow.split(",").filter((name) => (SDK_BUILTIN_TOOLS as readonly string[]).includes(name)).join(",") : allow,
2024
- model: resume.recipe.model, clean, allowNested: sandboxEnabled ? false : allowNested, config: cfg,
2270
+ model, clean, allowNested: sandboxEnabled ? false : allowNested, config: cfg,
2025
2271
  });
2026
- const referenceArgs = [...extensionArgs(reference, resolveExtensionPath).args, ...codemodeArgs,
2027
- ...(!resume.recipe.baseExtensionArgs ? trustedExtArgs : []),
2272
+ const { args: resolvedExtArgs, missing } = extensionArgs(resolution, resolveExtensionPath);
2273
+ const trustedExtArgs = [...new Set(taskTools?.trusted.map((tool) => tool.loadPath) ?? [])]
2274
+ .filter((path) => !resolvedExtArgs.includes(path)).flatMap((path) => ["--extension", path]);
2275
+ // Harness child controls ride along in every mode, including clean and unsandboxed runs.
2276
+ // They deliver deadline steers and keep external monitoring with the coordinator.
2277
+ const codemodeArgs = !sandboxEnabled && allow.split(",").includes("codemode") && !requestedExcludes.has("codemode")
2278
+ ? ["--extension", join(selfDir(), "child-codemode.ts")] : [];
2279
+ const extArgs = [...resolvedExtArgs, ...trustedExtArgs, ...codemodeArgs,
2028
2280
  "--extension", childSteerExtensionPath(), "--extension", join(selfDir(), "child-ownership.ts")]
2029
2281
  .map((value, index, all) => sandboxEnabled && all[index - 1] === "--extension" ? canonicalizePath(value) : value);
2030
- assertContinuationExtensions(resume.prior.id, resume.recipe,
2031
- referenceArgs, taskTools?.trusted ?? []);
2032
- }
2033
- if (sandboxEnabled && resolution.mode === "inherit") {
2034
- throw new Error("Task confinement requires explicit extensions; inheritExtensions is unsupported while sandboxing is enabled.");
2035
- }
2036
- if (missing.length) {
2037
- throw new Error(
2038
- `Subagent needs extension(s) that are not installed: ${missing.join(", ")}. ` +
2039
- `Install them, drop the tools that require them, or remove the mapping from config.json.`,
2040
- );
2041
- }
2282
+ const baseExtensionArgs = [...resolvedExtArgs, ...codemodeArgs,
2283
+ "--extension", childSteerExtensionPath(), "--extension", join(selfDir(), "child-ownership.ts")]
2284
+ .map((value, index, all) => sandboxEnabled && all[index - 1] === "--extension" ? canonicalizePath(value) : value);
2285
+ if (resume?.recipe.extensionArgs) {
2286
+ // A model escalation may change provider auth, but an unchanged tool
2287
+ // must not silently switch implementations with current configuration.
2288
+ const reference = model === resume.recipe.model ? resolution : resolveExtensions({
2289
+ tools: sandboxEnabled ? allow.split(",").filter((name) => (SDK_BUILTIN_TOOLS as readonly string[]).includes(name)).join(",") : allow,
2290
+ model: resume.recipe.model, clean, allowNested: sandboxEnabled ? false : allowNested, config: cfg,
2291
+ });
2292
+ const referenceArgs = [...extensionArgs(reference, resolveExtensionPath).args, ...codemodeArgs,
2293
+ ...(!resume.recipe.baseExtensionArgs ? trustedExtArgs : []),
2294
+ "--extension", childSteerExtensionPath(), "--extension", join(selfDir(), "child-ownership.ts")]
2295
+ .map((value, index, all) => sandboxEnabled && all[index - 1] === "--extension" ? canonicalizePath(value) : value);
2296
+ assertContinuationExtensions(resume.prior.id, resume.recipe,
2297
+ referenceArgs, taskTools?.trusted ?? []);
2298
+ }
2299
+ if (sandboxEnabled && resolution.mode === "inherit") {
2300
+ throw new Error("Task confinement requires explicit extensions; inheritExtensions is unsupported while sandboxing is enabled.");
2301
+ }
2302
+ if (missing.length) {
2303
+ throw new Error(
2304
+ `Subagent needs extension(s) that are not installed: ${missing.join(", ")}. ` +
2305
+ `Install them, drop the tools that require them, or remove the mapping from config.json.`,
2306
+ );
2307
+ }
2042
2308
 
2043
- const excludes = new Set<string>();
2044
- if (requestedExcludeTools) for (const t of requestedExcludeTools.split(",")) if (t.trim()) excludes.add(t.trim());
2045
- if (!allowNested && resolution.mode === "inherit") {
2046
- for (const t of SUBAGENT_TOOLS) excludes.add(t);
2047
- }
2309
+ const excludes = new Set<string>();
2310
+ if (requestedExcludeTools) for (const t of requestedExcludeTools.split(",")) if (t.trim()) excludes.add(t.trim());
2311
+ if (!allowNested && resolution.mode === "inherit") {
2312
+ for (const t of SUBAGENT_TOOLS) excludes.add(t);
2313
+ }
2048
2314
 
2049
- // A continuation reopens the exact saved conversation with `--session`;
2050
- // never `--session-id`, which would create a replacement session when the
2051
- // history is missing, and never both (Pi rejects the combination).
2052
- const sessionArgs = resume
2053
- ? ["--session", resume.conversation.path, "--session-dir", childSessionDir]
2054
- : ["--session-dir", childSessionDir, "--session-id", id];
2055
- const args = [
2056
- "-p", "--mode", "json",
2057
- ...sessionArgs,
2058
- ...extArgs,
2059
- ...(model ? ["--model", model] : []),
2060
- ...(thinking ? ["--thinking", thinking] : []),
2061
- ...(allow && !sandboxEnabled ? ["--tools", allow] : []),
2062
- ...(excludes.size ? ["--exclude-tools", [...excludes].join(",")] : []),
2063
- ...(sandboxEnabled ? ["--no-builtin-tools", "--no-approve"] : approve ? ["--approve"] : []),
2064
- p.prompt,
2065
- ];
2066
-
2067
- const piBin = resolvePiBinary();
2068
- const selectedTools = allow.split(",").filter((name) => name && !excludes.has(name));
2069
- const unavailable = taskTools?.refused.filter((tool) => selectedTools.includes(tool.name)) ?? [];
2070
- const unavailableTools = unavailable.map((tool) => tool.name);
2071
- if (sandboxEnabled && selectedTools.length && unavailableTools.length === selectedTools.length) {
2072
- throw new Error(`No requested tool has a verified task sandbox adapter: ${unavailable.map((tool) => `${tool.name} (${tool.reason})`).join(", ")}.`);
2073
- }
2074
- const taskRuntime = sandboxEnabled && requestedSandboxDir ? prepareTaskRuntime({
2075
- root: requestedSandboxDir, controlDir: join(runDir(id), "control"), piBin,
2076
- tools: selectedTools,
2077
- permissions: permissionPlan.permissions && { ...permissionPlan.permissions, ...commandSettings },
2078
- applyPatch: taskTools?.applyPatch === true,
2079
- extensionTools: taskTools?.trusted.map(({ loadPath: _loadPath, ...tool }) => tool) ?? [],
2080
- extensionPaths: extArgs.flatMap((arg, index) => arg === "--extension" && extArgs[index + 1] ? [extArgs[index + 1]!] : []),
2081
- runtimeRoots: [baseDir()],
2082
- }) : undefined;
2083
- if (sandboxEnabled && !taskRuntime) throw new Error("Task sandbox has no workspace; refusing an unconfined child.");
2084
- // Parent-authored trust record, written before the child can run (#325).
2085
- if (taskRuntime) recordTaskRuntimeProvenance(id);
2086
- // Outside project = Write or Write & delete lets the run change files
2087
- // outside its workspace: start an APFS local snapshot (macOS, in the
2088
- // background; a failure is reported, never blocks the run).
2089
- const snapshot = taskRuntime ? takeRecoverySnapshot(taskRuntime.policy.permissions) : undefined;
2090
- if (snapshot?.started) {
2091
- void snapshot.done.then((outcome) => {
2092
- if (outcome.ok) return;
2093
- // The snapshot can finish after the session was replaced and ctx went stale.
2094
- try { ctx.ui?.notify?.(`Subagent ${id}: recovery snapshot failed (run continues): ${outcome.detail}`, "warning"); } catch { /* ignore */ }
2095
- });
2096
- }
2097
- const cmd = taskRuntime ? { file: taskRuntime.file, fileArgs: [...taskRuntime.fileArgs, ...args] } : { file: piBin, fileArgs: args };
2098
- const sandboxDir = taskRuntime ? requestedSandboxDir : undefined;
2315
+ // A continuation reopens the exact saved conversation with `--session`;
2316
+ // never `--session-id`, which would create a replacement session when the
2317
+ // history is missing, and never both (Pi rejects the combination).
2318
+ const sessionArgs = resume
2319
+ ? ["--session", resume.conversation.path, "--session-dir", childSessionDir]
2320
+ : ["--session-dir", childSessionDir, "--session-id", id];
2321
+ const args = [
2322
+ "-p", "--mode", "json",
2323
+ ...sessionArgs,
2324
+ ...extArgs,
2325
+ ...(model ? ["--model", model] : []),
2326
+ ...(thinking ? ["--thinking", thinking] : []),
2327
+ ...(allow && !sandboxEnabled ? ["--tools", allow] : []),
2328
+ ...(excludes.size ? ["--exclude-tools", [...excludes].join(",")] : []),
2329
+ ...(sandboxEnabled ? ["--no-builtin-tools", "--no-approve"] : approve ? ["--approve"] : []),
2330
+ p.prompt,
2331
+ ];
2332
+
2333
+ const piBin = resolvePiBinary();
2334
+ const selectedTools = allow.split(",").filter((name) => name && !excludes.has(name));
2335
+ const unavailable = taskTools?.refused.filter((tool) => selectedTools.includes(tool.name)) ?? [];
2336
+ const unavailableTools = unavailable.map((tool) => tool.name);
2337
+ if (sandboxEnabled && selectedTools.length && unavailableTools.length === selectedTools.length) {
2338
+ throw new Error(`No requested tool has a verified task sandbox adapter: ${unavailable.map((tool) => `${tool.name} (${tool.reason})`).join(", ")}.`);
2339
+ }
2340
+ const taskRuntime = sandboxEnabled && requestedSandboxDir ? prepareTaskRuntime({
2341
+ root: requestedSandboxDir, controlDir: join(runDir(id), "control"), piBin,
2342
+ tools: selectedTools,
2343
+ permissions: permissionPlan.permissions && { ...permissionPlan.permissions, ...commandSettings },
2344
+ applyPatch: taskTools?.applyPatch === true,
2345
+ extensionTools: taskTools?.trusted.map(({ loadPath: _loadPath, ...tool }) => tool) ?? [],
2346
+ extensionPaths: extArgs.flatMap((arg, index) => arg === "--extension" && extArgs[index + 1] ? [extArgs[index + 1]!] : []),
2347
+ runtimeRoots: [baseDir()],
2348
+ }) : undefined;
2349
+ launchScratch = taskRuntime?.policy.scratch;
2350
+ if (sandboxEnabled && !taskRuntime) throw new Error("Task sandbox has no workspace; refusing an unconfined child.");
2351
+ // Parent-authored trust record, written before the child can run (#325).
2352
+ if (taskRuntime) recordTaskRuntimeProvenance(id);
2353
+ // Outside project = Write or Write & delete lets the run change files
2354
+ // outside its workspace: start an APFS local snapshot (macOS, in the
2355
+ // background; a failure is reported, never blocks the run).
2356
+ const snapshot = taskRuntime ? takeRecoverySnapshot(taskRuntime.policy.permissions) : undefined;
2357
+ if (snapshot?.started) {
2358
+ void snapshot.done.then((outcome) => {
2359
+ if (outcome.ok) return;
2360
+ // The snapshot can finish after the session was replaced and ctx went stale.
2361
+ try { ctx.ui?.notify?.(`Subagent ${id}: recovery snapshot failed (run continues): ${outcome.detail}`, "warning"); } catch { /* ignore */ }
2362
+ });
2363
+ }
2364
+ const cmd = taskRuntime ? { file: taskRuntime.file, fileArgs: [...taskRuntime.fileArgs, ...args] } : { file: piBin, fileArgs: args };
2365
+ const sandboxDir = taskRuntime ? requestedSandboxDir : undefined;
2099
2366
 
2100
- let spawned: ReturnType<typeof spawnDetached>;
2101
- let lease: ConversationLease | undefined;
2102
- try {
2103
2367
  // Reservations prevent competing admissions, but do not grandfather
2104
2368
  // unstarted work after a cap reduction. No await separates this live
2105
2369
  // occupancy check, child creation, and the running metadata below.
@@ -2122,106 +2386,120 @@ export default function (pi: ExtensionAPI) {
2122
2386
  if (resume) revalidateContinuationUnderLease(resume, callbackOrigin);
2123
2387
  spawned = spawnDetached({ file: cmd.file, fileArgs: cmd.fileArgs, cwd, logPath: logPathFor(id),
2124
2388
  env: { [STEER_FILE_ENV]: steerPathFor(id) } });
2125
- } catch (error) {
2126
- // Nothing references the run yet (no metadata): drop its directory (prompt, control/), its
2127
- // provenance record, its session directory, its clone workspace, and the task scratch, so a
2128
- // failed launch leaves nothing behind (#325, #332). A continuation's session
2129
- // directory is the retained owner's and is never removed here.
2130
- lease?.release();
2131
- discardFailedLaunch(id, { sessionDir: childSessionDir, workspaceDir: ownedCloneWorkspace, scratch: taskRuntime?.policy.scratch });
2132
- throw error;
2133
- }
2134
- // Record process identity (pgid, start-time token) so health
2135
- // reconciliation can tell a supervised child from a recycled pid
2136
- // or an orphaned process group (#63). Best-effort: when the OS
2137
- // probes are unavailable the fields stay absent and the run is
2138
- // reconciled via the conservative old-metadata path.
2139
- const identity = captureProcessIdentity(spawned.pid, spawnIdentityProbe);
2140
- const startedAt = Date.now();
2141
- // The effective launch recipe is frozen on the attempt so a later
2142
- // continuation can reproduce its runtime intent without re-resolving the
2143
- // catalog or guessing from current configuration.
2144
- const recipe = buildLaunchRecipe({
2145
- attemptId: id,
2146
- sessionId,
2147
- sessionDir: childSessionDir,
2148
- cwd,
2149
- model,
2150
- effort: thinking,
2151
- tools: allow,
2152
- excludeTools: requestedExcludes.size ? [...requestedExcludes].join(",") : undefined,
2153
- clean,
2154
- allowNested,
2155
- approve,
2156
- sandbox: sandboxEnabled,
2157
- sandboxDir: requestedSandboxDir,
2158
- gitCloneWorkspace,
2159
- callback: callbackEnabled,
2160
- name: launchName,
2161
- agent: resume ? resume.recipe.agent : p.agent,
2162
- role: resume ? resume.recipe.role : p.role,
2163
- alias: resume ? resume.recipe.alias : p.alias,
2164
- catalog: launchCatalog,
2165
- extensionArgs: extArgs,
2166
- baseExtensionArgs,
2167
- trustedExtensions: resume?.recipe.trustedExtensions ?? taskTools?.trusted.map(({ name, package: owner, loadPath }) => ({ name, package: owner, loadPath })),
2168
- });
2389
+ // Record process identity (pgid, start-time token) so health
2390
+ // reconciliation can tell a supervised child from a recycled pid
2391
+ // or an orphaned process group (#63). Best-effort: when the OS
2392
+ // probes are unavailable the fields stay absent and the run is
2393
+ // reconciled via the conservative old-metadata path.
2394
+ const identity = captureProcessIdentity(spawned.pid, spawnIdentityProbe);
2395
+ const startedAt = Date.now();
2396
+ // The effective launch recipe is frozen on the attempt so a later
2397
+ // continuation can reproduce its runtime intent without re-resolving the
2398
+ // catalog or guessing from current configuration.
2399
+ const recipe = buildLaunchRecipe({
2400
+ attemptId: id,
2401
+ sessionId,
2402
+ sessionDir: childSessionDir,
2403
+ cwd,
2404
+ model,
2405
+ effort: thinking,
2406
+ tools: allow,
2407
+ excludeTools: requestedExcludes.size ? [...requestedExcludes].join(",") : undefined,
2408
+ clean,
2409
+ allowNested,
2410
+ approve,
2411
+ sandbox: sandboxEnabled,
2412
+ sandboxDir: requestedSandboxDir,
2413
+ gitCloneWorkspace,
2414
+ callback: callbackEnabled,
2415
+ name: launchName,
2416
+ agent: resume ? resume.recipe.agent : p.agent,
2417
+ role: resume ? resume.recipe.role : p.role,
2418
+ alias: resume ? resume.recipe.alias : p.alias,
2419
+ catalog: launchCatalog,
2420
+ extensionArgs: extArgs,
2421
+ baseExtensionArgs,
2422
+ trustedExtensions: resume?.recipe.trustedExtensions ?? taskTools?.trusted.map(({ name, package: owner, loadPath }) => ({ name, package: owner, loadPath })),
2423
+ });
2169
2424
 
2170
- const meta: RunMeta = {
2171
- id, name: launchName, status: "running",
2172
- pid: spawned.pid, spawnPid: process.pid, spawnPidStartTime: parentStartToken(), model,
2173
- effort: thinking, cwd,
2174
- ...identity,
2175
- promptPreview: p.prompt.slice(0, 200),
2176
- startedAt, logPath: logPathFor(id), sessionId,
2177
- rootRunId,
2178
- ...(resume ? { resumedFrom: resume.prior.id } : {}),
2179
- recipe,
2180
- callbackOrigin,
2181
- sandbox: sandboxDir, taskRuntime: Boolean(taskRuntime), taskScratch: taskRuntime?.policy.scratch, callback: callbackEnabled,
2182
- ...batchInfo,
2183
- // The launch record is JSON. Registry freezes that value; it does not
2184
- // require the resolver's nominal type to carry an index signature.
2185
- ...(launchCatalog ? { catalog: launchCatalog as unknown as RunMeta["catalog"] } : {}),
2186
- timing: resolveRunTiming({ params: p, settings: cfg, env: process.env, startedAt }),
2187
- };
2188
- // Register exit supervision before any fallible post-spawn publication.
2189
- // A failed metadata write must not strand a running child without a close
2190
- // handler; the lease stays held until that child has actually exited.
2191
- void spawned.exit.then((code) => {
2192
- try { finalizeRun(pi, ctx, id, code); }
2193
- finally { lease?.release(); }
2194
- });
2195
- try {
2425
+ const meta: RunMeta = {
2426
+ id, name: launchName, status: "running",
2427
+ pid: spawned.pid, spawnPid: process.pid, spawnPidStartTime: parentStartToken(), model,
2428
+ effort: thinking, cwd,
2429
+ ...identity,
2430
+ promptPreview: p.prompt.slice(0, 200),
2431
+ startedAt, logPath: logPathFor(id), sessionId,
2432
+ rootRunId,
2433
+ ...(resume ? { resumedFrom: resume.prior.id } : {}),
2434
+ recipe,
2435
+ callbackOrigin,
2436
+ sandbox: sandboxDir, taskRuntime: Boolean(taskRuntime), taskScratch: taskRuntime?.policy.scratch, callback: callbackEnabled,
2437
+ ...batchInfo,
2438
+ // The launch record is JSON. Registry freezes that value; it does not
2439
+ // require the resolver's nominal type to carry an index signature.
2440
+ ...(launchCatalog ? { catalog: launchCatalog as unknown as RunMeta["catalog"] } : {}),
2441
+ timing: resolveRunTiming({ params: p, settings: cfg, env: process.env, startedAt }),
2442
+ };
2443
+ // This instance holds the exit observer for a run it actually
2444
+ // started; only it can finalize on the exit event (#625).
2445
+ directlySupervisedRunIds.add(id);
2446
+ // A launch is live work of the current session, so an earlier
2447
+ // teardown of this instance no longer applies. Without this the
2448
+ // teardown latch would keep supervision from ever settling again
2449
+ // for a run started after it (#625).
2450
+ sessionTornDown = false;
2451
+ // Register exit supervision before any fallible post-spawn publication.
2452
+ // A failed metadata write must not strand a running child without a close
2453
+ // handler; the lease stays held until that child has actually exited.
2454
+ void spawned.exit.then((code) => {
2455
+ try { finalizeRun(pi, ctx, id, code); }
2456
+ finally { lease?.release(); }
2457
+ });
2196
2458
  writeMeta(meta);
2459
+ committed = true;
2460
+ // `meta.json` is now the record of this run; the claim has served its
2461
+ // purpose. Best effort: a leftover claim is inert while metadata exists.
2462
+ clearLaunchAttempt(id);
2463
+
2464
+ uiCtx = ctx;
2465
+ ensureTicker();
2466
+ // Start periodic supervision reconciliation (self-stops when idle).
2467
+ ensureHealthTicker();
2468
+ // Footer hint: a visible run now exists, so `← background work · N` shows.
2469
+ updateNavigatorFooter(ctx);
2470
+
2471
+ const toolSummary = taskTools ? describeTaskTools(taskTools) : undefined;
2472
+ const runtime = resolution.mode === "inherit"
2473
+ ? `Runtime: ALL installed extensions (inheritExtensions) — mid-turn drain risk\n`
2474
+ : toolSummary
2475
+ ? `Runtime: isolated · ${toolSummary}${resolution.specs.length ? ` · extensions ${resolution.specs.join(", ")}` : ""}\n`
2476
+ : resolution.specs.length
2477
+ ? `Runtime: isolated · extensions ${resolution.specs.join(", ")}\n`
2478
+ : `Runtime: isolated · built-in tools only\n`;
2479
+ const warn = (unavailable.length ? `Task sandbox: ${unavailable.map((tool) => `${tool.name} disabled (${tool.reason})`).join("; ")}.\n` : "") +
2480
+ (!sandboxEnabled && resolution.unmapped.length
2481
+ ? `NOTE: no extension mapped for ${resolution.unmapped.join(", ")} — ` +
2482
+ `${resolution.unmapped.length > 1 ? "these tools" : "this tool"} will NOT exist in the child. ` +
2483
+ `Add a toolExtensions entry in config.json.\n`
2484
+ : "");
2485
+ const modelNote = catalogDefaultNote(resume ? undefined : p.catalog, model, thinking);
2486
+ return { id, meta, spawned, runtime: runtime + (meta.timing ? `${formatTimingLimits(meta.timing, startedAt)}\n` : ""), warn, sandboxDir, modelNote };
2197
2487
  } catch (error) {
2198
- killProcessTree(spawned.pid, "SIGKILL");
2488
+ // A launch that never committed metadata is not a run: drop
2489
+ // everything the attempt created so the registry keeps no
2490
+ // unreadable record (#325, #332, #623). A continuation's session
2491
+ // directory belongs to the retained owner and a caller-chosen
2492
+ // `sandbox_dir` is never ours, so `discardFailedLaunch` only
2493
+ // removes this attempt's own paths. A child that already started
2494
+ // must not keep running unsupervised; its log goes with the
2495
+ // attempt, because a record without metadata can never be read.
2496
+ if (!committed) {
2497
+ lease?.release();
2498
+ if (spawned) killProcessTree(spawned.pid, "SIGKILL");
2499
+ discardFailedLaunch(id, { sessionDir: childSessionDir, workspaceDir: ownedCloneWorkspace, scratch: launchScratch });
2500
+ }
2199
2501
  throw error;
2200
2502
  }
2201
-
2202
- uiCtx = ctx;
2203
- ensureTicker();
2204
- // Start periodic supervision reconciliation (self-stops when idle).
2205
- ensureHealthTicker();
2206
- // Footer hint: a visible run now exists, so `← background work · N` shows.
2207
- updateNavigatorFooter(ctx);
2208
-
2209
- const toolSummary = taskTools ? describeTaskTools(taskTools) : undefined;
2210
- const runtime = resolution.mode === "inherit"
2211
- ? `Runtime: ALL installed extensions (inheritExtensions) — mid-turn drain risk\n`
2212
- : toolSummary
2213
- ? `Runtime: isolated · ${toolSummary}${resolution.specs.length ? ` · extensions ${resolution.specs.join(", ")}` : ""}\n`
2214
- : resolution.specs.length
2215
- ? `Runtime: isolated · extensions ${resolution.specs.join(", ")}\n`
2216
- : `Runtime: isolated · built-in tools only\n`;
2217
- const warn = (unavailable.length ? `Task sandbox: ${unavailable.map((tool) => `${tool.name} disabled (${tool.reason})`).join("; ")}.\n` : "") +
2218
- (!sandboxEnabled && resolution.unmapped.length
2219
- ? `NOTE: no extension mapped for ${resolution.unmapped.join(", ")} — ` +
2220
- `${resolution.unmapped.length > 1 ? "these tools" : "this tool"} will NOT exist in the child. ` +
2221
- `Add a toolExtensions entry in config.json.\n`
2222
- : "");
2223
- const modelNote = catalogDefaultNote(resume ? undefined : p.catalog, model, thinking);
2224
- return { id, meta, spawned, runtime: runtime + (meta.timing ? `${formatTimingLimits(meta.timing, startedAt)}\n` : ""), warn, sandboxDir, modelNote };
2225
2503
  }
2226
2504
 
2227
2505
  // ---- subagent_spawn -------------------------------------------------
@@ -2252,7 +2530,7 @@ export default function (pi: ExtensionAPI) {
2252
2530
  "Subagent sandboxing defaults to off. Human settings in /sandbox control file, credential-file, command, and network permissions; sandbox:false cannot override an enabled human profile. Set sandbox:true to request kernel confinement, including without published settings. Set callback:false to finish quietly — then read the result on demand via subagent_result.",
2253
2531
  "Every launch automatically joins one shared harness-owned watcher, including batch launches; it stops when the last active run ends. Do not start a separate heartbeat or background watcher for subagents. No progress for stuck_minutes (default 10) wakes you once without stopping the run. Elapsed-time limits are opt-in: deadline_minutes steers the child to wrap up and later stops it after grace_minutes, while max_minutes stops it without grace. Do not set elapsed-time limits merely because a task may take a while; use them only when the work needs a real wall-clock bound.",
2254
2532
  "Use git_clone_workspace:true when the subagent will mutate Git in a sandbox. The parent prepares a disposable, self-contained clone with a real .git/ directory inside the sandbox root, so linked-worktree metadata outside the sandbox cannot stall the child.",
2255
- "Saved conversations persist automatically. To continue a completed worker in its own history, call subagent_spawn with session_id (the native session id reported for the saved conversation) and the new feedback as prompt. Omit session_id for a brand-new conversation.",
2533
+ "Saved conversations persist automatically. To continue a completed or stopped worker in its own history, call subagent_spawn with session_id (the native session id reported for the saved conversation) and the new feedback as prompt. Omit session_id for a brand-new conversation.",
2256
2534
  "On a continuation, pass prompt, session_id, and only optional model, thinking, callback, or timing overrides. Launch-only options (name, agent, role, alias, tools, exclude_tools, clean, sandbox, sandbox_dir, cwd, git_clone_workspace, approve, allow_nested) keep the saved recipe; repeat them only with the same value, otherwise the launch is refused.",
2257
2535
  "Do not restate the original task or role when continuing: they already live in the saved conversation. A running or orphaned latest attempt blocks continuation until it stops, and missing saved history is refused rather than recreated.",
2258
2536
  ],
@@ -2328,7 +2606,7 @@ export default function (pi: ExtensionAPI) {
2328
2606
  reserved = 0;
2329
2607
  return {
2330
2608
  content: [{ type: "text" as const, text:
2331
- `Subagent continued: ${plan.recipe.name ? `${plan.recipe.name} ` : ""}id=${id} (pid ${spawned.pid}) from ${plan.prior.id}.\n` +
2609
+ `Subagent continued: ${plan.recipe.name ? `${plan.recipe.name} ` : ""}id=${id} (pid ${spawned.pid}) from ${plan.prior.id}${plan.prior.status === "killed" ? " (interrupted attempt)" : ""}.\n` +
2332
2610
  `Conversation: session ${plan.conversation.sessionId} — pass session_id=${plan.conversation.sessionId} for the next follow-up.\n` +
2333
2611
  (modelNote ? `${modelNote[0]!.toUpperCase()}${modelNote.slice(1)}.\n` : "") +
2334
2612
  (continuation.callback === false
@@ -2672,9 +2950,12 @@ export default function (pi: ExtensionAPI) {
2672
2950
  const acceptanceResultTool = subagentResultTool(Type, toolSession);
2673
2951
  pi.registerTool(acceptanceResultTool);
2674
2952
  publishAcceptanceHooks(acceptanceResultTool);
2675
- const acceptanceStopTool = subagentStopTool(Type, { onStopped: () => {
2953
+ const acceptanceStopTool = subagentStopTool(Type, { onStopped: (id) => {
2676
2954
  renderWidget();
2677
2955
  syncHealthTicker();
2956
+ // Stopping a run is a terminal transition, so it owes the caller its one
2957
+ // completion callback even when the caller is the one who asked (#624).
2958
+ enqueueCompletionCallback(pi, id);
2678
2959
  } });
2679
2960
  acceptanceStopToolRef = acceptanceStopTool;
2680
2961
  pi.registerTool(acceptanceStopTool);
@@ -2853,6 +3134,10 @@ export default function (pi: ExtensionAPI) {
2853
3134
  // alive, resume the ticking widget. Deferred out of the factory per pi's
2854
3135
  // "no background resources at load" rule.
2855
3136
  pi.on("session_start", async (_event, ctx) => {
3137
+ // A session begins in this process again (reload, restart, or a session
3138
+ // switch), so the previous session's teardown no longer applies: the
3139
+ // replacing session owns this instance's supervision loops (#625).
3140
+ sessionTornDown = false;
2856
3141
  setCallbackBatchContext(pi, ctx);
2857
3142
  agentSessionSettings.restore(ctx);
2858
3143
  restoreDelegationMode(ctx);
@@ -2870,6 +3155,13 @@ export default function (pi: ExtensionAPI) {
2870
3155
  // - Repaint the widget even if its last in-memory lines match; the host
2871
3156
  // may have dropped extension UI during reload/session replacement.
2872
3157
  ensureSubagentProvider();
3158
+ // A reload/restart leaves detached children alive without an in-memory
3159
+ // exit observer (#625). Finalize any that finished while the foreground
3160
+ // session was gone; live ones stay `running` and the ticker below
3161
+ // supervises them until they exit. This runs BEFORE abandonment
3162
+ // adoption: a finished child's coherent log is terminal evidence, and
3163
+ // `lost` would otherwise win the race and hide the result.
3164
+ recoverInterruptedSubagents(pi);
2873
3165
  // Adopt records left non-terminal by a pi that died without a clean
2874
3166
  // shutdown, so the age sweep can eventually retire them.
2875
3167
  reconcileAbandonedRuns();
@@ -2897,18 +3189,34 @@ export default function (pi: ExtensionAPI) {
2897
3189
  });
2898
3190
 
2899
3191
  // Tear down the timer and clear the widget when the session ends.
2900
- pi.on("session_shutdown", async (_event, ctx) => {
3192
+ pi.on("session_shutdown", async (event, ctx) => {
2901
3193
  if (typeof unsubscribeSettingsRequest === "function") unsubscribeSettingsRequest();
2902
- // The foreground Pi session owns this work. Stop current-session
2903
- // running/orphaned children before dropping the session origin, so they
2904
- // cannot become live process groups with no coordinator.
2905
- stopCurrentSessionSubagents(ctx);
2906
- // The stopped children exit after this handler returns; their finalizers
2907
- // must not reach for a ctx that Pi invalidates once the session is replaced.
3194
+ // #625: subagent children are detached process groups that outlive this
3195
+ // foreground session. A controlled reload or quit must not destroy
3196
+ // delegated work: record the interruption durably, warn the human, and
3197
+ // leave the child, its log, and its saved state untouched. The next
3198
+ // session of this pi process resumes supervision and finalizes the run
3199
+ // from the child's own log.
3200
+ const reason = typeof event?.reason === "string" ? event.reason : "shutdown";
3201
+ try {
3202
+ const interrupted = interruptCurrentSessionSubagents(reason, ctx);
3203
+ warnInterruptedSubagents(ctx, interrupted, reason);
3204
+ } catch { /* shutdown cleanup must never block the session teardown */ }
3205
+ // Late finalizers of surviving children must not restart supervision
3206
+ // loops in this replaced instance.
3207
+ sessionTornDown = true;
3208
+ // Children keep running; their finalizers (if this instance still holds
3209
+ // one) must not reach for a ctx that Pi invalidates once the session is
3210
+ // replaced.
2908
3211
  uiCtx = undefined;
2909
3212
  agentSessionSettings.clear();
2910
3213
  catalogModelRegistry = undefined;
2911
- activeCallbackOrigin = undefined;
3214
+ // `/reload` keeps the same session identity, so a finalizer that lands
3215
+ // after the replacement still targets the live session and may deliver
3216
+ // its completion. Every other reason replaces or ends that identity, so
3217
+ // the origin is dropped and the pending marker is left for whichever
3218
+ // session owns the run next.
3219
+ if (reason !== "reload") activeCallbackOrigin = undefined;
2912
3220
  if (typeof unsubscribeDelegationRequest === "function") unsubscribeDelegationRequest();
2913
3221
  cancelCallbackBatch(pi);
2914
3222
  mainAgentStartedAt = undefined;