pi-better-subagents 0.26.0 → 0.26.2

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,11 +32,11 @@ 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";
39
- import { loadConfig, writeDelegationMode, writeSubagentSettings, isConcurrencyCap, normalizeConcurrencyCap, normalizeTools, resolveExtensionPath, selfDir, SAFE_DEFAULT_TOOLS, SAFE_CLEAN_TOOLS } from "./config.ts";
39
+ import { loadConfig, writeDelegationMode, writeSubagentSettings, isConcurrencyCap, normalizeConcurrencyCap, normalizeTools, resolveExtensionPath, configPath, selfDir, SAFE_DEFAULT_TOOLS, SAFE_CLEAN_TOOLS } from "./config.ts";
40
40
  import { createSubagentSettingsPage } from "./settings-page.ts";
41
41
  import { effectiveSubagentSettings, formatSubagentSettings, subagentSettingsTool, SUBAGENT_SETTINGS_CONTEXT } from "./effective-settings.ts";
42
42
  import { STEER_FILE_ENV, readSteerReceipt } from "./child-steer.ts";
@@ -57,6 +57,8 @@ import {
57
57
  import { readAppendedLines, type LogCursor } from "./log-cursor.ts";
58
58
  import { DELEGATION_MODES, DELEGATION_MODE_REQUEST, isDelegationMode, normalizeDelegationMode, type DelegationMode } from "./delegation.ts";
59
59
  import { appendExecutionPolicy } from "./shared-execution-policy.ts";
60
+ import { resolveChildClosure, resolveChildLaunch, configSnapshot } from "./child-dependencies.mjs";
61
+ import { PREFLIGHT_ENV } from "./child-preflight.mjs";
60
62
  import { resolveExtensions, extensionArgs } from "./extensions.ts";
61
63
  import { prepareTaskRuntime, applyDirectApplicationLoadout, RUN_APPLICATION, SDK_BUILTIN_TOOLS } from "./task-policy.ts";
62
64
  import { canonicalizePath, takeRecoverySnapshot } from "./shared-sandbox-core.ts";
@@ -66,7 +68,7 @@ import {
66
68
  announceExecutionAdapter, observeSandboxPermissions, resolveCommandSettings, resolveSubagentPermissions,
67
69
  } from "./permission-policy.ts";
68
70
  import { resolveSubagentWorkspace } from "./git-workspace.ts";
69
- import { join } from "node:path";
71
+ import { dirname, join } from "node:path";
70
72
  import {
71
73
  baseDir,
72
74
  taskWorkspaceDir,
@@ -74,6 +76,8 @@ import {
74
76
  runDir,
75
77
  recordTaskRuntimeProvenance,
76
78
  discardFailedLaunch,
79
+ recordLaunchAttempt,
80
+ clearLaunchAttempt,
77
81
  logPathFor,
78
82
  promptPathFor,
79
83
  nextRunId,
@@ -295,10 +299,18 @@ function verifiedOriginFromContext(ctx: ExtensionContext | undefined): RunCallba
295
299
  }
296
300
  }
297
301
 
302
+ /**
303
+ * Instance-local suppression: this module has no active session, not the run.
304
+ * A finalizer that runs after `/reload` (the process and its exit observer
305
+ * survive the session) can report this even though the replacing session owns
306
+ * the run, so it must never be written as a durable suppression (#625).
307
+ */
308
+ const NO_ACTIVE_SESSION_REASON = "active session identity is unavailable";
309
+
298
310
  function callbackSuppressionReason(meta: RunMeta, active: RunCallbackOrigin | undefined = activeCallbackOrigin): string | undefined {
299
311
  const origin = meta.callbackOrigin;
300
312
  if (origin) {
301
- if (!active) return "active session identity is unavailable";
313
+ if (!active) return NO_ACTIVE_SESSION_REASON;
302
314
  if (origin.cwd !== active.cwd) return `origin cwd ${origin.cwd} does not match active cwd ${active.cwd}`;
303
315
  if (origin.sessionId && origin.sessionId !== active.sessionId) {
304
316
  return `origin session ${origin.sessionId} does not match active session ${active.sessionId ?? "unknown"}`;
@@ -333,25 +345,104 @@ function hasSelfProcessIdentity(meta: RunMeta): boolean {
333
345
  return meta.pid === process.pid || meta.pgid === process.pid;
334
346
  }
335
347
 
336
- function stopCurrentSessionSubagents(ctx: ExtensionContext): void {
348
+ /**
349
+ * Runs this extension instance launched, so its in-memory exit observer is the
350
+ * authority that finalizes them. A run adopted after `/reload` is absent here:
351
+ * the instance that held the observer is gone, so supervision falls back to the
352
+ * child's own log (see `finalizeInterruptedRunFromLog`).
353
+ */
354
+ const directlySupervisedRunIds = new Set<string>();
355
+
356
+ /**
357
+ * Detach current-session live work instead of killing it (#625).
358
+ *
359
+ * Subagent children are detached process groups: they survive the foreground
360
+ * process dying. The previous shutdown loop therefore made every controlled
361
+ * `/reload` (and every clean quit) a silent, destructive end to in-flight work —
362
+ * no drain, no warning, and the run recorded `killed`. Shutdown now only records
363
+ * that this session's direct supervision ended; the child and all of its saved
364
+ * state stay untouched, and the next session of the same pi process resumes
365
+ * supervision and finalizes it from the child's own log.
366
+ *
367
+ * Returns the interrupted runs so the caller can warn the human.
368
+ */
369
+ function interruptCurrentSessionSubagents(reason: string, ctx: ExtensionContext): RunMeta[] {
337
370
  const origin = callbackOriginFromContext(ctx);
371
+ const now = Date.now();
372
+ const interrupted: RunMeta[] = [];
338
373
  for (const summary of listMetasForParent(process.pid)) {
339
374
  if (!ownedByThisParent(summary)) continue;
340
375
  if (summary.status !== "running" && summary.status !== "orphaned") continue;
341
376
  if (!belongsToOrigin(summary, origin)) continue;
342
- // Automatic shutdown cleanup must not let corrupt or synthetic metadata
343
- // signal the foreground Pi process itself.
377
+ // Corrupt or synthetic metadata must never point the interruption record
378
+ // (or any later signal) at the foreground Pi process itself.
344
379
  if (hasSelfProcessIdentity(summary)) continue;
345
- try { stopRun(summary.id); } catch { /* best-effort shutdown cleanup */ }
380
+ try {
381
+ // Re-read under the id: a run may have finished while shutdown ran.
382
+ const meta = readMeta(summary.id);
383
+ if (!meta || (meta.status !== "running" && meta.status !== "orphaned")) continue;
384
+ meta.supervisionInterruptedAt = now;
385
+ meta.supervisionInterruptedReason = reason;
386
+ writeMeta(meta);
387
+ interrupted.push(meta);
388
+ } catch { /* a failed marker must never kill or block the child */ }
346
389
  spendCache.delete(summary.id);
347
390
  healthLogCache.delete(summary.id);
348
391
  resetChildEventLogCursor(summary.id);
349
392
  }
393
+ return interrupted;
394
+ }
395
+
396
+ /** Warn the human that a shutdown/reload left delegated work running (#625). */
397
+ function warnInterruptedSubagents(ctx: ExtensionContext, interrupted: RunMeta[], reason: string): void {
398
+ if (interrupted.length === 0) return;
399
+ const count = interrupted.length;
400
+ const label = count === 1 ? "1 subagent run is" : `${count} subagent runs are`;
401
+ const ids = interrupted.slice(0, 3).map((meta) => meta.id).join(", ") + (count > 3 ? ", …" : "");
402
+ const verb = reason === "reload" ? "reload" : "session shutdown";
403
+ const guidance = reason === "reload"
404
+ ? "The reloaded session resumes supervision and reports the result; use subagent_stop to end it instead."
405
+ : "They keep running detached and stay readable with subagent_result/subagent_output; use subagent_stop to end one.";
406
+ try {
407
+ ctx.ui.notify(`Subagent ${label} still running (${ids}) — ${verb} no longer kills delegated work. ${guidance}`, "warning");
408
+ } catch { /* no UI available (print/RPC/quit) */ }
409
+ }
410
+
411
+ /**
412
+ * True once this extension instance's `session_shutdown` has run. A late child
413
+ * finalizer can still execute after `/reload` (the process and its exit
414
+ * observer survive the session), and such a finalizer must not restart
415
+ * supervision loops or durably suppress a callback just because THIS instance
416
+ * no longer has a session.
417
+ */
418
+ let sessionTornDown = false;
419
+
420
+ /**
421
+ * "The rightful conversation is not the active one", not "this notification is
422
+ * dead" (#625). These reasons only defer delivery to whoever owns the run, so
423
+ * they must never consume an interrupted run's owed completion.
424
+ */
425
+ function isConversationIdentityReason(reason: string): boolean {
426
+ return reason === NO_ACTIVE_SESSION_REASON
427
+ || reason.startsWith("origin session ")
428
+ || reason.startsWith("origin cwd ")
429
+ || reason.startsWith("legacy run cwd ");
350
430
  }
351
431
 
352
432
  function markCompletionCallbackSuppressed(id: string, reason: string, now: number = Date.now()): void {
433
+ // A finalizer that runs after this instance was torn down cannot name the
434
+ // session that owns the run now. Suppressing durably would erase the
435
+ // pending marker the replacing session recovers (#625), so leave it.
436
+ if (sessionTornDown && reason === NO_ACTIVE_SESSION_REASON) return;
353
437
  const meta = readMeta(id);
354
438
  if (!meta || meta.completionCallbackSentAt !== undefined || meta.completionCallbackSuppressedAt !== undefined) return;
439
+ // An explicitly interrupted run owes its completion to the conversation that
440
+ // launched it (#625, DEV-226 criterion 5). An unrelated session merely being
441
+ // active — B opening before the original A returns — drops this delivery
442
+ // attempt but must keep the obligation: the pending marker stays, and A
443
+ // recovers it when it comes back. Records that never lost supervision keep
444
+ // today's durable suppression, so legacy/foreign notifications stay dead.
445
+ if (meta.supervisionInterruptedAt !== undefined && isConversationIdentityReason(reason)) return;
355
446
  meta.completionCallbackSuppressedAt = now;
356
447
  meta.completionCallbackSuppressedReason = reason;
357
448
  writeMeta(meta);
@@ -401,12 +492,34 @@ function enqueueCompletionCallback(pi: ExtensionAPI, id: string): void {
401
492
  });
402
493
  }
403
494
 
404
- /** Recover only records explicitly marked pending; legacy terminal runs never replay. */
495
+ /**
496
+ * Recover only records explicitly marked pending; legacy terminal runs never replay.
497
+ *
498
+ * Current-parent records are recovered unconditionally (the owner decides, and the
499
+ * session gate still suppresses a different foreground session). A run an
500
+ * interrupted DEAD parent left behind is recovered only by the conversation that
501
+ * launched it: that session id is the ownership proof, so an unrelated session
502
+ * never adopts it. A foreign parent that is still alive keeps ownership — the
503
+ * same `isAbandonedByParent` proof the running-record supervision uses — so this
504
+ * path never takes a live pi's terminal callback (#625, DEV-226 criterion 5).
505
+ */
405
506
  function recoverCompletionCallbacks(pi: ExtensionAPI): void {
406
507
  for (const meta of listMetasForParent(process.pid)) {
407
508
  if (!ownedByThisParent(meta)) continue;
408
509
  enqueueCompletionCallback(pi, meta.id);
409
510
  }
511
+ const activeSessionId = activeCallbackOrigin?.sessionId;
512
+ if (!activeSessionId) return;
513
+ for (const summary of listMetas()) {
514
+ if (ownedByThisParent(summary) || summary.supervisionInterruptedAt === undefined) continue;
515
+ if (summary.status === "running" || summary.status === "orphaned") continue;
516
+ // A live foreign parent still owns its run's callback: never deliver for it.
517
+ if (!isAbandonedByParent(summary, realProcessProbe)) continue;
518
+ const meta = readMeta(summary.id);
519
+ if (!meta || meta.status === "running" || meta.status === "orphaned") continue;
520
+ if (meta.callbackOrigin?.sessionId !== activeSessionId) continue;
521
+ enqueueCompletionCallback(pi, meta.id);
522
+ }
410
523
  }
411
524
 
412
525
  function deliverFailureAttention(pi: ExtensionAPI | undefined, meta: RunMeta, now: number): void {
@@ -673,7 +786,9 @@ function childSteerExtensionPath(): string {
673
786
  function readProgress(meta: RunMeta): ProgressState {
674
787
  let entry = progressCache.get(meta.id);
675
788
  const read = readAppendedLines(logPathFor(meta.id), entry?.cursor);
676
- if (!entry || read.restarted) entry = { state: emptyProgress(meta.startedAt) };
789
+ // A fresh (or restarted) fold may have lost the start of a call that is still
790
+ // running: seed it from the durable record rather than reporting silence.
791
+ if (!entry || read.restarted) entry = { state: emptyProgress(meta.startedAt, meta.timing?.inFlight) };
677
792
  if (read.error === undefined) entry.cursor = read.cursor;
678
793
  for (const line of read.lines) {
679
794
  if (!isProgressRelevantLine(line)) continue;
@@ -755,6 +870,9 @@ function stopForTiming(pi: ExtensionAPI | undefined, id: string, reason: TimingS
755
870
  // it was finalized from its log): its own exit is the outcome, not a harness stop.
756
871
  patchTiming(id, { stopReason: undefined, stoppedAt: undefined });
757
872
  progressCache.delete(id);
873
+ // A log finalization is terminal evidence discovered here, not by the child
874
+ // exit handler, so this path still owes the one completion callback (#624).
875
+ if (pi && outcome.action === "finalized") enqueueCompletionCallback(pi, id);
758
876
  return outcome.action === "finalized";
759
877
  }
760
878
  const current = readMeta(id);
@@ -785,10 +903,24 @@ function enforceTiming(pi: ExtensionAPI | undefined, meta: RunMeta, now: number)
785
903
  return timing.ceilingAt !== undefined && now >= timing.ceilingAt ? stopForTiming(pi, meta.id, "ceiling", now) : false;
786
904
  }
787
905
  if (meta.status !== "running") return false;
788
- const needsProgress = timing.stuckMs !== undefined || (timing.deadlineAt !== undefined && now >= timing.deadlineAt);
906
+ // Progress is folded whenever a control can use it: the stuck window, or a deadline whose
907
+ // steer must be held behind a running call (the record of that call must exist before the
908
+ // deadline, not only after it).
909
+ const needsProgress = timing.stuckMs !== undefined || timing.deadlineAt !== undefined;
789
910
  const progress = needsProgress ? readProgress(meta) : undefined;
790
911
  const patch: Partial<NonNullable<RunMeta["timing"]>> = {};
791
912
  if (progress?.lastProgressAt !== undefined && progress.lastProgressAt > (timing.lastProgressAt ?? 0)) patch.lastProgressAt = progress.lastProgressAt;
913
+ if (progress) {
914
+ // Durable still-alive evidence: the call the child is waiting on. Survives a
915
+ // reload whose bounded log read no longer contains the call's start (#620).
916
+ const openId = progress.open.keys().next().value as string | undefined;
917
+ const since = progress.inFlightSince ?? progress.lastEventAt ?? meta.startedAt;
918
+ if (openId === undefined) {
919
+ if (timing.inFlight !== undefined) patch.inFlight = undefined;
920
+ } else if (timing.inFlight?.id !== openId || timing.inFlight.since !== since) {
921
+ patch.inFlight = { id: openId, since };
922
+ }
923
+ }
792
924
  if (timing.steerRequestedAt !== undefined && timing.steerDeliveredAt === undefined) {
793
925
  // The child's receipt for this run's steer; clamped so a skewed clock cannot move grace earlier than the request.
794
926
  const receipt = readSteerReceipt(steerPathFor(meta.id));
@@ -845,6 +977,14 @@ function reconcileHealth(): void {
845
977
  summary: meta.status === "lost" ? "Child supervision was lost; outcome is unknown" : "Child supervision interrupted; related work may still be alive" }], now);
846
978
  }
847
979
  deliverFailureAttention(pi, meta, now);
980
+ // Interrupted work whose child already exited is finalized from its own
981
+ // coherent log before any other verdict (and before timing can mislabel
982
+ // an already-finished run as stopped) (#625).
983
+ if (meta.status === "running" || meta.status === "orphaned") {
984
+ try {
985
+ if (finalizeInterruptedRunFromLog(pi, meta, now)) continue;
986
+ } catch { /* best-effort; the ordinary reconciliation below still runs */ }
987
+ }
848
988
  try {
849
989
  if (enforceTiming(pi, meta, now)) continue;
850
990
  } catch { /* timing is best-effort per tick; supervision below still runs */ }
@@ -882,6 +1022,19 @@ function reconcileHealth(): void {
882
1022
  deliverHealthCallback(pi, meta, meta.status, now);
883
1023
  }
884
1024
  }
1025
+ // A restart leaves an explicitly interrupted child whose owning pi is gone
1026
+ // (#625). Its record is foreign, so the owner-gated loops above never see it:
1027
+ // finalize it from its own coherent log once the child itself is gone. This
1028
+ // is the human's own interrupted work, not another session's live run, and
1029
+ // `finalizeInterruptedRunFromLog` still requires all process evidence to be
1030
+ // absent, so a live writer is never touched.
1031
+ for (const summary of listMetas()) {
1032
+ if (summary.status !== "running" && summary.status !== "orphaned") continue;
1033
+ if (ownedByThisParent(summary) || !ownsInterruptedSupervision(summary)) continue;
1034
+ const meta = readMeta(summary.id);
1035
+ if (!meta || (meta.status !== "running" && meta.status !== "orphaned")) continue;
1036
+ try { finalizeInterruptedRunFromLog(pi, meta, Date.now()); } catch { /* the next tick retries */ }
1037
+ }
885
1038
  // Completed runs can still have failed completion handoffs to retry.
886
1039
  for (const summary of listMetasForParent(process.pid)) {
887
1040
  if (!pi || !ownedByThisParent(summary) || summary.status === "running" || summary.status === "orphaned" || summary.status === "lost") continue;
@@ -905,6 +1058,11 @@ export function progressCacheIdsForTests(): string[] {
905
1058
  return [...progressCache.keys()];
906
1059
  }
907
1060
 
1061
+ /** Test seam: drop the in-memory progress fold, as a reloaded extension instance does. */
1062
+ export function forgetProgressCacheForTests(): void {
1063
+ progressCache.clear();
1064
+ }
1065
+
908
1066
  /**
909
1067
  * This pi's own start-identity token, recorded on every run it spawns so a later
910
1068
  * process can tell "my parent is gone" from "my parent's pid was recycled".
@@ -960,12 +1118,24 @@ function reconcileAbandonedRuns(now: number = Date.now()): number {
960
1118
 
961
1119
  /** Completion batches own their retry timer; only supervision keeps this one alive. */
962
1120
  function syncHealthTicker(): void {
963
- if (needsMonitoring(listMetasForParent(process.pid))) ensureHealthTicker();
1121
+ // A replaced instance never restarts supervision loops for a session it no
1122
+ // longer owns; the live instance runs its own. It must still STOP one that is
1123
+ // already armed: a run this instance launched before teardown can finish
1124
+ // afterwards, and returning early here left the interval supervising a
1125
+ // session that no longer exists (#625).
1126
+ if (sessionTornDown) {
1127
+ stopHealthTicker();
1128
+ return;
1129
+ }
1130
+ if (needsMonitoring(listMetasForParent(process.pid)) || needsInterruptedSupervision()) ensureHealthTicker();
964
1131
  else stopHealthTicker();
965
1132
  }
966
1133
 
967
1134
  /** Start the reconciliation loop if it isn't already running. */
968
1135
  function ensureHealthTicker(): void {
1136
+ // Not gated on `sessionTornDown`: a spawn always means the current session is
1137
+ // doing new work. Only `syncHealthTicker` — the path a late child finalizer
1138
+ // takes — stays closed in a replaced instance.
969
1139
  if (healthTicker) return;
970
1140
  healthTicker = setInterval(reconcileHealth, HEALTH_TICK_MS);
971
1141
  healthTicker.unref?.(); // never keep the process alive on our account
@@ -1108,6 +1278,10 @@ function navigatorCloseRun(id: string) {
1108
1278
  resetChildEventLogCursor(id);
1109
1279
  resetParseRunCursor(id);
1110
1280
  syncHealthTicker();
1281
+ // Close stops (or log-finalizes) the run, which is a terminal transition:
1282
+ // queue its one completion callback so no terminal state is silent (#624).
1283
+ // enqueueCompletionCallback is a no-op for runs that owe no callback.
1284
+ if (healthPi) enqueueCompletionCallback(healthPi, id);
1111
1285
  return outcome;
1112
1286
  }
1113
1287
 
@@ -1447,21 +1621,100 @@ function resolvePiBinary(): string {
1447
1621
  * first-party finalizer (finalization.ts) so tests can exercise the durable
1448
1622
  * path without importing the pi package.
1449
1623
  */
1450
- function finalizeRun(pi: ExtensionAPI, ctx: ExtensionContext, id: string, code: number | null): void {
1624
+ function finalizeRun(pi: ExtensionAPI, ctx: ExtensionContext | undefined, id: string, code: number | null): void {
1451
1625
  progressCache.delete(id);
1626
+ directlySupervisedRunIds.delete(id);
1452
1627
  // Host-facing wrapper around first-party finalizer (finalization.ts).
1453
1628
  // Coherent child-exit evidence may supersede provisional orphaned/lost
1454
1629
  // reconciliation; finalization.ts enforces canExitFinalize + lifecycle authority.
1455
1630
  finalizeRunCore(id, code, {
1456
1631
  renderWidget,
1457
1632
  notify: (message, level) => {
1458
- try { ctx.ui.notify(message, level); } catch { /* ignore */ }
1633
+ try { ctx?.ui.notify(message, level); } catch { /* ignore */ }
1459
1634
  },
1460
1635
  sendMessage: () => enqueueCompletionCallback(pi, id),
1461
1636
  });
1462
1637
  syncHealthTicker();
1463
1638
  }
1464
1639
 
1640
+ /**
1641
+ * Finalize a run whose supervision a previous session interrupted (`/reload`,
1642
+ * a session switch, or a quit) once its process evidence is gone (#625).
1643
+ *
1644
+ * The instance that held the in-memory exit observer is gone, so nothing else
1645
+ * reads the child's own log when the process disappears: health reconciliation
1646
+ * alone would record an interrupted-but-finished run `lost`, hiding a result
1647
+ * that is fully on disk. Only coherent terminal stream evidence is accepted
1648
+ * (`agent_end` with every tool call closed); anything else keeps the existing
1649
+ * reconciliation verdict, so no failure or completion is manufactured.
1650
+ *
1651
+ * Runs this instance launched are skipped: their exit observer finalizes them.
1652
+ */
1653
+ function finalizeInterruptedRunFromLog(
1654
+ pi: ExtensionAPI | undefined,
1655
+ meta: RunMeta,
1656
+ now: number,
1657
+ ): boolean {
1658
+ if (!pi) return false;
1659
+ if (directlySupervisedRunIds.has(meta.id)) return false;
1660
+ if (meta.supervisionInterruptedAt === undefined) return false;
1661
+ // Process evidence still exists: the child keeps running, nothing to finalize.
1662
+ if (reconcileRun(meta, realProcessProbe, now).status !== "lost") return false;
1663
+ let run;
1664
+ try { run = parseRunForLifecycle(meta.id); } catch { return false; }
1665
+ if (!run.sawEnd || run.unmatchedToolCalls.length > 0) return false;
1666
+ // Exit code is unknown after the observer is gone; the lifecycle authority
1667
+ // classifies from the coherent stream instead of inventing one.
1668
+ finalizeRun(pi, uiCtx, meta.id, null);
1669
+ return true;
1670
+ }
1671
+
1672
+ /**
1673
+ * Does this process have to supervise this explicit interruption record (#625)?
1674
+ *
1675
+ * A run this parent launched is this session's own (#625 reload). A run left by
1676
+ * a parent that is provably gone has no live owner at all — the restart case —
1677
+ * so its recorded interruption is the only thing that can recover it. Anything
1678
+ * else belongs to a live pi and is never adjudicated here.
1679
+ */
1680
+ function ownsInterruptedSupervision(summary: Pick<RunMeta, "spawnPid" | "spawnPidStartTime" | "supervisionInterruptedAt">): boolean {
1681
+ if (summary.supervisionInterruptedAt === undefined) return false;
1682
+ return ownedByThisParent(summary) || isAbandonedByParent(summary, realProcessProbe);
1683
+ }
1684
+
1685
+ /** True while an interrupted record still needs this process's supervision loop. */
1686
+ function needsInterruptedSupervision(): boolean {
1687
+ try {
1688
+ for (const summary of listMetas()) {
1689
+ if (summary.status !== "running" && summary.status !== "orphaned") continue;
1690
+ if (ownsInterruptedSupervision(summary)) return true;
1691
+ }
1692
+ } catch { /* best-effort scheduler gate */ }
1693
+ return false;
1694
+ }
1695
+
1696
+ /**
1697
+ * Attempt log-evidence finalization for every interrupted run this process has
1698
+ * to supervise: its own current-parent ones and the ones a dead parent left
1699
+ * behind. Live children are never finalized (`finalizeInterruptedRunFromLog`
1700
+ * requires the process evidence to be gone), so this only recovers a child that
1701
+ * already finished on its own.
1702
+ */
1703
+ function recoverInterruptedSubagents(pi: ExtensionAPI | undefined): number {
1704
+ let recovered = 0;
1705
+ const now = Date.now();
1706
+ for (const summary of listMetas()) {
1707
+ if (summary.status !== "running" && summary.status !== "orphaned") continue;
1708
+ if (!ownsInterruptedSupervision(summary)) continue;
1709
+ const meta = readMeta(summary.id);
1710
+ if (!meta || (meta.status !== "running" && meta.status !== "orphaned")) continue;
1711
+ try {
1712
+ if (finalizeInterruptedRunFromLog(pi, meta, now)) recovered += 1;
1713
+ } catch { /* best-effort at session start; the health ticker retries */ }
1714
+ }
1715
+ return recovered;
1716
+ }
1717
+
1465
1718
  /**
1466
1719
  * Re-prove a continuation's native history identity after its writer lease is held.
1467
1720
  *
@@ -1923,183 +2176,204 @@ export default function (pi: ExtensionAPI) {
1923
2176
  // A continuation never prepares another clone: the recipe's workspace already
1924
2177
  // holds the prior attempt's uncommitted work.
1925
2178
  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
- }
2179
+ // A launch attempt only becomes a run when `writeMeta` commits. Until
2180
+ // then everything it creates (prompt, control/, provenance, its own
2181
+ // session dir, clone workspace, task scratch) belongs to the attempt and
2182
+ // must go if it fails, so no unreadable record is left in the registry
2183
+ // (#325, #332, #623).
2184
+ let lease: ConversationLease | undefined;
2185
+ let spawned: ReturnType<typeof spawnDetached> | undefined;
2186
+ let launchScratch: string | undefined;
2187
+ let committed = false;
2188
+ try {
2189
+ if (!resume) mkdirSync(childSessionDir, { recursive: true });
2190
+ mkdirSync(runDir(id), { recursive: true });
2191
+ // Claim the directory before anything else is prepared. Until
2192
+ // `meta.json` exists this claim is the only ownership evidence, so a
2193
+ // concurrent purge can tell this live attempt from dead launch debris
2194
+ // (#623 R1). The outer catch drops the whole directory on failure.
2195
+ recordLaunchAttempt(id);
2196
+
2197
+ const workspace = resume
2198
+ ? { cwd: resume.recipe.cwd, requestedSandboxDir: resume.recipe.sandboxDir }
2199
+ : resolveSubagentWorkspace({
2200
+ ctxCwd: ctx.cwd,
2201
+ cwd: p.cwd,
2202
+ sandboxDir: p.sandbox_dir ?? ownedCloneWorkspace,
2203
+ gitCloneWorkspace: p.git_clone_workspace,
2204
+ runId: id,
2205
+ runDirPath: runDir(id),
2206
+ sandboxEnabled,
2207
+ });
2208
+ const cwd = workspace.cwd;
2209
+ const requestedSandboxDir = workspace.requestedSandboxDir;
2210
+
2211
+ if (requestedSandboxDir) mkdirSync(requestedSandboxDir, { recursive: true });
2212
+ writeFileSync(promptPathFor(id), p.prompt);
2213
+
2214
+ // A continuation keeps the recipe's launch intent; only current
2215
+ // permission-driven adjustments are re-derived from it.
2216
+ const requestedTools = resume ? resume.recipe.tools : p.tools;
2217
+ const requestedExcludeTools = resume ? resume.recipe.excludeTools ?? "" : p.exclude_tools ?? "";
2218
+ const clean = resume ? resume.recipe.clean : p.clean === true;
2219
+ const allowNested = resume ? resume.recipe.allowNested : p.allow_nested === true;
2220
+ const approve = resume ? resume.recipe.approve : p.approve === true;
2221
+ const gitCloneWorkspace = resume ? resume.recipe.gitCloneWorkspace : p.git_clone_workspace === true;
2222
+ const callbackEnabled = resume ? p.callback ?? resume.recipe.callback : p.callback !== false;
2223
+ const launchName = resume ? resume.recipe.name : p.name;
2224
+ // The frozen launch snapshot is the same shape a fresh spawn freezes.
2225
+ const launchCatalog: RunMeta["catalog"] = resume
2226
+ ? resume.recipe.catalog
2227
+ : p.catalog as unknown as RunMeta["catalog"] | undefined;
2228
+
2229
+ let allow = normalizeTools(
2230
+ requestedTools ?? cfg.defaultTools ?? (clean ? SAFE_CLEAN_TOOLS : SAFE_DEFAULT_TOOLS),
2231
+ );
2232
+ if (allowNested) {
2233
+ const have = new Set(allow.split(","));
2234
+ allow = [...allow.split(","), ...SUBAGENT_TOOLS.filter((t) => !have.has(t))]
2235
+ .filter(Boolean).join(",");
2236
+ }
1969
2237
 
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({
2238
+ // A confined child gets extension tools only through /sandbox Subagents · Tools (ADR 0009):
2239
+ // the guarded apply_patch adapter, and trusted tools admitted by name and package.
2240
+ const requestedExcludes = new Set(requestedExcludeTools.split(",").map((t) => t.trim()).filter(Boolean));
2241
+ if (sandboxEnabled && !clean) {
2242
+ const names = allow.split(",").filter(Boolean);
2243
+ // Models reach for apply_patch whenever they may edit; ticked trusted tools join the default set.
2244
+ if (permissionPlan.tools.applyPatch && names.some((name) => name === "edit" || name === "write")) names.push(APPLY_PATCH);
2245
+ if (requestedTools === undefined) names.push(...permissionPlan.tools.trusted.map((entry) => entry.name));
2246
+ allow = [...new Set(names)].join(",");
2247
+ }
2248
+ if (sandboxEnabled && requestedTools === undefined && permissionPlan.permissions?.processAccess === "read") {
2249
+ allow = [...new Set([...allow.split(","), "process_list"])].join(",");
2250
+ }
2251
+ // Shell Off confines the child to directly launched applications: a requested bash
2252
+ // becomes the guarded run_application builtin. Exclusions stay exclusions (an excluded
2253
+ // run_application leaves bash out rather than restoring it), and a read-only loadout
2254
+ // keeps no command capability at all.
2255
+ const commandSettings = resolveCommandSettings(permissionPlan.permissions);
2256
+ if (sandboxEnabled && !commandSettings.shell) {
2257
+ allow = applyDirectApplicationLoadout(allow.split(",").filter(Boolean), {
2258
+ shell: false, excluded: requestedExcludes,
2259
+ }).tools.join(",");
2260
+ }
2261
+ const taskTools = sandboxEnabled ? planTaskTools({
2262
+ requested: allow.split(",").filter((name) => name && !requestedExcludes.has(name)),
2263
+ settings: permissionPlan.tools, network: permissionPlan.permissions?.network ?? true,
2264
+ processAccess: permissionPlan.permissions?.processAccess ?? "off",
2265
+ builtins: [...TASK_BUILTINS, "codemode"], registered: pi.getAllTools?.() ?? [],
2266
+ toolExtensions: cfg.toolExtensions, resolvePath: resolveExtensionPath,
2267
+ }) : undefined;
2268
+ const dependencyOptions = {
2269
+ model, virtual: (() => {
2270
+ const slash = model?.indexOf("/") ?? -1;
2271
+ return slash > 0 && ctx.modelRegistry?.find?.(model!.slice(0, slash), model!.slice(slash + 1))?.api === "pi-virtual";
2272
+ })(), config: cfg, resolvePath: resolveExtensionPath,
2273
+ configPaths: [configPath(), join(selfDir(), "config.json")],
2274
+ };
2275
+ const { resolution, fullResolution } = await resolveChildLaunch({ ...dependencyOptions, resolution: resolveExtensions({
2276
+ // Only SDK builtins reach `--tools` and extension resolution: process_list and run_application
2277
+ // are task builtins that the mandatory guard installs and activates itself.
2023
2278
  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,
2025
- });
2026
- const referenceArgs = [...extensionArgs(reference, resolveExtensionPath).args, ...codemodeArgs,
2027
- ...(!resume.recipe.baseExtensionArgs ? trustedExtArgs : []),
2279
+ model, clean, allowNested: sandboxEnabled ? false : allowNested, config: cfg,
2280
+ }) }, taskTools?.trusted.map(tool => tool.loadPath) ?? []);
2281
+ const { args: resolvedExtArgs, missing } = extensionArgs(resolution, (spec) => resolution.paths[spec] ?? resolveExtensionPath(spec));
2282
+ const trustedExtArgs = fullResolution.specs.map(spec => fullResolution.paths[spec])
2283
+ .filter(path => !resolvedExtArgs.includes(path)).flatMap(path => ["--extension", path]);
2284
+ // Harness child controls ride along in every mode, including clean and unsandboxed runs.
2285
+ // They deliver deadline steers and keep external monitoring with the coordinator.
2286
+ const codemodeArgs = !sandboxEnabled && allow.split(",").includes("codemode") && !requestedExcludes.has("codemode")
2287
+ ? ["--extension", join(selfDir(), "child-codemode.ts")] : [];
2288
+ const extArgs = [...resolvedExtArgs, ...trustedExtArgs, ...codemodeArgs,
2028
2289
  "--extension", childSteerExtensionPath(), "--extension", join(selfDir(), "child-ownership.ts")]
2029
2290
  .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
- }
2291
+ const baseExtensionArgs = [...resolvedExtArgs, ...codemodeArgs,
2292
+ "--extension", childSteerExtensionPath(), "--extension", join(selfDir(), "child-ownership.ts")]
2293
+ .map((value, index, all) => sandboxEnabled && all[index - 1] === "--extension" ? canonicalizePath(value) : value);
2294
+ if (resume?.recipe.extensionArgs) {
2295
+ // A model escalation may change provider auth, but an unchanged tool
2296
+ // must not silently switch implementations with current configuration.
2297
+ const reference = model === resume.recipe.model ? resolution : await resolveChildClosure({
2298
+ ...dependencyOptions, model: resume.recipe.model, virtual: false, resolution: resolveExtensions({
2299
+ tools: sandboxEnabled ? allow.split(",").filter((name) => (SDK_BUILTIN_TOOLS as readonly string[]).includes(name)).join(",") : allow,
2300
+ model: resume.recipe.model, clean, allowNested: sandboxEnabled ? false : allowNested, config: cfg,
2301
+ }) });
2302
+ const referenceArgs = [...extensionArgs(reference, (spec) => reference.paths[spec] ?? resolveExtensionPath(spec)).args, ...codemodeArgs,
2303
+ ...(!resume.recipe.baseExtensionArgs ? trustedExtArgs : []),
2304
+ "--extension", childSteerExtensionPath(), "--extension", join(selfDir(), "child-ownership.ts")]
2305
+ .map((value, index, all) => sandboxEnabled && all[index - 1] === "--extension" ? canonicalizePath(value) : value);
2306
+ assertContinuationExtensions(resume.prior.id, resume.recipe,
2307
+ referenceArgs, taskTools?.trusted ?? []);
2308
+ }
2309
+ if (sandboxEnabled && resolution.mode === "inherit") {
2310
+ throw new Error("Task confinement requires explicit extensions; inheritExtensions is unsupported while sandboxing is enabled.");
2311
+ }
2312
+ if (missing.length) {
2313
+ throw new Error(
2314
+ `Subagent needs extension(s) that are not installed: ${missing.join(", ")}. ` +
2315
+ `Install them, drop the tools that require them, or remove the mapping from config.json.`,
2316
+ );
2317
+ }
2042
2318
 
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
- }
2319
+ const excludes = new Set<string>();
2320
+ if (requestedExcludeTools) for (const t of requestedExcludeTools.split(",")) if (t.trim()) excludes.add(t.trim());
2321
+ if (!allowNested && resolution.mode === "inherit") {
2322
+ for (const t of SUBAGENT_TOOLS) excludes.add(t);
2323
+ }
2048
2324
 
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;
2325
+ // A continuation reopens the exact saved conversation with `--session`;
2326
+ // never `--session-id`, which would create a replacement session when the
2327
+ // history is missing, and never both (Pi rejects the combination).
2328
+ const sessionArgs = resume
2329
+ ? ["--session", resume.conversation.path, "--session-dir", childSessionDir]
2330
+ : ["--session-dir", childSessionDir, "--session-id", id];
2331
+ const args = [
2332
+ "-p", "--mode", "json",
2333
+ ...sessionArgs,
2334
+ ...extArgs,
2335
+ ...(model ? ["--model", model] : []),
2336
+ ...(thinking ? ["--thinking", thinking] : []),
2337
+ ...(allow && !sandboxEnabled ? ["--tools", allow] : []),
2338
+ ...(excludes.size ? ["--exclude-tools", [...excludes].join(",")] : []),
2339
+ ...(sandboxEnabled ? ["--no-builtin-tools", "--no-approve"] : approve ? ["--approve"] : []),
2340
+ p.prompt,
2341
+ ];
2342
+
2343
+ const piBin = resolvePiBinary();
2344
+ const selectedTools = allow.split(",").filter((name) => name && !excludes.has(name));
2345
+ const unavailable = taskTools?.refused.filter((tool) => selectedTools.includes(tool.name)) ?? [];
2346
+ const unavailableTools = unavailable.map((tool) => tool.name);
2347
+ if (sandboxEnabled && selectedTools.length && unavailableTools.length === selectedTools.length) {
2348
+ throw new Error(`No requested tool has a verified task sandbox adapter: ${unavailable.map((tool) => `${tool.name} (${tool.reason})`).join(", ")}.`);
2349
+ }
2350
+ const taskRuntime = sandboxEnabled && requestedSandboxDir ? prepareTaskRuntime({
2351
+ root: requestedSandboxDir, controlDir: join(runDir(id), "control"), piBin,
2352
+ tools: selectedTools,
2353
+ permissions: permissionPlan.permissions && { ...permissionPlan.permissions, ...commandSettings },
2354
+ applyPatch: taskTools?.applyPatch === true,
2355
+ extensionTools: taskTools?.trusted.map(({ loadPath: _loadPath, ...tool }) => tool) ?? [],
2356
+ extensionPaths: extArgs.flatMap((arg, index) => arg === "--extension" && extArgs[index + 1] ? [extArgs[index + 1]!] : []),
2357
+ runtimeRoots: [baseDir()],
2358
+ }) : undefined;
2359
+ launchScratch = taskRuntime?.policy.scratch;
2360
+ if (sandboxEnabled && !taskRuntime) throw new Error("Task sandbox has no workspace; refusing an unconfined child.");
2361
+ // Parent-authored trust record, written before the child can run (#325).
2362
+ if (taskRuntime) recordTaskRuntimeProvenance(id);
2363
+ // Outside project = Write or Write & delete lets the run change files
2364
+ // outside its workspace: start an APFS local snapshot (macOS, in the
2365
+ // background; a failure is reported, never blocks the run).
2366
+ const snapshot = taskRuntime ? takeRecoverySnapshot(taskRuntime.policy.permissions) : undefined;
2367
+ if (snapshot?.started) {
2368
+ void snapshot.done.then((outcome) => {
2369
+ if (outcome.ok) return;
2370
+ // The snapshot can finish after the session was replaced and ctx went stale.
2371
+ try { ctx.ui?.notify?.(`Subagent ${id}: recovery snapshot failed (run continues): ${outcome.detail}`, "warning"); } catch { /* ignore */ }
2372
+ });
2373
+ }
2374
+ const cmd = taskRuntime ? { file: taskRuntime.file, fileArgs: [...taskRuntime.fileArgs, ...args] } : { file: process.execPath, fileArgs: [join(selfDir(), "child-runtime.mjs"), piBin, ...args] };
2375
+ const sandboxDir = taskRuntime ? requestedSandboxDir : undefined;
2099
2376
 
2100
- let spawned: ReturnType<typeof spawnDetached>;
2101
- let lease: ConversationLease | undefined;
2102
- try {
2103
2377
  // Reservations prevent competing admissions, but do not grandfather
2104
2378
  // unstarted work after a cap reduction. No await separates this live
2105
2379
  // occupancy check, child creation, and the running metadata below.
@@ -2120,108 +2394,126 @@ export default function (pi: ExtensionAPI) {
2120
2394
  // built from, so `--session` can never reopen a file another sweep
2121
2395
  // removed as an empty replacement.
2122
2396
  if (resume) revalidateContinuationUnderLease(resume, callbackOrigin);
2397
+ const preflightPath = join(runDir(id), "child-preflight.json");
2398
+ writeFileSync(preflightPath, JSON.stringify({ ...fullResolution, model, tools: selectedTools,
2399
+ configSnapshot: configSnapshot([dirname(configPath()), join(cwd, ".pi")]),
2400
+ }));
2123
2401
  spawned = spawnDetached({ file: cmd.file, fileArgs: cmd.fileArgs, cwd, logPath: logPathFor(id),
2124
- 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
- });
2402
+ env: { [STEER_FILE_ENV]: steerPathFor(id), [PREFLIGHT_ENV]: preflightPath } });
2403
+ // Record process identity (pgid, start-time token) so health
2404
+ // reconciliation can tell a supervised child from a recycled pid
2405
+ // or an orphaned process group (#63). Best-effort: when the OS
2406
+ // probes are unavailable the fields stay absent and the run is
2407
+ // reconciled via the conservative old-metadata path.
2408
+ const identity = captureProcessIdentity(spawned.pid, spawnIdentityProbe);
2409
+ const startedAt = Date.now();
2410
+ // The effective launch recipe is frozen on the attempt so a later
2411
+ // continuation can reproduce its runtime intent without re-resolving the
2412
+ // catalog or guessing from current configuration.
2413
+ const recipe = buildLaunchRecipe({
2414
+ attemptId: id,
2415
+ sessionId,
2416
+ sessionDir: childSessionDir,
2417
+ cwd,
2418
+ model,
2419
+ effort: thinking,
2420
+ tools: allow,
2421
+ excludeTools: requestedExcludes.size ? [...requestedExcludes].join(",") : undefined,
2422
+ clean,
2423
+ allowNested,
2424
+ approve,
2425
+ sandbox: sandboxEnabled,
2426
+ sandboxDir: requestedSandboxDir,
2427
+ gitCloneWorkspace,
2428
+ callback: callbackEnabled,
2429
+ name: launchName,
2430
+ agent: resume ? resume.recipe.agent : p.agent,
2431
+ role: resume ? resume.recipe.role : p.role,
2432
+ alias: resume ? resume.recipe.alias : p.alias,
2433
+ catalog: launchCatalog,
2434
+ extensionArgs: extArgs,
2435
+ baseExtensionArgs,
2436
+ trustedExtensions: resume?.recipe.trustedExtensions ?? taskTools?.trusted.map(({ name, package: owner, loadPath }) => ({ name, package: owner, loadPath })),
2437
+ });
2169
2438
 
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 {
2439
+ const meta: RunMeta = {
2440
+ id, name: launchName, status: "running",
2441
+ pid: spawned.pid, spawnPid: process.pid, spawnPidStartTime: parentStartToken(), model,
2442
+ effort: thinking, cwd,
2443
+ ...identity,
2444
+ promptPreview: p.prompt.slice(0, 200),
2445
+ startedAt, logPath: logPathFor(id), sessionId,
2446
+ rootRunId,
2447
+ ...(resume ? { resumedFrom: resume.prior.id } : {}),
2448
+ recipe,
2449
+ callbackOrigin,
2450
+ sandbox: sandboxDir, taskRuntime: Boolean(taskRuntime), taskScratch: taskRuntime?.policy.scratch, callback: callbackEnabled,
2451
+ ...batchInfo,
2452
+ // The launch record is JSON. Registry freezes that value; it does not
2453
+ // require the resolver's nominal type to carry an index signature.
2454
+ ...(launchCatalog ? { catalog: launchCatalog as unknown as RunMeta["catalog"] } : {}),
2455
+ timing: resolveRunTiming({ params: p, settings: cfg, env: process.env, startedAt }),
2456
+ };
2457
+ // This instance holds the exit observer for a run it actually
2458
+ // started; only it can finalize on the exit event (#625).
2459
+ directlySupervisedRunIds.add(id);
2460
+ // A launch is live work of the current session, so an earlier
2461
+ // teardown of this instance no longer applies. Without this the
2462
+ // teardown latch would keep supervision from ever settling again
2463
+ // for a run started after it (#625).
2464
+ sessionTornDown = false;
2465
+ // Register exit supervision before any fallible post-spawn publication.
2466
+ // A failed metadata write must not strand a running child without a close
2467
+ // handler; the lease stays held until that child has actually exited.
2468
+ void spawned.exit.then((code) => {
2469
+ try { finalizeRun(pi, ctx, id, code); }
2470
+ finally { lease?.release(); }
2471
+ });
2196
2472
  writeMeta(meta);
2473
+ committed = true;
2474
+ // `meta.json` is now the record of this run; the claim has served its
2475
+ // purpose. Best effort: a leftover claim is inert while metadata exists.
2476
+ clearLaunchAttempt(id);
2477
+
2478
+ uiCtx = ctx;
2479
+ ensureTicker();
2480
+ // Start periodic supervision reconciliation (self-stops when idle).
2481
+ ensureHealthTicker();
2482
+ // Footer hint: a visible run now exists, so `← background work · N` shows.
2483
+ updateNavigatorFooter(ctx);
2484
+
2485
+ const toolSummary = taskTools ? describeTaskTools(taskTools) : undefined;
2486
+ const runtime = resolution.mode === "inherit"
2487
+ ? `Runtime: ALL installed extensions (inheritExtensions) — mid-turn drain risk\n`
2488
+ : toolSummary
2489
+ ? `Runtime: isolated · ${toolSummary}${resolution.specs.length ? ` · extensions ${resolution.specs.join(", ")}` : ""}\n`
2490
+ : resolution.specs.length
2491
+ ? `Runtime: isolated · extensions ${resolution.specs.join(", ")}\n`
2492
+ : `Runtime: isolated · built-in tools only\n`;
2493
+ const warn = (unavailable.length ? `Task sandbox: ${unavailable.map((tool) => `${tool.name} disabled (${tool.reason})`).join("; ")}.\n` : "") +
2494
+ (!sandboxEnabled && resolution.unmapped.length
2495
+ ? `NOTE: no extension mapped for ${resolution.unmapped.join(", ")} — ` +
2496
+ `${resolution.unmapped.length > 1 ? "these tools" : "this tool"} will NOT exist in the child. ` +
2497
+ `Add a toolExtensions entry in config.json.\n`
2498
+ : "");
2499
+ const modelNote = catalogDefaultNote(resume ? undefined : p.catalog, model, thinking);
2500
+ return { id, meta, spawned, runtime: runtime + (meta.timing ? `${formatTimingLimits(meta.timing, startedAt)}\n` : ""), warn, sandboxDir, modelNote };
2197
2501
  } catch (error) {
2198
- killProcessTree(spawned.pid, "SIGKILL");
2502
+ // A launch that never committed metadata is not a run: drop
2503
+ // everything the attempt created so the registry keeps no
2504
+ // unreadable record (#325, #332, #623). A continuation's session
2505
+ // directory belongs to the retained owner and a caller-chosen
2506
+ // `sandbox_dir` is never ours, so `discardFailedLaunch` only
2507
+ // removes this attempt's own paths. A child that already started
2508
+ // must not keep running unsupervised; its log goes with the
2509
+ // attempt, because a record without metadata can never be read.
2510
+ if (!committed) {
2511
+ lease?.release();
2512
+ if (spawned) killProcessTree(spawned.pid, "SIGKILL");
2513
+ discardFailedLaunch(id, { sessionDir: childSessionDir, workspaceDir: ownedCloneWorkspace, scratch: launchScratch });
2514
+ }
2199
2515
  throw error;
2200
2516
  }
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
2517
  }
2226
2518
 
2227
2519
  // ---- subagent_spawn -------------------------------------------------
@@ -2252,7 +2544,7 @@ export default function (pi: ExtensionAPI) {
2252
2544
  "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
2545
  "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
2546
  "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.",
2547
+ "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
2548
  "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
2549
  "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
2550
  ],
@@ -2328,7 +2620,7 @@ export default function (pi: ExtensionAPI) {
2328
2620
  reserved = 0;
2329
2621
  return {
2330
2622
  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` +
2623
+ `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
2624
  `Conversation: session ${plan.conversation.sessionId} — pass session_id=${plan.conversation.sessionId} for the next follow-up.\n` +
2333
2625
  (modelNote ? `${modelNote[0]!.toUpperCase()}${modelNote.slice(1)}.\n` : "") +
2334
2626
  (continuation.callback === false
@@ -2672,9 +2964,12 @@ export default function (pi: ExtensionAPI) {
2672
2964
  const acceptanceResultTool = subagentResultTool(Type, toolSession);
2673
2965
  pi.registerTool(acceptanceResultTool);
2674
2966
  publishAcceptanceHooks(acceptanceResultTool);
2675
- const acceptanceStopTool = subagentStopTool(Type, { onStopped: () => {
2967
+ const acceptanceStopTool = subagentStopTool(Type, { onStopped: (id) => {
2676
2968
  renderWidget();
2677
2969
  syncHealthTicker();
2970
+ // Stopping a run is a terminal transition, so it owes the caller its one
2971
+ // completion callback even when the caller is the one who asked (#624).
2972
+ enqueueCompletionCallback(pi, id);
2678
2973
  } });
2679
2974
  acceptanceStopToolRef = acceptanceStopTool;
2680
2975
  pi.registerTool(acceptanceStopTool);
@@ -2853,6 +3148,10 @@ export default function (pi: ExtensionAPI) {
2853
3148
  // alive, resume the ticking widget. Deferred out of the factory per pi's
2854
3149
  // "no background resources at load" rule.
2855
3150
  pi.on("session_start", async (_event, ctx) => {
3151
+ // A session begins in this process again (reload, restart, or a session
3152
+ // switch), so the previous session's teardown no longer applies: the
3153
+ // replacing session owns this instance's supervision loops (#625).
3154
+ sessionTornDown = false;
2856
3155
  setCallbackBatchContext(pi, ctx);
2857
3156
  agentSessionSettings.restore(ctx);
2858
3157
  restoreDelegationMode(ctx);
@@ -2870,6 +3169,13 @@ export default function (pi: ExtensionAPI) {
2870
3169
  // - Repaint the widget even if its last in-memory lines match; the host
2871
3170
  // may have dropped extension UI during reload/session replacement.
2872
3171
  ensureSubagentProvider();
3172
+ // A reload/restart leaves detached children alive without an in-memory
3173
+ // exit observer (#625). Finalize any that finished while the foreground
3174
+ // session was gone; live ones stay `running` and the ticker below
3175
+ // supervises them until they exit. This runs BEFORE abandonment
3176
+ // adoption: a finished child's coherent log is terminal evidence, and
3177
+ // `lost` would otherwise win the race and hide the result.
3178
+ recoverInterruptedSubagents(pi);
2873
3179
  // Adopt records left non-terminal by a pi that died without a clean
2874
3180
  // shutdown, so the age sweep can eventually retire them.
2875
3181
  reconcileAbandonedRuns();
@@ -2897,18 +3203,34 @@ export default function (pi: ExtensionAPI) {
2897
3203
  });
2898
3204
 
2899
3205
  // Tear down the timer and clear the widget when the session ends.
2900
- pi.on("session_shutdown", async (_event, ctx) => {
3206
+ pi.on("session_shutdown", async (event, ctx) => {
2901
3207
  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.
3208
+ // #625: subagent children are detached process groups that outlive this
3209
+ // foreground session. A controlled reload or quit must not destroy
3210
+ // delegated work: record the interruption durably, warn the human, and
3211
+ // leave the child, its log, and its saved state untouched. The next
3212
+ // session of this pi process resumes supervision and finalizes the run
3213
+ // from the child's own log.
3214
+ const reason = typeof event?.reason === "string" ? event.reason : "shutdown";
3215
+ try {
3216
+ const interrupted = interruptCurrentSessionSubagents(reason, ctx);
3217
+ warnInterruptedSubagents(ctx, interrupted, reason);
3218
+ } catch { /* shutdown cleanup must never block the session teardown */ }
3219
+ // Late finalizers of surviving children must not restart supervision
3220
+ // loops in this replaced instance.
3221
+ sessionTornDown = true;
3222
+ // Children keep running; their finalizers (if this instance still holds
3223
+ // one) must not reach for a ctx that Pi invalidates once the session is
3224
+ // replaced.
2908
3225
  uiCtx = undefined;
2909
3226
  agentSessionSettings.clear();
2910
3227
  catalogModelRegistry = undefined;
2911
- activeCallbackOrigin = undefined;
3228
+ // `/reload` keeps the same session identity, so a finalizer that lands
3229
+ // after the replacement still targets the live session and may deliver
3230
+ // its completion. Every other reason replaces or ends that identity, so
3231
+ // the origin is dropped and the pending marker is left for whichever
3232
+ // session owns the run next.
3233
+ if (reason !== "reload") activeCallbackOrigin = undefined;
2912
3234
  if (typeof unsubscribeDelegationRequest === "function") unsubscribeDelegationRequest();
2913
3235
  cancelCallbackBatch(pi);
2914
3236
  mainAgentStartedAt = undefined;