@drakonkat/ai-helper 1.1.1 → 1.2.3
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/ARCHITECTURE.md +14 -3
- package/CHANGELOG.md +9 -0
- package/README.md +483 -26
- package/docs/benchmark.md +373 -0
- package/package.json +17 -5
- package/scripts/bench-proxy.js +111 -0
- package/scripts/build.js +16 -0
- package/src/benchmark/fixtures.js +162 -0
- package/src/benchmark/live.js +207 -0
- package/src/benchmark/measurement.js +180 -0
- package/src/benchmark/quality-fixtures.js +95 -0
- package/src/benchmark/quality.js +206 -0
- package/src/benchmark/report.js +162 -0
- package/src/benchmark/runner.js +287 -0
- package/src/codex-config.js +247 -0
- package/src/codex-routing.js +132 -0
- package/src/config.js +19 -1
- package/src/index.js +158 -26
- package/src/manager.js +233 -15
- package/src/proxy-interceptor.example.mjs +33 -0
- package/src/proxy-presets.js +235 -0
- package/src/proxy-stats.js +64 -0
- package/src/proxy-worker.js +17 -0
- package/src/proxy.js +313 -0
- package/src/request-images.js +69 -0
- package/src/service-updates.js +68 -0
- package/src/tui.js +370 -162
- package/src/update.js +41 -0
- package/src/utils/metrics.js +39 -12
- package/src/utils/process.js +92 -146
- package/src/utils/versions.js +165 -0
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
import { evaluatePreservation, validateAnswerChecks, requestTexts } from "./quality.js";
|
|
2
|
+
import { qualityFixtures } from "./quality-fixtures.js";
|
|
3
|
+
import { requestImages } from "../request-images.js";
|
|
4
|
+
|
|
5
|
+
const PATHS = { responses: "/v1/responses", chat: "/v1/chat/completions", anthropic: "/v1/messages" };
|
|
6
|
+
const SYSTEM = "You are evaluating synthetic tool results. Answer the final question using only the tool output. Return the requested literal values, case-sensitive, without explanation. Never execute further tools.";
|
|
7
|
+
const repeat = (count, line) => Array.from({ length: count }, (_, index) => line(index)).join("\n");
|
|
8
|
+
const DENSE_CONTEXT = repeat(600, index => `Reference rule ${index}: the synthetic module component_${index} accepts value_${index}, validates type and range, and emits a structured diagnostic on invalid input. Preserve literal names and numerical values when reporting results.`);
|
|
9
|
+
|
|
10
|
+
function scenarios() {
|
|
11
|
+
return [
|
|
12
|
+
{
|
|
13
|
+
id: "build-success", category: "build", command: "npm run build",
|
|
14
|
+
output: `vite v6.2.0 building for production...\n${repeat(150, index => `transforming src/components/Widget${index}.tsx ... done`)}\n✓ 150 modules transformed.\ndist/index.html 0.46 kB │ gzip: 0.30 kB\ndist/assets/checkout-7f3c.js 183.42 kB │ gzip: 52.10 kB\n✓ built in 3.84s`,
|
|
15
|
+
question: "What is the emitted JavaScript bundle path?", expected: ["dist/assets/checkout-7f3c.js"],
|
|
16
|
+
},
|
|
17
|
+
{
|
|
18
|
+
id: "build-failure", category: "build", command: "npm run build",
|
|
19
|
+
output: `${repeat(120, index => `Checking project packages/module-${index}/tsconfig.json`)}\nsrc/payments/settlement.ts(73,9): error TS2322: Type 'string' is not assignable to type 'number'.\nFound 1 error.\nProcess exited with code 2.`,
|
|
20
|
+
question: "Report the compiler error code and the source location exactly as shown.", expected: ["TS2322", "src/payments/settlement.ts(73,9)"],
|
|
21
|
+
},
|
|
22
|
+
{
|
|
23
|
+
id: "test-failure", category: "test", command: "pytest -v",
|
|
24
|
+
output: `${repeat(100, index => `tests/test_health.py::test_case_${index} PASSED [ ${Math.min(99, index)}%]`)}\nFAILED tests/test_billing.py::test_refund_rounding - AssertionError: expected 42, got 41\nE assert 41 == 42\n=========================== 1 failed, 100 passed in 2.93s ===========================`,
|
|
25
|
+
question: "Which fully qualified test failed, and what were the expected and actual integers?", expected: ["tests/test_billing.py::test_refund_rounding", "42", "41"],
|
|
26
|
+
preserve: ["tests/test_billing.py::test_refund_rounding", "expected 42, got 41"],
|
|
27
|
+
},
|
|
28
|
+
{
|
|
29
|
+
id: "stack-trace", category: "stacktrace", command: "node scripts/checkout.js",
|
|
30
|
+
output: `TypeError: Cannot read properties of undefined (reading 'currency')\n at normalizeInvoice (/workspace/src/invoices/normalize.js:118:27)\n at submitInvoice (/workspace/src/invoices/submit.js:56:12)\n${repeat(110, index => ` at middleware${index} (/workspace/node_modules/router/layer.js:95:5)`)}\nCaused by: missing customer profile\nDiagnostic code: CUSTOMER_PROFILE_MISSING`,
|
|
31
|
+
question: "Return the first application source location and the diagnostic code.", expected: ["/workspace/src/invoices/normalize.js:118:27", "CUSTOMER_PROFILE_MISSING"],
|
|
32
|
+
},
|
|
33
|
+
{
|
|
34
|
+
id: "repeated-logs", category: "logs", command: "docker logs synthetic-worker",
|
|
35
|
+
output: `${repeat(240, index => `2026-01-01T12:${String(index % 60).padStart(2, "0")}:00Z INFO heartbeat worker=alpha queue_depth=0`)}\n2026-01-01T13:00:00Z ERROR request_id=req-9d82 code=QUEUE_LIMIT queue_depth=317 retry_after_ms=8500\n${repeat(80, index => `2026-01-01T13:01:${String(index % 60).padStart(2, "0")}Z INFO heartbeat worker=alpha queue_depth=0`)}`,
|
|
36
|
+
question: "For the ERROR event only, return request_id, code and retry_after_ms.", expected: ["req-9d82", "QUEUE_LIMIT", "8500"],
|
|
37
|
+
},
|
|
38
|
+
{
|
|
39
|
+
id: "grep-results", category: "search", command: "rg -n timeout src",
|
|
40
|
+
output: `${repeat(160, index => `src/generated/client${index}.ts:20:const timeoutMs = 5000;`)}\nsrc/gateway/retry.ts:87:const timeoutMs = 17321; // production override\nsrc/gateway/retry.ts:88:const retryLimit = 4;`,
|
|
41
|
+
question: "Return the production override source path, its line number and its timeout value.", expected: ["src/gateway/retry.ts", "87", "17321"],
|
|
42
|
+
preserve: ["src/gateway/retry.ts:87:const timeoutMs = 17321"],
|
|
43
|
+
},
|
|
44
|
+
{
|
|
45
|
+
id: "git-diff", category: "git", command: "git diff -- src",
|
|
46
|
+
output: `diff --git a/src/config/retries.js b/src/config/retries.js\nindex e183fd0..d0beaf1 100644\n--- a/src/config/retries.js\n+++ b/src/config/retries.js\n@@ -1,162 +1,162 @@\n${repeat(160, index => ` // Configuration reference item ${index}; keep consistent across deployments.`)}\n-export const BACKOFF_CAP_MS = 4000;\n+export const BACKOFF_CAP_MS = 12500;\n export const RETRY_LIMIT = 3;`,
|
|
47
|
+
question: "What configuration symbol changed, and what is its new value?", expected: ["BACKOFF_CAP_MS", "12500"],
|
|
48
|
+
},
|
|
49
|
+
{
|
|
50
|
+
id: "large-json", category: "json", command: "cat synthetic-status.json",
|
|
51
|
+
output: JSON.stringify({ records: Array.from({ length: 180 }, (_, index) => ({ id: `job-${index}`, state: "complete", duration_ms: 230 + index, attempts: 1 })), incident: { id: "inc-b62f", state: "blocked", reason: "SCHEMA_MISMATCH", affected_rows: 2917 } }, null, 2),
|
|
52
|
+
question: "Return the incident id, reason and affected_rows count.", expected: ["inc-b62f", "SCHEMA_MISMATCH", "2917"],
|
|
53
|
+
},
|
|
54
|
+
{
|
|
55
|
+
id: "short-output", category: "short", command: "node scripts/read-version.js",
|
|
56
|
+
output: "service_version=2.17.4-rc.3\nstatus=ready\n",
|
|
57
|
+
question: "What is the exact service version, including its suffix?", expected: ["2.17.4-rc.3"],
|
|
58
|
+
},
|
|
59
|
+
{
|
|
60
|
+
id: "dense-context", category: "context", command: "cat synthetic-deploy-report.txt", dense: true,
|
|
61
|
+
output: `${repeat(220, index => `Preflight check ${index}: valid; no remediation required; policy=documented`)}\nDeployment result: FAILED\nFailure domain: inventory-eu\nRecovery checkpoint: checkpoint-4e6b\nRequired action: REPLAY_PENDING_EVENTS\n`,
|
|
62
|
+
question: "Return the failure domain, recovery checkpoint and required action from the deployment report.", expected: ["inventory-eu", "checkpoint-4e6b", "REPLAY_PENDING_EVENTS"],
|
|
63
|
+
},
|
|
64
|
+
];
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function request(format, model, scenario) {
|
|
68
|
+
const instructions = scenario.dense ? `${SYSTEM}\n\n${DENSE_CONTEXT}` : SYSTEM;
|
|
69
|
+
const callId = `call_${scenario.id.replaceAll("-", "_")}`;
|
|
70
|
+
const parameters = { type: "object", properties: { cmd: { type: "string" } }, required: ["cmd"], additionalProperties: false };
|
|
71
|
+
const definition = { name: "exec_command", description: "Run the given shell command and return textual output.", parameters };
|
|
72
|
+
const args = { cmd: scenario.command };
|
|
73
|
+
if (format === "responses") return {
|
|
74
|
+
model, instructions, max_output_tokens: 256, stream: false,
|
|
75
|
+
tools: [{ type: "function", ...definition }],
|
|
76
|
+
input: [
|
|
77
|
+
{ role: "user", content: "Inspect the synthetic command output." },
|
|
78
|
+
{ type: "function_call", call_id: callId, name: definition.name, arguments: JSON.stringify(args) },
|
|
79
|
+
{ type: "function_call_output", call_id: callId, output: scenario.output },
|
|
80
|
+
{ role: "user", content: scenario.question },
|
|
81
|
+
],
|
|
82
|
+
};
|
|
83
|
+
if (format === "chat") return {
|
|
84
|
+
model, max_completion_tokens: 256, stream: false, tools: [{ type: "function", function: definition }],
|
|
85
|
+
messages: [
|
|
86
|
+
{ role: "system", content: instructions },
|
|
87
|
+
{ role: "user", content: "Inspect the synthetic command output." },
|
|
88
|
+
{ role: "assistant", content: null, tool_calls: [{ id: callId, type: "function", function: { name: definition.name, arguments: JSON.stringify(args) } }] },
|
|
89
|
+
{ role: "tool", tool_call_id: callId, content: scenario.output },
|
|
90
|
+
{ role: "user", content: scenario.question },
|
|
91
|
+
],
|
|
92
|
+
};
|
|
93
|
+
return {
|
|
94
|
+
model, system: instructions, max_tokens: 256, stream: false,
|
|
95
|
+
tools: [{ name: definition.name, description: definition.description, input_schema: parameters }],
|
|
96
|
+
messages: [
|
|
97
|
+
{ role: "user", content: "Inspect the synthetic command output." },
|
|
98
|
+
{ role: "assistant", content: [{ type: "tool_use", id: callId, name: definition.name, input: args }] },
|
|
99
|
+
{ role: "user", content: [{ type: "tool_result", tool_use_id: callId, content: scenario.output }, { type: "text", text: scenario.question }] },
|
|
100
|
+
],
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** Thirty reproducible, secret-free requests; commands are data, never executed. */
|
|
105
|
+
export function builtInFixtures({ model = "gpt-5.5", formats = Object.keys(PATHS), suite = "core" } = {}) {
|
|
106
|
+
if (typeof model !== "string" || !model.trim()) throw new Error("fixture model must be a nonempty string");
|
|
107
|
+
if (!Array.isArray(formats) || !formats.length || formats.some(format => !Object.hasOwn(PATHS, format)) || new Set(formats).size !== formats.length) {
|
|
108
|
+
throw new Error(`fixture formats must be a nonempty, unique subset of: ${Object.keys(PATHS).join(", ")}`);
|
|
109
|
+
}
|
|
110
|
+
if (!["core", "quality", "all"].includes(suite)) throw new Error("fixture suite must be core, quality or all");
|
|
111
|
+
const core = suite === "quality" ? [] : formats.flatMap(format => scenarios().map(scenario => ({
|
|
112
|
+
id: `${format}-${scenario.id}`, category: scenario.category, format, path: PATHS[format],
|
|
113
|
+
body: request(format, model, scenario),
|
|
114
|
+
checks: { toolIncludes: [...(scenario.preserve || scenario.expected)], requestIncludes: [scenario.question] },
|
|
115
|
+
answerChecks: { includes: [...scenario.expected] },
|
|
116
|
+
})));
|
|
117
|
+
return [...core, ...(suite === "core" ? [] : qualityFixtures({ model, formats }))];
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
function object(value) { return value !== null && typeof value === "object" && !Array.isArray(value); }
|
|
121
|
+
function checkArrays(value, keys, where) {
|
|
122
|
+
if (!object(value)) throw new Error(`${where} must be an object`);
|
|
123
|
+
for (const key of Object.keys(value)) {
|
|
124
|
+
if (!keys.includes(key)) throw new Error(`${where}.${key} is unknown; allowed keys: ${keys.join(", ")}`);
|
|
125
|
+
if (!Array.isArray(value[key]) || value[key].some(text => typeof text !== "string" || !text.trim())) throw new Error(`${where}.${key} must be an array of nonempty strings`);
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** Validate a parsed JSON fixture array without changing it or inventing checks. */
|
|
130
|
+
export function validateFixtures(input) {
|
|
131
|
+
if (!Array.isArray(input) || !input.length) throw new Error("Fixtures must be a nonempty JSON array");
|
|
132
|
+
const ids = new Set();
|
|
133
|
+
input.forEach((fixture, index) => {
|
|
134
|
+
const where = `Fixture[${index}]${fixture?.id ? ` (${fixture.id})` : ""}`;
|
|
135
|
+
if (!object(fixture)) throw new Error(`${where} must be an object`);
|
|
136
|
+
for (const key of ["id", "category"]) if (typeof fixture[key] !== "string" || !fixture[key].trim()) throw new Error(`${where}.${key} must be a nonempty string`);
|
|
137
|
+
if (ids.has(fixture.id)) throw new Error(`${where}.id is duplicated`);
|
|
138
|
+
ids.add(fixture.id);
|
|
139
|
+
if (!Object.hasOwn(PATHS, fixture.format)) throw new Error(`${where}.format must be responses, chat or anthropic`);
|
|
140
|
+
if (fixture.path !== PATHS[fixture.format]) throw new Error(`${where}.path must be ${PATHS[fixture.format]} for ${fixture.format}`);
|
|
141
|
+
if (!object(fixture.body)) throw new Error(`${where}.body must be a request object`);
|
|
142
|
+
if (typeof fixture.body.model !== "string" || !fixture.body.model.trim()) throw new Error(`${where}.body.model must be a nonempty string`);
|
|
143
|
+
if (fixture.format === "responses") {
|
|
144
|
+
if (!(typeof fixture.body.input === "string" && fixture.body.input.trim()) && !(Array.isArray(fixture.body.input) && fixture.body.input.length)) throw new Error(`${where}.body.input must be nonempty text or an array`);
|
|
145
|
+
} else if (!Array.isArray(fixture.body.messages) || !fixture.body.messages.length) throw new Error(`${where}.body.messages must be a nonempty array`);
|
|
146
|
+
if (fixture.body.tools !== undefined && !Array.isArray(fixture.body.tools)) throw new Error(`${where}.body.tools must be an array`);
|
|
147
|
+
checkArrays(fixture.checks, ["toolIncludes", "requestIncludes"], `${where}.checks`);
|
|
148
|
+
if (fixture.answerChecks !== undefined) validateAnswerChecks(fixture.answerChecks, `${where}.answerChecks`);
|
|
149
|
+
if (fixture.evaluation !== undefined) {
|
|
150
|
+
const e = fixture.evaluation;
|
|
151
|
+
if (!object(e) || !["rendered_context", "native_image"].includes(e.kind) || Object.keys(e).some(k => !["kind", "evidence"].includes(k)) ||
|
|
152
|
+
!Array.isArray(e.evidence) || !e.evidence.length || e.evidence.some(x => typeof x !== "string" || !x.trim())) throw new Error(`${where}.evaluation requires kind and nonempty evidence strings`);
|
|
153
|
+
const nativeText = requestTexts(fixture.body).join("\n");
|
|
154
|
+
if (e.kind === "native_image" && (!requestImages(fixture.body).length || e.evidence.some(x => nativeText.includes(x)))) throw new Error(`${where}.evaluation native-image evidence must be absent from native text and images must exist`);
|
|
155
|
+
if (e.kind === "rendered_context" && e.evidence.some(x => !nativeText.includes(x))) throw new Error(`${where}.evaluation rendered-context evidence must exist in original text`);
|
|
156
|
+
}
|
|
157
|
+
const quality = evaluatePreservation(fixture.body, fixture.body, fixture.checks);
|
|
158
|
+
const invalid = quality.checks.find(check => check.reason === "not_in_original");
|
|
159
|
+
if (invalid) throw new Error(`${where}.checks.${invalid.kind} assertion ${JSON.stringify(invalid.expected)} is absent from the original ${invalid.kind === "toolIncludes" ? "tool output" : "request text"}`);
|
|
160
|
+
});
|
|
161
|
+
return input;
|
|
162
|
+
}
|
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
// Live evaluation is opt-in. No tool requested by a model is ever executed.
|
|
2
|
+
import { performance } from "node:perf_hooks";
|
|
3
|
+
|
|
4
|
+
export function validateUpstream(value) {
|
|
5
|
+
const url = new URL(value);
|
|
6
|
+
if (!["http:", "https:"].includes(url.protocol) || url.username || url.password || url.search || url.hash) {
|
|
7
|
+
throw new Error("Live upstream must be HTTP(S), without credentials, query or fragment");
|
|
8
|
+
}
|
|
9
|
+
return url.href;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export async function readLimited(response, maxBytes) {
|
|
13
|
+
const chunks = [];
|
|
14
|
+
let size = 0;
|
|
15
|
+
for await (const chunk of response.body) {
|
|
16
|
+
size += chunk.length;
|
|
17
|
+
if (size > maxBytes) throw new Error("Response exceeds benchmark maxBodyBytes");
|
|
18
|
+
chunks.push(chunk);
|
|
19
|
+
}
|
|
20
|
+
return Buffer.concat(chunks).toString("utf8");
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
async function readResponsesStream(response, maxBytes, start) {
|
|
24
|
+
const reader = response.body.getReader();
|
|
25
|
+
const decoder = new TextDecoder("utf-8", { fatal: true });
|
|
26
|
+
const finalizedItems = new Map(), finalizedIds = new Map();
|
|
27
|
+
let size = 0, buffer = "", scanOffset = 0, event = "", data = [], firstOutputMs = null;
|
|
28
|
+
function finalizedItem(value) {
|
|
29
|
+
const { item, output_index: index } = value;
|
|
30
|
+
if (!Number.isSafeInteger(index) || index < 0 || !item || typeof item !== "object" || Array.isArray(item) ||
|
|
31
|
+
typeof item.id !== "string" || !item.id || typeof item.type !== "string" || !item.type || item.status === "in_progress") {
|
|
32
|
+
throw new Error("Provider SSE contained an invalid finalized output item");
|
|
33
|
+
}
|
|
34
|
+
if ((finalizedIds.has(item.id) && finalizedIds.get(item.id) !== index) ||
|
|
35
|
+
(finalizedItems.has(index) && JSON.stringify(finalizedItems.get(index)) !== JSON.stringify(item))) {
|
|
36
|
+
throw new Error("Provider SSE contained conflicting finalized output items");
|
|
37
|
+
}
|
|
38
|
+
finalizedItems.set(index, item); finalizedIds.set(item.id, index);
|
|
39
|
+
}
|
|
40
|
+
function mergedOutput(terminal) {
|
|
41
|
+
const items = new Map(finalizedItems), terminalIds = new Set();
|
|
42
|
+
for (const [position, item] of (terminal.output || []).entries()) {
|
|
43
|
+
if (!item || typeof item !== "object" || Array.isArray(item) || typeof item.type !== "string") throw new Error("Provider SSE contained an invalid terminal response");
|
|
44
|
+
const index = finalizedIds.get(item.id) ?? position, previous = items.get(index);
|
|
45
|
+
if ((item.id && terminalIds.has(item.id)) || (previous && (previous.type !== item.type ||
|
|
46
|
+
(item.id && previous.id && item.id !== previous.id)))) throw new Error("Provider SSE contained an invalid terminal response");
|
|
47
|
+
if (item.id) terminalIds.add(item.id);
|
|
48
|
+
// The terminal item wins over its earlier finalized event, but absent
|
|
49
|
+
// items retain their finalized content. Never reconstruct from deltas.
|
|
50
|
+
items.set(index, item);
|
|
51
|
+
}
|
|
52
|
+
const output = [...items].sort(([a], [b]) => a - b).map(([, item]) => item);
|
|
53
|
+
const restored = output.length > (terminal.output || []).length;
|
|
54
|
+
const merged = { ...terminal, output };
|
|
55
|
+
if (restored && merged.output_text === "") delete merged.output_text;
|
|
56
|
+
return { merged, restored };
|
|
57
|
+
}
|
|
58
|
+
function line(text) {
|
|
59
|
+
if (text.startsWith(":")) return null;
|
|
60
|
+
if (text) {
|
|
61
|
+
const colon = text.indexOf(":");
|
|
62
|
+
const field = colon < 0 ? text : text.slice(0, colon);
|
|
63
|
+
const content = colon < 0 ? "" : text.slice(colon + 1).replace(/^ /, "");
|
|
64
|
+
if (field === "event") event = content;
|
|
65
|
+
else if (field === "data") data.push(content);
|
|
66
|
+
return null;
|
|
67
|
+
}
|
|
68
|
+
const name = event, payload = data.join("\n");
|
|
69
|
+
event = ""; data = [];
|
|
70
|
+
if (!payload) return null;
|
|
71
|
+
if (payload === "[DONE]") throw new Error("Provider SSE ended without a terminal response");
|
|
72
|
+
let value;
|
|
73
|
+
try { value = JSON.parse(payload); }
|
|
74
|
+
catch { throw new Error("Provider SSE contained invalid event data"); }
|
|
75
|
+
if (!value || typeof value !== "object" || Array.isArray(value) ||
|
|
76
|
+
(name && value.type && name !== value.type)) throw new Error("Provider SSE contained invalid event data");
|
|
77
|
+
const type = value.type || name;
|
|
78
|
+
if (type === "response.output_text.delta" && typeof value.delta === "string" && value.delta.length && firstOutputMs === null) firstOutputMs = performance.now() - start;
|
|
79
|
+
if (type === "response.output_item.done") { finalizedItem(value); return null; }
|
|
80
|
+
if (type === "error") throw new Error("Provider SSE reported an error");
|
|
81
|
+
if (!["response.completed", "response.incomplete", "response.failed"].includes(type)) return null;
|
|
82
|
+
const terminal = value.response, status = type.slice("response.".length);
|
|
83
|
+
if (!terminal || typeof terminal !== "object" || Array.isArray(terminal) || terminal.status !== status ||
|
|
84
|
+
(terminal.output !== undefined && !Array.isArray(terminal.output)) ||
|
|
85
|
+
(status !== "failed" && !Array.isArray(terminal.output) && typeof terminal.output_text !== "string" && !finalizedItems.size)) {
|
|
86
|
+
throw new Error("Provider SSE contained an invalid terminal response");
|
|
87
|
+
}
|
|
88
|
+
let parsed, restored;
|
|
89
|
+
try {
|
|
90
|
+
const result = mergedOutput(terminal); restored = result.restored;
|
|
91
|
+
parsed = parseProviderResponse(result.merged, "responses");
|
|
92
|
+
if (result.merged.output.some(item => item.status === "incomplete")) parsed.complete = false;
|
|
93
|
+
}
|
|
94
|
+
catch { throw new Error("Provider SSE contained an invalid terminal response"); }
|
|
95
|
+
const missingFinalText = firstOutputMs !== null && !parsed.text && !parsed.additionalToolCalls;
|
|
96
|
+
return { ...parsed, firstOutputMs, outputFromFinalizedItems: restored,
|
|
97
|
+
...(missingFinalText ? { complete: false, error: "Provider SSE ended without finalized output text" } : {}),
|
|
98
|
+
...(status === "failed" ? { error: "Provider response failed" } : {}) };
|
|
99
|
+
}
|
|
100
|
+
function consume(final = false) {
|
|
101
|
+
let offset = 0, index = scanOffset;
|
|
102
|
+
for (; index < buffer.length; index++) {
|
|
103
|
+
if (buffer[index] !== "\n" && buffer[index] !== "\r") continue;
|
|
104
|
+
// A CR and LF can arrive in separate network chunks.
|
|
105
|
+
if (buffer[index] === "\r" && index === buffer.length - 1 && !final) break;
|
|
106
|
+
const result = line(buffer.slice(offset, index));
|
|
107
|
+
if (buffer[index] === "\r" && buffer[index + 1] === "\n") index++;
|
|
108
|
+
offset = index + 1;
|
|
109
|
+
if (result) return result;
|
|
110
|
+
}
|
|
111
|
+
buffer = buffer.slice(offset);
|
|
112
|
+
scanOffset = index - offset;
|
|
113
|
+
return null;
|
|
114
|
+
}
|
|
115
|
+
try {
|
|
116
|
+
while (true) {
|
|
117
|
+
const { value, done } = await reader.read();
|
|
118
|
+
if (done) {
|
|
119
|
+
buffer += decoder.decode();
|
|
120
|
+
const terminal = consume(true);
|
|
121
|
+
if (terminal) return terminal;
|
|
122
|
+
throw new Error("Provider SSE ended without a terminal response");
|
|
123
|
+
}
|
|
124
|
+
size += value.byteLength;
|
|
125
|
+
if (size > maxBytes) throw new Error("Response exceeds benchmark maxBodyBytes");
|
|
126
|
+
buffer += decoder.decode(value, { stream: true });
|
|
127
|
+
const terminal = consume();
|
|
128
|
+
if (terminal) return terminal;
|
|
129
|
+
}
|
|
130
|
+
} finally {
|
|
131
|
+
// Providers may keep SSE sockets open after a terminal event. Do not wait
|
|
132
|
+
// for EOF, leak a reader, or accept subsequent contradictory/delta events.
|
|
133
|
+
await reader.cancel().catch(() => {});
|
|
134
|
+
reader.releaseLock();
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
export async function callProvider(body, fixture, options) {
|
|
139
|
+
const headers = { "content-type": "application/json" };
|
|
140
|
+
if (options.apiKey) {
|
|
141
|
+
if (fixture.format === "anthropic") headers["x-api-key"] = options.apiKey;
|
|
142
|
+
else headers.authorization = `Bearer ${options.apiKey}`;
|
|
143
|
+
}
|
|
144
|
+
if (fixture.format === "anthropic") headers["anthropic-version"] = "2023-06-01";
|
|
145
|
+
const url = options.upstream.replace(/\/$/, "") + fixture.path;
|
|
146
|
+
const start = performance.now();
|
|
147
|
+
const response = await fetch(url, {
|
|
148
|
+
method: "POST", headers, body: JSON.stringify(body), redirect: "error",
|
|
149
|
+
signal: options.signal ? AbortSignal.any([options.signal, AbortSignal.timeout(options.timeoutMs)]) : AbortSignal.timeout(options.timeoutMs),
|
|
150
|
+
});
|
|
151
|
+
if (response.ok && fixture.format === "responses" && /^text\/event-stream(?:\s*;|\s*$)/i.test(response.headers.get("content-type") || "")) {
|
|
152
|
+
try {
|
|
153
|
+
const parsed = await readResponsesStream(response, options.maxBodyBytes, start);
|
|
154
|
+
return { status: response.status, durationMs: performance.now() - start, ...parsed };
|
|
155
|
+
} catch (error) {
|
|
156
|
+
// Only locally constructed diagnostics survive; never JSON parser errors,
|
|
157
|
+
// provider event bodies, echoed prompts or credentials.
|
|
158
|
+
const safe = ["Provider SSE ended without a terminal response", "Provider SSE contained invalid event data",
|
|
159
|
+
"Provider SSE reported an error", "Provider SSE contained an invalid terminal response", "Response exceeds benchmark maxBodyBytes",
|
|
160
|
+
"Provider SSE contained an invalid finalized output item", "Provider SSE contained conflicting finalized output items"];
|
|
161
|
+
return { status: response.status, durationMs: performance.now() - start, complete: false,
|
|
162
|
+
error: safe.includes(error.message) ? error.message : "Provider SSE could not be read" };
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
const raw = await readLimited(response, options.maxBodyBytes);
|
|
166
|
+
const durationMs = performance.now() - start;
|
|
167
|
+
// Never put provider error bodies (which can echo credentials/prompts) in reports.
|
|
168
|
+
if (!response.ok) return { status: response.status, durationMs, error: `Provider HTTP ${response.status}` };
|
|
169
|
+
let value;
|
|
170
|
+
try { value = JSON.parse(raw); } catch { return { status: response.status, durationMs, error: "Provider did not return JSON or a supported Responses SSE stream" }; }
|
|
171
|
+
try { return { status: response.status, durationMs, ...parseProviderResponse(value, fixture.format) }; }
|
|
172
|
+
catch { return { status: response.status, durationMs, error: "Provider returned an invalid response shape" }; }
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
const number = n => Number.isFinite(n) && n >= 0 ? n : null;
|
|
176
|
+
|
|
177
|
+
export function parseProviderResponse(value, format) {
|
|
178
|
+
const u = value?.usage || {};
|
|
179
|
+
let text = "", additionalToolCalls = 0, complete = true;
|
|
180
|
+
let inputTokens = number(u.input_tokens ?? u.prompt_tokens);
|
|
181
|
+
const outputTokens = number(u.output_tokens ?? u.completion_tokens);
|
|
182
|
+
const cachedInputTokens = number(u.input_tokens_details?.cached_tokens ?? u.prompt_tokens_details?.cached_tokens ?? u.cache_read_input_tokens);
|
|
183
|
+
const cacheWriteInputTokens = number(u.cache_creation_input_tokens);
|
|
184
|
+
if (format === "anthropic") {
|
|
185
|
+
text = (value.content || []).filter(x => x.type === "text").map(x => x.text).join("\n");
|
|
186
|
+
additionalToolCalls = (value.content || []).filter(x => x.type === "tool_use").length;
|
|
187
|
+
complete = value.stop_reason === "end_turn" || value.stop_reason === "stop_sequence";
|
|
188
|
+
// Anthropic input_tokens excludes cache reads/writes; normalize to all input.
|
|
189
|
+
if (inputTokens !== null) inputTokens += (cachedInputTokens ?? 0) + (cacheWriteInputTokens ?? 0);
|
|
190
|
+
} else if (format === "chat") {
|
|
191
|
+
const choice = value.choices?.[0];
|
|
192
|
+
const content = choice?.message?.content;
|
|
193
|
+
text = typeof content === "string" ? content : Array.isArray(content) ? content.filter(x => x.type === "text").map(x => x.text).join("\n") : "";
|
|
194
|
+
additionalToolCalls = choice?.message?.tool_calls?.length || 0;
|
|
195
|
+
complete = choice?.finish_reason === "stop";
|
|
196
|
+
} else {
|
|
197
|
+
text = typeof value.output_text === "string" ? value.output_text : (value.output || []).flatMap(x => x.content || []).filter(x => x.type === "output_text").map(x => x.text).join("\n");
|
|
198
|
+
additionalToolCalls = (value.output || []).filter(x => /(?:^|_)call$/.test(x.type || "")).length;
|
|
199
|
+
complete = value.status === "completed";
|
|
200
|
+
}
|
|
201
|
+
return {
|
|
202
|
+
text, additionalToolCalls, complete: complete && additionalToolCalls === 0,
|
|
203
|
+
usage: { inputTokens, outputTokens, cachedInputTokens, cacheWriteInputTokens,
|
|
204
|
+
totalTokens: inputTokens !== null && outputTokens !== null ? inputTokens + outputTokens : null,
|
|
205
|
+
reasoningTokens: number(u.output_tokens_details?.reasoning_tokens ?? u.completion_tokens_details?.reasoning_tokens) },
|
|
206
|
+
};
|
|
207
|
+
}
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
import { countTokens } from "gpt-tokenizer/encoding/o200k_base";
|
|
2
|
+
import { openAIVisionTokens, resolveVisionCost } from "pxpipe-proxy";
|
|
3
|
+
|
|
4
|
+
const PNG_SIGNATURE = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]);
|
|
5
|
+
const IMAGE_TYPES = new Set(["image", "image_url", "input_image"]);
|
|
6
|
+
const OTHER_MEDIA_TYPES = new Set(["audio", "input_audio", "output_audio", "video", "video_url", "input_video", "file", "input_file", "document"]);
|
|
7
|
+
const BINARY_KEYS = new Set(["encrypted_content", "file_data", "b64_json", "base64", "bytes", "audio_data", "image_data", "video_data"]);
|
|
8
|
+
|
|
9
|
+
function tokenize(text) {
|
|
10
|
+
// Tool output may contain special-token spellings; count them as ordinary text.
|
|
11
|
+
return countTokens(text, { disallowedSpecial: new Set() });
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
function parseBody(body) {
|
|
15
|
+
const serialized = typeof body === "string" ? body
|
|
16
|
+
: body instanceof Uint8Array ? Buffer.from(body).toString("utf8") : JSON.stringify(body);
|
|
17
|
+
const parsed = JSON.parse(serialized);
|
|
18
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
|
|
19
|
+
throw new TypeError("Benchmark measurement requires a JSON request object");
|
|
20
|
+
}
|
|
21
|
+
return { parsed, bytes: Buffer.byteLength(serialized, "utf8") };
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function pngDimensions(url) {
|
|
25
|
+
if (typeof url !== "string" || !url.startsWith("data:image/png;base64,")) return null;
|
|
26
|
+
const payload = url.slice("data:image/png;base64,".length);
|
|
27
|
+
// Decode only IHDR, never the whole image. A malformed or truncated header is
|
|
28
|
+
// not an image with zero cost. PNG dimensions are unsigned 31-bit integers.
|
|
29
|
+
if (payload.length < 44 || payload.length % 4 !== 0 || !/^[A-Za-z0-9+/]+={0,2}$/.test(payload)) return null;
|
|
30
|
+
const header = Buffer.from(payload.slice(0, 44), "base64");
|
|
31
|
+
if (header.length < 33 || !header.subarray(0, 8).equals(PNG_SIGNATURE)
|
|
32
|
+
|| header.readUInt32BE(8) !== 13 || header.toString("ascii", 12, 16) !== "IHDR") return null;
|
|
33
|
+
const width = header.readUInt32BE(16);
|
|
34
|
+
const height = header.readUInt32BE(20);
|
|
35
|
+
if (!width || !height || width > 0x7fffffff || height > 0x7fffffff) return null;
|
|
36
|
+
return { width, height };
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function recognizedOpenAIModel(value) {
|
|
40
|
+
// Do not let pxpipe's unknown-model fallback charge an Anthropic/Gemini image
|
|
41
|
+
// using OpenAI tile costs. These are model families represented by the pinned
|
|
42
|
+
// pxpipe version; future/unrecognized versions must be added deliberately.
|
|
43
|
+
const model = typeof value === "string" ? value.toLowerCase().replace(/^openai\//, "") : "";
|
|
44
|
+
const date = "(?:-\\d{4}-\\d{2}-\\d{2})?";
|
|
45
|
+
const known = ["gpt-4o", "gpt-4\\.1(?:-mini|-nano)?", "gpt-4\\.5-preview",
|
|
46
|
+
"gpt-5(?:-mini|-nano|-chat-latest)?", "gpt-5\\.[1-6](?:-mini|-nano|-sol|-terra|-luna|-chat-latest|-codex)?",
|
|
47
|
+
"o1(?:-pro)?", "o3(?:-pro)?", "o4-mini"];
|
|
48
|
+
return new RegExp(`^(?:${known.join("|")})${date}$`).test(model) ? model : null;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function imageSource(block) {
|
|
52
|
+
if (block.type === "image_url") return { url: block.image_url?.url ?? block.image_url, detail: block.image_url?.detail ?? block.detail };
|
|
53
|
+
if (block.type === "input_image") return { url: block.image_url, detail: block.detail };
|
|
54
|
+
const source = block.source ?? block.inline_data ?? block.inlineData;
|
|
55
|
+
if (source?.type === "base64" || source?.data) {
|
|
56
|
+
return { url: `data:${source.media_type ?? source.mime_type ?? source.mimeType};base64,${source.data}`, detail: block.detail };
|
|
57
|
+
}
|
|
58
|
+
return { url: source?.url ?? block.url, detail: block.detail };
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function toolStrings(body) {
|
|
62
|
+
const strings = [];
|
|
63
|
+
const add = value => {
|
|
64
|
+
if (typeof value === "string") strings.push(value);
|
|
65
|
+
else if (Array.isArray(value)) {
|
|
66
|
+
for (const block of value) {
|
|
67
|
+
if (["text", "input_text", "output_text"].includes(block?.type) && typeof block.text === "string") strings.push(block.text);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
};
|
|
71
|
+
for (const item of Array.isArray(body.input) ? body.input : []) {
|
|
72
|
+
if (item?.type === "function_call_output") add(item.output);
|
|
73
|
+
}
|
|
74
|
+
for (const message of Array.isArray(body.messages) ? body.messages : []) {
|
|
75
|
+
if (message?.role === "tool" || message?.role === "function") add(message.content);
|
|
76
|
+
for (const block of Array.isArray(message?.content) ? message.content : []) {
|
|
77
|
+
if (block?.type === "tool_result") add(block.content);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
return strings;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* A deterministic, cross-preset estimate, NOT provider billing/count_tokens.
|
|
85
|
+
* textTokens counts canonical JSON (including structural/request fields) after
|
|
86
|
+
* removing media payloads and opaque encrypted content. It uses o200k_base for
|
|
87
|
+
* EVERY model so comparisons do not mix compressors' incompatible counters.
|
|
88
|
+
* Image estimates use the installed pxpipe profile only for recognized OpenAI
|
|
89
|
+
* models with explicit high/original detail. Unknown detail, remote/non-PNG
|
|
90
|
+
* images, non-OpenAI media, and opaque content make totalTokens null; the known
|
|
91
|
+
* subtotal remains available in knownTokens. No remote URL is fetched.
|
|
92
|
+
*/
|
|
93
|
+
export async function measureRequest(body) {
|
|
94
|
+
const { parsed, bytes } = parseBody(body);
|
|
95
|
+
const warnings = new Set(["Local estimate: o200k_base over sanitized canonical JSON, not provider billing; JSON framing differs from model serialization."]);
|
|
96
|
+
const model = recognizedOpenAIModel(parsed.model);
|
|
97
|
+
const imageMeasurements = [];
|
|
98
|
+
let unknownMedia = 0;
|
|
99
|
+
let opaqueFields = 0;
|
|
100
|
+
let omittedPayloads = 0;
|
|
101
|
+
|
|
102
|
+
function inspectImage(block) {
|
|
103
|
+
const { url, detail } = imageSource(block);
|
|
104
|
+
const dimensions = pngDimensions(url);
|
|
105
|
+
let reason;
|
|
106
|
+
if (!model) reason = "unsupported_model";
|
|
107
|
+
else if (!dimensions) reason = "remote_non_png_or_invalid_header";
|
|
108
|
+
else if (detail !== "high" && detail !== "original") reason = "unknown_image_detail";
|
|
109
|
+
let tokens = null;
|
|
110
|
+
if (!reason) {
|
|
111
|
+
const profile = resolveVisionCost(model);
|
|
112
|
+
if (!["tile", "patch"].includes(profile?.regime)) reason = "unsupported_vision_profile";
|
|
113
|
+
// The dependency's patch-cap shortcut is not a full provider resize
|
|
114
|
+
// algorithm. Above its cap, leave the cost unknown rather than undercount.
|
|
115
|
+
else if (profile.regime === "patch" && profile.patchCap
|
|
116
|
+
&& Math.ceil(dimensions.width / 32) * Math.ceil(dimensions.height / 32) > profile.patchCap) reason = "image_resize_not_modeled";
|
|
117
|
+
else {
|
|
118
|
+
const estimate = openAIVisionTokens(model, dimensions.width, dimensions.height);
|
|
119
|
+
if (!Number.isFinite(estimate) || estimate < 0) reason = "invalid_vision_estimate";
|
|
120
|
+
else tokens = estimate;
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
if (reason) warnings.add(`Image token cost unknown (${reason}); totalTokens is null, not zero.`);
|
|
124
|
+
else warnings.add("Image tokens are an installed pxpipe profile approximation for explicit high/original detail; provider resizing/detail rules and profile overrides may differ. Validate with provider usage.");
|
|
125
|
+
imageMeasurements.push({ ...(dimensions ?? {}), detail: detail ?? null, tokens, reason: reason ?? null });
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function stripDataUris(text) {
|
|
129
|
+
return text.replace(/data:[^\s\"'<>]*;base64,[A-Za-z0-9+/=_-]*/gi, () => {
|
|
130
|
+
omittedPayloads++;
|
|
131
|
+
return "";
|
|
132
|
+
});
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
function sanitize(value) {
|
|
136
|
+
if (typeof value === "string") return stripDataUris(value);
|
|
137
|
+
if (Array.isArray(value)) return value.map(sanitize);
|
|
138
|
+
if (!value || typeof value !== "object") return value;
|
|
139
|
+
const inline = value.inline_data ?? value.inlineData;
|
|
140
|
+
const isImage = IMAGE_TYPES.has(value.type) || /^image\//.test(inline?.mime_type ?? inline?.mimeType ?? "");
|
|
141
|
+
if (isImage) {
|
|
142
|
+
inspectImage(value);
|
|
143
|
+
// Image URLs, IDs and payloads are transport representations, NOT text.
|
|
144
|
+
return { type: value.type ?? "image", ...(value.detail ? { detail: value.detail } : {}) };
|
|
145
|
+
}
|
|
146
|
+
if (OTHER_MEDIA_TYPES.has(value.type) || inline) {
|
|
147
|
+
unknownMedia++;
|
|
148
|
+
return { type: value.type ?? "media" };
|
|
149
|
+
}
|
|
150
|
+
const result = Object.create(null);
|
|
151
|
+
for (const key of Object.keys(value).sort()) {
|
|
152
|
+
if (BINARY_KEYS.has(key) || key === "data" && value.type === "base64") {
|
|
153
|
+
if (key === "encrypted_content") opaqueFields++;
|
|
154
|
+
else omittedPayloads++;
|
|
155
|
+
continue;
|
|
156
|
+
}
|
|
157
|
+
result[key] = sanitize(value[key]);
|
|
158
|
+
}
|
|
159
|
+
return result;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
const sanitized = sanitize(parsed);
|
|
163
|
+
const textTokens = tokenize(JSON.stringify(sanitized));
|
|
164
|
+
// These are bare tool text counts, without JSON framing. Do not treat the
|
|
165
|
+
// disappearance of native tool text into images as 100% whole-request savings.
|
|
166
|
+
const toolTextTokens = toolStrings(parsed).reduce((sum, text) => sum + tokenize(stripDataUris(text)), 0);
|
|
167
|
+
const unknownImages = imageMeasurements.filter(item => item.tokens === null).length;
|
|
168
|
+
const imageTokens = imageMeasurements.reduce((sum, item) => sum + (item.tokens ?? 0), 0);
|
|
169
|
+
const knownTokens = textTokens + imageTokens;
|
|
170
|
+
if (unknownMedia) warnings.add("Audio/video/file or other media cost is unknown; its payload is excluded from text tokens.");
|
|
171
|
+
if (opaqueFields) warnings.add("Opaque encrypted_content is excluded; its token cost is unknown.");
|
|
172
|
+
if (omittedPayloads) warnings.add("Unclassified binary/base64 payloads are excluded from text tokens; their token cost is unknown.");
|
|
173
|
+
const hasUnknown = unknownImages > 0 || unknownMedia > 0 || opaqueFields > 0 || omittedPayloads > 0;
|
|
174
|
+
return {
|
|
175
|
+
method: "o200k_base:canonical-json+pxpipe:openai-vision-estimate",
|
|
176
|
+
textTokens, toolTextTokens, imageTokens, totalTokens: hasUnknown ? null : knownTokens,
|
|
177
|
+
knownTokens, images: imageMeasurements.length, unknownImages, unknownMedia, opaqueFields,
|
|
178
|
+
bytes, warnings: [...warnings], imageMeasurements,
|
|
179
|
+
};
|
|
180
|
+
}
|