@qlairoslabs/acp-client 0.6.0 → 0.7.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 (40) hide show
  1. package/CONSUMER_GUIDE.md +579 -292
  2. package/README.md +25 -0
  3. package/package.json +1 -1
  4. package/src/agent-session.ts +2188 -96
  5. package/src/cli/index.ts +33 -5
  6. package/src/cli/managed.ts +220 -0
  7. package/src/controller.ts +13 -0
  8. package/src/index.ts +228 -3
  9. package/src/metering/engine.ts +9 -1
  10. package/src/metering/record.ts +2 -1
  11. package/src/persistence/activity-projection.ts +71 -0
  12. package/src/persistence/audit-log-reader.ts +506 -0
  13. package/src/persistence/audit-runtime.ts +162 -0
  14. package/src/persistence/checkpoint.ts +304 -0
  15. package/src/persistence/config.ts +538 -0
  16. package/src/persistence/configuration-state.ts +191 -0
  17. package/src/persistence/deletion.ts +227 -0
  18. package/src/persistence/file-registry-store.ts +740 -0
  19. package/src/persistence/integrity.ts +147 -0
  20. package/src/persistence/legacy-registry-import.ts +240 -0
  21. package/src/persistence/managed-checkpoint.ts +81 -0
  22. package/src/persistence/managed-creation.ts +456 -0
  23. package/src/persistence/managed-load.ts +172 -0
  24. package/src/persistence/managed-registry.ts +57 -0
  25. package/src/persistence/migration.ts +298 -0
  26. package/src/persistence/paths.ts +172 -0
  27. package/src/persistence/projection.ts +373 -0
  28. package/src/persistence/reconfiguration.ts +453 -0
  29. package/src/persistence/records.ts +873 -0
  30. package/src/persistence/reducer.ts +498 -0
  31. package/src/persistence/registry.ts +446 -0
  32. package/src/persistence/restoration.ts +689 -0
  33. package/src/persistence/session-log-writer.ts +480 -0
  34. package/src/persistence/state-runtime.ts +176 -0
  35. package/src/persistence/transcript-reader.ts +980 -0
  36. package/src/persistence/transcript-runtime.ts +667 -0
  37. package/src/persistence/transcript-scanner.ts +385 -0
  38. package/src/persistence/truncation.ts +276 -0
  39. package/src/session-manager.ts +257 -7
  40. package/src/transcript.ts +3 -3
@@ -0,0 +1,980 @@
1
+ import { createHash } from "node:crypto";
2
+ import { open, type FileHandle } from "node:fs/promises";
3
+ import { isAbsolute } from "node:path";
4
+ import {
5
+ parseLegacyTranscriptLine,
6
+ type TranscriptLine as LegacyTranscriptLine,
7
+ type TranscriptMessageLine as LegacyTranscriptMessageLine,
8
+ } from "../transcript.ts";
9
+ import { canonicalizeJson } from "./integrity.ts";
10
+ import type { JsonObject } from "./checkpoint.ts";
11
+ import {
12
+ validateTranscriptRecord,
13
+ type KnownTranscriptRecord,
14
+ type TranscriptActivityRecord,
15
+ type TranscriptConfigurationRecord,
16
+ type TranscriptHeaderRecord,
17
+ type TranscriptLifecycleRecord,
18
+ type TranscriptMessageRecord,
19
+ type TranscriptMeteringReferenceRecord,
20
+ type TranscriptPermissionRecord,
21
+ type TranscriptProtocolMetadataRecord,
22
+ type TranscriptReasoningRecord,
23
+ type TranscriptRecordType,
24
+ type TranscriptTransitionRecord,
25
+ type UnknownTranscriptRecord,
26
+ } from "./records.ts";
27
+
28
+ const DEFAULT_LIMIT = 50;
29
+ const MAX_LIMIT = 500;
30
+ const READ_CHUNK_BYTES = 64 * 1024;
31
+ const HARD_MAX_RECORD_BYTES = 16_777_216;
32
+ const CURSOR_VERSION = 1;
33
+ const UTF8 = new TextDecoder("utf-8", { fatal: true });
34
+
35
+ const RECORD_TYPE_ORDER: readonly TranscriptRecordType[] = Object.freeze([
36
+ "header", "checkpoint", "operation", "message", "reasoning", "activity",
37
+ "configuration", "permission", "transition", "metering_reference", "lifecycle",
38
+ "protocol", "raw",
39
+ ]);
40
+ const RECORD_TYPES = new Set(RECORD_TYPE_ORDER);
41
+ const TIMELINE_TYPES = new Set<TranscriptRecordType>([
42
+ "message", "reasoning", "activity", "configuration", "permission", "transition",
43
+ "metering_reference", "lifecycle", "protocol",
44
+ ]);
45
+
46
+ export type TranscriptView = "conversation" | "timeline" | "records";
47
+ export type TranscriptCursor = string & { readonly __transcriptCursor: unique symbol };
48
+ export type TranscriptSnapshotCursor = string & { readonly __transcriptSnapshotCursor: unique symbol };
49
+
50
+ export interface ReadTranscriptPageOptions {
51
+ readonly cursor?: TranscriptCursor;
52
+ readonly limit?: number;
53
+ readonly view?: TranscriptView;
54
+ readonly types?: readonly TranscriptRecordType[];
55
+ }
56
+
57
+ export interface TranscriptPage<
58
+ T,
59
+ C = TranscriptCursor,
60
+ S = TranscriptSnapshotCursor,
61
+ > {
62
+ readonly items: readonly T[];
63
+ readonly olderCursor: C | null;
64
+ readonly newerCursor: C | null;
65
+ readonly hasOlder: boolean;
66
+ readonly hasNewer: boolean;
67
+ readonly snapshot: S;
68
+ }
69
+
70
+ export type TranscriptConversationItem = TranscriptMessageRecord | LegacyTranscriptMessageLine;
71
+ export type TranscriptTimelineItem =
72
+ | TranscriptMessageRecord
73
+ | TranscriptReasoningRecord
74
+ | TranscriptActivityRecord
75
+ | TranscriptConfigurationRecord
76
+ | TranscriptPermissionRecord
77
+ | TranscriptTransitionRecord
78
+ | TranscriptMeteringReferenceRecord
79
+ | TranscriptLifecycleRecord
80
+ | TranscriptProtocolMetadataRecord
81
+ | LegacyTranscriptLine;
82
+
83
+ export type TranscriptReadableRecord =
84
+ | KnownTranscriptRecord
85
+ | UnknownTranscriptRecord
86
+ | LegacyTranscriptLine;
87
+
88
+ export type ActivityExecutionState = "observed_live" | "historically_open" | "terminal";
89
+
90
+ export interface PersistedActivityState {
91
+ readonly activityId: string;
92
+ readonly activityRevision: number;
93
+ readonly operationId: string;
94
+ readonly reason: TranscriptActivityRecord["reason"];
95
+ readonly kind: string;
96
+ readonly status?: string;
97
+ readonly data: JsonObject;
98
+ readonly execution: ActivityExecutionState;
99
+ }
100
+
101
+ export interface ListTranscriptActivitiesOptions {
102
+ readonly at?: TranscriptSnapshotCursor;
103
+ readonly status?: "open" | "terminal" | "all";
104
+ readonly limit?: number;
105
+ readonly order?: "updated_desc" | "updated_asc";
106
+ }
107
+
108
+ export interface PersistedActivityStatePage {
109
+ readonly activities: readonly PersistedActivityState[];
110
+ readonly snapshot: TranscriptSnapshotCursor;
111
+ }
112
+
113
+ export class TranscriptCursorInvalidError extends Error {
114
+ constructor(message: string, options?: ErrorOptions) {
115
+ super(message, options);
116
+ this.name = "TranscriptCursorInvalidError";
117
+ }
118
+ }
119
+
120
+ export class TranscriptReaderError extends Error {
121
+ constructor(message: string, options?: ErrorOptions) {
122
+ super(message, options);
123
+ this.name = "TranscriptReaderError";
124
+ }
125
+ }
126
+
127
+ interface SnapshotBoundary {
128
+ readonly v: 1;
129
+ readonly id: string;
130
+ readonly generation: number;
131
+ readonly highSequence: number;
132
+ readonly highOffset: number;
133
+ readonly prefixDigest: string;
134
+ }
135
+
136
+ interface SnapshotPayload extends SnapshotBoundary {
137
+ readonly k: "transcript_snapshot";
138
+ }
139
+
140
+ interface NavigationPayload extends SnapshotBoundary {
141
+ readonly k: "transcript_navigation";
142
+ readonly direction: "older" | "newer";
143
+ readonly boundarySequence: number;
144
+ readonly boundaryStart: number;
145
+ readonly boundaryEnd: number;
146
+ readonly boundaryDigest: string;
147
+ readonly view: TranscriptView;
148
+ readonly types: readonly TranscriptRecordType[];
149
+ readonly filterProvided: boolean;
150
+ }
151
+
152
+ interface PhysicalRecord<T = TranscriptReadableRecord> {
153
+ readonly item: T;
154
+ readonly sequence: number;
155
+ readonly start: number;
156
+ readonly end: number;
157
+ readonly digest: string;
158
+ }
159
+
160
+ interface SnapshotContext {
161
+ readonly handle: FileHandle;
162
+ readonly header: TranscriptHeaderRecord;
163
+ readonly payload: SnapshotPayload;
164
+ readonly snapshotCursor: TranscriptSnapshotCursor;
165
+ readonly navigation: NavigationPayload | null;
166
+ }
167
+
168
+ /** Snapshot-bound, cursor-paginated reader for one v2 transcript generation. */
169
+ export class TranscriptReader {
170
+ constructor(readonly path: string) {
171
+ if (!isAbsolute(path)) throw new TranscriptReaderError("transcript reader path must be absolute");
172
+ }
173
+
174
+ readPage(options?: ReadTranscriptPageOptions & { readonly view?: "timeline" }): Promise<TranscriptPage<TranscriptTimelineItem>>;
175
+ readPage(options: ReadTranscriptPageOptions & { readonly view: "conversation" }): Promise<TranscriptPage<TranscriptConversationItem>>;
176
+ readPage(options: ReadTranscriptPageOptions & { readonly view: "records" }): Promise<TranscriptPage<TranscriptReadableRecord>>;
177
+ async readPage(
178
+ options: ReadTranscriptPageOptions = {},
179
+ ): Promise<TranscriptPage<TranscriptReadableRecord>> {
180
+ const limit = validatedLimit(options.limit);
181
+ const view = options.view ?? "timeline";
182
+ const filter = normalizeTypes(view, options.types);
183
+ const snapshot = await this.openSnapshot(options.cursor, "navigation");
184
+ try {
185
+ const navigation = snapshot.navigation;
186
+ if (navigation) {
187
+ if (navigation.view !== view || navigation.filterProvided !== filter.provided
188
+ || canonicalizeJson(navigation.types) !== canonicalizeJson(filter.types)) {
189
+ throw new TranscriptCursorInvalidError("transcript cursor view or type filter changed");
190
+ }
191
+ await validateBoundary(snapshot.handle, snapshot.header, navigation);
192
+ }
193
+
194
+ let selected: PhysicalRecord[];
195
+ let hasOlder: boolean;
196
+ let hasNewer: boolean;
197
+ if (!navigation || navigation.direction === "older") {
198
+ const end = navigation?.boundaryStart ?? snapshot.payload.highOffset;
199
+ const matches = await collectBackward(
200
+ snapshot.handle,
201
+ snapshot.header,
202
+ end,
203
+ limit + 1,
204
+ navigation ? navigation.boundarySequence - 1 : snapshot.payload.highSequence,
205
+ (record) => projectRecord(record.item, view, filter),
206
+ );
207
+ hasOlder = matches.length > limit;
208
+ selected = matches.slice(0, limit).reverse();
209
+ hasNewer = navigation !== null;
210
+ } else {
211
+ const matches = await collectForward(
212
+ snapshot.handle,
213
+ snapshot.header,
214
+ navigation.boundaryEnd,
215
+ snapshot.payload.highOffset,
216
+ limit + 1,
217
+ navigation.boundaryStart < legacyBoundary(snapshot.header)
218
+ ? 1
219
+ : navigation.boundarySequence + 1,
220
+ (record) => projectRecord(record.item, view, filter),
221
+ );
222
+ hasOlder = true;
223
+ hasNewer = matches.length > limit;
224
+ selected = matches.slice(0, limit);
225
+ }
226
+
227
+ const first = selected[0];
228
+ const last = selected.at(-1);
229
+ return Object.freeze({
230
+ items: Object.freeze(selected.map((record) => structuredClone(record.item))),
231
+ olderCursor: hasOlder && first
232
+ ? boundedCursor(
233
+ encodeNavigation(snapshot.payload, "older", first, view, filter),
234
+ snapshot.header.effectiveLimits.maxCursorBytes,
235
+ )
236
+ : null,
237
+ newerCursor: hasNewer && last
238
+ ? boundedCursor(
239
+ encodeNavigation(snapshot.payload, "newer", last, view, filter),
240
+ snapshot.header.effectiveLimits.maxCursorBytes,
241
+ )
242
+ : null,
243
+ hasOlder,
244
+ hasNewer,
245
+ snapshot: snapshot.snapshotCursor,
246
+ });
247
+ } finally {
248
+ await snapshot.handle.close().catch(() => undefined);
249
+ }
250
+ }
251
+
252
+ async listActivityStates(
253
+ options: ListTranscriptActivitiesOptions = {},
254
+ ): Promise<PersistedActivityStatePage> {
255
+ const limit = validatedLimit(options.limit);
256
+ const status = options.status ?? "all";
257
+ if (status !== "all" && status !== "open" && status !== "terminal") {
258
+ throw new TranscriptReaderError(`invalid activity status filter: ${String(status)}`);
259
+ }
260
+ const order = options.order ?? "updated_desc";
261
+ if (order !== "updated_desc" && order !== "updated_asc") {
262
+ throw new TranscriptReaderError(`invalid activity order: ${String(order)}`);
263
+ }
264
+ const snapshot = await this.openSnapshot(options.at, "snapshot");
265
+ try {
266
+ const latest = new Map<string, { record: TranscriptActivityRecord; sequence: number }>();
267
+ for await (const physical of forwardLines(snapshot.handle, 0, snapshot.payload.highOffset, snapshot.header.effectiveLimits.maxRecordBytes)) {
268
+ const parsed = parsePhysical(physical, snapshot.header);
269
+ if (!parsed) continue;
270
+ if (!isActivityRecord(parsed.item)) continue;
271
+ const previous = latest.get(parsed.item.activityId);
272
+ if (previous && parsed.item.activityRevision <= previous.record.activityRevision) {
273
+ throw new TranscriptReaderError(`activity revisions are not increasing for ${parsed.item.activityId}`);
274
+ }
275
+ latest.set(parsed.item.activityId, { record: parsed.item, sequence: parsed.sequence });
276
+ }
277
+ const folded = [...latest.values()].map(({ record, sequence }) => ({
278
+ state: activityState(record),
279
+ sequence,
280
+ })).filter(({ state }) => status === "all"
281
+ || (status === "terminal" ? state.execution === "terminal" : state.execution !== "terminal"));
282
+ folded.sort((left, right) => {
283
+ const bySequence = left.sequence - right.sequence;
284
+ const deterministic = bySequence || left.state.activityId.localeCompare(right.state.activityId);
285
+ return order === "updated_asc" ? deterministic : -deterministic;
286
+ });
287
+ return Object.freeze({
288
+ activities: Object.freeze(folded.slice(0, limit).map(({ state }) => Object.freeze(state))),
289
+ snapshot: snapshot.snapshotCursor,
290
+ });
291
+ } finally {
292
+ await snapshot.handle.close().catch(() => undefined);
293
+ }
294
+ }
295
+
296
+ private async openSnapshot(
297
+ cursor: TranscriptCursor | TranscriptSnapshotCursor | undefined,
298
+ expected: "navigation" | "snapshot",
299
+ ): Promise<SnapshotContext> {
300
+ let handle: FileHandle;
301
+ try {
302
+ handle = await open(this.path, "r");
303
+ } catch (error) {
304
+ throw new TranscriptReaderError(`cannot open transcript: ${this.path}`, { cause: error });
305
+ }
306
+ try {
307
+ const stat = await handle.stat();
308
+ if (!stat.isFile()) throw new TranscriptReaderError("transcript reader target is not a regular file");
309
+ const header = await readHeader(handle, stat.size);
310
+ let payload: SnapshotPayload;
311
+ let navigation: NavigationPayload | null = null;
312
+ if (cursor !== undefined) {
313
+ const decoded = decodeCursor(cursor, header.effectiveLimits.maxCursorBytes);
314
+ if (expected === "snapshot" && decoded.k !== "transcript_snapshot") {
315
+ throw new TranscriptCursorInvalidError("activity state requires a transcript snapshot cursor");
316
+ }
317
+ if (expected === "navigation" && decoded.k !== "transcript_navigation") {
318
+ throw new TranscriptCursorInvalidError("readPage requires a transcript navigation cursor");
319
+ }
320
+ payload = snapshotPayloadFrom(decoded);
321
+ navigation = decoded.k === "transcript_navigation" ? decoded : null;
322
+ validateSnapshotPayload(payload, header, stat.size);
323
+ const digest = await digestPrefix(handle, payload.highOffset);
324
+ if (digest !== payload.prefixDigest) {
325
+ throw new TranscriptCursorInvalidError("transcript content changed before the cursor snapshot boundary");
326
+ }
327
+ await validateHighBoundary(handle, header, payload);
328
+ } else {
329
+ const highOffset = await lastCompleteOffset(handle, stat.size);
330
+ if (highOffset === 0) throw new TranscriptReaderError("transcript has no complete records");
331
+ const high = await readLastPhysical(handle, highOffset, header.effectiveLimits.maxRecordBytes);
332
+ const parsedHigh = parsePhysical(high, header);
333
+ if (!parsedHigh || parsedHigh.item.v !== 2) {
334
+ throw new TranscriptReaderError("transcript snapshot has no v2 high-water record");
335
+ }
336
+ payload = {
337
+ v: CURSOR_VERSION,
338
+ k: "transcript_snapshot",
339
+ id: identityTag(header.transcriptId),
340
+ generation: header.generation,
341
+ highSequence: parsedHigh.sequence,
342
+ highOffset,
343
+ prefixDigest: await digestPrefix(handle, highOffset),
344
+ };
345
+ }
346
+ const snapshotPayload = snapshotPayloadFrom(payload);
347
+ return {
348
+ handle,
349
+ header,
350
+ payload: snapshotPayload,
351
+ snapshotCursor: boundedSnapshotCursor(
352
+ encodeCursor(snapshotPayload),
353
+ header.effectiveLimits.maxCursorBytes,
354
+ ),
355
+ navigation,
356
+ };
357
+ } catch (error) {
358
+ await handle.close().catch(() => undefined);
359
+ if (error instanceof TranscriptReaderError || error instanceof TranscriptCursorInvalidError) throw error;
360
+ throw new TranscriptReaderError("cannot read transcript snapshot", { cause: error });
361
+ }
362
+ }
363
+ }
364
+
365
+ function projectRecord(
366
+ record: TranscriptReadableRecord,
367
+ view: TranscriptView,
368
+ filter: TypeFilter,
369
+ ): boolean {
370
+ if (view === "conversation") return record.t === "message" || record.t === "msg";
371
+ const type = "transcriptId" in record
372
+ ? record.t as TranscriptRecordType
373
+ : legacyProjectionType(record);
374
+ if (view === "timeline") return type !== null && TIMELINE_TYPES.has(type)
375
+ && (!filter.provided || filter.types.includes(type));
376
+ return !filter.provided || (type !== null && filter.types.includes(type));
377
+ }
378
+
379
+ interface TypeFilter {
380
+ readonly provided: boolean;
381
+ readonly types: readonly TranscriptRecordType[];
382
+ }
383
+
384
+ function normalizeTypes(
385
+ view: TranscriptView,
386
+ input: readonly TranscriptRecordType[] | undefined,
387
+ ): TypeFilter {
388
+ if (view !== "conversation" && view !== "timeline" && view !== "records") {
389
+ throw new TranscriptReaderError(`invalid transcript view: ${String(view)}`);
390
+ }
391
+ if (view === "conversation") {
392
+ if (input !== undefined) throw new TranscriptReaderError("conversation view does not accept a type filter");
393
+ return Object.freeze({ provided: false, types: Object.freeze([]) });
394
+ }
395
+ if (input === undefined) return Object.freeze({ provided: false, types: Object.freeze([]) });
396
+ const unique = [...new Set(input)].sort();
397
+ for (const type of unique) {
398
+ if (!RECORD_TYPES.has(type)) throw new TranscriptReaderError(`unknown transcript record type: ${String(type)}`);
399
+ if (view === "timeline" && !TIMELINE_TYPES.has(type)) {
400
+ throw new TranscriptReaderError(`record type ${type} is not part of the timeline view`);
401
+ }
402
+ }
403
+ return Object.freeze({ provided: true, types: Object.freeze(unique) });
404
+ }
405
+
406
+ function validatedLimit(value: number | undefined): number {
407
+ const limit = value ?? DEFAULT_LIMIT;
408
+ if (!Number.isInteger(limit) || limit < 1 || limit > MAX_LIMIT) {
409
+ throw new TranscriptReaderError(`limit must be an integer from 1 through ${MAX_LIMIT}`);
410
+ }
411
+ return limit;
412
+ }
413
+
414
+ function activityState(record: TranscriptActivityRecord): PersistedActivityState {
415
+ return {
416
+ activityId: record.activityId,
417
+ activityRevision: record.activityRevision,
418
+ operationId: record.operationId,
419
+ reason: record.reason,
420
+ kind: record.kind,
421
+ ...(record.status === undefined ? {} : { status: record.status }),
422
+ data: structuredClone(record.data) as JsonObject,
423
+ execution: record.reason === "settled" ? "terminal" : "historically_open",
424
+ };
425
+ }
426
+
427
+ async function collectBackward(
428
+ handle: FileHandle,
429
+ header: TranscriptHeaderRecord,
430
+ end: number,
431
+ count: number,
432
+ expectedFirstSequence: number,
433
+ match: (record: PhysicalRecord) => boolean,
434
+ ): Promise<PhysicalRecord[]> {
435
+ const output: PhysicalRecord[] = [];
436
+ let expectedSequence = expectedFirstSequence;
437
+ for await (const physical of backwardLines(handle, end, header.effectiveLimits.maxRecordBytes)) {
438
+ const parsed = parsePhysical(physical, header);
439
+ if (!parsed) continue;
440
+ if (parsed.item.v === 2) {
441
+ if (parsed.sequence !== expectedSequence) throw new TranscriptReaderError("transcript sequence is not physically contiguous");
442
+ expectedSequence--;
443
+ }
444
+ if (match(parsed)) output.push(parsed);
445
+ if (output.length >= count) break;
446
+ }
447
+ return output;
448
+ }
449
+
450
+ async function collectForward(
451
+ handle: FileHandle,
452
+ header: TranscriptHeaderRecord,
453
+ start: number,
454
+ end: number,
455
+ count: number,
456
+ expectedFirstSequence: number,
457
+ match: (record: PhysicalRecord) => boolean,
458
+ ): Promise<PhysicalRecord[]> {
459
+ const output: PhysicalRecord[] = [];
460
+ let expectedSequence = expectedFirstSequence;
461
+ for await (const physical of forwardLines(handle, start, end, header.effectiveLimits.maxRecordBytes)) {
462
+ const parsed = parsePhysical(physical, header);
463
+ if (!parsed) continue;
464
+ if (parsed.item.v === 2) {
465
+ if (parsed.sequence !== expectedSequence) throw new TranscriptReaderError("transcript sequence is not physically contiguous");
466
+ expectedSequence++;
467
+ }
468
+ if (match(parsed)) output.push(parsed);
469
+ if (output.length >= count) break;
470
+ }
471
+ return output;
472
+ }
473
+
474
+ export interface SessionLogPhysicalLine {
475
+ readonly bytes: Uint8Array;
476
+ readonly start: number;
477
+ readonly end: number;
478
+ }
479
+
480
+ type PhysicalLine = SessionLogPhysicalLine;
481
+
482
+ async function* forwardLines(
483
+ handle: FileHandle,
484
+ startOffset: number,
485
+ endOffset: number,
486
+ maxRecordBytes: number,
487
+ ): AsyncGenerator<PhysicalLine> {
488
+ let position = startOffset;
489
+ let pending = Buffer.alloc(0);
490
+ let pendingStart = startOffset;
491
+ while (position < endOffset) {
492
+ const size = Math.min(READ_CHUNK_BYTES, endOffset - position);
493
+ const block = await readBytes(handle, position, size);
494
+ if (block.byteLength !== size) throw new TranscriptReaderError("transcript changed while reading snapshot");
495
+ position += size;
496
+ const combined = pending.byteLength === 0 ? Buffer.from(block) : Buffer.concat([pending, block]);
497
+ let cursor = 0;
498
+ for (;;) {
499
+ const lf = combined.indexOf(0x0a, cursor);
500
+ if (lf < 0) break;
501
+ const bytes = combined.subarray(cursor, lf);
502
+ if (bytes.byteLength > maxRecordBytes) throw new TranscriptReaderError("transcript record exceeds engraved limit");
503
+ const start = pendingStart + cursor;
504
+ yield { bytes, start, end: pendingStart + lf + 1 };
505
+ cursor = lf + 1;
506
+ }
507
+ pending = Buffer.from(combined.subarray(cursor));
508
+ pendingStart += cursor;
509
+ if (pending.byteLength > Math.min(maxRecordBytes, HARD_MAX_RECORD_BYTES)) {
510
+ throw new TranscriptReaderError("transcript record exceeds reader safety ceiling");
511
+ }
512
+ }
513
+ if (pending.byteLength !== 0) throw new TranscriptReaderError("snapshot boundary does not end at a complete record");
514
+ }
515
+
516
+ async function* backwardLines(
517
+ handle: FileHandle,
518
+ endOffset: number,
519
+ maxRecordBytes: number,
520
+ ): AsyncGenerator<PhysicalLine> {
521
+ let position = endOffset;
522
+ let carry = Buffer.alloc(0);
523
+ while (position > 0) {
524
+ const start = Math.max(0, position - READ_CHUNK_BYTES);
525
+ const block = await readBytes(handle, start, position - start);
526
+ if (block.byteLength !== position - start) throw new TranscriptReaderError("transcript changed while reading snapshot");
527
+ const combined = carry.byteLength === 0 ? Buffer.from(block) : Buffer.concat([block, carry]);
528
+ const lineFeeds: number[] = [];
529
+ for (let at = combined.indexOf(0x0a); at >= 0; at = combined.indexOf(0x0a, at + 1)) lineFeeds.push(at);
530
+ for (let index = lineFeeds.length - 1; index >= 1; index--) {
531
+ const lineStart = lineFeeds[index - 1]! + 1;
532
+ const lineEnd = lineFeeds[index]!;
533
+ const bytes = combined.subarray(lineStart, lineEnd);
534
+ if (bytes.byteLength > maxRecordBytes) throw new TranscriptReaderError("transcript record exceeds engraved limit");
535
+ yield { bytes, start: start + lineStart, end: start + lineEnd + 1 };
536
+ }
537
+ if (start === 0 && lineFeeds.length > 0) {
538
+ const lineEnd = lineFeeds[0]!;
539
+ const bytes = combined.subarray(0, lineEnd);
540
+ if (bytes.byteLength > maxRecordBytes) throw new TranscriptReaderError("transcript record exceeds engraved limit");
541
+ yield { bytes, start: 0, end: lineEnd + 1 };
542
+ return;
543
+ }
544
+ carry = lineFeeds.length > 0
545
+ ? Buffer.from(combined.subarray(0, lineFeeds[0]! + 1))
546
+ : combined;
547
+ if (carry.byteLength > Math.min(maxRecordBytes, HARD_MAX_RECORD_BYTES) + 1) {
548
+ throw new TranscriptReaderError("transcript record exceeds reader safety ceiling");
549
+ }
550
+ position = start;
551
+ }
552
+ }
553
+
554
+ function parsePhysical(
555
+ physical: PhysicalLine,
556
+ header: TranscriptHeaderRecord,
557
+ ): PhysicalRecord | null {
558
+ if (physical.bytes.byteLength === 0) throw new TranscriptReaderError("transcript contains an empty record");
559
+ if (physical.start < legacyBoundary(header)) {
560
+ let raw: string;
561
+ try {
562
+ raw = UTF8.decode(physical.bytes);
563
+ } catch {
564
+ return null;
565
+ }
566
+ const item = parseLegacyTranscriptLine(raw);
567
+ return item ? {
568
+ item,
569
+ sequence: physical.start + 1,
570
+ start: physical.start,
571
+ end: physical.end,
572
+ digest: sha256Bytes(physical.bytes),
573
+ } : null;
574
+ }
575
+ let value: unknown;
576
+ try {
577
+ value = JSON.parse(UTF8.decode(physical.bytes));
578
+ } catch (error) {
579
+ throw new TranscriptReaderError("transcript contains malformed UTF-8 or JSON", { cause: error });
580
+ }
581
+ if (!isRecord(value)) throw new TranscriptReaderError("transcript record must be an object");
582
+ const commonValid = value.v === 2
583
+ && typeof value.t === "string" && value.t.length > 0
584
+ && value.transcriptId === header.transcriptId
585
+ && value.generation === header.generation
586
+ && value.agentSessionId === header.agentSessionId
587
+ && Number.isSafeInteger(value.seq) && (value.seq as number) > 0
588
+ && Number.isSafeInteger(value.ts);
589
+ if (!commonValid) throw new TranscriptReaderError("transcript record envelope is invalid or changes identity");
590
+ let item: KnownTranscriptRecord | UnknownTranscriptRecord;
591
+ if (RECORD_TYPES.has(value.t as TranscriptRecordType)) {
592
+ try {
593
+ validateTranscriptRecord(value, {
594
+ agentSessionId: header.agentSessionId,
595
+ logId: header.transcriptId,
596
+ generation: header.generation,
597
+ });
598
+ } catch (error) {
599
+ throw new TranscriptReaderError(`invalid transcript record at sequence ${String(value.seq)}`, { cause: error });
600
+ }
601
+ item = value;
602
+ } else {
603
+ try {
604
+ canonicalizeJson(value);
605
+ } catch (error) {
606
+ throw new TranscriptReaderError("unknown transcript record is not canonical JSON", { cause: error });
607
+ }
608
+ item = {
609
+ v: value.v as number,
610
+ t: value.t as string,
611
+ transcriptId: value.transcriptId as string,
612
+ generation: value.generation as number,
613
+ agentSessionId: value.agentSessionId as string,
614
+ seq: value.seq as number,
615
+ ts: value.ts as number,
616
+ value: structuredClone(value) as JsonObject,
617
+ };
618
+ }
619
+ return {
620
+ item,
621
+ sequence: value.seq as number,
622
+ start: physical.start,
623
+ end: physical.end,
624
+ digest: sha256Bytes(physical.bytes),
625
+ };
626
+ }
627
+
628
+ async function readHeader(handle: FileHandle, fileSize: number): Promise<TranscriptHeaderRecord> {
629
+ if (fileSize === 0) throw new TranscriptReaderError("transcript is empty");
630
+ const completeOffset = await lastCompleteOffset(handle, fileSize);
631
+ for await (const physical of forwardLines(handle, 0, completeOffset, HARD_MAX_RECORD_BYTES)) {
632
+ let value: unknown;
633
+ try {
634
+ value = JSON.parse(UTF8.decode(physical.bytes));
635
+ } catch {
636
+ continue;
637
+ }
638
+ if (!isRecord(value) || value.v !== 2) continue;
639
+ try {
640
+ validateTranscriptRecord(value);
641
+ } catch (error) {
642
+ throw new TranscriptReaderError("transcript v2 header is invalid", { cause: error });
643
+ }
644
+ if (value.t !== "header" || value.seq !== 1) {
645
+ throw new TranscriptReaderError("first v2 transcript record is not its header");
646
+ }
647
+ if (physical.start > 0 && (value.event !== "upgraded"
648
+ || value.upgradedFrom?.boundaryOffset !== physical.start)) {
649
+ throw new TranscriptReaderError("mixed transcript legacy boundary is invalid");
650
+ }
651
+ return value;
652
+ }
653
+ throw new TranscriptReaderError("transcript has no complete v2 header");
654
+ }
655
+
656
+ async function firstPhysical(handle: FileHandle, fileSize: number): Promise<PhysicalLine> {
657
+ let position = 0;
658
+ let bytes = Buffer.alloc(0);
659
+ while (position < fileSize && bytes.byteLength <= HARD_MAX_RECORD_BYTES) {
660
+ const size = Math.min(READ_CHUNK_BYTES, fileSize - position);
661
+ const block = await readBytes(handle, position, size);
662
+ if (block.byteLength === 0) throw new TranscriptReaderError("transcript changed while reading its header");
663
+ const combined = bytes.byteLength === 0 ? Buffer.from(block) : Buffer.concat([bytes, block]);
664
+ const lf = combined.indexOf(0x0a);
665
+ if (lf >= 0) return { bytes: combined.subarray(0, lf), start: 0, end: lf + 1 };
666
+ bytes = combined;
667
+ position += block.byteLength;
668
+ }
669
+ throw new TranscriptReaderError("transcript has no bounded complete header");
670
+ }
671
+
672
+ async function readLastPhysical(handle: FileHandle, highOffset: number, maxRecordBytes: number): Promise<PhysicalLine> {
673
+ for await (const physical of backwardLines(handle, highOffset, maxRecordBytes)) return physical;
674
+ throw new TranscriptReaderError("transcript has no complete record at its snapshot boundary");
675
+ }
676
+
677
+ async function lastCompleteOffset(handle: FileHandle, fileSize: number): Promise<number> {
678
+ let position = fileSize;
679
+ let suffixBytes = 0;
680
+ while (position > 0) {
681
+ const start = Math.max(0, position - READ_CHUNK_BYTES);
682
+ const block = await readBytes(handle, start, position - start);
683
+ for (let index = block.byteLength - 1; index >= 0; index--) {
684
+ if (block[index] === 0x0a) return start + index + 1;
685
+ }
686
+ suffixBytes += block.byteLength;
687
+ if (suffixBytes > HARD_MAX_RECORD_BYTES) {
688
+ throw new TranscriptReaderError("incomplete transcript suffix exceeds reader safety ceiling");
689
+ }
690
+ position = start;
691
+ }
692
+ return 0;
693
+ }
694
+
695
+ async function validateBoundary(
696
+ handle: FileHandle,
697
+ header: TranscriptHeaderRecord,
698
+ cursor: NavigationPayload,
699
+ ): Promise<void> {
700
+ if (cursor.boundaryStart < 0 || cursor.boundaryEnd <= cursor.boundaryStart
701
+ || cursor.boundaryEnd > cursor.highOffset) {
702
+ throw new TranscriptCursorInvalidError("transcript cursor boundary offsets are invalid");
703
+ }
704
+ const bytes = await readBytes(handle, cursor.boundaryStart, cursor.boundaryEnd - cursor.boundaryStart);
705
+ if (bytes.byteLength === 0 || bytes.at(-1) !== 0x0a) {
706
+ throw new TranscriptCursorInvalidError("transcript cursor boundary is no longer a complete record");
707
+ }
708
+ const physical = { bytes: bytes.subarray(0, bytes.byteLength - 1), start: cursor.boundaryStart, end: cursor.boundaryEnd };
709
+ let parsed: PhysicalRecord;
710
+ try {
711
+ const candidate = parsePhysical(physical, header);
712
+ if (!candidate) throw new Error("unreadable boundary");
713
+ parsed = candidate;
714
+ } catch (error) {
715
+ throw new TranscriptCursorInvalidError("transcript cursor boundary is invalid", { cause: error });
716
+ }
717
+ if (parsed.sequence !== cursor.boundarySequence || parsed.digest !== cursor.boundaryDigest) {
718
+ throw new TranscriptCursorInvalidError("transcript cursor boundary changed");
719
+ }
720
+ }
721
+
722
+ async function validateHighBoundary(
723
+ handle: FileHandle,
724
+ header: TranscriptHeaderRecord,
725
+ cursor: SnapshotPayload,
726
+ ): Promise<void> {
727
+ let physical: PhysicalLine;
728
+ let parsed: PhysicalRecord;
729
+ try {
730
+ physical = await readLastPhysical(handle, cursor.highOffset, header.effectiveLimits.maxRecordBytes);
731
+ const candidate = parsePhysical(physical, header);
732
+ if (!candidate) throw new Error("unreadable high-water boundary");
733
+ parsed = candidate;
734
+ } catch (error) {
735
+ throw new TranscriptCursorInvalidError("transcript cursor high-water boundary is invalid", { cause: error });
736
+ }
737
+ if (parsed.sequence !== cursor.highSequence || physical.end !== cursor.highOffset) {
738
+ throw new TranscriptCursorInvalidError("transcript cursor high-water boundary changed");
739
+ }
740
+ }
741
+
742
+ function encodeNavigation(
743
+ snapshot: SnapshotPayload,
744
+ direction: "older" | "newer",
745
+ boundary: PhysicalRecord,
746
+ view: TranscriptView,
747
+ filter: TypeFilter,
748
+ ): TranscriptCursor {
749
+ return encodeCursor({
750
+ ...snapshot,
751
+ k: "transcript_navigation",
752
+ direction,
753
+ boundarySequence: boundary.sequence,
754
+ boundaryStart: boundary.start,
755
+ boundaryEnd: boundary.end,
756
+ boundaryDigest: boundary.digest,
757
+ view,
758
+ types: filter.types,
759
+ filterProvided: filter.provided,
760
+ }) as TranscriptCursor;
761
+ }
762
+
763
+ function snapshotPayloadFrom(payload: SnapshotBoundary): SnapshotPayload {
764
+ return {
765
+ v: CURSOR_VERSION,
766
+ k: "transcript_snapshot",
767
+ id: payload.id,
768
+ generation: payload.generation,
769
+ highSequence: payload.highSequence,
770
+ highOffset: payload.highOffset,
771
+ prefixDigest: payload.prefixDigest,
772
+ };
773
+ }
774
+
775
+ function encodeCursor(payload: SnapshotPayload | NavigationPayload): string {
776
+ const wire = payload.k === "transcript_snapshot"
777
+ ? [1, "s", payload.id, payload.generation, payload.highSequence, payload.highOffset, payload.prefixDigest]
778
+ : [
779
+ 1, "n", payload.id, payload.generation, payload.highSequence, payload.highOffset,
780
+ payload.prefixDigest, payload.direction === "older" ? "o" : "n",
781
+ payload.boundarySequence, payload.boundaryStart, payload.boundaryEnd,
782
+ payload.boundaryDigest, viewCode(payload.view), payload.filterProvided ? typesMask(payload.types) : null,
783
+ ];
784
+ return Buffer.from(JSON.stringify(wire), "utf8").toString("base64url");
785
+ }
786
+
787
+ function decodeCursor(cursor: string, maxBytes: number): SnapshotPayload | NavigationPayload {
788
+ if (typeof cursor !== "string" || cursor.length === 0 || Buffer.byteLength(cursor, "utf8") > maxBytes) {
789
+ throw new TranscriptCursorInvalidError("transcript cursor is blank or exceeds its engraved limit");
790
+ }
791
+ if (!/^[A-Za-z0-9_-]+$/.test(cursor)) {
792
+ throw new TranscriptCursorInvalidError("transcript cursor is not canonical base64url");
793
+ }
794
+ let value: unknown;
795
+ try {
796
+ const decoded = Buffer.from(cursor, "base64url");
797
+ if (decoded.toString("base64url") !== cursor) throw new Error("non-canonical base64url");
798
+ value = JSON.parse(decoded.toString("utf8"));
799
+ } catch (error) {
800
+ throw new TranscriptCursorInvalidError("transcript cursor is malformed", { cause: error });
801
+ }
802
+ if (!Array.isArray(value) || (value.length !== 7 && value.length !== 14)
803
+ || value[0] !== CURSOR_VERSION || (value[1] !== "s" && value[1] !== "n")
804
+ || !integrityTag(value[2])
805
+ || !positiveInteger(value[3]) || !positiveInteger(value[4])
806
+ || !positiveInteger(value[5]) || !integrityTag(value[6])) {
807
+ throw new TranscriptCursorInvalidError("transcript cursor payload is invalid");
808
+ }
809
+ if (value[1] === "s") {
810
+ return {
811
+ v: 1,
812
+ k: "transcript_snapshot",
813
+ id: value[2],
814
+ generation: value[3] as number,
815
+ highSequence: value[4] as number,
816
+ highOffset: value[5] as number,
817
+ prefixDigest: value[6],
818
+ };
819
+ }
820
+ const types = value[13] === null ? [] : typesFromMask(value[13]);
821
+ const view = decodeView(value[12]);
822
+ if ((value[7] !== "o" && value[7] !== "n")
823
+ || !positiveInteger(value[8])
824
+ || !nonnegativeInteger(value[9])
825
+ || !positiveInteger(value[10])
826
+ || !integrityTag(value[11])
827
+ || view === null
828
+ || types === null) {
829
+ throw new TranscriptCursorInvalidError("transcript navigation cursor payload is invalid");
830
+ }
831
+ {
832
+ if ((view === "timeline" && types.some((type) => !TIMELINE_TYPES.has(type)))
833
+ || (view === "conversation" && value[13] !== null)) {
834
+ throw new TranscriptCursorInvalidError("transcript navigation cursor filter is invalid");
835
+ }
836
+ }
837
+ return {
838
+ v: 1,
839
+ k: "transcript_navigation",
840
+ id: value[2],
841
+ generation: value[3] as number,
842
+ highSequence: value[4] as number,
843
+ highOffset: value[5] as number,
844
+ prefixDigest: value[6],
845
+ direction: value[7] === "o" ? "older" : "newer",
846
+ boundarySequence: value[8] as number,
847
+ boundaryStart: value[9] as number,
848
+ boundaryEnd: value[10] as number,
849
+ boundaryDigest: value[11] as string,
850
+ view,
851
+ types,
852
+ filterProvided: value[13] !== null,
853
+ };
854
+ }
855
+
856
+ function validateSnapshotPayload(payload: SnapshotPayload, header: TranscriptHeaderRecord, fileSize: number): void {
857
+ if (payload.id !== identityTag(header.transcriptId) || payload.generation !== header.generation) {
858
+ throw new TranscriptCursorInvalidError("transcript cursor belongs to another log generation");
859
+ }
860
+ if (payload.highOffset > fileSize) throw new TranscriptCursorInvalidError("transcript was truncated after cursor creation");
861
+ }
862
+
863
+ async function digestPrefix(handle: FileHandle, end: number): Promise<string> {
864
+ const hash = createHash("sha256");
865
+ let position = 0;
866
+ while (position < end) {
867
+ const size = Math.min(READ_CHUNK_BYTES, end - position);
868
+ const bytes = await readBytes(handle, position, size);
869
+ if (bytes.byteLength !== size) throw new TranscriptCursorInvalidError("transcript changed while validating snapshot");
870
+ hash.update(bytes);
871
+ position += size;
872
+ }
873
+ return hash.digest("base64url").slice(0, 22);
874
+ }
875
+
876
+ async function readBytes(handle: FileHandle, start: number, length: number): Promise<Buffer> {
877
+ const output = Buffer.allocUnsafe(length);
878
+ let read = 0;
879
+ while (read < length) {
880
+ const result = await handle.read(output, read, length - read, start + read);
881
+ if (result.bytesRead === 0) break;
882
+ read += result.bytesRead;
883
+ }
884
+ return read === length ? output : output.subarray(0, read);
885
+ }
886
+
887
+ function sha256Bytes(value: Uint8Array): string {
888
+ return createHash("sha256").update(value).digest("base64url").slice(0, 22);
889
+ }
890
+
891
+ function identityTag(value: string): string {
892
+ return sha256Bytes(Buffer.from(value, "utf8"));
893
+ }
894
+
895
+ function typesMask(types: readonly TranscriptRecordType[]): number {
896
+ let mask = 0;
897
+ for (const type of types) mask |= 1 << RECORD_TYPE_ORDER.indexOf(type);
898
+ return mask;
899
+ }
900
+
901
+ function typesFromMask(value: unknown): TranscriptRecordType[] | null {
902
+ if (!nonnegativeInteger(value) || value >= (1 << RECORD_TYPE_ORDER.length)) return null;
903
+ return RECORD_TYPE_ORDER.filter((_, index) => (value & (1 << index)) !== 0).sort();
904
+ }
905
+
906
+ function positiveInteger(value: unknown): value is number {
907
+ return Number.isSafeInteger(value) && (value as number) > 0;
908
+ }
909
+
910
+ function nonnegativeInteger(value: unknown): value is number {
911
+ return Number.isSafeInteger(value) && (value as number) >= 0;
912
+ }
913
+
914
+ function integrityTag(value: unknown): value is string {
915
+ return typeof value === "string" && /^[A-Za-z0-9_-]{22}$/.test(value);
916
+ }
917
+
918
+ function viewCode(view: TranscriptView): "c" | "t" | "r" {
919
+ return view === "conversation" ? "c" : view === "timeline" ? "t" : "r";
920
+ }
921
+
922
+ function decodeView(value: unknown): TranscriptView | null {
923
+ return value === "c" ? "conversation" : value === "t" ? "timeline" : value === "r" ? "records" : null;
924
+ }
925
+
926
+ function boundedCursor(cursor: TranscriptCursor, maxBytes: number): TranscriptCursor {
927
+ if (Buffer.byteLength(cursor, "utf8") > maxBytes) {
928
+ throw new TranscriptReaderError("generated transcript navigation cursor exceeds the engraved limit");
929
+ }
930
+ return cursor;
931
+ }
932
+
933
+ function boundedSnapshotCursor(cursor: string, maxBytes: number): TranscriptSnapshotCursor {
934
+ if (Buffer.byteLength(cursor, "utf8") > maxBytes) {
935
+ throw new TranscriptReaderError("generated transcript snapshot cursor exceeds the engraved limit");
936
+ }
937
+ return cursor as TranscriptSnapshotCursor;
938
+ }
939
+
940
+ function isRecord(value: unknown): value is Record<string, unknown> {
941
+ return typeof value === "object" && value !== null && !Array.isArray(value);
942
+ }
943
+
944
+ function isActivityRecord(
945
+ value: TranscriptReadableRecord,
946
+ ): value is TranscriptActivityRecord {
947
+ return "transcriptId" in value && value.v === 2
948
+ && value.t === "activity" && "activityId" in value;
949
+ }
950
+
951
+ function legacyBoundary(header: TranscriptHeaderRecord): number {
952
+ return header.event === "upgraded" ? header.upgradedFrom!.boundaryOffset : 0;
953
+ }
954
+
955
+ function legacyProjectionType(record: LegacyTranscriptLine): TranscriptRecordType | null {
956
+ switch (record.t) {
957
+ case "msg": return "message";
958
+ case "activity": return "activity";
959
+ case "permission": return "permission";
960
+ case "handoff": return "transition";
961
+ case "meta": return "protocol";
962
+ case "raw": return "raw";
963
+ }
964
+ }
965
+
966
+ /** @internal Shared byte-scanning primitives for the audit-log reader. */
967
+ export const SESSION_LOG_READER_INTERNALS = Object.freeze({
968
+ hardMaxRecordBytes: HARD_MAX_RECORD_BYTES,
969
+ forwardLines,
970
+ backwardLines,
971
+ readBytes,
972
+ firstPhysical,
973
+ readLastPhysical,
974
+ lastCompleteOffset,
975
+ digestPrefix,
976
+ sha256Bytes,
977
+ positiveInteger,
978
+ nonnegativeInteger,
979
+ integrityTag,
980
+ });