@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,1380 @@
1
+ /**
2
+ * Google AI Studio / Gemini API request transformer and usage extractor.
3
+ * Intercepts /google-ai-studio/v1beta/models/*:generateContent and :streamGenerateContent
4
+ * requests, extracts static system instructions, renders them to PNG image parts, and
5
+ * passes transformed payloads to Google AI Studio.
6
+ */
7
+ import { PAD_Y, READABLE_CHARS_PER_IMAGE, estimateImageCount, neutralizeSentinel, reflow, renderCellHeight, renderTextToPngs, shrinkColsToContent, } from './render.js';
8
+ import { geminiVisionTokens, hasGeminiMeasuredProfile, isGeminiModel, resolveGeminiProfile } from './gemini-model-profiles.js';
9
+ import { bytesToBase64 } from './png.js';
10
+ import { applyClientSessionIdentity, classifyContent, compactSlabWhitespace, resolveOpticalHistoryPolicy, sha8, } from './transform.js';
11
+ import { noteHistoryRequest, sessionAnchorText } from './session-state.js';
12
+ import { prepareImagedRenderText, droppedCodepointsTop, schemaAnnotationLines, buildLiveRequestGuard, CHAT_HEADER, HISTORY_TRANSCRIPT_INTRO, HISTORY_TRANSCRIPT_OUTRO, COMPACT_HISTORY_TRANSCRIPT_INTRO, COMPACT_HISTORY_TRANSCRIPT_OUTRO, pinnedRequestBlock, } from './openai.js';
13
+ import { extractFactSheetTokens, factSheetText, prepareFactSheet } from './factsheet.js';
14
+ import { stripSchemaDescriptions } from './schema-strip.js';
15
+ import { relocateGooglePins } from './pin.js';
16
+ import { compactPreview, verbatimTaskText } from './history.js';
17
+ import { extractFaultSignalSnippet } from './context-mmu.js';
18
+ import { gateRatesFor, priceMode, resolvePriceRates } from './pricing.js';
19
+ import { applyGoogleTextHygiene, isTextHygieneActive, resolveTextHygieneMode, } from './text-hygiene.js';
20
+ const GOOGLE_ROUTE = /^(?:\/google-ai-studio)?\/(?:v1|v1beta)\/models\/([^/:]+):(generateContent|streamGenerateContent)$/;
21
+ const CLOUDCODE_PA_INFERENCE_ROUTE = /^\/v1internal:(?:generateContent|streamGenerateContent)$/;
22
+ export function parseGoogleModelFromPath(pathname) {
23
+ const match = GOOGLE_ROUTE.exec(pathname);
24
+ return match && match[1] ? match[1] : null;
25
+ }
26
+ export function isGoogleInferencePath(pathname) {
27
+ return parseGoogleModelFromPath(pathname) !== null || CLOUDCODE_PA_INFERENCE_ROUTE.test(pathname);
28
+ }
29
+ const SYSTEM_POINTER = 'The original system instruction is rendered in the image at the start of the first user turn. ' +
30
+ 'Treat that image as this system instruction, with the same authority and priority.';
31
+ const TOOL_POINTER_PREFIX = 'Full parameter docs: see "## Tool: ';
32
+ function countGoogleInlineImageBytes(req) {
33
+ let bytes = 0;
34
+ const addParts = (parts) => {
35
+ if (!Array.isArray(parts))
36
+ return;
37
+ for (const part of parts) {
38
+ if (part?.inlineData && typeof part.inlineData.data === 'string') {
39
+ bytes += part.inlineData.data.length;
40
+ }
41
+ if (part?.functionResponse && Array.isArray(part.functionResponse.parts)) {
42
+ addParts(part.functionResponse.parts);
43
+ }
44
+ }
45
+ };
46
+ addParts(req.systemInstruction?.parts);
47
+ if (Array.isArray(req.contents)) {
48
+ for (const c of req.contents)
49
+ addParts(c?.parts);
50
+ }
51
+ return bytes;
52
+ }
53
+ function record(value) {
54
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
55
+ ? value
56
+ : null;
57
+ }
58
+ function readString(value) {
59
+ return typeof value === 'string' && value ? value : undefined;
60
+ }
61
+ /** Gemini 3+ replay token. Present on the part, thought block, or nested on functionCall. */
62
+ function readGeminiThoughtSignature(part) {
63
+ const rec = record(part);
64
+ if (!rec)
65
+ return undefined;
66
+ const direct = readString(rec.thoughtSignature) ?? readString(rec.thought_signature) ?? readString(rec.signature);
67
+ if (direct)
68
+ return direct;
69
+ const functionCall = record(rec.functionCall);
70
+ if (functionCall) {
71
+ const fcSig = readString(functionCall.thoughtSignature) ?? readString(functionCall.thought_signature) ?? readString(functionCall.signature);
72
+ if (fcSig)
73
+ return fcSig;
74
+ }
75
+ return undefined;
76
+ }
77
+ function isGeminiFunctionCallPart(part) {
78
+ return record(part)?.functionCall !== undefined;
79
+ }
80
+ function cleanGeminiFunctionCall(fc) {
81
+ const rec = record(fc);
82
+ if (!rec)
83
+ return { cleaned: undefined, changed: false };
84
+ // FunctionCall in Gemini protobuf only permits `name`, `args`, and `id`.
85
+ // Discard any thought_signature / thoughtSignature mistakenly attached to functionCall itself.
86
+ if ('thoughtSignature' in rec || 'thought_signature' in rec || 'signature' in rec) {
87
+ const { thoughtSignature, thought_signature, signature, ...rest } = rec;
88
+ return { cleaned: rest, changed: true };
89
+ }
90
+ return { cleaned: rec, changed: false };
91
+ }
92
+ /** Normalize signature placement without changing Gemini's signed part sequence. */
93
+ function normalizeGeminiThoughtSignatures(contents) {
94
+ let changed = false;
95
+ const next = contents.map((content) => {
96
+ if (!Array.isArray(content.parts) || content.parts.length === 0)
97
+ return content;
98
+ let partsChanged = false;
99
+ const parts = content.parts.map((part) => {
100
+ if (!isGeminiFunctionCallPart(part))
101
+ return part;
102
+ const rec = record(part) ?? {};
103
+ const { cleaned: fc, changed: fcChanged } = cleanGeminiFunctionCall(rec.functionCall);
104
+ const signature = readGeminiThoughtSignature(part);
105
+ const hasCanonicalSignature = readString(rec.thoughtSignature) === signature;
106
+ const hasLegacySignature = 'thought_signature' in rec || 'signature' in rec;
107
+ if (!signature) {
108
+ if (fcChanged) {
109
+ partsChanged = true;
110
+ return { ...rec, functionCall: fc };
111
+ }
112
+ return part;
113
+ }
114
+ if (hasCanonicalSignature && !hasLegacySignature && !fcChanged) {
115
+ return part;
116
+ }
117
+ const { thought_signature, signature: legacySignature, ...rest } = rec;
118
+ partsChanged = true;
119
+ return {
120
+ ...rest,
121
+ thoughtSignature: signature,
122
+ ...(fc ? { functionCall: fc } : {}),
123
+ };
124
+ });
125
+ if (!partsChanged)
126
+ return content;
127
+ changed = true;
128
+ return { ...content, parts };
129
+ });
130
+ return changed ? next : contents;
131
+ }
132
+ function safeJson(value) {
133
+ try {
134
+ return JSON.stringify(value) ?? '';
135
+ }
136
+ catch {
137
+ return String(value ?? '');
138
+ }
139
+ }
140
+ function googleTextTokens(text) {
141
+ return text ? Math.ceil(text.length / 3.5) : 0;
142
+ }
143
+ function rewriteGoogleTools(tools) {
144
+ if (!Array.isArray(tools) || tools.length === 0) {
145
+ return { tools, docs: '', originalTokens: 0, rewrittenTokens: 0 };
146
+ }
147
+ const originalTokens = googleTextTokens(safeJson(tools));
148
+ const docs = [];
149
+ let changed = false;
150
+ const rewritten = tools.map((rawTool) => {
151
+ const tool = record(rawTool);
152
+ if (!tool || !Array.isArray(tool.functionDeclarations))
153
+ return rawTool;
154
+ let toolChanged = false;
155
+ const declarations = tool.functionDeclarations.map((rawDeclaration) => {
156
+ const declaration = record(rawDeclaration);
157
+ if (!declaration || typeof declaration.name !== 'string')
158
+ return rawDeclaration;
159
+ const annotations = schemaAnnotationLines(declaration.parameters);
160
+ const description = typeof declaration.description === 'string'
161
+ ? declaration.description
162
+ : '';
163
+ if (!description && annotations.length === 0)
164
+ return rawDeclaration;
165
+ docs.push([
166
+ `## Tool: ${declaration.name}`,
167
+ description,
168
+ declaration.parameters === undefined
169
+ ? ''
170
+ : `\`\`\`json\n${safeJson(declaration.parameters)}\n\`\`\``,
171
+ ].filter(Boolean).join('\n'));
172
+ toolChanged = true;
173
+ return {
174
+ ...declaration,
175
+ description: `${TOOL_POINTER_PREFIX}${declaration.name}" in the rendered context image.`,
176
+ parameters: stripSchemaDescriptions(declaration.parameters),
177
+ };
178
+ });
179
+ if (!toolChanged)
180
+ return rawTool;
181
+ changed = true;
182
+ return { ...tool, functionDeclarations: declarations };
183
+ });
184
+ const toolsOut = changed ? rewritten : tools;
185
+ return {
186
+ tools: toolsOut,
187
+ docs: docs.join('\n\n'),
188
+ originalTokens,
189
+ rewrittenTokens: googleTextTokens(safeJson(toolsOut)),
190
+ };
191
+ }
192
+ const SIMPLE_RESPONSE_KEYS = new Set(['name', 'output', 'content', 'result', 'error']);
193
+ function extractGoogleFunctionResponseText(response) {
194
+ const rec = record(response);
195
+ if (rec) {
196
+ const keys = Object.keys(rec);
197
+ if (keys.length > 0 && keys.every((k) => SIMPLE_RESPONSE_KEYS.has(k))) {
198
+ const parts = [];
199
+ for (const k of ['content', 'output', 'result', 'error']) {
200
+ const v = rec[k];
201
+ if (typeof v === 'string' && v.length > 0)
202
+ parts.push(v);
203
+ }
204
+ if (parts.length > 0)
205
+ return compactSlabWhitespace(parts.join('\n'));
206
+ }
207
+ }
208
+ return safeJson(response ?? {});
209
+ }
210
+ const GOOGLE_REMINDER_OPEN = '<system-reminder>';
211
+ const GOOGLE_REMINDER_CLOSE = '</system-reminder>';
212
+ const GOOGLE_NOTICE_OPEN = '<system-notice>';
213
+ const GOOGLE_NOTICE_CLOSE = '</system-notice>';
214
+ const USER_INTERJECTION_HEADER_RE = /^User interjection during work[^\n]*\n?/i;
215
+ const USER_INTERJECTION_FOOTER_RE = /\n?\[User interjection supersedes conflicting prior instructions\.[^\]]*\]\s*$/i;
216
+ /**
217
+ * Extract human-authored prompt text from a Gemini user turn's text parts.
218
+ * Strips `<system-reminder>` envelopes and non-interjection `<system-notice>`
219
+ * blocks (e.g. device-inventory updates), while unwrapping mid-work user
220
+ * interjections (`<system-notice>User interjection during work...</system-notice>`)
221
+ * so they remain recognized as part of the active user request.
222
+ */
223
+ function extractGoogleUserPrompt(parts) {
224
+ if (parts.length === 0)
225
+ return undefined;
226
+ const cleanedParts = [];
227
+ let isInterjection = false;
228
+ for (const raw of parts) {
229
+ let withoutReminders = '';
230
+ let at = 0;
231
+ for (;;) {
232
+ const open = raw.indexOf(GOOGLE_REMINDER_OPEN, at);
233
+ if (open < 0)
234
+ break;
235
+ const close = raw.indexOf(GOOGLE_REMINDER_CLOSE, open + GOOGLE_REMINDER_OPEN.length);
236
+ if (close < 0)
237
+ break;
238
+ withoutReminders += raw.slice(at, open);
239
+ at = close + GOOGLE_REMINDER_CLOSE.length;
240
+ }
241
+ withoutReminders += raw.slice(at);
242
+ let out = '';
243
+ let cursor = 0;
244
+ for (;;) {
245
+ const open = withoutReminders.indexOf(GOOGLE_NOTICE_OPEN, cursor);
246
+ if (open < 0)
247
+ break;
248
+ const close = withoutReminders.indexOf(GOOGLE_NOTICE_CLOSE, open + GOOGLE_NOTICE_OPEN.length);
249
+ if (close < 0)
250
+ break;
251
+ out += withoutReminders.slice(cursor, open);
252
+ const inner = withoutReminders
253
+ .slice(open + GOOGLE_NOTICE_OPEN.length, close)
254
+ .trim();
255
+ if (USER_INTERJECTION_HEADER_RE.test(inner)) {
256
+ isInterjection = true;
257
+ const unwrapped = inner
258
+ .replace(USER_INTERJECTION_HEADER_RE, '')
259
+ .replace(USER_INTERJECTION_FOOTER_RE, '')
260
+ .trim();
261
+ if (unwrapped) {
262
+ out += (out && !out.endsWith('\n') ? '\n' : '') + unwrapped + '\n';
263
+ }
264
+ }
265
+ cursor = close + GOOGLE_NOTICE_CLOSE.length;
266
+ }
267
+ out += withoutReminders.slice(cursor);
268
+ const trimmed = out.trim();
269
+ if (trimmed)
270
+ cleanedParts.push(trimmed);
271
+ }
272
+ if (cleanedParts.length === 0)
273
+ return undefined;
274
+ return { text: cleanedParts.join('\n\n'), isInterjection };
275
+ }
276
+ function googlePartText(part) {
277
+ if (typeof part.text === 'string')
278
+ return part.text;
279
+ if (part.functionCall) {
280
+ return `[tool_use ${part.functionCall.name ?? 'tool'}]\n${safeJson(part.functionCall.args ?? {})}`;
281
+ }
282
+ if (part.functionResponse) {
283
+ return `[tool_result ${part.functionResponse.name ?? 'tool'}]\n${extractGoogleFunctionResponseText(part.functionResponse.response)}`;
284
+ }
285
+ return '';
286
+ }
287
+ function googleHistoryUnit(content, index) {
288
+ if (!Array.isArray(content.parts)) {
289
+ return { index, text: '', baselineTokens: 0, source: content, opens: [], closes: [], opaque: true };
290
+ }
291
+ const text = [];
292
+ const rawTexts = [];
293
+ const userTextParts = [];
294
+ const opens = [];
295
+ const closes = [];
296
+ let opaque = false;
297
+ for (const rawPart of content.parts) {
298
+ const part = record(rawPart);
299
+ if (!part) {
300
+ opaque = true;
301
+ continue;
302
+ }
303
+ if (part.thought === true) {
304
+ if (typeof part.text === 'string' && part.text)
305
+ rawTexts.push(part.text);
306
+ continue;
307
+ }
308
+ if (typeof part.text === 'string') {
309
+ text.push(part.text);
310
+ rawTexts.push(part.text);
311
+ if (content.role !== 'model')
312
+ userTextParts.push(part.text);
313
+ continue;
314
+ }
315
+ if (part.functionCall) {
316
+ const name = typeof part.functionCall.name === 'string' ? part.functionCall.name : 'tool';
317
+ opens.push(name);
318
+ const serialized = googlePartText(part);
319
+ text.push(serialized);
320
+ rawTexts.push(safeJson(part.functionCall));
321
+ continue;
322
+ }
323
+ if (part.functionResponse) {
324
+ const name = typeof part.functionResponse.name === 'string' ? part.functionResponse.name : 'tool';
325
+ closes.push(name);
326
+ const serialized = googlePartText(part);
327
+ text.push(serialized);
328
+ rawTexts.push(safeJson(part.functionResponse.response ?? {}));
329
+ continue;
330
+ }
331
+ if (part.inlineData) {
332
+ text.push('[image]');
333
+ continue;
334
+ }
335
+ if (readGeminiThoughtSignature(part) !== undefined) {
336
+ continue;
337
+ }
338
+ // Server tool state and unknown parts must stay native.
339
+ opaque = true;
340
+ }
341
+ const role = content.role === 'model' ? 'assistant' : 'user';
342
+ const body = text.filter(Boolean).join('\n\n');
343
+ const rawBody = rawTexts.filter(Boolean).join('\n\n');
344
+ const transcript = body ? `<${role} t="${index}">\n${body}\n</${role}>` : '';
345
+ const userPrompt = content.role !== 'model' ? extractGoogleUserPrompt(userTextParts) : undefined;
346
+ return {
347
+ index,
348
+ text: transcript,
349
+ ...(userPrompt
350
+ ? {
351
+ userText: userPrompt.text,
352
+ userInterjection: userPrompt.isInterjection || closes.length > 0,
353
+ }
354
+ : {}),
355
+ baselineTokens: Math.max(googleTextTokens(body), googleTextTokens(rawBody)),
356
+ source: content,
357
+ opens,
358
+ closes,
359
+ opaque,
360
+ };
361
+ }
362
+ /**
363
+ * File-reading tools whose outputs are commonly quoted verbatim by an immediately
364
+ * following edit tool (`edit_file`, `Edit`, `replace`, `view_file`). Keeping
365
+ * them as native text in the live tail avoids OCR/whitespace misses while a file
366
+ * is actively being edited; once those turns age into collapsed history,
367
+ * `planGoogleHistory` still compresses them.
368
+ */
369
+ const EXACT_TEXT_TOOL_NAMES = new Set([
370
+ 'read',
371
+ 'read_file',
372
+ 'view_file',
373
+ 'file_read',
374
+ 'get_file_contents',
375
+ ]);
376
+ function isExactTextTool(name) {
377
+ const bare = name.includes(':') ? name.slice(name.lastIndexOf(':') + 1) : name;
378
+ return EXACT_TEXT_TOOL_NAMES.has(bare.toLowerCase());
379
+ }
380
+ async function compressGoogleToolResults(contents, modelName, options) {
381
+ const empty = () => ({
382
+ contents,
383
+ images: [],
384
+ imageSources: [],
385
+ baselineTokens: 0,
386
+ nativeTokens: 0,
387
+ compressedChars: 0,
388
+ bucketChars: {},
389
+ droppedChars: 0,
390
+ droppedCodepoints: new Map(),
391
+ });
392
+ if (options.compressToolResults === false)
393
+ return empty();
394
+ const profile = resolveGeminiProfile(modelName);
395
+ const minChars = Math.max(0, options.minToolResultChars ?? 4500);
396
+ const perResultCap = Math.max(1, options.maxImagesPerToolResult ?? 10);
397
+ const allImages = [];
398
+ const imageSources = [];
399
+ const bucketChars = {};
400
+ const droppedCodepoints = new Map();
401
+ let baselineTokens = 0;
402
+ let nativeTokens = 0;
403
+ let compressedChars = 0;
404
+ let droppedChars = 0;
405
+ let changed = false;
406
+ const rewrittenContents = [];
407
+ for (const content of contents) {
408
+ if (!Array.isArray(content.parts)) {
409
+ rewrittenContents.push(content);
410
+ continue;
411
+ }
412
+ let contentChanged = false;
413
+ const rewrittenParts = [];
414
+ for (const rawPart of content.parts) {
415
+ const part = record(rawPart);
416
+ const response = part?.functionResponse;
417
+ const responseBody = record(response?.response);
418
+ const textKey = ['content', 'output', 'result', 'error'].find((k) => typeof responseBody?.[k] === 'string' && responseBody[k].length >= minChars);
419
+ const raw = textKey ? responseBody[textKey] : '';
420
+ if (!part || !response || !responseBody || !textKey || raw.length < minChars ||
421
+ (Array.isArray(response.parts) && response.parts.length > 0)) {
422
+ rewrittenParts.push(rawPart);
423
+ continue;
424
+ }
425
+ const name = typeof response.name === 'string' ? response.name : 'tool';
426
+ if (isExactTextTool(name)) {
427
+ rewrittenParts.push(rawPart);
428
+ continue;
429
+ }
430
+ const compact = compactSlabWhitespace(raw);
431
+ const safe = neutralizeSentinel(compact);
432
+ const packed = options.reflow !== false ? reflow(safe) ?? safe : safe;
433
+ const rendered = prepareImagedRenderText(`================= RENDERED TOOL RESULT: ${name} =================\n` +
434
+ 'fiche rendered this completed tool result into image pages to reduce input tokens. Read it as the exact result returned by the tool.\n' +
435
+ packed, false);
436
+ const cellH = renderCellHeight(profile.style);
437
+ const maxLines = Math.max(1, Math.floor((profile.maxHeightPx - 2 * PAD_Y) / cellH));
438
+ const maxCharsPerImg = Math.min(READABLE_CHARS_PER_IMAGE, Math.max(1, profile.stripCols) * maxLines);
439
+ if (estimateImageCount(rendered, profile.stripCols, maxCharsPerImg, maxLines) > perResultCap) {
440
+ rewrittenParts.push(rawPart);
441
+ continue;
442
+ }
443
+ const images = await renderTextToPngs(rendered, profile.stripCols, profile.style, profile.maxHeightPx);
444
+ if (images.length === 0 || images.length > perResultCap) {
445
+ rewrittenParts.push(rawPart);
446
+ continue;
447
+ }
448
+ const imageTokens = images.reduce((sum, image) => sum + geminiVisionTokens(modelName, image.width, image.height), 0);
449
+ const sheet = factSheetText(raw, profile.factSheetFormat);
450
+ const pointer = `The completed ${name} tool result is rendered in the attached image part(s).` +
451
+ (sheet ? `\n${sheet}` : '');
452
+ const textTokens = googleTextTokens(raw);
453
+ const pointerTokens = googleTextTokens(pointer);
454
+ if (imageTokens + pointerTokens >= textTokens) {
455
+ rewrittenParts.push(rawPart);
456
+ continue;
457
+ }
458
+ rewrittenParts.push({
459
+ ...part,
460
+ functionResponse: {
461
+ ...response,
462
+ response: { ...responseBody, [textKey]: pointer },
463
+ parts: images.map(imagePart),
464
+ },
465
+ });
466
+ contentChanged = true;
467
+ changed = true;
468
+ allImages.push(...images);
469
+ imageSources.push(...images.map(() => raw));
470
+ baselineTokens += textTokens;
471
+ nativeTokens += pointerTokens;
472
+ compressedChars += raw.length;
473
+ const shape = classifyContent(compact);
474
+ const bucket = shape === 'structured'
475
+ ? 'tool_result_json'
476
+ : shape === 'log' ? 'tool_result_log' : 'tool_result_prose';
477
+ bucketChars[bucket] = (bucketChars[bucket] ?? 0) + raw.length;
478
+ for (const image of images) {
479
+ droppedChars += image.droppedChars;
480
+ for (const [codepoint, count] of image.droppedCodepoints) {
481
+ droppedCodepoints.set(codepoint, (droppedCodepoints.get(codepoint) ?? 0) + count);
482
+ }
483
+ }
484
+ }
485
+ rewrittenContents.push(contentChanged ? { ...content, parts: rewrittenParts } : content);
486
+ }
487
+ return {
488
+ contents: changed ? rewrittenContents : contents,
489
+ images: allImages,
490
+ imageSources,
491
+ baselineTokens,
492
+ nativeTokens,
493
+ compressedChars,
494
+ bucketChars,
495
+ droppedChars,
496
+ droppedCodepoints,
497
+ };
498
+ }
499
+ function googleClosedBoundary(units, fromInclusive, cutoffExclusive) {
500
+ const open = new Map();
501
+ let lastClosed = fromInclusive - 1;
502
+ for (let i = fromInclusive; i < Math.min(cutoffExclusive, units.length); i++) {
503
+ const unit = units[i];
504
+ if (unit.opaque)
505
+ break;
506
+ for (const name of unit.opens)
507
+ open.set(name, (open.get(name) ?? 0) + 1);
508
+ for (const name of unit.closes) {
509
+ const count = open.get(name) ?? 0;
510
+ // An output whose call sits before the selected range is a protocol barrier.
511
+ if (count === 0)
512
+ return lastClosed;
513
+ if (count === 1)
514
+ open.delete(name);
515
+ else
516
+ open.set(name, count - 1);
517
+ }
518
+ if (open.size === 0)
519
+ lastClosed = i;
520
+ }
521
+ return lastClosed;
522
+ }
523
+ async function planGoogleHistory(contents, modelName, reflowEnabled) {
524
+ const profile = resolveGeminiProfile(modelName);
525
+ const units = contents.map(googleHistoryUnit);
526
+ const cutoff = Math.max(0, units.length - profile.history.keepTail);
527
+ // Keep Turn 0 anchored as native (`start = 1`) permanently whenever Turn 0 is a
528
+ // user turn, so Turn 2+ never flips `start` from 1 -> 0 or retroactively seeds
529
+ // `coveredTokens` into already-sealed segments.
530
+ const userTurns = [];
531
+ for (let i = 0; i < units.length; i++) {
532
+ if (units[i]?.userText !== undefined) {
533
+ userTurns.push(i);
534
+ }
535
+ }
536
+ const start = userTurns[0] === 0 ? 1 : 0;
537
+ const boundary = googleClosedBoundary(units, start, cutoff);
538
+ if (boundary < start || boundary + 1 - start < 4)
539
+ return null;
540
+ const selected = units.slice(start, boundary + 1);
541
+ const eligibleTokens = selected.reduce((sum, unit) => sum + unit.baselineTokens, 0);
542
+ if (eligibleTokens < profile.history.minCollapseTokens)
543
+ return null;
544
+ const admitted = [];
545
+ const segments = [];
546
+ const images = [];
547
+ const imageSources = [];
548
+ const coveredTokens = new Set();
549
+ const minChunkTurns = 8;
550
+ let cursor = 0;
551
+ const cellH = renderCellHeight(profile.style);
552
+ const maxLines = Math.max(1, Math.floor((profile.maxHeightPx - 2 * PAD_Y) / cellH));
553
+ const maxCharsPerImg = Math.min(READABLE_CHARS_PER_IMAGE, Math.max(1, profile.stripCols) * maxLines);
554
+ const maxPaybackReads = profile.history.maxCachePaybackReads ?? 10;
555
+ const rates = resolvePriceRates(modelName);
556
+ const compactFraming = profile.history.framing === 'compact';
557
+ const intro = compactFraming ? COMPACT_HISTORY_TRANSCRIPT_INTRO : HISTORY_TRANSCRIPT_INTRO;
558
+ const outro = compactFraming ? COMPACT_HISTORY_TRANSCRIPT_OUTRO : HISTORY_TRANSCRIPT_OUTRO;
559
+ const framingOverheadTokens = googleTextTokens(`${intro}\n\n${outro}`);
560
+ const segmentPaysBack = (segBaselineTokens, segCollapsedTokens) => {
561
+ if (segCollapsedTokens >= segBaselineTokens)
562
+ return false;
563
+ const savedPerRead = (segBaselineTokens - segCollapsedTokens) * rates.read;
564
+ if (!(savedPerRead > 0))
565
+ return false;
566
+ const transitionCost = segCollapsedTokens * rates.write - segBaselineTokens * rates.read;
567
+ const paybackReads = Math.ceil(Math.max(0, transitionCost) / savedPerRead);
568
+ return paybackReads <= maxPaybackReads;
569
+ };
570
+ while (cursor < selected.length && images.length < profile.history.maxImages) {
571
+ const remaining = profile.history.maxImages - images.length;
572
+ let targetEnd = -1;
573
+ let accruedChars = 0;
574
+ for (let i = cursor; i < selected.length; i++) {
575
+ accruedChars += selected[i].text.length + 2;
576
+ if (i + 1 >= cursor + minChunkTurns && accruedChars >= READABLE_CHARS_PER_IMAGE) {
577
+ const closed = googleClosedBoundary(selected, cursor, i + 1) + 1;
578
+ if (closed > cursor) {
579
+ targetEnd = closed;
580
+ break;
581
+ }
582
+ }
583
+ }
584
+ if (targetEnd <= cursor)
585
+ break;
586
+ let candidateEnd = googleClosedBoundary(selected, cursor, targetEnd) + 1;
587
+ let accepted = false;
588
+ while (candidateEnd > cursor) {
589
+ const chunk = selected.slice(cursor, candidateEnd);
590
+ const chunkText = chunk.map((unit) => unit.text).filter(Boolean).join('\n\n');
591
+ if (!chunkText) {
592
+ admitted.push(...chunk);
593
+ cursor = candidateEnd;
594
+ accepted = true;
595
+ break;
596
+ }
597
+ const safe = neutralizeSentinel(chunkText);
598
+ const renderedText = reflowEnabled ? reflow(safe) ?? safe : safe;
599
+ if (estimateImageCount(renderedText, profile.stripCols, maxCharsPerImg, maxLines) > remaining) {
600
+ candidateEnd = googleClosedBoundary(selected, cursor, candidateEnd - 1) + 1;
601
+ continue;
602
+ }
603
+ const chunkImages = await renderTextToPngs(renderedText, profile.stripCols, profile.style, profile.maxHeightPx);
604
+ if (chunkImages.length > 0 && chunkImages.length <= remaining) {
605
+ const segSheet = prepareFactSheet(chunkText, profile.factSheetFormat)(coveredTokens);
606
+ const segImageTokens = chunkImages.reduce((sum, image) => sum + geminiVisionTokens(modelName, image.width, image.height), 0);
607
+ const segBaselineTokens = chunk.reduce((sum, unit) => sum + unit.baselineTokens, 0);
608
+ const segCollapsedTokens = segImageTokens + framingOverheadTokens + googleTextTokens(segSheet);
609
+ if (!segmentPaysBack(segBaselineTokens, segCollapsedTokens)) {
610
+ break;
611
+ }
612
+ if (segSheet) {
613
+ for (const tok of extractFactSheetTokens(segSheet))
614
+ coveredTokens.add(tok);
615
+ }
616
+ const chunkSources = chunkImages.map(() => chunkText);
617
+ segments.push({
618
+ images: chunkImages,
619
+ imageSources: chunkSources,
620
+ text: chunkText,
621
+ factSheet: segSheet,
622
+ });
623
+ admitted.push(...chunk);
624
+ images.push(...chunkImages);
625
+ imageSources.push(...chunkSources);
626
+ cursor = candidateEnd;
627
+ accepted = true;
628
+ break;
629
+ }
630
+ candidateEnd = googleClosedBoundary(selected, cursor, candidateEnd - 1) + 1;
631
+ }
632
+ if (!accepted)
633
+ break;
634
+ }
635
+ if (admitted.length < 4 || images.length === 0)
636
+ return null;
637
+ const text = admitted.map((unit) => unit.text).filter(Boolean).join('\n\n');
638
+ const baselineTokens = admitted.reduce((sum, unit) => sum + unit.baselineTokens, 0);
639
+ if (!text || baselineTokens < profile.history.minCollapseTokens)
640
+ return null;
641
+ const imageTokens = images.reduce((sum, image) => sum + geminiVisionTokens(modelName, image.width, image.height), 0);
642
+ const segSheets = segments.map((s) => s.factSheet).filter(Boolean);
643
+ const factSheet = segSheets.join('\n');
644
+ const endExclusive = start + admitted.length;
645
+ // Identify the active user request: the latest human user turn, plus any
646
+ // preceding user turn(s) that were not yet answered by a completed assistant
647
+ // prose turn (no tool calls) or that the latest user turn interjected into
648
+ // mid-work.
649
+ const activeUserIndices = [];
650
+ if (userTurns.length > 0) {
651
+ const lastUserIdx = userTurns[userTurns.length - 1];
652
+ activeUserIndices.push(lastUserIdx);
653
+ let needParentPrompt = units[lastUserIdx].userInterjection === true;
654
+ for (let i = lastUserIdx - 1; i >= 0; i--) {
655
+ const u = units[i];
656
+ if (u.userText !== undefined) {
657
+ activeUserIndices.unshift(i);
658
+ needParentPrompt = u.userInterjection === true;
659
+ continue;
660
+ }
661
+ if (!needParentPrompt && u.source.role === 'model') {
662
+ break;
663
+ }
664
+ }
665
+ }
666
+ const activeUserSet = new Set(activeUserIndices);
667
+ const collapsedUserIndices = userTurns.filter((i) => i >= start && i < endExclusive);
668
+ const collapsedActiveIndices = collapsedUserIndices.filter((i) => activeUserSet.has(i));
669
+ const collapsedPriorIndices = collapsedUserIndices.filter((i) => !activeUserSet.has(i));
670
+ // If Turn 0 remained anchored at index 0 (`start === 1`) and has been superseded
671
+ // by a later user turn, keep a prior-turn breadcrumb in the live tail without
672
+ // mutating contents[0] or any sealed segment.
673
+ if (start === 1 &&
674
+ userTurns[0] === 0 &&
675
+ userTurns.length > 1 &&
676
+ !activeUserSet.has(0) &&
677
+ !collapsedPriorIndices.includes(0)) {
678
+ collapsedPriorIndices.unshift(0);
679
+ }
680
+ let pinnedUserText;
681
+ if (collapsedUserIndices.length > 0 || collapsedPriorIndices.length > 0) {
682
+ const blocks = [];
683
+ if (collapsedPriorIndices.length > 0) {
684
+ // Never drop Turn 0 from prior-turn breadcrumbs when there are >6 user turns.
685
+ const recentPrior = collapsedPriorIndices.length > 6 && collapsedPriorIndices[0] === 0
686
+ ? [0, ...collapsedPriorIndices.slice(-5)]
687
+ : collapsedPriorIndices.slice(-6);
688
+ const priorLines = recentPrior.map((i) => `<user t="${i}">${compactPreview(units[i].userText)}</user>`);
689
+ blocks.push(`[Earlier user turns in this session (prior context only - superseded by later turns):\n${priorLines.join('\n')}]`);
690
+ }
691
+ if (collapsedActiveIndices.length > 0) {
692
+ const activeVerbatim = activeUserIndices
693
+ .map((i) => `<user t="${i}">\n${verbatimTaskText(units[i].userText)}\n</user>`)
694
+ .join('\n\n');
695
+ const activeSummary = activeUserIndices
696
+ .map((i) => `<user t="${i}"> ${compactPreview(units[i].userText)} </user>`)
697
+ .join(' ');
698
+ blocks.push(pinnedRequestBlock(activeVerbatim).trim());
699
+ blocks.push(buildLiveRequestGuard(activeSummary));
700
+ }
701
+ else {
702
+ blocks.push(buildLiveRequestGuard(undefined));
703
+ }
704
+ pinnedUserText = blocks.join('\n\n');
705
+ }
706
+ const segNativeText = segments
707
+ .map((s) => [intro, s.factSheet, outro].filter(Boolean).join('\n\n'))
708
+ .join('\n\n');
709
+ const nativeTokens = googleTextTokens([segNativeText, pinnedUserText].filter(Boolean).join('\n\n'));
710
+ if (!segmentPaysBack(baselineTokens, imageTokens + nativeTokens))
711
+ return null;
712
+ const droppedCodepoints = new Map();
713
+ let droppedChars = 0;
714
+ for (const image of images) {
715
+ droppedChars += image.droppedChars;
716
+ for (const [codepoint, count] of image.droppedCodepoints) {
717
+ droppedCodepoints.set(codepoint, (droppedCodepoints.get(codepoint) ?? 0) + count);
718
+ }
719
+ }
720
+ return {
721
+ start,
722
+ endExclusive,
723
+ segments,
724
+ images,
725
+ imageSources,
726
+ text,
727
+ factSheet,
728
+ ...(pinnedUserText ? { pinnedUserText } : {}),
729
+ baselineTokens,
730
+ nativeTokens,
731
+ collapsedTurns: admitted.length,
732
+ droppedChars,
733
+ droppedCodepoints,
734
+ };
735
+ }
736
+ function imagePart(image) {
737
+ return {
738
+ inlineData: {
739
+ mimeType: 'image/png',
740
+ data: bytesToBase64(image.png),
741
+ },
742
+ };
743
+ }
744
+ /**
745
+ * Normalizes Google turn roles so that:
746
+ * 1. Adjacent turns with the same role are merged.
747
+ * 2. The conversation starts with a user turn.
748
+ * 3. The conversation ends with a user turn (never a model turn), avoiding
749
+ * Google AI Studio's 400 "Requests ending with a model turn are not supported."
750
+ */
751
+ export function normalizeGoogleTurnRoles(contents) {
752
+ if (contents.length === 0)
753
+ return contents;
754
+ const merged = [];
755
+ for (const turn of contents) {
756
+ // Google AI Studio rejects empty-parts turns; skip turns with no content.
757
+ if (!turn || !Array.isArray(turn.parts) || turn.parts.length === 0)
758
+ continue;
759
+ const role = turn.role === 'model' ? 'model' : 'user';
760
+ const last = merged[merged.length - 1];
761
+ if (last && last.role === role) {
762
+ merged[merged.length - 1] = { ...last, parts: [...(last.parts ?? []), ...turn.parts] };
763
+ }
764
+ else {
765
+ merged.push({ ...turn, role, parts: [...turn.parts] });
766
+ }
767
+ }
768
+ if (merged.length === 0)
769
+ return [];
770
+ const first = merged[0];
771
+ if (first && first.role === 'model') {
772
+ merged.unshift({ role: 'user', parts: [{ text: ' ' }] });
773
+ }
774
+ const last = merged[merged.length - 1];
775
+ if (last && last.role === 'model') {
776
+ merged.push({ role: 'user', parts: [{ text: ' ' }] });
777
+ }
778
+ return merged;
779
+ }
780
+ function firstGoogleUserText(contents) {
781
+ if (!Array.isArray(contents))
782
+ return '';
783
+ const texts = [];
784
+ for (const turn of contents) {
785
+ if (!turn || typeof turn !== 'object')
786
+ continue;
787
+ if (turn.role === 'model') {
788
+ if (texts.length > 0)
789
+ break;
790
+ continue;
791
+ }
792
+ if (Array.isArray(turn.parts)) {
793
+ for (const part of turn.parts) {
794
+ if (part && typeof part === 'object' && typeof part.text === 'string' && part.text.trim()) {
795
+ texts.push(part.text);
796
+ }
797
+ }
798
+ }
799
+ if (texts.length > 0)
800
+ break;
801
+ }
802
+ return sessionAnchorText(texts);
803
+ }
804
+ function extractGoogleLiveTailTexts(contents) {
805
+ if (!Array.isArray(contents) || contents.length === 0)
806
+ return [];
807
+ const out = [];
808
+ const last = contents[contents.length - 1];
809
+ if (!last || !Array.isArray(last.parts))
810
+ return out;
811
+ const isToolResponseTurn = last.parts.some((part) => part && typeof part === 'object' && Boolean(part.functionResponse));
812
+ // Only inspect contents[n - 2] when contents[n - 1] is a tool-response turn,
813
+ // and ONLY pull functionCall names/args — never Turn t-1's user prompt prose.
814
+ if (isToolResponseTurn && contents.length >= 2) {
815
+ const prev = contents[contents.length - 2];
816
+ if (prev && Array.isArray(prev.parts)) {
817
+ for (const part of prev.parts) {
818
+ if (!part || typeof part !== 'object')
819
+ continue;
820
+ if (part.functionCall && typeof part.functionCall === 'object') {
821
+ const fcName = typeof part.functionCall.name === 'string' ? part.functionCall.name : '';
822
+ const serialized = safeJson(part.functionCall.args);
823
+ out.push(fcName ? `${fcName} ${serialized}` : serialized);
824
+ }
825
+ }
826
+ }
827
+ }
828
+ else if (!isToolResponseTurn && last.role === 'user' && contents.length >= 2) {
829
+ // If a trailing user prompt immediately follows a functionResponse turn, surface any
830
+ // active fault/stack snippet from those tool responses (never prior user prompt prose).
831
+ const prev = contents[contents.length - 2];
832
+ if (prev && Array.isArray(prev.parts)) {
833
+ for (const part of prev.parts) {
834
+ if (!part || typeof part !== 'object' || !part.functionResponse || typeof part.functionResponse !== 'object')
835
+ continue;
836
+ const frName = typeof part.functionResponse.name === 'string' ? part.functionResponse.name : '';
837
+ const frPartsText = Array.isArray(part.functionResponse.parts)
838
+ ? part.functionResponse.parts
839
+ .map((sub) => (sub && typeof sub === 'object' && typeof sub.text === 'string' ? sub.text : ''))
840
+ .filter(Boolean)
841
+ .join('\n')
842
+ : '';
843
+ const rawFr = frPartsText
844
+ ? `${safeJson(part.functionResponse.response)}\n${frPartsText}`
845
+ : safeJson(part.functionResponse.response);
846
+ const faultSnippet = extractFaultSignalSnippet(rawFr);
847
+ if (faultSnippet) {
848
+ out.push(frName ? `${frName} ${faultSnippet}` : faultSnippet);
849
+ }
850
+ }
851
+ }
852
+ }
853
+ const promptTexts = [];
854
+ for (const part of last.parts) {
855
+ if (!part || typeof part !== 'object')
856
+ continue;
857
+ if (typeof part.text === 'string' && part.text.trim()) {
858
+ promptTexts.push(part.text);
859
+ }
860
+ else if (part.functionCall && typeof part.functionCall === 'object') {
861
+ const fcName = typeof part.functionCall.name === 'string' ? part.functionCall.name : '';
862
+ const serialized = safeJson(part.functionCall.args);
863
+ out.push(fcName ? `${fcName} ${serialized}` : serialized);
864
+ }
865
+ else if (part.functionResponse && typeof part.functionResponse === 'object') {
866
+ const frName = typeof part.functionResponse.name === 'string' ? part.functionResponse.name : '';
867
+ const frPartsText = Array.isArray(part.functionResponse.parts)
868
+ ? part.functionResponse.parts
869
+ .map((sub) => (sub && typeof sub === 'object' && typeof sub.text === 'string' ? sub.text : ''))
870
+ .filter(Boolean)
871
+ .join('\n')
872
+ : '';
873
+ const rawFr = frPartsText
874
+ ? `${safeJson(part.functionResponse.response)}\n${frPartsText}`
875
+ : safeJson(part.functionResponse.response);
876
+ const faultSnippet = extractFaultSignalSnippet(rawFr);
877
+ if (faultSnippet) {
878
+ out.push(frName ? `${frName} ${faultSnippet}` : faultSnippet);
879
+ }
880
+ }
881
+ }
882
+ for (const t of promptTexts)
883
+ out.push(t);
884
+ return out;
885
+ }
886
+ function appendGoogleTailHydration(req, hydrationBlock) {
887
+ if (!hydrationBlock)
888
+ return;
889
+ if (!Array.isArray(req.contents))
890
+ req.contents = [];
891
+ // Never scan backwards past model turns into earlier cached user messages.
892
+ const last = req.contents[req.contents.length - 1];
893
+ if (last && last.role === 'user') {
894
+ if (!Array.isArray(last.parts))
895
+ last.parts = [];
896
+ last.parts.push({ text: hydrationBlock });
897
+ return;
898
+ }
899
+ req.contents.push({ role: 'user', parts: [{ text: hydrationBlock }] });
900
+ }
901
+ export async function transformGoogleGenerateContent(bodyBytes, modelName, options = {}) {
902
+ const isGemini = isGeminiModel(modelName);
903
+ const text = new TextDecoder().decode(bodyBytes);
904
+ let parsed;
905
+ try {
906
+ parsed = JSON.parse(text);
907
+ }
908
+ catch {
909
+ const info = createDefaultInfo(modelName);
910
+ if (!isGemini)
911
+ info.reason = 'unsupported_model';
912
+ return { body: bodyBytes, info };
913
+ }
914
+ const reqRecord = record(parsed);
915
+ if (!reqRecord) {
916
+ const info = createDefaultInfo(modelName);
917
+ if (!isGemini)
918
+ info.reason = 'unsupported_model';
919
+ return { body: bodyBytes, info };
920
+ }
921
+ const isEnvelope = Boolean(reqRecord.request
922
+ && typeof reqRecord.request === 'object'
923
+ && !Array.isArray(reqRecord.request));
924
+ const req = (isEnvelope ? reqRecord.request : reqRecord);
925
+ const info = createDefaultInfo(modelName);
926
+ const measuredProfile = isGemini && hasGeminiMeasuredProfile(modelName);
927
+ const firstUser = firstGoogleUserText(req.contents);
928
+ const resolvedSessionKey = await applyClientSessionIdentity(info, firstUser, options);
929
+ const infoMeasured = measuredProfile;
930
+ if (options.compress === false) {
931
+ info.reason = 'compression_disabled';
932
+ return infoMeasured
933
+ ? withStampedThoughtSignatures(req, bodyBytes, info, isEnvelope ? reqRecord : undefined)
934
+ : { body: bodyBytes, info };
935
+ }
936
+ const sessionState = resolvedSessionKey
937
+ ? noteHistoryRequest(resolvedSessionKey, { model: modelName })
938
+ : { cold: false, minFreezeStep: 0 };
939
+ const pinChars = relocateGooglePins(req);
940
+ if (pinChars > 0)
941
+ info.pinChars = pinChars;
942
+ const nativeImageBytes = countGoogleInlineImageBytes(req);
943
+ const opticalEnabled = measuredProfile &&
944
+ options.imageCompress !== false &&
945
+ options.stageToggles?.optical !== false;
946
+ const textHygieneActive = isTextHygieneActive(options.textHygiene);
947
+ let hygieneStats;
948
+ const runGoogleHygiene = (hygieneOpts) => {
949
+ if (!textHygieneActive)
950
+ return;
951
+ hygieneStats = applyGoogleTextHygiene(req, {
952
+ foldLogs: hygieneOpts.deep,
953
+ deepTextCompact: hygieneOpts.deep,
954
+ cleanUserPayloads: options.cleanUserPayloads === true,
955
+ enableTscg: hygieneOpts.hasStaticSlabOptical ? false : options.stageToggles?.tscg,
956
+ enableToon: options.stageToggles?.toon,
957
+ enableAcdc: options.stageToggles?.acdc,
958
+ enableCasi: hygieneOpts.deep && options.stageToggles?.casi !== false,
959
+ enableLsm: options.stageToggles?.lsm,
960
+ enableMmu: options.stageToggles?.mmu,
961
+ enableSkillLinker: hygieneOpts.hasStaticSlabOptical ? false : options.stageToggles?.skillLinker,
962
+ aggressiveToon: resolveTextHygieneMode(options.textHygiene) === 'on',
963
+ model: modelName,
964
+ expectedOutputTokens: options.expectedOutputTokens,
965
+ rawBodyBytes: bodyBytes.byteLength,
966
+ nativeImageBytes,
967
+ sessionKey: resolvedSessionKey,
968
+ firstUserText: firstUser,
969
+ sessionCacheCold: sessionState.cold,
970
+ liveTailTexts: hygieneOpts.deep ? extractGoogleLiveTailTexts(req.contents) : undefined,
971
+ appendTailHydration: hygieneOpts.deep ? (blk) => appendGoogleTailHydration(req, blk) : undefined,
972
+ });
973
+ if (hygieneStats.changed || hygieneStats.tailHydrated) {
974
+ info.textHygieneSavedChars = hygieneStats.savedChars;
975
+ info.textHygieneSavedTokens = hygieneStats.savedTokens;
976
+ info.textHygieneBlocks = hygieneStats.blocks;
977
+ info.textHygieneStages = [...hygieneStats.stages];
978
+ if (hygieneStats.cliffAvoided)
979
+ info.cliffAvoided = hygieneStats.cliffAvoided;
980
+ }
981
+ };
982
+ let cachedPinBody;
983
+ const getPinBody = () => {
984
+ if (cachedPinBody)
985
+ return cachedPinBody;
986
+ cachedPinBody = pinChars > 0 || hygieneStats?.changed || hygieneStats?.tailHydrated
987
+ ? new TextEncoder().encode(JSON.stringify(isEnvelope ? { ...reqRecord, request: req } : req))
988
+ : bodyBytes;
989
+ return cachedPinBody;
990
+ };
991
+ if (!opticalEnabled) {
992
+ runGoogleHygiene({ deep: true });
993
+ if (hygieneStats?.changed) {
994
+ info.compressed = true;
995
+ info.reason = 'text_hygiene';
996
+ return measuredProfile
997
+ ? withStampedThoughtSignatures(req, getPinBody(), info, isEnvelope ? reqRecord : undefined)
998
+ : { body: getPinBody(), info };
999
+ }
1000
+ if (hygieneStats?.tailHydrated) {
1001
+ info.reason = 'mmu_hydrate';
1002
+ return measuredProfile
1003
+ ? withStampedThoughtSignatures(req, getPinBody(), info, isEnvelope ? reqRecord : undefined)
1004
+ : { body: getPinBody(), info };
1005
+ }
1006
+ info.reason = !measuredProfile ? 'unsupported_model' : 'image_disabled';
1007
+ if (pinChars > 0) {
1008
+ return measuredProfile
1009
+ ? withStampedThoughtSignatures(req, getPinBody(), info, isEnvelope ? reqRecord : undefined)
1010
+ : { body: getPinBody(), info };
1011
+ }
1012
+ return { body: bodyBytes, info };
1013
+ }
1014
+ const finishEarlyInvalid = () => {
1015
+ if (hygieneStats?.changed) {
1016
+ info.compressed = true;
1017
+ info.reason = 'text_hygiene';
1018
+ }
1019
+ else if (hygieneStats?.tailHydrated) {
1020
+ info.reason = 'mmu_hydrate';
1021
+ }
1022
+ return { body: getPinBody(), info };
1023
+ };
1024
+ // Extract system instructions
1025
+ const systemTexts = [];
1026
+ const systemInstruction = record(req.systemInstruction);
1027
+ const systemParts = systemInstruction?.parts;
1028
+ let invalidSystemParts = systemParts !== undefined && !Array.isArray(systemParts);
1029
+ if (!invalidSystemParts && Array.isArray(systemParts)) {
1030
+ for (const rawPart of systemParts) {
1031
+ const part = record(rawPart);
1032
+ if (!part) {
1033
+ invalidSystemParts = true;
1034
+ break;
1035
+ }
1036
+ if (typeof part.text === 'string' && part.text.trim()) {
1037
+ systemTexts.push(part.text);
1038
+ info.staticChars += part.text.length;
1039
+ }
1040
+ }
1041
+ }
1042
+ if (invalidSystemParts) {
1043
+ runGoogleHygiene({ deep: false });
1044
+ return finishEarlyInvalid();
1045
+ }
1046
+ const toolRewrite = options.compressTools === false
1047
+ // Tools pass through untouched, so the saving is 0 by construction. Don't
1048
+ // pay two full safeJson walks of the tool array to compute `x - x`.
1049
+ ? { tools: req.tools, docs: '', originalTokens: 0, rewrittenTokens: 0 }
1050
+ : rewriteGoogleTools(req.tools);
1051
+ if (toolRewrite.docs)
1052
+ info.toolDocsChars = toolRewrite.docs.length;
1053
+ const authorityText = systemTexts.join('\n\n');
1054
+ const combinedRaw = [authorityText, toolRewrite.docs].filter(Boolean).join('\n\n');
1055
+ info.origChars = combinedRaw.length;
1056
+ const profile = resolveGeminiProfile(modelName);
1057
+ const contentPromptTokens = Array.isArray(req.contents)
1058
+ ? req.contents.reduce((sum, c) => sum + (record(c) ? googleHistoryUnit(c, 0).baselineTokens : 0), 0)
1059
+ : 0;
1060
+ const estPromptTokens = googleTextTokens(authorityText) + toolRewrite.originalTokens + contentPromptTokens;
1061
+ const opticalHistoryPolicy = resolveOpticalHistoryPolicy({
1062
+ opticalMode: options.opticalMode,
1063
+ collapseHistory: options.collapseHistory === true ? true : undefined,
1064
+ model: modelName,
1065
+ estPromptTokens,
1066
+ textHygieneActive,
1067
+ sessionKey: resolvedSessionKey,
1068
+ sessionCold: sessionState.cold,
1069
+ });
1070
+ const hybridTextMmu = opticalHistoryPolicy === 'hybrid';
1071
+ if (priceMode() === 'kosha' && gateRatesFor(modelName, { promptTokens: estPromptTokens }) === null) {
1072
+ runGoogleHygiene({ deep: hybridTextMmu });
1073
+ info.reason = hygieneStats?.changed
1074
+ ? 'text_hygiene'
1075
+ : hygieneStats?.tailHydrated
1076
+ ? 'mmu_hydrate'
1077
+ : 'unpriced_model';
1078
+ if (hygieneStats?.changed)
1079
+ info.compressed = true;
1080
+ return withStampedThoughtSignatures(req, getPinBody(), info, isEnvelope ? reqRecord : undefined);
1081
+ }
1082
+ if (!hybridTextMmu) {
1083
+ runGoogleHygiene({ deep: false });
1084
+ }
1085
+ let staticImages = [];
1086
+ let staticProfitable = false;
1087
+ let textTokens = 0;
1088
+ let imageTokens = 0;
1089
+ let nativeInjectedTokens = 0;
1090
+ let fsText = null;
1091
+ let renderedText = '';
1092
+ if (combinedRaw) {
1093
+ const combined = compactSlabWhitespace(combinedRaw).trimEnd();
1094
+ info.systemSha8 = await sha8(combined);
1095
+ const reflowNote = options.reflow !== false
1096
+ ? ' The glyph ↵ (U+21B5) marks an original hard line break in content; treat it as a real newline.'
1097
+ : '';
1098
+ const header = CHAT_HEADER.replace('\n====', reflowNote + '\n====');
1099
+ renderedText = prepareImagedRenderText(header + combined, options.reflow !== false);
1100
+ const maxCols = options.cols ?? profile.stripCols;
1101
+ const cols = Math.min(shrinkColsToContent(renderedText, maxCols, profile.style.markerScale, profile.style.font), profile.stripCols);
1102
+ staticImages = await renderTextToPngs(renderedText, cols, profile.style, profile.maxHeightPx);
1103
+ imageTokens = staticImages.reduce((total, image) => total + geminiVisionTokens(modelName, image.width, image.height), 0);
1104
+ textTokens = Math.max(1, googleTextTokens(authorityText)
1105
+ + Math.max(0, toolRewrite.originalTokens - toolRewrite.rewrittenTokens));
1106
+ fsText = factSheetText(combinedRaw, profile.factSheetFormat);
1107
+ const nativeText = SYSTEM_POINTER + (fsText ?? '');
1108
+ nativeInjectedTokens = Math.ceil(nativeText.length / 3.5);
1109
+ const slabProfitable = imageTokens + nativeInjectedTokens < textTokens;
1110
+ info.gateEval = {
1111
+ site: 'slab',
1112
+ imageTokens,
1113
+ textTokens,
1114
+ burnImageSide: nativeInjectedTokens,
1115
+ burnTextSide: 0,
1116
+ profitable: slabProfitable,
1117
+ };
1118
+ staticProfitable = slabProfitable;
1119
+ }
1120
+ // Build static image parts if static slab is profitable
1121
+ const hasStaticCompression = staticProfitable && staticImages.length > 0;
1122
+ const imageParts = hasStaticCompression ? staticImages.map(imagePart) : [];
1123
+ if (hasStaticCompression && fsText) {
1124
+ imageParts.push({ text: fsText });
1125
+ }
1126
+ if (hybridTextMmu) {
1127
+ runGoogleHygiene({ deep: true, hasStaticSlabOptical: hasStaticCompression });
1128
+ }
1129
+ // Prepare transformed request. Plan history against the ORIGINAL contents;
1130
+ // inserting the slab image first would make content[0] an opaque image barrier.
1131
+ if (req.contents !== undefined && !Array.isArray(req.contents)) {
1132
+ return finishEarlyInvalid();
1133
+ }
1134
+ const originalContents = Array.isArray(req.contents) ? [...req.contents] : [];
1135
+ for (const content of originalContents) {
1136
+ if (!record(content) || (content.parts !== undefined && !Array.isArray(content.parts))) {
1137
+ return finishEarlyInvalid();
1138
+ }
1139
+ }
1140
+ const historyPlan = options.collapseHistory === false || hybridTextMmu
1141
+ ? null
1142
+ : await planGoogleHistory(originalContents, modelName, options.reflow !== false);
1143
+ let contents = originalContents;
1144
+ if (historyPlan) {
1145
+ const compactFraming = resolveGeminiProfile(modelName).history.framing === 'compact';
1146
+ const intro = compactFraming ? COMPACT_HISTORY_TRANSCRIPT_INTRO : HISTORY_TRANSCRIPT_INTRO;
1147
+ const outro = compactFraming ? COMPACT_HISTORY_TRANSCRIPT_OUTRO : HISTORY_TRANSCRIPT_OUTRO;
1148
+ const historyParts = [];
1149
+ for (const seg of historyPlan.segments) {
1150
+ historyParts.push({ text: intro });
1151
+ historyParts.push(...seg.images.map(imagePart));
1152
+ if (seg.factSheet)
1153
+ historyParts.push({ text: seg.factSheet });
1154
+ historyParts.push({ text: outro });
1155
+ }
1156
+ if (historyPlan.start > 0 && contents[historyPlan.start - 1]?.role === 'user') {
1157
+ // Keep Gemini's alternating role shape: append the synthetic prior-context
1158
+ // parts to the preceding live user turn rather than emitting user→user.
1159
+ const carrier = contents[historyPlan.start - 1];
1160
+ contents = [
1161
+ ...contents.slice(0, historyPlan.start - 1),
1162
+ { ...carrier, parts: [...(carrier.parts ?? []), ...historyParts] },
1163
+ ...contents.slice(historyPlan.endExclusive),
1164
+ ];
1165
+ }
1166
+ else {
1167
+ contents = [
1168
+ ...contents.slice(0, historyPlan.start),
1169
+ { role: 'user', parts: historyParts },
1170
+ ...contents.slice(historyPlan.endExclusive),
1171
+ ];
1172
+ }
1173
+ if (historyPlan.pinnedUserText) {
1174
+ // Keep mutable active/prior user framing OUT of contents[0] so sealed
1175
+ // optical segments remain byte-identical across turns and never bust KV cache.
1176
+ const last = contents[contents.length - 1];
1177
+ if (last && last.role === 'user') {
1178
+ contents[contents.length - 1] = {
1179
+ ...last,
1180
+ parts: [{ text: historyPlan.pinnedUserText }, ...(last.parts ?? [])],
1181
+ };
1182
+ }
1183
+ else {
1184
+ contents.push({ role: 'user', parts: [{ text: historyPlan.pinnedUserText }] });
1185
+ }
1186
+ }
1187
+ }
1188
+ const toolResultPlan = hybridTextMmu
1189
+ ? {
1190
+ contents,
1191
+ images: [],
1192
+ imageSources: [],
1193
+ baselineTokens: 0,
1194
+ nativeTokens: 0,
1195
+ compressedChars: 0,
1196
+ bucketChars: {},
1197
+ droppedChars: 0,
1198
+ droppedCodepoints: new Map(),
1199
+ }
1200
+ : await compressGoogleToolResults(contents, modelName, options);
1201
+ contents = toolResultPlan.contents;
1202
+ const hasHistoryCompression = !!historyPlan && historyPlan.images.length > 0;
1203
+ const hasToolCompression = toolResultPlan.images.length > 0;
1204
+ if (!hasStaticCompression && !hasHistoryCompression && !hasToolCompression) {
1205
+ if (hygieneStats?.changed) {
1206
+ info.compressed = true;
1207
+ info.reason = 'text_hygiene';
1208
+ }
1209
+ else if (hygieneStats?.tailHydrated) {
1210
+ info.reason = 'mmu_hydrate';
1211
+ }
1212
+ else if (!combinedRaw) {
1213
+ info.reason = 'no_static_context';
1214
+ }
1215
+ else if (!staticProfitable) {
1216
+ info.reason = 'not_profitable';
1217
+ }
1218
+ return withStampedThoughtSignatures(req, getPinBody(), info, isEnvelope ? reqRecord : undefined);
1219
+ }
1220
+ if (hasStaticCompression) {
1221
+ // Static context goes first in the first user turn, matching the Anthropic path.
1222
+ if (contents.length > 0 && contents[0] && contents[0].role === 'user') {
1223
+ const firstTurn = contents[0];
1224
+ contents[0] = {
1225
+ ...firstTurn,
1226
+ parts: [...imageParts, ...(firstTurn.parts || [])],
1227
+ };
1228
+ }
1229
+ else {
1230
+ contents.unshift({
1231
+ role: 'user',
1232
+ parts: imageParts,
1233
+ });
1234
+ }
1235
+ }
1236
+ const normalizedContents = normalizeGeminiThoughtSignatures(normalizeGoogleTurnRoles(contents));
1237
+ // Keep a native system-level pointer so the imaged instruction retains its
1238
+ // original authority instead of being demoted to ordinary user content.
1239
+ const transformedReq = {
1240
+ ...req,
1241
+ contents: normalizedContents,
1242
+ ...(hasStaticCompression && toolRewrite.tools !== undefined ? { tools: toolRewrite.tools } : {}),
1243
+ ...(hasStaticCompression
1244
+ ? {
1245
+ systemInstruction: {
1246
+ ...req.systemInstruction,
1247
+ parts: [{ text: SYSTEM_POINTER }],
1248
+ },
1249
+ }
1250
+ : {}),
1251
+ };
1252
+ const effectiveStaticImages = hasStaticCompression ? staticImages : [];
1253
+ const mergedDroppedCodepoints = new Map();
1254
+ let totalDroppedChars = 0;
1255
+ for (const img of effectiveStaticImages) {
1256
+ totalDroppedChars += img.droppedChars;
1257
+ for (const [codepoint, count] of img.droppedCodepoints) {
1258
+ mergedDroppedCodepoints.set(codepoint, (mergedDroppedCodepoints.get(codepoint) ?? 0) + count);
1259
+ }
1260
+ }
1261
+ info.compressed = true;
1262
+ info.imageCount = effectiveStaticImages.length;
1263
+ info.imageBytes = effectiveStaticImages.reduce((acc, img) => acc + img.png.byteLength, 0);
1264
+ info.imageTokens = hasStaticCompression ? imageTokens : 0;
1265
+ info.baselineImagedTokens = hasStaticCompression ? textTokens : 0;
1266
+ info.nativeInjectedTokens = hasStaticCompression ? nativeInjectedTokens : 0;
1267
+ info.compressedChars = hasStaticCompression ? combinedRaw.length : 0;
1268
+ info.bucketChars = hasStaticCompression ? { static_slab: combinedRaw.length } : {};
1269
+ info.firstImagePng = effectiveStaticImages[0]?.png;
1270
+ info.firstImageWidth = effectiveStaticImages[0]?.width;
1271
+ info.firstImageHeight = effectiveStaticImages[0]?.height;
1272
+ info.imagePngs = effectiveStaticImages.map((image) => image.png);
1273
+ info.imageDims = effectiveStaticImages.map((image) => ({ width: image.width, height: image.height }));
1274
+ info.imageSourceText = hasStaticCompression ? renderedText.slice(0, 65_536) : '';
1275
+ // Google renders a single combined text slab into page images; share source text across pages.
1276
+ info.imageSourceTexts = effectiveStaticImages.map(() => info.imageSourceText);
1277
+ if (historyPlan) {
1278
+ const historyImageTokens = historyPlan.images.reduce((sum, image) => sum + geminiVisionTokens(modelName, image.width, image.height), 0);
1279
+ info.imageTokens += historyImageTokens;
1280
+ info.baselineImagedTokens += historyPlan.baselineTokens;
1281
+ info.nativeInjectedTokens += historyPlan.nativeTokens;
1282
+ info.imageCount += historyPlan.images.length;
1283
+ info.imageBytes += historyPlan.images.reduce((sum, image) => sum + image.png.byteLength, 0);
1284
+ info.imagePngs.push(...historyPlan.images.map((image) => image.png));
1285
+ info.imageDims.push(...historyPlan.images.map((image) => ({ width: image.width, height: image.height })));
1286
+ info.imageSourceTexts.push(...historyPlan.imageSources);
1287
+ info.compressedChars += historyPlan.text.length;
1288
+ info.bucketChars = { ...info.bucketChars, history: historyPlan.text.length };
1289
+ info.historyTextChars = historyPlan.text.length;
1290
+ info.collapsedTurns = historyPlan.collapsedTurns;
1291
+ info.collapsedChars = historyPlan.text.length;
1292
+ info.collapsedImages = historyPlan.images.length;
1293
+ info.historyReason = 'collapsed';
1294
+ totalDroppedChars += historyPlan.droppedChars;
1295
+ for (const [codepoint, count] of historyPlan.droppedCodepoints) {
1296
+ mergedDroppedCodepoints.set(codepoint, (mergedDroppedCodepoints.get(codepoint) ?? 0) + count);
1297
+ }
1298
+ }
1299
+ else if (options.collapseHistory !== false && !hybridTextMmu) {
1300
+ info.historyReason = originalContents.length > profile.history.keepTail
1301
+ ? 'not_profitable'
1302
+ : 'no_history';
1303
+ }
1304
+ if (toolResultPlan.images.length > 0) {
1305
+ const resultImageTokens = toolResultPlan.images.reduce((sum, image) => sum + geminiVisionTokens(modelName, image.width, image.height), 0);
1306
+ info.imageTokens += resultImageTokens;
1307
+ info.baselineImagedTokens += toolResultPlan.baselineTokens;
1308
+ info.nativeInjectedTokens += toolResultPlan.nativeTokens;
1309
+ info.imageCount += toolResultPlan.images.length;
1310
+ info.imageBytes += toolResultPlan.images.reduce((sum, image) => sum + image.png.byteLength, 0);
1311
+ info.imagePngs.push(...toolResultPlan.images.map((image) => image.png));
1312
+ info.imageDims.push(...toolResultPlan.images.map((image) => ({ width: image.width, height: image.height })));
1313
+ info.imageSourceTexts.push(...toolResultPlan.imageSources);
1314
+ info.compressedChars += toolResultPlan.compressedChars;
1315
+ info.toolResultImgs = toolResultPlan.images.length;
1316
+ info.bucketChars = { ...info.bucketChars, ...toolResultPlan.bucketChars };
1317
+ totalDroppedChars += toolResultPlan.droppedChars;
1318
+ for (const [codepoint, count] of toolResultPlan.droppedCodepoints) {
1319
+ mergedDroppedCodepoints.set(codepoint, (mergedDroppedCodepoints.get(codepoint) ?? 0) + count);
1320
+ }
1321
+ }
1322
+ info.droppedChars = (info.droppedChars ?? 0) + totalDroppedChars;
1323
+ info.droppedCodepointsTop = droppedCodepointsTop(mergedDroppedCodepoints) ?? {};
1324
+ if (hybridTextMmu && hasStaticCompression) {
1325
+ info.reason = 'hybrid_slab_optical';
1326
+ const stages = info.textHygieneStages ? [...info.textHygieneStages] : [];
1327
+ if (!stages.includes('hybrid_slab_optical'))
1328
+ stages.push('hybrid_slab_optical');
1329
+ info.textHygieneStages = stages;
1330
+ }
1331
+ const outPayload = isEnvelope ? { ...reqRecord, request: transformedReq } : transformedReq;
1332
+ const transformedBytes = new TextEncoder().encode(JSON.stringify(outPayload));
1333
+ return { body: transformedBytes, info };
1334
+ }
1335
+ function isNormalizedGoogleTurnRoles(contents) {
1336
+ if (contents.length === 0)
1337
+ return true;
1338
+ for (let i = 0; i < contents.length; i++) {
1339
+ const turn = contents[i];
1340
+ if (!turn || !Array.isArray(turn.parts) || turn.parts.length === 0)
1341
+ return false;
1342
+ const expectedRole = i % 2 === 0 ? 'user' : 'model';
1343
+ const role = turn.role === 'model' ? 'model' : 'user';
1344
+ if (role !== expectedRole)
1345
+ return false;
1346
+ }
1347
+ return contents.length % 2 === 1;
1348
+ }
1349
+ function withStampedThoughtSignatures(req, bodyBytes, info, envelopeRecord) {
1350
+ if (!Array.isArray(req.contents))
1351
+ return { body: bodyBytes, info };
1352
+ const normalized = isNormalizedGoogleTurnRoles(req.contents)
1353
+ ? req.contents
1354
+ : normalizeGoogleTurnRoles(req.contents);
1355
+ const normalizedSignatures = normalizeGeminiThoughtSignatures(normalized);
1356
+ if (normalizedSignatures === req.contents && normalized === req.contents)
1357
+ return { body: bodyBytes, info };
1358
+ const outObj = envelopeRecord
1359
+ ? { ...envelopeRecord, request: { ...req, contents: normalizedSignatures } }
1360
+ : { ...req, contents: normalizedSignatures };
1361
+ return {
1362
+ body: new TextEncoder().encode(JSON.stringify(outObj)),
1363
+ info,
1364
+ };
1365
+ }
1366
+ function createDefaultInfo(_model) {
1367
+ return {
1368
+ compressed: false,
1369
+ reason: undefined,
1370
+ origChars: 0,
1371
+ compressedChars: 0,
1372
+ staticChars: 0,
1373
+ dynamicChars: 0,
1374
+ dynamicBlockCount: 0,
1375
+ imageCount: 0,
1376
+ imageBytes: 0,
1377
+ droppedCodepointsTop: {},
1378
+ };
1379
+ }
1380
+ //# sourceMappingURL=google.js.map