pi-durable-subagents 1.0.42 → 1.0.45

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,66 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.0.45
4
+
5
+ - 1.0.44 was tagged but never published: its release checks failed on macOS. 1.0.45 is the first release with
6
+ command calls; on macOS, too, an argv whose program path does not exist ends with 127.
7
+ - Command calls: a call spec with `command` (an argv array, or a string for `/bin/sh -c`) instead of `agent`/`task`
8
+ runs the command without a model, a provider slot or tokens, and wakes the session that started it like any finished
9
+ call. Use it for a long build, a test suite or a wait that should not keep an agent busy. It works in every launch
10
+ form (single call, `tasks`, `chain`, `runs.run` in a script, `run --request`) and takes `cwd`, `timeoutMs`
11
+ (wall-clock from its start), `env` (added to the orchestrator's environment; `DSA_*` is reserved), `rerun` and
12
+ `writer` (default `false`). See README, "Command calls".
13
+ - An argv array runs a program, never shell syntax: its first element is looked up on the command's `PATH` (127 when
14
+ no program has it, 126 when the file is not executable), and a shell builtin name such as `exit` is not run as a
15
+ builtin. A string runs through `/bin/sh -c`. The wrapper that records the exit status works under any `env` the
16
+ command gets (`PATH` unset or bogus, `IFS`, locale).
17
+ - Result: exit 0 is `ok`, another status `failed`, past `timeoutMs` `timeout`, `stop` `stopped`; `data` is
18
+ `{exitCode, signal, durationMs}` and `output` the last 16 KiB of the interleaved stdout/stderr log. Stop and timeout
19
+ end the whole process tree, including detached descendants. Steer, follow-up, answer, model and notify are refused
20
+ with one reason, from the tool and the CLI alike (an `answer` without `qid` included).
21
+ - The timeout counts from the command's start, also while no orchestrator runs: a command that ended in time is `ok`
22
+ or `failed` even when its result is recorded later, and one that ended after its deadline is `timeout` (its exit
23
+ status still in `data`).
24
+ - A command outlives the orchestrator: a restart (also a forced one), an idle exit, a crash, a quitting pi session or
25
+ `stop-all` leaves it running; the next orchestrator takes it over, or records its result if it ended meanwhile. It
26
+ never runs twice at once. A process gone without an exit record ends `unknown`, or with `rerun: true` starts once
27
+ more. Restart refusals do not count command calls as busy and say how many keep running.
28
+ - A hold (`drain`, `stop-all`, a quitting pi) prevents a command call from starting and never stops one that started.
29
+ One not started yet (also one waiting for its worktree's writer lock, and the one `rerun`) starts after `resume`.
30
+ One that started runs to its end and its result is delivered as without the hold, also after an orchestrator
31
+ restart: a held workflow with a running command counts as pending work, so `start` and a pi session start an
32
+ orchestrator for it, and a workflow that is then complete finishes and sends its notice. A call it wants next waits
33
+ for `resume`.
34
+ - In a chain, a command step gets no `{previous}` substitution; an agent step after it gets its output.
35
+ - Status, describe and the subagent view show a command call's command, pid, attempt, elapsed time and log path
36
+ instead of a model.
37
+ - Fixed: an orchestrator started from inside a call (a subagent or a command running the CLI) inherited that call's
38
+ identity (`DSA_EXEC`, `DSA_CALL` and the other per-call variables), so the end or stop of that call could also end
39
+ the orchestrator. It now starts without them.
40
+ - Downgrade: once a command call has run, an older version is unsupported. Its orchestrator exits at startup with
41
+ `Unknown pinned agent: undefined` and changes nothing; installing 1.0.44 again recovers.
42
+
43
+ ## 1.0.43
44
+
45
+ Steady-state cost no longer grows with history. Behaviour, file formats and recorded decisions are unchanged.
46
+ Measured on a copy of a real home (2084 workflows, 51k orchestrator ledger entries):
47
+
48
+ - Orchestrator memory: after a restart and 60 s idle, RSS 751 MiB in 1.0.42 and about 320 MiB now (under 200 MiB a
49
+ minute later); JS heap 468 MiB -> 91 MiB. A terminal workflow releases its pinned agents and sources after 1 s idle
50
+ and reloads them, checked as before, when a request needs them; a damaged pin still seals only that follow-up
51
+ `pin-failed`. The sweep keeps process identities only for executions that were never fenced (a fenced execution
52
+ keeps its tag, so a straggler is still found and killed after a restart). The orchestrator's outbox keeps only
53
+ pending requests in memory.
54
+ - Request intake costs the new work, not the history: the orchestrator folds its ledger incrementally and indexes open
55
+ requests, and decisions get a read-only view instead of a deep copy. With one request every 5 s the orchestrator used
56
+ 26.6 CPU s/min in 1.0.42 and 1.7 now; a pass with nothing new fell from 264 ms to 0.5 ms.
57
+ - CLI request lookups filter journal lines by bytes before decoding them and remember, per file, which request ids a
58
+ verified prefix does not contain (no envelopes are kept). `send`: 4.1 s -> 1.5 s CPU and 455 -> 130 MiB RSS; `run`
59
+ 3.7 -> 1.2 s; `describe --key` 1.7 -> 1.0 s. A cold `status` is unchanged.
60
+ - The pi session reads its own outbox incrementally instead of folding it on every poll.
61
+ - A restart reaches the evaluator in about 2.5 s. Upgrading from 1.0.42 needs no one-time pass (the first start took
62
+ 2.6 s on this home); upgrading from 1.0.41 still runs the one-time pass of 1.0.42 (about 40 s on this home).
63
+
3
64
  ## 1.0.42
4
65
 
5
66
  - The orchestrator starts in seconds on a large home. Measured on a copy of a real home (2084 workflows, 432 MB of
package/README.md CHANGED
@@ -69,6 +69,7 @@ the agent calls it:
69
69
  ```text
70
70
  subagents({ action: "agents" })
71
71
  subagents({ agent: "worker", task: "Fix the flaky lease test" })
72
+ subagents({ command: ["npm", "test"], cwd: "./repo", timeoutMs: 1800000 })
72
73
  subagents({ tasks: [{ agent: "scout", task: "…" }, { agent: "reviewer", task: "…" }] })
73
74
  subagents({ chain: [{ agent: "worker", task: "…" }, { agent: "reviewer", task: "Review: {previous}" }] })
74
75
  subagents({ workflow: "./batch.js", args: { … }, usageBudget: { costUsd: 20 } })
@@ -103,10 +104,12 @@ call at once with that error instead of retrying it.
103
104
  With `tasks` or `chain`, top-level `agent`, `model`, `timeoutMs`, `budget`,
104
105
  `isolation`, `context`, `tools`, `skills`, `once` and `writer` apply to every
105
106
  step that does not set its own, e.g.
106
- `{ tasks: [{ task: "…" }, { task: "…" }], agent: "reviewer" }`. A top-level
107
- `task` beside a list is refused (agent + task is a single call); other call
108
- fields there, and any of them beside a workflow script, are refused rather
109
- than ignored.
107
+ `{ tasks: [{ task: "…" }, { task: "…" }], agent: "reviewer" }`. A command
108
+ step takes only `timeoutMs` and `writer` of them, plus `env` and `rerun`,
109
+ which apply to command steps only (see [Command calls](#command-calls)). A
110
+ top-level `task` or `command` beside a list is refused (each is a single
111
+ call; put it in a step); other call fields there, and any of them beside a
112
+ workflow script, are refused rather than ignored.
110
113
  When a call of a new run already waits for its worktree's writer lock as the
111
114
  run reply is written, the reply names it: `writerWait: ["<wid>/<key> held by
112
115
  <wid>/<key> (<root>)"]` with a hint that `writer: false` or
@@ -118,13 +121,13 @@ it something. Each verb means one thing, and a refusal says what would work:
118
121
 
119
122
  | Verb | Applies to | Effect |
120
123
  |---|---|---|
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. |
124
+ | `run` | — | Start one subagent, a command call, `tasks` in parallel, a `chain`, or a workflow script. An unknown agent name is refused before anything starts, with the list of agents. |
122
125
  | `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. |
123
126
  | `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). |
124
127
  | `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. |
125
128
  | `send answer` | an open question | Answers it once, at the first chance: as the result of the question it waits on, or (when it no longer waits on that question, say after a steer) as a message at its next safe point. An answer to an earlier question while it waits on a later one ends the later one: that question is withdrawn (`superseded`, the subagent is told to ask again if it still needs it) and takes no answer. |
126
129
  | `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. |
127
- | `stop` | a subagent or a workflow | Final: `stopped`, usage kept, edits left as they are. |
130
+ | `stop` | a subagent or a workflow | Final: `stopped`, usage kept, edits left as they are. A command call's whole process tree ends. |
128
131
  | `drain` / `resume` | existing workflows | A reversible hold; runs started later are not held. |
129
132
 
130
133
  Notes recorded for a call that is not running are durable and pending until
@@ -195,6 +198,9 @@ single file: it cannot `import` or `require` other modules.
195
198
  - `writer` (`false`: the call does not write in its cwd's worktree, so it does
196
199
  not take that worktree's writer lock; `true`: it does, whatever its tools).
197
200
 
201
+ A spec with `command` instead of `agent` and `task` is a
202
+ [command call](#command-calls).
203
+
198
204
  The result has `ok`, `status`, the full `output` text and the structured
199
205
  `data`.
200
206
 
@@ -202,6 +208,79 @@ A script is replayed after a crash. Finished calls are not run again, and a
202
208
  changed script is detected rather than silently mixed. Keep scripts
203
209
  deterministic: use `now()`/`random()`, not `Date`/`Math.random`.
204
210
 
211
+ ### Command calls
212
+
213
+ A command call runs a command instead of an agent: no model, no provider slot,
214
+ no tokens. It is a call like any other: it has a key and an address
215
+ (`<wid>/<key>`), it can be a step of `tasks` or `chain` or a `runs.run` of a
216
+ script, and when it ends it wakes the session that started it like any
217
+ finished call. Use it for a long build, a test suite or a wait that should not
218
+ keep an agent (and its slot) busy.
219
+
220
+ ```text
221
+ subagents({ command: ["npm", "test"], cwd: "./repo" })
222
+ subagents({ command: "make -j8 && ./bench > bench.txt", timeoutMs: 3600000, env: { CI: "1" } })
223
+ subagents({ chain: [{ command: ["npm", "test"] }, { agent: "worker", task: "Fix what failed:\n{previous}" }] })
224
+ ```
225
+
226
+ | Field | Meaning |
227
+ |---|---|
228
+ | `command` | An array runs a program with those arguments, never shell syntax: its first element is looked up in the command's `PATH` (exit 127 when there is none), and a shell builtin is not run as a builtin (`["exit", "7"]` looks for a program named `exit`). A string runs through `/bin/sh -c`. |
229
+ | `cwd` | Its directory, resolved like an agent call's. |
230
+ | `timeoutMs` | Wall-clock time from its start, including time the orchestrator was down (see the result table). |
231
+ | `env` | Variables added to the environment (`DSA_*` names are reserved). |
232
+ | `rerun` | `true`: when the process vanished without an exit record (the machine restarted), start it once more instead of ending `unknown`. For idempotent commands. |
233
+ | `writer` | `true`: take its worktree's writer lock (default `false`). |
234
+ | `key` | Its key in `tasks`/`chain`, as for agent steps. |
235
+
236
+ Other call fields (`agent`, `task`, `model`, `tools`, `schema`, `gate`, …)
237
+ are refused in a command call, and `env`/`rerun` in an agent call. stdin is
238
+ empty; stdout and stderr go, interleaved, to `output.log` in the attempt's
239
+ directory. The command sees the orchestrator's environment plus `env`,
240
+ `DSA_CALL` (its call id), `DSA_EXEC` (its attempt) and `DSA_HOME`, so a
241
+ `pi-durable-subagents` command inside it (`hold`, `run`, `send`) addresses
242
+ the same home; it cannot force a restart.
243
+
244
+ | The command | Result |
245
+ |---|---|
246
+ | exits 0 | `ok` |
247
+ | exits with another status or is killed by a signal | `failed`, error `Command exited <status>` / `Command killed by <SIG>` |
248
+ | ends after its deadline (start + `timeoutMs`), or still runs then | `timeout`, error `Command timed out after <ms> ms` |
249
+ | is stopped (`stop`) | `stopped` |
250
+ | vanished without an exit record, no `rerun` | `unknown`, error `Command ended without an exit record` |
251
+
252
+ `data` is `{exitCode, signal, durationMs}` and `output` the last 16 KiB of
253
+ `output.log`. Only `stop` controls a command call (it ends the whole process
254
+ tree); `steer`, `follow-up`, `answer`, `model` and `notify` are refused with
255
+ `command call: <kind> is not supported (stop it, or start a new call)`.
256
+
257
+ The deadline counts from the command's start, also while no orchestrator
258
+ runs: a command that ended in time is `ok` (or `failed`) even when the
259
+ orchestrator records it later, and one that ended after its deadline is
260
+ `timeout` (with its exit in `data`) although nothing had to stop it.
261
+
262
+ A command outlives the orchestrator: a restart (also a forced one), an idle
263
+ exit or a crash leaves it running, and the next orchestrator takes it over or
264
+ records its result if it ended meanwhile. The restart busy list does not count
265
+ it.
266
+
267
+ A hold (`drain`, `stop-all`, a quit pi) prevents starting, never stops what
268
+ started. A command call that has not started yet (also one waiting for its
269
+ worktree's writer lock) waits while its workflow is held and starts after
270
+ `resume`. One that has started runs to its end; its result is recorded and
271
+ delivered to its workflow as without the hold, also after an orchestrator
272
+ restart (`start` and the pi session's starter start an orchestrator for it):
273
+ a workflow that is then complete finishes and sends its notice, and a call it
274
+ wants next waits for `resume`. The one `rerun` of a lost command is a new
275
+ start, so under a hold it waits for `resume` too.
276
+
277
+ In a chain, a command step gets no `{previous}` (its command is not changed);
278
+ an agent step after a command step gets the command's output as `{previous}`.
279
+ `status`, `describe` and the `/subagents` view show a running command call
280
+ with `command: <command>`, its pid and how long it runs instead of a model;
281
+ `describe` also names its `output.log`. A finished one shows its status and
282
+ exit code.
283
+
205
284
  ### Watch any subagent like the main agent
206
285
 
207
286
  While subagents work, a small dock sits above the editor: one quiet row per
@@ -370,7 +449,8 @@ answers, the question id and revision). Persist the exact spec bytes you
370
449
  submit and retry with those bytes: the run's `cwd` is part of the content
371
450
  (`spec.cwd`, else `--cwd`, else the current directory, made absolute), so
372
451
  retry from the same place or pass it explicitly. The `spec` file is the
373
- `subagents` tool's run form (`{agent, task, model?, schema?, …}` or
452
+ `subagents` tool's run form (`{agent, task, model?, schema?, …}`,
453
+ `{command, cwd?, timeoutMs?, env?, rerun?}` or
374
454
  `{tasks: […], name?, usageBudget?, maxCalls?}`); `context: "fork"` needs a pi
375
455
  session and is rejected.
376
456
 
@@ -412,7 +492,9 @@ full text, `qid`, `rev` and the `to` address to answer), `sealed` (finished:
412
492
  `status` plus every call's unclipped `output`, `error` and schema `data`) or
413
493
  `pruned` (`pruned: {status, endedAt}`; workflows pruned before 1.0.21 have
414
494
  only `endedAt`), with `wid`, `request` and
415
- `spec_digest`, and `labels` when the run has any. Live calls also show what
495
+ `spec_digest`, and `labels` when the run has any. A command call has
496
+ `command` (its command on one line, clipped), `attempt`, `log` (its
497
+ `output.log`) and, while it runs, `pid` and `elapsed`. Live calls also show what
416
498
  they wait for (slot, writer lock, lease, exhausted provider; see "Labels and
417
499
  why a call does not move"). `lastFence: {at, exec, reason}` appears only
418
500
  when an execution was cut off: it had not ended its turn when it was fenced,
@@ -1,7 +1,8 @@
1
1
  // The subagents tool's parameter schema. Kept apart from tool.ts because it needs the optional pi peer
2
2
  // package, which the CLI (sharing tool.ts) must not import: it runs from the package directory.
3
3
  import { Type } from "@earendil-works/pi-ai";
4
- const stepsDoc = "Call specs {agent, task, model?, cwd?, timeoutMs?, output?, schema?, gate?, isolation?, context?, budget?, once?, tools?, skills?, writer?, key?}; " +
4
+ const stepsDoc = "Call specs {agent, task, model?, cwd?, timeoutMs?, output?, schema?, gate?, isolation?, context?, budget?, once?, tools?, skills?, writer?, key?} " +
5
+ "or command specs {command, cwd?, timeoutMs?, env?, rerun?, writer?, key?}; " +
5
6
  "each call is addressed as '<wid>/<key>', where key is the step's own unique key or else 'tasks:<i>' / 'chain:<i>'.";
6
7
  export const parameters = Type.Object({
7
8
  action: Type.Optional(Type.Union(["run", "agents", "send", "stop", "revise", "status", "resume", "drain", "restart"].map(v => Type.Literal(v)))),
@@ -9,6 +10,9 @@ export const parameters = Type.Object({
9
10
  tasks: Type.Optional(Type.Array(Type.Any(), { description: `Parallel calls. ${stepsDoc}` })),
10
11
  chain: Type.Optional(Type.Array(Type.Any(), { description: `Sequential calls ({previous} = previous output). ${stepsDoc}` })),
11
12
  agent: Type.Optional(Type.String()), task: Type.Optional(Type.String()), model: Type.Optional(Type.String()),
13
+ command: Type.Optional(Type.Union([Type.String(), Type.Array(Type.String())], { description: "A command call instead of agent+task: an argv array runs a program (PATH lookup, no shell: a builtin is not a builtin), a string runs through /bin/sh -c. No model or slot; it survives restarts. Result data {exitCode, signal, durationMs}, output = the last 16 KiB of stdout+stderr." })),
14
+ env: Type.Optional(Type.Record(Type.String(), Type.String(), { description: "Command calls: variables added to the environment (DSA_* reserved)." })),
15
+ rerun: Type.Optional(Type.Boolean({ description: "Command calls: start the command once more when it vanished without an exit record (machine restart) instead of sealing unknown; for idempotent commands." })),
12
16
  cwd: Type.Optional(Type.String({ description: "Run directory (default: this session's). Relative workflow, inputs and call cwd paths resolve against it." })),
13
17
  to: Type.Optional(Type.Union([Type.String(), Type.Array(Type.String())], { description: "send: '<wid>/<key>', or a list of them for steer, notify, follow-up and model (one request per call; answer takes one)." })),
14
18
  kind: Type.Optional(Type.Union([Type.Literal("steer"), Type.Literal("notify"), Type.Literal("follow-up"), Type.Literal("answer"), Type.Literal("model")])),
@@ -18,7 +22,7 @@ export const parameters = Type.Object({
18
22
  maxCalls: Type.Optional(Type.Integer({ minimum: 1 })), inputs: Type.Optional(Type.Record(Type.String(), Type.String())),
19
23
  name: Type.Optional(Type.String()),
20
24
  labels: Type.Optional(Type.Record(Type.String(), Type.String(), { description: "run: your labels, e.g. {node, attempt}: at most 32 keys [A-Za-z0-9_.:-]{1,64}, string values of at most 256 characters, 4096 bytes of JSON; part of the request's content (spec_digest), shown by describe and on its events." })),
21
- timeoutMs: Type.Optional(Type.Number({ description: "Per-call limit on active time in milliseconds (a number). Omit unless a hard limit is needed; prefer budgets." })),
25
+ timeoutMs: Type.Optional(Type.Number({ description: "Per-call limit on active time in milliseconds (a number; a command call: wall-clock time since it started). Omit unless a hard limit is needed; prefer budgets." })),
22
26
  key: Type.Optional(Type.String({ description: "A single agent/task run: the call's key. status with wid: that call's full result." })),
23
27
  tail: Type.Optional(Type.Integer({ minimum: 1, description: "status with wid: the last N lines of each call's result (unclipped, at most 4000 characters per call)." })),
24
28
  grep: Type.Optional(Type.String({ description: "status with wid: only the lines of each call's result matching this case-sensitive JS regular expression, run in-process: avoid nested quantifiers such as (a+)+; it tests the first 2000 characters of a line and the last 5000 lines (with tail: grep first, then the last N)." })),
@@ -1,11 +1,35 @@
1
1
  import { closeSync, openSync, readSync, statSync } from "node:fs";
2
2
  import { StringDecoder } from "node:string_decoder";
3
3
  import { join } from "node:path";
4
- import { forgetJournalSnapshot, journalAppends, readJournalSnapshot, readJournalUncached } from "../../kernel/journal.js";
4
+ import { liveCommandCalls } from "../../orchestrator/executor/command.js";
5
+ import { forgetJournalSnapshot, journalAppends, readJournalFold, readJournalSnapshot, readJournalUncached } from "../../kernel/journal.js";
5
6
  import { journalPath } from "../../paths.js";
6
7
  import { CT, JT } from "../../types.js";
7
8
  import { openGeneration, readerWorkflowListing, releaseLoadedSettledJournals, releaseSettledJournals, SETTLED_RECHECK_MS, unresolvedAttention, workflowDigest, workflowDigestChecked } from "../../orchestrator/snapshot.js";
8
9
  import { readerHold, readerLedgerIdentity } from "../../orchestrator/reader-ledger.js";
10
+ /** Session-outbox reader: retain only pending identities and a verified position, not sent envelopes/history. */
11
+ export class PendingOutboxReader {
12
+ positions = new Map();
13
+ clear() { this.positions.clear(); }
14
+ read(path) {
15
+ const prior = this.positions.get(path);
16
+ this.positions.delete(path); // Never retry partially applied state after a failed read.
17
+ const record = readJournalFold(path, prior, () => new Set(), (pending, entry) => {
18
+ if (entry.type === 'sent')
19
+ pending.add(entry.request.rid);
20
+ else if (entry.type === 'resolved')
21
+ pending.delete(String(entry.rid));
22
+ }, { needles: ['"type":"sent"', '"type":"resolved"'] });
23
+ // A torn tail may be repaired at unchanged size; do not reuse that file identity as a committed position.
24
+ if (record && record.length === record.size) {
25
+ this.positions.set(path, record);
26
+ if (this.positions.size > 64)
27
+ this.positions.delete(this.positions.keys().next().value);
28
+ }
29
+ // A copy: the fold extends its state in place on the next read, so a returned set must not alias it.
30
+ return new Set(record?.state);
31
+ }
32
+ }
9
33
  const passes = new Map();
10
34
  export function workflows(home, origin, fresh = false) {
11
35
  const { record, names, checked: listed } = readerWorkflowListing(home, fresh), ix = record.state, mark = readerLedgerIdentity(record), now = Date.now();
@@ -87,10 +111,49 @@ function unfinishedJournal(path, known) {
87
111
  decided.set(path, { ino: read.ino, size: read.size, unfinished });
88
112
  return unfinished;
89
113
  }
114
+ /** R3, F4: Whether a journal has a live command attempt (liveCommandCalls: an intent not withdrawn, of a call neither
115
+ * sealed nor retired). A hold never stops
116
+ * one, so an orchestrator must watch and seal it even while its workflow is held. Cached by file identity. */
117
+ const commanded = new Map();
118
+ function startedCommand(path, known) {
119
+ let stat;
120
+ try {
121
+ stat = statSync(path);
122
+ }
123
+ catch (error) {
124
+ if (error.code !== "ENOENT")
125
+ throw error;
126
+ commanded.delete(path);
127
+ return false;
128
+ }
129
+ if (!stat.isFile()) {
130
+ commanded.delete(path);
131
+ return false;
132
+ } // unreadable held work stays held
133
+ const hit = commanded.get(path);
134
+ if (hit && hit.ino === stat.ino && hit.size === stat.size)
135
+ return hit.running;
136
+ let read = known;
137
+ try {
138
+ read ??= readJournalUncached(path);
139
+ }
140
+ catch {
141
+ commanded.delete(path);
142
+ return false;
143
+ }
144
+ if (!read) {
145
+ commanded.delete(path);
146
+ return false;
147
+ }
148
+ const running = liveCommandCalls(read.entries).length > 0;
149
+ commanded.set(path, { ino: read.ino, size: read.size, running });
150
+ return running;
151
+ }
90
152
  /** P1: Workflow-side pending work shared by every starter: a workflow without JT.done or with an unsealed generation,
91
153
  * unless a drain (stop-all) holds it: held work waits for an explicit resume, which starts the orchestrator itself.
92
- * Stops at the first unfinished workflow (newest first); a held workflow the ledger attributes is skipped without
93
- * reading its journal, and an unchanged journal is not read again. */
154
+ * R3: a held workflow with a started, unsealed command call is pending all the same (the hold does not stop it).
155
+ * Stops at the first unfinished workflow (newest first); a held workflow is read only for a started command call
156
+ * (startedCommand), and an unchanged journal is not read again. */
94
157
  export function unfinishedWorkflow(home, fresh = false) {
95
158
  const { record, names } = readerWorkflowListing(home, fresh), ix = record.state, { created, pruned } = ix;
96
159
  const ids = [...new Set([...[...created.keys()].map(String), ...names].filter(wid => !pruned.has(wid)))].sort().reverse();
@@ -99,13 +162,19 @@ export function unfinishedWorkflow(home, fresh = false) {
99
162
  // The hold rule is the one workflows() applies: the ledger's `created` names the origin a drain may hold; only for
100
163
  // a wid the ledger has no `created` for is the journal read first, for a `created` entry of its own.
101
164
  const known = created.get(wid);
102
- if (known && readerHold(ix, wid, known.origin))
165
+ if (known && readerHold(ix, wid, known.origin)) {
166
+ if (startedCommand(path))
167
+ return true;
103
168
  continue;
169
+ }
104
170
  let read;
105
171
  if (!known) {
106
172
  read = readJournalUncached(path);
107
- if (readerHold(ix, wid, read?.entries.find(e => e.type === JT.created)?.origin))
173
+ if (readerHold(ix, wid, read?.entries.find(e => e.type === JT.created)?.origin)) {
174
+ if (startedCommand(path, read))
175
+ return true;
108
176
  continue;
177
+ }
109
178
  }
110
179
  if (unfinishedJournal(path, read))
111
180
  return true;
@@ -1,14 +1,22 @@
1
1
  import { restartInputError } from "../../orchestrator/restart.js";
2
2
  import { existsSync } from "node:fs";
3
3
  import { resolve } from "node:path";
4
- import { readJournalSnapshot } from "../../kernel/journal.js";
4
+ import { readJournalFold } from "../../kernel/journal.js";
5
5
  import { generationRids } from "../../orchestrator/notes.js";
6
6
  import { journalPath } from "../../paths.js";
7
+ import { isCommandCall } from "../../types.js";
7
8
  import { validateCallSpec } from "../../compat/spec.js";
8
9
  import { compileFanout } from "../../compat/fanout.js";
9
10
  import { checkLabels } from "../../events/labels.js";
10
11
  /** Call fields a tasks/chain run applies to every step that does not set its own. */
11
- export const stepDefaults = ["agent", "model", "timeoutMs", "budget", "isolation", "context", "tools", "skills", "once", "writer"];
12
+ export const stepDefaults = ["agent", "model", "timeoutMs", "budget", "isolation", "context", "tools", "skills", "once", "writer", "env", "rerun"];
13
+ /** The run-level defaults a command step takes; agent steps take the others (env and rerun belong to command calls). */
14
+ const commandDefaults = new Set(["timeoutMs", "writer", "env", "rerun"]), agentOnly = new Set(["env", "rerun"]);
15
+ /** The run-level defaults that apply to one step: a command step skips agent-only fields, an agent step skips env/rerun. */
16
+ function defaultsFor(step, defaults) {
17
+ const command = step.command !== undefined;
18
+ return Object.fromEntries(Object.entries(defaults).filter(([k]) => command ? commandDefaults.has(k) : !agentOnly.has(k)));
19
+ }
12
20
  function string(args, name) {
13
21
  if (typeof args[name] !== "string" || !args[name])
14
22
  throw new Error(`${name} is required`);
@@ -27,7 +35,8 @@ function call(value, cwd, where) {
27
35
  /** v12 §2: Reject unknown explicit call agents before starter or outbox publication; scripts remain call-local. Shared by
28
36
  * the tool and the CLI `run --request`. */
29
37
  export function checkAgents(body, available) {
30
- const names = [...(body.call ? [body.call] : []), ...(body.tasks ?? []), ...(body.chain ?? [])].map(call => call.agent);
38
+ // A command call names no agent.
39
+ const names = [...(body.call ? [body.call] : []), ...(body.tasks ?? []), ...(body.chain ?? [])].filter(call => !isCommandCall(call)).map(call => call.agent);
31
40
  if (!names.length)
32
41
  return;
33
42
  const known = available(), unknown = [...new Set(names.filter(name => !known.includes(name)))];
@@ -59,7 +68,8 @@ export function followUpReceipt(home, rid, body) {
59
68
  const wid = send.to.split("/")[0].split("@")[0], path = journalPath(home, wid);
60
69
  if (!existsSync(path))
61
70
  return {};
62
- const log = readJournalSnapshot(path), opened = log.find(e => e.type === "generation" && generationRids(e).includes(rid));
71
+ const log = readJournalFold(path, undefined, () => [], (entries, entry) => { entries.push(entry); }, { needles: [JSON.stringify(rid)] })?.state ?? [];
72
+ const opened = log.find(e => e.type === "generation" && generationRids(e).includes(rid));
63
73
  if (opened)
64
74
  return { generation: Number(opened.gen), call: `${wid}/${String(opened.key)}` };
65
75
  const queued = log.find(e => e.type === "forward" && e.rid === rid);
@@ -92,7 +102,10 @@ export function request(args, cwd) {
92
102
  // A task beside tasks/chain is refused with what to do, before the launch form is inferred (with or without action).
93
103
  if ((args.action === undefined || args.action === "run") && listRun && args.task !== undefined)
94
104
  throw new Error(`task cannot be set beside ${args.tasks !== undefined ? "tasks" : "chain"}: agent+task is a single call; give each step its own task (a top-level agent alone is the default agent of every step)`);
95
- const launchForms = [args.task !== undefined || args.agent !== undefined && !listRun, args.tasks !== undefined,
105
+ // So is a command: a command call is a launch form of its own, or a step of the list.
106
+ if ((args.action === undefined || args.action === "run") && listRun && args.command !== undefined)
107
+ throw new Error(`command cannot be set beside ${args.tasks !== undefined ? "tasks" : "chain"}: put it in a step ({command, ...}); a top-level command is a single command call`);
108
+ const launchForms = [args.task !== undefined || args.command !== undefined || args.agent !== undefined && !listRun, args.tasks !== undefined,
96
109
  args.chain !== undefined, args.workflow !== undefined, args.source !== undefined];
97
110
  const action = args.action === undefined && launchForms.filter(Boolean).length === 1 ? "run" : args.action;
98
111
  if (typeof action !== "string" || !action)
@@ -101,10 +114,10 @@ export function request(args, cwd) {
101
114
  const { action: _, workflow, source, tasks, chain, args: inputs, name, usageBudget, maxCalls, inputs: files, labels, by: _by, request: _request, ...spec } = args;
102
115
  const steps = tasks !== undefined || chain !== undefined;
103
116
  // With tasks/chain a top-level agent (no task) is the default agent of every step, like model or timeoutMs.
104
- const single = spec.task !== undefined || spec.agent !== undefined && !steps;
117
+ const single = spec.task !== undefined || spec.command !== undefined || spec.agent !== undefined && !steps;
105
118
  const choices = [workflow, source, tasks, chain, single ? spec : undefined];
106
119
  if (choices.filter(v => v !== undefined).length !== 1)
107
- throw new Error("run requires exactly one of workflow, source, tasks, chain, or agent/task (with tasks/chain, a top-level agent without task is the steps' default agent)");
120
+ throw new Error("run requires exactly one of workflow, source, tasks, chain, agent/task or command (with tasks/chain, a top-level agent without task is the steps' default agent)");
108
121
  // A top-level cwd on a workflow/tasks/chain/source run is the run's directory: relative paths (the workflow file,
109
122
  // inputs, per-call cwd) resolve against it and calls default to it. It used to be ignored, so a relative
110
123
  // workflow path was looked up in the session's directory instead.
@@ -131,7 +144,7 @@ export function request(args, cwd) {
131
144
  if (!Array.isArray(list) || !list.length)
132
145
  throw new Error("tasks/chain must be nonempty");
133
146
  const kind = tasks !== undefined ? "tasks" : "chain";
134
- body[kind] = list.map((value, i) => call(value && typeof value === "object" && !Array.isArray(value) ? { ...defaults, ...value } : value, runCwd, `${kind}[${i}]`));
147
+ body[kind] = list.map((value, i) => call(value && typeof value === "object" && !Array.isArray(value) ? { ...defaultsFor(value, defaults), ...value } : value, runCwd, `${kind}[${i}]`));
135
148
  compileFanout(kind === "tasks" ? { tasks: body.tasks } : { chain: body.chain }); // duplicate keys fail here, not at admission
136
149
  }
137
150
  else
@@ -5,14 +5,13 @@ import { fileURLToPath } from "node:url";
5
5
  import { setTimeout as delay } from "node:timers/promises";
6
6
  import { defineTool } from "@earendil-works/pi-coding-agent";
7
7
  import { Outbox, scanInbox } from "../kernel/mailbox.js";
8
- import { readJournalSnapshot } from "../kernel/journal.js";
9
8
  import { readerLedger } from "../orchestrator/reader-ledger.js";
10
9
  import { OsLock } from "../platform/lock.js";
11
10
  import { launchOrchestrator } from "../platform/launch.js";
12
11
  import { dsaHome, orchInbox, orchLock, outboxRoot } from "../paths.js";
13
12
  import { CT, JT } from "../types.js";
14
- import { attention, presentText, presented, resolved, unfinishedWorkflow } from "./main/snapshots.js";
15
- import { NOTIFY_SINCE, isLive, orchestratorTooOld, ownWorkflows, pausedElsewhere, runningOrchestrator, statusBrief, statusCallDetail, statusCompactDetail, statusDetail, statusView, outputSelect, writerWaits, writerWaitLine, WRITER_WAIT_HINT } from "../orchestrator/snapshot.js";
13
+ import { PendingOutboxReader, attention, presentText, presented, resolved, unfinishedWorkflow } from "./main/snapshots.js";
14
+ import { NOTIFY_SINCE, commandSendRefusal, isCommandTarget, isLive, orchestratorTooOld, ownWorkflows, pausedElsewhere, runningOrchestrator, statusBrief, statusCallDetail, statusCompactDetail, statusDetail, statusView, outputSelect, writerWaits, writerWaitLine, WRITER_WAIT_HINT } from "../orchestrator/snapshot.js";
16
15
  import { BATCH, checkAgents, followUpReceipt, outcomeLine, request, sendReceipt } from "./main/tool.js";
17
16
  import { parameters } from "./main/schema.js";
18
17
  import { batchConflict, batchDigest, findRequest, manyIds, namesMany, requestRid, sendIdentified } from "../requests.js";
@@ -50,6 +49,7 @@ export function registerMain(pi, ui) {
50
49
  let queue = Promise.resolve(), timer;
51
50
  let reserved = [], notes = [], stopped = true, lastStarter = 0;
52
51
  let polling = false;
52
+ const pendingReader = new PendingOutboxReader();
53
53
  const sink = (text) => { notes.push(text); };
54
54
  function serial(fn) {
55
55
  const result = queue.then(fn);
@@ -66,14 +66,7 @@ export function registerMain(pi, ui) {
66
66
  }
67
67
  function pendingOutbox() { return pendingRids().size > 0; }
68
68
  function pendingRids() {
69
- const pending = new Set();
70
- for (const entry of readJournalSnapshot(join(outboxRoot(home), "outbox", `${sender}.jsonl`))) {
71
- if (entry.type === "sent")
72
- pending.add(entry.request.rid);
73
- else if (entry.type === "resolved")
74
- pending.delete(String(entry.rid));
75
- }
76
- return pending;
69
+ return pendingReader.read(join(outboxRoot(home), "outbox", `${sender}.jsonl`));
77
70
  }
78
71
  async function starter(submitting = false) {
79
72
  if (stopped)
@@ -145,6 +138,7 @@ export function registerMain(pi, ui) {
145
138
  await queue;
146
139
  await outbox?.close();
147
140
  outbox = undefined;
141
+ pendingReader.clear();
148
142
  if (noteSink === sink)
149
143
  noteSink = undefined;
150
144
  reserved = [];
@@ -337,6 +331,10 @@ export function registerMain(pi, ui) {
337
331
  (args.to === undefined || args.to === body.to) && (args.qid === undefined || args.qid === prior.cond.qid))
338
332
  args = { ...args, to: body.to, qid: prior.cond.qid, rev: args.rev ?? prior.cond.rev };
339
333
  }
334
+ // R8: a command call has no questions: an answer is refused with the pinned reason (as the orchestrator refuses one
335
+ // that names a qid/rev), not with the question pre-fill's "no open question".
336
+ if (args.action === "send" && args.kind === "answer" && (args.qid === undefined || args.rev === undefined) && isCommandTarget(home, args.to))
337
+ return { applied: false, reason: commandSendRefusal("answer") };
340
338
  if (args.action === "send")
341
339
  args = completeSend(args);
342
340
  // A session resumes its own held work (what its quit paused); the CLI `resume` remains the global one.
@@ -436,7 +434,7 @@ export function registerMain(pi, ui) {
436
434
  pi.registerTool(defineTool({
437
435
  name: "subagents", label: "Subagents", description: [
438
436
  "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.",
439
- "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
+ "run (action optional for exactly one launch form): agent+task; command (a command call); 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. A command call {command:[argv] or 'sh string', cwd?, timeoutMs? (wall-clock), env?, rerun?, writer?} runs a process instead of an agent: no model, slot or tokens; it keeps running across orchestrator restarts and a quit pi, and wakes you like any call; result ok on exit 0 else failed, data {exitCode, signal, durationMs}, output = last 16 KiB of stdout+stderr; only stop controls it. Run-level env/rerun apply to command steps, agent-only defaults skip them; in a chain an agent step after a command step gets its output as {previous}. Explicit unknown agents are rejected BEFORE creation, with available names; unknown script agents fail only their call.",
440
438
  "agents: list names, descriptions, default models and source for this cwd; use these names for run.",
441
439
  "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.",
442
440
  "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, queued: why a queued call does not start (orchestrator starting while it recovers after a start, a used-up provider, a writer lock, full providers; absent when not known), 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 (with ', starting <age>' while it recovers; 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.",
@@ -4,8 +4,8 @@ import { join } from "node:path";
4
4
  import { fileURLToPath } from "node:url";
5
5
  import { setTimeout as delay } from "node:timers/promises";
6
6
  import { Outbox, scanInbox } from "../kernel/mailbox.js";
7
- import { readJournalSnapshot } from "../kernel/journal.js";
8
- import { reduceLifecycle } from "../kernel/lifecycle.js";
7
+ import { readJournalFold, readJournalSnapshot } from "../kernel/journal.js";
8
+ import { isResolution } from "../kernel/lifecycle.js";
9
9
  import { OsLock } from "../platform/lock.js";
10
10
  import { launchOrchestrator } from "../platform/launch.js";
11
11
  import { orchInbox, orchLedger, orchLock, outboxRoot } from "../paths.js";
@@ -34,7 +34,7 @@ async function pendingOutboxes(home) {
34
34
  const names = await readdir(dir).catch(error => { if (error.code === "ENOENT")
35
35
  return []; throw error; });
36
36
  const ledger = readJournalSnapshot(orchLedger(home));
37
- const decided = reduceLifecycle(ledger.filter(e => [JT.admitted, JT.applied, JT.rejected, JT.withdrawn].includes(e.type))).resolved;
37
+ const decided = new Set(ledger.filter(isResolution).map(e => String(e.rid)));
38
38
  const created = new Set(ledger.filter(e => e.type === JT.created).map(e => String(e.rid)));
39
39
  for (const name of names.filter(n => n.endsWith(".jsonl"))) {
40
40
  const pending = new Map();
@@ -68,11 +68,15 @@ export async function start(home, env, starter = startOrchestrator) {
68
68
  /** P6, housekeeping: Wait (bounded) until the ledger resolves `rid`; undefined when it is still pending at the deadline. */
69
69
  export async function resolution(home, rid, timeoutMs, interval = 100) {
70
70
  const deadline = performance.now() + timeoutMs;
71
+ let journal;
71
72
  for (;;) {
72
- const records = readJournalSnapshot(orchLedger(home)).filter(e => [JT.admitted, JT.applied, JT.rejected, JT.withdrawn].includes(e.type));
73
- const resolved = reduceLifecycle(records).resolved.get(rid);
74
- if (resolved)
75
- return resolved.type === "rejected" ? { type: "rejected", reason: String(resolved.reason) } : { type: "applied" };
73
+ // The compact reader retains only this rid's first terminal decision and reads appended bytes on each poll.
74
+ journal = readJournalFold(orchLedger(home), journal, () => ({}), (state, entry) => {
75
+ if (!state.resolved && entry.rid === rid && isResolution(entry))
76
+ state.resolved = entry.type === "rejected" ? { type: "rejected", reason: String(entry.reason) } : { type: "applied" };
77
+ }, { needles: [JSON.stringify(rid)] });
78
+ if (journal?.state.resolved)
79
+ return journal.state.resolved;
76
80
  if (performance.now() >= deadline)
77
81
  return undefined;
78
82
  await delay(interval);
@@ -132,9 +136,15 @@ async function withSender(home, fn) {
132
136
  try {
133
137
  const outbox = await Outbox.open(outboxRoot(home), sender, () => orchInbox(home));
134
138
  try {
135
- const records = readJournalSnapshot(orchLedger(home)).filter(e => ["admitted", "applied", "rejected", "withdrawn"].includes(e.type));
136
- for (const rid of reduceLifecycle(records).resolved.keys())
137
- await outbox.markResolved(rid);
139
+ const pending = outbox.pendingRids();
140
+ if (pending.size) {
141
+ const resolved = readJournalFold(orchLedger(home), undefined, () => [], (rids, entry) => {
142
+ if (isResolution(entry) && pending.delete(String(entry.rid)))
143
+ rids.push(String(entry.rid));
144
+ }, { needles: [...pending].map(rid => JSON.stringify(rid)) });
145
+ for (const rid of resolved?.state ?? [])
146
+ await outbox.markResolved(rid);
147
+ }
138
148
  await outbox.republishPending();
139
149
  return await fn(outbox, sender);
140
150
  }