pi-durable-subagents 1.0.43 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,16 +1,16 @@
1
1
  // Pi-side ledger state: only projections used by readers, never decoded ledger history or run bodies.
2
2
  import { forgetJournalSnapshot, readJournalFold } from "../kernel/journal.js";
3
- import { orchLedger } from "../paths.js";
3
+ import { orchLedger, journalPath } from "../paths.js";
4
4
  import { JT } from "../types.js";
5
5
  import { LEDGER_ENTRY_TYPES, applyLedger, emptyLedger } from "./ledger.js";
6
6
  import { labelsOf } from "../events/derive.js";
7
7
  export function emptyReaderLedger() {
8
8
  return { created: new Map(), origins: new Map(), intents: new Map(), revisions: new Map(), pruned: new Set(), labels: new Map(), runLabels: new Map(), sessions: new Map(), runSessions: new Map(),
9
- byWid: new Map(), byOrigin: new Map(), state: emptyLedger(), createdRids: new Map(), decisions: new Map(), resolutions: new Map(), sendNotes: new Map() };
9
+ byWid: new Map(), byOrigin: new Map(), state: emptyLedger(), createdRids: new Map(), decisions: new Map(), resolutions: new Map(), sendNotes: new Map(), wakeRuns: new Map(), wakeByTo: new Map() };
10
10
  }
11
11
  /** Reader-only projections, combined with applyLedger's type list by the byte filter. */
12
12
  export const READER_ENTRY_TYPES = [JT.created, 'create-intent', 'revise-intent', 'request', 'pruned', 'drain', 'undrain',
13
- JT.applied, JT.rejected, 'send-note'];
13
+ JT.admitted, JT.applied, JT.rejected, 'send-note'];
14
14
  const discardedLedgerTypes = ['switch-observed', 'skip', 'writer-hold', 'writer-release'];
15
15
  export function applyReaderLedger(ix, e) {
16
16
  if (e.type === JT.created) {
@@ -42,6 +42,10 @@ export function applyReaderLedger(ix, e) {
42
42
  }
43
43
  else if (e.type === "request") {
44
44
  const r = e.request;
45
+ const body = r?.kind === 'run' ? r.body : undefined;
46
+ if (body?.wake && typeof body.wake.to === 'string' && typeof body.caller === 'string' && typeof r?.rid === 'string' && !ix.wakeRuns.has(r.rid)) {
47
+ ix.wakeRuns.set(r.rid, { rid: r.rid, to: body.wake.to, caller: body.caller });
48
+ }
45
49
  const labels = r?.kind === "run" ? labelsOf(r.body) : undefined;
46
50
  if (labels && typeof r?.rid === "string")
47
51
  ix.runLabels.set(r.rid, labels);
@@ -49,6 +53,15 @@ export function applyReaderLedger(ix, e) {
49
53
  if (typeof session === "string" && session && typeof r?.rid === "string")
50
54
  ix.runSessions.set(r.rid, session);
51
55
  }
56
+ else if (e.type === JT.admitted && e.kind === 'run') {
57
+ const run = ix.wakeRuns.get(String(e.rid));
58
+ if (run && !run.admitted) {
59
+ run.admitted = true;
60
+ const list = ix.wakeByTo.get(run.to) ?? [];
61
+ list.push(run.rid);
62
+ ix.wakeByTo.set(run.to, list);
63
+ }
64
+ }
52
65
  else if (e.type === "pruned") {
53
66
  ix.pruned.add(String(e.wid));
54
67
  ix.labels.delete(String(e.wid));
@@ -94,9 +107,9 @@ export function readerHold(ix, wid, origin) {
94
107
  }
95
108
  const readers = new Map();
96
109
  // Canonical writer JSON: these are exactly the types that affect reader projections or applyLedger below.
97
- const needles = [...new Set([...READER_ENTRY_TYPES.filter(type => type !== 'request'),
110
+ const needles = [...new Set([...READER_ENTRY_TYPES.filter(type => type !== 'request' && type !== JT.admitted),
98
111
  ...LEDGER_ENTRY_TYPES.filter(type => !discardedLedgerTypes.includes(type))])].map(type => `"type":${JSON.stringify(type)}`);
99
- // Request records only affect labels/session for runs; the other request kinds have no reader projection.
112
+ // Run requests and run admissions affect labels/session and caller wake routing; other request kinds have no projection.
100
113
  needles.push('"kind":"run"');
101
114
  export function readerLedger(home) {
102
115
  const path = orchLedger(home);
@@ -117,4 +130,51 @@ export function readerLedger(home) {
117
130
  throw error;
118
131
  } // a partial fold is never retried as an accepted prefix
119
132
  }
133
+ const wakeReaders = new Map();
134
+ /** Only matching wake runs are read, incrementally, with a byte filter for completion and wake receipts. */
135
+ function wakeFacts(home, wid) {
136
+ const path = journalPath(home, wid);
137
+ try {
138
+ const record = readJournalFold(path, wakeReaders.get(path), () => ({ rev: 0 }), (state, e) => {
139
+ if (e.type === JT.done)
140
+ state.rev++;
141
+ if (e.type === 'wake-outcome')
142
+ state.outcome = { state: e.state, rev: Number(e.rev),
143
+ ...(typeof e.generation === 'number' ? { generation: e.generation } : {}), ...(typeof e.reason === 'string' ? { reason: e.reason } : {}) };
144
+ }, { needles: ['"type":"workflow-done"', '"type":"wake-outcome"'] });
145
+ if (record) {
146
+ wakeReaders.set(path, record);
147
+ return record.state;
148
+ }
149
+ wakeReaders.delete(path);
150
+ return { rev: 0 };
151
+ }
152
+ catch (error) {
153
+ wakeReaders.delete(path);
154
+ throw error;
155
+ }
156
+ }
157
+ export function wakeStatus(home, request, wid) {
158
+ const body = request?.kind === 'run' ? request.body : undefined;
159
+ if (!body?.wake)
160
+ return undefined;
161
+ const facts = wid ? wakeFacts(home, wid) : { rev: 0 };
162
+ return { to: body.wake.to, ...(facts.outcome && facts.outcome.rev === facts.rev ? facts.outcome : { state: 'pending' }) };
163
+ }
164
+ export function awaitingRuns(home, wid, key, revision) {
165
+ const ix = readerLedger(home).state, out = [];
166
+ for (const rid of ix.wakeByTo.get(`${wid}/${key}`) ?? []) {
167
+ const run = ix.wakeRuns.get(rid);
168
+ if (run.caller.slice(0, run.caller.indexOf('/')) !== `${wid}@${revision}` || ix.decisions.get(rid)?.type === 'rejected')
169
+ continue;
170
+ const created = ix.createdRids.get(rid), child = created ? String(created.wid) : undefined;
171
+ if (child && ix.pruned.has(child))
172
+ continue;
173
+ const facts = child ? wakeFacts(home, child) : undefined;
174
+ if (facts?.rev && facts.outcome?.rev === facts.rev)
175
+ continue;
176
+ out.push({ request: rid.startsWith('req:') ? rid.slice(4) : rid, ...(child ? { wid: child } : {}), state: !child ? 'pending' : facts?.rev ? 'finished' : 'running' });
177
+ }
178
+ return out.length ? out : undefined;
179
+ }
120
180
  export const readerLedgerIdentity = (record) => `${record.dev}:${record.ino}:${record.size}`;
@@ -18,7 +18,9 @@ export function restartInputError(body, subagent = false) {
18
18
  return "restart force needs the 12-hex token from a refused restart; first show the user the running executions";
19
19
  return undefined;
20
20
  }
21
- export function restartRefusal(home, live, body, tool = false, now = Date.now()) {
21
+ /** `commands`: command calls running now. They are never in `live` (nor in the token): a restart leaves them running and
22
+ * the successor adopts them; a refusal shown for other executions says so in one line. */
23
+ export function restartRefusal(home, live, body, tool = false, now = Date.now(), commands = 0) {
22
24
  const invalid = restartInputError(body);
23
25
  if (invalid)
24
26
  return invalid;
@@ -53,6 +55,7 @@ export function restartRefusal(home, live, body, tool = false, now = Date.now())
53
55
  `${origin}:`, ...executions.map(l => ` ${l.wid}/${l.key} ${age(now - l.since)}${l.phase === "gate" ? " gate" : ""}${leases.has(l.callId) ? ` ${leases.get(l.callId)}` : ""}`),
54
56
  ]),
55
57
  ...(others.length ? ["not fenced (a restart leaves these leases held):", ...others] : []),
58
+ ...(commands > 0 ? [`not fenced: ${commands} command call${commands === 1 ? "" : "s"} keep${commands === 1 ? "s" : ""} running across the restart`] : []),
56
59
  `token: ${token}`,
57
60
  tool ? `to fence exactly these: subagents {action:"restart", force:"${token}", reason:"<why>"}` : `to fence exactly these: pi-durable-subagents restart --force ${token} --reason "<why>"`,
58
61
  ].join("\n");
@@ -17,6 +17,7 @@ import { revisionEntries, terminalEntry } from "./store.js";
17
17
  import { RECOVERY_VERSION } from "./executor/recovered.js";
18
18
  import { sweepSeed } from "./executor/sweep.js";
19
19
  import { callEntries } from "./executor/indexes.js";
20
+ import { unsealedCommandCalls } from "./executor/command.js";
20
21
  /** Bump whenever the record gains a field or settledFacts a condition: every record is then rebuilt once. */
21
22
  export const SETTLED_VERSION = 2;
22
23
  export const settledPath = (home, wid) => join(cacheDir(home), "settled", `${wid}.json`);
@@ -29,6 +30,8 @@ export function settledFacts(wf, recovered) {
29
30
  const log = wf.journal.entries(), rev = revisionEntries(wf), done = terminalEntry(rev);
30
31
  if (!done)
31
32
  return "running";
33
+ if (wf.wake && !log.some(e => e.type === "wake-outcome" && e.rev === log.filter(e => e.type === JT.done).length))
34
+ return "wake pending";
32
35
  const has = (type, field, value) => log.some(e => e.type === type && e[field] === value);
33
36
  const sealedCalls = new Set(log.filter(e => e.type === JT.sealed).map(e => String(e.call)));
34
37
  const ended = new Set([...sealedCalls, ...log.filter(e => e.type === "retired").map(e => String(e.call))]);
@@ -41,6 +44,9 @@ export function settledFacts(wf, recovered) {
41
44
  if (!fenced.has(String(e.exec)))
42
45
  return `unfenced:${String(e.exec)}`;
43
46
  }
47
+ // A command call with an attempt and no seal may still run: the next start adopts it.
48
+ for (const call of unsealedCommandCalls(log))
49
+ return `live:${call}`;
44
50
  for (const call of calls) {
45
51
  if (!ended.has(call))
46
52
  return `live:${call}`;
@@ -3,14 +3,14 @@
3
3
  import { initiatorSummary, restartLine } from "./restart.js";
4
4
  import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
5
5
  import { join } from "node:path";
6
- import { compileFanout } from "../compat/fanout.js";
6
+ import { FANOUT_BODIES } from "../compat/fanout.js";
7
7
  import { crc32, forgetJournalSnapshot, forgetJournalSnapshotsIf, journalAppends, readJournalRecord, readJournalSnapshot, readJournalUncached } from "../kernel/journal.js";
8
8
  import { readCache, writeCache } from "../kernel/cache.js";
9
9
  import { digestDir, journalPath, pinnedDir, workflowDir } from "../paths.js";
10
10
  import { JT, attentionEntries, isEntry } from "../types.js";
11
11
  import { parseModel, resolveModel } from "../compat/model.js";
12
12
  import {} from "./ledger.js";
13
- import { readerHold, readerLedger, readerLedgerIdentity } from "./reader-ledger.js";
13
+ import { awaitingRuns, readerHold, readerLedger, readerLedgerIdentity } from "./reader-ledger.js";
14
14
  import { packageVersion } from "../version.js";
15
15
  import { worktreeCalls, worktreeLabel } from "./executor/worktree.js";
16
16
  import { leaseCalls, leaseLines, leaseState } from "../platform/lease.js";
@@ -31,6 +31,44 @@ export function modelStatusText(c, now = Date.now()) {
31
31
  (c.routedModel ? ` (routed ${c.routedModel})` : "") +
32
32
  (m ? ` (used ${m.used}, selected ${m.selected})` : "") + (c.modelUnavailable ? ` (model-unavailable: ${c.modelUnavailable})` : "");
33
33
  }
34
+ /** A command call's command as one line: an argv array joined with spaces (an argument that needs it single-quoted as
35
+ * for sh), a string as it is. */
36
+ export function commandText(command) {
37
+ if (Array.isArray(command))
38
+ return command.map(a => { const s = String(a); return /^[A-Za-z0-9_./:=@%+,-]+$/.test(s) ? s : `'${s.replaceAll("'", "'\\''")}'`; }).join(" ");
39
+ return String(command ?? "");
40
+ }
41
+ /** R8: The pinned refusal of a send to a command call (the engine gives the same reason). */
42
+ export const commandSendRefusal = (kind) => `command call: ${kind} is not supported (stop it, or start a new call)`;
43
+ /** R8, F5: Whether a send address names a command call, matched whole as the engine's findCall does, among the
44
+ * current revision's calls: `<wid>/<key>`, `<wid>@<rev>/<key>@<gen>`, or a bare wid of a workflow with one key. A key
45
+ * may contain `@` and digits: nothing is stripped. Read-only; false for anything it cannot resolve. */
46
+ export function isCommandTarget(home, to) {
47
+ if (typeof to !== "string" || !to)
48
+ return false;
49
+ const wid = to.split(/[@/]/, 1)[0]; // a wid has neither '@' nor '/'
50
+ if (!wid || !existsSync(journalPath(home, wid)))
51
+ return false;
52
+ let entries;
53
+ try {
54
+ entries = readJournalSnapshot(journalPath(home, wid));
55
+ }
56
+ catch {
57
+ return false;
58
+ }
59
+ const rev = Math.max(1, ...entries.filter(e => e.type === "wf-created" || e.type === "revised").map(e => Number(e.revision) || 1));
60
+ const start = entries.findLastIndex(e => e.type === "revised");
61
+ const calls = (start < 0 ? entries : entries.slice(start)).filter(e => e.type === "call" || e.type === "generation");
62
+ const keys = new Set(calls.map(e => String(e.key)));
63
+ const named = calls.findLast(e => to === `${wid}/${e.key}` || to === `${wid}@${rev}/${e.key}@${e.gen}` || (to === wid && keys.size === 1));
64
+ if (!named)
65
+ return false;
66
+ return calls.findLast(e => e.key === named.key).spec?.command !== undefined;
67
+ }
68
+ /** A command clipped to one display line of at most `n` characters ("command: <clipped>" in status and the UI). */
69
+ export function commandLine(command, n = 80) {
70
+ return clip(command.replace(/\s+/g, " ").trim(), n);
71
+ }
34
72
  /** A workflow has live work: it runs, or follow-ups opened on it after it finished have not ended yet. */
35
73
  export function isLive(wf) {
36
74
  return wf.status === "running" || (wf.followUps ?? 0) > 0;
@@ -46,8 +84,8 @@ export function progressOf(wf) {
46
84
  const done = [...latest.values()].filter(c => c.phase === "sealed").length;
47
85
  return { done, total: wf.planned ?? latest.size, plus: wf.planned === undefined && wf.status === "running" };
48
86
  }
49
- // v12 §4: the exact bodies compileFanout emits after the `const steps = [...];` line, so only true fanouts count as planned.
50
- const fanoutBodies = [compileFanout({ tasks: [] }).source, compileFanout({ chain: [] }).source].map(s => s.slice(s.indexOf("\n") + 1));
87
+ // v12 §4: the exact bodies compileFanout emits (or emitted) after the `const steps = [...];` line, so only true fanouts count as planned.
88
+ const fanoutBodies = FANOUT_BODIES;
51
89
  /** v12 §4: The planned total of a pinned script: its steps count when it is a compiled tasks/chain fanout; scripts have none. */
52
90
  export function plannedFromScript(source) {
53
91
  const cut = source.indexOf("\n"), head = source.slice(0, Math.max(0, cut)), rest = source.slice(cut + 1);
@@ -101,6 +139,7 @@ function snapshotReducer(wid, entries) {
101
139
  let terminal = current.findLast(e => e.type === JT.done || (e.type === "resumed" && !e.call));
102
140
  const calls = new Map();
103
141
  const byExec = new Map();
142
+ const byCommand = new Map(); // command attempt id -> its call
104
143
  const hibernating = new Map(); // callId → exec that decided to hibernate and is not fenced yet
105
144
  const fenced = new Set();
106
145
  const resolved = new Set();
@@ -109,6 +148,7 @@ function snapshotReducer(wid, entries) {
109
148
  // P31: usage per call id, deduplicated by message id; a seal carries the authoritative total.
110
149
  const live = new Map(), sealedUsage = new Map(), seen = new Set();
111
150
  const tools = new Map();
151
+ const endedAtSeal = new Map();
112
152
  // P7, P27: forward / forward-delivered / forward-retired, by destination call; retirements carry only rid2.
113
153
  const sends = new Map(), byRid2 = new Map();
114
154
  // Pending notes of the current revision by key (notes.ts): recorded rids, and those a generation carried.
@@ -133,7 +173,9 @@ function snapshotReducer(wid, entries) {
133
173
  const result = e.type === "refused" ? refusedResult(key, e.reason) :
134
174
  e.type === "reused" ? entries.find(s => s.type === JT.sealed && s.call === e.from)?.result : undefined;
135
175
  const wanted = e.spec?.model;
176
+ const command = e.spec?.command;
136
177
  calls.set(callId, { key, gen, callId, pos: Number(e.pos), agent: String(e.spec?.agent ?? ""),
178
+ ...(command !== undefined ? { command: commandText(command) } : {}),
137
179
  // Until a slot is acquired (`selected`), show the model the call asked for, not nothing.
138
180
  ...(typeof wanted === "string" && wanted ? { model: wanted } : {}),
139
181
  phase: result ? "sealed" : "queued", ...(result ? { result, endedAt: e.ts } : {}),
@@ -168,6 +210,26 @@ function snapshotReducer(wid, entries) {
168
210
  hibernating.delete(call.callId);
169
211
  }
170
212
  }
213
+ else if (e.type === "command-intent") {
214
+ // A command call runs from its intent until its seal; it never has an `exec`, so nothing treats it as an execution.
215
+ const call = calls.get(String(e.call));
216
+ if (call && call.phase !== "sealed") {
217
+ call.commandRun = { attempt: Number(e.n) || 1, id: String(e.id) };
218
+ call.phase = "running";
219
+ call.startedAt = e.ts;
220
+ call.lastActivity = e.ts;
221
+ delete call.writerWait;
222
+ byCommand.set(String(e.id), call);
223
+ }
224
+ }
225
+ else if (e.type === "command-started") {
226
+ const call = byCommand.get(String(e.id)), dir = e.dir;
227
+ if (call && call.commandRun?.id === e.id) {
228
+ call.commandRun = { ...call.commandRun, ...(Number.isSafeInteger(e.pid) ? { pid: Number(e.pid) } : {}), ...(typeof dir === "string" ? { log: join(dir, "output.log") } : {}) };
229
+ call.startedAt = e.ts;
230
+ call.lastActivity = e.ts;
231
+ }
232
+ }
171
233
  else if (e.type === "slot-wait") {
172
234
  const call = byExec.get(String(e.exec));
173
235
  if (call && call.exec === e.exec) {
@@ -288,6 +350,10 @@ function snapshotReducer(wid, entries) {
288
350
  total.costUsd += u.costUsd;
289
351
  live.set(String(e.call), total);
290
352
  }
353
+ else if (isEntry(e, 'ended')) {
354
+ const prior = endedAtSeal.get(e.call), procs = [...(prior?.procs ?? []), ...e.procs];
355
+ endedAtSeal.set(e.call, { procs: procs.slice(0, 20), more: (prior?.more ?? 0) + Math.max(0, procs.length - 20) + (e.more ?? 0) });
356
+ }
291
357
  else if (e.type === JT.sealed) {
292
358
  const usage = e.result?.usage;
293
359
  if (usage)
@@ -364,6 +430,11 @@ function snapshotReducer(wid, entries) {
364
430
  if (c.phase !== "sealed" && c.phase !== "queued")
365
431
  delete c.poolWait;
366
432
  counts[c.phase]++;
433
+ const ended = endedAtSeal.get(c.callId);
434
+ if (ended?.procs.length)
435
+ c.endedAtSeal = structuredClone(ended.procs);
436
+ if (ended?.more)
437
+ c.endedAtSealMore = ended.more;
367
438
  const usage = usageOf(c.callId);
368
439
  if (usage)
369
440
  c.usage = { ...usage };
@@ -489,6 +560,9 @@ const digests = new Map();
489
560
  const FINAL_STATUS = new Set(["done", "failed", "stopped"]);
490
561
  /** Post-seal/recovery work that can append without a new request must not enter a polling trust window. */
491
562
  export function pendingRecovery(wid, entries) {
563
+ const rev = entries.filter(e => e.type === JT.done).length;
564
+ if (entries.some(e => e.type === 'wf-created' && e.wake) && !entries.some(e => e.type === 'wake-outcome' && e.rev === rev))
565
+ return true;
492
566
  const start = entries.findLastIndex(e => e.type === "revised"), current = start < 0 ? entries : entries.slice(start);
493
567
  const consumed = new Set(current.filter(e => e.type === "generation").flatMap(generationRids));
494
568
  const retiredForwards = new Map(entries.filter(e => e.type === "forward-retired").map(e => [String(e.rid2), e]));
@@ -892,7 +966,8 @@ export function queueWait(c, state, now = Date.now(), starting = orchestratorSta
892
966
  return undefined;
893
967
  if (starting)
894
968
  return { reason: "starting", detail: "orchestrator starting", since: starting.since };
895
- const settings = state.config?.settings ?? {}, pools = settings.pools ?? {}, wanted = c.poolWait?.model ?? c.model ?? settings.defaultModel;
969
+ // A command call takes no provider slot: only the orchestrator's start and a writer lock hold it back.
970
+ const settings = state.config?.settings ?? {}, pools = settings.pools ?? {}, wanted = c.command !== undefined ? undefined : c.poolWait?.model ?? c.model ?? settings.defaultModel;
896
971
  let providers = [];
897
972
  if (wanted && Object.hasOwn(pools, wanted)) {
898
973
  try {
@@ -1076,6 +1151,20 @@ export function formatUsage(u) {
1076
1151
  const n = (v) => v >= 1e6 ? `${(v / 1e6).toFixed(2)}M` : v >= 1e3 ? `${(v / 1e3).toFixed(1)}K` : String(v);
1077
1152
  return `${n(u.input)} in / ${n(u.output)} out${u.costUsd > 0 ? `, $${u.costUsd.toFixed(u.costUsd < 0.01 ? 4 : 2)}` : ""}`;
1078
1153
  }
1154
+ /** The CommandStatus of a command call (empty for an agent call): pid only while it is live. */
1155
+ export function commandStatus(c, now = Date.now()) {
1156
+ if (c.command === undefined)
1157
+ return {};
1158
+ const run = c.commandRun, data = c.result?.data, live = c.phase !== "sealed" && run !== undefined;
1159
+ return { command: commandLine(c.command),
1160
+ ...(live && run.pid !== undefined ? { pid: run.pid } : {}), ...(live && (run.attempt ?? 1) > 1 ? { attempt: run.attempt } : {}),
1161
+ ...(live && c.startedAt !== undefined ? { for: age(now - c.startedAt) } : {}),
1162
+ ...(typeof data?.exitCode === "number" ? { exitCode: data.exitCode } : {}), ...(typeof data?.signal === "string" ? { signal: data.signal } : {}) };
1163
+ }
1164
+ /** "pid 123" / "exit 3" / "SIGKILL" of a command call's status line (empty for an agent call or before the start). */
1165
+ export function commandFacts(c) {
1166
+ return [c.pid !== undefined ? `pid ${c.pid}` : "", c.attempt ? `attempt ${c.attempt}` : "", c.for ?? "", c.exitCode !== undefined ? `exit ${c.exitCode}` : "", c.signal ?? ""].filter(Boolean).join(", ");
1167
+ }
1079
1168
  /** P25, T10: Compact one workflow snapshot: per-call one-line facts, usage, open attention; no outputs or entries. */
1080
1169
  export function compactWorkflow(wf, leases) {
1081
1170
  const progress = progressOf(wf); // v12 §4
@@ -1087,7 +1176,7 @@ export function compactWorkflow(wf, leases) {
1087
1176
  ...(wf.planned !== undefined ? { planned: wf.planned } : {}), done: progress.done,
1088
1177
  calls: wf.calls.map(c => {
1089
1178
  const r = c.result, last = r?.output?.split("\n").map(l => l.trim()).filter(Boolean).at(-1);
1090
- return { key: c.key, gen: c.gen, callId: c.callId, phase: c.phase, ...modelStatus(c), ...(r ? { status: r.status, ok: r.ok } : {}),
1179
+ return { key: c.key, gen: c.gen, callId: c.callId, phase: c.phase, ...modelStatus(c), ...commandStatus(c), ...(r ? { status: r.status, ok: r.ok } : {}),
1091
1180
  ...(c.sharedWorktree ? { sharedWorktree: c.sharedWorktree } : {}),
1092
1181
  ...(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 } : {}),
1093
1182
  ...(last ? { lastLine: clip(last, 200) } : {}), ...(r?.error ? { error: clip(r.error, 300) } : {}), ...(c.hibernated ? { hibernated: true } : {}),
@@ -1198,6 +1287,8 @@ export function versionNote(running, loaded) {
1198
1287
  }
1199
1288
  /** The first version whose orchestrator and child know send kind "notify". */
1200
1289
  export const NOTIFY_SINCE = "1.0.28";
1290
+ /** The first orchestrator version that delivers run --wake caller. */
1291
+ export const WAKE_SINCE = "1.1.0";
1201
1292
  /** A refusal when the orchestrator running now predates `since` and is older than the version this process loaded (an
1202
1293
  * older orchestrator would accept the request and its child would drop it); none when none runs (the next one starts
1203
1294
  * on the installed version) or it is current. */
@@ -1274,12 +1365,13 @@ export function statusBrief(home, options = {}) {
1274
1365
  const brief = (w) => {
1275
1366
  const p = progressOf(w), open = w.attention.filter(a => a.kind !== "finished");
1276
1367
  const calls = latestCalls(w).filter(c => c.phase !== "sealed" || (c.result && !c.result.ok) || c.notesPending).map((c) => {
1277
- const live = c.phase !== "sealed", quiet = c.lastActivity !== undefined ? now - c.lastActivity : undefined;
1278
- return { key: c.key, agent: c.agent, phase: c.phase, ...modelStatus(c), ...(c.model ? { model: c.model } : {}),
1368
+ // A command call shows its command, pid and age instead of a model, quiet time and tokens.
1369
+ const live = c.phase !== "sealed", quiet = c.lastActivity !== undefined ? now - c.lastActivity : undefined, agent = c.command === undefined;
1370
+ return { key: c.key, agent: c.agent, phase: c.phase, ...modelStatus(c), ...(c.model ? { model: c.model } : {}), ...commandStatus(c, now),
1279
1371
  ...(c.sharedWorktree ? { sharedWorktree: c.sharedWorktree } : {}),
1280
1372
  ...(live && c.startedAt !== undefined ? { for: age(now - c.startedAt) } : {}),
1281
- ...(live && c.phase !== "asking" && quiet !== undefined && quiet >= 60_000 ? { quiet: age(quiet) } : {}),
1282
- ...(live && c.startedAt !== undefined ? { tokens: tokens(c.usage) } : {}),
1373
+ ...(agent && live && c.phase !== "asking" && quiet !== undefined && quiet >= 60_000 ? { quiet: age(quiet) } : {}),
1374
+ ...(agent && live && c.startedAt !== undefined ? { tokens: tokens(c.usage) } : {}),
1283
1375
  ...(c.result ? { status: c.result.status, ...(c.result.error ? { error: clip(c.result.error, 200) } : {}) } : {}),
1284
1376
  ...(c.hibernated ? { hibernated: true } : {}), ...(c.answered ? { answered: c.answered } : {}), ...(c.answerForwarded ? { answerForwarded: c.answerForwarded } : {}), ...(live && c.writerWait ? { writerWait: c.writerWait } : {}),
1285
1377
  ...(live && byCall.get(c.callId) ? { lease: byCall.get(c.callId) } : {}),
@@ -1398,7 +1490,8 @@ export function statusDetail(home, wid) {
1398
1490
  if (!origin.has(wid))
1399
1491
  throw new Error(prunedIds(home).has(wid) ? `Workflow ${wid} was pruned` : `Unknown workflow: ${wid}`);
1400
1492
  const held = heldWorkflows(home), wf = labelled(workflowSnapshot(home, wid), held.labels(wid), held.session(wid)), log = scriptLogPath(home, wid);
1401
- return { ...wf, ...(wf.origin === undefined && origin.get(wid) !== undefined ? { origin: origin.get(wid) } : {}), ...(existsSync(log) ? { scriptLog: log } : {}),
1493
+ const calls = wf.calls.map(c => { const awaiting = awaitingRuns(home, wid, c.key, wf.rev); return awaiting ? { ...c, awaiting } : c; });
1494
+ return { ...wf, calls, ...(wf.origin === undefined && origin.get(wid) !== undefined ? { origin: origin.get(wid) } : {}), ...(existsSync(log) ? { scriptLog: log } : {}),
1402
1495
  ...(isLive(wf) && held.held(wid) ? { paused: true } : {}) };
1403
1496
  }
1404
1497
  /** P25, T10: Project a workflow journal into meaningful events (no observations, time or tracking). */
@@ -375,7 +375,7 @@ export class Store {
375
375
  async create(req) {
376
376
  let intent = this.index().createByRid.get(req.rid);
377
377
  intent ??= await this.ledgers.orch.append('create-intent', { rid: req.rid, wid: ulid(), origin: req.from, cwd: req.body.cwd,
378
- ...(req.body.name !== undefined ? { name: req.body.name } : {}), snapshot: await this.reference(req.rid) });
378
+ ...(req.body.name !== undefined ? { name: req.body.name } : {}), ...(req.body.wake ? { wake: { rid: req.rid, to: req.body.wake.to, caller: req.body.caller } } : {}), snapshot: await this.reference(req.rid) });
379
379
  return this.materialize(intent);
380
380
  }
381
381
  /** P14, A5: Bind the next revision before retiring any old authority. */
@@ -627,7 +627,7 @@ export class Store {
627
627
  try {
628
628
  const current = settled.revised ?? intent, files = await this.pinnedFiles(wid, settled.revision, current, false);
629
629
  const facts = { revision: settled.revision, ...(settled.revised ? { revised: settled.revised } : {}), done: settled.done, resumed: settled.resumed, quiet: settled.quiet, calls: settled.calls, sweep: settled.sweep };
630
- const wf = { wid, revision: settled.revision, origin: intent.origin, cwd: intent.cwd, journal: lazy, ...files, settled: facts };
630
+ const wf = { wid, revision: settled.revision, origin: intent.origin, cwd: intent.cwd, journal: lazy, ...files, settled: facts, ...(intent.wake ? { wake: intent.wake } : {}) };
631
631
  this.releasePins(wf);
632
632
  this.unverified.set(wid, current);
633
633
  lazy.onAppend = () => this.appended?.(wid);
@@ -655,7 +655,7 @@ export class Store {
655
655
  // terminalEntry over the whole journal: a `revised` after the last done supersedes it, as in the revision's view.
656
656
  const ended = !first && entries.length > 0 && terminalEntry(entries) !== undefined;
657
657
  const files = first ?? (ended ? await this.pinnedFiles(wid, revision, current, false) : await this.pinnedFiles(wid, 1, intent));
658
- wf = { wid, revision: ended ? revision : 1, origin: intent.origin, cwd: intent.cwd, journal, ...files };
658
+ wf = { wid, revision: ended ? revision : 1, origin: intent.origin, cwd: intent.cwd, journal, ...files, ...(intent.wake ? { wake: intent.wake } : {}) };
659
659
  if (ended) {
660
660
  this.releasePins(wf);
661
661
  this.unverified.set(wid, current);
@@ -669,7 +669,7 @@ export class Store {
669
669
  this.workflows.set(wid, wf);
670
670
  if (!journal.entries().length)
671
671
  await journal.append('wf-created', { rid: intent.rid, origin: intent.origin, cwd: intent.cwd, revision: 1,
672
- ...(intent.name !== undefined ? { name: intent.name } : {}) });
672
+ ...(intent.name !== undefined ? { name: intent.name } : {}), ...(intent.wake ? { wake: intent.wake } : {}) });
673
673
  const revised = journal.entries().findLast(e => e.type === 'revised');
674
674
  if (revised && wf.revision !== Number(revised.revision))
675
675
  Object.assign(wf, await this.pinnedFiles(wid, Number(revised.revision), revised), { revision: Number(revised.revision) });
@@ -0,0 +1,16 @@
1
+ import { execFile } from "node:child_process";
2
+ import { readFile } from "node:fs/promises";
3
+ import { promisify } from "node:util";
4
+ import { PS } from "./proctable.js";
5
+ const exec = promisify(execFile);
6
+ /** EX1: A diagnostic argv, never evidence of identity or death. Unreadable processes have an empty command. */
7
+ export async function commandLine(pid, signal) {
8
+ try {
9
+ if (process.platform === "linux")
10
+ return (await readFile(`/proc/${pid}/cmdline`, { encoding: "utf8", signal })).replace(/\0/g, " ").trimEnd().slice(0, 200);
11
+ if (process.platform === "darwin")
12
+ return (await exec(PS, ["-o", "command=", "-p", String(pid)], { signal, timeout: 450, maxBuffer: 1024 * 1024 })).stdout.trim().slice(0, 200);
13
+ }
14
+ catch { /* Diagnostics must not prevent a fence. */ }
15
+ return "";
16
+ }
@@ -0,0 +1,98 @@
1
+ // Command calls (CallSpec.command): the launcher. A command runs detached in its own session under a tiny /bin/sh
2
+ // wrapper that runs it, then records its exit status atomically in the attempt directory (`exit.tmp`, renamed to `exit`)
3
+ // and exits with the same status. Its output (stdout and stderr, interleaved) is appended to `output.log` in the same
4
+ // directory through a descriptor the orchestrator opens, passes and closes: no pipe leads back into the orchestrator and
5
+ // no node process stays resident for the life of the command, so it outlives the orchestrator that started it.
6
+ import { spawn } from "node:child_process";
7
+ import { closeSync, openSync } from "node:fs";
8
+ import { mkdir, readFile, stat, open } from "node:fs/promises";
9
+ import { constants } from "node:os";
10
+ import { join } from "node:path";
11
+ import { captureStart } from "./proctable.js";
12
+ import { findOnPath } from "./launch.js";
13
+ export const COMMAND_LOG = "output.log";
14
+ export const COMMAND_EXIT = "exit";
15
+ /** The output a result carries: the last bytes of `output.log`. */
16
+ export const OUTPUT_TAIL_BYTES = 16 * 1024;
17
+ /** The wrapper: `$1` is the attempt directory, `$2` the absolute `mv`, the rest the command's argv. Its own steps use
18
+ * only shell builtins and that absolute `mv` with every expansion quoted, so they work under any environment the
19
+ * command gets (PATH unset or bogus, IFS, LC_*). The argv runs through `exec` in a subshell: it is always a program
20
+ * (looked up on the command's PATH; a shell builtin name such as `exit` is no builtin there, 127 when no program has
21
+ * it), and its end, however it comes, never skips recording the status. A program named by a path that does not exist
22
+ * is 127 before `exec`: some shells (bash 3.2, the macOS /bin/sh) report 126 for it instead. */
23
+ const WRAPPER = 'd="$1"; m="$2"; shift 2; ( case "$1" in (*/*) [ -e "$1" ] || { printf "%s: %s: not found\\n" "$0" "$1" >&2; exit 127; } ;; esac; exec "$@" ); s="$?"; printf "%s\\n" "$s" > "$d/exit.tmp" && "$m" -f "$d/exit.tmp" "$d/exit"; exit "$s"';
24
+ /** `mv` for the wrapper: from this process's PATH, else /bin or /usr/bin; resolved once. */
25
+ let mvPath;
26
+ export function resolveMv(PATH = process.env.PATH) {
27
+ mvPath ??= findOnPath("mv", PATH) ?? findOnPath("mv", "/bin:/usr/bin") ?? "/bin/mv";
28
+ return mvPath;
29
+ }
30
+ /** The argv the wrapper runs: an argv as given (a program, never shell syntax), a string through `/bin/sh -c`. */
31
+ export const commandArgv = (command) => typeof command === "string" ? ["/bin/sh", "-c", command] : [...command];
32
+ export async function spawnCommand(spec) {
33
+ await mkdir(spec.dir, { recursive: true });
34
+ const fd = openSync(join(spec.dir, COMMAND_LOG), "a");
35
+ try {
36
+ const mv = resolveMv(), argv = commandArgv(spec.command);
37
+ if (spec.proceed && !spec.proceed())
38
+ return undefined;
39
+ const child = spawn("/bin/sh", ["-c", WRAPPER, "dsa-command", spec.dir, mv, ...argv], { cwd: spec.cwd, env: spec.env, detached: true, stdio: ["ignore", fd, fd] });
40
+ const exited = new Promise(resolve => { child.once("exit", () => resolve()); child.once("error", () => resolve()); });
41
+ await new Promise((resolve, reject) => { child.once("spawn", resolve); child.once("error", reject); });
42
+ child.unref();
43
+ const pid = child.pid;
44
+ const start = child.exitCode !== null || child.signalCode !== null ? "" : await captureStart(pid).catch(() => "");
45
+ return { pid, start, exited };
46
+ }
47
+ finally {
48
+ closeSync(fd);
49
+ }
50
+ }
51
+ /** The status the wrapper recorded, or undefined while there is none (the command runs, or ended without one). */
52
+ export async function readExitRecord(dir) {
53
+ const path = join(dir, COMMAND_EXIT);
54
+ let text, at;
55
+ try {
56
+ [text, at] = await Promise.all([readFile(path, "utf8"), stat(path).then(s => s.mtimeMs)]);
57
+ }
58
+ catch (error) {
59
+ if (error.code === "ENOENT")
60
+ return undefined;
61
+ throw error;
62
+ }
63
+ const status = Number(text.trim());
64
+ return Number.isInteger(status) && status >= 0 ? { status, at } : undefined;
65
+ }
66
+ const signalNames = new Map(Object.entries(constants.signals).map(([name, n]) => [n, name]));
67
+ /** How an exit status reads. The wrapper sees the status of a shell: a command killed by signal N exits 128+N. A command
68
+ * that itself exits with a status above 128 (`exit 130`) therefore reads as killed by that signal: the two cannot be
69
+ * told apart from the status alone (the shell convention). */
70
+ export function exitMeaning(status) {
71
+ const name = status > 128 ? signalNames.get(status - 128) : undefined;
72
+ return name ? { exitCode: null, signal: name } : { exitCode: status, signal: null };
73
+ }
74
+ /** The last `bytes` of a file, starting on a UTF-8 character boundary ("" when it is missing). */
75
+ export async function readTail(path, bytes = OUTPUT_TAIL_BYTES) {
76
+ const file = await open(path, "r").catch(error => { if (error.code === "ENOENT")
77
+ return undefined; throw error; });
78
+ if (!file)
79
+ return "";
80
+ try {
81
+ const { size } = await file.stat(), from = Math.max(0, size - bytes), buffer = Buffer.alloc(size - from);
82
+ for (let read = 0; read < buffer.length;) {
83
+ const { bytesRead } = await file.read(buffer, read, buffer.length - read, from + read);
84
+ if (!bytesRead)
85
+ break;
86
+ read += bytesRead;
87
+ }
88
+ // Skip continuation bytes (10xxxxxx) a cut in the middle of a character left at the start.
89
+ let skip = 0;
90
+ if (from > 0)
91
+ while (skip < buffer.length && skip < 4 && (buffer[skip] & 0xc0) === 0x80)
92
+ skip++;
93
+ return buffer.subarray(skip).toString("utf8");
94
+ }
95
+ finally {
96
+ await file.close();
97
+ }
98
+ }
@@ -104,6 +104,7 @@ export class Containment {
104
104
  if (!Number.isFinite(timeout) || timeout < 0)
105
105
  throw new Error("Invalid fence timeout");
106
106
  const deadline = performance.now() + timeout;
107
+ let recordingMs = 500;
107
108
  const known = new Map(tracked.filter(p => p.start !== "").map(p => [identity(p), p]));
108
109
  for (;;) {
109
110
  const remaining = deadline - performance.now();
@@ -119,11 +120,44 @@ export class Containment {
119
120
  }
120
121
  if (performance.now() >= deadline)
121
122
  throw new Error(`Fence timeout: ${exec}`);
123
+ const killing = [];
122
124
  for (const p of targets) {
123
125
  known.set(identity(p), p);
124
126
  // C3: the pid may have exited and been reused since the scan; kill only if it still has the scanned start.
125
127
  if (p.start !== "" && await captureStart(p.pid) !== p.start)
126
128
  continue;
129
+ if (!opts.beforeKill) {
130
+ try {
131
+ process.kill(p.pid, "SIGKILL");
132
+ }
133
+ catch (error) {
134
+ if (error.code !== "ESRCH")
135
+ throw error;
136
+ }
137
+ }
138
+ else
139
+ killing.push(p);
140
+ }
141
+ if (killing.length && opts.beforeKill && recordingMs > 0) {
142
+ const recordingStarted = performance.now(), controller = new AbortController();
143
+ let timer;
144
+ try {
145
+ await Promise.race([
146
+ Promise.resolve().then(() => opts.beforeKill(killing, controller.signal)),
147
+ new Promise(resolve => { timer = setTimeout(() => { controller.abort(); resolve(); }, recordingMs); }),
148
+ ]);
149
+ }
150
+ catch { /* A recording failure must never prevent SIGKILL. */ }
151
+ finally {
152
+ clearTimeout(timer);
153
+ controller.abort();
154
+ recordingMs = Math.max(0, recordingMs - (performance.now() - recordingStarted));
155
+ }
156
+ }
157
+ for (const p of killing) {
158
+ // Diagnostic I/O was asynchronous: revalidate identity again before signalling.
159
+ if (opts.beforeKill && p.start !== "" && await captureStart(p.pid) !== p.start)
160
+ continue;
127
161
  try {
128
162
  process.kill(p.pid, "SIGKILL");
129
163
  }
@@ -100,15 +100,25 @@ export async function scopeRunner(env, options = {}) {
100
100
  function started(child) {
101
101
  return new Promise((resolve, reject) => { child.once("spawn", resolve); child.once("error", reject); });
102
102
  }
103
+ /** The variables the executor sets for one call's processes (a subagent, a command call, a gate). An orchestrator
104
+ * started from inside a call (its CLI, a command that runs `start`) never carries them: with the call's DSA_EXEC it
105
+ * would be one of that call's processes, and the call's fence (its end, a stop) would kill it. */
106
+ export const PER_CALL_ENV = ["DSA_SESSION", "DSA_EXEC", "DSA_CALL", "DSA_INBOX", "DSA_JOURNAL", "DSA_SCHEMA", "DSA_BUDGET", "DSA_MODEL", "DSA_RESULT", "DSA_OUTPUT", "DSA_PROBE"];
107
+ /** `env` without PER_CALL_ENV. */
108
+ export function orchestratorEnv(env) {
109
+ const rest = { ...env };
110
+ for (const name of PER_CALL_ENV)
111
+ delete rest[name];
112
+ return rest;
113
+ }
103
114
  /** 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
115
+ * session) and every other per-call variable (PER_CALL_ENV) plus DSA_HOME and the resolved DSA_PI_BIN. In its own systemd scope when one is available (the scope execs
105
116
  * the command: same environment, and the pid is the orchestrator's), else a plain detached process. */
106
117
  export async function launchOrchestrator(entry, env, options) {
107
118
  const pi = resolvePi(env);
108
119
  if (!pi.path && options.requirePi)
109
120
  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 } : {}) };
121
+ const childEnv = { ...orchestratorEnv(env), DSA_HOME: options.home, ...(pi.path ? { DSA_PI_BIN: pi.path } : {}) };
112
122
  const node = options.node ?? process.execPath, run = options.spawn ?? spawn;
113
123
  const runner = await scopeRunner(env, options);
114
124
  if (runner) {