UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

14 lines • 18.4 kB
import{l as normalizeOptionalString}from"./string-coerce-CpTFcSwY.mjs";import{c as resolveUserPath}from"./home-dir-DEN5DisQ.mjs";import{l as isRecord}from"./record-coerce-BTbqdJ3-.mjs";import{c as isSecretRef}from"./ref-contract-CdpCUlb6.mjs";import"./types.secrets-UWdyCdE6.mjs";import"./utils-Dlk0IYAa.mjs";import{E as defaultSlotIdForKey,u as normalizePluginsConfig}from"./config-state-C1eV6UWf.mjs";import{a as resolveManifestOwnerBasePolicyBlock}from"./manifest-owner-policy-DVnu9FAE.mjs";import{t as formatErrorMessage}from"./errors-D37BJTfI.mjs";import{t as formatCliCommand}from"./command-format-D7KhNLP0.mjs";import{n as findNormalizedProviderValue,r as normalizeProviderId}from"./provider-id-A-8WTtLA.mjs";import{u as tryResolveDefaultAgentId}from"./agent-roster-4XrgUgPK.mjs";import{i as isInstalledPluginEnabled}from"./installed-plugin-index-B04a42mO.mjs";import{v as listProviderPolicyOwners}from"./plugin-metadata-snapshot-CDKhemiT.mjs";import{i as loadPluginRegistrySnapshot}from"./plugin-registry-snapshot-Dz_L4M3w.mjs";import{t as getProviderEnvVarsCore}from"./provider-env-vars-CSXML2JF.mjs";import{n as loadPluginManifestRegistryForPluginRegistry}from"./plugin-registry-contributions-C4xBwxaW.mjs";import"./agent-scope-Dw5XRSEh.mjs";import"./legacy-config-record-shared-B0hPoAz4.mjs";import{t as loadProviderPolicyArtifactsAsync}from"./provider-public-artifacts-DlwyY-Ow.mjs";import"./plugin-registry-BAbRxjjy.mjs";import{t as captureRuntimeConfig}from"./runtime-source-projection-DvPkX_nq.mjs";import{b as resolveUsableCustomProviderApiKey}from"./model-auth-provider-config-KlOdxZHz.mjs";import{t as isConfiguredAwsSdkAuthProfileForProvider}from"./order-B8e_5ABM.mjs";import{r as hasAuthProfileStoreSourceForProvider,t as hasAnyAuthProfileStoreSource}from"./source-check-rCWqGxdp.mjs";import{n as OPENAI_COMPATIBLE_MODEL_APIS,t as OPENAI_COMPATIBLE_EMBEDDING_PROVIDER_ID}from"./embedding-provider-config-Cq8OZlZj.mjs";import{t as resolveEnvApiKey}from"./model-auth-env-B6Hhnpzd.mjs";import{t as note}from"./note-e4DtVgg2.mjs";import{o as resolveRememberAcrossConversations}from"./config-utils-BYmSFUQe.mjs";import"./config-utils-B-g18Kn9.mjs";import"./auth-profiles-nMUErGRQ.mjs";import{t as resolveApiKeyForProviderCore}from"./model-auth-provider-CUvjd6Re.mjs";import"./model-auth-C99Q9Dp8.mjs";import{a as getActiveMemoryProviderCore,l as resolveActiveMemoryBackendConfig}from"./memory-runtime-CqK_5Mw-.mjs";import{t as resolveCommandSecretRefsViaGateway}from"./command-secret-gateway-DRP7S338.mjs";import{s as getMemoryEmbeddingCommandSecretTargetIds}from"./command-secret-targets-X-olXSJu.mjs";import{t as hasConfiguredMemorySecretInput}from"./secret-input-mKkGBlBY.mjs";import{n as resolveMemorySearchConfig}from"./memory-search-CD-bpCVZ.mjs";import"./secret-CqsL84rV.mjs";import{a as getMissingLocalMemoryEmbeddingProviderMessage}from"./memory-core-bundled-runtime-hGWhomYA.mjs";import{n as resolveMemoryDoctorAgentScopes,t as formatMemoryDoctorAgentMessage}from"./doctor-memory-scope-C_cR43OE.mjs";import{i as noteWorkspaceMemoryHealth}from"./doctor-workspace-DESytzQ0.mjs";import{safeStatSync}from"@openclaw/fs-safe/path"; //!src/commands/doctor-memory-search-local.ts function formatLocalRuntimeDoctorNote(e){const t=e.backend??`unknown`;const n=e.buildInfo?`, ${e.buildInfo}`:``;const r=e.model?.id?`\nModel: ${e.model.id}${e.model.path?` (${e.model.path})`:``}`:``;const i=e.capabilities?`\nCapabilities: ${[e.capabilities.vision?`vision`:null,e.capabilities.draft?`draft`:null].filter(Boolean).join(`, `)||`text only`}`:``;const a=e.endpoints?`\nEndpoints: ${Object.entries(e.endpoints).map(([e,t])=>`${e}=${t}`).join(` `)}`:``;const o=e.loadError?`\nLoad error: ${e.loadError}`:``;return`llama.cpp server: ${t}${n}${e.state===`ready`?``:` (${e.state})`}${r}${i}${a}${o}`}function resolveLocalProviderPolicyBlockGuidance(e,t){switch(e){case`plugins-disabled`:return{message:`Plugin loading is disabled for this config.`,fix:`Fix: ${formatCliCommand(`openclaw config set plugins.enabled true --strict-json`)}, or select another memory provider.`};case`blocked-by-denylist`:return{message:`Installed plugin "${t}" is blocked by plugins.deny.`,fix:`Fix: Remove "${t}" from plugins.deny, or select another memory provider.`};case`plugin-disabled`:return{message:`Installed plugin "${t}" is disabled for this config.`,fix:`Fix: Enable it: ${formatCliCommand(`openclaw plugins enable ${t} --accept-capabilities`)}, or select another memory provider.`};case`not-in-allowlist`:return{message:`Installed plugin "${t}" is omitted from plugins.allow.`,fix:`Fix: Include "${t}" in plugins.allow, or select another memory provider.`}}return e} //!src/commands/doctor-memory-search.ts const MEMORY_EMBEDDING_PROVIDER_AUTH_IDS=/* @__PURE__ */ new Map([[`github-copilot`,`github-copilot`],[`openai`,`openai`],[`gemini`,`google`],[`voyage`,`voyage`],[`mistral`,`mistral`],[`bedrock`,`amazon-bedrock`]]);function hasConfiguredAwsSdkAuthForProvider(e,t){if(findNormalizedProviderValue(t.models?.providers,e)?.auth===`aws-sdk`)return true;return(findNormalizedProviderValue(t.auth?.order,e)??(t.auth?.profiles?Object.keys(t.auth.profiles):[])).some(n=>isConfiguredAwsSdkAuthProfileForProvider({cfg:t,provider:e,profileId:n}))}function isOpenAICompatibleMemoryProvider(e,t){const n=normalizeProviderId(e);if(n===`openai-compatible`)return true;if(MEMORY_EMBEDDING_PROVIDER_AUTH_IDS.has(n))return false;const r=findNormalizedProviderValue(t.models?.providers,e);if(!r)return false;const i=normalizeProviderId(r.api??``);if(i===`openai-compatible`||OPENAI_COMPATIBLE_MODEL_APIS.has(i))return true;return!i&&Boolean(normalizeOptionalString(r.baseUrl))}function hasActiveAlternateMemoryPluginSlot(e){const t=normalizePluginsConfig(e.plugins);const n=t.slots.memory;if(!t.enabled||!n||n===defaultSlotIdForKey(`memory`)||t.deny.includes(n)||!Object.hasOwn(t.entries,n))return false;const r=t.entries[n];if(!r||r.enabled===false)return false;return r.enabled===true||r.config!==void 0}function resolveActiveMemoryConversationRecallSupport(e,t){const n=normalizePluginsConfig(e.plugins);const r=n.entries[`active-memory`];const i=isRecord(r?.config)?r.config:void 0;const a=e.plugins?.entries?.[`active-memory`]?.config;const o=isRecord(a)?a:void 0;return{available:t&&i?.enabled!==false,providerSupported:n.slots.memory===defaultSlotIdForKey(`memory`),memorySearchAllowed:!Array.isArray(o?.toolsAllow)||o.toolsAllow.some(e=>typeof e===`string`&&e.trim().toLowerCase()===`memory_search`)}}function describeActiveMemoryEnablementSteps(e){const t=normalizePluginsConfig(e.plugins);const n=t.entries[`active-memory`];const r=isRecord(n?.config)?n.config:void 0;const i=[];if(!t.enabled)i.push(`set plugins.enabled=true`);if(t.deny.includes(`active-memory`))i.push(`remove active-memory from plugins.deny`);if(t.allow.length>0&&!t.allow.includes(`active-memory`))i.push(`add active-memory to plugins.allow`);if(n?.enabled!==true)i.push(`set plugins.entries.active-memory.enabled=true`);if(r?.enabled===false)i.push(`set plugins.entries.active-memory.config.enabled=true`);if(i.length===0)return`Enable the Active Memory plugin`;const a=i.join(`, `);return a.charAt(0).toUpperCase()+a.slice(1)}function inspectRememberAcrossConversationsHealth(e){if(!resolveRememberAcrossConversations(e.cfg,e.agentId))return false;const t=resolveActiveMemoryConversationRecallSupport(e.cfg,e.activeMemoryEnabled);if(!t.available)e.report(`Remember across conversations is effectively enabled for agent "${e.agentId}", but the Active Memory plugin is disabled. ${describeActiveMemoryEnablementSteps(e.cfg)}, or set memory.search.rememberAcrossConversations to false.`);else if(!t.providerSupported)e.report(`Remember across conversations is effectively enabled for agent "${e.agentId}", but the current memory provider does not support protected private transcript recall. Set memory.search.rememberAcrossConversations to false or use that provider's own recall path; advanced Active Memory can still use its recall tools.`);else if(!t.memorySearchAllowed)e.report(`Remember across conversations is effectively enabled for agent "${e.agentId}", but Active Memory does not allow memory_search. Add memory_search to the plugin toolsAllow list or set memory.search.rememberAcrossConversations to false.`);return true}async function noteMemorySearchHealth(e,t){await inspectMemorySearchHealth(e,t??{},({text:e})=>note(e,`Memory search`))}async function collectMemorySearchHealthFindings(e){const t=[];await inspectMemorySearchHealth(e.cfg,{env:e.env,includeWorkspaceMemoryHealth:false,skipAuthProfileResolution:true,allowExecSecretRefs:e.allowExecSecretRefs===true,gatewayMemoryProbe:{checked:false,ready:false,skipped:true}},({finding:e})=>{if(e)t.push(e)});return t}async function inspectMemorySearchHealth(e,t,n){const r=captureRuntimeConfig(e);const i=resolveMemoryDoctorAgentScopes(r);const a=tryResolveDefaultAgentId(r);const o=i.some(({agentId:e})=>resolveRememberAcrossConversations(r,e))&&isInstalledPluginEnabled(loadPluginRegistrySnapshot({config:r,env:t.env}),`active-memory`,r,t.env);const s=i.length>1;for(const e of i){if(t.includeWorkspaceMemoryHealth!==false)await noteWorkspaceMemoryHealth({agentId:e.agentId,workspaceDir:e.workspaceDir,labelAgent:s});const report=(t,r=`memory.search.provider`,i=false,a=false)=>{const o=formatMemoryDoctorAgentMessage(e.agentId,s,t);const[c,...l]=o.split(` `);const u=l.map(e=>e.trimEnd()).join(` `).trim();n({text:o,finding:a||i&&!s?null:{checkId:`core/doctor/memory-search`,severity:`warning`,message:(c??o).trim(),path:r,...u?{fixHint:u}:{}}})};await inspectMemorySearchHealthForAgent(r,e,o,{...t,gatewayMemoryProbe:e.agentId===a||t.gatewayMemoryProbe?.skipped?t.gatewayMemoryProbe:void 0},report)}}async function inspectMemorySearchHealthForAgent(e,t,n,r,i){const{agentId:a,agentDir:o}=t;const s=resolveMemorySearchConfig(e,a);if(!s){const t=inspectRememberAcrossConversationsHealth({cfg:e,agentId:a,activeMemoryEnabled:n,report:i});i(t?`Remember across conversations is effectively enabled for agent "${a}", but memory search is disabled. Enable memory search or set memory.search.rememberAcrossConversations to false.`:`Memory search is explicitly disabled (enabled: false).`,`memory.search.provider`,!t);return}const c=s.provider;const l=normalizePluginsConfig(e.plugins);if(c===`local`&&!l.enabled){const e=resolveLocalProviderPolicyBlockGuidance(`plugins-disabled`,c);i([e.message,``,e.fix,``,`Verify: ${formatCliCommand(`openclaw memory status --deep`)}`].join(` `));return}const u=resolveActiveMemoryBackendConfig({cfg:e,agentId:a});if(u?.backend===`provider-runtime`){let t=null;let n=`unavailable`;let o=`provider unavailable`;try{const{resolvedConfig:i,diagnostics:s,hadUnresolvedTargets:c}=await resolveCommandSecretRefsViaGateway({config:e,commandName:`doctor`,targetIds:getMemoryEmbeddingCommandSecretTargetIds(e),mode:`read_only_status`,allowLocalExecSecretRefs:r.allowExecSecretRefs===true});if(c)throw new Error(s.join(` `));const l=await getActiveMemoryProviderCore({cfg:i,agentId:a,purpose:`status`,context:{authority:{kind:`host`,operation:`status`},assertCurrent(){}}});t=l.provider;if(t){const e=await t.health();n=e.status;o=e.message??`no provider message`}else o=l.error??o}catch(e){o=formatErrorMessage(e)}finally{await t?.close().catch(()=>{})}i(n===`ready`?`Not applicable: ${u.providerId} uses the provider runtime; see its health.\nProvider health: ${n}${o?` (${o})`:``}.`:`Memory provider "${u.providerId}" is ${n}${o?`: ${o}`:``}.\nCheck the provider's configuration and service availability.`,`plugins.slots.memory`,false,n===`ready`);return}inspectRememberAcrossConversationsHealth({cfg:e,agentId:a,activeMemoryEnabled:n,report:i});const d=hasConfiguredMemorySecretInput(s.remote?.apiKey);if(!u){if(r?.gatewayMemoryProbe?.checked&&r.gatewayMemoryProbe.ready)return;if(hasActiveAlternateMemoryPluginSlot(e))return;i(`No active memory plugin is registered for the current config.`,`plugins.slots.memory`);return}if(s.sessionSourceExcluded)i(`Memory search for agent "${a}" requests the "sessions" source, but session indexing is disabled. Set memory.search.experimental.sessionMemory to true for this agent, or enable memory.search.rememberAcrossConversations for private cross-conversation recall.`,`memory.search.sources`,false,true);if(c===`none`)return;if(c===`local`){const t=r?.gatewayMemoryProbe?.runtimeFacts;if(r?.gatewayMemoryProbe?.checked&&r.gatewayMemoryProbe.ready){if(t)i(formatLocalRuntimeDoctorNote(t));return}const n=hasLocalEmbeddings(s.local);const o=Boolean(normalizeOptionalString(s.local.modelPath))&&!n;const u=r?.gatewayMemoryProbe?.error?.trim();const d=u&&u!==t?.loadError?u:null;const f=r.env??process.env;const p=loadPluginManifestRegistryForPluginRegistry({config:e,env:f,includeDisabled:true});const m=listProviderPolicyOwners(c,p);if(m.length===0){i(getMissingLocalMemoryEmbeddingProviderMessage());return}const h=m.map(e=>({owner:e,policyBlock:resolveManifestOwnerBasePolicyBlock({plugin:e,normalizedConfig:l})}));const g=h.filter(({policyBlock:e})=>!e).map(({owner:e})=>e);const _=g.length>0?await loadProviderPolicyArtifactsAsync(g):null;const v=_?{owner:_.owner,policyBlock:null}:h.find(({policyBlock:e})=>e);if(!v)throw new Error(`Unable to resolve the installed provider owner for "${c}".`);const{owner:y,policyBlock:b}=v;const x=_?.surface;const S=b?void 0:x?.inspectEmbeddingProviderSetup;const C=S?await S({config:e,env:f,agentId:a,provider:c}):null;const w=C?.reason.trim();const T=C?.fixHint?.trim();const E=!b&&!S?`Fix: Update the installed plugin: ${formatCliCommand(`openclaw plugins update ${y.id}`)}`:null;const D=b?resolveLocalProviderPolicyBlockGuidance(b,y.id):null;if(r?.gatewayMemoryProbe?.skipped&&!o&&!C&&!D&&!E)return;const O=Boolean(d||t?.loadError);i([t?formatLocalRuntimeDoctorNote(t):null,t?``:null,n?`Memory search provider is set to "local" and a local model path is configured, but local embeddings are not confirmed ready.`:`Memory search provider is set to "local", but local embeddings are not confirmed ready.`,w?`Setup: ${w}`:null,D?.message,E?`Installed plugin "${y.id}" does not provide current local-memory setup diagnostics.`:null,d&&d!==w?`Gateway check: ${d}`:null,``,D?.fix??E??(T?`Fix: ${T}`:o?`Fix: Set memory.search.local.modelPath to an existing GGUF file, or remove it to use the managed default.`:O?`Fix: Repair the llama.cpp server problem reported by the Gateway.`:null),``,`Verify: ${formatCliCommand(`openclaw memory status --deep`)}`].filter(Boolean).join(` `));return}const f=isOpenAICompatibleMemoryProvider(c,e);const p=f&&!(normalizeOptionalString(s.remote?.baseUrl)??normalizeOptionalString(findNormalizedProviderValue(e.models?.providers,c)?.baseUrl));if(f&&(p||!normalizeOptionalString(s.model))){const e=p?`memory.search.remote.baseUrl`:`memory.search.model`;const t=p?`embeddings endpoint`:`embedding model`;const n=p?`the /v1 endpoint for your embeddings server`:`the embedding model id your server expects`;const r=p?`http://127.0.0.1:1234/v1`:`text-embedding-bge-m3`;i([`Memory search provider is set to "${c}" but no OpenAI-compatible ${t} was configured.`,`Set ${e} to ${n}.`,``,`Fix:`,`- ${formatCliCommand(`openclaw config set ${e} ${r}`)}`,``,`Verify: ${formatCliCommand(`openclaw memory status --deep`)}`].join(` `),e);return}if(c===`ollama`||c===`lmstudio`||f){if(r?.gatewayMemoryProbe?.checked&&r.gatewayMemoryProbe.ready)return;if(r?.gatewayMemoryProbe?.skipped)return;const e=buildGatewayProbeWarning(r?.gatewayMemoryProbe);i([e?`Memory search provider "${c}" is configured, but the gateway reports embeddings are not ready.`:`Memory search provider "${c}" is configured, but the gateway could not confirm embeddings are ready.`,e,`Verify: ${formatCliCommand(`openclaw memory status --deep`)}`].filter(Boolean).join(` `));return}if(d||await hasApiKeyForProvider(c,e,o,{skipProfileResolution:r?.skipAuthProfileResolution===true}))return;if(r?.gatewayMemoryProbe?.checked&&r.gatewayMemoryProbe.ready){i([`Memory search provider is set to "${c}" but the API key was not found in the CLI environment.`,`The running gateway reports memory embeddings are ready for the default agent.`,`Verify: ${formatCliCommand(`openclaw memory status --deep`)}`].join(` `));return}const m=buildGatewayProbeWarning(r?.gatewayMemoryProbe);const h=resolvePrimaryMemoryProviderEnvVar(c);i([`Memory search provider is set to "${c}" but no API key was found.`,`Without working primary or fallback embeddings, memory sync stops for explicitly configured providers or existing vector indexes; new and changed memory files are not indexed.`,m?m:null,``,`Fix (pick one):`,`- Set ${h} in your environment`,`- Configure credentials: ${formatCliCommand(`openclaw configure --section model`)}`,`- For keyword-only recall without a key, set memory.search.provider to "none" for this agent (including any agent override), then run ${formatCliCommand(`openclaw memory index --force --agent ${a}`)}`,``,`Then rerun: ${formatCliCommand(`openclaw doctor`)}`].join(` `))}function hasLocalEmbeddings(e){const t=normalizeOptionalString(e.modelPath);if(!t)return false;if(/^(hf:|https?:)/i.test(t))return true;const n=resolveUserPath(t);return safeStatSync(n)?.isFile()??false}async function hasApiKeyForProvider(e,t,n,r){const i=MEMORY_EMBEDDING_PROVIDER_AUTH_IDS.get(e)??e;if(isSecretRef(findNormalizedProviderValue(t.models?.providers,i)?.apiKey)||resolveEnvApiKey(i)||resolveUsableCustomProviderApiKey({cfg:t,provider:i}))return true;if(r?.skipProfileResolution===true){if(i===`amazon-bedrock`)return hasConfiguredAwsSdkAuthForProvider(i,t);const e=findNormalizedProviderValue(t.auth?.order,i);return e===void 0?hasAuthProfileStoreSourceForProvider(i,n):hasAuthProfileStoreSourceForProvider(i,n,{profileIds:e})}if(i!==`amazon-bedrock`&&!hasAnyAuthProfileStoreSource(n))return false;try{await resolveApiKeyForProviderCore({provider:i,cfg:t,agentDir:n});return true}catch{return false}}function resolvePrimaryMemoryProviderEnvVar(e){if(e===`openai`)return`OPENAI_API_KEY`;const t=MEMORY_EMBEDDING_PROVIDER_AUTH_IDS.get(e);return(t?getProviderEnvVarsCore(t)[0]:void 0)??`${e.toUpperCase()}_API_KEY`}function buildGatewayProbeWarning(e){if(!e?.checked||e.ready)return null;const t=e.error?.trim();return t?`Gateway memory check for default agent is not ready: ${t}`:`Gateway memory check for default agent is not ready.`}export{collectMemorySearchHealthFindings,noteMemorySearchHealth};