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.
- package/CHANGELOG.md +73 -0
- package/README.md +135 -15
- 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 +42 -17
- package/dist/cli/main.js +50 -11
- package/dist/cli/requests.js +105 -19
- package/dist/events/derive.js +7 -3
- 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/executor/session.js +4 -2
- 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 +53 -11
- package/dist/platform/proctable.js +16 -3
- package/dist/requests.js +31 -0
- package/dist/ui/session.js +2 -2
- 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();
|
|
@@ -136,7 +136,9 @@ export function evidence(entries, exec) {
|
|
|
136
136
|
/** Only explicit payment failures are terminal; rate limits, overload and transport errors still retry, and a used-up
|
|
137
137
|
* usage window (`quotaExhausted`) waits for the provider or moves to another one. */
|
|
138
138
|
export function fatalProviderError(text) {
|
|
139
|
-
|
|
139
|
+
// Chinese "balance", but not inside "remaining quota": "remaining quota is 0, resets at 00:00 the next day" is a daily
|
|
140
|
+
// window. CJK text is written as \u escapes (the repository is ASCII-only English).
|
|
141
|
+
return /\b402\b|insufficient[_ ]?(quota|balance|funds)|billing|credit balance|(?<!\u5269)\u4f59\u989d/i.test(text);
|
|
140
142
|
}
|
|
141
143
|
/** A provider's usage window is used up: its requests are refused (and not counted) until the window resets, hours
|
|
142
144
|
* later. Seen as a gateway's `503 No available accounts` once pi's own retries are spent, or a usage-limit message.
|
|
@@ -150,7 +152,7 @@ export function quotaExhausted(text) {
|
|
|
150
152
|
// per minute"): pi's retries and the lost-execution path handle it; it must not take the provider out for minutes.
|
|
151
153
|
if (/rate.?limit|too many requests|request limit|per (second|minute)|\b[RT]PM\b|resets? in \d+ ?(ms|s|secs?|seconds?|minutes?)\b/i.test(text))
|
|
152
154
|
return false;
|
|
153
|
-
return /usage limit|quota (exceeded|exhausted)|exceeded your (current )?(usage|quota)|limit (reached|exceeded)[^.]*resets?\b
|
|
155
|
+
return /usage limit|quota (exceeded|exhausted)|exceeded your (current )?(usage|quota)|limit (reached|exceeded)[^.]*resets?\b|\u989d\u5ea6/i.test(text);
|
|
154
156
|
}
|
|
155
157
|
/** A refusal of the request's content (terms of service, usage or content policy): the same request is refused again,
|
|
156
158
|
* on this provider and usually on another, so it is reported at once instead of retried as a lost execution. */
|
|
@@ -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;
|