UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

7 lines • 14.8 kB
import"./src-0ci69Prg.mjs";import{t as expectDefined}from"./expect-DkJCbmLj.mjs";import{a as asOptionalRecord}from"./record-coerce-BTbqdJ3-.mjs";import{t as resolvePathViaExistingAncestorSync}from"./boundary-path-BeuXNL_4.mjs";import{n as normalizeAgentId}from"./agent-id-cOfqmfln.mjs";import{N as parseAgentSessionKey}from"./session-key-BPgKfU2m.mjs";import{t as formatCliCommand}from"./command-format-D7KhNLP0.mjs";import{i as listAgentIds}from"./agent-roster-4XrgUgPK.mjs";import{a as resolveAgentDir,y as resolveMutableAgentEntry}from"./agent-scope-config-CG9CFpGX.mjs";import{o as resolveAgentModelFallbackValues,u as toAgentModelListLike}from"./model-input-CJnF-FEy.mjs";import{t as splitTrailingAuthProfile}from"./model-ref-profile-DFGpvDZX.mjs";import{i as resolveProviderIdForAuth}from"./provider-auth-aliases-BRA1A5Vm.mjs";import{u as resolveAgentModelFallbacksOverride}from"./agent-scope-Dw5XRSEh.mjs";import{b as readUtilityModelSetting}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 prepareOpenClawAgentDatabaseRegistrySnapshotRead}from"./openclaw-agent-db-registry-listing-Bnnfy4SV.mjs";import{H as resolveNativeSharedAuthStorePath,b as resolveAuthProfileDatabasePath}from"./sqlite-y_WDH-Xr.mjs";import{v as withSessionHistoryWorkerReadCandidates}from"./session-transcript-worker-resources-BCJ3nyGg.mjs";import{a as withSessionHistoryWorkerDatabase}from"./session-transcript-worker-runtime-Cx43k2lO.mjs";import{r as prepareSessionStoreTargetInventory}from"./session-store-target-inventory-CcuhBOtl.mjs";import"./session-accessor-CY8UYP4m.mjs";import{a as patchSessionEntryTarget}from"./session-accessor.sqlite-entry-CQTjQD5y.mjs";import{g as resolveProviderConfigSecretInput,v as resolveProviderEntryApiKeyProfileReference}from"./model-auth-provider-config-KlOdxZHz.mjs";import{f as listProfilesForProvider}from"./order-B8e_5ABM.mjs";import{c as ensureAuthProfileStoreWithoutExternalProfilesAsync,g as loadAuthProfileStoreWithoutExternalProfilesAsync,l as findPersistedAuthProfileCredentialAsync,y as resolvePersistedAuthProfileOwnerAgentDirAsync}from"./store-runtime-GNz-2GjY.mjs";import{n as clearRemovedQueuedAuthProfiles}from"./state-t6zhY2pl.mjs";import{i as removeAuthProfilesAcrossOwnerStores,v as listCandidateAuthProfileStores}from"./profiles-Bp0-JifZ.mjs";import{r as logConfigUpdated}from"./logging-C183DMvG.mjs";import"./auth-profiles-nMUErGRQ.mjs";import{i as removeAuthProfileConfig,r as configReferencesAuthProfile}from"./provider-auth-helpers-5o5rkp5c.mjs";import{t as createClackPrompter}from"./clack-prompter-CkhFfk2k.mjs";import{l as resolveModelsTargetAgent,u as updateConfig}from"./shared-Sc7lnGKV.mjs";import"./queue-CwAyyslb.mjs";import{t as loadModelsConfig}from"./load-config-BZk4Hyvt.mjs";import{n as refreshRunningGatewayAuthState}from"./auth-refresh-B35YNJt_.mjs";import{isDeepStrictEqual}from"node:util"; //!src/sessions/auth-profile-removal.ts async function clearRemovedSessionAuthProfiles(e){clearRemovedQueuedAuthProfiles(e);if(e.removedByAgent.size===0)return;const{candidates:t,...n}=prepareSessionStoreTargetInventory(e.cfg,[...e.removedByAgent.keys()]);const r=prepareOpenClawAgentDatabaseRegistrySnapshotRead({env:n.env});await withSessionHistoryWorkerReadCandidates(t,async t=>{let i=await t.readTargetInventory({...n,registeredDatabases:{status:`deferred`}});if(i.kind===`session-target-registry-required`){const e=await r.read();i=await t.readTargetInventory({...n,registeredDatabases:e.result.status===`available`?e.result.entries:{status:`unavailable`}})}if(i.kind!==`session-target-inventory`)throw new Error(`Session stores could not be resolved after removing the account.`);for(const{agentId:a,result:o,reads:s}of i.agents){if(!o.available){if(o.reason===`database-missing`)continue;throw new Error(`Sessions for agent ${a} could not be read after removing the account.`)}const i=expectDefined(e.removedByAgent.get(a),`removed agent profiles`);const isRemoved=e=>e!==void 0&&i.has(e);for(const{database:e}of s)await withSessionHistoryWorkerDatabase({...e,env:n.env},async i=>{const assertCurrent=()=>{t.assertCurrent();r.assertCurrent();i.assertCurrent()};const{entries:o}=await i.readEntries({agentId:e.agentId,storePath:e.path,env:n.env,projection:`list`,readConsistency:`latest`});const s=o.filter(({sessionKey:t,entry:n})=>normalizeAgentId(parseAgentSessionKey(t)?.agentId??e.agentId)===a&&(isRemoved(n.authProfileOverride)||isRemoved(n.modelFallback?.prevAuthProfileOverride))).map(({sessionKey:e})=>e);if(s.length===0)return;const c=await i.readExactEntries({env:n.env,sessionKeys:s,includeAuthorization:true,snapshotFields:[]});assertCurrent();if(c.entries.length===0)return;const l=expectDefined(c.databaseIdentity,`session database identity`);for(const{sessionKey:t,entry:r}of c.entries){const i=new Set([r.authProfileOverride,r.modelFallback?.prevAuthProfileOverride].filter(isRemoved));for(const r of i)await patchSessionEntryTarget({agentId:a,storePath:e.path,env:n.env,readSource:{...e,databaseIdentity:l.identity,databaseBirthtime:l.birthtime},target:{canonicalKey:t,storeKeys:[t]}},e=>{const t=e.authProfileOverride===r;const n=e.modelFallback;const i=n?.prevAuthProfileOverride===r;if(!t&&!i)return null;return{...t?{authProfileOverride:void 0,authProfileOverrideSource:void 0,authProfileOverrideCompactionCount:void 0}:{},...i?{modelFallback:{...n,prevAuthProfileOverride:void 0,prevAuthProfileOverrideSource:void 0,prevAuthProfileOverrideCompactionCount:void 0}}:{}}},{preserveActivity:true,skipMaintenance:true,workerGuard:{assertCurrent}})}})}})} //!src/commands/models/auth-logout-selections.ts async function resolveModelAuthProfileRemoval(e,t){const n=/* @__PURE__ */ new Map;for(const e of t){const t=n.get(e.databasePath)??/* @__PURE__ */ new Set;for(const n of e.profileIds)t.add(n);n.set(e.databasePath,t)}const r=resolvePathViaExistingAncestorSync(resolveNativeSharedAuthStorePath());const i=n.get(r)??/* @__PURE__ */ new Set;const a=/* @__PURE__ */ new Map;if(n.size===0)return{shared:i,agents:a};const o=new Map(listAgentIds(e).map(t=>[t,resolveAgentDir(e,t)]));for(const t of await listCandidateAuthProfileStores({cfg:e}))if(!o.has(t.agentId))o.set(t.agentId,t.agentDir);const s=new Set(t.flatMap(e=>[...e.profileIds]));for(const[e,t]of o){const i=/* @__PURE__ */ new Set;for(const e of s){if(!await findPersistedAuthProfileCredentialAsync({agentDir:t,profileId:e}))continue;const a=await resolvePersistedAuthProfileOwnerAgentDirAsync({agentDir:t,profileId:e});const o=a?resolvePathViaExistingAncestorSync(resolveAuthProfileDatabasePath(a)):r;if(n.get(o)?.has(e))i.add(e)}if(i.size>0)a.set(e,i)}return{shared:i,agents:a}}function removeModelAuthProfileSelections(e,t){if(!e.agents)return e;const strip=(e,t)=>{if(!e||!t?.size)return e;const{model:n,profile:r}=splitTrailingAuthProfile(e);return r&&t.has(r)?n:e};const stripModel=(e,t)=>{if(typeof e===`string`||e===void 0)return strip(e,t);return{...e,...e.primary!==void 0?{primary:strip(e.primary,t)}:{},...e.fallbacks?{fallbacks:e.fallbacks.map(e=>strip(e,t))}:{}}};const n=structuredClone(e);const r=e.agents.defaults;const i=n.agents?.defaults;if(i){if(i.model!==void 0)i.model=stripModel(i.model,t.shared);if(i.utilityModel!==void 0)i.utilityModel=stripModel(i.utilityModel,t.shared)}for(const a of listAgentIds(e)){let o=resolveMutableAgentEntry(n,a);const s=!o;if(!o&&n.agents){n.agents.entries={[a]:{}};o=n.agents.entries[a]}if(!o)continue;const c=t.agents.get(a);const resolveFallbacks=(e,t)=>{if(t===`model`)return resolveAgentModelFallbacksOverride(e,a)??resolveAgentModelFallbackValues(e.agents?.defaults?.model);const n=readUtilityModelSetting(e,a);return n.kind===`disabled`?[]:n.fallbacks};for(const t of[`model`,`utilityModel`]){const a=o[t];if(t===`utilityModel`&&typeof a===`string`&&!a.trim())continue;const s=toAgentModelListLike(a);const l=toAgentModelListLike(r?.[t]);const u=toAgentModelListLike(i?.[t]);const d=toAgentModelListLike(stripModel(a,c))??{};if(s?.primary===void 0&&l?.primary!==void 0){const e=strip(l.primary,c);if(e!==u?.primary)d.primary=e}if(Object.keys(d).length>0){const e=a??(t===`utilityModel`?r?.utilityModel:void 0);o[t]=typeof e===`string`&&d.fallbacks===void 0?d.primary:d}const f=resolveFallbacks(e,t).map(e=>strip(e,c));if(!isDeepStrictEqual(f,resolveFallbacks(n,t)))o[t]={...toAgentModelListLike(o[t]),fallbacks:f}}if(s&&Object.keys(o).length===0&&n.agents)delete n.agents.entries}return isDeepStrictEqual(e,n)?e:n} //!src/commands/models/auth-logout.ts const MISSING_CONFIG_VALUE=Symbol(`missing-config-value`);function restoreConfigMutationValue(e,t,n){if(isDeepStrictEqual(t,n))return e;if(isDeepStrictEqual(e,n))return t;const r=asOptionalRecord(e);const i=asOptionalRecord(t);const a=asOptionalRecord(n);if(!r||!i||!a)return e;const o={...r};const s=/* @__PURE__ */ new Set([...Object.keys(i),...Object.keys(a)]);for(const e of s){const t=restoreConfigMutationValue(Object.hasOwn(r,e)?r[e]:MISSING_CONFIG_VALUE,Object.hasOwn(i,e)?i[e]:MISSING_CONFIG_VALUE,Object.hasOwn(a,e)?a[e]:MISSING_CONFIG_VALUE);if(t===MISSING_CONFIG_VALUE)delete o[e];else o[e]=t}return o}function restoreCredentialConfigMutation(e){return restoreConfigMutationValue(e.current,e.before,e.after)}async function removeModelAuthCredentials(e){if(e.provider!==void 0){const{forgetSignedOutPluginModelCatalogRows:t}=await import(`./plugin-model-catalog-save-BiLP8H1U.mjs`);await t(e.agentDir,e.provider)}const t=e.apiKeyProvider;const keyBindings=(e,n)=>{const r=t===void 0?void 0:resolveProviderIdForAuth(t,{config:e});return{owner:r,bindings:Object.fromEntries(Object.entries(e.models?.providers??{}).filter(([t,n])=>n.apiKey!==void 0&&resolveProviderIdForAuth(t,{config:e})===r).map(([t])=>{const{providerConfig:r,ref:i}=resolveProviderConfigSecretInput(e,t,n);return[t,i??r?.apiKey]}))}};const n=t===void 0?void 0:keyBindings(e.cfg);const r=createRuntimeConfigWriteApplication(captureGatewayRootWorkAdmissionContinuationScope()?.run);let i=false;let a;let o;const beforeRemove=async(a,s=[])=>{await updateConfig(async(r,{runtimeConfig:c})=>{if(n&&!isDeepStrictEqual(keyBindings(c,c),n))throw new Error(`The key changed while removing it. Nothing was removed. Reload Models and retry removal.`);const l=await loadAuthProfileStoreWithoutExternalProfilesAsync(e.agentDir,{allowKeychainPrompt:false});if(t!==void 0&&a.some(e=>{const n=l.profiles[e];return n?.type!==`api_key`||Boolean(n.keyRef)||resolveProviderIdForAuth(n.provider,{config:r,storedCredential:true})!==resolveProviderIdForAuth(t,{config:r})}))throw new Error(`The selected API key changed. Reload Models and retry removal.`);const u=await resolveModelAuthProfileRemoval(c,s);let d=r;for(const e of a)d=removeAuthProfileConfig(d,e);if(t!==void 0&&d.models?.providers){const e=resolveProviderIdForAuth(t,{config:d});const n={...d.models.providers};for(const[t,r]of Object.entries(n))if(resolveProviderIdForAuth(t,{config:d})===e&&resolveProviderEntryApiKeyProfileReference({cfg:c,sourceConfig:c,provider:t,store:l}).kind===`literal`){const{apiKey:e,...i}=r;n[t]=i}d={...d,models:{...d.models,providers:n}}}const f=removeModelAuthProfileSelections(d,u);o={before:r,after:f,profileIds:a,selections:u};i=!isDeepStrictEqual(r,f);return f},void 0,void 0,attachRuntimeConfigWriteApplication({},r))};const restoreIncompleteRemoval=async(e,t=[])=>{const n=o;if(!n)return;const r=new Set(e.keys());let i=n.before;for(const e of n.profileIds)if(r.has(e))i=removeAuthProfileConfig(i,e);let s=restoreCredentialConfigMutation({current:n.after,before:n.before,after:i});const c={...n.after.auth?.order};for(const[e,t]of Object.entries(n.before.auth?.order??{})){const i=n.after.auth?.order?.[e]??[];const a=t.filter(e=>i.includes(e)||r.has(e));for(const e of i)if(!a.includes(e))a.push(e);if(a.length>0||Object.hasOwn(c,e))c[e]=a}if(Object.keys(c).length>0||s.auth){const{order:e,...t}=s.auth??{};s={...s,auth:{...t,...Object.keys(c).length>0?{order:c}:{}}}}const l=n.selections;const u=await resolveModelAuthProfileRemoval(n.before,t);const d={shared:new Set([...l.shared].filter(e=>!u.shared.has(e))),agents:new Map([...l.agents].map(([e,t])=>[e,new Set([...t].filter(t=>!u.agents.get(e)?.has(t)))]).filter(([,e])=>e.size>0))};a=d;s=restoreCredentialConfigMutation({current:s,before:removeModelAuthProfileSelections(n.before,d),after:removeModelAuthProfileSelections(n.before,n.selections)});await updateConfig(e=>restoreCredentialConfigMutation({current:e,before:s,after:n.after}));n.selections=d};let s;try{s=await removeAuthProfilesAcrossOwnerStores({cfg:e.cfg,agentDir:e.agentDir,profileIds:e.profileIds,beforeRemove,onIncomplete:restoreIncompleteRemoval,...e.provider!==void 0?{provider:e.provider}:{}});if(s&&o)a=o.selections}finally{if(o&&a){const e=a;await clearRemovedSessionAuthProfiles({cfg:o.after,removedByAgent:e.agents,rewriteConfig:t=>removeModelAuthProfileSelections(t,e)})}}if(!s)throw new Error(`Saved credentials could not be removed. Wait a moment and retry.`);if(i&&!(r.claimed&&await r.result===`applied`))return"Credentials were removed, but the Gateway has not confirmed applying the change. Run `openclaw gateway restart` to apply it."}async function modelsAuthLogoutCommand(e,t){const n=e.profileId?.trim();if(!n)throw new Error(`Missing profile id. Run ${formatCliCommand(`openclaw models auth list`)} to see saved profile ids.`);const r=await loadModelsConfig({commandName:`models auth logout`,runtime:t});const{agentId:i,agentDir:a}=resolveModelsTargetAgent(r,e.agent,{kind:`mutation`});const o=await ensureAuthProfileStoreWithoutExternalProfilesAsync(a);const s=o.profiles[n];if(!s)throw new Error(`Auth profile "${n}" not found for agent "${i}". Run ${formatCliCommand(`openclaw models auth list --agent ${i}`)} to see saved profile ids.`);const c=`${n} (${s.provider}/${s.type})`;if(!e.yes){if(!process.stdin.isTTY)throw new Error(`Refusing to remove auth profile ${c} without confirmation. Pass --yes to remove it non-interactively.`);if(!await createClackPrompter().confirm({message:`Remove auth profile ${c} from agent ${i}?`,initialValue:false})){t.log(`Cancelled.`);return}}const l=await removeModelAuthCredentials({cfg:r,agentDir:a,profileIds:[n]});if(configReferencesAuthProfile(r,n))logConfigUpdated(t);await refreshRunningGatewayAuthState(i,`logout`,t);if(l)t.error(l);t.log(`Agent: ${i}`);t.log(`Removed auth profile: ${c}`);if(listProfilesForProvider(o,s.provider).filter(e=>e!==n).length===0)t.log(`No auth profiles remain for ${s.provider}. Run ${formatCliCommand(`openclaw models auth login --provider ${s.provider}`)} to sign in again.`)}export{modelsAuthLogoutCommand,removeModelAuthCredentials};