pi-durable-subagents 1.0.45 → 1.2.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.
- package/CHANGELOG.md +116 -0
- package/README.md +297 -26
- package/dist/agent/child/schema.js +53 -0
- package/dist/agent/child.js +23 -6
- package/dist/agent/main/snapshots.js +2 -2
- package/dist/agent/main.js +2 -2
- package/dist/cli/hold.js +85 -80
- package/dist/cli/main.js +9 -3
- package/dist/cli/requests.js +54 -18
- package/dist/orchestrator/config.js +4 -2
- package/dist/orchestrator/engine.js +160 -13
- package/dist/orchestrator/executor/command.js +7 -0
- package/dist/orchestrator/executor/digest.js +3 -3
- package/dist/orchestrator/executor/ended.js +23 -0
- package/dist/orchestrator/executor/index.js +27 -11
- package/dist/orchestrator/executor/sweep.js +5 -1
- package/dist/orchestrator/model-choice.js +17 -0
- package/dist/orchestrator/reader-ledger.js +65 -5
- package/dist/orchestrator/settled.js +2 -0
- package/dist/orchestrator/snapshot.js +62 -6
- package/dist/orchestrator/store.js +4 -4
- package/dist/platform/cmdline.js +16 -0
- package/dist/platform/containment.js +34 -0
- package/dist/platform/lease.js +91 -44
- package/dist/platform/proctable.js +43 -5
- package/dist/requests.js +1 -1
- package/dist/types.js +12 -0
- package/package.json +1 -1
|
@@ -1,7 +1,60 @@
|
|
|
1
|
+
import { ASK_FIELDS } from "../../types.js";
|
|
1
2
|
import { isDeepStrictEqual } from 'node:util';
|
|
2
3
|
const keywords = new Set(['type', 'enum', 'items', 'properties', 'required', 'additionalProperties', 'description', 'title']);
|
|
3
4
|
const types = new Set(['null', 'boolean', 'object', 'array', 'number', 'integer', 'string']);
|
|
4
5
|
const isObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
|
|
6
|
+
/** AK2: validate before creating a question, revision or waiter. No coercion. */
|
|
7
|
+
export function askProblem(value, requireDecision = false) {
|
|
8
|
+
if (!isObject(value))
|
|
9
|
+
return 'ask refused: arguments must be an object';
|
|
10
|
+
const structured = ASK_FIELDS.some(key => Object.hasOwn(value, key));
|
|
11
|
+
if ((structured || requireDecision) && (value.decision_needed === undefined || typeof value.decision_needed === 'string' && !value.decision_needed.trim()))
|
|
12
|
+
return 'ask refused: decision_needed is required (one sentence naming the decision you need), then options';
|
|
13
|
+
const string = (v, at) => typeof v !== 'string' ? `${at} must be a string` : v.length > 2000 ? `${at} exceeds 2000 characters` : undefined;
|
|
14
|
+
const list = (v, at, max, item) => {
|
|
15
|
+
if (!Array.isArray(v))
|
|
16
|
+
return `${at} must be an array`;
|
|
17
|
+
if (v.length > max)
|
|
18
|
+
return `${at} exceeds ${max} items`;
|
|
19
|
+
for (const [i, entry] of v.entries()) {
|
|
20
|
+
const problem = item(entry, `${at}[${i}]`);
|
|
21
|
+
if (problem)
|
|
22
|
+
return problem;
|
|
23
|
+
}
|
|
24
|
+
};
|
|
25
|
+
let problem = typeof value.question !== 'string' || structured || requireDecision ? string(value.question, 'question') : undefined;
|
|
26
|
+
if (!problem && Object.hasOwn(value, 'decision_needed'))
|
|
27
|
+
problem = string(value.decision_needed, 'decision_needed');
|
|
28
|
+
for (const key of ['facts', 'tried'])
|
|
29
|
+
if (!problem && Object.hasOwn(value, key))
|
|
30
|
+
problem = list(value[key], key, 20, string);
|
|
31
|
+
if (!problem && Object.hasOwn(value, 'options')) {
|
|
32
|
+
problem = list(value.options, 'options', 9, (v, at) => {
|
|
33
|
+
if (!isObject(v))
|
|
34
|
+
return `${at} must be an object`;
|
|
35
|
+
let p = string(v.label, `${at}.label`);
|
|
36
|
+
for (const key of ['scope', 'cost', 'risk'])
|
|
37
|
+
if (!p && Object.hasOwn(v, key))
|
|
38
|
+
p = string(v[key], `${at}.${key}`);
|
|
39
|
+
if (!p && Object.hasOwn(v, 'preferred') && typeof v.preferred !== 'boolean')
|
|
40
|
+
p = `${at}.preferred must be a boolean`;
|
|
41
|
+
return p;
|
|
42
|
+
});
|
|
43
|
+
if (!problem && value.options.filter(o => o.preferred).length > 1)
|
|
44
|
+
problem = 'at most one option may be preferred';
|
|
45
|
+
}
|
|
46
|
+
if (!problem && Object.hasOwn(value, 'classification_candidates'))
|
|
47
|
+
problem = list(value.classification_candidates, 'classification_candidates', 9, (v, at) => {
|
|
48
|
+
if (!isObject(v))
|
|
49
|
+
return `${at} must be an object`;
|
|
50
|
+
let p = string(v.label, `${at}.label`);
|
|
51
|
+
for (const key of ['evidence', 'unproven'])
|
|
52
|
+
if (!p && Object.hasOwn(v, key))
|
|
53
|
+
p = list(v[key], `${at}.${key}`, Infinity, string);
|
|
54
|
+
return p;
|
|
55
|
+
});
|
|
56
|
+
return problem ? `ask refused: ${problem}` : undefined;
|
|
57
|
+
}
|
|
5
58
|
/** P24, T4: List unsupported keywords and malformed shapes so a schema that would not constrain fails loudly. */
|
|
6
59
|
export function schemaProblems(schema, path = '$') {
|
|
7
60
|
if (typeof schema === 'boolean')
|
package/dist/agent/child.js
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
import fs, { watch } from 'node:fs';
|
|
2
2
|
import { readFile } from 'node:fs/promises';
|
|
3
3
|
import { Type } from '@earendil-works/pi-ai';
|
|
4
|
-
import { ASK_CUT, CT, ENV, JT } from "../types.js";
|
|
4
|
+
import { ASK_CUT, CT, ENV, JT, askFields } from "../types.js";
|
|
5
5
|
import { readJournalSnapshot } from "../kernel/journal.js";
|
|
6
6
|
import { scanInbox } from "../kernel/mailbox.js";
|
|
7
7
|
import { contentHash } from "../kernel/ids.js";
|
|
8
8
|
import { planDecisions } from "../kernel/lifecycle.js";
|
|
9
9
|
import { openness } from "../kernel/guards.js";
|
|
10
10
|
import { recover } from "./child/history.js";
|
|
11
|
-
import { validate } from "./child/schema.js";
|
|
11
|
+
import { askProblem, validate } from "./child/schema.js";
|
|
12
12
|
import { catalogModel, parseModel, sameModel } from "../compat/model.js";
|
|
13
13
|
import { registerLive } from "./child/live.js";
|
|
14
14
|
const MESSAGES = ['task', 'steer', 'notify', 'follow-up', 'continue'];
|
|
@@ -45,6 +45,7 @@ export function usage(entries, call) {
|
|
|
45
45
|
}
|
|
46
46
|
/** P4, P8, P23, P24: Consume the child mailbox at serialized pi boundaries, retaining native session receipts. */
|
|
47
47
|
export function registerChild(pi) {
|
|
48
|
+
const requireDecision = process.env[ENV.askRequireDecision] === 'true';
|
|
48
49
|
let target = process.env[ENV.model];
|
|
49
50
|
const exec = process.env[ENV.exec], call = process.env[ENV.call], inbox = process.env[ENV.inbox], journal = process.env[ENV.journal];
|
|
50
51
|
let active = false, watcher, queue = Promise.resolve();
|
|
@@ -360,9 +361,25 @@ export function registerChild(pi) {
|
|
|
360
361
|
await queue;
|
|
361
362
|
});
|
|
362
363
|
pi.registerTool({
|
|
363
|
-
name: 'ask', label: 'Ask supervisor', description: 'Ask a question and wait for an answer or steering message.',
|
|
364
|
-
parameters: Type.Object({
|
|
365
|
-
|
|
364
|
+
name: 'ask', label: 'Ask supervisor', description: 'Ask a question and wait for an answer or steering message. State the decision you need (one sentence) in decision_needed, list numbered options with scope/cost/risk and at most one preferred option. Give facts (commit, run id, log sha), what you tried, and candidate explanations with evidence and what is unproven. Every string is at most 2000 characters; options and classification_candidates at most 9, facts and tried at most 20.',
|
|
365
|
+
parameters: Type.Object({
|
|
366
|
+
question: Type.String(), decision_needed: Type.Optional(Type.String()),
|
|
367
|
+
options: Type.Optional(Type.Array(Type.Object({ label: Type.String(), scope: Type.Optional(Type.String()), cost: Type.Optional(Type.String()), risk: Type.Optional(Type.String()), preferred: Type.Optional(Type.Boolean()) }))),
|
|
368
|
+
facts: Type.Optional(Type.Array(Type.String())), tried: Type.Optional(Type.Array(Type.String())),
|
|
369
|
+
classification_candidates: Type.Optional(Type.Array(Type.Object({ label: Type.String(), evidence: Type.Optional(Type.Array(Type.String())), unproven: Type.Optional(Type.Array(Type.String())) }))),
|
|
370
|
+
}), executionMode: 'sequential', exposure: 'model-only',
|
|
371
|
+
// pi validates the schema before execute; reject raw malformed arguments here without coercion as well.
|
|
372
|
+
prepareArguments(args) {
|
|
373
|
+
const problem = askProblem(args, requireDecision);
|
|
374
|
+
if (problem)
|
|
375
|
+
throw new Error(problem);
|
|
376
|
+
return args;
|
|
377
|
+
},
|
|
378
|
+
async execute(_id, args, signal, _update, ctx) {
|
|
379
|
+
const problem = askProblem(args, requireDecision);
|
|
380
|
+
if (problem)
|
|
381
|
+
throw new Error(problem);
|
|
382
|
+
const { question } = args;
|
|
366
383
|
let resolve, reject;
|
|
367
384
|
const result = new Promise((yes, no) => { resolve = yes; reject = no; });
|
|
368
385
|
// Attach immediately so abort during the queued intake never produces an unhandled rejection.
|
|
@@ -377,7 +394,7 @@ export function registerChild(pi) {
|
|
|
377
394
|
if (blocked)
|
|
378
395
|
throw new Error('Another question is already blocked');
|
|
379
396
|
const qid = contentHash({ exec, question }), rev = (state.questions.get(qid)?.rev ?? 0) + 1;
|
|
380
|
-
const q = { qid, rev, question };
|
|
397
|
+
const q = { qid, rev, question, ...askFields(args) };
|
|
381
398
|
state.questions.set(qid, q);
|
|
382
399
|
pi.appendEntry(CT.question, q);
|
|
383
400
|
blocked = { ...q, resolve, reject };
|
|
@@ -4,7 +4,7 @@ import { join } from "node:path";
|
|
|
4
4
|
import { liveCommandCalls } from "../../orchestrator/executor/command.js";
|
|
5
5
|
import { forgetJournalSnapshot, journalAppends, readJournalFold, readJournalSnapshot, readJournalUncached } from "../../kernel/journal.js";
|
|
6
6
|
import { journalPath } from "../../paths.js";
|
|
7
|
-
import { CT, JT } from "../../types.js";
|
|
7
|
+
import { CT, JT, askText } from "../../types.js";
|
|
8
8
|
import { openGeneration, readerWorkflowListing, releaseLoadedSettledJournals, releaseSettledJournals, SETTLED_RECHECK_MS, unresolvedAttention, workflowDigest, workflowDigestChecked } from "../../orchestrator/snapshot.js";
|
|
9
9
|
import { readerHold, readerLedgerIdentity } from "../../orchestrator/reader-ledger.js";
|
|
10
10
|
/** Session-outbox reader: retain only pending identities and a verified position, not sent envelopes/history. */
|
|
@@ -212,7 +212,7 @@ export function attention(home, sender, seen, fresh = false) {
|
|
|
212
212
|
export function presentText(item) {
|
|
213
213
|
const call = item.call ? item.call.replace(/@\d+\/([^@/]+)@\d+$/, "/$1") : undefined, where = call ?? item.wid;
|
|
214
214
|
if (item.kind === "question" && call)
|
|
215
|
-
return `Question from ${call}${item.qid ? ` (qid ${item.qid})` : ""}; reply with send kind:"answer" to:"${call}": ${item.text}`;
|
|
215
|
+
return `Question from ${call}${item.qid ? ` (qid ${item.qid})` : ""}; reply with send kind:"answer" to:"${call}": ${askText(item, item.text)}`;
|
|
216
216
|
return item.text.includes(item.wid) ? item.text : `${where}: ${item.text}`;
|
|
217
217
|
}
|
|
218
218
|
/** Resolutions recorded in one immutable journal snapshot, keyed by id and rev. */
|
package/dist/agent/main.js
CHANGED
|
@@ -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, commandSendRefusal, isCommandTarget, 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, statusText, 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";
|
|
@@ -444,7 +444,7 @@ export function registerMain(pi, ui) {
|
|
|
444
444
|
].join("\n"), parameters,
|
|
445
445
|
async execute(_id, args, signal, _update, context) {
|
|
446
446
|
const value = await submit(args, context.cwd, signal);
|
|
447
|
-
return { content: [{ type: "text", text: JSON.stringify(value) }], details: value };
|
|
447
|
+
return { content: [{ type: "text", text: args.action === 'status' ? statusText(home, value) : JSON.stringify(value) }], details: value };
|
|
448
448
|
},
|
|
449
449
|
}));
|
|
450
450
|
}
|
package/dist/cli/hold.js
CHANGED
|
@@ -1,15 +1,13 @@
|
|
|
1
|
-
//
|
|
2
|
-
//
|
|
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,
|
|
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
|
|
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 (
|
|
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 } : {}), ...(
|
|
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
|
|
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)} (${
|
|
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
|
-
|
|
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
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
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
|
-
|
|
139
|
-
const
|
|
140
|
-
const
|
|
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 =
|
|
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 ${
|
|
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
|
|
163
|
+
await pause();
|
|
150
164
|
}
|
|
151
|
-
|
|
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
|
-
//
|
|
162
|
-
const c = spawn(args.argv[0], args.argv.slice(1), { stdio: [process.stdin.isTTY ? "ignore" : "inherit", "inherit", "inherit"], detached: true,
|
|
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
|
|
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
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
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
|
-
|
|
195
|
+
await pause();
|
|
198
196
|
}
|
|
199
|
-
removeTicket(home, ticket);
|
|
200
197
|
return status;
|
|
201
198
|
}
|
|
202
199
|
finally {
|
|
203
200
|
watcher?.close();
|
|
204
|
-
|
|
205
|
-
|
|
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
|
@@ -17,6 +17,8 @@ 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";
|
|
21
|
+
import { askText } from "../types.js";
|
|
20
22
|
const commands = ["smoke", "tail", "status", "events", "start", "resume", "drain", "stop", "stop-all", "prune", "restart", "leases", "doctor", "install-service", "uninstall-service", "help"];
|
|
21
23
|
/** P25: Reject ambiguous CLI arguments before any durable action. */
|
|
22
24
|
export function parseArgs(args) {
|
|
@@ -126,7 +128,7 @@ export function renderStatus(wf) {
|
|
|
126
128
|
const last = c.result?.output?.split("\n").map(l => l.trim()).filter(Boolean).at(-1), err = c.result?.error;
|
|
127
129
|
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)}`;
|
|
128
130
|
}),
|
|
129
|
-
...wf.attention.map(a => ` ${a.kind}: ${JSON.stringify(clip(a.text, 300))}`),
|
|
131
|
+
...wf.attention.map(a => ` ${a.kind}: ${JSON.stringify(a.decision_needed === undefined ? clip(a.text, 300) : askText(a, a.text))}`),
|
|
130
132
|
...(wf.scriptLog ? [` script log: ${wf.scriptLog}`] : [])].join("\n");
|
|
131
133
|
}
|
|
132
134
|
/** `status <wid> --tail/--grep`: the workflow line, then each call with its selected output lines. */
|
|
@@ -138,7 +140,7 @@ export function renderSelected(wf) {
|
|
|
138
140
|
export function renderView(view) {
|
|
139
141
|
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)}` : ""}`,
|
|
140
142
|
...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)}`),
|
|
141
|
-
...w.attention.map(a => ` ${a.kind}: ${JSON.stringify(a.text.split("\n")[0])}`)].join("\n"));
|
|
143
|
+
...w.attention.map(a => ` ${a.kind}: ${JSON.stringify(a.decision_needed === undefined ? a.text.split("\n")[0] : askText(a, a.text))}`)].join("\n"));
|
|
142
144
|
if (view.paused)
|
|
143
145
|
lines.unshift(`${view.paused} (pi-durable-subagents resume)`);
|
|
144
146
|
if (view.olderFinished)
|
|
@@ -182,7 +184,7 @@ export function serviceEntryError(entry) {
|
|
|
182
184
|
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.`;
|
|
183
185
|
return undefined;
|
|
184
186
|
}
|
|
185
|
-
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]";
|
|
187
|
+
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]";
|
|
186
188
|
/** Restart: the orchestrator exits when no execution runs (or `force`) and the installed version takes over. */
|
|
187
189
|
async function restartCommand(home, env, write, options) {
|
|
188
190
|
const body = { ...(typeof options.force === "string" ? { token: options.force } : options.force === true ? { force: true } : {}), ...(options.reason !== undefined ? { reason: options.reason } : {}), initiator: cliInitiator(env) };
|
|
@@ -238,6 +240,10 @@ async function restartCommand(home, env, write, options) {
|
|
|
238
240
|
}
|
|
239
241
|
/** P1, P21, P25, P38: Dispatch the public CLI using durable requests and read-only snapshots. */
|
|
240
242
|
export async function main(args = process.argv.slice(2), options = {}) {
|
|
243
|
+
if (args.length === 1 && (args[0] === "version" || args[0] === "--version")) {
|
|
244
|
+
(options.write ?? console.log)(`pi-durable-subagents ${packageVersion()}`);
|
|
245
|
+
return 0;
|
|
246
|
+
}
|
|
241
247
|
if (args[0] === "hold") {
|
|
242
248
|
const { hold, parseHold } = await import("./hold.js");
|
|
243
249
|
return hold(parseHold(args.slice(1)), { env: options.env ?? process.env });
|