openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
1,109 lines (1,108 loc) • 38.2 kB
JavaScript
import { l as normalizeOptionalString } from "./string-coerce-CCIiB4H7.mjs";
import { D as parseStrictPositiveInteger } from "./number-coercion-D6u-4YD8.mjs";
import { l as isRecord } from "./record-coerce-CVPuDqcc.mjs";
import "./src-H3RMXyFL.mjs";
import { t as expectDefined } from "./expect-DDakjvvQ.mjs";
import { r as truncateUtf16Safe } from "./utf16-slice-CuDyEXgS.mjs";
import { r as defaultRuntime } from "./runtime-B-SLYP-m.mjs";
import { s as readFileDescriptorBounded } from "./boundary-file-read-BfaFLDqt.mjs";
import { n as sanitizeForLog } from "./ansi-CZa2t0Hf.mjs";
import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs";
import { h as resolveConfiguredAgentId } from "./agent-scope-config-DmXgFGKP.mjs";
import { r as captureOpenClawStateWorkerContext } from "./openclaw-state-worker-context-DAKL_dnZ.mjs";
import { l as parsePersistedExecApprovals, s as normalizeExecApprovalsInternal } from "./exec-approvals-config-BBzEUJlE.mjs";
import { r as decodeUtf8Input } from "./utf8-input-BHczGT8v.mjs";
import { Fi as validateExecApprovalsNativeRequest } from "./src-BX8OAe1J.mjs";
import { n as classifyExecAllowlistScope } from "./exec-command-resolution-DaBYjPqy.mjs";
import { n as APPROVALS_SCOPE, t as ADMIN_SCOPE } from "./operator-scopes-CULmYfyY.mjs";
import { a as readBestEffortConfig } from "./io.runtime-DsJ2dLCQ.mjs";
import "./method-scopes-Dpyb0Ck-.mjs";
import { n as isWellFormedApprovalId } from "./approval-id-CfM0pBs_.mjs";
import { t as GATEWAY_SERVER_CAPS } from "./server-capabilities-BDosLJeN.mjs";
import "./config-CMA-J084.mjs";
import { n as isRich, r as theme } from "./theme-BOI0xyRZ.mjs";
import { r as readExecApprovalsSocket } from "./exec-approvals-socket-DEOHtzox.mjs";
import { d as updateExecApprovals, l as readExecApprovalsSnapshotAsync } from "./exec-approvals-store-BUZ9uOWF.mjs";
import { t as redactExecApprovals } from "./exec-approvals-rOfoWejC.mjs";
import { d as throwExpectedCliError, u as rethrowExpectedCliError } from "./failure-output-DVVDqwuu.mjs";
import { n as callGatewayFromCli } from "./gateway-rpc-CxUN2f1a.mjs";
import { t as runWithLocalStateOwner } from "./local-state-owner-DTl7OHpC.mjs";
import { t as readByteStreamWithLimit } from "./read-byte-stream-with-limit-BjmaH2Xs.mjs";
import { n as formatTimeAgo } from "./format-relative-JG-kbkDF.mjs";
import { r as renderTerminalSafeTable, t as getTerminalTableWidth } from "./table-D2a-pD4_.mjs";
import { n as formatHelpExamples, t as formatDocsHelp } from "./help-format-D2ytHW5E.mjs";
import { a as nodesCallOpts, u as resolveCliNodeId } from "./rpc-BLWTBJRk.mjs";
import { t as parseOptionalPositiveInteger } from "./parse-positive-integer-DrSNo4LV.mjs";
import { t as applyParentDefaultHelpAction } from "./parent-default-help-BZo1QRJR.mjs";
import { n as collectExecPolicyScopeSnapshots, t as SESSION_EXEC_OVERRIDES_NOTE } from "./exec-approvals-effective-e7qqZqNV.mjs";
import { t as commitNativeExecAuthorization } from "./exec-approvals-native-Bb9hLtyx.mjs";
import fs from "node:fs/promises";
import JSON5 from "json5";
//#region src/cli/exec-approvals-cli.shared.ts
const EXEC_APPROVALS_STDIN_MAX_BYTES = 1048576;
async function readStdin() {
const e = await readByteStreamWithLimit(process.stdin, {
maxBytes: EXEC_APPROVALS_STDIN_MAX_BYTES,
onOverflow: ({ maxBytes: e }) => /* @__PURE__ */ new Error(`Exec approvals stdin exceeds ${e} bytes.`)
});
return decodeUtf8Input(e, "Exec approvals stdin");
}
function formatCliError(e) {
const t = formatErrorMessage(e);
const n = t.includes("\n") ? t.split("\n")[0] : t;
const r = sanitizeForLog(expectDefined(n, "exec approvals cli first line"));
return r.length > 300 ? `${truncateUtf16Safe(r, 300)}...` : r;
}
function failApprovalsCommand(e, t) {
rethrowExpectedCliError(e);
const n = formatCliError(e);
if (t.json) throw new Error(n);
defaultRuntime.error(n);
defaultRuntime.exit(1);
}
async function runApprovalsAction(e, t) {
try {
await t();
} catch (t) {
failApprovalsCommand(t, e);
}
}
//#endregion
//#region src/cli/exec-approvals-local.ts
function loadSnapshotLocal() {
return runWithLocalStateOwner({
method: "exec.approvals.get",
params: {},
target: "default exec approvals",
databaseEngine: "configured",
requiredCapabilities: [GATEWAY_SERVER_CAPS.EXEC_APPROVALS_GET_OWNER],
recoveryCommand: "openclaw approvals get --json",
runLocal: async ({ env: e, assertCurrent: t }) => {
t();
const n = await readExecApprovalsSnapshotAsync();
t();
const r = await readExecApprovalsSocket(e, { assertCurrent: t });
t();
return redactExecApprovals({
...n,
file: r?.socket_path ? {
...n.file,
socket: {
...n.file.socket,
path: r.socket_path
}
} : n.file
});
}
});
}
function saveSnapshotLocal(e, t) {
const n = normalizeExecApprovalsInternal(e);
return runWithLocalStateOwner({
method: "exec.approvals.set",
params: {
file: n,
baseHash: t
},
target: "default exec approvals",
databaseEngine: "configured",
requiredCapabilities: [GATEWAY_SERVER_CAPS.EXEC_APPROVALS_SET_OWNER],
recoveryCommand: "openclaw approvals get --json",
runLocal: async ({ assertCurrent: e }) => {
e();
const r = captureOpenClawStateWorkerContext();
const i = await updateExecApprovals({
baseHash: t,
assertCurrent: e,
update: {
kind: "replace",
file: n,
preserveSocket: true
}
}, r);
if (!i) throw new Error("Exec approvals changed; reload and retry.");
return redactExecApprovals(i);
}
});
}
function commitNativeExecLocal(e) {
return runWithLocalStateOwner({
method: "exec.approvals.native.commit",
params: e,
target: "native exec authorization",
databaseEngine: "configured",
requiredCapabilities: [GATEWAY_SERVER_CAPS.EXEC_APPROVALS_NATIVE_COMMIT],
recoveryCommand: "openclaw approvals get --json",
runLocal: async ({ assertCurrent: t }) => {
t();
return commitNativeExecAuthorization(e, t, captureOpenClawStateWorkerContext());
}
});
}
//#endregion
//#region src/cli/exec-approvals-native-cli.ts
function registerNativeExecApprovalsCli(e) {
e.command("native", { hidden: true }).description("Internal native approval owner transport").requiredOption("--stdin", "Read one bounded native owner operation as JSON").option("--json", "Keep the native result on stdout and diagnostics on stderr", true).action(async () => {
try {
const e = JSON.parse(await readStdin());
if (!validateExecApprovalsNativeRequest(e)) throw new Error("Invalid native exec approval owner request.");
let t;
if (e.operation === "get") t = await loadSnapshotLocal();
else if (e.operation === "set") {
const n = parsePersistedExecApprovals(JSON.stringify(e.file));
if (!n.ok) throw new Error(`Invalid native exec approval policy: ${n.error}`);
t = await saveSnapshotLocal(n.value, e.baseHash);
} else {
const { operation: n, ...r } = e;
t = await commitNativeExecLocal(r);
}
defaultRuntime.writeJson(t, 0);
} catch (e) {
rethrowExpectedCliError(e);
throwExpectedCliError(formatCliError(e));
}
});
}
//#endregion
//#region src/cli/exec-approvals-cli.ts
const APPROVALS_GET_DEFAULT_TIMEOUT_MS = 6e4;
const APPROVAL_DECISIONS = [
"allow-once",
"allow-always",
"deny"
];
const PENDING_APPROVAL_SUMMARY_MAX_LENGTH = 96;
const APPROVAL_ID_TOKEN_PREFIX = "id64_";
const APPROVAL_TERMINAL_UNSAFE_CHAR = /^[\p{Cc}\p{Cf}\p{Cs}\p{Zl}\p{Zp}\u00A0\u1680\u2000-\u200A\u202F\u205F\u3000\u115F\u1160\u3164\uFFA0]$/u;
async function readApprovalsFile(e) {
const t = await fs.open(e, "r");
try {
const e = await readFileDescriptorBounded(t.fd, EXEC_APPROVALS_STDIN_MAX_BYTES);
return decodeUtf8Input(e, "Exec approvals file");
} finally {
await t.close();
}
}
async function resolveTargetNodeId(e) {
const t = normalizeOptionalString(e.node) ?? "";
if (e.gateway && t) throw new Error("Pass only one of --gateway or --node.");
if (e.gateway) return null;
if (!t) return null;
return await resolveCliNodeId(e, t);
}
async function loadSnapshot(e, t) {
return await callGatewayFromCli(t ? "exec.approvals.node.get" : "exec.approvals.get", e, t ? { nodeId: t } : {});
}
function isFileApprovalsSnapshot(e) {
return "file" in e;
}
function isNativeApprovalsSnapshot(e) {
return "enabled" in e;
}
function parseNativeAction(e, t) {
if (e === "allow" || e === "deny" || e === "prompt") return e;
throw new Error(`${t} must be allow, deny, or prompt.`);
}
async function loadSnapshotTarget(e) {
if (!e.gateway && !e.node) return {
snapshot: await loadSnapshotLocal(),
nodeId: null,
source: "local"
};
const t = await resolveTargetNodeId(e);
return {
snapshot: await loadSnapshot(e, t),
nodeId: t,
source: t ? "node" : "gateway"
};
}
function requireTrimmedNonEmpty(e, t) {
const n = e.trim();
if (!n) throw new Error(t);
return n;
}
async function loadWritableSnapshotTarget(e) {
const { snapshot: t, nodeId: n, source: r } = await loadSnapshotTarget(e);
const i = r === "local" ? "local" : n ? `node:${n}` : "gateway";
if (isNativeApprovalsSnapshot(t) && !t.enabled) throw new Error("Host-native exec approvals are disabled on this node and cannot be configured remotely.");
const a = "hash" in t ? t.hash : void 0;
if (!a) throw new Error("Exec approvals hash missing; reload and retry.");
return {
snapshot: t,
nodeId: n,
source: r,
targetLabel: i,
baseHash: a
};
}
async function saveSnapshotTargeted(e) {
let t;
if ("native" in e) {
if (e.source !== "node" || !e.nodeId) throw new Error("Host-native exec approvals can only target a node.");
await callGatewayFromCli("exec.approvals.node.set", e.opts, {
nodeId: e.nodeId,
native: e.native,
baseHash: e.baseHash
});
t = await loadSnapshot(e.opts, e.nodeId);
} else if (e.source === "local") {
if (!e.opts.json) defaultRuntime.log(theme.muted("Writing approvals for this state root."));
t = await saveSnapshotLocal(e.file, e.baseHash);
} else {
const { opts: n, nodeId: r, file: i, baseHash: a } = e;
t = await callGatewayFromCli(r ? "exec.approvals.node.set" : "exec.approvals.set", n, r ? {
nodeId: r,
file: i,
baseHash: a
} : {
file: i,
baseHash: a
});
}
if (e.opts.json) {
defaultRuntime.writeJson(isFileApprovalsSnapshot(t) ? redactExecApprovals(t) : t, 0);
return;
}
defaultRuntime.log(theme.muted(`Target: ${e.targetLabel}`));
renderApprovalsSnapshot(t, e.targetLabel);
}
function isApprovalDecision(e) {
return APPROVAL_DECISIONS.includes(e);
}
function shortenPendingApprovalSummary(e) {
if (e.length <= PENDING_APPROVAL_SUMMARY_MAX_LENGTH) return e;
return `${truncateUtf16Safe(e, 93)}...`;
}
function escapeApprovalTextForTerminal(e) {
let t = "";
for (const n of e) {
if (n === "\\") {
t += "\\\\";
continue;
}
if (APPROVAL_TERMINAL_UNSAFE_CHAR.test(n)) {
t += `\\u{${n.codePointAt(0)?.toString(16).toUpperCase() ?? "FFFD"}}`;
continue;
}
t += n;
}
return t;
}
const APPROVAL_ID_TERMINAL_SAFE_RE = /^[A-Za-z0-9._:][A-Za-z0-9._:-]{0,127}$/;
function formatApprovalIdForTerminal(e) {
if (APPROVAL_ID_TERMINAL_SAFE_RE.test(e)) return e;
return `${APPROVAL_ID_TOKEN_PREFIX}${Buffer.from(e, "utf16le").toString("base64url")}`;
}
function decodeDisplayedApprovalId(e) {
if (!e.startsWith(APPROVAL_ID_TOKEN_PREFIX)) return null;
const t = e.slice(5);
if (!t || !/^[a-zA-Z0-9_-]+$/.test(t)) return null;
const n = Buffer.from(t, "base64url").toString("utf16le");
return Buffer.from(n, "utf16le").toString("base64url") === t ? n : null;
}
function readPendingApprovalEntry(e, t) {
if (!isRecord(e) || !isRecord(e.request)) return null;
const n = typeof e.id === "string" && isWellFormedApprovalId(e.id) ? e.id : null;
const r = e.createdAtMs;
const i = e.expiresAtMs;
if (!n || typeof r !== "number" || !Number.isFinite(r) || typeof i !== "number" || !Number.isFinite(i)) return null;
const a = e.request;
const o = normalizeOptionalString(a.agentId) ?? null;
const s = normalizeOptionalString(a.sessionKey) ?? null;
const c = typeof a.command === "string" && a.command ? a.command : null;
const l = typeof a.title === "string" && a.title ? a.title : null;
const u = typeof a.description === "string" && a.description ? a.description : null;
const d = l && u ? `${l}: ${u}` : l ?? u;
return {
id: n,
kind: t,
agentId: o,
sessionKey: s,
createdAtMs: r,
expiresAtMs: i,
summary: (t === "exec" ? c : t === "plugin" && c ? `${d ? `${d} — ` : ""}Command: ${c}` : d) ?? "(summary unavailable)"
};
}
function readPendingApprovalList(e, t) {
if (!Array.isArray(e)) throw new Error(`Invalid ${t} approval list response.`);
return e.flatMap((e) => {
const n = readPendingApprovalEntry(e, t);
return n ? [n] : [];
});
}
async function loadPendingApprovals(e) {
const listCall = (t) => callGatewayFromCli(t, e, {}, { scopes: [ADMIN_SCOPE] });
const [t, n, r] = await Promise.all([
listCall("exec.approval.list"),
listCall("plugin.approval.list"),
listCall("openclaw.approval.list")
]);
return [
...readPendingApprovalList(t, "exec"),
...readPendingApprovalList(n, "plugin"),
...readPendingApprovalList(r, "system-agent")
].toSorted((e, t) => t.createdAtMs - e.createdAtMs);
}
function describeGrantState(e, t) {
if (e.revokedAtMs !== null) return `revoked${e.revokedBy ? ` by ${escapeApprovalTextForTerminal(e.revokedBy)}` : ""}`;
if (e.expiresAtMs !== null && e.expiresAtMs <= t) return "expired";
if (e.expiresAtMs !== null) return `expires in ${Math.max(1, Math.ceil((e.expiresAtMs - t) / 864e5))}d`;
return "until revoked";
}
function formatResolver(e) {
const t = e.resolver;
if (!t) return "unknown resolver";
return t.id ? `${t.kind}:${escapeApprovalTextForTerminal(t.id)}` : t.kind;
}
async function loadConfigForApprovalsTarget(e) {
try {
if (e.source === "local") return {
config: await readBestEffortConfig(),
timedOut: false
};
const t = await callGatewayFromCli("config.get", e.opts, {});
return {
config: t.config && typeof t.config === "object" ? t.config : null,
timedOut: false
};
} catch (e) {
return {
config: null,
timedOut: /^gateway timeout after \d+ms\b/i.test(formatCliError(e))
};
}
}
function renderApprovalsSummary(e, t) {
defaultRuntime.log(isRich() ? theme.heading("Approvals") : "Approvals");
defaultRuntime.log(renderTerminalSafeTable({
width: t,
columns: [{
key: "Field",
header: "Field",
minWidth: 8
}, {
key: "Value",
header: "Value",
minWidth: 24,
flex: true
}],
rows: e
}).trimEnd());
}
function renderApprovalsSnapshot(e, t) {
if (isNativeApprovalsSnapshot(e)) {
const n = isRich();
const nativeHeading = (e) => n ? theme.heading(e) : e;
const nativeMuted = (e) => n ? theme.muted(e) : e;
const r = e.enabled ? e.rules : [];
renderApprovalsSummary([
{
Field: "Target",
Value: t
},
{
Field: "Kind",
Value: "host-native"
},
{
Field: "Enabled",
Value: e.enabled ? "yes" : "no"
},
{
Field: "Hash",
Value: e.enabled ? e.hash : "unavailable"
},
{
Field: "Default",
Value: e.enabled ? e.defaultAction : e.message ?? "unavailable"
},
{
Field: "Rules",
Value: String(r.length)
}
], getTerminalTableWidth());
if (r.length === 0) {
defaultRuntime.log("");
defaultRuntime.log(nativeMuted("No host-native rules."));
return;
}
defaultRuntime.log("");
defaultRuntime.log(nativeHeading("Rules"));
defaultRuntime.log(renderTerminalSafeTable({
width: getTerminalTableWidth(),
columns: [
{
key: "Pattern",
header: "Pattern",
minWidth: 20,
flex: true
},
{
key: "Action",
header: "Action",
minWidth: 8
},
{
key: "Shells",
header: "Shells",
minWidth: 10,
flex: true
},
{
key: "Enabled",
header: "Enabled",
minWidth: 7
}
],
rows: r.map((e) => ({
Pattern: e.pattern,
Action: e.action,
Shells: e.shells?.join(", ") || "all",
Enabled: e.enabled === false ? "no" : "yes"
}))
}).trimEnd());
return;
}
const n = isRich();
const heading = (e) => n ? theme.heading(e) : e;
const muted = (e) => n ? theme.muted(e) : e;
const r = getTerminalTableWidth();
const i = e.file ?? { version: 1 };
const a = i.defaults ?? {};
const o = [
a.security ? `security=${a.security}` : null,
a.ask ? `ask=${a.ask}` : null,
a.askFallback ? `askFallback=${a.askFallback}` : null,
typeof a.autoAllowSkills === "boolean" ? `autoAllowSkills=${a.autoAllowSkills ? "on" : "off"}` : null
].filter((e) => e != null);
const s = i.agents ?? {};
const c = [];
const l = Date.now();
for (const [e, n] of Object.entries(s)) {
const r = Array.isArray(n.allowlist) ? n.allowlist : [];
for (const n of r) {
const r = normalizeOptionalString(n?.pattern) ?? "";
if (!r) continue;
const i = typeof n.lastUsedAt === "number" ? n.lastUsedAt : null;
c.push({
Target: t,
Agent: e,
Pattern: r,
Scope: classifyExecAllowlistScope(n),
LastUsed: i ? formatTimeAgo(Math.max(0, l - i)) : muted("unknown")
});
}
}
const u = Object.entries(s).flatMap(([e, t]) => (t.mcpTools ?? []).map((t) => ({
Agent: e,
Server: t.server,
Tool: t.tool,
Added: formatTimeAgo(Math.max(0, l - t.addedAt))
})));
renderApprovalsSummary([
{
Field: "Target",
Value: t
},
{
Field: "Path",
Value: e.path
},
{
Field: "State",
Value: e.exists ? "stored" : "defaults (no stored overrides)"
},
{
Field: "Hash",
Value: e.hash
},
{
Field: "Version",
Value: String(i.version ?? 1)
},
{
Field: "Socket",
Value: i.socket?.path ?? "default"
},
{
Field: "Defaults",
Value: o.length > 0 ? o.join(", ") : "none"
},
{
Field: "Agents",
Value: String(Object.keys(s).length)
},
{
Field: "Allowlist",
Value: String(c.length)
},
{
Field: "MCP tool grants",
Value: String(u.length)
}
], r);
defaultRuntime.log("");
if (c.length > 0) {
defaultRuntime.log(heading("Allowlist"));
defaultRuntime.log(renderTerminalSafeTable({
width: r,
columns: [
{
key: "Target",
header: "Target",
minWidth: 10
},
{
key: "Agent",
header: "Agent",
minWidth: 8
},
{
key: "Pattern",
header: "Pattern",
minWidth: 20,
flex: true
},
{
key: "Scope",
header: "Scope",
minWidth: 10
},
{
key: "LastUsed",
header: "Last Used",
minWidth: 10
}
],
rows: c
}).trimEnd());
} else defaultRuntime.log(muted("No allowlist entries."));
if (u.length === 0) return;
defaultRuntime.log("");
defaultRuntime.log(heading("MCP tool grants"));
defaultRuntime.log(renderTerminalSafeTable({
width: r,
columns: [
{
key: "Agent",
header: "Agent",
minWidth: 8
},
{
key: "Server",
header: "Server",
minWidth: 16,
flex: true
},
{
key: "Tool",
header: "Tool",
minWidth: 16,
flex: true
},
{
key: "Added",
header: "Added",
minWidth: 10
}
],
rows: u
}).trimEnd());
}
function resolveAgentKey(e) {
return e == null ? "*" : requireTrimmedNonEmpty(e, "--agent must not be blank");
}
async function loadWritableAllowlistAgent(e) {
const t = resolveAgentKey(e.agent);
if (t !== "*") {
const { config: n } = await loadConfigForApprovalsTarget({
opts: e,
source: !e.gateway && !e.node ? "local" : e.gateway ? "gateway" : "node"
});
if (!n) throw new Error("Config unavailable; cannot validate --agent.");
resolveConfiguredAgentId(n, t);
}
const n = await loadWritableSnapshotTarget(e);
const { snapshot: r } = n;
if (isNativeApprovalsSnapshot(r) || !isFileApprovalsSnapshot(r)) throw new Error("Host-native node approvals do not support allowlist mutations; use approvals set --node with host-native JSON.");
const i = structuredClone(r.file);
i.version = 1;
const a = i.agents?.[t] ?? {};
const o = Array.isArray(a.allowlist) ? a.allowlist : [];
return {
...n,
snapshot: r,
file: i,
agentKey: t,
agent: a,
allowlistEntries: o
};
}
function registerAllowlistMutationCommand(e) {
const t = e.allowlist.command(`${e.name} <pattern>`).description(e.description).option("--node <node>", "Target node id/name/IP").option("--gateway", "Force gateway approvals", false).option("--agent <id>", "Agent id (defaults to \"*\")").action(async (t, n) => {
await runApprovalsAction(n, async () => {
const r = requireTrimmedNonEmpty(t, "Pattern required.");
const i = await loadWritableAllowlistAgent(n);
if (!e.mutate({
...i,
trimmedPattern: r
})) {
if (n.json) defaultRuntime.writeJson(redactExecApprovals(i.snapshot), 0);
return;
}
await saveSnapshotTargeted({
...i,
opts: n
});
});
});
nodesCallOpts(t);
}
function registerExecApprovalsCli(e) {
const t = e.command("approvals").alias("exec-approvals").description("Manage approval policy and pending requests").addHelpText("after", () => formatDocsHelp("/cli/approvals"));
registerNativeExecApprovalsCli(t);
const n = t.command("pending").description("List pending exec, plugin, and system-agent approvals").action(async (e) => {
await runApprovalsAction(e, async () => {
const t = await loadPendingApprovals(e);
if (e.json) {
defaultRuntime.writeJson({ approvals: t }, 0);
return;
}
if (t.length === 0) {
defaultRuntime.log(theme.muted("No pending approvals."));
return;
}
const n = Date.now();
defaultRuntime.log(`${theme.heading("Pending approvals")} ${theme.muted(`(${t.length})`)}`);
defaultRuntime.log(renderTerminalSafeTable({
width: getTerminalTableWidth(),
columns: [
{
key: "ID",
header: "ID",
minWidth: 16,
flex: true
},
{
key: "Kind",
header: "Kind",
minWidth: 12
},
{
key: "AgentSession",
header: "Agent / Session",
minWidth: 16,
flex: true
},
{
key: "Requested",
header: "Requested",
minWidth: 12
},
{
key: "Expires",
header: "Expires In",
minWidth: 10
},
{
key: "Summary",
header: "Command / Summary",
minWidth: 20,
flex: true
}
],
rows: t.map((e) => {
const t = escapeApprovalTextForTerminal(e.summary);
const r = formatApprovalIdForTerminal(e.id);
const i = [e.agentId, e.sessionKey].filter((e) => Boolean(e));
return {
ID: r,
Kind: e.kind,
AgentSession: i.length > 0 ? escapeApprovalTextForTerminal(i.join(" / ")) : "-",
Requested: formatTimeAgo(Math.max(0, n - e.createdAtMs)),
Expires: formatTimeAgo(Math.max(0, e.expiresAtMs - n), { suffix: false }),
Summary: shortenPendingApprovalSummary(t)
};
})
}).trimEnd());
defaultRuntime.log(theme.heading("Full request text"));
for (const e of t) defaultRuntime.log(`${formatApprovalIdForTerminal(e.id)}: ${escapeApprovalTextForTerminal(e.summary)}`);
});
});
nodesCallOpts(n);
const r = t.command("resolve <id> <decision>").description("Resolve a pending approval").option("--reason <text>", "Add a local note to the CLI confirmation").option("--expires-in-days <days>", "Allow-always on an automation approval: freeze this grant lifetime instead of the configured default").action(async (e, t, n) => {
await runApprovalsAction(n, async () => {
if (e.length === 0) throw new Error("Approval id required.");
const r = e;
const i = requireTrimmedNonEmpty(t, "Decision required.");
if (!isApprovalDecision(i)) throw new Error(`Decision must be one of: ${APPROVAL_DECISIONS.join(", ")}.`);
const a = n.reason === void 0 ? null : normalizeOptionalString(n.reason);
if (n.reason !== void 0 && !a) throw new Error("Reason must not be empty.");
const o = { scopes: [ADMIN_SCOPE, APPROVALS_SCOPE] };
const lookupOne = async (e, t = false) => {
try {
return await callGatewayFromCli("approval.get", n, { id: e }, o);
} catch (e) {
if (t && formatErrorMessage(e).toLowerCase().includes("approval not found")) return null;
throw e;
}
};
const s = decodeDisplayedApprovalId(r);
let c = r;
let l;
if (s && s !== r) {
const [e, t] = await Promise.all([lookupOne(r, true), lookupOne(s, true)]);
if (e && t) throw new Error("Approval id is ambiguous: it matches both a raw id and a displayed id token. This CLI cannot resolve it safely.");
if (e) l = e;
else if (t) {
c = s;
l = t;
} else throw new Error("Approval not found.");
} else l = expectDefined(await lookupOne(r), "approval lookup result");
const u = formatApprovalIdForTerminal(c);
const d = l.approval;
if (d.status === "pending") {
const e = d.presentation.allowedDecisions;
if (!e.includes(i)) throw new Error(`Decision ${i} is not allowed for ${d.presentation.kind} approvals; allowed decisions: ${e.join(", ")}.`);
}
const f = parseStrictPositiveInteger(n.expiresInDays);
if (n.expiresInDays !== void 0 && (f === void 0 || f > 3650)) throw new Error("--expires-in-days must be a whole number of days between 1 and 3650.");
if (f !== void 0 && i !== "allow-always") throw new Error("--expires-in-days only applies to allow-always.");
const p = await callGatewayFromCli("approval.resolve", n, {
id: c,
kind: d.presentation.kind,
decision: i,
...f !== void 0 ? { grantExpiresInDays: f } : {}
}, o);
const m = "decision" in p.approval && isApprovalDecision(p.approval.decision) ? p.approval.decision : null;
if (!m) {
const e = formatApprovalIdForTerminal(p.approval.id);
if (p.approval.status === "expired") throw new Error(`Approval ${e} expired.`);
if (p.approval.status === "cancelled") throw new Error(`Approval ${e} was cancelled (${p.approval.reason}).`);
throw new Error(`Approval ${e} did not settle to a recorded decision.`);
}
if (m !== i) throw new Error(`Approval ${u} was already resolved with ${m} by ${formatResolver(p.approval)}.`);
if (n.json) {
defaultRuntime.writeJson({
...p,
alreadyResolved: !p.applied,
...a ? { cliReason: a } : {}
}, 0);
return;
}
const h = p.applied ? `resolved ${m}` : `already resolved (same decision: ${m})`;
const g = a ? `; CLI reason: ${shortenPendingApprovalSummary(escapeApprovalTextForTerminal(a))}` : "";
defaultRuntime.log(`Approval ${u} ${h} by ${formatResolver(p.approval)}${g}.`);
});
});
nodesCallOpts(r);
const i = t.command("grants").description("Standing grants minted by allow-always on automation approvals");
const a = i.command("list").description("List standing grants, newest first").option("--limit <n>", "Maximum rows to return (default 200)").action(async (e) => {
await runApprovalsAction(e, async () => {
const t = parseOptionalPositiveInteger(e.limit, "--limit", ".");
const n = await callGatewayFromCli("exec.approval.grants.list", e, t !== void 0 ? { limit: t } : {});
if (e.json) {
defaultRuntime.writeJson(n, 0);
return;
}
const r = n.grants;
if (r.length === 0) {
defaultRuntime.log(theme.muted("No standing grants."));
return;
}
const i = Date.now();
defaultRuntime.log(`${theme.heading("Standing grants")} ${theme.muted(`(${r.length})`)}`);
defaultRuntime.log(renderTerminalSafeTable({
width: getTerminalTableWidth(),
columns: [
{
key: "ID",
header: "ID",
minWidth: 12,
flex: true
},
{
key: "Automation",
header: "Automation",
minWidth: 12,
flex: true
},
{
key: "Command",
header: "Command",
minWidth: 16,
flex: true
},
{
key: "Uses",
header: "Uses",
minWidth: 4
},
{
key: "State",
header: "State",
minWidth: 12
}
],
rows: r.map((e) => ({
ID: e.grantId,
Automation: escapeApprovalTextForTerminal(e.cronJobName ?? e.cronJobId),
Command: escapeApprovalTextForTerminal(e.command),
Uses: String(e.useCount),
State: describeGrantState(e, i)
}))
}));
defaultRuntime.log(theme.muted("Revoke with: openclaw approvals grants revoke <grant-id>"));
});
});
nodesCallOpts(a);
const o = i.command("revoke <grantId>").description("Revoke a standing grant; the next occurrence prompts again").action(async (e, t) => {
await runApprovalsAction(t, async () => {
const n = await callGatewayFromCli("exec.approval.grants.revoke", t, { grantId: e });
if (t.json) {
defaultRuntime.writeJson(n, 0);
return;
}
if (n.outcome === "revoked") defaultRuntime.log(`Grant ${e} revoked. The next occurrence prompts again.`);
else if (n.outcome === "already-revoked") defaultRuntime.log(`Grant ${e} was already revoked.`);
else throw new Error(`Grant ${e} not found.`);
});
});
nodesCallOpts(o);
const s = t.command("get").description("Fetch exec approvals snapshot").option("--node <node>", "Target node id/name/IP").option("--gateway", "Force gateway approvals", false).action(async (e) => {
await runApprovalsAction(e, async () => {
const { snapshot: t, nodeId: n, source: r } = await loadSnapshotTarget(e);
const i = isNativeApprovalsSnapshot(t);
const a = i ? {
config: null,
timedOut: false
} : await loadConfigForApprovalsTarget({
opts: e,
source: r
});
const o = isFileApprovalsSnapshot(t) ? t : null;
const s = o?.file;
const c = o?.resolvedDefaults;
const l = o?.path ?? "";
const u = (() => {
const e = a.config;
const t = a.timedOut ? "Config fetch timed out. Re-run with a higher --timeout to inspect Effective Policy." : null;
if (!s) return {
scopes: [],
note: i ? "This node enforces a host-native exec policy; OpenClaw approvals-file policy math does not apply." : "Host approvals policy unavailable."
};
if (!e) return {
scopes: [],
note: t ?? (r === "node" ? "Gateway config unavailable. Node output above shows host approvals state only, and final runtime policy still intersects with gateway tools.exec." : "Config unavailable.")
};
if (r === "node" && !c) return {
scopes: [],
note: "This node does not expose a complete resolved host policy, so Effective Policy is unavailable."
};
return {
scopes: collectExecPolicyScopeSnapshots({
cfg: e,
approvals: s,
hostPath: l,
...r === "node" ? {
hostDefaults: c,
hostDefaultSource: "node-reported resolved defaults"
} : {}
}),
note: (r === "node" ? "Effective exec policy is the node host approvals policy intersected with gateway tools.exec policy. " : "Effective exec policy is the host approvals policy intersected with requested tools.exec policy. ") + SESSION_EXEC_OVERRIDES_NOTE
};
})();
if (e.json) {
const e = o ? redactExecApprovals(o) : t;
defaultRuntime.writeJson({
...e,
effectivePolicy: u
}, 0);
return;
}
const muted = (e) => isRich() ? theme.muted(e) : e;
if (r === "local") {
defaultRuntime.log(muted("Showing local approvals."));
defaultRuntime.log("");
}
renderApprovalsSnapshot(t, r === "local" ? "local" : n ? `node:${n}` : "gateway");
const d = isRich();
const heading = (e) => d ? theme.heading(e) : e;
const policyMuted = (e) => d ? theme.muted(e) : e;
defaultRuntime.log("");
defaultRuntime.log(heading("Effective Policy"));
if (u.scopes.length === 0) {
defaultRuntime.log(policyMuted(u.note));
return;
}
const f = u.scopes.map((e) => ({
Scope: e.scopeLabel,
Requested: `security=${e.security.requested} (${e.security.requestedSource})\nask=${e.ask.requested} (${e.ask.requestedSource})`,
Host: `security=${e.security.host} (${e.security.hostSource})\nask=${e.ask.host} (${e.ask.hostSource})\naskFallback=${e.askFallback.effective} (${e.askFallback.source})`,
Effective: `security=${e.security.effective}\nask=${e.ask.effective}`,
Notes: `${e.security.note}; ${e.ask.note}`
}));
defaultRuntime.log(renderTerminalSafeTable({
width: getTerminalTableWidth(),
columns: [
{
key: "Scope",
header: "Scope",
minWidth: 12
},
{
key: "Requested",
header: "Requested",
minWidth: 24,
flex: true
},
{
key: "Host",
header: "Host",
minWidth: 24,
flex: true
},
{
key: "Effective",
header: "Effective",
minWidth: 16
},
{
key: "Notes",
header: "Notes",
minWidth: 20,
flex: true
}
],
rows: f
}).trimEnd());
defaultRuntime.log("");
defaultRuntime.log(policyMuted(`Precedence: ${u.note}`));
});
});
nodesCallOpts(s, { timeoutMs: APPROVALS_GET_DEFAULT_TIMEOUT_MS });
const c = t.command("set").description("Replace exec approvals with a JSON file").option("--node <node>", "Target node id/name/IP").option("--gateway", "Force gateway approvals", false).option("--file <path>", "Path to JSON file to upload").option("--stdin", "Read JSON from stdin", false).action(async (e) => {
await runApprovalsAction(e, async () => {
if (!e.file && !e.stdin) throw new Error("Provide --file or --stdin.");
if (e.file && e.stdin) throw new Error("Use either --file or --stdin (not both).");
const { source: t, nodeId: n, targetLabel: r, baseHash: i, snapshot: a } = await loadWritableSnapshotTarget(e);
const o = e.stdin ? await readStdin() : await readApprovalsFile(String(e.file));
let s;
try {
s = JSON5.parse(o);
} catch (e) {
throw new Error(`Failed to parse approvals JSON: ${String(e)}`, { cause: e });
}
if (isNativeApprovalsSnapshot(a)) {
if (!isRecord(s)) throw new Error("Host-native exec approvals JSON must be an object.");
const a = Object.keys(s).filter((e) => e !== "defaultAction" && e !== "rules");
if (a.length > 0) throw new Error(`Unknown host-native exec approvals field: ${a[0]}.`);
const o = s.defaultAction === void 0 ? void 0 : parseNativeAction(s.defaultAction, "defaultAction");
if (!Array.isArray(s.rules)) throw new Error("Host-native exec approvals rules must be an array.");
const c = s.rules.map((e, t) => {
if (!isRecord(e)) throw new Error(`Host-native exec approval rule ${t + 1} must be an object.`);
const n = Object.keys(e).filter((e) => e !== "pattern" && e !== "action" && e !== "shells" && e !== "description" && e !== "enabled");
if (n.length > 0) throw new Error(`Unknown host-native exec approval rule ${t + 1} field: ${n[0]}.`);
const r = normalizeOptionalString(e.pattern);
if (!r) throw new Error(`Host-native exec approval rule ${t + 1} requires pattern.`);
const i = parseNativeAction(e.action, `Host-native exec approval rule ${t + 1} action`);
let a;
if (e.shells !== void 0) {
if (!Array.isArray(e.shells)) throw new Error(`Host-native exec approval rule ${t + 1} shells must be an array.`);
a = e.shells.map((e) => {
const n = typeof e === "string" ? e.trim() : "";
if (!n) throw new Error(`Host-native exec approval rule ${t + 1} shells must be non-empty strings.`);
return n;
});
}
if (e.description !== void 0 && typeof e.description !== "string") throw new Error(`Host-native exec approval rule ${t + 1} description must be a string.`);
if (e.enabled !== void 0 && typeof e.enabled !== "boolean") throw new Error(`Host-native exec approval rule ${t + 1} enabled must be a boolean.`);
return {
pattern: r,
action: i,
...a ? { shells: a } : {},
...e.description !== void 0 ? { description: e.description } : {},
...e.enabled !== void 0 ? { enabled: e.enabled } : {}
};
});
await saveSnapshotTargeted({
opts: e,
source: t,
nodeId: n,
native: {
...o ? { defaultAction: o } : {},
rules: c
},
baseHash: i,
targetLabel: r
});
return;
}
if (!isRecord(s)) throw new Error("Exec approvals JSON must be an object.");
const c = s;
c.version = 1;
await saveSnapshotTargeted({
opts: e,
source: t,
nodeId: n,
file: c,
baseHash: i,
targetLabel: r
});
});
});
nodesCallOpts(c);
const l = t.command("allowlist").description("Edit the per-agent allowlist").addHelpText("after", () => `\n${theme.heading("Examples:")}\n${formatHelpExamples([
["openclaw approvals allowlist add \"~/Projects/**/bin/rg\"", "Allowlist a local binary pattern for the main agent."],
["openclaw approvals allowlist add --agent main --node <id|name|ip> \"/usr/bin/uptime\"", "Allowlist on a specific node/agent."],
["openclaw approvals allowlist add --agent \"*\" \"/usr/bin/uname\"", "Allowlist for all agents (wildcard)."],
["openclaw approvals allowlist remove \"~/Projects/**/bin/rg\"", "Remove an allowlist pattern."]
])}\n${formatDocsHelp("/cli/approvals")}`);
registerAllowlistMutationCommand({
allowlist: l,
name: "add",
description: "Add a glob pattern to an allowlist",
mutate: ({ trimmedPattern: e, file: t, agent: n, agentKey: r, allowlistEntries: i }) => {
if (i.some((t) => normalizeOptionalString(t?.pattern) === e)) {
defaultRuntime.log("Already allowlisted.");
return false;
}
i.push({
pattern: e,
lastUsedAt: Date.now()
});
n.allowlist = i;
t.agents = {
...t.agents,
[r]: n
};
return true;
}
});
registerAllowlistMutationCommand({
allowlist: l,
name: "remove",
description: "Remove a glob pattern from an allowlist",
mutate: ({ trimmedPattern: e, file: t, agent: n, agentKey: r, allowlistEntries: i }) => {
const a = i.filter((t) => normalizeOptionalString(t?.pattern) !== e);
if (a.length === i.length) {
defaultRuntime.log("Pattern not found.");
return false;
}
if (a.length === 0) delete n.allowlist;
else n.allowlist = a;
if (a.length === 0 && !n.security && !n.ask && !n.askFallback && n.autoAllowSkills === void 0 && !n.mcpTools?.length) {
const e = { ...t.agents };
delete e[r];
t.agents = Object.keys(e).length > 0 ? e : void 0;
} else t.agents = {
...t.agents,
[r]: n
};
return true;
}
});
applyParentDefaultHelpAction(t);
}
//#endregion
export { registerExecApprovalsCli };