UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

715 lines (714 loc) • 28.4 kB
import { r as truncateUtf16Safe } from "./utf16-slice-CuDyEXgS.mjs"; import { o as getPluginRuntimeGatewayRequestScope } from "./gateway-request-scope-BvvDhs5D.mjs"; import { r as isIncognitoSessionKey } from "./session-key-DW1jcHbM.mjs"; import "./session-key-CqAyZeVk.mjs"; import { r as resolveAgentConfig } from "./agent-scope-config-DmXgFGKP.mjs"; import { S as resolveRuntimeConfigCacheKey } from "./runtime-snapshot-WbwbY5b7.mjs"; import { a as validateBoardPromptAuthorizeParams, c as validateBoardWidgetContent, i as validateBoardGetParams, l as validateBoardWidgetGrantParams, n as validateBoardDataReadParams, o as validateBoardUpdateParams, r as validateBoardEventParams, s as validateBoardWidgetAppViewParams, t as validateBoardActionParams, u as validateBoardWidgetPutParams } from "./src-BX8OAe1J.mjs"; import "./agent-scope-BwB8YH6y.mjs"; import { a as captureExternalSessionCommitGuard, o as composeSessionSourceAssertion } from "./session-source-authority-TlTpfRVE.mjs"; import { o as capturePluginRegistryLifecycleEpoch, v as isPluginRegistryLifecycleEpochActive } from "./registry-lifecycle-CJjWnl-y.mjs"; import { l as getActivePluginRegistry } from "./runtime-ezCEpumg.mjs"; import { n as validateJsonSchemaValue } from "./schema-validator-NvoOmaWr.mjs"; import { f as isGatewaySubordinateWorkAdmissionClosed } from "./gateway-work-admission-79pid1hQ.mjs"; import { n as operatorScopeSatisfied } from "./operator-scope-compat-CpFHu-FC.mjs"; import { l as withSystemEventOwner } from "./system-event-ownership-zDxyv2EM.mjs"; import { o as resolveSessionStorePathForScope } from "./session-store-path-BIJyO4vM.mjs"; import { l as enqueueSystemEvent } from "./system-events-BFJiZPP0.mjs"; import { t as ErrorCodes } from "./gateway-error-details-B69XiHdh.mjs"; import { p as errorShape } from "./error-codes-BzF7aRQ0.mjs"; import { t as SessionMutationAuthorizationChangedError } from "./session-mutation-authorization-error-0K0ZVV7q.mjs"; import { n as readSessionEntriesFromStoreInWorker } from "./session-entry-read-runtime-1Fp1sybj.mjs"; import { o as runWithSessionActorStorage } from "./session-actor-storage-binding-DMwpDsij.mjs"; import { r as BoardValidationError } from "./board-layout-C0d9b7cg.mjs"; import { s as buildWidgetDocument } from "./sandbox-host-C-9vv4vO.mjs"; import { a as resolveGitHubActionsRequest, n as GITHUB_ACTIONS_BINDING_ID, r as GITHUB_ACTIONS_GRANT_PREFIX } from "./github-actions-capability-ByBXQPgn.mjs"; import { c as normalizeBoardWidgetDeclared, s as boardWidgetHasGrantedTool } from "./board-store-32jhOjw-.mjs"; import { t as acquireSessionActorStorage } from "./session-actor-storage-acquisition-bj-qIczw.mjs"; import { r as resolveRequestedSessionStoreTarget } from "./session-store-key-CEwU3noi.mjs"; import "./session-accessor.entry-f0bkn7cv.mjs"; import { a as loadSessionEntryReadOnly } from "./session-accessor.sqlite-exact-read-CbvqUmsG.mjs"; import { a as createBoardViewTicket, c as verifyBoardViewTicket, i as buildBoardWidgetFrameUrl, n as BOARD_VIEW_TICKET_TTL_MS, o as requireBoardViewTicketAuthority, r as BoardGatewayUnavailableError } from "./board-view-ticket-CRLjSnq1.mjs"; import { S as CORE_BOARD_DATA_BINDING_IDS } from "./loader-runtime-load-Ba16vW6K.mjs"; import { n as captureGatewayOperatorRunAuthority } from "./operator-run-authority-3Pm3MQDA.mjs"; import { s as readExecApprovalsPolicyReadOnlyAsync } from "./exec-approvals-store-BUZ9uOWF.mjs"; import { r as resolveExecDefaults } from "./exec-defaults-BaVI-sJD.mjs"; import { r as emitSessionsChanged } from "./session-change-event-DFgDuXAu.mjs"; import { r as defineValidatedGatewayMethod, t as assertValidParams } from "./validation-DwNk6A-B.mjs"; import { r as readCanvasDocumentHtmlSource } from "./documents-A82Go5Wp.mjs"; import { c as resolveExecAutoReviewDecision } from "./exec-auto-review-CaqSrKQR.mjs"; import { c as resolveMcpAppAllowedToolNames, f as mintMcpAppViewFromTranscript, s as resolveMcpAppActiveView, u as supportsMcpAppInteraction } from "./mcp-app-operations-Qv9yxlnB.mjs"; import { n as buildBoardWidgetSandboxPath } from "./board-sandbox-CCY2jPEI.mjs"; import { n as prepareGatewayRequestHandler } from "./lazy-core-handlers-CzhLmFts.mjs"; import { t as coreGatewayHandlers } from "./core-handlers-DV1pwVG7.mjs"; import { t as boardStore } from "./board-store-DbsKOphK.mjs"; import { t as withAuthorizedBoardWidgetView } from "./board-widget-view-B57zgDE_.mjs"; import { h as sessionObserverScopeKey } from "./session-observer-model-CoCBcuix.mjs"; import { n as retainCanvasWidgetRead } from "./canvas-widget-read-CndFwB6U.mjs"; import { createHash } from "node:crypto"; import { isDeepStrictEqual } from "node:util"; //#region src/boards/board-notices.ts const BOARD_EVENT_MAX_BYTES = 8192; const BOARD_EVENT_DEDUPE_MS = 5e3; const recentNotices = /* @__PURE__ */ new Map(); var BoardEventPayloadError = class extends Error { constructor(...e) { super(...e); this.name = "BoardEventPayloadError"; } }; function appendBoardEventNotice(e) { const t = e.payload; let n; try { const e = JSON.stringify(t); n = e === void 0 ? String(t) : e; } catch { throw new BoardEventPayloadError("board event payload must be JSON serializable"); } if (Buffer.byteLength(n, "utf8") > BOARD_EVENT_MAX_BYTES) throw new BoardEventPayloadError(`board event payload exceeds ${BOARD_EVENT_MAX_BYTES} bytes`); const r = Date.now(); const i = `${e.agentId ?? ""}\0${e.sessionKey}\0${e.widget}`; const a = recentNotices.get(i); if (a?.summary === n && r - a.at < BOARD_EVENT_DEDUPE_MS) return false; recentNotices.set(i, { summary: n, at: r }); for (const [e, t] of recentNotices) if (r - t.at >= BOARD_EVENT_DEDUPE_MS) recentNotices.delete(e); const o = { sessionKey: e.sessionKey, contextKey: `dashboard:${e.widget}:${r}` }; const s = "[dashboard] "; const c = ` on widget ${e.widget}`; const l = 488 - c.length; const u = n.length <= l ? n : `${truncateUtf16Safe(n, Math.max(0, l - 1))}…`; return enqueueSystemEvent(`${s}${u}${c}`, e.agentId ? withSystemEventOwner(o, e.agentId) : o); } //#endregion //#region src/gateway/board-host-tools.ts function assertBoardCapabilityParamsSize(e, t) { if (Buffer.byteLength(JSON.stringify(e), "utf8") > 8192) throw new BoardValidationError("invalid_operation", `board widget ${t} params exceed 8192 UTF-8 bytes`); } function boardDataBindingCapability(e, t) { return e === "github.actions.runs" ? resolveGitHubActionsRequest(t).capability : e; } /** Retained reads/actions own the exact live widget grant, not just its Gateway. */ function captureBoardCapabilityAuthority(e, t, n, r) { const i = captureBoardRequestAuthority(n); const a = verifyBoardViewTicket(t); if (!a) throw new BoardValidationError("invalid_operation", "board widget view ticket is invalid"); requireBoardViewTicketAuthority(a, n.context); const resolveSession = (e) => { i.assertActive(); const t = n.context.getRuntimeConfig(); const r = resolveRequestedSessionStoreTarget(t, e.sessionKey, e.agentId); if (!r.ok || r.value.sessionKey !== e.sessionKey) throw new BoardValidationError("invalid_operation", "board widget session identity changed; reload the dashboard"); return r.value; }; const o = resolveSession(a); return { ...i, boardSession: o, useCurrent: async (i) => await withAuthorizedBoardWidgetView(e, t, (e) => { const t = resolveSession(e); if (t.agentId !== o.agentId || t.sessionKey !== o.sessionKey) throw new BoardValidationError("invalid_operation", "board widget session identity changed; reload the dashboard"); if (!boardWidgetHasGrantedTool(e.document.declared, e.document.grantState, r)) throw new BoardValidationError("invalid_operation", `board widget tool is not granted: ${r}`); return i(); }, { gatewayContext: n.context }) }; } function captureBoardRequestAuthority(e) { const t = e.context; const n = t.resolveGatewayContext; if (!n) throw new BoardGatewayUnavailableError(); const r = t.getGatewayMethodRegistry?.(); const i = getPluginRuntimeGatewayRequestScope()?.pluginRegistry ?? getActivePluginRegistry() ?? void 0; const a = i ? capturePluginRegistryLifecycleEpoch(i) : void 0; const o = composeSessionSourceAssertion([captureExternalSessionCommitGuard(e.sessionMutationCommitGuard), captureExternalSessionCommitGuard(e.sessionMutationAuthorization?.assertCurrent)], (o) => { try { e.signal?.throwIfAborted(); o(); if (isGatewaySubordinateWorkAdmissionClosed() || n() !== t || t.resolveGatewayContext !== n || r && t.getGatewayMethodRegistry?.() !== r || i && (!a || !isPluginRegistryLifecycleEpochActive(i, a))) throw new BoardGatewayUnavailableError(); } catch (e) { if (e instanceof BoardGatewayUnavailableError) throw e; throw new BoardGatewayUnavailableError(); } }); o(); return { assertActive: o, ...i ? { pluginRegistry: i } : {}, ticketAuthority: { gatewayContext: t, resolveGatewayContext: n, ...i ? { pluginRegistry: i } : {} } }; } function respondBoardError(e, t) { if (e instanceof BoardGatewayUnavailableError) { t(false, void 0, errorShape(ErrorCodes.UNAVAILABLE, e.message)); return; } if (e instanceof BoardValidationError || e instanceof BoardEventPayloadError) { t(false, void 0, errorShape(ErrorCodes.INVALID_REQUEST, e.message)); return; } t(false, void 0, errorShape(ErrorCodes.UNAVAILABLE, String(e))); } function isBoardDataBindingId(e) { return CORE_BOARD_DATA_BINDING_IDS.includes(e); } async function invokeGatewayHandler(e, t, n, r, i, a) { let o; await i.useCurrent(async () => { try { await e({ ...r, req: { ...r.req, method: t, params: n }, params: n, respond: (e, t, n) => { o ??= { kind: "reply", ok: e, payload: t, error: n }; } }); } catch (e) { o = { kind: "thrown", error: e }; } }); await i.useCurrent(() => { if (!o) a(false, void 0, errorShape(ErrorCodes.INVALID_REQUEST, `${t} did not return a result`)); else if (o.kind === "thrown") respondBoardError(o.error, a); else if (!o.ok) a(false, void 0, errorShape(ErrorCodes.INVALID_REQUEST, o.error?.message || `${t} failed`)); else a(true, o.payload); }); } async function readBoardDataBinding(e, t, n, r, i) { if (e === "github.actions.runs") { const { readBoardGitHubActions: e } = await import("./github-actions-read-BEUKWtRp.mjs"); return await e(t, n.context, r, i); } if (isBoardDataBindingId(e)) return await invokeGatewayHandler(await prepareGatewayRequestHandler(coreGatewayHandlers[e]), e, t, e === "usage.status" ? { ...n, client: null } : n, r, i); const a = r.pluginRegistry?.dashboardDataBindings.get(e); if (!a) throw new BoardValidationError("invalid_operation", `board widget data binding is not allowed: ${e}`); return await invokeGatewayHandler(a.handler, a.method, t, n, r, i); } async function runBoardActionVerb(e, t, n, r, i) { const a = r.pluginRegistry?.dashboardActionVerbs.get(e); if (!a) throw new BoardValidationError("invalid_operation", `board widget action verb is not allowed: ${e}`); if (a.paramShape) { const n = validateJsonSchemaValue({ schema: a.paramShape, cacheKey: `dashboard-action:${a.pluginId}:${a.id}`, value: t }); if (!n.ok) throw new BoardValidationError("invalid_operation", `board widget action params do not match ${e}: ${n.errors.map((e) => e.text).join(", ")}`); } return await invokeGatewayHandler(a.handler, a.method, t, n, r, i); } async function triggerBoardCronJob(e, t, n, r) { return await invokeGatewayHandler(await prepareGatewayRequestHandler(coreGatewayHandlers["cron.run"]), "cron.run", { id: e, mode: "force" }, t, n, r); } //#endregion //#region src/gateway/board-widget-approval.ts /** One bounded assessment cache per Board handler owner, never a cache of grant authority. */ function createBoardWidgetApprovalResolver() { const e = /* @__PURE__ */ new Set(); let t; let n; return async (r) => { const { cfg: i, agentId: a, sessionKey: o, name: s, content: c, declared: l } = r; const u = resolveRuntimeConfigCacheKey(i); const d = { sessionKey: o, agentId: a }; const f = isIncognitoSessionKey(o); const p = r.incognitoSession; if (p && (!f || p.agentId !== a || p.sessionKey !== o)) throw new Error("Widget approval belongs to another incognito session"); const assertPrepared = () => { p?.assertCurrent(); }; const m = p && structuredClone(p.entry); const [h, g] = await Promise.all([readExecApprovalsPolicyReadOnlyAsync(), p ? m : f ? loadSessionEntryReadOnly(d) : readSessionEntriesFromStoreInWorker({ agentId: a, storePath: resolveSessionStorePathForScope(d, i), sessionKeys: [o], snapshotFields: [] }).then((e) => e.entries.find((e) => e.sessionKey === o)?.entry)]); assertPrepared(); if (t !== u || n !== h.revision) { e.clear(); t = u; n = h.revision; } const _ = resolveExecDefaults({ cfg: i, agentId: a, sessionKey: o, sessionEntry: g ?? null, execApprovals: h.file }).mode; if (_ === "ask") return; if (_ !== "auto") return _ === "full" ? "granted" : "rejected"; const v = !f && h.revision && c.kind === "html" ? createHash("sha256").update(JSON.stringify([ a, s, c, l ])).digest("hex") : void 0; if (v && e.has(v)) return "granted"; const { createModelExecAutoReviewer: y } = await import("./exec-auto-reviewer-BABANvdR.mjs"); assertPrepared(); const b = await resolveExecAutoReviewDecision(y({ cfg: i, agentId: a, reviewer: resolveAgentConfig(i, a)?.tools?.exec?.reviewer ?? i.tools?.exec?.reviewer }), { kind: "board-widget", name: s, declared: l, agent: { id: a, sessionKey: o } }); assertPrepared(); switch (b.decision) { case "allow-once": if (b.risk !== "low") return "rejected"; if (v && t === u && n === h.revision) { if (e.size >= 256) e.delete(e.keys().next().value); e.add(v); } return "granted"; case "deny": case "ask": return "rejected"; default: throw new Error("Unsupported widget review decision", { cause: b }); } }; } //#endregion //#region src/gateway/server-methods/board-handler-context.ts function defineBoardMethod(...[e, t, n]) { return defineValidatedGatewayMethod(e, t, async (e) => { try { await n(e); } catch (t) { if (t instanceof SessionMutationAuthorizationChangedError) { e.respond(false, void 0, t.error); return; } respondBoardError(t, e.respond); } }); } function resolveBoardSession(e, t, n, r = "write") { const i = t.getRuntimeConfig(); const a = resolveRequestedSessionStoreTarget(i, e.sessionKey, e.agentId, r); if (!a.ok) { n(false, void 0, a.error); return; } return a.value; } function projectBoardSnapshot(e, t) { return { ...e, sessionKey: sessionObserverScopeKey(e.sessionKey, t) }; } function broadcastBoardChanged(e, t, { sessionKey: n, revision: r }, i) { e.broadcast("board.changed", { sessionKey: n, revision: r, ...i !== void 0 ? { widget: i } : {} }, { sessionKeys: [t.sessionKey], agentId: t.agentId }); } //#endregion //#region src/gateway/server-methods/board.ts function createBoardHandlers(e) { const t = createBoardWidgetApprovalResolver(); return { "board.get": defineBoardMethod("board.get", validateBoardGetParams, async (t) => { const { params: n, respond: r, context: i, client: a } = t; const o = a?.remoteControlUiIngress; const s = captureBoardRequestAuthority(t); const c = resolveBoardSession(n, i, r, "read"); if (!c) return; const { snapshot: l, htmlViewMetadata: u } = await e.getSnapshotWithHtmlViewMetadata(c); s.assertActive(); const d = projectBoardSnapshot(l, c.agentId); let f = i.getMcpAppSandboxPort?.(); let p = null; for (const e of l.widgets) { if (e.grantState !== "none" && e.grantState !== "granted") continue; const t = u.get(e.name); if (!t || t.revision !== e.revision) continue; if (f === void 0 && i.ensureSandboxHostPort) f = await i.ensureSandboxHostPort(); s.assertActive(); const { ticket: n } = createBoardViewTicket({ agentId: c.agentId, sessionKey: l.sessionKey, name: e.name, revision: e.revision, viewGeneration: t.viewGeneration, authority: { ...s.ticketAuthority, remoteIngressPrincipal: a?.internal?.remoteIngressPrincipal } }); e.frameUrl = buildBoardWidgetFrameUrl({ sessionKey: d.sessionKey, name: e.name, ticket: n }); if (o) e.frameUrl = new URL(e.frameUrl, o.publicOrigin).href; e.viewTicket = n; e.viewTicketTtlMs = BOARD_VIEW_TICKET_TTL_MS; e.viewGeneration = t.viewGeneration; if (f !== void 0) { e.sandboxUrl = buildBoardWidgetSandboxPath(t); if (o) e.sandboxUrl = new URL(e.sandboxUrl, o.sandboxOrigin).href; e.sandboxPort = f; if (p === null) { const e = o?.sandboxOrigin ?? i.getRuntimeConfig?.().mcp?.apps?.sandboxOrigin; p = e ? new URL(e).origin : void 0; } if (p) e.sandboxOrigin = p; } } s.assertActive(); r(true, d); }), "board.update": defineBoardMethod("board.update", validateBoardUpdateParams, async (t) => { const { params: n, respond: r, context: i } = t; const a = captureBoardRequestAuthority(t); const o = resolveBoardSession(n, i, r); if (!o) return; a.assertActive(); const s = projectBoardSnapshot(await e.applyOps(o, n.ops, { assertCurrent: a.assertActive }), o.agentId); a.assertActive(); if (n.ops.length > 0) { emitSessionsChanged(i, { sessionKey: o.sessionKey, agentId: o.agentId, reason: "board" }); broadcastBoardChanged(i, o, s); } r(true, s); }), "board.widget.put": defineBoardMethod("board.widget.put", validateBoardWidgetPutParams, async (n) => { const { params: r, respond: i, context: a } = n; if (r.content.kind === "registered") throw new BoardValidationError("invalid_operation", "Registered board widgets were removed; use HTML widgets instead."); const o = captureBoardRequestAuthority(n); let s; let c; const l = { ...o, assertActive: composeSessionSourceAssertion([o.assertActive], (e) => { e(); s?.authority.assertCurrent(); c?.read.assertCurrent(); }) }; const u = resolveBoardSession(r, a, i); if (!u) return; const d = { assertCurrent: l.assertActive, authorize: l.assertActive }; const f = await acquireSessionActorStorage(u, { authority: d, lifetime: { assertCurrent: l.assertActive, assertReadable: l.assertActive } }); if (isIncognitoSessionKey(u.sessionKey) && !f) throw new BoardValidationError("not_found", "board session no longer exists"); try { const { declared: d, ...p } = r; let m; let h = d; let resolveMcpAppInteraction; if (r.content.kind === "canvas-doc") { if (n.client?.connect && !operatorScopeSatisfied("operator.read", n.client.connect.scopes ?? [])) c = await retainCanvasWidgetRead(n, { ...u, docId: r.content.docId }); l.assertActive(); if (c?.pending) { i(false, void 0, errorShape(ErrorCodes.UNAVAILABLE, "Waiting for the widget result.", { retryable: true })); return; } const e = await readCanvasDocumentHtmlSource(r.content.docId); l.assertActive(); if (e.cspSandbox !== "scripts") throw new BoardValidationError("invalid_operation", `canvas document is not script-enabled: ${r.content.docId}`); m = { kind: "html", html: e.html }; } else if (r.content.kind === "mcp-app") { s = await captureGatewayOperatorRunAuthority({ client: n.client, context: a, hasCurrentClientAuthority: n.hasCurrentClientAuthority, invocationAuthority: { assertCurrent: o.assertActive, signal: n.signal } }); l.assertActive(); const e = await resolveMcpAppActiveView({ ...u, viewId: r.content.viewId, cfg: a.getRuntimeConfig(), requesterId: s?.authority.profileId }); l.assertActive(); const { view: t } = e; if (!t.toolCallId) throw new BoardValidationError("invalid_operation", "MCP App view is missing its originating tool call"); resolveMcpAppInteraction = () => supportsMcpAppInteraction(t); let i = await resolveMcpAppInteraction(); l.assertActive(); const c = i ? await resolveMcpAppAllowedToolNames(e) : []; l.assertActive(); if (i) { i = await resolveMcpAppInteraction(); l.assertActive(); } m = { kind: "mcp-app", descriptor: { serverName: t.serverName, toolName: t.toolName, uiResourceUri: t.uiResourceUri, toolCallId: t.toolCallId }, interactive: i }; h = i && c.length > 0 ? { tools: c } : void 0; } else m = r.content; const g = m.kind === "mcp-app" ? { kind: m.kind, descriptor: m.descriptor } : m; if (!assertValidParams(g, validateBoardWidgetContent, "board.widget.put content", i)) return; h = normalizeBoardWidgetDeclared(h); const _ = m.kind === "html" ? { kind: "html", html: buildWidgetDocument(r.title ?? r.name, m.html, { connectOrigins: h?.netOrigins }) } : m; const v = { ...p, ...u, content: _, ...h ? { declared: h } : {} }; let y; if (m.kind === "html" && h?.tools?.some((e) => e.startsWith("github.actions.runs:"))) { const { prepareBoardGitHubIdentity: e } = await import("./github-actions-read-BEUKWtRp.mjs"); y = await e(a, { ...l, boardSession: u }); } const putWidget = () => e.putWidget(v, { ...resolveMcpAppInteraction ? { resolveMcpAppInteraction } : {}, assertCurrent: composeSessionSourceAssertion([y?.assertSelected ?? l.assertActive], (e) => { e(); const t = a.getRuntimeConfig(); const n = resolveRequestedSessionStoreTarget(t, u.sessionKey, u.agentId); if (!n.ok || n.value.sessionKey !== u.sessionKey) throw new BoardValidationError("invalid_operation", "board session changed; retry"); }) }); const putAndApprove = async () => { let n = y ? await y.start(putWidget) : await putWidget(); l.assertActive(); const r = n.widgets.find((e) => e.name === n.resolvedWidgetName); if (r?.grantState === "pending") { const i = f?.actor.storage.readCurrent({ type: "session.entry.read", input: { sessionKey: u.sessionKey } }, f.authority); const assertApprovalCurrent = () => { l.assertActive(); if (!f) return; const e = f.actor.storage.readCurrent({ type: "session.entry.read", input: { sessionKey: u.sessionKey } }, f.authority); if (!i || !e || [ "sessionId", "lifecycleRevision", "sandbox", "sandboxMode", "createdActor", "execHost", "execNode", "permissionMode" ].some((t) => !isDeepStrictEqual(e[t], i[t]))) throw new BoardValidationError("invalid_operation", "board approval policy changed; retry"); }; const o = await t({ cfg: a.getRuntimeConfig(), ...u, name: n.resolvedWidgetName, content: _, declared: h ?? {}, ...f ? { incognitoSession: { agentId: u.agentId, sessionKey: u.sessionKey, entry: i, assertCurrent: assertApprovalCurrent } } : {} }); l.assertActive(); if (o) n = { ...await e.grant(u, n.resolvedWidgetName, o, r.revision, r.instanceId, { assertCurrent: assertApprovalCurrent }), resolvedWidgetName: n.resolvedWidgetName }; } l.assertActive(); n = projectBoardSnapshot(n, u.agentId); emitSessionsChanged(a, { sessionKey: u.sessionKey, agentId: u.agentId, reason: "board" }); broadcastBoardChanged(a, u, n, n.resolvedWidgetName); i(true, n); }; await (f ? runWithSessionActorStorage(f, putAndApprove) : putAndApprove()); } finally { try { await f?.actor.release(); } finally { c?.read.release(); s?.release(); } } }), "board.widget.grant": defineBoardMethod("board.widget.grant", validateBoardWidgetGrantParams, async (t) => { const { params: n, respond: r, context: i } = t; const a = captureBoardRequestAuthority(t); const o = resolveBoardSession(n, i, r); if (!o) return; a.assertActive(); const s = projectBoardSnapshot(await e.grant(o, n.name, n.decision, n.revision, n.instanceId, { assertCurrent: a.assertActive }), o.agentId); a.assertActive(); broadcastBoardChanged(i, o, s); r(true, s); }), "board.widget.appView": defineBoardMethod("board.widget.appView", validateBoardWidgetAppViewParams, async (t) => { const { params: n, respond: r, context: i } = t; const a = captureBoardRequestAuthority(t); const o = resolveBoardSession(n, i, r); if (!o) return; const s = (await e.getSnapshot(o)).widgets.find((e) => e.name === n.name); const c = await e.readWidgetMcpApp(o, n.name); a.assertActive(); if (!s || s.contentKind !== "mcp-app" || s.revision !== n.revision || s.instanceId !== n.instanceId || !c || c.revision !== n.revision || c.instanceId !== n.instanceId) throw new BoardValidationError("not_found", `board MCP App widget not found: ${n.name}`); const l = c.interactive && c.grantState === "granted"; const u = l ? async () => { const t = await e.readWidgetMcpApp(o, n.name); return t?.interactive === true && t.grantState === "granted" && t.revision === n.revision && t.instanceId === n.instanceId; } : void 0; const d = await mintMcpAppViewFromTranscript({ cfg: i.getRuntimeConfig(), ...o, descriptor: c.descriptor, allowedAppToolNames: new Set(l ? c.declaredTools : []), ...u ? { authorizeAppInteraction: u } : {}, readOnly: !l }); a.assertActive(); if (!d) throw new Error("Pinned MCP App source is no longer available"); r(true, { viewId: d.view.viewId, expiresAtMs: d.view.expiresAtMs }); }), "board.event": defineBoardMethod("board.event", validateBoardEventParams, async (t) => { const { params: n, respond: r, context: i } = t; const a = captureBoardRequestAuthority(t); const publish = (e) => { a.assertActive(); const t = appendBoardEventNotice({ sessionKey: e.sessionKey, agentId: e.agentId, widget: e.name, payload: n.payload }); r(true, { ok: true, appended: t }); }; if ("ticket" in n) await withAuthorizedBoardWidgetView(e, n.ticket, publish, { gatewayContext: i }); else { const t = resolveBoardSession(n, i, r); if (!t) return; await e.useSnapshot(t, (e) => { if (!e.widgets.some((e) => e.name === n.widget)) throw new BoardValidationError("not_found", `board widget not found: ${n.widget}`); publish({ ...t, name: n.widget }); }); } }), "board.prompt.authorize": defineBoardMethod("board.prompt.authorize", validateBoardPromptAuthorizeParams, async (t) => { const { params: n, respond: r, context: i } = t; const a = captureBoardRequestAuthority(t); await withAuthorizedBoardWidgetView(e, n.ticket, ({ document: e }) => { a.assertActive(); r(true, { confirmationRequired: !boardWidgetHasGrantedTool(e.declared, e.grantState, "prompt") }); }, { gatewayContext: i }); }), "board.data.read": defineBoardMethod("board.data.read", validateBoardDataReadParams, async (t) => { const { params: n, respond: r } = t; const i = n.params ?? {}; assertBoardCapabilityParamsSize(i, "data binding"); const a = captureBoardCapabilityAuthority(e, n.ticket, t, boardDataBindingCapability(n.bindingId, i)); await readBoardDataBinding(n.bindingId, i, t, a, r); }), "board.action": defineBoardMethod("board.action", validateBoardActionParams, async (t) => { const { params: n, respond: r } = t; const i = "jobId" in n ? `cron.trigger:${n.jobId}` : n.action; const a = captureBoardCapabilityAuthority(e, n.ticket, t, i); if ("jobId" in n) { await triggerBoardCronJob(n.jobId, t, a, r); return; } const o = n.params ?? {}; assertBoardCapabilityParamsSize(o, "action"); await runBoardActionVerb(n.action, o, t, a, r); }) }; } const boardHandlers = createBoardHandlers(boardStore); //#endregion export { boardHandlers };