import "./pi-embedded-utils-Dx4_ysu7.js";
import "./subsystem-B57zAnh3.js";
import "./paths-aMBPuCJR.js";
import "./auth-profiles-vy16iW9a.js";
import "./env-DFfOiqpV.js";
import { p as resolveAgentIdFromSessionKey } from "./session-key-j5Y_js6r.js";
import "./exec-rVpUMUjU.js";
import "./agent-scope-C3vq_G9s.js";
import "./github-copilot-token-5G6j3BB0.js";
import "./reliability-CU83NHOD.js";
import "./sqlite-CbyDDiup.js";
import "./accounts-Diz2TIQa.js";
import "./dock-YZOG_yQS.js";
import "./normalize-C804TuMz.js";
import "./bindings-DLG2Bod-.js";
import "./plugins-DqFdJSNb.js";
import "./message-channel-Cw5DRkgR.js";
import "./image-ops-D6in9bm7.js";
import "./pi-embedded-helpers-14yhAK8Z.js";
import { n as loadConfig } from "./config-BWfcFg-o.js";
import "./manifest-registry-DOrMVNcS.js";
import "./chrome-CdUTjfym.js";
import "./server-context-CCjHJE9j.js";
import "./skills-WWjjkPNZ.js";
import "./redact-BXcZFg1V.js";
import "./errors-CGLTQpIl.js";
import "./ssrf-Clw7QAxV.js";
import "./sessions-Bge3YYgW.js";
import { n as resolveSessionFilePath } from "./paths-a4Li8t1f.js";
import "./tool-images-DTeIBF5l.js";
import "./thinking-B4KYQMkY.js";
import { a as jsonResult, c as readStringArrayParam } from "./common-CBZ0Olph.js";
import { n as callGateway } from "./call-qL_BTieR.js";
import { a as stripToolMessages, c as resolveEffectiveSessionToolsVisibility, d as resolveDisplaySessionKey, f as resolveInternalSessionKey, l as resolveSandboxedSessionToolContext, n as deriveChannel, o as createAgentToAgentPolicy, s as createSessionVisibilityGuard, t as classifySessionKind } from "./sessions-helpers-CApxk4ya.js";
import path from "node:path";
import { Type } from "@sinclair/typebox";

//#region src/agents/tools/sessions/sessions-list-tool.ts
const SessionsListToolSchema = Type.Object({
	kinds: Type.Optional(Type.Array(Type.String())),
	limit: Type.Optional(Type.Number({ minimum: 1 })),
	activeMinutes: Type.Optional(Type.Number({ minimum: 1 })),
	messageLimit: Type.Optional(Type.Number({ minimum: 0 }))
});
function createSessionsListTool(opts) {
	return {
		label: "Sessions",
		name: "sessions_list",
		description: "List sessions with optional filters and last messages.",
		parameters: SessionsListToolSchema,
		execute: async (_toolCallId, args) => {
			const params = args;
			const cfg = loadConfig();
			const { mainKey, alias, requesterInternalKey, restrictToSpawned } = resolveSandboxedSessionToolContext({
				cfg,
				agentSessionKey: opts?.agentSessionKey,
				sandboxed: opts?.sandboxed
			});
			const effectiveRequesterKey = requesterInternalKey ?? alias;
			const visibility = resolveEffectiveSessionToolsVisibility({
				cfg,
				sandboxed: opts?.sandboxed === true
			});
			const allowedKindsList = (readStringArrayParam(params, "kinds")?.map((value) => value.trim().toLowerCase()) ?? []).filter((value) => [
				"main",
				"group",
				"cron",
				"hook",
				"node",
				"other"
			].includes(value));
			const allowedKinds = allowedKindsList.length ? new Set(allowedKindsList) : void 0;
			const limit = typeof params.limit === "number" && Number.isFinite(params.limit) ? Math.max(1, Math.floor(params.limit)) : void 0;
			const activeMinutes = typeof params.activeMinutes === "number" && Number.isFinite(params.activeMinutes) ? Math.max(1, Math.floor(params.activeMinutes)) : void 0;
			const messageLimitRaw = typeof params.messageLimit === "number" && Number.isFinite(params.messageLimit) ? Math.max(0, Math.floor(params.messageLimit)) : 0;
			const messageLimit = Math.min(messageLimitRaw, 20);
			const list = await callGateway({
				method: "sessions.list",
				params: {
					limit,
					activeMinutes,
					includeGlobal: !restrictToSpawned,
					includeUnknown: !restrictToSpawned,
					spawnedBy: restrictToSpawned ? effectiveRequesterKey : void 0
				}
			});
			const sessions = Array.isArray(list?.sessions) ? list.sessions : [];
			const storePath = typeof list?.path === "string" ? list.path : void 0;
			const visibilityGuard = await createSessionVisibilityGuard({
				action: "list",
				requesterSessionKey: effectiveRequesterKey,
				visibility,
				a2aPolicy: createAgentToAgentPolicy(cfg)
			});
			const rows = [];
			const historyTargets = [];
			for (const entry of sessions) {
				if (!entry || typeof entry !== "object") continue;
				const key = typeof entry.key === "string" ? entry.key : "";
				if (!key) continue;
				if (!visibilityGuard.check(key).allowed) continue;
				if (key === "unknown") continue;
				if (key === "global" && alias !== "global") continue;
				const kind = classifySessionKind({
					key,
					gatewayKind: typeof entry.kind === "string" ? entry.kind : void 0,
					alias,
					mainKey
				});
				if (allowedKinds && !allowedKinds.has(kind)) continue;
				const displayKey = resolveDisplaySessionKey({
					key,
					alias,
					mainKey
				});
				const entryChannel = typeof entry.channel === "string" ? entry.channel : void 0;
				const deliveryContext = entry.deliveryContext && typeof entry.deliveryContext === "object" ? entry.deliveryContext : void 0;
				const deliveryChannel = typeof deliveryContext?.channel === "string" ? deliveryContext.channel : void 0;
				const deliveryTo = typeof deliveryContext?.to === "string" ? deliveryContext.to : void 0;
				const deliveryAccountId = typeof deliveryContext?.accountId === "string" ? deliveryContext.accountId : void 0;
				const lastChannel = deliveryChannel ?? (typeof entry.lastChannel === "string" ? entry.lastChannel : void 0);
				const lastAccountId = deliveryAccountId ?? (typeof entry.lastAccountId === "string" ? entry.lastAccountId : void 0);
				const derivedChannel = deriveChannel({
					key,
					kind,
					channel: entryChannel,
					lastChannel
				});
				const sessionId = typeof entry.sessionId === "string" ? entry.sessionId : void 0;
				const sessionFileRaw = entry.sessionFile;
				const sessionFile = typeof sessionFileRaw === "string" ? sessionFileRaw : void 0;
				let transcriptPath;
				if (sessionId && storePath) try {
					transcriptPath = resolveSessionFilePath(sessionId, sessionFile ? { sessionFile } : void 0, {
						agentId: resolveAgentIdFromSessionKey(key),
						sessionsDir: path.dirname(storePath)
					});
				} catch {
					transcriptPath = void 0;
				}
				const row = {
					key: displayKey,
					kind,
					channel: derivedChannel,
					label: typeof entry.label === "string" ? entry.label : void 0,
					displayName: typeof entry.displayName === "string" ? entry.displayName : void 0,
					deliveryContext: deliveryChannel || deliveryTo || deliveryAccountId ? {
						channel: deliveryChannel,
						to: deliveryTo,
						accountId: deliveryAccountId
					} : void 0,
					updatedAt: typeof entry.updatedAt === "number" ? entry.updatedAt : void 0,
					sessionId,
					model: typeof entry.model === "string" ? entry.model : void 0,
					contextTokens: typeof entry.contextTokens === "number" ? entry.contextTokens : void 0,
					totalTokens: typeof entry.totalTokens === "number" ? entry.totalTokens : void 0,
					thinkingLevel: typeof entry.thinkingLevel === "string" ? entry.thinkingLevel : void 0,
					verboseLevel: typeof entry.verboseLevel === "string" ? entry.verboseLevel : void 0,
					systemSent: typeof entry.systemSent === "boolean" ? entry.systemSent : void 0,
					abortedLastRun: typeof entry.abortedLastRun === "boolean" ? entry.abortedLastRun : void 0,
					sendPolicy: typeof entry.sendPolicy === "string" ? entry.sendPolicy : void 0,
					lastChannel,
					lastTo: deliveryTo ?? (typeof entry.lastTo === "string" ? entry.lastTo : void 0),
					lastAccountId,
					transcriptPath
				};
				if (messageLimit > 0) {
					const resolvedKey = resolveInternalSessionKey({
						key: displayKey,
						alias,
						mainKey
					});
					historyTargets.push({
						row,
						resolvedKey
					});
				}
				rows.push(row);
			}
			if (messageLimit > 0 && historyTargets.length > 0) {
				const maxConcurrent = Math.min(4, historyTargets.length);
				let index = 0;
				const worker = async () => {
					while (true) {
						const next = index;
						index += 1;
						if (next >= historyTargets.length) return;
						const target = historyTargets[next];
						const history = await callGateway({
							method: "chat.history",
							params: {
								sessionKey: target.resolvedKey,
								limit: messageLimit
							}
						});
						const filtered = stripToolMessages(Array.isArray(history?.messages) ? history.messages : []);
						target.row.messages = filtered.length > messageLimit ? filtered.slice(-messageLimit) : filtered;
					}
				};
				await Promise.all(Array.from({ length: maxConcurrent }, () => worker()));
			}
			return jsonResult({
				count: rows.length,
				sessions: rows
			});
		}
	};
}

//#endregion
export { createSessionsListTool };