pi-durable-subagents 1.0.25 → 1.0.28
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +73 -0
- package/README.md +135 -15
- package/dist/agent/child.js +7 -2
- package/dist/agent/main/schema.js +4 -1
- package/dist/agent/main/tool.js +42 -8
- package/dist/agent/main.js +62 -12
- package/dist/cli/doctor.js +4 -3
- package/dist/cli/drill/index.js +287 -0
- package/dist/cli/drill/provider.js +25 -0
- package/dist/cli/hold.js +42 -17
- package/dist/cli/main.js +50 -11
- package/dist/cli/requests.js +105 -19
- package/dist/events/derive.js +7 -3
- package/dist/kernel/journal.js +99 -15
- package/dist/kernel/mailbox.js +1 -1
- package/dist/orchestrator/engine.js +157 -12
- package/dist/orchestrator/evaluator-client.js +18 -3
- package/dist/orchestrator/executor/digest.js +80 -0
- package/dist/orchestrator/executor/index.js +47 -37
- package/dist/orchestrator/executor/observe.js +21 -7
- package/dist/orchestrator/executor/session.js +4 -2
- package/dist/orchestrator/notes.js +20 -0
- package/dist/orchestrator/restart.js +5 -3
- package/dist/orchestrator/snapshot.js +144 -21
- package/dist/orchestrator/stats.js +49 -0
- package/dist/platform/containment.js +35 -11
- package/dist/platform/lease.js +53 -11
- package/dist/platform/proctable.js +16 -3
- package/dist/requests.js +31 -0
- package/dist/ui/session.js +2 -2
- package/dist/ui/view.js +5 -2
- package/package.json +1 -1
package/dist/agent/main.js
CHANGED
|
@@ -12,10 +12,10 @@ import { OsLock } from "../platform/lock.js";
|
|
|
12
12
|
import { dsaHome, orchInbox, orchLedger, orchLock, outboxRoot } from "../paths.js";
|
|
13
13
|
import { CT, JT } from "../types.js";
|
|
14
14
|
import { attention, presentText, presented, resolved, unfinishedWorkflow } from "./main/snapshots.js";
|
|
15
|
-
import { isLive, pausedElsewhere, runningOrchestrator, statusBrief, statusCallDetail, statusCompactDetail, statusDetail, statusView, widOfRid } from "../orchestrator/snapshot.js";
|
|
16
|
-
import { checkAgents, request, sendReceipt } from "./main/tool.js";
|
|
15
|
+
import { NOTIFY_SINCE, isLive, orchestratorTooOld, pausedElsewhere, runningOrchestrator, statusBrief, statusCallDetail, statusCompactDetail, statusDetail, statusView, widOfRid, outputSelect, writerWaits, writerWaitLine, WRITER_WAIT_HINT } from "../orchestrator/snapshot.js";
|
|
16
|
+
import { BATCH, checkAgents, outcomeLine, request, sendReceipt } from "./main/tool.js";
|
|
17
17
|
import { parameters } from "./main/schema.js";
|
|
18
|
-
import { findRequest, requestRid, sendIdentified } from "../requests.js";
|
|
18
|
+
import { batchConflict, batchDigest, findRequest, manyIds, namesMany, requestRid, sendIdentified } from "../requests.js";
|
|
19
19
|
import { discoverAgents } from "../compat/agents.js";
|
|
20
20
|
import { restartInputError } from "../orchestrator/restart.js";
|
|
21
21
|
import { currentOrchestrator, legacyRestart, waitExit } from "../cli/restart.js";
|
|
@@ -236,9 +236,9 @@ export function registerMain(pi, ui) {
|
|
|
236
236
|
return { ...args, to: to ?? q.call, qid: q.qid, rev: args.rev ?? q.rev };
|
|
237
237
|
}
|
|
238
238
|
if (typeof args.to !== "string" || !args.to) {
|
|
239
|
-
const want = args.kind === "follow-up" ? (c) => c.phase === "sealed" : (c) => c.phase !== "sealed";
|
|
239
|
+
const want = args.kind === "follow-up" ? (c) => c.phase === "sealed" : args.kind === "notify" ? () => true : (c) => c.phase !== "sealed";
|
|
240
240
|
const targets = own.flatMap(w => w.calls.filter(want).map(c => `${w.wid}/${c.key}`));
|
|
241
|
-
throw new Error(`to is required: '<wid>/<key>'${targets.length ? `; ${args.kind === "follow-up" ? "finished" : "running"}: ${targets.slice(0, 12).join(", ")}` : ""}`);
|
|
241
|
+
throw new Error(`to is required: '<wid>/<key>'${targets.length ? `; ${args.kind === "follow-up" ? "finished" : args.kind === "notify" ? "calls" : "running"}: ${targets.slice(0, 12).join(", ")}` : ""}`);
|
|
242
242
|
}
|
|
243
243
|
return args;
|
|
244
244
|
}
|
|
@@ -260,7 +260,39 @@ export function registerMain(pi, ui) {
|
|
|
260
260
|
const others = pausedElsewhere(home, sender);
|
|
261
261
|
return others.length ? `nothing-to-resume: nothing of this session is paused; paused in other sessions: ${others.slice(0, 8).join(", ")} — resume wid=<wid> continues one` : reason;
|
|
262
262
|
}
|
|
263
|
+
/** A send to several calls: one request per target (the same kind, message and model), each decided on its own; the
|
|
264
|
+
* reply lists every target's outcome. With a request id <id>, target i (1-based, in the order given) is sent as
|
|
265
|
+
* <id>:<i>, so a retry with the same list gets the same outcomes; another list under that id is a request-conflict. */
|
|
266
|
+
async function sendMany(args, cwd, signal, wait = true) {
|
|
267
|
+
const targets = args.to;
|
|
268
|
+
if (!targets.length || !targets.every(t => typeof t === "string" && t))
|
|
269
|
+
throw new Error("to must name a call '<wid>/<key>' or a nonempty list of them");
|
|
270
|
+
if (args.kind === "answer")
|
|
271
|
+
throw new Error("answer goes to one call: give to as a single address");
|
|
272
|
+
if (targets.length === 1)
|
|
273
|
+
return submit({ ...args, to: targets[0] }, cwd, signal, wait);
|
|
274
|
+
if (args.replaces !== undefined)
|
|
275
|
+
throw new Error("replaces supersedes one earlier send: use it with a single target");
|
|
276
|
+
const id = args.request, ids = typeof id === "string" ? manyIds(id, targets.length) : undefined;
|
|
277
|
+
if (id !== undefined && !ids)
|
|
278
|
+
throw new Error(REQUEST_USE);
|
|
279
|
+
const batch = batchDigest(targets);
|
|
280
|
+
if (ids && typeof id === "string" && await batchConflict(home, id, batch))
|
|
281
|
+
return { applied: false, reason: "request-conflict", request: id, note: "this request id was used for different content (another message or list of calls); use a new id" };
|
|
282
|
+
const results = await Promise.all(targets.map(async (to, i) => {
|
|
283
|
+
const request = ids ? { request: ids[i] } : {};
|
|
284
|
+
try {
|
|
285
|
+
return { to, ...request, ...await submit({ ...args, to, ...request, ...(ids ? { [BATCH]: batch } : {}) }, cwd, signal, wait) };
|
|
286
|
+
}
|
|
287
|
+
catch (error) {
|
|
288
|
+
return { to, ...request, applied: false, reason: error instanceof Error ? error.message : String(error) };
|
|
289
|
+
}
|
|
290
|
+
}));
|
|
291
|
+
return { targets: results, summary: results.map(r => `${String(r.to)}: ${outcomeLine(r)}`).join("\n") };
|
|
292
|
+
}
|
|
263
293
|
async function submit(args, cwd, signal, wait = true) {
|
|
294
|
+
if (args.action === "send" && Array.isArray(args.to))
|
|
295
|
+
return sendMany(args, cwd, signal, wait);
|
|
264
296
|
// A run answers {submitted:{rid}} when its workflow is not created within 10 s; that rid then stands for the wid.
|
|
265
297
|
for (const field of ["wid", "to", "target"])
|
|
266
298
|
if (typeof args[field] === "string")
|
|
@@ -268,14 +300,20 @@ export function registerMain(pi, ui) {
|
|
|
268
300
|
if (args.request !== undefined && (args.action === "status" || args.action === "agents"))
|
|
269
301
|
throw new Error(REQUEST_USE);
|
|
270
302
|
if (args.action === "status") {
|
|
271
|
-
|
|
303
|
+
const select = outputSelect(args.tail, args.grep);
|
|
304
|
+
if (typeof args.wid !== "string" || !args.wid) {
|
|
305
|
+
if (select)
|
|
306
|
+
throw new Error("tail and grep select lines of one workflow's outputs: give a wid");
|
|
272
307
|
return statusBrief(home, { origin: sender });
|
|
308
|
+
}
|
|
273
309
|
const pending = pendingRun(args.wid);
|
|
274
310
|
if (pending)
|
|
275
311
|
return pending;
|
|
312
|
+
if (select && (args.full === true || typeof args.key === "string" && args.key))
|
|
313
|
+
throw new Error("tail and grep apply to status wid=<wid> without key or full");
|
|
276
314
|
if (typeof args.key === "string" && args.key)
|
|
277
315
|
return statusCallDetail(home, args.wid, args.key);
|
|
278
|
-
return args.full === true ? statusDetail(home, args.wid) : statusCompactDetail(home, args.wid);
|
|
316
|
+
return args.full === true ? statusDetail(home, args.wid) : statusCompactDetail(home, args.wid, select);
|
|
279
317
|
}
|
|
280
318
|
if (args.action === "agents")
|
|
281
319
|
return agentsAt(cwd).map(({ name, description, model, source }) => ({ name, description, ...(model === undefined ? {} : { model }), source }));
|
|
@@ -301,6 +339,15 @@ export function registerMain(pi, ui) {
|
|
|
301
339
|
if (args.request !== undefined && (typeof args.request !== "string" || !["run", "send", "stop"].includes(normalized.kind) || normalized.replaces?.length))
|
|
302
340
|
throw new Error(REQUEST_USE);
|
|
303
341
|
const rid = typeof args.request === "string" ? requestRid(args.request) : undefined;
|
|
342
|
+
// A single send under an id that already names a send to several calls (<id>:1 ...) is other content.
|
|
343
|
+
if (rid && normalized.kind === "send" && !await findRequest(home, rid) && await namesMany(home, String(args.request)))
|
|
344
|
+
return { applied: false, reason: "request-conflict", request: args.request, note: "this request id was used for a send to several calls; use a new id" };
|
|
345
|
+
// A retry of a recorded request gets its first outcome; a new notify is refused while an orchestrator too old for it runs.
|
|
346
|
+
if (normalized.kind === "send" && normalized.body.kind === "notify" && !(rid && await findRequest(home, rid))) {
|
|
347
|
+
const old = orchestratorTooOld(home, 'send kind "notify"', NOTIFY_SINCE);
|
|
348
|
+
if (old)
|
|
349
|
+
throw new Error(old);
|
|
350
|
+
}
|
|
304
351
|
if (normalized.kind === "run")
|
|
305
352
|
checkAgents(normalized.body, () => agentsAt(cwd).map(agent => agent.name));
|
|
306
353
|
// P33: any call of the run may fork the origin context, so the origin branch is always offered for pinning.
|
|
@@ -352,8 +399,11 @@ export function registerMain(pi, ui) {
|
|
|
352
399
|
const decision = receipt ? undefined : decisions().get(sent.rid);
|
|
353
400
|
if (receipt || decision) {
|
|
354
401
|
await serial(async () => { await outbox?.markResolved(sent.rid); });
|
|
355
|
-
if (receipt)
|
|
356
|
-
|
|
402
|
+
if (receipt) {
|
|
403
|
+
// A call already queued behind a worktree's writer lock is named at once (read once; nothing waits for it).
|
|
404
|
+
const waits = writerWaits(home, String(receipt.wid));
|
|
405
|
+
return { wid: receipt.wid, ...(waits.length ? { writerWait: waits.map(writerWaitLine), hint: WRITER_WAIT_HINT } : {}) };
|
|
406
|
+
}
|
|
357
407
|
// The rid is returned so a later send can supersede this one (replaces: [rid]).
|
|
358
408
|
if (decision.type === "rejected")
|
|
359
409
|
return { applied: false, reason: sent.kind === "resume" && args.wid === undefined ? resumeElsewhere(String(decision.reason)) : decision.reason, rid: sent.rid };
|
|
@@ -378,10 +428,10 @@ export function registerMain(pi, ui) {
|
|
|
378
428
|
pi.registerTool(defineTool({
|
|
379
429
|
name: "subagents", label: "Subagents", description: [
|
|
380
430
|
"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.",
|
|
381
|
-
"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 model, timeoutMs, budget, isolation, context, tools, skills, once 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.",
|
|
431
|
+
"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.",
|
|
382
432
|
"agents: list names, descriptions, default models and source for this cwd; use these names for run.",
|
|
383
|
-
"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'. follow-up continues a sealed call as generation g+1 or queues after a running turn; 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.",
|
|
384
|
-
"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; status lists lease holders and waiters). status: without wid, what runs, 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, 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 (versionNote when it differs from the loaded one); wid: one workflow, outputs clipped; wid+key: one call's full result; full:true: everything. A run's rid from {submitted:{rid}} works wherever a wid is expected. revise wid + workflow/source/args starts a revision.",
|
|
433
|
+
"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 or queues after a running turn; 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.",
|
|
434
|
+
"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, 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 (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.",
|
|
385
435
|
"Control replies are {applied:true,rid} or {applied:false,reason,rid} when decided; otherwise {submitted:{rid}} after 10s.",
|
|
386
436
|
...(agents ? [`Available agents: ${agents}.`] : []),
|
|
387
437
|
"User sees a summary line above the editor; ↓ on an empty editor (or /subagents) opens the list, Enter watches live OR finished calls (finished transcripts remain on disk) and expands finished workflows. List keys: s steer (paste-capable input), x stop (confirm y), m model, a answer when asked, f follow-up on finished calls; action feedback appears in footer.",
|
package/dist/cli/doctor.js
CHANGED
|
@@ -9,7 +9,8 @@ import { reduceLifecycle } from "../kernel/lifecycle.js";
|
|
|
9
9
|
import { scanInbox } from "../kernel/mailbox.js";
|
|
10
10
|
import { OsLock } from "../platform/lock.js";
|
|
11
11
|
import { journalPath, orchInbox, orchLedger, orchLock } from "../paths.js";
|
|
12
|
-
import { snapshotFromEntries } from "../orchestrator/snapshot.js";
|
|
12
|
+
import { runningStats, snapshotFromEntries } from "../orchestrator/snapshot.js";
|
|
13
|
+
import { statsLine } from "../orchestrator/stats.js";
|
|
13
14
|
import { diskUsage } from "../orchestrator/store.js";
|
|
14
15
|
import { JT, isEntry } from "../types.js";
|
|
15
16
|
import { serviceFiles } from "./service.js";
|
|
@@ -48,7 +49,7 @@ export async function doctor(home, env = process.env, now = Date.now()) {
|
|
|
48
49
|
const ledger = readJournalSnapshot(orchLedger(home));
|
|
49
50
|
const pruned = new Set(ledger.filter(e => e.type === "pruned").map(e => String(e.wid)));
|
|
50
51
|
const report = { home, bytes: await diskUsage(home), workflows: {}, ledger: { entries: ledger.length, bytes: await diskUsage(orchLedger(home)) },
|
|
51
|
-
largestJournals: [], parked: [], attention: [], fenceFailed: [], orphanStaging: [], tmpFiles: [], orchestrator: await lockHeld(home), service: "unavailable", findings: [] };
|
|
52
|
+
largestJournals: [], parked: [], attention: [], fenceFailed: [], orphanStaging: [], tmpFiles: [], orchestrator: await lockHeld(home), service: "unavailable", findings: [], ...runningStats(home) };
|
|
52
53
|
const journals = [];
|
|
53
54
|
for (const wid of (await names(join(home, "w"))).filter(n => !n.startsWith(".") && !pruned.has(n)).sort()) {
|
|
54
55
|
const entries = readJournalSnapshot(journalPath(home, wid)), snap = snapshotFromEntries(wid, entries);
|
|
@@ -140,7 +141,7 @@ export function renderDoctor(r) {
|
|
|
140
141
|
...list("unresolved fence failures", r.fenceFailed, f => `${f.wid} ${f.exec} ${age(f.ageMs)}`),
|
|
141
142
|
...list("orphan staging", r.orphanStaging, s => s),
|
|
142
143
|
...list("leftover tmp files", r.tmpFiles, s => s),
|
|
143
|
-
`orchestrator: ${r.orchestrator === "running" ? "running (holds the lock)" : r.orchestrator}`,
|
|
144
|
+
`orchestrator: ${r.orchestrator === "running" ? "running (holds the lock)" : r.orchestrator}${r.orchestratorStats ? `; ${statsLine(r.orchestratorStats)}` : ""}`,
|
|
144
145
|
`service: ${r.service}`,
|
|
145
146
|
...(r.findings.length ? [`${r.findings.length} actionable finding(s):`, ...r.findings.flatMap(f => [` ${f.kind}: ${f.detail}`, ` ${f.command}`])] : ["nothing actionable"]),
|
|
146
147
|
].join("\n");
|
|
@@ -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,13 +1,14 @@
|
|
|
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
|
-
// group, then releases.
|
|
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.
|
|
4
5
|
import { spawn } from "node:child_process";
|
|
5
6
|
import { watch } from "node:fs";
|
|
6
7
|
import { constants } from "node:os";
|
|
7
8
|
import { dsaHome } from "../paths.js";
|
|
8
9
|
import { captureStart } from "../platform/proctable.js";
|
|
9
|
-
import { blockers, enqueue, groupAlive, leaseDir, liveTickets, orphaned, removeTicket, RESOURCE, who, writeTicket } from "../platform/lease.js";
|
|
10
|
-
export const HOLD_USAGE = "usage: pi-durable-subagents hold <resource> [--shared] [--max-wait <seconds>] [--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…]";
|
|
11
12
|
/** Exit status when --max-wait expires before the lease is granted (EX_TEMPFAIL). */
|
|
12
13
|
export const WAIT_EXPIRED = 75;
|
|
13
14
|
export function parseHold(args) {
|
|
@@ -15,17 +16,24 @@ export function parseHold(args) {
|
|
|
15
16
|
if (split < 0)
|
|
16
17
|
throw new Error(`hold needs -- before the command. ${HOLD_USAGE}`);
|
|
17
18
|
const opts = args.slice(0, split), argv = args.slice(split + 1);
|
|
18
|
-
let resource,
|
|
19
|
+
let resource, shared = false, slots, maxWaitMs, note;
|
|
19
20
|
for (let i = 0; i < opts.length; i++) {
|
|
20
21
|
const a = opts[i];
|
|
21
22
|
if (a === "--shared")
|
|
22
|
-
|
|
23
|
-
else if (a === "--
|
|
23
|
+
shared = true;
|
|
24
|
+
else if (a === "--no-wait")
|
|
25
|
+
maxWaitMs = 0;
|
|
26
|
+
else if (a === "--max-wait" || a === "--note" || a === "--slots") {
|
|
24
27
|
const v = opts[++i];
|
|
25
28
|
if (v === undefined)
|
|
26
29
|
throw new Error(`${a} needs a value. ${HOLD_USAGE}`);
|
|
27
30
|
if (a === "--note")
|
|
28
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
|
+
}
|
|
29
37
|
else {
|
|
30
38
|
const s = Number(v);
|
|
31
39
|
if (!Number.isFinite(s) || s < 0)
|
|
@@ -46,7 +54,10 @@ export function parseHold(args) {
|
|
|
46
54
|
throw new Error(`Invalid resource ${JSON.stringify(resource)}: use 1–64 of A-Z a-z 0-9 . _ -`);
|
|
47
55
|
if (!argv.length)
|
|
48
56
|
throw new Error(`hold needs a command after --. ${HOLD_USAGE}`);
|
|
49
|
-
|
|
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 };
|
|
50
61
|
}
|
|
51
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`;
|
|
52
63
|
const SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"];
|
|
@@ -54,13 +65,21 @@ const SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"];
|
|
|
54
65
|
export async function hold(args, options = {}) {
|
|
55
66
|
const env = options.env ?? process.env, home = dsaHome(env), say = options.stderr ?? (l => process.stderr.write(`${l}\n`));
|
|
56
67
|
const pollMs = options.pollMs ?? 250, graceMs = options.graceMs ?? 2000;
|
|
57
|
-
const
|
|
58
|
-
resource: args.resource, mode: args.mode,
|
|
68
|
+
const request = {
|
|
69
|
+
resource: args.resource, mode: args.mode, ...(args.slots !== undefined ? { slots: args.slots } : {}),
|
|
59
70
|
wrapper: { pid: process.pid, start: (await captureStart(process.pid)) || undefined },
|
|
60
71
|
argv: args.argv.map(a => a.length > 200 ? `${a.slice(0, 199)}…` : a).slice(0, 32), cwd: process.cwd(),
|
|
61
72
|
...(args.note ? { note: args.note.slice(0, 300) } : {}), since: Date.now(),
|
|
62
73
|
...(env.DSA_EXEC ? { exec: env.DSA_EXEC } : {}), ...(env.DSA_CALL ? { call: env.DSA_CALL } : {}),
|
|
63
|
-
}
|
|
74
|
+
};
|
|
75
|
+
// No wait: granted now, or refused without a ticket — never listed as a waiter, even for a moment.
|
|
76
|
+
const granted = args.maxWaitMs === 0 ? await tryGrant(home, request) : undefined;
|
|
77
|
+
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(", ");
|
|
79
|
+
say(`hold: ${args.resource} is not free now (${by}); not running the command (exit ${WAIT_EXPIRED})`);
|
|
80
|
+
return WAIT_EXPIRED;
|
|
81
|
+
}
|
|
82
|
+
const ticket = granted ?? await enqueue(home, request);
|
|
64
83
|
// Signals: while waiting they withdraw the request; while the command runs they go to its process group.
|
|
65
84
|
let child, interrupted, wake = () => { };
|
|
66
85
|
const onSignal = (signal) => {
|
|
@@ -88,12 +107,13 @@ export async function hold(args, options = {}) {
|
|
|
88
107
|
catch { /* polling suffices */ }
|
|
89
108
|
let shown;
|
|
90
109
|
const ended = new Map();
|
|
91
|
-
|
|
110
|
+
// A ticket granted under the lock (no wait) runs at once; only a queued one waits.
|
|
111
|
+
while (ticket.grantedAt === undefined) {
|
|
92
112
|
if (interrupted) {
|
|
93
113
|
removeTicket(home, ticket);
|
|
94
114
|
return 128 + (constants.signals[interrupted] ?? 1);
|
|
95
115
|
}
|
|
96
|
-
const
|
|
116
|
+
const all = liveTickets(home, args.resource), ahead = blockers(ticket, all);
|
|
97
117
|
if (!ahead.length)
|
|
98
118
|
break;
|
|
99
119
|
const now = Date.now();
|
|
@@ -115,17 +135,22 @@ export async function hold(args, options = {}) {
|
|
|
115
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})`);
|
|
116
136
|
return WAIT_EXPIRED;
|
|
117
137
|
}
|
|
118
|
-
|
|
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}` : ""}`;
|
|
119
142
|
if (key !== shown) {
|
|
120
143
|
shown = key;
|
|
121
|
-
const by =
|
|
122
|
-
say(
|
|
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`);
|
|
123
148
|
}
|
|
124
149
|
await new Promise(resolve => { const timer = setTimeout(resolve, pollMs); wake = () => { clearTimeout(timer); resolve(); }; });
|
|
125
150
|
}
|
|
126
151
|
watcher?.close();
|
|
127
152
|
watcher = undefined;
|
|
128
|
-
ticket.grantedAt
|
|
153
|
+
ticket.grantedAt ??= Date.now();
|
|
129
154
|
await writeTicket(home, ticket);
|
|
130
155
|
if (interrupted) {
|
|
131
156
|
removeTicket(home, ticket);
|