UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

231 lines (230 loc) • 9.35 kB
import { t as hasNonEmptyString } from "../string-coerce-CCIiB4H7.mjs"; import { A as resolveExpiresAtMsFromDurationMs, o as asDateTimestampMs } from "../number-coercion-D6u-4YD8.mjs"; import { o as resolveAgentEntry } from "../agent-scope-config-DmXgFGKP.mjs"; import { u as resolveExecModePolicy } from "../exec-approvals-core-puBAw1bE.mjs"; import { d as replaceCorePluginStateEntry, t as createCorePluginStateKeyedStore } from "../plugin-state-store-C2xZ8cMl.mjs"; import "../exec-approvals-rOfoWejC.mjs"; import { a as isPersistentSystemAgentOperation, i as formatSystemAgentPersistentPlan, o as parseSystemAgentOperation } from "../operations-parse-DoFrSk0v.mjs"; import { t as listAgentRoles } from "../agent-roles-BJUCg-FF.mjs"; import { n as SystemAgentOperationExitError } from "../operations-execution-helpers-cXxYzJCh.mjs"; import { t as executeSystemAgentOperation } from "../operations-CBf52_6Y.mjs"; import { r as classifySystemAgentApprovalText } from "../operator-approval-DrWu-F-I.mjs"; import { createHash } from "node:crypto"; //#region src/system-agent/rescue-message.ts const SYSTEM_AGENT_COMMAND = "/openclaw"; const RESCUE_PENDING_NAMESPACE = "rescue-pending"; const RESCUE_PENDING_MAX_ENTRIES = 1024; const RESCUE_PENDING_TTL_MS = 9e5; const RESCUE_OPERATION_FIELDS = /* @__PURE__ */ new Map([ ["set-default-model", { required: ["model"], optional: ["agentId"] }], ["config-set", { required: ["path", "value"] }], ["config-set-ref", { required: [ "path", "source", "id" ], optional: ["provider"] }], ["setup", { optional: ["workspace", "model"] }], ["plugin-install", { required: ["spec"] }], ["create-agent", { required: ["agentId"], optional: [ "name", "purpose", "workspace", "model", "role" ] }], ["create-team", { optional: [ "coordinatorId", "prefix", "workspaceRoot" ] }], ["gateway-start", {}], ["gateway-stop", {}], ["gateway-restart", {}] ]); function createCaptureRuntime() { const e = []; const push = (...t) => { e.push(t.map((e) => typeof e === "string" ? e : JSON.stringify(e)).join(" ")); }; return { runtime: { log: push, error: push, exit: (e) => { throw new SystemAgentOperationExitError(e); } }, read: () => e.join("\n").trim() }; } /** Run one operation and reply with its output; a non-zero exit is part of that reply. */ async function runCapturedOperation(e, t, n) { const r = createCaptureRuntime(); try { await executeSystemAgentOperation(e, r.runtime, t); } catch (e) { if (!(e instanceof SystemAgentOperationExitError)) throw e; return [r.read(), `OpenClaw operation exited with code ${e.code ?? 1}.`].filter(Boolean).join("\n\n"); } return r.read() || n; } /** Extract the command body after `/openclaw`, or null when the message is not for rescue. */ function extractSystemAgentRescueMessage(e) { const t = e.trim(); const n = t.toLowerCase(); if (n !== SYSTEM_AGENT_COMMAND && !n.startsWith(`${SYSTEM_AGENT_COMMAND} `)) return null; return t.slice(9).trim(); } function resolvePendingKey(e) { const t = JSON.stringify({ accountId: resolveAccountDiscriminator(e.command), channel: e.command.channelId ?? e.command.channel, from: e.command.from, senderId: e.command.senderId }); return createHash("sha256").update(t).digest("hex").slice(0, 32); } function resolveAccountDiscriminator(e) { return e.accountId?.trim() || e.to?.trim() || "default"; } function isPlainRecord(e) { return e !== null && typeof e === "object" && !Array.isArray(e) && Object.getPrototypeOf(e) === Object.prototype; } function hasOperationFields(e, t = [], n = []) { const r = /* @__PURE__ */ new Set([ "kind", ...t, ...n ]); return Object.hasOwn(e, "kind") && t.every((t) => Object.hasOwn(e, t) && hasNonEmptyString(e[t])) && n.every((t) => t === "role" ? e.role === void 0 || listAgentRoles().some((t) => t === e.role) : !Object.hasOwn(e, t) || hasNonEmptyString(e[t])) && Object.keys(e).every((e) => r.has(e)); } function parsePendingOperation(e) { if (!isPlainRecord(e) || e.version !== 1 || !isPlainRecord(e.operation)) return null; const t = e.operation; if (typeof t.kind !== "string") return null; const n = RESCUE_OPERATION_FIELDS.get(t.kind); if (!n || !hasOperationFields(t, n.required, n.optional)) return null; if (t.kind === "config-set-ref" && t.source !== "env" && t.source !== "file" && t.source !== "exec" && t.source !== "store") return null; return isPersistentSystemAgentOperation(t) ? t : null; } function buildAuditDetails(e) { return { rescue: true, channel: e.command.channelId ?? e.command.channel, accountId: resolveAccountDiscriminator(e.command), senderId: e.command.senderId, from: e.command.from }; } function formatUnsupportedRemoteOperation(e) { if (e.kind === "open-tui") return ["OpenClaw rescue cannot open the local TUI from a message channel.", "Use local `openclaw` for agent handoff, or ask for status, doctor, config, gateway, agents, or models."].join(" "); if (e.kind === "channel-setup") return ["OpenClaw rescue cannot host the interactive channel setup from a message channel.", "Run `openclaw setup` locally and say `connect " + e.channel + "` instead."].join(" "); if (e.kind === "config-unset") return ["OpenClaw rescue cannot remove configuration settings.", "Ask your regular agent to remove the setting, or run `openclaw config unset <path>` locally."].join(" "); if (e.kind === "doctor-fix") return ["OpenClaw rescue cannot run doctor repairs from a message channel because they can change the inference route powering this session.", "On the machine running OpenClaw, with OpenClaw stopped, run `openclaw doctor --fix`."].join(" "); if (e.kind === "plugin-install") return ["OpenClaw rescue cannot install plugins from a message channel by default because plugin install downloads executable code.", "Use local `openclaw setup` or `openclaw plugins install` instead."].join(" "); return null; } /** Process one rescue message and return a reply, or null when not a rescue command. */ async function runSystemAgentRescueMessage(e) { const t = extractSystemAgentRescueMessage(e.commandBody); if (t === null) return null; const n = e.cfg; const r = e.agentId; const i = e.command.senderIsOwner; const a = !e.isGroup; const o = r ? resolveAgentEntry(n, r) : void 0; if ((o?.sandbox?.mode ?? n.agents?.defaults?.sandbox?.mode ?? "off") !== "off") return "OpenClaw rescue is blocked because OpenClaw sandboxing is active. Fix the install locally or disable sandboxing before using remote rescue."; const s = n.tools?.exec; const c = resolveExecModePolicy({ mode: s?.mode, security: s?.security ?? "full", ask: s?.ask ?? "off" }); const l = o?.tools?.exec; if (resolveExecModePolicy({ mode: l?.mode, security: l?.security ?? c.security, ask: l?.ask ?? c.ask }).mode !== "full") return "OpenClaw rescue requires YOLO host posture with sandboxing off."; if (!i) return "OpenClaw rescue only accepts commands from an OpenClaw owner."; if (!a) return "OpenClaw rescue is restricted to owner DMs by default."; const u = e.command.assertOwnerCurrent; const d = e.assertCurrent; const assertCurrent = () => { u?.(); d?.(); }; const f = e.env; const p = { ownerId: "core:system-agent", namespace: RESCUE_PENDING_NAMESPACE, maxEntries: RESCUE_PENDING_MAX_ENTRIES, overflowPolicy: "reject-new", ...f ? { env: f } : {} }; const m = createCorePluginStateKeyedStore(p).withCurrent({ assertCurrent }); const h = resolvePendingKey(e); const g = classifySystemAgentApprovalText(t); if (g === "approve") { const t = parsePendingOperation(await m.consume(h)); assertCurrent(); if (!t) return "No pending OpenClaw rescue change is waiting for approval."; const n = formatUnsupportedRemoteOperation(t); if (n) return n; return await runCapturedOperation(t, { approved: true, auditDetails: buildAuditDetails(e), deps: e.deps, beforePersistentApply: assertCurrent }, "OpenClaw rescue change applied."); } if (g === "decline") { const e = parsePendingOperation(await m.consume(h)); assertCurrent(); return e ? "Dropped the pending OpenClaw rescue change." : "No pending OpenClaw rescue change is waiting for approval."; } const _ = parseSystemAgentOperation(t); const v = formatUnsupportedRemoteOperation(_); if (v) { await m.delete(h); assertCurrent(); return v; } if (isPersistentSystemAgentOperation(_)) { const e = asDateTimestampMs((/* @__PURE__ */ new Date()).getTime()); const t = e === void 0 ? void 0 : resolveExpiresAtMsFromDurationMs(RESCUE_PENDING_TTL_MS, { nowMs: e }); if (e === void 0 || t === void 0) { await m.delete(h); assertCurrent(); return "OpenClaw rescue could not create a pending approval because the expiry clock is invalid."; } const n = t - e; await replaceCorePluginStateEntry(p, h, { version: 1, operation: _ }, { ttlMs: n, assertCurrent }); assertCurrent(); return formatSystemAgentPersistentPlan(_).replace("Say yes to apply.", "Reply /openclaw yes to apply."); } await m.delete(h); assertCurrent(); return await runCapturedOperation(_, { approved: true, auditDetails: buildAuditDetails(e), deps: e.deps }, "OpenClaw listened, clicked a claw, and found nothing to change."); } //#endregion export { extractSystemAgentRescueMessage, runSystemAgentRescueMessage };