openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
524 lines (523 loc) • 21.1 kB
JavaScript
import { r as defaultRuntime } from "./runtime-B-SLYP-m.mjs";
import { n as sanitizeTerminalText } from "./safe-text-C80HAQ2e.mjs";
import { n as normalizeAgentId } from "./agent-id-CQjtp2ft.mjs";
import { j as parseAgentSessionKey } from "./session-key-CqAyZeVk.mjs";
import { i as listAgentIds } from "./agent-roster-t1ooUdXp.mjs";
import { T as resolveSoleAgentId, h as resolveConfiguredAgentId, t as AgentSelectionRequiredError } from "./agent-scope-config-DmXgFGKP.mjs";
import { r as captureOpenClawStateWorkerContext } from "./openclaw-state-worker-context-DAKL_dnZ.mjs";
import { a as normalizeExecSecurity, c as resolveExactExecModeFromPolicy, i as normalizeExecMode, o as normalizeExecTarget, r as normalizeExecAsk, u as resolveExecModePolicy } from "./exec-approvals-core-puBAw1bE.mjs";
import { s as readConfigFileSnapshot } from "./io.runtime-DsJ2dLCQ.mjs";
import { r as replaceConfigFile } from "./mutate-DhAOi0-2.mjs";
import "./config-CMA-J084.mjs";
import { r as theme } from "./theme-BOI0xyRZ.mjs";
import { d as updateExecApprovals, l as readExecApprovalsSnapshotAsync, u as restoreExecApprovalsSnapshotLocked } from "./exec-approvals-store-BUZ9uOWF.mjs";
import "./exec-approvals-rOfoWejC.mjs";
import { n as sanitizeExecApprovalDisplayText } from "./exec-approval-text-sanitize-Xx3Q87a8.mjs";
import { t as ExpectedCliError, u as rethrowExpectedCliError } from "./failure-output-DVVDqwuu.mjs";
import { r as callGatewayFromCliWithTransport, s as resolveGatewayRpcOptionsWithLocalPort, t as addGatewayClientOptions } from "./gateway-rpc-CxUN2f1a.mjs";
import { t as runWithLocalStateOwner } from "./local-state-owner-DTl7OHpC.mjs";
import { n as renderTable, t as getTerminalTableWidth } from "./table-D2a-pD4_.mjs";
import { n as resolveConfiguredToolAccess } from "./tool-access-diagnostics-CxiCxmS0.mjs";
import { t as formatDocsHelp } from "./help-format-D2ytHW5E.mjs";
import { n as collectExecPolicyScopeSnapshots, t as SESSION_EXEC_OVERRIDES_NOTE } from "./exec-approvals-effective-e7qqZqNV.mjs";
//#region src/cli/exec-policy-diagnostics.ts
const TERMINAL_TOOLS = ["exec", "process"];
async function buildExecPolicyToolAccess(e, t) {
const n = t.agent?.trim();
const r = t.session?.trim();
if (t.agent !== void 0 && !n) throw new Error("--agent must not be blank.");
if (t.session !== void 0 && !r) throw new Error("--session must not be blank.");
const i = r ? parseAgentSessionKey(r)?.agentId : void 0;
const a = n ? normalizeAgentId(n) : void 0;
if (a && i && a !== i) throw new Error(`Agent "${a}" does not match session agent "${i}".`);
const o = r ? a ?? i : resolveConfiguredAgentId(e, a ?? resolveSoleAgentId(e, {
surface: "exec-policy show",
hint: "Pass --agent <id> or --session <agent session key>."
}));
const s = {
...o ? { agentId: o } : {},
...r ? { sessionKey: r } : {}
};
if (r) try {
const e = await callGatewayFromCliWithTransport("tools.effective", t, {
...o ? { agentId: o } : {},
sessionKey: r
}, {
progress: false,
sharedStateMode: "read-only"
});
if (o && e.agentId !== o) throw new Error("The Gateway returned tool access for a different agent.");
s.agentId = e.agentId;
s.live = {
status: "verified",
diagnostics: e.toolAccess ?? describeLegacySessionPreview(e)
};
} catch (e) {
s.live = {
status: "unverified",
error: e instanceof Error ? e.message : String(e)
};
}
if (s.agentId && listAgentIds(e).includes(s.agentId)) s.local = resolveConfiguredToolAccess({
config: e,
agentId: s.agentId,
toolNames: TERMINAL_TOOLS
});
return s;
}
function describeLegacySessionPreview(e) {
const t = e.groups.flatMap((e) => e.tools);
return {
checked: "live-session",
profiles: [],
tools: TERMINAL_TOOLS.map((e) => {
const n = t.find((t) => t.id === e);
return {
id: e,
status: n?.deniedBySession ? "excluded" : n ? "available" : "unavailable",
reasons: n?.deniedBySession ? [{
kind: "session",
label: "Denied by this session's tool restrictions"
}] : n ? [] : [{
kind: "runtime",
label: "Not included in the session preview"
}]
};
})
};
}
function display(e) {
return sanitizeExecApprovalDisplayText(sanitizeTerminalText(e));
}
function terminalTools(e) {
return e.tools.filter((e) => TERMINAL_TOOLS.some((t) => t === e.id));
}
function formatExecPolicyCommandApprovals(e) {
const t = e.scopes.map((t) => {
const n = t.ask.effective === "on-miss" ? "ask on miss" : t.ask.effective === "always" ? "always ask" : t.ask.effective === "off" ? "no approval prompts" : "approval mode unknown";
return display(`${e.showScopeLabels && t.scopeLabel ? `${t.scopeLabel}: ` : ""}${t.host.requested} · ${t.security.effective} · ${n} · fallback ${t.askFallback.effective}`);
});
if (!e.approvalsExists) t.push("Approvals State: defaults (no stored overrides)");
t.push("Command approvals do not grant tool access.", SESSION_EXEC_OVERRIDES_NOTE);
return t;
}
function renderExecPolicyToolAccess(e) {
const { access: t } = e;
const n = t.live?.status === "verified" ? t.live.diagnostics : void 0;
const r = n ?? t.local;
const i = r ? terminalTools(r) : [];
const a = i.filter((e) => e.status === "excluded");
const o = i.some((e) => e.status === "unavailable");
const s = t.live?.status === "unverified" ? "UNVERIFIED" : a.length === TERMINAL_TOOLS.length ? n ? "BLOCKED" : "OFF" : a.length > 0 ? "PARTIAL" : n ? "PREVIEW" : "UNVERIFIED";
const c = [theme.heading(`TERMINAL ACCESS · ${display(t.agentId ?? "unknown agent")} — ${s}`)];
if (t.sessionKey) c.push(`Session: ${display(t.sessionKey)}`);
const section = (e) => {
c.push("", theme.heading(`── ${e} ${"─".repeat(Math.max(1, 43 - e.length))}`), "");
};
if (r && r.profiles.length > 0) {
section(n ? "PROFILE (GATEWAY CONFIGURATION)" : "PROFILE");
const e = r.profiles.find((e) => e.source === "tools.profile");
const t = r.profiles.find((e) => e.source.startsWith("agents.") && e.source.endsWith(".tools.profile"));
const profileText = (e) => `${display(e.profile)}${e.active ? " ← active" : ""}`;
if (e) c.push(`Global: ${profileText(e)}`);
if (t) c.push(`${e ? "└─ " : ""}Agent: ${profileText(t)}`);
for (const n of r.profiles.filter((n) => n !== e && n !== t)) c.push(`${display(n.source)}: ${profileText(n)}`);
}
section("CHECK RESULTS");
if (!t.local) c.push("Local tool policy: unavailable — no matching local agent.");
if (t.live?.status === "unverified") {
if (t.local) {
const e = terminalTools(t.local).filter((e) => e.status === "excluded");
c.push(e.length > 0 ? `Local configuration excludes: ${e.map((e) => e.id).join(", ")}` : "Local configuration allows terminal tools; execution unverified");
}
c.push(`Session preview: could not retrieve — ${display(t.live.error)}`);
}
for (const e of i) {
const t = e.status === "available" ? "Included in session preview" : e.status === "allowed" ? "Allowed by configuration; execution unverified" : e.status === "excluded" ? "Excluded by policy" : "Not included in session preview; execution unverified";
c.push(`${display(e.id)}: ${t}`);
for (const t of e.reasons) c.push(` ${display(t.label)}${t.source ? ` (${display(t.source)})` : ""}`);
}
if (r) c.push("", `Based on: ${n ? "session preview (saved settings)" : "local configuration"}`);
if (n) c.push("Session preview uses saved settings; active runs may differ.");
section("COMMAND APPROVALS (LOCAL)");
c.push(...formatExecPolicyCommandApprovals({
scopes: e.approvals ? [e.approvals] : [],
approvalsExists: e.approvalsExists
}));
section("NEXT STEP");
if (t.live?.status === "unverified") c.push("Check the Gateway connection and session key, then retry.");
else if (a.length > 0) {
const e = /* @__PURE__ */ new Map();
if (!o && a.every((e) => e.alsoAllowPath)) {
for (const t of a) {
const n = t.alsoAllowPath;
e.set(n, [...e.get(n) ?? [], t.id]);
}
c.push("If terminal access is intended, append:");
for (const [t, n] of e) c.push(` ${n.join(", ")}`, "to:", ` ${display(t)}`);
c.push("", "Preserve existing entries and command approvals.", "Inspect the session preview, then verify execution in a run.");
} else c.push("Review the policy exclusions listed above before enabling terminal access.");
} else if (n) c.push(o ? "Missing preview tools are not necessarily disabled." : "Preview inclusion does not guarantee execution.", "Verify execution in a run; command approvals still apply.");
else {
c.push("Inspect an existing session's tool preview:");
c.push(" openclaw exec-policy show --session <session-key>");
c.push("Verify execution in a run; command approvals still apply.");
}
if (n && o && a.length > 0) c.push("Missing preview tools are not necessarily disabled; verify execution in a run.");
if (e.verbose) {
section("TOOL POLICY SOURCES");
for (const e of r?.profiles ?? []) c.push(`${display(e.source)} = ${display(e.profile)}`);
} else c.push("", "Use --verbose for policy sources and all command approval scopes.");
defaultRuntime.log(c.join("\n"));
}
//#endregion
//#region src/cli/exec-policy-cli.ts
const EXEC_POLICY_PRESETS = {
yolo: {
host: "gateway",
security: "full",
ask: "off",
askFallback: "full"
},
cautious: {
host: "gateway",
security: "allowlist",
ask: "on-miss",
askFallback: "deny"
},
"deny-all": {
host: "gateway",
security: "deny",
ask: "off",
askFallback: "deny"
}
};
function formatExecPolicyError(e) {
return sanitizeExecPolicyMessage(e instanceof Error ? e.message : String(e));
}
async function runExecPolicyAction(e, t) {
try {
await t();
} catch (t) {
const n = formatExecPolicyError(t);
if (e.json) {
rethrowExpectedCliError(t);
const e = new ExpectedCliError({
message: n,
humanOutput: n,
machineOutput: n
});
e.cause = t;
throw e;
}
defaultRuntime.error(n);
defaultRuntime.exit(1);
}
}
function sanitizeExecPolicyTableCell(e) {
return sanitizeExecApprovalDisplayText(sanitizeTerminalText(e));
}
function sanitizeExecPolicyMessage(e) {
return sanitizeTerminalText(String(e));
}
async function buildLocalExecPolicyShowPayload(e) {
const t = await readConfigFileSnapshot();
const n = await readExecApprovalsSnapshotAsync();
const r = t.config ?? {};
const i = collectExecPolicyScopeSnapshots({
cfg: r,
approvals: n.file,
hostPath: n.path
}).map(buildExecPolicyShowScope);
const a = i.some((e) => e.runtimeApprovalsSource === "node-runtime") ? "Scopes requesting host=node are node-managed at runtime. Local approvals are shown only for local/gateway scopes." : "Effective exec policy is the host approvals policy intersected with requested tools.exec policy.";
const o = {
configPath: t.path,
approvalsPath: n.path,
approvalsExists: n.exists,
effectivePolicy: {
note: `${a} ${SESSION_EXEC_OVERRIDES_NOTE}`,
scopes: i
}
};
if (!e) return o;
const s = e.agent !== void 0 || e.session !== void 0;
if (!s && listAgentIds(r).length === 0) {
o.toolAccessSelectionRequired = {
agentIds: [],
hint: "Configure an agent with openclaw agents add to inspect terminal tool access."
};
return o;
}
try {
o.toolAccess = await buildExecPolicyToolAccess(r, e);
} catch (e) {
if (s || !(e instanceof AgentSelectionRequiredError)) throw e;
o.toolAccessSelectionRequired = {
agentIds: e.agentIds,
hint: e.hint
};
}
return o;
}
function buildExecPolicyShowScope(e) {
const { allowedDecisions: t, ...n } = e;
if (e.host.requested !== "node") return {
...n,
runtimeApprovalsSource: "local-file"
};
const nodeManagedPolicy = (t) => ({
requested: e[t].requested,
requestedSource: e[t].requestedSource,
host: "unknown",
hostSource: "node runtime approvals",
effective: "unknown",
note: "runtime policy resolved by node approvals"
});
return {
...n,
runtimeApprovalsSource: "node-runtime",
security: nodeManagedPolicy("security"),
ask: nodeManagedPolicy("ask"),
askFallback: {
effective: "unknown",
source: "node runtime approvals"
}
};
}
function renderExecPolicyShow(e) {
defaultRuntime.log(theme.heading("Exec Policy"));
defaultRuntime.log(renderTable({
width: getTerminalTableWidth(),
columns: [{
key: "Field",
header: "Field",
minWidth: 14
}, {
key: "Value",
header: "Value",
minWidth: 24,
flex: true
}],
rows: [
{
Field: "Config",
Value: sanitizeExecPolicyTableCell(e.configPath)
},
{
Field: "Approvals",
Value: sanitizeExecPolicyTableCell(e.approvalsPath)
},
{
Field: "Approvals State",
Value: sanitizeExecPolicyTableCell(e.approvalsExists ? "stored" : "defaults (no stored overrides)")
}
]
}).trimEnd());
defaultRuntime.log("");
defaultRuntime.log(theme.heading("Effective Policy"));
defaultRuntime.log(renderTable({
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
}
],
rows: e.effectivePolicy.scopes.map((e) => ({
Scope: sanitizeExecPolicyTableCell(e.scopeLabel),
Requested: sanitizeExecPolicyTableCell(`host=${e.host.requested} (${e.host.requestedSource})\nsecurity=${e.security.requested} (${e.security.requestedSource})\nask=${e.ask.requested} (${e.ask.requestedSource})`),
Host: sanitizeExecPolicyTableCell(`security=${e.security.host} (${e.security.hostSource})\nask=${e.ask.host} (${e.ask.hostSource})\naskFallback=${e.askFallback.effective} (${e.askFallback.source})`),
Effective: sanitizeExecPolicyTableCell(`security=${e.security.effective}\nask=${e.ask.effective}`)
}))
}).trimEnd());
defaultRuntime.log("");
defaultRuntime.log(theme.muted(e.effectivePolicy.note));
}
function applyLocalExecPolicy(e) {
return runWithLocalStateOwner({
method: "exec-policy.set",
params: { ...e },
target: "local exec policy and approvals",
onForeignOwner: "refuse",
runLocal: async ({ assertCurrent: t }) => {
const n = captureOpenClawStateWorkerContext();
const r = await readConfigFileSnapshot();
t();
const i = structuredClone(r.config ?? {});
i.tools ??= {};
i.tools.exec ??= {};
if (e.host !== void 0) i.tools.exec.host = e.host;
if (e.security !== void 0 || e.ask !== void 0) {
const t = resolveExecModePolicy({
mode: normalizeExecMode(i.tools.exec.mode),
security: i.tools.exec.security ?? "full",
ask: i.tools.exec.ask ?? "off"
});
const n = e.security ?? t.security;
const r = e.ask ?? t.ask;
const a = t.mode === "auto" && n === t.security && r === t.ask ? "auto" : resolveExactExecModeFromPolicy({
security: n,
ask: r
});
if (a) {
i.tools.exec.mode = a;
delete i.tools.exec.security;
delete i.tools.exec.ask;
} else {
delete i.tools.exec.mode;
i.tools.exec.security = n;
i.tools.exec.ask = r;
}
}
if (i.tools?.exec?.host === "node") throw new Error("Local exec-policy cannot synchronize host=node. Node approvals are fetched from the node at runtime.");
const a = await readExecApprovalsSnapshotAsync(n);
t();
const o = structuredClone(a.file ?? { version: 1 });
o.version = 1;
o.defaults ??= {};
if (e.security !== void 0) o.defaults.security = e.security;
if (e.ask !== void 0) o.defaults.ask = e.ask;
if (e.askFallback !== void 0) o.defaults.askFallback = e.askFallback;
const s = await updateExecApprovals({
baseHash: a.hash,
assertCurrent: t,
update: {
kind: "replace",
file: o
}
}, n);
if (!s) throw new Error("Exec approvals changed; reload and retry.");
try {
t();
await replaceConfigFile({
baseHash: r.hash,
nextConfig: i,
writeOptions: { assertCurrent: t }
});
} catch (r) {
try {
t();
if (!await restoreExecApprovalsSnapshotLocked(a, s.hash, n, t)) await updateExecApprovals({
assertCurrent: t,
update: {
kind: "rollback-defaults",
original: a.file,
written: s.file,
policy: e
}
}, n);
} catch (e) {
throw new Error(`Config update failed: ${formatExecPolicyError(r)}; exec approvals rollback failed: ${formatExecPolicyError(e)}`, { cause: e });
}
throw r;
}
return await buildLocalExecPolicyShowPayload();
}
});
}
function registerExecPolicyCli(e) {
const t = e.command("exec-policy").description("Show or synchronize requested exec policy with host approvals").addHelpText("after", () => formatDocsHelp("/cli/approvals"));
addGatewayClientOptions(t.command("show").description("Explain terminal tool access and command approvals (offline unless --session)").option("--agent <id>", "Agent whose terminal tools to inspect (automatic for one agent)").option("--session <key>", "Fetch an existing session's tool preview from saved settings").option("--verbose", "Include policy sources and all command approval scopes", false).option("--json", "Output as JSON", false)).action(async (e, t) => {
await runExecPolicyAction(e, async () => {
const n = await buildLocalExecPolicyShowPayload(resolveGatewayRpcOptionsWithLocalPort(e, t));
if (e.json) {
defaultRuntime.writeJson(n, 0);
return;
}
if (n.toolAccess) {
const t = n.effectivePolicy.scopes.find((e) => e.scopeLabel === `agent:${n.toolAccess?.agentId}`) ?? n.effectivePolicy.scopes.find((e) => e.agentId === n.toolAccess?.agentId) ?? n.effectivePolicy.scopes[0];
renderExecPolicyToolAccess({
access: n.toolAccess,
approvals: t,
approvalsExists: n.approvalsExists,
verbose: e.verbose
});
} else if (n.toolAccessSelectionRequired) {
const { agentIds: t, hint: r } = n.toolAccessSelectionRequired;
const i = `TERMINAL ACCESS — ${t.length ? "SELECT AGENT" : "NO AGENT CONFIGURED"}`;
defaultRuntime.log(theme.heading(i));
if (t.length > 0) defaultRuntime.log(`Configured agents: ${t.map(sanitizeExecPolicyTableCell).join(", ")}`);
defaultRuntime.log("");
defaultRuntime.log(theme.heading("── COMMAND APPROVALS (LOCAL) ──────────────────"));
defaultRuntime.log("");
defaultRuntime.log(formatExecPolicyCommandApprovals({
scopes: n.effectivePolicy.scopes,
approvalsExists: n.approvalsExists,
showScopeLabels: true
}).join("\n"));
defaultRuntime.log("");
defaultRuntime.log(theme.heading("── NEXT STEP ─────────────────────────────────"));
defaultRuntime.log("");
defaultRuntime.log(sanitizeExecPolicyTableCell(r));
if (!e.verbose) defaultRuntime.log("Use --verbose for policy sources and detailed command approval scopes.");
}
if (e.verbose) {
defaultRuntime.log("");
renderExecPolicyShow(n);
}
});
});
t.command("preset <name>").description("Apply a synchronized preset: \"yolo\", \"cautious\", or \"deny-all\"").option("--json", "Output as JSON", false).action(async (e, t) => {
await runExecPolicyAction(t, async () => {
if (!Object.hasOwn(EXEC_POLICY_PRESETS, e)) throw new Error(`Unknown exec-policy preset: ${sanitizeExecPolicyMessage(e)}`);
const n = EXEC_POLICY_PRESETS[e];
const r = await applyLocalExecPolicy(n);
if (t.json) {
defaultRuntime.writeJson({
preset: e,
...r
}, 0);
return;
}
defaultRuntime.log(`Applied exec-policy preset: ${sanitizeExecPolicyMessage(e)}`);
defaultRuntime.log("");
renderExecPolicyShow(r);
});
});
t.command("set").description("Synchronize local config and host approvals using explicit values").option("--host <host>", "Exec host target: auto|sandbox|gateway|node").option("--security <mode>", "Exec security: deny|allowlist|full").option("--ask <mode>", "Exec ask mode: off|on-miss|always").option("--ask-fallback <mode>", "Host approvals fallback: deny|allowlist|full").option("--json", "Output as JSON", false).action(async (e) => {
await runExecPolicyAction(e, async () => {
const t = {};
const parse = (e, t, n) => {
const r = t(e);
if (!r) throw new Error(`Invalid exec ${n}: ${sanitizeExecPolicyMessage(e)}`);
return r;
};
if (e.host !== void 0) t.host = parse(e.host, normalizeExecTarget, "host");
if (e.security !== void 0) t.security = parse(e.security, normalizeExecSecurity, "security");
if (e.ask !== void 0) t.ask = parse(e.ask, normalizeExecAsk, "ask mode");
if (e.askFallback !== void 0) t.askFallback = parse(e.askFallback, normalizeExecSecurity, "askFallback");
if (Object.keys(t).length === 0) throw new Error("Provide at least one of --host, --security, --ask, or --ask-fallback.");
const n = await applyLocalExecPolicy(t);
if (e.json) {
defaultRuntime.writeJson({
applied: t,
...n
}, 0);
return;
}
defaultRuntime.log("Synchronized local exec policy.");
defaultRuntime.log("");
renderExecPolicyShow(n);
});
});
}
//#endregion
export { registerExecPolicyCli };