@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.
- package/CHANGELOG.md +134 -0
- package/LICENSE +22 -0
- package/NOTICE +13 -0
- package/PRIVACY.md +41 -0
- package/README.md +288 -2
- package/SECURITY.md +53 -0
- package/assets/JETBRAINS_MONO_LICENSE.txt +89 -0
- package/assets/SPLEEN_LICENSE.txt +24 -0
- package/assets/UNIFONT_LICENSE.txt +476 -0
- package/assets/fiche-logo-dark.svg +61 -0
- package/assets/fiche-logo-light.svg +61 -0
- package/assets/fiche-logo.svg +71 -0
- package/assets/fiche-mark.svg +48 -0
- package/bin/cli.js +7 -0
- package/bin/mcp.js +8 -0
- package/dist/calibrate.d.ts +30 -0
- package/dist/calibrate.js +588 -0
- package/dist/core/anthropic-vision.d.ts +28 -0
- package/dist/core/anthropic-vision.js +34 -0
- package/dist/core/applicability.d.ts +63 -0
- package/dist/core/applicability.js +151 -0
- package/dist/core/atlas-gray-jbmono10.d.ts +26 -0
- package/dist/core/atlas-gray-jbmono10.js +64 -0
- package/dist/core/atlas-gray-jbmono12.d.ts +26 -0
- package/dist/core/atlas-gray-jbmono12.js +64 -0
- package/dist/core/atlas-gray-jbmono14.d.ts +26 -0
- package/dist/core/atlas-gray-jbmono14.js +64 -0
- package/dist/core/atlas-gray.d.ts +26 -0
- package/dist/core/atlas-gray.js +64 -0
- package/dist/core/atlas-jbmono10.d.ts +34 -0
- package/dist/core/atlas-jbmono10.js +71 -0
- package/dist/core/atlas-jbmono12.d.ts +34 -0
- package/dist/core/atlas-jbmono12.js +71 -0
- package/dist/core/atlas-jbmono14.d.ts +34 -0
- package/dist/core/atlas-jbmono14.js +71 -0
- package/dist/core/atlas.d.ts +34 -0
- package/dist/core/atlas.js +71 -0
- package/dist/core/baseline.d.ts +121 -0
- package/dist/core/baseline.js +200 -0
- package/dist/core/calibration.d.ts +86 -0
- package/dist/core/calibration.js +547 -0
- package/dist/core/casi-delta.d.ts +63 -0
- package/dist/core/casi-delta.js +1271 -0
- package/dist/core/claude-model-profiles.d.ts +53 -0
- package/dist/core/claude-model-profiles.js +160 -0
- package/dist/core/client-tool-round.d.ts +31 -0
- package/dist/core/client-tool-round.js +58 -0
- package/dist/core/codex-cache.d.ts +20 -0
- package/dist/core/codex-cache.js +59 -0
- package/dist/core/context-mmu.d.ts +350 -0
- package/dist/core/context-mmu.js +3028 -0
- package/dist/core/cpt-fit.d.ts +70 -0
- package/dist/core/cpt-fit.js +197 -0
- package/dist/core/env.d.ts +8 -0
- package/dist/core/env.js +15 -0
- package/dist/core/export.d.ts +127 -0
- package/dist/core/export.js +385 -0
- package/dist/core/factsheet.d.ts +77 -0
- package/dist/core/factsheet.js +494 -0
- package/dist/core/gemini-model-profiles.d.ts +20 -0
- package/dist/core/gemini-model-profiles.js +134 -0
- package/dist/core/google.d.ts +76 -0
- package/dist/core/google.js +1380 -0
- package/dist/core/gpt-model-profiles.d.ts +218 -0
- package/dist/core/gpt-model-profiles.js +570 -0
- package/dist/core/gpt-tokens.d.ts +14 -0
- package/dist/core/gpt-tokens.js +165 -0
- package/dist/core/history.d.ts +197 -0
- package/dist/core/history.js +1003 -0
- package/dist/core/index.d.ts +16 -0
- package/dist/core/index.js +16 -0
- package/dist/core/library.d.ts +80 -0
- package/dist/core/library.js +131 -0
- package/dist/core/measurement.d.ts +34 -0
- package/dist/core/measurement.js +280 -0
- package/dist/core/messages-chat-bridge.d.ts +23 -0
- package/dist/core/messages-chat-bridge.js +747 -0
- package/dist/core/messages-responses-bridge.d.ts +11 -0
- package/dist/core/messages-responses-bridge.js +893 -0
- package/dist/core/openai-history.d.ts +184 -0
- package/dist/core/openai-history.js +1279 -0
- package/dist/core/openai-savings.d.ts +57 -0
- package/dist/core/openai-savings.js +116 -0
- package/dist/core/openai.d.ts +68 -0
- package/dist/core/openai.js +2523 -0
- package/dist/core/pin.d.ts +199 -0
- package/dist/core/pin.js +1353 -0
- package/dist/core/png.d.ts +14 -0
- package/dist/core/png.js +188 -0
- package/dist/core/prefix-tape.d.ts +102 -0
- package/dist/core/prefix-tape.js +315 -0
- package/dist/core/price-id.d.ts +10 -0
- package/dist/core/price-id.js +26 -0
- package/dist/core/prices.generated.d.ts +36 -0
- package/dist/core/prices.generated.js +369 -0
- package/dist/core/pricing.d.ts +134 -0
- package/dist/core/pricing.js +335 -0
- package/dist/core/profile-base.d.ts +30 -0
- package/dist/core/profile-base.js +67 -0
- package/dist/core/provider-router.d.ts +51 -0
- package/dist/core/provider-router.js +121 -0
- package/dist/core/proxy.d.ts +252 -0
- package/dist/core/proxy.js +2929 -0
- package/dist/core/reader-tier.d.ts +24 -0
- package/dist/core/reader-tier.js +118 -0
- package/dist/core/render.d.ts +280 -0
- package/dist/core/render.js +1302 -0
- package/dist/core/request-guard.d.ts +31 -0
- package/dist/core/request-guard.js +126 -0
- package/dist/core/request-transform.d.ts +43 -0
- package/dist/core/request-transform.js +173 -0
- package/dist/core/schema-compiler.d.ts +64 -0
- package/dist/core/schema-compiler.js +1696 -0
- package/dist/core/schema-strip.d.ts +29 -0
- package/dist/core/schema-strip.js +173 -0
- package/dist/core/session-state.d.ts +219 -0
- package/dist/core/session-state.js +929 -0
- package/dist/core/stage-plugins.d.ts +45 -0
- package/dist/core/stage-plugins.js +205 -0
- package/dist/core/text-history.d.ts +74 -0
- package/dist/core/text-history.js +612 -0
- package/dist/core/text-hygiene.d.ts +160 -0
- package/dist/core/text-hygiene.js +2259 -0
- package/dist/core/toon.d.ts +29 -0
- package/dist/core/toon.js +425 -0
- package/dist/core/tracker.d.ts +223 -0
- package/dist/core/tracker.js +290 -0
- package/dist/core/transform.d.ts +589 -0
- package/dist/core/transform.js +3153 -0
- package/dist/core/types.d.ts +87 -0
- package/dist/core/types.js +8 -0
- package/dist/core/upstream-hosts.d.ts +127 -0
- package/dist/core/upstream-hosts.js +398 -0
- package/dist/core/vision-cost.d.ts +63 -0
- package/dist/core/vision-cost.js +137 -0
- package/dist/dashboard/fragments.d.ts +87 -0
- package/dist/dashboard/fragments.js +1515 -0
- package/dist/dashboard/types.d.ts +217 -0
- package/dist/dashboard/types.js +3 -0
- package/dist/dashboard/vendor.d.ts +3 -0
- package/dist/dashboard/vendor.js +6 -0
- package/dist/dashboard.d.ts +372 -0
- package/dist/dashboard.js +2731 -0
- package/dist/export-collect.d.ts +36 -0
- package/dist/export-collect.js +59 -0
- package/dist/file-tracker.d.ts +42 -0
- package/dist/file-tracker.js +234 -0
- package/dist/kosha-sync.d.ts +74 -0
- package/dist/kosha-sync.js +272 -0
- package/dist/launchd-socket.d.ts +22 -0
- package/dist/launchd-socket.js +210 -0
- package/dist/mcp/cli.d.ts +2 -0
- package/dist/mcp/cli.js +55 -0
- package/dist/mcp/server.d.ts +48 -0
- package/dist/mcp/server.js +987 -0
- package/dist/mmu-store.d.ts +31 -0
- package/dist/mmu-store.js +179 -0
- package/dist/node-fetch.d.ts +22 -0
- package/dist/node-fetch.js +489 -0
- package/dist/node.d.ts +9 -0
- package/dist/node.js +244396 -0
- package/dist/request-decoding.d.ts +30 -0
- package/dist/request-decoding.js +85 -0
- package/dist/sessions.d.ts +179 -0
- package/dist/sessions.js +837 -0
- package/dist/stats.d.ts +114 -0
- package/dist/stats.js +439 -0
- package/dist/turn-report.d.ts +65 -0
- package/dist/turn-report.js +724 -0
- package/dist/warp/app-launch.d.ts +26 -0
- package/dist/warp/app-launch.js +155 -0
- package/dist/warp/ca.d.ts +74 -0
- package/dist/warp/ca.js +416 -0
- package/dist/warp/connect.d.ts +42 -0
- package/dist/warp/connect.js +686 -0
- package/dist/warp/der.d.ts +57 -0
- package/dist/warp/der.js +151 -0
- package/dist/warp/index.d.ts +79 -0
- package/dist/warp/index.js +650 -0
- package/dist/warp/resolve.d.ts +12 -0
- package/dist/warp/resolve.js +49 -0
- package/dist/warp/route.d.ts +71 -0
- package/dist/warp/route.js +134 -0
- package/dist/worker.d.ts +71 -0
- package/dist/worker.js +174 -0
- package/docs/SECURITY_MODEL.md +84 -0
- package/package.json +122 -4
- package/plugins/fiche-companion/README.md +42 -0
- package/plugins/fiche-companion/assets/logo.svg +48 -0
- package/plugins/fiche-companion/hooks.json +11 -0
- package/plugins/fiche-companion/mcp_config.json +8 -0
- package/plugins/fiche-companion/plugin.json +18 -0
- package/plugins/fiche-companion/scripts/claude-statusline.mjs +35 -0
- package/plugins/fiche-companion/scripts/post-invocation.mjs +122 -0
- package/plugins/fiche-companion/scripts/resolve-turn-report.mjs +132 -0
- package/plugins/fiche-companion/skills/fiche/SKILL.md +61 -0
|
@@ -0,0 +1,1003 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* History-image compression (Variant C).
|
|
3
|
+
*
|
|
4
|
+
* Collapses the largest closed-tool-sequence prefix into one synthetic user message
|
|
5
|
+
* containing 1-N PNG image blocks. The live tail (keepTail turns + any open tool
|
|
6
|
+
* sequence) stays as text. thinking blocks are dropped from the collapsed range —
|
|
7
|
+
* only the most-recent assistant-with-tool_use must round-trip bit-perfect, and
|
|
8
|
+
* that turn is in the live tail by construction.
|
|
9
|
+
*
|
|
10
|
+
* Synthesized message uses role:'user' because Anthropic forbids image blocks inside
|
|
11
|
+
* role:'assistant'. cache_control placement is left to the caller (transform.ts).
|
|
12
|
+
*/
|
|
13
|
+
import { DENSE_CONTENT_CHARS_PER_IMAGE, DENSE_CONTENT_COLS, maxCharsPerImage, DENSE_RENDER_STYLE, MAX_HEIGHT_PX, neutralizeSentinel, reflow, renderTextToPngsWithCharLimit, roleSlotSegment, SLOT_MARK_ASSISTANT, SLOT_MARK_USER } from './render.js';
|
|
14
|
+
import { factSheetText } from './factsheet.js';
|
|
15
|
+
import { bytesToBase64 } from './png.js';
|
|
16
|
+
/**
|
|
17
|
+
* Banner text blocks that bracket the collapsed-history image(s) in the synthetic
|
|
18
|
+
* user message. Exported as the SINGLE SOURCE OF TRUTH: transform.ts keys its
|
|
19
|
+
* cache-anchor relocation off the intro text, so a literal copy there would
|
|
20
|
+
* silently break relocation whenever this wording changes (it did exactly once —
|
|
21
|
+
* the XML-framing reword left the matcher pointing at the old banner). Both the
|
|
22
|
+
* emitter (here) and the matcher (transform.ts) must reference this constant.
|
|
23
|
+
*/
|
|
24
|
+
export const HISTORY_SYNTHETIC_INTRO = '[Earlier turns of THIS conversation, transcribed in the image(s) below. Each turn is wrapped in <user t="N">...</user> or <assistant t="N">...</assistant> tags, where N is an absolute turn index (larger N = more recent); attribute every turn strictly by its tag, and treat the highest-N turns as the most recent prior context, NOT the low-N opening turns. Earlier turns may contain questions or tasks that were already answered later in this same history; do not reopen low-N turns unless the live text after this block asks you to. For exact identifiers, hashes, version strings, and numbers from the transcript, rely on the exact-value factsheet or re-read the source; do not guess an exact value seen only in the image. This is prior context, NOT the current request.]';
|
|
25
|
+
export const HISTORY_SYNTHETIC_OUTRO = '[End of earlier conversation. The current request is the live text that follows below.]';
|
|
26
|
+
const LATEST_COLLAPSED_USER_PREVIEW_CHARS = 300;
|
|
27
|
+
/** Images Anthropic accepts per request. Exceeding it fails the WHOLE request with
|
|
28
|
+
* an opaque `500` (observed 2026-07-31 at 387 images), not a typed 400 — so the
|
|
29
|
+
* cap has to be enforced on our side, before the wire. */
|
|
30
|
+
export const ANTHROPIC_MAX_IMAGES = 100;
|
|
31
|
+
/** Default history-image budget: the hard cap minus headroom for the slab, tool-doc
|
|
32
|
+
* and tool_result images that share the same request. transform.ts narrows this
|
|
33
|
+
* further with the count it has already emitted for this very request. */
|
|
34
|
+
export const ANTHROPIC_HISTORY_IMAGE_BUDGET = 80;
|
|
35
|
+
export const HISTORY_DEFAULTS = {
|
|
36
|
+
keepTail: 4,
|
|
37
|
+
minCollapsePrefix: 10,
|
|
38
|
+
cols: 100,
|
|
39
|
+
collapseChunk: 50,
|
|
40
|
+
freezeChunk: 10,
|
|
41
|
+
protectedPrefix: 0,
|
|
42
|
+
reflow: true,
|
|
43
|
+
style: DENSE_RENDER_STYLE,
|
|
44
|
+
maxHeightPx: MAX_HEIGHT_PX,
|
|
45
|
+
// MUST agree with `cols` above: pageChars is what the budget arithmetic thinks
|
|
46
|
+
// one image holds, and DENSE_CONTENT_CHARS_PER_IMAGE is only true at 312 cols.
|
|
47
|
+
pageChars: maxCharsPerImage(100),
|
|
48
|
+
imageBudget: ANTHROPIC_HISTORY_IMAGE_BUDGET,
|
|
49
|
+
packFill: false,
|
|
50
|
+
minFreezeStep: 0,
|
|
51
|
+
separateAdjacentToolPairs: false,
|
|
52
|
+
};
|
|
53
|
+
/**
|
|
54
|
+
* Return the last index ≤ cutoffExclusive at which all tool_use_ids are matched
|
|
55
|
+
* by tool_results in [0..i]. Returns -1 if no closed boundary exists.
|
|
56
|
+
* Robust to interleaved/parallel tool calls via openSet tracking. Consecutive
|
|
57
|
+
* assistant-tool/user-result pairs are treated as one tool round: some Anthropic
|
|
58
|
+
* clients serialize a parallel batch that way, so the apparently-closed gap
|
|
59
|
+
* between two pairs is not a safe collapse boundary.
|
|
60
|
+
*
|
|
61
|
+
* Pass `separateAdjacentToolPairs = true` only for clients that merge parallel
|
|
62
|
+
* tool calls into a single assistant message (e.g. Claude Code).
|
|
63
|
+
*/
|
|
64
|
+
export function findClosedPrefixBoundary(messages, cutoffExclusive, separateAdjacentToolPairs = false) {
|
|
65
|
+
if (cutoffExclusive <= 0)
|
|
66
|
+
return -1;
|
|
67
|
+
const openSet = new Set();
|
|
68
|
+
let lastClosed = -1;
|
|
69
|
+
let inToolRound = false;
|
|
70
|
+
const limit = Math.min(cutoffExclusive, messages.length);
|
|
71
|
+
// Never close on an assistant tool_use message, even when a tool_use id is
|
|
72
|
+
// absent or non-string (so openSet never tracks it).
|
|
73
|
+
const closeAt = (j) => {
|
|
74
|
+
const m = messages[j];
|
|
75
|
+
const opensToolUse = m?.role === 'assistant' &&
|
|
76
|
+
Array.isArray(m.content) &&
|
|
77
|
+
m.content.some((blk) => !!blk && blk.type === 'tool_use');
|
|
78
|
+
if (!opensToolUse)
|
|
79
|
+
lastClosed = j;
|
|
80
|
+
};
|
|
81
|
+
for (let i = 0; i < limit; i++) {
|
|
82
|
+
const msg = messages[i];
|
|
83
|
+
const assistantToolUses = msg.role === 'assistant' && Array.isArray(msg.content)
|
|
84
|
+
? msg.content.filter((blk) => !!blk && blk.type === 'tool_use')
|
|
85
|
+
: [];
|
|
86
|
+
// A closed tool pair is only provisional until we see what follows. OpenCode
|
|
87
|
+
// commonly emits a parallel Anthropic round as A-call/A-result,
|
|
88
|
+
// B-call/B-result. Do not expose the gap between those adjacent pairs as a
|
|
89
|
+
// collapse boundary.
|
|
90
|
+
if (inToolRound && openSet.size === 0 && assistantToolUses.length === 0) {
|
|
91
|
+
closeAt(i - 1);
|
|
92
|
+
inToolRound = false;
|
|
93
|
+
}
|
|
94
|
+
if (!Array.isArray(msg.content)) {
|
|
95
|
+
if (openSet.size === 0 && !inToolRound)
|
|
96
|
+
lastClosed = i;
|
|
97
|
+
continue;
|
|
98
|
+
}
|
|
99
|
+
if (msg.role === 'assistant') {
|
|
100
|
+
if (assistantToolUses.length > 0 && !separateAdjacentToolPairs)
|
|
101
|
+
inToolRound = true;
|
|
102
|
+
for (const blk of assistantToolUses) {
|
|
103
|
+
const id = blk.id;
|
|
104
|
+
if (typeof id === 'string')
|
|
105
|
+
openSet.add(id);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
else if (msg.role === 'user') {
|
|
109
|
+
for (const blk of msg.content) {
|
|
110
|
+
if (blk && blk.type === 'tool_result') {
|
|
111
|
+
const id = blk.tool_use_id;
|
|
112
|
+
if (typeof id === 'string')
|
|
113
|
+
openSet.delete(id);
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
if (openSet.size === 0 && !inToolRound)
|
|
118
|
+
closeAt(i);
|
|
119
|
+
}
|
|
120
|
+
// The end of a closed round is safe only if the actual next message does not
|
|
121
|
+
// continue it with another serialized tool call. Looking one message past the
|
|
122
|
+
// cutoff changes no collapsed index; it merely prevents splitting the round.
|
|
123
|
+
if (inToolRound && openSet.size === 0) {
|
|
124
|
+
const next = messages[limit];
|
|
125
|
+
const nextContinuesRound = next?.role === 'assistant' &&
|
|
126
|
+
Array.isArray(next.content) &&
|
|
127
|
+
next.content.some((blk) => !!blk && blk.type === 'tool_use');
|
|
128
|
+
if (!nextContinuesRound)
|
|
129
|
+
closeAt(limit - 1);
|
|
130
|
+
}
|
|
131
|
+
return lastClosed;
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* Claude Code appends "(file state is current in your context — no need to Read it
|
|
135
|
+
* back)" to Edit/Write tool_results. True when emitted; stale by the time the turn
|
|
136
|
+
* reaches this serializer: everything blocksToText feeds becomes collapsed/imaged
|
|
137
|
+
* HISTORY, the CLI's read-ledger resets on process restart, and the file may have
|
|
138
|
+
* changed in later turns anyway. Models trusting the hint from prior turns were the
|
|
139
|
+
* dominant cause of `File has not been read yet` gate errors (2026-07-03 audit,
|
|
140
|
+
* n=55 classified: 20 had a same-transcript Read invalidated by a restart while
|
|
141
|
+
* this hint said "current"; 34 edited from prior-session context with no Read at
|
|
142
|
+
* all). Rewriting at serialization time also cleans slabs inherited by future
|
|
143
|
+
* continuation sessions. Whitespace-tolerant match: 3 of ~2,125 logged instances
|
|
144
|
+
* wrap mid-hint.
|
|
145
|
+
*/
|
|
146
|
+
const FRESHNESS_HINT_RE = /\(file state is current in your\s+context — no need to Read it back\)/g;
|
|
147
|
+
const STALE_FRESHNESS_NOTE = '(state as of this PRIOR turn — the file may have changed since; Read it again before editing)';
|
|
148
|
+
export function staleFreshnessHints(text) {
|
|
149
|
+
return text.replace(FRESHNESS_HINT_RE, STALE_FRESHNESS_NOTE);
|
|
150
|
+
}
|
|
151
|
+
/**
|
|
152
|
+
* Linearise content blocks to a single string. Drops thinking blocks (only the
|
|
153
|
+
* most-recent assistant turn needs bit-perfect thinking, and it's in the live tail).
|
|
154
|
+
* Inline images collapse to [image] to avoid double-encoding.
|
|
155
|
+
*/
|
|
156
|
+
export function blocksToText(content) {
|
|
157
|
+
if (typeof content === 'string')
|
|
158
|
+
return content;
|
|
159
|
+
// Untrusted bodies can carry a non-array content (e.g. `content: null`).
|
|
160
|
+
// Tolerate it like every sibling serializer/scanner here rather than letting
|
|
161
|
+
// `for...of` throw and 502 the whole request.
|
|
162
|
+
if (!Array.isArray(content))
|
|
163
|
+
return '';
|
|
164
|
+
const parts = [];
|
|
165
|
+
for (const blk of content) {
|
|
166
|
+
if (!blk || typeof blk !== 'object')
|
|
167
|
+
continue;
|
|
168
|
+
const t = blk.type;
|
|
169
|
+
switch (t) {
|
|
170
|
+
case 'text':
|
|
171
|
+
parts.push(blk.text);
|
|
172
|
+
break;
|
|
173
|
+
case 'tool_use': {
|
|
174
|
+
const tu = blk;
|
|
175
|
+
// Compact JSON (no indent) — pretty-printing bloats text ~5× and the renderer is row-aware.
|
|
176
|
+
let argsStr;
|
|
177
|
+
try {
|
|
178
|
+
argsStr = JSON.stringify(tu.input);
|
|
179
|
+
}
|
|
180
|
+
catch {
|
|
181
|
+
argsStr = String(tu.input);
|
|
182
|
+
}
|
|
183
|
+
parts.push(`[tool_use ${tu.name}]\n${argsStr}`);
|
|
184
|
+
break;
|
|
185
|
+
}
|
|
186
|
+
case 'tool_result': {
|
|
187
|
+
const tr = blk;
|
|
188
|
+
const inner = tr.content;
|
|
189
|
+
let innerText;
|
|
190
|
+
if (typeof inner === 'string') {
|
|
191
|
+
innerText = inner;
|
|
192
|
+
}
|
|
193
|
+
else if (Array.isArray(inner)) {
|
|
194
|
+
const subParts = [];
|
|
195
|
+
for (const sub of inner) {
|
|
196
|
+
if (!sub || typeof sub !== 'object')
|
|
197
|
+
continue;
|
|
198
|
+
if (sub.type === 'text') {
|
|
199
|
+
subParts.push(sub.text);
|
|
200
|
+
}
|
|
201
|
+
else if (sub.type === 'image') {
|
|
202
|
+
subParts.push('[image]');
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
innerText = subParts.join('\n');
|
|
206
|
+
}
|
|
207
|
+
else {
|
|
208
|
+
innerText = '';
|
|
209
|
+
}
|
|
210
|
+
const errMark = tr.is_error === true ? ' (error)' : '';
|
|
211
|
+
parts.push(`[tool_result${errMark}]\n${staleFreshnessHints(innerText)}`);
|
|
212
|
+
break;
|
|
213
|
+
}
|
|
214
|
+
case 'image':
|
|
215
|
+
parts.push('[image]');
|
|
216
|
+
break;
|
|
217
|
+
// 'thinking' and any other block type → drop silently.
|
|
218
|
+
default:
|
|
219
|
+
break;
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
return parts.join('\n\n');
|
|
223
|
+
}
|
|
224
|
+
/** Return the caller's cache_control marker on a message, if any block carries one.
|
|
225
|
+
* Used to align freeze-chunk boundaries to roaming breakpoints so a marked segment
|
|
226
|
+
* stays independently cacheable instead of being silently flattened into the image. */
|
|
227
|
+
export function messageCacheControl(m) {
|
|
228
|
+
if (!Array.isArray(m.content))
|
|
229
|
+
return undefined;
|
|
230
|
+
for (let i = m.content.length - 1; i >= 0; i--) {
|
|
231
|
+
const b = m.content[i];
|
|
232
|
+
if (b && b.cache_control !== undefined)
|
|
233
|
+
return b.cache_control;
|
|
234
|
+
}
|
|
235
|
+
return undefined;
|
|
236
|
+
}
|
|
237
|
+
/** Serialize messages [fromInclusive..upToExclusive) to a text blob with
|
|
238
|
+
* `<role>…</role>` XML wrappers. Open+close tags bracket each turn so a misread
|
|
239
|
+
* boundary self-corrects and the model attributes speakers reliably even off a
|
|
240
|
+
* lossy image — bare `--- role ---` start-dividers let one role bleed into the
|
|
241
|
+
* next when a divider is missed. */
|
|
242
|
+
export function messagesToHistoryText(messages, upToExclusive, fromInclusive = 0) {
|
|
243
|
+
return messagesToHistorySegments(messages, upToExclusive, fromInclusive).text;
|
|
244
|
+
}
|
|
245
|
+
/** Like {@link messagesToHistoryText} but also returns the parallel slot string for
|
|
246
|
+
* colorByRole: a width-identical copy where each `<role>` tag is replaced by its
|
|
247
|
+
* role marker and the body is copied verbatim (slot 0). Role attribution is decided
|
|
248
|
+
* HERE, where the message role is known — never re-parsed out of flattened text.
|
|
249
|
+
* A tool_result block sits inside its user message and a tool_use block inside its
|
|
250
|
+
* assistant message, so each is owned by the turn that carries it. */
|
|
251
|
+
export function messagesToHistorySegments(messages, upToExclusive, fromInclusive = 0) {
|
|
252
|
+
const textOut = [];
|
|
253
|
+
const slotOut = [];
|
|
254
|
+
for (let i = fromInclusive; i < upToExclusive; i++) {
|
|
255
|
+
const m = messages[i];
|
|
256
|
+
// The user's typed words are carried as TEXT alongside the image (see
|
|
257
|
+
// userTurnBlocks) and are deliberately not rasterized. Everything else in the
|
|
258
|
+
// message — tool_results, system-reminders, slab scaffolding — still renders.
|
|
259
|
+
const body = blocksToText(m.role === 'user' ? withoutTypedUserText(m.content) : m.content);
|
|
260
|
+
if (!body.trim())
|
|
261
|
+
continue;
|
|
262
|
+
const isAssistant = m.role === 'assistant';
|
|
263
|
+
const tag = isAssistant ? 'assistant' : 'user';
|
|
264
|
+
const mark = isAssistant ? SLOT_MARK_ASSISTANT : SLOT_MARK_USER;
|
|
265
|
+
// Absolute turn index = message position from conversation start. Gives the model an
|
|
266
|
+
// explicit recency anchor so it can tell turn 1 from turn 60, instead of pattern-matching
|
|
267
|
+
// the most salient turn — primacy was resurrecting the OPENING turn as if it were the live
|
|
268
|
+
// request. MUST stay absolute (never "N ago" or "i/total"): a per-turn value that's stable
|
|
269
|
+
// once the turn closes keeps each frozen chunk byte-identical, so cache_read survives.
|
|
270
|
+
const attr = ` t="${i}"`;
|
|
271
|
+
textOut.push(`<${tag}${attr}>\n${body}\n</${tag}>`);
|
|
272
|
+
slotOut.push(roleSlotSegment(tag, body, mark, attr));
|
|
273
|
+
}
|
|
274
|
+
return { text: textOut.join('\n\n'), slotText: slotOut.join('\n\n') };
|
|
275
|
+
}
|
|
276
|
+
export function compactPreview(text) {
|
|
277
|
+
const compact = text.replace(/\s+/g, ' ').trim();
|
|
278
|
+
if (compact.length <= LATEST_COLLAPSED_USER_PREVIEW_CHARS)
|
|
279
|
+
return compact;
|
|
280
|
+
return compact.slice(0, LATEST_COLLAPSED_USER_PREVIEW_CHARS).trimEnd() + '...';
|
|
281
|
+
}
|
|
282
|
+
// User-typed words must never survive ONLY as a truncated preview (#7: the EC demo's
|
|
283
|
+
// 577-char task lost its questions and "Reply as:" format at the 300-char preview cap,
|
|
284
|
+
// because no later turn restated them). Task-defining text is carried verbatim up to
|
|
285
|
+
// this cap; beyond it, head+tail elision keeps both the setup AND the trailing output
|
|
286
|
+
// format, which real prompts put at the end.
|
|
287
|
+
const LATEST_COLLAPSED_USER_VERBATIM_CHARS = 4000;
|
|
288
|
+
const VERBATIM_HEAD_CHARS = 2600;
|
|
289
|
+
const VERBATIM_TAIL_CHARS = 1400;
|
|
290
|
+
export function verbatimTaskText(text) {
|
|
291
|
+
const t = text.trim();
|
|
292
|
+
if (t.length <= LATEST_COLLAPSED_USER_VERBATIM_CHARS)
|
|
293
|
+
return t;
|
|
294
|
+
const elided = t.length - VERBATIM_HEAD_CHARS - VERBATIM_TAIL_CHARS;
|
|
295
|
+
return (t.slice(0, VERBATIM_HEAD_CHARS) +
|
|
296
|
+
`\n[… middle elided (${elided} chars) …]\n` +
|
|
297
|
+
t.slice(t.length - VERBATIM_TAIL_CHARS));
|
|
298
|
+
}
|
|
299
|
+
/** A user message's content with the user's typed text blocks removed. */
|
|
300
|
+
function withoutTypedUserText(content) {
|
|
301
|
+
if (typeof content === 'string')
|
|
302
|
+
return '';
|
|
303
|
+
if (!Array.isArray(content))
|
|
304
|
+
return content;
|
|
305
|
+
const { typedIdx } = splitUserTyped(content);
|
|
306
|
+
if (typedIdx.size === 0)
|
|
307
|
+
return content;
|
|
308
|
+
return content.filter((_, i) => !typedIdx.has(i));
|
|
309
|
+
}
|
|
310
|
+
/**
|
|
311
|
+
* The user's typed words in a user message: text blocks only, excluding
|
|
312
|
+
* <system-reminder> wrappers and (in the opening slab message) everything at or
|
|
313
|
+
* before the '[End of rendered context.]' boundary — same rule as
|
|
314
|
+
* demoteProtectedHeadText, so inkling scaffolding is never mistaken for the task.
|
|
315
|
+
*/
|
|
316
|
+
function typedUserText(content) {
|
|
317
|
+
return splitUserTyped(content).text;
|
|
318
|
+
}
|
|
319
|
+
/**
|
|
320
|
+
* Same selection as {@link typedUserText}, but also reports WHICH block indices hold
|
|
321
|
+
* it. The collapse renders a user message minus these indices, so the user's own
|
|
322
|
+
* words never enter the history image while the tool_results in the same message —
|
|
323
|
+
* which pair with an imaged assistant tool_use and must not be orphaned — still do.
|
|
324
|
+
*/
|
|
325
|
+
function splitUserTyped(content) {
|
|
326
|
+
const typedIdx = new Set();
|
|
327
|
+
if (typeof content === 'string')
|
|
328
|
+
return { text: content.trim(), typedIdx };
|
|
329
|
+
if (!Array.isArray(content))
|
|
330
|
+
return { text: '', typedIdx };
|
|
331
|
+
const boundaryIdx = content.findIndex((b) => b && typeof b === 'object' &&
|
|
332
|
+
b.type === 'text' &&
|
|
333
|
+
b.text === '[End of rendered context.]');
|
|
334
|
+
const parts = [];
|
|
335
|
+
for (let i = 0; i < content.length; i++) {
|
|
336
|
+
if (boundaryIdx >= 0 && i <= boundaryIdx)
|
|
337
|
+
continue;
|
|
338
|
+
const blk = content[i];
|
|
339
|
+
if (!blk || typeof blk !== 'object')
|
|
340
|
+
continue;
|
|
341
|
+
if (blk.type !== 'text')
|
|
342
|
+
continue;
|
|
343
|
+
const text = blk.text.trim();
|
|
344
|
+
if (!text)
|
|
345
|
+
continue;
|
|
346
|
+
if (text.startsWith('<system-reminder>'))
|
|
347
|
+
continue;
|
|
348
|
+
parts.push(text);
|
|
349
|
+
typedIdx.add(i);
|
|
350
|
+
}
|
|
351
|
+
return { text: parts.join('\n\n'), typedIdx };
|
|
352
|
+
}
|
|
353
|
+
/**
|
|
354
|
+
* Demote request TEXT in the protected head (slab anchor) to a marked PRIOR-CONTEXT
|
|
355
|
+
* tombstone. The session's OPENING user turn rides in the SAME message as the slab
|
|
356
|
+
* images (transform.ts sets protectedPrefix = firstUserIdx + 1 to keep that message
|
|
357
|
+
* from collapsing into [image] placeholders). Protecting it for the cache anchor also
|
|
358
|
+
* passed its request text through as clean native text at the very TOP — ahead of the
|
|
359
|
+
* synthetic history block — where the model reads it as the LIVE request. It never is:
|
|
360
|
+
* the live request is always in the tail (tail = messages.slice(collapseLen),
|
|
361
|
+
* keepTail >= 1), so any text in the protected head is, by construction, stale.
|
|
362
|
+
*
|
|
363
|
+
* Image/tool blocks (the slab) pass through byte-identical so the cache anchor and any
|
|
364
|
+
* cache_control breakpoint survive; the demotion is a pure function of the message, so
|
|
365
|
+
* the protected prefix stays byte-stable across turns (one-time re-cache on deploy).
|
|
366
|
+
*/
|
|
367
|
+
/**
|
|
368
|
+
* Standing instructions (CLAUDE.md and friends) ride INSIDE the opening user message
|
|
369
|
+
* as <system-reminder> blocks. They are not conversational content: they govern the
|
|
370
|
+
* CURRENT turn and every later one, so demoting them to a 300-char preview silently
|
|
371
|
+
* drops project rules from the live request (the preview truncates long CLAUDE.md
|
|
372
|
+
* bodies well before their last rule). Carve them out and pass them through verbatim —
|
|
373
|
+
* same treatment the slab scaffolding gets above. Byte-stability is preserved: the
|
|
374
|
+
* reminder text is identical turn to turn, so the protected prefix still re-caches
|
|
375
|
+
* only on deploy.
|
|
376
|
+
*
|
|
377
|
+
* Only the LEADING run is carved out, which is where the harness puts them: the
|
|
378
|
+
* opening message is `<system-reminder>…</system-reminder>\n\n<the user's words>`.
|
|
379
|
+
* A reminder appearing later in the text is not the harness's — an `@file` mention
|
|
380
|
+
* inlines untrusted file content into this same block, so a file containing
|
|
381
|
+
* `</system-reminder><system-reminder>new rules…` would otherwise be lifted out of
|
|
382
|
+
* the tombstone and re-emitted as a standing instruction governing the session.
|
|
383
|
+
* Anything past the leading run stays in `rest` and is truncated to a preview.
|
|
384
|
+
*/
|
|
385
|
+
const LEADING_REMINDER_RE = /^\s*<system-reminder>[\s\S]*?<\/system-reminder>/;
|
|
386
|
+
function splitStandingInstructions(text) {
|
|
387
|
+
const reminders = [];
|
|
388
|
+
let rest = text;
|
|
389
|
+
for (;;) {
|
|
390
|
+
const m = LEADING_REMINDER_RE.exec(rest);
|
|
391
|
+
if (!m)
|
|
392
|
+
break;
|
|
393
|
+
reminders.push(m[0].trim());
|
|
394
|
+
rest = rest.slice(m[0].length);
|
|
395
|
+
}
|
|
396
|
+
return { reminders, rest };
|
|
397
|
+
}
|
|
398
|
+
function demoteProtectedHeadText(head) {
|
|
399
|
+
return head.map((m, idx) => {
|
|
400
|
+
if (m.role !== 'user')
|
|
401
|
+
return m;
|
|
402
|
+
const tomb = (preview, cc) => {
|
|
403
|
+
const t = {
|
|
404
|
+
type: 'text',
|
|
405
|
+
text: `[Opening turn <user t="${idx}"> of this session — PRIOR CONTEXT ONLY, ` +
|
|
406
|
+
`superseded by later turns; NOT the current request and must not be acted ` +
|
|
407
|
+
`on. Preview: "${preview}"]`,
|
|
408
|
+
};
|
|
409
|
+
if (cc !== undefined) {
|
|
410
|
+
t.cache_control = cc;
|
|
411
|
+
}
|
|
412
|
+
return t;
|
|
413
|
+
};
|
|
414
|
+
// Standing instructions survive verbatim; only the stale request prose demotes.
|
|
415
|
+
const demoteText = (text, cc) => {
|
|
416
|
+
const { reminders, rest } = splitStandingInstructions(text);
|
|
417
|
+
// A protected opening turn above the normal native-text budget is exactly
|
|
418
|
+
// where a long task contract lives. Keep its existing bounded head+tail
|
|
419
|
+
// representation instead of reducing the whole contract to 300 chars.
|
|
420
|
+
const preview = rest.length > USER_TEXT_MAX_CHARS
|
|
421
|
+
? verbatimTaskText(rest)
|
|
422
|
+
: compactPreview(rest);
|
|
423
|
+
if (reminders.length === 0)
|
|
424
|
+
return preview ? [tomb(preview, cc)] : undefined;
|
|
425
|
+
const out = reminders.map((r) => ({ type: 'text', text: r }));
|
|
426
|
+
if (preview)
|
|
427
|
+
out.push(tomb(preview));
|
|
428
|
+
// cache_control rides the LAST block so the breakpoint keeps its position.
|
|
429
|
+
if (cc !== undefined) {
|
|
430
|
+
out[out.length - 1].cache_control = cc;
|
|
431
|
+
}
|
|
432
|
+
return out;
|
|
433
|
+
};
|
|
434
|
+
if (typeof m.content === 'string') {
|
|
435
|
+
const blocks = demoteText(m.content);
|
|
436
|
+
return blocks ? { ...m, content: blocks } : m;
|
|
437
|
+
}
|
|
438
|
+
if (!Array.isArray(m.content))
|
|
439
|
+
return m;
|
|
440
|
+
// inkling's own slab scaffolding (the rendered images, the fact-sheet, and the
|
|
441
|
+
// '[End of rendered context.]' boundary) is NOT the user's request and must
|
|
442
|
+
// survive byte-identical: relocateAnchorToHistoryImage keys on that boundary
|
|
443
|
+
// text to locate the slab cache anchor. Only the user's stale opening turn —
|
|
444
|
+
// the blocks AFTER the boundary — gets demoted. With no boundary (the slab did
|
|
445
|
+
// not image) boundaryIdx is -1 and the whole message demotes, exactly as before.
|
|
446
|
+
const boundaryIdx = m.content.findIndex((b) => b && typeof b === 'object' &&
|
|
447
|
+
b.type === 'text' &&
|
|
448
|
+
b.text === '[End of rendered context.]');
|
|
449
|
+
let changed = false;
|
|
450
|
+
const out = [];
|
|
451
|
+
for (let i = 0; i < m.content.length; i++) {
|
|
452
|
+
const blk = m.content[i];
|
|
453
|
+
if (boundaryIdx >= 0 && i <= boundaryIdx) {
|
|
454
|
+
out.push(blk); // slab images + fact-sheet + boundary: proxy scaffolding, kept verbatim
|
|
455
|
+
continue;
|
|
456
|
+
}
|
|
457
|
+
if (blk && typeof blk === 'object' && blk.type === 'text') {
|
|
458
|
+
const blocks = demoteText(blk.text, blk.cache_control);
|
|
459
|
+
if (blocks) {
|
|
460
|
+
out.push(...blocks);
|
|
461
|
+
changed = true;
|
|
462
|
+
continue;
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
out.push(blk); // images / tool blocks (slab anchor) pass through byte-identical
|
|
466
|
+
}
|
|
467
|
+
return changed ? { ...m, content: out } : m;
|
|
468
|
+
});
|
|
469
|
+
}
|
|
470
|
+
// A user prompt is the one thing in the transcript the model cannot reconstruct:
|
|
471
|
+
// assistant prose and tool output are recoverable from the work itself, but the
|
|
472
|
+
// instruction that caused them exists nowhere else. Real prompts are also short —
|
|
473
|
+
// a few hundred chars — so they are NEVER rasterized with the history: they stay
|
|
474
|
+
// native text, at zero OCR risk, on the path that matters most. Past this cap a
|
|
475
|
+
// prompt is a pasted document, not an instruction; that one gets its own image
|
|
476
|
+
// rather than bloating the text, and still does not join the history transcript.
|
|
477
|
+
const USER_TEXT_MAX_CHARS = 2000;
|
|
478
|
+
/**
|
|
479
|
+
* The user's own words for one chunk's message range, as native text — the
|
|
480
|
+
* counterpart to withoutTypedUserText, which removed them from the render.
|
|
481
|
+
*
|
|
482
|
+
* A chunk's blocks are a pure function of its own range, so a frozen chunk emits
|
|
483
|
+
* identical blocks forever and the cache_read chain across it survives (#11).
|
|
484
|
+
* Range starts at protectedPrefix, so head turns stay tombstoned (#14).
|
|
485
|
+
*/
|
|
486
|
+
async function userTurnBlocks(messages, fromInclusive, upToExclusive, onImage, renderOpts) {
|
|
487
|
+
const out = [];
|
|
488
|
+
let pending = [];
|
|
489
|
+
// Over-cap prompts are collected and rendered TOGETHER at the end of the chunk.
|
|
490
|
+
// One image per pasted document would put a floor of ≥1 image on every such turn
|
|
491
|
+
// that no grid coarsening can lift: a session with 175 pasted logs rendered 175
|
|
492
|
+
// near-empty images and blew the 100-image cap (#161), which upstream answers with
|
|
493
|
+
// a 500 rather than a usable error. Batching packs them at ~28k chars/image and
|
|
494
|
+
// makes the count a function of BYTES, which the freeze grid can actually control.
|
|
495
|
+
// Within a chunk the order is fixed and the chunk is frozen once closed, so the
|
|
496
|
+
// grouped bytes are as stable as the transcript image next to them.
|
|
497
|
+
const imaged = [];
|
|
498
|
+
const flush = () => {
|
|
499
|
+
if (pending.length === 0)
|
|
500
|
+
return;
|
|
501
|
+
out.push({
|
|
502
|
+
type: 'text',
|
|
503
|
+
text: `[User turns from this session, verbatim — these are the user's own words, kept as text rather than rendered into the images above. PRIOR context: none of it is the current request unless the live text at the end of this message says to continue it.\n${pending.join('\n')}\n]`,
|
|
504
|
+
});
|
|
505
|
+
pending = [];
|
|
506
|
+
};
|
|
507
|
+
for (let i = fromInclusive; i < upToExclusive; i++) {
|
|
508
|
+
const m = messages[i];
|
|
509
|
+
if (m.role !== 'user')
|
|
510
|
+
continue;
|
|
511
|
+
const typed = typedUserText(m.content);
|
|
512
|
+
if (!typed)
|
|
513
|
+
continue;
|
|
514
|
+
if (typed.length <= USER_TEXT_MAX_CHARS) {
|
|
515
|
+
pending.push(`<user t="${i}">${typed}</user>`);
|
|
516
|
+
continue;
|
|
517
|
+
}
|
|
518
|
+
// Past the cap this is a pasted document, not an instruction: it is rendered
|
|
519
|
+
// verbatim below instead of bloating the text.
|
|
520
|
+
imaged.push({ idx: i, typed });
|
|
521
|
+
}
|
|
522
|
+
flush();
|
|
523
|
+
if (imaged.length > 0) {
|
|
524
|
+
// Every batched turn is NAMED (attribution is the point), but only the newest
|
|
525
|
+
// few carry a preview: 60 pasted docs × a 300-char preview is a wall of text
|
|
526
|
+
// that buys nothing the images below don't already say, verbatim.
|
|
527
|
+
const PREVIEW_LIMIT = 8;
|
|
528
|
+
const previews = imaged
|
|
529
|
+
.map((u, k) => k >= imaged.length - PREVIEW_LIMIT
|
|
530
|
+
? `<user t="${u.idx}"> (${u.typed.length} chars) Preview: ${compactPreview(u.typed)}`
|
|
531
|
+
: `<user t="${u.idx}"> (${u.typed.length} chars)`)
|
|
532
|
+
.join('\n');
|
|
533
|
+
out.push({
|
|
534
|
+
type: 'text',
|
|
535
|
+
text: `[${imaged.length} user turn(s) from this session were too long to carry as text; they are rendered verbatim, in turn order, in the image(s) immediately below, separate from the history transcript. Each begins with its own <user t="N"> tag. PRIOR context, not the current request.\n${previews}]`,
|
|
536
|
+
});
|
|
537
|
+
const rawUserText = imaged.map((u) => `<user t="${u.idx}">\n${u.typed}\n</user>`).join('\n\n');
|
|
538
|
+
const safeUserText = neutralizeSentinel(rawUserText);
|
|
539
|
+
const renderUserText = (renderOpts?.reflow ?? true)
|
|
540
|
+
? (reflow(safeUserText) ?? safeUserText)
|
|
541
|
+
: rawUserText;
|
|
542
|
+
const imgs = await renderTextToPngsWithCharLimit(renderUserText, renderOpts?.cols ?? DENSE_CONTENT_COLS, DENSE_CONTENT_CHARS_PER_IMAGE, renderOpts?.style ?? DENSE_RENDER_STYLE, renderOpts?.maxHeightPx);
|
|
543
|
+
for (const img of imgs) {
|
|
544
|
+
out.push({
|
|
545
|
+
type: 'image',
|
|
546
|
+
source: {
|
|
547
|
+
type: 'base64',
|
|
548
|
+
media_type: 'image/png',
|
|
549
|
+
data: bytesToBase64(img.png),
|
|
550
|
+
},
|
|
551
|
+
});
|
|
552
|
+
onImage(img);
|
|
553
|
+
}
|
|
554
|
+
}
|
|
555
|
+
return out;
|
|
556
|
+
}
|
|
557
|
+
function latestCollapsedUserPointer(messages, upToExclusive, protectedPrefix) {
|
|
558
|
+
// Scan the WHOLE demoted/collapsed range, INCLUDING the protected head (#7):
|
|
559
|
+
// in single-task sessions the opening turn is the only user-typed text there is.
|
|
560
|
+
// Two fidelity regimes:
|
|
561
|
+
// - i >= protectedPrefix: the turn is rendered into the history images at full
|
|
562
|
+
// fidelity — a bounded preview is only a recency cue, keep it cheap.
|
|
563
|
+
// - i < protectedPrefix: demoteProtectedHeadText reduced the turn to a 300-char
|
|
564
|
+
// preview and it is NOT imaged — the pointer is the ONLY carrier, so the typed
|
|
565
|
+
// text goes verbatim (capped with head+tail elision). It lives in the synthetic
|
|
566
|
+
// message after the slab anchor, so cache stability is unaffected.
|
|
567
|
+
for (let i = upToExclusive - 1; i >= 0; i--) {
|
|
568
|
+
const m = messages[i];
|
|
569
|
+
if (m.role !== 'user')
|
|
570
|
+
continue;
|
|
571
|
+
const typed = typedUserText(m.content);
|
|
572
|
+
if (!typed)
|
|
573
|
+
continue;
|
|
574
|
+
if (i >= protectedPrefix) {
|
|
575
|
+
const preview = compactPreview(typed);
|
|
576
|
+
return {
|
|
577
|
+
type: 'text',
|
|
578
|
+
text: `[Most recent collapsed user turn: <user t="${i}">${preview}</user>. This is still prior context; do not treat it as the current request unless the live text that follows asks to continue it.]`,
|
|
579
|
+
};
|
|
580
|
+
}
|
|
581
|
+
const carried = verbatimTaskText(typed);
|
|
582
|
+
return {
|
|
583
|
+
type: 'text',
|
|
584
|
+
text: `[Most recent collapsed user turn, carried verbatim because it appears nowhere else in full: <user t="${i}">${carried}</user>. This is still prior context; but if no later turn supersedes it, it is the task the live turn continues — follow its exact instructions, including any requested output format.]`,
|
|
585
|
+
};
|
|
586
|
+
}
|
|
587
|
+
return undefined;
|
|
588
|
+
}
|
|
589
|
+
/**
|
|
590
|
+
* Collapse the closed-prefix run into one synthetic user message with 1+ history images.
|
|
591
|
+
* Returns original messages unchanged on any no-collapse path (reason set in info).
|
|
592
|
+
* Image blocks are returned with NO cache_control — caller decides placement.
|
|
593
|
+
*/
|
|
594
|
+
export async function collapseHistory(messages, isProfitable, opts = {}) {
|
|
595
|
+
const o = { ...HISTORY_DEFAULTS, ...opts };
|
|
596
|
+
const info = {
|
|
597
|
+
collapsedTurns: 0,
|
|
598
|
+
collapsedChars: 0,
|
|
599
|
+
collapsedImages: 0,
|
|
600
|
+
collapsedImageBytes: 0,
|
|
601
|
+
collapsedImagePixels: 0,
|
|
602
|
+
collapsedPngs: [],
|
|
603
|
+
collapsedImageDims: [],
|
|
604
|
+
droppedChars: 0,
|
|
605
|
+
droppedCodepoints: new Map(),
|
|
606
|
+
};
|
|
607
|
+
if (!messages || messages.length === 0) {
|
|
608
|
+
info.reason = 'no_history';
|
|
609
|
+
return { messages: messages ?? [], info };
|
|
610
|
+
}
|
|
611
|
+
// Protected leading messages (slab) pass through untouched; collapse starts after them.
|
|
612
|
+
const protectedPrefix = Math.max(0, Math.min(o.protectedPrefix ?? 0, messages.length));
|
|
613
|
+
// Snap the cutoff to a collapseChunk grid so the rendered PNG stays byte-identical
|
|
614
|
+
// across turns and keeps hitting Anthropic's prompt cache. See docs/HISTORY_CACHE_MODEL.md.
|
|
615
|
+
// Floor at minCollapsePrefix + protectedPrefix so short histories still collapse.
|
|
616
|
+
const rawCutoff = messages.length - o.keepTail;
|
|
617
|
+
const cutoff = o.collapseChunk > 0
|
|
618
|
+
? Math.min(rawCutoff, Math.max(o.minCollapsePrefix + protectedPrefix, Math.floor(rawCutoff / o.collapseChunk) * o.collapseChunk))
|
|
619
|
+
: rawCutoff;
|
|
620
|
+
const boundary = findClosedPrefixBoundary(messages, cutoff, o.separateAdjacentToolPairs);
|
|
621
|
+
if (boundary < 0) {
|
|
622
|
+
info.reason = 'no_closed_prefix';
|
|
623
|
+
return { messages, info };
|
|
624
|
+
}
|
|
625
|
+
// Need at least minCollapsePrefix turns in [protectedPrefix..boundary] — collapsing
|
|
626
|
+
// 2-3 turns is net cost (cache-amortization math doesn't work at small scale).
|
|
627
|
+
let collapseLen = boundary + 1;
|
|
628
|
+
if (collapseLen - protectedPrefix < o.minCollapsePrefix) {
|
|
629
|
+
info.reason = 'prefix_too_short';
|
|
630
|
+
return { messages, info };
|
|
631
|
+
}
|
|
632
|
+
// ---- Image budget ---------------------------------------------------------
|
|
633
|
+
// Anthropic rejects the WHOLE request past ANTHROPIC_MAX_IMAGES with an opaque
|
|
634
|
+
// 500, so the budget is a hard constraint we must enforce before the wire. Price
|
|
635
|
+
// candidate grids off per-message serialized lengths: one pass here replaces
|
|
636
|
+
// re-serializing the transcript once per candidate step.
|
|
637
|
+
const budget = o.imageBudget > 0 ? o.imageBudget : Infinity;
|
|
638
|
+
const pageChars = Math.max(1, o.pageChars);
|
|
639
|
+
const msgLen = [];
|
|
640
|
+
// Over-cap user prompts are imaged too (userTurnBlocks), batched per chunk. They
|
|
641
|
+
// are NOT part of the transcript segments, so they must be priced separately or
|
|
642
|
+
// the estimate silently under-counts and the wire limit is what finds out.
|
|
643
|
+
const userImgLen = [];
|
|
644
|
+
for (let i = protectedPrefix; i < collapseLen; i++) {
|
|
645
|
+
const seg = messagesToHistorySegments(messages, i + 1, i).text;
|
|
646
|
+
msgLen.push(seg.length === 0 ? 0 : seg.length + 2); // +2 = the "\n\n" joiner
|
|
647
|
+
const m = messages[i];
|
|
648
|
+
const typed = m.role === 'user' ? typedUserText(m.content) : '';
|
|
649
|
+
userImgLen.push(typed && typed.length > USER_TEXT_MAX_CHARS ? typed.length + 20 : 0);
|
|
650
|
+
}
|
|
651
|
+
const sumOf = (arr, from, to) => {
|
|
652
|
+
let n = 0;
|
|
653
|
+
for (let i = from; i < to; i++)
|
|
654
|
+
n += arr[i];
|
|
655
|
+
return n;
|
|
656
|
+
};
|
|
657
|
+
const sumLen = (from, to) => sumOf(msgLen, from, to);
|
|
658
|
+
const perfectPages = Math.ceil(sumLen(0, msgLen.length) / pageChars) +
|
|
659
|
+
Math.ceil(sumOf(userImgLen, 0, userImgLen.length) / pageChars);
|
|
660
|
+
const emptyInfo = (reason, collapsedChars = 0) => ({
|
|
661
|
+
collapsedTurns: 0,
|
|
662
|
+
collapsedChars,
|
|
663
|
+
collapsedImages: 0,
|
|
664
|
+
collapsedImageBytes: 0,
|
|
665
|
+
collapsedImagePixels: 0,
|
|
666
|
+
collapsedPngs: [],
|
|
667
|
+
collapsedImageDims: [],
|
|
668
|
+
droppedChars: 0,
|
|
669
|
+
droppedCodepoints: new Map(),
|
|
670
|
+
reason,
|
|
671
|
+
});
|
|
672
|
+
let trimmed = false;
|
|
673
|
+
if (perfectPages > budget) {
|
|
674
|
+
// Even a perfectly packed render of the full range overflows. Keep the OLDEST
|
|
675
|
+
// messages collapsed (the frozen prefix must stay anchored at protectedPrefix
|
|
676
|
+
// or every cached chunk re-keys) and leave the tail as live text.
|
|
677
|
+
let acc = 0;
|
|
678
|
+
let k = 0;
|
|
679
|
+
while (k < msgLen.length && acc + msgLen[k] + userImgLen[k] <= budget * pageChars) {
|
|
680
|
+
acc += msgLen[k] + userImgLen[k];
|
|
681
|
+
k++;
|
|
682
|
+
}
|
|
683
|
+
const trimmedLen = findClosedPrefixBoundary(messages, protectedPrefix + k, o.separateAdjacentToolPairs) + 1;
|
|
684
|
+
if (trimmedLen <= protectedPrefix || trimmedLen - protectedPrefix < o.minCollapsePrefix) {
|
|
685
|
+
return { messages, info: emptyInfo('over_budget') };
|
|
686
|
+
}
|
|
687
|
+
collapseLen = trimmedLen;
|
|
688
|
+
msgLen.length = collapseLen - protectedPrefix;
|
|
689
|
+
userImgLen.length = collapseLen - protectedPrefix;
|
|
690
|
+
trimmed = true;
|
|
691
|
+
}
|
|
692
|
+
let effPageChars = pageChars;
|
|
693
|
+
let text = '';
|
|
694
|
+
let assembledChunks = [];
|
|
695
|
+
let carryOverEnd = -1;
|
|
696
|
+
let stepFreezeStep;
|
|
697
|
+
const maxBudgetAttempts = 3;
|
|
698
|
+
for (let attempt = 0; attempt < maxBudgetAttempts; attempt++) {
|
|
699
|
+
msgLen.length = collapseLen - protectedPrefix;
|
|
700
|
+
userImgLen.length = collapseLen - protectedPrefix;
|
|
701
|
+
// Exclude slab messages (protectedPrefix) from serialization.
|
|
702
|
+
text = messagesToHistoryText(messages, collapseLen, protectedPrefix);
|
|
703
|
+
if (!text || text.length === 0) {
|
|
704
|
+
return { messages, info: emptyInfo('render_empty') };
|
|
705
|
+
}
|
|
706
|
+
// Reflow for RENDERING ONLY: pack short lines + mark hard breaks with ↵ so the
|
|
707
|
+
// newline-heavy transcript fills full rows instead of one line per row. Same
|
|
708
|
+
// glyph size (cols unchanged) → identical legibility, fewer images, more saved.
|
|
709
|
+
// `text` stays original — it backs `collapsedChars` and the cache byte-stability.
|
|
710
|
+
const safeText = neutralizeSentinel(text);
|
|
711
|
+
const renderText = o.reflow ? reflow(safeText) ?? safeText : text;
|
|
712
|
+
if (!isProfitable(renderText, o.cols)) { // pass string, not length — see ProfitableFn
|
|
713
|
+
return { messages, info: emptyInfo('not_profitable', text.length) };
|
|
714
|
+
}
|
|
715
|
+
// APPEND-ONLY rendering. Render the collapse range [protectedPrefix..collapseLen)
|
|
716
|
+
// as independent image blocks on an ABSOLUTE message grid anchored at
|
|
717
|
+
// protectedPrefix (step = freezeChunk). A completed chunk's bytes are fixed by
|
|
718
|
+
// its message range alone, so old chunks stay byte-identical as the conversation
|
|
719
|
+
// grows (cache_read forever); only the newest partial chunk re-renders.
|
|
720
|
+
//
|
|
721
|
+
// Chunk-end positions = the absolute grid ∪ caller cache_control marks: a marked
|
|
722
|
+
// message forces a split right after it, and that chunk's LAST image carries the
|
|
723
|
+
// caller's marker — so a roaming breakpoint survives as an aligned, independently
|
|
724
|
+
// cacheable image boundary instead of being silently flattened (count conserved,
|
|
725
|
+
// never added). Each chunk is reflowed and rendered on its own, which is what
|
|
726
|
+
// makes the bytes a pure function of the chunk's messages.
|
|
727
|
+
//
|
|
728
|
+
// The grid step is ADAPTIVE. A fixed 10-message step emits ≥1 page per chunk no
|
|
729
|
+
// matter how little text the chunk holds: a long session of short turns rendered
|
|
730
|
+
// 317 pages at 43% fill and 500'd the request (#161). Doubling the step merges
|
|
731
|
+
// neighbouring chunks — pages fill up, count drops ~2× per doubling — while
|
|
732
|
+
// keeping chunk boundaries a SUBSET of the base grid, so a chunk frozen at the
|
|
733
|
+
// coarse step spans whole base chunks and stays byte-identical as long as the
|
|
734
|
+
// step never shrinks again (the caller pins it via minFreezeStep).
|
|
735
|
+
const baseStep = o.freezeChunk > 0 ? o.freezeChunk : collapseLen - protectedPrefix;
|
|
736
|
+
const rangeLen = collapseLen - protectedPrefix;
|
|
737
|
+
const pagesFor = (s) => {
|
|
738
|
+
let pages = 0;
|
|
739
|
+
for (let a = 0; a < rangeLen; a += s) {
|
|
740
|
+
const b = Math.min(a + s, rangeLen);
|
|
741
|
+
const chars = sumLen(a, b);
|
|
742
|
+
if (chars > 0)
|
|
743
|
+
pages += Math.ceil(chars / effPageChars);
|
|
744
|
+
// Over-cap user prompts in this chunk are batched into their own image(s).
|
|
745
|
+
const uchars = sumOf(userImgLen, a, b);
|
|
746
|
+
if (uchars > 0)
|
|
747
|
+
pages += Math.ceil(uchars / effPageChars);
|
|
748
|
+
}
|
|
749
|
+
return pages;
|
|
750
|
+
};
|
|
751
|
+
// Caller cache_control marks force extra splits below; charge one page each so a
|
|
752
|
+
// marked request can't slip past the budget the estimate just cleared.
|
|
753
|
+
let markSplits = 0;
|
|
754
|
+
for (let i = protectedPrefix; i < collapseLen; i++) {
|
|
755
|
+
if (messageCacheControl(messages[i]) !== undefined)
|
|
756
|
+
markSplits++;
|
|
757
|
+
}
|
|
758
|
+
let step = baseStep;
|
|
759
|
+
// Sticky floor first: a session already repacked coarse must STAY coarse.
|
|
760
|
+
while (step < o.minFreezeStep && step < rangeLen)
|
|
761
|
+
step *= 2;
|
|
762
|
+
// packFill trades the append-only freeze for ~2× fewer image tokens and is only
|
|
763
|
+
// set when the upstream cache is dead anyway (cold session / after a 500).
|
|
764
|
+
const packedPages = Math.max(1, Math.ceil(sumLen(0, rangeLen) / effPageChars));
|
|
765
|
+
const goal = Math.min(budget, o.packFill ? packedPages + 1 : Infinity);
|
|
766
|
+
while (step < rangeLen && pagesFor(step) + markSplits > goal)
|
|
767
|
+
step *= 2;
|
|
768
|
+
stepFreezeStep = o.minFreezeStep > 0 ? Math.max(step, o.minFreezeStep) : step;
|
|
769
|
+
const ends = new Set();
|
|
770
|
+
for (let e = protectedPrefix + step; e < collapseLen; e += step)
|
|
771
|
+
ends.add(e);
|
|
772
|
+
const markerByEnd = new Map();
|
|
773
|
+
for (let i = protectedPrefix; i < collapseLen; i++) {
|
|
774
|
+
const cc = messageCacheControl(messages[i]);
|
|
775
|
+
if (cc !== undefined) {
|
|
776
|
+
ends.add(i + 1);
|
|
777
|
+
markerByEnd.set(i + 1, cc);
|
|
778
|
+
}
|
|
779
|
+
}
|
|
780
|
+
ends.add(collapseLen);
|
|
781
|
+
const sortedEnds = [...ends].filter((e) => e > protectedPrefix && e <= collapseLen).sort((a, b) => a - b);
|
|
782
|
+
// Carry-over anchor end: the largest FULLY grid-aligned chunk boundary strictly
|
|
783
|
+
// before collapseLen. That chunk's bytes are frozen across window advances, unlike
|
|
784
|
+
// the newest partial chunk — so it's the stable place to pin the cache breakpoint (#11).
|
|
785
|
+
carryOverEnd = -1;
|
|
786
|
+
for (let e = protectedPrefix + step; e < collapseLen; e += step)
|
|
787
|
+
carryOverEnd = e;
|
|
788
|
+
const chunkJobs = [];
|
|
789
|
+
let chunkStart = protectedPrefix;
|
|
790
|
+
for (const chunkEnd of sortedEnds) {
|
|
791
|
+
// messagesToHistorySegments already omits the user's typed words; userTurnBlocks
|
|
792
|
+
// below carries them as text so a prompt is never read back out of pixels.
|
|
793
|
+
const seg = messagesToHistorySegments(messages, chunkEnd, chunkStart);
|
|
794
|
+
const userFrom = chunkStart;
|
|
795
|
+
chunkStart = chunkEnd;
|
|
796
|
+
if (!seg.text || seg.text.length === 0) {
|
|
797
|
+
chunkJobs.push({ chunkEnd, userFrom, empty: true });
|
|
798
|
+
continue;
|
|
799
|
+
}
|
|
800
|
+
let chunkRender = seg.text;
|
|
801
|
+
let chunkSlot = seg.slotText;
|
|
802
|
+
if (o.reflow) {
|
|
803
|
+
const safeTextSeg = neutralizeSentinel(seg.text);
|
|
804
|
+
const safeSlotSeg = neutralizeSentinel(seg.slotText);
|
|
805
|
+
const rt = reflow(safeTextSeg);
|
|
806
|
+
const rs = reflow(safeSlotSeg);
|
|
807
|
+
if (rt !== null && rs !== null) {
|
|
808
|
+
chunkRender = rt;
|
|
809
|
+
chunkSlot = rs;
|
|
810
|
+
}
|
|
811
|
+
else {
|
|
812
|
+
chunkRender = safeTextSeg;
|
|
813
|
+
chunkSlot = safeSlotSeg;
|
|
814
|
+
}
|
|
815
|
+
}
|
|
816
|
+
chunkJobs.push({ chunkEnd, userFrom, empty: false, chunkRender, chunkSlot });
|
|
817
|
+
}
|
|
818
|
+
// Render all chunks concurrently across off-thread CompressionStream workers while
|
|
819
|
+
// preserving deterministic chunk order when assembling blocks and metrics below.
|
|
820
|
+
const chunkStyle = { ...o.style, colorByRole: true };
|
|
821
|
+
const renderedChunkImgs = await Promise.all(chunkJobs.map((job) => job.empty
|
|
822
|
+
? Promise.resolve([])
|
|
823
|
+
: renderTextToPngsWithCharLimit(job.chunkRender, o.cols, DENSE_CONTENT_CHARS_PER_IMAGE, chunkStyle, o.maxHeightPx, job.chunkSlot)));
|
|
824
|
+
const userRenderOpts = {
|
|
825
|
+
cols: o.cols,
|
|
826
|
+
style: o.style,
|
|
827
|
+
maxHeightPx: o.maxHeightPx,
|
|
828
|
+
reflow: o.reflow,
|
|
829
|
+
};
|
|
830
|
+
assembledChunks = [];
|
|
831
|
+
for (let jobIdx = 0; jobIdx < chunkJobs.length; jobIdx++) {
|
|
832
|
+
const job = chunkJobs[jobIdx];
|
|
833
|
+
const chunkBlocks = [];
|
|
834
|
+
const chunkImgs = [];
|
|
835
|
+
let transcriptImgCount = 0;
|
|
836
|
+
if (job.empty) {
|
|
837
|
+
// Transcript empty (e.g. the chunk was nothing but user prompts) — the
|
|
838
|
+
// prompts themselves still belong in the output.
|
|
839
|
+
chunkBlocks.push(...(await userTurnBlocks(messages, job.userFrom, job.chunkEnd, (img) => chunkImgs.push(img), userRenderOpts)));
|
|
840
|
+
assembledChunks.push({ chunkEnd: job.chunkEnd, blocks: chunkBlocks, imgs: chunkImgs, transcriptImgCount: 0 });
|
|
841
|
+
continue;
|
|
842
|
+
}
|
|
843
|
+
const imgs = renderedChunkImgs[jobIdx];
|
|
844
|
+
transcriptImgCount = imgs.length;
|
|
845
|
+
const markerCC = markerByEnd.get(job.chunkEnd);
|
|
846
|
+
for (let k = 0; k < imgs.length; k++) {
|
|
847
|
+
const img = imgs[k];
|
|
848
|
+
const block = {
|
|
849
|
+
type: 'image',
|
|
850
|
+
source: {
|
|
851
|
+
type: 'base64',
|
|
852
|
+
media_type: 'image/png',
|
|
853
|
+
data: bytesToBase64(img.png),
|
|
854
|
+
},
|
|
855
|
+
};
|
|
856
|
+
// Mark the LAST image of a marked segment — the caller's breakpoint anchor.
|
|
857
|
+
if (markerCC !== undefined && k === imgs.length - 1)
|
|
858
|
+
block.cache_control = markerCC;
|
|
859
|
+
chunkBlocks.push(block);
|
|
860
|
+
chunkImgs.push(img);
|
|
861
|
+
}
|
|
862
|
+
// This chunk's user prompts, as text, immediately after the image they were
|
|
863
|
+
// pulled out of — attribution stays local and the ordering matches the render.
|
|
864
|
+
chunkBlocks.push(...(await userTurnBlocks(messages, job.userFrom, job.chunkEnd, (img) => chunkImgs.push(img), userRenderOpts)));
|
|
865
|
+
assembledChunks.push({ chunkEnd: job.chunkEnd, blocks: chunkBlocks, imgs: chunkImgs, transcriptImgCount });
|
|
866
|
+
}
|
|
867
|
+
let totalImages = 0;
|
|
868
|
+
for (const ch of assembledChunks)
|
|
869
|
+
totalImages += ch.imgs.length;
|
|
870
|
+
if (!Number.isFinite(budget) || totalImages <= budget) {
|
|
871
|
+
break;
|
|
872
|
+
}
|
|
873
|
+
// Post-render hard budget guard: chars/pageChars can underestimate actual rendered
|
|
874
|
+
// PNG counts on short-line transcripts, coarse steps, or reflowed user turns.
|
|
875
|
+
// First try trimming to the largest valid closed chunk prefix within budget; if
|
|
876
|
+
// even the first chunk exceeds budget, tighten collapseLen using observed density.
|
|
877
|
+
let cum = 0;
|
|
878
|
+
const cumByChunk = [];
|
|
879
|
+
for (const ch of assembledChunks) {
|
|
880
|
+
cum += ch.imgs.length;
|
|
881
|
+
cumByChunk.push(cum);
|
|
882
|
+
}
|
|
883
|
+
let keepIdx = -1;
|
|
884
|
+
for (let k = assembledChunks.length - 1; k >= 0; k--) {
|
|
885
|
+
const candidateEnd = assembledChunks[k].chunkEnd;
|
|
886
|
+
if (cumByChunk[k] <= budget &&
|
|
887
|
+
cumByChunk[k] > 0 &&
|
|
888
|
+
candidateEnd - protectedPrefix >= o.minCollapsePrefix &&
|
|
889
|
+
findClosedPrefixBoundary(messages, candidateEnd) + 1 === candidateEnd) {
|
|
890
|
+
keepIdx = k;
|
|
891
|
+
break;
|
|
892
|
+
}
|
|
893
|
+
}
|
|
894
|
+
if (keepIdx >= 0) {
|
|
895
|
+
assembledChunks.length = keepIdx + 1;
|
|
896
|
+
collapseLen = assembledChunks[keepIdx].chunkEnd;
|
|
897
|
+
trimmed = true;
|
|
898
|
+
text = messagesToHistoryText(messages, collapseLen, protectedPrefix);
|
|
899
|
+
if (!text || text.length === 0) {
|
|
900
|
+
return { messages, info: emptyInfo('render_empty') };
|
|
901
|
+
}
|
|
902
|
+
const trimmedSafe = neutralizeSentinel(text);
|
|
903
|
+
const trimmedRender = o.reflow ? reflow(trimmedSafe) ?? trimmedSafe : text;
|
|
904
|
+
if (!isProfitable(trimmedRender, o.cols)) {
|
|
905
|
+
return { messages, info: emptyInfo('not_profitable', text.length) };
|
|
906
|
+
}
|
|
907
|
+
carryOverEnd = -1;
|
|
908
|
+
for (let e = protectedPrefix + step; e < collapseLen; e += step)
|
|
909
|
+
carryOverEnd = e;
|
|
910
|
+
break;
|
|
911
|
+
}
|
|
912
|
+
if (attempt === maxBudgetAttempts - 1) {
|
|
913
|
+
return { messages, info: emptyInfo('over_budget') };
|
|
914
|
+
}
|
|
915
|
+
// Even the first chunk exceeded budget (e.g. coarse adaptive step merged into one
|
|
916
|
+
// chunk or short-line wrap reduced effective chars/image). Measure actual yield
|
|
917
|
+
// and re-budget to a closed prefix that fits without bailing out at 0 turns.
|
|
918
|
+
const c0Imgs = cumByChunk[0] ?? totalImages;
|
|
919
|
+
const useChunk0 = assembledChunks.length > 0 && c0Imgs > budget;
|
|
920
|
+
const sampleSpan = useChunk0
|
|
921
|
+
? Math.min(rangeLen, assembledChunks[0].chunkEnd - protectedPrefix)
|
|
922
|
+
: rangeLen;
|
|
923
|
+
const sampleImgs = useChunk0 ? c0Imgs : totalImages;
|
|
924
|
+
const sampleChars = sumLen(0, sampleSpan) + sumOf(userImgLen, 0, sampleSpan);
|
|
925
|
+
if (sampleImgs <= 0 || sampleChars <= 0) {
|
|
926
|
+
return { messages, info: emptyInfo('over_budget') };
|
|
927
|
+
}
|
|
928
|
+
const observedCharsPerImg = Math.max(1, Math.floor(sampleChars / sampleImgs));
|
|
929
|
+
effPageChars = Math.min(effPageChars, observedCharsPerImg);
|
|
930
|
+
const targetChars = Math.max(0, Math.floor(sampleChars * (budget / sampleImgs) * 0.9));
|
|
931
|
+
let acc2 = 0;
|
|
932
|
+
let k2 = 0;
|
|
933
|
+
while (k2 < sampleSpan && acc2 + msgLen[k2] + userImgLen[k2] <= targetChars) {
|
|
934
|
+
acc2 += msgLen[k2] + userImgLen[k2];
|
|
935
|
+
k2++;
|
|
936
|
+
}
|
|
937
|
+
let nextLen = findClosedPrefixBoundary(messages, protectedPrefix + k2) + 1;
|
|
938
|
+
if (nextLen >= collapseLen) {
|
|
939
|
+
nextLen = findClosedPrefixBoundary(messages, collapseLen - 1) + 1;
|
|
940
|
+
}
|
|
941
|
+
if (nextLen <= protectedPrefix || nextLen - protectedPrefix < o.minCollapsePrefix) {
|
|
942
|
+
return { messages, info: emptyInfo('over_budget') };
|
|
943
|
+
}
|
|
944
|
+
collapseLen = nextLen;
|
|
945
|
+
trimmed = true;
|
|
946
|
+
}
|
|
947
|
+
const blocks = [];
|
|
948
|
+
let imageCount = 0;
|
|
949
|
+
let carryOverOrdinal = -1;
|
|
950
|
+
const countImage = (img) => {
|
|
951
|
+
imageCount++;
|
|
952
|
+
info.collapsedImageBytes += img.png.length;
|
|
953
|
+
info.collapsedImagePixels += img.width * img.height;
|
|
954
|
+
info.collapsedPngs.push(img.png);
|
|
955
|
+
info.collapsedImageDims.push({ width: img.width, height: img.height });
|
|
956
|
+
info.droppedChars += img.droppedChars;
|
|
957
|
+
for (const [cp, n] of img.droppedCodepoints) {
|
|
958
|
+
info.droppedCodepoints.set(cp, (info.droppedCodepoints.get(cp) ?? 0) + n);
|
|
959
|
+
}
|
|
960
|
+
};
|
|
961
|
+
for (const ch of assembledChunks) {
|
|
962
|
+
blocks.push(...ch.blocks);
|
|
963
|
+
for (let i = 0; i < ch.imgs.length; i++) {
|
|
964
|
+
countImage(ch.imgs[i]);
|
|
965
|
+
// Record after the last transcript image of carryOverEnd (before any over-cap user turn images).
|
|
966
|
+
if (ch.chunkEnd === carryOverEnd && ch.transcriptImgCount > 0 && i === ch.transcriptImgCount - 1) {
|
|
967
|
+
carryOverOrdinal = imageCount - 1;
|
|
968
|
+
}
|
|
969
|
+
}
|
|
970
|
+
}
|
|
971
|
+
if (imageCount === 0) {
|
|
972
|
+
return { messages, info: emptyInfo('render_empty') };
|
|
973
|
+
}
|
|
974
|
+
const latestUserPointer = latestCollapsedUserPointer(messages, collapseLen, protectedPrefix);
|
|
975
|
+
const historyFactSheet = factSheetText(text);
|
|
976
|
+
const syntheticContent = [
|
|
977
|
+
{ type: 'text', text: HISTORY_SYNTHETIC_INTRO },
|
|
978
|
+
...blocks,
|
|
979
|
+
...(latestUserPointer ? [latestUserPointer] : []),
|
|
980
|
+
...(historyFactSheet ? [{ type: 'text', text: historyFactSheet }] : []),
|
|
981
|
+
{ type: 'text', text: HISTORY_SYNTHETIC_OUTRO },
|
|
982
|
+
];
|
|
983
|
+
const syntheticUser = {
|
|
984
|
+
role: 'user',
|
|
985
|
+
content: syntheticContent,
|
|
986
|
+
};
|
|
987
|
+
// Demote stale request text in the protected head so the session's opening turn
|
|
988
|
+
// can't surface as clean native text ahead of the history image and read as live.
|
|
989
|
+
const head = demoteProtectedHeadText(messages.slice(0, protectedPrefix));
|
|
990
|
+
const tail = messages.slice(collapseLen);
|
|
991
|
+
info.collapsedTurns = collapseLen - protectedPrefix;
|
|
992
|
+
info.collapsedChars = text.length;
|
|
993
|
+
info.collapsedImages = imageCount;
|
|
994
|
+
if (stepFreezeStep !== undefined)
|
|
995
|
+
info.freezeStep = stepFreezeStep;
|
|
996
|
+
if (trimmed)
|
|
997
|
+
info.budgetTrimmed = true;
|
|
998
|
+
if (carryOverOrdinal >= 0)
|
|
999
|
+
info.carryOverImageOrdinal = carryOverOrdinal;
|
|
1000
|
+
// [slab, history image, live tail] — slab cache_control anchor stays at the front.
|
|
1001
|
+
return { messages: [...head, syntheticUser, ...tail], info };
|
|
1002
|
+
}
|
|
1003
|
+
//# sourceMappingURL=history.js.map
|