UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

505 lines (504 loc) • 21.9 kB
import { l as normalizeOptionalString } from "./string-coerce-CCIiB4H7.mjs"; import { a as getCommandArgsWithRootOptions } from "./cli-root-options-xlQx6o4R.mjs"; import { t as resolveCliArgvInvocation } from "./argv-invocation-C9SmXUsh.mjs"; import { t as normalizeWindowsArgv } from "./windows-argv-Co4garuq.mjs"; import "./src-H3RMXyFL.mjs"; import { t as expectDefined } from "./expect-DDakjvvQ.mjs"; import { r as defaultRuntime } from "./runtime-B-SLYP-m.mjs"; import { t as isBlockedObjectKey } from "./prototype-keys-CLGi5xDj.mjs"; import { n as sanitizeForLog } from "./ansi-CZa2t0Hf.mjs"; import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs"; import { t as formatCliCommand } from "./command-format-CqdwUgPk.mjs"; import { r as setVerbose } from "./global-state-DXCtmsFO.mjs"; import { i as GATEWAY_CLIENT_NAMES, r as GATEWAY_CLIENT_MODES } from "./client-info-Cm1BcrMm.mjs"; import { t as captureRuntimeConfigAsyncReader } from "./io.runtime-DsJ2dLCQ.mjs"; import { t as normalizeAnyChannelId } from "./registry-normalize-guW5_4yo.mjs"; import { r as listChannelPlugins } from "./registry-ByqVE5S3.mjs"; import "./message-channel-DTYVLJT1.mjs"; import "./plugins-BoMiRtiY.mjs"; import "./config-CMA-J084.mjs"; import { r as theme } from "./theme-BOI0xyRZ.mjs"; import { t as danger } from "./globals-CgepmiqE.mjs"; import { r as resolveChannelAccount } from "./account-resolution-D7u1J1M0.mjs"; import { t as applyPluginAutoEnable } from "./plugin-auto-enable-CPcwS2II.mjs"; import { n as inheritOptionFromParent, t as hasExplicitOptions } from "./command-options-D76J8Wl7.mjs"; import { r as callGateway } from "./call-DVCK1deJ.mjs"; import { t as commitConfigWithPendingPluginInstalls } from "./install-record-commit-BBhtfevs.mjs"; import { i as resolveChannelDefaultAccountId } from "./helpers-ELZNDAnv.mjs"; import { o as formatUnsupportedChannelActionMessage } from "./error-format-O7EzXfiI.mjs"; import { n as runCommandWithRuntime } from "./cli-utils-BPmaaZlG.mjs"; import { n as formatHelpExamples, t as formatDocsHelp } from "./help-format-D2ytHW5E.mjs"; import { t as parseAccountSelector } from "./account-selector-DYSCYrB8.mjs"; import { t as resolveInstallableChannelPlugin } from "./channel-plugin-resolution-Umf-XLaZ.mjs"; import { t as parseChannelSelector } from "./channel-selector-C0_uoV_u.mjs"; import { r as requireValidConfigForWrite } from "./config-validation-Cy6dkTWs.mjs"; import { t as formatCliChannelOptions } from "./channel-options-N5USZ2xw.mjs"; import { t as applyParentDefaultHelpAction } from "./parent-default-help-BZo1QRJR.mjs"; import { Option } from "commander"; //#region src/cli/channel-auth.ts function unsupportedChannelAuth(e, t) { return new Error(formatUnsupportedChannelActionMessage({ channel: e, action: t, inspectCommand: "openclaw channels status --channel " + e })); } function supportsChannelAuthMode(e, t) { return t === "login" ? Boolean(e.auth?.login) : Boolean(e.gateway?.logoutAccount); } async function isConfiguredAuthPlugin(e, t) { const n = e.id; if (isBlockedObjectKey(n)) return false; const r = t.channels?.[n]; if (r && typeof r === "object" && "enabled" in r && r.enabled === false) return false; for (const n of e.config.listAccountIds(t)) try { const r = await resolveChannelAccount({ plugin: e, cfg: t, accountId: n }); if (e.config.isEnabled ? e.config.isEnabled(r, t) : r && typeof r === "object" ? r.enabled ?? true : true) return true; } catch { continue; } return false; } async function resolveConfiguredAuthChannelInput(e) { const t = applyPluginAutoEnable({ config: await captureRuntimeConfigAsyncReader()(), env: process.env }).config; const n = []; for (const r of listChannelPlugins()) if (supportsChannelAuthMode(r, e) && await isConfiguredAuthPlugin(r, t)) n.push(r.id); if (n.length === 1) return expectDefined(n[0], "configured entry at 0"); if (n.length === 0) throw new Error(`No configured channel supports ${e}. Run ${formatCliCommand("openclaw channels status")} to inspect channels or ${formatCliCommand("openclaw channels add --channel <channel>")} to add one.`); const r = n.map(sanitizeForLog); throw new Error(`Multiple configured channels support ${e}: ${r.join(", ")}. Choose one with --channel <channel>.`); } async function resolveChannelPluginForMode(e, t, n) { parseAccountSelector(e.account); parseChannelSelector(e.channel); const r = await requireValidConfigForWrite(n); if (!r) return null; const i = r.snapshot.sourceConfig; const a = e.channel?.trim() || await resolveConfiguredAuthChannelInput(t); const o = normalizeAnyChannelId(a); const s = await resolveInstallableChannelPlugin({ cfg: i, runtime: n, agentId: e.agent, rawChannel: a, ...o ? { channelId: o } : {}, allowInstall: true, supports: (e) => supportsChannelAuthMode(e, t) }); const c = s.channelId ?? o; if (!c) throw new Error(`Unsupported channel "${a}". Run ${formatCliCommand("openclaw channels list")} to see available channels.`); const l = s.plugin; if (!l || !supportsChannelAuthMode(l, t)) throw unsupportedChannelAuth(c, t); if (s.configChanged) await commitConfigWithPendingPluginInstalls({ sourceConfig: s.cfg, baseHash: r.snapshot.hash, writeOptions: r.writeOptions }); return { cfg: await captureRuntimeConfigAsyncReader()(), channelInput: a, channelId: c, plugin: l }; } function isChannelMissingFromGatewayRegistry(e) { const t = e; return t instanceof Error && t.name === "GatewayClientRequestError" && t.gatewayCode === "INVALID_REQUEST" && t.message === "invalid channels.start channel"; } async function runChannelLogin(e, t = defaultRuntime) { const n = await resolveChannelPluginForMode(e, "login", t); if (!n) return; const { cfg: r, channelInput: i, plugin: a } = n; const o = a.auth?.login; if (!o) throw unsupportedChannelAuth(i, "login"); setVerbose(Boolean(e.verbose)); const s = normalizeOptionalString(e.account) || resolveChannelDefaultAccountId({ plugin: a, cfg: r }); await o({ cfg: r, accountId: s, runtime: t, verbose: Boolean(e.verbose), channelInput: i }); const c = a.id; if (!a.gateway?.startAccount) return; if (r.gateway?.mode === "remote") { t.log(`Gateway is in remote mode; local login saved auth for ${c}/${s} but did not start the remote runtime.`); return; } try { const e = await callGateway({ config: r, method: "channels.start", params: { channel: c, accountId: s }, mode: GATEWAY_CLIENT_MODES.BACKEND, clientName: GATEWAY_CLIENT_NAMES.GATEWAY_CLIENT, deviceIdentity: null }); if (e.outcome && e.outcome.status !== "handed-off") t.log(`Local login saved auth for ${c}/${s}. Gateway start: ${e.outcome.reason}. Check ${formatCliCommand(`openclaw channels status --channel ${c} --probe`)}.`); } catch (e) { if (isChannelMissingFromGatewayRegistry(e)) try { await callGateway({ config: r, method: "gateway.restart.request", params: { reason: `channel login: load ${c}` }, mode: GATEWAY_CLIENT_MODES.BACKEND, clientName: GATEWAY_CLIENT_NAMES.GATEWAY_CLIENT, deviceIdentity: null }); t.log(`Gateway restart requested to load ${c}; the channel will start after restart.`); return; } catch {} t.log(`Local login saved auth for ${c}/${s}, but the running gateway did not restart it: ${formatErrorMessage(e)}`); } } async function runChannelLogout(e, t = defaultRuntime) { const n = await resolveChannelPluginForMode(e, "logout", t); if (!n) return; const { cfg: r, channelInput: i, plugin: a } = n; const o = a.gateway?.logoutAccount; if (!o) throw unsupportedChannelAuth(i, "logout"); const s = normalizeOptionalString(e.account) || resolveChannelDefaultAccountId({ plugin: a, cfg: r }); let c; const l = a.id; try { c = await callGateway({ config: r, method: "channels.logout", params: { channel: l, accountId: s }, mode: GATEWAY_CLIENT_MODES.BACKEND, clientName: GATEWAY_CLIENT_NAMES.GATEWAY_CLIENT, deviceIdentity: null }); } catch (e) { if (r.gateway?.mode === "remote") throw e; t.log(`Local logout will clear auth for ${l}/${s}, but the running gateway did not stop it: ${formatErrorMessage(e)}`); c = null; } if (!c) c = await o({ cfg: r, accountId: s, account: await resolveChannelAccount({ plugin: a, cfg: r, accountId: s }), runtime: t }); const u = sanitizeForLog(`${a.id}/${s}`); t.log(`${c.cleared ? "Cleared saved auth" : "No saved auth was cleared"} for ${u}.${c.loggedOut === false ? " Other credentials may still be active." : ""}`); } //#endregion //#region src/cli/channels-cli.ts const CHANNEL_ADD_SHARED_BOOLEAN_OPTIONS = /* @__PURE__ */ new Set(["--help", "-h"]); const CHANNEL_ADD_SHARED_VALUE_OPTIONS = /* @__PURE__ */ new Set([ "--agent", "--channel", "--account", "--name" ]); function getChannelSetupOptionSwitches(e) { return [e.short, e.long].filter((e) => Boolean(e)); } async function resolveChannelsAddChannelFromArgv(e) { const t = normalizeWindowsArgv(e); const n = getCommandArgsWithRootOptions(t, { commandPath: ["channels", "add"], valueFlags: ["--agent"], mode: "command-path" }); if (!n) return; let r; for (let e = 0; e < n.length; e += 1) { const t = n[e]; if (!t || t === "--") break; if (t === "--channel") { r = n[e + 1]?.trim() || r; e += 1; continue; } if (CHANNEL_ADD_SHARED_VALUE_OPTIONS.has(t)) { e += 1; continue; } if (t.startsWith("--channel=")) r = t.slice(10).trim() || r; } if (r) return r; let i; for (let e = 0; e < n.length; e += 1) { const t = n[e]; if (!t || t === "--") break; if (CHANNEL_ADD_SHARED_VALUE_OPTIONS.has(t)) { e += 1; continue; } if (t.includes("=") && CHANNEL_ADD_SHARED_VALUE_OPTIONS.has(t.slice(0, t.indexOf("=")))) continue; if (CHANNEL_ADD_SHARED_BOOLEAN_OPTIONS.has(t)) continue; if (t.startsWith("-")) { if (!i) { const { resolveChannelSetupCliOptionMetadata: e } = await import("./cli-add-options-gxKyfpVW.mjs"); const { optionCandidates: t } = e(void 0, { includeAll: true }); const n = /* @__PURE__ */ new Map(); const addSwitch = (e, t) => { const r = n.get(e); n.set(e, r === void 0 || r === t ? t : "conflict"); }; for (const e of t) { const t = /<[^>]+>|\[[^\]]+\]/u.test(e.flags) ? "value" : "boolean"; for (const n of getChannelSetupOptionSwitches(new Option(e.flags))) addSwitch(n, t); if (e.negatedFlags) for (const t of getChannelSetupOptionSwitches(new Option(e.negatedFlags))) addSwitch(t, "boolean"); } i = n; } const n = t.indexOf("="); const r = n === -1 ? t : t.slice(0, n); const a = i.get(r); if (!a || a === "conflict") return; if (n === -1 && a === "value") e += 1; continue; } return t; } } const optionNamesRemove = [ "channel", "account", "delete" ]; const CHANNEL_ADD_SELECTION_OPTION_NAMES = /* @__PURE__ */ new Set(["agent", "channel"]); const LEGACY_CHANNEL_SETUP_OPTIONS = [ { flags: "--token <token>", description: "Channel token or credential payload" }, { flags: "--token-file <path>", description: "Read channel token or credential payload from file" }, { flags: "--secret <secret>", description: "Channel shared secret" }, { flags: "--bot-token <token>", description: "Bot token" }, { flags: "--app-token <token>", description: "App token" }, { flags: "--password <password>", description: "Channel password or login secret" }, { flags: "--cli-path <path>", description: "Channel CLI path" }, { flags: "--url <url>", description: "Channel setup URL" }, { flags: "--base-url <url>", description: "Channel base URL" }, { flags: "--http-url <url>", description: "Channel HTTP service URL" }, { flags: "--auth-dir <path>", description: "Channel auth directory override" }, { flags: "--use-env", description: "Use env-backed credentials when supported", defaultValue: false } ]; function runChannelsCommandWithDanger(e, t) { return runCommandWithRuntime(defaultRuntime, e, (e) => { defaultRuntime.error(danger(`${t}: ${formatErrorMessage(e)}`)); defaultRuntime.exit(1); }); } function resolveStringOption(e, t) { const n = inheritOptionFromParent(e, t) ?? e.getOptionValue(t); return typeof n === "string" ? n : void 0; } function addChannelSetupOption(e, t, n) { const r = e.createOption(t.flags, t.description); const i = getChannelSetupOptionSwitches(r); if (i.some((e) => n.has(e))) return; i.forEach((e) => n.add(e)); e.addOption(r.makeOptionMandatory(false).default(t.defaultValue)); if (t.negatedFlags) { const r = e.createOption(t.negatedFlags, t.description); const i = getChannelSetupOptionSwitches(r); if (!i.some((e) => n.has(e))) { i.forEach((e) => n.add(e)); e.addOption(r.makeOptionMandatory(false).default(void 0)); } } } async function registerChannelsCli(e, t = process.argv, n = {}) { const r = formatCliChannelOptions(); const i = e.command("channels").description("Manage connected chat channels and accounts").option("--agent <id>", "Agent owner for channel commands that require workspace context").addHelpText("after", () => `\n${theme.heading("Examples:")}\n${formatHelpExamples([ ["openclaw channels list", "List configured channels."], ["openclaw channels list --all", "Show configured, bundled, and installable channels."], ["openclaw channels add", "Open guided channel setup."], ["openclaw channels status --probe", "Check channel status and connectivity."], ["openclaw channels add --channel telegram --token <token>", "Add or update a channel account non-interactively."], ["openclaw channels login --channel whatsapp", "Link a WhatsApp Web account."] ])}\n${formatDocsHelp("/cli/channels")}`); i.command("list").description("List chat channels (configured by default; pass --all for installable catalog)").option("--all", "Include bundled and installable catalog channels", false).option("--json", "Output JSON", false).action(async (e) => { await runCommandWithRuntime(defaultRuntime, async () => { const { channelsListCommand: t } = await import("./list-52Kf6ens.mjs"); await t(e, defaultRuntime); }); }); i.command("status").description("Show channel status (use openclaw status --deep for a full connection check)").option("--channel <name>", `Only show one channel (${formatCliChannelOptions(["all"])})`).option("--probe", "Check channel credentials", false).option("--timeout <ms>", "Timeout in ms").option("--json", "Output JSON", false).action(async (e) => { await runCommandWithRuntime(defaultRuntime, async () => { const { channelsStatusCommand: t } = await import("./status-DoKU6Rw3.mjs"); await t(e, defaultRuntime); }); }); i.command("capabilities").description("Show provider capabilities (intents/scopes + supported features)").option("--agent <id>", "Agent owner for channel discovery").option("--channel <name>", `Channel (${formatCliChannelOptions(["all"])})`).option("--account <id>", "Account id (only with --channel)", parseAccountSelector).option("--target <dest>", "Channel target for permission audit (Discord channel:<id>)").option("--timeout <ms>", "Timeout in ms", "10000").option("--json", "Output JSON", false).action(async (e, t) => { await runCommandWithRuntime(defaultRuntime, async () => { const { channelsCapabilitiesCommand: n } = await import("./capabilities-CmEppmdo.mjs"); await n({ ...e, agent: resolveStringOption(t, "agent") }, defaultRuntime); }); }); i.command("resolve").description("Resolve channel/user names to IDs").argument("<entries...>", "Entries to resolve (names or ids)").option("--channel <name>", `Channel (${r})`).option("--account <id>", "Account id (accountId)", parseAccountSelector).option("--agent <id>", "Agent owner for channel resolution").addOption(new Option("--kind <kind>", "Target kind (auto|user|group|channel)").choices([ "auto", "user", "group", "channel" ]).default("auto")).option("--json", "Output JSON", false).action(async (e, t, n) => { await runCommandWithRuntime(defaultRuntime, async () => { const { channelsResolveCommand: r } = await import("./resolve-DrCFtMzx.mjs"); await r({ agent: resolveStringOption(n, "agent"), channel: t.channel, account: t.account, kind: t.kind, json: Boolean(t.json), entries: Array.isArray(e) ? e : [String(e)] }, defaultRuntime); }); }); i.command("logs").description("Show recent channel logs from the gateway log file").option("--channel <name>", `Channel (${formatCliChannelOptions(["all"])}; default: all)`).option("--lines <n>", "Number of lines (default: 200)", "200").option("--json", "Output JSON", false).action(async (e) => { await runCommandWithRuntime(defaultRuntime, async () => { const { channelsLogsCommand: t } = await import("./logs-DxJyB-z0.mjs"); await t(e); }); }); const a = i.command("dead-letters").description("Inspect and resubmit failed inbound channel events").option("--account <id>", "Account id", "default"); a.command("list").description("List failed inbound events for one channel account").requiredOption("--channel <name>", "Channel id").option("--account <id>", "Account id", "default").option("--limit <n>", "Maximum entries", "100").option("--json", "Output JSON", false).action(async (e, t) => { await runCommandWithRuntime(defaultRuntime, async () => { const { channelsDeadLettersListCommand: n } = await import("./dead-letters-DDL8_bSy.mjs"); await n({ ...e, account: resolveStringOption(t, "account") }); }); }); a.command("resubmit").description("Re-enqueue one failed inbound event").argument("<event-id>", "Ingress event id").requiredOption("--channel <name>", "Channel id").option("--account <id>", "Account id", "default").option("--json", "Output JSON", false).action(async (e, t, n) => { await runCommandWithRuntime(defaultRuntime, async () => { const { channelsDeadLettersResubmitCommand: r } = await import("./dead-letters-DDL8_bSy.mjs"); await r(e, { ...t, account: resolveStringOption(n, "account") }); }); }); applyParentDefaultHelpAction(a); const o = i.command("add").description("Add or update a channel account").argument("[channel]", "Channel id").addHelpText("after", () => `\n${theme.heading("Examples:")}\n${formatHelpExamples([ ["openclaw channels add", "Open guided setup for available chat channels."], ["openclaw channels add --channel telegram --token <token>", "Add or update Telegram non-interactively."], ["openclaw channels list --all", "Find channel ids before using --channel."] ])}\n`).option("--channel <name>", `Channel (${r})`).option("--agent <id>", "Agent owner for channel setup").option("--account <id>", "Account id (default when omitted)").option("--name <name>", "Display name for this account"); let s = true; const c = /* @__PURE__ */ new Set(); const l = await resolveChannelsAddChannelFromArgv(t); let u = n.includeSetupOptions; if (!u) { const { commandPath: e } = resolveCliArgvInvocation(normalizeWindowsArgv(t)); u = e[0] === "channels" && e[1] === "add"; } if (u && (l !== void 0 || n.includeSetupOptions)) { const { resolveChannelSetupCliOptionMetadata: e } = await import("./cli-add-options-gxKyfpVW.mjs"); const t = l?.trim().toLowerCase(); const { options: r, selectedChannel: i, valueMetadataByAttributeName: a } = e(t, { includeAll: n.includeSetupOptions }); const u = new Set(o.options.flatMap(getChannelSetupOptionSwitches)); for (const e of r) addChannelSetupOption(o, e, u); if (n.includeSetupOptions || t && i?.setup === void 0) for (const e of LEGACY_CHANNEL_SETUP_OPTIONS) addChannelSetupOption(o, e, u); for (const [e, t] of a) if (t.valueType === "int") c.add(e); s = !t || !i?.setup; } o.action(async (e, t, n) => { await runCommandWithRuntime(defaultRuntime, async () => { const { channelsAddCommand: r } = await import("./add-B3b_pt3M.mjs"); const i = hasExplicitOptions(n, n.options.map((e) => e.attributeName()).filter((e) => !CHANNEL_ADD_SELECTION_OPTION_NAMES.has(e))); await r({ ...Object.fromEntries(Object.entries(t).filter(([e, t]) => { const r = n.getOptionValueSource(e); if (r === "cli") return true; if (!s || r !== "default" || t === void 0) return false; if (t === "") return !c.has(e); return true; })), channel: t.channel ?? e, agent: resolveStringOption(n, "agent") }, defaultRuntime, { hasFlags: i }); }); }); i.command("remove").description("Disable or delete a channel account").option("--agent <id>", "Agent owner for channel discovery").option("--channel <name>", `Channel (${r})`).option("--account <id>", "Account id (default when omitted)").option("--delete", "Delete config entries (no prompt)", false).action(async (e, t) => { await runCommandWithRuntime(defaultRuntime, async () => { const { channelsRemoveCommand: n } = await import("./remove-UhL3c0kf.mjs"); const r = hasExplicitOptions(t, optionNamesRemove); await n({ ...e, agent: resolveStringOption(t, "agent") }, defaultRuntime, { hasFlags: r }); }); }); for (const e of ["login", "logout"]) { const t = i.command(e).description(e === "login" ? "Link a channel account (if supported)" : "Log out of a channel session (if supported)").option("--agent <id>", "Agent owner for channel discovery").option("--channel <channel>", "Channel alias (auto when only one is configured)").option("--account <id>", "Account id (accountId)"); if (e === "login") t.option("--verbose", "Verbose connection logs", false); t.action(async (t, n) => { await runChannelsCommandWithDanger(() => (e === "login" ? runChannelLogin : runChannelLogout)({ agent: resolveStringOption(n, "agent"), channel: t.channel, account: t.account, ...e === "login" ? { verbose: Boolean(t.verbose) } : {} }, defaultRuntime), `Channel ${e} failed`); }); } applyParentDefaultHelpAction(i); } //#endregion export { registerChannelsCli };