pi-better-subagents 0.26.2 → 0.27.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.
package/index.ts CHANGED
@@ -150,6 +150,7 @@ import {
150
150
  import {
151
151
  executeNavigatorClose,
152
152
  buildNavigatorRows,
153
+ pendingNavigatorPark,
153
154
  buildNavigatorDetail,
154
155
  } from "./navigator.ts";
155
156
  import { enforceRegistrySizeCapOnce, runDailyCleanupOnce } from "./cleanup.ts";
@@ -162,6 +163,7 @@ import {
162
163
  type ContinuationPlan,
163
164
  type ConversationLease,
164
165
  } from "./continuation.ts";
166
+ import { createHash } from "node:crypto";
165
167
  import { assertThinkingLevel, parseModelThinking, type ThinkingLevel } from "./thinking.ts";
166
168
  import { createAgentOperations } from "./agent-operations.ts";
167
169
  import { createAgentSessionSettings } from "./agent-session-settings.ts";
@@ -180,6 +182,33 @@ import {
180
182
  type CatalogRunRecord,
181
183
  } from "./catalog-runtime.ts";
182
184
  import { registerSubagentsGoalProvider } from "./goal-provider.ts";
185
+ import {
186
+ DEFAULT_WORKER_BRIDGE_TOOLS,
187
+ PreSpawnResumeError,
188
+ assertFinalResumeDispatch,
189
+ releaseChild,
190
+ cancelParkedWait,
191
+ captureWorkerPolicy,
192
+ createOwnedAttemptStopper,
193
+ childBridgeExtensionPath,
194
+ childWriterLeaseEnv,
195
+ createResumeOrchestration,
196
+ createWorkerOperationsHost,
197
+ finalizeWorkerParkAfterExit,
198
+ manualResumeRefusal,
199
+ ownerBindingFromContext,
200
+ parkedWaitForRun,
201
+ planWorkerBridgeTools,
202
+ reconcileParkedWaits,
203
+ resolveProductionSchemas,
204
+ resumePrompt,
205
+ settleResumedAttemptExit,
206
+ type ResumeCapacity,
207
+ type ResumeLaunchInput,
208
+ type WaitOwnerBinding,
209
+ type ResumeOrchestration,
210
+ type WorkerOperationsHost,
211
+ } from "./worker-waits.ts";
183
212
  import { defaultUserRoot, type CatalogSnapshot } from "./catalog-store.ts";
184
213
 
185
214
  const SUBAGENT_MODE_ACTIONS: readonly AutocompleteItem[] = [
@@ -1218,7 +1247,7 @@ function navigatorRows(visible?: RunMeta[], at?: number) {
1218
1247
 
1219
1248
  /** Runs that should advertise/open the left-arrow navigator affordance. */
1220
1249
  function navigatorRunningRuns(): RunMeta[] {
1221
- return sessionVisibleNavigatorRuns().filter((m) => effectiveStatus(m) === "running");
1250
+ return sessionVisibleNavigatorRuns().filter((m) => effectiveStatus(m) === "running" || pendingNavigatorPark(m));
1222
1251
  }
1223
1252
 
1224
1253
  function navigatorRunningCount(): number {
@@ -1239,6 +1268,7 @@ function sessionVisibleNavigatorRuns(now: number = Date.now()): RunMeta[] {
1239
1268
  }
1240
1269
 
1241
1270
  function isExpiredTerminalNavigatorRun(meta: RunMeta, now: number): boolean {
1271
+ if (pendingNavigatorPark(meta)) return false;
1242
1272
  const status = effectiveStatus(meta);
1243
1273
  if (!isTerminalNavigatorStatus(status)) return false;
1244
1274
  const endedAt = meta.endedAt ?? meta.lostAt;
@@ -1264,8 +1294,25 @@ function navigatorDetail(id: string, now: number = Date.now()) {
1264
1294
  });
1265
1295
  }
1266
1296
 
1297
+ /**
1298
+ * Set by the active extension instance: cancel a parked assignment's pending
1299
+ * wait. Returns false when the run is not parked, so the ordinary stop path runs.
1300
+ */
1301
+ let cancelParkedForUi: ((id: string, reason: string) => boolean) | undefined;
1302
+
1267
1303
  /** Shared #44 stop+dismiss path used by navigator Close (#47). */
1268
1304
  function navigatorCloseRun(id: string) {
1305
+ // A parked attempt's child already exited cleanly, so "close" must cancel the
1306
+ // pending automatic resume instead of pretending to stop a live process.
1307
+ if (cancelParkedForUi?.(id, "closed from the navigator; the automatic resume is cancelled")) {
1308
+ try { dismissRun(id); } catch { /* dismissal is best effort */ }
1309
+ spendCache.delete(id);
1310
+ healthLogCache.delete(id);
1311
+ resetChildEventLogCursor(id);
1312
+ resetParseRunCursor(id);
1313
+ syncHealthTicker();
1314
+ return { action: "stopped", id };
1315
+ }
1269
1316
  const outcome = executeNavigatorClose(id, {
1270
1317
  readMeta,
1271
1318
  effectiveStatus,
@@ -1291,6 +1338,7 @@ function statusTone(status: string): BackgroundWorkRow["statusTone"] {
1291
1338
  case "completed": return "success";
1292
1339
  case "failed":
1293
1340
  case "lost": return "failed";
1341
+ case "held":
1294
1342
  case "killed":
1295
1343
  case "orphaned": return "warning";
1296
1344
  default: return "muted";
@@ -1325,7 +1373,7 @@ function subagentWorkRows(now: number): BackgroundWorkRow[] {
1325
1373
  expiresAt: (() => {
1326
1374
  const meta = metaById.get(row.id);
1327
1375
  const endedAt = meta?.endedAt ?? meta?.lostAt;
1328
- return meta && isTerminalNavigatorStatus(effectiveStatus(meta)) && typeof endedAt === "number"
1376
+ return meta && !pendingNavigatorPark(meta) && isTerminalNavigatorStatus(effectiveStatus(meta)) && typeof endedAt === "number"
1329
1377
  ? endedAt + TERMINAL_NAVIGATOR_RETENTION_MS
1330
1378
  : undefined;
1331
1379
  })(),
@@ -1419,6 +1467,10 @@ function subagentWorkDetail(id: string, now: number, options?: { logTailLines?:
1419
1467
  { label: "elapsed", value: detail.elapsed },
1420
1468
  { label: "tools", value: detail.currentTool ? `current ${detail.currentTool}` : (detail.tools || "(none)") },
1421
1469
  { label: "spend", value: detail.spend || "(none)" },
1470
+ ...(detail.park ? [
1471
+ { label: "wait", value: `${detail.park.waitId} generation ${detail.park.generation}` },
1472
+ { label: "assignment", value: detail.park.heldReason || detail.park.continuationNote || "Waiting for the operation result; assignment unfinished" },
1473
+ ] : []),
1422
1474
  { label: "pid", value: detail.pid != null ? String(detail.pid) : "-" },
1423
1475
  { label: "pgid", value: detail.pgid != null ? String(detail.pgid) : "-" },
1424
1476
  ];
@@ -1433,7 +1485,7 @@ function subagentWorkDetail(id: string, now: number, options?: { logTailLines?:
1433
1485
  evidence: { label: "transcript", text: detail.output || "(no transcript yet)" },
1434
1486
  transcript: transcript.entries,
1435
1487
  transcriptDiagnostic: transcript.diagnostic,
1436
- footerActions: [detail.status === "running" || detail.status === "orphaned" ? "x stop" : "x dismiss"],
1488
+ footerActions: [detail.park ? "x cancel resume" : detail.status === "running" || detail.status === "orphaned" ? "x stop" : "x dismiss"],
1437
1489
  };
1438
1490
  }
1439
1491
 
@@ -1496,7 +1548,7 @@ function ensureSubagentProvider(): void {
1496
1548
  label: "Subagents",
1497
1549
  priority: 10,
1498
1550
  visibleCount: () => navigatorRunningCount(),
1499
- showSection: (rows) => rows.some((row) => row.status === "running"),
1551
+ showSection: (rows) => rows.some((row) => row.status === "running" || ["parking", "waiting", "ready", "resuming", "held"].includes(row.status)),
1500
1552
  parentRow: (now) => mainAgentWorkRow(now),
1501
1553
  listRows: (now) => subagentWorkRows(now),
1502
1554
  detail: (id, now, options) => subagentWorkDetail(id, now, options),
@@ -1510,7 +1562,7 @@ function ensureSubagentProvider(): void {
1510
1562
  saveDelegationDefault(readDelegation().mode);
1511
1563
  return true;
1512
1564
  },
1513
- armCloseLabel: (row) => row.status === "running" || row.status === "orphaned" ? "x again to stop" : "x again to dismiss",
1565
+ armCloseLabel: (row) => pendingNavigatorPark(readMeta(row.id)) ? "x again to cancel resume" : row.status === "running" || row.status === "orphaned" ? "x again to stop" : "x again to dismiss",
1514
1566
  close: (id) => {
1515
1567
  const outcome = navigatorCloseRun(id) as { action: string; id: string; status?: string };
1516
1568
  return { ...outcome, providerId: "subagents" };
@@ -1916,6 +1968,28 @@ export default function (pi: ExtensionAPI) {
1916
1968
  const activeDelegationMode = (): DelegationMode => delegationOverride ?? normalizeDelegationMode(loadConfig().delegationMode);
1917
1969
  const countRunning = () =>
1918
1970
  listActiveMetasForParent(process.pid).filter((meta) => effectiveStatus(meta) === "running").length;
1971
+ // Supervised worker operations: the Background observed-waits service owns
1972
+ // durable records, this extension owns the trusted transport its children
1973
+ // talk to. Both are absent in a standalone Subagents install, which is why
1974
+ // the bridge is optional and parking refuses instead of pretending.
1975
+ const workerOperations: WorkerOperationsHost = createWorkerOperationsHost({
1976
+ pi,
1977
+ childExtensionPath: childBridgeExtensionPath(selfDir()),
1978
+ });
1979
+ let resumeOrchestration: ResumeOrchestration | undefined;
1980
+ /**
1981
+ * Stop a continuation attempt only when this parent owns it and the token
1982
+ * published with it matches. A pid is never signalled on a guess.
1983
+ */
1984
+ const stopPublishedAttempt = createOwnedAttemptStopper();
1985
+ cancelParkedForUi = (id, reason) => {
1986
+ const parked = parkedWaitForRun(id);
1987
+ if (!parked) return false;
1988
+ void cancelParkedWait(workerOperations.service, parked, reason, { stopAttempt: stopPublishedAttempt })
1989
+ .catch(() => { /* the durable record keeps the wait visible */ })
1990
+ .finally(() => syncHealthTicker());
1991
+ return true;
1992
+ };
1919
1993
  const effectiveSettings = () => effectiveSubagentSettings({
1920
1994
  delegationMode: activeDelegationMode(), maxConcurrent: activeConcurrencyCap(),
1921
1995
  sources: { delegationMode: delegationOverride ? "session" : "config",
@@ -2092,6 +2166,37 @@ export default function (pi: ExtensionAPI) {
2092
2166
  p: SpawnParams,
2093
2167
  batchInfo?: { batchId: string; batchName?: string },
2094
2168
  resume?: ContinuationPlan,
2169
+ /**
2170
+ * Internal resume identity. Never a tool parameter: an auto-resume
2171
+ * publishes its attempt id and launch token in the coordinator before
2172
+ * this call, and a manual continuation passes neither.
2173
+ */
2174
+ internal?: {
2175
+ assignedRunId?: string;
2176
+ launchToken?: string;
2177
+ /** Present for an automatic resume: it may continue a conversation whose wait is still pending. */
2178
+ resumeWait?: { waitId: string; generation: number };
2179
+ /**
2180
+ * The owner binding captured when the worker parked. A resumed attempt
2181
+ * must register its operation bridge and record meta.operations under
2182
+ * THIS parent workspace/session/branch/Goal: a parent model turn appends
2183
+ * branch entries while the continuation is being admitted, and the wait's
2184
+ * exact-revision reads and acknowledgement are checked against the
2185
+ * captured owner, not the current one.
2186
+ */
2187
+ parkOwner?: WaitOwnerBinding;
2188
+ /**
2189
+ * Final dispatch fence: runs after every async preparation and
2190
+ * immediately before the child is released. Throwing proves no child
2191
+ * was started.
2192
+ */
2193
+ beforeSpawn?: (context: {
2194
+ runId: string;
2195
+ permissionPlan: ReturnType<typeof resolveSubagentPermissions>;
2196
+ }) => Promise<void | (() => void)> | void | (() => void);
2197
+ /** Called once a child process exists, so an ambiguous failure is never retried. */
2198
+ onSpawned?: () => void;
2199
+ },
2095
2200
  ): Promise<{
2096
2201
  id: string;
2097
2202
  meta: RunMeta;
@@ -2103,6 +2208,14 @@ export default function (pi: ExtensionAPI) {
2103
2208
  modelNote?: string;
2104
2209
  }> {
2105
2210
  assertThinkingLevel(p.thinking);
2211
+ // A conversation parked on an observed wait resumes through the
2212
+ // coordinator's claim. An ordinary manual continuation would leave that
2213
+ // automatic resume armed for the same assignment, so it is refused until
2214
+ // the human takes the parked attempt over (subagent_stop cancels the wait).
2215
+ if (resume && !internal?.resumeWait) {
2216
+ const parked = parkedWaitForRun(resume.prior.id);
2217
+ if (parked) throw new ContinuationError(manualResumeRefusal(parked));
2218
+ }
2106
2219
  // A continuation re-applies the CURRENT mandatory human permissions to its
2107
2220
  // frozen confinement intent. Historical metadata can never widen authority,
2108
2221
  // and a profile that would change confinement refuses instead of silently
@@ -2164,7 +2277,9 @@ export default function (pi: ExtensionAPI) {
2164
2277
  // .git/ inside the writable root for Git-mutating sandboxed subagents.
2165
2278
  const sandboxEnabled = permissionPlan.sandboxEnabled;
2166
2279
 
2167
- const id = nextRunId();
2280
+ // An auto-resume carries the attempt id the coordinator already published;
2281
+ // a fresh or manual launch allocates a new one.
2282
+ const id = internal?.assignedRunId ?? nextRunId();
2168
2283
  // Attempt identity (`id`) and conversation identity (`sessionId`) are
2169
2284
  // separate. A continuation keeps the native session; only the attempt is new.
2170
2285
  const sessionId = resume ? resume.conversation.sessionId : id;
@@ -2238,6 +2353,28 @@ export default function (pi: ExtensionAPI) {
2238
2353
  // A confined child gets extension tools only through /sandbox Subagents · Tools (ADR 0009):
2239
2354
  // the guarded apply_patch adapter, and trusted tools admitted by name and package.
2240
2355
  const requestedExcludes = new Set(requestedExcludeTools.split(",").map((t) => t.trim()).filter(Boolean));
2356
+
2357
+ // Supervised worker operations. This only decides which names the
2358
+ // child's loadout carries: clean children, explicit tool lists,
2359
+ // exclusions and task-sandboxed children keep their restrictions, and
2360
+ // the Background host still intersects the captured task authority
2361
+ // with the current profile before any task launches.
2362
+ // Production schemas come from the parent Background extension's own
2363
+ // tool registrations; a bridge tool without one is withheld instead of
2364
+ // being advertised with a permissive fallback schema.
2365
+ const productionBridgeSchemas = resolveProductionSchemas(pi, DEFAULT_WORKER_BRIDGE_TOOLS);
2366
+ const bridgePlan = planWorkerBridgeTools({
2367
+ allow: allow.split(",").filter(Boolean),
2368
+ excluded: [...requestedExcludes],
2369
+ clean,
2370
+ explicitTools: requestedTools !== undefined,
2371
+ productionSchemas: new Set(productionBridgeSchemas.schemas.keys()),
2372
+ });
2373
+ const bridgeEnabled = workerOperations.available && bridgePlan.tools.length > 0;
2374
+ if (bridgeEnabled) {
2375
+ allow = [...new Set([...allow.split(",").filter(Boolean), ...bridgePlan.tools])].join(",");
2376
+ }
2377
+
2241
2378
  if (sandboxEnabled && !clean) {
2242
2379
  const names = allow.split(",").filter(Boolean);
2243
2380
  // Models reach for apply_patch whenever they may edit; ticked trusted tools join the default set.
@@ -2258,8 +2395,9 @@ export default function (pi: ExtensionAPI) {
2258
2395
  shell: false, excluded: requestedExcludes,
2259
2396
  }).tools.join(",");
2260
2397
  }
2398
+ const bridgeToolNames = new Set<string>(bridgeEnabled ? bridgePlan.tools : []);
2261
2399
  const taskTools = sandboxEnabled ? planTaskTools({
2262
- requested: allow.split(",").filter((name) => name && !requestedExcludes.has(name)),
2400
+ requested: allow.split(",").filter((name) => name && !requestedExcludes.has(name) && !bridgeToolNames.has(name)),
2263
2401
  settings: permissionPlan.tools, network: permissionPlan.permissions?.network ?? true,
2264
2402
  processAccess: permissionPlan.permissions?.processAccess ?? "off",
2265
2403
  builtins: [...TASK_BUILTINS, "codemode"], registered: pi.getAllTools?.() ?? [],
@@ -2272,10 +2410,17 @@ export default function (pi: ExtensionAPI) {
2272
2410
  })(), config: cfg, resolvePath: resolveExtensionPath,
2273
2411
  configPaths: [configPath(), join(selfDir(), "config.json")],
2274
2412
  };
2413
+ // Bridge tools are supplied by the worker bridge extension, not by a
2414
+ // configured toolExtensions mapping: keep them out of extension
2415
+ // resolution so `unmapped` stays an accurate operator warning and the
2416
+ // frozen launch recipe never depends on bridge availability.
2417
+ const extensionAllowlist = () => (bridgeEnabled
2418
+ ? allow.split(",").filter((name) => !(bridgePlan.tools as readonly string[]).includes(name)).join(",")
2419
+ : allow);
2275
2420
  const { resolution, fullResolution } = await resolveChildLaunch({ ...dependencyOptions, resolution: resolveExtensions({
2276
2421
  // Only SDK builtins reach `--tools` and extension resolution: process_list and run_application
2277
2422
  // are task builtins that the mandatory guard installs and activates itself.
2278
- tools: sandboxEnabled ? allow.split(",").filter((name) => (SDK_BUILTIN_TOOLS as readonly string[]).includes(name)).join(",") : allow,
2423
+ tools: sandboxEnabled ? allow.split(",").filter((name) => (SDK_BUILTIN_TOOLS as readonly string[]).includes(name)).join(",") : extensionAllowlist(),
2279
2424
  model, clean, allowNested: sandboxEnabled ? false : allowNested, config: cfg,
2280
2425
  }) }, taskTools?.trusted.map(tool => tool.loadPath) ?? []);
2281
2426
  const { args: resolvedExtArgs, missing } = extensionArgs(resolution, (spec) => resolution.paths[spec] ?? resolveExtensionPath(spec));
@@ -2296,7 +2441,7 @@ export default function (pi: ExtensionAPI) {
2296
2441
  // must not silently switch implementations with current configuration.
2297
2442
  const reference = model === resume.recipe.model ? resolution : await resolveChildClosure({
2298
2443
  ...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,
2444
+ tools: sandboxEnabled ? allow.split(",").filter((name) => (SDK_BUILTIN_TOOLS as readonly string[]).includes(name)).join(",") : extensionAllowlist(),
2300
2445
  model: resume.recipe.model, clean, allowNested: sandboxEnabled ? false : allowNested, config: cfg,
2301
2446
  }) });
2302
2447
  const referenceArgs = [...extensionArgs(reference, (spec) => reference.paths[spec] ?? resolveExtensionPath(spec)).args, ...codemodeArgs,
@@ -2328,10 +2473,17 @@ export default function (pi: ExtensionAPI) {
2328
2473
  const sessionArgs = resume
2329
2474
  ? ["--session", resume.conversation.path, "--session-dir", childSessionDir]
2330
2475
  : ["--session-dir", childSessionDir, "--session-id", id];
2476
+ // The bridge extension is added to the command, not to the frozen
2477
+ // recipe: whether a supervising Background host is installed is a
2478
+ // supervision capability, not a tool implementation, so it must not
2479
+ // invalidate a conversation's saved recipe when it appears later.
2480
+ const commandExtArgs = bridgeEnabled
2481
+ ? [...extArgs, "--extension", childBridgeExtensionPath(selfDir())]
2482
+ : extArgs;
2331
2483
  const args = [
2332
2484
  "-p", "--mode", "json",
2333
2485
  ...sessionArgs,
2334
- ...extArgs,
2486
+ ...commandExtArgs,
2335
2487
  ...(model ? ["--model", model] : []),
2336
2488
  ...(thinking ? ["--thinking", thinking] : []),
2337
2489
  ...(allow && !sandboxEnabled ? ["--tools", allow] : []),
@@ -2353,7 +2505,13 @@ export default function (pi: ExtensionAPI) {
2353
2505
  permissions: permissionPlan.permissions && { ...permissionPlan.permissions, ...commandSettings },
2354
2506
  applyPatch: taskTools?.applyPatch === true,
2355
2507
  extensionTools: taskTools?.trusted.map(({ loadPath: _loadPath, ...tool }) => tool) ?? [],
2356
- extensionPaths: extArgs.flatMap((arg, index) => arg === "--extension" && extArgs[index + 1] ? [extArgs[index + 1]!] : []),
2508
+ // The sandboxed child's policy enables the guarded operation bridge
2509
+ // only when the fixed bridge adapter path is among its extension
2510
+ // paths; the task guard then admits those tools by exact source.
2511
+ extensionPaths: [
2512
+ ...extArgs.flatMap((arg, index) => arg === "--extension" && extArgs[index + 1] ? [extArgs[index + 1]!] : []),
2513
+ ...(bridgeEnabled ? [childBridgeExtensionPath(selfDir())] : []),
2514
+ ],
2357
2515
  runtimeRoots: [baseDir()],
2358
2516
  }) : undefined;
2359
2517
  launchScratch = taskRuntime?.policy.scratch;
@@ -2398,8 +2556,76 @@ export default function (pi: ExtensionAPI) {
2398
2556
  writeFileSync(preflightPath, JSON.stringify({ ...fullResolution, model, tools: selectedTools,
2399
2557
  configSnapshot: configSnapshot([dirname(configPath()), join(cwd, ".pi")]),
2400
2558
  }));
2401
- spawned = spawnDetached({ file: cmd.file, fileArgs: cmd.fileArgs, cwd, logPath: logPathFor(id),
2402
- env: { [STEER_FILE_ENV]: steerPathFor(id), [PREFLIGHT_ENV]: preflightPath } });
2559
+ // Register the worker's bridge run before the child can start, so the
2560
+ // child's first handshake finds a bound run and its task authority is
2561
+ // already captured. A resume requires the bridge: without it the
2562
+ // attempt could not read evidence or acknowledge its wait.
2563
+ let workerBridge: { env: Record<string, string>; policy: ReturnType<typeof captureWorkerPolicy>; authorityReference: string } | undefined;
2564
+ if (bridgeEnabled) {
2565
+ const workerPolicy = captureWorkerPolicy({
2566
+ sandbox: sandboxEnabled,
2567
+ tools: selectedTools,
2568
+ clean,
2569
+ workspace: cwd,
2570
+ authorityReference: "",
2571
+ // The assignment deadline the attempt was admitted with; a
2572
+ // continuation must not silently extend it.
2573
+ deadlineAt: resolveRunTiming({ params: p, settings: cfg, env: process.env, startedAt: Date.now() }).deadlineAt ?? null,
2574
+ taskPolicy: taskRuntime?.policy ?? null,
2575
+ });
2576
+ const authorityReference = `worker-policy:${createHash("sha256")
2577
+ .update(JSON.stringify(workerPolicy))
2578
+ .digest("hex")
2579
+ .slice(0, 16)}`;
2580
+ // A resumed attempt keeps the owner captured at park time; a fresh
2581
+ // launch uses the active foreground binding.
2582
+ const owner = internal?.parkOwner ?? ownerBindingFromContext(ctx);
2583
+ try {
2584
+ const handle = await workerOperations.register({
2585
+ runId: id,
2586
+ conversationId: sessionId,
2587
+ workspace: cwd,
2588
+ authorityReference,
2589
+ branchId: owner.branchId,
2590
+ goalId: owner.goalId,
2591
+ policy: { ...workerPolicy, authorityReference },
2592
+ capabilities: bridgePlan.capabilities,
2593
+ tools: bridgePlan.tools,
2594
+ schemas: bridgePlan.tools.map((name) => productionBridgeSchemas.schemas.get(name)!).filter(Boolean),
2595
+ attemptId: id,
2596
+ ...(lease?.token ? { writerLeaseId: lease.token } : {}),
2597
+ owner,
2598
+ });
2599
+ workerBridge = {
2600
+ env: { ...handle.env, ...childWriterLeaseEnv(lease?.token) },
2601
+ policy: workerPolicy,
2602
+ authorityReference,
2603
+ };
2604
+ } catch (error) {
2605
+ const reason = error instanceof Error ? error.message : String(error);
2606
+ // The child's loadout already promises the bridge (and a
2607
+ // sandboxed task policy would refuse to start without it), so a
2608
+ // registration failure refuses this launch instead of letting the
2609
+ // child run with tools that cannot work.
2610
+ if (internal?.resumeWait) {
2611
+ throw new PreSpawnResumeError(`Cannot resume this conversation without its operation bridge: ${reason}`);
2612
+ }
2613
+ throw new Error(`Cannot supervise this worker's background operations: ${reason}`);
2614
+ }
2615
+ }
2616
+ // Last gate before execution: the parent identity, Goal admission
2617
+ // revision, durable claim/token and current policy must all still hold.
2618
+ // The fence returns a synchronous release guard that is invoked with no
2619
+ // await between it and the spawn, so a cancellation or parent change
2620
+ // cannot hide inside a final asynchronous window.
2621
+ const dispatchGuard = await internal?.beforeSpawn?.({ runId: id, permissionPlan });
2622
+ spawned = releaseChild(dispatchGuard, () => spawnDetached({ file: cmd.file, fileArgs: cmd.fileArgs, cwd, logPath: logPathFor(id),
2623
+ env: {
2624
+ [STEER_FILE_ENV]: steerPathFor(id),
2625
+ [PREFLIGHT_ENV]: preflightPath,
2626
+ ...(workerBridge?.env ?? {}),
2627
+ } }));
2628
+ internal?.onSpawned?.();
2403
2629
  // Record process identity (pgid, start-time token) so health
2404
2630
  // reconciliation can tell a supervised child from a recycled pid
2405
2631
  // or an orphaned process group (#63). Best-effort: when the OS
@@ -2452,6 +2678,34 @@ export default function (pi: ExtensionAPI) {
2452
2678
  // The launch record is JSON. Registry freezes that value; it does not
2453
2679
  // require the resolver's nominal type to carry an index signature.
2454
2680
  ...(launchCatalog ? { catalog: launchCatalog as unknown as RunMeta["catalog"] } : {}),
2681
+ // Supervised-operation binding (references only; the per-run bridge
2682
+ // token stays in the child environment and is never persisted).
2683
+ ...(workerBridge ? {
2684
+ operations: {
2685
+ version: 1 as const,
2686
+ bridgeRunId: id,
2687
+ conversationId: sessionId,
2688
+ workspace: cwd,
2689
+ authorityReference: workerBridge.authorityReference,
2690
+ // Captured at park time for a resumed attempt; the worker
2691
+ // workspace above stays the actual task/sandbox root.
2692
+ ...(internal?.parkOwner
2693
+ ? { branchId: internal.parkOwner.branchId, goalId: internal.parkOwner.goalId }
2694
+ : {
2695
+ branchId: ownerBindingFromContext(ctx).branchId,
2696
+ goalId: ownerBindingFromContext(ctx).goalId,
2697
+ }),
2698
+ ...(internal?.launchToken ? { resumeLaunchToken: internal.launchToken } : {}),
2699
+ policy: {
2700
+ version: 1 as const,
2701
+ sandbox: workerBridge.policy.sandbox,
2702
+ tools: workerBridge.policy.tools,
2703
+ clean: workerBridge.policy.clean,
2704
+ deadlineAt: workerBridge.policy.deadlineAt,
2705
+ },
2706
+ tools: bridgePlan.tools,
2707
+ },
2708
+ } : {}),
2455
2709
  timing: resolveRunTiming({ params: p, settings: cfg, env: process.env, startedAt }),
2456
2710
  };
2457
2711
  // This instance holds the exit observer for a run it actually
@@ -2468,6 +2722,25 @@ export default function (pi: ExtensionAPI) {
2468
2722
  void spawned.exit.then((code) => {
2469
2723
  try { finalizeRun(pi, ctx, id, code); }
2470
2724
  finally { lease?.release(); }
2725
+ if (workerBridge) workerOperations.release(id, "attempt-exited");
2726
+ // After the writer lease is free: a clean park may already have a
2727
+ // ready dependency, and a failed park must hold its wait rather
2728
+ // than leave an automatic resume armed.
2729
+ void settleParkedExit(id);
2730
+ // If this attempt was a published resume of an earlier parked
2731
+ // assignment, an exit before acknowledgement must settle that
2732
+ // unconsumed generation explicitly instead of leaving it resuming.
2733
+ void settleResumedAttemptExit({
2734
+ attemptId: id,
2735
+ service: workerOperations.service,
2736
+ status: readMeta(id)?.status ?? "exited",
2737
+ // The exit handler releases the conversation writer lease just
2738
+ // above, before this call.
2739
+ writerLeaseReleased: true,
2740
+ notify: (message) => {
2741
+ try { uiCtx?.ui?.notify?.(message, "warning"); } catch { /* ignore UI failures */ }
2742
+ },
2743
+ });
2471
2744
  });
2472
2745
  writeMeta(meta);
2473
2746
  committed = true;
@@ -2516,6 +2789,235 @@ export default function (pi: ExtensionAPI) {
2516
2789
  }
2517
2790
  }
2518
2791
 
2792
+ /**
2793
+ * Finalize a parked attempt after its child exited.
2794
+ *
2795
+ * The bridge staged the verified checkpoint while the child was still alive;
2796
+ * this is where Background receives the three-fact exit proof
2797
+ * (checkpoint recorded, writer lease released, original writer gone) and the
2798
+ * durable wait leaves `parking`. A park that cannot be proven holds the
2799
+ * generation instead of leaving a resume armed for supervision that stopped.
2800
+ */
2801
+ async function settleParkedExit(id: string): Promise<void> {
2802
+ try {
2803
+ const result = await finalizeWorkerParkAfterExit({
2804
+ runId: id,
2805
+ service: workerOperations.service,
2806
+ // The exit handler calls this after `lease?.release()`.
2807
+ writerLeaseReleased: true,
2808
+ });
2809
+ if (result.outcome === "held" && result.reason) {
2810
+ try { uiCtx?.ui?.notify?.(`Subagent ${id} park held: ${result.reason}`, "warning"); } catch { /* ignore UI failures */ }
2811
+ } else if (result.outcome === "parked" && result.wait?.phase === "ready" && resumeOrchestration) {
2812
+ // The dependency settled while this attempt was exiting: the ready
2813
+ // delivery may already have been dispatched, but reconcile it here.
2814
+ const park = parkedWaitForRun(id);
2815
+ if (park) void resumeOrchestration.resume(park);
2816
+ }
2817
+ } catch {
2818
+ // The durable park record still shows the staged state; reconciliation
2819
+ // at the next session start retries the proof.
2820
+ } finally {
2821
+ syncHealthTicker();
2822
+ }
2823
+ }
2824
+
2825
+ /**
2826
+ * Launch one automatic continuation of a parked conversation.
2827
+ *
2828
+ * Everything below is the ordinary continuation admission path
2829
+ * (`planContinuation` → `spawnSubagentRun`), reused unchanged: native session,
2830
+ * frozen recipe, current mandatory permissions, capacity, writer lease. Only
2831
+ * the attempt id/token come from the durable park record written before this
2832
+ * call; every failure is classified as pre-spawn (releasable) or ambiguous
2833
+ * (must be held).
2834
+ */
2835
+ async function launchParkedResume(input: ResumeLaunchInput): Promise<void> {
2836
+ const ctx = uiCtx;
2837
+ if (!ctx || sessionTornDown) {
2838
+ throw new PreSpawnResumeError("No active foreground session can resume the parked assignment.");
2839
+ }
2840
+ const prior = readMeta(input.park.runId);
2841
+ if (!prior) throw new PreSpawnResumeError(`Cannot resume ${input.park.runId}: its run record is gone.`);
2842
+ const now = Date.now();
2843
+ if (prior.timing?.deadlineAt !== undefined && now >= prior.timing.deadlineAt) {
2844
+ throw new PreSpawnResumeError(
2845
+ `Cannot resume ${input.park.runId}: its assignment deadline passed while it was parked. The wait is held for the owner.`,
2846
+ );
2847
+ }
2848
+ let plan: ContinuationPlan;
2849
+ try {
2850
+ plan = planContinuation({
2851
+ id: prior.id,
2852
+ prior,
2853
+ origin: callbackOriginFromContext(ctx),
2854
+ others: listMetas(),
2855
+ });
2856
+ } catch (error) {
2857
+ throw new PreSpawnResumeError(error instanceof Error ? error.message : String(error));
2858
+ }
2859
+ const owner: WaitOwnerBinding = {
2860
+ sessionId: input.park.record.ownerSessionId ?? ownerBindingFromContext(ctx).sessionId,
2861
+ workspace: input.park.record.ownerWorkspace ?? ctx.cwd,
2862
+ branchId: input.park.record.ownerBranchId ?? ownerBindingFromContext(ctx).branchId,
2863
+ goalId: input.park.record.ownerGoalId ?? null,
2864
+ };
2865
+ const target = plan;
2866
+ let spawned = false;
2867
+ try {
2868
+ await spawnSubagentRun(
2869
+ ctx,
2870
+ {
2871
+ prompt: resumePrompt(input.park),
2872
+ session_id: plan.conversation.sessionId,
2873
+ callback: prior.callback ?? true,
2874
+ ...continuationTiming(prior),
2875
+ },
2876
+ undefined,
2877
+ plan,
2878
+ {
2879
+ assignedRunId: input.assignedRunId,
2880
+ launchToken: input.launchToken,
2881
+ // Marks this launch as an automatic resume: it may continue a
2882
+ // conversation whose wait is still pending, which a manual
2883
+ // continuation is refused until it takes over.
2884
+ resumeWait: { waitId: input.park.waitId, generation: input.park.generation },
2885
+ // The bridge registration and meta.operations must describe the
2886
+ // owner captured when the worker parked, not the foreground
2887
+ // branch as it stands after the parent's later model turn.
2888
+ parkOwner: owner,
2889
+ // Final dispatch fence: extension resolution, permission
2890
+ // re-resolution, the bridge registration and the writer lease
2891
+ // all happened above. Nothing may have changed since admission.
2892
+ beforeSpawn: ({ permissionPlan }) => assertFinalResumeDispatch({
2893
+ pi,
2894
+ rpc: workerOperations.rpc,
2895
+ // Getter, not a captured value: the foreground context can be
2896
+ // replaced during the asynchronous preparation.
2897
+ service: () => workerOperations.service,
2898
+ context: () => uiCtx,
2899
+ park: input.park,
2900
+ claim: input.claim,
2901
+ owner,
2902
+ admissionRevision: input.admissionRevision,
2903
+ permissionsUnchanged: () => samePermissionPlan(
2904
+ permissionPlan,
2905
+ resolveSubagentPermissions(pi, target.recipe.sandbox),
2906
+ ),
2907
+ capacityAvailable: () => resumeCapacity().recheck(),
2908
+ }),
2909
+ onSpawned: () => { spawned = true; },
2910
+ },
2911
+ );
2912
+ } catch (error) {
2913
+ // A child that exists is ambiguous: the coordinator holds the claim
2914
+ // and the next reconciliation must not launch a second execution.
2915
+ if (spawned) throw error;
2916
+ throw error instanceof PreSpawnResumeError
2917
+ ? error
2918
+ : new PreSpawnResumeError(error instanceof Error ? error.message : String(error));
2919
+ }
2920
+ }
2921
+
2922
+ /**
2923
+ * Compare two permission resolutions by value. A changed worker authority
2924
+ * during preparation (tightened or relaxed) invalidates the admission and
2925
+ * requires a fresh launch decision.
2926
+ */
2927
+ function samePermissionPlan(
2928
+ left: ReturnType<typeof resolveSubagentPermissions>,
2929
+ right: ReturnType<typeof resolveSubagentPermissions>,
2930
+ ): boolean {
2931
+ const canonical = (value: unknown): string => {
2932
+ const sort = (input: unknown): unknown => {
2933
+ if (Array.isArray(input)) return input.map(sort);
2934
+ if (input && typeof input === "object") {
2935
+ return Object.fromEntries(Object.keys(input as Record<string, unknown>).sort()
2936
+ .map((key) => [key, sort((input as Record<string, unknown>)[key])]));
2937
+ }
2938
+ return input;
2939
+ };
2940
+ return JSON.stringify(sort(value));
2941
+ };
2942
+ return canonical(left) === canonical(right);
2943
+ }
2944
+
2945
+ /** Preserve the original assignment deadline across parking; never extend it. */
2946
+ function continuationTiming(prior: RunMeta): TimingParams {
2947
+ const timing = prior.timing;
2948
+ if (!timing) return {};
2949
+ const minutes = (at: number | undefined): number | undefined => {
2950
+ if (at === undefined) return undefined;
2951
+ return Math.max(1, at - Date.now()) / 60_000;
2952
+ };
2953
+ return {
2954
+ ...(timing.deadlineAt !== undefined ? { deadline_minutes: minutes(timing.deadlineAt) } : {}),
2955
+ ...(timing.ceilingAt !== undefined ? { max_minutes: minutes(timing.ceilingAt) } : {}),
2956
+ ...(timing.graceMs !== undefined ? { grace_minutes: timing.graceMs / 60_000 } : {}),
2957
+ ...(timing.stuckMs !== undefined ? { stuck_minutes: timing.stuckMs / 60_000 } : {}),
2958
+ };
2959
+ }
2960
+
2961
+ /**
2962
+ * Capacity admission for an automatic resume. The ordinary shared gate is
2963
+ * reserved before any durable pre-spawn record, so a saturated pool leaves the
2964
+ * generation ready (delivery is retried) instead of publishing an
2965
+ * unresumable claim; the recheck covers a cap reduced in the meantime.
2966
+ */
2967
+ function resumeCapacity(): ResumeCapacity {
2968
+ const gate = () => getSharedCapacityGate(countRunning);
2969
+ return {
2970
+ tryReserve: () => gate().tryReserve(1, activeConcurrencyCap()),
2971
+ recheck: () => countRunning() + gate().pending <= activeConcurrencyCap(),
2972
+ commit: () => gate().commit(1),
2973
+ release: () => gate().release(1),
2974
+ };
2975
+ }
2976
+
2977
+ /** Create the resume orchestration lazily (needs an active foreground context). */
2978
+ function ensureResumeOrchestration(): ResumeOrchestration {
2979
+ resumeOrchestration ??= createResumeOrchestration({
2980
+ pi,
2981
+ service: () => workerOperations.service,
2982
+ rpc: workerOperations.rpc,
2983
+ context: () => uiCtx,
2984
+ capacity: resumeCapacity(),
2985
+ launch: launchParkedResume,
2986
+ stopAttempt: stopPublishedAttempt,
2987
+ notify: (message, level) => {
2988
+ try { uiCtx?.ui?.notify?.(message, level); } catch { /* ignore UI failures */ }
2989
+ },
2990
+ });
2991
+ return resumeOrchestration;
2992
+ }
2993
+
2994
+ /**
2995
+ * Start the supervised-worker path: the local bridge host plus reconciliation
2996
+ * of parked generations left by a previous session. Nothing here runs when the
2997
+ * Background service is absent.
2998
+ */
2999
+ async function startWorkerOperations(): Promise<void> {
3000
+ const ready = await workerOperations.start();
3001
+ if (!ready) return;
3002
+ const service = workerOperations.service;
3003
+ if (!service) return;
3004
+ const orchestration = ensureResumeOrchestration();
3005
+ try {
3006
+ // Register the continuation adapter first: Background refuses to
3007
+ // register a park wait without one, and ready deliveries are dispatched
3008
+ // to exactly this adapter.
3009
+ service.registerContinuationAdapter(orchestration.adapter);
3010
+ } catch { /* a host that refuses the adapter leaves parking unavailable */ }
3011
+ try {
3012
+ await reconcileParkedWaits(service, {
3013
+ resume: (park) => orchestration.resume(park),
3014
+ notify: (message) => {
3015
+ try { uiCtx?.ui?.notify?.(message, "warning"); } catch { /* ignore UI failures */ }
3016
+ },
3017
+ });
3018
+ } catch { /* reconciliation retries on the next session start */ }
3019
+ }
3020
+
2519
3021
  // ---- subagent_spawn -------------------------------------------------
2520
3022
  //
2521
3023
  // One tool launches both fresh work and a continuation of saved work. A
@@ -2972,7 +3474,30 @@ export default function (pi: ExtensionAPI) {
2972
3474
  enqueueCompletionCallback(pi, id);
2973
3475
  } });
2974
3476
  acceptanceStopToolRef = acceptanceStopTool;
2975
- pi.registerTool(acceptanceStopTool);
3477
+ // A parked assignment has no live child: `subagent_stop` is the explicit
3478
+ // takeover that cancels its pending automatic resume, so the conversation can
3479
+ // be continued manually. Without this, stop would report "not running" and
3480
+ // leave the automatic resume armed for the same assignment.
3481
+ const acceptanceStopToolWithParked = {
3482
+ ...acceptanceStopTool,
3483
+ async execute(toolCallId: string, params: unknown, signal?: AbortSignal, onUpdate?: unknown, ctx?: unknown) {
3484
+ const target = (params as { id?: unknown } | undefined)?.id;
3485
+ if (typeof target === "string" && cancelParkedForUi?.(target, "cancelled by subagent_stop; the automatic resume is cancelled")) {
3486
+ renderWidget();
3487
+ syncHealthTicker();
3488
+ return {
3489
+ content: [{
3490
+ type: "text",
3491
+ text: `Cancelled the pending wait of parked subagent ${target}. Its conversation can now be continued with subagent_spawn session_id.`,
3492
+ }],
3493
+ };
3494
+ }
3495
+ return (acceptanceStopTool.execute as (
3496
+ id: string, p: unknown, s?: AbortSignal, u?: unknown, c?: unknown,
3497
+ ) => Promise<unknown>)(toolCallId, params, signal, onUpdate, ctx) as Promise<never>;
3498
+ },
3499
+ };
3500
+ pi.registerTool(acceptanceStopToolWithParked as typeof acceptanceStopTool);
2976
3501
  publishAcceptanceHooks();
2977
3502
 
2978
3503
  const agentOperations = createAgentOperations({
@@ -3190,6 +3715,10 @@ export default function (pi: ExtensionAPI) {
3190
3715
  renderWidget();
3191
3716
  // Reattach one watcher after reload; ordinary completion retries belong to the batcher.
3192
3717
  syncHealthTicker();
3718
+ // Supervised worker operations (ADR 0020): the bridge host is bound to this
3719
+ // process, and parked generations from a previous session are reconciled
3720
+ // against the durable coordinator before anything resumes.
3721
+ void startWorkerOperations();
3193
3722
  });
3194
3723
 
3195
3724
  pi.on("session_before_switch", () => {
@@ -3219,6 +3748,12 @@ export default function (pi: ExtensionAPI) {
3219
3748
  // Late finalizers of surviving children must not restart supervision
3220
3749
  // loops in this replaced instance.
3221
3750
  sessionTornDown = true;
3751
+ // This instance's bridge host dies with the session: a surviving child
3752
+ // loses its transport (and therefore refuses to park) instead of talking
3753
+ // to a replaced session's handlers. Durable wait records are untouched.
3754
+ try { resumeOrchestration?.stop(); } catch { /* best effort */ }
3755
+ resumeOrchestration = undefined;
3756
+ void workerOperations.close().catch(() => {});
3222
3757
  // Children keep running; their finalizers (if this instance still holds
3223
3758
  // one) must not reach for a ctx that Pi invalidates once the session is
3224
3759
  // replaced.