import { __esmMin } from "../../_virtual/_rolldown/runtime.js";
import { DEFAULT_ACCOUNT_ID, normalizeAccountId, normalizeOptionalAccountId } from "./account-id.js";
import { getSubagentDepth, init_session_key_utils, isAcpSessionKey, isCronRunSessionKey, isCronSessionKey, isSubagentSessionKey, parseAgentSessionKey, parseRawSessionConversationRef, parseThreadSessionSuffix, resolveThreadParentSessionKey } from "./session-key-utils.js";
import { DEFAULT_AGENT_ID, DEFAULT_MAIN_KEY, assertAgentSessionKey, buildAgentMainSessionKey, buildAgentPeerSessionKey, buildGroupHistoryKey, classifySessionKeyShape, defaultMainSessionKey, init_agent_session_key, isValidAgentId, normalizeAgentId, normalizeMainKey, normalizeSessionKey, resolveAgentIdFromSessionKey, resolveThreadSessionKeys, sanitizeAgentId, scopedHeartbeatWakeOptions, toAgentRequestSessionKey, toAgentStoreSessionKey } from "./agent-session-key.js";
//#region src/routing/session-key.ts
function sanitizeSegment(value, options) {
	const trimmed = (value ?? "").trim();
	if (!trimmed) return "";
	let cleaned = trimmed.toLowerCase().replace(INVALID_CHARS_RE, "-");
	if (!options?.allowLeadingDash) cleaned = cleaned.replace(LEADING_DASH_RE, "").replace(TRAILING_DASH_RE, "");
	else cleaned = cleaned.replace(TRAILING_DASH_RE, "");
	if (!cleaned) return "";
	return cleaned.slice(0, 64);
}
function isValidSegment(value) {
	const trimmed = (value ?? "").trim();
	if (!trimmed || trimmed.length > 64) return false;
	return VALID_SEGMENT_RE.test(trimmed);
}
/** Build an OpenClaw-style agent session key from routing segments. */
function buildSessionKey(params) {
	const peerKind = params.peerKind === "dm" ? "direct" : params.peerKind;
	let key = buildAgentPeerSessionKey({
		agentId: params.agentId,
		mainKey: params.mainKey,
		channel: params.source,
		accountId: params.accountId,
		peerKind,
		peerId: params.peerId,
		identityLinks: params.identityLinks,
		dmScope: params.dmScope ?? (peerKind === "direct" ? "per-account-channel-peer" : void 0)
	});
	if (params.threadId) key = resolveThreadSessionKeys({
		baseSessionKey: key,
		threadId: params.threadId
	}).sessionKey;
	if (params.scopeId) key = `${key}:scope:${sanitizeSegment(params.scopeId, { allowLeadingDash: true }) || "default"}`;
	return key;
}
/** Parse `agent:{agentId}:{rest}` into routing segments. Returns null for invalid keys. */
function parseSessionKey(sessionKey) {
	const raw = (sessionKey ?? "").trim();
	if (!raw) return null;
	const { baseSessionKey, threadId } = parseThreadSuffix(raw);
	const agentParsed = parseAgentSessionKey(baseSessionKey);
	if (!agentParsed) return null;
	const scopeParts = parseScopeSuffix(agentParsed.rest);
	const rest = scopeParts.rest;
	const scopeId = scopeParts.scopeId;
	const mainKey = normalizeMainKey(void 0);
	if (rest === mainKey) return {
		agentId: agentParsed.agentId,
		source: "cli",
		accountId: "default",
		peerKind: "direct",
		peerId: mainKey,
		threadId,
		scopeId
	};
	if (rest.startsWith("subagent:")) return parseSubagentRest(agentParsed.agentId, rest, threadId, scopeId);
	if (rest.startsWith("cron:")) {
		const parts = rest.split(":");
		return {
			agentId: agentParsed.agentId,
			source: "cron",
			accountId: "default",
			peerKind: "direct",
			peerId: parts.slice(1).join(":") || "cron",
			threadId,
			scopeId
		};
	}
	const parts = rest.split(":").filter(Boolean);
	if (parts.length >= 4 && parts[2] === "direct") return {
		agentId: agentParsed.agentId,
		source: parts[0],
		accountId: parts[1],
		peerKind: "direct",
		peerId: parts.slice(3).join(":"),
		threadId,
		scopeId
	};
	if (parts.length >= 3 && parts[1] === "direct") return {
		agentId: agentParsed.agentId,
		source: parts[0],
		accountId: "default",
		peerKind: "direct",
		peerId: parts.slice(2).join(":"),
		threadId,
		scopeId
	};
	if (parts.length >= 2 && parts[0] === "direct") return {
		agentId: agentParsed.agentId,
		source: "cli",
		accountId: "default",
		peerKind: "direct",
		peerId: parts.slice(1).join(":"),
		threadId,
		scopeId
	};
	if (parts.length >= 3 && (parts[1] === "group" || parts[1] === "channel")) return {
		agentId: agentParsed.agentId,
		source: parts[0],
		accountId: "default",
		peerKind: parts[1],
		peerId: parts.slice(2).join(":"),
		threadId,
		scopeId
	};
	return {
		agentId: agentParsed.agentId,
		source: "cli",
		accountId: "default",
		peerKind: "direct",
		peerId: rest,
		threadId,
		scopeId
	};
}
function parseThreadSuffix(raw) {
	const idx = raw.toLowerCase().lastIndexOf(":thread:");
	if (idx === -1) return { baseSessionKey: raw };
	return {
		baseSessionKey: raw.slice(0, idx),
		threadId: raw.slice(idx + 8)
	};
}
function parseScopeSuffix(rest) {
	const idx = rest.toLowerCase().lastIndexOf(":scope:");
	if (idx === -1) return { rest };
	return {
		rest: rest.slice(0, idx),
		scopeId: rest.slice(idx + 7)
	};
}
function parseSubagentRest(parentAgentId, rest, threadId, scopeId) {
	const body = rest.replace(/^subagent:/, "");
	const parentKey = body ? `agent:${parentAgentId}:${body}` : "";
	const parentParsed = parentKey ? parseSessionKey(parentKey) : null;
	if (parentParsed) return {
		...parentParsed,
		agentId: "subagent",
		threadId: threadId ?? parentParsed.threadId,
		scopeId: scopeId ?? parentParsed.scopeId
	};
	return {
		agentId: "subagent",
		source: parentAgentId,
		accountId: "default",
		peerKind: "direct",
		peerId: body || "unknown",
		threadId,
		scopeId
	};
}
function buildSubagentSessionKey(params) {
	const parentParsed = parseAgentSessionKey(params.parentSessionKey);
	if (!parentParsed) throw new Error(`Invalid parent session key: ${params.parentSessionKey}`);
	const parentRest = parentParsed.rest;
	let key = `agent:${normalizeAgentId(parentParsed.agentId)}:subagent:${parentRest}`;
	if (params.threadId) key = resolveThreadSessionKeys({
		baseSessionKey: key,
		threadId: params.threadId
	}).sessionKey;
	return key;
}
function getParentSessionKey(sessionKey) {
	const parsed = parseSessionKey(sessionKey);
	if (!parsed?.threadId) return null;
	return buildSessionKey({
		agentId: parsed.agentId,
		source: parsed.source,
		accountId: parsed.accountId,
		peerKind: parsed.peerKind,
		peerId: parsed.peerId,
		scopeId: parsed.scopeId
	});
}
var VALID_SEGMENT_RE, INVALID_CHARS_RE, LEADING_DASH_RE, TRAILING_DASH_RE;
var init_session_key = __esmMin((() => {
	init_agent_session_key();
	init_agent_session_key();
	init_session_key_utils();
	VALID_SEGMENT_RE = /^[a-z0-9](?:[a-z0-9_-]*[a-z0-9])?$/i;
	INVALID_CHARS_RE = /[^a-z0-9_-]+/g;
	LEADING_DASH_RE = /^-+/;
	TRAILING_DASH_RE = /-+$/;
}));
//#endregion
init_session_key();
export { DEFAULT_ACCOUNT_ID, DEFAULT_AGENT_ID, DEFAULT_MAIN_KEY, assertAgentSessionKey, buildAgentMainSessionKey, buildAgentPeerSessionKey, buildGroupHistoryKey, buildSessionKey, buildSubagentSessionKey, classifySessionKeyShape, defaultMainSessionKey, getParentSessionKey, getSubagentDepth, init_session_key, isAcpSessionKey, isCronRunSessionKey, isCronSessionKey, isSubagentSessionKey, isValidAgentId, isValidSegment, normalizeAccountId, normalizeAgentId, normalizeMainKey, normalizeOptionalAccountId, normalizeSessionKey, parseAgentSessionKey, parseRawSessionConversationRef, parseSessionKey, parseThreadSessionSuffix, resolveAgentIdFromSessionKey, resolveThreadParentSessionKey, resolveThreadSessionKeys, sanitizeAgentId, sanitizeSegment, scopedHeartbeatWakeOptions, toAgentRequestSessionKey, toAgentStoreSessionKey };

//# sourceMappingURL=session-key.js.map