@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,130 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Model metadata: context window, list pricing, and (for Anthropic) the
|
|
3
|
+
* prompt-cache minimum-cacheable-prefix and read-discount rules.
|
|
4
|
+
*
|
|
5
|
+
* Anthropic figures are from Anthropic's model pricing table and prompt
|
|
6
|
+
* caching reference (minimum cacheable prefix per model, write multipliers,
|
|
7
|
+
* per-model read prices), as of 2026-09-25. Two current models break the
|
|
8
|
+
* usual "reads cost 0.1x input" rule: Claude Opus 5.5 reads at $0.20/MTok
|
|
9
|
+
* (0.05x of $4) and Claude Fable 5.1 at $0.25/MTok (0.025x of $10). The
|
|
10
|
+
* minimum cacheable prefix is not monotonic across generations (512 tokens on
|
|
11
|
+
* the newest models, 4096 on Opus 4.6 and Haiku 4.5), which is exactly why it
|
|
12
|
+
* is looked up per model instead of assumed.
|
|
13
|
+
*
|
|
14
|
+
* OpenAI figures were fetched on 2026-09-24 from
|
|
15
|
+
* https://developers.openai.com/api/docs/pricing (model pricing) and
|
|
16
|
+
* https://developers.openai.com/api/docs/guides/prompt-caching (caching
|
|
17
|
+
* rules). Cache regimes were checked again on 2026-10-09: current models
|
|
18
|
+
* use exact modeled boundaries and 30-minute write charges; GPT-5.1/5.2
|
|
19
|
+
* retain the documented legacy approximation (see cache-openai.ts).
|
|
20
|
+
*/
|
|
21
|
+
// Cache write multipliers are the same across all current Anthropic models.
|
|
22
|
+
export const ANTHROPIC_CACHE_WRITE_MULTIPLIER_5M = 1.25;
|
|
23
|
+
export const ANTHROPIC_CACHE_WRITE_MULTIPLIER_1H = 2.0;
|
|
24
|
+
export const ANTHROPIC_MAX_BREAKPOINTS = 4;
|
|
25
|
+
export const ANTHROPIC_LOOKBACK_POSITIONS = 20;
|
|
26
|
+
export const ANTHROPIC_MODELS = [
|
|
27
|
+
{ id: "claude-fable-5-1", displayName: "Claude Fable 5.1", contextWindow: 1_000_000, inputPricePerMTok: 10, outputPricePerMTok: 50, cacheReadMultiplier: 0.025, minCacheableTokens: 512, midConversationSystem: true },
|
|
28
|
+
{ id: "claude-fable-5", displayName: "Claude Fable 5", contextWindow: 1_000_000, inputPricePerMTok: 10, outputPricePerMTok: 50, cacheReadMultiplier: 0.1, minCacheableTokens: 512, midConversationSystem: true },
|
|
29
|
+
{ id: "claude-opus-5-5", displayName: "Claude Opus 5.5", contextWindow: 1_000_000, inputPricePerMTok: 4, outputPricePerMTok: 20, cacheReadMultiplier: 0.05, minCacheableTokens: 512, midConversationSystem: true },
|
|
30
|
+
{ id: "claude-opus-5", displayName: "Claude Opus 5", contextWindow: 1_000_000, inputPricePerMTok: 5, outputPricePerMTok: 25, cacheReadMultiplier: 0.1, minCacheableTokens: 512, midConversationSystem: true },
|
|
31
|
+
{ id: "claude-opus-4-8", displayName: "Claude Opus 4.8", contextWindow: 1_000_000, inputPricePerMTok: 5, outputPricePerMTok: 25, cacheReadMultiplier: 0.1, minCacheableTokens: 1024, midConversationSystem: true },
|
|
32
|
+
{ id: "claude-opus-4-7", displayName: "Claude Opus 4.7", contextWindow: 1_000_000, inputPricePerMTok: 5, outputPricePerMTok: 25, cacheReadMultiplier: 0.1, minCacheableTokens: 2048, midConversationSystem: false },
|
|
33
|
+
{ id: "claude-opus-4-6", displayName: "Claude Opus 4.6", contextWindow: 1_000_000, inputPricePerMTok: 5, outputPricePerMTok: 25, cacheReadMultiplier: 0.1, minCacheableTokens: 4096, midConversationSystem: false },
|
|
34
|
+
{ id: "claude-sonnet-5-5", displayName: "Claude Sonnet 5.5", contextWindow: 1_000_000, inputPricePerMTok: 2, outputPricePerMTok: 10, cacheReadMultiplier: 0.1, minCacheableTokens: 512, midConversationSystem: true },
|
|
35
|
+
{ id: "claude-sonnet-5", displayName: "Claude Sonnet 5", contextWindow: 1_000_000, inputPricePerMTok: 2, outputPricePerMTok: 10, cacheReadMultiplier: 0.1, minCacheableTokens: 1024, midConversationSystem: false },
|
|
36
|
+
{ id: "claude-sonnet-4-6", displayName: "Claude Sonnet 4.6", contextWindow: 1_000_000, inputPricePerMTok: 3, outputPricePerMTok: 15, cacheReadMultiplier: 0.1, minCacheableTokens: 1024, midConversationSystem: false },
|
|
37
|
+
// Claude 4.5 generation, fetched 2026-10-08 from https://platform.claude.com/docs/en/about-claude/pricing and
|
|
38
|
+
// https://platform.claude.com/docs/en/build-with-claude/prompt-caching (minimums), context windows from
|
|
39
|
+
// https://platform.claude.com/docs/en/models/opus-4-5/overview and .../build-with-claude/context-windows.
|
|
40
|
+
// Without these two a Claude Opus 4.5 log was priced as the default model and its 4,096-token minimum read as 512.
|
|
41
|
+
{ id: "claude-opus-4-5", displayName: "Claude Opus 4.5", contextWindow: 200_000, inputPricePerMTok: 5, outputPricePerMTok: 25, cacheReadMultiplier: 0.1, minCacheableTokens: 4096, midConversationSystem: false },
|
|
42
|
+
{ id: "claude-sonnet-4-5", displayName: "Claude Sonnet 4.5", contextWindow: 200_000, inputPricePerMTok: 3, outputPricePerMTok: 15, cacheReadMultiplier: 0.1, minCacheableTokens: 1024, midConversationSystem: false },
|
|
43
|
+
{ id: "claude-haiku-4-5", displayName: "Claude Haiku 4.5", contextWindow: 200_000, inputPricePerMTok: 1, outputPricePerMTok: 5, cacheReadMultiplier: 0.1, minCacheableTokens: 4096, midConversationSystem: false },
|
|
44
|
+
];
|
|
45
|
+
// GPT-6 Astra / Sol / Luna: prices, context windows and long-context multiplier checked
|
|
46
|
+
// against https://developers.openai.com/api/docs/models/gpt-6-{astra,sol,luna} on 2026-10-09.
|
|
47
|
+
export const OPENAI_MODELS = [
|
|
48
|
+
{ id: "gpt-6-astra", displayName: "GPT-6 Astra", contextWindow: 1_050_000, inputPricePerMTok: 10, outputPricePerMTok: 50, cachedInputPricePerMTok: 1, cacheStyle: "breakpoints", longContextInput: { aboveTokens: 272_000, multiplier: 2 } },
|
|
49
|
+
{ id: "gpt-6-sol", displayName: "GPT-6 Sol", contextWindow: 1_050_000, inputPricePerMTok: 2, outputPricePerMTok: 10, cachedInputPricePerMTok: 0.2, cacheStyle: "breakpoints", longContextInput: { aboveTokens: 272_000, multiplier: 2 } },
|
|
50
|
+
{ id: "gpt-6-luna", displayName: "GPT-6 Luna", contextWindow: 1_050_000, inputPricePerMTok: 0.1, outputPricePerMTok: 0.5, cachedInputPricePerMTok: 0.01, cacheStyle: "breakpoints", longContextInput: { aboveTokens: 272_000, multiplier: 2 } },
|
|
51
|
+
// Historical models present in the public replay corpus. Model pages checked 2026-10-09:
|
|
52
|
+
// https://developers.openai.com/api/docs/models/gpt-5.1 and .../gpt-5.2.
|
|
53
|
+
{ id: "gpt-5.2", displayName: "GPT-5.2", contextWindow: 400_000, inputPricePerMTok: 1.75, outputPricePerMTok: 14, cachedInputPricePerMTok: 0.175, cacheStyle: "legacy" },
|
|
54
|
+
{ id: "gpt-5.1", displayName: "GPT-5.1", contextWindow: 400_000, inputPricePerMTok: 1.25, outputPricePerMTok: 10, cachedInputPricePerMTok: 0.125, cacheStyle: "legacy" },
|
|
55
|
+
];
|
|
56
|
+
export const DEFAULT_ANTHROPIC_MODEL = "claude-sonnet-5-5";
|
|
57
|
+
export const DEFAULT_OPENAI_MODEL = "gpt-6-sol";
|
|
58
|
+
/**
|
|
59
|
+
* Reduces the model ids real request logs carry to the canonical ids in the
|
|
60
|
+
* tables above: dated snapshots (`claude-haiku-4-5-20251001`), Amazon Bedrock
|
|
61
|
+
* ids (`anthropic.claude-opus-5-5`, `us.anthropic.claude-sonnet-5-v1:0`),
|
|
62
|
+
* Google Vertex AI snapshots (`claude-opus-4-5@20251101`), and OpenAI dated
|
|
63
|
+
* snapshots (`gpt-6-sol-2026-08-01`).
|
|
64
|
+
*/
|
|
65
|
+
export function normalizeModelId(id) {
|
|
66
|
+
let out = id.trim().toLowerCase();
|
|
67
|
+
out = out.replace(/^(?:[a-z]+\.)?anthropic\./, "");
|
|
68
|
+
out = out.replace(/@.*$/, "");
|
|
69
|
+
out = out.replace(/-v\d+(?::\d+)?$/, "");
|
|
70
|
+
out = out.replace(/-\d{8}$/, "");
|
|
71
|
+
out = out.replace(/-\d{4}-\d{2}-\d{2}$/, "");
|
|
72
|
+
return out;
|
|
73
|
+
}
|
|
74
|
+
export function lookupAnthropicModel(id) {
|
|
75
|
+
if (!id)
|
|
76
|
+
return undefined;
|
|
77
|
+
const key = normalizeModelId(id);
|
|
78
|
+
return ANTHROPIC_MODELS.find((m) => m.id === key);
|
|
79
|
+
}
|
|
80
|
+
export function lookupOpenAiModel(id) {
|
|
81
|
+
if (!id)
|
|
82
|
+
return undefined;
|
|
83
|
+
const key = normalizeModelId(id);
|
|
84
|
+
return OPENAI_MODELS.find((m) => m.id === key);
|
|
85
|
+
}
|
|
86
|
+
export function findAnthropicModel(id) {
|
|
87
|
+
return lookupAnthropicModel(id) ?? ANTHROPIC_MODELS.find((m) => m.id === DEFAULT_ANTHROPIC_MODEL);
|
|
88
|
+
}
|
|
89
|
+
export function findOpenAiModel(id) {
|
|
90
|
+
return lookupOpenAiModel(id) ?? OPENAI_MODELS.find((m) => m.id === DEFAULT_OPENAI_MODEL);
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* Resolves model metadata: an explicit option wins; otherwise
|
|
94
|
+
* the model named most often in the requests themselves; otherwise the
|
|
95
|
+
* provider default. An id with no pricing entry falls back to the default but
|
|
96
|
+
* is reported as `unrecognized`, so callers can say so instead of silently
|
|
97
|
+
* pricing an Opus log at Sonnet rates. Analysis calls this for each request;
|
|
98
|
+
* the most-common choice remains only as a compatibility summary.
|
|
99
|
+
*/
|
|
100
|
+
export function resolveModel(provider, explicit, requestModels) {
|
|
101
|
+
const lookup = provider === "anthropic" ? lookupAnthropicModel : lookupOpenAiModel;
|
|
102
|
+
const fallback = provider === "anthropic" ? findAnthropicModel(undefined) : findOpenAiModel(undefined);
|
|
103
|
+
let candidate;
|
|
104
|
+
let source = "default";
|
|
105
|
+
if (explicit !== undefined && explicit.trim() !== "") {
|
|
106
|
+
candidate = explicit;
|
|
107
|
+
source = "option";
|
|
108
|
+
}
|
|
109
|
+
else {
|
|
110
|
+
const counts = new Map();
|
|
111
|
+
for (const m of requestModels)
|
|
112
|
+
if (m)
|
|
113
|
+
counts.set(m, (counts.get(m) ?? 0) + 1);
|
|
114
|
+
let best;
|
|
115
|
+
for (const entry of counts)
|
|
116
|
+
if (!best || entry[1] > best[1])
|
|
117
|
+
best = entry;
|
|
118
|
+
if (best) {
|
|
119
|
+
candidate = best[0];
|
|
120
|
+
source = "request";
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
if (candidate === undefined)
|
|
124
|
+
return { id: fallback.id, displayName: fallback.displayName, source: "default" };
|
|
125
|
+
const info = lookup(candidate);
|
|
126
|
+
if (info)
|
|
127
|
+
return { id: info.id, displayName: info.displayName, source };
|
|
128
|
+
return { id: fallback.id, displayName: fallback.displayName, source: "default", unrecognized: candidate };
|
|
129
|
+
}
|
|
130
|
+
//# sourceMappingURL=pricing.js.map
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import type { Provider, Segment } from "./types.js";
|
|
2
|
+
/** Attach source prompt units after parsing, without changing their text or token counts.
|
|
3
|
+
* A start marker retains message boundaries without binding history to absolute indices:
|
|
4
|
+
* a sliding-window rewrite can still match older messages at their new positions. */
|
|
5
|
+
export declare function attachPromptIdentity(request: Record<string, unknown>, segments: Segment[], provider: Provider): void;
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import { isRecord } from "./json-utils.js";
|
|
2
|
+
/** The message's header belongs to every part; following tool calls have their own segments. */
|
|
3
|
+
function header(message) {
|
|
4
|
+
return Object.fromEntries(Object.entries(message).filter(([key]) => !["content", "tool_calls", "function_call"].includes(key)));
|
|
5
|
+
}
|
|
6
|
+
/** A tool result's string content is shorthand for one text block, as a message's string content is. */
|
|
7
|
+
function withTextBlockContent(block) {
|
|
8
|
+
if (!isRecord(block) || block["type"] !== "tool_result" || typeof block["content"] !== "string")
|
|
9
|
+
return block;
|
|
10
|
+
return { ...block, content: [{ type: "text", text: block["content"] }] };
|
|
11
|
+
}
|
|
12
|
+
/** Attach source prompt units after parsing, without changing their text or token counts.
|
|
13
|
+
* A start marker retains message boundaries without binding history to absolute indices:
|
|
14
|
+
* a sliding-window rewrite can still match older messages at their new positions. */
|
|
15
|
+
export function attachPromptIdentity(request, segments, provider) {
|
|
16
|
+
let previousMessage;
|
|
17
|
+
for (const segment of segments) {
|
|
18
|
+
const path = segment.path;
|
|
19
|
+
const messagePath = /^messages\[(\d+)\](.*)$/.exec(path);
|
|
20
|
+
if (messagePath) {
|
|
21
|
+
const index = Number(messagePath[1]);
|
|
22
|
+
const message = request["messages"][index];
|
|
23
|
+
const owner = `messages:${index}`;
|
|
24
|
+
const context = { api: provider === "anthropic" ? "messages" : "chat", header: isRecord(message) ? header(message) : null, startsMessage: owner !== previousMessage };
|
|
25
|
+
previousMessage = owner;
|
|
26
|
+
let content = message;
|
|
27
|
+
if (isRecord(message)) {
|
|
28
|
+
const suffix = messagePath[2];
|
|
29
|
+
const part = /^\.content\[(\d+)\]$/.exec(suffix);
|
|
30
|
+
const call = /^\.tool_calls\[(\d+)\]$/.exec(suffix);
|
|
31
|
+
if (suffix.startsWith(".content")) {
|
|
32
|
+
const raw = message["content"];
|
|
33
|
+
content = typeof raw === "string" ? { type: "text", text: raw }
|
|
34
|
+
: part && Array.isArray(raw) ? (provider === "anthropic" ? withTextBlockContent(raw[Number(part[1])]) : raw[Number(part[1])]) : raw;
|
|
35
|
+
}
|
|
36
|
+
else if (call && Array.isArray(message["tool_calls"]))
|
|
37
|
+
content = message["tool_calls"][Number(call[1])];
|
|
38
|
+
else if (suffix === ".function_call")
|
|
39
|
+
content = message["function_call"];
|
|
40
|
+
else if (suffix === ".refusal")
|
|
41
|
+
content = { type: "refusal", refusal: message["refusal"] };
|
|
42
|
+
}
|
|
43
|
+
segment.prefix = { context, content };
|
|
44
|
+
continue;
|
|
45
|
+
}
|
|
46
|
+
const responsePath = /^input\[(\d+)\](.*)$/.exec(path);
|
|
47
|
+
if (provider === "openai" && responsePath && Array.isArray(request["input"])) {
|
|
48
|
+
const index = Number(responsePath[1]);
|
|
49
|
+
const item = request["input"][index];
|
|
50
|
+
const owner = `input:${index}`;
|
|
51
|
+
const outputPart = /^\.output\[(\d+)\]$/.exec(responsePath[2]);
|
|
52
|
+
if (isRecord(item) && outputPart && Array.isArray(item["output"])) {
|
|
53
|
+
segment.prefix = {
|
|
54
|
+
context: { api: "responses", header: Object.fromEntries(Object.entries(item).filter(([key]) => key !== "output")), startsMessage: owner !== previousMessage },
|
|
55
|
+
content: item["output"][Number(outputPart[1])],
|
|
56
|
+
};
|
|
57
|
+
previousMessage = owner;
|
|
58
|
+
continue;
|
|
59
|
+
}
|
|
60
|
+
const message = isRecord(item) && (item["type"] === undefined || item["type"] === "message");
|
|
61
|
+
const context = { api: "responses", header: message ? header(item) : null, startsMessage: owner !== previousMessage };
|
|
62
|
+
previousMessage = owner;
|
|
63
|
+
let content = item;
|
|
64
|
+
if (message && responsePath[2].startsWith(".content")) {
|
|
65
|
+
const raw = item["content"];
|
|
66
|
+
const part = /^\.content\[(\d+)\]$/.exec(responsePath[2]);
|
|
67
|
+
content = typeof raw === "string" ? { type: item["role"] === "assistant" ? "output_text" : "input_text", text: raw }
|
|
68
|
+
: part && Array.isArray(raw) ? raw[Number(part[1])] : raw;
|
|
69
|
+
}
|
|
70
|
+
segment.prefix = { context, content };
|
|
71
|
+
continue;
|
|
72
|
+
}
|
|
73
|
+
// A plain system string is shorthand for one text block, not a different prompt.
|
|
74
|
+
const system = /^system(?:\[(\d+)\])?$/.exec(path);
|
|
75
|
+
if (provider === "anthropic" && system) {
|
|
76
|
+
const raw = request["system"];
|
|
77
|
+
segment.prefix = { content: typeof raw === "string" ? { type: "text", text: raw }
|
|
78
|
+
: Array.isArray(raw) && system[1] !== undefined ? raw[Number(system[1])] : raw };
|
|
79
|
+
}
|
|
80
|
+
else
|
|
81
|
+
segment.prefix = { content: segment.raw };
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
//# sourceMappingURL=prompt-identity.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/** Validate evidence before analysis can use overwritten fields or rounded numbers.
|
|
2
|
+
* Syntax remains the native parser's job; this scan bounds nesting and tracks object keys.
|
|
3
|
+
* It is iterative so even an input thousands of levels deep produces an actionable error. */
|
|
4
|
+
export declare const MAX_JSON_DEPTH = 128;
|
|
5
|
+
export declare class JsonIntegrityError extends Error {
|
|
6
|
+
}
|
|
7
|
+
export declare function readJson(text: string): unknown;
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
/** Validate evidence before analysis can use overwritten fields or rounded numbers.
|
|
2
|
+
* Syntax remains the native parser's job; this scan bounds nesting and tracks object keys.
|
|
3
|
+
* It is iterative so even an input thousands of levels deep produces an actionable error. */
|
|
4
|
+
export const MAX_JSON_DEPTH = 128;
|
|
5
|
+
export class JsonIntegrityError extends Error {
|
|
6
|
+
}
|
|
7
|
+
/** Decimal value independent of spelling, without converting its digits to a
|
|
8
|
+
* floating-point number. This permits 1.0 / 1e0 while detecting changed IDs or
|
|
9
|
+
* precise decimals after the parser's number is serialized into prompt text. */
|
|
10
|
+
function decimalIdentity(literal) {
|
|
11
|
+
const [coefficient = "", exponent = "0"] = literal.toLowerCase().split("e");
|
|
12
|
+
const dot = coefficient.indexOf(".");
|
|
13
|
+
const fractionDigits = dot < 0 ? 0 : coefficient.length - dot - 1;
|
|
14
|
+
const digits = coefficient.replace(/[-.]/g, "").replace(/^0+/, "");
|
|
15
|
+
if (!digits)
|
|
16
|
+
return "0";
|
|
17
|
+
const significant = digits.replace(/0+$/, "");
|
|
18
|
+
const power = Number(exponent) - fractionDigits + digits.length - significant.length;
|
|
19
|
+
return `${coefficient.startsWith("-") ? "-" : ""}${significant}e${power}`;
|
|
20
|
+
}
|
|
21
|
+
export function readJson(text) {
|
|
22
|
+
// Native parsing is iterative and supplies syntax validation. Only inspect valid JSON:
|
|
23
|
+
// an incomplete JSONL line must not make the following records appear nested inside it.
|
|
24
|
+
const value = JSON.parse(text);
|
|
25
|
+
const containers = [];
|
|
26
|
+
for (let i = 0; i < text.length; i++) {
|
|
27
|
+
const char = text[i];
|
|
28
|
+
if (char === '"') {
|
|
29
|
+
const start = i;
|
|
30
|
+
for (i++; i < text.length; i++) {
|
|
31
|
+
if (text[i] === "\\")
|
|
32
|
+
i++;
|
|
33
|
+
else if (text[i] === '"')
|
|
34
|
+
break;
|
|
35
|
+
}
|
|
36
|
+
let next = i + 1;
|
|
37
|
+
while (/\s/.test(text[next] ?? "") && next < text.length)
|
|
38
|
+
next++;
|
|
39
|
+
const keys = containers[containers.length - 1];
|
|
40
|
+
if (keys && text[next] === ":") {
|
|
41
|
+
const key = JSON.parse(text.slice(start, i + 1));
|
|
42
|
+
if (keys.has(key))
|
|
43
|
+
throw new JsonIntegrityError(`Duplicate JSON field ${JSON.stringify(key.slice(0, 80))}. Keep one explicit value before analysis.`);
|
|
44
|
+
keys.add(key);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
else if (char === "{" || char === "[") {
|
|
48
|
+
containers.push(char === "{" ? new Set() : undefined);
|
|
49
|
+
if (containers.length > MAX_JSON_DEPTH)
|
|
50
|
+
throw new JsonIntegrityError(`JSON nesting exceeds ${MAX_JSON_DEPTH} levels. Flatten the request metadata or split the log before analysis.`);
|
|
51
|
+
}
|
|
52
|
+
else if (char === "}" || char === "]") {
|
|
53
|
+
containers.pop();
|
|
54
|
+
}
|
|
55
|
+
else if (char === "-" || (char !== undefined && char >= "0" && char <= "9")) {
|
|
56
|
+
const start = i;
|
|
57
|
+
while (i + 1 < text.length && /[\d.eE+-]/.test(text[i + 1]))
|
|
58
|
+
i++;
|
|
59
|
+
const literal = text.slice(start, i + 1);
|
|
60
|
+
const number = Number(literal);
|
|
61
|
+
if (!Number.isFinite(number))
|
|
62
|
+
throw new JsonIntegrityError("JSON number is outside the finite JavaScript number range. Preserve it as a string or use representable units.");
|
|
63
|
+
if (number === 0 && /[1-9]/.test(literal.split(/[eE]/, 1)[0])) {
|
|
64
|
+
throw new JsonIntegrityError("Nonzero JSON number underflows to zero in JavaScript. Preserve it as a string or use representable units.");
|
|
65
|
+
}
|
|
66
|
+
const serialized = String(number);
|
|
67
|
+
if (literal !== serialized && decimalIdentity(literal) !== decimalIdentity(serialized)) {
|
|
68
|
+
throw new JsonIntegrityError(`JSON number at character ${start + 1} would be rounded during analysis. Contextscope cannot analyze this record without changing its numeric content.`);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
return value;
|
|
73
|
+
}
|
|
74
|
+
//# sourceMappingURL=read-json.js.map
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { findAnthropicModel, findOpenAiModel, resolveModel } from "./pricing.js";
|
|
2
|
+
import { sumTokenCounts } from "./media-accounting.js";
|
|
3
|
+
const CATEGORY_ORDER = ["system", "tools", "user", "assistant", "tool_call", "tool_result", "image", "thinking", "reference"];
|
|
4
|
+
export function buildRequestReport(request, provider, model) {
|
|
5
|
+
const resolved = resolveModel(provider, model, [request.model]);
|
|
6
|
+
const byCategory = CATEGORY_ORDER.map((category) => {
|
|
7
|
+
const segs = request.segments.filter((s) => s.category === category);
|
|
8
|
+
return {
|
|
9
|
+
category,
|
|
10
|
+
segmentCount: segs.length,
|
|
11
|
+
openaiTokens: sumTokenCounts(segs.map(s => s.openaiTokens)),
|
|
12
|
+
claudeTokensEstimate: sumTokenCounts(segs.map(s => s.claudeTokensEstimate)),
|
|
13
|
+
};
|
|
14
|
+
}).filter((c) => c.segmentCount > 0);
|
|
15
|
+
const totals = {
|
|
16
|
+
openaiTokens: sumTokenCounts(request.segments.map(s => s.openaiTokens)),
|
|
17
|
+
claudeTokensEstimate: sumTokenCounts(request.segments.map(s => s.claudeTokensEstimate)),
|
|
18
|
+
};
|
|
19
|
+
const contextWindow = provider === "anthropic" ? findAnthropicModel(resolved.id).contextWindow : findOpenAiModel(resolved.id).contextWindow;
|
|
20
|
+
const tokensForWindow = provider === "anthropic" ? totals.claudeTokensEstimate : totals.openaiTokens;
|
|
21
|
+
return {
|
|
22
|
+
requestIndex: request.index,
|
|
23
|
+
model: resolved,
|
|
24
|
+
totals,
|
|
25
|
+
byCategory,
|
|
26
|
+
segments: request.segments,
|
|
27
|
+
contextWindow,
|
|
28
|
+
percentOfContextWindow: contextWindow > 0 && tokensForWindow !== null ? tokensForWindow / contextWindow : undefined,
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
//# sourceMappingURL=report.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { Provider, ReportedUsage } from "./types.js";
|
|
2
|
+
/**
|
|
3
|
+
* Only same-record pairs are joined. A request body can itself contain arbitrary tool data
|
|
4
|
+
* named usage/response, so response adapters are enabled only for an unwrapped request.
|
|
5
|
+
* SSE deltas and response-only records must be assembled/paired by the caller first.
|
|
6
|
+
*/
|
|
7
|
+
export declare function readReportedUsage(record: unknown, envelope: string | undefined, provider: Provider): ReportedUsage | undefined;
|
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
import { readJson } from "./read-json.js";
|
|
2
|
+
function object(value) {
|
|
3
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
4
|
+
}
|
|
5
|
+
function empty(sources, status, issues = []) {
|
|
6
|
+
return { sources, schema: "unknown", status, inputTokens: null, cacheReadTokens: null, cacheWriteTokens: null, outputTokens: null, counters: [], issues, notes: [] };
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* Only same-record pairs are joined. A request body can itself contain arbitrary tool data
|
|
10
|
+
* named usage/response, so response adapters are enabled only for an unwrapped request.
|
|
11
|
+
* SSE deltas and response-only records must be assembled/paired by the caller first.
|
|
12
|
+
*/
|
|
13
|
+
export function readReportedUsage(record, envelope, provider) {
|
|
14
|
+
if (!envelope || !object(record))
|
|
15
|
+
return undefined;
|
|
16
|
+
const candidates = [];
|
|
17
|
+
const invalidBodies = [];
|
|
18
|
+
const decode = (value, path) => {
|
|
19
|
+
if (typeof value !== "string")
|
|
20
|
+
return value;
|
|
21
|
+
try {
|
|
22
|
+
return readJson(value);
|
|
23
|
+
}
|
|
24
|
+
catch {
|
|
25
|
+
invalidBodies.push(path);
|
|
26
|
+
return undefined;
|
|
27
|
+
}
|
|
28
|
+
};
|
|
29
|
+
const addUsage = (value, path) => {
|
|
30
|
+
if (object(value) && Object.hasOwn(value, "usage"))
|
|
31
|
+
candidates.push({ path: `${path}.usage`, value: value["usage"] });
|
|
32
|
+
};
|
|
33
|
+
if (Object.hasOwn(record, "usage"))
|
|
34
|
+
candidates.push({ path: "usage", value: record["usage"] });
|
|
35
|
+
for (const field of ["response", "response_body"]) {
|
|
36
|
+
const response = decode(record[field], field);
|
|
37
|
+
addUsage(response, field);
|
|
38
|
+
if (field === "response" && object(response) && Object.hasOwn(response, "body")) {
|
|
39
|
+
addUsage(decode(response["body"], "response.body"), "response.body");
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
if (invalidBodies.length)
|
|
43
|
+
return empty([...candidates.map((c) => c.path), ...invalidBodies], "invalid", invalidBodies.map((path) => `${path} is not a valid JSON response body.`));
|
|
44
|
+
if (candidates.length === 0)
|
|
45
|
+
return undefined;
|
|
46
|
+
if (candidates.length > 1)
|
|
47
|
+
return empty(candidates.map((c) => c.path), "invalid", ["Multiple response usage objects in one record; keep one unambiguous response per request."]);
|
|
48
|
+
const candidate = candidates[0];
|
|
49
|
+
return normalizeUsage(candidate.value, candidate.path, provider);
|
|
50
|
+
}
|
|
51
|
+
function normalizeUsage(value, source, provider) {
|
|
52
|
+
if (value === null || value === undefined)
|
|
53
|
+
return empty([source], "unavailable");
|
|
54
|
+
if (!object(value))
|
|
55
|
+
return empty([source], "invalid", [`${source} must be an object or null.`]);
|
|
56
|
+
const result = empty([source], "unavailable");
|
|
57
|
+
const issues = result.issues;
|
|
58
|
+
const counters = new Map();
|
|
59
|
+
const has = (path) => {
|
|
60
|
+
let node = value;
|
|
61
|
+
for (const key of path.split(".")) {
|
|
62
|
+
if (!object(node) || !Object.hasOwn(node, key))
|
|
63
|
+
return false;
|
|
64
|
+
node = node[key];
|
|
65
|
+
}
|
|
66
|
+
return true;
|
|
67
|
+
};
|
|
68
|
+
const count = (path) => {
|
|
69
|
+
const existing = counters.get(path);
|
|
70
|
+
if (existing)
|
|
71
|
+
return existing.value ?? null;
|
|
72
|
+
let node = value;
|
|
73
|
+
const keys = path.split(".");
|
|
74
|
+
let malformed = false;
|
|
75
|
+
for (const key of keys) {
|
|
76
|
+
if (node === null || node === undefined) {
|
|
77
|
+
node = undefined;
|
|
78
|
+
break;
|
|
79
|
+
}
|
|
80
|
+
if (!object(node)) {
|
|
81
|
+
malformed = true;
|
|
82
|
+
break;
|
|
83
|
+
}
|
|
84
|
+
node = node[key];
|
|
85
|
+
}
|
|
86
|
+
const fullPath = `${source}.${path}`;
|
|
87
|
+
if (!malformed && (node === undefined || node === null)) {
|
|
88
|
+
counters.set(path, { path: fullPath, status: "missing" });
|
|
89
|
+
return null;
|
|
90
|
+
}
|
|
91
|
+
if (!malformed && typeof node === "number" && Number.isSafeInteger(node) && node >= 0) {
|
|
92
|
+
counters.set(path, { path: fullPath, status: "reported", value: node });
|
|
93
|
+
return node;
|
|
94
|
+
}
|
|
95
|
+
counters.set(path, { path: fullPath, status: "invalid" });
|
|
96
|
+
issues.push(`${fullPath} must be a nonnegative safe integer (or null when unavailable).`);
|
|
97
|
+
return null;
|
|
98
|
+
};
|
|
99
|
+
const aliases = (primary, alternatives) => {
|
|
100
|
+
const names = [primary, ...alternatives.filter(has)];
|
|
101
|
+
const values = names.map(count).filter((n) => n !== null);
|
|
102
|
+
if (new Set(values).size > 1)
|
|
103
|
+
issues.push(`${source}: counters ${names.join(", ")} disagree.`);
|
|
104
|
+
return values[0] ?? null;
|
|
105
|
+
};
|
|
106
|
+
const sum = (numbers, label) => {
|
|
107
|
+
if (numbers.some((n) => n === null))
|
|
108
|
+
return null;
|
|
109
|
+
const total = numbers.reduce((a, b) => a + b, 0);
|
|
110
|
+
if (Number.isSafeInteger(total))
|
|
111
|
+
return total;
|
|
112
|
+
issues.push(`${source}: ${label} exceeds the safe integer range.`);
|
|
113
|
+
return null;
|
|
114
|
+
};
|
|
115
|
+
const chat = ["prompt_tokens", "completion_tokens", "prompt_tokens_details"].some(has);
|
|
116
|
+
const responses = has("input_tokens_details");
|
|
117
|
+
const native = !chat && (["cache_read_input_tokens", "cache_creation_input_tokens", "cache_creation"].some(has) || provider === "anthropic");
|
|
118
|
+
if ((chat && (has("input_tokens") || has("output_tokens") || responses)) || (responses && native)) {
|
|
119
|
+
return empty([source], "invalid", [`${source} mixes incompatible usage schemas.`]);
|
|
120
|
+
}
|
|
121
|
+
let input;
|
|
122
|
+
let read;
|
|
123
|
+
let write;
|
|
124
|
+
let output;
|
|
125
|
+
let total = null;
|
|
126
|
+
if (chat) {
|
|
127
|
+
result.schema = "openai-chat";
|
|
128
|
+
input = count("prompt_tokens");
|
|
129
|
+
output = count("completion_tokens");
|
|
130
|
+
// Gateway captures can include native aliases. Keep their provenance and reject
|
|
131
|
+
// conflicts; historical LiteLLM totals need a separate ambiguity check below.
|
|
132
|
+
read = aliases("prompt_tokens_details.cached_tokens", ["cache_read_input_tokens"]);
|
|
133
|
+
write = aliases("prompt_tokens_details.cache_write_tokens", ["prompt_tokens_details.cache_creation_tokens", "cache_creation_input_tokens"]);
|
|
134
|
+
if (has("total_tokens"))
|
|
135
|
+
total = count("total_tokens");
|
|
136
|
+
}
|
|
137
|
+
else if (native) {
|
|
138
|
+
result.schema = "anthropic";
|
|
139
|
+
read = count("cache_read_input_tokens");
|
|
140
|
+
write = count("cache_creation_input_tokens");
|
|
141
|
+
input = sum([count("input_tokens"), read, write], "total input tokens");
|
|
142
|
+
output = count("output_tokens");
|
|
143
|
+
}
|
|
144
|
+
else {
|
|
145
|
+
result.schema = "openai-responses";
|
|
146
|
+
input = count("input_tokens");
|
|
147
|
+
output = count("output_tokens");
|
|
148
|
+
read = count("input_tokens_details.cached_tokens");
|
|
149
|
+
write = count("input_tokens_details.cache_write_tokens");
|
|
150
|
+
if (has("total_tokens"))
|
|
151
|
+
total = count("total_tokens");
|
|
152
|
+
}
|
|
153
|
+
if (input !== null && total !== null && output !== null && total !== sum([input, output], "input plus output tokens"))
|
|
154
|
+
issues.push(`${source}.total_tokens disagrees with input plus output tokens.`);
|
|
155
|
+
const gateway = chat && (provider === "anthropic" || has("cache_creation_input_tokens") || has("prompt_tokens_details.cache_creation_tokens"));
|
|
156
|
+
if (gateway && write !== 0) {
|
|
157
|
+
// Some LiteLLM versions exclude creation tokens from prompt_tokens; others include
|
|
158
|
+
// them. The capture contains no versioned contract proving which sum was used.
|
|
159
|
+
if (input !== null && read !== null && read > input)
|
|
160
|
+
issues.push(`${source}: cache reads exceed prompt_tokens.`);
|
|
161
|
+
input = null;
|
|
162
|
+
result.notes.push("Gateway prompt_tokens may include or exclude cache creation, depending on the gateway version. Total input is unavailable unless cache creation is explicitly zero; original counters and cache reads are retained.");
|
|
163
|
+
}
|
|
164
|
+
if (input !== null) {
|
|
165
|
+
if ((read !== null && read > input) || (write !== null && write > input))
|
|
166
|
+
issues.push(`${source}: cache reads or writes exceed total input tokens.`);
|
|
167
|
+
if (read !== null && write !== null) {
|
|
168
|
+
const cached = sum([read, write], "cache reads plus writes");
|
|
169
|
+
if (cached !== null && cached > input)
|
|
170
|
+
issues.push(`${source}: cache reads plus writes exceed total input tokens.`);
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
for (const path of ["cache_creation", "prompt_tokens_details.cache_creation_token_details"]) {
|
|
174
|
+
if (!has(path))
|
|
175
|
+
continue;
|
|
176
|
+
const short = count(`${path}.ephemeral_5m_input_tokens`);
|
|
177
|
+
const long = count(`${path}.ephemeral_1h_input_tokens`);
|
|
178
|
+
const ttlTotal = sum([short, long], "cache write TTL breakdown");
|
|
179
|
+
if (write !== null && ((short !== null && short > write) || (long !== null && long > write) || (ttlTotal !== null && ttlTotal !== write))) {
|
|
180
|
+
issues.push(`${source}.${path} disagrees with total cache writes.`);
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
result.counters = [...counters.values()];
|
|
184
|
+
if (issues.length) {
|
|
185
|
+
result.status = "invalid";
|
|
186
|
+
return result;
|
|
187
|
+
}
|
|
188
|
+
result.inputTokens = input;
|
|
189
|
+
result.cacheReadTokens = read;
|
|
190
|
+
result.cacheWriteTokens = write;
|
|
191
|
+
result.outputTokens = output;
|
|
192
|
+
result.status = [input, read, write, output].some((n) => n !== null) ? "valid" : "unavailable";
|
|
193
|
+
return result;
|
|
194
|
+
}
|
|
195
|
+
//# sourceMappingURL=reported-usage.js.map
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import type { ParsedRequest, PrefixRelation } from "./types.js";
|
|
2
|
+
/**
|
|
3
|
+
* A request log is not one conversation. A proxy capture of a coding agent
|
|
4
|
+
* holds its main loop and, between the turns, small side requests on another
|
|
5
|
+
* model; a gateway's log holds every user's conversation, interleaved. The
|
|
6
|
+
* line before a request is then some other conversation's, and comparing the
|
|
7
|
+
* two reports a cache break on every line where there is none.
|
|
8
|
+
*
|
|
9
|
+
* So each request is compared with the request it continues, wherever in the
|
|
10
|
+
* file that is. In order of preference:
|
|
11
|
+
*
|
|
12
|
+
* 1. `continues`: the earlier request whose messages this one starts with,
|
|
13
|
+
* all of them and in order. An agent loop re-sends its history and adds
|
|
14
|
+
* to it, so this is the previous turn of the same conversation.
|
|
15
|
+
* 2. `rewrites`: no request's messages are a prefix of this one's, but at
|
|
16
|
+
* least half of a recent request's messages are re-sent somewhere in it:
|
|
17
|
+
* the same conversation with its history edited (a sliding window, a
|
|
18
|
+
* tool result trimmed, a message re-serialized differently).
|
|
19
|
+
* 3. `new_conversation`: nothing of the conversation was sent before, but
|
|
20
|
+
* the tools and system prompt were, at least once volatile values and
|
|
21
|
+
* ordering are normalized away: a new conversation of the same
|
|
22
|
+
* application. It is compared with the most similar earlier request, and
|
|
23
|
+
* only as far as the setup they share.
|
|
24
|
+
* 4. Otherwise, still `new_conversation` against the request just before it
|
|
25
|
+
* when that one is on the same model with the same tools, which keeps a
|
|
26
|
+
* system prompt rebuilt on every request visible.
|
|
27
|
+
*
|
|
28
|
+
* A request that matches none of these starts a conversation with nothing
|
|
29
|
+
* to compare it to, like the first request of a file.
|
|
30
|
+
*/
|
|
31
|
+
export interface Threads {
|
|
32
|
+
/** For each request: the index of the earlier request it is compared with, if any. */
|
|
33
|
+
predecessor: (number | undefined)[];
|
|
34
|
+
/** For each request: how it relates to that predecessor. */
|
|
35
|
+
relation: (PrefixRelation | undefined)[];
|
|
36
|
+
/** For each request: the number (from 0, in order of first appearance) of its conversation. */
|
|
37
|
+
conversation: number[];
|
|
38
|
+
conversationCount: number;
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* For each request, the trie node of each of its leading runs of segments,
|
|
42
|
+
* in the order the provider serializes them. Two requests share their first
|
|
43
|
+
* `n` segments exactly when their paths agree at position `n - 1`. With
|
|
44
|
+
* `normalizeVolatile`, segments are compared as the optimized scenario
|
|
45
|
+
* compares them (see prefix.ts).
|
|
46
|
+
*/
|
|
47
|
+
export declare function prefixPaths(requests: ParsedRequest[], normalizeVolatile: boolean): number[][];
|
|
48
|
+
export declare function threadRequests(requests: ParsedRequest[], raw?: number[][], normalized?: number[][]): Threads;
|