openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
52 lines • 58.9 kB
JavaScript
import{r as normalizeProviderId}from"./provider-id-A-8WTtLA.mjs";import{_ as resolveDefaultAgentId,f as resolveAgentWorkspaceDir}from"./agent-scope-config-CG9CFpGX.mjs";import{t as canAccess}from"./path-existence-BR9MXlgL.mjs";import{t as createSubsystemLogger}from"./subsystem-DLCDFvCH.mjs";import{s as normalizeModelFamily}from"./model-catalog-types-C-uYZJxd.mjs";import{t as ModelInferenceCapabilitiesSchema}from"./model-inference-capabilities-QSRBvvpe.mjs";import{a as isCurrentPluginMetadataSnapshotRuntimeGeneration,i as getCurrentPluginMetadataSnapshot}from"./current-plugin-metadata-snapshot-CYi8VAby.mjs";import{t as normalizeOptionalSecretInput}from"./normalize-secret-input-CEFJUjQX.mjs";import{h as readRuntimeConfig}from"./runtime-snapshot-Bg5K4JNu.mjs";import{p as resolvePluginMetadataSnapshot}from"./plugin-metadata-snapshot-CDKhemiT.mjs";import"./agent-scope-Dw5XRSEh.mjs";import{n as modelTransportRoutesMatch}from"./model-compat-catalog-yXiNopuo.mjs";import{t as planEffectiveModelCatalogRows}from"./model-catalog-BG6rYCD1.mjs";import{n as projectConfigOntoRuntimeSourceSnapshot}from"./runtime-source-projection-DvPkX_nq.mjs";import{t as warnPluginSdkDeprecation}from"./sdk-deprecation-BDUCyBrU.mjs";import{i as normalizeResolvedPricing}from"./usage-cost-CjmYqezS.mjs";import"./src-BHImOHU3.mjs";import{p as resolveExplicitProviderNoAuth,s as applyLocalNoAuthHeaders}from"./model-auth-markers-Dc97K3d8.mjs";import{a as sanitizeModelHeaders}from"./model.inline-provider-CzhYYsMw.mjs";import{a as hasUsableCustomProviderApiKey}from"./model-auth-provider-config-KlOdxZHz.mjs";import{p as resolveManagedSecretRefRuntimeProviderAuth}from"./loader-runtime-load-CVvaB9FO.mjs";import{t as buildEffectiveManifestProviderConfig}from"./provider-catalog-BfCEo7Wb.mjs";import{o as normalizeProviderMapKeys,r as mergeProviderModels,s as validateProviderModels,t as buildSourceModelFields}from"./models-config.merge-UO5Fldbo.mjs";import{a as getAuthStorageOAuthProviderRegistry,i as resolveHeadersOrThrow,n as resolveConfigValueOrThrow,r as resolveConfigValueUncached}from"./auth-storage.core-CJFKhJwL.mjs";import{t as parseModelCatalogJson}from"./model-catalog-json-D7uWchaX.mjs";import{n as isGeneratedPluginModelCatalog}from"./plugin-model-catalog-repair-CzksjYl4.mjs";import{t as materializeConfiguredProviderCatalogModels}from"./models-config.providers.catalog-AHh-6iYl.mjs";import{t as loadPersistedPluginModelCatalogs}from"./plugin-model-catalog-execution-BVIEjWCC.mjs";import{n as inspectLegacyPluginModelCatalogs,r as loadPersistedPluginModelCatalogsReadOnly,t as filterGeneratedPluginModelCatalogProviders}from"./plugin-model-catalog-CFTAUpvN.mjs";import{n as initializeModelRegistryRuntime,r as resetModelRegistryRuntime,t as getModelRegistryRuntime}from"./model-registry-runtime-VNuLOQ9O.mjs";import{existsSync,readFileSync}from"node:fs";import{dirname}from"node:path";import{Type}from"typebox";import{Errors,Pointer}from"typebox/schema";
//!src/agents/model-discovery-context.ts
function resolveModelWorkspaceDir(e,t,n){if(t!==void 0||!e)return t;return resolveAgentWorkspaceDir(e,n??resolveDefaultAgentId(e))}function resolveModelPluginMetadataSnapshot(e){if(e.pluginMetadataSnapshot)return e.pluginMetadataSnapshot;const t=process.env;try{if(!e.config){const n=getCurrentPluginMetadataSnapshot({allowWorkspaceScopedSnapshot:true,allowSynchronousPolicyRead:false,env:t,...e.workspaceDir?{workspaceDir:e.workspaceDir}:{}});if(n&&isCurrentPluginMetadataSnapshotRuntimeGeneration(n))return n}const n=e.config??readRuntimeConfig();return getCurrentPluginMetadataSnapshot({allowWorkspaceScopedSnapshot:true,env:t,config:n,...e.workspaceDir?{workspaceDir:e.workspaceDir}:{}})??resolvePluginMetadataSnapshot({config:n,env:t,...e.workspaceDir?{workspaceDir:e.workspaceDir}:{},...e.allowWorkspaceScopedCurrent!==void 0?{allowWorkspaceScopedCurrent:e.allowWorkspaceScopedCurrent}:{}})}catch{return}}
//!src/agents/sessions/model-registry-request-auth.ts
function scopeModelProviderRequestConfig(e,t){if(e?.baseUrls&&!e.baseUrls.some(e=>modelTransportRoutesMatch({baseUrl:e},{baseUrl:t.baseUrl})))return;return e}async function resolveModelRegistryRequestAuth(e){const{model:t,providerConfig:n,authStorage:r}=e;try{if(n?.auth===`native-command`)return{ok:false,error:`Native command auth requires the Codex runtime.`};const i=resolveExplicitProviderNoAuth({provider:t.provider,providerConfig:{auth:n?.auth},modelApi:t.api});const a=n?.auth===`aws-sdk`;const o=(i?i.apiKey:a?void 0:await r.getApiKey(t.provider,{includeFallback:false,baseUrl:t.baseUrl}))??(!a&&n?.apiKey?await resolveConfigValueOrThrow(n.apiKey,`API key for provider "${t.provider}"`):void 0);const resolveHeaders=(e,t)=>resolveHeadersOrThrow(i&&e?Object.fromEntries(Object.entries(e).filter(([e])=>e.toLowerCase()!==`authorization`)):e,t);const s=await resolveHeaders(n?.headers,`provider "${t.provider}"`);const c=await resolveHeaders(e.modelHeaders,`model "${t.provider}/${t.id}"`);let l=t.headers||s||c?{...t.headers,...s,...c}:void 0;if(i)l=applyLocalNoAuthHeaders(t.api,i.apiKey,l);else if(n?.authHeader){if(!o)return{ok:false,error:`No API key found for "${t.provider}"`};l={...l,Authorization:`Bearer ${o}`}}return{ok:true,apiKey:o,headers:l&&Object.keys(l).length>0?l:void 0}}catch(e){return{ok:false,error:e instanceof Error?e.message:String(e)}}}async function resolveModelRegistryProviderApiKey(e){if(e.readProviderConfig()?.auth===`native-command`)return;const t=await e.authStorage.getApiKey(e.provider,{includeFallback:false});if(t!==void 0)return t;const n=e.readProviderConfig()?.apiKey;return n?resolveConfigValueUncached(n):void 0}function hasModelRegistryConfiguredAuth(e){const{model:t,providerConfig:n,authStorage:r}=e;if(n?.auth===`native-command`)return false;if(n?.auth===`none`)return t.api===`openai-completions`;return r.hasAuth(t.provider)||n?.auth===`aws-sdk`||n?.apiKey!==void 0}
//!src/agents/sessions/model-registry-sources.ts
function captureProviderSource(...[e,t]){return{...t===`authored`?e:{api:e.api,baseUrl:e.baseUrl,compat:e.compat},models:e.models?.map(n=>{const{headers:r,...i}=n;const a=t===`composed`?n.maxTokensSource:t===`static`?`discovered`:`configured`;return Object.assign(t===`authored`?n:i,{api:n.api??e.api,baseUrl:n.baseUrl??e.baseUrl,maxTokensSource:a,compat:t===`composed`?n.compat:mergeCompat(e.compat,n.compat)})})}}function cloneMapValues(e){return new Map([...e].map(([e,t])=>[e,{...t}]))}function storeModelHeaders(e,t,n,r){const i=JSON.stringify([t,n]);if(!r||Object.keys(r).length===0){e.delete(i);return}e.set(i,r)}function mergeCompat(e,t){if(!t)return e;const n={...e,...t};for(const r of[`openRouterRouting`,`vercelGatewayRouting`])if(e?.[r]||t[r])n[r]={...e?.[r],...t[r]};return n}async function readModelRegistryPluginCatalogs(e,t){if(t.config?.models?.mode===`replace`||t.modelsJsonContents===null||t.modelsJsonContents===void 0&&!await canAccess(e))return{catalogs:[]};try{return{catalogs:await loadPersistedPluginModelCatalogs(dirname(e))}}catch(e){return{catalogs:[],error:`Failed to load generated plugin model catalogs: ${e instanceof Error?e.message:String(e)}`}}}function emptyCustomModelsResult(e){return{providers:{},error:e}}function mergeProviderSources(...e){const t={};for(const n of e)for(const[e,r]of Object.entries(n)){const n=t[e];t[e]=n?mergeProviderModels(n,r,{providerId:e,modelIdMatching:`exact`}):r}return t}function projectProviderRequestConfig(e){if(!e.apiKey&&!e.auth&&!e.headers&&!e.authHeader)return;return{baseUrls:e.baseUrl?[e.baseUrl,...(e.models??[]).flatMap(e=>e.baseUrl??[])]:void 0,apiKey:e.apiKey,auth:e.auth,headers:e.headers,authHeader:e.authHeader}}function readGeneratedPluginModelCatalogProviders(e){const t=filterGeneratedPluginModelCatalogProviders(e);const n=e.pluginMetadataSnapshot?.manifestRegistry?.plugins.find(t=>t.id===e.catalogPluginId);if(!n?.modelCatalog?.providers)return t;return Object.fromEntries(Object.entries(t).map(([t,r])=>{if(!r.models?.length)return[t,r];const i=normalizeProviderId(t);const a=planEffectiveModelCatalogRows({registry:{plugins:[n]},config:e.config??{},providerFilter:i}).rows.filter(e=>e.provider===i);const o=new Map(a.map(e=>[e.id,e]));const s=new Map(buildEffectiveManifestProviderConfig(a)?.models.map(e=>[e.id,e]));const c=r.models.map(e=>{const t=o.get(e.id);const n=s.get(e.id);if(!t||!n)return e;const{api:r,baseUrl:i,headers:a,...c}=n;const{inference:l,...u}=e;const d=l?.chat===false?l:t.inference;return{...u,...c,...e.compat?.supportedReasoningEfforts!==void 0?{compat:{...c.compat??e.compat,supportedReasoningEfforts:e.compat.supportedReasoningEfforts}}:{},...t.cost?{}:{cost:e.cost},...d?{inference:d}:{}}});return[t,{...r,models:c}]}))}
//!src/agents/sessions/model-registry-runtime-model.ts
function createRegistryRuntimeModel(e,t,n,r,i){const a=normalizeModelFamily(n.family);const o=n.inference===void 0?void 0:ModelInferenceCapabilitiesSchema.safeParse(n.inference);return{id:n.id,name:i?n.name??n.id:n.name,api:r,provider:e,baseUrl:i?i.baseUrl:n.baseUrl??t.baseUrl,reasoning:i?n.reasoning??false:n.reasoning,thinkingLevelMap:n.thinkingLevelMap,input:i?i.input:n.input,cost:i?normalizeResolvedPricing(n.cost??{}):n.cost,contextWindow:n.contextWindow??Math.max(n.contextTokens??0,128e3),...n.contextWindow===void 0?{contextWindowSource:`synthetic`}:{},contextTokens:n.contextTokens,...n.parameterCount!==void 0?{parameterCount:n.parameterCount}:{},...a?{family:a}:{},...o?{inference:o.success?o.data:{chat:false}}:{},contextWindows:n.contextWindows,contextWindowDefault:n.contextWindowDefault,maxTokens:i?n.maxTokens??16384:n.maxTokens,...i&&n.maxTokens!==void 0?{maxTokensSource:n.maxTokensSource}:{},params:n.params,headers:void 0,compat:n.compat}}function parseRegistryRuntimeModels(e,t){const n=[];for(const[r,i]of Object.entries(e))for(const e of i.models??[]){const a=e.api??i.api;if(!a)continue;const o=e.baseUrl??i.baseUrl;if(!o)continue;const s=(e.input??[`text`]).filter(e=>e===`text`||e===`image`);if((e.input?.length??0)>0&&s.length===0)continue;storeModelHeaders(t,r,e.id,e.headers);n.push(createRegistryRuntimeModel(r,i,e,a,{baseUrl:o,input:s}))}return n}
//!src/agents/sessions/model-registry-schema-definition.ts
const PercentileCutoffsSchema=Type.Object({p50:Type.Optional(Type.Number()),p75:Type.Optional(Type.Number()),p90:Type.Optional(Type.Number()),p99:Type.Optional(Type.Number())});const OpenRouterRoutingSchema=Type.Object({allow_fallbacks:Type.Optional(Type.Boolean()),require_parameters:Type.Optional(Type.Boolean()),data_collection:Type.Optional(Type.Union([Type.Literal(`deny`),Type.Literal(`allow`)])),zdr:Type.Optional(Type.Boolean()),enforce_distillable_text:Type.Optional(Type.Boolean()),order:Type.Optional(Type.Array(Type.String())),only:Type.Optional(Type.Array(Type.String())),ignore:Type.Optional(Type.Array(Type.String())),quantizations:Type.Optional(Type.Array(Type.String())),sort:Type.Optional(Type.Union([Type.String(),Type.Object({by:Type.Optional(Type.String()),partition:Type.Optional(Type.Union([Type.String(),Type.Null()]))})])),max_price:Type.Optional(Type.Object({prompt:Type.Optional(Type.Union([Type.Number(),Type.String()])),completion:Type.Optional(Type.Union([Type.Number(),Type.String()])),image:Type.Optional(Type.Union([Type.Number(),Type.String()])),audio:Type.Optional(Type.Union([Type.Number(),Type.String()])),request:Type.Optional(Type.Union([Type.Number(),Type.String()]))})),preferred_min_throughput:Type.Optional(Type.Union([Type.Number(),PercentileCutoffsSchema])),preferred_max_latency:Type.Optional(Type.Union([Type.Number(),PercentileCutoffsSchema]))});const VercelGatewayRoutingSchema=Type.Object({only:Type.Optional(Type.Array(Type.String())),order:Type.Optional(Type.Array(Type.String()))});const ThinkingLevelMapValueSchema=Type.Union([Type.String(),Type.Null()]);const ThinkingLevelMapSchema=Type.Object({off:Type.Optional(ThinkingLevelMapValueSchema),minimal:Type.Optional(ThinkingLevelMapValueSchema),low:Type.Optional(ThinkingLevelMapValueSchema),medium:Type.Optional(ThinkingLevelMapValueSchema),high:Type.Optional(ThinkingLevelMapValueSchema),xhigh:Type.Optional(ThinkingLevelMapValueSchema),max:Type.Optional(ThinkingLevelMapValueSchema)});const OpenAICompletionsCompatSchema=Type.Object({supportsStore:Type.Optional(Type.Boolean()),supportsDeveloperRole:Type.Optional(Type.Boolean()),supportsReasoningEffort:Type.Optional(Type.Boolean()),supportsUsageInStreaming:Type.Optional(Type.Boolean()),maxTokensField:Type.Optional(Type.Union([Type.Literal(`max_completion_tokens`),Type.Literal(`max_tokens`)])),requiresToolResultName:Type.Optional(Type.Boolean()),requiresAssistantAfterToolResult:Type.Optional(Type.Boolean()),requiresThinkingAsText:Type.Optional(Type.Boolean()),requiresReasoningContentOnAssistantMessages:Type.Optional(Type.Boolean()),thinkingFormat:Type.Optional(Type.Union([Type.Literal(`openai`),Type.Literal(`openrouter`),Type.Literal(`together`),Type.Literal(`deepseek`),Type.Literal(`zai`),Type.Literal(`qwen`),Type.Literal(`qwen-chat-template`)])),cacheControlFormat:Type.Optional(Type.Literal(`anthropic`)),openRouterRouting:Type.Optional(OpenRouterRoutingSchema),vercelGatewayRouting:Type.Optional(VercelGatewayRoutingSchema),supportsStrictMode:Type.Optional(Type.Boolean()),supportsJsonSchemaResponseFormat:Type.Optional(Type.Boolean()),supportsLongCacheRetention:Type.Optional(Type.Boolean())});const OpenAIResponsesCompatSchema=Type.Object({supportsTemperature:Type.Optional(Type.Boolean()),supportsInstructions:Type.Optional(Type.Boolean()),cachesInstructions:Type.Optional(Type.Boolean()),sendSessionIdHeader:Type.Optional(Type.Boolean()),supportsLongCacheRetention:Type.Optional(Type.Boolean())});const AnthropicMessagesCompatSchema=Type.Object({supportsEagerToolInputStreaming:Type.Optional(Type.Boolean()),supportsLongCacheRetention:Type.Optional(Type.Boolean())});const ProviderCompatSchema=Type.Union([OpenAICompletionsCompatSchema,OpenAIResponsesCompatSchema,AnthropicMessagesCompatSchema]);const ProviderAuthModeSchema=Type.Union([Type.Literal(`api-key`),Type.Literal(`aws-sdk`),Type.Literal(`oauth`),Type.Literal(`token`),Type.Literal(`none`),Type.Literal(`native-command`)]);const ModelDefinitionSchema=Type.Object({id:Type.String({minLength:1}),name:Type.Optional(Type.String({minLength:1})),api:Type.Optional(Type.String({minLength:1})),baseUrl:Type.Optional(Type.String({minLength:1})),reasoning:Type.Optional(Type.Boolean()),thinkingLevelMap:Type.Optional(ThinkingLevelMapSchema),input:Type.Optional(Type.Array(Type.Union([Type.Literal(`text`),Type.Literal(`image`),Type.Literal(`audio`),Type.Literal(`video`)]))),cost:Type.Optional(Type.Object({input:Type.Number(),output:Type.Number(),cacheRead:Type.Number(),cacheWrite:Type.Number()})),contextWindow:Type.Optional(Type.Number()),contextTokens:Type.Optional(Type.Number()),parameterCount:Type.Optional(Type.Integer({minimum:1})),family:Type.Optional(Type.String()),maxTokens:Type.Optional(Type.Number()),params:Type.Optional(Type.Record(Type.String(),Type.Unknown())),headers:Type.Optional(Type.Record(Type.String(),Type.String())),compat:Type.Optional(ProviderCompatSchema)});const ProviderConfigSchema=Type.Object({name:Type.Optional(Type.String({minLength:1})),baseUrl:Type.Optional(Type.String({minLength:1})),apiKey:Type.Optional(Type.String({minLength:1})),auth:Type.Optional(ProviderAuthModeSchema),api:Type.Optional(Type.String({minLength:1})),headers:Type.Optional(Type.Record(Type.String(),Type.String())),compat:Type.Optional(ProviderCompatSchema),authHeader:Type.Optional(Type.Boolean()),models:Type.Optional(Type.Array(ModelDefinitionSchema))});const ModelRegistryConfigSchema=Type.Object({generatedBy:Type.Optional(Type.String()),providers:Type.Record(Type.String(),ProviderConfigSchema)});
//!src/agents/sessions/model-registry-validator.generated.js
/*!
TypeBox
The MIT License (MIT)
Copyright (c) 2017-2026 Haydn Paterson
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
function CodePointCount(e){let t=0,n=0,r=0;for(;n<e.length;){let i=e.charCodeAt(n++)>>10;t+=+((r<<8|i)!==13879),r=i}return t}var isModelsConfig=(()=>{let e=[/^.*$/u,/^.*$/u,/^.*$/u,/^.*$/u],check_0=t=>typeof t==`object`&&t!==null&&!Array.isArray(t)&&`providers`in t&&(t.generatedBy===void 0||!(`generatedBy`in t)||typeof t.generatedBy==`string`)&&typeof t.providers==`object`&&t.providers!==null&&!Array.isArray(t.providers)&&Object.entries(t.providers).every(([t,n],r)=>!e[0].test(t)||typeof n==`object`&&n!==null&&!Array.isArray(n)&&(n.name===void 0||!(`name`in n)||typeof n.name==`string`&&(n.name.length>=2||n.name.length>=1&&CodePointCount(n.name)>=1))&&(n.baseUrl===void 0||!(`baseUrl`in n)||typeof n.baseUrl==`string`&&(n.baseUrl.length>=2||n.baseUrl.length>=1&&CodePointCount(n.baseUrl)>=1))&&(n.apiKey===void 0||!(`apiKey`in n)||typeof n.apiKey==`string`&&(n.apiKey.length>=2||n.apiKey.length>=1&&CodePointCount(n.apiKey)>=1))&&(n.auth===void 0||!(`auth`in n)||typeof n.auth==`string`&&n.auth===`api-key`||typeof n.auth==`string`&&n.auth===`aws-sdk`||typeof n.auth==`string`&&n.auth===`oauth`||typeof n.auth==`string`&&n.auth===`token`||typeof n.auth==`string`&&n.auth===`none`||typeof n.auth==`string`&&n.auth===`native-command`)&&(n.api===void 0||!(`api`in n)||typeof n.api==`string`&&(n.api.length>=2||n.api.length>=1&&CodePointCount(n.api)>=1))&&(n.headers===void 0||!(`headers`in n)||typeof n.headers==`object`&&n.headers!==null&&!Array.isArray(n.headers)&&Object.entries(n.headers).every(([t,n],r)=>!e[1].test(t)||typeof n==`string`))&&(n.compat===void 0||!(`compat`in n)||typeof n.compat==`object`&&n.compat!==null&&!Array.isArray(n.compat)&&(n.compat.supportsStore===void 0||!(`supportsStore`in n.compat)||typeof n.compat.supportsStore==`boolean`)&&(n.compat.supportsDeveloperRole===void 0||!(`supportsDeveloperRole`in n.compat)||typeof n.compat.supportsDeveloperRole==`boolean`)&&(n.compat.supportsReasoningEffort===void 0||!(`supportsReasoningEffort`in n.compat)||typeof n.compat.supportsReasoningEffort==`boolean`)&&(n.compat.supportsUsageInStreaming===void 0||!(`supportsUsageInStreaming`in n.compat)||typeof n.compat.supportsUsageInStreaming==`boolean`)&&(n.compat.maxTokensField===void 0||!(`maxTokensField`in n.compat)||typeof n.compat.maxTokensField==`string`&&n.compat.maxTokensField===`max_completion_tokens`||typeof n.compat.maxTokensField==`string`&&n.compat.maxTokensField===`max_tokens`)&&(n.compat.requiresToolResultName===void 0||!(`requiresToolResultName`in n.compat)||typeof n.compat.requiresToolResultName==`boolean`)&&(n.compat.requiresAssistantAfterToolResult===void 0||!(`requiresAssistantAfterToolResult`in n.compat)||typeof n.compat.requiresAssistantAfterToolResult==`boolean`)&&(n.compat.requiresThinkingAsText===void 0||!(`requiresThinkingAsText`in n.compat)||typeof n.compat.requiresThinkingAsText==`boolean`)&&(n.compat.requiresReasoningContentOnAssistantMessages===void 0||!(`requiresReasoningContentOnAssistantMessages`in n.compat)||typeof n.compat.requiresReasoningContentOnAssistantMessages==`boolean`)&&(n.compat.thinkingFormat===void 0||!(`thinkingFormat`in n.compat)||typeof n.compat.thinkingFormat==`string`&&n.compat.thinkingFormat===`openai`||typeof n.compat.thinkingFormat==`string`&&n.compat.thinkingFormat===`openrouter`||typeof n.compat.thinkingFormat==`string`&&n.compat.thinkingFormat===`together`||typeof n.compat.thinkingFormat==`string`&&n.compat.thinkingFormat===`deepseek`||typeof n.compat.thinkingFormat==`string`&&n.compat.thinkingFormat===`zai`||typeof n.compat.thinkingFormat==`string`&&n.compat.thinkingFormat===`qwen`||typeof n.compat.thinkingFormat==`string`&&n.compat.thinkingFormat===`qwen-chat-template`)&&(n.compat.cacheControlFormat===void 0||!(`cacheControlFormat`in n.compat)||typeof n.compat.cacheControlFormat==`string`&&n.compat.cacheControlFormat===`anthropic`)&&(n.compat.openRouterRouting===void 0||!(`openRouterRouting`in n.compat)||typeof n.compat.openRouterRouting==`object`&&n.compat.openRouterRouting!==null&&!Array.isArray(n.compat.openRouterRouting)&&(n.compat.openRouterRouting.allow_fallbacks===void 0||!(`allow_fallbacks`in n.compat.openRouterRouting)||typeof n.compat.openRouterRouting.allow_fallbacks==`boolean`)&&(n.compat.openRouterRouting.require_parameters===void 0||!(`require_parameters`in n.compat.openRouterRouting)||typeof n.compat.openRouterRouting.require_parameters==`boolean`)&&(n.compat.openRouterRouting.data_collection===void 0||!(`data_collection`in n.compat.openRouterRouting)||typeof n.compat.openRouterRouting.data_collection==`string`&&n.compat.openRouterRouting.data_collection===`deny`||typeof n.compat.openRouterRouting.data_collection==`string`&&n.compat.openRouterRouting.data_collection===`allow`)&&(n.compat.openRouterRouting.zdr===void 0||!(`zdr`in n.compat.openRouterRouting)||typeof n.compat.openRouterRouting.zdr==`boolean`)&&(n.compat.openRouterRouting.enforce_distillable_text===void 0||!(`enforce_distillable_text`in n.compat.openRouterRouting)||typeof n.compat.openRouterRouting.enforce_distillable_text==`boolean`)&&(n.compat.openRouterRouting.order===void 0||!(`order`in n.compat.openRouterRouting)||Array.isArray(n.compat.openRouterRouting.order)&&n.compat.openRouterRouting.order.every((e,t)=>typeof e==`string`))&&(n.compat.openRouterRouting.only===void 0||!(`only`in n.compat.openRouterRouting)||Array.isArray(n.compat.openRouterRouting.only)&&n.compat.openRouterRouting.only.every((e,t)=>typeof e==`string`))&&(n.compat.openRouterRouting.ignore===void 0||!(`ignore`in n.compat.openRouterRouting)||Array.isArray(n.compat.openRouterRouting.ignore)&&n.compat.openRouterRouting.ignore.every((e,t)=>typeof e==`string`))&&(n.compat.openRouterRouting.quantizations===void 0||!(`quantizations`in n.compat.openRouterRouting)||Array.isArray(n.compat.openRouterRouting.quantizations)&&n.compat.openRouterRouting.quantizations.every((e,t)=>typeof e==`string`))&&(n.compat.openRouterRouting.sort===void 0||!(`sort`in n.compat.openRouterRouting)||typeof n.compat.openRouterRouting.sort==`string`||typeof n.compat.openRouterRouting.sort==`object`&&n.compat.openRouterRouting.sort!==null&&!Array.isArray(n.compat.openRouterRouting.sort)&&(n.compat.openRouterRouting.sort.by===void 0||!(`by`in n.compat.openRouterRouting.sort)||typeof n.compat.openRouterRouting.sort.by==`string`)&&(n.compat.openRouterRouting.sort.partition===void 0||!(`partition`in n.compat.openRouterRouting.sort)||typeof n.compat.openRouterRouting.sort.partition==`string`||n.compat.openRouterRouting.sort.partition===null))&&(n.compat.openRouterRouting.max_price===void 0||!(`max_price`in n.compat.openRouterRouting)||typeof n.compat.openRouterRouting.max_price==`object`&&n.compat.openRouterRouting.max_price!==null&&!Array.isArray(n.compat.openRouterRouting.max_price)&&(n.compat.openRouterRouting.max_price.prompt===void 0||!(`prompt`in n.compat.openRouterRouting.max_price)||Number.isFinite(n.compat.openRouterRouting.max_price.prompt)||typeof n.compat.openRouterRouting.max_price.prompt==`string`)&&(n.compat.openRouterRouting.max_price.completion===void 0||!(`completion`in n.compat.openRouterRouting.max_price)||Number.isFinite(n.compat.openRouterRouting.max_price.completion)||typeof n.compat.openRouterRouting.max_price.completion==`string`)&&(n.compat.openRouterRouting.max_price.image===void 0||!(`image`in n.compat.openRouterRouting.max_price)||Number.isFinite(n.compat.openRouterRouting.max_price.image)||typeof n.compat.openRouterRouting.max_price.image==`string`)&&(n.compat.openRouterRouting.max_price.audio===void 0||!(`audio`in n.compat.openRouterRouting.max_price)||Number.isFinite(n.compat.openRouterRouting.max_price.audio)||typeof n.compat.openRouterRouting.max_price.audio==`string`)&&(n.compat.openRouterRouting.max_price.request===void 0||!(`request`in n.compat.openRouterRouting.max_price)||Number.isFinite(n.compat.openRouterRouting.max_price.request)||typeof n.compat.openRouterRouting.max_price.request==`string`))&&(n.compat.openRouterRouting.preferred_min_throughput===void 0||!(`preferred_min_throughput`in n.compat.openRouterRouting)||Number.isFinite(n.compat.openRouterRouting.preferred_min_throughput)||typeof n.compat.openRouterRouting.preferred_min_throughput==`object`&&n.compat.openRouterRouting.preferred_min_throughput!==null&&!Array.isArray(n.compat.openRouterRouting.preferred_min_throughput)&&(n.compat.openRouterRouting.preferred_min_throughput.p50===void 0||!(`p50`in n.compat.openRouterRouting.preferred_min_throughput)||Number.isFinite(n.compat.openRouterRouting.preferred_min_throughput.p50))&&(n.compat.openRouterRouting.preferred_min_throughput.p75===void 0||!(`p75`in n.compat.openRouterRouting.preferred_min_throughput)||Number.isFinite(n.compat.openRouterRouting.preferred_min_throughput.p75))&&(n.compat.openRouterRouting.preferred_min_throughput.p90===void 0||!(`p90`in n.compat.openRouterRouting.preferred_min_throughput)||Number.isFinite(n.compat.openRouterRouting.preferred_min_throughput.p90))&&(n.compat.openRouterRouting.preferred_min_throughput.p99===void 0||!(`p99`in n.compat.openRouterRouting.preferred_min_throughput)||Number.isFinite(n.compat.openRouterRouting.preferred_min_throughput.p99)))&&(n.compat.openRouterRouting.preferred_max_latency===void 0||!(`preferred_max_latency`in n.compat.openRouterRouting)||Number.isFinite(n.compat.openRouterRouting.preferred_max_latency)||typeof n.compat.openRouterRouting.preferred_max_latency==`object`&&n.compat.openRouterRouting.preferred_max_latency!==null&&!Array.isArray(n.compat.openRouterRouting.preferred_max_latency)&&(n.compat.openRouterRouting.preferred_max_latency.p50===void 0||!(`p50`in n.compat.openRouterRouting.preferred_max_latency)||Number.isFinite(n.compat.openRouterRouting.preferred_max_latency.p50))&&(n.compat.openRouterRouting.preferred_max_latency.p75===void 0||!(`p75`in n.compat.openRouterRouting.preferred_max_latency)||Number.isFinite(n.compat.openRouterRouting.preferred_max_latency.p75))&&(n.compat.openRouterRouting.preferred_max_latency.p90===void 0||!(`p90`in n.compat.openRouterRouting.preferred_max_latency)||Number.isFinite(n.compat.openRouterRouting.preferred_max_latency.p90))&&(n.compat.openRouterRouting.preferred_max_latency.p99===void 0||!(`p99`in n.compat.openRouterRouting.preferred_max_latency)||Number.isFinite(n.compat.openRouterRouting.preferred_max_latency.p99))))&&(n.compat.vercelGatewayRouting===void 0||!(`vercelGatewayRouting`in n.compat)||typeof n.compat.vercelGatewayRouting==`object`&&n.compat.vercelGatewayRouting!==null&&!Array.isArray(n.compat.vercelGatewayRouting)&&(n.compat.vercelGatewayRouting.only===void 0||!(`only`in n.compat.vercelGatewayRouting)||Array.isArray(n.compat.vercelGatewayRouting.only)&&n.compat.vercelGatewayRouting.only.every((e,t)=>typeof e==`string`))&&(n.compat.vercelGatewayRouting.order===void 0||!(`order`in n.compat.vercelGatewayRouting)||Array.isArray(n.compat.vercelGatewayRouting.order)&&n.compat.vercelGatewayRouting.order.every((e,t)=>typeof e==`string`)))&&(n.compat.supportsStrictMode===void 0||!(`supportsStrictMode`in n.compat)||typeof n.compat.supportsStrictMode==`boolean`)&&(n.compat.supportsJsonSchemaResponseFormat===void 0||!(`supportsJsonSchemaResponseFormat`in n.compat)||typeof n.compat.supportsJsonSchemaResponseFormat==`boolean`)&&(n.compat.supportsLongCacheRetention===void 0||!(`supportsLongCacheRetention`in n.compat)||typeof n.compat.supportsLongCacheRetention==`boolean`)||typeof n.compat==`object`&&n.compat!==null&&!Array.isArray(n.compat)&&(n.compat.supportsTemperature===void 0||!(`supportsTemperature`in n.compat)||typeof n.compat.supportsTemperature==`boolean`)&&(n.compat.supportsInstructions===void 0||!(`supportsInstructions`in n.compat)||typeof n.compat.supportsInstructions==`boolean`)&&(n.compat.cachesInstructions===void 0||!(`cachesInstructions`in n.compat)||typeof n.compat.cachesInstructions==`boolean`)&&(n.compat.sendSessionIdHeader===void 0||!(`sendSessionIdHeader`in n.compat)||typeof n.compat.sendSessionIdHeader==`boolean`)&&(n.compat.supportsLongCacheRetention===void 0||!(`supportsLongCacheRetention`in n.compat)||typeof n.compat.supportsLongCacheRetention==`boolean`)||typeof n.compat==`object`&&n.compat!==null&&!Array.isArray(n.compat)&&(n.compat.supportsEagerToolInputStreaming===void 0||!(`supportsEagerToolInputStreaming`in n.compat)||typeof n.compat.supportsEagerToolInputStreaming==`boolean`)&&(n.compat.supportsLongCacheRetention===void 0||!(`supportsLongCacheRetention`in n.compat)||typeof n.compat.supportsLongCacheRetention==`boolean`))&&(n.authHeader===void 0||!(`authHeader`in n)||typeof n.authHeader==`boolean`)&&(n.models===void 0||!(`models`in n)||Array.isArray(n.models)&&n.models.every((t,n)=>typeof t==`object`&&t!==null&&!Array.isArray(t)&&`id`in t&&typeof t.id==`string`&&(t.id.length>=2||t.id.length>=1&&CodePointCount(t.id)>=1)&&(t.name===void 0||!(`name`in t)||typeof t.name==`string`&&(t.name.length>=2||t.name.length>=1&&CodePointCount(t.name)>=1))&&(t.api===void 0||!(`api`in t)||typeof t.api==`string`&&(t.api.length>=2||t.api.length>=1&&CodePointCount(t.api)>=1))&&(t.baseUrl===void 0||!(`baseUrl`in t)||typeof t.baseUrl==`string`&&(t.baseUrl.length>=2||t.baseUrl.length>=1&&CodePointCount(t.baseUrl)>=1))&&(t.reasoning===void 0||!(`reasoning`in t)||typeof t.reasoning==`boolean`)&&(t.thinkingLevelMap===void 0||!(`thinkingLevelMap`in t)||typeof t.thinkingLevelMap==`object`&&t.thinkingLevelMap!==null&&!Array.isArray(t.thinkingLevelMap)&&(t.thinkingLevelMap.off===void 0||!(`off`in t.thinkingLevelMap)||typeof t.thinkingLevelMap.off==`string`||t.thinkingLevelMap.off===null)&&(t.thinkingLevelMap.minimal===void 0||!(`minimal`in t.thinkingLevelMap)||typeof t.thinkingLevelMap.minimal==`string`||t.thinkingLevelMap.minimal===null)&&(t.thinkingLevelMap.low===void 0||!(`low`in t.thinkingLevelMap)||typeof t.thinkingLevelMap.low==`string`||t.thinkingLevelMap.low===null)&&(t.thinkingLevelMap.medium===void 0||!(`medium`in t.thinkingLevelMap)||typeof t.thinkingLevelMap.medium==`string`||t.thinkingLevelMap.medium===null)&&(t.thinkingLevelMap.high===void 0||!(`high`in t.thinkingLevelMap)||typeof t.thinkingLevelMap.high==`string`||t.thinkingLevelMap.high===null)&&(t.thinkingLevelMap.xhigh===void 0||!(`xhigh`in t.thinkingLevelMap)||typeof t.thinkingLevelMap.xhigh==`string`||t.thinkingLevelMap.xhigh===null)&&(t.thinkingLevelMap.max===void 0||!(`max`in t.thinkingLevelMap)||typeof t.thinkingLevelMap.max==`string`||t.thinkingLevelMap.max===null))&&(t.input===void 0||!(`input`in t)||Array.isArray(t.input)&&t.input.every((e,t)=>typeof e==`string`&&e===`text`||typeof e==`string`&&e===`image`||typeof e==`string`&&e===`audio`||typeof e==`string`&&e===`video`))&&(t.cost===void 0||!(`cost`in t)||typeof t.cost==`object`&&t.cost!==null&&!Array.isArray(t.cost)&&`input`in t.cost&&`output`in t.cost&&`cacheRead`in t.cost&&`cacheWrite`in t.cost&&Number.isFinite(t.cost.input)&&Number.isFinite(t.cost.output)&&Number.isFinite(t.cost.cacheRead)&&Number.isFinite(t.cost.cacheWrite))&&(t.contextWindow===void 0||!(`contextWindow`in t)||Number.isFinite(t.contextWindow))&&(t.contextTokens===void 0||!(`contextTokens`in t)||Number.isFinite(t.contextTokens))&&(t.parameterCount===void 0||!(`parameterCount`in t)||Number.isInteger(t.parameterCount)&&(!(Number.isFinite(t.parameterCount)||typeof t.parameterCount==`bigint`)||t.parameterCount>=1))&&(t.family===void 0||!(`family`in t)||typeof t.family==`string`)&&(t.maxTokens===void 0||!(`maxTokens`in t)||Number.isFinite(t.maxTokens))&&(t.params===void 0||!(`params`in t)||typeof t.params==`object`&&t.params!==null&&!Array.isArray(t.params)&&Object.entries(t.params).every(([t,n],r)=>!e[2].test(t)||!0))&&(t.headers===void 0||!(`headers`in t)||typeof t.headers==`object`&&t.headers!==null&&!Array.isArray(t.headers)&&Object.entries(t.headers).every(([t,n],r)=>!e[3].test(t)||typeof n==`string`))&&(t.compat===void 0||!(`compat`in t)||typeof t.compat==`object`&&t.compat!==null&&!Array.isArray(t.compat)&&(t.compat.supportsStore===void 0||!(`supportsStore`in t.compat)||typeof t.compat.supportsStore==`boolean`)&&(t.compat.supportsDeveloperRole===void 0||!(`supportsDeveloperRole`in t.compat)||typeof t.compat.supportsDeveloperRole==`boolean`)&&(t.compat.supportsReasoningEffort===void 0||!(`supportsReasoningEffort`in t.compat)||typeof t.compat.supportsReasoningEffort==`boolean`)&&(t.compat.supportsUsageInStreaming===void 0||!(`supportsUsageInStreaming`in t.compat)||typeof t.compat.supportsUsageInStreaming==`boolean`)&&(t.compat.maxTokensField===void 0||!(`maxTokensField`in t.compat)||typeof t.compat.maxTokensField==`string`&&t.compat.maxTokensField===`max_completion_tokens`||typeof t.compat.maxTokensField==`string`&&t.compat.maxTokensField===`max_tokens`)&&(t.compat.requiresToolResultName===void 0||!(`requiresToolResultName`in t.compat)||typeof t.compat.requiresToolResultName==`boolean`)&&(t.compat.requiresAssistantAfterToolResult===void 0||!(`requiresAssistantAfterToolResult`in t.compat)||typeof t.compat.requiresAssistantAfterToolResult==`boolean`)&&(t.compat.requiresThinkingAsText===void 0||!(`requiresThinkingAsText`in t.compat)||typeof t.compat.requiresThinkingAsText==`boolean`)&&(t.compat.requiresReasoningContentOnAssistantMessages===void 0||!(`requiresReasoningContentOnAssistantMessages`in t.compat)||typeof t.compat.requiresReasoningContentOnAssistantMessages==`boolean`)&&(t.compat.thinkingFormat===void 0||!(`thinkingFormat`in t.compat)||typeof t.compat.thinkingFormat==`string`&&t.compat.thinkingFormat===`openai`||typeof t.compat.thinkingFormat==`string`&&t.compat.thinkingFormat===`openrouter`||typeof t.compat.thinkingFormat==`string`&&t.compat.thinkingFormat===`together`||typeof t.compat.thinkingFormat==`string`&&t.compat.thinkingFormat===`deepseek`||typeof t.compat.thinkingFormat==`string`&&t.compat.thinkingFormat===`zai`||typeof t.compat.thinkingFormat==`string`&&t.compat.thinkingFormat===`qwen`||typeof t.compat.thinkingFormat==`string`&&t.compat.thinkingFormat===`qwen-chat-template`)&&(t.compat.cacheControlFormat===void 0||!(`cacheControlFormat`in t.compat)||typeof t.compat.cacheControlFormat==`string`&&t.compat.cacheControlFormat===`anthropic`)&&(t.compat.openRouterRouting===void 0||!(`openRouterRouting`in t.compat)||typeof t.compat.openRouterRouting==`object`&&t.compat.openRouterRouting!==null&&!Array.isArray(t.compat.openRouterRouting)&&(t.compat.openRouterRouting.allow_fallbacks===void 0||!(`allow_fallbacks`in t.compat.openRouterRouting)||typeof t.compat.openRouterRouting.allow_fallbacks==`boolean`)&&(t.compat.openRouterRouting.require_parameters===void 0||!(`require_parameters`in t.compat.openRouterRouting)||typeof t.compat.openRouterRouting.require_parameters==`boolean`)&&(t.compat.openRouterRouting.data_collection===void 0||!(`data_collection`in t.compat.openRouterRouting)||typeof t.compat.openRouterRouting.data_collection==`string`&&t.compat.openRouterRouting.data_collection===`deny`||typeof t.compat.openRouterRouting.data_collection==`string`&&t.compat.openRouterRouting.data_collection===`allow`)&&(t.compat.openRouterRouting.zdr===void 0||!(`zdr`in t.compat.openRouterRouting)||typeof t.compat.openRouterRouting.zdr==`boolean`)&&(t.compat.openRouterRouting.enforce_distillable_text===void 0||!(`enforce_distillable_text`in t.compat.openRouterRouting)||typeof t.compat.openRouterRouting.enforce_distillable_text==`boolean`)&&(t.compat.openRouterRouting.order===void 0||!(`order`in t.compat.openRouterRouting)||Array.isArray(t.compat.openRouterRouting.order)&&t.compat.openRouterRouting.order.every((e,t)=>typeof e==`string`))&&(t.compat.openRouterRouting.only===void 0||!(`only`in t.compat.openRouterRouting)||Array.isArray(t.compat.openRouterRouting.only)&&t.compat.openRouterRouting.only.every((e,t)=>typeof e==`string`))&&(t.compat.openRouterRouting.ignore===void 0||!(`ignore`in t.compat.openRouterRouting)||Array.isArray(t.compat.openRouterRouting.ignore)&&t.compat.openRouterRouting.ignore.every((e,t)=>typeof e==`string`))&&(t.compat.openRouterRouting.quantizations===void 0||!(`quantizations`in t.compat.openRouterRouting)||Array.isArray(t.compat.openRouterRouting.quantizations)&&t.compat.openRouterRouting.quantizations.every((e,t)=>typeof e==`string`))&&(t.compat.openRouterRouting.sort===void 0||!(`sort`in t.compat.openRouterRouting)||typeof t.compat.openRouterRouting.sort==`string`||typeof t.compat.openRouterRouting.sort==`object`&&t.compat.openRouterRouting.sort!==null&&!Array.isArray(t.compat.openRouterRouting.sort)&&(t.compat.openRouterRouting.sort.by===void 0||!(`by`in t.compat.openRouterRouting.sort)||typeof t.compat.openRouterRouting.sort.by==`string`)&&(t.compat.openRouterRouting.sort.partition===void 0||!(`partition`in t.compat.openRouterRouting.sort)||typeof t.compat.openRouterRouting.sort.partition==`string`||t.compat.openRouterRouting.sort.partition===null))&&(t.compat.openRouterRouting.max_price===void 0||!(`max_price`in t.compat.openRouterRouting)||typeof t.compat.openRouterRouting.max_price==`object`&&t.compat.openRouterRouting.max_price!==null&&!Array.isArray(t.compat.openRouterRouting.max_price)&&(t.compat.openRouterRouting.max_price.prompt===void 0||!(`prompt`in t.compat.openRouterRouting.max_price)||Number.isFinite(t.compat.openRouterRouting.max_price.prompt)||typeof t.compat.openRouterRouting.max_price.prompt==`string`)&&(t.compat.openRouterRouting.max_price.completion===void 0||!(`completion`in t.compat.openRouterRouting.max_price)||Number.isFinite(t.compat.openRouterRouting.max_price.completion)||typeof t.compat.openRouterRouting.max_price.completion==`string`)&&(t.compat.openRouterRouting.max_price.image===void 0||!(`image`in t.compat.openRouterRouting.max_price)||Number.isFinite(t.compat.openRouterRouting.max_price.image)||typeof t.compat.openRouterRouting.max_price.image==`string`)&&(t.compat.openRouterRouting.max_price.audio===void 0||!(`audio`in t.compat.openRouterRouting.max_price)||Number.isFinite(t.compat.openRouterRouting.max_price.audio)||typeof t.compat.openRouterRouting.max_price.audio==`string`)&&(t.compat.openRouterRouting.max_price.request===void 0||!(`request`in t.compat.openRouterRouting.max_price)||Number.isFinite(t.compat.openRouterRouting.max_price.request)||typeof t.compat.openRouterRouting.max_price.request==`string`))&&(t.compat.openRouterRouting.preferred_min_throughput===void 0||!(`preferred_min_throughput`in t.compat.openRouterRouting)||Number.isFinite(t.compat.openRouterRouting.preferred_min_throughput)||typeof t.compat.openRouterRouting.preferred_min_throughput==`object`&&t.compat.openRouterRouting.preferred_min_throughput!==null&&!Array.isArray(t.compat.openRouterRouting.preferred_min_throughput)&&(t.compat.openRouterRouting.preferred_min_throughput.p50===void 0||!(`p50`in t.compat.openRouterRouting.preferred_min_throughput)||Number.isFinite(t.compat.openRouterRouting.preferred_min_throughput.p50))&&(t.compat.openRouterRouting.preferred_min_throughput.p75===void 0||!(`p75`in t.compat.openRouterRouting.preferred_min_throughput)||Number.isFinite(t.compat.openRouterRouting.preferred_min_throughput.p75))&&(t.compat.openRouterRouting.preferred_min_throughput.p90===void 0||!(`p90`in t.compat.openRouterRouting.preferred_min_throughput)||Number.isFinite(t.compat.openRouterRouting.preferred_min_throughput.p90))&&(t.compat.openRouterRouting.preferred_min_throughput.p99===void 0||!(`p99`in t.compat.openRouterRouting.preferred_min_throughput)||Number.isFinite(t.compat.openRouterRouting.preferred_min_throughput.p99)))&&(t.compat.openRouterRouting.preferred_max_latency===void 0||!(`preferred_max_latency`in t.compat.openRouterRouting)||Number.isFinite(t.compat.openRouterRouting.preferred_max_latency)||typeof t.compat.openRouterRouting.preferred_max_latency==`object`&&t.compat.openRouterRouting.preferred_max_latency!==null&&!Array.isArray(t.compat.openRouterRouting.preferred_max_latency)&&(t.compat.openRouterRouting.preferred_max_latency.p50===void 0||!(`p50`in t.compat.openRouterRouting.preferred_max_latency)||Number.isFinite(t.compat.openRouterRouting.preferred_max_latency.p50))&&(t.compat.openRouterRouting.preferred_max_latency.p75===void 0||!(`p75`in t.compat.openRouterRouting.preferred_max_latency)||Number.isFinite(t.compat.openRouterRouting.preferred_max_latency.p75))&&(t.compat.openRouterRouting.preferred_max_latency.p90===void 0||!(`p90`in t.compat.openRouterRouting.preferred_max_latency)||Number.isFinite(t.compat.openRouterRouting.preferred_max_latency.p90))&&(t.compat.openRouterRouting.preferred_max_latency.p99===void 0||!(`p99`in t.compat.openRouterRouting.preferred_max_latency)||Number.isFinite(t.compat.openRouterRouting.preferred_max_latency.p99))))&&(t.compat.vercelGatewayRouting===void 0||!(`vercelGatewayRouting`in t.compat)||typeof t.compat.vercelGatewayRouting==`object`&&t.compat.vercelGatewayRouting!==null&&!Array.isArray(t.compat.vercelGatewayRouting)&&(t.compat.vercelGatewayRouting.only===void 0||!(`only`in t.compat.vercelGatewayRouting)||Array.isArray(t.compat.vercelGatewayRouting.only)&&t.compat.vercelGatewayRouting.only.every((e,t)=>typeof e==`string`))&&(t.compat.vercelGatewayRouting.order===void 0||!(`order`in t.compat.vercelGatewayRouting)||Array.isArray(t.compat.vercelGatewayRouting.order)&&t.compat.vercelGatewayRouting.order.every((e,t)=>typeof e==`string`)))&&(t.compat.supportsStrictMode===void 0||!(`supportsStrictMode`in t.compat)||typeof t.compat.supportsStrictMode==`boolean`)&&(t.compat.supportsJsonSchemaResponseFormat===void 0||!(`supportsJsonSchemaResponseFormat`in t.compat)||typeof t.compat.supportsJsonSchemaResponseFormat==`boolean`)&&(t.compat.supportsLongCacheRetention===void 0||!(`supportsLongCacheRetention`in t.compat)||typeof t.compat.supportsLongCacheRetention==`boolean`)||typeof t.compat==`object`&&t.compat!==null&&!Array.isArray(t.compat)&&(t.compat.supportsTemperature===void 0||!(`supportsTemperature`in t.compat)||typeof t.compat.supportsTemperature==`boolean`)&&(t.compat.supportsInstructions===void 0||!(`supportsInstructions`in t.compat)||typeof t.compat.supportsInstructions==`boolean`)&&(t.compat.cachesInstructions===void 0||!(`cachesInstructions`in t.compat)||typeof t.compat.cachesInstructions==`boolean`)&&(t.compat.sendSessionIdHeader===void 0||!(`sendSessionIdHeader`in t.compat)||typeof t.compat.sendSessionIdHeader==`boolean`)&&(t.compat.supportsLongCacheRetention===void 0||!(`supportsLongCacheRetention`in t.compat)||typeof t.compat.supportsLongCacheRetention==`boolean`)||typeof t.compat==`object`&&t.compat!==null&&!Array.isArray(t.compat)&&(t.compat.supportsEagerToolInputStreaming===void 0||!(`supportsEagerToolInputStreaming`in t.compat)||typeof t.compat.supportsEagerToolInputStreaming==`boolean`)&&(t.compat.supportsLongCacheRetention===void 0||!(`supportsLongCacheRetention`in t.compat)||typeof t.compat.supportsLongCacheRetention==`boolean`)))));return e=>check_0(e)})();
//!src/agents/sessions/model-registry-schema.ts
const validateModelsConfig={Check:isModelsConfig,Errors:e=>Errors(ModelRegistryConfigSchema,e)[1]};function omitInvalidModelCosts(e){const t=/* @__PURE__ */ new Set;for(const n of validateModelsConfig.Errors(e)){const e=/^(\/providers\/[^/]+\/models\/\d+)\/cost(?:\/|$)/.exec(n.instancePath);if(!e?.[1])return/* @__PURE__ */ new Set;t.add(e[1])}const n=/* @__PURE__ */ new Set;for(const r of t){n.add(Pointer.Get(e,r));Pointer.Delete(e,`${r}/cost`)}return n}function formatValidationPath(e){const t=Pointer.Indices(e.instancePath).join(`.`).replace(/\//g,`.`);if(e.keyword===`required`){const n=e.params.requiredProperties[0];if(n)return t?`${t}.${n}`:n}return t||`root`}
//!src/agents/sessions/provider-display-names.ts
const BUILT_IN_PROVIDER_DISPLAY_NAMES={anthropic:`Anthropic`,"amazon-bedrock":`Amazon Bedrock`,"azure-openai-responses":`Azure OpenAI Responses`,cerebras:`Cerebras`,"cloudflare-ai-gateway":`Cloudflare AI Gateway`,"cloudflare-workers-ai":`Cloudflare Workers AI`,deepseek:`DeepSeek`,fireworks:`Fireworks`,google:`Google Gemini`,"google-vertex":`Google Vertex AI`,groq:`Groq`,huggingface:`Hugging Face`,"kimi-coding":`Kimi For Coding`,meta:`Meta`,mistral:`Mistral`,minimax:`MiniMax`,"minimax-cn":`MiniMax (China)`,moonshotai:`Moonshot AI`,"moonshotai-cn":`Moonshot AI (China)`,opencode:`OpenCode Zen`,"opencode-go":`OpenCode Go`,openai:`OpenAI`,openrouter:`OpenRouter`,together:`Together AI`,"vercel-ai-gateway":`Vercel AI Gateway`,xai:`xAI`,zai:`ZAI`,xiaomi:`Xiaomi MiMo`,"xiaomi-token-plan-cn":`Xiaomi MiMo Token Plan (China)`,"xiaomi-token-plan-ams":`Xiaomi MiMo Token Plan (Amsterdam)`,"xiaomi-token-plan-sgp":`Xiaomi MiMo Token Plan (Singapore)`};
//!src/agents/sessions/model-registry.core.ts
const log=createSubsystemLogger(`agents/model-registry`);var ModelRegistry=class ModelRegistry{constructor(e,t,n={},r,i){this.models=[];this.providerRequestConfigs=/* @__PURE__ */ new Map;this.modelRequestHeaders=/* @__PURE__ */ new Map;this.registeredProviders=/* @__PURE__ */ new Map;this.loadError=void 0;this.includePluginCatalogs=true;this.authStorage=e;this.config=n.config??n.sourceSnapshot?.config;this.excludeGeneratedProviderIds=new Set(n.excludeGeneratedProviderIds);this.includePluginCatalogs=n.includePluginCatalogs!==false;this.reloadPluginCatalogs=this.includePluginCatalogs&&n.pluginCatalogs===void 0;initializeModelRegistryRuntime(this);if(n.sourceSnapshot){const t=n.sourceSnapshot;const i=t.baseCatalogSnapshot??t.captureCatalogSnapshot();const a=r?{...i,models:[...i.models.filter(e=>!r.has(e.provider)),...[...r.values()].flat()]}:i;this.sourceSnapshot=a;this.baseCatalogSnapshot=a;this.restoreSourceCatalog(a,n.selectedModel);this.registeredProviders=cloneMapValues(t.registeredProviders);getAuthStorageOAuthProviderRegistry(e).reset();for(const t of a.oauthProviders)getAuthStorageOAuthProviderRegistry(e).register(t);for(const[e,t]of this.registeredProviders.entries())this.applyProviderConfig(e,t);return}this.modelsJsonPath=t;this.modelsJsonContents=n.modelsJsonContents;this.pluginCatalogs=i?.catalogs??n.pluginCatalogs;this.pluginCatalogReadError=i?.error;this.staticProviderConfigs=n.staticProviderConfigs;this.pluginMetadataSnapshot=resolveModelPluginMetadataSnapshot({config:this.config,...n.pluginMetadataSnapshot?{pluginMetadataSnapshot:n.pluginMetadataSnapshot}:{},...n.workspaceDir?{workspaceDir:n.workspaceDir}:{},allowWorkspaceScopedCurrent:true});this.loadModels();this.baseCatalogSnapshot=this.captureCatalogSnapshot()}captureCatalogSnapshot(){return{models:structuredClone(this.models),providerRequestConfigs:cloneMapValues(this.providerRequestConfigs),modelRequestHeaders:cloneMapValues(this.modelRequestHeaders),loadError:this.loadError,pluginMetadataSnapshot:this.pluginMetadataSnapshot,oauthProviders:[...this.authStorage.getOAuthProviders()]}}restoreSourceCatalog(e,t){const n=t?e.models.findIndex(e=>e.provider===t.provider&&e.id===t.modelId):-1;const r=e.models[n];this.modelScope=t?{source:e.models,index:n}:void 0;this.models=structuredClone(t?r?[r]:[]:e.models);this.providerRequestConfigs=cloneMapValues(e.providerRequestConfigs);this.modelRequestHeaders=cloneMapValues(e.modelRequestHeaders);this.loadError=e.loadError;this.pluginMetadataSnapshot=e.pluginMetadataSnapshot}static create(e,t,n={}){if(n.pluginCatalogs===void 0&&n.includePluginCatalogs!==false)ModelRegistry.warnNativeCatalogRead(`ModelRegistry.create`,`ModelRegistry.createAsync`);return new ModelRegistry(e,t,n)}static async createAsync(e,t,n={}){const r=n.pluginCatalogs===void 0&&n.includePluginCatalogs!==false?await readModelRegistryPluginCatalogs(t,n):void 0;return new ModelRegistry(e,t,n,void 0,r)}static fromCapturedSources(e,t,n){return new ModelRegistry(e,t,n)}static warnNativeCatalogRead(e,t){warnPluginSdkDeprecation({family:`model-registry-native-read`,method:e,replacement:t})}static inMemory(e){return new ModelRegistry(e,void 0)}fork(e,t,n){return new ModelRegistry(e,void 0,{sourceSnapshot:this,selectedModel:n},t)}refresh(){if(this.reloadPluginCatalogs&&this.modelsJsonPath)ModelRegistry.warnNativeCatalogRead(`ModelRegistry.refresh`,`ModelRegistry.refreshAsync`);this.refreshFromStorage()}refreshFromStorage(){if(this.reloadPluginCatalogs&&this.modelsJsonPath){this.pluginCatalogs=void 0;this.pluginCatalogReadError=void 0}this.reload()}async refreshAsync(){if(this.reloadPluginCatalogs&&this.modelsJsonPath){const e=await readModelRegistryPluginCatalogs(this.modelsJsonPath,{config:this.config,modelsJsonContents:this.modelsJsonContents});this.pluginCatalogs=e.catalogs;this.pluginCatalogReadError=e.error}this.reload()}reload(){this.providerRequestConfigs.clear();this.modelRequestHeaders.clear();this.loadError=void 0;resetModelRegistryRuntime(this);getAuthStorageOAuthProviderRegistry(this.authStorage).reset();if(this.sourceSnapshot){this.restoreSourceCatalog(this.sourceSnapshot);for(const e of this.sourceSnapshot.oauthProviders)getAuthStorageOAuthProviderRegistry(this.authStorage).register(e)}else{this.loadModels();this.baseCatalogSnapshot=this.captureCatalogSnapshot()}for(const[e,t]of this.registeredProviders.entries())this.applyProviderConfig(e,t)}getError(){return this.loadError}getProviderMetadataOwners(){return this.pluginMetadataSnapshot?.owners}loadModels(){const e=this.config?.models?.mode===`replace`;const t=!e&&this.modelsJsonPath&&this.modelsJsonContents!==null?this.loadCustomModels(this.modelsJsonPath,{...this.modelsJsonContents!==void 0?{contents:this.modelsJsonContents}:{},includePluginCatalogs:this.includePluginCatalogs&&this.pluginCatalogs===void 0}):emptyCustomModelsResult();const n=!e&&this.includePluginCatalogs&&this.pluginCatalogs!==void 0?this.loadCapturedPluginCatalogs(this.pluginCatalogs):emptyCustomModelsResult();const r=[t.error,n.error,this.pluginCatalogReadError].filter(e=>Boolean(e));if(!e&&this.modelsJsonPath&&this.modelsJsonContents===void 0&&this.reloadPluginCatalogs&&this.staticProviderConfigs===void 0&&this.includePluginCatalogs){const e=inspectLegacyPluginModelCatalogs(dirname(this.modelsJsonPath));const t=[...e.warnings,...e.catalogs.map(({pathname:e})=>`Legacy generated provider catalog: ${e}`)];if(t.length>0)r.push(`${t.join(`
`)}\nRun openclaw doctor --fix to verify and import legacy provider catalogs.`)}if(r.length>0){this.loadError=r.join(`
`);log.warn(`model catalog load issue: ${this.loadError}`)}const i=mergeProviderSources(e?{}:Object.fromEntries(Object.entries(this.staticProviderConfigs??{}).map(([e,t])=>[e,captureProviderSource(t,`static`)])),n.providers,t.providers);const a=buildSourceModelFields(materializeConfiguredProviderCatalogModels(this.config&&projectConfigOntoRuntimeSourceSnapshot(this.config).models?.providers,{manifestPlugins:this.pluginMetadataSnapshot}));for(const[e,t]of Object.entries(normalizeProviderMapKeys(materializeConfiguredProviderCatalogModels(this.config?.models?.providers,{manifestPlugins:this.pluginMetadataSnapshot})))){const n=i[e];const r=new Map(n?.models?.map(e=>[e.id,e]));const o={api:t.api,baseUrl:t.baseUrl,models:t.models?.map(e=>({...e,api:e.api??r.get(e.id)?.api??t.api,baseUrl:e.baseUrl??r.get(e.id)?.baseUrl??t.baseUrl,maxTokensSource:`configured`,headers:sanitizeModelHeaders(e.headers)}))};i[e]=n?mergeProviderModels(captureProviderSource(n,`composed`),o,{providerId:e,modelIdMatching:`exact`,sourceModelFields:a}):o;this.providerRequestConfigs.delete(e);this.storeProviderRequestConfig(e,{apiKey:normalizeOptionalSecretInput(t.apiKey),auth:t.auth,authHeader:t.authHeader,headers:sanitizeModelHeaders(t.headers)})}let o=parseRegistryRuntimeModels(i,this.modelRequestHeaders);for(const e of this.authStorage.getOAuthProviders()){const t=this.authStorage.get(e.id);if(t?.type===`oauth`&&e.modifyModels)o=e.modifyModels(o,t)}this.models=o}loadCapturedPluginCatalogs(e){let t={};const n=[];for(const r of e){const e=this.loadCustomModels(`sqlite:plugin-model-catalog/${r.pluginId}`,{catalogPluginId:r.pluginId,contents:r.contents,includePluginCatalogs:false,requireGeneratedCatalog:true});t=mergeProviderSources(t,e.providers);if(e.error)n.push(e.error)}return{providers:t,error:n.join(`
`)||void 0}}loadCustomModels(e,t={includePluginCatalogs:true}){if(t.contents===void 0&&!existsSync(e))return emptyCustomModelsResult();try{const n=t.contents??readFileSync(e,`utf-8`);const r=parseModelCatalogJson(n,t.requireGeneratedCatalog);if(t.requireGeneratedCatalog===true&&!isGeneratedPluginModelCatalog(r))return emptyCustomModelsResult();const i=validateModelsConfig.Check(r);const a=i?void 0:omitInvalidModelCosts(r);if(!i&&!validateModelsConfig.Check(r)){const t=validateModelsConfig.Errors(r).map(e=>` - ${formatValidationPath(e)}: ${e.message}`).join(`
`)||`Unknown schema error`;return emptyCustomModelsResult(`Invalid models.json schema:\n${t}\n\nFile: ${e}`)}const o=t.requireGeneratedCatalog===true?readGeneratedPluginModelCatalogProviders({catalogPluginId:t.catalogPluginId,config:this.config,isProviderAvailable:e=>this.authStorage.hasAuth(normalizeProviderId(e))||hasUsableCustomProviderApiKey(this.config,e)||resolveManagedSecretRefRuntimeProviderAuth({cfg:this.config,provider:e})!==void 0,parsedCatalog:r,pluginMetadataSnapshot:this.pluginMetadataSnapshot,providers:r.providers}):r.providers;if(t.requireGeneratedCatalog===true&&Object.keys(o).length===0)return emptyCustomModelsResult();const s=[];for(const[n,r]of Object.entries(o)){validateProviderModels(n,r,`catalog`);if(a?.size&&r.models)r.models=r.models.filter(r=>{if(!a.has(r))return true;const i=t.requireGeneratedCatalog?`the provider's catalog source`:e;s.push(`Skipped model ${n}/${r.id}: invalid cost. Fix or remove its cost block in ${i}, then refresh the model catalog.`);return false})}const c=t.requireGeneratedCatalog===true;let l={};for(const[e,t]of Object.entries(o)){if(c&&this.excludeGeneratedProviderIds.has(normalizeProviderId(e)))continue;if(!c&&(t.models??[]).length>0)this.storeProviderRequestConfig(e,t);l[e]=c?captureProviderSource(t,`static`):captureProviderSource(t,`authored`)}const u=s.map(t=>`${t}\nFile: ${e}`);if(t.includePluginCatalogs!==false){let t=[];try{t=loadPersistedPluginModelCatalogsReadOnly(dirname(e))}catch(e){u.push(`Failed to load generated plugin model catalogs: ${e instanceof Error?e.message:String(e)}`)}const n=this.loadCapturedPluginCatalogs(t);l=mergeProviderSources(n.providers,l);if(n.error)u.push(`${n.error}\nRun openclaw doctor --fix to repair persisted generated provider catalogs.`)}return{providers:l,error:u.join(`
`)||void 0}}catch(n){if(n instanceof SyntaxError){if(t.requireGeneratedCatalog===true)return emptyCustomModelsResult();return emptyCustomModelsResult(`Failed to parse models.json: ${n.message}\n\nFile: ${e}`)}return emptyCustomModelsResult(`Failed to load models.json: ${n instanceof Error?n.message:String(n)}\n\nFile: ${e}`)}}getAll(){if(this.modelScope){const e=structuredClone(this.modelScope.source);const t=this.models[0];if(t)e[this.modelScope.index]=t;this.models=e;this.modelScope=void 0}return this.models}getAvailable(){return this.getAll().filter(e=>this.hasConfiguredAuth(e))}find(e,t){const matches=n=>n.provider===e&&n.id===t;return this.models.find(matches)??(this.modelScope?this.getAll().find(matches):void 0)}hasConfiguredAuth(e){return hasModelRegistryConfiguredAuth({model:e,providerConfig:this.getModelProviderRequestConfig(e),authStorage:this.authStorage})}getModelProviderRequestConfig(e){return scopeModelProviderRequestConfig(this.providerRequestConfigs.get(e.provider),e)}storeProviderRequestConfig(e,t){const n=projectProviderRequestConfig(t);if(n)this.providerRequestConfigs.set(e,n)}async getApiKeyAndHeaders(e){return resolveModelRegistryRequestAuth({model:e,providerConfig:this.getModelProviderRequestConfig(e),modelHeaders:this.modelRequestHeaders.get(JSON.stringify([e.provider,e.id])),authStorage:this.authStorage})}getProviderAuthStatus(e){const t=this.providerRequestConfigs.get(e);if(t?.auth===`aws-sdk`)return{configured:true,source:`models_json_key`,label:t.auth};const n=this.authStorage.getAuthStatus(e);if(n.source)return n;const r=t?.apiKey;if(!r)return n;if(r.startsWith(`!`))return{configured:true,source:`models_json_command`};if(process.env[r])return{configured:true,source:`environment`,label:r};return{configured:true,source:`models_json_key`}}getProviderDisplayName(e){const t=this.registeredProviders.get(e);const n=this.authStorage.getOAuthProviders().find(t=>t.id===e);return t?.name??t?.oauth?.name??n?.name??BUILT_IN_PROVIDER_DISPLAY_NAMES[e]??e}async getApiKeyForProvider(e){return resolveModelRegistryProviderApiKey({provider:e,readProviderConfig:()=>this.providerRequestConfigs.get(e),authStorage:this.authStorage})}isUsingOAuth(e){return this.authStorage.get(e.provider)?.type===`oauth`}registerProvider(e,t){if(t.streamSimple&&!t.api)throw new Error(`Provider ${e}: "api" is required when registering streamSimple.`);validateProviderModels(e,t,`registration`);this.applyProviderConfig(e,t);const n=this.registeredProviders.get(e);if(!n){this.registeredProviders.set(e,t);return}for(const e of Object.keys(t))if(t[e]!==void 0)n[e]=t[e]}unregisterProvider(e){if(this.reloadPluginCatalogs&&this.modelsJsonPath)ModelRegistry.warnNativeCatalogRead(`ModelRegistry.unregisterProvider`,`ModelRegistry.unregisterProviderAsync`);if(!this.registeredProviders.delete(e))return;this.refreshFromStorage()}async unregisterProviderAsync(e){if(!this.registeredProviders.delete(e))return;await this.refreshAsync()}applyProviderConfig(e,t){if(t.oauth){const n={...t.oauth,id:e};getAuthStorageOAuthProviderRegistry(this.authStorage).register(n)}if(t.streamSimple){const n=t.streamSimple;getModelRegistryRuntime(this).apiRegistry.registerApiProvider({api:t.api,stream:(e,t,r)=>n(e,t,r),streamSimple:n},`provider:${e}`)}this.storeProviderRequestConfig(e,t);if(t.models&&t.models.length>0){this.models=this.getAll().filter(t=>t.provider!==e);for(const n of t.models){const r=n.api||t.api;storeModelHeaders(this.modelRequestHeaders,e,n.id,n.headers);this.models.push(createRegistryRuntimeModel(e,t,n,r))}if(t.oauth?.modifyModels){const n=this.authStorage.get(e);if(n?.type===`oauth`)this.models=t.oauth.modifyModels(this.models,n)}}}};export{resolveModelPluginMetadataSnapshot as n,resolveModelWorkspaceDir as r,ModelRegistry as t};