UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

551 lines (550 loc) • 19.7 kB
import { l as normalizeOptionalString } from "./string-coerce-CCIiB4H7.mjs"; import { v as normalizeUniqueTrimmedStringList } from "./string-normalization-DLmfYZXI.mjs"; import { t as createDeferredCore } from "./deferred-D0La5CRk.mjs"; import { j as parseAgentSessionKey } from "./session-key-CqAyZeVk.mjs"; import { l as resolveSessionStorePathCore } from "./paths-DvQ5AJvD.mjs"; import { t as _usingCtx } from "./usingCtx-rhpPzaNq.mjs"; import { h as readRuntimeConfig } from "./runtime-snapshot-WbwbY5b7.mjs"; import { t as INTERNAL_MESSAGE_CHANNEL } from "./message-channel-constants-CkbqRgGl.mjs"; import { n as normalizeMessageChannel } from "./message-channel-core-BbYZT1a-.mjs"; import { n as getLoadedChannelPlugin } from "./registry-ByqVE5S3.mjs"; import "./message-channel-DTYVLJT1.mjs"; import { t as ErrorCodes } from "./gateway-error-details-B69XiHdh.mjs"; import { p as errorShape } from "./error-codes-BzF7aRQ0.mjs"; import { n as resolveChannelApprovalCapability } from "./plugins-BoMiRtiY.mjs"; import { l as withSessionEntryReadOnlyInWorker } from "./session-entry-read-runtime-1Fp1sybj.mjs"; import { r as resolveSqliteSessionKey } from "./session-accessor.sqlite-scope-helpers-5_tKUULP.mjs"; import { n as captureMemoryExactSessionReader } from "./session-accessor.memory-exact-read-DXDGhyTq.mjs"; import "./session-accessor.sqlite-scope-Cbj2BdoG.mjs"; import { _ as retainPreparedSessionEntryPredicate } from "./session-accessor.sqlite-entry-cache-publication-state-B4mkg2yK.mjs"; import "./config-CMA-J084.mjs"; import { t as isConfiguredCommandOwner } from "./command-auth-CC1Z19Eh.mjs"; import { t as assertValidParams } from "./validation-DwNk6A-B.mjs"; import { t as canChannelEnforcePluginReviewerPolicy } from "./approval-channel-policy-support-CGr6SWrA.mjs"; import { i as resolveApprovalInitiatingSurfaceStateAsync } from "./exec-approval-surface-B1PpwJWS.mjs"; import { m as isPluginApprovalRequest, s as doesApprovalRequestSelectChannelAccountFromDelivery } from "./approval-request-account-binding-DOCAr58L.mjs"; import { a as readApprovalRequestSource, c as respondPendingApprovalLookupError, i as prepareApprovalSessionAccess, l as respondUnknownOrExpiredApproval, n as isApprovalRecordVisibleToClient, o as resolvePendingApprovalRecord, s as resolveResolvedApprovalRecord } from "./approval-record-lookup-mkMfll81.mjs"; import { isDeepStrictEqual } from "node:util"; //#region src/infra/approval-turn-source.ts /** Returns whether approval replies can route back to the turn's initiating surface. */ async function hasApprovalTurnSourceRoute(e) { const t = normalizeMessageChannel(e.turnSourceChannel); if (!t || t === "webchat" || t === "tui") return false; return (await resolveApprovalInitiatingSurfaceStateAsync({ channel: t, accountId: e.turnSourceAccountId, cfg: readRuntimeConfig(), approvalKind: e.approvalKind ?? "exec", ...e.request ? { request: e.request } : {} })).kind === "enabled"; } //#endregion //#region src/gateway/approval-channel-custody.ts function sameDelivery(e, t) { return e?.sessionId === t?.sessionId && isDeepStrictEqual(e?.delivery, t?.delivery); } function prepareApprovalChannelCustody(e) { const t = e.reviewer.channel.trim().toLowerCase(); const n = e.reviewer.accountId.trim(); const r = e.reviewer.senderId.trim(); if (!t || !n || !r) return null; const i = getLoadedChannelPlugin(t); const a = resolveChannelApprovalCapability(i); if (e.approvalKind === "plugin" && !canChannelEnforcePluginReviewerPolicy(e.cfg, t, a)) return null; const o = a?.authorizeActorActionAsync ?? a?.authorizeActorAction; const configCurrent = () => (!e.getCfg || e.getCfg() === e.cfg) && getLoadedChannelPlugin(t) === i; if (!o) { if (e.approvalKind !== "system-agent" || !isConfiguredCommandOwner(e.cfg, { channel: t, accountId: n, senderId: r })) return null; return { resolverId: `${t}:${n}`, authorizes: async () => configCurrent(), isCurrent: configCurrent, [Symbol.dispose]() {} }; } if (!i || !i.config.listAccountIds(e.cfg).includes(n)) return null; const s = /* @__PURE__ */ new Map(); let c = true; const assertCurrent = () => { e.assertCurrent?.(); if (!c || !configCurrent()) throw new Error("approval reviewer policy changed during preparation"); }; return { resolverId: `${t}:${n}`, async authorizes(a) { const l = s.get(a); if (l) return c && configCurrent() && l.authorized && l.isCurrent(); assertCurrent(); const u = a.request.sessionKey?.trim() ?? ""; const d = parseAgentSessionKey(u)?.agentId ?? a.request.agentId ?? "main"; let f = null; let isCurrent = () => true; let release = () => {}; const p = u && captureMemoryExactSessionReader({ sessionKey: u, agentId: d, storePath: resolveSessionStorePathCore(e.cfg.session?.store, { agentId: d }) }, assertCurrent); try { if (p) { const e = p.read(u, "list"); f = e ?? null; isCurrent = () => sameDelivery(e, p.read(u, "list")); } else if (u && (!a.request.turnSourceAccountId || a.request.turnSourceChannel && a.request.turnSourceChannel.trim().toLowerCase() !== t)) { const t = { agentId: d, storePath: resolveSessionStorePathCore(e.cfg.session?.store, { agentId: d }), sessionKey: u, projection: "list", hydrateSkillPromptRefs: false }; await withSessionEntryReadOnlyInWorker(t, assertCurrent, async (e, t) => { if (!e.ok) throw e.error; f = e.value ?? null; if (t.source) { const n = retainPreparedSessionEntryPredicate({ databaseIdentity: `file:${t.source.databaseIdentity}`, sessionKey: resolveSqliteSessionKey(u, d), entry: e.value, matches: sameDelivery }); isCurrent = n.isCurrent; release = n.release; } }); } const c = e.approvalKind === "plugin" && isPluginApprovalRequest(a) ? a : void 0; const l = i.config.listAccountIds(e.cfg); const m = e.approvalKind === "plugin" && !c ? [] : (await Promise.all(l.map(async (t) => { return (await o({ cfg: e.cfg, accountId: t, senderId: r, action: "approve", approvalKind: e.approvalKind, ...c ? { request: c } : {}, sessionDelivery: f })).authorized ? t : void 0; }))).filter((e) => e !== void 0); assertCurrent(); const h = m.includes(n) && doesApprovalRequestSelectChannelAccountFromDelivery({ cfg: e.cfg, request: a, channel: t, accountId: n, defaultAccountId: i.config.defaultAccountId?.(e.cfg) ?? "", eligibleAccountIds: m }, f); s.set(a, { authorized: h, isCurrent, release }); return h && isCurrent(); } catch (e) { release(); throw e; } }, isCurrent(e) { const t = s.get(e); return c && configCurrent() && t?.authorized === true && t.isCurrent(); }, [Symbol.dispose]() { c = false; for (const e of s.values()) e.release(); s.clear(); } }; } //#endregion //#region src/gateway/server-methods/approval-shared.ts const APPROVAL_ALREADY_RESOLVED_DETAILS = { reason: "APPROVAL_ALREADY_RESOLVED" }; function isApprovalDecision(e) { return e === "allow-once" || e === "allow-always" || e === "deny"; } function bindApprovalRequesterMetadata(e) { e.record.requestedByConnId = e.client?.connId ?? null; e.record.requestedByDeviceId = e.client?.connect?.device?.id ?? null; e.record.requestedByClientId = e.client?.connect?.client?.id ?? null; e.record.requestedByDeviceTokenAuth = e.client?.isDeviceTokenAuth === true; } function bindApprovalReviewerDeviceIds(e) { const t = normalizeUniqueTrimmedStringList(e.deviceIds); if (t.length > 0) e.record.approvalReviewerDeviceIds = t; } function respondApprovalStorageUnavailable(e) { e.context.logGateway?.error?.(`approval ${e.operation} storage failure: ${String(e.error)}`); e.respond(false, void 0, errorShape(ErrorCodes.UNAVAILABLE, `approval ${e.operation} unavailable`)); } function buildRequestedApprovalEvent(e, t) { return { ...t ? { approvalKind: t } : {}, id: e.id, request: e.request, createdAtMs: e.createdAtMs, expiresAtMs: e.expiresAtMs }; } function resolveApprovalDecisionParams(e) { const t = e.rawParams; if (!assertValidParams(t, e.validate, e.methodName, e.respond)) return null; if (!isApprovalDecision(t.decision)) { e.respond(false, void 0, errorShape(ErrorCodes.INVALID_REQUEST, "invalid decision")); return null; } return { inputId: t.id, decision: t.decision, ...t.reviewer ? { reviewer: t.reviewer } : {} }; } function resolveApprovalRequestRecipientConnIds(e) { return e.context.getApprovalClientConnIds?.({ approvalKind: e.approvalKind, excludeConnId: e.excludeConnId, record: e.record, filter: (t) => isApprovalRecordVisibleToClient({ record: e.record, client: t }) }) ?? null; } /** Sends a resolved approval only to clients authorized for its live binding. */ function broadcastApprovalResolvedEvent(e) { const t = e.approvalKind === "system-agent" ? "openclaw.approval.resolved" : `${e.approvalKind}.approval.resolved`; const n = resolveApprovalRequestRecipientConnIds(e); if (n) { e.context.broadcastToConnIds(t, e.event, n, { dropIfSlow: true }); return; } e.context.broadcast(t, e.event, { dropIfSlow: true }); } async function handleApprovalWaitDecision(e) { try { var t = _usingCtx(); const n = normalizeOptionalString(e.inputId) ?? ""; if (!n) { e.respond(false, void 0, errorShape(ErrorCodes.INVALID_REQUEST, "id is required")); return; } const r = await e.manager.getSnapshot(n, e.authority); e.authority?.assertCurrent(); const i = t.u(await prepareApprovalSessionAccess({ ...e, client: e.client ?? null, sources: r ? [readApprovalRequestSource(r)] : [] })); e.authority?.assertCurrent(); const visible = (t) => { const n = e.getCfg?.() ?? e.cfg; return !e.client?.invalidated && isApprovalRecordVisibleToClient({ record: t, client: e.client ?? null, ...n ? { cfg: n } : {}, sessionAccess: i }); }; if (!r || !visible(r)) { e.respond(false, void 0, errorShape(ErrorCodes.INVALID_REQUEST, "approval expired or not found")); return; } e.authority?.bindSource(readApprovalRequestSource(r)); const a = e.manager.awaitDecision(n); if (!a) { e.respond(false, void 0, errorShape(ErrorCodes.INVALID_REQUEST, "approval expired or not found")); return; } const o = await a; e.authority?.assertCurrent(); const s = await e.manager.getSnapshot(n, e.authority) ?? r; e.authority?.assertCurrent(); if (!visible(s)) { respondUnknownOrExpiredApproval(e.respond); return; } const c = e.manager.projectDecisionIfActive(n, o); const l = e.resolveTerminalReason?.(s); e.respond(true, { id: n, decision: c, createdAtMs: s.createdAtMs, expiresAtMs: s.expiresAtMs, terminalReason: l ?? s.terminalReason }, void 0); } catch (e) { t.e = e; } finally { t.d(); } } /** Broadcasts or routes a pending approval request, then responds after acceptance/decision. */ async function handlePendingApprovalRequest(e) { const t = createDeferredCore(); let n = false; const r = e.manager.registerDecisionHandoff(e.record.id, async (r) => { if (!await t.promise) return; let i = e.manager.projectDecisionIfActive(e.record.id, r); if (!n && e.afterDecision) try { await e.afterDecision(i, e.requestEvent); } catch (t) { e.context.logGateway?.error?.(`${e.afterDecisionErrorLabel ?? "approval follow-up failed"}: ${String(t)}`); } i = e.manager.projectDecisionIfActive(e.record.id, i); e.respond(true, { id: e.record.id, decision: i, createdAtMs: e.record.createdAtMs, expiresAtMs: e.record.expiresAtMs }, void 0); }); r.observation.catch(() => {}); try { const i = e.suppressDelivery === true; const a = !i && e.deliverToApprovalClientsOnly === true; const o = i ? null : resolveApprovalRequestRecipientConnIds({ approvalKind: e.approvalKind ?? "exec", context: e.context, record: e.record, excludeConnId: e.clientConnId }); if (!i) { if (o) e.context.broadcastToConnIds(e.requestEventName, e.requestEvent, o, { dropIfSlow: true }); else e.context.broadcast(e.requestEventName, e.requestEvent, { dropIfSlow: true }); } const s = e.context.approvalEvents; let c = 0; if (!i && !a && s) c = s.publishRequestedAsync ? await s.publishRequestedAsync(e.approvalKind ?? "exec", e.requestEvent) : s.publishRequested(e.approvalKind ?? "exec", e.requestEvent); if (!e.manager.isPendingDeliveryCurrent(e.record)) { t.resolve(true); await r.observation; return; } const l = i ? false : o !== null ? o.size > 0 || c > 0 : (e.context.hasExecApprovalClients?.(e.clientConnId) ?? false) || c > 0; const u = i || a ? false : await e.manager.trackActiveWork(e.deliverRequest); const d = e.approvalKind === "plugin" && isPluginApprovalRequest(e.requestEvent) ? e.requestEvent : void 0; const f = !i && !a && !l && !u && (e.approvalKind !== "plugin" || d !== void 0) && await hasApprovalTurnSourceRoute({ turnSourceChannel: e.record.request.turnSourceChannel, turnSourceAccountId: e.record.request.turnSourceAccountId, approvalKind: e.approvalKind ?? "exec", ...d ? { request: d } : {} }); if (!e.manager.isPendingDeliveryCurrent(e.record)) { t.resolve(true); await r.observation; return; } const p = u ? "forwarder" : l ? "approval-client" : f ? "turn-source" : "none"; if (e.requireDeliveryRoute !== false && !e.keepPendingWithoutRoute && p === "none") try { n = await e.manager.expire(e.record.id, "no-approval-route"); } catch (n) { t.resolve(false); r.abandon(); respondApprovalStorageUnavailable({ ...e, operation: "request", error: n }); return; } else if (e.twoPhase) e.respond(true, { status: "accepted", id: e.record.id, deliveryRoute: p, createdAtMs: e.record.createdAtMs, expiresAtMs: e.record.expiresAtMs }, void 0); } catch (e) { t.resolve(false); r.abandon(); throw e; } t.resolve(true); await r.observation; } function respondRepeatedApprovalResolution(e, t, n) { if ((e.decision ?? e.consumedDecision) === t) { n(true, { ok: true }, void 0); return; } n(false, void 0, errorShape(ErrorCodes.INVALID_REQUEST, "approval already resolved", { details: APPROVAL_ALREADY_RESOLVED_DETAILS })); } /** Resolves a pending approval and broadcasts the final decision exactly once. */ async function handleApprovalResolve(e) { try { var t = _usingCtx(); if (!e.authority.isCurrent()) { respondUnknownOrExpiredApproval(e.respond); return; } const respondFailure = (t) => { if (!e.authority.isCurrent()) respondUnknownOrExpiredApproval(e.respond); else respondApprovalStorageUnavailable({ ...e, operation: "resolve", error: t }); }; const n = t.u(e.reviewer ? prepareApprovalChannelCustody({ cfg: e.context.getRuntimeConfig(), getCfg: e.context.getRuntimeConfig, assertCurrent: () => e.authority.assertCurrent(), approvalKind: e.approvalKind, reviewer: e.reviewer }) : null); if (e.reviewer && !n) { respondUnknownOrExpiredApproval(e.respond); return; } const r = n ? (e) => n.authorizes(e) : void 0; const i = { manager: e.manager, authority: e.authority, getCfg: e.context.getRuntimeConfig, inputId: e.inputId, client: e.client, exposeAmbiguousPrefixError: e.exposeAmbiguousPrefixError, recordFilter: r }; let a; try { a = await resolvePendingApprovalRecord(i); } catch (e) { respondFailure(e); return; } if (!e.authority.isCurrent()) { respondUnknownOrExpiredApproval(e.respond); return; } if (!a.ok) { let t; try { t = await resolveResolvedApprovalRecord(i); } catch (e) { respondFailure(e); return; } if (!e.authority.isCurrent()) { respondUnknownOrExpiredApproval(e.respond); return; } if (t.ok) { respondRepeatedApprovalResolution(t.snapshot, e.decision, e.respond); return; } respondPendingApprovalLookupError({ respond: e.respond, response: a.response }); return; } let o; try { o = await prepareApprovalSessionAccess({ client: e.client, getCfg: e.context.getRuntimeConfig, sources: [readApprovalRequestSource(a.snapshot)] }); } catch (e) { respondFailure(e); return; } const s = t.u(o); if (!e.authority.isCurrent()) { respondUnknownOrExpiredApproval(e.respond); return; } const c = e.validateDecision?.(a.snapshot); if (c) { e.respond(false, void 0, errorShape(ErrorCodes.INVALID_REQUEST, c.message, c.details ? { details: c.details } : void 0)); return; } const l = e.client?.connect?.client?.displayName ?? e.client?.connect?.client?.id ?? null; const u = n ? { kind: "channel", id: n.resolverId } : void 0; const d = a.snapshot.request.sessionKey; const f = a.snapshot.request.agentId; const p = { family: e.authority.guard.family, assertCurrent: () => { e.authority.assertCommitCurrent(); if (e.manager.getLocalSnapshot(a.approvalId) !== a.snapshot || a.snapshot.request.sessionKey !== d || a.snapshot.request.agentId !== f || e.client?.invalidated || !isApprovalRecordVisibleToClient({ record: a.snapshot, client: e.client, ...e.authority.guard.family === "native-compatibility" ? { cfg: e.context.getRuntimeConfig(), sessionAccess: s } : {} }) || e.reviewer && !n?.isCurrent(a.snapshot)) throw new Error("approval resolver authority is no longer active"); } }; let m; try { m = e.resolveRecord ? await e.resolveRecord({ approvalId: a.approvalId, decision: e.decision, resolvedBy: l, snapshot: a.snapshot, resolver: u, guard: p }) : u ? (await e.manager.resolveDetailed(a.approvalId, e.decision, u, l, "operator", { guard: p })).outcome === "resolved" : await e.manager.resolve(a.approvalId, e.decision, l, { guard: p }); } catch (e) { respondFailure(e); return; } if (!m) { const t = await e.manager.getSnapshot(a.approvalId, e.authority); e.authority.assertCurrent(); if (t && t.resolvedAtMs !== void 0) { respondRepeatedApprovalResolution(t, e.decision, e.respond); return; } respondUnknownOrExpiredApproval(e.respond); return; } e.respond(true, { ok: true }, void 0); const h = { id: a.approvalId, decision: e.decision, resolvedBy: l, ts: Date.now(), request: a.snapshot.request }; broadcastApprovalResolvedEvent({ approvalKind: e.approvalKind, context: e.context, record: a.snapshot, event: h }); if (e.approvalKind !== "system-agent") e.context.approvalEvents?.publishResolved(e.approvalKind, h); const g = [ e.forwardResolved ? { run: e.forwardResolved, errorLabel: e.forwardResolvedErrorLabel ?? "approval resolve follow-up failed" } : null, ...e.extraResolvedHandlers ?? [], e.context.approvalWebPushDelivery ? { run: e.context.approvalWebPushDelivery.handleResolved, errorLabel: `${e.approvalKind} approvals: Web Push resolve failed` } : null ].filter((e) => e !== null); for (const t of g) try { await t.run(h); } catch (n) { e.context.logGateway?.error?.(`${t.errorLabel}: ${String(n)}`); } } catch (e) { t.e = e; } finally { t.d(); } } //#endregion export { handleApprovalResolve as a, resolveApprovalDecisionParams as c, buildRequestedApprovalEvent as i, respondApprovalStorageUnavailable as l, bindApprovalReviewerDeviceIds as n, handleApprovalWaitDecision as o, broadcastApprovalResolvedEvent as r, handlePendingApprovalRequest as s, bindApprovalRequesterMetadata as t, prepareApprovalChannelCustody as u };