pi-better-server 0.2.4 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (109) hide show
  1. package/package.json +6 -3
  2. package/scripts/measure-shared-reads/daemon.mjs +7 -0
  3. package/scripts/measure-shared-reads/probe.mjs +10 -0
  4. package/scripts/measure-shared-reads.mjs +165 -0
  5. package/scripts/test-on-pi.sh +21 -3
  6. package/src/cli.ts +39 -2
  7. package/src/client.ts +9 -4
  8. package/src/daemon-owner.ts +48 -6
  9. package/src/handshake.ts +8 -7
  10. package/src/lifecycle-config.ts +4 -0
  11. package/src/paths.ts +1 -11
  12. package/src/protocol.ts +7 -0
  13. package/src/registry.ts +2 -1
  14. package/src/runtime/background-history.ts +241 -0
  15. package/src/runtime/background.ts +182 -0
  16. package/src/runtime/cancellation.ts +99 -0
  17. package/src/runtime/catalog-admission.ts +50 -0
  18. package/src/runtime/catalog.ts +133 -0
  19. package/src/runtime/client.ts +111 -0
  20. package/src/runtime/domain/assignment-observation.d.mts +1 -0
  21. package/src/runtime/domain/assignment-observation.mjs +120 -0
  22. package/src/runtime/domain/assignment-projection.d.mts +1 -0
  23. package/src/runtime/domain/assignment-projection.mjs +245 -0
  24. package/src/runtime/domain/background/conditions.mjs +93 -0
  25. package/src/runtime/domain/background/process-identity.mjs +110 -0
  26. package/src/runtime/domain/background/process.mjs +511 -0
  27. package/src/runtime/domain/background/registry.mjs +374 -0
  28. package/src/runtime/domain/background/snapshot.mjs +73 -0
  29. package/src/runtime/domain/background/supervisor/identity.mjs +92 -0
  30. package/src/runtime/domain/background/supervisor/invocation.mjs +29 -0
  31. package/src/runtime/domain/background/supervisor/store.mjs +604 -0
  32. package/src/runtime/domain/background/supervisor/supervisor.mjs +720 -0
  33. package/src/runtime/domain/background/supervisor/types.mjs +47 -0
  34. package/src/runtime/domain/background/terminal-publication.mjs +58 -0
  35. package/src/runtime/domain/background/types.mjs +3 -0
  36. package/src/runtime/domain/catalog/agent-session-settings.d.mts +30 -0
  37. package/src/runtime/domain/catalog/agent-session-settings.mjs +112 -0
  38. package/src/runtime/domain/catalog/catalog-overlay.d.mts +3 -0
  39. package/src/runtime/domain/catalog/catalog-overlay.mjs +9 -0
  40. package/src/runtime/domain/catalog/catalog-preferences.d.mts +17 -0
  41. package/src/runtime/domain/catalog/catalog-preferences.mjs +164 -0
  42. package/src/runtime/domain/catalog/catalog-schema.d.mts +265 -0
  43. package/src/runtime/domain/catalog/catalog-schema.mjs +1331 -0
  44. package/src/runtime/domain/catalog/catalog-skill-edits.d.mts +42 -0
  45. package/src/runtime/domain/catalog/catalog-skill-edits.mjs +95 -0
  46. package/src/runtime/domain/catalog/catalog-store.d.mts +126 -0
  47. package/src/runtime/domain/catalog/catalog-store.mjs +810 -0
  48. package/src/runtime/domain/catalog/roles/role.architect.md +13 -0
  49. package/src/runtime/domain/catalog/roles/role.developer.md +16 -0
  50. package/src/runtime/domain/catalog/roles/role.explorer.md +13 -0
  51. package/src/runtime/domain/catalog/roles/role.product-manager.md +13 -0
  52. package/src/runtime/domain/catalog/roles/role.researcher.md +13 -0
  53. package/src/runtime/domain/catalog/roles/role.reviewer.md +13 -0
  54. package/src/runtime/domain/catalog/roles/role.writer.md +12 -0
  55. package/src/runtime/domain/catalog/thinking.d.mts +8 -0
  56. package/src/runtime/domain/catalog/thinking.mjs +22 -0
  57. package/src/runtime/domain/coordinator/index.mjs +50 -0
  58. package/src/runtime/domain/coordinator/src/assignment-outcomes.mjs +160 -0
  59. package/src/runtime/domain/coordinator/src/discovery.mjs +94 -0
  60. package/src/runtime/domain/coordinator/src/errors.mjs +12 -0
  61. package/src/runtime/domain/coordinator/src/operations.mjs +301 -0
  62. package/src/runtime/domain/coordinator/src/outbox.mjs +282 -0
  63. package/src/runtime/domain/coordinator/src/recovery.mjs +51 -0
  64. package/src/runtime/domain/coordinator/src/result-supervision.mjs +101 -0
  65. package/src/runtime/domain/coordinator/src/rows.mjs +277 -0
  66. package/src/runtime/domain/coordinator/src/schema.mjs +367 -0
  67. package/src/runtime/domain/coordinator/src/sqlite.mjs +193 -0
  68. package/src/runtime/domain/coordinator/src/store.mjs +245 -0
  69. package/src/runtime/domain/coordinator/src/task-cancellation.mjs +187 -0
  70. package/src/runtime/domain/coordinator/src/types.mjs +24 -0
  71. package/src/runtime/domain/coordinator/src/validate.mjs +233 -0
  72. package/src/runtime/domain/coordinator/src/waits.mjs +850 -0
  73. package/src/runtime/domain/health-observation.d.mts +3 -0
  74. package/src/runtime/domain/health-observation.mjs +613 -0
  75. package/src/runtime/domain/health-surface.mjs +279 -0
  76. package/src/runtime/domain/log-cursor.mjs +148 -0
  77. package/src/runtime/domain/log-paths.mjs +13 -0
  78. package/src/runtime/domain/parse.d.mts +2 -0
  79. package/src/runtime/domain/parse.mjs +1173 -0
  80. package/src/runtime/domain/process-status.d.mts +1 -0
  81. package/src/runtime/domain/process-status.mjs +25 -0
  82. package/src/runtime/domain/session-store.d.mts +2 -0
  83. package/src/runtime/domain/session-store.mjs +489 -0
  84. package/src/runtime/domain/shared-harness-settings.d.mts +1 -0
  85. package/src/runtime/domain/shared-harness-settings.mjs +126 -0
  86. package/src/runtime/domain/shared-log-utils.mjs +1223 -0
  87. package/src/runtime/domain/shared-stall-detector.mjs +37 -0
  88. package/src/runtime/domain/widget.d.mts +1 -0
  89. package/src/runtime/domain/widget.mjs +250 -0
  90. package/src/runtime/guardian.ts +189 -0
  91. package/src/runtime/health-config.ts +27 -0
  92. package/src/runtime/local-client.ts +34 -0
  93. package/src/runtime/mutation-store.ts +34 -0
  94. package/src/runtime/queries.ts +76 -0
  95. package/src/runtime/query-executor.ts +277 -0
  96. package/src/runtime/query-worker.mjs +119 -0
  97. package/src/runtime/read-model.ts +409 -0
  98. package/src/runtime/result-supervision.ts +63 -0
  99. package/src/runtime/root.ts +29 -0
  100. package/src/runtime/socket.ts +10 -0
  101. package/src/runtime/status-cli.ts +11 -0
  102. package/src/runtime/work-client.d.mts +14 -0
  103. package/src/runtime/work-client.mjs +102 -0
  104. package/src/server.ts +199 -14
  105. package/src/session-activity.ts +22 -2
  106. package/src/startup/activation.ts +32 -5
  107. package/src/startup/ensure.ts +13 -1
  108. package/src/startup/install.ts +2 -0
  109. package/src/version.ts +4 -0
@@ -0,0 +1,279 @@
1
+ /**
2
+ * Pure helpers that surface #66 health observations on existing list / output /
3
+ * widget text without inventing a parallel health model (issue #67).
4
+ *
5
+ * Healthy/quiet stays low-noise. Degraded/actionable compact facts and durable
6
+ * orphaned/lost statuses are the only additions.
7
+ */
8
+
9
+ /** Statuses that are always actionable on list/output surfaces. */
10
+ const ACTIONABLE_STATUSES = new Set(["orphaned", "lost"]);
11
+
12
+ /** Age suffix from health-observation fmtAge: `10s`, `2m`, `1h5m`. */
13
+ const ORDINARY_TOOL_AGE = /^(?:\d+s|\d+m|\d+h\d+m)$/;
14
+
15
+ /**
16
+ * Ordinary short-running open-tool label from #66: bare tool name, or name plus
17
+ * a fmtAge duration. Degraded facts that merely share the tool-name prefix
18
+ * (e.g. `model error` while a tool named `model` is running) must be kept.
19
+ *
20
+ * @param {string} fact
21
+ * @param {string} toolName
22
+ */
23
+ function isOrdinaryRunningToolFact(fact, toolName) {
24
+ if (fact === toolName) return true;
25
+ const prefix = `${toolName} `;
26
+ if (!fact.startsWith(prefix)) return false;
27
+ return ORDINARY_TOOL_AGE.test(fact.slice(prefix.length));
28
+ }
29
+
30
+ /**
31
+ * #66 emits ordinary open-tool labels (e.g. `bash 10s`) in compactFacts before
32
+ * long_running. Those are not degraded health for #67 surfaces — the widget
33
+ * already shows the active tool via its normal label. Keep long_running and
34
+ * every other compact fact.
35
+ *
36
+ * @param {{ compactFacts?: string[], tool?: { state?: string, active?: { toolName?: string } } }|null|undefined} obs
37
+ * @returns {string[]}
38
+ */
39
+ export function surfaceableCompactFacts(obs) {
40
+ const facts = Array.isArray(obs?.compactFacts) ? obs.compactFacts : [];
41
+ if (!obs || obs.tool?.state !== "running") {
42
+ return facts.filter(Boolean);
43
+ }
44
+ const name = obs.tool?.active?.toolName;
45
+ if (!name) return facts.filter(Boolean);
46
+ // Drop only the ordinary running duration fact (`${name}` / `${name} 10s`).
47
+ // Prefix-sharing degraded facts (`model error`, `model retrying`, …) stay.
48
+ // long_running (`long ${name}…`) is retained because tool.state !== "running".
49
+ return facts.filter((f) => f && !isOrdinaryRunningToolFact(f, name));
50
+ }
51
+
52
+ /**
53
+ * True when the observation should add diagnostics beyond the compact baseline.
54
+ * Quiet is intentionally silent — residual silence without residual stale /
55
+ * phase warnings is not actionable noise for list/widget.
56
+ * Ordinary tool.state === "running" compact facts are not actionable (#67).
57
+ *
58
+ * @param {{ status?: string, activity?: string, compactFacts?: string[], tool?: { state?: string, active?: { toolName?: string } } }|null|undefined} obs
59
+ */
60
+ export function isActionableHealth(obs) {
61
+ if (!obs) return false;
62
+ if (ACTIONABLE_STATUSES.has(obs.status)) return true;
63
+ if (obs.activity === "stale") return true;
64
+ return surfaceableCompactFacts(obs).length > 0;
65
+ }
66
+
67
+ /**
68
+ * Compact fact labels for degraded/actionable health, including process
69
+ * liveness labels for orphaned/lost when compactFacts alone are empty.
70
+ * Ordinary short-running tool labels are omitted (degraded-only contract).
71
+ *
72
+ * @param {{ status?: string, activity?: string, compactFacts?: string[], process?: { liveness?: string }, tool?: { state?: string, active?: { toolName?: string } } }|null|undefined} obs
73
+ * @returns {string[]}
74
+ */
75
+ export function healthSurfaceFacts(obs) {
76
+ if (!obs) return [];
77
+ const facts = [];
78
+ if (obs.status === "orphaned") facts.push("orphaned");
79
+ else if (obs.status === "lost") facts.push("lost");
80
+ for (const f of surfaceableCompactFacts(obs)) {
81
+ if (f && !facts.includes(f)) facts.push(f);
82
+ }
83
+ // Residual stale may already be in compactFacts; ensure it appears when
84
+ // activity is stale and nothing more specific was listed.
85
+ if (obs.activity === "stale" && !facts.some((f) => /\bstale\b/i.test(f))) {
86
+ facts.push("stale");
87
+ }
88
+ return facts.slice(0, 3);
89
+ }
90
+
91
+ /**
92
+ * Format list-row health suffix. Empty string when healthy/quiet so the row
93
+ * stays on today's compact format.
94
+ *
95
+ * @param {{ status?: string, activity?: string, compactFacts?: string[] }|null|undefined} obs
96
+ */
97
+ export function formatListHealthSuffix(obs) {
98
+ if (!isActionableHealth(obs)) return "";
99
+ const facts = healthSurfaceFacts(obs);
100
+ // Orphaned/lost already appear in the status bracket; prefer remaining facts.
101
+ const rest = facts.filter((f) => f !== obs.status);
102
+ if (rest.length === 0) {
103
+ // Still actionable via status alone — no extra suffix needed.
104
+ return "";
105
+ }
106
+ return ` · ${rest.join(", ")}`;
107
+ }
108
+
109
+ /**
110
+ * One-line health diagnostic for subagent_output / result heads.
111
+ * Empty when healthy/quiet running.
112
+ *
113
+ * @param {{ status?: string, activity?: string, compactFacts?: string[] }|null|undefined} obs
114
+ */
115
+ export function formatHealthDiagnosticLine(obs) {
116
+ if (!isActionableHealth(obs)) return "";
117
+ const facts = healthSurfaceFacts(obs);
118
+ if (facts.length === 0) return "";
119
+ return `[health: ${facts.join(", ")}]`;
120
+ }
121
+
122
+ /**
123
+ * Short suffix for a passive widget run line. Empty for healthy/quiet so
124
+ * geometry and text stay unchanged for quiet runs.
125
+ *
126
+ * @param {{ status?: string, activity?: string, compactFacts?: string[] }|null|undefined} obs
127
+ */
128
+ export function formatWidgetHealthSuffix(obs) {
129
+ if (!isActionableHealth(obs)) return "";
130
+ const facts = healthSurfaceFacts(obs)
131
+ // Widget already implies "running"; skip redundant process labels when
132
+ // a more specific compact fact exists, but keep orphaned/lost alone.
133
+ .filter((f) => f !== "running");
134
+ if (facts.length === 0) return "";
135
+ // Keep widget geometry mostly stable: at most two short tokens.
136
+ return ` · ${facts.slice(0, 2).join(", ")}`;
137
+ }
138
+
139
+ /**
140
+ * Append a health diagnostic line to an existing tool body when present.
141
+ *
142
+ * @param {string} body
143
+ * @param {string} healthLine
144
+ */
145
+ export function appendHealthDiagnostic(body, healthLine) {
146
+ if (!healthLine) return body;
147
+ // Place diagnostic just under the head line when body starts with `[id ·`.
148
+ const nl = body.indexOf("\n");
149
+ if (nl === -1) return `${body}\n${healthLine}`;
150
+ return `${body.slice(0, nl)}\n${healthLine}${body.slice(nl)}`;
151
+ }
152
+
153
+ /**
154
+ * Compact health facts for TUI navigator rows (#69).
155
+ * Healthy/quiet stays empty. Durable status is rendered separately, so
156
+ * orphaned/lost labels are not repeated as facts. Cap is two facts.
157
+ *
158
+ * @param {{ status?: string, activity?: string, compactFacts?: string[], tool?: { state?: string, active?: { toolName?: string } } }|null|undefined} obs
159
+ * @returns {string[]}
160
+ */
161
+ export function formatNavigatorHealthFacts(obs) {
162
+ if (!obs || !isActionableHealth(obs)) return [];
163
+ const facts = [];
164
+ for (const f of surfaceableCompactFacts(obs)) {
165
+ if (obs.model?.state === "error" && f === obs.model.listWarning) continue;
166
+ if (f && f !== obs.status && !facts.includes(f)) facts.push(f);
167
+ }
168
+ if (obs.activity === "stale" && !facts.some((f) => /\bstale\b/i.test(f))) {
169
+ facts.push("stale");
170
+ }
171
+ // Process-group / log diagnostics when orphaned/lost and no phase facts.
172
+ if (facts.length === 0 && (obs.status === "orphaned" || obs.status === "lost")) {
173
+ const live = obs.process?.liveness;
174
+ if (live && live !== obs.status) facts.push(live);
175
+ const logAge = obs.rawLog?.mtimeMs;
176
+ // raw age is computed by callers into compactFacts when needed; skip here.
177
+ void logAge;
178
+ }
179
+ return facts.slice(0, 2);
180
+ }
181
+
182
+ /**
183
+ * Semantic theme color for a durable/effective run status in the TUI.
184
+ * completed → success; failed/lost → error; killed/orphaned → warning;
185
+ * running → accent; anything else → dim.
186
+ *
187
+ * @param {string|undefined|null} status
188
+ * @returns {string}
189
+ */
190
+ export function statusThemeColor(status) {
191
+ switch (String(status ?? "").toLowerCase()) {
192
+ case "completed":
193
+ return "success";
194
+ case "failed":
195
+ case "lost":
196
+ return "error";
197
+ case "killed":
198
+ case "cancelled":
199
+ case "waiting":
200
+ case "orphaned":
201
+ return "warning";
202
+ case "running":
203
+ return "accent";
204
+ default:
205
+ return "dim";
206
+ }
207
+ }
208
+
209
+ /** Strip CSI / OSC ANSI sequences for visible-width measurement. */
210
+ const ANSI_RE = new RegExp(
211
+ // eslint-disable-next-line no-control-regex
212
+ "[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[a-zA-Z\\d]*)*)?\\u0007)|(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))",
213
+ "g",
214
+ );
215
+
216
+ /**
217
+ * Visible (cell) width of a string, ignoring ANSI styling sequences.
218
+ * Also strips the lightweight `<color>…</>` test theme markers used in unit stubs.
219
+ *
220
+ * @param {string} s
221
+ * @returns {number}
222
+ */
223
+ export function visibleWidth(s) {
224
+ const plain = String(s ?? "")
225
+ .replace(ANSI_RE, "")
226
+ // Theme stub markers from unit tests: <accent>…</> (closing tag is bare </>).
227
+ .replace(/<\/?[a-zA-Z][\w-]*>/g, "")
228
+ .replace(/<\/>/g, "");
229
+ // Treat combining marks / wide chars as single cells — sufficient for our
230
+ // ASCII status tokens and English labels; pi-tui handles full East-Asian.
231
+ return plain.length;
232
+ }
233
+
234
+ /**
235
+ * Truncate to a maximum visible width while preserving ANSI / theme markers.
236
+ * Prefer the host's `truncateToWidth` when available (index.ts injects pi-tui);
237
+ * this fallback keeps unit tests width-safe when color escapes are present.
238
+ *
239
+ * @param {string} s
240
+ * @param {number} width
241
+ * @returns {string}
242
+ */
243
+ export function truncateToVisibleWidth(s, width) {
244
+ const str = String(s ?? "");
245
+ const max = Math.max(0, Number(width) || 0);
246
+ if (visibleWidth(str) <= max) return str;
247
+
248
+ // Walk code units, skipping ANSI and <tag> markers for the budget.
249
+ let out = "";
250
+ let vis = 0;
251
+ let i = 0;
252
+ while (i < str.length && vis < max) {
253
+ // ANSI CSI/OSC
254
+ if (str[i] === "\u001b" || str[i] === "\u009b") {
255
+ const m = str.slice(i).match(ANSI_RE);
256
+ if (m && m.index === 0) {
257
+ out += m[0];
258
+ i += m[0].length;
259
+ continue;
260
+ }
261
+ }
262
+ // Lightweight theme markers from test stubs: <accent>…</>
263
+ if (str[i] === "<") {
264
+ const close = str.indexOf(">", i);
265
+ if (close !== -1) {
266
+ const tag = str.slice(i, close + 1);
267
+ if (/^<\/?[a-zA-Z][\w-]*>$/.test(tag) || tag === "</>") {
268
+ out += tag;
269
+ i = close + 1;
270
+ continue;
271
+ }
272
+ }
273
+ }
274
+ out += str[i];
275
+ vis += 1;
276
+ i += 1;
277
+ }
278
+ return out;
279
+ }
@@ -0,0 +1,148 @@
1
+ // Generated from packages/pi-better-subagents/log-cursor.ts. Do not edit directly.
2
+ /**
3
+ * Incremental NDJSON log reading for the UI hot path.
4
+ *
5
+ * Child run logs are append-only and can reach gigabytes: a `message_update`
6
+ * event re-serialises the whole accumulated message, so a long assistant turn
7
+ * grows the log roughly quadratically. Re-reading a whole log on every widget
8
+ * frame pegged the host's main thread (a 1 GB log, four times a second), and on
9
+ * logs past V8's max string length `readFileSync` fails outright. This module
10
+ * reads only the bytes appended since the previous call.
11
+ *
12
+ * Contract:
13
+ * - the cursor always sits on a line boundary, so callers only ever see
14
+ * complete lines — a half-written trailing line is left for the next read;
15
+ * - a log that shrank, or whose head bytes changed, is treated as a new log
16
+ * and re-read from a bounded tail (rotation / rewrite);
17
+ * - one read never exceeds `maxBytes`. When a log outran that budget the
18
+ * cursor skips ahead rather than falling permanently behind, and
19
+ * `truncated` reports that bytes were never seen.
20
+ */
21
+ import { closeSync, openSync, readSync, statSync } from "node:fs";
22
+ /** Bytes of the log head kept to detect a rewrite behind our back. */
23
+ const HEAD_SAMPLE_BYTES = 256;
24
+ /** Default ceiling on a single read: also the cold-start tail window. */
25
+ export const DEFAULT_MAX_READ_BYTES = 32 * 1024 * 1024; // 32 MiB
26
+ function errText(err) {
27
+ return err instanceof Error ? err.message : String(err);
28
+ }
29
+ function readAt(fd, position, length) {
30
+ const buf = Buffer.allocUnsafe(length);
31
+ let filled = 0;
32
+ while (filled < length) {
33
+ const n = readSync(fd, buf, filled, length - filled, position + filled);
34
+ if (n <= 0)
35
+ break;
36
+ filled += n;
37
+ }
38
+ return filled === length ? buf : buf.subarray(0, filled);
39
+ }
40
+ /** Head sample as a byte-exact string, for rewrite detection. */
41
+ function readHead(fd, size) {
42
+ const length = Math.min(HEAD_SAMPLE_BYTES, size);
43
+ if (length <= 0)
44
+ return "";
45
+ return readAt(fd, 0, length).toString("latin1");
46
+ }
47
+ /**
48
+ * Same log? Compare the prefix both samples cover, so a head that is still
49
+ * growing is not read as a rewrite. No shared prefix means one sample was taken
50
+ * while the log was empty — nothing was read from it, so there is nothing the
51
+ * new bytes could contradict.
52
+ */
53
+ function headsAgree(previous, current) {
54
+ const shared = Math.min(previous.length, current.length);
55
+ if (shared === 0)
56
+ return true;
57
+ return previous.slice(0, shared) === current.slice(0, shared);
58
+ }
59
+ /**
60
+ * Read the complete lines appended to `path` since `previous`.
61
+ *
62
+ * Passing `previous: undefined` starts cold: the last `maxBytes` of the log,
63
+ * with the leading partial line dropped.
64
+ */
65
+ export function readAppendedLines(path, previous, maxBytes = DEFAULT_MAX_READ_BYTES) {
66
+ const empty = (error) => ({
67
+ lines: [],
68
+ cursor: previous ?? { offset: 0, head: "" },
69
+ totalBytes: 0,
70
+ truncated: false,
71
+ restarted: false,
72
+ error,
73
+ });
74
+ let size;
75
+ try {
76
+ size = statSync(path).size;
77
+ }
78
+ catch (err) {
79
+ return empty(errText(err));
80
+ }
81
+ let fd;
82
+ try {
83
+ fd = openSync(path, "r");
84
+ }
85
+ catch (err) {
86
+ return empty(errText(err));
87
+ }
88
+ try {
89
+ const head = readHead(fd, size);
90
+ // A log that shrank or whose head changed is a different log: the old
91
+ // offset would point into unrelated bytes. Compare only the prefix the
92
+ // two samples share, so a log still shorter than the sample window is
93
+ // not "rewritten" every time it grows.
94
+ const resumable = previous !== undefined
95
+ && previous.offset <= size
96
+ && headsAgree(previous.head, head);
97
+ const restarted = previous !== undefined && !resumable;
98
+ let start = resumable ? previous.offset : 0;
99
+ let truncated = false;
100
+ if (size - start > maxBytes) {
101
+ // Skip ahead instead of lagging: a chatty log must not push the
102
+ // cursor permanently into the past.
103
+ start = size - maxBytes;
104
+ truncated = true;
105
+ }
106
+ // We begin mid-line whenever bytes were skipped.
107
+ const startedMidLine = truncated;
108
+ if (size === start) {
109
+ return { lines: [], cursor: { offset: start, head }, totalBytes: size, truncated, restarted };
110
+ }
111
+ const buf = readAt(fd, start, size - start);
112
+ const lastNewline = buf.lastIndexOf(0x0a);
113
+ if (lastNewline === -1) {
114
+ // No complete line yet. Hold position so the line can finish —
115
+ // unless it is an oversized partial we already skipped into, which
116
+ // would otherwise be re-read forever.
117
+ const offset = startedMidLine ? start + buf.length : start;
118
+ const partial = startedMidLine ? undefined : buf.toString("utf-8");
119
+ return { lines: [], partial, cursor: { offset, head }, totalBytes: size, truncated, restarted };
120
+ }
121
+ const text = buf.subarray(0, lastNewline + 1).toString("utf-8");
122
+ const lines = text.split("\n");
123
+ lines.pop(); // trailing "" after the final newline
124
+ if (startedMidLine)
125
+ lines.shift(); // partial first line
126
+ // Anything after the final newline is unterminated: hand it over
127
+ // separately rather than pretending it is a line.
128
+ const trailing = buf.subarray(lastNewline + 1);
129
+ const partial = trailing.length > 0 ? trailing.toString("utf-8") : undefined;
130
+ return {
131
+ lines,
132
+ partial,
133
+ cursor: { offset: start + lastNewline + 1, head },
134
+ totalBytes: size,
135
+ truncated,
136
+ restarted,
137
+ };
138
+ }
139
+ catch (err) {
140
+ return empty(errText(err));
141
+ }
142
+ finally {
143
+ try {
144
+ closeSync(fd);
145
+ }
146
+ catch { /* ignore */ }
147
+ }
148
+ }
@@ -0,0 +1,13 @@
1
+ import { realpathSync } from "node:fs";
2
+ import { tmpdir } from "node:os";
3
+ import { join } from "node:path";
4
+ /** Root of the VOLATILE runtime registry, deliberately OUTSIDE any repo. */
5
+ export function baseDir() {
6
+ return join(realpathSync(tmpdir()), "pi-better-subagents");
7
+ }
8
+ export function runDir(id) {
9
+ return join(baseDir(), "runs", id);
10
+ }
11
+ export function logPathFor(id) {
12
+ return join(runDir(id), "output.log");
13
+ }
@@ -0,0 +1,2 @@
1
+ export function parseRun(id: string, options?: { logPath?: string }): { usage: any; toolCalls: string[] };
2
+ export function readRunTranscript(id: string, options?: { logPath?: string }): any;