pi-better-subagents 0.37.0 → 0.37.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.
@@ -1,6 +1,6 @@
1
1
  import { createHash, randomUUID } from "node:crypto";
2
2
  import { closeSync, constants, fstatSync, fsyncSync, lstatSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
3
- import { createRequire } from "node:module";
3
+ import lockfile from "proper-lockfile";
4
4
  import { join, resolve } from "node:path";
5
5
  import { THINKING_LEVELS, type ThinkingLevel } from "./thinking.ts";
6
6
 
@@ -84,10 +84,6 @@ export function readCatalogPreferences(root: string): { settings: CatalogPrefere
84
84
  }
85
85
 
86
86
  function acquire(path: string): () => void {
87
- // Read-only catalog consumers (including the portable CLI) need no lock adapter.
88
- const lockfile = createRequire(import.meta.url)("proper-lockfile") as {
89
- lockSync(path: string, options: { realpath: boolean }): () => void;
90
- };
91
87
  for (let attempt = 0; attempt < 100; attempt++) {
92
88
  try { return lockfile.lockSync(path, { realpath: false }); }
93
89
  catch (error) {
package/config.ts CHANGED
@@ -45,7 +45,7 @@ export interface SubagentConfig extends TimingSettings {
45
45
  /**
46
46
  * Provider → extension package(s) that authenticate it. Model auth is not
47
47
  * tool-shaped: `xai/grok-4.5` needs pi-xai-oauth loaded whatever the tools.
48
- * A built-in entry covers `ollama-cloud`; an entry here replaces it.
48
+ * Entries here override built-in mappings, including Ollama Cloud and LiteLLM.
49
49
  */
50
50
  providerExtensions?: Record<string, string | string[]> | null;
51
51
  /**
package/extensions.mjs CHANGED
@@ -49,6 +49,7 @@ export const SELF_SPEC = "self";
49
49
  export const BUILTIN_PROVIDER_EXTENSIONS = {
50
50
  "router": "npm:pi-better-model-router",
51
51
  "ollama-cloud": "npm:pi-ollama-cloud",
52
+ "litellm": "npm:pi-provider-litellm",
52
53
  };
53
54
 
54
55
  /** Split "xai/grok-4.5" -> "xai". Returns undefined when there is no provider. */
package/finalization.ts CHANGED
@@ -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;
package/git-workspace.ts CHANGED
@@ -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
  }
package/index.ts CHANGED
@@ -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
  }
@@ -15,7 +15,7 @@ import {
15
15
  writeFileSync,
16
16
  } from "node:fs";
17
17
  import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
18
- import { inspectGitWorkspace, syncGitRemotes } from "./git-workspace.ts";
18
+ import { inspectGitWorkspace, isIgnoredGitSubdirectory, syncGitRemotes } from "./git-workspace.ts";
19
19
  import { restoreTree, snapshotTree, verifyTree, type SavedEntry } from "./workspace-files.ts";
20
20
  import { durableSubagentRoot } from "./session-store.ts";
21
21
  import { taskWorkspaceDir } from "./registry.ts";
@@ -93,16 +93,7 @@ export function workspaceChoice(
93
93
  throw error;
94
94
  }
95
95
  const subdir = relative(info.repoRoot, realpathSync(source));
96
- // A directory ignored by its enclosing checkout (e.g. a separate project in
97
- // build output) is not part of that checkout's selected Git base.
98
- if (subdir) {
99
- try {
100
- git(info.repoRoot, ["check-ignore", "--quiet", "--", subdir]);
101
- return;
102
- } catch (error) {
103
- if ((error as { status?: number }).status !== 1) throw error;
104
- }
105
- }
96
+ if (isIgnoredGitSubdirectory(info.repoRoot, subdir)) return;
106
97
  let base: string;
107
98
  try {
108
99
  base = value(source, ["rev-parse", "--verify", "HEAD"]);
@@ -188,7 +179,6 @@ const withoutGit = new Set([".git"]);
188
179
  const worktreePointers = new Set(["commondir", "gitdir"]);
189
180
  const sharedGitEntries = new Set(["config", "objects", "packed-refs", "refs", "logs", "info", "shallow", "hooks"]);
190
181
  const pendingOperation = [
191
- "index.lock",
192
182
  "rebase-merge",
193
183
  "rebase-apply",
194
184
  "MERGE_HEAD",
@@ -355,6 +345,10 @@ function checkpoint(w: IsolatedWorkspace, attempt: string) {
355
345
  const { root, record, store } = paths(w);
356
346
  const info = inspectOwned(w);
357
347
  const linked = w.mode === "worktree";
348
+ const indexLock = join(info.gitDir, "index.lock");
349
+ if (existsSync(indexLock)) {
350
+ throw new Error(`Git index lock blocks workspace recovery at ${indexLock}. Original checkout retained at ${root}.`);
351
+ }
358
352
  if (
359
353
  pendingOperation.some((name) => existsSync(join(info.gitDir, name))) ||
360
354
  existsSync(join(info.commonGitDir, "objects/info/alternates")) ||
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-better-subagents",
3
- "version": "0.37.0",
3
+ "version": "0.37.1",
4
4
  "description": "Pi extension for detached, sandboxed subagent runs that keep the foreground session free.",
5
5
  "license": "MIT",
6
6
  "type": "module",
package/registry.ts CHANGED
@@ -1092,7 +1092,8 @@ function takeToken(lockPath: string, payload: string, deadline: number, id: stri
1092
1092
  * decides who may recover or release it. A live pid — even one paused well
1093
1093
  * past two seconds — is not stolen. Release renames the lock aside and deletes
1094
1094
  * it only when the moved bytes are still ours, so a newer owner's lock stays.
1095
- * The lock is per run and is not a second registry.
1095
+ * The lock is per run. Metadata transitions that depend on the current record
1096
+ * use a patch so that the read and preconditions are repeated after lock loss.
1096
1097
  */
1097
1098
  function withRunMetaLock(id: string, body: (owns: () => boolean) => void): void {
1098
1099
  const directory = runDir(id);
@@ -1270,7 +1271,7 @@ export function writeMeta(meta: RunMeta, options: {
1270
1271
  ifAbsent?: boolean;
1271
1272
  /** Build a field update from current metadata under the existing run lock. */
1272
1273
  patch?: (current: Readonly<RunMeta>) => Partial<RunMeta> | undefined;
1273
- } = {}): void {
1274
+ } = {}): RunMeta | undefined {
1274
1275
  if (options.patch && !readMeta(meta.id)) return;
1275
1276
  mkdirSync(runDir(meta.id), { recursive: true });
1276
1277
  let written = false;
@@ -1303,10 +1304,11 @@ export function writeMeta(meta: RunMeta, options: {
1303
1304
  owns();
1304
1305
  written = true;
1305
1306
  });
1306
- if (options.patch && !written) return;
1307
+ if (options.patch && !written) return undefined;
1307
1308
  for (const listener of metaChangedListeners) {
1308
1309
  try { listener(meta); } catch { /* best effort */ }
1309
1310
  }
1311
+ return written ? meta : undefined;
1310
1312
  }
1311
1313
 
1312
1314
  export function onMetaChanged(listener: (meta?: RunMeta) => void): () => void {
@@ -1893,11 +1895,9 @@ export function isDismissed(meta: Pick<RunMeta, "dismissedAt">): boolean {
1893
1895
  export function dismissRun(id: string, at: number = Date.now()): RunMeta | undefined {
1894
1896
  const meta = readMeta(id);
1895
1897
  if (!meta) return undefined;
1896
- if (meta.dismissedAt === undefined) {
1897
- meta.dismissedAt = at;
1898
- writeMeta(meta);
1899
- }
1900
- return meta;
1898
+ return writeMeta(meta, {
1899
+ patch: current => current.dismissedAt === undefined ? { dismissedAt: at } : undefined,
1900
+ }) ?? readMeta(id);
1901
1901
  }
1902
1902
 
1903
1903
  /**
@@ -1 +1 @@
1
- {"build":{"format":1,"sourceDigest":"5bd2e8ad130e4ee494caf40bb7129c5c9c1f787d486de66304ec9a7fa5fcb45e","piSdkVersion":"1.4.0","nodeVersion":"24.14.1","platform":"darwin-arm64","dependencyLockDigest":"300f19071b0e3f4e68220f42d7976b92dc6a629dd2719325fb7fad41781164c8","protocolVersion":1,"serverVersion":"0.7.0","contentId":"be4b4f5c05d403d84c98a0e34f407fbf65fb8f90e4e9d07930404c8f408665eb"},"sha256":"701e694c1047bcb5ef4652c6a05cfbee0798eb90a4a1e57574118c0b3df59d18"}
1
+ {"build":{"format":1,"sourceDigest":"1a13882b3d93635543ba5ce23618d49d89a4dddd753e75b813c9717346da9066","piSdkVersion":"1.4.0","nodeVersion":"24.14.1","platform":"darwin-arm64","dependencyLockDigest":"300f19071b0e3f4e68220f42d7976b92dc6a629dd2719325fb7fad41781164c8","protocolVersion":1,"serverVersion":"0.7.1","contentId":"41b03fd7c1ec59d3a988425593df167293ff6733348e1e1ee2c26f5839255dec"},"sha256":"ae72e92a22c7d15b5252d0ffed543e576e31a944cdd801fde2f88563b27617c5"}
@@ -1 +1 @@
1
- {"build":{"format":1,"sourceDigest":"5bd2e8ad130e4ee494caf40bb7129c5c9c1f787d486de66304ec9a7fa5fcb45e","piSdkVersion":"1.4.0","nodeVersion":"24.14.1","platform":"darwin-x64","dependencyLockDigest":"300f19071b0e3f4e68220f42d7976b92dc6a629dd2719325fb7fad41781164c8","protocolVersion":1,"serverVersion":"0.7.0","contentId":"3db710d017c57fdc43d18531bcd3144de15767b9021223fcc262d39107db55f6"},"sha256":"4f88a4c1bf931f4af0805f227f5d473336f796f74cacad45020bad79e3962232"}
1
+ {"build":{"format":1,"sourceDigest":"1a13882b3d93635543ba5ce23618d49d89a4dddd753e75b813c9717346da9066","piSdkVersion":"1.4.0","nodeVersion":"24.14.1","platform":"darwin-x64","dependencyLockDigest":"300f19071b0e3f4e68220f42d7976b92dc6a629dd2719325fb7fad41781164c8","protocolVersion":1,"serverVersion":"0.7.1","contentId":"7fcd83a7e4ca03f06e2a17151c13ef7a39f674b098b61a096b8d191b3d609084"},"sha256":"3f33c2a9871efeac1de259d47133431805db6f78e6ec83dfc35a14c633b019e7"}
@@ -1 +1 @@
1
- {"build":{"format":1,"sourceDigest":"5bd2e8ad130e4ee494caf40bb7129c5c9c1f787d486de66304ec9a7fa5fcb45e","piSdkVersion":"1.4.0","nodeVersion":"24.14.1","platform":"linux-arm64","dependencyLockDigest":"300f19071b0e3f4e68220f42d7976b92dc6a629dd2719325fb7fad41781164c8","protocolVersion":1,"serverVersion":"0.7.0","contentId":"93a5ca8f14a1667ff653465e5844577f34c3f48c79b1ac87daea77f52eba65e3"},"sha256":"24938d0af26379b8b068e09e1e92d3a4c87d88ea04894a676100a4ed19d90649"}
1
+ {"build":{"format":1,"sourceDigest":"1a13882b3d93635543ba5ce23618d49d89a4dddd753e75b813c9717346da9066","piSdkVersion":"1.4.0","nodeVersion":"24.14.1","platform":"linux-arm64","dependencyLockDigest":"300f19071b0e3f4e68220f42d7976b92dc6a629dd2719325fb7fad41781164c8","protocolVersion":1,"serverVersion":"0.7.1","contentId":"974a599e19549eb47553301f8a2abf3f75f9ef49133835dd4feab13117aca209"},"sha256":"79dbfb51ab1495c873657db19815e6e23a2f22eb9fd00beec18bcdad20a3253f"}
@@ -1 +1 @@
1
- {"build":{"format":1,"sourceDigest":"5bd2e8ad130e4ee494caf40bb7129c5c9c1f787d486de66304ec9a7fa5fcb45e","piSdkVersion":"1.4.0","nodeVersion":"24.14.1","platform":"linux-x64","dependencyLockDigest":"300f19071b0e3f4e68220f42d7976b92dc6a629dd2719325fb7fad41781164c8","protocolVersion":1,"serverVersion":"0.7.0","contentId":"71973a617087e76c008eb1eb0b6e50d4ec51f2e6617af432828dba6bdf4baaa1"},"sha256":"b5f918fde231b83e9351dc194ec10bd60f5d8641c452c4925f0bbbffa5eeebd9"}
1
+ {"build":{"format":1,"sourceDigest":"1a13882b3d93635543ba5ce23618d49d89a4dddd753e75b813c9717346da9066","piSdkVersion":"1.4.0","nodeVersion":"24.14.1","platform":"linux-x64","dependencyLockDigest":"300f19071b0e3f4e68220f42d7976b92dc6a629dd2719325fb7fad41781164c8","protocolVersion":1,"serverVersion":"0.7.1","contentId":"ae922b992761077c8ed0d6c548495ce4f7f00a78535ecdb4e202c4d3967cf3ae"},"sha256":"cb9c77c019e2ce62ffde1098fa2944f6fff6ca828c59a10fad3c07db38dffa5b"}
@@ -1,14 +1,11 @@
1
1
  // Generated from packages/harness-settings/index.ts. Do not edit directly.
2
2
  import { existsSync, lstatSync, realpathSync, readFileSync, mkdirSync, renameSync, rmSync, writeFileSync } from "node:fs";
3
3
  import { randomUUID } from "node:crypto";
4
- import { createRequire } from "node:module";
5
4
  import { join } from "node:path";
6
5
  import { getAgentDir } from "@earendil-works/pi-coding-agent";
6
+ // A static import lets the compiled Pi loader resolve dependencies of the settings lock.
7
+ import lockfile from "proper-lockfile";
7
8
 
8
- // Match Pi's settings lock without depending on a private SDK import.
9
- const lockfile = createRequire(import.meta.url)("proper-lockfile") as {
10
- lockSync(path: string, options: { realpath: boolean }): () => void;
11
- };
12
9
  const NAMESPACE = "piBetterHarness";
13
10
  export interface HarnessSettingsSeams { agentDir?: () => string }
14
11
 
@@ -0,0 +1,11 @@
1
+ import { parentPort, workerData } from "node:worker_threads";
2
+ import { resolveSubagentWorkspace } from "./git-workspace.ts";
3
+ import { createIsolatedWorkspace } from "./isolated-workspace.ts";
4
+
5
+ const { options, isolated } = workerData;
6
+ if (isolated) {
7
+ const cwd = createIsolatedWorkspace(isolated, true);
8
+ parentPort.postMessage({ cwd, requestedSandboxDir: options.sandboxEnabled ? cwd : undefined });
9
+ } else {
10
+ parentPort.postMessage(resolveSubagentWorkspace(options));
11
+ }