pi-durable-subagents 1.0.45 → 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.
- package/CHANGELOG.md +66 -0
- package/README.md +165 -20
- package/dist/cli/hold.js +85 -80
- package/dist/cli/main.js +6 -1
- package/dist/cli/requests.js +51 -15
- package/dist/orchestrator/engine.js +113 -6
- package/dist/orchestrator/executor/command.js +7 -0
- package/dist/orchestrator/executor/ended.js +23 -0
- package/dist/orchestrator/executor/index.js +19 -5
- package/dist/orchestrator/executor/sweep.js +5 -1
- package/dist/orchestrator/reader-ledger.js +65 -5
- package/dist/orchestrator/settled.js +2 -0
- package/dist/orchestrator/snapshot.js +18 -2
- 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/package.json +1 -1
|
@@ -10,7 +10,7 @@ import { digestDir, journalPath, pinnedDir, workflowDir } from "../paths.js";
|
|
|
10
10
|
import { JT, attentionEntries, isEntry } from "../types.js";
|
|
11
11
|
import { parseModel, resolveModel } from "../compat/model.js";
|
|
12
12
|
import {} from "./ledger.js";
|
|
13
|
-
import { readerHold, readerLedger, readerLedgerIdentity } from "./reader-ledger.js";
|
|
13
|
+
import { awaitingRuns, readerHold, readerLedger, readerLedgerIdentity } from "./reader-ledger.js";
|
|
14
14
|
import { packageVersion } from "../version.js";
|
|
15
15
|
import { worktreeCalls, worktreeLabel } from "./executor/worktree.js";
|
|
16
16
|
import { leaseCalls, leaseLines, leaseState } from "../platform/lease.js";
|
|
@@ -148,6 +148,7 @@ function snapshotReducer(wid, entries) {
|
|
|
148
148
|
// P31: usage per call id, deduplicated by message id; a seal carries the authoritative total.
|
|
149
149
|
const live = new Map(), sealedUsage = new Map(), seen = new Set();
|
|
150
150
|
const tools = new Map();
|
|
151
|
+
const endedAtSeal = new Map();
|
|
151
152
|
// P7, P27: forward / forward-delivered / forward-retired, by destination call; retirements carry only rid2.
|
|
152
153
|
const sends = new Map(), byRid2 = new Map();
|
|
153
154
|
// Pending notes of the current revision by key (notes.ts): recorded rids, and those a generation carried.
|
|
@@ -349,6 +350,10 @@ function snapshotReducer(wid, entries) {
|
|
|
349
350
|
total.costUsd += u.costUsd;
|
|
350
351
|
live.set(String(e.call), total);
|
|
351
352
|
}
|
|
353
|
+
else if (isEntry(e, 'ended')) {
|
|
354
|
+
const prior = endedAtSeal.get(e.call), procs = [...(prior?.procs ?? []), ...e.procs];
|
|
355
|
+
endedAtSeal.set(e.call, { procs: procs.slice(0, 20), more: (prior?.more ?? 0) + Math.max(0, procs.length - 20) + (e.more ?? 0) });
|
|
356
|
+
}
|
|
352
357
|
else if (e.type === JT.sealed) {
|
|
353
358
|
const usage = e.result?.usage;
|
|
354
359
|
if (usage)
|
|
@@ -425,6 +430,11 @@ function snapshotReducer(wid, entries) {
|
|
|
425
430
|
if (c.phase !== "sealed" && c.phase !== "queued")
|
|
426
431
|
delete c.poolWait;
|
|
427
432
|
counts[c.phase]++;
|
|
433
|
+
const ended = endedAtSeal.get(c.callId);
|
|
434
|
+
if (ended?.procs.length)
|
|
435
|
+
c.endedAtSeal = structuredClone(ended.procs);
|
|
436
|
+
if (ended?.more)
|
|
437
|
+
c.endedAtSealMore = ended.more;
|
|
428
438
|
const usage = usageOf(c.callId);
|
|
429
439
|
if (usage)
|
|
430
440
|
c.usage = { ...usage };
|
|
@@ -550,6 +560,9 @@ const digests = new Map();
|
|
|
550
560
|
const FINAL_STATUS = new Set(["done", "failed", "stopped"]);
|
|
551
561
|
/** Post-seal/recovery work that can append without a new request must not enter a polling trust window. */
|
|
552
562
|
export function pendingRecovery(wid, entries) {
|
|
563
|
+
const rev = entries.filter(e => e.type === JT.done).length;
|
|
564
|
+
if (entries.some(e => e.type === 'wf-created' && e.wake) && !entries.some(e => e.type === 'wake-outcome' && e.rev === rev))
|
|
565
|
+
return true;
|
|
553
566
|
const start = entries.findLastIndex(e => e.type === "revised"), current = start < 0 ? entries : entries.slice(start);
|
|
554
567
|
const consumed = new Set(current.filter(e => e.type === "generation").flatMap(generationRids));
|
|
555
568
|
const retiredForwards = new Map(entries.filter(e => e.type === "forward-retired").map(e => [String(e.rid2), e]));
|
|
@@ -1274,6 +1287,8 @@ export function versionNote(running, loaded) {
|
|
|
1274
1287
|
}
|
|
1275
1288
|
/** The first version whose orchestrator and child know send kind "notify". */
|
|
1276
1289
|
export const NOTIFY_SINCE = "1.0.28";
|
|
1290
|
+
/** The first orchestrator version that delivers run --wake caller. */
|
|
1291
|
+
export const WAKE_SINCE = "1.1.0";
|
|
1277
1292
|
/** A refusal when the orchestrator running now predates `since` and is older than the version this process loaded (an
|
|
1278
1293
|
* older orchestrator would accept the request and its child would drop it); none when none runs (the next one starts
|
|
1279
1294
|
* on the installed version) or it is current. */
|
|
@@ -1475,7 +1490,8 @@ export function statusDetail(home, wid) {
|
|
|
1475
1490
|
if (!origin.has(wid))
|
|
1476
1491
|
throw new Error(prunedIds(home).has(wid) ? `Workflow ${wid} was pruned` : `Unknown workflow: ${wid}`);
|
|
1477
1492
|
const held = heldWorkflows(home), wf = labelled(workflowSnapshot(home, wid), held.labels(wid), held.session(wid)), log = scriptLogPath(home, wid);
|
|
1478
|
-
|
|
1493
|
+
const calls = wf.calls.map(c => { const awaiting = awaitingRuns(home, wid, c.key, wf.rev); return awaiting ? { ...c, awaiting } : c; });
|
|
1494
|
+
return { ...wf, calls, ...(wf.origin === undefined && origin.get(wid) !== undefined ? { origin: origin.get(wid) } : {}), ...(existsSync(log) ? { scriptLog: log } : {}),
|
|
1479
1495
|
...(isLive(wf) && held.held(wid) ? { paused: true } : {}) };
|
|
1480
1496
|
}
|
|
1481
1497
|
/** P25, T10: Project a workflow journal into meaningful events (no observations, time or tracking). */
|
|
@@ -375,7 +375,7 @@ export class Store {
|
|
|
375
375
|
async create(req) {
|
|
376
376
|
let intent = this.index().createByRid.get(req.rid);
|
|
377
377
|
intent ??= await this.ledgers.orch.append('create-intent', { rid: req.rid, wid: ulid(), origin: req.from, cwd: req.body.cwd,
|
|
378
|
-
...(req.body.name !== undefined ? { name: req.body.name } : {}), snapshot: await this.reference(req.rid) });
|
|
378
|
+
...(req.body.name !== undefined ? { name: req.body.name } : {}), ...(req.body.wake ? { wake: { rid: req.rid, to: req.body.wake.to, caller: req.body.caller } } : {}), snapshot: await this.reference(req.rid) });
|
|
379
379
|
return this.materialize(intent);
|
|
380
380
|
}
|
|
381
381
|
/** P14, A5: Bind the next revision before retiring any old authority. */
|
|
@@ -627,7 +627,7 @@ export class Store {
|
|
|
627
627
|
try {
|
|
628
628
|
const current = settled.revised ?? intent, files = await this.pinnedFiles(wid, settled.revision, current, false);
|
|
629
629
|
const facts = { revision: settled.revision, ...(settled.revised ? { revised: settled.revised } : {}), done: settled.done, resumed: settled.resumed, quiet: settled.quiet, calls: settled.calls, sweep: settled.sweep };
|
|
630
|
-
const wf = { wid, revision: settled.revision, origin: intent.origin, cwd: intent.cwd, journal: lazy, ...files, settled: facts };
|
|
630
|
+
const wf = { wid, revision: settled.revision, origin: intent.origin, cwd: intent.cwd, journal: lazy, ...files, settled: facts, ...(intent.wake ? { wake: intent.wake } : {}) };
|
|
631
631
|
this.releasePins(wf);
|
|
632
632
|
this.unverified.set(wid, current);
|
|
633
633
|
lazy.onAppend = () => this.appended?.(wid);
|
|
@@ -655,7 +655,7 @@ export class Store {
|
|
|
655
655
|
// terminalEntry over the whole journal: a `revised` after the last done supersedes it, as in the revision's view.
|
|
656
656
|
const ended = !first && entries.length > 0 && terminalEntry(entries) !== undefined;
|
|
657
657
|
const files = first ?? (ended ? await this.pinnedFiles(wid, revision, current, false) : await this.pinnedFiles(wid, 1, intent));
|
|
658
|
-
wf = { wid, revision: ended ? revision : 1, origin: intent.origin, cwd: intent.cwd, journal, ...files };
|
|
658
|
+
wf = { wid, revision: ended ? revision : 1, origin: intent.origin, cwd: intent.cwd, journal, ...files, ...(intent.wake ? { wake: intent.wake } : {}) };
|
|
659
659
|
if (ended) {
|
|
660
660
|
this.releasePins(wf);
|
|
661
661
|
this.unverified.set(wid, current);
|
|
@@ -669,7 +669,7 @@ export class Store {
|
|
|
669
669
|
this.workflows.set(wid, wf);
|
|
670
670
|
if (!journal.entries().length)
|
|
671
671
|
await journal.append('wf-created', { rid: intent.rid, origin: intent.origin, cwd: intent.cwd, revision: 1,
|
|
672
|
-
...(intent.name !== undefined ? { name: intent.name } : {}) });
|
|
672
|
+
...(intent.name !== undefined ? { name: intent.name } : {}), ...(intent.wake ? { wake: intent.wake } : {}) });
|
|
673
673
|
const revised = journal.entries().findLast(e => e.type === 'revised');
|
|
674
674
|
if (revised && wf.revision !== Number(revised.revision))
|
|
675
675
|
Object.assign(wf, await this.pinnedFiles(wid, Number(revised.revision), revised), { revision: Number(revised.revision) });
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { execFile } from "node:child_process";
|
|
2
|
+
import { readFile } from "node:fs/promises";
|
|
3
|
+
import { promisify } from "node:util";
|
|
4
|
+
import { PS } from "./proctable.js";
|
|
5
|
+
const exec = promisify(execFile);
|
|
6
|
+
/** EX1: A diagnostic argv, never evidence of identity or death. Unreadable processes have an empty command. */
|
|
7
|
+
export async function commandLine(pid, signal) {
|
|
8
|
+
try {
|
|
9
|
+
if (process.platform === "linux")
|
|
10
|
+
return (await readFile(`/proc/${pid}/cmdline`, { encoding: "utf8", signal })).replace(/\0/g, " ").trimEnd().slice(0, 200);
|
|
11
|
+
if (process.platform === "darwin")
|
|
12
|
+
return (await exec(PS, ["-o", "command=", "-p", String(pid)], { signal, timeout: 450, maxBuffer: 1024 * 1024 })).stdout.trim().slice(0, 200);
|
|
13
|
+
}
|
|
14
|
+
catch { /* Diagnostics must not prevent a fence. */ }
|
|
15
|
+
return "";
|
|
16
|
+
}
|
|
@@ -104,6 +104,7 @@ export class Containment {
|
|
|
104
104
|
if (!Number.isFinite(timeout) || timeout < 0)
|
|
105
105
|
throw new Error("Invalid fence timeout");
|
|
106
106
|
const deadline = performance.now() + timeout;
|
|
107
|
+
let recordingMs = 500;
|
|
107
108
|
const known = new Map(tracked.filter(p => p.start !== "").map(p => [identity(p), p]));
|
|
108
109
|
for (;;) {
|
|
109
110
|
const remaining = deadline - performance.now();
|
|
@@ -119,11 +120,44 @@ export class Containment {
|
|
|
119
120
|
}
|
|
120
121
|
if (performance.now() >= deadline)
|
|
121
122
|
throw new Error(`Fence timeout: ${exec}`);
|
|
123
|
+
const killing = [];
|
|
122
124
|
for (const p of targets) {
|
|
123
125
|
known.set(identity(p), p);
|
|
124
126
|
// C3: the pid may have exited and been reused since the scan; kill only if it still has the scanned start.
|
|
125
127
|
if (p.start !== "" && await captureStart(p.pid) !== p.start)
|
|
126
128
|
continue;
|
|
129
|
+
if (!opts.beforeKill) {
|
|
130
|
+
try {
|
|
131
|
+
process.kill(p.pid, "SIGKILL");
|
|
132
|
+
}
|
|
133
|
+
catch (error) {
|
|
134
|
+
if (error.code !== "ESRCH")
|
|
135
|
+
throw error;
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
else
|
|
139
|
+
killing.push(p);
|
|
140
|
+
}
|
|
141
|
+
if (killing.length && opts.beforeKill && recordingMs > 0) {
|
|
142
|
+
const recordingStarted = performance.now(), controller = new AbortController();
|
|
143
|
+
let timer;
|
|
144
|
+
try {
|
|
145
|
+
await Promise.race([
|
|
146
|
+
Promise.resolve().then(() => opts.beforeKill(killing, controller.signal)),
|
|
147
|
+
new Promise(resolve => { timer = setTimeout(() => { controller.abort(); resolve(); }, recordingMs); }),
|
|
148
|
+
]);
|
|
149
|
+
}
|
|
150
|
+
catch { /* A recording failure must never prevent SIGKILL. */ }
|
|
151
|
+
finally {
|
|
152
|
+
clearTimeout(timer);
|
|
153
|
+
controller.abort();
|
|
154
|
+
recordingMs = Math.max(0, recordingMs - (performance.now() - recordingStarted));
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
for (const p of killing) {
|
|
158
|
+
// Diagnostic I/O was asynchronous: revalidate identity again before signalling.
|
|
159
|
+
if (opts.beforeKill && p.start !== "" && await captureStart(p.pid) !== p.start)
|
|
160
|
+
continue;
|
|
127
161
|
try {
|
|
128
162
|
process.kill(p.pid, "SIGKILL");
|
|
129
163
|
}
|
package/dist/platform/lease.js
CHANGED
|
@@ -1,18 +1,15 @@
|
|
|
1
|
-
// Command-scoped resource leases: `pi-durable-subagents hold <resource> -- <command
|
|
2
|
-
//
|
|
3
|
-
//
|
|
4
|
-
//
|
|
5
|
-
//
|
|
6
|
-
//
|
|
7
|
-
//
|
|
8
|
-
// counted tickets are all granted before it is (FIFO), so counted grants happen one at a time in number order and none
|
|
9
|
-
// can be missed: a grant needs no lock once the ticket exists. A ticket is live while its wrapper or its
|
|
10
|
-
// command (pid + start token) lives, or processes the command left in its group remain; a waiter next in line ends such
|
|
11
|
-
// leftovers of a killed wrapper. Anyone may delete a dead ticket. No orchestrator is involved.
|
|
1
|
+
// Command-scoped resource leases: `pi-durable-subagents hold <resource> -- <command>`.
|
|
2
|
+
// Tickets are numbered under a kernel lock and waiters rank by descending priority, then ascending sequence.
|
|
3
|
+
// Granted incompatible tickets always block; waiting incompatible tickets block only requests behind them in rank.
|
|
4
|
+
// Enqueue and every final check-and-grant share the resource lock: a later higher-priority waiter can now block an
|
|
5
|
+
// earlier request, so the old FIFO lock-free grant argument no longer applies. No lock is held while commands run or
|
|
6
|
+
// their processes are ended. A ticket stays live while its wrapper, command, group or exact DSA_HOLD tag lives;
|
|
7
|
+
// waiters reclaim orphaned command trees before granting the next request. No orchestrator is involved.
|
|
12
8
|
import { chmodSync, mkdirSync, readdirSync, readFileSync, renameSync, statSync, unlinkSync, writeFileSync } from "node:fs";
|
|
13
9
|
import { readFile, unlink, writeFile } from "node:fs/promises";
|
|
14
10
|
import path from "node:path";
|
|
15
11
|
import { OsLock } from "./lock.js";
|
|
12
|
+
import { ProcessTable } from "./proctable.js";
|
|
16
13
|
export const RESOURCE = /^[A-Za-z0-9._-]{1,64}$/;
|
|
17
14
|
export const leasesRoot = (home) => path.join(home, "leases");
|
|
18
15
|
export const leaseDir = (home, resource) => path.join(leasesRoot(home), resource);
|
|
@@ -77,9 +74,9 @@ export function groupAlive(pgid) {
|
|
|
77
74
|
* the original group emptied and the pid was reused. macOS has no start token here: a reused pid that is alive there
|
|
78
75
|
* counts as the command (the lease waits for it), never as leftovers to end.
|
|
79
76
|
*/
|
|
80
|
-
|
|
77
|
+
function leftoverGroup(t) {
|
|
81
78
|
const c = t.command;
|
|
82
|
-
if (!c
|
|
79
|
+
if (!c)
|
|
83
80
|
return false;
|
|
84
81
|
if (process.platform === "linux") {
|
|
85
82
|
try {
|
|
@@ -108,8 +105,49 @@ export function orphaned(t) {
|
|
|
108
105
|
catch { /* the group is gone */ }
|
|
109
106
|
return false;
|
|
110
107
|
}
|
|
111
|
-
|
|
108
|
+
const holdTable = new ProcessTable({ tagName: "DSA_HOLD" });
|
|
109
|
+
export const holdTag = (t) => `${t.resource}:${t.seq}`;
|
|
110
|
+
export const tagged = (t) => holdTable.tagged(holdTag(t));
|
|
111
|
+
/** An orphan may retain its tag even after its leader and entire original process group have gone. */
|
|
112
|
+
export const orphaned = (t) => !alive(t.wrapper) && !alive(t.command) && (leftoverGroup(t) || tagged(t).length > 0);
|
|
113
|
+
/** A ticket is live while its wrapper, command, process group or exact inherited tag can still act. */
|
|
112
114
|
export const live = (t) => alive(t.wrapper) || alive(t.command) || orphaned(t);
|
|
115
|
+
/** End the group and escaped tagged descendants, rescanning for forks. Release is bounded even for unkillable tasks. */
|
|
116
|
+
export async function endLeaseProcesses(t, graceMs, say) {
|
|
117
|
+
const started = Date.now(), until = started + 5000;
|
|
118
|
+
for (;;) {
|
|
119
|
+
const members = tagged(t), group = t.command && (alive(t.command) || leftoverGroup(t));
|
|
120
|
+
const signal = Date.now() - started >= graceMs ? "SIGKILL" : "SIGTERM";
|
|
121
|
+
if (group) {
|
|
122
|
+
try {
|
|
123
|
+
process.kill(-t.command.pid, signal);
|
|
124
|
+
}
|
|
125
|
+
catch { /* gone */ }
|
|
126
|
+
}
|
|
127
|
+
for (const p of members)
|
|
128
|
+
if (alive(p)) {
|
|
129
|
+
try {
|
|
130
|
+
process.kill(p.pid, signal);
|
|
131
|
+
}
|
|
132
|
+
catch { /* gone */ }
|
|
133
|
+
}
|
|
134
|
+
if (!group && !members.length)
|
|
135
|
+
break;
|
|
136
|
+
if (Date.now() >= until) {
|
|
137
|
+
if (members.length)
|
|
138
|
+
say(`hold: ${members.length} processes tagged ${holdTag(t)} survived; releasing`);
|
|
139
|
+
break;
|
|
140
|
+
}
|
|
141
|
+
await new Promise(r => setTimeout(r, 25));
|
|
142
|
+
}
|
|
143
|
+
// /proc listings are not atomic. A final group signal also reaches a newborn missed by the last scan.
|
|
144
|
+
if (t.command && (alive(t.command) || leftoverGroup(t))) {
|
|
145
|
+
try {
|
|
146
|
+
process.kill(-t.command.pid, "SIGKILL");
|
|
147
|
+
}
|
|
148
|
+
catch { /* gone */ }
|
|
149
|
+
}
|
|
150
|
+
}
|
|
113
151
|
/** The tickets of one resource in request order (unreadable or half-written files are skipped). */
|
|
114
152
|
export function readTickets(home, resource) {
|
|
115
153
|
let names;
|
|
@@ -140,20 +178,17 @@ export function liveTickets(home, resource) {
|
|
|
140
178
|
return false;
|
|
141
179
|
});
|
|
142
180
|
}
|
|
143
|
-
/**
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
* granted ticket is never blocked again: later grants (shared, or counted with a larger N) must not take it back. */
|
|
181
|
+
/** Priority is optional for persisted 1.0 tickets. Ties retain the original sequence order. */
|
|
182
|
+
export const rank = (a, b) => (b.priority ?? 0) - (a.priority ?? 0) || a.seq - b.seq;
|
|
183
|
+
/** All incompatible holders, plus incompatible waiters ranked ahead. A grant is never taken back by later grants. */
|
|
147
184
|
export function blockers(t, tickets) {
|
|
148
185
|
if (t.grantedAt !== undefined)
|
|
149
186
|
return [];
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
const granted = tickets.filter(o => o.seq !== t.seq && o.grantedAt !== undefined);
|
|
156
|
-
return granted.length >= (t.slots ?? 1) ? granted : [];
|
|
187
|
+
const others = tickets.filter(o => o.seq !== t.seq);
|
|
188
|
+
const full = t.mode === "counted" && others.filter(o => o.grantedAt !== undefined).length >= (t.slots ?? 1);
|
|
189
|
+
return others.filter(o => o.grantedAt !== undefined
|
|
190
|
+
? t.mode === "exclusive" || o.mode === "exclusive" || full
|
|
191
|
+
: rank(o, t) < 0 && (t.mode !== "shared" || o.mode === "exclusive"));
|
|
157
192
|
}
|
|
158
193
|
/** Write `file` through a temporary file renamed over it; a failed write or rename removes the temporary file (a full
|
|
159
194
|
* disk left empty ones behind). */
|
|
@@ -218,20 +253,16 @@ export function removeTicket(home, t) {
|
|
|
218
253
|
}
|
|
219
254
|
catch { /* already gone */ }
|
|
220
255
|
}
|
|
221
|
-
/** Queue a request
|
|
222
|
-
* later request always sees it. */
|
|
256
|
+
/** Queue a request under the same lock used by queued and no-wait grants. */
|
|
223
257
|
export async function enqueue(home, ticket, lock = new OsLock()) {
|
|
224
258
|
return (await numbered(home, ticket, false, lock));
|
|
225
259
|
}
|
|
226
|
-
/** Take the lease now or not at all
|
|
227
|
-
* blocks it and its ticket is written already granted, or nothing is written and the blockers are returned. A refused
|
|
228
|
-
* request is never visible as a waiter, and a granted one never was one. Granting needs no more than the lock: a later
|
|
229
|
-
* request gets a higher number and waits behind this ticket, and earlier tickets can only disappear. */
|
|
260
|
+
/** Take the lease now or not at all. Refusal never creates a waiter; the synthetic sequence ranks after equal priority. */
|
|
230
261
|
export async function tryGrant(home, ticket, lock = new OsLock()) {
|
|
231
262
|
return numbered(home, ticket, true, lock);
|
|
232
263
|
}
|
|
233
|
-
async function
|
|
234
|
-
const dir = leaseDir(home,
|
|
264
|
+
async function locked(home, resource, lock, action) {
|
|
265
|
+
const dir = leaseDir(home, resource);
|
|
235
266
|
mkdirSync(dir, { recursive: true });
|
|
236
267
|
let handle = await lock.tryAcquire(path.join(dir, ".lock"));
|
|
237
268
|
for (let delay = 5; !handle; delay = Math.min(delay * 2, 100)) {
|
|
@@ -239,7 +270,26 @@ async function numbered(home, ticket, now, lock) {
|
|
|
239
270
|
handle = await lock.tryAcquire(path.join(dir, ".lock"));
|
|
240
271
|
}
|
|
241
272
|
try {
|
|
242
|
-
|
|
273
|
+
return await action();
|
|
274
|
+
}
|
|
275
|
+
finally {
|
|
276
|
+
await handle.release();
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
/** Recheck and commit a queued grant under the resource lock. No awaits separate the final read and ticket write. */
|
|
280
|
+
export async function grantQueued(home, t, lock = new OsLock()) {
|
|
281
|
+
return locked(home, t.resource, lock, () => {
|
|
282
|
+
const busy = blockers(t, liveTickets(home, t.resource));
|
|
283
|
+
if (!busy.length) {
|
|
284
|
+
t.grantedAt = Date.now();
|
|
285
|
+
writeTicketSync(home, t);
|
|
286
|
+
}
|
|
287
|
+
return busy;
|
|
288
|
+
});
|
|
289
|
+
}
|
|
290
|
+
async function numbered(home, ticket, now, lock) {
|
|
291
|
+
return locked(home, ticket.resource, lock, async () => {
|
|
292
|
+
const dir = leaseDir(home, ticket.resource), counter = path.join(dir, ".seq");
|
|
243
293
|
const last = Number.parseInt(await readFile(counter, "utf8").catch(() => "0"), 10) || 0;
|
|
244
294
|
const highest = readTickets(home, ticket.resource).reduce((m, t) => Math.max(m, t.seq), last);
|
|
245
295
|
const t = { ...ticket, seq: highest + 1 };
|
|
@@ -252,10 +302,7 @@ async function numbered(home, ticket, now, lock) {
|
|
|
252
302
|
await replaceFile(counter, String(t.seq));
|
|
253
303
|
writeTicketSync(home, t);
|
|
254
304
|
return t;
|
|
255
|
-
}
|
|
256
|
-
finally {
|
|
257
|
-
await handle.release();
|
|
258
|
-
}
|
|
305
|
+
});
|
|
259
306
|
}
|
|
260
307
|
export function leaseState(home) {
|
|
261
308
|
let resources;
|
|
@@ -266,15 +313,15 @@ export function leaseState(home) {
|
|
|
266
313
|
return [];
|
|
267
314
|
}
|
|
268
315
|
return resources.map(resource => {
|
|
269
|
-
const tickets = liveTickets(home, resource), holders = tickets.filter(t => t.grantedAt !== undefined), waiters = tickets.filter(t => t.grantedAt === undefined);
|
|
316
|
+
const tickets = liveTickets(home, resource), holders = tickets.filter(t => t.grantedAt !== undefined), waiters = tickets.filter(t => t.grantedAt === undefined).sort(rank);
|
|
270
317
|
const slots = slotCount(tickets);
|
|
271
318
|
return { resource, holders, waiters, ...(slots !== undefined ? { slots, held: holders.length } : {}) };
|
|
272
319
|
}).filter(r => r.holders.length || r.waiters.length);
|
|
273
320
|
}
|
|
274
|
-
/** The slot count shown for a resource: its first counted waiter's, else its latest counted ticket's
|
|
321
|
+
/** The slot count shown for a resource: its first ranked counted waiter's, else its latest counted ticket's. */
|
|
275
322
|
export function slotCount(tickets) {
|
|
276
323
|
const counted = tickets.filter(t => t.mode === "counted");
|
|
277
|
-
return (counted.
|
|
324
|
+
return (counted.filter(t => t.grantedAt === undefined).sort(rank)[0] ?? counted.at(-1))?.slots;
|
|
278
325
|
}
|
|
279
326
|
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`;
|
|
280
327
|
const clip = (s, n) => s.length > n ? `${s.slice(0, n - 1)}…` : s;
|
|
@@ -286,17 +333,17 @@ export const who = (t) => t.call ? callAddress(t.call) : `pid ${t.wrapper.pid} \
|
|
|
286
333
|
export const modeLabel = (t) => t.mode === "counted" ? "slot" : t.mode;
|
|
287
334
|
/** A granted ticket's mode, how long it has been held, the command (unless `who` already names it) and the note:
|
|
288
335
|
* "exclusive, 12m, `make bench`, nightly". */
|
|
289
|
-
export const holdDetail = (t, now = Date.now(), command = !!t.call) => `${modeLabel(t)}, ${age(now - (t.grantedAt ?? t.since))}${command ? `, \`${clip(t.argv.join(" "), 60)}\`` : ""}${t.note ? `, ${clip(t.note, 80)}` : ""}`;
|
|
336
|
+
export const holdDetail = (t, now = Date.now(), command = !!t.call) => `${modeLabel(t)}, ${age(now - (t.grantedAt ?? t.since))}${t.expectMs !== undefined ? ` of ~${age(t.expectMs)}` : ""}${command ? `, \`${clip(t.argv.join(" "), 60)}\`` : ""}${t.note ? `, ${clip(t.note, 80)}` : ""}`;
|
|
290
337
|
/** One status line per resource: "machine held by <who> (exclusive, 12m, `make bench`); waiting: <who> 3m, …". A resource
|
|
291
338
|
* with counted tickets: "build 3/5 held: <who> (slot, 2m, ...), ...; waiting: 2 (first: <who>, 30s)". */
|
|
292
339
|
export function leaseLines(state, now = Date.now()) {
|
|
293
340
|
return state.map(({ resource, holders, waiters, slots }) => {
|
|
294
341
|
if (slots !== undefined) {
|
|
295
342
|
const by = holders.map(t => `${who(t)} (${holdDetail(t, now)})`).join(", ");
|
|
296
|
-
return `${resource} ${holders.length}/${slots} held${by ? `: ${by}` : ""}${waiters.length ? `; waiting: ${waiters.length} (first: ${who(waiters[0])}, ${age(now - waiters[0].since)})` : ""}`;
|
|
343
|
+
return `${resource} ${holders.length}/${slots} held${by ? `: ${by}` : ""}${waiters.length ? `; waiting: ${waiters.length} (first: ${who(waiters[0])}, ${age(now - waiters[0].since)}${waiters[0].expectMs !== undefined ? `, expects ${age(waiters[0].expectMs)}` : ""})` : ""}`;
|
|
297
344
|
}
|
|
298
345
|
const held = holders.length ? `held by ${holders.map(t => `${who(t)} (${holdDetail(t, now)})`).join(", ")}` : "free";
|
|
299
|
-
return `${resource} ${held}${waiters.length ? `; waiting: ${waiters.map(t => `${who(t)} ${t.mode === "shared" ? "shared " : ""}${age(now - t.since)}`).join(", ")}` : ""}`;
|
|
346
|
+
return `${resource} ${held}${waiters.length ? `; waiting: ${waiters.map(t => `${who(t)} ${t.mode === "shared" ? "shared " : ""}${age(now - t.since)}${t.expectMs !== undefined ? ` expects ${age(t.expectMs)}` : ""}`).join(", ")}` : ""}`;
|
|
300
347
|
});
|
|
301
348
|
}
|
|
302
349
|
/** Per call id: "holds lease machine" / "waiting for lease machine 3m". */
|
|
@@ -2,8 +2,8 @@
|
|
|
2
2
|
// Known-id filtering assumes argv/other values do not impersonate the sole known
|
|
3
3
|
// execution id. Multiple known ids are ambiguous; macOS verification awaits CI.
|
|
4
4
|
import { readFile, readdir } from "node:fs/promises";
|
|
5
|
-
import { closeSync, existsSync, openSync, readFileSync, readSync } from "node:fs";
|
|
6
|
-
import { execFile } from "node:child_process";
|
|
5
|
+
import { closeSync, existsSync, openSync, readFileSync, readdirSync, readSync } from "node:fs";
|
|
6
|
+
import { execFile, execFileSync } from "node:child_process";
|
|
7
7
|
import { promisify } from "node:util";
|
|
8
8
|
/** `ps` by its absolute path where it has one (macOS and Linux: /bin/ps), so a minimal PATH (a service unit, a test
|
|
9
9
|
* that hides `pi`) does not take the process table away. */
|
|
@@ -61,12 +61,50 @@ export class ProcessTable {
|
|
|
61
61
|
ticks;
|
|
62
62
|
platform;
|
|
63
63
|
ps;
|
|
64
|
+
tagName;
|
|
64
65
|
constructor(options = {}) {
|
|
66
|
+
this.tagName = options.tagName ?? "DSA_EXEC";
|
|
67
|
+
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(this.tagName))
|
|
68
|
+
throw new Error("Invalid process tag name");
|
|
65
69
|
this.platform = options.platform ?? process.platform;
|
|
66
70
|
this.ps = options.ps ?? (async () => (await exec(PS, ["-axEww", "-o", "pid=,ppid=,lstart=,time=,stat=,command="],
|
|
67
71
|
// The whole table with environments is large; 2 s proved too short on loaded macOS machines.
|
|
68
72
|
{ env: { ...process.env, LC_ALL: "C" }, timeout: 10_000, maxBuffer: 32 * 1024 * 1024 })).stdout);
|
|
69
73
|
}
|
|
74
|
+
/** Synchronous liveness for lease readers. Unlike execution tracking, hold tags are reread after each exec. */
|
|
75
|
+
tagged(tag) {
|
|
76
|
+
if (this.platform === "darwin") {
|
|
77
|
+
try {
|
|
78
|
+
return this.mac(execFileSync(PS, ["-axEww", "-o", "pid=,ppid=,lstart=,time=,stat=,command="], { encoding: "utf8", env: { ...process.env, LC_ALL: "C" }, timeout: 1000, maxBuffer: 32 * 1024 * 1024 }), new Set([tag]))
|
|
79
|
+
.filter(p => p.tag === tag);
|
|
80
|
+
}
|
|
81
|
+
catch {
|
|
82
|
+
return []; /* ps may not expose environments: group-only fallback */
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
if (this.platform !== "linux")
|
|
86
|
+
return [];
|
|
87
|
+
const out = [];
|
|
88
|
+
for (const name of readdirSync("/proc")) {
|
|
89
|
+
if (!/^\d+$/.test(name))
|
|
90
|
+
continue;
|
|
91
|
+
try {
|
|
92
|
+
const stat = readStat(name), fields = stat.slice(stat.lastIndexOf(")") + 2).split(" ");
|
|
93
|
+
if (fields[0] === "Z" || fields[0] === "X")
|
|
94
|
+
continue;
|
|
95
|
+
if (!readFileSync(`/proc/${name}/environ`, "utf8").split("\0").includes(`${this.tagName}=${tag}`))
|
|
96
|
+
continue;
|
|
97
|
+
const check = readStat(name), current = check.slice(check.lastIndexOf(")") + 2).split(" ");
|
|
98
|
+
if (current[19] === fields[19] && current[0] !== "Z" && current[0] !== "X")
|
|
99
|
+
out.push({ pid: Number(name), start: fields[19] });
|
|
100
|
+
}
|
|
101
|
+
catch (error) {
|
|
102
|
+
if (!vanished(error))
|
|
103
|
+
throw error;
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
return out;
|
|
107
|
+
}
|
|
70
108
|
/** C2, F1: Concurrent observations share a scan; fences wait out all pre-request work. */
|
|
71
109
|
async list(knownExecs = new Set(), options = {}) {
|
|
72
110
|
const value = await this.listRaw(options);
|
|
@@ -118,10 +156,10 @@ export class ProcessTable {
|
|
|
118
156
|
const start = fields[19];
|
|
119
157
|
const key = `${name}:${start}`;
|
|
120
158
|
let tag = this.tags.get(key);
|
|
121
|
-
if (!this.tags.has(key)) {
|
|
159
|
+
if (this.tagName !== "DSA_EXEC" || !this.tags.has(key)) {
|
|
122
160
|
try {
|
|
123
161
|
const env = await readFile(`/proc/${name}/environ`, "utf8");
|
|
124
|
-
tag = env.split("\0").find(value => value.startsWith(
|
|
162
|
+
tag = env.split("\0").find(value => value.startsWith(`${this.tagName}=`))?.slice(this.tagName.length + 1);
|
|
125
163
|
}
|
|
126
164
|
catch (error) {
|
|
127
165
|
if (!vanished(error))
|
|
@@ -152,7 +190,7 @@ export class ProcessTable {
|
|
|
152
190
|
continue;
|
|
153
191
|
const parts = match[4].split(":").map(Number);
|
|
154
192
|
const seconds = parts.reduce((total, part) => total * 60 + part, 0);
|
|
155
|
-
const tags = new Set([...match[6].matchAll(
|
|
193
|
+
const tags = new Set([...match[6].matchAll(new RegExp(`(?:^|\\s)${this.tagName}=([^\\s]*)`, "g"))]
|
|
156
194
|
.map(token => token[1]).filter(tag => knownExecs.has(tag)));
|
|
157
195
|
result.push({ pid: Number(match[1]), ppid: Number(match[2]), start: match[3].replace(/\s+/g, " "),
|
|
158
196
|
tag: tags.size === 1 ? tags.values().next().value : undefined, cpuMs: seconds * 1000,
|
package/dist/requests.js
CHANGED
|
@@ -56,7 +56,7 @@ export const SESSION_ID = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
|
|
|
56
56
|
export function specDigest(req) {
|
|
57
57
|
let body = req.body;
|
|
58
58
|
if (req.kind === 'run' && body && typeof body === 'object' && !Array.isArray(body)) {
|
|
59
|
-
const { origin: _, session: _s, ...rest } = body;
|
|
59
|
+
const { origin: _, session: _s, caller: _c, ...rest } = body;
|
|
60
60
|
body = rest;
|
|
61
61
|
}
|
|
62
62
|
if (req.kind === 'send' && body && typeof body === 'object' && !Array.isArray(body)) {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-durable-subagents",
|
|
3
|
-
"version": "1.0
|
|
3
|
+
"version": "1.1.0",
|
|
4
4
|
"description": "Subagents for pi that never lose work and never do it twice. Crash-safe workflows, automatic recovery, and a live view just like the main agent.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|