pi-durable-subagents 1.0.33 → 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 +54 -0
- package/README.md +97 -8
- package/dist/agent/main/tool.js +26 -1
- package/dist/agent/main.js +6 -8
- 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 +9 -10
- 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/engine.js +77 -20
- package/dist/orchestrator/executor/index.js +248 -66
- package/dist/orchestrator/ledger.js +6 -3
- package/dist/orchestrator/main.js +24 -9
- package/dist/orchestrator/notes.js +27 -0
- 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 +4 -3
- 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,59 @@
|
|
|
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
|
+
|
|
35
|
+
## 1.0.35
|
|
36
|
+
|
|
37
|
+
- Generation openings of one workflow are serialized. The reopen of undelivered follow-ups at orchestrator start, the
|
|
38
|
+
one after each seal and a follow-up sent to a sealed call could each find the same key unopened and open its next
|
|
39
|
+
generation twice (seen after a restart while a reopened generation sealed). A follow-up that finds a generation
|
|
40
|
+
opened meanwhile is deferred and then reaches that generation.
|
|
41
|
+
- Releases publish to npm through trusted publishing (OIDC, no token) from the `npm` environment, with provenance.
|
|
42
|
+
Workflows run with read-only permissions by default.
|
|
43
|
+
|
|
44
|
+
## 1.0.34
|
|
45
|
+
|
|
46
|
+
- A follow-up queued into running work is no longer lost when that generation ends before taking it. The next
|
|
47
|
+
generation opens with it, after any pending notes. A follow-up sent to the finished call in the meantime takes the
|
|
48
|
+
queued ones along, in the order sent (`generation.follows`). Restarts open it once. Only a stop drops it, because
|
|
49
|
+
a stop is final; a withdrawn one is gone too. The executor marks such a forward `forward-retired` with reason
|
|
50
|
+
`undelivered-follow-up`.
|
|
51
|
+
- The send reply says where a follow-up went. One that opened a generation has `generation` and `call`, from the CLI
|
|
52
|
+
and now also from the pi tool. One queued into running work has `delivery: "forwarded"` and
|
|
53
|
+
`call: "<wid>/<key>@<gen>"`. A retry of the same request names the generation it went into.
|
|
54
|
+
- Typing in the watch view to a finished subagent sends a follow-up. Before, it sent a steer, which the orchestrator
|
|
55
|
+
refused with `finished:<status> — use kind "follow-up"`.
|
|
56
|
+
|
|
3
57
|
## 1.0.33
|
|
4
58
|
|
|
5
59
|
- A run copies its origin session branch only when it can use it: its script
|
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
|
|
@@ -119,7 +121,7 @@ it something. Each verb means one thing, and a refusal says what would work:
|
|
|
119
121
|
| `run` | — | Start one subagent, `tasks` in parallel, a `chain`, or a workflow script. An unknown agent name is refused before anything starts, with the list of agents. |
|
|
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
|
-
| `send follow-up` |
|
|
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
125
|
| `send answer` | an open question | Answers it once. |
|
|
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. |
|
|
@@ -142,6 +144,14 @@ requests. A notify accepted for a running call that seals before it gets the
|
|
|
142
144
|
note becomes a pending note too. `status` shows them on the call
|
|
143
145
|
(`b@1 ok "..." · 2 notes pending`; JSON `notesPending`).
|
|
144
146
|
|
|
147
|
+
A follow-up queued into running work is not lost when that generation ends
|
|
148
|
+
before taking it: the next generation opens with it, after any pending notes,
|
|
149
|
+
as if it had been sent just after the end. A follow-up sent to the finished call
|
|
150
|
+
in the meantime opens that generation and takes the queued ones along (in the
|
|
151
|
+
order sent, before its own message). A retry of the same request then names the
|
|
152
|
+
generation it went into. Only a stop drops it, because a stop is final; a
|
|
153
|
+
withdrawn follow-up is gone too.
|
|
154
|
+
|
|
145
155
|
`to` may list several calls for `steer`, `notify`, `follow-up` and `model`
|
|
146
156
|
(`answer` takes one). Each call gets its own request and is decided on its
|
|
147
157
|
own: an unknown or refused target does not affect the others, and the reply
|
|
@@ -229,7 +239,8 @@ subagents of one workflow. Scrolling up pauses following; pi's
|
|
|
229
239
|
`↓ Jump to latest message · End` badge (or `End`, or a click) brings you back.
|
|
230
240
|
|
|
231
241
|
Typing steers the subagent you are watching (`Alt+Enter` queues a
|
|
232
|
-
follow-up instead),
|
|
242
|
+
follow-up instead), answers it if it is asking you something, and continues
|
|
243
|
+
it (a follow-up) if it has finished. `/model`
|
|
233
244
|
switches its model. Steers, answers and model switches are journaled as
|
|
234
245
|
coming from you, and the main agent sees a note at its next turn.
|
|
235
246
|
|
|
@@ -523,10 +534,13 @@ that applies wins:
|
|
|
523
534
|
| `silent` | is running (launched, not stopped) without visible activity: the stall notice of that execution, with the command running and for how long |
|
|
524
535
|
|
|
525
536
|
A call whose current execution asked a question (also while it hibernates
|
|
526
|
-
until the answer) is `asking`, not waiting. Once
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
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
|
|
530
544
|
(no execution running) is never `silent`; a sealed call never waits. `provider-exhausted`, `writer-lock`, `lease` and `slot` are queues
|
|
531
545
|
that clear by themselves; `silent` and `unconfirmed-stop` may need a look.
|
|
532
546
|
|
|
@@ -563,6 +577,58 @@ read, in a burst each time a call ends), `pid` and `at` (when it was
|
|
|
563
577
|
written). The orchestrator writes these to `orchestrator-stats.json` every
|
|
564
578
|
10 s; they are shown only while that process runs.
|
|
565
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
|
+
|
|
566
632
|
### Resource leases
|
|
567
633
|
|
|
568
634
|
Benchmarks, timing measurements and big builds need the machine to
|
|
@@ -645,6 +711,17 @@ State lives in `~/.pi/durable-subagents`; set `DSA_HOME` to move it.
|
|
|
645
711
|
file or a model send). The first candidate with a free slot is
|
|
646
712
|
used, and a candidate that keeps failing is skipped for 10 minutes. The
|
|
647
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.
|
|
648
725
|
- **A used-up provider** is not sent new calls until its next try, 15 minutes
|
|
649
726
|
after it last refused (`"k": { "probeMs": 900000 }`). Then one call at a
|
|
650
727
|
time goes to it, so finding out costs no extra request. A call that moved to
|
|
@@ -668,7 +745,19 @@ State lives in `~/.pi/durable-subagents`; set `DSA_HOME` to move it.
|
|
|
668
745
|
Interrupted (Ctrl-C), it stops what it started and cleans up the same way
|
|
669
746
|
(exit 130, or 143 for SIGTERM).
|
|
670
747
|
- **Provider slots:** never exceeded, including while a model switch is in
|
|
671
|
-
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)`.
|
|
672
761
|
- **Memory:** new subagents wait while memory is short. Running ones are
|
|
673
762
|
never stopped for memory.
|
|
674
763
|
- **Writer lock:** `"queue"` (default) runs one writing call per git
|
package/dist/agent/main/tool.js
CHANGED
|
@@ -1,5 +1,9 @@
|
|
|
1
1
|
import { restartInputError } from "../../orchestrator/restart.js";
|
|
2
|
+
import { existsSync } from "node:fs";
|
|
2
3
|
import { resolve } from "node:path";
|
|
4
|
+
import { readJournalSnapshot } from "../../kernel/journal.js";
|
|
5
|
+
import { generationRids } from "../../orchestrator/notes.js";
|
|
6
|
+
import { journalPath } from "../../paths.js";
|
|
3
7
|
import { validateCallSpec } from "../../compat/spec.js";
|
|
4
8
|
import { compileFanout } from "../../compat/fanout.js";
|
|
5
9
|
import { checkLabels } from "../../events/labels.js";
|
|
@@ -43,12 +47,33 @@ export function sendReceipt(ledger, rid) {
|
|
|
43
47
|
return { delivery: note.delivery, note: DELIVERY_NOTE[note.delivery] ?? note.delivery };
|
|
44
48
|
return { model: String(note.model), effect: String(note.effect), ...(note.pool ? { pool: String(note.pool) } : {}) };
|
|
45
49
|
}
|
|
50
|
+
/** Where an applied follow-up went. It opened a generation: `generation` and `call` (`<wid>/<key>`), from the workflow
|
|
51
|
+
* journal, under the request's rid or, for one forwarded into running work that sealed first, in `follows` of the
|
|
52
|
+
* generation that took it along. It was queued into unfinished work: `delivery: "forwarded"` and `call`
|
|
53
|
+
* (`<wid>/<key>@<gen>`, the running generation). If that generation ends before taking it, the message opens the next
|
|
54
|
+
* generation (unless a stop ended it), and a retry of the same request then names that generation. */
|
|
55
|
+
export function followUpReceipt(home, rid, body) {
|
|
56
|
+
const send = body;
|
|
57
|
+
if (send?.kind !== "follow-up" || typeof send.to !== "string")
|
|
58
|
+
return {};
|
|
59
|
+
const wid = send.to.split("/")[0].split("@")[0], path = journalPath(home, wid);
|
|
60
|
+
if (!existsSync(path))
|
|
61
|
+
return {};
|
|
62
|
+
const log = readJournalSnapshot(path), opened = log.find(e => e.type === "generation" && generationRids(e).includes(rid));
|
|
63
|
+
if (opened)
|
|
64
|
+
return { generation: Number(opened.gen), call: `${wid}/${String(opened.key)}` };
|
|
65
|
+
const queued = log.find(e => e.type === "forward" && e.rid === rid);
|
|
66
|
+
if (!queued)
|
|
67
|
+
return {};
|
|
68
|
+
const into = `${wid}/${String(queued.dest).slice(String(queued.dest).indexOf("/") + 1)}`;
|
|
69
|
+
return { delivery: "forwarded", call: into, note: `queued into running ${into}; if it ends before taking it, it opens the next generation` };
|
|
70
|
+
}
|
|
46
71
|
/** The internal argument through which a send to several calls passes its `batch` (not a tool parameter). */
|
|
47
72
|
export const BATCH = Symbol("batch");
|
|
48
73
|
/** One line of a reply per target: applied (with how a notify went), rejected with its reason, or not decided yet. */
|
|
49
74
|
export function outcomeLine(r) {
|
|
50
75
|
if (r.applied === true)
|
|
51
|
-
return `applied${r.delivery ? ` (${String(r.delivery)}: ${String(r.note)})` : r.effect ? ` (model ${String(r.model)}, ${String(r.effect)})` : ""}`;
|
|
76
|
+
return `applied${r.generation !== undefined ? ` (follow-up generation ${String(r.generation)} of ${String(r.call)})` : ""}${r.delivery ? ` (${String(r.delivery)}: ${String(r.note)})` : r.effect ? ` (model ${String(r.model)}, ${String(r.effect)})` : ""}`;
|
|
52
77
|
if (r.applied === false)
|
|
53
78
|
return `rejected ${String(r.reason)}`;
|
|
54
79
|
if (r.submitted)
|
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,11 +8,12 @@ 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";
|
|
15
15
|
import { NOTIFY_SINCE, isLive, orchestratorTooOld, pausedElsewhere, runningOrchestrator, statusBrief, statusCallDetail, statusCompactDetail, statusDetail, statusView, widOfRid, outputSelect, writerWaits, writerWaitLine, WRITER_WAIT_HINT } from "../orchestrator/snapshot.js";
|
|
16
|
-
import { BATCH, checkAgents, outcomeLine, request, sendReceipt } from "./main/tool.js";
|
|
16
|
+
import { BATCH, checkAgents, followUpReceipt, outcomeLine, request, sendReceipt } from "./main/tool.js";
|
|
17
17
|
import { parameters } from "./main/schema.js";
|
|
18
18
|
import { batchConflict, batchDigest, findRequest, manyIds, namesMany, requestRid, sendIdentified } from "../requests.js";
|
|
19
19
|
import { discoverAgents } from "../compat/agents.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.
|
|
@@ -413,7 +411,7 @@ export function registerMain(pi, ui) {
|
|
|
413
411
|
if (decision.type === "rejected")
|
|
414
412
|
return { applied: false, reason: sent.kind === "resume" && args.wid === undefined ? resumeElsewhere(String(decision.reason)) : decision.reason, rid: sent.rid };
|
|
415
413
|
if (sent.kind !== "run") {
|
|
416
|
-
return { applied: true, rid: sent.rid, ...sendReceipt(ledger(), sent.rid) };
|
|
414
|
+
return { applied: true, rid: sent.rid, ...followUpReceipt(home, sent.rid, sent.body), ...sendReceipt(ledger(), sent.rid) };
|
|
417
415
|
}
|
|
418
416
|
}
|
|
419
417
|
if (performance.now() >= deadline || signal?.aborted)
|
|
@@ -435,7 +433,7 @@ export function registerMain(pi, ui) {
|
|
|
435
433
|
"Durable asynchronous subagents; run returns {wid} when created (or {submitted:{rid}} while pending). A finished workflow (its notice carries every agent's result) or a question wakes you, so after starting work end your turn: never poll with sleep or repeated status. Crash recovery resumes sessions, not external side effects. Background helper processes (orchestrator, evaluator) exit by themselves about 10 s after all work ends: never kill processes or delete files to 'clean up'. When the user quits pi, this session's running workflows pause (nothing is spent); resume continues them.",
|
|
436
434
|
"run (action optional for exactly one launch form): agent+task; tasks:[call specs] parallel; chain:[call specs] sequential ({previous}); workflow:'./script.js' or source (runs.run(key,spec), runs.all([...]), emit(value), args, runs.input(name)). Optional name, cwd, usageBudget, maxCalls, inputs, labels. With tasks/chain, top-level agent (without task), model, timeoutMs, budget, isolation, context, tools, skills, once, writer are defaults for every step (a step's own value wins); a workflow/source script sets them per runs.run call. timeoutMs is milliseconds of active time (a number); omit it unless a hard limit is needed. Explicit unknown agents are rejected BEFORE creation, with available names; unknown script agents fail only their call.",
|
|
437
435
|
"agents: list names, descriptions, default models and source for this cwd; use these names for run.",
|
|
438
|
-
"send to:'<wid>/<key>' (bare '<wid>' only for a single-call workflow): steer on a running call delivers at the next safe point (receipt in status/UI); a steer to a call waiting on its question interrupts the question and the subagent usually asks again — use answer to answer it; sealed → finished:<status> — use kind 'follow-up'. notify tells a call a decision without disturbing it; the reply's delivery says how: steered (running: it gets the note at its next safe point), held-until-answer (waiting on its question: never interrupts it, delivered after the answer) or noted (not running: nothing starts; the note is recorded and the call's next follow-up opens with every pending note; status shows notesPending). to may list several calls for steer, notify, follow-up and model: one request per call, each decided on its own, one result line per target (request:<id> sends <id>:1...<id>:n; a retry with the same list is safe). follow-up continues a sealed call as generation g+1 or queues after a running turn; follow-up model:'provider/id' or a pool name runs that generation on it. answer: give the qid (or just the call, or nothing when one question is open); to and rev are filled in. A question that needs the user's decision goes to the user; if you answer one yourself, tell the user what you chose. model ('provider/id' or a pool name — its first model not used up): a running call switches at its next provider request; an asking, hibernated or queued call launches on it when it runs again; the reply's model/effect (next-request|next-execution|next-generation) says which. status model = model actually used by the last request; switching = requested, not used yet; switchFailed = refused. A provider content refusal (ToS/usage policy) fails the call at once, not retried. Unknown targets list valid addresses. replaces:[rid] supersedes an earlier send.",
|
|
436
|
+
"send to:'<wid>/<key>' (bare '<wid>' only for a single-call workflow): steer on a running call delivers at the next safe point (receipt in status/UI); a steer to a call waiting on its question interrupts the question and the subagent usually asks again — use answer to answer it; sealed → finished:<status> — use kind 'follow-up'. notify tells a call a decision without disturbing it; the reply's delivery says how: steered (running: it gets the note at its next safe point), held-until-answer (waiting on its question: never interrupts it, delivered after the answer) or noted (not running: nothing starts; the note is recorded and the call's next follow-up opens with every pending note; status shows notesPending). to may list several calls for steer, notify, follow-up and model: one request per call, each decided on its own, one result line per target (request:<id> sends <id>:1...<id>:n; a retry with the same list is safe). follow-up continues a sealed call as generation g+1 (reply generation) or queues after a running turn (reply delivery forwarded; if that turn ends without taking it, it opens g+1); follow-up model:'provider/id' or a pool name runs that generation on it. answer: give the qid (or just the call, or nothing when one question is open); to and rev are filled in. A question that needs the user's decision goes to the user; if you answer one yourself, tell the user what you chose. model ('provider/id' or a pool name — its first model not used up): a running call switches at its next provider request; an asking, hibernated or queued call launches on it when it runs again; the reply's model/effect (next-request|next-execution|next-generation) says which. status model = model actually used by the last request; switching = requested, not used yet; switchFailed = refused. A provider content refusal (ToS/usage policy) fails the call at once, not retried. Unknown targets list valid addresses. replaces:[rid] supersedes an earlier send.",
|
|
439
437
|
"stop target:<wid|<wid>/<key>> is terminal stopped (usage and partial edits kept); a sealed call → already-sealed:<status>, a finished workflow → terminal:<status>. drain holds existing workflows reversibly (new runs unaffected); resume [wid] releases held workflows. restart (after an update) replaces the orchestrator with the installed version: refused with busy:<running executions> while any runs. Never force without the user's explicit approval: show the user the refusal's list first, then supply force:'<token>' and reason. Subagents cannot force; hibernated askers and queued calls do not block it. Never kill the orchestrator process. Commands that need the machine (benchmarks, timing) take a lease: tell the subagent to run them as `pi-durable-subagents hold machine [--shared] -- <command>` (FIFO; `hold <name> --slots N` admits N at a time; status lists lease holders and waiters). status: without wid, what runs (with its run labels, clipped), asks (with its answer address; hibernated:true holds no slot) or failed, writerWait: a call queued for its git worktree's writer lock (one call whose tools include edit/write runs per worktree; spec writer:false or isolation:'worktree' opts out), sharedWorktree names calls sharing observed edit/write roots (reminder), lease: a call holding or waiting for a resource lease, finished workflows one line each, provider slots held/limit, the config in effect and providers whose usage window is used up (avoided until a probe finds them answering again), and the orchestrator version (versionNote when it differs from the loaded one); wid: one workflow, outputs clipped; wid+tail:N: the last N lines of each call's result, wid+grep:'<regex>': only its matching lines (a JS regex run in-process: avoid nested quantifiers like (a+)+; first 2000 chars of a line, last 5000 lines; both: grep, then tail; at most 4000 chars per call); wid+key: one call's full result; full:true: everything. A run reply names calls already queued behind a writer lock (writerWait). A run's rid from {submitted:{rid}} works wherever a wid is expected. revise wid + workflow/source/args starts a revision.",
|
|
440
438
|
"Control replies are {applied:true,rid} or {applied:false,reason,rid} when decided; otherwise {submitted:{rid}} after 10s.",
|
|
441
439
|
...(agents ? [`Available agents: ${agents}.`] : []),
|
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,9 +8,9 @@ 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
|
-
import { BATCH, checkAgents, outcomeLine, request, sendReceipt } from "../agent/main/tool.js";
|
|
13
|
+
import { BATCH, checkAgents, followUpReceipt, outcomeLine, request, sendReceipt } from "../agent/main/tool.js";
|
|
14
14
|
import { discoverAgents } from "../compat/agents.js";
|
|
15
15
|
import { JT } from "../types.js";
|
|
16
16
|
import { startOrchestrator, submitIdentified } from "./control.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) => {
|
|
@@ -501,15 +501,14 @@ function decided(ctx, id, done, json) {
|
|
|
501
501
|
ctx.write(json ? JSON.stringify({ request: id, applied: false, reason: done.outcome.reason, spec_digest: done.sent.digest }) : `${id}: rejected ${done.outcome.reason}`);
|
|
502
502
|
return EXIT.rejected;
|
|
503
503
|
}
|
|
504
|
-
// A follow-up
|
|
505
|
-
const
|
|
506
|
-
const
|
|
507
|
-
const opened = done.sent.request.kind === "send" && wid && existsSync(journalPath(ctx.home, wid))
|
|
508
|
-
? readJournalSnapshot(journalPath(ctx.home, wid)).find(e => e.type === "generation" && e.rid === done.sent.request.rid) : undefined;
|
|
504
|
+
// A follow-up opened a generation, or was queued into unfinished work (followUpReceipt).
|
|
505
|
+
const followed = done.sent.request.kind === "send" ? followUpReceipt(ctx.home, done.sent.request.rid, done.sent.request.body) : {};
|
|
506
|
+
const opened = followed.generation !== undefined ? followed : undefined;
|
|
509
507
|
// A notify says how it went (steered, held-until-answer or noted); a model send which model and when it applies.
|
|
510
508
|
const notified = done.sent.request.kind === "send" ? sendReceipt(ledger(ctx.home), done.sent.request.rid) : {};
|
|
511
|
-
const receipt = notified.delivery ? { delivery: notified.delivery, note: notified.note }
|
|
512
|
-
|
|
509
|
+
const receipt = notified.delivery ? { delivery: notified.delivery, note: notified.note }
|
|
510
|
+
: followed.delivery ? { delivery: followed.delivery, call: followed.call, note: followed.note } : {};
|
|
511
|
+
const reply = { request: id, applied: true, ...(opened ? { generation: opened.generation, call: opened.call } : {}), ...receipt, spec_digest: done.sent.digest };
|
|
513
512
|
ctx.write(json ? JSON.stringify(reply) : `${id}: applied${opened ? ` (follow-up generation ${reply.generation} of ${reply.call})` : ""}${receipt.delivery ? ` (${receipt.delivery}: ${receipt.note})` : ""}`);
|
|
514
513
|
return EXIT.ok;
|
|
515
514
|
}
|
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. */
|