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.
@@ -1,18 +1,15 @@
1
- // Command-scoped resource leases: `pi-durable-subagents hold <resource> -- <command>` (README "Resource leases").
2
- // One ticket file per request under $DSA_HOME/leases/<resource>/, numbered under a kernel lock so the numbers are
3
- // strictly increasing and never reused. Grants are strict FIFO by number: an exclusive request needs no earlier live
4
- // ticket, a shared one no earlier live exclusive ticket. A counted request (`--slots N`) needs no earlier live waiter of
5
- // any mode, no earlier live exclusive ticket, and fewer than N live granted tickets. Whether an exclusive or shared
6
- // request is grantable depends only on earlier tickets, which can only disappear. A counted request also counts later
7
- // granted tickets, but only shared ones can be granted past it (shared requests ignore slots by design), and earlier
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
- export function orphaned(t) {
77
+ function leftoverGroup(t) {
81
78
  const c = t.command;
82
- if (!c || alive(t.wrapper) || alive(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
- /** A ticket is live while its wrapper, its command, or processes the command left in its group run. */
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
- /** The live tickets that keep `t` waiting (empty when it may run). For an exclusive or shared request these are earlier
144
- * tickets; a counted one is kept by earlier waiters and exclusive tickets, else, when all its slots are taken, by every
145
- * granted ticket (a granted shared one may be later). `tickets` is the resource's live list, `t` itself ignored. A
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
- if (t.mode !== "counted")
151
- return tickets.filter(o => o.seq < t.seq && (t.mode === "exclusive" || o.mode === "exclusive"));
152
- const ahead = tickets.filter(o => o.seq < t.seq && (o.grantedAt === undefined || o.mode === "exclusive"));
153
- if (ahead.length)
154
- return ahead;
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: number it under the resource's kernel lock and write its ticket before the lock is released, so a
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 (`hold --max-wait 0`): under the resource's kernel lock, either no live ticket
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 numbered(home, ticket, now, lock) {
234
- const dir = leaseDir(home, ticket.resource);
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
- const counter = path.join(dir, ".seq");
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 (one N per name). */
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.find(t => t.grantedAt === undefined) ?? counted.at(-1))?.slots;
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("DSA_EXEC="))?.slice(9);
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(/(?:^|\s)DSA_EXEC=([^\s]*)/g)]
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/dist/types.js CHANGED
@@ -56,6 +56,17 @@ export const JT = {
56
56
  rejected: "rejected",
57
57
  withdrawn: "withdrawn",
58
58
  };
59
+ export const ASK_FIELDS = ['decision_needed', 'options', 'facts', 'tried', 'classification_candidates'];
60
+ /** Copy only present metadata, never inserting defaults into old records. */
61
+ export function askFields(value) {
62
+ return Object.fromEntries(ASK_FIELDS.filter(key => Object.hasOwn(value, key)).map(key => [key, value[key]]));
63
+ }
64
+ /** Parent-facing text; the stored question and machine-facing text remain unchanged. */
65
+ export function askText(value, question) {
66
+ if (value.decision_needed === undefined)
67
+ return question;
68
+ return [value.decision_needed, ...(value.options ?? []).map((o, i) => `${i + 1}. ${o.label}${o.preferred ? ' (preferred)' : ''}`), question].join('\n');
69
+ }
59
70
  /** A command call (CallSpec.command): no agent, task or model at runtime even though the type declares them. */
60
71
  export const isCommandCall = (spec) => spec?.command !== undefined;
61
72
  // ---------------------------------------------------------------------------
@@ -68,6 +79,7 @@ export const ENV = {
68
79
  inbox: "DSA_INBOX", // absolute path of this call's inbox dir
69
80
  journal: "DSA_JOURNAL", // absolute path of the workflow journal (read-only snapshot for the launch gate)
70
81
  schema: "DSA_SCHEMA", // absolute path of report JSON schema, if any
82
+ askRequireDecision: "DSA_ASK_REQUIRE_DECISION", // execution-start snapshot of config.askRequireDecision (default false)
71
83
  budget: "DSA_BUDGET", // JSON {tokens?, costUsd?}: per-call budget; the child refuses the next provider request once reached (P31b)
72
84
  model: "DSA_MODEL", // "provider/id" the executor holds a slot for; the child re-applies it if pi started without it (C8)
73
85
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-durable-subagents",
3
- "version": "1.0.45",
3
+ "version": "1.2.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",