import "./tool-display-B7qTeoCS.js";
import "./paths-D4_LjrY7.js";
import { D as truncateUtf16Safe } from "./utils-BnlaT0eO.js";
import "./theme-CG-K7m8u.js";
import "./thinking-CKGMvVgd.js";
import "./subsystem-ocBR131w.js";
import "./runtime-CRvfzclG.js";
import "./exec-CZr_EJHt.js";
import "./agent-scope-CVnlY0oG.js";
import "./model-selection-p6J3l4qF.js";
import "./github-copilot-token-CjSKohyA.js";
import "./emitter-oHo8y9ow.js";
import "./sqlite-wYNyDR1B.js";
import "./reliability-Dl7hbRzF.js";
import "./boolean-DGGu1sGA.js";
import "./env-CvUd308i.js";
import "./validation-p1IK70TM.js";
import { o as loadConfig } from "./config-DJ3A5x_1.js";
import "./manifest-registry-U2EDFVP4.js";
import "./pi-embedded-utils-BraP32ED.js";
import "./redact-DcYCKU6u.js";
import "./pi-embedded-helpers-CLkeTWAT.js";
import "./sandbox-C5rKvtrA.js";
import "./chrome-BQkAVfz8.js";
import "./tailscale-CcUMoDkd.js";
import "./auth-BxKMeEw-.js";
import "./server-context-s_zNpSdX.js";
import "./frontmatter-VFr0KMAQ.js";
import "./skills-CHYyY1lO.js";
import "./routes-CT0DmotX.js";
import "./errors-DbYSuCgv.js";
import "./paths-Ct4sqLyX.js";
import "./ssrf-tneKFjA6.js";
import "./image-ops-C0D77XHD.js";
import "./store-Cdm3Z5cQ.js";
import "./ports-DvLDsgl0.js";
import "./trash-BRBQoy9m.js";
import { S as capArrayByJsonBytes } from "./sessions-Ct2d_bGl.js";
import "./message-channel-DSU96OKy.js";
import "./dock-DY0TWaYa.js";
import "./normalize-DgwtBdm-.js";
import "./accounts-BZv5WxME.js";
import "./accounts-DFaskvEN.js";
import "./accounts-T7o73ZSN.js";
import "./bindings-BbaWTQJM.js";
import "./logging-wfRfbMvt.js";
import "./plugins-DYgcd4QJ.js";
import "./paths-DRyRQF9o.js";
import "./tool-images-CRPqucMe.js";
import { a as jsonResult, u as readStringParam } from "./common-oaZdjdal.js";
import "./client-DNPnFy4E.js";
import { n as callGateway } from "./call-C206Z-zx.js";
import { a as stripToolMessages, c as resolveEffectiveSessionToolsVisibility, l as resolveSandboxedSessionToolContext, m as resolveSessionReference, o as createAgentToAgentPolicy, s as createSessionVisibilityGuard, u as isRequesterSpawnedSessionVisible } from "./sessions-helpers-DYJnJN3U.js";
import { Type } from "@sinclair/typebox";

//#region src/agents/tools/sessions/sessions-history-tool.ts
const SessionsHistoryToolSchema = Type.Object({
	sessionKey: Type.String(),
	limit: Type.Optional(Type.Number({ minimum: 1 })),
	includeTools: Type.Optional(Type.Boolean())
});
const SESSIONS_HISTORY_MAX_BYTES = 80 * 1024;
const SESSIONS_HISTORY_TEXT_MAX_CHARS = 4e3;
function truncateHistoryText(text) {
	if (text.length <= SESSIONS_HISTORY_TEXT_MAX_CHARS) return {
		text,
		truncated: false
	};
	return {
		text: `${truncateUtf16Safe(text, SESSIONS_HISTORY_TEXT_MAX_CHARS)}\n…(truncated)…`,
		truncated: true
	};
}
function sanitizeHistoryContentBlock(block) {
	if (!block || typeof block !== "object") return {
		block,
		truncated: false
	};
	const entry = { ...block };
	let truncated = false;
	const type = typeof entry.type === "string" ? entry.type : "";
	if (typeof entry.text === "string") {
		const res = truncateHistoryText(entry.text);
		entry.text = res.text;
		truncated ||= res.truncated;
	}
	if (type === "thinking") {
		if (typeof entry.thinking === "string") {
			const res = truncateHistoryText(entry.thinking);
			entry.thinking = res.text;
			truncated ||= res.truncated;
		}
		if ("thinkingSignature" in entry) {
			delete entry.thinkingSignature;
			truncated = true;
		}
	}
	if (typeof entry.partialJson === "string") {
		const res = truncateHistoryText(entry.partialJson);
		entry.partialJson = res.text;
		truncated ||= res.truncated;
	}
	if (type === "image") {
		const data = typeof entry.data === "string" ? entry.data : void 0;
		const bytes = data ? data.length : void 0;
		if ("data" in entry) {
			delete entry.data;
			truncated = true;
		}
		entry.omitted = true;
		if (bytes !== void 0) entry.bytes = bytes;
	}
	return {
		block: entry,
		truncated
	};
}
function sanitizeHistoryMessage(message) {
	if (!message || typeof message !== "object") return {
		message,
		truncated: false
	};
	const entry = { ...message };
	let truncated = false;
	if ("details" in entry) {
		delete entry.details;
		truncated = true;
	}
	if ("usage" in entry) {
		delete entry.usage;
		truncated = true;
	}
	if ("cost" in entry) {
		delete entry.cost;
		truncated = true;
	}
	if (typeof entry.content === "string") {
		const res = truncateHistoryText(entry.content);
		entry.content = res.text;
		truncated ||= res.truncated;
	} else if (Array.isArray(entry.content)) {
		const updated = entry.content.map((block) => sanitizeHistoryContentBlock(block));
		entry.content = updated.map((item) => item.block);
		truncated ||= updated.some((item) => item.truncated);
	}
	if (typeof entry.text === "string") {
		const res = truncateHistoryText(entry.text);
		entry.text = res.text;
		truncated ||= res.truncated;
	}
	return {
		message: entry,
		truncated
	};
}
function jsonUtf8Bytes(value) {
	try {
		return Buffer.byteLength(JSON.stringify(value), "utf8");
	} catch {
		return Buffer.byteLength(String(value), "utf8");
	}
}
function enforceSessionsHistoryHardCap(params) {
	if (params.bytes <= params.maxBytes) return {
		items: params.items,
		bytes: params.bytes,
		hardCapped: false
	};
	const last = params.items.at(-1);
	const lastOnly = last ? [last] : [];
	const lastBytes = jsonUtf8Bytes(lastOnly);
	if (lastBytes <= params.maxBytes) return {
		items: lastOnly,
		bytes: lastBytes,
		hardCapped: true
	};
	const placeholder = [{
		role: "assistant",
		content: "[sessions_history omitted: message too large]"
	}];
	return {
		items: placeholder,
		bytes: jsonUtf8Bytes(placeholder),
		hardCapped: true
	};
}
function createSessionsHistoryTool(opts) {
	return {
		label: "Session History",
		name: "sessions_history",
		description: "Fetch message history for a session.",
		parameters: SessionsHistoryToolSchema,
		execute: async (_toolCallId, args) => {
			const params = args;
			const sessionKeyParam = readStringParam(params, "sessionKey", { required: true });
			const cfg = loadConfig();
			const { mainKey, alias, effectiveRequesterKey, restrictToSpawned } = resolveSandboxedSessionToolContext({
				cfg,
				agentSessionKey: opts?.agentSessionKey,
				sandboxed: opts?.sandboxed
			});
			const resolvedSession = await resolveSessionReference({
				sessionKey: sessionKeyParam,
				alias,
				mainKey,
				requesterInternalKey: effectiveRequesterKey,
				restrictToSpawned
			});
			if (!resolvedSession.ok) return jsonResult({
				status: resolvedSession.status,
				error: resolvedSession.error
			});
			const resolvedKey = resolvedSession.key;
			const displayKey = resolvedSession.displayKey;
			const resolvedViaSessionId = resolvedSession.resolvedViaSessionId;
			if (restrictToSpawned && !resolvedViaSessionId && resolvedKey !== effectiveRequesterKey) {
				if (!await isRequesterSpawnedSessionVisible({
					requesterSessionKey: effectiveRequesterKey,
					targetSessionKey: resolvedKey
				})) return jsonResult({
					status: "forbidden",
					error: `Session not visible from this sandboxed agent session: ${sessionKeyParam}`
				});
			}
			const a2aPolicy = createAgentToAgentPolicy(cfg);
			const access = (await createSessionVisibilityGuard({
				action: "history",
				requesterSessionKey: effectiveRequesterKey,
				visibility: resolveEffectiveSessionToolsVisibility({
					cfg,
					sandboxed: opts?.sandboxed === true
				}),
				a2aPolicy
			})).check(resolvedKey);
			if (!access.allowed) return jsonResult({
				status: access.status,
				error: access.error
			});
			const limit = typeof params.limit === "number" && Number.isFinite(params.limit) ? Math.max(1, Math.floor(params.limit)) : void 0;
			const includeTools = Boolean(params.includeTools);
			const result = await callGateway({
				method: "chat.history",
				params: {
					sessionKey: resolvedKey,
					limit
				}
			});
			const rawMessages = Array.isArray(result?.messages) ? result.messages : [];
			const selectedMessages = includeTools ? rawMessages : stripToolMessages(rawMessages);
			const sanitizedMessages = selectedMessages.map((message) => sanitizeHistoryMessage(message));
			const contentTruncated = sanitizedMessages.some((entry) => entry.truncated);
			const cappedMessages = capArrayByJsonBytes(sanitizedMessages.map((entry) => entry.message), SESSIONS_HISTORY_MAX_BYTES);
			const droppedMessages = cappedMessages.items.length < selectedMessages.length;
			const hardened = enforceSessionsHistoryHardCap({
				items: cappedMessages.items,
				bytes: cappedMessages.bytes,
				maxBytes: SESSIONS_HISTORY_MAX_BYTES
			});
			return jsonResult({
				sessionKey: displayKey,
				messages: hardened.items,
				truncated: droppedMessages || contentTruncated || hardened.hardCapped,
				droppedMessages: droppedMessages || hardened.hardCapped,
				contentTruncated,
				bytes: hardened.bytes
			});
		}
	};
}

//#endregion
export { createSessionsHistoryTool };