@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,47 @@
|
|
|
1
|
+
import { canonicalJson, isRecord } from "./json-utils.js";
|
|
2
|
+
export function isAnthropicMessageSegment(segment) {
|
|
3
|
+
// A role:system message is still in the message cache, not the top-level system cache.
|
|
4
|
+
return segment.path.startsWith("messages[");
|
|
5
|
+
}
|
|
6
|
+
function hasImages(request) {
|
|
7
|
+
const messages = Array.isArray(request.messages) ? request.messages : [];
|
|
8
|
+
const pending = messages.flatMap((message) => isRecord(message) && Array.isArray(message.content) ? message.content : []);
|
|
9
|
+
while (pending.length) {
|
|
10
|
+
const block = pending.pop();
|
|
11
|
+
if (!isRecord(block))
|
|
12
|
+
continue;
|
|
13
|
+
if (block.type === "image")
|
|
14
|
+
return true;
|
|
15
|
+
// Follow content grammar only. A tool input or text may describe an image
|
|
16
|
+
// without actually including one in the prompt.
|
|
17
|
+
if ((block.type === "tool_result" || block.type === "mcp_tool_result") && Array.isArray(block.content)) {
|
|
18
|
+
for (const child of block.content)
|
|
19
|
+
pending.push(child);
|
|
20
|
+
}
|
|
21
|
+
else if (block.type === "document" && isRecord(block.source) && block.source.type === "content" && Array.isArray(block.source.content)) {
|
|
22
|
+
for (const child of block.source.content)
|
|
23
|
+
pending.push(child);
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
return false;
|
|
27
|
+
}
|
|
28
|
+
export function anthropicMessageCacheScope(request) {
|
|
29
|
+
const raw = isRecord(request.raw) ? request.raw : {};
|
|
30
|
+
let choice = raw.tool_choice;
|
|
31
|
+
if (choice === undefined || choice === null) {
|
|
32
|
+
// Documented defaults for ordinary tools. Unsupported toolset-only bodies
|
|
33
|
+
// retain an unspecified scope rather than guessing their implicit choice.
|
|
34
|
+
choice = Array.isArray(raw.tools) && raw.tools.length > 0 ? { type: "auto" }
|
|
35
|
+
: Array.isArray(raw.toolsets) && raw.toolsets.length > 0 ? null : { type: "none" };
|
|
36
|
+
}
|
|
37
|
+
if (isRecord(choice) && ["auto", "any", "tool"].includes(String(choice.type)) && choice.disable_parallel_tool_use === false) {
|
|
38
|
+
const normalized = { ...choice };
|
|
39
|
+
delete normalized.disable_parallel_tool_use;
|
|
40
|
+
choice = normalized;
|
|
41
|
+
}
|
|
42
|
+
return { toolChoice: canonicalJson(choice), hasImages: hasImages(raw) };
|
|
43
|
+
}
|
|
44
|
+
export function anthropicMessageCacheKey(scope) {
|
|
45
|
+
return JSON.stringify([scope.toolChoice, scope.hasImages]);
|
|
46
|
+
}
|
|
47
|
+
//# sourceMappingURL=anthropic-cache-scope.js.map
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { ParsedRequest } from "./types.js";
|
|
2
|
+
export interface AnthropicInjectedSettings {
|
|
3
|
+
format: Record<string, unknown> | null;
|
|
4
|
+
/** Schema property order is meaningful; do not canonicalize this key. */
|
|
5
|
+
formatKey: string;
|
|
6
|
+
citations: boolean;
|
|
7
|
+
}
|
|
8
|
+
/** Request controls that change provider-injected prompt instructions.
|
|
9
|
+
* This reads content grammar only: schema examples and tool inputs may quote
|
|
10
|
+
* documents without actually supplying a citable content block.
|
|
11
|
+
* https://platform.claude.com/docs/en/build-with-claude/structured-outputs#prompt-modification-and-token-costs
|
|
12
|
+
* https://platform.claude.com/docs/en/build-with-claude/prompt-caching#what-invalidates-the-cache
|
|
13
|
+
*/
|
|
14
|
+
export declare function anthropicInjectedSettings(request: Pick<ParsedRequest, "raw" | "index">): AnthropicInjectedSettings;
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { isRecord } from "./json-utils.js";
|
|
2
|
+
import { ContextScopeParseError } from "./parse-error.js";
|
|
3
|
+
/** Request controls that change provider-injected prompt instructions.
|
|
4
|
+
* This reads content grammar only: schema examples and tool inputs may quote
|
|
5
|
+
* documents without actually supplying a citable content block.
|
|
6
|
+
* https://platform.claude.com/docs/en/build-with-claude/structured-outputs#prompt-modification-and-token-costs
|
|
7
|
+
* https://platform.claude.com/docs/en/build-with-claude/prompt-caching#what-invalidates-the-cache
|
|
8
|
+
*/
|
|
9
|
+
export function anthropicInjectedSettings(request) {
|
|
10
|
+
const raw = isRecord(request.raw) ? request.raw : {};
|
|
11
|
+
const fail = (detail) => { throw new ContextScopeParseError(`Request ${request.index + 1}: ${detail}`); };
|
|
12
|
+
const config = raw.output_config;
|
|
13
|
+
const current = isRecord(config) ? config.format : undefined;
|
|
14
|
+
const legacy = raw.output_format;
|
|
15
|
+
if (current != null && legacy != null)
|
|
16
|
+
fail("both output_config.format and deprecated output_format are present; select one output format before simulating cache use.");
|
|
17
|
+
const value = current ?? legacy ?? null;
|
|
18
|
+
let format = null;
|
|
19
|
+
if (value !== null) {
|
|
20
|
+
if (!isRecord(value) || value.type !== "json_schema" || !isRecord(value.schema)) {
|
|
21
|
+
fail("output format must have type \"json_schema\" and an object-valued schema, or be null/omitted. Unsupported format settings cannot establish cache reuse.");
|
|
22
|
+
}
|
|
23
|
+
format = value;
|
|
24
|
+
}
|
|
25
|
+
const modes = { document: new Set(), search_result: new Set() };
|
|
26
|
+
function visit(block, path) {
|
|
27
|
+
if (!isRecord(block))
|
|
28
|
+
return;
|
|
29
|
+
if (block.type === "document" || block.type === "search_result") {
|
|
30
|
+
const citation = block.citations;
|
|
31
|
+
let enabled = false;
|
|
32
|
+
if (citation !== undefined && citation !== null) {
|
|
33
|
+
if (!isRecord(citation) || (citation.enabled !== undefined && typeof citation.enabled !== "boolean")) {
|
|
34
|
+
fail(`${path}.citations.enabled must be boolean when supplied; malformed citation controls cannot establish a cache scope.`);
|
|
35
|
+
}
|
|
36
|
+
enabled = citation.enabled ?? false;
|
|
37
|
+
}
|
|
38
|
+
modes[block.type].add(enabled);
|
|
39
|
+
}
|
|
40
|
+
else if ((block.type === "tool_result" || block.type === "mcp_tool_result") && Array.isArray(block.content)) {
|
|
41
|
+
block.content.forEach((child, i) => visit(child, `${path}.content[${i}]`));
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
if (Array.isArray(raw.messages))
|
|
45
|
+
raw.messages.forEach((message, i) => {
|
|
46
|
+
if (isRecord(message) && Array.isArray(message.content))
|
|
47
|
+
message.content.forEach((block, j) => visit(block, `messages[${i}].content[${j}]`));
|
|
48
|
+
});
|
|
49
|
+
if (modes.document.size > 1 || modes.search_result.size > 1) {
|
|
50
|
+
fail("mixed citation enablement within document or search_result blocks is unsupported by the API; enable citations on all blocks of that kind or on none.");
|
|
51
|
+
}
|
|
52
|
+
const citations = modes.document.has(true) || modes.search_result.has(true);
|
|
53
|
+
if (format !== null && citations)
|
|
54
|
+
fail("citations and structured output formats are incompatible; remove the output format or disable citations before simulating cache use.");
|
|
55
|
+
return { format, formatKey: JSON.stringify(format), citations };
|
|
56
|
+
}
|
|
57
|
+
//# sourceMappingURL=anthropic-injected-settings.js.map
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { ParsedRequest } from "./types.js";
|
|
2
|
+
export interface AnthropicReasoningScope {
|
|
3
|
+
thinking: string;
|
|
4
|
+
effort: string;
|
|
5
|
+
}
|
|
6
|
+
/** Top-level thinking/effort changes always invalidate message entries. Setup
|
|
7
|
+
* survival is model-specific, so the simulator conservatively isolates every
|
|
8
|
+
* level. This is not a prediction of the provider's hidden prompt placement.
|
|
9
|
+
* Per-message effort stays in message identity and never changes this scope.
|
|
10
|
+
* https://platform.claude.com/docs/en/build-with-claude/thinking#thinking-and-prompt-caching
|
|
11
|
+
*/
|
|
12
|
+
export declare function anthropicReasoningScope(request: ParsedRequest): AnthropicReasoningScope;
|
|
13
|
+
export declare function anthropicReasoningKey(request: ParsedRequest): string;
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { canonicalJson, isRecord } from "./json-utils.js";
|
|
2
|
+
import { normalizeModelId } from "./pricing.js";
|
|
3
|
+
// Claude API defaults checked 2026-10-16, not inferred from the pricing fallback.
|
|
4
|
+
// https://platform.claude.com/docs/en/build-with-claude/thinking#configuring-thinking
|
|
5
|
+
// https://platform.claude.com/docs/en/build-with-claude/effort#effort-levels
|
|
6
|
+
const DEFAULTS = {
|
|
7
|
+
"claude-fable-5-1": { thinking: "adaptive", effort: "high" },
|
|
8
|
+
"claude-fable-5": { thinking: "adaptive", effort: "high" },
|
|
9
|
+
"claude-mythos-5-1": { thinking: "adaptive", effort: "high" },
|
|
10
|
+
"claude-mythos-5": { thinking: "adaptive", effort: "high" },
|
|
11
|
+
"claude-mythos-preview": { thinking: "adaptive", effort: "high" },
|
|
12
|
+
"claude-opus-5-5": { thinking: "adaptive", effort: "medium" },
|
|
13
|
+
"claude-opus-5": { thinking: "adaptive", effort: "high" },
|
|
14
|
+
"claude-opus-4-8": { thinking: "disabled", effort: "high" },
|
|
15
|
+
"claude-opus-4-7": { thinking: "disabled", effort: "high" },
|
|
16
|
+
"claude-opus-4-6": { thinking: "disabled", effort: "high" },
|
|
17
|
+
"claude-opus-4-5": { thinking: "disabled", effort: "high" },
|
|
18
|
+
"claude-sonnet-5-5": { thinking: "adaptive", effort: "high" },
|
|
19
|
+
"claude-sonnet-5": { thinking: "adaptive", effort: "high" },
|
|
20
|
+
"claude-sonnet-4-6": { thinking: "disabled", effort: "high" },
|
|
21
|
+
"claude-sonnet-4-5": { thinking: "disabled" },
|
|
22
|
+
"claude-haiku-5-5": { thinking: "adaptive", effort: "medium" },
|
|
23
|
+
"claude-haiku-4-5": { thinking: "disabled" },
|
|
24
|
+
};
|
|
25
|
+
/** Top-level thinking/effort changes always invalidate message entries. Setup
|
|
26
|
+
* survival is model-specific, so the simulator conservatively isolates every
|
|
27
|
+
* level. This is not a prediction of the provider's hidden prompt placement.
|
|
28
|
+
* Per-message effort stays in message identity and never changes this scope.
|
|
29
|
+
* https://platform.claude.com/docs/en/build-with-claude/thinking#thinking-and-prompt-caching
|
|
30
|
+
*/
|
|
31
|
+
export function anthropicReasoningScope(request) {
|
|
32
|
+
const raw = isRecord(request.raw) ? request.raw : {};
|
|
33
|
+
const model = request.model === undefined ? undefined : normalizeModelId(request.model);
|
|
34
|
+
const defaults = model !== undefined && Object.hasOwn(DEFAULTS, model) ? DEFAULTS[model] : undefined;
|
|
35
|
+
let thinking = raw.thinking;
|
|
36
|
+
if (isRecord(thinking) && (thinking.type === "adaptive" || thinking.type === "enabled")
|
|
37
|
+
&& (thinking.display === undefined || (typeof thinking.display === "string"
|
|
38
|
+
&& ["summarized", "omitted", "updates"].includes(thinking.display)))) {
|
|
39
|
+
// Display controls returned thinking text, not mode or reasoning budget.
|
|
40
|
+
// Preserve unrecognized fields conservatively rather than erasing them.
|
|
41
|
+
thinking = Object.fromEntries(Object.entries(thinking).filter(([key]) => key !== "display"));
|
|
42
|
+
}
|
|
43
|
+
const config = raw.output_config;
|
|
44
|
+
const effort = isRecord(config) ? config.effort : undefined;
|
|
45
|
+
return {
|
|
46
|
+
thinking: canonicalJson(thinking !== undefined ? ["value", thinking]
|
|
47
|
+
: defaults ? ["value", { type: defaults.thinking }] : ["unrecorded"]),
|
|
48
|
+
effort: config !== undefined && !isRecord(config) ? canonicalJson(["unrecognized", config])
|
|
49
|
+
: canonicalJson(effort !== undefined ? ["value", effort]
|
|
50
|
+
: defaults?.effort ? ["value", defaults.effort] : ["unrecorded"]),
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
export function anthropicReasoningKey(request) {
|
|
54
|
+
const scope = anthropicReasoningScope(request);
|
|
55
|
+
return JSON.stringify([scope.thinking, scope.effort]);
|
|
56
|
+
}
|
|
57
|
+
//# sourceMappingURL=anthropic-reasoning.js.map
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import type { ParsedRequest, ResolvedModel } from "./types.js";
|
|
2
|
+
export declare function anthropicSpeed(request: ParsedRequest): "standard" | "fast" | "unrecognized";
|
|
3
|
+
export declare function anthropicSpeedKey(request: ParsedRequest): string;
|
|
4
|
+
export declare function anthropicSpeedMultiplier(request: ParsedRequest, pricedModel: ResolvedModel): number | undefined;
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { canonicalJson, isRecord } from "./json-utils.js";
|
|
2
|
+
import { normalizeModelId } from "./pricing.js";
|
|
3
|
+
// Claude API rules checked 2026-10-10. Request bodies cannot prove the server's
|
|
4
|
+
// actual speed or historical pricing; these are current documented scenarios.
|
|
5
|
+
// https://platform.claude.com/docs/en/build-with-claude/fast-mode
|
|
6
|
+
const FAST_MODELS = new Set(["claude-opus-5-5", "claude-opus-5", "claude-opus-4-8"]);
|
|
7
|
+
export function anthropicSpeed(request) {
|
|
8
|
+
const value = isRecord(request.raw) ? request.raw.speed : undefined;
|
|
9
|
+
if (value === undefined || value === "standard")
|
|
10
|
+
return "standard";
|
|
11
|
+
if (value !== "fast")
|
|
12
|
+
return "unrecognized";
|
|
13
|
+
// Opus 4.6 currently accepts fast requests but silently uses standard speed.
|
|
14
|
+
return request.model && normalizeModelId(request.model) === "claude-opus-4-6" ? "standard" : "fast";
|
|
15
|
+
}
|
|
16
|
+
export function anthropicSpeedKey(request) {
|
|
17
|
+
const speed = anthropicSpeed(request);
|
|
18
|
+
return speed === "unrecognized" ? canonicalJson(isRecord(request.raw) ? request.raw.speed : null) : speed;
|
|
19
|
+
}
|
|
20
|
+
export function anthropicSpeedMultiplier(request, pricedModel) {
|
|
21
|
+
const speed = anthropicSpeed(request);
|
|
22
|
+
if (speed === "standard")
|
|
23
|
+
return 1;
|
|
24
|
+
// Never borrow the fallback model's standard price for an unknown fast rate.
|
|
25
|
+
return speed === "fast" && !pricedModel.unrecognized && FAST_MODELS.has(pricedModel.id) ? 2 : undefined;
|
|
26
|
+
}
|
|
27
|
+
//# sourceMappingURL=anthropic-speed.js.map
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
import { ANTHROPIC_CACHE_WRITE_MULTIPLIER_1H, ANTHROPIC_CACHE_WRITE_MULTIPLIER_5M, ANTHROPIC_LOOKBACK_POSITIONS, findAnthropicModel, resolveModel } from "./pricing.js";
|
|
2
|
+
import { ModelScoped } from "./model-id.js";
|
|
3
|
+
import { anthropicPositions, lastCacheableSegment } from "./anthropic-breakpoints.js";
|
|
4
|
+
import { ContextScopeParseError } from "./parse-error.js";
|
|
5
|
+
import { anthropicMessageCacheKey, anthropicMessageCacheScope, isAnthropicMessageSegment } from "./anthropic-cache-scope.js";
|
|
6
|
+
import { anthropicSpeed, anthropicSpeedKey, anthropicSpeedMultiplier } from "./anthropic-speed.js";
|
|
7
|
+
import { isRecord } from "./json-utils.js";
|
|
8
|
+
import { anthropicReasoningKey } from "./anthropic-reasoning.js";
|
|
9
|
+
import { anthropicInjectedSettings } from "./anthropic-injected-settings.js";
|
|
10
|
+
import { hasUnmodeledTokens, unavailableCacheReason, unavailableCacheStep } from "./media-accounting.js";
|
|
11
|
+
function breakpointsOf(segments, cumulative) {
|
|
12
|
+
const out = [];
|
|
13
|
+
segments.forEach((segment, i) => {
|
|
14
|
+
if (segment.cacheControl) {
|
|
15
|
+
out.push({ segmentIndex: i, cumulativeTokens: cumulative[i], ttl: segment.cacheControl.ttl });
|
|
16
|
+
}
|
|
17
|
+
});
|
|
18
|
+
return out;
|
|
19
|
+
}
|
|
20
|
+
export function simulateAnthropicCacheSequence(requests, paths, model, forceOptimizedBreakpoint) {
|
|
21
|
+
const resolvedModels = requests.map((request) => resolveModel("anthropic", model, [request.model]));
|
|
22
|
+
const models = resolvedModels.map((resolved) => findAnthropicModel(resolved.id));
|
|
23
|
+
const showSpeed = requests.some((request) => isRecord(request.raw) && request.raw.speed !== undefined);
|
|
24
|
+
if (hasUnmodeledTokens(requests, "anthropic")) {
|
|
25
|
+
const reason = unavailableCacheReason(requests);
|
|
26
|
+
return requests.map((request, i) => {
|
|
27
|
+
if (request.segments.filter(s => s.cacheControl).length > 4)
|
|
28
|
+
throw new ContextScopeParseError(`Request ${request.index + 1}: cache simulation requires at most 4 breakpoints.`);
|
|
29
|
+
return { ...unavailableCacheStep(request.index, reason), ...(showSpeed ? {
|
|
30
|
+
speed: anthropicSpeed(request), inputPriceMultiplier: anthropicSpeedMultiplier(request, resolvedModels[i]),
|
|
31
|
+
} : {}) };
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
const steps = [];
|
|
35
|
+
// Speed changes preserve explicit tool entries but invalidate system and messages.
|
|
36
|
+
// Tool choice / image presence further partition only the message cache.
|
|
37
|
+
// Thinking/effort placement ahead of setup is model-specific. Keep a
|
|
38
|
+
// conservative all-level scope rather than inventing setup reuse; the
|
|
39
|
+
// corresponding finding explains that actual setup survival can differ.
|
|
40
|
+
const toolsBySettings = new Map();
|
|
41
|
+
const systemsWritten = new Map();
|
|
42
|
+
const messagesWritten = new Map();
|
|
43
|
+
requests.forEach((request, i) => {
|
|
44
|
+
const modelInfo = models[i];
|
|
45
|
+
const segments = request.segments;
|
|
46
|
+
const path = paths[i];
|
|
47
|
+
let total = 0;
|
|
48
|
+
// The sequence-wide availability check above excludes null counts.
|
|
49
|
+
const cumulative = segments.map((s) => (total += s.claudeTokensEstimate));
|
|
50
|
+
let breakpoints = breakpointsOf(segments, cumulative);
|
|
51
|
+
if (breakpoints.length > 4)
|
|
52
|
+
throw new ContextScopeParseError(`Request ${request.index + 1}: cache simulation requires at most 4 breakpoints.`);
|
|
53
|
+
// "Optimized" mode: put a trailing breakpoint on the last cacheable block (the
|
|
54
|
+
// "automatic caching on the growing tail" pattern the docs recommend), on top of whatever the
|
|
55
|
+
// request already has. This - not a breakpoint keyed off the previous request's boundary - is
|
|
56
|
+
// what actually composes across a sequence: the same position (this request's last segment)
|
|
57
|
+
// is also where the *next* request will look for a prior entry, so consecutive forced
|
|
58
|
+
// breakpoints line up and can read each other.
|
|
59
|
+
if (forceOptimizedBreakpoint) {
|
|
60
|
+
const lastIndex = lastCacheableSegment(segments);
|
|
61
|
+
if (lastIndex >= 0 && !breakpoints.some((b) => b.segmentIndex === lastIndex)) {
|
|
62
|
+
// With four occupied slots, move the last marker (preserving its TTL) instead
|
|
63
|
+
// of inventing a fifth one that the provider would reject.
|
|
64
|
+
const ttl = breakpoints.length === 4 ? breakpoints.pop().ttl : "5m";
|
|
65
|
+
const forced = { segmentIndex: lastIndex, cumulativeTokens: cumulative[lastIndex], ttl };
|
|
66
|
+
breakpoints = [...breakpoints, forced].sort((a, b) => a.segmentIndex - b.segmentIndex);
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
breakpoints = breakpoints.filter((bp) => bp.cumulativeTokens >= modelInfo.minCacheableTokens);
|
|
70
|
+
if (breakpoints.length === 0) {
|
|
71
|
+
// No marker reaches the minimum: nothing is read or written, even with a stable prefix.
|
|
72
|
+
steps.push({ requestIndex: request.index, readTokens: 0, writeTokens5m: 0, writeTokens1h: 0, uncachedTokens: total, costUsd: undefined });
|
|
73
|
+
return;
|
|
74
|
+
}
|
|
75
|
+
const positions = anthropicPositions(segments);
|
|
76
|
+
// Entries of another model are never visible: a cached prefix is that model's own state.
|
|
77
|
+
const speed = anthropicSpeedKey(request);
|
|
78
|
+
const injected = anthropicInjectedSettings(request);
|
|
79
|
+
// Output formats alter the injected prompt; grammar compilation caching
|
|
80
|
+
// is a different cache and cannot establish prompt reuse. A citation
|
|
81
|
+
// toggle preserves tools but invalidates system and message entries.
|
|
82
|
+
const toolScope = JSON.stringify([anthropicReasoningKey(request), injected.formatKey]);
|
|
83
|
+
const systemScope = JSON.stringify([toolScope, speed, injected.citations]);
|
|
84
|
+
const scope = JSON.stringify([systemScope, anthropicMessageCacheKey(anthropicMessageCacheScope(request))]);
|
|
85
|
+
let toolsWritten = toolsBySettings.get(toolScope);
|
|
86
|
+
if (!toolsWritten)
|
|
87
|
+
toolsBySettings.set(toolScope, toolsWritten = new ModelScoped());
|
|
88
|
+
let systemWritten = systemsWritten.get(systemScope);
|
|
89
|
+
if (!systemWritten)
|
|
90
|
+
systemsWritten.set(systemScope, systemWritten = new ModelScoped());
|
|
91
|
+
let messageWritten = messagesWritten.get(scope);
|
|
92
|
+
if (!messageWritten)
|
|
93
|
+
messagesWritten.set(scope, messageWritten = new ModelScoped());
|
|
94
|
+
const toolCached = toolsWritten.visibleTo(request.model);
|
|
95
|
+
const systemCached = systemWritten.visibleTo(request.model);
|
|
96
|
+
const messageCached = messageWritten.visibleTo(request.model);
|
|
97
|
+
let readTokens = 0;
|
|
98
|
+
for (const bp of breakpoints) {
|
|
99
|
+
// The longest cached prefix of this request that ends at or before the breakpoint - it can't
|
|
100
|
+
// "read ahead" of its own coverage - and no more than the lookback window behind it.
|
|
101
|
+
let readFromThis = 0;
|
|
102
|
+
// The breakpoint itself is position one: distance 20 is already out of range.
|
|
103
|
+
for (let at = bp.segmentIndex; at >= 0 && positions[bp.segmentIndex] - positions[at] < ANTHROPIC_LOOKBACK_POSITIONS; at--) {
|
|
104
|
+
const segment = segments[at];
|
|
105
|
+
const cached = isAnthropicMessageSegment(segment) ? messageCached : segment.path.startsWith("tools[") ? toolCached : systemCached;
|
|
106
|
+
if (cached.some((entries) => entries.has(path[at]))) {
|
|
107
|
+
readFromThis = cumulative[at];
|
|
108
|
+
break;
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
if (readFromThis > readTokens)
|
|
112
|
+
readTokens = readFromThis; // a later breakpoint's read supersedes an earlier smaller one
|
|
113
|
+
}
|
|
114
|
+
// Resolve every read before billing any write. A later breakpoint can find a
|
|
115
|
+
// hit covering an earlier miss. Anthropic's A/B/C partition bills that prefix
|
|
116
|
+
// once: [0,A) reads, [A,B) 1h writes, [B,C) 5m writes, [C,total) plain input.
|
|
117
|
+
const oneHourThrough = Math.max(readTokens, ...breakpoints.filter((bp) => bp.ttl === "1h").map((bp) => bp.cumulativeTokens));
|
|
118
|
+
const coveredTokens = breakpoints[breakpoints.length - 1].cumulativeTokens;
|
|
119
|
+
const write1h = oneHourThrough - readTokens;
|
|
120
|
+
const write5m = coveredTokens - oneHourThrough;
|
|
121
|
+
const uncachedTokens = total - coveredTokens;
|
|
122
|
+
steps.push({ requestIndex: request.index, readTokens, writeTokens5m: write5m, writeTokens1h: write1h, uncachedTokens, costUsd: undefined });
|
|
123
|
+
for (const bp of breakpoints) {
|
|
124
|
+
const segment = segments[bp.segmentIndex];
|
|
125
|
+
const mine = (isAnthropicMessageSegment(segment) ? messageWritten : segment.path.startsWith("tools[") ? toolsWritten : systemWritten).of(request.model);
|
|
126
|
+
mine.add(path[bp.segmentIndex]);
|
|
127
|
+
}
|
|
128
|
+
});
|
|
129
|
+
return steps.map((step, i) => {
|
|
130
|
+
const speed = anthropicSpeed(requests[i]);
|
|
131
|
+
const multiplier = anthropicSpeedMultiplier(requests[i], resolvedModels[i]);
|
|
132
|
+
return {
|
|
133
|
+
...step,
|
|
134
|
+
...(showSpeed ? { speed, inputPriceMultiplier: multiplier } : {}),
|
|
135
|
+
costUsd: multiplier === undefined ? undefined : anthropicStepCostUsd(step, models[i]) * multiplier,
|
|
136
|
+
};
|
|
137
|
+
});
|
|
138
|
+
}
|
|
139
|
+
function anthropicStepCostUsd(step, modelInfo) {
|
|
140
|
+
const perTok = modelInfo.inputPricePerMTok / 1_000_000;
|
|
141
|
+
return (step.uncachedTokens * perTok +
|
|
142
|
+
step.writeTokens5m * perTok * ANTHROPIC_CACHE_WRITE_MULTIPLIER_5M +
|
|
143
|
+
step.writeTokens1h * perTok * ANTHROPIC_CACHE_WRITE_MULTIPLIER_1H +
|
|
144
|
+
step.readTokens * perTok * modelInfo.cacheReadMultiplier);
|
|
145
|
+
}
|
|
146
|
+
//# sourceMappingURL=cache-anthropic.js.map
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import { findOpenAiModel, resolveModel } from "./pricing.js";
|
|
2
|
+
import { openAiCachePlan, openAiCacheScope } from "./openai-breakpoints.js";
|
|
3
|
+
import { ContextScopeParseError } from "./parse-error.js";
|
|
4
|
+
import { hasUnmodeledTokens, unavailableCacheReason, unavailableCacheStep } from "./media-accounting.js";
|
|
5
|
+
/**
|
|
6
|
+
* Modern OpenAI: exact modeled boundaries, explicit/implicit mode, four writes and 30m
|
|
7
|
+
* write pricing. Legacy: the existing optimistic 1024/128-token approximation; hidden
|
|
8
|
+
* intervals and renderer tokens remain unavailable. No wall-clock eviction is modeled.
|
|
9
|
+
* Rules checked 2026-10-09: https://developers.openai.com/api/docs/guides/prompt-caching
|
|
10
|
+
*/
|
|
11
|
+
const MIN_CACHEABLE_TOKENS = 1024;
|
|
12
|
+
const CACHE_GRANULARITY = 128;
|
|
13
|
+
export function simulateOpenAiCacheSequence(requests, paths, model) {
|
|
14
|
+
const unavailable = hasUnmodeledTokens(requests, "openai");
|
|
15
|
+
const reason = unavailable ? unavailableCacheReason(requests) : undefined;
|
|
16
|
+
const cached = new Map();
|
|
17
|
+
return requests.map((request, i) => {
|
|
18
|
+
const modelInfo = findOpenAiModel(resolveModel("openai", model, [request.model]).id);
|
|
19
|
+
const plan = openAiCachePlan(request);
|
|
20
|
+
const modern = modelInfo.cacheStyle === "breakpoints";
|
|
21
|
+
if (!modern && (plan.explicit.length || plan.mode === "explicit")) {
|
|
22
|
+
throw new ContextScopeParseError(`Request ${request.index + 1}: explicit OpenAI caching requires a model with breakpoint caching; ${modelInfo.displayName} uses legacy caching.`);
|
|
23
|
+
}
|
|
24
|
+
if (unavailable)
|
|
25
|
+
return { ...unavailableCacheStep(request.index, reason),
|
|
26
|
+
...(modern ? { writeTokens30m: null } : {}), cacheMode: modern ? plan.mode : "legacy" };
|
|
27
|
+
const path = paths[i];
|
|
28
|
+
let total = 0;
|
|
29
|
+
const cumulative = request.segments.map((s) => (total += s.openaiTokens));
|
|
30
|
+
const scope = openAiCacheScope(request);
|
|
31
|
+
let entries = cached.get(scope);
|
|
32
|
+
if (!entries) {
|
|
33
|
+
entries = new Set();
|
|
34
|
+
cached.set(scope, entries);
|
|
35
|
+
}
|
|
36
|
+
let readTokens = 0;
|
|
37
|
+
let writeTokens = 0;
|
|
38
|
+
if (modern) {
|
|
39
|
+
for (const index of plan.lookup) {
|
|
40
|
+
if (cumulative[index] >= MIN_CACHEABLE_TOKENS && entries.has(path[index]))
|
|
41
|
+
readTokens = Math.max(readTokens, cumulative[index]);
|
|
42
|
+
}
|
|
43
|
+
const writes = plan.write.filter((index) => cumulative[index] >= MIN_CACHEABLE_TOKENS);
|
|
44
|
+
const covered = Math.max(readTokens, ...writes.map((index) => cumulative[index]), 0);
|
|
45
|
+
writeTokens = covered - readTokens;
|
|
46
|
+
// Reads are resolved before any writes so one request cannot read its own entries.
|
|
47
|
+
for (const index of writes)
|
|
48
|
+
entries.add(path[index]);
|
|
49
|
+
}
|
|
50
|
+
else {
|
|
51
|
+
let matched = 0;
|
|
52
|
+
let high = path.length;
|
|
53
|
+
while (matched < high) {
|
|
54
|
+
const mid = (matched + high + 1) >> 1;
|
|
55
|
+
if (entries.has(path[mid - 1]))
|
|
56
|
+
matched = mid;
|
|
57
|
+
else
|
|
58
|
+
high = mid - 1;
|
|
59
|
+
}
|
|
60
|
+
const shared = matched ? cumulative[matched - 1] : 0;
|
|
61
|
+
readTokens = shared >= MIN_CACHEABLE_TOKENS ? Math.floor(shared / CACHE_GRANULARITY) * CACHE_GRANULARITY : 0;
|
|
62
|
+
for (const node of path)
|
|
63
|
+
entries.add(node);
|
|
64
|
+
}
|
|
65
|
+
const uncachedTokens = total - readTokens - writeTokens;
|
|
66
|
+
const priceMultiplier = modelInfo.longContextInput && total > modelInfo.longContextInput.aboveTokens ? modelInfo.longContextInput.multiplier : 1;
|
|
67
|
+
const costUsd = priceMultiplier * ((uncachedTokens + writeTokens * 1.25) * modelInfo.inputPricePerMTok + readTokens * modelInfo.cachedInputPricePerMTok) / 1_000_000;
|
|
68
|
+
return { requestIndex: request.index, readTokens, writeTokens5m: 0, writeTokens1h: 0,
|
|
69
|
+
...(modern ? { writeTokens30m: writeTokens } : {}), cacheMode: modern ? plan.mode : "legacy", uncachedTokens, costUsd };
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
//# sourceMappingURL=cache-openai.js.map
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Optional calibration against Anthropic's token-counting endpoint.
|
|
3
|
+
*
|
|
4
|
+
* Claude token counts elsewhere in contextscope are heuristic estimates.
|
|
5
|
+
* `POST /v1/messages/count_tokens` returns the real, model-specific input
|
|
6
|
+
* token count for a whole request body - tools, system prompt, messages and
|
|
7
|
+
* the framing around them - and the endpoint is free to call. One call on one
|
|
8
|
+
* request gives the ratio of real to estimated tokens for this workload;
|
|
9
|
+
* passing that ratio as `claudeTokenScale` rescales every estimate in the
|
|
10
|
+
* analysis, so the cost figures rest on a measured count instead of the
|
|
11
|
+
* heuristic alone. It is still a scale factor: segments whose text is denser
|
|
12
|
+
* or sparser than the calibrated request's average keep some error.
|
|
13
|
+
*
|
|
14
|
+
* In a browser the call is made directly from the page with
|
|
15
|
+
* `anthropic-dangerous-direct-browser-access: true`, Anthropic's documented
|
|
16
|
+
* opt-in for CORS. The key is held by the caller in memory only.
|
|
17
|
+
*/
|
|
18
|
+
import type { ParsedRequest } from "./types.js";
|
|
19
|
+
export interface CalibrationResult {
|
|
20
|
+
requestIndex: number;
|
|
21
|
+
model: string;
|
|
22
|
+
/** Input tokens reported by count_tokens for the whole request. */
|
|
23
|
+
exactTokens: number;
|
|
24
|
+
/** The heuristic estimate for the same request (sum of its segments' unscaled estimates). */
|
|
25
|
+
estimatedTokens: number;
|
|
26
|
+
/** exactTokens / estimatedTokens - pass as AnalysisOptions.claudeTokenScale. */
|
|
27
|
+
scale: number;
|
|
28
|
+
}
|
|
29
|
+
export declare class CalibrationError extends Error {
|
|
30
|
+
}
|
|
31
|
+
export interface CountTokensOptions {
|
|
32
|
+
/** Injected for tests; defaults to the global fetch. */
|
|
33
|
+
fetchImpl?: typeof fetch;
|
|
34
|
+
/** Send the browser CORS opt-in header. Defaults to true when running in a page. */
|
|
35
|
+
browser?: boolean;
|
|
36
|
+
}
|
|
37
|
+
/** The count_tokens request body for one parsed request, priced as `model`. */
|
|
38
|
+
export declare function countTokensBody(request: ParsedRequest, model: string): Record<string, unknown>;
|
|
39
|
+
export declare function calibrationScale(exactTokens: number, estimatedTokens: number): number;
|
|
40
|
+
/** Calibrate locally against a measured count supplied by the caller. No request is sent. */
|
|
41
|
+
export declare function calibrateRequest(request: ParsedRequest, model: string, exactTokens: number): CalibrationResult;
|
|
42
|
+
/** Counts one request exactly and returns the scale that maps the heuristic onto it. */
|
|
43
|
+
export declare function countRequestTokens(apiKey: string, model: string, request: ParsedRequest, options?: CountTokensOptions): Promise<CalibrationResult>;
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import { anthropicInjectedSettings } from "./anthropic-injected-settings.js";
|
|
2
|
+
import { isRecord } from "./json-utils.js";
|
|
3
|
+
import { hasUnmodeledTokens } from "./media-accounting.js";
|
|
4
|
+
const COUNT_TOKENS_URL = "https://api.anthropic.com/v1/messages/count_tokens";
|
|
5
|
+
const ANTHROPIC_VERSION = "2023-06-01";
|
|
6
|
+
// Supported prompt fields, including controls for provider-injected instructions.
|
|
7
|
+
// Generation limits, stream mode and sampling parameters do not belong in this
|
|
8
|
+
// endpoint's body. This is not a complete validator for every API feature.
|
|
9
|
+
const PROMPT_FIELDS = ["system", "tools", "messages", "tool_choice", "thinking", "output_config", "speed", "cache_control"];
|
|
10
|
+
export class CalibrationError extends Error {
|
|
11
|
+
}
|
|
12
|
+
/** The count_tokens request body for one parsed request, priced as `model`. */
|
|
13
|
+
export function countTokensBody(request, model) {
|
|
14
|
+
if (request.segments.some(s => s.unmodeledContext === "mcp_tools")) {
|
|
15
|
+
throw new CalibrationError("Cannot construct a count_tokens request for unmodeled MCP tool context. Omitting the server configuration would count a different prompt.");
|
|
16
|
+
}
|
|
17
|
+
const raw = request.raw !== null && typeof request.raw === "object" ? request.raw : {};
|
|
18
|
+
const body = { model };
|
|
19
|
+
for (const field of PROMPT_FIELDS)
|
|
20
|
+
if (raw[field] !== undefined)
|
|
21
|
+
body[field] = raw[field];
|
|
22
|
+
// The current counting endpoint accepts output_config.format. Preserve a
|
|
23
|
+
// legacy request's same format rather than silently counting a plain reply.
|
|
24
|
+
if (raw.output_format != null) {
|
|
25
|
+
const { format } = anthropicInjectedSettings(request);
|
|
26
|
+
body.output_config = { ...(isRecord(raw.output_config) ? raw.output_config : {}), format };
|
|
27
|
+
}
|
|
28
|
+
if (!Array.isArray(body["messages"]) || body["messages"].length === 0) {
|
|
29
|
+
throw new CalibrationError(`Request ${request.index + 1} has no messages, so there is nothing to count.`);
|
|
30
|
+
}
|
|
31
|
+
return body;
|
|
32
|
+
}
|
|
33
|
+
export function calibrationScale(exactTokens, estimatedTokens) {
|
|
34
|
+
if (!Number.isSafeInteger(exactTokens) || exactTokens <= 0)
|
|
35
|
+
throw new CalibrationError("Enter a positive whole-number token count within the safe integer range.");
|
|
36
|
+
if (!Number.isSafeInteger(estimatedTokens) || estimatedTokens <= 0)
|
|
37
|
+
throw new CalibrationError("Cannot calibrate against an empty or invalid request estimate.");
|
|
38
|
+
return exactTokens / estimatedTokens;
|
|
39
|
+
}
|
|
40
|
+
/** Calibrate locally against a measured count supplied by the caller. No request is sent. */
|
|
41
|
+
export function calibrateRequest(request, model, exactTokens) {
|
|
42
|
+
if (request.provider !== "anthropic")
|
|
43
|
+
throw new CalibrationError("Calibration only applies to Anthropic requests.");
|
|
44
|
+
requireCountableRequest(request);
|
|
45
|
+
const estimatedTokens = request.segments.reduce((sum, s) => sum + s.claudeTokensEstimate, 0);
|
|
46
|
+
return { requestIndex: request.index, model, exactTokens, estimatedTokens, scale: calibrationScale(exactTokens, estimatedTokens) };
|
|
47
|
+
}
|
|
48
|
+
/** Counts one request exactly and returns the scale that maps the heuristic onto it. */
|
|
49
|
+
export async function countRequestTokens(apiKey, model, request, options = {}) {
|
|
50
|
+
if (request.provider !== "anthropic")
|
|
51
|
+
throw new CalibrationError("Calibration uses Anthropic's count_tokens endpoint, so it only applies to Anthropic requests.");
|
|
52
|
+
requireCountableRequest(request);
|
|
53
|
+
if (apiKey.trim() === "")
|
|
54
|
+
throw new CalibrationError("An Anthropic API key is required.");
|
|
55
|
+
const body = countTokensBody(request, model);
|
|
56
|
+
const fetchImpl = options.fetchImpl ?? fetch;
|
|
57
|
+
const browser = options.browser ?? typeof window !== "undefined";
|
|
58
|
+
const headers = {
|
|
59
|
+
"content-type": "application/json",
|
|
60
|
+
"x-api-key": apiKey.trim(),
|
|
61
|
+
"anthropic-version": ANTHROPIC_VERSION,
|
|
62
|
+
};
|
|
63
|
+
if (browser)
|
|
64
|
+
headers["anthropic-dangerous-direct-browser-access"] = "true";
|
|
65
|
+
let response;
|
|
66
|
+
try {
|
|
67
|
+
response = await fetchImpl(COUNT_TOKENS_URL, { method: "POST", headers, body: JSON.stringify(body) });
|
|
68
|
+
}
|
|
69
|
+
catch (err) {
|
|
70
|
+
throw new CalibrationError(`Could not reach api.anthropic.com: ${err.message}`);
|
|
71
|
+
}
|
|
72
|
+
if (!response.ok) {
|
|
73
|
+
const text = await response.text().catch(() => "");
|
|
74
|
+
throw new CalibrationError(`count_tokens failed (HTTP ${response.status}): ${errorMessage(text)}`);
|
|
75
|
+
}
|
|
76
|
+
const data = await response.json();
|
|
77
|
+
if (data === null || typeof data !== "object" || !("input_tokens" in data) || typeof data.input_tokens !== "number") {
|
|
78
|
+
throw new CalibrationError("count_tokens returned no input_tokens field.");
|
|
79
|
+
}
|
|
80
|
+
return calibrateRequest(request, model, data.input_tokens);
|
|
81
|
+
}
|
|
82
|
+
function requireCountableRequest(request) {
|
|
83
|
+
if (hasUnmodeledTokens([request], "anthropic"))
|
|
84
|
+
throw new CalibrationError("Cannot apply a scalar calibration to unmodeled media or tool context. A whole-request count cannot recover missing segments or their cache boundaries. Keep the measured count as reported usage instead.");
|
|
85
|
+
}
|
|
86
|
+
function errorMessage(body) {
|
|
87
|
+
try {
|
|
88
|
+
const parsed = JSON.parse(body);
|
|
89
|
+
if (typeof parsed.error?.message === "string")
|
|
90
|
+
return parsed.error.message;
|
|
91
|
+
}
|
|
92
|
+
catch {
|
|
93
|
+
// not JSON - fall through to the raw text
|
|
94
|
+
}
|
|
95
|
+
return body.slice(0, 200) || "(empty response)";
|
|
96
|
+
}
|
|
97
|
+
//# sourceMappingURL=calibrate.js.map
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A log's text, as Windows tools save it too. A proxy or an SDK hook writes UTF-8, but
|
|
3
|
+
* `... > requests.jsonl` in Windows PowerShell saves UTF-16 with a byte-order mark, which
|
|
4
|
+
* read as UTF-8 holds no JSON at all ("No valid JSON objects found"). The mark decides the
|
|
5
|
+
* encoding and is dropped; a mark in front of UTF-8 is dropped too.
|
|
6
|
+
*
|
|
7
|
+
* Kept free of imports: the web app loads it before the (large) rest of the core.
|
|
8
|
+
*/
|
|
9
|
+
export declare function decodeText(bytes: Uint8Array): string;
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A log's text, as Windows tools save it too. A proxy or an SDK hook writes UTF-8, but
|
|
3
|
+
* `... > requests.jsonl` in Windows PowerShell saves UTF-16 with a byte-order mark, which
|
|
4
|
+
* read as UTF-8 holds no JSON at all ("No valid JSON objects found"). The mark decides the
|
|
5
|
+
* encoding and is dropped; a mark in front of UTF-8 is dropped too.
|
|
6
|
+
*
|
|
7
|
+
* Kept free of imports: the web app loads it before the (large) rest of the core.
|
|
8
|
+
*/
|
|
9
|
+
export function decodeText(bytes) {
|
|
10
|
+
const utf16 = bytes[0] === 0xff && bytes[1] === 0xfe ? "utf-16le" : bytes[0] === 0xfe && bytes[1] === 0xff ? "utf-16be" : null;
|
|
11
|
+
const encoding = utf16 ?? "utf-8";
|
|
12
|
+
try {
|
|
13
|
+
// Replacement decoding would turn two different corrupt captures into the same
|
|
14
|
+
// prompt, then incorrectly report complete coverage and matching cache prefixes.
|
|
15
|
+
return new TextDecoder(encoding, { fatal: true }).decode(bytes);
|
|
16
|
+
}
|
|
17
|
+
catch {
|
|
18
|
+
throw new Error(`Invalid ${encoding.toUpperCase()} encoding. Export or save the original log as valid UTF-8 (or UTF-16 with a byte-order mark) and import it again.`);
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
//# sourceMappingURL=decode-text.js.map
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { Provider } from "./types.js";
|
|
2
|
+
/**
|
|
3
|
+
* Auto-detects whether a single request object is Anthropic Messages API or
|
|
4
|
+
* OpenAI Chat Completions shaped. Scores a handful of shape-specific
|
|
5
|
+
* signals rather than requiring one exact marker, since real requests often
|
|
6
|
+
* carry only a subset (e.g. no tools, no system prompt).
|
|
7
|
+
*/
|
|
8
|
+
export declare function detectFormat(request: unknown): Provider;
|
|
9
|
+
/** Strong provider evidence only: a bare user message works in either format. */
|
|
10
|
+
export declare function detectProvider(request: unknown): Provider | undefined;
|