@anthonymercer/contextscope 0.0.0-stage → 0.4.1
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,99 @@
|
|
|
1
|
+
import { stripVolatilePatterns } from "./volatile.js";
|
|
2
|
+
/** Small deterministic-serialization helpers shared by the parsers and findings. */
|
|
3
|
+
/** JSON.stringify with recursively sorted object keys, so semantically identical objects with
|
|
4
|
+
* different key order serialize identically. Used by the optimized cache scenario ("what if the
|
|
5
|
+
* schema were serialized deterministically") and by the key-order finding. */
|
|
6
|
+
export function canonicalJson(value) {
|
|
7
|
+
return JSON.stringify(sortKeysDeep(value)) ?? "null";
|
|
8
|
+
}
|
|
9
|
+
/** A JSON object: not null, not an array. Request logs are untrusted input, so the parsers
|
|
10
|
+
* check before reading a field rather than assume the documented shape. */
|
|
11
|
+
export function isRecord(value) {
|
|
12
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
13
|
+
}
|
|
14
|
+
/** The text of a segment: the string itself, or the JSON of whatever sits where a string
|
|
15
|
+
* should be, so a malformed block is still counted and compared instead of crashing the parse. */
|
|
16
|
+
export function asText(value) {
|
|
17
|
+
return typeof value === "string" ? value : blockJson(value);
|
|
18
|
+
}
|
|
19
|
+
function withoutCacheMetadata(value) {
|
|
20
|
+
if (value === null || typeof value !== "object" || Array.isArray(value) || (!("cache_control" in value) && !("prompt_cache_breakpoint" in value)))
|
|
21
|
+
return value;
|
|
22
|
+
const rest = { ...value };
|
|
23
|
+
delete rest["cache_control"];
|
|
24
|
+
delete rest["prompt_cache_breakpoint"];
|
|
25
|
+
return rest;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* A content block or tool definition as the API receives it - key order preserved, because the
|
|
29
|
+
* prompt is rendered in that order and a reordered key breaks the cached prefix - minus its
|
|
30
|
+
* `cache_control` or `prompt_cache_breakpoint` marker. A rolling breakpoint moves every turn; the marker isn't part of the
|
|
31
|
+
* cached content, so it must not make two otherwise identical blocks differ.
|
|
32
|
+
*/
|
|
33
|
+
export function blockJson(value) {
|
|
34
|
+
// JSON.stringify(undefined) is undefined, not a string.
|
|
35
|
+
return JSON.stringify(withoutCacheMetadata(value)) ?? "null";
|
|
36
|
+
}
|
|
37
|
+
/** blockJson with sorted keys: the same block if it were serialized deterministically. */
|
|
38
|
+
export function canonicalBlockJson(value) {
|
|
39
|
+
return canonicalJson(withoutCacheMetadata(value));
|
|
40
|
+
}
|
|
41
|
+
// Routing, speaker/type identity and signed thinking data are prompt structure.
|
|
42
|
+
// A UUID-looking destination is not a timestamp that can be parameterized away.
|
|
43
|
+
const STRUCTURAL_FIELDS = new Set(["id", "tool_use_id", "tool_call_id", "call_id", "signature", "name", "role", "type"]);
|
|
44
|
+
function normalizeStrings(value) {
|
|
45
|
+
if (typeof value === "string")
|
|
46
|
+
return stripVolatilePatterns(value);
|
|
47
|
+
if (Array.isArray(value))
|
|
48
|
+
return value.map(normalizeStrings);
|
|
49
|
+
if (isRecord(value)) {
|
|
50
|
+
// Thinking is signed/opaque provider evidence, not freely editable prompt text.
|
|
51
|
+
if (value["type"] === "thinking" || value["type"] === "redacted_thinking")
|
|
52
|
+
return value;
|
|
53
|
+
return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, STRUCTURAL_FIELDS.has(key) ? item : normalizeStrings(item)]));
|
|
54
|
+
}
|
|
55
|
+
return value;
|
|
56
|
+
}
|
|
57
|
+
/** Optimized content: sorted keys and volatile text, with routing identities preserved. */
|
|
58
|
+
export function normalizedBlockJson(value) {
|
|
59
|
+
return canonicalJson(normalizeStrings(withoutCacheMetadata(value)));
|
|
60
|
+
}
|
|
61
|
+
function sortKeysDeep(value) {
|
|
62
|
+
if (Array.isArray(value))
|
|
63
|
+
return value.map(sortKeysDeep);
|
|
64
|
+
if (value !== null && typeof value === "object") {
|
|
65
|
+
const entries = Object.entries(value).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
|
|
66
|
+
// A JSON field named __proto__ is ordinary content, not a prototype setter.
|
|
67
|
+
const out = Object.create(null);
|
|
68
|
+
for (const [k, v] of entries)
|
|
69
|
+
out[k] = sortKeysDeep(v);
|
|
70
|
+
return out;
|
|
71
|
+
}
|
|
72
|
+
return value;
|
|
73
|
+
}
|
|
74
|
+
/** Recursively lists object keys in their ORIGINAL (insertion) order, depth-first, as
|
|
75
|
+
* "path.key" strings - used to detect "tool schema key order differs" between requests. */
|
|
76
|
+
export function keyOrderFingerprint(value, prefix = "") {
|
|
77
|
+
const out = [];
|
|
78
|
+
if (Array.isArray(value)) {
|
|
79
|
+
value.forEach((item, i) => out.push(...keyOrderFingerprint(item, `${prefix}[${i}]`)));
|
|
80
|
+
}
|
|
81
|
+
else if (value !== null && typeof value === "object") {
|
|
82
|
+
for (const key of Object.keys(value)) {
|
|
83
|
+
out.push(`${prefix}.${key}`);
|
|
84
|
+
out.push(...keyOrderFingerprint(value[key], `${prefix}.${key}`));
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
return out;
|
|
88
|
+
}
|
|
89
|
+
/** A short, stable debugging signature (FNV-1a, 32-bit, hex).
|
|
90
|
+
* Collisions are possible; never use it to establish content identity. */
|
|
91
|
+
export function fnv1a(text) {
|
|
92
|
+
let hash = 0x811c9dc5;
|
|
93
|
+
for (let i = 0; i < text.length; i++) {
|
|
94
|
+
hash ^= text.charCodeAt(i);
|
|
95
|
+
hash = Math.imul(hash, 0x01000193);
|
|
96
|
+
}
|
|
97
|
+
return (hash >>> 0).toString(16).padStart(8, "0");
|
|
98
|
+
}
|
|
99
|
+
//# sourceMappingURL=json-utils.js.map
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { CacheSimStep, MediaKind, ParsedRequest, Provider, TokenCount } from "./types.js";
|
|
2
|
+
/** Follow content grammar, never arbitrary JSON in tool arguments or quoted text.
|
|
3
|
+
* Encoded bytes, URLs and file IDs are transport representations, not model tokens.
|
|
4
|
+
* No remote content is fetched, and no media decoder or provider renderer is assumed.
|
|
5
|
+
*/
|
|
6
|
+
export declare function unmodeledMedia(block: unknown, provider: Provider): MediaKind[];
|
|
7
|
+
export declare function sumTokenCounts(values: Iterable<TokenCount>): TokenCount;
|
|
8
|
+
export declare function hasUnmodeledTokens(requests: ParsedRequest[], provider: Provider): boolean;
|
|
9
|
+
export declare const UNMODELED_CACHE_REASON = "Media token counts are unavailable. Cache token partitions and costs are unavailable for this sequence because unknown media lengths can affect cache thresholds and entries written by earlier requests.";
|
|
10
|
+
export declare function unavailableCacheReason(requests: ParsedRequest[]): string;
|
|
11
|
+
export declare function unavailableCacheStep(requestIndex: number, reason?: string): CacheSimStep;
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import { isRecord } from "./json-utils.js";
|
|
2
|
+
/** Follow content grammar, never arbitrary JSON in tool arguments or quoted text.
|
|
3
|
+
* Encoded bytes, URLs and file IDs are transport representations, not model tokens.
|
|
4
|
+
* No remote content is fetched, and no media decoder or provider renderer is assumed.
|
|
5
|
+
*/
|
|
6
|
+
export function unmodeledMedia(block, provider) {
|
|
7
|
+
const kinds = new Set();
|
|
8
|
+
function visit(value) {
|
|
9
|
+
if (!isRecord(value))
|
|
10
|
+
return;
|
|
11
|
+
const type = value.type;
|
|
12
|
+
if (provider === "anthropic") {
|
|
13
|
+
if (type === "image")
|
|
14
|
+
kinds.add("image");
|
|
15
|
+
else if (type === "document") {
|
|
16
|
+
const source = value.source;
|
|
17
|
+
if (isRecord(source) && source.type === "text" && typeof source.data === "string")
|
|
18
|
+
return;
|
|
19
|
+
if (isRecord(source) && source.type === "content" && (typeof source.content === "string" || Array.isArray(source.content))) {
|
|
20
|
+
if (Array.isArray(source.content))
|
|
21
|
+
source.content.forEach(visit);
|
|
22
|
+
}
|
|
23
|
+
else
|
|
24
|
+
kinds.add("document");
|
|
25
|
+
}
|
|
26
|
+
else if (type === "tool_result" || (typeof type === "string" && type.endsWith("_tool_result"))) {
|
|
27
|
+
if (Array.isArray(value.content))
|
|
28
|
+
value.content.forEach(visit);
|
|
29
|
+
else if (type === "web_fetch_tool_result" && isRecord(value.content) && value.content.type === "web_fetch_result")
|
|
30
|
+
visit(value.content.content);
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
else {
|
|
34
|
+
if (type === "image_url" || type === "input_image" || type === "computer_screenshot")
|
|
35
|
+
kinds.add("image");
|
|
36
|
+
else if (type === "file" || type === "input_file")
|
|
37
|
+
kinds.add("file");
|
|
38
|
+
else if (type === "input_audio")
|
|
39
|
+
kinds.add("audio");
|
|
40
|
+
else if (type === "function_call_output" && Array.isArray(value.output))
|
|
41
|
+
value.output.forEach(visit);
|
|
42
|
+
else if (type === "computer_call_output")
|
|
43
|
+
kinds.add("image");
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
visit(block);
|
|
47
|
+
return [...kinds].sort();
|
|
48
|
+
}
|
|
49
|
+
export function sumTokenCounts(values) {
|
|
50
|
+
let total = 0;
|
|
51
|
+
for (const value of values) {
|
|
52
|
+
if (value === null)
|
|
53
|
+
return null;
|
|
54
|
+
total += value;
|
|
55
|
+
}
|
|
56
|
+
return total;
|
|
57
|
+
}
|
|
58
|
+
export function hasUnmodeledTokens(requests, provider) {
|
|
59
|
+
return requests.some(request => request.segments.some(segment => (provider === "openai" ? segment.openaiTokens : segment.claudeTokensEstimate) === null));
|
|
60
|
+
}
|
|
61
|
+
export const UNMODELED_CACHE_REASON = "Media token counts are unavailable. Cache token partitions and costs are unavailable for this sequence because unknown media lengths can affect cache thresholds and entries written by earlier requests.";
|
|
62
|
+
export function unavailableCacheReason(requests) {
|
|
63
|
+
if (requests.some(r => r.segments.some(s => s.unmodeledContext === "mcp_tools"))) {
|
|
64
|
+
return "MCP tool context is not modeled. Resolved tool definitions and their provider-side rendering cannot be established by this estimator. Whole-request cache token partitions and costs are unavailable for this sequence; visible text matches do not establish the resolved prompt or prior cache entries.";
|
|
65
|
+
}
|
|
66
|
+
const context = requests.some(r => r.segments.some(s => s.unmodeledContext));
|
|
67
|
+
const media = requests.some(r => r.segments.some(s => s.unmodeledContent));
|
|
68
|
+
if (context)
|
|
69
|
+
return `${media ? "Media and stored or opaque context" : "Stored or opaque context"} cannot be reconstructed from these records. Whole-request cache token partitions and costs are unavailable for this sequence; visible text matches do not establish the resolved prompt or prior cache entries.`;
|
|
70
|
+
return UNMODELED_CACHE_REASON;
|
|
71
|
+
}
|
|
72
|
+
export function unavailableCacheStep(requestIndex, reason = UNMODELED_CACHE_REASON) {
|
|
73
|
+
return { requestIndex, readTokens: null, writeTokens5m: null, writeTokens1h: null,
|
|
74
|
+
uncachedTokens: null, costUsd: undefined, unavailableReason: reason };
|
|
75
|
+
}
|
|
76
|
+
//# sourceMappingURL=media-accounting.js.map
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/** Two requests hit the same prompt cache only if they run on the same model: a cached prefix is
|
|
2
|
+
* the model's own attention state, so it can't carry over to a different model. Requests with
|
|
3
|
+
* no model named form a separate assumed-model group; missing is not a wildcard. */
|
|
4
|
+
export declare function sameModel(a: string | undefined, b: string | undefined): boolean;
|
|
5
|
+
/**
|
|
6
|
+
* Sets of cached prefixes, one per model. What a request can read is what its own model cached,
|
|
7
|
+
* with missing model names isolated from all named models. This matches `sameModel`.
|
|
8
|
+
*/
|
|
9
|
+
export declare class ModelScoped {
|
|
10
|
+
private readonly byModel;
|
|
11
|
+
private static key;
|
|
12
|
+
/** The set this model writes to. */
|
|
13
|
+
of(model: string | undefined): Set<number>;
|
|
14
|
+
/** Every set a request on this model can read from. */
|
|
15
|
+
visibleTo(model: string | undefined): Set<number>[];
|
|
16
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { normalizeModelId } from "./pricing.js";
|
|
2
|
+
/** Two requests hit the same prompt cache only if they run on the same model: a cached prefix is
|
|
3
|
+
* the model's own attention state, so it can't carry over to a different model. Requests with
|
|
4
|
+
* no model named form a separate assumed-model group; missing is not a wildcard. */
|
|
5
|
+
export function sameModel(a, b) {
|
|
6
|
+
if (a === undefined || b === undefined)
|
|
7
|
+
return a === b;
|
|
8
|
+
return normalizeModelId(a) === normalizeModelId(b);
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* Sets of cached prefixes, one per model. What a request can read is what its own model cached,
|
|
12
|
+
* with missing model names isolated from all named models. This matches `sameModel`.
|
|
13
|
+
*/
|
|
14
|
+
export class ModelScoped {
|
|
15
|
+
byModel = new Map();
|
|
16
|
+
static key(model) {
|
|
17
|
+
return model === undefined ? "" : normalizeModelId(model);
|
|
18
|
+
}
|
|
19
|
+
/** The set this model writes to. */
|
|
20
|
+
of(model) {
|
|
21
|
+
const key = ModelScoped.key(model);
|
|
22
|
+
let set = this.byModel.get(key);
|
|
23
|
+
if (set === undefined) {
|
|
24
|
+
set = new Set();
|
|
25
|
+
this.byModel.set(key, set);
|
|
26
|
+
}
|
|
27
|
+
return set;
|
|
28
|
+
}
|
|
29
|
+
/** Every set a request on this model can read from. */
|
|
30
|
+
visibleTo(model) {
|
|
31
|
+
const mine = ModelScoped.key(model);
|
|
32
|
+
const entries = this.byModel.get(mine);
|
|
33
|
+
return entries ? [entries] : [];
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
//# sourceMappingURL=model-id.js.map
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { AnalysisResult, ResolvedModel } from "./types.js";
|
|
2
|
+
/** Group the actual assumptions used by each request, including unknown-model fallbacks. */
|
|
3
|
+
export declare function modelGroups(result: AnalysisResult): {
|
|
4
|
+
model: ResolvedModel;
|
|
5
|
+
requestIndices: number[];
|
|
6
|
+
}[];
|
|
7
|
+
export declare function modelLabel(model: ResolvedModel): string;
|
|
8
|
+
export declare function modelSummary(result: AnalysisResult): string;
|
|
9
|
+
/** Plain text only: renderers must apply their own escaping. */
|
|
10
|
+
export declare function modelNotes(result: AnalysisResult): string[];
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { describeRequestIndices } from "./group-findings.js";
|
|
2
|
+
/** Group the actual assumptions used by each request, including unknown-model fallbacks. */
|
|
3
|
+
export function modelGroups(result) {
|
|
4
|
+
const groups = new Map();
|
|
5
|
+
for (const report of result.reports) {
|
|
6
|
+
const model = report.model;
|
|
7
|
+
const key = JSON.stringify([model.id, model.source, model.unrecognized]);
|
|
8
|
+
const group = groups.get(key);
|
|
9
|
+
if (group)
|
|
10
|
+
group.requestIndices.push(report.requestIndex);
|
|
11
|
+
else
|
|
12
|
+
groups.set(key, { model, requestIndices: [report.requestIndex] });
|
|
13
|
+
}
|
|
14
|
+
return [...groups.values()];
|
|
15
|
+
}
|
|
16
|
+
export function modelLabel(model) {
|
|
17
|
+
return `${model.displayName}${model.unrecognized ? ` (fallback for ${model.unrecognized})` : model.source === "default" ? " (assumed)" : ""}`;
|
|
18
|
+
}
|
|
19
|
+
export function modelSummary(result) {
|
|
20
|
+
const groups = modelGroups(result);
|
|
21
|
+
return groups.length === 1 ? modelLabel(groups[0].model) : "models resolved per request";
|
|
22
|
+
}
|
|
23
|
+
/** Plain text only: renderers must apply their own escaping. */
|
|
24
|
+
export function modelNotes(result) {
|
|
25
|
+
const notes = [];
|
|
26
|
+
for (const { model, requestIndices } of modelGroups(result)) {
|
|
27
|
+
const where = describeRequestIndices(requestIndices);
|
|
28
|
+
if (model.unrecognized)
|
|
29
|
+
notes.push(`${where}: "${model.unrecognized}" is not in the pricing table. Prices, cache thresholds and context window assume ${model.displayName}. Use a model override to change this assumption.`);
|
|
30
|
+
else if (model.source === "default")
|
|
31
|
+
notes.push(`${where}: no model named; prices, cache thresholds and context window assume ${model.displayName}. Unnamed requests share a separate cache, isolated from named models.`);
|
|
32
|
+
}
|
|
33
|
+
if (result.reports.some((r) => r.model.source === "option"))
|
|
34
|
+
notes.push("Model override applies prices, cache thresholds and context windows to every request. Cache identity still follows the model names captured in the log.");
|
|
35
|
+
if (result.cacheSimulation.provider === "openai") {
|
|
36
|
+
const modes = new Set(result.cacheSimulation.actual.map((s) => s.cacheMode));
|
|
37
|
+
if (modes.has("implicit") || modes.has("explicit"))
|
|
38
|
+
notes.push("OpenAI breakpoint caching: 30-minute writes cost 1.25 times ordinary input. Reads require an eligible matching boundary. GPT-6 input/cache rates double above 272,000 modeled input tokens. Prices assume Standard processing. Cache keys and changed renderer settings are isolated; expiry and hidden provider tokens are not modeled.");
|
|
39
|
+
if (modes.has("legacy"))
|
|
40
|
+
notes.push("Legacy OpenAI caching is an optimistic approximation: visible prefixes of at least 1,024 tokens, reads rounded to 128. Actual thresholds and hidden breakpoint intervals depend on request settings; no write premium is modeled.");
|
|
41
|
+
}
|
|
42
|
+
return notes;
|
|
43
|
+
}
|
|
44
|
+
//# sourceMappingURL=model-summary.js.map
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { ParsedRequest } from "./types.js";
|
|
2
|
+
export interface OpenAiCachePlan {
|
|
3
|
+
mode: "implicit" | "explicit";
|
|
4
|
+
/** Segment endpoints the incoming request can look up, not just the ones it writes. */
|
|
5
|
+
lookup: number[];
|
|
6
|
+
write: number[];
|
|
7
|
+
explicit: number[];
|
|
8
|
+
}
|
|
9
|
+
/** Cache options are control data, never tokens or prefix content. Validate before simulating. */
|
|
10
|
+
export declare function openAiCachePlan(request: ParsedRequest): OpenAiCachePlan;
|
|
11
|
+
/** Different cache keys and renderer settings cannot safely share a predicted hit.
|
|
12
|
+
* Conservatively isolate the whole request when settings change; providers may retain a
|
|
13
|
+
* smaller prefix. Keys and configuration strings are never volatile-normalized. */
|
|
14
|
+
export declare function openAiCacheScope(request: ParsedRequest): string;
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
import { isRecord } from "./json-utils.js";
|
|
2
|
+
import { normalizeModelId } from "./pricing.js";
|
|
3
|
+
import { ContextScopeParseError } from "./parse-error.js";
|
|
4
|
+
function fail(request, detail) {
|
|
5
|
+
throw new ContextScopeParseError(`Request ${request.index + 1}: ${detail}`);
|
|
6
|
+
}
|
|
7
|
+
/** Cache options are control data, never tokens or prefix content. Validate before simulating. */
|
|
8
|
+
export function openAiCachePlan(request) {
|
|
9
|
+
const raw = isRecord(request.raw) ? request.raw : {};
|
|
10
|
+
const options = raw["prompt_cache_options"];
|
|
11
|
+
if (options !== undefined && options !== null && (!isRecord(options)
|
|
12
|
+
|| (options.mode !== undefined && options.mode !== "implicit" && options.mode !== "explicit")
|
|
13
|
+
|| (options.ttl !== undefined && options.ttl !== "30m"))) {
|
|
14
|
+
fail(request, 'prompt_cache_options requires mode "implicit" or "explicit" and an omitted or "30m" ttl.');
|
|
15
|
+
}
|
|
16
|
+
const mode = isRecord(options) && options.mode === "explicit" ? "explicit" : "implicit";
|
|
17
|
+
const key = raw["prompt_cache_key"];
|
|
18
|
+
if (key !== undefined && key !== null && typeof key !== "string")
|
|
19
|
+
fail(request, "prompt_cache_key must be a string or null.");
|
|
20
|
+
const explicit = [];
|
|
21
|
+
request.segments.forEach((segment, index) => {
|
|
22
|
+
if (!isRecord(segment.raw))
|
|
23
|
+
return;
|
|
24
|
+
const marker = segment.raw["prompt_cache_breakpoint"];
|
|
25
|
+
if (marker === undefined || marker === null)
|
|
26
|
+
return;
|
|
27
|
+
if (!isRecord(marker) || marker.mode !== "explicit")
|
|
28
|
+
fail(request, `${segment.path}.prompt_cache_breakpoint requires mode "explicit".`);
|
|
29
|
+
// Tool definitions, message headers and reasoning items cannot receive content-block markers.
|
|
30
|
+
if (!/^(?:messages|input)\[\d+\]\.(?:content|output)\[\d+\]$/.test(segment.path)) {
|
|
31
|
+
fail(request, `${segment.path}.prompt_cache_breakpoint is outside a supported content block.`);
|
|
32
|
+
}
|
|
33
|
+
explicit.push(index);
|
|
34
|
+
});
|
|
35
|
+
const { eligible, initialDeveloper } = eligibleEndings(raw, request.segments);
|
|
36
|
+
const implicit = mode === "implicit" ? eligible.at(-1) : undefined;
|
|
37
|
+
const write = [...explicit.slice(mode === "explicit" ? -4 : -3), ...(implicit === undefined ? [] : [implicit])];
|
|
38
|
+
// The current caching guide specifies first 2 + latest 50; generated API reference prose
|
|
39
|
+
// still says latest 80. Follow the guide, which the reference links for current behavior.
|
|
40
|
+
const lookup = [...explicit.slice(0, 2), ...explicit.slice(-50)];
|
|
41
|
+
if (mode === "implicit") {
|
|
42
|
+
lookup.push(...eligible.slice(-21)); // latest endpoint and up to 20 earlier endings
|
|
43
|
+
if (initialDeveloper !== undefined)
|
|
44
|
+
lookup.push(initialDeveloper);
|
|
45
|
+
}
|
|
46
|
+
const unique = (values) => [...new Set(values)].sort((a, b) => a - b);
|
|
47
|
+
return { mode, lookup: unique(lookup), write: unique(write), explicit };
|
|
48
|
+
}
|
|
49
|
+
function eligibleEndings(raw, segments) {
|
|
50
|
+
const responses = !Array.isArray(raw["messages"]);
|
|
51
|
+
const input = raw[responses ? "input" : "messages"];
|
|
52
|
+
if (responses && typeof input === "string") {
|
|
53
|
+
const end = segments.findIndex((s) => s.path === "input");
|
|
54
|
+
const initialDeveloper = segments.findIndex((s) => s.path === "instructions");
|
|
55
|
+
return { eligible: [initialDeveloper, end].filter((n) => n >= 0), ...(initialDeveloper < 0 ? {} : { initialDeveloper }) };
|
|
56
|
+
}
|
|
57
|
+
const items = Array.isArray(input) ? input : [];
|
|
58
|
+
const prefix = responses ? "input" : "messages";
|
|
59
|
+
const endings = new Map();
|
|
60
|
+
segments.forEach((segment, index) => {
|
|
61
|
+
const match = /^(messages|input)\[(\d+)\]/.exec(segment.path);
|
|
62
|
+
if (match?.[1] === prefix)
|
|
63
|
+
endings.set(Number(match[2]), index);
|
|
64
|
+
});
|
|
65
|
+
const role = (item) => {
|
|
66
|
+
if (!isRecord(item))
|
|
67
|
+
return undefined;
|
|
68
|
+
if (responses && typeof item.type === "string" && item.type.endsWith("_output"))
|
|
69
|
+
return "tool";
|
|
70
|
+
if (responses && item.type !== undefined && item.type !== "message")
|
|
71
|
+
return undefined;
|
|
72
|
+
return typeof item.role === "string" ? item.role : "user";
|
|
73
|
+
};
|
|
74
|
+
let initialDeveloper = responses ? segments.findIndex((s) => s.path === "instructions") : -1;
|
|
75
|
+
let inInitialDevelopers = true;
|
|
76
|
+
const eligible = [];
|
|
77
|
+
items.forEach((item, i) => {
|
|
78
|
+
const current = role(item);
|
|
79
|
+
const developer = current === "developer" || current === "system";
|
|
80
|
+
const end = endings.get(i);
|
|
81
|
+
if (inInitialDevelopers && developer) {
|
|
82
|
+
if (end !== undefined)
|
|
83
|
+
initialDeveloper = end;
|
|
84
|
+
}
|
|
85
|
+
else
|
|
86
|
+
inInitialDevelopers = false;
|
|
87
|
+
if (end !== undefined && (current === "user" || (current === "tool" && role(items[i + 1]) !== "tool")))
|
|
88
|
+
eligible.push(end);
|
|
89
|
+
});
|
|
90
|
+
if (initialDeveloper >= 0)
|
|
91
|
+
eligible.push(initialDeveloper);
|
|
92
|
+
eligible.sort((a, b) => a - b);
|
|
93
|
+
return { eligible, ...(initialDeveloper < 0 ? {} : { initialDeveloper }) };
|
|
94
|
+
}
|
|
95
|
+
/** Different cache keys and renderer settings cannot safely share a predicted hit.
|
|
96
|
+
* Conservatively isolate the whole request when settings change; providers may retain a
|
|
97
|
+
* smaller prefix. Keys and configuration strings are never volatile-normalized. */
|
|
98
|
+
export function openAiCacheScope(request) {
|
|
99
|
+
const raw = isRecord(request.raw) ? request.raw : {};
|
|
100
|
+
const settings = Object.fromEntries(["reasoning", "reasoning_effort", "text", "response_format", "parallel_tool_calls", "tool_choice", "context_management"]
|
|
101
|
+
.filter((key) => raw[key] !== undefined).map((key) => [key, raw[key]]));
|
|
102
|
+
// Schema property order can affect the rendered instructions/output order. Preserve
|
|
103
|
+
// nested setting order rather than canonicalizing two potentially different prompts.
|
|
104
|
+
return JSON.stringify([request.model === undefined ? null : normalizeModelId(request.model),
|
|
105
|
+
Array.isArray(raw["messages"]) ? "chat" : "responses", raw["prompt_cache_key"] ?? null, settings]);
|
|
106
|
+
}
|
|
107
|
+
//# sourceMappingURL=openai-breakpoints.js.map
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { UnmodeledContextKind } from "./types.js";
|
|
2
|
+
/** A native response can echo request fields; it is not another request. */
|
|
3
|
+
export declare function isOpenAiResponseObject(value: unknown): boolean;
|
|
4
|
+
/** Responses can consist entirely of a stored prompt/context reference. */
|
|
5
|
+
export declare function isResponsesBody(value: unknown): value is Record<string, unknown>;
|
|
6
|
+
export interface ContextControl {
|
|
7
|
+
path: string;
|
|
8
|
+
label: string;
|
|
9
|
+
raw: unknown;
|
|
10
|
+
kind: UnmodeledContextKind;
|
|
11
|
+
}
|
|
12
|
+
/** Inspect only actual top-level controls, never quoted text, schemas or metadata. */
|
|
13
|
+
export declare function openAiContextControls(raw: Record<string, unknown>, index: number): ContextControl[];
|
|
14
|
+
/** A bare {id} is the SDK's ItemReference; inline message IDs do not imply a reference. */
|
|
15
|
+
export declare function openAiItemContext(item: Record<string, unknown>, path: string, index: number): UnmodeledContextKind | undefined;
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { isRecord } from "./json-utils.js";
|
|
2
|
+
import { ContextScopeParseError } from "./parse-error.js";
|
|
3
|
+
/** A native response can echo request fields; it is not another request. */
|
|
4
|
+
export function isOpenAiResponseObject(value) {
|
|
5
|
+
return isRecord(value) && value.object === "response" && Array.isArray(value.output);
|
|
6
|
+
}
|
|
7
|
+
/** Responses can consist entirely of a stored prompt/context reference. */
|
|
8
|
+
export function isResponsesBody(value) {
|
|
9
|
+
return isRecord(value) && !isOpenAiResponseObject(value) && !Array.isArray(value.messages)
|
|
10
|
+
&& ("input" in value || "instructions" in value
|
|
11
|
+
|| value.previous_response_id != null || value.conversation != null || value.prompt != null);
|
|
12
|
+
}
|
|
13
|
+
function requireId(value, path, index) {
|
|
14
|
+
if (typeof value !== "string" || value.trim().length === 0)
|
|
15
|
+
throw new ContextScopeParseError(`Request ${index + 1}: ${path} must be a nonempty string. An invalid reference cannot establish context or cache reuse.`);
|
|
16
|
+
}
|
|
17
|
+
/** Inspect only actual top-level controls, never quoted text, schemas or metadata. */
|
|
18
|
+
export function openAiContextControls(raw, index) {
|
|
19
|
+
const out = [];
|
|
20
|
+
if (raw.previous_response_id != null && raw.conversation != null)
|
|
21
|
+
throw new ContextScopeParseError(`Request ${index + 1}: cannot combine previous_response_id and conversation. Select one context source before analysis.`);
|
|
22
|
+
if (raw.previous_response_id != null) {
|
|
23
|
+
requireId(raw.previous_response_id, "previous_response_id", index);
|
|
24
|
+
out.push({ path: "previous_response_id", label: "stored response reference", raw: raw.previous_response_id, kind: "previous_response" });
|
|
25
|
+
}
|
|
26
|
+
if (raw.conversation != null) {
|
|
27
|
+
requireId(isRecord(raw.conversation) ? raw.conversation.id : raw.conversation, "conversation or conversation.id", index);
|
|
28
|
+
out.push({ path: "conversation", label: "stored conversation reference", raw: raw.conversation, kind: "conversation" });
|
|
29
|
+
}
|
|
30
|
+
if (raw.prompt != null) {
|
|
31
|
+
requireId(isRecord(raw.prompt) ? raw.prompt.id : undefined, "prompt.id", index);
|
|
32
|
+
out.push({ path: "prompt", label: "reusable prompt reference", raw: raw.prompt, kind: "prompt_template" });
|
|
33
|
+
}
|
|
34
|
+
return out;
|
|
35
|
+
}
|
|
36
|
+
/** A bare {id} is the SDK's ItemReference; inline message IDs do not imply a reference. */
|
|
37
|
+
export function openAiItemContext(item, path, index) {
|
|
38
|
+
if (item.type === "item_reference" || (item.type == null && "id" in item && !("role" in item) && !("content" in item))) {
|
|
39
|
+
requireId(item.id, `${path}.id`, index);
|
|
40
|
+
return "item_reference";
|
|
41
|
+
}
|
|
42
|
+
// Summary/content fields and opaque ciphertext do not reproduce the
|
|
43
|
+
// provider's reasoning-history rendering. Withhold this unit conservatively.
|
|
44
|
+
if (item.type === "reasoning")
|
|
45
|
+
return "reasoning";
|
|
46
|
+
if (item.type === "compaction")
|
|
47
|
+
return "compaction";
|
|
48
|
+
// MCP configuration, imported listings and tool-protocol items do not
|
|
49
|
+
// reproduce the provider's model-facing MCP prompt rendering locally.
|
|
50
|
+
if (typeof item.type === "string" && ["mcp_list_tools", "mcp_call", "mcp_approval_request", "mcp_approval_response"].includes(item.type))
|
|
51
|
+
return "mcp_tools";
|
|
52
|
+
return undefined;
|
|
53
|
+
}
|
|
54
|
+
//# sourceMappingURL=openai-context.js.map
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import type { ParsedRequest } from "./types.js";
|
|
2
|
+
import { type TokenCounter } from "./token-counter.js";
|
|
3
|
+
/** Parses one Anthropic Messages API request body into provider-order segments: tools -> system -> messages. */
|
|
4
|
+
export declare function parseAnthropicRequest(raw: unknown, index: number, counter?: TokenCounter): ParsedRequest;
|