pi-durable-subagents 1.0.27 → 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.
@@ -0,0 +1,287 @@
1
+ // `drill failover`: rehearse pool failover on this machine without a real outage. Everything runs in a temporary
2
+ // root: its own DSA_HOME, HOME and pi agent dir, the real CLI (as a child process), the real orchestrator it starts,
3
+ // real subagent pi processes and two offline providers (provider.ts). The user's home, providers and credentials are
4
+ // never read: the child environment carries only PATH and the variables set here.
5
+ import { spawn } from "node:child_process";
6
+ import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, unlinkSync, writeFileSync } from "node:fs";
7
+ import { tmpdir } from "node:os";
8
+ import { join } from "node:path";
9
+ import { fileURLToPath } from "node:url";
10
+ import { setTimeout as delay } from "node:timers/promises";
11
+ import { readJournalSnapshot } from "../../kernel/journal.js";
12
+ import { journalPath, orchLedger } from "../../paths.js";
13
+ import { captureStart, ProcessTable } from "../../platform/proctable.js";
14
+ import { Containment } from "../../platform/containment.js";
15
+ import { JT } from "../../types.js";
16
+ const A = "drill-a", B = "drill-b", POOL = "failover";
17
+ /** Steps 1-3 (about 5 s here) must finish before it; 25 s leaves room for a loaded or several times slower machine
18
+ * and keeps the drill well under a minute. Step 3 says so explicitly when the machine was too slow. */
19
+ export const DRILL_PROBE_MS = 25_000;
20
+ const STEPS = [
21
+ `a pool call starts on ${A}, hits the used-up error, moves to ${B} and ends ok there`,
22
+ `status lists ${A} as used up with its next probe time; describe/events show the move ${A} -> ${B}`,
23
+ `a second call while ${A} is out starts directly on ${B}`,
24
+ `${A} answers again; after the probe interval the next call probes it and it is marked available`,
25
+ `the third call (the probe) starts on ${A} and ends ok there`,
26
+ ];
27
+ /** Validate drill arguments before allocating a temporary root or starting anything. */
28
+ export function parseDrill(args) {
29
+ if (args[0] !== "failover")
30
+ throw new Error(`Invalid drill: ${args[0] ?? "(none)"}; use: drill failover [--keep] [--json]`);
31
+ const options = { keep: false, json: false }, seen = new Set();
32
+ for (const arg of args.slice(1)) {
33
+ if (seen.has(arg))
34
+ throw new Error(`Repeated drill option: ${arg}`);
35
+ seen.add(arg);
36
+ if (arg === "--keep")
37
+ options.keep = true;
38
+ else if (arg === "--json")
39
+ options.json = true;
40
+ else
41
+ throw new Error(`Invalid drill argument: ${arg}; use: drill failover [--keep] [--json]`);
42
+ }
43
+ return options;
44
+ }
45
+ const sibling = (name) => fileURLToPath(new URL(name + (import.meta.url.endsWith(".ts") ? ".ts" : ".js"), import.meta.url));
46
+ class StepFailure extends Error {
47
+ }
48
+ const check = (ok, detail) => { if (!ok)
49
+ throw new StepFailure(detail); };
50
+ /** Run the failover drill; exit code 0 only when every step passed. */
51
+ export async function drill(args, inherited = process.env, write = console.log) {
52
+ const options = parseDrill(args), started = performance.now();
53
+ const root = realpathSync(mkdtempSync(join(tmpdir(), "dsa-drill-")));
54
+ const home = join(root, "dsa"), cwd = join(root, "work"), agent = join(root, "agent");
55
+ for (const dir of [home, agent, join(root, "home"), join(cwd, ".pi/agents")])
56
+ mkdirSync(dir, { recursive: true });
57
+ writeFileSync(join(agent, "settings.json"), JSON.stringify({ extensions: [sibling("./provider")], defaultProvider: B, defaultModel: "m",
58
+ // pi's retries stay on (a used-up window is noticed while pi retries, as on a real setup), with a short backoff.
59
+ retry: { enabled: true, baseDelayMs: 200 }, compaction: { enabled: false }, defaultProjectTrust: "always" }));
60
+ writeFileSync(join(cwd, ".pi/agents/worker.md"), "---\nname: worker\ndescription: Failover drill worker\ntools: bash\n---\nAnswer the task.\n");
61
+ writeFileSync(join(home, "config.json"), JSON.stringify({ pools: { [POOL]: [`${A}/m`, `${B}/m`] }, k: { probeMs: DRILL_PROBE_MS } }));
62
+ writeFileSync(join(root, "a-exhausted"), "");
63
+ const env = { PATH: inherited.PATH, HOME: join(root, "home"), TMPDIR: root, PI_CODING_AGENT_DIR: agent,
64
+ PI_OFFLINE: "1", PI_SKIP_VERSION_CHECK: "1", PI_TELEMETRY: "0", DSA_HOME: home, DSA_DRILL_ROOT: root };
65
+ const entry = sibling("../main");
66
+ const cli = (argv) => new Promise((resolve, reject) => {
67
+ const child = spawn(process.execPath, [entry, ...argv], { cwd, env, stdio: ["ignore", "pipe", "pipe"] });
68
+ let out = "", err = "";
69
+ child.stdout.on("data", d => { out += d; });
70
+ child.stderr.on("data", d => { err += d; });
71
+ child.once("error", reject);
72
+ child.once("close", code => resolve({ code, out: out.trim(), err: err.trim() }));
73
+ });
74
+ const json = async (argv) => {
75
+ const r = await cli([...argv, "--json"]);
76
+ check(r.code === 0, `${argv.join(" ")} exited ${r.code}: ${r.err || r.out}`);
77
+ return JSON.parse(r.out);
78
+ };
79
+ const requests = () => existsSync(join(root, "requests.log")) ? readFileSync(join(root, "requests.log"), "utf8").split("\n").filter(Boolean) : [];
80
+ const ledger = () => readJournalSnapshot(orchLedger(home));
81
+ const submit = async (id) => {
82
+ const spec = join(root, `${id}.json`);
83
+ writeFileSync(spec, JSON.stringify({ agent: "worker", task: "Answer briefly.", model: POOL }));
84
+ const reply = await json(["run", "--request", id, "--spec", spec]);
85
+ check(reply.created === true && reply.wid, `run ${id}: ${JSON.stringify(reply)}`);
86
+ return String(reply.wid);
87
+ };
88
+ const sealed = async (id, ms = 60_000) => {
89
+ const end = Date.now() + ms;
90
+ for (;;) {
91
+ const d = await json(["describe", "--key", id]);
92
+ if (d.state === "sealed")
93
+ return d;
94
+ check(Date.now() < end, `${id} did not finish within ${ms / 1000} s: ${JSON.stringify(d).slice(0, 400)}`);
95
+ await delay(250);
96
+ }
97
+ };
98
+ /** The models `events <wid>` reports the workflow's executions on (launch and switch). */
99
+ const models = async (wid) => {
100
+ const r = await cli(["events", wid, "--json"]);
101
+ check(r.code === 0, `events ${wid} exited ${r.code}: ${r.err}`);
102
+ return r.out.split("\n").filter(Boolean).map(l => JSON.parse(l)).filter((e) => e.event === "model").map((e) => e.model);
103
+ };
104
+ const statusLine = async () => ((await json(["status"])).exhausted ?? []).find((l) => l.startsWith(`${A} `));
105
+ const call = (d) => d.calls?.[0] ?? {};
106
+ const summary = (d) => `status ${d.status}, call ${call(d).status} on ${call(d).model}, output ${JSON.stringify(call(d).output)}${call(d).error ? `, error ${JSON.stringify(String(call(d).error).slice(0, 200))}` : ""}`;
107
+ const steps = [];
108
+ let failed = false;
109
+ const step = async (n, run) => {
110
+ const t0 = performance.now();
111
+ if (failed) {
112
+ steps.push({ step: n, name: STEPS[n - 1], ok: false, ms: 0, detail: "not run: an earlier step failed" });
113
+ return;
114
+ }
115
+ try {
116
+ steps.push({ step: n, name: STEPS[n - 1], ok: true, ms: Math.round(performance.now() - t0), detail: await run() });
117
+ }
118
+ catch (error) {
119
+ failed = true;
120
+ steps.push({ step: n, name: STEPS[n - 1], ok: false, ms: Math.round(performance.now() - t0), detail: error instanceof Error ? error.message : String(error) });
121
+ }
122
+ steps.at(-1).ms = Math.round(performance.now() - t0);
123
+ if (!options.json) {
124
+ const s = steps.at(-1);
125
+ write(` ${s.step}. ${s.ok ? "pass" : "FAIL"} ${(s.ms / 1000).toFixed(1).padStart(5)} s ${s.name}\n${" ".repeat(16)}${s.detail}`);
126
+ }
127
+ };
128
+ let first, firstWid = "", nextTry = 0, before2 = 0, wid3 = "";
129
+ // An interrupted drill cleans up as a finished one: stop its orchestrator, fence what its calls left, and remove the
130
+ // root (with --keep, print it). The handlers are removed when the drill ends.
131
+ let stopping = false;
132
+ const interrupted = (signal) => {
133
+ if (stopping)
134
+ return;
135
+ stopping = true;
136
+ void (async () => {
137
+ try {
138
+ await cleanup(home);
139
+ }
140
+ catch (error) {
141
+ write(` cleanup after ${signal} failed: ${String(error)}`);
142
+ }
143
+ if (!options.keep)
144
+ rmSync(root, { recursive: true, force: true });
145
+ if (options.json)
146
+ write(JSON.stringify({ drill: "failover", passed: false, interrupted: signal, steps, ms: Math.round(performance.now() - started), probeMs: DRILL_PROBE_MS, ...(options.keep ? { evidence: root } : {}) }));
147
+ else {
148
+ if (options.keep)
149
+ write(` kept: ${root}`);
150
+ write(`failover drill: interrupted by ${signal}`);
151
+ }
152
+ process.exit(signal === "SIGINT" ? 130 : 143);
153
+ })();
154
+ };
155
+ const onInt = () => interrupted("SIGINT"), onTerm = () => interrupted("SIGTERM");
156
+ process.on("SIGINT", onInt);
157
+ process.on("SIGTERM", onTerm);
158
+ try {
159
+ if (!options.json)
160
+ write(`failover drill (isolated home ${home}, probe interval ${DRILL_PROBE_MS / 1000} s)`);
161
+ await step(1, async () => {
162
+ firstWid = await submit("drill-1");
163
+ first = await sealed("drill-1", 90_000);
164
+ check(first.status === "done" && call(first).status === "ok" && call(first).ok === true, summary(first));
165
+ check(call(first).model === `${B}/m` && call(first).output === `answered by ${B}`, `expected to end on ${B}/m: ${summary(first)}`);
166
+ const log = requests();
167
+ check(log[0] === A && log.at(-1) === B && !log.slice(log.indexOf(B)).includes(A), `provider requests: ${log.join(",")}`);
168
+ const x = ledger().find(e => e.type === "provider-exhausted" && e.provider === A);
169
+ check(x, `no provider-exhausted entry for ${A} in the orchestrator ledger`);
170
+ nextTry = Number(x.nextTry);
171
+ return `requests ${log.join(" -> ")}; ${summary(first)}`;
172
+ });
173
+ await step(2, async () => {
174
+ const text = await cli(["status"]);
175
+ check(text.code === 0, `status exited ${text.code}: ${text.err}`);
176
+ const line = text.out.split("\n").find(l => l.startsWith(`${A} exhausted`));
177
+ check(line && /No available accounts/.test(line) && /next try in \d+s$/.test(line), `status does not list ${A} as used up with a next try:\n${text.out}`);
178
+ check(!text.out.split("\n").some(l => l.startsWith(`${B} exhausted`)), `status lists ${B} as used up:\n${text.out}`);
179
+ // `events` shows the launch on A and the model switch delivered to the running call; describe shows where it ended.
180
+ const r = await cli(["events", firstWid, "--json"]);
181
+ check(r.code === 0, `events ${firstWid} exited ${r.code}: ${r.err}`);
182
+ const events = r.out.split("\n").filter(Boolean).map(l => JSON.parse(l));
183
+ const launched = events.filter(e => e.event === "model").map(e => e.model);
184
+ const forward = events.find(e => e.event === "forward" && e.kind === "model");
185
+ check(forward?.model === `${B}/m` && forward.failover === A, `events show no failover ${A} -> ${B}/m: ${JSON.stringify(forward ?? null)}`);
186
+ const delivered = forward && events.find(e => e.event === "delivered" && e.kind === "model" && e.rid === forward.rid);
187
+ check(launched.length === 1 && launched[0] === `${A}/m`, `events show launches on ${launched.join(", ") || "(none)"}`);
188
+ check(delivered, `events show no model switch delivered to the call: ${events.map(e => e.event).join(" ")}`);
189
+ const d = await json(["describe", firstWid]);
190
+ check(d.calls?.length === 1 && call(d).model === `${B}/m`, `describe ${firstWid}: ${summary(d)}`);
191
+ return `status: ${line}; events: launched on ${launched[0]}, failover from ${forward.failover} to ${forward.model} (#${forward.seq}, delivered #${delivered.seq})`;
192
+ });
193
+ await step(3, async () => {
194
+ before2 = requests().length;
195
+ const wid = await submit("drill-2"), d = await sealed("drill-2");
196
+ check(d.status === "done" && call(d).status === "ok" && call(d).model === `${B}/m`, summary(d));
197
+ const launched = await models(wid), log = requests().slice(before2);
198
+ const admitted = readJournalSnapshot(journalPath(home, wid)).find(e => e.type === "selected");
199
+ check(admitted && Number(admitted.ts) < nextTry, `the second call was admitted after ${A}'s next try; this machine is too slow for the ${DRILL_PROBE_MS / 1000} s probe interval`);
200
+ check(launched.length === 1 && launched[0] === `${B}/m`, `events show models ${launched.join(", ")}`);
201
+ check(log.length > 0 && log.every(p => p === B), `provider requests during the second call: ${log.join(",")}`);
202
+ check(await statusLine(), `${A} no longer listed as used up before its next try`);
203
+ return `events: ${launched.join(" -> ")}; requests ${log.join(", ")}; ${A} still used up`;
204
+ });
205
+ await step(4, async () => {
206
+ unlinkSync(join(root, "a-exhausted"));
207
+ while (Date.now() < nextTry + 100)
208
+ await delay(Math.min(500, Math.max(10, nextTry + 100 - Date.now())));
209
+ const due = await statusLine();
210
+ check(due && /next call probes it$/.test(due), `after the probe interval status says: ${due ?? "(not listed)"}`);
211
+ const n = requests().length;
212
+ wid3 = await submit("drill-3");
213
+ const end = Date.now() + 60_000;
214
+ let probe, available;
215
+ while (!(probe && available) && Date.now() < end) {
216
+ const entries = ledger();
217
+ probe = entries.find(e => e.type === "provider-probe" && e.provider === A && String(e.exec).startsWith(wid3));
218
+ available = entries.find(e => e.type === "provider-available" && e.provider === A);
219
+ if (!(probe && available))
220
+ await delay(200);
221
+ }
222
+ check(probe, `the third call was not admitted to ${A} as its probe (requests since: ${requests().slice(n).join(",")})`);
223
+ check(available, `${A} was probed but not marked available (requests since: ${requests().slice(n).join(",")})`);
224
+ const after = await statusLine();
225
+ check(!after, `status still lists ${A}: ${after}`);
226
+ return `status before: ${due}; probe by ${String(probe.exec).split("#")[0]}; ${A} available ${Math.round((Number(available.ts) - nextTry) / 100) / 10} s after its next try`;
227
+ });
228
+ await step(5, async () => {
229
+ const n = requests().length, d = await sealed("drill-3");
230
+ check(d.status === "done" && call(d).status === "ok" && call(d).model === `${A}/m` && call(d).output === `answered by ${A}`, summary(d));
231
+ const launched = await models(wid3);
232
+ check(launched.length === 1 && launched[0] === `${A}/m`, `events show models ${launched.join(", ")}`);
233
+ check(!requests().slice(n).includes(B), `${B} received a request during the third call: ${requests().join(",")}`);
234
+ return `events: ${launched.join(" -> ")}; ${summary(d)}`;
235
+ });
236
+ }
237
+ finally {
238
+ if (stopping)
239
+ await new Promise(() => { }); // the signal handler owns cleanup and exits
240
+ process.removeListener("SIGINT", onInt);
241
+ process.removeListener("SIGTERM", onTerm);
242
+ await cleanup(home);
243
+ }
244
+ const passed = steps.length === STEPS.length && steps.every(s => s.ok), ms = Math.round(performance.now() - started);
245
+ const report = { drill: "failover", passed, steps, ms, probeMs: DRILL_PROBE_MS, ...(options.keep ? { evidence: root } : {}) };
246
+ writeFileSync(join(root, "report.json"), JSON.stringify(report, null, 2));
247
+ if (options.json)
248
+ write(JSON.stringify(report));
249
+ else {
250
+ if (options.keep)
251
+ write(` kept: ${root}`);
252
+ write(`failover drill: ${passed ? "pass" : "FAILED"} (${steps.filter(s => s.ok).length}/${STEPS.length} steps, ${(ms / 1000).toFixed(1)} s)${passed || options.keep ? "" : "; rerun with --keep to retain the evidence"}`);
253
+ }
254
+ if (!options.keep)
255
+ rmSync(root, { recursive: true, force: true });
256
+ return passed ? 0 : 1;
257
+ }
258
+ /** Stop every orchestrator started on the drill's home and fence any process its executions left. */
259
+ async function cleanup(home) {
260
+ const ledger = () => readJournalSnapshot(orchLedger(home));
261
+ const hosts = ledger().filter(e => e.type === "orchestrator" && e.pid).map(e => ({ pid: Number(e.pid), start: e.start ? String(e.start) : undefined }));
262
+ const same = async (h) => { const now = await captureStart(h.pid); return now !== "" && (h.start === undefined || now === h.start); };
263
+ for (const h of hosts)
264
+ if (await same(h)) {
265
+ try {
266
+ process.kill(h.pid, "SIGTERM");
267
+ }
268
+ catch { }
269
+ }
270
+ const end = Date.now() + 15_000;
271
+ for (const h of hosts) {
272
+ while (await same(h) && Date.now() < end)
273
+ await delay(100);
274
+ if (await same(h)) {
275
+ try {
276
+ process.kill(h.pid, "SIGKILL");
277
+ }
278
+ catch { }
279
+ }
280
+ }
281
+ const containment = new Containment(new ProcessTable());
282
+ for (const created of ledger().filter(e => e.type === JT.created)) {
283
+ const journal = readJournalSnapshot(journalPath(home, String(created.wid)));
284
+ for (const exec of journal.filter(e => e.type === JT.exec))
285
+ await containment.fence(String(exec.exec), journal.filter(e => e.type === "tracked" && e.exec === exec.exec).map(e => ({ pid: Number(e.pid), ppid: 0, start: String(e.start) })));
286
+ }
287
+ }
@@ -0,0 +1,25 @@
1
+ // Offline providers for `drill failover`, loaded by the drill's isolated pi setup (never by a user's pi).
2
+ // drill-a/m: while `$DSA_DRILL_ROOT/a-exhausted` exists it refuses every request like a gateway whose usage window
3
+ // is used up; otherwise it answers.
4
+ // drill-b/m: always answers.
5
+ // Every request is appended to `$DSA_DRILL_ROOT/requests.log` as the provider's name.
6
+ import { appendFileSync, existsSync } from "node:fs";
7
+ import { join } from "node:path";
8
+ import { fauxProvider, fauxAssistantMessage } from "@earendil-works/pi-ai";
9
+ /** The refusal text of a gateway with no account left; the executor classifies it as a used-up window. */
10
+ export const EXHAUSTED = '503 {"error":{"message":"No available accounts: no available accounts","type":"api_error"}}';
11
+ export default function drillProviders(pi) {
12
+ const root = process.env.DSA_DRILL_ROOT;
13
+ if (!root)
14
+ return;
15
+ for (const [provider, flag] of [["drill-a", "a-exhausted"], ["drill-b", undefined]]) {
16
+ const faux = fauxProvider({ provider, api: `${provider}-faux`, models: [{ id: "m", name: `${provider} model` }], tokensPerSecond: 500 });
17
+ faux.setResponses(Array.from({ length: 200 }, () => async () => {
18
+ appendFileSync(join(root, "requests.log"), `${provider}\n`);
19
+ if (flag && existsSync(join(root, flag)))
20
+ return fauxAssistantMessage([], { stopReason: "error", errorMessage: EXHAUSTED });
21
+ return fauxAssistantMessage(`answered by ${provider}`);
22
+ }));
23
+ pi.registerProvider(faux.provider);
24
+ }
25
+ }
package/dist/cli/hold.js CHANGED
@@ -1,4 +1,4 @@
1
- // `pi-durable-subagents hold <resource> [--shared] [--max-wait <s>] [--note <text>] -- <command> [args…]`
1
+ // `pi-durable-subagents hold <resource> [--shared | --slots <n>] [--max-wait <s>] [--note <text>] -- <command> [args…]`
2
2
  // Waits for the lease (strict FIFO), runs the command in its own process group, ends what the command left in that
3
3
  // group, then releases. `--max-wait 0` (or `--no-wait`) takes the lease at once or exits 75 without ever being queued.
4
4
  // See src/platform/lease.ts for the ticket protocol.
@@ -7,8 +7,8 @@ import { watch } from "node:fs";
7
7
  import { constants } from "node:os";
8
8
  import { dsaHome } from "../paths.js";
9
9
  import { captureStart } from "../platform/proctable.js";
10
- import { blockers, enqueue, groupAlive, tryGrant, leaseDir, liveTickets, orphaned, removeTicket, RESOURCE, who, writeTicket } from "../platform/lease.js";
11
- export const HOLD_USAGE = "usage: pi-durable-subagents hold <resource> [--shared] [--max-wait <seconds> | --no-wait] [--note <text>] -- <command> [args…]";
10
+ import { blockers, enqueue, groupAlive, tryGrant, leaseDir, liveTickets, orphaned, removeTicket, RESOURCE, who, writeTicket, modeLabel } from "../platform/lease.js";
11
+ export const HOLD_USAGE = "usage: pi-durable-subagents hold <resource> [--shared | --slots <n>] [--max-wait <seconds> | --no-wait] [--note <text>] -- <command> [args…]";
12
12
  /** Exit status when --max-wait expires before the lease is granted (EX_TEMPFAIL). */
13
13
  export const WAIT_EXPIRED = 75;
14
14
  export function parseHold(args) {
@@ -16,19 +16,24 @@ export function parseHold(args) {
16
16
  if (split < 0)
17
17
  throw new Error(`hold needs -- before the command. ${HOLD_USAGE}`);
18
18
  const opts = args.slice(0, split), argv = args.slice(split + 1);
19
- let resource, mode = "exclusive", maxWaitMs, note;
19
+ let resource, shared = false, slots, maxWaitMs, note;
20
20
  for (let i = 0; i < opts.length; i++) {
21
21
  const a = opts[i];
22
22
  if (a === "--shared")
23
- mode = "shared";
23
+ shared = true;
24
24
  else if (a === "--no-wait")
25
25
  maxWaitMs = 0;
26
- else if (a === "--max-wait" || a === "--note") {
26
+ else if (a === "--max-wait" || a === "--note" || a === "--slots") {
27
27
  const v = opts[++i];
28
28
  if (v === undefined)
29
29
  throw new Error(`${a} needs a value. ${HOLD_USAGE}`);
30
30
  if (a === "--note")
31
31
  note = v;
32
+ else if (a === "--slots") {
33
+ if (!/^\d+$/.test(v) || !(Number(v) >= 1) || !Number.isSafeInteger(Number(v)))
34
+ throw new Error(`--slots must be an integer >= 1. ${HOLD_USAGE}`);
35
+ slots = Number(v);
36
+ }
32
37
  else {
33
38
  const s = Number(v);
34
39
  if (!Number.isFinite(s) || s < 0)
@@ -49,7 +54,10 @@ export function parseHold(args) {
49
54
  throw new Error(`Invalid resource ${JSON.stringify(resource)}: use 1–64 of A-Z a-z 0-9 . _ -`);
50
55
  if (!argv.length)
51
56
  throw new Error(`hold needs a command after --. ${HOLD_USAGE}`);
52
- return { resource, mode, ...(maxWaitMs !== undefined ? { maxWaitMs } : {}), ...(note !== undefined ? { note } : {}), argv };
57
+ if (shared && slots !== undefined)
58
+ throw new Error(`--slots and --shared cannot be combined. ${HOLD_USAGE}`);
59
+ const mode = slots !== undefined ? "counted" : shared ? "shared" : "exclusive";
60
+ return { resource, mode, ...(slots !== undefined ? { slots } : {}), ...(maxWaitMs !== undefined ? { maxWaitMs } : {}), ...(note !== undefined ? { note } : {}), argv };
53
61
  }
54
62
  const age = (ms) => ms < 60_000 ? `${Math.max(0, Math.round(ms / 1000))}s` : ms < 3_600_000 ? `${Math.round(ms / 60_000)}m` : `${(ms / 3_600_000).toFixed(1)}h`;
55
63
  const SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"];
@@ -58,7 +66,7 @@ export async function hold(args, options = {}) {
58
66
  const env = options.env ?? process.env, home = dsaHome(env), say = options.stderr ?? (l => process.stderr.write(`${l}\n`));
59
67
  const pollMs = options.pollMs ?? 250, graceMs = options.graceMs ?? 2000;
60
68
  const request = {
61
- resource: args.resource, mode: args.mode,
69
+ resource: args.resource, mode: args.mode, ...(args.slots !== undefined ? { slots: args.slots } : {}),
62
70
  wrapper: { pid: process.pid, start: (await captureStart(process.pid)) || undefined },
63
71
  argv: args.argv.map(a => a.length > 200 ? `${a.slice(0, 199)}…` : a).slice(0, 32), cwd: process.cwd(),
64
72
  ...(args.note ? { note: args.note.slice(0, 300) } : {}), since: Date.now(),
@@ -67,7 +75,7 @@ export async function hold(args, options = {}) {
67
75
  // No wait: granted now, or refused without a ticket — never listed as a waiter, even for a moment.
68
76
  const granted = args.maxWaitMs === 0 ? await tryGrant(home, request) : undefined;
69
77
  if (granted && "busy" in granted) {
70
- const now = Date.now(), by = granted.busy.map(t => `${who(t)} (${t.mode}${t.grantedAt === undefined ? ", waiting" : ""}, ${age(now - (t.grantedAt ?? t.since))})`).join(", ");
78
+ const now = Date.now(), by = granted.busy.map(t => `${who(t)} (${modeLabel(t)}${t.grantedAt === undefined ? ", waiting" : ""}, ${age(now - (t.grantedAt ?? t.since))})`).join(", ");
71
79
  say(`hold: ${args.resource} is not free now (${by}); not running the command (exit ${WAIT_EXPIRED})`);
72
80
  return WAIT_EXPIRED;
73
81
  }
@@ -99,12 +107,13 @@ export async function hold(args, options = {}) {
99
107
  catch { /* polling suffices */ }
100
108
  let shown;
101
109
  const ended = new Map();
102
- for (;;) {
110
+ // A ticket granted under the lock (no wait) runs at once; only a queued one waits.
111
+ while (ticket.grantedAt === undefined) {
103
112
  if (interrupted) {
104
113
  removeTicket(home, ticket);
105
114
  return 128 + (constants.signals[interrupted] ?? 1);
106
115
  }
107
- const ahead = blockers(ticket, liveTickets(home, args.resource));
116
+ const all = liveTickets(home, args.resource), ahead = blockers(ticket, all);
108
117
  if (!ahead.length)
109
118
  break;
110
119
  const now = Date.now();
@@ -126,11 +135,16 @@ export async function hold(args, options = {}) {
126
135
  say(`hold: ${args.resource} still held by ${ahead.filter(t => t.grantedAt !== undefined).map(who).join(", ") || who(ahead[0])} after ${age(now - ticket.since)}; not running the command (exit ${WAIT_EXPIRED})`);
127
136
  return WAIT_EXPIRED;
128
137
  }
129
- const holders = ahead.filter(t => t.grantedAt !== undefined), key = holders.map(t => t.seq).join(",") || `q${ahead[0].seq}`;
138
+ // A counted request names its place among the waiters and how many slots are taken: "position 2, held 4/4".
139
+ const counted = args.mode === "counted", granted = (counted ? all : ahead).filter(t => t.grantedAt !== undefined && t.seq !== ticket.seq);
140
+ const position = all.filter(t => t.seq < ticket.seq && t.grantedAt === undefined).length + 1;
141
+ const key = `${granted.map(t => t.seq).join(",") || `q${ahead[0].seq}`}${counted ? `@${position}` : ""}`;
130
142
  if (key !== shown) {
131
143
  shown = key;
132
- const by = holders.length ? holders.map(t => `${who(t)} (${t.mode}, ${age(now - (t.grantedAt ?? t.since))})`).join(", ") : `${who(ahead[0])} (waiting)`;
133
- say(`hold: waiting for ${args.resource} (${args.mode}) — held by ${by}; ${ahead.length} ahead`);
144
+ const by = granted.length ? granted.map(t => `${who(t)} (${modeLabel(t)}, ${age(now - (t.grantedAt ?? t.since))})`).join(", ") : `${who(ahead[0])} (waiting)`;
145
+ say(counted
146
+ ? `hold: waiting for ${args.resource} (slot, position ${position}, held ${granted.length}/${args.slots}); held by ${by}`
147
+ : `hold: waiting for ${args.resource} (${args.mode}) — held by ${by}; ${ahead.length} ahead`);
134
148
  }
135
149
  await new Promise(resolve => { const timer = setTimeout(resolve, pollMs); wake = () => { clearTimeout(timer); resolve(); }; });
136
150
  }
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> | --no-wait] [--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
  }