@sriinnu/fiche 0.0.0-stage → 0.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (196) hide show
  1. package/CHANGELOG.md +134 -0
  2. package/LICENSE +22 -0
  3. package/NOTICE +13 -0
  4. package/PRIVACY.md +41 -0
  5. package/README.md +288 -2
  6. package/SECURITY.md +53 -0
  7. package/assets/JETBRAINS_MONO_LICENSE.txt +89 -0
  8. package/assets/SPLEEN_LICENSE.txt +24 -0
  9. package/assets/UNIFONT_LICENSE.txt +476 -0
  10. package/assets/fiche-logo-dark.svg +61 -0
  11. package/assets/fiche-logo-light.svg +61 -0
  12. package/assets/fiche-logo.svg +71 -0
  13. package/assets/fiche-mark.svg +48 -0
  14. package/bin/cli.js +7 -0
  15. package/bin/mcp.js +8 -0
  16. package/dist/calibrate.d.ts +30 -0
  17. package/dist/calibrate.js +588 -0
  18. package/dist/core/anthropic-vision.d.ts +28 -0
  19. package/dist/core/anthropic-vision.js +34 -0
  20. package/dist/core/applicability.d.ts +63 -0
  21. package/dist/core/applicability.js +151 -0
  22. package/dist/core/atlas-gray-jbmono10.d.ts +26 -0
  23. package/dist/core/atlas-gray-jbmono10.js +64 -0
  24. package/dist/core/atlas-gray-jbmono12.d.ts +26 -0
  25. package/dist/core/atlas-gray-jbmono12.js +64 -0
  26. package/dist/core/atlas-gray-jbmono14.d.ts +26 -0
  27. package/dist/core/atlas-gray-jbmono14.js +64 -0
  28. package/dist/core/atlas-gray.d.ts +26 -0
  29. package/dist/core/atlas-gray.js +64 -0
  30. package/dist/core/atlas-jbmono10.d.ts +34 -0
  31. package/dist/core/atlas-jbmono10.js +71 -0
  32. package/dist/core/atlas-jbmono12.d.ts +34 -0
  33. package/dist/core/atlas-jbmono12.js +71 -0
  34. package/dist/core/atlas-jbmono14.d.ts +34 -0
  35. package/dist/core/atlas-jbmono14.js +71 -0
  36. package/dist/core/atlas.d.ts +34 -0
  37. package/dist/core/atlas.js +71 -0
  38. package/dist/core/baseline.d.ts +121 -0
  39. package/dist/core/baseline.js +200 -0
  40. package/dist/core/calibration.d.ts +86 -0
  41. package/dist/core/calibration.js +547 -0
  42. package/dist/core/casi-delta.d.ts +63 -0
  43. package/dist/core/casi-delta.js +1271 -0
  44. package/dist/core/claude-model-profiles.d.ts +53 -0
  45. package/dist/core/claude-model-profiles.js +160 -0
  46. package/dist/core/client-tool-round.d.ts +31 -0
  47. package/dist/core/client-tool-round.js +58 -0
  48. package/dist/core/codex-cache.d.ts +20 -0
  49. package/dist/core/codex-cache.js +59 -0
  50. package/dist/core/context-mmu.d.ts +350 -0
  51. package/dist/core/context-mmu.js +3028 -0
  52. package/dist/core/cpt-fit.d.ts +70 -0
  53. package/dist/core/cpt-fit.js +197 -0
  54. package/dist/core/env.d.ts +8 -0
  55. package/dist/core/env.js +15 -0
  56. package/dist/core/export.d.ts +127 -0
  57. package/dist/core/export.js +385 -0
  58. package/dist/core/factsheet.d.ts +77 -0
  59. package/dist/core/factsheet.js +494 -0
  60. package/dist/core/gemini-model-profiles.d.ts +20 -0
  61. package/dist/core/gemini-model-profiles.js +134 -0
  62. package/dist/core/google.d.ts +76 -0
  63. package/dist/core/google.js +1380 -0
  64. package/dist/core/gpt-model-profiles.d.ts +218 -0
  65. package/dist/core/gpt-model-profiles.js +570 -0
  66. package/dist/core/gpt-tokens.d.ts +14 -0
  67. package/dist/core/gpt-tokens.js +165 -0
  68. package/dist/core/history.d.ts +197 -0
  69. package/dist/core/history.js +1003 -0
  70. package/dist/core/index.d.ts +16 -0
  71. package/dist/core/index.js +16 -0
  72. package/dist/core/library.d.ts +80 -0
  73. package/dist/core/library.js +131 -0
  74. package/dist/core/measurement.d.ts +34 -0
  75. package/dist/core/measurement.js +280 -0
  76. package/dist/core/messages-chat-bridge.d.ts +23 -0
  77. package/dist/core/messages-chat-bridge.js +747 -0
  78. package/dist/core/messages-responses-bridge.d.ts +11 -0
  79. package/dist/core/messages-responses-bridge.js +893 -0
  80. package/dist/core/openai-history.d.ts +184 -0
  81. package/dist/core/openai-history.js +1279 -0
  82. package/dist/core/openai-savings.d.ts +57 -0
  83. package/dist/core/openai-savings.js +116 -0
  84. package/dist/core/openai.d.ts +68 -0
  85. package/dist/core/openai.js +2523 -0
  86. package/dist/core/pin.d.ts +199 -0
  87. package/dist/core/pin.js +1353 -0
  88. package/dist/core/png.d.ts +14 -0
  89. package/dist/core/png.js +188 -0
  90. package/dist/core/prefix-tape.d.ts +102 -0
  91. package/dist/core/prefix-tape.js +315 -0
  92. package/dist/core/price-id.d.ts +10 -0
  93. package/dist/core/price-id.js +26 -0
  94. package/dist/core/prices.generated.d.ts +36 -0
  95. package/dist/core/prices.generated.js +369 -0
  96. package/dist/core/pricing.d.ts +134 -0
  97. package/dist/core/pricing.js +335 -0
  98. package/dist/core/profile-base.d.ts +30 -0
  99. package/dist/core/profile-base.js +67 -0
  100. package/dist/core/provider-router.d.ts +51 -0
  101. package/dist/core/provider-router.js +121 -0
  102. package/dist/core/proxy.d.ts +252 -0
  103. package/dist/core/proxy.js +2929 -0
  104. package/dist/core/reader-tier.d.ts +24 -0
  105. package/dist/core/reader-tier.js +118 -0
  106. package/dist/core/render.d.ts +280 -0
  107. package/dist/core/render.js +1302 -0
  108. package/dist/core/request-guard.d.ts +31 -0
  109. package/dist/core/request-guard.js +126 -0
  110. package/dist/core/request-transform.d.ts +43 -0
  111. package/dist/core/request-transform.js +173 -0
  112. package/dist/core/schema-compiler.d.ts +64 -0
  113. package/dist/core/schema-compiler.js +1696 -0
  114. package/dist/core/schema-strip.d.ts +29 -0
  115. package/dist/core/schema-strip.js +173 -0
  116. package/dist/core/session-state.d.ts +219 -0
  117. package/dist/core/session-state.js +929 -0
  118. package/dist/core/stage-plugins.d.ts +45 -0
  119. package/dist/core/stage-plugins.js +205 -0
  120. package/dist/core/text-history.d.ts +74 -0
  121. package/dist/core/text-history.js +612 -0
  122. package/dist/core/text-hygiene.d.ts +160 -0
  123. package/dist/core/text-hygiene.js +2259 -0
  124. package/dist/core/toon.d.ts +29 -0
  125. package/dist/core/toon.js +425 -0
  126. package/dist/core/tracker.d.ts +223 -0
  127. package/dist/core/tracker.js +290 -0
  128. package/dist/core/transform.d.ts +589 -0
  129. package/dist/core/transform.js +3153 -0
  130. package/dist/core/types.d.ts +87 -0
  131. package/dist/core/types.js +8 -0
  132. package/dist/core/upstream-hosts.d.ts +127 -0
  133. package/dist/core/upstream-hosts.js +398 -0
  134. package/dist/core/vision-cost.d.ts +63 -0
  135. package/dist/core/vision-cost.js +137 -0
  136. package/dist/dashboard/fragments.d.ts +87 -0
  137. package/dist/dashboard/fragments.js +1515 -0
  138. package/dist/dashboard/types.d.ts +217 -0
  139. package/dist/dashboard/types.js +3 -0
  140. package/dist/dashboard/vendor.d.ts +3 -0
  141. package/dist/dashboard/vendor.js +6 -0
  142. package/dist/dashboard.d.ts +372 -0
  143. package/dist/dashboard.js +2731 -0
  144. package/dist/export-collect.d.ts +36 -0
  145. package/dist/export-collect.js +59 -0
  146. package/dist/file-tracker.d.ts +42 -0
  147. package/dist/file-tracker.js +234 -0
  148. package/dist/kosha-sync.d.ts +74 -0
  149. package/dist/kosha-sync.js +272 -0
  150. package/dist/launchd-socket.d.ts +22 -0
  151. package/dist/launchd-socket.js +210 -0
  152. package/dist/mcp/cli.d.ts +2 -0
  153. package/dist/mcp/cli.js +55 -0
  154. package/dist/mcp/server.d.ts +48 -0
  155. package/dist/mcp/server.js +987 -0
  156. package/dist/mmu-store.d.ts +31 -0
  157. package/dist/mmu-store.js +179 -0
  158. package/dist/node-fetch.d.ts +22 -0
  159. package/dist/node-fetch.js +489 -0
  160. package/dist/node.d.ts +9 -0
  161. package/dist/node.js +244396 -0
  162. package/dist/request-decoding.d.ts +30 -0
  163. package/dist/request-decoding.js +85 -0
  164. package/dist/sessions.d.ts +179 -0
  165. package/dist/sessions.js +837 -0
  166. package/dist/stats.d.ts +114 -0
  167. package/dist/stats.js +439 -0
  168. package/dist/turn-report.d.ts +65 -0
  169. package/dist/turn-report.js +724 -0
  170. package/dist/warp/app-launch.d.ts +26 -0
  171. package/dist/warp/app-launch.js +155 -0
  172. package/dist/warp/ca.d.ts +74 -0
  173. package/dist/warp/ca.js +416 -0
  174. package/dist/warp/connect.d.ts +42 -0
  175. package/dist/warp/connect.js +686 -0
  176. package/dist/warp/der.d.ts +57 -0
  177. package/dist/warp/der.js +151 -0
  178. package/dist/warp/index.d.ts +79 -0
  179. package/dist/warp/index.js +650 -0
  180. package/dist/warp/resolve.d.ts +12 -0
  181. package/dist/warp/resolve.js +49 -0
  182. package/dist/warp/route.d.ts +71 -0
  183. package/dist/warp/route.js +134 -0
  184. package/dist/worker.d.ts +71 -0
  185. package/dist/worker.js +174 -0
  186. package/docs/SECURITY_MODEL.md +84 -0
  187. package/package.json +122 -4
  188. package/plugins/fiche-companion/README.md +42 -0
  189. package/plugins/fiche-companion/assets/logo.svg +48 -0
  190. package/plugins/fiche-companion/hooks.json +11 -0
  191. package/plugins/fiche-companion/mcp_config.json +8 -0
  192. package/plugins/fiche-companion/plugin.json +18 -0
  193. package/plugins/fiche-companion/scripts/claude-statusline.mjs +35 -0
  194. package/plugins/fiche-companion/scripts/post-invocation.mjs +122 -0
  195. package/plugins/fiche-companion/scripts/resolve-turn-report.mjs +132 -0
  196. package/plugins/fiche-companion/skills/fiche/SKILL.md +61 -0
@@ -0,0 +1,1279 @@
1
+ /**
2
+ * GPT history-image compression.
3
+ *
4
+ * The static system+tool slab is small (~30k chars); the bulk of a GPT agent
5
+ * request is the conversation transcript, which OpenCode resends in full every
6
+ * turn — the Responses API is driven statelessly here (no `previous_response_id`),
7
+ * so turns 1..N-1 are re-sent as plain text on turn N. inkling collapses the OLD
8
+ * closed-tool-call prefix of that transcript into 1-N PNG images and keeps the
9
+ * recent tail as text.
10
+ *
11
+ * OpenAI prompt-caching is automatic and prefix-based: no `cache_control`
12
+ * breakpoints, no 1.25× write premium, cached reads at ~0.1×. The collapse
13
+ * boundary is snapped to a chunk grid so the history image stays byte-identical
14
+ * across turns and keeps hitting that automatic cache (the same flap-avoidance
15
+ * trick src/core/history.ts uses for Anthropic).
16
+ *
17
+ * This mirrors src/core/history.ts but operates on Responses `input` items and
18
+ * Chat `messages` rather than Anthropic Message blocks. The two formats differ
19
+ * enough (function_call/function_call_output vs tool_calls/tool role) that a
20
+ * shared block type isn't worth it; instead each format is lowered to a common
21
+ * HistoryTurn list and the planner/renderer are shared.
22
+ */
23
+ import { PAD_Y, READABLE_CHARS_PER_IMAGE, estimateImageCount, renderCellHeight, renderTextToPngs, measureContentCols, reflow, neutralizeSentinel, } from './render.js';
24
+ import { DEFAULT_GPT_PROFILE, GPT_MAX_HEIGHT_PX } from './gpt-model-profiles.js';
25
+ import { gptTokenCount as o200kCountTokens } from './gpt-tokens.js';
26
+ /** Portrait-strip width for GPT history images. Mirrors GPT_STRIP_COLS in
27
+ * openai.ts (kept local to avoid a circular import): ≤768px wide so OpenAI
28
+ * doesn't downscale dense text below its OCR-legibility floor. The 384-col
29
+ * Anthropic dense profile would be scaled to fit OpenAI's 768px box and become
30
+ * illegible — that profile is Anthropic-only. */
31
+ const GPT_HISTORY_COLS = 152;
32
+ export const GPT_HISTORY_DEFAULTS = {
33
+ keepTail: 6,
34
+ keepRecentPairs: 6,
35
+ responsesMode: 'pairs',
36
+ minCollapsePrefix: 10,
37
+ minCollapseTokens: 2000,
38
+ cols: GPT_HISTORY_COLS,
39
+ collapseChunk: 10,
40
+ freezeChunk: 10,
41
+ sectionTokens: 2000,
42
+ // GPT path: OpenAI's resize bounds (2048-bbox / 768 short side) permit the tall
43
+ // strip — do NOT re-link to render.ts MAX_HEIGHT_PX (Anthropic's 1568/1.15 MP clamp).
44
+ maxHeightPx: GPT_MAX_HEIGHT_PX,
45
+ style: DEFAULT_GPT_PROFILE.style,
46
+ maxImages: DEFAULT_GPT_PROFILE.history.maxImages,
47
+ reflow: true,
48
+ };
49
+ function safeJson(v) {
50
+ if (typeof v === 'string')
51
+ return v;
52
+ try {
53
+ return JSON.stringify(v) ?? '';
54
+ }
55
+ catch {
56
+ return String(v ?? '');
57
+ }
58
+ }
59
+ /** Last index i in [from, cutoffExclusive) where every opened tool-call id has a
60
+ * matching close. Returns from-1 (no collapse) if none. Stops at the first
61
+ * opaque barrier so unknown items are never swept into the image. */
62
+ function findClosedBoundary(turns, cutoffExclusive, from) {
63
+ const open = new Set();
64
+ let lastClosed = from - 1;
65
+ const limit = Math.min(cutoffExclusive, turns.length);
66
+ for (let i = from; i < limit; i++) {
67
+ const t = turns[i];
68
+ if (t.opaque)
69
+ break;
70
+ for (const id of t.openIds)
71
+ open.add(id);
72
+ for (const id of t.closeIds)
73
+ open.delete(id);
74
+ if (open.size === 0)
75
+ lastClosed = i;
76
+ }
77
+ return lastClosed;
78
+ }
79
+ /** True if [from, toExclusive) opens no tool call it doesn't also close (and hits
80
+ * no opaque barrier). Used to confirm the pinned user turn sits at a tool-closed
81
+ * boundary so force-sealing the section before it can't orphan a function call. */
82
+ function isClosedPrefix(turns, from, toExclusive) {
83
+ const open = new Set();
84
+ for (let i = from; i < toExclusive; i++) {
85
+ const t = turns[i];
86
+ if (t.opaque)
87
+ return false;
88
+ for (const id of t.openIds)
89
+ open.add(id);
90
+ for (const id of t.closeIds)
91
+ open.delete(id);
92
+ }
93
+ return open.size === 0;
94
+ }
95
+ /** Join turn texts over [from, toExclusive), skipping empties and `skip` (the
96
+ * pinned turn, which is emitted as text rather than imaged). */
97
+ function joinTurns(turns, from, toExclusive, skip) {
98
+ const parts = [];
99
+ for (let i = from; i < toExclusive; i++) {
100
+ if (i === skip)
101
+ continue;
102
+ const s = turns[i].text;
103
+ if (s && s.length > 0)
104
+ parts.push(s);
105
+ }
106
+ return parts.join('\n\n');
107
+ }
108
+ /**
109
+ * Plan + render a history collapse over pre-lowered turns. Pure w.r.t. the input
110
+ * (caller does the splice and builds the format-specific synthetic item).
111
+ */
112
+ export async function planGptCollapse(turns, protectedPrefix, isProfitable, opts = {}) {
113
+ const o = { ...GPT_HISTORY_DEFAULTS, ...opts };
114
+ const base = {
115
+ images: [],
116
+ imagesAfter: [],
117
+ imageSources: [],
118
+ imageSourcesAfter: [],
119
+ text: '',
120
+ start: 0,
121
+ endExclusive: 0,
122
+ collapsedTurns: 0,
123
+ collapsedChars: 0,
124
+ droppedChars: 0,
125
+ droppedCodepoints: new Map(),
126
+ };
127
+ const pp = Math.max(0, Math.min(protectedPrefix, turns.length));
128
+ const rawCutoff = turns.length - o.keepTail;
129
+ if (rawCutoff - pp < o.minCollapsePrefix) {
130
+ return { ...base, reason: 'prefix_too_short' };
131
+ }
132
+ // Snap the cutoff down to a collapseChunk grid (relative to pp) so the image
133
+ // stays byte-stable across turns. Floor at pp + minCollapsePrefix.
134
+ const cutoff = o.collapseChunk > 0
135
+ ? Math.min(rawCutoff, Math.max(pp + o.minCollapsePrefix, pp + Math.floor((rawCutoff - pp) / o.collapseChunk) * o.collapseChunk))
136
+ : rawCutoff;
137
+ const boundary = findClosedBoundary(turns, cutoff, pp);
138
+ if (boundary < pp) {
139
+ return { ...base, reason: 'no_closed_prefix' };
140
+ }
141
+ if (boundary + 1 - pp < o.minCollapsePrefix) {
142
+ return { ...base, reason: 'prefix_too_short' };
143
+ }
144
+ const rawEnd = boundary + 1;
145
+ // Pin the LIVE request — the most-recent user turn OVERALL — as legible TEXT so it
146
+ // is never OCR-only. Older user turns stay imaged (they must NOT look like the live
147
+ // request; that's the snap-to-first-prompt guard). The history BEFORE and AFTER the
148
+ // pin both stay imaged, so compression holds.
149
+ //
150
+ // CRITICAL: pin ONLY when the latest user turn falls INSIDE the collapse range. If
151
+ // it sits in the kept tail (ordinary interactive turn) it is already native text —
152
+ // pinning an OLDER in-range user turn would make the pin migrate across collapse-
153
+ // chunk boundaries and re-image frozen history (cache churn). Restricting the pin to
154
+ // the latest user turn means its position is fixed until the next prompt, so the
155
+ // before/after section grid stays byte-stable across a long run. This covers exactly
156
+ // the two shapes that need it: the autonomous single-prompt agent (pin == pp), and a
157
+ // long current turn whose tool loop overflowed the tail (pin in the middle).
158
+ let pinIdx = -1;
159
+ for (let i = turns.length - 1; i >= pp; i--) {
160
+ if (turns[i].userText !== undefined) {
161
+ pinIdx = i;
162
+ break;
163
+ }
164
+ }
165
+ if (pinIdx >= rawEnd)
166
+ pinIdx = -1; // latest user turn is in the live tail → already text
167
+ // Only pin at a tool-closed boundary: a user turn straddled by an open tool call
168
+ // (malformed input) would orphan the call when we seal the section before it.
169
+ if (pinIdx >= 0 && !isClosedPrefix(turns, pp, pinIdx))
170
+ pinIdx = -1;
171
+ // Imaged baseline EXCLUDES the pinned turn (it is emitted as text, not rendered).
172
+ const text = joinTurns(turns, pp, rawEnd, pinIdx);
173
+ // Floor gate in o200k TOKENS, not chars: imaging bills vision tokens and the
174
+ // text baseline is o200k tokens, so the break-even is a token comparison.
175
+ // NOTE: this counts the IMAGEABLE work only (pin excluded), so a small history
176
+ // whose non-pin content is below the floor is left fully as text. That is correct,
177
+ // not a regression: the pinned request stays legible either way, and imaging a
178
+ // sub-floor amount of work would cost more vision tokens than it saves. Only long
179
+ // sessions (where the bug lived) clear the floor and collapse.
180
+ if (!text || gptCountTokens(text) < o.minCollapseTokens) {
181
+ return { ...base, reason: 'below_min_tokens', collapsedChars: text?.length ?? 0 };
182
+ }
183
+ // Reflow for RENDERING ONLY: pack soft-wrapped lines and mark hard newlines
184
+ // with the ↵ sentinel so the history image is as dense as the static slab
185
+ // (newline-heavy transcripts otherwise burn a full row per short line and
186
+ // show no ↵). `text` itself stays original — it backs the o200k baseline and
187
+ // the chunk-snapped cache byte-stability, so it must not change shape here.
188
+ const safeText = neutralizeSentinel(text);
189
+ let renderText = o.reflow ? reflow(safeText) ?? safeText : text;
190
+ if (!isProfitable(renderText, o.cols)) {
191
+ return { ...base, reason: 'not_profitable', collapsedChars: text.length };
192
+ }
193
+ // APPEND-ONLY, TOKEN-LENGTH sectioning. Cut the closed prefix [pp..rawEnd) into
194
+ // sections of ~sectionTokens o200k tokens by walking turns from pp and sealing a
195
+ // section each time its cumulative token count crosses the target. A sealed
196
+ // section's bytes are a pure function of its turn range — independent of where
197
+ // the conversation currently ends — so old sections stay byte-identical (OpenAI
198
+ // prefix-cache hit) as turns are appended; only freshly-sealed sections are new.
199
+ // Leftover tail turns that don't fill a whole section are NOT collapsed: collapse
200
+ // ends at the last SEALED boundary so every emitted image is a frozen section.
201
+ // (freezeChunk 0 = legacy whole-blob: one section spanning the whole range.)
202
+ // The pinned turn force-seals the section before it and starts a fresh section
203
+ // after it, so no image straddles the live request (history stays imaged on both
204
+ // sides). (freezeChunk 0 = legacy whole-blob, still split around the pin.)
205
+ const sections = [];
206
+ if (o.freezeChunk <= 0) {
207
+ if (pinIdx > pp)
208
+ sections.push([pp, pinIdx]);
209
+ const afterStart = pinIdx >= pp ? pinIdx + 1 : pp;
210
+ if (afterStart < rawEnd)
211
+ sections.push([afterStart, rawEnd]);
212
+ }
213
+ else {
214
+ let secStart = pp;
215
+ let acc = 0;
216
+ // Track open tool-call ids so a section is only sealed at a TOOL-CLOSED point.
217
+ // The token threshold can otherwise land between a function_call and its
218
+ // function_call_output: the call gets imaged while the output stays a live
219
+ // item, and OpenAI rejects the orphan with "No tool call found for function
220
+ // call output" (400). The overall [pp, rawEnd) boundary being closed does NOT
221
+ // protect the intermediate section cut — collapseEnd is the live boundary, so
222
+ // it (and every seal) must itself be tool-closed. Anthropic doesn't hit this
223
+ // because it collapses the whole closed prefix with no live leftover.
224
+ const open = new Set();
225
+ for (let i = pp; i < rawEnd; i++) {
226
+ if (i === pinIdx) {
227
+ if (secStart < i)
228
+ sections.push([secStart, i]);
229
+ secStart = i + 1;
230
+ acc = 0;
231
+ continue;
232
+ }
233
+ acc += gptCountTokens(turns[i].text);
234
+ for (const id of turns[i].openIds)
235
+ open.add(id);
236
+ for (const id of turns[i].closeIds)
237
+ open.delete(id);
238
+ if (acc >= o.sectionTokens && open.size === 0) {
239
+ sections.push([secStart, i + 1]);
240
+ secStart = i + 1;
241
+ acc = 0;
242
+ }
243
+ }
244
+ // Trailing turns [secStart, rawEnd) didn't fill a section → leave as live text.
245
+ }
246
+ if (sections.length === 0) {
247
+ // Closed prefix cleared the floor but no single section sealed (only when
248
+ // sectionTokens > the whole prefix). Treat as below-min rather than emit a
249
+ // cache-unstable partial blob.
250
+ return { ...base, reason: 'below_min_tokens', collapsedChars: text.length };
251
+ }
252
+ const maxImages = Math.max(0, Math.floor(o.maxImages));
253
+ const rendered = [];
254
+ let imgCount = 0;
255
+ let collapseEnd = pp;
256
+ for (const [s, e] of sections) {
257
+ const sectionText = joinTurns(turns, s, e, -1);
258
+ if (!sectionText || sectionText.length === 0)
259
+ continue;
260
+ const safeSection = neutralizeSentinel(sectionText);
261
+ let sectionRender = o.reflow ? reflow(safeSection) ?? safeSection : sectionText;
262
+ // Readable portrait strips (≤768px wide) — legible to OpenAI vision, same as
263
+ // the static slab. renderTextToPngs caps each PNG at MAX_HEIGHT_PX so a tall
264
+ // section pages into N images, all still well under the 10,000-patch budget.
265
+ const sectionImgs = await renderTextToPngs(sectionRender, o.cols, o.style ?? DEFAULT_GPT_PROFILE.style, o.maxHeightPx);
266
+ if (imgCount + sectionImgs.length > maxImages) {
267
+ // TRUE cap: keep the sections already selected, leave this and every later
268
+ // section (and the pin, if not yet reached) as normal text in the remainder.
269
+ break;
270
+ }
271
+ rendered.push({ s, e, imgs: sectionImgs });
272
+ imgCount += sectionImgs.length;
273
+ collapseEnd = e;
274
+ }
275
+ // The pin is "consumed" (emitted as text inside the synthetic) only once we have
276
+ // collapsed PAST it. If the image cap stopped us before the pin, it survives as a
277
+ // native user message in the untouched remainder — still legible, no work lost.
278
+ const pinConsumed = pinIdx >= pp && collapseEnd > pinIdx;
279
+ const imagesBefore = [];
280
+ const imagesAfter = [];
281
+ const imageSources = [];
282
+ const imageSourcesAfter = [];
283
+ for (const r of rendered) {
284
+ // Source preview uses the original serialized section (not reflow/IDS) so it
285
+ // remains byte-exact. Multipage sections repeat the same source for each PNG.
286
+ const source = joinTurns(turns, r.s, r.e, -1);
287
+ if (pinConsumed && r.s >= pinIdx + 1) {
288
+ imagesAfter.push(...r.imgs);
289
+ imageSourcesAfter.push(...r.imgs.map(() => source));
290
+ }
291
+ else {
292
+ imagesBefore.push(...r.imgs);
293
+ imageSources.push(...r.imgs.map(() => source));
294
+ }
295
+ }
296
+ if (imagesBefore.length === 0 && imagesAfter.length === 0) {
297
+ // First section alone exceeded the cap (or cap <= 0). Fall back to text.
298
+ return { ...base, reason: 'too_many_images', collapsedChars: text.length };
299
+ }
300
+ const pinText = pinConsumed ? turns[pinIdx].userText : undefined;
301
+ // The collapsed transcript / o200k baseline reflects ONLY what we imaged — the
302
+ // pin, when consumed, is text and is excluded from the imaged baseline.
303
+ const collapsedText = joinTurns(turns, pp, collapseEnd, pinConsumed ? pinIdx : -1);
304
+ const droppedCodepoints = new Map();
305
+ let droppedChars = 0;
306
+ for (const img of [...imagesBefore, ...imagesAfter]) {
307
+ droppedChars += img.droppedChars;
308
+ for (const [cp, n] of img.droppedCodepoints) {
309
+ droppedCodepoints.set(cp, (droppedCodepoints.get(cp) ?? 0) + n);
310
+ }
311
+ }
312
+ return {
313
+ images: imagesBefore,
314
+ imagesAfter,
315
+ imageSources,
316
+ imageSourcesAfter,
317
+ pinText,
318
+ text: collapsedText,
319
+ start: pp,
320
+ endExclusive: collapseEnd,
321
+ collapsedTurns: collapseEnd - pp - (pinConsumed ? 1 : 0),
322
+ collapsedChars: collapsedText.length,
323
+ droppedChars,
324
+ droppedCodepoints,
325
+ };
326
+ }
327
+ /** o200k_base token count — gpt-5 / gpt-4o / o-series share this encoding.
328
+ * Used for the history collapse floor (token-, not char-based). */
329
+ function gptCountTokens(text) {
330
+ if (!text)
331
+ return 0;
332
+ try {
333
+ return o200kCountTokens(text);
334
+ }
335
+ catch {
336
+ return 0;
337
+ }
338
+ }
339
+ // ---- Responses completed-pair planning -------------------------------------
340
+ function responseCallText(item) {
341
+ const name = typeof item.name === 'string' ? item.name : 'tool';
342
+ const qualifiedName = typeof item.namespace === 'string' && item.namespace && !name.startsWith(`${item.namespace}.`)
343
+ ? `${item.namespace}.${name}` : name;
344
+ const payload = item.type === 'custom_tool_call' ? item.input : item.arguments;
345
+ const args = typeof payload === 'string' ? payload : safeJson(payload);
346
+ return `[tool_use ${qualifiedName}]\n${args}`;
347
+ }
348
+ function extractTextOutput(output) {
349
+ if (typeof output === 'string')
350
+ return output;
351
+ if (Array.isArray(output)) {
352
+ const texts = [];
353
+ for (const part of output) {
354
+ if (part && typeof part === 'object' && typeof part.text === 'string') {
355
+ texts.push(part.text);
356
+ }
357
+ }
358
+ return texts.join('\n\n');
359
+ }
360
+ return safeJson(output);
361
+ }
362
+ function responseOutputText(item) {
363
+ const output = extractTextOutput(item.output);
364
+ return `[tool_result]\n${output}`;
365
+ }
366
+ function responseItemType(item) {
367
+ const o = item;
368
+ return o && typeof o.type === 'string' ? o.type : '';
369
+ }
370
+ /** Shared with Responses accounting so custom tools do not disappear into Other. */
371
+ export function isResponsesToolCall(item) {
372
+ const type = responseItemType(item);
373
+ return type === 'function_call' || type === 'custom_tool_call';
374
+ }
375
+ export function isResponsesToolOutput(item) {
376
+ const type = responseItemType(item);
377
+ return type === 'function_call_output' || type === 'custom_tool_call_output';
378
+ }
379
+ function isRenderableTextOutput(output) {
380
+ if (typeof output === 'string')
381
+ return true;
382
+ if (!Array.isArray(output))
383
+ return false;
384
+ return output.every((part) => part !== null &&
385
+ typeof part === 'object' &&
386
+ (part.type === 'input_text' ||
387
+ part.type === 'output_text' ||
388
+ part.type === 'text') &&
389
+ typeof part.text === 'string');
390
+ }
391
+ function isRenderableResponsesPair(call, output) {
392
+ // A matching id alone is insufficient: cross-kind, partial and unknown state
393
+ // must remain native, even if an output happens to be present already.
394
+ if (output.type !== `${call.type}_output`)
395
+ return false;
396
+ if (call.status !== undefined && call.status !== 'completed')
397
+ return false;
398
+ if (output.status !== undefined && output.status !== 'completed')
399
+ return false;
400
+ // Tool outputs can contain input_image / input_file parts for BOTH function_call
401
+ // and custom_tool_call; never JSON-stringify non-text parts into PNGs.
402
+ if (!isRenderableTextOutput(output.output))
403
+ return false;
404
+ if (call.type !== 'custom_tool_call')
405
+ return true;
406
+ if (typeof call.name !== 'string' || !call.name || typeof call.input !== 'string')
407
+ return false;
408
+ if (call.namespace !== undefined && typeof call.namespace !== 'string')
409
+ return false;
410
+ return true;
411
+ }
412
+ function responseCallId(item) {
413
+ const o = item;
414
+ return o && typeof o.call_id === 'string' ? o.call_id : '';
415
+ }
416
+ /** Return a lossless textual Responses message, or null when the item carries
417
+ * non-text content that must stay native (images, unknown parts, empty state). */
418
+ function responseMessageText(item) {
419
+ const o = item;
420
+ if (!o || (o.role !== 'user' && o.role !== 'assistant'))
421
+ return null;
422
+ const itemType = typeof o.type === 'string' ? o.type : '';
423
+ if (itemType && itemType !== 'message')
424
+ return null;
425
+ let body = '';
426
+ if (typeof o.content === 'string') {
427
+ body = o.content;
428
+ }
429
+ else if (Array.isArray(o.content)) {
430
+ const parts = [];
431
+ for (const part of o.content) {
432
+ const p = part;
433
+ const type = p && typeof p.type === 'string' ? p.type : '';
434
+ if (!p)
435
+ return null;
436
+ // A refusal is plain model-authored prose that happens to ride in its own
437
+ // part type. Rejecting it made the whole message non-imageable, and since
438
+ // a non-imageable message is a hard barrier, ONE refusal split the run and
439
+ // cost a page break. Same for any future part that carries a string
440
+ // `text`: the content is losslessly renderable, so gate on the payload
441
+ // being text rather than on an allow-list of part names.
442
+ if (type === 'refusal' && typeof p.refusal === 'string') {
443
+ parts.push(p.refusal);
444
+ continue;
445
+ }
446
+ if (typeof p.text !== 'string')
447
+ return null;
448
+ parts.push(p.text);
449
+ }
450
+ body = parts.join('\n\n');
451
+ }
452
+ else {
453
+ return null;
454
+ }
455
+ if (!body.trim())
456
+ return null;
457
+ return { role: o.role, text: body };
458
+ }
459
+ /** True for a `message` item that carries no renderable text at all: empty
460
+ * content array, or parts whose text is present but blank. Such an item is
461
+ * inert — imaging it would produce nothing and skipping it changes no
462
+ * ordering — so it must not end a collapse run. Anything with non-text parts
463
+ * (images, unknown shapes) is NOT contentless and stays a barrier. */
464
+ function isContentlessMessage(item) {
465
+ const o = item;
466
+ if (!o || (o.role !== 'user' && o.role !== 'assistant'))
467
+ return false;
468
+ const itemType = typeof o.type === 'string' ? o.type : '';
469
+ if (itemType && itemType !== 'message')
470
+ return false;
471
+ if (typeof o.content === 'string')
472
+ return !o.content.trim();
473
+ if (!Array.isArray(o.content))
474
+ return false;
475
+ for (const part of o.content) {
476
+ const p = part;
477
+ const type = p && typeof p.type === 'string' ? p.type : '';
478
+ if (!p)
479
+ return false;
480
+ if (type === 'refusal' && typeof p.refusal === 'string') {
481
+ if (p.refusal.trim())
482
+ return false;
483
+ continue;
484
+ }
485
+ // A non-text part means real payload we cannot render — not contentless.
486
+ if (typeof p.text !== 'string')
487
+ return false;
488
+ if (p.text.trim())
489
+ return false;
490
+ }
491
+ return true;
492
+ }
493
+ function responseMessageTranscript(item, index) {
494
+ const msg = responseMessageText(item);
495
+ return msg ? `<${msg.role} t="${index}">\n${msg.text}\n</${msg.role}>` : null;
496
+ }
497
+ function responseReferencedIds(items) {
498
+ const refs = new Set();
499
+ for (const item of items) {
500
+ const o = item;
501
+ if (!o || o.type !== 'item_reference')
502
+ continue;
503
+ for (const key of ['id', 'item_id', 'ref_id']) {
504
+ if (typeof o[key] === 'string' && o[key])
505
+ refs.add(o[key]);
506
+ }
507
+ }
508
+ return refs;
509
+ }
510
+ /** Classify Responses tool state without interpreting recency from raw item count.
511
+ * Accept both adjacent pairs and protocol-atomic parallel rounds:
512
+ * `call A, call B, output A, output B`. Unknown/intervening native items remain
513
+ * hard barriers, and duplicate/reversed/orphan state is never selected. */
514
+ function classifyResponsesPairs(items, keepRecentPairs) {
515
+ const calls = new Map();
516
+ const outputs = new Map();
517
+ let missingIdItems = 0;
518
+ for (let i = 0; i < items.length; i++) {
519
+ const call = isResponsesToolCall(items[i]);
520
+ if (!call && !isResponsesToolOutput(items[i]))
521
+ continue;
522
+ const id = responseCallId(items[i]);
523
+ if (!id) {
524
+ missingIdItems++;
525
+ continue;
526
+ }
527
+ const map = call ? calls : outputs;
528
+ const at = map.get(id) ?? [];
529
+ at.push(i);
530
+ map.set(id, at);
531
+ }
532
+ const pairByCallIndex = new Map();
533
+ let openCalls = 0;
534
+ let orphanOutputs = 0;
535
+ let malformedItems = missingIdItems;
536
+ const ids = new Set([...calls.keys(), ...outputs.keys()]);
537
+ for (const id of ids) {
538
+ const cs = calls.get(id) ?? [];
539
+ const os = outputs.get(id) ?? [];
540
+ if (cs.length === 1 && os.length === 1 && cs[0] < os[0]) {
541
+ const callIndex = cs[0];
542
+ const outputIndex = os[0];
543
+ const call = items[callIndex];
544
+ const output = items[outputIndex];
545
+ if (!isRenderableResponsesPair(call, output)) {
546
+ malformedItems += 2;
547
+ continue;
548
+ }
549
+ pairByCallIndex.set(callIndex, {
550
+ callIndex,
551
+ outputIndex,
552
+ text: `${responseCallText(call)}\n${responseOutputText(output)}`,
553
+ // Match measureResponsesComposition exactly so the share is comparable
554
+ // to its functionCalls/functionOutputs buckets.
555
+ callTokens: gptCountTokens(JSON.stringify(call)),
556
+ outputTokens: gptCountTokens(extractTextOutput(output.output)),
557
+ });
558
+ }
559
+ else if (cs.length > 0 && os.length === 0)
560
+ openCalls += cs.length;
561
+ else if (os.length > 0 && cs.length === 0)
562
+ orphanOutputs += os.length;
563
+ else
564
+ malformedItems += cs.length + os.length;
565
+ }
566
+ // Discover contiguous calls* + outputs* rounds. A candidate unique pair that
567
+ // does not fit one of these rounds is non-adjacent protocol state and remains
568
+ // native. This is the shape OpenCode uses for parallel tool calls.
569
+ const completed = [];
570
+ const acceptedCallIndices = new Set();
571
+ for (let i = 0; i < items.length;) {
572
+ if (!isResponsesToolCall(items[i]) || !pairByCallIndex.has(i)) {
573
+ i++;
574
+ continue;
575
+ }
576
+ const calls = [];
577
+ let j = i;
578
+ while (isResponsesToolCall(items[j]) && pairByCallIndex.has(j)) {
579
+ calls.push(pairByCallIndex.get(j));
580
+ j++;
581
+ }
582
+ const roundOutputIndices = new Set(calls.map((pair) => pair.outputIndex));
583
+ const outputs = [];
584
+ // Do not absorb an output belonging to orphan/other state into this round.
585
+ while (isResponsesToolOutput(items[j])
586
+ && roundOutputIndices.has(j)) {
587
+ outputs.push(j);
588
+ j++;
589
+ }
590
+ const outputSet = new Set(outputs);
591
+ const valid = calls.length > 0
592
+ && outputs.length === calls.length
593
+ && calls.every((pair) => outputSet.has(pair.outputIndex));
594
+ if (!valid) {
595
+ i++;
596
+ continue;
597
+ }
598
+ const byOutput = [...calls].sort((a, b) => a.outputIndex - b.outputIndex);
599
+ const indices = [
600
+ ...calls.map((pair) => pair.callIndex),
601
+ ...byOutput.map((pair) => pair.outputIndex),
602
+ ];
603
+ completed.push({
604
+ pairs: calls,
605
+ indices,
606
+ startIndex: i,
607
+ endIndex: j - 1,
608
+ text: byOutput.map((pair) => pair.text).join('\n\n'),
609
+ callTokens: calls.reduce((sum, pair) => sum + pair.callTokens, 0),
610
+ outputTokens: calls.reduce((sum, pair) => sum + pair.outputTokens, 0),
611
+ });
612
+ for (const pair of calls)
613
+ acceptedCallIndices.add(pair.callIndex);
614
+ i = j;
615
+ }
616
+ for (const pair of pairByCallIndex.values()) {
617
+ if (!acceptedCallIndices.has(pair.callIndex))
618
+ malformedItems += 2;
619
+ }
620
+ const keep = Math.max(0, Math.floor(keepRecentPairs));
621
+ let recentStart = completed.length;
622
+ let recentPairs = 0;
623
+ while (recentStart > 0 && recentPairs < keep) {
624
+ recentStart--;
625
+ recentPairs += completed[recentStart].pairs.length;
626
+ }
627
+ const old = completed.slice(0, recentStart);
628
+ const completedPairs = completed.reduce((n, round) => n + round.pairs.length, 0);
629
+ const oldPairs = old.reduce((n, round) => n + round.pairs.length, 0);
630
+ const imageableFunctionCallTokens = old.reduce((n, round) => n + round.callTokens, 0);
631
+ const imageableFunctionOutputTokens = old.reduce((n, round) => n + round.outputTokens, 0);
632
+ return {
633
+ old,
634
+ completed,
635
+ state: {
636
+ completedPairs,
637
+ recentCompletedPairs: completedPairs - oldPairs,
638
+ oldCompletedPairs: oldPairs,
639
+ openCalls,
640
+ orphanOutputs,
641
+ malformedItems,
642
+ imageableFunctionCallTokens,
643
+ imageableFunctionOutputTokens,
644
+ collapsedPairs: 0,
645
+ collapsedFunctionCallTokens: 0,
646
+ collapsedFunctionOutputTokens: 0,
647
+ },
648
+ };
649
+ }
650
+ function emptyResponsesPairPlan(state) {
651
+ return {
652
+ images: [], imagesAfter: [], imageSources: [], imageSourcesAfter: [],
653
+ text: '', start: 0, endExclusive: 0, collapsedTurns: 0,
654
+ collapsedChars: 0, droppedChars: 0, droppedCodepoints: new Map(),
655
+ segments: [], selectedIndices: [], pairState: state,
656
+ };
657
+ }
658
+ function isUserMessage(item) {
659
+ return responseMessageText(item)?.role === 'user';
660
+ }
661
+ function freezeResponsesRuns(runs, items, opts, tokensFor) {
662
+ if (opts.freezeChunk <= 0)
663
+ return runs;
664
+ const sections = [];
665
+ const target = Math.max(1, opts.sectionTokens);
666
+ for (const run of runs) {
667
+ let pending = [];
668
+ let tokens = 0;
669
+ const seal = () => {
670
+ if (pending.length > 0)
671
+ sections.push(pending);
672
+ pending = [];
673
+ tokens = 0;
674
+ };
675
+ for (const unit of run) {
676
+ pending.push(unit);
677
+ tokens += tokensFor(unit);
678
+ if (tokens >= target)
679
+ seal();
680
+ }
681
+ const last = run[run.length - 1];
682
+ if (!last)
683
+ continue;
684
+ let nextIndex = last.indices[last.indices.length - 1] + 1;
685
+ while (nextIndex < items.length && isContentlessMessage(items[nextIndex]))
686
+ nextIndex++;
687
+ const next = items[nextIndex];
688
+ // A user message is a permanent barrier (see the mixed planner), so a run
689
+ // that ends at one can never grow and its tail is safe to seal now.
690
+ if (next && !isResponsesToolCall(next) && !isResponsesToolOutput(next)
691
+ && (responseMessageText(next) === null || isUserMessage(next)))
692
+ seal();
693
+ }
694
+ return sections;
695
+ }
696
+ /** Profile-gated broad Responses planner. Safe textual messages and complete old
697
+ * call/output pairs may share one image group only when they are contiguous.
698
+ * Every other item is a hard barrier, preserving native protocol order/state. */
699
+ async function planResponsesMixedCollapse(items, old, completed, state, isProfitable, o) {
700
+ const base = emptyResponsesPairPlan(state);
701
+ const oldStarts = new Set(old.map((round) => round.startIndex));
702
+ const oldByCall = new Map((o.freezeChunk > 0 ? completed : old).map((round) => [round.startIndex, round]));
703
+ const messageIndices = [];
704
+ const referencedIds = responseReferencedIds(items);
705
+ let latestUserIndex = -1;
706
+ for (let i = 0; i < items.length; i++) {
707
+ const msg = responseMessageText(items[i]);
708
+ if (!msg)
709
+ continue;
710
+ messageIndices.push(i);
711
+ if (msg.role === 'user')
712
+ latestUserIndex = i;
713
+ }
714
+ // slice(-0) returns the WHOLE array, so guard keepTail===0 explicitly —
715
+ // otherwise "protect 0 tail messages" protects every message and blocks
716
+ // all collapse. latestUserIndex is added separately below.
717
+ const tail = Math.max(0, Math.floor(o.keepTail));
718
+ const protectedMessages = new Set(tail > 0 ? messageIndices.slice(-tail) : []);
719
+ if (latestUserIndex >= 0)
720
+ protectedMessages.add(latestUserIndex);
721
+ const runs = [];
722
+ let current = [];
723
+ // Every flush ends a run, and every run renders at least one image. Naming
724
+ // the item type that caused it is the only way to tell an unavoidable
725
+ // barrier (protected tail, item_reference) from an incidental one that is
726
+ // silently costing a page break per occurrence.
727
+ const barrierTypes = new Map();
728
+ const noteBarrier = (index) => {
729
+ if (current.length === 0)
730
+ return; // nothing to split — not a real break
731
+ const t = responseItemType(items[index]) || 'untyped';
732
+ barrierTypes.set(t, (barrierTypes.get(t) ?? 0) + 1);
733
+ };
734
+ const flush = () => {
735
+ if (current.length > 0)
736
+ runs.push(current);
737
+ current = [];
738
+ };
739
+ for (let i = 0; i < items.length; i++) {
740
+ const round = oldByCall.get(i);
741
+ const roundReferenced = !!round && round.indices
742
+ .map((index) => items[index])
743
+ .map((item) => item?.id)
744
+ .some((id) => typeof id === 'string' && referencedIds.has(id));
745
+ if (round && (o.freezeChunk > 0 || !roundReferenced)) {
746
+ current.push({
747
+ eligible: oldStarts.has(round.startIndex) && !roundReferenced,
748
+ indices: round.indices,
749
+ text: round.text,
750
+ baselineTokens: round.callTokens + round.outputTokens,
751
+ });
752
+ i = round.endIndex;
753
+ continue;
754
+ }
755
+ // User messages stay native and split runs. The latest one is protected,
756
+ // and every user message is the latest for a while; one that sat inside a
757
+ // section kept the rounds after it native until the next turn unprotected
758
+ // it, and then a new segment landed mid-prefix and re-billed everything
759
+ // behind it uncached (replayed Codex traffic: ~295k tokens on one turn).
760
+ // As a barrier it never changes state, so earlier segments never move.
761
+ if (responseMessageText(items[i])?.role === 'user') {
762
+ noteBarrier(i);
763
+ flush();
764
+ continue;
765
+ }
766
+ const item = items[i];
767
+ const referenced = !!item && typeof item.id === 'string' && referencedIds.has(item.id);
768
+ const eligible = !protectedMessages.has(i) && !referenced;
769
+ const text = o.freezeChunk <= 0 && !eligible ? null : responseMessageTranscript(items[i], i);
770
+ if (text) {
771
+ current.push({
772
+ eligible,
773
+ indices: [i],
774
+ text,
775
+ baselineTokens: gptCountTokens(responseMessageText(items[i]).text),
776
+ });
777
+ continue;
778
+ }
779
+ // A contentless message (empty content array, whitespace-only text) carries
780
+ // nothing to image and nothing to reorder, but treating it as a barrier
781
+ // still split the run and cost a page break. Leave it native in place and
782
+ // keep the run open: `selectedIndices` never includes it, so the splice in
783
+ // openai.ts re-emits it at its original position and protocol order is
784
+ // unchanged. Only applies when the item is genuinely a message with no
785
+ // renderable payload — anything unrecognized remains a hard barrier.
786
+ if (!protectedMessages.has(i) && !referenced && isContentlessMessage(items[i])) {
787
+ continue;
788
+ }
789
+ noteBarrier(i);
790
+ flush();
791
+ }
792
+ flush();
793
+ const eligible = runs.flat().filter((unit) => unit.eligible);
794
+ const allText = eligible.map((unit) => unit.text).join('\n\n');
795
+ const allBaselineTokens = eligible.reduce((sum, unit) => sum + unit.baselineTokens, 0);
796
+ if (eligible.length === 0)
797
+ return { ...base, reason: 'no_closed_prefix' };
798
+ if (allBaselineTokens < o.minCollapseTokens) {
799
+ return { ...base, reason: 'below_min_tokens', collapsedChars: allText.length };
800
+ }
801
+ const maxImages = Math.max(0, Math.floor(o.maxImages));
802
+ if (maxImages === 0) {
803
+ return { ...base, reason: 'too_many_images', collapsedChars: allText.length };
804
+ }
805
+ const style = o.style ?? DEFAULT_GPT_PROFILE.style;
806
+ const maxLines = Math.max(1, Math.floor((o.maxHeightPx - 2 * PAD_Y) / renderCellHeight(style)));
807
+ const prepareUnits = (units) => {
808
+ const source = units.map((unit) => unit.text).join('\n\n');
809
+ const safe = neutralizeSentinel(source);
810
+ const renderedText = o.reflow ? reflow(safe) ?? safe : safe;
811
+ const cols = o.reflow ? o.cols : measureContentCols(renderedText, o.cols, style.markerScale, style.font);
812
+ const maxCharsPerImg = Math.min(READABLE_CHARS_PER_IMAGE, Math.max(1, cols) * maxLines);
813
+ const estImages = estimateImageCount(renderedText, cols, maxCharsPerImg, maxLines);
814
+ return { source, renderedText, cols, estImages };
815
+ };
816
+ const renderPreparedUnits = async (prep) => {
817
+ const images = await renderTextToPngs(prep.renderedText, prep.cols, style, o.maxHeightPx);
818
+ return { source: prep.source, renderedText: prep.renderedText, images, cols: prep.cols };
819
+ };
820
+ const segments = [];
821
+ let remainingImages = maxImages;
822
+ let hitImageCap = false;
823
+ const frozenRuns = freezeResponsesRuns(runs, items, o, (unit) => unit.baselineTokens)
824
+ .filter((run) => run.every((unit) => unit.eligible));
825
+ for (const run of frozenRuns) {
826
+ if (remainingImages === 0) {
827
+ hitImageCap = true;
828
+ break;
829
+ }
830
+ let low = 0;
831
+ let best;
832
+ const fullPrep = prepareUnits(run);
833
+ if (fullPrep.estImages <= remainingImages) {
834
+ const full = await renderPreparedUnits(fullPrep);
835
+ if (full.images.length > 0 && full.images.length <= remainingImages) {
836
+ low = run.length;
837
+ best = full;
838
+ }
839
+ else if (run.length > 1) {
840
+ let high = run.length;
841
+ while (low + 1 < high) {
842
+ const count = Math.floor((low + high) / 2);
843
+ const prep = prepareUnits(run.slice(0, count));
844
+ if (prep.estImages > remainingImages) {
845
+ high = count;
846
+ continue;
847
+ }
848
+ const rendered = await renderPreparedUnits(prep);
849
+ if (rendered.images.length > 0 && rendered.images.length <= remainingImages) {
850
+ low = count;
851
+ best = rendered;
852
+ }
853
+ else {
854
+ high = count;
855
+ }
856
+ }
857
+ }
858
+ }
859
+ else if (run.length > 1) {
860
+ // Pre-shrink run length by estimateImageCount BEFORE calling renderTextToPngs.
861
+ let estLow = 0;
862
+ let estHigh = run.length;
863
+ while (estLow + 1 < estHigh) {
864
+ const mid = Math.floor((estLow + estHigh) / 2);
865
+ if (prepareUnits(run.slice(0, mid)).estImages <= remainingImages) {
866
+ estLow = mid;
867
+ }
868
+ else {
869
+ estHigh = mid;
870
+ }
871
+ }
872
+ if (estLow > 0) {
873
+ const cand = await renderPreparedUnits(prepareUnits(run.slice(0, estLow)));
874
+ if (cand.images.length > 0 && cand.images.length <= remainingImages) {
875
+ low = estLow;
876
+ best = cand;
877
+ }
878
+ else if (estLow > 1) {
879
+ let high = estLow;
880
+ while (low + 1 < high) {
881
+ const count = Math.floor((low + high) / 2);
882
+ const prep = prepareUnits(run.slice(0, count));
883
+ if (prep.estImages > remainingImages) {
884
+ high = count;
885
+ continue;
886
+ }
887
+ const rendered = await renderPreparedUnits(prep);
888
+ if (rendered.images.length > 0 && rendered.images.length <= remainingImages) {
889
+ low = count;
890
+ best = rendered;
891
+ }
892
+ else {
893
+ high = count;
894
+ }
895
+ }
896
+ }
897
+ }
898
+ }
899
+ if (!best || low === 0) {
900
+ hitImageCap = true;
901
+ break;
902
+ }
903
+ const selected = run.slice(0, low);
904
+ const selectedBaselineTokens = selected.reduce((sum, unit) => sum + unit.baselineTokens, 0);
905
+ if (!isProfitable(best.renderedText, best.cols, selectedBaselineTokens, best.source))
906
+ continue;
907
+ const selectedIndices = selected.flatMap((unit) => unit.indices).sort((a, b) => a - b);
908
+ segments.push({
909
+ insertAt: selectedIndices[0],
910
+ selectedIndices,
911
+ images: best.images,
912
+ imageSources: best.images.map(() => best.source),
913
+ text: best.source,
914
+ baselineTokens: selectedBaselineTokens,
915
+ });
916
+ remainingImages -= best.images.length;
917
+ if (low < run.length) {
918
+ hitImageCap = true;
919
+ break;
920
+ }
921
+ }
922
+ if (segments.length === 0) {
923
+ return {
924
+ ...base,
925
+ reason: hitImageCap ? 'too_many_images' : 'not_profitable',
926
+ collapsedChars: allText.length,
927
+ barrierTypes,
928
+ };
929
+ }
930
+ const selectedIndices = segments.flatMap((segment) => segment.selectedIndices).sort((a, b) => a - b);
931
+ const selectedIds = new Set(selectedIndices);
932
+ const selectedRounds = old.filter((round) => round.indices.every((index) => selectedIds.has(index)));
933
+ state.collapsedPairs = selectedRounds.reduce((n, round) => n + round.pairs.length, 0);
934
+ state.collapsedFunctionCallTokens = selectedRounds.reduce((n, round) => n + round.callTokens, 0);
935
+ state.collapsedFunctionOutputTokens = selectedRounds.reduce((n, round) => n + round.outputTokens, 0);
936
+ const images = segments.flatMap((segment) => segment.images);
937
+ const imageSources = segments.flatMap((segment) => segment.imageSources);
938
+ const text = segments.map((segment) => segment.text).join('\n\n');
939
+ const baselineTokens = segments.reduce((sum, segment) => sum + (segment.baselineTokens ?? 0), 0);
940
+ const droppedCodepoints = new Map();
941
+ let droppedChars = 0;
942
+ for (const image of images) {
943
+ droppedChars += image.droppedChars;
944
+ for (const [codepoint, count] of image.droppedCodepoints) {
945
+ droppedCodepoints.set(codepoint, (droppedCodepoints.get(codepoint) ?? 0) + count);
946
+ }
947
+ }
948
+ return {
949
+ ...base,
950
+ barrierTypes,
951
+ segments,
952
+ images,
953
+ imageSources,
954
+ text,
955
+ baselineTokens,
956
+ start: selectedIndices[0] ?? 0,
957
+ endExclusive: (selectedIndices.at(-1) ?? -1) + 1,
958
+ collapsedTurns: selectedIndices.length,
959
+ collapsedChars: text.length,
960
+ droppedChars,
961
+ droppedCodepoints,
962
+ selectedIndices,
963
+ pairState: state,
964
+ };
965
+ }
966
+ /** Render only old, unambiguously completed Responses call/output rounds.
967
+ * Native messages, reasoning, recent rounds, open calls, and malformed state stay
968
+ * in place. Consecutive rounds may share pages, but no segment crosses native state. */
969
+ export async function planResponsesPairCollapse(items, isProfitable, opts = {}) {
970
+ const o = { ...GPT_HISTORY_DEFAULTS, ...opts, freezeChunk: opts.freezeChunk ?? 0 };
971
+ const { old, completed, state } = classifyResponsesPairs(items, o.keepRecentPairs);
972
+ if (o.responsesMode === 'mixed') {
973
+ return planResponsesMixedCollapse(items, old, completed, state, isProfitable, o);
974
+ }
975
+ const base = emptyResponsesPairPlan(state);
976
+ if (old.length === 0)
977
+ return { ...base, reason: 'no_closed_prefix' };
978
+ const allText = old.map((pair) => pair.text).join('\n\n');
979
+ if (!allText || gptCountTokens(allText) < o.minCollapseTokens) {
980
+ return { ...base, reason: 'below_min_tokens', collapsedChars: allText.length };
981
+ }
982
+ const maxImages = Math.max(0, Math.floor(o.maxImages));
983
+ if (maxImages === 0) {
984
+ return { ...base, reason: 'too_many_images', collapsedChars: allText.length };
985
+ }
986
+ const runs = [];
987
+ const referencedIds = responseReferencedIds(items);
988
+ const oldStarts = new Set(old.filter((round) => !round.indices.some((index) => {
989
+ const id = items[index]?.id;
990
+ return typeof id === 'string' && referencedIds.has(id);
991
+ })).map((round) => round.startIndex));
992
+ for (const round of o.freezeChunk > 0 ? completed : old) {
993
+ // In unfrozen mode a referenced round is a native barrier, not a reason
994
+ // to discard every otherwise-safe neighbor in the same contiguous run.
995
+ if (o.freezeChunk <= 0 && !oldStarts.has(round.startIndex))
996
+ continue;
997
+ const run = runs.at(-1);
998
+ if (run && round.startIndex === run.at(-1).endIndex + 1)
999
+ run.push(round);
1000
+ else
1001
+ runs.push([round]);
1002
+ }
1003
+ const style = o.style ?? DEFAULT_GPT_PROFILE.style;
1004
+ const maxLines = Math.max(1, Math.floor((o.maxHeightPx - 2 * PAD_Y) / renderCellHeight(style)));
1005
+ const preparePairs = (rounds) => {
1006
+ const source = rounds.map((round) => round.text).join('\n\n');
1007
+ const safe = neutralizeSentinel(source);
1008
+ const renderedText = o.reflow ? reflow(safe) ?? safe : safe;
1009
+ const cols = o.reflow ? o.cols : measureContentCols(renderedText, o.cols, style.markerScale, style.font);
1010
+ const maxCharsPerImg = Math.min(READABLE_CHARS_PER_IMAGE, Math.max(1, cols) * maxLines);
1011
+ const estImages = estimateImageCount(renderedText, cols, maxCharsPerImg, maxLines);
1012
+ return { source, renderedText, cols, estImages };
1013
+ };
1014
+ const renderPreparedPairs = async (prep) => {
1015
+ const images = await renderTextToPngs(prep.renderedText, prep.cols, style, o.maxHeightPx);
1016
+ return { source: prep.source, renderedText: prep.renderedText, images, cols: prep.cols };
1017
+ };
1018
+ const segments = [];
1019
+ let remainingImages = maxImages;
1020
+ let hitImageCap = false;
1021
+ const frozenRuns = freezeResponsesRuns(runs, items, o, (round) => round.callTokens + round.outputTokens)
1022
+ .filter((run) => run.every((round) => oldStarts.has(round.startIndex)));
1023
+ for (const run of frozenRuns) {
1024
+ if (remainingImages === 0) {
1025
+ hitImageCap = true;
1026
+ break;
1027
+ }
1028
+ let low = 0;
1029
+ let best;
1030
+ const fullPrep = preparePairs(run);
1031
+ if (fullPrep.estImages <= remainingImages) {
1032
+ const full = await renderPreparedPairs(fullPrep);
1033
+ if (full.images.length > 0 && full.images.length <= remainingImages) {
1034
+ low = run.length;
1035
+ best = full;
1036
+ }
1037
+ else if (run.length > 1) {
1038
+ let high = run.length;
1039
+ while (low + 1 < high) {
1040
+ const count = Math.floor((low + high) / 2);
1041
+ const prep = preparePairs(run.slice(0, count));
1042
+ if (prep.estImages > remainingImages) {
1043
+ high = count;
1044
+ continue;
1045
+ }
1046
+ const rendered = await renderPreparedPairs(prep);
1047
+ if (rendered.images.length > 0 && rendered.images.length <= remainingImages) {
1048
+ low = count;
1049
+ best = rendered;
1050
+ }
1051
+ else {
1052
+ high = count;
1053
+ }
1054
+ }
1055
+ }
1056
+ }
1057
+ else if (run.length > 1) {
1058
+ let estLow = 0;
1059
+ let estHigh = run.length;
1060
+ while (estLow + 1 < estHigh) {
1061
+ const mid = Math.floor((estLow + estHigh) / 2);
1062
+ if (preparePairs(run.slice(0, mid)).estImages <= remainingImages) {
1063
+ estLow = mid;
1064
+ }
1065
+ else {
1066
+ estHigh = mid;
1067
+ }
1068
+ }
1069
+ if (estLow > 0) {
1070
+ const cand = await renderPreparedPairs(preparePairs(run.slice(0, estLow)));
1071
+ if (cand.images.length > 0 && cand.images.length <= remainingImages) {
1072
+ low = estLow;
1073
+ best = cand;
1074
+ }
1075
+ else if (estLow > 1) {
1076
+ let high = estLow;
1077
+ while (low + 1 < high) {
1078
+ const count = Math.floor((low + high) / 2);
1079
+ const prep = preparePairs(run.slice(0, count));
1080
+ if (prep.estImages > remainingImages) {
1081
+ high = count;
1082
+ continue;
1083
+ }
1084
+ const rendered = await renderPreparedPairs(prep);
1085
+ if (rendered.images.length > 0 && rendered.images.length <= remainingImages) {
1086
+ low = count;
1087
+ best = rendered;
1088
+ }
1089
+ else {
1090
+ high = count;
1091
+ }
1092
+ }
1093
+ }
1094
+ }
1095
+ }
1096
+ if (!best || low === 0) {
1097
+ hitImageCap = true;
1098
+ break;
1099
+ }
1100
+ if (!isProfitable(best.renderedText, best.cols, undefined, best.source))
1101
+ continue;
1102
+ const selected = run.slice(0, low);
1103
+ const selectedIndices = selected
1104
+ .flatMap((round) => round.indices)
1105
+ .sort((a, b) => a - b);
1106
+ segments.push({
1107
+ insertAt: selected[0].startIndex,
1108
+ selectedIndices,
1109
+ images: best.images,
1110
+ imageSources: best.images.map(() => best.source),
1111
+ text: best.source,
1112
+ });
1113
+ remainingImages -= best.images.length;
1114
+ if (low < run.length) {
1115
+ hitImageCap = true;
1116
+ break;
1117
+ }
1118
+ }
1119
+ if (segments.length === 0) {
1120
+ return {
1121
+ ...base,
1122
+ reason: hitImageCap ? 'too_many_images' : 'not_profitable',
1123
+ collapsedChars: allText.length,
1124
+ };
1125
+ }
1126
+ const selectedIndices = segments
1127
+ .flatMap((segment) => segment.selectedIndices)
1128
+ .sort((a, b) => a - b);
1129
+ const images = segments.flatMap((segment) => segment.images);
1130
+ const imageSources = segments.flatMap((segment) => segment.imageSources);
1131
+ const text = segments.map((segment) => segment.text).join('\n\n');
1132
+ const selectedIds = new Set(selectedIndices);
1133
+ const selectedRounds = old.filter((round) => round.indices.every((index) => selectedIds.has(index)));
1134
+ state.collapsedPairs = selectedRounds.reduce((n, round) => n + round.pairs.length, 0);
1135
+ state.collapsedFunctionCallTokens = selectedRounds.reduce((n, round) => n + round.callTokens, 0);
1136
+ state.collapsedFunctionOutputTokens = selectedRounds.reduce((n, round) => n + round.outputTokens, 0);
1137
+ const droppedCodepoints = new Map();
1138
+ let droppedChars = 0;
1139
+ for (const image of images) {
1140
+ droppedChars += image.droppedChars;
1141
+ for (const [codepoint, count] of image.droppedCodepoints) {
1142
+ droppedCodepoints.set(codepoint, (droppedCodepoints.get(codepoint) ?? 0) + count);
1143
+ }
1144
+ }
1145
+ return {
1146
+ ...base,
1147
+ segments,
1148
+ images,
1149
+ imageSources,
1150
+ text,
1151
+ start: selectedIndices[0] ?? 0,
1152
+ endExclusive: (selectedIndices.at(-1) ?? -1) + 1,
1153
+ collapsedTurns: selectedIndices.length,
1154
+ collapsedChars: text.length,
1155
+ droppedChars,
1156
+ droppedCodepoints,
1157
+ selectedIndices,
1158
+ pairState: state,
1159
+ };
1160
+ }
1161
+ // ---- Chat Completions lowering ----------------------------------------------
1162
+ function chatContentToText(content) {
1163
+ if (typeof content === 'string')
1164
+ return content;
1165
+ if (!Array.isArray(content))
1166
+ return '';
1167
+ const parts = [];
1168
+ for (const p of content) {
1169
+ if (!p || typeof p !== 'object')
1170
+ continue;
1171
+ const t = p.type;
1172
+ if (t === 'text') {
1173
+ const txt = p.text;
1174
+ if (typeof txt === 'string')
1175
+ parts.push(txt);
1176
+ }
1177
+ else if (t === 'image_url' || t === 'input_image' || t === 'image') {
1178
+ parts.push('[image]');
1179
+ }
1180
+ }
1181
+ return parts.join('\n');
1182
+ }
1183
+ function chatMessageToTurn(msg, idx) {
1184
+ const o = (msg ?? {});
1185
+ const role = typeof o.role === 'string' ? o.role : '';
1186
+ const hasImage = Array.isArray(o.content) && o.content.some((part) => {
1187
+ if (!part || typeof part !== 'object')
1188
+ return false;
1189
+ const type = part.type;
1190
+ return type === 'image_url' || type === 'input_image' || type === 'image';
1191
+ });
1192
+ const body = chatContentToText(o.content);
1193
+ if (role === 'tool') {
1194
+ const id = typeof o.tool_call_id === 'string' ? o.tool_call_id : '';
1195
+ return {
1196
+ text: `[tool_result]\n${body}`,
1197
+ openIds: [],
1198
+ closeIds: id ? [id] : [],
1199
+ opaque: hasImage,
1200
+ };
1201
+ }
1202
+ if (role === 'assistant') {
1203
+ const openIds = [];
1204
+ const parts = [];
1205
+ if (body.trim())
1206
+ parts.push(body);
1207
+ const tc = o.tool_calls;
1208
+ if (Array.isArray(tc)) {
1209
+ for (const call of tc) {
1210
+ const c = (call ?? {});
1211
+ const id = typeof c.id === 'string' ? c.id : '';
1212
+ if (id)
1213
+ openIds.push(id);
1214
+ const fn = c.function;
1215
+ const name = fn && typeof fn.name === 'string' ? fn.name : 'tool';
1216
+ const args = fn && typeof fn.arguments === 'string' ? fn.arguments : safeJson(fn?.arguments);
1217
+ parts.push(`[tool_use ${name}]\n${args}`);
1218
+ }
1219
+ }
1220
+ const text = parts.join('\n');
1221
+ return {
1222
+ text: text.trim() ? `<assistant t="${idx}">\n${text}\n</assistant>` : '',
1223
+ openIds,
1224
+ closeIds: [],
1225
+ opaque: hasImage,
1226
+ };
1227
+ }
1228
+ if (!body.trim())
1229
+ return { text: '', openIds: [], closeIds: [], opaque: hasImage };
1230
+ const tag = role === 'user' ? 'user' : role || 'user';
1231
+ return {
1232
+ text: `<${tag} t="${idx}">\n${body}\n</${tag}>`,
1233
+ openIds: [],
1234
+ closeIds: [],
1235
+ opaque: hasImage,
1236
+ userText: role === 'user' ? body : undefined,
1237
+ };
1238
+ }
1239
+ export function chatMessagesToTurns(messages) {
1240
+ return messages.map((msg, i) => chatMessageToTurn(msg, i));
1241
+ }
1242
+ function responsesItemToTurn(item, idx) {
1243
+ const o = (item ?? {});
1244
+ const type = responseItemType(item);
1245
+ const callId = responseCallId(item);
1246
+ if (type === 'function_call_output') {
1247
+ return {
1248
+ text: responseOutputText(o),
1249
+ openIds: [],
1250
+ closeIds: callId ? [callId] : [],
1251
+ opaque: false,
1252
+ };
1253
+ }
1254
+ if (type === 'function_call') {
1255
+ return {
1256
+ text: responseCallText(o),
1257
+ openIds: callId ? [callId] : [],
1258
+ closeIds: [],
1259
+ opaque: false,
1260
+ };
1261
+ }
1262
+ const msgText = responseMessageText(item);
1263
+ if (msgText) {
1264
+ const { role, text } = msgText;
1265
+ const tag = role === 'user' ? 'user' : 'assistant';
1266
+ return {
1267
+ text: `<${tag} t="${idx}">\n${text}\n</${tag}>`,
1268
+ openIds: [],
1269
+ closeIds: [],
1270
+ opaque: false,
1271
+ userText: role === 'user' ? text : undefined,
1272
+ };
1273
+ }
1274
+ return { text: '', openIds: [], closeIds: [], opaque: false };
1275
+ }
1276
+ export function responsesItemsToTurns(items) {
1277
+ return items.map((item, i) => responsesItemToTurn(item, i));
1278
+ }
1279
+ //# sourceMappingURL=openai-history.js.map