pi-durable-subagents 1.0.35 → 1.0.38

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.
@@ -5,7 +5,8 @@
5
5
  // provider-*: used-up usage windows (providers.ts).
6
6
  // config{hash,config}: the orchestrator settings in effect from here; config-rejected{error,hash?}: a change of
7
7
  // config.json refused, while the earlier settings stay (cleared by the next config record).
8
- // orchestrator{version,pid} / orchestrator-exit{pid}: the orchestrator running (its package version) and its exit.
8
+ // orchestrator{version,pid,pi?} / orchestrator-exit{pid,reason?,signal?,error?}: the orchestrator running (its package
9
+ // version, the pi it launches) and its exit (why: idle, restart, signal, error).
9
10
  // restart{rid,force,reason?,initiator?,from?,live}: accepted restart; the next start consumes its status provenance.
10
11
  // Old records lack reason/initiator/from and remain readable (A1).
11
12
  // writer-hold/writer-release{root,call}: the writer lock of a worktree root, held by one call until it ends.
@@ -36,7 +37,7 @@ export function applyLedger(state, e) {
36
37
  else if (e.type === "restart")
37
38
  state.pendingRestart = e.force === true ? { ts: e.ts, reason: e.reason, initiator: e.initiator, from: e.from } : undefined;
38
39
  else if (isEntry(e, "orchestrator")) {
39
- state.orchestrator = { version: String(e.version), pid: Number(e.pid), ...(e.start ? { start: String(e.start) } : {}), ts: e.ts, ...(e.restart === true ? { restart: true } : {}), ...(state.pendingRestart ? { forceRestart: state.pendingRestart } : {}) };
40
+ state.orchestrator = { version: String(e.version), pid: Number(e.pid), ...(e.start ? { start: String(e.start) } : {}), ts: e.ts, ...(e.pi !== undefined ? { pi: e.pi } : {}), ...(e.restart === true ? { restart: true } : {}), ...(state.pendingRestart ? { forceRestart: state.pendingRestart } : {}) };
40
41
  delete state.pendingRestart;
41
42
  }
42
43
  else if (e.type === "writer-hold") {
@@ -50,6 +51,8 @@ export function applyLedger(state, e) {
50
51
  else if (isEntry(e, "orchestrator-exit")) {
51
52
  if (state.orchestrator?.pid === e.pid)
52
53
  state.orchestrator.exited = true;
54
+ if (e.reason)
55
+ state.lastExit = { pid: e.pid, ts: e.ts, reason: e.reason, ...(e.signal ? { signal: e.signal } : {}), ...(e.error ? { error: e.error } : {}) };
53
56
  }
54
57
  foldExhaustion(state.exhausted, e);
55
58
  }
@@ -58,7 +61,7 @@ export function applyLedger(state, e) {
58
61
  export function foldLedger(state, entries) {
59
62
  // Journal readers keep the entry objects of a ledger as it grows (kernel/journal.ts), so identity tells them apart.
60
63
  if (state.seen && entries[state.seen - 1] !== state.last)
61
- Object.assign(state, emptyLedger(), { config: undefined, rejected: undefined, orchestrator: undefined, pendingRestart: undefined, last: undefined });
64
+ Object.assign(state, emptyLedger(), { config: undefined, rejected: undefined, orchestrator: undefined, pendingRestart: undefined, last: undefined, lastExit: undefined });
62
65
  for (; state.seen < entries.length; state.seen++)
63
66
  applyLedger(state, entries[state.seen]);
64
67
  state.last = entries[state.seen - 1];
@@ -6,13 +6,13 @@ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExte
6
6
  }
7
7
  return path;
8
8
  };
9
- import { spawn } from 'node:child_process';
10
9
  import { mkdir } from 'node:fs/promises';
11
10
  import { fileURLToPath } from 'node:url';
12
11
  import { realpathSync } from 'node:fs';
13
12
  import { join, resolve } from 'node:path';
14
13
  import { binDir, dsaHome, orchLedger, orchLock } from "../paths.js";
15
- import { writeShim } from "../platform/lease.js";
14
+ import { removeStaleTemps, writeShim } from "../platform/lease.js";
15
+ import { launchOrchestrator, resolvePi } from "../platform/launch.js";
16
16
  import { openJournal } from "../kernel/journal.js";
17
17
  import { OsLock } from "../platform/lock.js";
18
18
  import { captureStart } from "../platform/proctable.js";
@@ -30,6 +30,7 @@ export async function main(options = {}) {
30
30
  if (!lock)
31
31
  return {};
32
32
  let engine, ledgers, watcher;
33
+ let exit = { reason: 'error', error: 'ended before its loop' };
33
34
  try {
34
35
  let config = options.config, stamp;
35
36
  if (!config) {
@@ -46,6 +47,8 @@ export async function main(options = {}) {
46
47
  // Which version runs is visible to every pi session (status; a notice when it differs from the one pi loaded).
47
48
  // `start` (Linux) tells this process from a later one given the same pid after a crash.
48
49
  const start = await captureStart(process.pid).catch(() => '');
50
+ // Partial writes of earlier starts (a full disk, say): best effort, never fails the start.
51
+ removeStaleTemps(binDir(home), 10 * 60_000);
49
52
  // Subagents reach `pi-durable-subagents hold …` through this shim, written before the start is recorded (executor puts its directory first on PATH).
50
53
  try {
51
54
  writeShim(binDir(home), process.execPath, fileURLToPath(new URL(import.meta.url.endsWith('.ts') ? '../cli/main.ts' : '../cli/main.js', import.meta.url)));
@@ -53,9 +56,14 @@ export async function main(options = {}) {
53
56
  catch (error) {
54
57
  console.error(`durable-subagents: cannot write ${binDir(home)}: ${String(error)}`);
55
58
  }
56
- await ledgers.orch.append('orchestrator', { version: packageVersion(), pid: process.pid, ...(start ? { start } : {}), restart: true });
59
+ // The pi subagents run: resolved once (an executable DSA_PI_BIN from the starter, else this PATH), not per launch from an inherited
60
+ // PATH; null when there is none (each launch then runs a bare `pi`, and fails as an environment error until it works).
61
+ const pi = resolvePi(process.env).path ?? resolvePi({ PATH: process.env.PATH }).path;
62
+ if (!pi)
63
+ console.error('durable-subagents: pi not found (DSA_PI_BIN unset or not executable, not on PATH); subagents launch `pi` from PATH');
64
+ await ledgers.orch.append('orchestrator', { version: packageVersion(), pid: process.pid, ...(start ? { start } : {}), restart: true, pi: pi ?? null });
57
65
  const factory = options.executor ?? (await import(__rewriteRelativeImportExtension(new URL(import.meta.url.endsWith('.ts') ? './executor/index.ts' : './executor/index.js', import.meta.url).href))).default;
58
- const executor = factory(ledgers);
66
+ const executor = factory(ledgers, pi ? { pi } : {});
59
67
  engine = new Engine(ledgers, executor, options);
60
68
  // A4: admission reads the settings recorded last, so the ones this run starts with are recorded (given ones too).
61
69
  await recordConfig(ledgers.orch, config);
@@ -66,8 +74,15 @@ export async function main(options = {}) {
66
74
  }
67
75
  await engine.recover();
68
76
  await engine.loop(options.signal);
77
+ const reason = options.signal?.reason;
78
+ exit = engine.restartRequested ? { reason: 'restart' }
79
+ : options.signal?.aborted ? { reason: 'signal', ...(typeof reason === 'string' ? { signal: reason } : {}) } : { reason: 'idle' };
69
80
  return engine.restartRequested ? { restart: true } : {};
70
81
  }
82
+ catch (error) {
83
+ exit = { reason: 'error', error: String(error).slice(0, 300) };
84
+ throw error;
85
+ }
71
86
  finally {
72
87
  try {
73
88
  await watcher?.stop();
@@ -75,7 +90,7 @@ export async function main(options = {}) {
75
90
  }
76
91
  finally {
77
92
  try {
78
- await ledgers?.orch.append('orchestrator-exit', { pid: process.pid }).catch(() => { });
93
+ await ledgers?.orch.append('orchestrator-exit', { pid: process.pid, ...exit }).catch(() => { });
79
94
  await ledgers?.orch.close();
80
95
  }
81
96
  finally {
@@ -88,12 +103,12 @@ export async function main(options = {}) {
88
103
  // import.meta.url is the real file: compare real paths, as the CLI does.
89
104
  if (process.argv[1] && realpathSync(resolve(process.argv[1])) === fileURLToPath(import.meta.url)) {
90
105
  const controller = new AbortController();
91
- process.once('SIGTERM', () => controller.abort());
92
- process.once('SIGINT', () => controller.abort());
93
- main({ signal: controller.signal }).then(({ restart }) => {
106
+ for (const signal of ['SIGTERM', 'SIGINT', 'SIGHUP'])
107
+ process.once(signal, () => controller.abort(signal));
108
+ main({ signal: controller.signal }).then(async ({ restart }) => {
94
109
  // Restart: the successor runs this same entry, which an update replaced in place; any pi session or CLI would start
95
110
  // it too (whoever takes the lock first wins, the others exit at once).
96
111
  if (restart)
97
- spawn(process.execPath, [process.argv[1]], { detached: true, stdio: 'ignore', env: process.env }).unref();
112
+ await launchOrchestrator(process.argv[1], process.env, { home: dsaHome() });
98
113
  }).catch(error => { console.error(error); process.exitCode = 1; });
99
114
  }
@@ -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,36 @@ 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
+ // D6: hibernated again after a bound answer the session had already closed: it waits for a new answer.
166
+ if (call.phase !== "sealed")
167
+ delete call.answered;
168
+ }
169
+ }
170
+ else if (e.type === "answer-bound") {
171
+ resolved.add(`q:${e.call}:${e.qid}@${e.rev}`);
172
+ const call = calls.get(String(e.call));
173
+ if (call && call.phase !== "sealed") {
174
+ call.answered = String(e.qid);
175
+ call.phase = "queued";
176
+ }
159
177
  }
160
- else if (e.type === "answer-bound" || (e.type === "resumed" && e.call)) {
178
+ else if (e.type === "resumed" && e.call) {
161
179
  const call = calls.get(String(e.call));
162
- if (call) {
180
+ if (call && call.phase !== "sealed" && (!e.exec || call.exec === e.exec)) {
181
+ call.phase = "running";
182
+ delete call.answered;
163
183
  delete call.hibernated;
164
184
  hibernating.delete(call.callId);
165
185
  }
166
186
  }
167
187
  else if (e.type === JT.fenced) {
188
+ fenced.add(String(e.exec));
168
189
  // A fenced execution without a seal (stop-all, a quit pi, a loss before its continuation) waits to run again.
169
190
  const call = byExec.get(String(e.exec));
170
191
  if (call && call.phase === "running")
@@ -176,8 +197,12 @@ function snapshotReducer(wid, entries) {
176
197
  const call = byExec.get(String(e.exec)), m = e.model;
177
198
  if (call && m)
178
199
  call.model = m.provider ? `${m.provider}/${m.id}` : m.id;
179
- if (call && call.phase === "queued")
200
+ if (call && call.exec === e.exec && call.phase === "queued") {
180
201
  call.phase = "running";
202
+ delete call.answered;
203
+ delete call.hibernated;
204
+ hibernating.delete(call.callId);
205
+ }
181
206
  }
182
207
  else if (e.type === "model-used") {
183
208
  // Evidence of a switch: the execution answered with another model than it launched with.
@@ -214,6 +239,7 @@ function snapshotReducer(wid, entries) {
214
239
  call.phase = "sealed";
215
240
  call.result = e.result;
216
241
  call.endedAt = e.ts;
242
+ delete call.answered;
217
243
  delete call.hibernated;
218
244
  delete call.writerWait;
219
245
  hibernating.delete(call.callId);
@@ -268,7 +294,7 @@ function snapshotReducer(wid, entries) {
268
294
  call.phase = "asking"; // a hibernated asker is fenced
269
295
  }
270
296
  for (const c of list)
271
- if (c.hibernated && c.phase !== "asking")
297
+ if (c.hibernated && c.phase !== "asking" && !c.answered)
272
298
  delete c.hibernated;
273
299
  const usageOf = (callId) => sealedUsage.get(callId) ?? live.get(callId);
274
300
  const counts = { queued: 0, running: 0, asking: 0, sealed: 0 };
@@ -313,6 +339,7 @@ function snapshotReducer(wid, entries) {
313
339
  wid, rev, ...(typeof created?.name === "string" ? { name: created.name } : {}),
314
340
  ...(created ? { origin: String(created.origin), cwd: String(created.cwd), startedAt: created.ts } : {}),
315
341
  status: done ? done.status : "running",
342
+ ...(latestCalls({ calls: list }).some(c => c.phase !== "sealed") ? { active: true } : {}),
316
343
  ...(done?.error ? { error: String(done.error) } : {}), ...(done && "result" in done ? { result: structuredClone(done.result) } : {}),
317
344
  ...(done ? { endedAt: done.ts } : {}),
318
345
  ...(followUps ? { followUps } : {}),
@@ -454,6 +481,10 @@ export function holdOf(ledger, wid, origin) {
454
481
  const created = ix.created.get(wid);
455
482
  return !created || created.seq < last.seq ? last : undefined;
456
483
  }
484
+ /** Drain: whether a drain holds workflow `wid`, from the orchestrator ledger's entries. */
485
+ export function heldIn(ledger) {
486
+ return wid => holdOf(ledger, wid, ledgerIndex(ledger).created.get(wid)?.origin) !== undefined;
487
+ }
457
488
  /** Drain: the workflows a drain (stop-all, a quit pi) holds until resume, and since when. */
458
489
  export function heldWorkflows(home) {
459
490
  const ledger = readJournalSnapshot(orchLedger(home)), ix = ledgerIndex(ledger);
@@ -494,7 +525,8 @@ export function formatUsage(u) {
494
525
  export function compactWorkflow(wf, leases) {
495
526
  const progress = progressOf(wf); // v12 §4
496
527
  return {
497
- wid: wf.wid, ...(wf.name ? { name: wf.name } : {}), ...(wf.origin ? { origin: wf.origin } : {}), status: wf.status, rev: wf.rev,
528
+ wid: wf.wid, ...(wf.name ? { name: wf.name } : {}), ...(wf.origin ? { origin: wf.origin } : {}), status: wf.status,
529
+ ...(wf.active ? { active: true } : {}), rev: wf.rev,
498
530
  ...(wf.startedAt !== undefined ? { startedAt: wf.startedAt } : {}), ...(wf.endedAt !== undefined ? { endedAt: wf.endedAt } : {}),
499
531
  ...(wf.error ? { error: clip(wf.error, 500) } : {}), usage: wf.usage ?? zero(), counts: wf.counts,
500
532
  ...(wf.planned !== undefined ? { planned: wf.planned } : {}), done: progress.done,
@@ -504,7 +536,7 @@ export function compactWorkflow(wf, leases) {
504
536
  ...(c.sharedWorktree ? { sharedWorktree: c.sharedWorktree } : {}),
505
537
  ...(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
538
  ...(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) } : {}),
539
+ ...(c.answered ? { answered: c.answered } : {}), ...(c.writerWait && !r ? { writerWait: c.writerWait } : {}), ...(!r && leases?.get(c.callId) ? { lease: leases.get(c.callId) } : {}),
508
540
  ...(c.notesPending ? { notesPending: c.notesPending } : {}) };
509
541
  }),
510
542
  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 +669,38 @@ export function exhaustedLine(provider, x, now) {
637
669
  export function slotLine(provider, held, limit) {
638
670
  return typeof limit === "number" ? `${provider} ${held}/${limit}` : `${provider} ${held} (no limit)`;
639
671
  }
672
+ /** A workflow origin as one short holder name: a pi session "main:<id>" as "session <first 8 of id>"; others as is. */
673
+ export function originLabel(origin) {
674
+ if (origin === undefined)
675
+ return "unknown";
676
+ return origin.startsWith("main:") ? `session ${origin.slice(5, 13)}` : clip(restartLine(origin), 40);
677
+ }
640
678
  export function slotsView(home, now = Date.now()) {
641
- const path = orchLedger(home), state = foldLedger(ledgerStates.get(path) ?? emptyLedger(), readJournalSnapshot(path));
679
+ const path = orchLedger(home), entries = readJournalSnapshot(path), state = foldLedger(ledgerStates.get(path) ?? emptyLedger(), entries);
642
680
  ledgerStates.set(path, state);
643
681
  const { held, config, rejected } = state, used = state.exhausted;
644
682
  const exhausted = [...used].sort(([a], [b]) => a.localeCompare(b)).map(([p, x]) => exhaustedLine(p, x, now));
645
683
  const limits = config?.settings.providers ?? {};
646
- const holders = new Map();
684
+ const holders = new Map(), byOrigin = new Map();
685
+ const created = ledgerIndex(entries).created;
647
686
  for (const e of held.values())
648
- if (e.pool !== "memory")
687
+ if (e.pool !== "memory") {
649
688
  holders.set(e.pool, (holders.get(e.pool) ?? 0) + 1);
689
+ // exec "<wid>@<rev>/<key>@<gen>#<n>" -> the origin of its workflow
690
+ const origin = originLabel(created.get(e.exec.slice(0, e.exec.indexOf("@")))?.origin);
691
+ const counts = byOrigin.get(e.pool) ?? new Map();
692
+ byOrigin.set(e.pool, counts);
693
+ counts.set(origin, (counts.get(origin) ?? 0) + 1);
694
+ }
695
+ // Who holds a provider's slots, when more than one workflow origin does: "(3 cli:alice@host, 2 session 01a11a3b)".
696
+ const who = (p) => {
697
+ const counts = byOrigin.get(p);
698
+ if (!counts || counts.size < 2)
699
+ return "";
700
+ return ` (${[...counts].sort(([a, x], [b, y]) => y - x || a.localeCompare(b)).map(([o, n]) => `${n} ${o}`).join(", ")})`;
701
+ };
650
702
  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));
703
+ const slots = names.map(p => slotLine(p, holders.get(p) ?? 0, limits[p]?.slots) + who(p));
652
704
  return { ...orchestratorView(state, packageVersion(), now), ...(slots.length ? { slots } : {}), ...(config ? { config: `${config.hash} since ${age(now - config.ts)} ago` } : {}),
653
705
  ...(exhausted.length ? { exhausted } : {}),
654
706
  ...(rejected ? { configRejected: `${clip(rejected.error, 200)} (${age(now - rejected.ts)} ago); ${config ? config.hash : "the start settings"} stay in effect` } : {}) };
@@ -662,7 +714,7 @@ export function statusBrief(home, options = {}) {
662
714
  const line = (w) => {
663
715
  const p = progressOf(w), notOk = latestCalls(w).filter(c => c.result && !c.result.ok).length;
664
716
  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` : "",
717
+ 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
718
  notes ? `${notes} note${notes > 1 ? "s" : ""} pending` : "",
667
719
  w.endedAt !== undefined ? `ended ${age(now - w.endedAt)} ago` : w.startedAt !== undefined ? `started ${age(now - w.startedAt)} ago` : ""].filter(Boolean).join(" · ");
668
720
  };
@@ -676,7 +728,7 @@ export function statusBrief(home, options = {}) {
676
728
  ...(live && c.phase !== "asking" && quiet !== undefined && quiet >= 60_000 ? { quiet: age(quiet) } : {}),
677
729
  ...(live && c.startedAt !== undefined ? { tokens: tokens(c.usage) } : {}),
678
730
  ...(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 } : {}),
731
+ ...(c.hibernated ? { hibernated: true } : {}), ...(c.answered ? { answered: c.answered } : {}), ...(live && c.writerWait ? { writerWait: c.writerWait } : {}),
680
732
  ...(live && byCall.get(c.callId) ? { lease: byCall.get(c.callId) } : {}),
681
733
  ...(live && c.switching ? { switching: c.switching } : {}), ...(live && c.switchFailed ? { switchFailed: c.switchFailed } : {}),
682
734
  ...(c.notesPending ? { notesPending: c.notesPending } : {}) };
@@ -684,7 +736,7 @@ export function statusBrief(home, options = {}) {
684
736
  const asking = open.filter(a => a.kind === "question" && a.call).map(a => ({ to: `${w.wid}/${callKey(a.call)}`, ...(a.qid ? { qid: a.qid } : {}),
685
737
  ...(w.calls.some(c => c.callId === a.call && c.hibernated) ? { hibernated: true } : {}), question: clip(a.text, 300) }));
686
738
  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 } : {}),
739
+ 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
740
  progress: `${p.done}/${p.total}${p.plus ? "+" : ""}`, tokens: tokens(w.usage), calls,
689
741
  ...(asking.length ? { asking } : {}), ...(alerts.length ? { alerts } : {}) };
690
742
  };
@@ -793,7 +845,8 @@ export function statusDetail(home, wid) {
793
845
  if (!origin.has(wid))
794
846
  throw new Error(prunedIds(home).has(wid) ? `Workflow ${wid} was pruned` : `Unknown workflow: ${wid}`);
795
847
  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 } : {}) };
848
+ return { ...wf, ...(wf.origin === undefined && origin.get(wid) !== undefined ? { origin: origin.get(wid) } : {}), ...(existsSync(log) ? { scriptLog: log } : {}),
849
+ ...(isLive(wf) && held.held(wid) ? { paused: true } : {}) };
797
850
  }
798
851
  /** P25, T10: Project a workflow journal into meaningful events (no observations, time or tracking). */
799
852
  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) });