@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,284 @@
|
|
|
1
|
+
import { asText, blockJson, isRecord } from "./json-utils.js";
|
|
2
|
+
import { countTokens } from "./token-counter.js";
|
|
3
|
+
import { attachPromptIdentity } from "./prompt-identity.js";
|
|
4
|
+
import { isCacheableSegment, lastCacheableSegment } from "./anthropic-breakpoints.js";
|
|
5
|
+
import { ContextScopeParseError } from "./parse-error.js";
|
|
6
|
+
import { anthropicInjectedSettings } from "./anthropic-injected-settings.js";
|
|
7
|
+
import { unmodeledMedia } from "./media-accounting.js";
|
|
8
|
+
function readCacheControl(block, location) {
|
|
9
|
+
const cc = isRecord(block) ? block["cache_control"] : undefined;
|
|
10
|
+
if (cc === undefined || cc === null)
|
|
11
|
+
return undefined;
|
|
12
|
+
if (!isRecord(cc) || cc["type"] !== "ephemeral" || (cc.ttl !== undefined && cc.ttl !== "5m" && cc.ttl !== "1h")) {
|
|
13
|
+
throw new ContextScopeParseError(`${location}.cache_control must use type "ephemeral" and an omitted, "5m", or "1h" TTL. Correct the marker before simulating cache use.`);
|
|
14
|
+
}
|
|
15
|
+
const ttl = cc.ttl === "1h" ? "1h" : "5m";
|
|
16
|
+
return { type: "ephemeral", ttl };
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Automatic caching: a `cache_control` at the top level of the request, beside `model` and
|
|
20
|
+
* `messages`, "automatically applies a cache_control marker to the last cacheable block in
|
|
21
|
+
* the request" (the SDK's own description of the parameter). It is the one-line way to turn
|
|
22
|
+
* caching on, and it moves forward by itself as the conversation grows.
|
|
23
|
+
*
|
|
24
|
+
* The last cacheable block is the last block that could carry a marker of its own: thinking
|
|
25
|
+
* blocks can't, and an empty text block can't be cached. A block that already has a marker
|
|
26
|
+
* keeps it.
|
|
27
|
+
*/
|
|
28
|
+
function applyAutomaticBreakpoint(request, segments, location) {
|
|
29
|
+
const automatic = readCacheControl(request, location);
|
|
30
|
+
if (!automatic)
|
|
31
|
+
return;
|
|
32
|
+
const at = lastCacheableSegment(segments);
|
|
33
|
+
if (at < 0)
|
|
34
|
+
return;
|
|
35
|
+
const segment = segments[at];
|
|
36
|
+
if (segment.cacheControl && segment.cacheControl.ttl !== automatic.ttl) {
|
|
37
|
+
throw new ContextScopeParseError(`${location}: top-level cache_control and ${segment.path}.cache_control use different TTLs. Anthropic rejects this combination; use matching TTLs or remove one marker.`);
|
|
38
|
+
}
|
|
39
|
+
if (!segment.cacheControl)
|
|
40
|
+
segment.cacheControl = { ...automatic, automatic: true };
|
|
41
|
+
}
|
|
42
|
+
function validateBreakpoints(segments, location) {
|
|
43
|
+
const marked = segments.filter((s) => s.cacheControl);
|
|
44
|
+
if (marked.length > 4) {
|
|
45
|
+
throw new ContextScopeParseError(`${location}: ${marked.length} cache breakpoints exceed Anthropic's limit of 4, including automatic caching. Remove or move a marker before simulating cache use.`);
|
|
46
|
+
}
|
|
47
|
+
let seenShort = false;
|
|
48
|
+
for (const segment of marked) {
|
|
49
|
+
if (!isCacheableSegment(segment)) {
|
|
50
|
+
throw new ContextScopeParseError(`${location}: ${segment.path}.cache_control targets thinking or empty text, which cannot carry an explicit cache marker. Move the marker to a cacheable block.`);
|
|
51
|
+
}
|
|
52
|
+
if (segment.cacheControl.ttl === "5m")
|
|
53
|
+
seenShort = true;
|
|
54
|
+
else if (seenShort) {
|
|
55
|
+
throw new ContextScopeParseError(`${location}: ${segment.path}.cache_control uses "1h" after a "5m" breakpoint. Anthropic requires all 1-hour markers before 5-minute markers. Correct the order before simulating cache use.`);
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
function makeSegment(params, counter) {
|
|
60
|
+
const { cacheControl, ...rest } = params;
|
|
61
|
+
// `text` is whatever the log had in that position: a number or an object is kept as its JSON.
|
|
62
|
+
const media = unmodeledMedia(params.raw, "anthropic");
|
|
63
|
+
const unavailable = media.length > 0 || params.unmodeledContext !== undefined;
|
|
64
|
+
const text = unavailable ? "" : asText(params.text);
|
|
65
|
+
const counts = unavailable ? { openai: null, claude: null } : counter(text);
|
|
66
|
+
return {
|
|
67
|
+
...rest,
|
|
68
|
+
text,
|
|
69
|
+
charLength: text.length,
|
|
70
|
+
openaiTokens: counts.openai,
|
|
71
|
+
claudeTokensEstimate: counts.claude,
|
|
72
|
+
...(media.length ? { unmodeledContent: media } : {}),
|
|
73
|
+
...(cacheControl ? { cacheControl } : {}),
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
/** Mid-conversation `system` messages (supported on current Claude models) are operator text, not user text. */
|
|
77
|
+
function roleCategory(role) {
|
|
78
|
+
return role === "assistant" ? "assistant" : role === "system" ? "system" : "user";
|
|
79
|
+
}
|
|
80
|
+
/** Server-side and MCP tool blocks (`server_tool_use`, `web_search_tool_result`, `mcp_tool_use`...) are tool traffic too. */
|
|
81
|
+
function otherBlockCategory(type, role) {
|
|
82
|
+
if (type === "server_tool_use" || type === "mcp_tool_use")
|
|
83
|
+
return "tool_call";
|
|
84
|
+
if (typeof type === "string" && type.endsWith("_tool_result"))
|
|
85
|
+
return "tool_result";
|
|
86
|
+
return roleCategory(role);
|
|
87
|
+
}
|
|
88
|
+
/** Parses one Anthropic Messages API request body into provider-order segments: tools -> system -> messages. */
|
|
89
|
+
export function parseAnthropicRequest(raw, index, counter = countTokens) {
|
|
90
|
+
const seg = (params) => makeSegment(params, counter);
|
|
91
|
+
const location = `Request ${index + 1}`;
|
|
92
|
+
const obj = (raw !== null && typeof raw === "object" ? raw : {});
|
|
93
|
+
const segments = [];
|
|
94
|
+
anthropicInjectedSettings({ raw: obj, index });
|
|
95
|
+
// The connector resolves tool definitions and their prompt rendering on the
|
|
96
|
+
// provider side. A server URL is not those definitions. Retain connection
|
|
97
|
+
// identity too: two servers with the same toolset name can expose different
|
|
98
|
+
// tools. Pinned lists remain inspectable, but their MCP rendering is not
|
|
99
|
+
// implemented by this estimator either.
|
|
100
|
+
const servers = Array.isArray(obj["mcp_servers"]) ? obj["mcp_servers"] : [];
|
|
101
|
+
servers.forEach((server, i) => {
|
|
102
|
+
const path = `mcp_servers[${i}]`;
|
|
103
|
+
segments.push(seg({ id: path, category: "reference", label: `MCP server ${i + 1}`,
|
|
104
|
+
path, text: "", raw: server, unmodeledContext: "mcp_tools" }));
|
|
105
|
+
});
|
|
106
|
+
const tools = Array.isArray(obj["tools"]) ? obj["tools"] : [];
|
|
107
|
+
tools.forEach((tool, i) => {
|
|
108
|
+
const mcp = isRecord(tool) && tool.type === "mcp_toolset";
|
|
109
|
+
const name = isRecord(tool) && typeof tool["name"] === "string" ? tool["name"] : `tool_${i}`;
|
|
110
|
+
segments.push(seg({
|
|
111
|
+
id: `tools[${i}]`,
|
|
112
|
+
category: "tools",
|
|
113
|
+
label: mcp ? `MCP toolset ${i + 1}` : `tool: ${name}`,
|
|
114
|
+
path: `tools[${i}]`,
|
|
115
|
+
text: mcp ? "" : blockJson(tool),
|
|
116
|
+
raw: tool,
|
|
117
|
+
...(mcp ? { unmodeledContext: "mcp_tools" } : {}),
|
|
118
|
+
cacheControl: readCacheControl(tool, `${location}.tools[${i}]`),
|
|
119
|
+
}));
|
|
120
|
+
});
|
|
121
|
+
const system = obj["system"];
|
|
122
|
+
if (typeof system === "string") {
|
|
123
|
+
segments.push(seg({
|
|
124
|
+
id: "system[0]",
|
|
125
|
+
category: "system",
|
|
126
|
+
label: "system prompt",
|
|
127
|
+
path: "system",
|
|
128
|
+
text: system,
|
|
129
|
+
raw: system,
|
|
130
|
+
}));
|
|
131
|
+
}
|
|
132
|
+
else if (Array.isArray(system)) {
|
|
133
|
+
system.forEach((block, i) => {
|
|
134
|
+
segments.push(seg({
|
|
135
|
+
id: `system[${i}]`,
|
|
136
|
+
category: "system",
|
|
137
|
+
label: `system block ${i + 1}`,
|
|
138
|
+
path: `system[${i}]`,
|
|
139
|
+
text: isRecord(block) && typeof block["text"] === "string" ? block["text"] : blockJson(block),
|
|
140
|
+
raw: block,
|
|
141
|
+
cacheControl: readCacheControl(block, `${location}.system[${i}]`),
|
|
142
|
+
}));
|
|
143
|
+
});
|
|
144
|
+
}
|
|
145
|
+
else if (system !== undefined && system !== null) {
|
|
146
|
+
segments.push(seg({ id: "system", category: "system", label: "system prompt (malformed)", path: "system", text: blockJson(system), raw: system }));
|
|
147
|
+
}
|
|
148
|
+
const messages = Array.isArray(obj["messages"]) ? obj["messages"] : [];
|
|
149
|
+
messages.forEach((message, mi) => {
|
|
150
|
+
if (!isRecord(message)) {
|
|
151
|
+
// Not a message object at all (null, a bare string): kept whole, so later positions don't shift.
|
|
152
|
+
const path = `messages[${mi}]`;
|
|
153
|
+
segments.push(seg({ id: path, category: "user", label: `message ${mi + 1} (malformed)`, path, text: blockJson(message), raw: message }));
|
|
154
|
+
return;
|
|
155
|
+
}
|
|
156
|
+
const role = typeof message["role"] === "string" ? message["role"] : "user";
|
|
157
|
+
const content = message["content"];
|
|
158
|
+
const start = segments.length;
|
|
159
|
+
const blocks = typeof content === "string" ? [{ type: "text", text: content }] : Array.isArray(content) ? content : [];
|
|
160
|
+
if (content !== undefined && content !== null && typeof content !== "string" && !Array.isArray(content)) {
|
|
161
|
+
const path = `messages[${mi}].content`;
|
|
162
|
+
segments.push(seg({ id: path, category: roleCategory(role), label: `message ${mi + 1} (${role}) malformed content`, path, text: blockJson(content), raw: message }));
|
|
163
|
+
}
|
|
164
|
+
blocks.forEach((entry, bi) => {
|
|
165
|
+
const path = `messages[${mi}].content[${bi}]`;
|
|
166
|
+
const id = path;
|
|
167
|
+
if (!isRecord(entry)) {
|
|
168
|
+
segments.push(seg({ id, category: roleCategory(role), label: `message ${mi + 1} (${role}) malformed block`, path, text: blockJson(entry), raw: entry }));
|
|
169
|
+
return;
|
|
170
|
+
}
|
|
171
|
+
const block = entry;
|
|
172
|
+
const cacheControl = readCacheControl(block, `${location}.${path}`);
|
|
173
|
+
switch (block.type) {
|
|
174
|
+
case "mcp_tool_listing":
|
|
175
|
+
case "mcp_tool_use":
|
|
176
|
+
case "mcp_tool_result":
|
|
177
|
+
segments.push(seg({ id, category: "reference", label: `message ${mi + 1} ${block.type === "mcp_tool_listing" ? "MCP tool listing" : block.type}`,
|
|
178
|
+
path, text: "", raw: block, unmodeledContext: "mcp_tools", cacheControl }));
|
|
179
|
+
break;
|
|
180
|
+
case "text":
|
|
181
|
+
segments.push(seg({
|
|
182
|
+
id,
|
|
183
|
+
category: roleCategory(role),
|
|
184
|
+
label: `message ${mi + 1} (${role}) text`,
|
|
185
|
+
path: typeof content === "string" ? `messages[${mi}].content` : path,
|
|
186
|
+
text: asText(block.text ?? ""),
|
|
187
|
+
// A plain content string is not a text-block object in the source log.
|
|
188
|
+
raw: typeof content === "string" ? content : block,
|
|
189
|
+
cacheControl,
|
|
190
|
+
}));
|
|
191
|
+
break;
|
|
192
|
+
case "thinking":
|
|
193
|
+
case "redacted_thinking":
|
|
194
|
+
segments.push(seg({
|
|
195
|
+
id,
|
|
196
|
+
category: "thinking",
|
|
197
|
+
label: `message ${mi + 1} thinking`,
|
|
198
|
+
path,
|
|
199
|
+
text: typeof block["thinking"] === "string" ? block["thinking"] : "[redacted thinking]",
|
|
200
|
+
raw: block,
|
|
201
|
+
cacheControl,
|
|
202
|
+
}));
|
|
203
|
+
break;
|
|
204
|
+
case "tool_use":
|
|
205
|
+
segments.push(seg({
|
|
206
|
+
id,
|
|
207
|
+
category: "tool_call",
|
|
208
|
+
label: `message ${mi + 1} tool_use: ${String(block["name"] ?? "?")}`,
|
|
209
|
+
path,
|
|
210
|
+
text: blockJson(block),
|
|
211
|
+
raw: block,
|
|
212
|
+
cacheControl,
|
|
213
|
+
}));
|
|
214
|
+
break;
|
|
215
|
+
case "tool_result": {
|
|
216
|
+
const resultContent = block["content"];
|
|
217
|
+
const text = typeof resultContent === "string"
|
|
218
|
+
? resultContent
|
|
219
|
+
: Array.isArray(resultContent)
|
|
220
|
+
? resultContent
|
|
221
|
+
.map((c) => (isRecord(c) && typeof c["text"] === "string" ? c["text"] : blockJson(c)))
|
|
222
|
+
.join("\n")
|
|
223
|
+
: blockJson(resultContent);
|
|
224
|
+
segments.push(seg({
|
|
225
|
+
id,
|
|
226
|
+
category: "tool_result",
|
|
227
|
+
label: `message ${mi + 1} tool_result`,
|
|
228
|
+
path,
|
|
229
|
+
text,
|
|
230
|
+
raw: block,
|
|
231
|
+
cacheControl,
|
|
232
|
+
}));
|
|
233
|
+
break;
|
|
234
|
+
}
|
|
235
|
+
case "image":
|
|
236
|
+
segments.push(seg({
|
|
237
|
+
id,
|
|
238
|
+
category: "image",
|
|
239
|
+
label: `message ${mi + 1} image`,
|
|
240
|
+
path,
|
|
241
|
+
text: blockJson(block["source"] ?? block),
|
|
242
|
+
raw: block,
|
|
243
|
+
cacheControl,
|
|
244
|
+
}));
|
|
245
|
+
break;
|
|
246
|
+
case "document":
|
|
247
|
+
segments.push(seg({
|
|
248
|
+
id,
|
|
249
|
+
category: roleCategory(role),
|
|
250
|
+
label: `message ${mi + 1} document`,
|
|
251
|
+
path,
|
|
252
|
+
text: blockJson(block["source"] ?? block),
|
|
253
|
+
raw: block,
|
|
254
|
+
cacheControl,
|
|
255
|
+
}));
|
|
256
|
+
break;
|
|
257
|
+
default:
|
|
258
|
+
segments.push(seg({
|
|
259
|
+
id,
|
|
260
|
+
category: otherBlockCategory(block.type, role),
|
|
261
|
+
label: `message ${mi + 1} (${role}) ${typeof block.type === "string" ? block.type : "content"}`,
|
|
262
|
+
path,
|
|
263
|
+
text: blockJson(block),
|
|
264
|
+
raw: block,
|
|
265
|
+
cacheControl,
|
|
266
|
+
}));
|
|
267
|
+
}
|
|
268
|
+
});
|
|
269
|
+
// Empty effort-only system messages still alter the rendered history.
|
|
270
|
+
// Retain their header/boundary without inventing text tokens or a block
|
|
271
|
+
// eligible for a cache marker. This also preserves other empty roles.
|
|
272
|
+
if (segments.length === start && "content" in message) {
|
|
273
|
+
const path = `messages[${mi}].content`;
|
|
274
|
+
segments.push(seg({ id: path, category: roleCategory(role),
|
|
275
|
+
label: `message ${mi + 1} (${role}) empty content`, path, text: "", raw: message }));
|
|
276
|
+
}
|
|
277
|
+
});
|
|
278
|
+
attachPromptIdentity(obj, segments, "anthropic");
|
|
279
|
+
applyAutomaticBreakpoint(obj, segments, location);
|
|
280
|
+
validateBreakpoints(segments, location);
|
|
281
|
+
const model = typeof obj["model"] === "string" ? obj["model"] : undefined;
|
|
282
|
+
return { provider: "anthropic", index, model, raw, segments };
|
|
283
|
+
}
|
|
284
|
+
//# sourceMappingURL=parse-anthropic.js.map
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { ParsedRequest } from "./types.js";
|
|
2
|
+
import { type TokenCounter } from "./token-counter.js";
|
|
3
|
+
/**
|
|
4
|
+
* Parses one OpenAI request body into segments, ordered `tools -> messages`.
|
|
5
|
+
* Two shapes are understood: Chat Completions (`messages`; the
|
|
6
|
+
* system/developer message is simply `messages[0]`) and the Responses API
|
|
7
|
+
* (`instructions` + `input`, where `input` is a string or a list of message,
|
|
8
|
+
* function_call, function_call_output and reasoning items).
|
|
9
|
+
*/
|
|
10
|
+
export declare function parseOpenAiRequest(raw: unknown, index: number, counter?: TokenCounter): ParsedRequest;
|
|
@@ -0,0 +1,273 @@
|
|
|
1
|
+
import { asText, blockJson, isRecord } from "./json-utils.js";
|
|
2
|
+
import { countTokens } from "./token-counter.js";
|
|
3
|
+
import { attachPromptIdentity } from "./prompt-identity.js";
|
|
4
|
+
import { unmodeledMedia } from "./media-accounting.js";
|
|
5
|
+
import { isOpenAiResponseObject, isResponsesBody, openAiContextControls, openAiItemContext } from "./openai-context.js";
|
|
6
|
+
/**
|
|
7
|
+
* Tokens the Chat Completions format adds around each message (role, delimiters), which the
|
|
8
|
+
* message's text does not contain. Measured on 2,205 requests of gpt-5.1 and gpt-5.2 whose
|
|
9
|
+
* messages were all plain text: reported prompt_tokens equalled the o200k_base count of the
|
|
10
|
+
* contents plus exactly 5 per message, with no remainder in any request (see
|
|
11
|
+
* studies/real-trajectories/README.md). Not measured for messages with array content, tool calls
|
|
12
|
+
* or tool definitions, or for other models, so only plain-string messages get it.
|
|
13
|
+
*/
|
|
14
|
+
const CHAT_MESSAGE_FRAMING_TOKENS = 5;
|
|
15
|
+
function makeSegment(params, counter) {
|
|
16
|
+
// `text` is whatever the log had in that position: a number or an object is kept as its JSON.
|
|
17
|
+
const media = unmodeledMedia(params.raw, "openai");
|
|
18
|
+
const unavailable = media.length > 0 || params.unmodeledContext !== undefined;
|
|
19
|
+
const text = unavailable ? "" : asText(params.text);
|
|
20
|
+
const counts = unavailable ? { openai: null, claude: null } : counter(text);
|
|
21
|
+
return {
|
|
22
|
+
...params,
|
|
23
|
+
text,
|
|
24
|
+
charLength: text.length,
|
|
25
|
+
openaiTokens: counts.openai,
|
|
26
|
+
claudeTokensEstimate: counts.claude,
|
|
27
|
+
...(media.length ? { unmodeledContent: media } : {}),
|
|
28
|
+
...(isRecord(params.raw) && isRecord(params.raw["prompt_cache_breakpoint"]) && params.raw["prompt_cache_breakpoint"].mode === "explicit" ? { promptCacheBreakpoint: true } : {}),
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Parses one OpenAI request body into segments, ordered `tools -> messages`.
|
|
33
|
+
* Two shapes are understood: Chat Completions (`messages`; the
|
|
34
|
+
* system/developer message is simply `messages[0]`) and the Responses API
|
|
35
|
+
* (`instructions` + `input`, where `input` is a string or a list of message,
|
|
36
|
+
* function_call, function_call_output and reasoning items).
|
|
37
|
+
*/
|
|
38
|
+
export function parseOpenAiRequest(raw, index, counter = countTokens) {
|
|
39
|
+
const seg = (params) => makeSegment(params, counter);
|
|
40
|
+
const obj = (raw !== null && typeof raw === "object" ? raw : {});
|
|
41
|
+
const segments = [];
|
|
42
|
+
const model = typeof obj["model"] === "string" ? obj["model"] : undefined;
|
|
43
|
+
if (isOpenAiResponseObject(obj))
|
|
44
|
+
return { provider: "openai", index, model, raw, segments };
|
|
45
|
+
const tools = Array.isArray(obj["tools"]) ? obj["tools"] : [];
|
|
46
|
+
tools.forEach((entry, i) => {
|
|
47
|
+
const tool = isRecord(entry) ? entry : {};
|
|
48
|
+
const mcp = tool.type === "mcp";
|
|
49
|
+
// Chat Completions nests the definition under `function`; the Responses API flattens it.
|
|
50
|
+
const fn = isRecord(tool["function"]) ? tool["function"] : tool;
|
|
51
|
+
const name = typeof fn["name"] === "string" ? fn["name"] : typeof tool["type"] === "string" ? tool["type"] : `tool_${i}`;
|
|
52
|
+
segments.push(seg({
|
|
53
|
+
id: `tools[${i}]`,
|
|
54
|
+
category: "tools",
|
|
55
|
+
label: mcp ? `MCP server ${i + 1}` : `tool: ${name}`,
|
|
56
|
+
path: `tools[${i}]`,
|
|
57
|
+
text: mcp ? "" : blockJson(entry),
|
|
58
|
+
raw: entry,
|
|
59
|
+
...(mcp ? { unmodeledContext: "mcp_tools" } : {}),
|
|
60
|
+
}));
|
|
61
|
+
});
|
|
62
|
+
if (isResponsesBody(obj)) {
|
|
63
|
+
segments.push(...parseResponsesBody(obj, seg, index));
|
|
64
|
+
attachPromptIdentity(obj, segments, "openai");
|
|
65
|
+
return { provider: "openai", index, model, raw, segments };
|
|
66
|
+
}
|
|
67
|
+
const messages = Array.isArray(obj["messages"]) ? obj["messages"] : [];
|
|
68
|
+
messages.forEach((message, mi) => {
|
|
69
|
+
if (!isRecord(message)) {
|
|
70
|
+
// Not a message object at all (null, a bare string): kept whole, so later positions don't shift.
|
|
71
|
+
const path = `messages[${mi}]`;
|
|
72
|
+
segments.push(seg({ id: path, category: "user", label: `message ${mi + 1} (malformed)`, path, text: blockJson(message), raw: message }));
|
|
73
|
+
return;
|
|
74
|
+
}
|
|
75
|
+
const role = typeof message["role"] === "string" ? message["role"] : "user";
|
|
76
|
+
const category = roleCategory(role);
|
|
77
|
+
const content = message["content"];
|
|
78
|
+
const start = segments.length;
|
|
79
|
+
if (typeof content === "string" || content === undefined || content === null) {
|
|
80
|
+
if (typeof content === "string") {
|
|
81
|
+
const segment = seg({
|
|
82
|
+
id: `messages[${mi}].content`,
|
|
83
|
+
category,
|
|
84
|
+
label: `message ${mi + 1} (${role}) text`,
|
|
85
|
+
path: `messages[${mi}].content`,
|
|
86
|
+
text: content,
|
|
87
|
+
raw: message,
|
|
88
|
+
});
|
|
89
|
+
if (segment.openaiTokens !== null)
|
|
90
|
+
segment.openaiTokens += CHAT_MESSAGE_FRAMING_TOKENS;
|
|
91
|
+
segments.push(segment);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
else if (Array.isArray(content)) {
|
|
95
|
+
content.forEach((entry, pi) => {
|
|
96
|
+
const path = `messages[${mi}].content[${pi}]`;
|
|
97
|
+
if (!isRecord(entry)) {
|
|
98
|
+
segments.push(seg({ id: path, category, label: `message ${mi + 1} (${role}) malformed part`, path, text: blockJson(entry), raw: entry }));
|
|
99
|
+
return;
|
|
100
|
+
}
|
|
101
|
+
const part = entry;
|
|
102
|
+
if (part.type === "text") {
|
|
103
|
+
segments.push(seg({ id: path, category, label: `message ${mi + 1} (${role}) text`, path, text: asText(part.text ?? ""), raw: part }));
|
|
104
|
+
}
|
|
105
|
+
else if (part.type === "refusal" && typeof part.refusal === "string") {
|
|
106
|
+
segments.push(seg({ id: path, category, label: `message ${mi + 1} (${role}) refusal`, path, text: part.refusal, raw: part }));
|
|
107
|
+
}
|
|
108
|
+
else if (part.type === "image_url") {
|
|
109
|
+
segments.push(seg({ id: path, category: "image", label: `message ${mi + 1} image`, path, text: blockJson(part.image_url), raw: part }));
|
|
110
|
+
}
|
|
111
|
+
else {
|
|
112
|
+
segments.push(seg({ id: path, category, label: `message ${mi + 1} (${role}) ${typeof part.type === "string" ? part.type : "content"}`, path, text: blockJson(part), raw: part }));
|
|
113
|
+
}
|
|
114
|
+
});
|
|
115
|
+
}
|
|
116
|
+
else {
|
|
117
|
+
// A number or an object where the content should be: still part of what was sent.
|
|
118
|
+
const path = `messages[${mi}].content`;
|
|
119
|
+
segments.push(seg({ id: path, category, label: `message ${mi + 1} (${role}) malformed content`, path, text: blockJson(content), raw: message }));
|
|
120
|
+
}
|
|
121
|
+
const refusal = message["refusal"];
|
|
122
|
+
if (refusal !== undefined && refusal !== null) {
|
|
123
|
+
const path = `messages[${mi}].refusal`;
|
|
124
|
+
segments.push(seg({ id: path, category, label: `message ${mi + 1} (${role}) refusal`, path, text: asText(refusal), raw: message }));
|
|
125
|
+
}
|
|
126
|
+
// assistant tool calls
|
|
127
|
+
const toolCalls = Array.isArray(message["tool_calls"]) ? message["tool_calls"] : [];
|
|
128
|
+
toolCalls.forEach((call, ci) => {
|
|
129
|
+
const fn = isRecord(call) && isRecord(call["function"]) ? call["function"] : {};
|
|
130
|
+
const path = `messages[${mi}].tool_calls[${ci}]`;
|
|
131
|
+
segments.push(seg({
|
|
132
|
+
id: path,
|
|
133
|
+
category: "tool_call",
|
|
134
|
+
label: `message ${mi + 1} tool_call: ${String(fn["name"] ?? "?")}`,
|
|
135
|
+
path,
|
|
136
|
+
text: blockJson(call),
|
|
137
|
+
raw: call,
|
|
138
|
+
}));
|
|
139
|
+
});
|
|
140
|
+
// legacy function_call (pre tool_calls)
|
|
141
|
+
if (message["function_call"] !== undefined && message["function_call"] !== null) {
|
|
142
|
+
const path = `messages[${mi}].function_call`;
|
|
143
|
+
segments.push(seg({
|
|
144
|
+
id: path,
|
|
145
|
+
category: "tool_call",
|
|
146
|
+
label: `message ${mi + 1} function_call`,
|
|
147
|
+
path,
|
|
148
|
+
text: blockJson(message["function_call"]),
|
|
149
|
+
raw: message["function_call"],
|
|
150
|
+
}));
|
|
151
|
+
}
|
|
152
|
+
// An empty/null content record still carries role and participant identity.
|
|
153
|
+
// Keep a zero-text unit when no text or call represented this message;
|
|
154
|
+
// dropping it would make later history reusable across a changed boundary.
|
|
155
|
+
if (segments.length === start && "content" in message) {
|
|
156
|
+
const path = `messages[${mi}].content`;
|
|
157
|
+
segments.push(seg({ id: path, category, label: `message ${mi + 1} (${role}) empty content`, path, text: "", raw: message }));
|
|
158
|
+
}
|
|
159
|
+
});
|
|
160
|
+
attachPromptIdentity(obj, segments, "openai");
|
|
161
|
+
return { provider: "openai", index, model, raw, segments };
|
|
162
|
+
}
|
|
163
|
+
function roleCategory(role) {
|
|
164
|
+
return role === "system" || role === "developer" ? "system" : role === "assistant" ? "assistant" : role === "tool" ? "tool_result" : "user";
|
|
165
|
+
}
|
|
166
|
+
/** Responses API: `instructions` then each `input` item, in order. */
|
|
167
|
+
function parseResponsesBody(obj, seg, index) {
|
|
168
|
+
const segments = [];
|
|
169
|
+
for (const control of openAiContextControls(obj, index)) {
|
|
170
|
+
segments.push(seg({ id: control.path, category: "reference", label: control.label, path: control.path,
|
|
171
|
+
text: "", raw: control.raw, unmodeledContext: control.kind }));
|
|
172
|
+
}
|
|
173
|
+
if (typeof obj["instructions"] === "string") {
|
|
174
|
+
segments.push(seg({ id: "instructions", category: "system", label: "instructions", path: "instructions", text: obj["instructions"], raw: obj["instructions"] }));
|
|
175
|
+
}
|
|
176
|
+
else if (obj["instructions"] !== undefined && obj["instructions"] !== null && typeof obj["instructions"] !== "string") {
|
|
177
|
+
segments.push(seg({ id: "instructions", category: "system", label: "instructions (malformed)", path: "instructions", text: blockJson(obj["instructions"]), raw: obj["instructions"] }));
|
|
178
|
+
}
|
|
179
|
+
const input = obj["input"];
|
|
180
|
+
if (typeof input === "string") {
|
|
181
|
+
segments.push(seg({ id: "input", category: "user", label: "input (user) text", path: "input", text: input, raw: input }));
|
|
182
|
+
return segments;
|
|
183
|
+
}
|
|
184
|
+
if (!Array.isArray(input)) {
|
|
185
|
+
if (input !== undefined && input !== null)
|
|
186
|
+
segments.push(seg({ id: "input", category: "user", label: "input (malformed)", path: "input", text: blockJson(input), raw: input }));
|
|
187
|
+
return segments;
|
|
188
|
+
}
|
|
189
|
+
input.forEach((item, ii) => {
|
|
190
|
+
const path = `input[${ii}]`;
|
|
191
|
+
if (!isRecord(item)) {
|
|
192
|
+
// Not an item object (null, a bare string): kept whole, so later positions don't shift.
|
|
193
|
+
segments.push(seg({ id: path, category: "user", label: `item ${ii + 1} (malformed)`, path, text: blockJson(item), raw: item }));
|
|
194
|
+
return;
|
|
195
|
+
}
|
|
196
|
+
const unresolved = openAiItemContext(item, path, index);
|
|
197
|
+
if (unresolved) {
|
|
198
|
+
segments.push(seg({ id: path, category: unresolved === "reasoning" ? "thinking" : "reference",
|
|
199
|
+
label: `item ${ii + 1} unresolved ${unresolved}`, path, text: "", raw: item, unmodeledContext: unresolved }));
|
|
200
|
+
return;
|
|
201
|
+
}
|
|
202
|
+
const type = typeof item["type"] === "string" ? item["type"] : "message";
|
|
203
|
+
switch (type) {
|
|
204
|
+
case "message": {
|
|
205
|
+
const role = typeof item["role"] === "string" ? item["role"] : "user";
|
|
206
|
+
const category = roleCategory(role);
|
|
207
|
+
const content = item["content"];
|
|
208
|
+
const start = segments.length;
|
|
209
|
+
if (typeof content === "string") {
|
|
210
|
+
segments.push(seg({ id: path, category, label: `item ${ii + 1} (${role}) text`, path: `${path}.content`, text: content, raw: item }));
|
|
211
|
+
}
|
|
212
|
+
else if (Array.isArray(content)) {
|
|
213
|
+
content.forEach((entry, pi) => {
|
|
214
|
+
const partPath = `${path}.content[${pi}]`;
|
|
215
|
+
if (!isRecord(entry)) {
|
|
216
|
+
segments.push(seg({ id: partPath, category, label: `item ${ii + 1} (${role}) malformed part`, path: partPath, text: blockJson(entry), raw: entry }));
|
|
217
|
+
return;
|
|
218
|
+
}
|
|
219
|
+
const part = entry;
|
|
220
|
+
const partType = typeof part.type === "string" ? part.type : "content";
|
|
221
|
+
if ((partType === "input_text" || partType === "output_text" || partType === "text") && typeof part.text === "string") {
|
|
222
|
+
segments.push(seg({ id: partPath, category, label: `item ${ii + 1} (${role}) text`, path: partPath, text: part.text, raw: part }));
|
|
223
|
+
}
|
|
224
|
+
else if (partType === "refusal" && typeof part.refusal === "string") {
|
|
225
|
+
segments.push(seg({ id: partPath, category, label: `item ${ii + 1} (${role}) refusal`, path: partPath, text: part.refusal, raw: part }));
|
|
226
|
+
}
|
|
227
|
+
else if (partType === "input_image") {
|
|
228
|
+
segments.push(seg({ id: partPath, category: "image", label: `item ${ii + 1} image`, path: partPath, text: blockJson(part), raw: part }));
|
|
229
|
+
}
|
|
230
|
+
else {
|
|
231
|
+
segments.push(seg({ id: partPath, category, label: `item ${ii + 1} (${role}) ${partType}`, path: partPath, text: blockJson(part), raw: part }));
|
|
232
|
+
}
|
|
233
|
+
});
|
|
234
|
+
}
|
|
235
|
+
else if (content !== undefined && content !== null) {
|
|
236
|
+
segments.push(seg({ id: path, category, label: `item ${ii + 1} (${role}) malformed content`, path: `${path}.content`, text: blockJson(content), raw: item }));
|
|
237
|
+
}
|
|
238
|
+
if (segments.length === start && "content" in item) {
|
|
239
|
+
segments.push(seg({ id: path, category, label: `item ${ii + 1} (${role}) empty content`, path: `${path}.content`, text: "", raw: item }));
|
|
240
|
+
}
|
|
241
|
+
break;
|
|
242
|
+
}
|
|
243
|
+
case "function_call":
|
|
244
|
+
segments.push(seg({ id: path, category: "tool_call", label: `item ${ii + 1} function_call: ${String(item["name"] ?? "?")}`, path, text: blockJson(item), raw: item }));
|
|
245
|
+
break;
|
|
246
|
+
case "function_call_output": {
|
|
247
|
+
const output = item["output"];
|
|
248
|
+
if (Array.isArray(output) && output.length > 0) {
|
|
249
|
+
output.forEach((part, pi) => {
|
|
250
|
+
const partPath = `${path}.output[${pi}]`;
|
|
251
|
+
segments.push(seg({ id: partPath, category: "tool_result", label: `item ${ii + 1} function_call_output part ${pi + 1}`, path: partPath,
|
|
252
|
+
text: isRecord(part) && typeof part.text === "string" ? part.text : blockJson(part), raw: part }));
|
|
253
|
+
});
|
|
254
|
+
}
|
|
255
|
+
else
|
|
256
|
+
segments.push(seg({ id: path, category: "tool_result", label: `item ${ii + 1} function_call_output`, path, text: typeof output === "string" ? output : blockJson(output), raw: item }));
|
|
257
|
+
break;
|
|
258
|
+
}
|
|
259
|
+
default:
|
|
260
|
+
// Built-in tool calls (web_search_call, file_search_call, computer_call, ...) and their outputs.
|
|
261
|
+
segments.push(seg({
|
|
262
|
+
id: path,
|
|
263
|
+
category: type.endsWith("_output") ? "tool_result" : type.endsWith("_call") ? "tool_call" : "user",
|
|
264
|
+
label: `item ${ii + 1} ${type}`,
|
|
265
|
+
path,
|
|
266
|
+
text: blockJson(item),
|
|
267
|
+
raw: item,
|
|
268
|
+
}));
|
|
269
|
+
}
|
|
270
|
+
});
|
|
271
|
+
return segments;
|
|
272
|
+
}
|
|
273
|
+
//# sourceMappingURL=parse-openai.js.map
|