@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,385 @@
1
+ import { open, type FileHandle } from "node:fs/promises";
2
+ import { isAbsolute } from "node:path";
3
+ import { canonicalizeJson } from "./integrity.ts";
4
+ import {
5
+ reduceTranscriptHistory,
6
+ reduceTranscriptState,
7
+ TranscriptReductionError,
8
+ type TranscriptHistoryReduction,
9
+ type TranscriptReductionResult,
10
+ type TranscriptStructuralRecord,
11
+ } from "./reducer.ts";
12
+ import {
13
+ validateTranscriptRecord,
14
+ type KnownTranscriptRecord,
15
+ type TranscriptCheckpointRecord,
16
+ type TranscriptHeaderRecord,
17
+ type TranscriptTransitionRecord,
18
+ } from "./records.ts";
19
+
20
+ const HARD_MAX_RECORD_BYTES = 16_777_216;
21
+ const READ_CHUNK_BYTES = 64 * 1024;
22
+ const UTF8 = new TextDecoder("utf-8", { fatal: true });
23
+ const KNOWN_TYPES = new Set([
24
+ "header", "checkpoint", "operation", "message", "reasoning", "activity",
25
+ "configuration", "permission", "transition", "metering_reference", "lifecycle",
26
+ "protocol", "raw",
27
+ ]);
28
+
29
+ export interface TranscriptScanExpectation {
30
+ readonly agentSessionId?: string;
31
+ readonly transcriptId?: string;
32
+ readonly generation?: number;
33
+ }
34
+
35
+ export interface TranscriptContinuationScan {
36
+ readonly header: TranscriptHeaderRecord;
37
+ readonly selectedCheckpointRecord: TranscriptCheckpointRecord;
38
+ readonly historyAtSelectedCheckpoint: TranscriptHistoryReduction;
39
+ readonly reduction: TranscriptReductionResult;
40
+ /** Structural records physically following the selected checkpoint record. */
41
+ readonly structuralTailAfterSelectedCheckpoint: readonly TranscriptStructuralRecord[];
42
+ readonly lastCompleteSequence: number;
43
+ readonly lastCompleteOffset: number;
44
+ /** File size captured before the scan; later appends are excluded from this result. */
45
+ readonly snapshotBytes: number;
46
+ readonly ignoredTrailingBytes: number;
47
+ /** At least one retained message lost text or structured detail to engraved limits. */
48
+ readonly conversationTruncated: boolean;
49
+ }
50
+
51
+ export class TranscriptNotFoundError extends Error {
52
+ constructor(readonly path: string) {
53
+ super(`transcript does not exist: ${path}`);
54
+ this.name = "TranscriptNotFoundError";
55
+ }
56
+ }
57
+
58
+ export class TranscriptUnavailableError extends Error {
59
+ constructor(message: string, options?: ErrorOptions) {
60
+ super(message, options);
61
+ this.name = "TranscriptUnavailableError";
62
+ }
63
+ }
64
+
65
+ export class TranscriptCorruptionError extends Error {
66
+ constructor(message: string, options?: ErrorOptions) {
67
+ super(message, options);
68
+ this.name = "TranscriptCorruptionError";
69
+ }
70
+ }
71
+
72
+ export class TranscriptIdentityError extends Error {
73
+ constructor(message: string) {
74
+ super(message);
75
+ this.name = "TranscriptIdentityError";
76
+ }
77
+ }
78
+
79
+ export async function scanTranscriptContinuation(
80
+ path: string,
81
+ expected: TranscriptScanExpectation = {},
82
+ ): Promise<TranscriptContinuationScan> {
83
+ if (!isAbsolute(path)) throw new TranscriptUnavailableError("transcript path must be absolute");
84
+ let handle: FileHandle;
85
+ try {
86
+ handle = await open(path, "r");
87
+ } catch (error) {
88
+ if (isNodeError(error, "ENOENT")) throw new TranscriptNotFoundError(path);
89
+ throw new TranscriptUnavailableError(`cannot open transcript: ${path}`, { cause: error });
90
+ }
91
+
92
+ try {
93
+ const stat = await handle.stat();
94
+ if (!stat.isFile()) throw new TranscriptUnavailableError(`transcript is not a regular file: ${path}`);
95
+ return await scanOpenTranscript(handle, path, expected);
96
+ } catch (error) {
97
+ if (error instanceof TranscriptNotFoundError
98
+ || error instanceof TranscriptUnavailableError
99
+ || error instanceof TranscriptCorruptionError
100
+ || error instanceof TranscriptIdentityError) throw error;
101
+ throw new TranscriptUnavailableError(`cannot safely read transcript: ${path}`, { cause: error });
102
+ } finally {
103
+ await handle.close().catch(() => undefined);
104
+ }
105
+ }
106
+
107
+ async function scanOpenTranscript(
108
+ handle: FileHandle,
109
+ path: string,
110
+ expected: TranscriptScanExpectation,
111
+ ): Promise<TranscriptContinuationScan> {
112
+ let header: TranscriptHeaderRecord | null = null;
113
+ let selected: TranscriptCheckpointRecord | null = null;
114
+ let selectedHistory: TranscriptHistoryReduction | null = null;
115
+ let structuralTail: TranscriptStructuralRecord[] = [];
116
+ const activations: TranscriptTransitionRecord[] = [];
117
+ let sequence = 0;
118
+ let conversationTruncated = false;
119
+ let lastCompleteOffset = 0;
120
+ const snapshotSize = (await handle.stat()).size;
121
+
122
+ for await (const physical of completeLines(handle, snapshotSize)) {
123
+ if (!header) {
124
+ const candidate = tryParseJsonObject(physical.bytes);
125
+ if (!candidate || candidate.v !== 2) {
126
+ // A linked v1 prefix is presentation-only and retains its permissive reader rules.
127
+ lastCompleteOffset = physical.endOffset;
128
+ continue;
129
+ }
130
+ let upgrade: KnownTranscriptRecord;
131
+ try {
132
+ validateTranscriptRecord(candidate, { transcriptPath: path });
133
+ upgrade = candidate;
134
+ } catch (error) {
135
+ throw new TranscriptCorruptionError("invalid v2 header after legacy prefix", { cause: error });
136
+ }
137
+ if (upgrade.t !== "header" || upgrade.seq !== 1) {
138
+ corrupt("first v2 record must be the transcript header", 1);
139
+ }
140
+ if (physical.startOffset > 0) {
141
+ if (upgrade.event !== "upgraded"
142
+ || upgrade.upgradedFrom?.boundaryOffset !== physical.startOffset) {
143
+ corrupt("mixed transcript has an invalid declared legacy boundary", 1);
144
+ }
145
+ } else if (upgrade.event === "upgraded" && upgrade.upgradedFrom?.boundaryOffset !== 0) {
146
+ corrupt("upgrade header boundary does not match its physical position", 1);
147
+ }
148
+ assertExpectedHeaderIdentity(upgrade, expected);
149
+ if (physical.bytes.byteLength > upgrade.effectiveLimits.maxRecordBytes) {
150
+ corrupt("header exceeds its engraved maxRecordBytes", 1);
151
+ }
152
+ header = upgrade;
153
+ sequence = 1;
154
+ lastCompleteOffset = physical.endOffset;
155
+ continue;
156
+ }
157
+
158
+ if (physical.bytes.byteLength === 0) corrupt("empty complete line", sequence + 1);
159
+ const maxBytes = header?.effectiveLimits.maxRecordBytes ?? HARD_MAX_RECORD_BYTES;
160
+ if (physical.bytes.byteLength > maxBytes) {
161
+ corrupt(`record exceeds effective maxRecordBytes (${physical.bytes.byteLength} > ${maxBytes})`, sequence + 1);
162
+ }
163
+ const raw = parseJsonObject(physical.bytes, sequence + 1);
164
+ const nextSequence = sequence + 1;
165
+ assertEnvelopeIdentity(raw, header, expected, nextSequence);
166
+ sequence = nextSequence;
167
+ lastCompleteOffset = physical.endOffset;
168
+
169
+ if (!KNOWN_TYPES.has(raw.t as string)) {
170
+ validateUnknownEnvelope(raw, nextSequence);
171
+ continue;
172
+ }
173
+
174
+ let record: KnownTranscriptRecord;
175
+ try {
176
+ validateTranscriptRecord(raw, {
177
+ ...(header ? {
178
+ agentSessionId: header.agentSessionId,
179
+ logId: header.transcriptId,
180
+ generation: header.generation,
181
+ transcriptPath: path,
182
+ } : {}),
183
+ });
184
+ record = raw;
185
+ } catch (error) {
186
+ throw new TranscriptCorruptionError(`invalid transcript record at sequence ${nextSequence}`, { cause: error });
187
+ }
188
+
189
+ if (record.t === "header") corrupt("transcript generation contains more than one header", nextSequence);
190
+ if (record.t === "message" && (record.truncation?.length ?? 0) > 0) {
191
+ conversationTruncated = true;
192
+ }
193
+
194
+ if (record.t === "transition" && record.event === "target_activated") activations.push(record);
195
+ if (!isStructural(record)) continue;
196
+
197
+ if (record.t !== "checkpoint") {
198
+ if (!selected) corrupt("structural record appears before the initial checkpoint", nextSequence);
199
+ structuralTail.push(record);
200
+ continue;
201
+ }
202
+
203
+ const history = historyThrough(activations, record.checkpoint.transcript!.coveredSequence);
204
+ if (!selected) {
205
+ validateReduction(record, history, []);
206
+ } else {
207
+ structuralTail.push(record);
208
+ validateReduction(selected, selectedHistory!, structuralTail);
209
+ }
210
+ selected = record;
211
+ selectedHistory = history;
212
+ structuralTail = [];
213
+ }
214
+
215
+ if (!header) throw new TranscriptCorruptionError("transcript has no complete header");
216
+ if (!selected || !selectedHistory) throw new TranscriptCorruptionError("transcript has no complete checkpoint");
217
+ const reduction = validateReduction(selected, selectedHistory, structuralTail);
218
+ return {
219
+ header,
220
+ selectedCheckpointRecord: selected,
221
+ historyAtSelectedCheckpoint: selectedHistory,
222
+ reduction,
223
+ structuralTailAfterSelectedCheckpoint: structuralTail.map((record) => structuredClone(record)),
224
+ lastCompleteSequence: sequence,
225
+ lastCompleteOffset,
226
+ snapshotBytes: snapshotSize,
227
+ ignoredTrailingBytes: snapshotSize - lastCompleteOffset,
228
+ conversationTruncated,
229
+ };
230
+ }
231
+
232
+ function historyThrough(
233
+ activations: readonly TranscriptTransitionRecord[],
234
+ coveredSequence: number,
235
+ ): TranscriptHistoryReduction {
236
+ return reduceTranscriptHistory(activations.filter((record) => record.seq <= coveredSequence));
237
+ }
238
+
239
+ function validateReduction(
240
+ checkpoint: TranscriptCheckpointRecord,
241
+ history: TranscriptHistoryReduction,
242
+ tail: readonly TranscriptStructuralRecord[],
243
+ ): TranscriptReductionResult {
244
+ try {
245
+ return reduceTranscriptState(checkpoint, history, tail);
246
+ } catch (error) {
247
+ if (error instanceof TranscriptReductionError) {
248
+ throw new TranscriptCorruptionError("transcript structural reduction failed", { cause: error });
249
+ }
250
+ throw error;
251
+ }
252
+ }
253
+
254
+ function isStructural(record: KnownTranscriptRecord): record is TranscriptStructuralRecord {
255
+ return record.t === "checkpoint" || record.t === "operation" || record.t === "transition";
256
+ }
257
+
258
+ function parseJsonObject(bytes: Buffer, sequence: number): Record<string, unknown> {
259
+ try {
260
+ const value: unknown = JSON.parse(UTF8.decode(bytes));
261
+ if (!isRecord(value)) corrupt("record must be a JSON object", sequence);
262
+ return value;
263
+ } catch (error) {
264
+ if (error instanceof TranscriptCorruptionError) throw error;
265
+ throw new TranscriptCorruptionError(`malformed complete JSON at sequence ${sequence}`, { cause: error });
266
+ }
267
+ }
268
+
269
+ function assertEnvelopeIdentity(
270
+ value: Record<string, unknown>,
271
+ header: TranscriptHeaderRecord | null,
272
+ expected: TranscriptScanExpectation,
273
+ sequence: number,
274
+ ): void {
275
+ if (value.seq !== sequence) corrupt(`expected sequence ${sequence}`, sequence);
276
+ if (value.v !== 2) corrupt(`unsupported transcript version at sequence ${sequence}`, sequence);
277
+ if (header) {
278
+ if (value.agentSessionId !== header.agentSessionId
279
+ || value.transcriptId !== header.transcriptId
280
+ || value.generation !== header.generation) {
281
+ throw new TranscriptIdentityError(`transcript identity changes at sequence ${sequence}`);
282
+ }
283
+ }
284
+ const agentSessionId = header?.agentSessionId ?? value.agentSessionId;
285
+ const transcriptId = header?.transcriptId ?? value.transcriptId;
286
+ const generation = header?.generation ?? value.generation;
287
+ if (expected.agentSessionId !== undefined && agentSessionId !== expected.agentSessionId) {
288
+ throw new TranscriptIdentityError("agentSessionId does not match requested transcript identity");
289
+ }
290
+ if (expected.transcriptId !== undefined && transcriptId !== expected.transcriptId) {
291
+ throw new TranscriptIdentityError("transcriptId does not match requested transcript identity");
292
+ }
293
+ if (expected.generation !== undefined && generation !== expected.generation) {
294
+ throw new TranscriptIdentityError("transcript generation does not match requested identity");
295
+ }
296
+ }
297
+
298
+ function validateUnknownEnvelope(value: Record<string, unknown>, sequence: number): void {
299
+ try {
300
+ canonicalizeJson(value);
301
+ } catch (error) {
302
+ throw new TranscriptCorruptionError(`unknown record at sequence ${sequence} is not canonical JSON`, { cause: error });
303
+ }
304
+ if (typeof value.t !== "string" || !value.t) corrupt("unknown record type must be nonblank", sequence);
305
+ if (typeof value.agentSessionId !== "string" || !value.agentSessionId
306
+ || typeof value.transcriptId !== "string" || !value.transcriptId
307
+ || !Number.isSafeInteger(value.generation) || (value.generation as number) < 1
308
+ || !Number.isSafeInteger(value.ts)) {
309
+ corrupt("unknown record has an invalid envelope", sequence);
310
+ }
311
+ }
312
+
313
+ interface CompleteLine {
314
+ bytes: Buffer;
315
+ startOffset: number;
316
+ endOffset: number;
317
+ }
318
+
319
+ async function* completeLines(handle: FileHandle, snapshotSize: number): AsyncGenerator<CompleteLine> {
320
+ const chunk = Buffer.allocUnsafe(READ_CHUNK_BYTES);
321
+ let pending = Buffer.alloc(0);
322
+ let position = 0;
323
+ while (position < snapshotSize) {
324
+ const requested = Math.min(chunk.byteLength, snapshotSize - position);
325
+ const read = await handle.read(chunk, 0, requested, position);
326
+ if (read.bytesRead === 0) {
327
+ throw new TranscriptUnavailableError("transcript was truncated while it was being read");
328
+ }
329
+ position += read.bytesRead;
330
+ const combined = pending.byteLength === 0
331
+ ? Buffer.from(chunk.subarray(0, read.bytesRead))
332
+ : Buffer.concat([pending, chunk.subarray(0, read.bytesRead)]);
333
+ let start = 0;
334
+ for (;;) {
335
+ const newline = combined.indexOf(0x0a, start);
336
+ if (newline < 0) break;
337
+ const bytes = combined.subarray(start, newline);
338
+ const startOffset = position - combined.byteLength + start;
339
+ const endOffset = position - combined.byteLength + newline + 1;
340
+ yield { bytes, startOffset, endOffset };
341
+ start = newline + 1;
342
+ }
343
+ pending = Buffer.from(combined.subarray(start));
344
+ if (pending.byteLength > HARD_MAX_RECORD_BYTES) {
345
+ throw new TranscriptCorruptionError("incomplete or oversized transcript record exceeds the hard safety ceiling");
346
+ }
347
+ }
348
+ // A nonempty pending suffix is a torn final line and intentionally ignored.
349
+ }
350
+
351
+ function tryParseJsonObject(bytes: Buffer): Record<string, unknown> | null {
352
+ try {
353
+ const value: unknown = JSON.parse(UTF8.decode(bytes));
354
+ return isRecord(value) ? value : null;
355
+ } catch {
356
+ return null;
357
+ }
358
+ }
359
+
360
+ function assertExpectedHeaderIdentity(
361
+ header: TranscriptHeaderRecord,
362
+ expected: TranscriptScanExpectation,
363
+ ): void {
364
+ if (expected.agentSessionId !== undefined && header.agentSessionId !== expected.agentSessionId) {
365
+ throw new TranscriptIdentityError("agentSessionId does not match requested transcript identity");
366
+ }
367
+ if (expected.transcriptId !== undefined && header.transcriptId !== expected.transcriptId) {
368
+ throw new TranscriptIdentityError("transcriptId does not match requested transcript identity");
369
+ }
370
+ if (expected.generation !== undefined && header.generation !== expected.generation) {
371
+ throw new TranscriptIdentityError("transcript generation does not match requested identity");
372
+ }
373
+ }
374
+
375
+ function corrupt(message: string, sequence?: number): never {
376
+ throw new TranscriptCorruptionError(sequence === undefined ? message : `${message} (sequence ${sequence})`);
377
+ }
378
+
379
+ function isNodeError(error: unknown, code: string): boolean {
380
+ return typeof error === "object" && error !== null && "code" in error && (error as { code?: unknown }).code === code;
381
+ }
382
+
383
+ function isRecord(value: unknown): value is Record<string, unknown> {
384
+ return typeof value === "object" && value !== null && !Array.isArray(value);
385
+ }
@@ -0,0 +1,276 @@
1
+ import { createHash } from "node:crypto";
2
+ import {
3
+ validatePersistenceLimits,
4
+ type PersistenceLimits,
5
+ } from "./config.ts";
6
+ import { canonicalizeJson, PersistenceSerializationError } from "./integrity.ts";
7
+ import type {
8
+ KnownAuditLogRecord,
9
+ KnownTranscriptRecord,
10
+ OmittedPersistedValue,
11
+ PersistedTruncation,
12
+ } from "./records.ts";
13
+
14
+ export interface SessionLogTruncationOptions {
15
+ readonly limits: PersistenceLimits;
16
+ readonly includeTruncationDigests?: boolean;
17
+ }
18
+
19
+ export class SessionLogTruncationError extends Error {
20
+ constructor(message: string, options?: ErrorOptions) {
21
+ super(message, options);
22
+ this.name = "SessionLogTruncationError";
23
+ }
24
+ }
25
+
26
+ /**
27
+ * Bound an already policy-filtered record. This function never decides capture policy:
28
+ * values excluded by projection must not be passed here merely to compute their size/hash.
29
+ */
30
+ export function truncateSessionLogRecord<T extends KnownTranscriptRecord | KnownAuditLogRecord>(
31
+ record: T,
32
+ options: SessionLogTruncationOptions,
33
+ ): T {
34
+ validatePersistenceLimits(options.limits);
35
+ let output: MutableRecord;
36
+ try {
37
+ output = structuredClone(record) as MutableRecord;
38
+ } catch (error) {
39
+ throw new SessionLogTruncationError("projected record cannot be cloned as persistence data", { cause: error });
40
+ }
41
+ const candidates = truncationCandidates(output);
42
+ const metadata = new Map<string, PersistedTruncation>();
43
+
44
+ for (const candidate of candidates) {
45
+ const value = candidate.get();
46
+ if (value === undefined) continue;
47
+ if (candidate.kind === "string") {
48
+ const original = String(value);
49
+ if (utf8Bytes(original) > options.limits.maxCapturedFieldBytes) {
50
+ candidate.set(prefixByUtf8Bytes(original, options.limits.maxCapturedFieldBytes));
51
+ metadata.set(candidate.field, truncationMetadata(candidate.field, "field_limit", original, options.includeTruncationDigests));
52
+ }
53
+ continue;
54
+ }
55
+ const measured = measureStructured(value, options.limits.maxJsonDepth);
56
+ if (measured.status === "too_deep") {
57
+ candidate.set(omitted("max_depth", undefined, undefined));
58
+ candidate.reduced = true;
59
+ } else if (measured.bytes > options.limits.maxCapturedFieldBytes) {
60
+ const info = truncationMetadata(candidate.field, "field_limit", value, options.includeTruncationDigests);
61
+ candidate.set(candidate.kind === "optional" ? undefined : omitted("field_limit", info.originalBytes, info.originalSha256));
62
+ metadata.set(candidate.field, info);
63
+ candidate.reduced = true;
64
+ }
65
+ }
66
+
67
+ installMetadata(output, metadata);
68
+ for (;;) {
69
+ const size = recordBytes(output, options.limits.maxJsonDepth);
70
+ if (size.status === "ok" && size.bytes <= options.limits.maxRecordBytes) return output as T;
71
+
72
+ const candidate = candidates.find((item) => !item.reduced && item.get() !== undefined);
73
+ if (!candidate) {
74
+ throw new SessionLogTruncationError(
75
+ size.status === "too_deep"
76
+ ? "structural session-log record exceeds maxJsonDepth"
77
+ : `structural session-log record exceeds maxRecordBytes (${size.bytes} > ${options.limits.maxRecordBytes})`,
78
+ );
79
+ }
80
+ const original = candidate.original;
81
+ if (candidate.kind === "string") {
82
+ const info = truncationMetadata(candidate.field, "record_limit", original, options.includeTruncationDigests);
83
+ metadata.set(candidate.field, info);
84
+ installMetadata(output, metadata);
85
+ candidate.set(longestFittingPrefix(output, candidate, String(candidate.get()), options.limits));
86
+ } else {
87
+ const measured = measureStructured(original, Number.MAX_SAFE_INTEGER);
88
+ const info = measured.status === "ok"
89
+ ? truncationMetadata(candidate.field, "record_limit", original, options.includeTruncationDigests)
90
+ : null;
91
+ candidate.set(candidate.kind === "optional"
92
+ ? undefined
93
+ : omitted("record_limit", info?.originalBytes, info?.originalSha256));
94
+ if (info) metadata.set(candidate.field, info);
95
+ }
96
+ candidate.reduced = true;
97
+ installMetadata(output, metadata);
98
+ }
99
+ }
100
+
101
+ type MutableRecord = Record<string, any>;
102
+ interface Candidate {
103
+ readonly field: string;
104
+ readonly kind: "string" | "value" | "optional";
105
+ readonly original: unknown;
106
+ get(): unknown;
107
+ set(value: unknown): void;
108
+ reduced: boolean;
109
+ }
110
+
111
+ function truncationCandidates(record: MutableRecord): Candidate[] {
112
+ const candidates: Candidate[] = [];
113
+ // Priority is normative: raw duplicates/results, reasoning, invocation input, message
114
+ // structure/text, then other presentation-only details.
115
+ if (record.t === "raw") add(record, "data", "data", "value", candidates);
116
+ if (record.t === "activity" && isRecord(record.data)) {
117
+ add(record.data, "content", "data.content", "value", candidates);
118
+ }
119
+ if (record.t === "reasoning") add(record, "text", "text", "string", candidates);
120
+ if (record.t === "activity" && isRecord(record.data)) {
121
+ add(record.data, "input", "data.input", "value", candidates);
122
+ }
123
+ if (record.t === "message") {
124
+ add(record, "structured", "structured", "optional", candidates);
125
+ add(record, "text", "text", "string", candidates);
126
+ add(record, "status", "status", "string", candidates);
127
+ add(record, "stopReason", "stopReason", "string", candidates);
128
+ }
129
+ if (record.t === "configuration") {
130
+ add(record, "definitions", "definitions", "value", candidates);
131
+ add(record, "value", "value", "value", candidates);
132
+ }
133
+ if (record.t === "permission") add(record, "details", "details", "value", candidates);
134
+ if (record.t === "transition") {
135
+ add(record, "summary", "summary", "string", candidates);
136
+ add(record, "reasonText", "reasonText", "string", candidates);
137
+ }
138
+ if (record.t === "metering_reference") add(record, "summary", "summary", "value", candidates);
139
+ if (record.t === "lifecycle") add(record, "detail", "detail", "value", candidates);
140
+ if (record.t === "protocol" && isRecord(record.agent)) {
141
+ add(record.agent, "name", "agent.name", "string", candidates);
142
+ add(record.agent, "title", "agent.title", "string", candidates);
143
+ add(record.agent, "version", "agent.version", "string", candidates);
144
+ }
145
+ return candidates;
146
+ }
147
+
148
+ function add(
149
+ container: MutableRecord,
150
+ key: string,
151
+ field: string,
152
+ kind: Candidate["kind"],
153
+ output: Candidate[],
154
+ ): void {
155
+ if (!(key in container)) return;
156
+ const original = structuredClone(container[key]);
157
+ output.push({
158
+ field,
159
+ kind,
160
+ original,
161
+ get: () => container[key],
162
+ set: (value) => { if (value === undefined) delete container[key]; else container[key] = value; },
163
+ reduced: false,
164
+ });
165
+ }
166
+
167
+ function installMetadata(record: MutableRecord, values: Map<string, PersistedTruncation>): void {
168
+ if (values.size === 0) return;
169
+ const existing = Array.isArray(record.truncation) ? record.truncation : [];
170
+ const fields = new Set(values.keys());
171
+ record.truncation = [
172
+ ...existing.filter((item: PersistedTruncation) => !fields.has(item.field)),
173
+ ...values.values(),
174
+ ];
175
+ }
176
+
177
+ function truncationMetadata(
178
+ field: string,
179
+ reason: PersistedTruncation["reason"],
180
+ value: unknown,
181
+ includeDigest = false,
182
+ ): PersistedTruncation {
183
+ const bytes = persistenceBytes(value);
184
+ return {
185
+ field,
186
+ reason,
187
+ originalBytes: bytes.byteLength,
188
+ ...(includeDigest ? { originalSha256: createHash("sha256").update(bytes).digest("hex") } : {}),
189
+ };
190
+ }
191
+
192
+ function omitted(
193
+ reason: OmittedPersistedValue["reason"],
194
+ originalBytes?: number,
195
+ originalSha256?: string,
196
+ ): OmittedPersistedValue {
197
+ return {
198
+ omitted: true,
199
+ reason,
200
+ ...(originalBytes === undefined ? {} : { originalBytes }),
201
+ ...(originalSha256 === undefined ? {} : { originalSha256 }),
202
+ };
203
+ }
204
+
205
+ function longestFittingPrefix(
206
+ record: MutableRecord,
207
+ candidate: Candidate,
208
+ current: string,
209
+ limits: PersistenceLimits,
210
+ ): string {
211
+ const points = Array.from(current);
212
+ let low = 0;
213
+ let high = points.length;
214
+ let best = "";
215
+ while (low <= high) {
216
+ const middle = Math.floor((low + high) / 2);
217
+ const value = points.slice(0, middle).join("");
218
+ candidate.set(value);
219
+ const size = recordBytes(record, limits.maxJsonDepth);
220
+ if (size.status === "ok" && size.bytes <= limits.maxRecordBytes) {
221
+ best = value;
222
+ low = middle + 1;
223
+ } else {
224
+ high = middle - 1;
225
+ }
226
+ }
227
+ return best;
228
+ }
229
+
230
+ function prefixByUtf8Bytes(value: string, limit: number): string {
231
+ let used = 0;
232
+ let output = "";
233
+ for (const point of value) {
234
+ const bytes = utf8Bytes(point);
235
+ if (used + bytes > limit) break;
236
+ output += point;
237
+ used += bytes;
238
+ }
239
+ return output;
240
+ }
241
+
242
+ function measureStructured(value: unknown, maxDepth: number): { status: "ok"; bytes: number } | { status: "too_deep" } {
243
+ try {
244
+ return { status: "ok", bytes: utf8Bytes(canonicalizeJson(value, maxDepth)) };
245
+ } catch (error) {
246
+ if (isMaximumDepthError(error)) return { status: "too_deep" };
247
+ throw new SessionLogTruncationError("captured value is not canonical JSON", { cause: error });
248
+ }
249
+ }
250
+
251
+ function recordBytes(record: MutableRecord, maxDepth: number): { status: "ok"; bytes: number } | { status: "too_deep"; bytes?: never } {
252
+ try {
253
+ canonicalizeJson(record, maxDepth);
254
+ return { status: "ok", bytes: utf8Bytes(JSON.stringify(record)) };
255
+ } catch (error) {
256
+ if (isMaximumDepthError(error)) return { status: "too_deep" };
257
+ throw new SessionLogTruncationError("session-log record is not canonical JSON", { cause: error });
258
+ }
259
+ }
260
+
261
+ function isMaximumDepthError(error: unknown): boolean {
262
+ return error instanceof PersistenceSerializationError
263
+ && error.message.startsWith("JSON value exceeds maximum depth ");
264
+ }
265
+
266
+ function persistenceBytes(value: unknown): Buffer {
267
+ return Buffer.from(typeof value === "string" ? value : canonicalizeJson(value), "utf8");
268
+ }
269
+
270
+ function utf8Bytes(value: string): number {
271
+ return Buffer.byteLength(value, "utf8");
272
+ }
273
+
274
+ function isRecord(value: unknown): value is MutableRecord {
275
+ return typeof value === "object" && value !== null && !Array.isArray(value);
276
+ }