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.
@@ -1,8 +1,12 @@
1
1
  // Command-scoped resource leases: `pi-durable-subagents hold <resource> -- <command>` (README "Resource leases").
2
2
  // One ticket file per request under $DSA_HOME/leases/<resource>/, numbered under a kernel lock so the numbers are
3
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. Whether a request is grantable depends only on earlier tickets,
5
- // which can only disappear, so a grant needs no lock once the ticket exists. A ticket is live while its wrapper or its
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
6
10
  // command (pid + start token) lives, or processes the command left in its group remain; a waiter next in line ends such
7
11
  // leftovers of a killed wrapper. Anyone may delete a dead ticket. No orchestrator is involved.
8
12
  import { chmodSync, mkdirSync, readdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
@@ -136,9 +140,20 @@ export function liveTickets(home, resource) {
136
140
  return false;
137
141
  });
138
142
  }
139
- /** The live tickets that come before `t` and keep it waiting (empty when it may run). */
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. */
140
147
  export function blockers(t, tickets) {
141
- return tickets.filter(o => o.seq < t.seq && (t.mode === "exclusive" || o.mode === "exclusive"));
148
+ if (t.grantedAt !== undefined)
149
+ 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 : [];
142
157
  }
143
158
  function writeTicketSync(home, t) {
144
159
  const file = path.join(leaseDir(home, t.resource), ticketName(t.seq)), tmp = `${file}.${process.pid}.tmp`;
@@ -159,6 +174,16 @@ export function removeTicket(home, t) {
159
174
  /** Queue a request: number it under the resource's kernel lock and write its ticket before the lock is released, so a
160
175
  * later request always sees it. */
161
176
  export async function enqueue(home, ticket, lock = new OsLock()) {
177
+ return (await numbered(home, ticket, false, lock));
178
+ }
179
+ /** Take the lease now or not at all (`hold --max-wait 0`): under the resource's kernel lock, either no live ticket
180
+ * blocks it and its ticket is written already granted, or nothing is written and the blockers are returned. A refused
181
+ * request is never visible as a waiter, and a granted one never was one. Granting needs no more than the lock: a later
182
+ * request gets a higher number and waits behind this ticket, and earlier tickets can only disappear. */
183
+ export async function tryGrant(home, ticket, lock = new OsLock()) {
184
+ return numbered(home, ticket, true, lock);
185
+ }
186
+ async function numbered(home, ticket, now, lock) {
162
187
  const dir = leaseDir(home, ticket.resource);
163
188
  mkdirSync(dir, { recursive: true });
164
189
  let handle = await lock.tryAcquire(path.join(dir, ".lock"));
@@ -171,6 +196,12 @@ export async function enqueue(home, ticket, lock = new OsLock()) {
171
196
  const last = Number.parseInt(await readFile(counter, "utf8").catch(() => "0"), 10) || 0;
172
197
  const highest = readTickets(home, ticket.resource).reduce((m, t) => Math.max(m, t.seq), last);
173
198
  const t = { ...ticket, seq: highest + 1 };
199
+ if (now) {
200
+ const busy = blockers(t, liveTickets(home, ticket.resource));
201
+ if (busy.length)
202
+ return { busy };
203
+ t.grantedAt = Date.now();
204
+ }
174
205
  await writeFile(`${counter}.tmp`, String(t.seq));
175
206
  renameSync(`${counter}.tmp`, counter);
176
207
  writeTicketSync(home, t);
@@ -180,8 +211,6 @@ export async function enqueue(home, ticket, lock = new OsLock()) {
180
211
  await handle.release();
181
212
  }
182
213
  }
183
- /** Every resource with live tickets: holders (granted) and waiters, in request order. Cheap: a directory listing,
184
- * small files and a liveness check of the few ticket processes. */
185
214
  export function leaseState(home) {
186
215
  let resources;
187
216
  try {
@@ -191,22 +220,35 @@ export function leaseState(home) {
191
220
  return [];
192
221
  }
193
222
  return resources.map(resource => {
194
- const tickets = liveTickets(home, resource);
195
- return { resource, holders: tickets.filter(t => t.grantedAt !== undefined), waiters: tickets.filter(t => t.grantedAt === undefined) };
223
+ const tickets = liveTickets(home, resource), holders = tickets.filter(t => t.grantedAt !== undefined), waiters = tickets.filter(t => t.grantedAt === undefined);
224
+ const slots = slotCount(tickets);
225
+ return { resource, holders, waiters, ...(slots !== undefined ? { slots, held: holders.length } : {}) };
196
226
  }).filter(r => r.holders.length || r.waiters.length);
197
227
  }
228
+ /** The slot count shown for a resource: its first counted waiter's, else its latest counted ticket's (one N per name). */
229
+ export function slotCount(tickets) {
230
+ const counted = tickets.filter(t => t.mode === "counted");
231
+ return (counted.find(t => t.grantedAt === undefined) ?? counted.at(-1))?.slots;
232
+ }
198
233
  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`;
199
234
  const clip = (s, n) => s.length > n ? `${s.slice(0, n - 1)}…` : s;
200
235
  /** "<wid>/<key>" of a call id "<wid>@<rev>/<key>@<gen>". */
201
236
  export const callAddress = (call) => { const m = /^([^@/]+)@\d+\/(.+)@\d+$/.exec(call); return m ? `${m[1]}/${m[2]}` : call; };
202
237
  /** Who holds or waits: the subagent call when there is one, else the pid and command. */
203
238
  export const who = (t) => t.call ? callAddress(t.call) : `pid ${t.wrapper.pid} \`${clip(t.argv.join(" "), 60)}\``;
239
+ /** How a mode reads in listings: a counted ticket holds a "slot". */
240
+ export const modeLabel = (t) => t.mode === "counted" ? "slot" : t.mode;
204
241
  /** A granted ticket's mode, how long it has been held, the command (unless `who` already names it) and the note:
205
242
  * "exclusive, 12m, `make bench`, nightly". */
206
- export const holdDetail = (t, now = Date.now(), command = !!t.call) => `${t.mode}, ${age(now - (t.grantedAt ?? t.since))}${command ? `, \`${clip(t.argv.join(" "), 60)}\`` : ""}${t.note ? `, ${clip(t.note, 80)}` : ""}`;
207
- /** One status line per resource: "machine held by <who> (exclusive, 12m, `make bench`); waiting: <who> 3m, …". */
243
+ 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)}` : ""}`;
244
+ /** One status line per resource: "machine held by <who> (exclusive, 12m, `make bench`); waiting: <who> 3m, …". A resource
245
+ * with counted tickets: "build 3/5 held: <who> (slot, 2m, ...), ...; waiting: 2 (first: <who>, 30s)". */
208
246
  export function leaseLines(state, now = Date.now()) {
209
- return state.map(({ resource, holders, waiters }) => {
247
+ return state.map(({ resource, holders, waiters, slots }) => {
248
+ if (slots !== undefined) {
249
+ const by = holders.map(t => `${who(t)} (${holdDetail(t, now)})`).join(", ");
250
+ return `${resource} ${holders.length}/${slots} held${by ? `: ${by}` : ""}${waiters.length ? `; waiting: ${waiters.length} (first: ${who(waiters[0])}, ${age(now - waiters[0].since)})` : ""}`;
251
+ }
210
252
  const held = holders.length ? `held by ${holders.map(t => `${who(t)} (${holdDetail(t, now)})`).join(", ")}` : "free";
211
253
  return `${resource} ${held}${waiters.length ? `; waiting: ${waiters.map(t => `${who(t)} ${t.mode === "shared" ? "shared " : ""}${age(now - t.since)}`).join(", ")}` : ""}`;
212
254
  });
@@ -2,11 +2,24 @@
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 { readFileSync } from "node:fs";
5
+ import { closeSync, openSync, readFileSync, readSync } from "node:fs";
6
6
  import { execFile } from "node:child_process";
7
7
  import { promisify } from "node:util";
8
8
  const exec = promisify(execFile);
9
9
  const vanished = (error) => ["ENOENT", "ESRCH", "EACCES", "EPERM"].includes(error.code ?? "");
10
+ // /proc/<pid>/stat is one short line: one open/read/close into a reused buffer, not readFileSync's fstat, sized read
11
+ // and EOF read (a scan reads it for every process of the machine every second).
12
+ const statBuffer = Buffer.alloc(4096);
13
+ function readStat(pid) {
14
+ const fd = openSync(`/proc/${pid}/stat`, "r");
15
+ try {
16
+ const n = readSync(fd, statBuffer, 0, statBuffer.length, 0);
17
+ return n < statBuffer.length ? statBuffer.toString("latin1", 0, n) : readFileSync(`/proc/${pid}/stat`, "latin1");
18
+ }
19
+ finally {
20
+ closeSync(fd);
21
+ }
22
+ }
10
23
  /** C2, C3: Capture only the newly spawned pid; an absent or dead process has no token. */
11
24
  export async function captureStart(pid) {
12
25
  if (process.platform === "linux") {
@@ -94,7 +107,7 @@ export class ProcessTable {
94
107
  continue;
95
108
  try {
96
109
  // /proc stat is a tiny kernel snapshot; avoid four libuv round trips per cached identity.
97
- const stat = readFileSync(`/proc/${name}/stat`, "utf8");
110
+ const stat = readStat(name);
98
111
  const fields = stat.slice(stat.lastIndexOf(")") + 2).split(" ");
99
112
  // Zombies cannot act and may remain indefinitely under a non-reaping init.
100
113
  if (fields[0] === "Z" || fields[0] === "X")
@@ -112,7 +125,7 @@ export class ProcessTable {
112
125
  throw error;
113
126
  }
114
127
  // Do not attach an old environment to a reused pid; cached identities already include the start token.
115
- const check = readFileSync(`/proc/${name}/stat`, "utf8");
128
+ const check = readStat(name);
116
129
  if (check.slice(check.lastIndexOf(")") + 2).split(" ")[19] !== start)
117
130
  continue;
118
131
  }
package/dist/requests.js CHANGED
@@ -21,6 +21,33 @@ export function requestRid(id) {
21
21
  }
22
22
  /** The request id of a `req:<id>` rid; undefined for any other rid (ULIDs never contain ':'). */
23
23
  export function requestId(rid) { return rid.startsWith(PREFIX) ? rid.slice(PREFIX.length) : undefined; }
24
+ /** The request ids of one send to `n` calls under `<id>`: `<id>:1` ... `<id>:n`, one per target in the order given
25
+ * (each is an ordinary request id, so a retry with the same list gets the same outcomes). Each body carries the list's
26
+ * digest (`batch`, see batchDigest), so another list under the id is a request-conflict (checked by batchConflict
27
+ * before anything is sent). */
28
+ export function manyIds(id, n) {
29
+ const ids = Array.from({ length: n }, (_, i) => `${id}:${i + 1}`);
30
+ for (const derived of ids)
31
+ if (!REQUEST_ID.test(derived))
32
+ throw new Error(`request id ${JSON.stringify(id)} is too long for a send to ${n} calls (${derived} exceeds 124 characters)`);
33
+ requestRid(id);
34
+ return ids;
35
+ }
36
+ /** The `batch` of every request of a send to the calls `targets` (in the order given). */
37
+ export function batchDigest(targets) { return contentHash({ to: targets }); }
38
+ /** Whether `<id>` names other content than a send to several calls with this `batch`: a single request under `<id>`, or
39
+ * a send to several calls with another list (its first request `<id>:1` has another batch). */
40
+ export async function batchConflict(home, id, batch) {
41
+ if (await findRequest(home, requestRid(id)))
42
+ return true;
43
+ const first = `${id}:1`, prior = REQUEST_ID.test(first) ? await findRequest(home, requestRid(first)) : undefined;
44
+ return prior !== undefined && prior.request.body?.batch !== batch;
45
+ }
46
+ /** Whether `<id>` already names a send to several calls (its first derived id `<id>:1` is recorded). */
47
+ export async function namesMany(home, id) {
48
+ const first = `${id}:1`;
49
+ return REQUEST_ID.test(first) && await findRequest(home, requestRid(first)) !== undefined;
50
+ }
24
51
  /** Spec_digest = contentHash({kind, body, cond}) (cond omitted when absent). A run's body.origin (the pi session
25
52
  * branch offered for context:"fork") is delivery metadata, not spec: it differs on every turn, so it is not hashed. */
26
53
  export function specDigest(req) {
@@ -29,6 +56,10 @@ export function specDigest(req) {
29
56
  const { origin: _, ...rest } = body;
30
57
  body = rest;
31
58
  }
59
+ if (req.kind === 'send' && body && typeof body === 'object' && !Array.isArray(body)) {
60
+ const { caller: _, ...rest } = body;
61
+ body = rest;
62
+ }
32
63
  return contentHash({ kind: req.kind, body, cond: req.cond });
33
64
  }
34
65
  /** The envelope recorded for `rid`: the orchestrator's admitted copy (ledger `request`, kept after prune), else any
@@ -86,8 +86,8 @@ export function thoughtSummary(text) {
86
86
  return (headings.at(-1)[1] ?? headings.at(-1)[2]).trim();
87
87
  return lastSentence(text);
88
88
  }
89
- const STOPS = new Set([...".!?。!?"]);
90
- /** The last match of /[^.!?。!?]+[.!?。!?](?=\s|$)/gu without the regex: a long thought with no sentence end made
89
+ const STOPS = new Set([...".!?\u3002\uff01\uff1f"]);
90
+ /** The last match of /[^.!?\u3002\uff01\uff1f]+[.!?\u3002\uff01\uff1f](?=\s|$)/gu without the regex: a long thought with no sentence end made
91
91
  * that regex retry from every position (quadratic), which stalled pi's startup on long histories. Such a match is a
92
92
  * whole run of non-stop characters followed by one stop that ends the text or precedes whitespace. */
93
93
  function lastSentence(text) {
package/dist/ui/view.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
2
- import { isLive, liveCalls, progressOf } from "../orchestrator/snapshot.js";
2
+ import { isLive, labelsText, liveCalls, progressOf } from "../orchestrator/snapshot.js";
3
3
  import { oneLine } from "./frame.js";
4
4
  /** UI §2: Render compact wall-clock durations; never present these as charged active time. */
5
5
  export function duration(ms) {
@@ -276,7 +276,10 @@ export function listRows(workflows, state, facts, name, width, now = Date.now())
276
276
  // Stable order (UI §2): active rows keep proposal (snapshot) order; done rows by immutable end time.
277
277
  const done = doneOrder(w.calls), active = liveCalls(w), folded = !isOpen(w, state);
278
278
  const progress = progressOf(w); // v12 §4: done/planned, `n+` while a script workflow keeps proposing
279
- rows.push({ id: w.wid, kind: "workflow", workflow: w, dim, text: `${folded ? "▸" : "▾"} ${w.name ?? w.wid} · ${progress.done}/${progress.total}${progress.plus ? "+" : ""} · ${duration((w.endedAt ?? now) - (w.startedAt ?? now))}` });
279
+ const head = `${folded ? "▸" : "▾"} ${w.name ?? w.wid} · ${progress.done}/${progress.total}${progress.plus ? "+" : ""} · ${duration((w.endedAt ?? now) - (w.startedAt ?? now))}`;
280
+ // The run's labels follow when the row has room for a useful part of them (clipped to at most 60 characters).
281
+ const room = Math.min(60, width - visibleWidth(head) - 3);
282
+ rows.push({ id: w.wid, kind: "workflow", workflow: w, dim, text: w.labels && room >= 12 ? `${head} · ${labelsText(w.labels, room)}` : head });
280
283
  if (folded)
281
284
  continue;
282
285
  if (dim) { // a finished workflow lists its agents directly (no nested "done" node)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-durable-subagents",
3
- "version": "1.0.25",
3
+ "version": "1.0.28",
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",