#!/usr/bin/env node

import { Ir as runtimeAgentControllerLaunchContractSchema, Lr as runtimeAgentControllerSettingsSchema, a as runWithHeldLock, n as isAtsLockError, t as acquireLock } from "./lock-C8RSrglP.js";
import { D as resolveAtsEnvPreset, _ as deviceSkillsInstallsPath, b as legacyRuntimeConfigPath, g as deviceSkillsDir, h as deviceSkillsCustomTargetsPath, l as deviceAgentRuntimePath, m as devicePreferencesPath, u as deviceDir, v as deviceSkillsStorePath } from "./paths-DFiopT5Y.js";
import { dirname, normalize, posix, win32 } from "node:path";
import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
import { createHash } from "node:crypto";

//#region src/protocol/urls.ts
const TRAILING_SLASHES_REGEX = /\/+$/;
const ROOT_PATH_REGEX = /^\/+$/;
function normalizeBaseUrl(baseUrl) {
	const url = new URL(baseUrl);
	if (!ROOT_PATH_REGEX.test(url.pathname)) throw new Error("baseUrl must be origin-only (no path prefix)");
	if (url.search || url.hash) throw new Error("baseUrl must be origin-only (no query or hash)");
	url.pathname = "";
	url.search = "";
	url.hash = "";
	return url.toString().replace(TRAILING_SLASHES_REGEX, "");
}
function toSpaceSignalsUrl(baseUrl, space) {
	const url = new URL(normalizeBaseUrl(baseUrl));
	url.pathname = `/v1/spaces/${encodeURIComponent(space)}/signals`;
	return url.toString();
}
function toSpaceCreateUrl(baseUrl) {
	const url = new URL(normalizeBaseUrl(baseUrl));
	url.pathname = "/v1/spaces";
	return url.toString();
}
function toSpaceDeleteUrl(baseUrl, space) {
	const url = new URL(normalizeBaseUrl(baseUrl));
	url.pathname = `/v1/spaces/${encodeURIComponent(space)}`;
	return url.toString();
}
function toSpaceMetaUrl(baseUrl, space) {
	const url = new URL(normalizeBaseUrl(baseUrl));
	url.pathname = `/v1/spaces/${encodeURIComponent(space)}/meta`;
	return url.toString();
}
function toSpaceContractUrl(baseUrl, space) {
	const url = new URL(normalizeBaseUrl(baseUrl));
	url.pathname = `/v1/spaces/${encodeURIComponent(space)}/contract`;
	return url.toString();
}
function toSpaceUpdatesUrl(baseUrl, space) {
	const url = new URL(normalizeBaseUrl(baseUrl));
	url.pathname = `/v1/spaces/${encodeURIComponent(space)}/updates`;
	return url.toString();
}
function toSpaceResultUrl(baseUrl, space) {
	const url = new URL(normalizeBaseUrl(baseUrl));
	url.pathname = `/v1/spaces/${encodeURIComponent(space)}/result`;
	return url.toString();
}
function toSpaceMembersUrl(baseUrl, space) {
	const url = new URL(normalizeBaseUrl(baseUrl));
	url.pathname = `/v1/spaces/${encodeURIComponent(space)}/members`;
	return url.toString();
}
function toSpaceRemoveMembersUrl(baseUrl, space) {
	const url = new URL(normalizeBaseUrl(baseUrl));
	url.pathname = `/v1/spaces/${encodeURIComponent(space)}/members/remove`;
	return url.toString();
}
function toSpaceLeaveUrl(baseUrl, space) {
	const url = new URL(normalizeBaseUrl(baseUrl));
	url.pathname = `/v1/spaces/${encodeURIComponent(space)}/leave`;
	return url.toString();
}
function toSpaceDispatchTraceUrl(baseUrl, space, dispatchId) {
	const url = new URL(normalizeBaseUrl(baseUrl));
	url.pathname = `/v1/spaces/${encodeURIComponent(space)}/dispatches/${encodeURIComponent(dispatchId)}/trace`;
	return url.toString();
}
function toSpaceDispatchLookupUrl(baseUrl, space) {
	const url = new URL(normalizeBaseUrl(baseUrl));
	url.pathname = `/v1/spaces/${encodeURIComponent(space)}/dispatches/lookup`;
	return url.toString();
}
function toDaemonRouteObservationUrl(baseUrl, profileId) {
	const url = new URL(normalizeBaseUrl(baseUrl));
	url.pathname = `/v1/daemon/routes/${encodeURIComponent(profileId)}`;
	return url.toString();
}
function toSpacePasswordUrl(baseUrl, space) {
	const url = new URL(normalizeBaseUrl(baseUrl));
	url.pathname = `/v1/spaces/${encodeURIComponent(space)}/password`;
	return url.toString();
}
function toSpaceCursorUrl(baseUrl, space, profileId) {
	const url = new URL(normalizeBaseUrl(baseUrl));
	url.pathname = `/v1/spaces/${encodeURIComponent(space)}/cursors/${encodeURIComponent(profileId)}`;
	return url.toString();
}
function toSpaceWsUrl(baseUrl, space) {
	const http = new URL(normalizeBaseUrl(baseUrl));
	let wsScheme;
	if (http.protocol === "http:") wsScheme = "ws:";
	else if (http.protocol === "https:") wsScheme = "wss:";
	else if (http.protocol === "ws:" || http.protocol === "wss:") wsScheme = http.protocol;
	else throw new Error(`unsupported baseUrl protocol for websocket URL: ${http.protocol}`);
	return `${wsScheme}//${http.host}/v1/spaces/${encodeURIComponent(space)}/stream`;
}

//#endregion
//#region src/config/runtime-config.ts
const DEFAULT_RUNTIME_AGENT_TRANSPORT_MODE = "local-cli";
const DEFAULT_RUNTIME_AGENT_STREAMING_MODE = "final";
const DEFAULT_LOCAL_ADAPTER_TIMEOUT_MS = null;
const DEFAULT_RUNTIME_AGENT_RETRY = 0;
const DEFAULT_RUNTIME_AGENT_CONTEXT_MAPPING_VERSION = 1;
const DEFAULT_RUNTIME_AGENT_CONTEXT_SOURCE_FIELD = "ATS_CLI_CONTEXT_ID";
const DEFAULT_RUNTIME_DAEMON_GLOBAL_CONCURRENCY = 10;
const DEFAULT_RUNTIME_DAEMON_QUEUE_MAX = 50;
const CUSTOM_TARGET_ID_PREFIX = "custom-";
const CUSTOM_TARGET_ID_LENGTH = 12;
const RUNTIME_CONFIG_LOCK_PROFILE = "__system__";
const RUNTIME_CONFIG_LOCK_KEY = "runtime-config";
const RUNTIME_CONFIG_LOCK_MAX_ATTEMPTS = 40;
const RUNTIME_CONFIG_LOCK_RETRY_DELAY_MS = 25;
const WINDOWS_DRIVE_ONLY_RE = /^[a-zA-Z]:$/;
const WINDOWS_DRIVE_PREFIX_RE = /^[a-zA-Z]:[\\/]/;
const WINDOWS_UNC_RE = /^[/\\]{2}[^/\\]+[/\\]+[^/\\]+/;
const WINDOWS_DRIVE_ANY_RE = /^[a-zA-Z]:/;
const TRAILING_PATH_SEPARATORS_RE = /[\\/]+$/;
function resolveRuntimeSkillsCustomTargetId(input) {
	const existingId = typeof input.id === "string" && input.id.trim().length > 0 ? input.id.trim() : "";
	if (existingId) return existingId;
	const normalizedDir = normalizeCustomTargetDir(input.dir);
	return `${CUSTOM_TARGET_ID_PREFIX}${createHash("sha256").update(normalizedDir).digest("hex").slice(0, CUSTOM_TARGET_ID_LENGTH)}`;
}
function resolveDefaultAgentContextSourceField(_agentId) {
	return DEFAULT_RUNTIME_AGENT_CONTEXT_SOURCE_FIELD;
}
function createDefaultRuntimeAgentControllerSettings(agentId) {
	return {
		transportMode: DEFAULT_RUNTIME_AGENT_TRANSPORT_MODE,
		streamingMode: resolveDefaultRuntimeAgentStreamingMode(),
		timeoutMs: DEFAULT_LOCAL_ADAPTER_TIMEOUT_MS,
		retry: DEFAULT_RUNTIME_AGENT_RETRY,
		contextIdMappingSpec: {
			sourceField: resolveDefaultAgentContextSourceField(agentId),
			mappingVersion: DEFAULT_RUNTIME_AGENT_CONTEXT_MAPPING_VERSION
		}
	};
}
const resolveDefaultRuntimeAgentStreamingMode = () => {
	const preset = resolveAtsEnvPreset();
	if (preset === "dev-local" || preset === "canary") return "stream";
	return DEFAULT_RUNTIME_AGENT_STREAMING_MODE;
};
async function getConfiguredBaseUrl() {
	const config = await readRuntimeConfig();
	if (!config?.baseUrl) return null;
	return normalizeGatewayBaseUrl(config.baseUrl);
}
async function getConfiguredViewCustomization() {
	return (await readRuntimeConfig())?.viewCustomization ?? null;
}
async function getConfiguredSkillsConfig() {
	return (await readRuntimeConfig())?.skills ?? null;
}
async function getConfiguredDeviceRuntimeState() {
	return (await readRuntimeConfig())?.deviceRuntimeState ?? null;
}
async function getConfiguredDaemonDispatchLimits() {
	return resolveRuntimeDaemonDispatchLimits((await readRuntimeConfig())?.daemon?.dispatch);
}
async function getConfiguredOnboardingConfig() {
	return (await readRuntimeConfig())?.onboarding ?? null;
}
async function getConfiguredOnboardingDisclaimerAcceptedAt() {
	return (await getConfiguredOnboardingConfig())?.disclaimerAcceptedAt ?? null;
}
async function getConfiguredStartV1OnboardingState() {
	return (await getConfiguredOnboardingConfig())?.startV1 ?? null;
}
async function getRuntimeConfigReadHealth() {
	return (await readRuntimeConfigDetailed()).health;
}
async function alignRuntimeConfigStorage() {
	return await withRuntimeConfigLock(async () => {
		const split = await readSplitRuntimeConfigDetailed();
		const legacy = await readLegacyRuntimeConfigDetailed();
		const hasLegacyConfig = await pathExists(legacyRuntimeConfigPath());
		if (legacy.config && (!split.hasFiles || split.health.parseFallback)) {
			await writeRuntimeConfig(legacy.config);
			return {
				migratedLegacyConfig: true,
				removedLegacyConfig: hasLegacyConfig
			};
		}
		if (hasLegacyConfig && split.hasFiles) {
			await rm(legacyRuntimeConfigPath(), { force: true });
			return {
				migratedLegacyConfig: false,
				removedLegacyConfig: true
			};
		}
		return {
			migratedLegacyConfig: false,
			removedLegacyConfig: false
		};
	});
}
async function setConfiguredBaseUrl(baseUrl) {
	await withRuntimeConfigLock(async () => {
		const normalized = normalizeGatewayBaseUrl(baseUrl);
		await writeRuntimeConfig(buildNextConfig(await readRuntimeConfig(), { baseUrl: normalized }));
	});
}
async function setConfiguredSkillsConfig(skills) {
	await withRuntimeConfigLock(async () => {
		await writeRuntimeConfig(buildNextConfig(await readRuntimeConfig(), { skills }));
	});
}
async function updateConfiguredSkillsConfig(updater) {
	await withRuntimeConfigLock(async () => {
		const previous = await readRuntimeConfig();
		const previousSkills = previous?.skills ?? null;
		const nextSkills = updater(previousSkills);
		if (JSON.stringify(previousSkills) === JSON.stringify(nextSkills)) return;
		await writeRuntimeConfig(buildNextConfig(previous, { skills: nextSkills }));
	});
}
async function updateConfiguredDeviceRuntimeState(updater) {
	await withRuntimeConfigLock(async () => {
		const previous = await readRuntimeConfig();
		const previousDeviceRuntimeState = previous?.deviceRuntimeState ?? null;
		const nextDeviceRuntimeState = updater(previousDeviceRuntimeState);
		if (JSON.stringify(previousDeviceRuntimeState) === JSON.stringify(nextDeviceRuntimeState)) return;
		await writeRuntimeConfig(buildNextConfig(previous, { deviceRuntimeState: nextDeviceRuntimeState }));
	});
}
async function updateConfiguredStartV1OnboardingState(updater) {
	await withRuntimeConfigLock(async () => {
		const previous = await readRuntimeConfig();
		const previousOnboarding = previous?.onboarding ?? null;
		const previousStartV1 = previousOnboarding?.startV1 ?? null;
		const nextStartV1 = updater(previousStartV1);
		if (JSON.stringify(previousStartV1) === JSON.stringify(nextStartV1)) return;
		await writeRuntimeConfig(buildNextConfig(previous, { onboarding: nextStartV1 || previousOnboarding?.disclaimerAcceptedAt ? {
			...previousOnboarding?.disclaimerAcceptedAt ? { disclaimerAcceptedAt: previousOnboarding.disclaimerAcceptedAt } : {},
			...nextStartV1 ? { startV1: nextStartV1 } : {}
		} : null }));
	});
}
async function updateConfiguredOnboardingConfig(updater) {
	await withRuntimeConfigLock(async () => {
		const previous = await readRuntimeConfig();
		const previousOnboarding = previous?.onboarding ?? null;
		const nextOnboarding = updater(previousOnboarding);
		if (JSON.stringify(previousOnboarding) === JSON.stringify(nextOnboarding)) return;
		await writeRuntimeConfig(buildNextConfig(previous, { onboarding: nextOnboarding }));
	});
}
function buildNextConfig(previous, overrides) {
	const baseUrl = resolveBaseUrlOverride(previous?.baseUrl, overrides);
	const viewCustomization = resolveConfigOverride("viewCustomization", previous?.viewCustomization, overrides);
	const skills = resolveConfigOverride("skills", previous?.skills, overrides);
	const daemon = resolveConfigOverride("daemon", previous?.daemon, overrides);
	const deviceRuntimeState = resolveConfigOverride("deviceRuntimeState", previous?.deviceRuntimeState, overrides);
	const onboarding = resolveConfigOverride("onboarding", previous?.onboarding, overrides);
	return {
		v: 1,
		...baseUrl ? { baseUrl } : {},
		...viewCustomization ? { viewCustomization } : {},
		...skills ? { skills } : {},
		...daemon ? { daemon } : {},
		...deviceRuntimeState ? { deviceRuntimeState } : {},
		...onboarding ? { onboarding } : {},
		updatedAt: (/* @__PURE__ */ new Date()).toISOString()
	};
}
function resolveBaseUrlOverride(previous, overrides) {
	if (!("baseUrl" in overrides)) return previous;
	if (typeof overrides.baseUrl !== "string" || overrides.baseUrl.length === 0) return;
	return overrides.baseUrl;
}
function resolveConfigOverride(key, previous, overrides) {
	if (!(key in overrides)) return previous;
	return overrides[key] ?? void 0;
}
async function acquireRuntimeConfigLock() {
	for (let attempt = 0; attempt < RUNTIME_CONFIG_LOCK_MAX_ATTEMPTS; attempt += 1) try {
		return await acquireLock({
			atsProfileId: RUNTIME_CONFIG_LOCK_PROFILE,
			key: RUNTIME_CONFIG_LOCK_KEY
		});
	} catch (error) {
		if (!isAtsLockError(error) || attempt === RUNTIME_CONFIG_LOCK_MAX_ATTEMPTS - 1) throw error;
		await delay(RUNTIME_CONFIG_LOCK_RETRY_DELAY_MS);
	}
	throw new Error("runtime config lock retries exhausted");
}
async function withRuntimeConfigLock(run) {
	return await runWithHeldLock({
		lock: await acquireRuntimeConfigLock(),
		run,
		releaseContext: {
			component: "runtime_config",
			lockKey: RUNTIME_CONFIG_LOCK_KEY,
			atsProfileId: RUNTIME_CONFIG_LOCK_PROFILE
		}
	});
}
async function readRuntimeConfig() {
	return (await readRuntimeConfigDetailed()).config;
}
async function readRuntimeConfigDetailed() {
	const split = await readSplitRuntimeConfigDetailed();
	if (split.hasFiles) return {
		config: split.config,
		health: split.health
	};
	return await readLegacyRuntimeConfigDetailed();
}
function parseConfiguredBaseUrl(value) {
	if (typeof value !== "string") return;
	try {
		return normalizeGatewayBaseUrl(value);
	} catch {
		return;
	}
}
function parseRuntimeViewCustomization(value) {
	if (!value || typeof value !== "object") return;
	const obj = value;
	const messages = parseMessageCustomization(obj.messages);
	const render = parseRenderCustomization(obj.render);
	if (!(messages || render)) return;
	return {
		...messages ? { messages } : {},
		...render ? { render } : {}
	};
}
function parseRuntimeSkillsConfig(value) {
	if (!value || typeof value !== "object") return;
	const obj = value;
	const storeDir = typeof obj.storeDir === "string" && obj.storeDir.trim().length > 0 ? obj.storeDir.trim() : void 0;
	const agents = parseRuntimeSkillsAgents(obj.agents);
	const installs = parseRuntimeSkillsInstallRecords(obj.installs);
	const customTargets = parseRuntimeSkillsCustomTargets(obj.customTargets, buildLegacyCustomTargetIdByDir(installs));
	if (!(storeDir || agents || customTargets || installs)) return;
	return {
		...storeDir ? { storeDir } : {},
		...agents ? { agents } : {},
		...customTargets ? { customTargets } : {},
		...installs ? { installs } : {}
	};
}
function parseRuntimeDaemonConfig(value) {
	if (!value || typeof value !== "object") return;
	const dispatch = parseRuntimeDaemonDispatchConfig(value.dispatch);
	if (!dispatch) return;
	return { dispatch };
}
function parseRuntimeDaemonDispatchConfig(value) {
	if (!value || typeof value !== "object") return;
	const obj = value;
	const globalConcurrency = parsePositiveInteger(obj.globalConcurrency);
	const queueMax = parsePositiveInteger(obj.queueMax);
	if (globalConcurrency === void 0 && queueMax === void 0) return;
	return {
		...globalConcurrency === void 0 ? {} : { globalConcurrency },
		...queueMax === void 0 ? {} : { queueMax }
	};
}
function parseRuntimeDeviceRuntimeState(value) {
	return parseRuntimeDeviceRuntimeStateObject(value);
}
function parseRuntimeDeviceRuntimeStateObject(value) {
	if (!value || typeof value !== "object") return;
	const controllers = parseRuntimeAgentControllerStates(value.controllers);
	if (!controllers) return;
	return { controllers };
}
function parseRuntimeOnboardingConfig(value) {
	if (!value || typeof value !== "object") return;
	const obj = value;
	const disclaimerAcceptedAt = toTrimmedStringOrUndefined(obj.disclaimerAcceptedAt);
	const startV1 = parseRuntimeStartV1OnboardingState(obj.startV1);
	if (!(disclaimerAcceptedAt || startV1)) return;
	return {
		...disclaimerAcceptedAt ? { disclaimerAcceptedAt } : {},
		...startV1 ? { startV1 } : {}
	};
}
function parseRuntimeStartV1OnboardingState(value) {
	if (!value || typeof value !== "object") return;
	const obj = value;
	const disclaimerAcceptedVersion = toTrimmedStringOrUndefined(obj.disclaimerAcceptedVersion);
	const lastCompletedAt = toTrimmedStringOrUndefined(obj.lastCompletedAt);
	const localAgentsSetupCompletedAt = toTrimmedStringOrUndefined(obj.localAgentsSetupCompletedAt);
	if (!(disclaimerAcceptedVersion || lastCompletedAt || localAgentsSetupCompletedAt)) return;
	return {
		...disclaimerAcceptedVersion ? { disclaimerAcceptedVersion } : {},
		...lastCompletedAt ? { lastCompletedAt } : {},
		...localAgentsSetupCompletedAt ? { localAgentsSetupCompletedAt } : {}
	};
}
async function writeRuntimeConfig(next) {
	await mkdir(deviceDir(), { recursive: true });
	await mkdir(deviceSkillsDir(), { recursive: true });
	const updatedAt = (/* @__PURE__ */ new Date()).toISOString();
	await writeJsonFileOrRemove(devicePreferencesPath(), buildDevicePreferencesState(next, updatedAt));
	await writeJsonFileOrRemove(deviceAgentRuntimePath(), buildDeviceAgentRuntimeState(next, updatedAt));
	await writeJsonFileOrRemove(deviceSkillsStorePath(), buildDeviceSkillsStoreState(next, updatedAt));
	await writeJsonFileOrRemove(deviceSkillsCustomTargetsPath(), buildDeviceSkillsCustomTargetsState(next, updatedAt));
	await writeJsonFileOrRemove(deviceSkillsInstallsPath(), buildDeviceSkillsInstallsState(next, updatedAt));
	await rm(legacyRuntimeConfigPath(), { force: true }).catch(() => void 0);
}
function delay(ms) {
	return new Promise((resolve) => {
		setTimeout(resolve, ms);
	});
}
function parseMessageCustomization(value) {
	if (!value || typeof value !== "object") return;
	const obj = value;
	const human = toStringMap(obj.human);
	const agent = toStringMap(obj.agent);
	if (!(human || agent)) return;
	return {
		...human ? { human } : {},
		...agent ? { agent } : {}
	};
}
function parseRenderCustomization(value) {
	if (!value || typeof value !== "object") return;
	const obj = value;
	const humanRaw = obj.human;
	const agentRaw = obj.agent;
	const human = humanRaw?.dataMode === "payload" || humanRaw?.dataMode === "envelope" ? { dataMode: humanRaw.dataMode } : void 0;
	const agent = agentRaw?.envelopeMode === "verbose" || agentRaw?.envelopeMode === "compact" ? { envelopeMode: agentRaw.envelopeMode } : void 0;
	if (!(human || agent)) return;
	return {
		...human ? { human } : {},
		...agent ? { agent } : {}
	};
}
function parseRuntimeSkillsAgents(value) {
	if (!value || typeof value !== "object") return;
	const entries = Object.entries(value).flatMap(([agentName, agentValue]) => {
		if (!agentValue || typeof agentValue !== "object") return [];
		const agentObj = agentValue;
		const skillsDir = typeof agentObj.skillsDir === "string" && agentObj.skillsDir.trim().length > 0 ? agentObj.skillsDir.trim() : void 0;
		const globalSkillsDir = typeof agentObj.globalSkillsDir === "string" && agentObj.globalSkillsDir.trim().length > 0 ? agentObj.globalSkillsDir.trim() : void 0;
		if (!(skillsDir || globalSkillsDir)) return [];
		return [[agentName, {
			...skillsDir ? { skillsDir } : {},
			...globalSkillsDir ? { globalSkillsDir } : {}
		}]];
	});
	if (entries.length === 0) return;
	return Object.fromEntries(entries);
}
function parseRuntimeSkillsCustomTargets(value, legacyCustomTargetIdByDir) {
	if (!Array.isArray(value)) return;
	const targets = value.flatMap((item) => {
		if (!item || typeof item !== "object") return [];
		const obj = item;
		const name = typeof obj.name === "string" && obj.name.trim().length > 0 ? obj.name.trim() : "";
		const dir = typeof obj.dir === "string" && obj.dir.trim().length > 0 ? normalizeCustomTargetDir(obj.dir) : "";
		if (!(name && dir)) return [];
		const explicitId = toTrimmedStringOrUndefined(obj.id);
		const fallbackLegacyId = legacyCustomTargetIdByDir?.get(dir);
		return [{
			id: resolveRuntimeSkillsCustomTargetId({
				dir,
				...explicitId ? { id: explicitId } : {},
				...!explicitId && fallbackLegacyId ? { id: fallbackLegacyId } : {}
			}),
			name,
			dir
		}];
	});
	if (targets.length === 0) return;
	return targets;
}
function parseRuntimeSkillsInstallRecords(value) {
	if (!Array.isArray(value)) return;
	const records = value.map((item) => parseRuntimeSkillsInstallRecord(item)).filter((record) => record !== null);
	if (records.length === 0) return;
	return records;
}
function buildLegacyCustomTargetIdByDir(installs) {
	const byDir = /* @__PURE__ */ new Map();
	for (const install of installs ?? []) {
		if (!install.targetId.startsWith(CUSTOM_TARGET_ID_PREFIX)) continue;
		const normalizedTargetDir = normalizeCustomTargetDir(install.targetDir);
		if (!normalizedTargetDir) continue;
		byDir.set(normalizedTargetDir, install.targetId);
	}
	return byDir;
}
function parseRuntimeSkillsInstallRecord(value) {
	if (!value || typeof value !== "object") return null;
	const obj = value;
	const targetId = toTrimmedStringOrEmpty(obj.targetId);
	const targetDir = toTrimmedStringOrEmpty(obj.targetDir);
	const mode = parseSkillsInstallMode(obj.mode);
	const status = parseSkillsInstallStatus(obj.status);
	const skillIds = Array.isArray(obj.skillIds) ? obj.skillIds.map((skill) => typeof skill === "string" ? skill.trim() : "").filter((skill) => skill.length > 0) : [];
	const updatedAt = toTrimmedStringOrEmpty(obj.updatedAt);
	const reason = toTrimmedStringOrUndefined(obj.reason);
	if (!(targetId && targetDir && mode && status && updatedAt)) return null;
	return {
		targetId,
		targetDir,
		mode,
		status,
		skillIds,
		...reason ? { reason } : {},
		updatedAt
	};
}
function parseRuntimeAgentControllerStates(value) {
	if (!Array.isArray(value)) return;
	const parsed = value.map((entry) => parseRuntimeAgentControllerState(entry)).filter((entry) => entry !== null);
	if (parsed.length === 0) return;
	const deduped = /* @__PURE__ */ new Map();
	for (const entry of parsed) deduped.set(entry.agentId, entry);
	return [...deduped.values()].sort((a, b) => a.agentId.localeCompare(b.agentId));
}
function parseRuntimeAgentControllerState(value) {
	if (!value || typeof value !== "object") return null;
	const obj = value;
	const agentId = toTrimmedStringOrEmpty(obj.agentId);
	const displayName = toTrimmedStringOrEmpty(obj.displayName);
	const enabled = typeof obj.enabled === "boolean" ? obj.enabled : null;
	const launchContract = parseRuntimeAgentControllerLaunchContract(obj.launchContract);
	const defaults = createDefaultRuntimeAgentControllerSettings(agentId);
	const controllerSettings = parseRuntimeAgentControllerSettings({
		transportMode: obj.transportMode,
		streamingMode: obj.streamingMode,
		timeoutMs: obj.timeoutMs,
		retry: obj.retry,
		contextIdMappingSpec: obj.contextIdMappingSpec
	}, defaults);
	const registeredAt = toTrimmedStringOrEmpty(obj.registeredAt);
	const updatedAt = toTrimmedStringOrEmpty(obj.updatedAt);
	if (!(agentId && displayName && enabled !== null && controllerSettings && registeredAt && updatedAt)) return null;
	return {
		agentId,
		displayName,
		enabled,
		...launchContract ? { launchContract } : {},
		transportMode: controllerSettings.transportMode,
		streamingMode: controllerSettings.streamingMode,
		timeoutMs: controllerSettings.timeoutMs,
		retry: controllerSettings.retry,
		contextIdMappingSpec: controllerSettings.contextIdMappingSpec,
		registeredAt,
		updatedAt
	};
}
function parseRuntimeAgentControllerLaunchContract(value) {
	if (!(value && typeof value === "object")) return;
	const parsed = runtimeAgentControllerLaunchContractSchema.safeParse(value);
	return parsed.success ? parsed.data : void 0;
}
function parseRuntimeAgentControllerSettings(raw, defaults) {
	const normalizedStreamingMode = normalizeRuntimeStreamingMode(raw.streamingMode);
	const parsed = runtimeAgentControllerSettingsSchema.safeParse({
		transport_mode: raw.transportMode ?? defaults.transportMode,
		streaming_mode: normalizedStreamingMode ?? defaults.streamingMode,
		timeout_ms: raw.timeoutMs === void 0 ? defaults.timeoutMs : raw.timeoutMs,
		retry: raw.retry ?? defaults.retry,
		context_id_mapping_spec: raw.contextIdMappingSpec ?? defaults.contextIdMappingSpec
	});
	if (!parsed.success) return null;
	return {
		transportMode: parsed.data.transport_mode,
		streamingMode: parsed.data.streaming_mode,
		timeoutMs: normalizeRuntimeAgentTimeoutMs({
			defaults,
			timeoutMs: parsed.data.timeout_ms
		}),
		retry: parsed.data.retry,
		contextIdMappingSpec: normalizeRuntimeAgentControllerConversationIdMappingSpec({
			contextIdMappingSpec: parsed.data.context_id_mapping_spec,
			defaults
		})
	};
}
function normalizeRuntimeAgentTimeoutMs(input) {
	if (input.timeoutMs === 12e4) return input.defaults.timeoutMs;
	return input.timeoutMs;
}
function normalizeRuntimeAgentControllerConversationIdMappingSpec(input) {
	if (input.contextIdMappingSpec.sourceField !== DEFAULT_RUNTIME_AGENT_CONTEXT_SOURCE_FIELD) return input.defaults.contextIdMappingSpec;
	return input.contextIdMappingSpec;
}
function resolveRuntimeDaemonDispatchLimits(config) {
	return {
		globalConcurrency: parsePositiveInteger(config?.globalConcurrency) ?? DEFAULT_RUNTIME_DAEMON_GLOBAL_CONCURRENCY,
		queueMax: parsePositiveInteger(config?.queueMax) ?? DEFAULT_RUNTIME_DAEMON_QUEUE_MAX
	};
}
function normalizeRuntimeStreamingMode(value) {
	if (value === "final" || value === "stream") return value;
	return null;
}
function parseSkillsInstallMode(value) {
	if (value === "symlink" || value === "copy") return value;
	return null;
}
function parseSkillsInstallStatus(value) {
	if (value === "installed" || value === "skipped" || value === "failed") return value;
	return null;
}
function parsePositiveInteger(value) {
	if (!Number.isInteger(value)) return;
	const numericValue = Number(value);
	if (numericValue <= 0) return;
	return numericValue;
}
function toTrimmedStringOrEmpty(value) {
	if (typeof value !== "string") return "";
	const trimmed = value.trim();
	return trimmed.length > 0 ? trimmed : "";
}
function toTrimmedStringOrUndefined(value) {
	if (typeof value !== "string") return;
	const trimmed = value.trim();
	return trimmed.length > 0 ? trimmed : void 0;
}
function normalizeCustomTargetDir(value) {
	const trimmed = value.trim();
	if (!trimmed) return "";
	if (WINDOWS_DRIVE_ONLY_RE.test(trimmed)) return `${trimmed[0]?.toUpperCase() ?? ""}:`;
	const normalizedPath = WINDOWS_DRIVE_PREFIX_RE.test(trimmed) || WINDOWS_UNC_RE.test(trimmed) ? (() => {
		const normalizedWindowsPath = win32.normalize(trimmed);
		if (WINDOWS_DRIVE_ANY_RE.test(normalizedWindowsPath)) return `${normalizedWindowsPath[0]?.toUpperCase() ?? ""}${normalizedWindowsPath.slice(1)}`;
		return normalizedWindowsPath;
	})() : normalize(trimmed);
	const isPosixRoot = normalizedPath === posix.parse(normalizedPath).root;
	const isWindowsRoot = normalizedPath === win32.parse(normalizedPath).root;
	if (isPosixRoot || isWindowsRoot) return normalizedPath;
	return normalizedPath.replace(TRAILING_PATH_SEPARATORS_RE, "");
}
function toStringMap(value) {
	if (!value || typeof value !== "object") return;
	const entries = Object.entries(value).filter((entry) => typeof entry[1] === "string");
	if (entries.length === 0) return;
	return Object.fromEntries(entries);
}
function isFileNotFoundError(error) {
	return typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT";
}
async function readSplitRuntimeConfigDetailed() {
	const [preferencesFile, agentRuntimeFile, skillsStoreFile, customTargetsFile, installsFile] = await Promise.all([
		readOptionalJsonFile(devicePreferencesPath()),
		readOptionalJsonFile(deviceAgentRuntimePath()),
		readOptionalJsonFile(deviceSkillsStorePath()),
		readOptionalJsonFile(deviceSkillsCustomTargetsPath()),
		readOptionalJsonFile(deviceSkillsInstallsPath())
	]);
	const files = [
		preferencesFile,
		agentRuntimeFile,
		skillsStoreFile,
		customTargetsFile,
		installsFile
	];
	if (!files.some((file) => file.found)) return {
		config: null,
		hasFiles: false,
		health: { parseFallback: false }
	};
	const invalidFile = files.find((file) => file.error);
	const preferences = parseDevicePreferencesConfig(preferencesFile.value);
	const agentRuntime = parseDeviceAgentRuntimeConfig(agentRuntimeFile.value);
	const skills = mergeRuntimeSkillsConfig({
		store: parseDeviceSkillsStoreConfig(skillsStoreFile.value),
		customTargets: parseDeviceSkillsCustomTargetsConfig(customTargetsFile.value),
		installs: parseDeviceSkillsInstallsConfig(installsFile.value)
	});
	return {
		config: buildRuntimeConfigFromParts({
			baseUrl: preferences.baseUrl,
			viewCustomization: preferences.viewCustomization,
			daemon: preferences.daemon,
			onboarding: preferences.onboarding,
			deviceRuntimeState: agentRuntime,
			skills
		}),
		hasFiles: true,
		health: invalidFile ? {
			parseFallback: true,
			reason: invalidFile.error ?? "invalid_json"
		} : { parseFallback: false }
	};
}
async function readLegacyRuntimeConfigDetailed() {
	let raw;
	try {
		raw = await readFile(legacyRuntimeConfigPath(), "utf8");
	} catch (error) {
		if (isFileNotFoundError(error)) return {
			config: null,
			health: { parseFallback: false }
		};
		throw error;
	}
	if (raw.trim().length === 0) return {
		config: null,
		health: { parseFallback: false }
	};
	let parsed;
	try {
		parsed = JSON.parse(raw);
	} catch {
		return {
			config: null,
			health: {
				parseFallback: true,
				reason: "invalid_json"
			}
		};
	}
	if (parsed.v !== 1) return {
		config: null,
		health: {
			parseFallback: true,
			reason: "invalid_version"
		}
	};
	if (parsed.agents !== void 0) throw new Error("runtime.config.legacy_agents_unsupported: key 'agents.registrations' is no longer supported. Use 'deviceRuntimeState.controllers' or run 'ats reset --yes'.");
	return {
		config: buildRuntimeConfigFromParts({
			baseUrl: parseConfiguredBaseUrl(parsed.baseUrl),
			viewCustomization: parseRuntimeViewCustomization(parsed.viewCustomization),
			skills: parseRuntimeSkillsConfig(parsed.skills),
			daemon: parseRuntimeDaemonConfig(parsed.daemon),
			deviceRuntimeState: parseRuntimeDeviceRuntimeState(parsed.deviceRuntimeState),
			onboarding: parseRuntimeOnboardingConfig(parsed.onboarding),
			updatedAt: typeof parsed.updatedAt === "string" ? parsed.updatedAt : (/* @__PURE__ */ new Date()).toISOString()
		}),
		health: { parseFallback: false }
	};
}
function buildRuntimeConfigFromParts(input) {
	const updatedAt = input.updatedAt ?? (/* @__PURE__ */ new Date()).toISOString();
	if (!(input.baseUrl || input.viewCustomization || input.skills || input.daemon || input.deviceRuntimeState || input.onboarding)) return null;
	return {
		v: 1,
		...input.baseUrl ? { baseUrl: input.baseUrl } : {},
		...input.viewCustomization ? { viewCustomization: input.viewCustomization } : {},
		...input.skills ? { skills: input.skills } : {},
		...input.daemon ? { daemon: input.daemon } : {},
		...input.deviceRuntimeState ? { deviceRuntimeState: input.deviceRuntimeState } : {},
		...input.onboarding ? { onboarding: input.onboarding } : {},
		updatedAt
	};
}
function parseDevicePreferencesConfig(value) {
	if (!value || typeof value !== "object") return {};
	const parsed = value;
	if (parsed.v !== 1) return {};
	return {
		...parseConfiguredBaseUrl(parsed.baseUrl) ? { baseUrl: parseConfiguredBaseUrl(parsed.baseUrl) } : {},
		...parseRuntimeViewCustomization(parsed.viewCustomization) ? { viewCustomization: parseRuntimeViewCustomization(parsed.viewCustomization) } : {},
		...parseRuntimeDaemonConfig(parsed.daemon) ? { daemon: parseRuntimeDaemonConfig(parsed.daemon) } : {},
		...parseRuntimeOnboardingConfig(parsed.onboarding) ? { onboarding: parseRuntimeOnboardingConfig(parsed.onboarding) } : {}
	};
}
function parseDeviceAgentRuntimeConfig(value) {
	if (!value || typeof value !== "object") return;
	const parsed = value;
	if (parsed.v !== 1) return;
	return parseRuntimeDeviceRuntimeState(parsed.deviceRuntimeState);
}
function parseDeviceSkillsStoreConfig(value) {
	if (!value || typeof value !== "object") return;
	const parsed = value;
	if (parsed.v !== 1) return;
	const storeDir = typeof parsed.storeDir === "string" && parsed.storeDir.trim().length > 0 ? parsed.storeDir.trim() : void 0;
	const agents = parseRuntimeSkillsAgents(parsed.agents);
	if (!(storeDir || agents)) return;
	return {
		...storeDir ? { storeDir } : {},
		...agents ? { agents } : {}
	};
}
function parseDeviceSkillsCustomTargetsConfig(value) {
	if (!value || typeof value !== "object") return;
	const parsed = value;
	if (parsed.v !== 1) return;
	return parseRuntimeSkillsCustomTargets(parsed.customTargets, void 0);
}
function parseDeviceSkillsInstallsConfig(value) {
	if (!value || typeof value !== "object") return;
	const parsed = value;
	if (parsed.v !== 1) return;
	return parseRuntimeSkillsInstallRecords(parsed.installs);
}
function mergeRuntimeSkillsConfig(input) {
	if (!(input.store || input.customTargets || input.installs)) return;
	return {
		...input.store?.storeDir ? { storeDir: input.store.storeDir } : {},
		...input.store?.agents ? { agents: input.store.agents } : {},
		...input.customTargets ? { customTargets: input.customTargets } : {},
		...input.installs ? { installs: input.installs } : {}
	};
}
function buildDevicePreferencesState(next, updatedAt) {
	if (!(next.baseUrl || next.viewCustomization || next.daemon || next.onboarding)) return null;
	return {
		v: 1,
		...next.baseUrl ? { baseUrl: next.baseUrl } : {},
		...next.viewCustomization ? { viewCustomization: next.viewCustomization } : {},
		...next.daemon ? { daemon: next.daemon } : {},
		...next.onboarding ? { onboarding: next.onboarding } : {},
		updatedAt
	};
}
function buildDeviceAgentRuntimeState(next, updatedAt) {
	if (!next.deviceRuntimeState) return null;
	return {
		v: 1,
		deviceRuntimeState: next.deviceRuntimeState,
		updatedAt
	};
}
function buildDeviceSkillsStoreState(next, updatedAt) {
	if (!(next.skills?.storeDir || next.skills?.agents)) return null;
	return {
		v: 1,
		...next.skills?.storeDir ? { storeDir: next.skills.storeDir } : {},
		...next.skills?.agents ? { agents: next.skills.agents } : {},
		updatedAt
	};
}
function buildDeviceSkillsCustomTargetsState(next, updatedAt) {
	if (!(next.skills?.customTargets && next.skills.customTargets.length > 0)) return null;
	return {
		v: 1,
		customTargets: next.skills.customTargets,
		updatedAt
	};
}
function buildDeviceSkillsInstallsState(next, updatedAt) {
	if (!(next.skills?.installs && next.skills.installs.length > 0)) return null;
	return {
		v: 1,
		installs: next.skills.installs,
		updatedAt
	};
}
async function writeJsonFileOrRemove(path, payload) {
	if (!payload) {
		await rm(path, { force: true }).catch(() => void 0);
		return;
	}
	await mkdir(dirname(path), { recursive: true });
	const tempPath = `${path}.tmp-${process.pid}-${Date.now()}`;
	await writeFile(tempPath, `${JSON.stringify(payload, null, 2)}\n`, "utf8");
	try {
		await rename(tempPath, path);
	} catch (error) {
		await rm(tempPath, { force: true }).catch(() => void 0);
		throw error;
	}
}
async function readOptionalJsonFile(path) {
	const raw = await readFile(path, "utf8").catch((error) => {
		if (isFileNotFoundError(error)) return null;
		throw error;
	});
	if (raw === null) return {
		found: false,
		value: null
	};
	if (raw.trim().length === 0) return {
		found: true,
		value: null
	};
	try {
		return {
			found: true,
			value: JSON.parse(raw)
		};
	} catch {
		return {
			found: true,
			value: null,
			error: "invalid_json"
		};
	}
}
async function pathExists(path) {
	return await readFile(path, "utf8").then(() => true).catch((error) => {
		if (isFileNotFoundError(error)) return false;
		throw error;
	});
}

//#endregion
//#region src/config/base-url.ts
const DEFAULT_GATEWAY_BASE_URL = "https://gateway.ats.sh";
const DEV_LOCAL_GATEWAY_BASE_URL = "http://localhost:8080";
const AUTH_HOST_LABEL = "auth";
const AUTH_HOST_PREFIX = "auth-";
const LOCAL_AUTH_PORT = "8788";
async function resolveBaseUrl(cliValue, input = {}) {
	const env = input.env ?? process.env;
	const fromCli = String(cliValue ?? "").trim();
	if (fromCli) return normalizeGatewayBaseUrl(fromCli);
	const fromEnv = String(env.ATS_GATEWAY_URL ?? "").trim();
	if (fromEnv) return normalizeGatewayBaseUrl(fromEnv);
	const fromConfig = await getConfiguredBaseUrl();
	if (fromConfig) return normalizeGatewayBaseUrl(fromConfig);
	return normalizeGatewayBaseUrl(resolveDefaultGatewayBaseUrl({ env }));
}
async function resolveBaseUrlOrNull(cliValue) {
	try {
		return await resolveBaseUrl(cliValue);
	} catch {
		return null;
	}
}
async function resolveExplicitGatewayUrlOrThrow(cliValue) {
	const explicitGatewayUrl = normalizeOptionalString(cliValue);
	if (!explicitGatewayUrl) return;
	try {
		return await Promise.resolve().then(() => normalizeGatewayBaseUrl(explicitGatewayUrl));
	} catch (error) {
		throw new Error(`Invalid explicit gateway URL "${explicitGatewayUrl}": ${toErrorMessage(error)}`);
	}
}
function normalizeGatewayBaseUrl(gatewayUrl) {
	const normalizedGatewayUrl = normalizeBaseUrl(gatewayUrl);
	if (isAuthWorkerUrl(new URL(normalizedGatewayUrl))) throw new Error("gateway URL must point to the ATS gateway, not the ATS auth worker");
	return normalizedGatewayUrl;
}
function normalizeGatewayBaseUrlOrNull(gatewayUrl) {
	const normalizedGatewayUrl = normalizeOptionalString(gatewayUrl);
	if (!normalizedGatewayUrl) return null;
	try {
		return normalizeGatewayBaseUrl(normalizedGatewayUrl);
	} catch {
		return null;
	}
}
function normalizeOptionalString(value) {
	const normalized = String(value ?? "").trim();
	return normalized.length > 0 ? normalized : null;
}
function resolveDefaultGatewayBaseUrl(input = {}) {
	const preset = resolveAtsEnvPreset(input);
	if (preset === "dev-local" || preset === "canary") return DEV_LOCAL_GATEWAY_BASE_URL;
	return DEFAULT_GATEWAY_BASE_URL;
}
function isAuthWorkerUrl(url) {
	if (isLoopbackHostname(url.hostname)) return resolveUrlPort(url) === LOCAL_AUTH_PORT;
	const [firstLabel = ""] = url.hostname.toLowerCase().split(".");
	return firstLabel === AUTH_HOST_LABEL || firstLabel.startsWith(AUTH_HOST_PREFIX);
}
function isLoopbackHostname(hostname) {
	const normalizedHostname = hostname.toLowerCase();
	return normalizedHostname === "localhost" || normalizedHostname === "127.0.0.1" || normalizedHostname === "::1";
}
function resolveUrlPort(url) {
	if (url.port) return url.port;
	if (url.protocol === "http:" || url.protocol === "ws:") return "80";
	if (url.protocol === "https:" || url.protocol === "wss:") return "443";
	return "";
}
function toErrorMessage(error) {
	return error instanceof Error ? error.message : String(error);
}

//#endregion
export { toSpaceDeleteUrl as A, toSpaceUpdatesUrl as B, updateConfiguredSkillsConfig as C, toSpaceContractUrl as D, toDaemonRouteObservationUrl as E, toSpaceMetaUrl as F, toSpacePasswordUrl as I, toSpaceRemoveMembersUrl as L, toSpaceDispatchTraceUrl as M, toSpaceLeaveUrl as N, toSpaceCreateUrl as O, toSpaceMembersUrl as P, toSpaceResultUrl as R, updateConfiguredOnboardingConfig as S, normalizeBaseUrl as T, toSpaceWsUrl as V, getRuntimeConfigReadHealth as _, resolveBaseUrlOrNull as a, setConfiguredSkillsConfig as b, DEFAULT_RUNTIME_AGENT_TRANSPORT_MODE as c, getConfiguredDaemonDispatchLimits as d, getConfiguredDeviceRuntimeState as f, getConfiguredViewCustomization as g, getConfiguredStartV1OnboardingState as h, resolveBaseUrl as i, toSpaceDispatchLookupUrl as j, toSpaceCursorUrl as k, alignRuntimeConfigStorage as l, getConfiguredSkillsConfig as m, normalizeGatewayBaseUrl as n, resolveDefaultGatewayBaseUrl as o, getConfiguredOnboardingDisclaimerAcceptedAt as p, normalizeGatewayBaseUrlOrNull as r, resolveExplicitGatewayUrlOrThrow as s, DEV_LOCAL_GATEWAY_BASE_URL as t, createDefaultRuntimeAgentControllerSettings as u, resolveRuntimeSkillsCustomTargetId as v, updateConfiguredStartV1OnboardingState as w, updateConfiguredDeviceRuntimeState as x, setConfiguredBaseUrl as y, toSpaceSignalsUrl as z };
//# sourceMappingURL=base-url-9erZ1vgx.js.map