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,4 +1,5 @@
1
1
  // Generated fixed launch domain from packages/pi-better-subagents/index.ts. Do not edit directly.
2
+ import { taskDeadline } from "./shared-operation-coordinator/src/task-lifetime.domain.mjs";
2
3
  import { shouldRestoreWorkObservation } from "./shared-work-client.mjs";
3
4
  import { appendTimingWake, removeTimingReceipt, receiptTimingWake, timingWakeReceipt } from "./timing-notifications.domain.mjs";
4
5
  import { captureLaunchContext } from "./launch-context.domain.mjs";
@@ -21,6 +22,7 @@ import { currentSandboxPermissions } from "./permission-policy.domain.mjs";
21
22
  import { assertWaitToolDependencies, createToolDescriptor } from "./operation-bridge-types.domain.mjs";
22
23
  import { requestResumeAdmission } from "./worker-waits.domain.mjs";
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 * as PiCodingAgent from "@earendil-works/pi-coding-agent";
26
28
  import * as PiTui from "@earendil-works/pi-tui";
@@ -43,13 +45,13 @@ import { ORDINARY_TOOL_PROVIDERS, activeChildProviders, ordinaryChildConfig, add
43
45
  import { createSubagentSettingsPage } from "./settings-page.domain.mjs";
44
46
  import { deliverSubagentPrompt, effectiveSubagentSettings, subagentSettingsTool } from "./effective-settings.domain.mjs";
45
47
  import { STEER_FILE_ENV, readSteerReceipt } from "./child-steer.domain.mjs";
46
- import { continuationTimingParams, decideTiming, describeTiming, DEFAULT_TIMING_MINUTES, emptyProgress, foldProgress, formatTimingLimits, isTimingMinutes, isProgressRelevantLine, resolveRunTiming, steerText, stuckAlertText, TIMING_ENV, timingParameterSchemas, toolWaitAlertText, validatedTimingMinutes, } from "./timing.domain.mjs";
48
+ import { continuationTimingParams, configuredMaxMinutes, decideTiming, describeTiming, DEFAULT_TIMING_MINUTES, emptyProgress, foldProgress, formatTimingLimits, isTimingMinutes, isProgressRelevantLine, resolveRunTiming, steerText, stuckAlertText, TIMING_ENV, timingParameterSchemas, toolWaitAlertText, validatedTimingMinutes, } from "./timing.domain.mjs";
47
49
  import { readAppendedLines } from "./log-cursor.domain.mjs";
48
50
  import { DELEGATION_MODES, DELEGATION_MODE_REQUEST, isDelegationMode, normalizeDelegationMode } from "./delegation.domain.mjs";
49
51
  import { resolveExtensions, extensionArgs } from "./extensions.domain.mjs";
50
52
  import { prepareTaskRuntime, applyDirectApplicationLoadout, DEFAULT_TASK_PERMISSIONS, RUN_APPLICATION, SDK_BUILTIN_TOOLS } from "./task-policy.domain.mjs";
51
53
  import { worktreePolicyNotice } from "./worktree-feedback.domain.mjs";
52
- import { canonicalizePath, compileWritePolicy, takeRecoverySnapshot } from "./shared-sandbox-core.domain.mjs";
54
+ import { canonicalizePath, compileWritePolicy, describeSandboxSupport, takeRecoverySnapshot } from "./shared-sandbox-core.domain.mjs";
53
55
  import { TASK_BUILTINS } from "./shared-task-sandbox.domain.mjs";
54
56
  import { describeTaskTools, planTaskTools, selectEffectiveTaskTools } from "./subagent-tools.domain.mjs";
55
57
  import { announceExecutionAdapter, describeSubagentProcessPolicy, effectiveWorkerProcessAccess, observeSandboxPermissions, resolveCommandSettings, resolveSubagentPermissions, } from "./permission-policy.domain.mjs";
@@ -354,7 +356,7 @@ function markCompletionCallbackSuppressed(id, reason, now = Date.now()) {
354
356
  if (sessionTornDown && reason === NO_ACTIVE_SESSION_REASON)
355
357
  return;
356
358
  const meta = readMeta(id);
357
- if (!meta || meta.completionCallbackSentAt !== undefined || meta.completionCallbackSuppressedAt !== undefined)
359
+ if (!meta)
358
360
  return;
359
361
  // An explicitly interrupted run owes its completion to the conversation that
360
362
  // launched it (#625, DEV-226 criterion 5). An unrelated session merely being
@@ -362,19 +364,22 @@ function markCompletionCallbackSuppressed(id, reason, now = Date.now()) {
362
364
  // attempt but must keep the obligation: the pending marker stays, and A
363
365
  // recovers it when it comes back. Records that never lost supervision keep
364
366
  // today's durable suppression, so legacy/foreign notifications stay dead.
365
- if ((meta.supervisionInterruptedAt !== undefined || meta.operations?.resumeLaunchToken)
366
- && isConversationIdentityReason(reason))
367
- return;
368
- meta.completionCallbackSuppressedAt = now;
369
- meta.completionCallbackSuppressedReason = reason;
370
- writeMeta(meta);
367
+ writeMeta(meta, { patch: current => {
368
+ if (current.completionCallbackSentAt !== undefined || current.completionCallbackSuppressedAt !== undefined)
369
+ return;
370
+ if ((current.supervisionInterruptedAt !== undefined || current.operations?.resumeLaunchToken)
371
+ && isConversationIdentityReason(reason))
372
+ return;
373
+ return { completionCallbackSuppressedAt: now, completionCallbackSuppressedReason: reason };
374
+ } });
371
375
  }
372
376
  function markCompletionCallbackSent(id, now) {
373
377
  const meta = readMeta(id);
374
- if (!meta || meta.completionCallbackSentAt !== undefined || meta.completionCallbackSuppressedAt !== undefined)
378
+ if (!meta)
375
379
  return;
376
- meta.completionCallbackSentAt = now;
377
- writeMeta(meta);
380
+ writeMeta(meta, { patch: current => current.completionCallbackSentAt === undefined && current.completionCallbackSuppressedAt === undefined
381
+ ? { completionCallbackSentAt: now } : undefined,
382
+ });
378
383
  }
379
384
  /** Queue one durable ordinary terminal event on the host-shared batch. */
380
385
  function enqueueCompletionCallback(pi, id) {
@@ -1127,10 +1132,11 @@ function stopForTiming(pi, id, reason, now) {
1127
1132
  return outcome.action === "finalized";
1128
1133
  }
1129
1134
  const current = readMeta(id);
1130
- if (current && current.callback !== false && current.completionCallbackPendingAt === undefined
1131
- && current.completionCallbackSentAt === undefined && current.completionCallbackSuppressedAt === undefined) {
1132
- current.completionCallbackPendingAt = now;
1133
- writeMeta(current);
1135
+ if (current) {
1136
+ writeMeta(current, { patch: latest => latest.callback !== false && latest.completionCallbackPendingAt === undefined
1137
+ && latest.completionCallbackSentAt === undefined && latest.completionCallbackSuppressedAt === undefined
1138
+ ? { completionCallbackPendingAt: now } : undefined,
1139
+ });
1134
1140
  }
1135
1141
  progressCache.delete(id);
1136
1142
  if (current && !callbackSuppressionReason(current)) {
@@ -1151,7 +1157,12 @@ function stopForTiming(pi, id, reason, now) {
1151
1157
  */
1152
1158
  function enforceTiming(pi, meta, now) {
1153
1159
  const timing = meta.timing;
1154
- if (!timing || timing.stopReason)
1160
+ if (!timing)
1161
+ return false;
1162
+ if ((meta.status === "running" || meta.status === "orphaned") && now >= (timing.lifetimeAt ?? taskDeadline(meta.startedAt))) {
1163
+ return stopForTiming(pi, meta.id, "ceiling", now);
1164
+ }
1165
+ if (timing.stopReason)
1155
1166
  return false;
1156
1167
  // The ceiling also bounds an orphaned run (child gone, its process group still alive).
1157
1168
  if (meta.status === "orphaned") {
@@ -1651,10 +1662,7 @@ function navigatorCloseRun(id) {
1651
1662
  if (outcome.action === "dismissed" || outcome.action === "stopped-and-dismissed")
1652
1663
  pendingNavigatorDismissals.add(id);
1653
1664
  // A closed row is off the hot path: release its caches and retained events.
1654
- spendCache.delete(id);
1655
- healthLogCache.delete(id);
1656
- resetChildEventLogCursor(id);
1657
- resetParseRunCursor(id);
1665
+ forgetRunCaches(id);
1658
1666
  syncHealthTicker();
1659
1667
  // Close stops (or log-finalizes) the run, which is a terminal transition:
1660
1668
  // queue its one completion callback so no terminal state is silent (#624).
@@ -2033,6 +2041,25 @@ function resolvePiBinary() {
2033
2041
  }
2034
2042
  return cachedPi;
2035
2043
  }
2044
+ function forgetRunCaches(id) {
2045
+ spendCache.delete(id);
2046
+ healthLogCache.delete(id);
2047
+ resetChildEventLogCursor(id);
2048
+ resetParseRunCursor(id);
2049
+ }
2050
+ function prepareLaunchWorkspace(options, isolated) {
2051
+ const built = import.meta.url.endsWith(".domain.mjs");
2052
+ const entry = new URL("./workspace-prepare-worker.mjs", import.meta.url);
2053
+ return new Promise((resolve, reject) => {
2054
+ const worker = new Worker(entry, {
2055
+ workerData: { options, isolated },
2056
+ execArgv: built ? [] : ["--import", import.meta.resolve("tsx")],
2057
+ });
2058
+ worker.once("message", resolve);
2059
+ worker.once("error", reject);
2060
+ worker.once("exit", code => reject(new Error(`Git workspace preparation exited before reporting a result (code ${code}).`)));
2061
+ });
2062
+ }
2036
2063
  /**
2037
2064
  * Finalize a run once its child exits. Host-facing wrapper around the
2038
2065
  * first-party finalizer (finalization.ts) so tests can exercise the durable
@@ -2470,13 +2497,13 @@ export default function (pi, managed) {
2470
2497
  const defaults = resolveRunTiming({ settings: cfg, env: process.env, startedAt: 0 });
2471
2498
  const minutes = (ms) => ms === undefined ? 0 : ms / 60_000;
2472
2499
  return {
2473
- maxMinutes: minutes(effective.ceilingAt),
2500
+ maxMinutes: configuredMaxMinutes(sessionTimeout, timingSettingsFor(cfg), process.env),
2474
2501
  toolWaitMinutes: minutes(effective.toolWaitMs),
2475
2502
  stuckMinutes: minutes(effective.stuckMs),
2476
2503
  timeoutSource: timeoutSource(),
2477
2504
  toolWaitSource: sourceFor("toolWaitMinutes"),
2478
2505
  stuckSource: sourceFor("stuckMinutes"),
2479
- defaultMaxMinutes: minutes(defaults.ceilingAt),
2506
+ defaultMaxMinutes: configuredMaxMinutes({}, cfg, process.env),
2480
2507
  defaultToolWaitMinutes: minutes(defaults.toolWaitMs),
2481
2508
  defaultStuckMinutes: minutes(defaults.stuckMs),
2482
2509
  };
@@ -2862,8 +2889,8 @@ export default function (pi, managed) {
2862
2889
  */
2863
2890
  internal) {
2864
2891
  const { resolveChildClosure, resolveChildLaunch, configSnapshot } = await import("./child-dependencies.mjs");
2865
- const { resolveSubagentWorkspace, inspectGitWorkspace } = await import("./git-workspace.domain.mjs");
2866
- const { workspaceChoice, createIsolatedWorkspace, restoreWorkspace, discardWorkspace, markWorkspaceWriter } = await import("./isolated-workspace.domain.mjs");
2892
+ const { resolveSubagentWorkspace, linkedWorktreeGitDir } = await import("./git-workspace.domain.mjs");
2893
+ const { workspaceChoice, restoreWorkspace, discardWorkspace, markWorkspaceWriter } = await import("./isolated-workspace.domain.mjs");
2867
2894
  const { PREFLIGHT_ENV } = await import("./child-preflight.mjs");
2868
2895
  assertThinkingLevel(p.thinking);
2869
2896
  // Skill exposure is a caller choice, not a launch: validate its shape
@@ -2885,6 +2912,16 @@ export default function (pi, managed) {
2885
2912
  // and a profile that would change confinement refuses instead of silently
2886
2913
  // moving a live conversation into a different sandbox.
2887
2914
  const permissionPlan = resolveSubagentPermissions(pi, p.sandbox, resume && { runId: resume.prior.id, sandbox: resume.recipe.sandbox });
2915
+ if (permissionPlan.sandboxEnabled) {
2916
+ const support = describeSandboxSupport();
2917
+ if (!support.supported) {
2918
+ const remedy = permissionPlan.permissions
2919
+ ? "Turn off the Subagents sandbox in /sandbox settings to run without confinement."
2920
+ : resume ? "Launch a new subagent with sandbox:false to run without confinement."
2921
+ : "Pass sandbox:false to run without confinement.";
2922
+ throw new Error(`Task sandbox unavailable: ${support.reason} ${remedy}`);
2923
+ }
2924
+ }
2888
2925
  const processPolicy = describeSubagentProcessPolicy(permissionPlan, process.platform);
2889
2926
  const processAccess = effectiveWorkerProcessAccess(permissionPlan);
2890
2927
  const taskPermissions = permissionPlan.inactiveProfile
@@ -2921,20 +2958,17 @@ export default function (pi, managed) {
2921
2958
  model = parsed.model;
2922
2959
  thinking = parsed.thinking;
2923
2960
  }
2924
- // Best-effort daily hygiene for durable tmp state. The marker makes
2925
- // this effectively free after the first subagent launch each day.
2926
- // Resume has already validated this history. Retiring it here would let
2927
- // native --session create an empty replacement before the child runs.
2928
- if (!resume)
2929
- runDailyCleanupOnce({ config: cfg });
2930
- // Age retires history; this bounds the peak one busy day can reach.
2931
- // Rate-limited inside cleanup.ts, and never on the UI hot path.
2932
- const capped = resume ? { removed: [] } : enforceRegistrySizeCapOnce({ config: cfg });
2933
- for (const id of capped.removed) {
2934
- spendCache.delete(id);
2935
- healthLogCache.delete(id);
2936
- resetChildEventLogCursor(id);
2937
- resetParseRunCursor(id);
2961
+ // Continuations revalidate and lease their saved history. Only fresh launches request maintenance.
2962
+ if (!resume) {
2963
+ if (managed) {
2964
+ const { cleanupTerminalRunRetentionMs, cleanupSessionRetentionMs, maxRegistryBytes } = cfg;
2965
+ managed.scheduleRegistryCleanup({ cleanupTerminalRunRetentionMs, cleanupSessionRetentionMs, maxRegistryBytes }, forgetRunCaches);
2966
+ }
2967
+ else {
2968
+ runDailyCleanupOnce({ config: cfg });
2969
+ for (const removed of enforceRegistrySizeCapOnce({ config: cfg }).removed)
2970
+ forgetRunCaches(removed);
2971
+ }
2938
2972
  }
2939
2973
  const callbackOrigin = internal?.parkOwner
2940
2974
  ? { cwd: internal.parkOwner.workspace, sessionId: internal.parkOwner.sessionId }
@@ -3020,14 +3054,15 @@ export default function (pi, managed) {
3020
3054
  mkdirSync(root, { mode: 0o700 });
3021
3055
  createdWorkspace = true;
3022
3056
  }
3023
- const isolatedCwd = isolated && !resume && !p.git_clone_workspace ? createIsolatedWorkspace(isolated, true) : undefined;
3057
+ const workspaceOptions = {
3058
+ ctxCwd: ctx.cwd, cwd: p.cwd, sandboxDir: p.sandbox_dir ?? ownedCloneWorkspace,
3059
+ gitCloneWorkspace: p.git_clone_workspace, runId: id, runDirPath: runDir(id), sandboxEnabled,
3060
+ };
3024
3061
  const workspace = resume
3025
3062
  ? { cwd: resume.recipe.cwd, requestedSandboxDir: resume.recipe.sandboxDir }
3026
- : isolatedCwd ? { cwd: isolatedCwd, requestedSandboxDir: sandboxEnabled ? isolatedCwd : undefined }
3027
- : resolveSubagentWorkspace({
3028
- ctxCwd: ctx.cwd, cwd: p.cwd, sandboxDir: p.sandbox_dir ?? ownedCloneWorkspace,
3029
- gitCloneWorkspace: p.git_clone_workspace, runId: id, runDirPath: runDir(id), sandboxEnabled,
3030
- });
3063
+ : isolated || p.git_clone_workspace
3064
+ ? await prepareLaunchWorkspace(workspaceOptions, p.git_clone_workspace ? undefined : isolated)
3065
+ : resolveSubagentWorkspace(workspaceOptions);
3031
3066
  // Legacy explicit clones launch at the repository root, even when the source is a subdirectory.
3032
3067
  if (!resume && isolated && p.git_clone_workspace)
3033
3068
  isolated = { ...isolated, subdir: "" };
@@ -3304,8 +3339,9 @@ export default function (pi, managed) {
3304
3339
  const optionalTrustedTools = taskTools?.trusted.filter(({ name }) => selectedTools.includes(name)
3305
3340
  && (inheritedTrusted ? inheritedTrusted.has(name) : requestedTools === undefined)).map(({ name }) => name) ?? [];
3306
3341
  const dropped = toolSelection?.dropped ?? [];
3342
+ const sharedGitDir = sandboxEnabled && isolated?.mode !== "clone" ? linkedWorktreeGitDir(cwd) : undefined;
3307
3343
  const taskRuntime = sandboxEnabled && requestedSandboxDir ? prepareTaskRuntime({
3308
- worktreeGitDir: isolated?.mode === "worktree" ? inspectGitWorkspace(cwd).gitDir : undefined,
3344
+ worktreeGitDir: isolated?.mode === "worktree" ? sharedGitDir : undefined,
3309
3345
  root: requestedSandboxDir, controlDir: join(runDir(id), "control"),
3310
3346
  tools: selectedTools,
3311
3347
  permissions: taskPermissions && { ...taskPermissions, ...commandSettings },
@@ -3324,14 +3360,15 @@ export default function (pi, managed) {
3324
3360
  ? resume?.prior.operations?.policy.sandbox?.denyWrite
3325
3361
  : handoffAuthority?.sandbox?.denyWrite,
3326
3362
  }) : undefined;
3327
- if (taskRuntime?.policy.worktreeGitDir) {
3363
+ if (taskRuntime && sharedGitDir) {
3328
3364
  const policy = taskRuntime.policy;
3329
- const notice = worktreePolicyNotice(policy.worktreeGitDir, compileWritePolicy({
3365
+ const notice = worktreePolicyNotice(sharedGitDir, compileWritePolicy({
3330
3366
  writableRoot: policy.root, home: policy.home, permissions: policy.permissions,
3331
3367
  denyWrite: policy.denyWrite, runtimeCompatibility: true, runtimeWrite: [policy.scratch],
3332
3368
  }));
3333
3369
  if (notice) {
3334
- workspaceNote += " " + notice;
3370
+ workspaceNote = isolated?.mode === "worktree" ? `${workspaceNote} ${notice}`
3371
+ : `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.`;
3335
3372
  args[args.length - 1] = workspaceNote + "\n\n" + p.prompt;
3336
3373
  writeFileSync(promptPathFor(id), args[args.length - 1]);
3337
3374
  }
@@ -3474,6 +3511,11 @@ export default function (pi, managed) {
3474
3511
  trustedExtensions: resume?.recipe.trustedExtensions ?? taskTools?.trusted.map(({ name, package: owner, loadPath }) => ({ name, package: owner, loadPath })),
3475
3512
  });
3476
3513
  const startedAt = Date.now();
3514
+ const timing = resolveRunTiming({ params: launchTimingParams(p), settings: timingSettingsFor(cfg), env: process.env, startedAt });
3515
+ if (internal?.resumeWait && resume) {
3516
+ timing.lifetimeAt = resume.prior.timing?.lifetimeAt ?? taskDeadline(resume.prior.startedAt);
3517
+ timing.ceilingAt = Math.min(timing.lifetimeAt, resume.prior.timing?.ceilingAt ?? Infinity, timing.ceilingAt);
3518
+ }
3477
3519
  const meta = {
3478
3520
  assignment,
3479
3521
  outcomeSupport: { version: 1, available: Boolean(assignment), ...(!assignment ? { reason: "Legacy host has no verified parent session/transcript; durable assignment delivery is unavailable." } : {}) },
@@ -3523,9 +3565,12 @@ export default function (pi, managed) {
3523
3565
  tools: bridgePlan.tools,
3524
3566
  },
3525
3567
  } : {}),
3526
- timing: resolveRunTiming({ params: launchTimingParams(p), settings: timingSettingsFor(cfg), env: process.env, startedAt }),
3568
+ timing,
3527
3569
  };
3528
3570
  const dispatchGuard = await internal?.beforeSpawn?.({ runId: id, permissionPlan });
3571
+ if (internal?.resumeWait && Date.now() >= timing.ceilingAt) {
3572
+ throw new PreSpawnResumeError("The parked task reached its execution time limit before dispatch.");
3573
+ }
3529
3574
  if (isolated)
3530
3575
  markWorkspaceWriter(isolated, id);
3531
3576
  const managedEnv = managed?.beforeSpawn({ id, sessionId, lease: lease.token, leasePath: lease.path,
@@ -3692,7 +3737,7 @@ export default function (pi, managed) {
3692
3737
  if (!prior)
3693
3738
  throw new PreSpawnResumeError(`Cannot resume ${input.park.runId}: its run record is gone.`);
3694
3739
  const now = Date.now();
3695
- if (prior.timing?.deadlineAt !== undefined && now >= prior.timing.deadlineAt) {
3740
+ if (now >= taskDeadline(prior.startedAt, prior.timing?.ceilingAt) || (prior.timing?.deadlineAt !== undefined && now >= prior.timing.deadlineAt)) {
3696
3741
  throw new PreSpawnResumeError(`Cannot resume ${input.park.runId}: its assignment deadline passed while it was parked. The wait is held for the owner.`);
3697
3742
  }
3698
3743
  let plan;
@@ -3894,7 +3939,7 @@ export default function (pi, managed) {
3894
3939
  "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.",
3895
3940
  ...CATALOG_GUIDELINES,
3896
3941
  "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.",
3897
- "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.",
3942
+ "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.",
3898
3943
  "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.",
3899
3944
  "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.",
3900
3945
  "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.",
@@ -4430,7 +4475,7 @@ export default function (pi, managed) {
4430
4475
  : skills.mode === "none" ? "no skills" : `${skills.paths.length} selected skills`;
4431
4476
  const timing = timingState();
4432
4477
  ctx.ui.notify(`Delegation mode: ${activeDelegationMode()}. Concurrent subagents: ${activeConcurrencyCap()}. ` +
4433
- `Run timeout: ${timing.maxMinutes ? timing.maxMinutes + " minutes" : "No limit"}. Tool-wait alert: ${timing.toolWaitMinutes} min. ` +
4478
+ `Run timeout: ${timing.maxMinutes ? timing.maxMinutes + " minutes" : "24 hours"}. Tool-wait alert: ${timing.toolWaitMinutes} min. ` +
4434
4479
  `No-progress alert: ${timing.stuckMinutes} min. Skills: ${skillChoice}. ` +
4435
4480
  `Use /subagents mode <mode>, cap <number>, tool-wait <minutes>, stuck <minutes>, or settings; /subagents save persists them.`, "info");
4436
4481
  }
@@ -4522,7 +4567,7 @@ export default function (pi, managed) {
4522
4567
  : skills.mode === "none" ? "no skills" : `${skills.paths.length} selected skills`;
4523
4568
  const timing = timingState();
4524
4569
  if (ctx.hasUI && !(await ctx.ui.confirm("Save subagent defaults?", `Future sessions will start in ${activeDelegationMode()} with a cap of ${activeConcurrencyCap()}, ` +
4525
- `run timeout ${timing.maxMinutes ? timing.maxMinutes + " minutes" : "No limit"}, tool-wait alert ${timing.toolWaitMinutes} min, ` +
4570
+ `run timeout ${timing.maxMinutes ? timing.maxMinutes + " minutes" : "24 hours"}, tool-wait alert ${timing.toolWaitMinutes} min, ` +
4526
4571
  `no-progress alert ${timing.stuckMinutes} min, and ${skillChoice}.`))) {
4527
4572
  ctx.ui.notify("Subagent defaults unchanged.", "info");
4528
4573
  return;