pi-better-subagents 0.36.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.
Files changed (48) 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/catalog-preferences.ts +1 -5
  7. package/cleanup.ts +10 -2
  8. package/config.ts +8 -2
  9. package/continuation.ts +4 -2
  10. package/docs/usage.md +39 -53
  11. package/extensions.mjs +1 -0
  12. package/failures.ts +10 -2
  13. package/finalization.ts +37 -30
  14. package/git-workspace.ts +48 -6
  15. package/index.ts +213 -75
  16. package/isolated-workspace.ts +551 -0
  17. package/list.mjs +2 -2
  18. package/managed-launch-client.ts +23 -6
  19. package/output-payload.ts +26 -12
  20. package/package.json +4 -2
  21. package/parse.ts +10 -5
  22. package/registry.ts +31 -13
  23. package/retained-result.ts +65 -0
  24. package/runtime-client/artifacts/darwin-arm64.gz +0 -0
  25. package/runtime-client/artifacts/darwin-arm64.json +1 -1
  26. package/runtime-client/artifacts/darwin-x64.gz +0 -0
  27. package/runtime-client/artifacts/darwin-x64.json +1 -1
  28. package/runtime-client/artifacts/linux-arm64.gz +0 -0
  29. package/runtime-client/artifacts/linux-arm64.json +1 -1
  30. package/runtime-client/artifacts/linux-x64.gz +0 -0
  31. package/runtime-client/artifacts/linux-x64.json +1 -1
  32. package/runtime-client/src/runtime/root.mjs +5 -2
  33. package/session-selection.ts +2 -1
  34. package/session-store.ts +9 -0
  35. package/settings-page.ts +147 -108
  36. package/shared-catalog.ts +23 -7
  37. package/shared-harness-settings.ts +2 -5
  38. package/shared-navigator.ts +47 -26
  39. package/shared-operation-coordinator/src/outbox.ts +9 -0
  40. package/shared-operation-coordinator/src/store.ts +6 -0
  41. package/task-guard.ts +13 -1
  42. package/task-policy.ts +5 -1
  43. package/tools.ts +4 -7
  44. package/work-observation.ts +20 -1
  45. package/workspace-files.ts +114 -0
  46. package/workspace-prepare-worker.mjs +11 -0
  47. package/workspace-scope.ts +6 -0
  48. package/worktree-feedback.ts +77 -0
package/README.md CHANGED
@@ -31,7 +31,8 @@ The API is `runtime-client/src/runtime/client.mjs`, exporting `ensureRuntime`.
31
31
  - Explicit tool allowlists for child sessions, and `skills` for prompt exposure: omit it to keep user-catalog discovery, pass `[]` for no skills, or pass absolute `SKILL.md` paths for exactly those. See [skill exposure](docs/usage.md#skill-exposure).
32
32
  - Durable logs, result retrieval, and [failure observations](docs/failure-observations.md) independent of lifecycle status. A live child handles its own tool errors; the parent is woken only for actionable incidents, and children can classify handled failures with `failure_disposition`.
33
33
  - Live background-work navigator for active runs.
34
- - Harness-owned run timing: every run gets independent factual alerts for a tool call left open (5 min) and for no progress (10 min), plus a 60-minute hard timeout. Change the timeout in `/subagents settings`; `0` disables it. Soft deadlines remain opt-in. Configure per spawn with `deadline_minutes`, `grace_minutes`, `max_minutes`, `tool_wait_minutes`, `stuck_minutes`, globally in `config.json` / `PI_SUBAGENT_*_MINUTES`, or in `/subagents settings`. See [usage notes](docs/usage.md#run-timing-deadline-ceiling-tool-wait-stuck).
34
+ - Git writers start in separate Clones by default. **Git workspace** in `/subagents settings` also offers Worktree. Results carry the working directory or a recoverable copy, including incomplete work. [Workspace recovery](docs/usage.md#git-workspaces)
35
+ - Harness-owned run timing: every run gets independent factual alerts for a tool call left open (5 min) and for no progress (10 min), plus a 60-minute hard timeout. Choose a duration or **No limit** under **Run timeout** in `/subagents settings`. Soft deadlines remain opt-in. Configure per spawn with `deadline_minutes`, `grace_minutes`, `max_minutes`, `tool_wait_minutes`, `stuck_minutes`, globally in `config.json` / `PI_SUBAGENT_*_MINUTES`, or in `/subagents settings`. See [usage notes](docs/usage.md#run-timing-deadline-ceiling-tool-wait-stuck).
35
36
 
36
37
  Every single or batch launch automatically joins one shared supervision watcher in the
37
38
  foreground Pi process. The last active run's exit or stop tears it down; a later
@@ -41,6 +42,8 @@ alerts retain supervision until their handoff is handled, so lost work is not si
41
42
 
42
43
  ## Worker Ownership
43
44
 
45
+ Every subagent follows the same contract for preserving work and delivering results to its parent. It applies to read-only investigations as well as tasks that create or change files. [Subagent lifecycle, preservation and delivery](https://github.com/1aboveio/pi-better-harness/blob/main/packages/pi-better-subagents/docs/adr/0007-subagent-lifecycle.md)
46
+
44
47
  Every child launch, including clean, batch and unsandboxed launches, loads a Pi
45
48
  hook that keeps external CI/PR monitoring with its coordinator. Workers finish
46
49
  their assigned implementation or diagnosis, run focused checks, push only when
@@ -93,19 +96,18 @@ Linux confinement requires a usable `bubblewrap` backend and Pi SDK 0.82.1 or ne
93
96
 
94
97
  The user config sets `delegationMode` to `manual`, `adaptive` (default), or
95
98
  `coordinator`. `/subagents settings` (or `/subagents`) opens a settings page
96
- for delegation mode, the concurrent-subagent cap (default 6), the tool-wait
97
- alert (default 5 minutes), the no-progress alert (default 10 minutes), and the
98
- default skill exposure. The two time values are edited independently; `0` turns
99
- one alert off. Skill exposure cycles between Discover automatically and No skill
99
+ for delegation mode, the concurrent-subagent cap (default 6), and Git workspace
100
+ (Clone or Worktree). Run timeout supports a duration or **No limit**. The
101
+ tool-wait alert (default 5 minutes) and no-progress alert (default 10 minutes)
102
+ have separate intervals. Enter `0` to turn an alert off. Skill exposure cycles between Discover automatically and No skill
100
103
  catalog. The Selected skills row opens the same searchable checkbox picker used
101
104
  by `/agents`: it lists loaded skills by name and description, Space toggles one,
102
105
  Enter applies, and typing filters without dropping checked items. Saved paths
103
106
  missing from discovery stay visible as unavailable and survive apply. Zero
104
107
  checked applies No skill catalog, not discovery. Manual Add skill path remains
105
- available. The page names whether the current value comes from the saved config
106
- or this session. The session choice controls the next launch before Ctrl+S, and
107
- edits persist across reloads. Ctrl+S saves mode, cap, timing alerts, and skill
108
- exposure as defaults, and Reset to defaults clears session overrides, including
108
+ available. The Skill exposure row shows where the current skill setting comes from. The session choice controls the next launch before Ctrl+S, and
109
+ edits persist across reloads. Ctrl+S saves delegation, workspace, timing, and skill
110
+ settings as defaults, and Reset to defaults clears session overrides, including
109
111
  the skill list. Agents opens the same catalog as `/agents`; a definition that inherits
110
112
  skill exposure shows whether the live value comes from this session, saved
111
113
  config, or discovery, and an invalid draft is marked invalid rather than shown
@@ -194,7 +196,7 @@ The projection exposes an opaque semantic `revision`, readable `reason`, attempt
194
196
  identity, process status, termination evidence and retained evidence references.
195
197
  Compare revisions for equality; unchanged observations keep the same revision.
196
198
  Unavailable or unsupported coordinator reads report Waiting with an unverified
197
- reason. See the [projection contract](../../docs/adr/0022-assignment-progress-projection.md).
199
+ reason. See the [projection contract](https://github.com/1aboveio/pi-better-harness/blob/main/docs/adr/0022-assignment-progress-projection.md).
198
200
 
199
201
  - Repository: https://github.com/1aboveio/pi-better-harness
200
202
  - Detailed notes: https://github.com/1aboveio/pi-better-harness/blob/main/packages/pi-better-subagents/docs/usage.md
@@ -8,7 +8,7 @@ import type { RunMeta } from "./registry.ts";
8
8
  import { processStartToken, readMeta } from "./registry.ts";
9
9
  import type { PermissionSnapshot } from "./permission-policy.ts";
10
10
  import { credentialFilePaths } from "./shared-sandbox-core.ts";
11
- import { readAssignmentReport } from "./assignment-report.ts";
11
+ import { assignmentReportOutcomeReason, readAssignmentReport } from "./assignment-report.ts";
12
12
 
13
13
  export const ASSIGNMENT_OUTCOMES_VERSION = 1;
14
14
  const closedHosts = (globalThis as typeof globalThis & { __assignmentOutcomeClosedHosts?: Set<string> }).__assignmentOutcomeClosedHosts ??= new Set<string>();
@@ -91,12 +91,9 @@ export function commitAssignmentTerminal(meta: RunMeta, recoveryFailure = false)
91
91
  catch { if (meta.status === "completed") invalidReport = "Assignment completion is unverified: retained report evidence is unavailable or changed."; }
92
92
  const complete = meta.status === "completed" && (report ? report.status === "complete"
93
93
  : !invalidReport && waits.some((w) => w.acknowledgement?.disposition === "assignment-complete"));
94
- const reportReason = report?.status === "incomplete" ? `Assignment incomplete: ${report.reason}`
95
- + (report.blocker ? ` Blocked (${report.blocker.kind}): ${report.blocker.reason}.` : "")
96
- + (report.remainingWork ? ` Remaining work: ${report.remainingWork.join("; ")}.` : "") : report?.reason;
97
94
  try { return store.recordAssignmentOutcome({ ...binding, revision: 1,
98
95
  outcome: complete ? "succeeded" : meta.status === "killed" ? "cancelled" : "failed",
99
- reason: (meta.failureReason || invalidReport || (meta.status === "completed" && report ? reportReason : complete ? "Assigned work and required interpretation are complete."
96
+ reason: (meta.failureReason || invalidReport || (meta.status === "completed" && report ? assignmentReportOutcomeReason(report) : complete ? "Assigned work and required interpretation are complete."
100
97
  : meta.status === "completed" && meta.assignmentReportRejection ? `Assignment report rejected: ${meta.assignmentReportRejection.reason}`
101
98
  : meta.status === "completed" ? "Assignment completion is unverified: the attempt exited without an evidence-backed completion decision. Inspect retained output and continue unfinished work or report a concrete blocker."
102
99
  : `Assignment ended ${meta.status}; retained attempt evidence is available.`)).slice(0, 8192),
@@ -6,6 +6,7 @@ import { runDir, writeMeta, type RunMeta } from "./registry.ts";
6
6
  import { credentialFilePaths } from "./shared-sandbox-core.ts";
7
7
  import type { PermissionSnapshot, PermissionProfile } from "./permission-policy.ts";
8
8
  import { OperationBridgeError, redactSecret } from "./operation-bridge-types.ts";
9
+ import { requireText } from "./shared-operation-coordinator/src/validate.ts";
9
10
 
10
11
  const hash = (bytes: string | Buffer) => createHash("sha256").update(bytes).digest("hex");
11
12
  const inside = (root: string, path: string) => { const rel = relative(root, path); return rel === "" || (!rel.startsWith("..") && !isAbsolute(rel)); };
@@ -33,6 +34,21 @@ interface ReportInput {
33
34
  evidence: Array<{ path: string; explanation: string; offset?: number; max_bytes?: number }>;
34
35
  }
35
36
 
37
+ export function assignmentReportOutcomeReason(report: AssignmentReport): string {
38
+ if (report.status === "complete") return report.reason;
39
+ return (`Assignment incomplete: ${report.reason}`
40
+ + (report.blocker ? ` Blocked (${report.blocker.kind}): ${report.blocker.reason}.` : "")
41
+ + (report.remainingWork ? ` Remaining work: ${report.remainingWork.join("; ")}.` : "")).slice(0, 8192);
42
+ }
43
+
44
+ function validateReportText(report: AssignmentReport): void {
45
+ requireText("report.reason", report.reason, 2048);
46
+ for (const item of report.remainingWork ?? []) requireText("report.remaining_work", item, 1024);
47
+ if (report.blocker) requireText("report.blocker.reason", report.blocker.reason, 1024);
48
+ for (const evidence of report.evidence) requireText("report.evidence.explanation", evidence.explanation, 1024);
49
+ requireText("report.outcome_reason", assignmentReportOutcomeReason(report), 8192);
50
+ }
51
+
36
52
  /** Runs synchronously under the authenticated handler: no yield between authority and persistence. */
37
53
  export function recordAssignmentReport(id: string, input: unknown, assertAuthority: () => RunMeta, current?: PermissionSnapshot) {
38
54
  const meta = assertAuthority();
@@ -86,6 +102,7 @@ function retainAssignmentReport(id: string, input: unknown, meta: RunMeta, asser
86
102
  status: report.status as AssignmentReport["status"], reason: report.reason,
87
103
  ...(report.remaining_work ? { remainingWork: report.remaining_work } : {}), ...(report.blocker ? { blocker: report.blocker } : {}),
88
104
  evidence: snapshots.map(({ digest, source, explanation, range }) => ({ path: join(directory, digest), digest, source, explanation, ...(range ? { range } : {}) })) };
105
+ validateReportText(retained);
89
106
  const text = JSON.stringify(retained);
90
107
  if (Buffer.byteLength(text) > 65536) throw new Error("Assignment report exceeds its retained metadata bound.");
91
108
  const digest = hash(text);
@@ -152,5 +169,8 @@ export function readAssignmentReport(meta: RunMeta): AssignmentReport | null {
152
169
  || !Number.isSafeInteger(e.range.sourceBytes) || e.range.sourceBytes < 0 || e.range.bytes !== bytes.length
153
170
  || e.range.offset + e.range.bytes > e.range.sourceBytes))) throw new Error("Retained assignment evidence changed.");
154
171
  }
172
+ // Older accepted reports may contain prose the terminal store cannot retain.
173
+ // Treat those as unverified evidence rather than throwing during finalization.
174
+ validateReportText(report);
155
175
  return report;
156
176
  }
package/batch.mjs CHANGED
@@ -94,13 +94,15 @@ export function mergeJobOptions(shared, job) {
94
94
  cwd: job.cwd ?? shared?.cwd,
95
95
  // Same semantics as subagent_spawn: shared and per-job values must reach
96
96
  // spawnSubagentRun so batch jobs can request disposable clone workspaces.
97
+ isolation: job.isolation ?? shared?.isolation,
98
+ recover_in_clone: job.recover_in_clone,
97
99
  git_clone_workspace: job.git_clone_workspace ?? shared?.git_clone_workspace,
98
100
  approve: job.approve ?? shared?.approve,
99
101
  allow_nested: job.allow_nested ?? shared?.allow_nested,
100
102
  // Native session id selected for this JOB only. A shared value would make
101
103
  // every job contend for the same conversation writer, so it is not inherited.
102
- session_id: typeof job.session_id === "string" ? job.session_id : undefined,
103
- session_name: typeof job.session_name === "string" ? job.session_name : undefined,
104
+ session_id: typeof job.session_id === "string" ? normalizeSessionSelector(job.session_id) : undefined,
105
+ session_name: typeof job.session_name === "string" ? normalizeSessionSelector(job.session_name) : undefined,
104
106
  // Harness timing; an explicit null means "not set", so it falls through to shared.
105
107
  deadline_minutes: job.deadline_minutes ?? shared?.deadline_minutes,
106
108
  grace_minutes: job.grace_minutes ?? shared?.grace_minutes,
@@ -113,6 +115,11 @@ export function mergeJobOptions(shared, job) {
113
115
  };
114
116
  }
115
117
 
118
+ /** Keep nonblank selectors exact. Only a blank string is equivalent to omission. */
119
+ export function normalizeSessionSelector(value) {
120
+ return typeof value === "string" && value.trim() === "" ? undefined : value;
121
+ }
122
+
116
123
  function catalogText(value) {
117
124
  return typeof value === "string" && value.trim() !== "" ? value : undefined;
118
125
  }
@@ -157,9 +164,11 @@ export function validateBatchPlan({ shared, jobs, onCapacity, config }) {
157
164
  if (typeof job.prompt !== "string" || job.prompt.trim() === "") {
158
165
  throw new Error(`job ${i + 1} is missing a non-empty prompt.`);
159
166
  }
160
- if (job.session_id !== undefined && job.session_name !== undefined) throw new Error(`job ${i + 1}: pass either session_id or session_name, not both.`);
161
- if (job.session_name !== undefined && (typeof job.session_name !== "string" || job.session_name.trim() === "")) throw new Error(`job ${i + 1} session_name must be a non-empty name.`);
162
- if (job.session_id !== undefined && (typeof job.session_id !== "string" || job.session_id.trim() === "")) {
167
+ const sessionId = normalizeSessionSelector(job.session_id);
168
+ const sessionName = normalizeSessionSelector(job.session_name);
169
+ if (sessionId !== undefined && sessionName !== undefined) throw new Error(`job ${i + 1}: pass either session_id or session_name, not both.`);
170
+ if (sessionName !== undefined && typeof sessionName !== "string") throw new Error(`job ${i + 1} session_name must be a non-empty name.`);
171
+ if (sessionId !== undefined && typeof sessionId !== "string") {
163
172
  throw new Error(`job ${i + 1} session_id must be a non-empty native session id.`);
164
173
  }
165
174
  if (seenPrompts.has(job.prompt)) {
@@ -0,0 +1,19 @@
1
+ #!/usr/bin/env node
2
+ // Recover a separate checkout, including failed runs that cannot start another writer.
3
+ import { tsImport } from "tsx/esm/api";
4
+ const { readMeta } = await tsImport("../registry.ts", import.meta.url);
5
+ const { readRetainedResult } = await tsImport("../retained-result.ts", import.meta.url);
6
+ const { exportWorkspace } = await tsImport("../isolated-workspace.ts", import.meta.url);
7
+ try {
8
+ const [, , id, destination] = process.argv;
9
+ if (!/^sa_[a-z0-9]+_[a-z0-9]+$/i.test(id ?? "") || !destination || process.argv.length !== 4) {
10
+ throw new Error("Usage: pi-subagents-recover <run-id> <new-directory>");
11
+ }
12
+ const meta = readRetainedResult(id) ?? readMeta(id);
13
+ if (!meta?.recipe?.workspace) throw new Error("No saved Git workspace for " + id);
14
+ exportWorkspace(meta.recipe.workspace, id, destination);
15
+ console.log("Recovered " + id + " to " + destination);
16
+ } catch (error) {
17
+ console.error(error.message);
18
+ process.exitCode = 1;
19
+ }
@@ -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/cleanup.ts CHANGED
@@ -615,7 +615,7 @@ function removeAgedRunArtifacts(
615
615
  if (!conversationQuiescentUnderLock(meta.sessionId, runIds)) return false;
616
616
  const fresh = readMeta(meta.id) ?? meta;
617
617
  if (!ageSweepEligible(fresh, cutoff, retained, scope)) return false;
618
- if (removeMetaArtifacts(fresh, { keepWorkspace: scope.persistent.has(fresh.sessionId) })) return true;
618
+ if (removeMetaArtifacts(fresh, { keepWorkspace: scope.persistent.has(fresh.sessionId), errors })) return true;
619
619
  errors.push(`${runDir(meta.id)}: could not remove run artifacts`);
620
620
  return false;
621
621
  }, () => false);
@@ -867,6 +867,7 @@ export function collectSizeCapEntries(): SizeCapEntry[] {
867
867
  return [];
868
868
  }
869
869
  const entries: SizeCapEntry[] = [];
870
+ const workspaces = new Map<string, { root: string; started: number; entry: SizeCapEntry }>();
870
871
  for (const id of ids) {
871
872
  const dir = runDir(id);
872
873
  const meta = readMeta(id);
@@ -877,7 +878,14 @@ export function collectSizeCapEntries(): SizeCapEntry[] {
877
878
  dirMtimeMs: safeStatMtime(dir) ?? 0,
878
879
  bytes: dirBytes(dir),
879
880
  });
881
+ const workspace = meta?.recipe?.workspace;
882
+ if (workspace && meta && meta.startedAt >= (workspaces.get(workspace.owner)?.started ?? 0)) {
883
+ workspaces.set(workspace.owner, { root: workspace.root, started: meta.startedAt, entry: entries[entries.length - 1]! });
884
+ }
880
885
  }
886
+ // A restored conversation may have outlived its first attempt. Charge its
887
+ // one shared checkout to the most recent writer still in the registry.
888
+ for (const { root, entry } of workspaces.values()) entry.bytes += dirBytes(root);
881
889
  return entries;
882
890
  }
883
891
 
@@ -999,7 +1007,7 @@ function removeSizeCappedRun(
999
1007
  if (!TERMINAL_CLEANUP_STATUSES.has(fresh.status)) return "retained";
1000
1008
  if (outcomeProtected(fresh)) return "retained";
1001
1009
  if (scope.occupancy.runIds.has(fresh.id)) return "retained";
1002
- if (removeMetaArtifacts(fresh, { keepWorkspace: scope.persistent.has(fresh.sessionId) })) return "removed";
1010
+ if (removeMetaArtifacts(fresh, { keepWorkspace: scope.persistent.has(fresh.sessionId), errors })) return "removed";
1003
1011
  errors.push(`${runDir(id)}: could not remove run artifacts`);
1004
1012
  return "failed";
1005
1013
  }, () => "retained");
package/config.ts CHANGED
@@ -25,6 +25,7 @@ import { harnessSettingsPath, readHarnessSetting, updateHarnessSetting } from ".
25
25
  export interface SubagentConfig extends TimingSettings {
26
26
  /** Foreground delegation policy; /subagents mode overrides this for the current session. */
27
27
  delegationMode?: DelegationMode | null;
28
+ gitWorkspace?: "clone" | "worktree";
28
29
  defaultModel?: string | null;
29
30
  defaultTools?: string | null;
30
31
  /**
@@ -44,7 +45,7 @@ export interface SubagentConfig extends TimingSettings {
44
45
  /**
45
46
  * Provider → extension package(s) that authenticate it. Model auth is not
46
47
  * tool-shaped: `xai/grok-4.5` needs pi-xai-oauth loaded whatever the tools.
47
- * A built-in entry covers `ollama-cloud`; an entry here replaces it.
48
+ * Entries here override built-in mappings, including Ollama Cloud and LiteLLM.
48
49
  */
49
50
  providerExtensions?: Record<string, string | string[]> | null;
50
51
  /**
@@ -197,6 +198,7 @@ export function writeSubagentSettings(
197
198
  settings: {
198
199
  delegationMode: DelegationMode;
199
200
  maxConcurrent: number;
201
+ gitWorkspace?: "clone" | "worktree";
200
202
  maxMinutes?: number;
201
203
  /** Omit to preserve the saved value; `null` explicitly records discovery. */
202
204
  defaultSkills?: string[] | null;
@@ -211,11 +213,15 @@ export function writeSubagentSettings(
211
213
  if (!isConcurrencyCap(settings.maxConcurrent)) throw new Error("Concurrent subagents must be a positive whole number.");
212
214
  const next: {
213
215
  delegationMode: DelegationMode; maxConcurrent: number; maxMinutes?: number; defaultSkills?: string[] | null;
214
- toolWaitMinutes?: number; stuckMinutes?: number;
216
+ toolWaitMinutes?: number; stuckMinutes?: number; gitWorkspace?: "clone" | "worktree";
215
217
  } = {
216
218
  delegationMode: settings.delegationMode,
217
219
  maxConcurrent: settings.maxConcurrent,
218
220
  };
221
+ if (settings.gitWorkspace !== undefined) {
222
+ if (settings.gitWorkspace !== "clone" && settings.gitWorkspace !== "worktree") throw new Error("Unknown Git workspace mode.");
223
+ next.gitWorkspace = settings.gitWorkspace;
224
+ }
219
225
  if (settings.maxMinutes !== undefined) {
220
226
  next.maxMinutes = validatedTimingMinutes(settings.maxMinutes, "maxMinutes");
221
227
  }
package/continuation.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { hasWorkspaceCheckpoint } from "./isolated-workspace.ts";
1
2
  /**
2
3
  * Subagent continuation.
3
4
  *
@@ -536,11 +537,12 @@ export function planContinuation(options: {
536
537
 
537
538
  let workspaceIsDir = false;
538
539
  try { workspaceIsDir = statSync(recipe.cwd).isDirectory(); } catch { workspaceIsDir = false; }
539
- if (!workspaceIsDir) throw refusal(id, `its workspace ${recipe.cwd} is missing.`);
540
+ const recoverable = !workspaceIsDir && recipe.workspace && hasWorkspaceCheckpoint(recipe.workspace);
541
+ if (!workspaceIsDir && !recoverable) throw refusal(id, `its workspace ${recipe.cwd} is missing.`);
540
542
  if (recipe.sandboxDir !== undefined) {
541
543
  let sandboxIsDir = false;
542
544
  try { sandboxIsDir = statSync(recipe.sandboxDir).isDirectory(); } catch { sandboxIsDir = false; }
543
- if (!sandboxIsDir) throw refusal(id, `its sandbox workspace ${recipe.sandboxDir} is missing.`);
545
+ if (!sandboxIsDir && !recoverable) throw refusal(id, `its sandbox workspace ${recipe.sandboxDir} is missing.`);
544
546
  }
545
547
 
546
548
  const lookup: ConversationLookup = findSavedConversation({
package/docs/usage.md CHANGED
@@ -18,12 +18,13 @@ Set `delegationMode` in the user config described under
18
18
  [Tool scoping](#tool-scoping-allowlist) to `manual`, `adaptive`, or
19
19
  `coordinator` (default `adaptive`). This controls foreground delegation guidance,
20
20
  not child permissions or catalog definitions. `/subagents settings` (or simply
21
- `/subagents`) opens the terminal settings page with mode, concurrent-subagent
22
- cap, tool-wait alert, no-progress alert, and default skill-exposure controls, an
23
- Agents shortcut to `/agents`, and Reset to defaults. The two time values are
24
- edited independently in minutes; `0` turns one alert off. The page uses the same
25
- selected-row and active-cell styling as `/sandbox`, with one editable value
26
- column. Skill exposure cycles between
21
+ `/subagents`) opens the terminal settings page. Delegation mode, the concurrency cap, and
22
+ Git workspace appear together. Run timeout and the two alert intervals come next,
23
+ followed by skills, the Agents catalog, and Reset to defaults. As in
24
+ `/harness-settings`, the cursor marks the active row and its help appears
25
+ below the list. On Run timeout, Space selects **No limit** and Enter edits
26
+ the duration. Each alert has a separate interval in minutes. Enter `0`
27
+ to turn that alert off. Skill exposure cycles between
27
28
  Discover automatically and No skill catalog. The Selected skills row opens the
28
29
  shared searchable checkbox picker, which lists loaded skills by name and
29
30
  description, uses Space to toggle, Enter to apply, and Esc to cancel. Typing
@@ -36,8 +37,8 @@ than being dropped.
36
37
  Edits automatically persist for this session, including across reloads; Escape
37
38
  closes the page without undoing them.
38
39
  Enter edits the cap as a positive whole number or a timing value in minutes;
39
- Escape cancels an unfinished edit. Ctrl+S saves mode, cap, timing alerts, and
40
- skill exposure as defaults. Reset to defaults restores them from the saved
40
+ Escape cancels an unfinished edit. Ctrl+S saves the session’s delegation, workspace,
41
+ timing, and skill settings as defaults. Reset to defaults restores them from the saved
41
42
  config. Sandbox permissions remain in `/sandbox`.
42
43
 
43
44
  Command equivalents also work outside the terminal UI:
@@ -112,7 +113,7 @@ thresholds continue to take precedence for subagent health.
112
113
 
113
114
  | Tool | Blocks? | What it does |
114
115
  |------|---------|--------------|
115
- | `subagent_spawn` | never | Launch a task in a background subagent; returns a run id at once. Params: `prompt`, `name`, `model`, `tools` (allowlist), `exclude_tools`, `skills` ([skill exposure](#skill-exposure)), `sandbox`, `sandbox_dir`, `callback`, `clean`, `cwd`, `git_clone_workspace`, `approve`, `allow_nested`, optional `session_id` or `session_name` (continue a saved conversation), and the [timing](#run-timing-deadline-ceiling-tool-wait-stuck) overrides `deadline_minutes`, `grace_minutes`, `max_minutes`, `tool_wait_minutes`, `stuck_minutes`. |
116
+ | `subagent_spawn` | never | Launch a task in a background subagent; returns a run id at once. Params: `prompt`, `name`, `model`, `tools` (allowlist), `exclude_tools`, `skills` ([skill exposure](#skill-exposure)), `sandbox`, `sandbox_dir`, `callback`, `clean`, `cwd`, `isolation`, `git_clone_workspace`, `recover_in_clone`, `approve`, `allow_nested`, optional `session_id` or `session_name` (continue a saved conversation), and the [timing](#run-timing-deadline-ceiling-tool-wait-stuck) overrides `deadline_minutes`, `grace_minutes`, `max_minutes`, `tool_wait_minutes`, `stuck_minutes`. |
116
117
  | `subagent_spawn_batch` | never | Launch several independent subagents at once. Each job becomes a normal run. Params: `batchName`, `shared` (options applied to every job), `jobs[]` (each needs `prompt`; optional per-job `session_id` or `session_name` continues a saved conversation), `onCapacity` (`reject` or `launch-available`). |
117
118
  | `subagent_settings` | never | Read-only effective settings and capacity snapshot. No parameters. Returns `delegationMode`, `maxConcurrent`, `toolWaitMinutes`, `stuckMinutes`, per-setting `sources`/`timingSources` (`environment`, `session`, `config`, or `default`), a stable settings `revision`, `runningCount`, `pendingCount`, `occupiedSlots`, and `availableSlots`. Timing values already account for the same environment precedence a launch uses. The limit is a ceiling, not a target; spawn admission rechecks live capacity. |
118
119
  | `subagent_list` | never | Compact list for the current folder and descendants across foreground sessions (default 10 rows / 1 KiB page). Each row includes `session_id`. Params: `all` (machine-global search), `limit` (default 10, max 100), `cursor`, `max_bytes` (max 4 KiB), `status` (`running`, `completed`, `failed`, `killed`, `exited`, durable `orphaned`, `lost`). Incident counts are compact; no spend/tool histories. Abandoned launch records are reported separately and are never counted as runs. |
@@ -303,14 +304,15 @@ by the existing harness runtime.
303
304
 
304
305
  ## Run timing (deadline, ceiling, tool wait, stuck)
305
306
 
307
+ When a limit stops the run, `subagent_result` identifies the limit, the last recorded work, open tool calls and the available files. Unfinished checks remain unverified. The same read works with `callback:false`.
308
+
306
309
  Timeout control belongs to the harness, not to the prompt or the skill that
307
310
  launched the run. A time limit written into a prompt is enforced by nothing, and
308
311
  a parent that only notices late tends to kill a child that was still making
309
312
  progress. Every run gets a tool-wait alert, stall detection, and a 60-minute hard
310
313
  timeout by default. Soft deadlines remain opt-in because total runtime does not
311
314
  distinguish a slow agent from a stalled one.
312
- Use Timeout (minutes) in `/subagents settings` to change the session default;
313
- Ctrl+S saves it for future sessions. `0` disables the timeout. Changes apply to
315
+ Choose **Run timeout** in `/subagents settings`. Enter a duration in minutes, type **No limit**, or press Space to select **No limit**. Ctrl+S saves the choice for future sessions. Changes apply to
314
316
  new attempts, not runs already in progress.
315
317
 
316
318
  | Control | Default | What happens |
@@ -437,11 +439,10 @@ given.
437
439
  pending completion, so the caller receives one `killed`/`completed`/`failed`
438
440
  row instead of discovering the outcome by polling `subagent_list()`. A run
439
441
  stopped while the session is shutting down is recovered by the next session.
440
- - **Optional busy steering.** In `/harness-settings`, set **Completions while
441
- busy** to **Steer active run** to receive ordinary completions during
442
+ - **Optional busy steering.** In `/harness-settings`, set **Completion delivery** to **During run** to receive ordinary completions during
442
443
  foreground work. Changes autosave to the current session branch and apply
443
444
  immediately; **Ctrl+S** saves the choice as the user default for future
444
- sessions, including standalone callback packages. **Wait until idle** is the
445
+ sessions, including standalone callback packages. **When idle** is the
445
446
  default. The former `PI_BETTER_CALLBACK_WHILE_BUSY` environment variable is
446
447
  no longer supported. Completions spanning multiple accumulation windows during
447
448
  one tool call stay together until the final active tool ends, then share one
@@ -594,45 +595,30 @@ there but refuse unlink, leaving an empty lock even when status exits zero.
594
595
  The default skips optional index refreshes; it does not disable required locks
595
596
  for `git add` or commits, grant metadata removal, or remove existing locks.
596
597
 
597
- A sandboxed subagent that will mutate Git should set **`git_clone_workspace:true`**
598
- on `subagent_spawn`. The parent prepares a fresh, self-contained Git clone whose
599
- `.git/` directory lives **inside the sandbox writable root**, then runs the child
600
- in that clone.
601
-
602
- Why this matters: a linked Git worktree (created with `git worktree add`) has a
603
- `.git` file that points back to administrative state under the main repository,
604
- typically outside the sandbox directory. A sandbox that only allows writes under
605
- the worktree directory therefore cannot support normal Git producer operations
606
- such as fetch, rebase, commit, and push — the child stalls or fails when Git
607
- tries to write metadata it cannot reach. `git_clone_workspace:true` avoids this
608
- by cloning the repository with a real `.git/` directory inside the writable root.
609
-
610
- The clone uses:
611
-
612
- ```
613
- git clone --reference-if-able <local-reference-repo> --dissociate \
614
- <remote-url> <sandbox-workspace>
615
- ```
616
-
617
- `--reference-if-able` borrows local objects from the parent repository during
618
- setup; `--dissociate` removes the alternates link afterwards, so the clone is
619
- self-contained and safe to delete. The clone source prefers the source
620
- workspace's upstream remote URL (`origin` when set) so the disposable
621
- workspace's `origin` points at the real remote rather than the parent working
622
- tree — pushes therefore target upstream, not the sandboxed parent. The local
623
- repository is used only as a reference (and as a content fallback when no
624
- remote is configured). Source remotes are re-synced after clone. The
625
- checked-out branch/commit matches the source workspace at spawn time.
626
- Repo-local Git identity settings from the source (`user.name`, `user.email`,
627
- and `user.signingkey` when set) are copied into the clone so ordinary commits
628
- work without reconfiguring identity inside the disposable workspace.
629
-
630
- If the source workspace is a linked worktree, the clone is prepared from the
631
- main repository's object database and the requested branch/commit; the child is
632
- never launched into the structurally broken linked-worktree sandbox. If clone
633
- preparation fails, the spawn fails fast with a message explaining that the
634
- linked-worktree Git metadata is outside the sandbox and recommending
635
- `git_clone_workspace:true`.
598
+ ### Git workspaces
599
+
600
+ Single and batch launches give each Git writer an independent checkout of the
601
+ source HEAD. **Git workspace** in `/subagents settings` selects **Clone** (the
602
+ default) or **Worktree** for new launches. Ctrl+S saves the selection. Clone
603
+ keeps Git metadata inside the checkout. Worktree shares the source object store.
604
+ A read-only launch, an explicit `sandbox_dir`, or `isolation:false` can use the
605
+ supplied directory. The explicit `git_clone_workspace:true` option keeps its
606
+ existing branch and upstream selection.
607
+
608
+ `subagent_result` reports the checkout or its saved result. Inspect and apply the
609
+ changes you want. Cleanup verifies an independent copy before reclaiming an idle
610
+ checkout and its Worktree registration. The saved files include the exact Git
611
+ index, working files, ignored outputs and local commits. Identical file contents
612
+ share storage. After cleanup, use `pi-subagents-recover <run-id> <new-directory>`
613
+ to inspect an independent copy, including an unsuccessful attempt. An eligible
614
+ continuation restores its saved workspace and history.
615
+
616
+ When sandbox rules block a Git metadata update in Worktree, the parent can
617
+ review the existing changes or continue with `session_id` and
618
+ `recover_in_clone:true`. The handoff verifies the copy under the conversation's
619
+ writer lease. The next attempt uses the same sandbox policy. If Git has an open
620
+ transaction or recovery cannot verify the copy, inspect the original directory
621
+ reported in the result.
636
622
 
637
623
  The mandatory task guard is independent of optional guardrails extensions.
638
624
  Adding a package to the tool map does not make its tools safe to execute outside
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/failures.ts CHANGED
@@ -1,4 +1,5 @@
1
- import { closeSync, fstatSync, openSync, readSync } from "node:fs";
1
+ import { resultDir } from "./session-store.ts";
2
+ import { existsSync, closeSync, fstatSync, openSync, readSync } from "node:fs";
2
3
  import { join } from "node:path";
3
4
  import { logPathFor, runDir, taskRuntimeTrust } from "./registry.ts";
4
5
  import { activeFailures, actionableFailures, disposeIncidents, failureIdentity, findIncident, formatFailureSummary, formatTerminalFailureFacts, markFailureAttentionDelivered,
@@ -18,7 +19,10 @@ const workerDiagnostics = new SandboxDiagnostics({ context: "worker",
18
19
 
19
20
  export { formatFailureSummary, pendingFailureAttention, markFailureAttentionDelivered, toolOperation };
20
21
  export const failurePath = (id: string) => join(runDir(id), "failures.jsonl");
21
- export const readRunFailures = (id: string): FailureState => readFailureState(failurePath(id));
22
+ export function readRunFailures(id: string): FailureState {
23
+ const retained = !existsSync(runDir(id)) && resultDir(id);
24
+ return readFailureState(retained ? join(retained, "failures.jsonl") : failurePath(id));
25
+ }
22
26
  interface Scan {
23
27
  offset: number; head: string; identity: string; model: IncidentModel; retry?: number;
24
28
  /**
@@ -162,6 +166,10 @@ function exactRuleLeftovers(path: string, prior: FailureState): Set<string> {
162
166
  /** Scan complete source records, independent of the finite progress/transcript tail. */
163
167
  export function collectRunFailures(id: string, cwd: string, terminal = false, assertCurrent: () => void = () => {}): FailureState {
164
168
  assertCurrent();
169
+ if (!existsSync(runDir(id))) {
170
+ const retained = resultDir(id);
171
+ if (retained && existsSync(join(retained, "result.json"))) return readRunFailures(id);
172
+ }
165
173
  const path = failurePath(id);
166
174
  let fd: number;
167
175
  try { fd = openSync(logPathFor(id), "r"); }