openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
3 lines • 10.9 kB
JavaScript
import{t as stableStringify}from"./stable-stringify-Cy0VZ0ci.mjs";import{C as resolveSessionAgentIds}from"./agent-scope-config-CG9CFpGX.mjs";import{t as _usingCtx}from"./usingCtx-CUVyQ_FT.mjs";import{B as listCoreToolFactoryDescriptors,I as isCoreCodingSurfaceToolName}from"./tool-catalog-Du-FMXr3.mjs";import{c as normalizeToolPolicyName}from"./tool-policy-shared-KKJW93v9.mjs";import"./agent-scope-Dw5XRSEh.mjs";import{p as readAdmittedRunOperatorAuthority}from"./admitted-run-context-xwC9VVgE.mjs";import{d as toolPolicyRestrictsTools,f as pickSandboxToolPolicy}from"./tool-policy-Bsc3kFBH.mjs";import{i as getPluginToolMeta}from"./tool-metadata-Cb5nBZYD.mjs";import{a as prepareSessionCapabilityRead}from"./subagent-session-store-ClkR5Yv6.mjs";import{n as getSessionRowProjection}from"./session-row-projection-access-w2LnU_PB.mjs";import{s as hasSessionControlAuthority}from"./conversation-capability-profile-DiRRWN6T.mjs";import{c as withReadySessionRows}from"./session-row-prepared-read-B7-BN1nJ.mjs";import{a as getInProcessGatewayToolContext}from"./in-process-gateway-vrnZpIbq.mjs";import{t as applyEmbeddedAttemptToolsAllow}from"./attempt-tool-construction-plan-DxPA0wqy.mjs";import{a as DirectoryCache}from"./target-resolver-DE3emqE4.mjs";import{n as loadPairedComputerUseAvailabilityForSurface}from"./computer-use-node-capabilities-BnQzbhL1.mjs";import{n as readMcpLoopbackToolName,t as buildMcpToolSchema}from"./mcp-http.schema-BA-97xdx.mjs";import{t as loadNodeExecAvailability}from"./node-exec-availability-BSZXGuuk.mjs";import{t as assertCompletionGrantLineage}from"./tool-resolution-completion-D_aLhjIH.mjs";import{t as resolveGatewayScopedTools}from"./tool-resolution-Ct1MtyA9.mjs";
//!src/gateway/mcp-http.runtime.ts
const TOOL_CACHE_TTL_MS=3e4;const TOOL_CACHE_MAX_ENTRIES=256;const NATIVE_TOOL_EXCLUDE=new Set(listCoreToolFactoryDescriptors().map(({name:e})=>e).filter(isCoreCodingSurfaceToolName));async function captureMcpLoopbackScope(e){const t=e.context.senderIsOwner===false&&Boolean(e.context.sessionKey.trim()&&e.context.sessionId);const n=t?getInProcessGatewayToolContext():void 0;const r=n?getSessionRowProjection(n):void 0;const i=await prepareSessionCapabilityRead(()=>{e.signal?.throwIfAborted();assertCompletionGrantLineage(e);hasSessionControlAuthority(readAdmittedRunOperatorAuthority(e.admittedRunContext));if(e.isGrantCurrent?.()===false)throw new Error(`MCP tool grant is no longer current`);if(t&&(getInProcessGatewayToolContext()!==n||getSessionRowProjection(n)!==r))throw new Error(`MCP tool preparation belongs to a retired Gateway`)});return{...e,projection:r,assertCurrent:i.read,[Symbol.dispose]:i.release}}function captureMcpCatalogSessionFacts(e){if(!e.projection)return;const{sessionAgentId:t}=resolveSessionAgentIds({config:e.cfg,sessionKey:e.context.sessionKey,agentId:e.context.agentId});const n=e.projection.capture({agentId:t,key:e.context.sessionKey});return{projection:e.projection,generation:n?.generation,revision:n?.databaseFactsRevision}}function isMcpCatalogSessionCurrent(e,t){const n=captureMcpCatalogSessionFacts(t);return e.sessionFacts?.projection===n?.projection&&e.sessionFacts?.generation===n?.generation&&e.sessionFacts?.revision===n?.revision}function resolveMediatedNativeTools(e,t){if(t===`exact`)return new Set((e??[]).map(e=>normalizeToolPolicyName(e)).filter(e=>NATIVE_TOOL_EXCLUDE.has(e)));if(e===void 0)return/* @__PURE__ */ new Set;return new Set(applyEmbeddedAttemptToolsAllow(Array.from(NATIVE_TOOL_EXCLUDE,e=>({name:e})),e).map(e=>e.name))}async function resolveNodeExecScope(e,t){if(!(!e.context.trustedInternalHandoff&&!toolPolicyRestrictsTools(pickSandboxToolPolicy(e.context.conversationToolPolicy))&&e.context.nodeExecAllowed===true&&!e.defaultMediatedToolNames?.length&&resolveMediatedNativeTools(e.context.toolsAllow,t).size===0))return e;const n=await loadNodeExecAvailability(e.signal);e.assertCurrent();return{...e,nodeExecAvailability:n}}function isComputerAllowedByMcpScope(e,t){const{toolsAllow:n}=e.context;if(t===`exact`)return n===void 0||n.some(e=>normalizeToolPolicyName(e)===`computer`);return applyEmbeddedAttemptToolsAllow([{name:`computer`}],n).length===1}async function resolvePairedComputerNodeScope(e,t){e.assertCurrent();if(!(isComputerAllowedByMcpScope(e,t)&&e.context.modelHasVision!==false))return{params:e};const n=await resolveMcpLoopbackTools(e,t);e.assertCurrent();const r=n.tools.some(e=>readMcpLoopbackToolName(e)===`computer`);const i=await loadPairedComputerUseAvailabilityForSurface({computerAllowed:r,modelHasVision:e.context.modelHasVision,signal:e.signal});e.assertCurrent();if(!i)return{params:e,policyResolved:n};const a={params:{...e,pairedComputerUseAvailability:i}};return i.prepared?a:{...a,policyResolved:n}}async function resolveMcpLoopbackTools(e,t,n){return withReadyMcpSession(e,()=>n&&isMcpCatalogSessionCurrent(n,e)?n:constructMcpLoopbackTools(e,t))}async function withReadyMcpSession(e,t){e.assertCurrent();const{sessionKey:n,sessionId:r,senderIsOwner:i}=e.context;if(!e.projection||!r||i!==false)return t();const{sessionAgentId:a}=resolveSessionAgentIds({config:e.cfg,sessionKey:n,agentId:e.context.agentId});let o;do{o=await withReadySessionRows(e.projection,()=>[{agentId:a,key:n}],()=>{e.assertCurrent();return{sessionFacts:captureMcpCatalogSessionFacts(e),sharingRevision:e.projection?.sharingRevision}});e.assertCurrent()}while(o.sharingRevision===void 0||o.sharingRevision!==e.projection.sharingRevision||!isMcpCatalogSessionCurrent(o,e));return t()}async function constructMcpLoopbackTools(e,t){e.assertCurrent();const n=captureMcpCatalogSessionFacts(e);const{toolsAllow:r,webSearchDisabled:i,...a}=e.context;const o=new Set(NATIVE_TOOL_EXCLUDE);if(i)o.add(`web_search`);const s=r===void 0&&(a.trustedInternalHandoff||toolPolicyRestrictsTools(pickSandboxToolPolicy(a.conversationToolPolicy)))?new Set(NATIVE_TOOL_EXCLUDE):resolveMediatedNativeTools(r,t);for(const t of e.defaultMediatedToolNames??[]){const e=normalizeToolPolicyName(t);if(!NATIVE_TOOL_EXCLUDE.has(e))throw new Error(`Unknown host-owned coding tool: ${t}`);s.add(e)}for(const e of s)o.delete(e);const c=a.nodeExecAllowed===true&&s.size===0;if(c)o.delete(`exec`);const l={...a,messageActionTurnCapability:e.messageActionTurnCapability,memoryAudience:e.memoryAudience,toolsAllow:r,cfg:e.cfg,authProfileStore:e.authProfileStore,onYield:e.onYield,skillLibraryAuthoring:e.skillLibraryAuthoring,bundledTools:e.bundledTools,nativeCronCreatorToolAllowlist:a.nativeCronCreatorToolAllowlist??void 0,agentDir:e.authProfileStoreAgentDir,conversationReadOrigin:`delegated`,surface:`loopback`,admittedRunContext:e.admittedRunContext,sessionEventSourcePolicy:e.sessionEventSourcePolicy,isGrantCurrent:e.isGrantCurrent,excludeToolNames:o,mediatedToolNames:s,includeNodeExecTool:c,nodeExecAvailable:e.nodeExecAvailability?.isAvailable,pairedNodeComputerUse:e.pairedComputerUseAvailability?.prepared};const u=await resolveGatewayScopedTools(l,e.assertCurrent);e.assertCurrent();const d=t===`exact`?applyGrantToolsAllow(u.tools,r):applyPolicyToolsAllow(u.tools,r);const f=buildMcpToolSchema(d);u.captureFinalCronCreatorTools?.(new Set(f.map(e=>e.name)));return{agentId:u.agentId,workspaceDir:u.workspaceDir,tools:d,toolSchema:f,sessionFacts:n}}async function resolveMcpLoopbackCatalog(e,t){try{var n=_usingCtx();const r=await resolvePairedComputerNodeScope(await resolveNodeExecScope(n.u(await captureMcpLoopbackScope(e)),t),t);for(;;){const e=await resolveMcpLoopbackTools(r.params,t,r.policyResolved);r.params.assertCurrent();if(isMcpCatalogSessionCurrent(e,r.params))return e}}catch(e){n.e=e}finally{n.d()}}function resolveMcpLoopbackScopedTools(e){return resolveMcpLoopbackCatalog(e,`exact`)}function resolveMcpLoopbackPolicyTools(e){return resolveMcpLoopbackCatalog(e,`policy`)}function applyGrantToolsAllow(e,t){if(!t)return e;const n=new Set(t.map(e=>normalizeToolPolicyName(e)).filter(Boolean));return e.filter(e=>{const t=readMcpLoopbackToolName(e);return t!==void 0&&n.has(normalizeToolPolicyName(t))})}function applyPolicyToolsAllow(e,t){if(!t)return e;const n=e.flatMap(e=>{const t=readMcpLoopbackToolName(e);return t?[{name:t,tool:e}]:[]});return applyEmbeddedAttemptToolsAllow(n,t,{toolMeta:e=>getPluginToolMeta(e.tool)}).map(e=>e.tool)}function buildMcpLoopbackToolCacheKey(e){const{context:t}=e;return`${e.grantToken??``}\u0000${stableStringify({context:{...t,clientCaps:[...new Set(t.clientCaps??[])].toSorted(),toolsAllow:t.toolsAllow?[...new Set(t.toolsAllow)].toSorted():void 0,pinnedWidgetAuthoring:t.pinnedWidgetAuthoring===true,currentInboundAudio:t.currentInboundAudio===true,sourceReplyOnly:t.sourceReplyOnly===true,requireExplicitMessageTarget:t.requireExplicitMessageTarget===true,nodeExecAllowed:t.nodeExecAllowed===true,delegationCapability:t.delegationCapability===`full`?void 0:t.delegationCapability},admittedRunInstance:e.admittedRunContext?.operationalRunInstance,defaultMediatedToolNames:e.defaultMediatedToolNames,sessionControlsAllowed:hasSessionControlAuthority(readAdmittedRunOperatorAuthority(e.admittedRunContext)),authProfileStoreAgentDir:e.authProfileStoreAgentDir,yieldContextCacheKey:e.yieldContextCacheKey,nodeExecAvailability:e.nodeExecAvailability?.cacheKey,pairedComputerUseAvailability:e.pairedComputerUseAvailability?.cacheKey})}`}var McpLoopbackToolCache=class{#e=new DirectoryCache(TOOL_CACHE_TTL_MS,TOOL_CACHE_MAX_ENTRIES);#t=/* @__PURE__ */ new Map;#n=0;async resolve(e){try{var t=_usingCtx();const n=this.#n;const r=await resolveNodeExecScope(t.u(await captureMcpLoopbackScope(e)),`exact`);for(;;){r.assertCurrent();const e=buildMcpLoopbackToolCacheKey(r);let t=this.#e.get(e,r.cfg);if(t){t=await withReadyMcpSession(r,()=>{const t=this.#e.get(e,r.cfg);return t&&isMcpCatalogSessionCurrent(t,r)?t:void 0});r.assertCurrent();if(t&&isMcpCatalogSessionCurrent(t,r))return t}const i=await resolvePairedComputerNodeScope(r,`exact`);r.assertCurrent();const{params:a}=i;const o=buildMcpLoopbackToolCacheKey(a);const s=await withReadyMcpSession(a,async()=>{const e=this.#e.get(o,a.cfg);if(e&&isMcpCatalogSessionCurrent(e,a))return e;const t=i.policyResolved&&isMcpCatalogSessionCurrent(i.policyResolved,a)?i.policyResolved:await constructMcpLoopbackTools(a,`exact`);a.assertCurrent();if(n===this.#n&&isMcpCatalogSessionCurrent(t,a)){this.#e.set(o,t,a.cfg);if(a.grantToken){const e=this.#t.get(a.grantToken)??/* @__PURE__ */ new Set;e.add(a.cfg);this.#t.set(a.grantToken,e)}}return t});a.assertCurrent();if(isMcpCatalogSessionCurrent(s,a))return s}}catch(e){t.e=e}finally{t.d()}}evictGrant(e){this.#n+=1;const t=this.#t.get(e);if(!t)return false;const n=`${e}\u0000`;for(const e of t)this.#e.clearMatching(e=>e.startsWith(n),e);this.#t.delete(e);return true}clear(){this.#n+=1;this.#e.clear();this.#t.clear()}};export{resolveMcpLoopbackPolicyTools as n,resolveMcpLoopbackScopedTools as r,McpLoopbackToolCache as t};