pi-better-subagents 0.35.0 → 0.36.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/README.md +1 -1
  2. package/assignment-outcomes.ts +11 -5
  3. package/assignment-report.ts +83 -19
  4. package/catalog-host-admission.ts +19 -3
  5. package/catalog-preferences.ts +1 -1
  6. package/catalog-resolver.ts +35 -1
  7. package/catalog-store.ts +27 -20
  8. package/child-apply-patch.ts +13 -0
  9. package/child-dependencies.mjs +25 -12
  10. package/child-operations.ts +80 -1
  11. package/child-preflight.mjs +8 -2
  12. package/child-process-list.ts +8 -0
  13. package/config.ts +46 -2
  14. package/continuation-authority.ts +3 -1
  15. package/continuation-runtime.ts +88 -0
  16. package/docs/usage.md +53 -28
  17. package/extensions.mjs +11 -13
  18. package/finalization.ts +15 -0
  19. package/goal-provider.ts +44 -2
  20. package/health-observation.ts +43 -48
  21. package/index.ts +257 -98
  22. package/launch-context.ts +23 -0
  23. package/launch-digest.mjs +6 -0
  24. package/log-cursor.ts +91 -15
  25. package/managed-launch-bootstrap.mjs +2 -2
  26. package/managed-launch-client.ts +6 -3
  27. package/managed-launch-host.ts +168 -15
  28. package/managed-launch-journal.mjs +1 -5
  29. package/managed-launch-port.ts +4 -0
  30. package/operation-bridge-types.ts +27 -2
  31. package/owned-exit.ts +12 -0
  32. package/package.json +1 -1
  33. package/parse.ts +48 -6
  34. package/permission-policy.ts +41 -8
  35. package/process-identity.d.mts +1 -0
  36. package/process-identity.mjs +29 -0
  37. package/registry.ts +54 -33
  38. package/runtime-client/artifacts/darwin-arm64.gz +0 -0
  39. package/runtime-client/artifacts/darwin-arm64.json +1 -1
  40. package/runtime-client/artifacts/darwin-x64.gz +0 -0
  41. package/runtime-client/artifacts/darwin-x64.json +1 -1
  42. package/runtime-client/artifacts/linux-arm64.gz +0 -0
  43. package/runtime-client/artifacts/linux-arm64.json +1 -1
  44. package/runtime-client/artifacts/linux-x64.gz +0 -0
  45. package/runtime-client/artifacts/linux-x64.json +1 -1
  46. package/runtime-client/src/runtime/client.mjs +30 -3
  47. package/runtime-client/src/runtime/work-client.mjs +150 -7
  48. package/shared-callback-batcher.ts +11 -2
  49. package/shared-catalog.ts +6 -14
  50. package/shared-navigator-panels.ts +26 -4
  51. package/shared-navigator.ts +197 -14
  52. package/shared-operation-coordinator/assignment-inbox.mjs +118 -0
  53. package/shared-operation-coordinator/assignment-observation.mjs +43 -35
  54. package/shared-operation-coordinator/src/assignment-changes.ts +73 -0
  55. package/shared-operation-coordinator/src/assignment-outcomes.ts +2 -0
  56. package/shared-operation-coordinator/src/background-requests.ts +14 -3
  57. package/shared-operation-coordinator/src/discovery.ts +5 -3
  58. package/shared-operation-coordinator/src/operations.ts +50 -2
  59. package/shared-operation-coordinator/src/result-supervision.ts +12 -0
  60. package/shared-operation-coordinator/src/rows.ts +2 -0
  61. package/shared-operation-coordinator/src/schema.ts +40 -24
  62. package/shared-operation-coordinator/src/store.ts +34 -8
  63. package/shared-operation-coordinator/src/subagent-launch.ts +24 -1
  64. package/shared-operation-coordinator/src/types.ts +5 -1
  65. package/shared-sandbox-core.ts +1 -1
  66. package/shared-task-exec.ts +12 -1
  67. package/shared-task-process-identity.ts +126 -0
  68. package/shared-task-process-list.ts +8 -2
  69. package/shared-task-sandbox.ts +5 -3
  70. package/shared-task-tools.ts +8 -5
  71. package/shared-work-client.d.mts +10 -0
  72. package/shared-work-client.mjs +150 -7
  73. package/subagent-tools.ts +28 -34
  74. package/task-policy.ts +3 -1
  75. package/timing.ts +10 -1
  76. package/work-observation.ts +71 -16
  77. package/worker-operations-host.ts +12 -4
  78. package/worker-waits.ts +93 -34
package/index.ts CHANGED
@@ -1,4 +1,6 @@
1
+ import { shouldRestoreWorkObservation } from "./shared-work-client.mjs";
1
2
  import { appendTimingWake, removeTimingReceipt, receiptTimingWake, timingWakeReceipt } from "./timing-notifications.ts";
3
+ import { captureLaunchContext } from "./launch-context.ts";
2
4
  /**
3
5
  * pi-better-subagents — Claude Code-style async subagents for pi.
4
6
  *
@@ -16,7 +18,7 @@ import { createAssignmentProjector } from "./assignment-projection.mjs";
16
18
  import { historicalWaits, attentionRevision, attentionDismissed, dismissAttention } from "./historical-attention.ts";
17
19
  import { registerAssignmentAttempt, commitAssignmentTerminal, readOutcome, receiptOutcome, outcomeTranscriptReceipt, inspectOutcome, createOutcomeHost, closeOutcomeHost, claimOutcome, type AssignmentBinding } from "./assignment-outcomes.ts";
18
20
  import { currentSandboxPermissions } from "./permission-policy.ts";
19
- import { createToolDescriptor } from "./operation-bridge-types.ts";
21
+ import { assertWaitToolDependencies, createToolDescriptor } from "./operation-bridge-types.ts";
20
22
  import { requestResumeAdmission } from "./worker-waits.ts";
21
23
  import { execSync } from "node:child_process";
22
24
  import { writeFileSync, mkdirSync, renameSync, statSync } from "node:fs";
@@ -25,7 +27,7 @@ import * as PiCodingAgent from "@earendil-works/pi-coding-agent";
25
27
  import * as PiTui from "@earendil-works/pi-tui";
26
28
  import { CustomEditor } from "@earendil-works/pi-coding-agent";
27
29
  import { initializeNavigatorPanels } from "./shared-navigator-panels.ts";
28
- import { workObservation, workObservationFailure, startWorkObservation, stopWorkObservation, observedAssignment, observedList, requestWorkDetail, TERMINAL_NAVIGATOR_RETENTION_MS } from "./work-observation.ts";
30
+ import { workObservation, workObservationStarted, workObservationFailure, configureWorkObservation, activateWorkObservation, stopWorkObservation, observedAssignment, observedList, requestWorkDetail, TERMINAL_NAVIGATOR_RETENTION_MS } from "./work-observation.ts";
29
31
  import { withAssignmentObservations } from "./assignment-projection.mjs";
30
32
  import { formatNavigatorHealthFacts } from "./health-surface.mjs";
31
33
  import { matchesKey, Key, truncateToWidth, type AutocompleteItem } from "@earendil-works/pi-tui";
@@ -36,18 +38,20 @@ import {
36
38
  isNavigatorUiAvailable,
37
39
  refreshBackgroundWorkNavigator,
38
40
  registerBackgroundWorkProvider,
41
+ observeNavigatorLaunch,
39
42
  renderRegisteredWorkDetail,
40
43
  type BackgroundWorkDetail,
41
44
  type BackgroundWorkProvider,
42
45
  type BackgroundWorkRow,
43
46
  } from "./shared-navigator.ts";
44
47
  import { spawnDetached, killProcessTree, type SpawnResult } from "./spawn.ts";
45
- import { abortUncommittedLaunch } from "./launch-abort.ts";
46
48
  import { parseRun, parseRunForLifecycle, readRunTranscript, resetParseRunCursor, type Usage } from "./parse.ts";
47
- import { finalizeRun as finalizeRunCore } from "./finalization.ts";
49
+ import { finalizeRun as finalizeRunCore, reconcileInterruptedRun } from "./finalization.ts";
50
+ import { completeOwnedExit } from "./owned-exit.ts";
48
51
  import { selectSessionByName } from "./session-selection.ts";
49
52
  import { isWithinWorkspace } from "./workspace-scope.ts";
50
- import { loadConfig, writeDelegationMode, writeSubagentSettings, isConcurrencyCap, normalizeConcurrencyCap, normalizeTools, resolveExtensionPath, configPath, selfDir, SAFE_DEFAULT_TOOLS, SAFE_CLEAN_TOOLS } from "./config.ts";
53
+ import { BUILTIN_TOOLS } from "./extensions.ts";
54
+ import { ORDINARY_TOOL_PROVIDERS, activeChildProviders, ordinaryChildConfig, addEditablePatch, loadConfig, writeDelegationMode, writeSubagentSettings, isConcurrencyCap, normalizeConcurrencyCap, normalizeTools, resolveExtensionPath, configPath, selfDir, SAFE_DEFAULT_TOOLS, SAFE_CLEAN_TOOLS } from "./config.ts";
51
55
  import { createSubagentSettingsPage } from "./settings-page.ts";
52
56
  import { deliverSubagentPrompt, effectiveSubagentSettings, formatSubagentSettings, subagentSettingsTool, SUBAGENT_SETTINGS_CONTEXT } from "./effective-settings.ts";
53
57
  import { STEER_FILE_ENV, readSteerReceipt } from "./child-steer.ts";
@@ -76,17 +80,14 @@ import {
76
80
  } from "./timing.ts";
77
81
  import { readAppendedLines, type LogCursor } from "./log-cursor.ts";
78
82
  import { DELEGATION_MODES, DELEGATION_MODE_REQUEST, isDelegationMode, normalizeDelegationMode, type DelegationMode } from "./delegation.ts";
79
- import { resolveChildClosure, resolveChildLaunch, configSnapshot } from "./child-dependencies.mjs";
80
- import { PREFLIGHT_ENV } from "./child-preflight.mjs";
81
83
  import { resolveExtensions, extensionArgs } from "./extensions.ts";
82
- import { prepareTaskRuntime, applyDirectApplicationLoadout, RUN_APPLICATION, SDK_BUILTIN_TOOLS } from "./task-policy.ts";
84
+ import { prepareTaskRuntime, applyDirectApplicationLoadout, DEFAULT_TASK_PERMISSIONS, RUN_APPLICATION, SDK_BUILTIN_TOOLS } from "./task-policy.ts";
83
85
  import { canonicalizePath, takeRecoverySnapshot } from "./shared-sandbox-core.ts";
84
86
  import { TASK_BUILTINS } from "./shared-task-sandbox.ts";
85
- import { APPLY_PATCH, describeTaskTools, planTaskTools, selectEffectiveTaskTools } from "./subagent-tools.ts";
87
+ import { describeTaskTools, planTaskTools, selectEffectiveTaskTools } from "./subagent-tools.ts";
86
88
  import {
87
- announceExecutionAdapter, observeSandboxPermissions, resolveCommandSettings, resolveSubagentPermissions,
89
+ announceExecutionAdapter, describeSubagentProcessPolicy, effectiveWorkerProcessAccess, observeSandboxPermissions, resolveCommandSettings, resolveSubagentPermissions,
88
90
  } from "./permission-policy.ts";
89
- import { resolveSubagentWorkspace } from "./git-workspace.ts";
90
91
  import { dirname, isAbsolute, join } from "node:path";
91
92
  import {
92
93
  baseDir,
@@ -127,6 +128,7 @@ import {
127
128
  type ChildEventFacts,
128
129
  type HealthObservation,
129
130
  type ProcessProbe,
131
+ type ReconcileResult,
130
132
  type RawLogDiagnostic,
131
133
  } from "./health.ts";
132
134
  import {
@@ -143,7 +145,7 @@ import {
143
145
  getSharedCapacityGate,
144
146
  } from "./capacity.mjs";
145
147
  import { buildHealthCallbackDelivery } from "./completion.ts";
146
- import { cancelCallbackBatch, getCallbackBatcher, setCallbackBatchContext } from "./shared-callback-batcher.ts";
148
+ import { cancelCallbackBatch, getCallbackBatcher, packCallbackBatch, setCallbackBatchContext } from "./shared-callback-batcher.ts";
147
149
  let managementPort: import("./managed-launch-port.ts").ManagedLaunchPort | undefined;
148
150
  const ownedByThisParent = (meta: Partial<RunMeta>) => managementPort ? managementPort.owns(meta) : ownedByFrontend(meta as RunMeta);
149
151
  const supervisedMetas = () => managementPort ? managementPort.supervised() : listMetasForParent(process.pid);
@@ -174,6 +176,7 @@ import {
174
176
  buildNavigatorDetail,
175
177
  } from "./navigator.ts";
176
178
  import { enforceRegistrySizeCapOnce, runDailyCleanupOnce } from "./cleanup.ts";
179
+ import { managedRuntimeRoot, selectContinuationRuntime } from "./continuation-runtime.ts";
177
180
  import {
178
181
  ContinuationError,
179
182
  acquireConversationLease,
@@ -353,7 +356,7 @@ function callbackOriginFromContext(ctx: ExtensionContext): RunCallbackOrigin {
353
356
  } catch {
354
357
  sessionId = undefined;
355
358
  }
356
- return { cwd: ctx.cwd, sessionId };
359
+ return { cwd: ctx.cwd, sessionId, branchId: ctx.sessionManager?.getLeafId?.() ?? null };
357
360
  }
358
361
 
359
362
  /** Origin with a readable session id, or undefined when identity is unavailable. */
@@ -640,10 +643,52 @@ async function tryEnqueueAssignmentOutcome(pi: ExtensionAPI, meta: RunMeta): Pro
640
643
  const prior = outcomeTranscriptReceipt(ctx.sessionManager.getBranch(), outcome.eventId);
641
644
  if (prior) { receiptOutcome(meta, prior); return; }
642
645
  const deliveryHost = outcomeHost;
643
- const gate = await requestResumeAdmission(pi, active, { timeoutMs: 50 });
646
+ // The Goal scheduler can take up to 20 seconds. Keep the short probe only
647
+ // for a standalone parent, with no bound Goal or acknowledged check.
648
+ const workflowBudgetMs = 25_000;
649
+ const gate = await requestResumeAdmission(pi, active, {
650
+ timeoutMs: active.goalId || outcome.recipient.goalId ? workflowBudgetMs : 50,
651
+ pendingTimeoutMs: workflowBudgetMs,
652
+ });
644
653
  outcomeAdmission.set(outcome.eventId, () => gate.allowed ? gate.isCurrent?.() !== false : !active.goalId && !outcome.recipient.goalId && gate.revision === -1);
645
654
  if (!gate.allowed && (active.goalId || outcome.recipient.goalId || gate.revision !== -1)) {
646
- deferOutcome(meta, gate.reason ?? "Parent admission refused; automatic reconciliation will retry.");
655
+ // Admission controls model execution, not delivery of an already
656
+ // committed result. Paused Goals still owe their human a notification.
657
+ if (sessionTornDown || outcomeHost !== deliveryHost || uiCtx !== ctx || callbackSuppressionReason(meta)
658
+ || (outcome.recipient.branchId && !ctx.sessionManager.getBranch().some(entry => entry.id === outcome.recipient.branchId))) {
659
+ deferOutcome(meta, "Recorded parent delivery scope changed; automatic reconciliation will retry.");
660
+ return;
661
+ }
662
+ // Native Pi queues messages during a turn even with triggerTurn:false.
663
+ // Wait for idle so replay cannot enqueue the same unreceipted message.
664
+ if (!ctx.isIdle()) {
665
+ deferOutcome(meta, "Waiting for an idle parent to append the outcome without starting a turn.");
666
+ return;
667
+ }
668
+ if (!claimOutcome(meta, deliveryHost)) {
669
+ deferOutcome(meta, "Outcome dispatch is owned by another host; automatic reconciliation will retry.");
670
+ return;
671
+ }
672
+ const details = { completionEventIds: [outcome.eventId] };
673
+ const packed = packCallbackBatch([{
674
+ source: "subagent", id: outcome.eventId, inspectId: meta.id, receiptId: outcome.eventId,
675
+ label: meta.name ?? meta.id, status: outcome.outcome, outcome: outcome.reason,
676
+ detailTool: "subagent_result", callback: true,
677
+ }]);
678
+ try {
679
+ await pi.sendMessage({ customType: "background-completion-batch", display: true,
680
+ content: `${packed.text}\nAutomatic continuation: ${gate.reason}`, details }, { triggerTurn: false });
681
+ } catch (error) {
682
+ // A failed persistence must not look like a durable transcript receipt.
683
+ details.completionEventIds.length = 0;
684
+ throw error;
685
+ }
686
+ const entry = outcomeTranscriptReceipt(ctx.sessionManager.getBranch(), outcome.eventId);
687
+ if (!entry) throw new Error("Awaiting durable recipient transcript receipt.");
688
+ receiptOutcome(meta, entry);
689
+ markCompletionCallbackSent(meta.id, Date.now());
690
+ deferOutcome(meta);
691
+ try { ctx.ui?.notify(`${meta.name ?? meta.id}: ${outcome.outcome}. Automatic continuation: ${gate.reason}. Inspect subagent_result.`, outcome.outcome === "failed" ? "warning" : "info"); } catch { /* transcript remains visible */ }
647
692
  return;
648
693
  }
649
694
  // Admission may yield across a session switch or Goal/workflow change.
@@ -767,16 +812,12 @@ function deliverFailureAttention(pi: ExtensionAPI | undefined, meta: RunMeta, no
767
812
 
768
813
  function markHealthCallbackSuppressed(meta: RunMeta, status: "orphaned" | "lost", reason: string, now: number): void {
769
814
  if (isConversationIdentityReason(reason)) return;
770
- if (status === "orphaned") {
771
- if (meta.orphanedCallbackSuppressedAt !== undefined) return;
772
- meta.orphanedCallbackSuppressedAt = now;
773
- meta.orphanedCallbackSuppressedReason = reason;
774
- } else {
775
- if (meta.lostCallbackSuppressedAt !== undefined) return;
776
- meta.lostCallbackSuppressedAt = now;
777
- meta.lostCallbackSuppressedReason = reason;
778
- }
779
- writeMeta(meta);
815
+ writeMeta(meta, { patch: current => {
816
+ if (isHealthCallbackHandled(current, status)) return;
817
+ return status === "orphaned"
818
+ ? { orphanedCallbackSuppressedAt: now, orphanedCallbackSuppressedReason: reason }
819
+ : { lostCallbackSuppressedAt: now, lostCallbackSuppressedReason: reason };
820
+ } });
780
821
  }
781
822
 
782
823
  function isHealthCallbackHandled(meta: RunMeta, status: "orphaned" | "lost"): boolean {
@@ -922,6 +963,7 @@ function stopTicker(): void {
922
963
  /** How often supervision is reconciled. Independent of TUI render scheduling. */
923
964
  const HEALTH_TICK_MS = 15_000;
924
965
  let healthTicker: ReturnType<typeof setInterval> | undefined;
966
+ let managedHealthClose: (() => void) | undefined;
925
967
  /** ExtensionAPI retained so health transitions can deliver coordinator follow-ups (#65). */
926
968
  let healthPi: ExtensionAPI | undefined;
927
969
 
@@ -958,9 +1000,10 @@ function deliverHealthCallback(pi: ExtensionAPI | undefined, meta: RunMeta, stat
958
1000
  try { uiCtx.ui.notify(notice, "warning"); }
959
1001
  catch { return; }
960
1002
  // The marker acknowledges quiet delivery, never a model turn.
961
- if (status === "orphaned") meta.orphanedCallbackSentAt = now;
962
- else meta.lostCallbackSentAt = now;
963
- writeMeta(meta);
1003
+ writeMeta(meta, { patch: current => {
1004
+ if (current.status !== status || isHealthCallbackHandled(current, status) || callbackSuppressionReason(current)) return;
1005
+ return status === "orphaned" ? { orphanedCallbackSentAt: now } : { lostCallbackSentAt: now };
1006
+ } });
964
1007
  return;
965
1008
  }
966
1009
  void getCallbackBatcher(pi).deliverUrgent({
@@ -982,9 +1025,10 @@ function deliverHealthCallback(pi: ExtensionAPI | undefined, meta: RunMeta, stat
982
1025
  markFailureAttentionDelivered(failurePath(meta.id), attention, at);
983
1026
  if (attention.incidents.some((incident) => pendingFailureAttention(collectRunFailures(meta.id, meta.cwd), at, { terminal: true })?.incidents.includes(incident))) return;
984
1027
  }
985
- if (status === "orphaned") current.orphanedCallbackSentAt = at;
986
- else current.lostCallbackSentAt = at;
987
- writeMeta(current);
1028
+ writeMeta(current, { patch: current => {
1029
+ if (isHealthCallbackHandled(current, status)) return;
1030
+ return status === "orphaned" ? { orphanedCallbackSentAt: at } : { lostCallbackSentAt: at };
1031
+ } });
988
1032
  },
989
1033
  onSuppressed: (reason, at) => {
990
1034
  const current = readMeta(meta.id);
@@ -1297,12 +1341,13 @@ function enforceTiming(pi: ExtensionAPI | undefined, meta: RunMeta, now: number)
1297
1341
  }
1298
1342
 
1299
1343
  /** One reconciliation + durable health-callback recovery pass. */
1300
- function reconcileHealth(): void {
1344
+ function reconcileHealth(ids?: readonly string[]): void {
1301
1345
  if (!managementPort) return;
1302
1346
  try { managementPort.assertCurrent(); } catch { stopHealthTicker(); return; }
1303
1347
  const ctx = uiCtx;
1304
1348
  const pi = healthPi;
1305
- for (const summary of supervisedMetas()) {
1349
+ const selected = ids ? ids.map(id => readMeta(id)).filter((meta): meta is NonNullable<typeof meta> => Boolean(meta)) : supervisedMetas();
1350
+ for (const summary of selected) {
1306
1351
  if (!ownedByThisParent(summary)) continue;
1307
1352
  // running/orphaned: process reconcile. lost: durable callback recovery only.
1308
1353
  if (summary.status !== "running" && summary.status !== "orphaned" && summary.status !== "lost") continue;
@@ -1320,9 +1365,18 @@ function reconcileHealth(): void {
1320
1365
  // Interrupted work whose child already exited is finalized from its own
1321
1366
  // coherent log before any other verdict (and before timing can mislabel
1322
1367
  // an already-finished run as stopped) (#625).
1368
+ let interruptedReconciliation: ReconcileResult | undefined;
1323
1369
  if (meta.status === "running" || meta.status === "orphaned") {
1324
1370
  try {
1325
- if (finalizeInterruptedRunFromLog(pi, meta, now)) continue;
1371
+ if (pi && !directlySupervisedRunIds.has(meta.id) && meta.supervisionInterruptedAt !== undefined) {
1372
+ const observed = reconcileInterruptedRun(meta, realProcessProbe, now, {
1373
+ renderWidget,
1374
+ notify: (message, level) => { try { ctx?.ui.notify(message, level); } catch { /* unavailable UI */ } },
1375
+ sendMessage: () => enqueueCompletionCallback(pi, meta.id),
1376
+ });
1377
+ if (observed.finalization?.applied) { syncHealthTicker(); continue; }
1378
+ interruptedReconciliation = observed.reconciliation;
1379
+ }
1326
1380
  } catch { /* best-effort; the ordinary reconciliation below still runs */ }
1327
1381
  }
1328
1382
  try {
@@ -1330,7 +1384,7 @@ function reconcileHealth(): void {
1330
1384
  } catch { /* timing is best-effort per tick; supervision below still runs */ }
1331
1385
 
1332
1386
  if (meta.status === "running" || meta.status === "orphaned") {
1333
- const result = reconcileRun(meta, realProcessProbe, now);
1387
+ const result = interruptedReconciliation ?? reconcileRun(meta, realProcessProbe, now);
1334
1388
  if (result.changed) {
1335
1389
  Object.assign(meta, result.patch, { status: result.status });
1336
1390
  writeMeta(meta);
@@ -1373,7 +1427,7 @@ function reconcileHealth(): void {
1373
1427
  // is the human's own interrupted work, not another session's live run, and
1374
1428
  // `finalizeInterruptedRunFromLog` still requires all process evidence to be
1375
1429
  // absent, so a live writer is never touched.
1376
- for (const summary of listMetas({ includeArchived: false })) {
1430
+ for (const summary of ids ? selected : listMetas({ includeArchived: false })) {
1377
1431
  if (summary.status !== "running" && summary.status !== "orphaned") continue;
1378
1432
  if (ownedByThisParent(summary) || !ownsInterruptedSupervision(summary)) continue;
1379
1433
  const meta = readMeta(summary.id);
@@ -1381,7 +1435,7 @@ function reconcileHealth(): void {
1381
1435
  try { finalizeInterruptedRunFromLog(pi, meta, Date.now()); } catch { /* the next tick retries */ }
1382
1436
  }
1383
1437
  // Completed runs can still have failed completion handoffs to retry.
1384
- for (const summary of supervisedMetas()) {
1438
+ for (const summary of selected) {
1385
1439
  if (!pi || !ownedByThisParent(summary) || summary.status === "running" || summary.status === "orphaned" || summary.status === "lost") continue;
1386
1440
  const meta = readMeta(summary.id);
1387
1441
  if (meta && meta.completionCallbackPendingAt !== undefined && meta.completionCallbackSentAt === undefined && meta.completionCallbackSuppressedAt === undefined) enqueueCompletionCallback(pi!, meta.id);
@@ -1474,6 +1528,7 @@ function syncHealthTicker(): void {
1474
1528
  stopHealthTicker();
1475
1529
  return;
1476
1530
  }
1531
+ if (managementPort.observeHealth) { ensureHealthTicker(); return; }
1477
1532
  if (needsMonitoring(supervisedMetas()) || needsInterruptedSupervision()) ensureHealthTicker();
1478
1533
  else stopHealthTicker();
1479
1534
  }
@@ -1481,6 +1536,10 @@ function syncHealthTicker(): void {
1481
1536
  /** Start the reconciliation loop if it isn't already running. */
1482
1537
  function ensureHealthTicker(): void {
1483
1538
  if (!managementPort) return;
1539
+ if (managementPort.observeHealth) {
1540
+ managedHealthClose ??= managementPort.observeHealth(ids => reconcileHealth(ids));
1541
+ return;
1542
+ }
1484
1543
  // Not gated on `sessionTornDown`: a spawn always means the current session is
1485
1544
  // doing new work. Only `syncHealthTicker` — the path a late child finalizer
1486
1545
  // takes — stays closed in a replaced instance.
@@ -1490,12 +1549,13 @@ function ensureHealthTicker(): void {
1490
1549
  }
1491
1550
 
1492
1551
  function stopHealthTicker(): void {
1552
+ managedHealthClose?.(); managedHealthClose = undefined;
1493
1553
  if (healthTicker) { clearInterval(healthTicker); healthTicker = undefined; }
1494
1554
  }
1495
1555
 
1496
1556
  /** Test/diagnostic seam: whether the periodic reconciliation loop is active. */
1497
1557
  export function isHealthTickerActive(): boolean {
1498
- return healthTicker !== undefined;
1558
+ return healthTicker !== undefined || managedHealthClose !== undefined;
1499
1559
  }
1500
1560
 
1501
1561
  /**
@@ -1563,7 +1623,7 @@ const pendingNavigatorDismissals = new Set<string>();
1563
1623
  function navigatorRunningCount(): number {
1564
1624
  const snapshot = workObservation();
1565
1625
  return (snapshot?.rows.filter((row: any) => !pendingNavigatorDismissals.has(row.meta.id) && !row.meta.dismissedAt && ["running", "waiting"].includes(row.assignment.state)).length ?? 0) +
1566
- (!snapshot || snapshot.status !== "ready" ? 1 : 0);
1626
+ (workObservationStarted() && snapshot?.status !== "ready" ? 1 : 0);
1567
1627
  }
1568
1628
 
1569
1629
  /**
@@ -1671,21 +1731,19 @@ function subagentWorkRows(now: number): BackgroundWorkRow[] {
1671
1731
  const undismissed = new Set(sourceRows.filter((row: any) => !row.meta.dismissedAt).map((row: any) => row.meta.id));
1672
1732
  for (const id of pendingNavigatorDismissals) if (!undismissed.has(id)) pendingNavigatorDismissals.delete(id);
1673
1733
  }
1674
- const rows: BackgroundWorkRow[] = sourceRows.filter((row: any) => !pendingNavigatorDismissals.has(row.meta.id) && !row.meta.dismissedAt &&
1675
- (["running", "waiting"].includes(row.assignment.state) || typeof (row.meta.endedAt ?? row.meta.lostAt) !== "number" ||
1676
- now - (row.meta.endedAt ?? row.meta.lostAt) < TERMINAL_NAVIGATOR_RETENTION_MS)).map((row: any) => {
1734
+ const rows: BackgroundWorkRow[] = sourceRows.filter((row: any) => !pendingNavigatorDismissals.has(row.meta.id) && !row.meta.dismissedAt).map((row: any) => {
1677
1735
  const meta = row.meta;
1678
1736
  const health = row.health ? observeRunHealth({ ...row.health, status: row.assignment.processStatus === "exited" ? meta.status : row.assignment.processStatus, now, startedAt: meta.startedAt }) : undefined;
1679
1737
  const terminal = !["running", "waiting"].includes(row.assignment.state);
1680
- return { providerId: "subagents", id: meta.id, name: meta.name || meta.id,
1738
+ return { providerId: "subagents", id: meta.id, agentId: meta.sessionId ?? meta.id, name: meta.name || meta.id,
1681
1739
  model: shortModel(meta.model), effort: meta.effort, status: row.assignment.state,
1682
1740
  tool: row.display?.tool, tokens: row.display?.spend,
1683
1741
  statusTone: statusTone(row.assignment.state), kind: "subagent", elapsed: fmtElapsed((meta.endedAt ?? now) - meta.startedAt),
1684
1742
  primary: [shortModel(meta.model), meta.effort, row.display?.tool, row.display?.spend].filter(Boolean).join(" ") || "subagent run", facts: formatNavigatorHealthFacts(health), sortStartedAt: meta.startedAt,
1685
1743
  expiresAt: terminal && typeof meta.endedAt === "number" ? meta.endedAt + TERMINAL_NAVIGATOR_RETENTION_MS : undefined };
1686
1744
  });
1687
- if (!snapshot || snapshot.status !== "ready") rows.unshift({ providerId: "subagents", id: "runtime-observation", name: "Subagents",
1688
- status: snapshot?.status ?? "degraded", statusTone: "warning", kind: "observation", elapsed: "", primary: workObservationFailure(), sortStartedAt: now });
1745
+ if (workObservationStarted() && snapshot?.status !== "ready") rows.unshift({ providerId: "subagents", id: "runtime-observation", name: "Status sync",
1746
+ status: snapshot?.status ?? "degraded", statusTone: "warning", kind: "observation", readOnly: true, elapsed: "", primary: "Task status unconfirmed · enter for details", sortStartedAt: now });
1689
1747
  return rows;
1690
1748
  }
1691
1749
 
@@ -1763,6 +1821,13 @@ function mainAgentWorkDetail(now: number): BackgroundWorkDetail {
1763
1821
 
1764
1822
  function subagentWorkDetail(id: string, now: number, options?: { logTailLines?: number }): BackgroundWorkDetail | null {
1765
1823
  if (id === "main") return mainAgentWorkDetail(now);
1824
+ if (id === "runtime-observation") return {
1825
+ providerId: "subagents", id, title: "Subagent status sync", status: workObservation()?.status ?? "rebuilding", statusTone: "warning",
1826
+ subtitle: "Shared status service · task status unconfirmed",
1827
+ metadata: [{ label: "scope", value: "Subagent status reads; not an individual task" }],
1828
+ evidence: { label: "Full diagnostic", text: workObservationFailure() },
1829
+ footerActions: [],
1830
+ };
1766
1831
  const row = requestWorkDetail(id);
1767
1832
  if (!row?.detail) return { providerId: "subagents", id, title: id, status: row?.observationError ? "degraded" : "rebuilding", statusTone: "warning", metadata: [], evidence: { label: "observation", text: row?.observationError ?? workObservationFailure() } };
1768
1833
  const health = row.health ? observeRunHealth({ ...row.health, status: row.assignment.processStatus === "exited" ? row.meta.status : row.assignment.processStatus, now, startedAt: row.meta.startedAt }) : undefined;
@@ -1867,8 +1932,10 @@ function ensureSubagentProvider(): void {
1867
1932
  id: "subagents",
1868
1933
  label: "Subagents",
1869
1934
  priority: 10,
1935
+ onOpen: () => { void activateWorkObservation(); },
1870
1936
  visibleCount: () => navigatorRunningCount(),
1871
- showSection: (rows) => rows.some((row) => row.status === "running" || ["parking", "waiting", "ready", "resuming", "held", "degraded", "rebuilding"].includes(row.status)),
1937
+ // The last worker becoming terminal must not hide its retained result.
1938
+ showSection: (rows) => rows.length > 0,
1872
1939
  parentRow: (now) => mainAgentWorkRow(now),
1873
1940
  listRows: (now) => subagentWorkRows(now),
1874
1941
  detail: (id, now, options) => subagentWorkDetail(id, now, options),
@@ -1884,6 +1951,7 @@ function ensureSubagentProvider(): void {
1884
1951
  },
1885
1952
  armCloseLabel: (row) => pendingNavigatorPark(workObservation()?.rows.find((observed: any) => observed.meta.id === row.id)?.meta) ? "x again to cancel resume" : row.status === "running" || row.status === "orphaned" ? "x again to stop" : "x again to dismiss",
1886
1953
  close: (id) => {
1954
+ if (id === "runtime-observation") return { action: "not-closable", providerId: "subagents", id };
1887
1955
  const outcome = navigatorCloseRun(id) as { action: string; id: string; status?: string };
1888
1956
  return { ...outcome, providerId: "subagents" };
1889
1957
  },
@@ -2115,7 +2183,8 @@ function revalidateContinuationUnderLease(
2115
2183
  id: plan.prior.id,
2116
2184
  prior: current,
2117
2185
  origin,
2118
- others: listMetas(),
2186
+ // Archived attempts are completed and cannot be competing writers.
2187
+ others: listMetas({ includeArchived: false }),
2119
2188
  });
2120
2189
  if (fresh.conversation.sessionId !== plan.conversation.sessionId || fresh.conversation.path !== plan.conversation.path) {
2121
2190
  throw new ContinuationError(
@@ -2668,13 +2737,16 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
2668
2737
  const registerSpawnTool: ExtensionAPI["registerTool"] = (definition) => {
2669
2738
  registeredSpawnSchemas.set(definition.name, definition.parameters);
2670
2739
  pi.registerTool(managed ? { ...definition, async execute(key, params, signal, onUpdate, ctx) {
2740
+ ctx = captureLaunchContext(ctx);
2671
2741
  restoreDelegationMode(ctx);
2672
2742
  await workerOperations.start();
2673
2743
  return definition.execute(key, params, signal, onUpdate, ctx);
2674
2744
  } } : { ...definition, async execute(key, params, _signal, _onUpdate, ctx) {
2745
+ ctx = captureLaunchContext(ctx);
2675
2746
  catalogHostFrom(ctx);
2676
2747
  const { submitManagedLaunch } = await import("./managed-launch-client.ts");
2677
- return await submitManagedLaunch(pi, ctx, key, definition.name, params) as never;
2748
+ void activateWorkObservation();
2749
+ return await observeNavigatorLaunch(ctx, "subagents", key, "Subagent launch", () => submitManagedLaunch(pi, ctx, key, definition.name, params)) as never;
2678
2750
  } });
2679
2751
  };
2680
2752
  announceExecutionAdapter(pi, {
@@ -2828,6 +2900,9 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
2828
2900
  /** Set only when a catalog run's model or effort differs from its role or agent default. */
2829
2901
  modelNote?: string;
2830
2902
  }> {
2903
+ const { resolveChildClosure, resolveChildLaunch, configSnapshot } = await import("./child-dependencies.mjs");
2904
+ const { resolveSubagentWorkspace } = await import("./git-workspace.ts");
2905
+ const { PREFLIGHT_ENV } = await import("./child-preflight.mjs");
2831
2906
  assertThinkingLevel(p.thinking);
2832
2907
  // Skill exposure is a caller choice, not a launch: validate its shape
2833
2908
  // before any attempt directory or capacity effect exists. A continuation
@@ -2846,13 +2921,13 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
2846
2921
  // frozen confinement intent. Historical metadata can never widen authority,
2847
2922
  // and a profile that would change confinement refuses instead of silently
2848
2923
  // moving a live conversation into a different sandbox.
2849
- const permissionPlan = resolveSubagentPermissions(pi, resume ? resume.recipe.sandbox : p.sandbox);
2850
- if (resume && permissionPlan.sandboxEnabled !== resume.recipe.sandbox) {
2851
- throw new ContinuationError(
2852
- `Cannot continue ${resume.prior.id}: current sandbox permissions would change its confinement. ` +
2853
- `Launch a new run instead of continuing this conversation.`,
2854
- );
2855
- }
2924
+ const permissionPlan = resolveSubagentPermissions(pi, p.sandbox,
2925
+ resume && { runId: resume.prior.id, sandbox: resume.recipe.sandbox });
2926
+ const processPolicy = describeSubagentProcessPolicy(permissionPlan, process.platform);
2927
+ const processAccess = effectiveWorkerProcessAccess(permissionPlan);
2928
+ const taskPermissions = permissionPlan.inactiveProfile
2929
+ ? { ...DEFAULT_TASK_PERMISSIONS, processAccess }
2930
+ : permissionPlan.permissions;
2856
2931
  const cfg = loadConfig();
2857
2932
  // Harness-owned timing (soft deadline, ceiling, tool-wait and stuck windows); validated before any side effect.
2858
2933
  resolveRunTiming({ params: launchTimingParams(p), settings: timingSettingsFor(cfg), env: process.env, startedAt: 0 });
@@ -3000,8 +3075,7 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
3000
3075
  .filter(Boolean).join(",");
3001
3076
  }
3002
3077
 
3003
- // A confined child gets extension tools only through /sandbox Subagents · Tools (ADR 0009):
3004
- // the guarded apply_patch adapter, and trusted tools admitted by name and package.
3078
+ // Exclusions apply to the worker selection before provider admission (ADR 0027).
3005
3079
  const requestedExcludes = new Set(requestedExcludeTools.split(",").map((t) => t.trim()).filter(Boolean));
3006
3080
 
3007
3081
  // Supervised worker operations. This only decides which names the
@@ -3044,19 +3118,19 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
3044
3118
  bridgePlan.capabilities = { ...bridgePlan.capabilities, reportAssignment: true };
3045
3119
  productionBridgeSchemas.schemas.set("report_assignment_result", createToolDescriptor("report_assignment_result"));
3046
3120
  }
3121
+ assertWaitToolDependencies(bridgePlan.capabilities, bridgePlan.tools);
3047
3122
  const bridgeEnabled = bridgePlan.tools.length > 0;
3048
3123
  if (bridgeEnabled) {
3049
3124
  allow = [...new Set([...allow.split(",").filter(Boolean), ...bridgePlan.tools])].join(",");
3050
3125
  }
3051
3126
 
3052
- if (sandboxEnabled && !clean) {
3127
+ if (!clean) {
3053
3128
  const names = allow.split(",").filter(Boolean);
3054
- // Models reach for apply_patch whenever they may edit; ticked trusted tools join the default set.
3055
- if (permissionPlan.tools.applyPatch && names.some((name) => name === "edit" || name === "write")) names.push(APPLY_PATCH);
3056
- if (requestedTools === undefined) names.push(...permissionPlan.tools.trusted.map((entry) => entry.name));
3129
+ // Derive the editable loadout before applying the resource policy.
3130
+ if (!resume) addEditablePatch(names, requestedExcludes);
3057
3131
  allow = [...new Set(names)].join(",");
3058
3132
  }
3059
- if (sandboxEnabled && requestedTools === undefined && permissionPlan.permissions?.processAccess === "read") {
3133
+ if (sandboxEnabled && requestedTools === undefined && processAccess === "read") {
3060
3134
  allow = [...new Set([...allow.split(","), "process_list"])].join(",");
3061
3135
  }
3062
3136
  // Shell Off confines the child to directly launched applications: a requested bash
@@ -3076,12 +3150,20 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
3076
3150
  // Candidates for the task-tool plan: exclusions and bridge-supplied
3077
3151
  // names never reach extension admission.
3078
3152
  const plannedTools = allow.split(",").filter((name) => name && !requestedExcludes.has(name) && !bridgeToolNames.has(name));
3153
+ const continuationRuntime = selectContinuationRuntime({ currentDir: selfDir(), recipe: resume?.recipe });
3154
+ const workerPath = (path: string) => continuationRuntime?.mapPath(path) ?? path;
3155
+ const workerArgs = (args: string[]) => continuationRuntime?.mapArgs(args) ?? args;
3156
+ const workerResolvePath = (spec: string) => {
3157
+ const path = resolveExtensionPath(spec);
3158
+ return path ? workerPath(path) : path;
3159
+ };
3160
+ const normalProviders = ordinaryChildConfig(cfg, managed?.activeProviders?.() ?? activeChildProviders(pi));
3079
3161
  const taskTools = sandboxEnabled ? planTaskTools({
3080
3162
  requested: plannedTools,
3081
3163
  settings: permissionPlan.tools, network: permissionPlan.permissions?.network ?? true,
3082
- processAccess: permissionPlan.permissions?.processAccess ?? "off",
3164
+ processAccess,
3083
3165
  builtins: [...TASK_BUILTINS, "codemode"], registered: pi.getAllTools?.() ?? [],
3084
- toolExtensions: cfg.toolExtensions, resolvePath: resolveExtensionPath,
3166
+ toolExtensions: normalProviders.toolExtensions, resolvePath: workerResolvePath,
3085
3167
  }) : undefined;
3086
3168
  // One effective selection feeds the task policy, child preflight, worker
3087
3169
  // bridge and frozen recipe, so a refused tool cannot leak into any of them
@@ -3102,11 +3184,11 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
3102
3184
  throw resume
3103
3185
  ? new ContinuationError(
3104
3186
  `Cannot continue ${resume.prior.id}: its frozen launch requires tool(s) this parent can no longer provide: ${detail}. ` +
3105
- `Launch a new run instead of continuing this conversation.`,
3187
+ `Launch a new run instead of continuing this conversation. ${processPolicy}`,
3106
3188
  )
3107
3189
  : new Error(
3108
3190
  `Requested tool(s) are not available in the task sandbox: ${detail}. ` +
3109
- `Remove them from the tools list, or make them available in /sandbox (Subagents · Tools); nothing was launched.`,
3191
+ `Check the child tool provider and the Subagents resource permissions; nothing was launched.`,
3110
3192
  );
3111
3193
  }
3112
3194
  if (toolSelection) {
@@ -3115,53 +3197,63 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
3115
3197
  }
3116
3198
  allow = toolSelection.tools.join(",");
3117
3199
  }
3200
+ // Older recipes were frozen before isolated workers gained Harness providers
3201
+ // and inherited workers began loading mappings explicitly.
3202
+ const legacyToolLoading = resume !== undefined && !resume.recipe.toolLoadingVersion;
3203
+ let extensionConfig = cfg;
3204
+ if (!sandboxEnabled && !legacyToolLoading) extensionConfig = normalProviders;
3205
+ if (legacyToolLoading && cfg.inheritExtensions) extensionConfig = { ...cfg, toolExtensions: {} };
3118
3206
  const dependencyOptions = {
3119
3207
  model, virtual: (() => {
3120
3208
  const slash = model?.indexOf("/") ?? -1;
3121
3209
  return slash > 0 && ctx.modelRegistry?.find?.(model!.slice(0, slash), model!.slice(slash + 1))?.api === "pi-virtual";
3122
- })(), config: cfg, resolvePath: resolveExtensionPath,
3123
- configPaths: [configPath(), join(selfDir(), "config.json")],
3210
+ })(), config: extensionConfig, resolvePath: workerResolvePath,
3211
+ configPaths: [configPath(), workerPath(join(selfDir(), "config.json"))],
3124
3212
  };
3125
3213
  // Bridge tools are supplied by the worker bridge extension, not by a
3126
3214
  // configured toolExtensions mapping: keep them out of extension
3127
3215
  // resolution so `unmapped` stays an accurate operator warning and the
3128
3216
  // frozen launch recipe never depends on bridge availability.
3129
- const extensionAllowlist = () => (bridgeEnabled
3130
- ? allow.split(",").filter((name) => !(bridgePlan.tools as readonly string[]).includes(name)).join(",")
3131
- : allow);
3217
+ const extensionAllowlist = () => allow.split(",")
3218
+ .filter(name => !requestedExcludes.has(name) && !bridgeToolNames.has(name)).join(",");
3132
3219
  const { resolution, fullResolution } = await resolveChildLaunch({ ...dependencyOptions, resolution: resolveExtensions({
3133
3220
  // Only SDK builtins reach `--tools` and extension resolution: process_list and run_application
3134
3221
  // are task builtins that the mandatory guard installs and activates itself.
3135
3222
  tools: sandboxEnabled ? allow.split(",").filter((name) => (SDK_BUILTIN_TOOLS as readonly string[]).includes(name)).join(",") : extensionAllowlist(),
3136
- model, clean, allowNested: sandboxEnabled ? false : allowNested, config: cfg,
3223
+ model, clean, allowNested: sandboxEnabled ? false : allowNested, config: extensionConfig,
3137
3224
  }) }, taskTools?.trusted.map(tool => tool.loadPath) ?? []);
3138
- const { args: resolvedExtArgs, missing } = extensionArgs(resolution, (spec) => resolution.paths[spec] ?? resolveExtensionPath(spec));
3225
+ if (!sandboxEnabled && resolution.mode === "isolated" &&
3226
+ fullResolution.specs.every((spec: string) => Object.values(ORDINARY_TOOL_PROVIDERS).includes(spec))) {
3227
+ const missingTools = resolution.unmapped.filter((name: string) => requiredToolNames.has(name));
3228
+ if (missingTools.length) throw new Error(`No provider for required child tools: ${missingTools.join(", ")}. Configure toolExtensions or change the requested tools.`);
3229
+ }
3230
+ const { args: resolvedExtArgs, missing } = extensionArgs(resolution, (spec) => resolution.paths[spec] ?? workerResolvePath(spec));
3139
3231
  const trustedExtArgs = fullResolution.specs.map(spec => fullResolution.paths[spec])
3140
3232
  .filter(path => !resolvedExtArgs.includes(path)).flatMap(path => ["--extension", path]);
3141
3233
  // Harness child controls ride along in every mode, including clean and unsandboxed runs.
3142
3234
  // They deliver deadline steers and keep external monitoring with the coordinator.
3143
3235
  const codemodeArgs = !sandboxEnabled && allow.split(",").includes("codemode") && !requestedExcludes.has("codemode")
3144
3236
  ? ["--extension", join(selfDir(), "child-codemode.ts")] : [];
3145
- const extArgs = [...resolvedExtArgs, ...trustedExtArgs, ...codemodeArgs,
3237
+ const extArgs = workerArgs([...resolvedExtArgs, ...trustedExtArgs, ...codemodeArgs,
3146
3238
  "--extension", childSteerExtensionPath(), "--extension", join(selfDir(), "child-ownership.ts")]
3147
- .map((value, index, all) => sandboxEnabled && all[index - 1] === "--extension" ? canonicalizePath(value) : value);
3148
- const baseExtensionArgs = [...resolvedExtArgs, ...codemodeArgs,
3239
+ .map((value, index, all) => sandboxEnabled && all[index - 1] === "--extension" ? canonicalizePath(value) : value));
3240
+ const baseExtensionArgs = workerArgs([...resolvedExtArgs, ...codemodeArgs,
3149
3241
  "--extension", childSteerExtensionPath(), "--extension", join(selfDir(), "child-ownership.ts")]
3150
- .map((value, index, all) => sandboxEnabled && all[index - 1] === "--extension" ? canonicalizePath(value) : value);
3242
+ .map((value, index, all) => sandboxEnabled && all[index - 1] === "--extension" ? canonicalizePath(value) : value));
3151
3243
  if (resume?.recipe.extensionArgs) {
3152
3244
  // A model escalation may change provider auth, but an unchanged tool
3153
3245
  // must not silently switch implementations with current configuration.
3154
3246
  const reference = model === resume.recipe.model ? resolution : await resolveChildClosure({
3155
3247
  ...dependencyOptions, model: resume.recipe.model, virtual: false, resolution: resolveExtensions({
3156
3248
  tools: sandboxEnabled ? allow.split(",").filter((name) => (SDK_BUILTIN_TOOLS as readonly string[]).includes(name)).join(",") : extensionAllowlist(),
3157
- model: resume.recipe.model, clean, allowNested: sandboxEnabled ? false : allowNested, config: cfg,
3249
+ model: resume.recipe.model, clean, allowNested: sandboxEnabled ? false : allowNested, config: extensionConfig,
3158
3250
  }) });
3159
- const referenceArgs = [...extensionArgs(reference, (spec) => reference.paths[spec] ?? resolveExtensionPath(spec)).args, ...codemodeArgs,
3251
+ const referenceArgs = [...extensionArgs(reference, (spec) => reference.paths[spec] ?? workerResolvePath(spec)).args, ...codemodeArgs,
3160
3252
  ...(!resume.recipe.baseExtensionArgs ? trustedExtArgs : []),
3161
3253
  "--extension", childSteerExtensionPath(), "--extension", join(selfDir(), "child-ownership.ts")]
3162
3254
  .map((value, index, all) => sandboxEnabled && all[index - 1] === "--extension" ? canonicalizePath(value) : value);
3163
3255
  assertContinuationExtensions(resume.prior.id, resume.recipe,
3164
- referenceArgs, taskTools?.trusted ?? []);
3256
+ workerArgs(referenceArgs), (taskTools?.trusted ?? []).map(tool => ({ ...tool, loadPath: workerPath(tool.loadPath) })));
3165
3257
  }
3166
3258
  if (sandboxEnabled && resolution.mode === "inherit") {
3167
3259
  throw new Error("Task confinement requires explicit extensions; inheritExtensions is unsupported while sandboxing is enabled.");
@@ -3190,7 +3282,7 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
3190
3282
  // supervision capability, not a tool implementation, so it must not
3191
3283
  // invalidate a conversation's saved recipe when it appears later.
3192
3284
  const commandExtArgs = bridgeEnabled
3193
- ? [...extArgs, "--extension", childBridgeExtensionPath(selfDir())]
3285
+ ? [...extArgs, "--extension", workerPath(childBridgeExtensionPath(selfDir()))]
3194
3286
  : extArgs;
3195
3287
  const args = [
3196
3288
  "-p", "--mode", "json",
@@ -3206,20 +3298,24 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
3206
3298
  ];
3207
3299
 
3208
3300
  const selectedTools = allow.split(",").filter((name) => name && !excludes.has(name));
3301
+ const inheritedTrusted = resume ? new Set(resume.recipe.optionalTrustedTools ?? []) : undefined;
3302
+ const optionalTrustedTools = taskTools?.trusted.filter(({ name }) => selectedTools.includes(name)
3303
+ && (inheritedTrusted ? inheritedTrusted.has(name) : requestedTools === undefined)).map(({ name }) => name) ?? [];
3209
3304
  const dropped = toolSelection?.dropped ?? [];
3210
3305
  const taskRuntime = sandboxEnabled && requestedSandboxDir ? prepareTaskRuntime({
3211
3306
  root: requestedSandboxDir, controlDir: join(runDir(id), "control"),
3212
3307
  tools: selectedTools,
3213
- permissions: permissionPlan.permissions && { ...permissionPlan.permissions, ...commandSettings },
3308
+ permissions: taskPermissions && { ...taskPermissions, ...commandSettings },
3214
3309
  applyPatch: taskTools?.applyPatch === true,
3215
- extensionTools: taskTools?.trusted.map(({ loadPath: _loadPath, ...tool }) => tool) ?? [],
3310
+ extensionTools: taskTools?.trusted.map(({ loadPath: _loadPath, ...tool }) => ({ ...tool, root: workerPath(tool.root) })) ?? [],
3216
3311
  // The sandboxed child's policy enables the guarded operation bridge
3217
3312
  // only when the fixed bridge adapter path is among its extension
3218
3313
  // paths; the task guard then admits those tools by exact source.
3219
3314
  extensionPaths: [
3220
3315
  ...extArgs.flatMap((arg, index) => arg === "--extension" && extArgs[index + 1] ? [extArgs[index + 1]!] : []),
3221
- ...(bridgeEnabled ? [childBridgeExtensionPath(selfDir())] : []),
3316
+ ...(bridgeEnabled ? [workerPath(childBridgeExtensionPath(selfDir()))] : []),
3222
3317
  ],
3318
+ operationBridgePath: workerPath(childBridgeExtensionPath(selfDir())),
3223
3319
  runtimeRoots: [baseDir()],
3224
3320
  capturedDenyWrite: internal?.resumeWait
3225
3321
  ? (resume?.prior.operations?.policy.sandbox as WorkerSandboxAuthority | null)?.denyWrite
@@ -3240,9 +3336,10 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
3240
3336
  try { ctx.ui?.notify?.(`Subagent ${id}: recovery snapshot failed (run continues): ${outcome.detail}`, "warning"); } catch { /* ignore */ }
3241
3337
  });
3242
3338
  }
3243
- const cmd = taskRuntime ? { file: taskRuntime.file, fileArgs: [...taskRuntime.fileArgs, ...args] }
3339
+ const currentCommand = taskRuntime ? { file: taskRuntime.file, fileArgs: [...taskRuntime.fileArgs, ...args] }
3244
3340
  : managed ? managed.workerCommand(args)
3245
3341
  : { file: process.execPath, fileArgs: [join(selfDir(), "child-runtime.mjs"), resolvePiBinary(), ...args] };
3342
+ const cmd = continuationRuntime?.command(currentCommand) ?? currentCommand;
3246
3343
  const sandboxDir = taskRuntime ? requestedSandboxDir : undefined;
3247
3344
 
3248
3345
  // Reservations prevent competing admissions, but do not grandfather
@@ -3267,6 +3364,7 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
3267
3364
  if (resume) revalidateContinuationUnderLease(resume, callbackOrigin);
3268
3365
  const preflightPath = join(runDir(id), "child-preflight.json");
3269
3366
  writeFileSync(preflightPath, JSON.stringify({ ...fullResolution, model, tools: selectedTools,
3367
+ optionalTrustedTools,
3270
3368
  configSnapshot: configSnapshot([dirname(configPath()), join(cwd, ".pi")]),
3271
3369
  }));
3272
3370
  // Register the worker's bridge run before the child can start, so the
@@ -3347,12 +3445,15 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
3347
3445
  }
3348
3446
  // Freeze the ordinary recipe before the durable external-launch intent.
3349
3447
  const recipe = buildLaunchRecipe({
3448
+ ...(!legacyToolLoading ? { toolLoadingVersion: 1 as const } : {}),
3350
3449
  attemptId: id, sessionId, sessionDir: childSessionDir, cwd, model, effort: thinking,
3351
3450
  tools: callerLaunchTools(allow), excludeTools: requestedExcludes.size ? [...requestedExcludes].join(",") : undefined,
3451
+ ...(optionalTrustedTools.length ? { optionalTrustedTools } : {}),
3352
3452
  skills: skills.mode === "inherit" ? undefined : [...skills.paths], clean, allowNested, approve,
3353
3453
  sandbox: sandboxEnabled, sandboxDir: requestedSandboxDir, gitCloneWorkspace, callback: callbackEnabled, name: launchName,
3354
3454
  agent: resume ? resume.recipe.agent : p.agent, role: resume ? resume.recipe.role : p.role,
3355
3455
  alias: resume ? resume.recipe.alias : p.alias, catalog: launchCatalog, extensionArgs: extArgs, baseExtensionArgs,
3456
+ runtimeRoot: continuationRuntime?.root ?? managedRuntimeRoot(selfDir()),
3356
3457
  trustedExtensions: resume?.recipe.trustedExtensions ?? taskTools?.trusted.map(({ name, package: owner, loadPath }) => ({ name, package: owner, loadPath })),
3357
3458
  });
3358
3459
  const startedAt = Date.now();
@@ -3437,14 +3538,15 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
3437
3538
  // Register exit supervision before any fallible post-spawn publication.
3438
3539
  // A failed metadata write must not strand a running child without a close
3439
3540
  // handler; the lease stays held until that child has actually exited.
3440
- void spawned.exit.then(async (code) => {
3441
- try { finalizeRun(pi, ctx, id, code); }
3442
- finally { lease?.release(); }
3541
+ const exitCompletion = completeOwnedExit(spawned.exit,
3542
+ code => finalizeRun(pi, ctx, id, code),
3543
+ () => { lease?.release(); }, async () => {
3443
3544
  if (workerBridge) workerOperations.release(id, "attempt-exited");
3444
3545
  // Reconcile this attempt's earlier published writer before its
3445
3546
  // next park can admit another continuation of the conversation.
3446
- await settleResumedAttemptExit({
3547
+ if (internal?.resumeWait && resume) await settleResumedAttemptExit({
3447
3548
  attemptId: id,
3549
+ priorPark: { runId: resume.prior.id, ...internal.resumeWait },
3448
3550
  service: workerOperations.service,
3449
3551
  status: readMeta(id)?.status ?? "exited",
3450
3552
  // The exit handler releases the conversation writer lease just
@@ -3456,6 +3558,7 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
3456
3558
  });
3457
3559
  await settleParkedExit(id);
3458
3560
  });
3561
+ managed?.observeExit?.(id, exitCompletion);
3459
3562
  writeMeta(meta);
3460
3563
  committed = true;
3461
3564
  // `meta.json` is now the record of this run; the claim has served its
@@ -3486,7 +3589,9 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
3486
3589
  const modelNote = catalogDefaultNote(resume ? undefined : p.catalog, model, thinking);
3487
3590
  // The resolved skill exposure rides with the runtime summary, which every
3488
3591
  // launch and continuation message already prints.
3489
- return { id, meta, spawned, runtime: `${runtime}${describeSkillExposure(skills)}\n${meta.timing ? `${formatTimingLimits(meta.timing, startedAt)}\n` : ""}`, warn, sandboxDir, modelNote };
3592
+ const inventoryNote = taskRuntime?.policy.permissions?.processAccess === "read" &&
3593
+ !taskRuntime.policy.tools.includes("process_list") ? " process_list is not in this launch's tool loadout." : "";
3594
+ return { id, meta, spawned, runtime: `${runtime}${processPolicy}${inventoryNote}\n${describeSkillExposure(skills)}\n${meta.timing ? `${formatTimingLimits(meta.timing, startedAt)}\n` : ""}`, warn, sandboxDir, modelNote };
3490
3595
  } catch (error) {
3491
3596
  // A launch that never committed metadata is not a run: drop
3492
3597
  // everything the attempt created so the registry keeps no
@@ -3497,6 +3602,7 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
3497
3602
  // must not keep running unsupervised; its log goes with the
3498
3603
  // attempt, because a record without metadata can never be read.
3499
3604
  if (!committed) {
3605
+ const { abortUncommittedLaunch } = await import("./launch-abort.ts");
3500
3606
  await abortUncommittedLaunch(id, {
3501
3607
  child: spawned, lease,
3502
3608
  artifacts: { sessionDir: childSessionDir, workspaceDir: ownedCloneWorkspace, scratch: launchScratch },
@@ -3568,7 +3674,7 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
3568
3674
  id: prior.id,
3569
3675
  prior,
3570
3676
  origin: { cwd: input.park.record.ownerWorkspace ?? prior.callbackOrigin?.cwd ?? prior.cwd, sessionId: input.park.record.ownerSessionId ?? prior.callbackOrigin?.sessionId },
3571
- others: listMetas(),
3677
+ others: listMetas({ includeArchived: false }),
3572
3678
  });
3573
3679
  } catch (error) {
3574
3680
  throw new PreSpawnResumeError(error instanceof Error ? error.message : String(error));
@@ -3619,7 +3725,7 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
3619
3725
  admissionRevision: input.admissionRevision,
3620
3726
  permissionsUnchanged: () => samePermissionPlan(
3621
3727
  permissionPlan,
3622
- resolveSubagentPermissions(pi, target.recipe.sandbox),
3728
+ resolveSubagentPermissions(pi, undefined, { runId: target.prior.id, sandbox: target.recipe.sandbox }),
3623
3729
  ),
3624
3730
  capacityAvailable: () => resumeCapacity().recheck(),
3625
3731
  }),
@@ -3656,7 +3762,10 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
3656
3762
  };
3657
3763
  return JSON.stringify(sort(value));
3658
3764
  };
3659
- return canonical(left) === canonical(right);
3765
+ // Describe provenance to the caller, but fence on authority, not its display label.
3766
+ const { activationSource: _leftSource, ...leftAuthority } = left;
3767
+ const { activationSource: _rightSource, ...rightAuthority } = right;
3768
+ return canonical(leftAuthority) === canonical(rightAuthority);
3660
3769
  }
3661
3770
 
3662
3771
  /** Preserve the original assignment deadline across parking; never extend it. */
@@ -4316,6 +4425,28 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
4316
4425
  pi.events?.emit("harness-settings:register", contribution);
4317
4426
  pi.events?.emit("harness-settings:register", agentsContribution);
4318
4427
  };
4428
+ const unsubscribeToolLoading = pi.events?.on?.("pi-better-subagents:default-tool-loading", (request: unknown) => {
4429
+ const query = request as { reply?: (rows: { name: string; provider: string }[]) => void } | undefined;
4430
+ if (typeof query?.reply !== "function") return;
4431
+ const config = ordinaryChildConfig(loadConfig(), activeChildProviders(pi));
4432
+ const names = normalizeTools(config.defaultTools ?? SAFE_DEFAULT_TOOLS).split(",").filter(Boolean);
4433
+ addEditablePatch(names, new Set());
4434
+ const rows = [...new Set(names)].map(name => {
4435
+ if (name === "codemode") {
4436
+ const supported = "createCodemodeExtension" in PiCodingAgent && typeof PiCodingAgent.createCodemodeExtension === "function";
4437
+ return { name, provider: supported ? "Harness" : "SDK unavailable" };
4438
+ }
4439
+ if (BUILTIN_TOOLS.includes(name)) return { name, provider: "Pi" };
4440
+ const spec = config.toolExtensions?.[name];
4441
+ const sources = typeof spec === "string" ? [spec] : spec ?? [];
4442
+ const providers = sources.map(source => {
4443
+ const label = source === ORDINARY_TOOL_PROVIDERS[name] ? "Harness" : source;
4444
+ return resolveExtensionPath(source) ? label : `${label} (missing)`;
4445
+ });
4446
+ return { name, provider: providers.join(", ") || (config.inheritExtensions ? "Session extensions" : "No provider mapped") };
4447
+ });
4448
+ query.reply(rows);
4449
+ });
4319
4450
  const unsubscribeSettingsRequest = pi.events?.on?.("harness-settings:request", registerSettings);
4320
4451
  const unsubscribeOutcomeWorkflow = pi.events?.on?.("pi-better-workflow:changed", () => recoverAssignmentOutcomes(pi));
4321
4452
  registerSettings();
@@ -4475,7 +4606,14 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
4475
4606
  // Capture a UI-bearing context and, if runs from a prior session are still
4476
4607
  // alive, resume the ticking widget. Deferred out of the factory per pi's
4477
4608
  // "no background resources at load" rule.
4478
- pi.on("session_start", async (_event, ctx) => {
4609
+ let restoreObservation: NodeJS.Immediate | undefined;
4610
+ let offFirstAssignment: (() => void) | undefined;
4611
+ const cancelDeferredObservation = () => {
4612
+ if (restoreObservation) clearImmediate(restoreObservation);
4613
+ offFirstAssignment?.();
4614
+ offFirstAssignment = undefined;
4615
+ };
4616
+ pi.on("session_start", async (event, ctx) => {
4479
4617
  // A session begins in this process again (reload, restart, or a session
4480
4618
  // switch), so the previous session's teardown no longer applies: the
4481
4619
  // replacing session owns this instance's supervision loops (#625).
@@ -4493,10 +4631,28 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
4493
4631
  activeCallbackOrigin = callbackOriginFromContext(ctx);
4494
4632
  pendingRecipientRecovery.clear();
4495
4633
  observedRecipientRows.clear();
4496
- if (!managed && activeCallbackOrigin) await startWorkObservation(PiCodingAgent.getAgentDir(), activeCallbackOrigin, () => {
4497
- refreshBackgroundWorkNavigator(ctx);
4498
- observeRecipientNotifications(pi);
4499
- });
4634
+ cancelDeferredObservation();
4635
+ if (!managed && activeCallbackOrigin) {
4636
+ configureWorkObservation(PiCodingAgent.getAgentDir(), activeCallbackOrigin, () => {
4637
+ refreshBackgroundWorkNavigator(ctx);
4638
+ observeRecipientNotifications(pi);
4639
+ });
4640
+ if (!event?.reason) {
4641
+ // Older hosts use completion of their untyped start callback as the readiness signal.
4642
+ await activateWorkObservation();
4643
+ } else if (shouldRestoreWorkObservation(event, ctx.sessionManager)) {
4644
+ restoreObservation = setImmediate(() => { void activateWorkObservation(); });
4645
+ } else {
4646
+ // Another extension can assign work to this recipient before it calls a tool.
4647
+ const origin = activeCallbackOrigin;
4648
+ offFirstAssignment = onMetaChanged(meta => {
4649
+ if (!meta || !belongsToOrigin(meta, origin)) return;
4650
+ offFirstAssignment?.();
4651
+ offFirstAssignment = undefined;
4652
+ void activateWorkObservation();
4653
+ });
4654
+ }
4655
+ }
4500
4656
  if (!managed) {
4501
4657
  recoverCompletionCallbacks(pi);
4502
4658
  observeRecipientNotifications(pi);
@@ -4546,6 +4702,7 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
4546
4702
  });
4547
4703
 
4548
4704
  pi.on("session_before_switch", () => {
4705
+ cancelDeferredObservation();
4549
4706
  closeCatalogHost();
4550
4707
  agentSessionSettings.clear();
4551
4708
  catalogModelRegistry = undefined;
@@ -4561,6 +4718,7 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
4561
4718
  // Tear down the timer and clear the widget when the session ends.
4562
4719
  pi.on("session_shutdown", async (event, ctx) => {
4563
4720
  closeCatalogHost();
4721
+ cancelDeferredObservation();
4564
4722
  stopWorkObservation();
4565
4723
  pendingNavigatorDismissals.clear();
4566
4724
  if (outcomeTicker) clearInterval(outcomeTicker);
@@ -4568,6 +4726,7 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
4568
4726
  outcomeAdmission.clear();
4569
4727
  closeOutcomeHost(outcomeHost);
4570
4728
  if (typeof unsubscribeOutcomeWorkflow === "function") unsubscribeOutcomeWorkflow();
4729
+ if (typeof unsubscribeToolLoading === "function") unsubscribeToolLoading();
4571
4730
  if (typeof unsubscribeSettingsRequest === "function") unsubscribeSettingsRequest();
4572
4731
  // #625: subagent children are detached process groups that outlive this
4573
4732
  // foreground session. A controlled reload or quit must not destroy