UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

238 lines (237 loc) • 9.12 kB
import { l as normalizeOptionalString } from "./string-coerce-CCIiB4H7.mjs"; import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs"; import { t as createSubsystemLogger } from "./subsystem-BHJiy01V.mjs"; import { t as resolveGatewayPublicOrigin } from "./gateway-public-origin-SLjx6A2a.mjs"; import "./string-coerce-runtime-BwAZZDf5.mjs"; import "./error-runtime-BM740gJj.mjs"; import "./runtime-env-D-Pa5lD6.mjs"; import { t as buildChannelApprovalNativeTargetKey } from "./approval-native-target-key-D0y5fYMe.mjs"; import { i as buildExecApprovalPendingReplyPayload, n as buildApprovalPresentationFromActionDescriptors, u as formatExecApprovalExpiresIn } from "./exec-approval-reply-CfpNUvnC.mjs"; import { i as createChannelApprovalNativeRuntimeAdapterAsync } from "./approval-handler-runtime-DaVxiojg.mjs"; import "./approval-handler-runtime-BEGhQVM0.mjs"; import "./approval-native-runtime-DBG67Vog.mjs"; import { r as buildPluginApprovalPendingReplyPayload } from "./approval-renderers-BFs8Orkr.mjs"; import "./approval-reply-runtime-B0T7gU8u.mjs"; import { t as normalizeControlUiBasePath } from "./control-ui-base-path-T8auL-Iv.mjs"; import { l as parseTelegramTarget, o as normalizeTelegramChatId } from "./topic-conversation-CDf2PinB.mjs"; import { F as resolveTelegramSendThreadSpec } from "./send-outbound-8-7P0nHN.mjs"; import { s as buildTelegramRoutingTarget, w as parseTelegramThreadId } from "./helpers-CoGccTxe.mjs"; import { E as escapeTelegramHtml } from "./text-chunk-limit-DTiKmKhG.mjs"; import { a as isTelegramExecApprovalHandlerConfigured, l as shouldHandleTelegramExecApprovalRequest } from "./exec-approvals-Crn--YHh.mjs"; import { c as buildTelegramApprovalCallbackData } from "./native-command-callback-data-DMBSeb_1.mjs"; import { i as normalizeTelegramButtonStyle, o as resolveTelegramInlineButtons } from "./button-types-D-RCz2yJ.mjs"; import { C as editMessageTelegram, R as sendTypingTelegram, S as editMessageReplyMarkupTelegram, u as sendMessageTelegram } from "./send-CkT6jkYo.mjs"; import { a as buildTelegramNativeResolvedApprovalText, i as buildTelegramNativeExpiredApprovalText } from "./approval-terminal-Coj6_74K.mjs"; //#region extensions/telegram/src/approval-handler.runtime.ts const log = createSubsystemLogger("telegram/approvals"); const terminalizedSystemAgentApprovals = /* @__PURE__ */ new Set(); function approvalTargetKey(e) { return buildTelegramRoutingTarget(e.chatId, resolveTelegramSendThreadSpec({ messageThreadId: e.messageThreadId, targetDirectMessagesTopicId: e.directMessagesTopicId, chatType: parseTelegramTarget(e.chatId).chatType })); } function resolveHandlerContext(e) { const t = e.context; const n = normalizeOptionalString(e.accountId) ?? ""; if (!t?.token || !n) return null; return { accountId: n, context: t, options: () => ({ cfg: e.cfg, token: t.token, accountId: n }) }; } function buildPendingPayload(e) { if (e.approvalKind === "system-agent") { const t = e.view; if (t.approvalKind !== "system-agent") throw new Error("system-agent approval request and view kinds do not match"); const n = resolveGatewayPublicOrigin(e.cfg); const r = n && e.cfg.gateway?.controlUi?.enabled !== false ? `${n}${normalizeControlUiBasePath(e.cfg.gateway?.controlUi?.basePath?.trim() ?? "", "one")}/approve/${encodeURIComponent(e.request.id)}` : void 0; const i = [ "🔒 OpenClaw change requires approval", `Change: ${t.operationSummary}`, `Agent: ${t.agentId ?? "unknown"}`, `Expires in: ${formatExecApprovalExpiresIn(e.request.expiresAtMs, e.nowMs)}` ]; const a = t.actions.flatMap((e) => { const t = e.action; if (!t || t.type !== "approval") return []; const n = buildTelegramApprovalCallbackData(t); const r = normalizeTelegramButtonStyle(e.style); return n ? [{ text: e.label, callback_data: n, ...r ? { style: r } : {} }] : []; }); const o = a.length > 0 ? [a] : []; return { text: i.join("\n"), buttons: r ? [[{ text: "Review in Control UI", url: r }], ...o] : o }; } const t = e.view.approvalKind === "exec" ? e.view : void 0; return { text: (e.approvalKind === "plugin" ? buildPluginApprovalPendingReplyPayload({ request: e.request, nowMs: e.nowMs }) : buildExecApprovalPendingReplyPayload({ approvalId: e.request.id, approvalSlug: e.request.id.slice(0, 8), approvalCommandId: e.request.id, warningText: t?.warningText ?? void 0, command: t?.commandText ?? "", cwd: t?.cwd ?? void 0, host: t?.host === "node" ? "node" : "gateway", nodeId: t?.nodeId ?? void 0, scope: t?.scope ?? void 0, allowedDecisions: e.view.actions.map((e) => e.decision), expiresAtMs: e.request.expiresAtMs, nowMs: e.nowMs })).text ?? "", buttons: resolveTelegramInlineButtons({ presentation: buildApprovalPresentationFromActionDescriptors(e.view.actions) }) }; } const telegramApprovalNativeRuntime = createChannelApprovalNativeRuntimeAdapterAsync({ eventKinds: [ "exec", "plugin", "system-agent" ], availability: { isConfigured: (e) => { const t = resolveHandlerContext(e); return t ? isTelegramExecApprovalHandlerConfigured({ cfg: e.cfg, accountId: t.accountId }) : false; }, shouldHandle: (e) => { const t = resolveHandlerContext(e); return t ? shouldHandleTelegramExecApprovalRequest({ cfg: e.cfg, accountId: t.accountId, request: e.request }) : false; } }, presentation: { buildPendingPayload, buildResolvedResult: ({ view: e }) => ({ kind: "update", payload: { text: buildTelegramNativeResolvedApprovalText(e) } }), buildExpiredResult: ({ view: e }) => ({ kind: "update", payload: { text: buildTelegramNativeExpiredApprovalText(e) } }) }, transport: { prepareTarget: ({ plannedTarget: e }) => { const t = parseTelegramTarget(e.target.to); return { dedupeKey: buildChannelApprovalNativeTargetKey(e.target), target: { chatId: t.chatId, messageThreadId: typeof e.target.threadId === "number" ? e.target.threadId : t.messageThreadId, directMessagesTopicId: t.directMessagesTopicId } }; }, deliverPending: async ({ cfg: e, accountId: t, context: n, preparedTarget: r, pendingPayload: i }) => { const a = resolveHandlerContext({ cfg: e, accountId: t, context: n }); if (!a) return null; const o = { ...a.options(), ...r.messageThreadId != null ? { messageThreadId: r.messageThreadId } : {} }; await sendTypingTelegram(r.chatId, o).catch(() => {}); const s = await sendMessageTelegram(r.chatId, i.text, { ...o, buttons: i.buttons, ...r.directMessagesTopicId != null ? { directMessagesTopicId: r.directMessagesTopicId } : {} }); return { ...r, chatId: s.chatId, messageId: s.messageId }; }, updateEntry: async ({ cfg: e, accountId: t, context: n, entry: r, payload: i, request: a, approvalKind: o, remainingEntries: s }) => { const c = resolveHandlerContext({ cfg: e, accountId: t, context: n }); if (!c) return; let l; try { await editMessageTelegram(r.chatId, r.messageId, escapeTelegramHtml(i.text), { ...c.options(), textMode: "html", buttons: [] }); } catch (e) { l = e; } if (o === "system-agent" && a.request.turnSourceChannel?.trim().toLowerCase() === "telegram") { const e = a.request.turnSourceTo?.trim(); const t = e ? parseTelegramTarget(e) : void 0; const n = t ? normalizeTelegramChatId(t.chatId) : void 0; const o = parseTelegramThreadId(a.request.turnSourceThreadId) ?? t?.messageThreadId; const u = a.request.turnSourceAccountId?.trim(); const d = !u || u === c.accountId; if (n && d) { const e = { chatId: n, messageThreadId: o, directMessagesTopicId: t?.directMessagesTopicId }; const u = approvalTargetKey(e); const d = approvalTargetKey(r) !== u || l !== void 0; if (!(d && s?.some((e) => approvalTargetKey(e) === u))) { if (d && !terminalizedSystemAgentApprovals.has(a.id)) await sendMessageTelegram(n, escapeTelegramHtml(i.text), { ...c.options(), textMode: "html", ...o != null ? { messageThreadId: o } : {}, ...e.directMessagesTopicId != null ? { directMessagesTopicId: e.directMessagesTopicId } : {} }); terminalizedSystemAgentApprovals.add(a.id); } } } if (l !== void 0) throw l instanceof Error ? l : new Error(formatErrorMessage(l)); } }, interactions: { clearPendingActions: async ({ cfg: e, accountId: t, context: n, entry: r }) => { const i = resolveHandlerContext({ cfg: e, accountId: t, context: n }); if (!i) return; await editMessageReplyMarkupTelegram(r.chatId, r.messageId, [], i.options()); } }, observe: { onDeliveryError: ({ error: e, request: t }) => { log.error(`telegram approvals: failed to send request ${t.id}: ${String(e)}`); }, onFinalized: ({ request: e, approvalKind: t }) => { if (t === "system-agent") terminalizedSystemAgentApprovals.delete(e.id); } } }); //#endregion export { telegramApprovalNativeRuntime };