@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,164 @@
|
|
|
1
|
+
import { detectFormat, detectProvider } from "./detect.js";
|
|
2
|
+
import { parseAnthropicRequest } from "./parse-anthropic.js";
|
|
3
|
+
import { parseOpenAiRequest } from "./parse-openai.js";
|
|
4
|
+
import { memoizedCounter } from "./token-counter.js";
|
|
5
|
+
import { JsonIntegrityError, readJson } from "./read-json.js";
|
|
6
|
+
import { readReportedUsage } from "./reported-usage.js";
|
|
7
|
+
import { ContextScopeParseError } from "./parse-error.js";
|
|
8
|
+
import { isOpenAiResponseObject, isResponsesBody } from "./openai-context.js";
|
|
9
|
+
export { ContextScopeParseError } from "./parse-error.js";
|
|
10
|
+
/** Splits raw input text into an array of request objects: a JSON array, a single JSON object, or JSONL (one JSON object per line, blank lines ignored). */
|
|
11
|
+
function splitRequests(input) {
|
|
12
|
+
const trimmed = input.trim();
|
|
13
|
+
if (trimmed.length === 0) {
|
|
14
|
+
throw new ContextScopeParseError("Input is empty.");
|
|
15
|
+
}
|
|
16
|
+
// Try whole-input JSON first (single object or array).
|
|
17
|
+
try {
|
|
18
|
+
const parsed = readJson(trimmed);
|
|
19
|
+
const values = Array.isArray(parsed) ? parsed : [parsed];
|
|
20
|
+
if (values.length === 0)
|
|
21
|
+
throw new ContextScopeParseError("The input array is empty: no requests to analyze.");
|
|
22
|
+
return { values, sources: values.map((_, recordIndex) => ({ recordIndex })), warnings: [], sourceRecords: values.length };
|
|
23
|
+
}
|
|
24
|
+
catch (err) {
|
|
25
|
+
if (err instanceof JsonIntegrityError)
|
|
26
|
+
throw new ContextScopeParseError(err.message);
|
|
27
|
+
if (err instanceof ContextScopeParseError)
|
|
28
|
+
throw err;
|
|
29
|
+
// Fall through to JSONL.
|
|
30
|
+
}
|
|
31
|
+
const lines = input.split("\n");
|
|
32
|
+
const values = [];
|
|
33
|
+
const sources = [];
|
|
34
|
+
const warnings = [];
|
|
35
|
+
let sourceRecords = 0;
|
|
36
|
+
lines.forEach((line, i) => {
|
|
37
|
+
const t = line.trim();
|
|
38
|
+
if (t.length === 0)
|
|
39
|
+
return;
|
|
40
|
+
const recordIndex = sourceRecords++;
|
|
41
|
+
try {
|
|
42
|
+
values.push(readJson(t));
|
|
43
|
+
sources.push({ recordIndex, line: i + 1 });
|
|
44
|
+
}
|
|
45
|
+
catch (err) {
|
|
46
|
+
if (err instanceof JsonIntegrityError)
|
|
47
|
+
throw new ContextScopeParseError(`Line ${i + 1}: ${err.message}`);
|
|
48
|
+
warnings.push({ sourceLine: i + 1, message: `Line ${i + 1}: could not parse as JSON. Skipped; analysis is incomplete.` });
|
|
49
|
+
}
|
|
50
|
+
});
|
|
51
|
+
if (values.length === 0) {
|
|
52
|
+
throw new ContextScopeParseError("No valid JSON objects found (input is neither valid JSON nor valid JSONL).");
|
|
53
|
+
}
|
|
54
|
+
return { values, sources, warnings, sourceRecords };
|
|
55
|
+
}
|
|
56
|
+
// Record fields that hold a request body in the batch-file and log formats people actually have:
|
|
57
|
+
// Anthropic Message Batches lines are {custom_id, params}, OpenAI Batch API lines are
|
|
58
|
+
// {custom_id, method, url, body}, and gateways/proxies commonly log {request: ...} or {request_body: ...}.
|
|
59
|
+
const ENVELOPE_FIELDS = ["params", "body", "request", "request_body"];
|
|
60
|
+
function isRecord(value) {
|
|
61
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
62
|
+
}
|
|
63
|
+
function looksLikeRequestBody(value) {
|
|
64
|
+
return isRecord(value) && !isOpenAiResponseObject(value) && (Array.isArray(value["messages"]) || isResponsesBody(value));
|
|
65
|
+
}
|
|
66
|
+
/** A capture can mix raw requests and different gateway wrappers; choose per record. */
|
|
67
|
+
function unwrapRecord(value, recordIndex) {
|
|
68
|
+
if (!isRecord(value))
|
|
69
|
+
return { value };
|
|
70
|
+
const candidates = ENVELOPE_FIELDS.map((field) => ({ envelope: field, value: unwrapField(value[field]) })).filter((candidate) => looksLikeRequestBody(candidate.value));
|
|
71
|
+
if (candidates.length > 1 || (looksLikeRequestBody(value) && candidates.length > 0)) {
|
|
72
|
+
throw new ContextScopeParseError(`Source record ${recordIndex + 1} has ambiguous request bodies. Keep one body or analyze each capture separately.`);
|
|
73
|
+
}
|
|
74
|
+
return candidates[0] ?? { value };
|
|
75
|
+
}
|
|
76
|
+
// Some gateways log the body as a JSON string rather than an object.
|
|
77
|
+
function unwrapField(value) {
|
|
78
|
+
if (typeof value !== "string")
|
|
79
|
+
return value;
|
|
80
|
+
try {
|
|
81
|
+
return readJson(value);
|
|
82
|
+
}
|
|
83
|
+
catch (err) {
|
|
84
|
+
if (err instanceof JsonIntegrityError)
|
|
85
|
+
throw new ContextScopeParseError(err.message);
|
|
86
|
+
return value;
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
/** "Request 2", "Requests 2-6", "Requests 2, 4 and 7": the requests one note is about. */
|
|
90
|
+
function requestList(indices) {
|
|
91
|
+
const numbers = indices.map((i) => i + 1);
|
|
92
|
+
if (numbers.length === 1)
|
|
93
|
+
return `Request ${numbers[0]}`;
|
|
94
|
+
const contiguous = numbers.every((n, k) => k === 0 || n === numbers[k - 1] + 1);
|
|
95
|
+
if (contiguous)
|
|
96
|
+
return `Requests ${numbers[0]}–${numbers[numbers.length - 1]}`;
|
|
97
|
+
const shown = numbers.slice(0, 6).join(", ");
|
|
98
|
+
return numbers.length > 6 ? `Requests ${shown} and ${numbers.length - 6} more` : `Requests ${shown}`;
|
|
99
|
+
}
|
|
100
|
+
/** History kept on OpenAI's servers cannot be recovered from the request body alone. */
|
|
101
|
+
function openAiStateWarnings(requests) {
|
|
102
|
+
const stored = [];
|
|
103
|
+
requests.forEach((request) => {
|
|
104
|
+
if (request.segments.some(s => s.unmodeledContext === "previous_response" || s.unmodeledContext === "conversation"))
|
|
105
|
+
stored.push(request.index);
|
|
106
|
+
});
|
|
107
|
+
const out = [];
|
|
108
|
+
if (stored.length > 0) {
|
|
109
|
+
const one = stored.length === 1;
|
|
110
|
+
out.push({
|
|
111
|
+
requestIndex: stored[0],
|
|
112
|
+
message: `${requestList(stored)} ${one ? "continues" : "continue"} a stored response or conversation (previous_response_id, conversation), so ${one ? "its" : "their"} earlier turns live on OpenAI's servers, not in this file. Visible segments retain their text counts; whole-request totals, context usage and sequence cache estimates are unavailable.`,
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
return out;
|
|
116
|
+
}
|
|
117
|
+
export function parseInput(input, formatOverride) {
|
|
118
|
+
const { values: rawValues, sources, warnings, sourceRecords } = splitRequests(input);
|
|
119
|
+
const records = rawValues.map((value, i) => unwrapRecord(value, sources[i].recordIndex));
|
|
120
|
+
const values = records.map((record) => record.value);
|
|
121
|
+
const envelope = records.every((record) => record.envelope === records[0].envelope) ? records[0].envelope : undefined;
|
|
122
|
+
const providers = values.map(detectProvider);
|
|
123
|
+
if (!formatOverride && new Set(providers.filter((provider) => provider !== undefined)).size > 1) {
|
|
124
|
+
throw new ContextScopeParseError("Mixed provider log contains both Anthropic and OpenAI requests. Split it by provider before analysis; their serialization and caching differ.");
|
|
125
|
+
}
|
|
126
|
+
const format = formatOverride ?? providers.find((provider) => provider !== undefined) ?? detectFormat(values[0]);
|
|
127
|
+
const parser = format === "openai" ? parseOpenAiRequest : parseAnthropicRequest;
|
|
128
|
+
const counter = memoizedCounter();
|
|
129
|
+
let complete = warnings.length === 0;
|
|
130
|
+
let skippedRecords = sourceRecords - values.length;
|
|
131
|
+
const requests = values.map((value, i) => {
|
|
132
|
+
const source = { ...sources[i], ...(records[i].envelope ? { envelope: records[i].envelope } : {}) };
|
|
133
|
+
if (providers[i] && providers[i] !== format) {
|
|
134
|
+
complete = false;
|
|
135
|
+
warnings.push({ requestIndex: i, ...(source.line ? { sourceLine: source.line } : {}), message: `Request ${i + 1} has ${providers[i]} provider evidence but the format override selects ${format}. Some content may not be analyzed; split the log by provider.` });
|
|
136
|
+
}
|
|
137
|
+
const reportedUsage = readReportedUsage(rawValues[i], records[i].envelope, format);
|
|
138
|
+
return { ...parser(value, i, counter), source, ...(reportedUsage ? { reportedUsage } : {}) };
|
|
139
|
+
});
|
|
140
|
+
if (format === "openai")
|
|
141
|
+
warnings.push(...openAiStateWarnings(requests));
|
|
142
|
+
requests.forEach((request, i) => {
|
|
143
|
+
if (request.segments.length === 0) {
|
|
144
|
+
complete = false;
|
|
145
|
+
skippedRecords++;
|
|
146
|
+
warnings.push({
|
|
147
|
+
requestIndex: i,
|
|
148
|
+
...(request.source.line ? { sourceLine: request.source.line } : {}),
|
|
149
|
+
message: `Request ${i + 1} has no tools, system prompt or messages - is it an API request body? (Response objects and usage records aren't analyzable.)`,
|
|
150
|
+
});
|
|
151
|
+
}
|
|
152
|
+
});
|
|
153
|
+
return {
|
|
154
|
+
format,
|
|
155
|
+
complete,
|
|
156
|
+
sourceRecords,
|
|
157
|
+
skippedRecords,
|
|
158
|
+
autoDetected: formatOverride === undefined,
|
|
159
|
+
envelope,
|
|
160
|
+
requests,
|
|
161
|
+
warnings,
|
|
162
|
+
};
|
|
163
|
+
}
|
|
164
|
+
//# sourceMappingURL=parse.js.map
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import type { ParsedRequest, PrefixMatch, PrefixRelation, Segment } from "./types.js";
|
|
2
|
+
/**
|
|
3
|
+
* A request's segments as keys, in the order they are compared: equal keys at equal positions are
|
|
4
|
+
* equal segments. Normalized, the keys are volatile-free and the leading tool definitions sorted.
|
|
5
|
+
*/
|
|
6
|
+
export declare function comparisonKeys(segments: Segment[], normalizeVolatile: boolean): string[];
|
|
7
|
+
/**
|
|
8
|
+
* `withDiff: false` skips the display diff - the optimized (volatile-normalized) scenario only needs the match length.
|
|
9
|
+
*
|
|
10
|
+
* A `new_conversation` is compared with its predecessor only as far as that request's setup
|
|
11
|
+
* (and whatever opening messages they happen to share): the rest of the other conversation was
|
|
12
|
+
* never this one's to re-send, and listing it as removed would bury the lines that matter.
|
|
13
|
+
*/
|
|
14
|
+
export declare function computePrefixMatch(from: ParsedRequest, to: ParsedRequest, normalizeVolatile?: boolean, withDiff?: boolean, relation?: PrefixRelation): PrefixMatch;
|
|
15
|
+
/**
|
|
16
|
+
* One match for each request that has an earlier request to be compared with. Without `threads`
|
|
17
|
+
* that is every request after the first, compared with the one before it, which is right for a
|
|
18
|
+
* file that holds a single conversation; `threadRequests` works out the pairs for any file.
|
|
19
|
+
*/
|
|
20
|
+
export declare function computeAllPrefixMatches(requests: ParsedRequest[], normalizeVolatile?: boolean, withDiff?: boolean, threads?: {
|
|
21
|
+
predecessor: (number | undefined)[];
|
|
22
|
+
relation: (PrefixRelation | undefined)[];
|
|
23
|
+
}): PrefixMatch[];
|
|
@@ -0,0 +1,290 @@
|
|
|
1
|
+
import { stripVolatilePatterns } from "./volatile.js";
|
|
2
|
+
import { blockJson, canonicalJson, normalizedBlockJson } from "./json-utils.js";
|
|
3
|
+
import { sumTokenCounts } from "./media-accounting.js";
|
|
4
|
+
// The optimized scenario compares each segment as if it were fixed: timestamps/UUIDs redacted and
|
|
5
|
+
// JSON keys sorted. That runs four regexes and a deep key sort per segment, and in a growing
|
|
6
|
+
// conversation every segment is compared against its counterpart in both neighbouring requests.
|
|
7
|
+
// Segments are immutable once parsed, so the normalized form is computed once per segment object.
|
|
8
|
+
const normalizedText = new WeakMap();
|
|
9
|
+
const literalText = new WeakMap();
|
|
10
|
+
/** Category plus prompt content/structure; constructed segments retain legacy text fallback. */
|
|
11
|
+
function segmentKey(segment, normalizeVolatile) {
|
|
12
|
+
const cache = normalizeVolatile ? normalizedText : literalText;
|
|
13
|
+
let text = cache.get(segment);
|
|
14
|
+
if (text === undefined) {
|
|
15
|
+
if (segment.unmodeledContext) {
|
|
16
|
+
// Opaque controls are identity, not volatile prompt text. Do not redact
|
|
17
|
+
// UUID-looking IDs or rewrite ciphertext in the optimized scenario.
|
|
18
|
+
text = JSON.stringify([segment.unmodeledContext, segment.prefix?.context, segment.prefix?.content ?? segment.raw]);
|
|
19
|
+
}
|
|
20
|
+
else if (segment.prefix) {
|
|
21
|
+
const context = normalizeVolatile ? canonicalJson(segment.prefix.context) : blockJson(segment.prefix.context);
|
|
22
|
+
const content = normalizeVolatile ? normalizedBlockJson(segment.prefix.content) : blockJson(segment.prefix.content);
|
|
23
|
+
text = JSON.stringify([context, content]);
|
|
24
|
+
}
|
|
25
|
+
else if (normalizeVolatile) {
|
|
26
|
+
text = segment.raw !== null && typeof segment.raw === "object" ? normalizedBlockJson(segment.raw) : stripVolatilePatterns(segment.text);
|
|
27
|
+
}
|
|
28
|
+
else
|
|
29
|
+
text = segment.unmodeledContent ? blockJson(segment.raw) : segment.text;
|
|
30
|
+
cache.set(segment, text);
|
|
31
|
+
}
|
|
32
|
+
return `${segment.category}::${text}`;
|
|
33
|
+
}
|
|
34
|
+
function sameSegment(a, b, normalizeVolatile) {
|
|
35
|
+
if (a.category !== b.category)
|
|
36
|
+
return false;
|
|
37
|
+
return segmentKey(a, normalizeVolatile) === segmentKey(b, normalizeVolatile);
|
|
38
|
+
}
|
|
39
|
+
/** Normalized mode also sorts the leading tool definitions, as a deterministic tool list would be. */
|
|
40
|
+
function inCanonicalOrder(segments) {
|
|
41
|
+
let toolCount = 0;
|
|
42
|
+
while (toolCount < segments.length && segments[toolCount].category === "tools")
|
|
43
|
+
toolCount++;
|
|
44
|
+
if (toolCount < 2)
|
|
45
|
+
return segments;
|
|
46
|
+
const tools = segments.slice(0, toolCount).sort((x, y) => {
|
|
47
|
+
const kx = segmentKey(x, true);
|
|
48
|
+
const ky = segmentKey(y, true);
|
|
49
|
+
return kx < ky ? -1 : kx > ky ? 1 : 0;
|
|
50
|
+
});
|
|
51
|
+
return [...tools, ...segments.slice(toolCount)];
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* A request's segments as keys, in the order they are compared: equal keys at equal positions are
|
|
55
|
+
* equal segments. Normalized, the keys are volatile-free and the leading tool definitions sorted.
|
|
56
|
+
*/
|
|
57
|
+
export function comparisonKeys(segments, normalizeVolatile) {
|
|
58
|
+
return (normalizeVolatile ? inCanonicalOrder(segments) : segments).map((segment) => segmentKey(segment, normalizeVolatile));
|
|
59
|
+
}
|
|
60
|
+
/** Length of the longest run of leading segments with identical prompt identities. */
|
|
61
|
+
function commonPrefixLength(a, b, normalizeVolatile) {
|
|
62
|
+
const left = normalizeVolatile ? inCanonicalOrder(a) : a;
|
|
63
|
+
const right = normalizeVolatile ? inCanonicalOrder(b) : b;
|
|
64
|
+
const n = Math.min(left.length, right.length);
|
|
65
|
+
let i = 0;
|
|
66
|
+
while (i < n && sameSegment(left[i], right[i], normalizeVolatile))
|
|
67
|
+
i++;
|
|
68
|
+
return i;
|
|
69
|
+
}
|
|
70
|
+
// Beyond this many edits between two consecutive requests a line-by-line diff stops being readable
|
|
71
|
+
// anyway (the requests are essentially unrelated), so the diff degrades to "old removed, new added".
|
|
72
|
+
const MAX_EDIT_DISTANCE = 2000;
|
|
73
|
+
/**
|
|
74
|
+
* Segment-level diff between two requests - what powers the "readable diff of
|
|
75
|
+
* what changed" view. It aligns matching segments anywhere, not just in the
|
|
76
|
+
* shared prefix, so a reordered tool or one edited system block shows up as a
|
|
77
|
+
* small, localized change rather than "everything after position 3 differs".
|
|
78
|
+
*
|
|
79
|
+
* Myers' O((N+M)·D) algorithm (E. W. Myers, "An O(ND) Difference Algorithm
|
|
80
|
+
* and Its Variations", Algorithmica 1, 1986) finds a shortest edit script,
|
|
81
|
+
* i.e. its unchanged lines form a longest common subsequence. D, the number
|
|
82
|
+
* of edits, is what matters: consecutive requests in an agent loop differ by a
|
|
83
|
+
* handful of appended turns and perhaps one changed block, so a 3,000-segment
|
|
84
|
+
* pair costs a few thousand steps instead of the nine million cells a classic
|
|
85
|
+
* LCS table would.
|
|
86
|
+
*/
|
|
87
|
+
function diffSegments(a, b) {
|
|
88
|
+
// Intern prompt identities to small integers for the diff's inner comparisons.
|
|
89
|
+
const ids = new Map();
|
|
90
|
+
let nextId = 0;
|
|
91
|
+
const intern = (s) => {
|
|
92
|
+
const key = segmentKey(s, false);
|
|
93
|
+
let id = ids.get(key);
|
|
94
|
+
if (id === undefined) {
|
|
95
|
+
id = nextId++;
|
|
96
|
+
ids.set(key, id);
|
|
97
|
+
}
|
|
98
|
+
return id;
|
|
99
|
+
};
|
|
100
|
+
const keysA = a.map(intern);
|
|
101
|
+
const keysB = b.map(intern);
|
|
102
|
+
const script = myers(keysA, keysB, MAX_EDIT_DISTANCE);
|
|
103
|
+
if (script)
|
|
104
|
+
return script.map(([type, index]) => ({ type, segment: type === "remove" ? a[index] : b[index] }));
|
|
105
|
+
const ops = [];
|
|
106
|
+
let head = 0;
|
|
107
|
+
while (head < a.length && head < b.length && keysA[head] === keysB[head])
|
|
108
|
+
ops.push({ type: "context", segment: b[head++] });
|
|
109
|
+
for (let i = head; i < a.length; i++)
|
|
110
|
+
ops.push({ type: "remove", segment: a[i] });
|
|
111
|
+
for (let j = head; j < b.length; j++)
|
|
112
|
+
ops.push({ type: "add", segment: b[j] });
|
|
113
|
+
return ops;
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* Shortest edit script from `a` to `b` as [op, index] pairs (index into `a` for
|
|
117
|
+
* removals, into `b` otherwise), or undefined if it needs more than `maxD` edits.
|
|
118
|
+
* The per-step snapshots only cover diagonals -d..d, so memory is O(D²).
|
|
119
|
+
*/
|
|
120
|
+
function myers(a, b, maxD) {
|
|
121
|
+
const n = a.length;
|
|
122
|
+
const m = b.length;
|
|
123
|
+
const max = n + m;
|
|
124
|
+
const offset = max + 1;
|
|
125
|
+
const v = new Int32Array(2 * max + 3);
|
|
126
|
+
const trace = [];
|
|
127
|
+
const limit = Math.min(max, maxD);
|
|
128
|
+
for (let d = 0; d <= limit; d++) {
|
|
129
|
+
// Snapshot of diagonals -(d+1)..(d+1) before this step; backtracking reads k±1 from it.
|
|
130
|
+
trace.push(v.slice(offset - d - 1, offset + d + 2));
|
|
131
|
+
for (let k = -d; k <= d; k += 2) {
|
|
132
|
+
const down = k === -d || (k !== d && v[offset + k - 1] < v[offset + k + 1]);
|
|
133
|
+
let x = down ? v[offset + k + 1] : v[offset + k - 1] + 1;
|
|
134
|
+
let y = x - k;
|
|
135
|
+
while (x < n && y < m && a[x] === b[y]) {
|
|
136
|
+
x++;
|
|
137
|
+
y++;
|
|
138
|
+
}
|
|
139
|
+
v[offset + k] = x;
|
|
140
|
+
if (x >= n && y >= m)
|
|
141
|
+
return backtrack(trace, n, m);
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
return undefined;
|
|
145
|
+
}
|
|
146
|
+
function backtrack(trace, n, m) {
|
|
147
|
+
const out = [];
|
|
148
|
+
let x = n;
|
|
149
|
+
let y = m;
|
|
150
|
+
for (let d = trace.length - 1; d >= 0; d--) {
|
|
151
|
+
const snap = trace[d];
|
|
152
|
+
const at = (k) => snap[k + d + 1];
|
|
153
|
+
const k = x - y;
|
|
154
|
+
const prevK = k === -d || (k !== d && at(k - 1) < at(k + 1)) ? k + 1 : k - 1;
|
|
155
|
+
const prevX = d === 0 ? 0 : at(prevK);
|
|
156
|
+
const prevY = d === 0 ? 0 : prevX - prevK;
|
|
157
|
+
while (x > prevX && y > prevY) {
|
|
158
|
+
out.push(["context", --y]);
|
|
159
|
+
x--;
|
|
160
|
+
}
|
|
161
|
+
if (d > 0) {
|
|
162
|
+
if (x === prevX)
|
|
163
|
+
out.push(["add", --y]);
|
|
164
|
+
else
|
|
165
|
+
out.push(["remove", --x]);
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
return out.reverse();
|
|
169
|
+
}
|
|
170
|
+
function describeSegment(segment) {
|
|
171
|
+
if (segment.unmodeledContext)
|
|
172
|
+
return `[${segment.category}] ${segment.label} — unresolved context; token count unavailable (inspect original unit)`;
|
|
173
|
+
if (segment.unmodeledContent)
|
|
174
|
+
return `[${segment.category}] ${segment.label} — media content; token count unavailable (inspect original block)`;
|
|
175
|
+
const preview = segment.text.length > 80 ? `${segment.text.slice(0, 80)}…` : segment.text;
|
|
176
|
+
return `[${segment.category}] ${segment.label} — ${preview.replace(/\s+/g, " ")}`;
|
|
177
|
+
}
|
|
178
|
+
/** Keeps context lines within `radius` of a change, like a unified diff, and renders only what is kept. */
|
|
179
|
+
function withContext(ops, radius = 2) {
|
|
180
|
+
const mediaKeys = new WeakMap();
|
|
181
|
+
const contentKey = (segment) => {
|
|
182
|
+
if (!segment.unmodeledContent && !segment.unmodeledContext)
|
|
183
|
+
return `${segment.category}::${segment.text}`;
|
|
184
|
+
let key = mediaKeys.get(segment);
|
|
185
|
+
if (key === undefined) {
|
|
186
|
+
key = `${segment.category}::${segment.unmodeledContext ?? "media"}::${blockJson(segment.prefix?.content ?? segment.raw)}`;
|
|
187
|
+
mediaKeys.set(segment, key);
|
|
188
|
+
}
|
|
189
|
+
return key;
|
|
190
|
+
};
|
|
191
|
+
const identities = (type) => {
|
|
192
|
+
const grouped = new Map();
|
|
193
|
+
for (const op of ops) {
|
|
194
|
+
if (op.type !== type)
|
|
195
|
+
continue;
|
|
196
|
+
const key = contentKey(op.segment);
|
|
197
|
+
const values = grouped.get(key) ?? new Set();
|
|
198
|
+
values.add(segmentKey(op.segment, false));
|
|
199
|
+
grouped.set(key, values);
|
|
200
|
+
}
|
|
201
|
+
return grouped;
|
|
202
|
+
};
|
|
203
|
+
const removed = identities("remove");
|
|
204
|
+
const added = identities("add");
|
|
205
|
+
const render = (op) => {
|
|
206
|
+
const key = contentKey(op.segment);
|
|
207
|
+
const other = (op.type === "remove" ? added : removed).get(key);
|
|
208
|
+
const structureChanged = op.type !== "context" && other !== undefined && (other.size > 1 || !other.has(segmentKey(op.segment, false)));
|
|
209
|
+
return { type: op.type, text: describeSegment(op.segment) + (structureChanged ? " [prompt metadata or message boundary changed]" : "") };
|
|
210
|
+
};
|
|
211
|
+
if (ops.length <= 60)
|
|
212
|
+
return ops.map(render); // small requests: show everything, no need to trim
|
|
213
|
+
const keep = new Array(ops.length).fill(false);
|
|
214
|
+
ops.forEach((op, idx) => {
|
|
215
|
+
if (op.type !== "context") {
|
|
216
|
+
for (let k = Math.max(0, idx - radius); k <= Math.min(ops.length - 1, idx + radius); k++)
|
|
217
|
+
keep[k] = true;
|
|
218
|
+
}
|
|
219
|
+
});
|
|
220
|
+
const out = [];
|
|
221
|
+
let skipped = 0;
|
|
222
|
+
ops.forEach((op, idx) => {
|
|
223
|
+
if (keep[idx]) {
|
|
224
|
+
if (skipped > 0) {
|
|
225
|
+
out.push({ type: "context", text: `⋯ ${skipped} unchanged segment${skipped === 1 ? "" : "s"} ⋯` });
|
|
226
|
+
skipped = 0;
|
|
227
|
+
}
|
|
228
|
+
out.push(render(op));
|
|
229
|
+
}
|
|
230
|
+
else {
|
|
231
|
+
skipped++;
|
|
232
|
+
}
|
|
233
|
+
});
|
|
234
|
+
if (skipped > 0)
|
|
235
|
+
out.push({ type: "context", text: `⋯ ${skipped} unchanged segment${skipped === 1 ? "" : "s"} ⋯` });
|
|
236
|
+
return out;
|
|
237
|
+
}
|
|
238
|
+
/** The leading tool definitions and system blocks: what a request sends before its conversation. */
|
|
239
|
+
function setupLength(segments) {
|
|
240
|
+
let n = 0;
|
|
241
|
+
while (n < segments.length && (segments[n].category === "tools" || segments[n].category === "system"))
|
|
242
|
+
n++;
|
|
243
|
+
return n;
|
|
244
|
+
}
|
|
245
|
+
/**
|
|
246
|
+
* `withDiff: false` skips the display diff - the optimized (volatile-normalized) scenario only needs the match length.
|
|
247
|
+
*
|
|
248
|
+
* A `new_conversation` is compared with its predecessor only as far as that request's setup
|
|
249
|
+
* (and whatever opening messages they happen to share): the rest of the other conversation was
|
|
250
|
+
* never this one's to re-send, and listing it as removed would bury the lines that matter.
|
|
251
|
+
*/
|
|
252
|
+
export function computePrefixMatch(from, to, normalizeVolatile = false, withDiff = true, relation = "continues") {
|
|
253
|
+
const matchedSegments = commonPrefixLength(from.segments, to.segments, normalizeVolatile);
|
|
254
|
+
const fromSegments = relation === "new_conversation" ? from.segments.slice(0, Math.max(setupLength(from.segments), matchedSegments)) : from.segments;
|
|
255
|
+
const matchedTo = to.segments.slice(0, matchedSegments);
|
|
256
|
+
const matchedOpenaiTokens = sumTokenCounts(matchedTo.map(s => s.openaiTokens));
|
|
257
|
+
const matchedClaudeTokensEstimate = sumTokenCounts(matchedTo.map(s => s.claudeTokensEstimate));
|
|
258
|
+
const fromDiverged = fromSegments[matchedSegments];
|
|
259
|
+
const toDiverged = to.segments[matchedSegments];
|
|
260
|
+
const divergedAt = matchedSegments < fromSegments.length || matchedSegments < to.segments.length
|
|
261
|
+
? { fromSegmentId: fromDiverged?.id, toSegmentId: toDiverged?.id }
|
|
262
|
+
: undefined;
|
|
263
|
+
const diff = withDiff ? withContext(diffSegments(fromSegments, to.segments)) : [];
|
|
264
|
+
return {
|
|
265
|
+
fromIndex: from.index,
|
|
266
|
+
toIndex: to.index,
|
|
267
|
+
relation,
|
|
268
|
+
matchedSegments,
|
|
269
|
+
matchedOpenaiTokens,
|
|
270
|
+
matchedClaudeTokensEstimate,
|
|
271
|
+
divergedAt,
|
|
272
|
+
diff,
|
|
273
|
+
};
|
|
274
|
+
}
|
|
275
|
+
/**
|
|
276
|
+
* One match for each request that has an earlier request to be compared with. Without `threads`
|
|
277
|
+
* that is every request after the first, compared with the one before it, which is right for a
|
|
278
|
+
* file that holds a single conversation; `threadRequests` works out the pairs for any file.
|
|
279
|
+
*/
|
|
280
|
+
export function computeAllPrefixMatches(requests, normalizeVolatile = false, withDiff = true, threads) {
|
|
281
|
+
const out = [];
|
|
282
|
+
for (let i = 1; i < requests.length; i++) {
|
|
283
|
+
const from = threads ? threads.predecessor[i] : i - 1;
|
|
284
|
+
if (from === undefined)
|
|
285
|
+
continue;
|
|
286
|
+
out.push(computePrefixMatch(requests[from], requests[i], normalizeVolatile, withDiff, threads?.relation[i] ?? "continues"));
|
|
287
|
+
}
|
|
288
|
+
return out;
|
|
289
|
+
}
|
|
290
|
+
//# sourceMappingURL=prefix.js.map
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
/** Browser presentation helpers without parsers or tokenizer data. Computation lives in a worker. */
|
|
2
|
+
export { ANTHROPIC_MODELS, OPENAI_MODELS } from "./pricing.js";
|
|
3
|
+
export { groupFindings, describeRequestIndices } from "./group-findings.js";
|
|
4
|
+
export { calibrationScale, calibrateRequest } from "./calibrate.js";
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
/** Browser presentation helpers without parsers or tokenizer data. Computation lives in a worker. */
|
|
2
|
+
export { ANTHROPIC_MODELS, OPENAI_MODELS } from "./pricing.js";
|
|
3
|
+
export { groupFindings, describeRequestIndices } from "./group-findings.js";
|
|
4
|
+
export { calibrationScale, calibrateRequest } from "./calibrate.js";
|
|
5
|
+
//# sourceMappingURL=presentation.js.map
|
|
@@ -0,0 +1,76 @@
|
|
|
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
|
+
import type { ResolvedModel } from "./types.js";
|
|
22
|
+
export interface AnthropicModelInfo {
|
|
23
|
+
id: string;
|
|
24
|
+
displayName: string;
|
|
25
|
+
contextWindow: number;
|
|
26
|
+
inputPricePerMTok: number;
|
|
27
|
+
outputPricePerMTok: number;
|
|
28
|
+
/** Cache read price as a fraction of `inputPricePerMTok`. */
|
|
29
|
+
cacheReadMultiplier: number;
|
|
30
|
+
/** Minimum prefix length (tokens) below which cache_control silently does not cache. */
|
|
31
|
+
minCacheableTokens: number;
|
|
32
|
+
/** Accepts `{role: "system"}` messages mid-conversation - the cache-safe place for per-request values. */
|
|
33
|
+
midConversationSystem: boolean;
|
|
34
|
+
}
|
|
35
|
+
export interface OpenAiModelInfo {
|
|
36
|
+
id: string;
|
|
37
|
+
displayName: string;
|
|
38
|
+
contextWindow: number;
|
|
39
|
+
inputPricePerMTok: number;
|
|
40
|
+
outputPricePerMTok: number;
|
|
41
|
+
cachedInputPricePerMTok: number;
|
|
42
|
+
cacheStyle: "legacy" | "breakpoints";
|
|
43
|
+
longContextInput?: {
|
|
44
|
+
aboveTokens: number;
|
|
45
|
+
multiplier: number;
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
export declare const ANTHROPIC_CACHE_WRITE_MULTIPLIER_5M = 1.25;
|
|
49
|
+
export declare const ANTHROPIC_CACHE_WRITE_MULTIPLIER_1H = 2;
|
|
50
|
+
export declare const ANTHROPIC_MAX_BREAKPOINTS = 4;
|
|
51
|
+
export declare const ANTHROPIC_LOOKBACK_POSITIONS = 20;
|
|
52
|
+
export declare const ANTHROPIC_MODELS: readonly AnthropicModelInfo[];
|
|
53
|
+
export declare const OPENAI_MODELS: readonly OpenAiModelInfo[];
|
|
54
|
+
export declare const DEFAULT_ANTHROPIC_MODEL = "claude-sonnet-5-5";
|
|
55
|
+
export declare const DEFAULT_OPENAI_MODEL = "gpt-6-sol";
|
|
56
|
+
/**
|
|
57
|
+
* Reduces the model ids real request logs carry to the canonical ids in the
|
|
58
|
+
* tables above: dated snapshots (`claude-haiku-4-5-20251001`), Amazon Bedrock
|
|
59
|
+
* ids (`anthropic.claude-opus-5-5`, `us.anthropic.claude-sonnet-5-v1:0`),
|
|
60
|
+
* Google Vertex AI snapshots (`claude-opus-4-5@20251101`), and OpenAI dated
|
|
61
|
+
* snapshots (`gpt-6-sol-2026-08-01`).
|
|
62
|
+
*/
|
|
63
|
+
export declare function normalizeModelId(id: string): string;
|
|
64
|
+
export declare function lookupAnthropicModel(id: string | undefined): AnthropicModelInfo | undefined;
|
|
65
|
+
export declare function lookupOpenAiModel(id: string | undefined): OpenAiModelInfo | undefined;
|
|
66
|
+
export declare function findAnthropicModel(id: string | undefined): AnthropicModelInfo;
|
|
67
|
+
export declare function findOpenAiModel(id: string | undefined): OpenAiModelInfo;
|
|
68
|
+
/**
|
|
69
|
+
* Resolves model metadata: an explicit option wins; otherwise
|
|
70
|
+
* the model named most often in the requests themselves; otherwise the
|
|
71
|
+
* provider default. An id with no pricing entry falls back to the default but
|
|
72
|
+
* is reported as `unrecognized`, so callers can say so instead of silently
|
|
73
|
+
* pricing an Opus log at Sonnet rates. Analysis calls this for each request;
|
|
74
|
+
* the most-common choice remains only as a compatibility summary.
|
|
75
|
+
*/
|
|
76
|
+
export declare function resolveModel(provider: "anthropic" | "openai", explicit: string | undefined, requestModels: (string | undefined)[]): ResolvedModel;
|