pi-durable-subagents 1.0.45 → 1.2.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,10 +1,12 @@
1
- // Private journal entries (A1): tracked{exec,pid,start}; loss{exec}; settled{exec};
1
+ // Private journal entries (A1): tracked{exec,pid,start,child?} (child:true identifies the direct pi process);
2
+ // loss{exec}; settled{exec};
2
3
  // stop-intent{call}; forward{rid,rid2,dest,hash,envelope:{to,kind,body,cond?}};
3
4
  // forward-delivered{rid,rid2,call,reason?}: the first observed child receipt of a forward (once per forward; reason when
4
5
  // the child resolved it as rejected, e.g. withdrawn); forward-retired{rid,rid2,reason}: sealed/retired without a receipt (P27);
5
6
  // an undelivered notify becomes a pending-note{rid,call,key,message} first (../notes.ts).
6
7
  // observation{exec,event}; selected{exec,model}; switch-observed{exec,rid,pool}.
7
8
  // P28 entries are documented in hibernate.ts; generation session publication in generation.ts.
9
+ // ended{exec,call,procs:[{pid,command}],more?}: agent fence SIGKILL targets other than its direct child (EX1/WK8).
8
10
  // session-corrupt{call,line}: a malformed native session line was skipped (once per line, E4).
9
11
  // spawn-env-failed{exec,call,command,error}: launching the child failed for a reason of the environment (ENOENT, EACCES:
10
12
  // pi or its interpreter missing or not executable); the call stays queued and launches again after a backoff.
@@ -24,7 +26,7 @@ import { setTimeout as delay } from "node:timers/promises";
24
26
  import { homedir } from "node:os";
25
27
  import { delimiter, dirname, join } from "node:path";
26
28
  import { fileURLToPath } from "node:url";
27
- import { CT, JT, attentionEntries, isCommandCall, isEntry } from "../../types.js";
29
+ import { CT, JT, askFields, attentionEntries, isCommandCall, isEntry } from "../../types.js";
28
30
  import { binDir, callDir, callInbox, callSession, journalPath, outboxRoot } from "../../paths.js";
29
31
  import { readJournalSnapshot, syncDirectory } from "../../kernel/journal.js";
30
32
  import { Outbox } from "../../kernel/mailbox.js";
@@ -35,6 +37,7 @@ import { parseModel, plainModel, resolveModel, sameModel } from "../../compat/mo
35
37
  import { buildCallResult } from "../../compat/result.js";
36
38
  import createEffects from "./effects/index.js";
37
39
  import { continueSession } from "./generation.js";
40
+ import { fenceAgent } from "./ended.js";
38
41
  import { answerInFlight, boundAnswer, hibernation, openAsked, openQuestion, supersededByBinding } from "./hibernate.js";
39
42
  import { SessionFold, answerKey, digestOpenQuestion, supersededBy } from "./digest.js";
40
43
  import { emptyLedger, foldLedger, holdings as holdingsOf, settingsOf } from "../ledger.js";
@@ -53,7 +56,7 @@ import { PENDING_NOTE, UNDELIVERED_FOLLOW_UP } from "../notes.js";
53
56
  import { COMMAND_LOG, exitMeaning, readExitRecord, readTail, spawnCommand } from "../../platform/command.js";
54
57
  import { captureStart } from "../../platform/proctable.js";
55
58
  import { heldIn } from "../snapshot.js";
56
- import { COMMAND_INTENT, COMMAND_SPAWN_FAILED, COMMAND_STARTED, COMMAND_TIMEOUT, COMMAND_WITHDRAWN, commandDirName, commandId, retiredCommandAttempts } from "./command.js";
59
+ import { COMMAND_INTENT, COMMAND_SPAWN_FAILED, COMMAND_STARTED, COMMAND_TIMEOUT, COMMAND_WITHDRAWN, commandDirName, commandEnvironment, commandId, retiredCommandAttempts } from "./command.js";
57
60
  const MEM_RECORD_MS = 30000;
58
61
  /** How long the processes of a stopped or timed-out command get between SIGTERM and SIGKILL. */
59
62
  const COMMAND_GRACE_MS = 2000;
@@ -144,6 +147,11 @@ export function continueMessage(dangling) {
144
147
  "(background ones included) were stopped with it: do not wait for them or their output; check what they left " +
145
148
  "and start again what is still needed. Tool calls whose outcomes are unknown: " + (dangling.join(", ") || "none") + ".";
146
149
  }
150
+ /** EX2: Appended to every derived agent prompt, never to the pinned agent definition. */
151
+ export const CHILD_LIFECYCLE_NOTE = "Processes you start end when your turn ends: dsa stops every process of this call when it seals.\n" +
152
+ "To run something that must outlive your turn (a long build, test suite or measurement), start it as a durable command call and end your turn:\n" +
153
+ " pi-durable-subagents run --request <unique id> --wake caller -- <program> [args…]\n" +
154
+ "It keeps running after your turn; when it finishes you get a follow-up with its exit status and output tail.";
147
155
  /** An asker hibernates while it waits (its execution is stopped to free the provider slot), so the answer says so. */
148
156
  export const HIBERNATED_NOTE = "While you waited for the answer below your execution was stopped; processes your tools had " +
149
157
  "started (background ones included) were stopped with it. Check them before relying on them.";
@@ -239,7 +247,7 @@ export default function createExecutor(ledgers, options = {}) {
239
247
  if (!failing.has(exec)) {
240
248
  let retired = false;
241
249
  try {
242
- await containment.fence(exec, tracked(journal, exec));
250
+ await fenceAgent(containment, journal, exec, tracked(journal, exec), opts.child);
243
251
  retired = true;
244
252
  }
245
253
  catch (error) {
@@ -924,10 +932,11 @@ export default function createExecutor(ledgers, options = {}) {
924
932
  await serial(async () => {
925
933
  await forwardsDelivered(t.journal, t.callId, entries);
926
934
  const digest = digestOf(t.callId, entries);
927
- for (const { qid, rev, question } of digest.questions) {
935
+ for (const q of digest.questions) {
936
+ const { qid, rev, question } = q;
928
937
  const id = `q:${t.callId}:${qid}`;
929
938
  if (!entriesOf(t.journal, JT.attention).some(r => isEntry(r, JT.attention) && r.item.id === id && r.item.rev === rev))
930
- await t.journal.append(JT.attention, { item: { id, rev, kind: "question", text: String(question), wid: t.wid, call: t.callId, qid, session: callSession(home, t.wid, t.key, t.gen) } });
939
+ await t.journal.append(JT.attention, { item: { id, rev, kind: "question", text: String(question), wid: t.wid, call: t.callId, qid, session: callSession(home, t.wid, t.key, t.gen), ...askFields(q) } });
931
940
  if (digest.answered.has(answerKey(qid, rev)) || t.journal.entries().some(e => e.type === "answer-bound" && e.call === t.callId && e.qid === qid && e.rev === rev))
932
941
  await resolveBoundAnswer(t.journal, t.callId, qid, rev);
933
942
  else if (digest.superseded.has(answerKey(qid, rev)) || supersededByBinding(t.journal.entries(), t.callId, qid, rev))
@@ -1334,7 +1343,7 @@ export default function createExecutor(ledgers, options = {}) {
1334
1343
  return refused === undefined;
1335
1344
  };
1336
1345
  const result = await spawnCommand({ command: t.spec.command, cwd: t.cwd, dir, proceed,
1337
- env: { ...process.env, ...t.spec.env, DSA_EXEC: id, DSA_CALL: t.callId, DSA_HOME: home } });
1346
+ env: commandEnvironment(home, id, t.callId, t.spec.env) });
1338
1347
  if (!result) {
1339
1348
  if (refused === "withdrawn")
1340
1349
  await serial(() => t.journal.append(COMMAND_WITHDRAWN, { call: t.callId, id }));
@@ -1675,7 +1684,7 @@ export default function createExecutor(ledgers, options = {}) {
1675
1684
  await mkdir(dir, { recursive: true });
1676
1685
  const prompt = join(dir, "system.txt"), schema = join(dir, "schema.json");
1677
1686
  // These are derived launch inputs, reconstructed from the pinned ticket after a crash.
1678
- await writeFile(prompt, t.agent.body);
1687
+ await writeFile(prompt, `${t.agent.body}\n\n${CHILD_LIFECYCLE_NOTE}`);
1679
1688
  if (t.spec.schema !== undefined)
1680
1689
  await writeFile(schema, JSON.stringify(t.spec.schema));
1681
1690
  const sender = await outbox;
@@ -1724,7 +1733,7 @@ export default function createExecutor(ledgers, options = {}) {
1724
1733
  try {
1725
1734
  child = await containment.spawn({ exec, command: piCommand, args: [...buildPiArgs(t.agent, t.spec, { sessionPath: session, systemPromptPath: prompt, continuation: decision.continuation, controlTools: t.spec.schema === undefined ? ["ask"] : ["ask", "report"], ...(model.id ? { model } : {}) }), "-e", extension], cwd,
1726
1735
  // The orchestrator's node follows binDir: a `#!/usr/bin/env node` pi runs under a PATH without node (a service's).
1727
- env: { DSA_HOME: home, PATH: [binDir(home), dirname(process.execPath), process.env.PATH].filter(Boolean).join(delimiter), DSA_EXEC: exec, DSA_CALL: t.callId, DSA_INBOX: inbox(t.callId), DSA_JOURNAL: journal.path, ...(t.spec.schema !== undefined ? { DSA_SCHEMA: schema } : {}), ...(t.spec.budget ? { DSA_BUDGET: JSON.stringify(t.spec.budget) } : {}), ...(model.provider && model.id ? { DSA_MODEL: `${model.provider}/${model.id}` } : {}) } });
1736
+ env: { DSA_HOME: home, PATH: [binDir(home), dirname(process.execPath), process.env.PATH].filter(Boolean).join(delimiter), DSA_EXEC: exec, DSA_CALL: t.callId, DSA_INBOX: inbox(t.callId), DSA_JOURNAL: journal.path, DSA_ASK_REQUIRE_DECISION: String(config.askRequireDecision ?? false), ...(t.spec.schema !== undefined ? { DSA_SCHEMA: schema } : {}), ...(t.spec.budget ? { DSA_BUDGET: JSON.stringify(t.spec.budget) } : {}), ...(model.provider && model.id ? { DSA_MODEL: `${model.provider}/${model.id}` } : {}) } });
1728
1737
  }
1729
1738
  catch (error) {
1730
1739
  const environment = environmentSpawnError(error);
@@ -1741,6 +1750,12 @@ export default function createExecutor(ledgers, options = {}) {
1741
1750
  }
1742
1751
  await serial(() => spawnEnvResolved(t));
1743
1752
  try {
1753
+ // EX1: retain the direct identity even if pi exited before start capture; otherwise a surviving grandchild
1754
+ // could become the first tracked process and be mistaken for pi on a recovery fence.
1755
+ if (child.pid > 0)
1756
+ await serial(async () => {
1757
+ await journal.append("tracked", { exec, pid: child.pid, start: child.start, child: true });
1758
+ });
1744
1759
  await track(journal, exec, [{ pid: child.pid, start: child.start, ppid: process.pid }]);
1745
1760
  await observeExecution({ home, config, ticket: t, exec, child, serial, read: () => readCall(journal, t.callId),
1746
1761
  setWake: fn => { a.wake = fn; }, interrupted: () => !!interrupted(a),
@@ -2009,7 +2024,8 @@ export default function createExecutor(ledgers, options = {}) {
2009
2024
  }
2010
2025
  }
2011
2026
  /** P12: a model request to this call, recorded with the rid given; a reject has no effect. */
2012
- const requestModel = async (rid, model, hash, cond) => {
2027
+ const requestModel = async (rid, choice, hash, cond) => {
2028
+ let model = choice;
2013
2029
  let body;
2014
2030
  const exec = current(ctx.journal, dest);
2015
2031
  // P28: with no live execution (not started yet, between executions, hibernated while asking) the model is
@@ -2053,7 +2069,7 @@ export default function createExecutor(ledgers, options = {}) {
2053
2069
  if (!idle && !await reserveSwitch(exec, body.provider, rid))
2054
2070
  return { action: "reject", reason: "provider-full" };
2055
2071
  await note(req.rid, model, idle ? "next-execution" : "next-request", pool);
2056
- const entry = await ctx.journal.append("forward", { rid, rid2, dest, hash, envelope });
2072
+ const entry = await ctx.journal.append("forward", { rid, rid2, dest, hash, envelope, choice });
2057
2073
  await replayForward(entry);
2058
2074
  if (idle) {
2059
2075
  active.get(dest)?.wake();
@@ -1,6 +1,7 @@
1
1
  import { JT, attentionEntries, isEntry } from "../../types.js";
2
2
  import { Containment as PlatformContainment } from "../../platform/containment.js";
3
3
  import { ProcessTable } from "../../platform/proctable.js";
4
+ import { fenceAgent } from "./ended.js";
4
5
  /** C2, F4: Real observers share snapshots; injected tables retain serialized access. */
5
6
  export function serialContainment(table) {
6
7
  if (!table || table instanceof ProcessTable)
@@ -152,7 +153,10 @@ export async function sweepExecutions(journals, containment, hooks = {}) {
152
153
  continue;
153
154
  }
154
155
  try {
155
- await containment.fence(t.exec, t.tracked);
156
+ if (t.exec.startsWith("gate:"))
157
+ await containment.fence(t.exec, t.tracked);
158
+ else
159
+ await fenceAgent(containment, t.journal, t.exec, t.tracked);
156
160
  }
157
161
  catch (error) {
158
162
  await hooks.failed?.(t.journal, t.exec, t.call, error);
@@ -0,0 +1,17 @@
1
+ /** Latest surviving manual choice in this generation. Earlier generations already carried theirs into the spec.
2
+ * Delivery consumes the live request, not the choice; a refusal or withdrawal disqualifies the request. Failover
3
+ * never contributes intent, even if its selected model later answers. A revision's entries scope the call identity. */
4
+ export function generationModel(log, call) {
5
+ const refused = new Set(log.filter(e => e.type === "forward-delivered" && e.reason !== undefined).map(e => String(e.rid2)));
6
+ const withdrawn = new Set(log.filter(e => e.type === "forward" && e.dest === call && e.envelope?.kind === "withdraw")
7
+ .flatMap(e => e.envelope.body?.rids ?? []));
8
+ for (let i = log.length - 1; i >= 0; i--) {
9
+ const e = log[i];
10
+ if (e.type === "model-choice" && e.call === call && typeof e.model === "string")
11
+ return e.model;
12
+ if (e.type === "forward" && e.dest === call && typeof e.choice === "string" && !e.failover &&
13
+ e.envelope?.kind === "model" && !refused.has(String(e.rid2)) && !withdrawn.has(String(e.rid2)))
14
+ return e.choice;
15
+ }
16
+ return undefined;
17
+ }
@@ -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}`;
@@ -30,6 +30,8 @@ export function settledFacts(wf, recovered) {
30
30
  const log = wf.journal.entries(), rev = revisionEntries(wf), done = terminalEntry(rev);
31
31
  if (!done)
32
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";
33
35
  const has = (type, field, value) => log.some(e => e.type === type && e[field] === value);
34
36
  const sealedCalls = new Set(log.filter(e => e.type === JT.sealed).map(e => String(e.call)));
35
37
  const ended = new Set([...sealedCalls, ...log.filter(e => e.type === "retired").map(e => String(e.call))]);
@@ -7,10 +7,10 @@ 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
- import { JT, attentionEntries, isEntry } from "../types.js";
10
+ import { JT, askText, 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";
@@ -148,10 +148,12 @@ function snapshotReducer(wid, entries) {
148
148
  // P31: usage per call id, deduplicated by message id; a seal carries the authoritative total.
149
149
  const live = new Map(), sealedUsage = new Map(), seen = new Set();
150
150
  const tools = new Map();
151
+ const endedAtSeal = new Map();
151
152
  // P7, P27: forward / forward-delivered / forward-retired, by destination call; retirements carry only rid2.
152
153
  const sends = new Map(), byRid2 = new Map();
153
154
  // Pending notes of the current revision by key (notes.ts): recorded rids, and those a generation carried.
154
155
  const notes = new Map(), carried = new Set();
156
+ const choices = new Map();
155
157
  function apply(batch, from = 0) {
156
158
  for (let i = from; i < batch.length; i++) {
157
159
  const e = batch[i];
@@ -166,6 +168,7 @@ function snapshotReducer(wid, entries) {
166
168
  const callId = e.type === "reused" ? String(e.from) : `${wid}@${rev}/${key}@${gen}`;
167
169
  if (e.type === "generation") {
168
170
  generations.add(callId);
171
+ choices.delete(String(e.from));
169
172
  for (const rid of Array.isArray(e.notes) ? e.notes : [])
170
173
  carried.add(String(rid));
171
174
  }
@@ -180,6 +183,10 @@ function snapshotReducer(wid, entries) {
180
183
  phase: result ? "sealed" : "queued", ...(result ? { result, endedAt: e.ts } : {}),
181
184
  ...(e.type === "refused" ? { refused: String(e.reason) } : {}), ...(e.type === "reused" ? { reused: String(e.from) } : {}) });
182
185
  }
186
+ else if (e.type === "model-choice") {
187
+ if (typeof e.model === "string" && calls.has(String(e.call)))
188
+ choices.set(String(e.call), e.model);
189
+ }
183
190
  else if (e.type === PENDING_NOTE) {
184
191
  if (boundary >= 0 && e.seq < entries[boundary].seq)
185
192
  continue;
@@ -349,6 +356,10 @@ function snapshotReducer(wid, entries) {
349
356
  total.costUsd += u.costUsd;
350
357
  live.set(String(e.call), total);
351
358
  }
359
+ else if (isEntry(e, 'ended')) {
360
+ const prior = endedAtSeal.get(e.call), procs = [...(prior?.procs ?? []), ...e.procs];
361
+ endedAtSeal.set(e.call, { procs: procs.slice(0, 20), more: (prior?.more ?? 0) + Math.max(0, procs.length - 20) + (e.more ?? 0) });
362
+ }
352
363
  else if (e.type === JT.sealed) {
353
364
  const usage = e.result?.usage;
354
365
  if (usage)
@@ -425,6 +436,11 @@ function snapshotReducer(wid, entries) {
425
436
  if (c.phase !== "sealed" && c.phase !== "queued")
426
437
  delete c.poolWait;
427
438
  counts[c.phase]++;
439
+ const ended = endedAtSeal.get(c.callId);
440
+ if (ended?.procs.length)
441
+ c.endedAtSeal = structuredClone(ended.procs);
442
+ if (ended?.more)
443
+ c.endedAtSealMore = ended.more;
428
444
  const usage = usageOf(c.callId);
429
445
  if (usage)
430
446
  c.usage = { ...usage };
@@ -447,7 +463,10 @@ function snapshotReducer(wid, entries) {
447
463
  else if (last && last.state !== "retired" && last.model !== (c.virtualModel ? c.selectedModel : c.model)?.replace(/:(off|minimal|low|medium|high|xhigh|max)$/, ""))
448
464
  c.switching = last.model;
449
465
  }
450
- const selected = c.switching ?? c.selectedModel;
466
+ // A sealed choice has not been used yet; retain the last actual model and expose the intent separately.
467
+ if (choices.has(c.callId) && !retired.has(c.callId))
468
+ c.switching = choices.get(c.callId);
469
+ const selected = c.phase === "sealed" ? c.selectedModel : c.switching ?? c.selectedModel;
451
470
  if (c.usedModel && c.virtualModel)
452
471
  c.routedModel = c.usedModel;
453
472
  else if (c.usedModel && selected && c.usedModel.toLowerCase() !== selected.toLowerCase())
@@ -550,6 +569,9 @@ const digests = new Map();
550
569
  const FINAL_STATUS = new Set(["done", "failed", "stopped"]);
551
570
  /** Post-seal/recovery work that can append without a new request must not enter a polling trust window. */
552
571
  export function pendingRecovery(wid, entries) {
572
+ const rev = entries.filter(e => e.type === JT.done).length;
573
+ if (entries.some(e => e.type === 'wf-created' && e.wake) && !entries.some(e => e.type === 'wake-outcome' && e.rev === rev))
574
+ return true;
553
575
  const start = entries.findLastIndex(e => e.type === "revised"), current = start < 0 ? entries : entries.slice(start);
554
576
  const consumed = new Set(current.filter(e => e.type === "generation").flatMap(generationRids));
555
577
  const retiredForwards = new Map(entries.filter(e => e.type === "forward-retired").map(e => [String(e.rid2), e]));
@@ -1170,7 +1192,7 @@ export function compactWorkflow(wf, leases) {
1170
1192
  ...(c.answered ? { answered: c.answered } : {}), ...(c.answerForwarded ? { answerForwarded: c.answerForwarded } : {}), ...(c.writerWait && !r ? { writerWait: c.writerWait } : {}), ...(!r && leases?.get(c.callId) ? { lease: leases.get(c.callId) } : {}),
1171
1193
  ...(c.notesPending ? { notesPending: c.notesPending } : {}), ...(c.queuedFor && !r && !wf.paused ? { queued: queuedText(c.queuedFor) } : {}) };
1172
1194
  }),
1173
- 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 } : {}) })),
1195
+ 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 } : {}), ...(a.decision_needed !== undefined ? { decision_needed: clip(a.decision_needed, 300), ...(a.options !== undefined ? { options: a.options } : {}) } : {}) })),
1174
1196
  ...(wf.paused ? { paused: true } : {}), ...(wf.followUps ? { followUps: wf.followUps } : {}), ...(wf.labels ? { labels: wf.labels } : {}),
1175
1197
  };
1176
1198
  }
@@ -1274,6 +1296,8 @@ export function versionNote(running, loaded) {
1274
1296
  }
1275
1297
  /** The first version whose orchestrator and child know send kind "notify". */
1276
1298
  export const NOTIFY_SINCE = "1.0.28";
1299
+ /** The first orchestrator version that delivers run --wake caller. */
1300
+ export const WAKE_SINCE = "1.1.0";
1277
1301
  /** A refusal when the orchestrator running now predates `since` and is older than the version this process loaded (an
1278
1302
  * older orchestrator would accept the request and its child would drop it); none when none runs (the next one starts
1279
1303
  * on the installed version) or it is current. */
@@ -1364,7 +1388,7 @@ export function statusBrief(home, options = {}) {
1364
1388
  ...(c.notesPending ? { notesPending: c.notesPending } : {}), ...(live && c.queuedFor && !w.paused ? { queued: queuedText(c.queuedFor, now) } : {}) };
1365
1389
  });
1366
1390
  const asking = open.filter(a => a.kind === "question" && a.call).map(a => ({ to: `${w.wid}/${callKey(a.call)}`, ...(a.qid ? { qid: a.qid } : {}),
1367
- ...(w.calls.some(c => c.callId === a.call && c.hibernated) ? { hibernated: true } : {}), question: clip(a.text, 300) }));
1391
+ ...(w.calls.some(c => c.callId === a.call && c.hibernated) ? { hibernated: true } : {}), question: clip(a.text, 300), ...(a.decision_needed !== undefined ? { rev: a.rev, decision_needed: clip(a.decision_needed, 300) } : {}) }));
1368
1392
  const alerts = open.filter(a => a.kind !== "question").map(a => `${a.kind}${a.call ? ` ${w.wid}/${callKey(a.call)}` : ""}: ${clip(a.text, 200)}`);
1369
1393
  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 } : {}),
1370
1394
  progress: `${p.done}/${p.total}${p.plus ? "+" : ""}`, tokens: tokens(w.usage), calls,
@@ -1383,6 +1407,34 @@ export function statusBrief(home, options = {}) {
1383
1407
  hint: "status wid=<wid> shows one workflow (outputs clipped); add key=<key> for one call's full result, or full:true for everything",
1384
1408
  };
1385
1409
  }
1410
+ /** AK4/R-12-AK-3: render only the projection's own question entries, never business result/data/output. */
1411
+ export function statusText(home, value) {
1412
+ const object = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
1413
+ const workflow = (v) => {
1414
+ if (!object(v) || typeof v.wid !== 'string')
1415
+ return v;
1416
+ const wid = v.wid;
1417
+ let questions;
1418
+ const items = (list, brief) => !Array.isArray(list) ? list : list.map(item => {
1419
+ if (!object(item) || item.decision_needed === undefined || (!brief && item.kind !== 'question'))
1420
+ return item;
1421
+ // Brief drops the attention id/call; its address, qid and revision still identify the original question.
1422
+ const q = (questions ??= workflowSnapshot(home, wid).attention).find(q => q.kind === 'question' && q.decision_needed !== undefined &&
1423
+ q.qid === item.qid && q.rev === item.rev && (brief
1424
+ ? q.call !== undefined && item.to === `${wid}/${callKey(q.call)}`
1425
+ : q.id === item.id && q.call === item.call));
1426
+ return q ? { ...item, [brief ? 'question' : 'text']: askText(q, q.text) } : item;
1427
+ });
1428
+ return { ...v, ...(Array.isArray(v.attention) ? { attention: items(v.attention, false) } : {}),
1429
+ ...(Array.isArray(v.asking) ? { asking: items(v.asking, true) } : {}) };
1430
+ };
1431
+ if (!object(value))
1432
+ return JSON.stringify(value);
1433
+ // These are the only workflow containers produced by status. Do not walk calls, result or arbitrary nesting.
1434
+ return JSON.stringify({ ...workflow(value),
1435
+ ...(Array.isArray(value.active) ? { active: value.active.map(workflow) } : {}),
1436
+ ...(Array.isArray(value.workflows) ? { workflows: value.workflows.map(workflow) } : {}) });
1437
+ }
1386
1438
  /** Running workflows of other sessions that a pause holds, as "wid" or "wid (name)": a session's own resume skips them. */
1387
1439
  export function pausedElsewhere(home, origin) {
1388
1440
  return snapshots(home, origin).all.filter(w => w.paused && w.origin !== origin && !settled(w)).map(w => w.name ? `${w.wid} (${w.name})` : w.wid);
@@ -1475,7 +1527,8 @@ export function statusDetail(home, wid) {
1475
1527
  if (!origin.has(wid))
1476
1528
  throw new Error(prunedIds(home).has(wid) ? `Workflow ${wid} was pruned` : `Unknown workflow: ${wid}`);
1477
1529
  const held = heldWorkflows(home), wf = labelled(workflowSnapshot(home, wid), held.labels(wid), held.session(wid)), log = scriptLogPath(home, wid);
1478
- return { ...wf, ...(wf.origin === undefined && origin.get(wid) !== undefined ? { origin: origin.get(wid) } : {}), ...(existsSync(log) ? { scriptLog: log } : {}),
1530
+ const calls = wf.calls.map(c => { const awaiting = awaitingRuns(home, wid, c.key, wf.rev); return awaiting ? { ...c, awaiting } : c; });
1531
+ return { ...wf, calls, ...(wf.origin === undefined && origin.get(wid) !== undefined ? { origin: origin.get(wid) } : {}), ...(existsSync(log) ? { scriptLog: log } : {}),
1479
1532
  ...(isLive(wf) && held.held(wid) ? { paused: true } : {}) };
1480
1533
  }
1481
1534
  /** P25, T10: Project a workflow journal into meaningful events (no observations, time or tracking). */
@@ -1529,6 +1582,9 @@ export function eventsFromEntries(entries) {
1529
1582
  case "hibernated":
1530
1583
  add(e, "hibernated", { call: e.call, qid: e.qid });
1531
1584
  break;
1585
+ case "model-choice":
1586
+ add(e, "model-choice", { rid: e.rid, call: e.call, model: e.model, effect: "next-generation" });
1587
+ break;
1532
1588
  case "forward": {
1533
1589
  forwards.set(String(e.rid2), e);
1534
1590
  // A model switch names its target, and a failover (the executor moved the call off a used-up provider) its source.
@@ -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
+ }
@@ -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
  }