UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

900 lines (899 loc) • 35.3 kB
import "./redact-BDinS1q9.js"; import "./errors-BxyFnvP3.js"; import "./unhandled-rejections-CDJ8dOVP.js"; import "./logger-kwZIqwuw.js"; import "./paths-ViKUYWUK.js"; import "./tmp-openclaw-dir-idKIOMmb.js"; import "./theme-CdOoMzRk.js"; import "./globals-DBUMOBZ8.js"; import "./subsystem-DISldKSB.js"; import "./ansi-BEJF8NKS.js"; import "./boolean-C3GkJetE.js"; import "./env-Dnra1IpT.js"; import "./warning-filter-CBhOcgHd.js"; import "./utils-CS0Ikux6.js"; import "./links-8xRhWBQL.js"; import "./paths-C4Oy7wjk.js"; import "./auth-profiles-DRuJBw5y.js"; import "./agent-scope-bjWqU22i.js"; import "./boundary-path-Dm0QJ7-y.js"; import "./boundary-file-read-DcZxlWD8.js"; import "./logger-BmpSCz93.js"; import "./exec-B5_AYfQG.js"; import "./workspace-D4K6QX9X.js"; import "./model-selection-BnFtDmP7.js"; import "./io-y3Az_Onx.js"; import "./shell-env-BOu7XeT_.js"; import "./safe-text-yavot2qw.js"; import "./version-CD3oP1-d.js"; import "./env-substitution-O6uabUmO.js"; import "./includes-Bj3eLUWH.js"; import "./zod-schema.providers-core-COy5nBQ0.js"; import "./legacy-web-search-BB-ZHEhz.js"; import "./registry-C5UkPpaO.js"; import "./config-state-Br0ucqMb.js"; import "./min-host-version-RMBWtIAR.js"; import "./manifest-registry-B5JNQdOM.js"; import "./runtime-guard-PhQ6PwQa.js"; import "./avatar-policy-B5nOfso_.js"; import "./ip-Ce8EDTBZ.js"; import "./zod-schema.agent-runtime-Dtg4Jy6G.js"; import "./zod-schema.core-BuVz8Rk7.js"; import "./config-D4zN4BRl.js"; import "./file-lock-DEiVq2ow.js"; import "./audit-fs-DTQIjp2r.js"; import "./resolve-B7S4PlnO.js"; import "./profiles-COPO-hHI.js"; import "./tailscale-CxY-91GZ.js"; import "./tailnet-DHiKSG7V.js"; import "./net-JAg9zL0G.js"; import "./auth-Buq0Niri.js"; import "./credentials-D8pfRimu.js"; import "./message-channel-BliByQBl.js"; import "./store-C5UK26Ce.js"; import "./runtime-Iz8uZ7EU.js"; import "./plugins-B09-vgme.js"; import "./sessions-D9ZgHCHb.js"; import "./paths-rhN9LKM_.js"; import "./session-write-lock-va3qZE6f.js"; import "./method-scopes-BiEi0X2g.js"; import "./call-CQbSO4Fr.js"; import "./prompt-style-C4CV4Y_p.js"; import "./ports-lsof-BLEgL_Gn.js"; import "./restart-stale-pids-BsPvlGJd.js"; import "./ports-FldL_Lhq.js"; import "./logging-CznuqaMu.js"; import "./commands-C6oAw_H-.js"; import "./issue-format-BtLIwOtN.js"; import "./identity-Dp-UIak4.js"; import "./heartbeat-Bdfr_onc.js"; import "./pi-embedded-CbCYZxIb.js"; import "./internal-hooks-CIUghoK4.js"; import "./multimodal-B8yEZcl5.js"; import "./memory-search-B_aq08y5.js"; import "./provider-catalog-rVN7ZbR5.js"; import "./secret-input-DXoOLNgb.js"; import "./bindings-CFudGB9Z.js"; import "./resolve-route-DwFWP4JW.js"; import "./routing-zOQ0wwtV.js"; import "./identity-file-DVLib087.js"; import "./outbound-runtime-m-y0nd6F.js"; import "./provider-env-vars-CpUJqT5v.js"; import "./provider-auth-input-Bus9W_qh.js"; import "./provider-model-minimax-DSmX4BNO.js"; import "./provider-models-BKjzpTsb.js"; import "./anthropic-vertex-provider-B2x4YywE.js"; import "./provider-catalog-BTgF8VyO.js"; import "./provider-catalog-D0IlX18O.js"; import "./provider-catalog-BTmUX0Mp.js"; import "./provider-catalog-sph_Rl63.js"; import "./provider-catalog-C7tUyBwV.js"; import "./provider-catalog-C8dPZpHW.js"; import "./provider-catalog-BJNff1VI.js"; import "./provider-catalog-IAdymoqT.js"; import "./provider-catalog-Bjc7evzh.js"; import "./models-config.providers.discovery-CjkO08q6.js"; import "./text-runtime-DVXt5xhi.js"; import "./tool-catalog-BjSY4C4F.js"; import "./docker-Bhjg8g2t.js"; import "./sandbox-DTlKNieF.js"; import { c as jsonResult, d as readNumberParam, f as readReactionParams, h as readStringParam, i as createActionGate, p as readStringArrayParam } from "./common-zReYuoMM.js"; import "./image-ops-By4YfyWa.js"; import "./thinking-CJoSRIGR.js"; import "./path-alias-guards-CwRM04O1.js"; import "./sandbox-paths-Cn8i8Jxm.js"; import "./channel-actions-fV93bLjV.js"; import "./mime-CsUtzcn2.js"; import "./ssrf-0bPJMoZR.js"; import "./fetch-guard-CYl1q2XH.js"; import "./provider-web-search-COZNygbd.js"; import "./manager-Bw8JrihM.js"; import "./config-schema-CPzP2Ds6.js"; import "./channel-plugin-common-ClptUZHU.js"; import "./status-helpers-Cflmo90d.js"; import "./conversation-runtime-nmWgJSXS.js"; import "./runtime-whatsapp-boundary-XjdkYMz_.js"; import "./pairing-store-BGKLrjo6.js"; import "./json-store--JDX3zNL.js"; import "./secret-file-Bif7RlZ-.js"; import "./channel-config-schema-CgpS17zB.js"; import "./setup-binary-C2MYZTCc.js"; import "./archive-pOxyr9r4.js"; import "./fs-safe-DZyOgpPN.js"; import "./signal-cli-install-fVOL9FvX.js"; import "./setup-wizard-proxy-DoOpOF8S.js"; import "./setup-BI3ohdrT.js"; import "./dm-policy-shared-DtcQProI.js"; import "./runtime-env-DQOYrXVl.js"; import "./temp-path-B91lt0LF.js"; import "./diagnostic-CDTtMQBT.js"; import "./logging-CCTKg_fh.js"; import "./config-runtime-BYNizC50.js"; import "./level-overrides-DzIzQ3ZY.js"; import "./exec-approvals-BF_Qfdq8.js"; import "./webhook-ingress-D-H5frou.js"; import "./system-events-BU_NYynX.js"; import "./ssrf-policy-DYINyIKC.js"; import "./hook-runtime-BUYmDbaA.js"; import "./templating-BDXRiJUh.js"; import "./channel-reply-pipeline-BxH4-AP2.js"; import "./reply-history-n7nOPLta.js"; import "./commands-registry.data-BFXJWoqi.js"; import "./commands-registry-Bh9pJ817.js"; import "./frontmatter-CP5371Rm.js"; import "./env-overrides-BNSo89u5.js"; import "./skills-M0AZJeXx.js"; import "./skills-remote-BHxDA4Jw.js"; import "./workspace-dirs-DqDLiRvZ.js"; import "./pairing-token-DAszGmwD.js"; import "./skill-commands-D73dGR_l.js"; import "./config-CLRQPUSt.js"; import "./routes-XT2JfvT-.js"; import "./ssh-tunnel-LM52qY6N.js"; import "./server-middleware-BP59C6FL.js"; import "./provider-auth-ref-CQEp9sp3.js"; import "./provider-auth-helpers-Do3RFvdi.js"; import "./provider-api-key-auth-BEeRW3dq.js"; import "./pairing-labels-D27Y4Vv6.js"; import "./directory-runtime-D9Y42mW-.js"; import "./read-only-account-inspect-CJPRBFj7.js"; import "./src-BoNU6eQs.js"; import "./web-media-PKy3RbRG.js"; import "./media-understanding-BDOSvuM9.js"; import "./web-media-CiSbdGPs.js"; import "./state-paths-Dvb3Mfl3.js"; import "./llm-task-Br6Ixjlh.js"; import "./pi-model-discovery-DO3tFksS.js"; import "./exec-inline-eval-CpmxWJsW.js"; import "./target-registry-9OUOvlxj.js"; import "./external-content-DZI9vlJn.js"; import "./brave-onFD06fq.js"; import "./duckduckgo-CZuAOfiQ.js"; import "./exa-5bwgY04k.js"; import "./security-runtime-xlw0Fxx2.js"; import "./provider-usage-ClxTGn5c.js"; import "./provider-models-Bjv0V4OP.js"; import "./media-understanding-provider-DllGbg-v.js"; import "./media-understanding-provider-BDq4rFL-.js"; import "./provider-onboard-CSnPvkMM.js"; import "./onboard-BU8aRvq7.js"; import "./perplexity-web-search-provider-CI38RNUU.js"; import "./perplexity-CMZbsreI.js"; import "./model-definitions-CLagLj0g.js"; import "./onboard-0P7GBI2D.js"; import "./provider-catalog-CKHo9CRM.js"; import "./provider-models-Dmjtw6kn.js"; import "./stream-C-KGzzT0.js"; import "./web-search-CO1hvu_l.js"; import "./stagger-CFqdtCYL.js"; import "./command-secret-targets-DLs8jC2H.js"; import "./delivery-queue-DHURMSqX.js"; import "./channel-summary-Ctrv7moa.js"; import "./follow-redirects-CVAaqIk4.js"; import "./tool-policy-match-DQWWRSN4.js"; import "./runtime-CAdCdG-M.js"; import "./channel-status-BfM90KqH.js"; import "./discord-core-DLbIyXWy.js"; import "./cli-runtime-Cx1v7N7v.js"; import "./config-presence-DA3j8Nmi.js"; import "./query-expansion-BOJBTXsp.js"; import "./search-manager-DNBHwaee.js"; import "./acp-runtime-BHZj-SLU.js"; import "./telegram-core-DD8gCuaX.js"; import "./audit-BI48Fi3j.js"; import "./gateway-runtime-Dn2qAGY7.js"; import "./connection-auth-Nl2a3tDb.js"; import "./mcp-config-CDIWSqVk.js"; import "./run-command-DPUsJhO7.js"; import "./channel-setup-C5JbULY6.js"; import "./ssrf-runtime-BT3ekdqD.js"; import "./backup-create-BuxXJpr7.js"; import "./matrix-wu3iTLk7.js"; import "./helper-api-CFToxS1G.js"; import "./setup-group-access-BIiwXi_V.js"; import "./runtime-api-C0mTuF54.js"; import "./matrix-migration-snapshot-DTfN6Lm9.js"; import "./matrix-runtime-heavy-DJQtmbKo.js"; import "./diagnostics-otel-DAhTkbUZ.js"; import "./credentials-read-BLFr7diG.js"; import { C as isPollStartType, R as resolveMatrixAccountConfig, S as isPollEventType, _ as summarizeMatrixReactionEvents, f as MATRIX_ANNOTATION_RELATION_TYPE, g as selectOwnMatrixReactionEventIds, m as buildMatrixReactionRelationsPath, n as sendMessageMatrix, o as resolveMatrixRoomId, p as MATRIX_REACTION_EVENT_TYPE, t as reactMatrixMessage, v as buildPollResponseContent, w as parsePollStart } from "./send-C-3t8GKS.js"; import "./types-DPt19vBR.js"; import "./encryption-guidance-CfWz-j8b.js"; import "./lib-362MCLYr.js"; import "./BasicParser-DQZpQAx5.js"; import "./APEv2Parser-D9Lk3cbl.js"; import { _ as startMatrixVerification, a as confirmMatrixVerificationSas, b as withResolvedRoomAction, c as getMatrixRoomKeyBackupStatus, d as listMatrixVerifications, f as mismatchMatrixVerificationSas, g as scanMatrixVerificationQr, h as restoreMatrixRoomKeyBackup, i as confirmMatrixVerificationReciprocateQr, l as getMatrixVerificationSas, n as bootstrapMatrixVerification, o as generateMatrixVerificationQr, p as requestMatrixVerification, r as cancelMatrixVerification, s as getMatrixEncryptionStatus, t as acceptMatrixVerification, u as getMatrixVerificationStatus, v as verifyMatrixRecoveryKey, y as withResolvedActionClient } from "./verification-BeSB_N0Z.js"; import "./profile-BMjCtAqv.js"; import { t as applyMatrixProfileUpdate } from "./profile-update-BlcBvVTy.js"; import { o as resolveMatrixMessageAttachment, r as resolveMatrixPollRootEventId, s as resolveMatrixMessageBody, t as fetchMatrixPollMessageSummary } from "./poll-summary-emaGSpPn.js"; //#region extensions/matrix/src/matrix/actions/limits.ts function resolveMatrixActionLimit(raw, fallback) { if (typeof raw !== "number" || !Number.isFinite(raw)) return fallback; return Math.max(1, Math.floor(raw)); } //#endregion //#region extensions/matrix/src/matrix/actions/types.ts const MsgType = { Text: "m.text" }; const RelationType = { Replace: "m.replace", Annotation: MATRIX_ANNOTATION_RELATION_TYPE }; const EventType = { RoomMessage: "m.room.message", RoomPinnedEvents: "m.room.pinned_events", RoomTopic: "m.room.topic", Reaction: MATRIX_REACTION_EVENT_TYPE }; //#endregion //#region extensions/matrix/src/matrix/actions/summary.ts function summarizeMatrixRawEvent(event) { const content = event.content; const relates = content["m.relates_to"]; let relType; let eventId; if (relates) { if ("rel_type" in relates) { relType = relates.rel_type; eventId = relates.event_id; } else if ("m.in_reply_to" in relates) eventId = relates["m.in_reply_to"]?.event_id; } const relatesTo = relType || eventId ? { relType, eventId } : void 0; return { eventId: event.event_id, sender: event.sender, body: resolveMatrixMessageBody({ body: content.body, filename: content.filename, msgtype: content.msgtype }), msgtype: content.msgtype, attachment: resolveMatrixMessageAttachment({ body: content.body, filename: content.filename, msgtype: content.msgtype }), timestamp: event.origin_server_ts, relatesTo }; } async function readPinnedEvents(client, roomId) { try { return (await client.getRoomStateEvent(roomId, EventType.RoomPinnedEvents, "")).pinned.filter((id) => id.trim().length > 0); } catch (err) { const errObj = err; const httpStatus = errObj.statusCode; const errcode = errObj.body?.errcode; if (httpStatus === 404 || errcode === "M_NOT_FOUND") return []; throw err; } } async function fetchEventSummary(client, roomId, eventId) { try { const raw = await client.getEvent(roomId, eventId); if (raw.unsigned?.redacted_because) return null; const pollSummary = await fetchMatrixPollMessageSummary(client, roomId, raw); if (pollSummary) return pollSummary; return summarizeMatrixRawEvent(raw); } catch { return null; } } //#endregion //#region extensions/matrix/src/matrix/actions/messages.ts async function sendMatrixMessage(to, content, opts = {}) { return await sendMessageMatrix(to, content, { cfg: opts.cfg, mediaUrl: opts.mediaUrl, mediaLocalRoots: opts.mediaLocalRoots, replyToId: opts.replyToId, threadId: opts.threadId, audioAsVoice: opts.audioAsVoice, accountId: opts.accountId ?? void 0, client: opts.client, timeoutMs: opts.timeoutMs }); } async function editMatrixMessage(roomId, messageId, content, opts = {}) { const trimmed = content.trim(); if (!trimmed) throw new Error("Matrix edit requires content"); return await withResolvedRoomAction(roomId, opts, async (client, resolvedRoom) => { const newContent = { msgtype: MsgType.Text, body: trimmed }; const payload = { msgtype: MsgType.Text, body: `* ${trimmed}`, "m.new_content": newContent, "m.relates_to": { rel_type: RelationType.Replace, event_id: messageId } }; return { eventId: await client.sendMessage(resolvedRoom, payload) ?? null }; }); } async function deleteMatrixMessage(roomId, messageId, opts = {}) { await withResolvedRoomAction(roomId, opts, async (client, resolvedRoom) => { await client.redactEvent(resolvedRoom, messageId, opts.reason); }); } async function readMatrixMessages(roomId, opts = {}) { return await withResolvedRoomAction(roomId, opts, async (client, resolvedRoom) => { const limit = resolveMatrixActionLimit(opts.limit, 20); const token = opts.before?.trim() || opts.after?.trim() || void 0; const dir = opts.after ? "f" : "b"; const res = await client.doRequest("GET", `/_matrix/client/v3/rooms/${encodeURIComponent(resolvedRoom)}/messages`, { dir, limit, from: token }); const hydratedChunk = await client.hydrateEvents(resolvedRoom, res.chunk); const seenPollRoots = /* @__PURE__ */ new Set(); const messages = []; for (const event of hydratedChunk) { if (event.unsigned?.redacted_because) continue; if (event.type === EventType.RoomMessage) { messages.push(summarizeMatrixRawEvent(event)); continue; } if (!isPollEventType(event.type)) continue; const pollRootId = resolveMatrixPollRootEventId(event); if (!pollRootId || seenPollRoots.has(pollRootId)) continue; seenPollRoots.add(pollRootId); const pollSummary = await fetchMatrixPollMessageSummary(client, resolvedRoom, event); if (pollSummary) messages.push(pollSummary); } return { messages, nextBatch: res.end ?? null, prevBatch: res.start ?? null }; }); } //#endregion //#region extensions/matrix/src/matrix/actions/polls.ts function normalizeOptionIndexes(indexes) { const normalized = indexes.map((index) => Math.trunc(index)).filter((index) => Number.isFinite(index) && index > 0); return Array.from(new Set(normalized)); } function normalizeOptionIds(optionIds) { return Array.from(new Set(optionIds.map((optionId) => optionId.trim()).filter((optionId) => optionId.length > 0))); } function resolveSelectedAnswerIds(params) { const parsed = parsePollStart(params.pollContent); if (!parsed) throw new Error("Matrix poll vote requires a valid poll start event."); const selectedById = normalizeOptionIds(params.optionIds ?? []); const selectedByIndex = normalizeOptionIndexes(params.optionIndexes ?? []).map((index) => { const answer = parsed.answers[index - 1]; if (!answer) throw new Error(`Matrix poll option index ${index} is out of range for a poll with ${parsed.answers.length} options.`); return answer.id; }); const answerIds = normalizeOptionIds([...selectedById, ...selectedByIndex]); if (answerIds.length === 0) throw new Error("Matrix poll vote requires at least one poll option id or index."); if (answerIds.length > parsed.maxSelections) throw new Error(`Matrix poll allows at most ${parsed.maxSelections} selection${parsed.maxSelections === 1 ? "" : "s"}.`); const answerMap = new Map(parsed.answers.map((answer) => [answer.id, answer.text])); return { answerIds, labels: answerIds.map((answerId) => { const label = answerMap.get(answerId); if (!label) throw new Error(`Matrix poll option id "${answerId}" is not valid for poll ${parsed.question}.`); return label; }), maxSelections: parsed.maxSelections }; } async function voteMatrixPoll(roomId, pollId, opts = {}) { return await withResolvedRoomAction(roomId, opts, async (client, resolvedRoom) => { const pollEvent = await client.getEvent(resolvedRoom, pollId); if (!isPollStartType(typeof pollEvent.type === "string" ? pollEvent.type : "")) throw new Error(`Event ${pollId} is not a Matrix poll start event.`); const { answerIds, labels, maxSelections } = resolveSelectedAnswerIds({ optionIds: [...opts.optionIds ?? [], ...opts.optionId ? [opts.optionId] : []], optionIndexes: [...opts.optionIndexes ?? [], ...opts.optionIndex !== void 0 ? [opts.optionIndex] : []], pollContent: pollEvent.content }); const content = buildPollResponseContent(pollId, answerIds); return { eventId: await client.sendEvent(resolvedRoom, "m.poll.response", content) ?? null, roomId: resolvedRoom, pollId, answerIds, labels, maxSelections }; }); } //#endregion //#region extensions/matrix/src/matrix/actions/reactions.ts async function listMatrixReactionEvents(client, roomId, messageId, limit) { const res = await client.doRequest("GET", buildMatrixReactionRelationsPath(roomId, messageId), { dir: "b", limit }); return Array.isArray(res.chunk) ? res.chunk : []; } async function listMatrixReactions(roomId, messageId, opts = {}) { return await withResolvedRoomAction(roomId, opts, async (client, resolvedRoom) => { return summarizeMatrixReactionEvents(await listMatrixReactionEvents(client, resolvedRoom, messageId, resolveMatrixActionLimit(opts.limit, 100))); }); } async function removeMatrixReactions(roomId, messageId, opts = {}) { return await withResolvedRoomAction(roomId, opts, async (client, resolvedRoom) => { const chunk = await listMatrixReactionEvents(client, resolvedRoom, messageId, 200); const userId = await client.getUserId(); if (!userId) return { removed: 0 }; const toRemove = selectOwnMatrixReactionEventIds(chunk, userId, opts.emoji); if (toRemove.length === 0) return { removed: 0 }; await Promise.all(toRemove.map((id) => client.redactEvent(resolvedRoom, id))); return { removed: toRemove.length }; }); } //#endregion //#region extensions/matrix/src/matrix/actions/pins.ts async function updateMatrixPins(roomId, messageId, opts, update) { return await withResolvedRoomAction(roomId, opts, async (client, resolvedRoom) => { const next = update(await readPinnedEvents(client, resolvedRoom)); const payload = { pinned: next }; await client.sendStateEvent(resolvedRoom, EventType.RoomPinnedEvents, "", payload); return { pinned: next }; }); } async function pinMatrixMessage(roomId, messageId, opts = {}) { return await updateMatrixPins(roomId, messageId, opts, (current) => current.includes(messageId) ? current : [...current, messageId]); } async function unpinMatrixMessage(roomId, messageId, opts = {}) { return await updateMatrixPins(roomId, messageId, opts, (current) => current.filter((id) => id !== messageId)); } async function listMatrixPins(roomId, opts = {}) { return await withResolvedRoomAction(roomId, opts, async (client, resolvedRoom) => { const pinned = await readPinnedEvents(client, resolvedRoom); return { pinned, events: (await Promise.all(pinned.map(async (eventId) => { try { return await fetchEventSummary(client, resolvedRoom, eventId); } catch { return null; } }))).filter((event) => Boolean(event)) }; }); } //#endregion //#region extensions/matrix/src/matrix/actions/room.ts async function getMatrixMemberInfo(userId, opts = {}) { return await withResolvedActionClient(opts, async (client) => { const roomId = opts.roomId ? await resolveMatrixRoomId(client, opts.roomId) : void 0; const profile = await client.getUserProfile(userId); return { userId, profile: { displayName: profile?.displayname ?? null, avatarUrl: profile?.avatar_url ?? null }, membership: null, powerLevel: null, displayName: profile?.displayname ?? null, roomId: roomId ?? null }; }); } async function getMatrixRoomInfo(roomId, opts = {}) { return await withResolvedRoomAction(roomId, opts, async (client, resolvedRoom) => { let name = null; let topic = null; let canonicalAlias = null; let memberCount = null; try { const nameState = await client.getRoomStateEvent(resolvedRoom, "m.room.name", ""); name = typeof nameState?.name === "string" ? nameState.name : null; } catch {} try { const topicState = await client.getRoomStateEvent(resolvedRoom, EventType.RoomTopic, ""); topic = typeof topicState?.topic === "string" ? topicState.topic : null; } catch {} try { const aliasState = await client.getRoomStateEvent(resolvedRoom, "m.room.canonical_alias", ""); canonicalAlias = typeof aliasState?.alias === "string" ? aliasState.alias : null; } catch {} try { memberCount = (await client.getJoinedRoomMembers(resolvedRoom)).length; } catch {} return { roomId: resolvedRoom, name, topic, canonicalAlias, altAliases: [], memberCount }; }); } //#endregion //#region extensions/matrix/src/tool-actions.ts const messageActions = new Set([ "sendMessage", "editMessage", "deleteMessage", "readMessages" ]); const reactionActions = new Set(["react", "reactions"]); const pinActions = new Set([ "pinMessage", "unpinMessage", "listPins" ]); const pollActions = new Set(["pollVote"]); const profileActions = new Set(["setProfile"]); const verificationActions = new Set([ "encryptionStatus", "verificationList", "verificationRequest", "verificationAccept", "verificationCancel", "verificationStart", "verificationGenerateQr", "verificationScanQr", "verificationSas", "verificationConfirm", "verificationMismatch", "verificationConfirmQr", "verificationStatus", "verificationBootstrap", "verificationRecoveryKey", "verificationBackupStatus", "verificationBackupRestore" ]); function readRoomId(params, required = true) { const direct = readStringParam(params, "roomId") ?? readStringParam(params, "channelId"); if (direct) return direct; if (!required) return readStringParam(params, "to") ?? ""; return readStringParam(params, "to", { required: true }); } function toSnakeCaseKey(key) { return key.replace(/([A-Z]+)([A-Z][a-z])/g, "$1_$2").replace(/([a-z0-9])([A-Z])/g, "$1_$2").toLowerCase(); } function readRawParam(params, key) { if (Object.hasOwn(params, key)) return params[key]; const snakeKey = toSnakeCaseKey(key); if (snakeKey !== key && Object.hasOwn(params, snakeKey)) return params[snakeKey]; } function readStringAliasParam(params, keys, options = {}) { for (const key of keys) { const raw = readRawParam(params, key); if (typeof raw !== "string") continue; const trimmed = raw.trim(); if (trimmed) return trimmed; } if (options.required) throw new Error(`${keys[0]} required`); } function readNumericArrayParam(params, key, options = {}) { const { integer = false } = options; const raw = readRawParam(params, key); if (raw === void 0) return []; return (Array.isArray(raw) ? raw : [raw]).map((value) => { if (typeof value === "number" && Number.isFinite(value)) return value; if (typeof value === "string") { const trimmed = value.trim(); if (!trimmed) return null; const parsed = Number(trimmed); return Number.isFinite(parsed) ? parsed : null; } return null; }).filter((value) => value !== null).map((value) => integer ? Math.trunc(value) : value); } async function handleMatrixAction(params, cfg, opts = {}) { const action = readStringParam(params, "action", { required: true }); const accountId = readStringParam(params, "accountId") ?? void 0; const isActionEnabled = createActionGate(resolveMatrixAccountConfig({ cfg, accountId }).actions); const clientOpts = { cfg, ...accountId ? { accountId } : {} }; if (reactionActions.has(action)) { if (!isActionEnabled("reactions")) throw new Error("Matrix reactions are disabled."); const roomId = readRoomId(params); const messageId = readStringParam(params, "messageId", { required: true }); if (action === "react") { const { emoji, remove, isEmpty } = readReactionParams(params, { removeErrorMessage: "Emoji is required to remove a Matrix reaction." }); if (remove || isEmpty) return jsonResult({ ok: true, removed: (await removeMatrixReactions(roomId, messageId, { ...clientOpts, emoji: remove ? emoji : void 0 })).removed }); await reactMatrixMessage(roomId, messageId, emoji, clientOpts); return jsonResult({ ok: true, added: emoji }); } const limit = readNumberParam(params, "limit", { integer: true }); return jsonResult({ ok: true, reactions: await listMatrixReactions(roomId, messageId, { ...clientOpts, limit: limit ?? void 0 }) }); } if (pollActions.has(action)) { const roomId = readRoomId(params); const pollId = readStringAliasParam(params, ["pollId", "messageId"], { required: true }); if (!pollId) throw new Error("pollId required"); const optionId = readStringParam(params, "pollOptionId"); const optionIndex = readNumberParam(params, "pollOptionIndex", { integer: true }); const optionIds = [...readStringArrayParam(params, "pollOptionIds") ?? [], ...optionId ? [optionId] : []]; const optionIndexes = [...readNumericArrayParam(params, "pollOptionIndexes", { integer: true }), ...optionIndex !== void 0 ? [optionIndex] : []]; return jsonResult({ ok: true, result: await voteMatrixPoll(roomId, pollId, { ...clientOpts, optionIds, optionIndexes }) }); } if (messageActions.has(action)) { if (!isActionEnabled("messages")) throw new Error("Matrix messages are disabled."); switch (action) { case "sendMessage": { const to = readStringParam(params, "to", { required: true }); const mediaUrl = readStringParam(params, "mediaUrl", { trim: false }) ?? readStringParam(params, "media", { trim: false }) ?? readStringParam(params, "filePath", { trim: false }) ?? readStringParam(params, "path", { trim: false }); const content = readStringParam(params, "content", { required: !mediaUrl, allowEmpty: true }); const replyToId = readStringParam(params, "replyToId") ?? readStringParam(params, "replyTo"); const threadId = readStringParam(params, "threadId"); const audioAsVoice = typeof readRawParam(params, "audioAsVoice") === "boolean" ? readRawParam(params, "audioAsVoice") : typeof readRawParam(params, "asVoice") === "boolean" ? readRawParam(params, "asVoice") : void 0; return jsonResult({ ok: true, result: await sendMatrixMessage(to, content, { mediaUrl: mediaUrl ?? void 0, mediaLocalRoots: opts.mediaLocalRoots, replyToId: replyToId ?? void 0, threadId: threadId ?? void 0, audioAsVoice, ...clientOpts }) }); } case "editMessage": return jsonResult({ ok: true, result: await editMatrixMessage(readRoomId(params), readStringParam(params, "messageId", { required: true }), readStringParam(params, "content", { required: true }), clientOpts) }); case "deleteMessage": await deleteMatrixMessage(readRoomId(params), readStringParam(params, "messageId", { required: true }), { reason: readStringParam(params, "reason") ?? void 0, ...clientOpts }); return jsonResult({ ok: true, deleted: true }); case "readMessages": { const roomId = readRoomId(params); const limit = readNumberParam(params, "limit", { integer: true }); const before = readStringParam(params, "before"); const after = readStringParam(params, "after"); return jsonResult({ ok: true, ...await readMatrixMessages(roomId, { limit: limit ?? void 0, before: before ?? void 0, after: after ?? void 0, ...clientOpts }) }); } default: break; } } if (pinActions.has(action)) { if (!isActionEnabled("pins")) throw new Error("Matrix pins are disabled."); const roomId = readRoomId(params); if (action === "pinMessage") return jsonResult({ ok: true, pinned: (await pinMatrixMessage(roomId, readStringParam(params, "messageId", { required: true }), clientOpts)).pinned }); if (action === "unpinMessage") return jsonResult({ ok: true, pinned: (await unpinMatrixMessage(roomId, readStringParam(params, "messageId", { required: true }), clientOpts)).pinned }); const result = await listMatrixPins(roomId, clientOpts); return jsonResult({ ok: true, pinned: result.pinned, events: result.events }); } if (profileActions.has(action)) { if (!isActionEnabled("profile")) throw new Error("Matrix profile updates are disabled."); const avatarPath = readStringParam(params, "avatarPath") ?? readStringParam(params, "path") ?? readStringParam(params, "filePath"); return jsonResult({ ok: true, ...await applyMatrixProfileUpdate({ cfg, account: accountId, displayName: readStringParam(params, "displayName") ?? readStringParam(params, "name"), avatarUrl: readStringParam(params, "avatarUrl"), avatarPath, mediaLocalRoots: opts.mediaLocalRoots }) }); } if (action === "memberInfo") { if (!isActionEnabled("memberInfo")) throw new Error("Matrix member info is disabled."); return jsonResult({ ok: true, member: await getMatrixMemberInfo(readStringParam(params, "userId", { required: true }), { roomId: readStringParam(params, "roomId") ?? readStringParam(params, "channelId") ?? void 0, ...clientOpts }) }); } if (action === "channelInfo") { if (!isActionEnabled("channelInfo")) throw new Error("Matrix room info is disabled."); return jsonResult({ ok: true, room: await getMatrixRoomInfo(readRoomId(params), clientOpts) }); } if (verificationActions.has(action)) { if (!isActionEnabled("verification")) throw new Error("Matrix verification actions are disabled."); const requestId = readStringParam(params, "requestId") ?? readStringParam(params, "verificationId") ?? readStringParam(params, "id"); if (action === "encryptionStatus") return jsonResult({ ok: true, status: await getMatrixEncryptionStatus({ includeRecoveryKey: params.includeRecoveryKey === true, ...clientOpts }) }); if (action === "verificationStatus") return jsonResult({ ok: true, status: await getMatrixVerificationStatus({ includeRecoveryKey: params.includeRecoveryKey === true, ...clientOpts }) }); if (action === "verificationBootstrap") { const result = await bootstrapMatrixVerification({ recoveryKey: readStringParam(params, "recoveryKey", { trim: false }) ?? readStringParam(params, "key", { trim: false }) ?? void 0, forceResetCrossSigning: params.forceResetCrossSigning === true, ...clientOpts }); return jsonResult({ ok: result.success, result }); } if (action === "verificationRecoveryKey") { const result = await verifyMatrixRecoveryKey(readStringParam({ recoveryKey: readStringParam(params, "recoveryKey", { trim: false }) ?? readStringParam(params, "key", { trim: false }) }, "recoveryKey", { required: true, trim: false }), clientOpts); return jsonResult({ ok: result.success, result }); } if (action === "verificationBackupStatus") return jsonResult({ ok: true, status: await getMatrixRoomKeyBackupStatus(clientOpts) }); if (action === "verificationBackupRestore") { const result = await restoreMatrixRoomKeyBackup({ recoveryKey: readStringParam(params, "recoveryKey", { trim: false }) ?? readStringParam(params, "key", { trim: false }) ?? void 0, ...clientOpts }); return jsonResult({ ok: result.success, result }); } if (action === "verificationList") return jsonResult({ ok: true, verifications: await listMatrixVerifications(clientOpts) }); if (action === "verificationRequest") { const userId = readStringParam(params, "userId"); const deviceId = readStringParam(params, "deviceId"); const roomId = readStringParam(params, "roomId") ?? readStringParam(params, "channelId"); return jsonResult({ ok: true, verification: await requestMatrixVerification({ ownUser: typeof params.ownUser === "boolean" ? params.ownUser : void 0, userId: userId ?? void 0, deviceId: deviceId ?? void 0, roomId: roomId ?? void 0, ...clientOpts }) }); } if (action === "verificationAccept") return jsonResult({ ok: true, verification: await acceptMatrixVerification(readStringParam({ requestId }, "requestId", { required: true }), clientOpts) }); if (action === "verificationCancel") { const reason = readStringParam(params, "reason"); const code = readStringParam(params, "code"); return jsonResult({ ok: true, verification: await cancelMatrixVerification(readStringParam({ requestId }, "requestId", { required: true }), { reason: reason ?? void 0, code: code ?? void 0, ...clientOpts }) }); } if (action === "verificationStart") { const method = readStringParam(params, "method")?.trim().toLowerCase(); if (method && method !== "sas") throw new Error("Matrix verificationStart only supports method=sas; use verificationGenerateQr/verificationScanQr for QR flows."); return jsonResult({ ok: true, verification: await startMatrixVerification(readStringParam({ requestId }, "requestId", { required: true }), { method: "sas", ...clientOpts }) }); } if (action === "verificationGenerateQr") return jsonResult({ ok: true, ...await generateMatrixVerificationQr(readStringParam({ requestId }, "requestId", { required: true }), clientOpts) }); if (action === "verificationScanQr") { const qrDataBase64 = readStringParam(params, "qrDataBase64") ?? readStringParam(params, "qrData") ?? readStringParam(params, "qr"); return jsonResult({ ok: true, verification: await scanMatrixVerificationQr(readStringParam({ requestId }, "requestId", { required: true }), readStringParam({ qrDataBase64 }, "qrDataBase64", { required: true }), clientOpts) }); } if (action === "verificationSas") return jsonResult({ ok: true, sas: await getMatrixVerificationSas(readStringParam({ requestId }, "requestId", { required: true }), clientOpts) }); if (action === "verificationConfirm") return jsonResult({ ok: true, verification: await confirmMatrixVerificationSas(readStringParam({ requestId }, "requestId", { required: true }), clientOpts) }); if (action === "verificationMismatch") return jsonResult({ ok: true, verification: await mismatchMatrixVerificationSas(readStringParam({ requestId }, "requestId", { required: true }), clientOpts) }); if (action === "verificationConfirmQr") return jsonResult({ ok: true, verification: await confirmMatrixVerificationReciprocateQr(readStringParam({ requestId }, "requestId", { required: true }), clientOpts) }); } throw new Error(`Unsupported Matrix action: ${action}`); } //#endregion export { handleMatrixAction };