@sriinnu/fiche 0.18.0-bootstrap.0 → 0.19.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +134 -0
- package/LICENSE +22 -0
- package/NOTICE +13 -0
- package/PRIVACY.md +41 -0
- package/README.md +289 -0
- 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 +115 -3
- 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,3153 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Request-body transformer. Extracts the static system prompt + tool definitions,
|
|
3
|
+
* renders them as PNG image blocks, and rewrites the body to reference those images —
|
|
4
|
+
* saving 65-73% input tokens while preserving reasoning quality.
|
|
5
|
+
*/
|
|
6
|
+
import { renderTextToPngs, reflow, shrinkColsToContent, MAX_HEIGHT_PX, NL_SENTINEL, NL_SENTINEL_PAD_CELLS, neutralizeSentinel, PAD_X, PAD_Y, CELL_W, CELL_H, READABLE_CHARS_PER_IMAGE, DENSE_CONTENT_CHARS_PER_IMAGE, DENSE_CONTENT_COLS, DENSE_RENDER_STYLE, ANTHROPIC_SLAB_COLS, renderTextToPngsWithCharLimit, renderCellHeight, renderCellWidth, LINES_PER_IMAGE, maxCharsPerImage, countVisualRows, estimateImageCount, } from './render.js';
|
|
7
|
+
import { appendPinBlock, canAppendPinBlock, foldPins, stripPinCommands, stripPinCommandsFromSystem, } from './pin.js';
|
|
8
|
+
import { factSheetText } from './factsheet.js';
|
|
9
|
+
import { extractFaultSignalSnippet } from './context-mmu.js';
|
|
10
|
+
import { stripSchemaDescriptions, schemaHasStructure } from './schema-strip.js';
|
|
11
|
+
import { bytesToBase64 } from './png.js';
|
|
12
|
+
import { collapseHistory, HISTORY_DEFAULTS, HISTORY_SYNTHETIC_INTRO, ANTHROPIC_MAX_IMAGES, ANTHROPIC_HISTORY_IMAGE_BUDGET, } from './history.js';
|
|
13
|
+
import { getPinnedOpticalHistoryPolicy, hasStage2SealKey, noteHistoryRequest, recordFreezeStep, recordStage2SealKey, sessionAnchorText, setPinnedOpticalHistoryPolicy, } from './session-state.js';
|
|
14
|
+
import { readBrandEnv } from './env.js';
|
|
15
|
+
import { ANTHROPIC_GATE_RATES, evaluateCliffAvoidance, gateRatesFor, priceMode, resolvePriceRates, } from './pricing.js';
|
|
16
|
+
import { applyAnthropicTextHygiene, coveringBreakpointInfo, estimateMessageTokens, isTextHygieneActive, markerTtlSeconds, resolveTextHygieneMode, } from './text-hygiene.js';
|
|
17
|
+
import { tapeHash64Hex } from './prefix-tape.js';
|
|
18
|
+
/** Gate rates for one request, priced once: the cache TTL its markers ask for
|
|
19
|
+
* and its size as it arrived. Keyed by the parsed request, so every gate in
|
|
20
|
+
* one transform uses the same rates. */
|
|
21
|
+
const REQUEST_GATE_RATES = new WeakMap();
|
|
22
|
+
/** Longest cache TTL the request's cache_control markers ask for, in seconds.
|
|
23
|
+
* Anthropic: `ttl: "1h"` = 3600, otherwise the 5-minute default. */
|
|
24
|
+
export function requestCacheTtlSec(req) {
|
|
25
|
+
let ttl = 300;
|
|
26
|
+
const visit = (v, depth) => {
|
|
27
|
+
if (depth > 8 || !v || typeof v !== 'object')
|
|
28
|
+
return;
|
|
29
|
+
if (Array.isArray(v)) {
|
|
30
|
+
for (const x of v)
|
|
31
|
+
visit(x, depth + 1);
|
|
32
|
+
return;
|
|
33
|
+
}
|
|
34
|
+
const o = v;
|
|
35
|
+
const cc = o.cache_control;
|
|
36
|
+
if (cc && typeof cc === 'object' && cc.ttl === '1h')
|
|
37
|
+
ttl = 3600;
|
|
38
|
+
for (const k of ['system', 'tools', 'messages', 'content'])
|
|
39
|
+
if (k in o)
|
|
40
|
+
visit(o[k], depth + 1);
|
|
41
|
+
};
|
|
42
|
+
visit(req, 0);
|
|
43
|
+
return ttl;
|
|
44
|
+
}
|
|
45
|
+
function seedGateRates(req, model, bodyBytes, charsPerToken) {
|
|
46
|
+
// Legacy prices every request alike; skip the walk over the body.
|
|
47
|
+
if (priceMode() === 'legacy') {
|
|
48
|
+
REQUEST_GATE_RATES.set(req, ANTHROPIC_GATE_RATES);
|
|
49
|
+
return;
|
|
50
|
+
}
|
|
51
|
+
REQUEST_GATE_RATES.set(req, gateRatesFor(model, {
|
|
52
|
+
ttlSec: requestCacheTtlSec(req),
|
|
53
|
+
promptTokens: Math.ceil(bodyBytes / Math.max(1, charsPerToken)),
|
|
54
|
+
}));
|
|
55
|
+
}
|
|
56
|
+
function gateRates(req, model) {
|
|
57
|
+
return REQUEST_GATE_RATES.has(req) ? REQUEST_GATE_RATES.get(req) : gateRatesFor(model);
|
|
58
|
+
}
|
|
59
|
+
import { visionTokens } from './vision-cost.js';
|
|
60
|
+
import { CLAUDE_PROFILE } from './claude-model-profiles.js';
|
|
61
|
+
import { resolveGptProfile } from './gpt-model-profiles.js';
|
|
62
|
+
const DEFAULTS = {
|
|
63
|
+
compress: true,
|
|
64
|
+
imageCompress: true,
|
|
65
|
+
opticalMode: 'auto',
|
|
66
|
+
textHygiene: 'auto',
|
|
67
|
+
expectedOutputTokens: 1000,
|
|
68
|
+
compressTools: true,
|
|
69
|
+
compressToolResults: true,
|
|
70
|
+
minCompressChars: 2000,
|
|
71
|
+
minToolResultChars: 6000,
|
|
72
|
+
// system field rejects images (400 system.N.type: Input should be 'text') —
|
|
73
|
+
// images always go into the first user message.
|
|
74
|
+
// 312 cols × 5 px + 8 px pad = 1568 px (Anthropic no-resize edge).
|
|
75
|
+
cols: ANTHROPIC_SLAB_COLS,
|
|
76
|
+
maxImagesPerToolResult: 10,
|
|
77
|
+
// Deliberately under the ~20 MiB cliff observed in production rather than at
|
|
78
|
+
// it: the measured threshold is empirical and varies by route and provider.
|
|
79
|
+
maxImageBytes: 18 * 1024 * 1024,
|
|
80
|
+
charsPerToken: 4,
|
|
81
|
+
historyAmortizationHorizon: 1,
|
|
82
|
+
priorWarmTokens: 0,
|
|
83
|
+
priorWarmImageTokens: 0,
|
|
84
|
+
reflow: true,
|
|
85
|
+
keepSharp: () => false,
|
|
86
|
+
emitRecoverable: false,
|
|
87
|
+
// GPT-only knobs; the Anthropic transform ignores them but Required<> needs them.
|
|
88
|
+
collapseHistory: true,
|
|
89
|
+
gptHistory: {},
|
|
90
|
+
model: '',
|
|
91
|
+
explicitPromptCacheBreakpoints: true,
|
|
92
|
+
stageToggles: {},
|
|
93
|
+
cleanUserPayloads: false,
|
|
94
|
+
separateAdjacentToolPairs: false,
|
|
95
|
+
clientSessionId: '',
|
|
96
|
+
clientSessionSource: 'fiche-header',
|
|
97
|
+
claudeCodeSessionId: '',
|
|
98
|
+
};
|
|
99
|
+
/**
|
|
100
|
+
* Subscription OAuth requests are classified as first-party traffic only when
|
|
101
|
+
* one of these exact identities remains the first, separate top-level system
|
|
102
|
+
* block. Never render one into an image or concatenate other text into its
|
|
103
|
+
* block: the endpoint answers an unclassified request with an opaque
|
|
104
|
+
* `429 rate_limit_error: "Error"` even when the account has quota left (#149).
|
|
105
|
+
*
|
|
106
|
+
* Which identity ships depends on the entrypoint, not the product. Claude Code
|
|
107
|
+
* 2.1.220 picks one of three:
|
|
108
|
+
*
|
|
109
|
+
* if (vertex) return CLI;
|
|
110
|
+
* if (nonInteractive) return appendSystemPrompt ? CLI_WITHIN_SDK : AGENT_SDK;
|
|
111
|
+
* return CLI;
|
|
112
|
+
*
|
|
113
|
+
* so the terminal sends the CLI line, `claude -p` / the VS Code extension /
|
|
114
|
+
* Claude Desktop's `stream-json` mode send the Agent SDK line, and adding
|
|
115
|
+
* `--append-system-prompt` to any of those switches to the CLI-within-SDK line.
|
|
116
|
+
*/
|
|
117
|
+
export const CLAUDE_CODE_OAUTH_IDENTITY = "You are Claude Code, Anthropic's official CLI for Claude.";
|
|
118
|
+
export const CLAUDE_CODE_WITHIN_SDK_OAUTH_IDENTITY = "You are Claude Code, Anthropic's official CLI for Claude, running within the Claude Agent SDK.";
|
|
119
|
+
export const CLAUDE_AGENT_SDK_OAUTH_IDENTITY = "You are a Claude agent, built on Anthropic's Claude Agent SDK.";
|
|
120
|
+
/** Longest first: CLAUDE_CODE_OAUTH_IDENTITY is a prefix of the within-SDK line,
|
|
121
|
+
* so a shorter-first `startsWith` scan would match it and emit a truncated
|
|
122
|
+
* identity, leaving `, running within the Claude Agent SDK.` to be imaged. */
|
|
123
|
+
const OAUTH_IDENTITIES = [
|
|
124
|
+
CLAUDE_CODE_OAUTH_IDENTITY,
|
|
125
|
+
CLAUDE_CODE_WITHIN_SDK_OAUTH_IDENTITY,
|
|
126
|
+
CLAUDE_AGENT_SDK_OAUTH_IDENTITY,
|
|
127
|
+
].sort((a, b) => b.length - a.length);
|
|
128
|
+
// --- per-block break-even check ---
|
|
129
|
+
//
|
|
130
|
+
// Image token cost is the serving model's DOCUMENTED per-image price, taken
|
|
131
|
+
// from its profile via `visionTokens` (src/core/vision-cost.ts) — never a
|
|
132
|
+
// hardcoded provider formula. Constants bias CONSERVATIVE: CHARS_PER_TOKEN
|
|
133
|
+
// sits above the measured density, under-estimating text savings; the gate
|
|
134
|
+
// multiplies the image cost by
|
|
135
|
+
// GATE_MARGIN on top. Mispredictions leave money on the table; they never
|
|
136
|
+
// generate net-loss images.
|
|
137
|
+
/** Chars-per-token for reminder/tool_result gate buckets. Was 4 (English prose
|
|
138
|
+
* average); a 77k-request fit over production events.jsonl (2026-08, joint
|
|
139
|
+
* text+pixel OLS via `fitCpt` in src/core/cpt-fit.ts) measured ~2.3 for the mixed
|
|
140
|
+
* JSON/log content that actually hits this gate. 3 keeps a conservative margin
|
|
141
|
+
* above the measurement while halving the prior under-pricing of text cost. */
|
|
142
|
+
const CHARS_PER_TOKEN = 3;
|
|
143
|
+
/** Empirical cpt for the system-slab path (Opus 4.7 tokenizer, N=391, observed 1.91).
|
|
144
|
+
* Slab-specific because reminders/tool_results have unknown shape; those use CHARS_PER_TOKEN. */
|
|
145
|
+
export const SLAB_CHARS_PER_TOKEN = 2.0;
|
|
146
|
+
// Tools whose stub description keeps a live-text read-before-edit precondition
|
|
147
|
+
// when full docs move into the imaged Tool Reference (read-gate audit, 2026-07-03).
|
|
148
|
+
const READ_FIRST_TOOLS = new Set(['Edit', 'Write', 'NotebookEdit']);
|
|
149
|
+
/** Empirical cpt for the history-collapse path (same Opus 4.7 telemetry as SLAB_CHARS_PER_TOKEN).
|
|
150
|
+
* History is even denser (tool_use JSON dominates), so 2.0 is doubly conservative. */
|
|
151
|
+
export const HISTORY_CHARS_PER_TOKEN = 2.0;
|
|
152
|
+
/** Chars-per-token for the `inkling export` *reporting* estimate (factsheet & savings %).
|
|
153
|
+
* Less conservative than the gate's CHARS_PER_TOKEN=4: reporting wants an accurate
|
|
154
|
+
* figure (~3.7 for source/prose text), not a safe-side under-estimate. Single source
|
|
155
|
+
* of truth — src/core/export.ts imports this rather than redefining it. */
|
|
156
|
+
export const REPORT_CHARS_PER_TOKEN = 3.7;
|
|
157
|
+
/** Gate-only conservatism: a 10% upward bias on the estimated image cost,
|
|
158
|
+
* keeping the gate on the safe (pass-through) side near break-even. This is NOT
|
|
159
|
+
* part of any provider's documented cost — those live in `visionTokens`
|
|
160
|
+
* (vision-cost.ts); this margin only tunes the gate, and it is deliberately the
|
|
161
|
+
* same margin for every model family on this path. The OpenAI/Responses gate
|
|
162
|
+
* deliberately applies NO margin: it reproduces the renderer's exact page split
|
|
163
|
+
* and compares against an exact o200k baseline, so it has no estimation error
|
|
164
|
+
* to absorb (see `evalOpenAIGate`). */
|
|
165
|
+
export const GATE_MARGIN = 1.10;
|
|
166
|
+
/** Width in px of a single-col PNG. Must stay in sync with `renderChunkToPng` (render.ts). */
|
|
167
|
+
function singleColWidthPx(cols, style) {
|
|
168
|
+
return 2 * PAD_X + cols * renderCellWidth(style);
|
|
169
|
+
}
|
|
170
|
+
/** Exact image-token cost for `visualRows` at the production geometry.
|
|
171
|
+
* Mirrors the renderer's height math so the gate matches Anthropic billing.
|
|
172
|
+
* Last image is partial-height; each image cost ∝ pixel area. */
|
|
173
|
+
function imageTokensForRows(visualRows, cols, imageCountCap, maxCharsPerImage = READABLE_CHARS_PER_IMAGE, geometry = {
|
|
174
|
+
cols: DENSE_CONTENT_COLS,
|
|
175
|
+
maxHeightPx: MAX_HEIGHT_PX,
|
|
176
|
+
maxChars: DENSE_CONTENT_CHARS_PER_IMAGE,
|
|
177
|
+
style: DENSE_RENDER_STYLE,
|
|
178
|
+
pricing: CLAUDE_PROFILE,
|
|
179
|
+
}) {
|
|
180
|
+
if (!Number.isFinite(visualRows) || visualRows <= 0)
|
|
181
|
+
return 0;
|
|
182
|
+
const widthPx = singleColWidthPx(cols, geometry.style);
|
|
183
|
+
const cellH = renderCellHeight(geometry.style);
|
|
184
|
+
const hardLinesPerImg = Math.max(1, Math.floor((geometry.maxHeightPx - 2 * PAD_Y) / cellH));
|
|
185
|
+
const readableLinesPerCol = Math.max(1, Math.floor(maxCharsPerImage / Math.max(1, cols)));
|
|
186
|
+
const linesPerImg = Math.min(hardLinesPerImg, readableLinesPerCol);
|
|
187
|
+
const rowsPerImage = linesPerImg; // pixel rows per image (height)
|
|
188
|
+
const linesPerImage = linesPerImg;
|
|
189
|
+
let imagesNeeded = Math.ceil(visualRows / linesPerImage);
|
|
190
|
+
if (imageCountCap !== undefined && imageCountCap > 0) {
|
|
191
|
+
imagesNeeded = Math.min(imagesNeeded, imageCountCap);
|
|
192
|
+
}
|
|
193
|
+
const fullImages = Math.max(0, imagesNeeded - 1);
|
|
194
|
+
const linesInLast = visualRows - fullImages * linesPerImage;
|
|
195
|
+
const rowsInLast = Math.min(Math.max(1, linesInLast), rowsPerImage);
|
|
196
|
+
const fullImageHeight = 2 * PAD_Y + rowsPerImage * cellH;
|
|
197
|
+
const lastImageHeight = 2 * PAD_Y + rowsInLast * cellH;
|
|
198
|
+
// Providers bill per IMAGE (patch grid, tile grid, or flat), not by summed
|
|
199
|
+
// pixel area, so price each page separately and sum.
|
|
200
|
+
const imageSum = fullImages * visionTokens(geometry.pricing, widthPx, fullImageHeight)
|
|
201
|
+
+ visionTokens(geometry.pricing, widthPx, lastImageHeight);
|
|
202
|
+
return Math.ceil(imageSum * GATE_MARGIN);
|
|
203
|
+
}
|
|
204
|
+
/** Exact image-token cost for `text`. Uses `countVisualRows` and optionally
|
|
205
|
+
* `shrinkColsToContent` (default true) so narrow blocks aren't priced at full
|
|
206
|
+
* canvas width. Pass `shrinkWidth=false` for the system slab (fills full `cols`). */
|
|
207
|
+
function imageTokensCost(text, cols, imageCountCap, shrinkWidth = true, maxCharsPerImage = READABLE_CHARS_PER_IMAGE, geometry) {
|
|
208
|
+
const effectiveCols = shrinkWidth ? shrinkColsToContent(text, cols, 1, geometry?.style.font) : cols;
|
|
209
|
+
const rows = countVisualRows(text, effectiveCols);
|
|
210
|
+
return imageTokensForRows(rows, effectiveCols, imageCountCap, maxCharsPerImage, geometry);
|
|
211
|
+
}
|
|
212
|
+
/** Gate geometry for collapsed history.
|
|
213
|
+
*
|
|
214
|
+
* Identical to {@link denseGateGeometry} unless the model profile sets
|
|
215
|
+
* `historyStripCols` / `historyStyle`, which let a deployment render history
|
|
216
|
+
* at a lower density than the slab without touching either default. Both are
|
|
217
|
+
* undefined in every shipped profile, so this returns the dense geometry
|
|
218
|
+
* unchanged out of the box. */
|
|
219
|
+
function historyGateGeometry(o, callerOverrodeCols = false) {
|
|
220
|
+
const dense = denseGateGeometry(o);
|
|
221
|
+
const profile = o?.model ? resolveGptProfile(o.model) : undefined;
|
|
222
|
+
if (profile?.historyStripCols === undefined && profile?.historyStyle === undefined)
|
|
223
|
+
return dense;
|
|
224
|
+
return {
|
|
225
|
+
...dense,
|
|
226
|
+
cols: callerOverrodeCols ? o.cols : profile.historyStripCols ?? dense.cols,
|
|
227
|
+
style: profile.historyStyle ?? dense.style,
|
|
228
|
+
};
|
|
229
|
+
}
|
|
230
|
+
/** Gate geometry for dense tool-result, reminder, and history pages. */
|
|
231
|
+
function denseGateGeometry(o) {
|
|
232
|
+
const profile = o?.model ? resolveGptProfile(o.model) : undefined;
|
|
233
|
+
const cols = o?.cols ?? profile?.stripCols ?? DENSE_CONTENT_COLS;
|
|
234
|
+
return {
|
|
235
|
+
cols,
|
|
236
|
+
maxHeightPx: profile?.maxHeightPx ?? MAX_HEIGHT_PX,
|
|
237
|
+
// Price a page at the width we actually render at, NOT at the 312-col constant.
|
|
238
|
+
// These are the same number in the default Anthropic geometry, but a narrower
|
|
239
|
+
// COLS (env override, GPT strip profile) holds proportionally fewer chars: the
|
|
240
|
+
// old constant overstated capacity up to 3.1× at COLS=100, so the history image
|
|
241
|
+
// budget cleared a plan that then emitted 3× the images and the oversized
|
|
242
|
+
// request came back 500. Capacity must track cols or the budget is fiction.
|
|
243
|
+
maxChars: maxCharsPerImage(cols),
|
|
244
|
+
style: profile?.style ?? DENSE_RENDER_STYLE,
|
|
245
|
+
// No model on the request (Anthropic slab path): price at the Claude
|
|
246
|
+
// profile, which is what is actually serving it.
|
|
247
|
+
pricing: profile ?? CLAUDE_PROFILE,
|
|
248
|
+
};
|
|
249
|
+
}
|
|
250
|
+
/** Re-exported from render.ts, which owns the cell geometry these derive from.
|
|
251
|
+
* Kept exported here because the eval harnesses and gpt paths import them from
|
|
252
|
+
* transform. Single implementation, so the page-capacity math can't fork. */
|
|
253
|
+
export { LINES_PER_IMAGE, maxCharsPerImage, countVisualRows, estimateImageCount };
|
|
254
|
+
/** Lossless pre-render whitespace compactor (each `\n` costs ≥1 visual row):
|
|
255
|
+
* 1. Strip trailing whitespace per line (preserves leading indent).
|
|
256
|
+
* 2. Collapse 3+ consecutive newlines to 2. Typically saves 10-25% rows on
|
|
257
|
+
* markdown/tool-doc slabs, enough to flip borderline gates to profitable. */
|
|
258
|
+
export function compactSlabWhitespace(text) {
|
|
259
|
+
if (!text)
|
|
260
|
+
return text;
|
|
261
|
+
// Single-pass trailing whitespace strip (avoids materializing a split array on ~160 KB slabs).
|
|
262
|
+
let trimmed = '';
|
|
263
|
+
let lineStart = 0;
|
|
264
|
+
for (let i = 0; i <= text.length; i++) {
|
|
265
|
+
if (i === text.length || text.charCodeAt(i) === 10 /* \n */) {
|
|
266
|
+
let end = i;
|
|
267
|
+
while (end > lineStart) {
|
|
268
|
+
const c = text.charCodeAt(end - 1);
|
|
269
|
+
if (c !== 32 && c !== 9)
|
|
270
|
+
break;
|
|
271
|
+
end--;
|
|
272
|
+
}
|
|
273
|
+
trimmed += text.slice(lineStart, end);
|
|
274
|
+
if (i < text.length)
|
|
275
|
+
trimmed += '\n';
|
|
276
|
+
lineStart = i + 1;
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
// Collapse 3+ newlines → 2 (kills multi-blank dividers; each costs a render row).
|
|
280
|
+
return trimmed.replace(/\n{3,}/g, '\n\n');
|
|
281
|
+
}
|
|
282
|
+
/** Apply R3 reflow when enabled. Run after `compactSlabWhitespace`, before
|
|
283
|
+
* the gate (gate/renderer/paging all see the same dense text). Falls back to
|
|
284
|
+
* input unchanged on sentinel collision. */
|
|
285
|
+
function maybeReflow(text, enabled) {
|
|
286
|
+
if (!enabled)
|
|
287
|
+
return text;
|
|
288
|
+
// Neutralize any pre-existing ↵ so reflow packs newlines instead of bailing to a raw,
|
|
289
|
+
// unpacked render (the tool_result "newlines not converted to ↵" case — common when the
|
|
290
|
+
// content is about inkling itself). Render-only; originals are preserved via
|
|
291
|
+
// recordRecoverable(innerRaw), so this substitution never reaches recovery.
|
|
292
|
+
const safe = neutralizeSentinel(text);
|
|
293
|
+
return reflow(safe) ?? safe;
|
|
294
|
+
}
|
|
295
|
+
/** Decompose the break-even gate into components for telemetry. Returns the
|
|
296
|
+
* imageTokens, textTokens, and symmetric burn terms the gate uses internally,
|
|
297
|
+
* or `null` for empty/non-finite input. */
|
|
298
|
+
export function evalCompressionProfitability(text, cols, imageCountCap = undefined, charsPerToken = CHARS_PER_TOKEN, priorWarmTokens = 0, priorWarmImageTokens = 0, shrinkWidth = true, geometry, rates = ANTHROPIC_GATE_RATES) {
|
|
299
|
+
if (typeof text !== 'string' || text.length === 0)
|
|
300
|
+
return null;
|
|
301
|
+
// Unpriced model (kosha mode): no ratios to weigh, so no decision to report.
|
|
302
|
+
if (rates === null)
|
|
303
|
+
return null;
|
|
304
|
+
const cpt = Number.isFinite(charsPerToken) && charsPerToken > 0
|
|
305
|
+
? charsPerToken
|
|
306
|
+
: CHARS_PER_TOKEN;
|
|
307
|
+
const imageTokens = imageTokensCost(text, cols, imageCountCap, shrinkWidth, READABLE_CHARS_PER_IMAGE, geometry);
|
|
308
|
+
const textTokens = text.length / cpt;
|
|
309
|
+
const burnImageSide = Number.isFinite(priorWarmTokens) && priorWarmTokens > 0
|
|
310
|
+
? priorWarmTokens * (rates.write - rates.read)
|
|
311
|
+
: 0;
|
|
312
|
+
const burnTextSide = Number.isFinite(priorWarmImageTokens) && priorWarmImageTokens > 0
|
|
313
|
+
? priorWarmImageTokens * (rates.write - rates.read)
|
|
314
|
+
: 0;
|
|
315
|
+
return {
|
|
316
|
+
imageTokens,
|
|
317
|
+
textTokens,
|
|
318
|
+
burnImageSide,
|
|
319
|
+
burnTextSide,
|
|
320
|
+
profitable: imageTokens + burnImageSide < textTokens + burnTextSide,
|
|
321
|
+
};
|
|
322
|
+
}
|
|
323
|
+
export function isCompressionProfitable(text, cols = DEFAULTS.cols, imageCountCap, charsPerToken = CHARS_PER_TOKEN, priorWarmTokens = 0, priorWarmImageTokens = 0, shrinkWidth = true, maxCharsPerImage = READABLE_CHARS_PER_IMAGE, geometry, rates = ANTHROPIC_GATE_RATES) {
|
|
324
|
+
if (typeof text !== 'string' || text.length === 0)
|
|
325
|
+
return false;
|
|
326
|
+
// Unpriced model (kosha mode): pass the text through untouched.
|
|
327
|
+
if (rates === null)
|
|
328
|
+
return false;
|
|
329
|
+
const cpt = Number.isFinite(charsPerToken) && charsPerToken > 0
|
|
330
|
+
? charsPerToken
|
|
331
|
+
: CHARS_PER_TOKEN;
|
|
332
|
+
const imageTokensCost_ = imageTokensCost(text, cols, imageCountCap, shrinkWidth, maxCharsPerImage, geometry);
|
|
333
|
+
const textTokensEquivalent = text.length / cpt;
|
|
334
|
+
// Symmetric burn penalty (anti-flapping): switching modes invalidates the warm
|
|
335
|
+
// cache on whichever side was warm, paying cache_create. Burn is added to the
|
|
336
|
+
// side that would flip — pinning the session in its current mode until
|
|
337
|
+
// per-turn savings exceed the burn cost.
|
|
338
|
+
const burnImageSide = Number.isFinite(priorWarmTokens) && priorWarmTokens > 0
|
|
339
|
+
? priorWarmTokens * (rates.write - rates.read)
|
|
340
|
+
: 0;
|
|
341
|
+
const burnTextSide = Number.isFinite(priorWarmImageTokens) && priorWarmImageTokens > 0
|
|
342
|
+
? priorWarmImageTokens * (rates.write - rates.read)
|
|
343
|
+
: 0;
|
|
344
|
+
return imageTokensCost_ + burnImageSide < textTokensEquivalent + burnTextSide;
|
|
345
|
+
}
|
|
346
|
+
/**
|
|
347
|
+
* Horizon-aware variant of `isCompressionProfitable` for history-collapse.
|
|
348
|
+
*
|
|
349
|
+
* Evaluates expected lifetime cost over N turns: worst-case-warm for image
|
|
350
|
+
* (cache_create turn 1, cache_read turns 2..N) vs best-case-warm for text
|
|
351
|
+
* (cache_read all N). Gate condition: I×(CC + CR×(N-1)) < T×CR×N.
|
|
352
|
+
* Examples: N=5 → I < 0.30×T; N=10 → I < 0.47×T.
|
|
353
|
+
* Falls back to cold per-turn gate when `horizon <= 1`. See docs/HISTORY_CACHE_MODEL.md.
|
|
354
|
+
*/
|
|
355
|
+
export function isCompressionProfitableAmortized(text, cols, imageCountCap, charsPerToken, horizon, priorWarmTokens = 0, priorWarmImageTokens = 0, shrinkWidth = true, maxCharsPerImage = READABLE_CHARS_PER_IMAGE, geometry, rates = ANTHROPIC_GATE_RATES) {
|
|
356
|
+
if (!Number.isFinite(horizon) || horizon <= 1) {
|
|
357
|
+
return isCompressionProfitable(text, cols, imageCountCap, charsPerToken, priorWarmTokens, priorWarmImageTokens, shrinkWidth, maxCharsPerImage, geometry, rates);
|
|
358
|
+
}
|
|
359
|
+
const N = Math.max(2, Math.floor(horizon));
|
|
360
|
+
if (typeof text !== 'string' || text.length === 0)
|
|
361
|
+
return false;
|
|
362
|
+
if (rates === null)
|
|
363
|
+
return false;
|
|
364
|
+
const cpt = Number.isFinite(charsPerToken) && charsPerToken > 0
|
|
365
|
+
? charsPerToken
|
|
366
|
+
: CHARS_PER_TOKEN;
|
|
367
|
+
const imageTokens = imageTokensCost(text, cols, imageCountCap, shrinkWidth, maxCharsPerImage, geometry);
|
|
368
|
+
const textTokens = text.length / cpt;
|
|
369
|
+
// Worst-case-for-image vs best-case-for-text (conservative, on purpose).
|
|
370
|
+
const imageLifetime = imageTokens * (rates.write + rates.read * (N - 1));
|
|
371
|
+
const textLifetime = textTokens * rates.read * N;
|
|
372
|
+
// Symmetric burn — see isCompressionProfitable for anti-flapping rationale.
|
|
373
|
+
const burnImageSide = Number.isFinite(priorWarmTokens) && priorWarmTokens > 0
|
|
374
|
+
? priorWarmTokens * (rates.write - rates.read)
|
|
375
|
+
: 0;
|
|
376
|
+
const burnTextSide = Number.isFinite(priorWarmImageTokens) && priorWarmImageTokens > 0
|
|
377
|
+
? priorWarmImageTokens * (rates.write - rates.read)
|
|
378
|
+
: 0;
|
|
379
|
+
return imageLifetime + burnImageSide < textLifetime + burnTextSide;
|
|
380
|
+
}
|
|
381
|
+
/** Increment a passthrough-reason counter on `info`. Lazily allocates `passthroughReasons`. */
|
|
382
|
+
function bumpPassthrough(info, reason) {
|
|
383
|
+
if (!info.passthroughReasons)
|
|
384
|
+
info.passthroughReasons = {};
|
|
385
|
+
info.passthroughReasons[reason] = (info.passthroughReasons[reason] ?? 0) + 1;
|
|
386
|
+
}
|
|
387
|
+
/** Invoke `keepSharp` defensively; a throw or non-`true` return means "image as usual". */
|
|
388
|
+
function callerKeepsSharp(fn, block) {
|
|
389
|
+
if (typeof fn !== 'function')
|
|
390
|
+
return false;
|
|
391
|
+
try {
|
|
392
|
+
return fn(block) === true;
|
|
393
|
+
}
|
|
394
|
+
catch {
|
|
395
|
+
return false;
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
/** Attribute `chars` to a compression bucket (called whether gate accepted or rejected). */
|
|
399
|
+
function bumpBucket(info, bucket, chars) {
|
|
400
|
+
if (chars <= 0)
|
|
401
|
+
return;
|
|
402
|
+
if (!info.bucketChars)
|
|
403
|
+
info.bucketChars = {};
|
|
404
|
+
info.bucketChars[bucket] = (info.bucketChars[bucket] ?? 0) + chars;
|
|
405
|
+
}
|
|
406
|
+
/** Map `classifyContent` shape to a tool_result bucket name. */
|
|
407
|
+
function toolResultBucket(shape) {
|
|
408
|
+
if (shape === 'structured')
|
|
409
|
+
return 'tool_result_json';
|
|
410
|
+
if (shape === 'log')
|
|
411
|
+
return 'tool_result_log';
|
|
412
|
+
return 'tool_result_prose';
|
|
413
|
+
}
|
|
414
|
+
// --- helpers ---------------------------------------------------------------
|
|
415
|
+
/** Extract (text, remainder) from a system field that may be string or block list. */
|
|
416
|
+
function extractSystemText(sys) {
|
|
417
|
+
if (sys == null)
|
|
418
|
+
return { text: '', kept: [] };
|
|
419
|
+
if (typeof sys === 'string')
|
|
420
|
+
return { text: sys, kept: '' };
|
|
421
|
+
const hasCacheControlledText = sys.some((block) => block && block.type === 'text' && block.cache_control !== undefined);
|
|
422
|
+
const textParts = [];
|
|
423
|
+
const kept = [];
|
|
424
|
+
for (const block of sys) {
|
|
425
|
+
if (block && typeof block === 'object' && block.type === 'text') {
|
|
426
|
+
if (!hasCacheControlledText || block.cache_control !== undefined) {
|
|
427
|
+
textParts.push(block.text);
|
|
428
|
+
}
|
|
429
|
+
else {
|
|
430
|
+
kept.push(block);
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
else {
|
|
434
|
+
kept.push(block);
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
return { text: textParts.join('\n\n'), kept };
|
|
438
|
+
}
|
|
439
|
+
/**
|
|
440
|
+
* Remove a standalone OAuth identity block from passed-through system blocks.
|
|
441
|
+
* The caller re-emits it first; see the identity note above OAUTH_IDENTITIES.
|
|
442
|
+
*/
|
|
443
|
+
function liftIdentityBlock(kept) {
|
|
444
|
+
if (!Array.isArray(kept))
|
|
445
|
+
return { kept };
|
|
446
|
+
let identity;
|
|
447
|
+
const rest = kept.filter((block) => {
|
|
448
|
+
if (identity !== undefined)
|
|
449
|
+
return true;
|
|
450
|
+
if (!block || typeof block !== 'object' || block.type !== 'text')
|
|
451
|
+
return true;
|
|
452
|
+
const match = OAUTH_IDENTITIES.find((id) => block.text.trim() === id);
|
|
453
|
+
if (match === undefined)
|
|
454
|
+
return true;
|
|
455
|
+
identity = match;
|
|
456
|
+
return false;
|
|
457
|
+
});
|
|
458
|
+
return { identity, kept: rest };
|
|
459
|
+
}
|
|
460
|
+
function lastStaticSystemCacheControl(sys) {
|
|
461
|
+
if (!Array.isArray(sys))
|
|
462
|
+
return undefined;
|
|
463
|
+
let cacheControl;
|
|
464
|
+
for (const block of sys) {
|
|
465
|
+
if (!block || block.type !== 'text' || block.cache_control === undefined)
|
|
466
|
+
continue;
|
|
467
|
+
const { body } = stripBillingLine(block.text);
|
|
468
|
+
if (splitStaticDynamic(body).staticText.length > 0) {
|
|
469
|
+
cacheControl = block.cache_control;
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
return cacheControl;
|
|
473
|
+
}
|
|
474
|
+
/**
|
|
475
|
+
* inkling relocates caller cache_control markers onto rendered image blocks.
|
|
476
|
+
* A relocated position is never a guaranteed "global prefix": pages 1..N-1 of
|
|
477
|
+
* a slab run and other inkling-injected blocks carry no marker, so a relocated
|
|
478
|
+
* `scope:"global"` violates Anthropic's "every preceding block must be
|
|
479
|
+
* globally scoped" rule and the whole request 400s (#95). Downgrade to plain
|
|
480
|
+
* ephemeral by dropping `scope` — a single trailing marker is always valid for
|
|
481
|
+
* ordinary ephemeral caching. `type`/`ttl` are preserved, and markers without
|
|
482
|
+
* `scope` pass through untouched (identity, so byte-stability is unaffected).
|
|
483
|
+
*/
|
|
484
|
+
function demoteRelocatedCacheControl(cc) {
|
|
485
|
+
if (cc && typeof cc === 'object' && 'scope' in cc) {
|
|
486
|
+
const { scope: _scope, ...rest } = cc;
|
|
487
|
+
return rest;
|
|
488
|
+
}
|
|
489
|
+
return cc;
|
|
490
|
+
}
|
|
491
|
+
// Per-turn dynamic blocks injected by Claude Code. These drift turn-to-turn and
|
|
492
|
+
// must not be baked into the cached image. Split out so only the stable static
|
|
493
|
+
// slab (CLAUDE.md + tool docs) carries cache_control.
|
|
494
|
+
const DYNAMIC_BLOCK_TAGS = [
|
|
495
|
+
'env',
|
|
496
|
+
'context',
|
|
497
|
+
'git_status',
|
|
498
|
+
'directoryStructure',
|
|
499
|
+
'system-reminder',
|
|
500
|
+
// A running per-turn counter. Left in the static slab it re-keys the slab image
|
|
501
|
+
// on every single turn, which is the worst possible cache shape: the prefix is
|
|
502
|
+
// paid for as a create and never read. It was showing up in
|
|
503
|
+
// `unknownStaticTags`, which is exactly the canary that list exists to be.
|
|
504
|
+
'total_tokens',
|
|
505
|
+
// Newer Claude Code identity/automode block (#234). Left in the static slab
|
|
506
|
+
// it gets imaged along with the rest of the prefix, and the provider's
|
|
507
|
+
// subscription-quota recognition on that block breaks -> spurious 429s on
|
|
508
|
+
// every compressed request. Route it to the dynamic tail instead, same as
|
|
509
|
+
// total_tokens above.
|
|
510
|
+
'cc_automode_session_rules',
|
|
511
|
+
'cc_automode_permissions',
|
|
512
|
+
'severity',
|
|
513
|
+
'category',
|
|
514
|
+
];
|
|
515
|
+
// Known-static slab tags — suppresses first-sighting `unknownStaticTags` noise
|
|
516
|
+
// only. Correctness doesn't depend on this list: observeStaticTagChurn catches
|
|
517
|
+
// a wrong entry on its second sighting.
|
|
518
|
+
const KNOWN_STATIC_TAGS = [
|
|
519
|
+
// Claude Code
|
|
520
|
+
'types',
|
|
521
|
+
// Nested under <available_skills> (static for a session; churn still observed)
|
|
522
|
+
'skill',
|
|
523
|
+
'name',
|
|
524
|
+
'description',
|
|
525
|
+
'location',
|
|
526
|
+
'available_references',
|
|
527
|
+
// opencode (codex system prompts have no tag-shaped blocks)
|
|
528
|
+
'example',
|
|
529
|
+
'available_skills',
|
|
530
|
+
// beast.txt + title.txt
|
|
531
|
+
'examples',
|
|
532
|
+
'rules',
|
|
533
|
+
'task',
|
|
534
|
+
// copilot-gpt-5.txt
|
|
535
|
+
'codeSearchInstructions',
|
|
536
|
+
'codeSearchToolUseInstructions',
|
|
537
|
+
'communicationGuidelines',
|
|
538
|
+
'gptAgentInstructions',
|
|
539
|
+
'outputFormatting',
|
|
540
|
+
'structuredWorkflow',
|
|
541
|
+
'toolUseInstructions',
|
|
542
|
+
];
|
|
543
|
+
/** Tag-name and whitespace classifiers matching /[a-zA-Z]/,
|
|
544
|
+
* /[a-zA-Z0-9_-]/ and /\s/. */
|
|
545
|
+
function isTagNameStart(c) {
|
|
546
|
+
return (c >= 97 && c <= 122) || (c >= 65 && c <= 90); // a-z A-Z
|
|
547
|
+
}
|
|
548
|
+
function isTagNameChar(c) {
|
|
549
|
+
return ((c >= 97 && c <= 122) || // a-z
|
|
550
|
+
(c >= 65 && c <= 90) || // A-Z
|
|
551
|
+
(c >= 48 && c <= 57) || // 0-9
|
|
552
|
+
c === 95 || // _
|
|
553
|
+
c === 45 // -
|
|
554
|
+
);
|
|
555
|
+
}
|
|
556
|
+
function isTagSpace(c) {
|
|
557
|
+
if (c === 32 || (c >= 9 && c <= 13))
|
|
558
|
+
return true; // space, \t \n \v \f \r
|
|
559
|
+
if (c < 0xa0)
|
|
560
|
+
return false;
|
|
561
|
+
return (c === 0xa0 ||
|
|
562
|
+
c === 0x1680 ||
|
|
563
|
+
(c >= 0x2000 && c <= 0x200a) ||
|
|
564
|
+
c === 0x2028 ||
|
|
565
|
+
c === 0x2029 ||
|
|
566
|
+
c === 0x202f ||
|
|
567
|
+
c === 0x205f ||
|
|
568
|
+
c === 0x3000 ||
|
|
569
|
+
c === 0xfeff);
|
|
570
|
+
}
|
|
571
|
+
export function splitStaticDynamic(text) {
|
|
572
|
+
if (!text)
|
|
573
|
+
return {
|
|
574
|
+
staticText: '',
|
|
575
|
+
dynamicText: '',
|
|
576
|
+
blockCount: 0,
|
|
577
|
+
unknownTags: [],
|
|
578
|
+
staticTagContents: new Map(),
|
|
579
|
+
};
|
|
580
|
+
const pattern = new RegExp(`<(${DYNAMIC_BLOCK_TAGS.join('|')})(\\s[^>]*)?>[\\s\\S]*?</\\1>`, 'g');
|
|
581
|
+
const dynamicParts = [];
|
|
582
|
+
let staticBuf = '';
|
|
583
|
+
let cursor = 0;
|
|
584
|
+
let m;
|
|
585
|
+
while ((m = pattern.exec(text)) !== null) {
|
|
586
|
+
staticBuf += text.slice(cursor, m.index);
|
|
587
|
+
dynamicParts.push(m[0]);
|
|
588
|
+
cursor = m.index + m[0].length;
|
|
589
|
+
}
|
|
590
|
+
staticBuf += text.slice(cursor);
|
|
591
|
+
// Sniff for unknown tag-shaped blocks in the static slab. A new per-turn
|
|
592
|
+
// Claude Code tag would silently bake into the image and collapse cache rate;
|
|
593
|
+
// surfacing the tag name lets us detect it within hours of a release.
|
|
594
|
+
const known = new Set(DYNAMIC_BLOCK_TAGS);
|
|
595
|
+
const knownStatic = new Set(KNOWN_STATIC_TAGS);
|
|
596
|
+
const unknown = new Set();
|
|
597
|
+
const staticTagContents = new Map();
|
|
598
|
+
// Scanned by index: matching this with a regex costs quadratic time on
|
|
599
|
+
// untrusted text, since both a lazy `[\s\S]*?` body and an `(?:\s[^>]*)?>`
|
|
600
|
+
// attribute run rescan the tail once per candidate tag.
|
|
601
|
+
const noCloser = new Set();
|
|
602
|
+
let i = 0;
|
|
603
|
+
while (i < staticBuf.length) {
|
|
604
|
+
const lt = staticBuf.indexOf('<', i);
|
|
605
|
+
if (lt < 0)
|
|
606
|
+
break;
|
|
607
|
+
let j = lt + 1;
|
|
608
|
+
if (!isTagNameStart(staticBuf.charCodeAt(j))) {
|
|
609
|
+
i = lt + 1;
|
|
610
|
+
continue;
|
|
611
|
+
}
|
|
612
|
+
j += 1;
|
|
613
|
+
while (j < staticBuf.length && isTagNameChar(staticBuf.charCodeAt(j)))
|
|
614
|
+
j += 1;
|
|
615
|
+
// Either `<tag>` or `<tag ...>`; anything else is not an opening tag.
|
|
616
|
+
let gt;
|
|
617
|
+
if (staticBuf[j] === '>') {
|
|
618
|
+
gt = j;
|
|
619
|
+
}
|
|
620
|
+
else if (j < staticBuf.length && isTagSpace(staticBuf.charCodeAt(j))) {
|
|
621
|
+
gt = staticBuf.indexOf('>', j);
|
|
622
|
+
// No `>` left, so no later opening can complete either.
|
|
623
|
+
if (gt < 0)
|
|
624
|
+
break;
|
|
625
|
+
}
|
|
626
|
+
else {
|
|
627
|
+
i = lt + 1;
|
|
628
|
+
continue;
|
|
629
|
+
}
|
|
630
|
+
const tag = staticBuf.slice(lt + 1, j);
|
|
631
|
+
const contentStart = gt + 1;
|
|
632
|
+
const closer = `</${tag}>`;
|
|
633
|
+
// A closer missing after one opening is missing for every later opening of
|
|
634
|
+
// the same tag, so record it and skip the repeated failed scan.
|
|
635
|
+
const end = noCloser.has(tag) ? -1 : staticBuf.indexOf(closer, contentStart);
|
|
636
|
+
if (end < 0) {
|
|
637
|
+
noCloser.add(tag);
|
|
638
|
+
i = lt + 1;
|
|
639
|
+
continue;
|
|
640
|
+
}
|
|
641
|
+
if (tag.length <= 64) {
|
|
642
|
+
if (!known.has(tag) && !knownStatic.has(tag))
|
|
643
|
+
unknown.add(tag);
|
|
644
|
+
// Fold repeated tags (e.g. several <example>s) into one fingerprint.
|
|
645
|
+
staticTagContents.set(tag, (staticTagContents.get(tag) ?? '') + staticBuf.slice(contentStart, end));
|
|
646
|
+
}
|
|
647
|
+
i = end + closer.length;
|
|
648
|
+
}
|
|
649
|
+
return {
|
|
650
|
+
// Collapse the run of blank lines left behind by removed blocks.
|
|
651
|
+
staticText: staticBuf.replace(/\n{3,}/g, '\n\n').trim(),
|
|
652
|
+
dynamicText: dynamicParts.join('\n\n'),
|
|
653
|
+
blockCount: dynamicParts.length,
|
|
654
|
+
unknownTags: [...unknown],
|
|
655
|
+
staticTagContents,
|
|
656
|
+
};
|
|
657
|
+
}
|
|
658
|
+
/** FNV-1a 32-bit — cheap synchronous content fingerprint for churn detection. */
|
|
659
|
+
function fnv1a(text) {
|
|
660
|
+
let h = 0x811c9dc5;
|
|
661
|
+
for (let i = 0; i < text.length; i++) {
|
|
662
|
+
h ^= text.charCodeAt(i);
|
|
663
|
+
h = Math.imul(h, 0x01000193);
|
|
664
|
+
}
|
|
665
|
+
return h >>> 0;
|
|
666
|
+
}
|
|
667
|
+
// Last content hash per (session, tag). Bounded LRU.
|
|
668
|
+
const TAG_OBSERVATIONS_MAX = 4096;
|
|
669
|
+
const tagObservations = new Map();
|
|
670
|
+
/** Returns slab tags whose content changed since the last sighting in the same
|
|
671
|
+
* session — proven per-turn dynamics, whatever the hardcoded lists say. */
|
|
672
|
+
function observeStaticTagChurn(sessionKey, tagContents) {
|
|
673
|
+
const churned = [];
|
|
674
|
+
for (const [tag, inner] of tagContents) {
|
|
675
|
+
const key = `${sessionKey}\0${tag}`;
|
|
676
|
+
const hash = fnv1a(inner);
|
|
677
|
+
const prev = tagObservations.get(key);
|
|
678
|
+
if (prev !== undefined) {
|
|
679
|
+
if (prev !== hash)
|
|
680
|
+
churned.push(tag);
|
|
681
|
+
tagObservations.delete(key); // refresh LRU position
|
|
682
|
+
}
|
|
683
|
+
tagObservations.set(key, hash);
|
|
684
|
+
}
|
|
685
|
+
while (tagObservations.size > TAG_OBSERVATIONS_MAX) {
|
|
686
|
+
const oldest = tagObservations.keys().next().value;
|
|
687
|
+
if (oldest === undefined)
|
|
688
|
+
break;
|
|
689
|
+
tagObservations.delete(oldest);
|
|
690
|
+
}
|
|
691
|
+
return churned;
|
|
692
|
+
}
|
|
693
|
+
/** sha256[0..8] hex via Web Crypto (works in Node 18+ and Workers). 32-bit collision-safe. */
|
|
694
|
+
export async function sha8(text) {
|
|
695
|
+
const buf = new TextEncoder().encode(text);
|
|
696
|
+
const digest = await crypto.subtle.digest('SHA-256', buf);
|
|
697
|
+
const bytes = new Uint8Array(digest);
|
|
698
|
+
let hex = '';
|
|
699
|
+
for (let i = 0; i < 4; i++)
|
|
700
|
+
hex += bytes[i].toString(16).padStart(2, '0');
|
|
701
|
+
return hex;
|
|
702
|
+
}
|
|
703
|
+
/** Record a recovery entry when `emitRecoverable` is on. No-op (no hash cost) when off. */
|
|
704
|
+
async function recordRecoverable(info, emit, entry) {
|
|
705
|
+
if (!emit)
|
|
706
|
+
return;
|
|
707
|
+
const id = 'rec_' + (await sha8(`${entry.kind}\u0000${entry.toolUseId ?? ''}\u0000${entry.text}`));
|
|
708
|
+
(info.recoverable ??= []).push({
|
|
709
|
+
id,
|
|
710
|
+
kind: entry.kind,
|
|
711
|
+
...(entry.toolUseId !== undefined ? { toolUseId: entry.toolUseId } : {}),
|
|
712
|
+
text: entry.text,
|
|
713
|
+
imageCount: entry.imageCount,
|
|
714
|
+
});
|
|
715
|
+
}
|
|
716
|
+
/** Hash the concatenated base64 of every image block on the synthetic history
|
|
717
|
+
* message. Stable across the quantized collapse window → proves Anthropic can
|
|
718
|
+
* cache_read the history prefix. Returns undefined if there is no such message.
|
|
719
|
+
*
|
|
720
|
+
* The synthetic message is NOT `messages[0]` whenever a slab anchor exists:
|
|
721
|
+
* collapseHistory returns `[...head, syntheticUser, ...tail]` and transform.ts
|
|
722
|
+
* passes `protectedPrefix = slabAnchorIdx + 1`, so on a Claude Code request
|
|
723
|
+
* `messages[0]` is the protected slab message. Hashing it reported SLAB image
|
|
724
|
+
* stability under the `history_image_sha8` name — the one field meant to prove
|
|
725
|
+
* history-image byte-identity was blind to the history images, so a drifting
|
|
726
|
+
* collapse boundary still looked stable in telemetry (#11 attribution). Locate
|
|
727
|
+
* the message by its banner instead, exactly like cachePrefixDigest does. */
|
|
728
|
+
async function historyImageSha8(messages) {
|
|
729
|
+
const synthetic = messages.find((m) => Array.isArray(m.content) &&
|
|
730
|
+
m.content[0]?.type === 'text' &&
|
|
731
|
+
m.content[0].text === HISTORY_SYNTHETIC_INTRO);
|
|
732
|
+
if (!synthetic || !Array.isArray(synthetic.content))
|
|
733
|
+
return undefined;
|
|
734
|
+
let concat = '';
|
|
735
|
+
for (const blk of synthetic.content) {
|
|
736
|
+
if (blk.type === 'image')
|
|
737
|
+
concat += blk.source.data;
|
|
738
|
+
}
|
|
739
|
+
return concat ? sha8(concat) : undefined;
|
|
740
|
+
}
|
|
741
|
+
/**
|
|
742
|
+
* After a history collapse, move inkling's single relocated cache breakpoint off
|
|
743
|
+
* the slab image and onto the LAST history image.
|
|
744
|
+
*
|
|
745
|
+
* The history image sits AFTER the slab in prefix order, so one marker on it
|
|
746
|
+
* caches the WHOLE imaged prefix (slab + history) as a single stable segment —
|
|
747
|
+
* created once, then read at the ~0.1x rate every turn. Without this the history
|
|
748
|
+
* image (usually the largest block) only lands in a cached prefix when the
|
|
749
|
+
* caller's roaming downstream marker happens to fall after it; when it doesn't,
|
|
750
|
+
* the entire history image re-creates at the 1.25x rate turn after turn.
|
|
751
|
+
*
|
|
752
|
+
* Pure relocation: it acts only when a slab image already carries the anchor, so
|
|
753
|
+
* the total marker count never increases (inkling never *adds* — only moves).
|
|
754
|
+
*/
|
|
755
|
+
function hasEarlierShorterTtlMarker(messages, targetMsgIdx, targetBlockIdx, ignoreBlock, system, tools) {
|
|
756
|
+
const is5mMarker = (cc) => Boolean(cc && typeof cc === 'object' && cc.ttl !== '1h');
|
|
757
|
+
if (Array.isArray(tools)) {
|
|
758
|
+
for (const t of tools) {
|
|
759
|
+
if (t && typeof t === 'object' && is5mMarker(t.cache_control)) {
|
|
760
|
+
return true;
|
|
761
|
+
}
|
|
762
|
+
}
|
|
763
|
+
}
|
|
764
|
+
if (Array.isArray(system)) {
|
|
765
|
+
for (const b of system) {
|
|
766
|
+
if (b && typeof b === 'object' && is5mMarker(b.cache_control)) {
|
|
767
|
+
return true;
|
|
768
|
+
}
|
|
769
|
+
}
|
|
770
|
+
}
|
|
771
|
+
for (let mIdx = 0; mIdx <= targetMsgIdx && mIdx < messages.length; mIdx++) {
|
|
772
|
+
const content = messages[mIdx]?.content;
|
|
773
|
+
if (!Array.isArray(content))
|
|
774
|
+
continue;
|
|
775
|
+
const bLimit = mIdx === targetMsgIdx ? targetBlockIdx : content.length;
|
|
776
|
+
for (let bIdx = 0; bIdx < bLimit; bIdx++) {
|
|
777
|
+
const b = content[bIdx];
|
|
778
|
+
if (!b || typeof b !== 'object' || b === ignoreBlock)
|
|
779
|
+
continue;
|
|
780
|
+
if (is5mMarker(b.cache_control))
|
|
781
|
+
return true;
|
|
782
|
+
}
|
|
783
|
+
}
|
|
784
|
+
return false;
|
|
785
|
+
}
|
|
786
|
+
function relocateAnchorToHistoryImage(messages, anchorOrdinal, system, tools) {
|
|
787
|
+
if (!Array.isArray(messages))
|
|
788
|
+
return;
|
|
789
|
+
// The synthetic history message is identified by its banner text block.
|
|
790
|
+
let historyImg;
|
|
791
|
+
let historyMsgIdx = -1;
|
|
792
|
+
let historyBlockIdx = -1;
|
|
793
|
+
for (let mIdx = 0; mIdx < messages.length; mIdx++) {
|
|
794
|
+
const m = messages[mIdx];
|
|
795
|
+
if (!Array.isArray(m.content))
|
|
796
|
+
continue;
|
|
797
|
+
const first = m.content[0];
|
|
798
|
+
if (!first || first.type !== 'text' || first.text !== HISTORY_SYNTHETIC_INTRO)
|
|
799
|
+
continue;
|
|
800
|
+
const imgsInMsg = [];
|
|
801
|
+
for (let bIdx = 0; bIdx < m.content.length; bIdx++) {
|
|
802
|
+
const b = m.content[bIdx];
|
|
803
|
+
if (b && b.type === 'image') {
|
|
804
|
+
imgsInMsg.push({ block: b, bIdx });
|
|
805
|
+
}
|
|
806
|
+
}
|
|
807
|
+
const picked = anchorOrdinal !== undefined && anchorOrdinal >= 0 && anchorOrdinal < imgsInMsg.length
|
|
808
|
+
? imgsInMsg[anchorOrdinal]
|
|
809
|
+
: imgsInMsg[imgsInMsg.length - 1];
|
|
810
|
+
if (picked) {
|
|
811
|
+
historyImg = picked.block;
|
|
812
|
+
historyMsgIdx = mIdx;
|
|
813
|
+
historyBlockIdx = picked.bIdx;
|
|
814
|
+
}
|
|
815
|
+
break;
|
|
816
|
+
}
|
|
817
|
+
if (!historyImg)
|
|
818
|
+
return;
|
|
819
|
+
// The slab anchor is the marked image BEFORE the '[End of rendered context.]'
|
|
820
|
+
// boundary in the slab-bearing message. Reminder/tool images sit after that
|
|
821
|
+
// boundary (or in other messages) and keep their own caller markers.
|
|
822
|
+
let slabAnchor;
|
|
823
|
+
for (const m of messages) {
|
|
824
|
+
if (!Array.isArray(m.content))
|
|
825
|
+
continue;
|
|
826
|
+
const hasBoundary = m.content.some((b) => b && b.type === 'text' && b.text === '[End of rendered context.]');
|
|
827
|
+
if (!hasBoundary)
|
|
828
|
+
continue;
|
|
829
|
+
for (const b of m.content) {
|
|
830
|
+
if (b && b.type === 'text' && b.text === '[End of rendered context.]')
|
|
831
|
+
break;
|
|
832
|
+
if (b && b.type === 'image' && b.cache_control !== undefined) {
|
|
833
|
+
slabAnchor = b;
|
|
834
|
+
}
|
|
835
|
+
}
|
|
836
|
+
break;
|
|
837
|
+
}
|
|
838
|
+
if (!slabAnchor)
|
|
839
|
+
return; // nothing to relocate → never add a marker
|
|
840
|
+
let relocatedCc = demoteRelocatedCacheControl(slabAnchor.cache_control);
|
|
841
|
+
if (relocatedCc &&
|
|
842
|
+
typeof relocatedCc === 'object' &&
|
|
843
|
+
relocatedCc.ttl === '1h' &&
|
|
844
|
+
hasEarlierShorterTtlMarker(messages, historyMsgIdx, historyBlockIdx, slabAnchor, system, tools)) {
|
|
845
|
+
// Anthropic requires monotonically non-increasing cache TTLs: never place 1h after an earlier 5m marker.
|
|
846
|
+
const { ttl: _ttl, ...clamped } = relocatedCc;
|
|
847
|
+
relocatedCc = clamped;
|
|
848
|
+
}
|
|
849
|
+
historyImg.cache_control = relocatedCc;
|
|
850
|
+
delete slabAnchor.cache_control;
|
|
851
|
+
}
|
|
852
|
+
/**
|
|
853
|
+
* Read-only digest of the cacheable prefix inkling actually sends: tools +
|
|
854
|
+
* system + message blocks up to and including the imaged history image (or, on
|
|
855
|
+
* no-collapse turns, the slab boundary). The naturally-growing live tail is
|
|
856
|
+
* excluded, so the digest only moves when something *inside the pinned prefix*
|
|
857
|
+
* moves. Pairs with per-turn cache_read/cache_create to attribute a prompt-cache
|
|
858
|
+
* bust: a digest that CHANGES between consecutive turns of one session means we
|
|
859
|
+
* serialized different prefix bytes (inkling-side — a per-turn block crossing the
|
|
860
|
+
* breakpoint, or marker drift); a STABLE digest on a turn that still re-created
|
|
861
|
+
* the prefix points upstream (eviction). Never mutates the request, so it cannot
|
|
862
|
+
* perturb the cache behavior it measures.
|
|
863
|
+
*/
|
|
864
|
+
async function cachePrefixDigest(req) {
|
|
865
|
+
const msgs = Array.isArray(req.messages) ? req.messages : [];
|
|
866
|
+
// Boundary = latest message carrying inkling's imaged prefix: the history image
|
|
867
|
+
// (banner) when collapse ran, else the slab message ('[End of rendered
|
|
868
|
+
// context.]'). Identified exactly as relocateAnchorToHistoryImage does.
|
|
869
|
+
let boundary = -1;
|
|
870
|
+
for (let i = 0; i < msgs.length; i++) {
|
|
871
|
+
const content = msgs[i]?.content;
|
|
872
|
+
if (!Array.isArray(content))
|
|
873
|
+
continue;
|
|
874
|
+
const first = content[0];
|
|
875
|
+
const isHistory = first?.type === 'text' && first.text === HISTORY_SYNTHETIC_INTRO;
|
|
876
|
+
const hasSlab = content.some((b) => b && b.type === 'text' && b.text === '[End of rendered context.]');
|
|
877
|
+
if (isHistory || hasSlab)
|
|
878
|
+
boundary = i;
|
|
879
|
+
}
|
|
880
|
+
if (boundary < 0)
|
|
881
|
+
return undefined; // not an imaged-prefix shape — nothing pinned
|
|
882
|
+
// Component digests, in wire order. A whole-prefix hash proves THAT the cache
|
|
883
|
+
// busted but never WHICH layer moved, and the layers fail for different
|
|
884
|
+
// reasons: tools drift when the client loads a deferred tool, system drifts
|
|
885
|
+
// when volatile text (env/git status) rides inside the pinned span, and the
|
|
886
|
+
// imaged head drifts when a collapse boundary or marker placement moves.
|
|
887
|
+
// Hashing each separately turns "prefix changed" into a one-line diagnosis.
|
|
888
|
+
const toolParts = [];
|
|
889
|
+
if (Array.isArray(req.tools))
|
|
890
|
+
for (const t of req.tools)
|
|
891
|
+
toolParts.push(JSON.stringify(t));
|
|
892
|
+
const sysParts = [];
|
|
893
|
+
const sys = req.system;
|
|
894
|
+
if (typeof sys === 'string')
|
|
895
|
+
sysParts.push(sys);
|
|
896
|
+
else if (Array.isArray(sys))
|
|
897
|
+
for (const b of sys)
|
|
898
|
+
sysParts.push(JSON.stringify(b));
|
|
899
|
+
// Memoize serialized blocks per message so shared span 0..boundary isn't stringified twice.
|
|
900
|
+
const serializedMsgs = new Map();
|
|
901
|
+
const getMsgSerialized = (idx) => {
|
|
902
|
+
const existing = serializedMsgs.get(idx);
|
|
903
|
+
if (existing !== undefined)
|
|
904
|
+
return existing;
|
|
905
|
+
const content = msgs[idx]?.content;
|
|
906
|
+
let res = [];
|
|
907
|
+
if (typeof content === 'string') {
|
|
908
|
+
res = content;
|
|
909
|
+
}
|
|
910
|
+
else if (Array.isArray(content)) {
|
|
911
|
+
res = content.map((b) => (typeof b === 'string' ? b : JSON.stringify(b)));
|
|
912
|
+
}
|
|
913
|
+
serializedMsgs.set(idx, res);
|
|
914
|
+
return res;
|
|
915
|
+
};
|
|
916
|
+
const headParts = [];
|
|
917
|
+
for (let i = 0; i <= boundary; i++) {
|
|
918
|
+
const s = getMsgSerialized(i);
|
|
919
|
+
if (typeof s === 'string')
|
|
920
|
+
headParts.push(s);
|
|
921
|
+
else
|
|
922
|
+
for (let j = 0; j < s.length; j++)
|
|
923
|
+
headParts.push(s[j]);
|
|
924
|
+
}
|
|
925
|
+
// The span Anthropic actually caches ends at the LAST cache_control marker —
|
|
926
|
+
// not at the message boundary above.
|
|
927
|
+
let markPos = '';
|
|
928
|
+
const markedParts = [...toolParts, ...sysParts];
|
|
929
|
+
const markedUpTo = [];
|
|
930
|
+
outer: for (let i = msgs.length - 1; i >= 0; i--) {
|
|
931
|
+
const content = msgs[i]?.content;
|
|
932
|
+
if (!Array.isArray(content))
|
|
933
|
+
continue;
|
|
934
|
+
for (let k = content.length - 1; k >= 0; k--) {
|
|
935
|
+
const b = content[k];
|
|
936
|
+
if (b && typeof b === 'object' && b.cache_control !== undefined) {
|
|
937
|
+
markPos = `m${i}.b${k}`;
|
|
938
|
+
for (let mi = 0; mi <= i; mi++) {
|
|
939
|
+
const s = getMsgSerialized(mi);
|
|
940
|
+
if (typeof s === 'string') {
|
|
941
|
+
markedUpTo.push(s);
|
|
942
|
+
}
|
|
943
|
+
else {
|
|
944
|
+
const lim = mi === i ? Math.min(k + 1, s.length) : s.length;
|
|
945
|
+
for (let bk = 0; bk < lim; bk++) {
|
|
946
|
+
markedUpTo.push(s[bk]);
|
|
947
|
+
}
|
|
948
|
+
}
|
|
949
|
+
}
|
|
950
|
+
break outer;
|
|
951
|
+
}
|
|
952
|
+
}
|
|
953
|
+
}
|
|
954
|
+
markedParts.push(...markedUpTo);
|
|
955
|
+
const marked = markedParts.join('\x00');
|
|
956
|
+
const parts = [...toolParts, ...sysParts, ...headParts];
|
|
957
|
+
const prefix = parts.join('\x00');
|
|
958
|
+
const [digestSha8, toolsSha8, systemSha8, headSha8, markedSha8] = await Promise.all([
|
|
959
|
+
sha8(prefix),
|
|
960
|
+
sha8(toolParts.join('\x00')),
|
|
961
|
+
sha8(sysParts.join('\x00')),
|
|
962
|
+
sha8(headParts.join('\x00')),
|
|
963
|
+
sha8(marked),
|
|
964
|
+
]);
|
|
965
|
+
return {
|
|
966
|
+
sha8: digestSha8,
|
|
967
|
+
bytes: prefix.length,
|
|
968
|
+
toolsSha8,
|
|
969
|
+
systemSha8,
|
|
970
|
+
headSha8,
|
|
971
|
+
markedSha8,
|
|
972
|
+
markedBytes: marked.length,
|
|
973
|
+
markerPos: markPos,
|
|
974
|
+
};
|
|
975
|
+
}
|
|
976
|
+
// Removed: extractClaudeMdSlab(). It scanned the static system text for
|
|
977
|
+
// "# CLAUDE.md" / "# Claude Code Rules" headings, which is both wrong and
|
|
978
|
+
// fragile — wrong because Claude Code does not put CLAUDE.md in the system
|
|
979
|
+
// field at all (it arrives in the first user message, wrapped in
|
|
980
|
+
// <system-reminder>, under a "# claudeMd" heading), and fragile because any
|
|
981
|
+
// pasted file or code comment containing that heading would have been treated
|
|
982
|
+
// as project instructions. Telemetry confirmed it: claude_md_sha8 never once
|
|
983
|
+
// appeared across the whole event log. Project instructions are now kept as
|
|
984
|
+
// text structurally — see the <system-reminder> handling below.
|
|
985
|
+
/**
|
|
986
|
+
* Session identity text: the user's first prompt, skipping harness envelopes
|
|
987
|
+
* (see {@link sessionAnchorText}). Scans every user message before the first
|
|
988
|
+
* assistant turn, because a client may send its envelope as a message of its own.
|
|
989
|
+
*/
|
|
990
|
+
export function firstUserText(req) {
|
|
991
|
+
const texts = [];
|
|
992
|
+
for (const m of req.messages ?? []) {
|
|
993
|
+
if (!m || typeof m !== 'object')
|
|
994
|
+
continue;
|
|
995
|
+
if (m.role !== 'user')
|
|
996
|
+
break;
|
|
997
|
+
if (typeof m.content === 'string') {
|
|
998
|
+
texts.push(m.content);
|
|
999
|
+
}
|
|
1000
|
+
else if (Array.isArray(m.content)) {
|
|
1001
|
+
for (const block of m.content) {
|
|
1002
|
+
if (block && typeof block === 'object' && block.type === 'text' && typeof block.text === 'string')
|
|
1003
|
+
texts.push(block.text);
|
|
1004
|
+
}
|
|
1005
|
+
}
|
|
1006
|
+
}
|
|
1007
|
+
return sessionAnchorText(texts);
|
|
1008
|
+
}
|
|
1009
|
+
/**
|
|
1010
|
+
* Resolve and record session isolation identity on `info` from explicit client
|
|
1011
|
+
* session headers (`x-fiche-session-id` -> `fs:`, `x-claude-code-session-id` -> `cc:`)
|
|
1012
|
+
* or fall back to the SHA-8 anchor of the first user turn (`anchor`).
|
|
1013
|
+
*/
|
|
1014
|
+
export async function applyClientSessionIdentity(info, firstUser, opts) {
|
|
1015
|
+
if (firstUser && !info.firstUserSha8) {
|
|
1016
|
+
info.firstUserSha8 = await sha8(firstUser);
|
|
1017
|
+
}
|
|
1018
|
+
const explicitId = opts?.clientSessionId?.trim();
|
|
1019
|
+
const resolvedId = explicitId || opts?.claudeCodeSessionId?.trim() || '';
|
|
1020
|
+
if (resolvedId) {
|
|
1021
|
+
const source = explicitId
|
|
1022
|
+
? (opts?.clientSessionSource ?? 'fiche-header')
|
|
1023
|
+
: 'claude-code-header';
|
|
1024
|
+
const prefix = source === 'fiche-header' ? 'fs:' : 'cc:';
|
|
1025
|
+
if (!info.sessionKey || info.sessionKeySource !== source) {
|
|
1026
|
+
info.sessionKey = await sha8(`${prefix}${resolvedId}`);
|
|
1027
|
+
info.sessionKeySource = source;
|
|
1028
|
+
}
|
|
1029
|
+
}
|
|
1030
|
+
else if (info.firstUserSha8 && !info.sessionKey) {
|
|
1031
|
+
info.sessionKey = info.firstUserSha8;
|
|
1032
|
+
info.sessionKeySource = 'anchor';
|
|
1033
|
+
}
|
|
1034
|
+
return info.sessionKey ?? info.firstUserSha8;
|
|
1035
|
+
}
|
|
1036
|
+
/**
|
|
1037
|
+
* True when the first message carries a `<system-reminder>` block — the
|
|
1038
|
+
* envelope Claude Code uses to inject CLAUDE.md project instructions. Such a
|
|
1039
|
+
* message must never be rendered to pixels: imaged rules read as description
|
|
1040
|
+
* rather than instruction, so the model stops obeying them mid-session.
|
|
1041
|
+
*/
|
|
1042
|
+
export function firstMessageHasSystemReminder(messages) {
|
|
1043
|
+
const first = (messages ?? [])[0];
|
|
1044
|
+
if (!first)
|
|
1045
|
+
return false;
|
|
1046
|
+
const has = (s) => typeof s === 'string' && s.includes('<system-reminder>');
|
|
1047
|
+
if (has(first.content))
|
|
1048
|
+
return true;
|
|
1049
|
+
if (Array.isArray(first.content)) {
|
|
1050
|
+
for (const block of first.content) {
|
|
1051
|
+
if (block && block.type === 'text' && has(block.text))
|
|
1052
|
+
return true;
|
|
1053
|
+
}
|
|
1054
|
+
}
|
|
1055
|
+
return false;
|
|
1056
|
+
}
|
|
1057
|
+
/** Body of the first `<tag>…</tag>` pair, or undefined when unpaired.
|
|
1058
|
+
* Scanned by index: a lazy `[\s\S]*?` span rescans the tail for every
|
|
1059
|
+
* candidate opening, so many openings and no closer costs quadratic time.
|
|
1060
|
+
* Tag names are ASCII literals, so lowercasing suffices for a
|
|
1061
|
+
* case-insensitive match. */
|
|
1062
|
+
function firstTagBody(text, tag) {
|
|
1063
|
+
const open = `<${tag}>`;
|
|
1064
|
+
const close = `</${tag}>`;
|
|
1065
|
+
const haystack = text.toLowerCase();
|
|
1066
|
+
const start = haystack.indexOf(open);
|
|
1067
|
+
if (start < 0)
|
|
1068
|
+
return undefined;
|
|
1069
|
+
const end = haystack.indexOf(close, start + open.length);
|
|
1070
|
+
if (end < 0)
|
|
1071
|
+
return undefined;
|
|
1072
|
+
return text.slice(start + open.length, end);
|
|
1073
|
+
}
|
|
1074
|
+
/** Parse structured fields from the dynamic slab for telemetry. Read-only. */
|
|
1075
|
+
export function extractEnvFields(dynamicText) {
|
|
1076
|
+
const out = {};
|
|
1077
|
+
if (!dynamicText)
|
|
1078
|
+
return out;
|
|
1079
|
+
const body = firstTagBody(dynamicText, 'env');
|
|
1080
|
+
if (body !== undefined) {
|
|
1081
|
+
const cwd = /(?:^|\n)\s*Working directory:\s*(.+?)\s*(?:\n|$)/i.exec(body);
|
|
1082
|
+
if (cwd)
|
|
1083
|
+
out.cwd = cwd[1].trim();
|
|
1084
|
+
const gitRepo = /(?:^|\n)\s*Is directory a git repo:\s*(Yes|No)\b/i.exec(body);
|
|
1085
|
+
if (gitRepo)
|
|
1086
|
+
out.isGitRepo = gitRepo[1].toLowerCase() === 'yes';
|
|
1087
|
+
const platform = /(?:^|\n)\s*Platform:\s*(.+?)\s*(?:\n|$)/i.exec(body);
|
|
1088
|
+
if (platform)
|
|
1089
|
+
out.platform = platform[1].trim();
|
|
1090
|
+
const osVer = /(?:^|\n)\s*OS Version:\s*(.+?)\s*(?:\n|$)/i.exec(body);
|
|
1091
|
+
if (osVer)
|
|
1092
|
+
out.osVersion = osVer[1].trim();
|
|
1093
|
+
const today = /(?:^|\n)\s*Today'?s date:\s*(.+?)\s*(?:\n|$)/i.exec(body);
|
|
1094
|
+
if (today)
|
|
1095
|
+
out.today = today[1].trim();
|
|
1096
|
+
}
|
|
1097
|
+
// Branch may be in <git_status>, <context name="git">, or a bare "Branch:" / "On branch" line.
|
|
1098
|
+
const branch = /(?:^|\n)\s*(?:On branch|Branch:)\s*([^\s\n]+)/i.exec(dynamicText) ??
|
|
1099
|
+
/(?:^|\n)\s*Current branch:\s*([^\s\n]+)/i.exec(dynamicText);
|
|
1100
|
+
if (branch)
|
|
1101
|
+
out.gitBranch = branch[1].trim();
|
|
1102
|
+
return out;
|
|
1103
|
+
}
|
|
1104
|
+
/** Strip the per-turn `x-anthropic-billing-header:` line (changes every turn;
|
|
1105
|
+
* must not be baked into the image). Returned as `kept`; re-emitted after the
|
|
1106
|
+
* final user message's markers — NOT into req.system, which always precedes
|
|
1107
|
+
* the last cache_control marker and would void the whole cached prefix.
|
|
1108
|
+
*
|
|
1109
|
+
* Claude Code sends this as its own system block, so after extractSystemText
|
|
1110
|
+
* joins the blocks the line is never line 1 and a first-line-only test never
|
|
1111
|
+
* fires: on 86/86 captured bodies the header reached splitStaticDynamic, which
|
|
1112
|
+
* has no XML wrapper to key on, classified it static, and baked it into the
|
|
1113
|
+
* slab PNG. On 2.1.220 the value was session-stable (11/11 captures share
|
|
1114
|
+
* `cch=07295`) so the PNG stayed byte-identical and nothing showed. 2.1.222
|
|
1115
|
+
* added `cc_prev_req=<previous request id>`, making the line per-turn by
|
|
1116
|
+
* construction — re-rendering the slab and voiding the whole cached prefix on
|
|
1117
|
+
* every request. Match the line wherever it appears. */
|
|
1118
|
+
function stripBillingLine(text) {
|
|
1119
|
+
const m = /(^|\n)(x-anthropic-billing-header:[^\n]*)(\n?)/.exec(text);
|
|
1120
|
+
if (!m)
|
|
1121
|
+
return { kept: null, body: text };
|
|
1122
|
+
const lead = m[1]; // '' when the line starts the text, else the preceding \n
|
|
1123
|
+
const trail = m[3]; // '\n' unless the line ends the text
|
|
1124
|
+
// Excise the line plus EXACTLY ONE adjacent newline, so the surviving text is
|
|
1125
|
+
// byte-identical to the same text without the header: the trailing newline
|
|
1126
|
+
// when there is one (keeps the preceding break), otherwise the leading one.
|
|
1127
|
+
// Taking both would splice the neighbouring lines together and re-render the
|
|
1128
|
+
// slab — the very churn this function exists to prevent.
|
|
1129
|
+
const cutStart = m.index + (trail ? lead.length : 0);
|
|
1130
|
+
return { kept: m[2], body: text.slice(0, cutStart) + text.slice(m.index + m[0].length) };
|
|
1131
|
+
}
|
|
1132
|
+
/** Extract the `# Environment` markdown section Claude Code injects into its
|
|
1133
|
+
* system text (working dir, git state, platform, model ID). It carries no XML
|
|
1134
|
+
* wrapper, so splitStaticDynamic can't catch it — yet its git-status lines
|
|
1135
|
+
* change across sessions, and baking them into the slab PNG busts the cross-
|
|
1136
|
+
* session cache (system_sha8 717f1fce → 5efaa4bb for a one-file edit). Parallel
|
|
1137
|
+
* to stripBillingLine: `kept` re-enters the system tail as plain text, after
|
|
1138
|
+
* the anchor, so the slab bytes stay independent of git state. */
|
|
1139
|
+
function stripMarkdownEnvSection(text) {
|
|
1140
|
+
const m = /(?:^|\n)(# Environment\b[\s\S]*?)(?=\n#{1,6}\s|$)/.exec(text);
|
|
1141
|
+
if (!m)
|
|
1142
|
+
return { kept: '', body: text };
|
|
1143
|
+
return {
|
|
1144
|
+
kept: m[1].trimEnd(),
|
|
1145
|
+
body: text.slice(0, m.index) + text.slice(m.index + m[0].length),
|
|
1146
|
+
};
|
|
1147
|
+
}
|
|
1148
|
+
/** Build the "## Tool: name\n<desc>\n```json …```" block for one tool. Docs are
|
|
1149
|
+
* imaged on this path (mirrors openai.ts renderToolDoc): the image carries the
|
|
1150
|
+
* full schema — annotations included — at image token rates, while tools[]
|
|
1151
|
+
* carries the annotation-stripped structure for Anthropic's tool-use validator.
|
|
1152
|
+
* (The earlier text-reference design kept this prose-only because schema JSON
|
|
1153
|
+
* at text rates would have duplicated what tools[] already pays for; at image
|
|
1154
|
+
* rates the duplicate structure is cheap and the stripped annotations are the
|
|
1155
|
+
* compression.) */
|
|
1156
|
+
function renderToolDoc(t) {
|
|
1157
|
+
const parts = [`## Tool: ${t.name ?? '?'}`];
|
|
1158
|
+
if (t.description)
|
|
1159
|
+
parts.push(t.description);
|
|
1160
|
+
if (t.input_schema !== undefined) {
|
|
1161
|
+
parts.push('```json\n' + JSON.stringify(t.input_schema) + '\n```');
|
|
1162
|
+
}
|
|
1163
|
+
return parts.join('\n');
|
|
1164
|
+
}
|
|
1165
|
+
function makeImageBlock(pngB64, _ephemeral = false) {
|
|
1166
|
+
// inkling never adds its own cache_control — only moves existing caller markers
|
|
1167
|
+
// across the text→image flip. `_ephemeral` is preserved for call-site compat.
|
|
1168
|
+
return {
|
|
1169
|
+
type: 'image',
|
|
1170
|
+
source: { type: 'base64', media_type: 'image/png', data: pngB64 },
|
|
1171
|
+
};
|
|
1172
|
+
}
|
|
1173
|
+
// --- paging / truncation ---------------------------------------------------
|
|
1174
|
+
// Anthropic caps requests at 100 images. Huge tool_results (find trees,
|
|
1175
|
+
// log dumps) are truncated with a paging marker before render.
|
|
1176
|
+
/** Visual rows a single input line will consume after soft-wrap at `cols`. */
|
|
1177
|
+
function lineRows(line, cols) {
|
|
1178
|
+
return Math.max(1, Math.ceil(line.length / cols));
|
|
1179
|
+
}
|
|
1180
|
+
// Removed duplicate countVisualRows / estimateImageCount — now imported & re-exported from render.ts.
|
|
1181
|
+
/** Classify content so we can pick a truncation strategy. Cheap heuristics on
|
|
1182
|
+
* the first ~4 KiB. Returns:
|
|
1183
|
+
* - `'structured'`: JSON/YAML/diff markers at the top. Truncate tail.
|
|
1184
|
+
* - `'log'`: ≥30% of lines start with a log level or timestamp. Truncate middle.
|
|
1185
|
+
* - `'other'`: prose, file dumps, etc. Truncate middle.
|
|
1186
|
+
* Exported for tests. */
|
|
1187
|
+
export function classifyContent(text) {
|
|
1188
|
+
const head = text.slice(0, 4096);
|
|
1189
|
+
const trimmed = head.trimStart();
|
|
1190
|
+
if (trimmed.startsWith('{') && /^\{\s*("|\})/.test(trimmed))
|
|
1191
|
+
return 'structured';
|
|
1192
|
+
if (trimmed.startsWith('[') && /^\[\s*("|\{|\[|-?\d|true\b|false\b|null\b|\])/.test(trimmed))
|
|
1193
|
+
return 'structured';
|
|
1194
|
+
if (trimmed.startsWith('---\n') || trimmed.startsWith('---\r\n'))
|
|
1195
|
+
return 'structured';
|
|
1196
|
+
if (trimmed.startsWith('diff --git ') || /^---\s+\S/.test(trimmed))
|
|
1197
|
+
return 'structured';
|
|
1198
|
+
const lines = head.split('\n').slice(0, 40).filter((l) => l.length > 0);
|
|
1199
|
+
if (lines.length < 4)
|
|
1200
|
+
return 'other';
|
|
1201
|
+
const LOG_LINE = /^(\[?(DEBUG|INFO|WARN|WARNING|ERROR|TRACE|FATAL)\]?\b|\d{4}-\d{2}-\d{2}[T ]?|\d{2}:\d{2}:\d{2}\b)/;
|
|
1202
|
+
let logHits = 0;
|
|
1203
|
+
for (const line of lines)
|
|
1204
|
+
if (LOG_LINE.test(line))
|
|
1205
|
+
logHits++;
|
|
1206
|
+
if (logHits / lines.length >= 0.3)
|
|
1207
|
+
return 'log';
|
|
1208
|
+
return 'other';
|
|
1209
|
+
}
|
|
1210
|
+
/** Build the paging marker text. The model sees this verbatim INSIDE the
|
|
1211
|
+
* rendered image so it can reason about what was elided. */
|
|
1212
|
+
function buildPagingMarker(args) {
|
|
1213
|
+
const tailNote = args.shownTailLines > 0
|
|
1214
|
+
? ` Showing first ${args.shownHeadLines} lines and last ${args.shownTailLines} lines.`
|
|
1215
|
+
: ` Showing first ${args.shownHeadLines} lines (tail elided).`;
|
|
1216
|
+
return (`\n\n[ fiche paging: omitted ${args.omittedLines.toLocaleString('en-US')} lines ` +
|
|
1217
|
+
`(${args.omittedChars.toLocaleString('en-US')} chars) of content here. ` +
|
|
1218
|
+
`Original length: ${args.originalChars.toLocaleString('en-US')} chars ` +
|
|
1219
|
+
`(${args.originalLines.toLocaleString('en-US')} lines, ~${args.originalEstImages} images).` +
|
|
1220
|
+
`${tailNote} ]\n\n`);
|
|
1221
|
+
}
|
|
1222
|
+
/** Truncate `text` so it renders to roughly `maxImages` images at the given
|
|
1223
|
+
* `cols`. Picks head/tail split based on `classifyContent`. Budget measured
|
|
1224
|
+
* in visual rows (what render.ts actually slices on). Returns the truncated
|
|
1225
|
+
* text (with paging marker embedded) and the count of chars omitted. If
|
|
1226
|
+
* `text` already fits, returns unchanged with `omittedChars: 0`. Exported
|
|
1227
|
+
* for tests. */
|
|
1228
|
+
export function truncateForBudget(text, maxImages, cols, maxCharsPerImage = DENSE_CONTENT_CHARS_PER_IMAGE, linesPerImage = LINES_PER_IMAGE) {
|
|
1229
|
+
const estImages = estimateImageCount(text, cols, maxCharsPerImage, linesPerImage);
|
|
1230
|
+
if (estImages <= maxImages)
|
|
1231
|
+
return { text, omittedChars: 0, truncated: false };
|
|
1232
|
+
const readableLinesPerCol = Math.max(1, Math.floor(maxCharsPerImage / Math.max(1, cols)));
|
|
1233
|
+
const totalRowBudget = Math.max(8, maxImages * Math.min(linesPerImage, readableLinesPerCol) - 6);
|
|
1234
|
+
const totalCharBudget = Math.max(128, maxImages * maxCharsPerImage - 512);
|
|
1235
|
+
const shape = classifyContent(text);
|
|
1236
|
+
// Reflowed text uses NL_SENTINEL (↵ U+21B5) as line separator instead of \n.
|
|
1237
|
+
// Split on whichever delimiter the text uses so we can truncate at logical
|
|
1238
|
+
// line boundaries rather than treating the entire reflowed blob as one line.
|
|
1239
|
+
const nlChar = text.indexOf('\n') >= 0 ? '\n' : NL_SENTINEL;
|
|
1240
|
+
const lines = text.split(nlChar);
|
|
1241
|
+
const originalLines = lines.length;
|
|
1242
|
+
const originalChars = text.length;
|
|
1243
|
+
// Reflowed text joins logical lines with the ↵ sentinel, which the renderer
|
|
1244
|
+
// treats as an inline glyph that never forces a row break (see countVisualRows
|
|
1245
|
+
// / wrapLines). So many ↵-segments pack into one visual row — charging one row
|
|
1246
|
+
// per segment (lineRows) overstates rows ~6x and over-truncates. Charge the
|
|
1247
|
+
// packed-row DELTA instead: total rows telescope to ceil(keptChars/cols),
|
|
1248
|
+
// matching the renderer, while still binding the row budget for narrow columns
|
|
1249
|
+
// where the char budget alone would under-truncate.
|
|
1250
|
+
const reflowed = nlChar === NL_SENTINEL;
|
|
1251
|
+
const sentinelPad = reflowed ? 2 * NL_SENTINEL_PAD_CELLS : 0;
|
|
1252
|
+
const packedRows = (n) => Math.ceil(n / Math.max(1, cols));
|
|
1253
|
+
const rowCost = (seg, priorCells, addCells) => reflowed ? packedRows(priorCells + addCells) - packedRows(priorCells) : lineRows(seg, cols);
|
|
1254
|
+
if (shape === 'structured') {
|
|
1255
|
+
let rows = 0;
|
|
1256
|
+
let chars = 0;
|
|
1257
|
+
let cells = 0;
|
|
1258
|
+
let cut = 0;
|
|
1259
|
+
for (let i = 0; i < lines.length; i++) {
|
|
1260
|
+
const sep = i > 0 ? 1 : 0;
|
|
1261
|
+
const c = lines[i].length + sep;
|
|
1262
|
+
const cellDelta = lines[i].length + (sep > 0 ? 1 + sentinelPad : 0);
|
|
1263
|
+
const r = rowCost(lines[i], cells, cellDelta);
|
|
1264
|
+
if (rows + r > totalRowBudget || chars + c > totalCharBudget)
|
|
1265
|
+
break;
|
|
1266
|
+
rows += r;
|
|
1267
|
+
chars += c;
|
|
1268
|
+
cells += cellDelta;
|
|
1269
|
+
cut = i + 1;
|
|
1270
|
+
}
|
|
1271
|
+
if (cut === 0)
|
|
1272
|
+
cut = 1;
|
|
1273
|
+
const head = lines.slice(0, cut).join(nlChar);
|
|
1274
|
+
const omitted = originalChars - head.length;
|
|
1275
|
+
return {
|
|
1276
|
+
text: head +
|
|
1277
|
+
buildPagingMarker({
|
|
1278
|
+
originalChars,
|
|
1279
|
+
originalLines,
|
|
1280
|
+
originalEstImages: estImages,
|
|
1281
|
+
shownHeadLines: cut,
|
|
1282
|
+
shownTailLines: 0,
|
|
1283
|
+
omittedLines: originalLines - cut,
|
|
1284
|
+
omittedChars: omitted,
|
|
1285
|
+
}),
|
|
1286
|
+
omittedChars: omitted,
|
|
1287
|
+
truncated: true,
|
|
1288
|
+
};
|
|
1289
|
+
}
|
|
1290
|
+
// log / other: 60% head, 40% tail.
|
|
1291
|
+
const headRowBudget = Math.floor(totalRowBudget * 0.6);
|
|
1292
|
+
const tailRowBudget = totalRowBudget - headRowBudget;
|
|
1293
|
+
const headCharBudget = Math.floor(totalCharBudget * 0.6);
|
|
1294
|
+
const tailCharBudget = totalCharBudget - headCharBudget;
|
|
1295
|
+
let headRows = 0;
|
|
1296
|
+
let headChars = 0;
|
|
1297
|
+
let headCells = 0;
|
|
1298
|
+
let headCut = 0;
|
|
1299
|
+
for (let i = 0; i < lines.length; i++) {
|
|
1300
|
+
const sep = i > 0 ? 1 : 0;
|
|
1301
|
+
const c = lines[i].length + sep;
|
|
1302
|
+
const cellDelta = lines[i].length + (sep > 0 ? 1 + sentinelPad : 0);
|
|
1303
|
+
const r = rowCost(lines[i], headCells, cellDelta);
|
|
1304
|
+
if (headRows + r > headRowBudget || headChars + c > headCharBudget)
|
|
1305
|
+
break;
|
|
1306
|
+
headRows += r;
|
|
1307
|
+
headChars += c;
|
|
1308
|
+
headCells += cellDelta;
|
|
1309
|
+
headCut = i + 1;
|
|
1310
|
+
}
|
|
1311
|
+
if (headCut === 0)
|
|
1312
|
+
headCut = 1;
|
|
1313
|
+
let tailRows = 0;
|
|
1314
|
+
let tailChars = 0;
|
|
1315
|
+
let tailCells = 0;
|
|
1316
|
+
let tailStart = lines.length;
|
|
1317
|
+
for (let i = lines.length - 1; i >= headCut; i--) {
|
|
1318
|
+
const sep = i < lines.length - 1 ? 1 : 0;
|
|
1319
|
+
const c = lines[i].length + sep;
|
|
1320
|
+
const cellDelta = lines[i].length + (sep > 0 ? 1 + sentinelPad : 0);
|
|
1321
|
+
const r = rowCost(lines[i], tailCells, cellDelta);
|
|
1322
|
+
if (tailRows + r > tailRowBudget || tailChars + c > tailCharBudget)
|
|
1323
|
+
break;
|
|
1324
|
+
tailRows += r;
|
|
1325
|
+
tailChars += c;
|
|
1326
|
+
tailCells += cellDelta;
|
|
1327
|
+
tailStart = i;
|
|
1328
|
+
}
|
|
1329
|
+
if (tailStart <= headCut || tailStart >= lines.length) {
|
|
1330
|
+
const head = lines.slice(0, headCut).join(nlChar);
|
|
1331
|
+
const omitted = originalChars - head.length;
|
|
1332
|
+
return {
|
|
1333
|
+
text: head +
|
|
1334
|
+
buildPagingMarker({
|
|
1335
|
+
originalChars,
|
|
1336
|
+
originalLines,
|
|
1337
|
+
originalEstImages: estImages,
|
|
1338
|
+
shownHeadLines: headCut,
|
|
1339
|
+
shownTailLines: 0,
|
|
1340
|
+
omittedLines: originalLines - headCut,
|
|
1341
|
+
omittedChars: omitted,
|
|
1342
|
+
}),
|
|
1343
|
+
omittedChars: omitted,
|
|
1344
|
+
truncated: true,
|
|
1345
|
+
};
|
|
1346
|
+
}
|
|
1347
|
+
const headText = lines.slice(0, headCut).join(nlChar);
|
|
1348
|
+
const tailText = lines.slice(tailStart).join(nlChar);
|
|
1349
|
+
const shownChars = headText.length + tailText.length;
|
|
1350
|
+
const omitted = originalChars - shownChars;
|
|
1351
|
+
return {
|
|
1352
|
+
text: headText +
|
|
1353
|
+
buildPagingMarker({
|
|
1354
|
+
originalChars,
|
|
1355
|
+
originalLines,
|
|
1356
|
+
originalEstImages: estImages,
|
|
1357
|
+
shownHeadLines: headCut,
|
|
1358
|
+
shownTailLines: lines.length - tailStart,
|
|
1359
|
+
omittedLines: originalLines - headCut - (lines.length - tailStart),
|
|
1360
|
+
omittedChars: omitted,
|
|
1361
|
+
}) +
|
|
1362
|
+
tailText,
|
|
1363
|
+
omittedChars: omitted,
|
|
1364
|
+
truncated: true,
|
|
1365
|
+
};
|
|
1366
|
+
}
|
|
1367
|
+
/**
|
|
1368
|
+
* Render text → Anthropic image blocks for the proxy. The width-selection rule below
|
|
1369
|
+
* is mirrored exactly by
|
|
1370
|
+
* the public SDK primitive `renderTextToImages` (library.ts), so the proxy and the
|
|
1371
|
+
* `inkling export` CLI emit byte-identical PNGs for the same text. Exported so
|
|
1372
|
+
* export-proxy-align.test.ts can pin that invariant against the real proxy code.
|
|
1373
|
+
*/
|
|
1374
|
+
export async function textToImageBlocks(text, cols,
|
|
1375
|
+
/** Shrink canvas to the longest wrapped line. Default `true`. */
|
|
1376
|
+
shrinkWidth = true, style = DENSE_RENDER_STYLE, maxHeightPx = MAX_HEIGHT_PX) {
|
|
1377
|
+
const renderText = text;
|
|
1378
|
+
const effectiveCols = shrinkWidth ? shrinkColsToContent(renderText, cols, 1, style.font) : cols;
|
|
1379
|
+
const imgs = await renderTextToPngsWithCharLimit(renderText, effectiveCols, DENSE_CONTENT_CHARS_PER_IMAGE, style, maxHeightPx);
|
|
1380
|
+
let droppedChars = 0;
|
|
1381
|
+
let pixels = 0;
|
|
1382
|
+
const droppedCodepoints = new Map();
|
|
1383
|
+
const blocks = [];
|
|
1384
|
+
for (const img of imgs) {
|
|
1385
|
+
blocks.push(makeImageBlock(bytesToBase64(img.png), false));
|
|
1386
|
+
droppedChars += img.droppedChars;
|
|
1387
|
+
pixels += img.width * img.height;
|
|
1388
|
+
for (const [cp, n] of img.droppedCodepoints) {
|
|
1389
|
+
droppedCodepoints.set(cp, (droppedCodepoints.get(cp) ?? 0) + n);
|
|
1390
|
+
}
|
|
1391
|
+
}
|
|
1392
|
+
return {
|
|
1393
|
+
blocks,
|
|
1394
|
+
pngs: imgs.map((i) => i.png),
|
|
1395
|
+
dims: imgs.map((i) => ({ width: i.width, height: i.height })),
|
|
1396
|
+
droppedChars,
|
|
1397
|
+
droppedCodepoints,
|
|
1398
|
+
pixels,
|
|
1399
|
+
};
|
|
1400
|
+
}
|
|
1401
|
+
/** Best-effort byte-count of an image block's PNG payload (decoded from b64).
|
|
1402
|
+
* Used only for the imageBytes telemetry; an exact value isn't worth a
|
|
1403
|
+
* second base64 round-trip. */
|
|
1404
|
+
function approxBlockBytes(blk) {
|
|
1405
|
+
const b64 = blk.source.data;
|
|
1406
|
+
// base64 → bytes: every 4 chars decode to 3 bytes, minus padding.
|
|
1407
|
+
const pad = b64.endsWith('==') ? 2 : b64.endsWith('=') ? 1 : 0;
|
|
1408
|
+
return Math.floor((b64.length * 3) / 4) - pad;
|
|
1409
|
+
}
|
|
1410
|
+
// --- main transform --------------------------------------------------------
|
|
1411
|
+
/**
|
|
1412
|
+
* Emit the user's pins at the tail, immediately before serialization.
|
|
1413
|
+
*
|
|
1414
|
+
* Last, so nothing the transform does afterwards can bury them again, and after
|
|
1415
|
+
* every cache_control breakpoint, so the appended bytes are always in the
|
|
1416
|
+
* re-read suffix and can never invalidate a cached prefix.
|
|
1417
|
+
*/
|
|
1418
|
+
function applyPins(req, info, pins) {
|
|
1419
|
+
if (pins.length === 0 || !Array.isArray(req.messages))
|
|
1420
|
+
return;
|
|
1421
|
+
const chars = appendPinBlock(req.messages, pins);
|
|
1422
|
+
if (chars > 0)
|
|
1423
|
+
info.pinChars = chars;
|
|
1424
|
+
}
|
|
1425
|
+
/**
|
|
1426
|
+
* Run history-image compression on `req.messages` and finalize the body.
|
|
1427
|
+
* Called from both the main path AND early-exit paths (below_min_chars,
|
|
1428
|
+
* not_profitable) — history collapse must run even when the slab skips.
|
|
1429
|
+
* Tolerant to missing/short message arrays (collapseHistory short-circuits). */
|
|
1430
|
+
/** Slack between our page estimate and the provider's hard image cap. The renderer
|
|
1431
|
+
* paginates on its own, so a candidate grid can come out one page heavier than the
|
|
1432
|
+
* estimator predicted; the request must still land under {@link ANTHROPIC_MAX_IMAGES}. */
|
|
1433
|
+
const HISTORY_IMAGE_SAFETY_MARGIN = 5;
|
|
1434
|
+
/**
|
|
1435
|
+
* Image blocks this request may still add before the provider's hard cap.
|
|
1436
|
+
*
|
|
1437
|
+
* The cap counts EVERY image on the wire: the client's own (`nativeImages`) and
|
|
1438
|
+
* ours (`imageCount`). Pricing only ours is how a request with 103 client images
|
|
1439
|
+
* still got imaged further and came back 400 — the cap is a wire property, not a
|
|
1440
|
+
* inkling property. Never negative; callers treat 0 as "keep it as text".
|
|
1441
|
+
*/
|
|
1442
|
+
export function imageHeadroom(info) {
|
|
1443
|
+
return Math.max(0, ANTHROPIC_MAX_IMAGES -
|
|
1444
|
+
HISTORY_IMAGE_SAFETY_MARGIN -
|
|
1445
|
+
info.imageCount -
|
|
1446
|
+
(info.nativeImages ?? 0));
|
|
1447
|
+
}
|
|
1448
|
+
/** Bytes still available for image content, caller images already deducted.
|
|
1449
|
+
*
|
|
1450
|
+
* Separate from {@link imageHeadroom} because the two limits fail differently.
|
|
1451
|
+
* The count cap is the provider's documented limit and rejects with a clear
|
|
1452
|
+
* error. The byte budget is empirical: past roughly 20 MiB production requests
|
|
1453
|
+
* start failing as 500s, 502s, empty 200s and stalls, which read as flakiness
|
|
1454
|
+
* rather than as "too big". */
|
|
1455
|
+
export function imageByteHeadroom(info, limit) {
|
|
1456
|
+
return Math.max(0, limit - info.imageBytes - (info.nativeImageBytes ?? 0));
|
|
1457
|
+
}
|
|
1458
|
+
/** True when this request finished close enough to the budget that the next turn
|
|
1459
|
+
* of the same session is likely to hit it. */
|
|
1460
|
+
function nearByteLimit(info, limit) {
|
|
1461
|
+
return limit > 0 && info.imageBytes + (info.nativeImageBytes ?? 0) >= limit * 0.9;
|
|
1462
|
+
}
|
|
1463
|
+
/** Decoded bytes of the caller's own images, at both nesting levels. Runs BEFORE
|
|
1464
|
+
* any rewrite, for the same reason {@link countNativeImages} does. */
|
|
1465
|
+
export function countNativeImageBytes(messages) {
|
|
1466
|
+
let bytes = 0;
|
|
1467
|
+
const add = (blk) => {
|
|
1468
|
+
const b = blk;
|
|
1469
|
+
if (b?.type === 'image' && typeof b.source?.data === 'string')
|
|
1470
|
+
bytes += approxBlockBytes(b);
|
|
1471
|
+
};
|
|
1472
|
+
for (const m of messages ?? []) {
|
|
1473
|
+
if (!Array.isArray(m.content))
|
|
1474
|
+
continue;
|
|
1475
|
+
for (const blk of m.content) {
|
|
1476
|
+
add(blk);
|
|
1477
|
+
const tr = blk;
|
|
1478
|
+
if (tr?.type === 'tool_result' && Array.isArray(tr.content)) {
|
|
1479
|
+
for (const inner of tr.content)
|
|
1480
|
+
add(inner);
|
|
1481
|
+
}
|
|
1482
|
+
}
|
|
1483
|
+
}
|
|
1484
|
+
return bytes;
|
|
1485
|
+
}
|
|
1486
|
+
/** Count image blocks already present in the caller's messages. Runs BEFORE any
|
|
1487
|
+
* rewrite, so it sees the client's images only — ours do not exist yet. */
|
|
1488
|
+
export function countNativeImages(messages) {
|
|
1489
|
+
let n = 0;
|
|
1490
|
+
for (const m of messages ?? []) {
|
|
1491
|
+
if (!Array.isArray(m.content))
|
|
1492
|
+
continue;
|
|
1493
|
+
for (const blk of m.content) {
|
|
1494
|
+
const t = blk?.type;
|
|
1495
|
+
if (t === 'image')
|
|
1496
|
+
n++;
|
|
1497
|
+
else if (t === 'tool_result') {
|
|
1498
|
+
const inner = blk.content;
|
|
1499
|
+
if (Array.isArray(inner)) {
|
|
1500
|
+
for (const ib of inner)
|
|
1501
|
+
if (ib?.type === 'image')
|
|
1502
|
+
n++;
|
|
1503
|
+
}
|
|
1504
|
+
}
|
|
1505
|
+
}
|
|
1506
|
+
}
|
|
1507
|
+
return n;
|
|
1508
|
+
}
|
|
1509
|
+
/**
|
|
1510
|
+
* Per-request history-grid tuning: how many images the collapse may still spend,
|
|
1511
|
+
* and whether it is allowed to re-cut the grid for density.
|
|
1512
|
+
*
|
|
1513
|
+
* `info.imageCount` already holds every image this request emitted before the
|
|
1514
|
+
* collapse (slab, tool docs, tool_results), so the remaining headroom is the hard
|
|
1515
|
+
* cap minus those, minus a margin for estimator drift — and never more than the
|
|
1516
|
+
* standing cost guard {@link ANTHROPIC_HISTORY_IMAGE_BUDGET}.
|
|
1517
|
+
*
|
|
1518
|
+
* `packFill`/`minFreezeStep` come from the session store: repack only when the
|
|
1519
|
+
* upstream cache is provably dead, and never below a grid this session already
|
|
1520
|
+
* froze at. See {@link noteHistoryRequest}.
|
|
1521
|
+
*/
|
|
1522
|
+
function historyGridTuning(info, preSession) {
|
|
1523
|
+
const headroom = imageHeadroom(info);
|
|
1524
|
+
const imageBudget = Math.max(1, Math.min(ANTHROPIC_HISTORY_IMAGE_BUDGET, headroom));
|
|
1525
|
+
const session = preSession ?? noteHistoryRequest(info.sessionKey ?? info.firstUserSha8);
|
|
1526
|
+
return { imageBudget, packFill: session.cold, minFreezeStep: session.minFreezeStep };
|
|
1527
|
+
}
|
|
1528
|
+
function buildHybridToolOpticalGuard(req, sessionKey, sessionCold) {
|
|
1529
|
+
const cacheBreakpoints = [];
|
|
1530
|
+
if (Array.isArray(req.tools)) {
|
|
1531
|
+
for (const rawTool of req.tools) {
|
|
1532
|
+
if (!rawTool || typeof rawTool !== 'object')
|
|
1533
|
+
continue;
|
|
1534
|
+
const ttl = markerTtlSeconds(rawTool.cache_control);
|
|
1535
|
+
if (ttl !== undefined)
|
|
1536
|
+
cacheBreakpoints.push({ msgIndex: -1, blockIndex: 0, ttlSec: ttl });
|
|
1537
|
+
}
|
|
1538
|
+
}
|
|
1539
|
+
if (Array.isArray(req.system)) {
|
|
1540
|
+
for (const rawBlk of req.system) {
|
|
1541
|
+
if (!rawBlk || typeof rawBlk !== 'object')
|
|
1542
|
+
continue;
|
|
1543
|
+
const ttl = markerTtlSeconds(rawBlk.cache_control);
|
|
1544
|
+
if (ttl !== undefined)
|
|
1545
|
+
cacheBreakpoints.push({ msgIndex: -1, blockIndex: 0, ttlSec: ttl });
|
|
1546
|
+
}
|
|
1547
|
+
}
|
|
1548
|
+
const messages = Array.isArray(req.messages) ? req.messages : [];
|
|
1549
|
+
const msgTotalTokens = new Array(messages.length).fill(0);
|
|
1550
|
+
for (let mIdx = 0; mIdx < messages.length; mIdx++) {
|
|
1551
|
+
const msg = messages[mIdx];
|
|
1552
|
+
msgTotalTokens[mIdx] = estimateMessageTokens(msg);
|
|
1553
|
+
if (!msg || typeof msg !== 'object')
|
|
1554
|
+
continue;
|
|
1555
|
+
const msgTtl = markerTtlSeconds(msg.cache_control);
|
|
1556
|
+
if (msgTtl !== undefined) {
|
|
1557
|
+
cacheBreakpoints.push({ msgIndex: mIdx, blockIndex: Number.MAX_SAFE_INTEGER, ttlSec: msgTtl });
|
|
1558
|
+
}
|
|
1559
|
+
if (!Array.isArray(msg.content))
|
|
1560
|
+
continue;
|
|
1561
|
+
for (let bIdx = 0; bIdx < msg.content.length; bIdx++) {
|
|
1562
|
+
const blk = msg.content[bIdx];
|
|
1563
|
+
if (!blk || typeof blk !== 'object')
|
|
1564
|
+
continue;
|
|
1565
|
+
const blkTtl = markerTtlSeconds(blk.cache_control);
|
|
1566
|
+
if (blkTtl !== undefined)
|
|
1567
|
+
cacheBreakpoints.push({ msgIndex: mIdx, blockIndex: bIdx, ttlSec: blkTtl });
|
|
1568
|
+
if (blk.type === 'tool_result' && Array.isArray(blk.content)) {
|
|
1569
|
+
for (const sub of blk.content) {
|
|
1570
|
+
if (!sub || typeof sub !== 'object')
|
|
1571
|
+
continue;
|
|
1572
|
+
const partTtl = markerTtlSeconds(sub.cache_control);
|
|
1573
|
+
if (partTtl !== undefined)
|
|
1574
|
+
cacheBreakpoints.push({ msgIndex: mIdx, blockIndex: bIdx, ttlSec: partTtl });
|
|
1575
|
+
}
|
|
1576
|
+
}
|
|
1577
|
+
}
|
|
1578
|
+
}
|
|
1579
|
+
return {
|
|
1580
|
+
cacheBreakpoints,
|
|
1581
|
+
msgTotalTokens,
|
|
1582
|
+
totalMessages: messages.length,
|
|
1583
|
+
sessionKey,
|
|
1584
|
+
sessionCold,
|
|
1585
|
+
};
|
|
1586
|
+
}
|
|
1587
|
+
function checkHybridToolOpticalBlock(mIdx, bIdx, slotSig, guard) {
|
|
1588
|
+
if (!guard)
|
|
1589
|
+
return { skip: false };
|
|
1590
|
+
const slotKey = `opt_tr:${slotSig}`;
|
|
1591
|
+
const alreadySealed = Boolean(guard.sessionKey && hasStage2SealKey(guard.sessionKey, slotKey));
|
|
1592
|
+
if (!alreadySealed && !guard.sessionCold) {
|
|
1593
|
+
const { coveringTtlSec, downstreamTokens } = coveringBreakpointInfo(mIdx, bIdx, guard.cacheBreakpoints, guard.msgTotalTokens, guard.totalMessages);
|
|
1594
|
+
if (coveringTtlSec > 0 && downstreamTokens > 0) {
|
|
1595
|
+
return { skip: true };
|
|
1596
|
+
}
|
|
1597
|
+
}
|
|
1598
|
+
return {
|
|
1599
|
+
skip: false,
|
|
1600
|
+
seal: () => {
|
|
1601
|
+
if (guard.sessionKey)
|
|
1602
|
+
recordStage2SealKey(guard.sessionKey, slotKey);
|
|
1603
|
+
},
|
|
1604
|
+
};
|
|
1605
|
+
}
|
|
1606
|
+
async function compressToolResultsInPlace(req, info, o, denseGeo, droppedCodepoints, hybridGuard) {
|
|
1607
|
+
let anyChanged = false;
|
|
1608
|
+
if (o.compressToolResults) {
|
|
1609
|
+
const messages = req.messages ?? [];
|
|
1610
|
+
for (let mIdx = 0; mIdx < messages.length; mIdx++) {
|
|
1611
|
+
const msg = messages[mIdx];
|
|
1612
|
+
if (msg.role !== 'user' || !Array.isArray(msg.content))
|
|
1613
|
+
continue;
|
|
1614
|
+
const rewritten = [];
|
|
1615
|
+
let changed = false;
|
|
1616
|
+
for (let bIdx = 0; bIdx < msg.content.length; bIdx++) {
|
|
1617
|
+
const blk = msg.content[bIdx];
|
|
1618
|
+
if (blk && blk.type === 'tool_result') {
|
|
1619
|
+
const tr = blk;
|
|
1620
|
+
// Anthropic rejects images inside is_error tool_results — leave alone.
|
|
1621
|
+
if (tr.is_error === true) {
|
|
1622
|
+
rewritten.push(blk);
|
|
1623
|
+
continue;
|
|
1624
|
+
}
|
|
1625
|
+
const innerRaw = tr.content;
|
|
1626
|
+
if (typeof innerRaw === 'string') {
|
|
1627
|
+
// Caller fidelity override: pin this tool_result as text.
|
|
1628
|
+
if (callerKeepsSharp(o.keepSharp, { kind: 'tool_result', text: innerRaw, toolUseId: tr.tool_use_id })) {
|
|
1629
|
+
bumpPassthrough(info, 'kept_sharp');
|
|
1630
|
+
info.keptSharpBlocks = (info.keptSharpBlocks ?? 0) + 1;
|
|
1631
|
+
rewritten.push(blk);
|
|
1632
|
+
continue;
|
|
1633
|
+
}
|
|
1634
|
+
const guardDecision = hybridGuard
|
|
1635
|
+
? checkHybridToolOpticalBlock(mIdx, bIdx, `${tr.tool_use_id ?? `${mIdx}_${bIdx}`}\0${innerRaw.length}:${tapeHash64Hex(innerRaw)}`, hybridGuard)
|
|
1636
|
+
: undefined;
|
|
1637
|
+
if (guardDecision?.skip) {
|
|
1638
|
+
rewritten.push(blk);
|
|
1639
|
+
continue;
|
|
1640
|
+
}
|
|
1641
|
+
// Hard wire cap: the client's own images plus ours must stay
|
|
1642
|
+
// under the provider's limit, else the WHOLE request is rejected.
|
|
1643
|
+
// Out of headroom → keep the text sharp; a big body beats a 400.
|
|
1644
|
+
if (imageHeadroom(info) <= 0) {
|
|
1645
|
+
bumpPassthrough(info, 'image_budget');
|
|
1646
|
+
info.imageBudgetSkips = (info.imageBudgetSkips ?? 0) + 1;
|
|
1647
|
+
rewritten.push(blk);
|
|
1648
|
+
continue;
|
|
1649
|
+
}
|
|
1650
|
+
const inner = compactSlabWhitespace(innerRaw);
|
|
1651
|
+
// classifyContent sees pre-reflow `inner` so shape bucketing reflects real structure.
|
|
1652
|
+
const innerR = maybeReflow(inner, o.reflow);
|
|
1653
|
+
if (innerR.length < o.minToolResultChars) {
|
|
1654
|
+
bumpPassthrough(info, 'below_threshold');
|
|
1655
|
+
rewritten.push(blk);
|
|
1656
|
+
}
|
|
1657
|
+
else if (!isCompressionProfitable(innerR, denseGeo.cols, o.maxImagesPerToolResult, o.charsPerToken, 0, 0, true, denseGeo.maxChars, denseGeo, gateRates(req, o.model))) {
|
|
1658
|
+
bumpPassthrough(info, 'not_profitable');
|
|
1659
|
+
rewritten.push(blk);
|
|
1660
|
+
}
|
|
1661
|
+
else {
|
|
1662
|
+
// Paging: truncate before render if it would blow the image cap.
|
|
1663
|
+
// The per-result cap is the SMALLER of the configured max and what
|
|
1664
|
+
// is actually left on the wire — the headroom shrinks as earlier
|
|
1665
|
+
// results spend it, so each result sees the live number.
|
|
1666
|
+
const resultImageCap = Math.min(o.maxImagesPerToolResult, imageHeadroom(info));
|
|
1667
|
+
const linesPerImage = Math.max(1, Math.floor((denseGeo.maxHeightPx - 2 * PAD_Y) / renderCellHeight(denseGeo.style)));
|
|
1668
|
+
const paged = truncateForBudget(innerR, resultImageCap, denseGeo.cols, denseGeo.maxChars, linesPerImage);
|
|
1669
|
+
const { blocks: imgs, pngs: rawPngs, dims: rawDims, droppedChars, droppedCodepoints: dcp, pixels } = await textToImageBlocks(paged.text, o.cols, true, denseGeo.style, denseGeo.maxHeightPx);
|
|
1670
|
+
// Paging is budgeted at denseGeo.cols but rendering happens at
|
|
1671
|
+
// o.cols; when they differ the real page count can exceed the plan.
|
|
1672
|
+
// Verify against the actual render and drop OUR images rather than
|
|
1673
|
+
// ship a request the provider rejects outright.
|
|
1674
|
+
// Atomic admission: this tool_result is one semantic group. It
|
|
1675
|
+
// is imaged whole or kept as text whole, by count and by weight
|
|
1676
|
+
// alike. A half-imaged result would ship pages without the text
|
|
1677
|
+
// they replaced.
|
|
1678
|
+
const groupBytes = imgs.reduce((sum, img) => sum + approxBlockBytes(img), 0);
|
|
1679
|
+
if (imgs.length > imageHeadroom(info)) {
|
|
1680
|
+
bumpPassthrough(info, 'image_budget');
|
|
1681
|
+
info.imageBudgetSkips = (info.imageBudgetSkips ?? 0) + 1;
|
|
1682
|
+
rewritten.push(blk);
|
|
1683
|
+
continue;
|
|
1684
|
+
}
|
|
1685
|
+
if (groupBytes > imageByteHeadroom(info, o.maxImageBytes)) {
|
|
1686
|
+
bumpPassthrough(info, 'image_budget');
|
|
1687
|
+
info.imageByteSkips = (info.imageByteSkips ?? 0) + 1;
|
|
1688
|
+
rewritten.push(blk);
|
|
1689
|
+
continue;
|
|
1690
|
+
}
|
|
1691
|
+
if (paged.truncated) {
|
|
1692
|
+
info.truncatedToolResults = (info.truncatedToolResults ?? 0) + 1;
|
|
1693
|
+
info.omittedChars = (info.omittedChars ?? 0) + paged.omittedChars;
|
|
1694
|
+
}
|
|
1695
|
+
(info.imagePngs ??= []).push(...rawPngs);
|
|
1696
|
+
(info.imageDims ??= []).push(...rawDims);
|
|
1697
|
+
for (const img of imgs)
|
|
1698
|
+
info.imageBytes += approxBlockBytes(img);
|
|
1699
|
+
info.imagePixels = (info.imagePixels ?? 0) + pixels;
|
|
1700
|
+
info.imageTokens = (info.imageTokens ?? 0) + rawDims.reduce((s, d) => s + visionTokens(denseGeo.pricing, d.width, d.height), 0);
|
|
1701
|
+
info.baselineImagedTokens = (info.baselineImagedTokens ?? 0) + Math.ceil(innerRaw.length / Math.max(1e-6, o.charsPerToken));
|
|
1702
|
+
info.toolResultImgs = (info.toolResultImgs ?? 0) + imgs.length;
|
|
1703
|
+
info.imageCount += imgs.length;
|
|
1704
|
+
await recordRecoverable(info, o.emitRecoverable, {
|
|
1705
|
+
kind: 'tool_result',
|
|
1706
|
+
toolUseId: tr.tool_use_id,
|
|
1707
|
+
text: innerRaw,
|
|
1708
|
+
imageCount: imgs.length,
|
|
1709
|
+
});
|
|
1710
|
+
info.compressedChars += innerRaw.length; // original length = what text billing would be
|
|
1711
|
+
info.droppedChars = (info.droppedChars ?? 0) + droppedChars;
|
|
1712
|
+
for (const [cp, n] of dcp) {
|
|
1713
|
+
droppedCodepoints.set(cp, (droppedCodepoints.get(cp) ?? 0) + n);
|
|
1714
|
+
}
|
|
1715
|
+
const trFactSheet = factSheetText(innerRaw);
|
|
1716
|
+
rewritten.push({
|
|
1717
|
+
...tr,
|
|
1718
|
+
content: trFactSheet ? [...imgs, { type: 'text', text: trFactSheet }] : imgs,
|
|
1719
|
+
});
|
|
1720
|
+
changed = true;
|
|
1721
|
+
guardDecision?.seal?.();
|
|
1722
|
+
bumpBucket(info, toolResultBucket(classifyContent(inner)), innerRaw.length);
|
|
1723
|
+
}
|
|
1724
|
+
}
|
|
1725
|
+
else if (Array.isArray(innerRaw)) {
|
|
1726
|
+
const newInner = [];
|
|
1727
|
+
let innerChanged = false;
|
|
1728
|
+
for (let pIdx = 0; pIdx < innerRaw.length; pIdx++) {
|
|
1729
|
+
const ib = innerRaw[pIdx];
|
|
1730
|
+
const isTextBlock = ib &&
|
|
1731
|
+
ib.type === 'text' &&
|
|
1732
|
+
typeof ib.text === 'string';
|
|
1733
|
+
if (!isTextBlock) {
|
|
1734
|
+
newInner.push(ib);
|
|
1735
|
+
continue;
|
|
1736
|
+
}
|
|
1737
|
+
const innerTextRaw = ib.text;
|
|
1738
|
+
// Caller fidelity override: pin this tool_result part as text.
|
|
1739
|
+
if (callerKeepsSharp(o.keepSharp, { kind: 'tool_result_part', text: innerTextRaw, toolUseId: tr.tool_use_id })) {
|
|
1740
|
+
bumpPassthrough(info, 'kept_sharp');
|
|
1741
|
+
info.keptSharpBlocks = (info.keptSharpBlocks ?? 0) + 1;
|
|
1742
|
+
newInner.push(ib);
|
|
1743
|
+
continue;
|
|
1744
|
+
}
|
|
1745
|
+
const partGuardDecision = hybridGuard
|
|
1746
|
+
? checkHybridToolOpticalBlock(mIdx, bIdx, `${tr.tool_use_id ?? `${mIdx}_${bIdx}`}#${pIdx}\0${innerTextRaw.length}:${tapeHash64Hex(innerTextRaw)}`, hybridGuard)
|
|
1747
|
+
: undefined;
|
|
1748
|
+
if (partGuardDecision?.skip) {
|
|
1749
|
+
newInner.push(ib);
|
|
1750
|
+
continue;
|
|
1751
|
+
}
|
|
1752
|
+
// Hard wire cap — see the string-content path above.
|
|
1753
|
+
if (imageHeadroom(info) <= 0) {
|
|
1754
|
+
bumpPassthrough(info, 'image_budget');
|
|
1755
|
+
info.imageBudgetSkips = (info.imageBudgetSkips ?? 0) + 1;
|
|
1756
|
+
newInner.push(ib);
|
|
1757
|
+
continue;
|
|
1758
|
+
}
|
|
1759
|
+
// Lossless whitespace compaction before gate + render.
|
|
1760
|
+
const innerText = compactSlabWhitespace(innerTextRaw);
|
|
1761
|
+
// R3: gate/page/render on reflowed text; classify pre-reflow.
|
|
1762
|
+
const innerTextR = maybeReflow(innerText, o.reflow);
|
|
1763
|
+
if (innerTextR.length < o.minToolResultChars) {
|
|
1764
|
+
bumpPassthrough(info, 'below_threshold');
|
|
1765
|
+
newInner.push(ib);
|
|
1766
|
+
continue;
|
|
1767
|
+
}
|
|
1768
|
+
if (!isCompressionProfitable(innerTextR, denseGeo.cols, o.maxImagesPerToolResult, o.charsPerToken, 0, 0, true, denseGeo.maxChars, denseGeo, gateRates(req, o.model))) {
|
|
1769
|
+
bumpPassthrough(info, 'not_profitable');
|
|
1770
|
+
newInner.push(ib);
|
|
1771
|
+
continue;
|
|
1772
|
+
}
|
|
1773
|
+
const linesPerImage = Math.max(1, Math.floor((denseGeo.maxHeightPx - 2 * PAD_Y) / renderCellHeight(denseGeo.style)));
|
|
1774
|
+
const resultImageCap = Math.min(o.maxImagesPerToolResult, imageHeadroom(info));
|
|
1775
|
+
const paged = truncateForBudget(innerTextR, resultImageCap, denseGeo.cols, denseGeo.maxChars, linesPerImage);
|
|
1776
|
+
const { blocks: imgs, pngs: rawPngs, dims: rawDims, droppedChars, droppedCodepoints: dcp, pixels } = await textToImageBlocks(paged.text, o.cols, true, denseGeo.style, denseGeo.maxHeightPx);
|
|
1777
|
+
// Paging is budgeted at denseGeo.cols but rendering happens at
|
|
1778
|
+
// o.cols; when they differ the real page count can exceed the plan.
|
|
1779
|
+
// Verify against the actual render and drop OUR images rather than
|
|
1780
|
+
// ship a request the provider rejects outright.
|
|
1781
|
+
const partBytes = imgs.reduce((sum, img) => sum + approxBlockBytes(img), 0);
|
|
1782
|
+
if (imgs.length > imageHeadroom(info)) {
|
|
1783
|
+
bumpPassthrough(info, 'image_budget');
|
|
1784
|
+
info.imageBudgetSkips = (info.imageBudgetSkips ?? 0) + 1;
|
|
1785
|
+
newInner.push(ib);
|
|
1786
|
+
continue;
|
|
1787
|
+
}
|
|
1788
|
+
if (partBytes > imageByteHeadroom(info, o.maxImageBytes)) {
|
|
1789
|
+
bumpPassthrough(info, 'image_budget');
|
|
1790
|
+
info.imageByteSkips = (info.imageByteSkips ?? 0) + 1;
|
|
1791
|
+
newInner.push(ib);
|
|
1792
|
+
continue;
|
|
1793
|
+
}
|
|
1794
|
+
if (paged.truncated) {
|
|
1795
|
+
info.truncatedToolResults = (info.truncatedToolResults ?? 0) + 1;
|
|
1796
|
+
info.omittedChars = (info.omittedChars ?? 0) + paged.omittedChars;
|
|
1797
|
+
}
|
|
1798
|
+
(info.imagePngs ??= []).push(...rawPngs);
|
|
1799
|
+
(info.imageDims ??= []).push(...rawDims);
|
|
1800
|
+
const srcCacheControl = demoteRelocatedCacheControl(ib.cache_control);
|
|
1801
|
+
for (let i = 0; i < imgs.length; i++) {
|
|
1802
|
+
const img = imgs[i];
|
|
1803
|
+
const out = i === imgs.length - 1 && srcCacheControl !== undefined
|
|
1804
|
+
? { ...img, cache_control: srcCacheControl }
|
|
1805
|
+
: img;
|
|
1806
|
+
newInner.push(out);
|
|
1807
|
+
info.imageBytes += approxBlockBytes(img);
|
|
1808
|
+
}
|
|
1809
|
+
const partFactSheet = factSheetText(innerTextRaw);
|
|
1810
|
+
if (partFactSheet)
|
|
1811
|
+
newInner.push({ type: 'text', text: partFactSheet });
|
|
1812
|
+
info.imagePixels = (info.imagePixels ?? 0) + pixels;
|
|
1813
|
+
info.imageTokens = (info.imageTokens ?? 0) + rawDims.reduce((s, d) => s + visionTokens(denseGeo.pricing, d.width, d.height), 0);
|
|
1814
|
+
info.baselineImagedTokens = (info.baselineImagedTokens ?? 0) + Math.ceil(innerTextRaw.length / Math.max(1e-6, o.charsPerToken));
|
|
1815
|
+
info.toolResultImgs = (info.toolResultImgs ?? 0) + imgs.length;
|
|
1816
|
+
info.imageCount += imgs.length;
|
|
1817
|
+
await recordRecoverable(info, o.emitRecoverable, {
|
|
1818
|
+
kind: 'tool_result_part',
|
|
1819
|
+
toolUseId: tr.tool_use_id,
|
|
1820
|
+
text: innerTextRaw,
|
|
1821
|
+
imageCount: imgs.length,
|
|
1822
|
+
});
|
|
1823
|
+
info.compressedChars += innerTextRaw.length;
|
|
1824
|
+
info.droppedChars = (info.droppedChars ?? 0) + droppedChars;
|
|
1825
|
+
for (const [cp, n] of dcp) {
|
|
1826
|
+
droppedCodepoints.set(cp, (droppedCodepoints.get(cp) ?? 0) + n);
|
|
1827
|
+
}
|
|
1828
|
+
bumpBucket(info, toolResultBucket(classifyContent(innerText)), innerTextRaw.length);
|
|
1829
|
+
partGuardDecision?.seal?.();
|
|
1830
|
+
innerChanged = true;
|
|
1831
|
+
}
|
|
1832
|
+
if (innerChanged) {
|
|
1833
|
+
rewritten.push({ ...tr, content: newInner });
|
|
1834
|
+
changed = true;
|
|
1835
|
+
}
|
|
1836
|
+
else {
|
|
1837
|
+
rewritten.push(blk);
|
|
1838
|
+
}
|
|
1839
|
+
}
|
|
1840
|
+
else {
|
|
1841
|
+
rewritten.push(blk);
|
|
1842
|
+
}
|
|
1843
|
+
}
|
|
1844
|
+
else {
|
|
1845
|
+
rewritten.push(blk);
|
|
1846
|
+
}
|
|
1847
|
+
}
|
|
1848
|
+
if (changed) {
|
|
1849
|
+
msg.content = rewritten;
|
|
1850
|
+
anyChanged = true;
|
|
1851
|
+
}
|
|
1852
|
+
}
|
|
1853
|
+
}
|
|
1854
|
+
if (anyChanged && hybridGuard) {
|
|
1855
|
+
const stages = info.textHygieneStages ? [...info.textHygieneStages] : [];
|
|
1856
|
+
if (!stages.includes('hybrid_tool_optical'))
|
|
1857
|
+
stages.push('hybrid_tool_optical');
|
|
1858
|
+
info.textHygieneStages = stages;
|
|
1859
|
+
}
|
|
1860
|
+
return anyChanged;
|
|
1861
|
+
}
|
|
1862
|
+
const ANTHROPIC_CLIFF_STICKY_MAX = 512;
|
|
1863
|
+
const anthropicCliffSticky = new Map();
|
|
1864
|
+
function getAnthropicCliffSticky(key) {
|
|
1865
|
+
const hit = anthropicCliffSticky.get(key);
|
|
1866
|
+
if (hit !== undefined) {
|
|
1867
|
+
anthropicCliffSticky.delete(key);
|
|
1868
|
+
anthropicCliffSticky.set(key, hit);
|
|
1869
|
+
}
|
|
1870
|
+
return hit;
|
|
1871
|
+
}
|
|
1872
|
+
function recordAnthropicCliffSticky(key, cliffAt) {
|
|
1873
|
+
if (anthropicCliffSticky.has(key)) {
|
|
1874
|
+
anthropicCliffSticky.delete(key);
|
|
1875
|
+
}
|
|
1876
|
+
else if (anthropicCliffSticky.size >= ANTHROPIC_CLIFF_STICKY_MAX) {
|
|
1877
|
+
const oldest = anthropicCliffSticky.keys().next().value;
|
|
1878
|
+
if (oldest !== undefined)
|
|
1879
|
+
anthropicCliffSticky.delete(oldest);
|
|
1880
|
+
}
|
|
1881
|
+
anthropicCliffSticky.set(key, cliffAt);
|
|
1882
|
+
}
|
|
1883
|
+
function estimateTailMsgTokens(messages, charsPerToken) {
|
|
1884
|
+
if (!Array.isArray(messages) || messages.length <= 1)
|
|
1885
|
+
return 0;
|
|
1886
|
+
try {
|
|
1887
|
+
return Math.ceil(JSON.stringify(messages[messages.length - 1]).length / Math.max(1, charsPerToken));
|
|
1888
|
+
}
|
|
1889
|
+
catch {
|
|
1890
|
+
return 0;
|
|
1891
|
+
}
|
|
1892
|
+
}
|
|
1893
|
+
/** Resolve whether optical compression covers only the static Turn-1 slab ('hybrid',
|
|
1894
|
+
* with dynamic turns handled by prefix-monotonic Text-MMU) or also history/tool_results ('full'). */
|
|
1895
|
+
export function resolveOpticalHistoryPolicy(opts) {
|
|
1896
|
+
const rawEnv = readBrandEnv('OPTICAL_MODE');
|
|
1897
|
+
const normEnv = rawEnv ? rawEnv.trim().toLowerCase() : undefined;
|
|
1898
|
+
const envMode = normEnv === 'full' || normEnv === 'hybrid' || normEnv === 'auto'
|
|
1899
|
+
? normEnv
|
|
1900
|
+
: undefined;
|
|
1901
|
+
if (opts.opticalMode === 'full' ||
|
|
1902
|
+
envMode === 'full' ||
|
|
1903
|
+
opts.collapseHistory === true ||
|
|
1904
|
+
!opts.textHygieneActive) {
|
|
1905
|
+
return 'full';
|
|
1906
|
+
}
|
|
1907
|
+
if (opts.opticalMode === 'hybrid' || envMode === 'hybrid') {
|
|
1908
|
+
return 'hybrid';
|
|
1909
|
+
}
|
|
1910
|
+
if (opts.sessionKey && !opts.sessionCold) {
|
|
1911
|
+
const pinned = getPinnedOpticalHistoryPolicy(opts.sessionKey, { model: opts.model });
|
|
1912
|
+
if (pinned !== undefined)
|
|
1913
|
+
return pinned;
|
|
1914
|
+
}
|
|
1915
|
+
const promptTokens = opts.estPromptTokens ?? 0;
|
|
1916
|
+
let computed;
|
|
1917
|
+
if (priceMode() !== 'kosha' || promptTokens >= 160_000) {
|
|
1918
|
+
computed = 'full';
|
|
1919
|
+
}
|
|
1920
|
+
else {
|
|
1921
|
+
const rates = resolvePriceRates(opts.model, { promptTokens: opts.estPromptTokens });
|
|
1922
|
+
computed = rates.read <= 0.10 ? 'hybrid' : 'full';
|
|
1923
|
+
}
|
|
1924
|
+
if (opts.sessionKey) {
|
|
1925
|
+
setPinnedOpticalHistoryPolicy(opts.sessionKey, computed, { model: opts.model });
|
|
1926
|
+
}
|
|
1927
|
+
return computed;
|
|
1928
|
+
}
|
|
1929
|
+
async function runHistoryCollapseAndFinalize(req, info, o, opts, droppedCodepoints, pins, reqPromptTokensEst, reqTtlSec, sessionState, hybridTextMmu = false) {
|
|
1930
|
+
let collapsedFlag = false;
|
|
1931
|
+
// Same wire cap as every other imaging path: the collapse buys tokens with
|
|
1932
|
+
// image blocks, and a request whose client images already fill the cap has
|
|
1933
|
+
// none left to spend. `historyGridTuning` floors the budget at 1, so without
|
|
1934
|
+
// this guard a full wire would still emit exactly one image — and 400.
|
|
1935
|
+
if (hybridTextMmu) {
|
|
1936
|
+
// Dynamic turns are handled by Text-MMU in hybrid mode.
|
|
1937
|
+
}
|
|
1938
|
+
else if (imageHeadroom(info) <= 0) {
|
|
1939
|
+
bumpPassthrough(info, 'image_budget');
|
|
1940
|
+
info.imageBudgetSkips = (info.imageBudgetSkips ?? 0) + 1;
|
|
1941
|
+
info.historyReason ??= 'too_many_images';
|
|
1942
|
+
}
|
|
1943
|
+
else if (Array.isArray(req.messages) && req.messages.length > 0) {
|
|
1944
|
+
const historyCpt = opts.charsPerToken !== undefined
|
|
1945
|
+
? o.charsPerToken
|
|
1946
|
+
: HISTORY_CHARS_PER_TOKEN;
|
|
1947
|
+
const horizon = Math.max(1, Math.floor(o.historyAmortizationHorizon));
|
|
1948
|
+
// Pass the symmetric warm-cache burn through to the history-collapse
|
|
1949
|
+
// gate as well. The slab gate alone got the symmetric treatment, which
|
|
1950
|
+
// let the history gate flip a session out of image mode even when
|
|
1951
|
+
// symmetric burn would have kept the slab gate in. Production data
|
|
1952
|
+
// 2026-05-23 showed three-turn sessions paying cache_create every
|
|
1953
|
+
// turn because the history gate ignored priorWarmImageTokens.
|
|
1954
|
+
const historyGeometry = historyGateGeometry(o, opts.cols !== undefined);
|
|
1955
|
+
const rates = gateRates(req, o.model);
|
|
1956
|
+
const historyProfitable = (text, _cols) => {
|
|
1957
|
+
// Gate with the same model profile used by the history renderer.
|
|
1958
|
+
if (isCompressionProfitableAmortized(text, historyGeometry.cols, undefined, historyCpt, horizon, o.priorWarmTokens, o.priorWarmImageTokens, true, historyGeometry.maxChars, historyGeometry, rates))
|
|
1959
|
+
return true;
|
|
1960
|
+
if (rates !== null && reqPromptTokensEst !== undefined) {
|
|
1961
|
+
const textTok = text.length / Math.max(1e-6, historyCpt);
|
|
1962
|
+
const imgTok = imageTokensCost(text, historyGeometry.cols, undefined, true, historyGeometry.maxChars, historyGeometry);
|
|
1963
|
+
if (imgTok < textTok) {
|
|
1964
|
+
const histCliffKey = `${o.model ?? ''}\0${reqTtlSec ?? ''}\0${info.sessionKey ?? info.firstUserSha8 ?? ''}\0history`;
|
|
1965
|
+
const stickyCliffAt = priceMode() === 'kosha' ? getAnthropicCliffSticky(histCliffKey) : undefined;
|
|
1966
|
+
if (stickyCliffAt !== undefined && reqPromptTokensEst > stickyCliffAt)
|
|
1967
|
+
return true;
|
|
1968
|
+
const upstreamSysTok = Math.ceil((info.origChars ?? 0) / Math.max(1, o.charsPerToken));
|
|
1969
|
+
const tailTok = estimateTailMsgTokens(req.messages, o.charsPerToken);
|
|
1970
|
+
const downstreamCachedTokens = Math.max(0, reqPromptTokensEst - upstreamSysTok - textTok - tailTok);
|
|
1971
|
+
const cliff = evaluateCliffAvoidance(o.model, {
|
|
1972
|
+
promptTokensBefore: reqPromptTokensEst,
|
|
1973
|
+
promptTokensAfter: Math.max(0, reqPromptTokensEst - (textTok - imgTok)),
|
|
1974
|
+
collapsedBaselineTokens: textTok,
|
|
1975
|
+
collapsedActualTokens: imgTok,
|
|
1976
|
+
downstreamCachedTokens,
|
|
1977
|
+
expectedOutputTokens: o.expectedOutputTokens,
|
|
1978
|
+
ttlSec: reqTtlSec,
|
|
1979
|
+
});
|
|
1980
|
+
if (cliff?.crossesCliff && cliff.netSingleTurnUsd > 0) {
|
|
1981
|
+
recordAnthropicCliffSticky(histCliffKey, cliff.cliffAt);
|
|
1982
|
+
info.cliffAvoided = { at: cliff.cliffAt, multiplier: cliff.multiplier, savedUsd: cliff.netSingleTurnUsd };
|
|
1983
|
+
return true;
|
|
1984
|
+
}
|
|
1985
|
+
}
|
|
1986
|
+
}
|
|
1987
|
+
return false;
|
|
1988
|
+
};
|
|
1989
|
+
// The slab needs no shield here: this path runs only when the slab did NOT
|
|
1990
|
+
// image (it stays as text in req.system). But project instructions do.
|
|
1991
|
+
// CLAUDE.md arrives in the FIRST user message wrapped in <system-reminder>,
|
|
1992
|
+
// so collapsing from the head images the user's rules on the first collapse
|
|
1993
|
+
// — they survive turn 1 as text, then silently become pixels mid-session.
|
|
1994
|
+
// Rules the model cannot read verbatim are rules it does not follow, so the
|
|
1995
|
+
// message carrying them is protected from collapse the same way the
|
|
1996
|
+
// non-collapse path already keeps <system-reminder> as text below.
|
|
1997
|
+
const protectedPrefix = firstMessageHasSystemReminder(req.messages) ? 1 : 0;
|
|
1998
|
+
const tuning = historyGridTuning(info, sessionState);
|
|
1999
|
+
const { messages: newMessages, info: histInfo } = await collapseHistory(req.messages, historyProfitable, {
|
|
2000
|
+
cols: historyGeometry.cols,
|
|
2001
|
+
protectedPrefix,
|
|
2002
|
+
reflow: o.reflow,
|
|
2003
|
+
style: historyGeometry.style,
|
|
2004
|
+
maxHeightPx: historyGeometry.maxHeightPx,
|
|
2005
|
+
pageChars: historyGeometry.maxChars,
|
|
2006
|
+
separateAdjacentToolPairs: o.separateAdjacentToolPairs,
|
|
2007
|
+
imageBudget: tuning.imageBudget,
|
|
2008
|
+
packFill: tuning.packFill,
|
|
2009
|
+
minFreezeStep: tuning.minFreezeStep,
|
|
2010
|
+
});
|
|
2011
|
+
// Atomic admission by weight. The collapse is one semantic group: applying
|
|
2012
|
+
// it means every collapsed message becomes pages, so a group that does not
|
|
2013
|
+
// fit the byte budget is not applied at all and the original text stands.
|
|
2014
|
+
// Rendering it first and discarding it costs CPU, which is the cheap half of
|
|
2015
|
+
// the trade: the alternative is estimating PNG size from character counts and
|
|
2016
|
+
// being wrong on the request that mattered.
|
|
2017
|
+
if (histInfo.collapsedTurns > 0 &&
|
|
2018
|
+
histInfo.collapsedImageBytes > imageByteHeadroom(info, o.maxImageBytes)) {
|
|
2019
|
+
bumpPassthrough(info, 'image_budget');
|
|
2020
|
+
info.imageByteSkips = (info.imageByteSkips ?? 0) + 1;
|
|
2021
|
+
info.historyReason = 'image_bytes';
|
|
2022
|
+
}
|
|
2023
|
+
else if (histInfo.collapsedTurns > 0) {
|
|
2024
|
+
recordFreezeStep(info.sessionKey ?? info.firstUserSha8, histInfo.freezeStep, o.model ? { model: o.model } : undefined);
|
|
2025
|
+
if (histInfo.freezeStep !== undefined)
|
|
2026
|
+
info.historyFreezeStep = histInfo.freezeStep;
|
|
2027
|
+
if (histInfo.budgetTrimmed)
|
|
2028
|
+
info.historyBudgetTrimmed = true;
|
|
2029
|
+
if (tuning.packFill)
|
|
2030
|
+
info.historyPackFill = true;
|
|
2031
|
+
if (o.separateAdjacentToolPairs)
|
|
2032
|
+
info.historySplitAdjacentPairs = true;
|
|
2033
|
+
req.messages = newMessages;
|
|
2034
|
+
info.collapsedTurns = histInfo.collapsedTurns;
|
|
2035
|
+
info.collapsedChars = histInfo.collapsedChars;
|
|
2036
|
+
info.collapsedImages = histInfo.collapsedImages;
|
|
2037
|
+
info.imageCount += histInfo.collapsedImages;
|
|
2038
|
+
info.imageBytes += histInfo.collapsedImageBytes;
|
|
2039
|
+
info.imagePixels = (info.imagePixels ?? 0) + histInfo.collapsedImagePixels;
|
|
2040
|
+
info.imageTokens = (info.imageTokens ?? 0) + histInfo.collapsedImageDims.reduce((s, d) => s + visionTokens(historyGeometry.pricing, d.width, d.height), 0);
|
|
2041
|
+
info.baselineImagedTokens = (info.baselineImagedTokens ?? 0) + Math.ceil(histInfo.collapsedChars / Math.max(1e-6, historyCpt));
|
|
2042
|
+
// Register the rendered (colored) history PNGs into the dashboard image ring
|
|
2043
|
+
// so they are visible, not merely counted. Every other image path feeds this.
|
|
2044
|
+
// imagePngs + imageDims must be pushed in lockstep (ring reads them parallel).
|
|
2045
|
+
(info.imagePngs ??= []).push(...histInfo.collapsedPngs);
|
|
2046
|
+
(info.imageDims ??= []).push(...histInfo.collapsedImageDims);
|
|
2047
|
+
info.droppedChars = (info.droppedChars ?? 0) + histInfo.droppedChars;
|
|
2048
|
+
for (const [cp, n] of histInfo.droppedCodepoints) {
|
|
2049
|
+
droppedCodepoints.set(cp, (droppedCodepoints.get(cp) ?? 0) + n);
|
|
2050
|
+
}
|
|
2051
|
+
info.historyReason = 'collapsed';
|
|
2052
|
+
info.historyTextChars = histInfo.collapsedChars;
|
|
2053
|
+
info.historyImageSha = await historyImageSha8(newMessages);
|
|
2054
|
+
bumpBucket(info, 'history', histInfo.collapsedChars);
|
|
2055
|
+
collapsedFlag = true;
|
|
2056
|
+
}
|
|
2057
|
+
else if (histInfo.reason) {
|
|
2058
|
+
info.historyReason = histInfo.reason;
|
|
2059
|
+
}
|
|
2060
|
+
}
|
|
2061
|
+
// tool_results are imaged on their own merits, not only when the slab is: a
|
|
2062
|
+
// tiny system with a large tool_result (e.g. a server-side thread continuation)
|
|
2063
|
+
// is exactly the request that needs it. After the collapse, per the invariant.
|
|
2064
|
+
const toolResultsImaged = o.compressToolResults
|
|
2065
|
+
? await compressToolResultsInPlace(req, info, o, denseGateGeometry(o), droppedCodepoints, hybridTextMmu
|
|
2066
|
+
? buildHybridToolOpticalGuard(req, info.sessionKey ?? info.firstUserSha8, sessionState?.cold ?? false)
|
|
2067
|
+
: undefined)
|
|
2068
|
+
: false;
|
|
2069
|
+
if (toolResultsImaged && !collapsedFlag && hybridTextMmu && info.imageCount > 0) {
|
|
2070
|
+
info.reason = 'hybrid_tool_optical';
|
|
2071
|
+
}
|
|
2072
|
+
applyPins(req, info, pins);
|
|
2073
|
+
info.outgoingTextChars = countOutgoingTextChars(req);
|
|
2074
|
+
// Ground truth, counted from the bytes we are about to send. The provider only
|
|
2075
|
+
// ever sees this number, so telemetry and any future headroom math must read it
|
|
2076
|
+
// and not the render counter. The collapse replaces whole messages, so a client
|
|
2077
|
+
// image sitting inside the collapsed range is counted in `nativeImages` but is
|
|
2078
|
+
// not on the wire, and only a count taken here sees that.
|
|
2079
|
+
//
|
|
2080
|
+
// This comment used to cite "95 rendered, 27 on the wire" as if the gap were a
|
|
2081
|
+
// property of the design. It was not. It was tool_result imaging running before
|
|
2082
|
+
// the collapse on the main path, so 68 renders were discarded together with the
|
|
2083
|
+
// messages that absorbed them. With the stages ordered correctly the same shape
|
|
2084
|
+
// measures 92 rendered and 92 on the wire.
|
|
2085
|
+
info.wireImages = countNativeImages(req.messages);
|
|
2086
|
+
if (nearByteLimit(info, o.maxImageBytes))
|
|
2087
|
+
info.imageBytesNearLimit = true;
|
|
2088
|
+
const outBody = new TextEncoder().encode(JSON.stringify(req));
|
|
2089
|
+
return { body: outBody, info, changed: collapsedFlag || toolResultsImaged };
|
|
2090
|
+
}
|
|
2091
|
+
/**
|
|
2092
|
+
* Rewrite a Messages API request body. Returns the new body (still JSON
|
|
2093
|
+
* bytes) plus diagnostic info. On any error, returns the original bytes
|
|
2094
|
+
* unchanged.
|
|
2095
|
+
*/
|
|
2096
|
+
function extractAnthropicLiveTailTexts(messages) {
|
|
2097
|
+
if (!Array.isArray(messages) || messages.length === 0)
|
|
2098
|
+
return [];
|
|
2099
|
+
const out = [];
|
|
2100
|
+
const last = messages[messages.length - 1];
|
|
2101
|
+
if (!last || typeof last !== 'object')
|
|
2102
|
+
return out;
|
|
2103
|
+
const isToolResultTurn = Array.isArray(last.content) &&
|
|
2104
|
+
last.content.some((blk) => blk && typeof blk === 'object' && blk.type === 'tool_result');
|
|
2105
|
+
// Only inspect messages[n - 2] when messages[n - 1] is a tool-response turn,
|
|
2106
|
+
// and ONLY pull tool_use names/arguments — never Turn t-1's user prompt prose.
|
|
2107
|
+
if (isToolResultTurn && messages.length >= 2) {
|
|
2108
|
+
const prev = messages[messages.length - 2];
|
|
2109
|
+
if (prev && typeof prev === 'object' && Array.isArray(prev.content)) {
|
|
2110
|
+
for (const blk of prev.content) {
|
|
2111
|
+
if (!blk || typeof blk !== 'object')
|
|
2112
|
+
continue;
|
|
2113
|
+
const b = blk;
|
|
2114
|
+
if (b.type === 'tool_use' && b.input !== undefined) {
|
|
2115
|
+
const s = typeof b.input === 'string' ? b.input : JSON.stringify(b.input);
|
|
2116
|
+
if (s)
|
|
2117
|
+
out.push(typeof b.name === 'string' ? `${b.name} ${s}` : s);
|
|
2118
|
+
}
|
|
2119
|
+
}
|
|
2120
|
+
}
|
|
2121
|
+
}
|
|
2122
|
+
else if (!isToolResultTurn && last.role === 'user' && messages.length >= 2) {
|
|
2123
|
+
// If a trailing user prompt immediately follows a tool_result message, surface any
|
|
2124
|
+
// active fault/stack snippet from that tool_result (never prior user prompt prose).
|
|
2125
|
+
const prev = messages[messages.length - 2];
|
|
2126
|
+
if (prev && typeof prev === 'object' && Array.isArray(prev.content)) {
|
|
2127
|
+
for (const blk of prev.content) {
|
|
2128
|
+
if (!blk || typeof blk !== 'object')
|
|
2129
|
+
continue;
|
|
2130
|
+
const b = blk;
|
|
2131
|
+
if (b.type === 'tool_result' && b.content !== undefined) {
|
|
2132
|
+
let s = '';
|
|
2133
|
+
if (typeof b.content === 'string') {
|
|
2134
|
+
s = b.content;
|
|
2135
|
+
}
|
|
2136
|
+
else if (Array.isArray(b.content)) {
|
|
2137
|
+
const parts = [];
|
|
2138
|
+
for (const sub of b.content) {
|
|
2139
|
+
if (sub && typeof sub === 'object' && typeof sub.text === 'string') {
|
|
2140
|
+
parts.push(sub.text);
|
|
2141
|
+
}
|
|
2142
|
+
}
|
|
2143
|
+
s = parts.join('\n');
|
|
2144
|
+
}
|
|
2145
|
+
const faultSnippet = extractFaultSignalSnippet(s);
|
|
2146
|
+
if (faultSnippet)
|
|
2147
|
+
out.push(faultSnippet);
|
|
2148
|
+
}
|
|
2149
|
+
}
|
|
2150
|
+
}
|
|
2151
|
+
}
|
|
2152
|
+
if (typeof last.content === 'string') {
|
|
2153
|
+
if (last.content.trim())
|
|
2154
|
+
out.push(last.content);
|
|
2155
|
+
return out;
|
|
2156
|
+
}
|
|
2157
|
+
if (!Array.isArray(last.content))
|
|
2158
|
+
return out;
|
|
2159
|
+
const promptTexts = [];
|
|
2160
|
+
for (const blk of last.content) {
|
|
2161
|
+
if (!blk || typeof blk !== 'object')
|
|
2162
|
+
continue;
|
|
2163
|
+
const b = blk;
|
|
2164
|
+
if (b.type === 'text' && typeof b.text === 'string' && b.text.trim()) {
|
|
2165
|
+
promptTexts.push(b.text);
|
|
2166
|
+
}
|
|
2167
|
+
else if (b.type === 'thinking' && typeof b.thinking === 'string' && b.thinking.trim()) {
|
|
2168
|
+
promptTexts.push(b.thinking);
|
|
2169
|
+
}
|
|
2170
|
+
else if (b.type === 'tool_use' && b.input !== undefined) {
|
|
2171
|
+
const s = typeof b.input === 'string' ? b.input : JSON.stringify(b.input);
|
|
2172
|
+
if (s)
|
|
2173
|
+
out.push(typeof b.name === 'string' ? `${b.name} ${s}` : s);
|
|
2174
|
+
}
|
|
2175
|
+
else if (b.type === 'tool_result' && b.content !== undefined) {
|
|
2176
|
+
let s = '';
|
|
2177
|
+
if (typeof b.content === 'string') {
|
|
2178
|
+
s = b.content;
|
|
2179
|
+
}
|
|
2180
|
+
else if (Array.isArray(b.content)) {
|
|
2181
|
+
const parts = [];
|
|
2182
|
+
for (const sub of b.content) {
|
|
2183
|
+
if (sub && typeof sub === 'object' && typeof sub.text === 'string') {
|
|
2184
|
+
parts.push(sub.text);
|
|
2185
|
+
}
|
|
2186
|
+
}
|
|
2187
|
+
s = parts.join('\n');
|
|
2188
|
+
}
|
|
2189
|
+
const faultSnippet = extractFaultSignalSnippet(s);
|
|
2190
|
+
if (faultSnippet)
|
|
2191
|
+
out.push(faultSnippet);
|
|
2192
|
+
}
|
|
2193
|
+
}
|
|
2194
|
+
for (const t of promptTexts)
|
|
2195
|
+
out.push(t);
|
|
2196
|
+
return out;
|
|
2197
|
+
}
|
|
2198
|
+
function appendAnthropicTailHydration(req, hydrationBlock) {
|
|
2199
|
+
if (!hydrationBlock)
|
|
2200
|
+
return;
|
|
2201
|
+
if (!Array.isArray(req.messages) || req.messages.length === 0)
|
|
2202
|
+
return;
|
|
2203
|
+
// Never walk backwards past an assistant/prefill turn into earlier cached user messages.
|
|
2204
|
+
const last = req.messages[req.messages.length - 1];
|
|
2205
|
+
if (!last || last.role !== 'user')
|
|
2206
|
+
return;
|
|
2207
|
+
if (typeof last.content === 'string') {
|
|
2208
|
+
last.content = last.content ? `${last.content}\n\n${hydrationBlock}` : hydrationBlock;
|
|
2209
|
+
return;
|
|
2210
|
+
}
|
|
2211
|
+
if (Array.isArray(last.content)) {
|
|
2212
|
+
last.content.push({ type: 'text', text: hydrationBlock });
|
|
2213
|
+
}
|
|
2214
|
+
}
|
|
2215
|
+
export async function transformRequest(body, opts = {}) {
|
|
2216
|
+
const profile = opts.model ? resolveGptProfile(opts.model) : undefined;
|
|
2217
|
+
const profileDefaults = profile
|
|
2218
|
+
? { cols: profile.stripCols, model: opts.model }
|
|
2219
|
+
: {};
|
|
2220
|
+
// Merge caller opts over DEFAULTS, but treat explicit `undefined` as "not
|
|
2221
|
+
// provided" so it falls through to the default. Without this, a caller that
|
|
2222
|
+
// passes `{ minToolResultChars: undefined }` (common when forwarding partial
|
|
2223
|
+
// options from upstream — e.g. an upstream gateway's handler) would silently disable the
|
|
2224
|
+
// tool_result text-passthrough gate and route everything through the
|
|
2225
|
+
// renderer.
|
|
2226
|
+
const definedOpts = Object.fromEntries(Object.entries(opts).filter(([, value]) => value !== undefined));
|
|
2227
|
+
const merged = { ...DEFAULTS, ...profileDefaults, ...definedOpts };
|
|
2228
|
+
for (const k of Object.keys(merged)) {
|
|
2229
|
+
if (merged[k] === undefined) {
|
|
2230
|
+
merged[k] =
|
|
2231
|
+
profileDefaults[k]
|
|
2232
|
+
?? DEFAULTS[k];
|
|
2233
|
+
}
|
|
2234
|
+
}
|
|
2235
|
+
const o = merged;
|
|
2236
|
+
const info = {
|
|
2237
|
+
compressed: false,
|
|
2238
|
+
origChars: 0,
|
|
2239
|
+
compressedChars: 0,
|
|
2240
|
+
imageCount: 0,
|
|
2241
|
+
imageBytes: 0,
|
|
2242
|
+
staticChars: 0,
|
|
2243
|
+
dynamicChars: 0,
|
|
2244
|
+
dynamicBlockCount: 0,
|
|
2245
|
+
droppedChars: 0,
|
|
2246
|
+
};
|
|
2247
|
+
// Per-request codepoint drop histogram. Merged from every render call
|
|
2248
|
+
// (static slab + reminder + tool_result compressions). Serialized to
|
|
2249
|
+
// `info.droppedCodepointsTop` at the end of transformRequest IF non-empty.
|
|
2250
|
+
const droppedCodepoints = new Map();
|
|
2251
|
+
if (!o.compress) {
|
|
2252
|
+
info.reason = 'compress=false';
|
|
2253
|
+
return { body, info };
|
|
2254
|
+
}
|
|
2255
|
+
let req;
|
|
2256
|
+
try {
|
|
2257
|
+
req = JSON.parse(new TextDecoder().decode(body));
|
|
2258
|
+
}
|
|
2259
|
+
catch (e) {
|
|
2260
|
+
info.reason = `parse_error: ${e.message}`;
|
|
2261
|
+
return { body, info };
|
|
2262
|
+
}
|
|
2263
|
+
// Every stage below — image pricing, pin folding, history collapse — reads
|
|
2264
|
+
// `m.content` or `m.role` off each element, so a non-object element throws a
|
|
2265
|
+
// TypeError out of transformRequest and the proxy answers 502 for a body the
|
|
2266
|
+
// upstream API would have rejected with its own 400. Bail to the untouched
|
|
2267
|
+
// bytes instead, exactly as parse_error above does: the body is forwarded as
|
|
2268
|
+
// the client sent it and the real error comes back from the real API.
|
|
2269
|
+
if (Array.isArray(req.messages) && req.messages.some((m) => !m || typeof m !== 'object')) {
|
|
2270
|
+
info.reason = 'invalid_messages';
|
|
2271
|
+
return { body, info };
|
|
2272
|
+
}
|
|
2273
|
+
const reqTtlSec = requestCacheTtlSec(req);
|
|
2274
|
+
const reqPromptTokensEst = Math.ceil(body.byteLength / Math.max(1, o.charsPerToken));
|
|
2275
|
+
// Price the caller's OWN images before we rewrite anything: they occupy the
|
|
2276
|
+
// same wire cap we are about to spend from. Counted once, here, because every
|
|
2277
|
+
// later path (slab, tool_results, history) rewrites content in place.
|
|
2278
|
+
info.nativeImages = countNativeImages(req.messages);
|
|
2279
|
+
info.nativeImageBytes = countNativeImageBytes(req.messages);
|
|
2280
|
+
// 0. User-pinned instructions. Fold the transcript's pin commands, then remove
|
|
2281
|
+
// them from the outbound copy — the client's own transcript is untouched, so
|
|
2282
|
+
// the next request still carries every command and re-derives the same state.
|
|
2283
|
+
// The surviving pins are re-emitted at the very tail (applyPins, below), after
|
|
2284
|
+
// every cache breakpoint, where the model reads them last.
|
|
2285
|
+
// `pinsRewrote` is what the early-exit paths below test: when either the
|
|
2286
|
+
// strip or the tail append changed `req`, the original bytes no longer
|
|
2287
|
+
// describe the request and must not be the ones forwarded.
|
|
2288
|
+
// Strip and append are one move, so both are skipped unless the tail can
|
|
2289
|
+
// take the block; otherwise the strip would delete the rules outright.
|
|
2290
|
+
let pins = [];
|
|
2291
|
+
let pinsRewrote = false;
|
|
2292
|
+
if (Array.isArray(req.messages) && canAppendPinBlock(req.messages)) {
|
|
2293
|
+
try {
|
|
2294
|
+
pins = foldPins(req.messages, req.system);
|
|
2295
|
+
const stripped = stripPinCommands(req.messages);
|
|
2296
|
+
// System too: OpenCode inlines AGENTS.md there, so that is where the
|
|
2297
|
+
// commands are. Must run BEFORE step 1 reads the system text, or the
|
|
2298
|
+
// stripped lines get baked into the rendered slab.
|
|
2299
|
+
const strippedSystem = stripPinCommandsFromSystem(req.system);
|
|
2300
|
+
pinsRewrote = pins.length > 0
|
|
2301
|
+
|| strippedSystem !== undefined
|
|
2302
|
+
|| stripped.length !== req.messages.length
|
|
2303
|
+
|| stripped.some((m, i) => m !== req.messages[i]);
|
|
2304
|
+
req.messages = stripped;
|
|
2305
|
+
if (strippedSystem !== undefined)
|
|
2306
|
+
req.system = strippedSystem;
|
|
2307
|
+
}
|
|
2308
|
+
catch (e) {
|
|
2309
|
+
// A malformed message must not fail the request: pins are an optimization,
|
|
2310
|
+
// the untouched body is still valid.
|
|
2311
|
+
pins = [];
|
|
2312
|
+
pinsRewrote = false;
|
|
2313
|
+
info.pinError = String(e?.message ?? e);
|
|
2314
|
+
}
|
|
2315
|
+
}
|
|
2316
|
+
const effectiveImageCompress = o.imageCompress && o.stageToggles?.optical !== false;
|
|
2317
|
+
const textHygieneActive = isTextHygieneActive(o.textHygiene);
|
|
2318
|
+
const earlyFirstUser = firstUserText(req);
|
|
2319
|
+
const resolvedSessionKey = await applyClientSessionIdentity(info, earlyFirstUser, o);
|
|
2320
|
+
const sessionState = resolvedSessionKey
|
|
2321
|
+
? noteHistoryRequest(resolvedSessionKey, { model: o.model })
|
|
2322
|
+
: { cold: false, minFreezeStep: 0 };
|
|
2323
|
+
const opticalHistoryPolicy = effectiveImageCompress
|
|
2324
|
+
? resolveOpticalHistoryPolicy({
|
|
2325
|
+
opticalMode: o.opticalMode,
|
|
2326
|
+
collapseHistory: opts.collapseHistory === true ? true : undefined,
|
|
2327
|
+
model: o.model,
|
|
2328
|
+
estPromptTokens: Math.ceil(Math.max(0, body.byteLength - Math.ceil((info.nativeImageBytes ?? 0) * 4 / 3)) /
|
|
2329
|
+
Math.max(1, o.charsPerToken)),
|
|
2330
|
+
textHygieneActive,
|
|
2331
|
+
sessionKey: resolvedSessionKey,
|
|
2332
|
+
sessionCold: sessionState.cold,
|
|
2333
|
+
})
|
|
2334
|
+
: 'full';
|
|
2335
|
+
const hybridTextMmu = effectiveImageCompress && opticalHistoryPolicy === 'hybrid';
|
|
2336
|
+
const hygieneStats = textHygieneActive
|
|
2337
|
+
? applyAnthropicTextHygiene(req, {
|
|
2338
|
+
foldLogs: !effectiveImageCompress || hybridTextMmu,
|
|
2339
|
+
deepTextCompact: !effectiveImageCompress || hybridTextMmu,
|
|
2340
|
+
cleanUserPayloads: o.cleanUserPayloads === true,
|
|
2341
|
+
enableTscg: hybridTextMmu ? false : o.stageToggles?.tscg,
|
|
2342
|
+
enableToon: o.stageToggles?.toon,
|
|
2343
|
+
enableAcdc: o.stageToggles?.acdc,
|
|
2344
|
+
enableCasi: (!effectiveImageCompress || hybridTextMmu) && o.stageToggles?.casi !== false && typeof opts.keepSharp !== 'function',
|
|
2345
|
+
enableLsm: o.stageToggles?.lsm,
|
|
2346
|
+
enableMmu: o.stageToggles?.mmu,
|
|
2347
|
+
enableSkillLinker: hybridTextMmu ? false : o.stageToggles?.skillLinker,
|
|
2348
|
+
aggressiveToon: resolveTextHygieneMode(o.textHygiene) === 'on',
|
|
2349
|
+
model: o.model,
|
|
2350
|
+
expectedOutputTokens: o.expectedOutputTokens,
|
|
2351
|
+
rawBodyBytes: body.byteLength,
|
|
2352
|
+
nativeImageBytes: Math.ceil((info.nativeImageBytes ?? 0) * 4 / 3),
|
|
2353
|
+
ttlSec: reqTtlSec,
|
|
2354
|
+
sessionKey: resolvedSessionKey,
|
|
2355
|
+
firstUserText: earlyFirstUser,
|
|
2356
|
+
sessionCacheCold: sessionState.cold,
|
|
2357
|
+
liveTailTexts: (!effectiveImageCompress || hybridTextMmu) ? extractAnthropicLiveTailTexts(req.messages) : undefined,
|
|
2358
|
+
appendTailHydration: (!effectiveImageCompress || hybridTextMmu) ? (blk) => appendAnthropicTailHydration(req, blk) : undefined,
|
|
2359
|
+
})
|
|
2360
|
+
: undefined;
|
|
2361
|
+
if (hygieneStats?.changed || hygieneStats?.tailHydrated) {
|
|
2362
|
+
info.textHygieneSavedChars = hygieneStats.savedChars;
|
|
2363
|
+
info.textHygieneSavedTokens = hygieneStats.savedTokens;
|
|
2364
|
+
info.textHygieneBlocks = hygieneStats.blocks;
|
|
2365
|
+
info.textHygieneStages = [...hygieneStats.stages];
|
|
2366
|
+
if (hygieneStats.cliffAvoided)
|
|
2367
|
+
info.cliffAvoided = hygieneStats.cliffAvoided;
|
|
2368
|
+
}
|
|
2369
|
+
if (!effectiveImageCompress) {
|
|
2370
|
+
if (pinsRewrote)
|
|
2371
|
+
applyPins(req, info, pins);
|
|
2372
|
+
if (hygieneStats?.changed) {
|
|
2373
|
+
info.compressed = true;
|
|
2374
|
+
info.reason = 'text_hygiene';
|
|
2375
|
+
info.outgoingTextChars = countOutgoingTextChars(req);
|
|
2376
|
+
return { body: new TextEncoder().encode(JSON.stringify(req)), info };
|
|
2377
|
+
}
|
|
2378
|
+
if (hygieneStats?.tailHydrated) {
|
|
2379
|
+
info.reason = 'mmu_hydrate';
|
|
2380
|
+
info.outgoingTextChars = countOutgoingTextChars(req);
|
|
2381
|
+
return { body: new TextEncoder().encode(JSON.stringify(req)), info };
|
|
2382
|
+
}
|
|
2383
|
+
info.reason = 'image_disabled';
|
|
2384
|
+
if (pinsRewrote) {
|
|
2385
|
+
info.outgoingTextChars = countOutgoingTextChars(req);
|
|
2386
|
+
return { body: new TextEncoder().encode(JSON.stringify(req)), info };
|
|
2387
|
+
}
|
|
2388
|
+
return { body, info };
|
|
2389
|
+
}
|
|
2390
|
+
seedGateRates(req, o.model, body.byteLength, o.charsPerToken);
|
|
2391
|
+
// 1. Pull system text out. Split into:
|
|
2392
|
+
// - billingLine: Claude Code's per-turn random header (must NOT be cached).
|
|
2393
|
+
// - dynamicText: <env>/<context>/... blocks (per-turn, kept as text).
|
|
2394
|
+
// - staticText: everything else (cacheable, goes into the image).
|
|
2395
|
+
const systemStaticCacheControl = lastStaticSystemCacheControl(req.system);
|
|
2396
|
+
const { text: rawSysText, kept: rawSysRemainder } = extractSystemText(req.system);
|
|
2397
|
+
// The identity block does not always carry cache_control — the CLI entrypoint
|
|
2398
|
+
// marks only the big instruction block — so extractSystemText holds it in
|
|
2399
|
+
// `kept`, which is re-emitted AFTER the env text. That is too late: the
|
|
2400
|
+
// endpoint classifies on the leading block and answers an opaque
|
|
2401
|
+
// `429 rate_limit_error: "Error"` when it does not lead (#149). Lift it out
|
|
2402
|
+
// here so the assembly below can put it back in front.
|
|
2403
|
+
const { identity: keptIdentity, kept: sysRemainder } = liftIdentityBlock(rawSysRemainder);
|
|
2404
|
+
let { kept: billingLine, body: sysBody } = stripBillingLine(rawSysText);
|
|
2405
|
+
// When another system block carries cache_control, the billing block is
|
|
2406
|
+
// un-marked, so extractSystemText routes it to `kept` and the strip above
|
|
2407
|
+
// never sees it — sysRemainder would re-emit it into req.system, inside the
|
|
2408
|
+
// cached span. Excise it from the remainder blocks too.
|
|
2409
|
+
if (Array.isArray(sysRemainder)) {
|
|
2410
|
+
for (let i = sysRemainder.length - 1; i >= 0; i--) {
|
|
2411
|
+
const blk = sysRemainder[i];
|
|
2412
|
+
if (!blk || blk.type !== 'text' || typeof blk.text !== 'string')
|
|
2413
|
+
continue;
|
|
2414
|
+
const r = stripBillingLine(blk.text);
|
|
2415
|
+
if (r.kept === null)
|
|
2416
|
+
continue;
|
|
2417
|
+
billingLine ??= r.kept; // never emit the per-turn line twice
|
|
2418
|
+
if (r.body.trim() === '')
|
|
2419
|
+
sysRemainder.splice(i, 1);
|
|
2420
|
+
else
|
|
2421
|
+
sysRemainder[i] = { ...blk, text: r.body };
|
|
2422
|
+
}
|
|
2423
|
+
}
|
|
2424
|
+
// `# Environment` (working dir, git status, model ID) churns per turn but has
|
|
2425
|
+
// no XML wrapper, so the static/dynamic split would bake it into the slab PNG
|
|
2426
|
+
// and a one-file edit would re-render the whole prefix. Pull it out first; it
|
|
2427
|
+
// re-enters below as plain system text in its original position (NOT relocated
|
|
2428
|
+
// into the message stream — that surfaced a <system-reminder> in the
|
|
2429
|
+
// conversation as if the user had written it).
|
|
2430
|
+
const { kept: envMarkdown, body: sysBodyNoEnv } = stripMarkdownEnvSection(sysBody);
|
|
2431
|
+
const splitSystem = splitStaticDynamic(sysBodyNoEnv);
|
|
2432
|
+
let staticText = splitSystem.staticText;
|
|
2433
|
+
const { dynamicText, blockCount: dynBlocks, unknownTags, staticTagContents } = splitSystem;
|
|
2434
|
+
const inlineIdentity = OAUTH_IDENTITIES.find((id) => staticText.startsWith(id));
|
|
2435
|
+
if (inlineIdentity) {
|
|
2436
|
+
staticText = staticText.slice(inlineIdentity.length).replace(/^\s+/, '');
|
|
2437
|
+
}
|
|
2438
|
+
const preservedIdentity = keptIdentity ?? inlineIdentity;
|
|
2439
|
+
info.staticChars = staticText.length;
|
|
2440
|
+
info.dynamicBlockCount = dynBlocks;
|
|
2441
|
+
if (unknownTags.length > 0)
|
|
2442
|
+
info.unknownStaticTags = unknownTags;
|
|
2443
|
+
// Parse env fields out of the dynamic slab — telemetry only, never mutates.
|
|
2444
|
+
const env = extractEnvFields(dynamicText);
|
|
2445
|
+
if (Object.keys(env).length > 0)
|
|
2446
|
+
info.env = env;
|
|
2447
|
+
// Privacy-safe fingerprints that don't depend on tool docs (computed
|
|
2448
|
+
// here so they're available even if we below_min_chars out below).
|
|
2449
|
+
// Keep canonical pre-hygiene firstUserSha8 so cleanUserPayloads never splits
|
|
2450
|
+
// session state between noteHistoryRequest/MMU and noteCacheOutcome/freezeStep.
|
|
2451
|
+
if (!info.firstUserSha8 || !info.sessionKey) {
|
|
2452
|
+
await applyClientSessionIdentity(info, firstUserText(req), o);
|
|
2453
|
+
}
|
|
2454
|
+
// Canary: slab tags whose content churns within a session bust the image
|
|
2455
|
+
// cache every turn — report them regardless of the hardcoded lists.
|
|
2456
|
+
if (staticTagContents.size > 0) {
|
|
2457
|
+
const churning = observeStaticTagChurn(info.sessionKey ?? info.firstUserSha8 ?? 'global', staticTagContents);
|
|
2458
|
+
if (churning.length > 0)
|
|
2459
|
+
info.churningStaticTags = churning;
|
|
2460
|
+
}
|
|
2461
|
+
info.dynamicChars = dynamicText.length;
|
|
2462
|
+
// 2. Move tool docs into the imaged "Tool Reference", stubbing originals.
|
|
2463
|
+
// Imaged (not text) because that IS the compression — descriptions and
|
|
2464
|
+
// schema annotations ride at image token rates, mirroring the GPT path.
|
|
2465
|
+
// Tool docs are static per session, so the slab image stays byte-stable
|
|
2466
|
+
// and cache-friendly. Each stub description cites its own heading
|
|
2467
|
+
// ("## Tool: <name>") so the model can link stub → full doc
|
|
2468
|
+
// deterministically.
|
|
2469
|
+
let toolDocsText = '';
|
|
2470
|
+
let toolsRewritten;
|
|
2471
|
+
if (o.compressTools && Array.isArray(req.tools) && req.tools.length > 0) {
|
|
2472
|
+
const docs = [];
|
|
2473
|
+
toolsRewritten = req.tools.map((t) => {
|
|
2474
|
+
// #43: native server-side tools (versioned `type`, e.g. advisor_20260301,
|
|
2475
|
+
// web_search_20250305) have a fixed API schema that rejects a `description`
|
|
2476
|
+
// field on the entry ("Extra inputs are not permitted" → 400). Only
|
|
2477
|
+
// client-defined tools — no `type`, or the explicit type:"custom" shape —
|
|
2478
|
+
// accept description/input_schema, so everything else passes through
|
|
2479
|
+
// byte-identical and stays out of the imaged reference (its docs live
|
|
2480
|
+
// server-side; there is nothing to compress). Mirrors the OpenAI-path
|
|
2481
|
+
// guard (openai.ts isFunctionTool).
|
|
2482
|
+
if (t.type !== undefined && t.type !== 'custom')
|
|
2483
|
+
return t;
|
|
2484
|
+
// Anthropic excludes deferred tool definitions from model context until
|
|
2485
|
+
// selected by tool search; imaging their docs would defeat that behavior.
|
|
2486
|
+
if (t.defer_loading === true)
|
|
2487
|
+
return t;
|
|
2488
|
+
docs.push(renderToolDoc(t));
|
|
2489
|
+
// tools[] keeps the annotation-STRIPPED schema: structure (type/properties/
|
|
2490
|
+
// required/enum/items) stays for Anthropic's tool-use validator — a bare
|
|
2491
|
+
// {type:'object'} stub caused 400s on non-interactive turns where Anthropic
|
|
2492
|
+
// deep-validates with no prior tool_use history to short-circuit. The
|
|
2493
|
+
// stripped annotations (description/title/examples/default) ride in the
|
|
2494
|
+
// imaged reference instead, at image rates. If stripping yields no
|
|
2495
|
+
// structural keys, keep the ORIGINAL schema untouched: it's tiny without
|
|
2496
|
+
// properties, and a bare stub is the riskier trade.
|
|
2497
|
+
let schema = t.input_schema;
|
|
2498
|
+
if (schema && typeof schema === 'object') {
|
|
2499
|
+
const stripped = stripSchemaDescriptions(schema, 0);
|
|
2500
|
+
if (stripped && typeof stripped === 'object' && schemaHasStructure(stripped)) {
|
|
2501
|
+
schema = stripped;
|
|
2502
|
+
}
|
|
2503
|
+
}
|
|
2504
|
+
// Read-before-Edit precondition rides as LIVE TEXT, not imaged: the CLI
|
|
2505
|
+
// rejects Edit/Write on any existing file not Read in THIS session's
|
|
2506
|
+
// process, and the rule lost salience once full tool docs moved into the
|
|
2507
|
+
// imaged reference (read-gate audit, 2026-07-03). Three tools only, no
|
|
2508
|
+
// banned wording — stays clear of the per-tool-stub repetition pattern
|
|
2509
|
+
// that tripped reasoning_extraction (see wording note below).
|
|
2510
|
+
const readFirstNote = READ_FIRST_TOOLS.has(t.name ?? '')
|
|
2511
|
+
? ' Requires a Read of the same file earlier in THIS session when the file' +
|
|
2512
|
+
' already exists — the call is rejected otherwise; file content recalled' +
|
|
2513
|
+
' from imaged or prior-session context does not satisfy this.'
|
|
2514
|
+
: '';
|
|
2515
|
+
return {
|
|
2516
|
+
...t,
|
|
2517
|
+
// Wording note (do NOT reintroduce "system prompt"/"authoritative" — same ban
|
|
2518
|
+
// as the imaged-slab banner below): a stub citing "...the Tool Reference
|
|
2519
|
+
// section of the system prompt", repeated once per tool, retripped Anthropic's
|
|
2520
|
+
// reasoning_extraction refusal (stop_reason: "refusal" → Claude Code fell back
|
|
2521
|
+
// to claude-opus-4-8 immediately on cold start, 2026-07-02). The reference
|
|
2522
|
+
// block's own header says where the docs live; the stub only needs the heading.
|
|
2523
|
+
description: `ⓘ Full docs: see "## Tool: ${t.name ?? '?'}" in the Tool Reference section.${readFirstNote}`,
|
|
2524
|
+
...(schema !== undefined ? { input_schema: schema } : {}),
|
|
2525
|
+
};
|
|
2526
|
+
});
|
|
2527
|
+
toolDocsText = docs.join('\n\n');
|
|
2528
|
+
info.toolDocsChars = toolDocsText.length;
|
|
2529
|
+
}
|
|
2530
|
+
// Static slab + Tool Reference go into the renderer; dynamic slab and billing
|
|
2531
|
+
// line stay as plain text so the cache key (= image bytes) is stable across
|
|
2532
|
+
// turns. The reference header carries the same first-party provenance framing
|
|
2533
|
+
// that defused the imaged-slab banner refusal (169521c): inkling names itself
|
|
2534
|
+
// as the author of the relocation so the block reads as this session's own
|
|
2535
|
+
// config, not a replayed/extracted prompt.
|
|
2536
|
+
const toolReferenceText = toolDocsText
|
|
2537
|
+
? '=== TOOL REFERENCE ===\n' +
|
|
2538
|
+
"fiche (this user's local proxy) moved the full tool documentation for this" +
|
|
2539
|
+
' session here to reduce token cost. Each tool in the tools list carries a short' +
|
|
2540
|
+
' stub description pointing here; the entry under the matching' +
|
|
2541
|
+
' "## Tool: <name>" heading below is the complete description for that tool.\n\n' +
|
|
2542
|
+
toolDocsText +
|
|
2543
|
+
'\n=== END TOOL REFERENCE ==='
|
|
2544
|
+
: '';
|
|
2545
|
+
const combinedRaw = [staticText, toolReferenceText]
|
|
2546
|
+
.filter((s) => s.length > 0)
|
|
2547
|
+
.join('\n\n');
|
|
2548
|
+
// Compact then reflow before the gate; gate/renderer/paging all see the same text.
|
|
2549
|
+
// origChars anchored to raw length — that's what Anthropic would have billed.
|
|
2550
|
+
const combined = maybeReflow(compactSlabWhitespace(combinedRaw), o.reflow);
|
|
2551
|
+
info.origChars = combinedRaw.length;
|
|
2552
|
+
info.compressedChars = 0;
|
|
2553
|
+
if (combined)
|
|
2554
|
+
info.systemSha8 = await sha8(combined);
|
|
2555
|
+
if (combined.length < o.minCompressChars) {
|
|
2556
|
+
info.reason = `below_min_chars (${combined.length} < ${o.minCompressChars})`;
|
|
2557
|
+
// Even with a static slab below the gate, message history may still be
|
|
2558
|
+
// collapsable. Run history collapse on the in-memory request so
|
|
2559
|
+
// production Codex traffic (tiny system, huge messages) still benefits.
|
|
2560
|
+
// If history collapses, we flip `info.compressed = true` and let the
|
|
2561
|
+
// library wrapper return reason='applied'; otherwise this still
|
|
2562
|
+
// populates `outgoingTextChars` for the regression denominator.
|
|
2563
|
+
const finalized = await runHistoryCollapseAndFinalize(req, info, o, opts, droppedCodepoints, pins, reqPromptTokensEst, reqTtlSec, sessionState, hybridTextMmu);
|
|
2564
|
+
if (finalized.changed || hygieneStats?.changed) {
|
|
2565
|
+
info.compressed = true;
|
|
2566
|
+
if (!finalized.changed && hygieneStats?.changed)
|
|
2567
|
+
info.reason = 'text_hygiene';
|
|
2568
|
+
return { body: finalized.body, info };
|
|
2569
|
+
}
|
|
2570
|
+
if (hygieneStats?.tailHydrated) {
|
|
2571
|
+
info.reason = 'mmu_hydrate';
|
|
2572
|
+
return { body: finalized.body, info };
|
|
2573
|
+
}
|
|
2574
|
+
// `body` is the original bytes. If the pin pass edited `req`, those bytes
|
|
2575
|
+
// describe a request we are no longer sending, so forwarding them would put
|
|
2576
|
+
// the raw `@inkling pin` line back and drop the tail block.
|
|
2577
|
+
return { body: pinsRewrote ? finalized.body : body, info };
|
|
2578
|
+
}
|
|
2579
|
+
// Anthropic's system field rejects image blocks, so without a user turn there
|
|
2580
|
+
// is nowhere valid to attach the slab images. Strip any billing line from
|
|
2581
|
+
// req.system (so it still leaves via HTTP header), keep staticText & tools
|
|
2582
|
+
// intact, and skip slab rendering rather than emitting dangling pointers.
|
|
2583
|
+
const firstUserIdxPre = (req.messages ?? []).findIndex((m) => m.role === 'user');
|
|
2584
|
+
if (firstUserIdxPre < 0) {
|
|
2585
|
+
if (billingLine) {
|
|
2586
|
+
info.billingLine = billingLine;
|
|
2587
|
+
const preservedSys = [];
|
|
2588
|
+
if (preservedIdentity)
|
|
2589
|
+
preservedSys.push({ type: 'text', text: preservedIdentity });
|
|
2590
|
+
if (staticText)
|
|
2591
|
+
preservedSys.push({ type: 'text', text: staticText });
|
|
2592
|
+
if (dynamicText)
|
|
2593
|
+
preservedSys.push({ type: 'text', text: dynamicText });
|
|
2594
|
+
if (envMarkdown)
|
|
2595
|
+
preservedSys.push({ type: 'text', text: envMarkdown });
|
|
2596
|
+
if (Array.isArray(sysRemainder))
|
|
2597
|
+
preservedSys.push(...sysRemainder);
|
|
2598
|
+
req.system = preservedSys.length > 0 ? preservedSys : undefined;
|
|
2599
|
+
}
|
|
2600
|
+
info.reason = 'no_user_message';
|
|
2601
|
+
const finalized = await runHistoryCollapseAndFinalize(req, info, o, opts, droppedCodepoints, pins, reqPromptTokensEst, reqTtlSec, sessionState, hybridTextMmu);
|
|
2602
|
+
if (finalized.changed || hygieneStats?.changed) {
|
|
2603
|
+
info.compressed = true;
|
|
2604
|
+
if (!finalized.changed && hygieneStats?.changed)
|
|
2605
|
+
info.reason = 'text_hygiene';
|
|
2606
|
+
}
|
|
2607
|
+
else if (hygieneStats?.tailHydrated) {
|
|
2608
|
+
info.reason = 'mmu_hydrate';
|
|
2609
|
+
}
|
|
2610
|
+
return {
|
|
2611
|
+
body: finalized.changed || pinsRewrote || hygieneStats?.changed || hygieneStats?.tailHydrated || billingLine !== null ? finalized.body : body,
|
|
2612
|
+
info,
|
|
2613
|
+
};
|
|
2614
|
+
}
|
|
2615
|
+
// The wire cap guards even the slab. Imaging it is our biggest single win, but
|
|
2616
|
+
// a request whose client images already fill the provider's cap has no image
|
|
2617
|
+
// left to spend: emitting one anyway turns a large-but-valid request into a
|
|
2618
|
+
// hard 400. Degrade to plain text and say why.
|
|
2619
|
+
if (imageHeadroom(info) <= 0) {
|
|
2620
|
+
info.reason = 'image_budget';
|
|
2621
|
+
bumpPassthrough(info, 'image_budget');
|
|
2622
|
+
info.imageBudgetSkips = (info.imageBudgetSkips ?? 0) + 1;
|
|
2623
|
+
const finalized = await runHistoryCollapseAndFinalize(req, info, o, opts, droppedCodepoints, pins, reqPromptTokensEst, reqTtlSec, sessionState, hybridTextMmu);
|
|
2624
|
+
if (hygieneStats?.changed && !finalized.changed) {
|
|
2625
|
+
info.compressed = true;
|
|
2626
|
+
info.reason = 'text_hygiene';
|
|
2627
|
+
}
|
|
2628
|
+
else if (hygieneStats?.tailHydrated && !finalized.changed) {
|
|
2629
|
+
info.reason = 'mmu_hydrate';
|
|
2630
|
+
}
|
|
2631
|
+
return { body: pinsRewrote || finalized.changed || hygieneStats?.changed || hygieneStats?.tailHydrated ? finalized.body : body, info };
|
|
2632
|
+
}
|
|
2633
|
+
// Break-even check guards even the slab (rare edge: tiny tool docs + tiny slab < 10k chars).
|
|
2634
|
+
const denseGeo = denseGateGeometry(o);
|
|
2635
|
+
// Use slab cpt (2.0) unless host pinned charsPerToken explicitly.
|
|
2636
|
+
const slabCpt = opts.charsPerToken !== undefined
|
|
2637
|
+
? o.charsPerToken
|
|
2638
|
+
: SLAB_CHARS_PER_TOKEN;
|
|
2639
|
+
// Shrink canvas to longest actual line — pure function of (text, cols) so the
|
|
2640
|
+
// cache prefix stays byte-identical across turns. The banner sets a natural width floor.
|
|
2641
|
+
const reflowNoteImg = o.reflow
|
|
2642
|
+
? ' The glyph ↵ (U+21B5) marks an original hard line break in content — treat as a real newline.'
|
|
2643
|
+
: '';
|
|
2644
|
+
// Wording note (do NOT reintroduce "system prompt"/"authoritative"): a user-turn
|
|
2645
|
+
// banner announcing "SYSTEM PROMPT ... treat as authoritative system instructions"
|
|
2646
|
+
// tripped Anthropic's reasoning_extraction refusal (reads as a replayed/extracted
|
|
2647
|
+
// prompt -> model-cloning heuristic) and forced a fallback-model switch. First-party
|
|
2648
|
+
// provenance framing below keeps obedience without the extraction signature.
|
|
2649
|
+
const imageInstructionHeader = '=================== SESSION CONFIGURATION PAGES ===================\n' +
|
|
2650
|
+
"fiche (this user's local proxy) rendered this session's configuration" +
|
|
2651
|
+
' into the following images to reduce token cost. Read the pages carefully and follow them as' +
|
|
2652
|
+
' your operating instructions for this session.' +
|
|
2653
|
+
' For exact identifiers, paths, hashes, version strings, and numbers, use the adjacent' +
|
|
2654
|
+
' exact-value factsheet; if a value was only visible in an image and is not in that factsheet,' +
|
|
2655
|
+
' do not guess it — say it is not safe to quote from the image and re-read the source text.' +
|
|
2656
|
+
reflowNoteImg +
|
|
2657
|
+
'\n====================== BEGIN RENDERED CONTEXT ======================\n';
|
|
2658
|
+
const combinedWithHeader = imageInstructionHeader + combined;
|
|
2659
|
+
// Shrink the canvas to the longest actual line in what we'll *render*,
|
|
2660
|
+
// so the gate's prediction and the renderer's output agree at the smallest
|
|
2661
|
+
// legible width. The banner above sets the natural floor — no separate
|
|
2662
|
+
// minWidth knob needed.
|
|
2663
|
+
const slabCols = shrinkColsToContent(combinedWithHeader, o.cols, 1, denseGeo.style.font);
|
|
2664
|
+
const slabRates = gateRates(req, o.model);
|
|
2665
|
+
const slabGateEval = evalCompressionProfitability(combinedWithHeader, slabCols, undefined, slabCpt, o.priorWarmTokens, o.priorWarmImageTokens, false, // already shrunk — don't double-shrink
|
|
2666
|
+
denseGeo, slabRates);
|
|
2667
|
+
let slabProfitable = slabGateEval?.profitable ?? false;
|
|
2668
|
+
if (slabGateEval && !slabProfitable && slabRates !== null) {
|
|
2669
|
+
const promptBefore = Math.max(slabGateEval.textTokens, reqPromptTokensEst);
|
|
2670
|
+
const slabCliffKey = `${o.model ?? ''}\0${reqTtlSec ?? ''}\0${info.sessionKey ?? info.firstUserSha8 ?? ''}\0${info.systemSha8 ?? ''}`;
|
|
2671
|
+
const stickyCliffAt = priceMode() === 'kosha' ? getAnthropicCliffSticky(slabCliffKey) : undefined;
|
|
2672
|
+
if (stickyCliffAt !== undefined && promptBefore > stickyCliffAt) {
|
|
2673
|
+
slabProfitable = true;
|
|
2674
|
+
}
|
|
2675
|
+
else {
|
|
2676
|
+
const promptAfter = Math.max(0, promptBefore - (slabGateEval.textTokens - slabGateEval.imageTokens));
|
|
2677
|
+
const tailTok = estimateTailMsgTokens(req.messages, o.charsPerToken);
|
|
2678
|
+
const downstreamCachedTokens = Math.max(0, promptBefore - slabGateEval.textTokens - tailTok);
|
|
2679
|
+
const cliff = evaluateCliffAvoidance(o.model, {
|
|
2680
|
+
promptTokensBefore: promptBefore,
|
|
2681
|
+
promptTokensAfter: promptAfter,
|
|
2682
|
+
collapsedBaselineTokens: slabGateEval.textTokens,
|
|
2683
|
+
collapsedActualTokens: slabGateEval.imageTokens,
|
|
2684
|
+
downstreamCachedTokens,
|
|
2685
|
+
expectedOutputTokens: o.expectedOutputTokens,
|
|
2686
|
+
ttlSec: reqTtlSec,
|
|
2687
|
+
});
|
|
2688
|
+
if (cliff?.crossesCliff && cliff.netSingleTurnUsd > 0) {
|
|
2689
|
+
slabProfitable = true;
|
|
2690
|
+
recordAnthropicCliffSticky(slabCliffKey, cliff.cliffAt);
|
|
2691
|
+
info.cliffAvoided = {
|
|
2692
|
+
at: cliff.cliffAt,
|
|
2693
|
+
multiplier: cliff.multiplier,
|
|
2694
|
+
savedUsd: cliff.netSingleTurnUsd,
|
|
2695
|
+
};
|
|
2696
|
+
}
|
|
2697
|
+
}
|
|
2698
|
+
}
|
|
2699
|
+
if (slabGateEval) {
|
|
2700
|
+
info.gateEval = {
|
|
2701
|
+
site: 'slab',
|
|
2702
|
+
imageTokens: slabGateEval.imageTokens,
|
|
2703
|
+
textTokens: slabGateEval.textTokens,
|
|
2704
|
+
burnImageSide: slabGateEval.burnImageSide,
|
|
2705
|
+
burnTextSide: slabGateEval.burnTextSide,
|
|
2706
|
+
profitable: slabProfitable,
|
|
2707
|
+
};
|
|
2708
|
+
}
|
|
2709
|
+
if (!slabProfitable) {
|
|
2710
|
+
info.reason = `not_profitable (slab=${combined.length} chars)`;
|
|
2711
|
+
bumpPassthrough(info, 'not_profitable');
|
|
2712
|
+
// Slab not profitable but history may still be collapsable — try before returning.
|
|
2713
|
+
const finalized = await runHistoryCollapseAndFinalize(req, info, o, opts, droppedCodepoints, pins, reqPromptTokensEst, reqTtlSec, sessionState, hybridTextMmu);
|
|
2714
|
+
if (finalized.changed || hygieneStats?.changed) {
|
|
2715
|
+
info.compressed = true;
|
|
2716
|
+
if (!finalized.changed && hygieneStats?.changed)
|
|
2717
|
+
info.reason = 'text_hygiene';
|
|
2718
|
+
return { body: finalized.body, info };
|
|
2719
|
+
}
|
|
2720
|
+
if (hygieneStats?.tailHydrated) {
|
|
2721
|
+
info.reason = 'mmu_hydrate';
|
|
2722
|
+
return { body: finalized.body, info };
|
|
2723
|
+
}
|
|
2724
|
+
// `body` is the original bytes. If the pin pass edited `req`, those bytes
|
|
2725
|
+
// describe a request we are no longer sending, so forwarding them would put
|
|
2726
|
+
// the raw `@inkling pin` line back and drop the tail block.
|
|
2727
|
+
return { body: pinsRewrote ? finalized.body : body, info };
|
|
2728
|
+
}
|
|
2729
|
+
// Instruction header co-renders into the same PNG (+1.04pp L1 OCR vs baseline;
|
|
2730
|
+
// single-modal framing keeps encoder in image-reading mode for both header + content).
|
|
2731
|
+
// Header text is continuous prose (no hard \n) so the renderer soft-wraps densely.
|
|
2732
|
+
// 3. Render to PNGs at slabCols width (banner sets natural floor).
|
|
2733
|
+
// Same style as the dense path above, so both Anthropic surfaces resolve the same
|
|
2734
|
+
// atlas. No-op for ASCII (gray and bitmap atlases are bit-identical there); it keeps
|
|
2735
|
+
// non-ASCII glyphs from depending on which code path happened to render them.
|
|
2736
|
+
const images = await renderTextToPngs(combinedWithHeader, slabCols, denseGeo.style, denseGeo.maxHeightPx);
|
|
2737
|
+
// Quantitative cap, not just "is there room": the slab is many pages, and a
|
|
2738
|
+
// boolean "headroom > 0" check happily emitted 15 of them into a single slot
|
|
2739
|
+
// (measured: 94 client images + 400k slab -> 109 on the wire -> 400). All or
|
|
2740
|
+
// nothing, because the slab is part of the cache prefix — imaging half of it
|
|
2741
|
+
// would re-key that prefix on every turn whose client-image count moved.
|
|
2742
|
+
const slabBytes = images.reduce((sum, img) => sum + img.png.length, 0);
|
|
2743
|
+
const slabOverCount = images.length > imageHeadroom(info);
|
|
2744
|
+
const slabOverBytes = slabBytes > imageByteHeadroom(info, o.maxImageBytes);
|
|
2745
|
+
if (slabOverCount || slabOverBytes) {
|
|
2746
|
+
info.reason = slabOverCount
|
|
2747
|
+
? `image_budget (slab needs ${images.length}, headroom ${imageHeadroom(info)})`
|
|
2748
|
+
: `image_bytes (slab needs ${slabBytes}, headroom ${imageByteHeadroom(info, o.maxImageBytes)})`;
|
|
2749
|
+
bumpPassthrough(info, 'image_budget');
|
|
2750
|
+
if (slabOverBytes && !slabOverCount)
|
|
2751
|
+
info.imageByteSkips = (info.imageByteSkips ?? 0) + 1;
|
|
2752
|
+
else
|
|
2753
|
+
info.imageBudgetSkips = (info.imageBudgetSkips ?? 0) + 1;
|
|
2754
|
+
const finalized = await runHistoryCollapseAndFinalize(req, info, o, opts, droppedCodepoints, pins, reqPromptTokensEst, reqTtlSec, sessionState, hybridTextMmu);
|
|
2755
|
+
if (finalized.changed || hygieneStats?.changed) {
|
|
2756
|
+
info.compressed = true;
|
|
2757
|
+
if (!finalized.changed && hygieneStats?.changed)
|
|
2758
|
+
info.reason = 'text_hygiene';
|
|
2759
|
+
return { body: finalized.body, info };
|
|
2760
|
+
}
|
|
2761
|
+
if (hygieneStats?.tailHydrated) {
|
|
2762
|
+
info.reason = 'mmu_hydrate';
|
|
2763
|
+
return { body: finalized.body, info };
|
|
2764
|
+
}
|
|
2765
|
+
return { body: pinsRewrote ? finalized.body : body, info };
|
|
2766
|
+
}
|
|
2767
|
+
const imageBlocks = [];
|
|
2768
|
+
for (let i = 0; i < images.length; i++) {
|
|
2769
|
+
const img = images[i];
|
|
2770
|
+
const b64 = bytesToBase64(img.png);
|
|
2771
|
+
info.imageBytes += img.png.length;
|
|
2772
|
+
info.imagePixels = (info.imagePixels ?? 0) + img.width * img.height;
|
|
2773
|
+
info.droppedChars = (info.droppedChars ?? 0) + img.droppedChars;
|
|
2774
|
+
for (const [cp, n] of img.droppedCodepoints) {
|
|
2775
|
+
droppedCodepoints.set(cp, (droppedCodepoints.get(cp) ?? 0) + n);
|
|
2776
|
+
}
|
|
2777
|
+
const imageBlock = makeImageBlock(b64, i === images.length - 1);
|
|
2778
|
+
imageBlocks.push(i === images.length - 1 && systemStaticCacheControl !== undefined
|
|
2779
|
+
? { ...imageBlock, cache_control: demoteRelocatedCacheControl(systemStaticCacheControl) }
|
|
2780
|
+
: imageBlock);
|
|
2781
|
+
}
|
|
2782
|
+
info.imageCount = imageBlocks.length;
|
|
2783
|
+
info.imageTokens = (info.imageTokens ?? 0) + images.reduce((s, img) => s + visionTokens(denseGeo.pricing, img.width, img.height), 0);
|
|
2784
|
+
info.baselineImagedTokens = (info.baselineImagedTokens ?? 0) + Math.ceil(combinedRaw.length / Math.max(1e-6, slabCpt));
|
|
2785
|
+
// Credit raw (pre-compaction) length — what Anthropic would have billed.
|
|
2786
|
+
info.compressedChars += combinedRaw.length;
|
|
2787
|
+
bumpBucket(info, 'static_slab', combinedRaw.length);
|
|
2788
|
+
if (images.length > 0) {
|
|
2789
|
+
info.firstImagePng = images[0].png;
|
|
2790
|
+
info.firstImageWidth = images[0].width;
|
|
2791
|
+
info.firstImageHeight = images[0].height;
|
|
2792
|
+
(info.imagePngs ??= []).push(...images.map((i) => i.png));
|
|
2793
|
+
(info.imageDims ??= []).push(...images.map((i) => ({ width: i.width, height: i.height })));
|
|
2794
|
+
info.imageSourceText = combinedWithHeader.slice(0, 65_536);
|
|
2795
|
+
}
|
|
2796
|
+
// 4. Splice images back into the request. OCR framing is baked into the image.
|
|
2797
|
+
//
|
|
2798
|
+
// Volatile env/context text (git status, cwd, date) stays in req.system, its
|
|
2799
|
+
// original position. Relocating it into the last user message traded a real
|
|
2800
|
+
// cache benefit for a visible protocol artifact — a <system-reminder> block
|
|
2801
|
+
// appearing in the conversation as if the user had written it — so the pipe
|
|
2802
|
+
// no longer moves it. Churn on these bytes costs prefix cache reads; that is
|
|
2803
|
+
// accepted rather than rewriting the caller's message stream.
|
|
2804
|
+
// Images go into first user message — system field rejects images (400 system.N.type).
|
|
2805
|
+
{
|
|
2806
|
+
const sysTail = [];
|
|
2807
|
+
if (preservedIdentity) {
|
|
2808
|
+
sysTail.push({ type: 'text', text: preservedIdentity });
|
|
2809
|
+
}
|
|
2810
|
+
// billingLine is NOT re-emitted here. req.system precedes messages[] in
|
|
2811
|
+
// Anthropic's cache-prefix order, so every system block sits inside the
|
|
2812
|
+
// span covered by the LAST cache_control marker (always in messages[] on
|
|
2813
|
+
// this path — see cachePrefixDigest). #180/#161 put the line here believing
|
|
2814
|
+
// "after the anchor"; telemetry showed 0 cache reads and 509/509 distinct
|
|
2815
|
+
// cachePrefixSha8 per day. It leaves the body entirely: exported via
|
|
2816
|
+
// info.billingLine and sent as a real HTTP header (src/core/proxy.ts).
|
|
2817
|
+
if (dynamicText)
|
|
2818
|
+
sysTail.push({ type: 'text', text: dynamicText });
|
|
2819
|
+
if (envMarkdown)
|
|
2820
|
+
sysTail.push({ type: 'text', text: envMarkdown });
|
|
2821
|
+
if (Array.isArray(sysRemainder))
|
|
2822
|
+
sysTail.push(...sysRemainder);
|
|
2823
|
+
// Tool Reference now rides INSIDE the imaged slab (combinedRaw above) — no
|
|
2824
|
+
// text splice here. Stubbed tools[] descriptions cite the "## Tool: <name>"
|
|
2825
|
+
// headings inside the image; stub ↔ reference invariant holds because both
|
|
2826
|
+
// are applied on this same path (gate-fail paths return earlier with
|
|
2827
|
+
// original tools untouched).
|
|
2828
|
+
req.system = sysTail.length > 0 ? sysTail : undefined;
|
|
2829
|
+
const firstUserIdx = (req.messages ?? []).findIndex((m) => m.role === 'user');
|
|
2830
|
+
if (firstUserIdx >= 0) {
|
|
2831
|
+
const m = req.messages[firstUserIdx];
|
|
2832
|
+
const existing = Array.isArray(m.content)
|
|
2833
|
+
? m.content
|
|
2834
|
+
: [{ type: 'text', text: m.content }];
|
|
2835
|
+
// <system-reminder> blocks stay text, always. They are the wrapper Claude
|
|
2836
|
+
// Code puts around every injected instruction block (CLAUDE.md included),
|
|
2837
|
+
// they churn turn-to-turn as the client re-injects and relocates them, and
|
|
2838
|
+
// imaging one drags its cache_control onto a block that will not recur
|
|
2839
|
+
// byte-identically next turn. Rendering them lost more to cache misses
|
|
2840
|
+
// than it saved in tokens, so the path is gone rather than flag-gated.
|
|
2841
|
+
const slabFactSheet = factSheetText(combinedRaw);
|
|
2842
|
+
m.content = [
|
|
2843
|
+
...imageBlocks,
|
|
2844
|
+
...(slabFactSheet ? [{ type: 'text', text: slabFactSheet }] : []),
|
|
2845
|
+
{ type: 'text', text: '[End of rendered context.]' },
|
|
2846
|
+
...existing,
|
|
2847
|
+
];
|
|
2848
|
+
}
|
|
2849
|
+
}
|
|
2850
|
+
if (toolsRewritten)
|
|
2851
|
+
req.tools = toolsRewritten;
|
|
2852
|
+
// 6. History-image compression. Runs BEFORE tool_result imaging (step 5b), so
|
|
2853
|
+
// the collapse reads the original textual message graph. See the ordering
|
|
2854
|
+
// invariant documented on step 5b below.
|
|
2855
|
+
// History is single-col dense; use slab cpt unless host pinned charsPerToken.
|
|
2856
|
+
// protectedPrefix excludes the slab-bearing first user message — collapsing it
|
|
2857
|
+
// would reduce slab images to [image] placeholders and destroy the cache anchor.
|
|
2858
|
+
if (hybridTextMmu) {
|
|
2859
|
+
// Dynamic turns are handled by Text-MMU in hybrid mode.
|
|
2860
|
+
}
|
|
2861
|
+
else if (imageHeadroom(info) <= 0) {
|
|
2862
|
+
bumpPassthrough(info, 'image_budget');
|
|
2863
|
+
info.imageBudgetSkips = (info.imageBudgetSkips ?? 0) + 1;
|
|
2864
|
+
info.historyReason ??= 'too_many_images';
|
|
2865
|
+
}
|
|
2866
|
+
else if (Array.isArray(req.messages) && req.messages.length > 0) {
|
|
2867
|
+
const historyCpt = opts.charsPerToken !== undefined
|
|
2868
|
+
? o.charsPerToken
|
|
2869
|
+
: HISTORY_CHARS_PER_TOKEN;
|
|
2870
|
+
const horizon = Math.max(1, Math.floor(o.historyAmortizationHorizon));
|
|
2871
|
+
const historyGeometry = historyGateGeometry(o, opts.cols !== undefined);
|
|
2872
|
+
const historyRates = gateRates(req, o.model);
|
|
2873
|
+
const historyProfitable = (text, _cols) => {
|
|
2874
|
+
// Gate with the same model profile used by the history renderer.
|
|
2875
|
+
if (isCompressionProfitableAmortized(text, historyGeometry.cols, undefined, historyCpt, horizon, o.priorWarmTokens, o.priorWarmImageTokens, true, historyGeometry.maxChars, historyGeometry, historyRates))
|
|
2876
|
+
return true;
|
|
2877
|
+
if (historyRates !== null) {
|
|
2878
|
+
const textTok = text.length / Math.max(1e-6, historyCpt);
|
|
2879
|
+
const imgTok = imageTokensCost(text, historyGeometry.cols, undefined, true, historyGeometry.maxChars, historyGeometry);
|
|
2880
|
+
if (imgTok < textTok) {
|
|
2881
|
+
const histCliffKey = `${o.model ?? ''}\0${reqTtlSec ?? ''}\0${info.sessionKey ?? info.firstUserSha8 ?? ''}\0history`;
|
|
2882
|
+
const stickyCliffAt = priceMode() === 'kosha' ? getAnthropicCliffSticky(histCliffKey) : undefined;
|
|
2883
|
+
if (stickyCliffAt !== undefined && reqPromptTokensEst > stickyCliffAt)
|
|
2884
|
+
return true;
|
|
2885
|
+
const tailTok = estimateTailMsgTokens(req.messages, o.charsPerToken);
|
|
2886
|
+
const downstreamCachedTokens = Math.max(0, reqPromptTokensEst - (info.imageTokens ?? 0) - textTok - tailTok);
|
|
2887
|
+
const cliff = evaluateCliffAvoidance(o.model, {
|
|
2888
|
+
promptTokensBefore: reqPromptTokensEst,
|
|
2889
|
+
promptTokensAfter: Math.max(0, reqPromptTokensEst - (textTok - imgTok)),
|
|
2890
|
+
collapsedBaselineTokens: textTok,
|
|
2891
|
+
collapsedActualTokens: imgTok,
|
|
2892
|
+
downstreamCachedTokens,
|
|
2893
|
+
expectedOutputTokens: o.expectedOutputTokens,
|
|
2894
|
+
ttlSec: reqTtlSec,
|
|
2895
|
+
});
|
|
2896
|
+
if (cliff?.crossesCliff && cliff.netSingleTurnUsd > 0) {
|
|
2897
|
+
recordAnthropicCliffSticky(histCliffKey, cliff.cliffAt);
|
|
2898
|
+
info.cliffAvoided = { at: cliff.cliffAt, multiplier: cliff.multiplier, savedUsd: cliff.netSingleTurnUsd };
|
|
2899
|
+
return true;
|
|
2900
|
+
}
|
|
2901
|
+
}
|
|
2902
|
+
}
|
|
2903
|
+
return false;
|
|
2904
|
+
};
|
|
2905
|
+
const slabAnchorIdx = (req.messages ?? []).findIndex((m) => m.role === 'user');
|
|
2906
|
+
const tuning = historyGridTuning(info, sessionState);
|
|
2907
|
+
const { messages: newMessages, info: histInfo } = await collapseHistory(req.messages, historyProfitable, {
|
|
2908
|
+
cols: historyGeometry.cols,
|
|
2909
|
+
protectedPrefix: slabAnchorIdx >= 0 ? slabAnchorIdx + 1 : 0,
|
|
2910
|
+
reflow: o.reflow,
|
|
2911
|
+
style: historyGeometry.style,
|
|
2912
|
+
maxHeightPx: historyGeometry.maxHeightPx,
|
|
2913
|
+
pageChars: historyGeometry.maxChars,
|
|
2914
|
+
separateAdjacentToolPairs: o.separateAdjacentToolPairs,
|
|
2915
|
+
imageBudget: tuning.imageBudget,
|
|
2916
|
+
packFill: tuning.packFill,
|
|
2917
|
+
minFreezeStep: tuning.minFreezeStep,
|
|
2918
|
+
});
|
|
2919
|
+
// Atomic admission by weight. The collapse is one semantic group: applying
|
|
2920
|
+
// it means every collapsed message becomes pages, so a group that does not
|
|
2921
|
+
// fit the byte budget is not applied at all and the original text stands.
|
|
2922
|
+
// Rendering it first and discarding it costs CPU, which is the cheap half of
|
|
2923
|
+
// the trade: the alternative is estimating PNG size from character counts and
|
|
2924
|
+
// being wrong on the request that mattered.
|
|
2925
|
+
if (histInfo.collapsedTurns > 0 &&
|
|
2926
|
+
histInfo.collapsedImageBytes > imageByteHeadroom(info, o.maxImageBytes)) {
|
|
2927
|
+
bumpPassthrough(info, 'image_budget');
|
|
2928
|
+
info.imageByteSkips = (info.imageByteSkips ?? 0) + 1;
|
|
2929
|
+
info.historyReason = 'image_bytes';
|
|
2930
|
+
}
|
|
2931
|
+
else if (histInfo.collapsedTurns > 0) {
|
|
2932
|
+
recordFreezeStep(info.sessionKey ?? info.firstUserSha8, histInfo.freezeStep, o.model ? { model: o.model } : undefined);
|
|
2933
|
+
if (histInfo.freezeStep !== undefined)
|
|
2934
|
+
info.historyFreezeStep = histInfo.freezeStep;
|
|
2935
|
+
if (histInfo.budgetTrimmed)
|
|
2936
|
+
info.historyBudgetTrimmed = true;
|
|
2937
|
+
if (tuning.packFill)
|
|
2938
|
+
info.historyPackFill = true;
|
|
2939
|
+
if (o.separateAdjacentToolPairs)
|
|
2940
|
+
info.historySplitAdjacentPairs = true;
|
|
2941
|
+
req.messages = newMessages;
|
|
2942
|
+
info.collapsedTurns = histInfo.collapsedTurns;
|
|
2943
|
+
info.collapsedChars = histInfo.collapsedChars;
|
|
2944
|
+
info.collapsedImages = histInfo.collapsedImages;
|
|
2945
|
+
info.imageCount += histInfo.collapsedImages;
|
|
2946
|
+
info.imageBytes += histInfo.collapsedImageBytes;
|
|
2947
|
+
info.imagePixels = (info.imagePixels ?? 0) + histInfo.collapsedImagePixels;
|
|
2948
|
+
info.imageTokens = (info.imageTokens ?? 0) + histInfo.collapsedImageDims.reduce((s, d) => s + visionTokens(historyGeometry.pricing, d.width, d.height), 0);
|
|
2949
|
+
info.baselineImagedTokens = (info.baselineImagedTokens ?? 0) + Math.ceil(histInfo.collapsedChars / Math.max(1e-6, historyCpt));
|
|
2950
|
+
// Register the rendered (colored) history PNGs into the dashboard image ring
|
|
2951
|
+
// so they are visible, not merely counted. Every other image path feeds this.
|
|
2952
|
+
// imagePngs + imageDims must be pushed in lockstep (ring reads them parallel).
|
|
2953
|
+
(info.imagePngs ??= []).push(...histInfo.collapsedPngs);
|
|
2954
|
+
(info.imageDims ??= []).push(...histInfo.collapsedImageDims);
|
|
2955
|
+
info.droppedChars = (info.droppedChars ?? 0) + histInfo.droppedChars;
|
|
2956
|
+
for (const [cp, n] of histInfo.droppedCodepoints) {
|
|
2957
|
+
droppedCodepoints.set(cp, (droppedCodepoints.get(cp) ?? 0) + n);
|
|
2958
|
+
}
|
|
2959
|
+
info.historyReason = 'collapsed';
|
|
2960
|
+
info.historyTextChars = histInfo.collapsedChars;
|
|
2961
|
+
info.historyImageSha = await historyImageSha8(newMessages);
|
|
2962
|
+
bumpBucket(info, 'history', histInfo.collapsedChars);
|
|
2963
|
+
// Move the single cache anchor onto the history image so slab + history
|
|
2964
|
+
// cache as one stable prefix (created once, then read), instead of the
|
|
2965
|
+
// history image re-creating whenever the caller's downstream marker moves.
|
|
2966
|
+
//
|
|
2967
|
+
// ONLY when collapseHistory pinned a byte-frozen carry-over chunk. On the
|
|
2968
|
+
// session's FIRST collapse the range fits in one freeze window, no carry-over
|
|
2969
|
+
// exists (ordinal undefined), and relocating would land the anchor on the
|
|
2970
|
+
// newest still-growing history image — a volatile breakpoint that forced a
|
|
2971
|
+
// one-time full-prefix rewrite (~53k tokens/session). Leave the anchor on
|
|
2972
|
+
// the byte-stable slab image until a frozen chunk exists to pin to.
|
|
2973
|
+
if (histInfo.carryOverImageOrdinal !== undefined) {
|
|
2974
|
+
relocateAnchorToHistoryImage(req.messages, histInfo.carryOverImageOrdinal, req.system, req.tools);
|
|
2975
|
+
}
|
|
2976
|
+
}
|
|
2977
|
+
else if (histInfo.reason) {
|
|
2978
|
+
info.historyReason = histInfo.reason;
|
|
2979
|
+
}
|
|
2980
|
+
}
|
|
2981
|
+
// 5b. Compress tool_result content across ALL user messages.
|
|
2982
|
+
//
|
|
2983
|
+
// ORDERING INVARIANT: this runs AFTER the history collapse (step 6), never
|
|
2984
|
+
// before it. Both stages are lossy, and composing them the other way lost
|
|
2985
|
+
// content outright: once a tool_result has become image blocks, the collapse
|
|
2986
|
+
// serializer (`blocksToText`) renders a nested image as the literal string
|
|
2987
|
+
// "[image]". A tool_result that was imaged here and then absorbed by the
|
|
2988
|
+
// collapse therefore reached the wire in neither form - not as text, because
|
|
2989
|
+
// the text had been replaced, and not as an image, because the collapse
|
|
2990
|
+
// replaces whole messages. Running the collapse first means it sees the
|
|
2991
|
+
// original textual graph, and only messages that survive outside the
|
|
2992
|
+
// collapsed prefix are still eligible for imaging here.
|
|
2993
|
+
//
|
|
2994
|
+
// Consequence to keep in mind when reading the budget calls below: the
|
|
2995
|
+
// history images are already counted in `info` by the time we get here, so
|
|
2996
|
+
// `imageHeadroom(info)` is the headroom left after the collapse spent its
|
|
2997
|
+
// share. Out of headroom degrades to sharp text, which is the safe direction.
|
|
2998
|
+
await compressToolResultsInPlace(req, info, o, denseGeo, droppedCodepoints, hybridTextMmu
|
|
2999
|
+
? buildHybridToolOpticalGuard(req, info.sessionKey ?? info.firstUserSha8, sessionState.cold)
|
|
3000
|
+
: undefined);
|
|
3001
|
+
// The volatile billing line is NOT re-emitted into the body at all. There is
|
|
3002
|
+
// no safe body position: req.system precedes the last cache_control marker
|
|
3003
|
+
// (#180/#161: 0 cache reads, 509/509 distinct cachePrefixSha8/day), and
|
|
3004
|
+
// appending after the final user message's markers renders it as
|
|
3005
|
+
// user-attributed text in the conversation (the leak this replaced). It is a
|
|
3006
|
+
// header by name and by nature — the proxy forwards `info.billingLine` as a
|
|
3007
|
+
// real HTTP header on the upstream request (src/core/proxy.ts), where its
|
|
3008
|
+
// per-turn churn (`cc_prev_req` on CLI >= 2.1.222) touches no cached bytes.
|
|
3009
|
+
if (billingLine)
|
|
3010
|
+
info.billingLine = billingLine;
|
|
3011
|
+
info.compressed = true;
|
|
3012
|
+
if (hybridTextMmu && info.imageCount > 0) {
|
|
3013
|
+
info.reason = 'hybrid_slab_optical';
|
|
3014
|
+
const stages = info.textHygieneStages ? [...info.textHygieneStages] : [];
|
|
3015
|
+
if (!stages.includes('hybrid_slab_optical'))
|
|
3016
|
+
stages.push('hybrid_slab_optical');
|
|
3017
|
+
info.textHygieneStages = stages;
|
|
3018
|
+
}
|
|
3019
|
+
// Attribution signal for prompt-cache busts (#11): digest the exact pinned
|
|
3020
|
+
// prefix we send (history/slab boundary; live tail excluded) AFTER all marker
|
|
3021
|
+
// placement — incl. relocateAnchorToHistoryImage — is final. Read-only.
|
|
3022
|
+
{
|
|
3023
|
+
const pfx = await cachePrefixDigest(req);
|
|
3024
|
+
if (pfx) {
|
|
3025
|
+
info.cachePrefixSha8 = pfx.sha8;
|
|
3026
|
+
info.cachePrefixBytes = pfx.bytes;
|
|
3027
|
+
info.cachePrefixToolsSha8 = pfx.toolsSha8;
|
|
3028
|
+
info.cachePrefixSystemSha8 = pfx.systemSha8;
|
|
3029
|
+
info.cachePrefixHeadSha8 = pfx.headSha8;
|
|
3030
|
+
info.cachePrefixMarkedSha8 = pfx.markedSha8;
|
|
3031
|
+
info.cachePrefixMarkedBytes = pfx.markedBytes;
|
|
3032
|
+
if (pfx.markerPos)
|
|
3033
|
+
info.cachePrefixMarkerPos = pfx.markerPos;
|
|
3034
|
+
}
|
|
3035
|
+
}
|
|
3036
|
+
// Top dropped codepoints, capped at 20 entries to bound JSONL row size.
|
|
3037
|
+
if (droppedCodepoints.size > 0) {
|
|
3038
|
+
const TOP_N = 20;
|
|
3039
|
+
const sorted = [...droppedCodepoints.entries()]
|
|
3040
|
+
.sort((a, b) => b[1] - a[1])
|
|
3041
|
+
.slice(0, TOP_N);
|
|
3042
|
+
const out = {};
|
|
3043
|
+
for (const [cp, count] of sorted) {
|
|
3044
|
+
const hex = cp.toString(16).toUpperCase().padStart(4, '0');
|
|
3045
|
+
out[`U+${hex}`] = count;
|
|
3046
|
+
}
|
|
3047
|
+
info.droppedCodepointsTop = out;
|
|
3048
|
+
}
|
|
3049
|
+
applyPins(req, info, pins);
|
|
3050
|
+
info.outgoingTextChars = countOutgoingTextChars(req);
|
|
3051
|
+
// Ground truth for the main path too — see the note at the other call site.
|
|
3052
|
+
info.wireImages = countNativeImages(req.messages);
|
|
3053
|
+
if (nearByteLimit(info, o.maxImageBytes))
|
|
3054
|
+
info.imageBytesNearLimit = true;
|
|
3055
|
+
const outBody = new TextEncoder().encode(JSON.stringify(req));
|
|
3056
|
+
return { body: outBody, info };
|
|
3057
|
+
}
|
|
3058
|
+
/** Sum every TEXT char the upstream tokenizer will see (system, tools, messages).
|
|
3059
|
+
* Excludes image base64 and redacted_thinking. Denominator for the
|
|
3060
|
+
* `tokens ≈ α·outgoingTextChars + β·imagePixels` regression. */
|
|
3061
|
+
function countOutgoingTextChars(req) {
|
|
3062
|
+
let n = 0;
|
|
3063
|
+
// 1. system field
|
|
3064
|
+
const sys = req.system;
|
|
3065
|
+
if (typeof sys === 'string') {
|
|
3066
|
+
n += sys.length;
|
|
3067
|
+
}
|
|
3068
|
+
else if (Array.isArray(sys)) {
|
|
3069
|
+
for (const b of sys) {
|
|
3070
|
+
if (b && b.type === 'text' && typeof b.text === 'string') {
|
|
3071
|
+
n += b.text.length;
|
|
3072
|
+
}
|
|
3073
|
+
}
|
|
3074
|
+
}
|
|
3075
|
+
// 2. tool definitions
|
|
3076
|
+
if (Array.isArray(req.tools)) {
|
|
3077
|
+
for (const tool of req.tools) {
|
|
3078
|
+
if (!tool || typeof tool !== 'object')
|
|
3079
|
+
continue;
|
|
3080
|
+
if (typeof tool.name === 'string')
|
|
3081
|
+
n += tool.name.length;
|
|
3082
|
+
if (typeof tool.description === 'string')
|
|
3083
|
+
n += tool.description.length;
|
|
3084
|
+
if (tool.input_schema !== undefined) {
|
|
3085
|
+
n += safeStringifyLen(tool.input_schema);
|
|
3086
|
+
}
|
|
3087
|
+
}
|
|
3088
|
+
}
|
|
3089
|
+
// 3. per-message content
|
|
3090
|
+
for (const msg of req.messages ?? []) {
|
|
3091
|
+
const c = msg.content;
|
|
3092
|
+
if (typeof c === 'string') {
|
|
3093
|
+
n += c.length;
|
|
3094
|
+
continue;
|
|
3095
|
+
}
|
|
3096
|
+
if (!Array.isArray(c))
|
|
3097
|
+
continue;
|
|
3098
|
+
for (const b of c) {
|
|
3099
|
+
if (!b || typeof b !== 'object')
|
|
3100
|
+
continue;
|
|
3101
|
+
const type = b.type;
|
|
3102
|
+
if (type === 'text') {
|
|
3103
|
+
const tb = b;
|
|
3104
|
+
if (typeof tb.text === 'string')
|
|
3105
|
+
n += tb.text.length;
|
|
3106
|
+
continue;
|
|
3107
|
+
}
|
|
3108
|
+
if (type === 'tool_use') {
|
|
3109
|
+
const tu = b;
|
|
3110
|
+
if (typeof tu.name === 'string')
|
|
3111
|
+
n += tu.name.length;
|
|
3112
|
+
if (tu.input !== undefined)
|
|
3113
|
+
n += safeStringifyLen(tu.input);
|
|
3114
|
+
continue;
|
|
3115
|
+
}
|
|
3116
|
+
if (type === 'tool_result') {
|
|
3117
|
+
const tr = b;
|
|
3118
|
+
if (typeof tr.tool_use_id === 'string')
|
|
3119
|
+
n += tr.tool_use_id.length;
|
|
3120
|
+
const inner = tr.content;
|
|
3121
|
+
if (typeof inner === 'string') {
|
|
3122
|
+
n += inner.length;
|
|
3123
|
+
}
|
|
3124
|
+
else if (Array.isArray(inner)) {
|
|
3125
|
+
for (const ib of inner) {
|
|
3126
|
+
if (ib && ib.type === 'text' && typeof ib.text === 'string') {
|
|
3127
|
+
n += ib.text.length;
|
|
3128
|
+
}
|
|
3129
|
+
}
|
|
3130
|
+
}
|
|
3131
|
+
continue;
|
|
3132
|
+
}
|
|
3133
|
+
if (type === 'thinking') {
|
|
3134
|
+
const th = b;
|
|
3135
|
+
if (typeof th.thinking === 'string')
|
|
3136
|
+
n += th.thinking.length;
|
|
3137
|
+
continue;
|
|
3138
|
+
}
|
|
3139
|
+
// image, redacted_thinking, server_tool_use, etc. — skip.
|
|
3140
|
+
}
|
|
3141
|
+
}
|
|
3142
|
+
return n;
|
|
3143
|
+
}
|
|
3144
|
+
/** JSON.stringify length, tolerant of cycles. Returns 0 on error. */
|
|
3145
|
+
function safeStringifyLen(v) {
|
|
3146
|
+
try {
|
|
3147
|
+
return JSON.stringify(v)?.length ?? 0;
|
|
3148
|
+
}
|
|
3149
|
+
catch {
|
|
3150
|
+
return 0;
|
|
3151
|
+
}
|
|
3152
|
+
}
|
|
3153
|
+
//# sourceMappingURL=transform.js.map
|