openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
531 lines (530 loc) • 20.4 kB
JavaScript
import { D as parseStrictPositiveInteger } from "./number-coercion-D6u-4YD8.mjs";
import { n as isNodeRuntime, t as isBunRuntime } from "./runtime-binary-QwVVJ9cA.mjs";
import { i as consumeRootOptionToken, l as isValueToken, s as getRootOptionAwareCommandPath, t as FLAG_TERMINATOR } from "./cli-root-options-xlQx6o4R.mjs";
import { t as isConfigMachineOutput } from "./config-output-mode-B_Eb6adL.mjs";
//#region src/cli/program/command-tree.ts
function getCommandHierarchy(e) {
const t = [];
for (let n = e; n; n = n.parent ?? null) t.unshift(n);
return t;
}
function getRootCommand(e) {
let t = e;
while (t.parent) t = t.parent;
return t;
}
/** Remove a command by primary name or alias. */
function removeCommandByName(e, t) {
const n = e.commands;
const r = n.findIndex((e) => e.name() === t || e.aliases().includes(t));
if (r < 0) return false;
n.splice(r, 1);
return true;
}
//#endregion
//#region src/cli/program/commander-parse-facts.ts
const activeErrorCommandByRoot = /* @__PURE__ */ new WeakMap();
const lazyCommands = /* @__PURE__ */ new WeakSet();
function markCommanderLazyCommand(e) {
lazyCommands.add(e);
}
function requiresFollowingValue(e, t) {
if (e.includes("=")) return false;
const n = t.find((t) => t.short === e || t.long === e);
if (n) return n.required;
if (!e.startsWith("-") || e.startsWith("--")) return false;
const r = e.slice(1);
for (let e = 0; e < r.length; e += 1) {
const n = t.find((t) => t.short === `-${r[e]}`);
if (!n) return false;
if (n.required || n.optional) return n.required && e === r.length - 1;
}
return false;
}
/** Match an argv token in its actual Commander role rather than its spelling alone. */
function hasCommanderOptionToken(e, t, n, r) {
const i = getCommandHierarchy(e);
const a = t.slice(2);
let o = 0;
for (let e = 0; e < a.length; e += 1) {
const t = a[e];
if (t === void 0 || t === "--") break;
const s = i[o + 1];
if (s && (t === s.name() || s.aliases().includes(t))) {
o += 1;
continue;
}
if (requiresFollowingValue(t, i[o]?.options ?? [])) {
const t = a[e + 1];
if (r === "value" && t && n.has(t)) return true;
e += 1;
continue;
}
if (r === "flag" && n.has(t.split("=")[0] ?? t)) return true;
}
return false;
}
/** Return the registered command path for the exact Commander node handling an error or action. */
function getCommanderCommandPath(e) {
return getCommandHierarchy(e).slice(1).map((e) => e.name());
}
/** Resolve lazy help before classifying a possible child on Commander's active command node. */
function getCommanderSubcommandFact(e, t) {
if ((t.includes("-h") || t.includes("--help")) && lazyCommands.has(e)) return { kind: "defer" };
const n = e.args[0];
const r = e.commands.some((e) => e.name() === n || e.aliases().includes(n ?? ""));
if (e.registeredArguments.length > 0 || n === void 0 || n.startsWith("-") || r) return;
return e.commands.length > 0 ? {
kind: "unknown",
name: n
} : void 0;
}
/** Scope the exact Commander node synchronously emitting an error. */
function setCommanderErrorCommand(e) {
const t = getRootCommand(e);
const n = activeErrorCommandByRoot.get(t);
activeErrorCommandByRoot.set(t, e);
return () => {
if (n) activeErrorCommandByRoot.set(t, n);
else activeErrorCommandByRoot.delete(t);
};
}
/** Return the active parse-error path without replacing Commander's configured output handler. */
function getCommanderErrorCommandPath(e) {
const t = activeErrorCommandByRoot.get(getRootCommand(e));
return t ? getCommanderCommandPath(t) : void 0;
}
/** Return visible children of the non-root command synchronously emitting a parse error. */
function getCommanderErrorCommandNames(e) {
const t = activeErrorCommandByRoot.get(getRootCommand(e));
return t && getCommanderCommandPath(t).length ? t.createHelp().visibleCommands(t).flatMap((e) => e.aliases().concat(e.name())) : void 0;
}
//#endregion
//#region src/cli/machine-output-argv.ts
const MACHINE_OUTPUT_JSON_OPTION_DESCRIPTION = "Explicit machine-output spelling (command results are JSON by default)";
/** Prefer registered option roles; early discovery falls back to literal option spellings. */
function hasMachineOutputOption(e, t, n) {
if (n) return hasCommanderOptionToken(n, e, /* @__PURE__ */ new Set([t]), "flag");
for (const n of e.slice(2)) {
if (n === "--") return false;
if (n === t || n.startsWith(`${t}=`)) return true;
}
return false;
}
//#endregion
//#region src/cli/doctor-output-mode.ts
/** Bare doctor JSON and non-TTY lint runs own machine-readable stdout. */
function isDoctorMachineOutput(e) {
if (hasMachineOutputOption(e.argv, "--lint")) return hasMachineOutputOption(e.argv, "--json") || !e.stdoutIsTTY;
const t = hasMachineOutputOption(e.argv, "--post-upgrade") || hasMachineOutputOption(e.argv, "--state-sqlite") || hasMachineOutputOption(e.argv, "--session-sqlite");
return hasMachineOutputOption(e.argv, "--json") && !t;
}
//#endregion
//#region src/cli/program/core-command-descriptors.ts
function command$1(e, t, n, r = {}) {
return {
name: e,
description: t,
hasSubcommands: n,
...r
};
}
const CORE_CLI_COMMAND_DESCRIPTORS = [
command$1("setup", "Chat with OpenClaw; onboard when setup is incomplete", false),
command$1("crestodian", "Deprecated: use openclaw setup", false, { hidden: true }),
command$1("onboard", "Guided setup for auth, models, Gateway, workspace, channels, and skills", true),
command$1("configure", "Interactive configuration for credentials, channels, gateway, and agent defaults", false),
command$1("config", "Non-interactive config helpers (get/set/patch/unset/file/schema/validate). Run without subcommand for guided setup.", true, { machineOutput: ({ argv: e }) => isConfigMachineOutput(e) }),
command$1("templates", "Author and add OpenClaw Templates", true, { parentDefaultHelp: true }),
command$1("backup", "Create, verify, and restore backup archives and SQLite snapshots", true),
command$1("database", "Inspect database compatibility, manage ownership, and port database stores", true, {
parentDefaultHelp: true,
machineOutput: ({ argv: e }) => hasMachineOutputOption(e, "--json")
}),
command$1("migrate", "Import state from another agent system", true),
command$1("storage", "List, initialize, and test configured storage locations", true, {
parentDefaultHelp: true,
machineOutput: ({ argv: e }) => hasMachineOutputOption(e, "--json")
}),
command$1("doctor", "Health checks + quick fixes for the gateway and channels", false, { machineOutput: isDoctorMachineOutput }),
command$1("triage", "Collect sanitized diagnostics and open a local coding agent for repair", false, { machineOutput: ({ argv: e }) => hasMachineOutputOption(e, "--json") }),
command$1("dashboard", "Open the Control UI with your current token", false),
command$1("reset", "Reset local config/state (keeps the CLI installed)", false),
command$1("uninstall", "Uninstall the gateway service + local data", false),
command$1("message", "Send, read, and manage messages and channel actions", true),
command$1("mcp", "Manage OpenClaw mcp.servers config and channel bridge", true, { parentDefaultHelp: true }),
command$1("transcripts", "Inspect stored transcripts", true),
command$1("agent", "Run an agent turn via the Gateway (use --local for embedded)", true),
command$1("agents", "Manage isolated agents (workspaces + auth + routing)", true),
command$1("status", "Show channel health and recent session recipients", false),
command$1("health", "Fetch health from the running gateway", false),
command$1("audit", "Inspect activity records and exact-run identity context", false),
command$1("sessions", "List stored conversation sessions", true)
];
function getCoreCliCommandDescriptors() {
return CORE_CLI_COMMAND_DESCRIPTORS;
}
function getCoreCliCommandNamesCore() {
return getCoreCliCommandDescriptors().map((e) => e.name);
}
//#endregion
//#region src/cli/program/private-qa-policy.ts
/** Private QA command visibility is independent of loading its source-only implementation. */
function isPrivateQaCliEnabled(e = process.env) {
return e.OPENCLAW_ENABLE_PRIVATE_QA_CLI === "1";
}
//#endregion
//#region src/cli/program/subcli-command-metadata.ts
function command(e, t, n = {}) {
return {
name: e,
description: t,
hasSubcommands: true,
...n
};
}
const commands = [
command("acp", "Run an ACP bridge backed by the Gateway"),
command("gateway", "Run, inspect, and query the WebSocket Gateway"),
command("daemon", "Manage the Gateway service (launchd/systemd/schtasks)"),
command("logs", "Tail gateway file logs via RPC", { hasSubcommands: false }),
command("system", "System tools (events, heartbeat, presence)"),
command("models", "Model discovery, scanning, and configuration"),
command("promos", "Discover and claim promotional model offers from ClawHub"),
command("telemetry", "Inspect and manage anonymous usage telemetry", { parentDefaultHelp: true }),
command("infer", "Run provider-backed inference commands through a stable CLI surface"),
command("capability", "Run provider capability commands (fallback alias: infer)"),
command("approvals", "Manage approval policy and pending requests", { parentDefaultHelp: true }),
command("exec-approvals", "Manage exec approvals (alias for approvals)"),
command("exec-policy", "Show or synchronize requested exec policy with host approvals"),
command("nodes", "Manage gateway-owned nodes (pairing, status, invoke, and media)"),
command("devices", "Device pairing and auth tokens (for mobile app setup codes, use `openclaw qr` instead)", { parentDefaultHelp: true }),
command("users", "Manage durable user profiles and email aliases", { parentDefaultHelp: true }),
command("node", "Run and manage the headless node host service"),
command("connect", "Connect this machine to an OpenClaw Gateway as a node", { hasSubcommands: false }),
command("worker", "Run the restricted cloud worker runtime", { hasSubcommands: false }),
command("sandbox", "Manage sandbox containers (Docker-based agent isolation)"),
command("worktrees", "Create, inspect, restore, and clean up managed worktrees", { parentDefaultHelp: true }),
command("attach", "Attach Claude Code to a gateway session with scoped MCP tools", { hasSubcommands: false }),
command("tui", "Open a terminal UI connected to the Gateway", { hasSubcommands: false }),
command("resume", "Resume a recent Gateway session in the TUI", { hasSubcommands: false }),
command("terminal", "Open a local terminal UI (alias for tui --local)", { hasSubcommands: false }),
command("chat", "Open a local terminal UI (alias for tui --local)", { hasSubcommands: false }),
command("cron", "Manage automations (via Gateway)", { parentDefaultHelp: true }),
command("automations", "Manage automations (alias for cron)", { parentDefaultHelp: true }),
command("dns", "DNS helpers for wide-area discovery (Tailscale + CoreDNS)"),
command("docs", "Search the live OpenClaw docs", { hasSubcommands: false }),
command("qa", "Run QA scenarios and launch the private QA debugger UI"),
command("proxy", "Run the OpenClaw debug proxy and inspect captured traffic"),
command("hooks", "Manage internal agent hooks"),
command("webhooks", "Webhook helpers and integrations"),
command("qr", "Generate a mobile pairing QR code and setup code", { hasSubcommands: false }),
command("clawbot", "Legacy clawbot command aliases"),
command("pairing", "Secure DM pairing (approve inbound requests)"),
command("plugins", "Manage OpenClaw plugins and extensions", { parentDefaultHelp: true }),
command("channels", "Manage connected chat channels and accounts", { parentDefaultHelp: true }),
command("directory", "Lookup contact and group IDs (self, peers, groups) for supported chat channels"),
command("security", "Audit local config and state for common security foot-guns"),
command("secrets", "Secrets runtime controls"),
command("skills", "List and inspect available skills"),
command("update", "Update OpenClaw and inspect update channel status"),
command("completion", "Generate shell completion script", { hasSubcommands: false })
];
function getSubCliCommandMetadata() {
return isPrivateQaCliEnabled() ? commands : commands.filter((e) => e.name !== "qa");
}
const SUB_CLI_COMMAND_METADATA = getSubCliCommandMetadata();
//#endregion
//#region src/cli/argv.ts
const HELP_FLAGS = /* @__PURE__ */ new Set(["-h", "--help"]);
const ROOT_VERSION_ALIAS_FLAGS = /* @__PURE__ */ new Set(["-v"]);
const VERSION_FLAGS = /* @__PURE__ */ new Set([
"-V",
"--version",
...ROOT_VERSION_ALIAS_FLAGS
]);
const ROOT_COMMAND_DESCRIPTORS = [...CORE_CLI_COMMAND_DESCRIPTORS, ...SUB_CLI_COMMAND_METADATA];
const KNOWN_ROOT_COMMANDS = new Set(ROOT_COMMAND_DESCRIPTORS.map((e) => e.name));
const ROOT_COMMANDS_WITH_SUBCOMMANDS = new Set(ROOT_COMMAND_DESCRIPTORS.filter((e) => e.hasSubcommands).map((e) => e.name));
function isHelpOrVersionInvocation(e) {
if (isRootVersionInvocation(e)) return true;
const t = e.slice(2);
let n = false;
let r = false;
const i = [];
for (let e = 0; e < t.length; e += 1) {
const a = t[e];
if (!a) break;
if (!r && a === "--") {
r = true;
continue;
}
const o = r ? 0 : consumeRootOptionToken(t, e);
if (o > 0) {
e += o - 1;
continue;
}
if (!r && HELP_FLAGS.has(a)) return true;
if (!r && a.startsWith("-")) {
n = true;
continue;
}
i.push(a);
if (a !== "help") continue;
if (n) return false;
if (i.length === 1) return true;
const [s] = i;
if (!s || !KNOWN_ROOT_COMMANDS.has(s)) return true;
if (i.length === 2 && ROOT_COMMANDS_WITH_SUBCOMMANDS.has(s)) return true;
return false;
}
return false;
}
function hasFlag(e, t) {
const n = e.slice(2);
for (const e of n) {
if (e === "--") break;
if (e === t) return true;
}
return false;
}
function hasRootVersionAlias(e) {
return isRootInvocationForFlags(e, ROOT_VERSION_ALIAS_FLAGS);
}
function isRootVersionInvocation(e) {
return isRootInvocationForFlags(e, VERSION_FLAGS);
}
function isRootInvocationForFlags(e, t) {
const n = e.slice(2);
let r = false;
for (let e = 0; e < n.length; e += 1) {
const i = n[e];
if (!i) continue;
if (i === "--") break;
if (t.has(i)) {
r = true;
continue;
}
const a = consumeRootOptionToken(n, e);
if (a > 0) {
e += a - 1;
continue;
}
return false;
}
return r;
}
function isRootHelpInvocation(e) {
return isRootInvocationForFlags(e, HELP_FLAGS);
}
/** Match fast-path command help only when no command option can own the help token as a value. */
function isSimpleCommandHelpInvocation(e, t) {
const n = e.slice(2);
let r = false;
let i = false;
for (let e = 0; e < n.length; e += 1) {
const a = n[e];
if (!a || a === "--") return false;
const o = r ? 0 : consumeRootOptionToken(n, e);
if (o > 0) {
e += o - 1;
continue;
}
if (HELP_FLAGS.has(a)) {
if (!r) return false;
i = true;
continue;
}
if (a.startsWith("-") || r) return false;
if (!t.has(a)) return false;
r = true;
}
return r && i;
}
function scanHelpNormalizationArgv(e) {
const t = [];
const n = [];
let r = null;
let i = false;
for (let a = 2; a < e.length; a += 1) {
const o = e[a];
if (!o) break;
if (!i && o === "--") {
i = true;
continue;
}
const s = i ? 0 : consumeRootOptionToken(e, a);
if (s > 0) {
n.push(...e.slice(a, a + s));
a += s - 1;
continue;
}
if (!i && HELP_FLAGS.has(o)) {
r = a;
continue;
}
if (o.startsWith("-")) return { ok: false };
t.push({
value: o,
index: a
});
}
return {
ok: true,
positionals: t,
rootOptions: n,
helpFlagIndex: r
};
}
function normalizeGeneratedHelpCommandArgv(e) {
const t = scanHelpNormalizationArgv(e);
if (!t.ok) return e;
const { positionals: n, rootOptions: r, helpFlagIndex: i } = t;
const [a, o, s] = n;
if (!a || o?.value !== "help" || KNOWN_ROOT_COMMANDS.has(a.value) && !ROOT_COMMANDS_WITH_SUBCOMMANDS.has(a.value)) return e;
if (n.length === 2 && i === o.index + 1) return e.toSpliced(i, 1);
if (!s || n.length !== 3 || i !== null && i !== s.index + 1) return e;
const [c, l] = e;
if (c === void 0 || l === void 0) return e;
return [
c,
l,
...r,
a.value,
s.value,
"--help"
];
}
function normalizeRootHelpTargetArgv(e) {
const t = scanHelpNormalizationArgv(e);
if (!t.ok) return e;
const { positionals: n, rootOptions: r, helpFlagIndex: i } = t;
const [a, o] = n;
const s = n.at(-1);
if (a?.value !== "help" || !o || !s || i !== null && i !== s.index + 1) return e;
const [c, l] = e;
if (c === void 0 || l === void 0) return e;
const u = n.slice(1).map((e) => e.value);
return [
c,
l,
...r,
...u,
"--help"
];
}
function isPossibleCommandOptionValue(e, t) {
const n = e[t - 1];
if (!n?.startsWith("-") || n === "--") return false;
return !n.includes("=");
}
function consumeRootLogLevelToken(e, t) {
const n = e[t];
if (!n || n === "--") return 0;
if (n.startsWith("--log-level=")) return n.slice(12).trim() ? 1 : 0;
if (n === "--log-level") return isValueToken(e[t + 1]) ? 2 : 0;
return 0;
}
function normalizeRootOptionArgv(e, t, n) {
const r = e.slice(0, 2);
const i = e.slice(2);
let a = 0;
for (let e = 0; e < i.length; e += 1) {
const t = i[e];
if (!t || t === "--") break;
const n = consumeRootOptionToken(i, e);
if (n <= 0) break;
a = e + n;
e += n - 1;
}
const o = i.slice(0, a);
const s = i.slice(a);
const c = [];
const l = [];
for (let e = 0; e < s.length; e += 1) {
const r = s.at(e);
if (r === void 0) break;
if (r === "--") {
l.push(...s.slice(e));
break;
}
const i = t(s, e);
if (i > 0) {
const t = n(s, e, i) ?? isPossibleCommandOptionValue(s, e);
const r = s.slice(e, e + i);
if (t) l.push(...r);
else c.push(...r);
e += i - 1;
continue;
}
l.push(r);
}
if (c.length === 0) return e;
return [
...r,
...o,
...c,
...l
];
}
function normalizeRootNoColorArgv(e, t = {}) {
return normalizeRootOptionArgv(e, (e, t) => e[t] === "--no-color" ? 1 : 0, (e, n) => t.shouldPreserveNoColor?.({
remainingArgs: e,
noColorIndex: n
}));
}
function normalizeRootLogLevelArgv(e, t = {}) {
return normalizeRootOptionArgv(e, consumeRootLogLevelToken, (e, n, r) => t.shouldPreserveLogLevel?.({
remainingArgs: e,
logLevelIndex: n,
consumed: r
}));
}
function getFlagValue(e, t) {
const n = e.slice(2);
let r;
for (let e = 0; e < n.length; e += 1) {
const i = n.at(e);
if (i === void 0) break;
if (i === "--") break;
if (i === t) {
const t = n[e + 1];
if (!isValueToken(t)) return null;
r = t;
e += 1;
continue;
}
if (i.startsWith(`${t}=`)) {
const e = i.slice(t.length + 1);
if (!e) return null;
r = e;
}
}
return r;
}
function getVerboseFlag(e) {
return hasFlag(e, "--verbose") || hasFlag(e, "--debug");
}
function getPositiveIntFlagValue(e, t) {
const n = getFlagValue(e, t);
if (n === null || n === void 0) return n;
return parseStrictPositiveInteger(n) ?? null;
}
function getCommandPathWithRootOptions(e, t = 2) {
return getRootOptionAwareCommandPath(e, t);
}
function getPrimaryCommand(e) {
const [t] = getCommandPathWithRootOptions(e, 1);
return t ?? null;
}
function buildParseArgv(e, t = "openclaw") {
const n = e[0] === t || e[0]?.endsWith("openclaw") ? e.slice(1) : e;
if (n.length >= 2 && (isNodeRuntime(n[0] ?? "") || isBunRuntime(n[0] ?? ""))) return n;
return [
"node",
t,
...n
];
}
//#endregion
export { setCommanderErrorCommand as A, hasMachineOutputOption as C, getCommanderSubcommandFact as D, getCommanderErrorCommandPath as E, getRootCommand as M, removeCommandByName as N, hasCommanderOptionToken as O, MACHINE_OUTPUT_JSON_OPTION_DESCRIPTION as S, getCommanderErrorCommandNames as T, getSubCliCommandMetadata as _, getPrimaryCommand as a, getCoreCliCommandNamesCore as b, hasRootVersionAlias as c, isRootVersionInvocation as d, isSimpleCommandHelpInvocation as f, normalizeRootNoColorArgv as g, normalizeRootLogLevelArgv as h, getPositiveIntFlagValue as i, getCommandHierarchy as j, markCommanderLazyCommand as k, isHelpOrVersionInvocation as l, normalizeRootHelpTargetArgv as m, getCommandPathWithRootOptions as n, getVerboseFlag as o, normalizeGeneratedHelpCommandArgv as p, getFlagValue as r, hasFlag as s, buildParseArgv as t, isRootHelpInvocation as u, isPrivateQaCliEnabled as v, getCommanderCommandPath as w, isDoctorMachineOutput as x, getCoreCliCommandDescriptors as y };