openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
428 lines (427 loc) • 14.2 kB
JavaScript
import { o as normalizeLowercaseStringOrEmpty } from "./string-coerce-CCIiB4H7.mjs";
import { b as uniqueStrings, h as normalizeUniqueSingleOrTrimmedStringList } from "./string-normalization-DLmfYZXI.mjs";
import { n as formatConcreteConfigPath } from "./dot-path-BJ4tyWKJ.mjs";
import { n as normalizeAgentId } from "./agent-id-CQjtp2ft.mjs";
import { D as parseThreadSessionSuffix, T as parseRawSessionConversationRef, j as parseAgentSessionKey } from "./session-key-CqAyZeVk.mjs";
import { n as normalizeAccountId, t as DEFAULT_ACCOUNT_ID } from "./account-id-BqKT3GuY.mjs";
import { r as listAgentEntriesWithSource, t as hasAgentRosterProperty } from "./agent-roster-t1ooUdXp.mjs";
import { C as resolveSessionAgentIds, r as resolveAgentConfig } from "./agent-scope-config-DmXgFGKP.mjs";
import "./agent-scope-BwB8YH6y.mjs";
import { n as normalizeMessageChannel } from "./message-channel-core-BbYZT1a-.mjs";
import { n as getLoadedChannelPlugin } from "./registry-ByqVE5S3.mjs";
import "./message-channel-DTYVLJT1.mjs";
import { f as pickSandboxToolPolicy, l as mergeAlsoAllowPolicy } from "./tool-policy-BR4v75RA.mjs";
import { t as AUTOMATIONS_TOOL_NAME } from "./automations-tool-name-DNRDs0aJ.mjs";
import { U as resolveCoreToolProfilePolicy } from "./tool-catalog-C1ALpCJD.mjs";
import { r as createToolPolicyMatcher } from "./tool-policy-match-DzwVnbV4.mjs";
import "./plugins-BoMiRtiY.mjs";
import { t as resolveSessionConversation } from "./session-conversation-ANXEVkYh.mjs";
import { r as resolveSandboxToolPolicyForAgent } from "./tool-policy-DsT-JaIj.mjs";
import { r as resolveChannelGroupToolsPolicy } from "./group-policy-ChfL4Y9r.mjs";
import { i as logWarn } from "./logger-CIwfuhOU.mjs";
import { i as resolveTemplateToolPolicyConsent, n as markFrozenTemplateToolAllowPolicy } from "./tool-policy-runtime-CvSLQvPo.mjs";
import { r as resolveProviderToolPolicyEntry } from "./provider-tool-policy-DNUBF9-2.mjs";
import { a as resolveStoredSubagentCapabilities, l as resolveSubagentCapabilityStore, n as isVisibleSpawnedSession, o as resolveStoredSubagentInheritedToolAllowlist, s as resolveStoredSubagentInheritedToolDenylist } from "./subagent-capabilities-D82nSYzB.mjs";
//#region src/agents/agent-tools.policy.ts
/**
* Resolves sandbox tool policies for agents, providers, sub-agents, and group
* sessions. Keeps runtime tool filtering tied to canonical config, session
* provenance, and inherited sub-agent capabilities.
*/
/**
* Default hard denies for sub-agents regardless of depth. Visible spawned
* sessions retain message delivery; all other hard denies still apply.
*/
const SUBAGENT_TOOL_DENY_ALWAYS = [
"gateway",
"agents_list",
"openclaw",
"session_status",
"progress_card",
AUTOMATIONS_TOOL_NAME,
"message",
"sessions_send",
"conversations_list",
"conversations_send",
"conversations_turn"
];
/** Tools that only make sense for orchestrator sub-agents that can spawn children. */
const SUBAGENT_TOOL_DENY_LEAF = [
"subagents",
"sessions_list",
"sessions_history",
"sessions_search",
"sessions_spawn"
];
function resolveSubagentToolPolicyForSession(e, t, n) {
const r = e?.tools?.subagents?.tools;
const i = resolveSubagentCapabilityStore(t, {
cfg: e,
store: n?.store
});
const a = resolveStoredSubagentCapabilities(t, {
cfg: e,
store: i
});
const o = r?.allow;
const s = r?.alsoAllow;
const c = [
...SUBAGENT_TOOL_DENY_ALWAYS.filter((n) => n !== "message" || !isVisibleSpawnedSession(t, {
cfg: e,
store: i
})),
...a.role === "leaf" ? SUBAGENT_TOOL_DENY_LEAF : [],
...r?.deny ?? []
];
return {
allow: o && s ? uniqueStrings([...o, ...s]) : o,
deny: c
};
}
function resolveInheritedToolPolicyForSession(e, t, n) {
const r = resolveStoredSubagentInheritedToolAllowlist(t, {
cfg: e,
store: n?.store
});
const i = resolveStoredSubagentInheritedToolDenylist(t, {
cfg: e,
store: n?.store
});
if (r.length === 0 && i.length === 0) return;
return {
...r.length > 0 ? { allow: r } : {},
...i.length > 0 ? { deny: i } : {}
};
}
function resolveConfiguredToolPolicies(e) {
const t = e.agentTools?.profile ?? e.cfg.tools?.profile;
const n = e.agentTools?.alsoAllow ?? e.cfg.tools?.alsoAllow;
const r = [
mergeAlsoAllowPolicy(resolveCoreToolProfilePolicy(t), n),
pickSandboxToolPolicy(e.cfg.tools),
pickSandboxToolPolicy(e.agentTools),
...e.extraPolicies ?? []
].filter((e) => Boolean(e));
if (e.sandboxMode === "all") r.push(resolveSandboxToolPolicyForAgent(e.cfg, e.agentId ?? void 0));
return r;
}
function buildScopedGroupIdCandidates(e) {
const t = e?.trim();
if (!t) return [];
const n = t.match(/^(.+):topic:([^:]+):sender:([^:]+)$/i);
if (n) {
const [, e, r] = n;
return normalizeUniqueSingleOrTrimmedStringList([
t,
`${e}:topic:${r}`,
e
]);
}
const r = t.match(/^(.+):topic:([^:]+)$/i);
if (r) {
const [, e, t] = r;
return normalizeUniqueSingleOrTrimmedStringList([`${e}:topic:${t}`, e]);
}
const i = t.match(/^(.+):sender:([^:]+)$/i);
if (i) {
const [, e] = i;
return normalizeUniqueSingleOrTrimmedStringList([t, e]);
}
return [t];
}
function resolveGroupContextFromSessionKey(e) {
const t = (e ?? "").trim();
if (!t) return {};
const { baseSessionKey: n, threadId: r } = parseThreadSessionSuffix(t);
const i = r ? n : t;
const a = parseRawSessionConversationRef(i);
if (a) {
const e = resolveSessionConversation({
channel: a.channel,
kind: a.kind,
rawId: a.rawId
});
return {
channel: a.channel,
groupIds: normalizeUniqueSingleOrTrimmedStringList([
...buildScopedGroupIdCandidates(a.rawId),
e?.id,
e?.baseConversationId,
...e?.parentConversationCandidates ?? []
])
};
}
const o = (i ?? t).split(":").filter(Boolean);
let s = o[0] === "agent" ? o.slice(2) : o;
if (s[0] === "subagent") s = s.slice(1);
if (s.length < 3) return {};
const [c, l, ...u] = s;
if (l !== "group" && l !== "channel") return {};
const d = u.join(":").trim();
if (!d) return {};
return {
channel: normalizeLowercaseStringOrEmpty(c),
groupIds: buildScopedGroupIdCandidates(d)
};
}
function resolveTrustedGroupIdFromContexts(e) {
const t = (e.groupId ?? "").trim();
if (!t) return {
groupId: e.groupId,
dropped: false
};
if (normalizeUniqueSingleOrTrimmedStringList([...e.sessionContext.groupIds ?? [], ...e.spawnedContext.groupIds ?? []]).includes(t)) return {
groupId: e.groupId,
dropped: false
};
return {
groupId: null,
dropped: true
};
}
/** Validate caller-supplied group ids against server-derived session context. */
function resolveTrustedGroupId(e) {
return resolveTrustedGroupIdFromContexts({
groupId: e.groupId,
sessionContext: resolveGroupContextFromSessionKey(e.sessionKey),
spawnedContext: resolveGroupContextFromSessionKey(e.spawnedBy)
});
}
function profileAllowsGatewayConfigReads(e, t) {
const n = resolveCoreToolProfilePolicy(e);
if (!n?.allow || n.allow.includes("*")) return true;
const r = normalizeUniqueSingleOrTrimmedStringList(t);
return r.length > 0 && createToolPolicyMatcher({ allow: r })("gateway");
}
/** Detect removed implicit grants for migration warnings only (#47487). */
function detectImplicitProfileGrants(e) {
return [{
section: "exec",
grants: ["exec", "process"]
}, {
section: "fs",
grants: [
"read",
"write",
"edit"
]
}].filter(({ section: t }) => e.agentTools?.[t] != null || e.includeGlobalSections && e.globalTools?.[t] != null).map(({ section: e, grants: t }) => ({
section: `tools.${e}`,
grants: t
}));
}
function resolveEffectiveToolPolicy(e) {
const t = e.agentId?.trim() ? normalizeAgentId(e.agentId) : void 0;
const n = e.config ? listAgentEntriesWithSource(e.config) : [];
const r = e.config && (!hasAgentRosterProperty(e.config) || n.length > 0) ? resolveSessionAgentIds({
config: e.config,
agentId: t,
sessionKey: e.sessionKey
}).sessionAgentId : t ?? parseAgentSessionKey(e.sessionKey)?.agentId;
const i = e.config && r ? resolveAgentConfig(e.config, r) : void 0;
const a = e.config ? (e.config.agents?.defaults)?.tools : void 0;
const o = i?.tools ?? (e.config && !hasAgentRosterProperty(e.config) ? a : void 0);
const s = e.config?.tools;
const c = o?.profile ?? s?.profile;
const l = o?.profile ? "agent" : s?.profile ? "global" : void 0;
const u = resolveProviderToolPolicyEntry({
byProvider: s?.byProvider,
modelProvider: e.modelProvider,
modelId: e.modelId
});
const d = resolveProviderToolPolicyEntry({
byProvider: o?.byProvider,
modelProvider: e.modelProvider,
modelId: e.modelId
});
const f = u?.policy;
const p = d?.policy;
const m = n.find(({ entry: e }) => normalizeAgentId(e.id) === r)?.source;
const h = m ? formatConcreteConfigPath([
"agents",
m.kind,
m.kind === "entries" ? m.key : m.index,
"tools"
]) : e.config && !hasAgentRosterProperty(e.config) && !i?.tools && a ? "agents.defaults.tools" : `agents.entries.${r}.tools`;
const g = u ? `tools.byProvider[${JSON.stringify(u.key)}]` : void 0;
const _ = d ? `${h}.byProvider[${JSON.stringify(d.key)}]` : void 0;
const v = p?.profile ? _ : g;
const y = !o?.allow && (o?.alsoAllow || !s?.alsoAllow?.length) ? `${h}.alsoAllow` : void 0;
const b = {
profile: {
kind: "profile",
path: l === "agent" ? `${h}.profile` : "tools.profile",
profile: c,
alsoAllowPath: y
},
providerProfile: {
kind: "profile",
path: v ? `${v}.profile` : void 0,
profile: p?.profile ?? f?.profile
},
global: {
kind: "config",
path: "tools"
},
globalProvider: {
kind: "config",
path: g
},
agent: {
kind: "config",
path: h
},
agentProvider: {
kind: "config",
path: _
}
};
const x = [
[
s,
"tools",
!o?.profile
],
[
o,
h,
true
],
[
f,
g,
!p?.profile
],
[
p,
_,
true
]
].flatMap(([e, t, n]) => e?.profile && t ? [{
profile: e.profile,
source: `${t}.profile`,
active: n
}] : []);
const S = o?.alsoAllow ?? s?.alsoAllow;
const C = pickSandboxToolPolicy(o);
if (resolveTemplateToolPolicyConsent({
agentTools: o,
agentId: r,
profile: c,
ownsProfile: l === "agent",
hasAgentAllowlist: (C?.allow?.length ?? 0) > 0
}).frozen) markFrozenTemplateToolAllowPolicy(C);
const w = {
agentId: r,
sources: b,
profiles: x,
globalPolicy: pickSandboxToolPolicy(s),
globalProviderPolicy: pickSandboxToolPolicy(f),
agentPolicy: C,
agentProviderPolicy: pickSandboxToolPolicy(p),
profile: c,
providerProfile: p?.profile ?? f?.profile,
profileAlsoAllow: S ? uniqueStrings(S) : void 0,
providerProfileAlsoAllow: p?.alsoAllow ?? f?.alsoAllow
};
const T = profileAllowsGatewayConfigReads(c, w.profileAlsoAllow) && profileAllowsGatewayConfigReads(w.providerProfile, w.providerProfileAlsoAllow);
if (c) {
const e = detectImplicitProfileGrants({
globalTools: s,
agentTools: o,
includeGlobalSections: l === "global"
});
if (e.length > 0) {
const t = mergeAlsoAllowPolicy(resolveCoreToolProfilePolicy(c), S);
const n = createToolPolicyMatcher(t);
const i = [
w.globalPolicy,
w.globalProviderPolicy,
w.agentPolicy,
w.agentProviderPolicy,
mergeAlsoAllowPolicy(resolveCoreToolProfilePolicy(w.providerProfile), w.providerProfileAlsoAllow)
].map((e) => createToolPolicyMatcher(e));
const a = e.map((e) => ({
section: e.section,
grants: e.grants.filter((e) => !n(e) && i.every((t) => t(e)))
})).filter((e) => e.grants.length > 0);
const o = a.flatMap((e) => e.grants);
if (o.length > 0) logWarn(`tools policy: profile "${c}"${r ? ` (agent "${r}")` : ""} has configured tool sections (${a.map((e) => e.section).join(" / ")}) that no longer implicitly widen the profile. Add alsoAllow: [${o.map((e) => `"${e}"`).join(", ")}] explicitly if these tools should be available. See #47487.`);
}
}
return {
...w,
gatewayConfigReadAllowed: T
};
}
function throwUnavailableScheduledAccount(e) {
throw new Error(`Scheduled account "${e}" is unavailable. Re-add it to the channel configuration, or recreate this automation from the intended account.`);
}
/** Tool-building callers must stop before exposing a surface with unavailable authority. */
function resolveGroupToolPolicy(e) {
if (!e.config) return;
const t = resolveGroupContextFromSessionKey(e.sessionKey);
const n = resolveGroupContextFromSessionKey(e.spawnedBy);
const r = resolveTrustedGroupIdFromContexts({
groupId: e.groupId,
sessionContext: t,
spawnedContext: n
});
const i = normalizeUniqueSingleOrTrimmedStringList([
...t.groupIds ?? [],
...n.groupIds ?? [],
...buildScopedGroupIdCandidates(r.groupId)
]);
const a = t.channel ?? n.channel ?? e.messageProvider;
const o = normalizeMessageChannel(a);
const s = normalizeAccountId(e.accountId);
if (!o) return e.requireConfiguredAccount && s !== "default" ? throwUnavailableScheduledAccount(s) : void 0;
let c;
try {
c = getLoadedChannelPlugin(o);
} catch {
c = void 0;
}
if (e.requireConfiguredAccount && s !== "default") {
let t;
try {
t = c?.config.listAccountIds(e.config).some((e) => normalizeAccountId(e) === s) === true;
} catch {
t = false;
}
if (!t) throwUnavailableScheduledAccount(s);
}
if (i.length === 0) return;
for (const t of i) {
const n = c?.groups?.resolveToolPolicy?.({
cfg: e.config,
groupId: t,
groupChannel: r.dropped ? null : e.groupChannel,
groupSpace: r.dropped ? null : e.groupSpace,
accountId: s,
senderPolicyMode: e.senderPolicyMode,
senderId: e.senderId,
senderName: e.senderName,
senderUsername: e.senderUsername,
senderE164: e.senderE164
});
const i = pickSandboxToolPolicy(n);
if (i) return i;
}
const l = resolveChannelGroupToolsPolicy({
cfg: e.config,
channel: o,
messageProvider: o,
groupId: i[0],
groupIdCandidates: i.slice(1),
accountId: s,
senderPolicyMode: e.senderPolicyMode,
senderId: e.senderId,
senderName: e.senderName,
senderUsername: e.senderUsername,
senderE164: e.senderE164
});
return pickSandboxToolPolicy(l);
}
//#endregion
export { resolveSubagentToolPolicyForSession as a, resolveInheritedToolPolicyForSession as i, resolveEffectiveToolPolicy as n, resolveTrustedGroupId as o, resolveGroupToolPolicy as r, resolveConfiguredToolPolicies as t };