UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

3 lines • 13.5 kB
import{t as formatErrorMessage}from"./errors-D37BJTfI.mjs";import{n as createLazyPromise}from"./lazy-promise-CismJCQR.mjs";import"./model-ref-shared-T-aCqInj.mjs";import{t as isUserModelAuthProfileId}from"./user-model-account-id-CU4k7NMV.mjs";import{s as resolveNativeOwnedRuntimeModel}from"./defaults-k51tX6yK.mjs";import{n as resolveProviderModelMaterializationAuthMode}from"./provider-model-route-auth-ClM4Emo4.mjs";import{m as resolveConfiguredModelPolicyAllow}from"./model-selection-shared-CIOFxJ36.mjs";import{t as createModelCatalogIdentityKeyResolver}from"./openai-model-routes-DFmM1mZU.mjs";import{r as findModelInCatalog}from"./model-catalog-lookup-bSGgKRpi.mjs";import{r as modelKey}from"./provider-registry-index-fv5AHL27.mjs";import{s as FailoverError}from"./error-oegzzI05.mjs";import{t as resolveAgentHarnessPolicy}from"./policy-B5H6zqjn.mjs";import{r as PreparedModelRuntimePublicationSupersededError}from"./prepared-model-runtime-admission-errors-DZto8oll.mjs";import"./prepared-model-runtime.errors-CJIB8kC0.mjs";import{n as resolveModelRuntimeRoute,t as CLAUDE_CLI_SETUP_GUIDANCE}from"./model-runtime-route-CZixJ6aq.mjs"; //!src/agents/model-runtime-choice.ts const loadPreparedModelCatalog=createLazyPromise(()=>import(`./prepared-model-catalog-BMl2SNE7.mjs`));const loadModelResolver=createLazyPromise(()=>import(`./model-X2vbd4LA.mjs`));const loadModelSelection=createLazyPromise(()=>import(`./model-selection-B0xBo4V2.mjs`));const loadModelRefProfile=createLazyPromise(()=>import(`./model-ref-profile-DNUQ6ZKf.mjs`));const loadModelCatalogDecisions=createLazyPromise(()=>import(`./model-catalog-decisions-BOXnPaXL.mjs`));const loadPreparedRuntimeAuth=createLazyPromise(()=>import(`./prepared-model-runtime-auth-R4HShvkd.mjs`));const loadProviderModelRoute=createLazyPromise(()=>import(`./provider-model-route-pb3RJibv.mjs`));const loadRuntimeModelMaterializer=createLazyPromise(()=>import(`./materialize-model-BajVoIcg.mjs`));const loadModelFallbackCandidates=createLazyPromise(()=>import(`./model-fallback-candidates-BnvyXRDj.mjs`));const loadProviderAuthAliases=createLazyPromise(()=>import(`./provider-auth-aliases-DG29l98l.mjs`));const loadPluginGenerationScope=createLazyPromise(()=>import(`./generation-scope-CiWPlhl8.mjs`));const loadModelCatalogEntry=createLazyPromise(()=>import(`./model-catalog-entry-BgU_nDxe.mjs`));const loadCatalogDecisionRuntime=createLazyPromise(()=>import(`./model-catalog-decision-runtime-DIMGj0XV.mjs`));async function prepareModelChoice(e){const{withPreparedModelCatalogOwner:t,materializePreparedModelCatalogOwner:n}=await loadPreparedModelCatalog();const{resolveModelAsync:r}=await loadModelResolver();const{buildModelAliasIndex:i,resolveAllowedModelRef:a,resolveDefaultModelForAgent:o,resolveModelRefFromString:s}=await loadModelSelection();const{splitTrailingAuthProfile:c}=await loadModelRefProfile();const{prepareModelCatalogDecisions:l,resolveCatalogDecisionRuntime:u}=await loadModelCatalogDecisions();const{getPreparedModelRuntimeAuthStore:d}=await loadPreparedRuntimeAuth();const{projectProviderModelRouteConfig:f}=await loadProviderModelRoute();const{validatePreparedRuntimeModel:p}=await loadRuntimeModelMaterializer();const{resolveModelCandidateChain:m}=await loadModelFallbackCandidates();const{resolveProviderIdForAuth:h}=await loadProviderAuthAliases();const{withPluginRuntimeGenerationScope:g}=await loadPluginGenerationScope();return await t({config:e.cfg,agentId:e.agentId,workspaceDir:e.workspaceDir,readOnly:true},t=>{let _=t;return g(_,async()=>{const t=o({cfg:_.config,agentId:e.agentId});const g={cfg:_.config,agentId:e.agentId,defaultProvider:t.provider,defaultModel:t,catalog:_.modelCatalog.entries,manifestPlugins:_.metadataSnapshot.plugins,raw:e.raw};const v=e.source===`automatic`&&e.resolvedRef?{ref:e.resolvedRef}:e.source===`override`?a(g):s({...g,aliasIndex:i(g)});if(!v)return{kind:`unavailable`,error:`invalid model: ${e.raw}`};if(`error`in v){const e=resolveConfiguredModelPolicyAllow(g);return{kind:`unavailable`,error:v.error.startsWith(`model not allowed:`)?`${v.error}. Rejected by ${e.configPath??e.repairConfigPath}. Add the model or its provider wildcard to ${e.repairConfigPath}, or choose an allowed model.`:v.error}}const y=v.ref;const authOwner=e=>h(e,{config:_.config,workspaceDir:_.workspaceDir,metadataSnapshot:_.metadataSnapshot});const b=authOwner(y.provider);const prepare=async t=>{const i=d(_);if(!i)return{kind:`unavailable`,error:`Model account facts are not prepared. Retry after configuration finishes loading.`};const a=authOwner(t.provider)===b?c(e.raw).profile:void 0;const o=modelKey(t.provider,t.model);const decide=async n=>{const r=await l({cfg:_.config,agentId:e.agentId,agentDir:_.agentDir,workspaceDir:_.workspaceDir,snapshot:n,metadataSnapshot:_.metadataSnapshot,preparedAuthStore:i,preparedRuntimeAuthModes:_.authModes,pluginRegistry:_.pluginRegistry,observationConfig:_.observationConfig,isCurrent:_.isCurrent,preferredProfileId:a,pinnedProfileId:a,profileProvider:t.provider});const s=r.snapshot.entries.find(e=>modelKey(e.provider,e.id)===o)??{provider:t.provider,id:t.model,name:t.model};const c=r.snapshot.routeVariants.filter(e=>modelKey(e.provider,e.id)===o);const u=r.evaluateEntry(s,c);return{decisions:r,entry:s,auth:r.evaluateNative(s,u)}};let{decisions:s,entry:m,auth:h}=await decide(_.modelCatalog);let g;if(h.runtimeAuth?.source===`native`&&h.availability!==true){await _.recheckNativeLogin?.({force:true});_=n(_);({decisions:s,entry:m,auth:h}=await decide(_.modelCatalog))}if(h.availability!==true&&h.runtimeAuth?.source===`native`&&_.loadNativeModelCatalog){const e=await _.loadNativeModelCatalog({provider:t.provider,modelId:t.model,runtime:h.runtimeAuth.id}).catch(e=>{g=e});if(e){if(!e.entries.some(e=>modelKey(e.provider,e.id)===o))return{kind:`unavailable`,error:`The native runtime no longer offers ${o}. Refresh the model catalog and choose again.`};({decisions:s,entry:m,auth:h}=await decide(e))}}if(h.routeResolution?.kind===`incompatible`)return{kind:`unavailable`,error:h.routeResolution.message};if(h.runtimeAuth?.source===`native`&&h.availability!==true||(a||h.availabilityAuthoritative)&&h.availability===false)return{kind:`unavailable`,error:g===void 0?`The selected account or native runtime is unavailable for ${o}. Restore that account before spawning this model.`:`The native runtime is unavailable for ${o}: native catalog renewal failed: ${formatErrorMessage(g)}`};const v=u({cfg:_.config,agentId:e.agentId,entry:m,evaluation:h,pluginRegistry:_.pluginRegistry,resolveOpenAIProviderRoutes:s.resolveOpenAIProviderRoutes})?.id;const y=resolveNativeOwnedRuntimeModel({catalog:s.snapshot,provider:t.provider,modelId:t.model,runtimeId:v});if(y)return s.isCurrent()?{kind:`resolved`,ref:t,model:y}:{kind:`unavailable`,error:`Model configuration changed during selection. Retry the request.`};const x=h.selectedRoute?f({provider:t.provider,config:_.config,route:h.selectedRoute}):_.config;const S=await r(t.provider,t.model,_.agentDir,x,{agentId:e.agentId,workspaceDir:_.workspaceDir,preparedModelRuntime:_,assertCurrent:s.assertCurrent,modelIdSource:`selected`,authProfileId:h.selectedProfileId,authProfileMode:resolveProviderModelMaterializationAuthMode(h.selectedAuthMode),...v?{agentRuntimeId:v}:{},allowBundledStaticCatalogFallback:true,deferProviderDynamicModelPreparation:e.source===`automatic`}).catch(e=>{if(e instanceof PreparedModelRuntimePublicationSupersededError)return;throw e});if(!S||!s.isCurrent())return{kind:`unavailable`,error:`Model configuration changed during selection. Retry the request.`};if(S.model)try{const e=p({provider:t.provider,modelId:t.model,config:x,workspaceDir:_.workspaceDir,metadataSnapshot:_.metadataSnapshot,route:h.selectedRoute?{...h.selectedRoute,provider:t.provider,modelId:t.model}:void 0,model:S.model});return{kind:`resolved`,ref:S.logicalRef,model:e}}catch(e){if(e instanceof FailoverError&&e.reason===`model_not_found`)return{kind:`unavailable`,error:e.message};throw e}return S.deferred===`provider-dynamic-model`?{kind:`pending`,ref:t}:{kind:`unavailable`,error:S.error}};const x=await prepare(y);if(e.source!==`automatic`||x.kind!==`unavailable`)return x;const S=m({cfg:_.config,agentId:e.agentId,provider:y.provider,model:y.model,requestedRouteResolution:`resolved`,allowPluginNormalization:false,manifestPlugins:_.metadataSnapshot.plugins,fallbacksOverride:e.fallbacks??[]}).slice(1);const C=await Promise.all(S.map(prepare));if(!_.isCurrent())return{kind:`unavailable`,error:`Model configuration changed during selection. Retry the request.`};return C.some(e=>e.kind!==`unavailable`)?{kind:`automatic`,ref:y}:x})})}async function preparePublishedModelRuntimeChoice(e){const t=await loadPreparedModelCatalog();const{getPublishedPreparedModelCatalogOwnerSnapshot:n,materializePreparedModelCatalogOwner:r}=t;const{getPreparedModelRuntimeAuthStore:i}=await loadPreparedRuntimeAuth();const{prepareModelCatalogDecisions:a}=await loadModelCatalogDecisions();const o={config:e.cfg,agentId:e.agentId,workspaceDir:e.workspaceDir};const s=e.prepareNativeCatalog?await e.prepareNativeCatalog(()=>t.loadPublishedPreparedModelCatalogOwnerSnapshot(o)):n(o);const c=`${e.runtimeId?`Runtime "${e.runtimeId}"`:`A runtime`} is not available for ${e.provider}/${e.model}`;const l=`${c}. Refresh the model catalog and choose again.`;if(!s)return{kind:`unavailable`,message:l};await s.recheckNativeLogin?.();let u;if(e.prepareNativeCatalog){const t=findModelInCatalog(s.modelCatalog.entries,e.provider,e.model);const n=e.runtimeId??e.preferredRuntimeId??resolveAgentHarnessPolicy({config:s.config,agentId:e.agentId,provider:e.provider,modelId:e.model,modelApi:t?.api,modelBaseUrl:t?.baseUrl}).runtime;if(s.pluginRegistry?.agentHarnesses.some(e=>e.harness.id===n&&typeof e.harness.loadModelCatalog===`function`))u=await e.prepareNativeCatalog(async()=>s.loadNativeModelCatalog?.({provider:e.provider,modelId:e.model,runtime:n}))}const d=r(s,u);const f=i(d);if(!f)return{kind:`unavailable`,message:l};const p=await a({cfg:d.config,agentId:d.agentId??e.agentId,agentDir:d.agentDir,workspaceDir:d.workspaceDir,snapshot:d.modelCatalog,metadataSnapshot:d.metadataSnapshot,preparedAuthStore:f,preparedRuntimeAuthModes:d.authModes,pluginRegistry:d.pluginRegistry,observationConfig:d.observationConfig,isCurrent:d.isCurrent,preferredProfileId:e.sessionEntry?.authProfileOverride,pinnedProfileId:e.sessionEntry?.authProfileOverrideSource===`user`?e.sessionEntry.authProfileOverride:void 0,profileProvider:e.sessionEntry?.providerOverride??e.sessionEntry?.modelProvider});const describeUnavailable=async(t,n,r)=>{const i=n.availability===true?void 0:n.unavailableReason;if(!i)return l;if((i===`missing-auth`||i===`auth-failed`)&&n.selectedProfileId&&!n.runtimeAuth){const e=isUserModelAuthProfileId(n.selectedProfileId)?`personal account`:`account "${n.selectedProfileId}"`;return`${c}: selected ${e} is unavailable. Restore that account, or change the explicit or default account selection.`}const{resolveCatalogDecisionRuntime:a}=await loadCatalogDecisionRuntime();const o=r??a({cfg:d.config,agentId:d.agentId??e.agentId,entry:t,evaluation:n,pluginRegistry:d.pluginRegistry,resolveOpenAIProviderRoutes:p.resolveOpenAIProviderRoutes})?.id;const s=resolveModelRuntimeRoute(e.provider,o)===`claudeCli`;switch(i){case`missing-auth`:return`${c}: sign-in needed. ${s?CLAUDE_CLI_SETUP_GUIDANCE:`Connect its provider account, or choose another model.`}`;case`auth-failed`:return`${c}: sign-in failed. ${s?CLAUDE_CLI_SETUP_GUIDANCE:`Sign in to its provider again, or choose another model.`}`;case`cooldown`:return`${c}: temporarily unavailable. Try again later or choose another model.`;default:return l}};let m=findModelInCatalog(p.snapshot.entries,e.provider,e.model)??p.snapshot.entries.find(t=>modelKey(t.provider,t.id)===modelKey(e.provider,e.model));if(!m){const{resolveModelAsync:t}=await loadModelResolver();const{modelCatalogRowToEntry:n}=await loadModelCatalogEntry();const r={provider:e.provider,id:e.model,name:e.model};const i=e.runtimeId??(e.preferredRuntimeId&&p.runtimeChoices(r,[r])?.includes(e.preferredRuntimeId)?e.preferredRuntimeId:void 0);const a=p.evaluateEntry(r,void 0,i);const o=resolveProviderModelMaterializationAuthMode(a.selectedAuthMode);if(a.availability!==true||!o)return{kind:`unavailable`,message:await describeUnavailable(r,a,i)};const s=await t(e.provider,e.model,d.agentDir,d.config,{agentId:d.agentId??e.agentId,workspaceDir:d.workspaceDir,preparedModelRuntime:d,agentRuntimeId:i,allowBundledStaticCatalogFallback:true,assertCurrent:p.assertCurrent,authProfileMode:o,...a.selectedProfileId?{authProfileId:a.selectedProfileId}:{}});if(!s.model)return{kind:`unavailable`,message:l};m=n(s.model)}const h=createModelCatalogIdentityKeyResolver();const g=h(m);const _=p.snapshot.routeVariants.filter(e=>h(e)===g);const v=_.length?_:[m];const y=p.runtimeChoices(m,v);const b=e.runtimeId??(e.preferredRuntimeId&&y?.includes(e.preferredRuntimeId)?e.preferredRuntimeId:y?.[0]);if(!b||!y?.includes(b)){const t=e.runtimeId??e.preferredRuntimeId;const n=p.evaluateNative(m,p.evaluateEntry(m,v,t),t);return{kind:`unavailable`,message:await describeUnavailable(m,n,t)}}const x=p.evaluateEntry(m,v,b);const validate=()=>p.isCurrent()&&p.evaluateNative(m,x,b).availability===true?void 0:l;return{kind:`ready`,runtimeId:b,validate,harness:d.pluginRegistry?.agentHarnesses.find(e=>e.harness.id===b)?.harness}}export{preparePublishedModelRuntimeChoice as n,prepareModelChoice as t};