pi-durable-subagents 1.0.35 → 1.0.37
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 +32 -0
- package/README.md +86 -6
- package/dist/agent/main.js +3 -5
- package/dist/cli/control.js +6 -6
- package/dist/cli/doctor.js +20 -1
- package/dist/cli/main.js +15 -9
- package/dist/cli/requests.js +2 -2
- package/dist/cli/restart.js +2 -1
- package/dist/cli/service.js +6 -4
- package/dist/compat/model.js +12 -6
- package/dist/events/derive.js +13 -4
- package/dist/events/waiting.js +36 -13
- package/dist/kernel/mailbox.js +2 -0
- package/dist/orchestrator/config.js +18 -3
- package/dist/orchestrator/executor/index.js +243 -64
- package/dist/orchestrator/ledger.js +6 -3
- package/dist/orchestrator/main.js +24 -9
- package/dist/orchestrator/snapshot.js +67 -17
- package/dist/platform/launch.js +127 -0
- package/dist/platform/lease.js +58 -14
- package/dist/platform/proctable.js +6 -3
- package/dist/ui/cards.js +1 -0
- package/dist/ui/screen.js +2 -2
- package/dist/ui/tool.js +3 -3
- package/dist/ui/view.js +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,37 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 1.0.37
|
|
4
|
+
|
|
5
|
+
- The process table runs `ps` by its absolute path (`/bin/ps`), so an orchestrator started with a minimal PATH keeps
|
|
6
|
+
working on macOS.
|
|
7
|
+
- Contains every change listed under 1.0.36, which was tagged but not published (its macOS CI failed on this).
|
|
8
|
+
|
|
9
|
+
## 1.0.36
|
|
10
|
+
|
|
11
|
+
- Slot precedence among waiting calls. When a provider slot frees, a call resuming earlier work (an answered
|
|
12
|
+
question, a follow-up, a recovery) is admitted before a fresh call; among equals the origin holding fewer slots of
|
|
13
|
+
that provider goes first, then the longest waiter. A waiter holds a slot back from others only while it is still
|
|
14
|
+
trying; one that is gone (stopped, interrupted, or silent for about 3 tracker periods) is ignored.
|
|
15
|
+
- Pool entries can wait before a pool spills over to them: `{"model": "provider/id", "afterMs": 600000}` is used only
|
|
16
|
+
after the call has waited that long for the entries before it. Failover and a model request that names the pool
|
|
17
|
+
skip such entries. The wait and the resume precedence are recomputed for each execution.
|
|
18
|
+
- `status` names the slot holders of a provider by origin when more than one origin holds it.
|
|
19
|
+
- An answered question no longer shows its call as `asking` while the call waits for a slot: it is `queued` with
|
|
20
|
+
`answered: "<qid>"` (and still `hibernated`). The question's attention resolves when the answer is bound, and the
|
|
21
|
+
`answered` event is emitted then (journals written before 1.0.36 still emit it once, at resolution).
|
|
22
|
+
- A follow-up running on a finished run shows `active: true`. `status` keeps meaning the run's result, so scripts that
|
|
23
|
+
read it are unaffected; the text renderings lead with `follow-up running (run done)`.
|
|
24
|
+
- The orchestrator no longer depends on whoever started it. The starter resolves `pi` to an absolute path and passes
|
|
25
|
+
it as `DSA_PI_BIN`; `run` and `send` refuse with exit 75 when no `pi` can be found, and the submitted request stays
|
|
26
|
+
pending. On Linux with a lingering systemd user manager the orchestrator runs in its own transient scope, so the end
|
|
27
|
+
of a oneshot unit, cron job or CI step does not end it. Subagents get the orchestrator's node directory on their
|
|
28
|
+
PATH.
|
|
29
|
+
- A launch that fails because `pi` is missing or not executable (ENOENT, EACCES) keeps the call queued, raises one
|
|
30
|
+
`environment` alert, releases its slots and retries every 60 s (at once after a restart). Only one dispatch message
|
|
31
|
+
is pending however many retries fail. Other launch failures stay terminal.
|
|
32
|
+
- The orchestrator records why it exited (idle, restart, signal, error); `doctor` shows the last reason. Stale
|
|
33
|
+
temporary files in `$DSA_HOME/bin` are removed at start.
|
|
34
|
+
|
|
3
35
|
## 1.0.35
|
|
4
36
|
|
|
5
37
|
- 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`
|
|
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
|
|
@@ -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
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
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
|
package/dist/agent/main.js
CHANGED
|
@@ -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
|
-
|
|
95
|
-
|
|
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.
|
package/dist/cli/control.js
CHANGED
|
@@ -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
|
-
|
|
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. */
|
package/dist/cli/doctor.js
CHANGED
|
@@ -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.
|
|
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
|
|
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;
|
package/dist/cli/requests.js
CHANGED
|
@@ -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) => {
|
package/dist/cli/restart.js
CHANGED
|
@@ -10,6 +10,7 @@ import { hostname, userInfo } from "node:os";
|
|
|
10
10
|
import { setTimeout as delay } from "node:timers/promises";
|
|
11
11
|
import { readJournalSnapshot } from "../kernel/journal.js";
|
|
12
12
|
import { journalPath, orchLedger } from "../paths.js";
|
|
13
|
+
import { PS } from "../platform/proctable.js";
|
|
13
14
|
import { JT } from "../types.js";
|
|
14
15
|
import { restartInputError, restartRefusal } from "../orchestrator/restart.js";
|
|
15
16
|
import { emptyLedger, foldLedger } from "../orchestrator/ledger.js";
|
|
@@ -26,7 +27,7 @@ export function cliInitiator(env) {
|
|
|
26
27
|
let parent = "";
|
|
27
28
|
try {
|
|
28
29
|
parent = process.platform === "linux" ? readFileSync(`/proc/${process.ppid}/cmdline`, "utf8").replace(/\0/g, " ").trim()
|
|
29
|
-
: process.platform === "darwin" ? execFileSync(
|
|
30
|
+
: process.platform === "darwin" ? execFileSync(PS, ["-o", "command=", "-p", String(process.ppid)], { encoding: "utf8", timeout: 1000, maxBuffer: 64 * 1024 }).trim() : "";
|
|
30
31
|
}
|
|
31
32
|
catch { /* Parent may have exited or /proc may be unavailable. */ }
|
|
32
33
|
return { cli: { user: userInfo().username, host: hostname(), ppid: process.ppid, parent: parent.slice(0, 200) } };
|
package/dist/cli/service.js
CHANGED
|
@@ -7,17 +7,19 @@ import { syncDirectory } from "../kernel/journal.js";
|
|
|
7
7
|
const name = "pi-durable-subagents";
|
|
8
8
|
const quote = (s, exec = true) => `"${s.replace(/[%$\\"\n\r]/g, c => c === "$" ? exec ? "$$" : "$" : ({ "%": "%%", "\\": "\\\\", '"': '\\"', "\n": "\\n", "\r": "\\r" })[c])}"`;
|
|
9
9
|
const xml = (s) => s.replace(/[&<>"']/g, c => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c]);
|
|
10
|
-
/** P1, K1: Render a login and 30-second starter using absolute runtime paths; it runs `start`, never `resume`.
|
|
11
|
-
|
|
10
|
+
/** P1, K1: Render a login and 30-second starter using absolute runtime paths; it runs `start`, never `resume`. `pi`
|
|
11
|
+
* (resolved when installing) becomes its DSA_PI_BIN: a service manager's PATH rarely has pi, and without one `start`
|
|
12
|
+
* refuses to start an orchestrator. */
|
|
13
|
+
export function serviceFiles(home, dsa, entry, platform = process.platform, node = process.execPath, pi) {
|
|
12
14
|
if (platform === "linux") {
|
|
13
15
|
const dir = join(home, ".config/systemd/user");
|
|
14
16
|
return [
|
|
15
|
-
{ path: join(dir, `${name}.service`), content: `[Unit]\nDescription=Durable subagents starter\n\n[Service]\nType=oneshot\n# Keep the detached orchestrator alive after the starter exits.\nKillMode=process\nEnvironment=${quote(`DSA_HOME=${dsa}`, false)}\
|
|
17
|
+
{ path: join(dir, `${name}.service`), content: `[Unit]\nDescription=Durable subagents starter\n\n[Service]\nType=oneshot\n# Keep the detached orchestrator alive after the starter exits.\nKillMode=process\nEnvironment=${quote(`DSA_HOME=${dsa}`, false)}\n${pi ? `Environment=${quote(`DSA_PI_BIN=${pi}`, false)}\n` : ""}ExecStart=${quote(node)} ${quote(entry)} start\n` },
|
|
16
18
|
{ path: join(dir, `${name}.timer`), content: `[Unit]\nDescription=Durable subagents periodic starter\n\n[Timer]\nOnStartupSec=1s\nOnUnitActiveSec=30s\nAccuracySec=1s\nUnit=${name}.service\n\n[Install]\nWantedBy=timers.target\n` },
|
|
17
19
|
];
|
|
18
20
|
}
|
|
19
21
|
if (platform === "darwin")
|
|
20
|
-
return [{ path: join(home, "Library/LaunchAgents", `${name}.plist`), content: `<?xml version="1.0" encoding="UTF-8"?>\n<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">\n<plist version="1.0"><dict>\n<key>Label</key><string>${name}</string>\n<key>ProgramArguments</key><array>${[node, entry, "start"].map(s => `<string>${xml(s)}</string>`).join("")}</array>\n<key>EnvironmentVariables</key><dict><key>DSA_HOME</key><string>${xml(dsa)}</string
|
|
22
|
+
return [{ path: join(home, "Library/LaunchAgents", `${name}.plist`), content: `<?xml version="1.0" encoding="UTF-8"?>\n<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">\n<plist version="1.0"><dict>\n<key>Label</key><string>${name}</string>\n<key>ProgramArguments</key><array>${[node, entry, "start"].map(s => `<string>${xml(s)}</string>`).join("")}</array>\n<key>EnvironmentVariables</key><dict><key>DSA_HOME</key><string>${xml(dsa)}</string>${pi ? `<key>DSA_PI_BIN</key><string>${xml(pi)}</string>` : ""}</dict>\n<key>RunAtLoad</key><true/>\n<!-- Keep the detached orchestrator alive after the starter exits. -->\n<key>AbandonProcessGroup</key><true/>\n<key>StartInterval</key><integer>30</integer>\n</dict></plist>\n` }];
|
|
21
23
|
throw new Error(`Starter service unavailable on ${platform}`);
|
|
22
24
|
}
|
|
23
25
|
/** P1: Invoke the platform service manager, surfacing the exact failed command. */
|
package/dist/compat/model.js
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
export const thinkingLevels = ["off", "minimal", "low", "medium", "high", "xhigh", "max"];
|
|
2
|
+
/** The model without scheduling fields, as recorded and launched. */
|
|
3
|
+
export const plainModel = (m) => ({ ...(m.provider !== undefined ? { provider: m.provider } : {}), id: m.id, ...(m.thinking ? { thinking: m.thinking } : {}) });
|
|
2
4
|
/** P35: Parse Pi model identifiers, preserving colons that are not thinking suffixes. */
|
|
3
5
|
export function parseModel(value) {
|
|
4
6
|
let id = value.trim();
|
|
@@ -13,17 +15,21 @@ export function parseModel(value) {
|
|
|
13
15
|
throw new Error(`Invalid model: ${value}`);
|
|
14
16
|
return { ...(slash < 0 ? {} : { provider: id.slice(0, slash) }), id: slash < 0 ? id : id.slice(slash + 1), ...(thinking ? { thinking } : {}) };
|
|
15
17
|
}
|
|
16
|
-
/** P11, P35: Resolve a pool into ordered candidates without making an unrecorded selection.
|
|
18
|
+
/** P11, P35: Resolve a pool into ordered candidates without making an unrecorded selection. An object entry's
|
|
19
|
+
* `afterMs` applies to every model it expands to; nested ones keep the larger value. */
|
|
17
20
|
export function resolveModel(value, pools = {}) {
|
|
18
|
-
const expand = (name, seen) => {
|
|
19
|
-
if (!Object.hasOwn(pools, name))
|
|
20
|
-
|
|
21
|
+
const expand = (name, seen, after) => {
|
|
22
|
+
if (!Object.hasOwn(pools, name)) {
|
|
23
|
+
const m = parseModel(name);
|
|
24
|
+
return [after > 0 ? { ...m, afterMs: after } : m];
|
|
25
|
+
}
|
|
21
26
|
if (seen.has(name))
|
|
22
27
|
throw new Error(`Cyclic model pool: ${name}`);
|
|
23
28
|
const entries = pools[name];
|
|
24
29
|
if (!entries.length)
|
|
25
30
|
throw new Error(`Empty model pool: ${name}`);
|
|
26
|
-
return entries.flatMap(entry => expand(entry, new Set([...seen, name]))
|
|
31
|
+
return entries.flatMap(entry => typeof entry === "string" ? expand(entry, new Set([...seen, name]), after)
|
|
32
|
+
: expand(entry.model, new Set([...seen, name]), Math.max(after, entry.afterMs ?? 0)));
|
|
27
33
|
};
|
|
28
|
-
return expand(value.trim(), new Set());
|
|
34
|
+
return expand(value.trim(), new Set(), 0);
|
|
29
35
|
}
|
package/dist/events/derive.js
CHANGED
|
@@ -104,19 +104,28 @@ export function deriveEntry(wid, entries, i, orch, id) {
|
|
|
104
104
|
const parts = callParts(item.call);
|
|
105
105
|
return [{ ...base("asking"), type: "asking", ...onCall(item.call), qid: item.qid, rev: item.rev, question: item.text, to: `${wid}/${parts?.key ?? ""}` }];
|
|
106
106
|
}
|
|
107
|
-
|
|
108
|
-
|
|
107
|
+
// `answered` at the binding of an answer when that `answer-bound` is marked `event: true` (written so from 1.0.36 on);
|
|
108
|
+
// otherwise (an older journal) at the question's `attention-resolved{answered}`, as before, so a rebuilt event log
|
|
109
|
+
// keeps the events (and ids) an older version derived.
|
|
110
|
+
if (e.type === "answer-bound" && e.event === true || isEntry(e, JT.attentionResolved)) {
|
|
111
|
+
const bound = e.type === "answer-bound";
|
|
112
|
+
if (!bound && e.resolution !== "answered")
|
|
109
113
|
return [];
|
|
114
|
+
const questionId = bound ? `q:${e.call}:${e.qid}` : e.id;
|
|
110
115
|
let item;
|
|
111
116
|
for (let j = i - 1; j >= 0 && !item; j--) {
|
|
112
117
|
const a = entries[j];
|
|
113
|
-
if (isEntry(a, JT.attention) && a.item.id ===
|
|
118
|
+
if (isEntry(a, JT.attention) && a.item.id === questionId && a.item.rev === e.rev)
|
|
114
119
|
item = a;
|
|
115
120
|
}
|
|
116
121
|
const q = item?.item;
|
|
117
122
|
if (!q || q.kind !== "question" || !q.call || q.qid === undefined)
|
|
118
123
|
return [];
|
|
119
|
-
|
|
124
|
+
// A marked binding reports answered immediately; the resolution after it, or a duplicate resolution, reports nothing.
|
|
125
|
+
if (entries.slice(0, i).some(a => a.type === "answer-bound" && a.event === true && a.call === q.call && a.qid === q.qid && a.rev === q.rev ||
|
|
126
|
+
a.type === JT.attentionResolved && a.id === q.id && a.rev === q.rev && a.resolution === "answered"))
|
|
127
|
+
return [];
|
|
128
|
+
const answer = answerOf(entries, bound ? i + 1 : i, before(orch, e), q.call, q.qid, q.rev);
|
|
120
129
|
return [{ ...base("answered"), type: "answered", ...onCall(q.call), qid: q.qid, rev: q.rev, ...answeredBy(answer.request),
|
|
121
130
|
digest: createHash("sha256").update(answer.text, "utf8").digest("hex"), length: answer.text.length }];
|
|
122
131
|
}
|
package/dist/events/waiting.js
CHANGED
|
@@ -19,13 +19,12 @@
|
|
|
19
19
|
// silent an open `stall:`/`noprogress:` attention item (kind stall; its text names the running command) of
|
|
20
20
|
// the current execution while it works (selected, not fenced): a drained call is not waiting.
|
|
21
21
|
// An asking call is not waiting, a sealed one never. Asking = an open question raised in the call's current execution
|
|
22
|
-
// (the call's latest `exec` before the question's attention entry is its current one), hibernated or not
|
|
23
|
-
// answer
|
|
24
|
-
// the new execution reads it (describe's `state: "asking"` still follows the open item).
|
|
22
|
+
// (the call's latest `exec` before the question's attention entry is its current one), hibernated or not. Binding an
|
|
23
|
+
// answer closes that question immediately and queues the call; its waits count before its next execution starts.
|
|
25
24
|
import { JT } from "../types.js";
|
|
26
25
|
import { EVENT_SEQ_SKIP, WAIT_REASONS } from "./types.js";
|
|
27
26
|
import { emptyLedger, foldLedger, settingsOf } from "../orchestrator/ledger.js";
|
|
28
|
-
import { exhaustedLine, slotLine } from "../orchestrator/snapshot.js";
|
|
27
|
+
import { exhaustedLine, heldIn, slotLine } from "../orchestrator/snapshot.js";
|
|
29
28
|
import { parseModel, resolveModel } from "../compat/model.js";
|
|
30
29
|
import { leaseCalls, leaseState } from "../platform/lease.js";
|
|
31
30
|
import { requestId } from "../requests.js";
|
|
@@ -86,10 +85,19 @@ function applyWait(f, e) {
|
|
|
86
85
|
case JT.done:
|
|
87
86
|
f.done = true;
|
|
88
87
|
break;
|
|
89
|
-
case "resumed":
|
|
88
|
+
case "resumed": {
|
|
90
89
|
if (!e.call)
|
|
91
90
|
f.done = false;
|
|
91
|
+
else {
|
|
92
|
+
const c = f.calls.get(String(e.call));
|
|
93
|
+
if (c && (!e.exec || c.exec === e.exec)) {
|
|
94
|
+
c.selected = true;
|
|
95
|
+
c.fenced = false;
|
|
96
|
+
delete c.answered;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
92
99
|
break;
|
|
100
|
+
}
|
|
93
101
|
case "call":
|
|
94
102
|
case "generation": {
|
|
95
103
|
const key = String(e.key), gen = Number(e.gen) || 1, call = `${f.wid}@${f.rev}/${key}@${gen}`, spec = e.spec;
|
|
@@ -104,6 +112,17 @@ function applyWait(f, e) {
|
|
|
104
112
|
c.queued = e.ts;
|
|
105
113
|
c.selected = false;
|
|
106
114
|
c.fenced = false;
|
|
115
|
+
delete c.answered;
|
|
116
|
+
}
|
|
117
|
+
break;
|
|
118
|
+
}
|
|
119
|
+
case "answer-bound": {
|
|
120
|
+
const c = f.calls.get(String(e.call)), id = `q:${e.call}:${e.qid}`, item = f.items.get(id);
|
|
121
|
+
if (item?.rev === e.rev)
|
|
122
|
+
f.items.delete(id);
|
|
123
|
+
if (c) {
|
|
124
|
+
c.answered = String(e.qid);
|
|
125
|
+
c.queued = e.ts;
|
|
107
126
|
}
|
|
108
127
|
break;
|
|
109
128
|
}
|
|
@@ -112,8 +131,10 @@ function applyWait(f, e) {
|
|
|
112
131
|
const c = ofExec(f, e.exec), model = modelName(e.model);
|
|
113
132
|
if (c && model)
|
|
114
133
|
c.model = model;
|
|
115
|
-
if (c && e.type === "selected")
|
|
134
|
+
if (c && e.type === "selected") {
|
|
116
135
|
c.selected = true;
|
|
136
|
+
delete c.answered;
|
|
137
|
+
}
|
|
117
138
|
break;
|
|
118
139
|
}
|
|
119
140
|
case JT.fenced: {
|
|
@@ -191,7 +212,9 @@ catch {
|
|
|
191
212
|
} };
|
|
192
213
|
/** The call's state as `whyWaiting` reads it. `agentModel` names the model of a pinned agent (for a call naming none). */
|
|
193
214
|
export function waitInput(f, c, env, agentModel) {
|
|
194
|
-
|
|
215
|
+
// An answered asker is queued (live) although its hibernated execution is fenced, unless a drain holds its workflow.
|
|
216
|
+
const answered = c.answered !== undefined && !env.held?.(f.wid);
|
|
217
|
+
const settings = settingsOf(env.ledger, env.config ?? {}), live = c.exec && (!c.fenced || answered), selected = c.selected && c.answered === undefined;
|
|
195
218
|
const attention = [];
|
|
196
219
|
let asking = false;
|
|
197
220
|
for (const [id, item] of f.items)
|
|
@@ -201,7 +224,7 @@ export function waitInput(f, c, env, agentModel) {
|
|
|
201
224
|
asking = true;
|
|
202
225
|
}
|
|
203
226
|
let providers = [];
|
|
204
|
-
if (live &&
|
|
227
|
+
if (live && selected) {
|
|
205
228
|
const p = providerOf(c.model);
|
|
206
229
|
if (p)
|
|
207
230
|
providers = [p];
|
|
@@ -222,8 +245,8 @@ export function waitInput(f, c, env, agentModel) {
|
|
|
222
245
|
providers = [p];
|
|
223
246
|
}
|
|
224
247
|
}
|
|
225
|
-
let full = live && !
|
|
226
|
-
const slot = live && !
|
|
248
|
+
let full = live && !selected && providers.length > 0;
|
|
249
|
+
const slot = live && !selected && providers.length ? providers.map(p => {
|
|
227
250
|
let held = 0;
|
|
228
251
|
for (const h of env.ledger.held.values())
|
|
229
252
|
if (h.pool === p)
|
|
@@ -233,10 +256,10 @@ export function waitInput(f, c, env, agentModel) {
|
|
|
233
256
|
full = false;
|
|
234
257
|
return slotLine(p, held, limit);
|
|
235
258
|
}).join(", ") : undefined;
|
|
236
|
-
const lease = live &&
|
|
259
|
+
const lease = live && selected ? env.leases?.get(c.call) : undefined;
|
|
237
260
|
return {
|
|
238
261
|
asking,
|
|
239
|
-
...(live ? { exec: { id: c.exec, since: c.queued ?? 0, selected: !!
|
|
262
|
+
...(live ? { exec: { id: c.exec, since: c.queued ?? 0, selected: !!selected } } : {}),
|
|
240
263
|
...(providers.length ? { providers } : {}), exhausted: env.ledger.exhausted,
|
|
241
264
|
...(c.writer ? { writerWait: c.writer } : {}), ...(lease ? { lease } : {}),
|
|
242
265
|
...(attention.length ? { attention } : {}), ...(slot ? { slot } : {}), ...(full ? { full } : {}),
|
|
@@ -385,7 +408,7 @@ export function waitCollector(src) {
|
|
|
385
408
|
foldLedger(ledger, orch);
|
|
386
409
|
foldRuns(orch);
|
|
387
410
|
let leases;
|
|
388
|
-
const env = { now, ledger, ...(src.config ? { config: src.config } : {}), get leases() { return leases ??= leaseWaits((src.leases ?? (() => leaseState(src.home)))(), now); } };
|
|
411
|
+
const env = { now, ledger, held: heldIn(orch), ...(src.config ? { config: src.config } : {}), get leases() { return leases ??= leaseWaits((src.leases ?? (() => leaseState(src.home)))(), now); } };
|
|
389
412
|
const current = new Map(), meta = new Map(), present = new Set();
|
|
390
413
|
for (const wf of src.workflows()) {
|
|
391
414
|
present.add(wf.wid);
|