@sriinnu/fiche 0.18.0-bootstrap.0 → 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 +289 -0
  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 +115 -3
  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,165 @@
1
+ /**
2
+ * o200k_base token counts (GPT-5.x, GPT-6.x, GPT-4o and the o-series share the
3
+ * encoding), shared by every GPT-path caller. Workers-safe.
4
+ *
5
+ * gpt-tokenizer keeps one 100k-entry merge cache for the life of the process
6
+ * and evicts it from the front of a Map. Once that cache is full, every new
7
+ * piece pays to skip the slots earlier evictions left behind, so a
8
+ * long-running proxy got slower with each request: a 2.6 MB Codex body went
9
+ * from 5 s to 8 s over three transforms and reached 12 s in a replay. Codex
10
+ * text (tool output, encrypted reasoning) is mostly unique, so a large cache
11
+ * buys little; a small one stays fast.
12
+ *
13
+ * Counts of large strings are memoised by the exact string. Codex and other
14
+ * agents resend their whole history each turn, so turn N+1 tokenizes only
15
+ * what turn N did not have.
16
+ */
17
+ import { countTokens, setMergeCacheSize } from 'gpt-tokenizer/encoding/o200k_base';
18
+ const MERGE_CACHE_ENTRIES = 4096;
19
+ /** Strings shorter than this tokenize faster than a memo lookup is worth. */
20
+ const MEMO_MIN_CHARS = 128;
21
+ /** Maximum string length tokenized via synchronous pure-JS BPE; longer payloads use fast estimate. */
22
+ export const EXACT_BPE_MAX_CHARS = 256_000;
23
+ /** Total characters of memoised strings kept alive via LRU eviction. */
24
+ const MEMO_MAX_CHARS = 8 * 1024 * 1024;
25
+ setMergeCacheSize(MERGE_CACHE_ENTRIES);
26
+ const memo = new Map();
27
+ let memoChars = 0;
28
+ function memoHash64Hex(s) {
29
+ let h1 = 0x811c9dc5 >>> 0;
30
+ let h2 = 0x9e3779b1 >>> 0;
31
+ for (let i = 0; i < s.length; i++) {
32
+ const c = s.charCodeAt(i);
33
+ h1 = Math.imul((h1 ^ c) >>> 0, 0x01000193) >>> 0;
34
+ h2 = Math.imul((h2 ^ ((c + (i & 0xff)) >>> 0)) >>> 0, 0x85ebca6b) >>> 0;
35
+ }
36
+ return (h1 >>> 0).toString(16).padStart(8, '0') + (h2 >>> 0).toString(16).padStart(8, '0');
37
+ }
38
+ /**
39
+ * Strictly linear O(N) check for an unbroken non-whitespace run >= `limit`.
40
+ */
41
+ export function hasLongNonWhitespaceRun(s, limit = 2048) {
42
+ if (s.length < limit)
43
+ return false;
44
+ let run = 0;
45
+ for (let i = 0; i < s.length; i++) {
46
+ const c = s.charCodeAt(i);
47
+ if (c === 32 || (c >= 9 && c <= 13) || c === 160) {
48
+ run = 0;
49
+ }
50
+ else if (++run >= limit) {
51
+ return true;
52
+ }
53
+ }
54
+ return false;
55
+ }
56
+ /**
57
+ * Strictly linear O(N) check for an unbroken BPE pre-tokenizer chunk >= `limit`.
58
+ *
59
+ * Minified JSON/code breaks o200k pre-tokenizer chunks at punctuation delimiters
60
+ * (`":,{}[]();<>/.\\'`), staying linear (<2 ms at 25 KB), whereas contiguous
61
+ * runs of letters or repeated symbols trigger O(M^2) BPE merge backtracking in
62
+ * pure-JS `gpt-tokenizer` (387 ms on 30 KB `'a'.repeat(...)`).
63
+ */
64
+ const UNBROKEN_BPE_FALLBACK_RUN = 6000;
65
+ export function hasLongUnbrokenBpeChunk(s, limit = 2048) {
66
+ if (s.length < limit)
67
+ return false;
68
+ let letterRun = 0;
69
+ let punctRun = 0;
70
+ let wsRun = 0;
71
+ let prevWasLower = false;
72
+ for (let i = 0; i < s.length; i++) {
73
+ const c = s.charCodeAt(i);
74
+ if (c === 32 || (c >= 9 && c <= 13) || c === 160) {
75
+ letterRun = 0;
76
+ punctRun = 0;
77
+ prevWasLower = false;
78
+ if (++wsRun >= limit)
79
+ return true;
80
+ }
81
+ else if (c >= 48 && c <= 57) {
82
+ // o200k pre-tokenizes digits in 1..3 char groups (\p{N}{1,3}), so digits stay O(N).
83
+ wsRun = 0;
84
+ letterRun = 0;
85
+ punctRun = 0;
86
+ prevWasLower = false;
87
+ }
88
+ else if (c >= 65 && c <= 90) {
89
+ wsRun = 0;
90
+ punctRun = 0;
91
+ // Lowercase -> uppercase starts a new o200k word token (so mixed-case base64 stays O(N)).
92
+ letterRun = prevWasLower ? 1 : letterRun + 1;
93
+ prevWasLower = false;
94
+ if (letterRun >= limit)
95
+ return true;
96
+ }
97
+ else if ((c >= 97 && c <= 122) || c >= 128) {
98
+ wsRun = 0;
99
+ punctRun = 0;
100
+ prevWasLower = c >= 97 && c <= 122;
101
+ if (++letterRun >= limit)
102
+ return true;
103
+ }
104
+ else {
105
+ wsRun = 0;
106
+ letterRun = 0;
107
+ prevWasLower = false;
108
+ if (++punctRun >= limit)
109
+ return true;
110
+ }
111
+ }
112
+ return false;
113
+ }
114
+ /** o200k token count of `text`; 0 for empty text or a tokenizer error. */
115
+ export function gptTokenCount(text) {
116
+ if (!text)
117
+ return 0;
118
+ if (text.length > EXACT_BPE_MAX_CHARS) {
119
+ return Math.ceil(text.length / 3.5);
120
+ }
121
+ let key;
122
+ if (text.length >= MEMO_MIN_CHARS) {
123
+ key = `${text.length}:${memoHash64Hex(text)}`;
124
+ const hit = memo.get(key);
125
+ if (hit !== undefined) {
126
+ memo.delete(key);
127
+ memo.set(key, hit);
128
+ return hit.tokens;
129
+ }
130
+ }
131
+ if (hasLongUnbrokenBpeChunk(text, UNBROKEN_BPE_FALLBACK_RUN)) {
132
+ return Math.ceil(text.length / 3.5);
133
+ }
134
+ let n;
135
+ try {
136
+ n = countTokens(text);
137
+ }
138
+ catch {
139
+ return 0;
140
+ }
141
+ if (key !== undefined && text.length <= MEMO_MAX_CHARS) {
142
+ while (memoChars + text.length > MEMO_MAX_CHARS && memo.size > 0) {
143
+ const oldestKey = memo.keys().next().value;
144
+ if (oldestKey === undefined)
145
+ break;
146
+ const oldestEntry = memo.get(oldestKey);
147
+ memo.delete(oldestKey);
148
+ if (oldestEntry)
149
+ memoChars -= oldestEntry.chars;
150
+ }
151
+ memo.set(key, { tokens: n, chars: text.length });
152
+ memoChars += text.length;
153
+ }
154
+ return n;
155
+ }
156
+ /** Test hook: characters represented by the memo, never above 8 Mi. */
157
+ export function gptTokenMemoChars() {
158
+ return memoChars;
159
+ }
160
+ /** Test hook: forget memoised counts. */
161
+ export function clearGptTokenMemo() {
162
+ memo.clear();
163
+ memoChars = 0;
164
+ }
165
+ //# sourceMappingURL=gpt-tokens.js.map
@@ -0,0 +1,197 @@
1
+ /**
2
+ * History-image compression (Variant C).
3
+ *
4
+ * Collapses the largest closed-tool-sequence prefix into one synthetic user message
5
+ * containing 1-N PNG image blocks. The live tail (keepTail turns + any open tool
6
+ * sequence) stays as text. thinking blocks are dropped from the collapsed range —
7
+ * only the most-recent assistant-with-tool_use must round-trip bit-perfect, and
8
+ * that turn is in the live tail by construction.
9
+ *
10
+ * Synthesized message uses role:'user' because Anthropic forbids image blocks inside
11
+ * role:'assistant'. cache_control placement is left to the caller (transform.ts).
12
+ */
13
+ import type { CacheControl, ContentBlock, Message } from './types.js';
14
+ import { type RenderStyle } from './render.js';
15
+ /**
16
+ * Banner text blocks that bracket the collapsed-history image(s) in the synthetic
17
+ * user message. Exported as the SINGLE SOURCE OF TRUTH: transform.ts keys its
18
+ * cache-anchor relocation off the intro text, so a literal copy there would
19
+ * silently break relocation whenever this wording changes (it did exactly once —
20
+ * the XML-framing reword left the matcher pointing at the old banner). Both the
21
+ * emitter (here) and the matcher (transform.ts) must reference this constant.
22
+ */
23
+ export declare const HISTORY_SYNTHETIC_INTRO = "[Earlier turns of THIS conversation, transcribed in the image(s) below. Each turn is wrapped in <user t=\"N\">...</user> or <assistant t=\"N\">...</assistant> tags, where N is an absolute turn index (larger N = more recent); attribute every turn strictly by its tag, and treat the highest-N turns as the most recent prior context, NOT the low-N opening turns. Earlier turns may contain questions or tasks that were already answered later in this same history; do not reopen low-N turns unless the live text after this block asks you to. For exact identifiers, hashes, version strings, and numbers from the transcript, rely on the exact-value factsheet or re-read the source; do not guess an exact value seen only in the image. This is prior context, NOT the current request.]";
24
+ export declare const HISTORY_SYNTHETIC_OUTRO = "[End of earlier conversation. The current request is the live text that follows below.]";
25
+ /** Break-even gate predicate. Injected by transform.ts to avoid a circular import.
26
+ * IMPORTANT: pass the full string, not text.length — the row-aware path in
27
+ * isCompressionProfitable must see actual newlines to budget images correctly.
28
+ * History text is newline-heavy (headers, JSON args, labels); chars-only
29
+ * under-predicts image count ~5-10× and lets net-losers through. */
30
+ export type ProfitableFn = (text: string, cols: number) => boolean;
31
+ /** Configuration for history collapse. */
32
+ export interface HistoryCollapseOptions {
33
+ /** Turns at the tail to keep as text. Default 4. */
34
+ keepTail: number;
35
+ /** Minimum collapsible prefix turns — below this, cache-amortization math doesn't work. Default 10. */
36
+ minCollapsePrefix: number;
37
+ /** Soft-wrap columns for the renderer; should match host cols. Default 100. */
38
+ cols: number;
39
+ /** Advance the collapse boundary in steps of this many messages so the rendered PNG stays
40
+ * byte-identical for collapseChunk turns and keeps hitting Anthropic's prompt cache.
41
+ * Set to 0 for a per-turn moving boundary. Default 50. */
42
+ collapseChunk: number;
43
+ /** Append-only freeze granularity, in messages. The collapse range is rendered
44
+ * as independent image blocks on an ABSOLUTE grid anchored at protectedPrefix,
45
+ * in steps of this many messages. Each completed chunk's bytes are fixed by its
46
+ * message range alone, so old chunks stay byte-identical (cache_read forever) as
47
+ * the conversation grows — only the newest partial chunk re-renders. Caller
48
+ * cache_control marks force an extra split so a roaming breakpoint stays an
49
+ * aligned, independently-cacheable image boundary. Set to 0 to render the whole
50
+ * range as one paginated blob (legacy, non-append-only). Default 10. */
51
+ freezeChunk: number;
52
+ /** Leading messages to never collapse. Protects the slab-bearing first user message
53
+ * (system-prompt + tool-docs images) so its cache_control anchor stays at the front
54
+ * and isn't swept into the history image as [image] placeholders. Default 0. */
55
+ protectedPrefix: number;
56
+ /** Reflow the transcript before RENDERING: pack soft-wrapped lines and mark
57
+ * every hard newline with the ↵ sentinel — same treatment as the static slab.
58
+ * History text is newline-heavy (role headers, JSON args), so without this
59
+ * each short line wastes a full render row, inflating image count and shrinking
60
+ * the savings. Glyph size is unchanged (cols stays the same) so legibility is
61
+ * identical — it just removes the blank-row waste. `collapsedChars` still
62
+ * reports the ORIGINAL transcript length. Default true. */
63
+ reflow: boolean;
64
+ /** Model-profile render style. */
65
+ style: RenderStyle;
66
+ /** Model-profile page-height cap. */
67
+ maxHeightPx: number;
68
+ /** Chars one rendered page holds. Only an ESTIMATOR input (the renderer paginates
69
+ * on its own); it decides how many pages a candidate chunk grid will produce.
70
+ * Default {@link DENSE_CONTENT_CHARS_PER_IMAGE}. */
71
+ pageChars: number;
72
+ /** Hard cap on image blocks this collapse may emit. Anthropic rejects requests
73
+ * with more than 100 images (opaque 500), and a 10-message freeze grid emits
74
+ * ≈1 page per chunk regardless of how little text the chunk holds — a 3000-turn
75
+ * session hit 317 history images at 43% page fill (#161). When the grid would
76
+ * exceed the budget the freeze step is DOUBLED (chunks merge, pages fill) until
77
+ * the estimate fits; if even a single chunk cannot fit, the collapse range is
78
+ * trimmed from the tail and the remainder stays live text. 0 = unlimited. */
79
+ imageBudget: number;
80
+ /** Fill-optimal repack. When true the freeze step is raised until the grid costs
81
+ * at most one page more than a perfectly packed render — trading the append-only
82
+ * cache freeze for ~2× fewer image tokens. Only correct when the upstream prefix
83
+ * cache is dead anyway (cold session, see node.ts session store); on a warm
84
+ * session it would re-key every frozen chunk. Default false. */
85
+ packFill: boolean;
86
+ /** Sticky lower bound for the freeze step, in messages. Once a session has been
87
+ * repacked at a coarser grid, every later turn must keep that grid or the
88
+ * re-render re-keys the whole history. Rounded UP to a power-of-two multiple of
89
+ * `freezeChunk` so chunk boundaries stay a subset of the base grid. Default 0. */
90
+ minFreezeStep: number;
91
+ /** Treat each closed assistant-tool/user-result pair as its own tool round.
92
+ * Safe only for clients that send a parallel batch as one assistant message
93
+ * (Claude Code). See {@link findClosedPrefixBoundary}. Default false. */
94
+ separateAdjacentToolPairs: boolean;
95
+ }
96
+ /** Images Anthropic accepts per request. Exceeding it fails the WHOLE request with
97
+ * an opaque `500` (observed 2026-07-31 at 387 images), not a typed 400 — so the
98
+ * cap has to be enforced on our side, before the wire. */
99
+ export declare const ANTHROPIC_MAX_IMAGES = 100;
100
+ /** Default history-image budget: the hard cap minus headroom for the slab, tool-doc
101
+ * and tool_result images that share the same request. transform.ts narrows this
102
+ * further with the count it has already emitted for this very request. */
103
+ export declare const ANTHROPIC_HISTORY_IMAGE_BUDGET = 80;
104
+ export declare const HISTORY_DEFAULTS: HistoryCollapseOptions;
105
+ /** Per-request metrics surfaced back to TransformInfo. */
106
+ export interface HistoryCollapseInfo {
107
+ /** Number of turns collapsed into the history image. */
108
+ collapsedTurns: number;
109
+ /** Total chars of text that went into the history image. */
110
+ collapsedChars: number;
111
+ /** Number of PNG image blocks emitted for the history (≥1 if collapsed). */
112
+ collapsedImages: number;
113
+ /** Total PNG bytes emitted. */
114
+ collapsedImageBytes: number;
115
+ /** Total pixel area (Σ width×height) — pairs with cache_create tokens for px/token regression. */
116
+ collapsedImagePixels: number;
117
+ /** Raw PNG bytes of each emitted history image, in order. Lets the caller register
118
+ * them into the dashboard image ring (info.imagePngs) so colored history frames are
119
+ * visible, not merely counted — every other image path already feeds the ring. */
120
+ collapsedPngs: Uint8Array[];
121
+ /** Per-image pixel dims, parallel to collapsedPngs. The dashboard ring reads
122
+ * info.imageDims in lockstep with info.imagePngs, so these must be pushed together. */
123
+ collapsedImageDims: {
124
+ width: number;
125
+ height: number;
126
+ }[];
127
+ /** Ordinal (0-based, into the emitted history images) of the last byte-stable
128
+ * history image — the carry-over cache anchor. The relocator pins the cache
129
+ * breakpoint here so it survives window advances (#11). Undefined when history is
130
+ * too short to have a fully grid-aligned chunk before collapseLen. */
131
+ carryOverImageOrdinal?: number;
132
+ /** Why we didn't collapse — populated only when no collapse happened. */
133
+ reason?: 'no_history' | 'prefix_too_short' | 'no_closed_prefix' | 'not_profitable' | 'render_empty' | 'over_budget';
134
+ /** Freeze step actually used (messages per chunk). Larger than `o.freezeChunk`
135
+ * when the image budget or fill-repack forced chunks to merge. The caller pins
136
+ * it per session (`minFreezeStep`) so the coarser grid never falls back — a
137
+ * fallback would re-key every frozen chunk it already paid to cache. */
138
+ freezeStep?: number;
139
+ /** True when the collapse range had to be shortened to stay inside the image
140
+ * budget; the dropped tail stays as live text. */
141
+ budgetTrimmed?: boolean;
142
+ /** Dropped codepoints from the history render, merged into the
143
+ * transform-wide map by the caller. */
144
+ droppedChars: number;
145
+ droppedCodepoints: Map<number, number>;
146
+ }
147
+ /**
148
+ * Return the last index ≤ cutoffExclusive at which all tool_use_ids are matched
149
+ * by tool_results in [0..i]. Returns -1 if no closed boundary exists.
150
+ * Robust to interleaved/parallel tool calls via openSet tracking. Consecutive
151
+ * assistant-tool/user-result pairs are treated as one tool round: some Anthropic
152
+ * clients serialize a parallel batch that way, so the apparently-closed gap
153
+ * between two pairs is not a safe collapse boundary.
154
+ *
155
+ * Pass `separateAdjacentToolPairs = true` only for clients that merge parallel
156
+ * tool calls into a single assistant message (e.g. Claude Code).
157
+ */
158
+ export declare function findClosedPrefixBoundary(messages: Message[], cutoffExclusive: number, separateAdjacentToolPairs?: boolean): number;
159
+ export declare function staleFreshnessHints(text: string): string;
160
+ /**
161
+ * Linearise content blocks to a single string. Drops thinking blocks (only the
162
+ * most-recent assistant turn needs bit-perfect thinking, and it's in the live tail).
163
+ * Inline images collapse to [image] to avoid double-encoding.
164
+ */
165
+ export declare function blocksToText(content: string | ContentBlock[]): string;
166
+ /** Return the caller's cache_control marker on a message, if any block carries one.
167
+ * Used to align freeze-chunk boundaries to roaming breakpoints so a marked segment
168
+ * stays independently cacheable instead of being silently flattened into the image. */
169
+ export declare function messageCacheControl(m: Message): CacheControl | undefined;
170
+ /** Serialize messages [fromInclusive..upToExclusive) to a text blob with
171
+ * `<role>…</role>` XML wrappers. Open+close tags bracket each turn so a misread
172
+ * boundary self-corrects and the model attributes speakers reliably even off a
173
+ * lossy image — bare `--- role ---` start-dividers let one role bleed into the
174
+ * next when a divider is missed. */
175
+ export declare function messagesToHistoryText(messages: Message[], upToExclusive: number, fromInclusive?: number): string;
176
+ /** Like {@link messagesToHistoryText} but also returns the parallel slot string for
177
+ * colorByRole: a width-identical copy where each `<role>` tag is replaced by its
178
+ * role marker and the body is copied verbatim (slot 0). Role attribution is decided
179
+ * HERE, where the message role is known — never re-parsed out of flattened text.
180
+ * A tool_result block sits inside its user message and a tool_use block inside its
181
+ * assistant message, so each is owned by the turn that carries it. */
182
+ export declare function messagesToHistorySegments(messages: Message[], upToExclusive: number, fromInclusive?: number): {
183
+ text: string;
184
+ slotText: string;
185
+ };
186
+ export declare function compactPreview(text: string): string;
187
+ export declare function verbatimTaskText(text: string): string;
188
+ /**
189
+ * Collapse the closed-prefix run into one synthetic user message with 1+ history images.
190
+ * Returns original messages unchanged on any no-collapse path (reason set in info).
191
+ * Image blocks are returned with NO cache_control — caller decides placement.
192
+ */
193
+ export declare function collapseHistory(messages: Message[], isProfitable: ProfitableFn, opts?: Partial<HistoryCollapseOptions>): Promise<{
194
+ messages: Message[];
195
+ info: HistoryCollapseInfo;
196
+ }>;
197
+ //# sourceMappingURL=history.d.ts.map