pi-better-server 0.7.0 → 0.7.1

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 (35) 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/domain/background-service/shared-harness-settings.domain.mjs +2 -3
  8. package/src/runtime/domain/background-service/shared-harness-settings.ts +2 -5
  9. package/src/runtime/domain/background-service/shared-ssh-core/index.domain.mjs +1 -1
  10. package/src/runtime/domain/background-service/shared-ssh-core/index.ts +1 -1
  11. package/src/runtime/domain/catalog/catalog-preferences.mjs +1 -3
  12. package/src/runtime/domain/sandbox-policy/package.json +1 -1
  13. package/src/runtime/domain/sandbox-policy/shared-harness-settings.domain.mjs +2 -3
  14. package/src/runtime/domain/sandbox-policy/shared-harness-settings.ts +2 -5
  15. package/src/runtime/domain/shared-harness-settings.mjs +2 -3
  16. package/src/runtime/domain/subagents/catalog-preferences.domain.mjs +1 -3
  17. package/src/runtime/domain/subagents/catalog-preferences.ts +1 -5
  18. package/src/runtime/domain/subagents/config.ts +1 -1
  19. package/src/runtime/domain/subagents/extensions.mjs +1 -0
  20. package/src/runtime/domain/subagents/finalization.domain.mjs +34 -30
  21. package/src/runtime/domain/subagents/finalization.ts +30 -28
  22. package/src/runtime/domain/subagents/git-workspace.domain.mjs +51 -6
  23. package/src/runtime/domain/subagents/git-workspace.ts +48 -6
  24. package/src/runtime/domain/subagents/index.domain.mjs +58 -27
  25. package/src/runtime/domain/subagents/index.ts +61 -26
  26. package/src/runtime/domain/subagents/isolated-workspace.domain.mjs +7 -14
  27. package/src/runtime/domain/subagents/isolated-workspace.ts +6 -12
  28. package/src/runtime/domain/subagents/package.json +1 -1
  29. package/src/runtime/domain/subagents/registry.domain.mjs +7 -7
  30. package/src/runtime/domain/subagents/registry.ts +8 -8
  31. package/src/runtime/domain/subagents/shared-harness-settings.domain.mjs +2 -3
  32. package/src/runtime/domain/subagents/shared-harness-settings.ts +2 -5
  33. package/src/runtime/domain/subagents/workspace-prepare-worker.mjs +12 -0
  34. package/src/shared-ssh-core/index.ts +1 -1
  35. package/src/version.ts +1 -1
@@ -72,15 +72,15 @@ export function finalizeRun(
72
72
  code: number | null,
73
73
  hooks: FinalizeHooks = {},
74
74
  ): FinalizeResult {
75
- const meta = readMeta(id);
75
+ const initial = readMeta(id);
76
76
  // Coherent child-exit evidence may supersede provisional orphaned/lost
77
77
  // reconciliation, but never overwrites a true terminal record.
78
- if (!meta || !canExitFinalize(meta.status)) return { applied: false };
78
+ if (!initial || !canExitFinalize(initial.status)) return { applied: false };
79
79
 
80
80
  // Lifecycle authority streams the complete NDJSON log; result text stays bounded.
81
81
  const r = parseRunForLifecycle(id);
82
82
  const outcome = classifyChildExit(code, r);
83
- collectRunFailures(id, meta.cwd, true);
83
+ collectRunFailures(id, initial.cwd, true);
84
84
  // A run can now end exit 0 as failed (a final request the model could not
85
85
  // serve), so "not incomplete and has an exit code" no longer means success.
86
86
  const completed = outcome.status === "completed";
@@ -98,11 +98,6 @@ export function finalizeRun(
98
98
  operation: "child-exit", kind: outcome.incomplete ? "incomplete" : "failure",
99
99
  category: "exit", summary }]);
100
100
  }
101
- meta.status = outcome.status;
102
- meta.lifecycleClassification = outcome.classification;
103
- if (outcome.incomplete) meta.failureReason = "incomplete-stream";
104
- meta.exitCode = code;
105
- meta.endedAt = Date.now();
106
101
  // A clean park finishes this ATTEMPT, not the assignment. It is only accepted
107
102
  // with a durable park record whose saved-conversation checkpoint still
108
103
  // verifies; a failed, incoherent or unverifiable exit stays an ordinary exit
@@ -115,26 +110,33 @@ export function finalizeRun(
115
110
  && completed && !outcome.incomplete && !outcome.diagnostics.modelError,
116
111
  });
117
112
  const parked = park.parked && park.record !== undefined;
118
- if (parked && park.record) {
119
- meta.park = park.record;
120
- // The rest of the attempt is complete; the assignment is still waiting.
121
- meta.status = "completed";
122
- }
123
- const callback = meta.callback !== false;
124
- if (callback
125
- && meta.completionCallbackPendingAt === undefined
126
- && meta.completionCallbackSentAt === undefined
127
- && meta.completionCallbackSuppressedAt === undefined) {
128
- if (parked) {
129
- // A parked attempt owes no completion callback: the continuation
130
- // resumes the same conversation and reports the assignment's result.
131
- meta.completionCallbackSuppressedAt = meta.endedAt;
132
- meta.completionCallbackSuppressedReason = `parked on wait ${park.record?.waitId} generation ${park.record?.generation}`;
133
- } else {
134
- meta.completionCallbackPendingAt = meta.endedAt;
113
+ const endedAt = Date.now();
114
+ const meta = writeMeta(initial, { patch: current => {
115
+ if (!canExitFinalize(current.status)) return undefined;
116
+ const patch: Partial<RunMeta> = {
117
+ status: outcome.status,
118
+ lifecycleClassification: outcome.classification,
119
+ ...(outcome.incomplete ? { failureReason: "incomplete-stream" } : {}),
120
+ exitCode: code,
121
+ endedAt,
122
+ };
123
+ if (parked && park.record) patch.park = park.record;
124
+ if (current.callback !== false
125
+ && current.completionCallbackPendingAt === undefined
126
+ && current.completionCallbackSentAt === undefined
127
+ && current.completionCallbackSuppressedAt === undefined) {
128
+ if (parked) {
129
+ // The continuation reports the assignment's result.
130
+ patch.completionCallbackSuppressedAt = endedAt;
131
+ patch.completionCallbackSuppressedReason = `parked on wait ${park.record?.waitId} generation ${park.record?.generation}`;
132
+ } else {
133
+ patch.completionCallbackPendingAt = endedAt;
134
+ }
135
135
  }
136
- }
137
- writeMeta(meta);
136
+ return patch;
137
+ } });
138
+ if (!meta) return { applied: false };
139
+ const callback = meta.callback !== false;
138
140
  commitAssignmentTerminal(meta);
139
141
  if (!parked && park.record) {
140
142
  // A park disposition existed but could not be proven on exit. Hold it in
@@ -150,7 +152,7 @@ export function finalizeRun(
150
152
  const verdict = parked
151
153
  ? `parked · waiting for ${park.record?.waitId ?? "its dependency"}`
152
154
  : outcome.verdict;
153
- const el = fmtElapsed(meta.endedAt - meta.startedAt);
155
+ const el = fmtElapsed(endedAt - meta.startedAt);
154
156
  const spend = fmtSpend(r.usage);
155
157
  const humanStat = `${el}${spend ? ` · ${spend}` : ""}`;
156
158
  const stat = el;
@@ -21,21 +21,27 @@
21
21
  */
22
22
  import { execFileSync } from "node:child_process";
23
23
  import { existsSync, lstatSync, mkdirSync, realpathSync } from "node:fs";
24
- import { dirname, join, resolve } from "node:path";
24
+ import { dirname, join, relative, resolve } from "node:path";
25
25
  import { readGitRemotes, syncGitRemotes } from "./git-remotes.domain.mjs";
26
26
  export { readGitRemotes, syncGitRemotes };
27
- function runGit(cwd, args, opts) {
27
+ const GIT_WORKSPACE_COMMAND_TIMEOUT_MS = 60_000;
28
+ function runGit(cwd, args, env) {
28
29
  try {
29
30
  return execFileSync("git", args, {
30
31
  cwd,
31
32
  encoding: "utf-8",
32
33
  stdio: ["ignore", "pipe", "pipe"],
33
- ...opts,
34
+ env: { ...(env ?? process.env), GIT_TERMINAL_PROMPT: "0" },
35
+ timeout: GIT_WORKSPACE_COMMAND_TIMEOUT_MS,
36
+ killSignal: "SIGKILL",
34
37
  }).trim();
35
38
  }
36
39
  catch (err) {
40
+ if (err.code === "ETIMEDOUT") {
41
+ throw new Error(`git ${args[0]} timed out after ${GIT_WORKSPACE_COMMAND_TIMEOUT_MS / 1_000} seconds in ${cwd}`, { cause: err });
42
+ }
37
43
  const message = err.message ?? String(err);
38
- throw new Error(`git ${args.join(" ")} failed in ${cwd}: ${message}`);
44
+ throw new Error(`git ${args.join(" ")} failed in ${cwd}: ${message}`, { cause: err });
39
45
  }
40
46
  }
41
47
  /** Resolve `path` to an absolute, real path. Falls back to resolve() if the path does not exist. */
@@ -226,6 +232,45 @@ function hasLinkedWorktreePointer(dir) {
226
232
  return false;
227
233
  }
228
234
  }
235
+ /** An ignored subdirectory can contain a separate, non-Git workspace. */
236
+ export function isIgnoredGitSubdirectory(root, subdir) {
237
+ if (!subdir)
238
+ return false;
239
+ try {
240
+ runGit(root, ["-c", "core.fsmonitor=false", "check-ignore", "--quiet", "--", subdir], Object.fromEntries(Object.entries(process.env).filter(([key]) => !key.startsWith("GIT_"))));
241
+ return true;
242
+ }
243
+ catch (error) {
244
+ if (error.cause?.status === 1)
245
+ return false;
246
+ throw error;
247
+ }
248
+ }
249
+ /** Locate shared metadata even when a caller supplies a subdirectory of the checkout. */
250
+ export function linkedWorktreeGitDir(cwd) {
251
+ const workspace = realPath(cwd);
252
+ let directory = workspace;
253
+ for (;;) {
254
+ const gitMarker = join(directory, ".git");
255
+ if (existsSync(gitMarker)) {
256
+ if (!hasLinkedWorktreePointer(directory))
257
+ return undefined;
258
+ try {
259
+ const info = inspectGitWorkspace(directory);
260
+ if (isIgnoredGitSubdirectory(info.repoRoot, relative(info.repoRoot, workspace)))
261
+ return undefined;
262
+ return info.gitDir;
263
+ }
264
+ catch {
265
+ throw linkedWorktreeError(directory);
266
+ }
267
+ }
268
+ const parent = dirname(directory);
269
+ if (parent === directory)
270
+ return undefined;
271
+ directory = parent;
272
+ }
273
+ }
229
274
  export function prepareGitCloneWorkspace(options) {
230
275
  const sourceDir = realPath(options.sourceDir);
231
276
  const targetDir = realPath(options.targetDir);
@@ -263,11 +308,11 @@ export function prepareGitCloneWorkspace(options) {
263
308
  // a normal clone. --dissociate removes the alternates link after setup.
264
309
  const cloneArgs = buildGitCloneArgs({ referenceRepo, cloneUrl, targetDir });
265
310
  try {
266
- runGit(dirname(targetDir), cloneArgs, { stdio: ["ignore", "pipe", "pipe"] });
311
+ runGit(dirname(targetDir), cloneArgs);
267
312
  }
268
313
  catch (err) {
269
314
  if (info.isLinkedWorktree) {
270
- throw linkedWorktreeError(sourceDir);
315
+ throw new Error(`${linkedWorktreeError(sourceDir).message} Clone preparation failed: ${err.message}`);
271
316
  }
272
317
  throw err;
273
318
  }
@@ -21,7 +21,7 @@
21
21
 
22
22
  import { execFileSync } from "node:child_process";
23
23
  import { existsSync, lstatSync, mkdirSync, realpathSync } from "node:fs";
24
- import { dirname, join, resolve } from "node:path";
24
+ import { dirname, join, relative, resolve } from "node:path";
25
25
 
26
26
  import { readGitRemotes, syncGitRemotes, type GitRemote } from "./git-remotes.ts";
27
27
 
@@ -38,17 +38,24 @@ export interface GitWorkspaceInfo {
38
38
  isLinkedWorktree: boolean;
39
39
  }
40
40
 
41
- function runGit(cwd: string, args: string[], opts?: { encoding?: BufferEncoding; stdio?: any }): string {
41
+ const GIT_WORKSPACE_COMMAND_TIMEOUT_MS = 60_000;
42
+
43
+ function runGit(cwd: string, args: string[], env?: NodeJS.ProcessEnv): string {
42
44
  try {
43
45
  return execFileSync("git", args, {
44
46
  cwd,
45
47
  encoding: "utf-8",
46
48
  stdio: ["ignore", "pipe", "pipe"],
47
- ...opts,
49
+ env: { ...(env ?? process.env), GIT_TERMINAL_PROMPT: "0" },
50
+ timeout: GIT_WORKSPACE_COMMAND_TIMEOUT_MS,
51
+ killSignal: "SIGKILL",
48
52
  }).trim();
49
53
  } catch (err) {
54
+ if ((err as NodeJS.ErrnoException).code === "ETIMEDOUT") {
55
+ throw new Error(`git ${args[0]} timed out after ${GIT_WORKSPACE_COMMAND_TIMEOUT_MS / 1_000} seconds in ${cwd}`, { cause: err });
56
+ }
50
57
  const message = (err as Error).message ?? String(err);
51
- throw new Error(`git ${args.join(" ")} failed in ${cwd}: ${message}`);
58
+ throw new Error(`git ${args.join(" ")} failed in ${cwd}: ${message}`, { cause: err });
52
59
  }
53
60
  }
54
61
 
@@ -298,6 +305,41 @@ function hasLinkedWorktreePointer(dir: string): boolean {
298
305
  }
299
306
  }
300
307
 
308
+ /** An ignored subdirectory can contain a separate, non-Git workspace. */
309
+ export function isIgnoredGitSubdirectory(root: string, subdir: string): boolean {
310
+ if (!subdir) return false;
311
+ try {
312
+ runGit(root, ["-c", "core.fsmonitor=false", "check-ignore", "--quiet", "--", subdir],
313
+ Object.fromEntries(Object.entries(process.env).filter(([key]) => !key.startsWith("GIT_"))));
314
+ return true;
315
+ } catch (error) {
316
+ if (((error as Error).cause as { status?: number } | undefined)?.status === 1) return false;
317
+ throw error;
318
+ }
319
+ }
320
+
321
+ /** Locate shared metadata even when a caller supplies a subdirectory of the checkout. */
322
+ export function linkedWorktreeGitDir(cwd: string): string | undefined {
323
+ const workspace = realPath(cwd);
324
+ let directory = workspace;
325
+ for (;;) {
326
+ const gitMarker = join(directory, ".git");
327
+ if (existsSync(gitMarker)) {
328
+ if (!hasLinkedWorktreePointer(directory)) return undefined;
329
+ try {
330
+ const info = inspectGitWorkspace(directory);
331
+ if (isIgnoredGitSubdirectory(info.repoRoot, relative(info.repoRoot, workspace))) return undefined;
332
+ return info.gitDir;
333
+ } catch {
334
+ throw linkedWorktreeError(directory);
335
+ }
336
+ }
337
+ const parent = dirname(directory);
338
+ if (parent === directory) return undefined;
339
+ directory = parent;
340
+ }
341
+ }
342
+
301
343
  export function prepareGitCloneWorkspace(options: PrepareGitCloneWorkspaceOptions): string {
302
344
  const sourceDir = realPath(options.sourceDir);
303
345
  const targetDir = realPath(options.targetDir);
@@ -343,10 +385,10 @@ export function prepareGitCloneWorkspace(options: PrepareGitCloneWorkspaceOption
343
385
  const cloneArgs = buildGitCloneArgs({ referenceRepo, cloneUrl, targetDir });
344
386
 
345
387
  try {
346
- runGit(dirname(targetDir), cloneArgs, { stdio: ["ignore", "pipe", "pipe"] });
388
+ runGit(dirname(targetDir), cloneArgs);
347
389
  } catch (err) {
348
390
  if (info.isLinkedWorktree) {
349
- throw linkedWorktreeError(sourceDir);
391
+ throw new Error(`${linkedWorktreeError(sourceDir).message} Clone preparation failed: ${(err as Error).message}`);
350
392
  }
351
393
  throw err;
352
394
  }
@@ -21,6 +21,7 @@ import { currentSandboxPermissions } from "./permission-policy.domain.mjs";
21
21
  import { assertWaitToolDependencies, createToolDescriptor } from "./operation-bridge-types.domain.mjs";
22
22
  import { requestResumeAdmission } from "./worker-waits.domain.mjs";
23
23
  import { execSync } from "node:child_process";
24
+ import { Worker } from "node:worker_threads";
24
25
  import { writeFileSync, mkdirSync, renameSync, statSync } from "node:fs";
25
26
  import * as PiCodingAgent from "@earendil-works/pi-coding-agent";
26
27
  import * as PiTui from "@earendil-works/pi-tui";
@@ -49,7 +50,7 @@ import { DELEGATION_MODES, DELEGATION_MODE_REQUEST, isDelegationMode, normalizeD
49
50
  import { resolveExtensions, extensionArgs } from "./extensions.domain.mjs";
50
51
  import { prepareTaskRuntime, applyDirectApplicationLoadout, DEFAULT_TASK_PERMISSIONS, RUN_APPLICATION, SDK_BUILTIN_TOOLS } from "./task-policy.domain.mjs";
51
52
  import { worktreePolicyNotice } from "./worktree-feedback.domain.mjs";
52
- import { canonicalizePath, compileWritePolicy, takeRecoverySnapshot } from "./shared-sandbox-core.domain.mjs";
53
+ import { canonicalizePath, compileWritePolicy, describeSandboxSupport, takeRecoverySnapshot } from "./shared-sandbox-core.domain.mjs";
53
54
  import { TASK_BUILTINS } from "./shared-task-sandbox.domain.mjs";
54
55
  import { describeTaskTools, planTaskTools, selectEffectiveTaskTools } from "./subagent-tools.domain.mjs";
55
56
  import { announceExecutionAdapter, describeSubagentProcessPolicy, effectiveWorkerProcessAccess, observeSandboxPermissions, resolveCommandSettings, resolveSubagentPermissions, } from "./permission-policy.domain.mjs";
@@ -354,7 +355,7 @@ function markCompletionCallbackSuppressed(id, reason, now = Date.now()) {
354
355
  if (sessionTornDown && reason === NO_ACTIVE_SESSION_REASON)
355
356
  return;
356
357
  const meta = readMeta(id);
357
- if (!meta || meta.completionCallbackSentAt !== undefined || meta.completionCallbackSuppressedAt !== undefined)
358
+ if (!meta)
358
359
  return;
359
360
  // An explicitly interrupted run owes its completion to the conversation that
360
361
  // launched it (#625, DEV-226 criterion 5). An unrelated session merely being
@@ -362,19 +363,22 @@ function markCompletionCallbackSuppressed(id, reason, now = Date.now()) {
362
363
  // attempt but must keep the obligation: the pending marker stays, and A
363
364
  // recovers it when it comes back. Records that never lost supervision keep
364
365
  // 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);
366
+ writeMeta(meta, { patch: current => {
367
+ if (current.completionCallbackSentAt !== undefined || current.completionCallbackSuppressedAt !== undefined)
368
+ return;
369
+ if ((current.supervisionInterruptedAt !== undefined || current.operations?.resumeLaunchToken)
370
+ && isConversationIdentityReason(reason))
371
+ return;
372
+ return { completionCallbackSuppressedAt: now, completionCallbackSuppressedReason: reason };
373
+ } });
371
374
  }
372
375
  function markCompletionCallbackSent(id, now) {
373
376
  const meta = readMeta(id);
374
- if (!meta || meta.completionCallbackSentAt !== undefined || meta.completionCallbackSuppressedAt !== undefined)
377
+ if (!meta)
375
378
  return;
376
- meta.completionCallbackSentAt = now;
377
- writeMeta(meta);
379
+ writeMeta(meta, { patch: current => current.completionCallbackSentAt === undefined && current.completionCallbackSuppressedAt === undefined
380
+ ? { completionCallbackSentAt: now } : undefined,
381
+ });
378
382
  }
379
383
  /** Queue one durable ordinary terminal event on the host-shared batch. */
380
384
  function enqueueCompletionCallback(pi, id) {
@@ -1127,10 +1131,11 @@ function stopForTiming(pi, id, reason, now) {
1127
1131
  return outcome.action === "finalized";
1128
1132
  }
1129
1133
  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);
1134
+ if (current) {
1135
+ writeMeta(current, { patch: latest => latest.callback !== false && latest.completionCallbackPendingAt === undefined
1136
+ && latest.completionCallbackSentAt === undefined && latest.completionCallbackSuppressedAt === undefined
1137
+ ? { completionCallbackPendingAt: now } : undefined,
1138
+ });
1134
1139
  }
1135
1140
  progressCache.delete(id);
1136
1141
  if (current && !callbackSuppressionReason(current)) {
@@ -2033,6 +2038,19 @@ function resolvePiBinary() {
2033
2038
  }
2034
2039
  return cachedPi;
2035
2040
  }
2041
+ function prepareLaunchWorkspace(options, isolated) {
2042
+ const built = import.meta.url.endsWith(".domain.mjs");
2043
+ const entry = new URL("./workspace-prepare-worker.mjs", import.meta.url);
2044
+ return new Promise((resolve, reject) => {
2045
+ const worker = new Worker(entry, {
2046
+ workerData: { options, isolated },
2047
+ execArgv: built ? [] : ["--import", import.meta.resolve("tsx")],
2048
+ });
2049
+ worker.once("message", resolve);
2050
+ worker.once("error", reject);
2051
+ worker.once("exit", code => reject(new Error(`Git workspace preparation exited before reporting a result (code ${code}).`)));
2052
+ });
2053
+ }
2036
2054
  /**
2037
2055
  * Finalize a run once its child exits. Host-facing wrapper around the
2038
2056
  * first-party finalizer (finalization.ts) so tests can exercise the durable
@@ -2862,8 +2880,8 @@ export default function (pi, managed) {
2862
2880
  */
2863
2881
  internal) {
2864
2882
  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");
2883
+ const { resolveSubagentWorkspace, linkedWorktreeGitDir } = await import("./git-workspace.domain.mjs");
2884
+ const { workspaceChoice, restoreWorkspace, discardWorkspace, markWorkspaceWriter } = await import("./isolated-workspace.domain.mjs");
2867
2885
  const { PREFLIGHT_ENV } = await import("./child-preflight.mjs");
2868
2886
  assertThinkingLevel(p.thinking);
2869
2887
  // Skill exposure is a caller choice, not a launch: validate its shape
@@ -2885,6 +2903,16 @@ export default function (pi, managed) {
2885
2903
  // and a profile that would change confinement refuses instead of silently
2886
2904
  // moving a live conversation into a different sandbox.
2887
2905
  const permissionPlan = resolveSubagentPermissions(pi, p.sandbox, resume && { runId: resume.prior.id, sandbox: resume.recipe.sandbox });
2906
+ if (permissionPlan.sandboxEnabled) {
2907
+ const support = describeSandboxSupport();
2908
+ if (!support.supported) {
2909
+ const remedy = permissionPlan.permissions
2910
+ ? "Turn off the Subagents sandbox in /sandbox settings to run without confinement."
2911
+ : resume ? "Launch a new subagent with sandbox:false to run without confinement."
2912
+ : "Pass sandbox:false to run without confinement.";
2913
+ throw new Error(`Task sandbox unavailable: ${support.reason} ${remedy}`);
2914
+ }
2915
+ }
2888
2916
  const processPolicy = describeSubagentProcessPolicy(permissionPlan, process.platform);
2889
2917
  const processAccess = effectiveWorkerProcessAccess(permissionPlan);
2890
2918
  const taskPermissions = permissionPlan.inactiveProfile
@@ -3020,14 +3048,15 @@ export default function (pi, managed) {
3020
3048
  mkdirSync(root, { mode: 0o700 });
3021
3049
  createdWorkspace = true;
3022
3050
  }
3023
- const isolatedCwd = isolated && !resume && !p.git_clone_workspace ? createIsolatedWorkspace(isolated, true) : undefined;
3051
+ const workspaceOptions = {
3052
+ ctxCwd: ctx.cwd, cwd: p.cwd, sandboxDir: p.sandbox_dir ?? ownedCloneWorkspace,
3053
+ gitCloneWorkspace: p.git_clone_workspace, runId: id, runDirPath: runDir(id), sandboxEnabled,
3054
+ };
3024
3055
  const workspace = resume
3025
3056
  ? { 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
- });
3057
+ : isolated || p.git_clone_workspace
3058
+ ? await prepareLaunchWorkspace(workspaceOptions, p.git_clone_workspace ? undefined : isolated)
3059
+ : resolveSubagentWorkspace(workspaceOptions);
3031
3060
  // Legacy explicit clones launch at the repository root, even when the source is a subdirectory.
3032
3061
  if (!resume && isolated && p.git_clone_workspace)
3033
3062
  isolated = { ...isolated, subdir: "" };
@@ -3304,8 +3333,9 @@ export default function (pi, managed) {
3304
3333
  const optionalTrustedTools = taskTools?.trusted.filter(({ name }) => selectedTools.includes(name)
3305
3334
  && (inheritedTrusted ? inheritedTrusted.has(name) : requestedTools === undefined)).map(({ name }) => name) ?? [];
3306
3335
  const dropped = toolSelection?.dropped ?? [];
3336
+ const sharedGitDir = sandboxEnabled && isolated?.mode !== "clone" ? linkedWorktreeGitDir(cwd) : undefined;
3307
3337
  const taskRuntime = sandboxEnabled && requestedSandboxDir ? prepareTaskRuntime({
3308
- worktreeGitDir: isolated?.mode === "worktree" ? inspectGitWorkspace(cwd).gitDir : undefined,
3338
+ worktreeGitDir: isolated?.mode === "worktree" ? sharedGitDir : undefined,
3309
3339
  root: requestedSandboxDir, controlDir: join(runDir(id), "control"),
3310
3340
  tools: selectedTools,
3311
3341
  permissions: taskPermissions && { ...taskPermissions, ...commandSettings },
@@ -3324,14 +3354,15 @@ export default function (pi, managed) {
3324
3354
  ? resume?.prior.operations?.policy.sandbox?.denyWrite
3325
3355
  : handoffAuthority?.sandbox?.denyWrite,
3326
3356
  }) : undefined;
3327
- if (taskRuntime?.policy.worktreeGitDir) {
3357
+ if (taskRuntime && sharedGitDir) {
3328
3358
  const policy = taskRuntime.policy;
3329
- const notice = worktreePolicyNotice(policy.worktreeGitDir, compileWritePolicy({
3359
+ const notice = worktreePolicyNotice(sharedGitDir, compileWritePolicy({
3330
3360
  writableRoot: policy.root, home: policy.home, permissions: policy.permissions,
3331
3361
  denyWrite: policy.denyWrite, runtimeCompatibility: true, runtimeWrite: [policy.scratch],
3332
3362
  }));
3333
3363
  if (notice) {
3334
- workspaceNote += " " + notice;
3364
+ workspaceNote = isolated?.mode === "worktree" ? `${workspaceNote} ${notice}`
3365
+ : `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
3366
  args[args.length - 1] = workspaceNote + "\n\n" + p.prompt;
3336
3367
  writeFileSync(promptPathFor(id), args[args.length - 1]);
3337
3368
  }
@@ -21,6 +21,7 @@ import { currentSandboxPermissions } from "./permission-policy.ts";
21
21
  import { assertWaitToolDependencies, createToolDescriptor } from "./operation-bridge-types.ts";
22
22
  import { requestResumeAdmission } from "./worker-waits.ts";
23
23
  import { execSync } from "node:child_process";
24
+ import { Worker } from "node:worker_threads";
24
25
  import { writeFileSync, mkdirSync, renameSync, statSync } from "node:fs";
25
26
  import type { ExtensionAPI, ExtensionCommandContext, ExtensionContext } from "@earendil-works/pi-coding-agent";
26
27
  import * as PiCodingAgent from "@earendil-works/pi-coding-agent";
@@ -83,7 +84,9 @@ import { DELEGATION_MODES, DELEGATION_MODE_REQUEST, isDelegationMode, normalizeD
83
84
  import { resolveExtensions, extensionArgs } from "./extensions.ts";
84
85
  import { prepareTaskRuntime, applyDirectApplicationLoadout, DEFAULT_TASK_PERMISSIONS, RUN_APPLICATION, SDK_BUILTIN_TOOLS } from "./task-policy.ts";
85
86
  import { worktreePolicyNotice } from "./worktree-feedback.ts";
86
- import { canonicalizePath, compileWritePolicy, takeRecoverySnapshot } from "./shared-sandbox-core.ts";
87
+ import type { IsolatedWorkspace } from "./isolated-workspace.ts";
88
+ import type { SubagentWorkspace, SubagentWorkspaceOptions } from "./git-workspace.ts";
89
+ import { canonicalizePath, compileWritePolicy, describeSandboxSupport, takeRecoverySnapshot } from "./shared-sandbox-core.ts";
87
90
  import { TASK_BUILTINS } from "./shared-task-sandbox.ts";
88
91
  import { describeTaskTools, planTaskTools, selectEffectiveTaskTools } from "./subagent-tools.ts";
89
92
  import {
@@ -537,25 +540,28 @@ function markCompletionCallbackSuppressed(id: string, reason: string, now: numbe
537
540
  // pending marker the replacing session recovers (#625), so leave it.
538
541
  if (sessionTornDown && reason === NO_ACTIVE_SESSION_REASON) return;
539
542
  const meta = readMeta(id);
540
- if (!meta || meta.completionCallbackSentAt !== undefined || meta.completionCallbackSuppressedAt !== undefined) return;
543
+ if (!meta) return;
541
544
  // An explicitly interrupted run owes its completion to the conversation that
542
545
  // launched it (#625, DEV-226 criterion 5). An unrelated session merely being
543
546
  // active — B opening before the original A returns — drops this delivery
544
547
  // attempt but must keep the obligation: the pending marker stays, and A
545
548
  // recovers it when it comes back. Records that never lost supervision keep
546
549
  // 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);
550
+ writeMeta(meta, { patch: current => {
551
+ if (current.completionCallbackSentAt !== undefined || current.completionCallbackSuppressedAt !== undefined) return;
552
+ if ((current.supervisionInterruptedAt !== undefined || current.operations?.resumeLaunchToken)
553
+ && isConversationIdentityReason(reason)) return;
554
+ return { completionCallbackSuppressedAt: now, completionCallbackSuppressedReason: reason };
555
+ } });
552
556
  }
553
557
 
554
558
  function markCompletionCallbackSent(id: string, now: number): void {
555
559
  const meta = readMeta(id);
556
- if (!meta || meta.completionCallbackSentAt !== undefined || meta.completionCallbackSuppressedAt !== undefined) return;
557
- meta.completionCallbackSentAt = now;
558
- writeMeta(meta);
560
+ if (!meta) return;
561
+ writeMeta(meta, { patch: current =>
562
+ current.completionCallbackSentAt === undefined && current.completionCallbackSuppressedAt === undefined
563
+ ? { completionCallbackSentAt: now } : undefined,
564
+ });
559
565
  }
560
566
 
561
567
  /** Queue one durable ordinary terminal event on the host-shared batch. */
@@ -1217,10 +1223,12 @@ function stopForTiming(pi: ExtensionAPI | undefined, id: string, reason: TimingS
1217
1223
  return outcome.action === "finalized";
1218
1224
  }
1219
1225
  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);
1226
+ if (current) {
1227
+ writeMeta(current, { patch: latest =>
1228
+ latest.callback !== false && latest.completionCallbackPendingAt === undefined
1229
+ && latest.completionCallbackSentAt === undefined && latest.completionCallbackSuppressedAt === undefined
1230
+ ? { completionCallbackPendingAt: now } : undefined,
1231
+ });
1224
1232
  }
1225
1233
  progressCache.delete(id);
1226
1234
  if (current && !callbackSuppressionReason(current)) {
@@ -2063,6 +2071,20 @@ function resolvePiBinary(): string {
2063
2071
  return cachedPi;
2064
2072
  }
2065
2073
 
2074
+ function prepareLaunchWorkspace(options: SubagentWorkspaceOptions, isolated?: IsolatedWorkspace): Promise<SubagentWorkspace> {
2075
+ const built = import.meta.url.endsWith(".domain.mjs");
2076
+ const entry = new URL("./workspace-prepare-worker.mjs", import.meta.url);
2077
+ return new Promise((resolve, reject) => {
2078
+ const worker = new Worker(entry, {
2079
+ workerData: { options, isolated },
2080
+ execArgv: built ? [] : ["--import", import.meta.resolve("tsx")],
2081
+ });
2082
+ worker.once("message", resolve);
2083
+ worker.once("error", reject);
2084
+ worker.once("exit", code => reject(new Error(`Git workspace preparation exited before reporting a result (code ${code}).`)));
2085
+ });
2086
+ }
2087
+
2066
2088
  /**
2067
2089
  * Finalize a run once its child exits. Host-facing wrapper around the
2068
2090
  * first-party finalizer (finalization.ts) so tests can exercise the durable
@@ -2933,8 +2955,8 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
2933
2955
  modelNote?: string;
2934
2956
  }> {
2935
2957
  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");
2958
+ const { resolveSubagentWorkspace, linkedWorktreeGitDir } = await import("./git-workspace.ts");
2959
+ const { workspaceChoice, restoreWorkspace, discardWorkspace, markWorkspaceWriter } = await import("./isolated-workspace.ts");
2938
2960
  const { PREFLIGHT_ENV } = await import("./child-preflight.mjs");
2939
2961
  assertThinkingLevel(p.thinking);
2940
2962
  // Skill exposure is a caller choice, not a launch: validate its shape
@@ -2956,6 +2978,16 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
2956
2978
  // moving a live conversation into a different sandbox.
2957
2979
  const permissionPlan = resolveSubagentPermissions(pi, p.sandbox,
2958
2980
  resume && { runId: resume.prior.id, sandbox: resume.recipe.sandbox });
2981
+ if (permissionPlan.sandboxEnabled) {
2982
+ const support = describeSandboxSupport();
2983
+ if (!support.supported) {
2984
+ const remedy = permissionPlan.permissions
2985
+ ? "Turn off the Subagents sandbox in /sandbox settings to run without confinement."
2986
+ : resume ? "Launch a new subagent with sandbox:false to run without confinement."
2987
+ : "Pass sandbox:false to run without confinement.";
2988
+ throw new Error(`Task sandbox unavailable: ${support.reason} ${remedy}`);
2989
+ }
2990
+ }
2959
2991
  const processPolicy = describeSubagentProcessPolicy(permissionPlan, process.platform);
2960
2992
  const processAccess = effectiveWorkerProcessAccess(permissionPlan);
2961
2993
  const taskPermissions = permissionPlan.inactiveProfile
@@ -3089,14 +3121,15 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
3089
3121
  mkdirSync(root, { mode: 0o700 });
3090
3122
  createdWorkspace = true;
3091
3123
  }
3092
- const isolatedCwd = isolated && !resume && !p.git_clone_workspace ? createIsolatedWorkspace(isolated, true) : undefined;
3124
+ const workspaceOptions = {
3125
+ ctxCwd: ctx.cwd, cwd: p.cwd, sandboxDir: p.sandbox_dir ?? ownedCloneWorkspace,
3126
+ gitCloneWorkspace: p.git_clone_workspace, runId: id, runDirPath: runDir(id), sandboxEnabled,
3127
+ };
3093
3128
  const workspace = resume
3094
3129
  ? { 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
- });
3130
+ : isolated || p.git_clone_workspace
3131
+ ? await prepareLaunchWorkspace(workspaceOptions, p.git_clone_workspace ? undefined : isolated)
3132
+ : resolveSubagentWorkspace(workspaceOptions);
3100
3133
  // Legacy explicit clones launch at the repository root, even when the source is a subdirectory.
3101
3134
  if (!resume && isolated && p.git_clone_workspace) isolated = { ...isolated, subdir: "" };
3102
3135
  let workspaceNote = isolated ? `Git workspace: ${isolated.mode} at ${workspace.cwd}. Base ${isolated.base}.`
@@ -3381,8 +3414,9 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
3381
3414
  const optionalTrustedTools = taskTools?.trusted.filter(({ name }) => selectedTools.includes(name)
3382
3415
  && (inheritedTrusted ? inheritedTrusted.has(name) : requestedTools === undefined)).map(({ name }) => name) ?? [];
3383
3416
  const dropped = toolSelection?.dropped ?? [];
3417
+ const sharedGitDir = sandboxEnabled && isolated?.mode !== "clone" ? linkedWorktreeGitDir(cwd) : undefined;
3384
3418
  const taskRuntime = sandboxEnabled && requestedSandboxDir ? prepareTaskRuntime({
3385
- worktreeGitDir: isolated?.mode === "worktree" ? inspectGitWorkspace(cwd).gitDir : undefined,
3419
+ worktreeGitDir: isolated?.mode === "worktree" ? sharedGitDir : undefined,
3386
3420
  root: requestedSandboxDir, controlDir: join(runDir(id), "control"),
3387
3421
  tools: selectedTools,
3388
3422
  permissions: taskPermissions && { ...taskPermissions, ...commandSettings },
@@ -3401,14 +3435,15 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
3401
3435
  ? (resume?.prior.operations?.policy.sandbox as WorkerSandboxAuthority | null)?.denyWrite
3402
3436
  : handoffAuthority?.sandbox?.denyWrite,
3403
3437
  }) : undefined;
3404
- if (taskRuntime?.policy.worktreeGitDir) {
3438
+ if (taskRuntime && sharedGitDir) {
3405
3439
  const policy = taskRuntime.policy;
3406
- const notice = worktreePolicyNotice(policy.worktreeGitDir!, compileWritePolicy({
3440
+ const notice = worktreePolicyNotice(sharedGitDir, compileWritePolicy({
3407
3441
  writableRoot: policy.root, home: policy.home, permissions: policy.permissions,
3408
3442
  denyWrite: policy.denyWrite, runtimeCompatibility: true, runtimeWrite: [policy.scratch],
3409
3443
  }));
3410
3444
  if (notice) {
3411
- workspaceNote += " " + notice;
3445
+ workspaceNote = isolated?.mode === "worktree" ? `${workspaceNote} ${notice}`
3446
+ : `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
3447
  args[args.length - 1] = workspaceNote + "\n\n" + p.prompt;
3413
3448
  writeFileSync(promptPathFor(id), args[args.length - 1]!);
3414
3449
  }