@sriinnu/fiche 0.0.0-stage → 0.19.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 (196) hide show
  1. package/CHANGELOG.md +134 -0
  2. package/LICENSE +22 -0
  3. package/NOTICE +13 -0
  4. package/PRIVACY.md +41 -0
  5. package/README.md +288 -2
  6. package/SECURITY.md +53 -0
  7. package/assets/JETBRAINS_MONO_LICENSE.txt +89 -0
  8. package/assets/SPLEEN_LICENSE.txt +24 -0
  9. package/assets/UNIFONT_LICENSE.txt +476 -0
  10. package/assets/fiche-logo-dark.svg +61 -0
  11. package/assets/fiche-logo-light.svg +61 -0
  12. package/assets/fiche-logo.svg +71 -0
  13. package/assets/fiche-mark.svg +48 -0
  14. package/bin/cli.js +7 -0
  15. package/bin/mcp.js +8 -0
  16. package/dist/calibrate.d.ts +30 -0
  17. package/dist/calibrate.js +588 -0
  18. package/dist/core/anthropic-vision.d.ts +28 -0
  19. package/dist/core/anthropic-vision.js +34 -0
  20. package/dist/core/applicability.d.ts +63 -0
  21. package/dist/core/applicability.js +151 -0
  22. package/dist/core/atlas-gray-jbmono10.d.ts +26 -0
  23. package/dist/core/atlas-gray-jbmono10.js +64 -0
  24. package/dist/core/atlas-gray-jbmono12.d.ts +26 -0
  25. package/dist/core/atlas-gray-jbmono12.js +64 -0
  26. package/dist/core/atlas-gray-jbmono14.d.ts +26 -0
  27. package/dist/core/atlas-gray-jbmono14.js +64 -0
  28. package/dist/core/atlas-gray.d.ts +26 -0
  29. package/dist/core/atlas-gray.js +64 -0
  30. package/dist/core/atlas-jbmono10.d.ts +34 -0
  31. package/dist/core/atlas-jbmono10.js +71 -0
  32. package/dist/core/atlas-jbmono12.d.ts +34 -0
  33. package/dist/core/atlas-jbmono12.js +71 -0
  34. package/dist/core/atlas-jbmono14.d.ts +34 -0
  35. package/dist/core/atlas-jbmono14.js +71 -0
  36. package/dist/core/atlas.d.ts +34 -0
  37. package/dist/core/atlas.js +71 -0
  38. package/dist/core/baseline.d.ts +121 -0
  39. package/dist/core/baseline.js +200 -0
  40. package/dist/core/calibration.d.ts +86 -0
  41. package/dist/core/calibration.js +547 -0
  42. package/dist/core/casi-delta.d.ts +63 -0
  43. package/dist/core/casi-delta.js +1271 -0
  44. package/dist/core/claude-model-profiles.d.ts +53 -0
  45. package/dist/core/claude-model-profiles.js +160 -0
  46. package/dist/core/client-tool-round.d.ts +31 -0
  47. package/dist/core/client-tool-round.js +58 -0
  48. package/dist/core/codex-cache.d.ts +20 -0
  49. package/dist/core/codex-cache.js +59 -0
  50. package/dist/core/context-mmu.d.ts +350 -0
  51. package/dist/core/context-mmu.js +3028 -0
  52. package/dist/core/cpt-fit.d.ts +70 -0
  53. package/dist/core/cpt-fit.js +197 -0
  54. package/dist/core/env.d.ts +8 -0
  55. package/dist/core/env.js +15 -0
  56. package/dist/core/export.d.ts +127 -0
  57. package/dist/core/export.js +385 -0
  58. package/dist/core/factsheet.d.ts +77 -0
  59. package/dist/core/factsheet.js +494 -0
  60. package/dist/core/gemini-model-profiles.d.ts +20 -0
  61. package/dist/core/gemini-model-profiles.js +134 -0
  62. package/dist/core/google.d.ts +76 -0
  63. package/dist/core/google.js +1380 -0
  64. package/dist/core/gpt-model-profiles.d.ts +218 -0
  65. package/dist/core/gpt-model-profiles.js +570 -0
  66. package/dist/core/gpt-tokens.d.ts +14 -0
  67. package/dist/core/gpt-tokens.js +165 -0
  68. package/dist/core/history.d.ts +197 -0
  69. package/dist/core/history.js +1003 -0
  70. package/dist/core/index.d.ts +16 -0
  71. package/dist/core/index.js +16 -0
  72. package/dist/core/library.d.ts +80 -0
  73. package/dist/core/library.js +131 -0
  74. package/dist/core/measurement.d.ts +34 -0
  75. package/dist/core/measurement.js +280 -0
  76. package/dist/core/messages-chat-bridge.d.ts +23 -0
  77. package/dist/core/messages-chat-bridge.js +747 -0
  78. package/dist/core/messages-responses-bridge.d.ts +11 -0
  79. package/dist/core/messages-responses-bridge.js +893 -0
  80. package/dist/core/openai-history.d.ts +184 -0
  81. package/dist/core/openai-history.js +1279 -0
  82. package/dist/core/openai-savings.d.ts +57 -0
  83. package/dist/core/openai-savings.js +116 -0
  84. package/dist/core/openai.d.ts +68 -0
  85. package/dist/core/openai.js +2523 -0
  86. package/dist/core/pin.d.ts +199 -0
  87. package/dist/core/pin.js +1353 -0
  88. package/dist/core/png.d.ts +14 -0
  89. package/dist/core/png.js +188 -0
  90. package/dist/core/prefix-tape.d.ts +102 -0
  91. package/dist/core/prefix-tape.js +315 -0
  92. package/dist/core/price-id.d.ts +10 -0
  93. package/dist/core/price-id.js +26 -0
  94. package/dist/core/prices.generated.d.ts +36 -0
  95. package/dist/core/prices.generated.js +369 -0
  96. package/dist/core/pricing.d.ts +134 -0
  97. package/dist/core/pricing.js +335 -0
  98. package/dist/core/profile-base.d.ts +30 -0
  99. package/dist/core/profile-base.js +67 -0
  100. package/dist/core/provider-router.d.ts +51 -0
  101. package/dist/core/provider-router.js +121 -0
  102. package/dist/core/proxy.d.ts +252 -0
  103. package/dist/core/proxy.js +2929 -0
  104. package/dist/core/reader-tier.d.ts +24 -0
  105. package/dist/core/reader-tier.js +118 -0
  106. package/dist/core/render.d.ts +280 -0
  107. package/dist/core/render.js +1302 -0
  108. package/dist/core/request-guard.d.ts +31 -0
  109. package/dist/core/request-guard.js +126 -0
  110. package/dist/core/request-transform.d.ts +43 -0
  111. package/dist/core/request-transform.js +173 -0
  112. package/dist/core/schema-compiler.d.ts +64 -0
  113. package/dist/core/schema-compiler.js +1696 -0
  114. package/dist/core/schema-strip.d.ts +29 -0
  115. package/dist/core/schema-strip.js +173 -0
  116. package/dist/core/session-state.d.ts +219 -0
  117. package/dist/core/session-state.js +929 -0
  118. package/dist/core/stage-plugins.d.ts +45 -0
  119. package/dist/core/stage-plugins.js +205 -0
  120. package/dist/core/text-history.d.ts +74 -0
  121. package/dist/core/text-history.js +612 -0
  122. package/dist/core/text-hygiene.d.ts +160 -0
  123. package/dist/core/text-hygiene.js +2259 -0
  124. package/dist/core/toon.d.ts +29 -0
  125. package/dist/core/toon.js +425 -0
  126. package/dist/core/tracker.d.ts +223 -0
  127. package/dist/core/tracker.js +290 -0
  128. package/dist/core/transform.d.ts +589 -0
  129. package/dist/core/transform.js +3153 -0
  130. package/dist/core/types.d.ts +87 -0
  131. package/dist/core/types.js +8 -0
  132. package/dist/core/upstream-hosts.d.ts +127 -0
  133. package/dist/core/upstream-hosts.js +398 -0
  134. package/dist/core/vision-cost.d.ts +63 -0
  135. package/dist/core/vision-cost.js +137 -0
  136. package/dist/dashboard/fragments.d.ts +87 -0
  137. package/dist/dashboard/fragments.js +1515 -0
  138. package/dist/dashboard/types.d.ts +217 -0
  139. package/dist/dashboard/types.js +3 -0
  140. package/dist/dashboard/vendor.d.ts +3 -0
  141. package/dist/dashboard/vendor.js +6 -0
  142. package/dist/dashboard.d.ts +372 -0
  143. package/dist/dashboard.js +2731 -0
  144. package/dist/export-collect.d.ts +36 -0
  145. package/dist/export-collect.js +59 -0
  146. package/dist/file-tracker.d.ts +42 -0
  147. package/dist/file-tracker.js +234 -0
  148. package/dist/kosha-sync.d.ts +74 -0
  149. package/dist/kosha-sync.js +272 -0
  150. package/dist/launchd-socket.d.ts +22 -0
  151. package/dist/launchd-socket.js +210 -0
  152. package/dist/mcp/cli.d.ts +2 -0
  153. package/dist/mcp/cli.js +55 -0
  154. package/dist/mcp/server.d.ts +48 -0
  155. package/dist/mcp/server.js +987 -0
  156. package/dist/mmu-store.d.ts +31 -0
  157. package/dist/mmu-store.js +179 -0
  158. package/dist/node-fetch.d.ts +22 -0
  159. package/dist/node-fetch.js +489 -0
  160. package/dist/node.d.ts +9 -0
  161. package/dist/node.js +244396 -0
  162. package/dist/request-decoding.d.ts +30 -0
  163. package/dist/request-decoding.js +85 -0
  164. package/dist/sessions.d.ts +179 -0
  165. package/dist/sessions.js +837 -0
  166. package/dist/stats.d.ts +114 -0
  167. package/dist/stats.js +439 -0
  168. package/dist/turn-report.d.ts +65 -0
  169. package/dist/turn-report.js +724 -0
  170. package/dist/warp/app-launch.d.ts +26 -0
  171. package/dist/warp/app-launch.js +155 -0
  172. package/dist/warp/ca.d.ts +74 -0
  173. package/dist/warp/ca.js +416 -0
  174. package/dist/warp/connect.d.ts +42 -0
  175. package/dist/warp/connect.js +686 -0
  176. package/dist/warp/der.d.ts +57 -0
  177. package/dist/warp/der.js +151 -0
  178. package/dist/warp/index.d.ts +79 -0
  179. package/dist/warp/index.js +650 -0
  180. package/dist/warp/resolve.d.ts +12 -0
  181. package/dist/warp/resolve.js +49 -0
  182. package/dist/warp/route.d.ts +71 -0
  183. package/dist/warp/route.js +134 -0
  184. package/dist/worker.d.ts +71 -0
  185. package/dist/worker.js +174 -0
  186. package/docs/SECURITY_MODEL.md +84 -0
  187. package/package.json +122 -4
  188. package/plugins/fiche-companion/README.md +42 -0
  189. package/plugins/fiche-companion/assets/logo.svg +48 -0
  190. package/plugins/fiche-companion/hooks.json +11 -0
  191. package/plugins/fiche-companion/mcp_config.json +8 -0
  192. package/plugins/fiche-companion/plugin.json +18 -0
  193. package/plugins/fiche-companion/scripts/claude-statusline.mjs +35 -0
  194. package/plugins/fiche-companion/scripts/post-invocation.mjs +122 -0
  195. package/plugins/fiche-companion/scripts/resolve-turn-report.mjs +132 -0
  196. package/plugins/fiche-companion/skills/fiche/SKILL.md +61 -0
@@ -0,0 +1,589 @@
1
+ /**
2
+ * Request-body transformer. Extracts the static system prompt + tool definitions,
3
+ * renders them as PNG image blocks, and rewrites the body to reference those images —
4
+ * saving 65-73% input tokens while preserving reasoning quality.
5
+ */
6
+ import type { ImageBlock, Message, MessagesRequest } from './types.js';
7
+ import { LINES_PER_IMAGE, maxCharsPerImage, countVisualRows, estimateImageCount, type RenderStyle } from './render.js';
8
+ import type { GptHistoryOptions } from './openai-history.js';
9
+ import { type PriceRates } from './pricing.js';
10
+ import { type TextHygieneMode } from './text-hygiene.js';
11
+ import type { StageToggles } from './stage-plugins.js';
12
+ /** Longest cache TTL the request's cache_control markers ask for, in seconds.
13
+ * Anthropic: `ttl: "1h"` = 3600, otherwise the 5-minute default. */
14
+ export declare function requestCacheTtlSec(req: unknown): number;
15
+ import { type VisionPricing } from './vision-cost.js';
16
+ /** Per-block descriptor passed to `TransformOptions.keepSharp`. */
17
+ export interface KeepSharpBlock {
18
+ /** Which live-region path is asking. `<system-reminder>` blocks are never offered:
19
+ * they always stay text, so the predicate has nothing to decide. */
20
+ readonly kind: 'tool_result' | 'tool_result_part';
21
+ /** The block's text exactly as the caller produced it (pre-render, pre-compaction). */
22
+ readonly text: string;
23
+ /** `tool_use_id` of the owning tool_result, when applicable. */
24
+ readonly toolUseId?: string;
25
+ }
26
+ /** A block inkling rendered to image(s), returned in `TransformInfo.recoverable`
27
+ * when the caller sets `emitRecoverable`. Lets a stateful harness restore
28
+ * byte-exact content if the model needs the imaged region verbatim. */
29
+ export interface RecoverableBlock {
30
+ /** `rec_` + 8 hex SHA-256 over kind + toolUseId + original text. */
31
+ readonly id: string;
32
+ readonly kind: 'tool_result' | 'tool_result_part';
33
+ readonly toolUseId?: string;
34
+ /** Original text before compaction/reflow/paging — the bytes to restore. */
35
+ readonly text: string;
36
+ readonly imageCount: number;
37
+ }
38
+ export type OpticalMode = 'auto' | 'hybrid' | 'full';
39
+ export type ClientSessionSource = 'fiche-header' | 'claude-code-header';
40
+ export interface ClientSessionIdentityInput {
41
+ clientSessionId?: string;
42
+ clientSessionSource?: ClientSessionSource;
43
+ claudeCodeSessionId?: string;
44
+ }
45
+ export interface TransformOptions {
46
+ /** Resolved model id. Its profile supplies font, columns, height, and history defaults. */
47
+ model?: string;
48
+ /** Master switch — false makes this a no-op pass-through (neither imaging nor text hygiene). */
49
+ compress?: boolean;
50
+ /** Enable image rendering passes (slab, history, tool_result PNGs). Set false for
51
+ * weak/text-only readers while leaving prefix-safe deterministic text hygiene active. */
52
+ imageCompress?: boolean;
53
+ /** Optical history policy: 'auto' (kosha + cheap read <= 0.10x & < 160k -> hybrid),
54
+ * 'hybrid' (Turn-1 static slab optical + dynamic Text-MMU), or 'full' (all-optical). */
55
+ opticalMode?: OpticalMode;
56
+ /** Prefix-safe deterministic tool-output hygiene (`auto` | `on` | `off` | boolean). */
57
+ textHygiene?: boolean | TextHygieneMode;
58
+ /** Optional expected output tokens for long-context output-cliff calculations. */
59
+ expectedOutputTokens?: number;
60
+ /** Move tool descriptions into the same image (and stub the originals). */
61
+ compressTools?: boolean;
62
+ /** Compress large tool_result text content across all user messages. */
63
+ compressToolResults?: boolean;
64
+ /** Don't compress if total compressible chars below this. */
65
+ minCompressChars?: number;
66
+ /** Per-block threshold for compressToolResults (chars). */
67
+ minToolResultChars?: number;
68
+ /** Soft-wrap width in monospace cells. */
69
+ cols?: number;
70
+ /** Hard upper bound on images per tool_result; source text truncated with a paging
71
+ * marker above this to stay under Anthropic's 100-image/request cap. Default 10. */
72
+ maxImagesPerToolResult?: number;
73
+ /** Ceiling on total decoded image bytes in one request, caller images
74
+ * included. The provider's hard limit is a count, not a size, so the image
75
+ * cap alone lets a long session assemble a request that is legal by count and
76
+ * fails by weight: production traffic degrades sharply past roughly 20 MiB
77
+ * with 500s, 502s, empty 200s and stalls (#157). Groups are admitted whole,
78
+ * and a group that does not fit keeps its source text. */
79
+ maxImageBytes?: number;
80
+ /** Chars-per-token assumption for `isCompressionProfitable()`. Default 4. */
81
+ charsPerToken?: number;
82
+ /** Multi-turn amortization horizon for the history-collapse gate. N≥2 evaluates as
83
+ * if N future turns share the prefix (worst-case-warm-image vs best-case-warm-text).
84
+ * Default 1 (per-turn cold gate). See docs/HISTORY_CACHE_MODEL.md. */
85
+ historyAmortizationHorizon?: number;
86
+ /** Tokens the un-rewritten path would have cache-hit on. Adds a one-time burn
87
+ * penalty `priorWarmTokens × (CC − CR)` to the image side so the gate accounts
88
+ * for invalidating a warm text cache. Default 0 (cold-start). ≤0 clamped to 0. */
89
+ priorWarmTokens?: number;
90
+ /** Symmetric counterpart: tokens the image path would have cache-hit on. Adds the
91
+ * same burn formula to the TEXT side, preventing the gate from flipping out of
92
+ * image mode when the image prefix is already warm. Default 0. ≤0 clamped to 0. */
93
+ priorWarmImageTokens?: number;
94
+ /** GPT only: collapse the OLD closed-tool-call conversation prefix into history
95
+ * image(s), keeping the recent tail as text. Independent of the static slab.
96
+ * Default on. See src/core/openai-history.ts. */
97
+ collapseHistory?: boolean;
98
+ /** GPT only: history-collapse tuning overrides (keepTail / collapseChunk / …). */
99
+ gptHistory?: Partial<GptHistoryOptions>;
100
+ /** Re-pack image-bound text into a ↵-delimited stream to fill `cols` (~29%→75-80%
101
+ * glyph-fill). ON by default (98.95% char accuracy at L1 OCR eval, +1pp vs baseline).
102
+ * Hard newlines become visible ↵ glyphs — tell the model via system prompt. */
103
+ reflow?: boolean;
104
+ /** Caller fidelity hint: return `true` for a block that must stay as text (IDs,
105
+ * hashes, file paths — content where mis-OCR would be silent and wrong). Only
106
+ * consulted on per-block live-region paths (reminders, tool_results). A throwing
107
+ * or non-boolean return is treated as `false`. */
108
+ keepSharp?: (block: KeepSharpBlock) => boolean;
109
+ /** When true, populate `TransformInfo.recoverable` with original text + provenance
110
+ * for every block rendered to images. Off by default (entries inflate `info`;
111
+ * only a stateful harness can use them). */
112
+ emitRecoverable?: boolean;
113
+ /**
114
+ * Inject OpenAI `prompt_cache_breakpoint` on Responses text parts when the
115
+ * model profile asks for it. Default true (api.openai.com). Set false for
116
+ * ChatGPT Codex (`chatgpt.com/backend-api/codex/responses`), which answers
117
+ * 400 `prompt_cache_breakpoint is not supported on this model`.
118
+ */
119
+ explicitPromptCacheBreakpoints?: boolean;
120
+ /** Per-stage enable flags synced from `~/.config/fiche/plugins.json`. */
121
+ stageToggles?: Partial<StageToggles>;
122
+ /** Opt-in Stage 2 lossless cleaning on bulky non-code user payloads (>=1500 chars). Default false. */
123
+ cleanUserPayloads?: boolean;
124
+ /** History collapse: treat each closed tool call/result pair as its own round.
125
+ * Set by proxy for Claude Code (`claude-cli/` UA + `x-app: cli|cli-bg`). Default false. */
126
+ separateAdjacentToolPairs?: boolean;
127
+ /** Validated client session ID (`x-fiche-session-id`, `x-inkling-session-id`, or `x-claude-code-session-id`) for swarm/session isolation. */
128
+ clientSessionId?: string;
129
+ /** Header family that supplied `clientSessionId`. */
130
+ clientSessionSource?: ClientSessionSource;
131
+ /** Validated Claude Code session UUID (`x-claude-code-session-id` header) for session isolation. */
132
+ claudeCodeSessionId?: string;
133
+ }
134
+ /**
135
+ * Subscription OAuth requests are classified as first-party traffic only when
136
+ * one of these exact identities remains the first, separate top-level system
137
+ * block. Never render one into an image or concatenate other text into its
138
+ * block: the endpoint answers an unclassified request with an opaque
139
+ * `429 rate_limit_error: "Error"` even when the account has quota left (#149).
140
+ *
141
+ * Which identity ships depends on the entrypoint, not the product. Claude Code
142
+ * 2.1.220 picks one of three:
143
+ *
144
+ * if (vertex) return CLI;
145
+ * if (nonInteractive) return appendSystemPrompt ? CLI_WITHIN_SDK : AGENT_SDK;
146
+ * return CLI;
147
+ *
148
+ * so the terminal sends the CLI line, `claude -p` / the VS Code extension /
149
+ * Claude Desktop's `stream-json` mode send the Agent SDK line, and adding
150
+ * `--append-system-prompt` to any of those switches to the CLI-within-SDK line.
151
+ */
152
+ export declare const CLAUDE_CODE_OAUTH_IDENTITY = "You are Claude Code, Anthropic's official CLI for Claude.";
153
+ export declare const CLAUDE_CODE_WITHIN_SDK_OAUTH_IDENTITY = "You are Claude Code, Anthropic's official CLI for Claude, running within the Claude Agent SDK.";
154
+ export declare const CLAUDE_AGENT_SDK_OAUTH_IDENTITY = "You are a Claude agent, built on Anthropic's Claude Agent SDK.";
155
+ /** Empirical cpt for the system-slab path (Opus 4.7 tokenizer, N=391, observed 1.91).
156
+ * Slab-specific because reminders/tool_results have unknown shape; those use CHARS_PER_TOKEN. */
157
+ export declare const SLAB_CHARS_PER_TOKEN = 2;
158
+ /** Empirical cpt for the history-collapse path (same Opus 4.7 telemetry as SLAB_CHARS_PER_TOKEN).
159
+ * History is even denser (tool_use JSON dominates), so 2.0 is doubly conservative. */
160
+ export declare const HISTORY_CHARS_PER_TOKEN = 2;
161
+ /** Chars-per-token for the `inkling export` *reporting* estimate (factsheet & savings %).
162
+ * Less conservative than the gate's CHARS_PER_TOKEN=4: reporting wants an accurate
163
+ * figure (~3.7 for source/prose text), not a safe-side under-estimate. Single source
164
+ * of truth — src/core/export.ts imports this rather than redefining it. */
165
+ export declare const REPORT_CHARS_PER_TOKEN = 3.7;
166
+ /** Gate-only conservatism: a 10% upward bias on the estimated image cost,
167
+ * keeping the gate on the safe (pass-through) side near break-even. This is NOT
168
+ * part of any provider's documented cost — those live in `visionTokens`
169
+ * (vision-cost.ts); this margin only tunes the gate, and it is deliberately the
170
+ * same margin for every model family on this path. The OpenAI/Responses gate
171
+ * deliberately applies NO margin: it reproduces the renderer's exact page split
172
+ * and compares against an exact o200k baseline, so it has no estimation error
173
+ * to absorb (see `evalOpenAIGate`). */
174
+ export declare const GATE_MARGIN = 1.1;
175
+ /** Everything the gate needs to price a hypothetical render: page geometry plus
176
+ * the serving model's image-cost regime (`vision`/`visionTier`, satisfied by a
177
+ * `GptModelProfile`). Defaults to the dense Anthropic page. */
178
+ interface GateGeometry {
179
+ cols: number;
180
+ maxHeightPx: number;
181
+ maxChars: number;
182
+ style: RenderStyle;
183
+ pricing: VisionPricing;
184
+ }
185
+ /** Re-exported from render.ts, which owns the cell geometry these derive from.
186
+ * Kept exported here because the eval harnesses and gpt paths import them from
187
+ * transform. Single implementation, so the page-capacity math can't fork. */
188
+ export { LINES_PER_IMAGE, maxCharsPerImage, countVisualRows, estimateImageCount };
189
+ /** Lossless pre-render whitespace compactor (each `\n` costs ≥1 visual row):
190
+ * 1. Strip trailing whitespace per line (preserves leading indent).
191
+ * 2. Collapse 3+ consecutive newlines to 2. Typically saves 10-25% rows on
192
+ * markdown/tool-doc slabs, enough to flip borderline gates to profitable. */
193
+ export declare function compactSlabWhitespace(text: string): string;
194
+ /** Decompose the break-even gate into components for telemetry. Returns the
195
+ * imageTokens, textTokens, and symmetric burn terms the gate uses internally,
196
+ * or `null` for empty/non-finite input. */
197
+ export declare function evalCompressionProfitability(text: string, cols: number, imageCountCap?: number | undefined, charsPerToken?: number, priorWarmTokens?: number, priorWarmImageTokens?: number, shrinkWidth?: boolean, geometry?: GateGeometry, rates?: Readonly<PriceRates> | null): {
198
+ imageTokens: number;
199
+ textTokens: number;
200
+ burnImageSide: number;
201
+ burnTextSide: number;
202
+ profitable: boolean;
203
+ } | null;
204
+ export declare function isCompressionProfitable(text: string, cols?: number, imageCountCap?: number, charsPerToken?: number, priorWarmTokens?: number, priorWarmImageTokens?: number, shrinkWidth?: boolean, maxCharsPerImage?: number, geometry?: GateGeometry, rates?: Readonly<PriceRates> | null): boolean;
205
+ /**
206
+ * Horizon-aware variant of `isCompressionProfitable` for history-collapse.
207
+ *
208
+ * Evaluates expected lifetime cost over N turns: worst-case-warm for image
209
+ * (cache_create turn 1, cache_read turns 2..N) vs best-case-warm for text
210
+ * (cache_read all N). Gate condition: I×(CC + CR×(N-1)) < T×CR×N.
211
+ * Examples: N=5 → I < 0.30×T; N=10 → I < 0.47×T.
212
+ * Falls back to cold per-turn gate when `horizon <= 1`. See docs/HISTORY_CACHE_MODEL.md.
213
+ */
214
+ export declare function isCompressionProfitableAmortized(text: string, cols: number, imageCountCap: number | undefined, charsPerToken: number, horizon: number, priorWarmTokens?: number, priorWarmImageTokens?: number, shrinkWidth?: boolean, maxCharsPerImage?: number, geometry?: GateGeometry, rates?: Readonly<PriceRates> | null): boolean;
215
+ /** Logical bucket for per-gate-call char attribution. Used by the rolling-cpt
216
+ * regression to derive per-bucket marginal cpt from production telemetry. */
217
+ export type BucketName = 'static_slab' | 'reminder' | 'tool_result_json' | 'tool_result_log' | 'tool_result_prose' | 'history';
218
+ /** Pre-compaction TEXT char totals per bucket. Absent when no bucket fired. */
219
+ export type BucketChars = Partial<Record<BucketName, number>>;
220
+ /** Parsed contents of Claude Code's <env> + git status blocks. All optional —
221
+ * fields are only populated if the corresponding line is present. */
222
+ export interface EnvFields {
223
+ /** Working directory at the time `claude` was launched. */
224
+ cwd?: string;
225
+ isGitRepo?: boolean;
226
+ /** Current git branch, parsed from <git_status> or a "Branch:" line. */
227
+ gitBranch?: string;
228
+ platform?: string;
229
+ osVersion?: string;
230
+ /** "Today's date" as Claude Code reported it (YYYY-MM-DD). */
231
+ today?: string;
232
+ }
233
+ export interface TransformInfo {
234
+ compressed: boolean;
235
+ reason?: string;
236
+ /** Exact UTF-8 byte length of the final serialized provider request. */
237
+ serializedRequestBytes?: number;
238
+ /** Result of the profile-level serialized request guard. */
239
+ sizeLimitOutcome?: 'within_limit' | 'rejected' | 'fallback';
240
+ origChars: number;
241
+ /** Total source chars image-encoded this request (static slab + reminders + tool_results).
242
+ * Unlike `origChars` (static slab + tool docs only), reflects what `imageCount` replaced. */
243
+ compressedChars: number;
244
+ imageCount: number;
245
+ imageBytes: number;
246
+ /** Σ width×height across all rendered images. Pairs with upstream token count for
247
+ * empirical px/token regression: `tokens ≈ α·outgoingTextChars + β·imagePixels`. */
248
+ imagePixels?: number;
249
+ /** Provider-estimated vision tokens the rendered images cost as input. */
250
+ imageTokens?: number;
251
+ /** Chars/tokens removed losslessly or structurally by prefix-safe text hygiene. */
252
+ textHygieneSavedChars?: number;
253
+ textHygieneSavedTokens?: number;
254
+ textHygieneBlocks?: number;
255
+ textHygieneStages?: string[];
256
+ /** Non-null when compression avoided a kosha long-context pricing cliff (e.g. >272K, >200K, >100K). */
257
+ cliffAvoided?: {
258
+ at: number;
259
+ multiplier: number;
260
+ savedUsd: number;
261
+ };
262
+ /** Provider-specific text-token estimate of the content inkling imaged/stripped —
263
+ * the would-have-paid "as plain text" baseline. Compared against imageTokens
264
+ * for the per-request saving. See src/core/openai-savings.ts. */
265
+ baselineImagedTokens?: number;
266
+ /** Provider-specific estimate of native tokens added solely by inkling (pointers, exact-token
267
+ * sheets, and framing). Removed from the unproxied counterfactual. */
268
+ nativeInjectedTokens?: number;
269
+ /** Total TEXT chars in the outgoing body (system + messages, excluding image base64).
270
+ * Denominator for empirical chars-per-token regression on cold-miss events. */
271
+ outgoingTextChars?: number;
272
+ /** User-pinned instructions relocated to the request tail, and the chars that
273
+ * cost. Both absent when nothing is pinned. Uncached by construction (the
274
+ * block lands after every breakpoint), so these chars are paid every turn. */
275
+ pinChars?: number;
276
+ /** Pin folding threw and was skipped. The body still goes out unpinned. */
277
+ pinError?: string;
278
+ /** Claude Code's volatile per-turn billing line, stripped from the body.
279
+ * The proxy forwards it as a real HTTP header on the upstream request.
280
+ * Any body position at-or-after the last cache_control marker renders as
281
+ * user-attributed text; any earlier position busts the cached prefix. */
282
+ billingLine?: string;
283
+ /** OpenAI Responses only: local o200k decomposition of the ORIGINAL request
284
+ * before inkling rewrites it. No provider count_tokens call. Categories are
285
+ * mutually exclusive text-token estimates; imageParts counts native images. */
286
+ responsesComposition?: {
287
+ instructions: number;
288
+ systemDeveloper: number;
289
+ userAssistant: number;
290
+ /** Legacy field names: include both function and custom tool items. */
291
+ functionCalls: number;
292
+ functionOutputs: number;
293
+ reasoningEncrypted: number;
294
+ compactionOpaque: number;
295
+ toolsJson: number;
296
+ other: number;
297
+ totalLocal: number;
298
+ imageParts: number;
299
+ /** Responses native-tool-state classification and realized image share. */
300
+ completedFunctionPairs?: number;
301
+ recentNativeFunctionPairs?: number;
302
+ oldFunctionPairs?: number;
303
+ openFunctionCalls?: number;
304
+ orphanFunctionOutputs?: number;
305
+ malformedFunctionItems?: number;
306
+ imageableFunctionCalls?: number;
307
+ imageableFunctionOutputs?: number;
308
+ collapsedFunctionPairs?: number;
309
+ collapsedFunctionCalls?: number;
310
+ collapsedFunctionOutputs?: number;
311
+ /** Item `type` values that acted as a hard barrier in the Responses
312
+ * planner, with occurrence counts (`local_shell_call:12`). Every barrier
313
+ * forces a page break, so a frequent type here is directly responsible
314
+ * for under-filled images. Diagnostic only — never affects routing. */
315
+ barrierTypes?: string[];
316
+ };
317
+ /** Length of the static (cacheable) slab rendered into the image. */
318
+ staticChars: number;
319
+ /** Length of the dynamic (per-turn) slab kept as plain text. */
320
+ dynamicChars: number;
321
+ dynamicBlockCount: number;
322
+ /** Tag-shaped blocks in the static slab not in DYNAMIC_BLOCK_TAGS.
323
+ * Canary: a new per-turn Claude Code tag would appear here before cache rate collapses. */
324
+ unknownStaticTags?: string[];
325
+ /** Static-slab tags whose content changed within a session — proven dynamic,
326
+ * busting the image cache each turn. The real alert signal. */
327
+ churningStaticTags?: string[];
328
+ env?: EnvFields;
329
+ /** sha8 of static slab + tool docs (what goes in the image). Repeats across turns → cache hits. */
330
+ systemSha8?: string;
331
+ /** sha8 of first user message text (first 4 KiB). Rough thread/session id. */
332
+ firstUserSha8?: string;
333
+ /** Isolated session key (`sha8('fs:' + id)`, `sha8('cc:' + id)`, or `firstUserSha8`). */
334
+ sessionKey?: string;
335
+ sessionKeySource?: ClientSessionSource | 'anchor';
336
+ /** Raw bytes of the first rendered image. Dashboard preview only; NOT persisted to JSONL. */
337
+ firstImagePng?: Uint8Array;
338
+ firstImageWidth?: number;
339
+ firstImageHeight?: number;
340
+ /** All rendered PNGs this request. Dashboard only; NOT persisted to JSONL. */
341
+ imagePngs?: Uint8Array[];
342
+ imageDims?: Array<{
343
+ width: number;
344
+ height: number;
345
+ }>;
346
+ /** Legacy shared source text for one render group. Dashboard-only; not persisted. */
347
+ imageSourceText?: string;
348
+ /** Source text parallel to imagePngs/imageDims. One entry per PNG; a multi-page
349
+ * render may repeat its section source. Dashboard-only; not persisted. */
350
+ imageSourceTexts?: Array<string | undefined>;
351
+ toolResultImgs?: number;
352
+ /** Image blocks the CLIENT already sent (screenshots, pasted images, prior
353
+ * tool_result images). They count against the provider's hard image cap just
354
+ * like ours do, so every inkling imaging path must price them in — a request
355
+ * whose own images already fill the cap must not get a single one from us.
356
+ * Counted once, before any rewrite. See {@link imageHeadroom}. */
357
+ nativeImages?: number;
358
+ /** Imaging steps skipped because the cap was exhausted (metrics for tuning). */
359
+ imageBudgetSkips?: number;
360
+ /** Decoded bytes of the CLIENT's own image blocks, counted once before any
361
+ * rewrite. They occupy the same weight budget ours do, and they are never
362
+ * removed to make room: a caller's screenshot outranks our compression. */
363
+ nativeImageBytes?: number;
364
+ /** Imaging groups skipped because the byte budget, not the count cap, was
365
+ * exhausted. Distinct from {@link imageBudgetSkips} because the two have
366
+ * different fixes: one wants fewer pages, the other wants smaller ones. */
367
+ imageByteSkips?: number;
368
+ /** Set when the request landed within 10% of the byte budget. Nothing was
369
+ * dropped, but the next turn of the same session probably will be. */
370
+ imageBytesNearLimit?: boolean;
371
+ /** Image blocks actually present in the outgoing body — ours AND the client's.
372
+ * This is the only number the provider counts. It is <= imageCount + nativeImages
373
+ * because the history collapse can absorb messages that already carried images. */
374
+ wireImages?: number;
375
+ /** Chars of tool docs moved to the system-text Tool Reference (not imaged). */
376
+ toolDocsChars?: number;
377
+ /** Codepoints missing from the atlas (rendered as blank cells). Telemetry for atlas tuning. */
378
+ droppedChars?: number;
379
+ /** Top dropped codepoints by frequency (`U+HHHH` → count), at most 20 entries. */
380
+ droppedCodepointsTop?: Record<string, number>;
381
+ /** Why blocks passed through without compression. Only present when count > 0. */
382
+ passthroughReasons?: {
383
+ below_threshold?: number;
384
+ not_profitable?: number;
385
+ kept_sharp?: number;
386
+ image_budget?: number;
387
+ };
388
+ /** Slab gate diagnostics — imageTokens, textTokens, burn terms, and verdict.
389
+ * Lets hosts measure flap-prevention efficacy and tune amortization horizon. */
390
+ gateEval?: {
391
+ readonly site: 'slab';
392
+ readonly imageTokens: number;
393
+ readonly textTokens: number;
394
+ /** `priorWarmTokens × (CC − CR)` added to image side. */
395
+ readonly burnImageSide: number;
396
+ /** `priorWarmImageTokens × (CC − CR)` added to text side (anti-flapping anchor). */
397
+ readonly burnTextSide: number;
398
+ readonly profitable: boolean;
399
+ };
400
+ /** Pre-compaction TEXT char totals per gate-call bucket. Rolling-cpt regression denominator. */
401
+ bucketChars?: BucketChars;
402
+ /** Chars fed into the history-image renderer. Folded into `bucketChars.history` too. */
403
+ historyTextChars?: number;
404
+ /** Blocks pinned as text by the caller's `keepSharp` predicate this request. */
405
+ keptSharpBlocks?: number;
406
+ /** Imaged live-region blocks with original text + provenance, when `emitRecoverable`. */
407
+ recoverable?: RecoverableBlock[];
408
+ truncatedToolResults?: number;
409
+ omittedChars?: number;
410
+ /** History-collapse: messages collapsed into the synthetic prepended user message. */
411
+ collapsedTurns?: number;
412
+ collapsedChars?: number;
413
+ /** History-collapse images. Also folded into `info.imageCount`. */
414
+ collapsedImages?: number;
415
+ /** sha8 of concatenated history-image base64. Stable across the collapse window →
416
+ * proves Anthropic's prompt cache can `cache_read` (0.1×) instead of `cache_create`.
417
+ * A changing hash means cache-key drift is back. Only set when collapse produced images. */
418
+ historyImageSha?: string;
419
+ /** Freeze-grid step the history collapse actually used, in messages. Rises when the
420
+ * adaptive packer merges chunks to fit the image budget; must never fall within a
421
+ * session (a finer re-cut re-keys every chunk). */
422
+ historyFreezeStep?: number;
423
+ /** The collapse re-cut the grid for page fill instead of cache freeze — only set when
424
+ * the session's upstream cache was provably dead (idle past TTL, or after a reject). */
425
+ historyPackFill?: boolean;
426
+ /** The image budget could not hold the whole closed prefix; the tail stayed live text. */
427
+ historyBudgetTrimmed?: boolean;
428
+ /** History collapse ran with separateAdjacentToolPairs enabled. */
429
+ historySplitAdjacentPairs?: boolean;
430
+ /** sha8 of the ACTUAL cacheable prefix sent this turn (tools + system +
431
+ * message blocks through the imaged history/slab boundary; the live tail is
432
+ * excluded). Read-only measurement. A change turn-over-turn within a session
433
+ * ⇒ inkling serialized different prefix bytes (we busted our own cache,
434
+ * inkling-side); STABLE while cache_create spikes / cache_read collapses ⇒ the
435
+ * prefix was evicted upstream. Decisive attribution signal (see #11). */
436
+ cachePrefixSha8?: string;
437
+ /** Approx size (chars) of that cached prefix — pairs with cachePrefixSha8 so a
438
+ * bust reads as growth (size up) vs pure invalidation (size unchanged). */
439
+ cachePrefixBytes?: number;
440
+ /** Per-layer digests of that same pinned prefix, in wire order: tool
441
+ * definitions, system blocks, and the imaged head (messages up to and
442
+ * including the history/slab boundary). Exactly one of these moving names
443
+ * the cache-bust culprit; the aggregate cachePrefixSha8 alone cannot. */
444
+ cachePrefixToolsSha8?: string;
445
+ cachePrefixSystemSha8?: string;
446
+ cachePrefixHeadSha8?: string;
447
+ /** Digest of the span Anthropic actually caches: everything up to and
448
+ * including the LAST cache_control marker. After a collapse this is a strict
449
+ * subset of the boundary-scoped prefix — the newest freeze chunk re-renders
450
+ * every turn by design and sits after the marker — so THIS is the digest that
451
+ * must stay stable turn over turn, and the boundary one is context. */
452
+ cachePrefixMarkedSha8?: string;
453
+ cachePrefixMarkedBytes?: number;
454
+ /** Where that last marker sits, as `m<messageIdx>.b<blockIdx>`. A marker that
455
+ * roams between turns re-cuts the cached span and busts it on its own. */
456
+ cachePrefixMarkerPos?: string;
457
+ /** Why the history collapse didn't run (or did). Diagnostic only. */
458
+ historyReason?: 'no_history' | 'prefix_too_short' | 'no_closed_prefix' | 'below_min_chars' | 'below_min_tokens' | 'not_profitable' | 'too_many_images'
459
+ /** Rendered, then not applied: the collapse group did not fit the decoded
460
+ * image-byte budget, so the original text stands. Distinct from
461
+ * `too_many_images`, which is the provider's count cap. */
462
+ | 'image_bytes' | 'render_empty' | 'over_budget' | 'collapsed';
463
+ /** Token count of the pre-compression body from /v1/messages/count_tokens (free).
464
+ * Absent when probe failed — event excluded from savings rollup. */
465
+ baselineTokens?: number;
466
+ /** Token count of the pre-compression body truncated at the last cache_control marker.
467
+ * Absent when the original body has no cache_control markers (cacheable=0 exactly). */
468
+ baselineCacheableTokens?: number;
469
+ /** 'ok': both probes resolved. 'partial': full-body resolved but cacheable-prefix
470
+ * didn't, or body is a server-side thread continuation whose probe covers only
471
+ * the delta (exclude from rollup either way). 'failed': no baseline.
472
+ * undefined: no probe attempted. */
473
+ baselineProbeStatus?: 'ok' | 'partial' | 'failed';
474
+ /** When baselineProbeStatus is 'failed': why (e.g. `http_400 ...`, `fetch_error ...`). */
475
+ baselineProbeError?: string;
476
+ /** Request was a server-side thread continuation (`thread.type === "continue"`). */
477
+ threadContinue?: boolean;
478
+ }
479
+ export declare function splitStaticDynamic(text: string): {
480
+ staticText: string;
481
+ dynamicText: string;
482
+ blockCount: number;
483
+ unknownTags: string[];
484
+ /** tag → concatenated inner content of same-named slab blocks. */
485
+ staticTagContents: Map<string, string>;
486
+ };
487
+ /** sha256[0..8] hex via Web Crypto (works in Node 18+ and Workers). 32-bit collision-safe. */
488
+ export declare function sha8(text: string): Promise<string>;
489
+ /**
490
+ * Session identity text: the user's first prompt, skipping harness envelopes
491
+ * (see {@link sessionAnchorText}). Scans every user message before the first
492
+ * assistant turn, because a client may send its envelope as a message of its own.
493
+ */
494
+ export declare function firstUserText(req: MessagesRequest): string;
495
+ /**
496
+ * Resolve and record session isolation identity on `info` from explicit client
497
+ * session headers (`x-fiche-session-id` -> `fs:`, `x-claude-code-session-id` -> `cc:`)
498
+ * or fall back to the SHA-8 anchor of the first user turn (`anchor`).
499
+ */
500
+ export declare function applyClientSessionIdentity(info: TransformInfo, firstUser: string, opts?: ClientSessionIdentityInput): Promise<string | undefined>;
501
+ /**
502
+ * True when the first message carries a `<system-reminder>` block — the
503
+ * envelope Claude Code uses to inject CLAUDE.md project instructions. Such a
504
+ * message must never be rendered to pixels: imaged rules read as description
505
+ * rather than instruction, so the model stops obeying them mid-session.
506
+ */
507
+ export declare function firstMessageHasSystemReminder(messages: Message[] | undefined): boolean;
508
+ /** Parse structured fields from the dynamic slab for telemetry. Read-only. */
509
+ export declare function extractEnvFields(dynamicText: string): EnvFields;
510
+ /** Classify content so we can pick a truncation strategy. Cheap heuristics on
511
+ * the first ~4 KiB. Returns:
512
+ * - `'structured'`: JSON/YAML/diff markers at the top. Truncate tail.
513
+ * - `'log'`: ≥30% of lines start with a log level or timestamp. Truncate middle.
514
+ * - `'other'`: prose, file dumps, etc. Truncate middle.
515
+ * Exported for tests. */
516
+ export declare function classifyContent(text: string): 'structured' | 'log' | 'other';
517
+ /** Truncate `text` so it renders to roughly `maxImages` images at the given
518
+ * `cols`. Picks head/tail split based on `classifyContent`. Budget measured
519
+ * in visual rows (what render.ts actually slices on). Returns the truncated
520
+ * text (with paging marker embedded) and the count of chars omitted. If
521
+ * `text` already fits, returns unchanged with `omittedChars: 0`. Exported
522
+ * for tests. */
523
+ export declare function truncateForBudget(text: string, maxImages: number, cols: number, maxCharsPerImage?: number, linesPerImage?: number): {
524
+ text: string;
525
+ omittedChars: number;
526
+ truncated: boolean;
527
+ };
528
+ /**
529
+ * Render text → Anthropic image blocks for the proxy. The width-selection rule below
530
+ * is mirrored exactly by
531
+ * the public SDK primitive `renderTextToImages` (library.ts), so the proxy and the
532
+ * `inkling export` CLI emit byte-identical PNGs for the same text. Exported so
533
+ * export-proxy-align.test.ts can pin that invariant against the real proxy code.
534
+ */
535
+ export declare function textToImageBlocks(text: string, cols: number,
536
+ /** Shrink canvas to the longest wrapped line. Default `true`. */
537
+ shrinkWidth?: boolean, style?: RenderStyle, maxHeightPx?: number): Promise<{
538
+ blocks: ImageBlock[];
539
+ /** Raw PNG bytes parallel to `blocks` (avoids re-decoding base64 for dashboard). */
540
+ pngs: Uint8Array[];
541
+ /** Pixel dimensions parallel to `pngs`. */
542
+ dims: Array<{
543
+ width: number;
544
+ height: number;
545
+ }>;
546
+ droppedChars: number;
547
+ droppedCodepoints: Map<number, number>;
548
+ /** Σ width×height — caller accumulates into `info.imagePixels` for px/token regression. */
549
+ pixels: number;
550
+ }>;
551
+ /**
552
+ * Image blocks this request may still add before the provider's hard cap.
553
+ *
554
+ * The cap counts EVERY image on the wire: the client's own (`nativeImages`) and
555
+ * ours (`imageCount`). Pricing only ours is how a request with 103 client images
556
+ * still got imaged further and came back 400 — the cap is a wire property, not a
557
+ * inkling property. Never negative; callers treat 0 as "keep it as text".
558
+ */
559
+ export declare function imageHeadroom(info: TransformInfo): number;
560
+ /** Bytes still available for image content, caller images already deducted.
561
+ *
562
+ * Separate from {@link imageHeadroom} because the two limits fail differently.
563
+ * The count cap is the provider's documented limit and rejects with a clear
564
+ * error. The byte budget is empirical: past roughly 20 MiB production requests
565
+ * start failing as 500s, 502s, empty 200s and stalls, which read as flakiness
566
+ * rather than as "too big". */
567
+ export declare function imageByteHeadroom(info: TransformInfo, limit: number): number;
568
+ /** Decoded bytes of the caller's own images, at both nesting levels. Runs BEFORE
569
+ * any rewrite, for the same reason {@link countNativeImages} does. */
570
+ export declare function countNativeImageBytes(messages: readonly Message[] | undefined): number;
571
+ /** Count image blocks already present in the caller's messages. Runs BEFORE any
572
+ * rewrite, so it sees the client's images only — ours do not exist yet. */
573
+ export declare function countNativeImages(messages: readonly Message[] | undefined): number;
574
+ /** Resolve whether optical compression covers only the static Turn-1 slab ('hybrid',
575
+ * with dynamic turns handled by prefix-monotonic Text-MMU) or also history/tool_results ('full'). */
576
+ export declare function resolveOpticalHistoryPolicy(opts: {
577
+ readonly opticalMode?: OpticalMode;
578
+ readonly collapseHistory?: boolean;
579
+ readonly model?: string;
580
+ readonly estPromptTokens?: number;
581
+ readonly textHygieneActive: boolean;
582
+ readonly sessionKey?: string;
583
+ readonly sessionCold?: boolean;
584
+ }): 'hybrid' | 'full';
585
+ export declare function transformRequest(body: Uint8Array, opts?: TransformOptions): Promise<{
586
+ body: Uint8Array;
587
+ info: TransformInfo;
588
+ }>;
589
+ //# sourceMappingURL=transform.d.ts.map