UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

7 lines • 18.5 kB
import{o as asDateTimestampMs}from"./number-coercion-B3CfI447.mjs";import{g as normalizeUniqueStringEntries}from"./string-normalization-D_oBUpO3.mjs";import{o as hasConfiguredSecretInput}from"./types.secrets-UWdyCdE6.mjs";import{r as normalizeProviderId,t as findNormalizedProviderKey}from"./provider-id-A-8WTtLA.mjs";import{O as tryResolveAmbientOwnerAgentId}from"./agent-scope-config-CG9CFpGX.mjs";import{t as createSubsystemLogger}from"./subsystem-DLCDFvCH.mjs";import{t as getOrCreateWeakOwnerMap}from"./weak-owner-map-B5mTikxj.mjs";import{Jc as validateModelsAuthRefreshParams,Yc as validateModelsAuthSetApiKeyParams}from"./src-BDZMFmKa.mjs";import{i as resolveProviderIdForAuth}from"./provider-auth-aliases-BRA1A5Vm.mjs";import{s as resolveProviderAuthLookupMaps}from"./provider-env-vars-CSXML2JF.mjs";import{f as hasGatewayAdminScope}from"./operator-scopes-bEvB7E5X.mjs";import{t as DEFAULT_OAUTH_REFRESH_MARGIN_MS}from"./credential-state-C3XZhGc-.mjs";import{m as getRuntimeAuthProfileStoreSnapshotsRevision,r as clearRuntimeAuthProfileStoreSnapshots,w as refreshRuntimeAuthProfileStoreSources}from"./runtime-snapshots-DYK7vyJv.mjs";import{i as ErrorCodes}from"./missing-scope-error-CkgBgh6d.mjs";import{t as NON_ENV_SECRETREF_MARKER}from"./provider-credential-values-BjeBUyPy.mjs";import{c as isKnownEnvApiKeyMarker,l as isNonSecretApiKeyMarker}from"./model-auth-markers-Dc97K3d8.mjs";import{c as resolveUsageProviderId,o as providerUsageLabel}from"./provider-usage.shared-CF-EgkxA.mjs";import{b as resolveUsableCustomProviderApiKey,g as resolveProviderConfigSecretInput,v as resolveProviderEntryApiKeyProfileReference}from"./model-auth-provider-config-KlOdxZHz.mjs";import{t as isExternalCliAuthProfileInScope}from"./external-cli-sync-C2s6hWdT.mjs";import{f as listProfilesForProvider,m as resolveExplicitAuthOrderSelection}from"./order-B8e_5ABM.mjs";import{t as externalCliDiscoveryForConfigStatus}from"./external-cli-discovery-CHmIqgrd.mjs";import{i as listProviderEnvAuthLookupKeys,r as resolveProviderEnvAuthEvidence}from"./model-auth-env-B6Hhnpzd.mjs";import{c as ensureAuthProfileStoreWithoutExternalProfilesAsync}from"./store-runtime-GNz-2GjY.mjs";import{n as resolveAuthProfileMetadata}from"./identity-Bk38qfq2.mjs";import{n as buildAuthHealthSummary,r as formatRemainingShort,t as DEFAULT_OAUTH_WARN_MS}from"./auth-health-DIboE8Qn.mjs";import{n as readPreparedCatalog,t as loadDeferredCatalog}from"./server-model-catalog-auth-DgYxoyva.mjs";import{t as formatForLog}from"./ws-log-DRCSDKLv.mjs";import{r as respondUnavailableOnThrow,t as respondError}from"./response-BYbuAh7a.mjs";import{n as defineValidatedGatewayHandler,t as assertValidParams}from"./validation-CM41YclJ.mjs";import{a as readGatewayRequestMutationAuthority}from"./session-mutation-guards-Bqnc5JYL.mjs";import"./auth-profiles-nMUErGRQ.mjs";import"./model-auth-C99Q9Dp8.mjs";import{n as localStateOwnerChangedError,t as captureLocalStateMutationGuard}from"./local-state-owner-DweIAMz2.mjs";import{n as abortChatRunsForProvider}from"./chat-abort-DTWUmwzL.mjs";import{n as createChatAbortOps}from"./chat-abort-ops-BUCPKCsd.mjs";import{s as refreshActiveProviderAuthRuntimeSnapshot}from"./runtime-_5KWLVzx.mjs";import{t as resolveModelAuthAgentScope}from"./model-auth-agent-scope-dS6ga2Rp.mjs";import{i as getProviderUsageRuntimeSnapshot,r as readProviderUsage}from"./models-auth-status-usage-cache-SINdS-I_.mjs";import{t as refreshModelAuthStateAfterMutation}from"./model-auth-refresh-DuOWCz8I.mjs";import{t as resolveConfigBoundProfileIds}from"./models-auth-status-config-8ZIDvApC.mjs";import{t as resolveModelProviderCapabilities}from"./model-provider-capabilities-D9B2E7Cu.mjs"; //!src/gateway/server-methods/models-auth-refresh.ts const modelsAuthRefreshHandlers={"models.authRefresh":defineValidatedGatewayHandler(`models.authRefresh`,validateModelsAuthRefreshParams,async({params:e,respond:t,context:n})=>{const r=n.getRuntimeConfig();const i=resolveModelAuthAgentScope(r,e.agentId===void 0||e.agentId===``?tryResolveAmbientOwnerAgentId(r):e.agentId);if(!i.ok){t(false,void 0,i.error);return}await respondUnavailableOnThrow(t,async()=>{clearRuntimeAuthProfileStoreSnapshots();await refreshModelAuthStateAfterMutation(n.getRuntimeConfig,i.agentId);t(true,{refreshed:true},void 0)})})}; //!src/gateway/server-methods/models-auth-status-facts.ts const apiKeyUsageStatusProviders=/* @__PURE__ */ new Set([`clawrouter`,`deepseek`]);const authStatusFacts=/* @__PURE__ */ new WeakMap;function resolveEnvVarName(e){return/^(?:shell env|env): ([A-Z][A-Z0-9_]*)$/u.exec(e)?.[1]}function buildModelAuthStatusFacts(e,t){const{config:n,authStore:r,workspaceDir:i}=e;const a={config:n,workspaceDir:i,metadataSnapshot:e.metadataSnapshot,includeUntrustedWorkspacePlugins:false};const o=resolveProviderAuthLookupMaps({...a,config:n,env:process.env});const s=/* @__PURE__ */ new Set([...Object.keys(n.models?.providers??{}),...Object.values(n.auth?.profiles??{}).map(e=>e?.provider).filter(e=>typeof e===`string`),...listProviderEnvAuthLookupKeys(o)]);const c=/* @__PURE__ */ new Map;for(const e of s){const t=normalizeProviderId(e);if(!t)continue;const{providerConfig:i,ref:s}=resolveProviderConfigSecretInput(n,t);if(hasConfiguredSecretInput(i?.apiKey,n.secrets?.defaults)){const e=resolveProviderEntryApiKeyProfileReference({cfg:n,authAliasLookupParams:a,provider:t,store:r});if(e.kind!==`profile`&&e.kind!==`profile-incompatible`){if(s&&s.source!==`env`){c.set(t,{source:`config`});continue}const r=resolveUsableCustomProviderApiKey({cfg:n,provider:t,env:process.env});if(r){const n=typeof i?.apiKey===`string`?i.apiKey.trim():``;if(n&&isNonSecretApiKeyMarker(n,{includeEnvVarName:false}))continue;const a=s?.source===`env`?s.id:e.kind===`marker`&&isKnownEnvApiKeyMarker(n)?n:resolveEnvVarName(r.source);c.set(t,a?{source:`env`,envVar:a}:{source:`config`});continue}}}const l=resolveProviderEnvAuthEvidence(t,process.env,{aliasMap:o.aliasMap,candidateMap:o.envCandidateMap,authEvidenceMap:o.authEvidenceMap});if(l?.mode===`api-key`){const e=resolveEnvVarName(l.source);c.set(t,{source:`env`,...e?{envVar:e}:{}})}}const l=/* @__PURE__ */ new Set;const u=/* @__PURE__ */ new Set;const includeConfiguredAuthProvider=(e,t)=>{if(c.has(e))return;l.add(e);if(t===`oauth`)u.add(e)};for(const[e,t]of Object.entries(n.models?.providers??{})){const r=normalizeProviderId(e);if(!r)continue;const i=typeof t?.apiKey===`string`?t.apiKey.trim():``;const a=hasConfiguredSecretInput(t?.apiKey,n.secrets?.defaults)&&(i===`secretref-managed`||!isNonSecretApiKeyMarker(i,{includeEnvVarName:false}));const o=t?.auth;if(o!==`oauth`&&o!==`token`&&!a)continue;includeConfiguredAuthProvider(r,o)}for(const e of Object.values(n.auth?.profiles??{})){const t=e?.provider;const n=e?.mode;if(typeof t!==`string`||t.length===0||n!==`oauth`&&n!==`token`)continue;const r=normalizeProviderId(t);if(!r)continue;includeConfiguredAuthProvider(r,n)}for(const e of c.keys())l.add(e);for(const e of Object.values(r.profiles)){const t=normalizeProviderId(e.provider);if(t)l.add(t)}const readAuthHealth=()=>buildAuthHealthSummary({store:r,cfg:n,providers:l.size>0?[...l]:void 0,authAliasLookupParams:a});const d=readAuthHealth();const f=d.profiles.some(e=>e.type===`oauth`&&isExternalCliAuthProfileInScope({store:r,profileId:e.profileId}));const p=[...new Set(d.profiles.flatMap(e=>{const t=resolveUsageProviderId(e.provider,{credentialType:e.type});return t&&(e.type===`oauth`||e.type===`token`||apiKeyUsageStatusProviders.has(t))?[t]:[]}))];const m=new Set(r.runtimeExternalProfileIds??[]);const h=new Set(Object.entries(r.profiles).filter(([e,t])=>!m.has(e)&&(t.type!==`api_key`||!t.keyRef)).map(([e])=>e));const g=resolveConfigBoundProfileIds(n,r,a);const _=new Set(Object.entries(r.profiles).filter(([e])=>g.has(e)).map(([,e])=>resolveProviderIdForAuth(e.provider,{...a,storedCredential:true})));const v=resolveModelProviderCapabilities({config:n,workspaceDir:i,metadataSnapshot:e.metadataSnapshot}).capabilities;let y=Infinity;for(const e of d.profiles){if(e.expiresAt===void 0)continue;for(const n of[DEFAULT_OAUTH_WARN_MS,DEFAULT_OAUTH_REFRESH_MARGIN_MS,0]){const r=e.expiresAt-n;if(r>t)y=Math.min(y,r)}}return{authAliasLookupParams:a,apiKeys:c,expectsOAuth:u,authHealth:d,readAuthHealth:f?readAuthHealth:void 0,usageProviderIds:p,externalProfileIds:m,logoutProfileIds:h,configBoundProfileIds:g,configBoundAuthProviders:_,providerCapabilities:v,refreshAt:y}}function readModelAuthStatusFacts(e,t,n){const r=getOrCreateWeakOwnerMap(authStatusFacts,e.isCurrent);const i=getRuntimeAuthProfileStoreSnapshotsRevision();const a=r.get(e.agentId);if(!t&&a&&a.revision===i&&a.profiles===e.authStore.profiles&&a.config===e.config&&a.metadata===e.metadataSnapshot&&a.agentDir===e.agentDir&&a.workspaceDir===e.workspaceDir&&n<a.facts.refreshAt)return a.facts.readAuthHealth?{...a.facts,authHealth:a.facts.readAuthHealth()}:a.facts;const o=buildModelAuthStatusFacts(e,n);r.set(e.agentId,{profiles:e.authStore.profiles,config:e.config,metadata:e.metadataSnapshot,agentDir:e.agentDir,workspaceDir:e.workspaceDir,revision:i,facts:o});return o} //!src/gateway/server-methods/models-auth-status.ts const log=createSubsystemLogger(`models-auth-status`);function resolveAuthRefreshScope(e){const t=externalCliDiscoveryForConfigStatus({cfg:e});if(t.mode!==`scoped`)return{providerIds:[]};const n=[...t.providerIds??[]];const r=[...t.profileIds??[]];return{providerIds:n,...r.length>0?{profileIds:r}:{}}}function readProviderParam(e){const t=e.provider;if(typeof t!==`string`)return null;return normalizeProviderId(t)||null}function readLogoutProfileSelection(e){if(!(`profileIds`in e))return{ok:true};if(!Array.isArray(e.profileIds)||e.profileIds.length===0)return{ok:false,message:`profileIds must be a non-empty string array`};for(const t of e.profileIds)if(typeof t!==`string`||!t.trim())return{ok:false,message:`profileIds must be a non-empty string array`};return{ok:true,profileIds:normalizeUniqueStringEntries(e.profileIds)}}function buildExpiry(e,t){const n=asDateTimestampMs(t);if(n===void 0||typeof e!==`number`)return;return{at:n,remainingMs:e,label:formatRemainingShort(e)}}function providerDisplayName(e){const t=resolveUsageProviderId(e);return t&&providerUsageLabel(t)||e}function aggregateProfileStatus(e,t){const n=new Set(e.map(e=>e.status));const r=[`expired`,`missing`,`expiring`,`ok`,`static`].find(e=>n.has(e));const i=e.map(e=>e.expiresAt).filter(e=>asDateTimestampMs(e)!==void 0);const a=i.length>0?Math.min(...i):void 0;const o=a!==void 0?a-t:void 0;return{status:r??`static`,expiresAt:a,remainingMs:o}}function aggregateRefreshableAuthStatus(e,t=Date.now(),n=false){const r=e.effectiveProfiles??e.profiles;for(const e of[`oauth`,`token`]){const n=r.filter(t=>t.type===e);if(n.length>0)return aggregateProfileStatus(n,t)}if(n)return{status:`missing`};return{status:e.status,expiresAt:e.expiresAt,remainingMs:e.remainingMs}}async function refreshAfterCredentialMutation(e,t){try{await refreshModelAuthStateAfterMutation(e.getRuntimeConfig,t);return}catch(e){log.warn(`credential change saved but auth refresh failed: ${formatForLog(e)}`);return"Model auth changes were saved, but the Gateway could not refresh them. Run `openclaw gateway restart` to apply the saved changes."}}const modelsAuthStatusHandlers={...modelsAuthRefreshHandlers,"models.authSetApiKey":async e=>{const{params:t,respond:n,context:r,client:i}=e;const a=t.expectedOwnerId;if(!assertValidParams(t,validateModelsAuthSetApiKeyParams,`models.authSetApiKey`,n))return;const o=readGatewayRequestMutationAuthority(e);let assertCurrent=o.assertCurrent;if(a!==void 0){if(typeof a!==`string`||!a.trim()){respondError(n,ErrorCodes.INVALID_REQUEST,`expectedOwnerId must be a non-empty string`);return}if(!hasGatewayAdminScope(i)){respondError(n,ErrorCodes.FORBIDDEN,`missing scope: operator.admin`);return}try{const t=captureLocalStateMutationGuard(a,e);assertCurrent=()=>{o.assertCurrent();t()}}catch(e){n(false,void 0,localStateOwnerChangedError(e));return}}const s=normalizeProviderId(t.provider);await respondUnavailableOnThrow(n,async()=>{const e=r.getRuntimeConfig();const i=a!==void 0?{ok:true,...(await import(`./shared-C5fQ2fJB.mjs`)).resolveModelsTargetAgent(e,t.agentId,{kind:`mutation`})}:resolveModelAuthAgentScope(e,t.agentId);if(!i.ok){n(false,void 0,i.error);return}const{saveModelProviderApiKey:o}=await import(`./auth-api-key-WmjHvHPD.mjs`);const{profileId:c,warning:l,modelAccess:u}=await o({config:e,provider:s,apiKey:t.apiKey,agentId:i.agentId,agentDir:i.agentDir,assertCurrent});if(u)log.info(u);const d=[l,await refreshAfterCredentialMutation(r,i.agentId)].filter(Boolean).join(` `);const f={provider:s,profileId:c,...d?{warning:d}:{}};n(true,f,void 0)})},"models.authLogout":async({params:e,respond:t,context:n})=>{const r=readProviderParam(e);if(!r){respondError(t,ErrorCodes.INVALID_REQUEST,`provider is required`);return}const i=readLogoutProfileSelection(e);if(!i.ok){respondError(t,ErrorCodes.INVALID_REQUEST,i.message);return}if(e.credentialType!==void 0&&e.credentialType!==`api_key`||e.credentialType!==void 0&&i.profileIds!==void 0){respondError(t,ErrorCodes.INVALID_REQUEST,`Choose either API keys or specific profiles`);return}const a=e.credentialType===`api_key`;await respondUnavailableOnThrow(t,async()=>{const o=n.getRuntimeConfig();const s=resolveModelAuthAgentScope(o,e.agentId);if(!s.ok){t(false,void 0,s.error);return}const{agentDir:c}=s;const l=resolveProviderIdForAuth(r,{config:o});const u=await ensureAuthProfileStoreWithoutExternalProfilesAsync(c);const d=listProfilesForProvider(u,r);const f=i.profileIds??d.filter(e=>{const t=u.profiles[e];return!a||t?.type===`api_key`&&!t.keyRef});if(i.profileIds&&i.profileIds.some(e=>!d.includes(e))){respondError(t,ErrorCodes.INVALID_REQUEST,`profileIds contain unavailable auth profiles`);return}const{removeModelAuthCredentials:p}=await import(`./auth-logout-DD_WyzDu.mjs`);const m=await p({cfg:o,agentDir:c,profileIds:f,...a?{apiKeyProvider:r}:{},...!a&&!i.profileIds?{provider:r}:{}});const{runIds:h}=i.profileIds||a?{runIds:[]}:abortChatRunsForProvider(createChatAbortOps(n),{cfg:o,providerId:l,agentId:s.agentId});const g=[m,await refreshAfterCredentialMutation(n,s.agentId)].filter(Boolean).join(` `);t(true,{provider:r,removedProfiles:f,abortedRunIds:h,...g?{warning:g}:{}},void 0)})},"models.authStatus":async({params:e,respond:t,context:n,client:r})=>{const i=Date.now();const a=Boolean(e.refresh);const o=hasGatewayAdminScope(r);const resolveScope=t=>resolveModelAuthAgentScope(t,e.agentId===void 0||e.agentId===``?tryResolveAmbientOwnerAgentId(t):e.agentId);await respondUnavailableOnThrow(t,async()=>{let r=n.getRuntimeConfig();let s=resolveScope(r);if(!s.ok){t(false,void 0,s.error);return}if(a){await refreshRuntimeAuthProfileStoreSources();await refreshActiveProviderAuthRuntimeSnapshot();r=n.getRuntimeConfig();s=resolveScope(r);if(!s.ok){t(false,void 0,s.error);return}}const c=a?await loadDeferredCatalog(n,s.agentId,{readOnly:true,authScope:resolveAuthRefreshScope(r),refreshAuth:true,refreshFullCatalog:false}):await readPreparedCatalog(n,s.agentId);if(!c){t(true,{ts:i,providers:[],unavailable:{code:`PREPARED_MODEL_AUTH_UNAVAILABLE`,message:`Model authentication status is unavailable. Refresh Models after setup finishes; restart the Gateway if it persists.`}},void 0);return}r=c.config;const{agentId:l,agentDir:u}=c;const d=c.authStore;const{authAliasLookupParams:f,apiKeys:p,expectsOAuth:m,authHealth:h,usageProviderIds:g,externalProfileIds:_,logoutProfileIds:v,configBoundProfileIds:y,configBoundAuthProviders:b,providerCapabilities:x}=readModelAuthStatusFacts(c,a,i);const S=await getProviderUsageRuntimeSnapshot({config:r,agentId:l,agentDir:u,store:d});const C={agentId:l,agentDir:u,authStore:S.store,configRef:r,credentialKey:S.credentialKey,forceRefresh:a,providerIds:g,now:i};const{usageByProvider:w,refreshAt:T}=await readProviderUsage({...C,awaitRefresh:Boolean(e.refreshUsage)});const E=[];for(const e of h.providers){const t=normalizeProviderId(e.provider);const n=resolveProviderIdForAuth(e.provider,f);const i=resolveExplicitAuthOrderSelection({storeOrder:d.order,configuredOrder:r.auth?.order,providerKey:t,providerAuthKey:n});const a=findNormalizedProviderKey(d.order,n)??findNormalizedProviderKey(d.order,t);const s=a!==void 0&&d.runtimeLocalOrderProviderIds?.includes(a);const c=new Set(d.runtimeLocalProfileIds??Object.keys(d.profiles).filter(e=>!_.has(e)));const l=b.has(n);const u=i.order!==void 0&&!i.fromStore;const h=e.profiles.find(e=>e.type===`oauth`||e.type===`token`)??e.profiles.find(e=>e.type===`api_key`);const g=resolveUsageProviderId(e.provider,{credentialType:h?.type});const x=g?w.get(g):void 0;const S=aggregateRefreshableAuthStatus(e,Date.now(),m.has(e.provider));const C=p.get(normalizeProviderId(e.provider));const T=e.profiles.some(e=>e.type===`oauth`||e.type===`token`);E.push({provider:e.provider,authProvider:n,displayName:providerDisplayName(e.provider),status:C&&!T&&S.status===`missing`?`static`:S.status,expiry:buildExpiry(S.remainingMs,S.expiresAt),profiles:e.profiles.map(e=>{const t=resolveAuthProfileMetadata({cfg:r,store:d,profileId:e.profileId});const n=d.usageStats?.[e.profileId]?.lastUsed;const i={profileId:e.profileId,type:e.type,status:e.status,reasonCode:e.reasonCode,source:y.has(e.profileId)?`config`:_.has(e.profileId)?`external`:c.has(e.profileId)?`saved`:`inherited`,expiry:buildExpiry(e.expiresAt===void 0?e.remainingMs:e.expiresAt-Date.now(),e.expiresAt)};if(o&&t.displayName)i.displayName=t.displayName;if(e.reasonCode===`setup_inactive`)i.displayName=`Saved sign-in (inactive)`;if(o&&t.email)i.email=t.email;if(o&&n)i.lastUsedAt=n;if(v.has(e.profileId))i.logoutSupported=true;return i}),...i.order!==void 0?{profileOrder:i.order}:{},...i.fromStore&&s?{profileOrderStored:true}:{},...l?{profileOrderLocked:`provider-config`}:u?{profileOrderLocked:`auth-config`}:{},...C?{apiKey:C}:{},usage:x&&g?{providerId:g,windows:x.windows,...x.summary?{summary:x.summary}:{},...x.plan?{plan:x.plan}:{},...x.billing?.length?{billing:x.billing}:{},...o&&x.authProfileId?{authProfileId:x.authProfileId}:{},...o&&x.accountEmail?{accountEmail:x.accountEmail}:{}}:void 0})}for(const[e,t]of Object.entries(c.authModes)){if(typeof t!==`object`||!t.display)continue;const n=E.find(t=>t.provider===e);if(n)n.nativeAuth=t.display;else E.push({provider:e,displayName:providerDisplayName(e),status:`ok`,profiles:[],nativeAuth:t.display})}t(true,{ts:i,providers:E,providerCapabilities:x,usageRefreshAt:T},void 0)})}};export{modelsAuthStatusHandlers};