UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

309 lines (308 loc) • 12.8 kB
import { r as resolveGlobalMap } from "./global-singleton-D7yf05nR.mjs"; import { a as asOptionalRecord } from "./record-coerce-CVPuDqcc.mjs"; import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs"; import { n as notifyListeners } from "./listeners-Cb2-CnP8.mjs"; import { n as normalizeAgentId } from "./agent-id-CQjtp2ft.mjs"; import { j as parseAgentSessionKey } from "./session-key-CqAyZeVk.mjs"; import { a as normalizeSandboxHostCsp, o as resolveSandboxHostPort, r as buildSandboxHostPath } from "./sandbox-host-C-9vv4vO.mjs"; import { i as logWarn } from "./logger-CIwfuhOU.mjs"; import { t as getSessionMcpRequestSignal } from "./agent-bundle-mcp-request-context-B-LzHCC-.mjs"; import { a as projectMcpAppModelContextInput, i as leaseMcpAppModelContextForTurn, n as clearMcpAppModelContextForView, u as completeDeferredSessionMcpRuntimeRetirement } from "./mcp-app-model-context-Nt0AWggG.mjs"; import { randomUUID } from "node:crypto"; //#region src/agents/mcp-app-sandbox.ts const normalizeMcpAppCsp = normalizeSandboxHostCsp; const buildMcpAppSandboxPath = buildSandboxHostPath; const resolveMcpAppSandboxPort = resolveSandboxHostPort; //#endregion //#region src/agents/mcp-ui-resource.ts const MCP_APP_RESOURCE_MIME_TYPE = "text/html;profile=mcp-app"; const MCP_APP_RESOURCE_MAX_BYTES = 2097152; const MCP_APP_VIEW_TTL_MS = 6e5; const MCP_APP_VIEW_MAX_ENTRIES = 32; const MCP_APP_VIEW_MAX_BYTES = 6291456; const MCP_APP_VIEW_STORE_MAX_BYTES = 67108864; const MCP_APP_VIEW_STORE_KEY = Symbol.for("openclaw.mcpAppViewStore"); /** Retain only the bounded view identity needed for late channel materialization. */ function readMcpAppChannelView(e) { const t = asOptionalRecord(asOptionalRecord(e)?.details); const n = asOptionalRecord(t?.mcpAppPreview); const r = asOptionalRecord(n?.view); const i = asOptionalRecord(n?.mcpApp); const a = typeof i?.viewId === "string" ? i.viewId.trim() : ""; const o = typeof r?.id === "string" ? r.id.trim() : ""; if (!a || o !== a) return; return { viewId: a }; } function getViewStore() { return resolveGlobalMap(MCP_APP_VIEW_STORE_KEY); } function deleteView(e, t) { const n = getViewStore(); const r = n.get(e); if (!r || t && r !== t) return; clearTimeout(r.expiryTimer); r.toolApprovalGrants?.clear(); clearMcpAppModelContextForView(r.runtime, r); notifyListeners(r.disposeCallbacks ?? [], void 0, (e) => { logWarn(`mcp-app: view cleanup failed: ${formatErrorMessage(e)}`); }); r.disposeCallbacks?.clear(); r.releaseRuntimeLease?.(); n.delete(e); completeDeferredSessionMcpRuntimeRetirement(r.runtime).catch((e) => { logWarn(`mcp-app: deferred runtime cleanup failed: ${formatErrorMessage(e)}`); }); } /** Retire only the exact runtime-owned view, including form preview children. */ function releaseMcpAppView(e, t) { const n = getViewStore().get(e); if (n?.runtime === t) deleteView(e, n); } function pruneViewStore(e = 0, t = false) { const n = getViewStore(); const r = Date.now(); for (const [e, t] of n) if (t.expiresAtMs <= r) deleteView(e, t); let i = Array.from(n.values()).reduce((e, t) => e + (t.byteSize ?? 0), 0); while (n.size + (t ? 1 : 0) > MCP_APP_VIEW_MAX_ENTRIES || i + e > MCP_APP_VIEW_STORE_MAX_BYTES) { const e = n.keys().next().value; if (e === void 0) return; const t = n.get(e); i -= t?.byteSize ?? 0; if (t) deleteView(e, t); } } function measureViewBytes(e, t, n) { const r = JSON.stringify({ toolInput: t, toolResult: n }); const i = Buffer.byteLength(e, "utf8") + Buffer.byteLength(r, "utf8"); if (i > MCP_APP_VIEW_MAX_BYTES) throw new Error(`MCP App view data exceeds ${MCP_APP_VIEW_MAX_BYTES} bytes`); return i; } function assertBoundedViewDescriptor(e) { if (e.viewId && (e.viewId.length > 128 || !e.viewId.startsWith("mcp-app-")) || !e.serverName || e.serverName.length > 256 || !e.toolName || e.toolName.length > 256 || !e.uiResourceUri.startsWith("ui://") || e.uiResourceUri.length > 2048 || e.toolCallId !== void 0 && e.toolCallId.length > 512) throw new Error("MCP App preview descriptor exceeds safe limits"); } function normalizePermissions(e) { const t = asOptionalRecord(e); if (!t) return; const n = {}; for (const e of [ "camera", "clipboardWrite", "geolocation", "microphone" ]) if (asOptionalRecord(t[e])) n[e] = {}; return Object.keys(n).length > 0 ? n : void 0; } function decodeResourceHtml(e) { if (typeof e.text === "string") { if (Buffer.byteLength(e.text, "utf8") > MCP_APP_RESOURCE_MAX_BYTES) throw new Error(`MCP App resource exceeds ${MCP_APP_RESOURCE_MAX_BYTES} bytes`); return e.text; } if (typeof e.blob !== "string") throw new Error("MCP App resource must provide text or base64 blob content"); const t = Math.ceil(MCP_APP_RESOURCE_MAX_BYTES / 3) * 4 + 4; if (e.blob.length > t) throw new Error(`MCP App resource exceeds ${MCP_APP_RESOURCE_MAX_BYTES} bytes`); const n = Buffer.from(e.blob, "base64"); if (n.byteLength > MCP_APP_RESOURCE_MAX_BYTES) throw new Error(`MCP App resource exceeds ${MCP_APP_RESOURCE_MAX_BYTES} bytes`); return n.toString("utf8"); } async function resolveListingUiMeta(e, t, n) { try { const r = await e.listResources?.(t, { failureBackoff: "ignore" }); const { _meta: i } = (Array.isArray(r) ? r : Array.isArray(asOptionalRecord(r)?.resources) ? asOptionalRecord(r)?.resources : []).map(asOptionalRecord).find((e) => e?.uri === n) ?? {}; return asOptionalRecord(asOptionalRecord(i)?.ui); } catch (e) { logWarn(`mcp-app: failed to read optional listing metadata for ${n} from "${t}": ${formatErrorMessage(e)}`); return; } } async function fetchMcpAppView(e) { let t; try { assertBoundedViewDescriptor(e); const n = e.agentId ? normalizeAgentId(e.agentId) : parseAgentSessionKey(e.runtime.sessionKey)?.agentId; if (!n) throw new Error("MCP App view requires a resolved session owner"); if (!e.runtime.readResource) return; const r = asOptionalRecord(await e.runtime.readResource(e.serverName, e.uiResourceUri, { failureBackoff: "ignore" })); const i = Array.isArray(r?.contents) ? r.contents : []; if (i.length !== 1) throw new Error(`expected one MCP App resource, received ${i.length}`); const a = asOptionalRecord(i[0]); if (!a || a.mimeType !== MCP_APP_RESOURCE_MIME_TYPE) throw new Error(`resource must use ${MCP_APP_RESOURCE_MIME_TYPE}`); const o = decodeResourceHtml(a); const s = measureViewBytes(o, e.toolInput, e.toolResult); const { _meta: c, meta: l } = a; const u = asOptionalRecord(asOptionalRecord(c ?? l)?.ui); const d = u ? void 0 : await resolveListingUiMeta(e.runtime, e.serverName, e.uiResourceUri); getSessionMcpRequestSignal()?.throwIfAborted(); const f = u ?? d; const p = asOptionalRecord(asOptionalRecord(c)?.["openai/ui"]); const m = ["inline", "fullscreen"]; const h = p?.availableDisplayModes; const g = Array.isArray(h) ? m.filter((e) => h.includes(e)) : void 0; const _ = p?.preferredDisplayMode === "inline" || p?.preferredDisplayMode === "fullscreen" ? p.preferredDisplayMode : void 0; const v = g || _ ? { availableDisplayModes: g ?? [_], ..._ ? { preferredDisplayMode: _ } : {} } : void 0; const y = e.displayMode ?? _ ?? "inline"; const b = normalizeMcpAppCsp(f?.csp); const x = normalizePermissions(f?.permissions); const S = `${e.toolName} UI`; const C = e.viewId ?? `mcp-app-${randomUUID()}`; t = e.runtime.acquireLease?.(); deleteView(C); pruneViewStore(s, true); const w = { viewId: C, runtime: e.runtime, agentId: n, sessionId: e.runtime.sessionId, serverName: e.serverName, toolName: e.toolName, uiResourceUri: e.uiResourceUri, ...e.toolCallId ? { toolCallId: e.toolCallId } : {}, html: o, ...b ? { csp: b } : {}, ...x ? { permissions: x } : {}, ...e.allowedAppToolNames ? { allowedAppToolNames: new Set(e.allowedAppToolNames) } : {}, ...e.prepareToolCall ? { prepareToolCall: e.prepareToolCall } : {}, ...e.uploadResources ? { uploadResources: e.uploadResources } : {}, ...e.authorizeAppInteraction ? { authorizeAppInteraction: e.authorizeAppInteraction } : {}, ...e.readOnly ? { readOnly: true } : {}, requesterId: e.requesterId, ...e.hostFile ? { hostFile: e.hostFile } : {}, ...e.richModelContextSupported !== void 0 ? { richModelContextSupported: e.richModelContextSupported } : {}, ...e.deepLink ? { deepLink: e.deepLink } : {}, displayMode: g?.length && !g.includes(y) ? g[0] : y, ...v ? { displayModes: v } : {}, toolInput: e.toolInput, toolResult: e.toolResult, expiresAtMs: Date.now() + MCP_APP_VIEW_TTL_MS, requestWindowStartedAtMs: Date.now(), requestCount: 0, toolCallCount: 0, activeRequests: 0, byteSize: s, ...t ? { releaseRuntimeLease: t } : {} }; t = void 0; w.expiryTimer = setTimeout(() => { deleteView(w.viewId, w); }, MCP_APP_VIEW_TTL_MS); w.expiryTimer.unref(); getViewStore().set(C, w); return { viewId: C, title: S, serverName: e.serverName, toolName: e.toolName, uiResourceUri: e.uiResourceUri, ...e.toolCallId ? { toolCallId: e.toolCallId } : {} }; } catch (n) { t?.(); getSessionMcpRequestSignal()?.throwIfAborted(); logWarn(`mcp-app: failed to prepare ${e.uiResourceUri} from "${e.serverName}": ${formatErrorMessage(n)}`); return; } } function getMcpAppViewLease(e, t) { pruneViewStore(); const n = getViewStore().get(e); return n?.runtime === t ? n : void 0; } /** Resolve a live view owned by its originating session, including harness-native runtimes. */ function getMcpAppViewLeaseForSession(e, t, n) { pruneViewStore(); const r = getViewStore().get(e); return r?.runtime.sessionKey === t && r.agentId === normalizeAgentId(n) ? r : void 0; } /** The bounded live-view owner joins managed, discovery and native runtimes for one exact turn. */ async function leaseMcpAppModelContextForSessionTurn(e) { if (!e.sessionKey) return; const t = normalizeAgentId(e.agentId ?? parseAgentSessionKey(e.sessionKey)?.agentId); pruneViewStore(); const n = /* @__PURE__ */ new Map(); for (const r of getViewStore().values()) { if (r.runtime.sessionKey !== e.sessionKey || r.sessionId !== e.sessionId || r.agentId !== t || r.requesterId !== void 0 && r.requesterId !== e.requesterId || r.readOnly || r.allowedAppToolNames === void 0) continue; try { r.runtime.assertOwnerCurrent?.(); if (r.authorizeAppInteraction && !await r.authorizeAppInteraction()) continue; } catch { continue; } if (getMcpAppViewLease(r.viewId, r.runtime) !== r || r.runtime.mcpAppModelContextRevoked) continue; const i = n.get(r.runtime) ?? /* @__PURE__ */ new Set(); i.add(r); n.set(r.runtime, i); } const r = [...n].flatMap(([e, t]) => { const n = leaseMcpAppModelContextForTurn({ runtime: e, views: t }); return n ? [n] : []; }); if (!r.length) return; const i = r.flatMap((e) => e.modelContext); const applyToLeases = (e) => () => { for (const t of r) t[e](); }; return { project: (e) => projectMcpAppModelContextInput(i, e), assertCurrent: applyToLeases("assertCurrent"), commit: applyToLeases("commit"), rollback: applyToLeases("rollback") }; } function acquireMcpAppViewRequest(e, t, n = Date.now()) { if (n - e.requestWindowStartedAtMs >= 6e4) { e.requestWindowStartedAtMs = n; e.requestCount = 0; e.toolCallCount = 0; } if (e.activeRequests >= 4) throw new Error("MCP App request concurrency limit reached"); if (e.requestCount >= 120 || t === "tool" && e.toolCallCount >= 30) throw new Error("MCP App request rate limit reached"); e.requestCount += 1; if (t === "tool") e.toolCallCount += 1; e.activeRequests += 1; let r = false; return () => { if (!r) { r = true; e.activeRequests -= 1; } }; } function buildMcpAppCanvasPayload(e) { assertBoundedViewDescriptor(e); return { kind: "canvas", view: { id: e.viewId, title: e.title }, presentation: { target: "assistant_message", title: e.title, preferred_height: 600, sandbox: "scripts" }, mcpApp: { viewId: e.viewId, serverName: e.serverName, toolName: e.toolName, uiResourceUri: e.uiResourceUri, ...e.toolCallId ? { toolCallId: e.toolCallId } : {}, ...e.originSessionKey ? { originSessionKey: e.originSessionKey } : {}, ...e.resultMetaState ? { resultMetaState: e.resultMetaState } : {} } }; } const testing = { clearViewStore() { for (const [e, t] of getViewStore()) deleteView(e, t); } }; if (process.env.VITEST || false) globalThis[Symbol.for("openclaw.mcpUiResourceTestApi")] = testing; //#endregion export { getMcpAppViewLeaseForSession as a, releaseMcpAppView as c, getMcpAppViewLease as i, buildMcpAppSandboxPath as l, buildMcpAppCanvasPayload as n, leaseMcpAppModelContextForSessionTurn as o, fetchMcpAppView as r, readMcpAppChannelView as s, acquireMcpAppViewRequest as t, resolveMcpAppSandboxPort as u };