pi-durable-subagents 1.0.40 → 1.0.41

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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,34 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.0.41
4
+
5
+ - An answer that races the planned hibernation no longer strands its call. In 1.0.40 the parent forwarded an answer,
6
+ the call hibernated two seconds later, the child had already read the answer and was fenced, and the call showed
7
+ `asking` for 49 minutes until a second answer arrived. Hibernation is now decided on the current journal inside the
8
+ serial section and is refused while an answer forward to the call is pending or in flight. A call fenced while
9
+ stopped on that `ask` (hibernated on the question, or the answer receipt is the last thing it did) is treated as
10
+ answered and continues its session at once, live and after recovery; a call that kept working after the answer is
11
+ judged by its own evidence as before (report, `once` with a dangling tool, losses). `status` flags an answer that
12
+ was forwarded but not delivered within 30 seconds.
13
+ - A bound answer excuses losses only for the execution it was bound to and for the first launch that never started a
14
+ child. A child that keeps dying before its first marker now stops at `lossBound` instead of relaunching without
15
+ limit (a defect since before 1.0.40).
16
+ - A resumed pool call no longer waits a whole turn on its session's full provider. After `k.resumeSpillMs` (default
17
+ 120000; `0` at once; `null` or negative never) it continues the same session on another entry of its pool that has a
18
+ free slot, preferring the same model id (compared by its last path segment, case-insensitively, without thinking
19
+ suffix). Explicit models and models requested by the parent never spill. `status` shows the wait, the free pool
20
+ providers and the spill. The wait timer restarts after recovery.
21
+ - A child never answers with a model dsa did not select. The child extension checks the active model at session
22
+ start and before every turn; a mismatch (for example pi falling back to its default model because the selected
23
+ provider has no credentials) stops the execution before its first request and records `model-unavailable` with
24
+ the reason. A pool call fails over to the next entry and skips the failed one for ten minutes; a call with an
25
+ explicit model fails naming both models. Virtual (routed) models must activate at launch; their answers name the
26
+ routed physical model, shown as `routed Y`. Any other answer from an unselected model shows `used Y, selected X`.
27
+ A refusal is rechecked once against fresh credentials of that provider first: pi can answer `setModel` from an
28
+ availability snapshot that a startup refresh briefly replaced (seen after resumes on CI), which is not a missing
29
+ credential.
30
+ - Slot waits are journaled once per wait episode; free providers are computed live for `status`.
31
+
3
32
  ## 1.0.40
4
33
 
5
34
  - Readers keep rebuildable digests of settled workflows and facts of final calls in `DSA_HOME/cache`, keyed by
package/README.md CHANGED
@@ -57,7 +57,7 @@ the npx cache, so `install-service` refuses to run from there.
57
57
  | A step is refused, or a dependency fails | The workflow stops that branch cleanly. Nothing is retried in vain. |
58
58
  | A provider's usage window runs out (`No available accounts`, usage limit, quota exceeded, a daily quota at 0) | Found at the second refusal in a row, while pi is still retrying. A call in a pool continues **in the same session** on the pool's next model (within pi's next retry or two); new calls skip that provider. After 15 minutes the next call that wants it tries it once; when it answers, new calls and new generations use it again. A call with a single model waits for it instead of failing. Billing errors (402, insufficient balance) still fail at once. |
59
59
  | Two subagents would write in the same worktree | Only one runs there at a time. A call that can write (its tools include `edit` or `write`, which pi's default tools do) holds its git worktree's writer lock from its launch until it ends, also while it waits for an answer. Another writer for that worktree waits in order, and status shows `waiting for writer lock: <root> held by <wid>/<key>`. `writer: false` (a call that does not write there), `isolation: "worktree"` and `"writerLock": "off"` opt out. |
60
- | A subagent waits for an answer for a long time | It releases its model slot and memory, then resumes exactly once when you answer. The question survives orchestrator restarts (also forced ones) and crashes, including one that hits before the subagent released its slot. |
60
+ | A subagent waits for an answer for a long time | It releases its model slot and memory, then resumes exactly once when you answer. A forwarded answer prevents planned hibernation. If an execution was stopped after consuming the answer, recovery continues the same session without another answer. The question survives orchestrator restarts (also forced ones) and crashes, including one that hits before the subagent released its slot. |
61
61
  | A subagent's work ends (finished, stopped, or cut off) | Every process its tools started ends with that execution, also ones started with `nohup`, `setsid` or `&`: they carry the execution's tag (see the limit below). Anything that must outlive the subagent has to be started by you or the parent session. A command run under `hold` is no exception: a forced restart stops it and its lease is released. |
62
62
  | A subagent runs in a worktree you made (`isolation: "none"`, the default, with `cwd`) | Durable Subagents never creates, cleans, moves or deletes that directory or its branch, also not on `prune`; `prune` deletes only its own state and the worktrees it created for `isolation: "worktree"`. |
63
63
 
@@ -544,6 +544,10 @@ answer is bound. A drained call
544
544
  (no execution running) is never `silent`; a sealed call never waits. `provider-exhausted`, `writer-lock`, `lease` and `slot` are queues
545
545
  that clear by themselves; `silent` and `unconfirmed-stop` may need a look.
546
546
 
547
+ An open question with an unconfirmed answer forward carries
548
+ `answerForwarded: {rid, qid, rev, at}` in JSON status. After 30 seconds, text status
549
+ says `asking: answer forwarded <age> ago, not delivered` instead of plain `asking`.
550
+
547
551
  ### Housekeeping
548
552
 
549
553
  Journals are never compacted, so state only grows. `prune` removes finished
@@ -745,6 +749,24 @@ State lives in `~/.pi/durable-subagents`; set `DSA_HOME` to move it.
745
749
  session's model or was asked for a model, and a running call that moves off
746
750
  a used-up provider skips such entries, as does a model send that names the
747
751
  pool.
752
+ - **Resumed pool calls:** keep their session's model for its prompt cache, but
753
+ after 2 minutes queued on its full provider try another free provider in the
754
+ same pool. Set `"k": { "resumeSpillMs": 120000 }` to change the wait;
755
+ `0` spills immediately, `null` or a negative number keeps waiting indefinitely.
756
+ The same model id on another provider is preferred, then pool order; the new
757
+ entry's thinking level and `afterMs` apply. This continues the same session
758
+ but gives up the old provider's prompt cache. Explicit models and models
759
+ requested by the parent do not spill. The timer restarts for each execution,
760
+ including recovery after an orchestrator restart, like `afterMs`.
761
+ `status` shows the queued provider, elapsed wait and free pool providers,
762
+ then the recorded spill and how long it waited (`poolWait` / `spill` in JSON).
763
+ - **Selected model unavailable:** before delivering work, the child verifies
764
+ that pi activated the selected model (including catalog aliases and display
765
+ names). Missing auth or a different model stops that execution; a pool call
766
+ tries another entry and skips the unavailable entry for that call for 10
767
+ minutes. A single-model call fails with the selected model, pi's fallback
768
+ and the reason. `status` retains `modelUnavailable`; an unexpected answering
769
+ model also shows `used Y, selected X` (`modelMismatch` in JSON).
748
770
  - **A used-up provider** is not sent new calls until its next try, 15 minutes
749
771
  after it last refused (`"k": { "probeMs": 900000 }`). Then one call at a
750
772
  time goes to it, so finding out costs no extra request. A call that moved to
@@ -1,4 +1,4 @@
1
- import { watch } from 'node:fs';
1
+ import fs, { watch } from 'node:fs';
2
2
  import { readFile } from 'node:fs/promises';
3
3
  import { Type } from '@earendil-works/pi-ai';
4
4
  import { ASK_CUT, CT, ENV, JT } from "../types.js";
@@ -9,6 +9,7 @@ import { planDecisions } from "../kernel/lifecycle.js";
9
9
  import { openness } from "../kernel/guards.js";
10
10
  import { recover } from "./child/history.js";
11
11
  import { validate } from "./child/schema.js";
12
+ import { catalogModel, parseModel, sameModel } from "../compat/model.js";
12
13
  import { registerLive } from "./child/live.js";
13
14
  const MESSAGES = ['task', 'steer', 'notify', 'follow-up', 'continue'];
14
15
  /** D2: the questions a bound continue supersedes: the hibernated asker's own question when it resumes with the answer
@@ -65,25 +66,69 @@ export function registerChild(pi) {
65
66
  * pi captures a turn's model when the turn begins, so a correction in the `context` hook comes too late for that
66
67
  * turn: seen on CI as one "Unknown provider: unknown" reply (pi's placeholder model) after a resume. The registry
67
68
  * can briefly lack an extension provider at startup, so wait for it up to 5 s. */
68
- async function ensureModel(ctx) {
69
- const slash = target?.indexOf('/') ?? -1;
70
- if (!target || slash <= 0 || `${ctx.model?.provider}/${ctx.model?.id}` === target)
71
- return;
72
- let model = ctx.modelRegistry.find(target.slice(0, slash), target.slice(slash + 1));
69
+ let verified, modelFailed = false;
70
+ async function ensureModel(ctx, correct = true) {
71
+ if (modelFailed)
72
+ return false;
73
+ if (!target)
74
+ return true;
75
+ const selected = parseModel(target), actual = ctx.model ? { provider: ctx.model.provider, id: ctx.model.id } : { id: 'none' };
76
+ let model = ctx.modelRegistry.find(selected.provider, selected.id) ?? catalogModel(selected, ctx.modelRegistry.getAll());
73
77
  for (let waited = 0; !model && waited < 5000; waited += 50) {
74
78
  await new Promise(resolve => setTimeout(resolve, 50));
75
- model = ctx.modelRegistry.find(target.slice(0, slash), target.slice(slash + 1));
79
+ model = ctx.modelRegistry.find(selected.provider, selected.id) ?? catalogModel(selected, ctx.modelRegistry.getAll());
76
80
  }
77
- if (model)
78
- await pi.setModel(model);
79
- else
80
- console.error(`durable-subagents: model ${target} is not registered in this pi (have: ${[...new Set(ctx.modelRegistry.getAll().map(m => m.provider))].join(', ')})`);
81
+ let reason;
82
+ if (!model)
83
+ reason = `model is not registered for provider ${selected.provider}`;
84
+ else if (!sameModel(ctx.model, model)) {
85
+ if (!correct)
86
+ reason = 'active model changed after turn selection';
87
+ else
88
+ try {
89
+ // pi 1.0.2 answers setModel from an availability snapshot that a startup refresh can briefly replace with
90
+ // one taken before an extension provider registered (seen on CI after a resume: provider found, setModel
91
+ // refused). Recheck that provider's credentials once, authoritatively, before calling the model unavailable.
92
+ if (!await pi.setModel(model)) {
93
+ try {
94
+ await ctx.modelRegistry.refresh({ providers: [model.provider], allowNetwork: false });
95
+ }
96
+ catch { /* recheck below */ }
97
+ if (!await pi.setModel(model))
98
+ reason = `no auth for provider ${model.provider} (setModel refused)`;
99
+ }
100
+ }
101
+ catch (error) {
102
+ reason = String(error);
103
+ }
104
+ }
105
+ if (!reason && model && !sameModel(ctx.model, model))
106
+ reason = 'pi did not activate the selected model';
107
+ if (reason) {
108
+ modelFailed = true;
109
+ active = false;
110
+ watcher?.close();
111
+ const data = { exec, selected, actual, reason };
112
+ pi.appendEntry(CT.modelUnavailable, data);
113
+ // Native state survives a crash; RPC wakes the observer even before a first answer exists.
114
+ fs.writeSync(process.stdout.fd, JSON.stringify({ type: CT.modelUnavailable, ...data }) + '\n');
115
+ console.error(`durable-subagents: model-unavailable: selected ${target}, pi would use ${actual.provider ? `${actual.provider}/` : ''}${actual.id}: ${reason}`);
116
+ ctx.shutdown();
117
+ return false;
118
+ }
119
+ if (verified !== target) {
120
+ const data = { exec, selected, model: { provider: model.provider, id: model.id }, virtual: model.api === 'pi-virtual' };
121
+ pi.appendEntry(CT.modelReady, data);
122
+ fs.writeSync(process.stdout.fd, JSON.stringify({ type: CT.modelReady, ...data }) + '\n');
123
+ verified = target;
124
+ }
125
+ return true;
81
126
  }
82
127
  async function consume(ctx, mode) {
83
128
  if (!active || (mode === 'idle' && !ctx.isIdle()))
84
129
  return [];
85
- if (mode === 'idle')
86
- await ensureModel(ctx); // an idle delivery starts a turn
130
+ if (mode === 'idle' && !await ensureModel(ctx))
131
+ return []; // an idle delivery starts a turn
87
132
  const candidates = await scanInbox(inbox), byRid = new Map(candidates.map(req => [req.rid, req]));
88
133
  // Scan is asynchronous: recheck before using the idle delivery API.
89
134
  if (!active || (mode === 'idle' && !ctx.isIdle()))
@@ -257,7 +302,8 @@ export function registerChild(pi) {
257
302
  // The executor names the model it holds a slot for; apply it before any provider request if pi did not.
258
303
  // Observed with pi 1.0.2 on resumed sessions: the registry briefly lacks an extension provider at startup.
259
304
  // Nothing is delivered (so no provider request starts) until the held model is resolvable, for up to 5 s.
260
- await ensureModel(ctx);
305
+ if (!await ensureModel(ctx))
306
+ return;
261
307
  watcher = watch(inbox, () => { void serial(async () => { await consume(ctx, blocked ? 'ask' : 'idle'); }).catch(error => fail(ctx, error)); });
262
308
  watcher.on('error', error => fail(ctx, error));
263
309
  await consume(ctx, 'idle');
@@ -282,14 +328,11 @@ export function registerChild(pi) {
282
328
  // turn_start runs before the request is prepared (pi reads the model then); `context` runs after it, too late for
283
329
  // that request (seen on CI: model_change after the delivered message, then "Unknown provider: unknown"). Keep both.
284
330
  const guard = async (_event, ctx) => {
285
- const slash = target?.indexOf('/') ?? -1;
286
- if (!target || slash <= 0 || `${ctx.model?.provider}/${ctx.model?.id}` === target)
287
- return;
288
- const model = ctx.modelRegistry.find(target.slice(0, slash), target.slice(slash + 1));
289
- if (model)
290
- await pi.setModel(model);
291
- else
292
- console.error(`durable-subagents: model ${target} is not registered before a provider request`);
331
+ if (!await ensureModel(ctx, _event?.type !== 'context')) {
332
+ // Hook errors are swallowed by pi. Exit this owned child synchronously so a captured fallback model
333
+ // cannot make a request, even when a provider ignores abort. The receipt was appended synchronously.
334
+ process.exit(1);
335
+ }
293
336
  };
294
337
  pi.on('turn_start', guard);
295
338
  pi.on('context', guard);
package/dist/cli/main.js CHANGED
@@ -7,7 +7,7 @@ import { setTimeout as delay } from "node:timers/promises";
7
7
  import { dsaHome } from "../paths.js";
8
8
  import { readJournalSnapshot } from "../kernel/journal.js";
9
9
  import { journalPath, orchLedger } from "../paths.js";
10
- import { allWorkflows, eventsFromEntries, heldWorkflows, isLive, formatUsage, renderEvent, statusDetail, statusView, workflowSnapshot, compactWorkflow, labelsText, outputSelect, statusCompactDetail } from "../orchestrator/snapshot.js";
10
+ import { answerForwardedNote, modelStatusText, allWorkflows, eventsFromEntries, heldWorkflows, isLive, formatUsage, renderEvent, statusDetail, statusView, workflowSnapshot, compactWorkflow, labelsText, outputSelect, statusCompactDetail } from "../orchestrator/snapshot.js";
11
11
  import { statsLine } from "../orchestrator/stats.js";
12
12
  import { resolution, start, startOrchestrator, submit } from "./control.js";
13
13
  import { doctor, renderDoctor, size } from "./doctor.js";
@@ -102,14 +102,17 @@ const clip = (text, n) => text.length > n ? `${text.slice(0, n)}…` : text;
102
102
  /** Notes recorded for a call that is not running (send kind "notify"); its next follow-up carries them. */
103
103
  const notesLine = (n) => n ? ` · ${n} note${n > 1 ? "s" : ""} pending` : "";
104
104
  /** An answered asker waiting for a slot; nothing while a drain holds its workflow (it waits for resume, as the UI says). */
105
- const answeredNote = (c, paused) => c.phase === "queued" && c.answered && !paused ? " (answered, waiting for a slot)" : "";
105
+ const answeredNote = (c, paused) => {
106
+ const forwarded = answerForwardedNote(c);
107
+ return forwarded ? `: ${forwarded}` : c.phase === "queued" && c.answered && !paused ? " (answered, waiting for a slot)" : "";
108
+ };
106
109
  /** P25, T10: Render journal-derived status (one line per call, last output line only) without live orchestrator memory. */
107
110
  export function renderStatus(wf) {
108
111
  const sealed = wf.counts.sealed, total = wf.calls.length, used = wf.usage && (wf.usage.input || wf.usage.output || wf.usage.costUsd);
109
112
  return [`${wf.wid}@${wf.rev}${wf.labels ? ` ${labelsText(wf.labels)}` : ""}${wf.name ? ` ${wf.name}` : ""}: ${wf.followUps ? `follow-up running (run ${wf.status})` : wf.status}${wf.error ? ` (${clip(wf.error, 300)})` : ""} · ${sealed}/${total} sealed${used ? ` · ${formatUsage(wf.usage)}` : ""}`,
110
113
  ...wf.calls.map(c => {
111
114
  const last = c.result?.output?.split("\n").map(l => l.trim()).filter(Boolean).at(-1), err = c.result?.error;
112
- return ` ${c.key}@${c.gen} ${c.result?.status ?? c.phase}${answeredNote(c, wf.paused)}${c.model ? ` ${c.model}` : ""}${c.tools ? ` tools:${c.tools}` : ""}${c.usage && (c.usage.input || c.usage.output) ? ` ${formatUsage(c.usage)}` : ""}${last ? ` ${JSON.stringify(clip(last, 160))}` : err ? ` (${clip(err, 160)})` : ""}${c.sharedWorktree ? ` (shares worktree with ${c.sharedWorktree.join(", ")})` : ""}${c.writerWait && !c.result && c.phase !== "sealed" ? ` (waiting for writer lock: ${c.writerWait.root} held by ${c.writerWait.holder})` : ""}${notesLine(c.notesPending)}`;
115
+ return ` ${c.key}@${c.gen} ${c.result?.status ?? c.phase}${answeredNote(c, wf.paused)}${c.model ? ` ${c.model}` : ""}${c.tools ? ` tools:${c.tools}` : ""}${c.usage && (c.usage.input || c.usage.output) ? ` ${formatUsage(c.usage)}` : ""}${last ? ` ${JSON.stringify(clip(last, 160))}` : err ? ` (${clip(err, 160)})` : ""}${c.sharedWorktree ? ` (shares worktree with ${c.sharedWorktree.join(", ")})` : ""}${c.writerWait && !c.result && c.phase !== "sealed" ? ` (waiting for writer lock: ${c.writerWait.root} held by ${c.writerWait.holder})` : ""}${notesLine(c.notesPending)}${modelStatusText(c)}`;
113
116
  }),
114
117
  ...wf.attention.map(a => ` ${a.kind}: ${JSON.stringify(clip(a.text, 300))}`),
115
118
  ...(wf.scriptLog ? [` script log: ${wf.scriptLog}`] : [])].join("\n");
@@ -122,7 +125,7 @@ export function renderSelected(wf) {
122
125
  /** P25, T10: Render the compact status projection shared with the `subagents` tool. */
123
126
  export function renderView(view) {
124
127
  const lines = view.workflows.map(w => [`${w.wid}@${w.rev}${w.labels ? ` ${labelsText(w.labels)}` : ""}${w.name ? ` ${w.name}` : ""}: ${w.followUps ? `follow-up running (run ${w.status})` : w.status}${w.error ? ` (${clip(w.error, 200)})` : ""} · ${w.done}/${w.planned ?? w.calls.length}${w.planned === undefined && w.status === "running" ? "+" : ""} done${w.usage.input || w.usage.output || w.usage.costUsd ? ` · ${formatUsage(w.usage)}` : ""}`,
125
- ...w.calls.map(c => ` ${c.key}@${c.gen} ${c.status ?? c.phase}${answeredNote(c, w.paused)}${c.hibernated ? " (hibernated, no slot)" : ""}${c.model ? ` ${c.model}` : ""}${c.switching ? ` → ${c.switching} (requested)` : ""}${c.switchFailed ? ` (switch refused: ${c.switchFailed})` : ""}${c.tools ? ` tools:${c.tools}` : ""}${c.usage ? ` ${formatUsage(c.usage)}` : ""}${c.lastLine ? ` ${JSON.stringify(c.lastLine)}` : c.error ? ` (${c.error})` : ""}${c.sharedWorktree ? ` (shares worktree with ${c.sharedWorktree.join(", ")})` : ""}${c.writerWait && c.phase !== "sealed" ? ` (waiting for writer lock: ${c.writerWait.root} held by ${c.writerWait.holder})` : ""}${c.lease && c.phase !== "sealed" ? ` (${c.lease})` : ""}${notesLine(c.notesPending)}`),
128
+ ...w.calls.map(c => ` ${c.key}@${c.gen} ${c.status ?? c.phase}${answeredNote(c, w.paused)}${c.hibernated ? " (hibernated, no slot)" : ""}${c.model ? ` ${c.model}` : ""}${c.switching ? ` \u2192 ${c.switching} (requested)` : ""}${c.switchFailed ? ` (switch refused: ${c.switchFailed})` : ""}${c.tools ? ` tools:${c.tools}` : ""}${c.usage ? ` ${formatUsage(c.usage)}` : ""}${c.lastLine ? ` ${JSON.stringify(c.lastLine)}` : c.error ? ` (${c.error})` : ""}${c.sharedWorktree ? ` (shares worktree with ${c.sharedWorktree.join(", ")})` : ""}${c.writerWait && c.phase !== "sealed" ? ` (waiting for writer lock: ${c.writerWait.root} held by ${c.writerWait.holder})` : ""}${c.lease && c.phase !== "sealed" ? ` (${c.lease})` : ""}${notesLine(c.notesPending)}${modelStatusText(c)}`),
126
129
  ...w.attention.map(a => ` ${a.kind}: ${JSON.stringify(a.text.split("\n")[0])}`)].join("\n"));
127
130
  if (view.paused)
128
131
  lines.unshift(`${view.paused} (pi-durable-subagents resume)`);
@@ -1,6 +1,18 @@
1
1
  export const thinkingLevels = ["off", "minimal", "low", "medium", "high", "xhigh", "max"];
2
2
  /** The model without scheduling fields, as recorded and launched. */
3
3
  export const plainModel = (m) => ({ ...(m.provider !== undefined ? { provider: m.provider } : {}), id: m.id, ...(m.thinking ? { thinking: m.thinking } : {}) });
4
+ export const sameModel = (a, b) => !!a && !!b && a.provider?.toLowerCase() === b.provider?.toLowerCase() && a.id.toLowerCase() === b.id.toLowerCase();
5
+ /** Resolve CLI spelling within the selected provider, using pi's alias-before-dated ordering. */
6
+ export function catalogModel(selected, catalog) {
7
+ const models = catalog.filter(m => m.provider.toLowerCase() === selected.provider?.toLowerCase());
8
+ const exact = models.find(m => sameModel(m, selected));
9
+ if (exact)
10
+ return exact;
11
+ const name = selected.id.toLowerCase();
12
+ const matches = models.filter(m => m.id.toLowerCase().includes(name) || m.name?.toLowerCase().includes(name));
13
+ const aliases = matches.filter(m => !/-\d{8}$/.test(m.id));
14
+ return (aliases.length ? aliases : matches).sort((a, b) => b.id.localeCompare(a.id))[0];
15
+ }
4
16
  /** P35: Parse Pi model identifiers, preserving colons that are not thinking suffixes. */
5
17
  export function parseModel(value) {
6
18
  let id = value.trim();
@@ -10,7 +10,7 @@ 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
12
  const KEYS = ["defaultModel", "pools", "providers", "memory", "writerLock", "k"];
13
- const K = ["lossBound", "checkpointMs", "stallMs", "progressMs", "switchTimeoutMs", "idleExitMs", "trackerMs", "hibernateMs", "spawnBudget", "probeMs", "eventRetentionMs", "waitCheckMs"];
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. */
16
16
  export function orchestratorSettings(raw) {
@@ -71,6 +71,11 @@ export function configProblem(raw) {
71
71
  for (const [key, v] of Object.entries(k)) {
72
72
  if (!K.includes(key))
73
73
  return `k.${key} is not a K-parameter (${K.join(", ")})`;
74
+ if (key === "resumeSpillMs") {
75
+ if (v !== null && !(typeof v === "number" && Number.isFinite(v)))
76
+ return "k.resumeSpillMs must be a finite number of milliseconds or null";
77
+ continue;
78
+ }
74
79
  if (!count(v) || (key !== "lossBound" && key !== "spawnBudget" && v === 0))
75
80
  return `k.${key} must be a positive number`;
76
81
  }
@@ -37,6 +37,17 @@ export function openAsked(entries, call, qid, rev) {
37
37
  return items.some(e => e.item.rev === rev) && !items.some(e => e.item.rev > rev) &&
38
38
  !entries.some(e => e.type === JT.attentionResolved && e.id === id && e.rev === rev) && !supersededByBinding(entries, call, qid, rev);
39
39
  }
40
+ /** An answer already forwarded to any open question prevents a planned hibernation, even while its receipt is
41
+ * unconfirmed. Read this inside the serial section that commits the hibernation, never from a prior snapshot. */
42
+ export function answerInFlight(entries, call) {
43
+ return entries.some(e => {
44
+ if (e.type !== "forward" || e.dest !== call)
45
+ return false;
46
+ const env = e.envelope;
47
+ return env?.kind === "answer" && openAsked(entries, call, env.cond?.qid, env.cond?.rev) &&
48
+ !entries.some(r => r.type === "forward-retired" && r.rid2 === e.rid2);
49
+ });
50
+ }
40
51
  /** D2: qid@rev of `call` was superseded by a durable binding: an `answer-bound` names it in `superseded`. The binding is
41
52
  * the source of truth; the attention resolution `superseded` is derived from it (and may lag it across a crash). */
42
53
  export function supersededByBinding(entries, call, qid, rev) {
@@ -21,12 +21,12 @@ import { Outbox } from "../../kernel/mailbox.js";
21
21
  import { contentHash, forwardRid } from "../../kernel/ids.js";
22
22
  import { capacity, seal } from "../../kernel/guards.js";
23
23
  import { buildPiArgs } from "../../compat/pi-args.js";
24
- import { parseModel, plainModel, resolveModel } from "../../compat/model.js";
24
+ import { parseModel, plainModel, resolveModel, sameModel } from "../../compat/model.js";
25
25
  import { buildCallResult } from "../../compat/result.js";
26
26
  import createEffects from "./effects/index.js";
27
27
  import { continueSession } from "./generation.js";
28
- import { boundAnswer, hibernation, openAsked, openQuestion, supersededByBinding } from "./hibernate.js";
29
- import { SessionFold, answerKey, digestOpenQuestion } from "./digest.js";
28
+ import { answerInFlight, boundAnswer, hibernation, openAsked, openQuestion, supersededByBinding } from "./hibernate.js";
29
+ import { SessionFold, answerKey, digestOpenQuestion, supersededBy } from "./digest.js";
30
30
  import { emptyLedger, foldLedger, holdings as holdingsOf, settingsOf } from "../ledger.js";
31
31
  import { evidence, fatalProviderError, quotaExhausted, refusedByProvider, forgetSession, readSessionState, receiptId, sessionModel } from "./session.js";
32
32
  import { activeTotal } from "./time.js";
@@ -37,6 +37,7 @@ import { reached, sessionUsage, totalUsage } from "./usage.js";
37
37
  import { indexSweep, recordFenceFailure, resolveFenceAttention, serialContainment, skipLostCandidate, sweepExecutions } from "./sweep.js";
38
38
  import { gateRetired } from "./effects/gate.js";
39
39
  import { WorktreeIndex, worktreeCalls, worktreeLabel, worktreePair, worktreeRoots } from "./worktree.js";
40
+ import { failedModel, modelFailures, MODEL_RETRY_MS, parentPinned, spillCandidates } from "./pool.js";
40
41
  import { PENDING_NOTE, UNDELIVERED_FOLLOW_UP } from "../notes.js";
41
42
  const MEM_RECORD_MS = 30000;
42
43
  /** A4, P29: A child admitted within this window may not show in MemAvailable yet; its share is reserved explicitly. */
@@ -714,6 +715,8 @@ export default function createExecutor(ledgers, options = {}) {
714
715
  }
715
716
  async function acquireLoop(a, exec, decide, mine, writer) {
716
717
  let continuation = false;
718
+ let pinnedWait;
719
+ let waitMark = "";
717
720
  for (;;) {
718
721
  let signal;
719
722
  const changed = new Promise(resolve => { signal = resolve; waiters.add(resolve); });
@@ -724,10 +727,30 @@ export default function createExecutor(ledgers, options = {}) {
724
727
  return;
725
728
  if (writer && !await writerAdmit(a, writer))
726
729
  return;
727
- const decision = await decide(), models = decision.candidates, pool = decision.pool;
730
+ const decision = await decide(), pool = decision.pool;
731
+ let models = decision.candidates;
732
+ const pinned = decision.spill?.[0];
733
+ const full = (m) => holdings().filter(h => h.pool === m.provider).length >= (settings().providers?.[m.provider ?? ""]?.slots ?? Infinity);
734
+ if (pinned && full(pinned)) {
735
+ if (!sameModel(pinnedWait?.model, pinned))
736
+ pinnedWait = { model: pinned, since: Date.now() };
737
+ const ms = settings().k?.resumeSpillMs;
738
+ if (ms !== null && (ms ?? 120_000) >= 0 && Date.now() - pinnedWait.since >= (ms ?? 120_000))
739
+ models = [...models, ...spillCandidates(pinned, decision.spill)];
740
+ }
741
+ else
742
+ pinnedWait = undefined;
743
+ const mark = pinnedWait ? JSON.stringify(pinnedWait.model) : "";
744
+ if (mark !== waitMark) {
745
+ await a.ticket.journal.append("slot-wait", { call: a.ticket.callId, exec, ...(pinnedWait ? { model: plainModel(pinnedWait.model), since: pinnedWait.since, pool } : {}) });
746
+ waitMark = mark;
747
+ }
728
748
  continuation = decision.continuation;
729
749
  for (const model of models) {
730
- if (!continuation && pool && models.length > 1 && skipped(pool, model))
750
+ const spilling = !!pinned && !sameModel(model, pinned);
751
+ if (pool && (spilling || !continuation && models.length > 1) && skipped(pool, model))
752
+ continue;
753
+ if (failedModel(modelFailures(a.ticket.journal, a.ticket.callId), model))
731
754
  continue;
732
755
  // A pool entry with afterMs waits its turn: it is taken only once this acquisition has waited that long.
733
756
  if (model.afterMs !== undefined && Date.now() - mine.since < model.afterMs)
@@ -774,6 +797,10 @@ export default function createExecutor(ledgers, options = {}) {
774
797
  await orch.append("provider-probe", { provider, exec });
775
798
  }
776
799
  const plain = plainModel(model);
800
+ if (spilling && pinnedWait) {
801
+ continuation = false;
802
+ await a.ticket.journal.append("spilled", { call: a.ticket.callId, exec, pool, from: plainModel(pinned), to: plain, waitedMs: Date.now() - pinnedWait.since });
803
+ }
777
804
  await a.ticket.journal.append("selected", { exec, model: plain, ...(pool ? { pool } : {}) });
778
805
  return plain;
779
806
  }
@@ -807,25 +834,30 @@ export default function createExecutor(ledgers, options = {}) {
807
834
  const { defaultModel: configured, pools } = settings();
808
835
  const raw = t.spec.model ?? t.agent.model ?? configured ?? await defaultModel();
809
836
  const pool = raw && pools?.[raw] ? raw : undefined;
810
- const candidates = raw ? resolveModel(raw, pools) : [{ id: "" }];
811
- const candidate = recorded && candidates.some(m => m.provider === recorded.provider && m.id === recorded.id);
837
+ const failures = modelFailures(t.journal, t.callId);
838
+ const candidates = (raw ? resolveModel(raw, pools) : [{ id: "" }]).filter(m => !failedModel(failures, m));
839
+ if (!candidates.length)
840
+ throw new Error(`model-unavailable: no usable model remains; ${String(failures.at(-1)?.reason ?? raw)}`);
841
+ const matches = (m, other) => sameModel(m, other) || !!other && t.journal.entries().some(e => e.type === "model-ready" && sameModel(e.selected, m) && sameModel(e.model, other));
842
+ const candidate = recorded && candidates.some(m => matches(m, recorded));
812
843
  // Leave the session's model for the pool's others when its pool skips it after losses, or its provider's usage
813
844
  // window is used up; and at a new generation, go back to the pool's order of preference.
814
845
  // A new generation of a pool call starts from the pool also when the session's model is not one of its models
815
846
  // (switched outside it, or the follow-up named the pool).
816
- const skip = pool && (candidate ? previous && ownSegment && skipped(pool, recorded) || unavailable(recorded.provider) || !ownSegment && !!t.continueFrom
817
- : !ownSegment && !!t.continueFrom);
847
+ const skip = pool && (previous && has(t.journal, "model-unavailable", previous) || (candidate ? previous && ownSegment && skipped(pool, recorded) || unavailable(recorded.provider) || !ownSegment && !!t.continueFrom
848
+ : !ownSegment && !!t.continueFrom));
818
849
  // A model the call was asked to use replaces the session's: launched with it, and holding its provider's slot.
819
850
  const wanted = requestedModel(t.journal, t.callId, t.model);
820
851
  // It outranks the pool's order at a new generation too, also when it names the model the session already has.
821
852
  // A requested model of the call's own pool keeps the pool: a used-up window still moves the call on.
822
853
  const keep = pool && candidates.some(m => m.provider === wanted?.provider && m.id === wanted?.id) ? pool : undefined;
823
- if (wanted)
854
+ if (wanted && !failedModel(failures, wanted))
824
855
  return recorded && !freshFork && recorded.provider === wanted.provider && recorded.id === wanted.id
825
856
  ? { candidates: [recorded], continuation: true, pool: keep }
826
857
  : { candidates: [wanted], continuation: false, pool: keep };
827
- if (recorded && !freshFork && !skip)
828
- return { candidates: [recorded], continuation: true, pool: candidate ? pool : undefined };
858
+ if (recorded && !freshFork && !skip && !failedModel(failures, recorded))
859
+ return { candidates: [recorded], continuation: true, pool: candidate ? pool : undefined,
860
+ spill: candidate && pool && !parentPinned(t) ? [recorded, ...candidates.map(m => matches(m, recorded) ? { ...m, id: recorded.id } : m)] : undefined };
829
861
  return { candidates, continuation: false, pool };
830
862
  }
831
863
  /** Resolve a bound answer before it waits for admission; also repairs an interrupted append pair. Called serially. */
@@ -875,12 +907,53 @@ export default function createExecutor(ledgers, options = {}) {
875
907
  await resolveQuestion(journal, call, item.qid, item.rev, "carried");
876
908
  }
877
909
  }
910
+ /** Model identity receipts are durable before the observer fences an unavailable execution. Serial sections only. */
911
+ async function unavailableModel(journal, exec, selected, actual, reason) {
912
+ if (!has(journal, "model-unavailable", exec))
913
+ await journal.append("model-unavailable", { exec, selected, actual, reason: `selected ${selected.provider}/${selected.id}, pi would use ${actual.provider ?? "none"}/${actual.id}: ${reason}`, until: Date.now() + MODEL_RETRY_MS });
914
+ }
915
+ function allowedModels(journal, exec) {
916
+ const log = journal.entries(), selected = log.find(e => e.type === "selected" && e.exec === exec)?.model;
917
+ const models = selected ? [selected] : [];
918
+ for (const e of log) {
919
+ const envelope = e.envelope;
920
+ if (e.type !== "forward" || e.dest !== callOf(exec) || envelope?.kind !== "model")
921
+ continue;
922
+ if (log.some(r => r.type === "forward-delivered" && r.rid2 === e.rid2 && r.reason !== undefined))
923
+ continue;
924
+ if (log.some(r => r.type === "forward" && r.dest === e.dest && r.envelope?.kind === "withdraw" && r.envelope.body?.rids?.includes(String(e.rid2))))
925
+ continue;
926
+ const body = envelope.body;
927
+ if (body.exec && body.exec !== exec)
928
+ continue;
929
+ models.push({ provider: body.provider, id: body.model });
930
+ }
931
+ for (const e of log)
932
+ if (e.type === "model-ready" && e.exec === exec && models.some(m => sameModel(m, e.selected)))
933
+ models.push(e.model);
934
+ return models;
935
+ }
936
+ async function modelControl(journal, exec, event) {
937
+ if (event.exec !== exec)
938
+ return;
939
+ return serial(async () => {
940
+ if (event.type === CT.modelUnavailable) {
941
+ await unavailableModel(journal, exec, event.selected, event.actual, String(event.reason));
942
+ return false;
943
+ }
944
+ if (event.type === CT.modelReady && allowedModels(journal, exec).some(m => sameModel(m, event.selected)) &&
945
+ !journal.entries().some(e => e.type === "model-ready" && e.exec === exec && sameModel(e.selected, event.selected)))
946
+ await journal.append("model-ready", { exec, selected: event.selected, model: event.model, virtual: event.virtual === true });
947
+ return !has(journal, "model-unavailable", exec);
948
+ });
949
+ }
878
950
  /** The model each execution last answered with (`selected`, then `model-used`), cached per execution. */
879
951
  const inUse = new Map();
880
952
  async function switched(exec, journal, event) {
881
953
  const message = event.message, provider = message?.provider;
882
954
  if (!provider)
883
955
  return;
956
+ let accepted = true;
884
957
  await serial(async () => {
885
958
  // Evidence of the model in use: the provider and model of each assistant message, recorded when it changes.
886
959
  if (message.role === "assistant" && message.model) {
@@ -894,6 +967,13 @@ export default function createExecutor(ledgers, options = {}) {
894
967
  await journal.append("model-used", { exec, model: { provider, id: message.model } });
895
968
  inUse.set(exec, name);
896
969
  }
970
+ const virtual = journal.entries().findLast(e => e.type === "model-ready" && e.exec === exec)?.virtual === true;
971
+ if (!virtual && !allowedModels(journal, exec).some(m => sameModel(m, { provider, id: message.model }))) {
972
+ const selected = journal.entries().find(e => e.type === "selected" && e.exec === exec)?.model;
973
+ await unavailableModel(journal, exec, selected, { provider, id: message.model }, "child reported an unselected model");
974
+ accepted = false;
975
+ return;
976
+ }
897
977
  }
898
978
  const target = holdings().find(h => h.exec === exec && h.pool === provider && h.reserved);
899
979
  if (!target)
@@ -905,6 +985,7 @@ export default function createExecutor(ledgers, options = {}) {
905
985
  }
906
986
  });
907
987
  wake();
988
+ return accepted;
908
989
  }
909
990
  /** The model an execution last answered with, or was launched on. */
910
991
  function modelOf(journal, exec) {
@@ -1118,7 +1199,22 @@ export default function createExecutor(ledgers, options = {}) {
1118
1199
  bound = pendingAnswer;
1119
1200
  if (exec) {
1120
1201
  await fence(journal, exec, { park: a });
1121
- await questions(t, entries = await readCall(journal, t.callId));
1202
+ entries = await readCall(journal, t.callId);
1203
+ await serial(() => repairConsumedAnswers(journal, t.callId, entries));
1204
+ await questions(t, entries);
1205
+ bound ??= journal.entries().findLast(e => e.type === "answer-bound" && e.call === t.callId && e.reason === "answered-in-session");
1206
+ // A binding excuses only the execution it was bound to (the asker it ended) and the first launch after it while
1207
+ // that launch never started a child. Every later or started execution is judged by its own evidence, so a
1208
+ // child that dies before writing its exec marker counts toward lossBound instead of relaunching forever.
1209
+ if (bound) {
1210
+ const all = journal.entries(), execSeq = all.find(r => r.type === JT.exec && r.exec === exec).seq;
1211
+ const firstAfter = !all.some(r => r.type === JT.exec && r.call === t.callId && r.seq > bound.seq && r.seq < execSeq);
1212
+ if (!(bound.seq > execSeq || firstAfter && !has(journal, "tracked", exec) &&
1213
+ !digestOf(t.callId, entries).execAt.has(exec)))
1214
+ bound = undefined;
1215
+ }
1216
+ if (bound)
1217
+ await release(exec);
1122
1218
  // D6: after the fence the session is final. A bound answer it closed (answered, superseded, or re-asked as a newer
1123
1219
  // revision) is settled; if the session still has an open question of this call, the call does not launch: it
1124
1220
  // hibernates again on that question (its attention is open, so the parent is asked), and resumes only on a new
@@ -1142,8 +1238,18 @@ export default function createExecutor(ledgers, options = {}) {
1142
1238
  return finish(journal, t.callId, exec, makeResult("timeout"));
1143
1239
  if (ev.budget || reached(totalUsage(journal.entries(), t.callId), t.spec.budget))
1144
1240
  return finish(journal, t.callId, exec, makeResult("budget"));
1241
+ for (const e of entries)
1242
+ if (e.customType === CT.modelUnavailable && e.data?.exec === exec)
1243
+ await modelControl(journal, exec, { type: CT.modelUnavailable, ...e.data });
1244
+ const modelFailure = entriesOf(journal, "model-unavailable", exec).at(-1);
1245
+ if (modelFailure) {
1246
+ const selected = entriesOf(journal, "selected", exec).at(-1);
1247
+ if (!selected?.pool)
1248
+ return finish(journal, t.callId, exec, makeResult("failed", "", `model-unavailable: ${String(modelFailure.reason)}`));
1249
+ await release(exec);
1250
+ }
1145
1251
  // A child that never started (its launch failed for a reason of the environment) lost nothing: launch again.
1146
- if (!bound && !has(journal, "spawn-env-failed", exec)) {
1252
+ if (!bound && !modelFailure && !has(journal, "spawn-env-failed", exec)) {
1147
1253
  // P28: an execution cut off while its only unfinished tool call is the open question's `ask` (before it
1148
1254
  // hibernated) was waiting, not working: it hibernates now and resumes with the answer, like a planned
1149
1255
  // hibernation; it is neither a loss nor, for `once`, an unknown outcome.
@@ -1289,13 +1395,18 @@ export default function createExecutor(ledgers, options = {}) {
1289
1395
  return;
1290
1396
  await serial(async () => {
1291
1397
  const attention = entriesOf(journal, JT.attention).find(e => isEntry(e, JT.attention) && e.item.qid === q.qid && e.item.call === t.callId && e.item.rev === q.rev);
1292
- if (attention && Date.now() - attention.ts >= (config.k?.hibernateMs ?? 120000) && !has(journal, JT.fenced, exec) && hibernation(journal, t.callId)?.exec !== exec) {
1398
+ const all = journal.entries();
1399
+ if (attention && Date.now() - attention.ts >= (config.k?.hibernateMs ?? 120000) && !interrupted(a) && current(journal, t.callId) === exec &&
1400
+ openAsked(all, t.callId, q.qid, q.rev) && !answerInFlight(all, t.callId) &&
1401
+ !all.some(e => e.type === "answer-bound" && e.call === t.callId && e.qid === q.qid && e.rev === q.rev) &&
1402
+ !has(journal, JT.fenced, exec) && hibernation(journal, t.callId)?.exec !== exec) {
1293
1403
  await journal.append("hibernated", { call: t.callId, exec, qid: q.qid, rev: q.rev });
1294
1404
  a.wake();
1295
1405
  }
1296
1406
  });
1297
1407
  }, recordUsage: values => recordUsage(t, values), usage: entries => digestOf(t.callId, entries).usage,
1298
1408
  wrote: path => wrote(t, exec, cwd, path),
1409
+ modelControl: event => modelControl(journal, exec, event),
1299
1410
  switched: event => switched(exec, journal, event), answered: event => answered(t, exec, event), pendingSwitch: () => pendingSwitch(exec),
1300
1411
  });
1301
1412
  }
@@ -1306,14 +1417,57 @@ export default function createExecutor(ledgers, options = {}) {
1306
1417
  }
1307
1418
  }
1308
1419
  /**
1309
- * P28: an answer forwarded to the child while the question was still open but before the call hibernated (a restart
1310
- * or crash cut the asker off, or the planned hibernation fenced it first) never reached a live child. Once the call
1311
- * hibernates it is bound to the question like an answer given during hibernation; the forward is retired, so the
1312
- * reply "apply" already given (and any retry with the same rid) stays true.
1420
+ * P28: reconcile an answer forwarded before an interrupted asker hibernated. A consumed answer continues the
1421
+ * session; an unconsumed one binds like an answer given during hibernation and retires its original forward.
1422
+ * The reply "apply" already given (and any retry with the same rid) stays true.
1313
1423
  */
1314
1424
  async function adoptAnswer(journal, call, sleeping) {
1315
1425
  const entries = await readCall(journal, call);
1316
- await serial(() => adopt(journal, call, sleeping, entries));
1426
+ await serial(async () => { await repairConsumedAnswers(journal, call, entries); await adopt(journal, call, sleeping, entries); });
1427
+ }
1428
+ /** A fenced asker may have consumed its forwarded answer before the fence. Publish the binding first, then its
1429
+ * derived resolution and delivery: every prefix is repaired on retry/recovery. Never resend the answer; the next
1430
+ * execution uses a plain continue in the same session. Called serially, only after the current execution is fenced. */
1431
+ async function repairConsumedAnswers(journal, call, entries) {
1432
+ const exec = current(journal, call);
1433
+ if (!exec || !has(journal, JT.fenced, exec) || sealed(journal, call) || journal.entries().some(e => e.type === "retired" && e.call === call))
1434
+ return;
1435
+ const digest = digestOf(call, entries);
1436
+ for (const f of entriesOf(journal, "forward").filter(e => e.dest === call)) {
1437
+ const env = f.envelope, qid = env.cond?.qid, rev = env.cond?.rev;
1438
+ if (env.kind !== "answer" || !digest.questions.some(q => q.qid === qid && q.rev === rev) ||
1439
+ journal.entries().some(e => e.type === "forward-retired" && e.rid2 === f.rid2))
1440
+ continue;
1441
+ const receipt = digest.receipts.get(String(f.rid2)), details = receipt?.message?.details ?? receipt?.details;
1442
+ if (!receipt || details?.qid !== qid || details?.rev !== rev)
1443
+ continue;
1444
+ // The binding must not outlive the evidence it derives: fsync the native receipt before journal publication.
1445
+ await collectReceipts(call, [...entries]);
1446
+ const binding = journal.entries().find(e => e.type === "answer-bound" && e.call === call && e.qid === qid && e.rev === rev);
1447
+ // A normal settled turn needs no continuation, nor does an answer consumed in an earlier execution. A receipt
1448
+ // in this execution counts even if observation already resolved its attention before the fence.
1449
+ const sleeping = hibernation(journal, call), segment = digest.execAt.get(exec);
1450
+ const at = entries.indexOf(receipt), consumedHere = segment !== undefined && at > segment;
1451
+ // The execution stopped ON that ask: its result is the answer receipt and nothing ran after it (no report, no
1452
+ // question, no tool call, no finished assistant turn, no other unfinished tool). Otherwise the execution went on
1453
+ // working after the answer and its own evidence (report, once + dangling, loss) decides as usual.
1454
+ const after = entries.slice(at + 1);
1455
+ const stoppedOnAsk = consumedHere && receipt.message?.role === "toolResult" && receipt.message.toolName === "ask" &&
1456
+ !evidence([...entries], exec).dangling.length &&
1457
+ !after.some(e => e.type === "custom" && (e.customType === CT.report || e.customType === CT.question) ||
1458
+ e.message?.role === "assistant" && ((Array.isArray(e.message.content) && e.message.content.some(b => b.type === "toolCall")) ||
1459
+ (e.message.stopReason !== "aborted" && e.message.stopReason !== "error")));
1460
+ const superseded = supersededBy(details);
1461
+ const sleepingAnswered = sleeping?.exec === exec && (sleeping.qid === qid && sleeping.rev === rev ||
1462
+ superseded.some(q => q.qid === sleeping.qid && q.rev === sleeping.rev));
1463
+ if (!binding && (sleepingAnswered || stoppedOnAsk && !has(journal, "settled", exec)))
1464
+ await journal.append("answer-bound", { call, qid, rev, rid: f.rid, rid2: f.rid2, hash: f.hash, reason: "answered-in-session",
1465
+ ...(superseded.length ? { superseded } : {}) });
1466
+ await resolveBoundAnswer(journal, call, qid, rev);
1467
+ for (const q of superseded)
1468
+ await resolveQuestion(journal, call, q.qid, q.rev, "superseded");
1469
+ }
1470
+ await forwardsDelivered(journal, call, [...entries]);
1317
1471
  }
1318
1472
  /** The forward whose adoption was begun (its envelope withdrawn from the child's inbox) and not yet bound. */
1319
1473
  async function adoptionBegun(journal, call) {
@@ -1325,9 +1479,20 @@ export default function createExecutor(ledgers, options = {}) {
1325
1479
  * adoption was begun before a crash (its envelope is withdrawn, so it can reach the child only through this binding).
1326
1480
  * Called serially. */
1327
1481
  async function adopt(journal, call, sleeping, entries, onlyBegun = false) {
1328
- const all = journal.entries();
1329
- if (boundAnswer(all, sleeping))
1482
+ const all = journal.entries(), bound = boundAnswer(all, sleeping);
1483
+ if (bound) {
1484
+ // Repair an adoption cut off after its binding but before resolution/retirement. The original forward and
1485
+ // derived bound identity prove adoption; a consumed answer instead keeps its original delivered identity.
1486
+ await resolveBoundAnswer(journal, call, bound.qid, bound.rev);
1487
+ await resolveSuperseded(journal, call);
1488
+ const f = all.find(e => e.type === "forward" && e.dest === call && e.rid === bound.rid &&
1489
+ contentHash([String(e.rid2), "hibernated"]) === bound.rid2);
1490
+ if (f && !all.some(e => e.type === "forward-retired" && e.rid2 === f.rid2))
1491
+ await journal.append("forward-retired", { rid: f.rid, rid2: f.rid2, reason: "bound-to-hibernation" });
1492
+ if (f)
1493
+ await (await outbox).markResolved(String(f.rid2));
1330
1494
  return;
1495
+ }
1331
1496
  const begun = await adoptionBegun(journal, call);
1332
1497
  const receipts = new Set(entries.map(receiptId).filter(rid => rid !== undefined));
1333
1498
  // The answer to the question it hibernated on, else to another of its questions still open (an earlier one).
@@ -1425,6 +1590,14 @@ export default function createExecutor(ledgers, options = {}) {
1425
1590
  if (prior) {
1426
1591
  if (prior.hash !== hash)
1427
1592
  return { action: "reject", reason: "identity-conflict" };
1593
+ if (prior.envelope.kind === "answer") {
1594
+ await repairConsumedAnswers(ctx.journal, dest, await readCall(ctx.journal, dest));
1595
+ const exec = current(ctx.journal, dest);
1596
+ if (exec && has(ctx.journal, JT.fenced, exec)) {
1597
+ active.get(dest)?.wake();
1598
+ wake();
1599
+ }
1600
+ }
1428
1601
  if (!ctx.journal.entries().some(e => e.type === "forward-retired" && e.rid2 === prior.rid2))
1429
1602
  await replayForward(prior);
1430
1603
  return { action: "apply" };
@@ -1440,6 +1613,12 @@ export default function createExecutor(ledgers, options = {}) {
1440
1613
  return { action: "reject", reason: req.kind === "send" && req.body.kind === "answer" ? "retired" : "call-sealed" };
1441
1614
  if (req.kind === "send" && req.body.kind === "answer") {
1442
1615
  const sleeping = hibernation(ctx.journal, dest);
1616
+ await repairConsumedAnswers(ctx.journal, dest, await readCall(ctx.journal, dest));
1617
+ const exec = current(ctx.journal, dest);
1618
+ if (exec && has(ctx.journal, JT.fenced, exec)) {
1619
+ active.get(dest)?.wake();
1620
+ wake();
1621
+ }
1443
1622
  // An adoption begun before a crash (the earlier answer withdrawn from the inbox, not yet bound) binds first.
1444
1623
  if (sleeping && current(ctx.journal, dest) === sleeping.exec && !boundAnswer(ctx.journal.entries(), sleeping) && await adoptionBegun(ctx.journal, dest))
1445
1624
  await adopt(ctx.journal, dest, sleeping, await readCall(ctx.journal, dest), true);
@@ -1639,6 +1818,7 @@ export default function createExecutor(ledgers, options = {}) {
1639
1818
  for (const call of calls) {
1640
1819
  const session = await readCall(journal, call), values = sessionUsage(session, call);
1641
1820
  await serial(async () => {
1821
+ await repairConsumedAnswers(journal, call, session);
1642
1822
  await forwardsDelivered(journal, call, session);
1643
1823
  const recorded = new Set(journal.entries().filter(e => e.type === "usage" && e.call === call).map(e => e.id));
1644
1824
  for (const u of values)
@@ -5,7 +5,7 @@ import { join } from "node:path";
5
5
  import { stat as fileStat } from "node:fs/promises";
6
6
  import { performance } from "node:perf_hooks";
7
7
  import { createInterface } from "node:readline";
8
- import { JT, attentionEntries } from "../../types.js";
8
+ import { CT, JT, attentionEntries } from "../../types.js";
9
9
  import { callDir, callSession } from "../../paths.js";
10
10
  import { monotoneTime } from "../../kernel/guards.js";
11
11
  import { readSession } from "./session.js";
@@ -35,7 +35,7 @@ export async function observeExecution(d) {
35
35
  let size = (await fileStat(session).catch(() => ({ size: 0 }))).size, checkpoint = performance.now();
36
36
  let signal;
37
37
  const boundary = new Promise(resolve => { signal = resolve; d.setWake(resolve); });
38
- let failure, pending = Promise.resolve(), ending = false;
38
+ let failure, pending = Promise.resolve(), ending = false, modelBlocked = false;
39
39
  const has = (type) => entriesOf(t.journal, type, exec).length > 0;
40
40
  const enqueue = (fn) => { if (!ending)
41
41
  pending = pending.then(fn).catch(error => { failure = error; signal(); }); };
@@ -145,14 +145,26 @@ export async function observeExecution(d) {
145
145
  if (event.type === "message_update" || event.type === "tool_execution_update")
146
146
  return;
147
147
  enqueue(async () => {
148
+ if (modelBlocked)
149
+ return;
150
+ if (event.type === CT.modelReady || event.type === CT.modelUnavailable) {
151
+ if (await d.modelControl?.(event) === false) {
152
+ modelBlocked = true;
153
+ signal();
154
+ }
155
+ return;
156
+ }
157
+ if ((event.type === "message_start" || event.type === "message_end") && await d.switched(event) === false) {
158
+ modelBlocked = true;
159
+ signal();
160
+ return;
161
+ }
148
162
  const args = event.args;
149
163
  if (event.type === "tool_execution_start" && (event.toolName === "edit" || event.toolName === "write") && typeof args?.path === "string")
150
164
  await d.wrote?.(args.path);
151
165
  const slim = observation(event);
152
166
  if (slim) {
153
167
  await serial(() => t.journal.append("observation", { exec, event: slim }));
154
- if (event.type === "message_start")
155
- await d.switched(event);
156
168
  if (event.type === "message_end") {
157
169
  await d.recordUsage([{ id: String(slim.id), usage: slim.usage }]);
158
170
  await d.answered?.(event);
@@ -200,6 +212,15 @@ export async function observeExecution(d) {
200
212
  size = nextSize;
201
213
  }
202
214
  const entries = await (d.read ? d.read() : readSession(session));
215
+ for (const e of entries)
216
+ if (e.type === "custom" && (e.customType === CT.modelReady || e.customType === CT.modelUnavailable) && e.data?.exec === exec)
217
+ if (await d.modelControl?.({ type: e.customType, ...e.data }) === false) {
218
+ modelBlocked = true;
219
+ signal();
220
+ return;
221
+ }
222
+ if (modelBlocked)
223
+ return;
203
224
  await d.questions(entries);
204
225
  const values = d.usage ? d.usage(entries) : sessionUsage(entries, t.callId);
205
226
  if (values !== usageList) {
@@ -0,0 +1,39 @@
1
+ import { parseModel, sameModel } from "../../compat/model.js";
2
+ /** A parent model request keeps its pin after it was applied, including in continued generations. */
3
+ export function parentPinned(t) {
4
+ if (t.model)
5
+ return true;
6
+ const log = t.journal.entries(), calls = new Set([t.callId]);
7
+ if (t.continueFrom)
8
+ calls.add(t.continueFrom);
9
+ for (let i = log.length - 1; i >= 0; i--) {
10
+ const e = log[i];
11
+ if (e.type === "generation" && calls.has(`${t.wid}@${e.revision}/${e.key}@${e.gen}`)) {
12
+ if (typeof e.model === "string")
13
+ return true;
14
+ calls.add(String(e.from));
15
+ }
16
+ }
17
+ return log.some(e => {
18
+ if (e.type !== "forward" || !calls.has(String(e.dest)) || e.failover || e.envelope?.kind !== "model")
19
+ return false;
20
+ if (log.some(r => r.type === "forward-delivered" && r.rid2 === e.rid2 && r.reason !== undefined))
21
+ return false;
22
+ return !log.some(r => r.type === "forward" && r.dest === e.dest && r.envelope?.kind === "withdraw" &&
23
+ r.envelope.body?.rids?.includes(String(e.rid2)));
24
+ });
25
+ }
26
+ /** Other providers with the same id first, then pool order; admission still checks afterMs and slots. */
27
+ export function spillCandidates(pinned, candidates) {
28
+ const others = candidates.filter(m => m.provider !== pinned.provider);
29
+ const name = (m) => parseModel(m.id).id.split("/").at(-1).toLowerCase();
30
+ return [...others.filter(m => name(m) === name(pinned)), ...others.filter(m => name(m) !== name(pinned))];
31
+ }
32
+ export const MODEL_RETRY_MS = 600_000;
33
+ export function modelFailures(journal, call) {
34
+ const execs = new Set(journal.entries().filter(e => e.type === "exec" && e.call === call).map(e => e.exec));
35
+ return journal.entries().filter(e => e.type === "model-unavailable" && execs.has(e.exec));
36
+ }
37
+ export function failedModel(failures, model) {
38
+ return failures.some(e => sameModel(e.selected, model) && Number(e.until) > Date.now());
39
+ }
@@ -166,6 +166,10 @@ export function refusedByProvider(text) {
166
166
  export function sessionModel(entries) {
167
167
  // pi restores the model of the last model change or assistant message: a relaunch with `--model` on an existing
168
168
  // session records no model change, so only the answer tells which model the session went on with.
169
+ // Virtual answers name the routed physical model; only a later selection replaces the virtual one.
170
+ const selection = entries.findLast(e => e.type === "model_change" || e.type === "custom" && e.customType === CT.modelReady);
171
+ if (selection?.customType === CT.modelReady && selection.data?.virtual === true)
172
+ return selection.data.model;
169
173
  const last = entries.findLast(e => e.type === "model_change" && e.provider && e.modelId
170
174
  || e.type === "message" && e.message?.role === "assistant" && !!e.message.provider && !!e.message.model);
171
175
  if (!last)
@@ -8,6 +8,7 @@ import { crc32, forgetJournalSnapshot, forgetJournalSnapshotsIf, journalAppends,
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
+ import { resolveModel } from "../compat/model.js";
11
12
  import {} from "./ledger.js";
12
13
  import { readerHold, readerLedger, readerLedgerIdentity } from "./reader-ledger.js";
13
14
  import { packageVersion } from "../version.js";
@@ -16,6 +17,20 @@ import { leaseCalls, leaseLines, leaseState } from "../platform/lease.js";
16
17
  import { labelsOf } from "../events/derive.js";
17
18
  import { PENDING_NOTE, generationRids, UNDELIVERED_FOLLOW_UP } from "./notes.js";
18
19
  import { readStats } from "./stats.js";
20
+ export function answerForwardedNote(c, now = Date.now()) {
21
+ const answer = c.answerForwarded;
22
+ return answer && now - answer.at >= 30_000 ? `answer forwarded ${age(now - answer.at)} ago, not delivered` : "";
23
+ }
24
+ const modelName = (m) => { const v = m; return v.provider ? `${v.provider}/${v.id}` : v.id; };
25
+ const modelStatus = (c) => Object.fromEntries(Object.entries(c).filter(([key]) => ["routedModel", "modelMismatch", "modelUnavailable", "poolWait", "spill"].includes(key)));
26
+ /** Scheduling and model identity facts shared by detailed and compact text status. */
27
+ export function modelStatusText(c, now = Date.now()) {
28
+ const w = c.poolWait, s = c.spill, m = c.modelMismatch;
29
+ return (w ? ` (queued ${age(now - w.since)} on ${w.model.split("/")[0]} (full)${w.free.length ? `; pool has free slots: ${w.free.join(", ")}` : ""})` : "") +
30
+ (s ? ` (spilled after ${age(s.waitedMs)}: ${s.from.split("/")[0]} full -> ${s.to})` : "") +
31
+ (c.routedModel ? ` (routed ${c.routedModel})` : "") +
32
+ (m ? ` (used ${m.used}, selected ${m.selected})` : "") + (c.modelUnavailable ? ` (model-unavailable: ${c.modelUnavailable})` : "");
33
+ }
19
34
  /** A workflow has live work: it runs, or follow-ups opened on it after it finished have not ended yet. */
20
35
  export function isLive(wf) {
21
36
  return wf.status === "running" || (wf.followUps ?? 0) > 0;
@@ -141,6 +156,9 @@ function snapshotReducer(wid, entries) {
141
156
  // An execution waits for a provider slot and memory before it launches; it is running once `selected` says so
142
157
  // (otherwise a call still waiting for a slot reads "thinking · 2m").
143
158
  call.exec = String(e.exec);
159
+ delete call.poolWait;
160
+ delete call.usedModel;
161
+ delete call.virtualModel;
144
162
  call.phase = "queued";
145
163
  call.startedAt ??= e.ts;
146
164
  call.lastActivity = e.ts;
@@ -150,6 +168,32 @@ function snapshotReducer(wid, entries) {
150
168
  hibernating.delete(call.callId);
151
169
  }
152
170
  }
171
+ else if (e.type === "slot-wait") {
172
+ const call = byExec.get(String(e.exec));
173
+ if (call && call.exec === e.exec) {
174
+ if (e.model)
175
+ call.poolWait = { since: Number(e.since), model: modelName(e.model), ...(typeof e.pool === "string" ? { pool: e.pool } : {}), free: [] };
176
+ else
177
+ delete call.poolWait;
178
+ }
179
+ }
180
+ else if (e.type === "spilled") {
181
+ const call = byExec.get(String(e.exec));
182
+ if (call)
183
+ call.spill = { from: modelName(e.from), to: modelName(e.to), waitedMs: Number(e.waitedMs) };
184
+ }
185
+ else if (e.type === "model-unavailable") {
186
+ const call = byExec.get(String(e.exec));
187
+ if (call)
188
+ call.modelUnavailable = String(e.reason);
189
+ }
190
+ else if (e.type === "model-ready") {
191
+ const call = byExec.get(String(e.exec));
192
+ if (call && call.exec === e.exec) {
193
+ call.selectedModel = modelName(e.model);
194
+ call.virtualModel = e.virtual === true;
195
+ }
196
+ }
153
197
  else if (e.type === "writer-wait" || e.type === "writer-acquired") {
154
198
  const call = calls.get(String(e.call)), holder = String(e.holder ?? "");
155
199
  if (call && e.type === "writer-wait")
@@ -198,8 +242,13 @@ function snapshotReducer(wid, entries) {
198
242
  }
199
243
  else if (e.type === "selected") {
200
244
  const call = byExec.get(String(e.exec)), m = e.model;
201
- if (call && m)
245
+ if (call && call.exec === e.exec && m) {
202
246
  call.model = m.provider ? `${m.provider}/${m.id}` : m.id;
247
+ call.selectedModel = call.model;
248
+ delete call.poolWait;
249
+ delete call.usedModel;
250
+ delete call.virtualModel;
251
+ }
203
252
  if (call && call.exec === e.exec && call.phase === "queued") {
204
253
  call.phase = "running";
205
254
  delete call.answered;
@@ -210,14 +259,21 @@ function snapshotReducer(wid, entries) {
210
259
  else if (e.type === "model-used") {
211
260
  // Evidence of a switch: the execution answered with another model than it launched with.
212
261
  const call = byExec.get(String(e.exec)), m = e.model;
213
- if (call && m)
262
+ if (call && call.exec === e.exec && m) {
214
263
  call.model = m.provider ? `${m.provider}/${m.id}` : m.id;
264
+ call.usedModel = call.model;
265
+ if (sends.get(call.callId)?.some(s => s.kind === "model" && !s.reason && s.model?.toLowerCase() === call.model?.toLowerCase()))
266
+ call.selectedModel = call.model;
267
+ }
215
268
  }
216
269
  else if (e.type === "observation") {
217
270
  // Only what the agent did counts as activity; tracker scans and time checkpoints are bookkeeping.
218
271
  const call = byExec.get(String(e.exec));
219
272
  if (call)
220
273
  call.lastActivity = e.ts;
274
+ const event = e.event;
275
+ if (call && call.exec === e.exec && event?.type === "message_start" && event.provider && event.model)
276
+ call.usedModel = `${event.provider}/${event.model}`;
221
277
  if (call && e.type === "observation" && e.event?.type === "tool_execution_start")
222
278
  tools.set(call.callId, (tools.get(call.callId) ?? 0) + 1);
223
279
  }
@@ -245,6 +301,7 @@ function snapshotReducer(wid, entries) {
245
301
  delete call.answered;
246
302
  delete call.hibernated;
247
303
  delete call.writerWait;
304
+ delete call.poolWait;
248
305
  hibernating.delete(call.callId);
249
306
  }
250
307
  else if (isEntry(e, JT.attention)) {
@@ -254,7 +311,9 @@ function snapshotReducer(wid, entries) {
254
311
  else if (e.type === "forward") {
255
312
  const envelope = e.envelope;
256
313
  const send = { rid: String(e.rid), kind: String(envelope?.kind ?? ""), state: "pending", at: e.ts,
257
- ...(envelope?.kind === "model" && envelope.body?.provider ? { model: `${envelope.body.provider}/${envelope.body.model}` } : {}) };
314
+ ...(envelope?.kind === "model" && envelope.body?.provider ? { model: `${envelope.body.provider}/${envelope.body.model}` } : {}),
315
+ ...(envelope?.kind === "answer" && typeof envelope.cond?.qid === "string" && typeof envelope.cond.rev === "number"
316
+ ? { question: { qid: envelope.cond.qid, rev: envelope.cond.rev } } : {}) };
258
317
  const list = sends.get(String(e.dest)) ?? [];
259
318
  list.push(send);
260
319
  sends.set(String(e.dest), list);
@@ -302,6 +361,8 @@ function snapshotReducer(wid, entries) {
302
361
  const usageOf = (callId) => sealedUsage.get(callId) ?? live.get(callId);
303
362
  const counts = { queued: 0, running: 0, asking: 0, sealed: 0 };
304
363
  for (const c of list) {
364
+ if (c.phase !== "sealed" && c.phase !== "queued")
365
+ delete c.poolWait;
305
366
  counts[c.phase]++;
306
367
  const usage = usageOf(c.callId);
307
368
  if (usage)
@@ -315,12 +376,21 @@ function snapshotReducer(wid, entries) {
315
376
  const pending = forwarded.filter(pendingMessage).length;
316
377
  if (pending)
317
378
  c.pending = pending;
379
+ const answer = c.phase === "asking" && forwarded.find(s => s.kind === "answer" && s.state === "pending" && s.question &&
380
+ openAttention.some(a => a.call === c.callId && a.qid === s.question.qid && a.rev === s.question.rev));
381
+ if (answer)
382
+ c.answerForwarded = { rid: answer.rid, ...answer.question, at: answer.at };
318
383
  const last = c.phase !== "sealed" && !retired.has(c.callId) ? forwarded.findLast(s => s.kind === "model" && s.reason !== "withdrawn" && s.reason !== "stale-execution") : undefined;
319
384
  if (last?.reason !== undefined)
320
385
  c.switchFailed = `${last.model} (${last.reason})`;
321
- else if (last && last.state !== "retired" && last.model !== c.model?.replace(/:(off|minimal|low|medium|high|xhigh|max)$/, ""))
386
+ else if (last && last.state !== "retired" && last.model !== (c.virtualModel ? c.selectedModel : c.model)?.replace(/:(off|minimal|low|medium|high|xhigh|max)$/, ""))
322
387
  c.switching = last.model;
323
388
  }
389
+ const selected = c.switching ?? c.selectedModel;
390
+ if (c.usedModel && c.virtualModel)
391
+ c.routedModel = c.usedModel;
392
+ else if (c.usedModel && selected && c.usedModel.toLowerCase() !== selected.toLowerCase())
393
+ c.modelMismatch = { used: c.usedModel, selected };
324
394
  }
325
395
  for (const [key, rids] of notes) {
326
396
  const n = [...rids].filter(rid => !carried.has(rid)).length, call = list.findLast(c => c.key === key);
@@ -362,7 +432,8 @@ const FOLDS = 256; // workflows whose fold state is kept; pruned and long-idle o
362
432
  const folds = new Map();
363
433
  const derived = new WeakMap();
364
434
  export function workflowSnapshot(home, wid, ledger) {
365
- const wf = workflowDigest(home, wid, ledger).snapshot;
435
+ const base = workflowDigest(home, wid, ledger).snapshot;
436
+ const wf = base.calls.some(c => c.poolWait) ? withPoolSlots(base, readerLedger(home).state.state) : base;
366
437
  const planned = plannedTotal(home, wid, wf.rev);
367
438
  return planned === undefined ? wf : { ...wf, planned };
368
439
  }
@@ -785,6 +856,31 @@ export function labelsText(labels, width = 60) {
785
856
  return text ? `[${clip(text, Math.max(1, width - 3))}]` : "";
786
857
  }
787
858
  const decorated = new WeakMap();
859
+ /** Free slots are live ledger state, not repeated workflow journal records. */
860
+ function withPoolSlots(wf, state) {
861
+ if (!wf.calls.some(c => c.poolWait))
862
+ return wf;
863
+ const held = new Map();
864
+ for (const h of state.held.values())
865
+ held.set(h.pool, (held.get(h.pool) ?? 0) + 1);
866
+ const pools = state.config?.settings.pools, limits = state.config?.settings.providers;
867
+ return { ...wf, calls: wf.calls.map(c => {
868
+ const wait = c.poolWait;
869
+ if (!wait)
870
+ return c;
871
+ let providers = [];
872
+ if (wait.pool && pools?.[wait.pool]) {
873
+ try {
874
+ providers = resolveModel(wait.pool, pools).map(m => m.provider).filter((p) => !!p);
875
+ }
876
+ catch { /* A removed or invalid pool has no available entries to show. */ }
877
+ }
878
+ const pinned = wait.model.split("/")[0];
879
+ const free = [...new Set(providers)].filter(p => p !== pinned && (held.get(p) ?? 0) < (limits?.[p]?.slots ?? Infinity) &&
880
+ !(state.exhausted.get(p)?.nextTry && state.exhausted.get(p).nextTry > Date.now()));
881
+ return { ...c, poolWait: { ...wait, free } };
882
+ }) };
883
+ }
788
884
  /** P25: Snapshot every workflow under DSA_HOME (newest first by wid, which is a ULID); `paused` marks work a drain holds. */
789
885
  export function allWorkflows(home) {
790
886
  return snapshotsOf(home, workflowIds(home));
@@ -796,11 +892,13 @@ function snapshotWithLedger(home, wid, ix, mark) {
796
892
  const pendingRevision = (ix.revisions.get(wid) ?? 0) > (digests.get(pathsOf(home, wid).journal)?.digest.snapshot.rev ?? 0);
797
893
  const base = workflowDigest(home, wid, pendingRevision ? undefined : mark).snapshot, planned = plannedTotal(home, wid, base.rev), l = ix.labels.get(wid), s = ix.sessions.get(wid);
798
894
  const paused = isLive(base) && !!readerHold(ix, wid, ix.created.get(wid)?.origin), hit = decorated.get(base);
799
- if (hit && hit.planned === planned && hit.labels === l && hit.session === s && hit.paused === paused)
895
+ const slotMark = base.calls.some(c => c.poolWait) ? `${mark}:${[...ix.state.exhausted.values()].map(x => x.nextTry > Date.now()).join(",")}` : undefined;
896
+ if (hit && hit.planned === planned && hit.labels === l && hit.session === s && hit.paused === paused && hit.slotMark === slotMark)
800
897
  return hit.wf;
801
- const planned1 = planned === undefined ? base : { ...base, planned }, labelled1 = labelled(planned1, l, s);
898
+ const live = withPoolSlots(base, ix.state);
899
+ const planned1 = planned === undefined ? live : { ...live, planned }, labelled1 = labelled(planned1, l, s);
802
900
  const wf = paused ? { ...labelled1, paused: true } : labelled1;
803
- decorated.set(base, { planned, labels: l, session: s, paused, wf });
901
+ decorated.set(base, { planned, labels: l, session: s, paused, slotMark, wf });
804
902
  return wf;
805
903
  }
806
904
  function snapshotsOf(home, wids) {
@@ -911,11 +1009,11 @@ export function compactWorkflow(wf, leases) {
911
1009
  ...(wf.planned !== undefined ? { planned: wf.planned } : {}), done: progress.done,
912
1010
  calls: wf.calls.map(c => {
913
1011
  const r = c.result, last = r?.output?.split("\n").map(l => l.trim()).filter(Boolean).at(-1);
914
- return { key: c.key, gen: c.gen, callId: c.callId, phase: c.phase, ...(r ? { status: r.status, ok: r.ok } : {}),
1012
+ return { key: c.key, gen: c.gen, callId: c.callId, phase: c.phase, ...modelStatus(c), ...(r ? { status: r.status, ok: r.ok } : {}),
915
1013
  ...(c.sharedWorktree ? { sharedWorktree: c.sharedWorktree } : {}),
916
1014
  ...(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 } : {}),
917
1015
  ...(last ? { lastLine: clip(last, 200) } : {}), ...(r?.error ? { error: clip(r.error, 300) } : {}), ...(c.hibernated ? { hibernated: true } : {}),
918
- ...(c.answered ? { answered: c.answered } : {}), ...(c.writerWait && !r ? { writerWait: c.writerWait } : {}), ...(!r && leases?.get(c.callId) ? { lease: leases.get(c.callId) } : {}),
1016
+ ...(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) } : {}),
919
1017
  ...(c.notesPending ? { notesPending: c.notesPending } : {}) };
920
1018
  }),
921
1019
  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 } : {}) })),
@@ -1097,13 +1195,13 @@ export function statusBrief(home, options = {}) {
1097
1195
  const p = progressOf(w), open = w.attention.filter(a => a.kind !== "finished");
1098
1196
  const calls = latestCalls(w).filter(c => c.phase !== "sealed" || (c.result && !c.result.ok) || c.notesPending).map((c) => {
1099
1197
  const live = c.phase !== "sealed", quiet = c.lastActivity !== undefined ? now - c.lastActivity : undefined;
1100
- return { key: c.key, agent: c.agent, phase: c.phase, ...(c.model ? { model: c.model } : {}),
1198
+ return { key: c.key, agent: c.agent, phase: c.phase, ...modelStatus(c), ...(c.model ? { model: c.model } : {}),
1101
1199
  ...(c.sharedWorktree ? { sharedWorktree: c.sharedWorktree } : {}),
1102
1200
  ...(live && c.startedAt !== undefined ? { for: age(now - c.startedAt) } : {}),
1103
1201
  ...(live && c.phase !== "asking" && quiet !== undefined && quiet >= 60_000 ? { quiet: age(quiet) } : {}),
1104
1202
  ...(live && c.startedAt !== undefined ? { tokens: tokens(c.usage) } : {}),
1105
1203
  ...(c.result ? { status: c.result.status, ...(c.result.error ? { error: clip(c.result.error, 200) } : {}) } : {}),
1106
- ...(c.hibernated ? { hibernated: true } : {}), ...(c.answered ? { answered: c.answered } : {}), ...(live && c.writerWait ? { writerWait: c.writerWait } : {}),
1204
+ ...(c.hibernated ? { hibernated: true } : {}), ...(c.answered ? { answered: c.answered } : {}), ...(c.answerForwarded ? { answerForwarded: c.answerForwarded } : {}), ...(live && c.writerWait ? { writerWait: c.writerWait } : {}),
1107
1205
  ...(live && byCall.get(c.callId) ? { lease: byCall.get(c.callId) } : {}),
1108
1206
  ...(live && c.switching ? { switching: c.switching } : {}), ...(live && c.switchFailed ? { switchFailed: c.switchFailed } : {}),
1109
1207
  ...(c.notesPending ? { notesPending: c.notesPending } : {}) };
package/dist/types.js CHANGED
@@ -22,6 +22,8 @@ export const CT = {
22
22
  withdrawn: "dsa-withdrawn", // custom: { rid, rids } — tombstones AND the withdraw request's receipt (rebuild: withdrawn{rids} + applied{rid})
23
23
  question: "dsa-question", // custom: { qid, rev, question }
24
24
  report: "dsa-report", // custom: { exec, outcome, data?, artifacts? }
25
+ modelReady: "dsa-model-ready", // custom: { exec, selected, model, virtual } - canonical model activated before delivery
26
+ modelUnavailable: "dsa-model-unavailable", // custom: { exec, selected, actual, reason } - no request may follow
25
27
  model: "dsa-model", // custom: { rid, provider, model } — model change receipt
26
28
  attention: "dsa-attention", // custom_message (main session): details { items: {id, rev}[] }
27
29
  budget: "dsa-budget", // custom: { exec, usage } — the child refused its next provider request: per-call budget reached (P31b)
package/dist/ui/view.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
2
- import { isLive, labelsText, liveCalls, ownedBy, progressOf } from "../orchestrator/snapshot.js";
2
+ import { answerForwardedNote, isLive, labelsText, liveCalls, ownedBy, progressOf } from "../orchestrator/snapshot.js";
3
3
  import { oneLine } from "./frame.js";
4
4
  /** UI §2: Render compact wall-clock durations; never present these as charged active time. */
5
5
  export function duration(ms) {
@@ -121,7 +121,7 @@ export function statusPhrase(call, workflow, facts, now) {
121
121
  return resultPhrase(call);
122
122
  const question = workflow.attention.find(a => a.kind === "question" && a.call === call.callId);
123
123
  if (question)
124
- return `asking main agent: ${question.text}`;
124
+ return answerForwardedNote(call, now) || `asking main agent: ${question.text}`;
125
125
  const noProgress = workflow.attention.find(a => a.kind === "stall" && a.call === call.callId && a.id.startsWith("noprogress:"));
126
126
  // The alert's duration measures progress, whereas lastActivity also advances on provider retries.
127
127
  if (noProgress)
@@ -234,7 +234,7 @@ export function dockLines(workflows, facts, name, width, now = Date.now(), rows
234
234
  // A running tool is activity; otherwise a minute without new evidence (no message, no tool) stops the spinner.
235
235
  const f = facts.get(c.callId), fresh = Boolean(f?.activity) || now - Math.max(c.lastActivity ?? 0, f?.lastActivity ?? 0, c.startedAt ?? 0) < 60_000;
236
236
  const mark = asking ? "?" : c.phase === "queued" ? "·" : fresh ? SPIN[Math.floor(now / 500) % SPIN.length] : "…";
237
- const phrase = asking ? `asks: ${w.attention.find(a => a.kind === "question" && a.call === c.callId).text}` : statusPhrase(c, w, f, now);
237
+ const phrase = answerForwardedNote(c, now) || (asking ? `asks: ${w.attention.find(a => a.kind === "question" && a.call === c.callId).text}` : statusPhrase(c, w, f, now));
238
238
  return rowText(`${mark} `, callName(w, c), name(f?.model ?? c.model), phrase, [], width, cols);
239
239
  });
240
240
  const more = active.length - shown.length;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-durable-subagents",
3
- "version": "1.0.40",
3
+ "version": "1.0.41",
4
4
  "description": "Subagents for pi that never lose work and never do it twice. Crash-safe workflows, automatic recovery, and a live view just like the main agent.",
5
5
  "type": "module",
6
6
  "license": "MIT",