openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
18 lines • 26.1 kB
JavaScript
import{l as normalizeOptionalString}from"./string-coerce-CpTFcSwY.mjs";import{D as parseStrictPositiveInteger}from"./number-coercion-B3CfI447.mjs";import{S as MACHINE_OUTPUT_JSON_OPTION_DESCRIPTION}from"./argv-BgC5-KlV.mjs";import"./src-0ci69Prg.mjs";import{n as formatByteSize}from"./format-66SdinIu.mjs";import{r as defaultRuntime,t as ExitError}from"./runtime-DIcLIHcp.mjs";import{o as getAsyncWorkSignal}from"./async-work-scope-DBcxYU4O.mjs";import{t as formatErrorMessage}from"./errors-D37BJTfI.mjs";import{n as createLazyPromise}from"./lazy-promise-CismJCQR.mjs";import{t as formatCliCommand}from"./command-format-D7KhNLP0.mjs";import{n as monotonicNow}from"./monotonic-time-DjtFTu2s.mjs";import{n as isRich,r as theme,t as colorize}from"./theme-DS2CtI9X.mjs";import{d as rethrowExpectedCliError,r as formatCliJsonFailure}from"./failure-output-Gn9zHEk3.mjs";import{t as formatDocsLink}from"./links-C_FK9uVv.mjs";import{n as inheritOptionFromParent}from"./command-options-Cl1CohDr.mjs";import{o as resolveGatewayRpcOptions,r as callGatewayFromCliWithTransport,s as resolveGatewayRpcOptionsWithLocalPort,t as addGatewayClientOptions}from"./gateway-rpc-17pTfL8i.mjs";import{t as addGatewayServiceCommands}from"./register-service-commands-DXqs3aGW.mjs";import{t as isReadOnlyGatewayCliCall}from"./cli-read-policy-DWy72acJ.mjs";import{t as isGatewayMachineOutput}from"./output-mode-Cd7xwBbG.mjs";import{n as parseTimeoutMsWithFallback}from"./parse-timeout-euv6DhlU.mjs";import{n as formatHelpExamples}from"./help-format-DLfgiheF.mjs";import{t as parseOptionalPositiveInteger}from"./parse-positive-integer-D-doE7rP.mjs";import{n as setCommandJsonMode}from"./json-mode-COATK2x3.mjs";import{t as addGatewayRunCommand}from"./run-command-CgJThsm9.mjs";import{randomBytes}from"node:crypto";import{setTimeout}from"node:timers/promises";
//!src/cli/gateway-cli/gateway-action.ts
function gatewayAction(e,t){return async function(...n){const r=Boolean(this.opts().json);try{await e.apply(this,n)}catch(e){if(e instanceof ExitError)throw e;if(!r)rethrowExpectedCliError(e);if(r){const{formatGatewayAuthErrorJson:t,formatGatewayClientRequestErrorJson:n,formatGatewayTransportErrorJson:r}=await import(`./call-CggG9h6i.mjs`);defaultRuntime.writeJson(t(e)??n(e)??r(e)??formatCliJsonFailure(e));defaultRuntime.exit(1);return}const n=formatErrorMessage(e);defaultRuntime.error(t?`${t}: ${n}`:n);defaultRuntime.exit(1)}}}
//!src/cli/gateway-cli/register-recover-lock.ts
function addGatewayLockRecoveryCommand(e){e.command(`recover-lock`,{hidden:true}).description(`Inspect or explicitly recover an unchanged Gateway state lock`).option(`--confirm <fingerprint>`,`Recover only the lock record shown by a prior inspection`).option(`--json`,`Output JSON`,false).action(gatewayAction(async e=>{const{inspectGatewayLockRecovery:t,recoverGatewayLock:n}=await import(`./gateway-lock-recovery-BM3c5icl.mjs`);if(e.confirm){const t=await n({confirmation:e.confirm});if(e.json)defaultRuntime.writeJson(t);else defaultRuntime.log(`Gateway lock recovery completed. Start the Gateway again.`);return}const r=await t();if(e.json){defaultRuntime.writeJson({present:r.present,holders:r.holders,confirmation:r.confirmation});return}if(!r.present){defaultRuntime.log(`No Gateway lock or owner lease is present.`);return}for(const e of r.holders)defaultRuntime.log(e);defaultRuntime.log(`Independently verify that the recorded holder has stopped.`);defaultRuntime.log(`Confirmation fingerprint: ${r.confirmation}`)},`Gateway lock recovery failed`))}
//!src/infra/restart-handoff-contract.ts
const GATEWAY_RESTART_HANDOFF_PROTOCOL=`openclaw.gateway.restart-handoff`;
//!src/cli/gateway-cli/register-restart-handoff.ts
function writeRestartHandoffError(e){defaultRuntime.writeJson({ok:false,protocol:GATEWAY_RESTART_HANDOFF_PROTOCOL,protocolVersion:1,status:`error`,reason:e})}function collectExpectedPid(e,t){return Array.isArray(t)?[...t,e]:[t,e]}function addGatewayRestartHandoffCommands(e){const t=e.command(`restart-handoff`,{hidden:true});t.command(`capabilities`).description(`Report the gateway restart-handoff machine contract`).option(`--json`,MACHINE_OUTPUT_JSON_OPTION_DESCRIPTION).action(()=>{defaultRuntime.writeJson({ok:true,protocol:GATEWAY_RESTART_HANDOFF_PROTOCOL,protocolVersion:1,operations:[`consume`]})});t.command(`consume`).description(`Atomically consume a gateway restart handoff`).helpOption(false).allowUnknownOption().allowExcessArguments().option(`--expected-pid [pid]`,`PID of the exited gateway process`,collectExpectedPid,[]).option(`--json`,MACHINE_OUTPUT_JSON_OPTION_DESCRIPTION).action(async(e,t)=>{const n=Array.isArray(e.expectedPid)?e.expectedPid:[];const r=t.args.length===0&&n.length===1?parseStrictPositiveInteger(n[0]):void 0;if(r===void 0){writeRestartHandoffError(`invalid-expected-pid`);defaultRuntime.exit(2);return}try{const{consumeGatewayRestartHandoffSync:e}=await import(`./restart-handoff-Do5V1PqY.mjs`);const t=e({expectedPid:r});defaultRuntime.writeJson({ok:true,protocol:GATEWAY_RESTART_HANDOFF_PROTOCOL,protocolVersion:1,...t})}catch(e){defaultRuntime.error(`Gateway restart handoff consume failed: ${String(e)}`);writeRestartHandoffError(`store-unavailable`);defaultRuntime.exit(1)}})}
//!src/cli/gateway-cli/stability-bundle-target.ts
function normalizeStabilityBundleTarget(e){if(e===void 0||e===false)return null;const t=normalizeOptionalString(e);if(typeof e===`string`&&t===void 0)throw new Error(`--bundle must be a non-empty path or "latest".`);return t??`latest`}
//!src/cli/gateway-cli/stability-format.ts
function formatStabilityBytes(e){if(e===void 0)return`n/a`;return formatByteSize(e,{style:`iec`,maxUnit:`giga`,separator:` `,fractionDigits:(e,t)=>t===`byte`||e>=100?0:1})}function formatStabilityEvent(e){return[new Date(e.ts).toISOString(),`#${e.seq}`,e.type,e.provider?`provider=${e.provider}`:``,e.model?`model=${e.model}`:``,e.durationMs!==void 0?`wall=${Math.round(e.durationMs)}ms`:``,e.providerProcessingMs!==void 0?`processing=${Math.round(e.providerProcessingMs)}ms`:``,e.providerWaitEstimateMs!==void 0?`wait~=${Math.round(e.providerWaitEstimateMs)}ms`:``,e.failureKind?`failure=${e.failureKind}`:``,e.level?`level=${e.level}`:``,e.action?`action=${e.action}`:``,e.outcome?`outcome=${e.outcome}`:``,e.surface?`surface=${e.surface}`:``,e.channel?`channel=${e.channel}`:``,e.pluginId?`plugin=${e.pluginId}`:``,e.reason?`reason=${e.reason}`:``,e.bytes!==void 0?`bytes=${formatStabilityBytes(e.bytes)}`:``,e.limitBytes!==void 0?`limit=${formatStabilityBytes(e.limitBytes)}`:``,e.queueDepth!==void 0?`queueDepth=${e.queueDepth}`:``,e.queueLength!==void 0?`queueLength=${e.queueLength}`:``,e.droppedEvents!==void 0?`dropped=${e.droppedEvents}`:``,e.maxQueueLength!==void 0?`maxQueue=${e.maxQueueLength}`:``,e.queued!==void 0?`queued=${e.queued}`:``,e.memory?`rss=${formatStabilityBytes(e.memory.rssBytes)}`:``,e.memory?`heap=${formatStabilityBytes(e.memory.heapUsedBytes)}`:``].filter(Boolean).join(` `)}
//!src/cli/gateway-cli/suspend-cli.ts
const MIN_SUSPEND_POLL_DELAY_MS=50;async function runGatewaySuspend(e,t){const n=e.requestId;const r=n===void 0?`cli-${randomBytes(4).toString(`hex`)}`:n.trim();if(n!==void 0&&(!r||r.length>128))throw new Error(`--request-id must contain 1 to 128 characters`);let i;const a=e.waitSeconds;if(a!==void 0){const e=typeof a===`number`?a:Number(a.trim()||NaN);if(!Number.isFinite(e)||e<0)throw new Error(`--wait must be a non-negative number of seconds`);i=Math.floor(e*1e3);if(!Number.isSafeInteger(i))throw new Error(`--wait is too large`)}const o=i===void 0?void 0:monotonicNow()+i;const s=i===void 0?1:Math.ceil(i/MIN_SUSPEND_POLL_DELAY_MS)+1;let c;const l=getAsyncWorkSignal();for(let n=0;n<s;n+=1){if(l?.aborted)return;if(n>0&&o!==void 0&&monotonicNow()>=o)break;c=await t.callGateway(`gateway.suspend.prepare`,e.rpcOpts,{requestId:r});if(c.status===`ready`){if(e.json){t.runtime.writeJson({...c,requestId:r});return}const n=isRich();t.runtime.log(colorize(n,theme.success,`Gateway suspension prepared.`));t.runtime.log(`${colorize(n,theme.muted,`Suspension ID:`)} ${c.suspensionId}`);t.runtime.log(`${colorize(n,theme.muted,`Expires:`)} ${new Date(c.expiresAtMs).toISOString()} (${c.expiresAtMs} ms)`);const i=e.rpcOpts.localPortOverride;const a=`openclaw gateway resume ${c.suspensionId}`;if(e.rpcOpts.url?.trim())t.runtime.log(`To resume this remote Gateway, run ${formatCliCommand(a)} with the same --url and authentication options used for suspend.`);else t.runtime.log(`Resume with: ${formatCliCommand(i===void 0?a:`${a} --port ${i}`)}`);return}if(l?.aborted)return;if(c.status===`draining`)throw new Error(`Gateway suspension unexpectedly entered drain mode`);if(o===void 0)break;const i=o-monotonicNow();if(i<=0)break;const a=Math.min(i,Math.max(MIN_SUSPEND_POLL_DELAY_MS,c.retryAfterMs));try{await setTimeout(a,void 0,{signal:l})}catch(e){if(!l?.aborted)throw e;return}}if(!c||c.status!==`busy`)throw new Error(`Gateway suspension polling ended without a result`);if(e.json){t.runtime.writeJson({...c,requestId:r});t.runtime.exit(1);return}const u=o===void 0?`Retry later or use --wait <seconds>.`:`Timed out waiting for the Gateway to become idle.`;const d=c.blockers.map(e=>`- ${e.message}`);const f=[`Gateway suspension is busy (${c.reason}; ${c.activeCount} active).`,...d.length>0?[`Blockers:`,...d]:[]].join(`
`);throw new Error(`${f}\n${u}`)}async function runGatewayResume(e,t){const n=await t.callGateway(`gateway.suspend.resume`,e.rpcOpts,{suspensionId:e.suspensionId});if(e.json){t.runtime.writeJson(n);return}t.runtime.log(n.resumed?`Gateway resumed.`:`No matching suspension was held (lease already expired or resumed); gateway is running.`)}
//!src/cli/gateway-cli/register.ts
const loadWideAreaDnsModule=createLazyPromise(()=>import(`./widearea-dns-CpqcVugy.mjs`));const loadCostUsageRenderer=createLazyPromise(()=>import(`./usage-cost-renderer-DTyBOj4s.mjs`));const loadStabilityBundleModule=createLazyPromise(()=>import(`./diagnostic-stability-bundle-BLtOrma2.mjs`));const DEFAULT_GATEWAY_RPC_TIMEOUT_MS=1e4;const SETUP_INFERENCE_DETECT_RPC_TIMEOUT_MS=4e4;function gatewayCallOpts(e){return addGatewayClientOptions(e,{timeoutMs:DEFAULT_GATEWAY_RPC_TIMEOUT_MS}).option(`--json`,`Output JSON`,false)}async function callGatewayReadOnlyCli(e,t,n){return await callGatewayFromCliWithTransport(e,t,n,{defaultTimeoutMs:DEFAULT_GATEWAY_RPC_TIMEOUT_MS,sharedStateMode:`read-only`})}async function callGatewayReadOnlyCliUnlessAborted(e,t,n){const r=getAsyncWorkSignal();let i;try{i=await callGatewayReadOnlyCli(e,t,n)}catch(e){if(!r?.aborted)throw e}return r?.aborted?void 0:{result:i}}function parseGatewayCallParams(e=`{}`){try{return JSON.parse(e)}catch{throw new Error(`--params must be valid JSON.`)}}function parseDaysOption(e){if(typeof e===`number`&&Number.isFinite(e))return Math.max(1,Math.floor(e));if(typeof e===`string`){const t=parseStrictPositiveInteger(e);if(t!==void 0)return t;throw new Error(`Invalid --days. Use a positive integer, e.g. --days 30. Received: "${e}".`)}return 30}async function printGatewayResult(e,t,n){if(e){defaultRuntime.writeJson(t);return}for(const e of await n(isRich()))defaultRuntime.log(e)}function renderStabilitySummary(e,t){const n=[colorize(t,theme.heading,`Gateway Stability`),`${colorize(t,theme.muted,`Events:`)} ${e.count}/${e.capacity}${e.dropped>0?` · dropped=${e.dropped}`:``}`];const r=Object.entries(e.summary.byType).toSorted((e,t)=>t[1]-e[1]||e[0].localeCompare(t[0])).slice(0,8).map(([e,t])=>`${e}=${t}`).join(`, `);if(r)n.push(`${colorize(t,theme.muted,`Types:`)} ${r}`);const i=e.summary.memory;if(i)n.push(`${colorize(t,theme.muted,`Memory:`)} rss=${formatStabilityBytes(i.latest?.rssBytes)} heap=${formatStabilityBytes(i.latest?.heapUsedBytes)} maxRss=${formatStabilityBytes(i.maxRssBytes)} pressure=${i.pressureCount}`);const a=e.summary.payloadLarge;if(a){const e=Object.entries(a.bySurface).toSorted((e,t)=>t[1]-e[1]||e[0].localeCompare(t[0])).map(([e,t])=>`${e}=${t}`).join(`, `);n.push(`${colorize(t,theme.muted,`Large payloads:`)} total=${a.count} rejected=${a.rejected} truncated=${a.truncated} chunked=${a.chunked}${e?` · ${e}`:``}`)}if(e.events.length>0){n.push(colorize(t,theme.muted,`Recent:`));for(const t of e.events)n.push(` ${formatStabilityEvent(t)}`)}return n}async function writeSupportExportFromCli(e){const{writeDiagnosticSupportExport:t}=await import(`./diagnostic-support-export-D31dy3Tj.mjs`);const n={url:e.rpc?.url,token:e.rpc?.token,password:e.rpc?.password,timeout:e.rpc?.timeout??`3000`,json:true};const r=await t({outputPath:e.output,logLimit:parseOptionalPositiveInteger(e.logLines,`--log-lines`,`.`),logMaxBytes:parseOptionalPositiveInteger(e.logBytes,`--log-bytes`,`.`),stabilityBundle:e.stabilityBundle,readStatusSnapshot:async()=>{const{gatherDaemonStatus:e}=await import(`./status.gather-yw4ltMY-.mjs`);return await e({rpc:n,probe:true,requireRpc:false,deep:false})},readHealthSnapshot:async()=>await callGatewayReadOnlyCli(`health`,n),readGatewayCapabilities:async()=>await callGatewayReadOnlyCli(`diagnostics.capabilities`,n)});await printGatewayResult(e.json,r,e=>[colorize(e,theme.heading,`Diagnostics export`),`${colorize(e,theme.muted,`Path:`)} ${r.path}`,`${colorize(e,theme.muted,`Size:`)} ${formatStabilityBytes(r.bytes)}`,`${colorize(e,theme.muted,`Files:`)} ${r.manifest.contents.length}`,`${colorize(e,theme.muted,`Privacy:`)} payload-free stability, sanitized logs/status/health/config`])}function registerGatewayCli(e){const t=addGatewayRunCommand(e.command(`gateway`).description(`Run, inspect, and query the WebSocket Gateway`).addHelpText(`after`,()=>`\n${theme.heading(`Examples:`)}\n${formatHelpExamples([[`openclaw gateway run`,`Run the gateway in the foreground.`],[`openclaw gateway status`,`Show service status plus connectivity/capability.`],[`openclaw gateway auth-token --show`,`Reveal the shared token interactively.`],[`openclaw gateway discover`,`Find local and wide-area gateway beacons.`],[`openclaw gateway stability`,`Show recent stability diagnostics.`],[`openclaw gateway call health`,`Call a gateway RPC method directly.`]])}\n\n${theme.muted(`Docs:`)} ${formatDocsLink(`/cli/gateway`,`docs.openclaw.ai/cli/gateway`)}\n`));addGatewayRunCommand(t.command(`run`).description(`Run the WebSocket Gateway (foreground)`));addGatewayServiceCommands(t,{statusDescription:`Show gateway service status + check connectivity/capability`});addGatewayRestartHandoffCommands(t);addGatewayLockRecoveryCommand(t);setCommandJsonMode(t,`output`,({argv:e})=>isGatewayMachineOutput(e));t.command(`auth-token`).description(`Reveal the configured shared Gateway token`).option(`--show`,`Print the token to an interactive terminal`,false).action(gatewayAction(async e=>{if(!e.show)throw new Error(`Pass --show to confirm that you want to print the Gateway token to this terminal.`);const{gatewayAuthTokenCommand:t}=await import(`./gateway-auth-token-Ckq9rrn0.mjs`);await t(defaultRuntime)},`Gateway auth token failed`));gatewayCallOpts(t.command(`call`).description(`Call a Gateway method`).argument(`<method>`,`Method name (health/status/system-presence/cron.*)`).option(`--expect-url <url>`,`Fail if the resolved Gateway URL differs; preserves configured authentication`).option(`--params <json>`,`JSON object string for params`,`{}`).action(gatewayAction(async(e,t,n)=>{const r=e===`openclaw.setup.detect`&&n.getOptionValueSource(`timeout`)==="default"?{...t,timeout:String(SETUP_INFERENCE_DETECT_RPC_TIMEOUT_MS)}:t;const i=resolveGatewayRpcOptionsWithLocalPort(r,n);const a=parseGatewayCallParams(String(t.params??`{}`));const o=isReadOnlyGatewayCliCall(e,a)?await callGatewayReadOnlyCliUnlessAborted(e,i,a):{result:await callGatewayReadOnlyCli(e,i,a)};if(!o)return;const s=o.result;if(i.json){defaultRuntime.writeJson(s);return}const c=isRich();defaultRuntime.log(`${colorize(c,theme.heading,`Gateway call`)}: ${colorize(c,theme.muted,String(e))}`);defaultRuntime.writeJson(s)},`Gateway call failed`)));gatewayCallOpts(t.command(`suspend`).description(`Prepare the Gateway for cooperative host suspension`).option(`--request-id <id>`,`Stable suspension request id`).option(`--wait <seconds>`,`Wait up to this many seconds for active work to drain`).action(gatewayAction(async(e,t)=>{const n=resolveGatewayRpcOptionsWithLocalPort(e,t);await runGatewaySuspend({rpcOpts:n,requestId:e.requestId,waitSeconds:e.wait,json:Boolean(n.json)},{callGateway:callGatewayReadOnlyCli,runtime:defaultRuntime})},`Gateway suspend failed`)));gatewayCallOpts(t.command(`resume`).description(`Release a cooperative Gateway suspension`).argument(`<suspensionId>`,`Suspension id returned by gateway suspend`).action(gatewayAction(async(e,t,n)=>{const r=resolveGatewayRpcOptionsWithLocalPort(t,n);await runGatewayResume({rpcOpts:r,suspensionId:String(e),json:Boolean(r.json)},{callGateway:callGatewayReadOnlyCli,runtime:defaultRuntime})},`Gateway resume failed`)));gatewayCallOpts(t.command(`usage-cost`).description(`Fetch usage cost summary from session logs`).option(`--days <days>`,`Number of days to include`,`30`).option(`--agent <id>`,`Scope the cost summary to a specific agent id`).option(`--all-agents`,`Aggregate the cost summary across all agents`,false).action(gatewayAction(async(e,t)=>{const n=resolveGatewayRpcOptionsWithLocalPort(e,t);const r=parseDaysOption(e.days);const i=typeof e.agent===`string`?e.agent.trim():void 0;if(i&&e.allAgents)throw new Error(`Use --agent or --all-agents, not both`);const a=await callGatewayReadOnlyCliUnlessAborted(`usage.cost`,n,{days:r,...i?{agentId:i}:{},...e.allAgents?{agentScope:`all`}:{}});if(!a)return;const o=a.result;await printGatewayResult(n.json,o,async e=>(await loadCostUsageRenderer()).renderGatewayCostUsageSummary(o,r,e))},`Gateway usage cost failed`)));gatewayCallOpts(t.command(`health`).description(`Fetch Gateway health`).action(gatewayAction(async(e,t)=>{const n=getAsyncWorkSignal();const r=resolveGatewayRpcOptionsWithLocalPort(e,t);let i;try{i=await callGatewayReadOnlyCli(`health`,r)}catch(e){if(n?.aborted)return;const{emitReachableGatewayAuthDiagnostic:t,readNonObservingHealthConfig:i}=await import(`./health-59vUbvpx.mjs`);if(await t({error:e,config:r.config??await i(),runtime:defaultRuntime,timeoutMs:parseTimeoutMsWithFallback(r.timeout,1e4,{invalidType:`error`}),token:r.token,password:r.password,localPortOverride:r.localPortOverride,json:Boolean(r.json),signal:n}))return;throw e}if(n?.aborted)return;if(r.json){defaultRuntime.writeJson(i);return}const[{formatHealthChannelLines:a},{styleHealthChannelLine:o}]=await Promise.all([import(`./health-59vUbvpx.mjs`),import(`./terminal-core/health-style.js`)]);const s=isRich();const c=i&&typeof i===`object`?i:{};const l=typeof c.durationMs===`number`?c.durationMs:null;defaultRuntime.log(colorize(s,theme.heading,`Gateway Health`));defaultRuntime.log(`${colorize(s,theme.success,`OK`)}${l!=null?` (${l}ms)`:``}`);if(c.channels&&typeof c.channels===`object`)for(const e of a(c))defaultRuntime.log(o(e,s))},void 0)));gatewayCallOpts(t.command(`stability`).description(`Fetch payload-free Gateway stability diagnostics`).option(`--limit <limit>`,`Maximum number of recent events`,`25`).option(`--type <type>`,`Filter by diagnostic event type`).option(`--since-seq <seq>`,`Only include events after this sequence`).option(`--bundle [path]`,`Read a persisted stability bundle instead of calling Gateway; pass "latest" for newest`).option(`--export`,`Write a shareable support diagnostics export`,false).option(`--output <path>`,`Diagnostics export output .zip path`).action(gatewayAction(async(e,t)=>{const{normalizeDiagnosticStabilityQuery:n,selectDiagnosticStabilitySnapshot:r}=await import(`./diagnostic-stability-BbUN1MQY.mjs`);const i=resolveGatewayRpcOptions(e,t);const a=n({limit:e.limit,sinceSeq:e.sinceSeq,type:e.type},{defaultLimit:25});const o=normalizeStabilityBundleTarget(e.bundle);if(e.export){await writeSupportExportFromCli({json:i.json,output:e.output,stabilityBundle:o??`latest`,rpc:i});return}if(o){const{readDiagnosticStabilityBundleFileSync:e,readLatestDiagnosticStabilityBundleSync:t}=await loadStabilityBundleModule();const n=o===`latest`?t():e(o);if(n.status===`missing`)throw new Error(`No stability bundles found in ${n.dir}`);if(n.status===`failed`)throw new Error(n.error instanceof Error?n.error.message:String(n.error));const s=r(n.bundle.snapshot,a);await printGatewayResult(i.json,{path:n.path,mtimeMs:n.mtimeMs,bundle:{...n.bundle,snapshot:s}},e=>{const{bundle:t,path:r}=n;const i=[`pid=${t.process.pid}`,...t.process.openclawVersion?[`openclaw=${t.process.openclawVersion}`]:[],...t.process.buildId?[`build=${t.process.buildId}`]:[],...t.process.commit?[`commit=${t.process.commit}`]:[],`node=${t.process.node}`,`${t.process.platform}/${t.process.arch}`,`uptime=${Math.round(t.process.uptimeMs/1e3)}s`].join(` `);const a=[colorize(e,theme.heading,`Stability bundle`),`${colorize(e,theme.muted,`Path:`)} ${r}`,`${colorize(e,theme.muted,`Generated:`)} ${t.generatedAt}`,`${colorize(e,theme.muted,`Reason:`)} ${t.reason}`,`${colorize(e,theme.muted,`Process:`)} ${i}`,`${colorize(e,theme.muted,`Host:`)} ${t.host.hostname}`];if(t.error){const n=[t.error.name?`name=${t.error.name}`:``,t.error.code?`code=${t.error.code}`:``].filter(Boolean);if(n.length>0)a.push(`${colorize(e,theme.muted,`Error:`)} ${n.join(` `)}`)}const o=t.evidence?.memoryPressure;if(o){a.push(`${colorize(e,theme.muted,`Memory pressure:`)} ${o.level}/${o.reason} rss=${formatStabilityBytes(o.memory.rssBytes)} heap=${formatStabilityBytes(o.memory.heapUsedBytes)} threshold=${formatStabilityBytes(o.thresholdBytes)}`);if(o.heapStatistics)a.push(`${colorize(e,theme.muted,`V8 heap:`)} used=${formatStabilityBytes(o.heapStatistics.usedHeapSizeBytes)} limit=${formatStabilityBytes(o.heapStatistics.heapSizeLimitBytes)} available=${formatStabilityBytes(o.heapStatistics.totalAvailableSizeBytes)}`);if(o.activeResources){const t=Object.entries(o.activeResources.byType).map(([e,t])=>`${e}=${t}`).join(`, `);a.push(`${colorize(e,theme.muted,`Active resources:`)} total=${o.activeResources.total}${t?` · ${t}`:``}`)}if(o.topSessionFiles?.length){const t=o.topSessionFiles.slice(0,5).map(e=>`${e.relativePath}=${formatStabilityBytes(e.sizeBytes)}`).join(`, `);a.push(`${colorize(e,theme.muted,`Largest session files:`)} ${t}`)}}a.push(``,...renderStabilitySummary(s,e));return a});return}const s=await callGatewayReadOnlyCliUnlessAborted(`diagnostics.stability`,resolveGatewayRpcOptionsWithLocalPort(i,t),{limit:a.limit,...a.type?{type:a.type}:{},...a.sinceSeq!==void 0?{sinceSeq:a.sinceSeq}:{}});if(!s)return;await printGatewayResult(i.json,s.result,e=>renderStabilitySummary(s.result,e))},`Gateway stability failed`)));t.command(`diagnostics`).description(`Export local support diagnostics`).command(`export`).description(`Write a shareable, payload-free diagnostics .zip`).option(`--output <path>`,`Output .zip path`).option(`--log-lines <count>`,`Maximum sanitized log lines to include`,`5000`).option(`--log-bytes <bytes>`,`Maximum log bytes to inspect`,`1000000`).option(`--url <url>`,`Gateway WebSocket URL for health snapshot`).option(`--token <token>`,`Gateway token for health snapshot`).option(`--password <password>`,`Gateway password for health snapshot`).option(`--timeout <ms>`,`Status/health snapshot timeout in ms`,`3000`).option(`--no-stability-bundle`,`Skip persisted stability bundle lookup`).option(`--json`,`Output JSON`,false).action(gatewayAction(async(e,t)=>{const n=resolveGatewayRpcOptions(e,t);await writeSupportExportFromCli({json:e.json,output:e.output,logLines:e.logLines,logBytes:e.logBytes,stabilityBundle:e.stabilityBundle===false?false:`latest`,rpc:n})},`Gateway diagnostics export failed`));t.command(`probe`).description(`Show gateway reachability, auth capability, and read-check summary (local + remote)`).option(`--url <url>`,`Explicit Gateway WebSocket URL (still checks localhost)`).option(`--port <port>`,`Local Gateway port`).option(`--ssh <target>`,`SSH target for remote gateway tunnel (user@host or user@host:port)`).option(`--ssh-identity <path>`,`SSH identity file path`).option(`--ssh-auto`,`Try to derive an SSH target from Bonjour discovery`,false).option(`--token <token>`,`Gateway token (applies to all checks)`).option(`--password <password>`,`Gateway password (applies to all checks)`).option(`--timeout <ms>`,`Overall check budget in ms`,`3000`).option(`--json`,`Output JSON`,false).action(gatewayAction(async(e,t)=>{const n=resolveGatewayRpcOptions(e,t);const{gatewayStatusCommand:r}=await import(`./gateway-status-BU17u27O.mjs`);await r({...n,port:e.port??inheritOptionFromParent(t,`port`)},defaultRuntime)},void 0));t.command(`discover`).description(`Discover gateways via Bonjour (local + wide-area if configured)`).option(`--timeout <ms>`,`Per-command timeout in ms`,`2000`).option(`--json`,`Output JSON`,false).action(gatewayAction(async e=>{const[{readSourceConfigBestEffort:t},{discoverGatewayBeacons:n,resolveGatewayDiscoveryEndpoint:r},{resolveWideAreaDiscoveryDomain:i},{dedupeBeacons:a,renderBeaconLines:o},{withProgress:s}]=await Promise.all([import(`./read-best-effort-config.runtime-fOLO_DtU.mjs`),import(`./bonjour-discovery-CIhDiLrJ.mjs`),loadWideAreaDnsModule(),import(`./discover-CGQuLBEP.mjs`),import(`./progress-BdnRYVMv.mjs`)]);const c=i({configDomain:(await t()).discovery?.wideArea?.domain});const l=parseTimeoutMsWithFallback(e.timeout,2e3,{invalidType:`error`});const u=[`local.`,...c?[c]:[]];const d=a(await s({label:`Scanning for gateways…`,indeterminate:true,enabled:e.json!==true,delayMs:0},async()=>await n({timeoutMs:l,wideAreaDomain:c}))).toSorted((e,t)=>(e.displayName||e.instanceName).localeCompare(t.displayName||t.instanceName));if(e.json){const e=d.map(e=>({...e,wsUrl:r(e)?.wsUrl??null}));defaultRuntime.writeJson({timeoutMs:l,domains:u,count:e.length,beacons:e});return}const f=isRich();defaultRuntime.log(colorize(f,theme.heading,`Gateway Discovery`));defaultRuntime.log(colorize(f,theme.muted,`Found ${d.length} gateway(s) · domains: ${u.join(`, `)}`));if(d.length===0)return;for(const e of d)for(const t of o(e,f))defaultRuntime.log(t)},`gateway discover failed`))}export{registerGatewayCli};