import { r as formatErrorMessage } from "./errors-CGMew-1w.js";
import { i as normalizeLowercaseStringOrEmpty, o as normalizeOptionalLowercaseString, s as normalizeOptionalString } from "./string-coerce-CIT1-v_a.js";
import { b as truncateUtf16Safe } from "./utils-CE5zxr9Z.js";
import { S as parseAgentSessionKey, _ as isAcpSessionKey, l as normalizeMainKey, u as resolveAgentIdFromSessionKey, x as isSubagentSessionKey } from "./session-key-NGoeHrFI.js";
import { a as loadConfig } from "./io-B_JNqEVl.js";
import "./config-BR67jvKt.js";
import "./sessions-Dr5S_J4E.js";
import { l as resolveStorePath } from "./paths-DRORteAV.js";
import { t as loadSessionStore } from "./store-load-Cz0tEUuX.js";
import { r as callGateway } from "./call-BbnBxegf.js";
import "./chat-history-text-CnTaMQhD.js";
import { a as sanitizeTaskStatusText } from "./task-status-DM0dKSwU.js";
import { n as normalizeSubagentSessionKey, t as getSubagentDepthFromSessionStore } from "./subagent-depth-C0PItBiy.js";
//#region src/sessions/session-id.ts
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());
}
let sessionsResolutionDeps = { callGateway };
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 === "current") return params.requesterInternalKey ?? params.key;
	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)) : void 0;
	try {
		const list = await sessionsResolutionDeps.callGateway({
			method: "sessions.list",
			params: {
				includeGlobal: false,
				includeUnknown: false,
				...limit !== void 0 ? { limit } : {},
				spawnedBy: params.requesterSessionKey
			}
		});
		const keys = (Array.isArray(list?.sessions) ? list.sessions : []).map((entry) => normalizeOptionalString(entry?.key) ?? "").filter(Boolean);
		return new Set(keys);
	} catch {
		return /* @__PURE__ */ new Set();
	}
}
async function isRequesterSpawnedSessionVisible(params) {
	if (params.requesterSessionKey === params.targetSessionKey) return true;
	try {
		const resolved = await sessionsResolutionDeps.callGateway({
			method: "sessions.resolve",
			params: {
				key: params.targetSessionKey,
				spawnedBy: params.requesterSessionKey
			}
		});
		if (typeof resolved?.key === "string" && resolved.key.trim() === params.targetSessionKey) return true;
	} catch {}
	return (await listSpawnedSessionKeys({
		requesterSessionKey: params.requesterSessionKey,
		limit: params.limit
	})).has(params.targetSessionKey);
}
function shouldVerifyRequesterSpawnedSessionVisibility(params) {
	return params.restrictToSpawned && !params.resolvedViaSessionId && params.requesterSessionKey !== params.targetSessionKey;
}
async function isResolvedSessionVisibleToRequester(params) {
	if (!shouldVerifyRequesterSpawnedSessionVisibility({
		requesterSessionKey: params.requesterSessionKey,
		targetSessionKey: params.targetSessionKey,
		restrictToSpawned: params.restrictToSpawned,
		resolvedViaSessionId: params.resolvedViaSessionId
	})) return true;
	return await isRequesterSpawnedSessionVisible({
		requesterSessionKey: params.requesterSessionKey,
		targetSessionKey: params.targetSessionKey,
		limit: params.limit
	});
}
function looksLikeSessionKey(value) {
	const raw = normalizeOptionalString(value) ?? "";
	if (!raw) return false;
	if (raw === "main" || raw === "global" || raw === "unknown" || raw === "current") 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);
}
function buildResolvedSessionReference(params) {
	return {
		ok: true,
		key: params.key,
		displayKey: resolveDisplaySessionKey({
			key: params.key,
			alias: params.alias,
			mainKey: params.mainKey
		}),
		resolvedViaSessionId: params.resolvedViaSessionId
	};
}
function buildSessionIdResolveParams(params) {
	return {
		sessionId: params.sessionId,
		spawnedBy: params.restrictToSpawned ? params.requesterInternalKey : void 0,
		includeGlobal: !params.restrictToSpawned,
		includeUnknown: !params.restrictToSpawned
	};
}
async function callGatewayResolveSessionId(params) {
	const key = normalizeOptionalString((await sessionsResolutionDeps.callGateway({
		method: "sessions.resolve",
		params: buildSessionIdResolveParams(params)
	}))?.key) ?? "";
	if (!key) throw new Error(`Session not found: ${params.sessionId} (use the full sessionKey from sessions_list)`);
	return key;
}
async function resolveSessionKeyFromSessionId(params) {
	try {
		return buildResolvedSessionReference({
			key: await callGatewayResolveSessionId(params),
			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: formatErrorMessage(err) || `Session not found: ${params.sessionId} (use the full sessionKey from sessions_list)`
		};
	}
}
async function resolveSessionKeyFromKey(params) {
	try {
		const key = normalizeOptionalString((await sessionsResolutionDeps.callGateway({
			method: "sessions.resolve",
			params: {
				key: params.key,
				spawnedBy: params.restrictToSpawned ? params.requesterInternalKey : void 0
			}
		}))?.key) ?? "";
		if (!key) return null;
		return buildResolvedSessionReference({
			key,
			alias: params.alias,
			mainKey: params.mainKey,
			resolvedViaSessionId: false
		});
	} catch {
		return null;
	}
}
async function tryResolveSessionKeyFromSessionId(params) {
	try {
		return buildResolvedSessionReference({
			key: await callGatewayResolveSessionId(params),
			alias: params.alias,
			mainKey: params.mainKey,
			resolvedViaSessionId: true
		});
	} catch {
		return null;
	}
}
async function resolveSessionReferenceByKeyOrSessionId(params) {
	if (!params.skipKeyLookup) {
		const resolvedByKey = await resolveSessionKeyFromKey({
			key: params.raw,
			alias: params.alias,
			mainKey: params.mainKey,
			requesterInternalKey: params.requesterInternalKey,
			restrictToSpawned: params.restrictToSpawned
		});
		if (resolvedByKey) return resolvedByKey;
	}
	if (!(params.forceSessionIdLookup || shouldResolveSessionIdInput(params.raw))) return null;
	if (params.allowUnresolvedSessionId) return await tryResolveSessionKeyFromSessionId({
		sessionId: params.raw,
		alias: params.alias,
		mainKey: params.mainKey,
		requesterInternalKey: params.requesterInternalKey,
		restrictToSpawned: params.restrictToSpawned
	});
	return await resolveSessionKeyFromSessionId({
		sessionId: params.raw,
		alias: params.alias,
		mainKey: params.mainKey,
		requesterInternalKey: params.requesterInternalKey,
		restrictToSpawned: params.restrictToSpawned
	});
}
async function resolveSessionReference(params) {
	const rawInput = params.sessionKey.trim();
	if (rawInput === "current") {
		const resolvedCurrent = await resolveSessionReferenceByKeyOrSessionId({
			raw: rawInput,
			alias: params.alias,
			mainKey: params.mainKey,
			requesterInternalKey: params.requesterInternalKey,
			restrictToSpawned: params.restrictToSpawned,
			allowUnresolvedSessionId: true,
			skipKeyLookup: params.restrictToSpawned,
			forceSessionIdLookup: true
		});
		if (resolvedCurrent) return resolvedCurrent;
	}
	const raw = rawInput === "current" && params.requesterInternalKey ? params.requesterInternalKey : rawInput;
	if (shouldResolveSessionIdInput(raw)) {
		const resolvedByGateway = await resolveSessionReferenceByKeyOrSessionId({
			raw,
			alias: params.alias,
			mainKey: params.mainKey,
			requesterInternalKey: params.requesterInternalKey,
			restrictToSpawned: params.restrictToSpawned,
			allowUnresolvedSessionId: false
		});
		if (resolvedByGateway) return resolvedByGateway;
	}
	const resolvedKey = resolveInternalSessionKey({
		key: raw,
		alias: params.alias,
		mainKey: params.mainKey,
		requesterInternalKey: params.requesterInternalKey
	});
	return {
		ok: true,
		key: resolvedKey,
		displayKey: resolveDisplaySessionKey({
			key: resolvedKey,
			alias: params.alias,
			mainKey: params.mainKey
		}),
		resolvedViaSessionId: false
	};
}
async function resolveVisibleSessionReference(params) {
	const resolvedKey = params.resolvedSession.key;
	const displayKey = params.resolvedSession.displayKey;
	if (!await isResolvedSessionVisibleToRequester({
		requesterSessionKey: params.requesterSessionKey,
		targetSessionKey: resolvedKey,
		restrictToSpawned: params.restrictToSpawned,
		resolvedViaSessionId: params.resolvedSession.resolvedViaSessionId
	})) return {
		ok: false,
		status: "forbidden",
		error: `Session not visible from this sandboxed agent session: ${params.visibilitySessionKey}`,
		displayKey
	};
	return {
		ok: true,
		key: resolvedKey,
		displayKey
	};
}
//#endregion
//#region src/agents/tools/sessions-access.ts
function resolveSessionToolsVisibility(cfg) {
	const raw = cfg.tools?.sessions?.visibility;
	const value = normalizeLowercaseStringOrEmpty(raw);
	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 requesterSessionKey = normalizeOptionalString(params.agentSessionKey);
	const requesterInternalKey = requesterSessionKey ? resolveInternalSessionKey({
		key: requesterSessionKey,
		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 routingA2A = cfg.tools?.agentToAgent;
	const enabled = routingA2A?.enabled === true;
	const allowPatterns = Array.isArray(routingA2A?.allow) ? routingA2A.allow : [];
	const matchesAllow = (agentId) => {
		if (allowPatterns.length === 0) return true;
		return allowPatterns.some((pattern) => {
			const raw = normalizeOptionalString(typeof pattern === "string" ? pattern : String(pattern ?? "")) ?? "";
			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 isAllowed = (requesterAgentId, targetAgentId) => {
		if (requesterAgentId === targetAgentId) return true;
		if (!enabled) return false;
		return matchesAllow(requesterAgentId) && matchesAllow(targetAgentId);
	};
	return {
		enabled,
		matchesAllow,
		isAllowed
	};
}
function actionPrefix(action) {
	if (action === "history") return "Session history";
	if (action === "send") return "Session send";
	if (action === "status") return "Session status";
	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.";
	if (action === "status") return "Agent-to-agent status is disabled. Set tools.agentToAgent.enabled=true to allow cross-agent access.";
	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.";
	if (action === "status") return "Agent-to-agent status 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.";
	if (action === "status") return "Session status 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.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-helpers.ts
function resolveSessionToolContext(opts) {
	const cfg = opts?.config ?? loadConfig();
	return {
		cfg,
		...resolveSandboxedSessionToolContext({
			cfg,
			agentSessionKey: opts?.agentSessionKey,
			sandboxed: opts?.sandboxed
		})
	};
}
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 = normalizeOptionalString(params.channel ?? void 0);
	if (channel) return channel;
	const lastChannel = normalizeOptionalString(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";
}
//#endregion
//#region src/agents/subagent-capabilities.ts
const SUBAGENT_SESSION_ROLES = [
	"main",
	"orchestrator",
	"leaf"
];
const SUBAGENT_CONTROL_SCOPES = ["children", "none"];
function normalizeSubagentRole(value) {
	const trimmed = normalizeOptionalLowercaseString(value);
	return SUBAGENT_SESSION_ROLES.find((entry) => entry === trimmed);
}
function normalizeSubagentControlScope(value) {
	const trimmed = normalizeOptionalLowercaseString(value);
	return SUBAGENT_CONTROL_SCOPES.find((entry) => entry === trimmed);
}
function readSessionStore(storePath) {
	try {
		return loadSessionStore(storePath);
	} catch {
		return {};
	}
}
function findEntryBySessionId(store, sessionId) {
	const normalizedSessionId = normalizeSubagentSessionKey(sessionId);
	if (!normalizedSessionId) return;
	for (const entry of Object.values(store)) if (normalizeSubagentSessionKey(entry?.sessionId) === normalizedSessionId) return entry;
}
function resolveSessionCapabilityEntry(params) {
	if (params.store) return params.store[params.sessionKey] ?? findEntryBySessionId(params.store, params.sessionKey);
	if (!params.cfg) return;
	const parsed = parseAgentSessionKey(params.sessionKey);
	if (!parsed?.agentId) return;
	const store = readSessionStore(resolveStorePath(params.cfg.session?.store, { agentId: parsed.agentId }));
	return store[params.sessionKey] ?? findEntryBySessionId(store, params.sessionKey);
}
function resolveSubagentRoleForDepth(params) {
	const depth = Number.isInteger(params.depth) ? Math.max(0, params.depth) : 0;
	const maxSpawnDepth = typeof params.maxSpawnDepth === "number" && Number.isFinite(params.maxSpawnDepth) ? Math.max(1, Math.floor(params.maxSpawnDepth)) : 1;
	if (depth <= 0) return "main";
	return depth < maxSpawnDepth ? "orchestrator" : "leaf";
}
function resolveSubagentControlScopeForRole(role) {
	return role === "leaf" ? "none" : "children";
}
function resolveSubagentCapabilities(params) {
	const role = resolveSubagentRoleForDepth(params);
	const controlScope = resolveSubagentControlScopeForRole(role);
	return {
		depth: Math.max(0, Math.floor(params.depth)),
		role,
		controlScope,
		canSpawn: role === "main" || role === "orchestrator",
		canControlChildren: controlScope === "children"
	};
}
function resolveStoredSubagentCapabilities(sessionKey, opts) {
	const normalizedSessionKey = normalizeSubagentSessionKey(sessionKey);
	const maxSpawnDepth = opts?.cfg?.agents?.defaults?.subagents?.maxSpawnDepth ?? 1;
	const depth = getSubagentDepthFromSessionStore(normalizedSessionKey, {
		cfg: opts?.cfg,
		store: opts?.store
	});
	if (!normalizedSessionKey || !isSubagentSessionKey(normalizedSessionKey)) return resolveSubagentCapabilities({
		depth,
		maxSpawnDepth
	});
	const entry = resolveSessionCapabilityEntry({
		sessionKey: normalizedSessionKey,
		cfg: opts?.cfg,
		store: opts?.store
	});
	const storedRole = normalizeSubagentRole(entry?.subagentRole);
	const storedControlScope = normalizeSubagentControlScope(entry?.subagentControlScope);
	const fallback = resolveSubagentCapabilities({
		depth,
		maxSpawnDepth
	});
	const role = storedRole ?? fallback.role;
	const controlScope = storedControlScope ?? resolveSubagentControlScopeForRole(role);
	return {
		depth,
		role,
		controlScope,
		canSpawn: role === "main" || role === "orchestrator",
		canControlChildren: controlScope === "children"
	};
}
//#endregion
//#region src/auto-reply/reply/subagents-utils.ts
function resolveSubagentLabel(entry, fallback = "subagent") {
	return normalizeOptionalString(entry.label) || normalizeOptionalString(entry.task) || fallback;
}
function formatRunLabel(entry, options) {
	const raw = sanitizeTaskStatusText(resolveSubagentLabel(entry)) || "subagent";
	const maxLength = options?.maxLength ?? 72;
	if (!Number.isFinite(maxLength) || maxLength <= 0) return raw;
	return raw.length > maxLength ? `${truncateUtf16Safe(raw, maxLength).trimEnd()}…` : raw;
}
function formatRunStatus(entry) {
	if (!entry.endedAt) return "running";
	const status = entry.outcome?.status ?? "done";
	return status === "ok" ? "done" : status;
}
function sortSubagentRuns(runs) {
	return [...runs].toSorted((a, b) => {
		const aTime = a.startedAt ?? a.createdAt ?? 0;
		return (b.startedAt ?? b.createdAt ?? 0) - aTime;
	});
}
function resolveSubagentTargetFromRuns(params) {
	const trimmed = normalizeOptionalString(params.token);
	if (!trimmed) return { error: params.errors.missingTarget };
	const sorted = sortSubagentRuns(params.runs);
	const deduped = [];
	const seenChildSessionKeys = /* @__PURE__ */ new Set();
	for (const entry of sorted) {
		if (seenChildSessionKeys.has(entry.childSessionKey)) continue;
		seenChildSessionKeys.add(entry.childSessionKey);
		deduped.push(entry);
	}
	if (trimmed === "last") return { entry: deduped[0] };
	const isActive = params.isActive ?? ((entry) => !entry.endedAt);
	const recentCutoff = Date.now() - params.recentWindowMinutes * 6e4;
	const numericOrder = [...deduped.filter((entry) => isActive(entry)), ...deduped.filter((entry) => !isActive(entry) && !!entry.endedAt && (entry.endedAt ?? 0) >= recentCutoff)];
	if (/^\d+$/.test(trimmed)) {
		const idx = Number.parseInt(trimmed, 10);
		if (!Number.isFinite(idx) || idx <= 0 || idx > numericOrder.length) return { error: params.errors.invalidIndex(trimmed) };
		return { entry: numericOrder[idx - 1] };
	}
	if (trimmed.includes(":")) {
		const bySessionKey = deduped.find((entry) => entry.childSessionKey === trimmed);
		return bySessionKey ? { entry: bySessionKey } : { error: params.errors.unknownSession(trimmed) };
	}
	const lowered = normalizeLowercaseStringOrEmpty(trimmed);
	const byExactLabel = deduped.filter((entry) => normalizeLowercaseStringOrEmpty(params.label(entry)) === lowered);
	if (byExactLabel.length === 1) return { entry: byExactLabel[0] };
	if (byExactLabel.length > 1) return { error: params.errors.ambiguousLabel(trimmed) };
	const byLabelPrefix = deduped.filter((entry) => normalizeLowercaseStringOrEmpty(params.label(entry)).startsWith(lowered));
	if (byLabelPrefix.length === 1) return { entry: byLabelPrefix[0] };
	if (byLabelPrefix.length > 1) return { error: params.errors.ambiguousLabelPrefix(trimmed) };
	const byRunIdPrefix = deduped.filter((entry) => entry.runId.startsWith(trimmed));
	if (byRunIdPrefix.length === 1) return { entry: byRunIdPrefix[0] };
	if (byRunIdPrefix.length > 1) return { error: params.errors.ambiguousRunIdPrefix(trimmed) };
	return { error: params.errors.unknownTarget(trimmed) };
}
//#endregion
//#region src/shared/subagents-format.ts
function formatTokenShort(value) {
	if (!value || !Number.isFinite(value) || value <= 0) return;
	const n = Math.floor(value);
	if (n < 1e3) return `${n}`;
	if (n < 1e4) return `${(n / 1e3).toFixed(1).replace(/\.0$/, "")}k`;
	if (n < 1e6) return `${Math.round(n / 1e3)}k`;
	return `${(n / 1e6).toFixed(1).replace(/\.0$/, "")}m`;
}
function truncateLine(value, maxLength) {
	if (value.length <= maxLength) return value;
	return `${value.slice(0, maxLength).trimEnd()}...`;
}
function resolveTotalTokens(entry) {
	if (!entry || typeof entry !== "object") return;
	if (typeof entry.totalTokens === "number" && Number.isFinite(entry.totalTokens)) return entry.totalTokens;
	const total = (typeof entry.inputTokens === "number" ? entry.inputTokens : 0) + (typeof entry.outputTokens === "number" ? entry.outputTokens : 0);
	return total > 0 ? total : void 0;
}
function resolveIoTokens(entry) {
	if (!entry || typeof entry !== "object") return;
	const input = typeof entry.inputTokens === "number" && Number.isFinite(entry.inputTokens) ? entry.inputTokens : 0;
	const output = typeof entry.outputTokens === "number" && Number.isFinite(entry.outputTokens) ? entry.outputTokens : 0;
	const total = input + output;
	if (total <= 0) return;
	return {
		input,
		output,
		total
	};
}
function formatTokenUsageDisplay(entry) {
	const io = resolveIoTokens(entry);
	const promptCache = resolveTotalTokens(entry);
	const parts = [];
	if (io) {
		const input = formatTokenShort(io.input) ?? "0";
		const output = formatTokenShort(io.output) ?? "0";
		parts.push(`tokens ${formatTokenShort(io.total)} (in ${input} / out ${output})`);
	} else if (typeof promptCache === "number" && promptCache > 0) parts.push(`tokens ${formatTokenShort(promptCache)} prompt/cache`);
	if (typeof promptCache === "number" && io && promptCache > io.total) parts.push(`prompt/cache ${formatTokenShort(promptCache)}`);
	return parts.join(", ");
}
//#endregion
export { shouldResolveSessionIdInput as C, resolveVisibleSessionReference as S, looksLikeSessionId as T, resolveSandboxedSessionToolContext as _, formatRunStatus as a, resolveMainSessionAlias as b, sortSubagentRuns as c, classifySessionKind as d, deriveChannel as f, resolveEffectiveSessionToolsVisibility as g, createSessionVisibilityGuard as h, formatRunLabel as i, resolveStoredSubagentCapabilities as l, createAgentToAgentPolicy as m, resolveTotalTokens as n, resolveSubagentLabel as o, resolveSessionToolContext as p, truncateLine as r, resolveSubagentTargetFromRuns as s, formatTokenUsageDisplay as t, resolveSubagentCapabilities as u, resolveDisplaySessionKey as v, SESSION_ID_RE as w, resolveSessionReference as x, resolveInternalSessionKey as y };
