pi-durable-subagents 1.0.43 → 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 +40 -0
- package/README.md +90 -8
- package/dist/agent/main/schema.js +6 -2
- package/dist/agent/main/snapshots.js +50 -4
- package/dist/agent/main/tool.js +18 -6
- package/dist/agent/main.js +6 -2
- package/dist/cli/main.js +5 -3
- package/dist/cli/requests.js +20 -3
- package/dist/compat/fanout.js +13 -5
- package/dist/compat/spec.js +46 -1
- package/dist/events/waiting.js +16 -1
- package/dist/orchestrator/engine.js +87 -10
- package/dist/orchestrator/executor/command.js +54 -0
- package/dist/orchestrator/executor/index.js +360 -8
- package/dist/orchestrator/main.js +4 -2
- package/dist/orchestrator/restart.js +4 -1
- package/dist/orchestrator/settled.js +4 -0
- package/dist/orchestrator/snapshot.js +86 -9
- package/dist/platform/command.js +98 -0
- package/dist/platform/launch.js +13 -3
- package/dist/types.js +2 -0
- package/dist/ui/screen.js +62 -13
- package/dist/ui/tool.js +8 -4
- package/dist/ui/view.js +18 -7
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,45 @@
|
|
|
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
|
+
|
|
3
43
|
## 1.0.43
|
|
4
44
|
|
|
5
45
|
Steady-state cost no longer grows with history. Behaviour, file formats and recorded decisions are unchanged.
|
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
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
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?, …}
|
|
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.
|
|
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,6 +1,7 @@
|
|
|
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 { liveCommandCalls } from "../../orchestrator/executor/command.js";
|
|
4
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";
|
|
@@ -110,10 +111,49 @@ function unfinishedJournal(path, known) {
|
|
|
110
111
|
decided.set(path, { ino: read.ino, size: read.size, unfinished });
|
|
111
112
|
return unfinished;
|
|
112
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
|
+
}
|
|
113
152
|
/** P1: Workflow-side pending work shared by every starter: a workflow without JT.done or with an unsealed generation,
|
|
114
153
|
* unless a drain (stop-all) holds it: held work waits for an explicit resume, which starts the orchestrator itself.
|
|
115
|
-
*
|
|
116
|
-
*
|
|
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. */
|
|
117
157
|
export function unfinishedWorkflow(home, fresh = false) {
|
|
118
158
|
const { record, names } = readerWorkflowListing(home, fresh), ix = record.state, { created, pruned } = ix;
|
|
119
159
|
const ids = [...new Set([...[...created.keys()].map(String), ...names].filter(wid => !pruned.has(wid)))].sort().reverse();
|
|
@@ -122,13 +162,19 @@ export function unfinishedWorkflow(home, fresh = false) {
|
|
|
122
162
|
// The hold rule is the one workflows() applies: the ledger's `created` names the origin a drain may hold; only for
|
|
123
163
|
// a wid the ledger has no `created` for is the journal read first, for a `created` entry of its own.
|
|
124
164
|
const known = created.get(wid);
|
|
125
|
-
if (known && readerHold(ix, wid, known.origin))
|
|
165
|
+
if (known && readerHold(ix, wid, known.origin)) {
|
|
166
|
+
if (startedCommand(path))
|
|
167
|
+
return true;
|
|
126
168
|
continue;
|
|
169
|
+
}
|
|
127
170
|
let read;
|
|
128
171
|
if (!known) {
|
|
129
172
|
read = readJournalUncached(path);
|
|
130
|
-
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;
|
|
131
176
|
continue;
|
|
177
|
+
}
|
|
132
178
|
}
|
|
133
179
|
if (unfinishedJournal(path, read))
|
|
134
180
|
return true;
|
package/dist/agent/main/tool.js
CHANGED
|
@@ -4,11 +4,19 @@ import { resolve } from "node:path";
|
|
|
4
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
|
-
|
|
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)))];
|
|
@@ -93,7 +102,10 @@ export function request(args, cwd) {
|
|
|
93
102
|
// A task beside tasks/chain is refused with what to do, before the launch form is inferred (with or without action).
|
|
94
103
|
if ((args.action === undefined || args.action === "run") && listRun && args.task !== undefined)
|
|
95
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)`);
|
|
96
|
-
|
|
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,
|
|
97
109
|
args.chain !== undefined, args.workflow !== undefined, args.source !== undefined];
|
|
98
110
|
const action = args.action === undefined && launchForms.filter(Boolean).length === 1 ? "run" : args.action;
|
|
99
111
|
if (typeof action !== "string" || !action)
|
|
@@ -102,10 +114,10 @@ export function request(args, cwd) {
|
|
|
102
114
|
const { action: _, workflow, source, tasks, chain, args: inputs, name, usageBudget, maxCalls, inputs: files, labels, by: _by, request: _request, ...spec } = args;
|
|
103
115
|
const steps = tasks !== undefined || chain !== undefined;
|
|
104
116
|
// With tasks/chain a top-level agent (no task) is the default agent of every step, like model or timeoutMs.
|
|
105
|
-
const single = spec.task !== undefined || spec.agent !== undefined && !steps;
|
|
117
|
+
const single = spec.task !== undefined || spec.command !== undefined || spec.agent !== undefined && !steps;
|
|
106
118
|
const choices = [workflow, source, tasks, chain, single ? spec : undefined];
|
|
107
119
|
if (choices.filter(v => v !== undefined).length !== 1)
|
|
108
|
-
throw new Error("run requires exactly one of workflow, source, tasks, chain,
|
|
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)");
|
|
109
121
|
// A top-level cwd on a workflow/tasks/chain/source run is the run's directory: relative paths (the workflow file,
|
|
110
122
|
// inputs, per-call cwd) resolve against it and calls default to it. It used to be ignored, so a relative
|
|
111
123
|
// workflow path was looked up in the session's directory instead.
|
|
@@ -132,7 +144,7 @@ export function request(args, cwd) {
|
|
|
132
144
|
if (!Array.isArray(list) || !list.length)
|
|
133
145
|
throw new Error("tasks/chain must be nonempty");
|
|
134
146
|
const kind = tasks !== undefined ? "tasks" : "chain";
|
|
135
|
-
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}]`));
|
|
136
148
|
compileFanout(kind === "tasks" ? { tasks: body.tasks } : { chain: body.chain }); // duplicate keys fail here, not at admission
|
|
137
149
|
}
|
|
138
150
|
else
|
package/dist/agent/main.js
CHANGED
|
@@ -11,7 +11,7 @@ import { launchOrchestrator } from "../platform/launch.js";
|
|
|
11
11
|
import { dsaHome, orchInbox, orchLock, outboxRoot } from "../paths.js";
|
|
12
12
|
import { CT, JT } from "../types.js";
|
|
13
13
|
import { PendingOutboxReader, attention, presentText, presented, resolved, unfinishedWorkflow } from "./main/snapshots.js";
|
|
14
|
-
import { NOTIFY_SINCE, isLive, orchestratorTooOld, ownWorkflows, pausedElsewhere, runningOrchestrator, statusBrief, statusCallDetail, statusCompactDetail, statusDetail, statusView, outputSelect, writerWaits, writerWaitLine, WRITER_WAIT_HINT } from "../orchestrator/snapshot.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";
|
|
15
15
|
import { BATCH, checkAgents, followUpReceipt, outcomeLine, request, sendReceipt } from "./main/tool.js";
|
|
16
16
|
import { parameters } from "./main/schema.js";
|
|
17
17
|
import { batchConflict, batchDigest, findRequest, manyIds, namesMany, requestRid, sendIdentified } from "../requests.js";
|
|
@@ -331,6 +331,10 @@ export function registerMain(pi, ui) {
|
|
|
331
331
|
(args.to === undefined || args.to === body.to) && (args.qid === undefined || args.qid === prior.cond.qid))
|
|
332
332
|
args = { ...args, to: body.to, qid: prior.cond.qid, rev: args.rev ?? prior.cond.rev };
|
|
333
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") };
|
|
334
338
|
if (args.action === "send")
|
|
335
339
|
args = completeSend(args);
|
|
336
340
|
// A session resumes its own held work (what its quit paused); the CLI `resume` remains the global one.
|
|
@@ -430,7 +434,7 @@ export function registerMain(pi, ui) {
|
|
|
430
434
|
pi.registerTool(defineTool({
|
|
431
435
|
name: "subagents", label: "Subagents", description: [
|
|
432
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.",
|
|
433
|
-
"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.",
|
|
434
438
|
"agents: list names, descriptions, default models and source for this cwd; use these names for run.",
|
|
435
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.",
|
|
436
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.",
|
package/dist/cli/main.js
CHANGED
|
@@ -7,7 +7,7 @@ import { setTimeout as delay } from "node:timers/promises";
|
|
|
7
7
|
import { dsaHome } from "../paths.js";
|
|
8
8
|
import { readJournalSnapshot } from "../kernel/journal.js";
|
|
9
9
|
import { journalPath, orchLedger } from "../paths.js";
|
|
10
|
-
import { answerForwardedNote, modelStatusText, queuedText, allWorkflows, eventsFromEntries, heldWorkflows, isLive, formatUsage, renderEvent, statusDetail, statusView, workflowSnapshot, compactWorkflow, labelsText, outputSelect, statusCompactDetail } from "../orchestrator/snapshot.js";
|
|
10
|
+
import { answerForwardedNote, modelStatusText, queuedText, allWorkflows, eventsFromEntries, heldWorkflows, isLive, formatUsage, renderEvent, statusDetail, statusView, workflowSnapshot, compactWorkflow, commandFacts, commandStatus, 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";
|
|
@@ -116,13 +116,15 @@ const answeredNote = (c, paused) => {
|
|
|
116
116
|
return why ? ` (answered): ${why}` : " (answered)"; // no slot claim without a full provider
|
|
117
117
|
return why ? `: ${why}` : "";
|
|
118
118
|
};
|
|
119
|
+
/** A command call's place of a model: " command: <clipped> (pid 123, 2m)" / " command: <clipped> (exit 3)". */
|
|
120
|
+
const commandSuffix = (c) => c.command === undefined ? "" : ` command: ${c.command}${commandFacts(c) ? ` (${commandFacts(c)})` : ""}`;
|
|
119
121
|
/** P25, T10: Render journal-derived status (one line per call, last output line only) without live orchestrator memory. */
|
|
120
122
|
export function renderStatus(wf) {
|
|
121
123
|
const sealed = wf.counts.sealed, total = wf.calls.length, used = wf.usage && (wf.usage.input || wf.usage.output || wf.usage.costUsd);
|
|
122
124
|
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)}` : ""}`,
|
|
123
125
|
...wf.calls.map(c => {
|
|
124
126
|
const last = c.result?.output?.split("\n").map(l => l.trim()).filter(Boolean).at(-1), err = c.result?.error;
|
|
125
|
-
return ` ${c.key}@${c.gen} ${c.result?.status ?? c.phase}${answeredNote(c, wf.paused)}${c.model ? ` ${c.model}` : ""}${c.tools ? ` tools:${c.tools}` : ""}${c.usage && (c.usage.input || c.usage.output) ? ` ${formatUsage(c.usage)}` : ""}${last ? ` ${JSON.stringify(clip(last, 160))}` : err ? ` (${clip(err, 160)})` : ""}${c.sharedWorktree ? ` (shares worktree with ${c.sharedWorktree.join(", ")})` : ""}${c.writerWait && !c.result && c.phase !== "sealed" ? ` (waiting for writer lock: ${c.writerWait.root} held by ${c.writerWait.holder})` : ""}${notesLine(c.notesPending)}${modelStatusText(c)}`;
|
|
127
|
+
return ` ${c.key}@${c.gen} ${c.result?.status ?? c.phase}${answeredNote(c, wf.paused)}${commandSuffix(commandStatus(c))}${c.model ? ` ${c.model}` : ""}${c.tools ? ` tools:${c.tools}` : ""}${c.usage && (c.usage.input || c.usage.output) ? ` ${formatUsage(c.usage)}` : ""}${last ? ` ${JSON.stringify(clip(last, 160))}` : err ? ` (${clip(err, 160)})` : ""}${c.sharedWorktree ? ` (shares worktree with ${c.sharedWorktree.join(", ")})` : ""}${c.writerWait && !c.result && c.phase !== "sealed" ? ` (waiting for writer lock: ${c.writerWait.root} held by ${c.writerWait.holder})` : ""}${notesLine(c.notesPending)}${modelStatusText(c)}`;
|
|
126
128
|
}),
|
|
127
129
|
...wf.attention.map(a => ` ${a.kind}: ${JSON.stringify(clip(a.text, 300))}`),
|
|
128
130
|
...(wf.scriptLog ? [` script log: ${wf.scriptLog}`] : [])].join("\n");
|
|
@@ -135,7 +137,7 @@ export function renderSelected(wf) {
|
|
|
135
137
|
/** P25, T10: Render the compact status projection shared with the `subagents` tool. */
|
|
136
138
|
export function renderView(view) {
|
|
137
139
|
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)}` : ""}`,
|
|
138
|
-
...w.calls.map(c => ` ${c.key}@${c.gen} ${c.status ?? c.phase}${answeredNote(c, w.paused)}${c.hibernated ? " (hibernated, no slot)" : ""}${c.model ? ` ${c.model}` : ""}${c.switching ? ` \u2192 ${c.switching} (requested)` : ""}${c.switchFailed ? ` (switch refused: ${c.switchFailed})` : ""}${c.tools ? ` tools:${c.tools}` : ""}${c.usage ? ` ${formatUsage(c.usage)}` : ""}${c.lastLine ? ` ${JSON.stringify(c.lastLine)}` : c.error ? ` (${c.error})` : ""}${c.sharedWorktree ? ` (shares worktree with ${c.sharedWorktree.join(", ")})` : ""}${c.writerWait && c.phase !== "sealed" ? ` (waiting for writer lock: ${c.writerWait.root} held by ${c.writerWait.holder})` : ""}${c.lease && c.phase !== "sealed" ? ` (${c.lease})` : ""}${notesLine(c.notesPending)}${modelStatusText(c)}`),
|
|
140
|
+
...w.calls.map(c => ` ${c.key}@${c.gen} ${c.status ?? c.phase}${answeredNote(c, w.paused)}${commandSuffix(c)}${c.hibernated ? " (hibernated, no slot)" : ""}${c.model ? ` ${c.model}` : ""}${c.switching ? ` \u2192 ${c.switching} (requested)` : ""}${c.switchFailed ? ` (switch refused: ${c.switchFailed})` : ""}${c.tools ? ` tools:${c.tools}` : ""}${c.usage ? ` ${formatUsage(c.usage)}` : ""}${c.lastLine ? ` ${JSON.stringify(c.lastLine)}` : c.error ? ` (${c.error})` : ""}${c.sharedWorktree ? ` (shares worktree with ${c.sharedWorktree.join(", ")})` : ""}${c.writerWait && c.phase !== "sealed" ? ` (waiting for writer lock: ${c.writerWait.root} held by ${c.writerWait.holder})` : ""}${c.lease && c.phase !== "sealed" ? ` (${c.lease})` : ""}${notesLine(c.notesPending)}${modelStatusText(c)}`),
|
|
139
141
|
...w.attention.map(a => ` ${a.kind}: ${JSON.stringify(a.text.split("\n")[0])}`)].join("\n"));
|
|
140
142
|
if (view.paused)
|
|
141
143
|
lines.unshift(`${view.paused} (pi-durable-subagents resume)`);
|
package/dist/cli/requests.js
CHANGED
|
@@ -8,7 +8,7 @@ import { findJournalEntry, readJournalFold, readJournalSnapshot } from "../kerne
|
|
|
8
8
|
import { isResolution, lifecycleResolution } 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, HOLD_ENTRY_TYPES, heldIn, isLive, orchestratorTooOld, slotsView, workflowSnapshot, writerWaits, writerWaitLine, WRITER_WAIT_HINT } from "../orchestrator/snapshot.js";
|
|
11
|
+
import { NOTIFY_SINCE, HOLD_ENTRY_TYPES, commandLine, commandSendRefusal, isCommandTarget, heldIn, isLive, orchestratorTooOld, slotsView, workflowSnapshot, writerWaits, writerWaitLine, WRITER_WAIT_HINT } from "../orchestrator/snapshot.js";
|
|
12
12
|
import { leaseCalls, leaseState } from "../platform/lease.js";
|
|
13
13
|
import { BATCH, checkAgents, followUpReceipt, outcomeLine, request, sendReceipt } from "../agent/main/tool.js";
|
|
14
14
|
import { discoverAgents } from "../compat/agents.js";
|
|
@@ -144,7 +144,11 @@ function describeWorkflow(home, wid, entries, now) {
|
|
|
144
144
|
...(line(slots.slots, c.model) ? { slot: line(slots.slots, c.model) } : {}), ...(line(slots.exhausted, c.model) ? { exhausted: line(slots.exhausted, c.model) } : {}),
|
|
145
145
|
...(c.hibernated ? { hibernated: true } : {}), ...waits.get(c.callId)
|
|
146
146
|
};
|
|
147
|
+
const run = c.command !== undefined ? c.commandRun : undefined, live = !r && run !== undefined;
|
|
147
148
|
return { key: c.key, gen: c.gen, phase: c.phase, agent: c.agent, ...(c.model ? { model: c.model } : {}),
|
|
149
|
+
...(c.command !== undefined ? { command: commandLine(c.command, 200) } : {}), ...(run?.attempt !== undefined ? { attempt: run.attempt } : {}),
|
|
150
|
+
...(live && run.pid !== undefined ? { pid: run.pid } : {}), ...(live && c.startedAt !== undefined ? { elapsed: commandAge(now - c.startedAt) } : {}),
|
|
151
|
+
...(run?.log ? { log: run.log } : {}),
|
|
148
152
|
...(r ? { status: r.status, ok: r.ok, ...(r.error ? { error: r.error } : {}), output: r.output, ...(r.data !== undefined ? { data: r.data } : {}) } : {}),
|
|
149
153
|
...(waiting && Object.keys(waiting).length ? { waiting } : {}) };
|
|
150
154
|
});
|
|
@@ -163,6 +167,11 @@ export function lastFence(journal, orch) {
|
|
|
163
167
|
const fence = journal.findLast(e => e.type === JT.fenced && !ended.has(String(e.exec)));
|
|
164
168
|
return fence ? { at: Number(fence.ts), exec: String(fence.exec), reason: fenceReason(journal, orch, fence) } : undefined;
|
|
165
169
|
}
|
|
170
|
+
/** A running command call's age: "42s", "3m05s", "1h02m". */
|
|
171
|
+
function commandAge(ms) {
|
|
172
|
+
const s = Math.max(0, Math.floor(ms / 1000));
|
|
173
|
+
return s < 60 ? `${s}s` : s < 3600 ? `${Math.floor(s / 60)}m${String(s % 60).padStart(2, "0")}s` : `${Math.floor(s / 3600)}h${String(Math.floor(s / 60) % 60).padStart(2, "0")}m`;
|
|
174
|
+
}
|
|
166
175
|
export function renderDescription(d) {
|
|
167
176
|
const lines = [`${d.request ?? d.wid}: ${d.state}${d.reason ? ` (${d.reason})` : ""}${d.wid && d.request ? ` — ${d.wid}` : ""}${d.status && d.state !== d.status ? ` · ${d.status}` : ""}`];
|
|
168
177
|
if (d.labels)
|
|
@@ -172,7 +181,12 @@ export function renderDescription(d) {
|
|
|
172
181
|
if (d.error)
|
|
173
182
|
lines.push(` error: ${d.error}`);
|
|
174
183
|
for (const c of d.calls ?? []) {
|
|
175
|
-
|
|
184
|
+
const facts = [c.pid !== undefined ? `pid ${c.pid}` : "", c.attempt !== undefined ? `attempt ${c.attempt}` : "", c.elapsed ?? ""].filter(Boolean).join(", ");
|
|
185
|
+
lines.push(c.command !== undefined
|
|
186
|
+
? ` ${c.key}@${c.gen} command ${c.phase}${c.status ? ` ${c.status}` : ""}${facts ? ` (${facts})` : ""}${c.error ? ` — ${c.error}` : ""}`
|
|
187
|
+
: ` ${c.key}@${c.gen} ${c.agent} ${c.phase}${c.status ? ` ${c.status}` : ""}${c.model ? ` (${c.model})` : ""}${c.error ? ` — ${c.error}` : ""}`);
|
|
188
|
+
if (c.command !== undefined)
|
|
189
|
+
lines.push(` command: ${c.command}`, ...(c.log ? [` log: ${c.log}`] : []));
|
|
176
190
|
if (c.waiting)
|
|
177
191
|
lines.push(` waiting: ${JSON.stringify(c.waiting)}`);
|
|
178
192
|
if (c.data !== undefined)
|
|
@@ -295,7 +309,7 @@ export function runSession(flag, env) {
|
|
|
295
309
|
return inherited && SESSION_ID.test(inherited) ? inherited : undefined;
|
|
296
310
|
}
|
|
297
311
|
/** `run --request <id> --spec <file|-> [--session <id>] [--cwd <dir>] [--json] [--wait-ms <n>]`. The spec is the `subagents` run
|
|
298
|
-
* form ({agent,task,…} or {tasks|chain:[…],…}); it is validated by the tool's own normalizer and agent check. */
|
|
312
|
+
* form ({agent,task,…}, {command,…} or {tasks|chain:[…],…}); it is validated by the tool's own normalizer and agent check. */
|
|
299
313
|
export const runCommand = (args, ctx) => refusable(args, ctx, runRequest);
|
|
300
314
|
async function runRequest(args, ctx, seen) {
|
|
301
315
|
const { values, positionals } = flags(args, { request: "value", spec: "value", cwd: "value", labels: "value", session: "value", json: "flag", "wait-ms": "value" });
|
|
@@ -469,6 +483,9 @@ async function sendRequest(args, ctx, seen, batch) {
|
|
|
469
483
|
if (rev !== undefined && !/^\d+$/.test(rev))
|
|
470
484
|
throw new Error("--rev needs a positive integer");
|
|
471
485
|
let qid = text(values, "qid"), revision = rev !== undefined ? Number(rev) : undefined;
|
|
486
|
+
// R8: a command call has no questions: an answer is refused with the pinned reason, not "no open question".
|
|
487
|
+
if (kind === "answer" && (qid === undefined || revision === undefined) && isCommandTarget(ctx.home, where.to))
|
|
488
|
+
throw new Error(commandSendRefusal("answer"));
|
|
472
489
|
if (kind === "answer" && (qid === undefined || revision === undefined)) {
|
|
473
490
|
// The open question of the target call (or, on a retry, the one the original answered) supplies qid/rev.
|
|
474
491
|
const before = prior?.kind === "send" && prior.body.kind === "answer" && prior.body.to === where.to ? prior.cond : undefined;
|
package/dist/compat/fanout.js
CHANGED
|
@@ -17,13 +17,22 @@ export function compileFanout(input) {
|
|
|
17
17
|
return { key, spec: spec };
|
|
18
18
|
});
|
|
19
19
|
const prefix = `const steps = ${JSON.stringify(steps)};\n`;
|
|
20
|
-
const source = kind === "tasks"
|
|
21
|
-
|
|
22
|
-
|
|
20
|
+
const source = prefix + (kind === "tasks" ? TASKS_BODY : CHAIN_BODY);
|
|
21
|
+
return { source, steps };
|
|
22
|
+
}
|
|
23
|
+
const TASKS_BODY = "return await runs.all(steps.map(({key, spec}) => ({...spec, key})));\n";
|
|
24
|
+
/** A chain step's task gets the previous step's output as {previous}; a command step (no task) runs unchanged. */
|
|
25
|
+
const CHAIN_BODY = chainBody(`spec.command === undefined ? {...spec, task: spec.task.replaceAll("{previous}", () => previous)} : spec`);
|
|
26
|
+
/** The chain body before command calls (1.0.43 and earlier): workflows pinned with it keep running it. */
|
|
27
|
+
const LEGACY_CHAIN_BODY = chainBody(`{...spec, task: spec.task.replaceAll("{previous}", () => previous)}`);
|
|
28
|
+
/** Every script body compileFanout emits or emitted after its `const steps = [...];` line (a pinned fanout is one of them). */
|
|
29
|
+
export const FANOUT_BODIES = [TASKS_BODY, CHAIN_BODY, LEGACY_CHAIN_BODY];
|
|
30
|
+
function chainBody(stepSpec) {
|
|
31
|
+
return `const results = [];
|
|
23
32
|
let previous = "";
|
|
24
33
|
for (let i = 0; i < steps.length; i++) {
|
|
25
34
|
const {key, spec} = steps[i];
|
|
26
|
-
const result = await runs.run(key, {
|
|
35
|
+
const result = await runs.run(key, ${stepSpec});
|
|
27
36
|
results.push(result);
|
|
28
37
|
if (!result.ok) {
|
|
29
38
|
const skipped = steps.slice(i + 1).map(({key}) => ({key, gen: 0, status: "skipped", ok: false, output: ""}));
|
|
@@ -35,5 +44,4 @@ for (let i = 0; i < steps.length; i++) {
|
|
|
35
44
|
}
|
|
36
45
|
return results;
|
|
37
46
|
`;
|
|
38
|
-
return { source, steps };
|
|
39
47
|
}
|