pi-durable-subagents 1.4.3 → 1.5.1

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/CHANGELOG.md CHANGED
@@ -1,5 +1,15 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.5.1
4
+
5
+ - A worktree on an unexpected branch or detached HEAD can no longer block unrelated workflows during startup recovery. If the call already succeeded, recovery keeps its result and files and records one notice that survives restarts. The notice identifies the call, path, expected branch and actual checkout (#10).
6
+
7
+ ## 1.5.0
8
+
9
+ - The `durable-subagents:activity` event includes `costUsd`, the sum of recorded costs for the session's retained workflows, including finished runs. Status bars receive a new event when spend changes (#6).
10
+ - Parallel and chained calls with `isolation: "worktree"` can create a Git branch for generated keys such as `tasks:0`. Each key gets a distinct branch, including when the workflow also has a key named `tasks-0` (#8).
11
+ - The CLI guide explains how to start a run whose completion wakes the main pi session (#9).
12
+
3
13
  ## 1.4.3
4
14
 
5
15
  - Startup: agent discovery no longer starts `npm root -g` every time (issue #5). Each pi start, run admission and CLI
package/README.md CHANGED
@@ -597,17 +597,19 @@ tell that work goes on after the main agent settles:
597
597
 
598
598
  ```ts
599
599
  pi.events.on("durable-subagents:activity", data => {
600
- const { sessionId, busy, working, asking, queued, paused } = data as {
601
- sessionId: string; busy: boolean; working: number; asking: number; queued: number; paused: number;
600
+ const { sessionId, busy, working, asking, queued, paused, costUsd } = data as {
601
+ sessionId: string; busy: boolean; working: number; asking: number; queued: number; paused: number; costUsd: number;
602
602
  };
603
603
  });
604
604
  ```
605
605
 
606
606
  The counts are this session's live calls by state, the same as the summary
607
607
  line above the editor. `busy` is true while any call works, asks or waits
608
- for a slot; paused work alone is not busy. The first state is sent when the
609
- session starts, then only changes, and every count at zero when the session
610
- ends with work still counted.
608
+ for a slot; paused work alone is not busy. `costUsd` is what this session's
609
+ workflows have spent so far, finished ones included, so a status bar can show
610
+ subagent spend next to pi's own cost; a pruned workflow no longer counts. The
611
+ first state is sent when the session starts, then only changes, and every
612
+ count at zero (the spend kept) when the session ends with work still counted.
611
613
 
612
614
  ## Your pi-subagents scripts, unchanged
613
615
 
@@ -950,7 +952,9 @@ any row; the run still belongs to its sender: that session's main agent gets
950
952
  no completion notices for it, quitting that pi does not pause it, and the
951
953
  session is not part of the content, so a retry from another session gets the
952
954
  first outcome. An invalid `--session` exits 1; an invalid inherited value
953
- is ignored.
955
+ is ignored. To have the main agent receive a completion notice, start the run
956
+ with the `subagents` tool in that pi session. `--wake caller` delivers to the
957
+ subagent call that launched a CLI run (see above).
954
958
 
955
959
  When an unsealed call does not move, its `waiting` in `describe` adds
956
960
  `reason`, `detail` (the status line for that cause, e.g. `waiting for a slot:
@@ -70,7 +70,7 @@ export function registerMain(pi, ui) {
70
70
  let ctx, sender = "", outbox;
71
71
  let queue = Promise.resolve(), timer;
72
72
  let reserved = [], notes = [], stopped = true, lastStarter = 0;
73
- let polling = false, lastActivity = "", activityAt = 0;
73
+ let polling = false, lastActivity = "", lastCostUsd = 0, activityAt = 0;
74
74
  const failures = new BackgroundFailures();
75
75
  const pendingReader = new PendingOutboxReader();
76
76
  const sink = (text) => { notes.push(text); };
@@ -107,12 +107,15 @@ export function registerMain(pi, ui) {
107
107
  const events = pi.events;
108
108
  if (typeof events?.emit !== "function" || !sender)
109
109
  return;
110
- const counts = sessionEnds ? { working: 0, asking: 0, queued: 0, paused: 0 } : activityCounts(ownWorkflows(home, sender));
111
- const activity = { sessionId: sender.slice("main:".length), busy: counts.working + counts.asking + counts.queued > 0, ...counts };
110
+ const workflows = sessionEnds ? [] : ownWorkflows(home, sender);
111
+ const counts = sessionEnds ? { working: 0, asking: 0, queued: 0, paused: 0 } : activityCounts(workflows);
112
+ const costUsd = sessionEnds ? lastCostUsd : workflows.reduce((sum, w) => sum + (w.usage?.costUsd ?? 0), 0);
113
+ const activity = { sessionId: sender.slice("main:".length), busy: counts.working + counts.asking + counts.queued > 0, ...counts, costUsd };
112
114
  const key = JSON.stringify(activity);
113
115
  if (key === lastActivity || (sessionEnds && !lastActivity))
114
116
  return;
115
117
  lastActivity = key;
118
+ lastCostUsd = costUsd;
116
119
  try {
117
120
  events.emit(ACTIVITY_CHANNEL, activity);
118
121
  }
@@ -199,6 +202,7 @@ export function registerMain(pi, ui) {
199
202
  notes = [];
200
203
  ctx = undefined;
201
204
  lastActivity = "";
205
+ lastCostUsd = 0;
202
206
  failures.ok();
203
207
  }
204
208
  async function start(context) {
@@ -56,13 +56,41 @@ async function branchHead(cwd, branch) {
56
56
  throw error;
57
57
  }
58
58
  }
59
+ /** What a registered worktree holds now, for a person: its branch (or a detached HEAD) and its commit. */
60
+ function holdText(tree) {
61
+ const at = tree.HEAD ? ` at ${tree.HEAD}` : "";
62
+ return tree.branch ? `${tree.branch.replace(/^refs\/heads\//, "")}${at}` : tree.detached !== undefined ? `a detached HEAD${at}` : `no branch${at}`;
63
+ }
64
+ /** P32: An identity mismatch names the call, the workflow, the path and both identities, so a person can repair the path;
65
+ * this process never moves a worktree, a branch or a file to make them agree. */
66
+ function identityConflict(t, path, branch, head, tree) {
67
+ return `Worktree identity conflict: ${t.callId} (workflow ${t.wid}) needs its worktree ${path} on ${branch}${head ? ` at ${head}` : ""}, ` +
68
+ `but the path holds ${holdText(tree)}`;
69
+ }
70
+ /** P32: What to advise a person. It names the path and the branch but never spells out a shell command: either may hold
71
+ * spaces or characters a shell would interpret, so the operator repairs the path with their own quoting. */
72
+ function repairAdvice(path, branch, kept) {
73
+ const inspect = `Check what ${path} holds and keep anything you need`;
74
+ return kept
75
+ ? `${inspect}. The worktree and its branch were kept, nothing was removed, and this call's sealed result is unchanged; ` +
76
+ `restore the path on ${branch} (or remove that worktree once its changes are preserved) and this note is no longer needed`
77
+ : `${inspect}. The call failed and the path, its files and its branches were left untouched: restore the path on ${branch}, ` +
78
+ `or remove that worktree once its changes are preserved, and run the call again`;
79
+ }
59
80
  /** P32: Commit creation intent and reconcile Git's worktree registry and branch identity. */
60
81
  export async function prepareWorktree(t) {
61
82
  if (t.spec.isolation !== "worktree")
62
83
  return t.cwd;
63
84
  let intent = records(t, "wt-intent")[0];
64
85
  if (!intent) {
65
- const root = resolve(t.cwd, ".dsa", t.wid), path = resolve(root, t.key), branch = `dsa/${t.wid}/${t.key}`;
86
+ const root = resolve(t.cwd, ".dsa", t.wid), path = resolve(root, t.key);
87
+ // Colon keys could never create a branch in the original namespace. Give them their own namespace so
88
+ // existing literal keys (including percent-encoded spellings) retain their branches across upgrades.
89
+ const branch = t.key.includes(":")
90
+ ? `dsa-colon/${t.wid}/${contentHash(t.key)}`
91
+ : `dsa/${t.wid}/${t.key}`;
92
+ if (t.key.split("/").some(part => !part || part === "." || part === ".."))
93
+ throw new Error("Invalid worktree key");
66
94
  if (!path.startsWith(root + sep))
67
95
  throw new Error("Invalid worktree key");
68
96
  await git(t.cwd, "check-ref-format", "--branch", branch);
@@ -77,8 +105,11 @@ export async function prepareWorktree(t) {
77
105
  return path;
78
106
  const tree = (await worktree(t.cwd, path)), head = await branchHead(t.cwd, branch);
79
107
  if (tree) {
108
+ // A path someone else moved fails this call only, before anything runs: the worktree is never re-created or moved
109
+ // over what it holds (its files and branch stay for the person to repair).
80
110
  if (tree.branch !== `refs/heads/${branch}` || tree.HEAD !== head)
81
- throw new Error(`Worktree identity conflict: ${path}`);
111
+ throw new Error(`${identityConflict(t, path, branch, head, tree)}. ` +
112
+ `${repairAdvice(path, branch, false)}`);
82
113
  }
83
114
  else {
84
115
  if (head) {
@@ -105,8 +136,16 @@ export async function cleanWorktree(t) {
105
136
  await t.journal.append("wt-removed", { call: t.callId });
106
137
  return;
107
138
  }
108
- if (tree.branch !== `refs/heads/${intent.branch}` || tree.HEAD !== await branchHead(t.cwd, String(intent.branch)))
109
- throw new Error(`Worktree identity conflict: ${path}`);
139
+ const head = await branchHead(t.cwd, String(intent.branch));
140
+ if (tree.branch !== `refs/heads/${intent.branch}` || tree.HEAD !== head) {
141
+ // The call already sealed ok: its result is final, and removing or moving anything would discard what the path
142
+ // holds, while throwing here would fail this call's recovery on every start. The note is an `unknown` item (like a
143
+ // dirty keep), not a `conflict` reminder: no cross-call contention is open, so it does not hold the workflow open.
144
+ await attention(t, "worktree-conflict", `${identityConflict(t, path, String(intent.branch), head, tree)}. ` +
145
+ `${repairAdvice(path, String(intent.branch), true)}`);
146
+ await t.journal.append("wt-kept", { call: t.callId });
147
+ return;
148
+ }
110
149
  if (await git(path, "status", "--porcelain", "--untracked-files=all")) {
111
150
  await attention(t, "worktree", `Dirty worktree kept: ${path}`);
112
151
  await t.journal.append("wt-kept", { call: t.callId });
@@ -53,7 +53,7 @@ import { availableMemory } from "./memory.js";
53
53
  import { reached, sessionUsage, totalUsage } from "./usage.js";
54
54
  import { indexSweep, seededSweep, recordFenceFailure, resolveFenceAttention, serialContainment, skipLostCandidate, sweepExecutions } from "./sweep.js";
55
55
  import { gateRetired } from "./effects/gate.js";
56
- import { WorktreeIndex, worktreeCalls, worktreeLabel, worktreePair, worktreeRoots } from "./worktree.js";
56
+ import { WorktreeIndex, isWorktreeConflict, worktreeCalls, worktreeLabel, worktreePair, worktreeRoots } from "./worktree.js";
57
57
  import { failedModel, modelFailures, MODEL_RETRY_MS, parentPinned, spillCandidates } from "./pool.js";
58
58
  import { PENDING_NOTE, UNDELIVERED_FOLLOW_UP } from "../notes.js";
59
59
  import { COMMAND_LOG, exitMeaning, readExitRecord, readTail, spawnCommand } from "../../platform/command.js";
@@ -531,6 +531,10 @@ export default function createExecutor(ledgers, options = {}) {
531
531
  for (const { item } of attentionEntries(journal.entries())) {
532
532
  if (item.kind === "finished" || item.id === `unknown:${call}` || item.id.startsWith("fence:"))
533
533
  continue;
534
+ // P32: the identity-conflict note reports what a kept worktree holds; the call ending repairs nothing, so a seal or a
535
+ // recovery leaves it open for the person to see and act on.
536
+ if (isWorktreeConflict(item.id, call))
537
+ continue;
534
538
  if (item.call === call && !journal.entries().some(r => r.type === JT.attentionResolved && r.id === item.id && r.rev === item.rev))
535
539
  await journal.append(JT.attentionResolved, { id: item.id, rev: item.rev, resolution: "retired" });
536
540
  }
@@ -63,6 +63,12 @@ export function worktreeRoots() {
63
63
  }
64
64
  /** Pair identity is durable; it also lets readers and seal recovery identify both participants. */
65
65
  export const worktreePair = (a, b) => `worktree:${[a, b].sort().join("|")}`;
66
+ /** P32: The id of the one durable note a successful call's kept worktree records when its path holds another identity
67
+ * (effects/prepare.ts writes it; the seal's retirement, the recovery predicate and the digest read it). */
68
+ export const worktreeConflictId = (call) => `worktree-conflict:${call}`;
69
+ /** P32: Whether an attention id is exactly `call`'s identity-conflict note. That note reports what the kept path holds
70
+ * for a person; the call ending does not settle it (nothing was repaired), so only its repair does. */
71
+ export const isWorktreeConflict = (id, call) => id === worktreeConflictId(call);
66
72
  export const worktreeCalls = (id) => id.startsWith("worktree:") ? id.slice(9).split("|") : [];
67
73
  export const worktreeLabel = (call) => call.replace(/@\d+\//, "/").replace(/@\d+$/, "");
68
74
  const callOf = (exec) => exec.slice(0, exec.lastIndexOf("#"));
@@ -13,7 +13,7 @@ import { heldOn, isModelPool, modelLimit, modelPool, slotsFull } from "./slots.j
13
13
  import {} from "./ledger.js";
14
14
  import { awaitingRuns, readerHold, readerLedger, readerLedgerIdentity } from "./reader-ledger.js";
15
15
  import { packageVersion } from "../version.js";
16
- import { worktreeCalls, worktreeLabel } from "./executor/worktree.js";
16
+ import { worktreeCalls, worktreeLabel, isWorktreeConflict } from "./executor/worktree.js";
17
17
  import { leaseCalls, leaseLines, leaseState } from "../platform/lease.js";
18
18
  import { labelsOf } from "../events/derive.js";
19
19
  import { PENDING_NOTE, generationRids, UNDELIVERED_FOLLOW_UP } from "./notes.js";
@@ -668,12 +668,14 @@ export function pendingRecovery(wid, entries) {
668
668
  return true;
669
669
  }
670
670
  }
671
- // Retirement, fence repair, and cross-workflow conflict resolution can still close these items.
671
+ // Retirement, fence repair, and cross-workflow conflict resolution can still close these items. A call's
672
+ // identity-conflict note (a kept worktree) is like `unknown:<call>`: a durable diagnostic of a sealed call that it writes
673
+ // once and never retires, so an open one is no recovery work due and does not hold the digest back.
672
674
  for (const { item } of attention)
673
675
  if (!resolved.has(JSON.stringify([item.id, item.rev]))) {
674
676
  if (item.id.startsWith("fence:") || item.kind === "conflict")
675
677
  return true;
676
- if (item.call && seals.has(item.call) && item.kind !== "finished" && item.id !== `unknown:${item.call}`)
678
+ if (item.call && seals.has(item.call) && item.kind !== "finished" && item.id !== `unknown:${item.call}` && !isWorktreeConflict(item.id, item.call))
677
679
  return true;
678
680
  }
679
681
  return false;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-durable-subagents",
3
- "version": "1.4.3",
3
+ "version": "1.5.1",
4
4
  "description": "Subagents for pi that never lose work and never do it twice. Crash-safe workflows, automatic recovery, and a live view just like the main agent.",
5
5
  "type": "module",
6
6
  "license": "MIT",