pi-durable-subagents 1.0.42 → 1.0.45

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/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)`);
@@ -4,20 +4,20 @@
4
4
  import { existsSync, readFileSync } from "node:fs";
5
5
  import { join, resolve } from "node:path";
6
6
  import { setTimeout as delay } from "node:timers/promises";
7
- import { readJournalSnapshot } from "../kernel/journal.js";
8
- import { reduceLifecycle } from "../kernel/lifecycle.js";
7
+ import { findJournalEntry, readJournalFold, readJournalSnapshot } from "../kernel/journal.js";
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, 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";
15
15
  import { JT } from "../types.js";
16
16
  import { startOrchestrator, submitIdentified } from "./control.js";
17
- import { endedExecs, fenceReason } from "../events/fence.js";
17
+ import { FENCE_LEDGER_TYPES, endedExecs, fenceReason } from "../events/fence.js";
18
18
  import { parseLabels } from "../events/labels.js";
19
19
  import { foldWaits, leaseWaits, waitsOf } from "../events/waiting.js";
20
- import { emptyLedger, foldLedger } from "../orchestrator/ledger.js";
20
+ import { LEDGER_ENTRY_TYPES, emptyLedger, foldLedger } from "../orchestrator/ledger.js";
21
21
  export const EXIT = { ok: 0, rejected: 1, conflict: 3, pending: 75 };
22
22
  /** Strict `--name value` / `--flag` parsing; unknown or repeated options are errors, except those given in `repeated`
23
23
  * (every value is kept, in order, in `lists`). */
@@ -55,26 +55,34 @@ function waitMs(values, ctx) {
55
55
  throw new Error("--wait-ms needs a non-negative integer");
56
56
  return raw !== undefined ? Number(raw) : ctx.waitMs ?? 60_000;
57
57
  }
58
- function ledger(home) { return readJournalSnapshot(orchLedger(home)); }
58
+ function ledger(home, needles) {
59
+ return readJournalFold(orchLedger(home), undefined, () => [], (entries, entry) => { entries.push(entry); }, { needles })?.state ?? [];
60
+ }
61
+ // Shared state consulted by describe's waits/holds/fence readers; workflow/request facts also match their identity.
62
+ export const descriptionNeedles = [...new Set(['pruned', ...HOLD_ENTRY_TYPES, ...LEDGER_ENTRY_TYPES, ...FENCE_LEDGER_TYPES])]
63
+ .map(type => `"type":${JSON.stringify(type)}`);
59
64
  function decision(entries, rid) {
60
- const records = entries.filter(e => [JT.admitted, JT.applied, JT.rejected, JT.withdrawn].includes(e.type));
61
- return reduceLifecycle(records).resolved.get(rid);
65
+ return lifecycleResolution(entries, rid);
62
66
  }
63
67
  const createdBy = (entries, rid) => entries.find(e => e.type === JT.created && e.rid === rid);
64
68
  async function stdin() { const chunks = []; for await (const chunk of process.stdin)
65
69
  chunks.push(chunk); return Buffer.concat(chunks).toString("utf8"); }
66
70
  /** The state of a request id (`{request}`) or a workflow (`{wid}`), with full texts (no clipping). */
67
71
  export async function describe(home, key, now = Date.now()) {
68
- const entries = ledger(home);
69
72
  if ("wid" in key)
70
- return describeWorkflow(home, key.wid, entries, now);
71
- const rid = requestRid(key.request), found = await findRequest(home, rid);
73
+ return describeWorkflow(home, key.wid, ledger(home, [...descriptionNeedles, JSON.stringify(key.wid)]), now);
74
+ const rid = requestRid(key.request), entries = ledger(home, [JSON.stringify(rid)]);
75
+ // A committed admitted envelope is immutable; reuse the same read when it already contains it.
76
+ const admitted = entries.find(e => e.type === 'request' && e.request.rid === rid);
77
+ const found = admitted ? { request: admitted.request, admitted: true } : await findRequest(home, rid);
72
78
  if (!found)
73
79
  return { state: "absent", request: key.request };
74
80
  const head = { request: key.request, kind: found.request.kind, spec_digest: specDigest(found.request), ...labelsOf(found.request) };
75
81
  const decided = decision(entries, rid), created = createdBy(entries, rid);
76
- if (found.request.kind === "run" && created)
77
- return { ...await describeWorkflow(home, String(created.wid), entries, now), ...head };
82
+ if (found.request.kind === "run" && created) {
83
+ const wid = String(created.wid), workflowEntries = ledger(home, [...descriptionNeedles, JSON.stringify(wid)]);
84
+ return { ...describeWorkflow(home, wid, workflowEntries, now), ...head };
85
+ }
78
86
  if (decided?.type === "rejected")
79
87
  return { state: "rejected", ...head, reason: String(decided.reason) };
80
88
  // A send or stop has no workflow of its own: its decision is the outcome.
@@ -88,9 +96,11 @@ function labelsOf(request) {
88
96
  return labels && typeof labels === "object" && Object.keys(labels).length ? { labels } : {};
89
97
  }
90
98
  /** The admitted run request that created `wid` (the ledger keeps it after a prune). */
91
- function runOf(entries, wid) {
99
+ function runOf(home, entries, wid) {
92
100
  const created = entries.find(e => e.type === JT.created && e.wid === wid);
93
- return { created, run: created ? entries.find(e => e.type === "request" && e.request.rid === created.rid)?.request : undefined };
101
+ const rid = created?.rid;
102
+ const run = created ? findJournalEntry(orchLedger(home), e => e.type === "request" && e.request.rid === rid, { needles: [JSON.stringify(rid)] })?.request : undefined;
103
+ return { created, run };
94
104
  }
95
105
  /** The pinned agents of a workflow revision, read once on demand (the waiting check needs the model of a call that names none). */
96
106
  function pinnedAgentModel(home, wid, rev) {
@@ -111,7 +121,7 @@ function describeWorkflow(home, wid, entries, now) {
111
121
  const pruned = entries.find(e => e.type === "pruned" && e.wid === wid);
112
122
  if (pruned)
113
123
  return { state: "pruned", wid, pruned: { ...(pruned.status !== undefined ? { status: String(pruned.status) } : {}), endedAt: Number(pruned.endedAt) },
114
- ...(typeof pruned.request === "string" ? { request: pruned.request } : {}), ...(typeof pruned.spec_digest === "string" ? { spec_digest: pruned.spec_digest } : {}), ...labelsOf(runOf(entries, wid).run) };
124
+ ...(typeof pruned.request === "string" ? { request: pruned.request } : {}), ...(typeof pruned.spec_digest === "string" ? { spec_digest: pruned.spec_digest } : {}), ...labelsOf(runOf(home, entries, wid).run) };
115
125
  if (!/^[^/\\\0]+$/.test(wid) || wid === "." || wid === ".." || !existsSync(journalPath(home, wid)))
116
126
  return { state: "absent", wid };
117
127
  // The snapshot and the journal the wait fold reads must be the same bytes (a writer-wait appended between the two reads
@@ -121,7 +131,7 @@ function describeWorkflow(home, wid, entries, now) {
121
131
  journal = again;
122
132
  wf = workflowSnapshot(home, wid);
123
133
  }
124
- const { created, run } = runOf(entries, wid), id = created ? requestId(String(created.rid)) : undefined;
134
+ const { created, run } = runOf(home, entries, wid), id = created ? requestId(String(created.rid)) : undefined;
125
135
  const admitted = id ? run : undefined;
126
136
  const lstate = leaseState(home), slots = slotsView(home, now), leases = leaseCalls(lstate, now);
127
137
  // The same fold and decision the orchestrator's collector uses, from the disk snapshots.
@@ -134,7 +144,11 @@ function describeWorkflow(home, wid, entries, now) {
134
144
  ...(line(slots.slots, c.model) ? { slot: line(slots.slots, c.model) } : {}), ...(line(slots.exhausted, c.model) ? { exhausted: line(slots.exhausted, c.model) } : {}),
135
145
  ...(c.hibernated ? { hibernated: true } : {}), ...waits.get(c.callId)
136
146
  };
147
+ const run = c.command !== undefined ? c.commandRun : undefined, live = !r && run !== undefined;
137
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 } : {}),
138
152
  ...(r ? { status: r.status, ok: r.ok, ...(r.error ? { error: r.error } : {}), output: r.output, ...(r.data !== undefined ? { data: r.data } : {}) } : {}),
139
153
  ...(waiting && Object.keys(waiting).length ? { waiting } : {}) };
140
154
  });
@@ -153,6 +167,11 @@ export function lastFence(journal, orch) {
153
167
  const fence = journal.findLast(e => e.type === JT.fenced && !ended.has(String(e.exec)));
154
168
  return fence ? { at: Number(fence.ts), exec: String(fence.exec), reason: fenceReason(journal, orch, fence) } : undefined;
155
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
+ }
156
175
  export function renderDescription(d) {
157
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}` : ""}`];
158
177
  if (d.labels)
@@ -162,7 +181,12 @@ export function renderDescription(d) {
162
181
  if (d.error)
163
182
  lines.push(` error: ${d.error}`);
164
183
  for (const c of d.calls ?? []) {
165
- lines.push(` ${c.key}@${c.gen} ${c.agent} ${c.phase}${c.status ? ` ${c.status}` : ""}${c.model ? ` (${c.model})` : ""}${c.error ? ` — ${c.error}` : ""}`);
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}`] : []));
166
190
  if (c.waiting)
167
191
  lines.push(` waiting: ${JSON.stringify(c.waiting)}`);
168
192
  if (c.data !== undefined)
@@ -187,17 +211,25 @@ export async function describeCommand(args, ctx) {
187
211
  ctx.write(values.json ? JSON.stringify(d, null, 2) : renderDescription(d));
188
212
  return 0;
189
213
  }
190
- /** Wait (bounded) for the request's decision: a run's `created` wid, or the lifecycle resolution. */
191
- async function outcome(home, rid, run, timeoutMs) {
214
+ /** Wait (bounded) for the request's decision: a run's `created` wid, or the lifecycle resolution. A command can carry
215
+ * its position across the pre-submit check and the wait; each call still stats and reads fresh appended bytes. */
216
+ async function outcome(home, rid, run, timeoutMs, poll = {}) {
192
217
  const deadline = performance.now() + timeoutMs;
193
218
  for (;;) {
194
- const entries = ledger(home), created = run ? createdBy(entries, rid) : undefined;
195
- if (created)
196
- return { type: "applied", wid: String(created.wid) };
197
- const decided = decision(entries, rid);
198
- if (decided?.type === "rejected")
199
- return { type: "rejected", reason: String(decided.reason) };
200
- if (decided && !run)
219
+ poll.journal = readJournalFold(orchLedger(home), poll.journal, () => ({}), (state, entry) => {
220
+ if (entry.rid !== rid)
221
+ return;
222
+ if (run && entry.type === JT.created && state.created === undefined)
223
+ state.created = String(entry.wid);
224
+ if (!state.decided && isResolution(entry))
225
+ state.decided = entry.type === "rejected" ? { type: "rejected", reason: String(entry.reason) } : { type: "applied" };
226
+ }, { needles: [JSON.stringify(rid)] });
227
+ const state = poll.journal?.state;
228
+ if (state?.created !== undefined)
229
+ return { type: "applied", wid: state.created };
230
+ if (state?.decided?.type === "rejected")
231
+ return state.decided;
232
+ if (state?.decided && !run)
201
233
  return { type: "applied" };
202
234
  if (performance.now() >= deadline)
203
235
  return undefined;
@@ -218,7 +250,7 @@ function pending(ctx, id, json, why = "") {
218
250
  async function submitAndWait(ctx, seen, id, kind, body, cond, wait, json) {
219
251
  // `created` is false only when the id was already decided before this invocation submitted (decisions are
220
252
  // monotonic); racing first attempts may all report created — the wid is what identifies the run.
221
- const rid = requestRid(id), earlier = Boolean(await outcome(ctx.home, rid, kind === "run", 0));
253
+ const rid = requestRid(id), poll = {}, earlier = Boolean(await outcome(ctx.home, rid, kind === "run", 0, poll));
222
254
  let sent;
223
255
  try {
224
256
  sent = await submitIdentified(ctx.home, rid, kind, body, cond, ctx.env, ctx.starter);
@@ -234,7 +266,7 @@ async function submitAndWait(ctx, seen, id, kind, body, cond, wait, json) {
234
266
  }
235
267
  if ("conflict" in sent)
236
268
  return { code: await conflict(ctx, id, sent.digest, json) };
237
- const result = await outcome(ctx.home, rid, kind === "run", wait);
269
+ const result = await outcome(ctx.home, rid, kind === "run", wait, poll);
238
270
  if (!result)
239
271
  return { code: pending(ctx, id, json) };
240
272
  const admitted = (await findRequest(ctx.home, rid))?.request;
@@ -277,7 +309,7 @@ export function runSession(flag, env) {
277
309
  return inherited && SESSION_ID.test(inherited) ? inherited : undefined;
278
310
  }
279
311
  /** `run --request <id> --spec <file|-> [--session <id>] [--cwd <dir>] [--json] [--wait-ms <n>]`. The spec is the `subagents` run
280
- * 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. */
281
313
  export const runCommand = (args, ctx) => refusable(args, ctx, runRequest);
282
314
  async function runRequest(args, ctx, seen) {
283
315
  const { values, positionals } = flags(args, { request: "value", spec: "value", cwd: "value", labels: "value", session: "value", json: "flag", "wait-ms": "value" });
@@ -337,11 +369,11 @@ async function runRequest(args, ctx, seen) {
337
369
  async function widOf(home, head) {
338
370
  if (!REQUEST_ID.test(head))
339
371
  return { wid: head };
340
- const rid = requestRid(head), created = createdBy(ledger(home), rid);
372
+ const rid = requestRid(head), created = createdBy(ledger(home, [JSON.stringify(rid)]), rid);
341
373
  if (created)
342
374
  return { wid: String(created.wid) };
343
375
  const found = await findRequest(home, rid);
344
- return found?.request.kind === "run" && decision(ledger(home), rid)?.type !== "rejected" ? { pending: true } : { wid: head };
376
+ return found?.request.kind === "run" && decision(ledger(home, [JSON.stringify(rid)]), rid)?.type !== "rejected" ? { pending: true } : { wid: head };
345
377
  }
346
378
  /** `--to <run-id>[/<key>] | <wid>/<key>` (+ `--call <key>`) → `<wid>/<key>`; a run of one call implies its key. */
347
379
  async function target(home, to, call, prior) {
@@ -436,7 +468,8 @@ async function sendRequest(args, ctx, seen, batch) {
436
468
  seen.json = json;
437
469
  if (!id || !to || !kind || positionals.length)
438
470
  throw new Error(SEND_USAGE);
439
- const rid = requestRid(id), prior = (await findRequest(ctx.home, rid))?.request;
471
+ const related = [`${id}:1`, to.split('/')[0]].filter(value => REQUEST_ID.test(value)).map(requestRid);
472
+ const rid = requestRid(id), prior = (await findRequest(ctx.home, rid, related))?.request;
440
473
  // A single send under an id that names a send to several calls (<id>:1 ...) is other content.
441
474
  if (!prior && await namesMany(ctx.home, id)) {
442
475
  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`);
@@ -450,6 +483,9 @@ async function sendRequest(args, ctx, seen, batch) {
450
483
  if (rev !== undefined && !/^\d+$/.test(rev))
451
484
  throw new Error("--rev needs a positive integer");
452
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"));
453
489
  if (kind === "answer" && (qid === undefined || revision === undefined)) {
454
490
  // The open question of the target call (or, on a retry, the one the original answered) supplies qid/rev.
455
491
  const before = prior?.kind === "send" && prior.body.kind === "answer" && prior.body.to === where.to ? prior.cond : undefined;
@@ -505,7 +541,7 @@ function decided(ctx, id, done, json) {
505
541
  const followed = done.sent.request.kind === "send" ? followUpReceipt(ctx.home, done.sent.request.rid, done.sent.request.body) : {};
506
542
  const opened = followed.generation !== undefined ? followed : undefined;
507
543
  // A notify says how it went (steered, held-until-answer or noted); a model send which model and when it applies.
508
- const notified = done.sent.request.kind === "send" ? sendReceipt(ledger(ctx.home), done.sent.request.rid) : {};
544
+ const notified = done.sent.request.kind === "send" ? sendReceipt(ledger(ctx.home, [JSON.stringify(done.sent.request.rid)]), done.sent.request.rid) : {};
509
545
  const receipt = notified.delivery ? { delivery: notified.delivery, note: notified.note }
510
546
  : followed.delivery ? { delivery: followed.delivery, call: followed.call, note: followed.note } : {};
511
547
  const reply = { request: id, applied: true, ...(opened ? { generation: opened.generation, call: opened.call } : {}), ...receipt, spec_digest: done.sent.digest };
@@ -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
- ? prefix + "return await runs.all(steps.map(({key, spec}) => ({...spec, key})));\n"
22
- : prefix + `const results = [];
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, {...spec, task: spec.task.replaceAll("{previous}", () => previous)});
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
  }
@@ -1,5 +1,8 @@
1
1
  import { schemaProblems } from "../agent/child/schema.js";
2
- const fields = new Set(["agent", "task", "model", "cwd", "timeoutMs", "output", "schema", "gate", "isolation", "context", "budget", "once", "tools", "skills", "key", "writer"]);
2
+ const fields = new Set(["agent", "task", "model", "cwd", "timeoutMs", "output", "schema", "gate", "isolation", "context", "budget", "once", "tools", "skills", "key", "writer", "command", "env", "rerun"]);
3
+ /** Fields a command call takes; every other known field belongs to agent calls. */
4
+ export const COMMAND_FIELDS = ["command", "cwd", "timeoutMs", "env", "rerun", "writer", "key"];
5
+ const ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
3
6
  const isObject = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
4
7
  const positive = (v) => typeof v === "number" && Number.isFinite(v) && v > 0;
5
8
  const text = (v) => typeof v === "string" && v.trim() !== "";
@@ -46,6 +49,11 @@ export function validateCallSpec(spec, options = {}) {
46
49
  else if (k === "key" && !options.fanout)
47
50
  errors.push("key is only allowed in tasks/chain steps");
48
51
  }
52
+ if (has("command"))
53
+ return [...errors, ...commandProblems(s, options)];
54
+ for (const k of ["env", "rerun"])
55
+ if (has(k))
56
+ errors.push(`${k} is only allowed in a command call`);
49
57
  if (!text(s.agent))
50
58
  errors.push(`agent must be a non-empty string${has("agent") ? got(s.agent) : ""}`);
51
59
  if (!text(s.task))
@@ -76,3 +84,40 @@ export function validateCallSpec(spec, options = {}) {
76
84
  errors.push("key must be a non-empty string");
77
85
  return errors;
78
86
  }
87
+ /** A command call: command (argv array or sh string) plus cwd, timeoutMs, env, rerun, writer, key; nothing else. */
88
+ function commandProblems(s, options) {
89
+ const errors = [], has = (k) => s[k] !== undefined;
90
+ for (const k of Object.keys(s))
91
+ if (has(k) && fields.has(k) && !COMMAND_FIELDS.includes(k))
92
+ errors.push(`${k} is not allowed in a command call`);
93
+ const c = s.command;
94
+ if (Array.isArray(c)) {
95
+ if (!c.length || !c.every(v => typeof v === "string") || !text(c[0]))
96
+ errors.push(`command must be a non-empty string or an array of strings with a non-empty first element${got(c)}`);
97
+ }
98
+ else if (!text(c))
99
+ errors.push(`command must be a non-empty string or an array of strings with a non-empty first element${got(c)}`);
100
+ if (has("cwd") && typeof s.cwd !== "string")
101
+ errors.push(`cwd must be a string${got(s.cwd)}`);
102
+ if (has("timeoutMs") && !positive(s.timeoutMs))
103
+ errors.push(`timeoutMs must be a positive number (milliseconds)${got(s.timeoutMs)}`);
104
+ if (has("env")) {
105
+ if (!isObject(s.env))
106
+ errors.push(`env must be an object of strings${got(s.env)}`);
107
+ else
108
+ for (const [k, v] of Object.entries(s.env)) {
109
+ if (!ENV_NAME.test(k))
110
+ errors.push(`env name ${JSON.stringify(k)} is not a valid variable name`);
111
+ else if (k.startsWith("DSA_"))
112
+ errors.push(`env name ${k} is reserved (DSA_*)`);
113
+ if (typeof v !== "string")
114
+ errors.push(`env.${k} must be a string${got(v)}`);
115
+ }
116
+ }
117
+ for (const k of ["rerun", "writer"])
118
+ if (has(k) && typeof s[k] !== "boolean")
119
+ errors.push(`${k} must be a boolean${got(s[k])}`);
120
+ if (options.fanout && has("key") && !text(s.key))
121
+ errors.push("key must be a non-empty string");
122
+ return errors;
123
+ }
@@ -2,6 +2,8 @@
2
2
  // committed journal entries; `limit` restricts the view to the first `limit` entries (the deriver may read only entries
3
3
  // before the one it derives, so a re-derivation after a crash sees the same history).
4
4
  import { JT } from "../types.js";
5
+ /** Orchestrator entry types read by fenceReason; workflow entries are read separately. */
6
+ export const FENCE_LEDGER_TYPES = ['restart', 'orchestrator', 'orchestrator-exit'];
5
7
  /** Executions whose fence did NOT interrupt work: every execution ends with a fence; one interrupted work only when
6
8
  * the execution neither settled (its turn ended) before it nor hibernated (it waits for an answer), and was not sealed
7
9
  * on purpose: a seal ends an execution on purpose unless its outcome is `unknown` (a `once` call cut off in a tool) or
@@ -102,7 +102,19 @@ function applyWait(f, e) {
102
102
  case "generation": {
103
103
  const key = String(e.key), gen = Number(e.gen) || 1, call = `${f.wid}@${f.rev}/${key}@${gen}`, spec = e.spec;
104
104
  const wanted = typeof e.model === "string" && e.model ? e.model : typeof spec?.model === "string" && spec.model ? spec.model : undefined;
105
- f.calls.set(call, { call, key, gen, generation: e.type === "generation", ...(typeof spec?.agent === "string" ? { agent: spec.agent } : {}), ...(wanted ? { wanted } : {}) });
105
+ f.calls.set(call, { call, key, gen, generation: e.type === "generation", ...(typeof spec?.agent === "string" ? { agent: spec.agent } : {}), ...(wanted ? { wanted } : {}),
106
+ ...(spec?.command !== undefined ? { command: true } : {}) });
107
+ break;
108
+ }
109
+ case "command-intent": {
110
+ const c = f.calls.get(String(e.call));
111
+ if (c?.command) {
112
+ c.exec = String(e.id);
113
+ c.queued = e.ts;
114
+ c.selected = true;
115
+ c.fenced = false;
116
+ delete c.writer;
117
+ }
106
118
  break;
107
119
  }
108
120
  case JT.exec: {
@@ -221,6 +233,9 @@ catch {
221
233
  export function waitInput(f, c, env, agentModel) {
222
234
  // An answered asker is queued (live) although its hibernated execution is fenced, unless a drain holds its workflow.
223
235
  const answered = c.answered !== undefined && !env.held?.(f.wid);
236
+ // A command call queued behind a writer lock has no attempt yet: the lock is its wait (it takes no slot).
237
+ if (c.command && !c.exec)
238
+ return c.writer ? { asking: false, exec: { id: "", since: c.writer.since, selected: false }, writerWait: c.writer } : { asking: false };
224
239
  const settings = settingsOf(env.ledger, env.config ?? {}), live = c.exec && (!c.fenced || answered), selected = c.selected && c.answered === undefined;
225
240
  const attention = [];
226
241
  let asking = false;
@@ -428,9 +443,16 @@ export function waitCollector(src) {
428
443
  hit = { entries, fold: foldWaits(wf.wid, entries, hit?.fold) };
429
444
  folds.set(wf.wid, hit);
430
445
  }
431
- if (!hit.fold.calls.size)
446
+ if (!liveWaitCalls(hit.fold).length)
432
447
  continue;
433
- const agents = wf.pins?.agents;
448
+ // A pins load that fails (released pins, damaged record) leaves the agents unknown, as when pins are absent.
449
+ let agents;
450
+ try {
451
+ agents = wf.pins?.agents;
452
+ }
453
+ catch {
454
+ agents = undefined;
455
+ }
434
456
  for (const [call, wait] of waitsOf(hit.fold, env, agents ? name => agents.find(a => a.name === name)?.model : undefined)) {
435
457
  const c = hit.fold.calls.get(call), m = runs.meta.get(wf.wid);
436
458
  current.set(call, wait);