@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,189 @@
|
|
|
1
|
+
import { comparisonKeys } from "./prefix.js";
|
|
2
|
+
import { sameModel } from "./model-id.js";
|
|
3
|
+
/** Interns sequences of keys: a node id stands for everything up to and including one item. */
|
|
4
|
+
class PrefixTrie {
|
|
5
|
+
itemIds = new Map();
|
|
6
|
+
children = new Map();
|
|
7
|
+
nextNode = 1; // 0 is the empty prefix
|
|
8
|
+
item(key) {
|
|
9
|
+
let id = this.itemIds.get(key);
|
|
10
|
+
if (id === undefined) {
|
|
11
|
+
id = this.itemIds.size;
|
|
12
|
+
this.itemIds.set(key, id);
|
|
13
|
+
}
|
|
14
|
+
return id;
|
|
15
|
+
}
|
|
16
|
+
/** The node reached after each key in turn. Equal nodes at the same position mean equal prefixes. */
|
|
17
|
+
path(keys) {
|
|
18
|
+
const out = [];
|
|
19
|
+
let node = 0;
|
|
20
|
+
for (const key of keys) {
|
|
21
|
+
const item = this.item(key);
|
|
22
|
+
let next = this.children.get(node);
|
|
23
|
+
if (next === undefined) {
|
|
24
|
+
next = new Map();
|
|
25
|
+
this.children.set(node, next);
|
|
26
|
+
}
|
|
27
|
+
let child = next.get(item);
|
|
28
|
+
if (child === undefined) {
|
|
29
|
+
child = this.nextNode++;
|
|
30
|
+
next.set(item, child);
|
|
31
|
+
}
|
|
32
|
+
out.push(child);
|
|
33
|
+
node = child;
|
|
34
|
+
}
|
|
35
|
+
return out;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* For each request, the trie node of each of its leading runs of segments,
|
|
40
|
+
* in the order the provider serializes them. Two requests share their first
|
|
41
|
+
* `n` segments exactly when their paths agree at position `n - 1`. With
|
|
42
|
+
* `normalizeVolatile`, segments are compared as the optimized scenario
|
|
43
|
+
* compares them (see prefix.ts).
|
|
44
|
+
*/
|
|
45
|
+
export function prefixPaths(requests, normalizeVolatile) {
|
|
46
|
+
const trie = new PrefixTrie();
|
|
47
|
+
return requests.map((request) => trie.path(comparisonKeys(request.segments, normalizeVolatile)));
|
|
48
|
+
}
|
|
49
|
+
/** How many leading positions two paths share. Agreement is monotone, so this is a binary search. */
|
|
50
|
+
function sharedLength(a, b) {
|
|
51
|
+
let low = 0;
|
|
52
|
+
let high = Math.min(a.length, b.length);
|
|
53
|
+
while (low < high) {
|
|
54
|
+
const mid = (low + high + 1) >> 1;
|
|
55
|
+
if (a[mid - 1] === b[mid - 1])
|
|
56
|
+
low = mid;
|
|
57
|
+
else
|
|
58
|
+
high = mid - 1;
|
|
59
|
+
}
|
|
60
|
+
return low;
|
|
61
|
+
}
|
|
62
|
+
const isMessage = (category) => category !== "tools" && category !== "system";
|
|
63
|
+
/** How many earlier requests are looked at for a rewritten history, and for candidates that tie. */
|
|
64
|
+
const RECENT = 64;
|
|
65
|
+
/** The share of an earlier request's messages a request must re-send to count as rewriting it. */
|
|
66
|
+
const REWRITE_OVERLAP = 0.5;
|
|
67
|
+
export function threadRequests(requests, raw = prefixPaths(requests, false), normalized = prefixPaths(requests, true)) {
|
|
68
|
+
// Messages on their own: which conversation a request belongs to does not depend on its tools
|
|
69
|
+
// or system prompt, which are exactly what a cache-breaking request gets wrong.
|
|
70
|
+
const messageTrie = new PrefixTrie();
|
|
71
|
+
const messageKeys = requests.map((r) => comparisonKeys(r.segments.filter((s) => isMessage(s.category)), false));
|
|
72
|
+
const messageItems = messageKeys.map((keys) => keys.map((key) => messageTrie.item(key)));
|
|
73
|
+
const messagePaths = messageKeys.map((keys) => messageTrie.path(keys));
|
|
74
|
+
/** Requests whose message list ends exactly at a node, latest last. */
|
|
75
|
+
const endingAt = new Map();
|
|
76
|
+
const toolNames = requests.map((r) => r.segments.filter((s) => s.category === "tools").map((s) => s.label).join("\u0000"));
|
|
77
|
+
/** The latest request whose normalized path goes through each node, by node id. */
|
|
78
|
+
const latestThrough = [];
|
|
79
|
+
const predecessor = [];
|
|
80
|
+
const relation = [];
|
|
81
|
+
/** The best of `candidates` by: longest shared setup (normalized), same model, longest shared bytes, latest. */
|
|
82
|
+
const closest = (i, candidates) => {
|
|
83
|
+
let best;
|
|
84
|
+
let bestScore = [-1, -1, -1];
|
|
85
|
+
for (const j of candidates) {
|
|
86
|
+
const score = [
|
|
87
|
+
sharedLength(normalized[i], normalized[j]),
|
|
88
|
+
sameModel(requests[i].model, requests[j].model) ? 1 : 0,
|
|
89
|
+
sharedLength(raw[i], raw[j]),
|
|
90
|
+
];
|
|
91
|
+
const better = score[0] !== bestScore[0] ? score[0] > bestScore[0] : score[1] !== bestScore[1] ? score[1] > bestScore[1] : score[2] !== bestScore[2] ? score[2] > bestScore[2] : best === undefined || j > best;
|
|
92
|
+
if (better) {
|
|
93
|
+
best = j;
|
|
94
|
+
bestScore = score;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
return best;
|
|
98
|
+
};
|
|
99
|
+
for (let i = 0; i < requests.length; i++) {
|
|
100
|
+
const path = messagePaths[i];
|
|
101
|
+
let found;
|
|
102
|
+
let how;
|
|
103
|
+
// 1. The longest earlier message list this one starts with.
|
|
104
|
+
for (let length = path.length; length >= 1 && found === undefined; length--) {
|
|
105
|
+
const ending = endingAt.get(path[length - 1]);
|
|
106
|
+
if (ending && ending.length > 0) {
|
|
107
|
+
found = closest(i, ending.slice(-RECENT));
|
|
108
|
+
how = "continues";
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
// 2. A recent request most of whose messages are re-sent, though not as a prefix.
|
|
112
|
+
if (found === undefined && path.length > 0) {
|
|
113
|
+
const mine = new Set(messageItems[i]);
|
|
114
|
+
let bestOverlap = 0;
|
|
115
|
+
const tied = [];
|
|
116
|
+
for (let j = Math.max(0, i - RECENT); j < i; j++) {
|
|
117
|
+
const theirs = messageItems[j];
|
|
118
|
+
if (theirs.length === 0)
|
|
119
|
+
continue;
|
|
120
|
+
let shared = 0;
|
|
121
|
+
for (const item of theirs)
|
|
122
|
+
if (mine.has(item))
|
|
123
|
+
shared++;
|
|
124
|
+
const overlap = shared / theirs.length;
|
|
125
|
+
if (overlap < REWRITE_OVERLAP)
|
|
126
|
+
continue;
|
|
127
|
+
if (overlap > bestOverlap) {
|
|
128
|
+
bestOverlap = overlap;
|
|
129
|
+
tied.length = 0;
|
|
130
|
+
}
|
|
131
|
+
if (overlap === bestOverlap)
|
|
132
|
+
tied.push(j);
|
|
133
|
+
}
|
|
134
|
+
if (tied.length > 0) {
|
|
135
|
+
found = closest(i, tied);
|
|
136
|
+
how = "rewrites";
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
// 3. A new conversation on a setup already sent: the earlier request sharing the most of it.
|
|
140
|
+
if (found === undefined && i > 0) {
|
|
141
|
+
const mine = normalized[i];
|
|
142
|
+
// Whether an earlier request went through a node is monotone along the path.
|
|
143
|
+
let longest = 0;
|
|
144
|
+
let high = mine.length;
|
|
145
|
+
while (longest < high) {
|
|
146
|
+
const mid = (longest + high + 1) >> 1;
|
|
147
|
+
if (latestThrough[mine[mid - 1]] !== undefined)
|
|
148
|
+
longest = mid;
|
|
149
|
+
else
|
|
150
|
+
high = mid - 1;
|
|
151
|
+
}
|
|
152
|
+
if (longest > 0) {
|
|
153
|
+
const candidates = [latestThrough[mine[longest - 1]]];
|
|
154
|
+
for (let j = Math.max(0, i - RECENT); j < i; j++) {
|
|
155
|
+
if (j !== candidates[0] && sharedLength(mine, normalized[j]) === longest)
|
|
156
|
+
candidates.push(j);
|
|
157
|
+
}
|
|
158
|
+
found = closest(i, candidates);
|
|
159
|
+
how = "new_conversation";
|
|
160
|
+
}
|
|
161
|
+
else if (sameModel(requests[i - 1].model, requests[i].model) && toolNames[i - 1] === toolNames[i] && requests[i - 1].segments[0]?.category === requests[i].segments[0]?.category) {
|
|
162
|
+
// 4. Nothing shared, but the same model and tools as the line before: one application
|
|
163
|
+
// whose prefix changes from its first byte.
|
|
164
|
+
found = i - 1;
|
|
165
|
+
how = "new_conversation";
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
predecessor.push(found);
|
|
169
|
+
relation.push(how);
|
|
170
|
+
for (const node of normalized[i])
|
|
171
|
+
latestThrough[node] = i;
|
|
172
|
+
if (path.length > 0) {
|
|
173
|
+
const node = path[path.length - 1];
|
|
174
|
+
const list = endingAt.get(node);
|
|
175
|
+
if (list)
|
|
176
|
+
list.push(i);
|
|
177
|
+
else
|
|
178
|
+
endingAt.set(node, [i]);
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
const conversation = [];
|
|
182
|
+
let conversationCount = 0;
|
|
183
|
+
for (let i = 0; i < requests.length; i++) {
|
|
184
|
+
const from = predecessor[i];
|
|
185
|
+
conversation.push(from !== undefined && relation[i] !== "new_conversation" ? conversation[from] : conversationCount++);
|
|
186
|
+
}
|
|
187
|
+
return { predecessor, relation, conversation, conversationCount };
|
|
188
|
+
}
|
|
189
|
+
//# sourceMappingURL=threads.js.map
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
export interface TokenCounts {
|
|
2
|
+
openai: number;
|
|
3
|
+
claude: number;
|
|
4
|
+
}
|
|
5
|
+
export type TokenCounter = (text: string) => TokenCounts;
|
|
6
|
+
export declare const countTokens: TokenCounter;
|
|
7
|
+
/**
|
|
8
|
+
* A counter that tokenizes each distinct text once. An agent loop re-sends its
|
|
9
|
+
* whole history on every request, so a 24-turn session carries ~1,300 segments
|
|
10
|
+
* but only ~100 distinct ones; BPE-encoding each distinct text once is most of
|
|
11
|
+
* the parse time saved. Scoped to one parse so nothing outlives the input.
|
|
12
|
+
*/
|
|
13
|
+
export declare function memoizedCounter(): TokenCounter;
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { countOpenaiTokens } from "./tokenize-openai.js";
|
|
2
|
+
import { estimateClaudeTokens } from "./tokenize-claude.js";
|
|
3
|
+
export const countTokens = (text) => ({ openai: countOpenaiTokens(text), claude: estimateClaudeTokens(text) });
|
|
4
|
+
/**
|
|
5
|
+
* A counter that tokenizes each distinct text once. An agent loop re-sends its
|
|
6
|
+
* whole history on every request, so a 24-turn session carries ~1,300 segments
|
|
7
|
+
* but only ~100 distinct ones; BPE-encoding each distinct text once is most of
|
|
8
|
+
* the parse time saved. Scoped to one parse so nothing outlives the input.
|
|
9
|
+
*/
|
|
10
|
+
export function memoizedCounter() {
|
|
11
|
+
const cache = new Map();
|
|
12
|
+
return (text) => {
|
|
13
|
+
let counts = cache.get(text);
|
|
14
|
+
if (counts === undefined) {
|
|
15
|
+
counts = countTokens(text);
|
|
16
|
+
cache.set(text, counts);
|
|
17
|
+
}
|
|
18
|
+
return counts;
|
|
19
|
+
};
|
|
20
|
+
}
|
|
21
|
+
//# sourceMappingURL=token-counter.js.map
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Estimated token counts for Claude models.
|
|
3
|
+
*
|
|
4
|
+
* Anthropic does not publish Claude's tokenizer, so there is no exact,
|
|
5
|
+
* offline way to count Claude tokens - the only exact source is the
|
|
6
|
+
* `POST /v1/messages/count_tokens` API (see `calibrate.ts`). Every count this
|
|
7
|
+
* module produces is a heuristic estimate and MUST be labeled "≈" in any UI
|
|
8
|
+
* or report; never present it as exact.
|
|
9
|
+
*
|
|
10
|
+
* Method: a length-based estimate, characters-per-token, with the divisor
|
|
11
|
+
* adjusted by how "dense" the text is (ratio of non-alphanumeric,
|
|
12
|
+
* non-whitespace characters - punctuation, brackets, operators). Prose
|
|
13
|
+
* tokenizes at roughly 3.3 characters/token on the agent transcripts it was
|
|
14
|
+
* fitted to; code and JSON, which are punctuation-heavy, tokenize denser (BPE
|
|
15
|
+
* splits on symbol boundaries more often), about 2.5 characters/token.
|
|
16
|
+
* `calibrate.ts` lets a user with an API key replace it with real counts.
|
|
17
|
+
*/
|
|
18
|
+
export declare function estimateClaudeTokens(text: string): number;
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Estimated token counts for Claude models.
|
|
3
|
+
*
|
|
4
|
+
* Anthropic does not publish Claude's tokenizer, so there is no exact,
|
|
5
|
+
* offline way to count Claude tokens - the only exact source is the
|
|
6
|
+
* `POST /v1/messages/count_tokens` API (see `calibrate.ts`). Every count this
|
|
7
|
+
* module produces is a heuristic estimate and MUST be labeled "≈" in any UI
|
|
8
|
+
* or report; never present it as exact.
|
|
9
|
+
*
|
|
10
|
+
* Method: a length-based estimate, characters-per-token, with the divisor
|
|
11
|
+
* adjusted by how "dense" the text is (ratio of non-alphanumeric,
|
|
12
|
+
* non-whitespace characters - punctuation, brackets, operators). Prose
|
|
13
|
+
* tokenizes at roughly 3.3 characters/token on the agent transcripts it was
|
|
14
|
+
* fitted to; code and JSON, which are punctuation-heavy, tokenize denser (BPE
|
|
15
|
+
* splits on symbol boundaries more often), about 2.5 characters/token.
|
|
16
|
+
* `calibrate.ts` lets a user with an API key replace it with real counts.
|
|
17
|
+
*/
|
|
18
|
+
// Fitted to the input tokens Anthropic reported for 5,160 agent steps (coding-agent trajectories on
|
|
19
|
+
// Claude Sonnet 4.5, Opus 4.5, Haiku 4.5 and Opus 4.6, half of the trajectories held out); see
|
|
20
|
+
// studies/real-trajectories/README.md. The earlier 4.0 and 2.9 undercounted that content by 20-30%.
|
|
21
|
+
// These models share a tokenizer; Claude Opus 4.7 and later use a newer one that Anthropic documents
|
|
22
|
+
// as producing about 30% more tokens, which this estimate does not model.
|
|
23
|
+
const PROSE_CHARS_PER_TOKEN = 3.3;
|
|
24
|
+
const DENSE_CHARS_PER_TOKEN = 2.5;
|
|
25
|
+
const LETTER_OR_NUMBER = /[\p{L}\p{N}]/u;
|
|
26
|
+
/** Fraction of characters that are not a letter, digit, or plain space. */
|
|
27
|
+
function symbolDensity(text) {
|
|
28
|
+
if (text.length === 0)
|
|
29
|
+
return 0;
|
|
30
|
+
let symbolCount = 0;
|
|
31
|
+
for (const ch of text) {
|
|
32
|
+
const code = ch.charCodeAt(0);
|
|
33
|
+
// ASCII fast path; the Unicode property test only runs for non-ASCII characters.
|
|
34
|
+
if (code < 128) {
|
|
35
|
+
const isAlnumOrSpace = (code >= 48 && code <= 57) || (code >= 65 && code <= 90) || (code >= 97 && code <= 122) || code === 32;
|
|
36
|
+
if (!isAlnumOrSpace)
|
|
37
|
+
symbolCount++;
|
|
38
|
+
}
|
|
39
|
+
else if (!LETTER_OR_NUMBER.test(ch)) {
|
|
40
|
+
symbolCount++;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
return symbolCount / text.length;
|
|
44
|
+
}
|
|
45
|
+
export function estimateClaudeTokens(text) {
|
|
46
|
+
if (text.length === 0)
|
|
47
|
+
return 0;
|
|
48
|
+
const density = symbolDensity(text);
|
|
49
|
+
// Linearly interpolate the divisor between the prose and dense endpoints,
|
|
50
|
+
// using density 0.15 (typical English punctuation rate) as the "pure prose"
|
|
51
|
+
// anchor and 0.45+ (JSON/code) as the "pure dense" anchor.
|
|
52
|
+
const t = Math.min(1, Math.max(0, (density - 0.15) / (0.45 - 0.15)));
|
|
53
|
+
const charsPerToken = PROSE_CHARS_PER_TOKEN + t * (DENSE_CHARS_PER_TOKEN - PROSE_CHARS_PER_TOKEN);
|
|
54
|
+
return Math.max(1, Math.round(text.length / charsPerToken));
|
|
55
|
+
}
|
|
56
|
+
//# sourceMappingURL=tokenize-claude.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function countOpenaiTokens(text: string): number;
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Exact token counts via `gpt-tokenizer`, a pure-JS port of OpenAI's tiktoken.
|
|
3
|
+
* o200k_base is the encoding used by GPT-4o and newer OpenAI models; it is
|
|
4
|
+
* also our best available proxy for a "typical BPE tokenizer" and is what we
|
|
5
|
+
* calibrate the Claude estimate against in tests.
|
|
6
|
+
*/
|
|
7
|
+
import { encode } from "gpt-tokenizer/encoding/o200k_base";
|
|
8
|
+
export function countOpenaiTokens(text) {
|
|
9
|
+
if (text.length === 0)
|
|
10
|
+
return 0;
|
|
11
|
+
// Segments contain logged text, not a tokenizer control-token stream. Literal
|
|
12
|
+
// delimiter spellings must use ordinary BPE pieces (and must not throw).
|
|
13
|
+
return encode(text, { disallowedSpecial: new Set() }).length;
|
|
14
|
+
}
|
|
15
|
+
//# sourceMappingURL=tokenize-openai.js.map
|
|
@@ -0,0 +1,326 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Core data model shared by the parsers, the analyzers, the CLI and the web app.
|
|
3
|
+
*
|
|
4
|
+
* A single API request (Anthropic Messages or OpenAI Chat Completions) is
|
|
5
|
+
* normalized into a `ParsedRequest`: a flat, ordered list of `Segment`s in the
|
|
6
|
+
* provider's own serialization order. Every other analysis (token accounting,
|
|
7
|
+
* prefix diffing, cache simulation, duplicate detection, findings) operates on
|
|
8
|
+
* that normalized list, so the parsers are the only place that know about the
|
|
9
|
+
* two wire formats.
|
|
10
|
+
*/
|
|
11
|
+
export type Provider = "anthropic" | "openai";
|
|
12
|
+
/** Null means this content cannot be counted locally, never zero tokens. */
|
|
13
|
+
export type TokenCount = number | null;
|
|
14
|
+
export type MediaKind = "image" | "document" | "audio" | "file";
|
|
15
|
+
export type UnmodeledContextKind = "previous_response" | "conversation" | "prompt_template" | "item_reference" | "reasoning" | "compaction" | "mcp_tools";
|
|
16
|
+
/** Eight content categories plus unresolved references, which receive no treemap area. */
|
|
17
|
+
export type SegmentCategory = "system" | "tools" | "user" | "assistant" | "tool_call" | "tool_result" | "image" | "thinking" | "reference";
|
|
18
|
+
export type CacheTtl = "5m" | "1h";
|
|
19
|
+
export interface CacheControl {
|
|
20
|
+
type: "ephemeral";
|
|
21
|
+
ttl: CacheTtl;
|
|
22
|
+
/**
|
|
23
|
+
* Set when the block has no marker of its own: the request carries a top-level
|
|
24
|
+
* `cache_control` (Anthropic's automatic caching), which puts a breakpoint on the last
|
|
25
|
+
* cacheable block of the request, and this is that block.
|
|
26
|
+
*/
|
|
27
|
+
automatic?: true;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* One content block, tool definition, or system block, normalized into a
|
|
31
|
+
* single addressable unit. `text` is the analyzed content used for token counts
|
|
32
|
+
* and duplicate detection. Prompt structure is kept separately for prefix
|
|
33
|
+
* comparison; a tool result's destination or a message boundary can change
|
|
34
|
+
* while its analyzed text remains identical.
|
|
35
|
+
*/
|
|
36
|
+
export interface Segment {
|
|
37
|
+
/** Stable within one request, e.g. "tools[2]", "system[0]", "messages[3].content[1]". */
|
|
38
|
+
id: string;
|
|
39
|
+
category: SegmentCategory;
|
|
40
|
+
/** Short human label for the table/treemap, e.g. "tool: get_weather" or "message 4 (user) text". */
|
|
41
|
+
label: string;
|
|
42
|
+
/** Dot/bracket path into the original request JSON, for the inspector. */
|
|
43
|
+
path: string;
|
|
44
|
+
/** Analyzed textual content used for tokenizing and duplicate detection. */
|
|
45
|
+
text: string;
|
|
46
|
+
/** Full prompt block and its message header/boundary, separate from counted text.
|
|
47
|
+
* Optional for callers constructing segments directly; parsed segments include it. */
|
|
48
|
+
prefix?: {
|
|
49
|
+
content: unknown;
|
|
50
|
+
context?: unknown;
|
|
51
|
+
};
|
|
52
|
+
/** Original block, for the raw-content inspector view. */
|
|
53
|
+
raw: unknown;
|
|
54
|
+
/** Exact o200k_base text count; null for media or unresolved context. */
|
|
55
|
+
openaiTokens: TokenCount;
|
|
56
|
+
/** Estimated token count for Claude models - see tokenize-claude.ts. Always "≈", even when scaled by calibration. */
|
|
57
|
+
claudeTokensEstimate: TokenCount;
|
|
58
|
+
/** Media is preserved in raw/prefix, excluded from textual tokenization. */
|
|
59
|
+
unmodeledContent?: MediaKind[];
|
|
60
|
+
/** A reference/opaque unit cannot establish the provider's resolved prompt. */
|
|
61
|
+
unmodeledContext?: UnmodeledContextKind;
|
|
62
|
+
cacheControl?: CacheControl;
|
|
63
|
+
/** Explicit OpenAI content-block boundary; TTL comes from request options (30m). */
|
|
64
|
+
promptCacheBreakpoint?: true;
|
|
65
|
+
charLength: number;
|
|
66
|
+
}
|
|
67
|
+
export interface ParsedRequest {
|
|
68
|
+
provider: Provider;
|
|
69
|
+
/** Position in the input sequence (0-based). */
|
|
70
|
+
index: number;
|
|
71
|
+
model: string | undefined;
|
|
72
|
+
/** The original parsed JSON, kept for raw inspection and re-serialization. */
|
|
73
|
+
raw: unknown;
|
|
74
|
+
/** Original record position and, for JSONL, its physical line before any skips. */
|
|
75
|
+
source?: {
|
|
76
|
+
recordIndex: number;
|
|
77
|
+
line?: number;
|
|
78
|
+
envelope?: string;
|
|
79
|
+
};
|
|
80
|
+
/** Response usage paired with this request in the same source record; never inferred. */
|
|
81
|
+
reportedUsage?: ReportedUsage;
|
|
82
|
+
/** Segments in the provider's own render/serialization order (tools -> system -> messages for Anthropic). */
|
|
83
|
+
segments: Segment[];
|
|
84
|
+
}
|
|
85
|
+
export interface ParseWarning {
|
|
86
|
+
requestIndex?: number;
|
|
87
|
+
sourceLine?: number;
|
|
88
|
+
message: string;
|
|
89
|
+
}
|
|
90
|
+
export interface ParseResult {
|
|
91
|
+
format: Provider;
|
|
92
|
+
/** False when malformed lines, non-request records or a mismatched override leave gaps. */
|
|
93
|
+
complete: boolean;
|
|
94
|
+
/** Nonblank source records, including malformed JSONL lines. */
|
|
95
|
+
sourceRecords: number;
|
|
96
|
+
/** Malformed JSONL lines and records with no analyzable segments. */
|
|
97
|
+
skippedRecords: number;
|
|
98
|
+
/** True when the format was inferred rather than explicitly specified. */
|
|
99
|
+
autoDetected: boolean;
|
|
100
|
+
/**
|
|
101
|
+
* Set when the request bodies were unwrapped from a record field: `params`
|
|
102
|
+
* (Anthropic Message Batches), `body` (OpenAI Batch API), or `request` /
|
|
103
|
+
* `request_body` (common proxy and gateway log shapes).
|
|
104
|
+
*/
|
|
105
|
+
envelope?: string | undefined;
|
|
106
|
+
requests: ParsedRequest[];
|
|
107
|
+
warnings: ParseWarning[];
|
|
108
|
+
}
|
|
109
|
+
export interface TokenTotals {
|
|
110
|
+
/** Null when any included segment has an unavailable count. */
|
|
111
|
+
openaiTokens: TokenCount;
|
|
112
|
+
claudeTokensEstimate: TokenCount;
|
|
113
|
+
}
|
|
114
|
+
export interface CategoryBreakdown extends TokenTotals {
|
|
115
|
+
category: SegmentCategory;
|
|
116
|
+
segmentCount: number;
|
|
117
|
+
}
|
|
118
|
+
/** One rectangle in the treemap / one row in the segment table, for a single request. */
|
|
119
|
+
export interface RequestTokenReport {
|
|
120
|
+
requestIndex: number;
|
|
121
|
+
/** This request's pricing, cache rules and context window, including any explicit override or fallback. */
|
|
122
|
+
model: ResolvedModel;
|
|
123
|
+
totals: TokenTotals;
|
|
124
|
+
byCategory: CategoryBreakdown[];
|
|
125
|
+
segments: Segment[];
|
|
126
|
+
contextWindow: number | undefined;
|
|
127
|
+
percentOfContextWindow: number | undefined;
|
|
128
|
+
}
|
|
129
|
+
export type FindingSeverity = "info" | "warning" | "error";
|
|
130
|
+
export type FindingKind = "openai_unmodeled_context" | "anthropic_mcp_context" | "openai_mcp_context" | "unmodeled_media" | "anthropic_injected_prompt" | "anthropic_output_cache_scope" | "anthropic_citation_cache_scope" | "anthropic_reasoning_cache_scope" | "anthropic_message_cache_scope" | "anthropic_speed" | "anthropic_speed_cache_scope" | "openai_cache_disabled" | "openai_cache_boundary" | "volatile_prefix" | "tools_reordered" | "tool_schema_key_order" | "breakpoint_before_change" | "no_cache_control" | "below_minimum_cacheable" | "duplicate_content" | "lookback_window_exceeded"
|
|
131
|
+
/** Kept for consumers of older reports; invalid TTL ordering now raises a parse error. */
|
|
132
|
+
| "ttl_ordering" | "missing_tail_breakpoint" | "model_switch";
|
|
133
|
+
export interface Finding {
|
|
134
|
+
kind: FindingKind;
|
|
135
|
+
severity: FindingSeverity;
|
|
136
|
+
/** Request index this finding applies to (the later one, for pairwise findings). */
|
|
137
|
+
requestIndex: number;
|
|
138
|
+
title: string;
|
|
139
|
+
detail: string;
|
|
140
|
+
/** Segment ids implicated, for click-through highlighting. */
|
|
141
|
+
segmentIds: string[];
|
|
142
|
+
}
|
|
143
|
+
/**
|
|
144
|
+
* How a request relates to the earlier request it is compared with (see threads.ts):
|
|
145
|
+
* the next turn of the same conversation, the same conversation with its history
|
|
146
|
+
* edited, or a new conversation on a setup (tools and system prompt) sent before.
|
|
147
|
+
*/
|
|
148
|
+
export type PrefixRelation = "continues" | "rewrites" | "new_conversation";
|
|
149
|
+
/**
|
|
150
|
+
* Longest common prefix between a request and the earlier request it is compared
|
|
151
|
+
* with, in provider serialization order. In a file that holds one conversation
|
|
152
|
+
* that is the request before it; in general it is the request it continues.
|
|
153
|
+
*/
|
|
154
|
+
export interface PrefixMatch {
|
|
155
|
+
fromIndex: number;
|
|
156
|
+
toIndex: number;
|
|
157
|
+
relation: PrefixRelation;
|
|
158
|
+
/** Number of whole leading segments that are byte-identical (by normalized text). */
|
|
159
|
+
matchedSegments: number;
|
|
160
|
+
/** Token count (OpenAI exact) covered by the matched segments. */
|
|
161
|
+
matchedOpenaiTokens: TokenCount;
|
|
162
|
+
matchedClaudeTokensEstimate: TokenCount;
|
|
163
|
+
/** The first segment (in `to`) where the prefix diverges, if any. */
|
|
164
|
+
divergedAt: {
|
|
165
|
+
fromSegmentId: string | undefined;
|
|
166
|
+
toSegmentId: string | undefined;
|
|
167
|
+
} | undefined;
|
|
168
|
+
/** Unified-diff-style lines describing the divergent region, for display. */
|
|
169
|
+
diff: DiffLine[];
|
|
170
|
+
}
|
|
171
|
+
export interface DiffLine {
|
|
172
|
+
type: "context" | "add" | "remove";
|
|
173
|
+
text: string;
|
|
174
|
+
}
|
|
175
|
+
export interface CacheSimStep {
|
|
176
|
+
requestIndex: number;
|
|
177
|
+
/** Tokens read from cache this request (billed at the read discount). */
|
|
178
|
+
readTokens: TokenCount;
|
|
179
|
+
/** Tokens newly written to cache this request, split by TTL. */
|
|
180
|
+
writeTokens5m: TokenCount;
|
|
181
|
+
writeTokens1h: TokenCount;
|
|
182
|
+
/** Modern OpenAI cache writes. Absent for Anthropic and legacy OpenAI simulation. */
|
|
183
|
+
writeTokens30m?: TokenCount;
|
|
184
|
+
/** OpenAI caching regime actually modeled for this row. */
|
|
185
|
+
cacheMode?: "legacy" | "implicit" | "explicit";
|
|
186
|
+
/** Tokens that were neither read nor written (no cache_control covers them, or below minimum). */
|
|
187
|
+
uncachedTokens: TokenCount;
|
|
188
|
+
/** All token partitions are null when the sequence cannot be simulated. */
|
|
189
|
+
unavailableReason?: string;
|
|
190
|
+
/** Estimated cost in USD for the input side of this request, using the resolved pricing. */
|
|
191
|
+
costUsd: number | undefined;
|
|
192
|
+
/** Anthropic only; emitted for every row when any request specifies speed.
|
|
193
|
+
* Current modeled speed, including Opus 4.6 fallback; not observed response usage. */
|
|
194
|
+
speed?: "standard" | "fast" | "unrecognized";
|
|
195
|
+
/** Multiplier on the model's standard input rates; undefined when not priced. */
|
|
196
|
+
inputPriceMultiplier?: number | undefined;
|
|
197
|
+
}
|
|
198
|
+
/** Where the model used for pricing came from. */
|
|
199
|
+
export type ModelSource = "option" | "request" | "default";
|
|
200
|
+
export interface ResolvedModel {
|
|
201
|
+
/** Canonical id of the pricing entry actually used. */
|
|
202
|
+
id: string;
|
|
203
|
+
displayName: string;
|
|
204
|
+
source: ModelSource;
|
|
205
|
+
/** The id as given (by option or request) when it had no pricing entry and the default was used instead. */
|
|
206
|
+
unrecognized?: string;
|
|
207
|
+
}
|
|
208
|
+
export interface CacheSimulation {
|
|
209
|
+
provider: Provider;
|
|
210
|
+
/** Representative model retained for compatibility. Each reports[i].model governs its own row. */
|
|
211
|
+
model: string;
|
|
212
|
+
/** Simulation of requests as captured; these are not provider-reported measurements. */
|
|
213
|
+
actual: CacheSimStep[];
|
|
214
|
+
/** The same sequence with content normalized: volatile values (timestamps, UUIDs, epochs)
|
|
215
|
+
* normalized out of the prefix comparison, JSON keys and the tool list in a deterministic order,
|
|
216
|
+
* and - Anthropic only - a cache_control breakpoint on the last cacheable block. When all four
|
|
217
|
+
* slots are used, the last existing marker moves there, preserving its TTL. */
|
|
218
|
+
optimized: CacheSimStep[];
|
|
219
|
+
totalActualCostUsd: number | undefined;
|
|
220
|
+
totalOptimizedCostUsd: number | undefined;
|
|
221
|
+
unavailableReason?: string;
|
|
222
|
+
}
|
|
223
|
+
export interface UsageCounter {
|
|
224
|
+
/** Path in the source record, including its response/usage envelope. */
|
|
225
|
+
path: string;
|
|
226
|
+
status: "reported" | "missing" | "invalid";
|
|
227
|
+
/** Only valid, nonnegative safe integers are retained. No arbitrary response content. */
|
|
228
|
+
value?: number;
|
|
229
|
+
}
|
|
230
|
+
export interface ReportedUsage {
|
|
231
|
+
sources: string[];
|
|
232
|
+
schema: "openai-chat" | "openai-responses" | "anthropic" | "unknown";
|
|
233
|
+
/** Valid does not mean complete: each absent counter stays null. Invalid records are excluded. */
|
|
234
|
+
status: "valid" | "unavailable" | "invalid";
|
|
235
|
+
inputTokens: number | null;
|
|
236
|
+
cacheReadTokens: number | null;
|
|
237
|
+
cacheWriteTokens: number | null;
|
|
238
|
+
outputTokens: number | null;
|
|
239
|
+
counters: UsageCounter[];
|
|
240
|
+
issues: string[];
|
|
241
|
+
/** Reasons a valid capture still cannot support a particular normalized measurement. */
|
|
242
|
+
notes: string[];
|
|
243
|
+
}
|
|
244
|
+
export type UsageReadOutcome = "both_zero" | "both_positive" | "simulated_hit_reported_zero" | "reported_hit_simulated_zero" | "unavailable";
|
|
245
|
+
export interface UsageComparisonRow {
|
|
246
|
+
requestIndex: number;
|
|
247
|
+
estimatedInputTokens: TokenCount;
|
|
248
|
+
simulatedReadTokens: TokenCount;
|
|
249
|
+
reportedInputTokens: number | null;
|
|
250
|
+
reportedReadTokens: number | null;
|
|
251
|
+
reportedWriteTokens: number | null;
|
|
252
|
+
/** Estimate/simulation minus reported, over this request only. */
|
|
253
|
+
inputDeltaTokens: number | null;
|
|
254
|
+
readDeltaTokens: number | null;
|
|
255
|
+
readOutcome: UsageReadOutcome;
|
|
256
|
+
}
|
|
257
|
+
export interface UsageMetricComparison {
|
|
258
|
+
/** Both sides of this comparison contain exactly these requests. */
|
|
259
|
+
requestIndices: number[];
|
|
260
|
+
/** Null when there is no coverage or the aggregate exceeds the safe integer range. */
|
|
261
|
+
reportedTokens: number | null;
|
|
262
|
+
simulatedTokens: number | null;
|
|
263
|
+
deltaTokens: number | null;
|
|
264
|
+
}
|
|
265
|
+
export interface UsageComparison {
|
|
266
|
+
/** Only requests with analyzable segments; skipped source records are tracked by ParseResult. */
|
|
267
|
+
rows: UsageComparisonRow[];
|
|
268
|
+
capturedRequests: number;
|
|
269
|
+
/** Paired usage exists, but the request has no analyzable prompt segments. */
|
|
270
|
+
uncomparedRequestIndices: number[];
|
|
271
|
+
invalidRequestIndices: number[];
|
|
272
|
+
input: UsageMetricComparison;
|
|
273
|
+
cacheRead: UsageMetricComparison;
|
|
274
|
+
readOutcomes: Record<UsageReadOutcome, number>;
|
|
275
|
+
issues: string[];
|
|
276
|
+
}
|
|
277
|
+
export interface DuplicateGroup {
|
|
278
|
+
/** Short member-location signature for debugging, never used to prove identity. */
|
|
279
|
+
signature: string;
|
|
280
|
+
/** Matched segments within one request, in source order. */
|
|
281
|
+
members: {
|
|
282
|
+
requestIndex: number;
|
|
283
|
+
segmentId: string;
|
|
284
|
+
label: string;
|
|
285
|
+
tokens: number;
|
|
286
|
+
}[];
|
|
287
|
+
/** Exact means identical text; near means word-shingle similarity only. */
|
|
288
|
+
matchKind: "exact" | "near";
|
|
289
|
+
/** Minimum five-word-shingle Jaccard similarity across every pair of members. */
|
|
290
|
+
similarity: number;
|
|
291
|
+
/** Claude-estimated tokens in members after the first, not established removable tokens. */
|
|
292
|
+
estimatedReviewTokens: number;
|
|
293
|
+
}
|
|
294
|
+
export interface AnalysisOptions {
|
|
295
|
+
/** Explicit format override; omit or pass undefined to auto-detect. */
|
|
296
|
+
format?: Provider | undefined;
|
|
297
|
+
/** Override prices, cache thresholds and context windows for all requests.
|
|
298
|
+
* Captured model names still determine which cache entries can be shared. */
|
|
299
|
+
model?: string | undefined;
|
|
300
|
+
/**
|
|
301
|
+
* Multiplier applied to every Claude token estimate before analysis - the
|
|
302
|
+
* ratio of an exact `count_tokens` result to the heuristic estimate for the
|
|
303
|
+
* same request (see calibrate.ts). Omit (or pass 1) for raw estimates.
|
|
304
|
+
*/
|
|
305
|
+
claudeTokenScale?: number | undefined;
|
|
306
|
+
}
|
|
307
|
+
export interface AnalysisResult {
|
|
308
|
+
parse: ParseResult;
|
|
309
|
+
/** Representative model retained for compatibility (most frequent, or explicit override).
|
|
310
|
+
* Use reports[i].model for each request's actual pricing and cache rules. */
|
|
311
|
+
model: ResolvedModel;
|
|
312
|
+
/** The claudeTokenScale actually applied (1 when uncalibrated). */
|
|
313
|
+
claudeTokenScale: number;
|
|
314
|
+
reports: RequestTokenReport[];
|
|
315
|
+
/** One entry for each request that has an earlier request to be compared with, in request order. */
|
|
316
|
+
prefixMatches: PrefixMatch[];
|
|
317
|
+
/** The conversations found in the input: for each request, the number of its conversation, counted from 0. */
|
|
318
|
+
conversations: {
|
|
319
|
+
count: number;
|
|
320
|
+
byRequest: number[];
|
|
321
|
+
};
|
|
322
|
+
cacheSimulation: CacheSimulation;
|
|
323
|
+
usageComparison: UsageComparison;
|
|
324
|
+
findings: Finding[];
|
|
325
|
+
duplicates: DuplicateGroup[];
|
|
326
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Core data model shared by the parsers, the analyzers, the CLI and the web app.
|
|
3
|
+
*
|
|
4
|
+
* A single API request (Anthropic Messages or OpenAI Chat Completions) is
|
|
5
|
+
* normalized into a `ParsedRequest`: a flat, ordered list of `Segment`s in the
|
|
6
|
+
* provider's own serialization order. Every other analysis (token accounting,
|
|
7
|
+
* prefix diffing, cache simulation, duplicate detection, findings) operates on
|
|
8
|
+
* that normalized list, so the parsers are the only place that know about the
|
|
9
|
+
* two wire formats.
|
|
10
|
+
*/
|
|
11
|
+
export {};
|
|
12
|
+
//# sourceMappingURL=types.js.map
|