pi-durable-subagents 1.0.40 → 1.0.42

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,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 { parseModel, 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 || c.phase === "queued") ? withLedgerFacts(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,107 @@ 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
+ /** The orchestrator that is still recovering the home's workflows: its start entry says it recovers first, it has not
860
+ * recorded `recovered` and its process lives. Undefined for an orchestrator that does not say so (older versions). */
861
+ export function orchestratorStarting(state) {
862
+ const o = state.orchestrator;
863
+ if (!o?.recovery || o.recovered || o.exited)
864
+ return undefined;
865
+ // Readers ask on every refresh; the process check is kept for a second per start entry.
866
+ const now = Date.now(), hit = startingChecks.get(o);
867
+ const alive = hit && now >= hit.at && now - hit.at < 1000 ? hit.alive : processAlive(o.pid, o.start);
868
+ if (!hit || hit.alive !== alive || now < hit.at || now - hit.at >= 1000)
869
+ startingChecks.set(o, { at: now, alive });
870
+ return alive ? { pid: o.pid, since: o.ts } : undefined;
871
+ }
872
+ const startingChecks = new WeakMap();
873
+ /** A queued call's wait as one phrase: "orchestrator starting (12s)", "waiting for a free slot (p 2/2)", ... */
874
+ export function queuedText(w, now = Date.now(), span = age) {
875
+ return w.reason === "starting" ? `orchestrator starting (${span(now - (w.since ?? now))})` : w.detail;
876
+ }
877
+ const providerOf = (model) => { try {
878
+ return parseModel(model).provider;
879
+ }
880
+ catch {
881
+ return undefined;
882
+ } };
883
+ /** Why a queued call waits, from what the orchestrator ledger records (precedence as events/waiting.ts): the
884
+ * orchestrator still recovering; every candidate provider used up and not admitted now; the writer lock of its worktree;
885
+ * every candidate provider full. Undefined when none is known: a call is never said to wait for a slot without a full
886
+ * provider (memory headroom and an admission in progress look the same from here). Candidates: the provider it waits
887
+ * for to resume on, else those of the model or pool it asked for (else the configured default). */
888
+ export function queueWait(c, state, now = Date.now(), starting = orchestratorStarting(state)) {
889
+ if (c.phase !== "queued")
890
+ return undefined;
891
+ if (starting)
892
+ return { reason: "starting", detail: "orchestrator starting", since: starting.since };
893
+ const settings = state.config?.settings ?? {}, pools = settings.pools ?? {}, wanted = c.poolWait?.model ?? c.model ?? settings.defaultModel;
894
+ let providers = [];
895
+ if (wanted && Object.hasOwn(pools, wanted)) {
896
+ try {
897
+ providers = [...new Set(resolveModel(wanted, pools).map(m => m.provider).filter((p) => !!p))];
898
+ }
899
+ catch { /* an invalid pool: unknown */ }
900
+ }
901
+ else if (wanted) {
902
+ const p = providerOf(wanted);
903
+ if (p)
904
+ providers = [p];
905
+ }
906
+ const used = providers.map(p => [p, state.exhausted.get(p)]);
907
+ if (used.length && used.every(([, x]) => x && (now < x.nextTry || x.probe !== undefined)))
908
+ return { reason: "provider-exhausted", detail: `${providers.join(", ")} usage window${providers.length > 1 ? "s" : ""} used up` };
909
+ if (c.writerWait)
910
+ return { reason: "writer-lock", detail: `waiting for the writer lock of ${c.writerWait.root}` };
911
+ if (!providers.length)
912
+ return undefined;
913
+ let full = true;
914
+ const lines = providers.map(p => {
915
+ let held = 0;
916
+ for (const h of state.held.values())
917
+ if (h.pool === p)
918
+ held++;
919
+ const limit = settings.providers?.[p]?.slots;
920
+ if (limit === undefined || held < limit)
921
+ full = false;
922
+ return slotLine(p, held, limit);
923
+ });
924
+ return full ? { reason: "slot", detail: `waiting for a free slot (${lines.join(", ")})` } : undefined;
925
+ }
926
+ /** A mark of the ledger facts a workflow's queued calls show: they are derived again when it changes. */
927
+ function queueMark(wf, state, mark) {
928
+ if (!wf.calls.some(c => c.poolWait || c.phase === "queued"))
929
+ return undefined;
930
+ return `${mark}:${[...state.exhausted.values()].map(x => x.nextTry > Date.now()).join(",")}:${orchestratorStarting(state)?.since ?? ""}`;
931
+ }
932
+ /** Free slots and why queued calls wait are live ledger state, not repeated workflow journal records. */
933
+ function withLedgerFacts(wf, state) {
934
+ if (!wf.calls.some(c => c.poolWait || c.phase === "queued"))
935
+ return wf;
936
+ const held = new Map(), now = Date.now(), starting = orchestratorStarting(state);
937
+ for (const h of state.held.values())
938
+ held.set(h.pool, (held.get(h.pool) ?? 0) + 1);
939
+ const pools = state.config?.settings.pools, limits = state.config?.settings.providers;
940
+ return { ...wf, calls: wf.calls.map(c => {
941
+ const why = queueWait(c, state, now, starting);
942
+ if (why)
943
+ c = { ...c, queuedFor: why };
944
+ const wait = c.poolWait;
945
+ if (!wait)
946
+ return c;
947
+ let providers = [];
948
+ if (wait.pool && pools?.[wait.pool]) {
949
+ try {
950
+ providers = resolveModel(wait.pool, pools).map(m => m.provider).filter((p) => !!p);
951
+ }
952
+ catch { /* A removed or invalid pool has no available entries to show. */ }
953
+ }
954
+ const pinned = wait.model.split("/")[0];
955
+ const free = [...new Set(providers)].filter(p => p !== pinned && (held.get(p) ?? 0) < (limits?.[p]?.slots ?? Infinity) &&
956
+ !(state.exhausted.get(p)?.nextTry && state.exhausted.get(p).nextTry > Date.now()));
957
+ return { ...c, poolWait: { ...wait, free } };
958
+ }) };
959
+ }
788
960
  /** P25: Snapshot every workflow under DSA_HOME (newest first by wid, which is a ULID); `paused` marks work a drain holds. */
789
961
  export function allWorkflows(home) {
790
962
  return snapshotsOf(home, workflowIds(home));
@@ -796,11 +968,13 @@ function snapshotWithLedger(home, wid, ix, mark) {
796
968
  const pendingRevision = (ix.revisions.get(wid) ?? 0) > (digests.get(pathsOf(home, wid).journal)?.digest.snapshot.rev ?? 0);
797
969
  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
970
  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)
971
+ const slotMark = queueMark(base, ix.state, mark);
972
+ if (hit && hit.planned === planned && hit.labels === l && hit.session === s && hit.paused === paused && hit.slotMark === slotMark)
800
973
  return hit.wf;
801
- const planned1 = planned === undefined ? base : { ...base, planned }, labelled1 = labelled(planned1, l, s);
974
+ const live = withLedgerFacts(base, ix.state);
975
+ const planned1 = planned === undefined ? live : { ...live, planned }, labelled1 = labelled(planned1, l, s);
802
976
  const wf = paused ? { ...labelled1, paused: true } : labelled1;
803
- decorated.set(base, { planned, labels: l, session: s, paused, wf });
977
+ decorated.set(base, { planned, labels: l, session: s, paused, slotMark, wf });
804
978
  return wf;
805
979
  }
806
980
  function snapshotsOf(home, wids) {
@@ -911,12 +1085,12 @@ export function compactWorkflow(wf, leases) {
911
1085
  ...(wf.planned !== undefined ? { planned: wf.planned } : {}), done: progress.done,
912
1086
  calls: wf.calls.map(c => {
913
1087
  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 } : {}),
1088
+ return { key: c.key, gen: c.gen, callId: c.callId, phase: c.phase, ...modelStatus(c), ...(r ? { status: r.status, ok: r.ok } : {}),
915
1089
  ...(c.sharedWorktree ? { sharedWorktree: c.sharedWorktree } : {}),
916
1090
  ...(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
1091
  ...(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) } : {}),
919
- ...(c.notesPending ? { notesPending: c.notesPending } : {}) };
1092
+ ...(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) } : {}),
1093
+ ...(c.notesPending ? { notesPending: c.notesPending } : {}), ...(c.queuedFor && !r && !wf.paused ? { queued: queuedText(c.queuedFor) } : {}) };
920
1094
  }),
921
1095
  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 } : {}) })),
922
1096
  ...(wf.paused ? { paused: true } : {}), ...(wf.followUps ? { followUps: wf.followUps } : {}), ...(wf.labels ? { labels: wf.labels } : {}),
@@ -980,7 +1154,9 @@ export function orchestratorView(state, loaded = packageVersion(), now = Date.no
980
1154
  return {};
981
1155
  const r = o.forceRestart, note = r && now - r.ts < 24 * 60 * 60_000
982
1156
  ? `; restarted by force ${age(now - r.ts)} ago by ${initiatorSummary(r.initiator, r.from)}: ${restartLine(r.reason ?? "no reason recorded")}` : "";
983
- return { orchestrator: `${o.version} (pid ${o.pid})${note}`, ...(o.version === loaded ? {} : { versionNote: versionNote(o.version, loaded) }) };
1157
+ // Still recovering the home's workflows: nothing is dispatched yet, whatever the slots say.
1158
+ const starting = orchestratorStarting(state), phase = starting ? `, starting ${age(now - starting.since)}` : "";
1159
+ return { orchestrator: `${o.version} (pid ${o.pid}${phase})${note}`, ...(o.version === loaded ? {} : { versionNote: versionNote(o.version, loaded) }) };
984
1160
  }
985
1161
  /** Whether the recorded orchestrator still runs. On Linux its start time also tells it from a later process given the
986
1162
  * same pid after a crash (elsewhere the pid alone is checked). */
@@ -1097,16 +1273,16 @@ export function statusBrief(home, options = {}) {
1097
1273
  const p = progressOf(w), open = w.attention.filter(a => a.kind !== "finished");
1098
1274
  const calls = latestCalls(w).filter(c => c.phase !== "sealed" || (c.result && !c.result.ok) || c.notesPending).map((c) => {
1099
1275
  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 } : {}),
1276
+ return { key: c.key, agent: c.agent, phase: c.phase, ...modelStatus(c), ...(c.model ? { model: c.model } : {}),
1101
1277
  ...(c.sharedWorktree ? { sharedWorktree: c.sharedWorktree } : {}),
1102
1278
  ...(live && c.startedAt !== undefined ? { for: age(now - c.startedAt) } : {}),
1103
1279
  ...(live && c.phase !== "asking" && quiet !== undefined && quiet >= 60_000 ? { quiet: age(quiet) } : {}),
1104
1280
  ...(live && c.startedAt !== undefined ? { tokens: tokens(c.usage) } : {}),
1105
1281
  ...(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 } : {}),
1282
+ ...(c.hibernated ? { hibernated: true } : {}), ...(c.answered ? { answered: c.answered } : {}), ...(c.answerForwarded ? { answerForwarded: c.answerForwarded } : {}), ...(live && c.writerWait ? { writerWait: c.writerWait } : {}),
1107
1283
  ...(live && byCall.get(c.callId) ? { lease: byCall.get(c.callId) } : {}),
1108
1284
  ...(live && c.switching ? { switching: c.switching } : {}), ...(live && c.switchFailed ? { switchFailed: c.switchFailed } : {}),
1109
- ...(c.notesPending ? { notesPending: c.notesPending } : {}) };
1285
+ ...(c.notesPending ? { notesPending: c.notesPending } : {}), ...(live && c.queuedFor && !w.paused ? { queued: queuedText(c.queuedFor, now) } : {}) };
1110
1286
  });
1111
1287
  const asking = open.filter(a => a.kind === "question" && a.call).map(a => ({ to: `${w.wid}/${callKey(a.call)}`, ...(a.qid ? { qid: a.qid } : {}),
1112
1288
  ...(w.calls.some(c => c.callId === a.call && c.hibernated) ? { hibernated: true } : {}), question: clip(a.text, 300) }));
@@ -13,7 +13,8 @@ import { discoverAgents } from "../compat/agents.js";
13
13
  import { parseFrontmatter } from "../compat/frontmatter.js";
14
14
  import { compileFanout } from "../compat/fanout.js";
15
15
  import { contentHash, ulid } from "../kernel/ids.js";
16
- import { openJournal, syncDirectory } from "../kernel/journal.js";
16
+ import { openJournal, openLazyJournal, syncDirectory } from "../kernel/journal.js";
17
+ import { readSettled, settledPath } from "./settled.js";
17
18
  import { publishFile } from "../kernel/mailbox.js";
18
19
  import { digestDir, factsDir, journalPath, pinnedDir, workflowDir } from "../paths.js";
19
20
  import { JT } from "../types.js";
@@ -185,7 +186,40 @@ export class Store {
185
186
  /** Called after each append to a workflow journal (the event pump derives from it). */
186
187
  appended;
187
188
  ledgers;
189
+ /** Terminal workflows materialized from their `pins.json` without verifying it: the revision and the intent to verify
190
+ * it with (see ready). */
191
+ unverified = new Map();
192
+ verifying = new Map();
193
+ /** What the store looks up in the orchestrator ledger, folded over appended entries only (first entry wins, as find). */
194
+ ix = { seen: 0, pruned: new Set(), created: new Set(), createIntents: [], createByRid: new Map(),
195
+ createByWid: new Map(), reviseByRid: new Map(), rids: new Map() };
188
196
  constructor(ledgers) { this.ledgers = ledgers; }
197
+ index() {
198
+ const ix = this.ix, entries = this.ledgers.orch.committed?.() ?? this.ledgers.orch.entries();
199
+ while (ix.seen < entries.length) {
200
+ const e = entries[ix.seen++];
201
+ if (e.type === 'pruned')
202
+ ix.pruned.add(String(e.wid));
203
+ else if (e.type === JT.created)
204
+ ix.created.add(String(e.rid));
205
+ else if (e.type === 'create-intent' || e.type === 'revise-intent') {
206
+ const byRid = e.type === 'create-intent' ? ix.createByRid : ix.reviseByRid, rid = String(e.rid), wid = String(e.wid);
207
+ if (e.type === 'create-intent') {
208
+ ix.createIntents.push(e);
209
+ if (!ix.createByWid.has(wid))
210
+ ix.createByWid.set(wid, e);
211
+ }
212
+ if (!byRid.has(rid))
213
+ byRid.set(rid, e);
214
+ const rids = ix.rids.get(wid);
215
+ if (rids)
216
+ rids.push(rid);
217
+ else
218
+ ix.rids.set(wid, [rid]);
219
+ }
220
+ }
221
+ return ix;
222
+ }
189
223
  stagePath(rid) {
190
224
  if (!rid || rid === '.' || rid === '..')
191
225
  throw new Error('Invalid staging identity');
@@ -215,6 +249,7 @@ export class Store {
215
249
  const change = req.body, wf = this.workflows.get(change?.wid);
216
250
  if (!wf)
217
251
  throw new Error('unknown-workflow');
252
+ await this.ready(wf);
218
253
  body = { cwd: wf.cwd, ...(change.workflow !== undefined ? { workflow: change.workflow } : { source: change.source ?? wf.pins.source }),
219
254
  args: Object.hasOwn(change, 'args') ? change.args : wf.pins.args, inputs: wf.pins.inputSources,
220
255
  usageBudget: wf.pins.usageBudget, maxCalls: wf.pins.maxCalls };
@@ -295,7 +330,8 @@ export class Store {
295
330
  }
296
331
  /** P3, P6: Remove staging only after a durable rejection or withdrawal without a committed intent. */
297
332
  async discardStage(rid) {
298
- if (this.ledgers.orch.entries().some(e => (e.type === 'create-intent' || e.type === 'revise-intent') && e.rid === rid))
333
+ const ix = this.index();
334
+ if (ix.createByRid.has(rid) || ix.reviseByRid.has(rid))
299
335
  return;
300
336
  await rm(this.stagePath(rid), { recursive: true, force: true });
301
337
  await syncDirectory(join(this.ledgers.home, 'staging')).catch(error => { if (error.code !== 'ENOENT')
@@ -303,14 +339,14 @@ export class Store {
303
339
  }
304
340
  /** A5: Fix the workflow identity and snapshot reference before filesystem effects. */
305
341
  async create(req) {
306
- let intent = this.ledgers.orch.entries().find(e => e.type === 'create-intent' && e.rid === req.rid);
342
+ let intent = this.index().createByRid.get(req.rid);
307
343
  intent ??= await this.ledgers.orch.append('create-intent', { rid: req.rid, wid: ulid(), origin: req.from, cwd: req.body.cwd,
308
344
  ...(req.body.name !== undefined ? { name: req.body.name } : {}), snapshot: await this.reference(req.rid) });
309
345
  return this.materialize(intent);
310
346
  }
311
347
  /** P14, A5: Bind the next revision before retiring any old authority. */
312
348
  async revisionIntent(req, wf) {
313
- return this.ledgers.orch.entries().find(e => e.type === 'revise-intent' && e.rid === req.rid) ??
349
+ return this.index().reviseByRid.get(req.rid) ??
314
350
  await this.ledgers.orch.append('revise-intent', { rid: req.rid, wid: wf.wid, revision: wf.revision + 1, snapshot: await this.reference(req.rid) });
315
351
  }
316
352
  async publishPins(wid, revision, pins) {
@@ -344,11 +380,11 @@ export class Store {
344
380
  * workflow), and use it only when it is well formed, names this snapshot, its pins hash to its digest and every file
345
381
  * hashes as recorded — otherwise they take the snapshot path, whose byte comparison reports a changed file as a
346
382
  * conflict, and record it again. */
347
- async pinnedFiles(wid, revision, intent) {
383
+ async pinnedFiles(wid, revision, intent, verify = true) {
348
384
  const dir = revision === 1 ? pinnedDir(this.ledgers.home, wid) : join(pinnedDir(this.ledgers.home, wid), `r${revision}`);
349
385
  const ref = intent.pins ? undefined : intent.snapshot;
350
386
  if (ref) {
351
- const files = await this.recorded(dir, ref.hash).catch(() => undefined);
387
+ const files = await this.recorded(dir, ref.hash, verify).catch(() => undefined);
352
388
  if (files)
353
389
  return files;
354
390
  }
@@ -363,20 +399,22 @@ export class Store {
363
399
  }
364
400
  return files;
365
401
  }
366
- /** The files `pins.json` in `dir` records for snapshot `hash`, when the record and every file verify; else undefined. */
367
- async recorded(dir, hash) {
402
+ /** The files `pins.json` in `dir` records for snapshot `hash`, when the record and every file verify; else undefined.
403
+ * Without `verify`, only the record's form is checked (its digest and the file hashes are left to `ready`). */
404
+ async recorded(dir, hash, verify = true) {
368
405
  const { digest, ...body } = JSON.parse(await readFile(join(dir, 'pins.json'), 'utf8'));
369
406
  // The digest covers everything the record decides (pins, input names → files, origin, file hashes).
370
- if (body.snapshot !== hash || typeof digest !== 'string' || contentHash(body) !== digest)
407
+ if (body.snapshot !== hash || typeof digest !== 'string' || (verify && contentHash(body) !== digest))
371
408
  return undefined;
372
409
  if (!body.pins || typeof body.pins !== 'object' || !body.inputs || typeof body.inputs !== 'object' || !body.files || typeof body.files !== 'object')
373
410
  return undefined;
374
411
  const names = publishedFiles(Object.values(body.inputs).map(String), body.origin === true);
375
412
  if (names.length !== Object.keys(body.files).length || names.some(name => !Object.hasOwn(body.files, name)))
376
413
  return undefined;
377
- for (const name of names)
378
- if (body.files[name] !== await fileHash(join(dir, name)))
379
- return undefined;
414
+ if (verify)
415
+ for (const name of names)
416
+ if (body.files[name] !== await fileHash(join(dir, name)))
417
+ return undefined;
380
418
  return { pins: body.pins, scriptPath: join(dir, 'script.js'), inputs: Object.fromEntries(Object.entries(body.inputs).map(([name, file]) => [name, join(dir, String(file))])),
381
419
  originPath: body.origin === true ? join(dir, 'origin.jsonl') : undefined };
382
420
  }
@@ -388,20 +426,49 @@ export class Store {
388
426
  const revision = Number(intent.revision), files = await this.pinnedFiles(wf.wid, revision, intent);
389
427
  await wf.journal.append('revised', { rid: intent.rid, revision, snapshot: intent.snapshot });
390
428
  Object.assign(wf, files, { revision });
429
+ this.unverified.delete(wf.wid);
391
430
  }
431
+ /** A1: Verify the pinned files of a workflow materialized unverified (a terminal one) before its script, inputs, origin
432
+ * or pins are used again: the record's digest and every file's hash, else the snapshot path (which republishes a
433
+ * missing file and refuses a changed one). Nothing evaluates from a file that does not hash as recorded. Idempotent;
434
+ * a refusal is raised again by every later call. */
435
+ async ready(wf) {
436
+ if (!this.unverified.has(wf.wid))
437
+ return;
438
+ let run = this.verifying.get(wf.wid);
439
+ if (!run) {
440
+ run = (async () => {
441
+ const pending = this.unverified.get(wf.wid);
442
+ if (!pending)
443
+ return;
444
+ const files = pending.revision === wf.revision ? await this.pinnedFiles(wf.wid, pending.revision, pending.intent) : undefined;
445
+ if (this.unverified.get(wf.wid) !== pending)
446
+ return; // A revision published meanwhile was verified by revise.
447
+ if (files && pending.revision === wf.revision)
448
+ Object.assign(wf, files);
449
+ this.unverified.delete(wf.wid);
450
+ })().finally(() => this.verifying.delete(wf.wid));
451
+ this.verifying.set(wf.wid, run);
452
+ }
453
+ await run;
454
+ }
455
+ /** Whether a workflow's pinned files were verified in this process (see ready). */
456
+ verified(wid) { return !this.unverified.has(wid); }
392
457
  /** P32: Rebuild a historical ticket from that revision's immutable snapshot. */
393
458
  async atRevision(wf, revision) {
394
- if (revision === wf.revision)
459
+ if (revision === wf.revision) {
460
+ await this.ready(wf);
395
461
  return wf;
462
+ }
396
463
  const intent = revision === 1
397
- ? this.ledgers.orch.entries().find(e => e.type === 'create-intent' && e.wid === wf.wid)
464
+ ? this.index().createByWid.get(wf.wid)
398
465
  : wf.journal.entries().find(e => e.type === 'revised' && e.revision === revision);
399
466
  if (!intent)
400
467
  throw new Error(`Missing pinned revision: ${wf.wid}@${revision}`);
401
468
  return { ...wf, revision, ...await this.pinnedFiles(wf.wid, revision, intent) };
402
469
  }
403
470
  /** A1, housekeeping: Wids with a committed pruned entry; they are gone and never materialize again. */
404
- pruned() { return new Set(this.ledgers.orch.entries().filter(e => e.type === 'pruned').map(e => String(e.wid))); }
471
+ pruned() { return this.index().pruned; }
405
472
  /** Housekeeping: Bytes a prune of `wid` frees: its workflow directory and the staging dirs of its requests. */
406
473
  async footprint(wid) {
407
474
  let total = await diskUsage(workflowDir(this.ledgers.home, wid));
@@ -410,7 +477,7 @@ export class Store {
410
477
  return total;
411
478
  }
412
479
  stagedRids(wid) {
413
- return this.ledgers.orch.entries().filter(e => (e.type === 'create-intent' || e.type === 'revise-intent') && e.wid === wid).map(e => String(e.rid));
480
+ return [...this.index().rids.get(wid) ?? []];
414
481
  }
415
482
  /** A1, A2: Retire a pruned workflow's handle after its pruned entry is committed; nothing appends to it again. */
416
483
  async drop(wid) {
@@ -429,6 +496,7 @@ export class Store {
429
496
  throw error; });
430
497
  // Readers' caches of it (derived, never authoritative: no sync needed).
431
498
  await rm(join(digestDir(this.ledgers.home), `${wid}.json`), { force: true });
499
+ await rm(settledPath(this.ledgers.home, wid), { force: true });
432
500
  const cached = await readdir(digestDir(this.ledgers.home)).catch(error => { if (error.code !== 'ENOENT')
433
501
  throw error; return []; });
434
502
  for (const name of cached)
@@ -448,28 +516,69 @@ export class Store {
448
516
  console.error(`durable-subagents: removal of pruned workflow ${wid} failed, retrying at next start: ${String(error)}`);
449
517
  }
450
518
  }
451
- for (const intent of this.ledgers.orch.entries().filter(e => e.type === 'create-intent'))
519
+ for (const intent of [...this.index().createIntents])
452
520
  if (!pruned.has(String(intent.wid)))
453
521
  await this.materialize(intent);
454
522
  }
523
+ /** A1: A workflow that already ended (its journal's current revision is terminal) is materialized from its pinned
524
+ * files' record without verifying them (see ready): a start does not hash the pinned files of finished history. */
455
525
  async materialize(intent) {
456
526
  const wid = intent.wid, existing = this.workflows.get(wid);
457
527
  if (existing)
458
528
  return existing;
459
529
  if (this.pruned().has(wid))
460
530
  throw new Error(`Workflow ${wid} was pruned`);
461
- const files = await this.pinnedFiles(wid, 1, intent);
462
- const journal = await openJournal(journalPath(this.ledgers.home, wid));
531
+ const path = journalPath(this.ledgers.home, wid);
532
+ // A settled workflow (settled.ts) whose journal is still what its record describes opens without decoding it.
533
+ const settled = readSettled(this.ledgers.home, wid), lazy = settled && await openLazyJournal(path, settled.journal);
534
+ if (settled && lazy) {
535
+ try {
536
+ const current = settled.revised ?? intent, files = await this.pinnedFiles(wid, settled.revision, current, false);
537
+ const facts = { revision: settled.revision, ...(settled.revised ? { revised: settled.revised } : {}), done: settled.done, resumed: settled.resumed, quiet: settled.quiet, calls: settled.calls, sweep: settled.sweep };
538
+ const wf = { wid, revision: settled.revision, origin: intent.origin, cwd: intent.cwd, journal: lazy, ...files, settled: facts };
539
+ this.unverified.set(wid, { revision: settled.revision, intent: current });
540
+ lazy.onAppend = () => this.appended?.(wid);
541
+ this.workflows.set(wid, wf);
542
+ if (!this.index().created.has(String(intent.rid)))
543
+ await this.ledgers.orch.append(JT.created, { rid: intent.rid, wid, origin: intent.origin });
544
+ return wf;
545
+ }
546
+ catch (error) {
547
+ this.workflows.delete(wid);
548
+ this.unverified.delete(wid);
549
+ await lazy.close();
550
+ throw error;
551
+ }
552
+ }
553
+ // A new workflow publishes its pins before its journal exists (a failed publication leaves no journal).
554
+ const fresh = await stat(path).then(() => false, error => { if (error.code === 'ENOENT')
555
+ return true; throw error; });
556
+ const first = fresh ? await this.pinnedFiles(wid, 1, intent) : undefined;
557
+ const journal = await openJournal(path);
558
+ let wf;
559
+ try {
560
+ const entries = journal.entries(), revised = entries.findLast(e => e.type === 'revised');
561
+ const revision = revised ? Number(revised.revision) : 1, current = revised ?? intent;
562
+ // terminalEntry over the whole journal: a `revised` after the last done supersedes it, as in the revision's view.
563
+ const ended = !first && entries.length > 0 && terminalEntry(entries) !== undefined;
564
+ const files = first ?? (ended ? await this.pinnedFiles(wid, revision, current, false) : await this.pinnedFiles(wid, 1, intent));
565
+ wf = { wid, revision: ended ? revision : 1, origin: intent.origin, cwd: intent.cwd, journal, ...files };
566
+ if (ended)
567
+ this.unverified.set(wid, { revision, intent: current });
568
+ }
569
+ catch (error) {
570
+ await journal.close();
571
+ throw error;
572
+ }
463
573
  journal.onAppend = () => this.appended?.(wid);
464
- const wf = { wid, revision: 1, origin: intent.origin, cwd: intent.cwd, journal, ...files };
465
574
  this.workflows.set(wid, wf);
466
575
  if (!journal.entries().length)
467
576
  await journal.append('wf-created', { rid: intent.rid, origin: intent.origin, cwd: intent.cwd, revision: 1,
468
577
  ...(intent.name !== undefined ? { name: intent.name } : {}) });
469
578
  const revised = journal.entries().findLast(e => e.type === 'revised');
470
- if (revised)
579
+ if (revised && wf.revision !== Number(revised.revision))
471
580
  Object.assign(wf, await this.pinnedFiles(wid, Number(revised.revision), revised), { revision: Number(revised.revision) });
472
- if (!this.ledgers.orch.entries().some(e => e.type === JT.created && e.rid === intent.rid))
581
+ if (!this.index().created.has(String(intent.rid)))
473
582
  await this.ledgers.orch.append(JT.created, { rid: intent.rid, wid, origin: intent.origin });
474
583
  return wf;
475
584
  }
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)