pi-better-subagents 0.32.7 → 0.33.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 (50) hide show
  1. package/README.md +13 -0
  2. package/assignment-outcomes.ts +14 -3
  3. package/assignment-projection.mjs +12 -4
  4. package/assignment-report.ts +92 -0
  5. package/child-operations.ts +2 -0
  6. package/child-ownership.ts +1 -1
  7. package/health-observation.ts +9 -4
  8. package/index.ts +142 -77
  9. package/list.mjs +1 -1
  10. package/navigator.mjs +2 -1
  11. package/operation-bridge-types.ts +18 -1
  12. package/output-payload.ts +2 -0
  13. package/package.json +4 -2
  14. package/parse.ts +7 -6
  15. package/registry.ts +4 -2
  16. package/runtime-client/artifacts/darwin-arm64.gz +0 -0
  17. package/runtime-client/artifacts/darwin-arm64.json +1 -0
  18. package/runtime-client/artifacts/darwin-x64.gz +0 -0
  19. package/runtime-client/artifacts/darwin-x64.json +1 -0
  20. package/runtime-client/artifacts/linux-arm64.gz +0 -0
  21. package/runtime-client/artifacts/linux-arm64.json +1 -0
  22. package/runtime-client/artifacts/linux-x64.gz +0 -0
  23. package/runtime-client/artifacts/linux-x64.json +1 -0
  24. package/runtime-client/scripts/private-runtime/format.mjs +90 -0
  25. package/runtime-client/src/daemon-owner.mjs +217 -0
  26. package/runtime-client/src/runtime/client.mjs +130 -0
  27. package/runtime-client/src/runtime/root.mjs +41 -0
  28. package/runtime-client/src/runtime/socket.mjs +9 -0
  29. package/runtime-client/src/runtime/status-cli.mjs +14 -0
  30. package/runtime-client/src/runtime/work-client.mjs +88 -0
  31. package/runtime-client/src/startup/artifact.mjs +76 -0
  32. package/runtime-client/src/startup/install.mjs +184 -0
  33. package/runtime-client/src/startup/managed-types.mjs +1 -0
  34. package/runtime-client/src/startup/runtime.mjs +120 -0
  35. package/session-store.ts +85 -30
  36. package/shared-harness-settings.ts +4 -2
  37. package/shared-log-utils.ts +18 -7
  38. package/shared-navigator.ts +16 -4
  39. package/shared-operation-coordinator/assignment-observation.mjs +63 -3
  40. package/shared-operation-coordinator/index.ts +2 -0
  41. package/shared-operation-coordinator/src/errors.ts +2 -0
  42. package/shared-operation-coordinator/src/schema.ts +20 -0
  43. package/shared-operation-coordinator/src/store.ts +35 -0
  44. package/shared-operation-coordinator/src/task-cancellation.ts +224 -0
  45. package/shared-work-client.d.mts +9 -0
  46. package/shared-work-client.mjs +88 -0
  47. package/tools.ts +39 -2
  48. package/work-observation.ts +177 -0
  49. package/worker-operations-host.ts +3 -0
  50. package/worker-waits.ts +50 -13
package/index.ts CHANGED
@@ -15,6 +15,7 @@ import { createAssignmentProjector } from "./assignment-projection.mjs";
15
15
  import { historicalWaits, attentionRevision, attentionDismissed, dismissAttention } from "./historical-attention.ts";
16
16
  import { registerAssignmentAttempt, commitAssignmentTerminal, readOutcome, receiptOutcome, outcomeTranscriptReceipt, inspectOutcome, createOutcomeHost, closeOutcomeHost, claimOutcome, type AssignmentBinding } from "./assignment-outcomes.ts";
17
17
  import { currentSandboxPermissions } from "./permission-policy.ts";
18
+ import { createToolDescriptor } from "./operation-bridge-types.ts";
18
19
  import { requestResumeAdmission } from "./worker-waits.ts";
19
20
  import { execSync } from "node:child_process";
20
21
  import { writeFileSync, mkdirSync, renameSync, statSync } from "node:fs";
@@ -23,6 +24,9 @@ import * as PiCodingAgent from "@earendil-works/pi-coding-agent";
23
24
  import * as PiTui from "@earendil-works/pi-tui";
24
25
  import { CustomEditor } from "@earendil-works/pi-coding-agent";
25
26
  import { initializeNavigatorPanels } from "./shared-navigator-panels.ts";
27
+ import { workObservation, workObservationFailure, startWorkObservation, stopWorkObservation, observedAssignment, observedList, requestWorkDetail, TERMINAL_NAVIGATOR_RETENTION_MS } from "./work-observation.ts";
28
+ import { withAssignmentObservations } from "./assignment-projection.mjs";
29
+ import { formatNavigatorHealthFacts } from "./health-surface.mjs";
26
30
  import { matchesKey, Key, truncateToWidth, type AutocompleteItem } from "@earendil-works/pi-tui";
27
31
  import { Type } from "@earendil-works/pi-ai";
28
32
  import {
@@ -162,7 +166,6 @@ import {
162
166
  } from "./widget.ts";
163
167
  import {
164
168
  executeNavigatorClose,
165
- buildNavigatorRows,
166
169
  pendingNavigatorPark,
167
170
  buildNavigatorDetail,
168
171
  } from "./navigator.ts";
@@ -482,6 +485,8 @@ function warnInterruptedSubagents(ctx: ExtensionContext, interrupted: RunMeta[],
482
485
  let sessionTornDown = false;
483
486
  let outcomeHost = createOutcomeHost();
484
487
  const outcomeAdmission = new Map<string, () => boolean>();
488
+ const outcomeEnqueuing = new Set<string>();
489
+ let outcomeTicker: ReturnType<typeof setInterval> | undefined;
485
490
 
486
491
  /**
487
492
  * "The rightful conversation is not the active one", not "this notification is
@@ -572,31 +577,69 @@ function enqueueCompletionCallback(pi: ExtensionAPI, id: string): void {
572
577
  }
573
578
 
574
579
  async function enqueueAssignmentOutcome(pi: ExtensionAPI, meta: RunMeta): Promise<void> {
580
+ if (outcomeEnqueuing.has(meta.id)) return;
581
+ outcomeEnqueuing.add(meta.id);
582
+ try { await tryEnqueueAssignmentOutcome(pi, meta); }
583
+ catch (error) {
584
+ try { deferOutcome(meta, `Outcome reconciliation failed: ${String(error)}`); } catch { /* storage remains unavailable; next reconciliation retries */ }
585
+ }
586
+ finally { outcomeEnqueuing.delete(meta.id); }
587
+ }
588
+
589
+ function deferOutcome(meta: RunMeta, reason?: string): void {
590
+ const current = readMeta(meta.id);
591
+ if (!current || current.outcomeDeliveryDeferredReason === reason) return;
592
+ current.outcomeDeliveryDeferredReason = reason;
593
+ writeMeta(current);
594
+ }
595
+
596
+ async function tryEnqueueAssignmentOutcome(pi: ExtensionAPI, meta: RunMeta): Promise<void> {
575
597
  const outcome = readOutcome(meta);
576
598
  const ctx = uiCtx;
577
- if (!outcome || outcome.deliveryReceipt || outcome.disposition || !ctx || meta.callback === false
578
- || typeof ctx.sessionManager?.getBranch !== "function") return;
599
+ if (!outcome || outcome.deliveryReceipt || outcome.disposition) return;
600
+ if (!ctx || meta.callback === false || typeof ctx.sessionManager?.getBranch !== "function") {
601
+ deferOutcome(meta, meta.callback === false ? "Assignment callbacks are disabled."
602
+ : "Recorded parent transcript is unavailable; automatic reconciliation will retry.");
603
+ return;
604
+ }
579
605
  const active = ownerBindingFromContext(ctx);
580
606
  if (active.sessionId !== outcome.recipient.sessionId || active.workspace !== outcome.recipient.workspace
581
- || (outcome.recipient.branchId && !ctx.sessionManager.getBranch().some((entry) => entry.id === outcome.recipient.branchId))) return;
607
+ || (outcome.recipient.branchId && !ctx.sessionManager.getBranch().some((entry) => entry.id === outcome.recipient.branchId))) {
608
+ deferOutcome(meta, "Recorded parent session, workspace or branch is inactive; automatic reconciliation will retry.");
609
+ return;
610
+ }
582
611
  const prior = outcomeTranscriptReceipt(ctx.sessionManager.getBranch(), outcome.eventId);
583
612
  if (prior) { receiptOutcome(meta, prior); return; }
613
+ const deliveryHost = outcomeHost;
584
614
  const gate = await requestResumeAdmission(pi, active, { timeoutMs: 50 });
585
615
  outcomeAdmission.set(outcome.eventId, () => gate.allowed ? gate.isCurrent?.() !== false : !active.goalId && !outcome.recipient.goalId && gate.revision === -1);
586
- if (!gate.allowed && (active.goalId || outcome.recipient.goalId || gate.revision !== -1)) return;
587
- if (!claimOutcome(meta, outcomeHost)) return;
616
+ if (!gate.allowed && (active.goalId || outcome.recipient.goalId || gate.revision !== -1)) {
617
+ deferOutcome(meta, gate.reason ?? "Parent admission refused; automatic reconciliation will retry.");
618
+ return;
619
+ }
620
+ // Admission may yield across a session switch or Goal/workflow change.
621
+ if (sessionTornDown || outcomeHost !== deliveryHost || !uiCtx || callbackSuppressionReason(meta)
622
+ || !outcomeAdmission.get(outcome.eventId)?.()) {
623
+ deferOutcome(meta, "Parent delivery authority changed; automatic reconciliation will retry.");
624
+ return;
625
+ }
626
+ if (!claimOutcome(meta, outcomeHost)) {
627
+ deferOutcome(meta, "Outcome dispatch is owned by another host; automatic reconciliation will retry.");
628
+ return;
629
+ }
630
+ deferOutcome(meta);
588
631
  getCallbackBatcher(pi).enqueue({
589
632
  source: "subagent", id: outcome.eventId, inspectId: meta.id, receiptId: outcome.eventId,
590
633
  label: meta.name ?? meta.id,
591
634
  status: outcome.outcome, outcome: outcome.reason, detailTool: "subagent_result", callback: true,
592
635
  isDelivered: () => Boolean(readOutcome(meta)?.deliveryReceipt),
593
636
  getSuppressionReason: () => {
594
- if (!uiCtx || callbackSuppressionReason(meta)) throw new Error("Recorded parent is inactive; retain outcome.");
637
+ if (outcomeHost !== deliveryHost || !uiCtx || callbackSuppressionReason(meta)) throw new Error("Recorded parent is inactive; retain outcome.");
595
638
  if ((outcome.recipient.branchId && !uiCtx.sessionManager.getBranch().some((entry) => entry.id === outcome.recipient.branchId)) || !outcomeAdmission.get(outcome.eventId)?.()) throw new Error("Parent delivery authority changed; retain outcome.");
596
639
  return undefined;
597
640
  },
598
641
  onDelivered: (at) => {
599
- const entry = outcomeTranscriptReceipt(ctx.sessionManager.getBranch(), outcome.eventId);
642
+ const entry = uiCtx && outcomeTranscriptReceipt(uiCtx.sessionManager.getBranch(), outcome.eventId);
600
643
  if (!entry) throw new Error("Awaiting durable recipient transcript receipt.");
601
644
  receiptOutcome(meta, entry);
602
645
  markCompletionCallbackSent(meta.id, at);
@@ -1201,7 +1244,7 @@ function reconcileHealth(): void {
1201
1244
  // is the human's own interrupted work, not another session's live run, and
1202
1245
  // `finalizeInterruptedRunFromLog` still requires all process evidence to be
1203
1246
  // absent, so a live writer is never touched.
1204
- for (const summary of listMetas()) {
1247
+ for (const summary of listMetas({ includeArchived: false })) {
1205
1248
  if (summary.status !== "running" && summary.status !== "orphaned") continue;
1206
1249
  if (ownedByThisParent(summary) || !ownsInterruptedSupervision(summary)) continue;
1207
1250
  const meta = readMeta(summary.id);
@@ -1353,7 +1396,6 @@ let unregisterSubagentProvider: (() => void) | undefined;
1353
1396
  let acceptanceProviderRef: BackgroundWorkProvider | undefined;
1354
1397
  let acceptanceSpawnToolRef: Parameters<ExtensionAPI["registerTool"]>[0] | undefined;
1355
1398
  let acceptanceStopToolRef: Parameters<ExtensionAPI["registerTool"]>[0] | undefined;
1356
- const TERMINAL_NAVIGATOR_RETENTION_MS = 30_000;
1357
1399
  let mainAgentStartedAt: number | undefined;
1358
1400
  const mainAgentTools = new Map<string, string>();
1359
1401
 
@@ -1368,25 +1410,14 @@ function observeNavigatorHealth(meta: RunMeta, now: number = Date.now()): Health
1368
1410
  return observeWidgetHealth(meta, now, effectiveStatus(meta));
1369
1411
  }
1370
1412
 
1371
- /** Rows for the overlay: visible current-parent runs, newest first (#44 seam). */
1372
- function navigatorRows(visible?: RunMeta[], at?: number) {
1373
- const now = at ?? Date.now();
1374
- return buildNavigatorRows(visible ?? sessionVisibleNavigatorRuns(now), {
1375
- effectiveStatus,
1376
- shortModel,
1377
- fmtElapsed,
1378
- now,
1379
- spendFor: (m: RunMeta) => {
1380
- const snap = spendFor(m.id, now);
1381
- return fmtSpend(snap.usage);
1382
- },
1383
- toolFor: (m: RunMeta) => {
1384
- const snap = spendFor(m.id, now);
1385
- return snap.tool ?? "";
1386
- },
1387
- effortFor: (m: RunMeta) => m.effort,
1388
- healthFor: (m: RunMeta) => observeNavigatorHealth(m, now),
1389
- });
1413
+ /** Keep expiry and formatting on one observation, only for this refresh. */
1414
+ function createNavigatorProjector() {
1415
+ const project = createAssignmentProjector();
1416
+ const results = new Map<string, ReturnType<typeof project>>();
1417
+ return (meta: RunMeta, status: string = meta.status) => {
1418
+ if (!results.has(meta.id)) results.set(meta.id, project(meta, status));
1419
+ return results.get(meta.id)!;
1420
+ };
1390
1421
  }
1391
1422
 
1392
1423
  /** Runs that should advertise/open the left-arrow navigator affordance. */
@@ -1395,8 +1426,12 @@ function navigatorRunningRuns(): RunMeta[] {
1395
1426
  return sessionVisibleNavigatorRuns(Date.now(), project).filter((m) => ["running", "waiting"].includes(project(m, effectiveStatus(m)).state));
1396
1427
  }
1397
1428
 
1429
+ const pendingNavigatorDismissals = new Set<string>();
1430
+
1398
1431
  function navigatorRunningCount(): number {
1399
- return navigatorRunningRuns().length;
1432
+ const snapshot = workObservation();
1433
+ return (snapshot?.rows.filter((row: any) => !pendingNavigatorDismissals.has(row.meta.id) && !row.meta.dismissedAt && ["running", "waiting"].includes(row.assignment.state)).length ?? 0) +
1434
+ (!snapshot || snapshot.status !== "ready" ? 1 : 0);
1400
1435
  }
1401
1436
 
1402
1437
  /**
@@ -1453,6 +1488,8 @@ function navigatorCloseRun(id: string) {
1453
1488
  .then((cancelled) => {
1454
1489
  if (!cancelled) throw new Error("The pending wait changed; inspect it again.");
1455
1490
  dismissRun(id);
1491
+ pendingNavigatorDismissals.add(id);
1492
+ refreshBackgroundWorkNavigator(uiCtx);
1456
1493
  uiCtx?.ui.notify(`Cancelled the pending wait of ${id}. Writer termination may remain unproven.`, "info");
1457
1494
  })
1458
1495
  .catch((error) => uiCtx?.ui.notify(`Cancellation failed for ${id}: ${String(error)}. The wait remains available for inspection and retry.`, "warning"));
@@ -1465,6 +1502,7 @@ function navigatorCloseRun(id: string) {
1465
1502
  stopRun,
1466
1503
  dismissRun,
1467
1504
  });
1505
+ if (outcome.action === "dismissed" || outcome.action === "stopped-and-dismissed") pendingNavigatorDismissals.add(id);
1468
1506
  // A closed row is off the hot path: release its caches and retained events.
1469
1507
  spendCache.delete(id);
1470
1508
  healthLogCache.delete(id);
@@ -1494,39 +1532,29 @@ function statusTone(status: string): BackgroundWorkRow["statusTone"] {
1494
1532
  }
1495
1533
 
1496
1534
  function subagentWorkRows(now: number): BackgroundWorkRow[] {
1497
- // One registry scan per rebuild: both the start times and the rows below are
1498
- // built from this snapshot.
1499
- const visible = sessionVisibleNavigatorRuns(now);
1500
- const metaById = new Map(visible.map((m) => [m.id, m]));
1501
- return navigatorRows(visible, now).map((row) => {
1502
- const bits = [];
1503
- if (row.model) bits.push(row.effort ? `${row.model} ${row.effort}` : row.model);
1504
- if (row.tool) bits.push(row.tool);
1505
- if (row.spend) bits.push(row.spend);
1506
- return {
1507
- providerId: "subagents",
1508
- id: row.id,
1509
- name: row.name,
1510
- model: row.model,
1511
- effort: row.effort,
1512
- tool: row.tool,
1513
- tokens: row.spend,
1514
- status: row.status,
1515
- statusTone: statusTone(row.status),
1516
- kind: "subagent",
1517
- elapsed: row.elapsed,
1518
- primary: bits.join(" · ") || "subagent run",
1519
- facts: row.healthFacts,
1520
- sortStartedAt: metaById.get(row.id)?.startedAt ?? now,
1521
- expiresAt: (() => {
1522
- const meta = metaById.get(row.id);
1523
- const endedAt = meta?.endedAt ?? meta?.lostAt;
1524
- return meta && isTerminalNavigatorStatus(row.status) && typeof endedAt === "number"
1525
- ? endedAt + TERMINAL_NAVIGATOR_RETENTION_MS
1526
- : undefined;
1527
- })(),
1528
- };
1535
+ const snapshot = workObservation();
1536
+ const sourceRows = snapshot?.rows ?? [];
1537
+ if (snapshot?.status === "ready" && pendingNavigatorDismissals.size) {
1538
+ // A successful local dismissal is already durable; hide its old observation until acknowledged.
1539
+ const undismissed = new Set(sourceRows.filter((row: any) => !row.meta.dismissedAt).map((row: any) => row.meta.id));
1540
+ for (const id of pendingNavigatorDismissals) if (!undismissed.has(id)) pendingNavigatorDismissals.delete(id);
1541
+ }
1542
+ const rows: BackgroundWorkRow[] = sourceRows.filter((row: any) => !pendingNavigatorDismissals.has(row.meta.id) && !row.meta.dismissedAt &&
1543
+ (["running", "waiting"].includes(row.assignment.state) || typeof (row.meta.endedAt ?? row.meta.lostAt) !== "number" ||
1544
+ now - (row.meta.endedAt ?? row.meta.lostAt) < TERMINAL_NAVIGATOR_RETENTION_MS)).map((row: any) => {
1545
+ const meta = row.meta;
1546
+ const health = row.health ? observeRunHealth({ ...row.health, status: row.assignment.processStatus === "exited" ? meta.status : row.assignment.processStatus, now, startedAt: meta.startedAt }) : undefined;
1547
+ const terminal = !["running", "waiting"].includes(row.assignment.state);
1548
+ return { providerId: "subagents", id: meta.id, name: meta.name || meta.id,
1549
+ model: shortModel(meta.model), effort: meta.effort, status: row.assignment.state,
1550
+ tool: row.display?.tool, tokens: row.display?.spend,
1551
+ statusTone: statusTone(row.assignment.state), kind: "subagent", elapsed: fmtElapsed((meta.endedAt ?? now) - meta.startedAt),
1552
+ primary: [shortModel(meta.model), meta.effort, row.display?.tool, row.display?.spend].filter(Boolean).join(" ") || "subagent run", facts: formatNavigatorHealthFacts(health), sortStartedAt: meta.startedAt,
1553
+ expiresAt: terminal && typeof meta.endedAt === "number" ? meta.endedAt + TERMINAL_NAVIGATOR_RETENTION_MS : undefined };
1529
1554
  });
1555
+ if (!snapshot || snapshot.status !== "ready") rows.unshift({ providerId: "subagents", id: "runtime-observation", name: "Subagents",
1556
+ status: snapshot?.status ?? "degraded", statusTone: "warning", kind: "observation", elapsed: "", primary: workObservationFailure(), sortStartedAt: now });
1557
+ return rows;
1530
1558
  }
1531
1559
 
1532
1560
  const DELEGATION_BLURB: Record<DelegationMode, string> = {
@@ -1603,12 +1631,19 @@ function mainAgentWorkDetail(now: number): BackgroundWorkDetail {
1603
1631
 
1604
1632
  function subagentWorkDetail(id: string, now: number, options?: { logTailLines?: number }): BackgroundWorkDetail | null {
1605
1633
  if (id === "main") return mainAgentWorkDetail(now);
1606
- const detail = navigatorDetail(id, now);
1634
+ const row = requestWorkDetail(id);
1635
+ if (!row?.detail) return { providerId: "subagents", id, title: id, status: row?.observationError ? "degraded" : "rebuilding", statusTone: "warning", metadata: [], evidence: { label: "observation", text: row?.observationError ?? workObservationFailure() } };
1636
+ const health = row.health ? observeRunHealth({ ...row.health, status: row.assignment.processStatus === "exited" ? row.meta.status : row.assignment.processStatus, now, startedAt: row.meta.startedAt }) : undefined;
1637
+ const detail = withAssignmentObservations([row], () => buildNavigatorDetail(id, {
1638
+ readMeta: () => row.meta, effectiveStatus: () => row.assignment.processStatus, parseRun: () => row.detail.parsed,
1639
+ shortModel, fmtElapsed, fmtSpend, now, effortFor: (meta: RunMeta) => meta.effort, healthFor: () => health,
1640
+ }));
1607
1641
  if (!detail) return null;
1608
1642
  void options;
1609
- const transcript = readRunTranscript(id);
1643
+ const transcript = row.detail.transcript;
1610
1644
  const metadata = [
1611
1645
  { label: "provider", value: "Subagents" },
1646
+ ...(row.observationError ? [{ label: "observation", value: row.observationError }] : []),
1612
1647
  { label: "id", value: detail.id },
1613
1648
  ...(detail.role ? [{ label: "role", value: String(detail.role) }] : []),
1614
1649
  { label: "model", value: detail.effort ? `${detail.model} · effort ${detail.effort}` : detail.model },
@@ -1701,7 +1736,7 @@ function ensureSubagentProvider(): void {
1701
1736
  label: "Subagents",
1702
1737
  priority: 10,
1703
1738
  visibleCount: () => navigatorRunningCount(),
1704
- showSection: (rows) => rows.some((row) => row.status === "running" || ["parking", "waiting", "ready", "resuming", "held"].includes(row.status)),
1739
+ showSection: (rows) => rows.some((row) => row.status === "running" || ["parking", "waiting", "ready", "resuming", "held", "degraded", "rebuilding"].includes(row.status)),
1705
1740
  parentRow: (now) => mainAgentWorkRow(now),
1706
1741
  listRows: (now) => subagentWorkRows(now),
1707
1742
  detail: (id, now, options) => subagentWorkDetail(id, now, options),
@@ -1890,7 +1925,7 @@ function ownsInterruptedSupervision(summary: Pick<RunMeta, "spawnPid" | "spawnPi
1890
1925
  /** True while an interrupted record still needs this process's supervision loop. */
1891
1926
  function needsInterruptedSupervision(): boolean {
1892
1927
  try {
1893
- for (const summary of listMetas()) {
1928
+ for (const summary of listMetas({ includeArchived: false })) {
1894
1929
  if (summary.status !== "running" && summary.status !== "orphaned") continue;
1895
1930
  if (ownsInterruptedSupervision(summary)) return true;
1896
1931
  }
@@ -1977,8 +2012,14 @@ function sameLaunchPath(left: unknown, right: string | undefined): boolean {
1977
2012
  try { return canonicalizePath(left) === canonicalizePath(right); } catch { return false; }
1978
2013
  }
1979
2014
 
2015
+ /** Reporting is injected by the supervisor, not part of the caller's tool intent.
2016
+ * Older recipes included it; remove only this internal name when reading them. */
2017
+ function callerLaunchTools(tools: string): string {
2018
+ return normalizeTools(tools).split(",").filter((name) => name !== "report_assignment_result").join(",");
2019
+ }
2020
+
1980
2021
  function sameLaunchTools(left: unknown, right: string): boolean {
1981
- return typeof left === "string" && normalizeTools(left) === normalizeTools(right);
2022
+ return typeof left === "string" && callerLaunchTools(left) === callerLaunchTools(right);
1982
2023
  }
1983
2024
 
1984
2025
  /**
@@ -2787,7 +2828,7 @@ export default function (pi: ExtensionAPI) {
2787
2828
 
2788
2829
  // A continuation keeps the recipe's launch intent; only current
2789
2830
  // permission-driven adjustments are re-derived from it.
2790
- const requestedTools = resume ? resume.recipe.tools : p.tools;
2831
+ const requestedTools = resume ? callerLaunchTools(resume.recipe.tools) : p.tools;
2791
2832
  const requestedExcludeTools = resume ? resume.recipe.excludeTools ?? "" : p.exclude_tools ?? "";
2792
2833
  const clean = resume ? resume.recipe.clean : p.clean === true;
2793
2834
  const allowNested = resume ? resume.recipe.allowNested : p.allow_nested === true;
@@ -2829,7 +2870,22 @@ export default function (pi: ExtensionAPI) {
2829
2870
  explicitTools: requestedTools !== undefined,
2830
2871
  productionSchemas: new Set(productionBridgeSchemas.schemas.keys()),
2831
2872
  });
2832
- const bridgeEnabled = workerOperations.available && bridgePlan.tools.length > 0;
2873
+ const parent = ownerBindingFromContext(ctx);
2874
+ const assignment: AssignmentBinding | undefined = internal?.resumeWait && resume?.prior.assignment
2875
+ ? resume.prior.assignment
2876
+ : parent.sessionId && typeof ctx.sessionManager?.getBranch === "function" ? { version: 1, assignmentId: id,
2877
+ owner: { kind: "worker-conversation", sessionId, workspace: cwd, branchId: parent.branchId, goalId: parent.goalId },
2878
+ recipient: { kind: "parent-session", ...parent } } : undefined;
2879
+ if (!workerOperations.available) {
2880
+ bridgePlan.tools = [];
2881
+ bridgePlan.capabilities = { background: { spawn: false, watch: false, status: false, log: false }, wait: false, acknowledge: false, parking: false };
2882
+ }
2883
+ if (assignment && !requestedExcludes.has("report_assignment_result")) {
2884
+ bridgePlan.tools = [...bridgePlan.tools, "report_assignment_result"];
2885
+ bridgePlan.capabilities = { ...bridgePlan.capabilities, reportAssignment: true };
2886
+ productionBridgeSchemas.schemas.set("report_assignment_result", createToolDescriptor("report_assignment_result"));
2887
+ }
2888
+ const bridgeEnabled = bridgePlan.tools.length > 0;
2833
2889
  if (bridgeEnabled) {
2834
2890
  allow = [...new Set([...allow.split(",").filter(Boolean), ...bridgePlan.tools])].join(",");
2835
2891
  }
@@ -3057,6 +3113,7 @@ export default function (pi: ExtensionAPI) {
3057
3113
  // already captured. A resume requires the bridge: without it the
3058
3114
  // attempt could not read evidence or acknowledge its wait.
3059
3115
  let workerBridge: { env: Record<string, string>; policy: ReturnType<typeof captureWorkerPolicy>; authorityReference: string } | undefined;
3116
+ if (assignment) registerAssignmentAttempt(assignment, id);
3060
3117
  if (bridgeEnabled) {
3061
3118
  const workerPolicy = captureWorkerPolicy({
3062
3119
  sandbox: sandboxEnabled,
@@ -3079,6 +3136,7 @@ export default function (pi: ExtensionAPI) {
3079
3136
  const owner = internal?.parkOwner ?? ownerBindingFromContext(ctx);
3080
3137
  try {
3081
3138
  const handle = await workerOperations.register({
3139
+ assignment,
3082
3140
  runId: id,
3083
3141
  conversationId: sessionId,
3084
3142
  workspace: cwd,
@@ -3116,14 +3174,7 @@ export default function (pi: ExtensionAPI) {
3116
3174
  // await between it and the spawn, so a cancellation or parent change
3117
3175
  // cannot hide inside a final asynchronous window.
3118
3176
  if (internal?.resumeWait && !resume?.prior.assignment) throw new PreSpawnResumeError("This legacy park has no verified assignment outcome recipient; refusing continuation on an unsupported binding.");
3119
- const parent = ownerBindingFromContext(ctx);
3120
- const assignment: AssignmentBinding | undefined = internal?.resumeWait && resume?.prior.assignment
3121
- ? resume.prior.assignment
3122
- : parent.sessionId && typeof ctx.sessionManager?.getBranch === "function" ? { version: 1, assignmentId: id,
3123
- owner: { kind: "worker-conversation", sessionId, workspace: cwd, branchId: parent.branchId, goalId: parent.goalId },
3124
- recipient: { kind: "parent-session", ...parent } } : undefined;
3125
3177
  if (!assignment && bridgeEnabled) throw new Error("Durable assignment outcomes require a recorded parent session and transcript capability.");
3126
- if (assignment) registerAssignmentAttempt(assignment, id);
3127
3178
  if (internal?.resumeWait) {
3128
3179
  const captured = resume?.prior.operations?.policy;
3129
3180
  const currentSandbox = taskRuntime ? {
@@ -3158,7 +3209,7 @@ export default function (pi: ExtensionAPI) {
3158
3209
  cwd,
3159
3210
  model,
3160
3211
  effort: thinking,
3161
- tools: allow,
3212
+ tools: callerLaunchTools(allow),
3162
3213
  excludeTools: requestedExcludes.size ? [...requestedExcludes].join(",") : undefined,
3163
3214
  skills: skills.mode === "inherit" ? undefined : [...skills.paths],
3164
3215
  clean,
@@ -3974,6 +4025,8 @@ export default function (pi: ExtensionAPI) {
3974
4025
  // The foreground origin from session_start; otherwise the calling context's
3975
4026
  // own session. An unreadable session id stays unavailable (never cwd-wide).
3976
4027
  const toolSession = {
4028
+ observeAssignment: observedAssignment,
4029
+ observeList: observedList,
3977
4030
  inspectOutcome: (meta: RunMeta, params: Record<string, unknown>, callCtx?: unknown) => {
3978
4031
  if (params.disposition !== undefined && params.disposition !== "consumed" && params.disposition !== "dismissed") throw new Error("Outcome disposition must be consumed or dismissed.");
3979
4032
  if (!readOutcome(meta)) {
@@ -4273,6 +4326,7 @@ export default function (pi: ExtensionAPI) {
4273
4326
  // switch), so the previous session's teardown no longer applies: the
4274
4327
  // replacing session owns this instance's supervision loops (#625).
4275
4328
  sessionTornDown = false;
4329
+ pendingNavigatorDismissals.clear();
4276
4330
  outcomeHost = createOutcomeHost();
4277
4331
  setCallbackBatchContext(pi, ctx);
4278
4332
  agentSessionSettings.restore(ctx);
@@ -4283,7 +4337,13 @@ export default function (pi: ExtensionAPI) {
4283
4337
  catch { mainAgentStartedAt = undefined; }
4284
4338
  mainAgentTools.clear();
4285
4339
  activeCallbackOrigin = callbackOriginFromContext(ctx);
4340
+ if (activeCallbackOrigin) await startWorkObservation(PiCodingAgent.getAgentDir(), activeCallbackOrigin, () => refreshBackgroundWorkNavigator(ctx));
4286
4341
  recoverCompletionCallbacks(pi);
4342
+ // Admission can defer before batcher enqueue, even after the last child
4343
+ // exits. Keep reconciliation independent of the live-run health ticker.
4344
+ if (outcomeTicker) clearInterval(outcomeTicker);
4345
+ outcomeTicker = setInterval(() => recoverAssignmentOutcomes(pi), 1000);
4346
+ outcomeTicker.unref?.();
4287
4347
  // Reload / session switch hardening (#48):
4288
4348
  // - Drop any leftover overlay timers/confirm state from a prior session
4289
4349
  // (defensive if the host skipped session_shutdown before re-start).
@@ -4332,6 +4392,11 @@ export default function (pi: ExtensionAPI) {
4332
4392
 
4333
4393
  // Tear down the timer and clear the widget when the session ends.
4334
4394
  pi.on("session_shutdown", async (event, ctx) => {
4395
+ stopWorkObservation();
4396
+ pendingNavigatorDismissals.clear();
4397
+ if (outcomeTicker) clearInterval(outcomeTicker);
4398
+ outcomeTicker = undefined;
4399
+ outcomeAdmission.clear();
4335
4400
  closeOutcomeHost(outcomeHost);
4336
4401
  if (typeof unsubscribeOutcomeWorkflow === "function") unsubscribeOutcomeWorkflow();
4337
4402
  if (typeof unsubscribeSettingsRequest === "function") unsubscribeSettingsRequest();
package/list.mjs CHANGED
@@ -106,7 +106,7 @@ export function formatSubagentListRow(meta, p) {
106
106
  : "";
107
107
  const assignment = p.assignment ?? assignmentFor(meta, p.processStatus ?? meta.status);
108
108
  const diagnostic = meta.operations || meta.park || status !== assignment.processStatus || status === "failed"
109
- ? `\n ${assignmentDiagnostic(assignment)}` : "";
109
+ ? `\n ${assignmentDiagnostic(assignment, { includeEvidence: !p.compact })}` : "";
110
110
  return `• ${name}${meta.id} [${status}] session_id=${meta.sessionId ?? "unavailable"} ${bounded(meta.model ?? "?", 60)} ${elapsed}${health}${timing}${batch}${failure}\n ${promptPreview(meta)} · r${assignment.revision}${diagnostic}`;
111
111
  }
112
112
 
package/navigator.mjs CHANGED
@@ -181,6 +181,7 @@ export function isNavigatorUiAvailable(ctx) {
181
181
  * @param {(m: object) => string} [deps.toolFor] - current/used tool label or ""
182
182
  * @param {(m: object) => string|undefined} [deps.effortFor] - model effort when available
183
183
  * @param {(m: object) => object|undefined} [deps.healthFor] - #66 HealthObservation
184
+ * @param {(m: object, status: string) => object} [deps.project] - refresh-local assignment results shared with expiry filtering
184
185
  * @param {number} [deps.now]
185
186
  */
186
187
  export function pendingNavigatorPark(meta) {
@@ -190,7 +191,7 @@ export function pendingNavigatorPark(meta) {
190
191
 
191
192
  export function buildNavigatorRows(metas, deps) {
192
193
  const now = deps.now ?? Date.now();
193
- const project = createAssignmentProjector();
194
+ const project = deps.project ?? createAssignmentProjector();
194
195
  return metas.map((m) => {
195
196
  const assignment = project(m, deps.effectiveStatus(m));
196
197
  const status = assignment.state;
@@ -72,6 +72,7 @@ export const OPERATION_BRIDGE_TOOL_NAMES = [
72
72
  "bg_task_log",
73
73
  "wait_for_operations",
74
74
  "acknowledge_operation_result",
75
+ "report_assignment_result",
75
76
  ] as const;
76
77
 
77
78
  export type OperationBridgeToolName = (typeof OPERATION_BRIDGE_TOOL_NAMES)[number];
@@ -102,6 +103,7 @@ export const OPERATION_BRIDGE_METHODS: readonly OperationBridgeMethod[] = [
102
103
  export type JsonRecord = Record<string, unknown>;
103
104
 
104
105
  export interface OperationBridgeCapabilities {
106
+ reportAssignment?: boolean;
105
107
  background: {
106
108
  spawn: boolean;
107
109
  watch: boolean;
@@ -628,6 +630,17 @@ const HANDSHAKE_SCHEMA: JsonRecord = object({
628
630
 
629
631
  export function canonicalToolSchema(name: OperationBridgeToolName): JsonRecord {
630
632
  switch (name) {
633
+ case "report_assignment_result": return {
634
+ type: "object", additionalProperties: false, required: ["status", "reason", "evidence"],
635
+ properties: {
636
+ status: { type: "string", enum: ["complete", "incomplete"] },
637
+ reason: { type: "string", minLength: 1, maxLength: 2048 },
638
+ evidence: { type: "array", minItems: 1, maxItems: 4, items: {
639
+ type: "object", additionalProperties: false, required: ["path", "explanation"],
640
+ properties: { path: { type: "string", minLength: 1, maxLength: 1024 }, explanation: { type: "string", minLength: 1, maxLength: 1024 } },
641
+ } },
642
+ },
643
+ };
631
644
  case "wait_for_operations": return WAIT_FOR_OPERATIONS_SCHEMA;
632
645
  case "acknowledge_operation_result": return ACKNOWLEDGE_OPERATION_RESULT_SCHEMA;
633
646
  default: return LOOSE_BACKGROUND_SCHEMA;
@@ -635,6 +648,7 @@ export function canonicalToolSchema(name: OperationBridgeToolName): JsonRecord {
635
648
  }
636
649
 
637
650
  const TOOL_LABELS: Record<OperationBridgeToolName, string> = {
651
+ report_assignment_result: "Report Assignment Result",
638
652
  bg_task_spawn: "BG Spawn",
639
653
  bg_task_watch: "BG Watch",
640
654
  bg_task_status: "BG Status",
@@ -644,6 +658,7 @@ const TOOL_LABELS: Record<OperationBridgeToolName, string> = {
644
658
  };
645
659
 
646
660
  const TOOL_DESCRIPTIONS: Record<OperationBridgeToolName, string> = {
661
+ report_assignment_result: "Record your complete or incomplete assignment judgment with retained workspace artifact evidence before your final answer. Does not terminalize the assignment, interpret waits or record parent acceptance. Report once; identical retries are allowed, conflicting reports are refused.",
647
662
  bg_task_spawn: "Start one long-running background operation through the trusted parent supervisor. Returns immediately. The operation is owned by the parent, not by this worker process.",
648
663
  bg_task_watch: "Start one background command watch through the trusted parent supervisor. Returns immediately. The operation is owned by the parent, not by this worker process.",
649
664
  bg_task_status: "Inspect one operation owned by this worker conversation. Only task ids accepted by the parent ownership check are readable.",
@@ -664,7 +679,7 @@ export function createToolDescriptor(
664
679
  ): OperationToolDescriptor {
665
680
  // The wait/acknowledge schemas are fixed here; a parent descriptor may not
666
681
  // loosen the contract that decides when a worker parks or consumes evidence.
667
- const parameters = name === WAIT_OPERATIONS_TOOL || name === ACKNOWLEDGE_OPERATION_TOOL
682
+ const parameters = name === WAIT_OPERATIONS_TOOL || name === ACKNOWLEDGE_OPERATION_TOOL || name === "report_assignment_result"
668
683
  ? canonicalToolSchema(name)
669
684
  : (overrides.parameters ?? canonicalToolSchema(name));
670
685
  return deepFreeze({
@@ -679,6 +694,7 @@ export function createToolDescriptor(
679
694
 
680
695
  export function descriptorsForCapabilities(capabilities: OperationBridgeCapabilities): OperationToolDescriptor[] {
681
696
  return deepFreeze([
697
+ ...(capabilities.reportAssignment === true ? [createToolDescriptor("report_assignment_result")] : []),
682
698
  ...(capabilities.background.spawn ? [createToolDescriptor("bg_task_spawn")] : []),
683
699
  ...(capabilities.background.watch ? [createToolDescriptor("bg_task_watch")] : []),
684
700
  ...(capabilities.background.status ? [createToolDescriptor("bg_task_status")] : []),
@@ -720,6 +736,7 @@ export function normalizeToolDescriptors(
720
736
 
721
737
  export function capabilityForTool(name: OperationBridgeToolName, capabilities: OperationBridgeCapabilities): boolean {
722
738
  switch (name) {
739
+ case "report_assignment_result": return capabilities.reportAssignment === true;
723
740
  case "bg_task_spawn": return capabilities.background.spawn;
724
741
  case "bg_task_watch": return capabilities.background.watch;
725
742
  case "bg_task_status": return capabilities.background.status;
package/output-payload.ts CHANGED
@@ -98,6 +98,8 @@ export type LoadedRun =
98
98
  | { kind: "unreadable"; detail: string };
99
99
 
100
100
  export type SubagentToolSession = {
101
+ observeAssignment?: (id: string) => Promise<{ assignment: ReturnType<typeof assignmentFor>; snapshot: unknown }>;
102
+ observeList?: (scope: object) => Promise<any>;
101
103
  inspectOutcome?: (meta: RunMeta, params: Record<string, unknown>, ctx?: unknown) => unknown;
102
104
  /** Current session origin; `ctx` is the tool call's host context when available. */
103
105
  getActiveOrigin?: (ctx?: unknown) => RunCallbackOrigin | undefined;
package/package.json CHANGED
@@ -1,10 +1,11 @@
1
1
  {
2
2
  "name": "pi-better-subagents",
3
- "version": "0.32.7",
3
+ "version": "0.33.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
+ "pi-subagents-runtime-status": "./runtime-client/src/runtime/status-cli.mjs",
8
9
  "pi-agent-catalog": "./agent-catalog.mjs"
9
10
  },
10
11
  "exports": {
@@ -41,7 +42,7 @@
41
42
  },
42
43
  "scripts": {
43
44
  "pretest": "node ../../scripts/sync-shared-log-utils.mjs && node ../../scripts/sync-shared-sandbox-core.mjs && node ../../scripts/sync-task-sandbox.mjs",
44
- "prepack": "node ../../scripts/sync-shared-log-utils.mjs && node ../../scripts/sync-shared-sandbox-core.mjs && node ../../scripts/sync-task-sandbox.mjs",
45
+ "prepack": "node ../../scripts/sync-shared-log-utils.mjs && node ../../scripts/sync-shared-sandbox-core.mjs && node ../../scripts/sync-task-sandbox.mjs && node ../../scripts/sync-runtime-client.mjs",
45
46
  "typecheck": "tsc -p tsconfig.task-runtime.json",
46
47
  "test": "node --import tsx --import ./tests/isolate-registry.mjs --test tests/*.test.mjs",
47
48
  "test:cross-session": "node --import tsx --import ./tests/isolate-registry.mjs --test --test-name-pattern \"callback session isolation\" tests/extension_health_lifecycle.test.mjs",
@@ -52,6 +53,7 @@
52
53
  "verify": "npm run typecheck && npm test"
53
54
  },
54
55
  "files": [
56
+ "runtime-client/**",
55
57
  "*.ts",
56
58
  "*.mjs",
57
59
  "*.d.mts",
package/parse.ts CHANGED
@@ -183,11 +183,11 @@ function transcriptContent(msg: Msg | undefined): ContentBlock[] {
183
183
  /** Bounded, display-oriented transcript fold for the subagent detail view. */
184
184
  export function readRunTranscript(
185
185
  id: string,
186
- options: { maxBytes?: number; maxEntries?: number } = {},
186
+ options: { maxBytes?: number; maxEntries?: number; logPath?: string } = {},
187
187
  ): RunTranscript {
188
188
  const maxBytes = Math.max(1024, options.maxBytes ?? DEFAULT_TRANSCRIPT_TAIL_BYTES);
189
189
  const maxEntries = Math.max(1, options.maxEntries ?? DEFAULT_TRANSCRIPT_ENTRIES);
190
- const tail = readTail(logPathFor(id), maxBytes);
190
+ const tail = readTail(options.logPath ?? logPathFor(id), maxBytes);
191
191
  if (tail.error) return { entries: [], truncated: false, diagnostic: `Log unreadable: ${tail.error}` };
192
192
 
193
193
  const lines = tail.text.split(/\r?\n/);
@@ -1312,15 +1312,16 @@ function foldParseEvent(state: ParseState, e: Record<string, unknown>): void {
1312
1312
  * rotated, truncated, or rewritten log is detected and re-read from a bounded
1313
1313
  * tail (see log-cursor.ts).
1314
1314
  */
1315
- export function parseRun(id: string): ParsedRun {
1316
- const previous = parseStates.get(id);
1317
- const read = readAppendedLines(logPathFor(id), previous?.cursor, maxParseBytes());
1315
+ export function parseRun(id: string, options: { logPath?: string } = {}): ParsedRun {
1316
+ const key = options.logPath ?? id;
1317
+ const previous = parseStates.get(key);
1318
+ const read = readAppendedLines(options.logPath ?? logPathFor(id), previous?.cursor, maxParseBytes());
1318
1319
  const state = read.restarted || !previous ? freshState(read.cursor) : previous;
1319
1320
  state.cursor = read.cursor;
1320
1321
  if (read.totalBytes > 0) state.totalBytes = read.totalBytes;
1321
1322
  if (read.truncated) state.windowTruncated = true;
1322
1323
  state.error = read.error;
1323
- rememberParseState(id, state);
1324
+ rememberParseState(key, state);
1324
1325
 
1325
1326
  if (read.error !== undefined) {
1326
1327
  return {
package/registry.ts CHANGED
@@ -240,6 +240,8 @@ export interface RunMeta {
240
240
  completionCallbackSentAt?: number;
241
241
  completionCallbackSuppressedAt?: number;
242
242
  completionCallbackSuppressedReason?: string;
243
+ outcomeDeliveryDeferredReason?: string;
244
+ assignmentReport?: { version: 1; assignmentId: string; attemptId: string; digest: string; path: string };
243
245
  orphanedCallbackSuppressedAt?: number;
244
246
  orphanedCallbackSuppressedReason?: string;
245
247
  lostCallbackSuppressedAt?: number;
@@ -1350,7 +1352,7 @@ export function removeMetaArtifacts(meta: RunMeta, options: RemoveMetaArtifactsO
1350
1352
  * whose raw log/run directory was already reclaimed. The volatile record wins
1351
1353
  * whenever both exist, so a reclaimed log never hides the live one.
1352
1354
  */
1353
- export function listMetas(): RunMeta[] {
1355
+ export function listMetas(options: { includeArchived?: boolean } = {}): RunMeta[] {
1354
1356
  let ids: string[] = [];
1355
1357
  try {
1356
1358
  registryIo.fullDirectoryReads += 1;
@@ -1366,7 +1368,7 @@ export function listMetas(): RunMeta[] {
1366
1368
  if (!meta) continue;
1367
1369
  metas.push(meta);
1368
1370
  }
1369
- for (const meta of listArchivedAttempts()) {
1371
+ for (const meta of options.includeArchived === false ? [] : listArchivedAttempts()) {
1370
1372
  if (seen.has(meta.id)) continue;
1371
1373
  seen.add(meta.id);
1372
1374
  metas.push(meta);
@@ -0,0 +1 @@
1
+ {"build":{"format":1,"sourceDigest":"3327fd5e74b18926f945db86bb1bc82f6a5f52eaef9ce091cfe45b7537df871c","piSdkVersion":"1.4.0","nodeVersion":"24.14.1","platform":"darwin-arm64","dependencyLockDigest":"c63ff3a60c411a06ad881d6ae81fbe88402cc1ff3a3447bf54765b090b2c77bb","protocolVersion":1,"serverVersion":"0.3.0","contentId":"4a441dc74b227cdaaeebe9bf93580d18c4773acd30a43df8376205888314877f"},"sha256":"d605829c1323baa03ec1908337950c965d97e7ded4dc24479fff7300be296367"}