import { d as readStringValue, i as normalizeLowercaseStringOrEmpty, o as normalizeOptionalLowercaseString, s as normalizeOptionalString } from "./string-coerce-CIT1-v_a.js";
import { b as truncateUtf16Safe, g as shortenHomeInString } from "./utils-CE5zxr9Z.js";
import { i as normalizeChannelId, t as getChannelPlugin } from "./registry-DAH3dnPp.js";
import "./plugins-g2B6w-qz.js";
import { l as normalizeToolName } from "./tool-policy-CCGIB_U8.js";
import { C as estimateToolResultReductionPotential, g as estimateMessageTokens, s as SAFETY_MARGIN, u as estimateMessagesTokens } from "./tool-schema-runtime-oH5gpy2r.js";
import { t as splitMediaFromOutput } from "./parse-HCVRGfCF.js";
import { a as normalizeTargetForProvider } from "./target-normalization-e6EndsBb.js";
import { r as resolveToolDisplay } from "./tool-display-C_AaHeLj.js";
import { t as collectTextContentBlocks } from "./content-blocks-CE9KLQo7.js";
import { i as pluginRegistrationContractRegistry } from "./registry-DMvaVAzc.js";
//#region src/auto-reply/tool-meta.ts
function shortenMeta(meta) {
	if (!meta) return meta;
	return shortenHomeInString(meta);
}
function formatToolAggregate(toolName, metas, options) {
	const filtered = (metas ?? []).filter(Boolean).map(shortenMeta);
	const display = resolveToolDisplay({ name: toolName });
	const prefix = `${display.emoji} ${display.label}`;
	if (!filtered.length) return prefix;
	const rawSegments = [];
	const grouped = {};
	for (const m of filtered) {
		if (!isPathLike(m)) {
			rawSegments.push(m);
			continue;
		}
		if (m.includes("→")) {
			rawSegments.push(m);
			continue;
		}
		const parts = m.split("/");
		if (parts.length > 1) {
			const dir = parts.slice(0, -1).join("/");
			const base = parts.at(-1) ?? m;
			if (!grouped[dir]) grouped[dir] = [];
			grouped[dir].push(base);
		} else {
			if (!grouped["."]) grouped["."] = [];
			grouped["."].push(m);
		}
	}
	const segments = Object.entries(grouped).map(([dir, files]) => {
		const brace = files.length > 1 ? `{${files.join(", ")}}` : files[0];
		if (dir === ".") return brace;
		return `${dir}/${brace}`;
	});
	return `${prefix}: ${formatMetaForDisplay(toolName, [...rawSegments, ...segments].join("; "), options?.markdown)}`;
}
function formatMetaForDisplay(toolName, meta, markdown) {
	const normalized = normalizeLowercaseStringOrEmpty(toolName);
	if (normalized === "exec" || normalized === "bash") {
		const { flags, body } = splitExecFlags(meta);
		if (flags.length > 0) {
			if (!body) return flags.join(" · ");
			return `${flags.join(" · ")} · ${maybeWrapMarkdown(body, markdown)}`;
		}
	}
	return maybeWrapMarkdown(meta, markdown);
}
function splitExecFlags(meta) {
	const parts = meta.split(" · ").map((part) => part.trim()).filter(Boolean);
	if (parts.length === 0) return {
		flags: [],
		body: ""
	};
	const flags = [];
	const bodyParts = [];
	for (const part of parts) {
		if (part === "elevated" || part === "pty") {
			flags.push(part);
			continue;
		}
		bodyParts.push(part);
	}
	return {
		flags,
		body: bodyParts.join(" · ")
	};
}
function isPathLike(value) {
	if (!value) return false;
	if (value.includes(" ")) return false;
	if (value.includes("://")) return false;
	if (value.includes("·")) return false;
	if (value.includes("&&") || value.includes("||")) return false;
	return /^~?(\/[^\s]+)+$/.test(value);
}
function maybeWrapMarkdown(value, markdown) {
	if (!markdown) return value;
	if (value.includes("`")) return value;
	return `\`${value}\``;
}
//#endregion
//#region src/agents/pi-embedded-messaging.ts
const CORE_MESSAGING_TOOLS = new Set(["sessions_send", "message"]);
function isMessagingTool(toolName) {
	if (CORE_MESSAGING_TOOLS.has(toolName)) return true;
	const providerId = normalizeChannelId(toolName);
	return Boolean(providerId && getChannelPlugin(providerId)?.actions);
}
function isMessagingToolSendAction(toolName, args) {
	const action = normalizeOptionalString(args.action) ?? "";
	if (toolName === "sessions_send") return true;
	if (toolName === "message") return action === "send" || action === "thread-reply";
	const providerId = normalizeChannelId(toolName);
	if (!providerId) return false;
	const plugin = getChannelPlugin(providerId);
	if (!plugin?.actions?.extractToolSend) return false;
	return Boolean(plugin.actions.extractToolSend({ args })?.to);
}
//#endregion
//#region src/agents/pi-embedded-subscribe.tools.ts
const TOOL_RESULT_MAX_CHARS = 8e3;
const TOOL_ERROR_MAX_CHARS = 400;
function truncateToolText(text) {
	if (text.length <= TOOL_RESULT_MAX_CHARS) return text;
	return `${truncateUtf16Safe(text, TOOL_RESULT_MAX_CHARS)}\n…(truncated)…`;
}
function normalizeToolErrorText(text) {
	const trimmed = text.trim();
	if (!trimmed) return;
	const firstLine = trimmed.split(/\r?\n/)[0]?.trim() ?? "";
	if (!firstLine) return;
	return firstLine.length > TOOL_ERROR_MAX_CHARS ? `${truncateUtf16Safe(firstLine, TOOL_ERROR_MAX_CHARS)}…` : firstLine;
}
function isErrorLikeStatus(status) {
	const normalized = normalizeOptionalLowercaseString(status);
	if (!normalized) return false;
	if (normalized === "0" || normalized === "ok" || normalized === "success" || normalized === "completed" || normalized === "running") return false;
	return /error|fail|timeout|timed[_\s-]?out|denied|cancel|invalid|forbidden/.test(normalized);
}
function readErrorCandidate(value) {
	if (typeof value === "string") return normalizeToolErrorText(value);
	if (!value || typeof value !== "object") return;
	const record = value;
	if (typeof record.message === "string") return normalizeToolErrorText(record.message);
	if (typeof record.error === "string") return normalizeToolErrorText(record.error);
}
function extractErrorField(value) {
	if (!value || typeof value !== "object") return;
	const record = value;
	const direct = readErrorCandidate(record.error) ?? readErrorCandidate(record.message) ?? readErrorCandidate(record.reason);
	if (direct) return direct;
	const status = normalizeOptionalString(record.status) ?? "";
	if (!status || !isErrorLikeStatus(status)) return;
	return normalizeToolErrorText(status);
}
function sanitizeToolResult(result) {
	if (!result || typeof result !== "object") return result;
	const record = result;
	const content = Array.isArray(record.content) ? record.content : null;
	if (!content) return record;
	const sanitized = content.map((item) => {
		if (!item || typeof item !== "object") return item;
		const entry = item;
		const type = readStringValue(entry.type);
		if (type === "text" && typeof entry.text === "string") return {
			...entry,
			text: truncateToolText(entry.text)
		};
		if (type === "image") {
			const data = readStringValue(entry.data);
			const bytes = data ? data.length : void 0;
			const cleaned = { ...entry };
			delete cleaned.data;
			return {
				...cleaned,
				bytes,
				omitted: true
			};
		}
		return entry;
	});
	return {
		...record,
		content: sanitized
	};
}
function extractToolResultText(result) {
	if (!result || typeof result !== "object") return;
	const texts = collectTextContentBlocks(result.content).map((item) => {
		const trimmed = item.trim();
		return trimmed ? trimmed : void 0;
	}).filter((value) => Boolean(value));
	if (texts.length === 0) return;
	return texts.join("\n");
}
const TRUSTED_TOOL_RESULT_MEDIA = new Set([
	"agents_list",
	"apply_patch",
	"browser",
	"canvas",
	"cron",
	"edit",
	"exec",
	"gateway",
	"image",
	"image_generate",
	"memory_get",
	"memory_search",
	"message",
	"music_generate",
	"nodes",
	"process",
	"read",
	"session_status",
	"sessions_history",
	"sessions_list",
	"sessions_send",
	"sessions_spawn",
	"subagents",
	"tts",
	"video_generate",
	"web_fetch",
	"web_search",
	"x_search",
	"write"
]);
const TRUSTED_BUNDLED_PLUGIN_MEDIA_TOOLS = new Set(pluginRegistrationContractRegistry.flatMap((entry) => entry.toolNames));
const HTTP_URL_RE = /^https?:\/\//i;
function readToolResultDetails(result) {
	if (!result || typeof result !== "object") return;
	const record = result;
	return record.details && typeof record.details === "object" && !Array.isArray(record.details) ? record.details : void 0;
}
function readToolResultStatus(result) {
	const status = readToolResultDetails(result)?.status;
	return normalizeOptionalLowercaseString(status);
}
function isExternalToolResult(result) {
	const details = readToolResultDetails(result);
	if (!details) return false;
	return typeof details.mcpServer === "string" || typeof details.mcpTool === "string";
}
function isToolResultMediaTrusted(toolName, result) {
	if (!toolName || isExternalToolResult(result)) return false;
	const normalized = normalizeToolName(toolName);
	return TRUSTED_TOOL_RESULT_MEDIA.has(normalized) || TRUSTED_BUNDLED_PLUGIN_MEDIA_TOOLS.has(normalized);
}
function filterToolResultMediaUrls(toolName, mediaUrls, result) {
	if (mediaUrls.length === 0) return mediaUrls;
	if (isToolResultMediaTrusted(toolName, result)) return mediaUrls;
	return mediaUrls.filter((url) => HTTP_URL_RE.test(url.trim()));
}
function readToolResultDetailsMedia(result) {
	const details = readToolResultDetails(result);
	return details?.media && typeof details.media === "object" && !Array.isArray(details.media) ? details.media : void 0;
}
function collectStructuredMediaUrls(media) {
	const urls = [];
	if (typeof media.mediaUrl === "string" && media.mediaUrl.trim()) urls.push(media.mediaUrl.trim());
	if (Array.isArray(media.mediaUrls)) urls.push(...media.mediaUrls.filter((value) => typeof value === "string").map((value) => value.trim()).filter(Boolean));
	return Array.from(new Set(urls));
}
function extractToolResultMediaArtifact(result) {
	if (!result || typeof result !== "object") return;
	const record = result;
	const detailsMedia = readToolResultDetailsMedia(record);
	if (detailsMedia) {
		const mediaUrls = collectStructuredMediaUrls(detailsMedia);
		if (mediaUrls.length > 0) return {
			mediaUrls,
			...detailsMedia.audioAsVoice === true ? { audioAsVoice: true } : {}
		};
	}
	const content = Array.isArray(record.content) ? record.content : null;
	if (!content) return;
	const paths = [];
	let hasImageContent = false;
	for (const item of content) {
		if (!item || typeof item !== "object") continue;
		const entry = item;
		if (entry.type === "image") {
			hasImageContent = true;
			continue;
		}
		if (entry.type === "text" && typeof entry.text === "string") {
			const parsed = splitMediaFromOutput(entry.text);
			if (parsed.mediaUrls?.length) paths.push(...parsed.mediaUrls);
		}
	}
	if (paths.length > 0) return { mediaUrls: paths };
	if (hasImageContent) {
		const details = record.details;
		const p = normalizeOptionalString(details?.path) ?? "";
		if (p) return { mediaUrls: [p] };
	}
}
function isToolResultError(result) {
	const normalized = readToolResultStatus(result);
	if (!normalized) return false;
	return normalized === "error" || normalized === "timeout";
}
function isToolResultTimedOut(result) {
	if (readToolResultStatus(result) === "timeout") return true;
	return readToolResultDetails(result)?.timedOut === true;
}
function extractToolErrorMessage(result) {
	if (!result || typeof result !== "object") return;
	const record = result;
	const fromDetails = extractErrorField(record.details);
	if (fromDetails) return fromDetails;
	const fromRoot = extractErrorField(record);
	if (fromRoot) return fromRoot;
	const text = extractToolResultText(result);
	if (!text) return;
	try {
		const fromJson = extractErrorField(JSON.parse(text));
		if (fromJson) return fromJson;
	} catch {}
	return normalizeToolErrorText(text);
}
function resolveMessageToolTarget(args) {
	const toRaw = readStringValue(args.to);
	if (toRaw) return toRaw;
	return readStringValue(args.target);
}
function extractMessagingToolSend(toolName, args) {
	const action = normalizeOptionalString(args.action) ?? "";
	const accountId = normalizeOptionalString(args.accountId);
	if (toolName === "message") {
		if (action !== "send" && action !== "thread-reply") return;
		const toRaw = resolveMessageToolTarget(args);
		if (!toRaw) return;
		const providerRaw = normalizeOptionalString(args.provider) ?? "";
		const channelRaw = normalizeOptionalString(args.channel) ?? "";
		const providerHint = providerRaw || channelRaw;
		const provider = (providerHint ? normalizeChannelId(providerHint) : null) ?? normalizeOptionalLowercaseString(providerHint) ?? "message";
		const to = normalizeTargetForProvider(provider, toRaw);
		return to ? {
			tool: toolName,
			provider,
			accountId,
			to
		} : void 0;
	}
	const providerId = normalizeChannelId(toolName);
	if (!providerId) return;
	const extracted = getChannelPlugin(providerId)?.actions?.extractToolSend?.({ args });
	if (!extracted?.to) return;
	const to = normalizeTargetForProvider(providerId, extracted.to);
	return to ? {
		tool: toolName,
		provider: providerId,
		accountId: extracted.accountId ?? accountId,
		to
	} : void 0;
}
//#endregion
//#region src/agents/pi-embedded-runner/run/attempt.tool-run-context.ts
function buildEmbeddedAttemptToolRunContext(params) {
	return {
		trigger: params.trigger,
		memoryFlushWritePath: params.memoryFlushWritePath
	};
}
//#endregion
//#region src/agents/pi-embedded-runner/run/preemptive-compaction.ts
const PREEMPTIVE_OVERFLOW_ERROR_TEXT = "Context overflow: prompt too large for the model (precheck).";
const TRUNCATION_ROUTE_BUFFER_TOKENS = 512;
function estimatePrePromptTokens(params) {
	const { messages, systemPrompt, prompt, lastUsageTokens } = params;
	const syntheticMessages = [];
	if (typeof systemPrompt === "string" && systemPrompt.trim().length > 0) syntheticMessages.push({
		role: "system",
		content: systemPrompt,
		timestamp: 0
	});
	syntheticMessages.push({
		role: "user",
		content: prompt,
		timestamp: 0
	});
	const syntheticTokens = syntheticMessages.reduce((sum, message) => sum + estimateMessageTokens(message), 0);
	if (lastUsageTokens !== void 0 && lastUsageTokens > 0) {
		const lastUsageIndex = findLastAssistantUsageIndex(messages);
		let trailingTokens = 0;
		if (lastUsageIndex !== null) for (let i = lastUsageIndex + 1; i < messages.length; i++) trailingTokens += estimateMessageTokens(messages[i]);
		else trailingTokens = estimateMessagesTokens(messages);
		return Math.max(0, Math.ceil((lastUsageTokens + trailingTokens + syntheticTokens) * SAFETY_MARGIN));
	}
	const estimated = estimateMessagesTokens(messages) + syntheticTokens;
	return Math.max(0, Math.ceil(estimated * SAFETY_MARGIN));
}
function findLastAssistantUsageIndex(messages) {
	for (let i = messages.length - 1; i >= 0; i--) {
		const msg = messages[i];
		if (msg.role === "assistant") {
			const usage = msg.usage;
			const stopReason = msg.stopReason;
			if (usage && typeof usage === "object" && stopReason !== "aborted" && stopReason !== "error") return i;
		}
	}
	return null;
}
function shouldPreemptivelyCompactBeforePrompt(params) {
	const estimatedPromptTokens = estimatePrePromptTokens({
		messages: params.messages,
		systemPrompt: params.systemPrompt,
		prompt: params.prompt,
		lastUsageTokens: params.lastUsageTokens
	});
	const promptBudgetBeforeReserve = Math.max(1, Math.floor(params.contextTokenBudget) - Math.max(0, Math.floor(params.reserveTokens)));
	const overflowTokens = Math.max(0, estimatedPromptTokens - promptBudgetBeforeReserve);
	const toolResultPotential = estimateToolResultReductionPotential({
		messages: params.messages,
		contextWindowTokens: params.contextTokenBudget
	});
	const CONSERVATIVE_CHARS_PER_TOKEN = 2;
	const overflowChars = overflowTokens * CONSERVATIVE_CHARS_PER_TOKEN;
	const truncationBufferChars = TRUNCATION_ROUTE_BUFFER_TOKENS * CONSERVATIVE_CHARS_PER_TOKEN;
	const truncateOnlyThresholdChars = Math.max(overflowChars + truncationBufferChars, Math.ceil(overflowChars * 1.5));
	const toolResultReducibleChars = toolResultPotential.maxReducibleChars;
	let route = "fits";
	if (overflowTokens > 0) if (toolResultReducibleChars <= 0) route = "compact_only";
	else if (toolResultReducibleChars >= truncateOnlyThresholdChars) route = "truncate_tool_results_only";
	else route = "compact_then_truncate";
	return {
		route,
		shouldCompact: route === "compact_only" || route === "compact_then_truncate",
		estimatedPromptTokens,
		promptBudgetBeforeReserve,
		overflowTokens,
		toolResultReducibleChars
	};
}
//#endregion
export { extractToolErrorMessage as a, filterToolResultMediaUrls as c, sanitizeToolResult as d, isMessagingTool as f, extractMessagingToolSend as i, isToolResultError as l, formatToolAggregate as m, shouldPreemptivelyCompactBeforePrompt as n, extractToolResultMediaArtifact as o, isMessagingToolSendAction as p, buildEmbeddedAttemptToolRunContext as r, extractToolResultText as s, PREEMPTIVE_OVERFLOW_ERROR_TEXT as t, isToolResultTimedOut as u };
