@dereekb/openrouter 13.38.0 → 13.40.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/index.cjs.js DELETED
@@ -1,1867 +0,0 @@
1
- 'use strict';
2
-
3
- var util = require('@dereekb/util');
4
- var callModel = require('@openrouter/sdk/funcs/call-model');
5
- var responsesSend = require('@openrouter/sdk/funcs/responsesSend');
6
- var conversationState = require('@openrouter/sdk/lib/conversation-state');
7
- var embeddingsGenerate = require('@openrouter/sdk/funcs/embeddingsGenerate');
8
- var generationsGetGeneration = require('@openrouter/sdk/funcs/generationsGetGeneration');
9
- var generationsListGenerationContent = require('@openrouter/sdk/funcs/generationsListGenerationContent');
10
- var modelResult = require('@openrouter/sdk/lib/model-result');
11
- var tool = require('@openrouter/sdk/lib/tool');
12
- var toolExecutor = require('@openrouter/sdk/lib/tool-executor');
13
- var stopConditions = require('@openrouter/sdk/lib/stop-conditions');
14
- var toolTypes = require('@openrouter/sdk/lib/tool-types');
15
-
16
- function _array_like_to_array$1(arr, len) {
17
- if (len == null || len > arr.length) len = arr.length;
18
- for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
19
- return arr2;
20
- }
21
- function _array_without_holes$1(arr) {
22
- if (Array.isArray(arr)) return _array_like_to_array$1(arr);
23
- }
24
- function asyncGeneratorStep$2(gen, resolve, reject, _next, _throw, key, arg) {
25
- try {
26
- var info = gen[key](arg);
27
- var value = info.value;
28
- } catch (error) {
29
- reject(error);
30
- return;
31
- }
32
- if (info.done) {
33
- resolve(value);
34
- } else {
35
- Promise.resolve(value).then(_next, _throw);
36
- }
37
- }
38
- function _async_to_generator$2(fn) {
39
- return function() {
40
- var self = this, args = arguments;
41
- return new Promise(function(resolve, reject) {
42
- var gen = fn.apply(self, args);
43
- function _next(value) {
44
- asyncGeneratorStep$2(gen, resolve, reject, _next, _throw, "next", value);
45
- }
46
- function _throw(err) {
47
- asyncGeneratorStep$2(gen, resolve, reject, _next, _throw, "throw", err);
48
- }
49
- _next(undefined);
50
- });
51
- };
52
- }
53
- function _define_property$2(obj, key, value) {
54
- if (key in obj) {
55
- Object.defineProperty(obj, key, {
56
- value: value,
57
- enumerable: true,
58
- configurable: true,
59
- writable: true
60
- });
61
- } else {
62
- obj[key] = value;
63
- }
64
- return obj;
65
- }
66
- function _iterable_to_array$1(iter) {
67
- if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
68
- }
69
- function _non_iterable_spread$1() {
70
- throw new TypeError("Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
71
- }
72
- function _object_spread$2(target) {
73
- for(var i = 1; i < arguments.length; i++){
74
- var source = arguments[i] != null ? arguments[i] : {};
75
- var ownKeys = Object.keys(source);
76
- if (typeof Object.getOwnPropertySymbols === "function") {
77
- ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
78
- return Object.getOwnPropertyDescriptor(source, sym).enumerable;
79
- }));
80
- }
81
- ownKeys.forEach(function(key) {
82
- _define_property$2(target, key, source[key]);
83
- });
84
- }
85
- return target;
86
- }
87
- function ownKeys$1(object, enumerableOnly) {
88
- var keys = Object.keys(object);
89
- if (Object.getOwnPropertySymbols) {
90
- var symbols = Object.getOwnPropertySymbols(object);
91
- keys.push.apply(keys, symbols);
92
- }
93
- return keys;
94
- }
95
- function _object_spread_props$1(target, source) {
96
- source = source != null ? source : {};
97
- if (Object.getOwnPropertyDescriptors) {
98
- Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
99
- } else {
100
- ownKeys$1(Object(source)).forEach(function(key) {
101
- Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
102
- });
103
- }
104
- return target;
105
- }
106
- function _object_without_properties$1(source, excluded) {
107
- if (source == null) return {};
108
- var target = {}, sourceKeys, key, i;
109
- if (typeof Reflect !== "undefined" && Reflect.ownKeys) {
110
- sourceKeys = Reflect.ownKeys(Object(source));
111
- for(i = 0; i < sourceKeys.length; i++){
112
- key = sourceKeys[i];
113
- if (excluded.indexOf(key) >= 0) continue;
114
- if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
115
- target[key] = source[key];
116
- }
117
- return target;
118
- }
119
- target = _object_without_properties_loose$1(source, excluded);
120
- if (Object.getOwnPropertySymbols) {
121
- sourceKeys = Object.getOwnPropertySymbols(source);
122
- for(i = 0; i < sourceKeys.length; i++){
123
- key = sourceKeys[i];
124
- if (excluded.indexOf(key) >= 0) continue;
125
- if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
126
- target[key] = source[key];
127
- }
128
- }
129
- return target;
130
- }
131
- function _object_without_properties_loose$1(source, excluded) {
132
- if (source == null) return {};
133
- var target = {}, sourceKeys = Object.getOwnPropertyNames(source), key, i;
134
- for(i = 0; i < sourceKeys.length; i++){
135
- key = sourceKeys[i];
136
- if (excluded.indexOf(key) >= 0) continue;
137
- if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
138
- target[key] = source[key];
139
- }
140
- return target;
141
- }
142
- function _to_consumable_array$1(arr) {
143
- return _array_without_holes$1(arr) || _iterable_to_array$1(arr) || _unsupported_iterable_to_array$1(arr) || _non_iterable_spread$1();
144
- }
145
- function _type_of(obj) {
146
- "@swc/helpers - typeof";
147
- return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj;
148
- }
149
- function _unsupported_iterable_to_array$1(o, minLen) {
150
- if (!o) return;
151
- if (typeof o === "string") return _array_like_to_array$1(o, minLen);
152
- var n = Object.prototype.toString.call(o).slice(8, -1);
153
- if (n === "Object" && o.constructor) n = o.constructor.name;
154
- if (n === "Map" || n === "Set") return Array.from(n);
155
- if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array$1(o, minLen);
156
- }
157
- function _ts_generator$2(thisArg, body) {
158
- var f, y, t, _ = {
159
- label: 0,
160
- sent: function() {
161
- if (t[0] & 1) throw t[1];
162
- return t[1];
163
- },
164
- trys: [],
165
- ops: []
166
- }, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype), d = Object.defineProperty;
167
- return d(g, "next", {
168
- value: verb(0)
169
- }), d(g, "throw", {
170
- value: verb(1)
171
- }), d(g, "return", {
172
- value: verb(2)
173
- }), typeof Symbol === "function" && d(g, Symbol.iterator, {
174
- value: function() {
175
- return this;
176
- }
177
- }), g;
178
- function verb(n) {
179
- return function(v) {
180
- return step([
181
- n,
182
- v
183
- ]);
184
- };
185
- }
186
- function step(op) {
187
- if (f) throw new TypeError("Generator is already executing.");
188
- while(g && (g = 0, op[0] && (_ = 0)), _)try {
189
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
190
- if (y = 0, t) op = [
191
- op[0] & 2,
192
- t.value
193
- ];
194
- switch(op[0]){
195
- case 0:
196
- case 1:
197
- t = op;
198
- break;
199
- case 4:
200
- _.label++;
201
- return {
202
- value: op[1],
203
- done: false
204
- };
205
- case 5:
206
- _.label++;
207
- y = op[1];
208
- op = [
209
- 0
210
- ];
211
- continue;
212
- case 7:
213
- op = _.ops.pop();
214
- _.trys.pop();
215
- continue;
216
- default:
217
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
218
- _ = 0;
219
- continue;
220
- }
221
- if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
222
- _.label = op[1];
223
- break;
224
- }
225
- if (op[0] === 6 && _.label < t[1]) {
226
- _.label = t[1];
227
- t = op;
228
- break;
229
- }
230
- if (t && _.label < t[2]) {
231
- _.label = t[2];
232
- _.ops.push(op);
233
- break;
234
- }
235
- if (t[2]) _.ops.pop();
236
- _.trys.pop();
237
- continue;
238
- }
239
- op = body.call(thisArg, _);
240
- } catch (e) {
241
- op = [
242
- 6,
243
- e
244
- ];
245
- y = 0;
246
- } finally{
247
- f = t = 0;
248
- }
249
- if (op[0] & 5) throw op[1];
250
- return {
251
- value: op[0] ? op[1] : void 0,
252
- done: true
253
- };
254
- }
255
- }
256
- /**
257
- * Splits a model config into request parameters and execution controls.
258
- *
259
- * Forwarding one of ours is not harmless: OpenRouter validates the request body, so leaving `maxSteps` on
260
- * it risks a 400 on the whole call. Which keys are ours is expressed by naming them in a rest-destructure
261
- * rather than in a list of strings, so TypeScript checks the names against
262
- * {@link OpenRouterModelConfig} and a rename cannot leave a stale entry behind.
263
- *
264
- * @param config - The merged model config.
265
- * @returns The split config.
266
- */ function splitOpenRouterModelConfig(config) {
267
- var _ref = config !== null && config !== void 0 ? config : {}, maxSteps = _ref.maxSteps, requestTimeoutMs = _ref.requestTimeoutMs, rest = _object_without_properties$1(_ref, [
268
- "maxSteps",
269
- "requestTimeoutMs"
270
- ]);
271
- return {
272
- requestConfig: util.filterUndefinedValues(rest),
273
- maxSteps: maxSteps,
274
- requestTimeoutMs: requestTimeoutMs
275
- };
276
- }
277
- /**
278
- * The hosted (server-executed) tool entries a config carries, e.g. `file_search`, `web_search`, `mcp`.
279
- *
280
- * These are NOT client tools and must never be handed to `callModel`: it destructures `tools` off the
281
- * request and runs every entry through `convertToolsToAPIFormat`, which reads `tool.function.name` — so
282
- * a hosted entry is dropped outright when no client tools are present and throws a
283
- * `Cannot read properties of undefined` from inside the SDK when they are. They are dispatched instead
284
- * by {@link sendOpenRouterResponsesRequest} or merged in after conversion by
285
- * {@link openRouterModelResultForRequest}.
286
- *
287
- * @param config - The merged model config.
288
- * @returns The hosted tool entries, or an empty array.
289
- *
290
- * @__NO_SIDE_EFFECTS__
291
- */ function openRouterHostedTools(config) {
292
- var tools = config === null || config === void 0 ? void 0 : config.tools;
293
- return Array.isArray(tools) ? tools : [];
294
- }
295
- /**
296
- * Converts a built request into the `/responses` request body.
297
- *
298
- * This is the whole wire body minus the SDK-only keys (`tools`/`state`/`stopWhen` on the `callModel`
299
- * path), so both dispatch paths assemble the request the same way and cannot drift.
300
- *
301
- * @param request - The built request.
302
- * @returns The request body, in the SDK's camelCase request surface.
303
- */ function openRouterResponsesRequestBody(request) {
304
- var requestConfig = splitOpenRouterModelConfig(request.config).requestConfig;
305
- return util.filterUndefinedValues(_object_spread_props$1(_object_spread$2({}, requestConfig), {
306
- input: request.input,
307
- instructions: request.instructions || undefined,
308
- trace: request.trace == null ? undefined : {
309
- additionalProperties: _object_spread$2({}, request.trace)
310
- }
311
- }));
312
- }
313
- /**
314
- * Converts a built request into the `callModel` input.
315
- *
316
- * Any hosted tools on the config are STRIPPED here rather than passed through: `callModel` owns the
317
- * `tools` key and converts every entry as a client function tool. Hosted entries are re-attached after
318
- * that conversion by {@link openRouterModelResultForRequest}.
319
- *
320
- * @param params - The request, tools, and state accessor.
321
- * @returns The `callModel` input.
322
- */ function openRouterCallModelInput(params) {
323
- var request = params.request, tools = params.tools, state = params.state;
324
- var maxSteps = splitOpenRouterModelConfig(request.config).maxSteps;
325
- // dropped by name rather than by mutation, so TypeScript sees which keys leave the body: the hosted
326
- // tools `callModel` cannot carry, and a config-set `stream` the non-streaming path must not inherit.
327
- var _openRouterResponsesRequestBody = openRouterResponsesRequestBody(request); _openRouterResponsesRequestBody.tools; _openRouterResponsesRequestBody.stream; var body = _object_without_properties$1(_openRouterResponsesRequestBody, [
328
- "tools",
329
- "stream"
330
- ]);
331
- var input = util.filterUndefinedValues(_object_spread_props$1(_object_spread$2({}, body), {
332
- tools: tools !== null && tools !== void 0 ? tools : undefined,
333
- state: state !== null && state !== void 0 ? state : undefined,
334
- stopWhen: maxSteps == null ? undefined : stopConditions.stepCountIs(maxSteps)
335
- }));
336
- return input;
337
- }
338
- /**
339
- * Header `callModel` stamps on every request it dispatches, so OpenRouter can tell an agent-loop request
340
- * apart from a plain one. Replicated on the merged hosted-tool path, which is a `callModel` request in
341
- * everything but the entry point.
342
- */ var OPENROUTER_CALL_MODEL_HEADER = 'x-openrouter-callmodel';
343
- /**
344
- * Builds the request options for a call, folding in the config's `requestTimeoutMs`.
345
- *
346
- * @param options - Caller-supplied options.
347
- * @param requestTimeoutMs - The per-request timeout from the config, when it set one.
348
- * @returns The merged options.
349
- */ function openRouterRequestOptions(options, requestTimeoutMs) {
350
- return _object_spread$2({}, options, requestTimeoutMs == null ? undefined : {
351
- timeoutMs: requestTimeoutMs
352
- });
353
- }
354
- /**
355
- * Copies request options and stamps the `x-openrouter-callmodel` header onto them.
356
- *
357
- * Both header sources are read for the same reason `callModel` reads both: the SDK resolves
358
- * `options.headers ?? options.fetchOptions.headers`, so setting `headers` alone would SHADOW a caller
359
- * who passed theirs through the (deprecated) `fetchOptions` instead of losing nothing.
360
- *
361
- * @param options - The request options.
362
- * @returns Options carrying the caller's headers plus the callModel marker.
363
- */ function openRouterCallModelRequestOptions(options) {
364
- var _ref, _options_headers;
365
- var _options_fetchOptions;
366
- // eslint-disable-next-line @typescript-eslint/no-deprecated
367
- var headers = new Headers((_ref = (_options_headers = options.headers) !== null && _options_headers !== void 0 ? _options_headers : (_options_fetchOptions = options.fetchOptions) === null || _options_fetchOptions === void 0 ? void 0 : _options_fetchOptions.headers) !== null && _ref !== void 0 ? _ref : undefined);
368
- headers.set(OPENROUTER_CALL_MODEL_HEADER, 'true');
369
- return _object_spread_props$1(_object_spread$2({}, options), {
370
- headers: headers
371
- });
372
- }
373
- /**
374
- * Sends a built request straight to `/responses`, bypassing `callModel` entirely.
375
- *
376
- * This is the path hosted (server-executed) tools take. `callModel` cannot carry them — it converts
377
- * every `tools` entry as a client function tool — and there is nothing for its loop to do on a run whose
378
- * tools are executed upstream anyway. Going direct also keeps the response VERBATIM: the request is
379
- * non-streaming, so the returned `OpenResponsesResult` is the body OpenRouter sent rather than one
380
- * reassembled from stream events, which is what preserves hosted-tool output items such as a
381
- * `file_search_call` and the chunks `include: ['file_search_call.results']` asked for.
382
- *
383
- * @param params - The client, request, and options.
384
- * @returns The response.
385
- * @throws {Error} When the request fails, or when a streaming response comes back for a non-streaming request.
386
- */ function sendOpenRouterResponsesRequest(params) {
387
- return _async_to_generator$2(function() {
388
- var client, request, options, requestTimeoutMs, responsesRequest, result;
389
- return _ts_generator$2(this, function(_state) {
390
- switch(_state.label){
391
- case 0:
392
- client = params.client, request = params.request, options = params.options;
393
- requestTimeoutMs = splitOpenRouterModelConfig(request.config).requestTimeoutMs;
394
- responsesRequest = _object_spread_props$1(_object_spread$2({}, openRouterResponsesRequestBody(request)), {
395
- stream: false
396
- });
397
- return [
398
- 4,
399
- responsesSend.responsesSend(client, {
400
- responsesRequest: responsesRequest
401
- }, openRouterRequestOptions(options, requestTimeoutMs))
402
- ];
403
- case 1:
404
- result = _state.sent();
405
- if (!result.ok) {
406
- throw result.error;
407
- }
408
- // `stream: false` narrows the SDK's response union by contract only, so the narrowing is asserted
409
- // rather than assumed: an event stream read as a result yields a value whose every field is undefined,
410
- // which a caller would store as a successful call that produced nothing.
411
- if (typeof result.value[Symbol.asyncIterator] === 'function') {
412
- throw new TypeError('OpenRouter returned a streaming response for a non-streaming `/responses` request.');
413
- }
414
- return [
415
- 2,
416
- result.value
417
- ];
418
- }
419
- });
420
- })();
421
- }
422
- /**
423
- * Starts a call for a built request and returns the SDK's `ModelResult` without consuming it.
424
- *
425
- * Use this when the caller needs the streaming / tool-event surface. Most callers want
426
- * {@link callModelForOpenRouterRequest}, which consumes the result into a normalized value.
427
- *
428
- * Hosted tools and client tools are NOT mutually exclusive here. When a config carries hosted tools this
429
- * assembles the `ModelResult` itself — client tools converted to API format exactly as `callModel` would,
430
- * with the hosted entries appended after that conversion — so a run can search a vector store AND drive
431
- * the client-side tool loop. `callModel` cannot express that: it owns the `tools` key and there is no
432
- * seam between its conversion and dispatch. Everything else about the run is unchanged, including the
433
- * `x-openrouter-callmodel` header and the `stopWhen` step ceiling.
434
- *
435
- * @param params - The client, request, tools, state, and options.
436
- * @returns The in-flight model result.
437
- */ function openRouterModelResultForRequest(params) {
438
- var client = params.client, request = params.request, tools = params.tools, state = params.state, options = params.options;
439
- var _splitOpenRouterModelConfig = splitOpenRouterModelConfig(request.config), maxSteps = _splitOpenRouterModelConfig.maxSteps, requestTimeoutMs = _splitOpenRouterModelConfig.requestTimeoutMs;
440
- var requestOptions = openRouterRequestOptions(options, requestTimeoutMs);
441
- var hostedTools = openRouterHostedTools(request.config);
442
- var result;
443
- if (hostedTools.length === 0) {
444
- result = callModel.callModel(client, openRouterCallModelInput(params), requestOptions);
445
- } else {
446
- // `stream` is dropped by name, exactly as the `callModel` path drops it, so neither path can inherit
447
- // a config-set value.
448
- var _openRouterResponsesRequestBody = openRouterResponsesRequestBody(request); _openRouterResponsesRequestBody.stream; var body = _object_without_properties$1(_openRouterResponsesRequestBody, [
449
- "stream"
450
- ]);
451
- var apiRequest = _object_spread_props$1(_object_spread$2({}, body), {
452
- tools: _to_consumable_array$1(tools == null ? [] : toolExecutor.convertToolsToAPIFormat(tools)).concat(_to_consumable_array$1(hostedTools))
453
- });
454
- result = new modelResult.ModelResult(_object_spread$2({
455
- client: client,
456
- request: apiRequest,
457
- options: openRouterCallModelRequestOptions(requestOptions)
458
- }, tools == null ? undefined : {
459
- tools: tools
460
- }, state == null ? undefined : {
461
- state: state
462
- }, maxSteps == null ? undefined : {
463
- stopWhen: stopConditions.stepCountIs(maxSteps)
464
- }));
465
- }
466
- return result;
467
- }
468
- /**
469
- * Runs a built request to completion and normalizes the response.
470
- *
471
- * Routes to the direct `/responses` path for a hosted-tool run that needs no client-side tool loop, and
472
- * to `ModelResult` otherwise. The caller does not choose: which transport a request needs is a property
473
- * of the request, and making it a parameter would only create a way to get it wrong.
474
- *
475
- * @param params - The client, request, tools, state, and options.
476
- * @returns The normalized call result.
477
- */ function callModelForOpenRouterRequest(params) {
478
- return _async_to_generator$2(function() {
479
- var _ref, _params_tools, needsClientToolLoop, sendDirect, response, _tmp;
480
- return _ts_generator$2(this, function(_state) {
481
- switch(_state.label){
482
- case 0:
483
- // Client tools and a `StateAccessor` both live on `ModelResult`, so a run using either needs the loop
484
- // that executes tools and round-trips conversation state — even when its hosted tools would otherwise
485
- // qualify it for the direct path.
486
- needsClientToolLoop = ((_ref = (_params_tools = params.tools) === null || _params_tools === void 0 ? void 0 : _params_tools.length) !== null && _ref !== void 0 ? _ref : 0) > 0 || params.state != null;
487
- sendDirect = openRouterHostedTools(params.request.config).length > 0 && !needsClientToolLoop;
488
- if (!sendDirect) return [
489
- 3,
490
- 2
491
- ];
492
- return [
493
- 4,
494
- sendOpenRouterResponsesRequest(params)
495
- ];
496
- case 1:
497
- _tmp = _state.sent();
498
- return [
499
- 3,
500
- 4
501
- ];
502
- case 2:
503
- return [
504
- 4,
505
- openRouterModelResultForRequest(params).getResponse()
506
- ];
507
- case 3:
508
- _tmp = _state.sent();
509
- _state.label = 4;
510
- case 4:
511
- response = _tmp;
512
- return [
513
- 2,
514
- openRouterCallResultFromResponse(response)
515
- ];
516
- }
517
- });
518
- })();
519
- }
520
- /**
521
- * Normalizes an OpenRouter response into an {@link OpenRouterCallResult}.
522
- *
523
- * @param response - The response to normalize.
524
- * @returns The normalized result.
525
- */ function openRouterCallResultFromResponse(response) {
526
- var outputText = openRouterOutputTextFromResponse(response);
527
- var usage = response.usage;
528
- return {
529
- outputText: outputText,
530
- outputJson: parseOpenRouterJsonOutput(outputText),
531
- generationIds: response.id ? [
532
- response.id
533
- ] : [],
534
- usage: usage == null ? undefined : openRouterRunUsageFromResponseUsage(usage),
535
- model: response.model,
536
- error: response.error == null ? undefined : openRouterRunErrorFromResponseError(response.error),
537
- response: response
538
- };
539
- }
540
- /**
541
- * Reads the assistant text out of a response.
542
- *
543
- * The convenience `output_text` field is NOT populated by OpenRouter's `/responses` API — verified live,
544
- * on both a streaming and a non-streaming request: the body carries `output` items (`reasoning`, then
545
- * `message`) and no `output_text` at all. Reading that field alone therefore returns undefined for every
546
- * real call, so a run task would store an empty `o` on a call that answered perfectly well and was
547
- * charged for.
548
- *
549
- * Text is concatenated across ALL message items rather than just the first, since nothing guarantees a
550
- * response is limited to one.
551
- *
552
- * @param response - The response.
553
- * @returns The output text, or undefined when the response carried none.
554
- */ function openRouterOutputTextFromResponse(response) {
555
- var result = response.outputText;
556
- if (!result) {
557
- var _response_output;
558
- var text = ((_response_output = response.output) !== null && _response_output !== void 0 ? _response_output : []).filter(function(item) {
559
- return item.type === 'message';
560
- }).flatMap(function(item) {
561
- var _item_content;
562
- return (_item_content = item.content) !== null && _item_content !== void 0 ? _item_content : [];
563
- }).filter(function(part) {
564
- return part.type === 'output_text';
565
- }).map(function(part) {
566
- var _part_text;
567
- return (_part_text = part.text) !== null && _part_text !== void 0 ? _part_text : '';
568
- }).join('');
569
- result = text || undefined;
570
- }
571
- return result;
572
- }
573
- /**
574
- * Flattens the SDK's nested usage object.
575
- *
576
- * A measurement the response did not report is OMITTED rather than carried as `undefined` or `null`.
577
- *
578
- * @param usage - The SDK usage object.
579
- * @returns The flattened usage.
580
- *
581
- * @__NO_SIDE_EFFECTS__
582
- */ function openRouterRunUsageFromResponseUsage(usage) {
583
- var inputTokens = usage.inputTokens, outputTokens = usage.outputTokens, totalTokens = usage.totalTokens, cost = usage.cost, isByok = usage.isByok, inputTokensDetails = usage.inputTokensDetails, outputTokensDetails = usage.outputTokensDetails;
584
- return util.filterUndefinedValues({
585
- inputTokens: inputTokens,
586
- outputTokens: outputTokens,
587
- totalTokens: totalTokens,
588
- reasoningTokens: outputTokensDetails === null || outputTokensDetails === void 0 ? void 0 : outputTokensDetails.reasoningTokens,
589
- cachedTokens: inputTokensDetails === null || inputTokensDetails === void 0 ? void 0 : inputTokensDetails.cachedTokens,
590
- cost: cost,
591
- isByok: isByok
592
- }, true);
593
- }
594
- /**
595
- * Flattens the error an OpenRouter response reports in its body.
596
- *
597
- * Named rather than inlined at the one call site for the same reason
598
- * {@link openRouterRunUsageFromResponseUsage} is: a library that exports `OpenRouterRunError` as a type
599
- * should let a caller holding a raw `OpenResponsesResult` produce one without transcribing its shape.
600
- *
601
- * `code` goes through `String()` because OpenRouter reports a NUMERIC code here (the HTTP status), while
602
- * `OpenRouterRunError.code` is a string — the same field an SDK-thrown error fills with `ECONNRESET`.
603
- *
604
- * @param error - The error reported on the response.
605
- * @returns The flattened error.
606
- *
607
- * @__NO_SIDE_EFFECTS__
608
- */ function openRouterRunErrorFromResponseError(error) {
609
- var code = error.code, message = error.message;
610
- return {
611
- code: code == null ? undefined : String(code),
612
- message: message
613
- };
614
- }
615
- /**
616
- * Parses model output as a JSON object.
617
- *
618
- * Returns undefined rather than throwing on anything that is not a JSON object: a model asked for
619
- * text can and will return prose, and that is not an error.
620
- *
621
- * @param outputText - The output text.
622
- * @returns The parsed object, or undefined when the output is not a JSON object.
623
- */ function parseOpenRouterJsonOutput(outputText) {
624
- var result;
625
- if (outputText) {
626
- try {
627
- var parsed = JSON.parse(outputText);
628
- if (parsed != null && (typeof parsed === "undefined" ? "undefined" : _type_of(parsed)) === 'object' && !Array.isArray(parsed)) {
629
- result = parsed;
630
- }
631
- } catch (unused) {
632
- // not JSON — leave undefined
633
- }
634
- }
635
- return result;
636
- }
637
-
638
- function _define_property$1(obj, key, value) {
639
- if (key in obj) {
640
- Object.defineProperty(obj, key, {
641
- value: value,
642
- enumerable: true,
643
- configurable: true,
644
- writable: true
645
- });
646
- } else {
647
- obj[key] = value;
648
- }
649
- return obj;
650
- }
651
- function _object_spread$1(target) {
652
- for(var i = 1; i < arguments.length; i++){
653
- var source = arguments[i] != null ? arguments[i] : {};
654
- var ownKeys = Object.keys(source);
655
- if (typeof Object.getOwnPropertySymbols === "function") {
656
- ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
657
- return Object.getOwnPropertyDescriptor(source, sym).enumerable;
658
- }));
659
- }
660
- ownKeys.forEach(function(key) {
661
- _define_property$1(target, key, source[key]);
662
- });
663
- }
664
- return target;
665
- }
666
- /**
667
- * Builds a hosted `file_search` tool entry with the field names the SDK actually forwards.
668
- *
669
- * @param vectorStoreIds - The `vs_…` ids to search.
670
- * @param maxNumResults - Optional cap on returned chunks.
671
- * @returns The hosted tool entry.
672
- *
673
- * @__NO_SIDE_EFFECTS__
674
- */ function openRouterFileSearchTool(vectorStoreIds, maxNumResults) {
675
- return _object_spread$1({
676
- type: 'file_search',
677
- vectorStoreIds: vectorStoreIds
678
- }, maxNumResults == null ? undefined : {
679
- maxNumResults: maxNumResults
680
- });
681
- }
682
- /**
683
- * The default PDF parser engine this package pins.
684
- *
685
- * Pinned because the alternative is silent: with no engine named, OpenRouter downgrades any model it
686
- * believes lacks native file support to `mistral-ocr`, inheriting its 8-image cap and per-page billing with
687
- * no error — which on a multi-page document quietly truncates content.
688
- *
689
- * `native` rather than the equally-free `pdf-text` because it fails LOUDLY. It requires a model with
690
- * native file input and 400s on one without, where `pdf-text` would hand a scanned PDF to the model as
691
- * empty text and let it answer ungrounded. A caller on a text-only model wants
692
- * `openRouterFileParserPlugin('pdf-text')` — see {@link OpenRouterPdfParserEngine}.
693
- */ var DEFAULT_OPENROUTER_PDF_PARSER_ENGINE = 'native';
694
- /**
695
- * The `file-parser` plugin entry with the PDF engine pinned.
696
- *
697
- * @param engine - Engine to pin. Defaults to {@link DEFAULT_OPENROUTER_PDF_PARSER_ENGINE}.
698
- * @returns The plugin config entry.
699
- *
700
- * @__NO_SIDE_EFFECTS__
701
- */ function openRouterFileParserPlugin() {
702
- var engine = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : DEFAULT_OPENROUTER_PDF_PARSER_ENGINE;
703
- return {
704
- id: 'file-parser',
705
- pdf: {
706
- engine: engine
707
- }
708
- };
709
- }
710
- /**
711
- * A provider config that pins routing to a single provider with fallbacks off and parameter support
712
- * required — the configuration that makes a BYOK request actually reach the intended upstream with
713
- * every parameter intact.
714
- *
715
- * @param provider - The provider slug to pin to (e.g. `openai`).
716
- * @returns The provider routing config.
717
- *
718
- * @__NO_SIDE_EFFECTS__
719
- */ function openRouterProviderPinnedTo(provider) {
720
- return {
721
- only: [
722
- provider
723
- ],
724
- allowFallbacks: false,
725
- requireParameters: true
726
- };
727
- }
728
- /**
729
- * Merges model configs left-to-right, so the last input wins.
730
- *
731
- * Merging is SHALLOW by key: an override that supplies `provider` replaces the whole provider object
732
- * rather than merging into it. That is the behaviour a caller wants — a half-overridden `provider`
733
- * (say, `only` from the override and `allowFallbacks` from the version) is a configuration nobody
734
- * wrote down and nobody can reason about.
735
- *
736
- * `undefined` values do not overwrite; an explicit `null` does (it is how a caller clears a value
737
- * the version set).
738
- *
739
- * @param configs - Configs to merge, lowest priority first.
740
- * @returns The merged config.
741
- */ function mergeOpenRouterModelConfig(configs) {
742
- return util.mergeObjects(configs);
743
- }
744
- /**
745
- * Validates a merged model config, catching the misconfigurations that fail silently at runtime
746
- * rather than loudly.
747
- *
748
- * @param config - The merged config to check.
749
- * @returns The validation result.
750
- */ function validateOpenRouterModelConfig(config) {
751
- var errors = [];
752
- var warnings = [];
753
- if (config == null) {
754
- errors.push('No model config was provided.');
755
- } else {
756
- var _ref;
757
- var _config_models, _config_text, _config_plugins, _fileParser_pdf, _config_tools, _config_tools1, _config_provider, _config_provider_only, _config_provider1;
758
- if (!config.model && !((_config_models = config.models) === null || _config_models === void 0 ? void 0 : _config_models.length)) {
759
- errors.push('No `model` (or `models` fallback chain) was specified.');
760
- }
761
- var format = (_config_text = config.text) === null || _config_text === void 0 ? void 0 : _config_text.format;
762
- if ((format === null || format === void 0 ? void 0 : format.type) === 'json_schema') {
763
- if (!format.name) {
764
- errors.push('A `json_schema` text format requires a `name`.');
765
- }
766
- if (!format.schema) {
767
- errors.push('A `json_schema` text format requires a `schema`.');
768
- }
769
- }
770
- var fileParser = (_config_plugins = config.plugins) === null || _config_plugins === void 0 ? void 0 : _config_plugins.find(function(x) {
771
- return x.id === 'file-parser';
772
- });
773
- if (fileParser != null && !((_fileParser_pdf = fileParser.pdf) === null || _fileParser_pdf === void 0 ? void 0 : _fileParser_pdf.engine)) {
774
- warnings.push('The `file-parser` plugin has no pinned `pdf.engine`; OpenRouter will silently fall back to `mistral-ocr` (8-image cap, per-page billing) on any model it believes lacks native file support.');
775
- }
776
- var hasHostedTools = ((_ref = (_config_tools = config.tools) === null || _config_tools === void 0 ? void 0 : _config_tools.length) !== null && _ref !== void 0 ? _ref : 0) > 0;
777
- var fileSearchWithoutStores = (_config_tools1 = config.tools) === null || _config_tools1 === void 0 ? void 0 : _config_tools1.some(function(x) {
778
- return x.type === 'file_search' && !Array.isArray(x['vectorStoreIds']);
779
- });
780
- if (fileSearchWithoutStores) {
781
- // The SDK drops an unrecognized field (a `vector_store_ids` authored in wire case, say) during
782
- // outbound serialization, leaving a tool that searches nothing and a model that answers ungrounded
783
- // with no error at all. That is exactly the failure worth refusing to publish.
784
- errors.push('A `file_search` hosted tool requires a `vectorStoreIds` array. Note the CAMELCASE — the SDK drops the wire-cased `vector_store_ids`, leaving a tool that searches nothing.');
785
- }
786
- if (hasHostedTools && ((_config_provider = config.provider) === null || _config_provider === void 0 ? void 0 : _config_provider.requireParameters) !== true) {
787
- warnings.push('Hosted tools were requested without `provider.requireParameters: true`; a provider that does not support them receives only the parameters it supports and ignores the rest, returning an ungrounded answer with no error.');
788
- }
789
- if (((_config_provider1 = config.provider) === null || _config_provider1 === void 0 ? void 0 : (_config_provider_only = _config_provider1.only) === null || _config_provider_only === void 0 ? void 0 : _config_provider_only.length) && config.provider.allowFallbacks !== false) {
790
- warnings.push('`provider.only` was set without `provider.allowFallbacks: false`, so routing can still leave the pinned provider.');
791
- }
792
- }
793
- return {
794
- valid: errors.length === 0,
795
- errors: errors,
796
- warnings: warnings
797
- };
798
- }
799
-
800
- function asyncGeneratorStep$1(gen, resolve, reject, _next, _throw, key, arg) {
801
- try {
802
- var info = gen[key](arg);
803
- var value = info.value;
804
- } catch (error) {
805
- reject(error);
806
- return;
807
- }
808
- if (info.done) {
809
- resolve(value);
810
- } else {
811
- Promise.resolve(value).then(_next, _throw);
812
- }
813
- }
814
- function _async_to_generator$1(fn) {
815
- return function() {
816
- var self = this, args = arguments;
817
- return new Promise(function(resolve, reject) {
818
- var gen = fn.apply(self, args);
819
- function _next(value) {
820
- asyncGeneratorStep$1(gen, resolve, reject, _next, _throw, "next", value);
821
- }
822
- function _throw(err) {
823
- asyncGeneratorStep$1(gen, resolve, reject, _next, _throw, "throw", err);
824
- }
825
- _next(undefined);
826
- });
827
- };
828
- }
829
- function _ts_generator$1(thisArg, body) {
830
- var f, y, t, _ = {
831
- label: 0,
832
- sent: function() {
833
- if (t[0] & 1) throw t[1];
834
- return t[1];
835
- },
836
- trys: [],
837
- ops: []
838
- }, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype), d = Object.defineProperty;
839
- return d(g, "next", {
840
- value: verb(0)
841
- }), d(g, "throw", {
842
- value: verb(1)
843
- }), d(g, "return", {
844
- value: verb(2)
845
- }), typeof Symbol === "function" && d(g, Symbol.iterator, {
846
- value: function() {
847
- return this;
848
- }
849
- }), g;
850
- function verb(n) {
851
- return function(v) {
852
- return step([
853
- n,
854
- v
855
- ]);
856
- };
857
- }
858
- function step(op) {
859
- if (f) throw new TypeError("Generator is already executing.");
860
- while(g && (g = 0, op[0] && (_ = 0)), _)try {
861
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
862
- if (y = 0, t) op = [
863
- op[0] & 2,
864
- t.value
865
- ];
866
- switch(op[0]){
867
- case 0:
868
- case 1:
869
- t = op;
870
- break;
871
- case 4:
872
- _.label++;
873
- return {
874
- value: op[1],
875
- done: false
876
- };
877
- case 5:
878
- _.label++;
879
- y = op[1];
880
- op = [
881
- 0
882
- ];
883
- continue;
884
- case 7:
885
- op = _.ops.pop();
886
- _.trys.pop();
887
- continue;
888
- default:
889
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
890
- _ = 0;
891
- continue;
892
- }
893
- if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
894
- _.label = op[1];
895
- break;
896
- }
897
- if (op[0] === 6 && _.label < t[1]) {
898
- _.label = t[1];
899
- t = op;
900
- break;
901
- }
902
- if (t && _.label < t[2]) {
903
- _.label = t[2];
904
- _.ops.push(op);
905
- break;
906
- }
907
- if (t[2]) _.ops.pop();
908
- _.trys.pop();
909
- continue;
910
- }
911
- op = body.call(thisArg, _);
912
- } catch (e) {
913
- op = [
914
- 6,
915
- e
916
- ];
917
- y = 0;
918
- } finally{
919
- f = t = 0;
920
- }
921
- if (op[0] & 5) throw op[1];
922
- return {
923
- value: op[0] ? op[1] : void 0,
924
- done: true
925
- };
926
- }
927
- }
928
- /**
929
- * Generates embeddings.
930
- *
931
- * Base64-encoded embeddings are decoded to numbers before being returned, so a caller never has to
932
- * branch on the encoding the model happened to use.
933
- *
934
- * @param params - The client, model, input, and routing options.
935
- * @returns The embeddings.
936
- */ function openRouterEmbeddings(params) {
937
- return _async_to_generator$1(function() {
938
- var _response_usage, _response_usage1, client, model, input, dimensions, inputType, provider, options, requestBody, result, response, embeddings;
939
- return _ts_generator$1(this, function(_state) {
940
- switch(_state.label){
941
- case 0:
942
- client = params.client, model = params.model, input = params.input, dimensions = params.dimensions, inputType = params.inputType, provider = params.provider, options = params.options;
943
- requestBody = {
944
- model: model,
945
- input: input,
946
- dimensions: dimensions !== null && dimensions !== void 0 ? dimensions : undefined,
947
- inputType: inputType !== null && inputType !== void 0 ? inputType : undefined,
948
- provider: provider !== null && provider !== void 0 ? provider : undefined
949
- };
950
- return [
951
- 4,
952
- embeddingsGenerate.embeddingsGenerate(client, {
953
- requestBody: requestBody
954
- }, options !== null && options !== void 0 ? options : undefined)
955
- ];
956
- case 1:
957
- result = _state.sent();
958
- if (!result.ok) {
959
- throw result.error;
960
- }
961
- response = result.value;
962
- if (typeof response === 'string') {
963
- throw new TypeError('OpenRouter returned a non-JSON embeddings response.');
964
- }
965
- embeddings = response.data.map(function(entry, index) {
966
- var _entry_index;
967
- return {
968
- index: (_entry_index = entry.index) !== null && _entry_index !== void 0 ? _entry_index : index,
969
- embedding: openRouterEmbeddingVector(entry.embedding)
970
- };
971
- });
972
- return [
973
- 2,
974
- {
975
- model: response.model,
976
- embeddings: embeddings,
977
- promptTokens: (_response_usage = response.usage) === null || _response_usage === void 0 ? void 0 : _response_usage.promptTokens,
978
- totalTokens: (_response_usage1 = response.usage) === null || _response_usage1 === void 0 ? void 0 : _response_usage1.totalTokens
979
- }
980
- ];
981
- }
982
- });
983
- })();
984
- }
985
- /**
986
- * Decodes a base64 string to bytes.
987
- *
988
- * `atob` is a WHATWG global, present on Node ≥16 and in every browser, so no Node-only `Buffer` is assumed.
989
- * Anything outside the base64 alphabet — padding, embedded newlines from a wrapped response — is stripped
990
- * first, which is what makes the input tolerant rather than strict.
991
- *
992
- * @param base64 - The base64 string. Padding is optional.
993
- * @returns The decoded bytes.
994
- */ function openRouterDecodeBase64(base64) {
995
- // `charCodeAt`, not `codePointAt`: `atob` returns a latin1 string, so every character is a single UTF-16
996
- // code unit below 256. The two agree here, and only `charCodeAt` is typed to return a plain `number`.
997
- // eslint-disable-next-line unicorn/prefer-code-point
998
- return Uint8Array.from(atob(base64.replaceAll(/[^A-Za-z0-9+/]/g, '')), function(c) {
999
- return c.charCodeAt(0);
1000
- });
1001
- }
1002
- /**
1003
- * Normalizes an embedding to a number array, decoding the base64 (little-endian float32) form.
1004
- *
1005
- * @param embedding - The embedding as returned.
1006
- * @returns The vector.
1007
- */ function openRouterEmbeddingVector(embedding) {
1008
- var result;
1009
- if (typeof embedding === 'string') {
1010
- var bytes = openRouterDecodeBase64(embedding);
1011
- var view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
1012
- var length = Math.floor(bytes.byteLength / 4);
1013
- result = [];
1014
- for(var i = 0; i < length; i += 1){
1015
- result.push(view.getFloat32(i * 4, true));
1016
- }
1017
- } else {
1018
- result = embedding;
1019
- }
1020
- return result;
1021
- }
1022
-
1023
- function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
1024
- try {
1025
- var info = gen[key](arg);
1026
- var value = info.value;
1027
- } catch (error) {
1028
- reject(error);
1029
- return;
1030
- }
1031
- if (info.done) {
1032
- resolve(value);
1033
- } else {
1034
- Promise.resolve(value).then(_next, _throw);
1035
- }
1036
- }
1037
- function _async_to_generator(fn) {
1038
- return function() {
1039
- var self = this, args = arguments;
1040
- return new Promise(function(resolve, reject) {
1041
- var gen = fn.apply(self, args);
1042
- function _next(value) {
1043
- asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
1044
- }
1045
- function _throw(err) {
1046
- asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
1047
- }
1048
- _next(undefined);
1049
- });
1050
- };
1051
- }
1052
- function _ts_generator(thisArg, body) {
1053
- var f, y, t, _ = {
1054
- label: 0,
1055
- sent: function() {
1056
- if (t[0] & 1) throw t[1];
1057
- return t[1];
1058
- },
1059
- trys: [],
1060
- ops: []
1061
- }, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype), d = Object.defineProperty;
1062
- return d(g, "next", {
1063
- value: verb(0)
1064
- }), d(g, "throw", {
1065
- value: verb(1)
1066
- }), d(g, "return", {
1067
- value: verb(2)
1068
- }), typeof Symbol === "function" && d(g, Symbol.iterator, {
1069
- value: function() {
1070
- return this;
1071
- }
1072
- }), g;
1073
- function verb(n) {
1074
- return function(v) {
1075
- return step([
1076
- n,
1077
- v
1078
- ]);
1079
- };
1080
- }
1081
- function step(op) {
1082
- if (f) throw new TypeError("Generator is already executing.");
1083
- while(g && (g = 0, op[0] && (_ = 0)), _)try {
1084
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
1085
- if (y = 0, t) op = [
1086
- op[0] & 2,
1087
- t.value
1088
- ];
1089
- switch(op[0]){
1090
- case 0:
1091
- case 1:
1092
- t = op;
1093
- break;
1094
- case 4:
1095
- _.label++;
1096
- return {
1097
- value: op[1],
1098
- done: false
1099
- };
1100
- case 5:
1101
- _.label++;
1102
- y = op[1];
1103
- op = [
1104
- 0
1105
- ];
1106
- continue;
1107
- case 7:
1108
- op = _.ops.pop();
1109
- _.trys.pop();
1110
- continue;
1111
- default:
1112
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
1113
- _ = 0;
1114
- continue;
1115
- }
1116
- if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
1117
- _.label = op[1];
1118
- break;
1119
- }
1120
- if (op[0] === 6 && _.label < t[1]) {
1121
- _.label = t[1];
1122
- t = op;
1123
- break;
1124
- }
1125
- if (t && _.label < t[2]) {
1126
- _.label = t[2];
1127
- _.ops.push(op);
1128
- break;
1129
- }
1130
- if (t[2]) _.ops.pop();
1131
- _.trys.pop();
1132
- continue;
1133
- }
1134
- op = body.call(thisArg, _);
1135
- } catch (e) {
1136
- op = [
1137
- 6,
1138
- e
1139
- ];
1140
- y = 0;
1141
- } finally{
1142
- f = t = 0;
1143
- }
1144
- if (op[0] & 5) throw op[1];
1145
- return {
1146
- value: op[0] ? op[1] : void 0,
1147
- done: true
1148
- };
1149
- }
1150
- }
1151
- /**
1152
- * Loads a generation's metadata — finish reason, cancellation, BYOK, latency, and the full token/cost
1153
- * breakdown, which is finalised server-side and so can be more complete than the usage the response
1154
- * carried.
1155
- *
1156
- * This is an AUDIT surface, never the system of record. What it returns is tied to account logging
1157
- * settings (nothing is retained under ZDR / logging-disabled), its retention is undocumented, and it is
1158
- * keyed per generation rather than per conversation — which is why a run task stores its own output and
1159
- * keeps `gi (generationIds)` only for lookups like this one.
1160
- *
1161
- * @param params - The client and generation id.
1162
- * @returns The generation metadata.
1163
- * @throws {Error} When the lookup fails, including the 404 a generation that was never retained produces.
1164
- */ function openRouterGeneration(params) {
1165
- return _async_to_generator(function() {
1166
- var client, id, options, result;
1167
- return _ts_generator(this, function(_state) {
1168
- switch(_state.label){
1169
- case 0:
1170
- client = params.client, id = params.id, options = params.options;
1171
- return [
1172
- 4,
1173
- generationsGetGeneration.generationsGetGeneration(client, {
1174
- id: id
1175
- }, options !== null && options !== void 0 ? options : undefined)
1176
- ];
1177
- case 1:
1178
- result = _state.sent();
1179
- if (!result.ok) {
1180
- throw result.error;
1181
- }
1182
- return [
1183
- 2,
1184
- result.value.data
1185
- ];
1186
- }
1187
- });
1188
- })();
1189
- }
1190
- /**
1191
- * Loads a generation's stored content — prompt, completion, reasoning, and output.
1192
- *
1193
- * Subject to every caveat on {@link openRouterGeneration}: this reloads what OpenRouter happened to
1194
- * retain, not what the run produced.
1195
- *
1196
- * @param params - The client and generation id.
1197
- * @returns The stored content.
1198
- * @throws {Error} When the lookup fails.
1199
- */ function openRouterGenerationContent(params) {
1200
- return _async_to_generator(function() {
1201
- var client, id, options, result;
1202
- return _ts_generator(this, function(_state) {
1203
- switch(_state.label){
1204
- case 0:
1205
- client = params.client, id = params.id, options = params.options;
1206
- return [
1207
- 4,
1208
- generationsListGenerationContent.generationsListGenerationContent(client, {
1209
- id: id
1210
- }, options !== null && options !== void 0 ? options : undefined)
1211
- ];
1212
- case 1:
1213
- result = _state.sent();
1214
- if (!result.ok) {
1215
- throw result.error;
1216
- }
1217
- return [
1218
- 2,
1219
- result.value.data
1220
- ];
1221
- }
1222
- });
1223
- })();
1224
- }
1225
-
1226
- function _define_property(obj, key, value) {
1227
- if (key in obj) {
1228
- Object.defineProperty(obj, key, {
1229
- value: value,
1230
- enumerable: true,
1231
- configurable: true,
1232
- writable: true
1233
- });
1234
- } else {
1235
- obj[key] = value;
1236
- }
1237
- return obj;
1238
- }
1239
- function _object_spread(target) {
1240
- for(var i = 1; i < arguments.length; i++){
1241
- var source = arguments[i] != null ? arguments[i] : {};
1242
- var ownKeys = Object.keys(source);
1243
- if (typeof Object.getOwnPropertySymbols === "function") {
1244
- ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
1245
- return Object.getOwnPropertyDescriptor(source, sym).enumerable;
1246
- }));
1247
- }
1248
- ownKeys.forEach(function(key) {
1249
- _define_property(target, key, source[key]);
1250
- });
1251
- }
1252
- return target;
1253
- }
1254
- function ownKeys(object, enumerableOnly) {
1255
- var keys = Object.keys(object);
1256
- if (Object.getOwnPropertySymbols) {
1257
- var symbols = Object.getOwnPropertySymbols(object);
1258
- keys.push.apply(keys, symbols);
1259
- }
1260
- return keys;
1261
- }
1262
- function _object_spread_props(target, source) {
1263
- source = source != null ? source : {};
1264
- if (Object.getOwnPropertyDescriptors) {
1265
- Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
1266
- } else {
1267
- ownKeys(Object(source)).forEach(function(key) {
1268
- Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
1269
- });
1270
- }
1271
- return target;
1272
- }
1273
- function _object_without_properties(source, excluded) {
1274
- if (source == null) return {};
1275
- var target = {}, sourceKeys, key, i;
1276
- if (typeof Reflect !== "undefined" && Reflect.ownKeys) {
1277
- sourceKeys = Reflect.ownKeys(Object(source));
1278
- for(i = 0; i < sourceKeys.length; i++){
1279
- key = sourceKeys[i];
1280
- if (excluded.indexOf(key) >= 0) continue;
1281
- if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
1282
- target[key] = source[key];
1283
- }
1284
- return target;
1285
- }
1286
- target = _object_without_properties_loose(source, excluded);
1287
- if (Object.getOwnPropertySymbols) {
1288
- sourceKeys = Object.getOwnPropertySymbols(source);
1289
- for(i = 0; i < sourceKeys.length; i++){
1290
- key = sourceKeys[i];
1291
- if (excluded.indexOf(key) >= 0) continue;
1292
- if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
1293
- target[key] = source[key];
1294
- }
1295
- }
1296
- return target;
1297
- }
1298
- function _object_without_properties_loose(source, excluded) {
1299
- if (source == null) return {};
1300
- var target = {}, sourceKeys = Object.getOwnPropertyNames(source), key, i;
1301
- for(i = 0; i < sourceKeys.length; i++){
1302
- key = sourceKeys[i];
1303
- if (excluded.indexOf(key) >= 0) continue;
1304
- if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
1305
- target[key] = source[key];
1306
- }
1307
- return target;
1308
- }
1309
- /**
1310
- * Normalizes input to a message array.
1311
- *
1312
- * @param input - The input to normalize.
1313
- * @returns The messages, empty when no input was given.
1314
- */ function openRouterInputMessages(input) {
1315
- var result;
1316
- if (input == null) {
1317
- result = [];
1318
- } else if (typeof input === 'string') {
1319
- result = [
1320
- {
1321
- role: 'user',
1322
- content: [
1323
- {
1324
- type: 'input_text',
1325
- text: input
1326
- }
1327
- ]
1328
- }
1329
- ];
1330
- } else {
1331
- result = input;
1332
- }
1333
- return result;
1334
- }
1335
- /**
1336
- * Builds a text content part.
1337
- *
1338
- * @param text - The text.
1339
- * @returns The content part.
1340
- *
1341
- * @__NO_SIDE_EFFECTS__
1342
- */ function openRouterInputTextPart(text) {
1343
- return {
1344
- type: 'input_text',
1345
- text: text
1346
- };
1347
- }
1348
- /**
1349
- * Builds an image content part.
1350
- *
1351
- * @param imageUrl - The image url (a signed url, a data url, or any publicly reachable url).
1352
- * @param detail - Detail level. Defaults to `auto`.
1353
- * @returns The content part.
1354
- *
1355
- * @__NO_SIDE_EFFECTS__
1356
- */ function openRouterInputImagePart(imageUrl) {
1357
- var detail = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : 'auto';
1358
- return {
1359
- type: 'input_image',
1360
- imageUrl: imageUrl,
1361
- detail: detail
1362
- };
1363
- }
1364
- /**
1365
- * Builds a file content part from a url.
1366
- *
1367
- * @param fileUrl - The url the parser will dereference. Must be reachable from the public internet.
1368
- * @param filename - Filename to present; its extension is what tells OpenRouter how to treat the file.
1369
- * @returns The content part.
1370
- *
1371
- * @__NO_SIDE_EFFECTS__
1372
- */ function openRouterInputFileUrlPart(fileUrl, filename) {
1373
- return {
1374
- type: 'input_file',
1375
- fileUrl: fileUrl,
1376
- filename: filename
1377
- };
1378
- }
1379
- /**
1380
- * Builds a file content part from base64 data.
1381
- *
1382
- * @param base64 - Base64 content, with or without a `data:` prefix.
1383
- * @param filename - Filename to present.
1384
- * @param contentType - Mime type used to build the `data:` prefix when the input lacks one. Defaults to `application/pdf`.
1385
- * @returns The content part.
1386
- *
1387
- * @__NO_SIDE_EFFECTS__
1388
- */ function openRouterInputFileDataPart(base64, filename) {
1389
- var contentType = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : 'application/pdf';
1390
- var fileData = base64.startsWith('data:') ? base64 : "data:".concat(contentType, ";base64,").concat(base64);
1391
- return {
1392
- type: 'input_file',
1393
- fileData: fileData,
1394
- filename: filename
1395
- };
1396
- }
1397
- /**
1398
- * Expands attached file references into file content parts.
1399
- *
1400
- * @param files - The attached file references.
1401
- * @returns One content part per file.
1402
- */ function openRouterInputFilePartsForAttachedFiles(files) {
1403
- return (files !== null && files !== void 0 ? files : []).map(function(param) {
1404
- var file = param.file, fileUrl = param.fileUrl, fileData = param.fileData;
1405
- return fileData == null ? openRouterInputFileUrlPart(fileUrl, file.filename) : openRouterInputFileDataPart(fileData, file.filename);
1406
- });
1407
- }
1408
- /**
1409
- * Rewrites the `input_file` parts of an already-assembled conversation with the attachment resolved for
1410
- * THIS attempt, matching on filename.
1411
- *
1412
- * A conversation persisted mid-run carries whatever the attempt that persisted it was carrying —
1413
- * a url that has since expired, or (with inline attachments stripped on save) nothing at all. Replaying
1414
- * it unchanged is the failure mode most likely to reach production unnoticed, because it only shows up
1415
- * on a retry or a deferred resume. Resolving fresh per attempt is only half the fix; the other half is
1416
- * making sure the stored history is re-pointed at the fresh attachment too.
1417
- *
1418
- * The field the attachment does NOT carry is REMOVED rather than left alone: a stored `fileUrl` sitting
1419
- * next to a fresh `fileData` would send OpenRouter both, and it is not defined which one wins. Removed
1420
- * rather than nulled, because this output goes on the wire — the SDK validates `input_file` against a
1421
- * schema where an explicit `null` is not a legal absent value.
1422
- *
1423
- * A part whose filename matches nothing in `files` is left alone: it came from somewhere other than
1424
- * this task's file list, and guessing at it would be worse than leaving it.
1425
- *
1426
- * @param messages - The assembled conversation.
1427
- * @param files - The files attached for this attempt.
1428
- * @returns The conversation with fresh attachments, or the input unchanged when there is nothing to rewrite.
1429
- */ function openRouterMessagesWithFreshFileAttachments(messages, files) {
1430
- var attachmentsByFilename = util.arrayToMap(files !== null && files !== void 0 ? files : [], function(attached) {
1431
- return attached.file.filename;
1432
- });
1433
- var result = messages !== null && messages !== void 0 ? messages : [];
1434
- if (attachmentsByFilename.size > 0 && result.length > 0) {
1435
- result = result.map(function(message) {
1436
- var updated = message;
1437
- if (Array.isArray(message.content)) {
1438
- var content = message.content.map(function(part) {
1439
- var updatedPart = part;
1440
- if (part.type === 'input_file' && part.filename != null) {
1441
- var fresh = attachmentsByFilename.get(part.filename);
1442
- if (fresh != null) {
1443
- part.fileUrl; part.fileData; var rest = _object_without_properties(part, [
1444
- "fileUrl",
1445
- "fileData"
1446
- ]);
1447
- updatedPart = _object_spread({}, rest, fresh.fileData == null ? {
1448
- fileUrl: fresh.fileUrl
1449
- } : {
1450
- fileData: fresh.fileData
1451
- });
1452
- }
1453
- }
1454
- return updatedPart;
1455
- });
1456
- updated = _object_spread_props(_object_spread({}, message), {
1457
- content: content
1458
- });
1459
- }
1460
- return updated;
1461
- });
1462
- }
1463
- return result;
1464
- }
1465
- /**
1466
- * Strips the attachment payload off every `input_file` part, keeping `filename` as the rejoin key.
1467
- *
1468
- * Applied on the way INTO Firestore. An attachment is resolved per attempt and is meaningless the
1469
- * moment that attempt ends — a signed url has expired, and inline base64 is the whole file, on a
1470
- * document with a 1 MiB ceiling and a `msg` field that already grows without bound. Nothing is lost:
1471
- * {@link openRouterMessagesWithFreshFileAttachments} re-points the stored parts on the way back out.
1472
- *
1473
- * @param messages - The conversation about to be persisted.
1474
- * @returns The conversation with attachment payloads removed.
1475
- */ function openRouterMessagesWithoutFileAttachmentData(messages) {
1476
- return (messages !== null && messages !== void 0 ? messages : []).map(function(message) {
1477
- var updated = message;
1478
- if (Array.isArray(message.content)) {
1479
- var content = message.content.map(function(part) {
1480
- return part.type === 'input_file' ? _object_spread_props(_object_spread({}, part), {
1481
- fileUrl: null,
1482
- fileData: null
1483
- }) : part;
1484
- });
1485
- updated = _object_spread_props(_object_spread({}, message), {
1486
- content: content
1487
- });
1488
- }
1489
- return updated;
1490
- });
1491
- }
1492
- /**
1493
- * Renders one cached annotation as message text.
1494
- *
1495
- * @param annotation - The cached annotation.
1496
- * @returns The text carrying the parse.
1497
- *
1498
- * @__NO_SIDE_EFFECTS__
1499
- */ function openRouterFileAnnotationText(annotation) {
1500
- var _annotation_content, _annotation_filename;
1501
- var content = typeof annotation.content === 'string' ? annotation.content : JSON.stringify((_annotation_content = annotation.content) !== null && _annotation_content !== void 0 ? _annotation_content : null);
1502
- return '<file name="'.concat((_annotation_filename = annotation.filename) !== null && _annotation_filename !== void 0 ? _annotation_filename : annotation.hash, '" hash="').concat(annotation.hash, '">\n').concat(content, "\n</file>");
1503
- }
1504
- /**
1505
- * Builds the assistant message that carries cached `file-parser` output back, so an already-parsed file
1506
- * is not parsed again.
1507
- *
1508
- * It carries the parse TWICE, deliberately, and for an empirical reason rather than a defensive one:
1509
- *
1510
- * - `annotations` is OpenRouter's own documented echo format, so the shape is kept and the mechanism
1511
- * starts working the day the Responses API models it. Today it does not: the SDK validates the request
1512
- * body against a closed union whose message variants have no `annotations` field, so the property is
1513
- * STRIPPED during outbound serialization. Verified against the wire, not assumed.
1514
- * - The parse is therefore ALSO rendered into `content`, as ordinary text, which does survive. Paired
1515
- * with the request builder dropping the file part for an already-parsed file, that is what makes the
1516
- * cache real today.
1517
- *
1518
- * @param annotations - The cached annotations.
1519
- * @returns The message, or undefined when there is nothing cached to resubmit.
1520
- */ function openRouterFileAnnotationMessage(annotations) {
1521
- var result;
1522
- if (annotations != null && annotations.length > 0) {
1523
- result = {
1524
- role: 'assistant',
1525
- content: annotations.map(openRouterFileAnnotationText).join('\n'),
1526
- annotations: annotations.map(function(annotation) {
1527
- return {
1528
- type: 'file',
1529
- file: {
1530
- hash: annotation.hash,
1531
- name: annotation.filename,
1532
- content: annotation.content
1533
- }
1534
- };
1535
- })
1536
- };
1537
- }
1538
- return result;
1539
- }
1540
- /**
1541
- * Drops the files whose parse is already cached.
1542
- *
1543
- * Not re-sending the document is what actually prevents a re-parse. The annotation echo alone cannot:
1544
- * the SDK strips it, and even where it survives it is a hint the provider is free to ignore, so a run
1545
- * that relied on it would pay for the parse again with no error to show for it.
1546
- *
1547
- * A file is matched to its cached parse by filename, which is the only handle both sides share — the
1548
- * annotation's `hash` is assigned by OpenRouter and the reference's `storagePath` is ours.
1549
- *
1550
- * @param files - The files attached for this attempt.
1551
- * @param annotations - The cached annotations.
1552
- * @returns The files that still need sending.
1553
- *
1554
- * @__NO_SIDE_EFFECTS__
1555
- */ function openRouterUnparsedAttachedFiles(files, annotations) {
1556
- var cachedFilenames = new Set((annotations !== null && annotations !== void 0 ? annotations : []).map(function(annotation) {
1557
- return annotation.filename;
1558
- }).filter(function(filename) {
1559
- return filename != null;
1560
- }));
1561
- return (files !== null && files !== void 0 ? files : []).filter(function(param) {
1562
- var file = param.file;
1563
- return !cachedFilenames.has(file.filename);
1564
- });
1565
- }
1566
-
1567
- function _array_like_to_array(arr, len) {
1568
- if (len == null || len > arr.length) len = arr.length;
1569
- for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
1570
- return arr2;
1571
- }
1572
- function _array_without_holes(arr) {
1573
- if (Array.isArray(arr)) return _array_like_to_array(arr);
1574
- }
1575
- function _iterable_to_array(iter) {
1576
- if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
1577
- }
1578
- function _non_iterable_spread() {
1579
- throw new TypeError("Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
1580
- }
1581
- function _to_consumable_array(arr) {
1582
- return _array_without_holes(arr) || _iterable_to_array(arr) || _unsupported_iterable_to_array(arr) || _non_iterable_spread();
1583
- }
1584
- function _unsupported_iterable_to_array(o, minLen) {
1585
- if (!o) return;
1586
- if (typeof o === "string") return _array_like_to_array(o, minLen);
1587
- var n = Object.prototype.toString.call(o).slice(8, -1);
1588
- if (n === "Object" && o.constructor) n = o.constructor.name;
1589
- if (n === "Map" || n === "Set") return Array.from(n);
1590
- if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
1591
- }
1592
- /**
1593
- * Builds a request from a resolved prompt version plus a caller's dynamic input.
1594
- *
1595
- * Content is emitted STATIC FIRST — seed messages, then annotation echoes, then continued history,
1596
- * then the caller's input, with attached files appended to the final user message. That ordering is
1597
- * not cosmetic: a prompt cache only hits on a shared prefix, so putting the per-call content last is
1598
- * what keeps the static prefix cacheable across runs of the same prompt.
1599
- *
1600
- * @param params - The prompt, input, overrides, files, history, and trace.
1601
- * @returns The built request.
1602
- */ function openRouterPromptRequest(params) {
1603
- var _messages;
1604
- var _prompt_messages;
1605
- var prompt = params.prompt, input = params.input, overrides = params.overrides, files = params.files, fileAnnotations = params.fileAnnotations, history = params.history, trace = params.trace;
1606
- var config = mergeOpenRouterModelConfig([
1607
- prompt.config,
1608
- overrides
1609
- ]);
1610
- var seedMessages = ((_prompt_messages = prompt.messages) !== null && _prompt_messages !== void 0 ? _prompt_messages : []).map(function(param) {
1611
- var role = param.role, content = param.content;
1612
- return {
1613
- role: role,
1614
- content: content
1615
- };
1616
- });
1617
- var annotationMessage = openRouterFileAnnotationMessage(fileAnnotations);
1618
- var inputMessages = openRouterInputMessages(input);
1619
- // A file whose parse is already cached is NOT re-attached. Sending it again is what causes the
1620
- // re-parse; the annotation echo alone cannot prevent one.
1621
- var fileParts = openRouterInputFilePartsForAttachedFiles(openRouterUnparsedAttachedFiles(files, fileAnnotations));
1622
- var messages = _to_consumable_array(seedMessages);
1623
- if (annotationMessage != null) {
1624
- messages.push(annotationMessage);
1625
- }
1626
- if (history != null && history.length > 0) {
1627
- var _messages1;
1628
- (_messages1 = messages).push.apply(_messages1, _to_consumable_array(history));
1629
- }
1630
- (_messages = messages).push.apply(_messages, _to_consumable_array(inputMessages));
1631
- if (fileParts.length > 0) {
1632
- // Files ride on the last user message so they sit alongside the text that refers to them. When
1633
- // the caller passed no input at all (a file-only run) a user message is created to carry them.
1634
- var lastUserIndex = messages.findLastIndex(function(x) {
1635
- return x.role === 'user';
1636
- });
1637
- if (lastUserIndex >= 0) {
1638
- var target = messages[lastUserIndex];
1639
- var content = typeof target.content === 'string' ? [
1640
- {
1641
- type: 'input_text',
1642
- text: target.content
1643
- }
1644
- ] : target.content;
1645
- messages[lastUserIndex] = {
1646
- role: target.role,
1647
- content: _to_consumable_array(content).concat(_to_consumable_array(fileParts))
1648
- };
1649
- } else {
1650
- messages.push({
1651
- role: 'user',
1652
- content: fileParts
1653
- });
1654
- }
1655
- }
1656
- return {
1657
- config: config,
1658
- instructions: prompt.instructions,
1659
- input: messages,
1660
- trace: trace
1661
- };
1662
- }
1663
-
1664
- /**
1665
- * Extracts the deferred (manual) tool calls from a conversation state.
1666
- *
1667
- * Only manual tools can be pending on resume: a tool with an `execute` function was run in-process
1668
- * before the state was ever saved.
1669
- *
1670
- * @param state - The conversation state.
1671
- * @param tools - The tool set the run was configured with, used to tell manual tools from executable ones.
1672
- * @returns The pending deferred tool calls.
1673
- */ function openRouterPendingDeferredToolCalls(state, tools) {
1674
- var _ref;
1675
- var manualToolNames = new Set((tools !== null && tools !== void 0 ? tools : []).filter(function(x) {
1676
- return toolTypes.isManualTool(x);
1677
- }).map(function(x) {
1678
- return x.function.name;
1679
- }));
1680
- return ((_ref = state === null || state === void 0 ? void 0 : state.pendingToolCalls) !== null && _ref !== void 0 ? _ref : []).filter(function(call) {
1681
- return manualToolNames.size === 0 || manualToolNames.has(call.name);
1682
- }).map(function(call) {
1683
- return openRouterPendingDeferredToolCallFromParsedCall(call);
1684
- });
1685
- }
1686
- /**
1687
- * Converts an SDK parsed tool call into a pending deferred tool call.
1688
- *
1689
- * @param call - The parsed tool call.
1690
- * @param taskId - Optional task id to associate. Defaults to the call id.
1691
- * @returns The pending deferred tool call.
1692
- */ function openRouterPendingDeferredToolCallFromParsedCall(call, taskId) {
1693
- return {
1694
- callId: call.id,
1695
- name: call.name,
1696
- taskId: taskId !== null && taskId !== void 0 ? taskId : call.id,
1697
- arguments: call.arguments
1698
- };
1699
- }
1700
- /**
1701
- * Turns resolutions into the `unsentToolResults` entries the SDK replays on the next call.
1702
- *
1703
- * A resolution whose `taskId` matches no pending call is DROPPED rather than throwing. Deferred
1704
- * resolutions arrive from outside this process and may be replayed — an unmatched one means the task
1705
- * was already settled, which must be a no-op, not a failure.
1706
- *
1707
- * @param pending - The currently pending deferred tool calls.
1708
- * @param resolutions - The resolutions received.
1709
- * @returns The unsent tool results, in the order the resolutions were given.
1710
- */ function openRouterResolvedDeferredToolResults(pending, resolutions) {
1711
- var byTaskId = util.arrayToMap(pending !== null && pending !== void 0 ? pending : [], function(call) {
1712
- return call.taskId;
1713
- });
1714
- var results = [];
1715
- (resolutions !== null && resolutions !== void 0 ? resolutions : []).forEach(function(resolution) {
1716
- var call = byTaskId.get(resolution.taskId);
1717
- if (call != null) {
1718
- results.push({
1719
- callId: call.callId,
1720
- name: call.name,
1721
- output: resolution.output,
1722
- error: resolution.error
1723
- });
1724
- }
1725
- });
1726
- return results;
1727
- }
1728
- /**
1729
- * Whether a conversation state is paused waiting on a deferred tool result.
1730
- *
1731
- * @param state - The conversation state.
1732
- * @returns True when the state has pending tool calls it cannot resolve itself.
1733
- */ function isOpenRouterStateAwaitingDeferredTools(state) {
1734
- var _ref;
1735
- var _state_pendingToolCalls;
1736
- return ((_ref = state === null || state === void 0 ? void 0 : (_state_pendingToolCalls = state.pendingToolCalls) === null || _state_pendingToolCalls === void 0 ? void 0 : _state_pendingToolCalls.length) !== null && _ref !== void 0 ? _ref : 0) > 0;
1737
- }
1738
- /**
1739
- * Converts recorded tool results into the `function_call_output` items that get appended to the
1740
- * conversation before the run is resumed.
1741
- *
1742
- * This is how a deferred pause is un-paused, and it is done HERE rather than through the SDK on
1743
- * purpose. `@openrouter/sdk@1.2.x` only knows how to resume a pause by re-running the tool locally
1744
- * (`approveToolCalls` calls the tool's `execute`, and a manual tool has none) or by rejecting it — so
1745
- * a result produced by another process has no route back in through the SDK's own API. Appending the
1746
- * outputs to the persisted conversation and re-sending it does have one, and it is the same wire
1747
- * format the SDK would have produced itself.
1748
- *
1749
- * @param results - The recorded results, in the persisted `callId` / `name` / `output` / `error` shape.
1750
- * @returns The `function_call_output` items to append to the conversation.
1751
- */ function openRouterFunctionCallOutputItems(results) {
1752
- return conversationState.unsentResultsToAPIFormat((results !== null && results !== void 0 ? results : []).map(function(result) {
1753
- var _result_error;
1754
- return {
1755
- callId: result.callId,
1756
- name: result.name,
1757
- output: result.output,
1758
- error: (_result_error = result.error) !== null && _result_error !== void 0 ? _result_error : undefined
1759
- };
1760
- }));
1761
- }
1762
-
1763
- Object.defineProperty(exports, "callModel", {
1764
- enumerable: true,
1765
- get: function () { return callModel.callModel; }
1766
- });
1767
- Object.defineProperty(exports, "responsesSend", {
1768
- enumerable: true,
1769
- get: function () { return responsesSend.responsesSend; }
1770
- });
1771
- Object.defineProperty(exports, "unsentResultsToAPIFormat", {
1772
- enumerable: true,
1773
- get: function () { return conversationState.unsentResultsToAPIFormat; }
1774
- });
1775
- Object.defineProperty(exports, "embeddingsGenerate", {
1776
- enumerable: true,
1777
- get: function () { return embeddingsGenerate.embeddingsGenerate; }
1778
- });
1779
- Object.defineProperty(exports, "generationsGetGeneration", {
1780
- enumerable: true,
1781
- get: function () { return generationsGetGeneration.generationsGetGeneration; }
1782
- });
1783
- Object.defineProperty(exports, "generationsListGenerationContent", {
1784
- enumerable: true,
1785
- get: function () { return generationsListGenerationContent.generationsListGenerationContent; }
1786
- });
1787
- Object.defineProperty(exports, "ModelResult", {
1788
- enumerable: true,
1789
- get: function () { return modelResult.ModelResult; }
1790
- });
1791
- Object.defineProperty(exports, "tool", {
1792
- enumerable: true,
1793
- get: function () { return tool.tool; }
1794
- });
1795
- Object.defineProperty(exports, "convertToolsToAPIFormat", {
1796
- enumerable: true,
1797
- get: function () { return toolExecutor.convertToolsToAPIFormat; }
1798
- });
1799
- Object.defineProperty(exports, "finishReasonIs", {
1800
- enumerable: true,
1801
- get: function () { return stopConditions.finishReasonIs; }
1802
- });
1803
- Object.defineProperty(exports, "hasToolCall", {
1804
- enumerable: true,
1805
- get: function () { return stopConditions.hasToolCall; }
1806
- });
1807
- Object.defineProperty(exports, "maxCost", {
1808
- enumerable: true,
1809
- get: function () { return stopConditions.maxCost; }
1810
- });
1811
- Object.defineProperty(exports, "maxTokensUsed", {
1812
- enumerable: true,
1813
- get: function () { return stopConditions.maxTokensUsed; }
1814
- });
1815
- Object.defineProperty(exports, "stepCountIs", {
1816
- enumerable: true,
1817
- get: function () { return stopConditions.stepCountIs; }
1818
- });
1819
- Object.defineProperty(exports, "ToolType", {
1820
- enumerable: true,
1821
- get: function () { return toolTypes.ToolType; }
1822
- });
1823
- Object.defineProperty(exports, "isManualTool", {
1824
- enumerable: true,
1825
- get: function () { return toolTypes.isManualTool; }
1826
- });
1827
- exports.DEFAULT_OPENROUTER_PDF_PARSER_ENGINE = DEFAULT_OPENROUTER_PDF_PARSER_ENGINE;
1828
- exports.OPENROUTER_CALL_MODEL_HEADER = OPENROUTER_CALL_MODEL_HEADER;
1829
- exports.callModelForOpenRouterRequest = callModelForOpenRouterRequest;
1830
- exports.isOpenRouterStateAwaitingDeferredTools = isOpenRouterStateAwaitingDeferredTools;
1831
- exports.mergeOpenRouterModelConfig = mergeOpenRouterModelConfig;
1832
- exports.openRouterCallModelInput = openRouterCallModelInput;
1833
- exports.openRouterCallResultFromResponse = openRouterCallResultFromResponse;
1834
- exports.openRouterDecodeBase64 = openRouterDecodeBase64;
1835
- exports.openRouterEmbeddingVector = openRouterEmbeddingVector;
1836
- exports.openRouterEmbeddings = openRouterEmbeddings;
1837
- exports.openRouterFileAnnotationMessage = openRouterFileAnnotationMessage;
1838
- exports.openRouterFileAnnotationText = openRouterFileAnnotationText;
1839
- exports.openRouterFileParserPlugin = openRouterFileParserPlugin;
1840
- exports.openRouterFileSearchTool = openRouterFileSearchTool;
1841
- exports.openRouterFunctionCallOutputItems = openRouterFunctionCallOutputItems;
1842
- exports.openRouterGeneration = openRouterGeneration;
1843
- exports.openRouterGenerationContent = openRouterGenerationContent;
1844
- exports.openRouterHostedTools = openRouterHostedTools;
1845
- exports.openRouterInputFileDataPart = openRouterInputFileDataPart;
1846
- exports.openRouterInputFilePartsForAttachedFiles = openRouterInputFilePartsForAttachedFiles;
1847
- exports.openRouterInputFileUrlPart = openRouterInputFileUrlPart;
1848
- exports.openRouterInputImagePart = openRouterInputImagePart;
1849
- exports.openRouterInputMessages = openRouterInputMessages;
1850
- exports.openRouterInputTextPart = openRouterInputTextPart;
1851
- exports.openRouterMessagesWithFreshFileAttachments = openRouterMessagesWithFreshFileAttachments;
1852
- exports.openRouterMessagesWithoutFileAttachmentData = openRouterMessagesWithoutFileAttachmentData;
1853
- exports.openRouterModelResultForRequest = openRouterModelResultForRequest;
1854
- exports.openRouterOutputTextFromResponse = openRouterOutputTextFromResponse;
1855
- exports.openRouterPendingDeferredToolCallFromParsedCall = openRouterPendingDeferredToolCallFromParsedCall;
1856
- exports.openRouterPendingDeferredToolCalls = openRouterPendingDeferredToolCalls;
1857
- exports.openRouterPromptRequest = openRouterPromptRequest;
1858
- exports.openRouterProviderPinnedTo = openRouterProviderPinnedTo;
1859
- exports.openRouterResolvedDeferredToolResults = openRouterResolvedDeferredToolResults;
1860
- exports.openRouterResponsesRequestBody = openRouterResponsesRequestBody;
1861
- exports.openRouterRunErrorFromResponseError = openRouterRunErrorFromResponseError;
1862
- exports.openRouterRunUsageFromResponseUsage = openRouterRunUsageFromResponseUsage;
1863
- exports.openRouterUnparsedAttachedFiles = openRouterUnparsedAttachedFiles;
1864
- exports.parseOpenRouterJsonOutput = parseOpenRouterJsonOutput;
1865
- exports.sendOpenRouterResponsesRequest = sendOpenRouterResponsesRequest;
1866
- exports.splitOpenRouterModelConfig = splitOpenRouterModelConfig;
1867
- exports.validateOpenRouterModelConfig = validateOpenRouterModelConfig;