pi-better-subagents 0.30.0 → 0.32.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,11 @@
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 { historicalWaits, attentionRevision, attentionDismissed, dismissAttention } from "./historical-attention.ts";
16
+ import { registerAssignmentAttempt, commitAssignmentTerminal, readOutcome, receiptOutcome, outcomeTranscriptReceipt, inspectOutcome, createOutcomeHost, closeOutcomeHost, claimOutcome, type AssignmentBinding } from "./assignment-outcomes.ts";
17
+ import { currentSandboxPermissions } from "./permission-policy.ts";
18
+ import { requestResumeAdmission } from "./worker-waits.ts";
14
19
  import { execSync } from "node:child_process";
15
20
  import { writeFileSync, mkdirSync, renameSync, statSync } from "node:fs";
16
21
  import type { ExtensionAPI, ExtensionCommandContext, ExtensionContext } from "@earendil-works/pi-coding-agent";
@@ -203,9 +208,12 @@ import { registerSubagentsGoalProvider } from "./goal-provider.ts";
203
208
  import {
204
209
  DEFAULT_WORKER_BRIDGE_TOOLS,
205
210
  PreSpawnResumeError,
211
+ type WorkerSandboxAuthority,
212
+ assertAssignmentPermissionScope,
206
213
  assertFinalResumeDispatch,
207
214
  releaseChild,
208
215
  cancelParkedWait,
216
+ branchContains,
209
217
  captureWorkerPolicy,
210
218
  createOwnedAttemptStopper,
211
219
  childBridgeExtensionPath,
@@ -231,6 +239,8 @@ import { defaultUserRoot, type CatalogSnapshot } from "./catalog-store.ts";
231
239
  import { restrictContextFilesToWorktree } from "./shared-worktree-context.ts";
232
240
 
233
241
  const SUBAGENT_MODE_ACTIONS: readonly AutocompleteItem[] = [
242
+ { value: "history", label: "history", description: "Inspect or cancel waits from other sessions" },
243
+ { value: "history dismiss", label: "history dismiss", description: "Dismiss unchanged historical attention notices" },
234
244
  { value: "settings", label: "settings", description: "Open delegation, concurrency, and timing settings" },
235
245
  { value: "cap", label: "cap <number>", description: "Set a positive concurrent subagent limit for this session" },
236
246
  { value: "tool-wait", label: "tool-wait <minutes>", description: "Set the session tool-wait alert time; 0 turns it off" },
@@ -365,6 +375,10 @@ function callbackSuppressionReason(meta: RunMeta, active: RunCallbackOrigin | un
365
375
  if (origin.sessionId && origin.sessionId !== active.sessionId) {
366
376
  return `origin session ${origin.sessionId} does not match active session ${active.sessionId ?? "unknown"}`;
367
377
  }
378
+ if (meta.operations?.resumeLaunchToken && meta.operations.branchId
379
+ && (!uiCtx || !branchContains(uiCtx, meta.operations.branchId))) {
380
+ return `origin branch ${meta.operations.branchId} is not active`;
381
+ }
368
382
  return undefined;
369
383
  }
370
384
 
@@ -466,6 +480,8 @@ function warnInterruptedSubagents(ctx: ExtensionContext, interrupted: RunMeta[],
466
480
  * no longer has a session.
467
481
  */
468
482
  let sessionTornDown = false;
483
+ let outcomeHost = createOutcomeHost();
484
+ const outcomeAdmission = new Map<string, () => boolean>();
469
485
 
470
486
  /**
471
487
  * "The rightful conversation is not the active one", not "this notification is
@@ -475,6 +491,7 @@ let sessionTornDown = false;
475
491
  function isConversationIdentityReason(reason: string): boolean {
476
492
  return reason === NO_ACTIVE_SESSION_REASON
477
493
  || reason.startsWith("origin session ")
494
+ || reason.startsWith("origin branch ")
478
495
  || reason.startsWith("origin cwd ")
479
496
  || reason.startsWith("legacy run cwd ");
480
497
  }
@@ -492,7 +509,8 @@ function markCompletionCallbackSuppressed(id: string, reason: string, now: numbe
492
509
  // attempt but must keep the obligation: the pending marker stays, and A
493
510
  // recovers it when it comes back. Records that never lost supervision keep
494
511
  // today's durable suppression, so legacy/foreign notifications stay dead.
495
- if (meta.supervisionInterruptedAt !== undefined && isConversationIdentityReason(reason)) return;
512
+ if ((meta.supervisionInterruptedAt !== undefined || meta.operations?.resumeLaunchToken)
513
+ && isConversationIdentityReason(reason)) return;
496
514
  meta.completionCallbackSuppressedAt = now;
497
515
  meta.completionCallbackSuppressedReason = reason;
498
516
  writeMeta(meta);
@@ -508,6 +526,17 @@ function markCompletionCallbackSent(id: string, now: number): void {
508
526
  /** Queue one durable ordinary terminal event on the host-shared batch. */
509
527
  function enqueueCompletionCallback(pi: ExtensionAPI, id: string): void {
510
528
  const meta = readMeta(id);
529
+ if (meta?.assignment) {
530
+ try {
531
+ const outcome = commitAssignmentTerminal(meta);
532
+ if (outcome) { void enqueueAssignmentOutcome(pi, meta); return; }
533
+ // An unresolved assignment exit belongs to repair, not legacy delivery.
534
+ return;
535
+ } catch (error) {
536
+ try { uiCtx?.ui?.notify(`Assignment outcome could not commit: ${String(error)}`, "warning"); } catch { /* no UI */ }
537
+ return;
538
+ }
539
+ }
511
540
  if (!meta
512
541
  || meta.callback === false
513
542
  || meta.completionCallbackPendingAt === undefined
@@ -542,6 +571,39 @@ function enqueueCompletionCallback(pi: ExtensionAPI, id: string): void {
542
571
  });
543
572
  }
544
573
 
574
+ async function enqueueAssignmentOutcome(pi: ExtensionAPI, meta: RunMeta): Promise<void> {
575
+ const outcome = readOutcome(meta);
576
+ const ctx = uiCtx;
577
+ if (!outcome || outcome.deliveryReceipt || outcome.disposition || !ctx || meta.callback === false
578
+ || typeof ctx.sessionManager?.getBranch !== "function") return;
579
+ const active = ownerBindingFromContext(ctx);
580
+ 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;
582
+ const prior = outcomeTranscriptReceipt(ctx.sessionManager.getBranch(), outcome.eventId);
583
+ if (prior) { receiptOutcome(meta, prior); return; }
584
+ const gate = await requestResumeAdmission(pi, active, { timeoutMs: 50 });
585
+ 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;
588
+ getCallbackBatcher(pi).enqueue({
589
+ source: "subagent", id: outcome.eventId, inspectId: meta.id, receiptId: outcome.eventId,
590
+ label: meta.name ?? meta.id,
591
+ status: outcome.outcome, outcome: outcome.reason, detailTool: "subagent_result", callback: true,
592
+ isDelivered: () => Boolean(readOutcome(meta)?.deliveryReceipt),
593
+ getSuppressionReason: () => {
594
+ if (!uiCtx || callbackSuppressionReason(meta)) throw new Error("Recorded parent is inactive; retain outcome.");
595
+ 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
+ return undefined;
597
+ },
598
+ onDelivered: (at) => {
599
+ const entry = outcomeTranscriptReceipt(ctx.sessionManager.getBranch(), outcome.eventId);
600
+ if (!entry) throw new Error("Awaiting durable recipient transcript receipt.");
601
+ receiptOutcome(meta, entry);
602
+ markCompletionCallbackSent(meta.id, at);
603
+ },
604
+ });
605
+ }
606
+
545
607
  /**
546
608
  * Recover only records explicitly marked pending; legacy terminal runs never replay.
547
609
  *
@@ -553,7 +615,14 @@ function enqueueCompletionCallback(pi: ExtensionAPI, id: string): void {
553
615
  * same `isAbandonedByParent` proof the running-record supervision uses — so this
554
616
  * path never takes a live pi's terminal callback (#625, DEV-226 criterion 5).
555
617
  */
618
+ function recoverAssignmentOutcomes(pi: ExtensionAPI): void {
619
+ for (const meta of activeCallbackOrigin ? listMetasForOrigin(activeCallbackOrigin) : []) if (meta.assignment) {
620
+ try { if (commitAssignmentTerminal(meta)) void enqueueAssignmentOutcome(pi, meta); } catch { /* keep unverified; no legacy handoff */ }
621
+ }
622
+ }
623
+
556
624
  function recoverCompletionCallbacks(pi: ExtensionAPI): void {
625
+ recoverAssignmentOutcomes(pi);
557
626
  for (const meta of listMetasForParent(process.pid)) {
558
627
  if (!ownedByThisParent(meta)) continue;
559
628
  enqueueCompletionCallback(pi, meta.id);
@@ -1322,7 +1391,7 @@ function navigatorRows(visible?: RunMeta[], at?: number) {
1322
1391
 
1323
1392
  /** Runs that should advertise/open the left-arrow navigator affordance. */
1324
1393
  function navigatorRunningRuns(): RunMeta[] {
1325
- return sessionVisibleNavigatorRuns().filter((m) => effectiveStatus(m) === "running" || pendingNavigatorPark(m));
1394
+ return sessionVisibleNavigatorRuns().filter((m) => ["running", "waiting"].includes(assignmentFor(m, effectiveStatus(m)).state));
1326
1395
  }
1327
1396
 
1328
1397
  function navigatorRunningCount(): number {
@@ -1343,15 +1412,14 @@ function sessionVisibleNavigatorRuns(now: number = Date.now()): RunMeta[] {
1343
1412
  }
1344
1413
 
1345
1414
  function isExpiredTerminalNavigatorRun(meta: RunMeta, now: number): boolean {
1346
- if (pendingNavigatorPark(meta)) return false;
1347
- const status = effectiveStatus(meta);
1415
+ const status = assignmentFor(meta, effectiveStatus(meta)).state;
1348
1416
  if (!isTerminalNavigatorStatus(status)) return false;
1349
1417
  const endedAt = meta.endedAt ?? meta.lostAt;
1350
1418
  return typeof endedAt === "number" && now - endedAt >= TERMINAL_NAVIGATOR_RETENTION_MS;
1351
1419
  }
1352
1420
 
1353
1421
  function isTerminalNavigatorStatus(status: string): boolean {
1354
- return status !== "running" && status !== "orphaned";
1422
+ return status !== "running" && status !== "waiting" && status !== "orphaned";
1355
1423
  }
1356
1424
 
1357
1425
  /** Live detail snapshot for one run (registry + log parse + health). */
@@ -1373,20 +1441,22 @@ function navigatorDetail(id: string, now: number = Date.now()) {
1373
1441
  * Set by the active extension instance: cancel a parked assignment's pending
1374
1442
  * wait. Returns false when the run is not parked, so the ordinary stop path runs.
1375
1443
  */
1376
- let cancelParkedForUi: ((id: string, reason: string) => boolean) | undefined;
1444
+ let cancelParkedForUi: ((id: string, reason: string) => Promise<boolean>) | undefined;
1377
1445
 
1378
1446
  /** Shared #44 stop+dismiss path used by navigator Close (#47). */
1379
1447
  function navigatorCloseRun(id: string) {
1380
1448
  // A parked attempt's child already exited cleanly, so "close" must cancel the
1381
1449
  // pending automatic resume instead of pretending to stop a live process.
1382
- if (cancelParkedForUi?.(id, "closed from the navigator; the automatic resume is cancelled")) {
1383
- try { dismissRun(id); } catch { /* dismissal is best effort */ }
1384
- spendCache.delete(id);
1385
- healthLogCache.delete(id);
1386
- resetChildEventLogCursor(id);
1387
- resetParseRunCursor(id);
1388
- syncHealthTicker();
1389
- return { action: "stopped", id };
1450
+ if (parkedWaitForRun(id) && cancelParkedForUi) {
1451
+ void cancelParkedForUi(id, "closed from the navigator; the automatic resume is cancelled")
1452
+ .then((cancelled) => {
1453
+ if (!cancelled) throw new Error("The pending wait changed; inspect it again.");
1454
+ dismissRun(id);
1455
+ uiCtx?.ui.notify(`Cancelled the pending wait of ${id}. Writer termination may remain unproven.`, "info");
1456
+ })
1457
+ .catch((error) => uiCtx?.ui.notify(`Cancellation failed for ${id}: ${String(error)}. The wait remains available for inspection and retry.`, "warning"));
1458
+ // The synchronous navigator must retain the row until the durable operation settles.
1459
+ return { action: "missing", id };
1390
1460
  }
1391
1461
  const outcome = executeNavigatorClose(id, {
1392
1462
  readMeta,
@@ -1414,6 +1484,8 @@ function statusTone(status: string): BackgroundWorkRow["statusTone"] {
1414
1484
  case "failed":
1415
1485
  case "lost": return "failed";
1416
1486
  case "held":
1487
+ case "waiting":
1488
+ case "cancelled":
1417
1489
  case "killed":
1418
1490
  case "orphaned": return "warning";
1419
1491
  default: return "muted";
@@ -1448,7 +1520,7 @@ function subagentWorkRows(now: number): BackgroundWorkRow[] {
1448
1520
  expiresAt: (() => {
1449
1521
  const meta = metaById.get(row.id);
1450
1522
  const endedAt = meta?.endedAt ?? meta?.lostAt;
1451
- return meta && !pendingNavigatorPark(meta) && isTerminalNavigatorStatus(effectiveStatus(meta)) && typeof endedAt === "number"
1523
+ return meta && isTerminalNavigatorStatus(row.status) && typeof endedAt === "number"
1452
1524
  ? endedAt + TERMINAL_NAVIGATOR_RETENTION_MS
1453
1525
  : undefined;
1454
1526
  })(),
@@ -1539,12 +1611,17 @@ function subagentWorkDetail(id: string, now: number, options?: { logTailLines?:
1539
1611
  { label: "id", value: detail.id },
1540
1612
  ...(detail.role ? [{ label: "role", value: String(detail.role) }] : []),
1541
1613
  { label: "model", value: detail.effort ? `${detail.model} · effort ${detail.effort}` : detail.model },
1614
+ ...(detail.assignment ? [
1615
+ { label: "revision", value: detail.assignment.revision },
1616
+ { label: "reason", value: detail.assignment.reason },
1617
+ { label: "process", value: `${detail.assignment.processStatus}; termination ${detail.assignment.termination}` },
1618
+ { label: "evidence", value: detail.assignment.evidence.join(", ") },
1619
+ ] : []),
1542
1620
  { label: "elapsed", value: detail.elapsed },
1543
1621
  { label: "tools", value: detail.currentTool ? `current ${detail.currentTool}` : (detail.tools || "(none)") },
1544
1622
  { label: "spend", value: detail.spend || "(none)" },
1545
1623
  ...(detail.park ? [
1546
1624
  { 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
1625
  ] : []),
1549
1626
  { label: "pid", value: detail.pid != null ? String(detail.pid) : "-" },
1550
1627
  { label: "pgid", value: detail.pgid != null ? String(detail.pgid) : "-" },
@@ -1560,7 +1637,7 @@ function subagentWorkDetail(id: string, now: number, options?: { logTailLines?:
1560
1637
  evidence: { label: "transcript", text: detail.output || "(no transcript yet)" },
1561
1638
  transcript: transcript.entries,
1562
1639
  transcriptDiagnostic: transcript.diagnostic,
1563
- footerActions: [detail.park ? "x cancel resume" : detail.status === "running" || detail.status === "orphaned" ? "x stop" : "x dismiss"],
1640
+ footerActions: [detail.park ? "x cancel resume" : detail.attemptStatus === "running" || detail.attemptStatus === "orphaned" ? "x stop" : "x dismiss"],
1564
1641
  };
1565
1642
  }
1566
1643
 
@@ -2228,17 +2305,21 @@ export default function (pi: ExtensionAPI) {
2228
2305
  childExtensionPath: childBridgeExtensionPath(selfDir()),
2229
2306
  });
2230
2307
  let resumeOrchestration: ResumeOrchestration | undefined;
2308
+ const notifyOwnedWait = (message: string, level: "warning" | "info" = "warning") => {
2309
+ try { uiCtx?.ui?.notify?.(message, level); } catch { /* no UI */ }
2310
+ };
2231
2311
  /**
2232
2312
  * Stop a continuation attempt only when this parent owns it and the token
2233
2313
  * published with it matches. A pid is never signalled on a guess.
2234
2314
  */
2235
2315
  const stopPublishedAttempt = createOwnedAttemptStopper();
2236
- cancelParkedForUi = (id, reason) => {
2316
+ cancelParkedForUi = async (id, reason) => {
2237
2317
  const parked = parkedWaitForRun(id);
2238
2318
  if (!parked) return false;
2239
- void cancelParkedWait(workerOperations.service, parked, reason, { stopAttempt: stopPublishedAttempt })
2240
- .catch(() => { /* the durable record keeps the wait visible */ })
2241
- .finally(() => syncHealthTicker());
2319
+ try {
2320
+ await cancelParkedWait(workerOperations.service, parked, reason, { stopAttempt: stopPublishedAttempt });
2321
+ if (parked.meta.assignment) enqueueCompletionCallback(pi, id);
2322
+ } finally { syncHealthTicker(); }
2242
2323
  return true;
2243
2324
  };
2244
2325
  const effectiveSettings = () => {
@@ -2615,8 +2696,10 @@ export default function (pi: ExtensionAPI) {
2615
2696
  resetChildEventLogCursor(id);
2616
2697
  resetParseRunCursor(id);
2617
2698
  }
2618
- const callbackOrigin = callbackOriginFromContext(ctx);
2619
- activeCallbackOrigin = callbackOrigin;
2699
+ const callbackOrigin = internal?.parkOwner
2700
+ ? { cwd: internal.parkOwner.workspace, sessionId: internal.parkOwner.sessionId }
2701
+ : callbackOriginFromContext(ctx);
2702
+ activeCallbackOrigin = callbackOriginFromContext(ctx);
2620
2703
 
2621
2704
  // Sandbox is opt-in. sandbox_dir moves the confinement + working
2622
2705
  // dir elsewhere. git_clone_workspace prepares a disposable clone with
@@ -2915,6 +2998,9 @@ export default function (pi: ExtensionAPI) {
2915
2998
  ...(bridgeEnabled ? [childBridgeExtensionPath(selfDir())] : []),
2916
2999
  ],
2917
3000
  runtimeRoots: [baseDir()],
3001
+ capturedDenyWrite: internal?.resumeWait
3002
+ ? (resume?.prior.operations?.policy.sandbox as WorkerSandboxAuthority | null)?.denyWrite
3003
+ : undefined,
2918
3004
  }) : undefined;
2919
3005
  launchScratch = taskRuntime?.policy.scratch;
2920
3006
  if (sandboxEnabled && !taskRuntime) throw new Error("Task sandbox has no workspace; refusing an unconfined child.");
@@ -2966,6 +3052,7 @@ export default function (pi: ExtensionAPI) {
2966
3052
  if (bridgeEnabled) {
2967
3053
  const workerPolicy = captureWorkerPolicy({
2968
3054
  sandbox: sandboxEnabled,
3055
+ mandatoryPermissions: permissionPlan.enforced,
2969
3056
  tools: selectedTools,
2970
3057
  clean,
2971
3058
  workspace: cwd,
@@ -3020,6 +3107,24 @@ export default function (pi: ExtensionAPI) {
3020
3107
  // The fence returns a synchronous release guard that is invoked with no
3021
3108
  // await between it and the spawn, so a cancellation or parent change
3022
3109
  // cannot hide inside a final asynchronous window.
3110
+ if (internal?.resumeWait && !resume?.prior.assignment) throw new PreSpawnResumeError("This legacy park has no verified assignment outcome recipient; refusing continuation on an unsupported binding.");
3111
+ const parent = ownerBindingFromContext(ctx);
3112
+ const assignment: AssignmentBinding | undefined = internal?.resumeWait && resume?.prior.assignment
3113
+ ? resume.prior.assignment
3114
+ : parent.sessionId && typeof ctx.sessionManager?.getBranch === "function" ? { version: 1, assignmentId: id,
3115
+ owner: { kind: "worker-conversation", sessionId, workspace: cwd, branchId: parent.branchId, goalId: parent.goalId },
3116
+ recipient: { kind: "parent-session", ...parent } } : undefined;
3117
+ if (!assignment && bridgeEnabled) throw new Error("Durable assignment outcomes require a recorded parent session and transcript capability.");
3118
+ if (assignment) registerAssignmentAttempt(assignment, id);
3119
+ if (internal?.resumeWait) {
3120
+ const captured = resume?.prior.operations?.policy;
3121
+ const currentSandbox = taskRuntime ? {
3122
+ root: taskRuntime.policy.root,
3123
+ ...(taskRuntime.policy.permissions ? { permissions: taskRuntime.policy.permissions } : {}),
3124
+ ...(taskRuntime.policy.denyWrite ? { denyWrite: [...taskRuntime.policy.denyWrite] } : {}),
3125
+ } : null;
3126
+ assertAssignmentPermissionScope(captured, { sandbox: currentSandbox, mandatoryPermissions: permissionPlan.enforced });
3127
+ }
3023
3128
  const dispatchGuard = await internal?.beforeSpawn?.({ runId: id, permissionPlan });
3024
3129
  spawned = releaseChild(dispatchGuard, () => spawnDetached({ file: cmd.file, fileArgs: cmd.fileArgs, cwd, logPath: logPathFor(id),
3025
3130
  env: {
@@ -3066,6 +3171,8 @@ export default function (pi: ExtensionAPI) {
3066
3171
  });
3067
3172
 
3068
3173
  const meta: RunMeta = {
3174
+ assignment,
3175
+ outcomeSupport: { version: 1, available: Boolean(assignment), ...(!assignment ? { reason: "Legacy host has no verified parent session/transcript; durable assignment delivery is unavailable." } : {}) },
3069
3176
  id, name: launchName, status: "running",
3070
3177
  pid: spawned.pid, spawnPid: process.pid, spawnPidStartTime: parentStartToken(), model,
3071
3178
  effort: thinking, cwd,
@@ -3103,6 +3210,7 @@ export default function (pi: ExtensionAPI) {
3103
3210
  ...(internal?.launchToken ? { resumeLaunchToken: internal.launchToken } : {}),
3104
3211
  policy: {
3105
3212
  version: 1 as const,
3213
+ mandatoryPermissions: workerBridge.policy.mandatoryPermissions,
3106
3214
  sandbox: workerBridge.policy.sandbox,
3107
3215
  tools: workerBridge.policy.tools,
3108
3216
  clean: workerBridge.policy.clean,
@@ -3257,16 +3365,16 @@ export default function (pi: ExtensionAPI) {
3257
3365
  plan = planContinuation({
3258
3366
  id: prior.id,
3259
3367
  prior,
3260
- origin: callbackOriginFromContext(ctx),
3368
+ origin: { cwd: input.park.record.ownerWorkspace ?? prior.callbackOrigin?.cwd ?? prior.cwd, sessionId: input.park.record.ownerSessionId ?? prior.callbackOrigin?.sessionId },
3261
3369
  others: listMetas(),
3262
3370
  });
3263
3371
  } catch (error) {
3264
3372
  throw new PreSpawnResumeError(error instanceof Error ? error.message : String(error));
3265
3373
  }
3266
3374
  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,
3375
+ sessionId: input.park.record.ownerSessionId ?? prior.callbackOrigin?.sessionId ?? "",
3376
+ workspace: input.park.record.ownerWorkspace ?? prior.callbackOrigin?.cwd ?? prior.cwd,
3377
+ branchId: input.park.record.ownerBranchId ?? null,
3270
3378
  goalId: input.park.record.ownerGoalId ?? null,
3271
3379
  };
3272
3380
  const target = plan;
@@ -3382,9 +3490,8 @@ export default function (pi: ExtensionAPI) {
3382
3490
  capacity: resumeCapacity(),
3383
3491
  launch: launchParkedResume,
3384
3492
  stopAttempt: stopPublishedAttempt,
3385
- notify: (message, level) => {
3386
- try { uiCtx?.ui?.notify?.(message, level); } catch { /* ignore UI failures */ }
3387
- },
3493
+ notifyWhen: (meta) => Boolean(activeCallbackOrigin && belongsToOrigin(meta, activeCallbackOrigin)),
3494
+ notify: notifyOwnedWait,
3388
3495
  });
3389
3496
  return resumeOrchestration;
3390
3497
  }
@@ -3409,10 +3516,13 @@ export default function (pi: ExtensionAPI) {
3409
3516
  try {
3410
3517
  await reconcileParkedWaits(service, {
3411
3518
  resume: (park) => orchestration.resume(park),
3412
- notify: (message) => {
3413
- try { uiCtx?.ui?.notify?.(message, "warning"); } catch { /* ignore UI failures */ }
3414
- },
3519
+ notifyWhen: (meta) => Boolean(activeCallbackOrigin && belongsToOrigin(meta, activeCallbackOrigin)),
3520
+ notify: notifyOwnedWait,
3415
3521
  });
3522
+ const historical = historicalWaits(activeCallbackOrigin);
3523
+ if (historical.length && activeCallbackOrigin && !attentionDismissed(activeCallbackOrigin.cwd, attentionRevision(historical))) {
3524
+ uiCtx?.ui?.notify?.(`${historical.length} historical subagent waits remain. Inspect or cancel with /subagents history; dismiss this notice with /subagents history dismiss.`, "warning");
3525
+ }
3416
3526
  } catch { /* reconciliation retries on the next session start */ }
3417
3527
  }
3418
3528
 
@@ -3860,6 +3970,20 @@ export default function (pi: ExtensionAPI) {
3860
3970
  // The foreground origin from session_start; otherwise the calling context's
3861
3971
  // own session. An unreadable session id stays unavailable (never cwd-wide).
3862
3972
  const toolSession = {
3973
+ inspectOutcome: (meta: RunMeta, params: Record<string, unknown>, callCtx?: unknown) => {
3974
+ if (params.disposition !== undefined && params.disposition !== "consumed" && params.disposition !== "dismissed") throw new Error("Outcome disposition must be consumed or dismissed.");
3975
+ if (!readOutcome(meta)) {
3976
+ if (params.disposition !== undefined || params.operation_id !== undefined) throw new Error("No committed terminal outcome is available for this assignment.");
3977
+ return null;
3978
+ }
3979
+ const context = (callCtx ?? uiCtx) as ExtensionContext;
3980
+ if (!context) throw new Error("Parent identity is unavailable.");
3981
+ return inspectOutcome(meta, { recipient: { kind: "parent-session", ...ownerBindingFromContext(context) }, permissions: currentSandboxPermissions(pi),
3982
+ branchIds: context.sessionManager.getBranch().map((entry) => entry.id),
3983
+ ...(typeof params.operation_id === "string" ? { operationId: params.operation_id } : {}),
3984
+ ...(typeof params.outcome_revision === "number" ? { revision: params.outcome_revision } : {}),
3985
+ ...(params.disposition === "consumed" || params.disposition === "dismissed" ? { disposition: params.disposition, note: String(params.note ?? "") } : {}) });
3986
+ },
3863
3987
  getActiveOrigin: (ctx?: unknown) => activeCallbackOrigin ?? verifiedOriginFromContext(ctx as ExtensionContext | undefined),
3864
3988
  };
3865
3989
  pi.registerTool(subagentListTool(Type, toolSession));
@@ -3876,23 +4000,25 @@ export default function (pi: ExtensionAPI) {
3876
4000
  enqueueCompletionCallback(pi, id);
3877
4001
  } });
3878
4002
  acceptanceStopToolRef = acceptanceStopTool;
3879
- // A parked assignment has no live child: `subagent_stop` is the explicit
3880
- // takeover that cancels its pending automatic resume, so the conversation can
3881
- // be continued manually. Without this, stop would report "not running" and
3882
- // leave the automatic resume armed for the same assignment.
4003
+ // A parked attempt may have exited, but its automatic resume is still armed.
4004
+ // Explicit stop must confirm durable cancellation, not just stop a process.
3883
4005
  const acceptanceStopToolWithParked = {
3884
4006
  ...acceptanceStopTool,
3885
4007
  async execute(toolCallId: string, params: unknown, signal?: AbortSignal, onUpdate?: unknown, ctx?: unknown) {
3886
4008
  const target = (params as { id?: unknown } | undefined)?.id;
3887
- if (typeof target === "string" && cancelParkedForUi?.(target, "cancelled by subagent_stop; the automatic resume is cancelled")) {
3888
- renderWidget();
3889
- syncHealthTicker();
3890
- return {
3891
- content: [{
3892
- type: "text",
3893
- text: `Cancelled the pending wait of parked subagent ${target}. Its conversation can now be continued with subagent_spawn session_id.`,
3894
- }],
3895
- };
4009
+ try {
4010
+ if (typeof target === "string" && await cancelParkedForUi?.(target, "cancelled by subagent_stop; the automatic resume is cancelled")) {
4011
+ renderWidget();
4012
+ syncHealthTicker();
4013
+ return {
4014
+ content: [{
4015
+ type: "text",
4016
+ text: `Durably cancelled the pending wait of parked subagent ${target}. Writer termination may remain unproven; ordinary continuation admission still applies.`,
4017
+ }],
4018
+ };
4019
+ }
4020
+ } catch (error) {
4021
+ return { isError: true, content: [{ type: "text", text: `Cancellation failed for ${target}: ${String(error)}. The retained wait remains available for inspection and retry.` }] };
3896
4022
  }
3897
4023
  return (acceptanceStopTool.execute as (
3898
4024
  id: string, p: unknown, s?: AbortSignal, u?: unknown, c?: unknown,
@@ -3980,15 +4106,42 @@ export default function (pi: ExtensionAPI) {
3980
4106
  pi.events?.emit("harness-settings:register", agentsContribution);
3981
4107
  };
3982
4108
  const unsubscribeSettingsRequest = pi.events?.on?.("harness-settings:request", registerSettings);
4109
+ const unsubscribeOutcomeWorkflow = pi.events?.on?.("pi-better-workflow:changed", () => recoverAssignmentOutcomes(pi));
3983
4110
  registerSettings();
3984
4111
 
3985
4112
  if (typeof pi.registerCommand === "function") {
3986
4113
  agentOperations.registerCommands(pi);
3987
4114
  pi.registerCommand("subagents", {
3988
- description: "[settings|mode manual|adaptive|coordinator|cap <number>|tool-wait <minutes>|stuck <minutes>|save|reset] — Subagent settings",
4115
+ description: "[history [dismiss]|settings|mode manual|adaptive|coordinator|cap <number>|tool-wait <minutes>|stuck <minutes>|save|reset] — Subagent management",
3989
4116
  getArgumentCompletions: subagentsArgumentCompletions,
3990
4117
  async handler(args, ctx) {
3991
4118
  const tokens = args.trim().split(/\s+/).filter(Boolean);
4119
+ if (tokens[0] === "history") {
4120
+ try {
4121
+ const origin = { cwd: ctx.cwd, sessionId: ctx.sessionManager.getSessionId() };
4122
+ const waits = historicalWaits(origin);
4123
+ if (tokens[1] === "dismiss") {
4124
+ dismissAttention(ctx.cwd, attentionRevision(waits));
4125
+ ctx.ui.notify("Historical attention notice dismissed. Waits and evidence are unchanged.", "info");
4126
+ return;
4127
+ }
4128
+ const labels = waits.map((p) => `${p.runId} · session ${p.record.ownerSessionId ?? "unknown"} · ${p.phase}`);
4129
+ const selected = await ctx.ui.select("Historical subagent waits", labels);
4130
+ const park = waits[labels.indexOf(selected ?? "")];
4131
+ if (!park) return;
4132
+ const action = await ctx.ui.select(`${park.runId} · session ${park.record.ownerSessionId ?? "unknown"}`, ["Inspect", "Cancel pending wait"]);
4133
+ if (action === "Inspect") {
4134
+ ctx.ui.notify(JSON.stringify({ runId: park.runId, originatingSession: park.record.ownerSessionId,
4135
+ workspace: park.record.ownerWorkspace, waitId: park.waitId, generation: park.generation,
4136
+ phase: park.phase, reason: park.record.heldReason, cancellation: park.record.cancelReason,
4137
+ resumedBy: park.record.resumedBy, log: park.meta.logPath }), "info");
4138
+ } else if (action === "Cancel pending wait" && await ctx.ui.confirm("Cancel pending wait?", `${park.runId} belongs to session ${park.record.ownerSessionId ?? "unknown"}. This does not prove its writer has stopped.`)) {
4139
+ if (!await cancelParkedForUi?.(park.runId, "explicit cancellation from historical management")) throw new Error("The pending wait changed; inspect it again.");
4140
+ ctx.ui.notify(`Durably cancelled the pending wait of ${park.runId}. Writer termination may remain unproven.`, "info");
4141
+ }
4142
+ } catch (error) { ctx.ui.notify(`Historical wait management failed: ${String(error)}. Inspect or retry with /subagents history.`, "warning"); }
4143
+ return;
4144
+ }
3992
4145
  if (tokens.length === 0 || (tokens.length === 1 && tokens[0] === "settings")) {
3993
4146
  await openSettings(ctx);
3994
4147
  return;
@@ -4038,7 +4191,7 @@ export default function (pi: ExtensionAPI) {
4038
4191
  changeTiming(key, minutes);
4039
4192
  ctx.ui.notify(`${tokens[0] === "tool-wait" ? "Tool-wait" : "No-progress"} alert: ${minutes} min (current session). Running subagents are unchanged.`, "info");
4040
4193
  } else {
4041
- ctx.ui.notify("Usage: /subagents [settings|mode manual|adaptive|coordinator|cap <number>|tool-wait <minutes>|stuck <minutes>|save|reset]", "warning");
4194
+ ctx.ui.notify("Usage: /subagents [history [dismiss]|settings|mode manual|adaptive|coordinator|cap <number>|tool-wait <minutes>|stuck <minutes>|save|reset]", "warning");
4042
4195
  }
4043
4196
  refreshBackgroundWorkNavigator(ctx);
4044
4197
  },
@@ -4097,6 +4250,7 @@ export default function (pi: ExtensionAPI) {
4097
4250
  mainAgentStartedAt = undefined;
4098
4251
  mainAgentTools.clear();
4099
4252
  refreshBackgroundWorkNavigator(ctx);
4253
+ recoverAssignmentOutcomes(pi);
4100
4254
  });
4101
4255
 
4102
4256
  pi.on("session_tree", async (_event, ctx) => {
@@ -4104,6 +4258,7 @@ export default function (pi: ExtensionAPI) {
4104
4258
  agentSessionSettings.restore(ctx);
4105
4259
  try { noteCatalogHost(catalogHostFrom(ctx)); } catch { /* catalog inspection stays undecided */ }
4106
4260
  restoreDelegationMode(ctx);
4261
+ recoverAssignmentOutcomes(pi);
4107
4262
  });
4108
4263
 
4109
4264
  // Capture a UI-bearing context and, if runs from a prior session are still
@@ -4114,6 +4269,7 @@ export default function (pi: ExtensionAPI) {
4114
4269
  // switch), so the previous session's teardown no longer applies: the
4115
4270
  // replacing session owns this instance's supervision loops (#625).
4116
4271
  sessionTornDown = false;
4272
+ outcomeHost = createOutcomeHost();
4117
4273
  setCallbackBatchContext(pi, ctx);
4118
4274
  agentSessionSettings.restore(ctx);
4119
4275
  restoreDelegationMode(ctx);
@@ -4172,6 +4328,8 @@ export default function (pi: ExtensionAPI) {
4172
4328
 
4173
4329
  // Tear down the timer and clear the widget when the session ends.
4174
4330
  pi.on("session_shutdown", async (event, ctx) => {
4331
+ closeOutcomeHost(outcomeHost);
4332
+ if (typeof unsubscribeOutcomeWorkflow === "function") unsubscribeOutcomeWorkflow();
4175
4333
  if (typeof unsubscribeSettingsRequest === "function") unsubscribeSettingsRequest();
4176
4334
  // #625: subagent children are detached process groups that outlive this
4177
4335
  // 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) {