@anthonymercer/contextscope 0.0.0-stage → 0.4.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/LICENSE +21 -0
- package/README.md +764 -2
- package/dist/cli/ansi.d.ts +31 -0
- package/dist/cli/ansi.js +80 -0
- package/dist/cli/args.d.ts +18 -0
- package/dist/cli/args.js +78 -0
- package/dist/cli/html-report.d.ts +2 -0
- package/dist/cli/html-report.js +119 -0
- package/dist/cli/index.d.ts +2 -0
- package/dist/cli/index.js +138 -0
- package/dist/cli/json-report.d.ts +1 -0
- package/dist/cli/json-report.js +2 -0
- package/dist/cli/read-input.d.ts +3 -0
- package/dist/cli/read-input.js +43 -0
- package/dist/cli/terminal-report.d.ts +7 -0
- package/dist/cli/terminal-report.js +271 -0
- package/dist/cli/usage-html.d.ts +2 -0
- package/dist/cli/usage-html.js +33 -0
- package/dist/cli/version.d.ts +2 -0
- package/dist/cli/version.js +3 -0
- package/dist/cli/write-reports.d.ts +12 -0
- package/dist/cli/write-reports.js +82 -0
- package/dist/core/analyze.d.ts +13 -0
- package/dist/core/analyze.js +99 -0
- package/dist/core/anthropic-breakpoints.d.ts +6 -0
- package/dist/core/anthropic-breakpoints.js +48 -0
- package/dist/core/anthropic-cache-scope.d.ts +12 -0
- package/dist/core/anthropic-cache-scope.js +47 -0
- package/dist/core/anthropic-injected-settings.d.ts +14 -0
- package/dist/core/anthropic-injected-settings.js +57 -0
- package/dist/core/anthropic-reasoning.d.ts +13 -0
- package/dist/core/anthropic-reasoning.js +57 -0
- package/dist/core/anthropic-speed.d.ts +4 -0
- package/dist/core/anthropic-speed.js +27 -0
- package/dist/core/cache-anthropic.d.ts +2 -0
- package/dist/core/cache-anthropic.js +146 -0
- package/dist/core/cache-openai.d.ts +2 -0
- package/dist/core/cache-openai.js +72 -0
- package/dist/core/calibrate.d.ts +43 -0
- package/dist/core/calibrate.js +97 -0
- package/dist/core/decode-text.d.ts +9 -0
- package/dist/core/decode-text.js +21 -0
- package/dist/core/detect.d.ts +10 -0
- package/dist/core/detect.js +102 -0
- package/dist/core/duplicates.d.ts +12 -0
- package/dist/core/duplicates.js +153 -0
- package/dist/core/findings.d.ts +4 -0
- package/dist/core/findings.js +437 -0
- package/dist/core/group-findings.d.ts +23 -0
- package/dist/core/group-findings.js +69 -0
- package/dist/core/index.d.ts +1 -0
- package/dist/core/index.js +2 -0
- package/dist/core/json-report.d.ts +10 -0
- package/dist/core/json-report.js +46 -0
- package/dist/core/json-utils.d.ts +28 -0
- package/dist/core/json-utils.js +99 -0
- package/dist/core/media-accounting.d.ts +11 -0
- package/dist/core/media-accounting.js +76 -0
- package/dist/core/model-id.d.ts +16 -0
- package/dist/core/model-id.js +36 -0
- package/dist/core/model-summary.d.ts +10 -0
- package/dist/core/model-summary.js +44 -0
- package/dist/core/openai-breakpoints.d.ts +14 -0
- package/dist/core/openai-breakpoints.js +107 -0
- package/dist/core/openai-context.d.ts +15 -0
- package/dist/core/openai-context.js +54 -0
- package/dist/core/parse-anthropic.d.ts +4 -0
- package/dist/core/parse-anthropic.js +284 -0
- package/dist/core/parse-error.d.ts +3 -0
- package/dist/core/parse-error.js +4 -0
- package/dist/core/parse-openai.d.ts +10 -0
- package/dist/core/parse-openai.js +273 -0
- package/dist/core/parse.d.ts +3 -0
- package/dist/core/parse.js +164 -0
- package/dist/core/prefix.d.ts +23 -0
- package/dist/core/prefix.js +290 -0
- package/dist/core/presentation.d.ts +4 -0
- package/dist/core/presentation.js +5 -0
- package/dist/core/pricing.d.ts +76 -0
- package/dist/core/pricing.js +130 -0
- package/dist/core/prompt-identity.d.ts +5 -0
- package/dist/core/prompt-identity.js +84 -0
- package/dist/core/read-json.d.ts +7 -0
- package/dist/core/read-json.js +74 -0
- package/dist/core/report.d.ts +2 -0
- package/dist/core/report.js +31 -0
- package/dist/core/reported-usage.d.ts +7 -0
- package/dist/core/reported-usage.js +195 -0
- package/dist/core/threads.d.ts +48 -0
- package/dist/core/threads.js +189 -0
- package/dist/core/token-counter.d.ts +13 -0
- package/dist/core/token-counter.js +21 -0
- package/dist/core/tokenize-claude.d.ts +18 -0
- package/dist/core/tokenize-claude.js +56 -0
- package/dist/core/tokenize-openai.d.ts +1 -0
- package/dist/core/tokenize-openai.js +15 -0
- package/dist/core/types.d.ts +326 -0
- package/dist/core/types.js +12 -0
- package/dist/core/usage-comparison.d.ts +2 -0
- package/dist/core/usage-comparison.js +70 -0
- package/dist/core/usage-labels.d.ts +5 -0
- package/dist/core/usage-labels.js +18 -0
- package/dist/core/volatile.d.ts +12 -0
- package/dist/core/volatile.js +31 -0
- package/package.json +75 -4
|
@@ -0,0 +1,437 @@
|
|
|
1
|
+
import { canonicalJson, isRecord, keyOrderFingerprint } from "./json-utils.js";
|
|
2
|
+
import { ANTHROPIC_LOOKBACK_POSITIONS, findAnthropicModel, resolveModel } from "./pricing.js";
|
|
3
|
+
import { openAiCachePlan, openAiCacheScope } from "./openai-breakpoints.js";
|
|
4
|
+
import { containsVolatilePattern } from "./volatile.js";
|
|
5
|
+
import { sameModel } from "./model-id.js";
|
|
6
|
+
import { comparisonKeys } from "./prefix.js";
|
|
7
|
+
import { anthropicPositions } from "./anthropic-breakpoints.js";
|
|
8
|
+
import { anthropicMessageCacheScope, isAnthropicMessageSegment } from "./anthropic-cache-scope.js";
|
|
9
|
+
import { anthropicSpeed, anthropicSpeedKey, anthropicSpeedMultiplier } from "./anthropic-speed.js";
|
|
10
|
+
import { anthropicReasoningScope } from "./anthropic-reasoning.js";
|
|
11
|
+
import { anthropicInjectedSettings } from "./anthropic-injected-settings.js";
|
|
12
|
+
import { sumTokenCounts } from "./media-accounting.js";
|
|
13
|
+
function push(list, f) {
|
|
14
|
+
list.push(f);
|
|
15
|
+
}
|
|
16
|
+
function toolSegments(request) {
|
|
17
|
+
return request.segments.filter((s) => s.category === "tools");
|
|
18
|
+
}
|
|
19
|
+
// A gap between actual and optimized cost below this fraction isn't worth a finding of its own -
|
|
20
|
+
// matches the ">10%" bar findings.test.ts and the CLI/web "potential savings" framing both use,
|
|
21
|
+
// so "no findings" and "no material savings shown" always agree (see missing_tail_breakpoint below).
|
|
22
|
+
const MATERIAL_SAVINGS_RATIO = 0.1;
|
|
23
|
+
// Finding kinds that already explain *why* a request's cache isn't paying off - if one of these
|
|
24
|
+
// already fired for a request, missing_tail_breakpoint would just be restating the same gap in
|
|
25
|
+
// different words, so it's skipped there.
|
|
26
|
+
const EXPLAINS_CACHE_GAP = new Set(["volatile_prefix", "breakpoint_before_change", "no_cache_control", "below_minimum_cacheable", "model_switch"]);
|
|
27
|
+
/** Only the window of positions that moved: "positions 2-3: [read_file, grep_search] → [grep_search, read_file]". */
|
|
28
|
+
export function describeReorder(before, after) {
|
|
29
|
+
let first = 0;
|
|
30
|
+
while (first < before.length && before[first] === after[first])
|
|
31
|
+
first++;
|
|
32
|
+
let last = before.length - 1;
|
|
33
|
+
while (last > first && before[last] === after[last])
|
|
34
|
+
last--;
|
|
35
|
+
const span = first === last ? `position ${first + 1}` : `positions ${first + 1}–${last + 1}`;
|
|
36
|
+
return `${span}: [${before.slice(first, last + 1).join(", ")}] → [${after.slice(first, last + 1).join(", ")}]`;
|
|
37
|
+
}
|
|
38
|
+
/** A tool definition's name, wherever the provider puts it: top level, or under `function` in
|
|
39
|
+
* Chat Completions. Undefined for an entry that isn't a tool object at all. */
|
|
40
|
+
function toolName(raw) {
|
|
41
|
+
if (!isRecord(raw))
|
|
42
|
+
return undefined;
|
|
43
|
+
const fn = raw["function"];
|
|
44
|
+
return raw["name"] ?? (isRecord(fn) ? fn["name"] : undefined);
|
|
45
|
+
}
|
|
46
|
+
/** A system segment counts as the system prompt only if no conversation turn comes before it
|
|
47
|
+
* (a mid-conversation system message is operator text too, but not "the system prompt"). */
|
|
48
|
+
function isSystemPrompt(segments, index) {
|
|
49
|
+
if (segments[index]?.category !== "system")
|
|
50
|
+
return false;
|
|
51
|
+
return segments.slice(0, index).every((seg) => seg.category === "tools" || seg.category === "system");
|
|
52
|
+
}
|
|
53
|
+
/** The request cut down to its tools and system prompt, or to `atLeast` segments if that is more. */
|
|
54
|
+
function setupOf(request, atLeast) {
|
|
55
|
+
let setup = 0;
|
|
56
|
+
while (setup < request.segments.length && (request.segments[setup].category === "tools" || request.segments[setup].category === "system"))
|
|
57
|
+
setup++;
|
|
58
|
+
return { ...request, segments: request.segments.slice(0, Math.max(setup, atLeast)) };
|
|
59
|
+
}
|
|
60
|
+
function volatileFix(provider, modelInfo) {
|
|
61
|
+
if (provider === "anthropic" && modelInfo?.midConversationSystem) {
|
|
62
|
+
return `Move it out of the cached region: ${modelInfo.displayName} accepts a mid-conversation {"role": "system"} message after the cached history, or put it at the end of the latest user turn.`;
|
|
63
|
+
}
|
|
64
|
+
return "Move it out of the cached region, e.g. to the end of the latest user turn.";
|
|
65
|
+
}
|
|
66
|
+
export function computeFindings(provider, requests, prefixMatches, model, duplicates, cacheSimulation) {
|
|
67
|
+
const findings = [];
|
|
68
|
+
// Each request is compared with the request it continues (threads.ts), which in a file that
|
|
69
|
+
// holds several conversations is not the line before it.
|
|
70
|
+
const matchTo = new Map(prefixMatches.map((match) => [match.toIndex, match]));
|
|
71
|
+
const previousOpenAiScope = new Map();
|
|
72
|
+
requests.forEach((request, i) => {
|
|
73
|
+
const modelInfo = provider === "anthropic" ? findAnthropicModel(resolveModel(provider, model, [request.model]).id) : undefined;
|
|
74
|
+
const cacheStep = cacheSimulation.actual[i];
|
|
75
|
+
const mediaSegments = request.segments.filter(s => s.unmodeledContent?.length);
|
|
76
|
+
const mcpSegments = request.segments.filter(s => s.unmodeledContext === "mcp_tools");
|
|
77
|
+
if (mcpSegments.length)
|
|
78
|
+
push(findings, {
|
|
79
|
+
kind: provider === "anthropic" ? "anthropic_mcp_context" : "openai_mcp_context", severity: "warning", requestIndex: i,
|
|
80
|
+
title: "MCP tool context is not modeled",
|
|
81
|
+
detail: "The MCP connector resolves tools on the provider side. Server connection settings and toolset configuration are not the loaded definitions or their model-facing rendering. Pinned lists and recorded listings remain inspectable, but this estimator does not implement their MCP rendering either. Visible text retains its counts; whole-request totals, context usage and sequence cache partitions and costs are unavailable. Nothing is fetched from a server URL, and captured provider usage is retained without inventing an estimated comparison.",
|
|
82
|
+
segmentIds: mcpSegments.map(s => s.id),
|
|
83
|
+
});
|
|
84
|
+
const contextSegments = request.segments.filter(s => s.unmodeledContext && s.unmodeledContext !== "mcp_tools");
|
|
85
|
+
if (contextSegments.length)
|
|
86
|
+
push(findings, {
|
|
87
|
+
kind: "openai_unmodeled_context", severity: "warning", requestIndex: i,
|
|
88
|
+
title: "Stored or opaque context is unresolved",
|
|
89
|
+
detail: "These units reference stored responses, conversations, prompt templates or input items, or contain opaque reasoning/compaction history. The file does not supply their complete resolved prompt. Visible text segments retain their counts, but whole-request totals and context usage are unavailable. Cache partitions and costs are unavailable for the whole sequence. Nothing is fetched or reconstructed from an ID, summary or ciphertext. Original units and captured usage remain inspectable; no comparison is invented for an unavailable side.",
|
|
90
|
+
segmentIds: contextSegments.map(s => s.id),
|
|
91
|
+
});
|
|
92
|
+
if (mediaSegments.length)
|
|
93
|
+
push(findings, {
|
|
94
|
+
kind: "unmodeled_media", severity: "warning", requestIndex: i,
|
|
95
|
+
title: "Media token counts are unavailable",
|
|
96
|
+
detail: "These segments contain media or opaque document/file references. Encoded bytes, URLs and file IDs are not model token counts. Request totals and context usage are unavailable. Cache token partitions and costs are unavailable for the whole sequence because unknown lengths affect thresholds and prior entries. Other segments retain their text counts, and original blocks remain inspectable. Captured provider usage remains visible. A scalar calibration cannot recover the missing media segments.",
|
|
97
|
+
segmentIds: mediaSegments.map(s => s.id),
|
|
98
|
+
});
|
|
99
|
+
if (provider === "anthropic") {
|
|
100
|
+
const injected = anthropicInjectedSettings(request);
|
|
101
|
+
if (injected.format !== null || injected.citations)
|
|
102
|
+
push(findings, {
|
|
103
|
+
kind: "anthropic_injected_prompt", severity: "info", requestIndex: i,
|
|
104
|
+
title: injected.format !== null ? "Output-format instructions are not counted" : "Citation instructions are not counted",
|
|
105
|
+
detail: `${injected.format !== null ? "Structured output format" : "Enabled citations"} adds provider-side prompt instructions. The local token estimator does not reproduce those instructions, so these totals and costs omit their overhead. Cache scope changes are still respected. A count_tokens calibration request preserves output configuration and citation controls, but one calibration scale cannot reproduce every hidden segment or establish an actual cache hit.`,
|
|
106
|
+
segmentIds: [],
|
|
107
|
+
});
|
|
108
|
+
}
|
|
109
|
+
if (provider === "anthropic" && isRecord(request.raw) && request.raw.speed !== undefined && request.raw.speed !== "standard") {
|
|
110
|
+
const speed = anthropicSpeed(request);
|
|
111
|
+
const multiplier = anthropicSpeedMultiplier(request, resolveModel(provider, model, [request.model]));
|
|
112
|
+
push(findings, {
|
|
113
|
+
kind: "anthropic_speed", severity: multiplier === undefined ? "warning" : "info", requestIndex: i,
|
|
114
|
+
title: multiplier === undefined ? "Speed pricing unavailable" : speed === "standard" ? "Fast request modeled at standard speed" : "Fast input pricing",
|
|
115
|
+
detail: multiplier === undefined
|
|
116
|
+
? "This speed/model combination has no supported fast input price in the current table. Input costs and sequence totals are unavailable; token partitions remain hypothetical. Current Claude API fast mode supports Opus 5.5, Opus 5 and Opus 4.8, with a standard-speed fallback on Opus 4.6. An unsupported request may be rejected by the provider."
|
|
117
|
+
: speed === "standard"
|
|
118
|
+
? "The current Claude API documents that Opus 4.6 accepts speed: fast but runs at standard speed. This simulation uses the standard cache scope and price. Request data cannot verify historical behavior or the response's actual speed."
|
|
119
|
+
: "Fast mode uses 2x the resolved model's standard input rate, including cache reads and both write TTLs. The simulation uses current Claude API rates, not measured charges; response speed, beta headers, platform support and historical rates are not verified. The optimized scenario keeps this speed.",
|
|
120
|
+
segmentIds: [],
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
const modernOpenAi = provider === "openai" && (cacheStep?.cacheMode === "implicit" || cacheStep?.cacheMode === "explicit");
|
|
124
|
+
if (modernOpenAi) {
|
|
125
|
+
const scope = openAiCacheScope(request);
|
|
126
|
+
const priorIndex = previousOpenAiScope.get(scope);
|
|
127
|
+
previousOpenAiScope.set(scope, i);
|
|
128
|
+
// Thread inference may choose an identical setup on another cache key. Diagnose
|
|
129
|
+
// against the previous request in this cache namespace, not that other thread.
|
|
130
|
+
if (priorIndex !== undefined && cacheStep.readTokens === 0
|
|
131
|
+
&& (cacheSimulation.actual[priorIndex]?.writeTokens30m ?? 0) > 0
|
|
132
|
+
&& !(cacheStep.cacheMode === "explicit" && openAiCachePlan(request).explicit.length === 0)) {
|
|
133
|
+
const left = comparisonKeys(requests[priorIndex].segments, false);
|
|
134
|
+
const right = comparisonKeys(request.segments, false);
|
|
135
|
+
let shared = 0;
|
|
136
|
+
for (let s = 0; s < Math.min(left.length, right.length) && left[s] === right[s]; s++)
|
|
137
|
+
shared += request.segments[s].openaiTokens;
|
|
138
|
+
if (shared >= 1024)
|
|
139
|
+
push(findings, { kind: "openai_cache_boundary", severity: "warning", requestIndex: i,
|
|
140
|
+
title: "Shared text has no reusable cache boundary",
|
|
141
|
+
detail: `Request ${i + 1} shares ${shared.toLocaleString("en-US")} modeled prefix tokens with request ${priorIndex + 1}, but none of its eligible lookup boundaries finds a cached endpoint. Matching text alone is insufficient. Keep earlier message endings intact, or mark the end of the stable content explicitly in both requests. An explicit-only request checks its explicit boundaries; implicit lookup also has a message lookback limit.`,
|
|
142
|
+
segmentIds: [] });
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
if (modernOpenAi && cacheStep.cacheMode === "explicit" && openAiCachePlan(request).explicit.length === 0) {
|
|
146
|
+
push(findings, { kind: "openai_cache_disabled", severity: "info", requestIndex: i,
|
|
147
|
+
title: "Explicit caching has no breakpoints",
|
|
148
|
+
detail: `Request ${i + 1} selects explicit-only caching but marks no content blocks. This disables cache reads and writes, even when the prompt repeats. If caching is intended, add prompt_cache_breakpoint: {"mode":"explicit"} after the reusable content in both the earlier and later request.`,
|
|
149
|
+
segmentIds: [] });
|
|
150
|
+
}
|
|
151
|
+
// no_cache_control / below_minimum_cacheable only apply to Anthropic, whose caching is opt-in via a marker.
|
|
152
|
+
if (provider === "anthropic" && modelInfo) {
|
|
153
|
+
const totalTokens = sumTokenCounts(request.segments.map(s => s.claudeTokensEstimate));
|
|
154
|
+
const breakpoints = request.segments.filter((s) => s.cacheControl);
|
|
155
|
+
if (breakpoints.length === 0 && requests.length > 1 && totalTokens !== null && totalTokens >= modelInfo.minCacheableTokens) {
|
|
156
|
+
push(findings, {
|
|
157
|
+
kind: "no_cache_control",
|
|
158
|
+
severity: "warning",
|
|
159
|
+
requestIndex: i,
|
|
160
|
+
title: "No cache_control breakpoint set",
|
|
161
|
+
detail: `Request ${i + 1} carries ≈${totalTokens.toLocaleString("en-US")} Claude tokens but no cache_control marker, so nothing is ever cached even though this is part of a ${requests.length}-request sequence. One line turns it on: a top-level "cache_control": {"type": "ephemeral"} beside "model" puts a breakpoint on the last block of every request.`,
|
|
162
|
+
segmentIds: [],
|
|
163
|
+
});
|
|
164
|
+
}
|
|
165
|
+
for (const bp of breakpoints) {
|
|
166
|
+
const cum = sumTokenCounts(request.segments.slice(0, request.segments.indexOf(bp) + 1).map(s => s.claudeTokensEstimate));
|
|
167
|
+
if (cum !== null && cum < modelInfo.minCacheableTokens) {
|
|
168
|
+
push(findings, {
|
|
169
|
+
kind: "below_minimum_cacheable",
|
|
170
|
+
severity: "warning",
|
|
171
|
+
requestIndex: i,
|
|
172
|
+
title: "Prefix below minimum cacheable length",
|
|
173
|
+
detail: `The ${bp.cacheControl?.automatic ? "automatic breakpoint (top-level cache_control), which lands on" : "cache_control breakpoint at"} "${bp.label}"${bp.cacheControl?.automatic ? "," : ""} covers only ≈${cum.toLocaleString("en-US")} tokens, below ${modelInfo.displayName}'s ${modelInfo.minCacheableTokens.toLocaleString("en-US")}-token minimum - it silently never caches.`,
|
|
174
|
+
segmentIds: [bp.id],
|
|
175
|
+
});
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
const match = matchTo.get(i);
|
|
180
|
+
if (!match)
|
|
181
|
+
return;
|
|
182
|
+
const from = match.fromIndex;
|
|
183
|
+
const startsConversation = match.relation === "new_conversation";
|
|
184
|
+
// A new conversation shares its predecessor's setup (tools and system prompt) and whatever
|
|
185
|
+
// opening messages they have in common, not the rest of that other conversation.
|
|
186
|
+
const prev = startsConversation ? setupOf(requests[from], match.matchedSegments) : requests[from];
|
|
187
|
+
if (provider === "anthropic") {
|
|
188
|
+
const before = anthropicInjectedSettings(prev), after = anthropicInjectedSettings(request);
|
|
189
|
+
if (before.formatKey !== after.formatKey)
|
|
190
|
+
push(findings, {
|
|
191
|
+
kind: "anthropic_output_cache_scope", severity: "info", requestIndex: i,
|
|
192
|
+
title: "Output format changed the prompt cache",
|
|
193
|
+
detail: `The output format differs between requests ${from + 1} and ${i + 1}. Claude injects instructions for structured outputs, so this simulation separates their prompt caches even when the visible messages match. Grammar compilation caching is separate and does not establish prompt reuse. Schema descriptions and property order remain significant. Both scenarios preserve the format; an earlier request with the current format can still supply a hit.`,
|
|
194
|
+
segmentIds: request.segments.filter(s => s.cacheControl).map(s => s.id),
|
|
195
|
+
});
|
|
196
|
+
if (before.citations !== after.citations)
|
|
197
|
+
push(findings, {
|
|
198
|
+
kind: "anthropic_citation_cache_scope", severity: "info", requestIndex: i,
|
|
199
|
+
title: "Citation setting changed the system cache",
|
|
200
|
+
detail: `Citation enablement differs between requests ${from + 1} and ${i + 1}. Claude's citation instructions change the system prompt, so system and message cache entries from that request cannot supply a hit, including before the cited document. Separately marked tool entries remain eligible. An earlier request with the current citation setting can still supply a hit; both scenarios preserve the setting.`,
|
|
201
|
+
segmentIds: request.segments.filter(s => s.cacheControl && !s.path.startsWith("tools[")).map(s => s.id),
|
|
202
|
+
});
|
|
203
|
+
}
|
|
204
|
+
if (provider === "anthropic" && request.segments.some((s) => s.cacheControl)) {
|
|
205
|
+
const before = anthropicReasoningScope(prev), after = anthropicReasoningScope(request);
|
|
206
|
+
const changed = [before.thinking !== after.thinking ? "thinking configuration" : "",
|
|
207
|
+
before.effort !== after.effort ? "output_config.effort" : ""].filter(Boolean);
|
|
208
|
+
if (changed.length)
|
|
209
|
+
push(findings, {
|
|
210
|
+
kind: "anthropic_reasoning_cache_scope", severity: "info", requestIndex: i,
|
|
211
|
+
title: "Thinking or effort cache settings changed",
|
|
212
|
+
detail: `${changed.join(" and ")} differs between requests ${from + 1} and ${i + 1}. Anthropic documents that these changes invalidate message entries even when visible text is identical. Tool and system survival is model-specific: this simulation conservatively isolates all three cache levels rather than inferring the provider's hidden prompt placement. Actual setup reuse and costs may differ. An earlier request with the current settings can still supply a hit. Both scenarios keep these settings; documented mode and effort defaults are normalized only for recognized recorded models.`,
|
|
213
|
+
segmentIds: request.segments.filter((s) => s.cacheControl).map((s) => s.id),
|
|
214
|
+
});
|
|
215
|
+
}
|
|
216
|
+
if (provider === "anthropic" && anthropicSpeedKey(prev) !== anthropicSpeedKey(request)) {
|
|
217
|
+
push(findings, {
|
|
218
|
+
kind: "anthropic_speed_cache_scope", severity: "info", requestIndex: i,
|
|
219
|
+
title: "Processing speed changed",
|
|
220
|
+
detail: `Processing speed differs between requests ${from + 1} and ${i + 1}. System and message cache entries from that request cannot supply a hit, even when the visible prefix matches. Separately marked tool entries remain eligible. An earlier request at the current speed can still supply a hit. Both simulation scenarios preserve the speed setting.`,
|
|
221
|
+
segmentIds: request.segments.filter((s) => s.cacheControl && !s.path.startsWith("tools[")).map((s) => s.id),
|
|
222
|
+
});
|
|
223
|
+
}
|
|
224
|
+
if (provider === "anthropic" && request.segments.some((s) => s.cacheControl && isAnthropicMessageSegment(s))) {
|
|
225
|
+
const before = anthropicMessageCacheScope(prev);
|
|
226
|
+
const after = anthropicMessageCacheScope(request);
|
|
227
|
+
const changed = [before.toolChoice !== after.toolChoice ? "tool_choice" : "", before.hasImages !== after.hasImages ? "image presence" : ""].filter(Boolean);
|
|
228
|
+
if (changed.length > 0)
|
|
229
|
+
push(findings, {
|
|
230
|
+
kind: "anthropic_message_cache_scope", severity: "info", requestIndex: i,
|
|
231
|
+
title: "Message cache settings changed",
|
|
232
|
+
detail: `${changed.join(" and ")} differs between requests ${from + 1} and ${i + 1}. Message cache entries from that request cannot be reused, even when the visible prefix matches or an image was added after its breakpoint. These changes alone preserve stable tools and top-level system entries. An earlier request with the current settings can still supply a hit; inspect the read/write counts. The optimized scenario preserves these settings.`,
|
|
233
|
+
segmentIds: request.segments.filter((s) => s.cacheControl && isAnthropicMessageSegment(s)).map((s) => s.id),
|
|
234
|
+
});
|
|
235
|
+
}
|
|
236
|
+
// A change blocks reuse from this predecessor, but not from earlier requests on the
|
|
237
|
+
// destination model. Missing metadata is not evidence that a switch actually happened.
|
|
238
|
+
if (prev.model && request.model && !sameModel(prev.model, request.model)) {
|
|
239
|
+
push(findings, {
|
|
240
|
+
kind: "model_switch",
|
|
241
|
+
severity: "warning",
|
|
242
|
+
requestIndex: i,
|
|
243
|
+
title: `Model changed between requests ${from + 1} and ${i + 1}`,
|
|
244
|
+
detail: `Request ${from + 1} ran on ${prev.model} and request ${i + 1} on ${request.model}. Request ${i + 1} cannot reuse cache entries from ${prev.model}; it can still reuse a matching prefix that earlier requests on ${request.model} cached. Inspect this request's simulated read and write counts before attributing cost to the switch.`,
|
|
245
|
+
segmentIds: [],
|
|
246
|
+
});
|
|
247
|
+
}
|
|
248
|
+
// volatile_prefix: a timestamp/UUID/epoch inside the stable-looking prefix busts the match every time.
|
|
249
|
+
const boundary = Math.min(prev.segments.length, request.segments.length);
|
|
250
|
+
for (let s = 0; s < boundary; s++) {
|
|
251
|
+
const a = prev.segments[s];
|
|
252
|
+
const b = request.segments[s];
|
|
253
|
+
if (a.category !== b.category)
|
|
254
|
+
break;
|
|
255
|
+
if (comparisonKeys([a], false)[0] === comparisonKeys([b], false)[0])
|
|
256
|
+
continue;
|
|
257
|
+
if ((containsVolatilePattern(a.text) || containsVolatilePattern(b.text))
|
|
258
|
+
&& comparisonKeys([a], true)[0] === comparisonKeys([b], true)[0]) {
|
|
259
|
+
push(findings, {
|
|
260
|
+
kind: "volatile_prefix",
|
|
261
|
+
severity: "error",
|
|
262
|
+
requestIndex: i,
|
|
263
|
+
title: `${isSystemPrompt(request.segments, s) ? "System prompt" : b.label} contains a value that changes every request`,
|
|
264
|
+
detail: `"${b.label}" differs between requests ${from + 1} and ${i + 1}, and looks like a timestamp/UUID/epoch value. Every byte after this point falls out of the cached prefix on every request. ${volatileFix(provider, modelInfo)}`,
|
|
265
|
+
segmentIds: [a.id, b.id],
|
|
266
|
+
});
|
|
267
|
+
}
|
|
268
|
+
break; // only the first divergence point is the interesting one for this finding
|
|
269
|
+
}
|
|
270
|
+
// tools_reordered / tool_schema_key_order
|
|
271
|
+
const prevTools = toolSegments(prev);
|
|
272
|
+
const currTools = toolSegments(request);
|
|
273
|
+
if (prevTools.length > 0 && currTools.length > 0) {
|
|
274
|
+
const prevNames = prevTools.map((t) => toolName(t.raw));
|
|
275
|
+
const currNames = currTools.map((t) => toolName(t.raw));
|
|
276
|
+
const sameSet = prevNames.length === currNames.length && [...prevNames].sort().join("|") === [...currNames].sort().join("|");
|
|
277
|
+
if (sameSet && prevNames.join("|") !== currNames.join("|")) {
|
|
278
|
+
push(findings, {
|
|
279
|
+
kind: "tools_reordered",
|
|
280
|
+
severity: "error",
|
|
281
|
+
requestIndex: i,
|
|
282
|
+
title: `Tools reordered between requests ${from + 1} and ${i + 1}`,
|
|
283
|
+
detail: `Same ${currNames.length} tools, different order: ${describeReorder(prevNames.map(String), currNames.map(String))}. Tools render at position 0 of the prefix, so any reorder invalidates the entire cache. Sort tools deterministically (e.g. by name) before sending.`,
|
|
284
|
+
segmentIds: currTools.map((t) => t.id),
|
|
285
|
+
});
|
|
286
|
+
}
|
|
287
|
+
for (const currTool of currTools) {
|
|
288
|
+
const name = toolName(currTool.raw);
|
|
289
|
+
const prevTool = prevTools.find((t) => toolName(t.raw) === name);
|
|
290
|
+
if (!prevTool)
|
|
291
|
+
continue;
|
|
292
|
+
if (canonicalJson(prevTool.raw) === canonicalJson(currTool.raw)) {
|
|
293
|
+
// Sorted-key form is identical (same tool, same content) - any difference in the raw
|
|
294
|
+
// insertion order is pure key-order drift, not a content change.
|
|
295
|
+
const fpPrev = keyOrderFingerprint(prevTool.raw).join(",");
|
|
296
|
+
const fpCurr = keyOrderFingerprint(currTool.raw).join(",");
|
|
297
|
+
if (fpPrev !== fpCurr) {
|
|
298
|
+
push(findings, {
|
|
299
|
+
kind: "tool_schema_key_order",
|
|
300
|
+
severity: "error",
|
|
301
|
+
requestIndex: i,
|
|
302
|
+
title: `Tool "${String(name)}" schema key order differs`,
|
|
303
|
+
detail: `The "${String(name)}" tool definition is semantically identical between requests ${from + 1} and ${i + 1}, but its JSON key order changed - almost always non-deterministic object key iteration (e.g. building the schema from an unordered map/set) upstream. Serialize tool schemas with sorted keys before sending.`,
|
|
304
|
+
segmentIds: [prevTool.id, currTool.id],
|
|
305
|
+
});
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
// breakpoint_before_change: a cache_control marker whose covered content is itself in the
|
|
311
|
+
// diverged region *and* existed (at that same position) in the previous request - i.e. it's
|
|
312
|
+
// genuinely unstable content (a timestamp, a UUID), not simply new content this turn. A
|
|
313
|
+
// rolling breakpoint deliberately placed on the newest tail segment always fails the first
|
|
314
|
+
// check (idx >= matchedSegments, since brand-new content is never part of the matched prefix)
|
|
315
|
+
// but is the *correct* pattern, not a bug - the second check (idx < prev.segments.length)
|
|
316
|
+
// excludes it: a genuinely new position has no corresponding segment in the previous request
|
|
317
|
+
// to have "changed" from.
|
|
318
|
+
if (provider === "anthropic") {
|
|
319
|
+
for (const bp of request.segments.filter((s) => s.cacheControl)) {
|
|
320
|
+
const idx = request.segments.indexOf(bp);
|
|
321
|
+
if (idx >= match.matchedSegments && idx < prev.segments.length) {
|
|
322
|
+
push(findings, {
|
|
323
|
+
kind: "breakpoint_before_change",
|
|
324
|
+
severity: "warning",
|
|
325
|
+
requestIndex: i,
|
|
326
|
+
title: "Cache breakpoint placed after content that changes",
|
|
327
|
+
detail: `"${bp.label}" carries ${bp.cacheControl?.automatic ? "the automatic breakpoint (top-level cache_control)" : "a cache_control marker"}, but it (or something before it) already differs from request ${from + 1}. The breakpoint can only pay off once the content it covers is stable.`,
|
|
328
|
+
segmentIds: [bp.id],
|
|
329
|
+
});
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
// lookback_window_exceeded (approximate re-check, mirrors cache-anthropic.ts's own distance test).
|
|
333
|
+
// Not for a new conversation: its first breakpoints have no earlier entry of their own to find.
|
|
334
|
+
if (startsConversation)
|
|
335
|
+
return;
|
|
336
|
+
const positions = anthropicPositions(request.segments);
|
|
337
|
+
const boundaryPos = match.matchedSegments > 0 ? positions[match.matchedSegments - 1] : -1;
|
|
338
|
+
for (const bp of request.segments.filter((s) => s.cacheControl)) {
|
|
339
|
+
const idx = request.segments.indexOf(bp);
|
|
340
|
+
if (idx < match.matchedSegments)
|
|
341
|
+
continue;
|
|
342
|
+
const distance = positions[idx] - boundaryPos;
|
|
343
|
+
if (distance >= ANTHROPIC_LOOKBACK_POSITIONS) {
|
|
344
|
+
push(findings, {
|
|
345
|
+
kind: "lookback_window_exceeded",
|
|
346
|
+
severity: "warning",
|
|
347
|
+
requestIndex: i,
|
|
348
|
+
title: "Breakpoint is outside the 20-position lookback window",
|
|
349
|
+
detail: `"${bp.label}" sits ${distance} positions past the last matching prefix boundary with request ${from + 1}. Anthropic checks 20 positions including the breakpoint itself, so this lookup cannot reach that boundary. An intermediate breakpoint closer to it can find a cache entry there if an earlier request wrote one.`,
|
|
350
|
+
segmentIds: [bp.id],
|
|
351
|
+
});
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
});
|
|
356
|
+
for (const group of duplicates) {
|
|
357
|
+
if (group.members.length < 2)
|
|
358
|
+
continue;
|
|
359
|
+
const first = group.members[0];
|
|
360
|
+
push(findings, {
|
|
361
|
+
kind: "duplicate_content",
|
|
362
|
+
severity: "info",
|
|
363
|
+
requestIndex: first.requestIndex,
|
|
364
|
+
title: `${group.matchKind === "exact" ? "Identical text" : "Similar text"} appears in ${group.members.length} segments`,
|
|
365
|
+
detail: `"${first.label}" and ${group.members.length - 1} other segment${group.members.length > 2 ? "s" : ""} ${group.matchKind === "exact" ? "contain identical text" : `have at least ${Math.floor(group.similarity * 100)}% word-shingle similarity across every pair`}. Later matches contain an estimated ≈${group.estimatedReviewTokens.toLocaleString("en-US")} tokens to review, not proven savings. ${group.matchKind === "exact" ? "Check whether the repeated observations are needed before removing them." : "Edits, ordering and repetition can carry new information; inspect the original segments before consolidating them."}`,
|
|
366
|
+
segmentIds: group.members.map((m) => m.segmentId),
|
|
367
|
+
});
|
|
368
|
+
}
|
|
369
|
+
// missing_tail_breakpoint: the single most valuable fix for a real agent loop and the one the
|
|
370
|
+
// other checks above don't cover - a cache_control breakpoint exists somewhere (so
|
|
371
|
+
// no_cache_control didn't fire) and isn't sitting on volatile content (so
|
|
372
|
+
// breakpoint_before_change didn't fire either), but it also never advances to cover the
|
|
373
|
+
// conversation's growing tail, so every turn re-sends prior history uncached. Derived directly
|
|
374
|
+
// from the cache simulation's own actual-vs-optimized gap (not a separately-reasoned estimate),
|
|
375
|
+
// so this finding and the "potential savings" figure shown alongside it can never disagree: if
|
|
376
|
+
// the saving is material, this (or one of the finding kinds above) is why.
|
|
377
|
+
if (provider === "anthropic") {
|
|
378
|
+
requests.forEach((request, i) => {
|
|
379
|
+
const actualStep = cacheSimulation.actual[i];
|
|
380
|
+
const optimizedStep = cacheSimulation.optimized[i];
|
|
381
|
+
if (!actualStep || !optimizedStep)
|
|
382
|
+
return;
|
|
383
|
+
if (actualStep.costUsd === undefined || optimizedStep.costUsd === undefined || actualStep.costUsd <= 0)
|
|
384
|
+
return;
|
|
385
|
+
if (actualStep.uncachedTokens === null)
|
|
386
|
+
return;
|
|
387
|
+
const gapUsd = actualStep.costUsd - optimizedStep.costUsd;
|
|
388
|
+
const ratio = gapUsd / actualStep.costUsd;
|
|
389
|
+
if (ratio < MATERIAL_SAVINGS_RATIO)
|
|
390
|
+
return;
|
|
391
|
+
if (findings.some((f) => f.requestIndex === i && EXPLAINS_CACHE_GAP.has(f.kind)))
|
|
392
|
+
return;
|
|
393
|
+
push(findings, {
|
|
394
|
+
kind: "missing_tail_breakpoint",
|
|
395
|
+
severity: "warning",
|
|
396
|
+
requestIndex: i,
|
|
397
|
+
title: "No cache breakpoint on the conversation tail",
|
|
398
|
+
detail: `This request resends ≈${actualStep.uncachedTokens.toLocaleString("en-US")} tokens of prior conversation history uncached - nothing after the last cache_control breakpoint (or there is none) covers the turns already in this conversation. A rolling breakpoint on the latest turn (Anthropic allows up to 4 per request, and each one needs to land within the 20-position lookback of the one it reads from) would let most of that history read from cache instead of resending it in full - estimated ≈$${gapUsd.toFixed(4)} (${Math.round(ratio * 100)}%) cheaper on this request alone.`,
|
|
399
|
+
segmentIds: [],
|
|
400
|
+
});
|
|
401
|
+
});
|
|
402
|
+
// Safety net for the invariant itself: the per-request loop above catches the common case
|
|
403
|
+
// (the gap is concentrated in individual requests, each clearing the 10% bar on its own), but
|
|
404
|
+
// a gap spread thinly across many requests could in principle stay under 10% on every single
|
|
405
|
+
// one while still summing to a material total. Check the aggregate the cost line itself shows
|
|
406
|
+
// and, if nothing above already explains it, point at the single request with the largest
|
|
407
|
+
// absolute gap - "no findings" must never coexist with a materially non-zero savings figure.
|
|
408
|
+
const { totalActualCostUsd, totalOptimizedCostUsd } = cacheSimulation;
|
|
409
|
+
if (totalActualCostUsd !== undefined && totalOptimizedCostUsd !== undefined && totalActualCostUsd > 0) {
|
|
410
|
+
const aggregateRatio = (totalActualCostUsd - totalOptimizedCostUsd) / totalActualCostUsd;
|
|
411
|
+
const alreadyExplained = findings.some((f) => EXPLAINS_CACHE_GAP.has(f.kind) || f.kind === "missing_tail_breakpoint");
|
|
412
|
+
if (aggregateRatio >= MATERIAL_SAVINGS_RATIO && !alreadyExplained) {
|
|
413
|
+
let worst = { index: -1, gap: -Infinity };
|
|
414
|
+
cacheSimulation.actual.forEach((step, i) => {
|
|
415
|
+
const optimizedCost = cacheSimulation.optimized[i]?.costUsd;
|
|
416
|
+
if (step.costUsd === undefined || optimizedCost === undefined)
|
|
417
|
+
return;
|
|
418
|
+
const gap = step.costUsd - optimizedCost;
|
|
419
|
+
if (gap > worst.gap)
|
|
420
|
+
worst = { index: i, gap };
|
|
421
|
+
});
|
|
422
|
+
if (worst.index >= 0) {
|
|
423
|
+
push(findings, {
|
|
424
|
+
kind: "missing_tail_breakpoint",
|
|
425
|
+
severity: "warning",
|
|
426
|
+
requestIndex: worst.index,
|
|
427
|
+
title: "No cache breakpoint on the conversation tail",
|
|
428
|
+
detail: `Across this sequence, caching the growing conversation tail (in addition to whatever's cached today) would cost ≈$${totalOptimizedCostUsd.toFixed(4)} instead of ≈$${totalActualCostUsd.toFixed(4)} - about ${Math.round(aggregateRatio * 100)}% lower, spread across requests rather than concentrated in any single one. A rolling cache_control breakpoint on the latest turn each request is the fix.`,
|
|
429
|
+
segmentIds: [],
|
|
430
|
+
});
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
}
|
|
435
|
+
return findings;
|
|
436
|
+
}
|
|
437
|
+
//# sourceMappingURL=findings.js.map
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import type { Finding, FindingKind, FindingSeverity } from "./types.js";
|
|
2
|
+
/**
|
|
3
|
+
* One problem reported once, however many requests it recurs in. A timestamp
|
|
4
|
+
* in the system prompt fires `volatile_prefix` on every request of a
|
|
5
|
+
* 300-turn session; listing 299 identical findings buries everything else, so
|
|
6
|
+
* the CLI and the web app show groups and keep the individual findings one
|
|
7
|
+
* click away.
|
|
8
|
+
*/
|
|
9
|
+
export interface FindingGroup {
|
|
10
|
+
kind: FindingKind;
|
|
11
|
+
severity: FindingSeverity;
|
|
12
|
+
title: string;
|
|
13
|
+
/** Detail text of the first occurrence. */
|
|
14
|
+
detail: string;
|
|
15
|
+
/** 0-based request indices the finding fired on, ascending and unique. */
|
|
16
|
+
requestIndices: number[];
|
|
17
|
+
/** The underlying findings, in their original order. */
|
|
18
|
+
findings: Finding[];
|
|
19
|
+
}
|
|
20
|
+
/** Groups equivalent messages about the same segments; orders by severity, then first occurrence. */
|
|
21
|
+
export declare function groupFindings(findings: readonly Finding[]): FindingGroup[];
|
|
22
|
+
/** "request 3", "requests 2-24", "requests 2, 5, 7-9" (1-based, en dash for ranges). */
|
|
23
|
+
export declare function describeRequestIndices(indices: readonly number[]): string;
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
const SEVERITY_RANK = { error: 0, warning: 1, info: 2 };
|
|
2
|
+
// Titles that name a specific request pair only make sense for a single occurrence.
|
|
3
|
+
const GROUP_TITLE = {
|
|
4
|
+
tools_reordered: "Tools reordered between requests",
|
|
5
|
+
model_switch: "Model changed mid-conversation",
|
|
6
|
+
};
|
|
7
|
+
/** Groups equivalent messages about the same segments; orders by severity, then first occurrence. */
|
|
8
|
+
export function groupFindings(findings) {
|
|
9
|
+
const groups = new Map();
|
|
10
|
+
for (const finding of findings) {
|
|
11
|
+
// Duplicate detection already suppresses repeated evidence across requests.
|
|
12
|
+
// Reused source paths can describe different text or an exact/near match;
|
|
13
|
+
// merging them here would apply the first occurrence's claim to all of them.
|
|
14
|
+
const requestScope = finding.kind === "duplicate_content" ? finding.requestIndex : null;
|
|
15
|
+
// A kind can have different meanings and severities: fast input pricing,
|
|
16
|
+
// standard-speed fallback, or unavailable pricing. None represents the others.
|
|
17
|
+
// Only known request-pair titles have a common meaning despite different text.
|
|
18
|
+
const title = GROUP_TITLE[finding.kind] ?? finding.title;
|
|
19
|
+
const key = JSON.stringify([
|
|
20
|
+
finding.kind, finding.severity, title, requestScope, [...new Set(finding.segmentIds)].sort(),
|
|
21
|
+
]);
|
|
22
|
+
const group = groups.get(key);
|
|
23
|
+
if (group) {
|
|
24
|
+
group.findings.push(finding);
|
|
25
|
+
if (!group.requestIndices.includes(finding.requestIndex))
|
|
26
|
+
group.requestIndices.push(finding.requestIndex);
|
|
27
|
+
}
|
|
28
|
+
else {
|
|
29
|
+
groups.set(key, {
|
|
30
|
+
kind: finding.kind,
|
|
31
|
+
severity: finding.severity,
|
|
32
|
+
title: finding.title,
|
|
33
|
+
detail: finding.detail,
|
|
34
|
+
requestIndices: [finding.requestIndex],
|
|
35
|
+
findings: [finding],
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
const out = [...groups.values()];
|
|
40
|
+
for (const group of out) {
|
|
41
|
+
group.requestIndices.sort((a, b) => a - b);
|
|
42
|
+
const generic = GROUP_TITLE[group.kind];
|
|
43
|
+
if (generic && group.requestIndices.length > 1)
|
|
44
|
+
group.title = generic;
|
|
45
|
+
}
|
|
46
|
+
return out.sort((a, b) => SEVERITY_RANK[a.severity] - SEVERITY_RANK[b.severity] || a.requestIndices[0] - b.requestIndices[0]);
|
|
47
|
+
}
|
|
48
|
+
/** "request 3", "requests 2-24", "requests 2, 5, 7-9" (1-based, en dash for ranges). */
|
|
49
|
+
export function describeRequestIndices(indices) {
|
|
50
|
+
const sorted = [...new Set(indices)].sort((a, b) => a - b);
|
|
51
|
+
if (sorted.length === 0)
|
|
52
|
+
return "";
|
|
53
|
+
if (sorted.length === 1)
|
|
54
|
+
return `request ${sorted[0] + 1}`;
|
|
55
|
+
const parts = [];
|
|
56
|
+
let start = sorted[0];
|
|
57
|
+
let prev = start;
|
|
58
|
+
for (const idx of [...sorted.slice(1), Number.NaN]) {
|
|
59
|
+
if (idx === prev + 1) {
|
|
60
|
+
prev = idx;
|
|
61
|
+
continue;
|
|
62
|
+
}
|
|
63
|
+
parts.push(start === prev ? `${start + 1}` : prev === start + 1 ? `${start + 1}, ${prev + 1}` : `${start + 1}–${prev + 1}`);
|
|
64
|
+
start = idx;
|
|
65
|
+
prev = idx;
|
|
66
|
+
}
|
|
67
|
+
return `requests ${parts.join(", ")}`;
|
|
68
|
+
}
|
|
69
|
+
//# sourceMappingURL=group-findings.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from "./analyze.js";
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { AnalysisResult } from "./types.js";
|
|
2
|
+
/**
|
|
3
|
+
* The analysis as JSON: every count, finding and cache step, and none of the request content it
|
|
4
|
+
* was computed from. The in-memory result holds each request body, each segment's text and each
|
|
5
|
+
* segment's original block, so serializing it whole wrote the input back out about five times
|
|
6
|
+
* over (a 46 MB session became a 252 MB file and took 1.3 GB to build). A segment's `path` says
|
|
7
|
+
* where its content is in its request (a message whose content is a plain string counts as one
|
|
8
|
+
* block, `content[0]`).
|
|
9
|
+
*/
|
|
10
|
+
export declare function toJsonReport(result: AnalysisResult): string;
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
/** A segment as `--json` writes it: where it is, what it is and what it costs, without its content. */
|
|
2
|
+
function summarize(segment) {
|
|
3
|
+
return {
|
|
4
|
+
id: segment.id,
|
|
5
|
+
category: segment.category,
|
|
6
|
+
label: segment.label,
|
|
7
|
+
path: segment.path,
|
|
8
|
+
openaiTokens: segment.openaiTokens,
|
|
9
|
+
claudeTokensEstimate: segment.claudeTokensEstimate,
|
|
10
|
+
...(segment.unmodeledContent ? { unmodeledContent: segment.unmodeledContent } : {}),
|
|
11
|
+
...(segment.unmodeledContext ? { unmodeledContext: segment.unmodeledContext } : {}),
|
|
12
|
+
...(segment.cacheControl ? { cacheControl: segment.cacheControl } : {}),
|
|
13
|
+
...(segment.promptCacheBreakpoint ? { promptCacheBreakpoint: true } : {}),
|
|
14
|
+
charLength: segment.charLength,
|
|
15
|
+
};
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* The analysis as JSON: every count, finding and cache step, and none of the request content it
|
|
19
|
+
* was computed from. The in-memory result holds each request body, each segment's text and each
|
|
20
|
+
* segment's original block, so serializing it whole wrote the input back out about five times
|
|
21
|
+
* over (a 46 MB session became a 252 MB file and took 1.3 GB to build). A segment's `path` says
|
|
22
|
+
* where its content is in its request (a message whose content is a plain string counts as one
|
|
23
|
+
* block, `content[0]`).
|
|
24
|
+
*/
|
|
25
|
+
export function toJsonReport(result) {
|
|
26
|
+
const report = {
|
|
27
|
+
...result,
|
|
28
|
+
parse: {
|
|
29
|
+
...result.parse,
|
|
30
|
+
requests: result.parse.requests.map((request) => ({
|
|
31
|
+
provider: request.provider,
|
|
32
|
+
index: request.index,
|
|
33
|
+
model: request.model,
|
|
34
|
+
source: request.source,
|
|
35
|
+
reportedUsage: request.reportedUsage,
|
|
36
|
+
segments: request.segments.map(summarize),
|
|
37
|
+
})),
|
|
38
|
+
},
|
|
39
|
+
reports: result.reports.map((r) => ({ ...r, segments: r.segments.map(summarize) })),
|
|
40
|
+
// A compact segment summary is insufficient if the readable diff still repeats
|
|
41
|
+
// its first 80 characters. Match counts/boundaries survive without those previews.
|
|
42
|
+
prefixMatches: result.prefixMatches.map((match) => ({ ...match, diff: undefined })),
|
|
43
|
+
};
|
|
44
|
+
return JSON.stringify(report, null, 2);
|
|
45
|
+
}
|
|
46
|
+
//# sourceMappingURL=json-report.js.map
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/** Small deterministic-serialization helpers shared by the parsers and findings. */
|
|
2
|
+
/** JSON.stringify with recursively sorted object keys, so semantically identical objects with
|
|
3
|
+
* different key order serialize identically. Used by the optimized cache scenario ("what if the
|
|
4
|
+
* schema were serialized deterministically") and by the key-order finding. */
|
|
5
|
+
export declare function canonicalJson(value: unknown): string;
|
|
6
|
+
/** A JSON object: not null, not an array. Request logs are untrusted input, so the parsers
|
|
7
|
+
* check before reading a field rather than assume the documented shape. */
|
|
8
|
+
export declare function isRecord(value: unknown): value is Record<string, unknown>;
|
|
9
|
+
/** The text of a segment: the string itself, or the JSON of whatever sits where a string
|
|
10
|
+
* should be, so a malformed block is still counted and compared instead of crashing the parse. */
|
|
11
|
+
export declare function asText(value: unknown): string;
|
|
12
|
+
/**
|
|
13
|
+
* A content block or tool definition as the API receives it - key order preserved, because the
|
|
14
|
+
* prompt is rendered in that order and a reordered key breaks the cached prefix - minus its
|
|
15
|
+
* `cache_control` or `prompt_cache_breakpoint` marker. A rolling breakpoint moves every turn; the marker isn't part of the
|
|
16
|
+
* cached content, so it must not make two otherwise identical blocks differ.
|
|
17
|
+
*/
|
|
18
|
+
export declare function blockJson(value: unknown): string;
|
|
19
|
+
/** blockJson with sorted keys: the same block if it were serialized deterministically. */
|
|
20
|
+
export declare function canonicalBlockJson(value: unknown): string;
|
|
21
|
+
/** Optimized content: sorted keys and volatile text, with routing identities preserved. */
|
|
22
|
+
export declare function normalizedBlockJson(value: unknown): string;
|
|
23
|
+
/** Recursively lists object keys in their ORIGINAL (insertion) order, depth-first, as
|
|
24
|
+
* "path.key" strings - used to detect "tool schema key order differs" between requests. */
|
|
25
|
+
export declare function keyOrderFingerprint(value: unknown, prefix?: string): string[];
|
|
26
|
+
/** A short, stable debugging signature (FNV-1a, 32-bit, hex).
|
|
27
|
+
* Collisions are possible; never use it to establish content identity. */
|
|
28
|
+
export declare function fnv1a(text: string): string;
|