pi-better-subagents 0.32.1 → 0.32.3

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
@@ -3233,18 +3233,13 @@ export default function (pi: ExtensionAPI) {
3233
3233
  // Register exit supervision before any fallible post-spawn publication.
3234
3234
  // A failed metadata write must not strand a running child without a close
3235
3235
  // handler; the lease stays held until that child has actually exited.
3236
- void spawned.exit.then((code) => {
3236
+ void spawned.exit.then(async (code) => {
3237
3237
  try { finalizeRun(pi, ctx, id, code); }
3238
3238
  finally { lease?.release(); }
3239
3239
  if (workerBridge) workerOperations.release(id, "attempt-exited");
3240
- // After the writer lease is free: a clean park may already have a
3241
- // ready dependency, and a failed park must hold its wait rather
3242
- // than leave an automatic resume armed.
3243
- void settleParkedExit(id);
3244
- // If this attempt was a published resume of an earlier parked
3245
- // assignment, an exit before acknowledgement must settle that
3246
- // unconsumed generation explicitly instead of leaving it resuming.
3247
- void settleResumedAttemptExit({
3240
+ // Reconcile this attempt's earlier published writer before its
3241
+ // next park can admit another continuation of the conversation.
3242
+ await settleResumedAttemptExit({
3248
3243
  attemptId: id,
3249
3244
  service: workerOperations.service,
3250
3245
  status: readMeta(id)?.status ?? "exited",
@@ -3255,6 +3250,7 @@ export default function (pi: ExtensionAPI) {
3255
3250
  try { uiCtx?.ui?.notify?.(message, "warning"); } catch { /* ignore UI failures */ }
3256
3251
  },
3257
3252
  });
3253
+ await settleParkedExit(id);
3258
3254
  });
3259
3255
  writeMeta(meta);
3260
3256
  committed = true;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-better-subagents",
3
- "version": "0.32.1",
3
+ "version": "0.32.3",
4
4
  "description": "Pi extension for detached, sandboxed subagent runs that keep the foreground session free.",
5
5
  "license": "MIT",
6
6
  "type": "module",
package/registry.ts CHANGED
@@ -385,6 +385,8 @@ export interface ParkRecord {
385
385
  */
386
386
  resumeClaimId?: string;
387
387
  resumeClaimToken?: string;
388
+ /** Exact claim whose writer exit has been reconciled with the coordinator. */
389
+ resumeExitReconciledClaimId?: string;
388
390
  cancelledAt?: number;
389
391
  cancelReason?: string;
390
392
  }
@@ -460,7 +462,8 @@ export function writeParkRecord(id: string, record: ParkRecord, options: { ifAbs
460
462
  const meta = readMeta(id);
461
463
  if (meta && (meta.park?.phase !== record.phase
462
464
  || meta.park?.heldReason !== record.heldReason
463
- || meta.park?.resumedBy !== record.resumedBy)) {
465
+ || meta.park?.resumedBy !== record.resumedBy
466
+ || meta.park?.resumeExitReconciledClaimId !== record.resumeExitReconciledClaimId)) {
464
467
  meta.park = record;
465
468
  writeMeta(meta);
466
469
  }
@@ -500,12 +503,21 @@ export function isPendingPark(record: Pick<ParkRecord, "phase">): boolean {
500
503
  * by resume reconciliation; a consumed or cancelled park is not included.
501
504
  */
502
505
  export function listPendingParkedRuns(metas: readonly RunMeta[] = listMetas()): RunMeta[] {
503
- return metas.filter((meta) => {
506
+ return listParkRecordCandidates(metas).filter((meta) => {
504
507
  const record = meta.park ?? readParkRecord(meta.id);
505
508
  return record !== undefined && isPendingPark(record);
506
509
  });
507
510
  }
508
511
 
512
+ /** Include a park file that was published just before its metadata mirror was lost. */
513
+ export function listParkRecordCandidates(metas: readonly RunMeta[] = listMetas()): RunMeta[] {
514
+ let volatileIds: Set<string>;
515
+ try { volatileIds = new Set(readdirSync(join(baseDir(), "runs"))); }
516
+ catch { volatileIds = new Set(); }
517
+ return metas.filter((meta) => meta.park !== undefined
518
+ || (volatileIds.has(meta.id) && existsSync(parkRecordPath(meta.id))));
519
+ }
520
+
509
521
  /**
510
522
  * How long a launch attempt that never produced a child is kept before a sweep
511
523
  * reclaims it. Launch preparation takes seconds; the grace only exists so a
@@ -24,11 +24,12 @@ import { StoreError } from "./errors.ts";
24
24
  import {
25
25
  dependencyState,
26
26
  mapOutbox,
27
+ ownerFromRow,
27
28
  readOperationEvidence,
28
29
  readOutboxRow,
29
30
  requireWaitRow,
30
31
  } from "./rows.ts";
31
- import { columnJson, columnNullableText, columnText, getRows, run, type StoreContext } from "./sqlite.ts";
32
+ import { columnJson, columnNullableText, columnNumber, columnText, getRows, run, type StoreContext } from "./sqlite.ts";
32
33
  import type {
33
34
  ClaimOutboxInput,
34
35
  OutboxDispatchClaim,
@@ -280,6 +281,23 @@ export function listOutbox(ctx: StoreContext, filter: OutboxFilter = {}): Outbox
280
281
  ).map((row) => mapOutbox(ctx, row));
281
282
  }
282
283
 
284
+ /** Find recipients with deliverable dependencies without loading each event's evidence. */
285
+ export function listDispatchableOutboxRecipients(ctx: StoreContext): Array<{ recipient: OwnerIdentity; count: number }> {
286
+ return getRows(
287
+ ctx,
288
+ `SELECT recipient_kind, recipient_session_id, recipient_workspace, recipient_branch_id, recipient_goal_id,
289
+ count(*) AS pending_count
290
+ FROM outbox_events
291
+ WHERE state = 'pending' AND event_type = 'dependency-ready'
292
+ AND EXISTS (SELECT 1 FROM waits w WHERE w.wait_id = outbox_events.wait_id
293
+ AND w.generation = outbox_events.generation
294
+ AND w.phase IN (${placeholders(DELIVERABLE_WAIT_PHASES.length)}))
295
+ GROUP BY recipient_kind, recipient_session_id, recipient_workspace, recipient_branch_id, recipient_goal_id
296
+ ORDER BY min(created_at), min(event_id)`,
297
+ ...DELIVERABLE_WAIT_PHASES,
298
+ ).map((row) => ({ recipient: ownerFromRow(row, "recipient"), count: columnNumber(row, "pending_count") }));
299
+ }
300
+
283
301
  function readDispatchClaim(row: Record<string, unknown>): OutboxDispatchClaim | null {
284
302
  return columnJson<OutboxDispatchClaim>(row, "dispatch_claim_json");
285
303
  }
@@ -58,6 +58,7 @@ import {
58
58
  } from "./waits.ts";
59
59
  import {
60
60
  claimOutbox as writeOutboxClaim,
61
+ listDispatchableOutboxRecipients as readDispatchableOutboxRecipients,
61
62
  listOutbox as readOutbox,
62
63
  markOutboxDelivered as writeOutboxDelivery,
63
64
  releaseOutbox as writeOutboxRelease,
@@ -272,6 +273,8 @@ export interface Store {
272
273
  // ---- outbox ----
273
274
 
274
275
  listOutbox(filter?: OutboxFilter): OutboxEventRecord[];
276
+ /** Lightweight dispatch candidates; evidence is read only after a claim succeeds. */
277
+ listDispatchableOutboxRecipients(): Array<{ recipient: OwnerIdentity; count: number }>;
275
278
  /** Claim pending deliveries for a `ready`/`resuming` generation. */
276
279
  claimOutbox(input: ClaimOutboxInput): OutboxEventRecord[];
277
280
  /** Mark a claimed delivery delivered; the result is still unconsumed. */
@@ -457,6 +460,10 @@ export function openStore(options: StoreOptions): Store {
457
460
  alive();
458
461
  return readOutbox(ctx, filter);
459
462
  },
463
+ listDispatchableOutboxRecipients() {
464
+ alive();
465
+ return readDispatchableOutboxRecipients(ctx);
466
+ },
460
467
  claimOutbox(input) {
461
468
  alive();
462
469
  return writeOutboxClaim(ctx, input);
@@ -484,7 +484,7 @@ export interface ReleaseResumeClaimResult {
484
484
  }
485
485
 
486
486
  /**
487
- * Proof that the published resume attempt can never interpret the generation:
487
+ * Proof that the published resume attempt can no longer write the conversation:
488
488
  * its writer process is gone and its conversation writer lease is free. A live
489
489
  * writer or an unverifiable identity must never be passed here.
490
490
  */
@@ -499,6 +499,8 @@ export interface ResumeAttemptExitProof {
499
499
  * evidence pins stay, and the generation remains visible to its owner. The claim
500
500
  * is invalidated (it can never publish again), which is what makes a second
501
501
  * automatic attempt impossible.
502
+ * If interpretation already consumed the wait, exact exit proof only invalidates
503
+ * the published writer claim and preserves the interpretation receipt.
502
504
  */
503
505
  export interface HoldFailedResumeInput {
504
506
  waitId: string;
@@ -508,7 +510,7 @@ export interface HoldFailedResumeInput {
508
510
  attemptId: string;
509
511
  launchToken: string;
510
512
  proof: ResumeAttemptExitProof;
511
- /** Why the attempt never interpreted the generation; retained on both records. */
513
+ /** Exit reason; a consumed generation's receipt is preserved. */
512
514
  reason: string;
513
515
  }
514
516
 
@@ -913,10 +913,14 @@ export function holdFailedResume(
913
913
 
914
914
  return ctx.transaction(() => {
915
915
  const terminal = getRow(ctx, "SELECT assignment_id FROM assignment_outcome_waits WHERE wait_id = ? AND generation = ?", waitId, generation);
916
- if (terminal) {
916
+ const recorded = requireWait(ctx, waitId, generation);
917
+ // Interpretation ends the wait, but its writer may continue until exit.
918
+ // Exact exit proof releases only that writer's claim, preserving the receipt.
919
+ if (terminal || recorded.phase === "consumed") {
917
920
  const claim = requireClaim(ctx, claimId);
918
921
  if (claim.waitId !== waitId || claim.generation !== generation || claim.claimToken !== claimToken
919
922
  || claim.attemptId !== attemptId || claim.launchToken !== launchToken) throw new StoreError("claim-state", "Terminal writer exit proof does not match the published attempt.");
923
+ if (!terminal && claim.cancelEpoch !== recorded.cancelEpoch) throw new StoreError("stale-cancel-epoch", "Writer exit proof belongs to a different cancellation epoch.");
920
924
  const applied = claim.state === "published";
921
925
  if (applied) run(ctx, "UPDATE resume_claims SET state = 'invalidated', invalidated_at = ?, reason = ? WHERE claim_id = ?", ctx.now(), reason, claimId);
922
926
  return { wait: requireWait(ctx, waitId, generation), claim: requireClaim(ctx, claimId), applied };
package/worker-waits.ts CHANGED
@@ -61,6 +61,7 @@ import { commitAssignmentTerminal } from "./assignment-outcomes.ts";
61
61
  import {
62
62
  effectiveStatus,
63
63
  isPendingPark,
64
+ listParkRecordCandidates,
64
65
  listMetas,
65
66
  listPendingParkedRuns,
66
67
  readMeta,
@@ -2278,7 +2279,7 @@ export async function recoverStagedPark(
2278
2279
  /** Every park record (any phase) that published `attemptId` as its resume. */
2279
2280
  export function parkedWaitsForResumedAttempt(attemptId: string): ParkedWait[] {
2280
2281
  const found: ParkedWait[] = [];
2281
- for (const meta of listMetas()) {
2282
+ for (const meta of listParkRecordCandidates()) {
2282
2283
  const record = readParkRecord(meta.id);
2283
2284
  if (!record || record.resumedBy !== attemptId) continue;
2284
2285
  found.push(parkedEntry(meta, record));
@@ -2339,24 +2340,31 @@ export function conversationWriterLeaseLive(
2339
2340
  * ambiguous identity (live or unverifiable writer, live lease, missing claim
2340
2341
  * identity, missing host capability) is reported as a local hold and the durable
2341
2342
  * generation is left untouched with its live writer — never a fallback cancel.
2343
+ * An interpreted generation needs only claim cleanup; its receipt and assignment
2344
+ * remain unchanged, even if writer exit cannot yet be proved.
2342
2345
  */
2343
2346
  export async function settleResumedAttemptExit(input: ResumedAttemptExitInput): Promise<ResumedAttemptExitResult> {
2344
- const candidates = parkedWaitsForResumedAttempt(input.attemptId);
2347
+ return settleResumedAttemptExitForParks(input, parkedWaitsForResumedAttempt(input.attemptId));
2348
+ }
2349
+
2350
+ async function settleResumedAttemptExitForParks(input: ResumedAttemptExitInput, candidates: readonly ParkedWait[]): Promise<ResumedAttemptExitResult> {
2345
2351
  if (candidates.length === 0) return { outcome: "ignored" };
2346
2352
  const attempt = readMeta(input.attemptId);
2347
2353
  const at = (input.now ?? Date.now)();
2348
2354
  let result: ResumedAttemptExitResult = { outcome: "ignored" };
2349
2355
  for (const park of candidates) {
2350
- if (park.record.phase === "consumed" || (park.record.phase === "cancelled" && !park.meta.assignment)) {
2356
+ if ((park.record.phase === "consumed" && park.record.resumeClaimId && park.record.resumeExitReconciledClaimId === park.record.resumeClaimId)
2357
+ || (park.record.phase === "cancelled" && !park.meta.assignment)) {
2351
2358
  result = { outcome: "ignored", waitPhase: park.record.phase };
2352
2359
  continue;
2353
2360
  }
2354
- const reason = input.reason
2355
- ?? `the published resume attempt ${input.attemptId} exited (${input.status ?? attempt?.status ?? "unknown"}) without interpreting the wait`;
2361
+ let interpreted = park.record.phase === "consumed";
2362
+ const exitReason = `the published resume attempt ${input.attemptId} exited (${input.status ?? attempt?.status ?? "unknown"})`;
2363
+ let reason = input.reason ?? `${exitReason}${interpreted ? "" : " without interpreting the wait"}`;
2356
2364
  const holdLocally = (cause: string, outcome: "deferred" | "settled" = "deferred"): void => {
2357
- updateParkRecord(park.runId, { phase: park.record.phase === "cancelled" ? "cancelled" : "held", heldReason: `${reason}; ${cause}` });
2365
+ updateParkRecord(park.runId, { phase: interpreted ? "consumed" : park.record.phase === "cancelled" ? "cancelled" : "held", heldReason: `${reason}; ${cause}` });
2358
2366
  const report = attempt ?? park.meta;
2359
- if (input.service && report.assignment) {
2367
+ if (!interpreted && input.service && report.assignment) {
2360
2368
  commitAssignmentTerminal({ ...report, status: "lost", failureReason: `${reason}; ${cause}` }, true);
2361
2369
  }
2362
2370
  result = { outcome, reason };
@@ -2385,6 +2393,20 @@ export async function settleResumedAttemptExit(input: ResumedAttemptExitInput):
2385
2393
  retainUnverified("the Background operation service is unavailable");
2386
2394
  continue;
2387
2395
  }
2396
+ const scope = backgroundScopeForMeta(park.meta, park.record);
2397
+ if (!scope) {
2398
+ holdLocally("the parked attempt records no worker conversation scope");
2399
+ continue;
2400
+ }
2401
+ let wait: WorkerWaitView | undefined;
2402
+ try {
2403
+ wait = input.service.listWorkerWaits(scope).find((w) => w.waitId === park.waitId && w.generation === park.generation);
2404
+ interpreted = wait?.phase === "consumed" || interpreted;
2405
+ if (interpreted && !input.reason) reason = exitReason;
2406
+ } catch (error) {
2407
+ retainUnverified(`the coordinator could not verify the wait (${reasonOf(error)})`);
2408
+ continue;
2409
+ }
2388
2410
  if (typeof input.service.holdFailedResumeForWorker !== "function") {
2389
2411
  holdLocally("this Background host has no proven-exit hold capability yet");
2390
2412
  continue;
@@ -2415,15 +2437,9 @@ export async function settleResumedAttemptExit(input: ResumedAttemptExitInput):
2415
2437
  holdLocally("a live conversation writer lease still holds the history, so writer exit is unproven");
2416
2438
  continue;
2417
2439
  }
2418
- const scope = backgroundScopeForMeta(park.meta, park.record);
2419
- if (!scope) {
2420
- holdLocally("the parked attempt records no worker conversation scope");
2421
- continue;
2422
- }
2423
2440
  try {
2424
- const wait = input.service.listWorkerWaits(scope).find((w) => w.waitId === park.waitId && w.generation === park.generation);
2425
2441
  // A held terminal writer needs proof-only reconciliation, not admission.
2426
- const reconcileOnly = park.record.phase === "cancelled" || wait?.phase === "held";
2442
+ const reconcileOnly = interpreted || park.record.phase === "cancelled" || wait?.phase === "held";
2427
2443
  if (!reconcileOnly && attempt.assignment && !input.service.repairFailedResumeForWorker) {
2428
2444
  holdLocally("this Background host does not support bounded autonomous repair");
2429
2445
  continue;
@@ -2456,9 +2472,11 @@ export async function settleResumedAttemptExit(input: ResumedAttemptExitInput):
2456
2472
  const phase = phaseOf(held.phase);
2457
2473
  updateParkRecord(park.runId, {
2458
2474
  phase: park.record.phase === "cancelled" ? "cancelled" : phase,
2475
+ resumeExitReconciledClaimId: claimId,
2476
+ ...(phase === "consumed" ? { heldReason: undefined } : {}),
2459
2477
  ...(phase === "held" && park.record.phase !== "cancelled" ? { heldReason: reason } : {}),
2460
2478
  });
2461
- input.notify?.(`Subagent ${park.runId}: ${reason}. The reconciled wait is ${phase}.`, "warning");
2479
+ if (phase !== "consumed") input.notify?.(`Subagent ${park.runId}: ${reason}. The reconciled wait is ${phase}.`, "warning");
2462
2480
  result = { outcome: "settled", waitPhase: phase, reason };
2463
2481
  } catch (error) {
2464
2482
  // The store refused (stale identity, terminal generation, unproven exit).
@@ -2520,8 +2538,8 @@ export async function reconcileParkedWaits(
2520
2538
  }
2521
2539
  const cached = readParkRecord(report.meta.id);
2522
2540
  const cancelled = (cached ?? report.record).phase === "cancelled";
2523
- if (cancelled && report.attempt && current.publishedClaimId === report.record.resumeClaimId) {
2524
- // Cancellation invalidates execution admission, not exact writer-exit proof.
2541
+ if ((cancelled || current.phase === "consumed") && report.attempt && current.publishedClaimId === report.record.resumeClaimId) {
2542
+ // Terminal waits still retain independent writer-exit proof.
2525
2543
  if (!readMeta(report.meta.id)) writeMeta(report.meta, { ifAbsent: true });
2526
2544
  if (!cached) writeParkRecord(report.meta.id, report.record, { ifAbsent: true });
2527
2545
  if (!readMeta(report.attempt.id)) writeMeta(report.attempt, { ifAbsent: true });
@@ -2568,13 +2586,26 @@ export async function reconcileParkedWaits(
2568
2586
  options.notify?.(`Degraded supervision: outage replay unavailable (${reasonOf(error)}).`, "warning");
2569
2587
  }
2570
2588
  }
2571
- for (const park of parkedWaits()) {
2589
+ // Consumed waits cannot resume, but a missed exit observer may have left
2590
+ // their published writer claim behind. Reconcile that exact claim once.
2591
+ const candidates: ParkedWait[] = [];
2592
+ for (const meta of listParkRecordCandidates()) {
2593
+ const snapshot = meta.park ?? readParkRecord(meta.id);
2594
+ if (!snapshot || (!isPendingPark(snapshot) && !(snapshot.phase === "consumed" && snapshot.resumedBy
2595
+ && snapshot.resumeClaimId && snapshot.resumeExitReconciledClaimId !== snapshot.resumeClaimId))) continue;
2596
+ const record = readParkRecord(meta.id);
2597
+ if (record) candidates.push(parkedEntry(meta, record));
2598
+ }
2599
+ // Release earlier writers before admitting later waits in the conversation.
2600
+ candidates.sort((a, b) => a.record.parkedAt - b.record.parkedAt);
2601
+ for (const park of candidates) {
2572
2602
  const options = scopedOptions(park.meta);
2573
2603
  try {
2574
- if (park.record.phase === "resuming") {
2604
+ if (park.record.phase === "resuming" || park.record.phase === "consumed") {
2575
2605
  const attemptId = park.record.resumedBy ?? "";
2576
2606
  const attempt = attemptId ? readMeta(attemptId) : undefined;
2577
2607
  if (!attemptId || !attempt) {
2608
+ if (park.record.phase === "consumed") { skipped += 1; continue; }
2578
2609
  updateParkRecord(park.runId, {
2579
2610
  phase: "held",
2580
2611
  heldReason: `Resume attempt ${attemptId || "(unknown)"} was published but launch and writer identity remain unproven.`,
@@ -2587,19 +2618,21 @@ export async function reconcileParkedWaits(
2587
2618
  held += 1;
2588
2619
  continue;
2589
2620
  }
2590
- // The published attempt already ended without acknowledging: settle the
2591
- // unconsumed generation now instead of leaving it `resuming` forever.
2592
- if (isTerminalAttempt(attempt)) {
2593
- const settled = await settleResumedAttemptExit({
2621
+ // A missed exit needs either unconsumed-wait recovery or proof-only
2622
+ // cleanup of a consumed wait's writer claim.
2623
+ const consumedWriterGone = park.record.phase === "consumed" && attempt.pid > 0 && writerPresence(attempt) === "absent";
2624
+ if (isTerminalAttempt(attempt) || consumedWriterGone) {
2625
+ const settled = await settleResumedAttemptExitForParks({
2594
2626
  attemptId,
2595
2627
  service,
2596
2628
  status: effectiveStatus(attempt),
2597
2629
  ...(options.notify ? { notify: options.notify } : {}),
2598
- });
2599
- if (settled.outcome === "settled") held += 1;
2630
+ }, [park]);
2631
+ if (settled.outcome === "settled" && settled.waitPhase !== "consumed") held += 1;
2600
2632
  else skipped += 1;
2601
2633
  continue;
2602
2634
  }
2635
+ if (park.record.phase === "consumed") { skipped += 1; continue; }
2603
2636
  }
2604
2637
  if (!service) {
2605
2638
  let reason = "Coordinator state is unverified; awaiting compatible supervision.";
@@ -2628,6 +2661,10 @@ export async function reconcileParkedWaits(
2628
2661
  }
2629
2662
  if (wait.phase === "consumed" || wait.phase === "cancelled") {
2630
2663
  updateParkRecord(park.runId, { phase: phaseOf(wait.phase), heldReason: undefined });
2664
+ if (wait.phase === "consumed" && park.record.resumedBy) {
2665
+ await settleResumedAttemptExitForParks({ attemptId: park.record.resumedBy, service,
2666
+ ...(options.notify ? { notify: options.notify } : {}) }, [park]);
2667
+ }
2631
2668
  skipped += 1;
2632
2669
  continue;
2633
2670
  }
@@ -2638,12 +2675,12 @@ export async function reconcileParkedWaits(
2638
2675
  const attemptId = park.record.resumedBy ?? "";
2639
2676
  const attempt = attemptId ? readMeta(attemptId) : undefined;
2640
2677
  if (!attempt || isTerminalAttempt(attempt)) {
2641
- const settled = await settleResumedAttemptExit({
2678
+ const settled = await settleResumedAttemptExitForParks({
2642
2679
  attemptId: attemptId || park.runId,
2643
2680
  service,
2644
2681
  status: attempt ? effectiveStatus(attempt) : "missing",
2645
2682
  ...(options.notify ? { notify: options.notify } : {}),
2646
- });
2683
+ }, [park]);
2647
2684
  // `deferred` means the local record was held while the durable
2648
2685
  // generation could not be proven (ambiguous identity/capability);
2649
2686
  // it is never a silent success.