openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
7 lines • 18.3 kB
JavaScript
import{o as normalizeLowercaseStringOrEmpty}from"./string-coerce-CpTFcSwY.mjs";import{u as normalizePluginsConfig}from"./config-state-C1eV6UWf.mjs";import{d as withPluginRuntimeRegistryScope}from"./gateway-request-scope-7deHmsb_.mjs";import{r as normalizeProviderId}from"./provider-id-A-8WTtLA.mjs";import{a as resolveAgentDir,b as resolveNativeModelPrimary,f as resolveAgentWorkspaceDir}from"./agent-scope-config-CG9CFpGX.mjs";import{i as getActiveOpenClawStateDatabaseReadSnapshot}from"./openclaw-state-db-readonly-Cd5_cxBs.mjs";import{n as captureOpenClawStateReadWorkerContext}from"./openclaw-state-worker-context-Dx8YjqO2.mjs";import{t as isUserModelAuthProfileId}from"./user-model-account-id-CU4k7NMV.mjs";import{r as captureUserProfileModelAccountLinksAuthority}from"./user-profile-events-CkQlfQnE.mjs";import{t as splitTrailingAuthProfile}from"./model-ref-profile-DFGpvDZX.mjs";import{i as resolveProviderIdForAuth}from"./provider-auth-aliases-BRA1A5Vm.mjs";import"./agent-scope-Dw5XRSEh.mjs";import{n as withPluginRuntimeGenerationScope}from"./generation-scope-CxHnQlew.mjs";import{i as listCliRuntimeModelBackendBindings}from"./cli-backends-BDgFsc0L.mjs";import{n as createProviderModelRoutesResolver}from"./provider-model-routes-D-c2AdKe.mjs";import{a as isAuthModeAllowedForModel}from"./model-runtime-policy-DJvvlwBk.mjs";import{n as isManifestPluginAvailableForControlPlane}from"./manifest-contract-eligibility-BFn2JM5T.mjs";import{o as dedupeModelCatalogEntries}from"./model-selection-shared-CIOFxJ36.mjs";import{r as openAIModelCatalogRoutePolicy,t as createModelCatalogIdentityKeyResolver}from"./openai-model-routes-DFmM1mZU.mjs";import{n as resolveDefaultModelForAgent}from"./model-selection-config-CnvHkHXn.mjs";import{l as getActiveSecretsRuntimeSnapshotRevisionState}from"./runtime-state-lO6JkIdi.mjs";import{t as resolveAgentHarnessPolicy}from"./policy-B5H6zqjn.mjs";import{p as resolveProviderRefOwnership}from"./providers-CcG8xzp1.mjs";import{n as buildAgentHarnessSupportContext}from"./support-DIIDUASx.mjs";import{r as PreparedModelRuntimePublicationSupersededError}from"./prepared-model-runtime-admission-errors-DZto8oll.mjs";import{R as resolvePluginOwnedProviderAuthWith,h as resolveAuthStoreReadOnlyValidUntil,z as resolveProviderAuthScope}from"./loader-runtime-load-CVvaB9FO.mjs";import{x as materializePreparedPersonalAuthProfile}from"./store-CX8ovUiF.mjs";import{a as resolveExternalCliAuthScopeFromConfig}from"./external-cli-discovery-CHmIqgrd.mjs";import{a as resolveLoadedProviderRuntimePlugin}from"./provider-hook-runtime-CkdKr0V8.mjs";import{a as resolveLegacyInheritedAuthDir}from"./legacy-inherited-auth-dir-9LCjV4lR.mjs";import{a as prepareModelCatalogView,o as selectModelCatalogRuntimeEntry,r as listModelCatalogObservedRoutes,t as createModelCatalogSnapshotView}from"./model-catalog-view-Dlcu0aHX.mjs";import{d as loadManifestModelCatalog}from"./prepared-model-runtime.plugin-generation-V-mQdME2.mjs";import"./prepared-model-runtime.errors-CJIB8kC0.mjs";import{n as isPreparedModelCatalogFull}from"./prepared-model-runtime.full-catalog-BxShrXPt.mjs";import{t as createUnlistedClaudeCliWildcardCheck}from"./model-catalog-cli-wildcard-CtZCSS0v.mjs";import{n as withCurrentReadAuthority}from"./current-read-authority-J_xgisvq.mjs";import{t as createModelAuthAvailabilityResolver}from"./model-auth-availability-B0kwJlCh.mjs";import{t as resolveCatalogDecisionRuntime}from"./model-catalog-decision-runtime-uVizY4Lw.mjs";
//!src/agents/model-catalog-account-outcomes.ts
const normalizedListings=/* @__PURE__ */ new WeakMap;function indexListing(e){const t=normalizedListings.get(e);if(t)return t;const n=/* @__PURE__ */ new Set;for(const t of e)n.add(normalizeLowercaseStringOrEmpty(t));normalizedListings.set(e,n);return n}function createAccountCatalogOutcomes(e=[]){const t=[...e];const n=/* @__PURE__ */ new Map;const keyOf=(e,t)=>JSON.stringify([e,t]);return{outcomes:t,accountListsModel:(e,r,i)=>{const a=keyOf(e,r);let o=n.get(a);if(!o){o=[];for(const n of t)if(n.status===`ready`&&n.listedModelIds&&n.profileId===r&&normalizeProviderId(n.provider)===e)o.push(indexListing(n.listedModelIds));n.set(a,o)}return o.length?o.some(e=>e.has(i)):void 0},replace(e,r,i){const matches=t=>normalizeProviderId(t.provider)===e&&t.profileId===r;const a=t.filter(matches);if(a.length===i.length&&a.every((e,t)=>e===i[t]))return false;t.splice(0,t.length,...t.filter(e=>!matches(e)),...i);n.delete(keyOf(e,r));return true}}}
//!src/agents/model-catalog-decisions.plugin-auth.ts
function createCatalogPluginAuth({cfg:e,workspaceDir:t,metadataSnapshot:n,pluginRegistry:r}){return{evaluatePluginAuth:(i,a)=>{if(!r)return{availability:void 0,routeResolution:null,availabilityAuthoritative:true};try{return withPluginRuntimeGenerationScope({metadataSnapshot:n,pluginRegistry:r},()=>{const r=resolvePluginOwnedProviderAuthWith({provider:i,config:e,workspaceDir:t,pluginMetadataSnapshot:n,profileId:a.requiredProfileId??a.pinnedProfileId,preferredProfile:a.preferredProfileId},resolveLoadedProviderRuntimePlugin);const o=isAuthModeAllowedForModel({provider:i,mode:r.mode,modelApi:a.api??void 0,modelBaseUrl:typeof a.baseUrl===`string`?a.baseUrl:void 0})&&(!r.nativeAuth||r.nativeAuth.runtime===a.runtimeId);return{availability:o,selectedAuthMode:r.mode,...o&&r.nativeAuth?{runtimeAuth:{id:r.nativeAuth.runtime,source:`native`}}:{},evidence:`runtime`,routeResolution:null,availabilityAuthoritative:true}})}catch{return{availability:false,unavailableReason:`missing-auth`,evidence:`runtime`,routeResolution:null,availabilityAuthoritative:true}}},canRefreshProviderOAuth:i=>{if(!r)return false;try{return withPluginRuntimeGenerationScope({metadataSnapshot:n,pluginRegistry:r},()=>typeof resolveLoadedProviderRuntimePlugin({provider:i,config:e,workspaceDir:t})?.refreshOAuth===`function`)}catch{return false}}}}
//!src/agents/model-catalog-decisions.ts
async function prepareModelCatalogDecisions(e,t){const n=e.preferredProfileId&&isUserModelAuthProfileId(e.preferredProfileId)?{profileId:e.preferredProfileId}:!e.preferredProfileId&&e.requesterProfileId?{requesterProfileId:e.requesterProfileId}:void 0;if(!n||e.preparedPersonalCatalog)return withCurrentReadAuthority(t,()=>createModelCatalogDecisions(e));const r=captureOpenClawStateReadWorkerContext();const i=`requesterProfileId`in n?captureUserProfileModelAccountLinksAuthority(r.admission,n.requesterProfileId):void 0;const isCurrent=()=>{try{r.admission.assertCurrent();return i?.()!==false}catch{return false}};const assertPreparedCurrent=()=>{if(!isCurrent()||e.isCurrent?.()===false)throw new PreparedModelRuntimePublicationSupersededError(`Personal model accounts changed while preparing the catalog`)};const{readPersonalCatalogProfiles:a}=await import(`./sqlite-read-Cf6U5QCN.mjs`);const o=await withCurrentReadAuthority(t,()=>{assertPreparedCurrent();if(`requesterProfileId`in n&&getActiveOpenClawStateDatabaseReadSnapshot())throw new PreparedModelRuntimePublicationSupersededError(`Default account selection requires current link authority`);return a(n,r)});return withCurrentReadAuthority(t,()=>{assertPreparedCurrent();return createModelCatalogDecisions({...e,preparedPersonalCatalog:{...o,isCurrent}})})}function createModelCatalogDecisions(e){const t=e.metadataSnapshot;const n=e.workspaceDir??resolveAgentWorkspaceDir(e.cfg,e.agentId);const r=splitTrailingAuthProfile(resolveNativeModelPrimary(e.cfg,e.agentId)??``).profile;const i=resolveDefaultModelForAgent({...e,manifestPlugins:t});const a={provider:i.provider,id:i.model};const o=createModelCatalogIdentityKeyResolver();const s=o(a);const configuredPinForEntry=e=>r!==void 0&&o(e)===s?r:void 0;const c=e.pluginRegistry?withPluginRuntimeRegistryScope(e.pluginRegistry,()=>listCliRuntimeModelBackendBindings()):listCliRuntimeModelBackendBindings();let l=e.preparedAuthStore;const u=/* @__PURE__ */ new Map;const d=/* @__PURE__ */ new Set;const f=e.preparedPersonalCatalog;if(!f&&(e.preferredProfileId&&isUserModelAuthProfileId(e.preferredProfileId)||!e.preferredProfileId&&e.requesterProfileId))throw new Error(`Personal model catalog records require asynchronous preparation`);if(e.preferredProfileId&&isUserModelAuthProfileId(e.preferredProfileId)){l=materializePreparedPersonalAuthProfile(l,e.preferredProfileId,f?.profiles[e.preferredProfileId]);const t=l.profiles[e.preferredProfileId]?.provider;if(t)d.add(normalizeProviderId(t))}else if(!e.preferredProfileId&&e.requesterProfileId)for(const t of f?.links??[]){const n=isUserModelAuthProfileId(t.authProfileId)?materializePreparedPersonalAuthProfile(l,t.authProfileId,f?.profiles[t.authProfileId]):l;const r=n.profiles[t.authProfileId]?.provider??e.cfg.auth?.profiles?.[t.authProfileId]?.provider;if(!r||normalizeProviderId(r)!==t.provider)continue;l=n;u.set(t.provider,t.authProfileId);if(isUserModelAuthProfileId(t.authProfileId))d.add(t.provider)}const p=d.size?[...e.snapshot.staticEntries??[],...loadManifestModelCatalog({config:e.cfg,metadataSnapshot:t})].filter(e=>d.has(normalizeProviderId(e.provider))):[];let m=p.length?{...e.snapshot,entries:dedupeModelCatalogEntries([...e.snapshot.entries,...p]),routeVariants:[...e.snapshot.routeVariants.length?e.snapshot.routeVariants:e.snapshot.entries,...p]}:e.snapshot;const h=e.preferredProfileId??e.pinnedProfileId;const g=e.profileProvider??(h?l.profiles[h]?.provider??e.cfg.auth?.profiles?.[h]?.provider:void 0);if(m.pendingProviders?.length&&(h||u.size)){const authProvider=n=>resolveProviderIdForAuth(n,{config:e.cfg,metadataSnapshot:t});m={...m,pendingProviders:m.pendingProviders.filter(e=>!u.has(normalizeProviderId(e))&&(!h||g&&authProvider(e)!==authProvider(g)))}}const _=createAccountCatalogOutcomes(m.providerOutcomes);const v=_.outcomes;const y=m;m={...m,providerOutcomes:v,get refreshFailed(){return y.refreshFailed},get refreshFailures(){return y.refreshFailures},get pendingProviders(){return y.pendingProviders}};const b=createProviderModelRoutesResolver({provider:`openai`,config:e.cfg,env:process.env});const x=prepareModelCatalogView({...e,snapshot:m,workspaceDir:n,profileProvider:g,resolveOpenAIProviderRoutes:b}).evaluateNative;const evaluateNative=(e,t,n)=>u.has(normalizeProviderId(e.provider))||configuredPinForEntry(e)?t:x(e,t,n);const S=resolveAuthStoreReadOnlyValidUntil(l,Date.now());const isPluginAuthProvider=r=>resolveProviderAuthScope({provider:r,config:e.cfg,workspaceDir:n,pluginMetadataSnapshot:t})===`plugin`;const C=getActiveSecretsRuntimeSnapshotRevisionState();const w=m.entries.some(e=>isPluginAuthProvider(e.provider));const T=resolveAgentDir(e.cfg,e.agentId);let E;const D=createModelAuthAvailabilityResolver({...createCatalogPluginAuth({cfg:e.cfg,workspaceDir:n,metadataSnapshot:t,pluginRegistry:e.pluginRegistry}),cfg:e.cfg,agentId:e.agentId,authStore:l,agentDir:T,preparedCliRuntimeAuthDirectories:{agentDir:T,inheritedAuthDir:resolveLegacyInheritedAuthDir(e.cfg)},env:process.env,metadataSnapshot:t,preparedRuntimeAuthModes:e.preparedRuntimeAuthModes,preparedRuntimeAuthMaterializations:e.preparedRuntimeAuthMaterializations,preparedSyntheticAuthComplete:e.preparedSyntheticAuthComplete??isPreparedModelCatalogFull(e.snapshot),workspaceDir:n,syntheticAuthProviderRefs:t.plugins.filter(n=>isManifestPluginAvailableForControlPlane({snapshot:t,plugin:n,config:e.cfg,normalizedConfig:e.cfg.plugins&&(E??=normalizePluginsConfig(e.cfg.plugins))})).flatMap(e=>e.syntheticAuthRefs??[]),externalCliProviderIds:resolveExternalCliAuthScopeFromConfig(e.cfg)?.providerIds??[],preparedRuntimeAuthStore:l,routeResolverFactory:e.routeResolverFactory,resolveOpenAIProviderRoutes:b,accountListsModel:_.accountListsModel});const O=/* @__PURE__ */ new Map;const k=e.preferredProfileId||void 0;const A=e.pinnedProfileId||void 0;const normalizeAuthProvider=n=>resolveProviderIdForAuth(n,{config:e.cfg,metadataSnapshot:t});const isSelectedProvider=e=>!g||normalizeAuthProvider(g)===normalizeAuthProvider(e);const pinnedProfileForEntry=e=>(isSelectedProvider(e.provider)?A:void 0)??u.get(normalizeProviderId(e.provider))??configuredPinForEntry(e);const j=createUnlistedClaudeCliWildcardCheck({cfg:e.cfg,agentId:e.agentId,outcomes:()=>m.providerOutcomes});const evaluateStoredEntry=(t,n,r)=>{const i=openAIModelCatalogRoutePolicy.resolveIdentity(t);const a=listModelCatalogObservedRoutes(n??[t]);const s=JSON.stringify([o(t),r,t.api,t.baseUrl,a]);const c=isPluginAuthProvider(t.provider);const l=normalizeProviderId(t.provider);const d=c?void 0:O.get(l)?.get(s);if(d)return d;const f=u.get(normalizeProviderId(t.provider));const p=isSelectedProvider(t.provider);const m=(p?k:void 0)??f;const h=pinnedProfileForEntry(t);const _=r??(p&&g?e.runtimeOverride:void 0);const y={...D.evaluateRuntimeModelAuth(t.provider,{modelId:i?.id??t.id,runtimeId:_,...l===`openai`?{}:{api:t.api,baseUrl:t.baseUrl},...m?{preferredProfileId:m}:{},...h?{pinnedProfileId:h}:{},observedRoutes:a}),..._?{requestedRuntimeId:_}:{}};const b=!_&&y.availability===true&&y.evidence===`runtime`&&j(l,i?.id??t.id)?{...y,availability:false}:y;const x=v.some(e=>e.status===`auth-rejected`&&e.rejectionScope!==`catalog`&&normalizeProviderId(e.provider)===l&&(e.profileId===void 0||e.profileId===y.selectedProfileId))?{...y,availability:false,unavailableReason:`auth-failed`,unavailableUntil:void 0}:b;if(!c){const e=O.get(l)??/* @__PURE__ */ new Map;e.set(s,x);O.set(l,e)}return x};const M=e.preferredProfileId&&isUserModelAuthProfileId(e.preferredProfileId)&&!l.profiles[e.preferredProfileId]?(t,n,r)=>g&&normalizeProviderId(g)!==normalizeProviderId(t.provider)?evaluateStoredEntry(t,n,r):{availability:false,unavailableReason:`missing-auth`,selectedProfileId:e.preferredProfileId,routeResolution:null}:evaluateStoredEntry;const N=[];const isCurrent=()=>Date.now()<S&&(!w||getActiveSecretsRuntimeSnapshotRevisionState()===C)&&f?.isCurrent()!==false&&(e.isCurrent?.()??e.observationConfig===void 0)&&N.every(e=>e());const prepareSelectedAccountCatalog=async(t,o)=>{const s=e.accountCatalog;if(!s)return;const c={assertCurrent:t,withCurrent:o.withCurrent};const d=new Map([...u].map(([e,t])=>[t,e]));if(h&&g)d.set(h,normalizeProviderId(g));if(r&&pinnedProfileForEntry(a)===r)d.set(r,normalizeProviderId(i.provider));for(const[r,i]of d){const a=await withCurrentReadAuthority(c,()=>l.profiles[r]);if(!a)continue;const u={profileId:r,credential:a,...o,allowDiscovery:o.refresh===true,load:async()=>{t();const a=e.pluginRegistry?.providers.find(({provider:e})=>normalizeProviderId(e.id)===i)?.provider;if(!a?.catalog)return[];const{loadSelectedProviderAccountCatalog:s}=await import(`./models-config.providers.catalog-context-BB6P9hl8.mjs`);t();const u={provider:a,providerId:i,profileId:r,authStore:l,refresh:o.refresh,config:e.cfg,agentDir:e.agentDir??resolveAgentDir(e.cfg,e.agentId),workspaceDir:n,isCurrent,assertCurrent:t,withCurrent:o.withCurrent,beforeRequest:o.beforeRequest};return withCurrentReadAuthority(c,()=>s(u))}};const d=await withCurrentReadAuthority(c,()=>s.acquire(u));await withCurrentReadAuthority(c,()=>{N.push(d.isCurrent);if(!d.hasPublishedCatalog||!_.replace(i,r,d.outcomes))return;for(const e of O.keys())if(e===i||normalizeAuthProvider(e)===i)O.delete(e);P=void 0})}};let P;return{preparedPersonalCatalog:f,projectCatalog:t=>withCurrentReadAuthority(t,()=>{if(P)return P;const n=createModelCatalogSnapshotView(e.cfg,m);const r=n.logicalEntries.map(t=>{const r=n.variantsOf(t)??[t];const i=M(t,r);const a=evaluateNative(t,i);const o=resolveCatalogDecisionRuntime({cfg:e.cfg,agentId:e.agentId,entry:t,evaluation:a,pluginRegistry:e.pluginRegistry,resolveOpenAIProviderRoutes:b})?.id??`openclaw`;const s=selectModelCatalogRuntimeEntry({entry:t,routeVariants:r,runtimeId:o});return n.project(s.entry,a,s.variants).runtimeEntry});if(!t)P=r;return r}),accountCatalog:e.accountCatalog,prepareSelectedAccountCatalog,hasPinnedAccount:e=>pinnedProfileForEntry(e)!==void 0,evaluateEntry:M,evaluateNative,resolveOpenAIProviderRoutes:b,snapshot:m,metadataSnapshot:t,authStore:l,authModes:e.preparedRuntimeAuthModes,runtimeChoices(r,i=[r]){const a=M(r,i);const o=resolveCatalogDecisionRuntime({cfg:e.cfg,agentId:e.agentId,entry:r,evaluation:a,pluginRegistry:e.pluginRegistry,resolveOpenAIProviderRoutes:b});const s=/* @__PURE__ */ new Set([o?.id??`openclaw`,`openclaw`,...e.pluginRegistry?.agentHarnesses.map(({harness:e})=>e.id)??[],...i.flatMap(e=>e.nativeRuntime?[e.nativeRuntime]:[]),...a.routeResolution?.kind===`routes`?a.routeResolution.routes.flatMap(e=>e.runtimePolicy?.compatibleIds??[]):[],...c.filter(e=>normalizeProviderId(e.provider)===normalizeProviderId(r.provider)).map(e=>e.runtime)]);const l=[];let u=false;for(const a of s){const o=M(r,i,a);const s=evaluateNative(r,o,a);if(s.availability===void 0)u=true;if(s.availability!==true)continue;const d=s.selectedRoute;const f=resolveAgentHarnessPolicy({config:e.cfg,agentId:e.agentId,provider:r.provider,modelId:r.id,modelApi:d?.api??r.api,modelBaseUrl:d?.baseUrl??r.baseUrl,requestTransportOverrides:d?.requestTransportOverrides,resolveOpenAIProviderRoutes:b});if(f.forcedByEnvironment&&f.runtime!==a)continue;const p=s.selectedRoute?.runtimePolicy?.compatibleIds;if(p&&!p.includes(a))continue;if(s.runtimeAuth&&s.runtimeAuth.id!==a)continue;if(a!==`openclaw`&&!c.some(e=>e.runtime===a&&normalizeProviderId(e.provider)===normalizeProviderId(r.provider))){const i=e.pluginRegistry?.agentHarnesses.find(e=>e.harness.id===a)?.harness;if(!i){u||=e.pluginRegistry===void 0;continue}if(!i.supports(buildAgentHarnessSupportContext({config:e.cfg,agentId:e.agentId,provider:r.provider,modelId:r.id,requestedRuntime:a,contextManagement:i.contextManagement,providerOwnership:resolveProviderRefOwnership({provider:r.provider,config:e.cfg,workspaceDir:n,metadataSnapshot:t}),modelProvider:{api:d?.api??r.api,baseUrl:d?.baseUrl??r.baseUrl,runtimePolicy:d?.runtimePolicy,requestTransportOverrides:d?.requestTransportOverrides,preparedAuth:s.selectedCredential}})).supported)continue}l.push(a)}return l.length===0&&u?void 0:l},authMaterializations:e.preparedRuntimeAuthMaterializations,cliRuntimeBindings:c,pluginRegistry:e.pluginRegistry,isCurrent,assertCurrent:()=>{if(!isCurrent())throw new PreparedModelRuntimePublicationSupersededError(`Model catalog changed while selecting runtimes`)},observationConfig:e.observationConfig}}export{prepareModelCatalogDecisions as n,createModelCatalogDecisions as t};