vectorbench 0.0.0-stage → 3.0.2

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.
@@ -0,0 +1,77 @@
1
+ // One adapter per kind of API, each turning the harness's conversation into
2
+ // that API's requests: the provider's own address, effort field and output
3
+ // cap, as bench.config.mjs and src/model-apis.js give them for plain runs.
4
+ //
5
+ // Every adapter exports `open(options)` and returns a conversation.
6
+ //
7
+ // options:
8
+ // url, headers where to ask and the key's headers (from the preset)
9
+ // model, effort, maxOutputTokens
10
+ // extraBody the preset's own fields, merged into every request
11
+ // background, stream, asMessages, statusUrl the preset's options for its style
12
+ // text the request (harness/request.mjs), the first user message
13
+ // tool { name, description, parameters } (JSON Schema): the one tool
14
+ //
15
+ // conversation:
16
+ // ask() sends what is pending and returns the model's reply:
17
+ // { calls, text, ended, id, servedModel, usage, raw }
18
+ // calls: one per tool call, in order: { id, command }, or
19
+ // { id, error } when the arguments can't be read (the
20
+ // loop answers that call with the error).
21
+ // ended: 'calls' (it called the tool), 'complete' (it
22
+ // stopped without), 'refused', or 'truncated' (it hit
23
+ // its output cap).
24
+ // usage: { input, output, cached, reasoning, cost? } in
25
+ // tokens; `input` includes `cached`; leave `cost` out
26
+ // unless the provider reports dollars.
27
+ // raw: the provider's reply as received, for the record.
28
+ // A failed request throws ProviderError and changes
29
+ // nothing: ask() can be called again.
30
+ // answer(results) the results of the last reply's calls, one per call in
31
+ // order: { id, text, images: [{ mime, data }] } (data is
32
+ // base64). The model must receive the images as images.
33
+ // say(text) a plain user message (after a reply with no tool call).
34
+ // close() async; deletes anything the provider stored. Never throws.
35
+ //
36
+ // Every request is streamed or run in the background: a connection that
37
+ // carries nothing for about a minute is closed on the way, and a top-effort
38
+ // reply can think for many minutes.
39
+
40
+ import { authHeaders, merge, presets } from '../../src/model-apis.js';
41
+ import * as chat from './chat.mjs';
42
+ import * as interactions from './interactions.mjs';
43
+ import * as messages from './messages.mjs';
44
+ import * as responses from './responses.mjs';
45
+
46
+ const styles = { chat, interactions, messages, responses };
47
+
48
+ // Routes only the harness uses, not in src/model-apis.js `presets`. Used with
49
+ // scripts/harness.mjs --via <id>, and only for the models each was checked
50
+ // for (VIA_CHECKED).
51
+ //
52
+ // The public copy has none.
53
+ const harnessPresets = [];
54
+ export const VIA_CHECKED = {};
55
+ /** What a route charges against the maker's list price. */
56
+ export const PRICE_RATIO = {};
57
+ const allPresets = [...presets, ...harnessPresets];
58
+
59
+ /** The environment variable that holds the key for each adapter in bench.config.mjs. */
60
+ export const KEYS = { anthropic: 'ANTHROPIC_API_KEY', openai: 'OPENAI_API_KEY', gemini: 'GEMINI_API_KEY', xai: 'XAI_API_KEY', openrouter: 'OPENROUTER_API_KEY' };
61
+ export const keyOf = (model) => KEYS[model.via] ?? KEYS[model.via.split('-')[0]];
62
+
63
+ /** Opens a conversation with a model from bench.config.mjs. */
64
+ export function open(model, { effort = model.effort, maxOutputTokens, text, tool, extraBody, key = process.env[keyOf(model)] }) {
65
+ const preset = allPresets.find((p) => p.id === model.via);
66
+ if (!preset || !styles[preset.style]) throw new Error(`The harness has no adapter for "${model.via}".`);
67
+ const { style, auth, label, id, via, ...options } = preset;
68
+ // A caller's fields go over the preset's, merged the way the adapters merge them into the request.
69
+ if (extraBody) options.extraBody = merge(options.extraBody ?? {}, extraBody);
70
+ return {
71
+ route: { via: model.via, style, url: preset.url },
72
+ ...styles[style].open({ ...options, headers: authHeaders(auth, key, style), model: model.model, effort, maxOutputTokens, text, tool }),
73
+ };
74
+ }
75
+
76
+ /** Which API style a model is asked in: responses, messages, chat or interactions. */
77
+ open.styleOf = (model) => allPresets.find((p) => p.id === model.via)?.style;
@@ -0,0 +1,212 @@
1
+ // Google Gemini over the Interactions API, for the harness.
2
+ //
3
+ // Every turn runs in the background and is polled, as plain runs do
4
+ // (src/model-apis.js): the request returns at once with an id, so no
5
+ // connection sits silent while the model thinks. That silence is what lost
6
+ // every Gemini run in the first trial.
7
+ //
8
+ // Turns are chained with `previous_interaction_id`: Google keeps the
9
+ // conversation, the model's thoughts and their signatures, and each request
10
+ // carries only what is new (the results of the last reply's calls, with
11
+ // their pictures inside the function result). The tool and
12
+ // `generation_config` apply to one interaction only, so they go with every
13
+ // request. Nothing is deleted until close(), since every later turn reads
14
+ // the ones before it.
15
+ //
16
+ // A reply cut off at its output cap (status `incomplete`) can't be chained
17
+ // to: the API answers "previous_interaction_id must point to a completed
18
+ // interaction". So the next request chains to the last reply that can be,
19
+ // and resends what came after it: what was sent, and the cut-off reply's
20
+ // steps exactly as received, thoughts included. Like the other adapters, a
21
+ // cut-off reply's calls are not run (one may be half a command); each is
22
+ // answered with a note so the replayed conversation stays whole.
23
+ //
24
+ // Facts from the API itself (17 November 2026, gemini-4-hydrogen):
25
+ // - A reply that calls the tool ends with status `requires_action`, not
26
+ // `completed`, and can be chained to.
27
+ // - GET /interactions/{id} lists the steps we sent (user_input,
28
+ // function_result, pictures and all) before the model's own (thought,
29
+ // model_output, function_call). It does not repeat earlier interactions.
30
+ // - Thought steps carry only a signature (no summary unless asked for).
31
+ // - A picture inside a function result is billed as image tokens and the
32
+ // model describes it correctly afterwards.
33
+ // - usage: total_tokens = total_input_tokens + total_output_tokens +
34
+ // total_thought_tokens, so thoughts are not inside total_output_tokens.
35
+ // - A cut-off reply can come back with no model steps at all, just usage.
36
+ // - An `incomplete` reply carries a `continuation_token` that would let the
37
+ // model go on past its cap. It isn't used: the cap is the cap.
38
+ // - DELETE answers 200 `{}`, again for an id already deleted; GET then 404s.
39
+
40
+ import { ProviderError, merge, requestBody, sendJson, statusAt, timing } from '../../src/model-apis.js';
41
+
42
+ // Google's "generation blocked" codes (docs: API errors). One comes as a 400
43
+ // on the request or, in the background, as a failed interaction's error code.
44
+ const BLOCKED = new Set(['safety', 'jailbreak', 'recitation', 'language', 'prohibited_content', 'spii', 'blocklist', 'content_blocked']);
45
+ const blocked = (problem) => [problem?.code, problem?.status, problem?.reason].some((value) => BLOCKED.has(String(value).toLowerCase()));
46
+ const declined = (status, problem) => status === 400 && blocked(problem);
47
+
48
+ const ENDED = new Set(['completed', 'requires_action', 'incomplete']);
49
+ // How often a retry looks again at a reply already asked for before asking afresh.
50
+ const LOOKS = 2;
51
+
52
+ /** The answer to a call of a cut-off reply, which is not run. */
53
+ const NOT_RUN = 'Not run: the reply ended before this call could be made.';
54
+
55
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
56
+ const userInput = (text) => ({ type: 'user_input', content: [{ type: 'text', text }] });
57
+ const isInput = (step) => step.type === 'user_input' || step.type === 'function_result';
58
+
59
+ /** The model's own steps: those after the last one we sent. */
60
+ function modelSteps(steps = []) {
61
+ return steps.slice(steps.findLastIndex(isInput) + 1);
62
+ }
63
+
64
+ // Thought tokens are counted apart from output tokens here (total_tokens =
65
+ // input + output + thought) and billed as output, so `output` is both added
66
+ // together, as harness/prices.mjs prices it. `total_input_tokens` includes
67
+ // the cached ones.
68
+ function usageOf(usage = {}) {
69
+ const reasoning = usage.total_thought_tokens ?? 0;
70
+ return { input: usage.total_input_tokens ?? 0, output: (usage.total_output_tokens ?? 0) + reasoning, cached: usage.total_cached_tokens ?? 0, reasoning };
71
+ }
72
+
73
+ /** One call of a reply, as the loop takes it. */
74
+ function readCall(step, toolName) {
75
+ if (step.name !== toolName) return { id: step.id, error: `There is no tool named "${step.name}", so nothing was run. The only tool is ${toolName}, which takes {"command": "..."}.` };
76
+ const command = step.arguments?.command;
77
+ if (typeof command !== 'string') return { id: step.id, error: `That call had no "command" string, so nothing was run. The tool takes {"command": "..."}. It sent: ${JSON.stringify(step.arguments ?? null).slice(0, 200)}` };
78
+ return { id: step.id, command };
79
+ }
80
+
81
+ export function open({ url, headers, model, effort, maxOutputTokens, extraBody, statusUrl, text, tool }) {
82
+ const at = (id) => statusAt(statusUrl || url, id);
83
+ const declaration = { type: 'function', name: tool.name, description: tool.description, parameters: tool.parameters };
84
+
85
+ let anchor = null; // the last reply the next request can chain to
86
+ let tail = []; // steps since the anchor: cut-off replies and what they answered
87
+ let pending = [userInput(text)]; // what the next request adds
88
+ let names = new Map(); // call id → the function name it used, which its result repeats
89
+ let flight = null; // a reply asked for and not yet read: { id, data, misses }
90
+ const stored = new Set(); // every interaction created, for close()
91
+
92
+ const cancel = (id) => sendJson('POST', `${at(id)}/cancel`, headers, undefined, { retries: 0 }).catch(() => {});
93
+
94
+ function body(input) {
95
+ // A lone first message goes as a string, as a plain run sends it.
96
+ const lone = !anchor && input.length === 1 && input[0].type === 'user_input';
97
+ const plain = requestBody('interactions', { model, text: lone ? input[0].content[0].text : input, maxOutputTokens, effort });
98
+ return merge({ ...plain, ...(anchor && { previous_interaction_id: anchor }), tools: [declaration] }, extraBody);
99
+ }
100
+
101
+ /** Polls the reply in flight until it has ended. Quick at first: most turns are short, and there are thirty of them. */
102
+ async function landed() {
103
+ const started = Date.now();
104
+ for (let polls = 0; !flight.data.declined && flight.data.status === 'in_progress'; polls++) {
105
+ if (Date.now() - started > timing.giveUpMs) {
106
+ const { id } = flight;
107
+ cancel(id);
108
+ flight = null;
109
+ throw new ProviderError(`${model} interaction ${id} was still running after ${timing.giveUpMs / 60000} minutes`);
110
+ }
111
+ await sleep(Math.min(timing.pollMs, 1000 * 2 ** polls));
112
+ flight.data = await sendJson('GET', at(flight.id), headers, undefined, { declined });
113
+ }
114
+ return flight.data;
115
+ }
116
+
117
+ function refused(raw, usage) {
118
+ flight = null;
119
+ return { calls: [], text: '', ended: 'refused', id: raw?.id ?? null, servedModel: raw?.model ?? model, usage: usageOf(usage), raw };
120
+ }
121
+
122
+ async function ask() {
123
+ const sent = [...tail, ...pending];
124
+
125
+ // After a failed poll the reply may still arrive, and a long think is
126
+ // not thrown away for a network blip: look again before asking again.
127
+ if (flight && flight.misses >= LOOKS) {
128
+ cancel(flight.id);
129
+ flight = null;
130
+ }
131
+ if (!flight) {
132
+ const first = await sendJson('POST', url, headers, body(sent), { declined });
133
+ if (first.declined) return refused(first.declined);
134
+ if (!first.id) throw new ProviderError(`Gemini started no interaction: ${JSON.stringify(first).slice(0, 200)}`);
135
+ stored.add(first.id);
136
+ flight = { id: first.id, data: first, misses: 0 };
137
+ }
138
+
139
+ let data;
140
+ try {
141
+ data = await landed();
142
+ } catch (error) {
143
+ if (flight) flight.misses += 1;
144
+ throw error;
145
+ }
146
+ flight = null;
147
+ if (data.declined) return refused(data.declined);
148
+ if (data.status === 'failed' && blocked(data.error)) return refused(data, data.usage);
149
+ if (!ENDED.has(data.status)) {
150
+ throw new ProviderError(`Gemini ended with status "${data.status}"${data.error ? `: ${JSON.stringify(data.error).slice(0, 200)}` : ''}`);
151
+ }
152
+
153
+ const steps = modelSteps(data.steps);
154
+ const called = steps.filter((step) => step.type === 'function_call');
155
+ const cut = data.status === 'incomplete';
156
+
157
+ // The reply is whole: only now does the conversation move on.
158
+ if (cut) {
159
+ const unanswered = called.map((step) => ({ type: 'function_result', name: step.name, call_id: step.id, result: [{ type: 'text', text: NOT_RUN }] }));
160
+ tail = [...sent, ...steps, ...unanswered];
161
+ } else {
162
+ anchor = data.id;
163
+ tail = [];
164
+ }
165
+ pending = [];
166
+ names = new Map(called.map((step) => [step.id, step.name]));
167
+
168
+ // Only a reply that stopped to call the tool has calls to run.
169
+ const calls = cut ? [] : called.map((step) => readCall(step, tool.name));
170
+ return {
171
+ calls,
172
+ text: steps
173
+ .filter((step) => step.type === 'model_output')
174
+ .flatMap((step) => step.content ?? [])
175
+ .filter((part) => part.type === 'text')
176
+ .map((part) => part.text)
177
+ .join(''),
178
+ ended: cut ? 'truncated' : calls.length ? 'calls' : 'complete',
179
+ id: data.id ?? null,
180
+ servedModel: data.model ?? model,
181
+ usage: usageOf(data.usage),
182
+ raw: data,
183
+ };
184
+ }
185
+
186
+ return {
187
+ ask,
188
+
189
+ answer(results) {
190
+ pending = results.map((result) => ({
191
+ type: 'function_result',
192
+ name: names.get(result.id) ?? tool.name,
193
+ call_id: result.id,
194
+ // A picture goes inside the result of the call that made it.
195
+ result: [{ type: 'text', text: result.text || '(no output)' }, ...(result.images ?? []).map((image) => ({ type: 'image', mime_type: image.mime, data: image.data }))],
196
+ }));
197
+ },
198
+
199
+ say(message) {
200
+ pending = [...pending, userInput(message)];
201
+ },
202
+
203
+ async close() {
204
+ try {
205
+ if (flight) await cancel(flight.id);
206
+ flight = null;
207
+ await Promise.all([...stored].map((id) => sendJson('DELETE', at(id), headers, undefined, { retries: 1 }).catch(() => {})));
208
+ stored.clear();
209
+ } catch {}
210
+ },
211
+ };
212
+ }
@@ -0,0 +1,190 @@
1
+ // Anthropic's Messages API: the plain run's request (src/model-apis.js) with
2
+ // the one tool added, and the whole conversation sent again on every turn.
3
+ //
4
+ // The API keeps nothing between requests, so three things are ours to get
5
+ // right:
6
+ // - A reply's blocks go back exactly as they came. A thinking block is signed
7
+ // against everything before it, and a request that changes or drops one in
8
+ // the middle of the conversation is refused.
9
+ // - The last block of each request is marked for the cache, so the next
10
+ // request reads the turns before it at a fraction of the price instead of
11
+ // paying for them again.
12
+ // - Nothing is added to the conversation until a reply has arrived whole, so
13
+ // a dropped connection can simply be asked again.
14
+
15
+ import { ProviderError, eachEvent, merge, request, requestBody } from '../../src/model-apis.js';
16
+
17
+ // Kept for five minutes from the start of the request that wrote or last read
18
+ // it. A reply that takes longer than that to write misses it.
19
+ const CACHE = { type: 'ephemeral' };
20
+
21
+ const ENDED = { tool_use: 'calls', end_turn: 'complete', refusal: 'refused' };
22
+
23
+ const isThinking = (block) => block.type === 'thinking' || block.type === 'redacted_thinking';
24
+
25
+ /** The messages with the cache mark on the last block of the last one, and on no other. */
26
+ function marked(messages) {
27
+ const last = messages.at(-1);
28
+ const content = [...last.content.slice(0, -1), { ...last.content.at(-1), cache_control: CACHE }];
29
+ return [...messages.slice(0, -1), { ...last, content }];
30
+ }
31
+
32
+ /**
33
+ * What can be kept of a reply whose tool calls will get no results (it was
34
+ * cut off, or stopped for another reason): the blocks before its first call,
35
+ * less any thinking left at the end. Cutting from the end leaves the blocks
36
+ * before the cut exactly as the model wrote them.
37
+ */
38
+ function withoutCalls(content) {
39
+ const firstCall = content.findIndex((block) => block.type === 'tool_use');
40
+ const kept = firstCall < 0 ? [...content] : content.slice(0, firstCall);
41
+ while (kept.length && (isThinking(kept.at(-1)) || (kept.at(-1).type === 'text' && !kept.at(-1).text.trim()))) kept.pop();
42
+ return kept;
43
+ }
44
+
45
+ /** Reads a streamed reply into the message a request without `stream` would have returned. */
46
+ async function assemble(response, url) {
47
+ const host = new URL(url).host;
48
+ let message = null;
49
+ const blocks = [];
50
+ const inputs = [];
51
+ await eachEvent(response, url, undefined, (event) => {
52
+ if (event.type === 'error') {
53
+ throw new ProviderError(`${host} stopped the answer: ${event.error?.type ?? 'error'}: ${event.error?.message ?? ''}`.trim());
54
+ }
55
+ if (event.type === 'message_start') {
56
+ message = { ...event.message };
57
+ } else if (event.type === 'content_block_start') {
58
+ blocks[event.index] = { ...event.content_block };
59
+ } else if (event.type === 'content_block_delta') {
60
+ const block = blocks[event.index];
61
+ const delta = event.delta ?? {};
62
+ if (!block) return;
63
+ if (delta.type === 'text_delta') block.text = (block.text ?? '') + delta.text;
64
+ else if (delta.type === 'thinking_delta') block.thinking = (block.thinking ?? '') + delta.thinking;
65
+ else if (delta.type === 'signature_delta') block.signature = delta.signature;
66
+ else if (delta.type === 'input_json_delta') inputs[event.index] = (inputs[event.index] ?? '') + delta.partial_json;
67
+ } else if (event.type === 'message_delta' && message) {
68
+ Object.assign(message, event.delta);
69
+ // Running totals; a count this event leaves out keeps the value it started with.
70
+ const counted = Object.entries(event.usage ?? {}).filter(([, value]) => value != null);
71
+ message.usage = { ...message.usage, ...Object.fromEntries(counted) };
72
+ }
73
+ });
74
+ // Every finished reply says why it stopped; without that the stream was cut.
75
+ if (!message?.stop_reason) throw new ProviderError(`${host} closed the stream before the reply finished`);
76
+ return { message, blocks, inputs };
77
+ }
78
+
79
+ /**
80
+ * One tool call's arguments, as the model wrote them. They arrive as JSON
81
+ * text in pieces and nothing has checked them, so they are read strictly
82
+ * here: half an object is an error, not a shorter command.
83
+ */
84
+ function readCall(block, json) {
85
+ let input = block.input ?? {};
86
+ if (json) {
87
+ try {
88
+ input = JSON.parse(json);
89
+ } catch {
90
+ return { input: {}, error: `The arguments of that call were not valid JSON, so nothing was run. They began: ${json.slice(0, 200)}` };
91
+ }
92
+ }
93
+ if (input === null || typeof input !== 'object' || Array.isArray(input)) {
94
+ return { input: {}, error: 'The arguments of that call were not a JSON object, so nothing was run. The tool takes {"command": "..."}.' };
95
+ }
96
+ if (typeof input.command !== 'string') return { input, error: 'That call had no "command" string, so nothing was run. The tool takes {"command": "..."}.' };
97
+ return { input, command: input.command };
98
+ }
99
+
100
+ export function open({ url, headers, model, effort, maxOutputTokens, extraBody, text, tool }) {
101
+ const tools = [{ name: tool.name, description: tool.description, input_schema: tool.parameters }];
102
+ // The conversation as the API is sent it, less the cache mark.
103
+ const messages = [{ role: 'user', content: [{ type: 'text', text }] }];
104
+ // The last reply's calls whose arguments couldn't be read: their results are errors.
105
+ let unread = new Set();
106
+
107
+ // The plain run's fields, so the two can't drift apart; then the tool and the turns so far.
108
+ const body = () => merge({ ...requestBody('messages', { model, text, maxOutputTokens, effort }), tools, messages: marked(messages) }, extraBody);
109
+
110
+ return {
111
+ async ask() {
112
+ const { response } = await request('POST', url, headers, body(), { timeoutMs: 0 });
113
+ const { message, blocks, inputs } = await assemble(response, url);
114
+
115
+ const ended = ENDED[message.stop_reason] ?? 'truncated';
116
+ const content = [];
117
+ const record = [];
118
+ const calls = [];
119
+ const failed = new Set();
120
+ blocks.forEach((block, index) => {
121
+ if (!block) return;
122
+ if (block.type !== 'tool_use') {
123
+ content.push(block);
124
+ record.push(block);
125
+ return;
126
+ }
127
+ const call = readCall(block, inputs[index]);
128
+ content.push({ ...block, input: call.input });
129
+ // The record keeps arguments that couldn't be read as they arrived.
130
+ record.push({ ...block, input: call.input, ...(call.error && inputs[index] && { partial_json: inputs[index] }) });
131
+ if (call.error) failed.add(block.id);
132
+ calls.push(call.error ? { id: block.id, error: call.error } : { id: block.id, command: call.command });
133
+ });
134
+
135
+ // Only a reply that stopped to call the tool has calls to run. One cut
136
+ // off at its output cap may hold half a command, and none of its calls
137
+ // will be answered, so none can stay in the conversation.
138
+ const called = ended === 'calls';
139
+ const kept = called ? content : ended === 'refused' ? [] : withoutCalls(content);
140
+ if (kept.length) messages.push({ role: 'assistant', content: kept });
141
+ unread = called ? failed : new Set();
142
+
143
+ const counts = message.usage ?? {};
144
+ const cached = counts.cache_read_input_tokens ?? 0;
145
+ return {
146
+ calls: called ? calls : [],
147
+ text: content
148
+ .filter((block) => block.type === 'text')
149
+ .map((block) => block.text)
150
+ .join(''),
151
+ ended,
152
+ id: message.id ?? null,
153
+ servedModel: message.model ?? model,
154
+ usage: {
155
+ // `input_tokens` is only what the cache neither held nor took.
156
+ input: (counts.input_tokens ?? 0) + (counts.cache_creation_input_tokens ?? 0) + cached,
157
+ output: counts.output_tokens ?? 0,
158
+ cached,
159
+ reasoning: counts.output_tokens_details?.thinking_tokens ?? 0,
160
+ },
161
+ raw: { ...message, content: record },
162
+ };
163
+ },
164
+
165
+ // All of a reply's results go in one message: split across several, the
166
+ // model learns to stop making more than one call at a time.
167
+ answer(results) {
168
+ messages.push({
169
+ role: 'user',
170
+ content: results.map((result) => ({
171
+ type: 'tool_result',
172
+ tool_use_id: result.id,
173
+ content: [
174
+ ...(result.text ? [{ type: 'text', text: result.text }] : []),
175
+ ...(result.images ?? []).map((image) => ({ type: 'image', source: { type: 'base64', media_type: image.mime, data: image.data } })),
176
+ ],
177
+ ...(unread.has(result.id) && { is_error: true }),
178
+ })),
179
+ });
180
+ unread = new Set();
181
+ },
182
+
183
+ say(said) {
184
+ messages.push({ role: 'user', content: [{ type: 'text', text: said }] });
185
+ },
186
+
187
+ // Nothing is stored on Anthropic's side to delete.
188
+ async close() {},
189
+ };
190
+ }
@@ -0,0 +1,179 @@
1
+ // The Responses API (OpenAI, xAI): the plain run's request (src/model-apis.js)
2
+ // with the one tool added, and the conversation carried one of two ways.
3
+ //
4
+ // - Chained (when the request runs in the background, as OpenAI's do): a
5
+ // background response has to be stored while it runs, so each request
6
+ // names the one before it with `previous_response_id` and sends only what
7
+ // is new. The server keeps the reasoning and the cached prefix, and
8
+ // nothing is resent. Every stored response is deleted by close(); the
9
+ // shared `background()` helper deletes as soon as it has an answer, which
10
+ // would break the chain, so the waiting is done here.
11
+ // - Replayed (xAI, which streams and stores nothing): every request sends the
12
+ // whole conversation, the model's output items exactly as they came. A
13
+ // reasoning item is only readable on the way back in when the request
14
+ // asked for `reasoning.encrypted_content`; without it the model forgets
15
+ // its own thinking between turns.
16
+ //
17
+ // Either way nothing is added to the conversation until a reply has arrived
18
+ // whole, so a dropped connection can simply be asked again.
19
+
20
+ import { ProviderError, eachEvent, merge, request, requestBody, sendJson, statusAt, timing } from '../../src/model-apis.js';
21
+
22
+ const FINISHED = new Set(['completed', 'incomplete', 'failed', 'cancelled']);
23
+ const running = (data) => data.status === 'queued' || data.status === 'in_progress';
24
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
25
+
26
+ /** Said for a call that was cut off or never got to run, so the conversation stays valid. */
27
+ const NOT_RUN = 'Not run: the reply ended before this call could be made.';
28
+
29
+ const failure = (host, data) => new ProviderError(`${host} ${data.status} the response: ${JSON.stringify(data.error ?? {}).slice(0, 200)}`);
30
+
31
+ /** An item as the API gave it, less any field it gave as null (those are refused when sent back). */
32
+ const asGiven = (item) => Object.fromEntries(Object.entries(item).filter(([, value]) => value !== null));
33
+
34
+ /**
35
+ * One tool call's arguments. They arrive as JSON text and nothing has checked
36
+ * them, so they are read strictly: half an object is an error, not a shorter
37
+ * command.
38
+ */
39
+ function readCall(item, toolName) {
40
+ const id = item.call_id;
41
+ if (item.name !== toolName) return { id, error: `There is no tool named "${item.name}", so nothing was run. The only tool is ${toolName}, which takes {"command": "..."}.` };
42
+ let input;
43
+ try {
44
+ input = JSON.parse(item.arguments);
45
+ } catch {
46
+ return { id, error: `The arguments of that call were not valid JSON, so nothing was run. They began: ${String(item.arguments).slice(0, 200)}` };
47
+ }
48
+ if (input === null || typeof input !== 'object' || Array.isArray(input)) {
49
+ return { id, error: 'The arguments of that call were not a JSON object, so nothing was run. The tool takes {"command": "..."}.' };
50
+ }
51
+ if (typeof input.command !== 'string') return { id, error: 'That call had no "command" string, so nothing was run. The tool takes {"command": "..."}.' };
52
+ return { id, command: input.command };
53
+ }
54
+
55
+ export function open({ url, headers, model, effort, maxOutputTokens, extraBody, background = false, stream = false, asMessages = false, statusUrl, text, tool }) {
56
+ const host = new URL(url).host;
57
+ const tools = [{ type: 'function', name: tool.name, description: tool.description, parameters: tool.parameters }];
58
+ const chained = background;
59
+ const streamed = stream && !background;
60
+
61
+ const first = [{ role: 'user', content: text }];
62
+ // Replayed: everything sent so far and every item the model gave back.
63
+ const history = [];
64
+ // Chained: the last reply's id, which the next request continues from.
65
+ let previous = null;
66
+ // What the next request adds: results, or a user message.
67
+ let pending = first;
68
+ // Calls of the last reply that will get no result from the loop (it was cut off).
69
+ let dangling = [];
70
+ // Every response of ours the provider is holding.
71
+ const stored = new Set();
72
+
73
+ const body = () => {
74
+ // The plain run's fields, so the two can't drift apart; then the tool and the turns so far.
75
+ const plain = requestBody('responses', { model, text, maxOutputTokens, effort, background, stream, asMessages });
76
+ const turns = chained ? { ...(previous && { previous_response_id: previous }), input: pending } : { input: [...history, ...pending], include: ['reasoning.encrypted_content'] };
77
+ return merge({ ...plain, ...turns, tools }, extraBody);
78
+ };
79
+
80
+ /** A response that has been started in the background, waited for. */
81
+ async function wait(data) {
82
+ const at = statusAt(statusUrl || url, data.id);
83
+ const started = Date.now();
84
+ try {
85
+ while (running(data)) {
86
+ if (Date.now() - started > timing.giveUpMs) throw new ProviderError(`${model} response ${data.id} was still running after ${timing.giveUpMs / 60000} minutes`);
87
+ await sleep(timing.pollMs);
88
+ data = await sendJson('GET', at, headers);
89
+ }
90
+ } catch (error) {
91
+ // Tell the provider to stop thinking about something nobody will read.
92
+ sendJson('POST', `${at}/cancel`, headers, undefined, { retries: 0 }).catch(() => {});
93
+ throw error;
94
+ }
95
+ return data;
96
+ }
97
+
98
+ async function send() {
99
+ if (streamed) {
100
+ const { response } = await request('POST', url, headers, body(), { timeoutMs: 0 });
101
+ // A server that ignores `stream` answers with one JSON body after all.
102
+ if (!(response.headers.get('content-type') ?? '').includes('event-stream')) return response.json();
103
+ let data = null;
104
+ await eachEvent(response, url, undefined, (event) => {
105
+ if (event.type === 'error') throw new ProviderError(`${host} sent an error mid-answer: ${String(event.message ?? event.error?.message ?? '').slice(0, 200)}`);
106
+ if (event.response && FINISHED.has(event.response.status)) data = event.response;
107
+ });
108
+ if (!data) throw new ProviderError(`${host} closed the stream without an answer`);
109
+ return data;
110
+ }
111
+ const data = await sendJson('POST', url, headers, body());
112
+ // Stored from the moment it exists, so close() finds it even if waiting fails.
113
+ if (chained && data.id) stored.add(data.id);
114
+ return background && data.id ? wait(data) : data;
115
+ }
116
+
117
+ return {
118
+ async ask() {
119
+ const data = await send();
120
+ if (data.status === 'failed' || data.status === 'cancelled') throw failure(host, data);
121
+ if (!FINISHED.has(data.status)) throw new ProviderError(`${host} gave a response with status "${data.status}"`);
122
+
123
+ const output = data.output ?? [];
124
+ const parts = output.filter((item) => item.type === 'message').flatMap((item) => item.content ?? []);
125
+ const items = output.filter((item) => item.type === 'function_call');
126
+ const refused = parts.some((part) => part.type === 'refusal') || data.incomplete_details?.reason === 'content_filter';
127
+ const ended = refused ? 'refused' : data.status === 'incomplete' ? 'truncated' : items.length ? 'calls' : 'complete';
128
+ const calls = items.map((item) => readCall(item, tool.name));
129
+
130
+ // Only a reply that stopped to call the tool has calls to run. One cut
131
+ // off at its output cap may hold half a command, so none of its calls
132
+ // are run, and the next request answers each with a note instead.
133
+ if (chained) previous = data.id ?? previous;
134
+ else history.push(...pending, ...output.map(asGiven));
135
+ pending = [];
136
+ dangling = ended === 'calls' ? [] : items.map((item) => ({ type: 'function_call_output', call_id: item.call_id, output: NOT_RUN }));
137
+ pending.push(...dangling);
138
+
139
+ const counts = data.usage ?? {};
140
+ return {
141
+ calls: ended === 'calls' ? calls : [],
142
+ text: parts.filter((part) => part.type === 'output_text').map((part) => part.text).join(''),
143
+ ended,
144
+ id: data.id ?? null,
145
+ servedModel: data.model ?? model,
146
+ usage: {
147
+ input: counts.input_tokens ?? 0,
148
+ output: counts.output_tokens ?? 0,
149
+ cached: counts.input_tokens_details?.cached_tokens ?? 0,
150
+ reasoning: counts.output_tokens_details?.reasoning_tokens ?? 0,
151
+ },
152
+ raw: data,
153
+ };
154
+ },
155
+
156
+ // Each result is one function_call_output, its pictures inside it (both
157
+ // OpenAI and xAI take them there and the model sees them).
158
+ answer(results) {
159
+ pending = results.map((result) => ({
160
+ type: 'function_call_output',
161
+ call_id: result.id,
162
+ output: [
163
+ { type: 'input_text', text: result.text || '(no output)' },
164
+ ...(result.images ?? []).map((image) => ({ type: 'input_image', image_url: `data:${image.mime};base64,${image.data}` })),
165
+ ],
166
+ }));
167
+ dangling = [];
168
+ },
169
+
170
+ say(said) {
171
+ pending = [...pending, { role: 'user', content: said }];
172
+ },
173
+
174
+ async close() {
175
+ await Promise.all([...stored].map((id) => sendJson('DELETE', statusAt(statusUrl || url, id), headers, undefined, { retries: 1 }).catch(() => {})));
176
+ stored.clear();
177
+ },
178
+ };
179
+ }