import { $n as lookupContextTokens, E as classifySessionKey, N as resolveSessionModelRef } from "./reply-B_OGAHxU.js";
import "./paths-B4BZAPZh.js";
import { P as setVerbose, k as info } from "./utils-h12D6i3s.js";
import { n as isRich, r as theme } from "./theme-CvDUwCeH.js";
import "./thinking-B3X4Pu2T.js";
import { x as parseAgentSessionKey } from "./session-key-CZ6OwgSB.js";
import "./registry-CEok6CBD.js";
import { f as defaultRuntime } from "./subsystem-CptcaHdG.js";
import "./exec-KZG5pigM.js";
import "./agent-scope-DuRxDIxP.js";
import { Gt as DEFAULT_PROVIDER, Ut as DEFAULT_CONTEXT_TOKENS, Wt as DEFAULT_MODEL, p as resolveConfiguredModelRef } from "./model-selection-Ci1X7yz4.js";
import "./github-copilot-token-BZDGcFI5.js";
import "./boolean-BsqeuxE6.js";
import "./env-Du80aeH-.js";
import { i as loadConfig } from "./config-DpEIy1Iq.js";
import "./manifest-registry-DP5prNZc.js";
import "./runner-B8-WBmYS.js";
import "./image-B5SB0tN4.js";
import "./models-config-BvUgiLNT.js";
import "./pi-model-discovery-BXtQTdf5.js";
import "./pi-embedded-helpers-Dt-sU2cn.js";
import "./sandbox-DaCbovTo.js";
import "./chrome-C2U0x_vA.js";
import "./tailscale-CRbgJwcF.js";
import "./auth-lS4wOBFo.js";
import "./server-context-B-YCUG7A.js";
import "./frontmatter-DrdSsH4-.js";
import "./skills-AD616ijL.js";
import "./routes-Cv9WOuy_.js";
import "./redact-CjJyQlVU.js";
import "./errors-CdJjJ1Jq.js";
import "./paths-WCTMjONe.js";
import "./ssrf-BT0IElaU.js";
import "./image-ops-BP1giyhy.js";
import "./store-q26Wtsy_.js";
import "./ports-CTzsGOMF.js";
import "./trash-BeFHeovG.js";
import { I as resolveFreshSessionTotalTokens, a as loadSessionStore } from "./sessions-C_NwV0mt.js";
import "./dock-kPWc7D0x.js";
import "./message-channel-CP2gEtPf.js";
import "./normalize-DqxNnJHS.js";
import "./accounts-DOhECffI.js";
import "./accounts-C1lp0M2X.js";
import "./accounts-BEp1f-Fs.js";
import "./bindings-OUZ-uS5k.js";
import "./logging-D3KTM1pH.js";
import "./send-D2KedNDe.js";
import "./plugins-DXhAnLR9.js";
import "./send-DgJ5msQW.js";
import { c as resolveStorePath } from "./paths-gjLMn4eA.js";
import "./tool-images-DJNWvX-X.js";
import "./tool-display-u8k8a1Tt.js";
import "./fetch-guard-ZRDg55CN.js";
import "./api-key-rotation-uNbQP6UQ.js";
import "./fetch-Dzzhxfkw.js";
import "./sqlite-DE_PUv3w.js";
import "./model-catalog-CvWJHJCg.js";
import "./tokens-DzxZZSkc.js";
import "./with-timeout-GP6SU5gJ.js";
import "./deliver-C4CaFOo6.js";
import "./diagnostic-BzB3fr3H.js";
import "./diagnostic-session-state-8W4S9gt1.js";
import "./send-CT8WXASB.js";
import "./model-Cvdxo1yi.js";
import "./reply-prefix-D96oVZA4.js";
import "./memory-cli-DWhshmym.js";
import "./manager--2hbjmvx.js";
import "./retry-C790w9um.js";
import "./common-DRqN8wrX.js";
import "./chunk-DLXgG-Hp.js";
import "./markdown-tables-PlwJ_Osa.js";
import "./ir-j6-6N0Xv.js";
import "./render-CXDO_kgw.js";
import "./commands-registry-HG-E3pjW.js";
import "./client-CyLl-iJJ.js";
import "./call-Bs5EoNE4.js";
import { n as formatTimeAgo } from "./format-relative-DlCMhQXD.js";
import "./channel-activity-BWmlj9sY.js";
import "./fetch-Cm3dYu7v.js";
import "./tables-nYGLZHh5.js";
import "./send-Cqajy2MP.js";
import "./pairing-store-DLcIgt6E.js";
import "./proxy-6yunx6Zq.js";
import { t as formatDocsLink } from "./links-Dmyh_lxI.js";
import { n as runCommandWithRuntime } from "./cli-utils-BqMwAlgf.js";
import { t as formatHelpExamples } from "./help-format-DEcAb7Hf.js";
import "./progress-CHPCu7oZ.js";
import "./resolve-route-D8T9lzde.js";
import "./replies-B-JUCnE1.js";
import "./skill-commands-BSfygubG.js";
import "./workspace-dirs-mwzNI7GY.js";
import "./pi-tools.policy-1nY10FTU.js";
import "./send-BgUrMvy5.js";
import "./onboard-helpers-C0RIySS1.js";
import "./prompt-style-7y8Wox11.js";
import "./outbound-attachment-CGcEC42p.js";
import "./pairing-labels-D713magM.js";
import "./session-cost-usage-CPpYqnqX.js";
import "./nodes-screen-DswDJioD.js";
import "./project-context-D8tjNLtw.js";
import "./control-service-2kAiX_qJ.js";
import "./stagger-Qhb6HicQ.js";
import "./channel-selection-DENvhXo1.js";
import "./delivery-queue-DnX3NB1u.js";
import "./runtime-guard-3Y9--7bU.js";
import { n as parsePositiveIntOrUndefined } from "./helpers-By2rxBQ5.js";
import "./skills-status-BcmTF6B8.js";
import "./dangerous-tools-BL-M3lPt.js";
import "./skill-scanner-Cd3fU8aC.js";
import "./channels-status-issues-DLRb-eyK.js";
import "./systemd-DRdU5sOU.js";
import "./service-BjqyRLSC.js";
import "./diagnostics-DQDJljoA.js";
import "./table-DLkikXy_.js";
import "./audit-zKH05-05.js";
import { t as statusCommand } from "./status-CWfJ5bwK.js";
import { r as healthCommand } from "./health-prGIcSiI.js";
import "./update-check-kCsojIzU.js";
import "./dm-policy-shared-BMsOB_6t.js";
import "./node-service-D9chWuEC.js";
import "./status.update-Dbc7PDVF.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 + 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([
		["openclaw status", "Show channel health + session summary."],
		["openclaw status --all", "Full diagnosis (read-only)."],
		["openclaw status --json", "Machine-readable output."],
		["openclaw status --usage", "Show model provider usage/quota snapshots."],
		["openclaw status --deep", "Run channel probes (WA + Telegram + Discord + Slack + Signal)."],
		["openclaw status --deep --timeout 5000", "Tighten probe timeout."]
	])}`).addHelpText("after", () => `\n${theme.muted("Docs:")} ${formatDocsLink("/cli/status", "docs.openclaw.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.openclaw.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([
		["openclaw sessions", "List all sessions."],
		["openclaw sessions --active 120", "Only last 2 hours."],
		["openclaw sessions --json", "Machine-readable output."],
		["openclaw 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.openclaw.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 };