pi-durable-subagents 1.0.27 → 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.
- package/CHANGELOG.md +41 -0
- package/README.md +121 -10
- package/dist/agent/child.js +7 -2
- package/dist/agent/main/schema.js +4 -1
- package/dist/agent/main/tool.js +42 -8
- package/dist/agent/main.js +62 -12
- package/dist/cli/doctor.js +4 -3
- package/dist/cli/drill/index.js +287 -0
- package/dist/cli/drill/provider.js +25 -0
- package/dist/cli/hold.js +28 -14
- package/dist/cli/main.js +50 -11
- package/dist/cli/requests.js +102 -18
- package/dist/kernel/journal.js +99 -15
- package/dist/kernel/mailbox.js +1 -1
- package/dist/orchestrator/engine.js +157 -12
- package/dist/orchestrator/evaluator-client.js +18 -3
- package/dist/orchestrator/executor/digest.js +80 -0
- package/dist/orchestrator/executor/index.js +47 -37
- package/dist/orchestrator/executor/observe.js +21 -7
- package/dist/orchestrator/notes.js +20 -0
- package/dist/orchestrator/restart.js +5 -3
- package/dist/orchestrator/snapshot.js +144 -21
- package/dist/orchestrator/stats.js +49 -0
- package/dist/platform/containment.js +35 -11
- package/dist/platform/lease.js +37 -11
- package/dist/platform/proctable.js +16 -3
- package/dist/requests.js +27 -0
- package/dist/ui/view.js +5 -2
- package/package.json +1 -1
|
@@ -12,6 +12,7 @@ import { readSession } from "./session.js";
|
|
|
12
12
|
import { entriesOf } from "./indexes.js";
|
|
13
13
|
import { ActiveTime, activeTotal } from "./time.js";
|
|
14
14
|
import { observation, reached, sessionUsage, totalUsage } from "./usage.js";
|
|
15
|
+
const UPDATE = '{"type":"tool_execution_update",';
|
|
15
16
|
export const sessionChanged = (name) => name === null || String(name) === "session.jsonl" || String(name) === "inbox";
|
|
16
17
|
/** A tool call's command for a status line: bash's command, else its arguments, on one line and clipped. */
|
|
17
18
|
export function toolCommand(args) {
|
|
@@ -103,12 +104,17 @@ export async function observeExecution(d) {
|
|
|
103
104
|
const drained = new Promise(resolve => lines.once("close", () => resolve()));
|
|
104
105
|
lines.on("line", line => {
|
|
105
106
|
let event;
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
}
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
107
|
+
// A tool update repeats the tool's whole partial output (tens of KiB per chunk of a chatty command) and is used only
|
|
108
|
+
// as activity evidence below: its type, which pi serializes first, is enough.
|
|
109
|
+
if (line.length > 4096 && line.startsWith(UPDATE) && line.endsWith("}"))
|
|
110
|
+
event = { type: "tool_execution_update" };
|
|
111
|
+
else
|
|
112
|
+
try {
|
|
113
|
+
event = JSON.parse(line);
|
|
114
|
+
}
|
|
115
|
+
catch {
|
|
116
|
+
return;
|
|
117
|
+
}
|
|
112
118
|
if (ending)
|
|
113
119
|
return;
|
|
114
120
|
// P18: Apply RPC boundaries at receipt, before any in-flight scan can resume.
|
|
@@ -163,6 +169,7 @@ export async function observeExecution(d) {
|
|
|
163
169
|
});
|
|
164
170
|
});
|
|
165
171
|
let scanning = false, sessionDirty = false, failingSince;
|
|
172
|
+
let usageList, usageSent = 0;
|
|
166
173
|
const scan = (processes = true) => {
|
|
167
174
|
if (scanning) {
|
|
168
175
|
if (!processes)
|
|
@@ -194,7 +201,14 @@ export async function observeExecution(d) {
|
|
|
194
201
|
}
|
|
195
202
|
const entries = await (d.read ? d.read() : readSession(session));
|
|
196
203
|
await d.questions(entries);
|
|
197
|
-
|
|
204
|
+
const values = d.usage ? d.usage(entries) : sessionUsage(entries, t.callId);
|
|
205
|
+
if (values !== usageList) {
|
|
206
|
+
usageList = values;
|
|
207
|
+
usageSent = 0;
|
|
208
|
+
}
|
|
209
|
+
const count = values.length;
|
|
210
|
+
await d.recordUsage(values.slice(usageSent));
|
|
211
|
+
usageSent = count;
|
|
198
212
|
await limits();
|
|
199
213
|
await stall();
|
|
200
214
|
await noProgress();
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/** The journal entry type of a pending note. */
|
|
2
|
+
export const PENDING_NOTE = "pending-note";
|
|
3
|
+
/** The pending notes of a call key in one revision's entries, in the order they were recorded. */
|
|
4
|
+
export function pendingNotes(log, key) {
|
|
5
|
+
const consumed = new Set(log.filter(e => e.type === "generation").flatMap(e => Array.isArray(e.notes) ? e.notes.map(String) : []));
|
|
6
|
+
return log.filter(e => e.type === PENDING_NOTE && e.key === key && !consumed.has(String(e.rid)));
|
|
7
|
+
}
|
|
8
|
+
/** A notify forwarded to `call` whose fate is not known yet (neither delivered nor retired): at its seal the executor may
|
|
9
|
+
* still turn it into a pending note, so a follow-up (or another note) waits for that first. */
|
|
10
|
+
export function unsettledNotify(log, call) {
|
|
11
|
+
return log.some(e => e.type === "forward" && e.dest === call && e.envelope?.kind === "notify" &&
|
|
12
|
+
!log.some(r => r.rid2 === e.rid2 && (r.type === "forward-retired" || r.type === "forward-delivered")));
|
|
13
|
+
}
|
|
14
|
+
/** The opening message of a follow-up that carries pending notes: every note in order, then the follow-up's own message. */
|
|
15
|
+
export function withNotes(notes, message) {
|
|
16
|
+
if (!notes.length)
|
|
17
|
+
return message;
|
|
18
|
+
const items = notes.map(n => `- ${n.replace(/\n/g, "\n ")}`).join("\n");
|
|
19
|
+
return `Notes recorded after your last turn:\n${items}\n\n${message}`;
|
|
20
|
+
}
|
|
@@ -31,12 +31,14 @@ export function restartRefusal(home, live, body, tool = false, now = Date.now())
|
|
|
31
31
|
// executions (a shell, a systemd unit, another call) keep their lease across the restart; they are listed so the
|
|
32
32
|
// machine is not mistaken for free.
|
|
33
33
|
const leases = new Map(), others = [], calls = new Set(live.map(l => l.callId));
|
|
34
|
-
for (const { resource, holders } of leaseState(home))
|
|
34
|
+
for (const { resource, holders, slots } of leaseState(home))
|
|
35
35
|
for (const t of holders) {
|
|
36
|
+
// A counted resource names how many of its slots are taken: "build 3/5".
|
|
37
|
+
const name = slots !== undefined ? `${resource} ${holders.length}/${slots}` : resource;
|
|
36
38
|
if (t.call && calls.has(t.call))
|
|
37
|
-
leases.set(t.call, [leases.get(t.call), `holds lease ${
|
|
39
|
+
leases.set(t.call, [leases.get(t.call), `holds lease ${name} (${holdDetail(t, now)})`].filter(Boolean).join(", "));
|
|
38
40
|
else
|
|
39
|
-
others.push(` ${
|
|
41
|
+
others.push(` ${name} held by ${who(t)} (${holdDetail(t, now)})`);
|
|
40
42
|
}
|
|
41
43
|
const groups = new Map();
|
|
42
44
|
for (const l of live) {
|
|
@@ -11,6 +11,9 @@ import { emptyLedger, foldLedger } from "./ledger.js";
|
|
|
11
11
|
import { packageVersion } from "../version.js";
|
|
12
12
|
import { worktreeCalls, worktreeLabel } from "./executor/worktree.js";
|
|
13
13
|
import { leaseCalls, leaseLines, leaseState } from "../platform/lease.js";
|
|
14
|
+
import { labelsOf } from "../events/derive.js";
|
|
15
|
+
import { PENDING_NOTE } from "./notes.js";
|
|
16
|
+
import { readStats } from "./stats.js";
|
|
14
17
|
/** A workflow has live work: it runs, or follow-ups opened on it after it finished have not ended yet. */
|
|
15
18
|
export function isLive(wf) {
|
|
16
19
|
return wf.status === "running" || (wf.followUps ?? 0) > 0;
|
|
@@ -59,7 +62,7 @@ function plannedTotal(home, wid, rev) {
|
|
|
59
62
|
const zero = () => ({ input: 0, output: 0, costUsd: 0 });
|
|
60
63
|
const nonzero = (u) => !!u && (u.input > 0 || u.output > 0 || u.costUsd > 0);
|
|
61
64
|
const clip = (text, n) => text.length > n ? `${text.slice(0, n)}…` : text;
|
|
62
|
-
const MESSAGES = new Set(["steer", "follow-up", "answer", "continue", "task"]);
|
|
65
|
+
const MESSAGES = new Set(["steer", "notify", "follow-up", "answer", "continue", "task"]);
|
|
63
66
|
/** P7, P27: A pending send that carries a message to the agent (model switches and withdrawals are controls). */
|
|
64
67
|
export const pendingMessage = (s) => s.state === "pending" && MESSAGES.has(s.kind);
|
|
65
68
|
/** P37: The display name of a call id `wid@r/key@g`: the key, with its generation when later than the first. */
|
|
@@ -89,6 +92,8 @@ function snapshotReducer(wid, entries) {
|
|
|
89
92
|
const tools = new Map();
|
|
90
93
|
// P7, P27: forward / forward-delivered / forward-retired, by destination call; retirements carry only rid2.
|
|
91
94
|
const sends = new Map(), byRid2 = new Map();
|
|
95
|
+
// Pending notes of the current revision by key (notes.ts): recorded rids, and those a generation carried.
|
|
96
|
+
const notes = new Map(), carried = new Set();
|
|
92
97
|
function apply(batch, from = 0) {
|
|
93
98
|
for (let i = from; i < batch.length; i++) {
|
|
94
99
|
const e = batch[i];
|
|
@@ -101,8 +106,11 @@ function snapshotReducer(wid, entries) {
|
|
|
101
106
|
continue;
|
|
102
107
|
const key = String(e.key), gen = Number(e.gen) || (e.type === "refused" ? 0 : 1);
|
|
103
108
|
const callId = e.type === "reused" ? String(e.from) : `${wid}@${rev}/${key}@${gen}`;
|
|
104
|
-
if (e.type === "generation")
|
|
109
|
+
if (e.type === "generation") {
|
|
105
110
|
generations.add(callId);
|
|
111
|
+
for (const rid of Array.isArray(e.notes) ? e.notes : [])
|
|
112
|
+
carried.add(String(rid));
|
|
113
|
+
}
|
|
106
114
|
const result = e.type === "refused" ? refusedResult(key, e.reason) :
|
|
107
115
|
e.type === "reused" ? entries.find(s => s.type === JT.sealed && s.call === e.from)?.result : undefined;
|
|
108
116
|
const wanted = e.spec?.model;
|
|
@@ -112,6 +120,13 @@ function snapshotReducer(wid, entries) {
|
|
|
112
120
|
phase: result ? "sealed" : "queued", ...(result ? { result, endedAt: e.ts } : {}),
|
|
113
121
|
...(e.type === "refused" ? { refused: String(e.reason) } : {}), ...(e.type === "reused" ? { reused: String(e.from) } : {}) });
|
|
114
122
|
}
|
|
123
|
+
else if (e.type === PENDING_NOTE) {
|
|
124
|
+
if (boundary >= 0 && e.seq < entries[boundary].seq)
|
|
125
|
+
continue;
|
|
126
|
+
const set = notes.get(String(e.key)) ?? new Set();
|
|
127
|
+
set.add(String(e.rid));
|
|
128
|
+
notes.set(String(e.key), set);
|
|
129
|
+
}
|
|
115
130
|
else if (e.type === "retired") {
|
|
116
131
|
retired.add(String(e.call));
|
|
117
132
|
}
|
|
@@ -278,6 +293,11 @@ function snapshotReducer(wid, entries) {
|
|
|
278
293
|
c.switching = last.model;
|
|
279
294
|
}
|
|
280
295
|
}
|
|
296
|
+
for (const [key, rids] of notes) {
|
|
297
|
+
const n = [...rids].filter(rid => !carried.has(rid)).length, call = list.findLast(c => c.key === key);
|
|
298
|
+
if (n && call)
|
|
299
|
+
call.notesPending = n;
|
|
300
|
+
}
|
|
281
301
|
const after = done ? list.filter(c => generations.has(c.callId) && c.phase !== "sealed" && !retired.has(c.callId)) : [];
|
|
282
302
|
for (const c of after)
|
|
283
303
|
c.afterEnd = true;
|
|
@@ -357,7 +377,7 @@ const ledgerIndexes = new WeakMap();
|
|
|
357
377
|
export function ledgerIndex(ledger) {
|
|
358
378
|
let ix = ledgerIndexes.get(ledger);
|
|
359
379
|
if (!ix || ix.length > ledger.length || (ix.length && ledger[ix.length - 1] !== ix.last)) {
|
|
360
|
-
ix = { length: 0, created: new Map(), pruned: new Set(), byWid: new Map(), byOrigin: new Map() };
|
|
380
|
+
ix = { length: 0, created: new Map(), pruned: new Set(), labels: new Map(), runLabels: new Map(), byWid: new Map(), byOrigin: new Map() };
|
|
361
381
|
ledgerIndexes.set(ledger, ix);
|
|
362
382
|
}
|
|
363
383
|
for (let i = ix.length; i < ledger.length; i++) {
|
|
@@ -365,9 +385,24 @@ export function ledgerIndex(ledger) {
|
|
|
365
385
|
if (e.type === JT.created) {
|
|
366
386
|
if (!ix.created.has(e.wid))
|
|
367
387
|
ix.created.set(e.wid, e);
|
|
388
|
+
const labels = ix.runLabels.get(String(e.rid));
|
|
389
|
+
if (labels) {
|
|
390
|
+
if (!ix.labels.has(String(e.wid)))
|
|
391
|
+
ix.labels.set(String(e.wid), labels);
|
|
392
|
+
ix.runLabels.delete(String(e.rid));
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
else if (e.type === "request") {
|
|
396
|
+
const r = e.request, labels = r?.kind === "run" ? labelsOf(r.body) : undefined;
|
|
397
|
+
if (labels && typeof r?.rid === "string")
|
|
398
|
+
ix.runLabels.set(r.rid, labels);
|
|
368
399
|
}
|
|
369
|
-
else if (e.type ===
|
|
400
|
+
else if (e.type === JT.rejected)
|
|
401
|
+
ix.runLabels.delete(String(e.rid));
|
|
402
|
+
else if (e.type === "pruned") {
|
|
370
403
|
ix.pruned.add(String(e.wid));
|
|
404
|
+
ix.labels.delete(String(e.wid));
|
|
405
|
+
}
|
|
371
406
|
else if (e.type === "drain" || e.type === "undrain") {
|
|
372
407
|
if (e.type === "drain")
|
|
373
408
|
ix.lastDrain = i;
|
|
@@ -413,12 +448,23 @@ export function heldWorkflows(home) {
|
|
|
413
448
|
const origin = (wid) => ix.created.get(wid)?.origin;
|
|
414
449
|
const hold = (wid) => holdOf(ledger, wid, origin(wid));
|
|
415
450
|
const since = ix.lastDrain !== undefined ? ledger[ix.lastDrain].ts : undefined;
|
|
416
|
-
return { ...(since !== undefined ? { since } : {}), held: wid => hold(wid) !== undefined };
|
|
451
|
+
return { ...(since !== undefined ? { since } : {}), held: wid => hold(wid) !== undefined, labels: wid => ix.labels.get(wid) };
|
|
452
|
+
}
|
|
453
|
+
/** The workflow with its run's labels, when it has any. */
|
|
454
|
+
function labelled(wf, labels) {
|
|
455
|
+
return labels ? { ...wf, labels } : wf;
|
|
456
|
+
}
|
|
457
|
+
/** Labels clipped for one status line: "[k=v k2=v2]", at most `width` characters (empty without labels). */
|
|
458
|
+
export function labelsText(labels, width = 60) {
|
|
459
|
+
if (!labels)
|
|
460
|
+
return "";
|
|
461
|
+
const text = Object.entries(labels).map(([k, v]) => `${k}=${v}`).join(" ").replace(/\s+/g, " ");
|
|
462
|
+
return text ? `[${clip(text, Math.max(1, width - 3))}]` : "";
|
|
417
463
|
}
|
|
418
464
|
/** P25: Snapshot every workflow under DSA_HOME (newest first by wid, which is a ULID); `paused` marks work a drain holds. */
|
|
419
465
|
export function allWorkflows(home) {
|
|
420
|
-
const { held } = heldWorkflows(home);
|
|
421
|
-
return workflowIds(home).sort().reverse().map(wid => { const wf = workflowSnapshot(home, wid); return isLive(wf) && held(wid) ? { ...wf, paused: true } : wf; });
|
|
466
|
+
const { held, labels } = heldWorkflows(home);
|
|
467
|
+
return workflowIds(home).sort().reverse().map(wid => { const wf = labelled(workflowSnapshot(home, wid), labels(wid)); return isLive(wf) && held(wid) ? { ...wf, paused: true } : wf; });
|
|
422
468
|
}
|
|
423
469
|
/** P10/P11: Per-workflow script console log written by the orchestrator (bounded, human-readable). */
|
|
424
470
|
export function scriptLogPath(home, wid) { return join(workflowDir(home, wid), "script.log"); }
|
|
@@ -441,10 +487,11 @@ export function compactWorkflow(wf, leases) {
|
|
|
441
487
|
...(c.sharedWorktree ? { sharedWorktree: c.sharedWorktree } : {}),
|
|
442
488
|
...(c.model ? { model: c.model } : {}), ...(c.tools ? { tools: c.tools } : {}), ...(c.pending ? { pending: c.pending } : {}), ...(c.switching ? { switching: c.switching } : {}), ...(c.switchFailed ? { switchFailed: c.switchFailed } : {}), ...(nonzero(c.usage) ? { usage: c.usage } : {}),
|
|
443
489
|
...(last ? { lastLine: clip(last, 200) } : {}), ...(r?.error ? { error: clip(r.error, 300) } : {}), ...(c.hibernated ? { hibernated: true } : {}),
|
|
444
|
-
...(c.writerWait && !r ? { writerWait: c.writerWait } : {}), ...(!r && leases?.get(c.callId) ? { lease: leases.get(c.callId) } : {})
|
|
490
|
+
...(c.writerWait && !r ? { writerWait: c.writerWait } : {}), ...(!r && leases?.get(c.callId) ? { lease: leases.get(c.callId) } : {}),
|
|
491
|
+
...(c.notesPending ? { notesPending: c.notesPending } : {}) };
|
|
445
492
|
}),
|
|
446
493
|
attention: wf.attention.map(a => ({ id: a.id, rev: a.rev, kind: a.kind, text: clip(a.text, 300), ...(a.call ? { call: a.call } : {}), ...(a.qid ? { qid: a.qid } : {}) })),
|
|
447
|
-
...(wf.paused ? { paused: true } : {}), ...(wf.followUps ? { followUps: wf.followUps } : {}),
|
|
494
|
+
...(wf.paused ? { paused: true } : {}), ...(wf.followUps ? { followUps: wf.followUps } : {}), ...(wf.labels ? { labels: wf.labels } : {}),
|
|
448
495
|
};
|
|
449
496
|
}
|
|
450
497
|
function origins(home) {
|
|
@@ -461,9 +508,9 @@ function origins(home) {
|
|
|
461
508
|
/** Every workflow with its origin and hold, own session first, then newest first. */
|
|
462
509
|
function snapshots(home, origin) {
|
|
463
510
|
const own = (w) => Number(!!origin && w.origin === origin);
|
|
464
|
-
const { since, held } = heldWorkflows(home);
|
|
511
|
+
const { since, held, labels } = heldWorkflows(home);
|
|
465
512
|
const all = [...origins(home)].sort(([a], [b]) => a < b ? 1 : a > b ? -1 : 0).map(([wid, origin]) => {
|
|
466
|
-
const wf = workflowSnapshot(home, wid), withOrigin = wf.origin === undefined && origin !== undefined ? { ...wf, origin } : wf;
|
|
513
|
+
const wf = labelled(workflowSnapshot(home, wid), labels(wid)), withOrigin = wf.origin === undefined && origin !== undefined ? { ...wf, origin } : wf;
|
|
467
514
|
return isLive(withOrigin) && held(wid) ? { ...withOrigin, paused: true } : withOrigin;
|
|
468
515
|
}).sort((a, b) => own(b) - own(a));
|
|
469
516
|
return { all, ...(since !== undefined ? { since } : {}) };
|
|
@@ -478,7 +525,14 @@ export function statusView(home, options = {}) {
|
|
|
478
525
|
const paused = all.filter(w => w.paused).length;
|
|
479
526
|
return { workflows: shown.map(w => compactWorkflow(w, byCall)), ...(hidden ? { olderFinished: hidden, hint: "status wid=<wid> shows any workflow in detail" } : {}),
|
|
480
527
|
...(paused ? { paused: `${paused} workflow${paused > 1 ? "s" : ""} paused (stop-all, drain or a quit pi) since ${new Date(since).toISOString()}; resume continues them (new runs are not affected)` } : {}),
|
|
481
|
-
...slotsView(home), ...(leases.length ? { leases: leaseLines(leases) } : {}) };
|
|
528
|
+
...slotsView(home), ...(leases.length ? { leases: leaseLines(leases) } : {}), ...runningStats(home) };
|
|
529
|
+
}
|
|
530
|
+
/** The stats the running orchestrator published (none when no orchestrator runs). */
|
|
531
|
+
export function runningStats(home) {
|
|
532
|
+
const path = orchLedger(home), state = foldLedger(ledgerStates.get(path) ?? emptyLedger(), readJournalSnapshot(path));
|
|
533
|
+
ledgerStates.set(path, state);
|
|
534
|
+
const o = state.orchestrator, stats = o && !o.exited && processAlive(o.pid, o.start) ? readStats(home, o.pid) : undefined;
|
|
535
|
+
return stats ? { orchestratorStats: stats } : {};
|
|
482
536
|
}
|
|
483
537
|
const FINAL = ["done", "failed", "stopped"];
|
|
484
538
|
/** Finished with nothing left running (a follow-up on a finished workflow is live work). */
|
|
@@ -537,6 +591,20 @@ export function versionNote(running, loaded) {
|
|
|
537
591
|
`restart (\`pi-durable-subagents restart\` or the subagents tool's restart action) — refused while an execution runs, ` +
|
|
538
592
|
`calls waiting for an answer or a slot do not block it; force with the refusal's token, a reason and explicit user approval fences running executions, which resume on the new version`;
|
|
539
593
|
}
|
|
594
|
+
/** The first version whose orchestrator and child know send kind "notify". */
|
|
595
|
+
export const NOTIFY_SINCE = "1.0.28";
|
|
596
|
+
/** A refusal when the orchestrator running now predates `since` and is older than the version this process loaded (an
|
|
597
|
+
* older orchestrator would accept the request and its child would drop it); none when none runs (the next one starts
|
|
598
|
+
* on the installed version) or it is current. */
|
|
599
|
+
export function orchestratorTooOld(home, feature, since, loaded = packageVersion()) {
|
|
600
|
+
const path = orchLedger(home), state = foldLedger(ledgerStates.get(path) ?? emptyLedger(), readJournalSnapshot(path));
|
|
601
|
+
ledgerStates.set(path, state);
|
|
602
|
+
const o = state.orchestrator;
|
|
603
|
+
if (!o || o.exited || !processAlive(o.pid, o.start) || !newer(since, o.version) || !newer(loaded, o.version))
|
|
604
|
+
return undefined;
|
|
605
|
+
return `the running orchestrator ${o.version} predates ${feature} (new in ${since}); restart it to the installed version ${loaded} first ` +
|
|
606
|
+
`(\`pi-durable-subagents restart\` or the subagents tool's restart action), then send again`;
|
|
607
|
+
}
|
|
540
608
|
/** orchestratorView of the home's orchestrator ledger. */
|
|
541
609
|
export function runningOrchestrator(home) {
|
|
542
610
|
const path = orchLedger(home), state = foldLedger(ledgerStates.get(path) ?? emptyLedger(), readJournalSnapshot(path));
|
|
@@ -576,12 +644,14 @@ export function statusBrief(home, options = {}) {
|
|
|
576
644
|
const mine = (w) => !origin || w.origin === origin;
|
|
577
645
|
const line = (w) => {
|
|
578
646
|
const p = progressOf(w), notOk = latestCalls(w).filter(c => c.result && !c.result.ok).length;
|
|
579
|
-
|
|
647
|
+
const notes = latestCalls(w).reduce((n, c) => n + (c.notesPending ?? 0), 0);
|
|
648
|
+
return [w.wid, labelsText(w.labels), w.name, `${w.paused ? "paused" : w.followUps ? `${w.status}, follow-up running` : w.status}`, `${p.done}/${p.total}${p.plus ? "+" : ""} done`, notOk ? `${notOk} not ok` : "",
|
|
649
|
+
notes ? `${notes} note${notes > 1 ? "s" : ""} pending` : "",
|
|
580
650
|
w.endedAt !== undefined ? `ended ${age(now - w.endedAt)} ago` : w.startedAt !== undefined ? `started ${age(now - w.startedAt)} ago` : ""].filter(Boolean).join(" · ");
|
|
581
651
|
};
|
|
582
652
|
const brief = (w) => {
|
|
583
653
|
const p = progressOf(w), open = w.attention.filter(a => a.kind !== "finished");
|
|
584
|
-
const calls = latestCalls(w).filter(c => c.phase !== "sealed" || (c.result && !c.result.ok)).map((c) => {
|
|
654
|
+
const calls = latestCalls(w).filter(c => c.phase !== "sealed" || (c.result && !c.result.ok) || c.notesPending).map((c) => {
|
|
585
655
|
const live = c.phase !== "sealed", quiet = c.lastActivity !== undefined ? now - c.lastActivity : undefined;
|
|
586
656
|
return { key: c.key, agent: c.agent, phase: c.phase, ...(c.model ? { model: c.model } : {}),
|
|
587
657
|
...(c.sharedWorktree ? { sharedWorktree: c.sharedWorktree } : {}),
|
|
@@ -591,12 +661,13 @@ export function statusBrief(home, options = {}) {
|
|
|
591
661
|
...(c.result ? { status: c.result.status, ...(c.result.error ? { error: clip(c.result.error, 200) } : {}) } : {}),
|
|
592
662
|
...(c.hibernated ? { hibernated: true } : {}), ...(live && c.writerWait ? { writerWait: c.writerWait } : {}),
|
|
593
663
|
...(live && byCall.get(c.callId) ? { lease: byCall.get(c.callId) } : {}),
|
|
594
|
-
...(live && c.switching ? { switching: c.switching } : {}), ...(live && c.switchFailed ? { switchFailed: c.switchFailed } : {})
|
|
664
|
+
...(live && c.switching ? { switching: c.switching } : {}), ...(live && c.switchFailed ? { switchFailed: c.switchFailed } : {}),
|
|
665
|
+
...(c.notesPending ? { notesPending: c.notesPending } : {}) };
|
|
595
666
|
});
|
|
596
667
|
const asking = open.filter(a => a.kind === "question" && a.call).map(a => ({ to: `${w.wid}/${callKey(a.call)}`, ...(a.qid ? { qid: a.qid } : {}),
|
|
597
668
|
...(w.calls.some(c => c.callId === a.call && c.hibernated) ? { hibernated: true } : {}), question: clip(a.text, 300) }));
|
|
598
669
|
const alerts = open.filter(a => a.kind !== "question").map(a => `${a.kind}${a.call ? ` ${w.wid}/${callKey(a.call)}` : ""}: ${clip(a.text, 200)}`);
|
|
599
|
-
return { wid: w.wid, ...(w.name ? { name: w.name } : {}), status: w.status, ...(w.paused ? { paused: true } : {}), ...(w.followUps ? { followUps: w.followUps } : {}),
|
|
670
|
+
return { wid: w.wid, ...(w.labels ? { labels: labelsText(w.labels) } : {}), ...(w.name ? { name: w.name } : {}), status: w.status, ...(w.paused ? { paused: true } : {}), ...(w.followUps ? { followUps: w.followUps } : {}),
|
|
600
671
|
progress: `${p.done}/${p.total}${p.plus ? "+" : ""}`, tokens: tokens(w.usage), calls,
|
|
601
672
|
...(asking.length ? { asking } : {}), ...(alerts.length ? { alerts } : {}) };
|
|
602
673
|
};
|
|
@@ -624,14 +695,63 @@ export function widOfRid(ledger, value) {
|
|
|
624
695
|
const created = head ? ledger.find(e => e.type === JT.created && e.rid === head) : undefined;
|
|
625
696
|
return created ? `${String(created.wid)}${value.slice(head.length)}` : value;
|
|
626
697
|
}
|
|
698
|
+
export const WRITER_WAIT_HINT = "a call waits for its worktree's writer lock (one call that may edit/write runs per worktree); writer:false (when it does not write there) or isolation:'worktree' opts out";
|
|
699
|
+
/** The unsealed calls of `wid` that wait for a writer lock now (a read of its journal; nothing waits for one). */
|
|
700
|
+
export function writerWaits(home, wid) {
|
|
701
|
+
if (!existsSync(journalPath(home, wid)))
|
|
702
|
+
return [];
|
|
703
|
+
return latestCalls(workflowSnapshot(home, wid)).filter(c => c.writerWait && c.phase !== "sealed")
|
|
704
|
+
.map(c => ({ call: `${wid}/${c.key}`, heldBy: c.writerWait.holder, cwd: c.writerWait.root }));
|
|
705
|
+
}
|
|
706
|
+
/** One line per waiting call: "<wid>/<key> held by <wid>/<key> (<cwd>)". */
|
|
707
|
+
export const writerWaitLine = (w) => `${w.call} held by ${w.heldBy} (${w.cwd})`;
|
|
627
708
|
const OUTPUT = 600;
|
|
709
|
+
/** Most characters of one call's selected lines (the last ones are kept). */
|
|
710
|
+
export const SELECT_MAX = 4000;
|
|
711
|
+
/** A valid selection (throws a usage error otherwise); undefined when neither is given. */
|
|
712
|
+
export function outputSelect(tail, grep) {
|
|
713
|
+
if (tail === undefined && grep === undefined)
|
|
714
|
+
return undefined;
|
|
715
|
+
if (tail !== undefined && (!Number.isSafeInteger(tail) || Number(tail) < 1))
|
|
716
|
+
throw new Error("tail must be a positive integer (lines)");
|
|
717
|
+
if (grep !== undefined && (typeof grep !== "string" || !grep))
|
|
718
|
+
throw new Error("grep must be a non-empty regular expression");
|
|
719
|
+
let regex;
|
|
720
|
+
if (typeof grep === "string")
|
|
721
|
+
try {
|
|
722
|
+
regex = new RegExp(grep);
|
|
723
|
+
}
|
|
724
|
+
catch (error) {
|
|
725
|
+
throw new Error(`grep is not a valid regular expression: ${error.message}`);
|
|
726
|
+
}
|
|
727
|
+
return { ...(tail !== undefined ? { tail: Number(tail) } : {}), ...(typeof grep === "string" ? { grep } : {}), ...(regex ? { regex } : {}) };
|
|
728
|
+
}
|
|
729
|
+
/** grep runs the caller's regular expression in this process (the pi session or the CLI): it tests at most the first
|
|
730
|
+
* GREP_LINE_CHARS characters of a line, and only the last GREP_MAX_LINES lines of each output, to bound its cost. */
|
|
731
|
+
export const GREP_LINE_CHARS = 2000, GREP_MAX_LINES = 5000;
|
|
732
|
+
/** The selected lines of `output`, unclipped up to SELECT_MAX characters (then its last SELECT_MAX, marked). */
|
|
733
|
+
export function selectLines(output, select) {
|
|
734
|
+
const regex = select.regex ?? (select.grep !== undefined ? new RegExp(select.grep) : undefined);
|
|
735
|
+
let lines = output.replace(/\n+$/, "").split("\n"), skipped = 0;
|
|
736
|
+
if (regex) {
|
|
737
|
+
skipped = Math.max(0, lines.length - GREP_MAX_LINES);
|
|
738
|
+
lines = lines.slice(skipped).filter(line => regex.test(line.length > GREP_LINE_CHARS ? line.slice(0, GREP_LINE_CHARS) : line));
|
|
739
|
+
}
|
|
740
|
+
if (select.tail !== undefined)
|
|
741
|
+
lines = lines.slice(-select.tail);
|
|
742
|
+
const text = lines.join("\n"), note = skipped ? `[${skipped} earlier lines not searched]\n` : "";
|
|
743
|
+
return note + (text.length > SELECT_MAX ? `[${text.length - SELECT_MAX} earlier chars clipped]...${text.slice(-SELECT_MAX)}` : text);
|
|
744
|
+
}
|
|
628
745
|
/** Tool status with a wid: one workflow with each call's output clipped (the full detail repeated every output twice and
|
|
629
|
-
* reached ~100K characters); `key` gives one call in full. */
|
|
630
|
-
export function statusCompactDetail(home, wid) {
|
|
746
|
+
* reached ~100K characters); `key` gives one call in full. With `select`, each output is its selected lines instead. */
|
|
747
|
+
export function statusCompactDetail(home, wid, select) {
|
|
631
748
|
const detail = statusDetail(home, wid), compact = compactWorkflow(detail);
|
|
632
749
|
const byId = new Map(detail.calls.map(c => [c.callId, c]));
|
|
633
750
|
const calls = compact.calls.map(({ lastLine: _l, ...c }) => {
|
|
634
|
-
const full = byId.get(c.callId)
|
|
751
|
+
const full = byId.get(c.callId);
|
|
752
|
+
if (select)
|
|
753
|
+
return { ...c, agent: full.agent, ...(full.result ? { output: selectLines(full.result.output ?? "", select) } : {}) };
|
|
754
|
+
const output = full.result?.output?.trim();
|
|
635
755
|
return { ...c, agent: full.agent, ...(output ? { output: output.length > OUTPUT ? `${output.slice(0, OUTPUT)}… [${output.length - OUTPUT} more chars: status wid key=${c.key}]` : output } : {}) };
|
|
636
756
|
});
|
|
637
757
|
let result;
|
|
@@ -655,7 +775,7 @@ export function statusDetail(home, wid) {
|
|
|
655
775
|
const origin = origins(home);
|
|
656
776
|
if (!origin.has(wid))
|
|
657
777
|
throw new Error(prunedIds(home).has(wid) ? `Workflow ${wid} was pruned` : `Unknown workflow: ${wid}`);
|
|
658
|
-
const wf = workflowSnapshot(home, wid), log = scriptLogPath(home, wid);
|
|
778
|
+
const wf = labelled(workflowSnapshot(home, wid), heldWorkflows(home).labels(wid)), log = scriptLogPath(home, wid);
|
|
659
779
|
return { ...wf, ...(wf.origin === undefined && origin.get(wid) !== undefined ? { origin: origin.get(wid) } : {}), ...(existsSync(log) ? { scriptLog: log } : {}) };
|
|
660
780
|
}
|
|
661
781
|
/** P25, T10: Project a workflow journal into meaningful events (no observations, time or tracking). */
|
|
@@ -711,7 +831,10 @@ export function eventsFromEntries(entries) {
|
|
|
711
831
|
break;
|
|
712
832
|
case "forward": {
|
|
713
833
|
forwards.set(String(e.rid2), e);
|
|
714
|
-
|
|
834
|
+
// A model switch names its target, and a failover (the executor moved the call off a used-up provider) its source.
|
|
835
|
+
const envelope = e.envelope;
|
|
836
|
+
const target = envelope?.kind === "model" && envelope.body?.model ? (envelope.body.provider ? `${envelope.body.provider}/${envelope.body.model}` : envelope.body.model) : undefined;
|
|
837
|
+
add(e, "forward", { rid: e.rid, kind: envelope?.kind, dest: e.dest, model: target, failover: typeof e.failover === "string" ? e.failover : undefined });
|
|
715
838
|
break;
|
|
716
839
|
}
|
|
717
840
|
case "forward-delivered":
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
// What the running orchestrator costs, for `status --json` and `doctor`: the orchestrator writes these counters of its
|
|
2
|
+
// own process to $DSA_HOME/orchestrator-stats.json every STATS_EVERY_MS (atomic replace, no fsync: a lost write only
|
|
3
|
+
// shows older numbers). Readers show them only when the pid in the file is the orchestrator the ledger records as running.
|
|
4
|
+
import { readFileSync } from "node:fs";
|
|
5
|
+
import { rename, rm, writeFile } from "node:fs/promises";
|
|
6
|
+
import { join } from "node:path";
|
|
7
|
+
export const STATS_EVERY_MS = 10_000;
|
|
8
|
+
export const statsPath = (home) => join(home, "orchestrator-stats.json");
|
|
9
|
+
/** /proc/self/io rchar, or undefined where there is none. */
|
|
10
|
+
export function readBytes() {
|
|
11
|
+
if (process.platform !== "linux")
|
|
12
|
+
return undefined;
|
|
13
|
+
try {
|
|
14
|
+
const match = /^rchar:\s*(\d+)$/m.exec(readFileSync("/proc/self/io", "utf8"));
|
|
15
|
+
return match ? Number(match[1]) : undefined;
|
|
16
|
+
}
|
|
17
|
+
catch {
|
|
18
|
+
return undefined;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
export async function writeStats(home, stats) {
|
|
22
|
+
const path = statsPath(home), temp = join(home, `.orchestrator-stats.${process.pid}.tmp`);
|
|
23
|
+
try {
|
|
24
|
+
await writeFile(temp, JSON.stringify(stats));
|
|
25
|
+
await rename(temp, path);
|
|
26
|
+
}
|
|
27
|
+
catch (error) {
|
|
28
|
+
await rm(temp, { force: true });
|
|
29
|
+
throw error;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
/** The stats file of orchestrator `pid`, or undefined (missing, unreadable, or written by another process). */
|
|
33
|
+
export function readStats(home, pid) {
|
|
34
|
+
if (pid === undefined)
|
|
35
|
+
return undefined;
|
|
36
|
+
try {
|
|
37
|
+
const stats = JSON.parse(readFileSync(statsPath(home), "utf8"));
|
|
38
|
+
return stats && typeof stats === "object" && stats.pid === pid && typeof stats.workflows === "number" ? stats : undefined;
|
|
39
|
+
}
|
|
40
|
+
catch {
|
|
41
|
+
return undefined;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
const megabytes = (n) => n >= 1e9 ? `${(n / 1e9).toFixed(1)} GB` : n >= 1e6 ? `${(n / 1e6).toFixed(0)} MB` : `${(n / 1e3).toFixed(0)} KB`;
|
|
45
|
+
/** One line: "3 live / 190 workflows, 3 journals open, 0.4 passes/s, read 12 MB". */
|
|
46
|
+
export function statsLine(s) {
|
|
47
|
+
return `${s.liveWorkflows} live / ${s.workflows} workflows, ${s.openJournals} journal${s.openJournals === 1 ? "" : "s"} open, ${s.passesPerSecond} passes/s` +
|
|
48
|
+
(s.readBytes !== undefined ? `, read ${megabytes(s.readBytes)}` : "");
|
|
49
|
+
}
|
|
@@ -53,23 +53,47 @@ export class Containment {
|
|
|
53
53
|
if (p.tag !== undefined)
|
|
54
54
|
execs.add(p.tag);
|
|
55
55
|
const result = new Map(), liveStarts = new Map(all.map(p => [p.pid, p.start]));
|
|
56
|
+
// One index of the table per scan: tagged processes and children by parent, so each execution costs its own tree.
|
|
57
|
+
const tagged = new Map(), children = new Map();
|
|
58
|
+
for (const p of all) {
|
|
59
|
+
if (p.tag !== undefined) {
|
|
60
|
+
const list = tagged.get(p.tag);
|
|
61
|
+
if (list)
|
|
62
|
+
list.push(p);
|
|
63
|
+
else
|
|
64
|
+
tagged.set(p.tag, [p]);
|
|
65
|
+
}
|
|
66
|
+
const list = children.get(p.ppid);
|
|
67
|
+
if (list)
|
|
68
|
+
list.push(p);
|
|
69
|
+
else
|
|
70
|
+
children.set(p.ppid, [p]);
|
|
71
|
+
}
|
|
56
72
|
for (const exec of execs) {
|
|
57
73
|
// Historical identities cannot select an absent/reused pid. Avoid allocating a string/Set entry for each one.
|
|
58
|
-
const ids = new
|
|
74
|
+
const ids = new Map();
|
|
59
75
|
for (const group of [known.get(exec) ?? [], this.launched.get(exec) ?? []])
|
|
60
76
|
for (const p of group)
|
|
61
77
|
if (p.start !== "" && liveStarts.get(p.pid) === p.start)
|
|
62
|
-
ids.
|
|
63
|
-
const
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
if (!selected.has(p.pid) && selected.has(p.ppid)) {
|
|
69
|
-
selected.set(p.pid, p);
|
|
70
|
-
changed = true;
|
|
71
|
-
}
|
|
78
|
+
ids.set(p.pid, p.start);
|
|
79
|
+
const own = tagged.get(exec);
|
|
80
|
+
// Nothing tagged and no live identity selects nothing (most execs of a sweep are history).
|
|
81
|
+
if (!ids.size && !own) {
|
|
82
|
+
result.set(exec, []);
|
|
83
|
+
continue;
|
|
72
84
|
}
|
|
85
|
+
// The tagged and the known live processes in table order, then every live descendant (breadth first).
|
|
86
|
+
const selected = new Map();
|
|
87
|
+
for (const p of all)
|
|
88
|
+
if (p.tag === exec || ids.get(p.pid) === p.start)
|
|
89
|
+
selected.set(p.pid, p);
|
|
90
|
+
const queue = [...selected.keys()];
|
|
91
|
+
for (let i = 0; i < queue.length; i++)
|
|
92
|
+
for (const c of children.get(queue[i]) ?? [])
|
|
93
|
+
if (!selected.has(c.pid)) {
|
|
94
|
+
selected.set(c.pid, c);
|
|
95
|
+
queue.push(c.pid);
|
|
96
|
+
}
|
|
73
97
|
result.set(exec, [...selected.values()]);
|
|
74
98
|
}
|
|
75
99
|
return result;
|
package/dist/platform/lease.js
CHANGED
|
@@ -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.
|
|
5
|
-
//
|
|
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
|
|
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
|
-
|
|
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`;
|
|
@@ -196,8 +211,6 @@ async function numbered(home, ticket, now, lock) {
|
|
|
196
211
|
await handle.release();
|
|
197
212
|
}
|
|
198
213
|
}
|
|
199
|
-
/** Every resource with live tickets: holders (granted) and waiters, in request order. Cheap: a directory listing,
|
|
200
|
-
* small files and a liveness check of the few ticket processes. */
|
|
201
214
|
export function leaseState(home) {
|
|
202
215
|
let resources;
|
|
203
216
|
try {
|
|
@@ -207,22 +220,35 @@ export function leaseState(home) {
|
|
|
207
220
|
return [];
|
|
208
221
|
}
|
|
209
222
|
return resources.map(resource => {
|
|
210
|
-
const tickets = liveTickets(home, resource);
|
|
211
|
-
|
|
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 } : {}) };
|
|
212
226
|
}).filter(r => r.holders.length || r.waiters.length);
|
|
213
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
|
+
}
|
|
214
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`;
|
|
215
234
|
const clip = (s, n) => s.length > n ? `${s.slice(0, n - 1)}…` : s;
|
|
216
235
|
/** "<wid>/<key>" of a call id "<wid>@<rev>/<key>@<gen>". */
|
|
217
236
|
export const callAddress = (call) => { const m = /^([^@/]+)@\d+\/(.+)@\d+$/.exec(call); return m ? `${m[1]}/${m[2]}` : call; };
|
|
218
237
|
/** Who holds or waits: the subagent call when there is one, else the pid and command. */
|
|
219
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;
|
|
220
241
|
/** A granted ticket's mode, how long it has been held, the command (unless `who` already names it) and the note:
|
|
221
242
|
* "exclusive, 12m, `make bench`, nightly". */
|
|
222
|
-
export const holdDetail = (t, now = Date.now(), command = !!t.call) => `${t
|
|
223
|
-
/** 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)". */
|
|
224
246
|
export function leaseLines(state, now = Date.now()) {
|
|
225
|
-
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
|
+
}
|
|
226
252
|
const held = holders.length ? `held by ${holders.map(t => `${who(t)} (${holdDetail(t, now)})`).join(", ")}` : "free";
|
|
227
253
|
return `${resource} ${held}${waiters.length ? `; waiting: ${waiters.map(t => `${who(t)} ${t.mode === "shared" ? "shared " : ""}${age(now - t.since)}`).join(", ")}` : ""}`;
|
|
228
254
|
});
|