@nones/agentflow-opencode 0.1.0 → 0.6.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.
@@ -0,0 +1,930 @@
1
+ /**
2
+ * Provider-only normalization of OpenCode visible history and usage.
3
+ *
4
+ * This module is deliberately independent of `@nones/agentflow-core`: it turns
5
+ * the native message list into bounded, redacted, safe summaries with stable
6
+ * message/part identities. Attachment, persistence and UI stay with the host
7
+ * application (see `inspectTranscript` in `adapter.ts` for the read-only loader).
8
+ *
9
+ * Guarantees:
10
+ * - private reasoning parts, provider headers and raw tool arguments are never
11
+ * surfaced; every omission carries an explicit state;
12
+ * - text and tool output are bounded, counters are bounded by reality (numbers);
13
+ * - counters are summed once per unique message id, so a replayed page or
14
+ * duplicate message/part cannot double-count usage;
15
+ * - a value the provider does not report stays `undefined`, never `0`.
16
+ */
17
+
18
+ import {
19
+ asNumber,
20
+ asString,
21
+ extractMessages,
22
+ isAssistantMessage,
23
+ isRecord,
24
+ isUserMessage,
25
+ messageCreatedAt,
26
+ messageErrorText,
27
+ messageId,
28
+ messageRole,
29
+ messageText,
30
+ tryParseModelRef,
31
+ unwrapData,
32
+ type JsonRecord,
33
+ } from "./normalize";
34
+ import type { ModelRef, Profile } from "./types";
35
+
36
+ /** Truncation state of any bounded string in a summary. */
37
+ export type BoundedState = "complete" | "truncated" | "omitted";
38
+
39
+ export type TranscriptTextPart = {
40
+ kind: "text";
41
+ id: string;
42
+ state: BoundedState;
43
+ text: string;
44
+ /** Provider-reported length when present, otherwise the normalized length. */
45
+ length?: number;
46
+ };
47
+
48
+ export type TranscriptToolPart = {
49
+ kind: "tool";
50
+ id: string;
51
+ name?: string;
52
+ status?: string;
53
+ /** Raw tool input is never included; only the state marker is. */
54
+ input: "omitted";
55
+ /**
56
+ * Default diagnostic mode never carries literal provider tool output. The
57
+ * field exists only so an opt-in caller can see the omission state; its text
58
+ * is always empty here and any provider result is reported as an omission.
59
+ */
60
+ output?: { state: BoundedState; text: string };
61
+ time?: { start?: number; end?: number };
62
+ };
63
+
64
+ export type TranscriptUnknownPart = {
65
+ kind: "unknown";
66
+ id: string;
67
+ /** Safe part type token; absent when the provider omitted a type. */
68
+ type?: string;
69
+ state: "unsupported";
70
+ };
71
+
72
+ /** Reasoning parts are recognized and flagged, never transcribed. */
73
+ export type TranscriptRedactedPart = {
74
+ kind: "reasoning";
75
+ id: string;
76
+ redacted: true;
77
+ };
78
+
79
+ export type TranscriptPart =
80
+ | TranscriptTextPart
81
+ | TranscriptToolPart
82
+ | TranscriptUnknownPart
83
+ | TranscriptRedactedPart;
84
+
85
+ /**
86
+ * Provider-native token counters. Each counter is kept independently: a counter
87
+ * the provider does not report is absent (`undefined`) rather than `0`. No
88
+ * relationship between `input`, `cachedInput` and `cacheWrite` is assumed — they
89
+ * are reported under the provider's own names and never added together to form
90
+ * an inclusive total.
91
+ */
92
+ export interface TranscriptUsage {
93
+ input?: number;
94
+ output?: number;
95
+ cachedInput?: number;
96
+ cacheWrite?: number;
97
+ reasoning?: number;
98
+ }
99
+
100
+ export interface TranscriptMessageSummary {
101
+ /** Stable provider message id; empty or non-string payloads are invalid. */
102
+ id: string;
103
+ role: "assistant" | "user" | "unknown";
104
+ sessionID?: string;
105
+ parentID?: string;
106
+ createdAt?: number;
107
+ completedAt?: number;
108
+ model?: ModelRef;
109
+ parts: TranscriptPart[];
110
+ /** This message's own counters, normalized with documented semantics. */
111
+ usage?: TranscriptUsage;
112
+ }
113
+
114
+ export interface TranscriptOmission {
115
+ kind: "header" | "arguments" | "output" | "reasoning" | "data" | "message";
116
+ reason: string;
117
+ }
118
+
119
+ export interface TranscriptTotals {
120
+ /** Messages that contributed at least one known counter. */
121
+ attempts: number;
122
+ /** Per-counter sums of the values actually reported; absent counters stay absent. */
123
+ usage: TranscriptUsage;
124
+ /** Counter names the provider reported that this mapping does not count. */
125
+ unmappedKeys: string[];
126
+ /** Known native counters absent from at least one usage-bearing message. */
127
+ missingCounters: string[];
128
+ }
129
+
130
+ export interface TranscriptSummary {
131
+ sessionID?: string;
132
+ /** Messages or parts that could not be identified (no stable id). */
133
+ invalid: number;
134
+ /** Parts of a type this adapter does not present. */
135
+ unsupportedParts: number;
136
+ redacted: { reasoningParts: number; headers: number };
137
+ messages: TranscriptMessageSummary[];
138
+ totals: TranscriptTotals;
139
+ omitted: TranscriptOmission[];
140
+ /** `false` when a usage-bearing message is missing a counter. */
141
+ usageComplete: boolean;
142
+ }
143
+
144
+ export interface TranscriptSnapshot extends TranscriptSummary {
145
+ /** Every unique message id seen so far, in first-seen order. */
146
+ seenMessageIds: string[];
147
+ }
148
+
149
+ export interface TranscriptOptions {
150
+ /** Maximum retained characters of a single text or tool output. Default 4_000. */
151
+ maxTextLength?: number;
152
+ /** Maximum retained messages in a snapshot. Default 200. */
153
+ maxMessages?: number;
154
+ /** Maximum retained parts of a single message. Default 200. */
155
+ maxParts?: number;
156
+ }
157
+
158
+ export type TranscriptPageStatus =
159
+ /** A page envelope was parsed. */
160
+ | "complete"
161
+ /** No pagination metadata; the entries are whatever the endpoint returned. */
162
+ | "unknown"
163
+ /** The body was a bare list; paging is not part of this response. */
164
+ | "unsupported";
165
+
166
+ export interface TranscriptPageRequest {
167
+ /** Opaque provider cursor; echoed back unchanged. */
168
+ cursor?: string;
169
+ /** Maximum entries requested; the adapter clamps it. */
170
+ limit?: number;
171
+ }
172
+
173
+ export interface TranscriptPage extends TranscriptPageRequest {
174
+ status: TranscriptPageStatus;
175
+ entries: JsonRecord[];
176
+ nextCursor?: string;
177
+ /** Provider-reported total when finite and non-negative. */
178
+ total?: number;
179
+ /** Capture time (ms) used by the host for ordering and staleness. */
180
+ capturedAt: number;
181
+ }
182
+
183
+ export interface TranscriptPageClient {
184
+ /** Existing read-only transport: `GET /api/session/{id}/message`. */
185
+ get(
186
+ path: string,
187
+ signal?: AbortSignal,
188
+ ): Promise<{ ok: boolean; status: number; body: unknown }>;
189
+ }
190
+
191
+ /** Provider-side cursor replay: the same page served twice counts once. */
192
+ export interface TranscriptAccumulator {
193
+ absorb(page: TranscriptPage): TranscriptSnapshot;
194
+ snapshot(): TranscriptSnapshot;
195
+ }
196
+
197
+ const DEFAULT_MAX_TEXT = 4_000;
198
+ const DEFAULT_MAX_MESSAGES = 200;
199
+ const DEFAULT_MAX_PARTS = 200;
200
+ const DEFAULT_PAGE_SIZE = 50;
201
+
202
+ function clampLimit(value: number | undefined, fallback: number): number {
203
+ if (value === undefined || !Number.isFinite(value)) return fallback;
204
+ const rounded = Math.floor(value);
205
+ if (rounded < 1) return 1;
206
+ return Math.min(rounded, fallback);
207
+ }
208
+
209
+ function boundText(
210
+ value: string,
211
+ maxLength: number,
212
+ ): { text: string; state: BoundedState } {
213
+ if (value.trim().length === 0) return { text: "", state: "omitted" };
214
+ if (value.length <= maxLength) return { text: value, state: "complete" };
215
+ return { text: value.slice(0, maxLength), state: "truncated" };
216
+ }
217
+
218
+ const MAPPED_USAGE_KEYS = new Set([
219
+ "input",
220
+ "output",
221
+ "reasoning",
222
+ "prompt_tokens",
223
+ "completion_tokens",
224
+ "input_tokens",
225
+ "output_tokens",
226
+ "reasoning_tokens",
227
+ "cache",
228
+ "cache_read",
229
+ "cache_read_input_tokens",
230
+ "cache_creation",
231
+ "cache_creation_input_tokens",
232
+ "total",
233
+ "total_tokens",
234
+ ]);
235
+
236
+ const NESTED_USAGE_KEYS = new Set(["read", "write", "total"]);
237
+
238
+ function counter(
239
+ source: JsonRecord | undefined,
240
+ ...keys: string[]
241
+ ): number | undefined {
242
+ if (!source) return undefined;
243
+ for (const key of keys) {
244
+ const value = asNumber(source[key]);
245
+ if (value !== undefined && value >= 0) return value;
246
+ }
247
+ return undefined;
248
+ }
249
+
250
+ export interface NormalizedUsage {
251
+ usage?: TranscriptUsage;
252
+ /** Counter names reported by the provider that this mapping ignores. */
253
+ unmappedKeys: string[];
254
+ /** Known native counters the provider did not report for this message. */
255
+ missingCounters: string[];
256
+ }
257
+
258
+ /** The counters this adapter counts, in provider-native terms. */
259
+ const KNOWN_COUNTERS = [
260
+ "input",
261
+ "output",
262
+ "cachedInput",
263
+ "cacheWrite",
264
+ ] as const;
265
+ type KnownCounter = (typeof KNOWN_COUNTERS)[number];
266
+
267
+ /**
268
+ * Map native counters. Each counter is read independently under its own native
269
+ * name; no counter is defaulted to `0` and no cache/input relationship is
270
+ * inferred. A counter the provider omits is listed in `missingCounters` so a
271
+ * partial attempt is explicit rather than looking complete.
272
+ */
273
+ export function normalizeUsage(usage: unknown): NormalizedUsage {
274
+ const unmappedKeys: string[] = [];
275
+ if (!isRecord(usage)) {
276
+ return { unmappedKeys, missingCounters: [...KNOWN_COUNTERS] };
277
+ }
278
+
279
+ const tokens = isRecord(usage.tokens) ? usage.tokens : usage;
280
+ const cache = isRecord(tokens.cache) ? tokens.cache : undefined;
281
+
282
+ const scan = (record: JsonRecord, allowed: Set<string>) => {
283
+ for (const key of Object.keys(record)) {
284
+ if (!allowed.has(key)) unmappedKeys.push(key);
285
+ }
286
+ };
287
+ // A native usage object may nest counters under `tokens` and carry siblings
288
+ // such as `cost`; record those siblings as reported-but-unmapped, not dropped.
289
+ if (tokens !== usage) {
290
+ for (const key of Object.keys(usage)) {
291
+ if (key !== "tokens") unmappedKeys.push(key);
292
+ }
293
+ }
294
+ scan(tokens, MAPPED_USAGE_KEYS);
295
+ if (cache) scan(cache, NESTED_USAGE_KEYS);
296
+
297
+ const reported: Partial<Record<KnownCounter, number>> = {};
298
+ const input = counter(tokens, "input", "input_tokens", "prompt_tokens");
299
+ if (input !== undefined) reported.input = input;
300
+ const output = counter(
301
+ tokens,
302
+ "output",
303
+ "output_tokens",
304
+ "completion_tokens",
305
+ );
306
+ if (output !== undefined) reported.output = output;
307
+ const cachedInput =
308
+ counter(cache, "read") ??
309
+ counter(tokens, "cache_read", "cache_read_input_tokens");
310
+ if (cachedInput !== undefined) reported.cachedInput = cachedInput;
311
+ const cacheWrite =
312
+ counter(cache, "write") ??
313
+ counter(tokens, "cache_creation", "cache_creation_input_tokens");
314
+ if (cacheWrite !== undefined) reported.cacheWrite = cacheWrite;
315
+ const reasoning = counter(tokens, "reasoning", "reasoning_tokens");
316
+
317
+ // A single `total` without a split is not attributable to any counter; keep it
318
+ // unmapped rather than manufacturing input/output values from it.
319
+ const total = counter(tokens, "total", "total_tokens");
320
+ if (total !== undefined && input === undefined && output === undefined) {
321
+ unmappedKeys.push("total");
322
+ }
323
+
324
+ const hasKnown = KNOWN_COUNTERS.some((key) => reported[key] !== undefined);
325
+ const missingCounters = KNOWN_COUNTERS.filter(
326
+ (key) => reported[key] === undefined,
327
+ );
328
+
329
+ return {
330
+ ...(hasKnown
331
+ ? {
332
+ usage: {
333
+ ...reported,
334
+ ...(reasoning === undefined ? {} : { reasoning }),
335
+ },
336
+ }
337
+ : {}),
338
+ unmappedKeys: [...new Set(unmappedKeys)],
339
+ missingCounters: [...missingCounters],
340
+ };
341
+ }
342
+
343
+ function partId(part: JsonRecord): string | undefined {
344
+ return (
345
+ asString(part.id) ??
346
+ asString(part.partID) ??
347
+ asString(part.partId) ??
348
+ asString(part.callID) ??
349
+ asString(part.callId)
350
+ );
351
+ }
352
+
353
+ function normalizeToolPart(
354
+ part: JsonRecord,
355
+ id: string,
356
+ onProviderOutput: (present: boolean) => void,
357
+ ): TranscriptToolPart {
358
+ const state = isRecord(part.state) ? part.state : undefined;
359
+ const time = isRecord(state?.time)
360
+ ? state.time
361
+ : isRecord(part.time)
362
+ ? part.time
363
+ : undefined;
364
+ const start = counter(time, "start");
365
+ const end = counter(time, "end", "completed");
366
+
367
+ // Default diagnostic mode keeps only safe metadata. Provider tool output
368
+ // (literal text, structured results) and raw tool errors are never copied;
369
+ // their presence is reported so the omission is explicit rather than empty.
370
+ const providerOutput = state?.output ?? state?.result ?? part.output;
371
+ const providerError = state?.error ?? part.error;
372
+ const hasOutput = providerOutput !== undefined;
373
+ const hasError = providerError !== undefined;
374
+ onProviderOutput(hasOutput || hasError);
375
+
376
+ const output: TranscriptToolPart["output"] | undefined = hasOutput
377
+ ? { state: "omitted", text: "" }
378
+ : undefined;
379
+
380
+ const toolTime: TranscriptToolPart["time"] | undefined =
381
+ start === undefined && end === undefined
382
+ ? undefined
383
+ : {
384
+ ...(start === undefined ? {} : { start }),
385
+ ...(end === undefined ? {} : { end }),
386
+ };
387
+
388
+ return {
389
+ kind: "tool",
390
+ id,
391
+ ...(asString(part.tool) !== undefined
392
+ ? { name: safeName(asString(part.tool)!) }
393
+ : asString(part.name) !== undefined
394
+ ? { name: safeName(asString(part.name)!) }
395
+ : {}),
396
+ ...(asString(state?.status) !== undefined
397
+ ? { status: safeName(asString(state?.status)!) }
398
+ : asString(part.status) !== undefined
399
+ ? { status: safeName(asString(part.status)!) }
400
+ : {}),
401
+ input: "omitted",
402
+ ...(output === undefined ? {} : { output }),
403
+ ...(toolTime === undefined ? {} : { time: toolTime }),
404
+ };
405
+ }
406
+
407
+ /** Tool names/statuses are provider-controlled; keep a bounded safe token. */
408
+ function safeName(value: string): string {
409
+ return value.length <= 120 ? value : value.slice(0, 120);
410
+ }
411
+
412
+ export interface NormalizeMessageResult {
413
+ message?: TranscriptMessageSummary;
414
+ invalid: boolean;
415
+ unsupportedParts: number;
416
+ reasoningParts: number;
417
+ headers: number;
418
+ omitted: TranscriptOmission[];
419
+ /** Known native counters this message did not report. */
420
+ missingCounters?: string[];
421
+ /** Counter names reported by the provider that this mapping ignores. */
422
+ unmappedKeys?: string[];
423
+ }
424
+
425
+ const REASONING_TYPES = new Set([
426
+ "reasoning",
427
+ "thinking",
428
+ "thought",
429
+ "redacted-thinking",
430
+ "redacted_thinking",
431
+ ]);
432
+
433
+ const AGGREGATE_PART_TYPES = new Set(["step-start", "step-start-part", "step"]);
434
+
435
+ /**
436
+ * Normalize one native message. Parts without a stable id cannot be deduplicated
437
+ * or upserted, so the whole message is rejected as `invalid` rather than being
438
+ * emitted with a synthesized identity that a later page could double-count.
439
+ */
440
+ export function normalizeTranscriptMessage(
441
+ message: unknown,
442
+ options: TranscriptOptions = {},
443
+ ): NormalizeMessageResult {
444
+ const maxTextLength = options.maxTextLength ?? DEFAULT_MAX_TEXT;
445
+ const maxParts = options.maxParts ?? DEFAULT_MAX_PARTS;
446
+ const omitted: TranscriptOmission[] = [];
447
+ const result: NormalizeMessageResult = {
448
+ invalid: false,
449
+ unsupportedParts: 0,
450
+ reasoningParts: 0,
451
+ headers: 0,
452
+ omitted,
453
+ };
454
+ if (!isRecord(message)) {
455
+ result.invalid = true;
456
+ omitted.push({
457
+ kind: "message",
458
+ reason: "message payload was not an object",
459
+ });
460
+ return result;
461
+ }
462
+
463
+ const id = messageId(message);
464
+ if (!id) {
465
+ result.invalid = true;
466
+ omitted.push({ kind: "message", reason: "message had no stable id" });
467
+ return result;
468
+ }
469
+
470
+ const request = message.request;
471
+ if (
472
+ isRecord(message.headers) ||
473
+ (isRecord(request) && isRecord(request.headers))
474
+ ) {
475
+ result.headers += 1;
476
+ omitted.push({
477
+ kind: "header",
478
+ reason: "provider request headers are never ingested",
479
+ });
480
+ }
481
+
482
+ const role = messageRole(message)?.toLowerCase();
483
+ const normalizedRole: TranscriptMessageSummary["role"] =
484
+ role === "assistant" && isAssistantMessage(message)
485
+ ? "assistant"
486
+ : role === "user" && isUserMessage(message)
487
+ ? "user"
488
+ : "unknown";
489
+
490
+ const parts: TranscriptPart[] = [];
491
+ let partCount = 0;
492
+ const rawParts = Array.isArray(message.parts) ? message.parts : undefined;
493
+
494
+ if (rawParts) {
495
+ for (const raw of rawParts) {
496
+ if (!isRecord(raw)) {
497
+ result.unsupportedParts += 1;
498
+ continue;
499
+ }
500
+ partCount += 1;
501
+ if (partCount > maxParts) {
502
+ omitted.push({
503
+ kind: "data",
504
+ reason: `message ${id} exceeded ${maxParts} parts; the remainder was dropped`,
505
+ });
506
+ result.unsupportedParts += rawParts.length - (partCount - 1);
507
+ break;
508
+ }
509
+ const partIdentifier = partId(raw);
510
+ if (!partIdentifier) {
511
+ result.unsupportedParts += 1;
512
+ omitted.push({
513
+ kind: "data",
514
+ reason: `a part of message ${id} had no stable id`,
515
+ });
516
+ continue;
517
+ }
518
+ const type = asString(raw.type)?.toLowerCase();
519
+ if (type && REASONING_TYPES.has(type)) {
520
+ result.reasoningParts += 1;
521
+ parts.push({ kind: "reasoning", id: partIdentifier, redacted: true });
522
+ continue;
523
+ }
524
+ if (AGGREGATE_PART_TYPES.has(type ?? "")) {
525
+ continue;
526
+ }
527
+ if (type === "text") {
528
+ const text =
529
+ asString(raw.text) ??
530
+ asString(raw.content) ??
531
+ (typeof raw.text === "string" ? raw.text : undefined) ??
532
+ "";
533
+ const bounded = boundText(text, maxTextLength);
534
+ // An empty text keeps its true length 0 rather than looking like an omission.
535
+ const length =
536
+ asNumber(raw.length) ??
537
+ asNumber(raw.textLength) ??
538
+ Math.max(text.length, bounded.text.length);
539
+ parts.push({
540
+ kind: "text",
541
+ id: partIdentifier,
542
+ state: bounded.state,
543
+ text: bounded.text,
544
+ length,
545
+ });
546
+ continue;
547
+ }
548
+ if (
549
+ type === "tool" ||
550
+ type === "tool-call" ||
551
+ type === "tool-invocation"
552
+ ) {
553
+ parts.push(
554
+ normalizeToolPart(raw, partIdentifier, (present) => {
555
+ if (!present) return;
556
+ omitted.push({
557
+ kind: "output",
558
+ reason: `tool output or error of ${partIdentifier} was omitted`,
559
+ });
560
+ }),
561
+ );
562
+ omitted.push({
563
+ kind: "arguments",
564
+ reason: `tool input of ${partIdentifier} was omitted`,
565
+ });
566
+ continue;
567
+ }
568
+ result.unsupportedParts += 1;
569
+ omitted.push({
570
+ kind: "data",
571
+ reason: `part ${partIdentifier} of type ${type ?? "unknown"} is unsupported`,
572
+ });
573
+ parts.push({
574
+ kind: "unknown",
575
+ id: partIdentifier,
576
+ ...(type === undefined ? {} : { type: safeName(type) }),
577
+ state: "unsupported",
578
+ });
579
+ }
580
+ }
581
+
582
+ if (!rawParts) {
583
+ // Fall back to plain text extraction when the provider sends no parts list.
584
+ const text = messageText(message);
585
+ const bounded = boundText(text, maxTextLength);
586
+ parts.push({
587
+ kind: "text",
588
+ id: `${id}:text`,
589
+ state: bounded.state,
590
+ text: bounded.text,
591
+ length: text.length,
592
+ });
593
+ }
594
+
595
+ const usage = normalizeUsage(message.tokens ?? message.usage);
596
+
597
+ const time = isRecord(message.time) ? message.time : undefined;
598
+ const createdAt = messageCreatedAt(message);
599
+ const completedAt =
600
+ counter(time, "completed", "completedAt") ?? asNumber(message.completedAt);
601
+
602
+ const modelSource =
603
+ message.model ?? message.modelID ?? message.modelId ?? undefined;
604
+ const model =
605
+ modelSource === undefined
606
+ ? undefined
607
+ : tryParseModelRef(modelSource, "message.model");
608
+
609
+ const summary: TranscriptMessageSummary = {
610
+ id,
611
+ role: normalizedRole,
612
+ ...(asString(message.sessionID) !== undefined
613
+ ? { sessionID: asString(message.sessionID)! }
614
+ : asString(message.sessionId) !== undefined
615
+ ? { sessionID: asString(message.sessionId)! }
616
+ : {}),
617
+ ...(asString(message.parentID) !== undefined
618
+ ? { parentID: asString(message.parentID)! }
619
+ : asString(message.parentId) !== undefined
620
+ ? { parentID: asString(message.parentId)! }
621
+ : {}),
622
+ ...(createdAt === undefined ? {} : { createdAt }),
623
+ ...(completedAt === undefined ? {} : { completedAt }),
624
+ ...(model === undefined ? {} : { model }),
625
+ parts,
626
+ ...(usage.usage === undefined ? {} : { usage: usage.usage }),
627
+ };
628
+
629
+ const error = messageErrorText(message);
630
+ if (error) {
631
+ // Raw provider error text is untrusted and may carry secrets; default
632
+ // diagnostic mode never copies it, only records that it was omitted.
633
+ omitted.push({
634
+ kind: "data",
635
+ reason: `error text of message ${id} was omitted`,
636
+ });
637
+ }
638
+
639
+ result.message = summary;
640
+ result.missingCounters = usage.missingCounters;
641
+ result.unmappedKeys = usage.unmappedKeys;
642
+ return result;
643
+ }
644
+
645
+ export interface NormalizeMessagesResult {
646
+ summary: TranscriptSummary;
647
+ /** Message ids present more than once in the input (kept once, first wins). */
648
+ duplicateMessageIds: string[];
649
+ /** `messageID/partID` keys present more than once across the input. */
650
+ duplicatePartIds: string[];
651
+ }
652
+
653
+ /**
654
+ * Normalize a whole history. Duplicate message ids are collapsed (first
655
+ * occurrence wins) and duplicate part ids are collapsed inside the retained
656
+ * message, so usage is summed exactly once per attempt.
657
+ */
658
+ export function normalizeTranscript(
659
+ messages: readonly unknown[],
660
+ options: TranscriptOptions = {},
661
+ ): NormalizeMessagesResult {
662
+ const maxMessages = options.maxMessages ?? DEFAULT_MAX_MESSAGES;
663
+ const summary: TranscriptSummary = {
664
+ invalid: 0,
665
+ unsupportedParts: 0,
666
+ redacted: { reasoningParts: 0, headers: 0 },
667
+ messages: [],
668
+ totals: {
669
+ attempts: 0,
670
+ usage: {},
671
+ unmappedKeys: [],
672
+ missingCounters: [],
673
+ },
674
+ omitted: [],
675
+ usageComplete: true,
676
+ };
677
+
678
+ const seenMessages = new Set<string>();
679
+ const seenParts = new Set<string>();
680
+ const duplicateMessageIds = new Set<string>();
681
+ const duplicatePartIds = new Set<string>();
682
+ const unmapped = new Set<string>();
683
+ const omittedKeys = new Set<string>();
684
+
685
+ const addOmission = (omission: TranscriptOmission) => {
686
+ const key = `${omission.kind}:${omission.reason}`;
687
+ if (omittedKeys.has(key)) return;
688
+ omittedKeys.add(key);
689
+ summary.omitted.push(omission);
690
+ };
691
+
692
+ for (const raw of messages) {
693
+ const id = isRecord(raw) ? messageId(raw) : undefined;
694
+ if (id && seenMessages.has(id)) {
695
+ duplicateMessageIds.add(id);
696
+ continue;
697
+ }
698
+ const normalized = normalizeTranscriptMessage(raw, options);
699
+ summary.invalid += normalized.invalid ? 1 : 0;
700
+ summary.unsupportedParts += normalized.unsupportedParts;
701
+ summary.redacted.reasoningParts += normalized.reasoningParts;
702
+ summary.redacted.headers += normalized.headers;
703
+ for (const omission of normalized.omitted) addOmission(omission);
704
+ for (const key of normalized.unmappedKeys ?? []) unmapped.add(key);
705
+
706
+ const message = normalized.message;
707
+ if (!message) continue;
708
+ if (seenMessages.has(message.id)) {
709
+ duplicateMessageIds.add(message.id);
710
+ continue;
711
+ }
712
+ seenMessages.add(message.id);
713
+
714
+ // Drop duplicate parts inside the message, keeping the first occurrence.
715
+ const parts: TranscriptPart[] = [];
716
+ for (const part of message.parts) {
717
+ const key = `${message.id}/${part.id}`;
718
+ if (seenParts.has(key)) {
719
+ duplicatePartIds.add(key);
720
+ continue;
721
+ }
722
+ seenParts.add(key);
723
+ parts.push(part);
724
+ }
725
+ message.parts = parts;
726
+
727
+ if (summary.messages.length >= maxMessages) {
728
+ addOmission({
729
+ kind: "data",
730
+ reason: `history exceeded ${maxMessages} messages; older entries were dropped`,
731
+ });
732
+ continue;
733
+ }
734
+
735
+ summary.messages.push(message);
736
+ if (message.usage) {
737
+ summary.totals.attempts += 1;
738
+ // Each counter is summed independently and only when reported; a message
739
+ // that omits a counter never contributes a manufactured zero.
740
+ for (const key of [
741
+ "input",
742
+ "output",
743
+ "cachedInput",
744
+ "cacheWrite",
745
+ "reasoning",
746
+ ] as const) {
747
+ const value = message.usage[key];
748
+ if (value === undefined) {
749
+ if (
750
+ key !== "reasoning" &&
751
+ !summary.totals.missingCounters.includes(key)
752
+ ) {
753
+ summary.totals.missingCounters.push(key);
754
+ }
755
+ continue;
756
+ }
757
+ summary.totals.usage[key] = (summary.totals.usage[key] ?? 0) + value;
758
+ }
759
+ }
760
+ for (const key of normalized.missingCounters ?? []) {
761
+ if (!summary.totals.missingCounters.includes(key)) {
762
+ summary.totals.missingCounters.push(key);
763
+ }
764
+ }
765
+ if (!message.usage) summary.usageComplete = false;
766
+ }
767
+
768
+ summary.totals.unmappedKeys = [...unmapped];
769
+ return {
770
+ summary,
771
+ duplicateMessageIds: [...duplicateMessageIds],
772
+ duplicatePartIds: [...duplicatePartIds],
773
+ };
774
+ }
775
+
776
+ /** Parse a `next` link or opaque cursor from a page envelope. */
777
+ function cursorFrom(value: unknown): string | undefined {
778
+ if (typeof value === "string") {
779
+ const trimmed = value.trim();
780
+ if (!trimmed) return undefined;
781
+ if (!trimmed.includes("?")) return trimmed;
782
+ try {
783
+ return (
784
+ new URL(trimmed, "http://localhost").searchParams.get("cursor") ??
785
+ trimmed
786
+ );
787
+ } catch {
788
+ return undefined;
789
+ }
790
+ }
791
+ if (isRecord(value)) {
792
+ return (
793
+ asString(value.cursor) ??
794
+ asString(value.nextCursor) ??
795
+ asString(value.id) ??
796
+ cursorFrom(value.href ?? value.url ?? value.next)
797
+ );
798
+ }
799
+ return undefined;
800
+ }
801
+
802
+ const CURSOR_KEYS = ["nextCursor", "next_cursor", "next"];
803
+ const TOTAL_KEYS = ["total", "count", "totalCount", "total_count"];
804
+
805
+ /**
806
+ * Split a native message response into a page. Paging metadata is used only
807
+ * when the v2 endpoint actually returns it; a bare list or a `{ data: … }`
808
+ * wrapper yields `unsupported`/`unknown` and the host must not request paging.
809
+ */
810
+ export function parseTranscriptPage(
811
+ body: unknown,
812
+ request: TranscriptPageRequest,
813
+ capturedAt: number,
814
+ ): TranscriptPage {
815
+ const limit = clampLimit(request.limit, DEFAULT_PAGE_SIZE);
816
+ const base: TranscriptPageRequest = {
817
+ ...(request.cursor === undefined ? {} : { cursor: request.cursor }),
818
+ limit,
819
+ };
820
+ const entries = extractMessages(body);
821
+
822
+ if (Array.isArray(body)) {
823
+ return { ...base, status: "unsupported", entries, capturedAt };
824
+ }
825
+ if (!isRecord(body)) {
826
+ return { ...base, status: "unsupported", entries, capturedAt };
827
+ }
828
+
829
+ const unwrapped = unwrapData(body);
830
+ const envelope = isRecord(unwrapped) ? unwrapped : undefined;
831
+ const metadataSource =
832
+ envelope && envelope !== body
833
+ ? envelope
834
+ : isRecord(body.page)
835
+ ? body.page
836
+ : body;
837
+
838
+ let status: TranscriptPageStatus = "unknown";
839
+ let nextCursor: string | undefined;
840
+ let total: number | undefined;
841
+ if (metadataSource) {
842
+ for (const key of CURSOR_KEYS) {
843
+ if (!(key in metadataSource)) continue;
844
+ nextCursor = cursorFrom(metadataSource[key]);
845
+ status = "complete";
846
+ break;
847
+ }
848
+ if (status === "complete") {
849
+ for (const key of TOTAL_KEYS) {
850
+ const value = asNumber(metadataSource[key]);
851
+ if (value !== undefined && value >= 0) {
852
+ total = value;
853
+ break;
854
+ }
855
+ }
856
+ }
857
+ }
858
+
859
+ return {
860
+ ...base,
861
+ status,
862
+ entries,
863
+ ...(nextCursor === undefined ? {} : { nextCursor }),
864
+ ...(total === undefined ? {} : { total }),
865
+ capturedAt,
866
+ };
867
+ }
868
+
869
+ /**
870
+ * Cursor replay guard. Each absorbed page replaces previously seen messages, and
871
+ * a message id already absorbed never extends totals a second time.
872
+ */
873
+ export function createTranscriptAccumulator(
874
+ options: TranscriptOptions = {},
875
+ ): TranscriptAccumulator {
876
+ const byId = new Map<string, unknown>();
877
+ let sessionID: string | undefined;
878
+ let lastCapturedAt = 0;
879
+
880
+ const compute = (): TranscriptSnapshot => {
881
+ const normalized = normalizeTranscript([...byId.values()], options);
882
+ return {
883
+ ...normalized.summary,
884
+ ...(sessionID === undefined ? {} : { sessionID }),
885
+ seenMessageIds: [...byId.keys()],
886
+ };
887
+ };
888
+
889
+ return {
890
+ absorb(page) {
891
+ if (page.capturedAt > lastCapturedAt) lastCapturedAt = page.capturedAt;
892
+ for (const entry of page.entries) {
893
+ const id = messageId(entry);
894
+ if (!id) continue;
895
+ // Later pages carry the newer state of the same provider entity.
896
+ byId.set(id, entry);
897
+ if (sessionID === undefined) {
898
+ const sid = asString(entry.sessionID) ?? asString(entry.sessionId);
899
+ if (sid) sessionID = sid;
900
+ }
901
+ }
902
+ return compute();
903
+ },
904
+ snapshot() {
905
+ return compute();
906
+ },
907
+ };
908
+ }
909
+
910
+ /** The minimal adapter slice this module needs to load a page. */
911
+ export interface TranscriptLoaderAdapter {
912
+ inspectTranscript(
913
+ profile: Profile,
914
+ sessionID: string,
915
+ request?: TranscriptPageRequest & { signal?: AbortSignal },
916
+ ): Promise<TranscriptPage>;
917
+ }
918
+
919
+ /**
920
+ * Read one page through the adapter. Read-only: it never sends a prompt, and
921
+ * the page status tells the caller whether pagination is supported.
922
+ */
923
+ export async function loadTranscriptPage(
924
+ adapter: TranscriptLoaderAdapter,
925
+ profile: Profile,
926
+ sessionID: string,
927
+ request: TranscriptPageRequest & { signal?: AbortSignal } = {},
928
+ ): Promise<TranscriptPage> {
929
+ return adapter.inspectTranscript(profile, sessionID, request);
930
+ }