pi-durable-subagents 1.0.39 → 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,58 @@
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
+
32
+ ## 1.0.40
33
+
34
+ - Readers keep rebuildable digests of settled workflows and facts of final calls in `DSA_HOME/cache`, keyed by
35
+ journal or session identity and the deriving code. Prune removes these cache entries with their workflow.
36
+
37
+ - A pi session uses these digests for its own workflows, keeps unchanged workflow objects, and releases settled
38
+ journals and fold state after each pass. An unchanged ledger permits at most five seconds without journal IO;
39
+ a ledger change forces a check, and turn boundaries check immediately for late attention. Final call facts release
40
+ their transcripts and recheck session identity within
41
+ five seconds. Concurrent cache writes are atomic, checked, and cannot recreate a pruned workflow's cache.
42
+ - Pi readers fold the ledger's committed prefix in bounded chunks into compact per-home state, without retaining
43
+ decoded history. Replacement and truncation rebuild it. Unchanged passes skip the workflow directory scan and
44
+ reuse settled results and the ordered UI view by identity; the dock and open list do not request redundant renders.
45
+ Incomplete creation or revision intents and unsettled workflows are still checked on the next pass.
46
+ - Workflows with pending undelivered follow-ups or unfinished recovery bookkeeping are not settled. Recovery-only
47
+ follow-ups therefore appear on the next poll, even without a new ledger entry. Missing completion notices, pending
48
+ forwards, fences, gates, successful worktree cleanup and retired questions also prevent the trust window.
49
+ - `scripts/bench-ui.ts` uses a temporary cache and reports steady RSS and live heap after history release. `--cache-home`
50
+ reuses caches for a second run; `node --expose-gc` collects released history before and after steady-state polling.
51
+ - Measured against 1.0.39 on a home with 1,530 workflows, for a session owning 197 of them (load 1.3, warm cache): a
52
+ steady refresh fell from 9.0 ms to 2.7 ms (p50), the steady RSS from 345 MiB to 145 MiB with a 26 MiB live heap, the
53
+ first refresh from 1.2 s to 0.4 s and the session-start notice from 0.71 s to 0.12 s. With an empty cache the first
54
+ refresh is unchanged (1.2 s) and the RSS stays near 300 MiB until the allocator returns memory.
55
+
3
56
  ## 1.0.39
4
57
 
5
58
  - A pi session reads only its own workflows. Since 1.0.30 the UI shows only the workflows of its session, yet the pi
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
@@ -584,7 +588,21 @@ an orchestrator runs, a pi session does not look for pending work at all;
584
588
  without one, it looks until it finds the first unfinished workflow and keeps
585
589
  none of the journals it read. `node scripts/bench-ui.ts --owner=main:<pi
586
590
  session id>` measures what a session pays on its main thread for a given
587
- `DSA_HOME` (read-only).
591
+ `DSA_HOME` (read-only). The measurement uses a temporary cache; pass
592
+ `--cache-home=<temporary directory>` to reuse it across runs, and run with
593
+ `node --expose-gc` to measure RSS after released history is collected.
594
+
595
+ Readers keep digests of settled workflows and facts of final calls in
596
+ `DSA_HOME/cache`. These are rebuildable: deleting the cache costs one slower
597
+ read. Digests are keyed by journal identity and reducer code; final facts by
598
+ call seal, session identity and deriving code. A settled journal is released
599
+ after each pass. Polling skips its journal IO while the ledger stays unchanged,
600
+ for at most five seconds. Turn boundaries check immediately for late attention.
601
+ Ledger changes force a journal check;
602
+ final sessions are also rechecked within five seconds. Only an explicitly
603
+ opened final call keeps its transcript. Prune removes the workflow's caches.
604
+ `DSA_CACHE_HOME=<directory>` places the derived cache under that directory
605
+ instead of `DSA_HOME`, without changing where authoritative data is read.
588
606
 
589
607
  ### Where the orchestrator starts
590
608
 
@@ -731,6 +749,24 @@ State lives in `~/.pi/durable-subagents`; set `DSA_HOME` to move it.
731
749
  session's model or was asked for a model, and a running call that moves off
732
750
  a used-up provider skips such entries, as does a model send that names the
733
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).
734
770
  - **A used-up provider** is not sent new calls until its next try, 15 minutes
735
771
  after it last refused (`"k": { "probeMs": 900000 }`). Then one call at a
736
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);
@@ -1,56 +1,65 @@
1
- import { closeSync, openSync, readdirSync, readSync, statSync } from "node:fs";
1
+ import { closeSync, openSync, readSync, statSync } from "node:fs";
2
2
  import { StringDecoder } from "node:string_decoder";
3
3
  import { join } from "node:path";
4
- import { readJournalSnapshot, readJournalUncached } from "../../kernel/journal.js";
5
- import { journalPath, orchLedger } from "../../paths.js";
6
- import { CT, JT, attentionEntries } from "../../types.js";
7
- import { holdOf, ledgerIndex } from "../../orchestrator/snapshot.js";
8
- /** P15, P25: Read workflow snapshots without modifying another domain's history; a wid with an orchestrator.jsonl
9
- * `pruned{wid}` entry is gone (housekeeping), even while its directory is still being removed. */
10
- export function workflows(home, origin) {
11
- const ledger = readJournalSnapshot(orchLedger(home)), { created: createdBy, pruned } = ledgerIndex(ledger);
12
- let names;
13
- try {
14
- names = readdirSync(join(home, "w"));
4
+ import { forgetJournalSnapshot, journalAppends, readJournalSnapshot, readJournalUncached } from "../../kernel/journal.js";
5
+ import { journalPath } from "../../paths.js";
6
+ import { CT, JT } from "../../types.js";
7
+ import { openGeneration, readerWorkflowListing, releaseLoadedSettledJournals, releaseSettledJournals, SETTLED_RECHECK_MS, unresolvedAttention, workflowDigest, workflowDigestChecked } from "../../orchestrator/snapshot.js";
8
+ import { readerHold, readerLedgerIdentity } from "../../orchestrator/reader-ledger.js";
9
+ const passes = new Map();
10
+ export function workflows(home, origin, fresh = false) {
11
+ const { record, names, checked: listed } = readerWorkflowListing(home, fresh), ix = record.state, mark = readerLedgerIdentity(record), now = Date.now();
12
+ let byOrigin = passes.get(home);
13
+ if (!byOrigin)
14
+ passes.set(home, byOrigin = new Map());
15
+ const prior = byOrigin.get(origin), current = !fresh && prior && prior.names === names && !prior.retryUnknown && prior.mark === mark && prior.appends === journalAppends() && now >= prior.checked && now - prior.checked < SETTLED_RECHECK_MS;
16
+ if (current && !prior.pending.length) {
17
+ releaseLoadedSettledJournals();
18
+ return prior.result;
15
19
  }
16
- catch (error) {
17
- if (error.code !== "ENOENT")
18
- throw error;
19
- names = [];
20
+ const ids = current ? prior.ids : [...new Set([...[...ix.created.keys()].map(String), ...names].filter(wid => !ix.pruned.has(wid)))].sort()
21
+ .filter(wid => origin === undefined || !ix.created.has(wid) || ix.created.get(wid)?.origin === origin);
22
+ const digests = new Map(current ? prior.digests : []), old = new Map(prior?.result.map(w => [w.wid, w])), changes = new Map();
23
+ try {
24
+ for (const wid of current ? prior.pending : ids) {
25
+ const pendingRevision = (ix.revisions.get(wid) ?? 0) > (prior?.digests.get(wid)?.snapshot.rev ?? 0);
26
+ const known = ix.created.get(wid), digest = workflowDigest(home, wid, fresh || pendingRevision ? undefined : mark), path = journalPath(home, wid);
27
+ const from = known ? known.origin : readJournalUncached(path)?.entries.find(e => e.type === JT.created)?.origin;
28
+ if (origin !== undefined && from !== origin) {
29
+ old.delete(wid);
30
+ digests.set(wid, digest);
31
+ continue;
32
+ }
33
+ if (prior?.digests.get(wid) === digest && old.get(wid)?.origin === from) {
34
+ digests.set(wid, digest);
35
+ continue;
36
+ }
37
+ digests.set(wid, digest);
38
+ changes.set(wid, { wid, origin: from, ...(digest.settled ? { settled: digest.settled } : {}), get entries() {
39
+ const entries = readJournalSnapshot(path);
40
+ if (digest.settled)
41
+ forgetJournalSnapshot(path);
42
+ return entries;
43
+ } });
44
+ }
45
+ const result = ids.map(wid => changes.get(wid) ?? old.get(wid)).filter((w) => !!w);
46
+ const same = prior && prior.result.length === result.length && result.every((w, i) => w === prior.result[i]);
47
+ // Digest reuse and another reader's listing refresh cannot extend this pass's trust window.
48
+ let checked = current ? prior.checked : Math.min(now, listed);
49
+ const pending = ids.filter(wid => {
50
+ const d = digests.get(wid);
51
+ if (d?.settled)
52
+ checked = Math.min(checked, workflowDigestChecked(home, wid));
53
+ return !d?.settled || (ix.revisions.get(wid) ?? 0) > d.snapshot.rev;
54
+ });
55
+ byOrigin.set(origin, { mark, checked, appends: journalAppends(), names, retryUnknown: ids.some(wid => !ix.created.has(wid)), ids, pending, digests, result: same ? prior.result : result });
56
+ return same ? prior.result : result;
20
57
  }
21
- const ids = new Set([...[...createdBy.keys()].map(String), ...names].filter(wid => !pruned.has(wid)));
22
- const result = [];
23
- for (const wid of [...ids].sort()) {
24
- // With an origin wanted, a workflow the ledger attributes to another session is skipped without reading its journal.
25
- const known = createdBy.get(wid);
26
- if (origin !== undefined && known && known.origin !== origin)
27
- continue;
28
- const entries = readJournalSnapshot(journalPath(home, wid));
29
- const created = known ?? entries.find(e => e.type === JT.created);
30
- if (origin !== undefined && created?.origin !== origin)
31
- continue;
32
- result.push({ wid, origin: created?.origin, entries });
58
+ finally {
59
+ releaseSettledJournals();
33
60
  }
34
- return result;
35
- }
36
- /** P37: a generation opened by a send (possibly after the workflow finished) that has no seal yet is pending work. */
37
- const opened = new WeakMap();
38
- export function openGeneration(entries) {
39
- const hit = opened.get(entries);
40
- if (hit?.length === entries.length)
41
- return hit.open;
42
- // Sealed call ids end in `/<key>@<gen>`; collect every such suffix once instead of rescanning per generation.
43
- const sealed = new Set();
44
- for (const s of entries)
45
- if (s.type === JT.sealed) {
46
- const call = String(s.call);
47
- for (let i = call.indexOf("/"); i >= 0; i = call.indexOf("/", i + 1))
48
- sealed.add(call.slice(i));
49
- }
50
- const open = entries.some(g => g.type === "generation" && !sealed.has(`/${String(g.key)}@${String(g.gen)}`));
51
- opened.set(entries, { length: entries.length, open });
52
- return open;
53
61
  }
62
+ export { openGeneration };
54
63
  /** Whether one journal is unfinished, by file identity: a journal that has not changed is not read again. */
55
64
  const decided = new Map();
56
65
  function unfinishedJournal(path, known) {
@@ -82,29 +91,20 @@ function unfinishedJournal(path, known) {
82
91
  * unless a drain (stop-all) holds it: held work waits for an explicit resume, which starts the orchestrator itself.
83
92
  * Stops at the first unfinished workflow (newest first); a held workflow the ledger attributes is skipped without
84
93
  * reading its journal, and an unchanged journal is not read again. */
85
- export function unfinishedWorkflow(home) {
86
- const ledger = readJournalSnapshot(orchLedger(home)), { created, pruned } = ledgerIndex(ledger);
87
- let names;
88
- try {
89
- names = readdirSync(join(home, "w"));
90
- }
91
- catch (error) {
92
- if (error.code !== "ENOENT")
93
- throw error;
94
- names = [];
95
- }
94
+ export function unfinishedWorkflow(home, fresh = false) {
95
+ const { record, names } = readerWorkflowListing(home, fresh), ix = record.state, { created, pruned } = ix;
96
96
  const ids = [...new Set([...[...created.keys()].map(String), ...names].filter(wid => !pruned.has(wid)))].sort().reverse();
97
97
  for (const wid of ids) {
98
98
  const path = journalPath(home, wid);
99
99
  // The hold rule is the one workflows() applies: the ledger's `created` names the origin a drain may hold; only for
100
100
  // a wid the ledger has no `created` for is the journal read first, for a `created` entry of its own.
101
101
  const known = created.get(wid);
102
- if (known && holdOf(ledger, wid, known.origin))
102
+ if (known && readerHold(ix, wid, known.origin))
103
103
  continue;
104
104
  let read;
105
105
  if (!known) {
106
106
  read = readJournalUncached(path);
107
- if (holdOf(ledger, wid, read?.entries.find(e => e.type === JT.created)?.origin))
107
+ if (readerHold(ix, wid, read?.entries.find(e => e.type === JT.created)?.origin))
108
108
  continue;
109
109
  }
110
110
  if (unfinishedJournal(path, read))
@@ -124,22 +124,11 @@ export function presented(ctx) {
124
124
  receipts.set(owner, { first: entries[0], last: entries.at(-1), length: entries.length, items });
125
125
  return items;
126
126
  }
127
- const open = new WeakMap();
128
- /** The unresolved attention items of one immutable journal snapshot, computed once per snapshot. */
129
- function unresolved(entries) {
130
- let items = open.get(entries);
131
- if (items)
132
- return items;
133
- const done = new Set(entries.filter(e => e.type === JT.attentionResolved).map(e => `${e.id}\0${e.rev}`));
134
- items = attentionEntries(entries).map(e => e.item).filter(item => !done.has(`${item.id}\0${item.rev}`));
135
- open.set(entries, items);
136
- return items;
137
- }
138
127
  /** P15, V7: Select only unresolved, unpresented items owned by this session. */
139
- export function attention(home, sender, seen) {
128
+ export function attention(home, sender, seen, fresh = false) {
140
129
  const items = [], shown = new Set(seen.map(s => `${s.id}\0${s.rev}`));
141
- for (const workflow of workflows(home, sender)) {
142
- for (const item of unresolved(workflow.entries)) {
130
+ for (const workflow of workflows(home, sender, fresh)) {
131
+ for (const item of workflow.settled?.attention ?? unresolvedAttention(workflow.entries)) {
143
132
  const key = `${item.id}\0${item.rev}`;
144
133
  if (shown.has(key))
145
134
  continue; // singlePresentation: one presentation per id/rev
@@ -6,13 +6,13 @@ import { setTimeout as delay } from "node:timers/promises";
6
6
  import { defineTool } from "@earendil-works/pi-coding-agent";
7
7
  import { Outbox, scanInbox } from "../kernel/mailbox.js";
8
8
  import { readJournalSnapshot } from "../kernel/journal.js";
9
- import { reduceLifecycle } from "../kernel/lifecycle.js";
9
+ import { readerLedger } from "../orchestrator/reader-ledger.js";
10
10
  import { OsLock } from "../platform/lock.js";
11
11
  import { launchOrchestrator } from "../platform/launch.js";
12
- import { dsaHome, orchInbox, orchLedger, orchLock, outboxRoot } from "../paths.js";
12
+ import { dsaHome, orchInbox, orchLock, outboxRoot } from "../paths.js";
13
13
  import { CT, JT } from "../types.js";
14
14
  import { attention, presentText, presented, resolved, unfinishedWorkflow } from "./main/snapshots.js";
15
- import { NOTIFY_SINCE, isLive, orchestratorTooOld, ownWorkflows, pausedElsewhere, runningOrchestrator, statusBrief, statusCallDetail, statusCompactDetail, statusDetail, statusView, widOfRid, outputSelect, writerWaits, writerWaitLine, WRITER_WAIT_HINT } from "../orchestrator/snapshot.js";
15
+ import { NOTIFY_SINCE, isLive, orchestratorTooOld, ownWorkflows, pausedElsewhere, runningOrchestrator, statusBrief, statusCallDetail, statusCompactDetail, statusDetail, statusView, outputSelect, writerWaits, writerWaitLine, WRITER_WAIT_HINT } from "../orchestrator/snapshot.js";
16
16
  import { BATCH, checkAgents, followUpReceipt, outcomeLine, request, sendReceipt } from "./main/tool.js";
17
17
  import { parameters } from "./main/schema.js";
18
18
  import { batchConflict, batchDigest, findRequest, manyIds, namesMany, requestRid, sendIdentified } from "../requests.js";
@@ -56,16 +56,13 @@ export function registerMain(pi, ui) {
56
56
  queue = result.catch(() => { });
57
57
  return result;
58
58
  }
59
- function ledger() { return readJournalSnapshot(orchLedger(home)); }
60
- function decisions() {
61
- return reduceLifecycle(ledger().filter(e => [JT.admitted, JT.applied, JT.rejected, JT.withdrawn].includes(e.type))).resolved;
62
- }
59
+ function ledger() { return readerLedger(home).state; }
60
+ function decisions() { return ledger().decisions; }
63
61
  async function reconcile() {
64
62
  for (const rid of decisions().keys())
65
63
  await outbox?.markResolved(rid);
66
- for (const entry of ledger())
67
- if (entry.type === JT.created)
68
- await outbox?.markResolved(String(entry.rid));
64
+ for (const rid of ledger().createdRids.keys())
65
+ await outbox?.markResolved(String(rid));
69
66
  }
70
67
  function pendingOutbox() { return pendingRids().size > 0; }
71
68
  function pendingRids() {
@@ -107,7 +104,7 @@ export function registerMain(pi, ui) {
107
104
  versionTold = orchestrator;
108
105
  ctx.ui.notify(`Durable Subagents: ${versionNote}.`, "warning");
109
106
  }
110
- function collect() { return ctx ? attention(home, sender, [...presented(ctx), ...reserved]) : []; }
107
+ function collect(fresh = false) { return ctx ? attention(home, sender, [...presented(ctx), ...reserved], fresh) : []; }
111
108
  function message(items) {
112
109
  return { type: "custom_message", customType: CT.attention, content: items.map(presentText).join("\n"), display: true, details: { items } };
113
110
  }
@@ -131,7 +128,8 @@ export function registerMain(pi, ui) {
131
128
  if (stopped)
132
129
  return;
133
130
  ctx = context;
134
- const items = collect(), entries = [];
131
+ // Polling can reuse a settled digest; a turn boundary must see attention appended just before it.
132
+ const items = collect(true), entries = [];
135
133
  if (items.length) {
136
134
  entries.push(message(items));
137
135
  reserved.push(...items);
@@ -250,7 +248,10 @@ export function registerMain(pi, ui) {
250
248
  return args;
251
249
  }
252
250
  /** "<rid>" or "<rid>/<key>" of a created run → the same address with its wid; anything else is unchanged. */
253
- function ridToWid(value) { return widOfRid(ledger(), value); }
251
+ function ridToWid(value) {
252
+ const cut = value.indexOf("/"), head = cut < 0 ? value : value.slice(0, cut), created = head ? ledger().createdRids.get(head) : undefined;
253
+ return created ? `${String(created.wid)}${value.slice(head.length)}` : value;
254
+ }
254
255
  /** A run request without a workflow yet (still pending, or rejected), asked about by its rid. */
255
256
  function pendingRun(rid) {
256
257
  const decision = decisions().get(rid);
@@ -394,7 +395,7 @@ export function registerMain(pi, ui) {
394
395
  return outbox.send("orch", normalized.kind, normalized.body, normalized.cond);
395
396
  });
396
397
  if ("conflict" in outcome) {
397
- const created = ledger().find(e => e.type === JT.created && e.rid === rid);
398
+ const created = ledger().createdRids.get(rid);
398
399
  return { applied: false, reason: "request-conflict", request: args.request, spec_digest: outcome.digest, ...(created ? { wid: created.wid } : {}),
399
400
  note: "this request id was used for different content; use a new id" };
400
401
  }
@@ -402,7 +403,7 @@ export function registerMain(pi, ui) {
402
403
  // P25: run waits for `created`; control requests wait for their terminal lifecycle record (applied or rejected+reason).
403
404
  const deadline = performance.now() + 10_000;
404
405
  while (wait || sent.kind === "run") {
405
- const receipt = sent.kind === "run" ? ledger().find(e => e.type === JT.created && e.rid === sent.rid) : undefined;
406
+ const receipt = sent.kind === "run" ? ledger().createdRids.get(sent.rid) : undefined;
406
407
  const decision = receipt ? undefined : decisions().get(sent.rid);
407
408
  if (receipt || decision) {
408
409
  await serial(async () => { await outbox?.markResolved(sent.rid); });
@@ -415,7 +416,7 @@ export function registerMain(pi, ui) {
415
416
  if (decision.type === "rejected")
416
417
  return { applied: false, reason: sent.kind === "resume" && args.wid === undefined ? resumeElsewhere(String(decision.reason)) : decision.reason, rid: sent.rid };
417
418
  if (sent.kind !== "run") {
418
- return { applied: true, rid: sent.rid, ...followUpReceipt(home, sent.rid, sent.body), ...sendReceipt(ledger(), sent.rid) };
419
+ return { applied: true, rid: sent.rid, ...followUpReceipt(home, sent.rid, sent.body), ...sendReceipt([ledger().sendNotes.get(sent.rid)].filter((e) => !!e), sent.rid) };
419
420
  }
420
421
  }
421
422
  if (performance.now() >= deadline || signal?.aborted)
@@ -55,7 +55,7 @@ async function pendingOutboxes(home) {
55
55
  /** P1: The pending-work rule shared with the main agent's starter: a non-empty orchestrator inbox, a pending
56
56
  * request to the orchestrator in any sender outbox, a workflow without JT.done, or an unsealed generation. */
57
57
  export async function pendingWork(home) {
58
- return (await scanInbox(orchInbox(home))).length > 0 || await pendingOutboxes(home) || unfinishedWorkflow(home);
58
+ return (await scanInbox(orchInbox(home))).length > 0 || await pendingOutboxes(home) || unfinishedWorkflow(home, true);
59
59
  }
60
60
  /** P1: The optional service's starter: start the orchestrator only when work is pending; publish no request
61
61
  * (unlike `resume`, it never undoes a drain or stop-all). Returns whether the starter was invoked. */
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)`);
@@ -13,11 +13,11 @@ import { journalPath, orchLedger } from "../paths.js";
13
13
  import { PS } from "../platform/proctable.js";
14
14
  import { JT } from "../types.js";
15
15
  import { restartInputError, restartRefusal } from "../orchestrator/restart.js";
16
- import { emptyLedger, foldLedger } from "../orchestrator/ledger.js";
16
+ import { readerLedger } from "../orchestrator/reader-ledger.js";
17
17
  import { allWorkflows, liveCalls, processAlive } from "../orchestrator/snapshot.js";
18
18
  /** The orchestrator that runs now: the last `orchestrator` record without an exit, whose process lives. */
19
19
  export function currentOrchestrator(home) {
20
- const o = foldLedger(emptyLedger(), readJournalSnapshot(orchLedger(home))).orchestrator;
20
+ const o = readerLedger(home).state.state.orchestrator;
21
21
  return o && !o.exited && processAlive(o.pid, o.start) ? { version: o.version, pid: o.pid, ...(o.start ? { start: o.start } : {}), ts: o.ts, ...(o.restart ? { restart: true } : {}) } : undefined;
22
22
  }
23
23
  /** Best-effort provenance; never read the live DSA home to identify the invoking process. */
@@ -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();