import { A as isRich, E as setVerbose, j as theme, x as info } from "./registry-Sbac4a4z.js";
import "./paths-By0XjHBk.js";
import "./utils-CTPsqyE_.js";
import { f as defaultRuntime } from "./subsystem-CHbO_DkH.js";
import "./auth-profiles-Ce7R_25e.js";
import { x as parseAgentSessionKey } from "./session-key-DUSb7CCb.js";
import "./exec-DuYbft0z.js";
import "./agent-scope-DOrZjOnW.js";
import { C as DEFAULT_MODEL, S as DEFAULT_CONTEXT_TOKENS, m as resolveConfiguredModelRef, w as DEFAULT_PROVIDER } from "./model-selection-7wdmO-Iw.js";
import "./file-lock-BVUYnlQv.js";
import "./agent-paths-BbZSGrUA.js";
import { i as loadConfig } from "./config-B4jkreCN.js";
import "./boolean-CbZoNRMn.js";
import "./env-BRnPI9sO.js";
import "./shell-env-Dc3iU7HK.js";
import "./manifest-registry-D1MLZEjS.js";
import "./sandbox-BkznAPKO.js";
import "./chrome-DJChpTwP.js";
import "./tailscale-DpKBMIvx.js";
import "./auth-Bkx-QuRN.js";
import "./server-context-ChcbJgNo.js";
import "./frontmatter-B_jqcova.js";
import "./skills-BwDmcZdt.js";
import "./routes-ivqbutvM.js";
import "./redact-B3O-RBO1.js";
import "./errors-bI7Tdx75.js";
import "./fs-safe-BdejYjW8.js";
import "./paths-DObzwe08.js";
import "./ssrf-DOZRI5XH.js";
import "./image-ops-L70xVnpG.js";
import "./ports-gxLM5ahL.js";
import "./trash-_YhavPQI.js";
import { R as resolveFreshSessionTotalTokens, o as loadSessionStore } from "./sessions-Dxf5Kjig.js";
import "./dock-hF45sewN.js";
import "./message-channel-DgjXWzf-.js";
import "./plugins-CF5skkHh.js";
import { c as resolveStorePath } from "./paths-BtvQ7JvU.js";
import "./model-auth-1EAQvYRv.js";
import "./github-copilot-token-D-FdDfee.js";
import "./models-config-B5Xxy-c-.js";
import { l as resolveSessionModelRef, n as classifySessionKey, x as lookupContextTokens } from "./session-utils-Cs1jlD-q.js";
import "./memory-BZ24UkLW.js";
import "./manager-Cw7IJGbB.js";
import "./sqlite-Cod7C5ba.js";
import "./commands-DUzLGgEZ.js";
import "./client-DH75FlQF.js";
import "./call-AZ9vNhST.js";
import "./pairing-token-Dcy37-4s.js";
import { n as formatTimeAgo } from "./format-relative-D4GQsWlP.js";
import "./skills-remote-bz71Bstn.js";
import "./workspace-dirs-jKFQf7of.js";
import "./pairing-store-BNhJOnWn.js";
import "./bindings-DIhsYGa_.js";
import { t as formatDocsLink } from "./links-Bqr0FxXx.js";
import { n as runCommandWithRuntime } from "./cli-utils-CuyGL3rq.js";
import { t as formatHelpExamples } from "./help-format-7hFcsqss.js";
import "./progress-swt2y17x.js";
import "./pi-tools.policy-H2t-Xkfc.js";
import "./runtime-guard-CWA00ZXa.js";
import { n as parsePositiveIntOrUndefined } from "./helpers-B_p8ul9t.js";
import "./skills-status-BKX1PjCc.js";
import "./prompt-style-olk5zI5k.js";
import "./skill-scanner-BCgVcIwi.js";
import "./channels-status-issues-DLIzUsjR.js";
import "./onboard-helpers-7IGQ8nAM.js";
import "./systemd-CUIM0n5P.js";
import "./service-e6MzlLCd.js";
import "./diagnostics-DlZODdRf.js";
import "./table-0A3xKJVC.js";
import "./audit-C_3fAFeS.js";
import { t as statusCommand } from "./status-D7QX7VDk.js";
import { r as healthCommand } from "./health-7UqIGG8U.js";
import "./update-check-BCL_K7kx.js";
import "./dm-policy-shared-CeFt0nch.js";
import "./node-service-BH08wY5j.js";
import "./status.update-DGJi0OLl.js";

//#region src/commands/sessions.ts
const KIND_PAD = 6;
const KEY_PAD = 26;
const AGE_PAD = 9;
const MODEL_PAD = 14;
const TOKENS_PAD = 20;
const formatKTokens = (value) => `${(value / 1e3).toFixed(value >= 1e4 ? 0 : 1)}k`;
const truncateKey = (key) => {
	if (key.length <= KEY_PAD) return key;
	const head = Math.max(4, KEY_PAD - 10);
	return `${key.slice(0, head)}...${key.slice(-6)}`;
};
const colorByPct = (label, pct, rich) => {
	if (!rich || pct === null) return label;
	if (pct >= 95) return theme.error(label);
	if (pct >= 80) return theme.warn(label);
	if (pct >= 60) return theme.success(label);
	return theme.muted(label);
};
const formatTokensCell = (total, contextTokens, rich) => {
	if (total === void 0) {
		const label = `unknown/${contextTokens ? formatKTokens(contextTokens) : "?"} (?%)`;
		return rich ? theme.muted(label.padEnd(TOKENS_PAD)) : label.padEnd(TOKENS_PAD);
	}
	const totalLabel = formatKTokens(total);
	const ctxLabel = contextTokens ? formatKTokens(contextTokens) : "?";
	const pct = contextTokens ? Math.min(999, Math.round(total / contextTokens * 100)) : null;
	return colorByPct(`${totalLabel}/${ctxLabel} (${pct ?? "?"}%)`.padEnd(TOKENS_PAD), pct, rich);
};
const formatKindCell = (kind, rich) => {
	const label = kind.padEnd(KIND_PAD);
	if (!rich) return label;
	if (kind === "group") return theme.accentBright(label);
	if (kind === "global") return theme.warn(label);
	if (kind === "direct") return theme.accent(label);
	return theme.muted(label);
};
const formatAgeCell = (updatedAt, rich) => {
	const padded = (updatedAt ? formatTimeAgo(Date.now() - updatedAt) : "unknown").padEnd(AGE_PAD);
	return rich ? theme.muted(padded) : padded;
};
const formatModelCell = (model, rich) => {
	const label = (model ?? "unknown").padEnd(MODEL_PAD);
	return rich ? theme.info(label) : label;
};
const formatFlagsCell = (row, rich) => {
	const label = [
		row.thinkingLevel ? `think:${row.thinkingLevel}` : null,
		row.verboseLevel ? `verbose:${row.verboseLevel}` : null,
		row.reasoningLevel ? `reasoning:${row.reasoningLevel}` : null,
		row.elevatedLevel ? `elev:${row.elevatedLevel}` : null,
		row.responseUsage ? `usage:${row.responseUsage}` : null,
		row.groupActivation ? `activation:${row.groupActivation}` : null,
		row.systemSent ? "system" : null,
		row.abortedLastRun ? "aborted" : null,
		row.sessionId ? `id:${row.sessionId}` : null
	].filter(Boolean).join(" ");
	return label.length === 0 ? "" : rich ? theme.muted(label) : label;
};
function toRows(store) {
	return Object.entries(store).map(([key, entry]) => {
		const updatedAt = entry?.updatedAt ?? null;
		return {
			key,
			kind: classifySessionKey(key, entry),
			updatedAt,
			ageMs: updatedAt ? Date.now() - updatedAt : null,
			sessionId: entry?.sessionId,
			systemSent: entry?.systemSent,
			abortedLastRun: entry?.abortedLastRun,
			thinkingLevel: entry?.thinkingLevel,
			verboseLevel: entry?.verboseLevel,
			reasoningLevel: entry?.reasoningLevel,
			elevatedLevel: entry?.elevatedLevel,
			responseUsage: entry?.responseUsage,
			groupActivation: entry?.groupActivation,
			inputTokens: entry?.inputTokens,
			outputTokens: entry?.outputTokens,
			totalTokens: entry?.totalTokens,
			totalTokensFresh: entry?.totalTokensFresh,
			model: entry?.model,
			modelProvider: entry?.modelProvider,
			providerOverride: entry?.providerOverride,
			modelOverride: entry?.modelOverride,
			contextTokens: entry?.contextTokens
		};
	}).toSorted((a, b) => (b.updatedAt ?? 0) - (a.updatedAt ?? 0));
}
async function sessionsCommand(opts, runtime) {
	const cfg = loadConfig();
	const resolved = resolveConfiguredModelRef({
		cfg,
		defaultProvider: DEFAULT_PROVIDER,
		defaultModel: DEFAULT_MODEL
	});
	const configContextTokens = cfg.agents?.defaults?.contextTokens ?? lookupContextTokens(resolved.model) ?? DEFAULT_CONTEXT_TOKENS;
	const configModel = resolved.model ?? DEFAULT_MODEL;
	const storePath = resolveStorePath(opts.store ?? cfg.session?.store);
	const store = loadSessionStore(storePath);
	let activeMinutes;
	if (opts.active !== void 0) {
		const parsed = Number.parseInt(String(opts.active), 10);
		if (Number.isNaN(parsed) || parsed <= 0) {
			runtime.error("--active must be a positive integer (minutes)");
			runtime.exit(1);
			return;
		}
		activeMinutes = parsed;
	}
	const rows = toRows(store).filter((row) => {
		if (activeMinutes === void 0) return true;
		if (!row.updatedAt) return false;
		return Date.now() - row.updatedAt <= activeMinutes * 6e4;
	});
	if (opts.json) {
		runtime.log(JSON.stringify({
			path: storePath,
			count: rows.length,
			activeMinutes: activeMinutes ?? null,
			sessions: rows.map((r) => {
				const model = resolveSessionModelRef(cfg, r, parseAgentSessionKey(r.key)?.agentId).model ?? configModel;
				return {
					...r,
					totalTokens: resolveFreshSessionTotalTokens(r) ?? null,
					totalTokensFresh: typeof r.totalTokens === "number" ? r.totalTokensFresh !== false : false,
					contextTokens: r.contextTokens ?? lookupContextTokens(model) ?? configContextTokens ?? null,
					model
				};
			})
		}, null, 2));
		return;
	}
	runtime.log(info(`Session store: ${storePath}`));
	runtime.log(info(`Sessions listed: ${rows.length}`));
	if (activeMinutes) runtime.log(info(`Filtered to last ${activeMinutes} minute(s)`));
	if (rows.length === 0) {
		runtime.log("No sessions found.");
		return;
	}
	const rich = isRich();
	const header = [
		"Kind".padEnd(KIND_PAD),
		"Key".padEnd(KEY_PAD),
		"Age".padEnd(AGE_PAD),
		"Model".padEnd(MODEL_PAD),
		"Tokens (ctx %)".padEnd(TOKENS_PAD),
		"Flags"
	].join(" ");
	runtime.log(rich ? theme.heading(header) : header);
	for (const row of rows) {
		const model = resolveSessionModelRef(cfg, row, parseAgentSessionKey(row.key)?.agentId).model ?? configModel;
		const contextTokens = row.contextTokens ?? lookupContextTokens(model) ?? configContextTokens;
		const total = resolveFreshSessionTotalTokens(row);
		const keyLabel = truncateKey(row.key).padEnd(KEY_PAD);
		const keyCell = rich ? theme.accent(keyLabel) : keyLabel;
		const line = [
			formatKindCell(row.kind, rich),
			keyCell,
			formatAgeCell(row.updatedAt, rich),
			formatModelCell(model, rich),
			formatTokensCell(total, contextTokens ?? null, rich),
			formatFlagsCell(row, rich)
		].join(" ");
		runtime.log(line.trimEnd());
	}
}

//#endregion
//#region src/cli/program/register.status-health-sessions.ts
function resolveVerbose(opts) {
	return Boolean(opts.verbose || opts.debug);
}
function parseTimeoutMs(timeout) {
	const parsed = parsePositiveIntOrUndefined(timeout);
	if (timeout !== void 0 && parsed === void 0) {
		defaultRuntime.error("--timeout must be a positive integer (milliseconds)");
		defaultRuntime.exit(1);
		return null;
	}
	return parsed;
}
function registerStatusHealthSessionsCommands(program) {
	program.command("status").description("Show channel health and recent session recipients").option("--json", "Output JSON instead of text", false).option("--all", "Full diagnosis (read-only, pasteable)", false).option("--usage", "Show model provider usage/quota snapshots", false).option("--deep", "Probe channels (WhatsApp Web + Telegram + Slack + Signal)", false).option("--timeout <ms>", "Probe timeout in milliseconds", "10000").option("--verbose", "Verbose logging", false).option("--debug", "Alias for --verbose", false).addHelpText("after", () => `\n${theme.heading("Examples:")}\n${formatHelpExamples([
		["symi status", "Show channel health + session summary."],
		["symi status --all", "Full diagnosis (read-only)."],
		["symi status --json", "Machine-readable output."],
		["symi status --usage", "Show model provider usage/quota snapshots."],
		["symi status --deep", "Run channel probes (WA + Telegram + Slack + Signal)."],
		["symi status --deep --timeout 5000", "Tighten probe timeout."]
	])}`).addHelpText("after", () => `\n${theme.muted("Docs:")} ${formatDocsLink("/cli/status", "docs.symi.ai/cli/status")}\n`).action(async (opts) => {
		const verbose = resolveVerbose(opts);
		setVerbose(verbose);
		const timeout = parseTimeoutMs(opts.timeout);
		if (timeout === null) return;
		await runCommandWithRuntime(defaultRuntime, async () => {
			await statusCommand({
				json: Boolean(opts.json),
				all: Boolean(opts.all),
				deep: Boolean(opts.deep),
				usage: Boolean(opts.usage),
				timeoutMs: timeout,
				verbose
			}, defaultRuntime);
		});
	});
	program.command("health").description("Fetch health from the running gateway").option("--json", "Output JSON instead of text", false).option("--timeout <ms>", "Connection timeout in milliseconds", "10000").option("--verbose", "Verbose logging", false).option("--debug", "Alias for --verbose", false).addHelpText("after", () => `\n${theme.muted("Docs:")} ${formatDocsLink("/cli/health", "docs.symi.ai/cli/health")}\n`).action(async (opts) => {
		const verbose = resolveVerbose(opts);
		setVerbose(verbose);
		const timeout = parseTimeoutMs(opts.timeout);
		if (timeout === null) return;
		await runCommandWithRuntime(defaultRuntime, async () => {
			await healthCommand({
				json: Boolean(opts.json),
				timeoutMs: timeout,
				verbose
			}, defaultRuntime);
		});
	});
	program.command("sessions").description("List stored conversation sessions").option("--json", "Output as JSON", false).option("--verbose", "Verbose logging", false).option("--store <path>", "Path to session store (default: resolved from config)").option("--active <minutes>", "Only show sessions updated within the past N minutes").addHelpText("after", () => `\n${theme.heading("Examples:")}\n${formatHelpExamples([
		["symi sessions", "List all sessions."],
		["symi sessions --active 120", "Only last 2 hours."],
		["symi sessions --json", "Machine-readable output."],
		["symi sessions --store ./tmp/sessions.json", "Use a specific session store."]
	])}\n\n${theme.muted("Shows token usage per session when the agent reports it; set agents.defaults.contextTokens to cap the window and show %.")}`).addHelpText("after", () => `\n${theme.muted("Docs:")} ${formatDocsLink("/cli/sessions", "docs.symi.ai/cli/sessions")}\n`).action(async (opts) => {
		setVerbose(Boolean(opts.verbose));
		await sessionsCommand({
			json: Boolean(opts.json),
			store: opts.store,
			active: opts.active
		}, defaultRuntime);
	});
}

//#endregion
export { registerStatusHealthSessionsCommands };