stitchkit 0.135.0 → 0.135.1

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.
Files changed (49) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/dist/agent-runtime/providers/openrouter-audio.d.ts +122 -0
  3. package/dist/agent-runtime/providers/openrouter-audio.d.ts.map +1 -0
  4. package/dist/agent-runtime/providers/openrouter-catalog-cache.d.ts.map +1 -1
  5. package/dist/agent-runtime/providers/openrouter-catalog.d.ts +2 -0
  6. package/dist/agent-runtime/providers/openrouter-catalog.d.ts.map +1 -1
  7. package/dist/agent-runtime/providers/openrouter-http.d.ts +100 -0
  8. package/dist/agent-runtime/providers/openrouter-http.d.ts.map +1 -0
  9. package/dist/agent-runtime/providers/openrouter-media.d.ts +160 -0
  10. package/dist/agent-runtime/providers/openrouter-media.d.ts.map +1 -0
  11. package/dist/agent-runtime/providers/openrouter-models.d.ts +1 -1
  12. package/dist/agent-runtime/providers/openrouter-models.d.ts.map +1 -1
  13. package/dist/agent-runtime/providers/openrouter-options.d.ts +2 -0
  14. package/dist/agent-runtime/providers/openrouter-options.d.ts.map +1 -1
  15. package/dist/agent-runtime/providers/openrouter-response.d.ts.map +1 -1
  16. package/dist/agent-runtime/providers/openrouter-retrieval.d.ts +114 -0
  17. package/dist/agent-runtime/providers/openrouter-retrieval.d.ts.map +1 -0
  18. package/dist/agent-runtime/providers/openrouter-spend.d.ts +5 -1
  19. package/dist/agent-runtime/providers/openrouter-spend.d.ts.map +1 -1
  20. package/dist/agent-runtime/providers/openrouter-stream.d.ts +29 -0
  21. package/dist/agent-runtime/providers/openrouter-stream.d.ts.map +1 -0
  22. package/dist/agent-runtime/providers/openrouter-systemone.d.ts +82 -0
  23. package/dist/agent-runtime/providers/openrouter-systemone.d.ts.map +1 -0
  24. package/dist/agent-runtime/providers/openrouter-url.d.ts +13 -0
  25. package/dist/agent-runtime/providers/openrouter-url.d.ts.map +1 -0
  26. package/dist/agent-runtime/providers/openrouter.d.ts +4 -1
  27. package/dist/agent-runtime/providers/openrouter.d.ts.map +1 -1
  28. package/dist/agent-runtime/providers/provider-http.d.ts +15 -1
  29. package/dist/agent-runtime/providers/provider-http.d.ts.map +1 -1
  30. package/dist/agent-runtime/stores/branch-observations.d.ts +42 -42
  31. package/dist/agent-runtime/testing/store-conformance-lifecycle.d.ts +20 -20
  32. package/dist/agent-runtime/testing/store-conformance-support.d.ts +10 -10
  33. package/dist/entrypoints/agent-runtime/anthropic.js +1 -1
  34. package/dist/entrypoints/agent-runtime/openai.js +1 -1
  35. package/dist/entrypoints/agent-runtime/openrouter.d.ts +7 -0
  36. package/dist/entrypoints/agent-runtime/openrouter.d.ts.map +1 -1
  37. package/dist/entrypoints/agent-runtime/openrouter.js +1444 -241
  38. package/dist/{index-zfrysr1e.js → index-ht71v1ag.js} +52 -32
  39. package/llms/agent-runtime-openrouter.txt +11 -3
  40. package/llms/agent-runtime.2.txt +333 -224
  41. package/llms/agent-runtime.3.txt +225 -380
  42. package/llms/agent-runtime.4.txt +381 -158
  43. package/llms/agent-runtime.5.txt +157 -152
  44. package/llms/agent-runtime.6.txt +164 -0
  45. package/llms/agent-runtime.txt +30 -332
  46. package/llms/spend.txt +17 -1
  47. package/llms-full.txt +54 -4
  48. package/llms.txt +3 -3
  49. package/package.json +1 -1
@@ -2,13 +2,15 @@ import {
2
2
  AgentModelCatalogSchema2
3
3
  } from "../../index-refgnzy0.js";
4
4
  import {
5
- AgentCacheControlSchema2
6
- } from "../../index-vebzvse6.js";
7
- import {
5
+ DEFAULT_MAX_ERROR_BODY_BYTES,
6
+ DEFAULT_MAX_JSON_BODY_BYTES,
8
7
  redactProviderFailureText,
8
+ headersToRecord,
9
9
  joinProviderUrl,
10
10
  assertNoExtraBodyClash,
11
11
  resolveProviderApiKey,
12
+ extractProviderRequestId,
13
+ buildProviderHttpError,
12
14
  postProviderStream,
13
15
  nonEmptyString2,
14
16
  recordField,
@@ -21,7 +23,10 @@ import {
21
23
  historyHasToolTraffic,
22
24
  parseSseStream,
23
25
  parseSseJson
24
- } from "../../index-zfrysr1e.js";
26
+ } from "../../index-ht71v1ag.js";
27
+ import {
28
+ AgentCacheControlSchema2
29
+ } from "../../index-vebzvse6.js";
25
30
  import {
26
31
  openAiCompatibleUsage2
27
32
  } from "../../index-6t4c98gr.js";
@@ -46,14 +51,16 @@ import {
46
51
  AgentProviderStreamCutError2
47
52
  } from "../../index-vse7x1qt.js";
48
53
  import {
49
- readBoundedBody2
54
+ readBoundedBody2,
55
+ readBoundedText
50
56
  } from "../../index-f16b7rze.js";
51
57
  import {
52
58
  isPositiveSafeInteger,
53
59
  assertPositiveSafeInteger
54
60
  } from "../../index-gr0kxymw.js";
55
61
  import {
56
- assertTimerMs
62
+ assertTimerMs,
63
+ withSignalDeadline
57
64
  } from "../../index-e1y74yra.js";
58
65
  import {
59
66
  abortReason,
@@ -61,6 +68,9 @@ import {
61
68
  linkAbortSignals,
62
69
  withLinkedAbortSignals
63
70
  } from "../../index-rptj3qnc.js";
71
+ import {
72
+ abortError
73
+ } from "../../index-wz392jyz.js";
64
74
  import {
65
75
  isRecord
66
76
  } from "../../index-ps3djm8d.js";
@@ -185,6 +195,90 @@ function collectOpenRouterBenchmarks(artificialResult, designResult) {
185
195
 
186
196
  // src/agent-runtime/providers/openrouter-models.ts
187
197
  import { z as z2 } from "zod";
198
+
199
+ // src/agent-runtime/providers/openrouter-url.ts
200
+ var OPENROUTER_API_BASE_URL = "https://openrouter.ai/api/v1";
201
+ var SCHEME_PREFIX = /^[a-z][a-z0-9+.-]*:/iu;
202
+ var ENCODED_TRAVERSAL = /%(?:2e|2f|5c)/iu;
203
+ function hasControlOrWhitespace(value) {
204
+ for (let i = 0;i < value.length; i += 1) {
205
+ const code = value.charCodeAt(i);
206
+ if (code <= 32 || code === 127)
207
+ return true;
208
+ }
209
+ return false;
210
+ }
211
+ function validateOpenRouterBaseUrl(raw) {
212
+ const candidate = raw ?? OPENROUTER_API_BASE_URL;
213
+ if (typeof candidate !== "string" || candidate.trim().length === 0 || !URL.canParse(candidate)) {
214
+ throw new TypeError("Invalid OpenRouter baseUrl");
215
+ }
216
+ const url = new URL(candidate);
217
+ if (url.protocol !== "http:" && url.protocol !== "https:") {
218
+ throw new TypeError(`OpenRouter baseUrl must use http: or https: protocol (received "${url.protocol}")`);
219
+ }
220
+ if (url.username.length > 0 || url.password.length > 0) {
221
+ throw new TypeError("OpenRouter baseUrl must not contain embedded credentials");
222
+ }
223
+ if (url.hash.length > 0) {
224
+ throw new TypeError("OpenRouter baseUrl must not contain a URL fragment");
225
+ }
226
+ return url;
227
+ }
228
+ function assertOpenRouterHttpUrl(name, value) {
229
+ if (typeof value !== "string" || value.trim().length === 0 || !URL.canParse(value)) {
230
+ throw new TypeError(`${name} must be a valid http: or https: URL`);
231
+ }
232
+ const url = new URL(value);
233
+ if (url.protocol !== "http:" && url.protocol !== "https:") {
234
+ throw new TypeError(`${name} must use http: or https: protocol`);
235
+ }
236
+ if (url.username.length > 0 || url.password.length > 0) {
237
+ throw new TypeError(`${name} must not contain embedded credentials`);
238
+ }
239
+ return value.trim();
240
+ }
241
+ function assertOpenRouterPathSegment(name, value) {
242
+ const trimmed = typeof value === "string" ? value.trim() : "";
243
+ if (trimmed.length === 0 || trimmed === "." || trimmed === ".." || trimmed.includes("/") || trimmed.includes("\\") || trimmed.includes("?") || trimmed.includes("#") || hasControlOrWhitespace(trimmed) || ENCODED_TRAVERSAL.test(trimmed)) {
244
+ throw new TypeError(`Invalid OpenRouter ${name}`);
245
+ }
246
+ return trimmed;
247
+ }
248
+ function resolveOpenRouterUrl(baseUrl, path, query) {
249
+ const base = validateOpenRouterBaseUrl(baseUrl);
250
+ if (typeof path !== "string" || path.length === 0 || SCHEME_PREFIX.test(path) || path.startsWith("//") || path.includes("\\") || path.includes("?") || path.includes("#") || hasControlOrWhitespace(path) || ENCODED_TRAVERSAL.test(path)) {
251
+ throw new TypeError("OpenRouter path must be a relative endpoint path without scheme or query");
252
+ }
253
+ const normalized = path.startsWith("/") ? path : `/${path}`;
254
+ const segments = normalized.slice(1).split("/");
255
+ if (segments.some((segment) => segment.length === 0 || segment === "." || segment === "..")) {
256
+ throw new TypeError("OpenRouter path must not contain empty or traversal segments");
257
+ }
258
+ const basePath = base.pathname.replace(/\/+$/u, "");
259
+ const resolved = new URL(base.toString());
260
+ resolved.pathname = `${basePath}${normalized}`;
261
+ if (resolved.origin !== base.origin || basePath.length > 0 && !resolved.pathname.startsWith(`${basePath}/`)) {
262
+ throw new TypeError("OpenRouter path escaped baseUrl scope");
263
+ }
264
+ if (query instanceof URLSearchParams) {
265
+ for (const [key, value] of query.entries()) {
266
+ resolved.searchParams.append(key, value);
267
+ }
268
+ } else if (query !== undefined) {
269
+ for (const [key, value] of Object.entries(query)) {
270
+ if (value === undefined)
271
+ continue;
272
+ if (typeof value === "number" && !Number.isFinite(value)) {
273
+ throw new TypeError(`OpenRouter query parameter "${key}" must be a finite number`);
274
+ }
275
+ resolved.searchParams.set(key, String(value));
276
+ }
277
+ }
278
+ return resolved;
279
+ }
280
+
281
+ // src/agent-runtime/providers/openrouter-models.ts
188
282
  var OpenRouterModelSchema = z2.object({
189
283
  id: z2.string().min(1),
190
284
  canonical_slug: z2.string().min(1).nullish(),
@@ -327,12 +421,12 @@ function usd(value) {
327
421
  return Number.isFinite(parsed) && parsed >= 0 ? parsed : undefined;
328
422
  }
329
423
  var MODEL_ID = /^~?[a-z0-9][a-z0-9._-]*\/[a-z0-9][a-z0-9._:-]*$/i;
330
- function openRouterEndpointsUrl(modelId) {
424
+ function openRouterEndpointsUrl(modelId, baseUrl) {
331
425
  if (!MODEL_ID.test(modelId) || modelId.includes("..")) {
332
426
  throw new TypeError(`Not an OpenRouter model id: ${modelId}`);
333
427
  }
334
428
  const [author = "", slug = ""] = modelId.split("/");
335
- return new URL(`https://openrouter.ai/api/v1/models/${encodeURIComponent(author)}/${encodeURIComponent(slug)}/endpoints`);
429
+ return resolveOpenRouterUrl(baseUrl, `/models/${encodeURIComponent(author)}/${encodeURIComponent(slug)}/endpoints`);
336
430
  }
337
431
  function assertValidOpenRouterEndpointsFor(endpointsFor) {
338
432
  if (endpointsFor === undefined)
@@ -500,6 +594,445 @@ function parseOpenRouterWirePricing(pricing) {
500
594
  };
501
595
  }
502
596
 
597
+ // src/agent-runtime/providers/openrouter-response.ts
598
+ var GENERIC_ERROR_MESSAGES = new Set([
599
+ "OpenRouter request failed",
600
+ "Provider returned error"
601
+ ]);
602
+ var EMPTY_RAW_SENTINELS = new Set(["null", "[]", "{}", '""']);
603
+ var HTML_SNIPPET_PATTERN = /^\s*(?:<!doctype\s+html\b|<html\b|<head\b|<body\b|<title\b|<h1\b|<div\b|<p\b|<pre\b)/iu;
604
+ var MAX_RAW_SNIPPET_CHARS = 512;
605
+ function readMetadataUsageRecord(metadata) {
606
+ if (!isRecord(metadata))
607
+ return;
608
+ const openrouter = recordField(metadata, "openrouter") ?? metadata;
609
+ return recordField(openrouter, "usage") ?? openrouter;
610
+ }
611
+ function readOpenRouterBaseCost(source, metadata) {
612
+ const direct = nonNegativeNumber(source.cost);
613
+ if (direct !== undefined)
614
+ return direct;
615
+ if (!isRecord(metadata))
616
+ return;
617
+ const openrouter = recordField(metadata, "openrouter") ?? metadata;
618
+ const top = nonNegativeNumber(openrouter.cost);
619
+ if (top !== undefined)
620
+ return top;
621
+ const nestedUsage = recordField(openrouter, "usage");
622
+ return nestedUsage ? nonNegativeNumber(nestedUsage.cost) : undefined;
623
+ }
624
+ function readBooleanField(record, key) {
625
+ return typeof record?.[key] === "boolean" ? record[key] : undefined;
626
+ }
627
+ function normalizeOpenRouterUsageDetails(usage, metadata) {
628
+ const source = isRecord(usage) ? recordField(usage, "raw") ?? usage : {};
629
+ const metaUsage = readMetadataUsageRecord(metadata);
630
+ const prompt = recordField(source, "prompt_tokens_details") ?? recordField(source, "input_tokens_details") ?? {};
631
+ const completion = recordField(source, "completion_tokens_details") ?? recordField(source, "output_tokens_details") ?? {};
632
+ const rawCostDetails = recordField(source, "cost_details") ?? (metaUsage ? recordField(metaUsage, "cost_details") : undefined);
633
+ const isByok = readBooleanField(source, "is_byok") ?? readBooleanField(metaUsage, "is_byok");
634
+ const promptCostUsd = nonNegativeNumber(rawCostDetails?.upstream_inference_prompt_cost) ?? nonNegativeNumber(rawCostDetails?.prompt_cost);
635
+ const outputCostUsd = nonNegativeNumber(rawCostDetails?.upstream_inference_completions_cost) ?? nonNegativeNumber(rawCostDetails?.completions_cost) ?? nonNegativeNumber(rawCostDetails?.completion_cost);
636
+ const upstreamInferenceCost = nonNegativeNumber(rawCostDetails?.upstream_inference_cost);
637
+ const baseCost = readOpenRouterBaseCost(source, metadata);
638
+ let cost;
639
+ if (isByok === true) {
640
+ const upstreamCost = upstreamInferenceCost ?? (promptCostUsd !== undefined || outputCostUsd !== undefined ? (promptCostUsd ?? 0) + (outputCostUsd ?? 0) : undefined);
641
+ cost = upstreamCost !== undefined ? computedUsd((baseCost ?? 0) + upstreamCost) : reportedUsd(baseCost);
642
+ } else {
643
+ cost = reportedUsd(baseCost);
644
+ }
645
+ const normalizedUsage = buildProviderUsage({
646
+ inputTokens: reportedInt(source.prompt_tokens ?? source.input_tokens),
647
+ outputTokens: reportedInt(source.completion_tokens ?? source.output_tokens),
648
+ reasoningTokens: reportedInt(completion.reasoning_tokens),
649
+ cacheReadTokens: reportedInt(prompt.cached_tokens),
650
+ cacheWriteTokens: reportedInt(prompt.cache_write_tokens),
651
+ cost
652
+ });
653
+ const costDetails = promptCostUsd !== undefined || outputCostUsd !== undefined || isByok !== undefined ? {
654
+ ...promptCostUsd !== undefined && { promptCostUsd },
655
+ ...outputCostUsd !== undefined && { outputCostUsd },
656
+ ...isByok !== undefined && { isByok }
657
+ } : undefined;
658
+ return {
659
+ usage: normalizedUsage,
660
+ ...costDetails !== undefined && { costDetails }
661
+ };
662
+ }
663
+ function normalizeOpenRouterUsage(usage, providerMetadata) {
664
+ return normalizeOpenRouterUsageDetails(usage, providerMetadata).usage;
665
+ }
666
+ function readHttpStatusNumber(value) {
667
+ return typeof value === "number" && Number.isInteger(value) && value >= 400 && value < 600 ? value : undefined;
668
+ }
669
+ function readCodeValue(value) {
670
+ return typeof value === "string" && value.length > 0 ? value : typeof value === "number" && Number.isFinite(value) ? value : undefined;
671
+ }
672
+ function extractNestedError(payload, depth) {
673
+ if (depth > 4 || !isRecord(payload))
674
+ return {};
675
+ const err = recordField(payload, "error") ?? payload;
676
+ const outerMessage = nonEmptyString2(err.message);
677
+ const outerCode = readCodeValue(err.code);
678
+ const outerType = nonEmptyString2(err.type) ?? nonEmptyString2(err.status);
679
+ const outerStatus = readHttpStatusNumber(err.code) ?? readHttpStatusNumber(err.status);
680
+ const meta = recordField(err, "metadata");
681
+ const providerName = nonEmptyString2(meta?.provider_name);
682
+ const limitSource = nonEmptyString2(meta?.limit_source);
683
+ const reason = nonEmptyString2(meta?.reason);
684
+ const rawMeta = meta?.raw;
685
+ let nested = {};
686
+ let rawFallback;
687
+ let rawIsHtml = false;
688
+ if (typeof rawMeta === "string" && rawMeta.trim().length > 0) {
689
+ const trimmed = rawMeta.trim();
690
+ if (!EMPTY_RAW_SENTINELS.has(trimmed)) {
691
+ try {
692
+ const parsedRaw = JSON.parse(trimmed);
693
+ if (isRecord(parsedRaw))
694
+ nested = extractNestedError(parsedRaw, depth + 1);
695
+ else
696
+ rawFallback = redactProviderFailureText(trimmed, MAX_RAW_SNIPPET_CHARS);
697
+ } catch {
698
+ rawIsHtml = HTML_SNIPPET_PATTERN.test(trimmed);
699
+ rawFallback = redactProviderFailureText(trimmed, MAX_RAW_SNIPPET_CHARS);
700
+ }
701
+ }
702
+ } else if (isRecord(rawMeta)) {
703
+ nested = extractNestedError(rawMeta, depth + 1);
704
+ }
705
+ const nestedMessage = nested.message && !GENERIC_ERROR_MESSAGES.has(nested.message) ? nested.message : undefined;
706
+ const meaningfulOuter = outerMessage && !GENERIC_ERROR_MESSAGES.has(outerMessage) ? outerMessage : undefined;
707
+ const message = nestedMessage ?? (rawIsHtml && meaningfulOuter !== undefined ? meaningfulOuter : rawFallback) ?? outerMessage;
708
+ const code = typeof nested.code === "string" ? nested.code : outerCode !== undefined ? outerCode : nested.code;
709
+ const errorType = nested.errorType ?? outerType;
710
+ const statusCode = outerStatus ?? nested.statusCode;
711
+ return {
712
+ ...message !== undefined && { message },
713
+ ...code !== undefined && { code },
714
+ ...errorType !== undefined && { errorType },
715
+ ...statusCode !== undefined && { statusCode },
716
+ ...(providerName ?? nested.providerName) !== undefined && {
717
+ providerName: providerName ?? nested.providerName
718
+ },
719
+ ...(limitSource ?? nested.limitSource) !== undefined && {
720
+ limitSource: limitSource ?? nested.limitSource
721
+ },
722
+ ...(reason ?? nested.reason) !== undefined && {
723
+ reason: reason ?? nested.reason
724
+ },
725
+ ...nested.code !== undefined && { upstreamCode: nested.code },
726
+ ...nested.statusCode !== undefined && { upstreamStatus: nested.statusCode }
727
+ };
728
+ }
729
+ function parseOpenRouterError(payload, rawText = "", status) {
730
+ const extracted = extractNestedError(payload, 0);
731
+ const trimmedRaw = rawText.trim();
732
+ const baseMessage = extracted.message ?? (trimmedRaw.length > 0 ? status !== undefined ? `OpenRouter HTTP ${status}: ${redactProviderFailureText(trimmedRaw, MAX_RAW_SNIPPET_CHARS)}` : redactProviderFailureText(trimmedRaw, MAX_RAW_SNIPPET_CHARS) : status !== undefined ? `OpenRouter HTTP ${status}` : "OpenRouter request failed");
733
+ const prefixed = extracted.providerName && !baseMessage.startsWith(`[${extracted.providerName}] `) ? `[${extracted.providerName}] ${baseMessage}` : baseMessage;
734
+ const message = redactProviderFailureText(prefixed);
735
+ const errorMeta = {};
736
+ if (extracted.providerName !== undefined)
737
+ errorMeta.provider_name = extracted.providerName;
738
+ if (extracted.limitSource !== undefined)
739
+ errorMeta.limit_source = extracted.limitSource;
740
+ if (extracted.reason !== undefined)
741
+ errorMeta.reason = extracted.reason;
742
+ if (extracted.upstreamCode !== undefined)
743
+ errorMeta.upstream_code = extracted.upstreamCode;
744
+ if (extracted.upstreamStatus !== undefined)
745
+ errorMeta.upstream_status = extracted.upstreamStatus;
746
+ const statusCode = extracted.statusCode ?? (status !== undefined && status >= 400 ? status : undefined);
747
+ const failureReason = statusCode === 402 && extracted.limitSource === "openrouter_in_flight_budget" ? "overloaded" : undefined;
748
+ return {
749
+ message,
750
+ ...extracted.code !== undefined && { code: extracted.code },
751
+ ...extracted.errorType !== undefined && { errorType: extracted.errorType },
752
+ ...statusCode !== undefined && { statusCode },
753
+ ...failureReason !== undefined && { failureReason },
754
+ ...Object.keys(errorMeta).length > 0 && { metadata: errorMeta }
755
+ };
756
+ }
757
+
758
+ // src/agent-runtime/providers/openrouter-http.ts
759
+ var DEFAULT_OPENROUTER_REQUEST_TIMEOUT_MS = 30000;
760
+ var JSON_CONTENT_TYPE = /^application\/(?:[a-z0-9.+-]+\+)?json(?:\s*;|$)/iu;
761
+ function assertNonEmptyOpenRouterField(caller, name, value) {
762
+ const trimmed = typeof value === "string" ? value.trim() : "";
763
+ if (trimmed.length === 0) {
764
+ throw new TypeError(`${caller}: ${name} must be a non-empty string`);
765
+ }
766
+ return trimmed;
767
+ }
768
+ function pickOpenRouterTransport(input) {
769
+ return {
770
+ ...input.apiKey !== undefined && { apiKey: input.apiKey },
771
+ ...input.baseUrl !== undefined && { baseUrl: input.baseUrl },
772
+ ...input.headers !== undefined && { headers: input.headers },
773
+ ...input.appName !== undefined && { appName: input.appName },
774
+ ...input.appUrl !== undefined && { appUrl: input.appUrl },
775
+ ...input.providerApiKeys !== undefined && { providerApiKeys: input.providerApiKeys },
776
+ ...input.fetch !== undefined && { fetch: input.fetch },
777
+ ...input.signal !== undefined && { signal: input.signal },
778
+ ...input.timeoutMs !== undefined && { timeoutMs: input.timeoutMs },
779
+ ...input.maxErrorBytes !== undefined && { maxErrorBytes: input.maxErrorBytes },
780
+ ...input.maxResponseBytes !== undefined && { maxResponseBytes: input.maxResponseBytes }
781
+ };
782
+ }
783
+ function validateApiKeyString(raw) {
784
+ if (typeof raw !== "string") {
785
+ throw new TypeError("OpenRouter apiKey must resolve to a non-empty string");
786
+ }
787
+ if (/[\r\n]/u.test(raw)) {
788
+ throw new TypeError("OpenRouter apiKey must not contain CR or LF characters");
789
+ }
790
+ const trimmed = raw.trim();
791
+ if (trimmed.length === 0) {
792
+ throw new TypeError("OpenRouter apiKey must be a non-empty string when provided");
793
+ }
794
+ return trimmed;
795
+ }
796
+ function assertValidOpenRouterApiKey(apiKey) {
797
+ if (apiKey === undefined || typeof apiKey === "function")
798
+ return;
799
+ validateApiKeyString(apiKey);
800
+ }
801
+ async function resolveOptionalOpenRouterApiKey2(apiKey) {
802
+ if (apiKey === undefined)
803
+ return;
804
+ const resolved = typeof apiKey === "function" ? await apiKey() : apiKey;
805
+ return validateApiKeyString(resolved);
806
+ }
807
+ function hasHeaderIgnoreCase(headers, targetLower) {
808
+ if (!headers)
809
+ return false;
810
+ return Object.keys(headers).some((key) => key.toLowerCase() === targetLower);
811
+ }
812
+ function assertOpenRouterDirectAuth(input) {
813
+ if (input.apiKey === undefined && input.fetch === undefined && input.baseUrl === undefined && !hasHeaderIgnoreCase(input.headers, "authorization")) {
814
+ throw new TypeError("OpenRouter apiKey is required unless a custom fetch transport or baseUrl is provided");
815
+ }
816
+ }
817
+ function buildOpenRouterBaseHeaders(settings, apiKey) {
818
+ return {
819
+ ...apiKey !== undefined && { authorization: `Bearer ${apiKey}` },
820
+ ...settings.appUrl !== undefined && { "HTTP-Referer": settings.appUrl },
821
+ ...settings.appName !== undefined && { "X-OpenRouter-Title": settings.appName },
822
+ ...settings.providerApiKeys !== undefined && {
823
+ "X-Provider-API-Keys": JSON.stringify(settings.providerApiKeys)
824
+ }
825
+ };
826
+ }
827
+ function prepareOpenRouterRequest(input) {
828
+ const url = resolveOpenRouterUrl(input.baseUrl, input.path, input.query).toString();
829
+ const method = input.method ?? (input.body !== undefined ? "POST" : "GET");
830
+ if (method === "GET" && input.body !== undefined) {
831
+ throw new TypeError("OpenRouter GET request must not include a request body");
832
+ }
833
+ assertValidOpenRouterApiKey(input.apiKey);
834
+ if (input.apiKey !== undefined && hasHeaderIgnoreCase(input.headers, "authorization")) {
835
+ throw new TypeError("OpenRouter request cannot specify both apiKey and Authorization header");
836
+ }
837
+ const isFormData = typeof FormData === "function" && input.body instanceof FormData;
838
+ if (isFormData && hasHeaderIgnoreCase(input.headers, "content-type")) {
839
+ throw new TypeError("OpenRouter FormData request must not specify a Content-Type header (multipart boundary is generated automatically)");
840
+ }
841
+ const timeoutMs = input.timeoutMs ?? DEFAULT_OPENROUTER_REQUEST_TIMEOUT_MS;
842
+ assertTimerMs("timeoutMs", timeoutMs);
843
+ const maxErrorBytes = input.maxErrorBytes ?? DEFAULT_MAX_ERROR_BODY_BYTES;
844
+ assertPositiveSafeInteger("maxErrorBytes", maxErrorBytes);
845
+ let serializedBody;
846
+ if (input.body !== undefined) {
847
+ if (isFormData) {
848
+ serializedBody = input.body;
849
+ } else {
850
+ const encoded = JSON.stringify(input.body);
851
+ if (encoded === undefined) {
852
+ throw new TypeError("OpenRouter request body is not JSON-serializable");
853
+ }
854
+ serializedBody = encoded;
855
+ }
856
+ }
857
+ return {
858
+ url,
859
+ method,
860
+ isFormData,
861
+ ...serializedBody !== undefined && { serializedBody },
862
+ timeoutMs,
863
+ maxErrorBytes,
864
+ fetcher: input.fetch ?? fetch
865
+ };
866
+ }
867
+ function assembleOpenRouterRequestHeaders(input, prepared, apiKey, defaultAccept) {
868
+ const headers = new Headers;
869
+ if (defaultAccept !== undefined)
870
+ headers.set("accept", defaultAccept);
871
+ if (prepared.serializedBody !== undefined && !prepared.isFormData) {
872
+ headers.set("content-type", "application/json");
873
+ }
874
+ for (const [k, v] of Object.entries(buildOpenRouterBaseHeaders(input, apiKey))) {
875
+ headers.set(k, v);
876
+ }
877
+ if (input.headers) {
878
+ for (const [k, v] of Object.entries(input.headers)) {
879
+ headers.set(k, v);
880
+ }
881
+ }
882
+ return headers;
883
+ }
884
+ async function assertNotRedirectedResponse(response) {
885
+ if (response.redirected || response.type === "opaqueredirect" || response.status >= 300 && response.status < 400) {
886
+ await response.body?.cancel().catch(() => {
887
+ return;
888
+ });
889
+ throw new AgentProviderError2(`OpenRouter redirected response refused (HTTP ${response.status})`, {
890
+ provider: "openrouter",
891
+ statusCode: response.status,
892
+ retryable: false,
893
+ responseHeaders: headersToRecord(response.headers)
894
+ });
895
+ }
896
+ }
897
+ function extractOpenRouterGenerationId(headers, parsedBody) {
898
+ const fromHeader = nonEmptyTrimmed(headers.get("x-generation-id"));
899
+ if (fromHeader !== undefined)
900
+ return fromHeader;
901
+ if (!isRecord(parsedBody))
902
+ return;
903
+ const genId = nonEmptyTrimmed(typeof parsedBody.generation_id === "string" ? parsedBody.generation_id : undefined);
904
+ if (genId !== undefined)
905
+ return genId;
906
+ const bodyId = nonEmptyTrimmed(typeof parsedBody.id === "string" ? parsedBody.id : undefined);
907
+ return bodyId?.startsWith("gen-") ? bodyId : undefined;
908
+ }
909
+ function extractCostUsd(parsedBody) {
910
+ if (!isRecord(parsedBody))
911
+ return;
912
+ const cost = normalizeOpenRouterUsageDetails(parsedBody.usage).usage.cost;
913
+ return cost?.value;
914
+ }
915
+ async function openRouterRequestJson(input) {
916
+ const prepared = prepareOpenRouterRequest(input);
917
+ const maxResponseBytes = input.maxResponseBytes ?? DEFAULT_MAX_JSON_BODY_BYTES;
918
+ assertPositiveSafeInteger("maxResponseBytes", maxResponseBytes);
919
+ input.signal?.throwIfAborted();
920
+ const apiKey = await resolveOptionalOpenRouterApiKey2(input.apiKey);
921
+ input.signal?.throwIfAborted();
922
+ return withSignalDeadline(prepared.timeoutMs, input.signal, () => abortError(`OpenRouter request ${input.path} timed out after ${prepared.timeoutMs} ms`, "TimeoutError"), async (signal) => {
923
+ const headers = assembleOpenRouterRequestHeaders(input, prepared, apiKey, "application/json");
924
+ const response = await raceAbort(prepared.fetcher(prepared.url, {
925
+ method: prepared.method,
926
+ headers,
927
+ ...prepared.serializedBody !== undefined && { body: prepared.serializedBody },
928
+ redirect: "error",
929
+ signal
930
+ }), signal, (late) => {
931
+ late.body?.cancel(abortReason(signal)).catch(() => {
932
+ return;
933
+ });
934
+ });
935
+ if (signal.aborted) {
936
+ await response.body?.cancel(abortReason(signal)).catch(() => {
937
+ return;
938
+ });
939
+ signal.throwIfAborted();
940
+ }
941
+ await assertNotRedirectedResponse(response);
942
+ if (!response.ok) {
943
+ throw await buildProviderHttpError({
944
+ provider: "openrouter",
945
+ response,
946
+ signal,
947
+ parseError: parseOpenRouterError,
948
+ maxErrorBytes: prepared.maxErrorBytes
949
+ });
950
+ }
951
+ const requestId = extractProviderRequestId(response.headers);
952
+ const responseHeaders = headersToRecord(response.headers);
953
+ const contentType = response.headers.get("content-type")?.trim() ?? "";
954
+ if (contentType.length > 0 && !JSON_CONTENT_TYPE.test(contentType)) {
955
+ const preview = await readBoundedText(response, { maxBytes: 4096, signal }).catch(() => ({
956
+ kind: "complete",
957
+ text: ""
958
+ }));
959
+ if (signal.aborted)
960
+ signal.throwIfAborted();
961
+ const snippet = preview.kind === "complete" && preview.text.length > 0 ? `: ${redactProviderFailureText(preview.text, 256)}` : "";
962
+ throw new AgentProviderError2(`OpenRouter returned unexpected content-type "${redactProviderFailureText(contentType, 128)}"${snippet}`, {
963
+ provider: "openrouter",
964
+ statusCode: response.status,
965
+ retryable: false,
966
+ ...requestId !== undefined && { requestId },
967
+ responseHeaders
968
+ });
969
+ }
970
+ const bodyResult = await readBoundedText(response, {
971
+ maxBytes: maxResponseBytes,
972
+ signal,
973
+ checkContentLength: true
974
+ });
975
+ if (signal.aborted)
976
+ signal.throwIfAborted();
977
+ if (bodyResult.kind === "over-limit") {
978
+ throw new AgentProviderError2(`OpenRouter JSON response exceeded ${maxResponseBytes} byte limit`, {
979
+ provider: "openrouter",
980
+ statusCode: response.status,
981
+ retryable: false,
982
+ ...requestId !== undefined && { requestId },
983
+ responseHeaders
984
+ });
985
+ }
986
+ if (bodyResult.text.trim().length === 0) {
987
+ throw new AgentProviderError2("OpenRouter returned an empty JSON response body", {
988
+ provider: "openrouter",
989
+ statusCode: response.status,
990
+ retryable: false,
991
+ ...requestId !== undefined && { requestId },
992
+ responseHeaders
993
+ });
994
+ }
995
+ let parsed;
996
+ try {
997
+ parsed = JSON.parse(bodyResult.text);
998
+ } catch (error) {
999
+ throw new AgentProviderError2(`OpenRouter returned invalid JSON body: ${redactProviderFailureText(bodyResult.text, 256)}`, {
1000
+ provider: "openrouter",
1001
+ statusCode: response.status,
1002
+ retryable: false,
1003
+ ...requestId !== undefined && { requestId },
1004
+ responseHeaders,
1005
+ cause: error
1006
+ });
1007
+ }
1008
+ let data = parsed;
1009
+ if (input.schema !== undefined) {
1010
+ const validated = input.schema.safeParse(parsed);
1011
+ if (!validated.success) {
1012
+ throw new AgentProviderError2(`OpenRouter response failed schema validation: ${redactProviderFailureText(validated.error.message, 512)}`, {
1013
+ provider: "openrouter",
1014
+ statusCode: response.status,
1015
+ retryable: false,
1016
+ ...requestId !== undefined && { requestId },
1017
+ responseHeaders,
1018
+ cause: validated.error
1019
+ });
1020
+ }
1021
+ data = validated.data;
1022
+ }
1023
+ const generationId = extractOpenRouterGenerationId(response.headers, parsed);
1024
+ const costUsd = extractCostUsd(parsed);
1025
+ return {
1026
+ data,
1027
+ status: response.status,
1028
+ ...generationId !== undefined && { generationId },
1029
+ ...requestId !== undefined && { requestId },
1030
+ ...costUsd !== undefined && { costUsd },
1031
+ headers: responseHeaders
1032
+ };
1033
+ });
1034
+ }
1035
+
503
1036
  // src/agent-runtime/providers/openrouter-options.ts
504
1037
  import { z as z3 } from "zod";
505
1038
  var OPENROUTER_POLICY_KEYS = [
@@ -587,9 +1120,26 @@ var OpenRouterRequestPolicySchema = z3.strictObject({
587
1120
  message: "A request pins its route by sessionId or by provider.order, not both"
588
1121
  });
589
1122
  });
1123
+ function serializeOpenRouterProviderRouting(raw) {
1124
+ const routing = OpenRouterProviderRoutingSchema.parse(raw);
1125
+ const wire = {
1126
+ ...routing.order && { order: routing.order },
1127
+ ...routing.only && { only: routing.only },
1128
+ ...routing.ignore && { ignore: routing.ignore },
1129
+ ...routing.allowFallbacks !== undefined && { allow_fallbacks: routing.allowFallbacks },
1130
+ ...routing.requireParameters !== undefined && {
1131
+ require_parameters: routing.requireParameters
1132
+ },
1133
+ ...routing.dataCollection && { data_collection: routing.dataCollection },
1134
+ ...routing.zdr !== undefined && { zdr: routing.zdr },
1135
+ ...routing.sort && { sort: routing.sort },
1136
+ ...routing.quantizations && { quantizations: routing.quantizations }
1137
+ };
1138
+ return Object.keys(wire).length > 0 ? wire : undefined;
1139
+ }
590
1140
  function resolveOpenRouterWirePolicy(raw) {
591
1141
  const policy = OpenRouterRequestPolicySchema.parse(raw);
592
- const routing = policy.provider;
1142
+ const routing = policy.provider ? serializeOpenRouterProviderRouting(policy.provider) : undefined;
593
1143
  const price = policy.maxPrice;
594
1144
  const maxPrice = price && {
595
1145
  ...price.promptUsdPerMillion !== undefined && { prompt: price.promptUsdPerMillion },
@@ -599,20 +1149,8 @@ function resolveOpenRouterWirePolicy(raw) {
599
1149
  ...price.requestUsd !== undefined && { request: price.requestUsd },
600
1150
  ...price.imageUsd !== undefined && { image: price.imageUsd }
601
1151
  };
602
- const provider = routing || maxPrice ? {
603
- ...routing?.order && { order: routing.order },
604
- ...routing?.only && { only: routing.only },
605
- ...routing?.ignore && { ignore: routing.ignore },
606
- ...routing?.allowFallbacks !== undefined && {
607
- allow_fallbacks: routing.allowFallbacks
608
- },
609
- ...routing?.requireParameters !== undefined && {
610
- require_parameters: routing.requireParameters
611
- },
612
- ...routing?.dataCollection && { data_collection: routing.dataCollection },
613
- ...routing?.zdr !== undefined && { zdr: routing.zdr },
614
- ...routing?.sort && { sort: routing.sort },
615
- ...routing?.quantizations && { quantizations: routing.quantizations },
1152
+ const provider = routing || maxPrice && Object.keys(maxPrice).length > 0 ? {
1153
+ ...routing,
616
1154
  ...maxPrice && Object.keys(maxPrice).length > 0 && { max_price: maxPrice }
617
1155
  } : undefined;
618
1156
  return {
@@ -662,191 +1200,30 @@ function mergeOpenRouterStepPolicy(base, providerOptions) {
662
1200
  const stepWire = resolveOpenRouterWirePolicy(parsedStep);
663
1201
  let mergedProvider;
664
1202
  if (base.provider || stepWire.provider) {
665
- const baseProvider = stepWire.sessionId !== undefined && base.provider ? Object.fromEntries(Object.entries(base.provider).filter(([k]) => k !== "order")) : base.provider;
666
- const baseMaxPrice = isRecord(baseProvider?.max_price) ? baseProvider.max_price : null;
667
- const stepMaxPrice = isRecord(stepWire.provider?.max_price) ? stepWire.provider.max_price : null;
668
- const combined = {
669
- ...baseProvider,
670
- ...stepWire.provider,
671
- ...baseMaxPrice && stepMaxPrice && { max_price: { ...baseMaxPrice, ...stepMaxPrice } }
672
- };
673
- if (Object.keys(combined).length > 0)
674
- mergedProvider = combined;
675
- }
676
- return {
677
- ...mergedProvider !== undefined && { provider: mergedProvider },
678
- ...(stepWire.reasoning ?? base.reasoning) !== undefined && {
679
- reasoning: stepWire.reasoning ?? base.reasoning
680
- },
681
- ...stepWire.sessionId !== undefined && { stepSessionId: stepWire.sessionId },
682
- ...base.sessionId !== undefined && { baseSessionId: base.sessionId },
683
- looseTools: parsedStep.looseTools !== undefined ? stepWire.looseTools : base.looseTools,
684
- ...stepWire.cacheControl !== undefined && {
685
- explicitCacheControl: stepWire.cacheControl
686
- },
687
- ...base.cacheControl !== undefined && { baseCacheControl: base.cacheControl },
688
- ...stepExtraBody !== undefined && { stepExtraBody }
689
- };
690
- }
691
-
692
- // src/agent-runtime/providers/openrouter-response.ts
693
- var GENERIC_ERROR_MESSAGES = new Set([
694
- "OpenRouter request failed",
695
- "Provider returned error"
696
- ]);
697
- var EMPTY_RAW_SENTINELS = new Set(["null", "[]", "{}", '""']);
698
- var HTML_SNIPPET_PATTERN = /^\s*(?:<!doctype\s+html\b|<html\b|<head\b|<body\b|<title\b|<h1\b|<div\b|<p\b|<pre\b)/iu;
699
- var MAX_RAW_SNIPPET_CHARS = 512;
700
- function readMetadataUsageRecord(metadata) {
701
- if (!isRecord(metadata))
702
- return;
703
- const openrouter = recordField(metadata, "openrouter") ?? metadata;
704
- return recordField(openrouter, "usage") ?? openrouter;
705
- }
706
- function readOpenRouterBaseCost(source, metadata) {
707
- const direct = nonNegativeNumber(source.cost);
708
- if (direct !== undefined)
709
- return direct;
710
- if (!isRecord(metadata))
711
- return;
712
- const openrouter = recordField(metadata, "openrouter") ?? metadata;
713
- const top = nonNegativeNumber(openrouter.cost);
714
- if (top !== undefined)
715
- return top;
716
- const nestedUsage = recordField(openrouter, "usage");
717
- return nestedUsage ? nonNegativeNumber(nestedUsage.cost) : undefined;
718
- }
719
- function readBooleanField(record, key) {
720
- return typeof record?.[key] === "boolean" ? record[key] : undefined;
721
- }
722
- function normalizeOpenRouterUsageDetails(usage, metadata) {
723
- const source = isRecord(usage) ? recordField(usage, "raw") ?? usage : {};
724
- const metaUsage = readMetadataUsageRecord(metadata);
725
- const prompt = recordField(source, "prompt_tokens_details") ?? {};
726
- const completion = recordField(source, "completion_tokens_details") ?? {};
727
- const rawCostDetails = recordField(source, "cost_details") ?? (metaUsage ? recordField(metaUsage, "cost_details") : undefined);
728
- const isByok = readBooleanField(source, "is_byok") ?? readBooleanField(metaUsage, "is_byok");
729
- const promptCostUsd = nonNegativeNumber(rawCostDetails?.upstream_inference_prompt_cost) ?? nonNegativeNumber(rawCostDetails?.prompt_cost);
730
- const outputCostUsd = nonNegativeNumber(rawCostDetails?.upstream_inference_completions_cost) ?? nonNegativeNumber(rawCostDetails?.completions_cost) ?? nonNegativeNumber(rawCostDetails?.completion_cost);
731
- const upstreamInferenceCost = nonNegativeNumber(rawCostDetails?.upstream_inference_cost);
732
- const baseCost = readOpenRouterBaseCost(source, metadata);
733
- let cost;
734
- if (isByok === true) {
735
- const upstreamCost = upstreamInferenceCost ?? (promptCostUsd !== undefined || outputCostUsd !== undefined ? (promptCostUsd ?? 0) + (outputCostUsd ?? 0) : undefined);
736
- cost = upstreamCost !== undefined ? computedUsd((baseCost ?? 0) + upstreamCost) : reportedUsd(baseCost);
737
- } else {
738
- cost = reportedUsd(baseCost);
739
- }
740
- const normalizedUsage = buildProviderUsage({
741
- inputTokens: reportedInt(source.prompt_tokens),
742
- outputTokens: reportedInt(source.completion_tokens),
743
- reasoningTokens: reportedInt(completion.reasoning_tokens),
744
- cacheReadTokens: reportedInt(prompt.cached_tokens),
745
- cacheWriteTokens: reportedInt(prompt.cache_write_tokens),
746
- cost
747
- });
748
- const costDetails = promptCostUsd !== undefined || outputCostUsd !== undefined || isByok !== undefined ? {
749
- ...promptCostUsd !== undefined && { promptCostUsd },
750
- ...outputCostUsd !== undefined && { outputCostUsd },
751
- ...isByok !== undefined && { isByok }
752
- } : undefined;
753
- return {
754
- usage: normalizedUsage,
755
- ...costDetails !== undefined && { costDetails }
756
- };
757
- }
758
- function normalizeOpenRouterUsage(usage, providerMetadata) {
759
- return normalizeOpenRouterUsageDetails(usage, providerMetadata).usage;
760
- }
761
- function readHttpStatusNumber(value) {
762
- return typeof value === "number" && Number.isInteger(value) && value >= 400 && value < 600 ? value : undefined;
763
- }
764
- function readCodeValue(value) {
765
- return typeof value === "string" && value.length > 0 ? value : typeof value === "number" && Number.isFinite(value) ? value : undefined;
766
- }
767
- function extractNestedError(payload, depth) {
768
- if (depth > 4 || !isRecord(payload))
769
- return {};
770
- const err = recordField(payload, "error") ?? payload;
771
- const outerMessage = nonEmptyString2(err.message);
772
- const outerCode = readCodeValue(err.code);
773
- const outerType = nonEmptyString2(err.type) ?? nonEmptyString2(err.status);
774
- const outerStatus = readHttpStatusNumber(err.code) ?? readHttpStatusNumber(err.status);
775
- const meta = recordField(err, "metadata");
776
- const providerName = nonEmptyString2(meta?.provider_name);
777
- const limitSource = nonEmptyString2(meta?.limit_source);
778
- const reason = nonEmptyString2(meta?.reason);
779
- const rawMeta = meta?.raw;
780
- let nested = {};
781
- let rawFallback;
782
- let rawIsHtml = false;
783
- if (typeof rawMeta === "string" && rawMeta.trim().length > 0) {
784
- const trimmed = rawMeta.trim();
785
- if (!EMPTY_RAW_SENTINELS.has(trimmed)) {
786
- try {
787
- const parsedRaw = JSON.parse(trimmed);
788
- if (isRecord(parsedRaw))
789
- nested = extractNestedError(parsedRaw, depth + 1);
790
- else
791
- rawFallback = redactProviderFailureText(trimmed, MAX_RAW_SNIPPET_CHARS);
792
- } catch {
793
- rawIsHtml = HTML_SNIPPET_PATTERN.test(trimmed);
794
- rawFallback = redactProviderFailureText(trimmed, MAX_RAW_SNIPPET_CHARS);
795
- }
796
- }
797
- } else if (isRecord(rawMeta)) {
798
- nested = extractNestedError(rawMeta, depth + 1);
1203
+ const baseProvider = stepWire.sessionId !== undefined && base.provider ? Object.fromEntries(Object.entries(base.provider).filter(([k]) => k !== "order")) : base.provider;
1204
+ const baseMaxPrice = isRecord(baseProvider?.max_price) ? baseProvider.max_price : null;
1205
+ const stepMaxPrice = isRecord(stepWire.provider?.max_price) ? stepWire.provider.max_price : null;
1206
+ const combined = {
1207
+ ...baseProvider,
1208
+ ...stepWire.provider,
1209
+ ...baseMaxPrice && stepMaxPrice && { max_price: { ...baseMaxPrice, ...stepMaxPrice } }
1210
+ };
1211
+ if (Object.keys(combined).length > 0)
1212
+ mergedProvider = combined;
799
1213
  }
800
- const nestedMessage = nested.message && !GENERIC_ERROR_MESSAGES.has(nested.message) ? nested.message : undefined;
801
- const meaningfulOuter = outerMessage && !GENERIC_ERROR_MESSAGES.has(outerMessage) ? outerMessage : undefined;
802
- const message = nestedMessage ?? (rawIsHtml && meaningfulOuter !== undefined ? meaningfulOuter : rawFallback) ?? outerMessage;
803
- const code = typeof nested.code === "string" ? nested.code : outerCode !== undefined ? outerCode : nested.code;
804
- const errorType = nested.errorType ?? outerType;
805
- const statusCode = outerStatus ?? nested.statusCode;
806
1214
  return {
807
- ...message !== undefined && { message },
808
- ...code !== undefined && { code },
809
- ...errorType !== undefined && { errorType },
810
- ...statusCode !== undefined && { statusCode },
811
- ...(providerName ?? nested.providerName) !== undefined && {
812
- providerName: providerName ?? nested.providerName
813
- },
814
- ...(limitSource ?? nested.limitSource) !== undefined && {
815
- limitSource: limitSource ?? nested.limitSource
1215
+ ...mergedProvider !== undefined && { provider: mergedProvider },
1216
+ ...(stepWire.reasoning ?? base.reasoning) !== undefined && {
1217
+ reasoning: stepWire.reasoning ?? base.reasoning
816
1218
  },
817
- ...(reason ?? nested.reason) !== undefined && {
818
- reason: reason ?? nested.reason
1219
+ ...stepWire.sessionId !== undefined && { stepSessionId: stepWire.sessionId },
1220
+ ...base.sessionId !== undefined && { baseSessionId: base.sessionId },
1221
+ looseTools: parsedStep.looseTools !== undefined ? stepWire.looseTools : base.looseTools,
1222
+ ...stepWire.cacheControl !== undefined && {
1223
+ explicitCacheControl: stepWire.cacheControl
819
1224
  },
820
- ...nested.code !== undefined && { upstreamCode: nested.code },
821
- ...nested.statusCode !== undefined && { upstreamStatus: nested.statusCode }
822
- };
823
- }
824
- function parseOpenRouterError(payload, rawText = "", status) {
825
- const extracted = extractNestedError(payload, 0);
826
- const trimmedRaw = rawText.trim();
827
- const baseMessage = extracted.message ?? (trimmedRaw.length > 0 ? status !== undefined ? `OpenRouter HTTP ${status}: ${redactProviderFailureText(trimmedRaw, MAX_RAW_SNIPPET_CHARS)}` : redactProviderFailureText(trimmedRaw, MAX_RAW_SNIPPET_CHARS) : status !== undefined ? `OpenRouter HTTP ${status}` : "OpenRouter request failed");
828
- const prefixed = extracted.providerName && !baseMessage.startsWith(`[${extracted.providerName}] `) ? `[${extracted.providerName}] ${baseMessage}` : baseMessage;
829
- const message = redactProviderFailureText(prefixed);
830
- const errorMeta = {};
831
- if (extracted.providerName !== undefined)
832
- errorMeta.provider_name = extracted.providerName;
833
- if (extracted.limitSource !== undefined)
834
- errorMeta.limit_source = extracted.limitSource;
835
- if (extracted.reason !== undefined)
836
- errorMeta.reason = extracted.reason;
837
- if (extracted.upstreamCode !== undefined)
838
- errorMeta.upstream_code = extracted.upstreamCode;
839
- if (extracted.upstreamStatus !== undefined)
840
- errorMeta.upstream_status = extracted.upstreamStatus;
841
- const statusCode = extracted.statusCode ?? (status !== undefined && status >= 400 ? status : undefined);
842
- const failureReason = statusCode === 402 && extracted.limitSource === "openrouter_in_flight_budget" ? "overloaded" : undefined;
843
- return {
844
- message,
845
- ...extracted.code !== undefined && { code: extracted.code },
846
- ...extracted.errorType !== undefined && { errorType: extracted.errorType },
847
- ...statusCode !== undefined && { statusCode },
848
- ...failureReason !== undefined && { failureReason },
849
- ...Object.keys(errorMeta).length > 0 && { metadata: errorMeta }
1225
+ ...base.cacheControl !== undefined && { baseCacheControl: base.cacheControl },
1226
+ ...stepExtraBody !== undefined && { stepExtraBody }
850
1227
  };
851
1228
  }
852
1229
 
@@ -1753,7 +2130,6 @@ async function* decodeOpenAiChatJsonResponse(body, options) {
1753
2130
  }
1754
2131
 
1755
2132
  // src/agent-runtime/providers/openrouter.ts
1756
- var DEFAULT_OPENROUTER_BASE_URL = "https://openrouter.ai/api/v1";
1757
2133
  var EMPTY_WIRE_POLICY = { looseTools: false };
1758
2134
  function catalogJson(fetcher, url, apiKey, signal) {
1759
2135
  return openRouterJson({
@@ -1771,17 +2147,21 @@ function openRouterModelCatalog(options = {}) {
1771
2147
  const timeoutMs = options.timeoutMs ?? 1e4;
1772
2148
  assertTimerMs("timeoutMs", timeoutMs);
1773
2149
  assertValidStaticOpenRouterApiKey(options.apiKey);
2150
+ validateOpenRouterBaseUrl(options.baseUrl);
1774
2151
  return {
1775
2152
  async load(input = {}) {
1776
- const modelsUrl = new URL("https://openrouter.ai/api/v1/models");
1777
- modelsUrl.searchParams.set("supported_parameters", "tools");
1778
- modelsUrl.searchParams.set("output_modalities", "text");
1779
- modelsUrl.searchParams.set("sort", "top-weekly");
1780
- const artificialUrl = new URL("https://openrouter.ai/api/v1/benchmarks");
1781
- artificialUrl.searchParams.set("source", "artificial-analysis");
1782
- const designUrl = new URL("https://openrouter.ai/api/v1/benchmarks");
1783
- designUrl.searchParams.set("source", "design-arena");
1784
- designUrl.searchParams.set("arena", "agents");
2153
+ const modelsUrl = resolveOpenRouterUrl(options.baseUrl, "/models", {
2154
+ supported_parameters: "tools",
2155
+ output_modalities: "text",
2156
+ sort: "top-weekly"
2157
+ });
2158
+ const artificialUrl = resolveOpenRouterUrl(options.baseUrl, "/benchmarks", {
2159
+ source: "artificial-analysis"
2160
+ });
2161
+ const designUrl = resolveOpenRouterUrl(options.baseUrl, "/benchmarks", {
2162
+ source: "design-arena",
2163
+ arena: "agents"
2164
+ });
1785
2165
  const [modelsRaw, artificialResult, designResult] = await withOpenRouterTimeout(timeoutMs, input.signal, (signal) => Promise.all([
1786
2166
  catalogJson(fetcher, modelsUrl, options.apiKey, signal),
1787
2167
  benchmarkOutcome(fetcher, artificialUrl, options.apiKey, signal),
@@ -1839,16 +2219,6 @@ function openRouterModelCatalog(options = {}) {
1839
2219
  }
1840
2220
  };
1841
2221
  }
1842
- function buildBaseHeaders(settings, apiKey) {
1843
- return {
1844
- authorization: `Bearer ${apiKey}`,
1845
- ...settings.appUrl !== undefined && { "HTTP-Referer": settings.appUrl },
1846
- ...settings.appName !== undefined && { "X-OpenRouter-Title": settings.appName },
1847
- ...settings.providerApiKeys !== undefined && {
1848
- "X-Provider-API-Keys": JSON.stringify(settings.providerApiKeys)
1849
- }
1850
- };
1851
- }
1852
2222
  function buildOpenRouterRequestBody(input) {
1853
2223
  const { modelId, request, policy, sessionPerConversation, extraBody } = input;
1854
2224
  const merged = mergeOpenRouterStepPolicy(policy, request.providerOptions);
@@ -1888,7 +2258,7 @@ function buildOpenRouterRequestBody(input) {
1888
2258
  function openRouterProvider(settings, access = {}) {
1889
2259
  assertNoExtraBodyClash("openRouterProvider", settings.extraBody, OPENROUTER_POLICY_KEYS);
1890
2260
  const defaultPolicy = access.defaultPolicy !== undefined ? resolveOpenRouterWirePolicy(access.defaultPolicy) : EMPTY_WIRE_POLICY;
1891
- const endpoint = joinProviderUrl(settings.baseUrl ?? DEFAULT_OPENROUTER_BASE_URL, "/chat/completions");
2261
+ const endpoint = joinProviderUrl(settings.baseUrl ?? OPENROUTER_API_BASE_URL, "/chat/completions");
1892
2262
  const policyOf = (modelId) => {
1893
2263
  const resolved = access.resolvePolicy?.(modelId);
1894
2264
  return resolved !== undefined ? resolveOpenRouterWirePolicy(resolved) : defaultPolicy;
@@ -1911,7 +2281,7 @@ function openRouterProvider(settings, access = {}) {
1911
2281
  const response = await postProviderStream({
1912
2282
  provider: "openrouter",
1913
2283
  url: endpoint,
1914
- headers: buildBaseHeaders(settings, apiKey),
2284
+ headers: buildOpenRouterBaseHeaders(settings, apiKey),
1915
2285
  ...settings.headers !== undefined && { extraHeaders: settings.headers },
1916
2286
  ...request.headers !== undefined && { requestHeaders: request.headers },
1917
2287
  body,
@@ -2076,7 +2446,8 @@ function mapSnapshotModel(model, endpoints) {
2076
2446
  }
2077
2447
  async function fetchOpenRouterModelEndpoints(modelId, options = {}) {
2078
2448
  assertValidStaticOpenRouterApiKey(options.apiKey);
2079
- const url = openRouterEndpointsUrl(modelId);
2449
+ validateOpenRouterBaseUrl(options.baseUrl);
2450
+ const url = openRouterEndpointsUrl(modelId, options.baseUrl);
2080
2451
  const parsed = OpenRouterEndpointsResponseSchema.parse(await withOpenRouterTimeout(options.timeoutMs ?? 1e4, options.signal, (signal) => openRouterJson({
2081
2452
  fetcher: options.fetcher ?? fetch,
2082
2453
  url,
@@ -2119,11 +2490,12 @@ async function loadOpenRouterCatalogSnapshot(options = {}) {
2119
2490
  if (!Number.isInteger(concurrency) || concurrency < 1 || concurrency > 16)
2120
2491
  throw new RangeError("concurrency must be an integer from 1 to 16");
2121
2492
  assertValidStaticOpenRouterApiKey(options.apiKey);
2493
+ validateOpenRouterBaseUrl(options.baseUrl);
2122
2494
  assertValidOpenRouterEndpointsFor(options.endpointsFor);
2123
2495
  const observedAt = (options.now?.() ?? new Date).toISOString();
2124
2496
  const listing = OpenRouterModelsResponseSchema.parse(await withOpenRouterTimeout(options.timeoutMs ?? 1e4, options.signal, (signal) => openRouterJson({
2125
2497
  fetcher: options.fetcher ?? fetch,
2126
- url: new URL("https://openrouter.ai/api/v1/models"),
2498
+ url: resolveOpenRouterUrl(options.baseUrl, "/models"),
2127
2499
  ...options.apiKey !== undefined && { apiKey: options.apiKey },
2128
2500
  signal,
2129
2501
  ...options.maxResponseBytes !== undefined && { maxBytes: options.maxResponseBytes }
@@ -2609,6 +2981,368 @@ function evaluateOpenRouterModelAdmission(input) {
2609
2981
  }
2610
2982
  return { state: "admitted" };
2611
2983
  }
2984
+ // src/agent-runtime/providers/openrouter-audio.ts
2985
+ import { z as z8 } from "zod";
2986
+
2987
+ // src/agent-runtime/providers/openrouter-stream.ts
2988
+ function wrapStreamWithCallerAbort(source, callerSignal, onRelease) {
2989
+ if (!callerSignal) {
2990
+ onRelease();
2991
+ return source;
2992
+ }
2993
+ const reader = source.getReader();
2994
+ let settled = false;
2995
+ const detach = () => {
2996
+ if (settled)
2997
+ return;
2998
+ settled = true;
2999
+ callerSignal.removeEventListener("abort", onAbort);
3000
+ onRelease();
3001
+ };
3002
+ const onAbort = () => {
3003
+ detach();
3004
+ reader.cancel(abortReason(callerSignal)).catch(() => {
3005
+ return;
3006
+ });
3007
+ };
3008
+ if (callerSignal.aborted) {
3009
+ onAbort();
3010
+ } else {
3011
+ callerSignal.addEventListener("abort", onAbort, { once: true });
3012
+ reader.closed.then(detach, detach);
3013
+ }
3014
+ return new ReadableStream({
3015
+ async pull(controller) {
3016
+ if (callerSignal.aborted) {
3017
+ detach();
3018
+ await reader.cancel(abortReason(callerSignal)).catch(() => {
3019
+ return;
3020
+ });
3021
+ controller.error(abortReason(callerSignal));
3022
+ return;
3023
+ }
3024
+ try {
3025
+ const chunk = await raceAbort(reader.read(), callerSignal);
3026
+ if (chunk.done) {
3027
+ detach();
3028
+ reader.releaseLock();
3029
+ controller.close();
3030
+ return;
3031
+ }
3032
+ controller.enqueue(chunk.value);
3033
+ } catch (error) {
3034
+ detach();
3035
+ await reader.cancel(error).catch(() => {
3036
+ return;
3037
+ });
3038
+ controller.error(error);
3039
+ }
3040
+ },
3041
+ async cancel(reason) {
3042
+ detach();
3043
+ await reader.cancel(reason).catch(() => {
3044
+ return;
3045
+ });
3046
+ }
3047
+ });
3048
+ }
3049
+ async function openRouterRequestStream(input) {
3050
+ const prepared = prepareOpenRouterRequest(input);
3051
+ input.signal?.throwIfAborted();
3052
+ const apiKey = await resolveOptionalOpenRouterApiKey2(input.apiKey);
3053
+ input.signal?.throwIfAborted();
3054
+ const deadline = new AbortController;
3055
+ const timer = setTimeout(() => deadline.abort(abortError(`OpenRouter stream ${input.path} timed out after ${prepared.timeoutMs} ms`, "TimeoutError")), prepared.timeoutMs);
3056
+ const openLink = linkAbortSignals(input.signal, deadline.signal);
3057
+ const disarmOpenPhase = () => {
3058
+ clearTimeout(timer);
3059
+ openLink.release();
3060
+ };
3061
+ let response;
3062
+ try {
3063
+ const headers = assembleOpenRouterRequestHeaders(input, prepared, apiKey, undefined);
3064
+ response = await raceAbort(prepared.fetcher(prepared.url, {
3065
+ method: prepared.method,
3066
+ headers,
3067
+ ...prepared.serializedBody !== undefined && { body: prepared.serializedBody },
3068
+ redirect: "error",
3069
+ signal: openLink.signal
3070
+ }), openLink.signal, (late) => {
3071
+ late.body?.cancel(abortReason(openLink.signal)).catch(() => {
3072
+ return;
3073
+ });
3074
+ });
3075
+ if (openLink.signal.aborted) {
3076
+ await response.body?.cancel(abortReason(openLink.signal)).catch(() => {
3077
+ return;
3078
+ });
3079
+ openLink.signal.throwIfAborted();
3080
+ }
3081
+ await assertNotRedirectedResponse(response);
3082
+ if (!response.ok) {
3083
+ throw await buildProviderHttpError({
3084
+ provider: "openrouter",
3085
+ response,
3086
+ signal: openLink.signal,
3087
+ parseError: parseOpenRouterError,
3088
+ maxErrorBytes: prepared.maxErrorBytes
3089
+ });
3090
+ }
3091
+ } catch (error) {
3092
+ disarmOpenPhase();
3093
+ throw error;
3094
+ }
3095
+ clearTimeout(timer);
3096
+ const requestId = extractProviderRequestId(response.headers);
3097
+ const responseHeaders = headersToRecord(response.headers);
3098
+ if (!response.body) {
3099
+ openLink.release();
3100
+ throw new AgentProviderError2("OpenRouter returned an empty streaming response body", {
3101
+ provider: "openrouter",
3102
+ statusCode: response.status,
3103
+ retryable: false,
3104
+ ...requestId !== undefined && { requestId },
3105
+ responseHeaders
3106
+ });
3107
+ }
3108
+ const generationId = extractOpenRouterGenerationId(response.headers);
3109
+ const contentType = response.headers.get("content-type")?.trim() || "application/octet-stream";
3110
+ return {
3111
+ body: wrapStreamWithCallerAbort(response.body, input.signal, openLink.release),
3112
+ contentType,
3113
+ status: response.status,
3114
+ ...generationId !== undefined && { generationId },
3115
+ ...requestId !== undefined && { requestId },
3116
+ headers: responseHeaders
3117
+ };
3118
+ }
3119
+
3120
+ // src/agent-runtime/providers/openrouter-audio.ts
3121
+ var STT_OWNED_KEYS = [
3122
+ "model",
3123
+ "file",
3124
+ "input_audio",
3125
+ "source_url",
3126
+ "language",
3127
+ "prompt",
3128
+ "temperature",
3129
+ "response_format",
3130
+ "timestamp_granularities",
3131
+ "timestamp_granularities[]",
3132
+ "diarize",
3133
+ "provider"
3134
+ ];
3135
+ var TTS_OWNED_KEYS = [
3136
+ "model",
3137
+ "input",
3138
+ "voice",
3139
+ "response_format",
3140
+ "speed",
3141
+ "output_delivery",
3142
+ "provider"
3143
+ ];
3144
+ var NonNegativeNum = z8.number().nonnegative();
3145
+ var NonNegativeInt = z8.int().nonnegative();
3146
+ var TranscriptionSegmentSchema = z8.object({
3147
+ id: z8.int().nonnegative().optional(),
3148
+ start: NonNegativeNum,
3149
+ end: NonNegativeNum,
3150
+ text: z8.string(),
3151
+ speaker: z8.string().optional()
3152
+ }).loose();
3153
+ var TranscriptionWordSchema = z8.object({
3154
+ word: z8.string(),
3155
+ start: NonNegativeNum,
3156
+ end: NonNegativeNum,
3157
+ speaker: z8.string().optional()
3158
+ }).loose();
3159
+ var TranscriptionUsageSchema = z8.object({
3160
+ seconds: NonNegativeNum.optional(),
3161
+ total_tokens: NonNegativeInt.optional(),
3162
+ input_tokens: NonNegativeInt.optional(),
3163
+ output_tokens: NonNegativeInt.optional(),
3164
+ prompt_tokens: NonNegativeInt.optional(),
3165
+ completion_tokens: NonNegativeInt.optional(),
3166
+ cost: NonNegativeNum.optional()
3167
+ }).loose();
3168
+ var OpenRouterAudioTranscriptionResponseSchema = z8.object({
3169
+ text: z8.string(),
3170
+ task: z8.string().optional(),
3171
+ language: z8.string().optional(),
3172
+ duration: NonNegativeNum.optional(),
3173
+ segments: z8.array(TranscriptionSegmentSchema).optional(),
3174
+ words: z8.array(TranscriptionWordSchema).optional(),
3175
+ usage: TranscriptionUsageSchema.optional()
3176
+ }).loose();
3177
+ function toSafeBlob(data, mimeType) {
3178
+ if (data instanceof Blob) {
3179
+ return mimeType !== undefined && data.type !== mimeType ? new Blob([data], { type: mimeType }) : data;
3180
+ }
3181
+ const source = data instanceof Uint8Array ? data : new Uint8Array(data);
3182
+ const copy = new Uint8Array(source.byteLength);
3183
+ copy.set(source);
3184
+ return mimeType !== undefined ? new Blob([copy], { type: mimeType }) : new Blob([copy]);
3185
+ }
3186
+ function hasUnsafeFilenameChar(value) {
3187
+ for (let i = 0;i < value.length; i += 1) {
3188
+ const code = value.charCodeAt(i);
3189
+ const ch = value[i];
3190
+ if (code < 32 || code === 127 || ch === '"' || ch === "\\" || ch === "/")
3191
+ return true;
3192
+ }
3193
+ return false;
3194
+ }
3195
+ function validateFilename(filename) {
3196
+ const trimmed = filename.trim();
3197
+ if (trimmed.length === 0 || hasUnsafeFilenameChar(trimmed)) {
3198
+ throw new TypeError("openRouterAudioTranscription: filename must be non-empty and free of path separators, quotes, or control characters");
3199
+ }
3200
+ return trimmed;
3201
+ }
3202
+ function appendFormExtraBody(form, extraBody) {
3203
+ for (const [key, value] of Object.entries(extraBody)) {
3204
+ if (value === undefined)
3205
+ continue;
3206
+ if (value === null || typeof value === "function" || typeof value === "symbol") {
3207
+ throw new TypeError(`openRouterAudioTranscription: unsupported multipart extraBody value for "${key}"`);
3208
+ }
3209
+ if (typeof value === "number" && !Number.isFinite(value)) {
3210
+ throw new TypeError(`openRouterAudioTranscription: extraBody["${key}"] must be a finite number`);
3211
+ }
3212
+ if (value instanceof Blob) {
3213
+ form.append(key, value);
3214
+ } else if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
3215
+ form.append(key, String(value));
3216
+ } else if (Array.isArray(value) || isRecord(value)) {
3217
+ form.append(key, JSON.stringify(value));
3218
+ } else {
3219
+ throw new TypeError(`openRouterAudioTranscription: unsupported multipart extraBody value for "${key}"`);
3220
+ }
3221
+ }
3222
+ }
3223
+ function buildTranscriptionBody(input, model, provider) {
3224
+ if (input.audio.kind === "file") {
3225
+ const form = new FormData;
3226
+ const defaultName = typeof File === "function" && input.audio.data instanceof File && input.audio.data.name ? input.audio.data.name : "audio";
3227
+ const filename = validateFilename(input.audio.filename ?? defaultName);
3228
+ form.append("file", toSafeBlob(input.audio.data, input.audio.mimeType), filename);
3229
+ form.append("model", model);
3230
+ if (input.language !== undefined)
3231
+ form.append("language", input.language);
3232
+ if (input.prompt !== undefined)
3233
+ form.append("prompt", input.prompt);
3234
+ if (input.temperature !== undefined)
3235
+ form.append("temperature", String(input.temperature));
3236
+ if (input.responseFormat !== undefined)
3237
+ form.append("response_format", input.responseFormat);
3238
+ if (input.timestampGranularities !== undefined) {
3239
+ for (const granularity of input.timestampGranularities) {
3240
+ form.append("timestamp_granularities[]", granularity);
3241
+ }
3242
+ }
3243
+ if (input.diarize !== undefined)
3244
+ form.append("diarize", String(input.diarize));
3245
+ if (provider !== undefined)
3246
+ form.append("provider", JSON.stringify(provider));
3247
+ if (input.extraBody !== undefined)
3248
+ appendFormExtraBody(form, input.extraBody);
3249
+ return form;
3250
+ }
3251
+ const audioFields = input.audio.kind === "base64" ? {
3252
+ input_audio: {
3253
+ data: input.audio.data,
3254
+ format: input.audio.format
3255
+ }
3256
+ } : { source_url: assertOpenRouterHttpUrl("audio.url", input.audio.url) };
3257
+ return {
3258
+ ...input.extraBody ?? {},
3259
+ model,
3260
+ ...audioFields,
3261
+ ...input.language !== undefined && { language: input.language },
3262
+ ...input.prompt !== undefined && { prompt: input.prompt },
3263
+ ...input.temperature !== undefined && { temperature: input.temperature },
3264
+ ...input.responseFormat !== undefined && { response_format: input.responseFormat },
3265
+ ...input.timestampGranularities !== undefined && {
3266
+ timestamp_granularities: [...input.timestampGranularities]
3267
+ },
3268
+ ...input.diarize !== undefined && { diarize: input.diarize },
3269
+ ...provider !== undefined && { provider }
3270
+ };
3271
+ }
3272
+ async function openRouterAudioTranscription(input) {
3273
+ assertOpenRouterDirectAuth(input);
3274
+ const model = assertNonEmptyOpenRouterField("openRouterAudioTranscription", "model", input.model);
3275
+ if (input.audio.kind === "base64") {
3276
+ if (input.audio.data.trim().length === 0 || input.audio.format.trim().length === 0) {
3277
+ throw new TypeError("openRouterAudioTranscription: base64 audio requires non-empty data and format");
3278
+ }
3279
+ }
3280
+ if (input.temperature !== undefined && (!Number.isFinite(input.temperature) || input.temperature < 0 || input.temperature > 1)) {
3281
+ throw new RangeError("openRouterAudioTranscription: temperature must be between 0 and 1");
3282
+ }
3283
+ if (input.diarize === true && input.responseFormat !== "verbose_json") {
3284
+ throw new TypeError('openRouterAudioTranscription: diarize requires responseFormat: "verbose_json"');
3285
+ }
3286
+ assertNoExtraBodyClash("openRouterAudioTranscription", input.extraBody, STT_OWNED_KEYS);
3287
+ const provider = input.provider !== undefined ? serializeOpenRouterProviderRouting(input.provider) : undefined;
3288
+ const body = buildTranscriptionBody(input, model, provider);
3289
+ const response = await openRouterRequestJson({
3290
+ ...pickOpenRouterTransport(input),
3291
+ path: "/audio/transcriptions",
3292
+ method: "POST",
3293
+ body,
3294
+ schema: OpenRouterAudioTranscriptionResponseSchema
3295
+ });
3296
+ return {
3297
+ text: response.data.text,
3298
+ ...response.data.task !== undefined && { task: response.data.task },
3299
+ ...response.data.language !== undefined && { language: response.data.language },
3300
+ ...response.data.duration !== undefined && { duration: response.data.duration },
3301
+ ...response.data.segments !== undefined && { segments: response.data.segments },
3302
+ ...response.data.words !== undefined && { words: response.data.words },
3303
+ ...response.data.usage !== undefined && { usage: response.data.usage },
3304
+ raw: response.data,
3305
+ status: response.status,
3306
+ ...response.generationId !== undefined && { generationId: response.generationId },
3307
+ ...response.requestId !== undefined && { requestId: response.requestId },
3308
+ ...response.costUsd !== undefined && { costUsd: response.costUsd },
3309
+ headers: response.headers
3310
+ };
3311
+ }
3312
+ async function openRouterAudioSpeech(input) {
3313
+ assertOpenRouterDirectAuth(input);
3314
+ const model = assertNonEmptyOpenRouterField("openRouterAudioSpeech", "model", input.model);
3315
+ assertNonEmptyOpenRouterField("openRouterAudioSpeech", "input", input.input);
3316
+ const voice = assertNonEmptyOpenRouterField("openRouterAudioSpeech", "voice", input.voice);
3317
+ if (input.speed !== undefined && (!Number.isFinite(input.speed) || input.speed <= 0)) {
3318
+ throw new RangeError("openRouterAudioSpeech: speed must be a positive finite number");
3319
+ }
3320
+ assertNoExtraBodyClash("openRouterAudioSpeech", input.extraBody, TTS_OWNED_KEYS);
3321
+ const provider = input.provider !== undefined ? serializeOpenRouterProviderRouting(input.provider) : undefined;
3322
+ const body = {
3323
+ ...input.extraBody ?? {},
3324
+ model,
3325
+ input: input.input,
3326
+ voice,
3327
+ ...input.responseFormat !== undefined && { response_format: input.responseFormat },
3328
+ ...input.speed !== undefined && { speed: input.speed },
3329
+ ...provider !== undefined && { provider }
3330
+ };
3331
+ const response = await openRouterRequestStream({
3332
+ ...pickOpenRouterTransport(input),
3333
+ path: "/audio/speech",
3334
+ method: "POST",
3335
+ body
3336
+ });
3337
+ return {
3338
+ audio: response.body,
3339
+ contentType: response.contentType,
3340
+ status: response.status,
3341
+ ...response.generationId !== undefined && { generationId: response.generationId },
3342
+ ...response.requestId !== undefined && { requestId: response.requestId },
3343
+ headers: response.headers
3344
+ };
3345
+ }
2612
3346
  // src/agent-runtime/providers/openrouter-catalog-cache.ts
2613
3347
  var DEFAULT_TIMEOUT_MS = 1e4;
2614
3348
  var DEFAULT_FRESH_MS = 15 * 60000;
@@ -2674,6 +3408,7 @@ function validateCacheOptions(options) {
2674
3408
  assertPositiveSafeInteger("maxResponseBytes", options.maxResponseBytes, RangeError);
2675
3409
  }
2676
3410
  assertValidStaticOpenRouterApiKey(options.apiKey);
3411
+ validateOpenRouterBaseUrl(options.baseUrl);
2677
3412
  assertValidOpenRouterEndpointsFor(options.endpointsFor);
2678
3413
  return {
2679
3414
  timeoutMs,
@@ -2845,36 +3580,381 @@ function createOpenRouterCatalogCache(options = {}) {
2845
3580
  }
2846
3581
  };
2847
3582
  }
3583
+ // src/agent-runtime/providers/openrouter-media.ts
3584
+ import { z as z9 } from "zod";
3585
+ var NonNegativeInt2 = z9.int().nonnegative();
3586
+ var NonNegativeNum2 = z9.number().nonnegative();
3587
+ var IMAGE_OWNED_KEYS = [
3588
+ "model",
3589
+ "prompt",
3590
+ "n",
3591
+ "aspect_ratio",
3592
+ "resolution",
3593
+ "response_format",
3594
+ "input_references",
3595
+ "provider"
3596
+ ];
3597
+ var VIDEO_OWNED_KEYS = [
3598
+ "model",
3599
+ "prompt",
3600
+ "duration",
3601
+ "aspect_ratio",
3602
+ "resolution",
3603
+ "generate_audio",
3604
+ "frame_images",
3605
+ "input_references",
3606
+ "callback_url",
3607
+ "provider"
3608
+ ];
3609
+ var ImageItemSchema = z9.object({
3610
+ b64_json: z9.string().optional(),
3611
+ url: z9.string().optional(),
3612
+ media_type: z9.string().optional()
3613
+ }).loose();
3614
+ var MediaUsageSchema = z9.object({
3615
+ prompt_tokens: NonNegativeInt2.optional(),
3616
+ completion_tokens: NonNegativeInt2.optional(),
3617
+ input_tokens: NonNegativeInt2.optional(),
3618
+ output_tokens: NonNegativeInt2.optional(),
3619
+ total_tokens: NonNegativeInt2.optional(),
3620
+ cost: NonNegativeNum2.optional(),
3621
+ is_byok: z9.boolean().optional()
3622
+ }).loose();
3623
+ var OpenRouterImageGenerationResponseSchema = z9.object({
3624
+ created: z9.int().nonnegative().optional(),
3625
+ data: z9.array(ImageItemSchema),
3626
+ expires_at: z9.int().nonnegative().optional(),
3627
+ usage: MediaUsageSchema.optional()
3628
+ }).loose();
3629
+ async function openRouterGenerateImages(input) {
3630
+ assertOpenRouterDirectAuth(input);
3631
+ const model = assertNonEmptyOpenRouterField("openRouterGenerateImages", "model", input.model);
3632
+ assertNonEmptyOpenRouterField("openRouterGenerateImages", "prompt", input.prompt);
3633
+ if (input.n !== undefined)
3634
+ assertPositiveSafeInteger("n", input.n);
3635
+ assertNoExtraBodyClash("openRouterGenerateImages", input.extraBody, IMAGE_OWNED_KEYS);
3636
+ const provider = input.provider !== undefined ? serializeOpenRouterProviderRouting(input.provider) : undefined;
3637
+ const body = {
3638
+ ...input.extraBody ?? {},
3639
+ model,
3640
+ prompt: input.prompt,
3641
+ ...input.n !== undefined && { n: input.n },
3642
+ ...input.aspectRatio !== undefined && { aspect_ratio: input.aspectRatio },
3643
+ ...input.resolution !== undefined && { resolution: input.resolution },
3644
+ ...input.responseFormat !== undefined && { response_format: input.responseFormat },
3645
+ ...input.inputReferences !== undefined && {
3646
+ input_references: [...input.inputReferences]
3647
+ },
3648
+ ...provider !== undefined && { provider }
3649
+ };
3650
+ const response = await openRouterRequestJson({
3651
+ ...pickOpenRouterTransport(input),
3652
+ path: "/images",
3653
+ method: "POST",
3654
+ body,
3655
+ schema: OpenRouterImageGenerationResponseSchema
3656
+ });
3657
+ return {
3658
+ ...response.data.created !== undefined && { created: response.data.created },
3659
+ images: response.data.data,
3660
+ ...response.data.expires_at !== undefined && { expiresAt: response.data.expires_at },
3661
+ ...response.data.usage !== undefined && { usage: response.data.usage },
3662
+ raw: response.data,
3663
+ status: response.status,
3664
+ ...response.generationId !== undefined && { generationId: response.generationId },
3665
+ ...response.requestId !== undefined && { requestId: response.requestId },
3666
+ ...response.costUsd !== undefined && { costUsd: response.costUsd },
3667
+ headers: response.headers
3668
+ };
3669
+ }
3670
+ var VideoSubmitResponseSchema = z9.object({
3671
+ id: z9.string().min(1),
3672
+ status: z9.string().min(1),
3673
+ polling_url: z9.string().min(1).optional()
3674
+ }).loose();
3675
+ var VideoStatusResponseSchema = z9.object({
3676
+ id: z9.string().min(1),
3677
+ status: z9.string().min(1),
3678
+ generation_id: z9.string().min(1).optional(),
3679
+ urls: z9.array(z9.string()).optional(),
3680
+ unsigned_urls: z9.array(z9.string()).optional(),
3681
+ expires_at: z9.int().nonnegative().optional(),
3682
+ usage: MediaUsageSchema.optional(),
3683
+ error: z9.unknown().optional()
3684
+ }).loose();
3685
+ async function openRouterSubmitVideo(input) {
3686
+ assertOpenRouterDirectAuth(input);
3687
+ const model = assertNonEmptyOpenRouterField("openRouterSubmitVideo", "model", input.model);
3688
+ assertNonEmptyOpenRouterField("openRouterSubmitVideo", "prompt", input.prompt);
3689
+ if (input.duration !== undefined && (!Number.isFinite(input.duration) || input.duration <= 0)) {
3690
+ throw new RangeError("openRouterSubmitVideo: duration must be a positive finite number");
3691
+ }
3692
+ const callbackUrl = input.callbackUrl !== undefined ? assertOpenRouterHttpUrl("callbackUrl", input.callbackUrl) : undefined;
3693
+ assertNoExtraBodyClash("openRouterSubmitVideo", input.extraBody, VIDEO_OWNED_KEYS);
3694
+ const provider = input.provider !== undefined ? serializeOpenRouterProviderRouting(input.provider) : undefined;
3695
+ const body = {
3696
+ ...input.extraBody ?? {},
3697
+ model,
3698
+ prompt: input.prompt,
3699
+ ...input.duration !== undefined && { duration: input.duration },
3700
+ ...input.aspectRatio !== undefined && { aspect_ratio: input.aspectRatio },
3701
+ ...input.resolution !== undefined && { resolution: input.resolution },
3702
+ ...input.generateAudio !== undefined && { generate_audio: input.generateAudio },
3703
+ ...input.frameImages !== undefined && { frame_images: [...input.frameImages] },
3704
+ ...input.inputReferences !== undefined && {
3705
+ input_references: [...input.inputReferences]
3706
+ },
3707
+ ...callbackUrl !== undefined && { callback_url: callbackUrl },
3708
+ ...provider !== undefined && { provider }
3709
+ };
3710
+ const response = await openRouterRequestJson({
3711
+ ...pickOpenRouterTransport(input),
3712
+ path: "/videos",
3713
+ method: "POST",
3714
+ body,
3715
+ schema: VideoSubmitResponseSchema
3716
+ });
3717
+ return {
3718
+ id: response.data.id,
3719
+ jobStatus: response.data.status,
3720
+ ...response.data.polling_url !== undefined && { pollingUrl: response.data.polling_url },
3721
+ raw: response.data,
3722
+ status: response.status,
3723
+ ...response.generationId !== undefined && { generationId: response.generationId },
3724
+ ...response.requestId !== undefined && { requestId: response.requestId },
3725
+ ...response.costUsd !== undefined && { costUsd: response.costUsd },
3726
+ headers: response.headers
3727
+ };
3728
+ }
3729
+ async function openRouterGetVideo(input) {
3730
+ assertOpenRouterDirectAuth(input);
3731
+ const jobId = assertOpenRouterPathSegment("jobId", input.jobId);
3732
+ const response = await openRouterRequestJson({
3733
+ ...pickOpenRouterTransport(input),
3734
+ path: `/videos/${encodeURIComponent(jobId)}`,
3735
+ method: "GET",
3736
+ schema: VideoStatusResponseSchema
3737
+ });
3738
+ return {
3739
+ id: response.data.id,
3740
+ jobStatus: response.data.status,
3741
+ ...response.data.urls !== undefined && { urls: response.data.urls },
3742
+ ...response.data.unsigned_urls !== undefined && {
3743
+ unsignedUrls: response.data.unsigned_urls
3744
+ },
3745
+ ...response.data.expires_at !== undefined && { expiresAt: response.data.expires_at },
3746
+ ...response.data.usage !== undefined && { usage: response.data.usage },
3747
+ ...response.data.error !== undefined && { error: response.data.error },
3748
+ raw: response.data,
3749
+ status: response.status,
3750
+ ...response.generationId !== undefined && { generationId: response.generationId },
3751
+ ...response.requestId !== undefined && { requestId: response.requestId },
3752
+ ...response.costUsd !== undefined && { costUsd: response.costUsd },
3753
+ headers: response.headers
3754
+ };
3755
+ }
3756
+ async function openRouterDownloadVideo(input) {
3757
+ assertOpenRouterDirectAuth(input);
3758
+ const jobId = assertOpenRouterPathSegment("jobId", input.jobId);
3759
+ return openRouterRequestStream({
3760
+ ...pickOpenRouterTransport(input),
3761
+ path: `/videos/${encodeURIComponent(jobId)}/content`,
3762
+ method: "GET"
3763
+ });
3764
+ }
3765
+ // src/agent-runtime/providers/openrouter-retrieval.ts
3766
+ import { z as z10 } from "zod";
3767
+ var NonNegativeInt3 = z10.int().nonnegative();
3768
+ var NonNegativeNum3 = z10.number().nonnegative();
3769
+ var EMBEDDINGS_OWNED_KEYS = [
3770
+ "model",
3771
+ "input",
3772
+ "encoding_format",
3773
+ "dimensions",
3774
+ "user",
3775
+ "provider"
3776
+ ];
3777
+ var RERANK_OWNED_KEYS = ["model", "query", "documents", "top_n", "provider"];
3778
+ var RetrievalUsageSchema = z10.object({
3779
+ prompt_tokens: NonNegativeInt3.optional(),
3780
+ completion_tokens: NonNegativeInt3.optional(),
3781
+ input_tokens: NonNegativeInt3.optional(),
3782
+ output_tokens: NonNegativeInt3.optional(),
3783
+ total_tokens: NonNegativeInt3.optional(),
3784
+ cost: NonNegativeNum3.optional(),
3785
+ is_byok: z10.boolean().optional()
3786
+ }).loose();
3787
+ var EmbeddingDatumSchema = z10.object({
3788
+ index: NonNegativeInt3,
3789
+ embedding: z10.union([z10.array(z10.number()), z10.string()])
3790
+ }).loose();
3791
+ var EmbeddingsResponseSchema = z10.object({
3792
+ model: z10.string().min(1).optional(),
3793
+ data: z10.array(EmbeddingDatumSchema),
3794
+ usage: RetrievalUsageSchema.optional()
3795
+ }).loose();
3796
+ async function openRouterEmbeddings(input) {
3797
+ assertOpenRouterDirectAuth(input);
3798
+ const model = assertNonEmptyOpenRouterField("openRouterEmbeddings", "model", input.model);
3799
+ if (Array.isArray(input.input) && input.input.length === 0) {
3800
+ throw new TypeError("openRouterEmbeddings: input array must not be empty");
3801
+ }
3802
+ if (input.dimensions !== undefined)
3803
+ assertPositiveSafeInteger("dimensions", input.dimensions);
3804
+ assertNoExtraBodyClash("openRouterEmbeddings", input.extraBody, EMBEDDINGS_OWNED_KEYS);
3805
+ const provider = input.provider !== undefined ? serializeOpenRouterProviderRouting(input.provider) : undefined;
3806
+ const body = {
3807
+ ...input.extraBody ?? {},
3808
+ model,
3809
+ input: Array.isArray(input.input) ? [...input.input] : input.input,
3810
+ ...input.encodingFormat !== undefined && { encoding_format: input.encodingFormat },
3811
+ ...input.dimensions !== undefined && { dimensions: input.dimensions },
3812
+ ...input.user !== undefined && { user: input.user },
3813
+ ...provider !== undefined && { provider }
3814
+ };
3815
+ const response = await openRouterRequestJson({
3816
+ ...pickOpenRouterTransport(input),
3817
+ path: "/embeddings",
3818
+ method: "POST",
3819
+ body,
3820
+ schema: EmbeddingsResponseSchema
3821
+ });
3822
+ return {
3823
+ ...response.data.model !== undefined && { model: response.data.model },
3824
+ data: response.data.data,
3825
+ ...response.data.usage !== undefined && { usage: response.data.usage },
3826
+ raw: response.data,
3827
+ status: response.status,
3828
+ ...response.generationId !== undefined && { generationId: response.generationId },
3829
+ ...response.requestId !== undefined && { requestId: response.requestId },
3830
+ ...response.costUsd !== undefined && { costUsd: response.costUsd },
3831
+ headers: response.headers
3832
+ };
3833
+ }
3834
+ var RerankResultItemSchema = z10.object({
3835
+ index: NonNegativeInt3,
3836
+ relevance_score: z10.number().finite(),
3837
+ document: z10.object({ text: z10.string() }).loose().optional()
3838
+ }).loose();
3839
+ var RerankResponseSchema = z10.object({
3840
+ results: z10.array(RerankResultItemSchema),
3841
+ meta: z10.record(z10.string(), z10.unknown()).optional(),
3842
+ usage: RetrievalUsageSchema.optional()
3843
+ }).loose();
3844
+ async function openRouterRerank(input) {
3845
+ assertOpenRouterDirectAuth(input);
3846
+ const model = assertNonEmptyOpenRouterField("openRouterRerank", "model", input.model);
3847
+ assertNonEmptyOpenRouterField("openRouterRerank", "query", input.query);
3848
+ if (input.documents.length === 0) {
3849
+ throw new TypeError("openRouterRerank: documents must be a non-empty array");
3850
+ }
3851
+ if (input.topN !== undefined)
3852
+ assertPositiveSafeInteger("topN", input.topN);
3853
+ assertNoExtraBodyClash("openRouterRerank", input.extraBody, RERANK_OWNED_KEYS);
3854
+ const provider = input.provider !== undefined ? serializeOpenRouterProviderRouting(input.provider) : undefined;
3855
+ const body = {
3856
+ ...input.extraBody ?? {},
3857
+ model,
3858
+ query: input.query,
3859
+ documents: [...input.documents],
3860
+ ...input.topN !== undefined && { top_n: input.topN },
3861
+ ...provider !== undefined && { provider }
3862
+ };
3863
+ const response = await openRouterRequestJson({
3864
+ ...pickOpenRouterTransport(input),
3865
+ path: "/rerank",
3866
+ method: "POST",
3867
+ body,
3868
+ schema: RerankResponseSchema
3869
+ });
3870
+ return {
3871
+ results: response.data.results.map((item) => ({
3872
+ index: item.index,
3873
+ relevanceScore: item.relevance_score,
3874
+ ...item.document !== undefined && { document: item.document }
3875
+ })),
3876
+ ...response.data.meta !== undefined && { meta: response.data.meta },
3877
+ ...response.data.usage !== undefined && { usage: response.data.usage },
3878
+ raw: response.data,
3879
+ status: response.status,
3880
+ ...response.generationId !== undefined && { generationId: response.generationId },
3881
+ ...response.requestId !== undefined && { requestId: response.requestId },
3882
+ ...response.costUsd !== undefined && { costUsd: response.costUsd },
3883
+ headers: response.headers
3884
+ };
3885
+ }
2848
3886
  // src/agent-runtime/providers/openrouter-spend.ts
2849
- import { z as z8 } from "zod";
3887
+ import { z as z11 } from "zod";
3888
+ var Count = z11.int().nonnegative();
3889
+ var NonNegativeFinite = z11.number().nonnegative();
3890
+ function readOptional(schema, value) {
3891
+ if (value === undefined || value === null)
3892
+ return;
3893
+ const parsed = schema.safeParse(value);
3894
+ return parsed.success ? parsed.data : undefined;
3895
+ }
3896
+ var openRouterSpendFacts = {
3897
+ headers(headers) {
3898
+ const generationId = nonEmptyTrimmed(headers.get("x-generation-id"));
3899
+ return generationId !== undefined ? { providerRequestId: generationId } : {};
3900
+ },
3901
+ event(value) {
3902
+ const base = openAiCompatibleUsage2.event?.(value) ?? {};
3903
+ const { providerRequestId: rawId, ...restBase } = base;
3904
+ if (!isRecord(value))
3905
+ return restBase;
3906
+ const trimmedRawId = nonEmptyTrimmed(rawId);
3907
+ const generationId = nonEmptyTrimmed(typeof value.generation_id === "string" ? value.generation_id : undefined) ?? (trimmedRawId?.startsWith("gen-") ? trimmedRawId : undefined);
3908
+ const usage = isRecord(value.usage) ? value.usage : undefined;
3909
+ const inputDetails = usage && isRecord(usage.input_tokens_details) ? usage.input_tokens_details : undefined;
3910
+ const outputDetails = usage && isRecord(usage.output_tokens_details) ? usage.output_tokens_details : undefined;
3911
+ const inputTokens = restBase.inputTokens ?? readOptional(Count, usage?.input_tokens);
3912
+ const outputTokens = restBase.outputTokens ?? readOptional(Count, usage?.output_tokens);
3913
+ const cacheReadTokens = restBase.cacheReadTokens ?? readOptional(Count, inputDetails?.cached_tokens);
3914
+ const cacheWriteTokens = restBase.cacheWriteTokens ?? readOptional(Count, inputDetails?.cache_write_tokens);
3915
+ const reasoningTokens = restBase.reasoningTokens ?? readOptional(Count, outputDetails?.reasoning_tokens);
3916
+ const seconds = readOptional(NonNegativeFinite, usage?.seconds);
3917
+ return {
3918
+ ...restBase,
3919
+ ...generationId !== undefined && { providerRequestId: generationId },
3920
+ ...inputTokens !== undefined && { inputTokens },
3921
+ ...outputTokens !== undefined && { outputTokens },
3922
+ ...cacheReadTokens !== undefined && { cacheReadTokens },
3923
+ ...cacheWriteTokens !== undefined && { cacheWriteTokens },
3924
+ ...reasoningTokens !== undefined && { reasoningTokens },
3925
+ ...seconds !== undefined && { workUnit: "seconds", workAmount: seconds }
3926
+ };
3927
+ }
3928
+ };
2850
3929
  function openRouterSpendProvider(options) {
3930
+ const origin = validateOpenRouterBaseUrl(options.baseUrl).origin;
2851
3931
  return {
2852
3932
  name: "openrouter",
2853
- origin: "https://openrouter.ai",
3933
+ origin,
2854
3934
  headers: async () => ({ authorization: `Bearer ${await options.apiKey()}` }),
2855
- facts: openAiCompatibleUsage2
3935
+ facts: openRouterSpendFacts
2856
3936
  };
2857
3937
  }
2858
- var GenerationSchema = z8.object({
2859
- data: z8.object({
2860
- total_cost: z8.number().nonnegative().nullish(),
2861
- provider_name: z8.string().min(1).nullish(),
2862
- model: z8.string().min(1).nullish(),
2863
- native_tokens_prompt: z8.int().nonnegative().nullish(),
2864
- native_tokens_completion: z8.int().nonnegative().nullish(),
2865
- native_tokens_reasoning: z8.int().nonnegative().nullish()
3938
+ var GenerationSchema = z11.object({
3939
+ data: z11.object({
3940
+ total_cost: z11.number().nonnegative().nullish(),
3941
+ provider_name: z11.string().min(1).nullish(),
3942
+ model: z11.string().min(1).nullish(),
3943
+ native_tokens_prompt: z11.int().nonnegative().nullish(),
3944
+ native_tokens_completion: z11.int().nonnegative().nullish(),
3945
+ native_tokens_reasoning: z11.int().nonnegative().nullish()
2866
3946
  }).loose()
2867
3947
  });
2868
3948
  function createOpenRouterSpendReconciler(options) {
2869
3949
  const fetcher = options.fetcher ?? fetch;
2870
3950
  const timeoutMs = options.timeoutMs ?? 1e4;
2871
3951
  assertTimerMs("timeoutMs", timeoutMs);
3952
+ validateOpenRouterBaseUrl(options.baseUrl);
2872
3953
  return async (record) => {
2873
3954
  const id = record.receipt?.facts.providerRequestId;
2874
3955
  if (id === undefined)
2875
3956
  return { costStatus: "unknown", failureCode: "no-generation-id" };
2876
- const url = new URL("https://openrouter.ai/api/v1/generation");
2877
- url.searchParams.set("id", id);
3957
+ const url = resolveOpenRouterUrl(options.baseUrl, "/generation", { id });
2878
3958
  let body;
2879
3959
  try {
2880
3960
  const apiKey = typeof options.apiKey === "string" ? options.apiKey : await options.apiKey(record);
@@ -2902,13 +3982,124 @@ function createOpenRouterSpendReconciler(options) {
2902
3982
  };
2903
3983
  };
2904
3984
  }
3985
+ // src/agent-runtime/providers/openrouter-systemone.ts
3986
+ import { z as z12 } from "zod";
3987
+ var SYSTEMONE_OWNED_KEYS = [
3988
+ "model",
3989
+ "state",
3990
+ "questions",
3991
+ "provider",
3992
+ "response_format"
3993
+ ];
3994
+ var ProbabilitySchema = z12.number().min(0).max(1);
3995
+ var NonNegativeInt4 = z12.int().nonnegative();
3996
+ var NonNegativeNum4 = z12.number().nonnegative();
3997
+ var SystemOneNoulQuestionSchema = z12.strictObject({
3998
+ type: z12.literal("noul"),
3999
+ instructions: z12.string().min(1),
4000
+ criteria: z12.object({
4001
+ true: z12.string().nullable().optional(),
4002
+ false: z12.string().nullable().optional()
4003
+ }).loose().optional()
4004
+ });
4005
+ var SystemOneChoiceQuestionSchema = z12.strictObject({
4006
+ type: z12.literal("choice"),
4007
+ instructions: z12.string().min(1),
4008
+ criteria: z12.record(z12.string().min(1), z12.string().nullable()).refine((value) => Object.keys(value).length >= 2, {
4009
+ message: "System One choice question requires at least 2 criteria entries"
4010
+ })
4011
+ });
4012
+ var SystemOneScoreQuestionSchema = z12.strictObject({
4013
+ type: z12.literal("score"),
4014
+ instructions: z12.string().min(1),
4015
+ criteria: z12.array(z12.string().min(1)).min(2)
4016
+ });
4017
+ var SystemOneQuestionSchema = z12.discriminatedUnion("type", [
4018
+ SystemOneNoulQuestionSchema,
4019
+ SystemOneChoiceQuestionSchema,
4020
+ SystemOneScoreQuestionSchema
4021
+ ]);
4022
+ var SystemOneNoulAnswerSchema = z12.object({
4023
+ type: z12.literal("noul"),
4024
+ noul: ProbabilitySchema
4025
+ }).loose();
4026
+ var SystemOneChoiceAnswerSchema = z12.object({
4027
+ type: z12.literal("choice"),
4028
+ choice: z12.string(),
4029
+ confidence: ProbabilitySchema.optional(),
4030
+ probabilities: z12.record(z12.string(), ProbabilitySchema).optional()
4031
+ }).loose();
4032
+ var SystemOneScoreAnswerSchema = z12.object({
4033
+ type: z12.literal("score"),
4034
+ score: z12.number().finite(),
4035
+ confidence: ProbabilitySchema.optional(),
4036
+ legend: z12.union([z12.array(z12.string()), z12.record(z12.string(), z12.string())]).optional(),
4037
+ probabilities: z12.record(z12.string(), ProbabilitySchema).optional()
4038
+ }).loose();
4039
+ var SystemOneAnswerSchema = z12.discriminatedUnion("type", [
4040
+ SystemOneNoulAnswerSchema,
4041
+ SystemOneChoiceAnswerSchema,
4042
+ SystemOneScoreAnswerSchema
4043
+ ]);
4044
+ var SystemOneUsageSchema = z12.object({
4045
+ input_tokens: NonNegativeInt4.optional(),
4046
+ output_tokens: NonNegativeInt4.optional(),
4047
+ prompt_tokens: NonNegativeInt4.optional(),
4048
+ completion_tokens: NonNegativeInt4.optional(),
4049
+ total_tokens: NonNegativeInt4.optional(),
4050
+ cost: NonNegativeNum4.optional()
4051
+ }).loose();
4052
+ var OpenRouterSystemOneResponseSchema = z12.object({
4053
+ id: z12.string().min(1).optional(),
4054
+ model: z12.string().min(1).optional(),
4055
+ answers: z12.record(z12.string(), SystemOneAnswerSchema),
4056
+ usage: SystemOneUsageSchema.optional()
4057
+ }).loose();
4058
+ var SystemOneQuestionsMapSchema = z12.record(z12.string().min(1), SystemOneQuestionSchema).refine((value) => Object.keys(value).length > 0, {
4059
+ message: "openRouterSystemOne requires at least one question"
4060
+ });
4061
+ async function openRouterSystemOne(input) {
4062
+ assertOpenRouterDirectAuth(input);
4063
+ const model = assertNonEmptyOpenRouterField("openRouterSystemOne", "model", input.model);
4064
+ const questions = SystemOneQuestionsMapSchema.parse(input.questions);
4065
+ assertNoExtraBodyClash("openRouterSystemOne", input.extraBody, SYSTEMONE_OWNED_KEYS);
4066
+ const provider = input.provider !== undefined ? serializeOpenRouterProviderRouting(input.provider) : undefined;
4067
+ const body = {
4068
+ ...input.extraBody ?? {},
4069
+ model,
4070
+ state: input.state,
4071
+ questions,
4072
+ ...provider !== undefined && { provider }
4073
+ };
4074
+ const response = await openRouterRequestJson({
4075
+ ...pickOpenRouterTransport(input),
4076
+ path: "/systemone",
4077
+ method: "POST",
4078
+ body,
4079
+ schema: OpenRouterSystemOneResponseSchema
4080
+ });
4081
+ return {
4082
+ ...response.data.model !== undefined && { model: response.data.model },
4083
+ answers: response.data.answers,
4084
+ ...response.data.usage !== undefined && { usage: response.data.usage },
4085
+ raw: response.data,
4086
+ status: response.status,
4087
+ ...response.generationId !== undefined && { generationId: response.generationId },
4088
+ ...response.requestId !== undefined && { requestId: response.requestId },
4089
+ ...response.costUsd !== undefined && { costUsd: response.costUsd },
4090
+ headers: response.headers
4091
+ };
4092
+ }
2905
4093
  export {
4094
+ OPENROUTER_API_BASE_URL,
2906
4095
  OpenRouterAdmissionPolicySchema,
2907
4096
  OpenRouterAdmissionReasonSchema,
4097
+ OpenRouterAudioTranscriptionResponseSchema,
2908
4098
  OpenRouterCatalogSnapshotSchema,
2909
4099
  OpenRouterEndpointSchema,
2910
4100
  OpenRouterEndpointSummarySchema,
2911
4101
  OpenRouterHttpError,
4102
+ OpenRouterImageGenerationResponseSchema,
2912
4103
  OpenRouterMaxPriceSchema,
2913
4104
  OpenRouterModelAdmissionSchema,
2914
4105
  OpenRouterModelAliasTargetSchema,
@@ -2920,6 +4111,7 @@ export {
2920
4111
  OpenRouterRequestPolicySchema,
2921
4112
  OpenRouterRoutePinSchema,
2922
4113
  OpenRouterSnapshotModelSchema,
4114
+ OpenRouterSystemOneResponseSchema,
2923
4115
  createMemoryOpenRouterRouteStore,
2924
4116
  createOpenRouterCatalogCache,
2925
4117
  createOpenRouterRouteResolver,
@@ -2930,9 +4122,20 @@ export {
2930
4122
  listOpenRouterModels,
2931
4123
  loadOpenRouterCatalogSnapshot,
2932
4124
  normalizeOpenRouterUsage,
4125
+ openRouterAudioSpeech,
4126
+ openRouterAudioTranscription,
4127
+ openRouterDownloadVideo,
4128
+ openRouterEmbeddings,
4129
+ openRouterGenerateImages,
4130
+ openRouterGetVideo,
2933
4131
  openRouterModelCatalog,
2934
4132
  openRouterProvider,
4133
+ openRouterRequestJson,
4134
+ openRouterRequestStream,
4135
+ openRouterRerank,
2935
4136
  openRouterSpendProvider,
4137
+ openRouterSubmitVideo,
4138
+ openRouterSystemOne,
2936
4139
  resolveOpenRouterModelCeiling,
2937
4140
  summarizeOpenRouterEndpoints
2938
4141
  };