pi-durable-subagents 1.0.25 → 1.0.28

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/dist/cli/main.js CHANGED
@@ -7,7 +7,8 @@ import { setTimeout as delay } from "node:timers/promises";
7
7
  import { dsaHome } from "../paths.js";
8
8
  import { readJournalSnapshot } from "../kernel/journal.js";
9
9
  import { journalPath, orchLedger } from "../paths.js";
10
- import { allWorkflows, eventsFromEntries, formatUsage, renderEvent, statusDetail, statusView, workflowSnapshot, compactWorkflow } from "../orchestrator/snapshot.js";
10
+ import { allWorkflows, eventsFromEntries, formatUsage, renderEvent, statusDetail, statusView, workflowSnapshot, compactWorkflow, labelsText, outputSelect, statusCompactDetail } from "../orchestrator/snapshot.js";
11
+ import { statsLine } from "../orchestrator/stats.js";
11
12
  import { resolution, start, startOrchestrator, submit } from "./control.js";
12
13
  import { doctor, renderDoctor, size } from "./doctor.js";
13
14
  import { smoke } from "./smoke.js";
@@ -34,7 +35,27 @@ export function parseArgs(args) {
34
35
  olderThanDays = Number(value);
35
36
  rest = [...rest.slice(0, at), ...rest.slice(at + 2)];
36
37
  }
37
- let force, reason;
38
+ let force, reason, tail, grep;
39
+ for (const flag of ["--tail", "--grep"]) {
40
+ const index = rest.indexOf(flag);
41
+ if (index < 0)
42
+ continue;
43
+ if (command !== "status")
44
+ throw new Error(`${flag} is only supported by status <wid>`);
45
+ if (rest.filter(a => a === flag).length > 1)
46
+ throw new Error("Unknown or repeated option");
47
+ const value = rest[index + 1];
48
+ if (value === undefined)
49
+ throw new Error(`${flag} needs a value`);
50
+ if (flag === "--tail") {
51
+ if (!/^[1-9]\d*$/.test(value))
52
+ throw new Error("--tail needs a positive number of lines");
53
+ tail = Number(value);
54
+ }
55
+ else
56
+ grep = value;
57
+ rest = [...rest.slice(0, index), ...rest.slice(index + 2)];
58
+ }
38
59
  for (const flag of ["--force", "--reason"]) {
39
60
  const index = rest.indexOf(flag);
40
61
  if (index < 0)
@@ -70,30 +91,41 @@ export function parseArgs(args) {
70
91
  throw new Error("Invalid workflow id");
71
92
  if (target && olderThanDays !== undefined)
72
93
  throw new Error("prune takes a workflow id or --older-than, not both");
73
- return { command, json, ...(force !== undefined ? { force } : {}), ...(reason !== undefined ? { reason } : {}), ...(dryRun ? { dryRun } : {}), ...(target ? { target } : {}), ...(olderThanDays !== undefined ? { olderThanDays } : {}) };
94
+ if ((tail !== undefined || grep !== undefined) && !target)
95
+ throw new Error("--tail and --grep select lines of one workflow's outputs: status <wid> --tail <n> --grep <regex>");
96
+ if (grep !== undefined)
97
+ outputSelect(undefined, grep); // an invalid regular expression is a usage error
98
+ return { command, json, ...(tail !== undefined ? { tail } : {}), ...(grep !== undefined ? { grep } : {}), ...(force !== undefined ? { force } : {}), ...(reason !== undefined ? { reason } : {}), ...(dryRun ? { dryRun } : {}), ...(target ? { target } : {}), ...(olderThanDays !== undefined ? { olderThanDays } : {}) };
74
99
  }
75
100
  const clip = (text, n) => text.length > n ? `${text.slice(0, n)}…` : text;
101
+ /** Notes recorded for a call that is not running (send kind "notify"); its next follow-up carries them. */
102
+ const notesLine = (n) => n ? ` · ${n} note${n > 1 ? "s" : ""} pending` : "";
76
103
  /** P25, T10: Render journal-derived status (one line per call, last output line only) without live orchestrator memory. */
77
104
  export function renderStatus(wf) {
78
105
  const sealed = wf.counts.sealed, total = wf.calls.length, used = wf.usage && (wf.usage.input || wf.usage.output || wf.usage.costUsd);
79
- return [`${wf.wid}@${wf.rev}${wf.name ? ` ${wf.name}` : ""}: ${wf.status}${wf.error ? ` (${clip(wf.error, 300)})` : ""} · ${sealed}/${total} sealed${used ? ` · ${formatUsage(wf.usage)}` : ""}`,
106
+ return [`${wf.wid}@${wf.rev}${wf.labels ? ` ${labelsText(wf.labels)}` : ""}${wf.name ? ` ${wf.name}` : ""}: ${wf.status}${wf.error ? ` (${clip(wf.error, 300)})` : ""} · ${sealed}/${total} sealed${used ? ` · ${formatUsage(wf.usage)}` : ""}`,
80
107
  ...wf.calls.map(c => {
81
108
  const last = c.result?.output?.split("\n").map(l => l.trim()).filter(Boolean).at(-1), err = c.result?.error;
82
- return ` ${c.key}@${c.gen} ${c.result?.status ?? c.phase}${c.model ? ` ${c.model}` : ""}${c.tools ? ` tools:${c.tools}` : ""}${c.usage && (c.usage.input || c.usage.output) ? ` ${formatUsage(c.usage)}` : ""}${last ? ` ${JSON.stringify(clip(last, 160))}` : err ? ` (${clip(err, 160)})` : ""}${c.sharedWorktree ? ` (shares worktree with ${c.sharedWorktree.join(", ")})` : ""}${c.writerWait && !c.result && c.phase !== "sealed" ? ` (waiting for writer lock: ${c.writerWait.root} held by ${c.writerWait.holder})` : ""}`;
109
+ return ` ${c.key}@${c.gen} ${c.result?.status ?? c.phase}${c.model ? ` ${c.model}` : ""}${c.tools ? ` tools:${c.tools}` : ""}${c.usage && (c.usage.input || c.usage.output) ? ` ${formatUsage(c.usage)}` : ""}${last ? ` ${JSON.stringify(clip(last, 160))}` : err ? ` (${clip(err, 160)})` : ""}${c.sharedWorktree ? ` (shares worktree with ${c.sharedWorktree.join(", ")})` : ""}${c.writerWait && !c.result && c.phase !== "sealed" ? ` (waiting for writer lock: ${c.writerWait.root} held by ${c.writerWait.holder})` : ""}${notesLine(c.notesPending)}`;
83
110
  }),
84
111
  ...wf.attention.map(a => ` ${a.kind}: ${JSON.stringify(clip(a.text, 300))}`),
85
112
  ...(wf.scriptLog ? [` script log: ${wf.scriptLog}`] : [])].join("\n");
86
113
  }
114
+ /** `status <wid> --tail/--grep`: the workflow line, then each call with its selected output lines. */
115
+ export function renderSelected(wf) {
116
+ return [`${wf.wid}@${wf.rev}${wf.labels ? ` ${labelsText(wf.labels)}` : ""}${wf.name ? ` ${wf.name}` : ""}: ${wf.status} · ${wf.done}/${wf.planned ?? wf.calls.length} done`,
117
+ ...wf.calls.flatMap(c => [` ${c.key}@${c.gen} ${c.status ?? c.phase}`, ...(c.output ? c.output.split("\n").map(l => ` | ${l}`) : [])])].join("\n");
118
+ }
87
119
  /** P25, T10: Render the compact status projection shared with the `subagents` tool. */
88
120
  export function renderView(view) {
89
- const lines = view.workflows.map(w => [`${w.wid}@${w.rev}${w.name ? ` ${w.name}` : ""}: ${w.status}${w.followUps ? " (follow-up running)" : ""}${w.error ? ` (${clip(w.error, 200)})` : ""} · ${w.done}/${w.planned ?? w.calls.length}${w.planned === undefined && w.status === "running" ? "+" : ""} done${w.usage.input || w.usage.output || w.usage.costUsd ? ` · ${formatUsage(w.usage)}` : ""}`,
90
- ...w.calls.map(c => ` ${c.key}@${c.gen} ${c.status ?? c.phase}${c.hibernated ? " (hibernated, no slot)" : ""}${c.model ? ` ${c.model}` : ""}${c.switching ? ` → ${c.switching} (requested)` : ""}${c.switchFailed ? ` (switch refused: ${c.switchFailed})` : ""}${c.tools ? ` tools:${c.tools}` : ""}${c.usage ? ` ${formatUsage(c.usage)}` : ""}${c.lastLine ? ` ${JSON.stringify(c.lastLine)}` : c.error ? ` (${c.error})` : ""}${c.sharedWorktree ? ` (shares worktree with ${c.sharedWorktree.join(", ")})` : ""}${c.writerWait && c.phase !== "sealed" ? ` (waiting for writer lock: ${c.writerWait.root} held by ${c.writerWait.holder})` : ""}${c.lease && c.phase !== "sealed" ? ` (${c.lease})` : ""}`),
121
+ const lines = view.workflows.map(w => [`${w.wid}@${w.rev}${w.labels ? ` ${labelsText(w.labels)}` : ""}${w.name ? ` ${w.name}` : ""}: ${w.status}${w.followUps ? " (follow-up running)" : ""}${w.error ? ` (${clip(w.error, 200)})` : ""} · ${w.done}/${w.planned ?? w.calls.length}${w.planned === undefined && w.status === "running" ? "+" : ""} done${w.usage.input || w.usage.output || w.usage.costUsd ? ` · ${formatUsage(w.usage)}` : ""}`,
122
+ ...w.calls.map(c => ` ${c.key}@${c.gen} ${c.status ?? c.phase}${c.hibernated ? " (hibernated, no slot)" : ""}${c.model ? ` ${c.model}` : ""}${c.switching ? ` → ${c.switching} (requested)` : ""}${c.switchFailed ? ` (switch refused: ${c.switchFailed})` : ""}${c.tools ? ` tools:${c.tools}` : ""}${c.usage ? ` ${formatUsage(c.usage)}` : ""}${c.lastLine ? ` ${JSON.stringify(c.lastLine)}` : c.error ? ` (${c.error})` : ""}${c.sharedWorktree ? ` (shares worktree with ${c.sharedWorktree.join(", ")})` : ""}${c.writerWait && c.phase !== "sealed" ? ` (waiting for writer lock: ${c.writerWait.root} held by ${c.writerWait.holder})` : ""}${c.lease && c.phase !== "sealed" ? ` (${c.lease})` : ""}${notesLine(c.notesPending)}`),
91
123
  ...w.attention.map(a => ` ${a.kind}: ${JSON.stringify(a.text.split("\n")[0])}`)].join("\n"));
92
124
  if (view.paused)
93
125
  lines.unshift(`${view.paused} (pi-durable-subagents resume)`);
94
126
  if (view.olderFinished)
95
127
  lines.push(`(+${view.olderFinished} older finished workflows; status <wid> shows one in detail)`);
96
- const footer = [view.slots?.length ? `slots: ${view.slots.join(", ")}` : "", view.config ? `config: ${view.config}` : "", view.configRejected ? `config.json rejected: ${view.configRejected}` : "", view.orchestrator ? `orchestrator: ${view.orchestrator}` : "", ...(view.leases ?? []).map(l => `lease: ${l}`), ...(view.exhausted ?? []), view.versionNote ? `note: ${view.versionNote}` : ""].filter(Boolean);
128
+ const footer = [view.slots?.length ? `slots: ${view.slots.join(", ")}` : "", view.config ? `config: ${view.config}` : "", view.configRejected ? `config.json rejected: ${view.configRejected}` : "", view.orchestrator || view.orchestratorStats ? `orchestrator: ${[view.orchestrator, view.orchestratorStats ? statsLine(view.orchestratorStats) : ""].filter(Boolean).join(" · ")}` : "", ...(view.leases ?? []).map(l => `lease: ${l}`), ...(view.exhausted ?? []), view.versionNote ? `note: ${view.versionNote}` : ""].filter(Boolean);
97
129
  if (!lines.length)
98
130
  lines.push("No workflows");
99
131
  return [...lines, ...footer].join("\n");
@@ -132,7 +164,7 @@ export function serviceEntryError(entry) {
132
164
  return `install-service refuses to run from an npx cache (${entry}); the cache can be pruned and the service would break. Install the CLI with \`npm i -g pi-durable-subagents\` and run \`pi-durable-subagents install-service\` again.`;
133
165
  return undefined;
134
166
  }
135
- export const HELP = "pi-durable-subagents: smoke | status [wid] [--json] | events <wid> [--json] | events --all [--since <cursor>] [--limit <n>] [--json] [--wait-ms <n>] | tail [wid] [--json] | start | resume [wid] | drain | stop <wid|callId> | stop-all | run --request <id> --spec <file|-> [--labels <json>] [--cwd <dir>] [--json] [--wait-ms <n>] | send --request <id> --to <run-id|wid/key> [--call <key>] --kind follow-up|answer|steer|model [--qid <qid> --rev <n>] [--message <text|@file>] [--model <m>] [--json] [--wait-ms <n>] | stop --request <id> <run-id|wid|wid/key> [--json] [--wait-ms <n>] | describe --key <id> | describe <wid> [--json] | prune [wid] [--older-than <days>] | restart [--force <token> --reason <text>] | hold <resource> [--shared] [--max-wait <s>] [--note <text>] -- <command…> | leases [--json] | doctor [--json] | install-service [--dry-run] | uninstall-service [--dry-run] | chaos [--scenario <1-9>] [--keep] [--json]";
167
+ export const HELP = "pi-durable-subagents: smoke | status [wid] [--json] | status <wid> [--tail <n>] [--grep <regex>] [--json] | events <wid> [--json] | events --all [--since <cursor>] [--limit <n>] [--json] [--wait-ms <n>] | tail [wid] [--json] | start | resume [wid] | drain | stop <wid|callId> | stop-all | run --request <id> --spec <file|-> [--labels <json>] [--cwd <dir>] [--json] [--wait-ms <n>] | send --request <id> --to <run-id|wid/key> [--to ...] [--call <key>] --kind follow-up|answer|steer|notify|model [--qid <qid> --rev <n>] [--message <text|@file>] [--model <m>] [--json] [--wait-ms <n>] | stop --request <id> <run-id|wid|wid/key> [--json] [--wait-ms <n>] | describe --key <id> | describe <wid> [--json] | prune [wid] [--older-than <days>] | restart [--force <token> --reason <text>] | hold <resource> [--shared | --slots <n>] [--max-wait <s> | --no-wait] [--note <text>] -- <command…> | leases [--json] | doctor [--json] | install-service [--dry-run] | uninstall-service [--dry-run] | chaos [--scenario <1-9>] [--keep] [--json] | drill failover [--keep] [--json]";
136
168
  /** Restart: the orchestrator exits when no execution runs (or `force`) and the installed version takes over. */
137
169
  async function restartCommand(home, env, write, options) {
138
170
  const body = { ...(typeof options.force === "string" ? { token: options.force } : options.force === true ? { force: true } : {}), ...(options.reason !== undefined ? { reason: options.reason } : {}), initiator: cliInitiator(env) };
@@ -194,6 +226,8 @@ export async function main(args = process.argv.slice(2), options = {}) {
194
226
  }
195
227
  if (args[0] === "chaos")
196
228
  return (await import("./chaos/index.js")).chaos(args.slice(1), options.env ?? process.env, options.write);
229
+ if (args[0] === "drill")
230
+ return (await import("./drill/index.js")).drill(args.slice(1), options.env ?? process.env, options.write);
197
231
  // The cross-workflow event log (strict flags of its own); `events <wid>` stays below.
198
232
  if (args[0] === "events" && args.includes("--all")) {
199
233
  const env = options.env ?? process.env;
@@ -206,7 +240,7 @@ export async function main(args = process.argv.slice(2), options = {}) {
206
240
  return args[0] === "run" ? requests.runCommand(args.slice(1), ctx) : args[0] === "send" ? requests.sendCommand(args.slice(1), ctx)
207
241
  : args[0] === "stop" ? requests.stopCommand(args.slice(1), ctx) : requests.describeCommand(args.slice(1), ctx);
208
242
  }
209
- const { command, target, json, dryRun, olderThanDays, force, reason } = parseArgs(args), env = options.env ?? process.env;
243
+ const { command, target, json, dryRun, olderThanDays, force, reason, tail: lines, grep } = parseArgs(args), env = options.env ?? process.env;
210
244
  const home = dsaHome(env), write = options.write ?? (line => console.log(line));
211
245
  if (command === "help") {
212
246
  write(HELP);
@@ -227,7 +261,12 @@ export async function main(args = process.argv.slice(2), options = {}) {
227
261
  return report.execution.every(c => c.ok) ? 0 : 1;
228
262
  }
229
263
  if (command === "status") {
230
- if (target) {
264
+ const select = outputSelect(lines, grep);
265
+ if (target && select) {
266
+ const detail = statusCompactDetail(home, target, select);
267
+ write(json ? JSON.stringify(detail, null, 2) : renderSelected(detail));
268
+ }
269
+ else if (target) {
231
270
  const detail = statusDetail(home, target);
232
271
  write(json ? JSON.stringify(detail, null, 2) : renderStatus(detail));
233
272
  }
@@ -7,10 +7,10 @@ import { setTimeout as delay } from "node:timers/promises";
7
7
  import { readJournalSnapshot } from "../kernel/journal.js";
8
8
  import { reduceLifecycle } from "../kernel/lifecycle.js";
9
9
  import { journalPath, orchLedger, pinnedDir } from "../paths.js";
10
- import { findRequest, REQUEST_ID, requestId, requestRid, RequestsBusy, specDigest } from "../requests.js";
11
- import { isLive, slotsView, workflowSnapshot } from "../orchestrator/snapshot.js";
10
+ import { batchConflict, batchDigest, findRequest, manyIds, namesMany, REQUEST_ID, requestId, requestRid, RequestsBusy, specDigest } from "../requests.js";
11
+ import { NOTIFY_SINCE, isLive, orchestratorTooOld, slotsView, workflowSnapshot, writerWaits, writerWaitLine, WRITER_WAIT_HINT } from "../orchestrator/snapshot.js";
12
12
  import { leaseCalls, leaseState } from "../platform/lease.js";
13
- import { checkAgents, request } from "../agent/main/tool.js";
13
+ import { BATCH, checkAgents, outcomeLine, request, sendReceipt } from "../agent/main/tool.js";
14
14
  import { discoverAgents } from "../compat/agents.js";
15
15
  import { JT } from "../types.js";
16
16
  import { startOrchestrator, submitIdentified } from "./control.js";
@@ -19,9 +19,10 @@ import { parseLabels } from "../events/labels.js";
19
19
  import { foldWaits, leaseWaits, waitsOf } from "../events/waiting.js";
20
20
  import { emptyLedger, foldLedger } from "../orchestrator/ledger.js";
21
21
  export const EXIT = { ok: 0, rejected: 1, conflict: 3, pending: 75 };
22
- /** Strict `--name value` / `--flag` parsing; unknown or repeated options are errors. */
23
- function flags(args, spec) {
24
- const values = {}, positionals = [];
22
+ /** Strict `--name value` / `--flag` parsing; unknown or repeated options are errors, except those given in `repeated`
23
+ * (every value is kept, in order, in `lists`). */
24
+ function flags(args, spec, repeated = []) {
25
+ const values = {}, positionals = [], lists = {};
25
26
  for (let i = 0; i < args.length; i++) {
26
27
  const arg = args[i];
27
28
  if (!arg.startsWith("--")) {
@@ -29,6 +30,11 @@ function flags(args, spec) {
29
30
  continue;
30
31
  }
31
32
  const name = arg.slice(2), kind = spec[name];
33
+ if (kind === "value" && repeated.includes(name) && args[i + 1] !== undefined) {
34
+ (lists[name] ??= []).push(args[++i]);
35
+ values[name] = args[i];
36
+ continue;
37
+ }
32
38
  if (!kind || Object.hasOwn(values, name))
33
39
  throw new Error(`Unknown or repeated option ${arg}`);
34
40
  if (kind === "flag") {
@@ -40,7 +46,7 @@ function flags(args, spec) {
40
46
  throw new Error(`${arg} needs a value`);
41
47
  values[name] = value;
42
48
  }
43
- return { values, positionals };
49
+ return { values, positionals, lists };
44
50
  }
45
51
  const text = (values, name) => typeof values[name] === "string" ? values[name] : undefined;
46
52
  function waitMs(values, ctx) {
@@ -201,7 +207,7 @@ async function outcome(home, rid, run, timeoutMs) {
201
207
  async function conflict(ctx, id, original, json) {
202
208
  const d = await describe(ctx.home, { request: id });
203
209
  const reply = { request: id, error: "request-conflict", ...(d.wid ? { wid: d.wid } : {}), spec_digest: original, state: d.state };
204
- ctx.write(json ? JSON.stringify(reply) : `${id}: request-conflict — this id names other content (${d.state}${d.wid ? `, ${d.wid}` : ""}); retry with the stored spec bytes or use a new id`);
210
+ ctx.write(json ? JSON.stringify(reply) : `${id}: request-conflict - this id names other content (${d.state}${d.wid ? `, ${d.wid}` : ""}); retry with the stored spec bytes or use a new id`);
205
211
  return EXIT.conflict;
206
212
  }
207
213
  function pending(ctx, id, json, why = "") {
@@ -306,8 +312,11 @@ async function runRequest(args, ctx, seen) {
306
312
  ctx.write(json ? JSON.stringify({ request: id, applied: false, reason: done.outcome.reason, spec_digest: done.sent.digest }) : `${id}: rejected ${done.outcome.reason}`);
307
313
  return EXIT.rejected;
308
314
  }
309
- const reply = { request: id, wid: done.outcome.wid, created: !done.earlier, spec_digest: done.sent.digest };
310
- ctx.write(json ? JSON.stringify(reply) : `${id} → ${reply.wid} (${reply.created ? "created" : "existing"})`);
315
+ // Calls already queued behind a worktree's writer lock are named at once (read once; nothing waits for them).
316
+ const waits = writerWaits(ctx.home, done.outcome.wid);
317
+ const reply = { request: id, wid: done.outcome.wid, created: !done.earlier, spec_digest: done.sent.digest, ...(waits.length ? { writerWait: waits, hint: WRITER_WAIT_HINT } : {}) };
318
+ ctx.write(json ? JSON.stringify(reply) : [`${id} → ${reply.wid} (${reply.created ? "created" : "existing"})`,
319
+ ...waits.map(w => ` writerWait: ${writerWaitLine(w)}`), ...(waits.length ? [` hint: ${WRITER_WAIT_HINT}`] : [])].join("\n"));
311
320
  return EXIT.ok;
312
321
  }
313
322
  /** `<run-id>` or `<wid>` → wid when that run id created one; `pending` when the run is known but has no workflow yet. */
@@ -341,16 +350,84 @@ async function target(home, to, call, prior) {
341
350
  return { to: `${resolved.wid}/${keys[0]}` };
342
351
  throw new Error(`${to} has ${keys.length ? `calls ${keys.join(", ")}` : "no calls yet"}; name one with --call <key> or --to <wid>/<key>`);
343
352
  }
344
- /** `send --request <id> --to <…> --kind follow-up|answer|steer|model [--qid <qid> --rev <n>] --message <text|@file> [--model <m>]`. */
345
- export const sendCommand = (args, ctx) => refusable(args, ctx, sendRequest);
346
- async function sendRequest(args, ctx, seen) {
347
- const { values, positionals } = flags(args, { request: "value", to: "value", call: "value", kind: "value", qid: "value", rev: "value", message: "value", model: "value", json: "flag", "wait-ms": "value" });
353
+ const SEND_FLAGS = { request: "value", to: "value", call: "value", kind: "value", qid: "value", rev: "value", message: "value", model: "value", json: "flag", "wait-ms": "value" };
354
+ const SEND_USAGE = "usage: send --request <id> --to <run-id|wid/key> [--to ...] --kind follow-up|answer|steer|notify|model [--qid <qid> --rev <n>] --message <text|@file> [--model <m>] [--json]";
355
+ /** `send --request <id> --to <...> --kind follow-up|answer|steer|notify|model [--qid <qid> --rev <n>] --message <text|@file> [--model <m>]`.
356
+ * A repeated --to sends one request per call (see sendMany). */
357
+ export const sendCommand = (args, ctx) => {
358
+ const at = args.flatMap((a, i) => a === "--to" ? [i] : []);
359
+ return at.length > 1 ? sendMany(args, at, ctx) : refusable(args, ctx, sendRequest);
360
+ };
361
+ /** A send to several calls (repeated --to): one request per target, `<id>:1` ... `<id>:n` in the order given, each decided
362
+ * on its own; one line (or, with --json, one entry of `targets`) per target. Exit 3 when the id or one target's id names
363
+ * other content, else 75 when one is not decided yet, else 1 when one was rejected, else 0. */
364
+ async function sendMany(args, at, ctx) {
365
+ const json = args.includes("--json");
366
+ let id, targets, ids;
367
+ try {
368
+ const parsed = flags(args, SEND_FLAGS, ["to"]);
369
+ if (text(parsed.values, "kind") === "answer")
370
+ throw new Error("answer goes to one call: give a single --to");
371
+ if (!text(parsed.values, "request") || parsed.positionals.length)
372
+ throw new Error(SEND_USAGE);
373
+ id = text(parsed.values, "request");
374
+ targets = parsed.lists.to;
375
+ ids = manyIds(id, targets.length);
376
+ }
377
+ catch (error) {
378
+ if (!json)
379
+ throw error;
380
+ const at = args.indexOf("--request");
381
+ ctx.write(JSON.stringify({ request: at >= 0 && at + 1 < args.length ? args[at + 1] : null, applied: false, reason: error.message }));
382
+ return EXIT.rejected;
383
+ }
384
+ const batch = batchDigest(targets);
385
+ if (await batchConflict(ctx.home, id, batch)) {
386
+ ctx.write(json ? JSON.stringify({ request: id, error: "request-conflict" }) : `${id}: request-conflict - this id names other content (another message or list of calls); retry with the same targets or use a new id`);
387
+ return EXIT.conflict;
388
+ }
389
+ const rest = args.filter((_, i) => !at.includes(i) && !at.includes(i - 1));
390
+ const request = rest.indexOf("--request");
391
+ const results = await Promise.all(targets.map(async (to, i) => {
392
+ const lines = [], own = [...rest.slice(0, request + 1), ids[i], ...rest.slice(request + 2), "--to", to, ...(json ? [] : ["--json"])];
393
+ let code;
394
+ try {
395
+ code = await refusable(own, { ...ctx, write: line => lines.push(line) }, (a, c, seen) => sendRequest(a, c, seen, batch));
396
+ }
397
+ catch (error) {
398
+ return { code: EXIT.rejected, reply: { request: ids[i], applied: false, reason: error.message }, to };
399
+ }
400
+ let reply;
401
+ try {
402
+ reply = JSON.parse(lines.join(""));
403
+ }
404
+ catch {
405
+ reply = { request: ids[i], output: lines.join("\n") };
406
+ }
407
+ return { code, reply, to };
408
+ }));
409
+ const codes = results.map(r => r.code);
410
+ const code = codes.includes(EXIT.conflict) ? EXIT.conflict : codes.includes(EXIT.pending) ? EXIT.pending : codes.some(c => c !== EXIT.ok) ? EXIT.rejected : EXIT.ok;
411
+ if (json)
412
+ ctx.write(JSON.stringify({ request: id, targets: results.map(r => ({ to: r.to, ...r.reply })) }));
413
+ else
414
+ for (const r of results)
415
+ ctx.write(`${r.to}: ${r.reply.error === "request-conflict" ? "request-conflict" : r.reply.pending ? `submitted, not decided yet${r.reply.reason ? ` (${String(r.reply.reason)})` : ""}` : outcomeLine(r.reply)} [${String(r.reply.request)}]`);
416
+ return code;
417
+ }
418
+ async function sendRequest(args, ctx, seen, batch) {
419
+ const { values, positionals } = flags(args, SEND_FLAGS);
348
420
  const id = text(values, "request"), to = text(values, "to"), kind = text(values, "kind"), json = values.json === true, wait = waitMs(values, ctx);
349
421
  seen.id = id;
350
422
  seen.json = json;
351
423
  if (!id || !to || !kind || positionals.length)
352
- throw new Error("usage: send --request <id> --to <run-id|wid/key> --kind follow-up|answer|steer|model [--qid <qid> --rev <n>] --message <text|@file> [--model <m>] [--json]");
424
+ throw new Error(SEND_USAGE);
353
425
  const rid = requestRid(id), prior = (await findRequest(ctx.home, rid))?.request;
426
+ // A single send under an id that names a send to several calls (<id>:1 ...) is other content.
427
+ if (!prior && await namesMany(ctx.home, id)) {
428
+ ctx.write(json ? JSON.stringify({ request: id, error: "request-conflict" }) : `${id}: request-conflict - this id names a send to several calls; use a new id`);
429
+ return EXIT.conflict;
430
+ }
354
431
  const where = await target(ctx.home, to, text(values, "call"), prior);
355
432
  if ("pending" in where)
356
433
  return pending(ctx, id, json, `run ${to.split("/")[0]} has no workflow yet`);
@@ -371,9 +448,15 @@ async function sendRequest(args, ctx, seen) {
371
448
  revision ??= open[0].rev;
372
449
  }
373
450
  const normalized = request({ action: "send", to: where.to, kind, ...(message !== undefined ? { message } : {}), ...(text(values, "model") !== undefined ? { model: text(values, "model") } : {}),
374
- ...(qid !== undefined ? { qid } : {}), ...(revision !== undefined ? { rev: revision } : {}) }, ctx.cwd ?? process.cwd());
451
+ ...(qid !== undefined ? { qid } : {}), ...(revision !== undefined ? { rev: revision } : {}), ...(batch !== undefined ? { [BATCH]: batch } : {}) }, ctx.cwd ?? process.cwd());
375
452
  seen.digest = specDigest({ kind: "send", body: normalized.body, cond: normalized.cond });
376
- const done = await submitAndWait(ctx, seen, id, "send", normalized.body, normalized.cond, wait, json);
453
+ // A retry of a recorded request gets its first outcome; a new notify is refused while an orchestrator too old for it runs.
454
+ const old = kind === "notify" && !prior ? orchestratorTooOld(ctx.home, 'send kind "notify"', NOTIFY_SINCE) : undefined;
455
+ if (old)
456
+ throw new Error(old);
457
+ // Inside a subagent the CLI names its call (provenance for `answered.by`; spec_digest ignores it).
458
+ const body = ctx.env.DSA_CALL ? { ...normalized.body, caller: ctx.env.DSA_CALL } : normalized.body;
459
+ const done = await submitAndWait(ctx, seen, id, "send", body, normalized.cond, wait, json);
377
460
  if ("code" in done)
378
461
  return done.code;
379
462
  return decided(ctx, id, done, json);
@@ -409,7 +492,10 @@ function decided(ctx, id, done, json) {
409
492
  const wid = typeof body.to === "string" ? body.to.split("/")[0].split("@")[0] : undefined;
410
493
  const opened = done.sent.request.kind === "send" && wid && existsSync(journalPath(ctx.home, wid))
411
494
  ? readJournalSnapshot(journalPath(ctx.home, wid)).find(e => e.type === "generation" && e.rid === done.sent.request.rid) : undefined;
412
- const reply = { request: id, applied: true, ...(opened ? { generation: Number(opened.gen), call: `${wid}/${String(opened.key)}` } : {}), spec_digest: done.sent.digest };
413
- ctx.write(json ? JSON.stringify(reply) : `${id}: applied${opened ? ` (follow-up generation ${reply.generation} of ${reply.call})` : ""}`);
495
+ // A notify says how it went (steered, held-until-answer or noted); a model send which model and when it applies.
496
+ const notified = done.sent.request.kind === "send" ? sendReceipt(ledger(ctx.home), done.sent.request.rid) : {};
497
+ const receipt = notified.delivery ? { delivery: notified.delivery, note: notified.note } : {};
498
+ const reply = { request: id, applied: true, ...(opened ? { generation: Number(opened.gen), call: `${wid}/${String(opened.key)}` } : {}), ...receipt, spec_digest: done.sent.digest };
499
+ ctx.write(json ? JSON.stringify(reply) : `${id}: applied${opened ? ` (follow-up generation ${reply.generation} of ${reply.call})` : ""}${receipt.delivery ? ` (${receipt.delivery}: ${receipt.note})` : ""}`);
414
500
  return EXIT.ok;
415
501
  }
@@ -23,11 +23,15 @@ export function labelsOf(body) {
23
23
  return entries.length && entries.every(([, v]) => typeof v === "string") ? Object.fromEntries(entries) : undefined;
24
24
  }
25
25
  /** `answered.by` from the answer request's sender: a pi session `main:<id>` → `session:<id>` (+ via "ui" when the
26
- * subagent list sent it, SendBody.by "user"); the CLI sender `cli:<user>@<host>` as is; anything else `unknown`. */
26
+ * subagent list sent it, SendBody.by "user"); the CLI run inside a subagent (SendBody.caller `<wid>@<rev>/<key>@<gen>`)
27
+ * → `call:<wid>/<key>`; any other CLI sender `cli:<user>@<host>` as is; anything else `unknown`. */
27
28
  export function answeredBy(req) {
28
- const from = req?.from ?? "";
29
+ const from = req?.from ?? "", body = req?.body;
29
30
  if (from.startsWith("main:"))
30
- return { by: `session:${from.slice(5)}`, ...(req.body?.by === "user" ? { via: "ui" } : {}) };
31
+ return { by: `session:${from.slice(5)}`, ...(body?.by === "user" ? { via: "ui" } : {}) };
32
+ const caller = typeof body?.caller === "string" ? /^([^/@]+)@\d+\/(.+)@\d+$/.exec(body.caller) : null;
33
+ if (from.startsWith("cli:") && caller)
34
+ return { by: `call:${caller[1]}/${caller[2]}` };
31
35
  if (/^cli:[^@]+@.+$/.test(from))
32
36
  return { by: from };
33
37
  return { by: "unknown" };
@@ -1,5 +1,5 @@
1
1
  import { open, mkdir } from 'node:fs/promises';
2
- import { closeSync, fstatSync, openSync, readSync } from 'node:fs';
2
+ import { closeSync, constants, fstatSync, openSync, readSync } from 'node:fs';
3
3
  import { dirname } from 'node:path';
4
4
  const TABLE = new Uint32Array(256).map((_, n) => { let c = n; for (let k = 0; k < 8; k++)
5
5
  c = (c & 1) ? 0xedb88320 ^ (c >>> 1) : c >>> 1; return c >>> 0; });
@@ -100,33 +100,82 @@ export function readJournalSnapshot(path) {
100
100
  closeSync(fd);
101
101
  }
102
102
  }
103
- /** A1, C11: Repair only the tail, then serialize durable framed appends. */
103
+ /** How long a resting journal keeps its descriptor after its last append (a burst of appends opens it once). */
104
+ export const JOURNAL_REST_MS = 1000;
105
+ let descriptors = 0, appends = 0;
106
+ /** Appends committed by this process to any journal: a fold over journal entries only can be reused while it stays. */
107
+ export function journalAppends() { return appends; }
108
+ /** Journal descriptors this process holds open now (handles opened by openJournal, resting ones excluded). */
109
+ export function openJournalDescriptors() { return descriptors; }
110
+ /** A1, C11: Repair only the tail, then serialize durable framed appends. A resting handle (`resting = true`) closes its
111
+ * descriptor once its appends are done and reopens it for the next append; its entries stay in memory. */
104
112
  export async function openJournal(path) {
105
113
  await mkdir(dirname(path), { recursive: true });
106
114
  let created = false;
107
- const file = await open(path, 'ax+').then(f => { created = true; return f; }, async (error) => {
115
+ const first = await open(path, 'ax+').then(f => { created = true; return f; }, async (error) => {
108
116
  if (error.code !== 'EEXIST')
109
117
  throw error;
110
118
  return open(path, 'a+');
111
119
  });
112
- let entries;
120
+ let entries, size;
113
121
  try {
114
- const bytes = await file.readFile(), decoded = decode(bytes);
122
+ const bytes = await first.readFile(), decoded = decode(bytes);
115
123
  entries = decoded.entries;
124
+ size = decoded.length;
116
125
  if (decoded.length !== bytes.length) {
117
- await file.truncate(decoded.length);
118
- await file.sync();
126
+ await first.truncate(decoded.length);
127
+ await first.sync();
119
128
  }
120
129
  if (created) {
121
- await file.sync();
130
+ await first.sync();
122
131
  await syncDirectory(dirname(path));
123
132
  }
124
133
  }
125
134
  catch (error) {
126
- await file.close();
135
+ await first.close();
127
136
  throw error;
128
137
  }
138
+ let file = first;
139
+ descriptors++;
129
140
  let queue = Promise.resolve(), closed = false, failed, view;
141
+ let resting = false, restTimer;
142
+ // Only this process writes the file (A2): a reopened file that is not exactly what was committed was changed by
143
+ // someone else, and appending to it could interleave records.
144
+ const reopen = async () => {
145
+ if (file)
146
+ return file;
147
+ const f = await open(path, constants.O_WRONLY | constants.O_APPEND);
148
+ try {
149
+ const now = (await f.stat()).size;
150
+ if (now !== size)
151
+ throw new Error(`Journal changed while closed: ${path} has ${now} bytes, ${size} committed`);
152
+ }
153
+ catch (error) {
154
+ await f.close();
155
+ throw error;
156
+ }
157
+ descriptors++;
158
+ return file = f;
159
+ };
160
+ const release = async () => {
161
+ if (!file || !resting || closed)
162
+ return;
163
+ const f = file;
164
+ file = undefined;
165
+ descriptors--;
166
+ await f.close().catch(error => console.error(`durable-subagents: closing resting journal ${path} failed: ${String(error)}`));
167
+ };
168
+ const unwritten = new WeakSet();
169
+ const rest = () => {
170
+ if (restTimer) {
171
+ restTimer.refresh();
172
+ return;
173
+ }
174
+ if (!resting || closed || !file)
175
+ return;
176
+ restTimer = setTimeout(() => { restTimer = undefined; queue = queue.then(release); }, JOURNAL_REST_MS);
177
+ restTimer.unref?.();
178
+ };
130
179
  const handle = {
131
180
  path,
132
181
  // Shared frozen view, rebuilt only after an append (entries are immutable, see freeze()).
@@ -143,11 +192,22 @@ export async function openJournal(path) {
143
192
  if (failed)
144
193
  throw failed;
145
194
  const entry = { ...frozen, seq: entries.length + 1, ts: Date.now(), type };
146
- const json = JSON.stringify(entry), bytes = Buffer.from(json);
147
- await file.writeFile(`${crc32(bytes)} ${json}\n`);
148
- await file.sync();
195
+ const json = JSON.stringify(entry), bytes = Buffer.from(json), line = `${crc32(bytes)} ${json}\n`;
196
+ let target;
197
+ try {
198
+ target = await reopen();
199
+ }
200
+ catch (error) {
201
+ unwritten.add(error);
202
+ throw error;
203
+ }
204
+ await target.writeFile(line);
205
+ await target.sync();
206
+ size += Buffer.byteLength(line);
149
207
  entries.push(freeze(JSON.parse(json)));
150
208
  view = undefined;
209
+ appends++;
210
+ rest();
151
211
  try {
152
212
  handle.onAppend?.();
153
213
  }
@@ -156,12 +216,36 @@ export async function openJournal(path) {
156
216
  }
157
217
  return structuredClone(entry);
158
218
  });
159
- queue = operation.catch(error => { failed = error; });
219
+ // A failed reopen wrote nothing: the next append tries again. A failed write or sync leaves the file unknown.
220
+ queue = operation.catch(error => { if (!(error && typeof error === 'object' && unwritten.has(error)))
221
+ failed = error; });
160
222
  return operation;
161
223
  },
162
- async close() { if (closed)
163
- return; closed = true; await queue; await file.close(); },
224
+ async close() {
225
+ if (closed)
226
+ return;
227
+ closed = true;
228
+ clearTimeout(restTimer);
229
+ await queue;
230
+ if (file) {
231
+ const f = file;
232
+ file = undefined;
233
+ descriptors--;
234
+ await f.close();
235
+ }
236
+ },
164
237
  get closed() { return closed; },
238
+ get resting() { return resting; },
239
+ set resting(value) {
240
+ resting = value;
241
+ if (value)
242
+ rest();
243
+ else {
244
+ clearTimeout(restTimer);
245
+ restTimer = undefined;
246
+ }
247
+ },
248
+ get descriptorOpen() { return file !== undefined; },
165
249
  };
166
250
  return handle;
167
251
  }
@@ -50,7 +50,7 @@ function isRequest(value) {
50
50
  const r = value;
51
51
  // A3, C11: request identities are short and path-safe, so every derived path (staging, receipts) is valid.
52
52
  return typeof r.rid === 'string' && /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/.test(r.rid) && typeof r.from === 'string' && typeof r.to === 'string' && Number.isSafeInteger(r.sseq) && r.sseq > 0 &&
53
- ['run', 'send', 'stop', 'revise', 'resume', 'drain', 'prune', 'restart', 'task', 'steer', 'follow-up', 'answer', 'model', 'continue', 'withdraw', 'call', 'emit'].includes(r.kind) && Object.hasOwn(r, 'body');
53
+ ['run', 'send', 'stop', 'revise', 'resume', 'drain', 'prune', 'restart', 'task', 'steer', 'notify', 'follow-up', 'answer', 'model', 'continue', 'withdraw', 'call', 'emit'].includes(r.kind) && Object.hasOwn(r, 'body');
54
54
  }
55
55
  /** P3: Scan immutable requests, reporting invalid files without admitting them. */
56
56
  export async function scanInbox(inboxDir, report = (path, error) => console.warn(path, error)) {