@linxiraos/zeta-compact 1.4.11 → 1.4.12

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,731 @@
1
+ /**
2
+ * Snapcompact compaction: archive conversation history as dense bitmap images.
3
+ *
4
+ * Instead of asking an LLM to summarize discarded history, the serialized
5
+ * conversation is rendered into PNG frames of pixel-font text that vision
6
+ * models read back directly, like an archivist at a snapcompact frame
7
+ * reader. Frames are `frameSize` wide; their height hugs the text rows
8
+ * actually printed, with a 64px floor for vision processors that reject
9
+ * smaller images.
10
+ *
11
+ * The frame shape is provider-aware. Original choices came from the SQuAD
12
+ * prose evals (`packages/snapcompact`, 200k-token monolithic runs); the
13
+ * spacing choices below come from the tool-result legibility bench
14
+ * (`research/toolbench.py`, real search/read/find output with structure QA),
15
+ * which exposed that the prose-tuned dense cells erase the line numbers and
16
+ * indentation that code/search output depends on:
17
+ *
18
+ * - **Anthropic** (`11on16-bw`): 8x13 glyphs on an 11px advance (extra
19
+ * letter-spacing), black ink. On the tool-result bench, tracking the
20
+ * readable cell beat plain `8on16-bw` (opus-4.8 f1 .806 vs .755) and far
21
+ * beat the prior dense `6x12-dim` (.351, which fell below the OCR ~16px/char
22
+ * floor and abstained). Opus 4.7+/Fable/Mythos ingest high-res natively
23
+ * (2576px edge, 4,784 visual-token cap), so those lines get 1932px frames:
24
+ * same bill, fewer frames. Older Claude lines downscale past 1568px.
25
+ * - **Google** (`8on22-bw` @2048): 8x13 glyphs on a 22px pitch (extra line
26
+ * spacing), black ink. Leading lifted gemini-3.5-flash to f1 .934 vs .807
27
+ * for `8on16-bw` and .287 for the prior `doc-8on16-sent-dim`. Gemini 3.x
28
+ * bills a fixed `media_resolution` budget per image (default 1,120 tokens)
29
+ * regardless of pixels, so the 2048px frame carries more chars at the same
30
+ * bill.
31
+ * - **OpenAI** (`8on22-bw`): same leading win (gpt-5.5/gpt-5.4-mini). Patch
32
+ * billing (32px × 1.2, 10k-patch budget at `detail: "original"`) is
33
+ * area-proportional, so resolution cannot improve chars/$ — 1568 stays.
34
+ * `detail: "high"` would downgrade (2,500-patch cap); `original` is sent.
35
+ * - **Unknown providers** default to `8on22-bw`. `providerImageBudget` caps
36
+ * per-request images at the deployment's catalog `image-count-budget`, so
37
+ * inline imaging cannot flood a request with attachments.
38
+ *
39
+ * The per-frame token estimate follows the reading model's catalog
40
+ * `image-tokenization` rule (its lineage, not the gateway), so Claude behind
41
+ * OpenRouter is billed as Claude and Opus 4.6 under its 1,568-token cap.
42
+ * Models without a lineage rule fall back to the catalog rule for their wire
43
+ * API; a reader with neither costs {@link FRAME_TOKEN_ESTIMATE} per frame.
44
+ *
45
+ * A host that downscales every image before the model reads it (catalog
46
+ * `image-max-edge`, e.g. Cursor) gets frames rendered at that edge instead,
47
+ * so glyphs reach the model at the size they were drawn.
48
+ *
49
+ * The whole pass is local and deterministic — no LLM call, no API key, no
50
+ * latency beyond rendering. Rasterization and PNG encoding happen in native
51
+ * code (`renderSnapcompactPng` in `crates/pi-natives/src/snapcompact.rs`).
52
+ * Frames persist in the compaction entry's `preserveData` and are
53
+ * re-attached to the compaction summary message on every context rebuild.
54
+ */
55
+ import type { Api, ImageContent, Message, Model, TextContent } from "@linxiraos/pi-ai";
56
+ import { type ImageSize, type ImageTokenization, type ImageTokenizationTarget } from "@linxiraos/pi-catalog/compat/image-tokenization";
57
+ /** One eval-validated frame shape: font, cell, ink, repetition, and size. */
58
+ export interface Shape {
59
+ /** Bundled font in the native renderer. */
60
+ font: "5x8" | "8x8" | "6x12" | "8x13" | "silver";
61
+ /** Target cell advance in pixels; differing from the font's natural cell
62
+ * renders via Lanczos stretch (anti-aliased RGB frame). */
63
+ cellWidth: number;
64
+ /** Target cell pitch in pixels. */
65
+ cellHeight: number;
66
+ /** `false` → glyphs drawn at natural size on the cell pitch (8on16);
67
+ * `true`/`undefined` → legacy auto Lanczos stretch when cell ≠ natural. */
68
+ stretch?: boolean;
69
+ /** Ink: `sent` cycles six hues at sentence boundaries; `bw` is black. */
70
+ variant: "sent" | "bw";
71
+ /** Print stopwords in dim ink (research `dim`/`sent-dim` variants). */
72
+ stopwordDim?: boolean;
73
+ /** 1/undefined = row-major grid; 2 = two word-wrapped newspaper columns
74
+ * (research `doc`). */
75
+ columns?: number;
76
+ /** Each text line is printed this many times; copies after the first sit
77
+ * on a pale highlight band (redundancy coding). */
78
+ lineRepeat: number;
79
+ /** Frame edge in pixels. */
80
+ frameSize: number;
81
+ /** Per-frame billed-token estimate for the shape's target provider. */
82
+ frameTokenEstimate: number;
83
+ /** `frameTokenEstimate` comes from a catalog rule measured against provider billing. */
84
+ frameTokensVerified?: boolean;
85
+ /** Resolution hint attached to frame images (OpenAI-only). */
86
+ imageDetail?: ImageContent["detail"];
87
+ }
88
+ /** Geometry half of a {@link Shape}: everything except provider billing. */
89
+ export type ShapeGeometry = Omit<Shape, "frameTokenEstimate" | "frameTokensVerified" | "imageDetail">;
90
+ /**
91
+ * Frame variants exercised by the SQuAD evals in `research/` that the native
92
+ * renderer reproduces faithfully, keyed by their research names. Font codes:
93
+ * `8x8u` unscii square cell, `8x8r` unscii with every line printed twice
94
+ * (redundancy coding), `6x6u` unscii Lanczos-squeezed to 6x6 (densest
95
+ * readable cell), `5x8` the X.org legacy font on its 2576px frame, `6x12`
96
+ * and `8x13` the X.org misc fonts, `8on16` 8x13 glyphs on an 8x16 cell pitch
97
+ * (no stretch, extra leading), `8on22` the same glyphs on a 22px pitch (more
98
+ * leading), `11on16` the same glyphs on an 11px advance (more tracking),
99
+ * `silver16` the embedded Silver TrueType font on a 16px grid for CJK and
100
+ * other non-Latin text, and `doc-` prefixed shapes a two-column word-wrapped
101
+ * newspaper layout. Ink: `sent` cycles six hues at sentence boundaries, `bw`
102
+ * is plain black, `-dim` suffix prints stopwords in gray.
103
+ */
104
+ export declare const SHAPE_VARIANTS: {
105
+ readonly "8x8r-bw": {
106
+ readonly font: "8x8";
107
+ readonly cellWidth: 8;
108
+ readonly cellHeight: 8;
109
+ readonly variant: "bw";
110
+ readonly lineRepeat: 2;
111
+ readonly frameSize: 1568;
112
+ };
113
+ readonly "8x8r-sent": {
114
+ readonly font: "8x8";
115
+ readonly cellWidth: 8;
116
+ readonly cellHeight: 8;
117
+ readonly variant: "sent";
118
+ readonly lineRepeat: 2;
119
+ readonly frameSize: 1568;
120
+ };
121
+ readonly "8x8u-bw": {
122
+ readonly font: "8x8";
123
+ readonly cellWidth: 8;
124
+ readonly cellHeight: 8;
125
+ readonly variant: "bw";
126
+ readonly lineRepeat: 1;
127
+ readonly frameSize: 1568;
128
+ };
129
+ readonly "8x8u-sent": {
130
+ readonly font: "8x8";
131
+ readonly cellWidth: 8;
132
+ readonly cellHeight: 8;
133
+ readonly variant: "sent";
134
+ readonly lineRepeat: 1;
135
+ readonly frameSize: 1568;
136
+ };
137
+ readonly "6x6u-bw": {
138
+ readonly font: "8x8";
139
+ readonly cellWidth: 6;
140
+ readonly cellHeight: 6;
141
+ readonly variant: "bw";
142
+ readonly lineRepeat: 1;
143
+ readonly frameSize: 1568;
144
+ };
145
+ readonly "6x6u-sent": {
146
+ readonly font: "8x8";
147
+ readonly cellWidth: 6;
148
+ readonly cellHeight: 6;
149
+ readonly variant: "sent";
150
+ readonly lineRepeat: 1;
151
+ readonly frameSize: 1568;
152
+ };
153
+ readonly "5x8-bw": {
154
+ readonly font: "5x8";
155
+ readonly cellWidth: 5;
156
+ readonly cellHeight: 8;
157
+ readonly variant: "bw";
158
+ readonly lineRepeat: 1;
159
+ readonly frameSize: 2576;
160
+ };
161
+ readonly "5x8-sent": {
162
+ readonly font: "5x8";
163
+ readonly cellWidth: 5;
164
+ readonly cellHeight: 8;
165
+ readonly variant: "sent";
166
+ readonly lineRepeat: 1;
167
+ readonly frameSize: 2576;
168
+ };
169
+ readonly "6x12-dim": {
170
+ readonly font: "6x12";
171
+ readonly cellWidth: 6;
172
+ readonly cellHeight: 12;
173
+ readonly variant: "bw";
174
+ readonly stopwordDim: true;
175
+ readonly lineRepeat: 1;
176
+ readonly frameSize: 1568;
177
+ };
178
+ readonly "8x13-bw": {
179
+ readonly font: "8x13";
180
+ readonly cellWidth: 8;
181
+ readonly cellHeight: 13;
182
+ readonly variant: "bw";
183
+ readonly lineRepeat: 1;
184
+ readonly frameSize: 1568;
185
+ };
186
+ readonly "8on16-bw": {
187
+ readonly font: "8x13";
188
+ readonly cellWidth: 8;
189
+ readonly cellHeight: 16;
190
+ readonly stretch: false;
191
+ readonly variant: "bw";
192
+ readonly lineRepeat: 1;
193
+ readonly frameSize: 1568;
194
+ };
195
+ readonly "8on22-bw": {
196
+ readonly font: "8x13";
197
+ readonly cellWidth: 8;
198
+ readonly cellHeight: 22;
199
+ readonly stretch: false;
200
+ readonly variant: "bw";
201
+ readonly lineRepeat: 1;
202
+ readonly frameSize: 1568;
203
+ };
204
+ readonly "11on16-bw": {
205
+ readonly font: "8x13";
206
+ readonly cellWidth: 11;
207
+ readonly cellHeight: 16;
208
+ readonly stretch: false;
209
+ readonly variant: "bw";
210
+ readonly lineRepeat: 1;
211
+ readonly frameSize: 1568;
212
+ };
213
+ readonly "silver16-bw": {
214
+ readonly font: "silver";
215
+ readonly cellWidth: 16;
216
+ readonly cellHeight: 16;
217
+ readonly variant: "bw";
218
+ readonly lineRepeat: 1;
219
+ readonly frameSize: 1568;
220
+ };
221
+ readonly "doc-8on16-bw": {
222
+ readonly font: "8x13";
223
+ readonly cellWidth: 8;
224
+ readonly cellHeight: 16;
225
+ readonly stretch: false;
226
+ readonly variant: "bw";
227
+ readonly columns: 2;
228
+ readonly lineRepeat: 1;
229
+ readonly frameSize: 1568;
230
+ };
231
+ readonly "doc-8on16-sent": {
232
+ readonly font: "8x13";
233
+ readonly cellWidth: 8;
234
+ readonly cellHeight: 16;
235
+ readonly stretch: false;
236
+ readonly variant: "sent";
237
+ readonly columns: 2;
238
+ readonly lineRepeat: 1;
239
+ readonly frameSize: 1568;
240
+ };
241
+ readonly "doc-8on16-sent-dim": {
242
+ readonly font: "8x13";
243
+ readonly cellWidth: 8;
244
+ readonly cellHeight: 16;
245
+ readonly stretch: false;
246
+ readonly variant: "sent";
247
+ readonly stopwordDim: true;
248
+ readonly columns: 2;
249
+ readonly lineRepeat: 1;
250
+ readonly frameSize: 1568;
251
+ };
252
+ };
253
+ /** Research name of one renderable frame variant. */
254
+ export type ShapeVariantName = keyof typeof SHAPE_VARIANTS;
255
+ /** All variant names, in declaration order (for settings enums). */
256
+ export declare const SHAPE_VARIANT_NAMES: readonly ShapeVariantName[];
257
+ /** Runtime guard for variant names loaded from config. */
258
+ export declare function isShapeVariantName(value: unknown): value is ShapeVariantName;
259
+ /**
260
+ * How a reader is billed per frame: its catalog `image-tokenization` rule
261
+ * (the model's lineage, else its wire API's fallback) and the `detail` hint
262
+ * snapcompact sends. OpenAI-family wires send `detail: "original"` (`high`
263
+ * caps the frame at 2,500 patches). Without a rule, every frame costs
264
+ * {@link FRAME_TOKEN_ESTIMATE}.
265
+ */
266
+ export interface FrameBilling {
267
+ rule?: ImageTokenization;
268
+ imageDetail?: ImageContent["detail"];
269
+ }
270
+ /** Resolve the frame billing of `target`. */
271
+ export declare function frameBilling(target: ShapeTarget | undefined): FrameBilling;
272
+ /** Identity of a frame price list: equal keys price every frame alike. */
273
+ export declare function frameBillingKey(billing: FrameBilling): string;
274
+ /** Billed-token estimate for one rendered frame of `size` under `billing`. */
275
+ export declare function frameTokens(billing: FrameBilling, size: ImageSize): number;
276
+ /**
277
+ * Per-frame tokens archive sizing charges `shape`: its own price when provider
278
+ * billing verified it, else at least {@link FRAME_TOKEN_ESTIMATE}.
279
+ */
280
+ export declare function plannedFrameTokens(shape: Shape): number;
281
+ /** Eval-validated shapes, keyed by the provider family they won on. */
282
+ export declare const SHAPES: {
283
+ /** `11on16-bw`: 8x13 glyphs on an 11px advance (extra tracking), black ink.
284
+ * Tool-result legibility bench (real search/read/find output, structure QA)
285
+ * on opus-4.8: f1 .806 vs .755 for plain `8on16-bw` and .351 for the prior
286
+ * `6x12-dim` default — letter-spacing the readable cell wins; the dense
287
+ * 6x12 was below the OCR ~16px/char floor and abstained. */
288
+ anthropic: Shape;
289
+ /** `8on22-bw`: 8x13 glyphs on a 22px pitch (extra leading), black ink.
290
+ * Tool-result legibility bench on gemini-3.5-flash: f1 .934 vs .807 for
291
+ * plain `8on16-bw` and .287 for the prior `doc-8on16-sent-dim`; the
292
+ * line-spacing reduces row crowding so line numbers stay legible. */
293
+ google: Shape;
294
+ /** `8on22-bw`: 8x13 glyphs on a 22px pitch (extra leading), black ink.
295
+ * Same line-spacing win for OpenAI; bench on gpt-5.5/gpt-5.4-mini showed
296
+ * leading lifts recall on the readable cell over plain `8on16-bw`. */
297
+ openai: Shape;
298
+ /** Original 5x8 X.org shape (pre-shape-table sessions rendered this). */
299
+ legacy: Shape;
300
+ };
301
+ /** Runtime guard for shape overrides loaded from config or preserve data. */
302
+ export declare function isShape(value: unknown): value is Shape;
303
+ /** One model line's ideal format: variant plus an optional frame-size
304
+ * override when the line reads larger frames at no extra cost. */
305
+ export interface IdealShape {
306
+ variant: ShapeVariantName;
307
+ frameSize?: number;
308
+ }
309
+ /** Eval-ideal format for a model id, or undefined when unmeasured. */
310
+ export declare function idealShapeVariant(modelId: string): IdealShape | undefined;
311
+ /** What will read the frames: the model id (shape and billing), the wire API
312
+ * (request hints, fallback billing), and optionally the host and parsed
313
+ * identity of a built model. */
314
+ export interface ShapeTarget {
315
+ api?: Api;
316
+ id?: string;
317
+ provider?: string;
318
+ identity?: ImageTokenizationTarget["identity"];
319
+ }
320
+ /**
321
+ * Pick the frame shape for a reader. An explicit `variant` (anything but
322
+ * `"auto"`) forces that geometry; otherwise the model id selects the
323
+ * eval-winning shape — and frame size — for its model line, falling back to
324
+ * the API family's winner when the model is unmeasured. Either way the frame
325
+ * is no wider than the host's catalog `image-max-edge`. Billing (token
326
+ * estimate, detail hint) is computed for the resolved frame size from the
327
+ * model's catalog image rule. Accepts a full pi-ai `Model` or any
328
+ * `{ api, id }` subset.
329
+ */
330
+ export declare function resolveShape(model?: ShapeTarget, variant?: ShapeVariantName | "auto"): Shape;
331
+ /**
332
+ * Pick the frame shape for `text`. Explicit variants remain forced. Auto first
333
+ * resolves the model/provider default, then selects the Silver CJK grid when
334
+ * the default font cannot safely render the text or wide CJK glyphs dominate
335
+ * the transcript and Silver can render it safely.
336
+ */
337
+ export declare function resolveShapeForText(text: string, model?: ShapeTarget, variant?: ShapeVariantName | "auto"): Shape;
338
+ /** Legacy frame edge in pixels (the 5x8 shape's eval-validated size). New
339
+ * shapes carry their own `frameSize`. */
340
+ export declare const FRAME_SIZE = 2576;
341
+ /** Default upper bound on archive frames carried per compaction. Sized to hold
342
+ * ~400k tokens of the high-res Anthropic frame Opus reads (1932px ≈ 5,000
343
+ * billed tokens each → 80 frames) while staying under the ~100-image
344
+ * per-request wire cap. Oldest frames are dropped first once the budget is
345
+ * exceeded (mirrors how iterative text summaries fade the oldest detail); a
346
+ * caller may pass a lower `maxFrames` upper limit, and per-model context
347
+ * fitting is handled by the caller's overflow guard. */
348
+ export declare const MAX_FRAMES_DEFAULT = 80;
349
+ /** High-quality (legible) frames rendered at each chronological edge of a
350
+ * foveated archive — the session head (oldest) and the slice just before the
351
+ * text region (newest) — with the denser low-quality tier filling the middle. */
352
+ export declare const HQ_EDGE_FRAMES = 3;
353
+ /** Conservative per-frame token estimate for sizing archives whose frame price
354
+ * is not billing-verified, and for frames of unknown size — the upper bound
355
+ * across shapes: high-res Claude frames hit the 4,784 visual-token cap, billed
356
+ * at +5% margin (ceil(4784 * 1.05)). Keeps the overflow guard from
357
+ * undercounting a high-res archive at the raised {@link MAX_FRAMES_DEFAULT}. */
358
+ export declare const FRAME_TOKEN_ESTIMATE = 5024;
359
+ /** Conservative upper bound for one persisted frame's base64 payload. The
360
+ * measured high-res Anthropic `8x13`/`11on16` PNG frames sit around 159 KB;
361
+ * 170 KB leaves margin for denser glyph pages without permitting multi-MB
362
+ * standing request bodies at large context windows. */
363
+ export declare const FRAME_DATA_BYTES_ESTIMATE = 170000;
364
+ /** Frame payload cap for a deployment without a catalog `inline-image-byte-budget`:
365
+ * an unmeasured backend can accept the HTTP body and still fail mid-stream
366
+ * with opaque 5xx errors. Keep this independent from visual-token budgeting:
367
+ * a 1M-token model can afford 70 images on paper, but not the resulting
368
+ * ~11 MB JSON payload on every turn. */
369
+ export declare const DEFAULT_FRAME_DATA_BYTES_BUDGET = 3000000;
370
+ /** Base64 image bytes the archive frames riding every request to `model` may
371
+ * carry: half the deployment's inline-image byte budget, else
372
+ * {@link DEFAULT_FRAME_DATA_BYTES_BUDGET}. Frames are the oldest images in the
373
+ * request, so the send-time byte clamp evicts them first; the other half stays
374
+ * free for live screenshots. */
375
+ export declare function frameDataBytesBudget(model: Model | undefined): number;
376
+ /** Frame-count cap a `budget` of base64 bytes implies for frames rendered by
377
+ * `shape`. {@link AREA_PRICED_VARIANTS} below 1932px are charged
378
+ * {@link FRAME_DATA_BYTES_ESTIMATE} scaled by pixel area; every other shape
379
+ * pays the full estimate. */
380
+ export declare function maxFramesForDataBudget(shape: ShapeGeometry, budget: number): number;
381
+ /** Base64 byte length for persisted snapcompact frames. */
382
+ export declare function frameDataBytes(frames: readonly Pick<Frame, "data">[]): number;
383
+ /** Safe floor for a deployment whose catalog rules set no `image-count-budget`
384
+ * (strictest mainstream measured: Groq ~5). */
385
+ export declare const DEFAULT_PROVIDER_IMAGE_BUDGET = 5;
386
+ /** Most images one request to `model`'s deployment may carry, archive,
387
+ * system-prompt and tool-result imaging combined. */
388
+ export declare function providerImageBudget(model: Model | undefined): number;
389
+ /** Archive frame cap for `model`: its image budget, never above {@link MAX_FRAMES_DEFAULT}. */
390
+ export declare function providerFrameBudget(model: Model | undefined): number;
391
+ /** Whether `model` may get a fresh `read` result as frames (catalog `snapcompact-image-reads`, opt-in). */
392
+ export declare function readerImagesReadResults(model: Model): boolean;
393
+ /** Key under `CompactionEntry.preserveData` holding the frame archive. */
394
+ export declare const PRESERVE_KEY = "snapcompact";
395
+ /** One developed snapcompact frame: a base64 PNG plus its reading geometry. */
396
+ export interface Frame {
397
+ /** Base64-encoded PNG. */
398
+ data: string;
399
+ mimeType: string;
400
+ /** Characters per row in the frame grid (per-column width on doc frames). */
401
+ cols: number;
402
+ /** Text rows in the frame grid (unique lines, not repeated copies). */
403
+ rows: number;
404
+ /** Characters actually printed onto this frame. */
405
+ chars: number;
406
+ /** Shape metadata (absent on legacy frames, which are 5x8 `sent`). */
407
+ font?: Shape["font"];
408
+ variant?: Shape["variant"];
409
+ lineRepeat?: number;
410
+ /** 2 on two-column doc frames; absent on row-major grid frames. */
411
+ columns?: number;
412
+ /** True when stopwords were printed in dim ink. */
413
+ stopwordDim?: boolean;
414
+ /** Resolution hint forwarded to the provider when re-attaching. */
415
+ detail?: ImageContent["detail"];
416
+ }
417
+ /** Frame archive persisted under `preserveData[PRESERVE_KEY]`. */
418
+ export interface Archive {
419
+ /** Rendered frames ordered oldest to newest, re-derived from {@link text}
420
+ * each compaction with foveated quality tiers (HQ/LQ/HQ inside the imaged
421
+ * middle). May be empty when the whole archive fits in text. */
422
+ frames: Frame[];
423
+ /** Characters currently readable across all frames plus the text regions. */
424
+ totalChars: number;
425
+ /** Characters dropped so far to respect the archive budget. */
426
+ truncatedChars: number;
427
+ /** Full kept archive source (oldest to newest, normalized, bounded to the
428
+ * rendered budget) — the single source re-rendered each compaction. */
429
+ text?: string;
430
+ /** Oldest text region kept verbatim around the imaged middle. */
431
+ textHead?: string;
432
+ /** Newest text region kept verbatim around the imaged middle. */
433
+ textTail?: string;
434
+ /** The same history re-rendered for a reader that excludes assistant
435
+ * reasoning ({@link SerializeOptions.includeThinking} `false`), when this
436
+ * archive carries it. Read through {@link viewWithoutThinking}. */
437
+ withoutThinking?: ArchiveView;
438
+ }
439
+ /** What a reader gets for one compaction: the summary text and the archive it introduces. */
440
+ export interface ArchiveView {
441
+ summary: string;
442
+ archive: Archive;
443
+ }
444
+ export interface Geometry {
445
+ /** Characters per row (per-column line width when `columns === 2`). */
446
+ cols: number;
447
+ rows: number;
448
+ /** Characters that fit one frame (nominal upper bound on doc shapes,
449
+ * where real consumption is wrap-dependent). */
450
+ capacity: number;
451
+ }
452
+ export interface Options<TMessage = Message> extends SerializeOptions {
453
+ /** App-level message transformer (same contract as agent-core's `SummaryOptions.convertToLlm`). */
454
+ convertToLlm?: ConvertToLlm<TMessage>;
455
+ /** Model whose provider API and id select the frame shape. */
456
+ model?: ShapeTarget;
457
+ /** Explicit shape override; wins over `model`. */
458
+ shape?: Shape;
459
+ /** Frame edge in pixels. Defaults to the shape's `frameSize`. */
460
+ frameSize?: number;
461
+ /** Upper limit on archive frames; clamped to (and defaulting to) {@link MAX_FRAMES_DEFAULT}. */
462
+ maxFrames?: number;
463
+ }
464
+ /** Result of rendering one frame. */
465
+ export interface RenderedFrame {
466
+ /** Base64-encoded PNG, as returned by the native renderer. */
467
+ data: string;
468
+ cols: number;
469
+ rows: number;
470
+ /** Characters printed (ink toggles excluded; input may be shorter than capacity). */
471
+ chars: number;
472
+ }
473
+ export interface FileOperations {
474
+ read: Set<string>;
475
+ written: Set<string>;
476
+ edited: Set<string>;
477
+ }
478
+ export interface CompactionDetails {
479
+ readFiles: string[];
480
+ modifiedFiles: string[];
481
+ }
482
+ export interface CompactionPreparation<TMessage = Message> {
483
+ /** UUID of first entry to keep. */
484
+ firstKeptEntryId: string;
485
+ /** Messages that will be archived and discarded. */
486
+ messagesToSummarize: TMessage[];
487
+ /** Messages that will be archived as the split-turn prefix, if any. */
488
+ turnPrefixMessages: TMessage[];
489
+ tokensBefore: number;
490
+ /** Summary from previous compaction, for continuity when no prior snapcompact archive exists. */
491
+ previousSummary?: string;
492
+ /** Preserved opaque compaction payload from the previous compaction, if any. */
493
+ previousPreserveData?: Record<string, unknown>;
494
+ /** File operations extracted by the host agent. */
495
+ fileOps: FileOperations;
496
+ }
497
+ export interface CompactionResult<T = CompactionDetails> {
498
+ summary: string;
499
+ shortSummary?: string;
500
+ firstKeptEntryId: string;
501
+ tokensBefore: number;
502
+ details?: T;
503
+ preserveData?: Record<string, unknown>;
504
+ }
505
+ export type ConvertToLlm<TMessage = Message> = (messages: TMessage[]) => Message[];
506
+ export declare function createFileOps(): FileOperations;
507
+ export declare function isUrlSchemePath(path: string): boolean;
508
+ export declare function computeFileLists(fileOps: FileOperations): CompactionDetails;
509
+ export declare function upsertFileOperations(summary: string, readFiles: string[], modifiedFiles: string[], readSet?: ReadonlySet<string>): string;
510
+ /** Default per-tool-result character cap in serialized history. */
511
+ export declare const TOOL_RESULT_MAX_CHARS = 2000;
512
+ /** Default per-argument-value character cap inside serialized tool calls
513
+ * (write/edit bodies otherwise dump whole files into the archive). */
514
+ export declare const TOOL_ARG_MAX_CHARS = 500;
515
+ /** Default character cap across one tool call's full serialized argument list. */
516
+ export declare const TOOL_CALL_MAX_CHARS = 2000;
517
+ /** Default fraction of a truncation budget spent on the head; the remainder
518
+ * keeps the tail, where command errors and test failures usually land. */
519
+ export declare const TRUNCATE_HEAD_RATIO = 0.6;
520
+ /** Zero-width ink toggles understood by the native renderer (shift-out/in):
521
+ * text between them prints in dim gray ink without occupying a cell. */
522
+ export declare const DIM_ON = "\u000E";
523
+ export declare const DIM_OFF = "\u000F";
524
+ /** Character budgets applied while serializing discarded history for frame
525
+ * rendering. Pass `Infinity` to disable an individual cap. */
526
+ export interface SerializeOptions {
527
+ /** Per-tool-result cap. Defaults to {@link TOOL_RESULT_MAX_CHARS}. */
528
+ toolResultMaxChars?: number;
529
+ /** Per-argument-value cap. Defaults to {@link TOOL_ARG_MAX_CHARS}. */
530
+ toolArgMaxChars?: number;
531
+ /** Whole-argument-list cap per call. Defaults to {@link TOOL_CALL_MAX_CHARS}. */
532
+ toolCallMaxChars?: number;
533
+ /** Head share of each budget, clamped to [0, 1]. Defaults to {@link TRUNCATE_HEAD_RATIO}. */
534
+ truncateHeadRatio?: number;
535
+ /** Print tool-result text in dim gray ink so archived conversation reads
536
+ * louder than archived tool noise. Defaults to `true`. */
537
+ dimToolResults?: boolean;
538
+ /** Serialize assistant reasoning as `¶think:` sections. Defaults to `true`.
539
+ * Callers archiving for a reader whose classifier refuses quoted reasoning
540
+ * ({@link readerIncludesThinking} `false`) set this `false`:
541
+ * the archive frames are replayed as text into every later request, and
542
+ * reasoning rendered back to Claude trips its `reasoning_extraction`
543
+ * classifier (issue #6093). */
544
+ includeThinking?: boolean;
545
+ }
546
+ export declare function serializeConversation(messages: Message[], options?: SerializeOptions): string;
547
+ /** Printed in place of newline runs: the native renderer fills this cell
548
+ * entirely with pitch-black ink, so line structure survives whitespace
549
+ * collapsing at a one-cell cost. */
550
+ export declare const NEWLINE_GLYPH = "\u2588";
551
+ export interface NormalizeOptions {
552
+ /** Shape whose font is tried before the embedded Silver fallback. */
553
+ shape?: Pick<Shape, "font">;
554
+ /** Native font name when a full shape is not available. */
555
+ font?: Shape["font"];
556
+ }
557
+ /**
558
+ * Prepare text for printing: strip ANSI escape sequences, collapse horizontal
559
+ * whitespace runs, fold unsupported symbols (including box drawing to ASCII),
560
+ * preserve Unicode glyphs that either the selected font or embedded Silver
561
+ * fallback can render, and drop decorative emoji instead of printing `?`.
562
+ */
563
+ export declare function normalize(text: string, options?: NormalizeOptions): string;
564
+ /**
565
+ * Scan text with the same font-aware path as {@link normalize}; unsafe means
566
+ * more than 5% of graphic characters would hit the `?` fallback.
567
+ */
568
+ export declare function scanRenderability(text: string, options?: NormalizeOptions): {
569
+ isSafe: boolean;
570
+ unrenderableRatio: number;
571
+ };
572
+ /**
573
+ * Wrap each maximal alphabetic run that is a stopword in {@link DIM_ON} /
574
+ * {@link DIM_OFF} so it prints in dim gray ink. Spans that are already dim
575
+ * (e.g. archived tool output) pass through untouched — wrapping there would
576
+ * terminate the enclosing dim span early. Markers are zero-width, so the
577
+ * visible glyph count is unchanged.
578
+ */
579
+ export declare function dimStopwords(text: string): string;
580
+ /**
581
+ * Greedy word-wrap, no mid-word breaks (hard split only for width+ words) —
582
+ * ported verbatim from `research/exp14_bestgpt.py` `wrap()`. Zero-width dim
583
+ * markers count toward word length here; serialized history places them at
584
+ * word boundaries, so the drift is at most one cell per affected line.
585
+ */
586
+ export declare function wrap(text: string, width: number, wideCells?: boolean): string[];
587
+ export declare function geometry(shape: Shape, size?: number): Geometry;
588
+ /** Render one snapcompact frame from already-normalized text. Doc shapes
589
+ * (`columns === 2`) expect one page of `\n`-joined pre-wrapped lines. */
590
+ export declare function render(text: string, shape: Shape, size?: number): Promise<RenderedFrame>;
591
+ /** Options for {@link renderMany} and {@link frames}. */
592
+ export interface RenderManyOptions {
593
+ /** Explicit shape; wins over `model`. */
594
+ shape?: Shape;
595
+ /** Model whose provider API and id select the frame shape. */
596
+ model?: ShapeTarget;
597
+ /** Frame edge in px; defaults to the shape's `frameSize`. */
598
+ frameSize?: number;
599
+ /** Hard cap on frames produced; omit for unbounded (caller decides usage). */
600
+ maxFrames?: number;
601
+ }
602
+ /**
603
+ * Render arbitrary text into snapcompact PNG frames as LLM image blocks
604
+ * (first page first). Empty/whitespace-only input yields no frames.
605
+ */
606
+ export declare function renderMany(text: string, options?: RenderManyOptions): Promise<ImageContent[]>;
607
+ /** Frames needed to hold `text` at the given shape/size, without rendering.
608
+ * For doc shapes this wraps the text once and counts pages of `2 * rows`
609
+ * lines; for grid shapes it divides by the frame capacity. */
610
+ export declare function frames(text: string, options?: Pick<RenderManyOptions, "shape" | "model" | "frameSize">): number;
611
+ /** Validate and extract a persisted frame archive from `preserveData`, with its
612
+ * {@link Archive.withoutThinking} variant when that is valid too. */
613
+ export declare function getPreservedArchive(preserveData: Record<string, unknown> | undefined): Archive | undefined;
614
+ /** Drop the persisted frame archive ({@link PRESERVE_KEY}) from `preserveData`,
615
+ * returning the remaining state — or `undefined` when nothing else remains, so
616
+ * an empty `{}` is never persisted. Callers strip the archive once its frames
617
+ * have been migrated into a new compaction's text, preventing the stale frames
618
+ * from leaking back into the rebuilt context. */
619
+ export declare function stripPreservedArchive(preserveData: Record<string, unknown> | undefined): Record<string, unknown> | undefined;
620
+ /** Extract persisted archive source text as plain text for LLM summarization. */
621
+ export declare function archiveSourceText(archive: Archive): string | undefined;
622
+ /** Build the text used to choose and preflight a font-aware snapcompact shape. */
623
+ export declare function renderabilityProbeText(serialized: string, previousPreserveData?: Record<string, unknown>, previousSummary?: string): string;
624
+ /** A frame payload that can be priced before it is materialized. */
625
+ export interface LazyFrameData {
626
+ readonly bytes: number;
627
+ read(): string;
628
+ }
629
+ /** Options for reconstructing a persisted snapcompact archive into prompt blocks. */
630
+ export interface HistoryBlockOptions {
631
+ /** Hard cap on image base64 bytes attached to one rebuilt provider request. */
632
+ maxFrameDataBytes?: number;
633
+ /**
634
+ * Price and resolve a frame payload. Called in newest-first budget order.
635
+ * Returning `undefined` drops a missing payload.
636
+ */
637
+ resolveFrameData?: (data: string) => LazyFrameData | undefined;
638
+ }
639
+ /** Convert archive frames into LLM image blocks (oldest first). */
640
+ export declare function images(archive: Archive): ImageContent[];
641
+ /** Ordered archive blocks for a compaction summary message, oldest to newest:
642
+ * the oldest text region, the imaged middle, then the newest text region.
643
+ * Runtime-only; reconstructed from {@link Archive} on each context rebuild
644
+ * instead of persisted on the session entry. */
645
+ export declare function historyBlocks(archive: Archive, options?: HistoryBlockOptions): (TextContent | ImageContent)[];
646
+ /**
647
+ * Re-applies a smaller frame byte budget to blocks {@link historyBlocks} already built: keeps the newest frames that
648
+ * fit, priced as {@link historyBlocks} prices them, and replaces each run of dropped frames with one omission notice.
649
+ * Returns `blocks` itself when every frame fits.
650
+ */
651
+ export declare function capFrameDataBytes(blocks: (TextContent | ImageContent)[], maxFrameDataBytes: number): (TextContent | ImageContent)[];
652
+ /**
653
+ * Whether an archive read by `model` may carry assistant reasoning. The archive
654
+ * replays as text into every later request, and a reader whose classifier
655
+ * refuses reasoning quoted back into its input (the `classifier-cot-extraction`
656
+ * catalog axis, set for Claude: `reasoning_extraction`, issue #6093) gets
657
+ * `¶think:` sections and their legend left out.
658
+ */
659
+ export declare function readerIncludesThinking(model: Model): boolean;
660
+ /** Whether a snapcompact summary declares `¶think:` reasoning scopes: true for
661
+ * archives rendered with {@link SerializeOptions.includeThinking}, and for
662
+ * summaries written before that legend was gated on it. */
663
+ export declare function summaryIncludesThinking(summary: string): boolean;
664
+ /**
665
+ * Whether a compaction whose summary is `summary` and archive `archive` may
666
+ * replay assistant reasoning: its summary declares `¶think:` scopes, or its
667
+ * kept text carries a `¶think:` section. A summary an extension or custom
668
+ * template wrote need not carry the legend while its archive's source does.
669
+ */
670
+ export declare function archiveIncludesThinking(summary: string, archive: Archive): boolean;
671
+ /** `text` (a summary or archive source, raw or normalized) without its
672
+ * `¶think:` sections, and with the reasoning scope dropped from any legend. */
673
+ export declare function textWithoutThinking(text: string): string;
674
+ /**
675
+ * What a reader that excludes assistant reasoning reads for a compaction
676
+ * whose summary is `summary` and archive `archive`: the archive's
677
+ * {@link Archive.withoutThinking} variant when it carries one, the original
678
+ * when it carries no reasoning ({@link archiveIncludesThinking}), else a
679
+ * fail-closed text-only form.
680
+ * That form keeps no frames (pixels cannot be scrubbed), takes its text edges
681
+ * from the source after every `¶think:` section is removed (so a section
682
+ * crossing an edge cannot leak), counts the dropped middle as truncated, and
683
+ * re-renders the summary without the reasoning legend; `details` restores its
684
+ * file list. A summary the template did not write keeps its own words
685
+ * ({@link viewSummary}).
686
+ */
687
+ export declare function viewWithoutThinking(summary: string, archive: Archive, details?: CompactionDetails): ArchiveView;
688
+ /**
689
+ * The summary a reader reads with an archive view: `rendered`, the template's
690
+ * summary for that view, when `summary` came from the template; otherwise
691
+ * `summary`'s own words (say, an extension's), without reasoning when
692
+ * `dropThinking`, followed by `rendered`, so the facts it alone holds survive
693
+ * the swap and the reader still gets the guide to the view's text.
694
+ */
695
+ export declare function viewSummary(summary: string, rendered: string, dropThinking: boolean): string;
696
+ /** Options for {@link viewWithoutFrames}. */
697
+ export interface ViewWithoutFramesOptions {
698
+ /** `false` for a reader that excludes assistant reasoning ({@link readerIncludesThinking}). */
699
+ includeThinking?: boolean;
700
+ /** Most archive characters the reader takes; the middle past it is dropped, both ends kept. */
701
+ maxChars?: number;
702
+ }
703
+ /**
704
+ * What a reader without image input reads for a compaction whose summary is
705
+ * `summary` and archive `archive`: the archive's kept source
706
+ * ({@link Archive.text}) as plain text in place of its frames, and the summary
707
+ * re-rendered without the frame legend, its file list kept (one the template
708
+ * did not write keeps its own words, {@link viewSummary}). With
709
+ * `includeThinking: false` the text and legend also leave out reasoning, as
710
+ * {@link viewWithoutThinking} does, without rendering frames this reader
711
+ * cannot see; past `maxChars` the middle of the text is dropped. An archive
712
+ * persisted without that source keeps its text edges and counts the imaged
713
+ * middle as dropped; a reader without reasoning also skips the tail's lines
714
+ * before its first scope label, whatever the summary declares. An archive with
715
+ * no frames, no reasoning to drop and no text past `maxChars` is returned as is.
716
+ */
717
+ export declare function viewWithoutFrames(summary: string, archive: Archive, options?: ViewWithoutFramesOptions): ArchiveView;
718
+ /**
719
+ * Run a snapcompact compaction over prepared messages. Fully local: serializes
720
+ * the discarded history, appends it to the accumulated archive source text, and
721
+ * re-renders that source into an ordered history layout: plain text at the
722
+ * oldest edge, imaged middle, then plain text at the newest edge. The imaged
723
+ * middle itself foveates (HQ/LQ/HQ) when it grows large.
724
+ *
725
+ * The full kept source persists on the archive (`text`) so each later compaction
726
+ * unfolds and re-renders it coherently alongside the newly archived history.
727
+ *
728
+ * If the previous compaction was text-based, its summary is printed at the head
729
+ * of the archive as `[Summary of earlier history]` so no continuity is lost.
730
+ */
731
+ export declare function compact<TMessage = Message>(preparation: CompactionPreparation<TMessage>, options?: Options<TMessage>): Promise<CompactionResult>;