import { __esmMin } from "../../_virtual/_rolldown/runtime.js";
import { init_paths_state, resolveStateDir } from "../config/paths-state.js";
import { expandWorkspacePathString, init_workspace_path } from "../config/workspace-path.js";
import { init_workspace_defaults, resolveDefaultAgentWorkspaceDir } from "../config/workspace-defaults.js";
import fs from "node:fs";
import { basename, isAbsolute, join, relative, resolve } from "node:path";
//#region src/agent/agent-scope.ts
/**
* Agent path and list resolution (config is the single source of truth).
*/
function normalizeLowercaseStringOrEmpty(s) {
	return s.trim().toLowerCase();
}
/** Path-safe agent id. */
function normalizeAgentId(value) {
	const trimmed = (value ?? "").trim();
	if (!trimmed) return DEFAULT_AGENT_ID;
	const normalized = normalizeLowercaseStringOrEmpty(trimmed);
	if (VALID_ID_RE.test(trimmed)) return normalized;
	return normalized.replace(INVALID_CHARS_RE, "-").replace(LEADING_DASH_RE, "").replace(TRAILING_DASH_RE, "").slice(0, 64) || "main";
}
/**
* Validate agent id for new agents (folder-safe path segment).
* When `explicitId` is set, it must already match {@link STRICT_AGENT_ID_RE} (case-insensitive input, stored lowercase).
* When omitted, id is derived from `displayNameForDerivation` via {@link normalizeAgentId}.
*/
function validateAgentIdForNewAgent(explicitId, displayNameForDerivation) {
	const explicit = explicitId?.trim();
	if (explicit) {
		const id = explicit.toLowerCase();
		if (!STRICT_AGENT_ID_RE.test(id)) return {
			ok: false,
			error: "Invalid agent id: use 1–64 characters; letters, digits, underscores, and hyphens only; start with a letter or digit."
		};
		if (id === "main") return {
			ok: false,
			error: `"${DEFAULT_AGENT_ID}" is reserved`
		};
		if (WINDOWS_RESERVED_AGENT_IDS.has(id)) return {
			ok: false,
			error: `Agent id "${id}" is reserved (Windows device name).`
		};
		return {
			ok: true,
			agentId: id
		};
	}
	const agentId = normalizeAgentId(displayNameForDerivation.trim());
	if (agentId === "main") return {
		ok: false,
		error: "Display name cannot produce a valid agent folder id. Set an explicit Agent id (letters, digits, underscores, hyphens only)."
	};
	if (WINDOWS_RESERVED_AGENT_IDS.has(agentId)) return {
		ok: false,
		error: `That display name resolves to "${agentId}", which is reserved. Use a different display name or set an explicit Agent id.`
	};
	if (!STRICT_AGENT_ID_RE.test(agentId)) return {
		ok: false,
		error: "Could not derive a folder-safe agent id from the display name. Set an explicit Agent id (letters, digits, underscores, hyphens only)."
	};
	return {
		ok: true,
		agentId
	};
}
/** Expand `~` and resolve to an absolute path. */
function resolveUserPath(raw) {
	return resolve(expandWorkspacePathString(raw.trim()));
}
function listAgentEntries(cfg) {
	const list = cfg.agents?.list;
	if (!Array.isArray(list)) return [];
	return list.filter((e) => Boolean(e && typeof e === "object"));
}
function resolveDefaultAgentId(cfg) {
	const explicit = cfg.agents?.default?.trim();
	if (explicit) return normalizeAgentId(explicit);
	const agents = listAgentEntries(cfg);
	if (agents.length === 0) return DEFAULT_AGENT_ID;
	const chosen = (agents.filter((a) => a?.default === true)[0] ?? agents[0])?.id?.trim();
	return chosen ? normalizeAgentId(chosen) : DEFAULT_AGENT_ID;
}
function resolveAgentEntry(cfg, agentId) {
	const id = normalizeAgentId(agentId);
	return listAgentEntries(cfg).find((e) => normalizeAgentId(e.id) === id);
}
/**
* Markdown workspace root for an agent.
*/
function resolveAgentWorkspaceDir(cfg, agentId) {
	const id = normalizeAgentId(agentId);
	const configured = resolveAgentEntry(cfg, id)?.workspace?.trim();
	if (configured) return resolveUserPath(configured);
	const defaultAgentId = resolveDefaultAgentId(cfg);
	const fallback = cfg.agents?.defaults?.workspace?.trim();
	if (fallback) return join(resolveUserPath(fallback), id);
	if (id === defaultAgentId) return resolveDefaultAgentWorkspaceDir(process.env);
	return join(resolveStateDir(process.env), `workspace-${id}`);
}
/**
* Internal agent state dir: credentials, `agent.json`, pid, inbox (`…/agent/`).
*/
function resolveAgentDir(cfg, agentId) {
	const id = normalizeAgentId(agentId);
	const configured = resolveAgentEntry(cfg, id)?.agentDir?.trim();
	if (configured) return resolveUserPath(configured);
	return join(resolveStateDir(process.env), "agents", id, "agent");
}
/** Parent of `sessions/` and `agent/`: `<stateDir>/agents/<id>/`. */
function resolveAgentHomeDir(cfg, agentId) {
	return join(resolveStateDir(process.env), "agents", normalizeAgentId(agentId));
}
/** Profile Markdown + gateway avatar files: `<stateDir>/agents/<id>/profile/`. */
function resolveAgentProfileDir(cfg, agentId) {
	return join(resolveAgentHomeDir(cfg, agentId), "profile");
}
/** Resolved path for a single profile Markdown basename (e.g. `SOUL.md`). */
function resolveAgentProfileMarkdownPath(cfg, agentId, filename) {
	const base = basename(filename.trim().replace(/\\/g, "/"));
	return join(resolveAgentProfileDir(cfg, agentId), base);
}
function resolveSessionsDir(cfg, agentId) {
	return join(resolveAgentHomeDir(cfg, agentId), "sessions");
}
function normalizePathForComparison(input) {
	const resolved = resolve(resolveUserPath(input));
	let normalized = resolved;
	try {
		normalized = fs.realpathSync.native(resolved);
	} catch {}
	if (process.platform === "win32") return normalized.toLowerCase();
	return normalized;
}
function isPathWithinRoot(candidatePath, rootPath) {
	const rel = relative(rootPath, candidatePath);
	return rel === "" || !rel.startsWith("..") && !isAbsolute(rel);
}
/** Agent ids whose workspace root contains `workspacePath` (longest match first). */
function resolveAgentIdsByWorkspacePath(cfg, workspacePath) {
	const normalizedWorkspacePath = normalizePathForComparison(workspacePath);
	const entries = listAgentEntries(cfg);
	const matches = [];
	for (let index = 0; index < entries.length; index += 1) {
		const entry = entries[index];
		const id = normalizeAgentId(entry.id);
		const workspaceDir = normalizePathForComparison(resolveAgentWorkspaceDir(cfg, id));
		if (!isPathWithinRoot(normalizedWorkspacePath, workspaceDir)) continue;
		matches.push({
			id,
			workspaceDir,
			order: index
		});
	}
	const defaultId = resolveDefaultAgentId(cfg);
	if (!entries.some((e) => normalizeAgentId(e.id) === defaultId)) {
		const workspaceDir = normalizePathForComparison(resolveAgentWorkspaceDir(cfg, defaultId));
		if (isPathWithinRoot(normalizedWorkspacePath, workspaceDir)) matches.push({
			id: defaultId,
			workspaceDir,
			order: entries.length
		});
	}
	matches.sort((left, right) => {
		const workspaceLengthDelta = right.workspaceDir.length - left.workspaceDir.length;
		if (workspaceLengthDelta !== 0) return workspaceLengthDelta;
		return left.order - right.order;
	});
	return matches.map((entry) => entry.id);
}
/** Best-matching agent id for cwd, or `undefined` when no workspace contains the path. */
function resolveAgentIdByWorkspacePath(cfg, workspacePath) {
	return resolveAgentIdsByWorkspacePath(cfg, workspacePath)[0];
}
/**
* Find the agent id whose resolved markdown workspace matches `resolvedWorkspacePath`.
* Falls back to {@link resolveDefaultAgentId} when no list entry matches.
*/
function resolveAgentIdForWorkspacePath(cfg, resolvedWorkspacePath) {
	return resolveAgentIdByWorkspacePath(cfg, resolvedWorkspacePath) ?? resolveDefaultAgentId(cfg);
}
function getDefaultWorkspacePath(cfg) {
	return resolveAgentWorkspaceDir(cfg, resolveDefaultAgentId(cfg));
}
var DEFAULT_AGENT_ID, VALID_ID_RE, INVALID_CHARS_RE, LEADING_DASH_RE, TRAILING_DASH_RE, STRICT_AGENT_ID_RE, WINDOWS_RESERVED_AGENT_IDS;
var init_agent_scope = __esmMin((() => {
	init_paths_state();
	init_workspace_path();
	init_workspace_defaults();
	DEFAULT_AGENT_ID = "main";
	VALID_ID_RE = /^[a-z0-9][a-z0-9_-]{0,63}$/i;
	INVALID_CHARS_RE = /[^a-z0-9_-]+/g;
	LEADING_DASH_RE = /^-+/;
	TRAILING_DASH_RE = /-+$/;
	STRICT_AGENT_ID_RE = /^[a-z0-9][a-z0-9_-]{0,63}$/;
	WINDOWS_RESERVED_AGENT_IDS = new Set([
		"con",
		"prn",
		"aux",
		"nul",
		"com1",
		"com2",
		"com3",
		"com4",
		"com5",
		"com6",
		"com7",
		"com8",
		"com9",
		"lpt1",
		"lpt2",
		"lpt3",
		"lpt4",
		"lpt5",
		"lpt6",
		"lpt7",
		"lpt8",
		"lpt9"
	]);
}));
//#endregion
init_agent_scope();
export { DEFAULT_AGENT_ID, STRICT_AGENT_ID_RE, getDefaultWorkspacePath, init_agent_scope, listAgentEntries, normalizeAgentId, resolveAgentDir, resolveAgentHomeDir, resolveAgentIdByWorkspacePath, resolveAgentIdForWorkspacePath, resolveAgentIdsByWorkspacePath, resolveAgentProfileDir, resolveAgentProfileMarkdownPath, resolveAgentWorkspaceDir, resolveDefaultAgentId, resolveSessionsDir, resolveUserPath, validateAgentIdForNewAgent };

//# sourceMappingURL=agent-scope.js.map