import "./paths-Ci0O5IXU.js";
import { f as isRich, n as info, p as theme, s as setVerbose } from "./globals-o4Hkf2nH.js";
import "./utils-DXDZXfi2.js";
import "./thinking-Fqckw03T.js";
import { G as resolveSessionModelRef, R as classifySessionKey, yn as lookupContextTokens } from "./reply-CHHLWXTP.js";
import { d as resolveDefaultAgentId, r as listAgentIds } from "./agent-scope-BUcFoOez.js";
import { d as defaultRuntime } from "./subsystem-CocLsF9M.js";
import { E as parseAgentSessionKey, c as normalizeAgentId } from "./session-key-CIXZm7v4.js";
import "./core-root-D_XTmw6_.js";
import "./logger-B4_TThxB.js";
import "./exec-Bvzmovpq.js";
import { Ji as DEFAULT_MODEL, Yi as DEFAULT_PROVIDER, h as resolveConfiguredModelRef, qi as DEFAULT_CONTEXT_TOKENS, rn as loadConfig } from "./model-selection-YEFtLNSF.js";
import "./registry-CZfQ-snX.js";
import "./github-copilot-token-DqwKrrmK.js";
import "./boolean-C6Pbt2Ue.js";
import "./env-D3eA4r2n.js";
import "./manifest-registry-CqRtX07d.js";
import "./dock-B9SrGH_K.js";
import "./message-channel-B7if8_Ss.js";
import "./send-D4IPI7DA.js";
import "./plugins-DPuCvyAr.js";
import { J as resolveFreshSessionTotalTokens, d as updateSessionStore, g as enforceSessionDiskBudget, h as resolveMaintenanceConfig, m as pruneStaleEntries, o as loadSessionStore, p as capEntryCount } from "./sessions-CxtmRBrc.js";
import "./audio-transcription-runner-BmYM79ae.js";
import "./image-C5KyeETN.js";
import "./models-config-B8Hasdzn.js";
import "./pi-embedded-helpers-M3RkS711.js";
import "./sandbox-C1_DWCsa.js";
import "./tool-catalog-7XRC3klR.js";
import "./chrome-BBVmc3Se.js";
import "./tailscale-BxdRBeK_.js";
import "./tailnet-DONkFGUG.js";
import "./ws-DQm2qOSB.js";
import "./auth-BfvQ8QYP.js";
import "./server-context-Ba0Dvxyt.js";
import "./frontmatter-wvk5Gwyc.js";
import "./skills-BgSP_JFk.js";
import "./path-alias-guards-Cjml85oF.js";
import "./paths-CI0-x9aa.js";
import "./redact-Nl4LWTUL.js";
import "./errors-D2aogITB.js";
import "./fs-safe-4KkU2jy0.js";
import "./proxy-env-QR3xvEvF.js";
import "./image-ops-BMK3YDnH.js";
import "./store-wnkoDS0q.js";
import "./ports-BJ314ngw.js";
import "./trash-C57Djqhz.js";
import "./server-middleware-Db5VJPvz.js";
import "./accounts--YCaC3h2.js";
import "./accounts-DIXxXacs.js";
import "./logging-w5jq5901.js";
import "./accounts-Cy5Z48cS.js";
import "./send-BftGPeDi.js";
import { c as resolveStorePath, n as resolveSessionFilePath, r as resolveSessionFilePathOptions } from "./paths-DyjDYWsu.js";
import "./chat-envelope-DjXKeY_Z.js";
import "./tool-images-BdgJAeDm.js";
import "./tool-display-DtW9AC9y.js";
import "./fetch-guard-BXj181Wi.js";
import "./api-key-rotation-kSZ_8x6S.js";
import "./local-roots-lI8oP7YT.js";
import "./model-catalog-CrylEG4v.js";
import "./proxy-fetch-1Erku4sd.js";
import "./tokens-CQyDX0_9.js";
import "./deliver-CjvogG-h.js";
import "./commands-CjCZ7VFi.js";
import "./commands-registry-Bjrh-xTL.js";
import "./client-DoEmtGyQ.js";
import "./call-CGx2d27E.js";
import "./pairing-token-BbiCPOiP.js";
import "./with-timeout-Z1s9Diet.js";
import "./diagnostic-dPBPmwAh.js";
import "./send-NUo-HdLp.js";
import "./pi-model-discovery-BYAKdd2d.js";
import "./exec-approvals-allowlist-DC_4Tf0s.js";
import "./exec-safe-bin-runtime-policy-bh7vljJv.js";
import "./ir-BjgRIHDw.js";
import "./render-CUAKPmvZ.js";
import "./target-errors-CbVI6ds_.js";
import "./channel-selection-aHawixyC.js";
import "./plugin-auto-enable-DRWWaZkx.js";
import "./send-DAtCjd-s.js";
import "./outbound-attachment-C2bCVbHg.js";
import "./fetch-MguOSqpo.js";
import "./delivery-queue-BEhfSqnG.js";
import "./send-eLzaCOuF.js";
import "./pairing-store-CbJHk_de.js";
import { n as formatTimeAgo } from "./format-relative-BXoxEQVN.js";
import "./read-only-account-inspect-Qmimgb8a.js";
import "./channel-activity-Cx5Unx4s.js";
import "./tables-BhHaE0Wa.js";
import "./proxy-j8BltAEx.js";
import "./timeouts-BNjB4b5v.js";
import "./skill-commands-BZahRPvp.js";
import "./workspace-dirs-BU0q6mL7.js";
import "./runtime-config-collectors-CW2xlUjz.js";
import "./command-secret-targets-B0--_778.js";
import "./session-cost-usage-qv_Px0s6.js";
import "./onboard-helpers-CgBGHcnn.js";
import "./prompt-style-C3CFmIhm.js";
import "./pairing-labels-DgY7LhGG.js";
import "./memory-cli-DnOu7SX5.js";
import "./manager-DPAW8PRF.js";
import "./query-expansion-D5WNngl2.js";
import { t as formatDocsLink } from "./links-DRjWcKgy.js";
import { n as runCommandWithRuntime } from "./cli-utils-CuyGL3rq.js";
import { t as formatHelpExamples } from "./help-format-BuSfnjUn.js";
import "./progress-CSvLovC9.js";
import "./exec-approvals-C8Ra1A3C.js";
import "./nodes-screen-CWe-prHK.js";
import "./system-run-command-DopVO6dk.js";
import "./server-lifecycle-ChsLH-5K.js";
import "./stagger-F4n43mMH.js";
import { n as parsePositiveIntOrUndefined } from "./helpers-DYN-5CJP.js";
import "./skills-status-DIRU8plG.js";
import "./dangerous-tools-CcEHmNno.js";
import "./skill-scanner-dq8DAqD3.js";
import "./issue-format-B5EOFmBa.js";
import "./channels-status-issues-D1CmgD0J.js";
import "./systemd-Coag6AD6.js";
import "./service-BuILYYFR.js";
import "./probe-C_0v4_gK.js";
import "./diagnostics-Dj8I6sv_.js";
import "./table-ClJ8xIil.js";
import { t as statusCommand } from "./status-8-koNYGg.js";
import { r as healthCommand } from "./health-B8CcGS1a.js";
import "./channel-account-context-DMN4F0HY.js";
import "./node-command-policy-qAQmvzXR.js";
import "./audit-D40Qlz_m.js";
import "./node-service-DVaff4lX.js";
import "./status.update-LOWOCMzP.js";
import fs from "node:fs";

//#region src/commands/session-store-targets.ts
function dedupeTargetsByStorePath(targets) {
	const deduped = /* @__PURE__ */ new Map();
	for (const target of targets) if (!deduped.has(target.storePath)) deduped.set(target.storePath, target);
	return [...deduped.values()];
}
function resolveSessionStoreTargets(cfg, opts) {
	const defaultAgentId = resolveDefaultAgentId(cfg);
	const hasAgent = Boolean(opts.agent?.trim());
	const allAgents = opts.allAgents === true;
	if (hasAgent && allAgents) throw new Error("--agent and --all-agents cannot be used together");
	if (opts.store && (hasAgent || allAgents)) throw new Error("--store cannot be combined with --agent or --all-agents");
	if (opts.store) return [{
		agentId: defaultAgentId,
		storePath: resolveStorePath(opts.store, { agentId: defaultAgentId })
	}];
	if (allAgents) return dedupeTargetsByStorePath(listAgentIds(cfg).map((agentId) => ({
		agentId,
		storePath: resolveStorePath(cfg.session?.store, { agentId })
	})));
	if (hasAgent) {
		const knownAgents = listAgentIds(cfg);
		const requested = normalizeAgentId(opts.agent ?? "");
		if (!knownAgents.includes(requested)) throw new Error(`Unknown agent id "${opts.agent}". Use "gensparx agents list" to see configured agents.`);
		return [{
			agentId: requested,
			storePath: resolveStorePath(cfg.session?.store, { agentId: requested })
		}];
	}
	return [{
		agentId: defaultAgentId,
		storePath: resolveStorePath(cfg.session?.store, { agentId: defaultAgentId })
	}];
}
function resolveSessionStoreTargetsOrExit(params) {
	try {
		return resolveSessionStoreTargets(params.cfg, params.opts);
	} catch (error) {
		params.runtime.error(error instanceof Error ? error.message : String(error));
		params.runtime.exit(1);
		return null;
	}
}

//#endregion
//#region src/commands/sessions-table.ts
const SESSION_KEY_PAD = 26;
const SESSION_AGE_PAD = 9;
const SESSION_MODEL_PAD = 14;
function toSessionDisplayRows(store) {
	return Object.entries(store).map(([key, entry]) => {
		const updatedAt = entry?.updatedAt ?? null;
		return {
			key,
			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));
}
function resolveSessionDisplayDefaults(cfg) {
	return { model: resolveConfiguredModelRef({
		cfg,
		defaultProvider: DEFAULT_PROVIDER,
		defaultModel: DEFAULT_MODEL
	}).model ?? DEFAULT_MODEL };
}
function resolveSessionDisplayModel(cfg, row, defaults) {
	return resolveSessionModelRef(cfg, row, parseAgentSessionKey(row.key)?.agentId).model ?? defaults.model;
}
function truncateSessionKey(key) {
	if (key.length <= SESSION_KEY_PAD) return key;
	const head = Math.max(4, SESSION_KEY_PAD - 10);
	return `${key.slice(0, head)}...${key.slice(-6)}`;
}
function formatSessionKeyCell(key, rich) {
	const label = truncateSessionKey(key).padEnd(SESSION_KEY_PAD);
	return rich ? theme.accent(label) : label;
}
function formatSessionAgeCell(updatedAt, rich) {
	const padded = (updatedAt ? formatTimeAgo(Date.now() - updatedAt) : "unknown").padEnd(SESSION_AGE_PAD);
	return rich ? theme.muted(padded) : padded;
}
function formatSessionModelCell(model, rich) {
	const label = (model ?? "unknown").padEnd(SESSION_MODEL_PAD);
	return rich ? theme.info(label) : label;
}
function formatSessionFlagsCell(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;
}

//#endregion
//#region src/commands/sessions-cleanup.ts
const ACTION_PAD = 12;
function resolveSessionCleanupAction(params) {
	if (params.missingKeys.has(params.key)) return "prune-missing";
	if (params.staleKeys.has(params.key)) return "prune-stale";
	if (params.cappedKeys.has(params.key)) return "cap-overflow";
	if (params.budgetEvictedKeys.has(params.key)) return "evict-budget";
	return "keep";
}
function formatCleanupActionCell(action, rich) {
	const label = action.padEnd(ACTION_PAD);
	if (!rich) return label;
	if (action === "keep") return theme.muted(label);
	if (action === "prune-missing") return theme.error(label);
	if (action === "prune-stale") return theme.warn(label);
	if (action === "cap-overflow") return theme.accentBright(label);
	return theme.error(label);
}
function buildActionRows(params) {
	return toSessionDisplayRows(params.beforeStore).map((row) => ({
		...row,
		action: resolveSessionCleanupAction({
			key: row.key,
			missingKeys: params.missingKeys,
			staleKeys: params.staleKeys,
			cappedKeys: params.cappedKeys,
			budgetEvictedKeys: params.budgetEvictedKeys
		})
	}));
}
function pruneMissingTranscriptEntries(params) {
	const sessionPathOpts = resolveSessionFilePathOptions({ storePath: params.storePath });
	let removed = 0;
	for (const [key, entry] of Object.entries(params.store)) {
		if (!entry?.sessionId) continue;
		const transcriptPath = resolveSessionFilePath(entry.sessionId, entry, sessionPathOpts);
		if (!fs.existsSync(transcriptPath)) {
			delete params.store[key];
			removed += 1;
			params.onPruned?.(key);
		}
	}
	return removed;
}
async function previewStoreCleanup(params) {
	const maintenance = resolveMaintenanceConfig();
	const beforeStore = loadSessionStore(params.target.storePath, { skipCache: true });
	const previewStore = structuredClone(beforeStore);
	const staleKeys = /* @__PURE__ */ new Set();
	const cappedKeys = /* @__PURE__ */ new Set();
	const missingKeys = /* @__PURE__ */ new Set();
	const missing = params.fixMissing === true ? pruneMissingTranscriptEntries({
		store: previewStore,
		storePath: params.target.storePath,
		onPruned: (key) => {
			missingKeys.add(key);
		}
	}) : 0;
	const pruned = pruneStaleEntries(previewStore, maintenance.pruneAfterMs, {
		log: false,
		onPruned: ({ key }) => {
			staleKeys.add(key);
		}
	});
	const capped = capEntryCount(previewStore, maintenance.maxEntries, {
		log: false,
		onCapped: ({ key }) => {
			cappedKeys.add(key);
		}
	});
	const beforeBudgetStore = structuredClone(previewStore);
	const diskBudget = await enforceSessionDiskBudget({
		store: previewStore,
		storePath: params.target.storePath,
		activeSessionKey: params.activeKey,
		maintenance,
		warnOnly: false,
		dryRun: true
	});
	const budgetEvictedKeys = /* @__PURE__ */ new Set();
	for (const key of Object.keys(beforeBudgetStore)) if (!Object.hasOwn(previewStore, key)) budgetEvictedKeys.add(key);
	const beforeCount = Object.keys(beforeStore).length;
	const afterPreviewCount = Object.keys(previewStore).length;
	const wouldMutate = missing > 0 || pruned > 0 || capped > 0 || Boolean((diskBudget?.removedEntries ?? 0) > 0 || (diskBudget?.removedFiles ?? 0) > 0);
	return {
		summary: {
			agentId: params.target.agentId,
			storePath: params.target.storePath,
			mode: params.mode,
			dryRun: params.dryRun,
			beforeCount,
			afterCount: afterPreviewCount,
			missing,
			pruned,
			capped,
			diskBudget,
			wouldMutate
		},
		actionRows: buildActionRows({
			beforeStore,
			staleKeys,
			cappedKeys,
			budgetEvictedKeys,
			missingKeys
		})
	};
}
function renderStoreDryRunPlan(params) {
	const rich = isRich();
	if (params.showAgentHeader) params.runtime.log(`Agent: ${params.summary.agentId}`);
	params.runtime.log(`Session store: ${params.summary.storePath}`);
	params.runtime.log(`Maintenance mode: ${params.summary.mode}`);
	params.runtime.log(`Entries: ${params.summary.beforeCount} -> ${params.summary.afterCount} (remove ${params.summary.beforeCount - params.summary.afterCount})`);
	params.runtime.log(`Would prune missing transcripts: ${params.summary.missing}`);
	params.runtime.log(`Would prune stale: ${params.summary.pruned}`);
	params.runtime.log(`Would cap overflow: ${params.summary.capped}`);
	if (params.summary.diskBudget) params.runtime.log(`Would enforce disk budget: ${params.summary.diskBudget.totalBytesBefore} -> ${params.summary.diskBudget.totalBytesAfter} bytes (files ${params.summary.diskBudget.removedFiles}, entries ${params.summary.diskBudget.removedEntries})`);
	if (params.actionRows.length === 0) return;
	params.runtime.log("");
	params.runtime.log("Planned session actions:");
	const header = [
		"Action".padEnd(ACTION_PAD),
		"Key".padEnd(SESSION_KEY_PAD),
		"Age".padEnd(SESSION_AGE_PAD),
		"Model".padEnd(SESSION_MODEL_PAD),
		"Flags"
	].join(" ");
	params.runtime.log(rich ? theme.heading(header) : header);
	for (const actionRow of params.actionRows) {
		const model = resolveSessionDisplayModel(params.cfg, actionRow, params.displayDefaults);
		const line = [
			formatCleanupActionCell(actionRow.action, rich),
			formatSessionKeyCell(actionRow.key, rich),
			formatSessionAgeCell(actionRow.updatedAt, rich),
			formatSessionModelCell(model, rich),
			formatSessionFlagsCell(actionRow, rich)
		].join(" ");
		params.runtime.log(line.trimEnd());
	}
}
async function sessionsCleanupCommand(opts, runtime) {
	const cfg = loadConfig();
	const displayDefaults = resolveSessionDisplayDefaults(cfg);
	const mode = opts.enforce ? "enforce" : resolveMaintenanceConfig().mode;
	const targets = resolveSessionStoreTargetsOrExit({
		cfg,
		opts: {
			store: opts.store,
			agent: opts.agent,
			allAgents: opts.allAgents
		},
		runtime
	});
	if (!targets) return;
	const previewResults = [];
	for (const target of targets) {
		const result = await previewStoreCleanup({
			target,
			mode,
			dryRun: Boolean(opts.dryRun),
			activeKey: opts.activeKey,
			fixMissing: Boolean(opts.fixMissing)
		});
		previewResults.push(result);
	}
	if (opts.dryRun) {
		if (opts.json) {
			if (previewResults.length === 1) {
				runtime.log(JSON.stringify(previewResults[0]?.summary ?? {}, null, 2));
				return;
			}
			runtime.log(JSON.stringify({
				allAgents: true,
				mode,
				dryRun: true,
				stores: previewResults.map((result) => result.summary)
			}, null, 2));
			return;
		}
		for (let i = 0; i < previewResults.length; i += 1) {
			const result = previewResults[i];
			if (i > 0) runtime.log("");
			renderStoreDryRunPlan({
				cfg,
				summary: result.summary,
				actionRows: result.actionRows,
				displayDefaults,
				runtime,
				showAgentHeader: previewResults.length > 1
			});
		}
		return;
	}
	const appliedSummaries = [];
	for (const target of targets) {
		const appliedReportRef = { current: null };
		const missingApplied = await updateSessionStore(target.storePath, async (store) => {
			if (!opts.fixMissing) return 0;
			return pruneMissingTranscriptEntries({
				store,
				storePath: target.storePath
			});
		}, {
			activeSessionKey: opts.activeKey,
			maintenanceOverride: { mode },
			onMaintenanceApplied: (report) => {
				appliedReportRef.current = report;
			}
		});
		const afterStore = loadSessionStore(target.storePath, { skipCache: true });
		const preview = previewResults.find((result) => result.summary.storePath === target.storePath);
		const appliedReport = appliedReportRef.current;
		const summary = appliedReport === null ? {
			...preview?.summary ?? {
				agentId: target.agentId,
				storePath: target.storePath,
				mode,
				dryRun: false,
				beforeCount: 0,
				afterCount: 0,
				missing: 0,
				pruned: 0,
				capped: 0,
				diskBudget: null,
				wouldMutate: false
			},
			dryRun: false,
			applied: true,
			appliedCount: Object.keys(afterStore).length
		} : {
			agentId: target.agentId,
			storePath: target.storePath,
			mode: appliedReport.mode,
			dryRun: false,
			beforeCount: appliedReport.beforeCount,
			afterCount: appliedReport.afterCount,
			missing: missingApplied,
			pruned: appliedReport.pruned,
			capped: appliedReport.capped,
			diskBudget: appliedReport.diskBudget,
			wouldMutate: missingApplied > 0 || appliedReport.pruned > 0 || appliedReport.capped > 0 || Boolean((appliedReport.diskBudget?.removedEntries ?? 0) > 0 || (appliedReport.diskBudget?.removedFiles ?? 0) > 0),
			applied: true,
			appliedCount: Object.keys(afterStore).length
		};
		appliedSummaries.push(summary);
	}
	if (opts.json) {
		if (appliedSummaries.length === 1) {
			runtime.log(JSON.stringify(appliedSummaries[0] ?? {}, null, 2));
			return;
		}
		runtime.log(JSON.stringify({
			allAgents: true,
			mode,
			dryRun: false,
			stores: appliedSummaries
		}, null, 2));
		return;
	}
	for (let i = 0; i < appliedSummaries.length; i += 1) {
		const summary = appliedSummaries[i];
		if (i > 0) runtime.log("");
		if (appliedSummaries.length > 1) runtime.log(`Agent: ${summary.agentId}`);
		runtime.log(`Session store: ${summary.storePath}`);
		runtime.log(`Applied maintenance. Current entries: ${summary.appliedCount ?? 0}`);
	}
}

//#endregion
//#region src/commands/sessions.ts
const AGENT_PAD = 10;
const KIND_PAD = 6;
const TOKENS_PAD = 20;
const formatKTokens = (value) => `${(value / 1e3).toFixed(value >= 1e4 ? 0 : 1)}k`;
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);
};
async function sessionsCommand(opts, runtime) {
	const aggregateAgents = opts.allAgents === true;
	const cfg = loadConfig();
	const displayDefaults = resolveSessionDisplayDefaults(cfg);
	const configContextTokens = cfg.agents?.defaults?.contextTokens ?? lookupContextTokens(displayDefaults.model) ?? DEFAULT_CONTEXT_TOKENS;
	const targets = resolveSessionStoreTargetsOrExit({
		cfg,
		opts: {
			store: opts.store,
			agent: opts.agent,
			allAgents: opts.allAgents
		},
		runtime
	});
	if (!targets) return;
	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 = targets.flatMap((target) => {
		const store = loadSessionStore(target.storePath);
		return toSessionDisplayRows(store).map((row) => ({
			...row,
			agentId: parseAgentSessionKey(row.key)?.agentId ?? target.agentId,
			kind: classifySessionKey(row.key, store[row.key])
		}));
	}).filter((row) => {
		if (activeMinutes === void 0) return true;
		if (!row.updatedAt) return false;
		return Date.now() - row.updatedAt <= activeMinutes * 6e4;
	}).toSorted((a, b) => (b.updatedAt ?? 0) - (a.updatedAt ?? 0));
	if (opts.json) {
		const multi = targets.length > 1;
		const aggregate = aggregateAgents || multi;
		runtime.log(JSON.stringify({
			path: aggregate ? null : targets[0]?.storePath ?? null,
			stores: aggregate ? targets.map((target) => ({
				agentId: target.agentId,
				path: target.storePath
			})) : void 0,
			allAgents: aggregateAgents ? true : void 0,
			count: rows.length,
			activeMinutes: activeMinutes ?? null,
			sessions: rows.map((r) => {
				const model = resolveSessionDisplayModel(cfg, r, displayDefaults);
				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;
	}
	if (targets.length === 1 && !aggregateAgents) runtime.log(info(`Session store: ${targets[0]?.storePath}`));
	else runtime.log(info(`Session stores: ${targets.length} (${targets.map((t) => t.agentId).join(", ")})`));
	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 showAgentColumn = aggregateAgents || targets.length > 1;
	const header = [
		...showAgentColumn ? ["Agent".padEnd(AGENT_PAD)] : [],
		"Kind".padEnd(KIND_PAD),
		"Key".padEnd(SESSION_KEY_PAD),
		"Age".padEnd(SESSION_AGE_PAD),
		"Model".padEnd(SESSION_MODEL_PAD),
		"Tokens (ctx %)".padEnd(TOKENS_PAD),
		"Flags"
	].join(" ");
	runtime.log(rich ? theme.heading(header) : header);
	for (const row of rows) {
		const model = resolveSessionDisplayModel(cfg, row, displayDefaults);
		const contextTokens = row.contextTokens ?? lookupContextTokens(model) ?? configContextTokens;
		const total = resolveFreshSessionTotalTokens(row);
		const line = [
			...showAgentColumn ? [rich ? theme.accentBright(row.agentId.padEnd(AGENT_PAD)) : row.agentId.padEnd(AGENT_PAD)] : [],
			formatKindCell(row.kind, rich),
			formatSessionKeyCell(row.key, rich),
			formatSessionAgeCell(row.updatedAt, rich),
			formatSessionModelCell(model, rich),
			formatTokensCell(total, contextTokens ?? null, rich),
			formatSessionFlagsCell(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;
}
async function runWithVerboseAndTimeout(opts, action) {
	const verbose = resolveVerbose(opts);
	setVerbose(verbose);
	const timeoutMs = parseTimeoutMs(opts.timeout);
	if (timeoutMs === null) return;
	await runCommandWithRuntime(defaultRuntime, async () => {
		await action({
			verbose,
			timeoutMs
		});
	});
}
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 + Discord + 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([
		["gensparx status", "Show channel health + session summary."],
		["gensparx status --all", "Full diagnosis (read-only)."],
		["gensparx status --json", "Machine-readable output."],
		["gensparx status --usage", "Show model provider usage/quota snapshots."],
		["gensparx status --deep", "Run channel probes (WA + Telegram + Discord + Slack + Signal)."],
		["gensparx status --deep --timeout 5000", "Tighten probe timeout."]
	])}`).addHelpText("after", () => `\n${theme.muted("Docs:")} ${formatDocsLink("/cli/status", "docs.gensparx.com/cli/status")}\n`).action(async (opts) => {
		await runWithVerboseAndTimeout(opts, async ({ verbose, timeoutMs }) => {
			await statusCommand({
				json: Boolean(opts.json),
				all: Boolean(opts.all),
				deep: Boolean(opts.deep),
				usage: Boolean(opts.usage),
				timeoutMs,
				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.gensparx.com/cli/health")}\n`).action(async (opts) => {
		await runWithVerboseAndTimeout(opts, async ({ verbose, timeoutMs }) => {
			await healthCommand({
				json: Boolean(opts.json),
				timeoutMs,
				verbose
			}, defaultRuntime);
		});
	});
	const sessionsCmd = 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("--agent <id>", "Agent id to inspect (default: configured default agent)").option("--all-agents", "Aggregate sessions across all configured agents", false).option("--active <minutes>", "Only show sessions updated within the past N minutes").addHelpText("after", () => `\n${theme.heading("Examples:")}\n${formatHelpExamples([
		["gensparx sessions", "List all sessions."],
		["gensparx sessions --agent work", "List sessions for one agent."],
		["gensparx sessions --all-agents", "Aggregate sessions across agents."],
		["gensparx sessions --active 120", "Only last 2 hours."],
		["gensparx sessions --json", "Machine-readable output."],
		["gensparx 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.gensparx.com/cli/sessions")}\n`).action(async (opts) => {
		setVerbose(Boolean(opts.verbose));
		await sessionsCommand({
			json: Boolean(opts.json),
			store: opts.store,
			agent: opts.agent,
			allAgents: Boolean(opts.allAgents),
			active: opts.active
		}, defaultRuntime);
	});
	sessionsCmd.enablePositionalOptions();
	sessionsCmd.command("cleanup").description("Run session-store maintenance now").option("--store <path>", "Path to session store (default: resolved from config)").option("--agent <id>", "Agent id to maintain (default: configured default agent)").option("--all-agents", "Run maintenance across all configured agents", false).option("--dry-run", "Preview maintenance actions without writing", false).option("--enforce", "Apply maintenance even when configured mode is warn", false).option("--fix-missing", "Remove store entries whose transcript files are missing (bypasses age/count retention)", false).option("--active-key <key>", "Protect this session key from budget-eviction").option("--json", "Output JSON", false).addHelpText("after", () => `\n${theme.heading("Examples:")}\n${formatHelpExamples([
		["gensparx sessions cleanup --dry-run", "Preview stale/cap cleanup."],
		["gensparx sessions cleanup --dry-run --fix-missing", "Also preview pruning entries with missing transcript files."],
		["gensparx sessions cleanup --enforce", "Apply maintenance now."],
		["gensparx sessions cleanup --agent work --dry-run", "Preview one agent store."],
		["gensparx sessions cleanup --all-agents --dry-run", "Preview all agent stores."],
		["gensparx sessions cleanup --enforce --store ./tmp/sessions.json", "Use a specific store."]
	])}`).action(async (opts, command) => {
		const parentOpts = command.parent?.opts();
		await runCommandWithRuntime(defaultRuntime, async () => {
			await sessionsCleanupCommand({
				store: opts.store ?? parentOpts?.store,
				agent: opts.agent ?? parentOpts?.agent,
				allAgents: Boolean(opts.allAgents || parentOpts?.allAgents),
				dryRun: Boolean(opts.dryRun),
				enforce: Boolean(opts.enforce),
				fixMissing: Boolean(opts.fixMissing),
				activeKey: opts.activeKey,
				json: Boolean(opts.json || parentOpts?.json)
			}, defaultRuntime);
		});
	});
}

//#endregion
export { registerStatusHealthSessionsCommands };