pi-durable-subagents 1.0.43 → 1.1.0

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.
@@ -1,6 +1,7 @@
1
1
  import { closeSync, openSync, readSync, statSync } from "node:fs";
2
2
  import { StringDecoder } from "node:string_decoder";
3
3
  import { join } from "node:path";
4
+ import { liveCommandCalls } from "../../orchestrator/executor/command.js";
4
5
  import { forgetJournalSnapshot, journalAppends, readJournalFold, readJournalSnapshot, readJournalUncached } from "../../kernel/journal.js";
5
6
  import { journalPath } from "../../paths.js";
6
7
  import { CT, JT } from "../../types.js";
@@ -110,10 +111,49 @@ function unfinishedJournal(path, known) {
110
111
  decided.set(path, { ino: read.ino, size: read.size, unfinished });
111
112
  return unfinished;
112
113
  }
114
+ /** R3, F4: Whether a journal has a live command attempt (liveCommandCalls: an intent not withdrawn, of a call neither
115
+ * sealed nor retired). A hold never stops
116
+ * one, so an orchestrator must watch and seal it even while its workflow is held. Cached by file identity. */
117
+ const commanded = new Map();
118
+ function startedCommand(path, known) {
119
+ let stat;
120
+ try {
121
+ stat = statSync(path);
122
+ }
123
+ catch (error) {
124
+ if (error.code !== "ENOENT")
125
+ throw error;
126
+ commanded.delete(path);
127
+ return false;
128
+ }
129
+ if (!stat.isFile()) {
130
+ commanded.delete(path);
131
+ return false;
132
+ } // unreadable held work stays held
133
+ const hit = commanded.get(path);
134
+ if (hit && hit.ino === stat.ino && hit.size === stat.size)
135
+ return hit.running;
136
+ let read = known;
137
+ try {
138
+ read ??= readJournalUncached(path);
139
+ }
140
+ catch {
141
+ commanded.delete(path);
142
+ return false;
143
+ }
144
+ if (!read) {
145
+ commanded.delete(path);
146
+ return false;
147
+ }
148
+ const running = liveCommandCalls(read.entries).length > 0;
149
+ commanded.set(path, { ino: read.ino, size: read.size, running });
150
+ return running;
151
+ }
113
152
  /** P1: Workflow-side pending work shared by every starter: a workflow without JT.done or with an unsealed generation,
114
153
  * unless a drain (stop-all) holds it: held work waits for an explicit resume, which starts the orchestrator itself.
115
- * Stops at the first unfinished workflow (newest first); a held workflow the ledger attributes is skipped without
116
- * reading its journal, and an unchanged journal is not read again. */
154
+ * R3: a held workflow with a started, unsealed command call is pending all the same (the hold does not stop it).
155
+ * Stops at the first unfinished workflow (newest first); a held workflow is read only for a started command call
156
+ * (startedCommand), and an unchanged journal is not read again. */
117
157
  export function unfinishedWorkflow(home, fresh = false) {
118
158
  const { record, names } = readerWorkflowListing(home, fresh), ix = record.state, { created, pruned } = ix;
119
159
  const ids = [...new Set([...[...created.keys()].map(String), ...names].filter(wid => !pruned.has(wid)))].sort().reverse();
@@ -122,13 +162,19 @@ export function unfinishedWorkflow(home, fresh = false) {
122
162
  // The hold rule is the one workflows() applies: the ledger's `created` names the origin a drain may hold; only for
123
163
  // a wid the ledger has no `created` for is the journal read first, for a `created` entry of its own.
124
164
  const known = created.get(wid);
125
- if (known && readerHold(ix, wid, known.origin))
165
+ if (known && readerHold(ix, wid, known.origin)) {
166
+ if (startedCommand(path))
167
+ return true;
126
168
  continue;
169
+ }
127
170
  let read;
128
171
  if (!known) {
129
172
  read = readJournalUncached(path);
130
- if (readerHold(ix, wid, read?.entries.find(e => e.type === JT.created)?.origin))
173
+ if (readerHold(ix, wid, read?.entries.find(e => e.type === JT.created)?.origin)) {
174
+ if (startedCommand(path, read))
175
+ return true;
131
176
  continue;
177
+ }
132
178
  }
133
179
  if (unfinishedJournal(path, read))
134
180
  return true;
@@ -4,11 +4,19 @@ import { resolve } from "node:path";
4
4
  import { readJournalFold } from "../../kernel/journal.js";
5
5
  import { generationRids } from "../../orchestrator/notes.js";
6
6
  import { journalPath } from "../../paths.js";
7
+ import { isCommandCall } from "../../types.js";
7
8
  import { validateCallSpec } from "../../compat/spec.js";
8
9
  import { compileFanout } from "../../compat/fanout.js";
9
10
  import { checkLabels } from "../../events/labels.js";
10
11
  /** Call fields a tasks/chain run applies to every step that does not set its own. */
11
- export const stepDefaults = ["agent", "model", "timeoutMs", "budget", "isolation", "context", "tools", "skills", "once", "writer"];
12
+ export const stepDefaults = ["agent", "model", "timeoutMs", "budget", "isolation", "context", "tools", "skills", "once", "writer", "env", "rerun"];
13
+ /** The run-level defaults a command step takes; agent steps take the others (env and rerun belong to command calls). */
14
+ const commandDefaults = new Set(["timeoutMs", "writer", "env", "rerun"]), agentOnly = new Set(["env", "rerun"]);
15
+ /** The run-level defaults that apply to one step: a command step skips agent-only fields, an agent step skips env/rerun. */
16
+ function defaultsFor(step, defaults) {
17
+ const command = step.command !== undefined;
18
+ return Object.fromEntries(Object.entries(defaults).filter(([k]) => command ? commandDefaults.has(k) : !agentOnly.has(k)));
19
+ }
12
20
  function string(args, name) {
13
21
  if (typeof args[name] !== "string" || !args[name])
14
22
  throw new Error(`${name} is required`);
@@ -27,7 +35,8 @@ function call(value, cwd, where) {
27
35
  /** v12 §2: Reject unknown explicit call agents before starter or outbox publication; scripts remain call-local. Shared by
28
36
  * the tool and the CLI `run --request`. */
29
37
  export function checkAgents(body, available) {
30
- const names = [...(body.call ? [body.call] : []), ...(body.tasks ?? []), ...(body.chain ?? [])].map(call => call.agent);
38
+ // A command call names no agent.
39
+ const names = [...(body.call ? [body.call] : []), ...(body.tasks ?? []), ...(body.chain ?? [])].filter(call => !isCommandCall(call)).map(call => call.agent);
31
40
  if (!names.length)
32
41
  return;
33
42
  const known = available(), unknown = [...new Set(names.filter(name => !known.includes(name)))];
@@ -93,7 +102,10 @@ export function request(args, cwd) {
93
102
  // A task beside tasks/chain is refused with what to do, before the launch form is inferred (with or without action).
94
103
  if ((args.action === undefined || args.action === "run") && listRun && args.task !== undefined)
95
104
  throw new Error(`task cannot be set beside ${args.tasks !== undefined ? "tasks" : "chain"}: agent+task is a single call; give each step its own task (a top-level agent alone is the default agent of every step)`);
96
- const launchForms = [args.task !== undefined || args.agent !== undefined && !listRun, args.tasks !== undefined,
105
+ // So is a command: a command call is a launch form of its own, or a step of the list.
106
+ if ((args.action === undefined || args.action === "run") && listRun && args.command !== undefined)
107
+ throw new Error(`command cannot be set beside ${args.tasks !== undefined ? "tasks" : "chain"}: put it in a step ({command, ...}); a top-level command is a single command call`);
108
+ const launchForms = [args.task !== undefined || args.command !== undefined || args.agent !== undefined && !listRun, args.tasks !== undefined,
97
109
  args.chain !== undefined, args.workflow !== undefined, args.source !== undefined];
98
110
  const action = args.action === undefined && launchForms.filter(Boolean).length === 1 ? "run" : args.action;
99
111
  if (typeof action !== "string" || !action)
@@ -102,10 +114,10 @@ export function request(args, cwd) {
102
114
  const { action: _, workflow, source, tasks, chain, args: inputs, name, usageBudget, maxCalls, inputs: files, labels, by: _by, request: _request, ...spec } = args;
103
115
  const steps = tasks !== undefined || chain !== undefined;
104
116
  // With tasks/chain a top-level agent (no task) is the default agent of every step, like model or timeoutMs.
105
- const single = spec.task !== undefined || spec.agent !== undefined && !steps;
117
+ const single = spec.task !== undefined || spec.command !== undefined || spec.agent !== undefined && !steps;
106
118
  const choices = [workflow, source, tasks, chain, single ? spec : undefined];
107
119
  if (choices.filter(v => v !== undefined).length !== 1)
108
- throw new Error("run requires exactly one of workflow, source, tasks, chain, or agent/task (with tasks/chain, a top-level agent without task is the steps' default agent)");
120
+ throw new Error("run requires exactly one of workflow, source, tasks, chain, agent/task or command (with tasks/chain, a top-level agent without task is the steps' default agent)");
109
121
  // A top-level cwd on a workflow/tasks/chain/source run is the run's directory: relative paths (the workflow file,
110
122
  // inputs, per-call cwd) resolve against it and calls default to it. It used to be ignored, so a relative
111
123
  // workflow path was looked up in the session's directory instead.
@@ -132,7 +144,7 @@ export function request(args, cwd) {
132
144
  if (!Array.isArray(list) || !list.length)
133
145
  throw new Error("tasks/chain must be nonempty");
134
146
  const kind = tasks !== undefined ? "tasks" : "chain";
135
- body[kind] = list.map((value, i) => call(value && typeof value === "object" && !Array.isArray(value) ? { ...defaults, ...value } : value, runCwd, `${kind}[${i}]`));
147
+ body[kind] = list.map((value, i) => call(value && typeof value === "object" && !Array.isArray(value) ? { ...defaultsFor(value, defaults), ...value } : value, runCwd, `${kind}[${i}]`));
136
148
  compileFanout(kind === "tasks" ? { tasks: body.tasks } : { chain: body.chain }); // duplicate keys fail here, not at admission
137
149
  }
138
150
  else
@@ -11,7 +11,7 @@ import { launchOrchestrator } from "../platform/launch.js";
11
11
  import { dsaHome, orchInbox, orchLock, outboxRoot } from "../paths.js";
12
12
  import { CT, JT } from "../types.js";
13
13
  import { PendingOutboxReader, attention, presentText, presented, resolved, unfinishedWorkflow } from "./main/snapshots.js";
14
- import { NOTIFY_SINCE, isLive, orchestratorTooOld, ownWorkflows, pausedElsewhere, runningOrchestrator, statusBrief, statusCallDetail, statusCompactDetail, statusDetail, statusView, outputSelect, writerWaits, writerWaitLine, WRITER_WAIT_HINT } from "../orchestrator/snapshot.js";
14
+ import { NOTIFY_SINCE, commandSendRefusal, isCommandTarget, isLive, orchestratorTooOld, ownWorkflows, pausedElsewhere, runningOrchestrator, statusBrief, statusCallDetail, statusCompactDetail, statusDetail, statusView, outputSelect, writerWaits, writerWaitLine, WRITER_WAIT_HINT } from "../orchestrator/snapshot.js";
15
15
  import { BATCH, checkAgents, followUpReceipt, outcomeLine, request, sendReceipt } from "./main/tool.js";
16
16
  import { parameters } from "./main/schema.js";
17
17
  import { batchConflict, batchDigest, findRequest, manyIds, namesMany, requestRid, sendIdentified } from "../requests.js";
@@ -331,6 +331,10 @@ export function registerMain(pi, ui) {
331
331
  (args.to === undefined || args.to === body.to) && (args.qid === undefined || args.qid === prior.cond.qid))
332
332
  args = { ...args, to: body.to, qid: prior.cond.qid, rev: args.rev ?? prior.cond.rev };
333
333
  }
334
+ // R8: a command call has no questions: an answer is refused with the pinned reason (as the orchestrator refuses one
335
+ // that names a qid/rev), not with the question pre-fill's "no open question".
336
+ if (args.action === "send" && args.kind === "answer" && (args.qid === undefined || args.rev === undefined) && isCommandTarget(home, args.to))
337
+ return { applied: false, reason: commandSendRefusal("answer") };
334
338
  if (args.action === "send")
335
339
  args = completeSend(args);
336
340
  // A session resumes its own held work (what its quit paused); the CLI `resume` remains the global one.
@@ -430,7 +434,7 @@ export function registerMain(pi, ui) {
430
434
  pi.registerTool(defineTool({
431
435
  name: "subagents", label: "Subagents", description: [
432
436
  "Durable asynchronous subagents; run returns {wid} when created (or {submitted:{rid}} while pending). A finished workflow (its notice carries every agent's result) or a question wakes you, so after starting work end your turn: never poll with sleep or repeated status. Crash recovery resumes sessions, not external side effects. Background helper processes (orchestrator, evaluator) exit by themselves about 10 s after all work ends: never kill processes or delete files to 'clean up'. When the user quits pi, this session's running workflows pause (nothing is spent); resume continues them.",
433
- "run (action optional for exactly one launch form): agent+task; tasks:[call specs] parallel; chain:[call specs] sequential ({previous}); workflow:'./script.js' or source (runs.run(key,spec), runs.all([...]), emit(value), args, runs.input(name)). Optional name, cwd, usageBudget, maxCalls, inputs, labels. With tasks/chain, top-level agent (without task), model, timeoutMs, budget, isolation, context, tools, skills, once, writer are defaults for every step (a step's own value wins); a workflow/source script sets them per runs.run call. timeoutMs is milliseconds of active time (a number); omit it unless a hard limit is needed. Explicit unknown agents are rejected BEFORE creation, with available names; unknown script agents fail only their call.",
437
+ "run (action optional for exactly one launch form): agent+task; command (a command call); tasks:[call specs] parallel; chain:[call specs] sequential ({previous}); workflow:'./script.js' or source (runs.run(key,spec), runs.all([...]), emit(value), args, runs.input(name)). Optional name, cwd, usageBudget, maxCalls, inputs, labels. With tasks/chain, top-level agent (without task), model, timeoutMs, budget, isolation, context, tools, skills, once, writer are defaults for every step (a step's own value wins); a workflow/source script sets them per runs.run call. timeoutMs is milliseconds of active time (a number); omit it unless a hard limit is needed. A command call {command:[argv] or 'sh string', cwd?, timeoutMs? (wall-clock), env?, rerun?, writer?} runs a process instead of an agent: no model, slot or tokens; it keeps running across orchestrator restarts and a quit pi, and wakes you like any call; result ok on exit 0 else failed, data {exitCode, signal, durationMs}, output = last 16 KiB of stdout+stderr; only stop controls it. Run-level env/rerun apply to command steps, agent-only defaults skip them; in a chain an agent step after a command step gets its output as {previous}. Explicit unknown agents are rejected BEFORE creation, with available names; unknown script agents fail only their call.",
434
438
  "agents: list names, descriptions, default models and source for this cwd; use these names for run.",
435
439
  "send to:'<wid>/<key>' (bare '<wid>' only for a single-call workflow): steer on a running call delivers at the next safe point (receipt in status/UI); a steer to a call waiting on its question interrupts the question and the subagent usually asks again — use answer to answer it; sealed → finished:<status> — use kind 'follow-up'. notify tells a call a decision without disturbing it; the reply's delivery says how: steered (running: it gets the note at its next safe point), held-until-answer (waiting on its question: never interrupts it, delivered after the answer) or noted (not running: nothing starts; the note is recorded and the call's next follow-up opens with every pending note; status shows notesPending). to may list several calls for steer, notify, follow-up and model: one request per call, each decided on its own, one result line per target (request:<id> sends <id>:1...<id>:n; a retry with the same list is safe). follow-up continues a sealed call as generation g+1 (reply generation) or queues after a running turn (reply delivery forwarded; if that turn ends without taking it, it opens g+1); follow-up model:'provider/id' or a pool name runs that generation on it. answer: give the qid (or just the call, or nothing when one question is open); to and rev are filled in. A question that needs the user's decision goes to the user; if you answer one yourself, tell the user what you chose. model ('provider/id' or a pool name — its first model not used up): a running call switches at its next provider request; an asking, hibernated or queued call launches on it when it runs again; the reply's model/effect (next-request|next-execution|next-generation) says which. status model = model actually used by the last request; switching = requested, not used yet; switchFailed = refused. A provider content refusal (ToS/usage policy) fails the call at once, not retried. Unknown targets list valid addresses. replaces:[rid] supersedes an earlier send.",
436
440
  "stop target:<wid|<wid>/<key>> is terminal stopped (usage and partial edits kept); a sealed call → already-sealed:<status>, a finished workflow → terminal:<status>. drain holds existing workflows reversibly (new runs unaffected); resume [wid] releases held workflows. restart (after an update) replaces the orchestrator with the installed version: refused with busy:<running executions> while any runs. Never force without the user's explicit approval: show the user the refusal's list first, then supply force:'<token>' and reason. Subagents cannot force; hibernated askers and queued calls do not block it. Never kill the orchestrator process. Commands that need the machine (benchmarks, timing) take a lease: tell the subagent to run them as `pi-durable-subagents hold machine [--shared] -- <command>` (FIFO; `hold <name> --slots N` admits N at a time; status lists lease holders and waiters). status: without wid, what runs (with its run labels, clipped), asks (with its answer address; hibernated:true holds no slot) or failed, writerWait: a call queued for its git worktree's writer lock (one call whose tools include edit/write runs per worktree; spec writer:false or isolation:'worktree' opts out), sharedWorktree names calls sharing observed edit/write roots (reminder), lease: a call holding or waiting for a resource lease, queued: why a queued call does not start (orchestrator starting while it recovers after a start, a used-up provider, a writer lock, full providers; absent when not known), finished workflows one line each, provider slots held/limit, the config in effect and providers whose usage window is used up (avoided until a probe finds them answering again), and the orchestrator version (with ', starting <age>' while it recovers; versionNote when it differs from the loaded one); wid: one workflow, outputs clipped; wid+tail:N: the last N lines of each call's result, wid+grep:'<regex>': only its matching lines (a JS regex run in-process: avoid nested quantifiers like (a+)+; first 2000 chars of a line, last 5000 lines; both: grep, then tail; at most 4000 chars per call); wid+key: one call's full result; full:true: everything. A run reply names calls already queued behind a writer lock (writerWait). A run's rid from {submitted:{rid}} works wherever a wid is expected. revise wid + workflow/source/args starts a revision.",
package/dist/cli/hold.js CHANGED
@@ -1,15 +1,13 @@
1
- // `pi-durable-subagents hold <resource> [--shared | --slots <n>] [--max-wait <s>] [--note <text>] -- <command> [args…]`
2
- // Waits for the lease (strict FIFO), runs the command in its own process group, ends what the command left in that
3
- // group, then releases. `--max-wait 0` (or `--no-wait`) takes the lease at once or exits 75 without ever being queued.
4
- // See src/platform/lease.ts for the ticket protocol.
1
+ // Command-scoped leases: priority then FIFO among waiters, with every grant committed under the resource lock.
2
+ // Commands run in their own process group and inherit DSA_HOLD; their group and tagged descendants end before release.
5
3
  import { spawn } from "node:child_process";
6
4
  import { watch } from "node:fs";
7
5
  import { constants } from "node:os";
8
6
  import { dsaHome } from "../paths.js";
9
7
  import { captureStart } from "../platform/proctable.js";
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
- /** Exit status when --max-wait expires before the lease is granted (EX_TEMPFAIL). */
8
+ import { blockers, endLeaseProcesses, enqueue, grantQueued, holdDetail, holdTag, tryGrant, leaseDir, liveTickets, orphaned, rank, removeTicket, RESOURCE, who, writeTicket } from "../platform/lease.js";
9
+ export const HOLD_USAGE = "usage: pi-durable-subagents hold <resource> [--shared | --slots <n>] [--priority <n>] [--yield] [--expect <duration>] [--max-wait <seconds> | --no-wait] [--note <text>] -- <command> [args…]";
10
+ /** Exit status when the command did not run or was stopped to yield (EX_TEMPFAIL). */
13
11
  export const WAIT_EXPIRED = 75;
14
12
  export function parseHold(args) {
15
13
  const split = args.indexOf("--");
@@ -17,13 +15,16 @@ export function parseHold(args) {
17
15
  throw new Error(`hold needs -- before the command. ${HOLD_USAGE}`);
18
16
  const opts = args.slice(0, split), argv = args.slice(split + 1);
19
17
  let resource, shared = false, slots, maxWaitMs, note;
18
+ let priority, yielding, expectMs;
20
19
  for (let i = 0; i < opts.length; i++) {
21
20
  const a = opts[i];
22
21
  if (a === "--shared")
23
22
  shared = true;
23
+ else if (a === "--yield")
24
+ yielding = true;
24
25
  else if (a === "--no-wait")
25
26
  maxWaitMs = 0;
26
- else if (a === "--max-wait" || a === "--note" || a === "--slots") {
27
+ else if (["--max-wait", "--note", "--slots", "--priority", "--expect"].includes(a)) {
27
28
  const v = opts[++i];
28
29
  if (v === undefined)
29
30
  throw new Error(`${a} needs a value. ${HOLD_USAGE}`);
@@ -34,6 +35,18 @@ export function parseHold(args) {
34
35
  throw new Error(`--slots must be an integer >= 1. ${HOLD_USAGE}`);
35
36
  slots = Number(v);
36
37
  }
38
+ else if (a === "--priority") {
39
+ if (!/^-?\d+$/.test(v) || !Number.isInteger(Number(v)) || Number(v) < -100 || Number(v) > 100)
40
+ throw new Error(`--priority must be an integer from -100 to 100. ${HOLD_USAGE}`);
41
+ priority = Number(v);
42
+ }
43
+ else if (a === "--expect") {
44
+ const m = /^(\d+)([smh]?)$/.exec(v);
45
+ const duration = m ? Number(m[1]) * (m[2] === "h" ? 3_600_000 : m[2] === "m" ? 60_000 : 1000) : NaN;
46
+ if (!Number.isSafeInteger(duration) || duration < 1000 || duration > 7 * 24 * 3_600_000)
47
+ throw new Error(`--expect must be a duration from 1s to 7d (seconds, s, m or h). ${HOLD_USAGE}`);
48
+ expectMs = duration;
49
+ }
37
50
  else {
38
51
  const s = Number(v);
39
52
  if (!Number.isFinite(s) || s < 0)
@@ -57,31 +70,35 @@ export function parseHold(args) {
57
70
  if (shared && slots !== undefined)
58
71
  throw new Error(`--slots and --shared cannot be combined. ${HOLD_USAGE}`);
59
72
  const mode = slots !== undefined ? "counted" : shared ? "shared" : "exclusive";
60
- return { resource, mode, ...(slots !== undefined ? { slots } : {}), ...(maxWaitMs !== undefined ? { maxWaitMs } : {}), ...(note !== undefined ? { note } : {}), argv };
73
+ return { resource, mode, ...(slots !== undefined ? { slots } : {}), ...(priority !== undefined ? { priority } : {}),
74
+ ...(yielding ? { yield: yielding } : {}), ...(expectMs !== undefined ? { expectMs } : {}),
75
+ ...(maxWaitMs !== undefined ? { maxWaitMs } : {}), ...(note !== undefined ? { note } : {}), argv };
61
76
  }
62
77
  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`;
63
78
  const SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"];
64
- /** Run one held command; resolves to the exit status for the process. */
79
+ /** Run one held command; resolves only after its command tree has been ended and its lease released. */
65
80
  export async function hold(args, options = {}) {
66
81
  const env = options.env ?? process.env, home = dsaHome(env), say = options.stderr ?? (l => process.stderr.write(`${l}\n`));
67
82
  const pollMs = options.pollMs ?? 250, graceMs = options.graceMs ?? 2000;
68
83
  const request = {
69
84
  resource: args.resource, mode: args.mode, ...(args.slots !== undefined ? { slots: args.slots } : {}),
85
+ ...(args.priority !== undefined ? { priority: args.priority } : {}), ...(args.yield ? { yield: args.yield } : {}),
86
+ ...(args.expectMs !== undefined ? { expectMs: args.expectMs } : {}),
70
87
  wrapper: { pid: process.pid, start: (await captureStart(process.pid)) || undefined },
71
88
  argv: args.argv.map(a => a.length > 200 ? `${a.slice(0, 199)}…` : a).slice(0, 32), cwd: process.cwd(),
72
89
  ...(args.note ? { note: args.note.slice(0, 300) } : {}), since: Date.now(),
73
90
  ...(env.DSA_EXEC ? { exec: env.DSA_EXEC } : {}), ...(env.DSA_CALL ? { call: env.DSA_CALL } : {}),
74
91
  };
75
- // No wait: granted now, or refused without a ticket — never listed as a waiter, even for a moment.
76
92
  const granted = args.maxWaitMs === 0 ? await tryGrant(home, request) : undefined;
77
93
  if (granted && "busy" in granted) {
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(", ");
94
+ const now = Date.now(), by = granted.busy.map(t => `${who(t)} (${t.grantedAt === undefined
95
+ ? `${t.mode === "counted" ? "slot" : t.mode}, waiting, ${age(now - t.since)}${t.expectMs !== undefined ? `, expects ${age(t.expectMs)}` : ""}`
96
+ : holdDetail({ ...t, note: undefined }, now, false)})`).join(", ");
79
97
  say(`hold: ${args.resource} is not free now (${by}); not running the command (exit ${WAIT_EXPIRED})`);
80
98
  return WAIT_EXPIRED;
81
99
  }
82
100
  const ticket = granted ?? await enqueue(home, request);
83
- // Signals: while waiting they withdraw the request; while the command runs they go to its process group.
84
- let child, interrupted, wake = () => { };
101
+ let child, interrupted, wake = () => { }, cleaned = false;
85
102
  const onSignal = (signal) => {
86
103
  if (child?.pid) {
87
104
  try {
@@ -97,8 +114,11 @@ export async function hold(args, options = {}) {
97
114
  for (const s of SIGNALS)
98
115
  process.on(s, onSignal);
99
116
  let watcher;
117
+ const pause = () => new Promise(resolve => {
118
+ const timer = setTimeout(resolve, pollMs);
119
+ wake = () => { clearTimeout(timer); resolve(); };
120
+ });
100
121
  try {
101
- // Wait in order.
102
122
  const deadline = args.maxWaitMs !== undefined ? ticket.since + args.maxWaitMs : undefined;
103
123
  try {
104
124
  watcher = watch(leaseDir(home, args.resource), () => wake());
@@ -106,103 +126,88 @@ export async function hold(args, options = {}) {
106
126
  }
107
127
  catch { /* polling suffices */ }
108
128
  let shown;
109
- const ended = new Map();
110
- // A ticket granted under the lock (no wait) runs at once; only a queued one waits.
111
129
  while (ticket.grantedAt === undefined) {
112
- if (interrupted) {
113
- removeTicket(home, ticket);
130
+ if (interrupted)
114
131
  return 128 + (constants.signals[interrupted] ?? 1);
132
+ const all = liveTickets(home, args.resource);
133
+ let ahead = blockers(ticket, all);
134
+ // A lock-free observation is only a hint. Priority can change while the lock is being acquired.
135
+ if (!ahead.length) {
136
+ ahead = await grantQueued(home, ticket);
137
+ if (ticket.grantedAt !== undefined)
138
+ break;
115
139
  }
116
- const all = liveTickets(home, args.resource), ahead = blockers(ticket, all);
117
- if (!ahead.length)
118
- break;
119
- const now = Date.now();
120
- // A holder whose wrapper was killed after its command ended can leave processes in the command's group; the
121
- // wrapper would have ended them before releasing, so a waiter does: TERM, then KILL after the grace period.
122
- for (const t of ahead.filter(orphaned)) {
123
- const first = ended.get(t.seq);
124
- if (first === undefined)
125
- say(`hold: ending processes left by ${who(t)} (its hold process is gone)`);
126
- try {
127
- process.kill(-t.command.pid, first !== undefined && now - first >= graceMs ? "SIGKILL" : "SIGTERM");
128
- }
129
- catch { /* gone */ }
130
- if (first === undefined)
131
- ended.set(t.seq, now);
140
+ const leftovers = ahead.filter(orphaned);
141
+ for (const t of leftovers) {
142
+ say(`hold: ending processes left by ${who(t)} (its hold process is gone)`);
143
+ await endLeaseProcesses(t, graceMs, say);
144
+ removeTicket(home, t);
132
145
  }
146
+ if (leftovers.length)
147
+ continue;
148
+ const now = Date.now();
133
149
  if (deadline !== undefined && now >= deadline) {
134
- removeTicket(home, ticket);
135
150
  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})`);
136
151
  return WAIT_EXPIRED;
137
152
  }
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}` : ""}`;
153
+ const counted = args.mode === "counted", holders = (counted ? all : ahead).filter(t => t.grantedAt !== undefined && t.seq !== ticket.seq);
154
+ const position = all.filter(t => t.grantedAt === undefined && rank(t, ticket) < 0).length + 1;
155
+ const key = `${holders.map(t => t.seq).join(",") || `q${ahead[0].seq}`}${counted ? `@${position}` : ""}`;
142
156
  if (key !== shown) {
143
157
  shown = key;
144
- const by = granted.length ? granted.map(t => `${who(t)} (${modeLabel(t)}, ${age(now - (t.grantedAt ?? t.since))})`).join(", ") : `${who(ahead[0])} (waiting)`;
158
+ const by = holders.length ? holders.map(t => `${who(t)} (${holdDetail({ ...t, note: undefined }, now, false)})`).join(", ") : `${who(ahead[0])} (waiting)`;
145
159
  say(counted
146
- ? `hold: waiting for ${args.resource} (slot, position ${position}, held ${granted.length}/${args.slots}); held by ${by}`
160
+ ? `hold: waiting for ${args.resource} (slot, position ${position}, held ${holders.length}/${args.slots}); held by ${by}`
147
161
  : `hold: waiting for ${args.resource} (${args.mode}) — held by ${by}; ${ahead.length} ahead`);
148
162
  }
149
- await new Promise(resolve => { const timer = setTimeout(resolve, pollMs); wake = () => { clearTimeout(timer); resolve(); }; });
163
+ await pause();
150
164
  }
151
- watcher?.close();
152
- watcher = undefined;
153
- ticket.grantedAt ??= Date.now();
154
- await writeTicket(home, ticket);
155
- if (interrupted) {
156
- removeTicket(home, ticket);
165
+ if (interrupted)
157
166
  return 128 + (constants.signals[interrupted] ?? 1);
158
- }
159
167
  if (shown)
160
168
  say(`hold: ${args.resource} granted after ${age(ticket.grantedAt - ticket.since)}`);
161
- // Run. stdin stays attached only when it is not a terminal: a background process group reading the terminal stops.
162
- const c = spawn(args.argv[0], args.argv.slice(1), { stdio: [process.stdin.isTTY ? "ignore" : "inherit", "inherit", "inherit"], detached: true, env });
169
+ // stdin stays attached only when it is not a terminal: a background group reading the terminal stops.
170
+ const c = spawn(args.argv[0], args.argv.slice(1), { stdio: [process.stdin.isTTY ? "ignore" : "inherit", "inherit", "inherit"], detached: true,
171
+ env: { ...env, DSA_HOLD: holdTag(ticket) } });
163
172
  child = c;
173
+ let status;
164
174
  const exit = new Promise(resolve => {
165
175
  c.once("error", error => { say(`hold: cannot run ${args.argv[0]}: ${error.message}`); resolve(127); });
166
176
  c.once("exit", (code, signal) => resolve(code ?? 128 + (signal ? constants.signals[signal] ?? 1 : 1)));
167
177
  });
178
+ void exit.then(value => { status = value; wake(); });
168
179
  if (c.pid) {
169
- ticket.command = { pid: c.pid, start: (await captureStart(c.pid)) || undefined };
180
+ ticket.command = { pid: c.pid };
181
+ ticket.command.start = (await captureStart(c.pid)) || undefined;
170
182
  await writeTicket(home, ticket).catch(() => { });
171
183
  }
172
- const status = await exit;
173
- // End what the command left behind in its group before the lease goes to the next holder.
174
- if (c.pid && groupAlive(c.pid)) {
175
- try {
176
- process.kill(-c.pid, "SIGTERM");
177
- }
178
- catch { /* gone */ }
179
- const until = Date.now() + graceMs;
180
- while (groupAlive(c.pid) && Date.now() < until)
181
- await new Promise(r => setTimeout(r, 50));
182
- if (groupAlive(c.pid)) {
183
- try {
184
- process.kill(-c.pid, "SIGKILL");
184
+ while (status === undefined) {
185
+ if (args.yield) {
186
+ const all = liveTickets(home, args.resource);
187
+ const waiter = all.filter(t => t.grantedAt === undefined && blockers(t, all).some(b => b.seq === ticket.seq)).sort(rank)[0];
188
+ if (waiter) {
189
+ await endLeaseProcesses(ticket, graceMs, say);
190
+ cleaned = true;
191
+ say(`hold: yielded ${args.resource} to ${who(waiter)} after ${age(Date.now() - ticket.grantedAt)}; the command was stopped (exit ${WAIT_EXPIRED})`);
192
+ return WAIT_EXPIRED;
185
193
  }
186
- catch { /* gone */ }
187
- }
188
- for (let i = 0; i < 40 && groupAlive(c.pid); i++)
189
- await new Promise(r => setTimeout(r, 25));
190
- }
191
- // A /proc listing is not atomic (a member can fork and exit while it is read): a last group signal ends any member
192
- // the checks missed, a newborn included. The group id is still ours while it has members.
193
- if (c.pid) {
194
- try {
195
- process.kill(-c.pid, "SIGKILL");
196
194
  }
197
- catch { /* gone */ }
195
+ await pause();
198
196
  }
199
- removeTicket(home, ticket);
200
197
  return status;
201
198
  }
202
199
  finally {
203
200
  watcher?.close();
204
- for (const s of SIGNALS)
205
- process.off(s, onSignal);
201
+ // Also covers errors during launch/capture/write and forwarded signals followed by command exit.
202
+ try {
203
+ if (child && !cleaned)
204
+ await endLeaseProcesses(ticket, graceMs, say);
205
+ }
206
+ finally {
207
+ removeTicket(home, ticket);
208
+ for (const s of SIGNALS)
209
+ process.off(s, onSignal);
210
+ }
206
211
  }
207
212
  }
208
213
  /** `leases [--json]`. */
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";
@@ -17,6 +17,7 @@ import { leaseLines, leaseState } from "../platform/lease.js";
17
17
  import { resolvePi } from "../platform/launch.js";
18
18
  import { currentOrchestrator, decidedBy, legacyRestart, cliInitiator, waitExit, waitSuccessor } from "./restart.js";
19
19
  import { restartInputError } from "../orchestrator/restart.js";
20
+ import { packageVersion } from "../version.js";
20
21
  const commands = ["smoke", "tail", "status", "events", "start", "resume", "drain", "stop", "stop-all", "prune", "restart", "leases", "doctor", "install-service", "uninstall-service", "help"];
21
22
  /** P25: Reject ambiguous CLI arguments before any durable action. */
22
23
  export function parseArgs(args) {
@@ -116,13 +117,15 @@ const answeredNote = (c, paused) => {
116
117
  return why ? ` (answered): ${why}` : " (answered)"; // no slot claim without a full provider
117
118
  return why ? `: ${why}` : "";
118
119
  };
120
+ /** A command call's place of a model: " command: <clipped> (pid 123, 2m)" / " command: <clipped> (exit 3)". */
121
+ const commandSuffix = (c) => c.command === undefined ? "" : ` command: ${c.command}${commandFacts(c) ? ` (${commandFacts(c)})` : ""}`;
119
122
  /** P25, T10: Render journal-derived status (one line per call, last output line only) without live orchestrator memory. */
120
123
  export function renderStatus(wf) {
121
124
  const sealed = wf.counts.sealed, total = wf.calls.length, used = wf.usage && (wf.usage.input || wf.usage.output || wf.usage.costUsd);
122
125
  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
126
  ...wf.calls.map(c => {
124
127
  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)}`;
128
+ 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
129
  }),
127
130
  ...wf.attention.map(a => ` ${a.kind}: ${JSON.stringify(clip(a.text, 300))}`),
128
131
  ...(wf.scriptLog ? [` script log: ${wf.scriptLog}`] : [])].join("\n");
@@ -135,7 +138,7 @@ export function renderSelected(wf) {
135
138
  /** P25, T10: Render the compact status projection shared with the `subagents` tool. */
136
139
  export function renderView(view) {
137
140
  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)}`),
141
+ ...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
142
  ...w.attention.map(a => ` ${a.kind}: ${JSON.stringify(a.text.split("\n")[0])}`)].join("\n"));
140
143
  if (view.paused)
141
144
  lines.unshift(`${view.paused} (pi-durable-subagents resume)`);
@@ -180,7 +183,7 @@ export function serviceEntryError(entry) {
180
183
  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.`;
181
184
  return undefined;
182
185
  }
183
- 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>] [--session <id>] [--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]";
186
+ 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 | version | --version | run --request <id> [--wake caller] --spec <file|-> [--labels <json>] [--session <id>] [--cwd <dir>] [--json] [--wait-ms <n>] | run --request <id> [--wake caller] [--cwd <dir>] [--timeout-ms <n>] [--name <text>] [--labels <json>] [--session <id>] [--json] [--wait-ms <n>] -- <program> [args…] | 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>] [--priority <n>] [--yield] [--expect <duration>] [--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]";
184
187
  /** Restart: the orchestrator exits when no execution runs (or `force`) and the installed version takes over. */
185
188
  async function restartCommand(home, env, write, options) {
186
189
  const body = { ...(typeof options.force === "string" ? { token: options.force } : options.force === true ? { force: true } : {}), ...(options.reason !== undefined ? { reason: options.reason } : {}), initiator: cliInitiator(env) };
@@ -236,6 +239,10 @@ async function restartCommand(home, env, write, options) {
236
239
  }
237
240
  /** P1, P21, P25, P38: Dispatch the public CLI using durable requests and read-only snapshots. */
238
241
  export async function main(args = process.argv.slice(2), options = {}) {
242
+ if (args.length === 1 && (args[0] === "version" || args[0] === "--version")) {
243
+ (options.write ?? console.log)(`pi-durable-subagents ${packageVersion()}`);
244
+ return 0;
245
+ }
239
246
  if (args[0] === "hold") {
240
247
  const { hold, parseHold } = await import("./hold.js");
241
248
  return hold(parseHold(args.slice(1)), { env: options.env ?? process.env });