pi-durable-subagents 1.0.35 → 1.0.38

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,63 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.0.38
4
+
5
+ - An answer to any open question of a call reaches it. A call whose question was interrupted (by a steer) and that
6
+ asked again in other words while waiting no longer orphans the answer to the first question: a waiting subagent
7
+ takes it as the result of its current question, a hibernated one resumes with it (also when the answer was sent
8
+ before it hibernated), and a subagent that is not waiting gets it as a message at its next safe point. Before, an
9
+ answer to a question other than the one the subagent waited on was held until a later ask, usually forever, and
10
+ then retired.
11
+ - One rule for answers: an answer (or the answer a hibernated asker resumes with) to an open question is delivered
12
+ once, at the first chance, never held. A waiting subagent prefers the answer to the question it waits on when
13
+ several are pending. Follow-ups sent before a pending answer still enter ahead of it, notifies after it.
14
+ - An answer to an earlier question that ends the wait on a later one supersedes the later question: the subagent is
15
+ told it was withdrawn and to ask again if it still needs it, its attention item resolves `superseded` (at once when
16
+ the answer is bound to a hibernated call), `status` no longer shows the call `asking`, and a later answer to it is
17
+ refused `stale-rev`.
18
+ - A question revision gets at most one answer receipt. An answer sent before the call hibernated and bound to the
19
+ hibernation is withdrawn from the subagent's inbox; any further envelope for an answered, superseded or stale
20
+ revision is dropped with a receipt, so nothing waits on it. These records survive a crash between their writes: a
21
+ supersession is derived from the binding that made it, an adoption whose withdrawal went out is completed first, and
22
+ a bound answer the session had already closed is settled without waiting for a receipt. An answer bound to a revision
23
+ the subagent has already asked again is not delivered: the call hibernates again and the parent is asked the newer
24
+ revision.
25
+ - A follow-up generation no longer re-opens the questions of the session it continues (its subagent would refuse
26
+ their answers). Items that 1.0.37 re-opened in a running generation are resolved `carried` at orchestrator start.
27
+ - Follow-ups queued while a call waited on its question reach the resumed model before the answer, in send order.
28
+
29
+ ## 1.0.37
30
+
31
+ - The process table runs `ps` by its absolute path (`/bin/ps`), so an orchestrator started with a minimal PATH keeps
32
+ working on macOS.
33
+ - Contains every change listed under 1.0.36, which was tagged but not published (its macOS CI failed on this).
34
+
35
+ ## 1.0.36
36
+
37
+ - Slot precedence among waiting calls. When a provider slot frees, a call resuming earlier work (an answered
38
+ question, a follow-up, a recovery) is admitted before a fresh call; among equals the origin holding fewer slots of
39
+ that provider goes first, then the longest waiter. A waiter holds a slot back from others only while it is still
40
+ trying; one that is gone (stopped, interrupted, or silent for about 3 tracker periods) is ignored.
41
+ - Pool entries can wait before a pool spills over to them: `{"model": "provider/id", "afterMs": 600000}` is used only
42
+ after the call has waited that long for the entries before it. Failover and a model request that names the pool
43
+ skip such entries. The wait and the resume precedence are recomputed for each execution.
44
+ - `status` names the slot holders of a provider by origin when more than one origin holds it.
45
+ - An answered question no longer shows its call as `asking` while the call waits for a slot: it is `queued` with
46
+ `answered: "<qid>"` (and still `hibernated`). The question's attention resolves when the answer is bound, and the
47
+ `answered` event is emitted then (journals written before 1.0.36 still emit it once, at resolution).
48
+ - A follow-up running on a finished run shows `active: true`. `status` keeps meaning the run's result, so scripts that
49
+ read it are unaffected; the text renderings lead with `follow-up running (run done)`.
50
+ - The orchestrator no longer depends on whoever started it. The starter resolves `pi` to an absolute path and passes
51
+ it as `DSA_PI_BIN`; `run` and `send` refuse with exit 75 when no `pi` can be found, and the submitted request stays
52
+ pending. On Linux with a lingering systemd user manager the orchestrator runs in its own transient scope, so the end
53
+ of a oneshot unit, cron job or CI step does not end it. Subagents get the orchestrator's node directory on their
54
+ PATH.
55
+ - A launch that fails because `pi` is missing or not executable (ENOENT, EACCES) keeps the call queued, raises one
56
+ `environment` alert, releases its slots and retries every 60 s (at once after a restart). Only one dispatch message
57
+ is pending however many retries fail. Other launch failures stay terminal.
58
+ - The orchestrator records why it exited (idle, restart, signal, error); `doctor` shows the last reason. Stale
59
+ temporary files in `$DSA_HOME/bin` are removed at start.
60
+
3
61
  ## 1.0.35
4
62
 
5
63
  - Generation openings of one workflow are serialized. The reopen of undelivered follow-ups at orchestrator start, the
package/README.md CHANGED
@@ -80,7 +80,9 @@ subagents({ action: "status" })
80
80
  `status` without a wid is brief: what runs, what asks (with the address to
81
81
  answer) or failed, and one line per finished workflow, each with its run
82
82
  `labels` clipped to 60 characters (the `/subagents` list shows them on a
83
- workflow's row when they fit). `status` with a wid
83
+ workflow's row when they fit). A workflow's `status` is its run's result;
84
+ `active: true` means a latest-generation call is still queued, running or
85
+ asking, including a follow-up on a finished run. `status` with a wid
84
86
  shows one workflow with outputs clipped; add `key` for one call's full result,
85
87
  or `full: true` for everything. `tail: N` gives the last N lines of each call's
86
88
  result instead, and `grep: "<regex>"` only its lines matching a case-sensitive
@@ -120,7 +122,7 @@ it something. Each verb means one thing, and a refusal says what would work:
120
122
  | `send steer` | a running subagent | Reaches it at its next safe point. To a finished one: refused, use `follow-up`; To one waiting on its question: it interrupts the question, and the subagent usually asks again; `answer` answers it. |
121
123
  | `send notify` | any subagent | Tells it a decision without disturbing it. The reply's `delivery` says how: `steered` (running: it gets the note at its next safe point, like a steer), `held-until-answer` (waiting on its question: never interrupts it; it gets the note at the first safe point after the answer) or `noted` (not running: nothing starts; the note is recorded, and the call's next follow-up opens with it). |
122
124
  | `send follow-up` | any subagent | A finished one continues in the same session as a new generation (`key@2`); the reply names it (`generation`, `call`). A running one gets it after its current turn; the reply says `delivery: forwarded` and names the running generation (`call: <wid>/<key>@<gen>`). With `model` (a model or a pool's name), the generation that takes it runs on it. |
123
- | `send answer` | an open question | Answers it once. |
125
+ | `send answer` | an open question | Answers it once, at the first chance: as the result of the question it waits on, or (when it no longer waits on that question, say after a steer) as a message at its next safe point. An answer to an earlier question while it waits on a later one ends the later one: that question is withdrawn (`superseded`, the subagent is told to ask again if it still needs it) and takes no answer. |
124
126
  | `send model` | any subagent | A running one switches at its next request; one asking, hibernated or waiting for a slot launches on it when it runs again. A pool's name picks its first model that is not used up (and, for a running call, has a free slot); the reply names the model picked, and a call from that pool stays in it. |
125
127
  | `stop` | a subagent or a workflow | Final: `stopped`, usage kept, edits left as they are. |
126
128
  | `drain` / `resume` | existing workflows | A reversible hold; runs started later are not held. |
@@ -532,10 +534,13 @@ that applies wins:
532
534
  | `silent` | is running (launched, not stopped) without visible activity: the stall notice of that execution, with the command running and for how long |
533
535
 
534
536
  A call whose current execution asked a question (also while it hibernates
535
- until the answer) is `asking`, not waiting. Once the answer arrives the call
536
- launches again, and from then on it waits like any call (for a slot, the
537
- writer lock, …) even though `describe` still lists the question as open until
538
- the new execution reads it (its `state` stays `asking`). A drained call
537
+ until the answer) is `asking`, not waiting. Once its answer is bound, it is
538
+ `queued` with `answered: "<qid>"` and no open question, retaining
539
+ `hibernated: true` while it holds no slot until its next execution starts.
540
+ It waits like any queued call (for a slot, the writer lock, ...), except while
541
+ a drain holds its workflow: then it waits for `resume`, not for a slot, and
542
+ `status` does not say it waits for one. Its `answered` event is logged when the
543
+ answer is bound. A drained call
539
544
  (no execution running) is never `silent`; a sealed call never waits. `provider-exhausted`, `writer-lock`, `lease` and `slot` are queues
540
545
  that clear by themselves; `silent` and `unconfirmed-stop` may need a look.
541
546
 
@@ -572,6 +577,58 @@ read, in a burst each time a call ends), `pid` and `at` (when it was
572
577
  written). The orchestrator writes these to `orchestrator-stats.json` every
573
578
  10 s; they are shown only while that process runs.
574
579
 
580
+ ### Where the orchestrator starts
581
+
582
+ Whatever needs it first starts the orchestrator: a pi session, a CLI
583
+ command, the optional service, or the orchestrator itself after a restart.
584
+ It must not depend on that caller's environment or lifetime:
585
+
586
+ - **pi is resolved once, by the starter.** `DSA_PI_BIN` when set (it must
587
+ be the absolute path of an executable file), else the first `pi` on the
588
+ starter's `PATH` (a package-manager shim stays the shim). The orchestrator
589
+ receives it as `DSA_PI_BIN` and launches every subagent with that path, not
590
+ with whatever `pi` its inherited `PATH` finds. Its start records it in the
591
+ ledger (`orchestrator{pi}`, `null` when none was found) and `doctor` shows
592
+ it as `pi: <path>`.
593
+ - **The CLI does not start an orchestrator without pi.** When neither
594
+ `DSA_PI_BIN` nor `PATH` has one, the command fails with an error naming
595
+ both; a request it already sent stays pending and runs once an orchestrator
596
+ starts from an environment that has pi (any pi session starts one). A pi
597
+ session starts it regardless; the orchestrator then looks pi up on its own
598
+ `PATH`. `install-service` writes the `pi` it finds into the service as
599
+ `DSA_PI_BIN`, since a service manager's `PATH` rarely has it.
600
+ - **Its own scope on Linux.** A oneshot systemd unit, a cron job or a CI step
601
+ ends every process in its cgroup when it finishes, a detached orchestrator
602
+ included. On Linux with a systemd user manager (`systemd-run` on `PATH`,
603
+ `XDG_RUNTIME_DIR` set) and lingering enabled for the user
604
+ (`loginctl enable-linger`, i.e. `/var/lib/systemd/linger/$USER` exists),
605
+ the starter therefore runs it as
606
+ `systemd-run --user --scope --collect -- node <entry>`, in a transient
607
+ scope of its own, after a quick probe that such a scope works. Otherwise
608
+ (macOS, no systemd, no lingering, a failing probe) it starts as a plain
609
+ detached process, as before: without lingering the user manager stops its
610
+ scopes at logout, while a detached process survives it under the usual
611
+ `KillUserProcesses=no`. `DSA_SCOPE=off` turns the scope off.
612
+ - **A launch the environment breaks does not use up the call.** When a
613
+ subagent's `pi` cannot be launched because it is missing or not
614
+ executable (`ENOENT`, `EACCES`), the call does not fail: its slots are
615
+ released, it stays queued, its workflow journal records
616
+ `spawn-env-failed{exec,command,error}`, and one `environment` alert says
617
+ what failed, which `pi` it ran and how to fix it. The launch is retried
618
+ every minute, and at once when the orchestrator restarts; the alert is
619
+ resolved when a launch works. Stop the call to give up. Other launch
620
+ errors still fail the call.
621
+ - **Every exit says why.** The ledger's `orchestrator-exit` carries
622
+ `reason`: `idle` (no work for `k.idleExitMs`), `restart` (an applied
623
+ restart request), `signal` (with `signal`, e.g. `SIGTERM`) or `error`
624
+ (with the clipped `error`). A process killed outright (SIGKILL, a crash)
625
+ records nothing. While none runs, `doctor` shows
626
+ `orchestrator: not running; last exit: signal SIGTERM 5m ago`, or
627
+ `no exit recorded (killed or crashed)`.
628
+ - Temporary files of interrupted writes (a full disk, say) are removed when
629
+ a write fails, and the orchestrator's start removes those older than
630
+ 10 minutes from `$DSA_HOME/bin`.
631
+
575
632
  ### Resource leases
576
633
 
577
634
  Benchmarks, timing measurements and big builds need the machine to
@@ -654,6 +711,17 @@ State lives in `~/.pi/durable-subagents`; set `DSA_HOME` to move it.
654
711
  file or a model send). The first candidate with a free slot is
655
712
  used, and a candidate that keeps failing is skipped for 10 minutes. The
656
713
  order is the preference: list the provider you want to use first.
714
+ - **Waiting before spilling over:** a pool entry can also be
715
+ `{ "model": "<provider/id[:thinking]> or pool name", "afterMs": <ms> }`. A
716
+ waiting call takes it only after it has waited `afterMs` for a slot; until
717
+ then it waits for the entries before it. In
718
+ `"opus": ["a/strong", "b/strong", {"model": "c/weaker", "afterMs": 600000}]`
719
+ a call uses `c/weaker` only after 10 minutes without a free `a` or `b` slot.
720
+ A nested pool's `afterMs` applies to every model it lists (the larger value
721
+ wins when nested twice). It does not apply to a call that continues its own
722
+ session's model or was asked for a model, and a running call that moves off
723
+ a used-up provider skips such entries, as does a model send that names the
724
+ pool.
657
725
  - **A used-up provider** is not sent new calls until its next try, 15 minutes
658
726
  after it last refused (`"k": { "probeMs": 900000 }`). Then one call at a
659
727
  time goes to it, so finding out costs no extra request. A call that moved to
@@ -677,7 +745,19 @@ State lives in `~/.pi/durable-subagents`; set `DSA_HOME` to move it.
677
745
  Interrupted (Ctrl-C), it stops what it started and cleans up the same way
678
746
  (exit 130, or 143 for SIGTERM).
679
747
  - **Provider slots:** never exceeded, including while a model switch is in
680
- progress.
748
+ progress. When several calls wait for a provider, a freed slot goes first to
749
+ a call that ran before (resumed after an answer, a follow-up generation, a
750
+ call recovered after a restart; its session and prompt cache are ready),
751
+ then to the workflow origin (pi session or CLI) that holds fewer of that
752
+ provider's slots, then to the call that has waited longest. A call yields
753
+ only to waiters that found the provider full on a recent attempt, so a slot
754
+ is not held back for a waiter that has gone, though it can stay free for up
755
+ to about three tracker periods (`k.trackerMs`) until that waiter no longer
756
+ counts as recent. The
757
+ `afterMs` wait and the precedence of a call that ran before are computed
758
+ anew for each execution: a call launched again (after a loss or a launch
759
+ that failed) starts its wait over. `status` names the holders per origin when more than one
760
+ holds a provider: `anthropic 4/4 (3 cli:alice@host, 1 session 01a11a3b)`.
681
761
  - **Memory:** new subagents wait while memory is short. Running ones are
682
762
  never stopped for memory.
683
763
  - **Writer lock:** `"queue"` (default) runs one writing call per git
@@ -3,7 +3,14 @@ import { CT } from "../../types.js";
3
3
  * session of the previous one (P37), but request sequences are per recipient (P5): records addressed to an earlier
4
4
  * generation stay in history and are skipped here: segments opened by another call's execution marker are foreign. */
5
5
  export function recover(entries, call) {
6
- const records = [], questions = new Map(), answered = new Set();
6
+ const records = [], questions = new Map(), answered = new Set(), superseded = new Set();
7
+ // D2: an answer to another question that ended a blocked ask (or resumed a hibernated one) supersedes that question.
8
+ const supersede = (details) => {
9
+ if (Array.isArray(details?.superseded))
10
+ for (const s of details.superseded)
11
+ if (typeof s?.qid === 'string' && typeof s.rev === 'number')
12
+ superseded.add(`${s.qid}@${s.rev}`);
13
+ };
7
14
  let foreign = false;
8
15
  for (const entry of entries) {
9
16
  if (entry.type === 'custom' && entry.customType === CT.exec) {
@@ -33,6 +40,7 @@ export function recover(entries, call) {
33
40
  else if (entry.type === 'custom_message' && entry.customType === CT.msg) {
34
41
  const details = entry.details;
35
42
  records.push({ type: 'applied', rid: details.rid });
43
+ supersede(details);
36
44
  // P28: a hibernation resume delivers the answer as a continue message; its receipt answers qid@rev.
37
45
  if (details.qid && details.rev)
38
46
  answered.add(`${details.qid}@${details.rev}`);
@@ -41,9 +49,10 @@ export function recover(entries, call) {
41
49
  const details = entry.message.details;
42
50
  if (details?.rid)
43
51
  records.push({ type: 'applied', rid: details.rid });
52
+ supersede(details);
44
53
  if (details?.qid && details.rev)
45
54
  answered.add(`${details.qid}@${details.rev}`);
46
55
  }
47
56
  }
48
- return { records, questions, answered };
57
+ return { records, questions, answered, superseded };
49
58
  }
@@ -11,6 +11,17 @@ import { recover } from "./child/history.js";
11
11
  import { validate } from "./child/schema.js";
12
12
  import { registerLive } from "./child/live.js";
13
13
  const MESSAGES = ['task', 'steer', 'notify', 'follow-up', 'continue'];
14
+ /** D2: the questions a bound continue supersedes: the hibernated asker's own question when it resumes with the answer
15
+ * to another one (the orchestrator names it in the body). */
16
+ function supersededOf(req) {
17
+ const list = req.kind === 'continue' ? req.body?.superseded : undefined;
18
+ return Array.isArray(list) ? list.filter((s) => typeof s?.qid === 'string' && typeof s?.rev === 'number').map(s => ({ qid: s.qid, rev: s.rev })) : [];
19
+ }
20
+ /** The question an envelope answers: an `answer`, or a `continue` that resumes a hibernated asker with its answer (P28). */
21
+ export function answers(req) {
22
+ const qid = req.cond?.qid, rev = req.cond?.rev;
23
+ return (req.kind === 'answer' || req.kind === 'continue') && typeof qid === 'string' && typeof rev === 'number' ? { qid, rev } : undefined;
24
+ }
14
25
  /** P31, P33, P37: Usage of this call only — assistant messages in segments opened by this call's executions,
15
26
  * deduplicated by entry id. Context inherited from an earlier generation or a forked origin is not charged. */
16
27
  export function usage(entries, call) {
@@ -78,20 +89,48 @@ export function registerChild(pi) {
78
89
  if (!active || (mode === 'idle' && !ctx.isIdle()))
79
90
  return [];
80
91
  let delivered = false;
92
+ // Revisions answered (taken) or superseded (planned) by a decision of this intake are closed for the rest of it:
93
+ // one delivery each (D3), and no answer to a question an earlier decision of the same intake superseded (D2).
94
+ const taken = new Set(), planned = new Set();
95
+ const closed = () => new Set([...state.answered, ...state.superseded, ...taken, ...planned]);
96
+ const open = (q) => openness({ open: [...state.questions.values()], closed: closed() }, q);
97
+ const pending = (req, view) => view.admitted.has(req.rid) && !view.resolved.has(req.rid) && !view.tombstones.has(req.rid);
98
+ // An answer to an open question (or a bound continue, P28) that waits to be delivered.
99
+ const waiting = (req, view) => {
100
+ const q = answers(req);
101
+ return !!q && pending(req, view) && open(q);
102
+ };
81
103
  const plans = planDecisions(state.records, candidates, (req, view) => {
82
104
  if (req.to !== call)
83
105
  return { action: 'reject', reason: 'wrong-recipient' };
84
106
  if ([...MESSAGES, 'answer'].includes(req.kind) && typeof req.body?.message !== 'string')
85
107
  return { action: 'reject', reason: 'malformed' };
86
- if (req.kind === 'answer') {
87
- const qid = req.cond?.qid, rev = req.cond?.rev, question = qid ? state.questions.get(qid) : undefined;
88
- if (state.answered.has(`${qid}@${rev}`))
108
+ const q = answers(req);
109
+ // D1, D3, V4: one rule for answers (an `answer`, or a bound `continue`): an open question takes its answer at the
110
+ // first opportunity, once; any further envelope for an answered or superseded revision is dropped with a receipt.
111
+ if (q) {
112
+ const key = `${q.qid}@${q.rev}`;
113
+ if (state.answered.has(key) || taken.has(key))
89
114
  return { action: 'reject', reason: 'already-answered' };
90
- if (!question || question.rev !== rev)
115
+ // Not open: superseded, an older revision, or a question this generation did not ask. A bound continue too: the
116
+ // orchestrator binds the latest revision it observed, and the child may have asked again meanwhile (V4).
117
+ if (!open(q))
91
118
  return { action: 'reject', reason: 'stale-rev' };
92
- if (mode !== 'ask' || delivered || !openness({ open: [...state.questions.values()], blocked }, { qid: qid, rev: rev }))
119
+ if (delivered && mode !== 'boundary' && mode !== 'settle')
120
+ return { action: 'defer' };
121
+ // A blocked ask prefers its own answer when answers to several open questions wait.
122
+ if (mode === 'ask' && blocked && !(q.qid === blocked.qid && q.rev === blocked.rev) && candidates.some(other => pending(other, view) &&
123
+ answers(other)?.qid === blocked.qid && answers(other)?.rev === blocked.rev))
124
+ return { action: 'defer' };
125
+ // Follow-ups ordered before it enter first (fix C): at a boundary they ride ahead (below); here it waits.
126
+ if (mode !== 'ask' && candidates.some(other => other.kind === 'follow-up' && pending(other, view) && view.order.get(other.rid) < view.order.get(req.rid)))
93
127
  return { action: 'defer' };
94
128
  delivered = true;
129
+ taken.add(key);
130
+ for (const s of supersededOf(req))
131
+ planned.add(`${s.qid}@${s.rev}`);
132
+ if (mode === 'ask' && blocked && !(q.qid === blocked.qid && q.rev === blocked.rev))
133
+ planned.add(`${blocked.qid}@${blocked.rev}`);
95
134
  return { action: 'apply' };
96
135
  }
97
136
  if (mode === 'ask' && (req.kind !== 'steer' || delivered))
@@ -103,12 +142,14 @@ export function registerChild(pi) {
103
142
  return body && ctx.modelRegistry.find(body.provider, body.model) ? { action: 'apply' } : { action: 'reject', reason: 'unknown-model' };
104
143
  }
105
144
  if (MESSAGES.includes(req.kind)) {
106
- if ((mode === 'idle' && delivered) || (req.kind === 'follow-up' && mode === 'boundary'))
145
+ // A resumed turn can reach this boundary before an idle intake. Older follow-ups must ride ahead of its
146
+ // bound answer; otherwise continue bypasses them and the model sees stale instructions after the answer.
147
+ const beforeResume = mode === 'boundary' && req.kind === 'follow-up' && candidates.some(other => waiting(other, view) && view.order.get(req.rid) < (view.order.get(other.rid) ?? -1));
148
+ if ((mode === 'idle' && delivered) || (req.kind === 'follow-up' && mode === 'boundary' && !beforeResume))
107
149
  return { action: 'defer' };
108
150
  // A notify never interrupts a question: while an answer waits to be delivered (a hibernated asker resumes with
109
151
  // its answer as a continue) it goes after it, at the next safe point. In ask mode it was deferred above.
110
- if (req.kind === 'notify' && candidates.some(other => !view.resolved.has(other.rid) && !view.tombstones.has(other.rid) &&
111
- (other.kind === 'answer' && !state.answered.has(`${other.cond?.qid}@${other.cond?.rev}`) || other.kind === 'continue' && other.cond?.qid !== undefined)))
152
+ if (req.kind === 'notify' && candidates.some(other => waiting(other, view)))
112
153
  return { action: 'defer' };
113
154
  delivered = true;
114
155
  return { action: 'apply' };
@@ -118,7 +159,7 @@ export function registerChild(pi) {
118
159
  // Idle delivery starts pi immediately. Commit only through that message's receipt;
119
160
  // later decisions must be reconsidered at the next boundary, in history order.
120
161
  if (mode === 'idle') {
121
- const firstMessage = plans.findIndex(d => d.type === 'applied' && MESSAGES.includes(byRid.get(d.rid).kind));
162
+ const firstMessage = plans.findIndex(d => d.type === 'applied' && [...MESSAGES, 'answer'].includes(byRid.get(d.rid).kind));
122
163
  if (firstMessage >= 0)
123
164
  plans.splice(firstMessage + 1);
124
165
  }
@@ -150,19 +191,35 @@ export function registerChild(pi) {
150
191
  record(CT.model, { rid: req.rid, provider: body.provider, model: body.model, ...(body.thinking ? { thinking: body.thinking } : {}) });
151
192
  }
152
193
  else if (mode === 'ask' && waiter) {
153
- const text = req.body.message;
154
- answer = req.kind === 'answer'
155
- ? { content: [{ type: 'text', text }], details: { rid: req.rid, qid: waiter.qid, rev: waiter.rev } }
156
- : { content: [{ type: 'text', text: `${JSON.stringify({ interrupted_by: 'steer', open: waiter.qid })}\n${text}` }], details: { rid: req.rid, kind: 'steer' } };
157
- if (req.kind === 'answer')
158
- state.answered.add(`${waiter.qid}@${waiter.rev}`);
194
+ const text = req.body.message, q = answers(req);
195
+ if (q) {
196
+ const carried = supersededOf(req);
197
+ // D2: an answer to another open question ends the blocked ask too; the blocked question is superseded (the
198
+ // model is told so), and a later answer to it is rejected.
199
+ const own = q.qid === waiter.qid && q.rev === waiter.rev;
200
+ const note = own ? '' : `${JSON.stringify({ answers_earlier_question: q.qid, withdrawn: waiter.qid })}\n` +
201
+ `Your question "${waiter.question}" is withdrawn: this answers your earlier question instead. Ask again if you still need it answered.\n` +
202
+ (req.kind === 'answer' ? `Question: ${state.questions.get(q.qid)?.question ?? q.qid}\nAnswer: ` : '');
203
+ const superseded = [...carried, ...(own ? [] : [{ qid: waiter.qid, rev: waiter.rev }])];
204
+ answer = { content: [{ type: 'text', text: `${note}${text}` }], details: { rid: req.rid, qid: q.qid, rev: q.rev, ...(superseded.length ? { superseded } : {}) } };
205
+ state.answered.add(`${q.qid}@${q.rev}`);
206
+ for (const s of superseded)
207
+ state.superseded.add(`${s.qid}@${s.rev}`);
208
+ }
209
+ else
210
+ answer = { content: [{ type: 'text', text: `${JSON.stringify({ interrupted_by: 'steer', open: waiter.qid })}\n${text}` }], details: { rid: req.rid, kind: 'steer' } };
159
211
  }
160
212
  else {
161
- // P28: a continue bound to a question (hibernation resume) is that question's answer receipt.
162
- const bound = req.kind === 'continue' && req.cond?.qid && req.cond.rev ? { qid: req.cond.qid, rev: req.cond.rev } : undefined;
163
- if (bound)
164
- state.answered.add(`${bound.qid}@${bound.rev}`);
165
- entries.push({ type: 'custom_message', customType: CT.msg, content: req.body.message, display: true, details: { rid: req.rid, kind: req.kind, from: req.from, ...bound } });
213
+ // P28: a continue bound to a question (hibernation resume) is that question's answer receipt; D1: so is an
214
+ // answer delivered outside an ask (its ask ended by a steer or a reminder), as a message at this boundary.
215
+ const q = answers(req), body = req.body, superseded = supersededOf(req);
216
+ if (q)
217
+ state.answered.add(`${q.qid}@${q.rev}`);
218
+ for (const s of superseded)
219
+ state.superseded.add(`${s.qid}@${s.rev}`);
220
+ const content = req.kind === 'answer'
221
+ ? `The answer to your earlier question arrived.\nQuestion: ${state.questions.get(q.qid)?.question ?? q.qid}\nAnswer: ${body.message}` : body.message;
222
+ entries.push({ type: 'custom_message', customType: CT.msg, content, display: true, details: { rid: req.rid, kind: req.kind, from: req.from, ...q, ...(superseded.length ? { superseded } : {}) } });
166
223
  }
167
224
  }
168
225
  }
@@ -1,4 +1,3 @@
1
- import { spawn } from "node:child_process";
2
1
  import { mkdir } from "node:fs/promises";
3
2
  import { readFileSync } from "node:fs";
4
3
  import { join } from "node:path";
@@ -9,6 +8,7 @@ import { Outbox, scanInbox } from "../kernel/mailbox.js";
9
8
  import { readJournalSnapshot } from "../kernel/journal.js";
10
9
  import { reduceLifecycle } from "../kernel/lifecycle.js";
11
10
  import { OsLock } from "../platform/lock.js";
11
+ import { launchOrchestrator } from "../platform/launch.js";
12
12
  import { dsaHome, orchInbox, orchLedger, 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";
@@ -91,10 +91,8 @@ export function registerMain(pi, ui) {
91
91
  return;
92
92
  await lock.release();
93
93
  const entry = process.env.DSA_ORCHESTRATOR_ENTRY ?? fileURLToPath(new URL(import.meta.url.endsWith(".ts") ? "../orchestrator/main.ts" : "../orchestrator/main.js", import.meta.url));
94
- const { DSA_SESSION: _session, ...env } = process.env;
95
- const child = spawn(process.execPath, [entry], { detached: true, stdio: "ignore", env: { ...env, DSA_HOME: home } });
96
- await new Promise((resolve, reject) => { child.once("spawn", resolve); child.once("error", reject); });
97
- child.unref();
94
+ // Inside pi: started even when pi cannot be resolved here (the orchestrator falls back to its own lookup).
95
+ await launchOrchestrator(entry, process.env, { home });
98
96
  }
99
97
  // Version visibility: say once per orchestrator process when it runs another version than this pi loaded (after an
100
98
  // update its running work stays on the old one); status shows the same note.
@@ -1,4 +1,3 @@
1
- import { spawn } from "node:child_process";
2
1
  import { mkdir, readdir } from "node:fs/promises";
3
2
  import { hostname, userInfo } from "node:os";
4
3
  import { join } from "node:path";
@@ -8,13 +7,17 @@ import { Outbox, scanInbox } from "../kernel/mailbox.js";
8
7
  import { readJournalSnapshot } from "../kernel/journal.js";
9
8
  import { reduceLifecycle } from "../kernel/lifecycle.js";
10
9
  import { OsLock } from "../platform/lock.js";
10
+ import { launchOrchestrator } from "../platform/launch.js";
11
11
  import { orchInbox, orchLedger, orchLock, outboxRoot } from "../paths.js";
12
12
  import { unfinishedWorkflow } from "../agent/main/snapshots.js";
13
13
  import { cliInitiator } from "./restart.js";
14
14
  import { restartInputError } from "../orchestrator/restart.js";
15
15
  import { JT } from "../types.js";
16
16
  import { RequestsBusy, sendIdentified } from "../requests.js";
17
- /** P1: Start the detached orchestrator only after probing its OS lock. */
17
+ /** P1: Start the detached orchestrator only after probing its OS lock (platform/launch.ts: pi resolved here, its own
18
+ * scope). Throws PiNotFound, starting nothing, when this environment has no pi: an orchestrator started here could
19
+ * launch no subagent, and a request already published stays pending for the next starter that has pi. A replaced
20
+ * entry (DSA_ORCHESTRATOR_ENTRY) may not launch pi at all and is started regardless. */
18
21
  export async function startOrchestrator(home, env) {
19
22
  const lock = await new OsLock().tryAcquire(orchLock(home));
20
23
  if (!lock)
@@ -22,10 +25,7 @@ export async function startOrchestrator(home, env) {
22
25
  await lock.release();
23
26
  const entry = env.DSA_ORCHESTRATOR_ENTRY ?? fileURLToPath(new URL(import.meta.url.endsWith(".ts") ? "../orchestrator/main.ts" : "../orchestrator/main.js", import.meta.url));
24
27
  // The orchestrator serves every session: it never carries the starting pi session's $DSA_SESSION to its children.
25
- const { DSA_SESSION: _session, ...rest } = env;
26
- const child = spawn(process.execPath, [entry], { detached: true, stdio: "ignore", env: { ...rest, DSA_HOME: home } });
27
- await new Promise((resolve, reject) => { child.once("spawn", resolve); child.once("error", reject); });
28
- child.unref();
28
+ await launchOrchestrator(entry, env, { home, requirePi: !env.DSA_ORCHESTRATOR_ENTRY });
29
29
  }
30
30
  /** P1, P38: Requests addressed to the orchestrator that some sender recorded as sent and that neither the sender nor the
31
31
  * ledger has resolved. Read-only: other senders' outboxes are never modified here. */
@@ -10,6 +10,7 @@ import { scanInbox } from "../kernel/mailbox.js";
10
10
  import { OsLock } from "../platform/lock.js";
11
11
  import { journalPath, orchInbox, orchLedger, orchLock } from "../paths.js";
12
12
  import { runningStats, snapshotFromEntries } from "../orchestrator/snapshot.js";
13
+ import { emptyLedger, foldLedger } from "../orchestrator/ledger.js";
13
14
  import { statsLine } from "../orchestrator/stats.js";
14
15
  import { diskUsage } from "../orchestrator/store.js";
15
16
  import { JT, isEntry } from "../types.js";
@@ -50,6 +51,16 @@ export async function doctor(home, env = process.env, now = Date.now()) {
50
51
  const pruned = new Set(ledger.filter(e => e.type === "pruned").map(e => String(e.wid)));
51
52
  const report = { home, bytes: await diskUsage(home), workflows: {}, ledger: { entries: ledger.length, bytes: await diskUsage(orchLedger(home)) },
52
53
  largestJournals: [], parked: [], attention: [], fenceFailed: [], orphanStaging: [], tmpFiles: [], orchestrator: await lockHeld(home), service: "unavailable", findings: [], ...runningStats(home) };
54
+ const last = foldLedger(emptyLedger(), ledger), o = last.orchestrator;
55
+ if (o && o.pi !== undefined)
56
+ report.pi = o.pi;
57
+ if (o && report.orchestrator === "not running") {
58
+ const exit = last.lastExit?.pid === o.pid ? last.lastExit : undefined;
59
+ if (exit)
60
+ report.lastExit = { reason: exit.reason, ageMs: now - exit.ts, ...(exit.signal ? { signal: exit.signal } : {}), ...(exit.error ? { error: exit.error } : {}) };
61
+ else if (!o.exited)
62
+ report.lastExit = { reason: "unrecorded", ageMs: now - o.ts };
63
+ }
53
64
  const journals = [];
54
65
  for (const wid of (await names(join(home, "w"))).filter(n => !n.startsWith(".") && !pruned.has(n)).sort()) {
55
66
  const entries = readJournalSnapshot(journalPath(home, wid)), snap = snapshotFromEntries(wid, entries);
@@ -126,6 +137,13 @@ export function age(ms) {
126
137
  const m = Math.floor(ms / 60_000), h = Math.floor(m / 60), d = Math.floor(h / 24);
127
138
  return d ? `${d}d ${h % 24}h` : h ? `${h}h ${m % 60}m` : `${m}m`;
128
139
  }
140
+ /** "last exit: idle 5m ago", "last exit: signal SIGTERM 2h ago", "last exit: error (message) 1m ago", "last exit
141
+ * unrecorded (killed or crashed), started 3h ago". */
142
+ export function exitLine(x) {
143
+ if (x.reason === "unrecorded")
144
+ return `no exit recorded (killed or crashed), started ${age(x.ageMs)} ago`;
145
+ return `last exit: ${x.reason}${x.signal ? ` ${x.signal}` : ""}${x.error ? ` (${x.error})` : ""} ${age(x.ageMs)} ago`;
146
+ }
129
147
  /** Housekeeping: Render the report; one suggested command per actionable finding. */
130
148
  export function renderDoctor(r) {
131
149
  const counts = Object.entries(r.workflows).sort(([a], [b]) => a < b ? -1 : 1);
@@ -141,7 +159,8 @@ export function renderDoctor(r) {
141
159
  ...list("unresolved fence failures", r.fenceFailed, f => `${f.wid} ${f.exec} ${age(f.ageMs)}`),
142
160
  ...list("orphan staging", r.orphanStaging, s => s),
143
161
  ...list("leftover tmp files", r.tmpFiles, s => s),
144
- `orchestrator: ${r.orchestrator === "running" ? "running (holds the lock)" : r.orchestrator}${r.orchestratorStats ? `; ${statsLine(r.orchestratorStats)}` : ""}`,
162
+ `orchestrator: ${r.orchestrator === "running" ? "running (holds the lock)" : r.orchestrator}${r.lastExit ? `; ${exitLine(r.lastExit)}` : ""}${r.orchestratorStats ? `; ${statsLine(r.orchestratorStats)}` : ""}`,
163
+ ...(r.pi !== undefined ? [`pi: ${r.pi ?? "not found (subagents launch \`pi\` from PATH; set DSA_PI_BIN)"}`] : []),
145
164
  `service: ${r.service}`,
146
165
  ...(r.findings.length ? [`${r.findings.length} actionable finding(s):`, ...r.findings.flatMap(f => [` ${f.kind}: ${f.detail}`, ` ${f.command}`])] : ["nothing actionable"]),
147
166
  ].join("\n");
package/dist/cli/main.js CHANGED
@@ -7,13 +7,14 @@ 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, formatUsage, renderEvent, statusDetail, statusView, workflowSnapshot, compactWorkflow, labelsText, outputSelect, statusCompactDetail } from "../orchestrator/snapshot.js";
10
+ import { 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";
14
14
  import { smoke } from "./smoke.js";
15
15
  import { serviceFiles, manageService } from "./service.js";
16
16
  import { leaseLines, leaseState } from "../platform/lease.js";
17
+ import { resolvePi } from "../platform/launch.js";
17
18
  import { currentOrchestrator, decidedBy, legacyRestart, cliInitiator, waitExit, waitSuccessor } from "./restart.js";
18
19
  import { restartInputError } from "../orchestrator/restart.js";
19
20
  const commands = ["smoke", "tail", "status", "events", "start", "resume", "drain", "stop", "stop-all", "prune", "restart", "leases", "doctor", "install-service", "uninstall-service", "help"];
@@ -100,26 +101,28 @@ export function parseArgs(args) {
100
101
  const clip = (text, n) => text.length > n ? `${text.slice(0, n)}…` : text;
101
102
  /** Notes recorded for a call that is not running (send kind "notify"); its next follow-up carries them. */
102
103
  const notesLine = (n) => n ? ` · ${n} note${n > 1 ? "s" : ""} pending` : "";
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)" : "";
103
106
  /** P25, T10: Render journal-derived status (one line per call, last output line only) without live orchestrator memory. */
104
107
  export function renderStatus(wf) {
105
108
  const sealed = wf.counts.sealed, total = wf.calls.length, used = wf.usage && (wf.usage.input || wf.usage.output || wf.usage.costUsd);
106
- return [`${wf.wid}@${wf.rev}${wf.labels ? ` ${labelsText(wf.labels)}` : ""}${wf.name ? ` ${wf.name}` : ""}: ${wf.status}${wf.error ? ` (${clip(wf.error, 300)})` : ""} · ${sealed}/${total} sealed${used ? ` · ${formatUsage(wf.usage)}` : ""}`,
109
+ 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)}` : ""}`,
107
110
  ...wf.calls.map(c => {
108
111
  const last = c.result?.output?.split("\n").map(l => l.trim()).filter(Boolean).at(-1), err = c.result?.error;
109
- return ` ${c.key}@${c.gen} ${c.result?.status ?? c.phase}${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)}`;
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)}`;
110
113
  }),
111
114
  ...wf.attention.map(a => ` ${a.kind}: ${JSON.stringify(clip(a.text, 300))}`),
112
115
  ...(wf.scriptLog ? [` script log: ${wf.scriptLog}`] : [])].join("\n");
113
116
  }
114
117
  /** `status <wid> --tail/--grep`: the workflow line, then each call with its selected output lines. */
115
118
  export function renderSelected(wf) {
116
- return [`${wf.wid}@${wf.rev}${wf.labels ? ` ${labelsText(wf.labels)}` : ""}${wf.name ? ` ${wf.name}` : ""}: ${wf.status} · ${wf.done}/${wf.planned ?? wf.calls.length} done`,
117
- ...wf.calls.flatMap(c => [` ${c.key}@${c.gen} ${c.status ?? c.phase}`, ...(c.output ? c.output.split("\n").map(l => ` | ${l}`) : [])])].join("\n");
119
+ 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.done}/${wf.planned ?? wf.calls.length} done`,
120
+ ...wf.calls.flatMap(c => [` ${c.key}@${c.gen} ${c.status ?? c.phase}${answeredNote(c, wf.paused)}`, ...(c.output ? c.output.split("\n").map(l => ` | ${l}`) : [])])].join("\n");
118
121
  }
119
122
  /** P25, T10: Render the compact status projection shared with the `subagents` tool. */
120
123
  export function renderView(view) {
121
- const lines = view.workflows.map(w => [`${w.wid}@${w.rev}${w.labels ? ` ${labelsText(w.labels)}` : ""}${w.name ? ` ${w.name}` : ""}: ${w.status}${w.followUps ? " (follow-up running)" : ""}${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)}` : ""}`,
122
- ...w.calls.map(c => ` ${c.key}@${c.gen} ${c.status ?? c.phase}${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)}`),
124
+ 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)}`),
123
126
  ...w.attention.map(a => ` ${a.kind}: ${JSON.stringify(a.text.split("\n")[0])}`)].join("\n"));
124
127
  if (view.paused)
125
128
  lines.unshift(`${view.paused} (pi-durable-subagents resume)`);
@@ -136,7 +139,7 @@ function snapshots(home, wid) {
136
139
  const snapshot = workflowSnapshot(home, wid);
137
140
  if (snapshot.startedAt === undefined)
138
141
  throw new Error(`Unknown workflow: ${wid}`);
139
- return [snapshot];
142
+ return [isLive(snapshot) && heldWorkflows(home).held(wid) ? { ...snapshot, paused: true } : snapshot];
140
143
  }
141
144
  /** P25: Follow fresh snapshots, emitting only changed human-readable workflow lines. */
142
145
  export async function tail(home, wid, write, signal, interval = 500, json = false) {
@@ -304,7 +307,10 @@ export async function main(args = process.argv.slice(2), options = {}) {
304
307
  (options.write ?? (line => console.error(line)))(refused);
305
308
  return 1;
306
309
  }
307
- const files = serviceFiles(env.HOME ?? homedir(), home, entry);
310
+ const pi = command === "install-service" ? resolvePi(env) : {};
311
+ if (command === "install-service" && !pi.path)
312
+ write(`note: ${pi.problem}; the service can start an orchestrator only once DSA_PI_BIN is set in it`);
313
+ const files = serviceFiles(env.HOME ?? homedir(), home, entry, process.platform, process.execPath, pi.path);
308
314
  await manageService(files, command === "install-service", { dryRun, runner: options.serviceRunner, write });
309
315
  files.forEach(f => write(`${command}: ${f.path}`));
310
316
  return 0;
@@ -8,7 +8,7 @@ import { readJournalSnapshot } from "../kernel/journal.js";
8
8
  import { reduceLifecycle } from "../kernel/lifecycle.js";
9
9
  import { journalPath, orchLedger, pinnedDir } from "../paths.js";
10
10
  import { batchConflict, batchDigest, findRequest, manyIds, namesMany, REQUEST_ID, requestId, requestRid, RequestsBusy, SESSION_ID, specDigest } from "../requests.js";
11
- import { NOTIFY_SINCE, isLive, orchestratorTooOld, slotsView, workflowSnapshot, writerWaits, writerWaitLine, WRITER_WAIT_HINT } from "../orchestrator/snapshot.js";
11
+ import { NOTIFY_SINCE, heldIn, isLive, orchestratorTooOld, slotsView, workflowSnapshot, writerWaits, writerWaitLine, WRITER_WAIT_HINT } from "../orchestrator/snapshot.js";
12
12
  import { leaseCalls, leaseState } from "../platform/lease.js";
13
13
  import { BATCH, checkAgents, followUpReceipt, outcomeLine, request, sendReceipt } from "../agent/main/tool.js";
14
14
  import { discoverAgents } from "../compat/agents.js";
@@ -125,7 +125,7 @@ function describeWorkflow(home, wid, entries, now) {
125
125
  const admitted = id ? run : undefined;
126
126
  const lstate = leaseState(home), slots = slotsView(home, now), leases = leaseCalls(lstate, now);
127
127
  // The same fold and decision the orchestrator's collector uses, from the disk snapshots.
128
- const waits = waitsOf(foldWaits(wid, journal), { now, ledger: foldLedger(emptyLedger(), entries), leases: leaseWaits(lstate, now) }, pinnedAgentModel(home, wid, wf.rev));
128
+ const waits = waitsOf(foldWaits(wid, journal), { now, ledger: foldLedger(emptyLedger(), entries), held: heldIn(entries), leases: leaseWaits(lstate, now) }, pinnedAgentModel(home, wid, wf.rev));
129
129
  const line = (lines, model) => { const provider = model?.split("/")[0]; return provider ? lines?.find(l => l.startsWith(`${provider} `)) : undefined; };
130
130
  const latest = [...new Map(wf.calls.map(c => [c.key, c])).values()];
131
131
  const calls = latest.map((c) => {