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,1223 @@
1
+ // Generated from packages/pi-better-subagents/shared-log-utils.ts. Do not edit directly.
2
+ // Generated from packages/log-utils/index.ts. Do not edit directly.
3
+ import { createHash } from "node:crypto";
4
+ import { closeSync, fstatSync, openSync, readFileSync, readSync, statSync } from "node:fs";
5
+ function errorText(error) {
6
+ return error instanceof Error ? error.message : String(error);
7
+ }
8
+ /**
9
+ * Read no more than `maxBytes` from a file's end. This avoids whole-file
10
+ * allocation for live logs that can grow past Node's string-size limit.
11
+ */
12
+ export function readBoundedTail(path, maxBytes) {
13
+ const budget = Math.max(1, Math.floor(maxBytes));
14
+ let totalBytes;
15
+ try {
16
+ totalBytes = statSync(path).size;
17
+ }
18
+ catch (error) {
19
+ return { text: "", truncated: false, totalBytes: 0, error: errorText(error) };
20
+ }
21
+ if (totalBytes === 0)
22
+ return { text: "", truncated: false, totalBytes };
23
+ if (totalBytes <= budget) {
24
+ try {
25
+ return { text: readFileSync(path, "utf8"), truncated: false, totalBytes };
26
+ }
27
+ catch (error) {
28
+ return { text: "", truncated: false, totalBytes, error: errorText(error) };
29
+ }
30
+ }
31
+ let fd;
32
+ try {
33
+ fd = openSync(path, "r");
34
+ const buffer = Buffer.allocUnsafe(budget);
35
+ const start = totalBytes - budget;
36
+ let offset = 0;
37
+ while (offset < budget) {
38
+ const read = readSync(fd, buffer, offset, budget - offset, start + offset);
39
+ if (read <= 0)
40
+ break;
41
+ offset += read;
42
+ }
43
+ return { text: buffer.toString("utf8", 0, offset), truncated: true, totalBytes };
44
+ }
45
+ catch (error) {
46
+ return { text: "", truncated: true, totalBytes, error: errorText(error) };
47
+ }
48
+ finally {
49
+ if (fd !== undefined) {
50
+ try {
51
+ closeSync(fd);
52
+ }
53
+ catch { /* best effort */ }
54
+ }
55
+ }
56
+ }
57
+ /**
58
+ * Convert terminal-like output into display rows. A bare carriage return is a
59
+ * cursor reset, so repeated progress redraws collapse to their latest state;
60
+ * CRLF remains a normal newline. Individual rows are capped defensively.
61
+ */
62
+ export function terminalDisplayRows(text, maxRowChars = 8 * 1024) {
63
+ const rowLimit = Math.max(64, Math.floor(maxRowChars));
64
+ const rows = [];
65
+ let current = "";
66
+ let progress = "";
67
+ const append = (value) => {
68
+ current += value;
69
+ if (current.length > rowLimit)
70
+ current = `...${current.slice(-(rowLimit - 3))}`;
71
+ };
72
+ const emit = () => {
73
+ const value = current || progress;
74
+ if (value)
75
+ rows.push(value);
76
+ current = "";
77
+ progress = "";
78
+ };
79
+ for (let i = 0; i < text.length; i += 1) {
80
+ const char = text[i];
81
+ if (char === "\r") {
82
+ if (text[i + 1] === "\n") {
83
+ emit();
84
+ i += 1;
85
+ }
86
+ else {
87
+ progress = current || progress;
88
+ current = "";
89
+ }
90
+ }
91
+ else if (char === "\n") {
92
+ emit();
93
+ }
94
+ else {
95
+ append(char);
96
+ }
97
+ }
98
+ const final = current || progress;
99
+ if (final)
100
+ rows.push(final);
101
+ return rows;
102
+ }
103
+ export function tailTerminalDisplay(text, rows, maxRowChars) {
104
+ const rendered = terminalDisplayRows(text, maxRowChars);
105
+ const count = Math.max(1, Math.floor(rows));
106
+ return rendered.slice(-count).join("\n");
107
+ }
108
+ // ---------------------------------------------------------------------------
109
+ // UTF-8 total-output budgets, verbatim paging, retained-file cursors, envelope
110
+ // ---------------------------------------------------------------------------
111
+ /** Issue #312 / OUTPUT-POLICY defaults: whole model-facing `content`, UTF-8 bytes. */
112
+ export const OUTPUT_BUDGET_BYTES = {
113
+ status: 1 * 1024,
114
+ answer: 2 * 1024,
115
+ log: 1 * 1024,
116
+ list: 1 * 1024,
117
+ callbackBatch: 2 * 1024,
118
+ rawPage: 16 * 1024,
119
+ };
120
+ /** Documented hard caps. Explicit larger pages are allowed up to these values. */
121
+ export const OUTPUT_BUDGET_MAX_BYTES = {
122
+ status: 2 * 1024,
123
+ answer: 8 * 1024,
124
+ log: 4 * 1024,
125
+ list: 4 * 1024,
126
+ callbackBatch: 8 * 1024,
127
+ rawPage: 64 * 1024,
128
+ };
129
+ export const OUTPUT_PAGE_DEFAULTS = {
130
+ logLines: 10,
131
+ listEntries: 10,
132
+ };
133
+ const encoder = new TextEncoder();
134
+ const decoder = new TextDecoder("utf-8", { fatal: false });
135
+ const CURSOR_PREFIX = "p1.";
136
+ const ROW_CURSOR_PREFIX = "l1.";
137
+ const HEAD_SAMPLE_BYTES = 256;
138
+ const WINDOW_SAMPLE_BYTES = 256;
139
+ const NEWLINE = 0x0a;
140
+ function positiveInt(value) {
141
+ const n = typeof value === "number" ? value : typeof value === "string" && value.trim() !== "" ? Number(value) : Number.NaN;
142
+ if (!Number.isFinite(n) || n <= 0)
143
+ return undefined;
144
+ return Math.max(1, Math.floor(n));
145
+ }
146
+ /** Nonpositive, NaN, and non-numeric inputs fall back; callers may request a lower budget. */
147
+ export function clampBudgetBytes(value, fallback) {
148
+ return positiveInt(value) ?? positiveInt(fallback) ?? 1;
149
+ }
150
+ /** Surface default, or a caller request clamped to the documented hard cap. */
151
+ export function budgetFor(surface, requested) {
152
+ const fallback = OUTPUT_BUDGET_BYTES[surface];
153
+ const cap = OUTPUT_BUDGET_MAX_BYTES[surface];
154
+ const n = positiveInt(requested);
155
+ if (n === undefined)
156
+ return fallback;
157
+ return Math.min(n, cap);
158
+ }
159
+ /** Pager budget: exact zero is an explicit empty page; garbage falls back. */
160
+ function pagerBudget(value, fallback) {
161
+ if (value === 0)
162
+ return 0;
163
+ const n = positiveInt(value);
164
+ if (n === undefined)
165
+ return fallback;
166
+ return Math.min(n, OUTPUT_BUDGET_MAX_BYTES.rawPage);
167
+ }
168
+ export function utf8ByteLength(text) {
169
+ return encoder.encode(text).byteLength;
170
+ }
171
+ function isContinuation(byte) {
172
+ return (byte & 0xc0) === 0x80;
173
+ }
174
+ function sequenceLength(lead) {
175
+ if (lead <= 0x7f)
176
+ return 1;
177
+ if ((lead & 0xe0) === 0xc0)
178
+ return 2;
179
+ if ((lead & 0xf0) === 0xe0)
180
+ return 3;
181
+ if ((lead & 0xf8) === 0xf0)
182
+ return 4;
183
+ return 1;
184
+ }
185
+ /**
186
+ * Largest end <= `to` that does not split a UTF-8 sequence, given that bytes
187
+ * after `to` are available in `bytes`. A sequence cut by the end of `bytes`
188
+ * itself is reported through `incompleteAtEnd` when `atEnd` is set.
189
+ */
190
+ function utf8SafeEnd(bytes, from, to) {
191
+ if (to <= from)
192
+ return from;
193
+ const limit = Math.min(to, bytes.length);
194
+ let seqStart = limit - 1;
195
+ while (seqStart > from && isContinuation(bytes[seqStart]) && limit - seqStart < 4)
196
+ seqStart -= 1;
197
+ const lead = bytes[seqStart];
198
+ if (isContinuation(lead))
199
+ return limit;
200
+ const needed = sequenceLength(lead);
201
+ if (needed === 1 || seqStart + needed <= limit)
202
+ return limit;
203
+ if (seqStart + needed <= bytes.length)
204
+ return seqStart;
205
+ // The sequence runs past the available bytes. When every following byte is
206
+ // a continuation it is a genuine, still-incomplete write; otherwise the
207
+ // source itself is malformed and is passed through rather than stalling.
208
+ for (let i = seqStart + 1; i < bytes.length; i += 1) {
209
+ if (!isContinuation(bytes[i]))
210
+ return limit;
211
+ }
212
+ return seqStart;
213
+ }
214
+ function alignStart(bytes, start) {
215
+ if (start <= 0)
216
+ return 0;
217
+ if (start >= bytes.length)
218
+ return bytes.length;
219
+ let i = start;
220
+ while (i < bytes.length && isContinuation(bytes[i]))
221
+ i += 1;
222
+ return i;
223
+ }
224
+ /**
225
+ * End the page after the last newline in [from, to) when that keeps at least
226
+ * half of the page; otherwise cut at `to` (already a UTF-8 boundary), so a
227
+ * short line followed by a huge one does not produce a nearly empty page.
228
+ */
229
+ function preferNewlineEnd(bytes, from, to) {
230
+ const floor = from + Math.ceil((to - from) / 2);
231
+ for (let i = to - 1; i >= floor - 1 && i >= from; i -= 1) {
232
+ if (bytes[i] === NEWLINE)
233
+ return i + 1;
234
+ }
235
+ return to;
236
+ }
237
+ /**
238
+ * Byte range for one text page. With `forceProgress` a budget smaller than
239
+ * the next code point still returns that code point (display clipping only);
240
+ * pagers pass `false` so a page never exceeds its budget.
241
+ */
242
+ function sliceUtf8Range(bytes, start, maxBytes, preferNewline, forceProgress = true) {
243
+ const from = alignStart(bytes, start);
244
+ if (from >= bytes.length)
245
+ return { start: from, end: from };
246
+ const budget = Math.max(0, Math.floor(maxBytes));
247
+ let to = utf8SafeEnd(bytes, from, Math.min(bytes.length, from + budget));
248
+ if (to <= from) {
249
+ if (!forceProgress)
250
+ return { start: from, end: from };
251
+ to = Math.min(bytes.length, from + sequenceLength(bytes[from]));
252
+ }
253
+ // Prefer a newline only when this slice is truncated. If the remainder fits,
254
+ // keep a final line that has no trailing newline.
255
+ if (preferNewline && to > from && to < bytes.length)
256
+ to = preferNewlineEnd(bytes, from, to);
257
+ return { start: from, end: to };
258
+ }
259
+ /** Display clipping helper. It may exceed `maxBytes` by one code point to make progress. */
260
+ export function sliceUtf8Bytes(text, startByte, maxBytes, preferNewline = true) {
261
+ const encoded = encoder.encode(text);
262
+ const range = sliceUtf8Range(encoded, startByte, maxBytes, preferNewline);
263
+ return {
264
+ text: decoder.decode(encoded.subarray(range.start, range.end)),
265
+ startByte: range.start,
266
+ endByte: range.end,
267
+ bytes: range.end - range.start,
268
+ };
269
+ }
270
+ function hashBytes(bytes) {
271
+ return createHash("sha256").update(bytes).digest("base64url");
272
+ }
273
+ /** Short digest stored in cursors (128 bits): cursors stay small in the model-facing budget. */
274
+ function shortHash(bytes) {
275
+ return hashBytes(bytes).slice(0, 22);
276
+ }
277
+ /** Cursors carry a digest of their resource/scope, never the scope text itself. */
278
+ function resourceTag(resource) {
279
+ return hashBytes(encoder.encode(resource)).slice(0, 16);
280
+ }
281
+ /**
282
+ * Cursors that carry an offset are tagged, so a hand-copied cursor can be
283
+ * recognised as damaged. Status cursors are not: they hold no offset, a
284
+ * damaged one already falls back to the current facts, and their payload sits
285
+ * in 1 KiB status responses where every cursor byte competes with decision
286
+ * facts (`remote setup: …` was clipped once the cursor grew).
287
+ */
288
+ function isTaggedCursorKind(kind) {
289
+ return kind !== "s";
290
+ }
291
+ function encodeCursor(payload) {
292
+ const tagged = isTaggedCursorKind(payload.k) ? { ...payload, x: cursorIntegrityTag(payload) } : payload;
293
+ return CURSOR_PREFIX + Buffer.from(JSON.stringify(tagged), "utf8").toString("base64url");
294
+ }
295
+ /**
296
+ * Integrity tag over every payload field except the tag itself.
297
+ *
298
+ * Cursors are re-typed by the model. One mistyped base64url character used to
299
+ * decode into a payload that still parsed: when the changed field was the
300
+ * source digest the pager reported `source-replaced`, restarted at byte 0 and
301
+ * minted the same cursor again — the caller could never reach the rest of the
302
+ * text (#617). The tag makes a near-miss detectable as corruption instead of
303
+ * being read as a different source.
304
+ */
305
+ function cursorIntegrityTag(payload) {
306
+ const { x: _ignored, ...rest } = payload;
307
+ // 36 bits: enough to catch an accidental edit, and short enough that the
308
+ // cursor stays a small thing to copy.
309
+ return shortHash(encoder.encode(JSON.stringify(rest))).slice(0, 6);
310
+ }
311
+ /**
312
+ * Structural decode only: a corrupted payload still reports its kind and
313
+ * resource so it can be classified and, where the offset is still meaningful,
314
+ * resumed. `cursorIntegrityOk` is the separate integrity verdict.
315
+ */
316
+ function decodeCursor(cursor) {
317
+ if (!cursor || !cursor.startsWith(CURSOR_PREFIX))
318
+ return undefined;
319
+ try {
320
+ const parsed = JSON.parse(Buffer.from(cursor.slice(CURSOR_PREFIX.length), "base64url").toString("utf8"));
321
+ if (parsed?.k === "t" || parsed?.k === "f" || parsed?.k === "s")
322
+ return parsed;
323
+ }
324
+ catch {
325
+ return undefined;
326
+ }
327
+ return undefined;
328
+ }
329
+ /** False when any payload field was altered after the cursor was minted. */
330
+ function cursorIntegrityOk(parsed) {
331
+ if (!isTaggedCursorKind(parsed.k))
332
+ return true;
333
+ return typeof parsed.x === "string" && parsed.x === cursorIntegrityTag(parsed);
334
+ }
335
+ /**
336
+ * Digest of one source snapshot at one offset. A text cursor carries it in `v`
337
+ * and, recomputed against the current text, it answers both questions a
338
+ * continuation needs: is this still the same source, and is this still its
339
+ * offset? A changed source or a shifted offset changes it (#617).
340
+ */
341
+ function textSnapshotDigest(revision, offset) {
342
+ return shortHash(encoder.encode(`t\0${revision}\0${offset}`));
343
+ }
344
+ /**
345
+ * Second, independent witness of the same fact, stored in `w`: the snapshot,
346
+ * its length, and the offset. Both witnesses are recomputed from the current
347
+ * text, so damage to either one alone still leaves a usable cursor — the
348
+ * reported one-character miscopy keeps the page advancing instead of replaying
349
+ * page 1 forever, while a genuinely replaced or shifted source fails both.
350
+ */
351
+ function textOffsetWitness(revision, offset, length) {
352
+ return shortHash(encoder.encode(`t\0${revision}\0${length}\0${offset}`)).slice(0, 6);
353
+ }
354
+ /** Decoded page offset, or NaN when the field did not survive decoding. */
355
+ function cursorOffset(parsed) {
356
+ const o = parsed.o;
357
+ return typeof o === "number" && Number.isFinite(o) ? Math.floor(o) : Number.NaN;
358
+ }
359
+ export function cursorKind(cursor) {
360
+ if (cursor?.startsWith(ROW_CURSOR_PREFIX))
361
+ return decodeRowCursor(cursor) ? "l" : undefined;
362
+ return decodeCursor(cursor)?.k;
363
+ }
364
+ function readAt(fd, position, length) {
365
+ if (length <= 0)
366
+ return Buffer.alloc(0);
367
+ const buffer = Buffer.allocUnsafe(length);
368
+ let filled = 0;
369
+ while (filled < length) {
370
+ const n = readSync(fd, buffer, filled, length - filled, position + filled);
371
+ if (n <= 0)
372
+ break;
373
+ filled += n;
374
+ }
375
+ return filled === length ? buffer : buffer.subarray(0, filled);
376
+ }
377
+ function singleLine(value) {
378
+ return value.replace(/[\r\n\x00-\x1f\x7f]/g, " ").trim();
379
+ }
380
+ function emptyPage(overrides) {
381
+ return {
382
+ text: "",
383
+ hasMore: false,
384
+ omittedBytes: 0,
385
+ totalBytes: 0,
386
+ startByte: 0,
387
+ endByte: 0,
388
+ gaps: [],
389
+ ...overrides,
390
+ };
391
+ }
392
+ /**
393
+ * Page exact UTF-8 text. Consecutive pages concatenate to the original string.
394
+ * Cursors are caller-owned: the same cursor plus maxBytes always yields the
395
+ * same page, and two callers do not share consumption.
396
+ *
397
+ * A cursor that fails its integrity check is reported as `cursor-corrupt`,
398
+ * never as a replaced source, and never replays page 1 blindly: it resumes at
399
+ * its decoded offset only when a witness recomputed from the current text
400
+ * proves that offset still belongs to the same snapshot. Otherwise — a
401
+ * replaced, grown, or shifted source, a damaged offset, or a cursor from
402
+ * before the witnesses existed — the page restarts at byte 0, so no unread
403
+ * text is skipped (#617).
404
+ */
405
+ export function pageVerbatimText(text, request = {}) {
406
+ const maxBytes = pagerBudget(request.maxBytes, OUTPUT_BUDGET_BYTES.answer);
407
+ const encoded = encoder.encode(text);
408
+ const revision = shortHash(encoded);
409
+ const resource = request.resource === undefined ? undefined : resourceTag(request.resource);
410
+ let offset = 0;
411
+ let reset;
412
+ const parsed = decodeCursor(request.cursor);
413
+ if (request.cursor) {
414
+ if (!parsed || parsed.k !== "t") {
415
+ reset = "stale-cursor";
416
+ }
417
+ else if (!cursorIntegrityOk(parsed) || parsed.w === undefined) {
418
+ // A payload without its position witness (a cursor minted before this
419
+ // format) is treated the same as a damaged one: its offset is unproven.
420
+ reset = "cursor-corrupt";
421
+ if ((parsed.r ?? undefined) === resource) {
422
+ const decoded = cursorOffset(parsed);
423
+ const inside = Number.isFinite(decoded) && decoded >= 0 && decoded <= encoded.length;
424
+ // Two independent witnesses of "this snapshot at this offset": either
425
+ // one surviving a single damaged field keeps a static-source cursor
426
+ // moving instead of looping on page 1.
427
+ const witnessed = inside && (parsed.v === textSnapshotDigest(revision, decoded)
428
+ || (parsed.w !== undefined && parsed.w === textOffsetWitness(revision, decoded, encoded.length)));
429
+ if (witnessed)
430
+ offset = decoded;
431
+ }
432
+ }
433
+ else if ((parsed.r ?? undefined) !== resource) {
434
+ reset = "stale-cursor";
435
+ }
436
+ else {
437
+ offset = Math.min(encoded.length, Math.max(0, Math.floor(parsed.o ?? 0)));
438
+ if (parsed.v !== textSnapshotDigest(revision, offset)) {
439
+ // Same cursor, different text: restart at byte 0 rather than serving
440
+ // bytes from a position that no longer means what it did.
441
+ reset = "source-replaced";
442
+ offset = 0;
443
+ }
444
+ }
445
+ }
446
+ const mint = (o) => encodeCursor({
447
+ k: "t",
448
+ ...(resource !== undefined ? { r: resource } : {}),
449
+ v: textSnapshotDigest(revision, o),
450
+ o,
451
+ n: encoded.length,
452
+ w: textOffsetWitness(revision, o, encoded.length),
453
+ });
454
+ const make = (start, end) => ({
455
+ text: decoder.decode(encoded.subarray(start, end)),
456
+ revision,
457
+ cursor: mint(start),
458
+ nextCursor: mint(end),
459
+ hasMore: end < encoded.length,
460
+ omittedBytes: Math.max(0, encoded.length - end),
461
+ totalBytes: encoded.length,
462
+ startByte: start,
463
+ endByte: end,
464
+ ...(reset ? { reset } : {}),
465
+ gaps: [],
466
+ });
467
+ if (offset >= encoded.length)
468
+ return make(encoded.length, encoded.length);
469
+ const range = sliceUtf8Range(encoded, offset, maxBytes, true, false);
470
+ let end = range.end;
471
+ const maxLines = positiveInt(request.maxLines);
472
+ if (maxLines !== undefined) {
473
+ let seen = 0;
474
+ for (let i = range.start; i < end; i += 1) {
475
+ if (encoded[i] === NEWLINE) {
476
+ seen += 1;
477
+ if (seen >= maxLines) {
478
+ end = i + 1;
479
+ break;
480
+ }
481
+ }
482
+ }
483
+ }
484
+ return make(range.start, end);
485
+ }
486
+ function fileGaps(request) {
487
+ const gaps = [];
488
+ const discarded = request.discardedBytes;
489
+ if (typeof discarded === "number" && Number.isFinite(discarded) && discarded > 0) {
490
+ gaps.push({
491
+ kind: "retention",
492
+ bytes: Math.floor(discarded),
493
+ detail: "older retained bytes discarded",
494
+ });
495
+ }
496
+ for (const gap of request.captureGaps ?? []) {
497
+ if (!Number.isFinite(gap.bytes) || gap.bytes <= 0)
498
+ continue;
499
+ gaps.push({ kind: "capture", bytes: Math.floor(gap.bytes), detail: gap.detail });
500
+ }
501
+ return gaps;
502
+ }
503
+ /**
504
+ * Identity of the file object, not just its path. Linux filesystems reuse a
505
+ * freed inode number immediately, so a delete + recreate can keep `dev:ino`;
506
+ * the birth time tells the files apart where the platform reports it at fine
507
+ * granularity. With coarse timestamps the two are indistinguishable by stat,
508
+ * and the head/pre-offset byte checks classify the change instead.
509
+ */
510
+ function fileIdentity(stats) {
511
+ const birth = stats.birthtimeNs > 0n ? `:${stats.birthtimeNs.toString(36)}` : "";
512
+ return `${stats.dev.toString(36)}:${stats.ino.toString(36)}${birth}`;
513
+ }
514
+ function fileRevision(generation, identity, snapshot) {
515
+ return `${generation ?? ""}|${identity}|${snapshot}`;
516
+ }
517
+ function fileReadError(request, path, error, reset) {
518
+ const resource = resourceTag(request.resource ?? path);
519
+ const cursor = encodeCursor({ k: "f", r: resource, o: 0, n: 0 });
520
+ return emptyPage({
521
+ revision: "unreadable",
522
+ cursor,
523
+ nextCursor: cursor,
524
+ gaps: [...fileGaps(request), { kind: "read", detail: errorText(error) }],
525
+ ...(reset ? { reset } : {}),
526
+ });
527
+ }
528
+ /**
529
+ * Start byte of an end-anchored page inside `window` (the bytes immediately
530
+ * before its upper bound). A backward page starts just after the first newline
531
+ * that keeps at least half the window, so consecutive pages concatenate; when
532
+ * no such newline exists (one oversized line) it starts on the next whole code
533
+ * point and the page begins mid-line rather than stalling.
534
+ */
535
+ function backwardPageStart(window) {
536
+ let start = 0;
537
+ while (start < window.length && isContinuation(window[start]))
538
+ start += 1;
539
+ const floor = Math.ceil(window.length / 2);
540
+ for (let i = start; i < floor; i += 1) {
541
+ if (window[i] === NEWLINE)
542
+ return i + 1;
543
+ }
544
+ return start;
545
+ }
546
+ /**
547
+ * Largest boundary <= `end` that does not split a UTF-8 sequence, looking only
548
+ * at the bytes retained up to `end`. Used for the newest retained byte, which
549
+ * a writer can leave inside a code point it has not finished emitting.
550
+ */
551
+ function completeCodePointEnd(fd, end) {
552
+ if (end <= 0)
553
+ return 0;
554
+ const from = Math.max(0, end - 4);
555
+ const tail = readAt(fd, from, end - from);
556
+ return from + utf8SafeEnd(tail, 0, tail.length);
557
+ }
558
+ /**
559
+ * Page retained file bytes without skipping unread ranges. Snapshot high-water
560
+ * marks keep a page stable while the file appends. Cursors bind the resource
561
+ * (task/run plus session scope), the file object's identity, the consumer
562
+ * generation, the head, and the bytes just before the offset, so replacement,
563
+ * same-inode compaction, and in-place rewrites reset instead of resuming at a
564
+ * meaningless offset. A trailing, still-incomplete UTF-8 sequence is withheld
565
+ * (`pendingBytes`) and returned whole once the writer completes it.
566
+ */
567
+ export function pageRetainedFile(path, request = {}) {
568
+ const maxBytes = pagerBudget(request.maxBytes, OUTPUT_BUDGET_BYTES.rawPage);
569
+ const resource = resourceTag(request.resource ?? path);
570
+ const generation = request.generation === undefined ? undefined : String(request.generation);
571
+ const suppliedGaps = fileGaps(request);
572
+ let fd;
573
+ try {
574
+ fd = openSync(path, "r");
575
+ }
576
+ catch (error) {
577
+ return fileReadError(request, path, error, request.cursor ? "source-replaced" : undefined);
578
+ }
579
+ const opened = fd;
580
+ try {
581
+ const stats = fstatSync(opened, { bigint: true });
582
+ const size = Number(stats.size);
583
+ const identity = fileIdentity(stats);
584
+ const head = readAt(opened, 0, Math.min(HEAD_SAMPLE_BYTES, size));
585
+ const headHash = shortHash(head);
586
+ const windowHash = (o) => {
587
+ if (o <= 0)
588
+ return undefined;
589
+ const from = Math.max(0, o - WINDOW_SAMPLE_BYTES);
590
+ return shortHash(readAt(opened, from, o - from));
591
+ };
592
+ const initialSnapshot = () => Math.min(size, request.snapshotBytes !== undefined
593
+ ? clampBudgetBytes(request.snapshotBytes, size)
594
+ : size);
595
+ const parsed = decodeCursor(request.cursor);
596
+ let reset;
597
+ let offset = 0;
598
+ let snapshot = initialSnapshot();
599
+ let appendReady = false;
600
+ if (request.cursor) {
601
+ if (!parsed || parsed.k !== "f") {
602
+ reset = "stale-cursor";
603
+ }
604
+ else {
605
+ // A hand-copied cursor is never reported as a replaced source: that was
606
+ // a false claim, and the restart replayed page 1 forever (#617). A
607
+ // damaged payload is also never resumed: its offset *and* its direction
608
+ // come from a payload that failed its integrity check, so the pass
609
+ // restarts at its own anchor (byte 0 forward, the newest byte backward)
610
+ // instead of continuing somewhere the caller never reached (#617 R1).
611
+ const corrupt = !cursorIntegrityOk(parsed);
612
+ const reason = (clean) => (corrupt ? "cursor-corrupt" : clean);
613
+ if (parsed.r !== resource) {
614
+ reset = reason("stale-cursor");
615
+ }
616
+ else if (parsed.i !== identity) {
617
+ reset = reason("source-replaced");
618
+ }
619
+ else if (corrupt) {
620
+ reset = "cursor-corrupt";
621
+ }
622
+ else {
623
+ const o = Math.max(0, Math.floor(parsed.o ?? 0));
624
+ const n = Math.max(0, Math.floor(parsed.n ?? 0));
625
+ const headLength = Math.max(0, Math.floor(parsed.hl ?? 0));
626
+ const generationChanged = generation !== undefined && parsed.g !== generation;
627
+ const bytesIntact = o <= n
628
+ && n <= size
629
+ && headLength <= size
630
+ && (!parsed.h || shortHash(head.subarray(0, headLength)) === parsed.h)
631
+ && (o === 0 || windowHash(o) === parsed.w);
632
+ if (generationChanged) {
633
+ // The consumer declared a compaction/replacement of this file.
634
+ reset = "compacted";
635
+ }
636
+ else if (!bytesIntact) {
637
+ // Same file object as far as stat can tell, but the bytes behind the
638
+ // cursor changed without a declared compaction: rewritten in place,
639
+ // or deleted and recreated on a reused inode with coarse timestamps.
640
+ reset = "source-replaced";
641
+ }
642
+ else {
643
+ offset = o;
644
+ snapshot = n;
645
+ appendReady = parsed.a === 1;
646
+ }
647
+ }
648
+ }
649
+ }
650
+ if (appendReady && offset >= snapshot && size > snapshot) {
651
+ snapshot = Math.max(snapshot, initialSnapshot());
652
+ }
653
+ const mint = (o, n, append, back = false) => {
654
+ const window = windowHash(o);
655
+ return encodeCursor({
656
+ k: "f",
657
+ r: resource,
658
+ o,
659
+ n,
660
+ ...(generation !== undefined ? { g: generation } : {}),
661
+ i: identity,
662
+ h: headHash,
663
+ hl: head.length,
664
+ ...(window ? { w: window } : {}),
665
+ ...(append ? { a: 1 } : {}),
666
+ ...(back ? { b: 1 } : {}),
667
+ });
668
+ };
669
+ const base = {
670
+ gaps: suppliedGaps,
671
+ ...(reset ? { reset } : {}),
672
+ };
673
+ // A backward cursor keeps its own direction (even after a reset, which
674
+ // restarts at the newest bytes); the request flag starts one.
675
+ const backward = parsed?.k === "f" ? parsed.b === 1 : request.direction === "backward";
676
+ if (backward) {
677
+ if (!request.cursor || reset)
678
+ offset = snapshot;
679
+ if (offset > snapshot)
680
+ offset = snapshot;
681
+ const mintBackward = (o) => mint(o, snapshot, false, true);
682
+ const revision = fileRevision(generation, identity, snapshot);
683
+ // The newest retained byte can stop inside a code point the writer has not
684
+ // finished. Withhold that suffix like the forward pager does, and anchor
685
+ // the append cursor at its first byte, so the whole character arrives once
686
+ // the writer completes it. Every other page starts where a previous page
687
+ // already aligned.
688
+ const snapshotEnd = completeCodePointEnd(opened, snapshot);
689
+ if (offset <= 0) {
690
+ // Nothing earlier is retained: hand back the forward append-ready cursor.
691
+ return emptyPage({
692
+ revision,
693
+ cursor: mintBackward(0),
694
+ nextCursor: mint(snapshotEnd, snapshotEnd, true),
695
+ totalBytes: snapshot,
696
+ startByte: 0,
697
+ endByte: 0,
698
+ appendReady: true,
699
+ direction: "backward",
700
+ ...(snapshotEnd < snapshot ? { pendingBytes: snapshot - snapshotEnd } : {}),
701
+ ...base,
702
+ });
703
+ }
704
+ const from = Math.max(0, offset - maxBytes);
705
+ const window = readAt(opened, from, offset - from);
706
+ const withheldFrom = offset === snapshot ? snapshotEnd : offset;
707
+ const pendingBytes = offset - withheldFrom;
708
+ // Byte 0 is always a valid page start; otherwise start at the first line
709
+ // boundary that keeps as much of the window as possible.
710
+ const reachedStart = from === 0;
711
+ const start = reachedStart ? 0 : from + backwardPageStart(window.subarray(0, withheldFrom - from));
712
+ if (!reachedStart && start >= withheldFrom) {
713
+ // Budget is smaller than the next code point behind the cursor: stay put.
714
+ const here = mintBackward(offset);
715
+ return emptyPage({
716
+ revision,
717
+ cursor: here,
718
+ nextCursor: here,
719
+ hasMore: true,
720
+ omittedBytes: offset,
721
+ totalBytes: snapshot,
722
+ startByte: offset,
723
+ endByte: offset,
724
+ direction: "backward",
725
+ ...(pendingBytes > 0 ? { pendingBytes } : {}),
726
+ ...base,
727
+ });
728
+ }
729
+ return {
730
+ text: decoder.decode(window.subarray(start - from, withheldFrom - from)),
731
+ revision,
732
+ cursor: mintBackward(offset),
733
+ // Reaching the oldest byte hands the whole pass back to forward polling:
734
+ // the append cursor sits on the newest complete code point, so a withheld
735
+ // character is returned whole rather than skipped.
736
+ nextCursor: reachedStart ? mint(snapshotEnd, snapshotEnd, true) : mintBackward(start),
737
+ hasMore: !reachedStart,
738
+ omittedBytes: start,
739
+ totalBytes: snapshot,
740
+ startByte: start,
741
+ endByte: withheldFrom,
742
+ ...(reachedStart ? { appendReady: true } : {}),
743
+ ...(pendingBytes > 0 ? { pendingBytes } : {}),
744
+ direction: "backward",
745
+ ...base,
746
+ };
747
+ }
748
+ if (offset > snapshot)
749
+ offset = snapshot;
750
+ if (offset >= snapshot) {
751
+ return emptyPage({
752
+ revision: fileRevision(generation, identity, snapshot),
753
+ cursor: mint(offset, snapshot, true),
754
+ nextCursor: mint(snapshot, snapshot, true),
755
+ totalBytes: snapshot,
756
+ startByte: snapshot,
757
+ endByte: snapshot,
758
+ appendReady: true,
759
+ ...base,
760
+ });
761
+ }
762
+ const available = snapshot - offset;
763
+ const limit = Math.min(maxBytes, available);
764
+ const atSnapshotEnd = limit === available;
765
+ const buffer = readAt(opened, offset, Math.min(available, limit + 4));
766
+ let end = utf8SafeEnd(buffer, 0, limit);
767
+ let pendingBytes = 0;
768
+ if (atSnapshotEnd && end < limit) {
769
+ // The retained bytes stop inside a sequence that is still being written.
770
+ pendingBytes = available - end;
771
+ snapshot = offset + end;
772
+ }
773
+ else if (!atSnapshotEnd && end > 0) {
774
+ end = preferNewlineEnd(buffer, 0, end);
775
+ }
776
+ const endByte = offset + end;
777
+ const revision = fileRevision(generation, identity, snapshot);
778
+ if (end === 0 && pendingBytes === 0) {
779
+ // Budget is smaller than the next code point: stay put, skip nothing.
780
+ const here = mint(offset, snapshot, false);
781
+ return emptyPage({
782
+ revision,
783
+ cursor: here,
784
+ nextCursor: here,
785
+ hasMore: true,
786
+ omittedBytes: available,
787
+ totalBytes: snapshot,
788
+ startByte: offset,
789
+ endByte: offset,
790
+ ...base,
791
+ });
792
+ }
793
+ const atEnd = endByte >= snapshot;
794
+ return {
795
+ text: decoder.decode(buffer.subarray(0, end)),
796
+ revision,
797
+ cursor: mint(offset, snapshot, false),
798
+ nextCursor: mint(endByte, snapshot, atEnd),
799
+ hasMore: !atEnd,
800
+ omittedBytes: Math.max(0, snapshot - endByte),
801
+ totalBytes: snapshot,
802
+ startByte: offset,
803
+ endByte,
804
+ ...(atEnd ? { appendReady: true } : {}),
805
+ ...(pendingBytes > 0 ? { pendingBytes } : {}),
806
+ ...base,
807
+ };
808
+ }
809
+ catch (error) {
810
+ return fileReadError(request, path, error, request.cursor ? "source-replaced" : undefined);
811
+ }
812
+ finally {
813
+ if (fd !== undefined) {
814
+ try {
815
+ closeSync(fd);
816
+ }
817
+ catch { /* best effort */ }
818
+ }
819
+ }
820
+ }
821
+ function statusRevisionToken(contentRevision, failureRevision) {
822
+ return hashBytes(encoder.encode(`${contentRevision}\0${failureRevision}`));
823
+ }
824
+ /**
825
+ * Compare a caller-owned status cursor to the current content and failure
826
+ * revisions. Failure-only changes are distinct from log-byte changes; nothing
827
+ * is consumed globally.
828
+ */
829
+ export function inspectStatusRevision(input) {
830
+ const revision = statusRevisionToken(input.contentRevision, input.failureRevision);
831
+ const resource = resourceTag(input.resource);
832
+ const content = shortHash(encoder.encode(input.contentRevision)).slice(0, 16);
833
+ const failure = shortHash(encoder.encode(input.failureRevision)).slice(0, 16);
834
+ const nextCursor = encodeCursor({ k: "s", r: resource, c: content, f: failure });
835
+ const parsed = decodeCursor(input.cursor);
836
+ if (!input.cursor)
837
+ return { change: "content", revision, nextCursor };
838
+ if (!parsed || parsed.k !== "s" || parsed.r !== resource) {
839
+ return { change: "reset", reset: "stale-cursor", revision, nextCursor };
840
+ }
841
+ const contentSame = parsed.c === content;
842
+ const failureSame = parsed.f === failure;
843
+ if (contentSame && failureSame)
844
+ return { change: "none", revision, nextCursor };
845
+ if (contentSame && !failureSame)
846
+ return { change: "failure", revision, nextCursor };
847
+ return { change: "content", revision, nextCursor };
848
+ }
849
+ export function formatUnchangedEvidence(cursor) {
850
+ return `No new evidence since cursor ${cursor}.`;
851
+ }
852
+ /** Stable short revision of arbitrary JSON-serialisable status facts. */
853
+ export function revisionOf(value) {
854
+ return createHash("sha256").update(JSON.stringify(value) ?? "undefined").digest("base64url").slice(0, 32);
855
+ }
856
+ // ---------------------------------------------------------------------------
857
+ // Shared output-control parameters, session scope keys, and log identity facts
858
+ // (#321/#323). Subagent and background-task tools both read these, so the two
859
+ // families cannot drift.
860
+ // ---------------------------------------------------------------------------
861
+ /**
862
+ * Canonical output-control parameter names and their deprecated aliases.
863
+ * Canonical names follow this repo's dominant snake_case tool-parameter style
864
+ * (`max_log_bytes`, `timeout_seconds`, `exclude_tools`, `sandbox_dir`, ...).
865
+ */
866
+ export const OUTPUT_CONTROL_ALIASES = {
867
+ max_bytes: "maxBytes",
868
+ lines: "tail_lines",
869
+ };
870
+ /**
871
+ * Resolve output-control parameters. Both spellings work; when both are given
872
+ * the canonical name wins. An explicit `null` is "not given", so a null
873
+ * canonical value never hides an alias value (#332). Values are returned
874
+ * unvalidated so each surface keeps its own defaults and hard caps.
875
+ */
876
+ export function readOutputControls(params) {
877
+ const p = (params && typeof params === "object" ? params : {});
878
+ const pick = (canonical) => p[canonical] ?? p[OUTPUT_CONTROL_ALIASES[canonical]] ?? undefined;
879
+ const maxBytes = pick("max_bytes");
880
+ const lines = pick("lines");
881
+ return {
882
+ ...(maxBytes !== undefined ? { maxBytes } : {}),
883
+ ...(lines !== undefined ? { lines } : {}),
884
+ };
885
+ }
886
+ /** Explicit opt-in sections for otherwise-omitted spend and tool facts. */
887
+ export const OUTPUT_INCLUDE_VALUES = ["cost", "tools"];
888
+ /** Parse an `include` request into known values and unknown ones (both deduplicated). */
889
+ export function readOutputInclude(value) {
890
+ // Any other non-null value (a number, boolean, or object) is one unknown entry, never silently nothing (#332).
891
+ const raw = Array.isArray(value) ? value : typeof value === "string" ? value.split(",") : value == null ? [] : [value];
892
+ const include = new Set();
893
+ const unknown = [];
894
+ for (const entry of raw) {
895
+ const name = String(entry ?? "").trim().toLowerCase();
896
+ if (!name)
897
+ continue;
898
+ if (OUTPUT_INCLUDE_VALUES.includes(name))
899
+ include.add(name);
900
+ else if (!unknown.includes(name))
901
+ unknown.push(name);
902
+ }
903
+ return { include, unknown };
904
+ }
905
+ /** Stable digest of one cwd + session origin (the digest the subagent registry indexes by). */
906
+ export function originScopeDigest(origin) {
907
+ return createHash("sha256").update(origin.cwd).update("\0").update(origin.sessionId ?? "").digest("hex").slice(0, 24);
908
+ }
909
+ /**
910
+ * Cursor scope. Every pagination and revision cursor binds this key, so a
911
+ * cursor never crosses session scopes. `unavailable` wins over an origin: a
912
+ * caller whose session identity could not be read is never the same scope as
913
+ * a readable one.
914
+ */
915
+ export function sessionScopeKey(input) {
916
+ if (input.all)
917
+ return "all";
918
+ if (input.unavailable)
919
+ return "session:unavailable";
920
+ if (input.origin)
921
+ return `session:${originScopeDigest(input.origin)}${!input.origin.sessionId && input.processId !== undefined ? `:process:${input.processId}` : ""}`;
922
+ return input.fallback ?? "none";
923
+ }
924
+ /**
925
+ * Identity facts of a retained log for a content revision: device, inode,
926
+ * size, and whole-millisecond mtime, or the read error. A deleted, replaced,
927
+ * or appended log is a content change.
928
+ */
929
+ export function logIdentityFacts(path) {
930
+ try {
931
+ const stats = statSync(path);
932
+ return [stats.dev, stats.ino, stats.size, Math.trunc(stats.mtimeMs)];
933
+ }
934
+ catch (error) {
935
+ return ["unreadable", error.code ?? String(error)];
936
+ }
937
+ }
938
+ /** Content revision: consumer lifecycle facts followed by the retained log's identity. */
939
+ export function lifecycleContentRevision(facts, logPath) {
940
+ return revisionOf([...facts, logIdentityFacts(logPath)]);
941
+ }
942
+ function encodeRowCursor(payload) {
943
+ return ROW_CURSOR_PREFIX + Buffer.from(JSON.stringify(payload), "utf8").toString("base64url");
944
+ }
945
+ function decodeRowCursor(cursor) {
946
+ if (!cursor || !cursor.startsWith(ROW_CURSOR_PREFIX))
947
+ return undefined;
948
+ try {
949
+ const parsed = JSON.parse(Buffer.from(cursor.slice(ROW_CURSOR_PREFIX.length), "base64url").toString("utf8"));
950
+ if (parsed?.k === "l" && typeof parsed.r === "string" && typeof parsed.t === "number" && typeof parsed.i === "string")
951
+ return parsed;
952
+ }
953
+ catch {
954
+ return undefined;
955
+ }
956
+ return undefined;
957
+ }
958
+ export function isRowCursor(cursor) {
959
+ return decodeRowCursor(cursor) !== undefined;
960
+ }
961
+ /** Resolve a list anchor only in the scope/filter that issued it. */
962
+ export function rowCursorKey(cursor, resource) {
963
+ const parsed = decodeRowCursor(cursor);
964
+ return parsed?.r === resourceTag(resource) && Number.isFinite(parsed.t) ? { time: parsed.t, id: parsed.i } : undefined;
965
+ }
966
+ /** Sorts before every real row: a cursor anchored here starts at the first row. */
967
+ const HEAD_ROW_KEY = { time: Number.MAX_SAFE_INTEGER, id: "" };
968
+ function rowOrder(a, b) {
969
+ if (a.time !== b.time)
970
+ return b.time - a.time;
971
+ return a.id < b.id ? 1 : a.id > b.id ? -1 : 0;
972
+ }
973
+ function clipRow(row, maxBytes) {
974
+ if (utf8ByteLength(row) <= maxBytes)
975
+ return row;
976
+ const marker = "…";
977
+ const room = maxBytes - utf8ByteLength(marker);
978
+ if (room <= 0)
979
+ return "";
980
+ const encoded = encoder.encode(row);
981
+ const end = utf8SafeEnd(encoded, 0, room);
982
+ return `${decoder.decode(encoded.subarray(0, end))}${marker}`;
983
+ }
984
+ /**
985
+ * Page compact rows newest-first. The cursor records the last row shown, so
986
+ * rows inserted ahead of it (new tasks) never shift later pages and rows are
987
+ * neither repeated nor skipped. Only whole rows are counted as shown; a single
988
+ * row larger than the page is clipped (callers put the id first).
989
+ */
990
+ export function pageRows(items, request) {
991
+ const keyed = items.map((item) => ({ item, key: request.keyOf(item) }))
992
+ .sort((a, b) => rowOrder(a.key, b.key));
993
+ const total = request.indexed?.total ?? keyed.length;
994
+ const limit = Math.max(1, Math.floor(request.limit));
995
+ const maxBytes = Math.max(0, Math.floor(request.maxBytes));
996
+ let start = 0;
997
+ let reset;
998
+ const resource = resourceTag(request.resource);
999
+ if (request.cursor) {
1000
+ const parsed = decodeRowCursor(request.cursor);
1001
+ if (!parsed || parsed.r !== resource) {
1002
+ reset = "stale-cursor";
1003
+ }
1004
+ else {
1005
+ const anchor = { time: parsed.t, id: parsed.i };
1006
+ start = keyed.findIndex((row) => rowOrder(row.key, anchor) > 0);
1007
+ if (start < 0)
1008
+ start = keyed.length;
1009
+ }
1010
+ }
1011
+ const lines = [];
1012
+ let used = 0;
1013
+ let clippedRows = 0;
1014
+ let index = start;
1015
+ for (; index < keyed.length && lines.length < limit; index += 1) {
1016
+ const row = request.render(keyed[index].item);
1017
+ const sep = lines.length ? 1 : 0;
1018
+ const size = utf8ByteLength(row);
1019
+ if (used + sep + size <= maxBytes) {
1020
+ lines.push(row);
1021
+ used += sep + size;
1022
+ continue;
1023
+ }
1024
+ if (lines.length === 0) {
1025
+ const clipped = clipRow(row, maxBytes);
1026
+ if (clipped) {
1027
+ lines.push(clipped);
1028
+ used += utf8ByteLength(clipped);
1029
+ clippedRows += 1;
1030
+ index += 1;
1031
+ }
1032
+ }
1033
+ break;
1034
+ }
1035
+ const shown = lines.length;
1036
+ const before = request.indexed?.before ?? start;
1037
+ const remaining = Math.max(0, total - before - lines.length);
1038
+ const current = request.cursor && !reset ? request.cursor : undefined;
1039
+ // The next page starts after the last row shown, or — when no row fit —
1040
+ // at this page's own start, so a caller can always retry with a larger page.
1041
+ const anchor = shown > 0 ? keyed[index - 1].key : rowCursorKey(current, request.resource) ?? (start > 0 ? keyed[start - 1].key : HEAD_ROW_KEY);
1042
+ const nextCursor = remaining > 0
1043
+ ? encodeRowCursor({ k: "l", r: resource, t: anchor.time, i: anchor.id })
1044
+ : undefined;
1045
+ return {
1046
+ text: lines.join("\n"),
1047
+ hasMore: remaining > 0,
1048
+ ...(current ? { cursor: current } : {}),
1049
+ ...(nextCursor ? { nextCursor } : {}),
1050
+ omittedBytes: 0,
1051
+ omittedRows: remaining,
1052
+ ...(reset ? { reset } : {}),
1053
+ gaps: [],
1054
+ shown,
1055
+ total,
1056
+ before,
1057
+ remaining,
1058
+ clippedRows,
1059
+ };
1060
+ }
1061
+ // ---------------------------------------------------------------------------
1062
+ // Priority envelope
1063
+ // ---------------------------------------------------------------------------
1064
+ function joinParts(parts) {
1065
+ return parts.filter((part) => Boolean(part && part.length > 0)).join("\n");
1066
+ }
1067
+ function clipPrefix(text, maxBytes) {
1068
+ const total = utf8ByteLength(text);
1069
+ if (total <= maxBytes)
1070
+ return { text, omittedBytes: 0 };
1071
+ if (maxBytes <= 0)
1072
+ return { text: "", omittedBytes: total };
1073
+ const encoded = encoder.encode(text);
1074
+ const range = sliceUtf8Range(encoded, 0, maxBytes, true, false);
1075
+ return { text: decoder.decode(encoded.subarray(0, range.end)), omittedBytes: total - range.end };
1076
+ }
1077
+ function formatContinuation(info) {
1078
+ const lines = [];
1079
+ const page = info.page;
1080
+ if (page?.reset)
1081
+ lines.push(`reset=${page.reset}`);
1082
+ if (page && (page.hasMore || page.omittedBytes > 0 || (page.omittedRows ?? 0) > 0)) {
1083
+ const amount = page.omittedRows !== undefined
1084
+ ? `omittedRows=${page.omittedRows}`
1085
+ : `omittedBytes=${page.omittedBytes}`;
1086
+ const cursor = page.nextCursor ? ` nextCursor=${page.nextCursor}${page.via ? ` (${page.via})` : ""}` : "";
1087
+ // End-anchored pages count earlier bytes and continue toward the start.
1088
+ const direction = page.direction === "backward" ? " (newest-first page; nextCursor reads earlier bytes)" : "";
1089
+ lines.push(`hasMore=${page.hasMore} ${amount}${cursor}${direction}`);
1090
+ }
1091
+ else if (page?.appendReady && page.nextCursor) {
1092
+ lines.push(`end nextCursor=${page.nextCursor} (reuse to read only bytes appended later)`);
1093
+ }
1094
+ if (page?.pendingBytes) {
1095
+ lines.push(`pendingBytes=${page.pendingBytes} (incomplete UTF-8 sequence withheld until the writer completes it)`);
1096
+ }
1097
+ for (const gap of info.gaps) {
1098
+ const bytes = gap.bytes !== undefined ? ` bytes=${gap.bytes}` : "";
1099
+ const detail = gap.detail ? ` detail=${singleLine(gap.detail)}` : "";
1100
+ lines.push(`gap ${gap.kind}${bytes}${detail}`);
1101
+ }
1102
+ for (const item of info.omitted) {
1103
+ lines.push(`omitted ${item.section} bytes=${item.omittedBytes}`);
1104
+ }
1105
+ if (info.statusCursor)
1106
+ lines.push(`statusCursor=${info.statusCursor}`);
1107
+ if (lines.length === 0)
1108
+ return undefined;
1109
+ return ["---", ...lines].join("\n");
1110
+ }
1111
+ /** Bytes always left for a function-valued failure section so its counts survive. */
1112
+ const FAILURE_SECTION_FLOOR = 256;
1113
+ /**
1114
+ * Assemble one model-facing payload under a total UTF-8 byte cap.
1115
+ *
1116
+ * Budget priority: identity, decision facts (matched condition, stop error,
1117
+ * exit), continuation/gap metadata, then failures, diagnostics, the verbatim
1118
+ * page, and finally routine progress. `verbatimReserve` holds bytes back from
1119
+ * failures/diagnostics so an answer page always advances. The verbatim pager
1120
+ * receives the exact remaining budget and is never clipped afterwards, so
1121
+ * `nextCursor` always points at the first byte not shown (a zero budget yields
1122
+ * an empty page positioned at its start). Text order: identity (or failure
1123
+ * first with `failureFirst`), failure, decision, diagnostics, verbatim,
1124
+ * progress, continuation.
1125
+ */
1126
+ export function assemblePriorityEnvelope(input) {
1127
+ const maxBytes = clampBudgetBytes(input.maxBytes, OUTPUT_BUDGET_BYTES.status);
1128
+ const sections = input.sections ?? {};
1129
+ const extraGaps = input.gaps ?? [];
1130
+ let continuationReserve = 0;
1131
+ let last;
1132
+ for (let attempt = 0; attempt < 10; attempt += 1) {
1133
+ const omitted = [];
1134
+ const avail = Math.max(0, maxBytes - continuationReserve);
1135
+ let used = 0;
1136
+ let count = 0;
1137
+ const place = (name, text, room) => {
1138
+ if (!text)
1139
+ return undefined;
1140
+ const sep = count > 0 ? 1 : 0;
1141
+ const clipped = clipPrefix(text, room - sep);
1142
+ if (clipped.omittedBytes > 0)
1143
+ omitted.push({ section: name, omittedBytes: clipped.omittedBytes });
1144
+ if (!clipped.text)
1145
+ return undefined;
1146
+ used += sep + utf8ByteLength(clipped.text);
1147
+ count += 1;
1148
+ return clipped.text;
1149
+ };
1150
+ const identity = place("identity", sections.identity, avail - used);
1151
+ const decision = place("decision", sections.decision, avail - used);
1152
+ const failureInput = sections.failure;
1153
+ const failureFloor = failureInput ? Math.min(FAILURE_SECTION_FLOOR, Math.max(0, avail - used)) : 0;
1154
+ const reserve = input.verbatim
1155
+ ? Math.max(0, Math.min(Math.floor(input.verbatimReserve ?? 0), avail - used - failureFloor - 1))
1156
+ : 0;
1157
+ const failureRoom = avail - used - reserve;
1158
+ const failureText = typeof failureInput === "function"
1159
+ ? failureInput(Math.max(0, failureRoom - (count > 0 ? 1 : 0)))
1160
+ : failureInput;
1161
+ const failure = place("failure", failureText, failureRoom);
1162
+ const diagnostics = place("diagnostics", sections.diagnostics, avail - used - reserve);
1163
+ const verbatimBudget = Math.max(0, avail - used - (count > 0 ? 1 : 0));
1164
+ let page = input.verbatim?.(verbatimBudget);
1165
+ if (page && utf8ByteLength(page.text) > verbatimBudget)
1166
+ page = input.verbatim?.(0);
1167
+ const pageText = page?.text ? page.text : undefined;
1168
+ const gaps = [...extraGaps, ...(page?.gaps ?? [])];
1169
+ const body = input.failureFirst
1170
+ ? joinParts([failure, identity, decision, diagnostics, pageText])
1171
+ : joinParts([identity, failure, decision, diagnostics, pageText]);
1172
+ const bodyBytes = utf8ByteLength(body);
1173
+ let progress;
1174
+ if (sections.progress) {
1175
+ // Size the continuation as if progress were clipped, so the omission
1176
+ // line it may add is already paid for.
1177
+ const worst = formatContinuation({
1178
+ page,
1179
+ gaps,
1180
+ omitted: [...omitted, { section: "progress", omittedBytes: utf8ByteLength(sections.progress) }],
1181
+ statusCursor: input.statusCursor,
1182
+ });
1183
+ const leftover = maxBytes - bodyBytes - (body ? 1 : 0) - (worst ? utf8ByteLength(worst) + 1 : 0);
1184
+ const clipped = clipPrefix(sections.progress, leftover);
1185
+ if (clipped.omittedBytes > 0)
1186
+ omitted.push({ section: "progress", omittedBytes: clipped.omittedBytes });
1187
+ progress = clipped.text || undefined;
1188
+ }
1189
+ const continuation = formatContinuation({ page, gaps, omitted, statusCursor: input.statusCursor });
1190
+ const text = joinParts([body, progress, continuation]);
1191
+ const size = utf8ByteLength(text);
1192
+ last = { text, omitted, page, continuation, gaps };
1193
+ if (size <= maxBytes) {
1194
+ return {
1195
+ text,
1196
+ byteLength: size,
1197
+ truncated: Boolean(page?.hasMore) || omitted.length > 0,
1198
+ omitted,
1199
+ verbatim: page,
1200
+ continuation,
1201
+ gaps,
1202
+ };
1203
+ }
1204
+ // Reserve at least the whole continuation block; grow further if the body
1205
+ // still overflows (for example when a smaller page changes the cursor).
1206
+ continuationReserve = Math.max(continuationReserve + (size - maxBytes), (continuation ? utf8ByteLength(continuation) + 1 : 0) + (progress ? utf8ByteLength(progress) + 1 : 0));
1207
+ }
1208
+ // Budgets smaller than the metadata itself: keep the continuation (the way
1209
+ // back to the evidence) ahead of any body text.
1210
+ const fallback = last ?? { text: "", omitted: [], gaps: extraGaps };
1211
+ const tail = fallback.continuation ?? "";
1212
+ const head = clipPrefix(sections.identity ?? "", Math.max(0, maxBytes - utf8ByteLength(tail) - 1)).text;
1213
+ const combined = clipPrefix(joinParts([head, tail]), maxBytes);
1214
+ return {
1215
+ text: combined.text,
1216
+ byteLength: utf8ByteLength(combined.text),
1217
+ truncated: true,
1218
+ omitted: [...fallback.omitted, ...(combined.omittedBytes > 0 ? [{ section: "continuation", omittedBytes: combined.omittedBytes }] : [])],
1219
+ verbatim: fallback.page,
1220
+ continuation: fallback.continuation,
1221
+ gaps: fallback.gaps,
1222
+ };
1223
+ }