@dereekb/openrouter 14.6.0 → 14.8.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.esm.js CHANGED
@@ -1,4 +1,4 @@
1
- import { filterUndefinedValues, mergeObjects, arrayToMap } from '@dereekb/util';
1
+ import { filterUndefinedValues, mergeObjects, mapObjectMap, arrayToMap } from '@dereekb/util';
2
2
  import { callModel } from '@openrouter/sdk/funcs/call-model';
3
3
  export { callModel } from '@openrouter/sdk/funcs/call-model';
4
4
  import { responsesSend } from '@openrouter/sdk/funcs/responsesSend';
@@ -7,6 +7,8 @@ import { unsentResultsToAPIFormat } from '@openrouter/sdk/lib/conversation-state
7
7
  export { unsentResultsToAPIFormat } from '@openrouter/sdk/lib/conversation-state';
8
8
  import { embeddingsGenerate } from '@openrouter/sdk/funcs/embeddingsGenerate';
9
9
  export { embeddingsGenerate } from '@openrouter/sdk/funcs/embeddingsGenerate';
10
+ import { systemOneCreate } from '@openrouter/sdk/funcs/systemOneCreate';
11
+ export { systemOneCreate } from '@openrouter/sdk/funcs/systemOneCreate';
10
12
  import { generationsGetGeneration } from '@openrouter/sdk/funcs/generationsGetGeneration';
11
13
  export { generationsGetGeneration } from '@openrouter/sdk/funcs/generationsGetGeneration';
12
14
  import { generationsListGenerationContent } from '@openrouter/sdk/funcs/generationsListGenerationContent';
@@ -21,15 +23,62 @@ export { finishReasonIs, hasToolCall, maxCost, maxTokensUsed, stepCountIs } from
21
23
  import { isManualTool } from '@openrouter/sdk/lib/tool-types';
22
24
  export { ToolType, isManualTool } from '@openrouter/sdk/lib/tool-types';
23
25
 
24
- function _array_like_to_array$1(arr, len) {
26
+ /**
27
+ * The namespace every System One model slug lives under.
28
+ */ var OPENROUTER_SYSTEM_ONE_MODEL_NAMESPACE = 'typesafe';
29
+ /**
30
+ * Jev 1.13, the System One model this package pins by default.
31
+ *
32
+ * A VERSIONED slug rather than one of the moving aliases (`jev-latest`, `jev-preview`), for the same
33
+ * reason {@link OpenRouterPromptVersionNumber} exists: a decision's answer is only reproducible against
34
+ * the exact model that produced it, and an alias silently moves out from under a stored prompt. Point a
35
+ * prompt at an alias deliberately, never by default.
36
+ */ var OPENROUTER_JEV_1_13_MODEL_ID = 'typesafe/jev-1.13';
37
+ /**
38
+ * The newest STABLE Jev. A moving alias — see {@link OPENROUTER_JEV_1_13_MODEL_ID}.
39
+ */ var OPENROUTER_JEV_LATEST_MODEL_ID = 'typesafe/jev-latest';
40
+ /**
41
+ * The newest Jev, stable or not. A moving alias — see {@link OPENROUTER_JEV_1_13_MODEL_ID}.
42
+ */ var OPENROUTER_JEV_PREVIEW_MODEL_ID = 'typesafe/jev-preview';
43
+ /**
44
+ * The System One model a decision uses when its config names none.
45
+ */ var DEFAULT_OPENROUTER_SYSTEM_ONE_MODEL_ID = OPENROUTER_JEV_1_13_MODEL_ID;
46
+ /**
47
+ * Matches the bare System One slugs OpenRouter maps into the `typesafe/` namespace.
48
+ */ var OPENROUTER_BARE_SYSTEM_ONE_MODEL_REGEX = /^jev(-|$)/;
49
+ /**
50
+ * Whether a model slug names a System One model.
51
+ *
52
+ * This is the ONLY discriminator available, and it is the reason this function exists rather than a
53
+ * lookup: System One models are NOT listed by `GET /models`, so nothing can be learned about one from
54
+ * the catalog. A caller that guessed wrong does not get an error it can read — a Jev slug sent to
55
+ * `/responses` fails at the provider, and a chat slug sent to `/systemone` is refused by the route.
56
+ *
57
+ * Both forms are recognised: the namespaced slug (`typesafe/jev-1.13`) and the bare one (`jev-1.13`,
58
+ * `jev-latest`), which the SDK documents itself as mapping onto the `typesafe/` namespace.
59
+ *
60
+ * @param model - The model slug to test.
61
+ * @returns True when the slug names a System One model.
62
+ *
63
+ * @__NO_SIDE_EFFECTS__
64
+ */ function isOpenRouterSystemOneModelId(model) {
65
+ var slug = model === null || model === void 0 ? void 0 : model.trim().toLowerCase();
66
+ return slug == null || slug === '' ? false : slug.startsWith("".concat(OPENROUTER_SYSTEM_ONE_MODEL_NAMESPACE, "/")) || OPENROUTER_BARE_SYSTEM_ONE_MODEL_REGEX.test(slug);
67
+ }
68
+
69
+ function _array_like_to_array$4(arr, len) {
25
70
  if (len == null || len > arr.length) len = arr.length;
26
71
  for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
27
72
  return arr2;
28
73
  }
29
- function _array_without_holes$1(arr) {
30
- if (Array.isArray(arr)) return _array_like_to_array$1(arr);
74
+ function _array_without_holes$4(arr) {
75
+ if (Array.isArray(arr)) return _array_like_to_array$4(arr);
31
76
  }
32
- function asyncGeneratorStep$2(gen, resolve, reject, _next, _throw, key, arg) {
77
+ function _assert_this_initialized$1(self) {
78
+ if (self === void 0) throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
79
+ return self;
80
+ }
81
+ function asyncGeneratorStep$3(gen, resolve, reject, _next, _throw, key, arg) {
33
82
  try {
34
83
  var info = gen[key](arg);
35
84
  var value = info.value;
@@ -40,22 +89,45 @@ function asyncGeneratorStep$2(gen, resolve, reject, _next, _throw, key, arg) {
40
89
  if (info.done) resolve(value);
41
90
  else Promise.resolve(value).then(_next, _throw);
42
91
  }
43
- function _async_to_generator$2(fn) {
92
+ function _async_to_generator$3(fn) {
44
93
  return function() {
45
94
  var self = this, args = arguments;
46
95
  return new Promise(function(resolve, reject) {
47
96
  var gen = fn.apply(self, args);
48
97
  function _next(value) {
49
- asyncGeneratorStep$2(gen, resolve, reject, _next, _throw, "next", value);
98
+ asyncGeneratorStep$3(gen, resolve, reject, _next, _throw, "next", value);
50
99
  }
51
100
  function _throw(err) {
52
- asyncGeneratorStep$2(gen, resolve, reject, _next, _throw, "throw", err);
101
+ asyncGeneratorStep$3(gen, resolve, reject, _next, _throw, "throw", err);
53
102
  }
54
103
  _next(undefined);
55
104
  });
56
105
  };
57
106
  }
58
- function _define_property$2(obj, key, value) {
107
+ function _call_super$1(_this, derived, args) {
108
+ derived = _get_prototype_of$1(derived);
109
+ return _possible_constructor_return$1(_this, _is_native_reflect_construct$1() ? Reflect.construct(derived, args || [], _get_prototype_of$1(_this).constructor) : derived.apply(_this, args));
110
+ }
111
+ function _class_call_check$1(instance, Constructor) {
112
+ if (!(instance instanceof Constructor)) throw new TypeError("Cannot call a class as a function");
113
+ }
114
+ function _construct$1(Parent, args, Class) {
115
+ if (_is_native_reflect_construct$1()) _construct$1 = Reflect.construct;
116
+ else {
117
+ _construct$1 = function construct(Parent, args, Class) {
118
+ var a = [
119
+ null
120
+ ];
121
+ a.push.apply(a, args);
122
+ var Constructor = Function.bind.apply(Parent, a);
123
+ var instance = new Constructor();
124
+ if (Class) _set_prototype_of$1(instance, Class.prototype);
125
+ return instance;
126
+ };
127
+ }
128
+ return _construct$1.apply(null, arguments);
129
+ }
130
+ function _define_property$4(obj, key, value) {
59
131
  if (key in obj) {
60
132
  Object.defineProperty(obj, key, {
61
133
  value: value,
@@ -66,15 +138,45 @@ function _define_property$2(obj, key, value) {
66
138
  } else obj[key] = value;
67
139
  return obj;
68
140
  }
69
- function _iterable_to_array$1(iter) {
141
+ function _get_prototype_of$1(o) {
142
+ _get_prototype_of$1 = Object.setPrototypeOf ? Object.getPrototypeOf : function getPrototypeOf(o) {
143
+ return o.__proto__ || Object.getPrototypeOf(o);
144
+ };
145
+ return _get_prototype_of$1(o);
146
+ }
147
+ function _inherits$1(subClass, superClass) {
148
+ if (typeof superClass !== "function" && superClass !== null) {
149
+ throw new TypeError("Super expression must either be null or a function");
150
+ }
151
+ subClass.prototype = Object.create(superClass && superClass.prototype, {
152
+ constructor: {
153
+ value: subClass,
154
+ writable: true,
155
+ configurable: true
156
+ }
157
+ });
158
+ if (superClass) _set_prototype_of$1(subClass, superClass);
159
+ }
160
+ function _is_native_function$1(fn) {
161
+ return Function.toString.call(fn).indexOf("[native code]") !== -1;
162
+ }
163
+ function _is_native_reflect_construct$1() {
164
+ try {
165
+ var result = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
166
+ } catch (_) {}
167
+ return (_is_native_reflect_construct$1 = function() {
168
+ return !!result;
169
+ })();
170
+ }
171
+ function _iterable_to_array$4(iter) {
70
172
  if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) {
71
173
  return Array.from(iter);
72
174
  }
73
175
  }
74
- function _non_iterable_spread$1() {
176
+ function _non_iterable_spread$4() {
75
177
  throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
76
178
  }
77
- function _object_spread$2(target) {
179
+ function _object_spread$4(target) {
78
180
  for(var i = 1; i < arguments.length; i++){
79
181
  var source = arguments[i] != null ? arguments[i] : {};
80
182
  var ownKeys = Object.keys(source);
@@ -84,12 +186,12 @@ function _object_spread$2(target) {
84
186
  }));
85
187
  }
86
188
  ownKeys.forEach(function(key) {
87
- _define_property$2(target, key, source[key]);
189
+ _define_property$4(target, key, source[key]);
88
190
  });
89
191
  }
90
192
  return target;
91
193
  }
92
- function ownKeys$1(object, enumerableOnly) {
194
+ function ownKeys$2(object, enumerableOnly) {
93
195
  var keys = Object.keys(object);
94
196
  if (Object.getOwnPropertySymbols) {
95
197
  var symbols = Object.getOwnPropertySymbols(object);
@@ -97,17 +199,17 @@ function ownKeys$1(object, enumerableOnly) {
97
199
  }
98
200
  return keys;
99
201
  }
100
- function _object_spread_props$1(target, source) {
202
+ function _object_spread_props$2(target, source) {
101
203
  source = source != null ? source : {};
102
204
  if (Object.getOwnPropertyDescriptors) Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
103
205
  else {
104
- ownKeys$1(Object(source)).forEach(function(key) {
206
+ ownKeys$2(Object(source)).forEach(function(key) {
105
207
  Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
106
208
  });
107
209
  }
108
210
  return target;
109
211
  }
110
- function _object_without_properties$1(source, excluded) {
212
+ function _object_without_properties$2(source, excluded) {
111
213
  if (source == null) return {};
112
214
  var target = {}, sourceKeys, key, i;
113
215
  if (typeof Reflect !== "undefined" && Reflect.ownKeys) {
@@ -120,7 +222,7 @@ function _object_without_properties$1(source, excluded) {
120
222
  }
121
223
  return target;
122
224
  }
123
- target = _object_without_properties_loose$1(source, excluded);
225
+ target = _object_without_properties_loose$2(source, excluded);
124
226
  if (Object.getOwnPropertySymbols) {
125
227
  sourceKeys = Object.getOwnPropertySymbols(source);
126
228
  for(i = 0; i < sourceKeys.length; i++){
@@ -132,7 +234,7 @@ function _object_without_properties$1(source, excluded) {
132
234
  }
133
235
  return target;
134
236
  }
135
- function _object_without_properties_loose$1(source, excluded) {
237
+ function _object_without_properties_loose$2(source, excluded) {
136
238
  if (source == null) return {};
137
239
  var target = {}, sourceKeys = Object.getOwnPropertyNames(source), key, i;
138
240
  for(i = 0; i < sourceKeys.length; i++){
@@ -143,10 +245,21 @@ function _object_without_properties_loose$1(source, excluded) {
143
245
  }
144
246
  return target;
145
247
  }
146
- function _to_consumable_array$1(arr) {
147
- return _array_without_holes$1(arr) || _iterable_to_array$1(arr) || _unsupported_iterable_to_array$1(arr) || _non_iterable_spread$1();
248
+ function _possible_constructor_return$1(self, call) {
249
+ if (call && (_type_of$2(call) === "object" || typeof call === "function")) return call;
250
+ return _assert_this_initialized$1(self);
148
251
  }
149
- function _ts_generator$2(thisArg, body) {
252
+ function _set_prototype_of$1(o, p) {
253
+ _set_prototype_of$1 = Object.setPrototypeOf || function setPrototypeOf(o, p) {
254
+ o.__proto__ = p;
255
+ return o;
256
+ };
257
+ return _set_prototype_of$1(o, p);
258
+ }
259
+ function _to_consumable_array$4(arr) {
260
+ return _array_without_holes$4(arr) || _iterable_to_array$4(arr) || _unsupported_iterable_to_array$4(arr) || _non_iterable_spread$4();
261
+ }
262
+ function _ts_generator$3(thisArg, body) {
150
263
  var f, y, t, _ = {
151
264
  label: 0,
152
265
  sent: function() {
@@ -245,17 +358,41 @@ function _ts_generator$2(thisArg, body) {
245
358
  };
246
359
  }
247
360
  }
248
- function _type_of(obj) {
361
+ function _type_of$2(obj) {
249
362
  "@swc/helpers - typeof";
250
363
  return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj;
251
364
  }
252
- function _unsupported_iterable_to_array$1(o, minLen) {
365
+ function _unsupported_iterable_to_array$4(o, minLen) {
253
366
  if (!o) return;
254
- if (typeof o === "string") return _array_like_to_array$1(o, minLen);
367
+ if (typeof o === "string") return _array_like_to_array$4(o, minLen);
255
368
  var n = Object.prototype.toString.call(o).slice(8, -1);
256
369
  if (n === "Object" && o.constructor) n = o.constructor.name;
257
370
  if (n === "Map" || n === "Set") return Array.from(n);
258
- if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array$1(o, minLen);
371
+ if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array$4(o, minLen);
372
+ }
373
+ function _wrap_native_super$1(Class) {
374
+ var _cache = typeof Map === "function" ? new Map() : undefined;
375
+ _wrap_native_super$1 = function(Class) {
376
+ if (Class === null || !_is_native_function$1(Class)) return Class;
377
+ if (typeof Class !== "function") throw new TypeError("Super expression must either be null or a function");
378
+ if (typeof _cache !== "undefined") {
379
+ if (_cache.has(Class)) return _cache.get(Class);
380
+ _cache.set(Class, Wrapper);
381
+ }
382
+ function Wrapper() {
383
+ return _construct$1(Class, arguments, _get_prototype_of$1(this).constructor);
384
+ }
385
+ Wrapper.prototype = Object.create(Class.prototype, {
386
+ constructor: {
387
+ value: Wrapper,
388
+ enumerable: false,
389
+ writable: true,
390
+ configurable: true
391
+ }
392
+ });
393
+ return _set_prototype_of$1(Wrapper, Class);
394
+ };
395
+ return _wrap_native_super$1(Class);
259
396
  }
260
397
  /**
261
398
  * Splits a model config into request parameters and execution controls.
@@ -268,7 +405,7 @@ function _unsupported_iterable_to_array$1(o, minLen) {
268
405
  * @param config - The merged model config.
269
406
  * @returns The split config.
270
407
  */ function splitOpenRouterModelConfig(config) {
271
- var _ref = config !== null && config !== void 0 ? config : {}, maxSteps = _ref.maxSteps, requestTimeoutMs = _ref.requestTimeoutMs, rest = _object_without_properties$1(_ref, [
408
+ var _ref = config !== null && config !== void 0 ? config : {}, maxSteps = _ref.maxSteps, requestTimeoutMs = _ref.requestTimeoutMs, rest = _object_without_properties$2(_ref, [
272
409
  "maxSteps",
273
410
  "requestTimeoutMs"
274
411
  ]);
@@ -296,21 +433,69 @@ function _unsupported_iterable_to_array$1(o, minLen) {
296
433
  var tools = config === null || config === void 0 ? void 0 : config.tools;
297
434
  return Array.isArray(tools) ? tools : [];
298
435
  }
436
+ /**
437
+ * Raised when a request naming a System One model is sent down the completion arm.
438
+ *
439
+ * Its own error type rather than a generic one because the fix is specific and mechanical — the call
440
+ * goes to `openRouterDecision` — and an error a reader can act on without opening the source is worth
441
+ * a named class.
442
+ */ var OpenRouterSystemOneModelOnCompletionArmError = /*#__PURE__*/ function(Error1) {
443
+ _inherits$1(OpenRouterSystemOneModelOnCompletionArmError, Error1);
444
+ function OpenRouterSystemOneModelOnCompletionArmError(model) {
445
+ _class_call_check$1(this, OpenRouterSystemOneModelOnCompletionArmError);
446
+ var _this;
447
+ _this = _call_super$1(this, OpenRouterSystemOneModelOnCompletionArmError, [
448
+ "`".concat(model, "` is a System One model. It answers only `POST /systemone` and cannot serve a completion — build an `OpenRouterDecisionRequest` and call `openRouterDecision` instead of `callModelForOpenRouterRequest`.")
449
+ ]), _define_property$4(_this, "model", void 0);
450
+ _this.name = 'OpenRouterSystemOneModelOnCompletionArmError';
451
+ _this.model = model;
452
+ return _this;
453
+ }
454
+ return OpenRouterSystemOneModelOnCompletionArmError;
455
+ }(_wrap_native_super$1(Error));
456
+ /**
457
+ * Refuses a config whose model cannot serve a completion.
458
+ *
459
+ * Asserted rather than assumed, for the same reason {@link sendOpenRouterResponsesRequest} asserts its
460
+ * response is not an event stream: the alternative failure is unreadable. A Jev slug on `/responses`
461
+ * comes back as a provider-level error naming neither the model class nor the route that would have
462
+ * served it, from inside a sweep, on a request whose config was accepted when it was written.
463
+ *
464
+ * @param config - The merged model config.
465
+ * @throws {OpenRouterSystemOneModelOnCompletionArmError} When the config names a System One model.
466
+ */ function assertOpenRouterCompletionModel(config) {
467
+ var _ref;
468
+ var model = [
469
+ config === null || config === void 0 ? void 0 : config.model
470
+ ].concat(_to_consumable_array$4((_ref = config === null || config === void 0 ? void 0 : config.models) !== null && _ref !== void 0 ? _ref : [])).filter(Boolean).find(function(x) {
471
+ return isOpenRouterSystemOneModelId(x);
472
+ });
473
+ if (model != null) {
474
+ throw new OpenRouterSystemOneModelOnCompletionArmError(model);
475
+ }
476
+ }
299
477
  /**
300
478
  * Converts a built request into the `/responses` request body.
301
479
  *
302
480
  * This is the whole wire body minus the SDK-only keys (`tools`/`state`/`stopWhen` on the `callModel`
303
481
  * path), so both dispatch paths assemble the request the same way and cannot drift.
304
482
  *
483
+ * It is also where a System One model is refused, because it is the ONE point every dispatch path
484
+ * converges on — `openRouterCallModelInput`, `sendOpenRouterResponsesRequest` and
485
+ * `openRouterModelResultForRequest` all build their body here — so no route to the completion arm can
486
+ * be added later that quietly skips the check.
487
+ *
305
488
  * @param request - The built request.
306
489
  * @returns The request body, in the SDK's camelCase request surface.
490
+ * @throws {OpenRouterSystemOneModelOnCompletionArmError} When the config names a System One model.
307
491
  */ function openRouterResponsesRequestBody(request) {
492
+ assertOpenRouterCompletionModel(request.config);
308
493
  var requestConfig = splitOpenRouterModelConfig(request.config).requestConfig;
309
- return filterUndefinedValues(_object_spread_props$1(_object_spread$2({}, requestConfig), {
494
+ return filterUndefinedValues(_object_spread_props$2(_object_spread$4({}, requestConfig), {
310
495
  input: request.input,
311
496
  instructions: request.instructions || undefined,
312
497
  trace: request.trace == null ? undefined : {
313
- additionalProperties: _object_spread$2({}, request.trace)
498
+ additionalProperties: _object_spread$4({}, request.trace)
314
499
  }
315
500
  }));
316
501
  }
@@ -328,11 +513,11 @@ function _unsupported_iterable_to_array$1(o, minLen) {
328
513
  var maxSteps = splitOpenRouterModelConfig(request.config).maxSteps;
329
514
  // dropped by name rather than by mutation, so TypeScript sees which keys leave the body: the hosted
330
515
  // tools `callModel` cannot carry, and a config-set `stream` the non-streaming path must not inherit.
331
- var _openRouterResponsesRequestBody = openRouterResponsesRequestBody(request); _openRouterResponsesRequestBody.tools; _openRouterResponsesRequestBody.stream; var body = _object_without_properties$1(_openRouterResponsesRequestBody, [
516
+ var _openRouterResponsesRequestBody = openRouterResponsesRequestBody(request); _openRouterResponsesRequestBody.tools; _openRouterResponsesRequestBody.stream; var body = _object_without_properties$2(_openRouterResponsesRequestBody, [
332
517
  "tools",
333
518
  "stream"
334
519
  ]);
335
- var input = filterUndefinedValues(_object_spread_props$1(_object_spread$2({}, body), {
520
+ var input = filterUndefinedValues(_object_spread_props$2(_object_spread$4({}, body), {
336
521
  tools: tools !== null && tools !== void 0 ? tools : undefined,
337
522
  state: state !== null && state !== void 0 ? state : undefined,
338
523
  stopWhen: maxSteps == null ? undefined : stepCountIs(maxSteps)
@@ -351,7 +536,7 @@ function _unsupported_iterable_to_array$1(o, minLen) {
351
536
  * @param requestTimeoutMs - The per-request timeout from the config, when it set one.
352
537
  * @returns The merged options.
353
538
  */ function openRouterRequestOptions(options, requestTimeoutMs) {
354
- return _object_spread$2({}, options, requestTimeoutMs == null ? undefined : {
539
+ return _object_spread$4({}, options, requestTimeoutMs == null ? undefined : {
355
540
  timeoutMs: requestTimeoutMs
356
541
  });
357
542
  }
@@ -370,7 +555,7 @@ function _unsupported_iterable_to_array$1(o, minLen) {
370
555
  // eslint-disable-next-line @typescript-eslint/no-deprecated
371
556
  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);
372
557
  headers.set(OPENROUTER_CALL_MODEL_HEADER, 'true');
373
- return _object_spread_props$1(_object_spread$2({}, options), {
558
+ return _object_spread_props$2(_object_spread$4({}, options), {
374
559
  headers: headers
375
560
  });
376
561
  }
@@ -388,14 +573,14 @@ function _unsupported_iterable_to_array$1(o, minLen) {
388
573
  * @returns The response.
389
574
  * @throws {Error} When the request fails, or when a streaming response comes back for a non-streaming request.
390
575
  */ function sendOpenRouterResponsesRequest(params) {
391
- return _async_to_generator$2(function() {
576
+ return _async_to_generator$3(function() {
392
577
  var client, request, options, requestTimeoutMs, responsesRequest, result;
393
- return _ts_generator$2(this, function(_state) {
578
+ return _ts_generator$3(this, function(_state) {
394
579
  switch(_state.label){
395
580
  case 0:
396
581
  client = params.client, request = params.request, options = params.options;
397
582
  requestTimeoutMs = splitOpenRouterModelConfig(request.config).requestTimeoutMs;
398
- responsesRequest = _object_spread_props$1(_object_spread$2({}, openRouterResponsesRequestBody(request)), {
583
+ responsesRequest = _object_spread_props$2(_object_spread$4({}, openRouterResponsesRequestBody(request)), {
399
584
  stream: false
400
585
  });
401
586
  return [
@@ -449,13 +634,13 @@ function _unsupported_iterable_to_array$1(o, minLen) {
449
634
  } else {
450
635
  // `stream` is dropped by name, exactly as the `callModel` path drops it, so neither path can inherit
451
636
  // a config-set value.
452
- var _openRouterResponsesRequestBody = openRouterResponsesRequestBody(request); _openRouterResponsesRequestBody.stream; var body = _object_without_properties$1(_openRouterResponsesRequestBody, [
637
+ var _openRouterResponsesRequestBody = openRouterResponsesRequestBody(request); _openRouterResponsesRequestBody.stream; var body = _object_without_properties$2(_openRouterResponsesRequestBody, [
453
638
  "stream"
454
639
  ]);
455
- var apiRequest = _object_spread_props$1(_object_spread$2({}, body), {
456
- tools: _to_consumable_array$1(tools == null ? [] : convertToolsToAPIFormat(tools)).concat(_to_consumable_array$1(hostedTools))
640
+ var apiRequest = _object_spread_props$2(_object_spread$4({}, body), {
641
+ tools: _to_consumable_array$4(tools == null ? [] : convertToolsToAPIFormat(tools)).concat(_to_consumable_array$4(hostedTools))
457
642
  });
458
- result = new ModelResult(_object_spread$2({
643
+ result = new ModelResult(_object_spread$4({
459
644
  client: client,
460
645
  request: apiRequest,
461
646
  options: openRouterCallModelRequestOptions(requestOptions)
@@ -479,9 +664,9 @@ function _unsupported_iterable_to_array$1(o, minLen) {
479
664
  * @param params - The client, request, tools, state, and options.
480
665
  * @returns The normalized call result.
481
666
  */ function callModelForOpenRouterRequest(params) {
482
- return _async_to_generator$2(function() {
667
+ return _async_to_generator$3(function() {
483
668
  var _ref, _params_tools, needsClientToolLoop, sendDirect, response, _tmp;
484
- return _ts_generator$2(this, function(_state) {
669
+ return _ts_generator$3(this, function(_state) {
485
670
  switch(_state.label){
486
671
  case 0:
487
672
  // Client tools and a `StateAccessor` both live on `ModelResult`, so a run using either needs the loop
@@ -629,7 +814,7 @@ function _unsupported_iterable_to_array$1(o, minLen) {
629
814
  if (outputText) {
630
815
  try {
631
816
  var parsed = JSON.parse(outputText);
632
- if (parsed != null && (typeof parsed === "undefined" ? "undefined" : _type_of(parsed)) === 'object' && !Array.isArray(parsed)) {
817
+ if (parsed != null && (typeof parsed === "undefined" ? "undefined" : _type_of$2(parsed)) === 'object' && !Array.isArray(parsed)) {
633
818
  result = parsed;
634
819
  }
635
820
  } catch (unused) {
@@ -639,7 +824,15 @@ function _unsupported_iterable_to_array$1(o, minLen) {
639
824
  return result;
640
825
  }
641
826
 
642
- function _define_property$1(obj, key, value) {
827
+ function _array_like_to_array$3(arr, len) {
828
+ if (len == null || len > arr.length) len = arr.length;
829
+ for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
830
+ return arr2;
831
+ }
832
+ function _array_without_holes$3(arr) {
833
+ if (Array.isArray(arr)) return _array_like_to_array$3(arr);
834
+ }
835
+ function _define_property$3(obj, key, value) {
643
836
  if (key in obj) {
644
837
  Object.defineProperty(obj, key, {
645
838
  value: value,
@@ -650,7 +843,15 @@ function _define_property$1(obj, key, value) {
650
843
  } else obj[key] = value;
651
844
  return obj;
652
845
  }
653
- function _object_spread$1(target) {
846
+ function _iterable_to_array$3(iter) {
847
+ if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) {
848
+ return Array.from(iter);
849
+ }
850
+ }
851
+ function _non_iterable_spread$3() {
852
+ throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
853
+ }
854
+ function _object_spread$3(target) {
654
855
  for(var i = 1; i < arguments.length; i++){
655
856
  var source = arguments[i] != null ? arguments[i] : {};
656
857
  var ownKeys = Object.keys(source);
@@ -660,11 +861,22 @@ function _object_spread$1(target) {
660
861
  }));
661
862
  }
662
863
  ownKeys.forEach(function(key) {
663
- _define_property$1(target, key, source[key]);
864
+ _define_property$3(target, key, source[key]);
664
865
  });
665
866
  }
666
867
  return target;
667
868
  }
869
+ function _to_consumable_array$3(arr) {
870
+ return _array_without_holes$3(arr) || _iterable_to_array$3(arr) || _unsupported_iterable_to_array$3(arr) || _non_iterable_spread$3();
871
+ }
872
+ function _unsupported_iterable_to_array$3(o, minLen) {
873
+ if (!o) return;
874
+ if (typeof o === "string") return _array_like_to_array$3(o, minLen);
875
+ var n = Object.prototype.toString.call(o).slice(8, -1);
876
+ if (n === "Object" && o.constructor) n = o.constructor.name;
877
+ if (n === "Map" || n === "Set") return Array.from(n);
878
+ if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array$3(o, minLen);
879
+ }
668
880
  /**
669
881
  * Builds a hosted `file_search` tool entry with the field names the SDK actually forwards.
670
882
  *
@@ -674,7 +886,7 @@ function _object_spread$1(target) {
674
886
  *
675
887
  * @__NO_SIDE_EFFECTS__
676
888
  */ function openRouterFileSearchTool(vectorStoreIds, maxNumResults) {
677
- return _object_spread$1({
889
+ return _object_spread$3({
678
890
  type: 'file_search',
679
891
  vectorStoreIds: vectorStoreIds
680
892
  }, maxNumResults == null ? undefined : {
@@ -748,18 +960,46 @@ function _object_spread$1(target) {
748
960
  * rather than loudly.
749
961
  *
750
962
  * @param config - The merged config to check.
963
+ * @param options - Which arm the config is for.
751
964
  * @returns The validation result.
752
- */ function validateOpenRouterModelConfig(config) {
965
+ */ function validateOpenRouterModelConfig(config, options) {
753
966
  var errors = [];
754
967
  var warnings = [];
968
+ var decision = (options === null || options === void 0 ? void 0 : options.decision) === true;
755
969
  if (config == null) {
756
970
  errors.push('No model config was provided.');
757
971
  } else {
758
- var _ref;
759
- var _config_models, _config_text, _config_plugins, _fileParser_pdf, _config_tools, _config_tools1, _config_provider, _config_provider_only, _config_provider1;
760
- if (!config.model && !((_config_models = config.models) === null || _config_models === void 0 ? void 0 : _config_models.length)) {
972
+ var _config_models, _ref;
973
+ var _config_models1, _config_text, _config_plugins, _fileParser_pdf, _config_tools, _config_tools1, _config_provider, _config_provider_only, _config_provider1;
974
+ if (!config.model && !((_config_models1 = config.models) === null || _config_models1 === void 0 ? void 0 : _config_models1.length)) {
761
975
  errors.push('No `model` (or `models` fallback chain) was specified.');
762
976
  }
977
+ // OpenRouter has TWO inference surfaces and the model slug is the only thing that says which one a
978
+ // request belongs to — System One models are absent from `GET /models`, so nothing can be learned
979
+ // about one from the catalog. Checked here because this runs at publish time: a Jev slug typed into
980
+ // a stored prompt version is refused when it is written, rather than failing in a sweep days later
981
+ // with an error that names neither the prompt nor the reason.
982
+ var declaredModels = [
983
+ config.model
984
+ ].concat(_to_consumable_array$3((_config_models = config.models) !== null && _config_models !== void 0 ? _config_models : [])).filter(Boolean);
985
+ var systemOneModels = declaredModels.filter(function(x) {
986
+ return isOpenRouterSystemOneModelId(x);
987
+ });
988
+ if (decision) {
989
+ var _config_models2;
990
+ declaredModels.filter(function(x) {
991
+ return !isOpenRouterSystemOneModelId(x);
992
+ }).forEach(function(model) {
993
+ errors.push("`".concat(model, "` is not a System One model, and only a System One model answers a decision. Name a `typesafe/…` model (see DEFAULT_OPENROUTER_SYSTEM_ONE_MODEL_ID)."));
994
+ });
995
+ if ((_config_models2 = config.models) === null || _config_models2 === void 0 ? void 0 : _config_models2.length) {
996
+ warnings.push('`models` has no meaning on a decision: the decisions route takes a single `model` and no fallback chain, so every entry here is dropped.');
997
+ }
998
+ } else {
999
+ systemOneModels.forEach(function(model) {
1000
+ errors.push("`".concat(model, "` is a System One model, which answers only `POST /systemone` and cannot serve a completion. Ask it through `openRouterDecision` rather than `callModelForOpenRouterRequest`, or name a chat model here."));
1001
+ });
1002
+ }
763
1003
  var format = (_config_text = config.text) === null || _config_text === void 0 ? void 0 : _config_text.format;
764
1004
  if ((format === null || format === void 0 ? void 0 : format.type) === 'json_schema') {
765
1005
  if (!format.name) {
@@ -799,6 +1039,1116 @@ function _object_spread$1(target) {
799
1039
  };
800
1040
  }
801
1041
 
1042
+ function _array_like_to_array$2(arr, len) {
1043
+ if (len == null || len > arr.length) len = arr.length;
1044
+ for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
1045
+ return arr2;
1046
+ }
1047
+ function _array_without_holes$2(arr) {
1048
+ if (Array.isArray(arr)) return _array_like_to_array$2(arr);
1049
+ }
1050
+ function _define_property$2(obj, key, value) {
1051
+ if (key in obj) {
1052
+ Object.defineProperty(obj, key, {
1053
+ value: value,
1054
+ enumerable: true,
1055
+ configurable: true,
1056
+ writable: true
1057
+ });
1058
+ } else obj[key] = value;
1059
+ return obj;
1060
+ }
1061
+ function _iterable_to_array$2(iter) {
1062
+ if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) {
1063
+ return Array.from(iter);
1064
+ }
1065
+ }
1066
+ function _non_iterable_spread$2() {
1067
+ throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
1068
+ }
1069
+ function _object_spread$2(target) {
1070
+ for(var i = 1; i < arguments.length; i++){
1071
+ var source = arguments[i] != null ? arguments[i] : {};
1072
+ var ownKeys = Object.keys(source);
1073
+ if (typeof Object.getOwnPropertySymbols === "function") {
1074
+ ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
1075
+ return Object.getOwnPropertyDescriptor(source, sym).enumerable;
1076
+ }));
1077
+ }
1078
+ ownKeys.forEach(function(key) {
1079
+ _define_property$2(target, key, source[key]);
1080
+ });
1081
+ }
1082
+ return target;
1083
+ }
1084
+ function _to_consumable_array$2(arr) {
1085
+ return _array_without_holes$2(arr) || _iterable_to_array$2(arr) || _unsupported_iterable_to_array$2(arr) || _non_iterable_spread$2();
1086
+ }
1087
+ function _type_of$1(obj) {
1088
+ "@swc/helpers - typeof";
1089
+ return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj;
1090
+ }
1091
+ function _unsupported_iterable_to_array$2(o, minLen) {
1092
+ if (!o) return;
1093
+ if (typeof o === "string") return _array_like_to_array$2(o, minLen);
1094
+ var n = Object.prototype.toString.call(o).slice(8, -1);
1095
+ if (n === "Object" && o.constructor) n = o.constructor.name;
1096
+ if (n === "Map" || n === "Set") return Array.from(n);
1097
+ if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array$2(o, minLen);
1098
+ }
1099
+ /**
1100
+ * Confidence at or above which {@link asOpenRouterDecisionConfidenceBand} reads `high`.
1101
+ *
1102
+ * A documented STARTING POINT, not a tuned threshold. Note also that a Noul probability and a Choice
1103
+ * confidence answer different questions and are not comparable, so a threshold calibrated for one may
1104
+ * not be carried over to the other.
1105
+ */ var OPENROUTER_DECISION_CONFIDENCE_HIGH = 0.75;
1106
+ /**
1107
+ * Confidence at or above which {@link asOpenRouterDecisionConfidenceBand} reads `medium`.
1108
+ *
1109
+ * See the note on {@link OPENROUTER_DECISION_CONFIDENCE_HIGH}.
1110
+ */ var OPENROUTER_DECISION_CONFIDENCE_MEDIUM = 0.5;
1111
+ /**
1112
+ * Most options a single Choice may declare.
1113
+ *
1114
+ * A hard transport limit, not a guideline. Past it, narrow in two stages — ask a first Choice that picks
1115
+ * the branch, then a second over that branch's members — rather than truncating the set, because an
1116
+ * option that was truncated away is one the model can never pick and nothing reports that it was missing.
1117
+ */ var OPENROUTER_DECISION_CHOICE_OPTIONS_MAX = 255;
1118
+ /**
1119
+ * Fewest levels a Score may declare.
1120
+ */ var OPENROUTER_DECISION_SCORE_LEVELS_MIN = 2;
1121
+ /**
1122
+ * Most levels a Score may declare.
1123
+ *
1124
+ * The trap this guards: a 0..8 band is NINE levels and legal, while a 0..10 scale is eleven and is
1125
+ * rejected at the wire. Past the ceiling, MERGE the levels that cannot be told apart — never truncate
1126
+ * the top, which silently removes the extreme the threshold usually cares about.
1127
+ */ var OPENROUTER_DECISION_SCORE_LEVELS_MAX = 10;
1128
+ /**
1129
+ * Whether a declaration entry says nothing at all.
1130
+ *
1131
+ * A blank string, an empty array, and a keyless object all ask nothing, and all three reach the wire as
1132
+ * a question the model cannot answer.
1133
+ *
1134
+ * @param entry - The entry to test.
1135
+ * @returns True when the entry carries no guidance.
1136
+ *
1137
+ * @__NO_SIDE_EFFECTS__
1138
+ */ function isBlankOpenRouterDecisionEntry(entry) {
1139
+ var result;
1140
+ if (entry == null) {
1141
+ result = true;
1142
+ } else if (typeof entry === 'string') {
1143
+ result = entry.trim() === '';
1144
+ } else if (Array.isArray(entry)) {
1145
+ result = entry.length === 0;
1146
+ } else {
1147
+ result = Object.keys(entry).length === 0;
1148
+ }
1149
+ return result;
1150
+ }
1151
+ /**
1152
+ * The option names a Choice declared — what the model was SHOWN.
1153
+ *
1154
+ * @param question - The choice question.
1155
+ * @returns The declared option names, in declaration order.
1156
+ *
1157
+ * @__NO_SIDE_EFFECTS__
1158
+ */ function openRouterDecisionChoiceOptionNames(question) {
1159
+ return Object.keys(question.options);
1160
+ }
1161
+ /**
1162
+ * Reads a confidence as a band.
1163
+ *
1164
+ * An ABSENT confidence reads `low` rather than throwing: the model is not required to report one, and a
1165
+ * caller that branches on the band should treat "did not say" the same as "not sure".
1166
+ *
1167
+ * @param confidence - The reported confidence, if any.
1168
+ * @returns The band.
1169
+ *
1170
+ * @__NO_SIDE_EFFECTS__
1171
+ */ function asOpenRouterDecisionConfidenceBand(confidence) {
1172
+ var result;
1173
+ if (confidence == null || confidence < OPENROUTER_DECISION_CONFIDENCE_MEDIUM) {
1174
+ result = 'low';
1175
+ } else if (confidence >= OPENROUTER_DECISION_CONFIDENCE_HIGH) {
1176
+ result = 'high';
1177
+ } else {
1178
+ result = 'medium';
1179
+ }
1180
+ return result;
1181
+ }
1182
+ /**
1183
+ * Reads a Choice's distribution as a ranking, most probable first.
1184
+ *
1185
+ * The distribution is a FREE full ranking — the model reports every option, not just the winner — so a
1186
+ * caller wanting a shortlist should read this rather than paying for a second question.
1187
+ *
1188
+ * Returns an empty array when the answer carried no distribution, which is a real reply rather than an
1189
+ * error. The sort is stable, so tied options keep declaration order.
1190
+ *
1191
+ * @param answer - The choice answer.
1192
+ * @returns The ranking rows.
1193
+ *
1194
+ * @__NO_SIDE_EFFECTS__
1195
+ */ function openRouterDecisionChoiceRanking(answer) {
1196
+ var probabilities = answer.probabilities;
1197
+ return probabilities == null ? [] : Object.keys(probabilities).map(function(option) {
1198
+ return {
1199
+ option: option,
1200
+ probability: probabilities[option]
1201
+ };
1202
+ }).sort(function(a, b) {
1203
+ return b.probability - a.probability;
1204
+ });
1205
+ }
1206
+ /**
1207
+ * Reads a Choice's distribution back as the caller's OWN rows, most probable first.
1208
+ *
1209
+ * The seam exists because a Choice's options are usually derived from rows the caller already holds, and
1210
+ * walking the distribution back to them by hand at every call site is where the option-name convention
1211
+ * quietly drifts.
1212
+ *
1213
+ * @param config - The answers, the question to read, and how to resolve an option to a row.
1214
+ * @returns The resolved rows, most probable first. Options that resolve to nothing are dropped.
1215
+ */ function mapOpenRouterDecisionChoiceRows(config) {
1216
+ var answers = config.answers, question = config.question, rowOf = config.rowOf;
1217
+ var answer = answers[question];
1218
+ return answer.type === 'choice' ? openRouterDecisionChoiceRanking(answer).map(function(param) {
1219
+ var option = param.option, probability = param.probability;
1220
+ return {
1221
+ row: rowOf(option),
1222
+ probability: probability
1223
+ };
1224
+ }).filter(function(x) {
1225
+ return x.row != null;
1226
+ }) : [];
1227
+ }
1228
+ /**
1229
+ * Matches a backticked dot-and-index path, the convention for naming a part of the state from inside
1230
+ * `instructions`.
1231
+ */ var OPENROUTER_DECISION_STATE_PATH_REGEX = /`([A-Za-z_$][\w$]*((\.[A-Za-z_$][\w$]*)|(\[\d+\]))*)`/g;
1232
+ /**
1233
+ * Reads back the state paths a declaration entry names.
1234
+ *
1235
+ * The convention is to name a part of the state as a dot-and-index path IN BACKTICKS — `` `phrase` ``,
1236
+ * `` `ticket.sender.email` ``, `` `messages[0].text` `` — so a question points at something the state
1237
+ * actually carries rather than describing it again in prose.
1238
+ *
1239
+ * Documented and inspectable, deliberately NOT enforced: backticks also legitimately quote an option key
1240
+ * or a literal, so a spec may pin that a declaration points at keys its state has, while the transport
1241
+ * never refuses one that does not.
1242
+ *
1243
+ * @param entry - The entry to read. Objects and arrays are walked.
1244
+ * @returns The paths, deduplicated, in the order they first appear.
1245
+ */ function openRouterDecisionStatePaths(entry) {
1246
+ var found = new Set();
1247
+ function read(value) {
1248
+ if (typeof value === 'string') {
1249
+ var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
1250
+ try {
1251
+ for(var _iterator = value.matchAll(OPENROUTER_DECISION_STATE_PATH_REGEX)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
1252
+ var match = _step.value;
1253
+ found.add(match[1]);
1254
+ }
1255
+ } catch (err) {
1256
+ _didIteratorError = true;
1257
+ _iteratorError = err;
1258
+ } finally{
1259
+ try {
1260
+ if (!_iteratorNormalCompletion && _iterator.return != null) {
1261
+ _iterator.return();
1262
+ }
1263
+ } finally{
1264
+ if (_didIteratorError) {
1265
+ throw _iteratorError;
1266
+ }
1267
+ }
1268
+ }
1269
+ } else if (Array.isArray(value)) {
1270
+ value.forEach(read);
1271
+ } else if (value != null && (typeof value === "undefined" ? "undefined" : _type_of$1(value)) === 'object') {
1272
+ Object.values(value).forEach(read);
1273
+ }
1274
+ }
1275
+ read(entry);
1276
+ return Array.from(found);
1277
+ }
1278
+ /**
1279
+ * Declares a Choice question.
1280
+ *
1281
+ * Supply the FULL option set, plus an explicit `other` / `none of the above` when the set may not cover
1282
+ * the input — the distribution is normalised over what was supplied, so a Choice always names a winner
1283
+ * whether or not one fits.
1284
+ *
1285
+ * @param instructions - The complete question, as the model will read it.
1286
+ * @param options - The options, keyed by the name the answer will quote.
1287
+ * @returns The declared question.
1288
+ *
1289
+ * @__NO_SIDE_EFFECTS__
1290
+ */ function openRouterChoiceQuestion(instructions, options) {
1291
+ return {
1292
+ type: 'choice',
1293
+ instructions: instructions,
1294
+ options: options
1295
+ };
1296
+ }
1297
+ /**
1298
+ * Declares a Score question.
1299
+ *
1300
+ * Use as many levels as can be described DISTINCTLY, lowest to highest — three is fine, and a rare
1301
+ * extreme deserves its own level. One dimension per question.
1302
+ *
1303
+ * @param instructions - The complete question, as the model will read it.
1304
+ * @param levels - The levels, lowest first. At least two.
1305
+ * @returns The declared question.
1306
+ *
1307
+ * @__NO_SIDE_EFFECTS__
1308
+ */ function openRouterScoreQuestion(instructions, levels) {
1309
+ return {
1310
+ type: 'score',
1311
+ instructions: instructions,
1312
+ levels: _to_consumable_array$2(levels)
1313
+ };
1314
+ }
1315
+ /**
1316
+ * Declares a Noul question.
1317
+ *
1318
+ * @param instructions - The complete question, as the model will read it.
1319
+ * @param means - Optional explicit definitions of the true and false sides.
1320
+ * @returns The declared question.
1321
+ *
1322
+ * @__NO_SIDE_EFFECTS__
1323
+ */ function openRouterNoulQuestion(instructions, means) {
1324
+ return _object_spread$2({
1325
+ type: 'noul',
1326
+ instructions: instructions
1327
+ }, means == null ? undefined : {
1328
+ means: means
1329
+ });
1330
+ }
1331
+ /**
1332
+ * Describes what is wrong with one declared question, or undefined when nothing is.
1333
+ *
1334
+ * @param question - The question to check.
1335
+ * @returns The problem, or undefined.
1336
+ */ function openRouterDecisionQuestionDeclarationDetail(question) {
1337
+ var result;
1338
+ if (isBlankOpenRouterDecisionEntry(question.instructions)) {
1339
+ result = 'a question with no instructions asks nothing';
1340
+ } else {
1341
+ switch(question.type){
1342
+ case 'choice':
1343
+ {
1344
+ var options = openRouterDecisionChoiceOptionNames(question).length;
1345
+ if (options === 0) {
1346
+ result = 'a Choice declaring no options asks nothing';
1347
+ } else if (options > OPENROUTER_DECISION_CHOICE_OPTIONS_MAX) {
1348
+ result = "a Choice may declare at most ".concat(OPENROUTER_DECISION_CHOICE_OPTIONS_MAX, " options and this one declares ").concat(options, "; narrow in two stages rather than truncating");
1349
+ }
1350
+ break;
1351
+ }
1352
+ case 'score':
1353
+ {
1354
+ var levels = question.levels.length;
1355
+ if (levels < OPENROUTER_DECISION_SCORE_LEVELS_MIN) {
1356
+ result = "a Score needs at least ".concat(OPENROUTER_DECISION_SCORE_LEVELS_MIN, " ordered levels and this one declares ").concat(levels);
1357
+ } else if (levels > OPENROUTER_DECISION_SCORE_LEVELS_MAX) {
1358
+ result = "a Score may declare at most ".concat(OPENROUTER_DECISION_SCORE_LEVELS_MAX, " levels and this one declares ").concat(levels, "; merge the levels that cannot be described distinctly rather than truncating the top");
1359
+ }
1360
+ break;
1361
+ }
1362
+ }
1363
+ }
1364
+ return result;
1365
+ }
1366
+ /**
1367
+ * Validates a declared question map.
1368
+ *
1369
+ * Every problem here fails AT THE DECLARATION, naming the question, rather than as a 4xx about a request
1370
+ * body — which is the difference between a publish that is refused and a run that dies in a sweep at 2am.
1371
+ *
1372
+ * Returns the package's standard validation result so a caller can report question problems and config
1373
+ * problems through one surface.
1374
+ *
1375
+ * @param questions - The declared questions.
1376
+ * @returns The validation result.
1377
+ */ function validateOpenRouterDecisionQuestions(questions) {
1378
+ var errors = [];
1379
+ var warnings = [];
1380
+ var ids = questions == null ? [] : Object.keys(questions);
1381
+ if (ids.length === 0) {
1382
+ errors.push('No questions were declared. A decision asks the model to pick a position inside an answer space, so there is nothing to ask without one.');
1383
+ }
1384
+ ids.forEach(function(id) {
1385
+ var detail = openRouterDecisionQuestionDeclarationDetail(questions[id]);
1386
+ if (detail != null) {
1387
+ errors.push("Question `".concat(id, "` cannot be asked: ").concat(detail, "."));
1388
+ }
1389
+ });
1390
+ return {
1391
+ valid: errors.length === 0,
1392
+ errors: errors,
1393
+ warnings: warnings
1394
+ };
1395
+ }
1396
+
1397
+ function _array_like_to_array$1(arr, len) {
1398
+ if (len == null || len > arr.length) len = arr.length;
1399
+ for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
1400
+ return arr2;
1401
+ }
1402
+ function _array_without_holes$1(arr) {
1403
+ if (Array.isArray(arr)) return _array_like_to_array$1(arr);
1404
+ }
1405
+ function _assert_this_initialized(self) {
1406
+ if (self === void 0) throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
1407
+ return self;
1408
+ }
1409
+ function asyncGeneratorStep$2(gen, resolve, reject, _next, _throw, key, arg) {
1410
+ try {
1411
+ var info = gen[key](arg);
1412
+ var value = info.value;
1413
+ } catch (error) {
1414
+ reject(error);
1415
+ return;
1416
+ }
1417
+ if (info.done) resolve(value);
1418
+ else Promise.resolve(value).then(_next, _throw);
1419
+ }
1420
+ function _async_to_generator$2(fn) {
1421
+ return function() {
1422
+ var self = this, args = arguments;
1423
+ return new Promise(function(resolve, reject) {
1424
+ var gen = fn.apply(self, args);
1425
+ function _next(value) {
1426
+ asyncGeneratorStep$2(gen, resolve, reject, _next, _throw, "next", value);
1427
+ }
1428
+ function _throw(err) {
1429
+ asyncGeneratorStep$2(gen, resolve, reject, _next, _throw, "throw", err);
1430
+ }
1431
+ _next(undefined);
1432
+ });
1433
+ };
1434
+ }
1435
+ function _call_super(_this, derived, args) {
1436
+ derived = _get_prototype_of(derived);
1437
+ return _possible_constructor_return(_this, _is_native_reflect_construct() ? Reflect.construct(derived, args || [], _get_prototype_of(_this).constructor) : derived.apply(_this, args));
1438
+ }
1439
+ function _class_call_check(instance, Constructor) {
1440
+ if (!(instance instanceof Constructor)) throw new TypeError("Cannot call a class as a function");
1441
+ }
1442
+ function _construct(Parent, args, Class) {
1443
+ if (_is_native_reflect_construct()) _construct = Reflect.construct;
1444
+ else {
1445
+ _construct = function construct(Parent, args, Class) {
1446
+ var a = [
1447
+ null
1448
+ ];
1449
+ a.push.apply(a, args);
1450
+ var Constructor = Function.bind.apply(Parent, a);
1451
+ var instance = new Constructor();
1452
+ if (Class) _set_prototype_of(instance, Class.prototype);
1453
+ return instance;
1454
+ };
1455
+ }
1456
+ return _construct.apply(null, arguments);
1457
+ }
1458
+ function _define_property$1(obj, key, value) {
1459
+ if (key in obj) {
1460
+ Object.defineProperty(obj, key, {
1461
+ value: value,
1462
+ enumerable: true,
1463
+ configurable: true,
1464
+ writable: true
1465
+ });
1466
+ } else obj[key] = value;
1467
+ return obj;
1468
+ }
1469
+ function _get_prototype_of(o) {
1470
+ _get_prototype_of = Object.setPrototypeOf ? Object.getPrototypeOf : function getPrototypeOf(o) {
1471
+ return o.__proto__ || Object.getPrototypeOf(o);
1472
+ };
1473
+ return _get_prototype_of(o);
1474
+ }
1475
+ function _inherits(subClass, superClass) {
1476
+ if (typeof superClass !== "function" && superClass !== null) {
1477
+ throw new TypeError("Super expression must either be null or a function");
1478
+ }
1479
+ subClass.prototype = Object.create(superClass && superClass.prototype, {
1480
+ constructor: {
1481
+ value: subClass,
1482
+ writable: true,
1483
+ configurable: true
1484
+ }
1485
+ });
1486
+ if (superClass) _set_prototype_of(subClass, superClass);
1487
+ }
1488
+ function _is_native_function(fn) {
1489
+ return Function.toString.call(fn).indexOf("[native code]") !== -1;
1490
+ }
1491
+ function _is_native_reflect_construct() {
1492
+ try {
1493
+ var result = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
1494
+ } catch (_) {}
1495
+ return (_is_native_reflect_construct = function() {
1496
+ return !!result;
1497
+ })();
1498
+ }
1499
+ function _iterable_to_array$1(iter) {
1500
+ if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) {
1501
+ return Array.from(iter);
1502
+ }
1503
+ }
1504
+ function _non_iterable_spread$1() {
1505
+ throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
1506
+ }
1507
+ function _object_spread$1(target) {
1508
+ for(var i = 1; i < arguments.length; i++){
1509
+ var source = arguments[i] != null ? arguments[i] : {};
1510
+ var ownKeys = Object.keys(source);
1511
+ if (typeof Object.getOwnPropertySymbols === "function") {
1512
+ ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
1513
+ return Object.getOwnPropertyDescriptor(source, sym).enumerable;
1514
+ }));
1515
+ }
1516
+ ownKeys.forEach(function(key) {
1517
+ _define_property$1(target, key, source[key]);
1518
+ });
1519
+ }
1520
+ return target;
1521
+ }
1522
+ function ownKeys$1(object, enumerableOnly) {
1523
+ var keys = Object.keys(object);
1524
+ if (Object.getOwnPropertySymbols) {
1525
+ var symbols = Object.getOwnPropertySymbols(object);
1526
+ keys.push.apply(keys, symbols);
1527
+ }
1528
+ return keys;
1529
+ }
1530
+ function _object_spread_props$1(target, source) {
1531
+ source = source != null ? source : {};
1532
+ if (Object.getOwnPropertyDescriptors) Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
1533
+ else {
1534
+ ownKeys$1(Object(source)).forEach(function(key) {
1535
+ Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
1536
+ });
1537
+ }
1538
+ return target;
1539
+ }
1540
+ function _object_without_properties$1(source, excluded) {
1541
+ if (source == null) return {};
1542
+ var target = {}, sourceKeys, key, i;
1543
+ if (typeof Reflect !== "undefined" && Reflect.ownKeys) {
1544
+ sourceKeys = Reflect.ownKeys(Object(source));
1545
+ for(i = 0; i < sourceKeys.length; i++){
1546
+ key = sourceKeys[i];
1547
+ if (excluded.indexOf(key) >= 0) continue;
1548
+ if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
1549
+ target[key] = source[key];
1550
+ }
1551
+ return target;
1552
+ }
1553
+ target = _object_without_properties_loose$1(source, excluded);
1554
+ if (Object.getOwnPropertySymbols) {
1555
+ sourceKeys = Object.getOwnPropertySymbols(source);
1556
+ for(i = 0; i < sourceKeys.length; i++){
1557
+ key = sourceKeys[i];
1558
+ if (excluded.indexOf(key) >= 0) continue;
1559
+ if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
1560
+ target[key] = source[key];
1561
+ }
1562
+ }
1563
+ return target;
1564
+ }
1565
+ function _object_without_properties_loose$1(source, excluded) {
1566
+ if (source == null) return {};
1567
+ var target = {}, sourceKeys = Object.getOwnPropertyNames(source), key, i;
1568
+ for(i = 0; i < sourceKeys.length; i++){
1569
+ key = sourceKeys[i];
1570
+ if (excluded.indexOf(key) >= 0) continue;
1571
+ if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
1572
+ target[key] = source[key];
1573
+ }
1574
+ return target;
1575
+ }
1576
+ function _possible_constructor_return(self, call) {
1577
+ if (call && (_type_of(call) === "object" || typeof call === "function")) return call;
1578
+ return _assert_this_initialized(self);
1579
+ }
1580
+ function _set_prototype_of(o, p) {
1581
+ _set_prototype_of = Object.setPrototypeOf || function setPrototypeOf(o, p) {
1582
+ o.__proto__ = p;
1583
+ return o;
1584
+ };
1585
+ return _set_prototype_of(o, p);
1586
+ }
1587
+ function _to_consumable_array$1(arr) {
1588
+ return _array_without_holes$1(arr) || _iterable_to_array$1(arr) || _unsupported_iterable_to_array$1(arr) || _non_iterable_spread$1();
1589
+ }
1590
+ function _ts_generator$2(thisArg, body) {
1591
+ var f, y, t, _ = {
1592
+ label: 0,
1593
+ sent: function() {
1594
+ if (t[0] & 1) throw t[1];
1595
+ return t[1];
1596
+ },
1597
+ trys: [],
1598
+ ops: []
1599
+ }, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype), d = Object.defineProperty;
1600
+ return d(g, "next", {
1601
+ value: verb(0)
1602
+ }), d(g, "throw", {
1603
+ value: verb(1)
1604
+ }), d(g, "return", {
1605
+ value: verb(2)
1606
+ }), typeof Symbol === "function" && d(g, Symbol.iterator, {
1607
+ value: function() {
1608
+ return this;
1609
+ }
1610
+ }), g;
1611
+ function verb(n) {
1612
+ return function(v) {
1613
+ return step([
1614
+ n,
1615
+ v
1616
+ ]);
1617
+ };
1618
+ }
1619
+ function step(op) {
1620
+ if (f) throw new TypeError("Generator is already executing.");
1621
+ while(g && (g = 0, op[0] && (_ = 0)), _)try {
1622
+ 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;
1623
+ if (y = 0, t) op = [
1624
+ op[0] & 2,
1625
+ t.value
1626
+ ];
1627
+ switch(op[0]){
1628
+ case 0:
1629
+ case 1:
1630
+ t = op;
1631
+ break;
1632
+ case 4:
1633
+ _.label++;
1634
+ return {
1635
+ value: op[1],
1636
+ done: false
1637
+ };
1638
+ case 5:
1639
+ _.label++;
1640
+ y = op[1];
1641
+ op = [
1642
+ 0
1643
+ ];
1644
+ continue;
1645
+ case 7:
1646
+ op = _.ops.pop();
1647
+ _.trys.pop();
1648
+ continue;
1649
+ default:
1650
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
1651
+ _ = 0;
1652
+ continue;
1653
+ }
1654
+ if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
1655
+ _.label = op[1];
1656
+ break;
1657
+ }
1658
+ if (op[0] === 6 && _.label < t[1]) {
1659
+ _.label = t[1];
1660
+ t = op;
1661
+ break;
1662
+ }
1663
+ if (t && _.label < t[2]) {
1664
+ _.label = t[2];
1665
+ _.ops.push(op);
1666
+ break;
1667
+ }
1668
+ if (t[2]) _.ops.pop();
1669
+ _.trys.pop();
1670
+ continue;
1671
+ }
1672
+ op = body.call(thisArg, _);
1673
+ } catch (e) {
1674
+ op = [
1675
+ 6,
1676
+ e
1677
+ ];
1678
+ y = 0;
1679
+ } finally{
1680
+ f = t = 0;
1681
+ }
1682
+ if (op[0] & 5) throw op[1];
1683
+ return {
1684
+ value: op[0] ? op[1] : void 0,
1685
+ done: true
1686
+ };
1687
+ }
1688
+ }
1689
+ function _type_of(obj) {
1690
+ "@swc/helpers - typeof";
1691
+ return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj;
1692
+ }
1693
+ function _unsupported_iterable_to_array$1(o, minLen) {
1694
+ if (!o) return;
1695
+ if (typeof o === "string") return _array_like_to_array$1(o, minLen);
1696
+ var n = Object.prototype.toString.call(o).slice(8, -1);
1697
+ if (n === "Object" && o.constructor) n = o.constructor.name;
1698
+ if (n === "Map" || n === "Set") return Array.from(n);
1699
+ if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array$1(o, minLen);
1700
+ }
1701
+ function _wrap_native_super(Class) {
1702
+ var _cache = typeof Map === "function" ? new Map() : undefined;
1703
+ _wrap_native_super = function(Class) {
1704
+ if (Class === null || !_is_native_function(Class)) return Class;
1705
+ if (typeof Class !== "function") throw new TypeError("Super expression must either be null or a function");
1706
+ if (typeof _cache !== "undefined") {
1707
+ if (_cache.has(Class)) return _cache.get(Class);
1708
+ _cache.set(Class, Wrapper);
1709
+ }
1710
+ function Wrapper() {
1711
+ return _construct(Class, arguments, _get_prototype_of(this).constructor);
1712
+ }
1713
+ Wrapper.prototype = Object.create(Class.prototype, {
1714
+ constructor: {
1715
+ value: Wrapper,
1716
+ enumerable: false,
1717
+ writable: true,
1718
+ configurable: true
1719
+ }
1720
+ });
1721
+ return _set_prototype_of(Wrapper, Class);
1722
+ };
1723
+ return _wrap_native_super(Class);
1724
+ }
1725
+ /**
1726
+ * How far a distribution's probabilities may sum from 1 before the reply is read as malformed.
1727
+ *
1728
+ * Wide enough to absorb the float rounding a JSON round-trip introduces, narrow enough that a
1729
+ * distribution missing an option does not pass.
1730
+ */ var OPENROUTER_DECISION_DISTRIBUTION_SUM_TOLERANCE = 0.05;
1731
+ /**
1732
+ * Raised when a decision cannot be asked as declared.
1733
+ *
1734
+ * Every declaration problem fails HERE — before a request is built, naming the question — rather than as
1735
+ * a 4xx about a request body. The distinction matters because the fixes are different: a malformed
1736
+ * declaration is a code or authoring bug, while a 4xx is an operational one.
1737
+ */ var OpenRouterDecisionDeclarationError = /*#__PURE__*/ function(Error1) {
1738
+ _inherits(OpenRouterDecisionDeclarationError, Error1);
1739
+ function OpenRouterDecisionDeclarationError(errors) {
1740
+ _class_call_check(this, OpenRouterDecisionDeclarationError);
1741
+ var _this;
1742
+ _this = _call_super(this, OpenRouterDecisionDeclarationError, [
1743
+ "This decision cannot be asked as declared: ".concat(errors.join(' '))
1744
+ ]), _define_property$1(_this, "errors", void 0);
1745
+ _this.name = 'OpenRouterDecisionDeclarationError';
1746
+ _this.errors = errors;
1747
+ return _this;
1748
+ }
1749
+ return OpenRouterDecisionDeclarationError;
1750
+ }(_wrap_native_super(Error));
1751
+ /**
1752
+ * Builds a decision request from an optional resolved prompt plus the caller's state and questions.
1753
+ *
1754
+ * Stored questions and caller questions are merged BY ID with the caller winning, the same composition
1755
+ * a prompt's static seed messages and dynamic `input` already use. What differs is the reason: there is
1756
+ * no prompt cache on this route, so the merge is about where a question is authored — a fixed taxonomy
1757
+ * belongs in a version an operator can edit, a per-call candidate set can only come from code.
1758
+ *
1759
+ * @param params - The prompt, state, questions, overrides, session id, and trace.
1760
+ * @returns The built request.
1761
+ * @throws {OpenRouterDecisionDeclarationError} When the merged question map cannot be asked.
1762
+ */ function openRouterDecisionRequest(params) {
1763
+ var _ref;
1764
+ var prompt = params.prompt, state = params.state, questions = params.questions, overrides = params.overrides, sessionId = params.sessionId, trace = params.trace;
1765
+ var config = mergeOpenRouterModelConfig([
1766
+ prompt === null || prompt === void 0 ? void 0 : prompt.config,
1767
+ overrides
1768
+ ]);
1769
+ var merged = _object_spread$1({}, (_ref = prompt === null || prompt === void 0 ? void 0 : prompt.questions) !== null && _ref !== void 0 ? _ref : undefined, questions !== null && questions !== void 0 ? questions : undefined);
1770
+ var validation = validateOpenRouterDecisionQuestions(merged);
1771
+ if (!validation.valid) {
1772
+ throw new OpenRouterDecisionDeclarationError(validation.errors);
1773
+ }
1774
+ return {
1775
+ config: config,
1776
+ state: state,
1777
+ questions: merged,
1778
+ sessionId: sessionId,
1779
+ trace: trace
1780
+ };
1781
+ }
1782
+ /**
1783
+ * Splits a model config into the parameters a decisions request accepts and the ones it does not.
1784
+ *
1785
+ * The decisions route takes only `model`, `provider` and `user`. Everything else on
1786
+ * {@link OpenRouterModelConfig} describes a completion — an output format, a reasoning budget, a tool
1787
+ * set, a temperature — and none of it has a meaning here: a decision has no free-form output to shape
1788
+ * and no tools to call. Those keys are reported in `dropped` rather than quietly discarded, because a
1789
+ * `temperature` a caller believes is in effect is exactly the kind of thing that is only noticed when
1790
+ * an answer is already wrong.
1791
+ *
1792
+ * `models` (the fallback chain) is dropped for a sharper reason: the decisions route takes a single
1793
+ * `model`, so a chain authored here does not degrade to its first entry — it simply does not exist.
1794
+ *
1795
+ * @param config - The merged model config.
1796
+ * @returns The split config.
1797
+ */ function splitOpenRouterDecisionModelConfig(config) {
1798
+ // Named in a destructure rather than a list of strings, exactly as `splitOpenRouterModelConfig` does,
1799
+ // so TypeScript checks the names against the config interface and a rename cannot leave a stale entry.
1800
+ var _ref = config !== null && config !== void 0 ? config : {}, model = _ref.model, provider = _ref.provider, user = _ref.user, requestTimeoutMs = _ref.requestTimeoutMs, rest = _object_without_properties$1(_ref, [
1801
+ "model",
1802
+ "provider",
1803
+ "user",
1804
+ "requestTimeoutMs"
1805
+ ]);
1806
+ var dropped = Object.keys(filterUndefinedValues(rest));
1807
+ return {
1808
+ requestConfig: filterUndefinedValues({
1809
+ model: model,
1810
+ provider: provider,
1811
+ user: user
1812
+ }),
1813
+ requestTimeoutMs: requestTimeoutMs,
1814
+ dropped: dropped
1815
+ };
1816
+ }
1817
+ /**
1818
+ * Validates a decision request before it is sent.
1819
+ *
1820
+ * The mirror of `validateOpenRouterModelConfig` for this arm, and the reason both exist: the model slug
1821
+ * is the ONLY thing that says which of OpenRouter's two inference surfaces a request belongs to, so it
1822
+ * is checked on both, and neither arm can be entered with a model the other one owns.
1823
+ *
1824
+ * @param request - The request to check.
1825
+ * @returns The validation result.
1826
+ */ function validateOpenRouterDecisionRequest(request) {
1827
+ var errors = [];
1828
+ var warnings = [];
1829
+ if (request == null) {
1830
+ errors.push('No decision request was provided.');
1831
+ } else {
1832
+ var _splitOpenRouterDecisionModelConfig = splitOpenRouterDecisionModelConfig(request.config), requestConfig = _splitOpenRouterDecisionModelConfig.requestConfig, dropped = _splitOpenRouterDecisionModelConfig.dropped;
1833
+ var model = requestConfig.model;
1834
+ if (!model) {
1835
+ errors.push('No `model` was specified.');
1836
+ } else if (!isOpenRouterSystemOneModelId(model)) {
1837
+ errors.push("`".concat(model, "` is not a System One model, and only a System One model answers a decision. Name a `typesafe/…` model (see DEFAULT_OPENROUTER_SYSTEM_ONE_MODEL_ID), or call `callModelForOpenRouterRequest` instead."));
1838
+ }
1839
+ var questionValidation = validateOpenRouterDecisionQuestions(request.questions);
1840
+ questionValidation.errors.forEach(function(x) {
1841
+ return errors.push(x);
1842
+ });
1843
+ questionValidation.warnings.forEach(function(x) {
1844
+ return warnings.push(x);
1845
+ });
1846
+ if (dropped.length > 0) {
1847
+ var names = dropped.map(function(x) {
1848
+ return '`' + x + '`';
1849
+ }).join(', ');
1850
+ warnings.push("The decisions route accepts only `model`, `provider` and `user`; ".concat(names, " ").concat(dropped.length === 1 ? 'was' : 'were', " dropped from the request."));
1851
+ }
1852
+ }
1853
+ return {
1854
+ valid: errors.length === 0,
1855
+ errors: errors,
1856
+ warnings: warnings
1857
+ };
1858
+ }
1859
+ /**
1860
+ * Converts one declared question to its wire shape.
1861
+ *
1862
+ * A pure rename. Three details carry meaning and are not incidental:
1863
+ *
1864
+ * - an option with no description becomes an explicit `null`, which is how the wire spells "undescribed
1865
+ * option" — omitting the key would instead remove the option from the answer space;
1866
+ * - a Noul with no `means` omits `criteria` ENTIRELY rather than sending an empty object;
1867
+ * - a structured entry is passed through by IDENTITY, never copied or re-serialized, because the wire
1868
+ * carries declaration guidance verbatim and a normalising round-trip is exactly the kind of silent
1869
+ * edit this mapping must not make.
1870
+ *
1871
+ * @param question - The declared question.
1872
+ * @returns The wire question.
1873
+ */ function openRouterDecisionWireQuestion(question) {
1874
+ var result;
1875
+ switch(question.type){
1876
+ case 'choice':
1877
+ result = {
1878
+ type: 'choice',
1879
+ instructions: question.instructions,
1880
+ criteria: openRouterDecisionChoiceOptionNames(question).reduce(function(all, option) {
1881
+ var _question_options_option;
1882
+ all[option] = (_question_options_option = question.options[option]) !== null && _question_options_option !== void 0 ? _question_options_option : null;
1883
+ return all;
1884
+ }, {})
1885
+ };
1886
+ break;
1887
+ case 'score':
1888
+ result = {
1889
+ type: 'score',
1890
+ instructions: question.instructions,
1891
+ criteria: _to_consumable_array$1(question.levels)
1892
+ };
1893
+ break;
1894
+ case 'noul':
1895
+ result = _object_spread$1({
1896
+ type: 'noul',
1897
+ instructions: question.instructions
1898
+ }, question.means == null ? undefined : {
1899
+ criteria: {
1900
+ true: question.means.true,
1901
+ false: question.means.false
1902
+ }
1903
+ });
1904
+ break;
1905
+ }
1906
+ return result;
1907
+ }
1908
+ /**
1909
+ * Converts a built request into the `/systemone` request body.
1910
+ *
1911
+ * @param request - The built request.
1912
+ * @returns The request body, in the SDK's request surface.
1913
+ */ function openRouterDecisionRequestBody(request) {
1914
+ var _requestConfig_model, _request_sessionId;
1915
+ var requestConfig = splitOpenRouterDecisionModelConfig(request.config).requestConfig;
1916
+ return filterUndefinedValues(_object_spread_props$1(_object_spread$1({}, requestConfig), {
1917
+ model: (_requestConfig_model = requestConfig.model) !== null && _requestConfig_model !== void 0 ? _requestConfig_model : '',
1918
+ state: request.state,
1919
+ questions: mapObjectMap(request.questions, function(question) {
1920
+ return openRouterDecisionWireQuestion(question);
1921
+ }),
1922
+ sessionId: (_request_sessionId = request.sessionId) !== null && _request_sessionId !== void 0 ? _request_sessionId : undefined,
1923
+ trace: request.trace == null ? undefined : {
1924
+ additionalProperties: _object_spread$1({}, request.trace)
1925
+ }
1926
+ }));
1927
+ }
1928
+ /**
1929
+ * Raised when a reply did not answer the questions that were declared.
1930
+ *
1931
+ * This is always a defect in the RESPONSE and never a judgement the model made. "None of these fits" is
1932
+ * not a fault — it is said through a Noul the caller declared for it, and arrives as an ANSWER. A caller
1933
+ * that catches this is handling a malformed reply, not a negative one.
1934
+ */ var OpenRouterDecisionAnswerFaultError = /*#__PURE__*/ function(Error1) {
1935
+ _inherits(OpenRouterDecisionAnswerFaultError, Error1);
1936
+ function OpenRouterDecisionAnswerFaultError(faults) {
1937
+ _class_call_check(this, OpenRouterDecisionAnswerFaultError);
1938
+ var _this;
1939
+ var described = faults.map(function(x) {
1940
+ return x.question + ' (' + x.kind + '): ' + x.detail;
1941
+ }).join('; ');
1942
+ _this = _call_super(this, OpenRouterDecisionAnswerFaultError, [
1943
+ "The decision reply did not answer its declared questions: ".concat(described)
1944
+ ]), _define_property$1(_this, "faults", void 0);
1945
+ _this.name = 'OpenRouterDecisionAnswerFaultError';
1946
+ _this.faults = faults;
1947
+ return _this;
1948
+ }
1949
+ return OpenRouterDecisionAnswerFaultError;
1950
+ }(_wrap_native_super(Error));
1951
+ /**
1952
+ * Collects everything wrong with one answer against the question that asked it.
1953
+ *
1954
+ * @param question - The declared question.
1955
+ * @param id - The question's id, for reporting.
1956
+ * @param answer - The answer as returned, if any.
1957
+ * @returns The faults found. Empty when the answer is well formed.
1958
+ */ function openRouterDecisionAnswerFaults(question, id, answer) {
1959
+ var faults = [];
1960
+ if (answer == null) {
1961
+ faults.push({
1962
+ kind: 'answer-missing',
1963
+ question: id,
1964
+ detail: 'no answer was returned'
1965
+ });
1966
+ } else if (answer.type !== question.type) {
1967
+ faults.push({
1968
+ kind: 'answer-mistyped',
1969
+ question: id,
1970
+ detail: "a ".concat(question.type, " question was answered with a ").concat(answer.type)
1971
+ });
1972
+ } else if (answer.type === 'choice' && question.type === 'choice') {
1973
+ var declared = new Set(openRouterDecisionChoiceOptionNames(question));
1974
+ if (!declared.has(answer.choice)) {
1975
+ faults.push({
1976
+ kind: 'choice-off-option',
1977
+ question: id,
1978
+ detail: "`".concat(answer.choice, "` was not one of the declared options")
1979
+ });
1980
+ }
1981
+ var probabilities = answer.probabilities;
1982
+ if (probabilities != null) {
1983
+ var options = Object.keys(probabilities);
1984
+ var undeclared = options.filter(function(x) {
1985
+ return !declared.has(x);
1986
+ });
1987
+ if (undeclared.length > 0) {
1988
+ var names = undeclared.map(function(x) {
1989
+ return '`' + x + '`';
1990
+ }).join(', ');
1991
+ faults.push({
1992
+ kind: 'choice-off-option',
1993
+ question: id,
1994
+ detail: "the distribution covers undeclared options ".concat(names)
1995
+ });
1996
+ }
1997
+ var sum = options.reduce(function(total, option) {
1998
+ return total + probabilities[option];
1999
+ }, 0);
2000
+ if (Math.abs(sum - 1) > OPENROUTER_DECISION_DISTRIBUTION_SUM_TOLERANCE) {
2001
+ faults.push({
2002
+ kind: 'value-out-of-range',
2003
+ question: id,
2004
+ detail: "the distribution sums to ".concat(sum, " rather than 1")
2005
+ });
2006
+ }
2007
+ }
2008
+ } else if (answer.type === 'score' && question.type === 'score') {
2009
+ var max = question.levels.length - 1;
2010
+ if (!(answer.score >= 0 && answer.score <= max)) {
2011
+ faults.push({
2012
+ kind: 'value-out-of-range',
2013
+ question: id,
2014
+ detail: "the score ".concat(answer.score, " is outside the declared 0..").concat(max)
2015
+ });
2016
+ }
2017
+ } else if (answer.type === 'noul' && !(answer.noul >= 0 && answer.noul <= 1)) {
2018
+ faults.push({
2019
+ kind: 'value-out-of-range',
2020
+ question: id,
2021
+ detail: "the noul ".concat(answer.noul, " is outside 0..1")
2022
+ });
2023
+ }
2024
+ return faults;
2025
+ }
2026
+ /**
2027
+ * Membership-checks a reply against the questions that were declared.
2028
+ *
2029
+ * This is the transport's GUARANTEE, and the reason no consumer re-checks: past this point a `choice` is
2030
+ * one of the declared options, a `score` is inside the declared range, and a `noul` is a probability. It
2031
+ * is what a decision has instead of the parse-and-salvage a completion needs — the answer space was
2032
+ * declared, so an answer either sits inside it or the reply is broken.
2033
+ *
2034
+ * Every fault is collected rather than the first, because a reply that lost one answer has usually lost
2035
+ * more than one and reporting them one round-trip at a time is no way to debug a declaration.
2036
+ *
2037
+ * An ABSENT distribution or confidence is checked for nothing: only `choice` / `score` / `noul` are
2038
+ * guaranteed on the wire, so their absence is a real reply.
2039
+ *
2040
+ * @param config - The declared questions and the raw answers.
2041
+ * @returns The answers, or the faults.
2042
+ */ function readOpenRouterDecisionAnswers(config) {
2043
+ var questions = config.questions, raw = config.raw;
2044
+ var faults = Object.keys(questions).flatMap(function(id) {
2045
+ return openRouterDecisionAnswerFaults(questions[id], id, raw[id]);
2046
+ });
2047
+ return faults.length > 0 ? {
2048
+ faults: faults
2049
+ } : {
2050
+ answers: raw
2051
+ };
2052
+ }
2053
+ /**
2054
+ * Flattens a decisions reply's usage into the package's usage shape.
2055
+ *
2056
+ * Reported through the SAME {@link OpenRouterRunUsage} a completion reports, so the cost ledger needs no
2057
+ * second counting site and a run's spend is readable without knowing which arm served it.
2058
+ *
2059
+ * Two things about this route's numbers, both measured rather than assumed:
2060
+ *
2061
+ * - `outputTokens` is REPORTED and non-zero, but it is not billed. `cost` is input alone at the model's
2062
+ * input rate — verified live at 350 input tokens and $0.042/Mtok giving exactly $0.0000147, with 34
2063
+ * output tokens on the same reply. So a cost-per-token derived from `totalTokens` here is wrong.
2064
+ * - `cost` is FINAL when it arrives. A completion's is settled server-side afterwards and refined by the
2065
+ * broadcast webhook; a decision's is synchronous, which is why a decision run needs no reconciliation.
2066
+ *
2067
+ * A measurement the reply did not report is OMITTED rather than carried as `undefined`, because a spread
2068
+ * `cost: undefined` reads downstream as "cost zero" rather than "cost unknown".
2069
+ *
2070
+ * @param usage - The usage as returned.
2071
+ * @returns The flattened usage.
2072
+ *
2073
+ * @__NO_SIDE_EFFECTS__
2074
+ */ function openRouterRunUsageFromDecisionsUsage(usage) {
2075
+ var result;
2076
+ if (usage != null) {
2077
+ var inputTokens = usage.inputTokens, outputTokens = usage.outputTokens, cost = usage.cost;
2078
+ var totalTokens = inputTokens == null && outputTokens == null ? undefined : (inputTokens !== null && inputTokens !== void 0 ? inputTokens : 0) + (outputTokens !== null && outputTokens !== void 0 ? outputTokens : 0);
2079
+ result = filterUndefinedValues({
2080
+ inputTokens: inputTokens,
2081
+ outputTokens: outputTokens,
2082
+ totalTokens: totalTokens,
2083
+ cost: cost
2084
+ }, true);
2085
+ }
2086
+ return result;
2087
+ }
2088
+ /**
2089
+ * Asks a decision and returns its answers.
2090
+ *
2091
+ * The request is validated first, so a model that cannot serve a decision is refused HERE rather than by
2092
+ * the route — the mirror of the refusal `callModelForOpenRouterRequest` makes for a System One model on
2093
+ * the completion arm. Which surface a request belongs to is a property of the request, not a choice the
2094
+ * caller makes at the call site.
2095
+ *
2096
+ * @param params - The client, request, and options.
2097
+ * @returns The normalized decision result.
2098
+ * @throws {OpenRouterDecisionDeclarationError} When the request cannot be asked as declared.
2099
+ * @throws {OpenRouterDecisionAnswerFaultError} When the reply did not answer the declared questions.
2100
+ */ function openRouterDecision(params) {
2101
+ return _async_to_generator$2(function() {
2102
+ var _response_answers, client, request, options, validation, requestTimeoutMs, decisionsRequest, result, response, read;
2103
+ return _ts_generator$2(this, function(_state) {
2104
+ switch(_state.label){
2105
+ case 0:
2106
+ client = params.client, request = params.request, options = params.options;
2107
+ validation = validateOpenRouterDecisionRequest(request);
2108
+ if (!validation.valid) {
2109
+ throw new OpenRouterDecisionDeclarationError(validation.errors);
2110
+ }
2111
+ requestTimeoutMs = splitOpenRouterDecisionModelConfig(request.config).requestTimeoutMs;
2112
+ decisionsRequest = openRouterDecisionRequestBody(request);
2113
+ return [
2114
+ 4,
2115
+ systemOneCreate(client, {
2116
+ decisionsRequest: decisionsRequest
2117
+ }, _object_spread$1({}, options, requestTimeoutMs == null ? undefined : {
2118
+ timeoutMs: requestTimeoutMs
2119
+ }))
2120
+ ];
2121
+ case 1:
2122
+ result = _state.sent();
2123
+ if (!result.ok) {
2124
+ throw result.error;
2125
+ }
2126
+ response = result.value;
2127
+ read = readOpenRouterDecisionAnswers({
2128
+ questions: request.questions,
2129
+ raw: (_response_answers = response.answers) !== null && _response_answers !== void 0 ? _response_answers : {}
2130
+ });
2131
+ if (read.faults != null) {
2132
+ throw new OpenRouterDecisionAnswerFaultError(read.faults);
2133
+ }
2134
+ return [
2135
+ 2,
2136
+ {
2137
+ answers: read.answers,
2138
+ model: response.model,
2139
+ provider: response.provider,
2140
+ generationIds: response.id ? [
2141
+ response.id
2142
+ ] : [],
2143
+ usage: openRouterRunUsageFromDecisionsUsage(response.usage),
2144
+ response: response
2145
+ }
2146
+ ];
2147
+ }
2148
+ });
2149
+ })();
2150
+ }
2151
+
802
2152
  function asyncGeneratorStep$1(gen, resolve, reject, _next, _throw, key, arg) {
803
2153
  try {
804
2154
  var info = gen[key](arg);
@@ -1755,4 +3105,4 @@ function _unsupported_iterable_to_array(o, minLen) {
1755
3105
  }));
1756
3106
  }
1757
3107
 
1758
- export { DEFAULT_OPENROUTER_PDF_PARSER_ENGINE, OPENROUTER_CALL_MODEL_HEADER, callModelForOpenRouterRequest, isOpenRouterStateAwaitingDeferredTools, mergeOpenRouterModelConfig, openRouterCallModelInput, openRouterCallResultFromResponse, openRouterDecodeBase64, openRouterEmbeddingVector, openRouterEmbeddings, openRouterFileAnnotationMessage, openRouterFileAnnotationText, openRouterFileParserPlugin, openRouterFileSearchTool, openRouterFunctionCallOutputItems, openRouterGeneration, openRouterGenerationContent, openRouterHostedTools, openRouterInputFileDataPart, openRouterInputFilePartsForAttachedFiles, openRouterInputFileUrlPart, openRouterInputImagePart, openRouterInputMessages, openRouterInputTextPart, openRouterMessagesWithFreshFileAttachments, openRouterMessagesWithoutFileAttachmentData, openRouterModelResultForRequest, openRouterOutputTextFromResponse, openRouterPendingDeferredToolCallFromParsedCall, openRouterPendingDeferredToolCalls, openRouterPromptRequest, openRouterProviderPinnedTo, openRouterResolvedDeferredToolResults, openRouterResponsesRequestBody, openRouterRunErrorFromResponseError, openRouterRunUsageFromResponseUsage, openRouterUnparsedAttachedFiles, parseOpenRouterJsonOutput, sendOpenRouterResponsesRequest, splitOpenRouterModelConfig, validateOpenRouterModelConfig };
3108
+ export { DEFAULT_OPENROUTER_PDF_PARSER_ENGINE, DEFAULT_OPENROUTER_SYSTEM_ONE_MODEL_ID, OPENROUTER_CALL_MODEL_HEADER, OPENROUTER_DECISION_CHOICE_OPTIONS_MAX, OPENROUTER_DECISION_CONFIDENCE_HIGH, OPENROUTER_DECISION_CONFIDENCE_MEDIUM, OPENROUTER_DECISION_DISTRIBUTION_SUM_TOLERANCE, OPENROUTER_DECISION_SCORE_LEVELS_MAX, OPENROUTER_DECISION_SCORE_LEVELS_MIN, OPENROUTER_JEV_1_13_MODEL_ID, OPENROUTER_JEV_LATEST_MODEL_ID, OPENROUTER_JEV_PREVIEW_MODEL_ID, OPENROUTER_SYSTEM_ONE_MODEL_NAMESPACE, OpenRouterDecisionAnswerFaultError, OpenRouterDecisionDeclarationError, OpenRouterSystemOneModelOnCompletionArmError, asOpenRouterDecisionConfidenceBand, callModelForOpenRouterRequest, isBlankOpenRouterDecisionEntry, isOpenRouterStateAwaitingDeferredTools, isOpenRouterSystemOneModelId, mapOpenRouterDecisionChoiceRows, mergeOpenRouterModelConfig, openRouterCallModelInput, openRouterCallResultFromResponse, openRouterChoiceQuestion, openRouterDecision, openRouterDecisionChoiceOptionNames, openRouterDecisionChoiceRanking, openRouterDecisionRequest, openRouterDecisionRequestBody, openRouterDecisionStatePaths, openRouterDecisionWireQuestion, openRouterDecodeBase64, openRouterEmbeddingVector, openRouterEmbeddings, openRouterFileAnnotationMessage, openRouterFileAnnotationText, openRouterFileParserPlugin, openRouterFileSearchTool, openRouterFunctionCallOutputItems, openRouterGeneration, openRouterGenerationContent, openRouterHostedTools, openRouterInputFileDataPart, openRouterInputFilePartsForAttachedFiles, openRouterInputFileUrlPart, openRouterInputImagePart, openRouterInputMessages, openRouterInputTextPart, openRouterMessagesWithFreshFileAttachments, openRouterMessagesWithoutFileAttachmentData, openRouterModelResultForRequest, openRouterNoulQuestion, openRouterOutputTextFromResponse, openRouterPendingDeferredToolCallFromParsedCall, openRouterPendingDeferredToolCalls, openRouterPromptRequest, openRouterProviderPinnedTo, openRouterResolvedDeferredToolResults, openRouterResponsesRequestBody, openRouterRunErrorFromResponseError, openRouterRunUsageFromDecisionsUsage, openRouterRunUsageFromResponseUsage, openRouterScoreQuestion, openRouterUnparsedAttachedFiles, parseOpenRouterJsonOutput, readOpenRouterDecisionAnswers, sendOpenRouterResponsesRequest, splitOpenRouterDecisionModelConfig, splitOpenRouterModelConfig, validateOpenRouterDecisionQuestions, validateOpenRouterDecisionRequest, validateOpenRouterModelConfig };