UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

957 lines (956 loc) • 39.4 kB
import { c as normalizeOptionalLowercaseString, l as normalizeOptionalString, o as normalizeLowercaseStringOrEmpty, p as normalizeStringifiedOptionalString } from "./string-coerce-CCIiB4H7.mjs"; import { s as hasFlag } from "./argv-CbnKpH-r.mjs"; import { t as resolveCliArgvInvocation } from "./argv-invocation-C9SmXUsh.mjs"; import { l as isRecord, o as asRecord } from "./record-coerce-CVPuDqcc.mjs"; import "./src-H3RMXyFL.mjs"; import { n as formatByteSize } from "./format-KwhqGIVR.mjs"; import { r as defaultRuntime } from "./runtime-B-SLYP-m.mjs"; import { n as sanitizeTerminalText, r as terminalText } from "./safe-text-C80HAQ2e.mjs"; import { a as displayPath, f as shortenHomeInString } from "./utils-C8YECn2Q.mjs"; import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs"; import { t as formatCliCommand } from "./command-format-CqdwUgPk.mjs"; import { t as parseDurationMs } from "./parse-duration-D6UJm52I.mjs"; import { r as theme } from "./theme-BOI0xyRZ.mjs"; import { r as isNodeHostStats } from "./node-host-stats-vBi-GLvG.mjs"; import { t as resolveNodePairApprovalScopes } from "./node-pairing-authz-D_t_JVHN.mjs"; import { a as withConsoleLogsRoutedToStderrForJson } from "./json-output-mode-DSme4Xvd.mjs"; import { t as formatDocsLink } from "./links-41lO3DKP.mjs"; import { n as formatTimeAgo } from "./format-relative-JG-kbkDF.mjs"; import { t as isNodesMachineOutput } from "./output-mode-CyDVYMbH.mjs"; import { n as renderTable, t as getTerminalTableWidth } from "./table-D2a-pD4_.mjs"; import { n as formatHelpExamples } from "./help-format-D2ytHW5E.mjs"; import { n as getNodesTheme, r as runNodesCommand, t as formatConnectionFlagReminder } from "./cli-utils-CqN0h1Th.mjs"; import { n as parsePairingList, t as parseNodeList } from "./node-list-parse-DT6NmnCE.mjs"; import { a as nodesCallOpts, c as parseOptionalNodeInteger, d as resolveNodeDiagnosticsId, i as callNodesGatewayCli, l as resolveCliNode, n as callNodeDiagnosticsGatewayCli, o as parseNodeDurationMs, r as callNodePairApprovalGatewayCli, s as parseOptionalNodeFiniteNumber, t as buildNodeInvokeParams, u as resolveCliNodeId } from "./rpc-BLWTBJRk.mjs"; import { a as cameraTempPath, c as resolveCameraClipTarget, d as writeBase64ToFile, f as writeCameraClipPayloadToFile, l as resolveCameraSnapTargets, n as screenRecordTempPath, o as parseCameraClipPayload, p as writeCameraPayloadToFile, s as parseCameraSnapPayload, t as parseScreenRecordPayload, u as withCameraArtifactBatch } from "./nodes-screen-DsUorxUm.mjs"; import { n as setCommandJsonMode } from "./json-mode-DF5JGxtm.mjs"; import { t as formatPairingApproveCommand } from "./pairing-command-format-6Zqnpsx_.mjs"; import { t as formatVersionLabel } from "./version-format-Dr72usOG.mjs"; import { Option } from "commander"; //#region src/cli/nodes-cli/pairing-render.ts /** Render pending pairing requests with sanitized labels and relative request age. */ function renderPendingPairingRequestsTable(e) { const { pending: t, now: n, tableWidth: r, theme: i } = e; const a = t.map((e) => ({ Request: terminalText`${e.requestId}`, Node: terminalText`${e.displayName?.trim() || e.nodeId}`, IP: terminalText`${e.remoteIp ?? ""}`, Scopes: terminalText`${resolveNodePairApprovalScopes(e.commands, e.requiredApproveScopes).join(", ")}`, Requested: typeof e.ts === "number" ? formatTimeAgo(Math.max(0, n - e.ts)) : i.muted("unknown") })); return { heading: i.heading("Pending"), table: renderTable({ width: r, columns: [ { key: "Request", header: "Request", minWidth: 8 }, { key: "Node", header: "Node", minWidth: 14, flex: true }, { key: "IP", header: "IP", minWidth: 10 }, { key: "Requested", header: "Requested", minWidth: 12 }, { key: "Scopes", header: "Approval scopes", minWidth: 14, flex: true } ], rows: a }).trimEnd() }; } //#endregion //#region src/cli/nodes-cli/register.pairing.ts const DEFAULT_NODE_PAIR_APPROVE_SCOPES = ["operator.pairing"]; async function resolveApproveScopesForRequest(e, t) { let n; try { const t = await callNodePairApprovalGatewayCli("node.pair.list", e, {}, { scopes: DEFAULT_NODE_PAIR_APPROVE_SCOPES }); n = parsePairingList(t).pending; } catch { return { scopes: [...DEFAULT_NODE_PAIR_APPROVE_SCOPES] }; } const r = n.map((e) => e.requestId).filter((e) => typeof e === "string" && e.length > 0); const i = n.find((e) => e.requestId === t); if (!i) throw new Error(buildUnknownNodePairRequestIdMessage(t, e, r)); return { scopes: resolveNodePairApprovalScopes(i.commands, i.requiredApproveScopes) }; } function isUnknownNodePairRequestIdError(e) { const t = e; return t instanceof Error && t.name === "GatewayClientRequestError" && t.gatewayCode === "INVALID_REQUEST" && t.message === "unknown requestId"; } function buildUnknownNodePairRequestIdMessage(e, t, n) { const r = [`Unknown node pairing requestId: ${e}`]; if (n !== void 0) { if (n.length > 0) r.push(`Pending requestIds: ${n.join(", ")}`); else r.push("No pending node pairing requests are currently visible."); } r.push(`Run ${formatCliCommand("openclaw nodes pending")} to inspect current requests.`); const i = formatConnectionFlagReminder(t); if (i) r.push(i); return r.join("\n"); } function registerNodesPairingCommands(e) { nodesCallOpts(e.command("pending").description("List pending pairing requests").action(async (e) => { await runNodesCommand("pending", async () => { const t = await callNodesGatewayCli("node.pair.list", e, {}); const { pending: n } = parsePairingList(t); if (e.json) { defaultRuntime.writeJson(n); return; } if (n.length === 0) { const { muted: e } = getNodesTheme(); defaultRuntime.log(e("No pending pairing requests.")); return; } const { heading: r, muted: i } = getNodesTheme(); const a = getTerminalTableWidth(); const o = renderPendingPairingRequestsTable({ pending: n, now: Date.now(), tableWidth: a, theme: { heading: r, muted: i } }); defaultRuntime.log(o.heading); defaultRuntime.log(o.table); }); })); for (const [t, n] of [["approve", "Approve a pending pairing request"], ["reject", "Reject a pending pairing request"]]) nodesCallOpts(e.command(t).description(n).argument("<requestId>", "Pending request id").action(async (e, n) => { await runNodesCommand(t, async () => { const r = t === "approve" ? await resolveApproveScopesForRequest(n, e) : void 0; let i; try { i = r ? await callNodePairApprovalGatewayCli("node.pair.approve", n, { requestId: e }, r) : await callNodesGatewayCli("node.pair.reject", n, { requestId: e }); } catch (t) { if (isUnknownNodePairRequestIdError(t)) { t.name = "Error"; t.message = buildUnknownNodePairRequestIdMessage(e, n); } throw t; } defaultRuntime.writeJson(i); }); })); nodesCallOpts(e.command("remove").description("Remove a paired node entry").requiredOption("--node <idOrNameOrIp>", "Node id, name, or IP").action(async (e) => { await runNodesCommand("remove", async () => { const t = await resolveCliNodeId(e, normalizeOptionalString(e.node) ?? ""); const n = await callNodesGatewayCli("node.pair.remove", e, { nodeId: t }); if (e.json) { defaultRuntime.writeJson(n); return; } const { warn: r } = getNodesTheme(); defaultRuntime.log(r(sanitizeTerminalText(`Removed paired node ${t}`))); }); })); nodesCallOpts(e.command("rename").description("Rename a paired node (display name override)").requiredOption("--node <idOrNameOrIp>", "Node id, name, or IP").requiredOption("--name <displayName>", "New display name").action(async (e) => { await runNodesCommand("rename", async () => { const t = normalizeOptionalString(e.name) ?? ""; if (!t) throw new Error(`--name must not be empty. Run ${formatCliCommand("openclaw nodes list")} to see paired nodes, then rerun with --name <displayName>.`); const n = await resolveCliNodeId(e, normalizeOptionalString(e.node) ?? ""); const r = await callNodesGatewayCli("node.rename", e, { nodeId: n, displayName: t }); if (e.json) { defaultRuntime.writeJson(r); return; } const { ok: i } = getNodesTheme(); defaultRuntime.log(i(sanitizeTerminalText(`node rename ok: ${n} -> ${t}`))); }); })); } //#endregion //#region src/cli/nodes-cli/register.status.ts /** Format node permission maps as a stable `[permission=yes|no]` label. */ function formatPermissions(e) { if (!e || typeof e !== "object" || Array.isArray(e)) return null; const t = Object.entries(e).map(([e, t]) => [normalizeStringifiedOptionalString(e) ?? "", t === true]).filter(([e]) => e.length > 0).toSorted((e, t) => e[0].localeCompare(t[0])); if (t.length === 0) return null; return `[${t.map(([e, t]) => `${e}=${t ? "yes" : "no"}`).join(", ")}]`; } function formatNodeStatsBytes(e) { return formatByteSize(e, { style: "legacy-binary", maxUnit: "tera", separator: " ", fractionDigits: (e, t) => e < 10 && t !== "byte" ? 1 : 0 }); } function formatNodeHostStats(e, t, n) { if (!isNodeHostStats(e)) return null; const r = formatNodeStatsBytes(e.memoryTotalBytes); const i = formatNodeStatsBytes(e.memoryTotalBytes - e.memoryFreeBytes); const a = r.slice(r.lastIndexOf(" ")); const o = i.endsWith(a) ? i.slice(0, -a.length) : i; const s = [ e.loadAverage ? `load ${e.loadAverage[0].toFixed(1)}/${e.cpuCount}` : null, `mem ${o}/${r}`, e.diskAvailableBytes !== void 0 ? `disk ${formatNodeStatsBytes(e.diskAvailableBytes)} free` : null ].filter(Boolean).join(" · "); return t ? s : `${s} (last known ${formatTimeAgo(Math.max(0, n - e.updatedAtMs))})`; } function formatNodeVersions(e) { let t = normalizeOptionalString(e.coreVersion); let n = normalizeOptionalString(e.uiVersion); if (!t && !n) { const r = e.version?.trim(); if (!r) return null; const i = normalizeOptionalLowercaseString(e.platform); if (i === "darwin" || i === "linux" || i === "win32" || i === "windows") t = r; else n = r; } return [t && `core ${formatVersionLabel(t)}`, n && `ui ${formatVersionLabel(n)}`].filter(Boolean).join(" · ") || null; } function formatPathEnv(e, t) { const n = normalizeOptionalString(e); if (!n) return null; const r = normalizeOptionalLowercaseString(t); const i = r === "win32" || r === "windows" ? ";" : ":"; const a = n.split(i).filter(Boolean); const o = a.length <= 3 ? n : `${a.slice(0, 2).join(i)}${i}…${i}${a.slice(-1)[0]}`; return shortenHomeInString(o); } function formatClientLabel(e) { return [e.clientId?.trim(), e.clientMode?.trim()].filter(Boolean).join("/") || null; } function formatNodeTerminalLabel(e) { return sanitizeTerminalText(e.displayName?.trim() || e.nodeId); } function sortedNodeStrings(e) { return Array.isArray(e) ? e.map(String).filter(Boolean).toSorted() : null; } function formatNodeTimeAgo(e, t) { return typeof t === "number" && Number.isFinite(t) ? formatTimeAgo(Math.max(0, e - t)) : null; } function formatNodeApprovalState(e) { return e === "approved" || e === "pending-approval" || e === "pending-reapproval" || e === "unapproved" ? e : null; } function formatApprovalStateLabel(e) { if (e === "pending-approval") return "approval pending"; if (e === "pending-reapproval") return "reapproval pending"; return e; } function isPendingApprovalState(e) { return e === "pending-approval" || e === "pending-reapproval"; } function parseSinceMs(e) { if (e === void 0) return; try { return parseDurationMs(e); } catch (e) { throw new Error(`Invalid --last-connected: ${formatErrorMessage(e)}`, { cause: e }); } } function matchesNodeConnectionFilter(e, t, n, r) { if (t && !e.connected) return false; const i = e.lastConnectedAtMs ?? e.connectedAtMs; return n === void 0 || typeof i === "number" && r - i <= n; } async function tryReadNodeList(e) { try { return parseNodeList(await callNodeDiagnosticsGatewayCli("node.list", e, {})); } catch (e) { defaultRuntime.error(getNodesTheme().muted(`live node view unavailable (${formatErrorMessage(e)}); showing paired-only data`)); return null; } } function registerNodesStatusCommands(e) { nodesCallOpts(e.command("status").description("List known nodes with connection status and capabilities").option("--connected", "Only show connected nodes").option("--last-connected <duration>", "Only show nodes connected within duration (e.g. 24h)").action(async (e) => { await runNodesCommand("status", async () => { const t = Boolean(e.connected); const n = parseSinceMs(e.lastConnected); const r = await callNodeDiagnosticsGatewayCli("node.list", e, {}); const i = typeof r === "object" && r !== null ? r : {}; const { ok: a, warn: o, muted: s } = getNodesTheme(); const c = getTerminalTableWidth(); const l = Date.now(); const u = parseNodeList(r); const d = u.filter((e) => matchesNodeConnectionFilter(e, t, n, l)); if (e.json) { const e = typeof i.ts === "number" ? i.ts : Date.now(); defaultRuntime.writeJson({ ...i, ts: e, nodes: d }); return; } const f = d.filter((e) => Boolean(e.paired)).length; const p = d.filter((e) => Boolean(e.connected)).length; const m = d.length !== u.length ? ` (of ${u.length})` : ""; defaultRuntime.log(`Known: ${d.length}${m} · Paired: ${f} · Connected: ${p}`); if (d.length === 0) return; const h = d.map((e) => { const t = formatPermissions(e.permissions); const n = formatNodeVersions(e); const r = formatPathEnv(e.pathEnv, e.platform); const i = formatClientLabel(e); const c = formatNodeTimeAgo(l, e.lastActiveAtMs); const u = [ i ? `client: ${i}` : null, e.deviceFamily ? `device: ${e.deviceFamily}` : null, e.modelIdentifier ? `hw: ${e.modelIdentifier}` : null, t ? `perms: ${t}` : null, n, formatNodeHostStats(e.hostStats, Boolean(e.connected), l), r ? `path: ${r}` : null, c ? `input: ${c}${e.active ? " (active)" : ""}` : null ].filter(Boolean).map((e) => sanitizeTerminalText(String(e))); const d = sortedNodeStrings(e.caps); const f = e.paired ? a("paired") : o("unpaired"); const p = e.connected ? a("connected") : s("disconnected"); const m = formatNodeApprovalState(e.approvalState); const h = m === "approved" ? a("approved") : isPendingApprovalState(m) ? o(formatApprovalStateLabel(m)) : m === "unapproved" ? o("unapproved") : null; const g = typeof e.connectedAtMs === "number" ? ` (${formatTimeAgo(Math.max(0, l - e.connectedAtMs))})` : ""; return { Node: formatNodeTerminalLabel(e), ID: sanitizeTerminalText(e.nodeId), IP: sanitizeTerminalText(e.remoteIp ?? ""), Detail: u.join(" · "), Status: `${f} · ${p}${g}${h ? ` · ${h}` : ""}`, Caps: d ? sanitizeTerminalText(d.join(", ")) : "?" }; }); defaultRuntime.log(renderTable({ width: c, columns: [ { key: "Node", header: "Node", minWidth: 14, flex: true }, { key: "ID", header: "ID", minWidth: 10 }, { key: "IP", header: "IP", minWidth: 10 }, { key: "Detail", header: "Detail", minWidth: 18, flex: true }, { key: "Status", header: "Status", minWidth: 18 }, { key: "Caps", header: "Caps", minWidth: 12, flex: true } ], rows: h }).trimEnd()); for (const t of d) { const n = formatNodeApprovalState(t.approvalState); const r = normalizeOptionalString(t.pendingRequestId); if (isPendingApprovalState(n) && r) { const i = formatPairingApproveCommand("nodes", r, { timeout: e.timeout }); const a = n === "pending-reapproval" ? "Reapproval" : "Approval"; defaultRuntime.log(o(`${a} pending for ${formatNodeTerminalLabel(t)}. Run ${sanitizeTerminalText(i)}`)); const s = formatConnectionFlagReminder(e); if (s) defaultRuntime.log(o(s)); } } }); })); nodesCallOpts(e.command("describe").description("Describe a node (capabilities + supported invoke commands)").requiredOption("--node <idOrNameOrIp>", "Node id, name, or IP").action(async (e) => { await runNodesCommand("describe", async () => { const t = await resolveNodeDiagnosticsId(e, e.node ?? ""); const n = await callNodeDiagnosticsGatewayCli("node.describe", e, { nodeId: t }); if (e.json) { defaultRuntime.writeJson(n); return; } const r = typeof n === "object" && n !== null ? n : {}; const i = typeof r.displayName === "string" ? r.displayName : t; const a = Boolean(r.connected); const o = Boolean(r.paired); const s = sortedNodeStrings(r.caps); const c = sortedNodeStrings(r.commands) ?? []; const l = formatPermissions(r.permissions); const u = formatNodeApprovalState(r.approvalState); const d = normalizeOptionalString(r.pendingRequestId); const f = sortedNodeStrings(r.pendingDeclaredCaps); const p = sortedNodeStrings(r.pendingDeclaredCommands) ?? []; const m = formatPermissions(r.pendingDeclaredPermissions); const h = isPendingApprovalState(u) && d ? formatPairingApproveCommand("nodes", d, { timeout: e.timeout }) : null; const g = h ? formatConnectionFlagReminder(e) : null; const _ = typeof r.deviceFamily === "string" ? r.deviceFamily : null; const v = typeof r.modelIdentifier === "string" ? r.modelIdentifier : null; const y = formatClientLabel(r); const b = typeof r.remoteIp === "string" ? r.remoteIp : null; const x = typeof r.pathEnv === "string" ? r.pathEnv : null; const S = formatNodeVersions(r); const C = formatNodeTimeAgo(Date.now(), r.lastActiveAtMs); const w = formatNodeHostStats(r.hostStats, a, Date.now()); const { heading: T, ok: E, warn: D, muted: O } = getNodesTheme(); const k = `${o ? E("paired") : D("unpaired")} · ${a ? E("connected") : O("disconnected")}`; const A = getTerminalTableWidth(); const j = [{ Field: "ID", Value: sanitizeTerminalText(t) }]; const addDetail = (e, t) => { if (t) j.push({ Field: e, Value: sanitizeTerminalText(t) }); }; addDetail("Name", i); addDetail("Client", y); addDetail("IP", b); addDetail("Device", _); addDetail("Model", v); addDetail("Perms", l); addDetail("Version", S); addDetail("Stats", w); addDetail("PATH", x); addDetail("Last input", C ? `${C}${r.active === true ? " (active node)" : ""}` : null); j.push({ Field: "Status", Value: k }); addDetail("Approval", u ? formatApprovalStateLabel(u) : null); addDetail("Pending request", d ?? null); if (f) j.push({ Field: "Pending caps", Value: sanitizeTerminalText(f.join(", ")) }); addDetail("Pending perms", m); addDetail(u === "pending-reapproval" ? "Reapprove" : "Approve", h); addDetail("Connection reminder", h && g); j.push({ Field: "Caps", Value: s ? sanitizeTerminalText(s.join(", ")) : "?" }); defaultRuntime.log(T("Node")); defaultRuntime.log(renderTable({ width: A, columns: [{ key: "Field", header: "Field", minWidth: 8 }, { key: "Value", header: "Value", minWidth: 24, flex: true }], rows: j }).trimEnd()); defaultRuntime.log(""); defaultRuntime.log(T("Commands")); if (c.length === 0) defaultRuntime.log(O("- (none effective)")); else for (const e of c) defaultRuntime.log(`- ${sanitizeTerminalText(e)}`); if (p.length > 0) { defaultRuntime.log(""); defaultRuntime.log(T("Pending commands")); for (const e of p) defaultRuntime.log(`- ${sanitizeTerminalText(e)}`); } }); })); nodesCallOpts(e.command("list").description("List pending and paired nodes").option("--connected", "Only show connected nodes").option("--last-connected <duration>", "Only show nodes connected within duration (e.g. 24h)").action(async (e) => { await runNodesCommand("list", async () => { const t = Boolean(e.connected); const n = parseSinceMs(e.lastConnected); const r = await callNodesGatewayCli("node.pair.list", e, {}); const { pending: i, paired: a } = parsePairingList(r); const { heading: o, muted: s } = getNodesTheme(); const c = getTerminalTableWidth(); const l = Date.now(); const u = t || n !== void 0; const d = u ? parseNodeList(await callNodeDiagnosticsGatewayCli("node.list", e, {})) : await tryReadNodeList(e); let f = a; if (d !== null) { const e = new Map(a.map((e) => [e.nodeId, e])); const t = /* @__PURE__ */ new Set(); f = []; for (const n of d) { const r = e.get(n.nodeId); if (!r && n.paired !== true) continue; t.add(n.nodeId); f.push({ ...r, ...n, createdAtMs: r?.createdAtMs, lastConnectedAtMs: n.lastConnectedAtMs ?? r?.lastConnectedAtMs ?? n.connectedAtMs, displayName: n.displayName ?? r?.displayName, platform: n.platform ?? r?.platform, version: n.version ?? r?.version, coreVersion: n.coreVersion ?? r?.coreVersion, uiVersion: n.uiVersion ?? r?.uiVersion, remoteIp: n.remoteIp ?? r?.remoteIp, permissions: n.permissions ?? r?.permissions, approvedAtMs: n.approvedAtMs ?? r?.approvedAtMs }); } for (const e of a) if (!t.has(e.nodeId)) f.push(e); } const p = f.filter((e) => matchesNodeConnectionFilter(e, t, n, l)); const m = u && p.length !== f.length ? ` (of ${f.length})` : ""; if (e.json) { defaultRuntime.writeJson({ pending: i, paired: p.map((e) => { const { token: t, ...n } = e; return n; }) }); return; } defaultRuntime.log(`Pending: ${i.length} · Paired: ${p.length}${m}`); if (i.length > 0) { const e = renderPendingPairingRequestsTable({ pending: i, now: l, tableWidth: c, theme: { heading: o, muted: s } }); defaultRuntime.log(""); defaultRuntime.log(e.heading); defaultRuntime.log(e.table); } if (p.length > 0) { const e = p.map((e) => ({ Node: formatNodeTerminalLabel(e), Id: sanitizeTerminalText(e.nodeId), IP: sanitizeTerminalText(e.remoteIp ?? ""), LastConnect: formatNodeTimeAgo(l, e.lastConnectedAtMs ?? e.connectedAtMs) ?? s("unknown") })); defaultRuntime.log(""); defaultRuntime.log(o("Paired")); defaultRuntime.log(renderTable({ width: c, columns: [ { key: "Node", header: "Node", minWidth: 14, flex: true }, { key: "Id", header: "ID", minWidth: 10 }, { key: "IP", header: "IP", minWidth: 10 }, { key: "LastConnect", header: "Last Connect", minWidth: 14 } ], rows: e }).trimEnd()); } }); })); } //#endregion //#region src/cli/nodes-cli/register.ts const BLOCKED_NODE_INVOKE_COMMANDS = /* @__PURE__ */ new Set(["system.run", "system.run.prepare"]); function parseNodeInvokeParams(e = "{}") { try { return JSON.parse(e); } catch { throw new Error("--params must be valid JSON."); } } /** Register the `nodes` command group and lazy plugin-provided node commands. */ async function registerNodesCli(e, t = process.argv) { const n = e.command("nodes").description("Manage gateway-owned nodes (pairing, status, invoke, and media)").addHelpText("after", () => `\n${theme.heading("Examples:")}\n${formatHelpExamples([ ["openclaw nodes status", "List known nodes with live status."], ["openclaw nodes pending", "Show pending node pairing requests."], ["openclaw nodes remove --node <id|name|ip>", "Remove a stale paired node entry."], ["openclaw nodes invoke --node <id> --command system.which --params '{\"bins\":[\"uname\"]}'", "Invoke a node command directly."], ["openclaw nodes camera snap --node <id>", "Capture a photo from a node camera."] ])}\n\n${theme.muted("Docs:")} ${formatDocsLink("/cli/nodes", "docs.openclaw.ai/cli/nodes")}\n`); registerNodesStatusCommands(n); registerNodesPairingCommands(n); nodesCallOpts(n.command("invoke").description("Invoke a command on a paired node").requiredOption("--node <idOrNameOrIp>", "Node id, name, or IP").requiredOption("--command <command>", "Command (e.g. canvas.navigate)").option("--params <json>", "JSON object string for params", "{}").option("--invoke-timeout <ms>", "Node invoke timeout in ms (default 15000)", "15000").option("--idempotency-key <key>", "Key to avoid duplicate requests (optional)").action(async (e) => { await runNodesCommand("invoke", async () => { const t = normalizeOptionalString(e.node) ?? ""; const n = normalizeOptionalString(e.command) ?? ""; if (!t || !n) throw new Error("--node and --command required"); if (BLOCKED_NODE_INVOKE_COMMANDS.has(n.toLowerCase())) throw new Error(`command "${n}" is reserved for shell execution; use the exec tool with host=node instead`); const r = parseNodeInvokeParams(e.params); const i = parseOptionalNodeInteger(e.invokeTimeout, "--invoke-timeout"); if (e.idempotencyKey === "") throw new Error("--idempotency-key must not be empty."); const a = await resolveCliNodeId(e, t); const o = buildNodeInvokeParams({ nodeId: a, command: n, params: r, idempotencyKey: e.idempotencyKey, timeoutMs: i }); const s = await callNodesGatewayCli("node.invoke", e, o); defaultRuntime.writeJson(s); }); }), { timeoutMs: 3e4 }); nodesCallOpts(n.command("notify").description("Send a local notification on a node").requiredOption("--node <idOrNameOrIp>", "Node id, name, or IP").option("--title <text>", "Notification title").option("--body <text>", "Notification body").option("--sound <name>", "Notification sound").addOption(new Option("--priority <passive|active|timeSensitive>", "Notification priority").choices([ "passive", "active", "timeSensitive" ])).addOption(new Option("--delivery <system|overlay|auto>", "Delivery mode").choices([ "system", "overlay", "auto" ]).default("system")).option("--invoke-timeout <ms>", "Node invoke timeout in ms (default 15000)", "15000").action(async (e) => { await runNodesCommand("notify", async () => { const t = normalizeOptionalString(e.title) ?? ""; const n = normalizeOptionalString(e.body) ?? ""; if (!t && !n) throw new Error("missing --title or --body"); const r = parseOptionalNodeInteger(e.invokeTimeout, "--invoke-timeout"); const i = await resolveCliNodeId(e, e.node ?? ""); const a = buildNodeInvokeParams({ nodeId: i, command: "system.notify", params: { title: t, body: n, sound: e.sound, priority: e.priority, delivery: e.delivery }, idempotencyKey: e.idempotencyKey, timeoutMs: r }); const o = await callNodesGatewayCli("node.invoke", e, a); if (e.json) { defaultRuntime.writeJson(o); return; } const { ok: s } = getNodesTheme(); defaultRuntime.log(s("notify ok")); }); })); nodesCallOpts(n.command("push").description("Send an APNs test push to an iOS node").requiredOption("--node <idOrNameOrIp>", "Node id, name, or IP").option("--title <text>", "Push title", "OpenClaw").option("--body <text>", "Push body").option("--environment <sandbox|production>", "Override APNs environment").action(async (e) => { await runNodesCommand("push", async () => { const t = normalizeOptionalLowercaseString(e.environment); if (e.environment !== void 0 && t !== "sandbox" && t !== "production") throw new Error("invalid --environment (use sandbox|production)"); const n = await resolveCliNodeId(e, e.node ?? ""); const r = normalizeOptionalString(e.title) || "OpenClaw"; const i = normalizeOptionalString(e.body) || `Push test for node ${n}`; const a = await callNodesGatewayCli("push.test", e, { nodeId: n, title: r, body: i, ...t ? { environment: t } : {} }); const o = asRecord(a); const s = o.ok === true; const c = typeof o.status === "number" ? o.status : 0; const l = normalizeOptionalString(o.reason); const u = normalizeOptionalString(o.environment) ?? "unknown"; if (e.json) defaultRuntime.writeJson(a); else { const { ok: e, error: t } = getNodesTheme(); const n = s ? e : t; defaultRuntime.log(n(`push.test status=${c} ok=${s} env=${u}`)); if (l) defaultRuntime.log(`reason: ${l}`); } if (!s) process.exitCode = 1; }); }), { timeoutMs: 25e3 }); const r = n.command("camera").description("Capture camera media from a paired node"); nodesCallOpts(r.command("list").description("List available cameras on a node").requiredOption("--node <idOrNameOrIp>", "Node id, name, or IP").action(async (e) => { await runNodesCommand("camera list", async () => { const t = await resolveCliNodeId(e, e.node ?? ""); const n = await callNodesGatewayCli("node.invoke", e, buildNodeInvokeParams({ nodeId: t, command: "camera.list", params: {} })); const r = asRecord(asRecord(n).payload); const i = Array.isArray(r.devices) ? r.devices.filter(isRecord) : Array.isArray(r.cameras) ? r.cameras.filter(isRecord).map(({ DeviceId: e, Name: t, ...n }) => Object.assign({ id: e, name: t }, n)) : []; if (e.json) { defaultRuntime.writeJson(i); return; } if (i.length === 0) { const { muted: e } = getNodesTheme(); defaultRuntime.log(e("No cameras reported.")); return; } const { heading: a, muted: o } = getNodesTheme(); const s = getTerminalTableWidth(); const text = (e, t) => typeof e === "string" ? terminalText`${e}` : t; const c = i.map((e) => ({ Name: text(e.name, "Unknown Camera"), Position: text(e.position, o("unspecified")), ID: text(e.id, "") })); defaultRuntime.log(a("Cameras")); defaultRuntime.log(renderTable({ width: s, columns: [ { key: "Name", header: "Name", minWidth: 14, flex: true }, { key: "Position", header: "Position", minWidth: 10 }, { key: "ID", header: "ID", minWidth: 10, flex: true } ], rows: c }).trimEnd()); }); }), { timeoutMs: 6e4 }); nodesCallOpts(r.command("snap").description("Capture a photo from a node camera (prints the saved path)").requiredOption("--node <idOrNameOrIp>", "Node id, name, or IP").option("--facing <front|back|both>", "Camera facing").option("--device-id <id>", "Camera device id (from nodes camera list)").option("--max-width <px>", "Max width in px (optional)").option("--quality <0-1>", "JPEG quality (optional; platform-specific default)").option("--delay-ms <ms>", "Delay before capture in ms (optional; platform-specific default)").option("--invoke-timeout <ms>", "Node invoke timeout in ms (default 20000)", "20000").action(async (e) => { await runNodesCommand("camera snap", async () => { const t = e.facing === void 0 ? void 0 : normalizeLowercaseStringOrEmpty(e.facing); if (t !== void 0 && t !== "both" && t !== "front" && t !== "back") throw new Error(`invalid facing: ${String(e.facing)} (expected front|back|both)`); const n = parseOptionalNodeInteger(e.maxWidth, "--max-width"); const r = parseOptionalNodeFiniteNumber(e.quality, "--quality", { minInclusive: 0, maxInclusive: 1 }); const i = parseOptionalNodeInteger(e.delayMs, "--delay-ms", "non-negative"); const a = normalizeOptionalString(e.deviceId); const o = parseOptionalNodeInteger(e.invokeTimeout, "--invoke-timeout"); const s = await resolveCliNode(e, e.node ?? ""); const c = s.nodeId; if (a && t === "both" && s.platform?.toLowerCase() !== "linux") throw new Error("facing=both is not allowed when --device-id is set"); const l = resolveCameraSnapTargets({ facing: t, platform: s.platform, deviceId: a }); const u = []; for (const t of l) { const l = buildNodeInvokeParams({ nodeId: c, command: "camera.snap", params: { ...t.requestFacing ? { facing: t.requestFacing } : {}, maxWidth: n, quality: r, format: "jpg", delayMs: i, deviceId: a }, timeoutMs: o }); const d = await callNodesGatewayCli("node.invoke", e, l); const f = parseCameraSnapPayload(asRecord(d).payload, { expectedHost: s.remoteIp }); u.push({ facing: t.artifactFacing, payload: f, filePath: cameraTempPath({ kind: "snap", facing: t.artifactFacing, ext: f.format === "jpeg" ? "jpg" : f.format }) }); } await withCameraArtifactBatch(u.map((e) => e.filePath), async (t) => { const n = []; for (const [e, { facing: r, payload: i }] of u.entries()) { const a = t[e]; if (a === void 0) throw new Error("missing camera batch output path"); await writeCameraPayloadToFile({ filePath: a, payload: i, expectedHost: s.remoteIp, invalidPayloadMessage: "invalid camera.snap payload" }); n.push({ facing: r, path: a, width: i.width, height: i.height }); } if (e.json) { defaultRuntime.writeJson({ files: n }); return; } defaultRuntime.log(n.map((e) => displayPath(e.path)).join("\n")); }); }); }), { timeoutMs: 6e4 }); nodesCallOpts(r.command("clip").description("Capture a short video clip from a node camera (prints the saved path)").requiredOption("--node <idOrNameOrIp>", "Node id, name, or IP").option("--facing <front|back>", "Camera facing", "front").option("--device-id <id>", "Camera device id (from nodes camera list)").option("--duration <ms|10s|1m>", "Duration (default 3000ms; supports ms/s/m, e.g. 10s)", "3000").option("--no-audio", "Disable audio capture").option("--invoke-timeout <ms>", "Node invoke timeout in ms (default 90000)", "90000").action(async (e) => { await runNodesCommand("camera clip", async () => { const t = e.facing ?? "front"; const n = normalizeLowercaseStringOrEmpty(t); if (n !== "front" && n !== "back") throw new Error(`invalid facing: ${t} (expected front|back)`); const r = parseNodeDurationMs(e.duration ?? "3000"); const i = e.audio !== false; const a = parseOptionalNodeInteger(e.invokeTimeout, "--invoke-timeout"); const o = normalizeOptionalString(e.deviceId); const s = await resolveCliNode(e, e.node ?? ""); const c = s.nodeId; const l = resolveCameraClipTarget({ facing: n, platform: s.platform }); const u = buildNodeInvokeParams({ nodeId: c, command: "camera.clip", params: { facing: l.requestFacing, durationMs: r, includeAudio: i, format: "mp4", deviceId: o }, timeoutMs: a }); const d = await callNodesGatewayCli("node.invoke", e, u); const f = parseCameraClipPayload(asRecord(d).payload); const p = await writeCameraClipPayloadToFile({ payload: f, facing: l.artifactFacing, expectedHost: s.remoteIp }); if (e.json) { defaultRuntime.writeJson({ file: { facing: l.artifactFacing, path: p, durationMs: f.durationMs, hasAudio: f.hasAudio } }); return; } defaultRuntime.log(displayPath(p)); }); }), { timeoutMs: 9e4 }); const i = n.command("screen").description("Capture screen recordings from a paired node"); nodesCallOpts(i.command("record").description("Capture a short screen recording from a node (prints the saved path)").requiredOption("--node <idOrNameOrIp>", "Node id, name, or IP").option("--screen <index>", "Screen index (0 = primary)", "0").option("--duration <ms|10s>", "Clip duration (ms or 10s)", "10000").option("--fps <fps>", "Frames per second", "10").option("--no-audio", "Disable microphone audio capture").option("--out <path>", "Output path").option("--invoke-timeout <ms>", "Node invoke timeout in ms (default 120000)", "120000").action(async (e) => { await runNodesCommand("screen record", async () => { const t = parseNodeDurationMs(e.duration ?? ""); const n = parseOptionalNodeInteger(e.screen ?? "0", "--screen", "non-negative"); const r = parseOptionalNodeFiniteNumber(e.fps ?? "10", "--fps", { minExclusive: 0 }); const i = parseOptionalNodeInteger(e.invokeTimeout, "--invoke-timeout"); const a = await resolveCliNodeId(e, e.node ?? ""); const o = buildNodeInvokeParams({ nodeId: a, command: "screen.record", params: { durationMs: t, screenIndex: n, fps: r, format: "mp4", includeAudio: e.audio !== false }, timeoutMs: i }); const s = await callNodesGatewayCli("node.invoke", e, o); const c = parseScreenRecordPayload(asRecord(s).payload); const l = e.out ?? screenRecordTempPath({ ext: c.format }); const u = await writeBase64ToFile(l, c.base64); if (e.json) { defaultRuntime.writeJson({ file: { path: u.path, durationMs: c.durationMs, fps: c.fps, screenIndex: c.screenIndex, hasAudio: c.hasAudio } }); return; } defaultRuntime.log(displayPath(u.path)); }); }), { timeoutMs: 18e4 }); const a = n.command("location").description("Fetch location from a paired node"); nodesCallOpts(a.command("get").description("Fetch the current location from a node").requiredOption("--node <idOrNameOrIp>", "Node id, name, or IP").option("--max-age <ms>", "Use cached location newer than this (ms)").option("--accuracy <coarse|balanced|precise>", "Desired accuracy (default: balanced/precise depending on node setting)").option("--location-timeout <ms>", "Location fix timeout (ms)", "10000").option("--invoke-timeout <ms>", "Node invoke timeout in ms (default 20000)", "20000").action(async (e) => { await runNodesCommand("location get", async () => { const t = normalizeOptionalLowercaseString(e.accuracy); const n = t === "coarse" || t === "balanced" || t === "precise" ? t : void 0; if (e.accuracy !== void 0 && n === void 0) throw new Error("invalid --accuracy (use coarse|balanced|precise)"); const r = parseOptionalNodeInteger(e.maxAge, "--max-age", "non-negative"); const i = parseOptionalNodeInteger(e.locationTimeout, "--location-timeout"); const a = parseOptionalNodeInteger(e.invokeTimeout, "--invoke-timeout"); const o = await resolveCliNodeId(e, e.node ?? ""); const s = buildNodeInvokeParams({ nodeId: o, command: "location.get", params: { maxAgeMs: r, desiredAccuracy: n, timeoutMs: i }, timeoutMs: a }); const c = await callNodesGatewayCli("node.invoke", e, s); const l = asRecord(asRecord(c).payload); if (e.json) { defaultRuntime.writeJson(l); return; } const u = l.lat; const d = l.lon; const f = l.accuracyMeters; if (typeof u === "number" && typeof d === "number") { const e = typeof f === "number" ? ` ±${f.toFixed(1)}m` : ""; defaultRuntime.log(`${u},${d}${e}`); return; } defaultRuntime.writeJson(l, 0); }); }), { timeoutMs: 3e4 }); setCommandJsonMode(n, "output", ({ argv: e }) => isNodesMachineOutput(e)); const { commandPath: o } = resolveCliArgvInvocation([...t]); if (o[0] === "completion" || o[0] === "nodes" && n.commands.some((e) => e.name() === o[1])) return; const { registerPluginCliCommandsFromValidatedConfig: s } = await import("./cli-Can2BQj3.mjs"); const c = o.length === 1 && o[0] === "nodes" && (hasFlag([...t], "--help") || hasFlag([...t], "-h")); await withConsoleLogsRoutedToStderrForJson(t, async () => await s(e, void 0, void 0, { mode: c ? "metadata" : "lazy", primary: "nodes" })); } //#endregion export { registerNodesCli };