UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

494 lines (493 loc) • 16.5 kB
import { l as normalizeOptionalString } from "./string-coerce-CCIiB4H7.mjs"; import { l as isRecord } from "./record-coerce-CVPuDqcc.mjs"; import { t as _usingCtx } from "./usingCtx-rhpPzaNq.mjs"; import { Ar as validateApprovalGetParams, Mr as validateApprovalResolveParams, jr as validateApprovalHistoryParams } from "./src-BX8OAe1J.mjs"; import { n as isWellFormedApprovalId } from "./approval-id-CfM0pBs_.mjs"; import { t as ErrorCodes } from "./gateway-error-details-B69XiHdh.mjs"; import { t as assertionSucceeds } from "./assertion-BVvbcE3a.mjs"; import { t as normalizeControlUiBasePath } from "./control-ui-shared-_tUmz6W8.mjs"; import { t as respondError } from "./response-C7fEiIN1.mjs"; import { i as OperatorApprovalHistoryCursorError } from "./operator-approval-store.rows-DGzIpZI3.mjs"; import { i as getOperatorApprovalDetailed, o as isOperatorApprovalStoreOutcomeUnknown, s as isOperatorApprovalStoreRefusal, u as listTerminalOperatorApprovals } from "./operator-approval-store-lZFt_sJ1.mjs"; import { n as canResolveOperatorApproval, r as canReviewOperatorApproval, t as canAccessOperatorApproval } from "./operator-approval-authorization-CczTmdXh.mjs"; import { l as respondApprovalStorageUnavailable, u as prepareApprovalChannelCustody } from "./approval-shared-C8HrUVTB.mjs"; import { i as prepareApprovalSessionAccess } from "./approval-record-lookup-mkMfll81.mjs"; import { t as projectOperatorApprovalSnapshot } from "./operator-approval-snapshot-N40cGMy0.mjs"; import { t as publishAppliedApprovalResolution } from "./approval-publication-DzFf7ySp.mjs"; import { t as createApprovalRequestAuthority } from "./approval-request-authority-IKBJABLe.mjs"; //#region src/gateway/server-methods/approval-visible-record.ts async function loadVisibleApproval(e) { try { var t = _usingCtx(); const n = e.allowApprovalRuntime ? canResolveOperatorApproval(e.client) : canReviewOperatorApproval(e.client); if (!e.authority.isCurrent() || !n || e.client?.invalidated) return null; const r = e.execApprovalManager.getLiveSnapshot(e.id) ?? e.pluginApprovalManager.getLiveSnapshot(e.id) ?? e.systemAgentApprovalManager?.getLiveSnapshot(e.id); let i = e.id; let a = r?.resolvedAtMs === void 0 ? r : void 0; let o = a ? [ e.execApprovalManager, e.pluginApprovalManager, e.systemAgentApprovalManager ].find((t) => t?.getLocalSnapshot(e.id) === a) : void 0; let s = a?.request.sessionKey; let c = a?.request.agentId; if (a) e.authority.bindSource(a.request); let l = await prepareApprovalSessionAccess({ client: e.client, getCfg: e.getCfg, sources: r ? [r.request] : [] }); const u = t.u({ retained: false, [Symbol.dispose]() { if (!this.retained) l[Symbol.dispose](); } }); e.authority.assertCurrent(); const canAccess = (t, n) => l.canAccess(t()) && canAccessOperatorApproval({ client: e.client, allowApprovalRuntime: e.allowApprovalRuntime, binding: { reviewerDeviceIds: n() } }); if (r && !canAccess(() => r.request, () => r.approvalReviewerDeviceIds)) return null; const assertBindingCurrent = () => { if (a && (o?.getLocalSnapshot(i) !== a || a.request.sessionKey !== s || a.request.agentId !== c || !canAccessOperatorApproval({ client: e.client, allowApprovalRuntime: e.allowApprovalRuntime, binding: { reviewerDeviceIds: a.approvalReviewerDeviceIds } }))) throw new Error("Approval lookup authority is no longer active"); }; const d = { assertCurrent: () => { e.authority.assertCurrent(); assertBindingCurrent(); }, guard: { family: e.authority.guard.family, assertCurrent: () => { e.authority.assertCommitCurrent(); assertBindingCurrent(); } } }; const isLookupCurrent = () => assertionSucceeds(() => d.assertCurrent()); const reconcile = async (e, t) => { try { return await e?.reconcileDurableLookup(t, null, d); } catch (e) { if (!isLookupCurrent()) return null; throw e; } }; let f; try { f = await getOperatorApprovalDetailed({ id: e.id, allowTransportRef: e.allowTransportRef, databaseOptions: e.databaseOptions, guard: d.guard }); } catch (t) { if (!isLookupCurrent()) return null; if (isOperatorApprovalStoreRefusal(t) || isOperatorApprovalStoreOutcomeUnknown(t)) throw t; const n = { outcome: "corrupt", id: e.id }; await reconcile(e.execApprovalManager, n); await reconcile(e.pluginApprovalManager, n); await reconcile(e.systemAgentApprovalManager, n); throw t; } if (!isLookupCurrent() || e.client?.invalidated || !(e.allowApprovalRuntime ? canResolveOperatorApproval(e.client) : canReviewOperatorApproval(e.client))) return null; if (f.outcome === "found") { const t = f; if (!r || (normalizeOptionalString(r.request.sessionKey) ?? null) !== t.record.source.sessionKey || (normalizeOptionalString(r.request.agentId) ?? null) !== t.record.source.agentId) { l[Symbol.dispose](); l = await prepareApprovalSessionAccess({ client: e.client, getCfg: e.getCfg, sources: [t.record.source] }); } if (!isLookupCurrent()) return null; if (!canAccess(() => t.record.source, () => t.record.reviewerDeviceIds)) return null; e.authority.bindSource(f.record.source); const n = f.record.kind === "exec" ? e.execApprovalManager : f.record.kind === "plugin" ? e.pluginApprovalManager : e.systemAgentApprovalManager; if (f.record.status === "pending") { const t = n?.getLocalSnapshot(f.record.id); if (t) { if ((normalizeOptionalString(t.request.sessionKey) ?? null) !== f.record.source.sessionKey || (normalizeOptionalString(t.request.agentId) ?? null) !== f.record.source.agentId || !canAccessOperatorApproval({ client: e.client, allowApprovalRuntime: e.allowApprovalRuntime, binding: { reviewerDeviceIds: t.approvalReviewerDeviceIds } })) return null; if (!a) { i = f.record.id; a = t; o = n; s = t.request.sessionKey; c = t.request.agentId; } } } const p = await reconcile(n, f); if (!p) return null; u.retained = true; return { guard: d.guard, [Symbol.dispose]: () => l[Symbol.dispose](), readCurrent: () => e.authority.isCurrent() && (p.status !== "pending" || isLookupCurrent()) && !e.client?.invalidated && canAccess(() => p.source, () => p.reviewerDeviceIds) ? p : null }; } const p = { outcome: f.outcome === "corrupt" ? "corrupt" : "missing", id: f.outcome === "corrupt" ? f.id ?? e.id : e.id }; await reconcile(e.execApprovalManager, p); await reconcile(e.pluginApprovalManager, p); await reconcile(e.systemAgentApprovalManager, p); return null; } catch (e) { t.e = e; } finally { t.d(); } } //#endregion //#region src/gateway/server-methods/approval.ts function buildApprovalSnapshot(e, t) { const n = projectOperatorApprovalSnapshot(e, t); if (!n || n.status === "pending") return n; return { ...n, source: { ...e.source.agentId ? { agentId: e.source.agentId } : {}, ...e.source.sessionKey ? { sessionKey: e.source.sessionKey } : {} }, ...e.resolver ? { resolver: { kind: e.resolver.kind, ...e.resolver.id ? { id: e.resolver.id } : {} } } : {} }; } function resolveApprovalResolver(e) { const t = normalizeOptionalString(e?.connect?.device?.id); if (t) return { kind: "device", id: t }; return { kind: "runtime", id: normalizeOptionalString(e?.connect?.client?.id) ?? null }; } function resolveLegacyApprovalLabel(e) { return normalizeOptionalString(e?.connect?.client?.displayName) ?? normalizeOptionalString(e?.connect?.client?.id) ?? null; } function respondApprovalNotFound(e) { respondError(e, ErrorCodes.INVALID_REQUEST, "approval not found", { details: { reason: ErrorCodes.APPROVAL_NOT_FOUND } }); } function readExactApprovalId(e) { if (!isRecord(e) || typeof e.id !== "string") return null; const t = e.id; return isWellFormedApprovalId(t) ? t : null; } async function applyApprovalDecision(e) { const t = e.forceMalformedDeny ? await e.manager.forceDenyDetailed(e.id, "malformed-verdict", e.resolver, "denied", void 0, false, e.localResolvedBy, void 0, e.guard) : await e.manager.resolveDetailed(e.id, e.decision, e.resolver, e.localResolvedBy, "operator", { guard: e.guard, ...e.grantExpiresAtMs !== void 0 ? { grantExpiresAtMs: e.grantExpiresAtMs } : {} }); if (t.outcome === "decision-not-allowed") return applyApprovalDecision({ ...e, forceMalformedDeny: true }); if (t.outcome === "not-found" || t.outcome === "corrupt") return { ok: false }; const n = t.outcome === "resolved" || t.outcome === "denied"; return { ok: true, applied: n, record: t.record, liveRecord: n ? t.liveRecord ?? e.manager.getLiveSnapshot(e.id) ?? void 0 : t.liveRecord }; } function createApprovalHandlers(e) { return { "approval.history": async (t) => { try { var n = _usingCtx(); const { params: r, respond: i, client: a, context: o } = t; const s = n.u(createApprovalRequestAuthority(t)); if (!validateApprovalHistoryParams(r)) { respondError(i, ErrorCodes.INVALID_REQUEST, "invalid approval.history params"); return; } if (!s.isCurrent()) { respondApprovalNotFound(i); return; } let c; try { c = await listTerminalOperatorApprovals({ cursor: r.cursor, limit: r.limit, kind: r.kind, databaseOptions: e.databaseOptions, guard: s.guard }); } catch (e) { if (!s.isCurrent()) { respondApprovalNotFound(i); return; } if (e instanceof OperatorApprovalHistoryCursorError) { respondError(i, ErrorCodes.INVALID_REQUEST, "invalid approval.history cursor"); return; } respondApprovalStorageUnavailable({ context: o, respond: i, operation: "history", error: e }); return; } if (!s.isCurrent()) { respondApprovalNotFound(i); return; } const l = n.u(await prepareApprovalSessionAccess({ client: a, getCfg: o.getRuntimeConfig, sources: c.records.map((e) => e.source) })); s.assertCurrent(); const u = o.getRuntimeConfig(); const d = normalizeControlUiBasePath(u.gateway?.controlUi?.basePath); i(true, { items: c.records.flatMap((e) => { if (!l.canAccess(e.source)) return []; const t = buildApprovalSnapshot(e, d); return t && t.status !== "pending" ? [t] : []; }), ...c.nextCursor ? { nextCursor: c.nextCursor } : {} }, void 0); } catch (e) { n.e = e; } finally { n.d(); } }, "approval.get": async (t) => { try { var n = _usingCtx(); const { params: i, respond: a, client: o, context: s } = t; const c = n.u(createApprovalRequestAuthority(t)); if (!validateApprovalGetParams(i)) { respondError(a, ErrorCodes.INVALID_REQUEST, "invalid approval.get params"); return; } const l = readExactApprovalId(i); let u; try { try { var r = _usingCtx(); u = r.u(l ? await loadVisibleApproval({ ...e, id: l, authority: c, client: o, getCfg: () => s.getRuntimeConfig() }) : null)?.readCurrent() ?? null; } catch (e) { r.e = e; } finally { r.d(); } } catch (e) { if (!c.isCurrent()) { respondApprovalNotFound(a); return; } respondApprovalStorageUnavailable({ context: s, respond: a, operation: "lookup", error: e }); return; } const d = normalizeControlUiBasePath(s.getRuntimeConfig()?.gateway?.controlUi?.basePath); const f = u ? buildApprovalSnapshot(u, d) : null; if (!f) { respondApprovalNotFound(a); return; } a(true, { approval: f }, void 0); } catch (e) { n.e = e; } finally { n.d(); } }, "approval.resolve": async (t) => { try { var n = _usingCtx(); const { params: r, respond: i, client: a, context: o } = t; const s = n.u(createApprovalRequestAuthority(t)); const c = validateApprovalResolveParams(r); const l = c ? r : null; if (isRecord(r) && "reviewer" in r && !l?.reviewer) { respondApprovalNotFound(i); return; } const u = readExactApprovalId(r); let d; let f; try { f = u ? await loadVisibleApproval({ ...e, id: u, authority: s, client: a, getCfg: () => o.getRuntimeConfig(), allowApprovalRuntime: true, allowTransportRef: true }) : null; d = f?.readCurrent() ?? null; } catch (e) { if (!s.isCurrent()) { respondApprovalNotFound(i); return; } respondApprovalStorageUnavailable({ context: o, respond: i, operation: "lookup", error: e }); return; } const p = n.u(f); if (!u || !d || !p) { respondApprovalNotFound(i); return; } const { guard: m, readCurrent: h } = p; const g = d.kind === "exec" ? e.execApprovalManager.getLiveSnapshot(d.id) : d.kind === "plugin" ? e.pluginApprovalManager.getLiveSnapshot(d.id) : e.systemAgentApprovalManager?.getLiveSnapshot(d.id); const _ = n.u(l?.reviewer ? prepareApprovalChannelCustody({ cfg: o.getRuntimeConfig(), getCfg: o.getRuntimeConfig, assertCurrent: () => m.assertCurrent(), approvalKind: d.kind, reviewer: l.reviewer }) : null); try { if (l?.reviewer && (!_ || !g || !await _.authorizes(g))) { respondApprovalNotFound(i); return; } } catch (e) { if (!s.isCurrent()) respondApprovalNotFound(i); else respondApprovalStorageUnavailable({ context: o, respond: i, operation: "lookup", error: e }); return; } if (d.status !== "pending") { const e = normalizeControlUiBasePath(o.getRuntimeConfig()?.gateway?.controlUi?.basePath); const t = buildApprovalSnapshot(d, e); if (!t || t.status === "pending") { respondApprovalNotFound(i); return; } i(true, { applied: false, approval: t }, void 0); return; } const v = _ ? { kind: "channel", id: _.resolverId } : resolveApprovalResolver(a); const y = resolveLegacyApprovalLabel(a); const b = l?.decision ?? null; const x = b === "deny" || b !== null && d.presentation.allowedDecisions.includes(b); const S = l?.kind === d.presentation.kind; const C = !c || !S || !x; const assertCurrent = () => { m.assertCurrent(); if (a?.invalidated || !canAccessOperatorApproval({ client: a, allowApprovalRuntime: true, binding: { reviewerDeviceIds: d.reviewerDeviceIds } }) || m.family === "native-compatibility" && !h() || l?.reviewer && (!g || !_?.isCurrent(g))) throw new Error("approval resolver authority is no longer active"); }; let w; try { w = await applyApprovalDecision({ id: d.id, decision: b, forceMalformedDeny: C, resolver: v, localResolvedBy: y, guard: { family: m.family, assertCurrent }, manager: d.kind === "exec" ? e.execApprovalManager : d.kind === "plugin" ? e.pluginApprovalManager : e.systemAgentApprovalManager, ...d.kind === "exec" && b === "allow-always" && typeof l?.grantExpiresInDays === "number" ? { grantExpiresAtMs: Date.now() + Math.floor(l.grantExpiresInDays) * 864e5 } : {} }); } catch (e) { if (!h()) { respondApprovalNotFound(i); return; } respondApprovalStorageUnavailable({ context: o, respond: i, operation: "resolve", error: e }); return; } if (!s.isCurrent() || !w.ok) { respondApprovalNotFound(i); return; } const T = w.record; if (T.status === "pending") { respondApprovalNotFound(i); return; } const E = buildApprovalSnapshot(T, normalizeControlUiBasePath(o.getRuntimeConfig()?.gateway?.controlUi?.basePath)); if (!E) { respondApprovalNotFound(i); return; } i(true, { applied: w.applied, approval: E }, void 0); if (w.applied && w.liveRecord) publishAppliedApprovalResolution({ ...e, record: T, liveRecord: w.liveRecord, context: o }).catch((e) => { o.logGateway?.error?.(`${T.kind} approvals: unified resolve publication failed: ${String(e)}`); }); } catch (e) { n.e = e; } finally { n.d(); } } }; } //#endregion export { createApprovalHandlers };