pi-better-subagents 0.30.0 → 0.31.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.
package/index.ts CHANGED
@@ -11,6 +11,10 @@
11
11
  * launch is the result · completion posts back · the foreground never blocks
12
12
  */
13
13
 
14
+ import { assignmentFor } from "./assignment-projection.mjs";
15
+ import { registerAssignmentAttempt, commitAssignmentTerminal, readOutcome, receiptOutcome, outcomeTranscriptReceipt, inspectOutcome, createOutcomeHost, closeOutcomeHost, claimOutcome, type AssignmentBinding } from "./assignment-outcomes.ts";
16
+ import { currentSandboxPermissions } from "./permission-policy.ts";
17
+ import { requestResumeAdmission } from "./worker-waits.ts";
14
18
  import { execSync } from "node:child_process";
15
19
  import { writeFileSync, mkdirSync, renameSync, statSync } from "node:fs";
16
20
  import type { ExtensionAPI, ExtensionCommandContext, ExtensionContext } from "@earendil-works/pi-coding-agent";
@@ -203,9 +207,12 @@ import { registerSubagentsGoalProvider } from "./goal-provider.ts";
203
207
  import {
204
208
  DEFAULT_WORKER_BRIDGE_TOOLS,
205
209
  PreSpawnResumeError,
210
+ type WorkerSandboxAuthority,
211
+ assertAssignmentPermissionScope,
206
212
  assertFinalResumeDispatch,
207
213
  releaseChild,
208
214
  cancelParkedWait,
215
+ branchContains,
209
216
  captureWorkerPolicy,
210
217
  createOwnedAttemptStopper,
211
218
  childBridgeExtensionPath,
@@ -365,6 +372,10 @@ function callbackSuppressionReason(meta: RunMeta, active: RunCallbackOrigin | un
365
372
  if (origin.sessionId && origin.sessionId !== active.sessionId) {
366
373
  return `origin session ${origin.sessionId} does not match active session ${active.sessionId ?? "unknown"}`;
367
374
  }
375
+ if (meta.operations?.resumeLaunchToken && meta.operations.branchId
376
+ && (!uiCtx || !branchContains(uiCtx, meta.operations.branchId))) {
377
+ return `origin branch ${meta.operations.branchId} is not active`;
378
+ }
368
379
  return undefined;
369
380
  }
370
381
 
@@ -466,6 +477,8 @@ function warnInterruptedSubagents(ctx: ExtensionContext, interrupted: RunMeta[],
466
477
  * no longer has a session.
467
478
  */
468
479
  let sessionTornDown = false;
480
+ let outcomeHost = createOutcomeHost();
481
+ const outcomeAdmission = new Map<string, () => boolean>();
469
482
 
470
483
  /**
471
484
  * "The rightful conversation is not the active one", not "this notification is
@@ -475,6 +488,7 @@ let sessionTornDown = false;
475
488
  function isConversationIdentityReason(reason: string): boolean {
476
489
  return reason === NO_ACTIVE_SESSION_REASON
477
490
  || reason.startsWith("origin session ")
491
+ || reason.startsWith("origin branch ")
478
492
  || reason.startsWith("origin cwd ")
479
493
  || reason.startsWith("legacy run cwd ");
480
494
  }
@@ -492,7 +506,8 @@ function markCompletionCallbackSuppressed(id: string, reason: string, now: numbe
492
506
  // attempt but must keep the obligation: the pending marker stays, and A
493
507
  // recovers it when it comes back. Records that never lost supervision keep
494
508
  // today's durable suppression, so legacy/foreign notifications stay dead.
495
- if (meta.supervisionInterruptedAt !== undefined && isConversationIdentityReason(reason)) return;
509
+ if ((meta.supervisionInterruptedAt !== undefined || meta.operations?.resumeLaunchToken)
510
+ && isConversationIdentityReason(reason)) return;
496
511
  meta.completionCallbackSuppressedAt = now;
497
512
  meta.completionCallbackSuppressedReason = reason;
498
513
  writeMeta(meta);
@@ -508,6 +523,17 @@ function markCompletionCallbackSent(id: string, now: number): void {
508
523
  /** Queue one durable ordinary terminal event on the host-shared batch. */
509
524
  function enqueueCompletionCallback(pi: ExtensionAPI, id: string): void {
510
525
  const meta = readMeta(id);
526
+ if (meta?.assignment) {
527
+ try {
528
+ const outcome = commitAssignmentTerminal(meta);
529
+ if (outcome) { void enqueueAssignmentOutcome(pi, meta); return; }
530
+ // An unresolved assignment exit belongs to repair, not legacy delivery.
531
+ return;
532
+ } catch (error) {
533
+ try { uiCtx?.ui?.notify(`Assignment outcome could not commit: ${String(error)}`, "warning"); } catch { /* no UI */ }
534
+ return;
535
+ }
536
+ }
511
537
  if (!meta
512
538
  || meta.callback === false
513
539
  || meta.completionCallbackPendingAt === undefined
@@ -542,6 +568,39 @@ function enqueueCompletionCallback(pi: ExtensionAPI, id: string): void {
542
568
  });
543
569
  }
544
570
 
571
+ async function enqueueAssignmentOutcome(pi: ExtensionAPI, meta: RunMeta): Promise<void> {
572
+ const outcome = readOutcome(meta);
573
+ const ctx = uiCtx;
574
+ if (!outcome || outcome.deliveryReceipt || outcome.disposition || !ctx || meta.callback === false
575
+ || typeof ctx.sessionManager?.getBranch !== "function") return;
576
+ const active = ownerBindingFromContext(ctx);
577
+ if (active.sessionId !== outcome.recipient.sessionId || active.workspace !== outcome.recipient.workspace
578
+ || (outcome.recipient.branchId && !ctx.sessionManager.getBranch().some((entry) => entry.id === outcome.recipient.branchId))) return;
579
+ const prior = outcomeTranscriptReceipt(ctx.sessionManager.getBranch(), outcome.eventId);
580
+ if (prior) { receiptOutcome(meta, prior); return; }
581
+ const gate = await requestResumeAdmission(pi, active, { timeoutMs: 50 });
582
+ outcomeAdmission.set(outcome.eventId, () => gate.allowed ? gate.isCurrent?.() !== false : !active.goalId && !outcome.recipient.goalId && gate.revision === -1);
583
+ if (!gate.allowed && (active.goalId || outcome.recipient.goalId || gate.revision !== -1)) return;
584
+ if (!claimOutcome(meta, outcomeHost)) return;
585
+ getCallbackBatcher(pi).enqueue({
586
+ source: "subagent", id: outcome.eventId, inspectId: meta.id, receiptId: outcome.eventId,
587
+ label: meta.name ?? meta.id,
588
+ status: outcome.outcome, outcome: outcome.reason, detailTool: "subagent_result", callback: true,
589
+ isDelivered: () => Boolean(readOutcome(meta)?.deliveryReceipt),
590
+ getSuppressionReason: () => {
591
+ if (!uiCtx || callbackSuppressionReason(meta)) throw new Error("Recorded parent is inactive; retain outcome.");
592
+ 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.");
593
+ return undefined;
594
+ },
595
+ onDelivered: (at) => {
596
+ const entry = outcomeTranscriptReceipt(ctx.sessionManager.getBranch(), outcome.eventId);
597
+ if (!entry) throw new Error("Awaiting durable recipient transcript receipt.");
598
+ receiptOutcome(meta, entry);
599
+ markCompletionCallbackSent(meta.id, at);
600
+ },
601
+ });
602
+ }
603
+
545
604
  /**
546
605
  * Recover only records explicitly marked pending; legacy terminal runs never replay.
547
606
  *
@@ -553,7 +612,14 @@ function enqueueCompletionCallback(pi: ExtensionAPI, id: string): void {
553
612
  * same `isAbandonedByParent` proof the running-record supervision uses — so this
554
613
  * path never takes a live pi's terminal callback (#625, DEV-226 criterion 5).
555
614
  */
615
+ function recoverAssignmentOutcomes(pi: ExtensionAPI): void {
616
+ for (const meta of activeCallbackOrigin ? listMetasForOrigin(activeCallbackOrigin) : []) if (meta.assignment) {
617
+ try { if (commitAssignmentTerminal(meta)) void enqueueAssignmentOutcome(pi, meta); } catch { /* keep unverified; no legacy handoff */ }
618
+ }
619
+ }
620
+
556
621
  function recoverCompletionCallbacks(pi: ExtensionAPI): void {
622
+ recoverAssignmentOutcomes(pi);
557
623
  for (const meta of listMetasForParent(process.pid)) {
558
624
  if (!ownedByThisParent(meta)) continue;
559
625
  enqueueCompletionCallback(pi, meta.id);
@@ -1322,7 +1388,7 @@ function navigatorRows(visible?: RunMeta[], at?: number) {
1322
1388
 
1323
1389
  /** Runs that should advertise/open the left-arrow navigator affordance. */
1324
1390
  function navigatorRunningRuns(): RunMeta[] {
1325
- return sessionVisibleNavigatorRuns().filter((m) => effectiveStatus(m) === "running" || pendingNavigatorPark(m));
1391
+ return sessionVisibleNavigatorRuns().filter((m) => ["running", "waiting"].includes(assignmentFor(m, effectiveStatus(m)).state));
1326
1392
  }
1327
1393
 
1328
1394
  function navigatorRunningCount(): number {
@@ -1343,15 +1409,14 @@ function sessionVisibleNavigatorRuns(now: number = Date.now()): RunMeta[] {
1343
1409
  }
1344
1410
 
1345
1411
  function isExpiredTerminalNavigatorRun(meta: RunMeta, now: number): boolean {
1346
- if (pendingNavigatorPark(meta)) return false;
1347
- const status = effectiveStatus(meta);
1412
+ const status = assignmentFor(meta, effectiveStatus(meta)).state;
1348
1413
  if (!isTerminalNavigatorStatus(status)) return false;
1349
1414
  const endedAt = meta.endedAt ?? meta.lostAt;
1350
1415
  return typeof endedAt === "number" && now - endedAt >= TERMINAL_NAVIGATOR_RETENTION_MS;
1351
1416
  }
1352
1417
 
1353
1418
  function isTerminalNavigatorStatus(status: string): boolean {
1354
- return status !== "running" && status !== "orphaned";
1419
+ return status !== "running" && status !== "waiting" && status !== "orphaned";
1355
1420
  }
1356
1421
 
1357
1422
  /** Live detail snapshot for one run (registry + log parse + health). */
@@ -1414,6 +1479,8 @@ function statusTone(status: string): BackgroundWorkRow["statusTone"] {
1414
1479
  case "failed":
1415
1480
  case "lost": return "failed";
1416
1481
  case "held":
1482
+ case "waiting":
1483
+ case "cancelled":
1417
1484
  case "killed":
1418
1485
  case "orphaned": return "warning";
1419
1486
  default: return "muted";
@@ -1448,7 +1515,7 @@ function subagentWorkRows(now: number): BackgroundWorkRow[] {
1448
1515
  expiresAt: (() => {
1449
1516
  const meta = metaById.get(row.id);
1450
1517
  const endedAt = meta?.endedAt ?? meta?.lostAt;
1451
- return meta && !pendingNavigatorPark(meta) && isTerminalNavigatorStatus(effectiveStatus(meta)) && typeof endedAt === "number"
1518
+ return meta && isTerminalNavigatorStatus(row.status) && typeof endedAt === "number"
1452
1519
  ? endedAt + TERMINAL_NAVIGATOR_RETENTION_MS
1453
1520
  : undefined;
1454
1521
  })(),
@@ -1539,12 +1606,17 @@ function subagentWorkDetail(id: string, now: number, options?: { logTailLines?:
1539
1606
  { label: "id", value: detail.id },
1540
1607
  ...(detail.role ? [{ label: "role", value: String(detail.role) }] : []),
1541
1608
  { label: "model", value: detail.effort ? `${detail.model} · effort ${detail.effort}` : detail.model },
1609
+ ...(detail.assignment ? [
1610
+ { label: "revision", value: detail.assignment.revision },
1611
+ { label: "reason", value: detail.assignment.reason },
1612
+ { label: "process", value: `${detail.assignment.processStatus}; termination ${detail.assignment.termination}` },
1613
+ { label: "evidence", value: detail.assignment.evidence.join(", ") },
1614
+ ] : []),
1542
1615
  { label: "elapsed", value: detail.elapsed },
1543
1616
  { label: "tools", value: detail.currentTool ? `current ${detail.currentTool}` : (detail.tools || "(none)") },
1544
1617
  { label: "spend", value: detail.spend || "(none)" },
1545
1618
  ...(detail.park ? [
1546
1619
  { label: "wait", value: `${detail.park.waitId} generation ${detail.park.generation}` },
1547
- { label: "assignment", value: detail.park.heldReason || detail.park.continuationNote || "Waiting for the operation result; assignment unfinished" },
1548
1620
  ] : []),
1549
1621
  { label: "pid", value: detail.pid != null ? String(detail.pid) : "-" },
1550
1622
  { label: "pgid", value: detail.pgid != null ? String(detail.pgid) : "-" },
@@ -1560,7 +1632,7 @@ function subagentWorkDetail(id: string, now: number, options?: { logTailLines?:
1560
1632
  evidence: { label: "transcript", text: detail.output || "(no transcript yet)" },
1561
1633
  transcript: transcript.entries,
1562
1634
  transcriptDiagnostic: transcript.diagnostic,
1563
- footerActions: [detail.park ? "x cancel resume" : detail.status === "running" || detail.status === "orphaned" ? "x stop" : "x dismiss"],
1635
+ footerActions: [detail.park ? "x cancel resume" : detail.attemptStatus === "running" || detail.attemptStatus === "orphaned" ? "x stop" : "x dismiss"],
1564
1636
  };
1565
1637
  }
1566
1638
 
@@ -2237,6 +2309,7 @@ export default function (pi: ExtensionAPI) {
2237
2309
  const parked = parkedWaitForRun(id);
2238
2310
  if (!parked) return false;
2239
2311
  void cancelParkedWait(workerOperations.service, parked, reason, { stopAttempt: stopPublishedAttempt })
2312
+ .then(() => { if (parked.meta.assignment) enqueueCompletionCallback(pi, id); })
2240
2313
  .catch(() => { /* the durable record keeps the wait visible */ })
2241
2314
  .finally(() => syncHealthTicker());
2242
2315
  return true;
@@ -2615,8 +2688,10 @@ export default function (pi: ExtensionAPI) {
2615
2688
  resetChildEventLogCursor(id);
2616
2689
  resetParseRunCursor(id);
2617
2690
  }
2618
- const callbackOrigin = callbackOriginFromContext(ctx);
2619
- activeCallbackOrigin = callbackOrigin;
2691
+ const callbackOrigin = internal?.parkOwner
2692
+ ? { cwd: internal.parkOwner.workspace, sessionId: internal.parkOwner.sessionId }
2693
+ : callbackOriginFromContext(ctx);
2694
+ activeCallbackOrigin = callbackOriginFromContext(ctx);
2620
2695
 
2621
2696
  // Sandbox is opt-in. sandbox_dir moves the confinement + working
2622
2697
  // dir elsewhere. git_clone_workspace prepares a disposable clone with
@@ -2915,6 +2990,9 @@ export default function (pi: ExtensionAPI) {
2915
2990
  ...(bridgeEnabled ? [childBridgeExtensionPath(selfDir())] : []),
2916
2991
  ],
2917
2992
  runtimeRoots: [baseDir()],
2993
+ capturedDenyWrite: internal?.resumeWait
2994
+ ? (resume?.prior.operations?.policy.sandbox as WorkerSandboxAuthority | null)?.denyWrite
2995
+ : undefined,
2918
2996
  }) : undefined;
2919
2997
  launchScratch = taskRuntime?.policy.scratch;
2920
2998
  if (sandboxEnabled && !taskRuntime) throw new Error("Task sandbox has no workspace; refusing an unconfined child.");
@@ -2966,6 +3044,7 @@ export default function (pi: ExtensionAPI) {
2966
3044
  if (bridgeEnabled) {
2967
3045
  const workerPolicy = captureWorkerPolicy({
2968
3046
  sandbox: sandboxEnabled,
3047
+ mandatoryPermissions: permissionPlan.enforced,
2969
3048
  tools: selectedTools,
2970
3049
  clean,
2971
3050
  workspace: cwd,
@@ -3020,6 +3099,24 @@ export default function (pi: ExtensionAPI) {
3020
3099
  // The fence returns a synchronous release guard that is invoked with no
3021
3100
  // await between it and the spawn, so a cancellation or parent change
3022
3101
  // cannot hide inside a final asynchronous window.
3102
+ if (internal?.resumeWait && !resume?.prior.assignment) throw new PreSpawnResumeError("This legacy park has no verified assignment outcome recipient; refusing continuation on an unsupported binding.");
3103
+ const parent = ownerBindingFromContext(ctx);
3104
+ const assignment: AssignmentBinding | undefined = internal?.resumeWait && resume?.prior.assignment
3105
+ ? resume.prior.assignment
3106
+ : parent.sessionId && typeof ctx.sessionManager?.getBranch === "function" ? { version: 1, assignmentId: id,
3107
+ owner: { kind: "worker-conversation", sessionId, workspace: cwd, branchId: parent.branchId, goalId: parent.goalId },
3108
+ recipient: { kind: "parent-session", ...parent } } : undefined;
3109
+ if (!assignment && bridgeEnabled) throw new Error("Durable assignment outcomes require a recorded parent session and transcript capability.");
3110
+ if (assignment) registerAssignmentAttempt(assignment, id);
3111
+ if (internal?.resumeWait) {
3112
+ const captured = resume?.prior.operations?.policy;
3113
+ const currentSandbox = taskRuntime ? {
3114
+ root: taskRuntime.policy.root,
3115
+ ...(taskRuntime.policy.permissions ? { permissions: taskRuntime.policy.permissions } : {}),
3116
+ ...(taskRuntime.policy.denyWrite ? { denyWrite: [...taskRuntime.policy.denyWrite] } : {}),
3117
+ } : null;
3118
+ assertAssignmentPermissionScope(captured, { sandbox: currentSandbox, mandatoryPermissions: permissionPlan.enforced });
3119
+ }
3023
3120
  const dispatchGuard = await internal?.beforeSpawn?.({ runId: id, permissionPlan });
3024
3121
  spawned = releaseChild(dispatchGuard, () => spawnDetached({ file: cmd.file, fileArgs: cmd.fileArgs, cwd, logPath: logPathFor(id),
3025
3122
  env: {
@@ -3066,6 +3163,8 @@ export default function (pi: ExtensionAPI) {
3066
3163
  });
3067
3164
 
3068
3165
  const meta: RunMeta = {
3166
+ assignment,
3167
+ outcomeSupport: { version: 1, available: Boolean(assignment), ...(!assignment ? { reason: "Legacy host has no verified parent session/transcript; durable assignment delivery is unavailable." } : {}) },
3069
3168
  id, name: launchName, status: "running",
3070
3169
  pid: spawned.pid, spawnPid: process.pid, spawnPidStartTime: parentStartToken(), model,
3071
3170
  effort: thinking, cwd,
@@ -3103,6 +3202,7 @@ export default function (pi: ExtensionAPI) {
3103
3202
  ...(internal?.launchToken ? { resumeLaunchToken: internal.launchToken } : {}),
3104
3203
  policy: {
3105
3204
  version: 1 as const,
3205
+ mandatoryPermissions: workerBridge.policy.mandatoryPermissions,
3106
3206
  sandbox: workerBridge.policy.sandbox,
3107
3207
  tools: workerBridge.policy.tools,
3108
3208
  clean: workerBridge.policy.clean,
@@ -3257,16 +3357,16 @@ export default function (pi: ExtensionAPI) {
3257
3357
  plan = planContinuation({
3258
3358
  id: prior.id,
3259
3359
  prior,
3260
- origin: callbackOriginFromContext(ctx),
3360
+ origin: { cwd: input.park.record.ownerWorkspace ?? prior.callbackOrigin?.cwd ?? prior.cwd, sessionId: input.park.record.ownerSessionId ?? prior.callbackOrigin?.sessionId },
3261
3361
  others: listMetas(),
3262
3362
  });
3263
3363
  } catch (error) {
3264
3364
  throw new PreSpawnResumeError(error instanceof Error ? error.message : String(error));
3265
3365
  }
3266
3366
  const owner: WaitOwnerBinding = {
3267
- sessionId: input.park.record.ownerSessionId ?? ownerBindingFromContext(ctx).sessionId,
3268
- workspace: input.park.record.ownerWorkspace ?? ctx.cwd,
3269
- branchId: input.park.record.ownerBranchId ?? ownerBindingFromContext(ctx).branchId,
3367
+ sessionId: input.park.record.ownerSessionId ?? prior.callbackOrigin?.sessionId ?? "",
3368
+ workspace: input.park.record.ownerWorkspace ?? prior.callbackOrigin?.cwd ?? prior.cwd,
3369
+ branchId: input.park.record.ownerBranchId ?? null,
3270
3370
  goalId: input.park.record.ownerGoalId ?? null,
3271
3371
  };
3272
3372
  const target = plan;
@@ -3860,6 +3960,20 @@ export default function (pi: ExtensionAPI) {
3860
3960
  // The foreground origin from session_start; otherwise the calling context's
3861
3961
  // own session. An unreadable session id stays unavailable (never cwd-wide).
3862
3962
  const toolSession = {
3963
+ inspectOutcome: (meta: RunMeta, params: Record<string, unknown>, callCtx?: unknown) => {
3964
+ if (params.disposition !== undefined && params.disposition !== "consumed" && params.disposition !== "dismissed") throw new Error("Outcome disposition must be consumed or dismissed.");
3965
+ if (!readOutcome(meta)) {
3966
+ if (params.disposition !== undefined || params.operation_id !== undefined) throw new Error("No committed terminal outcome is available for this assignment.");
3967
+ return null;
3968
+ }
3969
+ const context = (callCtx ?? uiCtx) as ExtensionContext;
3970
+ if (!context) throw new Error("Parent identity is unavailable.");
3971
+ return inspectOutcome(meta, { recipient: { kind: "parent-session", ...ownerBindingFromContext(context) }, permissions: currentSandboxPermissions(pi),
3972
+ branchIds: context.sessionManager.getBranch().map((entry) => entry.id),
3973
+ ...(typeof params.operation_id === "string" ? { operationId: params.operation_id } : {}),
3974
+ ...(typeof params.outcome_revision === "number" ? { revision: params.outcome_revision } : {}),
3975
+ ...(params.disposition === "consumed" || params.disposition === "dismissed" ? { disposition: params.disposition, note: String(params.note ?? "") } : {}) });
3976
+ },
3863
3977
  getActiveOrigin: (ctx?: unknown) => activeCallbackOrigin ?? verifiedOriginFromContext(ctx as ExtensionContext | undefined),
3864
3978
  };
3865
3979
  pi.registerTool(subagentListTool(Type, toolSession));
@@ -3980,6 +4094,7 @@ export default function (pi: ExtensionAPI) {
3980
4094
  pi.events?.emit("harness-settings:register", agentsContribution);
3981
4095
  };
3982
4096
  const unsubscribeSettingsRequest = pi.events?.on?.("harness-settings:request", registerSettings);
4097
+ const unsubscribeOutcomeWorkflow = pi.events?.on?.("pi-better-workflow:changed", () => recoverAssignmentOutcomes(pi));
3983
4098
  registerSettings();
3984
4099
 
3985
4100
  if (typeof pi.registerCommand === "function") {
@@ -4097,6 +4212,7 @@ export default function (pi: ExtensionAPI) {
4097
4212
  mainAgentStartedAt = undefined;
4098
4213
  mainAgentTools.clear();
4099
4214
  refreshBackgroundWorkNavigator(ctx);
4215
+ recoverAssignmentOutcomes(pi);
4100
4216
  });
4101
4217
 
4102
4218
  pi.on("session_tree", async (_event, ctx) => {
@@ -4104,6 +4220,7 @@ export default function (pi: ExtensionAPI) {
4104
4220
  agentSessionSettings.restore(ctx);
4105
4221
  try { noteCatalogHost(catalogHostFrom(ctx)); } catch { /* catalog inspection stays undecided */ }
4106
4222
  restoreDelegationMode(ctx);
4223
+ recoverAssignmentOutcomes(pi);
4107
4224
  });
4108
4225
 
4109
4226
  // Capture a UI-bearing context and, if runs from a prior session are still
@@ -4114,6 +4231,7 @@ export default function (pi: ExtensionAPI) {
4114
4231
  // switch), so the previous session's teardown no longer applies: the
4115
4232
  // replacing session owns this instance's supervision loops (#625).
4116
4233
  sessionTornDown = false;
4234
+ outcomeHost = createOutcomeHost();
4117
4235
  setCallbackBatchContext(pi, ctx);
4118
4236
  agentSessionSettings.restore(ctx);
4119
4237
  restoreDelegationMode(ctx);
@@ -4172,6 +4290,8 @@ export default function (pi: ExtensionAPI) {
4172
4290
 
4173
4291
  // Tear down the timer and clear the widget when the session ends.
4174
4292
  pi.on("session_shutdown", async (event, ctx) => {
4293
+ closeOutcomeHost(outcomeHost);
4294
+ if (typeof unsubscribeOutcomeWorkflow === "function") unsubscribeOutcomeWorkflow();
4175
4295
  if (typeof unsubscribeSettingsRequest === "function") unsubscribeSettingsRequest();
4176
4296
  // #625: subagent children are detached process groups that outlive this
4177
4297
  // foreground session. A controlled reload or quit must not destroy
package/list.mjs CHANGED
@@ -1,3 +1,4 @@
1
+ import { assignmentFor, assignmentDiagnostic } from "./assignment-projection.mjs";
1
2
  import { describeTiming } from "./timing.ts";
2
3
  import { fmtElapsed } from "./widget.mjs";
3
4
  import { formatListHealthSuffix } from "./health-surface.mjs";
@@ -7,6 +8,8 @@ export const SUBAGENT_LIST_DEFAULT_LIMIT = 10;
7
8
  export const SUBAGENT_LIST_MAX_LIMIT = 100;
8
9
  /** Effective + durable supervision statuses accepted by subagent_list filters. */
9
10
  export const SUBAGENT_LIST_STATUSES = [
11
+ "waiting",
12
+ "cancelled",
10
13
  "running",
11
14
  "completed",
12
15
  "failed",
@@ -101,7 +104,10 @@ export function formatSubagentListRow(meta, p) {
101
104
  const batch = meta.batchId
102
105
  ? ` [batch: ${meta.batchName ? `${bounded(meta.batchName, 40)} ` : ""}${bounded(meta.batchId, 60)}]`
103
106
  : "";
104
- return `• ${name}${meta.id} [${status}] session_id=${meta.sessionId ?? "unavailable"} ${bounded(meta.model ?? "?", 60)} ${elapsed}${health}${timing}${batch}${failure}\n ${promptPreview(meta)}`;
107
+ const assignment = assignmentFor(meta, p.processStatus ?? meta.status);
108
+ const diagnostic = meta.operations || meta.park || status !== assignment.processStatus || status === "failed"
109
+ ? `\n ${assignmentDiagnostic(assignment)}` : "";
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}`;
105
111
  }
106
112
 
107
113
  export function collectSubagentList(p) {
package/navigator.mjs CHANGED
@@ -24,6 +24,7 @@
24
24
  * with visible-width-aware truncation.
25
25
  */
26
26
 
27
+ import { assignmentFor } from "./assignment-projection.mjs";
27
28
  import {
28
29
  formatNavigatorHealthFacts,
29
30
  statusThemeColor,
@@ -42,6 +43,11 @@ export const NAVIGATOR_STATUS_KEY = "subagents-nav";
42
43
 
43
44
  export const CLOSE_CONFIRM_STATUS_KEY = "subagents-close";
44
45
 
46
+ function isStoppableView(row) {
47
+ const processStatus = row?.assignment?.processStatus ?? row?.attemptStatus ?? row?.status;
48
+ return processStatus === "running" || processStatus === "orphaned";
49
+ }
50
+
45
51
  /** Legacy footer helpers no longer write status. */
46
52
  export function navigatorFooterHint(count) {
47
53
  return null;
@@ -64,7 +70,7 @@ export function applyNavigatorFooter(ui, count) {
64
70
  export function closeConfirmHint(row) {
65
71
  if (!row) return null;
66
72
  const label = (row.name != null && String(row.name).length > 0) ? String(row.name) : String(row.id);
67
- const stoppable = row.status === "running" || row.status === "orphaned";
73
+ const stoppable = isStoppableView(row);
68
74
  return stoppable ? `x again to stop ${label}` : `x again to dismiss ${label}`;
69
75
  }
70
76
 
@@ -182,20 +188,18 @@ export function pendingNavigatorPark(meta) {
182
188
  return park?.version === 1 && ["parking", "waiting", "ready", "resuming", "held"].includes(park.phase) ? park : undefined;
183
189
  }
184
190
 
185
- function navigatorDisplayStatus(meta, status) {
186
- return status === "running" || status === "orphaned" ? status : pendingNavigatorPark(meta)?.phase ?? status;
187
- }
188
-
189
191
  export function buildNavigatorRows(metas, deps) {
190
192
  const now = deps.now ?? Date.now();
191
193
  return metas.map((m) => {
192
- const status = navigatorDisplayStatus(m, deps.effectiveStatus(m));
194
+ const assignment = assignmentFor(m, deps.effectiveStatus(m));
195
+ const status = assignment.state;
193
196
  const health = typeof deps.healthFor === "function" ? deps.healthFor(m) : undefined;
194
197
  const effort = typeof deps.effortFor === "function" ? deps.effortFor(m) : (m.effort ?? m.modelEffort);
195
198
  const tool = typeof deps.toolFor === "function" ? (deps.toolFor(m) || "") : "";
196
199
  return {
197
200
  id: m.id,
198
201
  name: m.name,
202
+ assignment,
199
203
  status,
200
204
  model: deps.shortModel(m.model),
201
205
  // Optional effort stays adjacent to model when the host exposes it.
@@ -332,7 +336,7 @@ export function buildNavigatorLines(state, opts = {}) {
332
336
  const rows = state.rows ?? [];
333
337
  const lines = [commandSheetRule(`Subagents · ${rows.length}`, width)];
334
338
  const selected = rows.length > 0 ? rows[state.selected] : null;
335
- const stoppable = selected?.status === "running" || selected?.status === "orphaned";
339
+ const stoppable = isStoppableView(selected);
336
340
  const action = stoppable ? "x stop" : (selected ? "x dismiss" : null);
337
341
  lines.push(` ${["↑↓ select", "Enter view", action, "Esc close"].filter(Boolean).join(" · ")}`);
338
342
  lines.push("");
@@ -383,7 +387,8 @@ export function buildNavigatorDetail(id, deps) {
383
387
  const now = deps.now ?? Date.now();
384
388
  const parsed = deps.parseRun(id);
385
389
  const toolCalls = parsed.toolCalls ?? [];
386
- const status = navigatorDisplayStatus(meta, deps.effectiveStatus(meta));
390
+ const assignment = assignmentFor(meta, deps.effectiveStatus(meta));
391
+ const status = assignment.state;
387
392
  const running = status === "running" || status === "orphaned";
388
393
  const health = typeof deps.healthFor === "function" ? deps.healthFor(meta) : undefined;
389
394
  const effortRaw = typeof deps.effortFor === "function"
@@ -395,6 +400,7 @@ export function buildNavigatorDetail(id, deps) {
395
400
  role: meta.catalog?.roleName || (meta.catalog?.roleId ? String(meta.catalog.roleId).replace(/^role\./, "") : undefined) || undefined,
396
401
  park: pendingNavigatorPark(meta),
397
402
  attemptStatus: deps.effectiveStatus(meta),
403
+ assignment,
398
404
  status,
399
405
  model: deps.shortModel(meta.model),
400
406
  effort: effortRaw ? String(effortRaw) : undefined,
@@ -475,11 +481,17 @@ export function buildDetailLines(detail, opts = {}) {
475
481
  const statusRaw = String(detail.status ?? "?");
476
482
  const statusText = colorize ? fg(statusThemeColor(statusRaw), statusRaw) : statusRaw;
477
483
 
478
- const stoppable = detail.status === "running" || detail.status === "orphaned";
484
+ const stoppable = isStoppableView(detail);
479
485
  const action = stoppable ? "x stop" : "x dismiss";
480
486
  lines.push(` ← back · ${action} · Esc close`);
481
487
  lines.push("");
482
488
  lines.push(` status ${statusText}`);
489
+ if (detail.assignment) {
490
+ lines.push(` revision ${detail.assignment.revision}`);
491
+ lines.push(` reason ${detail.assignment.reason}`);
492
+ lines.push(` process ${detail.assignment.processStatus}; termination ${detail.assignment.termination}`);
493
+ for (const ref of detail.assignment.evidence) lines.push(` evidence ${ref}`);
494
+ }
483
495
  lines.push(` id ${detail.id ?? "?"}`);
484
496
  if (detail.role) lines.push(` role ${detail.role}`);
485
497
 
@@ -509,6 +521,7 @@ export function buildDetailLines(detail, opts = {}) {
509
521
  // detail header already shows a non-running effective status (legacy
510
522
  // dead-running metadata → effective "exited" must read as terminal).
511
523
  let live = h?.process?.liveness;
524
+ if (detail.assignment) live = `${detail.assignment.processStatus}; termination ${detail.assignment.termination}`;
512
525
  if (!live || (detail.status !== "running" && live === "supervised")) {
513
526
  live = detail.status === "orphaned" ? "orphaned"
514
527
  : detail.status === "lost" ? "lost"
@@ -766,7 +779,7 @@ export function createNavigatorOverlayComponent(rows, deps, tui, theme, done) {
766
779
  if (detailId == null) return null;
767
780
  // Prefer live detail snapshot (status may have changed while armed).
768
781
  if (detail && detail.id === detailId) {
769
- return { id: detail.id, name: detail.name, status: detail.status };
782
+ return { id: detail.id, name: detail.name, status: detail.status, assignment: detail.assignment, attemptStatus: detail.attemptStatus };
770
783
  }
771
784
  const fromList = (state.rows ?? []).find((r) => r && r.id === detailId);
772
785
  return fromList ?? { id: detailId, name: detailId, status: "completed" };
@@ -0,0 +1,73 @@
1
+ /** Versioned reconciliation evidence in the existing durable conversation store. */
2
+ import { createHash, randomBytes } from "node:crypto";
3
+ import { closeSync, fsyncSync, mkdirSync, openSync, readFileSync, readdirSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
4
+ import { join } from "node:path";
5
+ import { durableSubagentRoot } from "./session-store.ts";
6
+ import type { ParkRecord, RunMeta } from "./registry.ts";
7
+
8
+ export interface OutageObservation {
9
+ version: 1;
10
+ id: string;
11
+ observedRevision: { generation: number; claimId: string | null; launchToken: string | null; cancelled?: true };
12
+ coordinatorEvidence?: ParkRecord["observedCoordinator"];
13
+ meta: RunMeta;
14
+ record: ParkRecord;
15
+ attempt?: RunMeta;
16
+ resolved?: true;
17
+ }
18
+
19
+ function directory(): string { return join(durableSubagentRoot(), "observations-v1"); }
20
+
21
+ function publish(path: string, value: unknown): void {
22
+ mkdirSync(directory(), { recursive: true, mode: 0o700 });
23
+ const temporary = join(directory(), `.${randomBytes(12).toString("hex")}.tmp`);
24
+ try {
25
+ writeFileSync(temporary, JSON.stringify(value), { flag: "wx", mode: 0o600 });
26
+ const fd = openSync(temporary, "r");
27
+ try { fsyncSync(fd); } finally { closeSync(fd); }
28
+ renameSync(temporary, path);
29
+ const dir = openSync(directory(), "r");
30
+ try { fsyncSync(dir); } finally { closeSync(dir); }
31
+ } finally {
32
+ try { unlinkSync(temporary); } catch { /* Already published. */ }
33
+ }
34
+ }
35
+
36
+ export function assertObservationStorage(): void {
37
+ try { publish(join(directory(), "storage-probe.json"), { version: 1 }); }
38
+ catch (error) { throw new Error(`Degraded supervision: durable conversation storage unavailable; new parking refused (${String(error)}).`); }
39
+ }
40
+
41
+ export function retainObservation(meta: RunMeta, record: ParkRecord, attempt?: RunMeta): OutageObservation {
42
+ const observedRevision = { generation: record.generation, claimId: record.resumeClaimId ?? null,
43
+ launchToken: record.resumeLaunchToken ?? null, ...(record.phase === "cancelled" ? { cancelled: true as const } : {}) };
44
+ const id = createHash("sha256").update(JSON.stringify([meta.assignment?.assignmentId ?? meta.id,
45
+ record.waitId, observedRevision])).digest("hex");
46
+ const path = join(directory(), `${id}.json`);
47
+ try {
48
+ const existing = JSON.parse(readFileSync(path, "utf8")) as OutageObservation;
49
+ if (existing.version !== 1 || existing.id !== id) throw new Error("Invalid observation identity");
50
+ return existing;
51
+ } catch (error) {
52
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
53
+ }
54
+ const report: OutageObservation = { version: 1, id, observedRevision, coordinatorEvidence: record.observedCoordinator,
55
+ meta, record, ...(attempt ? { attempt } : {}) };
56
+ publish(path, report);
57
+ return report;
58
+ }
59
+
60
+ export function pendingObservations(): OutageObservation[] {
61
+ let names: string[];
62
+ try { names = readdirSync(directory()); }
63
+ catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return []; throw error; }
64
+ return names.filter((name) => /^[a-f0-9]{64}\.json$/.test(name)).map((name) => {
65
+ const report = JSON.parse(readFileSync(join(directory(), name), "utf8")) as OutageObservation;
66
+ if (report.version !== 1 || `${report.id}.json` !== name) throw new Error("Unsupported or corrupt outage observation");
67
+ return report;
68
+ }).filter((report) => !report.resolved);
69
+ }
70
+
71
+ export function resolveObservation(report: OutageObservation): void {
72
+ publish(join(directory(), `${report.id}.json`), { ...report, resolved: true });
73
+ }