UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

7 lines • 17.6 kB
import{g as normalizeUniqueStringEntries}from"./string-normalization-D_oBUpO3.mjs";import{t as appendConfigPathSegment}from"./dot-path-B1bYAWM5.mjs";import{_ as resolveSecretInputRef,o as hasConfiguredSecretInput,p as normalizeSecretInputString}from"./types.secrets-UWdyCdE6.mjs";import{a as copyConfigResolutionFactsExcept,i as copyConfigResolutionFacts,p as resolveConfigSecretRef}from"./resolution-facts-DYKtoyes.mjs";import{t as createDeferredCore}from"./deferred-QsZCoVH-.mjs";import{a as captureAsyncWorkTracker,o as getAsyncWorkSignal,t as AsyncWorkScope}from"./async-work-scope-DBcxYU4O.mjs";import{t as formatErrorMessage}from"./errors-D37BJTfI.mjs";import{r as normalizeProviderId}from"./provider-id-A-8WTtLA.mjs";import{_ as resolveDefaultAgentId,a as resolveAgentDir,f as resolveAgentWorkspaceDir}from"./agent-scope-config-CG9CFpGX.mjs";import{t as createSubsystemLogger}from"./subsystem-DLCDFvCH.mjs";import{n as monotonicNow}from"./monotonic-time-DjtFTu2s.mjs";import{r as cloneEnvWithPlatformSemantics}from"./config-env-vars-DCDGIBtT.mjs";import{G as getScopedAuthProfileEnv}from"./user-model-account-authority-B8H7rvCb.mjs";import{i as DEFAULT_PROVIDER}from"./defaults-k51tX6yK.mjs";import{o as resolveMergedModelProviderEntry}from"./model-provider-config-DrdykcWe.mjs";import{i as resolveProviderIdForAuth}from"./provider-auth-aliases-BRA1A5Vm.mjs";import"./agent-scope-Dw5XRSEh.mjs";import{n as parseModelRef,t as findNormalizedProviderValue}from"./model-selection-normalize-DU37Sfvg.mjs";import{b as resolveAuthProfileDatabasePath}from"./sqlite-y_WDH-Xr.mjs";import{n as clearRuntimeAuthProfileStoreSnapshotCore}from"./runtime-snapshots-DYK7vyJv.mjs";import"./model-selection-CNHinoVN.mjs";import{l as isNonSecretApiKeyMarker}from"./model-auth-markers-Dc97K3d8.mjs";import{_ as resolveProviderEntryApiKeyBinding,a as hasUsableCustomProviderApiKey,b as resolveUsableCustomProviderApiKey,i as hasSyntheticLocalProviderAuthConfig,v as resolveProviderEntryApiKeyProfileReference}from"./model-auth-provider-config-KlOdxZHz.mjs";import"./store-CX8ovUiF.mjs";import{f as listProfilesForProvider,i as resolveAuthProfileEligibility,o as resolveAuthProfileOrderWithMetadata}from"./order-B8e_5ABM.mjs";import{i as externalCliDiscoveryScoped}from"./external-cli-discovery-CHmIqgrd.mjs";import{t as resolveEnvApiKey}from"./model-auth-env-B6Hhnpzd.mjs";import{i as ensureAuthProfileStoreAsync}from"./store-runtime-GNz-2GjY.mjs";import{n as resolveAuthProfileDisplayLabel}from"./display-_lnk7MT7.mjs";import{f as readPreparedModelCatalog}from"./prepared-model-catalog-DR44fXi2.mjs";import{i as describeFailoverError}from"./failover-error-DWH-eolC.mjs";import{n as recordAgentCleanupFailure}from"./run-cleanup-timeout-B__J_Jbc.mjs";import{u as upsertAuthProfileWithLock}from"./profiles-Bp0-JifZ.mjs";import{t as resolveSecretRefString}from"./resolve-B002P2vn.mjs";import"./auth-profiles-nMUErGRQ.mjs";import"./model-auth-C99Q9Dp8.mjs";import{t as FAILOVER_PROBE_STATUS}from"./probe-status-EiTyOS0f.mjs";import{t as CONNECTION_CHECK_PROMPT}from"./connection-check-DjTZ6H1C.mjs";import{r as formatMs}from"./shared-Sc7lnGKV.mjs";import{t as prepareLocalCapabilityAccountSecrets}from"./local-account-secrets-Bs9U391q.mjs";import{t as redactStatusSecrets}from"./status-redaction-C7GJukcz.mjs";import"./format-C4BG3_tr.mjs";import{t as disposeOpenClawAgentDatabaseByPath}from"./openclaw-agent-db-disposal-COBwVbLB.mjs";import path from"node:path";import crypto from"node:crypto";import fs from"node:fs/promises";import os from"node:os";import{AsyncLocalStorage}from"node:async_hooks";import pMap from"p-map"; //!src/commands/models/list.probe.cleanup.ts const log=createSubsystemLogger(`models/probe`);async function disposeAuthProbeDirectory(e,t){clearRuntimeAuthProfileStoreSnapshotCore(e);try{await disposeOpenClawAgentDatabaseByPath(resolveAuthProfileDatabasePath(e),{env:t})}catch(t){throw new Error(`Auth probe database cleanup failed; retained ${e}: ${formatErrorMessage(t)}`,{cause:t})}await fs.rm(e,{recursive:true,force:true})}async function createAuthProbeWork(e){const t=captureAsyncWorkTracker();const n=getAsyncWorkSignal();const r=createDeferredCore();const i=createDeferredCore();t(()=>{r.resolve();return i.promise}).catch(r.reject);await r.promise;const a=new AsyncWorkScope;const o=a.run(()=>AsyncLocalStorage.snapshot());const s=/* @__PURE__ */ new Map;for(const t of[e,n]){if(!t||s.has(t))continue;const abort=()=>o(()=>a.beginClose(t.reason));s.set(t,abort);t.addEventListener(`abort`,abort,{once:true});if(t.aborted)abort()}return{settled:i.promise.catch(()=>{}),run(e){return a.track(e)},async settle(e){const finish=async()=>{try{await AsyncWorkScope.runWhenAllIdle(()=>[a],()=>o(()=>a.drain()));await e()}catch(e){recordAgentCleanupFailure();i.reject(e);throw e}finally{for(const[e,t]of s)e.removeEventListener(`abort`,t);i.resolve()}};if(!a.hasPendingWork){await finish();return}finish().catch(e=>{log.warn(`Auth check cleanup failed: ${redactStatusSecrets(formatErrorMessage(e))}`)})}}} //!src/commands/models/list.probe.models.ts function buildProbeCandidateMap(e){const t=/* @__PURE__ */ new Map;for(const n of e){const e=parseModelRef(n??``,DEFAULT_PROVIDER);if(e&&!t.has(e.provider))t.set(e.provider,e.model)}return t}async function loadProbeModelCatalog(e,t){return t.length?readPreparedModelCatalog({...e,readOnly:true,scopedLiveProviderDiscovery:true,providerDiscoveryProviderIds:t}):[]}function probePriority(e,t){const n=t.trim().toLowerCase();if(e!==`anthropic`)return 50;if(/^claude-haiku-4-5-\d{8}$/.test(n))return 0;if(n===`claude-haiku-4-5`)return 1;if(n===`claude-sonnet-5`||n.startsWith(`claude-sonnet-5-`))return 2;if(n===`claude-sonnet-4-6`||n.startsWith(`claude-sonnet-4-6-`))return 3;if(n.startsWith(`claude-sonnet-4-`))return 4;if(n.startsWith(`claude-3-`))return 100;return 50}function selectProbeModel(e){const{provider:t,candidates:n,catalog:r}=e;const i=n.get(t);if(i)return{provider:t,model:i};const a=r.filter(e=>normalizeProviderId(e.provider)===t&&e.status!==`deprecated`&&e.status!==`disabled`).toSorted((e,n)=>probePriority(t,e.id)-probePriority(t,n.id))[0];return a?{provider:t,model:a.id}:null} //!src/commands/models/list.probe.ts function buildProbeResult(e,t){return{provider:e.provider,model:e.model?`${e.model.provider}/${e.model.model}`:void 0,profileId:e.profileId,label:e.label,source:e.source,mode:e.mode,...t}}function buildNoModelProbeResult(e){return buildProbeResult(e,{status:`no_model`,reasonCode:`no_model`,error:`No model available for check`})}const ELIGIBILITY_PROBE_ERRORS={expired:`token credentials are expired.`,refresh_failed:`the OAuth refresh failed; sign in again.`,invalid_expires:`token expires must be a positive Unix ms timestamp.`,missing_credential:`no inline credential or SecretRef is configured.`,unresolved_ref:`configured SecretRef could not be resolved.`,ineligible_profile:`profile is incompatible with provider config.`};function mapEligibilityReasonToProbeReasonCode(e){switch(e){case`missing_credential`:case`expired`:case`refresh_failed`:case`invalid_expires`:case`unresolved_ref`:return e;default:return`ineligible_profile`}}function resolveProbeSecretRef(e,t){const n=t.secrets?.defaults;if(e.type===`api_key`)return resolveSecretInputRef({value:e.key,refValue:e.keyRef,defaults:n}).ref;if(e.type===`token`)return resolveSecretInputRef({value:e.token,refValue:e.tokenRef,defaults:n}).ref;return null}function createProbeConfig(e,t){if(!t.useRuntimeAuth&&!t.boundValue)return e;const n=t.useRuntimeAuth?void 0:t.boundValue;const r=n?resolveMergedModelProviderEntry(e,t.provider):void 0;const i={...e,...r?.providerConfig?{models:{...e.models,providers:{...e.models?.providers,[r.providerKey]:{...r.providerConfig,apiKey:n,auth:t.mode===`oauth`||t.mode===`token`?t.mode:`api-key`}}}}:{},auth:{...e.auth,order:{...e.auth?.order,[t.provider]:[]}}};if(r?.providerConfig)copyConfigResolutionFactsExcept(e,i,[`${appendConfigPathSegment(`models.providers`,r.providerKey)}.apiKey`]);else copyConfigResolutionFacts(e,i);return i}async function buildProbeTargets(e){const{cfg:t,agentDir:n,providers:r,modelCandidates:i,options:a,workspaceDir:o}=e;const s={config:t,workspaceDir:o};const c=await ensureAuthProfileStoreAsync(n,{externalCli:externalCliDiscoveryScoped({config:t,allowKeychainPrompt:false,providerIds:r.map(e=>resolveProviderIdForAuth(e,s)),profileIds:a.profileIds})});const l=a.provider?.trim();const u=l?normalizeProviderId(l):null;const d=new Set(normalizeUniqueStringEntries(a.profileIds));const f={};const p=buildProbeCandidateMap(i);const m=u?r.filter(e=>normalizeProviderId(e)===u):r;const h=await loadProbeModelCatalog({config:t,agentId:e.agentId,agentDir:n,workspaceDir:o},m.filter(e=>!p.has(normalizeProviderId(e))));const g=[];const _=[];const appendTarget=e=>{if(e.model)g.push(e);else _.push(buildNoModelProbeResult(e))};for(const e of m){const r=normalizeProviderId(e);const i=resolveProviderIdForAuth(r,s);const l=selectProbeModel({provider:r,candidates:p,catalog:h});const u=resolveMergedModelProviderEntry(t,r);const m=u?.providerConfig;const v=Boolean(u&&resolveConfigSecretRef({config:t,path:`${appendConfigPathSegment(`models.providers`,u.providerKey)}.apiKey`,value:m?.apiKey,defaults:t.secrets?.defaults}));const y=a.includeDirectKeys===true&&d.size===0;const b=y&&hasConfiguredSecretInput(m?.apiKey,t.secrets?.defaults);const x=[.../* @__PURE__ */ new Set([...listProfilesForProvider(c,i),...i===r?[]:listProfilesForProvider(c,r)])];const S=b?resolveProviderEntryApiKeyProfileReference({cfg:t,provider:r,store:c}):{kind:`none`};const C=S.kind===`profile`&&!x.includes(S.profileId)?await resolveProviderEntryApiKeyBinding({cfg:t,provider:r,store:c,agentDir:n}):null;const w=u&&b&&S.kind!==`profile`&&S.kind!==`profile-incompatible`?S.kind===`marker`?resolveUsableCustomProviderApiKey({cfg:t,provider:r,env:process.env})?.apiKey??null:await(async()=>{const e=m?.apiKey;const n=`${appendConfigPathSegment(`models.providers`,u.providerKey)}.apiKey`;const r=resolveConfigSecretRef({config:t,path:n,value:e,defaults:t.secrets?.defaults});if(!r)return normalizeSecretInputString(e)??null;try{return await resolveSecretRefString(r,{config:t,env:process.env,cache:f})}catch{return null}})():null;const T=m?.auth===`oauth`||m?.auth===`token`?m.auth:`api_key`;const E=y&&!v?resolveEnvApiKey(i,process.env,{config:t,workspaceDir:o}):null;const D=E?.apiKey===w?null:E;const O=S.kind===`marker`&&w&&isNonSecretApiKeyMarker(w,{includeEnvVarName:false})?`provider`:`config`;const k=findNormalizedProviderValue(c.order,i)??findNormalizedProviderValue(c.order,r)??findNormalizedProviderValue(t?.auth?.order,i)??findNormalizedProviderValue(t?.auth?.order,r);const A=resolveAuthProfileOrderWithMetadata({cfg:t,store:c,provider:r,forModel:l?.model});const j=A.hasExplicitOrder?new Set(A.profileIds):null;const M=d.size?x.filter(e=>d.has(e)):x;for(const e of M){const n=c.profiles[e];const i=n?.type;const a={provider:r,model:l,profileId:e,label:resolveAuthProfileDisplayLabel({cfg:t,store:c,profileId:e}),source:`profile`,mode:i};const o=b&&S.kind===`profile`&&e===S.profileId;let s;if(!o&&k&&!k.includes(e))s={reasonCode:`excluded_by_auth_order`,error:`Excluded by auth.order for this provider.`};else if(!o&&j&&!j.has(e)){const n=mapEligibilityReasonToProbeReasonCode(resolveAuthProfileEligibility({cfg:t,store:c,provider:r,profileId:e}).reasonCode);s={reasonCode:n,error:`Auth profile credentials are missing or expired.\n↳ Auth reason [${n}]: ${ELIGIBILITY_PROBE_ERRORS[n]}`}}else s=await(async()=>{if(!n)return null;const e=resolveProbeSecretRef(n,t);if(!e)return null;try{await resolveSecretRefString(e,{config:t,env:process.env,cache:f});return null}catch{return{reasonCode:`unresolved_ref`,error:`Auth profile credentials are missing or expired.\n↳ Auth reason [unresolved_ref]: could not resolve SecretRef "${`${e.source}:${e.provider}:${e.id}`}".`}}})();if(s)_.push(buildProbeResult(a,{status:`unknown`,...s}));else appendTarget(a)}if(M.length===0&&d.size>0)continue;if(b){const e={provider:r,model:l,...S.kind===`profile`||S.kind===`profile-incompatible`?{profileId:S.profileId}:{},label:`config`,source:`models.json`,mode:T};const unresolvedResult=t=>({...e,model:l?`${l.provider}/${l.model}`:void 0,status:l?`unknown`:`no_model`,reasonCode:l?`unresolved_ref`:`no_model`,error:l?t:`No model available for check`});if(S.kind===`profile-incompatible`)_.push({...e,model:l?`${l.provider}/${l.model}`:void 0,status:`unknown`,reasonCode:`ineligible_profile`,error:`Configured API key references an incompatible auth profile.`});else if(S.kind===`profile`){if(!x.includes(S.profileId)){if(C?.kind===`profile-resolved`&&l)g.push({...e,profileId:C.auth.profileId,mode:C.auth.mode,boundValue:C.auth.apiKey});else _.push(unresolvedResult(`Configured auth profile could not be resolved.`))}}else if(!w)_.push(unresolvedResult(`Configured API key could not be resolved.`));else appendTarget({...e,label:O,boundValue:w,...S.kind===`marker`?{useRuntimeAuth:true}:{}})}if(D){const e=m?.auth===`oauth`||m?.auth===`token`?m.auth:D.source.includes(`OAUTH_TOKEN`)?`oauth`:`api_key`;appendTarget({provider:r,model:l,label:D.source,source:`env`,mode:e,boundValue:D.apiKey})}if(M.length>0||b||D)continue;const N=hasUsableCustomProviderApiKey(t,r);const P=hasSyntheticLocalProviderAuthConfig({cfg:t,provider:r});if(A.hasExplicitOrder&&!N&&!P)continue;const F=A.hasExplicitOrder||v?null:resolveEnvApiKey(i,process.env,{config:t,workspaceDir:o});if(!F&&!N&&!P)continue;const I=F?`env`:`models.json`;appendTarget({provider:r,model:l,label:I,source:I,mode:F?.source.includes(`OAUTH_TOKEN`)?`oauth`:`api_key`,...P&&!F&&!N?{useRuntimeAuth:true}:{}})}return{targets:g,results:_}}async function withAuthProbeStateOwnership(e,t){if(!e)return await t();const{runWithLocalStateOwner:n}=await import(`./local-state-owner-D6lzsNxM.mjs`);return await n({method:`models status --probe`,params:{},target:`model credentials`,onForeignOwner:`refuse`,onlineAlternative:`Omit --probe to read status without live checks.`,runLocal:async({signal:e})=>{const n=await createAuthProbeWork(e);try{return await n.run(()=>t(e))}finally{await n.settle(async()=>{});await n.settled}}})}async function runAuthProbes(e){return await withAuthProbeStateOwnership(e.stateOwnership,async t=>{const n=Date.now();const r=monotonicNow();const i=await buildProbeTargets(e);const a=i.targets.length;e.onProgress?.({completed:0,total:a});let o=[];if(a){const n=e.cfg;const r=e.agentId;const a=e.agentDir;const s=e.workspaceDir;const c=e.options;const l=e.onProgress;const u=i.targets;const{timeoutMs:d,maxTokens:f}=c;const p=Math.max(1,Math.min(u.length||1,c.concurrency));const m=r??resolveDefaultAgentId(n);const h=a??resolveAgentDir(n,m);const g=s??resolveAgentWorkspaceDir(n,m);if(e.stateOwnership)await prepareLocalCapabilityAccountSecrets({cfg:n,agentId:m});await fs.mkdir(g,{recursive:true});let _=0;o=await pMap(u,async e=>{l?.({completed:_,total:u.length,label:`Checking ${e.provider}${e.profileId?` (${e.label})`:``}`});const r=await(async()=>{const r=t;const i=createProbeConfig(n,e);if(!e.model)return buildNoModelProbeResult(e);const a=e.model;let o=null;let s;let c;let l;const u=await createAuthProbeWork(r);const buildResult=(t,n)=>buildProbeResult(e,{status:t,...n?{error:n}:{},...l!==void 0?{latencyMs:l}:{}});try{if(e.boundValue||e.useRuntimeAuth){o=await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(),`openclaw-auth-probe-`)));s=cloneEnvWithPlatformSemantics(getScopedAuthProfileEnv()??process.env)}if(e.boundValue&&!e.useRuntimeAuth&&o){c=`${e.provider}:probe-${crypto.randomUUID()}`;const t=e.boundValue;const n=e.mode===`oauth`?{type:`oauth`,provider:e.provider,access:t,refresh:`not-a-real`,expires:Date.now()+36e5}:e.mode===`token`?{type:`token`,provider:e.provider,token:t}:{type:`api_key`,provider:e.provider,key:t};if(!await upsertAuthProfileWithLock({profileId:c,credential:n,agentDir:o}))throw new Error(`Could not prepare isolated auth check profile`)}const{runIsolatedCompletion:t}=await import(`./isolated-completion-DVknICtD.mjs`);if(!(await u.run(()=>t({config:i,agentId:m,agentDir:o??h,workspaceDir:g,provider:a.provider,model:a.model,authProfileId:c??e.profileId,...o?{preparedModelRuntimeMode:`isolated-read-only`}:{},agentHarnessRuntimeOverride:`openclaw`,systemPrompt:``,prompt:`Reply with the single word OK. Do not use tools.`,timeoutMs:d,abortSignal:r,thinkLevel:`off`,...f!==void 0?{streamParams:{maxTokens:f}}:{},outputTextPolicy:`strict-visible`,onRequestComplete:e=>{l=Math.round(e)}}))).text.trim())return buildResult(`format`,`The provider returned no visible text.`);return buildResult(`ok`)}catch(e){const t=describeFailoverError(e);return buildResult(t.reason?FAILOVER_PROBE_STATUS[t.reason]??`unknown`:`unknown`,redactStatusSecrets(t.message))}finally{await u.settle(async()=>{if(o)await disposeAuthProbeDirectory(o,s)})}})();_+=1;l?.({completed:_,total:u.length});return r},{concurrency:p,stopOnError:true,...t?{signal:t}:{}})}return{startedAt:n,finishedAt:Date.now(),durationMs:Math.round(monotonicNow()-r),totalTargets:a,options:e.options,results:[...i.results,...o]}})}function sortProbeResults(e){return e.toSorted((e,t)=>{const n=e.provider.localeCompare(t.provider);if(n!==0)return n;const r=e.label||e.profileId||``;const i=t.label||t.profileId||``;return r.localeCompare(i)})}function describeProbeSummary(e){if(e.totalTargets===0)return`No check targets.`;return`Checked ${e.totalTargets} target${e.totalTargets===1?``:`s`} in ${formatMs(e.durationMs)}`}export{withAuthProbeStateOwnership as a,sortProbeResults as i,describeProbeSummary as n,runAuthProbes as r,buildProbeTargets as t};