UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

716 lines (715 loc) • 26.5 kB
import { l as normalizeOptionalString, o as normalizeLowercaseStringOrEmpty, p as normalizeStringifiedOptionalString } from "./string-coerce-CCIiB4H7.mjs"; import { n as coerceErrorMessage } from "./error-coercion-hDrHOSGy.mjs"; import { b as uniqueStrings, h as normalizeUniqueSingleOrTrimmedStringList, v as normalizeUniqueTrimmedStringList } from "./string-normalization-DLmfYZXI.mjs"; import { r as defaultRuntime } from "./runtime-B-SLYP-m.mjs"; import { n as sanitizeForLog } from "./ansi-CZa2t0Hf.mjs"; import { r as terminalText } from "./safe-text-C80HAQ2e.mjs"; import { t as formatCliCommand } from "./command-format-CqdwUgPk.mjs"; import { f as isOperatorScope, r as PAIRING_SCOPE, t as ADMIN_SCOPE } from "./operator-scopes-CULmYfyY.mjs"; import "./method-scopes-Dpyb0Ck-.mjs"; import { s as isLoopbackHost } from "./net-BgRayX-P.mjs"; import { f as readConnectPairingRequiredMessage } from "./connect-error-details-BdhXf496.mjs"; import { r as theme } from "./theme-BOI0xyRZ.mjs"; import { n as normalizeDeviceAuthScopes } from "./device-auth-Cu5vRDvP.mjs"; import { i as listDevicePairing } from "./device-pairing-D--Fzrek.mjs"; import { s as isGatewayTransportError } from "./transport-error-BL_kuysc.mjs"; import { t as ExpectedCliError } from "./failure-output-DVVDqwuu.mjs"; import { r as callGatewayFromCliWithTransport } from "./gateway-rpc-CxUN2f1a.mjs"; import { c as formatGatewayTransportErrorJson, t as buildGatewayConnectionDetails } from "./call-DVCK1deJ.mjs"; import { t as runWithLocalStateOwner } from "./local-state-owner-DTl7OHpC.mjs"; import { n as formatTimeAgo } from "./format-relative-JG-kbkDF.mjs"; import { r as renderTerminalSafeTable, t as getTerminalTableWidth } from "./table-D2a-pD4_.mjs"; import { r as summarizeDeviceTokens } from "./device-pairing-token-utils-fd1VQ1i6.mjs"; import "./device-pairing-tokens-Bivg3I0v.mjs"; import { t as formatConnectionFlagReminder } from "./cli-utils-CqN0h1Th.mjs"; import { n as approveDevicePairing, r as formatDevicePairingForbiddenMessage } from "./device-pairing-approval-QMJvpfTq.mjs"; import { t as formatPairingApproveCommand } from "./pairing-command-format-6Zqnpsx_.mjs"; import { r as prepareCliGatewayStateAccess } from "./gateway-rpc.runtime-DGuEWCMQ.mjs"; //#region src/shared/device-pairing-access.ts function normalizeRoleList(...e) { return [...new Set(e.flatMap(normalizeUniqueSingleOrTrimmedStringList))].toSorted(); } function includesAll(e, t) { const n = new Set(e); return t.every((e) => n.has(e)); } /** Normalizes requested roles/scopes from pending pairing records, including legacy singular role. */ function summarizePendingDeviceAccess(e) { return { roles: normalizeRoleList(e.roles, e.role), scopes: normalizeDeviceAuthScopes(e.scopes) }; } /** Summarizes currently approved device access, excluding roles whose tokens are revoked. */ function summarizeApprovedDeviceAccess(e) { const t = normalizeRoleList(e.roles, e.role); const n = Array.isArray(e.tokens) ? e.tokens : e.tokens ? Object.values(e.tokens) : void 0; return { roles: n === void 0 ? t : normalizeRoleList(n.filter((e) => !e.revokedAtMs).flatMap((e) => e.role ?? [])).filter((e) => t.includes(e)), scopes: normalizeDeviceAuthScopes(e.scopes) }; } /** Classifies a pending pairing request as new pairing, role upgrade, scope upgrade, or re-approval. */ function resolvePendingDeviceApprovalState(e, t) { const n = summarizePendingDeviceAccess(e); const r = t ? summarizeApprovedDeviceAccess(t) : null; if (!r) return { kind: "new-pairing", requested: n, approved: null }; if (!includesAll(r.roles, n.roles)) return { kind: "role-upgrade", requested: n, approved: r }; if (!includesAll(r.scopes, n.scopes)) return { kind: "scope-upgrade", requested: n, approved: r }; return { kind: "re-approval", requested: n, approved: r }; } //#endregion //#region src/cli/devices-cli-fallback.ts const FALLBACK_STATE_MISMATCH_MESSAGE = "Gateway requires device pairing, but local fallback pairing state does not contain the gateway request."; function resolveLocalPairingFallback(e, t) { const n = normalizeLowercaseStringOrEmpty(coerceErrorMessage(t)); const r = readConnectPairingRequiredMessage(n); const i = isGatewayTransportError(t) && t.kind === "closed" && t.code === void 0 && t.requestDispatched !== true; if (!r && !i) return null; if (typeof e.url === "string" && e.url.trim().length > 0) return null; const a = buildGatewayConnectionDetails(); if (a.urlSource !== "local loopback") return null; try { return isLoopbackHost(new URL(a.url).hostname) ? { details: r ?? {} } : null; } catch { return null; } } function buildFallbackStateMismatchError(e, t) { const n = e.requestId ? `${FALLBACK_STATE_MISMATCH_MESSAGE} Missing requestId: ${e.requestId}.` : FALLBACK_STATE_MISMATCH_MESSAGE; const r = t[0]; const i = r ? ["That request was superseded by a newer pending request.", `Approve the current request instead: ${formatPairingApproveCommand("devices", r)}`] : ["The running gateway may be using a different OPENCLAW_PROFILE or OPENCLAW_STATE_DIR than this CLI.", "Rerun with the gateway's profile/state-dir; if the gateway uses shared auth, pass --token/--password to approve through it."]; return new Error([n, ...i].join("\n")); } function assertLocalFallbackMatchesGatewayRequest(e, t) { const n = normalizeOptionalString(e.requestId); if (!n) return; const r = (t.pending ?? []).map((e) => normalizeOptionalString(e.requestId)).filter((e) => Boolean(e)); if (!r.includes(n)) throw buildFallbackStateMismatchError(e, r); } //#endregion //#region src/cli/devices-cli.runtime.ts const FALLBACK_NOTICE = "Direct scope access failed; using local fallback."; const DEFAULT_DEVICES_TIMEOUT_MS = 1e4; const OPERATOR_ROLE = "operator"; const OPERATOR_SCOPE_PREFIX = "operator."; const callGatewayCli = async (e, t, n, r) => callGatewayFromCliWithTransport(e, t, n, { label: `Devices ${e}`, defaultTimeoutMs: DEFAULT_DEVICES_TIMEOUT_MS, scopes: r?.scopes, sharedStateMode: "read-only" }); function stringsMatch(e, t) { const n = normalizeOptionalString(e); const r = normalizeOptionalString(t); return Boolean(n && r && n === r); } function pairedDeviceMatchesNodeApprovalQuery(e, t) { return stringsMatch(e.deviceId, t) || stringsMatch(e.remoteIp, t) || stringsMatch(e.pendingNodeSurface?.requestId, t) || stringsMatch(e.pendingNodeSurface?.remoteIp, t); } function buildPendingNodeApprovalNotice(e, t) { const n = e.pendingNodeSurface; const r = normalizeOptionalString(n?.requestId); if (!n || !r) return null; const i = e.nodeSurface ? "reapproval" : "approval"; const a = normalizeOptionalString(e.operatorLabel) ?? normalizeOptionalString(n.displayName) ?? normalizeOptionalString(e.nodeSurface?.displayName) ?? normalizeOptionalString(e.displayName) ?? e.deviceId; const o = formatPairingApproveCommand("nodes", r, { timeout: t.timeout }); const s = formatConnectionFlagReminder(t); const c = [terminalText`Node ${i} pending for ${sanitizeForLog(a)}. Run ${sanitizeForLog(o)}`]; if (s) c.push(s); return c.join("\n"); } function findPairedDevicePendingNodeApprovalNotices(e, t) { return (t ?? []).flatMap((t) => { const n = buildPendingNodeApprovalNotice(t, e); return n ? [n] : []; }); } function isDevicePairingApprovalDenied(e) { return normalizeLowercaseStringOrEmpty(coerceErrorMessage(e)).includes("device pairing approval denied"); } function isUnknownRequestIdError(e) { const t = typeof e === "object" && e !== null ? e : void 0; const n = t?.gatewayCode; if (n !== void 0 && n !== "INVALID_REQUEST") return false; const r = typeof t?.message === "string" ? t.message : coerceErrorMessage(e); return normalizeLowercaseStringOrEmpty(r).includes("unknown requestid"); } function isScopeUpgradePendingApproval(e) { return readConnectPairingRequiredMessage(coerceErrorMessage(e))?.reason === "scope-upgrade"; } function redactLocalPairedDevice(e) { const { tokens: t, ...n } = e; return { ...n, tokens: summarizeDeviceTokens(t) }; } async function listPairingWithFallback(e) { try { return parseDevicePairingList(await callGatewayCli("device.pair.list", e, {}, { scopes: [PAIRING_SCOPE] })); } catch (t) { const n = resolveLocalPairingFallback(e, t); if (!n) throw t; await prepareCliGatewayStateAccess(); const r = await listDevicePairing(); const i = { pending: r.pending, paired: r.paired.map((e) => redactLocalPairedDevice(e)) }; assertLocalFallbackMatchesGatewayRequest(n.details, i); if (e.json !== true) defaultRuntime.log(theme.warn(FALLBACK_NOTICE)); return i; } } async function approvePairingWithFallback(e, t, n) { const { scopes: r, originalRequest: i } = n; try { return await callGatewayCli("device.pair.approve", e, { requestId: t }, r ? { scopes: r } : void 0); } catch (a) { if (isDevicePairingApprovalDenied(a) && !r?.includes("operator.admin")) try { return await callGatewayCli("device.pair.approve", e, { requestId: t }, { scopes: [ADMIN_SCOPE] }); } catch (e) { if (isUnknownRequestIdError(e)) return null; throw e; } const o = resolveLocalPairingFallback(e, a); if (!o) { if (isUnknownRequestIdError(a)) return null; throw a; } return await runWithLocalStateOwner({ method: "device.pair.approve", params: { requestId: t }, target: t, databaseEngine: "configured", onForeignOwner: "refuse", runLocal: async ({ env: r, assertCurrent: s }) => { const c = normalizeOptionalString(o.details.requestId); let l = null; if (c && c !== t) { const e = await listDevicePairing(r.OPENCLAW_STATE_DIR); const a = { pending: e.pending, paired: e.paired.map((e) => redactLocalPairedDevice(e)) }; n.pairingList = a; l = findSameDeviceReplacementRequest({ originalRequest: i, originalRequestId: t, gatewayRequestId: c, pending: a.pending, paired: a.paired }); if (!l) { const e = Boolean(findPendingRequestById(a.pending, t)); const n = Boolean(findPendingRequestById(a.pending, c)); if (!e && !n) return null; throw buildFallbackStateMismatchError(o.details, []); } } const u = l?.requestId ?? t; const d = await approveDevicePairing(u, { callerScopes: ["operator.admin"], isApprovalCurrent: () => { s(); return true; } }, r.OPENCLAW_STATE_DIR); if (!d) { if (!l && c && c === t) throw buildFallbackStateMismatchError(o.details, []); return null; } if (d.status === "forbidden") throw new Error(formatDevicePairingForbiddenMessage(d), { cause: a }); if (e.json !== true) { if (l) defaultRuntime.log(theme.warn(terminalText`Pending request ${sanitizeForLog(t)} was replaced by same-device repair ${sanitizeForLog(l.requestId)}; approving latest compatible request.`)); defaultRuntime.log(theme.warn(FALLBACK_NOTICE)); } return { requestId: u, ...l ? { resolved: { kind: "same-device-replacement", requestedRequestId: t, approvedRequestId: u } } : {}, device: redactLocalPairedDevice(d.device) }; } }); } } function parseDevicePairingList(e) { const t = typeof e === "object" && e !== null ? e : {}; return { pending: Array.isArray(t.pending) ? t.pending : [], paired: Array.isArray(t.paired) ? t.paired : [] }; } function normalizeDeviceRoles(e) { return normalizeUniqueTrimmedStringList([...e.roles ?? [], e.role]); } function normalizeOperatorScopes(e) { return normalizeDeviceAuthScopes(e).filter((e) => e.startsWith(OPERATOR_SCOPE_PREFIX)); } function findPendingRequestById(e, t) { const n = normalizeOptionalString(t); if (!n) return null; return e?.find((e) => normalizeOptionalString(e.requestId) === n) ?? null; } function hasExactRoleMatch(e, t) { const n = normalizeDeviceRoles(e); const r = normalizeDeviceRoles(t); if (n.length !== r.length) return false; const i = new Set(r); return n.every((e) => i.has(e)); } function hasCompatibleClientMetadata(e, t) { return ["clientId", "clientMode"].every((n) => { const r = normalizeOptionalString(e[n]); const i = normalizeOptionalString(t[n]); return !r || !i || r === i; }); } function replacementScopesCoverOriginal(e, t, n) { const r = uniqueStrings([...normalizeDeviceAuthScopes(e.scopes), ...resolvePendingOperatorApprovalScopes(e, n)]); const i = normalizeDeviceAuthScopes(t.scopes); const a = new Set(i); if (!r.every((e) => a.has(e))) return false; return i.every((e) => r.includes(e) || e === "operator.pairing"); } function findSameDeviceReplacementRequest(e) { const t = normalizeOptionalString(e.originalRequestId); if (!e.originalRequest || !t) return null; if (normalizeOptionalString(e.originalRequest.requestId) !== t) return null; const n = findPendingRequestById(e.pending, e.gatewayRequestId); if (!n) return null; if (!stringsMatch(e.originalRequest.deviceId, n.deviceId) || !stringsMatch(e.originalRequest.publicKey, n.publicKey)) return null; if (!hasExactRoleMatch(e.originalRequest, n)) return null; if (!hasCompatibleClientMetadata(e.originalRequest, n)) return null; const r = indexPairedDevices(e.paired); const i = lookupPairedDevice(r, e.originalRequest); const a = lookupPairedDevice(r, n); if (!replacementScopesCoverOriginal(e.originalRequest, n, i)) return null; if (n.isRepair !== true && (!i || !a)) return null; return n; } function resolvePairedOperatorScopes(e) { const t = e?.tokens?.find((e) => { return normalizeOptionalString(e.role) === OPERATOR_ROLE && !e.revokedAtMs; }); return normalizeOperatorScopes(t?.scopes ?? e?.scopes); } function resolvePendingOperatorApprovalScopes(e, t) { if (!normalizeDeviceRoles(e).includes(OPERATOR_ROLE)) return []; const n = normalizeOperatorScopes(e.scopes); return n.length > 0 ? n : resolvePairedOperatorScopes(t); } function resolvePairingCallScopes(e) { if (e.length === 0) return; const t = /* @__PURE__ */ new Set([PAIRING_SCOPE]); for (const n of e) { if (n === "operator.admin" || !isOperatorScope(n)) return [ADMIN_SCOPE]; t.add(n); } return [...t]; } async function resolveTokenManagementScopes(e, t, n) { if (t.role !== OPERATOR_ROLE) return [ADMIN_SCOPE]; const r = parseDevicePairingList(await callGatewayCli("device.pair.list", e, {})).paired.find((e) => e.deviceId === t.deviceId); if (!r) return [ADMIN_SCOPE]; const i = r.tokens?.find((e) => e.role === t.role); return resolvePairingCallScopes(normalizeOperatorScopes(n ?? i?.scopes ?? r.scopes)); } function selectLatestPendingRequest(e) { if (!e?.length) return null; return e.reduce((e, t) => { const n = typeof e.ts === "number" ? e.ts : 0; return (typeof t.ts === "number" ? t.ts : 0) > n ? t : e; }); } function formatTokenSummary(e) { if (!e || e.length === 0) return "none"; return e.map((e) => terminalText`${sanitizeForLog(e.role)}${e.revokedAtMs ? " (revoked)" : ""}`).toSorted((e, t) => e.localeCompare(t)).join(", "); } function formatPendingDeviceIdentity(e) { return terminalText`${sanitizeForLog(normalizeOptionalString(e.displayName) ?? normalizeOptionalString(e.deviceId) ?? "")}`; } function formatAccessSummary(e) { if (!e) return "none"; const t = e.roles.length > 0 ? e.roles.map(sanitizeForLog).join(", ") : "none"; const n = e.scopes.length > 0 ? e.scopes.map(sanitizeForLog).join(", ") : "none"; return terminalText`roles: ${t}; scopes: ${n}`; } const PENDING_APPROVAL_COPY = { "new-pairing": { label: "new pairing", note: "First-time device pairing request." }, "role-upgrade": { label: "role upgrade", note: "Already paired. Requested role exceeds the current approval, so reconnect stays blocked until you approve this upgrade." }, "scope-upgrade": { label: "scope upgrade", note: "Already paired. Requested scopes exceed the current approval, so reconnect stays blocked until you approve this upgrade." }, "re-approval": { label: "re-approval", note: "Already paired. Approval-bound device details changed, so OpenClaw created a fresh request instead of silently reusing the old approval." } }; function indexPairedDevices(e) { const t = /* @__PURE__ */ new Map(); for (const n of e ?? []) { const e = normalizeOptionalString(n.deviceId); if (e) t.set(e, n); } return t; } function lookupPairedDevice(e, t) { const n = normalizeOptionalString(t.deviceId); if (!n) return; const r = e.get(n); if (!r) return; const i = normalizeOptionalString(t.publicKey); const a = normalizeOptionalString(r.publicKey); if (i && a && i !== a) return; return r; } function failDevicesCommand(e, ...t) { if (e) { const e = t.join("\n"); throw new ExpectedCliError({ message: e, humanOutput: e, machineOutput: e }); } for (const e of t) defaultRuntime.error(e); defaultRuntime.exit(1); } async function runDevicesListCommand(e) { let t; try { t = await listPairingWithFallback(e); } catch (t) { if (e.json) { const e = formatGatewayTransportErrorJson(t); if (e) { defaultRuntime.writeJson(e); defaultRuntime.exit(1); return; } } throw t; } const n = indexPairedDevices(t.paired); if (e.json) { defaultRuntime.writeJson(t); return; } if (t.pending.length) { const e = getTerminalTableWidth(); defaultRuntime.log(`${theme.heading("Pending")} ${theme.muted(`(${t.pending.length})`)}`); defaultRuntime.log(renderTerminalSafeTable({ width: e, columns: [ { key: "Request", header: "Request", minWidth: 10 }, { key: "Device", header: "Device", minWidth: 16, flex: true }, { key: "Requested", header: "Requested", minWidth: 20, flex: true }, { key: "Approved", header: "Approved", minWidth: 20, flex: true }, { key: "Age", header: "Age", minWidth: 8 }, { key: "Status", header: "Status", minWidth: 12 } ], rows: t.pending.map((e) => { const t = resolvePendingDeviceApprovalState(e, lookupPairedDevice(n, e)); const r = [PENDING_APPROVAL_COPY[t.kind].label]; if (e.isRepair) r.push("repair"); return { Request: e.requestId, Device: `${formatPendingDeviceIdentity(e)}${e.remoteIp ? terminalText` · ${sanitizeForLog(e.remoteIp)}` : ""}`, Requested: formatAccessSummary(t.requested), Approved: formatAccessSummary(t.approved), Age: typeof e.ts === "number" ? formatTimeAgo(Date.now() - e.ts) : "", Status: r.join(", ") }; }) }).trimEnd()); } if (t.paired.length) { const n = getTerminalTableWidth(); const r = t.paired.map((e) => ({ Device: sanitizeForLog(e.operatorLabel || e.displayName || e.clientId || e.deviceId), "Device ID": sanitizeForLog(e.deviceId), Roles: e.roles?.length ? e.roles.map(sanitizeForLog).join(", ") : "", Scopes: e.scopes?.length ? e.scopes.map(sanitizeForLog).join(", ") : "", Tokens: formatTokenSummary(e.tokens), IP: e.remoteIp ? sanitizeForLog(e.remoteIp) : "" })); defaultRuntime.log(`${theme.heading("Paired")} ${theme.muted(`(${t.paired.length})`)}`); defaultRuntime.log(renderTerminalSafeTable({ width: n, columns: [ { key: "Device", header: "Device", minWidth: 16, flex: true }, { key: "Device ID", header: "Device ID", minWidth: 12, flex: true }, { key: "Roles", header: "Roles", minWidth: 12, flex: true }, { key: "Scopes", header: "Scopes", minWidth: 12, flex: true }, { key: "Tokens", header: "Tokens", minWidth: 12, flex: true }, { key: "IP", header: "IP", minWidth: 12 } ], rows: r }).trimEnd()); defaultRuntime.log(theme.muted("Full device IDs")); for (const e of r) defaultRuntime.log(` ${e["Device ID"]} ${e.Device}`); const i = findPairedDevicePendingNodeApprovalNotices(e, t.paired); for (const e of i) defaultRuntime.log(theme.warn(e)); } if (!t.pending.length && !t.paired.length) defaultRuntime.log(theme.muted("No device pairing entries.")); } async function runDevicesDeleteCommand(e, t, n) { const r = e === "remove" ? t.trim() : normalizeOptionalString(t); const i = e === "remove" ? "deviceId" : "requestId"; if (!r) { failDevicesCommand(n.json, terminalText`${i} is required. Run ${formatCliCommand("openclaw devices list")} to choose a ${e === "remove" ? "paired device" : "pending request"}.`); return; } const a = await callGatewayCli(`device.pair.${e}`, n, { [i]: r }); if (n.json) { defaultRuntime.writeJson(a); return; } const o = e === "remove" ? r : a?.deviceId; defaultRuntime.log(`${theme.warn(e === "remove" ? "Removed" : "Rejected")} ${theme.command(terminalText`${o ?? "ok"}`)}`); } async function runDevicesClearCommand(e) { if (!e.yes) { failDevicesCommand(e.json, "Refusing to clear pairing table without --yes"); return; } const t = parseDevicePairingList(await callGatewayCli("device.pair.list", e, {})); const n = []; const r = []; for (const r of t.paired) { const t = normalizeOptionalString(r.deviceId) ?? ""; if (!t) continue; await callGatewayCli("device.pair.remove", e, { deviceId: t }); n.push(t); } if (e.pending) for (const n of t.pending) { const t = normalizeOptionalString(n.requestId) ?? ""; if (!t) continue; await callGatewayCli("device.pair.reject", e, { requestId: t }); r.push(t); } if (e.json) { defaultRuntime.writeJson({ removedDevices: n, rejectedPending: r }); return; } defaultRuntime.log(`${theme.warn("Cleared")} ${n.length} paired device${n.length === 1 ? "" : "s"}`); if (e.pending) defaultRuntime.log(`${theme.warn("Rejected")} ${r.length} pending request${r.length === 1 ? "" : "s"}`); } async function runDevicesApproveCommand(e, t) { let n = null; let r = e?.trim(); const i = !r || Boolean(t.latest); let a = null; if (i) { n = await listPairingWithFallback(t); a = selectLatestPendingRequest(n.pending); r = a?.requestId?.trim(); } if (!r) { failDevicesCommand(t.json, "No pending device pairing requests to approve"); return; } if (i) { const e = a; const r = resolvePendingDeviceApprovalState(e, lookupPairedDevice(indexPairedDevices(n?.paired), e)); const i = formatPairingApproveCommand("devices", e.requestId, t); const o = []; if (normalizeOptionalString(t.token)) o.push("--token"); if (normalizeOptionalString(t.password)) o.push("--password"); const s = o.length === 0 ? "" : `Reuse the same ${o.join("/")} option${o.length === 1 ? "" : "s"} when rerunning.`; if (t.json) { defaultRuntime.writeJson({ selected: e, approvalState: { kind: r.kind, requested: r.requested, approved: r.approved }, approveCommand: i, requiresAuthFlags: { token: Boolean(normalizeOptionalString(t.token)), password: Boolean(normalizeOptionalString(t.password)) } }); defaultRuntime.exit(1); return; } defaultRuntime.log(`${theme.warn("Selected pending device request")} ${theme.command(terminalText`${e.requestId}`)}`); defaultRuntime.log(` Device: ${formatPendingDeviceIdentity(e)}`); defaultRuntime.log(` Requested: ${formatAccessSummary(r.requested)}`); if (r.approved) defaultRuntime.log(` Approved: ${formatAccessSummary(r.approved)}`); if (e.remoteIp) defaultRuntime.log(terminalText` IP: ${sanitizeForLog(e.remoteIp)}`); defaultRuntime.log(` Note: ${PENDING_APPROVAL_COPY[r.kind].note}`); defaultRuntime.error(terminalText`Approve this exact request with: ${i}`); if (s) defaultRuntime.error(s); defaultRuntime.exit(1); return; } let o; let s; try { const e = await listPairingWithFallback(t); const n = findPendingRequestById(e.pending, r); s = { originalRequest: n, pairingList: e, scopes: n ? resolvePairingCallScopes(resolvePendingOperatorApprovalScopes(n, lookupPairedDevice(indexPairedDevices(e.paired), n))) : void 0 }; } catch { s = { originalRequest: null, pairingList: null, scopes: void 0 }; } try { o = await approvePairingWithFallback(t, r, s); } catch (e) { if (isScopeUpgradePendingApproval(e)) { failDevicesCommand(t.json, "This device can't approve its own scope upgrade. Approve it from the Control UI or another authorized device."); return; } throw e; } if (!o) { const e = terminalText`No pending device request matches ${sanitizeForLog(r)}. Run ${formatCliCommand("openclaw devices list")} and retry with the current request ID.`; const n = findPairedDevicePendingNodeApprovalNotices(t, s.pairingList?.paired.filter((e) => pairedDeviceMatchesNodeApprovalQuery(e, r))); failDevicesCommand(t.json, e, ...n); return; } if (t.json) { defaultRuntime.writeJson(o); return; } const c = o?.requestId; const l = typeof c === "string" && c.trim().length > 0 ? c : r; const u = o?.device?.deviceId; defaultRuntime.log(`${theme.success("Approved")} ${theme.command(terminalText`${u ?? "ok"}`)} ${theme.muted(terminalText`(${l})`)}`); } async function runDevicesRenameCommand(e) { const t = normalizeStringifiedOptionalString(e.device) ?? ""; const n = normalizeStringifiedOptionalString(e.name) ?? ""; if (!t || !n) { failDevicesCommand(e.json, terminalText`--device and --name are required. Run ${formatCliCommand("openclaw devices list")} to choose a paired device.`); return; } const r = await callGatewayCli("device.pair.rename", e, { deviceId: t, label: n }); if (e.json) { defaultRuntime.writeJson(r); return; } defaultRuntime.log(`${theme.success("Renamed")} ${theme.command(terminalText`${t}`)} ${theme.muted("→")} ${terminalText`${sanitizeForLog(n)}`}`); } async function runDevicesTokenCommand(e, t) { const n = normalizeStringifiedOptionalString(t.device) ?? ""; const r = normalizeStringifiedOptionalString(t.role) ?? ""; if (!n || !r) { failDevicesCommand(true, `--device and --role are required. Run ${formatCliCommand("openclaw devices list")} to choose a paired device.`); return; } const i = { deviceId: n, role: r }; const a = e === "rotate" ? t.scopes === false ? [] : t.scope : void 0; const o = e === "rotate" ? { ...i, scopes: a } : i; const s = await resolveTokenManagementScopes(t, i, a); const c = await callGatewayCli(`device.token.${e}`, t, o, { scopes: s }); defaultRuntime.writeJson(c); } //#endregion export { runDevicesApproveCommand, runDevicesClearCommand, runDevicesDeleteCommand, runDevicesListCommand, runDevicesRenameCommand, runDevicesTokenCommand };