pi-better-server 0.7.0 → 0.7.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (105) hide show
  1. package/package.json +1 -1
  2. package/src/codex/return.ts +3 -2
  3. package/src/detach/extension.ts +20 -3
  4. package/src/event-log.ts +40 -12
  5. package/src/hosted-session.ts +11 -5
  6. package/src/remote-client/packages.ts +1 -4
  7. package/src/runtime/background-tools.ts +2 -1
  8. package/src/runtime/domain/background/registry.mjs +3 -0
  9. package/src/runtime/domain/background/shared-operation-coordinator/src/task-lifetime.mjs +6 -0
  10. package/src/runtime/domain/background/terminal-publication.mjs +5 -2
  11. package/src/runtime/domain/background-service/managed-authority.domain.mjs +13 -0
  12. package/src/runtime/domain/background-service/managed-authority.ts +16 -0
  13. package/src/runtime/domain/background-service/managed-client.domain.mjs +2 -2
  14. package/src/runtime/domain/background-service/managed-client.ts +2 -2
  15. package/src/runtime/domain/background-service/observed-waits.domain.mjs +8 -4
  16. package/src/runtime/domain/background-service/observed-waits.ts +8 -4
  17. package/src/runtime/domain/background-service/registry.domain.mjs +3 -0
  18. package/src/runtime/domain/background-service/registry.ts +2 -0
  19. package/src/runtime/domain/background-service/runtime.domain.mjs +3 -2
  20. package/src/runtime/domain/background-service/runtime.ts +3 -2
  21. package/src/runtime/domain/background-service/shared-harness-settings.domain.mjs +2 -3
  22. package/src/runtime/domain/background-service/shared-harness-settings.ts +2 -5
  23. package/src/runtime/domain/background-service/shared-operation-coordinator/src/expiry.domain.mjs +44 -0
  24. package/src/runtime/domain/background-service/shared-operation-coordinator/src/expiry.ts +44 -0
  25. package/src/runtime/domain/background-service/shared-operation-coordinator/src/schema.domain.mjs +8 -1
  26. package/src/runtime/domain/background-service/shared-operation-coordinator/src/schema.ts +8 -1
  27. package/src/runtime/domain/background-service/shared-operation-coordinator/src/store.domain.mjs +3 -0
  28. package/src/runtime/domain/background-service/shared-operation-coordinator/src/store.ts +5 -0
  29. package/src/runtime/domain/background-service/shared-operation-coordinator/src/task-lifetime.domain.mjs +7 -0
  30. package/src/runtime/domain/background-service/shared-operation-coordinator/src/task-lifetime.ts +7 -0
  31. package/src/runtime/domain/background-service/shared-operation-coordinator/src/waits.domain.mjs +22 -13
  32. package/src/runtime/domain/background-service/shared-operation-coordinator/src/waits.ts +40 -32
  33. package/src/runtime/domain/background-service/shared-sandbox-diagnostics.domain.mjs +12 -19
  34. package/src/runtime/domain/background-service/shared-sandbox-diagnostics.ts +12 -16
  35. package/src/runtime/domain/background-service/shared-ssh-core/index.domain.mjs +1 -1
  36. package/src/runtime/domain/background-service/shared-ssh-core/index.ts +1 -1
  37. package/src/runtime/domain/background-service/supervisor/emit-runner.mjs +1 -0
  38. package/src/runtime/domain/background-service/supervisor/generated/runner.mjs +12 -7
  39. package/src/runtime/domain/background-service/supervisor/generated/task-lifetime.mjs +9 -0
  40. package/src/runtime/domain/background-service/supervisor/runner.domain.mjs +12 -7
  41. package/src/runtime/domain/background-service/supervisor/runner.ts +12 -7
  42. package/src/runtime/domain/background-service/supervisor/types.ts +1 -1
  43. package/src/runtime/domain/background-service/tools.domain.mjs +3 -2
  44. package/src/runtime/domain/background-service/tools.ts +3 -2
  45. package/src/runtime/domain/catalog/catalog-preferences.mjs +1 -3
  46. package/src/runtime/domain/coordinator/src/expiry.mjs +43 -0
  47. package/src/runtime/domain/coordinator/src/schema.mjs +8 -1
  48. package/src/runtime/domain/coordinator/src/store.mjs +3 -0
  49. package/src/runtime/domain/coordinator/src/task-lifetime.mjs +6 -0
  50. package/src/runtime/domain/coordinator/src/waits.mjs +22 -13
  51. package/src/runtime/domain/sandbox-policy/package.json +1 -1
  52. package/src/runtime/domain/sandbox-policy/shared-harness-settings.domain.mjs +2 -3
  53. package/src/runtime/domain/sandbox-policy/shared-harness-settings.ts +2 -5
  54. package/src/runtime/domain/sandbox-policy/shared-sandbox-diagnostics.domain.mjs +12 -19
  55. package/src/runtime/domain/sandbox-policy/shared-sandbox-diagnostics.ts +12 -16
  56. package/src/runtime/domain/shared-harness-settings.mjs +2 -3
  57. package/src/runtime/domain/subagents/README.md +2 -2
  58. package/src/runtime/domain/subagents/catalog-preferences.domain.mjs +1 -3
  59. package/src/runtime/domain/subagents/catalog-preferences.ts +1 -5
  60. package/src/runtime/domain/subagents/cleanup.domain.mjs +5 -2
  61. package/src/runtime/domain/subagents/cleanup.ts +4 -1
  62. package/src/runtime/domain/subagents/config.ts +1 -1
  63. package/src/runtime/domain/subagents/extensions.mjs +1 -0
  64. package/src/runtime/domain/subagents/finalization.domain.mjs +34 -30
  65. package/src/runtime/domain/subagents/finalization.ts +30 -28
  66. package/src/runtime/domain/subagents/git-workspace.domain.mjs +51 -6
  67. package/src/runtime/domain/subagents/git-workspace.ts +48 -6
  68. package/src/runtime/domain/subagents/index.domain.mjs +99 -54
  69. package/src/runtime/domain/subagents/index.ts +100 -51
  70. package/src/runtime/domain/subagents/isolated-workspace.domain.mjs +7 -14
  71. package/src/runtime/domain/subagents/isolated-workspace.ts +6 -12
  72. package/src/runtime/domain/subagents/managed-launch-host.domain.mjs +28 -2
  73. package/src/runtime/domain/subagents/managed-launch-host.ts +26 -2
  74. package/src/runtime/domain/subagents/managed-launch-port.ts +2 -0
  75. package/src/runtime/domain/subagents/package.json +1 -1
  76. package/src/runtime/domain/subagents/registry-cleanup-worker.mjs +24 -0
  77. package/src/runtime/domain/subagents/registry.domain.mjs +40 -14
  78. package/src/runtime/domain/subagents/registry.ts +26 -12
  79. package/src/runtime/domain/subagents/settings-page.domain.mjs +10 -10
  80. package/src/runtime/domain/subagents/settings-page.ts +10 -10
  81. package/src/runtime/domain/subagents/shared-harness-settings.domain.mjs +2 -3
  82. package/src/runtime/domain/subagents/shared-harness-settings.ts +2 -5
  83. package/src/runtime/domain/subagents/shared-operation-coordinator/src/expiry.domain.mjs +44 -0
  84. package/src/runtime/domain/subagents/shared-operation-coordinator/src/expiry.ts +44 -0
  85. package/src/runtime/domain/subagents/shared-operation-coordinator/src/schema.domain.mjs +8 -1
  86. package/src/runtime/domain/subagents/shared-operation-coordinator/src/schema.ts +8 -1
  87. package/src/runtime/domain/subagents/shared-operation-coordinator/src/store.domain.mjs +3 -0
  88. package/src/runtime/domain/subagents/shared-operation-coordinator/src/store.ts +5 -0
  89. package/src/runtime/domain/subagents/shared-operation-coordinator/src/task-lifetime.domain.mjs +7 -0
  90. package/src/runtime/domain/subagents/shared-operation-coordinator/src/task-lifetime.ts +7 -0
  91. package/src/runtime/domain/subagents/shared-operation-coordinator/src/waits.domain.mjs +22 -13
  92. package/src/runtime/domain/subagents/shared-operation-coordinator/src/waits.ts +40 -32
  93. package/src/runtime/domain/subagents/shared-sandbox-diagnostics.domain.mjs +12 -19
  94. package/src/runtime/domain/subagents/shared-sandbox-diagnostics.ts +12 -16
  95. package/src/runtime/domain/subagents/stop.domain.mjs +7 -5
  96. package/src/runtime/domain/subagents/stop.ts +7 -5
  97. package/src/runtime/domain/subagents/timing.domain.mjs +7 -3
  98. package/src/runtime/domain/subagents/timing.ts +11 -4
  99. package/src/runtime/domain/subagents/workspace-files.domain.mjs +6 -6
  100. package/src/runtime/domain/subagents/workspace-files.ts +6 -6
  101. package/src/runtime/domain/subagents/workspace-prepare-worker.mjs +12 -0
  102. package/src/runtime/task-expiry.ts +52 -0
  103. package/src/server.ts +4 -0
  104. package/src/shared-ssh-core/index.ts +1 -1
  105. package/src/version.ts +1 -1
@@ -1,3 +1,4 @@
1
+ import { taskDeadline } from "./shared-operation-coordinator/src/task-lifetime.ts";
1
2
  import { shouldRestoreWorkObservation } from "./shared-work-client.mjs";
2
3
  import { appendTimingWake, removeTimingReceipt, receiptTimingWake, timingWakeReceipt } from "./timing-notifications.ts";
3
4
  import { captureLaunchContext } from "./launch-context.ts";
@@ -21,6 +22,7 @@ import { currentSandboxPermissions } from "./permission-policy.ts";
21
22
  import { assertWaitToolDependencies, createToolDescriptor } from "./operation-bridge-types.ts";
22
23
  import { requestResumeAdmission } from "./worker-waits.ts";
23
24
  import { execSync } from "node:child_process";
25
+ import { Worker } from "node:worker_threads";
24
26
  import { writeFileSync, mkdirSync, renameSync, statSync } from "node:fs";
25
27
  import type { ExtensionAPI, ExtensionCommandContext, ExtensionContext } from "@earendil-works/pi-coding-agent";
26
28
  import * as PiCodingAgent from "@earendil-works/pi-coding-agent";
@@ -57,6 +59,7 @@ import { deliverSubagentPrompt, effectiveSubagentSettings, formatSubagentSetting
57
59
  import { STEER_FILE_ENV, readSteerReceipt } from "./child-steer.ts";
58
60
  import {
59
61
  continuationTimingParams,
62
+ configuredMaxMinutes,
60
63
  decideTiming,
61
64
  describeTiming,
62
65
  DEFAULT_TIMING_MINUTES,
@@ -83,7 +86,9 @@ import { DELEGATION_MODES, DELEGATION_MODE_REQUEST, isDelegationMode, normalizeD
83
86
  import { resolveExtensions, extensionArgs } from "./extensions.ts";
84
87
  import { prepareTaskRuntime, applyDirectApplicationLoadout, DEFAULT_TASK_PERMISSIONS, RUN_APPLICATION, SDK_BUILTIN_TOOLS } from "./task-policy.ts";
85
88
  import { worktreePolicyNotice } from "./worktree-feedback.ts";
86
- import { canonicalizePath, compileWritePolicy, takeRecoverySnapshot } from "./shared-sandbox-core.ts";
89
+ import type { IsolatedWorkspace } from "./isolated-workspace.ts";
90
+ import type { SubagentWorkspace, SubagentWorkspaceOptions } from "./git-workspace.ts";
91
+ import { canonicalizePath, compileWritePolicy, describeSandboxSupport, takeRecoverySnapshot } from "./shared-sandbox-core.ts";
87
92
  import { TASK_BUILTINS } from "./shared-task-sandbox.ts";
88
93
  import { describeTaskTools, planTaskTools, selectEffectiveTaskTools } from "./subagent-tools.ts";
89
94
  import {
@@ -537,25 +542,28 @@ function markCompletionCallbackSuppressed(id: string, reason: string, now: numbe
537
542
  // pending marker the replacing session recovers (#625), so leave it.
538
543
  if (sessionTornDown && reason === NO_ACTIVE_SESSION_REASON) return;
539
544
  const meta = readMeta(id);
540
- if (!meta || meta.completionCallbackSentAt !== undefined || meta.completionCallbackSuppressedAt !== undefined) return;
545
+ if (!meta) return;
541
546
  // An explicitly interrupted run owes its completion to the conversation that
542
547
  // launched it (#625, DEV-226 criterion 5). An unrelated session merely being
543
548
  // active — B opening before the original A returns — drops this delivery
544
549
  // attempt but must keep the obligation: the pending marker stays, and A
545
550
  // recovers it when it comes back. Records that never lost supervision keep
546
551
  // today's durable suppression, so legacy/foreign notifications stay dead.
547
- if ((meta.supervisionInterruptedAt !== undefined || meta.operations?.resumeLaunchToken)
548
- && isConversationIdentityReason(reason)) return;
549
- meta.completionCallbackSuppressedAt = now;
550
- meta.completionCallbackSuppressedReason = reason;
551
- writeMeta(meta);
552
+ writeMeta(meta, { patch: current => {
553
+ if (current.completionCallbackSentAt !== undefined || current.completionCallbackSuppressedAt !== undefined) return;
554
+ if ((current.supervisionInterruptedAt !== undefined || current.operations?.resumeLaunchToken)
555
+ && isConversationIdentityReason(reason)) return;
556
+ return { completionCallbackSuppressedAt: now, completionCallbackSuppressedReason: reason };
557
+ } });
552
558
  }
553
559
 
554
560
  function markCompletionCallbackSent(id: string, now: number): void {
555
561
  const meta = readMeta(id);
556
- if (!meta || meta.completionCallbackSentAt !== undefined || meta.completionCallbackSuppressedAt !== undefined) return;
557
- meta.completionCallbackSentAt = now;
558
- writeMeta(meta);
562
+ if (!meta) return;
563
+ writeMeta(meta, { patch: current =>
564
+ current.completionCallbackSentAt === undefined && current.completionCallbackSuppressedAt === undefined
565
+ ? { completionCallbackSentAt: now } : undefined,
566
+ });
559
567
  }
560
568
 
561
569
  /** Queue one durable ordinary terminal event on the host-shared batch. */
@@ -1217,10 +1225,12 @@ function stopForTiming(pi: ExtensionAPI | undefined, id: string, reason: TimingS
1217
1225
  return outcome.action === "finalized";
1218
1226
  }
1219
1227
  const current = readMeta(id);
1220
- if (current && current.callback !== false && current.completionCallbackPendingAt === undefined
1221
- && current.completionCallbackSentAt === undefined && current.completionCallbackSuppressedAt === undefined) {
1222
- current.completionCallbackPendingAt = now;
1223
- writeMeta(current);
1228
+ if (current) {
1229
+ writeMeta(current, { patch: latest =>
1230
+ latest.callback !== false && latest.completionCallbackPendingAt === undefined
1231
+ && latest.completionCallbackSentAt === undefined && latest.completionCallbackSuppressedAt === undefined
1232
+ ? { completionCallbackPendingAt: now } : undefined,
1233
+ });
1224
1234
  }
1225
1235
  progressCache.delete(id);
1226
1236
  if (current && !callbackSuppressionReason(current)) {
@@ -1238,7 +1248,11 @@ function stopForTiming(pi: ExtensionAPI | undefined, id: string, reason: TimingS
1238
1248
  */
1239
1249
  function enforceTiming(pi: ExtensionAPI | undefined, meta: RunMeta, now: number): boolean {
1240
1250
  const timing = meta.timing;
1241
- if (!timing || timing.stopReason) return false;
1251
+ if (!timing) return false;
1252
+ if ((meta.status === "running" || meta.status === "orphaned") && now >= (timing.lifetimeAt ?? taskDeadline(meta.startedAt))) {
1253
+ return stopForTiming(pi, meta.id, "ceiling", now);
1254
+ }
1255
+ if (timing.stopReason) return false;
1242
1256
  // The ceiling also bounds an orphaned run (child gone, its process group still alive).
1243
1257
  if (meta.status === "orphaned") {
1244
1258
  return timing.ceilingAt !== undefined && now >= timing.ceilingAt ? stopForTiming(pi, meta.id, "ceiling", now) : false;
@@ -1703,10 +1717,7 @@ function navigatorCloseRun(id: string) {
1703
1717
  });
1704
1718
  if (outcome.action === "dismissed" || outcome.action === "stopped-and-dismissed") pendingNavigatorDismissals.add(id);
1705
1719
  // A closed row is off the hot path: release its caches and retained events.
1706
- spendCache.delete(id);
1707
- healthLogCache.delete(id);
1708
- resetChildEventLogCursor(id);
1709
- resetParseRunCursor(id);
1720
+ forgetRunCaches(id);
1710
1721
  syncHealthTicker();
1711
1722
  // Close stops (or log-finalizes) the run, which is a terminal transition:
1712
1723
  // queue its one completion callback so no terminal state is silent (#624).
@@ -2063,6 +2074,27 @@ function resolvePiBinary(): string {
2063
2074
  return cachedPi;
2064
2075
  }
2065
2076
 
2077
+ function forgetRunCaches(id: string): void {
2078
+ spendCache.delete(id);
2079
+ healthLogCache.delete(id);
2080
+ resetChildEventLogCursor(id);
2081
+ resetParseRunCursor(id);
2082
+ }
2083
+
2084
+ function prepareLaunchWorkspace(options: SubagentWorkspaceOptions, isolated?: IsolatedWorkspace): Promise<SubagentWorkspace> {
2085
+ const built = import.meta.url.endsWith(".domain.mjs");
2086
+ const entry = new URL("./workspace-prepare-worker.mjs", import.meta.url);
2087
+ return new Promise((resolve, reject) => {
2088
+ const worker = new Worker(entry, {
2089
+ workerData: { options, isolated },
2090
+ execArgv: built ? [] : ["--import", import.meta.resolve("tsx")],
2091
+ });
2092
+ worker.once("message", resolve);
2093
+ worker.once("error", reject);
2094
+ worker.once("exit", code => reject(new Error(`Git workspace preparation exited before reporting a result (code ${code}).`)));
2095
+ });
2096
+ }
2097
+
2066
2098
  /**
2067
2099
  * Finalize a run once its child exits. Host-facing wrapper around the
2068
2100
  * first-party finalizer (finalization.ts) so tests can exercise the durable
@@ -2514,13 +2546,13 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
2514
2546
  const defaults = resolveRunTiming({ settings: cfg, env: process.env, startedAt: 0 });
2515
2547
  const minutes = (ms: number | undefined): number => ms === undefined ? 0 : ms / 60_000;
2516
2548
  return {
2517
- maxMinutes: minutes(effective.ceilingAt),
2549
+ maxMinutes: configuredMaxMinutes(sessionTimeout, timingSettingsFor(cfg), process.env),
2518
2550
  toolWaitMinutes: minutes(effective.toolWaitMs),
2519
2551
  stuckMinutes: minutes(effective.stuckMs),
2520
2552
  timeoutSource: timeoutSource(),
2521
2553
  toolWaitSource: sourceFor("toolWaitMinutes"),
2522
2554
  stuckSource: sourceFor("stuckMinutes"),
2523
- defaultMaxMinutes: minutes(defaults.ceilingAt),
2555
+ defaultMaxMinutes: configuredMaxMinutes({}, cfg, process.env),
2524
2556
  defaultToolWaitMinutes: minutes(defaults.toolWaitMs),
2525
2557
  defaultStuckMinutes: minutes(defaults.stuckMs),
2526
2558
  };
@@ -2933,8 +2965,8 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
2933
2965
  modelNote?: string;
2934
2966
  }> {
2935
2967
  const { resolveChildClosure, resolveChildLaunch, configSnapshot } = await import("./child-dependencies.mjs");
2936
- const { resolveSubagentWorkspace, inspectGitWorkspace } = await import("./git-workspace.ts");
2937
- const { workspaceChoice, createIsolatedWorkspace, restoreWorkspace, discardWorkspace, markWorkspaceWriter } = await import("./isolated-workspace.ts");
2968
+ const { resolveSubagentWorkspace, linkedWorktreeGitDir } = await import("./git-workspace.ts");
2969
+ const { workspaceChoice, restoreWorkspace, discardWorkspace, markWorkspaceWriter } = await import("./isolated-workspace.ts");
2938
2970
  const { PREFLIGHT_ENV } = await import("./child-preflight.mjs");
2939
2971
  assertThinkingLevel(p.thinking);
2940
2972
  // Skill exposure is a caller choice, not a launch: validate its shape
@@ -2956,6 +2988,16 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
2956
2988
  // moving a live conversation into a different sandbox.
2957
2989
  const permissionPlan = resolveSubagentPermissions(pi, p.sandbox,
2958
2990
  resume && { runId: resume.prior.id, sandbox: resume.recipe.sandbox });
2991
+ if (permissionPlan.sandboxEnabled) {
2992
+ const support = describeSandboxSupport();
2993
+ if (!support.supported) {
2994
+ const remedy = permissionPlan.permissions
2995
+ ? "Turn off the Subagents sandbox in /sandbox settings to run without confinement."
2996
+ : resume ? "Launch a new subagent with sandbox:false to run without confinement."
2997
+ : "Pass sandbox:false to run without confinement.";
2998
+ throw new Error(`Task sandbox unavailable: ${support.reason} ${remedy}`);
2999
+ }
3000
+ }
2959
3001
  const processPolicy = describeSubagentProcessPolicy(permissionPlan, process.platform);
2960
3002
  const processAccess = effectiveWorkerProcessAccess(permissionPlan);
2961
3003
  const taskPermissions = permissionPlan.inactiveProfile
@@ -2989,19 +3031,15 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
2989
3031
  model = parsed.model;
2990
3032
  thinking = parsed.thinking;
2991
3033
  }
2992
- // Best-effort daily hygiene for durable tmp state. The marker makes
2993
- // this effectively free after the first subagent launch each day.
2994
- // Resume has already validated this history. Retiring it here would let
2995
- // native --session create an empty replacement before the child runs.
2996
- if (!resume) runDailyCleanupOnce({ config: cfg });
2997
- // Age retires history; this bounds the peak one busy day can reach.
2998
- // Rate-limited inside cleanup.ts, and never on the UI hot path.
2999
- const capped = resume ? { removed: [] } : enforceRegistrySizeCapOnce({ config: cfg });
3000
- for (const id of capped.removed) {
3001
- spendCache.delete(id);
3002
- healthLogCache.delete(id);
3003
- resetChildEventLogCursor(id);
3004
- resetParseRunCursor(id);
3034
+ // Continuations revalidate and lease their saved history. Only fresh launches request maintenance.
3035
+ if (!resume) {
3036
+ if (managed) {
3037
+ const { cleanupTerminalRunRetentionMs, cleanupSessionRetentionMs, maxRegistryBytes } = cfg;
3038
+ managed.scheduleRegistryCleanup({ cleanupTerminalRunRetentionMs, cleanupSessionRetentionMs, maxRegistryBytes }, forgetRunCaches);
3039
+ } else {
3040
+ runDailyCleanupOnce({ config: cfg });
3041
+ for (const removed of enforceRegistrySizeCapOnce({ config: cfg }).removed) forgetRunCaches(removed);
3042
+ }
3005
3043
  }
3006
3044
  const callbackOrigin = internal?.parkOwner
3007
3045
  ? { cwd: internal.parkOwner.workspace, sessionId: internal.parkOwner.sessionId }
@@ -3089,14 +3127,15 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
3089
3127
  mkdirSync(root, { mode: 0o700 });
3090
3128
  createdWorkspace = true;
3091
3129
  }
3092
- const isolatedCwd = isolated && !resume && !p.git_clone_workspace ? createIsolatedWorkspace(isolated, true) : undefined;
3130
+ const workspaceOptions = {
3131
+ ctxCwd: ctx.cwd, cwd: p.cwd, sandboxDir: p.sandbox_dir ?? ownedCloneWorkspace,
3132
+ gitCloneWorkspace: p.git_clone_workspace, runId: id, runDirPath: runDir(id), sandboxEnabled,
3133
+ };
3093
3134
  const workspace = resume
3094
3135
  ? { cwd: resume.recipe.cwd, requestedSandboxDir: resume.recipe.sandboxDir }
3095
- : isolatedCwd ? { cwd: isolatedCwd, requestedSandboxDir: sandboxEnabled ? isolatedCwd : undefined }
3096
- : resolveSubagentWorkspace({
3097
- ctxCwd: ctx.cwd, cwd: p.cwd, sandboxDir: p.sandbox_dir ?? ownedCloneWorkspace,
3098
- gitCloneWorkspace: p.git_clone_workspace, runId: id, runDirPath: runDir(id), sandboxEnabled,
3099
- });
3136
+ : isolated || p.git_clone_workspace
3137
+ ? await prepareLaunchWorkspace(workspaceOptions, p.git_clone_workspace ? undefined : isolated)
3138
+ : resolveSubagentWorkspace(workspaceOptions);
3100
3139
  // Legacy explicit clones launch at the repository root, even when the source is a subdirectory.
3101
3140
  if (!resume && isolated && p.git_clone_workspace) isolated = { ...isolated, subdir: "" };
3102
3141
  let workspaceNote = isolated ? `Git workspace: ${isolated.mode} at ${workspace.cwd}. Base ${isolated.base}.`
@@ -3381,8 +3420,9 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
3381
3420
  const optionalTrustedTools = taskTools?.trusted.filter(({ name }) => selectedTools.includes(name)
3382
3421
  && (inheritedTrusted ? inheritedTrusted.has(name) : requestedTools === undefined)).map(({ name }) => name) ?? [];
3383
3422
  const dropped = toolSelection?.dropped ?? [];
3423
+ const sharedGitDir = sandboxEnabled && isolated?.mode !== "clone" ? linkedWorktreeGitDir(cwd) : undefined;
3384
3424
  const taskRuntime = sandboxEnabled && requestedSandboxDir ? prepareTaskRuntime({
3385
- worktreeGitDir: isolated?.mode === "worktree" ? inspectGitWorkspace(cwd).gitDir : undefined,
3425
+ worktreeGitDir: isolated?.mode === "worktree" ? sharedGitDir : undefined,
3386
3426
  root: requestedSandboxDir, controlDir: join(runDir(id), "control"),
3387
3427
  tools: selectedTools,
3388
3428
  permissions: taskPermissions && { ...taskPermissions, ...commandSettings },
@@ -3401,14 +3441,15 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
3401
3441
  ? (resume?.prior.operations?.policy.sandbox as WorkerSandboxAuthority | null)?.denyWrite
3402
3442
  : handoffAuthority?.sandbox?.denyWrite,
3403
3443
  }) : undefined;
3404
- if (taskRuntime?.policy.worktreeGitDir) {
3444
+ if (taskRuntime && sharedGitDir) {
3405
3445
  const policy = taskRuntime.policy;
3406
- const notice = worktreePolicyNotice(policy.worktreeGitDir!, compileWritePolicy({
3446
+ const notice = worktreePolicyNotice(sharedGitDir, compileWritePolicy({
3407
3447
  writableRoot: policy.root, home: policy.home, permissions: policy.permissions,
3408
3448
  denyWrite: policy.denyWrite, runtimeCompatibility: true, runtimeWrite: [policy.scratch],
3409
3449
  }));
3410
3450
  if (notice) {
3411
- workspaceNote += " " + notice;
3451
+ workspaceNote = isolated?.mode === "worktree" ? `${workspaceNote} ${notice}`
3452
+ : `Git workspace: existing linked worktree at ${cwd}. ${notice} Use git_clone_workspace:true for a new worker that needs to commit, or return the changes for the parent to commit.`;
3412
3453
  args[args.length - 1] = workspaceNote + "\n\n" + p.prompt;
3413
3454
  writeFileSync(promptPathFor(id), args[args.length - 1]!);
3414
3455
  }
@@ -3541,6 +3582,11 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
3541
3582
  trustedExtensions: resume?.recipe.trustedExtensions ?? taskTools?.trusted.map(({ name, package: owner, loadPath }) => ({ name, package: owner, loadPath })),
3542
3583
  });
3543
3584
  const startedAt = Date.now();
3585
+ const timing = resolveRunTiming({ params: launchTimingParams(p), settings: timingSettingsFor(cfg), env: process.env, startedAt });
3586
+ if (internal?.resumeWait && resume) {
3587
+ timing.lifetimeAt = resume.prior.timing?.lifetimeAt ?? taskDeadline(resume.prior.startedAt);
3588
+ timing.ceilingAt = Math.min(timing.lifetimeAt, resume.prior.timing?.ceilingAt ?? Infinity, timing.ceilingAt!);
3589
+ }
3544
3590
  const meta: RunMeta = {
3545
3591
  assignment,
3546
3592
  outcomeSupport: { version: 1, available: Boolean(assignment), ...(!assignment ? { reason: "Legacy host has no verified parent session/transcript; durable assignment delivery is unavailable." } : {}) },
@@ -3590,9 +3636,12 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
3590
3636
  tools: bridgePlan.tools,
3591
3637
  },
3592
3638
  } : {}),
3593
- timing: resolveRunTiming({ params: launchTimingParams(p), settings: timingSettingsFor(cfg), env: process.env, startedAt }),
3639
+ timing,
3594
3640
  };
3595
3641
  const dispatchGuard = await internal?.beforeSpawn?.({ runId: id, permissionPlan });
3642
+ if (internal?.resumeWait && Date.now() >= timing.ceilingAt!) {
3643
+ throw new PreSpawnResumeError("The parked task reached its execution time limit before dispatch.");
3644
+ }
3596
3645
  if (isolated) markWorkspaceWriter(isolated,id);
3597
3646
  const managedEnv = managed?.beforeSpawn({ id, sessionId, lease: lease!.token, leasePath: lease!.path,
3598
3647
  preflightPath, policyPath: taskRuntime?.policyPath, permissions: permissionPlan, recipe, recoveryMeta: meta });
@@ -3749,7 +3798,7 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
3749
3798
  const prior = readMeta(input.park.runId);
3750
3799
  if (!prior) throw new PreSpawnResumeError(`Cannot resume ${input.park.runId}: its run record is gone.`);
3751
3800
  const now = Date.now();
3752
- if (prior.timing?.deadlineAt !== undefined && now >= prior.timing.deadlineAt) {
3801
+ if (now >= taskDeadline(prior.startedAt, prior.timing?.ceilingAt) || (prior.timing?.deadlineAt !== undefined && now >= prior.timing.deadlineAt)) {
3753
3802
  throw new PreSpawnResumeError(
3754
3803
  `Cannot resume ${input.park.runId}: its assignment deadline passed while it was parked. The wait is held for the owner.`,
3755
3804
  );
@@ -3963,7 +4012,7 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
3963
4012
  "The tools param is both the tool allowlist AND what determines which extensions load in the child (e.g. tools='read,bash,web_fetch' loads only the web-tools package). Ask for the tools the task needs and nothing more; clean:true gives a built-ins-only child. When the task already names its SKILL.md by path, pass skills with those absolute paths (or [] for none) so the child does not advertise the whole skills catalog. Without an agent or role, pick a model with the model param (e.g. 'xai/grok-4.5@high'); providerless model patterns are resolved by Pi, while provider/model is deterministic and loads mapped provider extensions.",
3964
4013
  ...CATALOG_GUIDELINES,
3965
4014
  "Subagent sandboxing defaults to off. Human settings in /sandbox control file, credential-file, command, and network permissions; sandbox:false cannot override an enabled human profile. Set sandbox:true to request kernel confinement, including without published settings. Set callback:false to finish quietly — then read the result on demand via subagent_result.",
3966
- "Every launch automatically joins one shared harness-owned watcher, including batch launches; it stops when the last active run ends. Do not start a separate heartbeat or background watcher for subagents. A tool call still open for tool_wait_minutes (default 5) or no progress for stuck_minutes (default 10) sends one factual alert; these alerts never stop, cancel, or restart the run. Hard timeouts default to 60 minutes; max_minutes overrides that default (0 disables). Soft deadlines remain opt-in for work with a real wall-clock bound: deadline_minutes steers the child to wrap up and later stops it after grace_minutes, while max_minutes stops it without grace. Do not set elapsed-time limits merely because a task may take a while; use them only when the work needs a real wall-clock bound.",
4015
+ "Every launch automatically joins one shared harness-owned watcher, including batch launches; it stops when the last active run ends. Do not start a separate heartbeat or background watcher for subagents. A tool call still open for tool_wait_minutes (default 5) or no progress for stuck_minutes (default 10) sends one factual alert; these alerts never stop, cancel, or restart the run. Hard timeouts default to 60 minutes; max_minutes overrides that default up to 24 hours (0 selects the maximum). Soft deadlines remain opt-in for work with a real wall-clock bound: deadline_minutes steers the child to wrap up and later stops it after grace_minutes, while max_minutes stops it without grace. Do not set elapsed-time limits merely because a task may take a while; use them only when the work needs a real wall-clock bound.",
3967
4016
  "Git writers receive separate checkouts by default. /subagents settings selects Clone or Worktree. isolation:false selects the live checkout. A sandboxed Worktree can return its files or explicitly continue in a verified Clone with recover_in_clone:true.",
3968
4017
  "Saved conversations persist automatically. To continue a completed or stopped worker in its own history, call subagent_spawn with session_id (the native session id reported for the saved conversation) and the new feedback as prompt. Omit session_id for a brand-new conversation.",
3969
4018
  "On a continuation, pass prompt, session_id, and only optional model, thinking, callback, or timing overrides. Launch-only options (name, agent, role, alias, tools, exclude_tools, skills, clean, sandbox, sandbox_dir, cwd, git_clone_workspace, approve, allow_nested) keep the saved recipe; repeat them only with the same value, otherwise the launch is refused.",
@@ -4517,7 +4566,7 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
4517
4566
  : skills.mode === "none" ? "no skills" : `${skills.paths.length} selected skills`;
4518
4567
  const timing = timingState();
4519
4568
  ctx.ui.notify(`Delegation mode: ${activeDelegationMode()}. Concurrent subagents: ${activeConcurrencyCap()}. ` +
4520
- `Run timeout: ${timing.maxMinutes ? timing.maxMinutes + " minutes" : "No limit"}. Tool-wait alert: ${timing.toolWaitMinutes} min. ` +
4569
+ `Run timeout: ${timing.maxMinutes ? timing.maxMinutes + " minutes" : "24 hours"}. Tool-wait alert: ${timing.toolWaitMinutes} min. ` +
4521
4570
  `No-progress alert: ${timing.stuckMinutes} min. Skills: ${skillChoice}. ` +
4522
4571
  `Use /subagents mode <mode>, cap <number>, tool-wait <minutes>, stuck <minutes>, or settings; /subagents save persists them.`, "info");
4523
4572
  }
@@ -4603,7 +4652,7 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
4603
4652
  const timing = timingState();
4604
4653
  if (ctx.hasUI && !(await ctx.ui.confirm("Save subagent defaults?",
4605
4654
  `Future sessions will start in ${activeDelegationMode()} with a cap of ${activeConcurrencyCap()}, ` +
4606
- `run timeout ${timing.maxMinutes ? timing.maxMinutes + " minutes" : "No limit"}, tool-wait alert ${timing.toolWaitMinutes} min, ` +
4655
+ `run timeout ${timing.maxMinutes ? timing.maxMinutes + " minutes" : "24 hours"}, tool-wait alert ${timing.toolWaitMinutes} min, ` +
4607
4656
  `no-progress alert ${timing.stuckMinutes} min, and ${skillChoice}.`))) {
4608
4657
  ctx.ui.notify("Subagent defaults unchanged.", "info");
4609
4658
  return;
@@ -3,7 +3,7 @@ import { randomUUID } from "node:crypto";
3
3
  import { execFileSync } from "node:child_process";
4
4
  import { closeSync, existsSync, lstatSync, mkdirSync, mkdtempSync, openSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, writeFileSync, } from "node:fs";
5
5
  import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
6
- import { inspectGitWorkspace, syncGitRemotes } from "./git-workspace.domain.mjs";
6
+ import { inspectGitWorkspace, isIgnoredGitSubdirectory, syncGitRemotes } from "./git-workspace.domain.mjs";
7
7
  import { restoreTree, snapshotTree, verifyTree } from "./workspace-files.domain.mjs";
8
8
  import { durableSubagentRoot } from "./session-store.domain.mjs";
9
9
  import { taskWorkspaceDir } from "./registry.domain.mjs";
@@ -63,18 +63,8 @@ export function workspaceChoice(source, owner, mode, tools, exclude) {
63
63
  throw error;
64
64
  }
65
65
  const subdir = relative(info.repoRoot, realpathSync(source));
66
- // A directory ignored by its enclosing checkout (e.g. a separate project in
67
- // build output) is not part of that checkout's selected Git base.
68
- if (subdir) {
69
- try {
70
- git(info.repoRoot, ["check-ignore", "--quiet", "--", subdir]);
71
- return;
72
- }
73
- catch (error) {
74
- if (error.status !== 1)
75
- throw error;
76
- }
77
- }
66
+ if (isIgnoredGitSubdirectory(info.repoRoot, subdir))
67
+ return;
78
68
  let base;
79
69
  try {
80
70
  base = value(source, ["rev-parse", "--verify", "HEAD"]);
@@ -152,7 +142,6 @@ const withoutGit = new Set([".git"]);
152
142
  const worktreePointers = new Set(["commondir", "gitdir"]);
153
143
  const sharedGitEntries = new Set(["config", "objects", "packed-refs", "refs", "logs", "info", "shallow", "hooks"]);
154
144
  const pendingOperation = [
155
- "index.lock",
156
145
  "rebase-merge",
157
146
  "rebase-apply",
158
147
  "MERGE_HEAD",
@@ -306,6 +295,10 @@ function checkpoint(w, attempt) {
306
295
  const { root, record, store } = paths(w);
307
296
  const info = inspectOwned(w);
308
297
  const linked = w.mode === "worktree";
298
+ const indexLock = join(info.gitDir, "index.lock");
299
+ if (existsSync(indexLock)) {
300
+ throw new Error(`Git index lock blocks workspace recovery at ${indexLock}. Original checkout retained at ${root}.`);
301
+ }
309
302
  if (pendingOperation.some((name) => existsSync(join(info.gitDir, name))) ||
310
303
  existsSync(join(info.commonGitDir, "objects/info/alternates")) ||
311
304
  (existsSync(join(info.commonGitDir, "worktrees")) && !linked)) {
@@ -15,7 +15,7 @@ import {
15
15
  writeFileSync,
16
16
  } from "node:fs";
17
17
  import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
18
- import { inspectGitWorkspace, syncGitRemotes } from "./git-workspace.ts";
18
+ import { inspectGitWorkspace, isIgnoredGitSubdirectory, syncGitRemotes } from "./git-workspace.ts";
19
19
  import { restoreTree, snapshotTree, verifyTree, type SavedEntry } from "./workspace-files.ts";
20
20
  import { durableSubagentRoot } from "./session-store.ts";
21
21
  import { taskWorkspaceDir } from "./registry.ts";
@@ -93,16 +93,7 @@ export function workspaceChoice(
93
93
  throw error;
94
94
  }
95
95
  const subdir = relative(info.repoRoot, realpathSync(source));
96
- // A directory ignored by its enclosing checkout (e.g. a separate project in
97
- // build output) is not part of that checkout's selected Git base.
98
- if (subdir) {
99
- try {
100
- git(info.repoRoot, ["check-ignore", "--quiet", "--", subdir]);
101
- return;
102
- } catch (error) {
103
- if ((error as { status?: number }).status !== 1) throw error;
104
- }
105
- }
96
+ if (isIgnoredGitSubdirectory(info.repoRoot, subdir)) return;
106
97
  let base: string;
107
98
  try {
108
99
  base = value(source, ["rev-parse", "--verify", "HEAD"]);
@@ -188,7 +179,6 @@ const withoutGit = new Set([".git"]);
188
179
  const worktreePointers = new Set(["commondir", "gitdir"]);
189
180
  const sharedGitEntries = new Set(["config", "objects", "packed-refs", "refs", "logs", "info", "shallow", "hooks"]);
190
181
  const pendingOperation = [
191
- "index.lock",
192
182
  "rebase-merge",
193
183
  "rebase-apply",
194
184
  "MERGE_HEAD",
@@ -355,6 +345,10 @@ function checkpoint(w: IsolatedWorkspace, attempt: string) {
355
345
  const { root, record, store } = paths(w);
356
346
  const info = inspectOwned(w);
357
347
  const linked = w.mode === "worktree";
348
+ const indexLock = join(info.gitDir, "index.lock");
349
+ if (existsSync(indexLock)) {
350
+ throw new Error(`Git index lock blocks workspace recovery at ${indexLock}. Original checkout retained at ${root}.`);
351
+ }
358
352
  if (
359
353
  pendingOperation.some((name) => existsSync(join(info.gitDir, name))) ||
360
354
  existsSync(join(info.commonGitDir, "objects/info/alternates")) ||
@@ -10,7 +10,7 @@ import extension from "./index.domain.mjs";
10
10
  import { bindRuntimeOutcomeStore } from "./assignment-outcomes.domain.mjs";
11
11
  import { catalogSnapshotFromWire } from "./catalog-store.domain.mjs";
12
12
  import { openLaunchJournal, launchDigest } from "./managed-launch-journal.mjs";
13
- import { baseDir, nextRunId, processStartToken, listMetas, writeMeta, listActiveMetasForParent, effectiveStatus, readMeta, readParkRecord, updateParkRecord } from "./registry.domain.mjs";
13
+ import { baseDir, nextRunId, processStartToken, listMetas, notifyRunRemoved, writeMeta, listActiveMetasForParent, effectiveStatus, readMeta, readParkRecord, updateParkRecord } from "./registry.domain.mjs";
14
14
  import { recoverLaunchMetadata } from "./managed-launch-recovery.domain.mjs";
15
15
  import { assertSubagentHandoff } from "./managed-launch-ownership.domain.mjs";
16
16
  import { createOwnerCapacityGates } from "./capacity.mjs";
@@ -42,6 +42,7 @@ export class ManagedSubagentHost {
42
42
  closeJournal;
43
43
  epoch;
44
44
  pending = 0;
45
+ registryCleanup;
45
46
  requestSequence = 0;
46
47
  requestRecords = new Map();
47
48
  foldRecord;
@@ -196,7 +197,8 @@ export class ManagedSubagentHost {
196
197
  }
197
198
  capacityFor = createOwnerCapacityGates(({ pid, start }) => listActiveMetasForParent(pid).filter(meta => meta.spawnPidStartTime === start && effectiveStatus(meta) === "running").length
198
199
  + this.journal.unresolvedAttempts().filter((attempt) => attempt.capacityOwner?.pid === pid && attempt.capacityOwner?.start === start && !readMeta(attempt.id)).length);
199
- get busy() { return this.pending > 0 || Boolean(this.failureResponse); }
200
+ get cleaningRegistry() { return this.registryCleanup !== undefined; }
201
+ get busy() { return this.pending > 0 || Boolean(this.failureResponse) || this.cleaningRegistry; }
200
202
  status() {
201
203
  return { owner: "server", instanceId: this.instance, runtimeEpoch: this.epoch,
202
204
  lifecycle: { ...this.lifecycleMetrics, activeDeadlines: this.healthDue.size },
@@ -339,10 +341,33 @@ export class ManagedSubagentHost {
339
341
  process.kill(record.pid, 0);
340
342
  return record;
341
343
  }
344
+ scheduleRegistryCleanup = (config, onRemoved) => {
345
+ if (this.registryCleanup)
346
+ return;
347
+ this.registryCleanup = new Promise((resolve, reject) => {
348
+ const worker = new Worker(new URL("./registry-cleanup-worker.mjs", import.meta.url), {
349
+ workerData: { root: this.root, config },
350
+ execArgv: import.meta.url.endsWith(".domain.mjs") ? [] : ["--import", import.meta.resolve("tsx")],
351
+ });
352
+ worker.on("message", (id) => {
353
+ notifyRunRemoved(id);
354
+ onRemoved(id);
355
+ });
356
+ worker.once("error", reject);
357
+ worker.once("exit", code => {
358
+ if (code === 0)
359
+ resolve();
360
+ else
361
+ reject(new Error(`Registry cleanup worker exited with code ${code}`));
362
+ });
363
+ }).catch(error => console.error("[pi-better-subagents] Registry cleanup failed:", error))
364
+ .finally(() => { this.registryCleanup = undefined; });
365
+ };
342
366
  initialize() {
343
367
  return this.initializing ??= (async () => {
344
368
  const host = this;
345
369
  const port = {
370
+ scheduleRegistryCleanup: this.scheduleRegistryCleanup,
346
371
  observeHealth: reconcile => host.observeHealth(reconcile),
347
372
  activeProviders: () => host.current.activeProviders ?? {},
348
373
  backgroundTools: () => host.current.background?.available === true ? host.current.background.tools : [],
@@ -598,6 +623,7 @@ export class ManagedSubagentHost {
598
623
  this.healthClose?.();
599
624
  Atomics.store(this.foldRevocation, 0, 1);
600
625
  await this.tail.catch(() => undefined);
626
+ await this.registryCleanup;
601
627
  await this.failureWorker?.terminate();
602
628
  this.failureWorker = undefined;
603
629
  if (failureFoldRevocations.get(this.root) === this.foldRevocation)
@@ -9,7 +9,7 @@ import extension from "./index.ts";
9
9
  import { bindRuntimeOutcomeStore } from "./assignment-outcomes.ts";
10
10
  import { catalogSnapshotFromWire } from "./catalog-store.ts";
11
11
  import { openLaunchJournal, launchDigest } from "./managed-launch-journal.mjs";
12
- import { baseDir, nextRunId, processStartToken, listMetas, writeMeta, listActiveMetasForParent, effectiveStatus, readMeta, readParkRecord, updateParkRecord } from "./registry.ts";
12
+ import { baseDir, nextRunId, processStartToken, listMetas, notifyRunRemoved, writeMeta, listActiveMetasForParent, effectiveStatus, readMeta, readParkRecord, updateParkRecord } from "./registry.ts";
13
13
  import { recoverLaunchMetadata } from "./managed-launch-recovery.ts";
14
14
  import { assertSubagentHandoff } from "./managed-launch-ownership.ts";
15
15
  import { createOwnerCapacityGates } from "./capacity.mjs";
@@ -37,6 +37,7 @@ export class ManagedSubagentHost {
37
37
  private closeJournal: () => void;
38
38
  private epoch: number;
39
39
  private pending = 0;
40
+ private registryCleanup?: Promise<void>;
40
41
  private requestSequence = 0;
41
42
  private requestRecords = new Map<number, any>();
42
43
  private foldRecord?: { kind: string; ids: readonly string[]; lastProgressAt: number; nextDeadline: number; recovery: string };
@@ -151,7 +152,8 @@ export class ManagedSubagentHost {
151
152
  private capacityFor = createOwnerCapacityGates(({ pid, start }: { pid: number; start: string }) =>
152
153
  listActiveMetasForParent(pid).filter(meta => meta.spawnPidStartTime === start && effectiveStatus(meta) === "running").length
153
154
  + this.journal.unresolvedAttempts().filter((attempt: any) => attempt.capacityOwner?.pid === pid && attempt.capacityOwner?.start === start && !readMeta(attempt.id)).length);
154
- get busy() { return this.pending > 0 || Boolean(this.failureResponse); }
155
+ get cleaningRegistry() { return this.registryCleanup !== undefined; }
156
+ get busy() { return this.pending > 0 || Boolean(this.failureResponse) || this.cleaningRegistry; }
155
157
  status() {
156
158
  return { owner: "server", instanceId: this.instance, runtimeEpoch: this.epoch,
157
159
  lifecycle: { ...this.lifecycleMetrics, activeDeadlines: this.healthDue.size },
@@ -260,10 +262,31 @@ export class ManagedSubagentHost {
260
262
  process.kill(record.pid, 0);
261
263
  return record;
262
264
  }
265
+ private scheduleRegistryCleanup: ManagedLaunchPort["scheduleRegistryCleanup"] = (config, onRemoved) => {
266
+ if (this.registryCleanup) return;
267
+ this.registryCleanup = new Promise<void>((resolve, reject) => {
268
+ const worker = new Worker(new URL("./registry-cleanup-worker.mjs", import.meta.url), {
269
+ workerData: { root: this.root, config },
270
+ execArgv: import.meta.url.endsWith(".domain.mjs") ? [] : ["--import", import.meta.resolve("tsx")],
271
+ });
272
+ worker.on("message", (id: string) => {
273
+ notifyRunRemoved(id);
274
+ onRemoved(id);
275
+ });
276
+ worker.once("error", reject);
277
+ worker.once("exit", code => {
278
+ if (code === 0) resolve();
279
+ else reject(new Error(`Registry cleanup worker exited with code ${code}`));
280
+ });
281
+ }).catch(error => console.error("[pi-better-subagents] Registry cleanup failed:", error))
282
+ .finally(() => { this.registryCleanup = undefined; });
283
+ };
284
+
263
285
  private initialize() {
264
286
  return this.initializing ??= (async () => {
265
287
  const host = this;
266
288
  const port: ManagedLaunchPort = {
289
+ scheduleRegistryCleanup: this.scheduleRegistryCleanup,
267
290
  observeHealth: reconcile => host.observeHealth(reconcile),
268
291
  activeProviders: () => host.current.activeProviders ?? {},
269
292
  backgroundTools: () => host.current.background?.available === true ? host.current.background.tools : [],
@@ -487,6 +510,7 @@ export class ManagedSubagentHost {
487
510
  this.healthClose?.();
488
511
  Atomics.store(this.foldRevocation, 0, 1);
489
512
  await this.tail.catch(() => undefined);
513
+ await this.registryCleanup;
490
514
  await this.failureWorker?.terminate(); this.failureWorker = undefined;
491
515
  if (failureFoldRevocations.get(this.root) === this.foldRevocation) failureFoldRevocations.delete(this.root);
492
516
  const session = this.session;
@@ -1,3 +1,4 @@
1
+ import type { SubagentConfig } from "./config.ts";
1
2
  import type { CatalogHost } from "./catalog-runtime.ts";
2
3
  import type { CatalogSnapshot } from "./catalog-store.ts";
3
4
  import type { RunMeta } from "./registry.ts";
@@ -6,6 +7,7 @@ import type { RunMeta } from "./registry.ts";
6
7
  export interface ManagedLaunchPort {
7
8
  observeHealth?(reconcile: (ids: readonly string[]) => void): () => void;
8
9
  activeProviders?(): Record<string, string>;
10
+ scheduleRegistryCleanup(config: Pick<SubagentConfig, "cleanupTerminalRunRetentionMs" | "cleanupSessionRetentionMs" | "maxRegistryBytes">, onRemoved: (id: string) => void): void;
9
11
  backgroundTools(): readonly string[];
10
12
  readonly owner: { pid: number; start?: string };
11
13
  readonly identity: { root: string; instance: string; epoch: number };
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-better-subagents",
3
- "version": "0.37.0",
3
+ "version": "0.37.2",
4
4
  "description": "Pi extension for detached, sandboxed subagent runs that keep the foreground session free.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -0,0 +1,24 @@
1
+ // Generated fixed launch domain from packages/pi-better-subagents/registry-cleanup-worker.mjs. Do not edit directly.
2
+ import { join } from "node:path";
3
+ import { parentPort, workerData } from "node:worker_threads";
4
+ import { bindRuntimeOutcomeStore } from "./assignment-outcomes.domain.mjs";
5
+ import { enforceRegistrySizeCapOnce, runDailyCleanupOnce } from "./cleanup.domain.mjs";
6
+ import { onMetaChanged } from "./registry.domain.mjs";
7
+ import { openStore } from "./shared-operation-coordinator/index.domain.mjs";
8
+ const { root, config } = workerData;
9
+ process.env.PI_CODING_AGENT_DIR = root;
10
+ // Reuse one coordinator connection for all assignment and retention checks in this sweep.
11
+ const store = openStore({ path: join(root, "operation-coordinator.sqlite") });
12
+ const unbind = bindRuntimeOutcomeStore(root, store);
13
+ // Cleanup emits a metadata change after each committed removal, including during the daily sweep.
14
+ const off = onMetaChanged(meta => { if (meta)
15
+ parentPort.postMessage(meta.id); });
16
+ try {
17
+ runDailyCleanupOnce({ config });
18
+ enforceRegistrySizeCapOnce({ config });
19
+ }
20
+ finally {
21
+ off();
22
+ unbind();
23
+ store.close();
24
+ }