import "./pi-embedded-utils-BmQgIEul.js";
import "./subsystem-Ci61Iebe.js";
import "./paths-aMBPuCJR.js";
import { C as modelKey, O as resolveDefaultModelForAgent, b as buildModelAliasIndex, k as resolveModelRefFromString, v as buildAllowedModelSet } from "./auth-profiles-CfyCILIe.js";
import "./env-3oW17BWM.js";
import { i as buildAgentMainSessionKey, n as DEFAULT_AGENT_ID, p as resolveAgentIdFromSessionKey } from "./session-key-j5Y_js6r.js";
import "./exec-B5OgjUV4.js";
import { r as resolveAgentDir } from "./agent-scope-CCFV2dzL.js";
import "./github-copilot-token-CgLcR-3z.js";
import "./reliability-B6TVU4OW.js";
import "./sqlite-CbyDDiup.js";
import "./pi-model-discovery-C9hP1DnY.js";
import "./tokens-Bvij_SSC.js";
import "./heartbeat-Bf1PpFld.js";
import { F as buildStatusMessage, L as applyModelOverrideToSessionEntry, M as formatUsageWindowSummary, N as resolveUsageProviderId, P as resolveModelAuthLabel, at as resolveUserTimezone, et as resolveQueueSettings, it as resolveUserTimeFormat, j as loadProviderUsageSummary, k as normalizeGroupActivation, n as loadCombinedSessionStoreForGateway, rt as formatUserTime, tt as getFollowupQueueDepth } from "./pi-embedded-runner-B7I92FYZ.js";
import "./accounts-TaYXhwSR.js";
import "./dock-BRgbOpqS.js";
import "./normalize-Dz9m5w2g.js";
import "./bindings-jC2ZutIF.js";
import "./helpers-Bu7dwsdB.js";
import "./client-BVxlvc45.js";
import "./plugins-6aUfx6Yt.js";
import "./diagnostic-CfwHM9PU.js";
import "./diagnostic-session-state-8XCWMS55.js";
import "./lanes-BUEJliXF.js";
import "./send-Bq6jbXbH.js";
import "./message-channel-BCPYwYUJ.js";
import "./route-reply-C7S9S-na.js";
import "./tts-BKXJ7fIm.js";
import "./image-ops-DfgorOBP.js";
import "./pi-embedded-helpers-DmbNPuyh.js";
import { n as loadConfig } from "./config-CaBTSkpu.js";
import "./manifest-registry-BPLS_vpk.js";
import "./chrome-CDWGRT0_.js";
import "./server-context-CU0HZM8q.js";
import "./skills-CEb7zc7i.js";
import "./redact-BXcZFg1V.js";
import "./errors-CGLTQpIl.js";
import "./ssrf-Clw7QAxV.js";
import { c as updateSessionStore, i as loadSessionStore } from "./sessions-FK8zYE33.js";
import { s as resolveStorePath } from "./paths-a4Li8t1f.js";
import "./tool-images-D39TNWEi.js";
import "./thinking-B4KYQMkY.js";
import "./image-tool.helpers-B7jX77eL.js";
import "./chat-trace-YVp5bEfe.js";
import "./response-prefix-template-CpJqwkyc.js";
import "./tool-tracking-CLcHzyfL.js";
import "./manager-CwxGvAk_.js";
import "./gemini-auth-UIYR3_Rv.js";
import "./session-files-CpNR2YZS.js";
import "./retry-13lqGuBf.js";
import "./hybrid-DRv9Yggt.js";
import { u as readStringParam } from "./common-BkBiFnII.js";
import "./replies-CpIxmKIz.js";
import "./chunk-CbeEZcZX.js";
import "./markdown-tables-COuv9r7p.js";
import "./fetch-guard-1C45XE5F.js";
import "./fetch-Cn7DNoxz.js";
import "./media-CrEbBlaK.js";
import "./ir-pL2nbM8K.js";
import "./render-MTSxc7LK.js";
import "./commands-registry-BPtbhRwL.js";
import "./call-CHvC3jba.js";
import { f as resolveInternalSessionKey, h as shouldResolveSessionIdInput, o as createAgentToAgentPolicy, p as resolveMainSessionAlias } from "./sessions-helpers-BkUTlqiP.js";
import "./external-content-CfbWCLcb.js";
import { s as loadModelCatalog } from "./runner-B3zVBP2H.js";
import "./image-DP51oWEy.js";
import "./skill-commands-D0ICIAHz.js";
import "./gateway-B-qVaiZA.js";
import "./nodes-utils-MqV9QJHm.js";
import "./resolve-route-CirHUsAv.js";
import "./knowledge-graph-CJ2-NLrF.js";
import "./model-fallback-tYPGXASj.js";
import "./active-listener-Ch-ciMyT.js";
import "./reply-prefix-BukioEEd.js";
import "./proxy-BoiJAz4L.js";
import { Type } from "@sinclair/typebox";

//#region src/agents/tools/sessions/session-status-tool.ts
const SessionStatusToolSchema = Type.Object({
	sessionKey: Type.Optional(Type.String()),
	model: Type.Optional(Type.String())
});
function resolveSessionEntry(params) {
	const keyRaw = params.keyRaw.trim();
	if (!keyRaw) return null;
	const internal = resolveInternalSessionKey({
		key: keyRaw,
		alias: params.alias,
		mainKey: params.mainKey
	});
	const candidates = new Set([keyRaw, internal]);
	if (!keyRaw.startsWith("agent:")) {
		candidates.add(`agent:${DEFAULT_AGENT_ID}:${keyRaw}`);
		candidates.add(`agent:${DEFAULT_AGENT_ID}:${internal}`);
	}
	if (keyRaw === "main") candidates.add(buildAgentMainSessionKey({
		agentId: DEFAULT_AGENT_ID,
		mainKey: params.mainKey
	}));
	for (const key of candidates) {
		const entry = params.store[key];
		if (entry) return {
			key,
			entry
		};
	}
	return null;
}
function resolveSessionKeyFromSessionId(params) {
	const trimmed = params.sessionId.trim();
	if (!trimmed) return null;
	const { store } = loadCombinedSessionStoreForGateway(params.cfg);
	return Object.entries(store).find(([key, entry]) => {
		if (entry?.sessionId !== trimmed) return false;
		if (!params.agentId) return true;
		return resolveAgentIdFromSessionKey(key) === params.agentId;
	})?.[0] ?? null;
}
async function resolveModelOverride(params) {
	const raw = params.raw.trim();
	if (!raw) return { kind: "reset" };
	if (raw.toLowerCase() === "default") return { kind: "reset" };
	const configDefault = resolveDefaultModelForAgent({
		cfg: params.cfg,
		agentId: params.agentId
	});
	const currentProvider = params.sessionEntry?.providerOverride?.trim() || configDefault.provider;
	const currentModel = params.sessionEntry?.modelOverride?.trim() || configDefault.model;
	const aliasIndex = buildModelAliasIndex({
		cfg: params.cfg,
		defaultProvider: currentProvider
	});
	const catalog = await loadModelCatalog({ config: params.cfg });
	const allowed = buildAllowedModelSet({
		cfg: params.cfg,
		catalog,
		defaultProvider: currentProvider,
		defaultModel: currentModel
	});
	const resolved = resolveModelRefFromString({
		raw,
		defaultProvider: currentProvider,
		aliasIndex
	});
	if (!resolved) throw new Error(`Unrecognized model "${raw}".`);
	const key = modelKey(resolved.ref.provider, resolved.ref.model);
	if (allowed.allowedKeys.size > 0 && !allowed.allowedKeys.has(key)) throw new Error(`Model "${key}" is not allowed.`);
	const isDefault = resolved.ref.provider === configDefault.provider && resolved.ref.model === configDefault.model;
	return {
		kind: "set",
		provider: resolved.ref.provider,
		model: resolved.ref.model,
		isDefault
	};
}
function createSessionStatusTool(opts) {
	return {
		label: "Session Status",
		name: "session_status",
		description: "Show a /status-equivalent session status card (usage + time + cost when available). Use for model-use questions (📊 session_status). Optional: set per-session model override (model=default resets overrides).",
		parameters: SessionStatusToolSchema,
		execute: async (_toolCallId, args) => {
			const params = args;
			const cfg = opts?.config ?? loadConfig();
			const { mainKey, alias } = resolveMainSessionAlias(cfg);
			const a2aPolicy = createAgentToAgentPolicy(cfg);
			let requestedKeyRaw = readStringParam(params, "sessionKey") ?? opts?.agentSessionKey;
			if (!requestedKeyRaw?.trim()) throw new Error("sessionKey required");
			const requesterAgentId = resolveAgentIdFromSessionKey(opts?.agentSessionKey ?? requestedKeyRaw);
			const ensureAgentAccess = (targetAgentId) => {
				if (targetAgentId === requesterAgentId) return;
				if (!a2aPolicy.enabled) throw new Error("Agent-to-agent status is disabled. Set tools.agentToAgent.enabled=true to allow cross-agent access.");
				if (!a2aPolicy.isAllowed(requesterAgentId, targetAgentId)) throw new Error("Agent-to-agent session status denied by tools.agentToAgent.allow.");
			};
			if (requestedKeyRaw.startsWith("agent:")) ensureAgentAccess(resolveAgentIdFromSessionKey(requestedKeyRaw));
			let agentId = requestedKeyRaw.startsWith("agent:") ? resolveAgentIdFromSessionKey(requestedKeyRaw) : requesterAgentId;
			let storePath = resolveStorePath(cfg.session?.store, { agentId });
			let store = loadSessionStore(storePath);
			let resolved = resolveSessionEntry({
				store,
				keyRaw: requestedKeyRaw,
				alias,
				mainKey
			});
			if (!resolved && shouldResolveSessionIdInput(requestedKeyRaw)) {
				const resolvedKey = resolveSessionKeyFromSessionId({
					cfg,
					sessionId: requestedKeyRaw,
					agentId: a2aPolicy.enabled ? void 0 : requesterAgentId
				});
				if (resolvedKey) {
					ensureAgentAccess(resolveAgentIdFromSessionKey(resolvedKey));
					requestedKeyRaw = resolvedKey;
					agentId = resolveAgentIdFromSessionKey(resolvedKey);
					storePath = resolveStorePath(cfg.session?.store, { agentId });
					store = loadSessionStore(storePath);
					resolved = resolveSessionEntry({
						store,
						keyRaw: requestedKeyRaw,
						alias,
						mainKey
					});
				}
			}
			if (!resolved) {
				const kind = shouldResolveSessionIdInput(requestedKeyRaw) ? "sessionId" : "sessionKey";
				throw new Error(`Unknown ${kind}: ${requestedKeyRaw}`);
			}
			const configured = resolveDefaultModelForAgent({
				cfg,
				agentId
			});
			const modelRaw = readStringParam(params, "model");
			let changedModel = false;
			if (typeof modelRaw === "string") {
				const selection = await resolveModelOverride({
					cfg,
					raw: modelRaw,
					sessionEntry: resolved.entry,
					agentId
				});
				const nextEntry = { ...resolved.entry };
				if (applyModelOverrideToSessionEntry({
					entry: nextEntry,
					selection: selection.kind === "reset" ? {
						provider: configured.provider,
						model: configured.model,
						isDefault: true
					} : {
						provider: selection.provider,
						model: selection.model,
						isDefault: selection.isDefault
					}
				}).updated) {
					store[resolved.key] = nextEntry;
					await updateSessionStore(storePath, (nextStore) => {
						nextStore[resolved.key] = nextEntry;
					});
					resolved.entry = nextEntry;
					changedModel = true;
				}
			}
			const agentDir = resolveAgentDir(cfg, agentId);
			const providerForCard = resolved.entry.providerOverride?.trim() || configured.provider;
			const usageProvider = resolveUsageProviderId(providerForCard);
			let usageLine;
			if (usageProvider) try {
				const snapshot = (await loadProviderUsageSummary({
					timeoutMs: 3500,
					providers: [usageProvider],
					agentDir
				})).providers.find((entry) => entry.provider === usageProvider);
				if (snapshot) {
					const formatted = formatUsageWindowSummary(snapshot, {
						now: Date.now(),
						maxWindows: 2,
						includeResets: true
					});
					if (formatted && !formatted.startsWith("error:")) usageLine = `📊 Usage: ${formatted}`;
				}
			} catch {}
			const groupActivation = resolved.entry.chatType === "group" || resolved.entry.chatType === "channel" || resolved.key.includes(":group:") || resolved.key.includes(":channel:") ? normalizeGroupActivation(resolved.entry.groupActivation) ?? "mention" : void 0;
			const queueSettings = resolveQueueSettings({
				cfg,
				channel: resolved.entry.channel ?? resolved.entry.lastChannel ?? "unknown",
				sessionEntry: resolved.entry
			});
			const queueKey = resolved.key ?? resolved.entry.sessionId;
			const queueDepth = queueKey ? getFollowupQueueDepth(queueKey) : 0;
			const queueOverrides = Boolean(resolved.entry.queueDebounceMs ?? resolved.entry.queueCap ?? resolved.entry.queueDrop);
			const userTimezone = resolveUserTimezone(cfg.agents?.defaults?.userTimezone);
			const userTimeFormat = resolveUserTimeFormat(cfg.agents?.defaults?.timeFormat);
			const userTime = formatUserTime(/* @__PURE__ */ new Date(), userTimezone, userTimeFormat);
			const timeLine = userTime ? `🕒 Time: ${userTime} (${userTimezone})` : `🕒 Time zone: ${userTimezone}`;
			const agentDefaults = cfg.agents?.defaults ?? {};
			const defaultLabel = `${configured.provider}/${configured.model}`;
			const agentModel = typeof agentDefaults.model === "object" && agentDefaults.model ? {
				...agentDefaults.model,
				primary: defaultLabel
			} : { primary: defaultLabel };
			const statusText = buildStatusMessage({
				config: cfg,
				agent: {
					...agentDefaults,
					model: agentModel
				},
				agentId,
				sessionEntry: resolved.entry,
				sessionKey: resolved.key,
				sessionStorePath: storePath,
				groupActivation,
				modelAuth: resolveModelAuthLabel({
					provider: providerForCard,
					cfg,
					sessionEntry: resolved.entry,
					agentDir
				}),
				usageLine,
				timeLine,
				queue: {
					mode: queueSettings.mode,
					depth: queueDepth,
					debounceMs: queueSettings.debounceMs,
					cap: queueSettings.cap,
					dropPolicy: queueSettings.dropPolicy,
					showDetails: queueOverrides
				},
				includeTranscriptUsage: false
			});
			return {
				content: [{
					type: "text",
					text: statusText
				}],
				details: {
					ok: true,
					sessionKey: resolved.key,
					changedModel,
					statusText
				}
			};
		}
	};
}

//#endregion
export { createSessionStatusTool };