import { p as resolveAgentIdFromSessionKey, w as resolveThreadParentSessionKey } from "./session-key-DIUsVZjU.js";
import { r as resolveAgentConfig } from "./agent-scope-CVnlY0oG.js";
import { D as AGENT_TYPE_SCOPES, O as ALL_SCOPES, k as DEFAULT_AGENT_TYPE } from "./config-DJ3A5x_1.js";
import { C as compileGlobPatterns, b as normalizeToolName, p as TOOL_GROUPS, v as expandToolGroups, w as matchesAnyGlobPattern } from "./sandbox-C5rKvtrA.js";
import { l as normalizeMessageChannel } from "./message-channel-DSU96OKy.js";
import { o as resolveChannelGroupToolsPolicy, t as getChannelDock } from "./dock-DY0TWaYa.js";
import { r as normalizeChannelId } from "./plugins-DYgcd4QJ.js";

//#region src/config/commands.ts
function resolveAutoDefault(providerId) {
	const id = normalizeChannelId(providerId);
	if (!id) return false;
	if (id === "discord" || id === "telegram") return true;
	if (id === "slack") return false;
	return false;
}
function resolveNativeSkillsEnabled(params) {
	return resolveNativeCommandSetting(params);
}
function resolveNativeCommandsEnabled(params) {
	return resolveNativeCommandSetting(params);
}
function resolveNativeCommandSetting(params) {
	const { providerId, providerSetting, globalSetting } = params;
	const setting = providerSetting === void 0 ? globalSetting : providerSetting;
	if (setting === true) return true;
	if (setting === false) return false;
	return resolveAutoDefault(providerId);
}
function isNativeCommandsExplicitlyDisabled(params) {
	const { providerSetting, globalSetting } = params;
	if (providerSetting === false) return true;
	if (providerSetting === void 0) return globalSetting === false;
	return false;
}

//#endregion
//#region src/agents/identity/scope-resolver.ts
/**
* Maps each AgentScope to the tool names it enables.
* Uses TOOL_GROUPS where possible; falls back to explicit tool name lists.
*/
const SCOPE_TO_TOOL_NAMES = {
	"fs:read": ["read"],
	"fs:write": [
		"write",
		"edit",
		"apply_patch"
	],
	exec: TOOL_GROUPS["group:runtime"] ?? ["exec", "process"],
	sessions: TOOL_GROUPS["group:sessions"] ?? [
		"session_status",
		"sessions_history",
		"sessions_list",
		"sessions_send",
		"sessions_spawn",
		"subagents"
	],
	memory: [
		"remember",
		"recall_entity",
		"find_related",
		"forget",
		"search_facts"
	],
	web: TOOL_GROUPS["group:web"] ?? ["web_fetch", "web_search"],
	messaging: TOOL_GROUPS["group:messaging"] ?? ["message"],
	gateway: [...TOOL_GROUPS["group:automation"] ?? ["cron", "gateway"], "agents_list"],
	browser: TOOL_GROUPS["group:ui"] ?? ["browser", "canvas"],
	media: [
		"image",
		"tts",
		"summarize"
	],
	gog: TOOL_GROUPS["group:gog"] ?? [
		"gog_auth_revoke",
		"gog_auth_start",
		"gog_auth_status",
		"gog_exec"
	],
	nodes: TOOL_GROUPS["group:nodes"] ?? ["nodes"]
};
/**
* All tool names declared across scopes. Includes conditionally-registered tools
* (e.g. apply_patch) that may not always be present in the tool list but are still
* legitimate core tool names — not plugin tools or typos.
*/
const SCOPE_DECLARED_TOOL_NAMES = new Set(Object.values(SCOPE_TO_TOOL_NAMES).flat());
/**
* Resolve effective scopes for an agent type with optional overrides.
*
* - Restricted/admin agents: addScopes that aren't already in the base set are
*   rejected with a warning (escalation blocked).
* - Standard agents: addScopes can add any valid scope freely.
* - removeScopes always works for all types (further restriction is always ok).
*/
function resolveEffectiveScopes(agentType, overrides) {
	const baseScopes = new Set(AGENT_TYPE_SCOPES[agentType]);
	const warnings = [];
	const validScopeSet = new Set(ALL_SCOPES);
	if (overrides?.addScopes?.length) {
		const validAdds = overrides.addScopes.filter((s) => validScopeSet.has(s));
		if (agentType === "restricted" || agentType === "admin") {
			const illegal = validAdds.filter((s) => !baseScopes.has(s));
			if (illegal.length > 0) warnings.push(`Agent type "${agentType}" cannot escalate scopes: ${illegal.join(", ")} ignored`);
		} else for (const scope of validAdds) baseScopes.add(scope);
	}
	if (overrides?.removeScopes?.length) {
		for (const scope of overrides.removeScopes) if (validScopeSet.has(scope)) baseScopes.delete(scope);
	}
	return {
		scopes: [...baseScopes],
		warnings
	};
}
/**
* Convert a set of effective scopes into a ToolPolicyLike for the pipeline.
*
* - All scopes present: returns { allow: undefined, deny: undefined } (no restrictions, admin).
* - Otherwise: builds explicit allowlist from included scopes' tool groups, and
*   deny list from excluded scopes' tool groups.
* - CRITICAL: Never returns empty allow array (empty allow means "allow all").
*/
function scopesToToolPolicy(scopes) {
	const scopeSet = new Set(scopes);
	if (ALL_SCOPES.every((s) => scopeSet.has(s))) return {
		allow: void 0,
		deny: void 0
	};
	const allowTools = [];
	const denyTools = [];
	for (const scope of ALL_SCOPES) {
		const tools = SCOPE_TO_TOOL_NAMES[scope];
		if (scopeSet.has(scope)) allowTools.push(...tools);
		else denyTools.push(...tools);
	}
	return {
		allow: allowTools.length > 0 ? [...new Set(allowTools)] : void 0,
		deny: denyTools.length > 0 ? [...new Set(denyTools)] : void 0
	};
}
/**
* Build a ToolPolicyPipelineStep from agent type + scope overrides.
* Designed to be the FIRST step in the tool policy pipeline.
*/
function resolveAgentTypePolicy(params) {
	const { scopes, warnings } = resolveEffectiveScopes(params.agentType, {
		addScopes: params.addScopes,
		removeScopes: params.removeScopes
	});
	for (const w of warnings) params.warn(w);
	const policy = scopesToToolPolicy(scopes);
	return {
		policy: policy.allow === void 0 && policy.deny === void 0 ? void 0 : policy,
		label: `agentType (${params.agentType})`,
		stripPluginOnlyAllowlist: true
	};
}
/** Returns true if the agent type is 'restricted'. */
function isRestrictedAgent(agentType) {
	return agentType === "restricted";
}
/** Returns true if the agent type should force workspaceOnly filesystem access. */
function shouldForceWorkspaceOnly(agentType) {
	return agentType === "restricted";
}

//#endregion
//#region src/agents/tool-governance/sandbox-tool-policy.ts
function unionAllow(base, extra) {
	if (!Array.isArray(extra) || extra.length === 0) return base;
	if (!Array.isArray(base) || base.length === 0) return Array.from(new Set(["*", ...extra]));
	return Array.from(new Set([...base, ...extra]));
}
function pickSandboxToolPolicy(config) {
	if (!config) return;
	const allow = Array.isArray(config.allow) ? unionAllow(config.allow, config.alsoAllow) : Array.isArray(config.alsoAllow) && config.alsoAllow.length > 0 ? unionAllow(void 0, config.alsoAllow) : void 0;
	const deny = Array.isArray(config.deny) ? config.deny : void 0;
	if (!allow && !deny) return;
	return {
		allow,
		deny
	};
}

//#endregion
//#region src/agents/pi-tools/pi-tools.policy.ts
function makeToolPolicyMatcher(policy) {
	const deny = compileGlobPatterns({
		raw: expandToolGroups(policy.deny ?? []),
		normalize: normalizeToolName
	});
	const allow = compileGlobPatterns({
		raw: expandToolGroups(policy.allow ?? []),
		normalize: normalizeToolName
	});
	return (name) => {
		const normalized = normalizeToolName(name);
		if (matchesAnyGlobPattern(normalized, deny)) return false;
		if (allow.length === 0) return true;
		if (matchesAnyGlobPattern(normalized, allow)) return true;
		if (normalized === "apply_patch" && matchesAnyGlobPattern("exec", allow)) return true;
		return false;
	};
}
/**
* Tools always denied for sub-agents regardless of depth.
* These are system-level or interactive tools that sub-agents should never use.
*/
const SUBAGENT_TOOL_DENY_ALWAYS = [
	"gateway",
	"agents_list",
	"whatsapp_login",
	"session_status",
	"cron",
	"memory_search",
	"memory_get",
	"sessions_send"
];
/**
* Additional tools denied for leaf sub-agents (depth >= maxSpawnDepth).
* These are tools that only make sense for orchestrator sub-agents that can spawn children.
*/
const SUBAGENT_TOOL_DENY_LEAF = [
	"sessions_list",
	"sessions_history",
	"sessions_spawn"
];
/**
* Build the deny list for a sub-agent at a given depth.
*
* - Depth 1 with maxSpawnDepth >= 2 (orchestrator): allowed to use sessions_spawn,
*   subagents, sessions_list, sessions_history so it can manage its children.
* - Depth >= maxSpawnDepth (leaf): denied sessions_spawn and
*   session management tools. Still allowed subagents (for list/status visibility).
*/
function resolveSubagentDenyList(depth, maxSpawnDepth) {
	if (depth >= Math.max(1, Math.floor(maxSpawnDepth))) return [...SUBAGENT_TOOL_DENY_ALWAYS, ...SUBAGENT_TOOL_DENY_LEAF];
	return [...SUBAGENT_TOOL_DENY_ALWAYS];
}
function resolveSubagentToolPolicy(cfg, depth, parentAgentType) {
	const configured = cfg?.tools?.subagents?.tools;
	const maxSpawnDepth = cfg?.agents?.defaults?.subagents?.maxSpawnDepth ?? 1;
	const deny = [...resolveSubagentDenyList(typeof depth === "number" && depth >= 0 ? depth : 1, maxSpawnDepth), ...Array.isArray(configured?.deny) ? configured.deny : []];
	if (parentAgentType === "restricted") {
		const { scopes: restrictedScopes } = resolveEffectiveScopes("restricted");
		const restrictedPolicy = scopesToToolPolicy(restrictedScopes);
		if (restrictedPolicy.deny) {
			for (const tool of restrictedPolicy.deny) if (!deny.includes(tool)) deny.push(tool);
		}
	}
	return {
		allow: Array.isArray(configured?.allow) ? configured.allow : void 0,
		deny
	};
}
function isToolAllowedByPolicyName(name, policy) {
	if (!policy) return true;
	return makeToolPolicyMatcher(policy)(name);
}
function filterToolsByPolicy(tools, policy) {
	if (!policy) return tools;
	const matcher = makeToolPolicyMatcher(policy);
	return tools.filter((tool) => matcher(tool.name));
}
function normalizeProviderKey(value) {
	return value.trim().toLowerCase();
}
function resolveGroupContextFromSessionKey(sessionKey) {
	const raw = (sessionKey ?? "").trim();
	if (!raw) return {};
	const parts = (resolveThreadParentSessionKey(raw) ?? raw).split(":").filter(Boolean);
	let body = parts[0] === "agent" ? parts.slice(2) : parts;
	if (body[0] === "subagent") body = body.slice(1);
	if (body.length < 3) return {};
	const [channel, kind, ...rest] = body;
	if (kind !== "group" && kind !== "channel") return {};
	const groupId = rest.join(":").trim();
	if (!groupId) return {};
	return {
		channel: channel.trim().toLowerCase(),
		groupId
	};
}
function resolveProviderToolPolicy(params) {
	const provider = params.modelProvider?.trim();
	if (!provider || !params.byProvider) return;
	const entries = Object.entries(params.byProvider);
	if (entries.length === 0) return;
	const lookup = /* @__PURE__ */ new Map();
	for (const [key, value] of entries) {
		const normalized = normalizeProviderKey(key);
		if (!normalized) continue;
		lookup.set(normalized, value);
	}
	const normalizedProvider = normalizeProviderKey(provider);
	const rawModelId = params.modelId?.trim().toLowerCase();
	const fullModelId = rawModelId && !rawModelId.includes("/") ? `${normalizedProvider}/${rawModelId}` : rawModelId;
	const candidates = [...fullModelId ? [fullModelId] : [], normalizedProvider];
	for (const key of candidates) {
		const match = lookup.get(key);
		if (match) return match;
	}
}
function resolveEffectiveToolPolicy(params) {
	const agentId = params.sessionKey ? resolveAgentIdFromSessionKey(params.sessionKey) : void 0;
	const agentConfig = params.config && agentId ? resolveAgentConfig(params.config, agentId) : void 0;
	const agentTools = agentConfig?.tools;
	const globalTools = params.config?.tools;
	const agentType = agentConfig?.agentType ?? params.config?.agents?.defaults?.agentType ?? DEFAULT_AGENT_TYPE;
	const scopeOverrides = agentConfig?.scopes;
	const warnFn = params.warn ?? (() => {});
	const agentTypeStep = resolveAgentTypePolicy({
		agentType,
		addScopes: scopeOverrides?.addScopes,
		removeScopes: scopeOverrides?.removeScopes,
		warn: warnFn
	});
	const profile = agentTools?.profile ?? globalTools?.profile;
	const providerPolicy = resolveProviderToolPolicy({
		byProvider: globalTools?.byProvider,
		modelProvider: params.modelProvider,
		modelId: params.modelId
	});
	const agentProviderPolicy = resolveProviderToolPolicy({
		byProvider: agentTools?.byProvider,
		modelProvider: params.modelProvider,
		modelId: params.modelId
	});
	return {
		agentId,
		agentType,
		agentTypeStep,
		globalPolicy: pickSandboxToolPolicy(globalTools),
		globalProviderPolicy: pickSandboxToolPolicy(providerPolicy),
		agentPolicy: pickSandboxToolPolicy(agentTools),
		agentProviderPolicy: pickSandboxToolPolicy(agentProviderPolicy),
		profile,
		providerProfile: agentProviderPolicy?.profile ?? providerPolicy?.profile,
		profileAlsoAllow: Array.isArray(agentTools?.alsoAllow) ? agentTools?.alsoAllow : Array.isArray(globalTools?.alsoAllow) ? globalTools?.alsoAllow : void 0,
		providerProfileAlsoAllow: Array.isArray(agentProviderPolicy?.alsoAllow) ? agentProviderPolicy?.alsoAllow : Array.isArray(providerPolicy?.alsoAllow) ? providerPolicy?.alsoAllow : void 0
	};
}
function resolveGroupToolPolicy(params) {
	if (!params.config) return;
	const sessionContext = resolveGroupContextFromSessionKey(params.sessionKey);
	const spawnedContext = resolveGroupContextFromSessionKey(params.spawnedBy);
	const groupId = params.groupId ?? sessionContext.groupId ?? spawnedContext.groupId;
	if (!groupId) return;
	const channel = normalizeMessageChannel(params.messageProvider ?? sessionContext.channel ?? spawnedContext.channel);
	if (!channel) return;
	let dock;
	try {
		dock = getChannelDock(channel);
	} catch {
		dock = void 0;
	}
	return pickSandboxToolPolicy(dock?.groups?.resolveToolPolicy?.({
		cfg: params.config,
		groupId,
		groupChannel: params.groupChannel,
		groupSpace: params.groupSpace,
		accountId: params.accountId,
		senderId: params.senderId,
		senderName: params.senderName,
		senderUsername: params.senderUsername,
		senderE164: params.senderE164
	}) ?? resolveChannelGroupToolsPolicy({
		cfg: params.config,
		channel,
		groupId,
		accountId: params.accountId,
		senderId: params.senderId,
		senderName: params.senderName,
		senderUsername: params.senderUsername,
		senderE164: params.senderE164
	}));
}
function isToolAllowedByPolicies(name, policies) {
	return policies.every((policy) => isToolAllowedByPolicyName(name, policy));
}

//#endregion
export { resolveSubagentToolPolicy as a, isRestrictedAgent as c, resolveNativeCommandsEnabled as d, resolveNativeSkillsEnabled as f, resolveGroupToolPolicy as i, shouldForceWorkspaceOnly as l, isToolAllowedByPolicies as n, pickSandboxToolPolicy as o, resolveEffectiveToolPolicy as r, SCOPE_DECLARED_TOOL_NAMES as s, filterToolsByPolicy as t, isNativeCommandsExplicitlyDisabled as u };