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.
@@ -8,15 +8,16 @@ import { findJournalEntry, readJournalFold, readJournalSnapshot } from "../kerne
8
8
  import { isResolution, lifecycleResolution } from "../kernel/lifecycle.js";
9
9
  import { journalPath, orchLedger, pinnedDir } from "../paths.js";
10
10
  import { batchConflict, batchDigest, findRequest, manyIds, namesMany, REQUEST_ID, requestId, requestRid, RequestsBusy, SESSION_ID, specDigest } from "../requests.js";
11
- import { NOTIFY_SINCE, HOLD_ENTRY_TYPES, commandLine, commandSendRefusal, isCommandTarget, heldIn, isLive, orchestratorTooOld, slotsView, workflowSnapshot, writerWaits, writerWaitLine, WRITER_WAIT_HINT } from "../orchestrator/snapshot.js";
12
- import { leaseCalls, leaseState } from "../platform/lease.js";
11
+ import { NOTIFY_SINCE, WAKE_SINCE, HOLD_ENTRY_TYPES, commandLine, commandSendRefusal, isCommandTarget, heldIn, isLive, orchestratorTooOld, slotsView, workflowSnapshot, writerWaits, writerWaitLine, WRITER_WAIT_HINT } from "../orchestrator/snapshot.js";
12
+ import { leaseCalls, leaseState, callAddress } from "../platform/lease.js";
13
13
  import { BATCH, checkAgents, followUpReceipt, outcomeLine, request, sendReceipt } from "../agent/main/tool.js";
14
14
  import { discoverAgents } from "../compat/agents.js";
15
- import { JT } from "../types.js";
15
+ import { JT, askFields, askText } from "../types.js";
16
16
  import { startOrchestrator, submitIdentified } from "./control.js";
17
17
  import { FENCE_LEDGER_TYPES, endedExecs, fenceReason } from "../events/fence.js";
18
18
  import { parseLabels } from "../events/labels.js";
19
19
  import { foldWaits, leaseWaits, waitsOf } from "../events/waiting.js";
20
+ import { awaitingRuns, wakeStatus } from "../orchestrator/reader-ledger.js";
20
21
  import { LEDGER_ENTRY_TYPES, emptyLedger, foldLedger } from "../orchestrator/ledger.js";
21
22
  export const EXIT = { ok: 0, rejected: 1, conflict: 3, pending: 75 };
22
23
  /** Strict `--name value` / `--flag` parsing; unknown or repeated options are errors, except those given in `repeated`
@@ -88,7 +89,7 @@ export async function describe(home, key, now = Date.now()) {
88
89
  // A send or stop has no workflow of its own: its decision is the outcome.
89
90
  if (decided && found.request.kind !== "run")
90
91
  return { state: "applied", ...head };
91
- return { state: "pending", ...head };
92
+ return { state: "pending", ...head, ...(wakeStatus(home, found.request) ? { wake: wakeStatus(home, found.request) } : {}) };
92
93
  }
93
94
  /** `{labels}` of a run request that has any. */
94
95
  function labelsOf(request) {
@@ -121,7 +122,7 @@ function describeWorkflow(home, wid, entries, now) {
121
122
  const pruned = entries.find(e => e.type === "pruned" && e.wid === wid);
122
123
  if (pruned)
123
124
  return { state: "pruned", wid, pruned: { ...(pruned.status !== undefined ? { status: String(pruned.status) } : {}), endedAt: Number(pruned.endedAt) },
124
- ...(typeof pruned.request === "string" ? { request: pruned.request } : {}), ...(typeof pruned.spec_digest === "string" ? { spec_digest: pruned.spec_digest } : {}), ...labelsOf(runOf(home, entries, wid).run) };
125
+ ...(typeof pruned.request === "string" ? { request: pruned.request } : {}), ...(typeof pruned.spec_digest === "string" ? { spec_digest: pruned.spec_digest } : {}), ...labelsOf(runOf(home, entries, wid).run), ...(pruned.wake ? { wake: pruned.wake } : {}) };
125
126
  if (!/^[^/\\\0]+$/.test(wid) || wid === "." || wid === ".." || !existsSync(journalPath(home, wid)))
126
127
  return { state: "absent", wid };
127
128
  // The snapshot and the journal the wait fold reads must be the same bytes (a writer-wait appended between the two reads
@@ -145,7 +146,9 @@ function describeWorkflow(home, wid, entries, now) {
145
146
  ...(c.hibernated ? { hibernated: true } : {}), ...waits.get(c.callId)
146
147
  };
147
148
  const run = c.command !== undefined ? c.commandRun : undefined, live = !r && run !== undefined;
148
- return { key: c.key, gen: c.gen, phase: c.phase, agent: c.agent, ...(c.model ? { model: c.model } : {}),
149
+ const awaiting = awaitingRuns(home, wid, c.key, wf.rev);
150
+ return { key: c.key, gen: c.gen, phase: c.phase, agent: c.agent, ...(c.phase === 'sealed' && c.endedAt !== undefined ? { sealedAt: c.endedAt } : {}), ...(awaiting ? { awaiting } : {}),
151
+ ...(c.endedAtSeal ? { endedAtSeal: c.endedAtSeal } : {}), ...(c.endedAtSealMore ? { endedAtSealMore: c.endedAtSealMore } : {}), ...(c.model ? { model: c.model } : {}),
149
152
  ...(c.command !== undefined ? { command: commandLine(c.command, 200) } : {}), ...(run?.attempt !== undefined ? { attempt: run.attempt } : {}),
150
153
  ...(live && run.pid !== undefined ? { pid: run.pid } : {}), ...(live && c.startedAt !== undefined ? { elapsed: commandAge(now - c.startedAt) } : {}),
151
154
  ...(run?.log ? { log: run.log } : {}),
@@ -153,12 +156,12 @@ function describeWorkflow(home, wid, entries, now) {
153
156
  ...(waiting && Object.keys(waiting).length ? { waiting } : {}) };
154
157
  });
155
158
  const keyOf = (call) => call?.replace(/^[^/]*\//, "").replace(/@\d+$/, "");
156
- const questions = wf.attention.filter(a => a.kind === "question").map(a => ({ ...(a.qid ? { qid: a.qid } : {}), rev: a.rev, to: `${wid}/${keyOf(a.call)}`, ...(a.call ? { call: a.call } : {}), text: a.text }));
159
+ const questions = wf.attention.filter(a => a.kind === "question").map(a => ({ ...(a.qid ? { qid: a.qid } : {}), rev: a.rev, to: `${wid}/${keyOf(a.call)}`, ...(a.call ? { call: a.call } : {}), text: a.text, ...askFields(a) }));
157
160
  const attention = wf.attention.filter(a => a.kind !== "question").map(a => ({ id: a.id, rev: a.rev, kind: a.kind, ...(a.call ? { call: a.call } : {}), text: a.text }));
158
161
  const state = questions.length ? "asking" : isLive(wf) || wf.status === "parked" ? "running" : "sealed";
159
162
  const fence = lastFence(journal, entries);
160
163
  return { state, wid, ...(id ? { request: id } : {}), ...(admitted ? { spec_digest: specDigest(admitted) } : {}), ...labelsOf(run), status: wf.status, ...(wf.error ? { error: wf.error } : {}),
161
- calls, ...(questions.length ? { questions } : {}), ...(attention.length ? { attention } : {}), ...(fence ? { lastFence: fence } : {}) };
164
+ ...(wakeStatus(home, run, wid) ? { wake: wakeStatus(home, run, wid) } : {}), calls, ...(questions.length ? { questions } : {}), ...(attention.length ? { attention } : {}), ...(fence ? { lastFence: fence } : {}) };
162
165
  }
163
166
  /** Best effort: why the latest fence that interrupted work happened. The per-execution classification and the
164
167
  * reason are shared with the event log's `fenced` events (src/events/fence.ts). */
@@ -178,6 +181,8 @@ export function renderDescription(d) {
178
181
  lines.push(` labels: ${Object.entries(d.labels).map(([k, v]) => `${k}=${v}`).join(" ")}`);
179
182
  if (d.pruned)
180
183
  lines.push(` pruned: ${d.pruned.status ?? "?"} at ${new Date(d.pruned.endedAt ?? 0).toISOString()}`);
184
+ if (d.wake)
185
+ lines.push(` wake: ${d.wake.to} ${d.wake.state}${d.wake.rev ? ` rev ${d.wake.rev}` : ''}${d.wake.generation ? ` generation ${d.wake.generation}` : ''}${d.wake.reason ? ` (${d.wake.reason})` : ''}`);
181
186
  if (d.error)
182
187
  lines.push(` error: ${d.error}`);
183
188
  for (const c of d.calls ?? []) {
@@ -187,6 +192,11 @@ export function renderDescription(d) {
187
192
  : ` ${c.key}@${c.gen} ${c.agent} ${c.phase}${c.status ? ` ${c.status}` : ""}${c.model ? ` (${c.model})` : ""}${c.error ? ` — ${c.error}` : ""}`);
188
193
  if (c.command !== undefined)
189
194
  lines.push(` command: ${c.command}`, ...(c.log ? [` log: ${c.log}`] : []));
195
+ if (c.awaiting)
196
+ for (const run of c.awaiting)
197
+ lines.push(` awaiting: ${run.request}${run.wid ? ` (${run.wid})` : ''} ${run.state}`);
198
+ if (c.endedAtSeal)
199
+ lines.push(` ended at seal: ${JSON.stringify(c.endedAtSeal)}${c.endedAtSealMore ? ` (${c.endedAtSealMore} more)` : ''}`);
190
200
  if (c.waiting)
191
201
  lines.push(` waiting: ${JSON.stringify(c.waiting)}`);
192
202
  if (c.data !== undefined)
@@ -195,7 +205,7 @@ export function renderDescription(d) {
195
205
  lines.push(...c.output.split("\n").map(l => ` | ${l}`));
196
206
  }
197
207
  for (const q of d.questions ?? [])
198
- lines.push(` question ${q.to} qid=${q.qid} rev=${q.rev}:`, ...q.text.split("\n").map(l => ` ${l}`));
208
+ lines.push(` question ${q.to} qid=${q.qid} rev=${q.rev}:`, ...askText(q, q.text).split("\n").map(l => ` ${l}`));
199
209
  for (const a of d.attention ?? [])
200
210
  lines.push(` ${a.kind}${a.call ? ` ${a.call}` : ""}: ${a.text}`);
201
211
  if (d.lastFence)
@@ -312,21 +322,40 @@ export function runSession(flag, env) {
312
322
  * form ({agent,task,…}, {command,…} or {tasks|chain:[…],…}); it is validated by the tool's own normalizer and agent check. */
313
323
  export const runCommand = (args, ctx) => refusable(args, ctx, runRequest);
314
324
  async function runRequest(args, ctx, seen) {
315
- const { values, positionals } = flags(args, { request: "value", spec: "value", cwd: "value", labels: "value", session: "value", json: "flag", "wait-ms": "value" });
325
+ const dash = args.indexOf("--"), argv = dash < 0 ? undefined : args.slice(dash + 1);
326
+ const { values, positionals } = flags(dash < 0 ? args : args.slice(0, dash), { request: "value", spec: "value", wake: "value", "timeout-ms": "value", name: "value", cwd: "value", labels: "value", session: "value", json: "flag", "wait-ms": "value" });
316
327
  const id = text(values, "request"), file = text(values, "spec"), json = values.json === true, wait = waitMs(values, ctx);
317
328
  seen.id = id;
318
329
  seen.json = json;
319
- if (!id || !file || positionals.length)
320
- throw new Error("usage: run --request <id> --spec <file|-> [--labels <json>] [--session <pi session id>] [--cwd <dir>] [--json] [--wait-ms <n>]");
330
+ if (file !== undefined && argv !== undefined)
331
+ throw new Error("--spec and -- are mutually exclusive");
332
+ if (argv === undefined && (values["timeout-ms"] !== undefined || values.name !== undefined))
333
+ throw new Error("--timeout-ms and --name require -- <program> [args…]");
334
+ if (!id || (file === undefined && argv === undefined) || positionals.length || (argv !== undefined && !argv[0]))
335
+ throw new Error("usage: run --request <id> [--wake caller] (--spec <file|-> | -- <program> [args…])");
336
+ const wake = text(values, "wake");
337
+ if (wake !== undefined && wake !== "caller")
338
+ throw new Error("--wake takes exactly caller");
339
+ if (wake && !ctx.env.DSA_CALL)
340
+ throw new Error("--wake caller needs DSA_CALL: run it from inside a subagent call");
341
+ if (wake && callAddress(ctx.env.DSA_CALL) === ctx.env.DSA_CALL)
342
+ throw new Error("--wake caller needs a valid DSA_CALL");
343
+ const timeout = text(values, "timeout-ms");
344
+ if (timeout !== undefined && (!/^[1-9]\d*$/.test(timeout) || !Number.isSafeInteger(Number(timeout))))
345
+ throw new Error("--timeout-ms needs a positive integer");
321
346
  requestRid(id);
322
347
  const raw = text(values, "labels"), labels = raw !== undefined ? parseLabels(raw) : undefined;
323
- const bytes = file === "-" ? await (ctx.stdin ?? stdin)() : readFileSync(resolve(ctx.cwd ?? process.cwd(), file), "utf8");
324
348
  let spec;
325
- try {
326
- spec = JSON.parse(bytes);
327
- }
328
- catch (error) {
329
- throw new Error(`--spec is not JSON: ${error.message}`);
349
+ if (argv !== undefined)
350
+ spec = { command: argv, ...(timeout !== undefined ? { timeoutMs: Number(timeout) } : {}), ...(values.name !== undefined ? { name: text(values, "name") } : {}) };
351
+ else {
352
+ const bytes = file === "-" ? await (ctx.stdin ?? stdin)() : readFileSync(resolve(ctx.cwd ?? process.cwd(), file), "utf8");
353
+ try {
354
+ spec = JSON.parse(bytes);
355
+ }
356
+ catch (error) {
357
+ throw new Error(`--spec is not JSON: ${error.message}`);
358
+ }
330
359
  }
331
360
  if (!spec || typeof spec !== "object" || Array.isArray(spec))
332
361
  throw new Error("--spec must be a JSON object");
@@ -345,10 +374,17 @@ async function runRequest(args, ctx, seen) {
345
374
  const session = runSession(text(values, "session"), ctx.env);
346
375
  if (session)
347
376
  body.session = session;
377
+ if (wake) {
378
+ body.wake = { to: callAddress(ctx.env.DSA_CALL) };
379
+ body.caller = ctx.env.DSA_CALL;
380
+ }
348
381
  seen.digest = specDigest({ kind: "run", body });
349
382
  // An id already recorded is decided by that record: the same content gets its first outcome (the agents it named may
350
383
  // have changed since), other content is a request-conflict. Only a new id is checked here.
351
384
  const prior = (await findRequest(ctx.home, requestRid(id)))?.request;
385
+ const old = wake && !prior ? orchestratorTooOld(ctx.home, 'run --wake', WAKE_SINCE) : undefined;
386
+ if (old)
387
+ throw new Error(old);
352
388
  if (!prior)
353
389
  checkAgents(body, () => discoverAgents(dir, { home: ctx.env.HOME || undefined, agentDir: ctx.env.PI_CODING_AGENT_DIR || undefined }).agents.map(a => a.name));
354
390
  const done = await submitAndWait(ctx, seen, id, "run", body, undefined, wait, json);
@@ -9,7 +9,7 @@ import { readFile } from "node:fs/promises";
9
9
  import { join } from "node:path";
10
10
  import { contentHash } from "../kernel/ids.js";
11
11
  /** The keys the orchestrator reads; config.json also holds pi-side settings (ui, onQuit) that it ignores. */
12
- const KEYS = ["defaultModel", "pools", "providers", "memory", "writerLock", "k"];
12
+ const KEYS = ["defaultModel", "pools", "providers", "memory", "writerLock", "askRequireDecision", "k"];
13
13
  const K = ["lossBound", "checkpointMs", "stallMs", "progressMs", "switchTimeoutMs", "idleExitMs", "trackerMs", "hibernateMs", "spawnBudget", "probeMs", "eventRetentionMs", "waitCheckMs", "resumeSpillMs"];
14
14
  export const configPath = (home) => join(home, "config.json");
15
15
  /** The orchestrator's part of a parsed config.json. */
@@ -24,7 +24,9 @@ const count = (v) => typeof v === "number" && Number.isFinite(v) && v >= 0;
24
24
  export function configProblem(raw) {
25
25
  if (!record(raw))
26
26
  return "config.json must be a JSON object";
27
- const { defaultModel, pools, providers, memory, writerLock, k } = raw;
27
+ const { defaultModel, pools, providers, memory, writerLock, askRequireDecision, k } = raw;
28
+ if (askRequireDecision !== undefined && typeof askRequireDecision !== "boolean")
29
+ return 'askRequireDecision must be a boolean';
28
30
  if (writerLock !== undefined && writerLock !== "queue" && writerLock !== "off")
29
31
  return 'writerLock must be "queue" or "off"';
30
32
  if (defaultModel !== undefined && typeof defaultModel !== "string")
@@ -32,7 +32,8 @@ import { labelsProblem } from "../events/labels.js";
32
32
  import { WaitTracker, waitCollector, startWaiting } from "../events/waiting.js";
33
33
  import { readPage } from "../events/log.js";
34
34
  import { eventsLog } from "../paths.js";
35
- import { parseModel } from "../compat/model.js";
35
+ import { parseModel, resolveModel } from "../compat/model.js";
36
+ import { generationModel } from "./model-choice.js";
36
37
  import { PENDING_NOTE, generationRids, openingMessage, pendingFollowUps, pendingNotes, unsettledForward, unsettledNotify } from "./notes.js";
37
38
  import { journalAppends } from "../kernel/journal.js";
38
39
  import { callEntries, entriesOf } from "./executor/indexes.js";
@@ -57,7 +58,7 @@ export function unknownAgent(name, agents) {
57
58
  return `unknown agent ${JSON.stringify(name)}; available agents: ${agents.map(a => a.name).sort().join(", ") || "none"}`;
58
59
  }
59
60
  /** v12 §3: Wake with bounded latest-per-key results, preferring structured reports and preserving clipped tails. */
60
- export function finishedText(wid, entries, call) {
61
+ export function finishedText(wid, entries, call, commandOutput = false) {
61
62
  const snap = snapshotFromEntries(wid, entries), label = snap.name ?? wid;
62
63
  const latest = new Map(snap.calls.map(c => [c.key, c]));
63
64
  const calls = call ? snap.calls.filter(c => c.callId === call) : [...latest.values()];
@@ -74,7 +75,7 @@ export function finishedText(wid, entries, call) {
74
75
  // Share the space fairly: short results take what they need and the rest goes to longer ones (one agent may use it
75
76
  // all), so a notice is cut only when the results really exceed it; usage and the full-output hint are never lost.
76
77
  const want = calls.map(c => {
77
- const message = c.result && Object.hasOwn(c.result, 'data') ? JSON.stringify(c.result.data) : c.result?.output;
78
+ const message = commandOutput && c.command !== undefined ? c.result?.output : c.result && Object.hasOwn(c.result, 'data') ? JSON.stringify(c.result.data) : c.result?.output;
78
79
  return 120 + (message?.length ?? 0) + Math.min(320, c.result?.error?.length ?? 0);
79
80
  });
80
81
  const shares = new Array(calls.length).fill(0);
@@ -95,12 +96,25 @@ export function finishedText(wid, entries, call) {
95
96
  const title = `\n${tail(name, allowance - 1)}`;
96
97
  const error = result?.error && allowance - title.length > 10 ? `\n Error: ${tail(result.error, Math.min(300, allowance - title.length - 9))}` : '';
97
98
  const space = allowance - title.length - error.length;
98
- const message = result && Object.hasOwn(result, 'data') ? JSON.stringify(result.data) : result?.output;
99
+ const message = commandOutput && c.command !== undefined ? result?.output : result && Object.hasOwn(result, 'data') ? JSON.stringify(result.data) : result?.output;
99
100
  const line = title + (message && space > 4 ? `\n ${tail(message.trimEnd(), space - 3)}` : '') + error;
100
101
  lines.push(line);
101
102
  }
102
103
  return `${prefix}${lines.join('')}${footer}`;
103
104
  }
105
+ export function wakeText(rid, wid, done, entries) {
106
+ const calls = [...new Map(snapshotFromEntries(wid, entries).calls.map(c => [c.key, c])).values()];
107
+ const lines = calls.slice(0, 20).map(c => {
108
+ const data = c.command !== undefined ? c.result?.data : undefined;
109
+ const ms = data?.durationMs ?? (c.endedAt !== undefined && c.startedAt !== undefined ? c.endedAt - c.startedAt : 0);
110
+ return `${c.key}: ${callStatus(c)}${data?.exitCode != null ? ` exit ${data.exitCode}` : ''}${data?.signal ? ` signal ${data.signal}` : ''} (${Math.max(0, Math.round(ms))}ms)`;
111
+ });
112
+ if (calls.length > 20)
113
+ lines.push(`… ${calls.length - 20} more`);
114
+ const head = `Durable run ${rid} (${wid}) that you started with --wake caller finished: ${done.status}.\n${lines.join('\n')}\n`;
115
+ const prefix = head.slice(0, 4000), space = 4000 - prefix.length;
116
+ return prefix + (space > 0 ? tail(finishedText(wid, entries, undefined, true), space) : '');
117
+ }
104
118
  /** A1, P2, P10, P11: Serialize decisions while executions run independently. */
105
119
  /** A key's latest call in the current revision: its first call or its newest generation. */
106
120
  function latestCall(wf, key) {
@@ -172,7 +186,7 @@ export class Engine {
172
186
  }
173
187
  /** Nothing of the workflow is live: it ended (or parked), no script runs, no executor run or follow-up is open. */
174
188
  quiescent(wf) {
175
- if (!this.terminal(wf) || this.states.has(wf.wid) || this.running.has(wf.wid) || this.openFollowUps(wf))
189
+ if (!this.terminal(wf) || this.wakePending(wf) || this.states.has(wf.wid) || this.running.has(wf.wid) || this.openFollowUps(wf))
176
190
  return false;
177
191
  for (const id of this.generations)
178
192
  if (id.startsWith(`${wf.wid}@`))
@@ -517,7 +531,8 @@ export class Engine {
517
531
  throw error; });
518
532
  }
519
533
  }
520
- this.consumed = { length: this.intakeSeen, pending: view.open.size > 0 };
534
+ await this.deliverWakes();
535
+ this.consumed = { length: this.intakeSeen, pending: this.lifecycle().open.size > 0 };
521
536
  }
522
537
  findCall(to, bareWid = false) {
523
538
  for (const wf of this.store.workflows.values()) {
@@ -571,6 +586,23 @@ export class Engine {
571
586
  }
572
587
  if (req.kind === 'run') {
573
588
  const created = this.ledgers.orch.entries().find(e => e.type === JT.created && e.rid === req.rid);
589
+ if (!created && req.body?.wake !== undefined) {
590
+ const { wake, caller } = req.body;
591
+ const match = typeof caller === 'string' && /^([^@/]+)@(\d+)\/(.+)@(\d+)$/.exec(caller);
592
+ const parent = match ? this.store.workflows.get(match[1]) : undefined;
593
+ const refuse = (reason) => ({ action: 'reject', reason: `wake caller: ${reason}` });
594
+ if (!match || !wake || wake.to !== `${match[1]}/${match[3]}`)
595
+ return refuse('invalid caller');
596
+ if (!parent || this.store.pruned().has(parent.wid))
597
+ return refuse('workflow missing or pruned');
598
+ if (parent.revision !== Number(match[2]))
599
+ return refuse('stale-revision');
600
+ const entry = latestCall(parent, match[3]);
601
+ if (!entry)
602
+ return refuse('unknown key');
603
+ if (isCommandCall(entry.spec))
604
+ return refuse('command call');
605
+ }
574
606
  // Senders validate labels; a hand-written request must not bypass that.
575
607
  const labels = req.body?.labels, invalid = !created && labels !== undefined ? labelsProblem(labels) : undefined;
576
608
  if (invalid)
@@ -615,6 +647,28 @@ export class Engine {
615
647
  this.dispatchGeneration(existing.wf, existing.entry);
616
648
  return { action: 'apply' };
617
649
  }
650
+ // A sealed choice was committed before its reply. Replay it even if another request has since opened a generation.
651
+ const chosen = [...this.store.workflows.values()].filter(wf => wf.journal.loaded !== false || to.startsWith(wf.wid))
652
+ .flatMap(wf => revisionEntries(wf).filter(e => e.type === 'model-choice' && e.rid === req.rid))[0];
653
+ if (chosen) {
654
+ await this.note(req.rid, String(chosen.model), 'next-generation');
655
+ return { action: 'apply' };
656
+ }
657
+ if (req.body?.kind === 'model') {
658
+ // A live forward may have committed just before a crash, then been refused or superseded before replay.
659
+ // Keep its original outcome; never turn it into a fresh sealed choice or send it to a newer generation.
660
+ for (const wf of this.store.workflows.values()) {
661
+ if (wf.journal.loaded === false && !to.startsWith(wf.wid))
662
+ continue;
663
+ const log = revisionEntries(wf), prior = log.find(e => e.type === 'forward' && e.rid === req.rid && e.envelope?.kind === 'model');
664
+ if (!prior)
665
+ continue;
666
+ const entry = log.find(e => (e.type === 'call' || e.type === 'generation') && `${wf.wid}@${wf.revision}/${e.key}@${e.gen}` === prior.dest);
667
+ if (entry && !log.some(e => (e.type === JT.sealed || e.type === 'retired') && e.call === prior.dest))
668
+ return this.executor.forward(req, this.context(wf, entry));
669
+ return { action: 'apply' };
670
+ }
671
+ }
618
672
  const target = this.findCall(req.body?.to, true);
619
673
  if (!target)
620
674
  return { action: 'reject', reason: this.unknownCall(req.body?.to) };
@@ -630,7 +684,7 @@ export class Engine {
630
684
  return this.notify(req, wf, entry, from, seal !== undefined);
631
685
  // A pool's name is a model too: the call keeps the pool, and its order and failover apply to the new generation.
632
686
  const pools = this.ledgers.config.pools, pool = send.model !== undefined && pools && Object.hasOwn(pools, send.model);
633
- if (send.kind === 'follow-up' && send.model !== undefined && !pool) {
687
+ if ((send.kind === 'follow-up' || send.kind === 'model') && send.model !== undefined && !pool) {
634
688
  try {
635
689
  if (!parseModel(send.model).provider)
636
690
  throw new Error('missing provider');
@@ -639,7 +693,7 @@ export class Engine {
639
693
  return { action: 'reject', reason: 'unknown-model' };
640
694
  }
641
695
  }
642
- if (seal && send.kind === 'follow-up')
696
+ if (seal && (send.kind === 'follow-up' || send.kind === 'model'))
643
697
  return this.serialOpen(wf.wid, async () => {
644
698
  // A generation opened meanwhile (undelivered follow-ups after a seal) is the call this follow-up now reaches.
645
699
  if (latestCall(wf, String(entry.key))?.gen !== entry.gen)
@@ -655,6 +709,20 @@ export class Engine {
655
709
  catch (error) {
656
710
  return { action: 'reject', reason: `pin-failed: ${String(error)}` };
657
711
  }
712
+ if (send.kind === 'model') {
713
+ if (!send.model)
714
+ return { action: 'reject', reason: 'unknown-model' };
715
+ // Record only intent. No execution, generation, mailbox delivery or provider reservation is created here.
716
+ try {
717
+ resolveModel(send.model, pools);
718
+ }
719
+ catch {
720
+ return { action: 'reject', reason: 'unknown-model' };
721
+ }
722
+ await wf.journal.append('model-choice', { rid: req.rid, call: from, model: send.model });
723
+ await this.note(req.rid, send.model, 'next-generation');
724
+ return { action: 'apply' };
725
+ }
658
726
  if (send.model !== undefined)
659
727
  await this.note(req.rid, send.model, 'next-generation');
660
728
  const opened = await this.openGeneration(wf, entry, from, { rid: req.rid, message: send.message ?? '', ...(send.model !== undefined ? { model: send.model } : {}) });
@@ -662,7 +730,9 @@ export class Engine {
662
730
  return { action: 'apply' };
663
731
  });
664
732
  // A follow-up naming a model, queued on unfinished work: the executor records its model request with the message.
665
- return this.executor.forward(req, this.context(wf, entry));
733
+ const forwarded = await this.executor.forward(req, this.context(wf, entry));
734
+ // The executor's serial queue may have sealed the call after our lookup; retry through the same sealed branch.
735
+ return send.kind === 'model' && forwarded.action === 'reject' && forwarded.reason === 'call-sealed' ? { action: 'defer' } : forwarded;
666
736
  }
667
737
  else if (req.kind === 'stop') {
668
738
  const target = req.body?.target;
@@ -838,6 +908,8 @@ export class Engine {
838
908
  /** Housekeeping: Why a workflow cannot be pruned: not final (parked or running), open executor work, an unresolved
839
909
  * fence failure, or ended after the cutoff. */
840
910
  unprunable(wf, cutoff) {
911
+ if (this.wakePending(wf))
912
+ return 'wake pending';
841
913
  const done = this.terminal(wf), status = done ? String(done.status) : 'running';
842
914
  if (!['done', 'failed', 'stopped'].includes(status))
843
915
  return `not-finished:${status}`;
@@ -877,7 +949,9 @@ export class Engine {
877
949
  catch (error) {
878
950
  return `event-log: ${error instanceof Error ? error.message : String(error)}`;
879
951
  }
880
- await this.ledgers.orch.append('pruned', { rid, wid: wf.wid, endedAt: done.ts, bytes, status: String(done.status), ...identity });
952
+ const wake = wf.wake && wf.journal.entries().findLast(e => e.type === 'wake-outcome');
953
+ const wakeReceipt = wake ? { wake: { to: wf.wake.to, state: wake.state, rev: wake.rev, ...(wake.generation !== undefined ? { generation: wake.generation } : {}), ...(wake.reason !== undefined ? { reason: wake.reason } : {}) } } : {};
954
+ await this.ledgers.orch.append('pruned', { rid, wid: wf.wid, endedAt: done.ts, bytes, status: String(done.status), ...identity, ...wakeReceipt });
881
955
  this.states.delete(wf.wid);
882
956
  await this.store.drop(wf.wid);
883
957
  try {
@@ -893,15 +967,16 @@ export class Engine {
893
967
  async openGeneration(wf, entry, from, own) {
894
968
  const log = revisionEntries(wf), key = String(entry.key), notes = pendingNotes(log, key), carried = pendingFollowUps(log, key);
895
969
  const asked = (rid) => this.ledgers.orch.entries().findLast(e => e.type === 'request' && e.request?.rid === rid)?.request?.body?.model;
896
- const model = [...carried.map(c => asked(c.rid)), own?.model].filter((m) => typeof m === 'string').at(-1);
970
+ const model = own?.model ?? generationModel(log, from) ?? carried.map(c => asked(c.rid)).filter((m) => typeof m === 'string').at(-1) ??
971
+ (typeof entry.choice === 'string' ? entry.choice : undefined);
897
972
  const pools = this.ledgers.config.pools, pool = model !== undefined && pools && Object.hasOwn(pools, model);
898
973
  const rid = own?.rid ?? carried[0].rid, follows = carried.map(c => c.rid).filter(r => r !== rid);
899
974
  const gen = Math.max(0, ...wf.journal.entries().filter(e => ['call', 'generation'].includes(e.type) && e.key === entry.key).map(e => Number(e.gen))) + 1;
900
- // A follow-up's model replaces the continued session's for this generation and those continuing it.
975
+ // A follow-up's explicit model or a new manual choice persists in the spec of every later generation.
901
976
  const spec = model !== undefined ? { ...entry.spec, model } : entry.spec;
902
977
  const message = openingMessage(notes.map(n => String(n.message)), [...carried.map(c => c.message), own?.message ?? '']);
903
978
  return wf.journal.append('generation', { rid, key: entry.key, gen, from, spec, revision: wf.revision, opening: { rid, kind: 'follow-up', message },
904
- ...(notes.length ? { notes: notes.map(n => String(n.rid)) } : {}), ...(follows.length ? { follows } : {}), ...(model !== undefined && !pool ? { model } : {}) });
979
+ ...(notes.length ? { notes: notes.map(n => String(n.rid)) } : {}), ...(follows.length ? { follows } : {}), ...(model !== undefined ? { choice: model } : {}), ...(model !== undefined && !pool ? { model } : {}) });
905
980
  }
906
981
  /** Follow-ups forwarded into running work whose call sealed before taking them (`undelivered-follow-up`) open the
907
982
  * key's next generation, as a follow-up sent after the seal would: once its latest generation has sealed, unless a
@@ -1244,6 +1319,78 @@ export class Engine {
1244
1319
  if (done && !wf.journal.entries().some(e => isEntry(e, JT.attention) && e.item.id === `finished:${wf.wid}` && e.item.rev === rev)) {
1245
1320
  await wf.journal.append(JT.attention, { item: { id: `finished:${wf.wid}`, rev, kind: 'finished', wid: wf.wid, text: finishedText(wf.wid, wf.journal.entries()) } });
1246
1321
  }
1322
+ await this.deliverWake(wf);
1323
+ }
1324
+ /** A pending wake keeps the journal decoded and unprunable until its durable outcome is recorded. */
1325
+ wakePending(wf) {
1326
+ if (!wf.wake || lazy(wf))
1327
+ return false;
1328
+ const log = wf.journal.entries(), rev = log.filter(e => e.type === JT.done).length;
1329
+ return !rev || !log.some(e => e.type === 'wake-outcome' && e.rev === rev);
1330
+ }
1331
+ async deliverWakes() {
1332
+ for (const wf of this.store.workflows.values())
1333
+ if (wf.wake && !lazy(wf)) {
1334
+ await this.deliverWake(wf);
1335
+ this.settle(wf);
1336
+ }
1337
+ }
1338
+ /** The intent pins the message before admission. Lifecycle resolution and send's existing generation/forward
1339
+ * receipts make every crash cut replayable, including a crash between the send effect and its decision. */
1340
+ waking = new Map();
1341
+ deliverWake(wf) {
1342
+ const pending = this.waking.get(wf.wid);
1343
+ if (pending)
1344
+ return pending;
1345
+ const run = this.deliverWakeNow(wf).finally(() => { if (this.waking.get(wf.wid) === run)
1346
+ this.waking.delete(wf.wid); });
1347
+ this.waking.set(wf.wid, run);
1348
+ return run;
1349
+ }
1350
+ async deliverWakeNow(wf) {
1351
+ if (!wf.wake || lazy(wf))
1352
+ return;
1353
+ const { rid, to, caller } = wf.wake;
1354
+ const dones = wf.journal.entries().filter(e => e.type === JT.done);
1355
+ for (const [n, done] of dones.entries()) {
1356
+ const rev = n + 1;
1357
+ if (wf.journal.entries().some(e => e.type === 'wake-outcome' && e.rev === rev))
1358
+ continue;
1359
+ let intent = wf.journal.entries().find(e => e.type === 'wake-request' && e.rev === rev);
1360
+ if (!intent) {
1361
+ const target = this.findCall(to), id = target && `${target.wf.wid}@${target.wf.revision}/${target.entry.key}@${target.entry.gen}`;
1362
+ const seal = target?.wf.journal.entries().find(e => e.type === JT.sealed && e.call === id);
1363
+ if (target && `${target.wf.wid}@${target.wf.revision}` === caller.slice(0, caller.indexOf('/')) && seal?.result?.status === 'stopped') {
1364
+ await wf.journal.append('wake-outcome', { rev, state: 'skipped', reason: 'caller stopped' });
1365
+ continue;
1366
+ }
1367
+ const request = { rid: `wake-${contentHash([rid, rev]).slice(0, 32)}`, from: `wake:${rid}:${rev}`, to: 'orch', sseq: 1,
1368
+ kind: 'send', cond: { epoch: caller.slice(0, caller.indexOf('/')) }, body: { to, kind: 'follow-up', message: wakeText(requestId(rid) ?? rid, wf.wid, done, wf.journal.entries().filter(e => e.seq <= done.seq)) } };
1369
+ intent = await wf.journal.append('wake-request', { rev, request });
1370
+ }
1371
+ const request = intent.request;
1372
+ for (const { type, ...fields } of planDecisions(this.lifecycle(), [request], () => ({ action: 'defer' }))) {
1373
+ if (type === 'admitted')
1374
+ await this.ledgers.orch.append('request', { request });
1375
+ await this.ledgers.orch.append(type, fields);
1376
+ }
1377
+ let resolution = this.lifecycle().resolved.get(request.rid);
1378
+ if (!resolution) {
1379
+ const decision = await this.decide(request);
1380
+ if (decision.action === 'defer')
1381
+ return;
1382
+ for (const { type, ...fields } of planDecisions(this.lifecycle(), [request], () => decision))
1383
+ await this.ledgers.orch.append(type, fields);
1384
+ resolution = this.lifecycle().resolved.get(request.rid);
1385
+ }
1386
+ if (!resolution)
1387
+ continue;
1388
+ const target = this.findCall(to), opened = target && revisionEntries(target.wf).find(e => e.type === 'generation' && generationRids(e).includes(request.rid));
1389
+ const forward = target && target.wf.journal.entries().find(e => e.type === 'forward' && e.rid === request.rid);
1390
+ const generation = opened ? Number(opened.gen) : forward ? Number(String(forward.dest).match(/@(\d+)$/)?.[1]) : undefined;
1391
+ await wf.journal.append('wake-outcome', { rev, state: resolution.type === 'applied' ? 'applied' : 'rejected',
1392
+ ...(resolution.type === 'rejected' ? { reason: resolution.reason } : {}), ...(generation !== undefined ? { generation } : {}) });
1393
+ }
1247
1394
  }
1248
1395
  async resolveFinished(wf) {
1249
1396
  for (const { item } of attentionEntries(wf.journal.entries())) {
@@ -1,6 +1,13 @@
1
1
  // Command calls: the workflow journal records the executor writes for them (documented in index.ts) and the questions
2
2
  // the engine and recovery ask of them. Pure functions of the journal's entries.
3
+ import { delimiter } from "node:path";
4
+ import { binDir } from "../../paths.js";
3
5
  import { JT } from "../../types.js";
6
+ /** EX3: Custom/inherited tools win; the orchestrator's shim is the last PATH entry, never an empty entry. */
7
+ export function commandEnvironment(home, id, call, env) {
8
+ const bin = binDir(home), PATH = [...(env?.PATH ?? process.env.PATH ?? "").split(delimiter).filter(p => p && p !== bin), bin].join(delimiter);
9
+ return { ...process.env, ...env, PATH, DSA_EXEC: id, DSA_CALL: call, DSA_HOME: home };
10
+ }
4
11
  export const COMMAND_INTENT = "command-intent";
5
12
  export const COMMAND_STARTED = "command-started";
6
13
  export const COMMAND_SPAWN_FAILED = "command-spawn-failed";
@@ -2,7 +2,7 @@
2
2
  // extends its entries array with the same entry objects when the file grew, so a fold over a prefix is reused and
3
3
  // only appended entries are visited. A session read from scratch (rewritten, replaced) restarts the fold. Each fold
4
4
  // equals what the whole-array function it replaces computes over the same entries (see the tests).
5
- import { CT } from "../../types.js";
5
+ import { CT, askFields } from "../../types.js";
6
6
  import { askOf, cutAskResult, receiptId } from "./session.js";
7
7
  import { messageUsage } from "./usage.js";
8
8
  export const answerKey = (qid, rev) => JSON.stringify([qid, rev]);
@@ -53,7 +53,7 @@ export class SessionFold {
53
53
  if (e.type === "custom") {
54
54
  s.lastQuestion = i;
55
55
  if (this.own && e.data && typeof e.data.qid === "string" && typeof e.data.rev === "number")
56
- s.questions.push({ qid: e.data.qid, rev: e.data.rev, question: e.data.question });
56
+ s.questions.push({ qid: e.data.qid, rev: e.data.rev, question: e.data.question, ...askFields(e.data) });
57
57
  }
58
58
  }
59
59
  const details = e.message?.details ?? e.details;
@@ -83,5 +83,5 @@ export function digestOpenQuestion(entries, s) {
83
83
  const result = ask === undefined ? undefined : s.results.get(ask);
84
84
  if (ask === undefined || result && !cutAskResult(result.message))
85
85
  return;
86
- return { qid: q.qid, rev: q.rev, question: String(q.question) };
86
+ return { qid: q.qid, rev: q.rev, question: String(q.question), ...askFields(q) };
87
87
  }
@@ -0,0 +1,23 @@
1
+ import { commandLine } from "../../platform/cmdline.js";
2
+ /** EX1 / WK8: Agent fences only. The direct child's tracked identity is retained across recovery (old journals: first tracked). */
3
+ export async function fenceAgent(containment, journal, exec, tracked, child) {
4
+ const options = { beforeKill: async (targets, signal) => {
5
+ const identities = journal.entries().filter(e => e.type === "tracked" && e.exec === exec);
6
+ const direct = child ?? identities.find(e => e.child === true) ?? identities[0];
7
+ // R-11-3: a crash after spawn but before tracked leaves no provable direct identity. Roots of the target
8
+ // forest may be pi or orphaned descendants: omit all roots rather than ever reporting the direct child.
9
+ const pids = new Set(targets.map(p => p.pid));
10
+ const others = direct ? targets.filter(p => p.pid !== direct.pid || p.start !== direct.start)
11
+ : targets.filter(p => pids.has(p.ppid));
12
+ if (!others.length || signal.aborted)
13
+ return;
14
+ const commands = await Promise.all(others.map(async (p) => ({ pid: p.pid, command: await commandLine(p.pid, signal) })));
15
+ const procs = commands.slice(0, 20);
16
+ // The timeout cancels command reads and prevents an outstanding read from appending after the kill/seal.
17
+ if (signal.aborted)
18
+ return;
19
+ await journal.append("ended", { exec, call: exec.slice(0, exec.lastIndexOf("#")), procs,
20
+ ...(others.length > procs.length ? { more: others.length - procs.length } : {}) });
21
+ } };
22
+ await containment.fence(exec, tracked, options);
23
+ }