@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,2523 @@
1
+ /**
2
+ * OpenAI Chat Completions + Responses API transformer for the GPT-5 family.
3
+ * Separate from the Anthropic path: no cache-control breakpoints,
4
+ * images as image_url/input_image parts, system/developer messages in messages[]/input[].
5
+ * OpenAI tools keep native names/descriptions/schema shape; verbose schema prose
6
+ * is also rendered into images for token savings so calls do not depend only on OCR.
7
+ */
8
+ import { readBrandEnv } from './env.js';
9
+ import { renderTextToPngs, reflow, neutralizeSentinel, shrinkColsToContent, renderCellWidth, renderCellHeight, PAD_X, PAD_Y, READABLE_CHARS_PER_IMAGE, } from './render.js';
10
+ import { resolveGptProfile, } from './gpt-model-profiles.js';
11
+ import { bytesToBase64 } from './png.js';
12
+ import { applyClientSessionIdentity, compactSlabWhitespace, countVisualRows, estimateImageCount, resolveOpticalHistoryPolicy, sha8, splitStaticDynamic, } from './transform.js';
13
+ import { splitVolatileXmlIslands } from './schema-compiler.js';
14
+ import { visionTokens } from './vision-cost.js';
15
+ import { computeOpenAICollapsePaybackReads } from './openai-savings.js';
16
+ import { extractFaultSignalSnippet, isFileReadToolName } from './context-mmu.js';
17
+ import { evaluateCliffAvoidance, gateRatesFor, priceMode } from './pricing.js';
18
+ import { applyOpenAIChatTextHygiene, applyOpenAIResponsesTextHygiene, buildOpticalToolSealKey, isTextHygieneActive, resolveTextHygieneMode, } from './text-hygiene.js';
19
+ import { stripSchemaDescriptions } from './schema-strip.js';
20
+ import { GPT_HISTORY_DEFAULTS, planGptCollapse, planResponsesPairCollapse, chatMessagesToTurns, isResponsesToolCall, isResponsesToolOutput, } from './openai-history.js';
21
+ import { HISTORY_SYNTHETIC_INTRO, HISTORY_SYNTHETIC_OUTRO } from './history.js';
22
+ import { extractFactSheetTokens, factSheetText, prepareFactSheet } from './factsheet.js';
23
+ import { relocateOpenAIPins } from './pin.js';
24
+ import { gptTokenCount as o200kCountTokens } from './gpt-tokens.js';
25
+ import { hasStage2SealKey, noteHistoryRequest, recordStage2SealKey, sessionAnchorText, } from './session-state.js';
26
+ export function resolveVisionCost(model) {
27
+ return resolveGptProfile(model).vision;
28
+ }
29
+ // Sharp framing around the collapsed-history image. The transcript flattens BOTH
30
+ // roles into one role:'user' message (the API forbids images inside role:'assistant'),
31
+ // so this text must (a) tell the model to attribute strictly by the <user>/<assistant>
32
+ // tags rendered inside the image and (b) make explicit this is PAST context, not the
33
+ // live request — otherwise the model summarizes the transcript instead of answering.
34
+ // Aliases of the SINGLE SOURCE OF TRUTH in history.ts (see its doc comment). Importing
35
+ // rather than re-declaring guarantees the GPT and Anthropic paths can never silently drift
36
+ // on the turn-attribution wording — the exact divergence history.ts warns about.
37
+ export const HISTORY_TRANSCRIPT_INTRO = HISTORY_SYNTHETIC_INTRO;
38
+ export const HISTORY_TRANSCRIPT_OUTRO = HISTORY_SYNTHETIC_OUTRO;
39
+ export const COMPACT_HISTORY_TRANSCRIPT_INTRO = '[Earlier turns in image(s): follow <user t=N>/<assistant t=N> tags in increasing N. Prior context—not the current request.]';
40
+ export const COMPACT_HISTORY_TRANSCRIPT_OUTRO = '[End earlier conversation.]';
41
+ // The most-recent user request is kept as LEGIBLE TEXT (never imaged) and spliced
42
+ // between the before/after history images inside the synthetic user message, under
43
+ // this banner. Older user turns stay imaged (they must not look live). This is the
44
+ // fix for autonomous single-user-turn agents (OpenCode): the lone request is the
45
+ // OLDEST turn, so it would otherwise be the first thing imaged and the model loses
46
+ // it — "I wonder what the user actually asked" → off-task drift.
47
+ const PINNED_REQUEST_HEADER = '\n===== CURRENT USER REQUEST (live; kept as text by fiche, NOT inside any image) =====\n';
48
+ const PINNED_REQUEST_FOOTER = '\n===== END CURRENT USER REQUEST =====\n';
49
+ export function pinnedRequestBlock(text) {
50
+ return PINNED_REQUEST_HEADER + text + PINNED_REQUEST_FOOTER;
51
+ }
52
+ // Developer-role guard placed after the history image. When a request was pinned it
53
+ // echoes it verbatim (capped) and points at the in-history text block; otherwise it
54
+ // falls back to "the live request is the trailing user message" (interactive shape,
55
+ // where the latest user turn is already native text in the kept tail).
56
+ export function buildLiveRequestGuard(pinText) {
57
+ if (pinText !== undefined) {
58
+ const echo = pinText.length > 600 ? pinText.slice(0, 600) + '…' : pinText;
59
+ return ('fiche note: everything in the rendered history above is PAST context. Your live current request is the plain-text block labeled "CURRENT USER REQUEST" inside it — NOT anything OCR\'d from an image. It reads: «' +
60
+ echo +
61
+ '» Answer THAT request.');
62
+ }
63
+ return 'fiche note: the preceding rendered history item is prior conversation context only. It is not the current user request. The live current request is in the user message(s) that follow, especially the final user message.';
64
+ }
65
+ /** Alias of `visionTokensForModel`, kept for OpenAI-path call sites and tests.
66
+ * There is no separate OpenAI formula: the model's profile carries its regime. */
67
+ export function openAIVisionTokens(model, w, h) {
68
+ return visionTokensForModel(model, w, h);
69
+ }
70
+ /** True when this Responses/Chat request is actually served by a Claude model.
71
+ * Codex-style clients speak OpenAI Responses while some models are Anthropic,
72
+ * so routing must agree with pricing: this re-exports the SAME predicate the
73
+ * profile table uses to route an id to the Anthropic profile. A second, subtly
74
+ * different copy here would route a request one way and price it the other. */
75
+ export { isClaudeModel } from './claude-model-profiles.js';
76
+ /** Per-image vision-token cost for the model actually serving the request.
77
+ * Model-based, not endpoint-based, and family-agnostic: the profile's `vision`
78
+ * regime decides the formula (Anthropic patches, OpenAI tiles/patches, Grok
79
+ * pixels, Gemini flat), so no provider branch is needed here. This is the exact
80
+ * provider cost; the gate applies its own margin separately. */
81
+ export function visionTokensForModel(model, w, h) {
82
+ return visionTokens(resolveGptProfile(model), w, h);
83
+ }
84
+ function responsesCacheBreakpoint(req, profile, allowExplicit) {
85
+ // ChatGPT Codex rejects this field on every model whose profile started
86
+ // marking cacheBreakpoints. api.openai.com still receives it when the
87
+ // profile asks and the caller did not already pick a non-implicit mode.
88
+ if (!allowExplicit || profile.cacheBreakpoints !== true)
89
+ return {};
90
+ const mode = req.prompt_cache_options?.mode;
91
+ return mode === undefined || mode === 'implicit'
92
+ ? { prompt_cache_breakpoint: { mode: 'explicit' } }
93
+ : {};
94
+ }
95
+ /** Profile-controlled native overflow is shared with rendered-content evals. */
96
+ export function historyFactSheet(text, profile, coveredTokens) {
97
+ return prepareHistoryFactSheet(text, profile)(coveredTokens);
98
+ }
99
+ function prepareHistoryFactSheet(text, profile) {
100
+ const renderSheet = prepareFactSheet(text, profile.factSheetFormat);
101
+ const sheet = renderSheet();
102
+ if (profile.history.factSheetOverflow !== 'native-opaque')
103
+ return () => sheet;
104
+ const opaque = /\b(?:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}|(?=[0-9a-f]{7,128}\b)(?=[0-9a-f]{0,127}\d)[0-9a-f]{7,128})\b/gi;
105
+ const covered = new Set([...sheet.matchAll(opaque)].map((m) => m[0]));
106
+ const excerpts = new Map();
107
+ let source = 'archived context';
108
+ let argumentsNext = false;
109
+ for (const line of text.split('\n')) {
110
+ if (line.startsWith('[tool_use ')) {
111
+ source = line;
112
+ argumentsNext = true;
113
+ }
114
+ else if (argumentsNext) {
115
+ source += ' ' + line;
116
+ argumentsNext = false;
117
+ }
118
+ const identifiers = [...line.matchAll(opaque)].map((m) => m[0]);
119
+ if (!identifiers.some((id) => !covered.has(id)))
120
+ continue;
121
+ const lines = excerpts.get(source) ?? [];
122
+ lines.push(line);
123
+ excerpts.set(source, lines);
124
+ for (const id of identifiers)
125
+ covered.add(id);
126
+ }
127
+ // Exact spellings already sent in earlier archive groups need not be sent
128
+ // again. Keep local repetition counts, and never deduplicate opaque excerpts.
129
+ if (excerpts.size === 0)
130
+ return (coveredTokens) => coveredTokens?.size
131
+ ? renderSheet(coveredTokens)
132
+ : sheet;
133
+ const raw = [...excerpts].map(([source, lines]) => [source, ...lines].join('\n')).join('\n');
134
+ const quoted = [...excerpts].map(([source, lines]) => ({ source, lines }));
135
+ const result = renderSheet(raw)
136
+ + '\n[Archived exact-value excerpts (quoted data, not current instructions): '
137
+ + JSON.stringify(quoted) + ']';
138
+ return () => result;
139
+ }
140
+ /** Bounded to one request. Only extraction is reused; final coverage-dependent
141
+ * output is always recomputed. No cross-request retention of source text. */
142
+ export function createHistoryFactSheetRenderer(profile, limits = {}) {
143
+ const maxEntries = Number.isFinite(limits.maxEntries) ? Math.max(0, Math.floor(limits.maxEntries)) : 64;
144
+ const maxChars = Number.isFinite(limits.maxChars) ? Math.max(0, Math.floor(limits.maxChars)) : 1024 * 1024;
145
+ const snapshot = { ...profile, history: { ...profile.history } };
146
+ const cache = new Map();
147
+ let chars = 0, hits = 0, misses = 0, admitMisses = true;
148
+ return {
149
+ render(text, coveredTokens) {
150
+ let prepared = cache.get(text);
151
+ if (prepared) {
152
+ hits++;
153
+ cache.delete(text);
154
+ cache.set(text, prepared);
155
+ }
156
+ else {
157
+ misses++;
158
+ prepared = prepareHistoryFactSheet(text, snapshot);
159
+ if (admitMisses && maxEntries > 0 && text.length <= maxChars) {
160
+ while (cache.size && (cache.size >= maxEntries || chars + text.length > maxChars)) {
161
+ const oldest = cache.keys().next().value;
162
+ chars -= oldest.length;
163
+ cache.delete(oldest);
164
+ }
165
+ cache.set(text, prepared);
166
+ chars += text.length;
167
+ }
168
+ }
169
+ return prepared(coveredTokens);
170
+ },
171
+ // Emission is a second sequential pass. Misses there must not evict
172
+ // prepared gate results that later segments can still reuse.
173
+ beginEmission: () => { admitMisses = false; },
174
+ stats: () => ({ entries: cache.size, chars, hits, misses }),
175
+ };
176
+ }
177
+ const DEFAULTS = {
178
+ compress: true,
179
+ imageCompress: true,
180
+ opticalMode: 'auto',
181
+ textHygiene: 'auto',
182
+ expectedOutputTokens: 1000,
183
+ compressTools: true,
184
+ compressToolResults: true,
185
+ minCompressChars: 2000,
186
+ cols: undefined,
187
+ charsPerToken: 4, // conservative OpenAI default; override after calibration
188
+ explicitCharsPerToken: false,
189
+ reflow: true,
190
+ collapseHistory: true,
191
+ explicitPromptCacheBreakpoints: true,
192
+ stageToggles: {},
193
+ cleanUserPayloads: false,
194
+ };
195
+ function resolveOptions(opts) {
196
+ return {
197
+ compress: opts.compress ?? DEFAULTS.compress,
198
+ imageCompress: opts.imageCompress ?? DEFAULTS.imageCompress,
199
+ opticalMode: opts.opticalMode ?? DEFAULTS.opticalMode,
200
+ textHygiene: opts.textHygiene ?? DEFAULTS.textHygiene,
201
+ expectedOutputTokens: opts.expectedOutputTokens ?? DEFAULTS.expectedOutputTokens,
202
+ compressTools: opts.compressTools ?? DEFAULTS.compressTools,
203
+ compressToolResults: opts.compressToolResults ?? DEFAULTS.compressToolResults,
204
+ minCompressChars: opts.minCompressChars ?? DEFAULTS.minCompressChars,
205
+ cols: opts.cols,
206
+ charsPerToken: opts.charsPerToken ?? DEFAULTS.charsPerToken,
207
+ explicitCharsPerToken: opts.charsPerToken !== undefined,
208
+ reflow: opts.reflow ?? DEFAULTS.reflow,
209
+ collapseHistory: opts.collapseHistory ?? DEFAULTS.collapseHistory,
210
+ gptHistory: opts.gptHistory,
211
+ explicitPromptCacheBreakpoints: opts.explicitPromptCacheBreakpoints !== false,
212
+ stageToggles: opts.stageToggles ?? {},
213
+ cleanUserPayloads: opts.cleanUserPayloads !== undefined
214
+ ? opts.cleanUserPayloads === true
215
+ : resolveTextHygieneMode(opts.textHygiene ?? DEFAULTS.textHygiene) === 'on',
216
+ clientSessionId: opts.clientSessionId,
217
+ clientSessionSource: opts.clientSessionSource,
218
+ claudeCodeSessionId: opts.claudeCodeSessionId,
219
+ };
220
+ }
221
+ /** History-collapse options for both Chat and Responses. Profile geometry is
222
+ * the single source of truth; Grok allows more pages because leftover plain
223
+ * history is expensive on its pixel bill + weak cache discount. */
224
+ function configuredHistoryMaxImages(model) {
225
+ const fallback = resolveGptProfile(model).history.maxImages;
226
+ const raw = readBrandEnv('GPT_HISTORY_MAX_IMAGES');
227
+ if (!raw)
228
+ return fallback;
229
+ const parsed = Number.parseInt(raw, 10);
230
+ // Responses providers impose their own total image caps. Keep a defensive ceiling
231
+ // while allowing long Sol sessions to opt into substantially more coverage.
232
+ return Number.isFinite(parsed) ? Math.max(1, Math.min(100, parsed)) : fallback;
233
+ }
234
+ function countRequestImages(messages) {
235
+ let count = 0;
236
+ for (const msg of messages) {
237
+ if (Array.isArray(msg.content)) {
238
+ for (const part of msg.content) {
239
+ if (typeof part === 'object' && part !== null && 'type' in part && part.type === 'image_url') {
240
+ count++;
241
+ }
242
+ }
243
+ }
244
+ }
245
+ return count;
246
+ }
247
+ function gptHistoryOpts(model, o, profile, slabImages = 0, clientImages = 0) {
248
+ const configuredMax = o.gptHistory?.maxImages ?? configuredHistoryMaxImages(model);
249
+ // Separate fiche's history-image budget from late client screenshots so adding a
250
+ // user/tool screenshot never shrinks the history budget and un-collapses sealed segments.
251
+ // Only providers with a hard total-image cap subtract clientImages from headroom.
252
+ const historyBudget = Math.max(0, configuredMax - slabImages);
253
+ const remainingMax = profile.providerImageCap !== undefined
254
+ ? Math.max(0, Math.min(historyBudget, profile.providerImageCap - slabImages - clientImages))
255
+ : historyBudget;
256
+ return {
257
+ ...o.gptHistory,
258
+ reflow: o.gptHistory?.reflow ?? profile.history.reflow ?? o.reflow,
259
+ keepTail: o.gptHistory?.keepTail ?? profile.history.keepTail,
260
+ keepRecentPairs: o.gptHistory?.keepRecentPairs ?? profile.history.keepRecentPairs,
261
+ minCollapseTokens: o.gptHistory?.minCollapseTokens ?? profile.history.minCollapseTokens,
262
+ ...(o.gptHistory?.minCollapsePrefix !== undefined || profile.history.minCollapsePrefix !== undefined
263
+ ? { minCollapsePrefix: o.gptHistory?.minCollapsePrefix ?? profile.history.minCollapsePrefix }
264
+ : {}),
265
+ ...(o.gptHistory?.collapseChunk !== undefined || profile.history.collapseChunk !== undefined
266
+ ? { collapseChunk: o.gptHistory?.collapseChunk ?? profile.history.collapseChunk }
267
+ : {}),
268
+ freezeChunk: o.gptHistory?.freezeChunk ?? profile.history.freezeChunk ?? GPT_HISTORY_DEFAULTS.freezeChunk,
269
+ responsesMode: profile.history.responsesMode,
270
+ cols: o.gptHistory?.cols ?? profile.stripCols,
271
+ maxHeightPx: o.gptHistory?.maxHeightPx ?? profile.maxHeightPx,
272
+ style: o.gptHistory?.style ?? profile.style,
273
+ maxImages: remainingMax,
274
+ };
275
+ }
276
+ function emptyInfo(reason) {
277
+ return {
278
+ compressed: false,
279
+ reason,
280
+ origChars: 0,
281
+ compressedChars: 0,
282
+ imageCount: 0,
283
+ imageBytes: 0,
284
+ staticChars: 0,
285
+ dynamicChars: 0,
286
+ dynamicBlockCount: 0,
287
+ droppedChars: 0,
288
+ };
289
+ }
290
+ export function prepareImagedRenderText(text, reflowEnabled) {
291
+ return maybeReflow(text.trimEnd(), reflowEnabled);
292
+ }
293
+ function maybeReflow(text, enabled) {
294
+ if (!enabled)
295
+ return text;
296
+ const safe = neutralizeSentinel(text);
297
+ return reflow(safe) ?? safe;
298
+ }
299
+ function isTextPart(part) {
300
+ return (typeof part === 'object'
301
+ && part !== null
302
+ && part.type === 'text'
303
+ && typeof part.text === 'string');
304
+ }
305
+ function contentText(content) {
306
+ if (typeof content === 'string')
307
+ return content;
308
+ if (!Array.isArray(content))
309
+ return '';
310
+ return content
311
+ .filter(isTextPart)
312
+ .map((p) => p.text)
313
+ .join('\n\n');
314
+ }
315
+ function setTextContent(msg, text) {
316
+ if (Array.isArray(msg.content)) {
317
+ const kept = msg.content.filter((p) => !isTextPart(p));
318
+ msg.content = [{ type: 'text', text }, ...kept];
319
+ }
320
+ else {
321
+ msg.content = text;
322
+ }
323
+ }
324
+ function firstUserText(req) {
325
+ const texts = [];
326
+ for (const msg of req.messages) {
327
+ if (!msg || typeof msg !== 'object')
328
+ continue;
329
+ if (msg.role === 'system' || msg.role === 'developer') {
330
+ if (texts.length > 0)
331
+ break;
332
+ continue;
333
+ }
334
+ if (msg.role !== 'user')
335
+ break;
336
+ const t = contentText(msg.content);
337
+ if (t.trim())
338
+ texts.push(t);
339
+ }
340
+ return sessionAnchorText(texts).slice(0, 4096);
341
+ }
342
+ function responsesContentText(content) {
343
+ if (typeof content === 'string')
344
+ return content;
345
+ if (!Array.isArray(content))
346
+ return '';
347
+ return content
348
+ .filter((p) => typeof p === 'object'
349
+ && p !== null
350
+ && (p.type === 'input_text' ||
351
+ p.type === 'output_text' ||
352
+ p.type === 'text')
353
+ && typeof p.text === 'string')
354
+ .map((p) => p.text)
355
+ .join('\n\n');
356
+ }
357
+ function firstResponsesUserText(inputWasString, originalInput, inputItems) {
358
+ if (inputWasString) {
359
+ return originalInput ? sessionAnchorText([originalInput]).slice(0, 4096) : '';
360
+ }
361
+ const texts = [];
362
+ for (const item of inputItems) {
363
+ if (!item || typeof item !== 'object')
364
+ continue;
365
+ const role = item.role;
366
+ const type = item.type;
367
+ if (role === 'system' || role === 'developer') {
368
+ if (texts.length > 0)
369
+ break;
370
+ continue;
371
+ }
372
+ if (role !== 'user') {
373
+ if (role || type === 'function_call' || type === 'function_call_output' || type === 'custom_tool_call')
374
+ break;
375
+ continue;
376
+ }
377
+ const t = responsesContentText(item.content);
378
+ if (t.trim())
379
+ texts.push(t);
380
+ }
381
+ return sessionAnchorText(texts).slice(0, 4096);
382
+ }
383
+ function extractChatLiveTailTexts(messages) {
384
+ if (!Array.isArray(messages) || messages.length === 0)
385
+ return [];
386
+ const out = [];
387
+ const last = messages[messages.length - 1];
388
+ if (!last || typeof last !== 'object')
389
+ return out;
390
+ if (last.role === 'tool') {
391
+ let toolStart = messages.length - 1;
392
+ while (toolStart > 0 && messages[toolStart - 1]?.role === 'tool') {
393
+ toolStart--;
394
+ }
395
+ const prev = toolStart > 0 ? messages[toolStart - 1] : undefined;
396
+ // Only pull tool_calls names/arguments from the preceding assistant message —
397
+ // never Turn t-1's user prompt prose or assistant prose.
398
+ if (prev && prev.role === 'assistant' && Array.isArray(prev.tool_calls)) {
399
+ for (const tc of prev.tool_calls) {
400
+ const fn = tc && typeof tc === 'object' ? tc.function : undefined;
401
+ if (fn && typeof fn.arguments === 'string' && fn.arguments.trim()) {
402
+ out.push(typeof fn.name === 'string' ? `${fn.name} ${fn.arguments}` : fn.arguments);
403
+ }
404
+ }
405
+ }
406
+ for (let i = toolStart; i < messages.length; i++) {
407
+ const msg = messages[i];
408
+ if (!msg || typeof msg !== 'object')
409
+ continue;
410
+ const t = contentText(msg.content);
411
+ const faultSnippet = extractFaultSignalSnippet(t) ?? (t.length <= 1024 && t.trim() ? t : undefined);
412
+ if (faultSnippet)
413
+ out.push(faultSnippet);
414
+ }
415
+ return out;
416
+ }
417
+ if (last.role === 'user') {
418
+ let toolEnd = messages.length - 1;
419
+ let toolStart = toolEnd;
420
+ while (toolStart > 0 && messages[toolStart - 1]?.role === 'tool') {
421
+ toolStart--;
422
+ }
423
+ for (let i = toolStart; i < toolEnd; i++) {
424
+ const msg = messages[i];
425
+ if (!msg || typeof msg !== 'object')
426
+ continue;
427
+ const faultSnippet = extractFaultSignalSnippet(contentText(msg.content));
428
+ if (faultSnippet)
429
+ out.push(faultSnippet);
430
+ }
431
+ }
432
+ const t = contentText(last.content);
433
+ if (t.trim())
434
+ out.push(t);
435
+ if (Array.isArray(last.tool_calls)) {
436
+ for (const tc of last.tool_calls) {
437
+ const fn = tc && typeof tc === 'object' ? tc.function : undefined;
438
+ if (fn && typeof fn.arguments === 'string' && fn.arguments.trim()) {
439
+ out.push(typeof fn.name === 'string' ? `${fn.name} ${fn.arguments}` : fn.arguments);
440
+ }
441
+ }
442
+ }
443
+ return out;
444
+ }
445
+ function appendChatTailHydration(req, hydrationBlock) {
446
+ if (!hydrationBlock)
447
+ return;
448
+ if (!Array.isArray(req.messages) || req.messages.length === 0)
449
+ return;
450
+ // Never walk backwards past an assistant/tool sequence into Turn-1 messages.
451
+ // Only append to the trailing live user or trailing tool-result message.
452
+ const last = req.messages[req.messages.length - 1];
453
+ if (!last || (last.role !== 'user' && last.role !== 'tool'))
454
+ return;
455
+ if (typeof last.content === 'string') {
456
+ last.content = last.content ? `${last.content}\n\n${hydrationBlock}` : hydrationBlock;
457
+ return;
458
+ }
459
+ if (Array.isArray(last.content)) {
460
+ last.content.push({ type: 'text', text: hydrationBlock });
461
+ }
462
+ }
463
+ function extractResponsesLiveTailTexts(inputWasString, originalInput, inputItems) {
464
+ if (inputWasString)
465
+ return originalInput ? [originalInput] : [];
466
+ if (!Array.isArray(inputItems) || inputItems.length === 0)
467
+ return [];
468
+ const out = [];
469
+ const isToolOutputItem = (item) => {
470
+ if (!item || typeof item !== 'object')
471
+ return false;
472
+ const t = item.type;
473
+ return t === 'function_call_output' || t === 'custom_tool_call_output';
474
+ };
475
+ const isToolCallItem = (item) => {
476
+ if (!item || typeof item !== 'object')
477
+ return false;
478
+ const t = item.type;
479
+ return t === 'function_call' || t === 'custom_tool_call';
480
+ };
481
+ const pushCallItem = (item) => {
482
+ if (!item || typeof item !== 'object')
483
+ return;
484
+ const rec = item;
485
+ if (typeof rec.arguments === 'string' && rec.arguments.trim()) {
486
+ out.push(typeof rec.name === 'string' ? `${rec.name} ${rec.arguments}` : rec.arguments);
487
+ }
488
+ else if (typeof rec.input === 'string' && rec.input.trim()) {
489
+ out.push(typeof rec.name === 'string' ? `${rec.name} ${rec.input}` : rec.input);
490
+ }
491
+ };
492
+ const last = inputItems[inputItems.length - 1];
493
+ if (!last || typeof last !== 'object')
494
+ return out;
495
+ if (isToolOutputItem(last)) {
496
+ let tailStart = inputItems.length - 1;
497
+ while (tailStart > 0 && isToolOutputItem(inputItems[tailStart - 1])) {
498
+ tailStart--;
499
+ }
500
+ // Pull ONLY preceding tool call names/arguments — never Turn t-1's user prompt prose.
501
+ let callStart = tailStart;
502
+ while (callStart > 0 && isToolCallItem(inputItems[callStart - 1])) {
503
+ callStart--;
504
+ }
505
+ for (let i = callStart; i < tailStart; i++) {
506
+ pushCallItem(inputItems[i]);
507
+ }
508
+ for (let i = tailStart; i < inputItems.length; i++) {
509
+ const rec = inputItems[i];
510
+ if (rec.output !== undefined) {
511
+ const rawOut = typeof rec.output === 'string' ? rec.output : JSON.stringify(rec.output);
512
+ const faultSnippet = extractFaultSignalSnippet(rawOut) ?? (rawOut.length <= 1024 && rawOut.trim() ? rawOut : undefined);
513
+ if (faultSnippet)
514
+ out.push(faultSnippet);
515
+ }
516
+ }
517
+ return out;
518
+ }
519
+ const rec = last;
520
+ if (rec.role === 'user') {
521
+ let toolEnd = inputItems.length - 1;
522
+ let toolStart = toolEnd;
523
+ while (toolStart > 0 && isToolOutputItem(inputItems[toolStart - 1])) {
524
+ toolStart--;
525
+ }
526
+ for (let i = toolStart; i < toolEnd; i++) {
527
+ const prevOut = inputItems[i];
528
+ if (prevOut.output !== undefined) {
529
+ const faultSnippet = extractFaultSignalSnippet(typeof prevOut.output === 'string' ? prevOut.output : JSON.stringify(prevOut.output));
530
+ if (faultSnippet)
531
+ out.push(faultSnippet);
532
+ }
533
+ }
534
+ }
535
+ pushCallItem(rec);
536
+ if (typeof rec.content === 'string' && rec.content.trim()) {
537
+ out.push(rec.content);
538
+ }
539
+ else if (Array.isArray(rec.content)) {
540
+ const txt = responsesContentText(rec.content);
541
+ if (txt.trim())
542
+ out.push(txt);
543
+ }
544
+ return out;
545
+ }
546
+ function appendResponsesTailHydration(req, hydrationBlock) {
547
+ if (!hydrationBlock)
548
+ return;
549
+ if (typeof req.input === 'string') {
550
+ req.input = req.input ? `${req.input}\n\n${hydrationBlock}` : hydrationBlock;
551
+ return;
552
+ }
553
+ if (!Array.isArray(req.input))
554
+ req.input = [];
555
+ const items = req.input;
556
+ const last = items[items.length - 1];
557
+ if (last && last.role === 'user') {
558
+ if (typeof last.content === 'string') {
559
+ last.content = last.content ? `${last.content}\n\n${hydrationBlock}` : hydrationBlock;
560
+ return;
561
+ }
562
+ if (Array.isArray(last.content)) {
563
+ last.content.push({ type: 'input_text', text: hydrationBlock });
564
+ return;
565
+ }
566
+ }
567
+ items.push({ type: 'message', role: 'user', content: [{ type: 'input_text', text: hydrationBlock }] });
568
+ }
569
+ function isFunctionTool(tool) {
570
+ return (typeof tool === 'object'
571
+ && tool !== null
572
+ && tool.type === 'function'
573
+ && typeof tool.function === 'object'
574
+ && tool.function !== null);
575
+ }
576
+ function isFlatFunctionTool(tool) {
577
+ return (typeof tool === 'object'
578
+ && tool !== null
579
+ && tool.type === 'function'
580
+ && typeof tool.name === 'string');
581
+ }
582
+ /** Render schema annotations removed from the native tool definition. The full
583
+ * top-level description rides in the same image and is replaced by a short
584
+ * per-tool pointer, matching the Anthropic tool-reference approach. */
585
+ export function schemaAnnotationLines(node, path = '$', depth = 0) {
586
+ if (!node || typeof node !== 'object' || depth > 20)
587
+ return [];
588
+ if (Array.isArray(node)) {
589
+ return node.flatMap((value, i) => schemaAnnotationLines(value, `${path}[${i}]`, depth + 1));
590
+ }
591
+ const obj = node;
592
+ const out = [];
593
+ for (const key of ['description', 'title', 'examples', 'default', '$comment']) {
594
+ if (obj[key] !== undefined)
595
+ out.push(`${path} ${key}: ${JSON.stringify(obj[key])}`);
596
+ }
597
+ if (typeof obj.format === 'string' && obj.format.length > 32) {
598
+ out.push(`${path} format: ${JSON.stringify(obj.format)}`);
599
+ }
600
+ for (const key of ['properties', 'patternProperties', 'definitions', '$defs']) {
601
+ const children = obj[key];
602
+ if (!children || typeof children !== 'object' || Array.isArray(children))
603
+ continue;
604
+ for (const [name, child] of Object.entries(children)) {
605
+ out.push(...schemaAnnotationLines(child, `${path}.${name}`, depth + 1));
606
+ }
607
+ }
608
+ for (const key of ['oneOf', 'anyOf', 'allOf']) {
609
+ const children = obj[key];
610
+ if (!Array.isArray(children))
611
+ continue;
612
+ children.forEach((child, i) => {
613
+ out.push(...schemaAnnotationLines(child, `${path}.${key}[${i}]`, depth + 1));
614
+ });
615
+ }
616
+ for (const key of [
617
+ 'items', 'additionalProperties', 'not', 'contains', 'propertyNames',
618
+ 'unevaluatedItems', 'unevaluatedProperties', 'if', 'then', 'else',
619
+ ]) {
620
+ if (obj[key] !== undefined) {
621
+ out.push(...schemaAnnotationLines(obj[key], `${path}.${key}`, depth + 1));
622
+ }
623
+ }
624
+ return out;
625
+ }
626
+ function renderToolDoc(tool) {
627
+ const f = tool.function;
628
+ const annotations = schemaAnnotationLines(f.parameters);
629
+ return f.description || annotations.length
630
+ ? [`## Tool: ${f.name ?? '?'}`, f.description ?? '', ...annotations].filter(Boolean).join('\n')
631
+ : '';
632
+ }
633
+ function renderFlatToolDoc(tool) {
634
+ const annotations = schemaAnnotationLines(tool.parameters);
635
+ return tool.description || annotations.length
636
+ ? [`## Tool: ${tool.name ?? '?'}`, tool.description ?? '', ...annotations].filter(Boolean).join('\n')
637
+ : '';
638
+ }
639
+ function rewriteToolsForGpt(tools) {
640
+ if (!Array.isArray(tools) || tools.length === 0)
641
+ return { tools, docs: '' };
642
+ const docs = [];
643
+ let changed = false;
644
+ const rewritten = tools.map((tool) => {
645
+ if (!isFunctionTool(tool))
646
+ return tool;
647
+ const doc = renderToolDoc(tool);
648
+ if (doc)
649
+ docs.push(doc);
650
+ if (tool.function.parameters === undefined)
651
+ return tool;
652
+ changed = true;
653
+ return {
654
+ ...tool,
655
+ function: {
656
+ ...tool.function,
657
+ description: `Full docs: see "## Tool: ${tool.function.name ?? '?'}" in the rendered context image.`,
658
+ parameters: stripSchemaDescriptions(tool.function.parameters),
659
+ },
660
+ };
661
+ });
662
+ return { tools: changed ? rewritten : tools, docs: docs.join('\n\n') };
663
+ }
664
+ function rewriteFlatToolsForGpt(tools) {
665
+ if (!Array.isArray(tools) || tools.length === 0)
666
+ return { tools, docs: '' };
667
+ const docs = [];
668
+ let changed = false;
669
+ const rewritten = tools.map((tool) => {
670
+ if (!isFlatFunctionTool(tool))
671
+ return tool;
672
+ const doc = renderFlatToolDoc(tool);
673
+ if (doc)
674
+ docs.push(doc);
675
+ if (tool.parameters === undefined)
676
+ return tool;
677
+ changed = true;
678
+ return {
679
+ ...tool,
680
+ description: `Full docs: see "## Tool: ${tool.name ?? '?'}" in the rendered context image.`,
681
+ parameters: stripSchemaDescriptions(tool.parameters),
682
+ };
683
+ });
684
+ return { tools: changed ? rewritten : tools, docs: docs.join('\n\n') };
685
+ }
686
+ /** Shared by normal outbound requests and profile-aligned evaluations. */
687
+ export function openAIImageDetail(model) {
688
+ const isGpt5Family = typeof model === 'string' && /^gpt-5/i.test(model);
689
+ return resolveGptProfile(model).imageDetail ?? (isGpt5Family ? 'original' : 'high');
690
+ }
691
+ function openAIImagePart(img, model) {
692
+ return {
693
+ type: 'image_url',
694
+ image_url: {
695
+ url: `data:image/png;base64,${bytesToBase64(img.png)}`,
696
+ detail: openAIImageDetail(model),
697
+ },
698
+ };
699
+ }
700
+ /** Build a Responses API input_image part. */
701
+ function responsesImagePart(img, model) {
702
+ return {
703
+ type: 'input_image',
704
+ image_url: `data:image/png;base64,${bytesToBase64(img.png)}`,
705
+ detail: openAIImageDetail(model),
706
+ };
707
+ }
708
+ function countOutgoingTextChars(req) {
709
+ let n = 0;
710
+ for (const msg of req.messages)
711
+ n += contentText(msg.content).length;
712
+ if (Array.isArray(req.tools)) {
713
+ for (const tool of req.tools) {
714
+ if (!isFunctionTool(tool))
715
+ continue;
716
+ const f = tool.function;
717
+ if (typeof f.name === 'string')
718
+ n += f.name.length;
719
+ if (typeof f.description === 'string')
720
+ n += f.description.length;
721
+ if (f.parameters !== undefined)
722
+ n += safeStringifyLen(f.parameters);
723
+ }
724
+ }
725
+ return n;
726
+ }
727
+ /** Bounded LRU cache for opaque reasoning/compaction blobs so immutable
728
+ * Codex `encrypted_content` items are not re-serialized & o200k-tokenized on every turn. */
729
+ const OPAQUE_ITEM_TOKEN_CACHE = new Map();
730
+ const OPAQUE_ITEM_CACHE_MAX = 256;
731
+ function dualDigest64Hex(s) {
732
+ let h1 = 0x811c9dc5 >>> 0;
733
+ let h2 = 0x9e3779b1 >>> 0;
734
+ for (let i = 0; i < s.length; i++) {
735
+ const c = s.charCodeAt(i);
736
+ h1 = Math.imul((h1 ^ c) >>> 0, 0x01000193) >>> 0;
737
+ h2 = Math.imul((h2 ^ ((c + (i & 0xff)) >>> 0)) >>> 0, 0x85ebca6b) >>> 0;
738
+ }
739
+ return (h1 >>> 0).toString(16).padStart(8, '0') + (h2 >>> 0).toString(16).padStart(8, '0');
740
+ }
741
+ function cachedOpaqueItemTokens(o) {
742
+ const enc = typeof o.encrypted_content === 'string' ? o.encrypted_content : undefined;
743
+ const keyCount = Object.keys(o).length;
744
+ if (enc && enc.length >= 256 && keyCount <= 6) {
745
+ const itemType = typeof o.type === 'string' ? o.type : '';
746
+ const id = typeof o.id === 'string' ? o.id : '';
747
+ const cacheKey = `${itemType}:${id}:${keyCount}:${enc.length}:${dualDigest64Hex(enc)}`;
748
+ const hit = OPAQUE_ITEM_TOKEN_CACHE.get(cacheKey);
749
+ if (hit !== undefined) {
750
+ OPAQUE_ITEM_TOKEN_CACHE.delete(cacheKey);
751
+ OPAQUE_ITEM_TOKEN_CACHE.set(cacheKey, hit);
752
+ return hit;
753
+ }
754
+ const tokens = gptTextTokens(JSON.stringify(o));
755
+ if (OPAQUE_ITEM_TOKEN_CACHE.size >= OPAQUE_ITEM_CACHE_MAX) {
756
+ const oldest = OPAQUE_ITEM_TOKEN_CACHE.keys().next().value;
757
+ if (oldest !== undefined)
758
+ OPAQUE_ITEM_TOKEN_CACHE.delete(oldest);
759
+ }
760
+ OPAQUE_ITEM_TOKEN_CACHE.set(cacheKey, tokens);
761
+ return tokens;
762
+ }
763
+ return gptTextTokens(JSON.stringify(o));
764
+ }
765
+ function responsesOutputTextOnly(output) {
766
+ if (typeof output === 'string')
767
+ return output;
768
+ if (Array.isArray(output)) {
769
+ const texts = [];
770
+ for (const part of output) {
771
+ if (!part || typeof part !== 'object')
772
+ continue;
773
+ const p = part;
774
+ const t = typeof p.type === 'string' ? p.type : '';
775
+ if (t === 'input_image' || t === 'image' || t === 'output_image' || t === 'image_url')
776
+ continue;
777
+ if ((t === 'input_text' || t === 'output_text' || t === 'text' || !t) && typeof p.text === 'string') {
778
+ texts.push(p.text);
779
+ }
780
+ else if (typeof p.content === 'string') {
781
+ texts.push(p.content);
782
+ }
783
+ }
784
+ return texts.join('\n\n');
785
+ }
786
+ if (output !== undefined && output !== null) {
787
+ try {
788
+ return JSON.stringify(output) ?? '';
789
+ }
790
+ catch {
791
+ return '';
792
+ }
793
+ }
794
+ return '';
795
+ }
796
+ /** Local o200k decomposition of the original Responses request. This is
797
+ * diagnostic only and never calls Anthropic/provider count_tokens. */
798
+ function measureResponsesComposition(req, inputWasString, originalInputString, inputItems) {
799
+ const c = {
800
+ instructions: gptTextTokens(typeof req.instructions === 'string' ? req.instructions : ''),
801
+ systemDeveloper: 0,
802
+ userAssistant: 0,
803
+ functionCalls: 0,
804
+ functionOutputs: 0,
805
+ reasoningEncrypted: 0,
806
+ compactionOpaque: 0,
807
+ toolsJson: Array.isArray(req.tools) ? gptTextTokens(JSON.stringify(req.tools)) : 0,
808
+ other: 0,
809
+ totalLocal: 0,
810
+ imageParts: 0,
811
+ };
812
+ if (inputWasString) {
813
+ c.userAssistant += gptTextTokens(originalInputString ?? '');
814
+ }
815
+ const countImages = (content) => {
816
+ if (!Array.isArray(content))
817
+ return 0;
818
+ return content.filter((p) => {
819
+ const type = p?.type;
820
+ return type === 'input_image' || type === 'image' || type === 'output_image';
821
+ }).length;
822
+ };
823
+ for (const item of inputItems) {
824
+ const o = item;
825
+ const type = typeof o.type === 'string' ? o.type : '';
826
+ const role = typeof o.role === 'string' ? o.role : '';
827
+ c.imageParts += countImages(o.content);
828
+ if (role === 'system' || role === 'developer') {
829
+ c.systemDeveloper += gptTextTokens(responsesContentText(o.content));
830
+ }
831
+ else if (role === 'user' || role === 'assistant') {
832
+ c.userAssistant += gptTextTokens(responsesContentText(o.content));
833
+ }
834
+ else if (isResponsesToolCall(o)) {
835
+ c.functionCalls += gptTextTokens(JSON.stringify(o));
836
+ }
837
+ else if (isResponsesToolOutput(o)) {
838
+ c.functionOutputs += gptTextTokens(responsesOutputTextOnly(o.output));
839
+ c.imageParts += countImages(o.output);
840
+ }
841
+ else if (type === 'reasoning') {
842
+ // Includes encrypted_content when present; this is often a large Codex-native bucket.
843
+ c.reasoningEncrypted += cachedOpaqueItemTokens(o);
844
+ }
845
+ else if (type === 'compaction' || type === 'compaction_trigger' ||
846
+ type === 'context_compaction' || type === 'item_reference') {
847
+ c.compactionOpaque += cachedOpaqueItemTokens(o);
848
+ }
849
+ else if (!role && type) {
850
+ c.other += gptTextTokens(JSON.stringify(o));
851
+ }
852
+ }
853
+ c.totalLocal = c.instructions + c.systemDeveloper + c.userAssistant +
854
+ c.functionCalls + c.functionOutputs + c.reasoningEncrypted +
855
+ c.compactionOpaque + c.toolsJson + c.other;
856
+ return c;
857
+ }
858
+ function countResponsesOutgoingTextChars(req) {
859
+ let n = 0;
860
+ if (typeof req.instructions === 'string')
861
+ n += req.instructions.length;
862
+ if (typeof req.input === 'string') {
863
+ n += req.input.length;
864
+ }
865
+ else if (Array.isArray(req.input)) {
866
+ for (const item of req.input) {
867
+ n += responsesContentText(item.content).length;
868
+ }
869
+ }
870
+ if (Array.isArray(req.tools)) {
871
+ for (const tool of req.tools) {
872
+ if (!isFlatFunctionTool(tool))
873
+ continue;
874
+ if (typeof tool.name === 'string')
875
+ n += tool.name.length;
876
+ if (typeof tool.description === 'string')
877
+ n += tool.description.length;
878
+ if (tool.parameters !== undefined)
879
+ n += safeStringifyLen(tool.parameters);
880
+ }
881
+ }
882
+ return n;
883
+ }
884
+ function safeStringifyLen(v) {
885
+ try {
886
+ return JSON.stringify(v)?.length ?? 0;
887
+ }
888
+ catch {
889
+ return 0;
890
+ }
891
+ }
892
+ export function droppedCodepointsTop(droppedCodepoints) {
893
+ if (droppedCodepoints.size === 0)
894
+ return undefined;
895
+ const out = {};
896
+ for (const [cp, count] of [...droppedCodepoints.entries()]
897
+ .sort((a, b) => b[1] - a[1])
898
+ .slice(0, 20)) {
899
+ out[`U+${cp.toString(16).toUpperCase().padStart(4, '0')}`] = count;
900
+ }
901
+ return out;
902
+ }
903
+ /** Shared gate: image vs text token cost → profitability.
904
+ *
905
+ * Profiles with a local-token floor always use o200k (same baseline as savings
906
+ * math). Legacy non-o200k profiles retain the charsPerToken override. Images bill full
907
+ * pages at maxHeight and the last page at residual height — charging every page
908
+ * as a full strip over-states cost and blocks profitable collapses. */
909
+ function evalOpenAIGate(model, renderedText, cols, charsPerToken, baselineTextTokens) {
910
+ const profile = resolveGptProfile(model);
911
+ const style = profile.style;
912
+ const cellW = renderCellWidth(style);
913
+ const cellH = renderCellHeight(style);
914
+ const stripW = 2 * PAD_X + cols * cellW;
915
+ const canvasRows = Math.max(1, Math.floor((profile.maxHeightPx - 2 * PAD_Y) / cellH));
916
+ const fullPageHeight = 2 * PAD_Y + canvasRows * cellH;
917
+ const maxLines = canvasRows;
918
+ const maxCharsPerImage = Math.min(READABLE_CHARS_PER_IMAGE, Math.max(1, cols) * maxLines);
919
+ const linesPerImage = Math.min(maxLines, Math.max(1, Math.floor(maxCharsPerImage / Math.max(1, cols))));
920
+ const estImages = estimateImageCount(renderedText, cols, maxCharsPerImage, maxLines);
921
+ // Last page: residual soft-wrapped rows, not a full strip.
922
+ const visualRows = countVisualRows(renderedText, cols);
923
+ const lastPageLines = estImages <= 1
924
+ ? Math.min(linesPerImage, Math.max(1, visualRows))
925
+ : Math.min(linesPerImage, Math.max(1, visualRows - (estImages - 1) * linesPerImage));
926
+ const lastPageHeight = Math.min(profile.maxHeightPx, 2 * PAD_Y + lastPageLines * cellH);
927
+ const fullPageTokens = visionTokens(profile, stripW, fullPageHeight);
928
+ const lastPageTokens = visionTokens(profile, stripW, lastPageHeight);
929
+ // No GATE_MARGIN here, unlike the Anthropic slab/history gate, and that
930
+ // asymmetry is deliberate rather than drift:
931
+ // - this path reproduces the renderer's own page split from the SAME
932
+ // profile geometry, so `imageTokens` is the exact cost of the images that
933
+ // will be sent (tests pin gateEval.imageTokens === info.imageTokens);
934
+ // - it compares against an exact o200k count of the text baseline, not a
935
+ // chars-per-token approximation.
936
+ // Both sides are exact, so a margin would only be pessimism: it would refuse
937
+ // real, measured savings. The Anthropic gate estimates rows/pages heuristically,
938
+ // which is the estimation error GATE_MARGIN exists to absorb.
939
+ const imageTokens = estImages <= 1
940
+ ? lastPageTokens
941
+ : (estImages - 1) * fullPageTokens + lastPageTokens;
942
+ const textTokens = baselineTextTokens ?? (charsPerToken !== DEFAULTS.charsPerToken
943
+ ? renderedText.length / Math.max(1e-6, charsPerToken)
944
+ : (profile.minCompressTokens !== undefined || charsPerToken === DEFAULTS.charsPerToken
945
+ ? Math.max(1, gptTextTokens(renderedText) || Math.ceil(renderedText.length / charsPerToken))
946
+ : renderedText.length / Math.max(1e-6, charsPerToken)));
947
+ return { imageTokens, textTokens, profitable: imageTokens < textTokens };
948
+ }
949
+ function usesExactStaticBaseline(model) {
950
+ return resolveGptProfile(model).exactStaticBaseline === true;
951
+ }
952
+ /** Shared image-part accumulation from rendered PNGs. */
953
+ function accumulateRenderedImages(images, info) {
954
+ const droppedCodepoints = new Map();
955
+ for (const img of images) {
956
+ info.imageBytes += img.png.length;
957
+ info.imagePixels = (info.imagePixels ?? 0) + img.width * img.height;
958
+ info.droppedChars = (info.droppedChars ?? 0) + img.droppedChars;
959
+ for (const [cp, count] of img.droppedCodepoints) {
960
+ droppedCodepoints.set(cp, (droppedCodepoints.get(cp) ?? 0) + count);
961
+ }
962
+ }
963
+ return { droppedCodepoints };
964
+ }
965
+ /** o200k_base token count — gpt-5 / gpt-4o / o-series share this encoding. The
966
+ * honest "as plain text" baseline for the content inkling imaged. Pure JS, no
967
+ * native build, runs in both Node and Workers. */
968
+ function gptTextTokens(text) {
969
+ if (!text)
970
+ return 0;
971
+ try {
972
+ return o200kCountTokens(text);
973
+ }
974
+ catch {
975
+ return 0;
976
+ }
977
+ }
978
+ /** Vision-token cost of the rendered images, summed over their real dims —
979
+ * what GPT actually bills as input for the slab inkling imaged. */
980
+ function gptImageTokens(model, images) {
981
+ let n = 0;
982
+ for (const img of images)
983
+ n += visionTokensForModel(model, img.width, img.height);
984
+ return n;
985
+ }
986
+ /** Text-token value of what inkling replaced with images this request: the
987
+ * original system/developer text (now a pointer + image) plus the tool
988
+ * *description* tokens stripped from the native JSON (the verbose docs moved
989
+ * into the image). Tool *structure* stays in the JSON on both paths, so only
990
+ * the stripped delta counts. Compared against gptImageTokens for the saving. */
991
+ function gptBaselineImagedTokens(systemTexts, originalTools, strippedTools) {
992
+ let n = 0;
993
+ for (const t of systemTexts)
994
+ n += gptTextTokens(t);
995
+ const orig = Array.isArray(originalTools) && originalTools.length > 0
996
+ ? gptTextTokens(JSON.stringify(originalTools))
997
+ : 0;
998
+ const stripped = Array.isArray(strippedTools) && strippedTools.length > 0
999
+ ? gptTextTokens(JSON.stringify(strippedTools))
1000
+ : 0;
1001
+ return n + Math.max(0, orig - stripped);
1002
+ }
1003
+ /** Fold a history-collapse plan into TransformInfo: the history images cost
1004
+ * vision tokens (added to imageTokens) and stand in for the o200k text tokens
1005
+ * the collapsed transcript would have cost unproxied (added to baselineImagedTokens).
1006
+ * openai-savings.ts then credits (baseline − image) × cache-weight with no
1007
+ * further change. Also merges image bytes/pixels/dropped + collapse stats. */
1008
+ function foldGptHistory(info, model, plan) {
1009
+ // A pin can split the collapse into before/after image groups — account for both.
1010
+ const allImages = [...plan.images, ...plan.imagesAfter];
1011
+ if (allImages.length === 0) {
1012
+ if (plan.reason)
1013
+ info.historyReason = plan.reason;
1014
+ if (plan.collapsedChars > 0)
1015
+ info.historyTextChars = plan.collapsedChars;
1016
+ return;
1017
+ }
1018
+ info.imageTokens = (info.imageTokens ?? 0) + gptImageTokens(model, allImages);
1019
+ // o200k token value of the collapsed transcript (what it cost as plain text).
1020
+ info.baselineImagedTokens = (info.baselineImagedTokens ?? 0) +
1021
+ (plan.baselineTokens ?? gptTextTokens(plan.text));
1022
+ info.imageCount = (info.imageCount ?? 0) + allImages.length;
1023
+ for (const img of allImages) {
1024
+ info.imageBytes = (info.imageBytes ?? 0) + img.png.length;
1025
+ info.imagePixels = (info.imagePixels ?? 0) + img.width * img.height;
1026
+ }
1027
+ info.imagePngs = [...(info.imagePngs ?? []), ...allImages.map((i) => i.png)];
1028
+ info.imageDims = [
1029
+ ...(info.imageDims ?? []),
1030
+ ...allImages.map((i) => ({ width: i.width, height: i.height })),
1031
+ ];
1032
+ info.imageSourceTexts = [
1033
+ ...(info.imageSourceTexts ?? []),
1034
+ ...plan.imageSources,
1035
+ ...plan.imageSourcesAfter,
1036
+ ];
1037
+ if (plan.droppedChars > 0)
1038
+ info.droppedChars = (info.droppedChars ?? 0) + plan.droppedChars;
1039
+ info.collapsedTurns = plan.collapsedTurns;
1040
+ info.collapsedChars = plan.collapsedChars;
1041
+ info.collapsedImages = allImages.length;
1042
+ info.historyTextChars = plan.collapsedChars;
1043
+ info.historyReason = 'collapsed';
1044
+ info.bucketChars = { ...(info.bucketChars ?? {}), history: plan.collapsedChars };
1045
+ }
1046
+ async function applyChatHistoryCollapse(req, info, o, profile, protectedPrefix) {
1047
+ const profitable = (text, cols, baselineTextTokens) => evalOpenAIGate(req.model, text, cols, o.charsPerToken, baselineTextTokens).profitable;
1048
+ // Count images already in the request. At the main call site the static slab
1049
+ // images are inserted into req.messages before this runs, so walking the
1050
+ // messages (instead of also adding info.imageCount) avoids double-counting
1051
+ // the slab and matches the Responses path's budget math.
1052
+ const slabImages = info.imageCount ?? 0;
1053
+ const clientImages = Math.max(0, countRequestImages(req.messages) - slabImages);
1054
+ const plan = await planGptCollapse(chatMessagesToTurns(req.messages), protectedPrefix, profitable, gptHistoryOpts(req.model, o, profile, slabImages, clientImages));
1055
+ foldGptHistory(info, req.model, plan);
1056
+ const allImages = [...plan.images, ...plan.imagesAfter];
1057
+ if (allImages.length === 0)
1058
+ return false;
1059
+ const compactFraming = profile.history.framing === 'compact';
1060
+ const intro = compactFraming ? COMPACT_HISTORY_TRANSCRIPT_INTRO : HISTORY_TRANSCRIPT_INTRO;
1061
+ const outro = compactFraming ? COMPACT_HISTORY_TRANSCRIPT_OUTRO : HISTORY_TRANSCRIPT_OUTRO;
1062
+ const histFactSheet = factSheetText(plan.text, profile.factSheetFormat);
1063
+ const content = [{ type: 'text', text: intro }];
1064
+ const chatB64Parts = [];
1065
+ for (const img of plan.images) {
1066
+ const part = openAIImagePart(img, req.model);
1067
+ chatB64Parts.push(part.image_url.url.slice('data:image/png;base64,'.length));
1068
+ content.push(part);
1069
+ }
1070
+ if (plan.pinText !== undefined) {
1071
+ content.push({ type: 'text', text: pinnedRequestBlock(plan.pinText) });
1072
+ for (const img of plan.imagesAfter) {
1073
+ const part = openAIImagePart(img, req.model);
1074
+ chatB64Parts.push(part.image_url.url.slice('data:image/png;base64,'.length));
1075
+ content.push(part);
1076
+ }
1077
+ }
1078
+ if (histFactSheet)
1079
+ content.push({ type: 'text', text: histFactSheet });
1080
+ content.push({ type: 'text', text: outro });
1081
+ const guard = buildLiveRequestGuard(plan.pinText);
1082
+ req.messages = [
1083
+ ...req.messages.slice(0, plan.start),
1084
+ { role: 'user', content },
1085
+ { role: 'developer', content: guard },
1086
+ ...req.messages.slice(plan.endExclusive),
1087
+ ];
1088
+ info.nativeInjectedTokens = (info.nativeInjectedTokens ?? 0)
1089
+ + gptTextTokens(intro + histFactSheet + outro + guard);
1090
+ info.historyImageSha = await sha8(chatB64Parts.join(''));
1091
+ return true;
1092
+ }
1093
+ const OPENAI_CLIFF_STICKY_MAX = 512;
1094
+ const openaiCliffSticky = new Map();
1095
+ function getOpenAICliffSticky(key) {
1096
+ const hit = openaiCliffSticky.get(key);
1097
+ if (hit !== undefined) {
1098
+ openaiCliffSticky.delete(key);
1099
+ openaiCliffSticky.set(key, hit);
1100
+ }
1101
+ return hit;
1102
+ }
1103
+ function recordOpenAICliffSticky(key, cliffAt) {
1104
+ if (openaiCliffSticky.has(key)) {
1105
+ openaiCliffSticky.delete(key);
1106
+ }
1107
+ else if (openaiCliffSticky.size >= OPENAI_CLIFF_STICKY_MAX) {
1108
+ const oldest = openaiCliffSticky.keys().next().value;
1109
+ if (oldest !== undefined)
1110
+ openaiCliffSticky.delete(oldest);
1111
+ }
1112
+ openaiCliffSticky.set(key, cliffAt);
1113
+ }
1114
+ function clearImageStatsForLimit(info) {
1115
+ info.imageCount = 0;
1116
+ info.imageTokens = 0;
1117
+ info.baselineImagedTokens = 0;
1118
+ info.nativeInjectedTokens = 0;
1119
+ info.imageBytes = 0;
1120
+ info.imagePixels = 0;
1121
+ info.imagePngs = undefined;
1122
+ info.imageDims = undefined;
1123
+ info.imageSourceText = undefined;
1124
+ info.imageSourceTexts = undefined;
1125
+ info.firstImagePng = undefined;
1126
+ info.firstImageWidth = undefined;
1127
+ info.firstImageHeight = undefined;
1128
+ info.collapsedTurns = undefined;
1129
+ info.collapsedChars = undefined;
1130
+ info.collapsedImages = undefined;
1131
+ info.historyReason = undefined;
1132
+ info.historyTextChars = undefined;
1133
+ info.historyImageSha = undefined;
1134
+ info.bucketChars = undefined;
1135
+ info.compressedChars = 0;
1136
+ }
1137
+ async function applyResponsesHistoryCollapse(req, inputItems, info, o, profile) {
1138
+ const historySheets = createHistoryFactSheetRenderer(profile);
1139
+ const renderHistorySheet = historySheets.render;
1140
+ // Match emission's prefix-local deduplication. Only accepted sections cover
1141
+ // spellings; rejected sections must not make a later replacement look cheaper.
1142
+ const plannedSheetTokens = profile.history.factSheetOverflow === 'native-opaque'
1143
+ && profile.history.factSheetScope === 'per-segment' ? new Set() : undefined;
1144
+ const initialComp = info.responsesComposition;
1145
+ let remainingPromptTokens = initialComp?.totalLocal ?? 0;
1146
+ const upstreamPrefixTokens = (initialComp?.instructions ?? 0) + (initialComp?.toolsJson ?? 0);
1147
+ const tailItemTokens = inputItems.length > 0
1148
+ ? gptTextTokens(JSON.stringify(inputItems[inputItems.length - 1]))
1149
+ : 0;
1150
+ const profitable = (text, cols, baselineTextTokens, sourceText = text) => {
1151
+ const gate = evalOpenAIGate(req.model, text, cols, o.charsPerToken, o.explicitCharsPerToken ? undefined : baselineTextTokens);
1152
+ if (!gate.profitable)
1153
+ return false;
1154
+ const maxReads = profile.history.maxCachePaybackReads;
1155
+ if (!profile.history.factSheetOverflow && maxReads === undefined)
1156
+ return true;
1157
+ const framing = profile.history.framing === 'compact'
1158
+ ? COMPACT_HISTORY_TRANSCRIPT_INTRO + COMPACT_HISTORY_TRANSCRIPT_OUTRO
1159
+ : HISTORY_TRANSCRIPT_INTRO + HISTORY_TRANSCRIPT_OUTRO;
1160
+ const sheet = renderHistorySheet(sourceText, plannedSheetTokens);
1161
+ const collapsedTokens = gate.imageTokens + gptTextTokens(sheet + framing);
1162
+ if (collapsedTokens >= gate.textTokens)
1163
+ return false;
1164
+ let accepted = maxReads === undefined
1165
+ || computeOpenAICollapsePaybackReads(gate.textTokens, collapsedTokens, req.model) <= maxReads;
1166
+ const cliffStickyKey = `${req.model}\0${info.sessionKey ?? info.firstUserSha8 ?? ''}\0${sourceText.length}:${sourceText.slice(0, 128)}`;
1167
+ if (!accepted && remainingPromptTokens > gate.textTokens) {
1168
+ const stickyCliffAt = priceMode() === 'kosha' ? getOpenAICliffSticky(cliffStickyKey) : undefined;
1169
+ if (stickyCliffAt !== undefined && remainingPromptTokens > stickyCliffAt) {
1170
+ accepted = true;
1171
+ }
1172
+ else {
1173
+ const downstreamCachedTokens = Math.max(0, remainingPromptTokens - upstreamPrefixTokens - gate.textTokens - tailItemTokens);
1174
+ const cliff = evaluateCliffAvoidance(req.model, {
1175
+ promptTokensBefore: remainingPromptTokens,
1176
+ promptTokensAfter: Math.max(0, remainingPromptTokens - (gate.textTokens - collapsedTokens)),
1177
+ collapsedBaselineTokens: gate.textTokens,
1178
+ collapsedActualTokens: collapsedTokens,
1179
+ downstreamCachedTokens,
1180
+ expectedOutputTokens: o.expectedOutputTokens,
1181
+ });
1182
+ if (cliff?.crossesCliff && cliff.netSingleTurnUsd > 0) {
1183
+ accepted = true;
1184
+ recordOpenAICliffSticky(cliffStickyKey, cliff.cliffAt);
1185
+ info.cliffAvoided = {
1186
+ at: cliff.cliffAt,
1187
+ multiplier: cliff.multiplier,
1188
+ savedUsd: cliff.netSingleTurnUsd,
1189
+ };
1190
+ }
1191
+ }
1192
+ }
1193
+ if (accepted) {
1194
+ remainingPromptTokens = Math.max(0, remainingPromptTokens - (gate.textTokens - collapsedTokens));
1195
+ if (plannedSheetTokens) {
1196
+ for (const token of extractFactSheetTokens(sheet))
1197
+ plannedSheetTokens.add(token);
1198
+ }
1199
+ }
1200
+ return accepted;
1201
+ };
1202
+ const slabImages = info.imageCount ?? 0;
1203
+ const clientImages = info.responsesComposition?.imageParts ?? 0;
1204
+ const plan = await planResponsesPairCollapse(inputItems, profitable, gptHistoryOpts(req.model, o, profile, slabImages, clientImages));
1205
+ historySheets.beginEmission();
1206
+ const ps = plan.pairState;
1207
+ const rc = info.responsesComposition;
1208
+ rc.completedFunctionPairs = ps.completedPairs;
1209
+ rc.recentNativeFunctionPairs = ps.recentCompletedPairs;
1210
+ rc.oldFunctionPairs = ps.oldCompletedPairs;
1211
+ rc.openFunctionCalls = ps.openCalls;
1212
+ rc.orphanFunctionOutputs = ps.orphanOutputs;
1213
+ rc.malformedFunctionItems = ps.malformedItems;
1214
+ rc.imageableFunctionCalls = ps.imageableFunctionCallTokens;
1215
+ rc.imageableFunctionOutputs = ps.imageableFunctionOutputTokens;
1216
+ rc.collapsedFunctionPairs = ps.collapsedPairs;
1217
+ rc.collapsedFunctionCalls = ps.collapsedFunctionCallTokens;
1218
+ rc.collapsedFunctionOutputs = ps.collapsedFunctionOutputTokens;
1219
+ // Descending count so the dominant page-breaker is first. Bounded to 8 so a
1220
+ // pathological body cannot bloat the event row.
1221
+ if (plan.barrierTypes && plan.barrierTypes.size > 0) {
1222
+ rc.barrierTypes = [...plan.barrierTypes.entries()]
1223
+ .sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))
1224
+ .slice(0, 8)
1225
+ .map(([type, count]) => `${type}:${count}`);
1226
+ }
1227
+ foldGptHistory(info, req.model, plan);
1228
+ if (plan.segments.length === 0)
1229
+ return false;
1230
+ const replacements = new Map();
1231
+ const compactFraming = profile.history.framing === 'compact';
1232
+ const intro = compactFraming ? COMPACT_HISTORY_TRANSCRIPT_INTRO : HISTORY_TRANSCRIPT_INTRO;
1233
+ const outro = compactFraming ? COMPACT_HISTORY_TRANSCRIPT_OUTRO : HISTORY_TRANSCRIPT_OUTRO;
1234
+ const combinedSheet = profile.history.factSheetScope === 'combined'
1235
+ ? renderHistorySheet(plan.text)
1236
+ : '';
1237
+ // Request-local and emission-ordered: a skipped/referenced/unimaged group
1238
+ // cannot cover a spelling. Use a fresh set to replay the same accepted-prefix
1239
+ // coverage used by planning; appended groups keep old prefixes.
1240
+ const coveredSheetTokens = profile.history.factSheetOverflow === 'native-opaque'
1241
+ ? new Set() : undefined;
1242
+ const respB64Parts = [];
1243
+ for (let segmentIndex = 0; segmentIndex < plan.segments.length; segmentIndex++) {
1244
+ const segment = plan.segments[segmentIndex];
1245
+ const segImgParts = segment.images.map((img) => {
1246
+ const part = responsesImagePart(img, req.model);
1247
+ respB64Parts.push(part.image_url.slice('data:image/png;base64,'.length));
1248
+ return part;
1249
+ });
1250
+ const content = [
1251
+ { type: 'input_text', text: intro },
1252
+ ...segImgParts,
1253
+ ];
1254
+ // For `combined`, emit the shared factsheet as a standalone item AFTER all frozen
1255
+ // segments so Segment 0 stays byte-identical when Segment 1 seals later.
1256
+ const sheet = profile.history.factSheetScope === 'combined'
1257
+ ? ''
1258
+ : renderHistorySheet(segment.text, coveredSheetTokens);
1259
+ if (sheet) {
1260
+ content.push({ type: 'input_text', text: sheet });
1261
+ if (coveredSheetTokens) {
1262
+ for (const token of extractFactSheetTokens(sheet))
1263
+ coveredSheetTokens.add(token);
1264
+ }
1265
+ }
1266
+ content.push({ type: 'input_text', text: outro, ...responsesCacheBreakpoint(req, profile, o.explicitPromptCacheBreakpoints) });
1267
+ info.nativeInjectedTokens = (info.nativeInjectedTokens ?? 0)
1268
+ + gptTextTokens(intro + sheet + outro);
1269
+ replacements.set(segment.insertAt, { role: 'user', content });
1270
+ }
1271
+ const removed = new Set(plan.selectedIndices);
1272
+ const lastCollapsedIdx = plan.selectedIndices.length > 0
1273
+ ? Math.max(...plan.selectedIndices)
1274
+ : -1;
1275
+ const rewritten = [];
1276
+ for (let i = 0; i < inputItems.length; i++) {
1277
+ const replacement = replacements.get(i);
1278
+ if (replacement)
1279
+ rewritten.push(replacement);
1280
+ if (!removed.has(i))
1281
+ rewritten.push(inputItems[i]);
1282
+ if (combinedSheet && i === lastCollapsedIdx) {
1283
+ rewritten.push({ role: 'user', content: [{ type: 'input_text', text: combinedSheet }] });
1284
+ info.nativeInjectedTokens = (info.nativeInjectedTokens ?? 0) + gptTextTokens(combinedSheet);
1285
+ }
1286
+ }
1287
+ req.input = rewritten;
1288
+ info.historyImageSha = await sha8(respB64Parts.join(''));
1289
+ return true;
1290
+ }
1291
+ const HYBRID_TOOL_OPTICAL_MIN_CHARS = 2_500;
1292
+ const HYBRID_TOOL_OPTICAL_MAX_IMAGES = 8;
1293
+ const LARGE_USER_OPTICAL_MIN_CHARS = 24_000;
1294
+ const USER_HEAD_KEEP_CHARS = 1_000;
1295
+ const USER_TAIL_KEEP_CHARS = 1_500;
1296
+ const LARGE_USER_OPTICAL_MAX_IMAGES = 24;
1297
+ async function compressResponsesToolOutputsOptically(req, inputItems, info, o, profile, droppedCodepoints, sessionKey, sessionCacheCold, rawIndexOffset = 0) {
1298
+ let addedImagesCount = 0;
1299
+ let addedBase64Bytes = 0;
1300
+ let changed = false;
1301
+ const maxSerialized = profile.maxSerializedRequestBytes;
1302
+ const reflowNote = o.reflow
1303
+ ? ' The glyph ↵ (U+21B5) marks an original hard line break in content; treat it as a real newline.'
1304
+ : '';
1305
+ const maxCols = o.cols ?? profile.stripCols;
1306
+ const cutoffL1 = Math.max(0, inputItems.length - 2);
1307
+ const toolNameById = new Map();
1308
+ for (const rawItem of inputItems) {
1309
+ if (!rawItem || typeof rawItem !== 'object')
1310
+ continue;
1311
+ const callItem = rawItem;
1312
+ if ((callItem.type === 'function_call' || callItem.type === 'custom_tool_call') &&
1313
+ typeof callItem.name === 'string') {
1314
+ if (typeof callItem.call_id === 'string' && callItem.call_id) {
1315
+ toolNameById.set(callItem.call_id, callItem.name);
1316
+ }
1317
+ if (typeof callItem.id === 'string' && callItem.id) {
1318
+ toolNameById.set(callItem.id, callItem.name);
1319
+ }
1320
+ }
1321
+ }
1322
+ for (let i = 0; i < inputItems.length; i++) {
1323
+ const rawItem = inputItems[i];
1324
+ if (!rawItem || typeof rawItem !== 'object')
1325
+ continue;
1326
+ const item = rawItem;
1327
+ if (item.type !== 'function_call_output' && item.type !== 'custom_tool_call_output')
1328
+ continue;
1329
+ if (typeof item.output !== 'string')
1330
+ continue;
1331
+ const rawText = item.output;
1332
+ if (rawText.length < HYBRID_TOOL_OPTICAL_MIN_CHARS)
1333
+ continue;
1334
+ if (rawText.startsWith('[fiche ') ||
1335
+ rawText.startsWith('[folded into ') ||
1336
+ rawText.startsWith('[inkling ')) {
1337
+ continue;
1338
+ }
1339
+ const callIdStr = typeof item.call_id === 'string' && item.call_id ? item.call_id : '';
1340
+ const toolName = callIdStr ? toolNameById.get(callIdStr) : undefined;
1341
+ const origIdx = Math.max(0, i - rawIndexOffset);
1342
+ const baseRef = callIdStr || `out_${origIdx}`;
1343
+ const sealKey = buildOpticalToolSealKey(baseRef, rawText);
1344
+ const alreadySealed = Boolean(sessionKey && hasStage2SealKey(sessionKey, sealKey));
1345
+ // Protect recent live-tail file reads from imaging so Edit/apply_patch string anchors stay exact.
1346
+ if (!alreadySealed && !sessionCacheCold && i >= cutoffL1 && isFileReadToolName(toolName)) {
1347
+ continue;
1348
+ }
1349
+ const existingImages = (info.responsesComposition?.imageParts ?? 0) + info.imageCount;
1350
+ const capRem = profile.providerImageCap !== undefined
1351
+ ? Math.max(0, profile.providerImageCap - existingImages)
1352
+ : HYBRID_TOOL_OPTICAL_MAX_IMAGES;
1353
+ const remBudget = Math.min(HYBRID_TOOL_OPTICAL_MAX_IMAGES - addedImagesCount, capRem);
1354
+ if (remBudget <= 0)
1355
+ break;
1356
+ const compacted = compactSlabWhitespace(rawText);
1357
+ const renderedText = prepareImagedRenderText(`=== RENDERED TOOL OUTPUT ===${reflowNote}\n${compacted}`, o.reflow);
1358
+ const cols = Math.min(shrinkColsToContent(renderedText, maxCols, profile.style.markerScale, profile.style.font), profile.stripCols);
1359
+ const factSheet = factSheetText(rawText, profile.factSheetFormat);
1360
+ const endMarker = '[End of rendered tool output.]';
1361
+ const nativeOverhead = gptTextTokens(factSheet) + gptTextTokens(endMarker);
1362
+ const rawTokens = gptTextTokens(rawText) || Math.ceil(rawText.length / Math.max(1, o.charsPerToken));
1363
+ const gate = evalOpenAIGate(req.model, renderedText, cols, o.charsPerToken, rawTokens);
1364
+ if (!(gate.imageTokens + nativeOverhead < gate.textTokens * 0.7))
1365
+ continue;
1366
+ const imgs = await renderTextToPngs(renderedText, cols, profile.style, profile.maxHeightPx);
1367
+ if (imgs.length === 0 || imgs.length > remBudget)
1368
+ continue;
1369
+ const imgTok = gptImageTokens(req.model, imgs);
1370
+ if (!(imgTok + nativeOverhead < rawTokens * 0.7))
1371
+ continue;
1372
+ const estAddedBytes = imgs.reduce((s, img) => s + Math.ceil((img.png.length * 4) / 3) + 128, 0);
1373
+ if (maxSerialized !== undefined && addedBase64Bytes + estAddedBytes > maxSerialized * 0.75) {
1374
+ continue;
1375
+ }
1376
+ const acc = accumulateRenderedImages(imgs, info);
1377
+ if (droppedCodepoints) {
1378
+ for (const [cp, n] of acc.droppedCodepoints) {
1379
+ droppedCodepoints.set(cp, (droppedCodepoints.get(cp) ?? 0) + n);
1380
+ }
1381
+ }
1382
+ const imgPartsResp = imgs.map((img) => responsesImagePart(img, req.model));
1383
+ const outParts = [...imgPartsResp];
1384
+ if (factSheet)
1385
+ outParts.push({ type: 'input_text', text: factSheet });
1386
+ outParts.push({ type: 'input_text', text: endMarker });
1387
+ item.output = outParts;
1388
+ if (sessionKey)
1389
+ recordStage2SealKey(sessionKey, sealKey);
1390
+ info.imageCount += imgs.length;
1391
+ info.imageTokens = (info.imageTokens ?? 0) + imgTok;
1392
+ info.baselineImagedTokens = (info.baselineImagedTokens ?? 0) + rawTokens;
1393
+ info.nativeInjectedTokens = (info.nativeInjectedTokens ?? 0) + nativeOverhead;
1394
+ info.compressedChars += rawText.length;
1395
+ (info.imagePngs ??= []).push(...imgs.map((img) => img.png));
1396
+ (info.imageDims ??= []).push(...imgs.map((img) => ({ width: img.width, height: img.height })));
1397
+ const sourceSlice = renderedText.slice(0, 65_536);
1398
+ (info.imageSourceTexts ??= []).push(...imgs.map(() => sourceSlice));
1399
+ if (!info.firstImagePng) {
1400
+ info.firstImagePng = imgs[0].png;
1401
+ info.firstImageWidth = imgs[0].width;
1402
+ info.firstImageHeight = imgs[0].height;
1403
+ info.imageSourceText = sourceSlice;
1404
+ }
1405
+ addedImagesCount += imgs.length;
1406
+ addedBase64Bytes += estAddedBytes;
1407
+ changed = true;
1408
+ }
1409
+ if (changed) {
1410
+ const stages = info.textHygieneStages ? [...info.textHygieneStages] : [];
1411
+ if (!stages.includes('hybrid_tool_optical'))
1412
+ stages.push('hybrid_tool_optical');
1413
+ info.textHygieneStages = stages;
1414
+ if (droppedCodepoints && droppedCodepoints.size > 0) {
1415
+ const top = droppedCodepointsTop(droppedCodepoints);
1416
+ if (top)
1417
+ info.droppedCodepointsTop = top;
1418
+ }
1419
+ }
1420
+ return changed;
1421
+ }
1422
+ async function compressResponsesLargeUserContextOptically(req, inputItems, info, o, profile, droppedCodepoints) {
1423
+ let addedImagesCount = 0;
1424
+ let addedBase64Bytes = 0;
1425
+ let changed = false;
1426
+ const maxSerialized = profile.maxSerializedRequestBytes;
1427
+ const reflowNote = o.reflow
1428
+ ? ' The glyph ↵ (U+21B5) marks an original hard line break in content; treat it as a real newline.'
1429
+ : '';
1430
+ const maxCols = o.cols ?? profile.stripCols;
1431
+ const tryCompressUserText = async (rawText) => {
1432
+ if (rawText.length < LARGE_USER_OPTICAL_MIN_CHARS)
1433
+ return undefined;
1434
+ if (rawText.includes('[fiche ') || rawText.includes('[End of rendered'))
1435
+ return undefined;
1436
+ const existingImages = (info.responsesComposition?.imageParts ?? 0) + info.imageCount;
1437
+ const capRem = profile.providerImageCap !== undefined
1438
+ ? Math.max(0, profile.providerImageCap - existingImages)
1439
+ : LARGE_USER_OPTICAL_MAX_IMAGES;
1440
+ const remBudget = Math.min(LARGE_USER_OPTICAL_MAX_IMAGES - addedImagesCount, capRem);
1441
+ if (remBudget <= 0)
1442
+ return undefined;
1443
+ const nlHead = rawText.lastIndexOf('\n', USER_HEAD_KEEP_CHARS);
1444
+ const headCut = nlHead >= 400 ? nlHead + 1 : USER_HEAD_KEEP_CHARS;
1445
+ const nlTail = rawText.indexOf('\n', Math.max(headCut, rawText.length - USER_TAIL_KEEP_CHARS));
1446
+ const tailCut = nlTail >= headCut && rawText.length - nlTail >= 500
1447
+ ? nlTail
1448
+ : rawText.length - USER_TAIL_KEEP_CHARS;
1449
+ const head = rawText.slice(0, headCut);
1450
+ const middle = rawText.slice(headCut, tailCut);
1451
+ const tail = rawText.slice(tailCut);
1452
+ if (middle.length < 16_000)
1453
+ return undefined;
1454
+ const compacted = compactSlabWhitespace(middle);
1455
+ const renderedText = prepareImagedRenderText(`=== RENDERED USER CONTEXT ===${reflowNote}\n${compacted}`, o.reflow);
1456
+ const cols = Math.min(shrinkColsToContent(renderedText, maxCols, profile.style.markerScale, profile.style.font), profile.stripCols);
1457
+ const factSheet = factSheetText(middle, profile.factSheetFormat);
1458
+ const endMarker = '[End of rendered user context.]';
1459
+ const nativeOverhead = gptTextTokens(factSheet) + gptTextTokens(endMarker);
1460
+ const middleTokens = gptTextTokens(middle) || Math.ceil(middle.length / Math.max(1, o.charsPerToken));
1461
+ const gate = evalOpenAIGate(req.model, renderedText, cols, o.charsPerToken, middleTokens);
1462
+ if (!(gate.imageTokens + nativeOverhead < gate.textTokens * 0.65))
1463
+ return undefined;
1464
+ const imgs = await renderTextToPngs(renderedText, cols, profile.style, profile.maxHeightPx);
1465
+ if (imgs.length === 0 || imgs.length > remBudget)
1466
+ return undefined;
1467
+ const imgTok = gptImageTokens(req.model, imgs);
1468
+ if (!(imgTok + nativeOverhead < middleTokens * 0.65))
1469
+ return undefined;
1470
+ const estAddedBytes = imgs.reduce((s, img) => s + Math.ceil((img.png.length * 4) / 3) + 128, 0);
1471
+ if (maxSerialized !== undefined && addedBase64Bytes + estAddedBytes > maxSerialized * 0.75) {
1472
+ return undefined;
1473
+ }
1474
+ const acc = accumulateRenderedImages(imgs, info);
1475
+ if (droppedCodepoints) {
1476
+ for (const [cp, n] of acc.droppedCodepoints) {
1477
+ droppedCodepoints.set(cp, (droppedCodepoints.get(cp) ?? 0) + n);
1478
+ }
1479
+ }
1480
+ const imgPartsResp = imgs.map((img) => responsesImagePart(img, req.model));
1481
+ const replacement = [];
1482
+ if (head)
1483
+ replacement.push({ type: 'input_text', text: head });
1484
+ replacement.push(...imgPartsResp);
1485
+ if (factSheet)
1486
+ replacement.push({ type: 'input_text', text: factSheet });
1487
+ replacement.push({ type: 'input_text', text: endMarker });
1488
+ if (tail)
1489
+ replacement.push({ type: 'input_text', text: tail });
1490
+ info.imageCount += imgs.length;
1491
+ info.imageTokens = (info.imageTokens ?? 0) + imgTok;
1492
+ info.baselineImagedTokens = (info.baselineImagedTokens ?? 0) + middleTokens;
1493
+ info.nativeInjectedTokens = (info.nativeInjectedTokens ?? 0) + nativeOverhead;
1494
+ info.compressedChars += middle.length;
1495
+ (info.imagePngs ??= []).push(...imgs.map((img) => img.png));
1496
+ (info.imageDims ??= []).push(...imgs.map((img) => ({ width: img.width, height: img.height })));
1497
+ const sourceSlice = renderedText.slice(0, 65_536);
1498
+ (info.imageSourceTexts ??= []).push(...imgs.map(() => sourceSlice));
1499
+ if (!info.firstImagePng) {
1500
+ info.firstImagePng = imgs[0].png;
1501
+ info.firstImageWidth = imgs[0].width;
1502
+ info.firstImageHeight = imgs[0].height;
1503
+ info.imageSourceText = sourceSlice;
1504
+ }
1505
+ addedImagesCount += imgs.length;
1506
+ addedBase64Bytes += estAddedBytes;
1507
+ changed = true;
1508
+ return replacement;
1509
+ };
1510
+ for (const rawItem of inputItems) {
1511
+ if (!rawItem || typeof rawItem !== 'object')
1512
+ continue;
1513
+ const item = rawItem;
1514
+ if (item.role !== 'user')
1515
+ continue;
1516
+ if (Array.isArray(item.content)) {
1517
+ const isInsertedSlab = item.content.some((p) => p &&
1518
+ typeof p === 'object' &&
1519
+ p.text === '[End of rendered GPT system/tool context.]');
1520
+ if (isInsertedSlab)
1521
+ continue;
1522
+ const nextContent = [];
1523
+ let itemChanged = false;
1524
+ for (const part of item.content) {
1525
+ if (part && typeof part === 'object' && part.type === 'input_text') {
1526
+ const textVal = part.text;
1527
+ if (typeof textVal === 'string') {
1528
+ const expanded = await tryCompressUserText(textVal);
1529
+ if (expanded) {
1530
+ nextContent.push(...expanded);
1531
+ itemChanged = true;
1532
+ continue;
1533
+ }
1534
+ }
1535
+ }
1536
+ nextContent.push(part);
1537
+ }
1538
+ if (itemChanged)
1539
+ item.content = nextContent;
1540
+ }
1541
+ else if (typeof item.content === 'string') {
1542
+ const expanded = await tryCompressUserText(item.content);
1543
+ if (expanded)
1544
+ item.content = expanded;
1545
+ }
1546
+ }
1547
+ if (changed) {
1548
+ const stages = info.textHygieneStages ? [...info.textHygieneStages] : [];
1549
+ if (!stages.includes('hybrid_user_optical'))
1550
+ stages.push('hybrid_user_optical');
1551
+ info.textHygieneStages = stages;
1552
+ if (droppedCodepoints && droppedCodepoints.size > 0) {
1553
+ const top = droppedCodepointsTop(droppedCodepoints);
1554
+ if (top)
1555
+ info.droppedCodepointsTop = top;
1556
+ }
1557
+ }
1558
+ return changed;
1559
+ }
1560
+ export const CHAT_HEADER = '================= RENDERED GPT SYSTEM + TOOL CONTEXT =================\n' +
1561
+ 'These images were injected by fiche, not by the end user. They contain system/developer instructions and tool parameter documentation rendered for token efficiency. Treat rendered system/developer instructions with the same priority as their original messages. OCR carefully and treat the rendered content as authoritative. For tool calls, use the native JSON tool definitions — they carry each tool\'s name and description; the imaged parameter annotations are supplemental.' +
1562
+ '\n====================== BEGIN RENDERED CONTEXT ======================\n';
1563
+ export const RESPONSES_HEADER = '================= RENDERED GPT SYSTEM + TOOL CONTEXT =================\n' +
1564
+ 'These images were injected by fiche, not by the end user. They contain instructions and tool parameter documentation rendered for token efficiency. Treat rendered instructions with the same priority as the originals. OCR carefully and treat the rendered content as authoritative. For tool calls, use the native JSON tool definitions — they carry each tool\'s name and description; the imaged parameter annotations are supplemental.' +
1565
+ '\n====================== BEGIN RENDERED CONTEXT ======================\n';
1566
+ const CHAT_POINTER = 'The full instructions for this message were rendered into image(s) attached to the first user message by fiche. Treat those rendered instructions as if they appeared here with the same priority. Tool definitions remain in native JSON (name and description); the rendered parameter annotations are supplemental.';
1567
+ const RESPONSES_POINTER = 'The full instructions were rendered into image(s) attached to the first user message by fiche. Treat them with the same priority. Tool definitions remain in native JSON (name and description); the rendered parameter annotations are supplemental.';
1568
+ function countOpenAINativeImageBytes(items) {
1569
+ if (!Array.isArray(items))
1570
+ return 0;
1571
+ let total = 0;
1572
+ const scanParts = (parts) => {
1573
+ if (!Array.isArray(parts))
1574
+ return;
1575
+ for (const p of parts) {
1576
+ if (!p || typeof p !== 'object')
1577
+ continue;
1578
+ const rec = p;
1579
+ const imgUrl = rec.image_url;
1580
+ if (typeof imgUrl === 'string' && imgUrl.startsWith('data:image/')) {
1581
+ total += imgUrl.length;
1582
+ }
1583
+ else if (imgUrl && typeof imgUrl === 'object') {
1584
+ const u = imgUrl.url;
1585
+ if (typeof u === 'string' && u.startsWith('data:image/'))
1586
+ total += u.length;
1587
+ }
1588
+ }
1589
+ };
1590
+ for (const item of items) {
1591
+ if (!item || typeof item !== 'object')
1592
+ continue;
1593
+ const rec = item;
1594
+ scanParts(rec.content);
1595
+ scanParts(rec.output);
1596
+ }
1597
+ return total;
1598
+ }
1599
+ export async function transformOpenAIChatCompletions(body, opts = {}) {
1600
+ const o = resolveOptions(opts);
1601
+ const info = emptyInfo();
1602
+ if (!o.compress) {
1603
+ info.reason = 'compress=false';
1604
+ return { body, info };
1605
+ }
1606
+ let req;
1607
+ try {
1608
+ req = JSON.parse(new TextDecoder().decode(body));
1609
+ }
1610
+ catch (e) {
1611
+ info.reason = `parse_error: ${e.message}`;
1612
+ return { body, info };
1613
+ }
1614
+ if (!Array.isArray(req.messages)) {
1615
+ info.reason = 'parse_error: messages must be an array';
1616
+ return { body, info };
1617
+ }
1618
+ // The element itself is read unguarded from here down (`m.role` just below,
1619
+ // then contentText/setTextContent/history collapse), so a non-object element
1620
+ // threw out of the transform and the proxy answered 502 for a body the
1621
+ // upstream would have rejected with its own 400. Same bail-out as above.
1622
+ if (req.messages.some((m) => !m || typeof m !== 'object')) {
1623
+ info.reason = 'invalid_messages';
1624
+ return { body, info };
1625
+ }
1626
+ const profile = resolveGptProfile(req.model);
1627
+ const pinChars = relocateOpenAIPins(req);
1628
+ if (pinChars > 0)
1629
+ info.pinChars = pinChars;
1630
+ const chatNativeImageBytes = countOpenAINativeImageBytes(req.messages);
1631
+ const effectiveImageCompress = o.imageCompress && o.stageToggles?.optical !== false;
1632
+ const textHygieneActive = isTextHygieneActive(o.textHygiene);
1633
+ const estTextPromptTokensChat = Math.ceil(Math.max(0, body.byteLength - chatNativeImageBytes) / Math.max(1, o.charsPerToken));
1634
+ const earlyFirstUser = firstUserText(req);
1635
+ const chatSessionKey = await applyClientSessionIdentity(info, earlyFirstUser, o);
1636
+ const sessionState = chatSessionKey
1637
+ ? noteHistoryRequest(chatSessionKey, { model: req.model })
1638
+ : { cold: false, minFreezeStep: 0 };
1639
+ const opticalHistoryPolicy = effectiveImageCompress
1640
+ ? resolveOpticalHistoryPolicy({
1641
+ opticalMode: o.opticalMode,
1642
+ collapseHistory: opts.collapseHistory === true ? true : undefined,
1643
+ model: req.model,
1644
+ estPromptTokens: estTextPromptTokensChat,
1645
+ textHygieneActive,
1646
+ sessionKey: chatSessionKey,
1647
+ sessionCold: sessionState.cold,
1648
+ })
1649
+ : 'full';
1650
+ const hybridTextMmu = effectiveImageCompress && opticalHistoryPolicy === 'hybrid';
1651
+ const hygieneStats = textHygieneActive
1652
+ ? applyOpenAIChatTextHygiene(req, {
1653
+ foldLogs: !effectiveImageCompress || hybridTextMmu,
1654
+ deepTextCompact: !effectiveImageCompress || hybridTextMmu,
1655
+ cleanUserPayloads: o.cleanUserPayloads,
1656
+ enableTscg: o.stageToggles?.tscg,
1657
+ enableToon: o.stageToggles?.toon,
1658
+ enableAcdc: o.stageToggles?.acdc,
1659
+ enableCasi: (!effectiveImageCompress || hybridTextMmu) && o.stageToggles?.casi !== false,
1660
+ enableLsm: o.stageToggles?.lsm,
1661
+ enableMmu: o.stageToggles?.mmu,
1662
+ enableSkillLinker: o.stageToggles?.skillLinker,
1663
+ aggressiveToon: resolveTextHygieneMode(o.textHygiene) === 'on',
1664
+ model: req.model,
1665
+ expectedOutputTokens: o.expectedOutputTokens,
1666
+ rawBodyBytes: body.byteLength,
1667
+ nativeImageBytes: chatNativeImageBytes,
1668
+ sessionKey: chatSessionKey,
1669
+ firstUserText: earlyFirstUser,
1670
+ sessionCacheCold: sessionState.cold,
1671
+ liveTailTexts: (!effectiveImageCompress || hybridTextMmu) ? extractChatLiveTailTexts(req.messages) : undefined,
1672
+ appendTailHydration: (!effectiveImageCompress || hybridTextMmu) ? (blk) => appendChatTailHydration(req, blk) : undefined,
1673
+ })
1674
+ : undefined;
1675
+ if (hygieneStats?.changed || hygieneStats?.tailHydrated) {
1676
+ info.textHygieneSavedChars = hygieneStats.savedChars;
1677
+ info.textHygieneSavedTokens = hygieneStats.savedTokens;
1678
+ info.textHygieneBlocks = hygieneStats.blocks;
1679
+ info.textHygieneStages = [...hygieneStats.stages];
1680
+ if (hygieneStats.cliffAvoided)
1681
+ info.cliffAvoided = hygieneStats.cliffAvoided;
1682
+ }
1683
+ let cachedPinBodyChat;
1684
+ let cachedPinOutgoingChat;
1685
+ const getPinBody = () => {
1686
+ if (cachedPinBodyChat)
1687
+ return cachedPinBodyChat;
1688
+ if (pinChars > 0 || hygieneStats?.changed || hygieneStats?.tailHydrated) {
1689
+ cachedPinOutgoingChat = countOutgoingTextChars(req);
1690
+ cachedPinBodyChat = new TextEncoder().encode(JSON.stringify(req));
1691
+ }
1692
+ else {
1693
+ cachedPinBodyChat = body;
1694
+ }
1695
+ return cachedPinBodyChat;
1696
+ };
1697
+ if (profile.maxSerializedRequestBytes !== undefined && (pinChars > 0 || hygieneStats?.changed || hygieneStats?.tailHydrated)) {
1698
+ getPinBody();
1699
+ }
1700
+ if (!effectiveImageCompress) {
1701
+ if (hygieneStats?.changed) {
1702
+ info.compressed = true;
1703
+ info.reason = 'text_hygiene';
1704
+ info.outgoingTextChars = countOutgoingTextChars(req);
1705
+ return { body: getPinBody(), info };
1706
+ }
1707
+ if (hygieneStats?.tailHydrated) {
1708
+ info.reason = 'mmu_hydrate';
1709
+ info.outgoingTextChars = countOutgoingTextChars(req);
1710
+ return { body: getPinBody(), info };
1711
+ }
1712
+ info.reason = 'image_disabled';
1713
+ if (pinChars > 0)
1714
+ info.outgoingTextChars = countOutgoingTextChars(req);
1715
+ return { body: getPinBody(), info };
1716
+ }
1717
+ const firstUserIdx = req.messages.findIndex((m) => m.role === 'user');
1718
+ if (firstUserIdx < 0) {
1719
+ if (hygieneStats?.changed) {
1720
+ info.compressed = true;
1721
+ info.reason = 'text_hygiene';
1722
+ info.outgoingTextChars = countOutgoingTextChars(req);
1723
+ }
1724
+ else {
1725
+ info.reason = 'no_user_message';
1726
+ }
1727
+ return { body: getPinBody(), info };
1728
+ }
1729
+ const estPromptTokensChat = Math.ceil(body.byteLength / Math.max(1, o.charsPerToken));
1730
+ if (priceMode() === 'kosha' && gateRatesFor(req.model, { promptTokens: estPromptTokensChat }) === null) {
1731
+ info.reason = hygieneStats?.changed ? 'text_hygiene' : 'unpriced_model';
1732
+ if (hygieneStats?.changed) {
1733
+ if (!info.firstUserSha8 || !info.sessionKey) {
1734
+ await applyClientSessionIdentity(info, firstUserText(req), o);
1735
+ }
1736
+ info.compressed = true;
1737
+ info.outgoingTextChars = countOutgoingTextChars(req);
1738
+ }
1739
+ return { body: getPinBody(), info };
1740
+ }
1741
+ const authorityDocs = [];
1742
+ const systemTexts = [];
1743
+ // Leading system/developer messages only; see the Responses path.
1744
+ for (const msg of req.messages.slice(0, firstUserIdx)) {
1745
+ if (msg.role !== 'system' && msg.role !== 'developer')
1746
+ continue;
1747
+ const text = contentText(msg.content);
1748
+ if (!text)
1749
+ continue;
1750
+ authorityDocs.push(`## ${String(msg.role).toUpperCase()} MESSAGE\n${text}`);
1751
+ systemTexts.push(text);
1752
+ info.staticChars += text.length;
1753
+ }
1754
+ const { tools: rewrittenTools, docs: toolDocs } = o.compressTools
1755
+ ? rewriteToolsForGpt(req.tools)
1756
+ : { tools: req.tools, docs: '' };
1757
+ const combinedRaw = [...authorityDocs, toolDocs].filter((s) => s.length > 0).join('\n\n');
1758
+ info.origChars = combinedRaw.length;
1759
+ const finishSerializedChat = () => {
1760
+ const encoded = new TextEncoder().encode(JSON.stringify(req));
1761
+ const serializedByteLimit = profile.maxSerializedRequestBytes;
1762
+ if (serializedByteLimit !== undefined && encoded.byteLength > serializedByteLimit) {
1763
+ clearImageStatsForLimit(info);
1764
+ info.reason = 'serialized_request_limit';
1765
+ if (body.byteLength > serializedByteLimit) {
1766
+ info.compressed = true;
1767
+ info.serializedRequestBytes = encoded.byteLength;
1768
+ info.sizeLimitOutcome = 'rejected';
1769
+ return { body, info };
1770
+ }
1771
+ const pinBody = getPinBody();
1772
+ const usePinBody = pinBody.byteLength <= serializedByteLimit;
1773
+ const outBody = usePinBody ? pinBody : body;
1774
+ info.compressed = usePinBody && Boolean(hygieneStats?.changed);
1775
+ info.sizeLimitOutcome = 'fallback';
1776
+ if (usePinBody && cachedPinOutgoingChat !== undefined) {
1777
+ info.outgoingTextChars = cachedPinOutgoingChat;
1778
+ }
1779
+ return { body: outBody, info };
1780
+ }
1781
+ info.outgoingTextChars = countOutgoingTextChars(req);
1782
+ info.compressed = true;
1783
+ return { body: encoded, info };
1784
+ };
1785
+ const finishHistoryOnly = async (reason) => {
1786
+ info.reason = reason;
1787
+ if (o.collapseHistory && !hybridTextMmu && await applyChatHistoryCollapse(req, info, o, profile, firstUserIdx + 1)) {
1788
+ info.reason = undefined;
1789
+ return finishSerializedChat();
1790
+ }
1791
+ if (hygieneStats?.changed) {
1792
+ info.compressed = true;
1793
+ info.reason = 'text_hygiene';
1794
+ info.outgoingTextChars = countOutgoingTextChars(req);
1795
+ }
1796
+ else if (hygieneStats?.tailHydrated) {
1797
+ info.reason = 'mmu_hydrate';
1798
+ info.outgoingTextChars = countOutgoingTextChars(req);
1799
+ }
1800
+ return { body: getPinBody(), info };
1801
+ };
1802
+ if (!combinedRaw) {
1803
+ return finishHistoryOnly('no_static_context');
1804
+ }
1805
+ if (!info.firstUserSha8 || !info.sessionKey) {
1806
+ await applyClientSessionIdentity(info, firstUserText(req), o);
1807
+ }
1808
+ const combined = compactSlabWhitespace(combinedRaw).trimEnd();
1809
+ const minCompressTokens = profile.minCompressTokens;
1810
+ const combinedTokens = minCompressTokens === undefined ? undefined : gptTextTokens(combined);
1811
+ if (minCompressTokens !== undefined && combinedTokens < minCompressTokens) {
1812
+ return finishHistoryOnly(`below_min_tokens (${combinedTokens} < ${minCompressTokens})`);
1813
+ }
1814
+ if (minCompressTokens === undefined && combined.length < o.minCompressChars) {
1815
+ return finishHistoryOnly(`below_min_chars (${combined.length} < ${o.minCompressChars})`);
1816
+ }
1817
+ const reflowNote = o.reflow
1818
+ ? ' The glyph ↵ (U+21B5) marks an original hard line break in content; treat it as a real newline.'
1819
+ : '';
1820
+ const header = CHAT_HEADER.replace('\n====', reflowNote + '\n====');
1821
+ const renderedText = prepareImagedRenderText(header + combined, o.reflow);
1822
+ const maxCols = o.cols ?? profile.stripCols;
1823
+ const cols = Math.min(shrinkColsToContent(renderedText, maxCols, profile.style.markerScale, profile.style.font), profile.stripCols);
1824
+ const slabFactSheetPreview = factSheetText(combinedRaw, profile.factSheetFormat);
1825
+ const slabNativeOverhead = systemTexts.length * gptTextTokens(CHAT_POINTER)
1826
+ + gptTextTokens('[End of rendered GPT system/tool context.]')
1827
+ + gptTextTokens(slabFactSheetPreview);
1828
+ const staticBaselineTokens = gptBaselineImagedTokens(systemTexts, req.tools, rewrittenTools);
1829
+ const gate = evalOpenAIGate(req.model, renderedText, cols, o.charsPerToken, opts.charsPerToken === undefined && usesExactStaticBaseline(req.model)
1830
+ ? staticBaselineTokens
1831
+ : undefined);
1832
+ const slabProfitable = gate.imageTokens + (profile.exactStaticBaseline ? slabNativeOverhead : 0) < gate.textTokens;
1833
+ info.gateEval = {
1834
+ site: 'slab',
1835
+ imageTokens: gate.imageTokens,
1836
+ textTokens: gate.textTokens,
1837
+ burnImageSide: 0,
1838
+ burnTextSide: 0,
1839
+ profitable: slabProfitable,
1840
+ };
1841
+ if (!slabProfitable) {
1842
+ info.passthroughReasons = { not_profitable: 1 };
1843
+ return finishHistoryOnly(`not_profitable (slab=${combined.length} chars)`);
1844
+ }
1845
+ const images = await renderTextToPngs(renderedText, cols, profile.style, profile.maxHeightPx);
1846
+ if (images.length === 0) {
1847
+ info.reason = 'render_empty';
1848
+ return { body: getPinBody(), info };
1849
+ }
1850
+ // A hard provider cap makes static-first allocation pathological on long Qwen
1851
+ // chats: the repeated system slab consumes slots that could replace much more
1852
+ // history. Plan against the full cap first and keep static text native when the
1853
+ // two image sets cannot coexist.
1854
+ if (o.collapseHistory && !hybridTextMmu && profile.providerImageCap !== undefined) {
1855
+ const historyReq = structuredClone(req);
1856
+ const historyInfo = structuredClone(info);
1857
+ if (await applyChatHistoryCollapse(historyReq, historyInfo, o, profile, firstUserIdx + 1) && countRequestImages(historyReq.messages) + images.length > profile.providerImageCap) {
1858
+ historyInfo.outgoingTextChars = countOutgoingTextChars(historyReq);
1859
+ historyInfo.compressed = true;
1860
+ return { body: new TextEncoder().encode(JSON.stringify(historyReq)), info: historyInfo };
1861
+ }
1862
+ }
1863
+ if (profile.providerImageCap !== undefined &&
1864
+ countRequestImages(req.messages) + images.length > profile.providerImageCap) {
1865
+ info.reason = 'provider_image_cap';
1866
+ return { body: getPinBody(), info };
1867
+ }
1868
+ const { droppedCodepoints } = accumulateRenderedImages(images, info);
1869
+ const topDropped = droppedCodepointsTop(droppedCodepoints);
1870
+ if (topDropped)
1871
+ info.droppedCodepointsTop = topDropped;
1872
+ const imageParts = images.map((img) => openAIImagePart(img, req.model));
1873
+ info.imageCount = images.length;
1874
+ // GPT savings basis: vision tokens the images actually cost vs the text tokens
1875
+ // the same content would have cost unproxied. req.tools is still the original
1876
+ // (reassigned to the stripped set below). See src/core/openai-savings.ts.
1877
+ info.imageTokens = gptImageTokens(req.model, images);
1878
+ info.baselineImagedTokens = staticBaselineTokens;
1879
+ info.compressedChars = combinedRaw.length;
1880
+ info.bucketChars = { static_slab: combinedRaw.length };
1881
+ info.systemSha8 = await sha8(combined);
1882
+ info.firstImagePng = images[0].png;
1883
+ info.firstImageWidth = images[0].width;
1884
+ info.firstImageHeight = images[0].height;
1885
+ info.imagePngs = images.map((img) => img.png);
1886
+ info.imageDims = images.map((img) => ({ width: img.width, height: img.height }));
1887
+ // One slab render may page into multiple PNGs; each page links to the same
1888
+ // rendered source. History sources are appended later by foldGptHistory.
1889
+ info.imageSourceText = renderedText.slice(0, 65_536);
1890
+ info.imageSourceTexts = images.map(() => info.imageSourceText);
1891
+ // Verbatim fact-sheet: precision-critical tokens (paths, ids, versions, flags)
1892
+ // pulled from the pre-image text so exact strings survive OCR loss. Deterministic
1893
+ // → stays inside the cached prefix. See src/core/factsheet.ts.
1894
+ const slabFactSheet = slabFactSheetPreview;
1895
+ info.nativeInjectedTokens = slabNativeOverhead;
1896
+ const slabUserMsg = {
1897
+ role: 'user',
1898
+ content: [
1899
+ ...imageParts,
1900
+ ...(slabFactSheet ? [{ type: 'text', text: slabFactSheet }] : []),
1901
+ { type: 'text', text: '[End of rendered GPT system/tool context.]' },
1902
+ ],
1903
+ };
1904
+ req.messages = [
1905
+ ...req.messages.slice(0, firstUserIdx),
1906
+ slabUserMsg,
1907
+ ...req.messages.slice(firstUserIdx),
1908
+ ];
1909
+ for (const msg of req.messages.slice(0, firstUserIdx)) {
1910
+ if (msg.role !== 'system' && msg.role !== 'developer')
1911
+ continue;
1912
+ if (!contentText(msg.content))
1913
+ continue;
1914
+ setTextContent(msg, CHAT_POINTER);
1915
+ }
1916
+ // Collapse the OLD conversation prefix into history image(s). The inserted slab
1917
+ // item carries static images and is protected; the original opening user prompt
1918
+ // remains collapsible history instead of looking like the live request.
1919
+ if (o.collapseHistory && !hybridTextMmu) {
1920
+ await applyChatHistoryCollapse(req, info, o, profile, firstUserIdx + 1);
1921
+ }
1922
+ if (rewrittenTools !== undefined)
1923
+ req.tools = rewrittenTools;
1924
+ if (hybridTextMmu && info.imageCount > 0) {
1925
+ info.reason = 'hybrid_slab_optical';
1926
+ const stages = info.textHygieneStages ? [...info.textHygieneStages] : [];
1927
+ if (!stages.includes('hybrid_slab_optical'))
1928
+ stages.push('hybrid_slab_optical');
1929
+ info.textHygieneStages = stages;
1930
+ }
1931
+ return finishSerializedChat();
1932
+ }
1933
+ const CODEX_ENV_CONTEXT_RE = /<environment_context>[\s\S]*?<\/environment_context>/g;
1934
+ function splitLeadingResponsesAuthorityText(text) {
1935
+ if (!text)
1936
+ return { staticText: '', dynamicText: '', blockCount: 0 };
1937
+ const base = splitStaticDynamic(text);
1938
+ const dynamicParts = base.dynamicText ? [base.dynamicText] : [];
1939
+ let blockCount = base.blockCount;
1940
+ let rem = base.staticText.replace(CODEX_ENV_CONTEXT_RE, (m) => {
1941
+ dynamicParts.push(m);
1942
+ blockCount++;
1943
+ return '';
1944
+ });
1945
+ const islands = splitVolatileXmlIslands(rem);
1946
+ if (islands.some((isl) => isl.volatile)) {
1947
+ const staticIslands = [];
1948
+ for (const isl of islands) {
1949
+ if (isl.volatile) {
1950
+ dynamicParts.push(isl.text);
1951
+ blockCount++;
1952
+ }
1953
+ else {
1954
+ staticIslands.push(isl.text);
1955
+ }
1956
+ }
1957
+ rem = staticIslands.join('');
1958
+ }
1959
+ if (blockCount === 0 && dynamicParts.length === 0) {
1960
+ return {
1961
+ staticText: text,
1962
+ dynamicText: '',
1963
+ blockCount: 0,
1964
+ };
1965
+ }
1966
+ return {
1967
+ staticText: rem.replace(/\n{3,}/g, '\n\n').trim(),
1968
+ dynamicText: dynamicParts.join('\n\n').trim(),
1969
+ blockCount,
1970
+ };
1971
+ }
1972
+ function makeRelocatedAuthorityItem(sourceItem, dynamicText) {
1973
+ const hadArray = Array.isArray(sourceItem.content);
1974
+ const base = {};
1975
+ if (typeof sourceItem.type === 'string') {
1976
+ base.type = sourceItem.type;
1977
+ }
1978
+ base.role = sourceItem.role;
1979
+ base.content = hadArray ? [{ type: 'input_text', text: dynamicText }] : dynamicText;
1980
+ return base;
1981
+ }
1982
+ async function computeResponsesCachePrefixSha8(req) {
1983
+ const input = Array.isArray(req.input) ? req.input : undefined;
1984
+ let prefixItems = [];
1985
+ if (input && input.length > 0) {
1986
+ const slabIdx = input.findIndex((it) => {
1987
+ const c = it?.content;
1988
+ return Array.isArray(c) && c.some((p) => p?.text === '[End of rendered GPT system/tool context.]');
1989
+ });
1990
+ if (slabIdx >= 0) {
1991
+ prefixItems = input.slice(0, slabIdx + 1);
1992
+ for (let i = slabIdx + 1; i < input.length; i++) {
1993
+ const it = input[i];
1994
+ if (it?.role === 'user' &&
1995
+ Array.isArray(it.content) &&
1996
+ it.content.some((p) => {
1997
+ const t = p?.text;
1998
+ return typeof t === 'string' && t.includes('Earlier turns in image(s)');
1999
+ })) {
2000
+ prefixItems.push(it);
2001
+ }
2002
+ }
2003
+ }
2004
+ else {
2005
+ for (const it of input) {
2006
+ const r = it?.role;
2007
+ if (r === 'system' || r === 'developer')
2008
+ prefixItems.push(it);
2009
+ else
2010
+ break;
2011
+ }
2012
+ }
2013
+ }
2014
+ if (prefixItems.length === 0 &&
2015
+ typeof req.instructions !== 'string' &&
2016
+ !Array.isArray(req.tools)) {
2017
+ return undefined;
2018
+ }
2019
+ try {
2020
+ return await sha8(JSON.stringify({
2021
+ instructions: req.instructions ?? null,
2022
+ tools: req.tools ?? null,
2023
+ prefix: prefixItems,
2024
+ }));
2025
+ }
2026
+ catch {
2027
+ return undefined;
2028
+ }
2029
+ }
2030
+ export async function transformOpenAIResponses(body, opts = {}) {
2031
+ const o = resolveOptions(opts);
2032
+ const info = emptyInfo();
2033
+ if (!o.compress) {
2034
+ info.reason = 'compress=false';
2035
+ return { body, info };
2036
+ }
2037
+ let req;
2038
+ try {
2039
+ req = JSON.parse(new TextDecoder().decode(body));
2040
+ }
2041
+ catch (e) {
2042
+ info.reason = `parse_error: ${e.message}`;
2043
+ return { body, info };
2044
+ }
2045
+ const inputWasString = typeof req.input === 'string';
2046
+ const originalInputString = inputWasString ? req.input : undefined;
2047
+ let inputItems;
2048
+ if (inputWasString) {
2049
+ inputItems = [];
2050
+ }
2051
+ else if (Array.isArray(req.input)) {
2052
+ inputItems = req.input;
2053
+ }
2054
+ else {
2055
+ info.reason = 'parse_error: input must be a string or array';
2056
+ return { body, info };
2057
+ }
2058
+ if (inputItems.some((item) => !item || typeof item !== 'object')) {
2059
+ info.reason = 'invalid_input';
2060
+ return { body, info };
2061
+ }
2062
+ const profile = resolveGptProfile(req.model);
2063
+ const pinChars = relocateOpenAIPins(req);
2064
+ if (pinChars > 0)
2065
+ info.pinChars = pinChars;
2066
+ const respNativeImageBytes = countOpenAINativeImageBytes(req.input);
2067
+ const effectiveImageCompress = o.imageCompress && o.stageToggles?.optical !== false;
2068
+ const textHygieneActive = isTextHygieneActive(o.textHygiene);
2069
+ const estTextPromptTokensResp = Math.ceil(Math.max(0, body.byteLength - respNativeImageBytes) / Math.max(1, o.charsPerToken));
2070
+ const earlyRespFirstUser = firstResponsesUserText(inputWasString, originalInputString, inputItems);
2071
+ const respSessionKey = await applyClientSessionIdentity(info, earlyRespFirstUser, o);
2072
+ const sessionState = respSessionKey
2073
+ ? noteHistoryRequest(respSessionKey, { model: req.model })
2074
+ : { cold: false, minFreezeStep: 0 };
2075
+ const opticalHistoryPolicy = effectiveImageCompress
2076
+ ? resolveOpticalHistoryPolicy({
2077
+ opticalMode: o.opticalMode,
2078
+ collapseHistory: opts.collapseHistory === true ? true : undefined,
2079
+ model: req.model,
2080
+ estPromptTokens: estTextPromptTokensResp,
2081
+ textHygieneActive,
2082
+ sessionKey: respSessionKey,
2083
+ sessionCold: sessionState.cold,
2084
+ })
2085
+ : 'full';
2086
+ const hybridTextMmu = effectiveImageCompress && opticalHistoryPolicy === 'hybrid';
2087
+ const hygieneStats = textHygieneActive
2088
+ ? applyOpenAIResponsesTextHygiene(req, {
2089
+ foldLogs: !effectiveImageCompress || hybridTextMmu,
2090
+ deepTextCompact: !effectiveImageCompress || hybridTextMmu,
2091
+ cleanUserPayloads: o.cleanUserPayloads,
2092
+ enableTscg: o.stageToggles?.tscg,
2093
+ enableToon: o.stageToggles?.toon,
2094
+ enableAcdc: o.stageToggles?.acdc,
2095
+ enableCasi: (!effectiveImageCompress || hybridTextMmu) && o.stageToggles?.casi !== false,
2096
+ enableLsm: o.stageToggles?.lsm,
2097
+ enableMmu: o.stageToggles?.mmu,
2098
+ enableSkillLinker: o.stageToggles?.skillLinker,
2099
+ aggressiveToon: resolveTextHygieneMode(o.textHygiene) === 'on',
2100
+ model: req.model,
2101
+ expectedOutputTokens: o.expectedOutputTokens,
2102
+ rawBodyBytes: body.byteLength,
2103
+ nativeImageBytes: respNativeImageBytes,
2104
+ sessionKey: respSessionKey,
2105
+ firstUserText: earlyRespFirstUser,
2106
+ sessionCacheCold: sessionState.cold,
2107
+ liveTailTexts: (!effectiveImageCompress || hybridTextMmu)
2108
+ ? extractResponsesLiveTailTexts(inputWasString, originalInputString, inputItems)
2109
+ : undefined,
2110
+ appendTailHydration: (!effectiveImageCompress || hybridTextMmu) ? (blk) => appendResponsesTailHydration(req, blk) : undefined,
2111
+ })
2112
+ : undefined;
2113
+ if (hygieneStats?.changed || hygieneStats?.tailHydrated) {
2114
+ info.textHygieneSavedChars = hygieneStats.savedChars;
2115
+ info.textHygieneSavedTokens = hygieneStats.savedTokens;
2116
+ info.textHygieneBlocks = hygieneStats.blocks;
2117
+ info.textHygieneStages = [...hygieneStats.stages];
2118
+ if (hygieneStats.cliffAvoided)
2119
+ info.cliffAvoided = hygieneStats.cliffAvoided;
2120
+ }
2121
+ let cachedPinBodyResp;
2122
+ let cachedPinOutgoingResp;
2123
+ const getPinBodyResp = () => {
2124
+ if (cachedPinBodyResp)
2125
+ return cachedPinBodyResp;
2126
+ if (pinChars > 0 || hygieneStats?.changed || hygieneStats?.tailHydrated) {
2127
+ cachedPinOutgoingResp = countResponsesOutgoingTextChars(req);
2128
+ cachedPinBodyResp = new TextEncoder().encode(JSON.stringify(req));
2129
+ }
2130
+ else {
2131
+ cachedPinBodyResp = body;
2132
+ }
2133
+ return cachedPinBodyResp;
2134
+ };
2135
+ if (profile.maxSerializedRequestBytes !== undefined && (pinChars > 0 || hygieneStats?.changed || hygieneStats?.tailHydrated)) {
2136
+ getPinBodyResp();
2137
+ }
2138
+ if (!effectiveImageCompress) {
2139
+ if (hygieneStats?.changed) {
2140
+ info.compressed = true;
2141
+ info.reason = 'text_hygiene';
2142
+ info.outgoingTextChars = countResponsesOutgoingTextChars(req);
2143
+ return { body: getPinBodyResp(), info };
2144
+ }
2145
+ if (hygieneStats?.tailHydrated) {
2146
+ info.reason = 'mmu_hydrate';
2147
+ info.outgoingTextChars = countResponsesOutgoingTextChars(req);
2148
+ return { body: getPinBodyResp(), info };
2149
+ }
2150
+ info.reason = 'image_disabled';
2151
+ if (pinChars > 0)
2152
+ info.outgoingTextChars = countResponsesOutgoingTextChars(req);
2153
+ return { body: getPinBodyResp(), info };
2154
+ }
2155
+ if (Array.isArray(req.input)) {
2156
+ inputItems = req.input;
2157
+ }
2158
+ // Find first user item index (skip non-message items like function_call_output, reasoning).
2159
+ const firstUserIdx = inputItems.findIndex((item) => typeof item.role === 'string' &&
2160
+ item.role === 'user');
2161
+ if (!inputWasString && firstUserIdx < 0) {
2162
+ if (hygieneStats?.changed) {
2163
+ info.compressed = true;
2164
+ info.reason = 'text_hygiene';
2165
+ info.outgoingTextChars = countResponsesOutgoingTextChars(req);
2166
+ }
2167
+ else {
2168
+ info.reason = 'no_user_message';
2169
+ }
2170
+ return { body: getPinBodyResp(), info };
2171
+ }
2172
+ info.responsesComposition = measureResponsesComposition(req, inputWasString, originalInputString, inputItems);
2173
+ if (priceMode() === 'kosha' && gateRatesFor(req.model, { promptTokens: info.responsesComposition.totalLocal }) === null) {
2174
+ info.reason = hygieneStats?.changed ? 'text_hygiene' : 'unpriced_model';
2175
+ if (hygieneStats?.changed) {
2176
+ if (!info.firstUserSha8 || !info.sessionKey) {
2177
+ await applyClientSessionIdentity(info, firstResponsesUserText(inputWasString, originalInputString, inputItems), o);
2178
+ }
2179
+ info.compressed = true;
2180
+ info.outgoingTextChars = countResponsesOutgoingTextChars(req);
2181
+ }
2182
+ return { body: getPinBodyResp(), info };
2183
+ }
2184
+ // Collect static context: instructions + system/developer items + flat tools.
2185
+ const authorityDocs = [];
2186
+ const systemTexts = [];
2187
+ if (typeof req.instructions === 'string' && req.instructions.length > 0) {
2188
+ authorityDocs.push(`## INSTRUCTIONS\n${req.instructions}`);
2189
+ systemTexts.push(req.instructions);
2190
+ info.staticChars += req.instructions.length;
2191
+ }
2192
+ // Only the LEADING system/developer items are static, and volatile XML islands
2193
+ // (<env>, <git_status>, <system-reminder>, <environment_context>, etc.) inside them
2194
+ // are split out and relocated after the static slab so per-turn changes never bust the slab.
2195
+ const leadingAuthorityEnd = inputWasString ? 0 : firstUserIdx;
2196
+ const leadingSplits = new Map();
2197
+ const relocatedVolatileItems = [];
2198
+ for (let idx = 0; idx < leadingAuthorityEnd; idx++) {
2199
+ const item = inputItems[idx];
2200
+ const r = item.role;
2201
+ if (r !== 'system' && r !== 'developer')
2202
+ continue;
2203
+ const content = item.content;
2204
+ // content may be a string OR an array of input_text parts (both are valid
2205
+ // Responses shapes for system/developer items) — read either form.
2206
+ const text = responsesContentText(content);
2207
+ if (!text)
2208
+ continue;
2209
+ const split = r === 'developer'
2210
+ ? splitLeadingResponsesAuthorityText(text)
2211
+ : { staticText: text, dynamicText: '', blockCount: 0 };
2212
+ leadingSplits.set(idx, {
2213
+ index: idx,
2214
+ item: item,
2215
+ staticText: split.staticText,
2216
+ dynamicText: split.dynamicText,
2217
+ });
2218
+ if (split.dynamicText) {
2219
+ info.dynamicChars += split.dynamicText.length;
2220
+ info.dynamicBlockCount += Math.max(1, split.blockCount);
2221
+ relocatedVolatileItems.push(makeRelocatedAuthorityItem(item, split.dynamicText));
2222
+ }
2223
+ if (split.staticText) {
2224
+ authorityDocs.push(`## ${String(r).toUpperCase()} MESSAGE\n${split.staticText}`);
2225
+ systemTexts.push(split.staticText);
2226
+ info.staticChars += split.staticText.length;
2227
+ }
2228
+ }
2229
+ const { tools: rewrittenTools, docs: toolDocs } = o.compressTools
2230
+ ? rewriteFlatToolsForGpt(req.tools)
2231
+ : { tools: req.tools, docs: '' };
2232
+ const combinedRaw = [...authorityDocs, toolDocs].filter((s) => s.length > 0).join('\n\n');
2233
+ info.origChars = combinedRaw.length;
2234
+ const finishSerialized = async () => {
2235
+ const encoded = new TextEncoder().encode(JSON.stringify(req));
2236
+ // The SAME cap the proxy enforces with a 413 (proxy.ts), applied to every
2237
+ // profile that declares one. Imaging trades tokens for bytes (base64 PNGs
2238
+ // are larger than the text they replace), so a compressed body can exceed a
2239
+ // provider's request-size limit even when the original fits. Falling back to
2240
+ // the original here turns a hard 413 into a plain uncompressed request.
2241
+ const serializedByteLimit = profile.maxSerializedRequestBytes;
2242
+ if (serializedByteLimit !== undefined && encoded.byteLength > serializedByteLimit) {
2243
+ clearImageStatsForLimit(info);
2244
+ info.reason = 'serialized_request_limit';
2245
+ if (body.byteLength > serializedByteLimit) {
2246
+ info.compressed = true;
2247
+ info.serializedRequestBytes = encoded.byteLength;
2248
+ info.sizeLimitOutcome = 'rejected';
2249
+ return { body, info };
2250
+ }
2251
+ const pinBody = getPinBodyResp();
2252
+ const usePinBody = pinBody.byteLength <= serializedByteLimit;
2253
+ const outBody = usePinBody ? pinBody : body;
2254
+ info.compressed = usePinBody && Boolean(hygieneStats?.changed);
2255
+ info.sizeLimitOutcome = 'fallback';
2256
+ if (usePinBody && cachedPinOutgoingResp !== undefined) {
2257
+ info.outgoingTextChars = cachedPinOutgoingResp;
2258
+ }
2259
+ return { body: outBody, info };
2260
+ }
2261
+ info.outgoingTextChars = countResponsesOutgoingTextChars(req);
2262
+ info.compressed = true;
2263
+ const prefixSha = await computeResponsesCachePrefixSha8(req);
2264
+ if (prefixSha)
2265
+ info.cachePrefixSha8 = prefixSha;
2266
+ return { body: encoded, info };
2267
+ };
2268
+ const origInputLen = inputItems.length;
2269
+ const pureUserAssistantHybrid = hybridTextMmu &&
2270
+ (info.responsesComposition?.functionOutputs ?? 0) === 0 &&
2271
+ (info.responsesComposition?.userAssistant ?? 0) >= 2_000;
2272
+ const runFallbackTextHygiene = () => {
2273
+ if (!textHygieneActive)
2274
+ return false;
2275
+ const fb = applyOpenAIResponsesTextHygiene(req, {
2276
+ foldLogs: true,
2277
+ deepTextCompact: true,
2278
+ cleanUserPayloads: o.cleanUserPayloads,
2279
+ enableTscg: o.stageToggles?.tscg,
2280
+ enableToon: o.stageToggles?.toon,
2281
+ enableAcdc: o.stageToggles?.acdc,
2282
+ enableCasi: o.stageToggles?.casi !== false,
2283
+ enableLsm: o.stageToggles?.lsm,
2284
+ enableMmu: o.stageToggles?.mmu,
2285
+ enableSkillLinker: o.stageToggles?.skillLinker,
2286
+ aggressiveToon: resolveTextHygieneMode(o.textHygiene) === 'on',
2287
+ model: req.model,
2288
+ expectedOutputTokens: o.expectedOutputTokens,
2289
+ rawBodyBytes: body.byteLength,
2290
+ nativeImageBytes: respNativeImageBytes,
2291
+ sessionKey: respSessionKey,
2292
+ firstUserText: earlyRespFirstUser,
2293
+ sessionCacheCold: sessionState.cold,
2294
+ liveTailTexts: extractResponsesLiveTailTexts(inputWasString, originalInputString, inputItems),
2295
+ appendTailHydration: (blk) => appendResponsesTailHydration(req, blk),
2296
+ });
2297
+ if (!fb.changed && !fb.tailHydrated)
2298
+ return false;
2299
+ info.textHygieneSavedChars = (info.textHygieneSavedChars ?? 0) + fb.savedChars;
2300
+ info.textHygieneSavedTokens = (info.textHygieneSavedTokens ?? 0) + fb.savedTokens;
2301
+ info.textHygieneBlocks = (info.textHygieneBlocks ?? 0) + fb.blocks;
2302
+ const mergedStages = new Set([...(info.textHygieneStages ?? []), ...fb.stages]);
2303
+ info.textHygieneStages = [...mergedStages];
2304
+ if (!info.cliffAvoided && fb.cliffAvoided)
2305
+ info.cliffAvoided = fb.cliffAvoided;
2306
+ return fb.changed;
2307
+ };
2308
+ const finishHistoryOnly = async (reason) => {
2309
+ info.reason = reason;
2310
+ const collapseRan = o.collapseHistory && (!hybridTextMmu || pureUserAssistantHybrid) && !inputWasString
2311
+ ? await applyResponsesHistoryCollapse(req, inputItems, info, o, profile)
2312
+ : false;
2313
+ if (collapseRan) {
2314
+ const collapsedItems = Array.isArray(req.input)
2315
+ ? req.input
2316
+ : inputItems;
2317
+ await compressResponsesLargeUserContextOptically(req, collapsedItems, info, o, profile);
2318
+ info.reason = undefined;
2319
+ return finishSerialized();
2320
+ }
2321
+ const toolOptRan = hybridTextMmu && o.compressToolResults && !inputWasString
2322
+ ? await compressResponsesToolOutputsOptically(req, inputItems, info, o, profile, undefined, respSessionKey, sessionState.cold, 0)
2323
+ : false;
2324
+ const userOptRan = !inputWasString
2325
+ ? await compressResponsesLargeUserContextOptically(req, inputItems, info, o, profile)
2326
+ : false;
2327
+ if (toolOptRan || userOptRan) {
2328
+ info.reason = toolOptRan ? 'hybrid_tool_optical' : 'hybrid_user_optical';
2329
+ return finishSerialized();
2330
+ }
2331
+ const fbChanged = !hybridTextMmu ? runFallbackTextHygiene() : false;
2332
+ if (hygieneStats?.changed || fbChanged) {
2333
+ info.compressed = true;
2334
+ info.reason = 'text_hygiene';
2335
+ info.outgoingTextChars = countResponsesOutgoingTextChars(req);
2336
+ const prefixSha = await computeResponsesCachePrefixSha8(req);
2337
+ if (prefixSha)
2338
+ info.cachePrefixSha8 = prefixSha;
2339
+ return { body: new TextEncoder().encode(JSON.stringify(req)), info };
2340
+ }
2341
+ if (hygieneStats?.tailHydrated) {
2342
+ info.reason = 'mmu_hydrate';
2343
+ info.outgoingTextChars = countResponsesOutgoingTextChars(req);
2344
+ }
2345
+ const prefixSha = await computeResponsesCachePrefixSha8(req);
2346
+ if (prefixSha)
2347
+ info.cachePrefixSha8 = prefixSha;
2348
+ return { body: getPinBodyResp(), info };
2349
+ };
2350
+ if (!combinedRaw) {
2351
+ return finishHistoryOnly('no_static_context');
2352
+ }
2353
+ if (!info.firstUserSha8 || !info.sessionKey) {
2354
+ await applyClientSessionIdentity(info, firstResponsesUserText(inputWasString, originalInputString, inputItems), o);
2355
+ }
2356
+ const combined = compactSlabWhitespace(combinedRaw).trimEnd();
2357
+ const minCompressTokens = profile.minCompressTokens;
2358
+ const combinedTokens = minCompressTokens === undefined ? undefined : gptTextTokens(combined);
2359
+ if (minCompressTokens !== undefined && combinedTokens < minCompressTokens) {
2360
+ return finishHistoryOnly(`below_min_tokens (${combinedTokens} < ${minCompressTokens})`);
2361
+ }
2362
+ if (minCompressTokens === undefined && combined.length < o.minCompressChars) {
2363
+ return finishHistoryOnly(`below_min_chars (${combined.length} < ${o.minCompressChars})`);
2364
+ }
2365
+ const reflowNote = o.reflow
2366
+ ? ' The glyph ↵ (U+21B5) marks an original hard line break in content; treat it as a real newline.'
2367
+ : '';
2368
+ const header = RESPONSES_HEADER.replace('\n====', reflowNote + '\n====');
2369
+ const renderedText = prepareImagedRenderText(header + combined, o.reflow);
2370
+ const maxCols = o.cols ?? profile.stripCols;
2371
+ const cols = Math.min(shrinkColsToContent(renderedText, maxCols, profile.style.markerScale, profile.style.font), profile.stripCols);
2372
+ const slabFactSheetPreview = factSheetText(combinedRaw, profile.factSheetFormat);
2373
+ let staticAuthorityCountPre = 0;
2374
+ for (const s of leadingSplits.values()) {
2375
+ if (s.staticText.length > 0)
2376
+ staticAuthorityCountPre++;
2377
+ }
2378
+ const authorityPointerCountPre = (typeof req.instructions === 'string' && req.instructions.length > 0 ? 1 : 0)
2379
+ + staticAuthorityCountPre;
2380
+ const slabNativeOverhead = authorityPointerCountPre * gptTextTokens(RESPONSES_POINTER)
2381
+ + gptTextTokens(slabFactSheetPreview)
2382
+ + gptTextTokens('[End of rendered GPT system/tool context.]');
2383
+ const staticBaselineTokens = gptBaselineImagedTokens(systemTexts, req.tools, rewrittenTools);
2384
+ const gate = evalOpenAIGate(req.model, renderedText, cols, o.charsPerToken, opts.charsPerToken === undefined && usesExactStaticBaseline(req.model)
2385
+ ? staticBaselineTokens
2386
+ : undefined);
2387
+ const slabProfitable = gate.imageTokens + (profile.exactStaticBaseline ? slabNativeOverhead : 0) < gate.textTokens;
2388
+ info.gateEval = {
2389
+ site: 'slab',
2390
+ imageTokens: gate.imageTokens,
2391
+ textTokens: gate.textTokens,
2392
+ burnImageSide: 0,
2393
+ burnTextSide: 0,
2394
+ profitable: slabProfitable,
2395
+ };
2396
+ if (!slabProfitable) {
2397
+ info.passthroughReasons = { not_profitable: 1 };
2398
+ return finishHistoryOnly(`not_profitable (slab=${combined.length} chars)`);
2399
+ }
2400
+ const images = await renderTextToPngs(renderedText, cols, profile.style, profile.maxHeightPx);
2401
+ if (images.length === 0) {
2402
+ info.reason = 'render_empty';
2403
+ return { body: getPinBodyResp(), info };
2404
+ }
2405
+ if (profile.providerImageCap !== undefined &&
2406
+ (info.responsesComposition?.imageParts ?? 0) + images.length > profile.providerImageCap) {
2407
+ info.reason = 'provider_image_cap';
2408
+ return { body: getPinBodyResp(), info };
2409
+ }
2410
+ const { droppedCodepoints } = accumulateRenderedImages(images, info);
2411
+ const topDropped = droppedCodepointsTop(droppedCodepoints);
2412
+ if (topDropped)
2413
+ info.droppedCodepointsTop = topDropped;
2414
+ info.imageCount = images.length;
2415
+ // GPT savings basis (see src/core/openai-savings.ts). req.tools is still the
2416
+ // original here — reassigned to the stripped set below.
2417
+ info.imageTokens = gptImageTokens(req.model, images);
2418
+ info.baselineImagedTokens = staticBaselineTokens;
2419
+ info.compressedChars = combinedRaw.length;
2420
+ info.bucketChars = { static_slab: combinedRaw.length };
2421
+ info.systemSha8 = await sha8(combined);
2422
+ info.firstImagePng = images[0].png;
2423
+ info.firstImageWidth = images[0].width;
2424
+ info.firstImageHeight = images[0].height;
2425
+ info.imagePngs = images.map((img) => img.png);
2426
+ info.imageDims = images.map((img) => ({ width: img.width, height: img.height }));
2427
+ // One slab render may page into multiple PNGs; each page links to the same
2428
+ // rendered source. History sources are appended later by foldGptHistory.
2429
+ info.imageSourceText = renderedText.slice(0, 65_536);
2430
+ info.imageSourceTexts = images.map(() => info.imageSourceText);
2431
+ const imagePartsResp = images.map((img) => responsesImagePart(img, req.model));
2432
+ const endMarker = { type: 'input_text', text: '[End of rendered GPT system/tool context.]', ...responsesCacheBreakpoint(req, profile, o.explicitPromptCacheBreakpoints) };
2433
+ // Verbatim fact-sheet (see src/core/factsheet.ts): exact tokens that survive OCR loss.
2434
+ const slabFactSheet = slabFactSheetPreview;
2435
+ const slabFactSheetPart = slabFactSheet
2436
+ ? [{ type: 'input_text', text: slabFactSheet }]
2437
+ : [];
2438
+ info.nativeInjectedTokens = slabNativeOverhead;
2439
+ if (inputWasString) {
2440
+ // Wrap bare string input into a user item with images prepended.
2441
+ req.input = [{
2442
+ role: 'user',
2443
+ content: [
2444
+ ...imagePartsResp,
2445
+ ...slabFactSheetPart,
2446
+ endMarker,
2447
+ { type: 'input_text', text: typeof req.input === 'string' ? req.input : originalInputString },
2448
+ ],
2449
+ }];
2450
+ }
2451
+ else {
2452
+ // Insert a dedicated static-slab item. Replace static leading items with pointers,
2453
+ // and relocate any volatile leading developer islands right AFTER the slab item so
2454
+ // per-turn volatile updates never bust the cached slab prefix.
2455
+ const staticLeadingItems = [];
2456
+ for (let idx = 0; idx < leadingAuthorityEnd; idx++) {
2457
+ const item = inputItems[idx];
2458
+ const split = leadingSplits.get(idx);
2459
+ if (!split) {
2460
+ staticLeadingItems.push(item);
2461
+ continue;
2462
+ }
2463
+ if (!split.staticText) {
2464
+ // Wholly volatile leading developer item: relocated to `relocatedVolatileItems` after slabUserItem.
2465
+ continue;
2466
+ }
2467
+ const it = item;
2468
+ if (typeof it.content === 'string') {
2469
+ it.content = RESPONSES_POINTER;
2470
+ }
2471
+ else if (Array.isArray(it.content)) {
2472
+ it.content = [{ type: 'input_text', text: RESPONSES_POINTER }];
2473
+ }
2474
+ staticLeadingItems.push(item);
2475
+ }
2476
+ const slabUserItem = {
2477
+ role: 'user',
2478
+ content: [...imagePartsResp, ...slabFactSheetPart, endMarker],
2479
+ };
2480
+ inputItems = [
2481
+ ...staticLeadingItems,
2482
+ slabUserItem,
2483
+ ...relocatedVolatileItems,
2484
+ ...inputItems.slice(firstUserIdx),
2485
+ ];
2486
+ req.input = inputItems;
2487
+ }
2488
+ // Replace instructions with pointer.
2489
+ if (typeof req.instructions === 'string' && req.instructions.length > 0) {
2490
+ req.instructions = RESPONSES_POINTER;
2491
+ }
2492
+ // Responses protocol state is not an ordinary contiguous conversation prefix.
2493
+ // The profile selects pair-only legacy coverage or mixed safe-message coverage;
2494
+ // both preserve recent/open/malformed calls and opaque protocol barriers.
2495
+ const mainCollapseRan = o.collapseHistory && (!hybridTextMmu || pureUserAssistantHybrid) && !inputWasString
2496
+ ? await applyResponsesHistoryCollapse(req, inputItems, info, o, profile)
2497
+ : false;
2498
+ const activeItems = Array.isArray(req.input)
2499
+ ? req.input
2500
+ : inputItems;
2501
+ if (hybridTextMmu && o.compressToolResults && !inputWasString && !pureUserAssistantHybrid) {
2502
+ await compressResponsesToolOutputsOptically(req, activeItems, info, o, profile, droppedCodepoints, respSessionKey, sessionState.cold, Math.max(0, inputItems.length - origInputLen));
2503
+ }
2504
+ if (!inputWasString) {
2505
+ await compressResponsesLargeUserContextOptically(req, activeItems, info, o, profile, droppedCodepoints);
2506
+ }
2507
+ if (!hybridTextMmu && !mainCollapseRan) {
2508
+ runFallbackTextHygiene();
2509
+ }
2510
+ if (rewrittenTools !== undefined)
2511
+ req.tools = rewrittenTools;
2512
+ if (hybridTextMmu && info.imageCount > 0) {
2513
+ info.reason = 'hybrid_slab_optical';
2514
+ const stages = info.textHygieneStages ? [...info.textHygieneStages] : [];
2515
+ if (!stages.includes('hybrid_slab_optical'))
2516
+ stages.push('hybrid_slab_optical');
2517
+ info.textHygieneStages = stages;
2518
+ }
2519
+ // Regression denominator, same as the Chat path — Responses was the only
2520
+ // transform that never recorded it.
2521
+ return await finishSerialized();
2522
+ }
2523
+ //# sourceMappingURL=openai.js.map