openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
5 lines • 9.51 kB
JavaScript
import{t as resolvePathViaExistingAncestorSync}from"./boundary-path-BeuXNL_4.mjs";import{o as registerSecretValueForRedaction}from"./secret-redaction-registry-DospXE4m.mjs";import"./model-ref-shared-T-aCqInj.mjs";import{r as normalizeProviderId,t as findNormalizedProviderKey}from"./provider-id-A-8WTtLA.mjs";import{i as materializeModelPolicyAllowlist}from"./model-policy-allowlist-migration-BI8Uf3RI.mjs";import{y as resolveMutableAgentEntry}from"./agent-scope-config-CG9CFpGX.mjs";import{n as normalizeSecretInput}from"./normalize-secret-input-CEFJUjQX.mjs";import{t as AuthProfileCredentialPublicationPendingError}from"./user-model-account-authority-B8H7rvCb.mjs";import{t as isUserModelAuthProfileId}from"./user-model-account-id-CU4k7NMV.mjs";import{i as DEFAULT_PROVIDER}from"./defaults-k51tX6yK.mjs";import{m as resolveConfiguredModelPolicyAllow,t as LEGACY_MODEL_POLICY_ALLOW_CONFIG_PATH}from"./model-selection-shared-CIOFxJ36.mjs";import{S as attachRuntimeConfigWriteApplication,w as createRuntimeConfigWriteApplication}from"./io.runtime-BvSeVFIY.mjs";import{a as captureGatewayRootWorkAdmissionContinuationScope}from"./gateway-work-admission-CnMW3_qr.mjs";import{d as resolveSharedAuthStorePath}from"./path-resolve-TSS6dv07.mjs";import{n as createModelVisibilityPolicy}from"./model-visibility-policy-Bd5YBCCk.mjs";import{g as resolveProviderConfigSecretInput,v as resolveProviderEntryApiKeyProfileReference}from"./model-auth-provider-config-KlOdxZHz.mjs";import{a as resolveAuthProfileOrder}from"./order-B8e_5ABM.mjs";import{c as ensureAuthProfileStoreWithoutExternalProfilesAsync,y as resolvePersistedAuthProfileOwnerAgentDirAsync}from"./store-runtime-GNz-2GjY.mjs";import{d as upsertAuthProfileWithLockOrThrow,v as listCandidateAuthProfileStores,y as prepareCandidateAuthProfileCredentialRead}from"./profiles-Bp0-JifZ.mjs";import{r as logConfigUpdated}from"./logging-C183DMvG.mjs";import{t as ProviderAuthConfigApplyError}from"./provider-auth-result-BBq2IiCp.mjs";import"./auth-profiles-nMUErGRQ.mjs";import{t as applyPrimaryModel}from"./provider-model-primary-10d4qbG3.mjs";import{t as applyAuthProfileConfig}from"./provider-auth-helpers-5o5rkp5c.mjs";import{i as loadValidConfigSnapshotOrThrow,l as resolveModelsTargetAgent,u as updateConfig}from"./shared-Sc7lnGKV.mjs";import{i as resolveDefaultTokenProfileId,n as normalizeManualAuthProvider,o as validateOpenAICodexApiKeyInput}from"./auth-manual-input-Cy929dbG.mjs";import{isDeepStrictEqual}from"node:util";
//!src/commands/models/auth-model-policy.ts
function applyProviderLoginDefaultModel(e,t){const n=applyPrimaryModel(e,t);if(resolveConfiguredModelPolicyAllow({cfg:e}).configPath===`agents.defaults.models`){n.agents??={};n.agents.defaults??={};n.agents.defaults.models=e.agents?.defaults?.models}return n}function withoutProviderModelPolicy(e,t){const n=structuredClone(e);if(n.agents?.defaults){delete n.agents.defaults.modelPolicy;if(resolveConfiguredModelPolicyAllow({cfg:t}).configPath===`agents.defaults.models`)delete n.agents.defaults.models}for(const e of Object.values(n.agents?.entries??{}))delete e.modelPolicy;return n}function policyNamesProvider(e,t,n){const{allowedKeys:r}=createModelVisibilityPolicy({cfg:e,catalog:[],defaultProvider:DEFAULT_PROVIDER,agentId:t});return[...r].some(e=>normalizeProviderId(e.split(`/`)[0]??``)===n)}function allowProviderModelsInConfig(e,t,n){const r=normalizeProviderId(n);const i=`${r}/*`;const a=resolveConfiguredModelPolicyAllow({cfg:e,agentId:t});if(a.refs.length===0||policyNamesProvider(e,t,r))return;const o=[...a.refs,i];if(a.repairConfigPath===`agents.entries.*.modelPolicy.allow`){const n=resolveMutableAgentEntry(e,t);if(!n)throw new Error(`Agent "${t}" no longer exists.`);n.modelPolicy={...n.modelPolicy,allow:o}}else{e.agents??={};e.agents.defaults??={};const t=e.agents.defaults;if(a.configPath===`agents.defaults.models`&&materializeModelPolicyAllowlist(e).kind===`deferred`)t.models={...t.models,[i]:{}};else t.modelPolicy={...t.modelPolicy,allow:o}}return`Added ${i} to allowed models.`}async function allowProviderModels(e){if(!allowProviderModelsInConfig(structuredClone(e.config),e.agentId,e.provider))return;const t=createRuntimeConfigWriteApplication(captureGatewayRootWorkAdmissionContinuationScope()?.run);let n;await updateConfig(t=>{e.assertCurrent?.(t);resolveModelsTargetAgent(t,e.agentId,{kind:`mutation`});n=allowProviderModelsInConfig(t,e.agentId,e.provider);return t},void 0,void 0,attachRuntimeConfigWriteApplication({assertCurrent:e.assertCurrent},t));if(!n)return;const r=t.claimed&&await t.result===`applied`;const i=r?n:`${n} OpenClaw has not confirmed it is active. Open Settings and select Apply changes, then send /models.`;logConfigUpdated(e.runtime);e.runtime.log(i);return{message:i,applied:r}}function allowLoginProviderModels(e,t,n){return allowProviderModels({config:e.config,agentId:t,provider:n,runtime:e.runtime,assertCurrent:()=>{e.signal?.throwIfAborted();e.assertCurrent?.()}}).catch(e=>{throw new ProviderAuthConfigApplyError(e)})}
//!src/commands/models/auth-api-key.ts
async function saveModelProviderApiKey(e){const t=normalizeManualAuthProvider(e.provider);const n=normalizeSecretInput(e.apiKey);registerSecretValueForRedaction(n);const r=!n?`API key is required`:t===`openai`?validateOpenAICodexApiKeyInput(n):void 0;if(r)throw new Error(r);const i=e.config??(await loadValidConfigSnapshotOrThrow()).runtimeConfig;const validateCurrentCredential=e=>{if(e?.type===`api_key`&&e.keyRef)throw new Error(`This API-key profile uses an external secret reference. Remove that saved sign-in before storing an inline key.`);if(e&&(e.type!==`api_key`||normalizeProviderId(e.provider)!==t))throw new Error(`The API-key profile belongs to another sign-in. Manage that saved sign-in first.`)};const configuredKey=e=>{const n=findNormalizedProviderKey(e.models?.providers,t);const r=n?e.models?.providers?.[n]:void 0;if(r?.auth&&r.auth!==`api-key`)throw new Error(`This connection uses another sign-in method. Use its sign-in option instead.`);return n};const configuredBinding=(e,t)=>{const{providerConfig:n,ref:r}=resolveProviderConfigSecretInput(e,t);return r??n?.apiKey};const a=e.profileId?void 0:configuredKey(i);const o=a===void 0?void 0:configuredBinding(i,a);const s=await ensureAuthProfileStoreWithoutExternalProfilesAsync(e.agentDir);const c=!a?resolveAuthProfileOrder({cfg:i,store:s,provider:t}).find(e=>{const t=s.profiles[e];return t?.type===`api_key`&&!t.keyRef}):void 0;const l=a?resolveProviderEntryApiKeyProfileReference({cfg:i,provider:a,store:s}):void 0;const u=l?.kind===`profile`||l?.kind===`profile-incompatible`?l.profileId:void 0;const d=e.profileId??u??c??resolveDefaultTokenProfileId(t);if(isUserModelAuthProfileId(d))throw new Error(`Personal model accounts are managed in Settings → Profile → Connected accounts.`);const f=a?void 0:s.profiles[d]?await resolvePersistedAuthProfileOwnerAgentDirAsync({agentDir:e.agentDir,profileId:d}):e.agentDir;const p=a?(await listCandidateAuthProfileStores({cfg:i})).filter(e=>e.databasePath!==resolvePathViaExistingAncestorSync(resolveSharedAuthStorePath())):[];const m=await Promise.all(p.map(e=>prepareCandidateAuthProfileCredentialRead(e,d)));const validateSharedBinding=()=>{if(m.some(e=>e.readCurrentCredential()))throw new Error(`An agent already overrides this shared key. Remove that agent's override before replacing the shared key.`)};const validateReplacement=t=>{e.assertCurrent?.();validateSharedBinding();validateCurrentCredential(t)};const withCurrentCredentials=async t=>{for(;;)try{return await t()}catch(t){if(!(t instanceof AuthProfileCredentialPublicationPendingError))throw t;await t.waitUntilCurrent();e.assertCurrent?.()}};await withCurrentCredentials(async()=>{validateReplacement(s.profiles[d]);await upsertAuthProfileWithLockOrThrow({profileId:d,credential:{type:`api_key`,provider:t,key:n},agentDir:f,preserveApiKeyMetadata:true,resetFailureState:true,validateCurrentCredential:validateReplacement,assertCurrent:e.assertCurrent})});const h=createRuntimeConfigWriteApplication(captureGatewayRootWorkAdmissionContinuationScope()?.run);let g=false;let _;await updateConfig(n=>withCurrentCredentials(()=>{validateSharedBinding();e.assertCurrent?.();const r=e.profileId?void 0:configuredKey(n);if(!e.profileId&&(r!==a||r!==void 0&&!isDeepStrictEqual(configuredBinding(n,r),o)))throw new Error(`The provider connection changed during the key update. Reopen the connection and save the key again`);let i=applyAuthProfileConfig(n,{...n.auth?.profiles?.[d],profileId:d,provider:t,mode:`api_key`});if(r&&i.models?.providers?.[r])i={...i,models:{...i.models,providers:{...i.models.providers,[r]:{...i.models.providers[r],apiKey:d}}}};i=structuredClone(i);_=allowProviderModelsInConfig(i,e.agentId,t);g=!isDeepStrictEqual(n,i);return i}),void 0,e.assertCurrent,attachRuntimeConfigWriteApplication({assertCurrent:e.assertCurrent},h)).catch(e=>{throw new Error(`API key saved, but provider settings could not be applied: `+(e instanceof Error?e.message:String(e))+`. Reopen Models and save the key again.`,{cause:e})});if(g&&!(h.claimed&&await h.result===`applied`))return{profileId:d,warning:"API key saved, but the Gateway has not confirmed applying the provider settings. Run `openclaw gateway restart` to apply them.",..._?{modelAccess:_}:{}};return{profileId:d,..._?{modelAccess:_}:{}}}export{withoutProviderModelPolicy as a,applyProviderLoginDefaultModel as i,allowLoginProviderModels as n,allowProviderModelsInConfig as r,saveModelProviderApiKey as t};