pi-durable-subagents 1.0.35 → 1.0.37

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.
@@ -84,6 +84,7 @@ function snapshotReducer(wid, entries) {
84
84
  const calls = new Map();
85
85
  const byExec = new Map();
86
86
  const hibernating = new Map(); // callId → exec that decided to hibernate and is not fenced yet
87
+ const fenced = new Set();
87
88
  const resolved = new Set();
88
89
  const generations = new Set(), retired = new Set();
89
90
  const attention = [];
@@ -141,8 +142,10 @@ function snapshotReducer(wid, entries) {
141
142
  call.startedAt ??= e.ts;
142
143
  call.lastActivity = e.ts;
143
144
  byExec.set(call.exec, call);
144
- delete call.hibernated;
145
- hibernating.delete(call.callId);
145
+ if (!call.answered) {
146
+ delete call.hibernated;
147
+ hibernating.delete(call.callId);
148
+ }
146
149
  }
147
150
  else if (e.type === "writer-wait" || e.type === "writer-acquired") {
148
151
  const call = calls.get(String(e.call)), holder = String(e.holder ?? "");
@@ -153,18 +156,33 @@ function snapshotReducer(wid, entries) {
153
156
  }
154
157
  else if (e.type === "hibernated") {
155
158
  // The decision to hibernate precedes the fence; the slot is released only once the execution is fenced.
159
+ // Recovery may record the hibernation after fencing the interrupted asker.
156
160
  const call = calls.get(String(e.call));
157
- if (call?.exec && call.exec === e.exec)
161
+ if (call?.exec && call.exec === e.exec) {
158
162
  hibernating.set(call.callId, call.exec);
163
+ if (fenced.has(call.exec))
164
+ call.hibernated = true;
165
+ }
166
+ }
167
+ else if (e.type === "answer-bound") {
168
+ resolved.add(`q:${e.call}:${e.qid}@${e.rev}`);
169
+ const call = calls.get(String(e.call));
170
+ if (call && call.phase !== "sealed") {
171
+ call.answered = String(e.qid);
172
+ call.phase = "queued";
173
+ }
159
174
  }
160
- else if (e.type === "answer-bound" || (e.type === "resumed" && e.call)) {
175
+ else if (e.type === "resumed" && e.call) {
161
176
  const call = calls.get(String(e.call));
162
- if (call) {
177
+ if (call && call.phase !== "sealed" && (!e.exec || call.exec === e.exec)) {
178
+ call.phase = "running";
179
+ delete call.answered;
163
180
  delete call.hibernated;
164
181
  hibernating.delete(call.callId);
165
182
  }
166
183
  }
167
184
  else if (e.type === JT.fenced) {
185
+ fenced.add(String(e.exec));
168
186
  // A fenced execution without a seal (stop-all, a quit pi, a loss before its continuation) waits to run again.
169
187
  const call = byExec.get(String(e.exec));
170
188
  if (call && call.phase === "running")
@@ -176,8 +194,12 @@ function snapshotReducer(wid, entries) {
176
194
  const call = byExec.get(String(e.exec)), m = e.model;
177
195
  if (call && m)
178
196
  call.model = m.provider ? `${m.provider}/${m.id}` : m.id;
179
- if (call && call.phase === "queued")
197
+ if (call && call.exec === e.exec && call.phase === "queued") {
180
198
  call.phase = "running";
199
+ delete call.answered;
200
+ delete call.hibernated;
201
+ hibernating.delete(call.callId);
202
+ }
181
203
  }
182
204
  else if (e.type === "model-used") {
183
205
  // Evidence of a switch: the execution answered with another model than it launched with.
@@ -214,6 +236,7 @@ function snapshotReducer(wid, entries) {
214
236
  call.phase = "sealed";
215
237
  call.result = e.result;
216
238
  call.endedAt = e.ts;
239
+ delete call.answered;
217
240
  delete call.hibernated;
218
241
  delete call.writerWait;
219
242
  hibernating.delete(call.callId);
@@ -268,7 +291,7 @@ function snapshotReducer(wid, entries) {
268
291
  call.phase = "asking"; // a hibernated asker is fenced
269
292
  }
270
293
  for (const c of list)
271
- if (c.hibernated && c.phase !== "asking")
294
+ if (c.hibernated && c.phase !== "asking" && !c.answered)
272
295
  delete c.hibernated;
273
296
  const usageOf = (callId) => sealedUsage.get(callId) ?? live.get(callId);
274
297
  const counts = { queued: 0, running: 0, asking: 0, sealed: 0 };
@@ -313,6 +336,7 @@ function snapshotReducer(wid, entries) {
313
336
  wid, rev, ...(typeof created?.name === "string" ? { name: created.name } : {}),
314
337
  ...(created ? { origin: String(created.origin), cwd: String(created.cwd), startedAt: created.ts } : {}),
315
338
  status: done ? done.status : "running",
339
+ ...(latestCalls({ calls: list }).some(c => c.phase !== "sealed") ? { active: true } : {}),
316
340
  ...(done?.error ? { error: String(done.error) } : {}), ...(done && "result" in done ? { result: structuredClone(done.result) } : {}),
317
341
  ...(done ? { endedAt: done.ts } : {}),
318
342
  ...(followUps ? { followUps } : {}),
@@ -454,6 +478,10 @@ export function holdOf(ledger, wid, origin) {
454
478
  const created = ix.created.get(wid);
455
479
  return !created || created.seq < last.seq ? last : undefined;
456
480
  }
481
+ /** Drain: whether a drain holds workflow `wid`, from the orchestrator ledger's entries. */
482
+ export function heldIn(ledger) {
483
+ return wid => holdOf(ledger, wid, ledgerIndex(ledger).created.get(wid)?.origin) !== undefined;
484
+ }
457
485
  /** Drain: the workflows a drain (stop-all, a quit pi) holds until resume, and since when. */
458
486
  export function heldWorkflows(home) {
459
487
  const ledger = readJournalSnapshot(orchLedger(home)), ix = ledgerIndex(ledger);
@@ -494,7 +522,8 @@ export function formatUsage(u) {
494
522
  export function compactWorkflow(wf, leases) {
495
523
  const progress = progressOf(wf); // v12 §4
496
524
  return {
497
- wid: wf.wid, ...(wf.name ? { name: wf.name } : {}), ...(wf.origin ? { origin: wf.origin } : {}), status: wf.status, rev: wf.rev,
525
+ wid: wf.wid, ...(wf.name ? { name: wf.name } : {}), ...(wf.origin ? { origin: wf.origin } : {}), status: wf.status,
526
+ ...(wf.active ? { active: true } : {}), rev: wf.rev,
498
527
  ...(wf.startedAt !== undefined ? { startedAt: wf.startedAt } : {}), ...(wf.endedAt !== undefined ? { endedAt: wf.endedAt } : {}),
499
528
  ...(wf.error ? { error: clip(wf.error, 500) } : {}), usage: wf.usage ?? zero(), counts: wf.counts,
500
529
  ...(wf.planned !== undefined ? { planned: wf.planned } : {}), done: progress.done,
@@ -504,7 +533,7 @@ export function compactWorkflow(wf, leases) {
504
533
  ...(c.sharedWorktree ? { sharedWorktree: c.sharedWorktree } : {}),
505
534
  ...(c.model ? { model: c.model } : {}), ...(c.tools ? { tools: c.tools } : {}), ...(c.pending ? { pending: c.pending } : {}), ...(c.switching ? { switching: c.switching } : {}), ...(c.switchFailed ? { switchFailed: c.switchFailed } : {}), ...(nonzero(c.usage) ? { usage: c.usage } : {}),
506
535
  ...(last ? { lastLine: clip(last, 200) } : {}), ...(r?.error ? { error: clip(r.error, 300) } : {}), ...(c.hibernated ? { hibernated: true } : {}),
507
- ...(c.writerWait && !r ? { writerWait: c.writerWait } : {}), ...(!r && leases?.get(c.callId) ? { lease: leases.get(c.callId) } : {}),
536
+ ...(c.answered ? { answered: c.answered } : {}), ...(c.writerWait && !r ? { writerWait: c.writerWait } : {}), ...(!r && leases?.get(c.callId) ? { lease: leases.get(c.callId) } : {}),
508
537
  ...(c.notesPending ? { notesPending: c.notesPending } : {}) };
509
538
  }),
510
539
  attention: wf.attention.map(a => ({ id: a.id, rev: a.rev, kind: a.kind, text: clip(a.text, 300), ...(a.call ? { call: a.call } : {}), ...(a.qid ? { qid: a.qid } : {}) })),
@@ -637,18 +666,38 @@ export function exhaustedLine(provider, x, now) {
637
666
  export function slotLine(provider, held, limit) {
638
667
  return typeof limit === "number" ? `${provider} ${held}/${limit}` : `${provider} ${held} (no limit)`;
639
668
  }
669
+ /** A workflow origin as one short holder name: a pi session "main:<id>" as "session <first 8 of id>"; others as is. */
670
+ export function originLabel(origin) {
671
+ if (origin === undefined)
672
+ return "unknown";
673
+ return origin.startsWith("main:") ? `session ${origin.slice(5, 13)}` : clip(restartLine(origin), 40);
674
+ }
640
675
  export function slotsView(home, now = Date.now()) {
641
- const path = orchLedger(home), state = foldLedger(ledgerStates.get(path) ?? emptyLedger(), readJournalSnapshot(path));
676
+ const path = orchLedger(home), entries = readJournalSnapshot(path), state = foldLedger(ledgerStates.get(path) ?? emptyLedger(), entries);
642
677
  ledgerStates.set(path, state);
643
678
  const { held, config, rejected } = state, used = state.exhausted;
644
679
  const exhausted = [...used].sort(([a], [b]) => a.localeCompare(b)).map(([p, x]) => exhaustedLine(p, x, now));
645
680
  const limits = config?.settings.providers ?? {};
646
- const holders = new Map();
681
+ const holders = new Map(), byOrigin = new Map();
682
+ const created = ledgerIndex(entries).created;
647
683
  for (const e of held.values())
648
- if (e.pool !== "memory")
684
+ if (e.pool !== "memory") {
649
685
  holders.set(e.pool, (holders.get(e.pool) ?? 0) + 1);
686
+ // exec "<wid>@<rev>/<key>@<gen>#<n>" -> the origin of its workflow
687
+ const origin = originLabel(created.get(e.exec.slice(0, e.exec.indexOf("@")))?.origin);
688
+ const counts = byOrigin.get(e.pool) ?? new Map();
689
+ byOrigin.set(e.pool, counts);
690
+ counts.set(origin, (counts.get(origin) ?? 0) + 1);
691
+ }
692
+ // Who holds a provider's slots, when more than one workflow origin does: "(3 cli:alice@host, 2 session 01a11a3b)".
693
+ const who = (p) => {
694
+ const counts = byOrigin.get(p);
695
+ if (!counts || counts.size < 2)
696
+ return "";
697
+ return ` (${[...counts].sort(([a, x], [b, y]) => y - x || a.localeCompare(b)).map(([o, n]) => `${n} ${o}`).join(", ")})`;
698
+ };
650
699
  const names = [...new Set([...Object.keys(limits), ...holders.keys()])].sort();
651
- const slots = names.map(p => slotLine(p, holders.get(p) ?? 0, limits[p]?.slots));
700
+ const slots = names.map(p => slotLine(p, holders.get(p) ?? 0, limits[p]?.slots) + who(p));
652
701
  return { ...orchestratorView(state, packageVersion(), now), ...(slots.length ? { slots } : {}), ...(config ? { config: `${config.hash} since ${age(now - config.ts)} ago` } : {}),
653
702
  ...(exhausted.length ? { exhausted } : {}),
654
703
  ...(rejected ? { configRejected: `${clip(rejected.error, 200)} (${age(now - rejected.ts)} ago); ${config ? config.hash : "the start settings"} stay in effect` } : {}) };
@@ -662,7 +711,7 @@ export function statusBrief(home, options = {}) {
662
711
  const line = (w) => {
663
712
  const p = progressOf(w), notOk = latestCalls(w).filter(c => c.result && !c.result.ok).length;
664
713
  const notes = latestCalls(w).reduce((n, c) => n + (c.notesPending ?? 0), 0);
665
- return [w.wid, labelsText(w.labels), w.name, `${w.paused ? "paused" : w.followUps ? `${w.status}, follow-up running` : w.status}`, `${p.done}/${p.total}${p.plus ? "+" : ""} done`, notOk ? `${notOk} not ok` : "",
714
+ return [w.wid, labelsText(w.labels), w.name, `${w.paused ? "paused" : w.followUps ? `follow-up running (run ${w.status})` : w.status}`, `${p.done}/${p.total}${p.plus ? "+" : ""} done`, notOk ? `${notOk} not ok` : "",
666
715
  notes ? `${notes} note${notes > 1 ? "s" : ""} pending` : "",
667
716
  w.endedAt !== undefined ? `ended ${age(now - w.endedAt)} ago` : w.startedAt !== undefined ? `started ${age(now - w.startedAt)} ago` : ""].filter(Boolean).join(" · ");
668
717
  };
@@ -676,7 +725,7 @@ export function statusBrief(home, options = {}) {
676
725
  ...(live && c.phase !== "asking" && quiet !== undefined && quiet >= 60_000 ? { quiet: age(quiet) } : {}),
677
726
  ...(live && c.startedAt !== undefined ? { tokens: tokens(c.usage) } : {}),
678
727
  ...(c.result ? { status: c.result.status, ...(c.result.error ? { error: clip(c.result.error, 200) } : {}) } : {}),
679
- ...(c.hibernated ? { hibernated: true } : {}), ...(live && c.writerWait ? { writerWait: c.writerWait } : {}),
728
+ ...(c.hibernated ? { hibernated: true } : {}), ...(c.answered ? { answered: c.answered } : {}), ...(live && c.writerWait ? { writerWait: c.writerWait } : {}),
680
729
  ...(live && byCall.get(c.callId) ? { lease: byCall.get(c.callId) } : {}),
681
730
  ...(live && c.switching ? { switching: c.switching } : {}), ...(live && c.switchFailed ? { switchFailed: c.switchFailed } : {}),
682
731
  ...(c.notesPending ? { notesPending: c.notesPending } : {}) };
@@ -684,7 +733,7 @@ export function statusBrief(home, options = {}) {
684
733
  const asking = open.filter(a => a.kind === "question" && a.call).map(a => ({ to: `${w.wid}/${callKey(a.call)}`, ...(a.qid ? { qid: a.qid } : {}),
685
734
  ...(w.calls.some(c => c.callId === a.call && c.hibernated) ? { hibernated: true } : {}), question: clip(a.text, 300) }));
686
735
  const alerts = open.filter(a => a.kind !== "question").map(a => `${a.kind}${a.call ? ` ${w.wid}/${callKey(a.call)}` : ""}: ${clip(a.text, 200)}`);
687
- return { wid: w.wid, ...(w.labels ? { labels: labelsText(w.labels) } : {}), ...(w.name ? { name: w.name } : {}), status: w.status, ...(w.paused ? { paused: true } : {}), ...(w.followUps ? { followUps: w.followUps } : {}),
736
+ return { wid: w.wid, ...(w.labels ? { labels: labelsText(w.labels) } : {}), ...(w.name ? { name: w.name } : {}), status: w.status, ...(w.active ? { active: true } : {}), ...(w.paused ? { paused: true } : {}), ...(w.followUps ? { followUps: w.followUps } : {}),
688
737
  progress: `${p.done}/${p.total}${p.plus ? "+" : ""}`, tokens: tokens(w.usage), calls,
689
738
  ...(asking.length ? { asking } : {}), ...(alerts.length ? { alerts } : {}) };
690
739
  };
@@ -793,7 +842,8 @@ export function statusDetail(home, wid) {
793
842
  if (!origin.has(wid))
794
843
  throw new Error(prunedIds(home).has(wid) ? `Workflow ${wid} was pruned` : `Unknown workflow: ${wid}`);
795
844
  const held = heldWorkflows(home), wf = labelled(workflowSnapshot(home, wid), held.labels(wid), held.session(wid)), log = scriptLogPath(home, wid);
796
- return { ...wf, ...(wf.origin === undefined && origin.get(wid) !== undefined ? { origin: origin.get(wid) } : {}), ...(existsSync(log) ? { scriptLog: log } : {}) };
845
+ return { ...wf, ...(wf.origin === undefined && origin.get(wid) !== undefined ? { origin: origin.get(wid) } : {}), ...(existsSync(log) ? { scriptLog: log } : {}),
846
+ ...(isLive(wf) && held.held(wid) ? { paused: true } : {}) };
797
847
  }
798
848
  /** P25, T10: Project a workflow journal into meaningful events (no observations, time or tracking). */
799
849
  export function eventsFromEntries(entries) {
@@ -0,0 +1,127 @@
1
+ // Starting the orchestrator (README "Starting the orchestrator"). Every starter (the CLI, a pi session, the restart
2
+ // successor) goes through launchOrchestrator, so the orchestrator never depends on whoever happened to start it:
3
+ // - `pi` is resolved once, by the starter, to an absolute path passed on as DSA_PI_BIN (the starter's PATH may be the
4
+ // only one that has it: a systemd unit or cron job usually has a minimal PATH);
5
+ // - on Linux with a systemd user manager and lingering enabled for the user it runs in its own transient scope, outside
6
+ // the starter's cgroup, so the end of a oneshot unit, a cron job or a CI step (which kill their whole cgroup) does not
7
+ // end it. Without lingering the user manager stops its scopes at logout, while a plain detached process survives it
8
+ // (KillUserProcesses=no, the usual default): it starts as a plain detached process then.
9
+ import { spawn } from "node:child_process";
10
+ import { accessSync, constants, existsSync, statSync } from "node:fs";
11
+ import { userInfo } from "node:os";
12
+ import { delimiter, isAbsolute, join } from "node:path";
13
+ /** Whether `path` is a regular file this process may execute. */
14
+ export function executableFile(path) {
15
+ try {
16
+ if (!statSync(path).isFile())
17
+ return false;
18
+ accessSync(path, constants.X_OK);
19
+ return true;
20
+ }
21
+ catch {
22
+ return false;
23
+ }
24
+ }
25
+ /** The first executable `name` in the directories of `PATH`, unresolved (a package-manager shim stays a shim). */
26
+ export function findOnPath(name, PATH) {
27
+ for (const dir of (PATH ?? "").split(delimiter)) {
28
+ if (!dir || !isAbsolute(dir))
29
+ continue;
30
+ const file = join(dir, name);
31
+ if (executableFile(file))
32
+ return file;
33
+ }
34
+ return undefined;
35
+ }
36
+ /** The `pi` the orchestrator launches subagents with: DSA_PI_BIN when set (it must be an executable file), else the
37
+ * first `pi` on PATH. `problem` says why there is none. */
38
+ export function resolvePi(env) {
39
+ const given = env.DSA_PI_BIN;
40
+ if (given) {
41
+ if (isAbsolute(given) && executableFile(given))
42
+ return { path: given, source: "DSA_PI_BIN" };
43
+ return { problem: `DSA_PI_BIN=${given} is not an absolute path to an executable file` };
44
+ }
45
+ const found = findOnPath("pi", env.PATH);
46
+ return found ? { path: found, source: "PATH" } : { problem: `pi was not found on PATH (${env.PATH || "unset"}) and DSA_PI_BIN is not set` };
47
+ }
48
+ /** The starter cannot start an orchestrator that could launch no subagent. */
49
+ export class PiNotFound extends Error {
50
+ constructor(problem) {
51
+ super(`cannot start the orchestrator: ${problem}. Set DSA_PI_BIN to the absolute path of pi, or run this from an ` +
52
+ "environment whose PATH has pi. A request already sent stays pending: it runs when an orchestrator starts from an " +
53
+ "environment that has pi (any pi session starts one)");
54
+ this.name = "PiNotFound";
55
+ }
56
+ }
57
+ export const SCOPE_ARGS = ["--user", "--scope", "--quiet", "--collect"];
58
+ const PROBE_TIMEOUT_MS = 3000;
59
+ export const runProbe = (command, args, { env, timeoutMs }) => new Promise(resolve => {
60
+ let child;
61
+ try {
62
+ child = spawn(command, args, { env, stdio: "ignore", timeout: timeoutMs, killSignal: "SIGKILL" });
63
+ }
64
+ catch {
65
+ resolve(false);
66
+ return;
67
+ }
68
+ child.once("error", () => resolve(false));
69
+ child.once("exit", code => resolve(code === 0));
70
+ });
71
+ /** Whether systemd keeps `user`'s manager (and its scopes) running after the last logout. */
72
+ export function lingering(user) {
73
+ return !!user && !user.includes("/") && existsSync(join("/var/lib/systemd/linger", user));
74
+ }
75
+ function currentUser(env) {
76
+ if (env.USER)
77
+ return env.USER;
78
+ try {
79
+ return userInfo().username;
80
+ }
81
+ catch {
82
+ return "";
83
+ }
84
+ }
85
+ /** systemd-run when the orchestrator should run in its own scope: Linux, a user manager (XDG_RUNTIME_DIR) that lingers
86
+ * (it outlives logouts; a scope under a manager that does not would be stopped at logout), systemd-run on PATH,
87
+ * DSA_SCOPE not "off", and a probe scope that works. Probed once per start attempt (the starter only runs when no
88
+ * orchestrator holds the lock). */
89
+ export async function scopeRunner(env, options = {}) {
90
+ if ((options.platform ?? process.platform) !== "linux" || env.DSA_SCOPE === "off" || !env.XDG_RUNTIME_DIR)
91
+ return undefined;
92
+ if (!(options.linger ?? lingering)(currentUser(env)))
93
+ return undefined;
94
+ const runner = findOnPath("systemd-run", env.PATH);
95
+ if (!runner)
96
+ return undefined;
97
+ const ok = await (options.probe ?? runProbe)(runner, [...SCOPE_ARGS, "true"], { env, timeoutMs: PROBE_TIMEOUT_MS }).catch(() => false);
98
+ return ok ? runner : undefined;
99
+ }
100
+ function started(child) {
101
+ return new Promise((resolve, reject) => { child.once("spawn", resolve); child.once("error", reject); });
102
+ }
103
+ /** Start the orchestrator at `entry`, detached, with `env` minus the starting session's DSA_SESSION (it serves every
104
+ * session) plus DSA_HOME and the resolved DSA_PI_BIN. In its own systemd scope when one is available (the scope execs
105
+ * the command: same environment, and the pid is the orchestrator's), else a plain detached process. */
106
+ export async function launchOrchestrator(entry, env, options) {
107
+ const pi = resolvePi(env);
108
+ if (!pi.path && options.requirePi)
109
+ throw new PiNotFound(pi.problem);
110
+ const { DSA_SESSION: _session, ...rest } = env;
111
+ const childEnv = { ...rest, DSA_HOME: options.home, ...(pi.path ? { DSA_PI_BIN: pi.path } : {}) };
112
+ const node = options.node ?? process.execPath, run = options.spawn ?? spawn;
113
+ const runner = await scopeRunner(env, options);
114
+ if (runner) {
115
+ try {
116
+ const child = run(runner, [...SCOPE_ARGS, "--description", "pi-durable-subagents orchestrator", "--", node, entry], { detached: true, stdio: "ignore", env: childEnv });
117
+ await started(child);
118
+ child.unref();
119
+ return { pid: child.pid, scope: true, ...(pi.path ? { pi: pi.path } : {}) };
120
+ }
121
+ catch { /* fall back to a plain detached process */ }
122
+ }
123
+ const child = run(node, [entry], { detached: true, stdio: "ignore", env: childEnv });
124
+ await started(child);
125
+ child.unref();
126
+ return { pid: child.pid, scope: false, ...(pi.path ? { pi: pi.path } : {}) };
127
+ }
@@ -9,8 +9,8 @@
9
9
  // can be missed: a grant needs no lock once the ticket exists. A ticket is live while its wrapper or its
10
10
  // command (pid + start token) lives, or processes the command left in its group remain; a waiter next in line ends such
11
11
  // leftovers of a killed wrapper. Anyone may delete a dead ticket. No orchestrator is involved.
12
- import { chmodSync, mkdirSync, readdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
13
- import { readFile, writeFile } from "node:fs/promises";
12
+ import { chmodSync, mkdirSync, readdirSync, readFileSync, renameSync, statSync, unlinkSync, writeFileSync } from "node:fs";
13
+ import { readFile, unlink, writeFile } from "node:fs/promises";
14
14
  import path from "node:path";
15
15
  import { OsLock } from "./lock.js";
16
16
  export const RESOURCE = /^[A-Za-z0-9._-]{1,64}$/;
@@ -155,15 +155,62 @@ export function blockers(t, tickets) {
155
155
  const granted = tickets.filter(o => o.seq !== t.seq && o.grantedAt !== undefined);
156
156
  return granted.length >= (t.slots ?? 1) ? granted : [];
157
157
  }
158
+ /** Write `file` through a temporary file renamed over it; a failed write or rename removes the temporary file (a full
159
+ * disk left empty ones behind). */
160
+ export function replaceFileSync(file, content, mode) {
161
+ const tmp = `${file}.${process.pid}.tmp`;
162
+ try {
163
+ writeFileSync(tmp, content);
164
+ if (mode !== undefined)
165
+ chmodSync(tmp, mode);
166
+ renameSync(tmp, file);
167
+ }
168
+ catch (error) {
169
+ try {
170
+ unlinkSync(tmp);
171
+ }
172
+ catch { /* never written */ }
173
+ throw error;
174
+ }
175
+ }
176
+ async function replaceFile(file, content) {
177
+ const tmp = `${file}.${process.pid}.tmp`;
178
+ try {
179
+ await writeFile(tmp, content);
180
+ renameSync(tmp, file);
181
+ }
182
+ catch (error) {
183
+ await unlink(tmp).catch(() => { });
184
+ throw error;
185
+ }
186
+ }
187
+ /** Remove `*.tmp` files in `dir` older than `maxAgeMs` (partial writes of processes that died or ran out of disk). Best
188
+ * effort: returns how many were removed, never throws. */
189
+ export function removeStaleTemps(dir, maxAgeMs, now = Date.now()) {
190
+ let removed = 0, names;
191
+ try {
192
+ names = readdirSync(dir);
193
+ }
194
+ catch {
195
+ return 0;
196
+ }
197
+ for (const name of names.filter(n => n.endsWith(".tmp"))) {
198
+ try {
199
+ const file = path.join(dir, name), info = statSync(file);
200
+ if (info.isFile() && now - info.mtimeMs > maxAgeMs) {
201
+ unlinkSync(file);
202
+ removed++;
203
+ }
204
+ }
205
+ catch { /* gone meanwhile, or not ours to remove */ }
206
+ }
207
+ return removed;
208
+ }
158
209
  function writeTicketSync(home, t) {
159
- const file = path.join(leaseDir(home, t.resource), ticketName(t.seq)), tmp = `${file}.${process.pid}.tmp`;
160
- writeFileSync(tmp, JSON.stringify(t));
161
- renameSync(tmp, file);
210
+ replaceFileSync(path.join(leaseDir(home, t.resource), ticketName(t.seq)), JSON.stringify(t));
162
211
  }
163
212
  export async function writeTicket(home, t) {
164
- const file = path.join(leaseDir(home, t.resource), ticketName(t.seq)), tmp = `${file}.${process.pid}.tmp`;
165
- await writeFile(tmp, JSON.stringify(t));
166
- renameSync(tmp, file);
213
+ await replaceFile(path.join(leaseDir(home, t.resource), ticketName(t.seq)), JSON.stringify(t));
167
214
  }
168
215
  export function removeTicket(home, t) {
169
216
  try {
@@ -202,8 +249,7 @@ async function numbered(home, ticket, now, lock) {
202
249
  return { busy };
203
250
  t.grantedAt = Date.now();
204
251
  }
205
- await writeFile(`${counter}.tmp`, String(t.seq));
206
- renameSync(`${counter}.tmp`, counter);
252
+ await replaceFile(counter, String(t.seq));
207
253
  writeTicketSync(home, t);
208
254
  return t;
209
255
  }
@@ -271,9 +317,7 @@ const quote = (s) => `'${s.replace(/'/g, `'\\''`)}'`;
271
317
  * the running orchestrator, so children can `hold` without the package on their PATH. Rewritten at every start. */
272
318
  export function writeShim(dir, node, entry) {
273
319
  mkdirSync(dir, { recursive: true });
274
- const file = path.join(dir, "pi-durable-subagents"), tmp = `${file}.${process.pid}.tmp`;
275
- writeFileSync(tmp, `#!/bin/sh\nexec ${quote(node)} ${quote(entry)} "$@"\n`);
276
- chmodSync(tmp, 0o755);
277
- renameSync(tmp, file);
320
+ const file = path.join(dir, "pi-durable-subagents");
321
+ replaceFileSync(file, `#!/bin/sh\nexec ${quote(node)} ${quote(entry)} "$@"\n`, 0o755);
278
322
  return file;
279
323
  }
@@ -2,9 +2,12 @@
2
2
  // Known-id filtering assumes argv/other values do not impersonate the sole known
3
3
  // execution id. Multiple known ids are ambiguous; macOS verification awaits CI.
4
4
  import { readFile, readdir } from "node:fs/promises";
5
- import { closeSync, openSync, readFileSync, readSync } from "node:fs";
5
+ import { closeSync, existsSync, openSync, readFileSync, readSync } from "node:fs";
6
6
  import { execFile } from "node:child_process";
7
7
  import { promisify } from "node:util";
8
+ /** `ps` by its absolute path where it has one (macOS and Linux: /bin/ps), so a minimal PATH (a service unit, a test
9
+ * that hides `pi`) does not take the process table away. */
10
+ export const PS = existsSync("/bin/ps") ? "/bin/ps" : "ps";
8
11
  const exec = promisify(execFile);
9
12
  const vanished = (error) => ["ENOENT", "ESRCH", "EACCES", "EPERM"].includes(error.code ?? "");
10
13
  // /proc/<pid>/stat is one short line: one open/read/close into a reused buffer, not readFileSync's fstat, sized read
@@ -36,7 +39,7 @@ export async function captureStart(pid) {
36
39
  }
37
40
  if (process.platform === "darwin") {
38
41
  try {
39
- const { stdout } = await exec("ps", ["-o", "lstart=", "-p", String(pid)], { env: { ...process.env, LC_ALL: "C" }, timeout: 2000 });
42
+ const { stdout } = await exec(PS, ["-o", "lstart=", "-p", String(pid)], { env: { ...process.env, LC_ALL: "C" }, timeout: 2000 });
40
43
  return stdout.trim().replace(/\s+/g, " ");
41
44
  }
42
45
  catch (error) {
@@ -60,7 +63,7 @@ export class ProcessTable {
60
63
  ps;
61
64
  constructor(options = {}) {
62
65
  this.platform = options.platform ?? process.platform;
63
- this.ps = options.ps ?? (async () => (await exec("ps", ["-axEww", "-o", "pid=,ppid=,lstart=,time=,stat=,command="],
66
+ this.ps = options.ps ?? (async () => (await exec(PS, ["-axEww", "-o", "pid=,ppid=,lstart=,time=,stat=,command="],
64
67
  // The whole table with environments is large; 2 s proved too short on loaded macOS machines.
65
68
  { env: { ...process.env, LC_ALL: "C" }, timeout: 10_000, maxBuffer: 32 * 1024 * 1024 })).stdout);
66
69
  }
package/dist/ui/cards.js CHANGED
@@ -8,6 +8,7 @@ const HEAD = {
8
8
  unknown: { icon: "!", title: "outcome unknown", tone: "warning" },
9
9
  conflict: { icon: "!", title: "shares a worktree", tone: "warning" },
10
10
  budget: { icon: "$", title: "budget reached", tone: "warning" },
11
+ environment: { icon: "!", title: "could not start", tone: "warning" },
11
12
  };
12
13
  const keyOf = (item) => item.call ? item.call.split("/").at(-1).replace(/@1$/, "") : item.wid;
13
14
  /** v12 §3: The finished digest body — first line prominent, per-agent lines dim, each clipped to the card's inner width. */
package/dist/ui/screen.js CHANGED
@@ -2,7 +2,7 @@ import { AssistantMessageComponent, UserMessageComponent, ToolExecutionComponent
2
2
  import { Input, SelectList, fuzzyFilter, matchesKey, truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
3
3
  import { CT } from "../types.js";
4
4
  import { UiActions, UiData } from "./data.js";
5
- import { callName, workflowName, doneOrder, isOpen, plainReason, toggleOpen, duration, keepSelection, summaryText, listRows, modelLabel, pendingText, resultPhrase, rowText, toolCount } from "./view.js";
5
+ import { callName, workflowName, doneOrder, isOpen, plainReason, toggleOpen, duration, keepSelection, summaryText, listRows, modelLabel, pendingText, resultPhrase, statusPhrase, rowText, toolCount } from "./view.js";
6
6
  import { fitWidth, frame, inner } from "./frame.js";
7
7
  import { thinkingElapsed } from "./thinking.js";
8
8
  import { thoughtSummary } from "./session.js";
@@ -568,7 +568,7 @@ export class SubagentScreen {
568
568
  const tools = toolCount(facts?.tools), pending = pendingText(c.pending), rule = this.theme.fg("borderMuted", "─".repeat(size.width));
569
569
  const switching = c.switching ? ` → ${this.name(c.switching)} (requested)` : "";
570
570
  const head = [tabs, `${callName(w, c)} · ${this.name(facts?.model ?? c.model)} ▾${switching} · ${facts?.thinking ?? "off"} ▾${tools ? ` · ${tools}` : ""}${pending ? ` · ${pending}` : ""}`,
571
- this.theme.fg("dim", this.spend(c, facts)), rule];
571
+ this.theme.fg("dim", this.spend(c, facts)), ...(c.phase === "queued" && c.answered ? [statusPhrase(c, w, facts, Date.now())] : []), rule];
572
572
  const asking = w.attention.some(a => a.kind === "question" && a.call === c.callId);
573
573
  const placeholder = `${c.phase === "sealed" ? "Continue" : asking ? "Reply to" : "Steer"} ${c.key}…${this.uses < 3 ? " / for commands" : ""}`;
574
574
  const empty = new Input({ prompt: "", placeholder, placeholderStyle: text => this.theme.fg("dim", text) });
package/dist/ui/tool.js CHANGED
@@ -32,7 +32,7 @@ export function resultLines(details) {
32
32
  const d = (details ?? {});
33
33
  if (typeof d.wid === "string" && typeof d.key === "string" && typeof d.phase === "string") {
34
34
  const r = d.result;
35
- return [`${d.key} · ${r?.status ?? d.phase}${typeof d.model === "string" ? ` · ${d.model}` : ""}`];
35
+ return [`${d.key} · ${r?.status ?? (d.phase === "queued" && d.answered ? "queued (answered, waiting for a slot)" : d.phase)}${typeof d.model === "string" ? ` · ${d.model}` : ""}`];
36
36
  }
37
37
  if (typeof d.wid === "string" && !Array.isArray(d.calls))
38
38
  return [`started workflow ${d.wid}`, ...(typeof d.paused === "string" ? [`⚠ ${d.paused}`] : [])];
@@ -45,12 +45,12 @@ export function resultLines(details) {
45
45
  const row = (w) => {
46
46
  const done = w.calls.filter(c => c.phase === "sealed").length, failed = w.calls.filter(c => c.status && c.status !== "ok").length;
47
47
  const asks = (w.attention ?? []).filter(a => a.kind === "question").length;
48
- return `${w.name ?? short(w.wid)} · ${w.status} · ${done}/${w.calls.length} done${failed ? ` · ${failed} not ok` : ""}${asks ? ` · ${asks} asking` : ""}`;
48
+ return `${w.name ?? short(w.wid)} · ${w.followUps ? `follow-up running (run ${w.status})` : w.status} · ${done}/${w.calls.length} done${failed ? ` · ${failed} not ok` : ""}${asks ? ` · ${asks} asking` : ""}`;
49
49
  };
50
50
  if (Array.isArray(d.active)) {
51
51
  const rows = d.active.map(w => {
52
52
  const failed = w.calls.filter(c => c.status && c.status !== "ok").length, asks = w.asking?.length ?? 0, alerts = w.alerts?.length ?? 0;
53
- return `${w.name ?? short(w.wid)} · ${w.paused ? "paused" : w.followUps ? `${w.status}, follow-up running` : w.status} · ${w.progress} done${failed ? ` · ${failed} not ok` : ""}${asks ? ` · ${asks} asking` : ""}${alerts ? ` · ${alerts} alert${alerts > 1 ? "s" : ""}` : ""}`;
53
+ return `${w.name ?? short(w.wid)} · ${w.paused ? "paused" : w.followUps ? `follow-up running (run ${w.status})` : w.status} · ${w.progress} done${failed ? ` · ${failed} not ok` : ""}${asks ? ` · ${asks} asking` : ""}${alerts ? ` · ${alerts} alert${alerts > 1 ? "s" : ""}` : ""}`;
54
54
  });
55
55
  const finished = Array.isArray(d.finished) ? d.finished.length + Number(d.olderFinished ?? 0) : 0;
56
56
  return [...(typeof d.paused === "string" ? [`⚠ ${d.paused}`] : []), ...(rows.length ? rows.slice(0, 6) : ["nothing running"]),
package/dist/ui/view.js CHANGED
@@ -129,7 +129,7 @@ export function statusPhrase(call, workflow, facts, now) {
129
129
  if (workflow.attention.some(a => a.kind === "stall" && a.call === call.callId))
130
130
  return `no activity for ${duration(now - Math.max(call.lastActivity ?? call.startedAt ?? now, facts?.lastActivity ?? 0))}`;
131
131
  if (call.phase === "queued")
132
- return workflow.paused ? "paused · r resumes" : "queued: waiting for a free slot";
132
+ return workflow.paused ? "paused · r resumes" : call.answered ? "queued (answered, waiting for a slot)" : "queued: waiting for a free slot";
133
133
  // Liveness (UI §2): the age of the newest evidence ticks, and resets whenever the agent does anything.
134
134
  const since = duration(Math.max(0, now - Math.max(call.lastActivity ?? 0, facts?.lastActivity ?? 0, call.startedAt ?? 0)));
135
135
  if (facts?.activity)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-durable-subagents",
3
- "version": "1.0.35",
3
+ "version": "1.0.37",
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",