openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
5 lines • 19.3 kB
JavaScript
import{l as normalizeOptionalString}from"./string-coerce-CpTFcSwY.mjs";import{a as getCommandArgsWithRootOptions}from"./cli-root-options-eez2TgAl.mjs";import{t as resolveCliArgvInvocation}from"./argv-invocation-aH4sq40s.mjs";import"./src-0ci69Prg.mjs";import{t as expectDefined}from"./expect-DkJCbmLj.mjs";import{t as normalizeWindowsArgv}from"./windows-argv-BJOcchA4.mjs";import{r as defaultRuntime}from"./runtime-DIcLIHcp.mjs";import{t as isBlockedObjectKey}from"./prototype-keys-Dc7Yq32J.mjs";import{n as sanitizeForLog}from"./ansi-54CEWBZf.mjs";import{t as formatErrorMessage}from"./errors-D37BJTfI.mjs";import{t as formatCliCommand}from"./command-format-D7KhNLP0.mjs";import{r as setVerbose}from"./global-state-BYcIiONI.mjs";import{i as GATEWAY_CLIENT_NAMES,r as GATEWAY_CLIENT_MODES}from"./client-info-Dr3-kuD1.mjs";import{t as captureRuntimeConfigAsyncReader}from"./io.runtime-BvSeVFIY.mjs";import{t as normalizeAnyChannelId}from"./registry-normalize-BP0gv89S.mjs";import{r as listChannelPlugins}from"./registry-CpNh6QcT.mjs";import"./message-channel-514k57tV.mjs";import{r as resolveChannelAccount}from"./account-resolution-BMEKSThh.mjs";import"./plugins-DxOycUNJ.mjs";import"./config-DkZ8y8Gv.mjs";import{r as theme}from"./theme-DS2CtI9X.mjs";import{t as danger}from"./globals-l9I53ZKA.mjs";import{t as applyPluginAutoEnable}from"./plugin-auto-enable-DD4D-LwA.mjs";import{n as inheritOptionFromParent,t as hasExplicitOptions}from"./command-options-Cl1CohDr.mjs";import{r as callGateway}from"./call-CVqWsTxX.mjs";import{t as commitConfigWithPendingPluginInstalls}from"./install-record-commit-reY_I7xC.mjs";import{i as resolveChannelDefaultAccountId}from"./helpers-1A2j6LGz.mjs";import{o as formatUnsupportedChannelActionMessage}from"./error-format-D9Q6t3gZ.mjs";import{n as runCommandWithRuntime}from"./cli-utils-Dm67QQ71.mjs";import{n as formatHelpExamples,t as formatDocsHelp}from"./help-format-DLfgiheF.mjs";import{t as applyParentDefaultHelpAction}from"./parent-default-help-BQhbR5_q.mjs";import{t as parseAccountSelector}from"./account-selector-j6B-yj9o.mjs";import{t as resolveInstallableChannelPlugin}from"./channel-plugin-resolution-Cc16Hm1A.mjs";import{t as parseChannelSelector}from"./channel-selector-CMlB-vmp.mjs";import{r as requireValidConfigForWrite}from"./config-validation-BexrhW6U.mjs";import{t as formatCliChannelOptions}from"./channel-options-BjPy1UtU.mjs";import{Option}from"commander";
//!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.`:``}`)}
//!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-D_EL93eM.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-C76kNGD9.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-BaL6BE9H.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-CbAxmJt6.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-SNmAVvtk.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-BFrqYoxI.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-B1zj91yy.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-B1zj91yy.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-D_EL93eM.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-AxFEkGSF.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-BTc2VS1p.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)}export{registerChannelsCli};