openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
809 lines (807 loc) • 39.1 kB
JavaScript
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 { n as isRich, r as theme } from "./theme-CdOoMzRk.js";
import { s as setVerbose, t as danger } from "./globals-DBUMOBZ8.js";
import { h as writeRuntimeJson, m as defaultRuntime } from "./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 { t as formatDocsLink } from "./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 { s as loadConfig } from "./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 { c as normalizeChatChannelId, r as getChatChannelMeta } from "./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 { h as GATEWAY_CLIENT_NAMES, m as GATEWAY_CLIENT_MODES } from "./message-channel-BliByQBl.js";
import "./store-C5UK26Ce.js";
import "./runtime-Iz8uZ7EU.js";
import { s as getChannelPlugin } from "./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 { n as withProgress } from "./progress-C78aA91n.js";
import { t as formatHelpExamples } from "./help-format-C_5MeE_w.js";
import "./identity-Dp-UIak4.js";
import "./heartbeat-Bdfr_onc.js";
import { Hd as resolveCommandSecretRefsViaGateway, Nd as formatTargetDisplay, Ud as CHANNEL_MESSAGE_ACTION_NAMES, Vd as resolveMessageSecretScope, Xv as runGlobalGatewayStopSafely, aa as createOutboundSendDeps, tc as runMessageAction, ua as createDefaultDeps } from "./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 "./common-zReYuoMM.js";
import "./image-ops-By4YfyWa.js";
import "./thinking-CJoSRIGR.js";
import "./path-alias-guards-CwRM04O1.js";
import "./sandbox-paths-Cn8i8Jxm.js";
import { d as CHANNEL_TARGET_DESCRIPTION, u as CHANNEL_TARGETS_DESCRIPTION } from "./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 { o as getScopedChannelsCommandSecretTargets } from "./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 { n as runCommandWithRuntime } from "./cli-utils-C5ijQCJ_.js";
import { t as collectOption } from "./helpers-CvoyfQ8F.js";
import { n as renderTable, t as getTerminalTableWidth } from "./table-7g_hocqO.js";
import "./channel-plugin-ids-CvPuUsCE.js";
import { t as shortenText } from "./text-format-bqpkYCKW.js";
import { t as ensurePluginRegistryLoaded } from "./plugin-registry-D62zMn9j.js";
//#region src/infra/outbound/format.ts
const resolveChannelLabel$1 = (channel) => {
const pluginLabel = getChannelPlugin(channel)?.meta.label;
if (pluginLabel) return pluginLabel;
const normalized = normalizeChatChannelId(channel);
if (normalized) return getChatChannelMeta(normalized).label;
return channel;
};
function formatOutboundDeliverySummary(channel, result) {
if (!result) return `✅ Sent via ${resolveChannelLabel$1(channel)}. Message ID: unknown`;
const base = `✅ Sent via ${resolveChannelLabel$1(result.channel)}. Message ID: ${result.messageId}`;
if ("chatId" in result) return `${base} (chat ${result.chatId})`;
if ("channelId" in result) return `${base} (channel ${result.channelId})`;
if ("roomId" in result) return `${base} (room ${result.roomId})`;
if ("conversationId" in result) return `${base} (conversation ${result.conversationId})`;
return base;
}
function formatGatewaySummary(params) {
return `✅ ${params.action ?? "Sent"} via gateway${params.channel ? ` (${params.channel})` : ""}. Message ID: ${params.messageId ?? "unknown"}`;
}
//#endregion
//#region src/commands/message-format.ts
const resolveChannelLabel = (channel) => getChannelPlugin(channel)?.meta.label ?? channel;
function extractMessageId(payload) {
if (!payload || typeof payload !== "object") return null;
const direct = payload.messageId;
if (typeof direct === "string" && direct.trim()) return direct.trim();
const result = payload.result;
if (result && typeof result === "object") {
const nested = result.messageId;
if (typeof nested === "string" && nested.trim()) return nested.trim();
}
return null;
}
function buildMessageCliJson(result) {
return {
action: result.action,
channel: result.channel,
dryRun: result.dryRun,
handledBy: result.handledBy,
payload: result.payload
};
}
function renderObjectSummary(payload, opts) {
if (!payload || typeof payload !== "object") return [String(payload)];
const obj = payload;
const keys = Object.keys(obj);
if (keys.length === 0) return [theme.muted("(empty)")];
const rows = keys.slice(0, 20).map((k) => {
const v = obj[k];
return {
Key: k,
Value: shortenText(v == null ? "null" : Array.isArray(v) ? `${v.length} items` : typeof v === "object" ? "object" : typeof v === "string" ? v : typeof v === "number" ? String(v) : typeof v === "boolean" ? v ? "true" : "false" : typeof v === "bigint" ? v.toString() : typeof v === "symbol" ? v.toString() : typeof v === "function" ? "function" : "unknown", 96)
};
});
return [renderTable({
width: opts.width,
columns: [{
key: "Key",
header: "Key",
minWidth: 16
}, {
key: "Value",
header: "Value",
flex: true,
minWidth: 24
}],
rows
}).trimEnd()];
}
function renderMessageList(messages, opts, emptyLabel) {
const rows = messages.slice(0, 25).map((m) => {
const msg = m;
const id = typeof msg.id === "string" && msg.id || typeof msg.ts === "string" && msg.ts || typeof msg.messageId === "string" && msg.messageId || "";
const authorObj = msg.author;
const author = typeof msg.authorTag === "string" && msg.authorTag || typeof authorObj?.username === "string" && authorObj.username || typeof msg.user === "string" && msg.user || "";
const time = typeof msg.timestamp === "string" && msg.timestamp || typeof msg.ts === "string" && msg.ts || "";
const text = typeof msg.content === "string" && msg.content || typeof msg.text === "string" && msg.text || "";
return {
Time: shortenText(time, 28),
Author: shortenText(author, 22),
Text: shortenText(text.replace(/\s+/g, " ").trim(), 90),
Id: shortenText(id, 22)
};
});
if (rows.length === 0) return [theme.muted(emptyLabel)];
return [renderTable({
width: opts.width,
columns: [
{
key: "Time",
header: "Time",
minWidth: 14
},
{
key: "Author",
header: "Author",
minWidth: 10
},
{
key: "Text",
header: "Text",
flex: true,
minWidth: 24
},
{
key: "Id",
header: "Id",
minWidth: 10
}
],
rows
}).trimEnd()];
}
function renderMessagesFromPayload(payload, opts) {
if (!payload || typeof payload !== "object") return null;
const messages = payload.messages;
if (!Array.isArray(messages)) return null;
return renderMessageList(messages, opts, "No messages.");
}
function renderPinsFromPayload(payload, opts) {
if (!payload || typeof payload !== "object") return null;
const pins = payload.pins;
if (!Array.isArray(pins)) return null;
return renderMessageList(pins, opts, "No pins.");
}
function extractDiscordSearchResultsMessages(results) {
if (!results || typeof results !== "object") return null;
const raw = results.messages;
if (!Array.isArray(raw)) return null;
const flattened = [];
for (const entry of raw) if (Array.isArray(entry) && entry.length > 0) flattened.push(entry[0]);
else if (entry && typeof entry === "object") flattened.push(entry);
return flattened.length ? flattened : null;
}
function renderReactions(payload, opts) {
if (!payload || typeof payload !== "object") return null;
const reactions = payload.reactions;
if (!Array.isArray(reactions)) return null;
const rows = reactions.slice(0, 50).map((r) => {
const entry = r;
const emojiObj = entry.emoji;
return {
Emoji: typeof emojiObj?.raw === "string" && emojiObj.raw || typeof entry.name === "string" && entry.name || typeof entry.emoji === "string" && entry.emoji || "",
Count: typeof entry.count === "number" ? String(entry.count) : "",
Users: shortenText((Array.isArray(entry.users) ? entry.users.slice(0, 8).map((u) => {
if (typeof u === "string") return u;
if (!u || typeof u !== "object") return "";
const user = u;
return typeof user.tag === "string" && user.tag || typeof user.username === "string" && user.username || typeof user.id === "string" && user.id || "";
}).filter(Boolean) : []).join(", "), 72)
};
});
if (rows.length === 0) return [theme.muted("No reactions.")];
return [renderTable({
width: opts.width,
columns: [
{
key: "Emoji",
header: "Emoji",
minWidth: 8
},
{
key: "Count",
header: "Count",
align: "right",
minWidth: 6
},
{
key: "Users",
header: "Users",
flex: true,
minWidth: 20
}
],
rows
}).trimEnd()];
}
function formatMessageCliText(result) {
const rich = isRich();
const ok = (text) => rich ? theme.success(text) : text;
const muted = (text) => rich ? theme.muted(text) : text;
const heading = (text) => rich ? theme.heading(text) : text;
const opts = { width: getTerminalTableWidth() };
if (result.handledBy === "dry-run") return [muted(`[dry-run] would run ${result.action} via ${result.channel}`)];
if (result.kind === "broadcast") {
const results = result.payload.results ?? [];
const rows = results.map((entry) => ({
Channel: resolveChannelLabel(entry.channel),
Target: shortenText(formatTargetDisplay({
channel: entry.channel,
target: entry.to
}), 36),
Status: entry.ok ? "ok" : "error",
Error: entry.ok ? "" : shortenText(entry.error ?? "unknown error", 48)
}));
const okCount = results.filter((entry) => entry.ok).length;
const total = results.length;
return [ok(`✅ Broadcast complete (${okCount}/${total} succeeded, ${total - okCount} failed)`), renderTable({
width: opts.width,
columns: [
{
key: "Channel",
header: "Channel",
minWidth: 10
},
{
key: "Target",
header: "Target",
minWidth: 12,
flex: true
},
{
key: "Status",
header: "Status",
minWidth: 6
},
{
key: "Error",
header: "Error",
minWidth: 20,
flex: true
}
],
rows: rows.slice(0, 50)
}).trimEnd()];
}
if (result.kind === "send") {
if (result.handledBy === "core" && result.sendResult) {
const send = result.sendResult;
if (send.via === "direct") {
const directResult = send.result;
return [ok(formatOutboundDeliverySummary(send.channel, directResult))];
}
const gatewayResult = send.result;
return [ok(formatGatewaySummary({
channel: send.channel,
messageId: gatewayResult?.messageId ?? null
}))];
}
const label = resolveChannelLabel(result.channel);
const msgId = extractMessageId(result.payload);
return [ok(`✅ Sent via ${label}.${msgId ? ` Message ID: ${msgId}` : ""}`)];
}
if (result.kind === "poll") {
if (result.handledBy === "core" && result.pollResult) {
const poll = result.pollResult;
const pollId = poll.result?.pollId;
const msgId = poll.result?.messageId ?? null;
const lines = [ok(formatGatewaySummary({
action: "Poll sent",
channel: poll.channel,
messageId: msgId
}))];
if (pollId) lines.push(ok(`Poll id: ${pollId}`));
return lines;
}
const label = resolveChannelLabel(result.channel);
const msgId = extractMessageId(result.payload);
return [ok(`✅ Poll sent via ${label}.${msgId ? ` Message ID: ${msgId}` : ""}`)];
}
const payload = result.payload;
const lines = [];
if (result.action === "react") {
const added = payload.added;
const removed = payload.removed;
if (typeof added === "string" && added.trim()) {
lines.push(ok(`✅ Reaction added: ${added.trim()}`));
return lines;
}
if (typeof removed === "string" && removed.trim()) {
lines.push(ok(`✅ Reaction removed: ${removed.trim()}`));
return lines;
}
if (Array.isArray(removed)) {
const list = removed.map((x) => String(x).trim()).filter(Boolean).join(", ");
lines.push(ok(`✅ Reactions removed${list ? `: ${list}` : ""}`));
return lines;
}
lines.push(ok("✅ Reaction updated."));
return lines;
}
const reactionsTable = renderReactions(payload, opts);
if (reactionsTable && result.action === "reactions") {
lines.push(heading("Reactions"));
lines.push(reactionsTable[0] ?? "");
return lines;
}
if (result.action === "read") {
const messagesTable = renderMessagesFromPayload(payload, opts);
if (messagesTable) {
lines.push(heading("Messages"));
lines.push(messagesTable[0] ?? "");
return lines;
}
}
if (result.action === "list-pins") {
const pinsTable = renderPinsFromPayload(payload, opts);
if (pinsTable) {
lines.push(heading("Pinned messages"));
lines.push(pinsTable[0] ?? "");
return lines;
}
}
if (result.action === "search") {
const results = payload.results;
const list = extractDiscordSearchResultsMessages(results);
if (list) {
lines.push(heading("Search results"));
lines.push(renderMessageList(list, opts, "No results.")[0] ?? "");
return lines;
}
}
lines.push(ok(`✅ ${result.action} via ${resolveChannelLabel(result.channel)}.`));
const summary = renderObjectSummary(payload, opts);
if (summary.length) {
lines.push("");
lines.push(...summary);
lines.push("");
lines.push(muted("Tip: use --json for full output."));
}
return lines;
}
//#endregion
//#region src/commands/message.ts
async function messageCommand(opts, deps, runtime) {
const loadedRaw = loadConfig();
const scope = resolveMessageSecretScope({
channel: opts.channel,
target: opts.target,
targets: opts.targets,
accountId: opts.accountId
});
const scopedTargets = getScopedChannelsCommandSecretTargets({
config: loadedRaw,
channel: scope.channel,
accountId: scope.accountId
});
const { resolvedConfig: cfg, diagnostics } = await resolveCommandSecretRefsViaGateway({
config: loadedRaw,
commandName: "message",
targetIds: scopedTargets.targetIds,
...scopedTargets.allowedPaths ? { allowedPaths: scopedTargets.allowedPaths } : {}
});
for (const entry of diagnostics) runtime.log(`[secrets] ${entry}`);
const actionInput = (typeof opts.action === "string" ? opts.action.trim() : "") || "send";
const actionMatch = CHANNEL_MESSAGE_ACTION_NAMES.find((name) => name.toLowerCase() === actionInput.toLowerCase());
if (!actionMatch) throw new Error(`Unknown message action: ${actionInput}`);
const action = actionMatch;
const outboundDeps = createOutboundSendDeps(deps);
const run = async () => await runMessageAction({
cfg,
action,
params: opts,
deps: outboundDeps,
gateway: {
clientName: GATEWAY_CLIENT_NAMES.CLI,
mode: GATEWAY_CLIENT_MODES.CLI
}
});
const json = opts.json === true;
const dryRun = opts.dryRun === true;
const result = !json && !dryRun && (action === "send" || action === "poll") ? await withProgress({
label: action === "poll" ? "Sending poll..." : "Sending...",
indeterminate: true,
enabled: true
}, run) : await run();
if (json) {
writeRuntimeJson(runtime, buildMessageCliJson(result));
return;
}
for (const line of formatMessageCliText(result)) runtime.log(line);
}
//#endregion
//#region src/cli/program/message/helpers.ts
function normalizeMessageOptions(opts) {
const { account, ...rest } = opts;
return {
...rest,
accountId: typeof account === "string" ? account : void 0
};
}
async function runPluginStopHooks() {
await runGlobalGatewayStopSafely({
event: { reason: "cli message action complete" },
ctx: {},
onError: (err) => defaultRuntime.error(danger(`gateway_stop hook failed: ${String(err)}`))
});
}
function createMessageCliHelpers(message, messageChannelOptions) {
const withMessageBase = (command) => command.option("--channel <channel>", `Channel: ${messageChannelOptions}`).option("--account <id>", "Channel account id (accountId)").option("--json", "Output result as JSON", false).option("--dry-run", "Print payload and skip sending", false).option("--verbose", "Verbose logging", false);
const withMessageTarget = (command) => command.option("-t, --target <dest>", CHANNEL_TARGET_DESCRIPTION);
const withRequiredMessageTarget = (command) => command.requiredOption("-t, --target <dest>", CHANNEL_TARGET_DESCRIPTION);
const runMessageAction = async (action, opts) => {
setVerbose(Boolean(opts.verbose));
ensurePluginRegistryLoaded();
const deps = createDefaultDeps();
let failed = false;
await runCommandWithRuntime(defaultRuntime, async () => {
await messageCommand({
...normalizeMessageOptions(opts),
action
}, deps, defaultRuntime);
}, (err) => {
failed = true;
defaultRuntime.error(danger(String(err)));
});
await runPluginStopHooks();
defaultRuntime.exit(failed ? 1 : 0);
};
return {
withMessageBase,
withMessageTarget,
withRequiredMessageTarget,
runMessageAction
};
}
//#endregion
//#region src/cli/program/message/register.broadcast.ts
function registerMessageBroadcastCommand(message, helpers) {
helpers.withMessageBase(message.command("broadcast").description("Broadcast a message to multiple targets")).requiredOption("--targets <target...>", CHANNEL_TARGETS_DESCRIPTION).option("--message <text>", "Message to send").option("--media <url>", "Media URL").action(async (options) => {
await helpers.runMessageAction("broadcast", options);
});
}
//#endregion
//#region src/cli/program/message/register.discord-admin.ts
function registerMessageDiscordAdminCommands(message, helpers) {
const role = message.command("role").description("Role actions");
helpers.withMessageBase(role.command("info").description("List roles").requiredOption("--guild-id <id>", "Guild id")).action(async (opts) => {
await helpers.runMessageAction("role-info", opts);
});
helpers.withMessageBase(role.command("add").description("Add role to a member").requiredOption("--guild-id <id>", "Guild id").requiredOption("--user-id <id>", "User id").requiredOption("--role-id <id>", "Role id")).action(async (opts) => {
await helpers.runMessageAction("role-add", opts);
});
helpers.withMessageBase(role.command("remove").description("Remove role from a member").requiredOption("--guild-id <id>", "Guild id").requiredOption("--user-id <id>", "User id").requiredOption("--role-id <id>", "Role id")).action(async (opts) => {
await helpers.runMessageAction("role-remove", opts);
});
const channel = message.command("channel").description("Channel actions");
helpers.withMessageBase(helpers.withRequiredMessageTarget(channel.command("info").description("Fetch channel info"))).action(async (opts) => {
await helpers.runMessageAction("channel-info", opts);
});
helpers.withMessageBase(channel.command("list").description("List channels").requiredOption("--guild-id <id>", "Guild id")).action(async (opts) => {
await helpers.runMessageAction("channel-list", opts);
});
const member = message.command("member").description("Member actions");
helpers.withMessageBase(member.command("info").description("Fetch member info").requiredOption("--user-id <id>", "User id")).option("--guild-id <id>", "Guild id (Discord)").action(async (opts) => {
await helpers.runMessageAction("member-info", opts);
});
const voice = message.command("voice").description("Voice actions");
helpers.withMessageBase(voice.command("status").description("Fetch voice status").requiredOption("--guild-id <id>", "Guild id").requiredOption("--user-id <id>", "User id")).action(async (opts) => {
await helpers.runMessageAction("voice-status", opts);
});
const event = message.command("event").description("Event actions");
helpers.withMessageBase(event.command("list").description("List scheduled events").requiredOption("--guild-id <id>", "Guild id")).action(async (opts) => {
await helpers.runMessageAction("event-list", opts);
});
helpers.withMessageBase(event.command("create").description("Create a scheduled event").requiredOption("--guild-id <id>", "Guild id").requiredOption("--event-name <name>", "Event name").requiredOption("--start-time <iso>", "Event start time")).option("--end-time <iso>", "Event end time").option("--desc <text>", "Event description").option("--channel-id <id>", "Channel id").option("--location <text>", "Event location").option("--event-type <stage|external|voice>", "Event type").action(async (opts) => {
await helpers.runMessageAction("event-create", opts);
});
helpers.withMessageBase(message.command("timeout").description("Timeout a member").requiredOption("--guild-id <id>", "Guild id").requiredOption("--user-id <id>", "User id")).option("--duration-min <n>", "Timeout duration minutes").option("--until <iso>", "Timeout until").option("--reason <text>", "Moderation reason").action(async (opts) => {
await helpers.runMessageAction("timeout", opts);
});
helpers.withMessageBase(message.command("kick").description("Kick a member").requiredOption("--guild-id <id>", "Guild id").requiredOption("--user-id <id>", "User id")).option("--reason <text>", "Moderation reason").action(async (opts) => {
await helpers.runMessageAction("kick", opts);
});
helpers.withMessageBase(message.command("ban").description("Ban a member").requiredOption("--guild-id <id>", "Guild id").requiredOption("--user-id <id>", "User id")).option("--reason <text>", "Moderation reason").option("--delete-days <n>", "Ban delete message days").action(async (opts) => {
await helpers.runMessageAction("ban", opts);
});
}
//#endregion
//#region src/cli/program/message/register.emoji-sticker.ts
function registerMessageEmojiCommands(message, helpers) {
const emoji = message.command("emoji").description("Emoji actions");
helpers.withMessageBase(emoji.command("list").description("List emojis")).option("--guild-id <id>", "Guild id (Discord)").action(async (opts) => {
await helpers.runMessageAction("emoji-list", opts);
});
helpers.withMessageBase(emoji.command("upload").description("Upload an emoji").requiredOption("--guild-id <id>", "Guild id")).requiredOption("--emoji-name <name>", "Emoji name").requiredOption("--media <path-or-url>", "Emoji media (path or URL)").option("--role-ids <id>", "Role id (repeat)", collectOption, []).action(async (opts) => {
await helpers.runMessageAction("emoji-upload", opts);
});
}
function registerMessageStickerCommands(message, helpers) {
const sticker = message.command("sticker").description("Sticker actions");
helpers.withMessageBase(helpers.withRequiredMessageTarget(sticker.command("send").description("Send stickers"))).requiredOption("--sticker-id <id>", "Sticker id (repeat)", collectOption).option("-m, --message <text>", "Optional message body").action(async (opts) => {
await helpers.runMessageAction("sticker", opts);
});
helpers.withMessageBase(sticker.command("upload").description("Upload a sticker").requiredOption("--guild-id <id>", "Guild id")).requiredOption("--sticker-name <name>", "Sticker name").requiredOption("--sticker-desc <text>", "Sticker description").requiredOption("--sticker-tags <tags>", "Sticker tags").requiredOption("--media <path-or-url>", "Sticker media (path or URL)").action(async (opts) => {
await helpers.runMessageAction("sticker-upload", opts);
});
}
//#endregion
//#region src/cli/program/message/register.permissions-search.ts
function registerMessagePermissionsCommand(message, helpers) {
helpers.withMessageBase(helpers.withRequiredMessageTarget(message.command("permissions").description("Fetch channel permissions"))).action(async (opts) => {
await helpers.runMessageAction("permissions", opts);
});
}
function registerMessageSearchCommand(message, helpers) {
helpers.withMessageBase(message.command("search").description("Search Discord messages")).requiredOption("--guild-id <id>", "Guild id").requiredOption("--query <text>", "Search query").option("--channel-id <id>", "Channel id").option("--channel-ids <id>", "Channel id (repeat)", collectOption, []).option("--author-id <id>", "Author id").option("--author-ids <id>", "Author id (repeat)", collectOption, []).option("--limit <n>", "Result limit").action(async (opts) => {
await helpers.runMessageAction("search", opts);
});
}
//#endregion
//#region src/cli/program/message/register.pins.ts
function registerMessagePinCommands(message, helpers) {
helpers.withMessageBase(helpers.withRequiredMessageTarget(message.command("pin").description("Pin a message"))).requiredOption("--message-id <id>", "Message id").action(async (opts) => {
await helpers.runMessageAction("pin", opts);
}), helpers.withMessageBase(helpers.withRequiredMessageTarget(message.command("unpin").description("Unpin a message"))).requiredOption("--message-id <id>", "Message id").action(async (opts) => {
await helpers.runMessageAction("unpin", opts);
}), helpers.withMessageBase(helpers.withRequiredMessageTarget(message.command("pins").description("List pinned messages"))).option("--limit <n>", "Result limit").action(async (opts) => {
await helpers.runMessageAction("list-pins", opts);
});
}
//#endregion
//#region src/cli/program/message/register.poll.ts
function registerMessagePollCommand(message, helpers) {
helpers.withMessageBase(helpers.withRequiredMessageTarget(message.command("poll").description("Send a poll"))).requiredOption("--poll-question <text>", "Poll question").option("--poll-option <choice>", "Poll option (repeat 2-12 times)", collectOption, []).option("--poll-multi", "Allow multiple selections", false).option("--poll-duration-hours <n>", "Poll duration in hours (Discord)").option("--poll-duration-seconds <n>", "Poll duration in seconds (Telegram; 5-600)").option("--poll-anonymous", "Send an anonymous poll (Telegram)", false).option("--poll-public", "Send a non-anonymous poll (Telegram)", false).option("-m, --message <text>", "Optional message body").option("--silent", "Send poll silently without notification (Telegram + Discord where supported)", false).option("--thread-id <id>", "Thread id (Telegram forum topic / Slack thread ts)").action(async (opts) => {
await helpers.runMessageAction("poll", opts);
});
}
//#endregion
//#region src/cli/program/message/register.reactions.ts
function registerMessageReactionsCommands(message, helpers) {
helpers.withMessageBase(helpers.withRequiredMessageTarget(message.command("react").description("Add or remove a reaction"))).requiredOption("--message-id <id>", "Message id").option("--emoji <emoji>", "Emoji for reactions").option("--remove", "Remove reaction", false).option("--participant <id>", "WhatsApp reaction participant").option("--from-me", "WhatsApp reaction fromMe", false).option("--target-author <id>", "Signal reaction target author (uuid or phone)").option("--target-author-uuid <uuid>", "Signal reaction target author uuid").action(async (opts) => {
await helpers.runMessageAction("react", opts);
});
helpers.withMessageBase(helpers.withRequiredMessageTarget(message.command("reactions").description("List reactions on a message"))).requiredOption("--message-id <id>", "Message id").option("--limit <n>", "Result limit").action(async (opts) => {
await helpers.runMessageAction("reactions", opts);
});
}
//#endregion
//#region src/cli/program/message/register.read-edit-delete.ts
function registerMessageReadEditDeleteCommands(message, helpers) {
helpers.withMessageBase(helpers.withRequiredMessageTarget(message.command("read").description("Read recent messages"))).option("--limit <n>", "Result limit").option("--before <id>", "Read/search before id").option("--after <id>", "Read/search after id").option("--around <id>", "Read around id").option("--include-thread", "Include thread replies (Discord)", false).action(async (opts) => {
await helpers.runMessageAction("read", opts);
});
helpers.withMessageBase(helpers.withRequiredMessageTarget(message.command("edit").description("Edit a message").requiredOption("--message-id <id>", "Message id").requiredOption("-m, --message <text>", "Message body"))).option("--thread-id <id>", "Thread id (Telegram forum thread)").action(async (opts) => {
await helpers.runMessageAction("edit", opts);
});
helpers.withMessageBase(helpers.withRequiredMessageTarget(message.command("delete").description("Delete a message").requiredOption("--message-id <id>", "Message id"))).action(async (opts) => {
await helpers.runMessageAction("delete", opts);
});
}
//#endregion
//#region src/cli/program/message/register.send.ts
function registerMessageSendCommand(message, helpers) {
helpers.withMessageBase(helpers.withRequiredMessageTarget(message.command("send").description("Send a message").option("-m, --message <text>", "Message body (required unless --media is set)")).option("--media <path-or-url>", "Attach media (image/audio/video/document). Accepts local paths or URLs.").option("--interactive <json>", "Shared interactive payload as JSON (buttons/selects rendered natively by supported channels)").option("--buttons <json>", "Telegram inline keyboard buttons as JSON (array of button rows)").option("--components <json>", "Discord components payload as JSON").option("--card <json>", "Adaptive Card JSON object (when supported by the channel)").option("--reply-to <id>", "Reply-to message id").option("--thread-id <id>", "Thread id (Telegram forum thread)").option("--gif-playback", "Treat video media as GIF playback (WhatsApp only).", false).option("--force-document", "Send media as document to avoid Telegram compression (Telegram only). Applies to images and GIFs.", false).option("--silent", "Send message silently without notification (Telegram + Discord)", false)).action(async (opts) => {
await helpers.runMessageAction("send", opts);
});
}
//#endregion
//#region src/cli/program/message/register.thread.ts
function registerMessageThreadCommands(message, helpers) {
const thread = message.command("thread").description("Thread actions");
helpers.withMessageBase(helpers.withRequiredMessageTarget(thread.command("create").description("Create a thread").requiredOption("--thread-name <name>", "Thread name"))).option("--message-id <id>", "Message id (optional)").option("-m, --message <text>", "Initial thread message text").option("--auto-archive-min <n>", "Thread auto-archive minutes").action(async (opts) => {
await helpers.runMessageAction("thread-create", opts);
});
helpers.withMessageBase(thread.command("list").description("List threads").requiredOption("--guild-id <id>", "Guild id")).option("--channel-id <id>", "Channel id").option("--include-archived", "Include archived threads", false).option("--before <id>", "Read/search before id").option("--limit <n>", "Result limit").action(async (opts) => {
await helpers.runMessageAction("thread-list", opts);
});
helpers.withMessageBase(helpers.withRequiredMessageTarget(thread.command("reply").description("Reply in a thread").requiredOption("-m, --message <text>", "Message body"))).option("--media <path-or-url>", "Attach media (image/audio/video/document). Accepts local paths or URLs.").option("--reply-to <id>", "Reply-to message id").action(async (opts) => {
await helpers.runMessageAction("thread-reply", opts);
});
}
//#endregion
//#region src/cli/program/register.message.ts
function registerMessageCommands(program, ctx) {
const message = program.command("message").description("Send, read, and manage messages and channel actions").addHelpText("after", () => `
${theme.heading("Examples:")}
${formatHelpExamples([
["openclaw message send --target +15555550123 --message \"Hi\"", "Send a text message."],
["openclaw message send --target +15555550123 --message \"Hi\" --media photo.jpg", "Send a message with media."],
["openclaw message poll --channel discord --target channel:123 --poll-question \"Snack?\" --poll-option Pizza --poll-option Sushi", "Create a Discord poll."],
["openclaw message react --channel discord --target 123 --message-id 456 --emoji \"✅\"", "React to a message."]
])}
${theme.muted("Docs:")} ${formatDocsLink("/cli/message", "docs.openclaw.ai/cli/message")}`).action(() => {
message.help({ error: true });
});
const helpers = createMessageCliHelpers(message, ctx.messageChannelOptions);
registerMessageSendCommand(message, helpers);
registerMessageBroadcastCommand(message, helpers);
registerMessagePollCommand(message, helpers);
registerMessageReactionsCommands(message, helpers);
registerMessageReadEditDeleteCommands(message, helpers);
registerMessagePinCommands(message, helpers);
registerMessagePermissionsCommand(message, helpers);
registerMessageSearchCommand(message, helpers);
registerMessageThreadCommands(message, helpers);
registerMessageEmojiCommands(message, helpers);
registerMessageStickerCommands(message, helpers);
registerMessageDiscordAdminCommands(message, helpers);
}
//#endregion
export { registerMessageCommands };