pi-durable-subagents 1.0.38 → 1.0.39

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 CHANGED
@@ -1,5 +1,22 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.0.39
4
+
5
+ - A pi session reads only its own workflows. Since 1.0.30 the UI shows only the workflows of its session, yet the pi
6
+ process read, folded and cached every workflow journal of the machine every 500 ms. Ownership is now decided from
7
+ the orchestrator ledger (the origin of a workflow's create-intent or `created`, or the session its run named)
8
+ before any journal is opened, so other sessions' journals are never opened, stat'ed or cached by a pi process.
9
+ Measured on a home with 1,132 workflows (load 16-27): the first refresh of a busy session fell from 9.4 s to 1.6 s,
10
+ a steady refresh from 86 ms to 7 ms and the process RSS from 696 MiB to 325 MiB; a session without workflows went
11
+ from 17.7 s to 0.4 s and 683 MiB to 166 MiB. A session that many runs name (here 759 workflows) still reads all of
12
+ them, so its gain is smaller. `scripts/bench-ui.ts` measures this (read-only).
13
+ - Session start no longer scans every journal: the starter checks whether an orchestrator holds its lock first and
14
+ scans only when none does; the scan stops at the first unfinished workflow and does not keep the journals it read.
15
+ The paused notice at session start and the pause on quit read only the workflows the session started.
16
+ - A workflow directory the ledger does not know (only a hand-made or damaged home has one) is attributed by its
17
+ journal's first entry, read once; a failed read is retried once the file changes.
18
+ - The CLI (`status`, `restart`) and the orchestrator are unchanged.
19
+
3
20
  ## 1.0.38
4
21
 
5
22
  - An answer to any open question of a call reaches it. A call whose question was interrupted (by a steer) and that
package/README.md CHANGED
@@ -577,6 +577,15 @@ read, in a burst each time a call ends), `pid` and `at` (when it was
577
577
  written). The orchestrator writes these to `orchestrator-stats.json` every
578
578
  10 s; they are shown only while that process runs.
579
579
 
580
+ A pi session reads only its own workflows. Which workflows are its own comes
581
+ from the orchestrator ledger, so its dock and list never open the journals or
582
+ transcripts of other sessions' workflows, however many the machine has. While
583
+ an orchestrator runs, a pi session does not look for pending work at all;
584
+ without one, it looks until it finds the first unfinished workflow and keeps
585
+ none of the journals it read. `node scripts/bench-ui.ts --owner=main:<pi
586
+ session id>` measures what a session pays on its main thread for a given
587
+ `DSA_HOME` (read-only).
588
+
580
589
  ### Where the orchestrator starts
581
590
 
582
591
  Whatever needs it first starts the orchestrator: a pi session, a CLI
@@ -1,7 +1,7 @@
1
1
  import { closeSync, openSync, readdirSync, readSync, statSync } from "node:fs";
2
2
  import { StringDecoder } from "node:string_decoder";
3
3
  import { join } from "node:path";
4
- import { readJournalSnapshot } from "../../kernel/journal.js";
4
+ import { readJournalSnapshot, readJournalUncached } from "../../kernel/journal.js";
5
5
  import { journalPath, orchLedger } from "../../paths.js";
6
6
  import { CT, JT, attentionEntries } from "../../types.js";
7
7
  import { holdOf, ledgerIndex } from "../../orchestrator/snapshot.js";
@@ -51,11 +51,66 @@ export function openGeneration(entries) {
51
51
  opened.set(entries, { length: entries.length, open });
52
52
  return open;
53
53
  }
54
+ /** Whether one journal is unfinished, by file identity: a journal that has not changed is not read again. */
55
+ const decided = new Map();
56
+ function unfinishedJournal(path, known) {
57
+ let stat;
58
+ try {
59
+ stat = statSync(path);
60
+ }
61
+ catch (error) {
62
+ if (error.code !== "ENOENT")
63
+ throw error;
64
+ decided.delete(path);
65
+ return true;
66
+ } // no done yet
67
+ const hit = decided.get(path);
68
+ if (hit && hit.ino === stat.ino && hit.size === stat.size)
69
+ return hit.unfinished;
70
+ // Read without keeping the entries in the shared journal cache: a pi process scans every workflow only when no
71
+ // orchestrator runs, and keeping every journal of the machine cost it hundreds of MB.
72
+ const read = known ?? readJournalUncached(path);
73
+ if (!read) {
74
+ decided.delete(path);
75
+ return true;
76
+ }
77
+ const unfinished = !read.entries.some(e => e.type === JT.done) || openGeneration(read.entries);
78
+ decided.set(path, { ino: read.ino, size: read.size, unfinished });
79
+ return unfinished;
80
+ }
54
81
  /** P1: Workflow-side pending work shared by every starter: a workflow without JT.done or with an unsealed generation,
55
- * unless a drain (stop-all) holds it: held work waits for an explicit resume, which starts the orchestrator itself. */
82
+ * unless a drain (stop-all) holds it: held work waits for an explicit resume, which starts the orchestrator itself.
83
+ * Stops at the first unfinished workflow (newest first); a held workflow the ledger attributes is skipped without
84
+ * reading its journal, and an unchanged journal is not read again. */
56
85
  export function unfinishedWorkflow(home) {
57
- const ledger = readJournalSnapshot(orchLedger(home));
58
- return workflows(home).some(w => (!w.entries.some(e => e.type === JT.done) || openGeneration(w.entries)) && !holdOf(ledger, w.wid, w.origin));
86
+ const ledger = readJournalSnapshot(orchLedger(home)), { created, pruned } = ledgerIndex(ledger);
87
+ let names;
88
+ try {
89
+ names = readdirSync(join(home, "w"));
90
+ }
91
+ catch (error) {
92
+ if (error.code !== "ENOENT")
93
+ throw error;
94
+ names = [];
95
+ }
96
+ const ids = [...new Set([...[...created.keys()].map(String), ...names].filter(wid => !pruned.has(wid)))].sort().reverse();
97
+ for (const wid of ids) {
98
+ const path = journalPath(home, wid);
99
+ // The hold rule is the one workflows() applies: the ledger's `created` names the origin a drain may hold; only for
100
+ // a wid the ledger has no `created` for is the journal read first, for a `created` entry of its own.
101
+ const known = created.get(wid);
102
+ if (known && holdOf(ledger, wid, known.origin))
103
+ continue;
104
+ let read;
105
+ if (!known) {
106
+ read = readJournalUncached(path);
107
+ if (holdOf(ledger, wid, read?.entries.find(e => e.type === JT.created)?.origin))
108
+ continue;
109
+ }
110
+ if (unfinishedJournal(path, read))
111
+ return true;
112
+ }
113
+ return false;
59
114
  }
60
115
  const receipts = new WeakMap();
61
116
  const receiptsOf = (entry) => entry.type === "custom_message" && entry.customType === CT.attention
@@ -12,7 +12,7 @@ import { launchOrchestrator } from "../platform/launch.js";
12
12
  import { dsaHome, orchInbox, orchLedger, orchLock, outboxRoot } from "../paths.js";
13
13
  import { CT, JT } from "../types.js";
14
14
  import { attention, presentText, presented, resolved, unfinishedWorkflow } from "./main/snapshots.js";
15
- import { NOTIFY_SINCE, isLive, orchestratorTooOld, pausedElsewhere, runningOrchestrator, statusBrief, statusCallDetail, statusCompactDetail, statusDetail, statusView, widOfRid, outputSelect, writerWaits, writerWaitLine, WRITER_WAIT_HINT } from "../orchestrator/snapshot.js";
15
+ import { NOTIFY_SINCE, isLive, orchestratorTooOld, ownWorkflows, pausedElsewhere, runningOrchestrator, statusBrief, statusCallDetail, statusCompactDetail, statusDetail, statusView, widOfRid, outputSelect, writerWaits, writerWaitLine, WRITER_WAIT_HINT } from "../orchestrator/snapshot.js";
16
16
  import { BATCH, checkAgents, followUpReceipt, outcomeLine, request, sendReceipt } from "./main/tool.js";
17
17
  import { parameters } from "./main/schema.js";
18
18
  import { batchConflict, batchDigest, findRequest, manyIds, namesMany, requestRid, sendIdentified } from "../requests.js";
@@ -82,14 +82,17 @@ export function registerMain(pi, ui) {
82
82
  if (stopped)
83
83
  return;
84
84
  await reconcile();
85
- const pending = submitting || pendingOutbox() || (await scanInbox(orchInbox(home))).length > 0 || unfinishedWorkflow(home);
86
- if (!pending)
87
- return;
85
+ // A running orchestrator (it holds its lock) serves every pending request and workflow: then nothing is scanned.
86
+ // Only without one is pending work looked for, stopping at the first; the scan reads workflow journals without
87
+ // keeping them (see unfinishedWorkflow).
88
88
  await mkdir(home, { recursive: true });
89
89
  const lock = await new OsLock().tryAcquire(orchLock(home));
90
90
  if (!lock)
91
91
  return;
92
92
  await lock.release();
93
+ const pending = submitting || pendingOutbox() || (await scanInbox(orchInbox(home))).length > 0 || unfinishedWorkflow(home);
94
+ if (!pending)
95
+ return;
93
96
  const entry = process.env.DSA_ORCHESTRATOR_ENTRY ?? fileURLToPath(new URL(import.meta.url.endsWith(".ts") ? "../orchestrator/main.ts" : "../orchestrator/main.js", import.meta.url));
94
97
  // Inside pi: started even when pi cannot be resolved here (the orchestrator falls back to its own lookup).
95
98
  await launchOrchestrator(entry, process.env, { home });
@@ -191,7 +194,8 @@ export function registerMain(pi, ui) {
191
194
  pi.on("session_start", async (_event, context) => {
192
195
  await start(context);
193
196
  // Quit pause: say once, at the session's start, which of its workflows wait for a resume.
194
- const paused = statusView(home, { origin: sender }).workflows.filter(w => w.origin === sender && isLive(w) && w.paused);
197
+ // Only the workflows this session started are read (ownership comes from the orchestrator ledger), not every one.
198
+ const paused = ownWorkflows(home, sender, { started: true }).filter(w => w.origin === sender && isLive(w) && w.paused);
195
199
  if (paused.length)
196
200
  pi.sendMessage({ customType: CT.note, display: true, content: `${paused.length} subagent workflow${paused.length > 1 ? "s were" : " was"} paused when pi quit (${paused.map(w => w.name ?? w.wid).join(", ")}). Ask to resume, or open /subagents (or ↓) and press r.` });
197
201
  });
@@ -202,7 +206,7 @@ export function registerMain(pi, ui) {
202
206
  pi.on("session_shutdown", async (event) => {
203
207
  if (event.reason === "quit" && quitPolicy(home) === "pause" && outbox && !stopped) {
204
208
  try {
205
- const running = statusView(home, { origin: sender }).workflows.some(w => w.origin === sender && isLive(w) && !w.paused);
209
+ const running = ownWorkflows(home, sender, { started: true }).some(w => w.origin === sender && isLive(w) && !w.paused);
206
210
  if (running)
207
211
  await serial(async () => { await outbox?.send("orch", "drain", { fence: true, origin: sender }); });
208
212
  }
@@ -100,6 +100,36 @@ export function readJournalSnapshot(path) {
100
100
  closeSync(fd);
101
101
  }
102
102
  }
103
+ /** A committed snapshot with the file identity it was read at, without keeping it in the shared snapshot cache (a
104
+ * cached snapshot of the same file is reused): for one-off scans over many journals whose entries are not needed
105
+ * again. `undefined` when the file does not exist. */
106
+ export function readJournalUncached(path) {
107
+ let fd;
108
+ try {
109
+ fd = openSync(path, 'r');
110
+ }
111
+ catch (error) {
112
+ if (error.code === 'ENOENT')
113
+ return undefined;
114
+ throw error;
115
+ }
116
+ try {
117
+ const { ino, size } = fstatSync(fd), cached = snapshots.get(path);
118
+ if (cached && cached.ino === ino && cached.size === size)
119
+ return { ino, size, entries: cached.entries };
120
+ const bytes = Buffer.alloc(size);
121
+ for (let read = 0; read < bytes.length;) {
122
+ const n = readSync(fd, bytes, read, bytes.length - read, read);
123
+ if (!n)
124
+ break;
125
+ read += n;
126
+ }
127
+ return { ino, size, entries: decode(bytes).entries };
128
+ }
129
+ finally {
130
+ closeSync(fd);
131
+ }
132
+ }
103
133
  /** How long a resting journal keeps its descriptor after its last append (a burst of appends opens it once). */
104
134
  export const JOURNAL_REST_MS = 1000;
105
135
  let descriptors = 0, appends = 0;
@@ -1,10 +1,10 @@
1
1
  // Read-only status snapshots (P25: `status` is always a fresh snapshot). Pure readers of committed journals:
2
2
  // never depend on orchestrator memory, so the UI, the CLI and the main agent see the same durable state.
3
3
  import { initiatorSummary, restartLine } from "./restart.js";
4
- import { existsSync, readFileSync, readdirSync } from "node:fs";
4
+ import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
5
5
  import { join } from "node:path";
6
6
  import { compileFanout } from "../compat/fanout.js";
7
- import { readJournalSnapshot } from "../kernel/journal.js";
7
+ import { readJournalSnapshot, readJournalUncached } from "../kernel/journal.js";
8
8
  import { journalPath, orchLedger, pinnedDir, workflowDir } from "../paths.js";
9
9
  import { JT, isEntry } from "../types.js";
10
10
  import { emptyLedger, foldLedger } from "./ledger.js";
@@ -404,7 +404,7 @@ const ledgerIndexes = new WeakMap();
404
404
  export function ledgerIndex(ledger) {
405
405
  let ix = ledgerIndexes.get(ledger);
406
406
  if (!ix || ix.length > ledger.length || (ix.length && ledger[ix.length - 1] !== ix.last)) {
407
- ix = { length: 0, created: new Map(), pruned: new Set(), labels: new Map(), runLabels: new Map(), sessions: new Map(), runSessions: new Map(), byWid: new Map(), byOrigin: new Map() };
407
+ ix = { length: 0, created: new Map(), intents: new Map(), pruned: new Set(), labels: new Map(), runLabels: new Map(), sessions: new Map(), runSessions: new Map(), byWid: new Map(), byOrigin: new Map() };
408
408
  ledgerIndexes.set(ledger, ix);
409
409
  }
410
410
  for (let i = ix.length; i < ledger.length; i++) {
@@ -425,6 +425,10 @@ export function ledgerIndex(ledger) {
425
425
  ix.runSessions.delete(String(e.rid));
426
426
  }
427
427
  }
428
+ else if (e.type === "create-intent") {
429
+ if (!ix.intents.has(String(e.wid)))
430
+ ix.intents.set(String(e.wid), e.origin);
431
+ }
428
432
  else if (e.type === "request") {
429
433
  const r = e.request, labels = r?.kind === "run" ? labelsOf(r.body) : undefined;
430
434
  if (labels && typeof r?.rid === "string")
@@ -493,6 +497,50 @@ export function heldWorkflows(home) {
493
497
  const since = ix.lastDrain !== undefined ? ledger[ix.lastDrain].ts : undefined;
494
498
  return { ...(since !== undefined ? { since } : {}), held: wid => hold(wid) !== undefined, labels: wid => ix.labels.get(wid), session: wid => ix.sessions.get(wid) };
495
499
  }
500
+ /** The origin of a workflow's `wf-created`, the first entry of its journal, for a workflow the ledger does not attribute
501
+ * (only a damaged or hand-made home has one), read without keeping the journal in the snapshot cache. The first entry
502
+ * never changes once written, so a successful read is kept for the life of the process. A journal that cannot be read
503
+ * counts as no origin (no session's own) only while it stays as it was: the failure is kept with the file's identity
504
+ * (inode, size, ctime and mode: ctime ticks coarsely, so a chmod right after the failure may leave it unchanged) and
505
+ * the read is retried once that changes. A journal without its first
506
+ * entry yet is asked again. */
507
+ const firstOrigins = new Map();
508
+ function firstOrigin(home, wid) {
509
+ const path = journalPath(home, wid), known = firstOrigins.get(path);
510
+ if (known && "origin" in known)
511
+ return known.origin;
512
+ const identity = () => { try {
513
+ const st = statSync(path);
514
+ return { ino: st.ino, size: st.size, ctimeMs: st.ctimeMs, mode: st.mode };
515
+ }
516
+ catch {
517
+ return undefined;
518
+ } };
519
+ const same = (a, b) => !!a && !!b && a.ino === b.ino && a.size === b.size && a.ctimeMs === b.ctimeMs && a.mode === b.mode;
520
+ // The identity is taken before the read, and a failure is kept only when the file did not change during the read:
521
+ // a chmod between the failed read and a later sample would otherwise be recorded as the failure's identity.
522
+ const before = identity();
523
+ if (known && same(before, known.failed))
524
+ return undefined;
525
+ let first;
526
+ try {
527
+ first = readJournalUncached(path)?.entries[0];
528
+ }
529
+ catch {
530
+ if (same(before, identity()))
531
+ firstOrigins.set(path, { failed: before });
532
+ else
533
+ firstOrigins.delete(path);
534
+ return undefined;
535
+ }
536
+ if (!first) {
537
+ firstOrigins.delete(path);
538
+ return undefined;
539
+ }
540
+ const origin = first.type === "wf-created" ? first.origin : undefined;
541
+ firstOrigins.set(path, { origin });
542
+ return origin;
543
+ }
496
544
  /** The workflow with its run's labels and session, when it has them. */
497
545
  function labelled(wf, labels, session) {
498
546
  return labels || session ? { ...wf, ...(labels ? { labels } : {}), ...(session ? { session } : {}) } : wf;
@@ -511,8 +559,35 @@ export function labelsText(labels, width = 60) {
511
559
  }
512
560
  /** P25: Snapshot every workflow under DSA_HOME (newest first by wid, which is a ULID); `paused` marks work a drain holds. */
513
561
  export function allWorkflows(home) {
562
+ return snapshotsOf(home, workflowIds(home));
563
+ }
564
+ function snapshotsOf(home, wids) {
514
565
  const { held, labels, session } = heldWorkflows(home);
515
- return workflowIds(home).sort().reverse().map(wid => { const wf = labelled(workflowSnapshot(home, wid), labels(wid), session(wid)); return isLive(wf) && held(wid) ? { ...wf, paused: true } : wf; });
566
+ return wids.sort().reverse().map(wid => { const wf = labelled(workflowSnapshot(home, wid), labels(wid), session(wid)); return isLive(wf) && held(wid) ? { ...wf, paused: true } : wf; });
567
+ }
568
+ /** The workflows `own` ("main:<pi session id>") shows as its own (`ownedBy`), snapshotted exactly as `allWorkflows`
569
+ * does: the same list as `allWorkflows(home).filter(w => ownedBy(w, own))`, but who owns a workflow is decided from
570
+ * the orchestrator ledger alone (the origin of its create-intent or `created`, the session its run named), so the
571
+ * journals of other sessions' workflows are never opened. A pi process polls only its own workflows: reading and
572
+ * caching every workflow of the machine cost it seconds at startup and hundreds of MB.
573
+ * The engine records a workflow's create-intent (with its origin) before it creates the workflow's directory, so a
574
+ * workflow just being created is already attributed; its `session` (like `allWorkflows`) shows once `created` lands.
575
+ * A directory under `w/` the ledger knows nothing of (given the order below, only a hand-made or damaged home has one)
576
+ * is attributed by its journal's first entry (see firstOrigin). `started`: only those `own` started itself (origin `own`),
577
+ * not runs of other senders that named its session. */
578
+ export function ownWorkflows(home, own, options = {}) {
579
+ // Order matters: list `w/` first, then read the ledger used for attribution. The engine appends a workflow's
580
+ // create-intent before it creates the directory, so every directory listed here already has its intent in a ledger
581
+ // read afterwards; a workflow another session creates in between is attributed without opening its journal. (Read
582
+ // the other way round, such a workflow would look unknown to the ledger and its journal would be read.)
583
+ const wids = workflowIds(home), ix = ledgerIndex(readJournalSnapshot(orchLedger(home)));
584
+ const mine = wids.filter(wid => {
585
+ const known = ix.intents.has(wid) || ix.created.has(wid), session = ix.sessions.get(wid);
586
+ const origin = known ? ix.intents.get(wid) ?? ix.created.get(wid)?.origin : firstOrigin(home, wid);
587
+ return origin === own || (!options.started && session !== undefined && `main:${session}` === own);
588
+ });
589
+ // The journal decides as well: a workflow whose wf-created is not written yet has no origin, as in allWorkflows.
590
+ return snapshotsOf(home, mine).filter(w => options.started ? w.origin === own : ownedBy(w, own));
516
591
  }
517
592
  /** P10/P11: Per-workflow script console log written by the orchestrator (bounded, human-readable). */
518
593
  export function scriptLogPath(home, wid) { return join(workflowDir(home, wid), "script.log"); }
package/dist/ui/data.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { readFileSync } from "node:fs";
2
2
  import { join } from "node:path";
3
3
  import { readJournalSnapshot } from "../kernel/journal.js";
4
- import { allWorkflows } from "../orchestrator/snapshot.js";
4
+ import { allWorkflows, ownWorkflows } from "../orchestrator/snapshot.js";
5
5
  import { callDir, callSession, journalPath, orchLedger } from "../paths.js";
6
6
  import { LIVE_FILE } from "../agent/child/live.js";
7
7
  import { JT } from "../types.js";
@@ -80,8 +80,11 @@ export class UiData {
80
80
  derived = new Map();
81
81
  home;
82
82
  constructor(home) { this.home = home; }
83
- refresh() {
84
- const workflows = allWorkflows(this.home), known = new Set(), deferred = new Map();
83
+ /** Read the workflows `own` ("main:<pi session id>") shows as its own (see ownWorkflows): the pi process reads only
84
+ * its own workflows, so other sessions' journals and call sessions are never opened, stat'ed or cached here. Without
85
+ * an owner every workflow is read (fixtures and tools that show them all). */
86
+ refresh(own) {
87
+ const workflows = own === undefined ? allWorkflows(this.home) : ownWorkflows(this.home, own), known = new Set(), deferred = new Map();
85
88
  const facts = new LazyMap(key => deferred.get(key)?.());
86
89
  const sessions = new LazyMap(key => deferred.has(key) ? deferred.get(key)() : this.transcript(key, sessions));
87
90
  for (const w of workflows) {
package/dist/ui/index.js CHANGED
@@ -67,11 +67,13 @@ export function registerUi(pi, deps) {
67
67
  if (stopped)
68
68
  return;
69
69
  try {
70
- data.refresh();
70
+ // This session's workflows only: ownership comes from the orchestrator ledger, and other sessions' journals are
71
+ // never read by this pi process. orderWorkflows filters by the same rule and orders the list.
72
+ const own = `main:${ctx.sessionManager.getSessionId()}`;
73
+ data.refresh(own);
71
74
  actions.reconcile();
72
75
  for (const result of actions.resolutions.splice(0))
73
76
  screen?.controlResult(result);
74
- const own = `main:${ctx.sessionManager.getSessionId()}`;
75
77
  data.workflows = orderWorkflows(data.workflows, own);
76
78
  // UI §1: the dock — live rows per active agent plus a summary line ("auto"), only the summary ("line"), or nothing.
77
79
  const name = (model) => modelLabel(model, (p, id) => ctx.modelRegistry.find(p, id), data.aliases);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-durable-subagents",
3
- "version": "1.0.38",
3
+ "version": "1.0.39",
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",