pi-better-subagents 0.36.0 → 0.37.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/README.md +12 -10
  2. package/assignment-outcomes.ts +2 -5
  3. package/assignment-report.ts +20 -0
  4. package/batch.mjs +14 -5
  5. package/bin/recover-workspace.mjs +19 -0
  6. package/cleanup.ts +10 -2
  7. package/config.ts +7 -1
  8. package/continuation.ts +4 -2
  9. package/docs/usage.md +39 -53
  10. package/failures.ts +10 -2
  11. package/finalization.ts +7 -2
  12. package/index.ts +163 -60
  13. package/isolated-workspace.ts +557 -0
  14. package/list.mjs +2 -2
  15. package/managed-launch-client.ts +23 -6
  16. package/output-payload.ts +26 -12
  17. package/package.json +4 -2
  18. package/parse.ts +10 -5
  19. package/registry.ts +23 -5
  20. package/retained-result.ts +65 -0
  21. package/runtime-client/artifacts/darwin-arm64.gz +0 -0
  22. package/runtime-client/artifacts/darwin-arm64.json +1 -1
  23. package/runtime-client/artifacts/darwin-x64.gz +0 -0
  24. package/runtime-client/artifacts/darwin-x64.json +1 -1
  25. package/runtime-client/artifacts/linux-arm64.gz +0 -0
  26. package/runtime-client/artifacts/linux-arm64.json +1 -1
  27. package/runtime-client/artifacts/linux-x64.gz +0 -0
  28. package/runtime-client/artifacts/linux-x64.json +1 -1
  29. package/runtime-client/src/runtime/root.mjs +5 -2
  30. package/session-selection.ts +2 -1
  31. package/session-store.ts +9 -0
  32. package/settings-page.ts +147 -108
  33. package/shared-catalog.ts +23 -7
  34. package/shared-navigator.ts +47 -26
  35. package/shared-operation-coordinator/src/outbox.ts +9 -0
  36. package/shared-operation-coordinator/src/store.ts +6 -0
  37. package/task-guard.ts +13 -1
  38. package/task-policy.ts +5 -1
  39. package/tools.ts +4 -7
  40. package/work-observation.ts +20 -1
  41. package/workspace-files.ts +114 -0
  42. package/workspace-scope.ts +6 -0
  43. package/worktree-feedback.ts +77 -0
package/index.ts CHANGED
@@ -82,7 +82,8 @@ import { readAppendedLines, type LogCursor } from "./log-cursor.ts";
82
82
  import { DELEGATION_MODES, DELEGATION_MODE_REQUEST, isDelegationMode, normalizeDelegationMode, type DelegationMode } from "./delegation.ts";
83
83
  import { resolveExtensions, extensionArgs } from "./extensions.ts";
84
84
  import { prepareTaskRuntime, applyDirectApplicationLoadout, DEFAULT_TASK_PERMISSIONS, RUN_APPLICATION, SDK_BUILTIN_TOOLS } from "./task-policy.ts";
85
- import { canonicalizePath, takeRecoverySnapshot } from "./shared-sandbox-core.ts";
85
+ import { worktreePolicyNotice } from "./worktree-feedback.ts";
86
+ import { canonicalizePath, compileWritePolicy, takeRecoverySnapshot } from "./shared-sandbox-core.ts";
86
87
  import { TASK_BUILTINS } from "./shared-task-sandbox.ts";
87
88
  import { describeTaskTools, planTaskTools, selectEffectiveTaskTools } from "./subagent-tools.ts";
88
89
  import {
@@ -137,6 +138,7 @@ import {
137
138
  batchLaunchResult,
138
139
  mergeJobOptions,
139
140
  nextBatchId,
141
+ normalizeSessionSelector,
140
142
  planBatchLaunches,
141
143
  validateBatchPlan,
142
144
  } from "./batch.mjs";
@@ -966,6 +968,7 @@ let healthTicker: ReturnType<typeof setInterval> | undefined;
966
968
  let managedHealthClose: (() => void) | undefined;
967
969
  /** ExtensionAPI retained so health transitions can deliver coordinator follow-ups (#65). */
968
970
  let healthPi: ExtensionAPI | undefined;
971
+ let recoverWorkerWaitsAfterExit: (() => Promise<void>) | undefined;
969
972
 
970
973
  /**
971
974
  * Deliver a durable, deduped coordinator follow-up for orphaned/lost (#65).
@@ -1374,7 +1377,11 @@ function reconcileHealth(ids?: readonly string[]): void {
1374
1377
  notify: (message, level) => { try { ctx?.ui.notify(message, level); } catch { /* unavailable UI */ } },
1375
1378
  sendMessage: () => enqueueCompletionCallback(pi, meta.id),
1376
1379
  });
1377
- if (observed.finalization?.applied) { syncHealthTicker(); continue; }
1380
+ if (observed.finalization?.applied) {
1381
+ void recoverWorkerWaitsAfterExit?.().catch(() => undefined);
1382
+ syncHealthTicker();
1383
+ continue;
1384
+ }
1378
1385
  interruptedReconciliation = observed.reconciliation;
1379
1386
  }
1380
1387
  } catch { /* best-effort; the ordinary reconciliation below still runs */ }
@@ -2061,19 +2068,25 @@ function resolvePiBinary(): string {
2061
2068
  * first-party finalizer (finalization.ts) so tests can exercise the durable
2062
2069
  * path without importing the pi package.
2063
2070
  */
2064
- function finalizeRun(pi: ExtensionAPI, ctx: ExtensionContext | undefined, id: string, code: number | null): void {
2071
+ function finalizeRun(pi: ExtensionAPI, ctx: ExtensionContext | undefined, id: string, code: number | null, recoveredWriterExit = false): void {
2065
2072
  progressCache.delete(id);
2066
2073
  directlySupervisedRunIds.delete(id);
2067
2074
  // Host-facing wrapper around first-party finalizer (finalization.ts).
2068
2075
  // Coherent child-exit evidence may supersede provisional orphaned/lost
2069
2076
  // reconciliation; finalization.ts enforces canExitFinalize + lifecycle authority.
2070
- finalizeRunCore(id, code, {
2077
+ const result = finalizeRunCore(id, code, {
2078
+ recoveredWriterExit,
2071
2079
  renderWidget,
2072
2080
  notify: (message, level) => {
2073
2081
  try { ctx?.ui.notify(message, level); } catch { /* ignore */ }
2074
2082
  },
2075
2083
  sendMessage: () => enqueueCompletionCallback(pi, id),
2076
2084
  });
2085
+ if (recoveredWriterExit && result.applied) {
2086
+ // The old exit callback is gone. Finish its durable wait handoff after
2087
+ // recovery, including the independent writer and lease proof checks.
2088
+ void recoverWorkerWaitsAfterExit?.().catch(() => undefined);
2089
+ }
2077
2090
  syncHealthTicker();
2078
2091
  }
2079
2092
 
@@ -2105,7 +2118,7 @@ function finalizeInterruptedRunFromLog(
2105
2118
  if (!run.sawEnd || run.unmatchedToolCalls.length > 0) return false;
2106
2119
  // Exit code is unknown after the observer is gone; the lifecycle authority
2107
2120
  // classifies from the coherent stream instead of inventing one.
2108
- finalizeRun(pi, uiCtx, meta.id, null);
2121
+ finalizeRun(pi, uiCtx, meta.id, null, true);
2109
2122
  return true;
2110
2123
  }
2111
2124
 
@@ -2329,14 +2342,16 @@ function latestConversationAttempt(sessionId: string, metas: readonly RunMeta[])
2329
2342
  * missing session is the only error added here. Nothing is ever recreated.
2330
2343
  */
2331
2344
  function requestedSessionId(job: { session_id?: string; session_name?: string }, cwd: string): string | undefined {
2332
- if (job.session_id !== undefined && job.session_name !== undefined) {
2345
+ const sessionId = normalizeSessionSelector(job.session_id);
2346
+ const sessionName = normalizeSessionSelector(job.session_name);
2347
+ if (sessionId !== undefined && sessionName !== undefined) {
2333
2348
  throw new Error("Pass either session_id or session_name, not both.");
2334
2349
  }
2335
- if (job.session_name !== undefined) {
2336
- if (typeof job.session_name !== "string") throw new Error("session_name must be a non-empty name.");
2337
- return selectSessionByName(listMetas(), job.session_name, (workspace) => isWithinWorkspace(workspace, cwd));
2350
+ if (sessionName !== undefined) {
2351
+ if (typeof sessionName !== "string") throw new Error("session_name must be a non-empty name.");
2352
+ return selectSessionByName(listMetas(), sessionName, (workspace) => isWithinWorkspace(workspace, cwd));
2338
2353
  }
2339
- return job.session_id;
2354
+ return sessionId;
2340
2355
  }
2341
2356
 
2342
2357
  function continuationPlanFor(sessionId: string, origin: RunCallbackOrigin | undefined): ContinuationPlan {
@@ -2409,6 +2424,12 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
2409
2424
  let catalogModelRegistry: ExtensionContext["modelRegistry"] | undefined;
2410
2425
  let delegationOverride: DelegationMode | undefined;
2411
2426
  let capOverride: number | undefined;
2427
+ let workspaceOverride: "clone" | "worktree" | undefined;
2428
+ const activeWorkspace = () => workspaceOverride ?? (loadConfig().gitWorkspace === "worktree" ? "worktree" : "clone");
2429
+ const changeWorkspace = (mode: "clone" | "worktree") => {
2430
+ workspaceOverride = mode;
2431
+ pi.appendEntry("pi-better-subagents-workspace", { version: 1, mode });
2432
+ };
2412
2433
  let timingOverride: { maxMinutes?: number; toolWaitMinutes?: number; stuckMinutes?: number } = {};
2413
2434
  interface SkillSelection { mode: SkillExposureMode; paths: string[] }
2414
2435
  let skillsOverride: SkillSelection | undefined;
@@ -2536,7 +2557,9 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
2536
2557
  capOverride = undefined;
2537
2558
  delegationOverride = undefined;
2538
2559
  timingOverride = {};
2560
+ workspaceOverride = undefined;
2539
2561
  skillsOverride = undefined;
2562
+ pi.appendEntry("pi-better-subagents-workspace", { version: 1, mode: null });
2540
2563
  pi.appendEntry("pi-better-subagents-cap", { version: 1, maxConcurrent: null });
2541
2564
  pi.appendEntry("pi-better-subagents-delegation", { version: 1, mode: null });
2542
2565
  pi.appendEntry("pi-better-subagents-timing", { version: 1, maxMinutes: null, toolWaitMinutes: null, stuckMinutes: null });
@@ -2629,6 +2652,7 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
2629
2652
  savedTiming.stuckMinutes = cfg.stuckMinutes;
2630
2653
  }
2631
2654
  writeSubagentSettings({
2655
+ ...(workspaceOverride ? { gitWorkspace: workspaceOverride } : {}),
2632
2656
  delegationMode: activeDelegationMode(),
2633
2657
  maxConcurrent: activeConcurrencyCap(),
2634
2658
  ...savedTiming,
@@ -2669,6 +2693,7 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
2669
2693
  delegationOverride = undefined;
2670
2694
  capOverride = undefined;
2671
2695
  timingOverride = {};
2696
+ workspaceOverride = undefined;
2672
2697
  skillsOverride = undefined;
2673
2698
  const branch = ctx.sessionManager?.getBranch?.();
2674
2699
  if (!Array.isArray(branch)) return;
@@ -2703,6 +2728,12 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
2703
2728
  }
2704
2729
  continue;
2705
2730
  }
2731
+ if (entry.type === "custom" && entry.customType === "pi-better-subagents-workspace") {
2732
+ const data = entry.data as { version?: number; mode?: unknown } | null;
2733
+ if (data?.version === 1 && (data.mode === "worktree" || data.mode === "clone" || data.mode === null)) {
2734
+ workspaceOverride = data.mode ?? undefined;
2735
+ }
2736
+ }
2706
2737
  if (entry.type === "custom" && entry.customType === "pi-better-subagents-timing") {
2707
2738
  const data = entry.data as {
2708
2739
  version?: unknown; maxMinutes?: unknown; toolWaitMinutes?: unknown; stuckMinutes?: unknown;
@@ -2728,6 +2759,7 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
2728
2759
  // Capture for the health ticker (module-level); needed for orphaned/lost
2729
2760
  // coordinator follow-ups that fire outside a tool-call stack (#65).
2730
2761
  healthPi = pi;
2762
+ recoverWorkerWaitsAfterExit = reconcileWorkerWaits;
2731
2763
  ensureSubagentProvider();
2732
2764
  registerSubagentsGoalProvider(pi);
2733
2765
  observeSandboxPermissions(pi);
@@ -2741,12 +2773,12 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
2741
2773
  restoreDelegationMode(ctx);
2742
2774
  await workerOperations.start();
2743
2775
  return definition.execute(key, params, signal, onUpdate, ctx);
2744
- } } : { ...definition, async execute(key, params, _signal, _onUpdate, ctx) {
2776
+ } } : { ...definition, async execute(key, params, signal, _onUpdate, ctx) {
2745
2777
  ctx = captureLaunchContext(ctx);
2746
2778
  catalogHostFrom(ctx);
2747
2779
  const { submitManagedLaunch } = await import("./managed-launch-client.ts");
2748
2780
  void activateWorkObservation();
2749
- return await observeNavigatorLaunch(ctx, "subagents", key, "Subagent launch", () => submitManagedLaunch(pi, ctx, key, definition.name, params)) as never;
2781
+ return await observeNavigatorLaunch(ctx, "subagents", key, "Subagent launch", () => submitManagedLaunch(pi, ctx, key, definition.name, params, signal)) as never;
2750
2782
  } });
2751
2783
  };
2752
2784
  announceExecutionAdapter(pi, {
@@ -2836,7 +2868,7 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
2836
2868
  /** Skill exposure for this launch; omit to inherit catalog/config/discovery. */
2837
2869
  skills?: readonly string[];
2838
2870
  sandbox_dir?: string; callback?: boolean; cwd?: string;
2839
- git_clone_workspace?: boolean; approve?: boolean; allow_nested?: boolean;
2871
+ git_clone_workspace?: boolean; isolation?: boolean; recover_in_clone?: boolean; approve?: boolean; allow_nested?: boolean;
2840
2872
  agent?: string; role?: string | readonly string[]; alias?: string;
2841
2873
  catalog?: CatalogRunRecord; catalogResolved?: boolean;
2842
2874
  /**
@@ -2901,7 +2933,8 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
2901
2933
  modelNote?: string;
2902
2934
  }> {
2903
2935
  const { resolveChildClosure, resolveChildLaunch, configSnapshot } = await import("./child-dependencies.mjs");
2904
- const { resolveSubagentWorkspace } = await import("./git-workspace.ts");
2936
+ const { resolveSubagentWorkspace, inspectGitWorkspace } = await import("./git-workspace.ts");
2937
+ const { workspaceChoice, createIsolatedWorkspace, restoreWorkspace, discardWorkspace, markWorkspaceWriter } = await import("./isolated-workspace.ts");
2905
2938
  const { PREFLIGHT_ENV } = await import("./child-preflight.mjs");
2906
2939
  assertThinkingLevel(p.thinking);
2907
2940
  // Skill exposure is a caller choice, not a launch: validate its shape
@@ -2993,7 +3026,38 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
2993
3026
  // The disposable clone this launch owns (removed if the spawn fails); a caller's sandbox_dir is not ours.
2994
3027
  // A continuation never prepares another clone: the recipe's workspace already
2995
3028
  // holds the prior attempt's uncommitted work.
2996
- const ownedCloneWorkspace = !resume && !p.sandbox_dir && sandboxEnabled && p.git_clone_workspace ? taskWorkspaceDir(id) : undefined;
3029
+ if (p.isolation === false && p.git_clone_workspace) throw new Error("Choose either live checkout or git_clone_workspace.");
3030
+ if (p.recover_in_clone && (!resume || resume.recipe.workspace?.mode !== "worktree" || internal?.resumeWait)) {
3031
+ throw new Error("Clone handoff requires an explicit continuation of a linked worktree.");
3032
+ }
3033
+ if (resume && p.isolation !== undefined && Boolean(resume.recipe.workspace || resume.recipe.gitCloneWorkspace) !== p.isolation) {
3034
+ throw new ContinuationError("Changing isolation would replace the saved workspace.");
3035
+ }
3036
+ const handoffAuthority = p.recover_in_clone ? resume?.recipe.workspaceAuthority : undefined;
3037
+ if (p.recover_in_clone && resume) {
3038
+ const previous = handoffAuthority?.sandbox;
3039
+ const permissions = taskPermissions ?? DEFAULT_TASK_PERMISSIONS;
3040
+ assertAssignmentPermissionScope(handoffAuthority, {
3041
+ mandatoryPermissions: permissionPlan.enforced,
3042
+ sandbox: sandboxEnabled ? {
3043
+ root: resume.recipe.sandboxDir,
3044
+ denyWrite: previous?.denyWrite ?? [],
3045
+ permissions: {
3046
+ ...DEFAULT_TASK_PERMISSIONS, ...permissions, ...resolveCommandSettings(permissions),
3047
+ processAccess: permissions.processAccess ?? "off",
3048
+ },
3049
+ } : null,
3050
+ });
3051
+ }
3052
+ const selected = normalizeTools(p.tools ?? cfg.defaultTools ?? (p.clean ? SAFE_CLEAN_TOOLS : SAFE_DEFAULT_TOOLS));
3053
+ let isolated = resume?.recipe.workspace;
3054
+ if (!resume && !p.sandbox_dir && p.isolation !== false) {
3055
+ isolated = workspaceChoice(
3056
+ p.cwd ?? ctx.cwd, id, p.git_clone_workspace ? "clone" : activeWorkspace(),
3057
+ p.git_clone_workspace ? "write" : selected, p.git_clone_workspace ? "" : p.exclude_tools ?? "",
3058
+ );
3059
+ }
3060
+ const ownedCloneWorkspace = !resume && !p.sandbox_dir && (isolated || p.git_clone_workspace) ? taskWorkspaceDir(id) : undefined;
2997
3061
  // A launch attempt only becomes a run when `writeMeta` commits. Until
2998
3062
  // then everything it creates (prompt, control/, provenance, its own
2999
3063
  // session dir, clone workspace, task scratch) belongs to the attempt and
@@ -3003,6 +3067,7 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
3003
3067
  let spawned: ReturnType<typeof spawnDetached> | undefined;
3004
3068
  let launchScratch: string | undefined;
3005
3069
  let committed = false;
3070
+ let createdWorkspace = false;
3006
3071
  try {
3007
3072
  if (!resume) mkdirSync(childSessionDir, { recursive: true });
3008
3073
  mkdirSync(runDir(id), { recursive: true });
@@ -3012,17 +3077,30 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
3012
3077
  // (#623 R1). The outer catch drops the whole directory on failure.
3013
3078
  recordLaunchAttempt(id);
3014
3079
 
3080
+ // Cleanup, restoration and the actual writer share the conversation lease.
3081
+ if (resume || managed) lease = acquireConversationLease({ sessionId, attemptId: id });
3082
+ if (resume) {
3083
+ revalidateContinuationUnderLease(resume, callbackOrigin);
3084
+ if (isolated) isolated = restoreWorkspace(isolated, p.recover_in_clone, resume.prior.id);
3085
+ }
3086
+ if (!resume && isolated) {
3087
+ const root = taskWorkspaceDir(id);
3088
+ mkdirSync(dirname(root), { recursive: true });
3089
+ mkdirSync(root, { mode: 0o700 });
3090
+ createdWorkspace = true;
3091
+ }
3092
+ const isolatedCwd = isolated && !resume && !p.git_clone_workspace ? createIsolatedWorkspace(isolated, true) : undefined;
3015
3093
  const workspace = resume
3016
3094
  ? { cwd: resume.recipe.cwd, requestedSandboxDir: resume.recipe.sandboxDir }
3095
+ : isolatedCwd ? { cwd: isolatedCwd, requestedSandboxDir: sandboxEnabled ? isolatedCwd : undefined }
3017
3096
  : resolveSubagentWorkspace({
3018
- ctxCwd: ctx.cwd,
3019
- cwd: p.cwd,
3020
- sandboxDir: p.sandbox_dir ?? ownedCloneWorkspace,
3021
- gitCloneWorkspace: p.git_clone_workspace,
3022
- runId: id,
3023
- runDirPath: runDir(id),
3024
- sandboxEnabled,
3097
+ ctxCwd: ctx.cwd, cwd: p.cwd, sandboxDir: p.sandbox_dir ?? ownedCloneWorkspace,
3098
+ gitCloneWorkspace: p.git_clone_workspace, runId: id, runDirPath: runDir(id), sandboxEnabled,
3025
3099
  });
3100
+ // Legacy explicit clones launch at the repository root, even when the source is a subdirectory.
3101
+ if (!resume && isolated && p.git_clone_workspace) isolated = { ...isolated, subdir: "" };
3102
+ let workspaceNote = isolated ? `Git workspace: ${isolated.mode} at ${workspace.cwd}. Base ${isolated.base}.`
3103
+ + (isolated.mode === "worktree" && sandboxEnabled ? " Git metadata is shared outside this checkout. If the sandbox denies a Git operation, report the operation and current changes. The parent can review them here or continue this session with recover_in_clone:true." : "") : "";
3026
3104
  const cwd = workspace.cwd;
3027
3105
  const requestedSandboxDir = workspace.requestedSandboxDir;
3028
3106
 
@@ -3049,7 +3127,8 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
3049
3127
  });
3050
3128
 
3051
3129
  if (requestedSandboxDir) mkdirSync(requestedSandboxDir, { recursive: true });
3052
- writeFileSync(promptPathFor(id), p.prompt);
3130
+ const workerPrompt = workspaceNote ? workspaceNote + "\n\n" + p.prompt : p.prompt;
3131
+ writeFileSync(promptPathFor(id), workerPrompt);
3053
3132
 
3054
3133
  // A continuation keeps the recipe's launch intent; only current
3055
3134
  // permission-driven adjustments are re-derived from it.
@@ -3058,7 +3137,7 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
3058
3137
  const clean = resume ? resume.recipe.clean : p.clean === true;
3059
3138
  const allowNested = resume ? resume.recipe.allowNested : p.allow_nested === true;
3060
3139
  const approve = resume ? resume.recipe.approve : p.approve === true;
3061
- const gitCloneWorkspace = resume ? resume.recipe.gitCloneWorkspace : p.git_clone_workspace === true;
3140
+ const gitCloneWorkspace = isolated ? isolated.mode === "clone" : resume ? resume.recipe.gitCloneWorkspace : p.git_clone_workspace === true;
3062
3141
  const callbackEnabled = resume ? p.callback ?? resume.recipe.callback : p.callback !== false;
3063
3142
  const launchName = resume ? resume.recipe.name : p.name;
3064
3143
  // The frozen launch snapshot is the same shape a fresh spawn freezes.
@@ -3294,7 +3373,7 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
3294
3373
  ...(allow && !sandboxEnabled ? ["--tools", allow] : []),
3295
3374
  ...(excludes.size ? ["--exclude-tools", [...excludes].join(",")] : []),
3296
3375
  ...(sandboxEnabled ? ["--no-builtin-tools", "--no-approve"] : approve ? ["--approve"] : []),
3297
- p.prompt,
3376
+ workerPrompt,
3298
3377
  ];
3299
3378
 
3300
3379
  const selectedTools = allow.split(",").filter((name) => name && !excludes.has(name));
@@ -3303,6 +3382,7 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
3303
3382
  && (inheritedTrusted ? inheritedTrusted.has(name) : requestedTools === undefined)).map(({ name }) => name) ?? [];
3304
3383
  const dropped = toolSelection?.dropped ?? [];
3305
3384
  const taskRuntime = sandboxEnabled && requestedSandboxDir ? prepareTaskRuntime({
3385
+ worktreeGitDir: isolated?.mode === "worktree" ? inspectGitWorkspace(cwd).gitDir : undefined,
3306
3386
  root: requestedSandboxDir, controlDir: join(runDir(id), "control"),
3307
3387
  tools: selectedTools,
3308
3388
  permissions: taskPermissions && { ...taskPermissions, ...commandSettings },
@@ -3319,8 +3399,20 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
3319
3399
  runtimeRoots: [baseDir()],
3320
3400
  capturedDenyWrite: internal?.resumeWait
3321
3401
  ? (resume?.prior.operations?.policy.sandbox as WorkerSandboxAuthority | null)?.denyWrite
3322
- : undefined,
3402
+ : handoffAuthority?.sandbox?.denyWrite,
3323
3403
  }) : undefined;
3404
+ if (taskRuntime?.policy.worktreeGitDir) {
3405
+ const policy = taskRuntime.policy;
3406
+ const notice = worktreePolicyNotice(policy.worktreeGitDir!, compileWritePolicy({
3407
+ writableRoot: policy.root, home: policy.home, permissions: policy.permissions,
3408
+ denyWrite: policy.denyWrite, runtimeCompatibility: true, runtimeWrite: [policy.scratch],
3409
+ }));
3410
+ if (notice) {
3411
+ workspaceNote += " " + notice;
3412
+ args[args.length - 1] = workspaceNote + "\n\n" + p.prompt;
3413
+ writeFileSync(promptPathFor(id), args[args.length - 1]!);
3414
+ }
3415
+ }
3324
3416
  launchScratch = taskRuntime?.policy.scratch;
3325
3417
  if (sandboxEnabled && !taskRuntime) throw new Error("Task sandbox has no workspace; refusing an unconfined child.");
3326
3418
  // Parent-authored trust record, written before the child can run (#325).
@@ -3349,18 +3441,7 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
3349
3441
  if (countRunning() >= maxConcurrent) {
3350
3442
  throw new Error(`Max concurrent subagents (${maxConcurrent}) reached. Stop or let some finish first.`);
3351
3443
  }
3352
- // One writer per conversation, held across admission, child lifetime,
3353
- // and finalization. A live duplicate continuation is refused instead of
3354
- // letting two processes rewrite one session file. A fresh launch has a
3355
- // brand-new native session id, so it cannot contend with anyone and
3356
- // needs no lease; every continuation does.
3357
- if (resume || managed) {
3358
- lease = acquireConversationLease({ sessionId, attemptId: id });
3359
- }
3360
- // The lease is the first moment no other process can retire this
3361
- // conversation: re-prove the history identity the cached plan was
3362
- // built from, so `--session` can never reopen a file another sweep
3363
- // removed as an empty replacement.
3444
+ // Recheck the saved conversation after asynchronous launch preparation.
3364
3445
  if (resume) revalidateContinuationUnderLease(resume, callbackOrigin);
3365
3446
  const preflightPath = join(runDir(id), "child-preflight.json");
3366
3447
  writeFileSync(preflightPath, JSON.stringify({ ...fullResolution, model, tools: selectedTools,
@@ -3434,18 +3515,21 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
3434
3515
  // cannot hide inside a final asynchronous window.
3435
3516
  if (internal?.resumeWait && !resume?.prior.assignment) throw new PreSpawnResumeError("This legacy park has no verified assignment outcome recipient; refusing continuation on an unsupported binding.");
3436
3517
  if (!assignment && bridgeEnabled) throw new Error("Durable assignment outcomes require a recorded parent session and transcript capability.");
3437
- if (internal?.resumeWait) {
3438
- const captured = resume?.prior.operations?.policy;
3439
- const currentSandbox = taskRuntime ? {
3518
+ const workspaceAuthority = {
3519
+ mandatoryPermissions: permissionPlan.enforced,
3520
+ sandbox: taskRuntime ? {
3440
3521
  root: taskRuntime.policy.root,
3441
- ...(taskRuntime.policy.permissions ? { permissions: taskRuntime.policy.permissions } : {}),
3442
- ...(taskRuntime.policy.denyWrite ? { denyWrite: [...taskRuntime.policy.denyWrite] } : {}),
3443
- } : null;
3444
- assertAssignmentPermissionScope(captured, { sandbox: currentSandbox, mandatoryPermissions: permissionPlan.enforced }, Boolean(managed));
3522
+ permissions: taskRuntime.policy.permissions,
3523
+ denyWrite: [...taskRuntime.policy.denyWrite],
3524
+ } : null,
3525
+ };
3526
+ if (internal?.resumeWait) {
3527
+ assertAssignmentPermissionScope(resume?.prior.operations?.policy, workspaceAuthority, Boolean(managed));
3445
3528
  }
3446
3529
  // Freeze the ordinary recipe before the durable external-launch intent.
3447
3530
  const recipe = buildLaunchRecipe({
3448
3531
  ...(!legacyToolLoading ? { toolLoadingVersion: 1 as const } : {}),
3532
+ ...(isolated ? { workspace: isolated, workspaceAuthority } : {}),
3449
3533
  attemptId: id, sessionId, sessionDir: childSessionDir, cwd, model, effort: thinking,
3450
3534
  tools: callerLaunchTools(allow), excludeTools: requestedExcludes.size ? [...requestedExcludes].join(",") : undefined,
3451
3535
  ...(optionalTrustedTools.length ? { optionalTrustedTools } : {}),
@@ -3509,6 +3593,7 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
3509
3593
  timing: resolveRunTiming({ params: launchTimingParams(p), settings: timingSettingsFor(cfg), env: process.env, startedAt }),
3510
3594
  };
3511
3595
  const dispatchGuard = await internal?.beforeSpawn?.({ runId: id, permissionPlan });
3596
+ if (isolated) markWorkspaceWriter(isolated,id);
3512
3597
  const managedEnv = managed?.beforeSpawn({ id, sessionId, lease: lease!.token, leasePath: lease!.path,
3513
3598
  preflightPath, policyPath: taskRuntime?.policyPath, permissions: permissionPlan, recipe, recoveryMeta: meta });
3514
3599
  spawned = releaseChild(dispatchGuard, () => spawnDetached({ file: cmd.file, fileArgs: cmd.fileArgs, cwd, logPath: logPathFor(id),
@@ -3580,7 +3665,7 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
3580
3665
  : resolution.specs.length
3581
3666
  ? `Runtime: isolated · extensions ${resolution.specs.join(", ")}\n`
3582
3667
  : `Runtime: isolated · built-in tools only\n`;
3583
- const warn = (dropped.length ? `Task sandbox: ${dropped.map((tool) => `${tool.name} disabled (${withheldBridgeReasons.get(tool.name) ?? tool.reason})`).join("; ")}.\n` : "") +
3668
+ const warn = (workspaceNote ? workspaceNote + "\n" : "") + (dropped.length ? `Task sandbox: ${dropped.map((tool) => `${tool.name} disabled (${withheldBridgeReasons.get(tool.name) ?? tool.reason})`).join("; ")}.\n` : "") +
3584
3669
  (!sandboxEnabled && resolution.unmapped.length
3585
3670
  ? `NOTE: no extension mapped for ${resolution.unmapped.join(", ")} — ` +
3586
3671
  `${resolution.unmapped.length > 1 ? "these tools" : "this tool"} will NOT exist in the child. ` +
@@ -3605,8 +3690,9 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
3605
3690
  const { abortUncommittedLaunch } = await import("./launch-abort.ts");
3606
3691
  await abortUncommittedLaunch(id, {
3607
3692
  child: spawned, lease,
3608
- artifacts: { sessionDir: childSessionDir, workspaceDir: ownedCloneWorkspace, scratch: launchScratch },
3693
+ artifacts: { sessionDir: childSessionDir, workspaceDir: isolated ? undefined : ownedCloneWorkspace, scratch: launchScratch },
3609
3694
  });
3695
+ if (createdWorkspace && isolated) discardWorkspace(isolated);
3610
3696
  }
3611
3697
  throw error;
3612
3698
  }
@@ -3827,11 +3913,7 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
3827
3913
  service.registerContinuationAdapter(orchestration.adapter);
3828
3914
  } catch { /* a host that refuses the adapter leaves parking unavailable */ }
3829
3915
  try {
3830
- const reconciliation = reconcileParkedWaits(service, {
3831
- resume: (park) => orchestration.resume(park),
3832
- notifyWhen: (meta) => Boolean(activeCallbackOrigin && belongsToOrigin(meta, activeCallbackOrigin)),
3833
- notify: notifyOwnedWait,
3834
- });
3916
+ const reconciliation = reconcileWorkerWaits();
3835
3917
  if (managed) {
3836
3918
  void reconciliation.catch(() => undefined);
3837
3919
  return;
@@ -3844,6 +3926,17 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
3844
3926
  } catch { /* reconciliation retries on the next session start */ }
3845
3927
  }
3846
3928
 
3929
+ async function reconcileWorkerWaits(): Promise<void> {
3930
+ const service = workerOperations.service;
3931
+ if (!service) return;
3932
+ const orchestration = ensureResumeOrchestration();
3933
+ await reconcileParkedWaits(service, {
3934
+ resume: (park) => orchestration.resume(park),
3935
+ notifyWhen: (meta) => Boolean(activeCallbackOrigin && belongsToOrigin(meta, activeCallbackOrigin)),
3936
+ notify: notifyOwnedWait,
3937
+ });
3938
+ }
3939
+
3847
3940
  // ---- subagent_spawn -------------------------------------------------
3848
3941
  //
3849
3942
  // One tool launches both fresh work and a continuation of saved work. A
@@ -3871,7 +3964,7 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
3871
3964
  ...CATALOG_GUIDELINES,
3872
3965
  "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.",
3873
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.",
3874
- "Use git_clone_workspace:true when the subagent will mutate Git in a sandbox. The parent prepares a disposable, self-contained clone with a real .git/ directory inside the sandbox root, so linked-worktree metadata outside the sandbox cannot stall the child.",
3967
+ "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.",
3875
3968
  "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.",
3876
3969
  "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.",
3877
3970
  "Do not restate the original task or role when continuing: they already live in the saved conversation. A running or orphaned latest attempt blocks continuation until it stops, and missing saved history is refused rather than recreated.",
@@ -3894,6 +3987,8 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
3894
3987
  sandbox_dir: Type.Optional(Type.String({ description: "Confine writes to (and run the child in) this directory instead of the working dir. Created if missing." })),
3895
3988
  callback: Type.Optional(Type.Boolean({ description: "Default TRUE: on completion, trigger a turn that calls subagent_result and presents the result. Set false to finish quietly — the result is then read on demand via subagent_result." })),
3896
3989
  cwd: Type.Optional(Type.String({ description: "Working directory (default: current)." })),
3990
+ isolation: Type.Optional(Type.Boolean({ description: "Use false to work in the live checkout. By default each Git writer gets its own workspace." })),
3991
+ recover_in_clone: Type.Optional(Type.Boolean({ description: "Continue a stopped or completed linked-worktree conversation in a verified clone with the same history and permissions." })),
3897
3992
  git_clone_workspace: Type.Optional(Type.Boolean({ description: "Prepare a disposable Git clone workspace for sandboxed Git-mutating subagents. The clone has a real .git/ directory inside the sandbox writable root and is self-contained after setup." })),
3898
3993
  approve: Type.Optional(Type.Boolean({ description: "Trust project-local files in the child (default: false; headless runs cannot prompt for trust)." })),
3899
3994
  allow_nested: Type.Optional(Type.Boolean({ description: "Allow the child to spawn its own subagents (default: false). Loads this extension in the child and allowlists its tools." })),
@@ -3937,6 +4032,8 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
3937
4032
  model: p.model,
3938
4033
  thinking: p.thinking,
3939
4034
  callback: p.callback,
4035
+ isolation: p.isolation,
4036
+ recover_in_clone: p.recover_in_clone,
3940
4037
  deadline_minutes: p.deadline_minutes,
3941
4038
  grace_minutes: p.grace_minutes,
3942
4039
  max_minutes: p.max_minutes,
@@ -4064,6 +4161,7 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
4064
4161
  callback: Type.Optional(Type.Boolean({ description: "Default TRUE: post result back on completion." })),
4065
4162
  clean: Type.Optional(Type.Boolean({ description: "Hermetic builtins-only child; no extensions load." })),
4066
4163
  cwd: Type.Optional(Type.String({ description: "Working directory (default: current)." })),
4164
+ isolation: Type.Optional(Type.Boolean({ description: "Use false to work in the live checkout. By default each Git writer gets its own workspace." })),
4067
4165
  git_clone_workspace: Type.Optional(Type.Boolean({ description: "Prepare a disposable Git clone workspace for each job (same semantics as subagent_spawn)." })),
4068
4166
  approve: Type.Optional(Type.Boolean({ description: "Trust project-local files in children." })),
4069
4167
  allow_nested: Type.Optional(Type.Boolean({ description: "Allow children to spawn their own subagents." })),
@@ -4087,6 +4185,8 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
4087
4185
  callback: Type.Optional(Type.Boolean()),
4088
4186
  clean: Type.Optional(Type.Boolean()),
4089
4187
  cwd: Type.Optional(Type.String()),
4188
+ isolation: Type.Optional(Type.Boolean({ description: "Use false to work in the live checkout. By default each Git writer gets its own workspace." })),
4189
+ recover_in_clone: Type.Optional(Type.Boolean({ description: "Continue this job in a verified Clone." })),
4090
4190
  git_clone_workspace: Type.Optional(Type.Boolean()),
4091
4191
  approve: Type.Optional(Type.Boolean()),
4092
4192
  allow_nested: Type.Optional(Type.Boolean()),
@@ -4129,8 +4229,10 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
4129
4229
 
4130
4230
  let catalogSnapshot: CatalogSnapshot | undefined;
4131
4231
  let catalogHost: CatalogHost | undefined;
4132
- const needsCatalog = p.jobs.some((job) => job.session_id === undefined && job.session_name === undefined
4133
- && hasCatalogSelector(mergeJobOptions(p.shared, job)));
4232
+ const needsCatalog = p.jobs.some((job) => {
4233
+ const merged = mergeJobOptions(p.shared, job);
4234
+ return merged.session_id === undefined && merged.session_name === undefined && hasCatalogSelector(merged);
4235
+ });
4134
4236
  if (needsCatalog) {
4135
4237
  catalogHost = catalogHostFrom(ctx);
4136
4238
  noteCatalogHost(catalogHost);
@@ -4192,7 +4294,7 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
4192
4294
  const job = p.jobs[i];
4193
4295
  let name = names[i];
4194
4296
  const merged = mergeJobOptions(p.shared, job);
4195
- const isContinuation = job.session_id !== undefined || job.session_name !== undefined;
4297
+ const isContinuation = merged.session_id !== undefined || merged.session_name !== undefined;
4196
4298
  // A continuation keeps its own frozen model and effort. shared.model
4197
4299
  // is a default for NEW conversations, so only a per-job value is an
4198
4300
  // explicit escalation of the saved recipe.
@@ -4210,7 +4312,7 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
4210
4312
  }
4211
4313
 
4212
4314
  try {
4213
- const sessionId = requestedSessionId(job, ctx.cwd);
4315
+ const sessionId = requestedSessionId(merged, ctx.cwd);
4214
4316
  // A saved conversation is never re-resolved against the catalog.
4215
4317
  if (sessionId === undefined && catalogSnapshot && catalogHost && hasCatalogSelector(merged)) {
4216
4318
  const explicitName = typeof job.name === "string" && job.name.trim() !== "" ? job.name : undefined;
@@ -4387,6 +4489,7 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
4387
4489
  const timing = timingState();
4388
4490
  return {
4389
4491
  mode: settings.delegationMode, maxConcurrent: settings.maxConcurrent,
4492
+ gitWorkspace: activeWorkspace(),
4390
4493
  maxMinutes: timing.maxMinutes,
4391
4494
  modeSource: settings.sources.delegationMode,
4392
4495
  capSource: settings.sources.maxConcurrent,
@@ -4402,7 +4505,7 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
4402
4505
  skillsError: skills.error,
4403
4506
  };
4404
4507
  },
4405
- changeMode, changeCap, changeTiming, changeSkills, save: saveSettings, reset: resetSettings,
4508
+ changeMode, changeWorkspace, changeCap, changeTiming, changeSkills, save: saveSettings, reset: resetSettings,
4406
4509
  discoverSkills: () => discoveredSkillsFromContext(ctx),
4407
4510
  // Close this page first; the catalog opens after ui.custom resolves.
4408
4511
  openAgents: () => done("agents"),
@@ -4414,7 +4517,7 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
4414
4517
  : skills.mode === "none" ? "no skills" : `${skills.paths.length} selected skills`;
4415
4518
  const timing = timingState();
4416
4519
  ctx.ui.notify(`Delegation mode: ${activeDelegationMode()}. Concurrent subagents: ${activeConcurrencyCap()}. ` +
4417
- `Timeout: ${timing.maxMinutes} minutes (0 disables). Tool-wait alert: ${timing.toolWaitMinutes} min. ` +
4520
+ `Run timeout: ${timing.maxMinutes ? timing.maxMinutes + " minutes" : "No limit"}. Tool-wait alert: ${timing.toolWaitMinutes} min. ` +
4418
4521
  `No-progress alert: ${timing.stuckMinutes} min. Skills: ${skillChoice}. ` +
4419
4522
  `Use /subagents mode <mode>, cap <number>, tool-wait <minutes>, stuck <minutes>, or settings; /subagents save persists them.`, "info");
4420
4523
  }
@@ -4500,7 +4603,7 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
4500
4603
  const timing = timingState();
4501
4604
  if (ctx.hasUI && !(await ctx.ui.confirm("Save subagent defaults?",
4502
4605
  `Future sessions will start in ${activeDelegationMode()} with a cap of ${activeConcurrencyCap()}, ` +
4503
- `timeout ${timing.maxMinutes} minutes (0 disables), tool-wait alert ${timing.toolWaitMinutes} min, ` +
4606
+ `run timeout ${timing.maxMinutes ? timing.maxMinutes + " minutes" : "No limit"}, tool-wait alert ${timing.toolWaitMinutes} min, ` +
4504
4607
  `no-progress alert ${timing.stuckMinutes} min, and ${skillChoice}.`))) {
4505
4608
  ctx.ui.notify("Subagent defaults unchanged.", "info");
4506
4609
  return;