UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

5 lines • 18.7 kB
import{i as copyConfigResolutionFacts,m as restoreConfigResolutionFacts}from"../resolution-facts-DYKtoyes.mjs";import{n as freezeTrustedJsonSnapshot,r as isDeeplyFrozenPlainData}from"../immutable-data-CyaF4H_G.mjs";import{t as AsyncWorkScope}from"../async-work-scope-DBcxYU4O.mjs";import{C as normalizePluginsConfigWithResolverCore}from"../config-state-C1eV6UWf.mjs";import{n as normalizeAgentId}from"../agent-id-cOfqmfln.mjs";import"../session-key-BPgKfU2m.mjs";import{r as normalizeProviderId}from"../provider-id-A-8WTtLA.mjs";import{F as resolveRegisteredAgentIdForDir,L as unregisterResolvedAgentDir,P as registerResolvedAgentDir}from"../agent-scope-config-CG9CFpGX.mjs";import{t as _usingCtx}from"../usingCtx-CUVyQ_FT.mjs";import{i as installDatabaseEngineSelection}from"../context-DZjni16e.mjs";import{X as withWorkerAuthProfileWrites,a as captureAuthProfileCredentialCommits}from"../user-model-account-authority-B8H7rvCb.mjs";import{O as setRuntimeConfigSnapshot,a as getRuntimeConfigSnapshot,c as getRuntimeConfigSourceSnapshot}from"../runtime-snapshot-Bg5K4JNu.mjs";import{_ as restorePluginMetadataSnapshot}from"../plugin-metadata-snapshot-CDKhemiT.mjs";import{f as withPluginSourceCaptureDirectory}from"../plugin-package-metadata-capture-DftefO2m.mjs";import{a as nativeReferenceProgress}from"../plugin-recovery-source-copy-D1GRsjul.mjs";import{n as withPluginRuntimeGenerationScope}from"../generation-scope-CxHnQlew.mjs";import{d as withRemoteModelCatalogSnapshot,n as captureRemoteModelCatalogStartupSnapshot}from"../remote-overlay-BQPwRXZH.mjs";import{n as isManifestPluginAvailableForControlPlane}from"../manifest-contract-eligibility-BFn2JM5T.mjs";import{r as hasUsableOAuthCredential}from"../credential-state-C3XZhGc-.mjs";import{u as mergeRuntimeExternalProfileReferences}from"../persisted-CpbPYi0y.mjs";import{i as noteCommittedSharedAuthStoreOwnership}from"../path-resolve-TSS6dv07.mjs";import{G as preserveResolvedSecretBackedCredentials,b as measureRuntimeAuthProfileStores,k as replaceRuntimeAuthProfileStoreSnapshotsAsync}from"../runtime-snapshots-DYK7vyJv.mjs";import{t as estimateRetainedDataSize}from"../retained-data-size-DvFKwu80.mjs";import{a as withTemplateInstallSchemaVersionFacts}from"../provenance-runtime-read-DtuKDa_2.mjs";import{n as getPluginRegistryInspectionResources}from"../registry-inspection-resources-5ksQH_Ac.mjs";import{t as manifestPluginResolvesRuntimeModelCatalogAugment}from"../providers-CcG8xzp1.mjs";import{r as planRuntimePluginDiscovery}from"../provider-discovery-Bd_7hFWy.mjs";import{r as getPluginRuntimeLoadContext}from"../load-context-BgV8IMWg.mjs";import"../store-CX8ovUiF.mjs";import{r as listExternalCliSyncProviderIds}from"../external-cli-sync-C2s6hWdT.mjs";import{p as restorePreparedSyntheticAuthFacts}from"../active-runtime-registry-CJ7JKnlv.mjs";import{u as loadAuthProfileStoreForCatalogAsync}from"../store-runtime-GNz-2GjY.mjs";import{n as PREPARED_MODEL_CATALOG_WORKER_TIMEOUT_MS}from"../model-catalog-timeouts-BhtT2di8.mjs";import{i as resolveRuntimeSyntheticAuthProviderRefs,t as listManifestSyntheticAuthProviderRefs}from"../synthetic-auth.runtime-DRYlh_Cv.mjs";import{_ as resolveUsableAgentCredentialModes,c as retainPreparedPluginRegistry,g as resolveAgentCredentialMapFromStore,h as resolveAmbientAgentCredentialsForDiscovery,r as ownPreparedPluginGeneration,u as PreparedModelRuntimeBuildResources}from"../prepared-model-runtime.plugin-lifetime-bsBOq40C.mjs";import{t as AuthStorage}from"../auth-storage.core-CJFKhJwL.mjs";import{t as parseModelCatalogJson}from"../model-catalog-json-D7uWchaX.mjs";import{a as scopeSyntheticAuthProviderRefs}from"../prepared-model-runtime.synthetic-auth-DztyLpYa.mjs";import{n as prepareModelCatalogAuthLabels}from"../model-catalog-auth-labels-vkiWBW9K.mjs";import{n as listCatalogOAuthRuntimeOwners}from"../models-config.providers.catalog-context-iaYp0ueR.mjs";import{i as resolveImplicitProviderDiscoveryScope,t as prepareImplicitProviderStaticCatalog}from"../models-config.providers.implicit-BY5Rs6IM.mjs";import{r as createProviderAuthResolver}from"../models-config.providers.secrets-CGm6WJby.mjs";import{n as serveWorkerTasks}from"../worker-task-server-BeWxX5OH.mjs";import{r as getLiveCatalogRetainedData}from"../provider-live-catalog-cache-CBTQofrX.mjs";import{n as overlayExternalAuthProfiles}from"../external-auth-runtime-mfuUQmJY.mjs";import{parentPort,workerData}from"node:worker_threads"; //!src/agents/prepared-model-catalog-retained-data.ts const row=(e,t,n,r={})=>({structure:e,entries:n,...r,...estimateRetainedDataSize(t)});const publishedCensuses=/* @__PURE__ */ new Map;function measurePublishedRoots(e,t,n,r){const i=publishedCensuses.get(e);if(i?.roots.length===t.length&&i.roots.every((e,n)=>e.deref()===t[n]))return i.rows;const a=n();if(!r||t.every(r))publishedCensuses.set(e,{roots:t.map(e=>new WeakRef(e)),rows:a});else publishedCensuses.delete(e);return a}function measureRemoteCatalogs(e){const t=e.filter(e=>e!==null);return measurePublishedRoots(`catalog-remote`,t,()=>[row(`catalog-remote`,t.map(e=>e.providers),t.reduce((e,t)=>e+Object.values(t.providers).reduce((e,t)=>e+t.models.length,0),0),{generations:t.length,providers:t.reduce((e,t)=>e+Object.keys(t.providers).length,0)}),row(`catalog-pricing`,t.flatMap(e=>[e.pricing,e.upstreamPricing]),t.reduce((e,t)=>e+Object.keys(t.pricing).length+Object.keys(t.upstreamPricing).length,0))],isDeeplyFrozenPlainData)}function measurePreparedCatalogRetainedData(e,t,n=[]){const r=[...e];const i=r.map(e=>getPluginRuntimeLoadContext(e.pluginRegistry));const a=/* @__PURE__ */ new Set([getRuntimeConfigSnapshot(),getRuntimeConfigSourceSnapshot(),...n,...i.flatMap(e=>e?[e.rawConfig,e.config,e.activationSourceConfig]:[])]);a.delete(null);const o=/* @__PURE__ */ new Set([captureRemoteModelCatalogStartupSnapshot(),...r.map(e=>e.remoteCatalog)]);o.delete(null);const s=new Set(r.map(e=>e.pluginMetadataSnapshot));const c=r.flatMap(e=>e.preparedStaticProviderCatalog?.entries??[]).flatMap(e=>Object.values(e.providerConfigs));return[row(`catalog-index`,[],r.length,{generations:r.length}),row(`catalog-config`,a,a.size),...measurePublishedRoots(`catalog-metadata`,[...s],()=>[row(`catalog-metadata`,s,s.size)]),row(`catalog-static`,c,c.length,{providers:c.length}),...measureRemoteCatalogs([...o]),row(`catalog-request`,t?[t]:[],t?1:0),...measureRuntimeAuthProfileStores()]} //!src/agents/prepared-model-catalog.worker.ts function restoreWorkerConfig(e,t){restoreConfigResolutionFacts(e.input.config,e.configResolutionFacts);if(e.sourceConfigResolutionFacts===e.configResolutionFacts)copyConfigResolutionFacts(e.input.config,e.sourceConfigForSecrets);else restoreConfigResolutionFacts(e.sourceConfigForSecrets,e.sourceConfigResolutionFacts);setRuntimeConfigSnapshot(t.runtime,t.source);return getRuntimeConfigSnapshot()}async function prepareWorkerGeneration(e,t,n,r){try{var i=_usingCtx();const a=n?.pluginGeneration.pluginMetadataSnapshot??restorePluginMetadataSnapshot(e.pluginMetadataSnapshot);const o=normalizePluginsConfigWithResolverCore(t.runtime.plugins,a.normalizePluginId);const s=r??(n&&[...n.pluginIds])??a.plugins.filter(n=>manifestPluginResolvesRuntimeModelCatalogAugment(n)&&isManifestPluginAvailableForControlPlane({snapshot:a,plugin:n,config:t.runtime,normalizedConfig:o,...e.input.env?{env:e.input.env}:{}})).map(e=>e.id).toSorted((e,t)=>e.localeCompare(t));const c=i.a(new PreparedModelRuntimeBuildResources(retainPreparedPluginRegistry));const l=n&&!r?n.pluginGeneration.pluginRegistry:await c.load({...e.input,config:t.runtime,metadataSnapshot:a,preferBuiltPluginArtifacts:e.preferBuiltPluginArtifacts,basePluginIds:s,reusableRegistry:n?.pluginGeneration.pluginRegistry,purpose:`model-catalog`},()=>{});const u=Object.freeze({...n?.pluginGeneration,remoteCatalog:e.remoteCatalog,pluginMetadataSnapshot:a,pluginRegistry:l,preparedStaticProviderCatalog:void 0,preferBuiltPluginArtifacts:e.preferBuiltPluginArtifacts});return{config:t,pluginGeneration:u,pluginIds:/* @__PURE__ */ new Set([...s,...l.plugins.map(e=>e.id)]),plannedPluginIds:n&&r?n.plannedPluginIds:/* @__PURE__ */ new Set,staticProviderIds:n?.staticProviderIds??/* @__PURE__ */ new Set,release:ownPreparedPluginGeneration(u).retain()}}catch(e){i.e=e}finally{await i.d()}}async function runCatalogRequest(e,t,n,r,i,a){const o=e.input.agentId?{agentId:e.input.agentId,agentDir:e.input.agentDir,env:e.input.env}:void 0;let s=false;let c;let l;try{if(e.sharedAuthStoreOwnership)noteCommittedSharedAuthStoreOwnership(e.sharedAuthStoreOwnership,e.input.env);if(o){s=registerResolvedAgentDir(o);if(resolveRegisteredAgentIdForDir(o.agentDir,o.env)!==normalizeAgentId(o.agentId))throw new Error(`Conflicting registered agent owners for ${o.agentDir}`)}const u=restoreWorkerConfig(e,t);restorePreparedSyntheticAuthFacts(n.syntheticAuth,[.../* @__PURE__ */ new Set([e.input.config,t.runtime,u])].flatMap(t=>[{config:t,env:e.input.env,workspaceDir:e.input.workspaceDir},{config:t,workspaceDir:e.input.workspaceDir}]));c=await i();const d={metadataSnapshot:c.pluginGeneration.pluginMetadataSnapshot,pluginRegistry:c.pluginGeneration.pluginRegistry};const resolveSyntheticCredentials=t=>withPluginRuntimeGenerationScope(d,()=>resolveAmbientAgentCredentialsForDiscovery({config:e.input.config,env:e.input.env,authoritativeSyntheticAuthProviderRefs:d.metadataSnapshot.owners.cliBackends.keys(),syntheticAuthProviderRefs:scopeSyntheticAuthProviderRefs([.../* @__PURE__ */ new Set([...listManifestSyntheticAuthProviderRefs(d.metadataSnapshot.index),...resolveRuntimeSyntheticAuthProviderRefs(),...n.syntheticAuth.map(({providerRef:e})=>e)])],t),...e.input.workspaceDir?{workspaceDir:e.input.workspaceDir}:{}}));if(n.kind===`auth-refresh`)await a();const{agentDir:f,inheritedAuthDir:p,config:m,env:h}=e.input;const g=n.kind===`auth-refresh`?n.profileIds:void 0;const _=n.providerIds??listExternalCliSyncProviderIds();const{store:v,displayPath:y}=await loadAuthProfileStoreForCatalogAsync(f,{allowKeychainPrompt:false,...p?{inheritedAuthDir:p}:{}});const b=preserveResolvedSecretBackedCredentials({next:v,existing:e.authStore});const x=new Set(e.authStore.runtimePersistedProfileIds??[]);const S=new Set(e.authStore.runtimeExternalProfileIds??[]);for(const[t,n]of Object.entries(e.authStore.profiles))if(!x.has(t)&&!S.has(t)&&b.profiles[t]===void 0)b.profiles[t]=n;const C=mergeRuntimeExternalProfileReferences({next:b,existing:e.authStore});const w=withPluginRuntimeGenerationScope(d,()=>overlayExternalAuthProfiles(C,{config:m,env:h,..._?{externalCliProviderIds:_}:{},...g?{externalCliProfileIds:g}:{}}));if(n.kind===`catalog`)await replaceRuntimeAuthProfileStoreSnapshotsAsync([{agentDir:e.input.agentDir,store:w}]);const T={...resolveSyntheticCredentials(n.providerIds??e.providerIds),...resolveAgentCredentialMapFromStore(w,{config:e.input.config})};if(n.kind===`auth-refresh`)return{status:`ok`,kind:`auth-refresh`,authStore:w,credentials:T,authModes:resolveUsableAgentCredentialModes(T)};const{prepareAgentCatalogSource:E}=await import(`../prepared-model-runtime.scoped-catalog-cRUubQYE.mjs`);const{prepareFullCatalogFacts:D}=await import(`../prepared-model-runtime.full-catalog-BP_UkIKk.mjs`);const O=new Set(e.providerIds.map(normalizeProviderId));const k={...e.catalogFacts,input:e.input,env:e.input.env,templateAuthStorage:AuthStorage.inMemory(T),credentials:T,providerIds:[...new Set(n.providerIds??[...e.providerIds,...Object.keys(T)])].toSorted((e,t)=>e.localeCompare(t))};const{pluginMetadataSnapshot:A}=c.pluginGeneration;const j=resolveImplicitProviderDiscoveryScope({config:e.input.config,env:e.input.env,workspaceDir:e.input.workspaceDir,pluginMetadataSnapshot:A,providerDiscoveryProviderIds:[.../* @__PURE__ */ new Set([...e.providerIds,...Object.keys(T),...k.providerIds])]});const M=[...j?.keys()??[]].filter(e=>A.byPluginId.has(e));const N=e.sourceConfigForSecrets.models?.mode!==`replace`&&Object.values(w.profiles).some(e=>e.type===`oauth`&&!e.oauthRef&&!hasUsableOAuthCredential(e));const P=new Set(M.flatMap(e=>j?.get(e)??[]));const{plannedPluginIds:F,pluginIds:I}=c;const L=c.pluginGeneration.preparedStaticProviderCatalog?.providers;const R=c.staticProviderIds;const z=!(N&&k.providerIds.map(normalizeProviderId).some(e=>P.has(e)&&!R.has(e))||M.some(e=>!F.has(e)))?void 0:await withPluginRuntimeGenerationScope(d,()=>planRuntimePluginDiscovery({config:e.input.config,env:e.input.env,workspaceDir:e.input.workspaceDir,pluginMetadataSnapshot:A,onlyPluginIds:M}));const B=z?.kind===`runtime`?[...z.pluginIds??M]:[];if(N&&j){const t=await withPluginRuntimeGenerationScope(d,()=>listCatalogOAuthRuntimeOwners({providers:z?.providers??L??[],providerIds:k.providerIds,discoveryScope:j,registered:I,config:e.sourceConfigForSecrets,manifests:A.byPluginId,authStore:w,resolveProviderAuth:createProviderAuthResolver(h,w,m,e.sourceConfigForSecrets,e.input.workspaceDir)}));B.push(...t)}let V=c.pluginGeneration;if(B.some(e=>!I.has(e))){l=await prepareWorkerGeneration(e,c.config,c,[.../* @__PURE__ */ new Set([...I,...B])].toSorted());V=l.pluginGeneration;d.pluginRegistry=V.pluginRegistry}const H=l??c;await a();const U=/* @__PURE__ */ new Set([...H.staticProviderIds,...k.providerIds.map(normalizeProviderId).filter(e=>P.has(e))]);if(!V.preparedStaticProviderCatalog||U.size>H.staticProviderIds.size){H.pluginGeneration=Object.freeze({...V,preparedStaticProviderCatalog:await withPluginRuntimeGenerationScope(d,()=>prepareImplicitProviderStaticCatalog({config:e.input.config,env:e.input.env,workspaceDir:e.input.workspaceDir,pluginMetadataSnapshot:A,providerDiscoveryProviderIds:[...U]}))});H.staticProviderIds=U}V=H.pluginGeneration;const W=await E(k,V,`live`,false,{authStore:w,refresh:n.refresh,providerDiscoveryProviderIds:n.providerIds,providerDiscoveryTimeoutMs:PREPARED_MODEL_CATALOG_WORKER_TIMEOUT_MS});const G=await D(k,V,`live`,W,{includeNative:false,providerIds:n.providerIds});const K={...resolveSyntheticCredentials([...G.modelCatalog.entries,...G.modelCatalog.routeVariants].map(e=>e.provider).filter(e=>!n.providerIds||n.providerIds.includes(normalizeProviderId(e))).filter(e=>!O.has(normalizeProviderId(e)))),...T};const q=/* @__PURE__ */ new Map;const{catalogModels:J}=G;for(const e of J){const t=normalizeProviderId(e.provider);const n=q.get(t)??[];n.push(e);q.set(t,n)}const Y=W.pluginCatalogs.flatMap(({contents:e})=>{const t=parseModelCatalogJson(e,true);return Object.keys(t.providers??{})});for(const e of[...(G.modelCatalog.providerOutcomes??[]).map(e=>e.provider),...Y].map(normalizeProviderId))if(!q.has(e))q.set(e,[]);const X=[...k.providerIds,...Object.keys(K),...Object.keys(e.input.config.models?.providers??{}),...G.modelCatalog.entries.map(e=>e.provider),...G.modelCatalog.routeVariants.map(e=>e.provider),...(G.modelCatalog.staticEntries??[]).map(e=>e.provider),...Object.values(w.profiles).map(e=>e.provider)];const Z={status:`ok`,kind:`catalog`,snapshot:G.modelCatalog,runtimeModels:q,providerExpiries:W.providerExpiries??/* @__PURE__ */ new Map,pluginCatalogs:W.pluginCatalogs,configuredRuntimeModels:G.configuredRuntimeModels,credentials:K,providerAuthLabels:X.length===0?/* @__PURE__ */ new Map:withPluginRuntimeGenerationScope(d,()=>prepareModelCatalogAuthLabels({config:e.input.config,agentDir:e.input.agentDir,authStorePath:y,workspaceDir:e.input.workspaceDir,env:e.input.env,store:w,providers:X})),authStore:w,authModes:resolveUsableAgentCredentialModes(K)};r.beginClose();await r.runWhenIdle(()=>void 0);if(l){const e=getPluginRegistryInspectionResources(l.pluginGeneration.pluginRegistry);if(!e)throw new Error(`Catalog scope growth has no inspection resource owner`);e.adoptRetainedRegistrations(c.pluginGeneration.pluginRegistry);const t=c.release;Object.assign(c,l);l=void 0;await t()}if(z)c.plannedPluginIds=/* @__PURE__ */ new Set([...c.plannedPluginIds,...M]);return Z}catch(e){return{status:`failed`,error:e instanceof Error?e.message:String(e)}}finally{try{r.beginClose();await r.runWhenIdle(()=>void 0);await l?.release()}finally{await r.drain();if(o&&s)unregisterResolvedAgentDir(o)}}}if(parentPort){const e=workerData;if(e.databaseEngineSelection)installDatabaseEngineSelection(e.databaseEngineSelection);const t=/* @__PURE__ */ new Map;let n;serveWorkerTasks(async(r,i)=>{const a=r;const{request:o,context:s}=a;let c;if(`pluginMetadataSnapshot`in a.value)c=a.value;else{const e=t.get(s.workspaceDir);if(e?.fingerprint!==s.fingerprint)throw new Error(`Prepared model catalog worker context is unavailable`);c={...a.value,remoteCatalog:e.prepared.pluginGeneration.remoteCatalog,pluginMetadataSnapshot:e.prepared.pluginGeneration.pluginMetadataSnapshot}}if(c.remoteCatalog){const e=[captureRemoteModelCatalogStartupSnapshot(),...Array.from(t.values(),({prepared:e})=>e.pluginGeneration.remoteCatalog)].find(e=>e?.sourceUrl===c.remoteCatalog?.sourceUrl&&e?.revision===c.remoteCatalog?.revision);if(e)c={...c,remoteCatalog:e}}n=c;let l=0;let u;const reportProgress=e=>{const t=e;const n=performance.now();if(n>=l||t.pluginId!==u){l=n+1e3;u=t.pluginId;i?.notify(t)}};nativeReferenceProgress.subscribe(reportProgress);const stopProgress=()=>nativeReferenceProgress.unsubscribe(reportProgress);return withRemoteModelCatalogSnapshot(freezeTrustedJsonSnapshot(c.remoteCatalog),()=>withPluginSourceCaptureDirectory(e.sourceCaptureDirectory,async()=>{const{result:e,receipts:n}=await captureAuthProfileCredentialCommits(async()=>{const{workspaceDir:e,fingerprint:n,registrationFingerprint:r}=s;let a=t.get(e);const l=a?.registrationFingerprint===r?a.prepared.config:freezeTrustedJsonSnapshot({runtime:c.input.config,source:c.sourceConfigForSecrets});let u;let d=false;try{const s=new AsyncWorkScope;const f=await withWorkerAuthProfileWrites(c.input.env,s,()=>withTemplateInstallSchemaVersionFacts(o.templateInstallSchemaVersions,()=>s.run(()=>runCatalogRequest(c,l,o,s,async()=>{if(a?.fingerprint===n)return a.prepared;d=a?.registrationFingerprint!==r;return u=await prepareWorkerGeneration(c,l,d?void 0:a?.prepared)},async()=>{stopProgress();const e=await i?.request(null);e?.consumed();if(e&&e.input!==true)throw new Error(`prepared model catalog request retired before discovery`)}))));if(u&&f.status===`ok`){t.set(e,{fingerprint:n,registrationFingerprint:r,prepared:u});u=void 0;d=false;await a?.prepared.release();a=void 0}return f}finally{try{if(d){t.delete(e);await a?.prepared.release()}}finally{await u?.release()}}});return{...e,authCredentials:n}},e.sourceCaptureManagedRoot)).finally(()=>{n=void 0;stopProgress()})},{retainedData:()=>[...measurePreparedCatalogRetainedData(Array.from(t.values(),({prepared:e})=>e.pluginGeneration),n,Array.from(t.values()).flatMap(({prepared:e})=>[e.config.runtime,e.config.source])),...getLiveCatalogRetainedData()]})}export{};