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/finalization.ts CHANGED
@@ -29,6 +29,8 @@ import { evaluateParkDisposition, type ParkDisposition } from "./worker-waits.ts
29
29
  import { reconcileRun, type ProcessProbe, type ReconcileResult } from "./health.ts";
30
30
 
31
31
  export interface FinalizeHooks {
32
+ /** Recovery proved the original writer gone; the exit observer was lost. */
33
+ recoveredWriterExit?: boolean;
32
34
  renderWidget?: () => void;
33
35
  notify?: (message: string, level: "info" | "warning") => void;
34
36
  sendMessage?: (
@@ -54,7 +56,7 @@ export function reconcileInterruptedRun(meta: RunMeta, probe: ProcessProbe, now:
54
56
  if ((meta.status === "running" || meta.status === "orphaned") && meta.supervisionInterruptedAt !== undefined && reconciliation.status === "lost") {
55
57
  const run = parseRunForLifecycle(meta.id);
56
58
  if (run.sawEnd && run.unmatchedToolCalls.length === 0) {
57
- return { reconciliation, finalization: finalizeRun(meta.id, null, hooks) };
59
+ return { reconciliation, finalization: finalizeRun(meta.id, null, { ...hooks, recoveredWriterExit: true }) };
58
60
  }
59
61
  }
60
62
  return { reconciliation };
@@ -70,15 +72,15 @@ export function finalizeRun(
70
72
  code: number | null,
71
73
  hooks: FinalizeHooks = {},
72
74
  ): FinalizeResult {
73
- const meta = readMeta(id);
75
+ const initial = readMeta(id);
74
76
  // Coherent child-exit evidence may supersede provisional orphaned/lost
75
77
  // reconciliation, but never overwrites a true terminal record.
76
- if (!meta || !canExitFinalize(meta.status)) return { applied: false };
78
+ if (!initial || !canExitFinalize(initial.status)) return { applied: false };
77
79
 
78
80
  // Lifecycle authority streams the complete NDJSON log; result text stays bounded.
79
81
  const r = parseRunForLifecycle(id);
80
82
  const outcome = classifyChildExit(code, r);
81
- collectRunFailures(id, meta.cwd, true);
83
+ collectRunFailures(id, initial.cwd, true);
82
84
  // A run can now end exit 0 as failed (a final request the model could not
83
85
  // serve), so "not incomplete and has an exit code" no longer means success.
84
86
  const completed = outcome.status === "completed";
@@ -96,40 +98,45 @@ export function finalizeRun(
96
98
  operation: "child-exit", kind: outcome.incomplete ? "incomplete" : "failure",
97
99
  category: "exit", summary }]);
98
100
  }
99
- meta.status = outcome.status;
100
- meta.lifecycleClassification = outcome.classification;
101
- if (outcome.incomplete) meta.failureReason = "incomplete-stream";
102
- meta.exitCode = code;
103
- meta.endedAt = Date.now();
104
101
  // A clean park finishes this ATTEMPT, not the assignment. It is only accepted
105
102
  // with a durable park record whose saved-conversation checkpoint still
106
103
  // verifies; a failed, incoherent or unverifiable exit stays an ordinary exit
107
104
  // and the recorded wait is held for its owner.
108
105
  const park = evaluateParkDisposition({
109
106
  runId: id,
110
- cleanExit: code === 0 && !outcome.incomplete && !outcome.diagnostics.modelError,
107
+ // Preserve a verified staged checkpoint for post-restart park recovery.
108
+ // The coordinator still requires writer-exit and lease-release proof.
109
+ cleanExit: (code === 0 || (code === null && hooks.recoveredWriterExit === true))
110
+ && completed && !outcome.incomplete && !outcome.diagnostics.modelError,
111
111
  });
112
112
  const parked = park.parked && park.record !== undefined;
113
- if (parked && park.record) {
114
- meta.park = park.record;
115
- // The rest of the attempt is complete; the assignment is still waiting.
116
- meta.status = "completed";
117
- }
118
- const callback = meta.callback !== false;
119
- if (callback
120
- && meta.completionCallbackPendingAt === undefined
121
- && meta.completionCallbackSentAt === undefined
122
- && meta.completionCallbackSuppressedAt === undefined) {
123
- if (parked) {
124
- // A parked attempt owes no completion callback: the continuation
125
- // resumes the same conversation and reports the assignment's result.
126
- meta.completionCallbackSuppressedAt = meta.endedAt;
127
- meta.completionCallbackSuppressedReason = `parked on wait ${park.record?.waitId} generation ${park.record?.generation}`;
128
- } else {
129
- 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
+ }
130
135
  }
131
- }
132
- writeMeta(meta);
136
+ return patch;
137
+ } });
138
+ if (!meta) return { applied: false };
139
+ const callback = meta.callback !== false;
133
140
  commitAssignmentTerminal(meta);
134
141
  if (!parked && park.record) {
135
142
  // A park disposition existed but could not be proven on exit. Hold it in
@@ -145,7 +152,7 @@ export function finalizeRun(
145
152
  const verdict = parked
146
153
  ? `parked · waiting for ${park.record?.waitId ?? "its dependency"}`
147
154
  : outcome.verdict;
148
- const el = fmtElapsed(meta.endedAt - meta.startedAt);
155
+ const el = fmtElapsed(endedAt - meta.startedAt);
149
156
  const spend = fmtSpend(r.usage);
150
157
  const humanStat = `${el}${spend ? ` · ${spend}` : ""}`;
151
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
  }