UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

327 lines (326 loc) • 13.1 kB
import { t as stableStringify } from "./stable-stringify-vqde_3tT.mjs"; import { C as resolveSessionAgentIds } from "./agent-scope-config-DmXgFGKP.mjs"; import { t as _usingCtx } from "./usingCtx-rhpPzaNq.mjs"; import "./agent-scope-BwB8YH6y.mjs"; import { p as readAdmittedRunOperatorAuthority } from "./admitted-run-context-D3Jvk_f_.mjs"; import { d as toolPolicyRestrictsTools, f as pickSandboxToolPolicy } from "./tool-policy-BR4v75RA.mjs"; import { I as isCoreCodingSurfaceToolName, z as listCoreToolFactoryDescriptors } from "./tool-catalog-C1ALpCJD.mjs"; import { c as normalizeToolPolicyName } from "./tool-policy-shared-BHvBopvF.mjs"; import { i as getPluginToolMeta } from "./tool-metadata-rqUpUHlb.mjs"; import { a as prepareSessionCapabilityRead } from "./subagent-session-store--G7wm9iV.mjs"; import { n as getSessionRowProjection } from "./session-row-projection-access-CjLImwLs.mjs"; import { s as hasSessionControlAuthority } from "./conversation-capability-profile-Be5DqCww.mjs"; import { s as withReadySessionRows } from "./session-row-prepared-read-B4U_T7SO.mjs"; import { a as DirectoryCache } from "./target-resolver-DZ4okT3e.mjs"; import { a as getInProcessGatewayToolContext } from "./in-process-gateway-Cy0xoBmg.mjs"; import { t as applyEmbeddedAttemptToolsAllow } from "./attempt-tool-construction-plan-Cp8YcsYs.mjs"; import { n as loadPairedComputerUseAvailabilityForSurface } from "./computer-use-node-capabilities-BLaoxSqZ.mjs"; import { n as readMcpLoopbackToolName, t as buildMcpToolSchema } from "./mcp-http.schema-D3hjCI90.mjs"; import { t as loadNodeExecAvailability } from "./node-exec-availability-BNnoURMg.mjs"; import { t as assertCompletionGrantLineage } from "./tool-resolution-completion-MPyjTfxy.mjs"; import { t as resolveGatewayScopedTools } from "./tool-resolution-BQOau9-l.mjs"; //#region 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 = e.skillLibraryAuthoring ? { libraryAuthoring: e.skillLibraryAuthoring } : void 0; const u = { ...a, messageActionTurnCapability: e.messageActionTurnCapability, memoryAudience: e.memoryAudience, toolsAllow: r, cfg: e.cfg, authProfileStore: e.authProfileStore, onYield: e.onYield, skillWorkshop: l, 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 d = await resolveGatewayScopedTools(u, e.assertCurrent); e.assertCurrent(); const f = t === "exact" ? applyGrantToolsAllow(d.tools, r) : applyPolicyToolsAllow(d.tools, r); const p = buildMcpToolSchema(f); d.captureFinalCronCreatorTools?.(new Set(p.map((e) => e.name))); return { agentId: d.agentId, workspaceDir: d.workspaceDir, tools: f, toolSchema: p, 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(); } } /** Resolves loopback-visible tools from the exact names carried by a minted grant. */ function resolveMcpLoopbackScopedTools(e) { return resolveMcpLoopbackCatalog(e, "exact"); } /** Materializes runtime policy expressions against the concrete loopback catalog. */ function resolveMcpLoopbackPolicyTools(e) { return resolveMcpLoopbackCatalog(e, "policy"); } /** * Hard-enforces a per-run grant allowlist on the loopback surface. Both * tools/list and tools/call consume this list, so a tool outside the * allowlist can be neither discovered nor executed even when the CLI runs * with a bypass permission mode. An empty allowlist fails closed. */ 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 })}`; } /** Short-lived cache for loopback tool lists keyed by session/channel context. */ 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(); } }; //#endregion export { resolveMcpLoopbackPolicyTools as n, resolveMcpLoopbackScopedTools as r, McpLoopbackToolCache as t };