import { S as isSubagentSessionKey, d as normalizeMainKey, p as resolveAgentIdFromSessionKey, y as isAcpSessionKey } from "./session-key-DIUsVZjU.js";
import { d as stripThinkingTagsFromText, f as extractTextFromChatContent, l as stripDowngradedToolCallText, u as stripMinimaxToolCallXml } from "./pi-embedded-utils-BraP32ED.js";
import { S as sanitizeUserFacingText } from "./pi-embedded-helpers-CLkeTWAT.js";
import { n as callGateway } from "./call-C206Z-zx.js";

//#region src/agents/tools/sessions/sessions-resolution.ts
function resolveMainSessionAlias(cfg) {
	const mainKey = normalizeMainKey(cfg.session?.mainKey);
	const scope = cfg.session?.scope ?? "per-sender";
	return {
		mainKey,
		alias: scope === "global" ? "global" : mainKey,
		scope
	};
}
function resolveDisplaySessionKey(params) {
	if (params.key === params.alias) return "main";
	if (params.key === params.mainKey) return "main";
	return params.key;
}
function resolveInternalSessionKey(params) {
	if (params.key === "main") return params.alias;
	return params.key;
}
async function listSpawnedSessionKeys(params) {
	const limit = typeof params.limit === "number" && Number.isFinite(params.limit) ? Math.max(1, Math.floor(params.limit)) : 500;
	try {
		const list = await callGateway({
			method: "sessions.list",
			params: {
				includeGlobal: false,
				includeUnknown: false,
				limit,
				spawnedBy: params.requesterSessionKey
			}
		});
		const keys = (Array.isArray(list?.sessions) ? list.sessions : []).map((entry) => typeof entry?.key === "string" ? entry.key : "").map((value) => value.trim()).filter(Boolean);
		return new Set(keys);
	} catch {
		return /* @__PURE__ */ new Set();
	}
}
async function isRequesterSpawnedSessionVisible(params) {
	if (params.requesterSessionKey === params.targetSessionKey) return true;
	return (await listSpawnedSessionKeys({
		requesterSessionKey: params.requesterSessionKey,
		limit: params.limit
	})).has(params.targetSessionKey);
}
const SESSION_ID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
function looksLikeSessionId(value) {
	return SESSION_ID_RE.test(value.trim());
}
function looksLikeSessionKey(value) {
	const raw = value.trim();
	if (!raw) return false;
	if (raw === "main" || raw === "global" || raw === "unknown") return true;
	if (isAcpSessionKey(raw)) return true;
	if (raw.startsWith("agent:")) return true;
	if (raw.startsWith("cron:") || raw.startsWith("hook:")) return true;
	if (raw.startsWith("node-") || raw.startsWith("node:")) return true;
	if (raw.includes(":group:") || raw.includes(":channel:")) return true;
	return false;
}
function shouldResolveSessionIdInput(value) {
	return looksLikeSessionId(value) || !looksLikeSessionKey(value);
}
async function resolveSessionKeyFromSessionId(params) {
	try {
		const result = await callGateway({
			method: "sessions.resolve",
			params: {
				sessionId: params.sessionId,
				spawnedBy: params.restrictToSpawned ? params.requesterInternalKey : void 0,
				includeGlobal: !params.restrictToSpawned,
				includeUnknown: !params.restrictToSpawned
			}
		});
		const key = typeof result?.key === "string" ? result.key.trim() : "";
		if (!key) throw new Error(`Session not found: ${params.sessionId} (use the full sessionKey from sessions_list)`);
		return {
			ok: true,
			key,
			displayKey: resolveDisplaySessionKey({
				key,
				alias: params.alias,
				mainKey: params.mainKey
			}),
			resolvedViaSessionId: true
		};
	} catch (err) {
		if (params.restrictToSpawned) return {
			ok: false,
			status: "forbidden",
			error: `Session not visible from this sandboxed agent session: ${params.sessionId}`
		};
		return {
			ok: false,
			status: "error",
			error: (err instanceof Error ? err.message : String(err)) || `Session not found: ${params.sessionId} (use the full sessionKey from sessions_list)`
		};
	}
}
async function resolveSessionKeyFromKey(params) {
	try {
		const result = await callGateway({
			method: "sessions.resolve",
			params: {
				key: params.key,
				spawnedBy: params.restrictToSpawned ? params.requesterInternalKey : void 0
			}
		});
		const key = typeof result?.key === "string" ? result.key.trim() : "";
		if (!key) return null;
		return {
			ok: true,
			key,
			displayKey: resolveDisplaySessionKey({
				key,
				alias: params.alias,
				mainKey: params.mainKey
			}),
			resolvedViaSessionId: false
		};
	} catch {
		return null;
	}
}
async function resolveSessionReference(params) {
	const raw = params.sessionKey.trim();
	if (shouldResolveSessionIdInput(raw)) {
		const resolvedByKey = await resolveSessionKeyFromKey({
			key: raw,
			alias: params.alias,
			mainKey: params.mainKey,
			requesterInternalKey: params.requesterInternalKey,
			restrictToSpawned: params.restrictToSpawned
		});
		if (resolvedByKey) return resolvedByKey;
		return await resolveSessionKeyFromSessionId({
			sessionId: raw,
			alias: params.alias,
			mainKey: params.mainKey,
			requesterInternalKey: params.requesterInternalKey,
			restrictToSpawned: params.restrictToSpawned
		});
	}
	const resolvedKey = resolveInternalSessionKey({
		key: raw,
		alias: params.alias,
		mainKey: params.mainKey
	});
	return {
		ok: true,
		key: resolvedKey,
		displayKey: resolveDisplaySessionKey({
			key: resolvedKey,
			alias: params.alias,
			mainKey: params.mainKey
		}),
		resolvedViaSessionId: false
	};
}

//#endregion
//#region src/agents/tools/sessions/sessions-access.ts
function resolveSessionToolsVisibility(cfg) {
	const raw = cfg.tools?.sessions?.visibility;
	const value = typeof raw === "string" ? raw.trim().toLowerCase() : "";
	if (value === "self" || value === "tree" || value === "agent" || value === "all") return value;
	return "tree";
}
function resolveEffectiveSessionToolsVisibility(params) {
	const visibility = resolveSessionToolsVisibility(params.cfg);
	if (!params.sandboxed) return visibility;
	if ((params.cfg.agents?.defaults?.sandbox?.sessionToolsVisibility ?? "spawned") === "spawned" && visibility !== "tree") return "tree";
	return visibility;
}
function resolveSandboxSessionToolsVisibility(cfg) {
	return cfg.agents?.defaults?.sandbox?.sessionToolsVisibility ?? "spawned";
}
function resolveSandboxedSessionToolContext(params) {
	const { mainKey, alias } = resolveMainSessionAlias(params.cfg);
	const visibility = resolveSandboxSessionToolsVisibility(params.cfg);
	const requesterInternalKey = typeof params.agentSessionKey === "string" && params.agentSessionKey.trim() ? resolveInternalSessionKey({
		key: params.agentSessionKey,
		alias,
		mainKey
	}) : void 0;
	return {
		mainKey,
		alias,
		visibility,
		requesterInternalKey,
		effectiveRequesterKey: requesterInternalKey ?? alias,
		restrictToSpawned: params.sandboxed === true && visibility === "spawned" && !!requesterInternalKey && !isSubagentSessionKey(requesterInternalKey)
	};
}
function createAgentToAgentPolicy(cfg) {
	const a2a = cfg.tools?.agentToAgent;
	const enabled = a2a?.enabled !== false;
	const legacyAllow = Array.isArray(a2a?.allow) ? a2a.allow : [];
	const pairs = Array.isArray(a2a?.pairs) ? a2a.pairs : [];
	const mode = a2a?.mode ?? (legacyAllow.length > 0 ? "allow" : "open");
	const matchesPattern = (agentId, pattern) => {
		const raw = String(pattern ?? "").trim();
		if (!raw) return false;
		if (raw === "*") return true;
		if (!raw.includes("*")) return raw === agentId;
		const escaped = raw.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
		return new RegExp(`^${escaped.replaceAll("\\*", ".*")}$`, "i").test(agentId);
	};
	const matchesAllow = (agentId) => {
		if (mode === "open") return true;
		if (legacyAllow.length > 0) return legacyAllow.some((p) => matchesPattern(agentId, p));
		return pairs.some(([a, b]) => matchesPattern(agentId, a) || matchesPattern(agentId, b));
	};
	const isAllowed = (requesterAgentId, targetAgentId) => {
		if (requesterAgentId === targetAgentId) return true;
		if (!enabled) return false;
		if (mode === "open") return true;
		if (legacyAllow.length > 0 && pairs.length === 0) return legacyAllow.some((p) => matchesPattern(requesterAgentId, p)) && legacyAllow.some((p) => matchesPattern(targetAgentId, p));
		for (const [a, b] of pairs) if (mode === "one-way") {
			if (matchesPattern(requesterAgentId, a) && matchesPattern(targetAgentId, b)) return true;
		} else {
			if (matchesPattern(requesterAgentId, a) && matchesPattern(targetAgentId, b)) return true;
			if (matchesPattern(requesterAgentId, b) && matchesPattern(targetAgentId, a)) return true;
		}
		return false;
	};
	return {
		enabled,
		matchesAllow,
		isAllowed
	};
}
function actionPrefix(action) {
	if (action === "history") return "Session history";
	if (action === "send") return "Session send";
	return "Session list";
}
function a2aDisabledMessage(action) {
	if (action === "history") return "Agent-to-agent history is disabled. Set tools.agentToAgent.enabled=true to allow cross-agent access.";
	if (action === "send") return "Agent-to-agent messaging is disabled. Set tools.agentToAgent.enabled=true to allow cross-agent sends.";
	return "Agent-to-agent listing is disabled. Set tools.agentToAgent.enabled=true to allow cross-agent visibility.";
}
function a2aDeniedMessage(action) {
	if (action === "history") return "Agent-to-agent history denied by tools.agentToAgent.allow.";
	if (action === "send") return "Agent-to-agent messaging denied by tools.agentToAgent.allow.";
	return "Agent-to-agent listing denied by tools.agentToAgent.allow.";
}
function crossVisibilityMessage(action) {
	if (action === "history") return "Session history visibility is restricted. Set tools.sessions.visibility=all to allow cross-agent access.";
	if (action === "send") return "Session send visibility is restricted. Set tools.sessions.visibility=all to allow cross-agent access.";
	return "Session list visibility is restricted. Set tools.sessions.visibility=all to allow cross-agent access.";
}
function selfVisibilityMessage(action) {
	return `${actionPrefix(action)} visibility is restricted to the current session (tools.sessions.visibility=self).`;
}
function treeVisibilityMessage(action) {
	return `${actionPrefix(action)} visibility is restricted to the current session tree (tools.sessions.visibility=tree).`;
}
async function createSessionVisibilityGuard(params) {
	const requesterAgentId = resolveAgentIdFromSessionKey(params.requesterSessionKey);
	const spawnedKeys = params.visibility === "tree" ? await listSpawnedSessionKeys({ requesterSessionKey: params.requesterSessionKey }) : null;
	const check = (targetSessionKey) => {
		const targetAgentId = resolveAgentIdFromSessionKey(targetSessionKey);
		if (targetAgentId !== requesterAgentId) {
			if (params.action === "send") {
				if (!params.a2aPolicy.enabled) return {
					allowed: false,
					status: "forbidden",
					error: a2aDisabledMessage(params.action)
				};
				if (!params.a2aPolicy.isAllowed(requesterAgentId, targetAgentId)) return {
					allowed: false,
					status: "forbidden",
					error: a2aDeniedMessage(params.action)
				};
				return { allowed: true };
			}
			if (params.visibility !== "all") return {
				allowed: false,
				status: "forbidden",
				error: crossVisibilityMessage(params.action)
			};
			if (!params.a2aPolicy.enabled) return {
				allowed: false,
				status: "forbidden",
				error: a2aDisabledMessage(params.action)
			};
			if (!params.a2aPolicy.isAllowed(requesterAgentId, targetAgentId)) return {
				allowed: false,
				status: "forbidden",
				error: a2aDeniedMessage(params.action)
			};
			return { allowed: true };
		}
		if (params.visibility === "self" && targetSessionKey !== params.requesterSessionKey) return {
			allowed: false,
			status: "forbidden",
			error: selfVisibilityMessage(params.action)
		};
		if (params.visibility === "tree" && targetSessionKey !== params.requesterSessionKey && !spawnedKeys?.has(targetSessionKey)) return {
			allowed: false,
			status: "forbidden",
			error: treeVisibilityMessage(params.action)
		};
		return { allowed: true };
	};
	return { check };
}

//#endregion
//#region src/agents/tools/sessions/sessions-helpers.ts
function normalizeKey(value) {
	const trimmed = value?.trim();
	return trimmed ? trimmed : void 0;
}
function classifySessionKind(params) {
	const key = params.key;
	if (key === params.alias || key === params.mainKey) return "main";
	if (key.startsWith("cron:")) return "cron";
	if (key.startsWith("hook:")) return "hook";
	if (key.startsWith("node-") || key.startsWith("node:")) return "node";
	if (params.gatewayKind === "group") return "group";
	if (key.includes(":group:") || key.includes(":channel:")) return "group";
	return "other";
}
function deriveChannel(params) {
	if (params.kind === "cron" || params.kind === "hook" || params.kind === "node") return "internal";
	const channel = normalizeKey(params.channel ?? void 0);
	if (channel) return channel;
	const lastChannel = normalizeKey(params.lastChannel ?? void 0);
	if (lastChannel) return lastChannel;
	const parts = params.key.split(":").filter(Boolean);
	if (parts.length >= 3 && (parts[1] === "group" || parts[1] === "channel")) return parts[0];
	return "unknown";
}
function stripToolMessages(messages) {
	return messages.filter((msg) => {
		if (!msg || typeof msg !== "object") return true;
		const role = msg.role;
		return role !== "toolResult" && role !== "tool";
	});
}
/**
* Sanitize text content to strip tool call markers and thinking tags.
* This ensures user-facing text doesn't leak internal tool representations.
*/
function sanitizeTextContent(text) {
	if (!text) return text;
	return stripThinkingTagsFromText(stripDowngradedToolCallText(stripMinimaxToolCallXml(text)));
}
function extractAssistantText(message) {
	if (!message || typeof message !== "object") return;
	if (message.role !== "assistant") return;
	const content = message.content;
	if (!Array.isArray(content)) return;
	const joined = extractTextFromChatContent(content, {
		sanitizeText: sanitizeTextContent,
		joinWith: "",
		normalizeText: (text) => text.trim()
	}) ?? "";
	const stopReason = message.stopReason;
	const errorMessage = message.errorMessage;
	const errorContext = stopReason === "error" || typeof errorMessage === "string" && Boolean(errorMessage.trim());
	return joined ? sanitizeUserFacingText(joined, { errorContext }) : void 0;
}

//#endregion
export { stripToolMessages as a, resolveEffectiveSessionToolsVisibility as c, resolveDisplaySessionKey as d, resolveInternalSessionKey as f, shouldResolveSessionIdInput as h, sanitizeTextContent as i, resolveSandboxedSessionToolContext as l, resolveSessionReference as m, deriveChannel as n, createAgentToAgentPolicy as o, resolveMainSessionAlias as p, extractAssistantText as r, createSessionVisibilityGuard as s, classifySessionKind as t, isRequesterSpawnedSessionVisible as u };