pi-durable-subagents 1.0.43 → 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.
@@ -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,8 @@ export const JT = {
56
56
  rejected: "rejected",
57
57
  withdrawn: "withdrawn",
58
58
  };
59
+ /** A command call (CallSpec.command): no agent, task or model at runtime even though the type declares them. */
60
+ export const isCommandCall = (spec) => spec?.command !== undefined;
59
61
  // ---------------------------------------------------------------------------
60
62
  // Environment variables passed to children (child session agent reads them)
61
63
  // ---------------------------------------------------------------------------
package/dist/ui/screen.js CHANGED
@@ -1,12 +1,39 @@
1
1
  import { AssistantMessageComponent, UserMessageComponent, ToolExecutionComponent, getMarkdownTheme, getSelectListTheme } from "@earendil-works/pi-coding-agent";
2
- import { Input, SelectList, fuzzyFilter, matchesKey, truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
2
+ import { Input, SelectList, fuzzyFilter, matchesKey, truncateToWidth, visibleWidth, wrapTextWithAnsi } from "@earendil-works/pi-tui";
3
3
  import { CT } from "../types.js";
4
4
  import { UiActions, UiData } from "./data.js";
5
- import { callName, workflowName, doneOrder, isOpen, plainReason, toggleOpen, duration, keepSelection, summaryText, listRows, modelLabel, pendingText, resultPhrase, statusPhrase, rowText, toolCount } from "./view.js";
5
+ import { callName, workflowName, doneOrder, isOpen, plainReason, toggleOpen, duration, keepSelection, summaryText, listRows, modelColumn, modelLabel, pendingText, resultPhrase, statusPhrase, rowText, toolCount } from "./view.js";
6
6
  import { fitWidth, frame, inner } from "./frame.js";
7
7
  import { thinkingElapsed } from "./thinking.js";
8
8
  import { thoughtSummary } from "./session.js";
9
9
  const levels = ["off", "minimal", "low", "medium", "high", "xhigh", "max"];
10
+ /** A command call runs a process: it takes no message and no model; only stop controls it. */
11
+ const isCommand = (c) => c?.command !== undefined;
12
+ const COMMAND_NOTE = "a command call takes no messages or model; x or /stop stops it";
13
+ /** The watch view's second head line of a command call: "running · pid 123 · 2m05s · <log>" / "failed · exit 3 · 41s". */
14
+ export function commandHead(c, w, now) {
15
+ const r = c.result, data = r?.data, log = c.commandRun?.log;
16
+ const ended = r ? [r.status, typeof data?.exitCode === "number" ? `exit ${data.exitCode}` : typeof data?.signal === "string" ? data.signal : "",
17
+ typeof data?.durationMs === "number" ? duration(data.durationMs) : ""] : [statusPhrase(c, w, undefined, now)];
18
+ return [...ended, log ?? ""].filter(Boolean).join(" · ");
19
+ }
20
+ /** The watch view's body of a command call: the whole command, then its result's output (the last 16 KiB of its log)
21
+ * once it ended, else where its output goes. */
22
+ export function commandTranscript(c, w, now) {
23
+ const lines = [`$ ${c.command ?? ""}`, ""];
24
+ if (c.result) {
25
+ if (c.result.error)
26
+ lines.push(c.result.error, "");
27
+ lines.push(...(c.result.output ? c.result.output.replace(/\n+$/, "").split("\n") : ["(no output)"]));
28
+ }
29
+ else if (c.phase === "queued")
30
+ lines.push(statusPhrase(c, w, undefined, now));
31
+ else
32
+ lines.push(`${statusPhrase(c, w, undefined, now)}${c.commandRun?.log ? `; output goes to ${c.commandRun.log}` : ""}`);
33
+ return lines;
34
+ }
35
+ /** One output line wrapped to the panel; control characters (also escape sequences a command printed) are dropped. */
36
+ const wrapLine = (line, width) => wrapTextWithAnsi(line.replace(/\t/g, " ").replace(/[\x00-\x08\x0b-\x1f\x7f]/g, ""), Math.max(1, width));
10
37
  /** UI §2–3: A single pi component owns list/watch navigation while the main agent keeps running. */
11
38
  const SPIN = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
12
39
  export class SubagentScreen {
@@ -174,6 +201,13 @@ export class SubagentScreen {
174
201
  const c = target ?? this.current().c;
175
202
  if (!c)
176
203
  return;
204
+ if (isCommand(c)) {
205
+ if (target)
206
+ this.listNotice = { text: COMMAND_NOTE, until: Date.now() + 5000 };
207
+ else
208
+ this.notice = COMMAND_NOTE;
209
+ return;
210
+ }
177
211
  this.menuTitle = `Model for ${c.key}`;
178
212
  const models = this.ctx.modelRegistry.getAvailable();
179
213
  this.menuItems = models.map(m => ({ value: `${m.provider}/${m.id}`, label: this.name(`${m.provider}/${m.id}`) }));
@@ -204,7 +238,7 @@ export class SubagentScreen {
204
238
  }
205
239
  thinkingMenu() {
206
240
  const { c } = this.current();
207
- if (!c)
241
+ if (!c || isCommand(c))
208
242
  return;
209
243
  const model = this.data.facts.get(c.callId)?.model ?? c.model;
210
244
  if (!model)
@@ -224,6 +258,10 @@ export class SubagentScreen {
224
258
  const { c } = this.current();
225
259
  if (!c)
226
260
  return;
261
+ if (isCommand(c)) {
262
+ this.notice = COMMAND_NOTE;
263
+ return;
264
+ }
227
265
  const facts = this.data.facts.get(c.callId), model = facts?.model ?? c.model;
228
266
  if (!model) {
229
267
  this.notice = "Model not yet recorded";
@@ -254,7 +292,11 @@ export class SubagentScreen {
254
292
  return;
255
293
  }
256
294
  if (message.startsWith("/")) {
257
- this.notice = "Commands: /model, /stop";
295
+ this.notice = isCommand(c) ? "Commands: /stop" : "Commands: /model, /stop";
296
+ return;
297
+ }
298
+ if (isCommand(c)) {
299
+ this.notice = COMMAND_NOTE;
258
300
  return;
259
301
  }
260
302
  const q = w.attention.find(a => a.kind === "question" && a.call === c.callId);
@@ -316,7 +358,9 @@ export class SubagentScreen {
316
358
  else if (!this.busy) {
317
359
  const row = this.selectedRow(), c = row?.kind === "call" ? row.call : undefined, w = row?.workflow;
318
360
  const asking = c && w?.attention.some(a => a.kind === "question" && a.call === c.callId);
319
- if (key === "s" && c && c.phase !== "sealed")
361
+ if (isCommand(c) && "sfam".includes(key))
362
+ this.listNotice = { text: COMMAND_NOTE, until: Date.now() + 5000 };
363
+ else if (key === "s" && c && c.phase !== "sealed")
320
364
  this.beginListInput("steer", row);
321
365
  else if (key === "f" && c?.phase === "sealed")
322
366
  this.beginListInput("follow-up", row);
@@ -379,7 +423,7 @@ export class SubagentScreen {
379
423
  // Panel coordinates: row 0 is the top border, column 2 is the first content column.
380
424
  if (event.y === 2) {
381
425
  const { c, w } = this.current();
382
- if (!c || !w)
426
+ if (!c || !w || isCommand(c))
383
427
  return;
384
428
  const facts = this.data.facts.get(c.callId), model = `${callName(w, c)} · ${this.name(facts?.model ?? c.model)} ▾ · `;
385
429
  const x = event.x - 2;
@@ -403,6 +447,8 @@ export class SubagentScreen {
403
447
  return this.input.handleMouse({ ...event, x: event.x - 2, y: 0 });
404
448
  }
405
449
  transcript(c, w, width) {
450
+ if (isCommand(c))
451
+ return { lines: commandTranscript(c, w, Date.now()).flatMap(line => line ? wrapLine(line, width) : [""]), thoughts: [] };
406
452
  const entries = this.data.sessions.get(c.callId) ?? [], lines = [], thoughts = [];
407
453
  const tools = new Map();
408
454
  // A `{ thought }` part is an expanded thinking block: like pi, a click anywhere on it collapses it again.
@@ -532,7 +578,7 @@ export class SubagentScreen {
532
578
  const rowWidth = Math.max(1, size.width - 2);
533
579
  this.rows = this.doneTab && w ? doneOrder(w.calls).map(c => {
534
580
  const f = this.data.facts.get(c.callId);
535
- return { id: c.callId, kind: "call", workflow: w, call: c, failed: !c.result?.ok, text: rowText(" ", callName(w, c), this.name(f?.model ?? c.model), resultPhrase(c), [toolCount(f?.tools)], rowWidth) };
581
+ return { id: c.callId, kind: "call", workflow: w, call: c, failed: !c.result?.ok, text: rowText(" ", callName(w, c), modelColumn(c, f, this.name), resultPhrase(c), [toolCount(f?.tools)], rowWidth) };
536
582
  }) : listRows(this.data.workflows, this.state, this.data.facts, this.name, rowWidth);
537
583
  height = this.height(Math.max(1, this.rows.length) + footerRows);
538
584
  size = inner(width, height); // inner width does not depend on height
@@ -549,10 +595,11 @@ export class SubagentScreen {
549
595
  const row = this.selectedRow(), c = row?.kind === "call" ? row.call : undefined;
550
596
  const asking = c && row?.workflow?.attention.some(a => a.kind === "question" && a.call === c.callId);
551
597
  const narrow = size.width < 72;
598
+ const agent = c && !isCommand(c);
552
599
  const keys = [narrow ? "↑↓" : "↑ ↓ select", row && row.kind !== "preview" ? `Enter ${narrow ? "" : row.kind === "workflow" ? (isOpen(row.workflow, this.state) ? "collapse" : "expand") : row.kind === "call" ? "watch" : "open"}`.trim() : "",
553
- c && c.phase !== "sealed" ? (narrow ? "s" : "s steer") : "", c?.phase === "sealed" ? (narrow ? "f" : "f follow-up") : "",
600
+ agent && c.phase !== "sealed" ? (narrow ? "s" : "s steer") : "", agent && c.phase === "sealed" ? (narrow ? "f" : "f follow-up") : "",
554
601
  c && c.phase !== "sealed" || row?.kind === "workflow" && row.workflow?.status === "running" ? (narrow ? "x" : "x stop") : "",
555
- c ? (narrow ? "m" : "m model") : "", asking ? (narrow ? "a" : "a answer") : "", row?.workflow?.paused ? (narrow ? "r" : "r resume") : "", "Esc back"].filter(Boolean).join(" · ");
602
+ agent ? (narrow ? "m" : "m model") : "", asking ? (narrow ? "a" : "a answer") : "", row?.workflow?.paused ? (narrow ? "r" : "r resume") : "", "Esc back"].filter(Boolean).join(" · ");
556
603
  const notice = this.listNotice && this.listNotice.until > Date.now() ? this.listNotice.text : "";
557
604
  const footer = this.listInput ? this.listInput.editor.render(size.width) : this.stopTarget ? [`Stop ${this.stopTarget.name}? y confirm · any other key cancels`] : notice ? [notice] : [];
558
605
  const body = this.rows.length ? lines.slice(0, Math.max(0, size.height - footer.length)) : ["No subagents"];
@@ -567,14 +614,16 @@ export class SubagentScreen {
567
614
  const tabs = size.width < 60 ? `${callName(w, c)} ${w.calls.indexOf(c) + 1}/${w.calls.length}` : `${[...active.map(c => callName(w, c)), ...(done ? [`${done} done`] : [])].join(" · ")} ← → switch`;
568
615
  const tools = toolCount(facts?.tools), pending = pendingText(c.pending), rule = this.theme.fg("borderMuted", "─".repeat(size.width));
569
616
  const switching = c.switching ? ` → ${this.name(c.switching)} (requested)` : "";
570
- const head = [tabs, `${callName(w, c)} · ${this.name(facts?.model ?? c.model)} ▾${switching} · ${facts?.thinking ?? "off"} ▾${tools ? ` · ${tools}` : ""}${pending ? ` · ${pending}` : ""}`,
571
- this.theme.fg("dim", this.spend(c, facts)), ...(c.phase === "queued" && c.answered ? [statusPhrase(c, w, facts, Date.now())] : []), rule];
617
+ // A command call shows its command, process and log instead of a model, thinking level and spend.
618
+ const head = isCommand(c) ? [tabs, `${callName(w, c)} · ${modelColumn(c, facts, this.name)}`, this.theme.fg("dim", commandHead(c, w, Date.now())), rule]
619
+ : [tabs, `${callName(w, c)} · ${this.name(facts?.model ?? c.model)} ▾${switching} · ${facts?.thinking ?? "off"} ▾${tools ? ` · ${tools}` : ""}${pending ? ` · ${pending}` : ""}`,
620
+ this.theme.fg("dim", this.spend(c, facts)), ...(c.phase === "queued" && c.answered ? [statusPhrase(c, w, facts, Date.now())] : []), rule];
572
621
  const asking = w.attention.some(a => a.kind === "question" && a.call === c.callId);
573
- const placeholder = `${c.phase === "sealed" ? "Continue" : asking ? "Reply to" : "Steer"} ${c.key}…${this.uses < 3 ? " / for commands" : ""}`;
622
+ const placeholder = isCommand(c) ? `${c.phase === "sealed" ? "Finished" : "Running"} command · /stop stops it` : `${c.phase === "sealed" ? "Continue" : asking ? "Reply to" : "Steer"} ${c.key}…${this.uses < 3 ? " / for commands" : ""}`;
574
623
  const empty = new Input({ prompt: "", placeholder, placeholderStyle: text => this.theme.fg("dim", text) });
575
624
  empty.focused = this.focused;
576
625
  const editor = this.input.getValue() ? this.input.render(size.width) : empty.render(size.width);
577
- const hint = this.input.getValue().startsWith("/") ? "/model · /stop" : this.notice;
626
+ const hint = this.input.getValue().startsWith("/") ? (isCommand(c) ? "/stop" : "/model · /stop") : this.notice;
578
627
  const transcript = this.transcript(c, w, size.width), available = Math.max(1, size.height - head.length - editor.length - 2);
579
628
  const bottom = Math.max(0, transcript.lines.length - available);
580
629
  // Scrolling back down to the end resumes following, as in pi's own transcript.
package/dist/ui/tool.js CHANGED
@@ -1,5 +1,8 @@
1
1
  import { Text } from "@earendil-works/pi-tui";
2
2
  import { plainReason, queuedPhrase } from "./view.js";
3
+ import { commandLine, commandText } from "../orchestrator/snapshot.js";
4
+ /** A step's agent, or "command" for a command step. */
5
+ const who = (s) => s.command !== undefined ? "command" : String(s.agent ?? "?");
3
6
  const short = (id) => typeof id === "string" ? (id.length > 12 ? `${id.slice(0, 10)}…` : id) : "";
4
7
  const clip = (s, n) => s.length > n ? `${s.slice(0, n - 1)}…` : s;
5
8
  /** UI §5: One line per tool call: what was asked, never the raw arguments (scripts and task prompts stay out of the transcript). */
@@ -8,15 +11,16 @@ export function callLine(args) {
8
11
  const agents = (list) => {
9
12
  const counts = new Map();
10
13
  for (const s of list)
11
- counts.set(String(s.agent ?? "?"), (counts.get(String(s.agent ?? "?")) ?? 0) + 1);
14
+ counts.set(who(s), (counts.get(who(s)) ?? 0) + 1);
12
15
  return [...counts].map(([a, n]) => n > 1 ? `${a}×${n}` : a).join(", ");
13
16
  };
14
17
  switch (args.action) {
15
18
  case "run": {
16
19
  const what = Array.isArray(args.tasks) ? `${steps.length} in parallel (${agents(steps)})`
17
- : Array.isArray(args.chain) ? `chain of ${steps.length} (${steps.map(s => String(s.agent ?? "?")).join(" → ")})`
20
+ : Array.isArray(args.chain) ? `chain of ${steps.length} (${steps.map(who).join(" → ")})`
18
21
  : typeof args.source === "string" ? `workflow script (${args.source.split("\n").length} lines)`
19
- : typeof args.workflow === "string" ? `workflow ${args.workflow}` : `${String(args.agent ?? "?")}: ${clip(String(args.task ?? "").split("\n")[0], 70)}`;
22
+ : typeof args.workflow === "string" ? `workflow ${args.workflow}`
23
+ : args.command !== undefined ? `command: ${clip(commandLine(commandText(args.command)), 70)}` : `${String(args.agent ?? "?")}: ${clip(String(args.task ?? "").split("\n")[0], 70)}`;
20
24
  return `run ${typeof args.name === "string" ? `${args.name} · ` : ""}${what}`;
21
25
  }
22
26
  case "send": return `send ${String(args.kind ?? "")} → ${String(args.to ?? "")}${typeof args.message === "string" ? `: ${clip(args.message.split("\n")[0], 70)}` : typeof args.model === "string" ? `: ${args.model}` : ""}`;
@@ -32,7 +36,7 @@ export function resultLines(details) {
32
36
  const d = (details ?? {});
33
37
  if (typeof d.wid === "string" && typeof d.key === "string" && typeof d.phase === "string") {
34
38
  const r = d.result;
35
- return [`${d.key} · ${r?.status ?? (d.phase === "queued" ? queuedPhrase(d, Date.now()) : d.phase)}${typeof d.model === "string" ? ` · ${d.model}` : ""}`];
39
+ return [`${d.key} · ${r?.status ?? (d.phase === "queued" ? queuedPhrase(d, Date.now()) : d.phase)}${typeof d.model === "string" ? ` · ${d.model}` : ""}${typeof d.command === "string" ? ` · command: ${commandLine(d.command, 60)}` : ""}`];
36
40
  }
37
41
  if (typeof d.wid === "string" && !Array.isArray(d.calls))
38
42
  return [`started workflow ${d.wid}`, ...(typeof d.paused === "string" ? [`⚠ ${d.paused}`] : [])];
package/dist/ui/view.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
2
- import { answerForwardedNote, isLive, queuedText, labelsText, liveCalls, ownedBy, progressOf } from "../orchestrator/snapshot.js";
2
+ import { answerForwardedNote, commandLine, isLive, queuedText, labelsText, liveCalls, ownedBy, 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) {
@@ -22,6 +22,10 @@ export function modelLabel(model, find, aliases = {}) {
22
22
  const named = (word) => Boolean(word) && new RegExp(`(^|[^a-z0-9])${word.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}([^a-z0-9]|$)`, "i").test(name);
23
23
  return suffix.toLowerCase() === family || named(provider) || named(suffix) ? name : `${name} (${suffix})`;
24
24
  }
25
+ /** UI §2: The model column of a call: a command call shows its command instead ("command: npm test"). */
26
+ export function modelColumn(c, f, name) {
27
+ return c.command !== undefined ? `command: ${commandLine(c.command, 40)}` : name(f?.model ?? c.model);
28
+ }
25
29
  /** UI §2–3: Count committed tool calls compactly; zero is not shown. */
26
30
  export const toolCount = (n) => n ? `${n} tool${n === 1 ? "" : "s"}` : "";
27
31
  /** UI §3, P7: Messages sent to a call whose delivery the child has not confirmed yet; zero is not shown. */
@@ -130,6 +134,11 @@ export function statusPhrase(call, workflow, facts, now) {
130
134
  return `no activity for ${duration(now - Math.max(call.lastActivity ?? call.startedAt ?? now, facts?.lastActivity ?? 0))}`;
131
135
  if (call.phase === "queued")
132
136
  return workflow.paused ? "paused · r resumes" : queuedPhrase(call, now);
137
+ // A command call has no session: its process and how long it runs (from the start of its attempt).
138
+ if (call.command !== undefined) {
139
+ const run = call.commandRun, age = duration(Math.max(0, now - (call.startedAt ?? now)));
140
+ return run?.pid !== undefined ? `running · pid ${run.pid}${(run.attempt ?? 1) > 1 ? ` · attempt ${run.attempt}` : ""} · ${age}` : `starting · ${age}`;
141
+ }
133
142
  // Liveness (UI §2): the age of the newest evidence ticks, and resets whenever the agent does anything.
134
143
  const since = duration(Math.max(0, now - Math.max(call.lastActivity ?? 0, facts?.lastActivity ?? 0, call.startedAt ?? 0)));
135
144
  if (facts?.activity)
@@ -175,7 +184,8 @@ export function callName(w, c) {
175
184
  return `${c.key}${gen}`;
176
185
  const peers = keys.filter(k => GENERATED.test(k) && w.calls.find(x => x.key === k)?.agent === c.agent)
177
186
  .sort((a, b) => Number(GENERATED.exec(a)[1]) - Number(GENERATED.exec(b)[1]));
178
- return `${c.agent}${peers.length > 1 ? ` ${peers.indexOf(c.key) + 1}` : ""}${gen}`;
187
+ // A command call has no agent: it goes by "command" (numbered like an agent's when there are several).
188
+ return `${c.agent || (c.command !== undefined ? "command" : "")}${peers.length > 1 ? ` ${peers.indexOf(c.key) + 1}` : ""}${gen}`;
179
189
  }
180
190
  const WORDS = { ok: "done", stopped: "stopped", failed: "failed", "gate-failed": "failed", timeout: "timeout", budget: "budget", unknown: "unknown", skipped: "skipped", parked: "parked" };
181
191
  /** v12 §4: The result word of a sealed status — a stopped call is never called failed; timeout/budget/unknown are named as such. */
@@ -240,14 +250,15 @@ export function dockLines(workflows, facts, name, width, now = Date.now(), rows
240
250
  const line = ended && now - (ended.endedAt ?? 0) < 10 * 60_000 ? mainLine(workflows, now) : undefined;
241
251
  return line ? [truncateToWidth(line, Math.max(1, width))] : [];
242
252
  }
243
- const cols = { key: Math.min(20, Math.max(...active.map(a => visibleWidth(callName(a.w, a.c))))), model: Math.min(20, Math.max(...active.map(a => visibleWidth(name(facts.get(a.c.callId)?.model ?? a.c.model))))) };
253
+ const cols = { key: Math.min(20, Math.max(...active.map(a => visibleWidth(callName(a.w, a.c))))), model: Math.min(20, Math.max(...active.map(a => visibleWidth(modelColumn(a.c, facts.get(a.c.callId), name))))) };
244
254
  const shown = active.slice(0, rows);
245
255
  const lines = shown.map(({ w, c, asking }) => {
246
256
  // A running tool is activity; otherwise a minute without new evidence (no message, no tool) stops the spinner.
247
- const f = facts.get(c.callId), fresh = Boolean(f?.activity) || now - Math.max(c.lastActivity ?? 0, f?.lastActivity ?? 0, c.startedAt ?? 0) < 60_000;
257
+ // A running command call is busy as long as its process runs.
258
+ const f = facts.get(c.callId), fresh = Boolean(f?.activity) || c.command !== undefined && c.phase === "running" || now - Math.max(c.lastActivity ?? 0, f?.lastActivity ?? 0, c.startedAt ?? 0) < 60_000;
248
259
  const mark = asking ? "?" : c.phase === "queued" ? "·" : fresh ? SPIN[Math.floor(now / 500) % SPIN.length] : "…";
249
260
  const phrase = answerForwardedNote(c, now) || (asking ? `asks: ${w.attention.find(a => a.kind === "question" && a.call === c.callId).text}` : statusPhrase(c, w, f, now));
250
- return rowText(`${mark} `, callName(w, c), name(f?.model ?? c.model), phrase, [], width, cols);
261
+ return rowText(`${mark} `, callName(w, c), modelColumn(c, f, name), phrase, [], width, cols);
251
262
  });
252
263
  const more = active.length - shown.length;
253
264
  lines.push(truncateToWidth(`${more ? `+${more} more · ` : ""}${summaryText(workflows, now)} · ↓ subagents`, Math.max(1, width)));
@@ -290,11 +301,11 @@ export function listRows(workflows, state, facts, name, width, now = Date.now())
290
301
  // Aligned columns across the whole list (UI §2): key and model start at the same column on every row.
291
302
  const shownCalls = visible.flatMap(w => w.calls.map(c => ({ w, c })));
292
303
  const cols = { key: Math.min(24, Math.max(0, ...shownCalls.map(({ w, c }) => visibleWidth(callName(w, c))))),
293
- model: Math.min(26, Math.max(0, ...shownCalls.map(({ c }) => visibleWidth(name(facts.get(c.callId)?.model ?? c.model))))) };
304
+ model: Math.min(26, Math.max(0, ...shownCalls.map(({ c }) => visibleWidth(modelColumn(c, facts.get(c.callId), name))))) };
294
305
  const callRow = (w, c, indent, preview, dim = false) => {
295
306
  const f = facts.get(c.callId), age = c.phase === "sealed" ? `${duration(now - (c.endedAt ?? now))} ago` : c.startedAt ? duration(now - c.startedAt) : "";
296
307
  // A requested switch shows at once (it applies when the current step ends; until then it would look as if it had failed).
297
- const shown = c.switching ? `${name(f?.model ?? c.model)} → ${name(c.switching)}` : name(f?.model ?? c.model);
308
+ const shown = c.switching ? `${name(f?.model ?? c.model)} → ${name(c.switching)}` : modelColumn(c, f, name);
298
309
  const text = rowText(indent, callName(w, c), shown, statusPhrase(c, w, f, now), [pendingMarker(c.pending), toolCount(f?.tools), age], width, cols);
299
310
  rows.push({ id: c.callId, kind: "call", workflow: w, call: c, failed: Boolean(failed(c)), dim, text });
300
311
  // Overview (UI §2): every active agent shows what it last said, thought or saw, without opening it.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-durable-subagents",
3
- "version": "1.0.43",
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",