pi-durable-subagents 1.0.39 → 1.0.40

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/dist/ui/data.js CHANGED
@@ -1,11 +1,15 @@
1
- import { readFileSync } from "node:fs";
1
+ import { readFileSync, statSync } from "node:fs";
2
+ import { fileURLToPath } from "node:url";
2
3
  import { join } from "node:path";
3
- import { readJournalSnapshot } from "../kernel/journal.js";
4
- import { allWorkflows, ownWorkflows } from "../orchestrator/snapshot.js";
5
- import { callDir, callSession, journalPath, orchLedger } from "../paths.js";
4
+ import { crc32, readJournalSnapshot } from "../kernel/journal.js";
5
+ import { readCache, writeCache } from "../kernel/cache.js";
6
+ import { allWorkflows, isLive, ownWorkflows, releaseSettledJournals, SETTLED_RECHECK_MS, workflowDigest, workflowDigestChecked } from "../orchestrator/snapshot.js";
7
+ import { readerLedger, readerLedgerIdentity } from "../orchestrator/reader-ledger.js";
8
+ import { callDir, callSession, factsDir, journalPath } from "../paths.js";
6
9
  import { LIVE_FILE } from "../agent/child/live.js";
7
10
  import { JT } from "../types.js";
8
11
  import { SessionTail, sessionBranch, sessionFacts } from "./session.js";
12
+ import { orderWorkflows } from "./view.js";
9
13
  /** UI §3: The child's in-flight response, if fresh (a crashed child's last write must not look alive for long). */
10
14
  function readLive(path) {
11
15
  try {
@@ -45,9 +49,51 @@ export class LazyMap extends Map {
45
49
  has(key) { return this.get(key) !== undefined; }
46
50
  }
47
51
  /** How long after its seal a call's session is still followed. A sealed execution has been fenced, so its session is
48
- * final: a follow-up or a revision runs as a new generation with its own session. A session changed after that (by
49
- * hand) shows in a new pi session only. */
52
+ * final: a follow-up or a revision runs as a new generation with its own session. Final facts are rechecked by
53
+ * session identity at most SETTLED_RECHECK_MS apart, including edits made outside the engine. */
50
54
  const FINAL_MS = 10_000;
55
+ // A final call's facts are kept on disk (DSA_HOME/cache/facts), keyed by its seal and its session file's identity: each
56
+ // pi start used to read every historical session again (gigabytes on a long history) to show the same lines. The key
57
+ // names the code that derives them (this module and session.ts), so changed code derives them again.
58
+ const FACTS_FORMAT = 1;
59
+ let factsCode;
60
+ function factsVersion() {
61
+ if (factsCode === undefined) {
62
+ try {
63
+ const ext = import.meta.url.endsWith(".ts") ? "ts" : "js";
64
+ factsCode = `${FACTS_FORMAT}.${crc32(Buffer.concat([new URL(import.meta.url), new URL(`./session.${ext}`, import.meta.url), new URL(`../types.${ext}`, import.meta.url)].map(u => readFileSync(fileURLToPath(u)))))}`;
65
+ }
66
+ catch {
67
+ factsCode = "";
68
+ } // without its own code to name, nothing is stored
69
+ }
70
+ return factsCode;
71
+ }
72
+ const sessionIdentity = (path) => { try {
73
+ const s = statSync(path);
74
+ return `${s.dev}:${s.ino}:${s.size}`;
75
+ }
76
+ catch {
77
+ return "none";
78
+ } };
79
+ function factsPath(home, wid, key, gen) { return join(factsDir(home), wid, `${encodeURIComponent(key)}@${gen}.json`); }
80
+ function storedFacts(path, callId, endedAt, session) {
81
+ const v = factsVersion();
82
+ if (!v)
83
+ return undefined;
84
+ try {
85
+ const stored = readCache(path);
86
+ return stored?.v === v && stored.callId === callId && stored.endedAt === endedAt && stored.session === session &&
87
+ typeof stored.facts?.task === "string" && typeof stored.facts.latest === "string" && Number.isFinite(stored.facts.tools) ? { ...stored.facts, model: stored.facts.model, thinking: stored.facts.thinking, activity: stored.facts.activity, live: undefined } : undefined;
88
+ }
89
+ catch {
90
+ return undefined;
91
+ }
92
+ }
93
+ function storeFacts(path, record, journal) {
94
+ if (record.v)
95
+ writeCache(path, record, journal);
96
+ }
51
97
  /** A1, P25: Read the UI's data from durable workflow snapshots and native session tails only. */
52
98
  export class UiData {
53
99
  workflows = [];
@@ -78,35 +124,90 @@ export class UiData {
78
124
  /** Branch and facts per call, reused while its session tail is unchanged: a finished call's session never grows, and
79
125
  * re-deriving every historical call on each refresh blocked pi's main thread for over a second. */
80
126
  derived = new Map();
127
+ source;
128
+ revision = {};
129
+ quietUntil = 0;
130
+ configIdentity = "";
81
131
  home;
82
132
  constructor(home) { this.home = home; }
133
+ readConfig() {
134
+ const path = join(this.home, "config.json");
135
+ let identity = "none";
136
+ try {
137
+ const s = statSync(path);
138
+ identity = `${s.dev}:${s.ino}:${s.size}:${s.mtimeMs}:${s.ctimeMs}`;
139
+ }
140
+ catch { /* optional */ }
141
+ if (identity === this.configIdentity)
142
+ return false;
143
+ this.configIdentity = identity;
144
+ try {
145
+ const config = JSON.parse(readFileSync(path, "utf8"));
146
+ this.aliases = Object.fromEntries(Object.entries(config.ui?.modelAliases ?? {}).filter(([, v]) => typeof v === "string"));
147
+ this.dock = ["auto", "line", "off"].includes(config.ui?.dock) ? config.ui.dock : "auto";
148
+ this.dockAt = config.ui?.dockAt === "below" ? "below" : "above";
149
+ }
150
+ catch {
151
+ this.aliases = {};
152
+ this.dock = "auto";
153
+ this.dockAt = "above";
154
+ }
155
+ return true;
156
+ }
83
157
  /** Read the workflows `own` ("main:<pi session id>") shows as its own (see ownWorkflows): the pi process reads only
84
158
  * its own workflows, so other sessions' journals and call sessions are never opened, stat'ed or cached here. Without
85
159
  * an owner every workflow is read (fixtures and tools that show them all). */
86
160
  refresh(own) {
87
- const workflows = own === undefined ? allWorkflows(this.home) : ownWorkflows(this.home, own), known = new Set(), deferred = new Map();
161
+ const workflows = own === undefined ? allWorkflows(this.home) : ownWorkflows(this.home, own), now = Date.now(), configChanged = this.readConfig();
162
+ if (workflows === this.source && !configChanged && now >= this.quietUntil - SETTLED_RECHECK_MS && now < this.quietUntil)
163
+ return this.revision;
164
+ // The upstream workflow pass is checked before the view fast path; inherit digest expiry as well.
165
+ let checked = now;
166
+ const known = new Set(), deferred = new Map();
88
167
  const facts = new LazyMap(key => deferred.get(key)?.());
89
- const sessions = new LazyMap(key => deferred.has(key) ? deferred.get(key)() : this.transcript(key, sessions));
168
+ const sessions = new LazyMap(key => { deferred.get(key)?.(); this.transcript(key, sessions); });
90
169
  for (const w of workflows) {
170
+ checked = Math.min(checked, workflowDigestChecked(this.home, w.wid));
91
171
  let index; // only calls still followed need it
172
+ let fallback;
173
+ const taskDigest = () => fallback ??= workflowDigest(this.home, w.wid, readerLedgerIdentity(readerLedger(this.home)));
92
174
  const journal = () => index ??= journalIndex(readJournalSnapshot(journalPath(this.home, w.wid)));
93
175
  for (const c of w.calls) {
94
176
  known.add(c.callId);
95
177
  const final = this.final.get(c.callId);
96
178
  if (final && c.phase === "sealed" && c.endedAt === final.endedAt) {
97
- facts.put(c.callId, final.facts);
98
- continue;
179
+ if (now >= final.checked && now - final.checked < SETTLED_RECHECK_MS) {
180
+ facts.put(c.callId, final.facts);
181
+ continue;
182
+ }
183
+ if (sessionIdentity(final.path) === final.identity) {
184
+ final.checked = now;
185
+ facts.put(c.callId, final.facts);
186
+ continue;
187
+ }
188
+ if (this.opened?.callId === c.callId)
189
+ this.opened = undefined;
99
190
  }
100
191
  if (final)
101
192
  this.final.delete(c.callId);
102
193
  const load = () => {
103
194
  deferred.delete(c.callId);
195
+ const final = c.phase === "sealed" && c.endedAt !== undefined && Date.now() - c.endedAt > FINAL_MS;
196
+ const sessionPath = callSession(this.home, w.wid, c.key, c.gen), stored = final ? factsPath(this.home, w.wid, c.key, c.gen) : "";
197
+ // History read before, by this or another pi: its stored facts, without reading the session.
198
+ const identity = final && !this.tails.has(c.callId) ? sessionIdentity(sessionPath) : "";
199
+ const known = identity ? storedFacts(stored, c.callId, c.endedAt, identity) : undefined;
200
+ if (known) {
201
+ facts.put(c.callId, known);
202
+ this.final.set(c.callId, { endedAt: c.endedAt, path: sessionPath, facts: known, identity, checked: now });
203
+ return;
204
+ }
104
205
  let tail = this.tails.get(c.callId);
105
206
  if (!tail) {
106
207
  tail = new SessionTail();
107
208
  this.tails.set(c.callId, tail);
108
209
  }
109
- const source = tail.read(callSession(this.home, w.wid, c.key, c.gen));
210
+ const source = tail.read(sessionPath);
110
211
  let cached = this.derived.get(c.callId);
111
212
  if (!cached || cached.source !== source || cached.length !== source.length) {
112
213
  const entries = sessionBranch(source);
@@ -114,23 +215,30 @@ export class UiData {
114
215
  this.derived.set(c.callId, cached);
115
216
  }
116
217
  const value = { ...cached.facts, live: undefined };
117
- const proposal = journal().calls.get(`${c.key}\0${c.gen}`);
118
- value.task ||= String(proposal?.spec?.task ?? "");
119
- const loss = journal().losses.get(String(c.exec)) ?? -1;
120
- const launch = journal().execs.get(String(c.exec)) ?? -1;
121
- if (c.phase !== "sealed" && loss > launch)
122
- value.activity = "connection dropped, retrying";
123
- if (c.phase !== "sealed")
218
+ // The journal only when the session does not say it: a settled workflow's journal is not kept in memory
219
+ // (orchestrator/snapshot.ts digests), and reading it back for every historical call undid that.
220
+ if (!value.task) {
221
+ const settled = taskDigest().settled;
222
+ value.task = settled ? settled.tasks[`${c.key}\0${c.gen}`] ?? "" : String(journal().calls.get(`${c.key}\0${c.gen}`)?.spec?.task ?? "");
223
+ }
224
+ if (c.phase !== "sealed") {
225
+ const loss = journal().losses.get(String(c.exec)) ?? -1;
226
+ const launch = journal().execs.get(String(c.exec)) ?? -1;
227
+ if (loss > launch)
228
+ value.activity = "connection dropped, retrying";
124
229
  value.live = readLive(join(callDir(this.home, w.wid, c.key, c.gen), LIVE_FILE));
125
- sessions.put(c.callId, cached.entries);
230
+ }
126
231
  facts.put(c.callId, value);
127
- // A call sealed a while ago writes nothing more (a follow-up opens a new generation and session), so its
128
- // session is not stat'ed again: polling every historical session twice a second kept pi's main thread busy.
129
- if (c.phase === "sealed" && c.endedAt !== undefined && Date.now() - c.endedAt > FINAL_MS) {
130
- this.final.set(c.callId, { endedAt: c.endedAt, path: callSession(this.home, w.wid, c.key, c.gen), facts: value });
232
+ const readIdentity = tail.snapshotIdentity;
233
+ if (final && readIdentity !== undefined) {
234
+ this.final.set(c.callId, { endedAt: c.endedAt, path: sessionPath, facts: value, identity: readIdentity, checked: now });
131
235
  this.tails.delete(c.callId);
132
236
  this.derived.delete(c.callId);
237
+ storeFacts(stored, { v: factsVersion(), callId: c.callId, endedAt: c.endedAt, session: readIdentity, facts: value }, journalPath(this.home, w.wid));
133
238
  }
239
+ else
240
+ sessions.put(c.callId, cached.entries);
241
+ releaseSettledJournals();
134
242
  };
135
243
  // A finished call never read before (history at startup) is read when first shown or by the idle warm-up below;
136
244
  // reading every historical session up front blocked pi's startup for seconds.
@@ -148,6 +256,8 @@ export class UiData {
148
256
  for (const key of this.final.keys())
149
257
  if (!known.has(key))
150
258
  this.final.delete(key);
259
+ if (this.opened && !known.has(this.opened.callId))
260
+ this.opened = undefined;
151
261
  // Warm the history a slice at a time, so opening the list later finds it read without one long stall now.
152
262
  const until = performance.now() + this.warmMs;
153
263
  for (const load of [...deferred.values()]) {
@@ -155,21 +265,17 @@ export class UiData {
155
265
  break;
156
266
  load();
157
267
  }
158
- this.workflows = workflows;
159
- this.facts = facts;
160
- this.sessions = sessions;
161
- // UI-only optional aliases; absence or invalid config must not break execution (P21).
162
- try {
163
- const config = JSON.parse(readFileSync(join(this.home, "config.json"), "utf8"));
164
- this.aliases = Object.fromEntries(Object.entries(config.ui?.modelAliases ?? {}).filter(([, v]) => typeof v === "string"));
165
- this.dock = ["auto", "line", "off"].includes(config.ui?.dock) ? config.ui.dock : "auto";
166
- this.dockAt = config.ui?.dockAt === "below" ? "below" : "above";
167
- }
168
- catch {
169
- this.aliases = {};
170
- this.dock = "auto";
171
- this.dockAt = "above";
268
+ const sameFacts = this.facts.size === facts.size && [...facts].every(([key, value]) => this.facts.get(key) === value);
269
+ const quiet = known.size === this.final.size && !deferred.size && !this.tails.size && !workflows.some(isLive);
270
+ this.quietUntil = quiet ? Math.min(checked + SETTLED_RECHECK_MS, ...[...this.final.values()].map(f => f.checked + SETTLED_RECHECK_MS)) : 0;
271
+ if (this.source !== workflows || configChanged || !sameFacts || !quiet) {
272
+ this.workflows = own === undefined ? workflows : orderWorkflows(workflows, own);
273
+ this.facts = facts;
274
+ this.sessions = sessions;
275
+ this.revision = {};
172
276
  }
277
+ this.source = workflows;
278
+ return this.revision;
173
279
  }
174
280
  }
175
281
  /** P16, P25: Submit through M1's durable user path and report asynchronous rejection without waking it. */
@@ -205,18 +311,18 @@ export class UiActions {
205
311
  let latest;
206
312
  if (!this.pending.size)
207
313
  return;
208
- for (const e of readJournalSnapshot(orchLedger(this.deps.home))) {
209
- const note = this.pending.get(String(e.rid));
210
- if (!note)
314
+ const decisions = readerLedger(this.deps.home).state.resolutions;
315
+ const ready = [...this.pending].filter(([rid]) => decisions.has(rid)).sort(([a], [b]) => decisions.get(a).seq - decisions.get(b).seq);
316
+ for (const [rid, note] of ready) {
317
+ const e = decisions.get(rid);
318
+ if (!e)
211
319
  continue;
212
320
  if (e.type === JT.rejected) {
213
321
  latest = `${note}: ${String(e.reason)}`;
214
322
  this.deps.presentNote(`[user] ${latest}`);
215
323
  }
216
- if (e.type === JT.applied || e.type === JT.rejected) {
217
- this.resolutions.push({ rid: String(e.rid), applied: e.type === JT.applied, ...(e.type === JT.rejected ? { reason: String(e.reason) } : {}) });
218
- this.pending.delete(String(e.rid));
219
- }
324
+ this.resolutions.push({ rid, applied: e.type === JT.applied, ...(e.type === JT.rejected ? { reason: String(e.reason) } : {}) });
325
+ this.pending.delete(rid);
220
326
  }
221
327
  return latest;
222
328
  }
package/dist/ui/index.js CHANGED
@@ -2,7 +2,7 @@ import { matchesKey, truncateToWidth, visibleWidth } from "@earendil-works/pi-tu
2
2
  import { UiActions, UiData } from "./data.js";
3
3
  import { SubagentScreen } from "./screen.js";
4
4
  import { oneLine } from "./frame.js";
5
- import { dockLines, mainLine, modelLabel, orderWorkflows } from "./view.js";
5
+ import { dockLines, mainLine, modelLabel } from "./view.js";
6
6
  import { registerCards } from "./cards.js";
7
7
  import { toolRenderers } from "./tool.js";
8
8
  /** UI §1–3, P16, P21: Register journal-backed list/watch surfaces only in interactive pi. */
@@ -38,6 +38,7 @@ export function registerUi(pi, deps) {
38
38
  let screen, opening = false, stopped = false, closeScreen;
39
39
  let unsubscribe, timer;
40
40
  let dockRows = () => [], dockAt = null, lastDock = "";
41
+ let lastData, completionExpires = Infinity;
41
42
  // ↓ opens the list only from pi's own input editor. Another surface — /model's selector, a dialog, another
42
43
  // extension's overlay — has the focus instead, and its ↓ belongs to it. pi's editor (and any editor built on
43
44
  // CustomEditor) carries the app action map; the TUI comes from the dock widget, so without a dock the check
@@ -70,11 +71,20 @@ export function registerUi(pi, deps) {
70
71
  // This session's workflows only: ownership comes from the orchestrator ledger, and other sessions' journals are
71
72
  // never read by this pi process. orderWorkflows filters by the same rule and orders the list.
72
73
  const own = `main:${ctx.sessionManager.getSessionId()}`;
73
- data.refresh(own);
74
+ const revision = data.refresh(own);
74
75
  actions.reconcile();
75
- for (const result of actions.resolutions.splice(0))
76
+ const resolved = actions.resolutions.splice(0);
77
+ for (const result of resolved)
76
78
  screen?.controlResult(result);
77
- data.workflows = orderWorkflows(data.workflows, own);
79
+ const cardsChanged = refreshCards();
80
+ if (revision === lastData && !resolved.length && Date.now() < completionExpires) {
81
+ if (cardsChanged)
82
+ keysTui?.requestRender?.();
83
+ return;
84
+ }
85
+ lastData = revision;
86
+ const expires = Math.max(0, ...data.workflows.map(w => w.endedAt ?? 0)) + 10 * 60_000;
87
+ completionExpires = expires > Date.now() ? expires : Infinity;
78
88
  // UI §1: the dock — live rows per active agent plus a summary line ("auto"), only the summary ("line"), or nothing.
79
89
  const name = (model) => modelLabel(model, (p, id) => ctx.modelRegistry.find(p, id), data.aliases);
80
90
  const now = Date.now(), dock = data.dock;
@@ -105,7 +115,6 @@ export function registerUi(pi, deps) {
105
115
  }, { placement: at === "above" ? "aboveEditor" : "belowEditor" });
106
116
  }
107
117
  const shown = dockRows(200).join("\n");
108
- const cardsChanged = refreshCards();
109
118
  if (shown !== lastDock || cardsChanged) {
110
119
  lastDock = shown;
111
120
  keysTui?.requestRender?.();
@@ -1,5 +1,5 @@
1
1
  // Read-only session tailing (C5, P21): incomplete trailing records are never displayed.
2
- import { closeSync, openSync, readSync, statSync } from "node:fs";
2
+ import { closeSync, fstatSync, openSync, readSync, statSync } from "node:fs";
3
3
  import { StringDecoder } from "node:string_decoder";
4
4
  import { CT } from "../types.js";
5
5
  /** C5: Incrementally read complete pi session records, resetting after replacement or truncation. */
@@ -10,6 +10,10 @@ export class SessionTail {
10
10
  decoder = new StringDecoder("utf8");
11
11
  entries = [];
12
12
  failure;
13
+ readIdentity = "none";
14
+ readSize = 0;
15
+ /** The complete file actually read, for derived caches; a torn tail cannot become final facts. */
16
+ get snapshotIdentity() { return this.pending || this.offset !== this.readSize ? undefined : this.readIdentity; }
13
17
  read(path) {
14
18
  let stat;
15
19
  try {
@@ -28,10 +32,21 @@ export class SessionTail {
28
32
  }
29
33
  if (this.failure)
30
34
  throw this.failure;
31
- if (stat.size === this.offset)
35
+ if (stat.size === this.offset) {
36
+ if (!stat.size)
37
+ this.readIdentity = `${stat.dev}:${stat.ino}:0`;
32
38
  return this.entries;
39
+ }
33
40
  const fd = openSync(path, "r");
34
41
  try {
42
+ stat = fstatSync(fd);
43
+ const openedIdentity = `${path}:${stat.dev}:${stat.ino}`;
44
+ if (openedIdentity !== this.identity || stat.size < this.offset) {
45
+ this.reset();
46
+ this.identity = openedIdentity;
47
+ }
48
+ this.readIdentity = `${stat.dev}:${stat.ino}:${stat.size}`;
49
+ this.readSize = stat.size;
35
50
  const buffer = Buffer.alloc(Math.min(64 * 1024, stat.size - this.offset));
36
51
  while (this.offset < stat.size) {
37
52
  const n = readSync(fd, buffer, 0, Math.min(buffer.length, stat.size - this.offset), this.offset);
@@ -62,7 +77,7 @@ export class SessionTail {
62
77
  }
63
78
  return this.entries;
64
79
  }
65
- reset() { this.identity = ""; this.offset = 0; this.pending = ""; this.entries = []; this.failure = undefined; this.decoder = new StringDecoder("utf8"); }
80
+ reset() { this.identity = ""; this.readIdentity = "none"; this.readSize = 0; this.offset = 0; this.pending = ""; this.entries = []; this.failure = undefined; this.decoder = new StringDecoder("utf8"); }
66
81
  }
67
82
  /** C5: Select the native session's current branch without showing abandoned conversation turns. */
68
83
  export function sessionBranch(entries) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-durable-subagents",
3
- "version": "1.0.39",
3
+ "version": "1.0.40",
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",