pi-better-server 0.6.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (120) hide show
  1. package/package.json +4 -3
  2. package/scripts/measure-full-runtime/frontend.ts +10 -2
  3. package/scripts/measure-full-runtime.mjs +2 -0
  4. package/src/runtime/background-tools.ts +54 -8
  5. package/src/runtime/background.ts +16 -4
  6. package/src/runtime/domain/background/process.mjs +49 -11
  7. package/src/runtime/domain/background/supervisor/store.mjs +3 -3
  8. package/src/runtime/domain/background/supervisor/supervisor.mjs +9 -3
  9. package/src/runtime/domain/background-service/index.domain.mjs +19 -0
  10. package/src/runtime/domain/background-service/index.ts +19 -0
  11. package/src/runtime/domain/background-service/managed-frontend.domain.mjs +87 -5
  12. package/src/runtime/domain/background-service/managed-frontend.ts +76 -5
  13. package/src/runtime/domain/background-service/navigator-provider.domain.mjs +5 -0
  14. package/src/runtime/domain/background-service/navigator-provider.ts +4 -0
  15. package/src/runtime/domain/background-service/observed-waits.domain.mjs +203 -31
  16. package/src/runtime/domain/background-service/observed-waits.ts +168 -24
  17. package/src/runtime/domain/background-service/process.domain.mjs +49 -11
  18. package/src/runtime/domain/background-service/process.ts +45 -11
  19. package/src/runtime/domain/background-service/review-settings.domain.mjs +16 -0
  20. package/src/runtime/domain/background-service/review-settings.ts +18 -0
  21. package/src/runtime/domain/background-service/runtime.domain.mjs +8 -70
  22. package/src/runtime/domain/background-service/runtime.ts +8 -73
  23. package/src/runtime/domain/background-service/shared-navigator.domain.mjs +55 -28
  24. package/src/runtime/domain/background-service/shared-navigator.ts +47 -26
  25. package/src/runtime/domain/background-service/shared-operation-coordinator/src/outbox.domain.mjs +7 -0
  26. package/src/runtime/domain/background-service/shared-operation-coordinator/src/outbox.ts +9 -0
  27. package/src/runtime/domain/background-service/shared-operation-coordinator/src/store.domain.mjs +5 -1
  28. package/src/runtime/domain/background-service/shared-operation-coordinator/src/store.ts +6 -0
  29. package/src/runtime/domain/background-service/stall.domain.mjs +5 -3
  30. package/src/runtime/domain/background-service/stall.ts +7 -4
  31. package/src/runtime/domain/background-service/supervised-progress.domain.mjs +42 -0
  32. package/src/runtime/domain/background-service/supervised-progress.ts +43 -0
  33. package/src/runtime/domain/background-service/supervisor/README.md +1 -4
  34. package/src/runtime/domain/background-service/supervisor/emit-runner.mjs +1 -0
  35. package/src/runtime/domain/background-service/supervisor/generated/process.mjs +49 -11
  36. package/src/runtime/domain/background-service/supervisor/generated/runner.mjs +47 -4
  37. package/src/runtime/domain/background-service/supervisor/generated/store.mjs +3 -3
  38. package/src/runtime/domain/background-service/supervisor/generated/watch-fingerprint.mjs +69 -0
  39. package/src/runtime/domain/background-service/supervisor/runner.domain.mjs +47 -4
  40. package/src/runtime/domain/background-service/supervisor/runner.ts +38 -3
  41. package/src/runtime/domain/background-service/supervisor/store.domain.mjs +3 -3
  42. package/src/runtime/domain/background-service/supervisor/store.ts +3 -3
  43. package/src/runtime/domain/background-service/supervisor/supervisor.domain.mjs +9 -3
  44. package/src/runtime/domain/background-service/supervisor/supervisor.ts +6 -3
  45. package/src/runtime/domain/background-service/tools.domain.mjs +22 -16
  46. package/src/runtime/domain/background-service/tools.ts +26 -16
  47. package/src/runtime/domain/background-service/types.ts +4 -2
  48. package/src/runtime/domain/background-service/watch-fingerprint.domain.mjs +67 -0
  49. package/src/runtime/domain/background-service/watch-fingerprint.ts +70 -0
  50. package/src/runtime/domain/coordinator/src/outbox.mjs +7 -0
  51. package/src/runtime/domain/coordinator/src/store.mjs +5 -1
  52. package/src/runtime/domain/log-paths.mjs +8 -1
  53. package/src/runtime/domain/parse.mjs +9 -5
  54. package/src/runtime/domain/sandbox-policy/README.md +3 -3
  55. package/src/runtime/domain/sandbox-policy/package.json +1 -1
  56. package/src/runtime/domain/session-store.mjs +7 -0
  57. package/src/runtime/domain/subagents/README.md +12 -10
  58. package/src/runtime/domain/subagents/assignment-outcomes.domain.mjs +2 -5
  59. package/src/runtime/domain/subagents/assignment-outcomes.ts +2 -5
  60. package/src/runtime/domain/subagents/assignment-report.domain.mjs +22 -0
  61. package/src/runtime/domain/subagents/assignment-report.ts +20 -0
  62. package/src/runtime/domain/subagents/batch.mjs +13 -5
  63. package/src/runtime/domain/subagents/cleanup.domain.mjs +11 -2
  64. package/src/runtime/domain/subagents/cleanup.ts +10 -2
  65. package/src/runtime/domain/subagents/config.domain.mjs +5 -0
  66. package/src/runtime/domain/subagents/config.ts +7 -1
  67. package/src/runtime/domain/subagents/continuation.domain.mjs +4 -2
  68. package/src/runtime/domain/subagents/continuation.ts +4 -2
  69. package/src/runtime/domain/subagents/failures.domain.mjs +11 -2
  70. package/src/runtime/domain/subagents/failures.ts +10 -2
  71. package/src/runtime/domain/subagents/finalization.domain.mjs +5 -2
  72. package/src/runtime/domain/subagents/finalization.ts +7 -2
  73. package/src/runtime/domain/subagents/index.domain.mjs +163 -61
  74. package/src/runtime/domain/subagents/index.ts +163 -60
  75. package/src/runtime/domain/subagents/isolated-workspace.domain.mjs +515 -0
  76. package/src/runtime/domain/subagents/isolated-workspace.ts +557 -0
  77. package/src/runtime/domain/subagents/list.mjs +2 -2
  78. package/src/runtime/domain/subagents/managed-launch-client.domain.mjs +22 -5
  79. package/src/runtime/domain/subagents/managed-launch-client.ts +23 -6
  80. package/src/runtime/domain/subagents/output-payload.domain.mjs +24 -9
  81. package/src/runtime/domain/subagents/output-payload.ts +26 -12
  82. package/src/runtime/domain/subagents/package.json +4 -2
  83. package/src/runtime/domain/subagents/parse.domain.mjs +9 -5
  84. package/src/runtime/domain/subagents/parse.ts +10 -5
  85. package/src/runtime/domain/subagents/registry.domain.mjs +24 -18
  86. package/src/runtime/domain/subagents/registry.ts +23 -5
  87. package/src/runtime/domain/subagents/retained-result.domain.mjs +56 -0
  88. package/src/runtime/domain/subagents/retained-result.ts +65 -0
  89. package/src/runtime/domain/subagents/session-selection.domain.mjs +3 -1
  90. package/src/runtime/domain/subagents/session-selection.ts +2 -1
  91. package/src/runtime/domain/subagents/session-store.domain.mjs +7 -0
  92. package/src/runtime/domain/subagents/session-store.ts +9 -0
  93. package/src/runtime/domain/subagents/settings-page.domain.mjs +151 -107
  94. package/src/runtime/domain/subagents/settings-page.ts +147 -108
  95. package/src/runtime/domain/subagents/shared-catalog.domain.mjs +23 -7
  96. package/src/runtime/domain/subagents/shared-catalog.ts +23 -7
  97. package/src/runtime/domain/subagents/shared-navigator.domain.mjs +55 -28
  98. package/src/runtime/domain/subagents/shared-navigator.ts +47 -26
  99. package/src/runtime/domain/subagents/shared-operation-coordinator/src/outbox.domain.mjs +7 -0
  100. package/src/runtime/domain/subagents/shared-operation-coordinator/src/outbox.ts +9 -0
  101. package/src/runtime/domain/subagents/shared-operation-coordinator/src/store.domain.mjs +5 -1
  102. package/src/runtime/domain/subagents/shared-operation-coordinator/src/store.ts +6 -0
  103. package/src/runtime/domain/subagents/task-guard.domain.mjs +14 -1
  104. package/src/runtime/domain/subagents/task-guard.ts +13 -1
  105. package/src/runtime/domain/subagents/task-policy.domain.mjs +2 -1
  106. package/src/runtime/domain/subagents/task-policy.ts +5 -1
  107. package/src/runtime/domain/subagents/tools.domain.mjs +4 -8
  108. package/src/runtime/domain/subagents/tools.ts +4 -7
  109. package/src/runtime/domain/subagents/work-observation.domain.mjs +25 -1
  110. package/src/runtime/domain/subagents/work-observation.ts +20 -1
  111. package/src/runtime/domain/subagents/workspace-files.domain.mjs +103 -0
  112. package/src/runtime/domain/subagents/workspace-files.ts +114 -0
  113. package/src/runtime/domain/subagents/workspace-scope.domain.d.mts +38 -0
  114. package/src/runtime/domain/subagents/workspace-scope.domain.mjs +5 -0
  115. package/src/runtime/domain/subagents/workspace-scope.ts +6 -0
  116. package/src/runtime/domain/subagents/worktree-feedback.domain.mjs +55 -0
  117. package/src/runtime/domain/subagents/worktree-feedback.ts +77 -0
  118. package/src/runtime/read-model.ts +4 -2
  119. package/src/runtime/root.ts +5 -2
  120. package/src/version.ts +1 -1
@@ -8,31 +8,40 @@ import { ownerBindingFromContext, getWorkerOperationService, resolveProductionSc
8
8
  import { processStartToken } from "./registry.ts";
9
9
  import { connectWorkClient } from "./shared-work-client.mjs";
10
10
  import { catalogHostAuthority } from "./catalog-host-admission.ts";
11
- import { openSharedCatalog } from "./shared-catalog.ts";
11
+ import { openSharedCatalog, waitForCatalogSetup } from "./shared-catalog.ts";
12
12
  import { SANDBOX_POLICY_CHANNEL } from "./permission-policy.ts";
13
13
  import { canonicalJson } from "./operation-bridge-types.ts";
14
14
  import { activeChildProviders } from "./config.ts";
15
15
  import { captureLaunchContext } from "./launch-context.ts";
16
16
 
17
17
  /** The fixed Pi host issues execution grants. Catalog registration grants no execution. */
18
- export async function submitManagedLaunch(pi: ExtensionAPI, ctx: ExtensionContext, key: string, tool: string, params: unknown) {
18
+ export async function submitManagedLaunch(pi: ExtensionAPI, ctx: ExtensionContext, key: string, tool: string, params: unknown, signal?: AbortSignal) {
19
+ signal?.throwIfAborted();
19
20
  ctx = captureLaunchContext(ctx);
20
21
  mkdirSync(getAgentDir(), { recursive: true });
21
22
  const root = realpathSync(getAgentDir());
22
- const catalog = await openSharedCatalog(ctx.cwd, root);
23
+ const catalog = await openSharedCatalog(ctx.cwd, root, undefined, undefined, signal);
23
24
  catalog.close();
25
+ signal?.throwIfAborted();
24
26
  const registration = JSON.parse(readFileSync(join(root, "server-registration-v1.json"), "utf8"));
25
27
  if (registration.agentDir !== root || registration.version !== 1) throw new Error("Invalid runtime registration");
26
28
  const directory = join(root, "subagent-launch-admission");
27
29
  mkdirSync(directory, { recursive: true, mode: 0o700 });
28
30
  const stat = lstatSync(directory);
29
31
  if (!stat.isDirectory() || stat.isSymbolicLink() || stat.uid !== process.getuid?.() || (stat.mode & 0o077)) throw new Error("Unsafe launch admission directory");
30
- const client = await connectWorkClient(join(registration.serverDir, "pi-server.sock"), root, ["runtime-subagent-launch-v1"]);
32
+ const client = await connectWorkClient(join(registration.serverDir, "pi-server.sock"), root, ["runtime-subagent-launch-v1"], { signal });
31
33
  const id = randomUUID(), secret = randomBytes(32).toString("hex"), path = join(directory, `${id}.json`);
32
34
  let unsubscribe: unknown;
35
+ const cancel = () => {
36
+ try { rmSync(path, { force: true }); } catch { /* Finally retries cleanup. */ }
37
+ client.close();
38
+ };
39
+ signal?.addEventListener("abort", cancel, { once: true });
33
40
  try {
41
+ signal?.throwIfAborted();
34
42
  const hello = await client.ready;
35
- const catalogAuthority = await catalogHostAuthority(root, ctx.cwd, join(registration.serverDir, "pi-server.sock"));
43
+ const catalogAuthority = await waitForCatalogSetup(catalogHostAuthority(root, ctx.cwd, join(registration.serverDir, "pi-server.sock")), signal);
44
+ signal?.throwIfAborted();
36
45
  const owner = ownerBindingFromContext(ctx);
37
46
  if (!owner.sessionId) throw new Error("Launch requires a registered parent session");
38
47
  // Only branch-local settings travel to the mechanical host, never the transcript.
@@ -55,5 +64,13 @@ export async function submitManagedLaunch(pi: ExtensionAPI, ctx: ExtensionContex
55
64
  finally { checking = false; }
56
65
  });
57
66
  return await client.request("runtime_launch_subagent", { authority: { id, secret } });
58
- } finally { if (typeof unsubscribe === "function") unsubscribe(); client.close(); rmSync(path, { force: true }); }
67
+ } catch (error) {
68
+ signal?.throwIfAborted();
69
+ throw error;
70
+ } finally {
71
+ signal?.removeEventListener("abort", cancel);
72
+ if (typeof unsubscribe === "function") unsubscribe();
73
+ client.close();
74
+ rmSync(path, { force: true });
75
+ }
59
76
  }
@@ -1,4 +1,8 @@
1
1
  // Generated fixed launch domain from packages/pi-better-subagents/output-payload.ts. Do not edit directly.
2
+ import { existsSync } from "node:fs";
3
+ import { readRetainedResult } from "./retained-result.domain.mjs";
4
+ import { worktreeDenialText } from "./worktree-feedback.domain.mjs";
5
+ import { workspaceDelivery } from "./isolated-workspace.domain.mjs";
2
6
  /**
3
7
  * Model-facing subagent payloads (#312).
4
8
  *
@@ -14,7 +18,7 @@ import { assemblePriorityEnvelope, budgetFor, cursorKind, formatUnchangedEvidenc
14
18
  import { collectRunFailures, failurePath } from "./failures.domain.mjs";
15
19
  import { formatLifecycleDiagnostics, formatLostResult, formatOrphanedResult, resolveLifecycle, } from "./lifecycle.domain.mjs";
16
20
  import { parseRun, parseRunForLifecycle } from "./parse.domain.mjs";
17
- import { ABANDONED_LAUNCH_GRACE_MS, belongsToOrigin, effectiveStatus, inspectRunMeta, logPathFor, originOf, } from "./registry.domain.mjs";
21
+ import { ABANDONED_LAUNCH_GRACE_MS, belongsToOrigin, effectiveStatus, inspectRunMeta, runDir, evidenceLogPath, originOf, } from "./registry.domain.mjs";
18
22
  import { actionableFailures, failureJournalFingerprint, fileChangeIdentity, failureRevision, formatIncidentSummary, formatTerminalIncidentSummary, incidentCursorScope, incidentPageHeading, incidentResource as sharedIncidentResource, incidentVerbatimPage, isIncidentCursor, requiresAction, scopedFailures, } from "./shared-failure-observations.domain.mjs";
19
23
  import { fmtElapsed, fmtSpend } from "./widget.domain.mjs";
20
24
  /** Bytes of a continuation answer page left for the incident count line. */
@@ -34,7 +38,11 @@ function isAll(value) {
34
38
  * run directory is missing.
35
39
  */
36
40
  export function loadRunRecord(id) {
37
- return inspectRunMeta(id);
41
+ const live = inspectRunMeta(id);
42
+ if (live.kind === "unreadable" || (live.kind === "ok" && existsSync(runDir(id))))
43
+ return live;
44
+ const retained = readRetainedResult(id);
45
+ return retained ? { kind: "ok", meta: retained, retained: true } : live;
38
46
  }
39
47
  export function isRawMode(mode) {
40
48
  return String(mode ?? "").trim().toLowerCase() === "raw";
@@ -99,7 +107,7 @@ function contentRevisionFor(id, meta) {
99
107
  meta.endedAt ?? null,
100
108
  meta.lifecycleClassification ?? null,
101
109
  meta.failureReason ?? null,
102
- ], logPathFor(id));
110
+ ], evidenceLogPath(id));
103
111
  }
104
112
  function assignmentLabel(meta) {
105
113
  const a = assignmentFor(meta, effectiveStatus(meta));
@@ -125,7 +133,7 @@ function outputIdentity(id, status, elapsed) {
125
133
  }
126
134
  function logGaps(id) {
127
135
  try {
128
- statSync(logPathFor(id));
136
+ statSync(evidenceLogPath(id));
129
137
  return [];
130
138
  }
131
139
  catch (error) {
@@ -270,7 +278,7 @@ function wantsTail(request) {
270
278
  return isAll(request.tail);
271
279
  }
272
280
  function rawPage(ctx, cursor, remaining) {
273
- const page = pageRetainedFile(logPathFor(ctx.id), {
281
+ const page = pageRetainedFile(evidenceLogPath(ctx.id), {
274
282
  cursor,
275
283
  maxBytes: remaining,
276
284
  resource: `raw:${ctx.scopeKey}:${ctx.id}`,
@@ -356,14 +364,14 @@ export function resolveRunAccess(id, request, session) {
356
364
  if (loaded.kind === "unreadable")
357
365
  return loaded;
358
366
  if (isAll(request.all))
359
- return { kind: "ok", meta: loaded.meta };
367
+ return loaded;
360
368
  const resolved = resolveActiveOrigin(session);
361
369
  // Unwired factories (no session provider) exist only for unit tests that
362
370
  // build a tool without the extension. index.ts always passes a provider,
363
371
  // so registered tools never take this branch; see the
364
372
  // "registered tools fail closed" test in subagent_output_budget.test.mjs.
365
373
  if (!resolved.wired)
366
- return { kind: "ok", meta: loaded.meta };
374
+ return loaded;
367
375
  if (!resolved.available || !resolved.origin) {
368
376
  return { kind: "denied", payload: assembleOwnershipGap(id, "unavailable", request) };
369
377
  }
@@ -371,7 +379,7 @@ export function resolveRunAccess(id, request, session) {
371
379
  if (owner !== "own") {
372
380
  return { kind: "denied", payload: assembleOwnershipGap(id, owner, request) };
373
381
  }
374
- return { kind: "ok", meta: loaded.meta };
382
+ return loaded;
375
383
  }
376
384
  function defaultScope() {
377
385
  return listScopeKey(false, undefined, process.pid);
@@ -521,6 +529,13 @@ export function assembleSubagentResult(id, meta, request = {}, healthLine = "",
521
529
  const ctx = callContext(id, meta, request, scopeKey, "subagent_result", true);
522
530
  const exit = meta.exitCode === undefined ? "?" : String(meta.exitCode);
523
531
  const run = parseRunForLifecycle(id);
532
+ const stop = meta.timing?.stopReason;
533
+ const delivery = meta.recipe?.workspace ? workspaceDelivery(meta.recipe.workspace, meta.cwd, Boolean(meta.sandbox), id) : undefined;
534
+ const partial = stop ? `Partial result · stopped: ${stop}. Unfinished checks remain unverified.${run.unmatchedToolCalls.length ? "\nOpen at stop: " + run.unmatchedToolCalls.map(call => call.toolName).join(", ") : ""}${delivery ? "" : "\nWorkspace: " + meta.cwd}` : undefined;
535
+ const denial = meta.sandbox && meta.recipe?.workspace?.mode === "worktree" && run.deniedWorktreeGitOperation
536
+ ? worktreeDenialText(run.deniedWorktreeGitOperation, meta.cwd) : undefined;
537
+ const scratch = meta.taskScratch ? "Task scratch: " + meta.taskScratch : undefined;
538
+ healthLine = joinSections([partial, delivery, denial, scratch, healthLine]) ?? "";
524
539
  const lifecycle = resolveLifecycle(meta, run);
525
540
  const identity = resultIdentity(id, assignmentLabel(meta), exit, elapsedFor(meta), lifecycle.classification);
526
541
  if (wantsIncidentPage(request))
@@ -621,7 +636,7 @@ const listIncidentCache = new Map();
621
636
  const LIST_INCIDENT_CACHE_MAX = 4096;
622
637
  let listIncidentComputations = 0;
623
638
  function listIncidentKey(id, terminal) {
624
- return JSON.stringify([terminal, fileChangeIdentity(logPathFor(id)), failureJournalFingerprint(failurePath(id))]);
639
+ return JSON.stringify([terminal, fileChangeIdentity(evidenceLogPath(id)), failureJournalFingerprint(failurePath(id))]);
625
640
  }
626
641
  export function listIncidentCount(id, cwd, terminal) {
627
642
  const cacheId = `${id}\0${cwd}`;
@@ -1,3 +1,7 @@
1
+ import { existsSync } from "node:fs";
2
+ import { readRetainedResult } from "./retained-result.ts";
3
+ import { worktreeDenialText } from "./worktree-feedback.ts";
4
+ import { workspaceDelivery } from "./isolated-workspace.ts";
1
5
  /**
2
6
  * Model-facing subagent payloads (#312).
3
7
  *
@@ -41,8 +45,8 @@ import {
41
45
  ABANDONED_LAUNCH_GRACE_MS,
42
46
  belongsToOrigin,
43
47
  effectiveStatus,
44
- inspectRunMeta,
45
- logPathFor,
48
+ inspectRunMeta, runDir,
49
+ evidenceLogPath,
46
50
  originOf,
47
51
  type RunCallbackOrigin,
48
52
  type RunMeta,
@@ -93,7 +97,7 @@ export interface PayloadRequest {
93
97
  }
94
98
 
95
99
  export type LoadedRun =
96
- | { kind: "ok"; meta: RunMeta }
100
+ | { kind: "ok"; meta: RunMeta; retained?: true }
97
101
  | { kind: "missing" }
98
102
  | { kind: "unreadable"; detail: string };
99
103
 
@@ -124,7 +128,10 @@ function isAll(value: unknown): boolean {
124
128
  * run directory is missing.
125
129
  */
126
130
  export function loadRunRecord(id: string): LoadedRun {
127
- return inspectRunMeta(id);
131
+ const live = inspectRunMeta(id);
132
+ if (live.kind === "unreadable" || (live.kind === "ok" && existsSync(runDir(id)))) return live;
133
+ const retained = readRetainedResult(id);
134
+ return retained ? { kind: "ok", meta: retained, retained: true } : live;
128
135
  }
129
136
 
130
137
  export function isRawMode(mode: unknown): boolean {
@@ -203,7 +210,7 @@ function contentRevisionFor(id: string, meta: RunMeta): string {
203
210
  meta.endedAt ?? null,
204
211
  meta.lifecycleClassification ?? null,
205
212
  meta.failureReason ?? null,
206
- ], logPathFor(id));
213
+ ], evidenceLogPath(id));
207
214
  }
208
215
 
209
216
  function assignmentLabel(meta: RunMeta): string {
@@ -236,7 +243,7 @@ function outputIdentity(id: string, status: string, elapsed: string): string {
236
243
 
237
244
  function logGaps(id: string): EvidenceGap[] {
238
245
  try {
239
- statSync(logPathFor(id));
246
+ statSync(evidenceLogPath(id));
240
247
  return [];
241
248
  } catch (error) {
242
249
  return [{ kind: "read", detail: error instanceof Error ? error.message : String(error) }];
@@ -414,7 +421,7 @@ function wantsTail(request: PayloadRequest): boolean {
414
421
  }
415
422
 
416
423
  function rawPage(ctx: CallContext, cursor: string | undefined, remaining: number): VerbatimPage {
417
- const page = pageRetainedFile(logPathFor(ctx.id), {
424
+ const page = pageRetainedFile(evidenceLogPath(ctx.id), {
418
425
  cursor,
419
426
  maxBytes: remaining,
420
427
  resource: `raw:${ctx.scopeKey}:${ctx.id}`,
@@ -507,17 +514,17 @@ export function resolveRunAccess(
507
514
  id: string,
508
515
  request: PayloadRequest,
509
516
  session: SubagentToolSession | undefined,
510
- ): { kind: "missing" } | { kind: "unreadable"; detail: string } | { kind: "denied"; payload: string } | { kind: "ok"; meta: RunMeta } {
517
+ ): LoadedRun | { kind: "denied"; payload: string } {
511
518
  const loaded = loadRunRecord(id);
512
519
  if (loaded.kind === "missing") return loaded;
513
520
  if (loaded.kind === "unreadable") return loaded;
514
- if (isAll(request.all)) return { kind: "ok", meta: loaded.meta };
521
+ if (isAll(request.all)) return loaded;
515
522
  const resolved = resolveActiveOrigin(session);
516
523
  // Unwired factories (no session provider) exist only for unit tests that
517
524
  // build a tool without the extension. index.ts always passes a provider,
518
525
  // so registered tools never take this branch; see the
519
526
  // "registered tools fail closed" test in subagent_output_budget.test.mjs.
520
- if (!resolved.wired) return { kind: "ok", meta: loaded.meta };
527
+ if (!resolved.wired) return loaded;
521
528
  if (!resolved.available || !resolved.origin) {
522
529
  return { kind: "denied", payload: assembleOwnershipGap(id, "unavailable", request) };
523
530
  }
@@ -525,7 +532,7 @@ export function resolveRunAccess(
525
532
  if (owner !== "own") {
526
533
  return { kind: "denied", payload: assembleOwnershipGap(id, owner, request) };
527
534
  }
528
- return { kind: "ok", meta: loaded.meta };
535
+ return loaded;
529
536
  }
530
537
 
531
538
  function defaultScope(): string {
@@ -702,6 +709,13 @@ export function assembleSubagentResult(
702
709
  const ctx = callContext(id, meta, request, scopeKey, "subagent_result", true);
703
710
  const exit = meta.exitCode === undefined ? "?" : String(meta.exitCode);
704
711
  const run = parseRunForLifecycle(id);
712
+ const stop = meta.timing?.stopReason;
713
+ const delivery = meta.recipe?.workspace ? workspaceDelivery(meta.recipe.workspace, meta.cwd, Boolean(meta.sandbox), id) : undefined;
714
+ const partial = stop ? `Partial result · stopped: ${stop}. Unfinished checks remain unverified.${run.unmatchedToolCalls.length ? "\nOpen at stop: " + run.unmatchedToolCalls.map(call => call.toolName).join(", ") : ""}${delivery ? "" : "\nWorkspace: " + meta.cwd}` : undefined;
715
+ const denial = meta.sandbox && meta.recipe?.workspace?.mode === "worktree" && run.deniedWorktreeGitOperation
716
+ ? worktreeDenialText(run.deniedWorktreeGitOperation, meta.cwd) : undefined;
717
+ const scratch = meta.taskScratch ? "Task scratch: " + meta.taskScratch : undefined;
718
+ healthLine = joinSections([partial, delivery, denial, scratch, healthLine]) ?? "";
705
719
  const lifecycle = resolveLifecycle(meta, run);
706
720
  const identity = resultIdentity(id, assignmentLabel(meta), exit, elapsedFor(meta), lifecycle.classification);
707
721
  if (wantsIncidentPage(request)) return assembleIncidentPage(ctx, identity);
@@ -814,7 +828,7 @@ const LIST_INCIDENT_CACHE_MAX = 4096;
814
828
  let listIncidentComputations = 0;
815
829
 
816
830
  function listIncidentKey(id: string, terminal: boolean): string {
817
- return JSON.stringify([terminal, fileChangeIdentity(logPathFor(id)), failureJournalFingerprint(failurePath(id))]);
831
+ return JSON.stringify([terminal, fileChangeIdentity(evidenceLogPath(id)), failureJournalFingerprint(failurePath(id))]);
818
832
  }
819
833
 
820
834
  export function listIncidentCount(id: string, cwd: string, terminal: boolean): ListIncidentCount {
@@ -1,12 +1,13 @@
1
1
  {
2
2
  "name": "pi-better-subagents",
3
- "version": "0.36.0",
3
+ "version": "0.37.0",
4
4
  "description": "Pi extension for detached, sandboxed subagent runs that keep the foreground session free.",
5
5
  "license": "MIT",
6
6
  "type": "module",
7
7
  "bin": {
8
8
  "pi-subagents-runtime-status": "./runtime-client/src/runtime/status-cli.mjs",
9
- "pi-agent-catalog": "./agent-catalog.mjs"
9
+ "pi-agent-catalog": "./agent-catalog.mjs",
10
+ "pi-subagents-recover": "./bin/recover-workspace.mjs"
10
11
  },
11
12
  "exports": {
12
13
  "./catalog": "./worker-catalog.ts",
@@ -53,6 +54,7 @@
53
54
  "verify": "npm run typecheck && npm test"
54
55
  },
55
56
  "files": [
57
+ "bin/**",
56
58
  "runtime-client/**",
57
59
  "*.ts",
58
60
  "*.mjs",
@@ -23,7 +23,7 @@
23
23
  import { closeSync, openSync, readSync, statSync, } from "node:fs";
24
24
  import { readBoundedTail, tailTerminalDisplay } from "./shared-log-utils.domain.mjs";
25
25
  import { readAppendedLines, parseLogEvent, logReadMetrics } from "./log-cursor.domain.mjs";
26
- import { logPathFor } from "./registry.domain.mjs";
26
+ import { evidenceLogPath } from "./registry.domain.mjs";
27
27
  const DEFAULT_PARSE_TAIL_BYTES = 32 * 1024 * 1024; // 32 MiB
28
28
  const DEFAULT_RAW_TAIL_BYTES = 256 * 1024; // 256 KiB
29
29
  function envBytes(name, fallback) {
@@ -58,7 +58,7 @@ function fmtBytes(n) {
58
58
  const readTail = readBoundedTail;
59
59
  /** Last `n` terminal display rows of a run's log, or a placeholder if empty/unreadable. */
60
60
  export function tailLog(id, n, maxBytes = maxRawTailBytes()) {
61
- const tail = readTail(logPathFor(id), maxBytes);
61
+ const tail = readTail(evidenceLogPath(id), maxBytes);
62
62
  if (tail.error || tail.text.trim() === "")
63
63
  return "(no output yet)";
64
64
  const out = tailTerminalDisplay(tail.text, n).trim();
@@ -97,7 +97,7 @@ function transcriptContent(msg) {
97
97
  export function readRunTranscript(id, options = {}) {
98
98
  const maxBytes = Math.max(1024, options.maxBytes ?? DEFAULT_TRANSCRIPT_TAIL_BYTES);
99
99
  const maxEntries = Math.max(1, options.maxEntries ?? DEFAULT_TRANSCRIPT_ENTRIES);
100
- const tail = readTail(options.logPath ?? logPathFor(id), maxBytes);
100
+ const tail = readTail(options.logPath ?? evidenceLogPath(id), maxBytes);
101
101
  if (tail.error)
102
102
  return { entries: [], truncated: false, diagnostic: `Log unreadable: ${tail.error}` };
103
103
  const lines = tail.text.split(/\r?\n/);
@@ -724,7 +724,7 @@ function feedStructuralRecordChar(scan, ch) {
724
724
  * only after a record is grammar-valid; unfinished/malformed records fail closed.
725
725
  */
726
726
  export function scanLifecycleEvidence(id) {
727
- const path = logPathFor(id);
727
+ const path = evidenceLogPath(id);
728
728
  let totalBytes = 0;
729
729
  try {
730
730
  totalBytes = statSync(path).size;
@@ -1083,6 +1083,9 @@ function foldParseEvent(state, e) {
1083
1083
  state.openToolCalls.set(toolCallId ?? `anonymous:${state.anonymousToolCall++}`, { id: toolCallId, toolName });
1084
1084
  }
1085
1085
  if (type === "tool_execution_end") {
1086
+ const operation = e.result?.details?.deniedWorktreeGitOperation;
1087
+ if (e.isError && typeof operation === "string" && /^[a-z-]{1,24}$/.test(operation))
1088
+ state.deniedWorktreeGitOperation = operation;
1086
1089
  if (toolCallId) {
1087
1090
  state.openToolCalls.delete(toolCallId);
1088
1091
  }
@@ -1105,7 +1108,7 @@ export function parseRun(id, options = {}) {
1105
1108
  const key = options.logPath ?? id;
1106
1109
  const states = options.states ?? parseStates;
1107
1110
  const previous = states.get(key);
1108
- const path = options.logPath ?? logPathFor(id);
1111
+ const path = options.logPath ?? evidenceLogPath(id);
1109
1112
  let catchUp = false;
1110
1113
  if (options.summaryOnly) {
1111
1114
  try {
@@ -1172,6 +1175,7 @@ export function parseRun(id, options = {}) {
1172
1175
  return {
1173
1176
  finalText: view.finalText,
1174
1177
  lastActivity: view.lastActivity,
1178
+ ...(view.deniedWorktreeGitOperation ? { deniedWorktreeGitOperation: view.deniedWorktreeGitOperation } : {}),
1175
1179
  toolCalls: [...view.toolCalls],
1176
1180
  toolCallCount: view.toolCallCount,
1177
1181
  unmatchedToolCalls: [...view.openToolCalls.values()],
@@ -28,7 +28,7 @@ import {
28
28
  } from "node:fs";
29
29
  import { readBoundedTail, tailTerminalDisplay } from "./shared-log-utils.ts";
30
30
  import { readAppendedLines, parseLogEvent, logReadMetrics, type LogCursor } from "./log-cursor.ts";
31
- import { logPathFor } from "./registry.ts";
31
+ import { evidenceLogPath } from "./registry.ts";
32
32
 
33
33
  interface ContentBlock { type: string; text?: string; thinking?: string; name?: string }
34
34
  interface Cost { total?: number }
@@ -91,7 +91,7 @@ const readTail: (path: string, maxBytes: number) => TailRead = readBoundedTail;
91
91
 
92
92
  /** Last `n` terminal display rows of a run's log, or a placeholder if empty/unreadable. */
93
93
  export function tailLog(id: string, n: number, maxBytes = maxRawTailBytes()): string {
94
- const tail = readTail(logPathFor(id), maxBytes);
94
+ const tail = readTail(evidenceLogPath(id), maxBytes);
95
95
  if (tail.error || tail.text.trim() === "") return "(no output yet)";
96
96
  const out = tailTerminalDisplay(tail.text, n).trim();
97
97
  return out === "" ? "(no output yet)" : out;
@@ -125,6 +125,7 @@ export interface ParsedRun {
125
125
  finalText: string;
126
126
  /** Latest streamed text/thinking, for a live progress peek. */
127
127
  lastActivity: string;
128
+ deniedWorktreeGitOperation?: string;
128
129
  /** Names of tools the child invoked, in order (deduped-adjacent). */
129
130
  toolCalls: string[];
130
131
  /** Every tool execution start seen, including adjacent repeats (opt-in `include: ["tools"]`). */
@@ -187,7 +188,7 @@ export function readRunTranscript(
187
188
  ): RunTranscript {
188
189
  const maxBytes = Math.max(1024, options.maxBytes ?? DEFAULT_TRANSCRIPT_TAIL_BYTES);
189
190
  const maxEntries = Math.max(1, options.maxEntries ?? DEFAULT_TRANSCRIPT_ENTRIES);
190
- const tail = readTail(options.logPath ?? logPathFor(id), maxBytes);
191
+ const tail = readTail(options.logPath ?? evidenceLogPath(id), maxBytes);
191
192
  if (tail.error) return { entries: [], truncated: false, diagnostic: `Log unreadable: ${tail.error}` };
192
193
 
193
194
  const lines = tail.text.split(/\r?\n/);
@@ -927,7 +928,7 @@ function feedStructuralRecordChar(scan: StructuralRecordScan, ch: string): void
927
928
  * only after a record is grammar-valid; unfinished/malformed records fail closed.
928
929
  */
929
930
  export function scanLifecycleEvidence(id: string): LifecycleEvidence {
930
- const path = logPathFor(id);
931
+ const path = evidenceLogPath(id);
931
932
  let totalBytes = 0;
932
933
  try {
933
934
  totalBytes = statSync(path).size;
@@ -1103,6 +1104,7 @@ interface ParseState {
1103
1104
  usage: Usage;
1104
1105
  finalText: string;
1105
1106
  lastActivity: string;
1107
+ deniedWorktreeGitOperation?: string;
1106
1108
  toolCalls: string[];
1107
1109
  toolCallCount: number;
1108
1110
  openToolCalls: Map<string, UnmatchedToolCall>;
@@ -1307,6 +1309,8 @@ function foldParseEvent(state: ParseState, e: Record<string, unknown>): void {
1307
1309
  state.openToolCalls.set(toolCallId ?? `anonymous:${state.anonymousToolCall++}`, { id: toolCallId, toolName });
1308
1310
  }
1309
1311
  if (type === "tool_execution_end") {
1312
+ const operation = (e.result as { details?: { deniedWorktreeGitOperation?: unknown } } | undefined)?.details?.deniedWorktreeGitOperation;
1313
+ if (e.isError && typeof operation === "string" && /^[a-z-]{1,24}$/.test(operation)) state.deniedWorktreeGitOperation = operation;
1310
1314
  if (toolCallId) {
1311
1315
  state.openToolCalls.delete(toolCallId);
1312
1316
  } else if (typeof e.toolName === "string") {
@@ -1328,7 +1332,7 @@ export function parseRun(id: string, options: { logPath?: string; states?: Map<s
1328
1332
  const key = options.logPath ?? id;
1329
1333
  const states = options.states ?? parseStates;
1330
1334
  const previous = states.get(key);
1331
- const path = options.logPath ?? logPathFor(id);
1335
+ const path = options.logPath ?? evidenceLogPath(id);
1332
1336
  let catchUp = false;
1333
1337
  if (options.summaryOnly) {
1334
1338
  try { catchUp = statSync(path).size > 1024 * 1024; } catch { /* read reports errors */ }
@@ -1392,6 +1396,7 @@ export function parseRun(id: string, options: { logPath?: string; states?: Map<s
1392
1396
  return {
1393
1397
  finalText: view.finalText,
1394
1398
  lastActivity: view.lastActivity,
1399
+ ...(view.deniedWorktreeGitOperation ? { deniedWorktreeGitOperation: view.deniedWorktreeGitOperation } : {}),
1395
1400
  toolCalls: [...view.toolCalls],
1396
1401
  toolCallCount: view.toolCallCount,
1397
1402
  unmatchedToolCalls: [...view.openToolCalls.values()],
@@ -1,17 +1,6 @@
1
1
  // Generated fixed launch domain from packages/pi-better-subagents/registry.ts. Do not edit directly.
2
- /**
3
- * Run registry — durable metadata for each spawned subagent.
4
- *
5
- * The authoritative record for every run is a `meta.json` sidecar on disk, so
6
- * `list` / `output` / `result` keep working across foreground turns, `/reload`,
7
- * and even a full pi restart. In-memory state holds only the live exit handlers
8
- * for runs this process spawned.
9
- *
10
- * Catalog launches may attach an optional immutable `catalog` snapshot to that
11
- * same record. Display-label reservations live under `{baseDir()}/labels`
12
- * (see catalog-identity.ts). They are not a second registry, and removing a
13
- * run directory does not delete them.
14
- */
2
+ import { reclaimWorkspace } from "./isolated-workspace.domain.mjs";
3
+ import { retainResult } from "./retained-result.domain.mjs";
15
4
  import { assignmentRetainsEvidence } from "./assignment-outcomes.domain.mjs";
16
5
  import { processStartToken } from "./process-identity.mjs";
17
6
  export { processStartToken } from "./process-identity.mjs";
@@ -22,7 +11,7 @@ import { readFile, readdir } from "node:fs/promises";
22
11
  import { tmpdir } from "node:os";
23
12
  import { basename, dirname, join } from "node:path";
24
13
  import { processExists } from "./spawn.domain.mjs";
25
- import { archiveCompletedAttempt, durableSessionsDir, listArchivedAttempts, readArchivedAttempt, recordArchiveStatusTombstone, } from "./session-store.domain.mjs";
14
+ import { archiveCompletedAttempt, durableSessionsDir, listArchivedAttempts, readArchivedAttempt, recordArchiveStatusTombstone, retainedLogPath, } from "./session-store.domain.mjs";
26
15
  import { failureIdentity, observeFailures, readFailureState } from "./shared-failure-observations.domain.mjs";
27
16
  /**
28
17
  * True when coherent child-exit evidence may finalize a run in this status.
@@ -61,6 +50,12 @@ export function runDir(id) {
61
50
  export function logPathFor(id) {
62
51
  return join(runDir(id), "output.log");
63
52
  }
53
+ export function evidenceLogPath(id) {
54
+ const live = logPathFor(id);
55
+ if (existsSync(live) || existsSync(runDir(id)))
56
+ return live;
57
+ return retainedLogPath(id) ?? live;
58
+ }
64
59
  export function promptPathFor(id) {
65
60
  return join(runDir(id), "prompt.md");
66
61
  }
@@ -1053,14 +1048,24 @@ export function removeMetaArtifacts(meta, options = {}) {
1053
1048
  // conversation's visible last word and could be continued as if this
1054
1049
  // attempt had never happened. A marker that cannot be published retains
1055
1050
  // the run (the throw below): the unsafe direction is deleting both.
1051
+ // Called under the conversation mutation lock by both retention sweeps.
1052
+ if (assignmentRetainsEvidence(meta))
1053
+ throw new Error("Assignment outcome or uncertain writer still retains this run's evidence.");
1054
+ const scratch = meta.taskRuntime && meta.taskScratch && dirname(meta.taskScratch) === realpathSync(tmpdir()) &&
1055
+ /^pi-task-scratch-[a-z0-9]{6}$/i.test(basename(meta.taskScratch)) ? meta.taskScratch : undefined;
1056
+ if (meta.timing?.stopReason || meta.recipe?.workspace || scratch)
1057
+ retainResult(meta, logPathFor(meta.id), scratch);
1058
+ const workspace = meta.recipe?.workspace;
1059
+ if (workspace)
1060
+ reclaimWorkspace(workspace, meta.id);
1056
1061
  recordArchiveStatusTombstone(meta);
1057
1062
  removeRunDirectory(meta.id);
1058
- if (!options.keepWorkspace
1063
+ if (!workspace && !meta.timing?.stopReason && !options.keepWorkspace
1059
1064
  && meta.taskRuntime && /^sa_[a-z0-9]+_[a-z0-9]+$/i.test(meta.id) && meta.cwd === taskWorkspaceDir(meta.id)) {
1060
1065
  rmSync(taskWorkspaceDir(meta.id), { recursive: true, force: true });
1061
1066
  }
1062
- if (meta.taskRuntime && meta.taskScratch && dirname(meta.taskScratch) === realpathSync(tmpdir()) && /^pi-task-scratch-[a-z0-9]{6}$/i.test(basename(meta.taskScratch))) {
1063
- rmSync(meta.taskScratch, { recursive: true, force: true });
1067
+ if (scratch) {
1068
+ rmSync(scratch, { recursive: true, force: true });
1064
1069
  }
1065
1070
  metaCache.delete(meta.id);
1066
1071
  removeIndexEntry(join(baseDir(), "by-parent", String(meta.spawnPid)), meta.id);
@@ -1074,7 +1079,8 @@ export function removeMetaArtifacts(meta, options = {}) {
1074
1079
  }
1075
1080
  return true;
1076
1081
  }
1077
- catch {
1082
+ catch (error) {
1083
+ options.errors?.push(meta.cwd + ": " + String(error));
1078
1084
  return false;
1079
1085
  }
1080
1086
  }
@@ -1,3 +1,5 @@
1
+ import { reclaimWorkspace } from "./isolated-workspace.ts";
2
+ import { retainResult } from "./retained-result.ts";
1
3
  /**
2
4
  * Run registry — durable metadata for each spawned subagent.
3
5
  *
@@ -30,7 +32,7 @@ import {
30
32
  durableSessionsDir,
31
33
  listArchivedAttempts,
32
34
  readArchivedAttempt,
33
- recordArchiveStatusTombstone,
35
+ recordArchiveStatusTombstone, retainedLogPath,
34
36
  } from "./session-store.ts";
35
37
  import { failureIdentity, observeFailures, readFailureState } from "./shared-failure-observations.ts";
36
38
 
@@ -129,6 +131,8 @@ export interface LaunchRecipe {
129
131
  /** Confinement root when the attempt was sandboxed. */
130
132
  sandboxDir?: string;
131
133
  gitCloneWorkspace: boolean;
134
+ workspace?: import("./isolated-workspace.ts").IsolatedWorkspace;
135
+ workspaceAuthority?: Pick<import("./worker-waits.ts").WorkerRunPolicy, "sandbox" | "mandatoryPermissions">;
132
136
  callback: boolean;
133
137
  name?: string;
134
138
  agent?: string;
@@ -327,6 +331,11 @@ export function runDir(id: string): string {
327
331
  export function logPathFor(id: string): string {
328
332
  return join(runDir(id), "output.log");
329
333
  }
334
+ export function evidenceLogPath(id: string): string {
335
+ const live = logPathFor(id);
336
+ if (existsSync(live) || existsSync(runDir(id))) return live;
337
+ return retainedLogPath(id) ?? live;
338
+ }
330
339
  export function promptPathFor(id: string): string {
331
340
  return join(runDir(id), "prompt.md");
332
341
  }
@@ -1338,6 +1347,7 @@ export interface RemoveMetaArtifactsOptions {
1338
1347
  * only its volatile log, metadata, and task scratch are reclaimed.
1339
1348
  */
1340
1349
  keepWorkspace?: boolean;
1350
+ errors?: string[];
1341
1351
  }
1342
1352
 
1343
1353
  export function removeMetaArtifacts(meta: RunMeta, options: RemoveMetaArtifactsOptions = {}): boolean {
@@ -1348,14 +1358,21 @@ export function removeMetaArtifacts(meta: RunMeta, options: RemoveMetaArtifactsO
1348
1358
  // conversation's visible last word and could be continued as if this
1349
1359
  // attempt had never happened. A marker that cannot be published retains
1350
1360
  // the run (the throw below): the unsafe direction is deleting both.
1361
+ // Called under the conversation mutation lock by both retention sweeps.
1362
+ if (assignmentRetainsEvidence(meta)) throw new Error("Assignment outcome or uncertain writer still retains this run's evidence.");
1363
+ const scratch = meta.taskRuntime && meta.taskScratch && dirname(meta.taskScratch) === realpathSync(tmpdir()) &&
1364
+ /^pi-task-scratch-[a-z0-9]{6}$/i.test(basename(meta.taskScratch)) ? meta.taskScratch : undefined;
1365
+ if (meta.timing?.stopReason || meta.recipe?.workspace || scratch) retainResult(meta, logPathFor(meta.id), scratch);
1366
+ const workspace = meta.recipe?.workspace;
1367
+ if (workspace) reclaimWorkspace(workspace, meta.id);
1351
1368
  recordArchiveStatusTombstone(meta);
1352
1369
  removeRunDirectory(meta.id);
1353
- if (!options.keepWorkspace
1370
+ if (!workspace && !meta.timing?.stopReason && !options.keepWorkspace
1354
1371
  && meta.taskRuntime && /^sa_[a-z0-9]+_[a-z0-9]+$/i.test(meta.id) && meta.cwd === taskWorkspaceDir(meta.id)) {
1355
1372
  rmSync(taskWorkspaceDir(meta.id), { recursive: true, force: true });
1356
1373
  }
1357
- if (meta.taskRuntime && meta.taskScratch && dirname(meta.taskScratch) === realpathSync(tmpdir()) && /^pi-task-scratch-[a-z0-9]{6}$/i.test(basename(meta.taskScratch))) {
1358
- rmSync(meta.taskScratch, { recursive: true, force: true });
1374
+ if (scratch) {
1375
+ rmSync(scratch, { recursive: true, force: true });
1359
1376
  }
1360
1377
  metaCache.delete(meta.id);
1361
1378
  removeIndexEntry(join(baseDir(), "by-parent", String(meta.spawnPid)), meta.id);
@@ -1365,7 +1382,8 @@ export function removeMetaArtifacts(meta: RunMeta, options: RemoveMetaArtifactsO
1365
1382
  try { listener(meta); } catch { /* best effort */ }
1366
1383
  }
1367
1384
  return true;
1368
- } catch {
1385
+ } catch (error) {
1386
+ options.errors?.push(meta.cwd + ": " + String(error));
1369
1387
  return false;
1370
1388
  }
1371
1389
  }