openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
302 lines (301 loc) • 10.4 kB
JavaScript
import { o as normalizeLowercaseStringOrEmpty } from "./string-coerce-CCIiB4H7.mjs";
import { l as isRecord } from "./record-coerce-CVPuDqcc.mjs";
import { t as isPlainObject } from "./plain-object-CGY5w7fM.mjs";
import "./utils-C8YECn2Q.mjs";
import { a as getRuntimeConfigSnapshot, h as readRuntimeConfig } from "./runtime-snapshot-WbwbY5b7.mjs";
import { l as getActivePluginRegistry } from "./runtime-ezCEpumg.mjs";
import { c as normalizeToolPolicyName } from "./tool-policy-shared-BHvBopvF.mjs";
import { o as isCodeModeControlTool } from "./code-mode-control-tools-2pBIuXDg.mjs";
import { i as markToolExecutionRefused } from "./tool-effect-receipt-BbbEwqBS.mjs";
import { a as copyAgentToolMetadata, l as isGatewayToolPolicyControl } from "./agent-tool-metadata-nrQgRaqv.mjs";
import { t as ToolAuthorizationError } from "./tool-input-error-B1hgavSw.mjs";
import "./config-CMA-J084.mjs";
import { r as normalizePluginToolMatcher, t as createPluginToolMatcherScope } from "./tool-hook-matcher-DlUmH-ng.mjs";
import { r as getPluginSessionExtensionState } from "./host-hook-state-DnsDi6ZY.mjs";
//#region src/plugins/trusted-tool-policy.ts
function hasTrustedToolPolicies(e = getActivePluginRegistry()) {
return copyTrustedPolicyRegistrations(e).length > 0;
}
function unreadableTrustedPolicyRegistration() {
return {
pluginId: "unknown-plugin",
source: "runtime",
get policy() {
throw new Error("trusted policy registration is unreadable");
}
};
}
function copyTrustedPolicyRegistrations(e) {
try {
const t = e?.trustedToolPolicies;
if (!t) return [];
return Array.isArray(t) ? t.map((e) => e) : [unreadableTrustedPolicyRegistration()];
} catch {
return [unreadableTrustedPolicyRegistration()];
}
}
function readTrustedPolicyPluginString(e, t) {
try {
const n = e[t];
return typeof n === "string" && n.trim() ? n.trim() : void 0;
} catch {
return;
}
}
function trustedPolicyDiagnosticPluginId(e) {
return readTrustedPolicyPluginString(e, "pluginId") ?? "unknown-plugin";
}
function readTrustedPolicy(e) {
try {
const t = e.policy;
return t && typeof t.evaluate === "function" ? t : void 0;
} catch {
return;
}
}
function readTrustedPolicyMatcher(e) {
try {
return normalizePluginToolMatcher(e.matcher);
} catch {
return null;
}
}
function getTrustedToolPolicyMatcherScope(e = getActivePluginRegistry()) {
return createPluginToolMatcherScope(copyTrustedPolicyRegistrations(e).map((e) => {
const t = readTrustedPolicy(e);
if (!t) return;
return readTrustedPolicyMatcher(t) ?? void 0;
}));
}
function readTrustedPolicyId(e) {
const t = trustedPolicyDiagnosticPluginId(e);
const n = readTrustedPolicy(e);
if (!n) return t;
try {
const e = n.id;
return typeof e === "string" && e.trim() ? e.trim() : t;
} catch {
return t;
}
}
function trustedPolicyDefaultBlockReason(e) {
return `blocked by ${readTrustedPolicyId(e)}`;
}
function trustedPolicyFailureResult(e, t) {
return {
block: true,
blockReason: `${trustedPolicyDefaultBlockReason(e)}: ${t}`
};
}
function getTrustedToolPolicyDiagnosticEntries(e = getActivePluginRegistry()) {
return copyTrustedPolicyRegistrations(e).map((e) => {
const t = {
id: readTrustedPolicyId(e),
pluginId: trustedPolicyDiagnosticPluginId(e)
};
const n = readTrustedPolicyPluginString(e, "pluginName");
if (n) t.pluginName = n;
return t;
});
}
function normalizeDerivedEventFields(e) {
return Array.isArray(e?.derivedPaths) ? { derivedPaths: Object.freeze([...e.derivedPaths]) } : {};
}
function normalizeToolIdentity(e) {
return {
...e?.toolKind && { toolKind: e.toolKind },
...e?.toolInputKind && { toolInputKind: e.toolInputKind }
};
}
/** Runs trusted tool policies before a tool call and returns the first terminal decision. */
async function runTrustedToolPolicies(e, t, n) {
const r = copyTrustedPolicyRegistrations(n?.registry ?? getActivePluginRegistry());
let i = e.params;
let a = false;
let o;
const s = /* @__PURE__ */ new Map();
let c = n?.config;
let l = Boolean(n?.config);
const resolveSessionConfig = () => {
if (!l) {
l = true;
try {
c = readRuntimeConfig();
} catch {
c = void 0;
}
}
return c;
};
const { derivedPaths: u, toolKind: d, toolInputKind: f, ...p } = e;
const { toolKind: m, toolInputKind: h, ...g } = t;
let _ = normalizeDerivedEventFields({ derivedPaths: u });
let v = normalizeToolIdentity({
toolKind: d,
toolInputKind: f
});
let y = normalizeToolIdentity({
toolKind: m,
toolInputKind: h
});
const buildEvent = (e) => ({
...p,
params: e,
...v,
..._
});
for (const c of r) {
const r = readTrustedPolicyPluginString(c, "pluginId");
if (!r) return trustedPolicyFailureResult(c, "policy owner is unreadable");
const l = {
...g,
...y,
getSessionExtension: (e) => {
const t = e.trim();
const n = s.get(r);
if (!t || !n) return;
return n[t];
}
};
const u = readTrustedPolicy(c);
if (!u) return trustedPolicyFailureResult(c, "policy is unreadable");
const d = readTrustedPolicyMatcher(u);
if (d === null) return trustedPolicyFailureResult(c, "policy matcher is unreadable");
if (d && !d.includes(normalizeLowercaseStringOrEmpty(e.toolName))) continue;
let f;
try {
if (!s.has(r)) {
const e = t.sessionKey ? resolveSessionConfig() : void 0;
s.set(r, e ? await getPluginSessionExtensionState({
cfg: e,
pluginId: r,
sessionKey: t.sessionKey,
agentId: t.agentId
}) : void 0);
}
f = await u.evaluate(buildEvent(i), l);
} catch {
return trustedPolicyFailureResult(c, "policy evaluation failed");
}
if (!f) continue;
try {
if ("allow" in f && f.allow === false) return {
block: true,
blockReason: f.reason ?? trustedPolicyDefaultBlockReason(c)
};
if ("block" in f && f.block === true) return {
...f,
blockReason: f.blockReason ?? trustedPolicyDefaultBlockReason(c)
};
if ("params" in f && isPlainObject(f.params)) {
const e = n?.normalizeEvent?.(buildEvent(f.params), l);
i = e?.params ?? f.params;
if (e?.event) v = normalizeToolIdentity(e.event);
if (e?.ctx) y = normalizeToolIdentity(e.ctx);
else if (e?.event) y = normalizeToolIdentity(e.event);
a = true;
_ = normalizeDerivedEventFields(await n?.deriveEvent?.(i));
}
if ("requireApproval" in f && f.requireApproval && !o) o = f.requireApproval;
} catch {
t.abortSignal?.throwIfAborted();
return trustedPolicyFailureResult(c, "policy decision is unreadable");
}
}
if (!a && !o) return;
return {
...a ? { params: i } : {},
...o ? { requireApproval: o } : {}
};
}
//#endregion
//#region src/agents/gateway-tool-policy.ts
function isExecutableTool(e) {
return "execute" in e && typeof e.execute === "function" && "label" in e && "description" in e;
}
function policyActions(e, t) {
const n = Object.entries(e.actions ?? {}).filter(([e]) => normalizeToolPolicyName(e) === t).map(([, e]) => e);
return n.length ? n.reduce((e, t) => e.filter((e) => t.includes(e))) : void 0;
}
function hasAction(e) {
if (!isRecord(e)) return false;
return Boolean(isRecord(e.properties) && e.properties.action) || [
e.anyOf,
e.oneOf,
e.allOf
].some((e) => Array.isArray(e) && e.some((e) => isRecord(e) && hasAction(e)));
}
function narrowActions(e, t) {
const n = e.parameters;
const r = isRecord(n) ? n.properties : void 0;
const i = isRecord(r) ? r.action : void 0;
if (!isRecord(n) || !isRecord(r) || !isRecord(i) || i.type !== "string" || i.anyOf || i.oneOf || i.allOf) throw new Error(`Gateway tool policy requires ${e.name} to declare a top-level string action field.`);
const a = t.filter((e) => (!Array.isArray(i.enum) || i.enum.includes(e)) && (i.const === void 0 || i.const === e));
if (!a.length) return;
const o = {
...i,
enum: a
};
delete o.default;
return {
...n,
properties: {
...r,
action: o
},
required: [.../* @__PURE__ */ new Set([...Array.isArray(n.required) ? n.required : [], "action"])]
};
}
function toolAllowed(e, t) {
return e.allow.some((e) => normalizeToolPolicyName(e) === t);
}
/** Query the execution contract for tools such as exec that have no action argument. */
function isGatewayToolAllowedWithoutAction(e, t = getRuntimeConfigSnapshot() ?? void 0) {
const n = t?.tools?.gatewayPolicy;
const r = normalizeToolPolicyName(e);
return !n || toolAllowed(n, r) && policyActions(n, r) === void 0;
}
function gatewayPolicyDenial(e) {
return markToolExecutionRefused(new ToolAuthorizationError(e), {
kind: "blocked",
reason: e
});
}
/** Capture the deployment policy when constructing the tool executor. */
function createGatewayToolPolicyAssertion(e, t = getRuntimeConfigSnapshot() ?? void 0) {
const n = t?.tools?.gatewayPolicy;
return (t) => {
if (!n || isGatewayToolPolicyControl(e) || isCodeModeControlTool(e)) return;
const r = normalizeToolPolicyName(e.name);
if (!toolAllowed(n, r)) throw gatewayPolicyDenial(`Gateway tool policy denies tool "${r}".`);
const i = policyActions(n, r);
if (!hasAction(e.parameters) && i === void 0) return;
const a = isRecord(t) && typeof t.action === "string" ? t.action.trim() : void 0;
if (!a || !i?.includes(a)) throw gatewayPolicyDenial(`Gateway tool policy denies ${r} action "${a ?? "<missing>"}".`);
};
}
/** Apply the deployment policy after ordinary tool and plugin grants. */
function applyGatewayToolPolicy(e, t = getRuntimeConfigSnapshot() ?? void 0) {
const n = t?.tools?.gatewayPolicy;
if (!n) return e;
return e.flatMap((e) => {
if (isGatewayToolPolicyControl(e) || isCodeModeControlTool(e)) return [e];
const t = normalizeToolPolicyName(e.name);
if (!toolAllowed(n, t)) return [];
const r = policyActions(n, t);
if (hasAction(e.parameters) && r === void 0) throw new Error(`Gateway tool policy requires tools.gatewayPolicy.actions.${t}.`);
if (r === void 0) return [e];
if (!r.length) return [];
const i = narrowActions(e, r);
if (!i) return [];
return [isExecutableTool(e) ? copyAgentToolMetadata(e, {
...e,
parameters: i
}) : {
...e,
parameters: i
}];
});
}
//#endregion
export { getTrustedToolPolicyMatcherScope as a, getTrustedToolPolicyDiagnosticEntries as i, createGatewayToolPolicyAssertion as n, hasTrustedToolPolicies as o, isGatewayToolAllowedWithoutAction as r, runTrustedToolPolicies as s, applyGatewayToolPolicy as t };