UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

223 lines (222 loc) • 8.02 kB
import { o as normalizeLowercaseStringOrEmpty } from "./string-coerce-CCIiB4H7.mjs"; import "./src-H3RMXyFL.mjs"; import { t as expectDefined } from "./expect-DDakjvvQ.mjs"; import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs"; import { t as createSubsystemLogger } from "./subsystem-BHJiy01V.mjs"; import { n as normalizeMessageChannel } from "./message-channel-core-BbYZT1a-.mjs"; import { t as getChannelPlugin } from "./registry-ByqVE5S3.mjs"; import "./message-channel-DTYVLJT1.mjs"; import { n as resolveChannelApprovalCapability } from "./plugins-BoMiRtiY.mjs"; import { r as logVerbose } from "./globals-CgepmiqE.mjs"; import { t as canChannelEnforcePluginReviewerPolicy } from "./approval-channel-policy-support-CGr6SWrA.mjs"; import { t as isApprovalNotFoundError } from "./approval-errors-byE8UOsC.mjs"; import { n as commandReply, u as requireGatewayClientScope } from "./command-gates-BZ-IYgiD.mjs"; import { r as isImplicitSameChatApprovalAuthorization } from "./approval-auth-helpers-nDvq-VbZ.mjs"; import { n as resolveApprovalOverGateway, t as isPendingSystemAgentApprovalOverGateway } from "./approval-gateway-resolver-D4neRbd5.mjs"; import { t as resolveChannelAccountId } from "./channel-context-C0btiqLS.mjs"; //#region src/auto-reply/reply/commands-approve.ts /** Resolves whether a chat `/approve` command is authorized by channel-specific approval policy. */ async function resolveApprovalCommandAuthorization(e) { const t = normalizeMessageChannel(e.channel); if (!t) return { authorized: true, explicit: false }; const n = resolveChannelApprovalCapability(getChannelPlugin(t)); if (e.kind === "plugin" && !canChannelEnforcePluginReviewerPolicy(e.cfg, t, n)) return { authorized: false, explicit: true, reason: `Plugin approvals on ${t} require an updated channel plugin for the configured reviewer policy.` }; const r = await (n?.authorizeActorActionAsync ?? n?.authorizeActorAction)?.({ cfg: e.cfg, accountId: e.accountId, senderId: e.senderId, action: "approve", approvalKind: e.kind }); if (!r) return { authorized: true, explicit: false }; const i = isImplicitSameChatApprovalAuthorization(r); const a = await (n?.getActionAvailabilityStateAsync ?? n?.getActionAvailabilityState)?.({ cfg: e.cfg, accountId: e.accountId, action: "approve", approvalKind: e.kind }); return { authorized: r.authorized, reason: r.reason, explicit: r.authorized ? !i && a?.kind !== "disabled" : true }; } const log = createSubsystemLogger("auto-reply/commands-approve"); const COMMAND_REGEX = /^\/?approve(?:\s|$)/i; const FOREIGN_COMMAND_MENTION_REGEX = /^\/approve@([^\s]+)(?:\s|$)/i; const DECISION_ALIASES = /* @__PURE__ */ new Map([ ["allow", "allow-once"], ["once", "allow-once"], ["allow-once", "allow-once"], ["allowonce", "allow-once"], ["always", "allow-always"], ["allow-always", "allow-always"], ["allowalways", "allow-always"], ["deny", "deny"], ["reject", "deny"], ["block", "deny"] ]); const APPROVE_USAGE_TEXT = "Usage: /approve <id> <decision> (see the pending approval message for available decisions)"; function parseApproveCommand(e) { const t = e.trim(); if (FOREIGN_COMMAND_MENTION_REGEX.test(t)) return { ok: false, error: "❌ This /approve command targets a different Telegram bot." }; const n = t.match(COMMAND_REGEX); if (!n) return null; const r = t.slice(n[0].length).trim().split(/\s+/); if (r.length < 2) return { ok: false, error: APPROVE_USAGE_TEXT }; const i = normalizeLowercaseStringOrEmpty(r[0]); const a = normalizeLowercaseStringOrEmpty(r[1]); const o = DECISION_ALIASES.get(i); const s = o ?? DECISION_ALIASES.get(a); if (s) return { ok: true, decision: s, id: o ? r.slice(1).join(" ") : expectDefined(r[0], "tokens entry at 0") }; return { ok: false, error: APPROVE_USAGE_TEXT }; } async function handleApproveCommandFromContext(e, t) { if (!t) return null; const n = e.command.commandBodyNormalized; const r = parseApproveCommand(n); if (!r) return null; if (!r.ok) return commandReply(r.error); const i = resolveChannelAccountId(e); const a = resolveChannelApprovalCapability(getChannelPlugin(e.command.channel)); const o = a?.resolveReviewerSenderId?.({ cfg: e.cfg, accountId: i, senderId: e.command.senderId, spaceId: e.ctx.GroupSpace }) ?? e.command.senderId; const s = [ "exec", "plugin", "system-agent" ]; const authorize = (t) => resolveApprovalCommandAuthorization({ cfg: e.cfg, channel: e.command.channel, accountId: i, senderId: t === "plugin" ? o : e.command.senderId, kind: t }); const [c, l, u] = await Promise.all([ authorize("exec"), authorize("plugin"), authorize("system-agent") ]); const d = { exec: c, plugin: l, "system-agent": u }; const f = Object.values(d).some((e) => e.explicit && e.authorized); if (!e.command.isAuthorizedSender && !f) { logVerbose(`Ignoring /approve from unauthorized sender: ${e.command.senderId || "<unknown>"}`); return { shouldContinue: false }; } const p = requireGatewayClientScope(e, { label: "/approve", allowedScopes: ["operator.approvals", "operator.admin"], missingText: "❌ /approve requires operator.approvals for gateway clients." }); if (p) return p; const m = !a?.authorizeActorActionAsync && !a?.authorizeActorAction; const h = /* @__PURE__ */ new Map(); for (const t of s) h.set(t, a?.resolveApproveCommandBehavior?.({ cfg: e.cfg, accountId: i, senderId: e.command.senderId, approvalKind: t })); const blockedCommandResult = () => { const e = Array.from(h.values()).find((e) => e?.kind === "reply"); if (e?.kind === "reply") return commandReply(e.text); if (Array.from(h.values()).some((e) => e?.kind === "ignore")) return { shouldContinue: false }; return _ ? v : null; }; const g = `${e.command.channel}:${e.command.senderId ?? "unknown"}`; const callApprovalMethod = async (t) => { const n = a?.authorizeActorActionAsync || a?.authorizeActorAction || t === "system-agent" && !Array.isArray(e.ctx.GatewayClientScopes) ? { channel: e.command.channel, accountId: i, senderId: t === "plugin" ? o : e.command.senderId } : {}; const s = `Chat approval (${g})`; if (t === "system-agent") { if (!await isPendingSystemAgentApprovalOverGateway({ cfg: e.cfg, approvalId: r.id, clientDisplayName: s })) throw new Error("unknown or expired approval id"); if (m) try { e.command.assertOwnerCurrent?.(); } catch { throw new Error("your owner authority changed; send /approve again"); } } const c = { cfg: e.cfg, approvalId: r.id, decision: r.decision, ...n, clientDisplayName: s }; await (t === "system-agent" ? resolveApprovalOverGateway({ ...c, approvalKind: t }) : resolveApprovalOverGateway({ ...c, resolveMethod: t })); }; const _ = m && !e.command.senderIsOwner && d["system-agent"].authorized; const v = commandReply("❌ Only the owner can approve OpenClaw changes in this chat."); const y = s.filter((e) => { if (e === "system-agent" && _) return false; const t = h.get(e); return d[e].authorized && (!t || t.kind === "allow"); }); if (y.length === 0) { const e = blockedCommandResult(); if (e) return e; return commandReply(Object.values(d).find((e) => e.reason)?.reason ?? "❌ You are not authorized to approve this request."); } for (const [e, t] of y.entries()) try { await callApprovalMethod(t); break; } catch (t) { if (isApprovalNotFoundError(t)) { if (e < y.length - 1) continue; const t = blockedCommandResult(); if (t) return t; return commandReply("That approval is no longer available. Check the request in the Control UI."); } log.warn(`Approval submission failed: ${formatErrorMessage(t)}`); return commandReply("⚠️ Couldn't confirm that approval. Check the request in the Control UI before trying again."); } return commandReply(`✅ Approval ${r.decision} submitted for ${r.id}.`); } //#endregion export { handleApproveCommandFromContext as t };