import "./tool-display-DMBmPBI-.js";
import "./paths-WcYpcMAY.js";
import { Dt as theme, _ as defaultRuntime, xt as setVerbose } from "./entry.js";
import "./auth-profiles-CaNK0cUT.js";
import "./exec-CmvuUufz.js";
import "./agent-scope-E2aR3Ci_.js";
import "./github-copilot-token-CKOQDjEZ.js";
import "./emitter-BKo8D7Oj.js";
import "./sqlite-CVrhPija.js";
import "./reliability-BnL75OlZ.js";
import "./pi-model-discovery-Cd63DV2B.js";
import "./model-nrbMzlbz.js";
import "./frontmatter-C3D7gE4Z.js";
import "./skills-UwTwDeDw.js";
import "./manifest-registry-AgGLF4V7.js";
import "./skills-status-DzBNF0yU.js";
import "./validation-B00oOkJ3.js";
import "./config-CoCeK5B2.js";
import "./client-DtQEs2_8.js";
import "./call-CkgY6Bq7.js";
import "./message-channel-DKXbq8GH.js";
import "./subagent-registry-BSfrC7gZ.js";
import "./sessions-CFJLtXRH.js";
import "./tokens-D-4TlWcT.js";
import "./heartbeat-XNOTz34R.js";
import "./accounts-CNwod9BY.js";
import "./accounts-C3i8BBiA.js";
import "./normalize-CRf-uoB2.js";
import "./bindings-B1hNZin3.js";
import "./helpers-C1I2eYI4.js";
import "./allow-list-C1QL6XM_.js";
import "./logging-BiuZwq5D.js";
import "./client-BrCP9C3o.js";
import "./plugins-DMpYx7kb.js";
import "./targets-DvKzWjKi.js";
import "./with-timeout-xvreNRIp.js";
import "./diagnostic-CvuUUG_n.js";
import "./diagnostic-session-state-Dom6CWV9.js";
import "./lanes-6YZC1uc5.js";
import "./reply-payloads-DHkZZC3s.js";
import "./route-reply-0Dr2Q7BS.js";
import "./tts-CLI3TzKv.js";
import "./image-ops-D0pBQqKh.js";
import "./audio-xR21p4sl.js";
import "./pi-embedded-helpers-D-q9ylFX.js";
import "./sandbox-C79rEJ_w.js";
import "./chrome-BTLLz_O2.js";
import "./tailscale-V4nwZFBO.js";
import "./auth-Beo6eR0R.js";
import "./server-context-T5wFkzWi.js";
import "./routes-Ch0tqbTH.js";
import "./redact-2qrQ_uJt.js";
import "./errors-BlUw40-o.js";
import "./paths-Cb76_eC_.js";
import "./ssrf-BEPhIfOk.js";
import "./store-Bz34pm8z.js";
import "./ports-BsKQWWi9.js";
import "./trash-Cn3CsF86.js";
import "./dock-BvRrtCWj.js";
import "./accounts-CdYdWklO.js";
import "./paths-CDTtU20P.js";
import "./tool-images-B4eVOjD0.js";
import "./thinking-C03RqJxq.js";
import "./models-config-By95gdZa.js";
import "./chat-trace-C0wGIaWO.js";
import "./response-prefix-template-C1xl3U-G.js";
import "./tool-tracking-CtNygH0q.js";
import "./memory-cli-85mo64bb.js";
import "./manager-CFXUPO5v.js";
import "./gemini-auth-dH8SvNUd.js";
import "./session-files-0TqN4M7r.js";
import "./retry-Bdf0L_dZ.js";
import "./hybrid-DSp5ZIQe.js";
import "./common-CxpUJZLb.js";
import "./send-BozJfiUK.js";
import "./chunk-CNObemR3.js";
import "./markdown-tables-Cex18ib0.js";
import "./fetch-guard-BLrk92iq.js";
import "./fetch-DFo2YRBT.js";
import "./media-PPft1pQs.js";
import "./ir-CRxad2DW.js";
import "./render-JkHfM4BD.js";
import "./commands-registry-Ckq8wOdS.js";
import "./sessions-helpers-NrlH9x7w.js";
import "./pi-embedded-utils-BCSBp2bL.js";
import "./external-content-pnoCpvzd.js";
import "./runner-Dbz36vkv.js";
import "./image-tool.helpers-Bb25eyJc.js";
import "./image-DnnIE6E3.js";
import "./model-catalog-c_sp3sxR.js";
import "./session-utils-CwXLwy_N.js";
import "./workspace-dirs-Dm1vImLQ.js";
import "./skill-commands-B6qVCgej.js";
import "./fetch-CbnJhXfl.js";
import "./pairing-store-BHSQgDEs.js";
import "./exec-approvals-DGBfDg6X.js";
import "./gateway-CWnGRD4E.js";
import "./nodes-utils-DKSV6jwI.js";
import "./session-cost-usage-COXOEQzN.js";
import "./typed-schema-NhH7oBv2.js";
import "./knowledge-graph-njh3pt-F.js";
import "./model-fallback-N2p6k-x8.js";
import "./send-DpN8GxWR.js";
import "./channel-activity-Renq827a.js";
import "./tables-BD7LbCl1.js";
import "./server-startup-users-Dzui320y.js";
import "./resolve-route-CjJJ3gIl.js";
import "./replies-f6OSxuwk.js";
import "./reply-prefix-CjtRvYlq.js";
import "./pi-tools.policy-CW2flz_o.js";
import "./send-CdF3YtrB.js";
import "./onboard-helpers-HmtMUhNQ.js";
import "./prompt-style-BNQCf62G.js";
import "./onboard-helpers-CMBWpQU-.js";
import "./outbound-attachment-BhyLC0RY.js";
import "./targets-Df3HJYGb.js";
import "./pairing-labels-B7JDegCR.js";
import "./send-oTQYKgod.js";
import "./send-BxB9sGGU.js";
import "./proxy-BWmn1C2E.js";
import { t as formatDocsLink } from "./links-BcL73qkF.js";
import { n as runCommandWithRuntime } from "./cli-utils-CpDxBFOW.js";
import { t as formatHelpExamples } from "./help-format-CSTLKmFP.js";
import "./progress-Dh4aWkCA.js";
import "./active-listener-Bqb34bVB.js";
import "./restart-sentinel-DlT1-lDY.js";
import "./deliver-i2e9PiiC.js";
import "./delivery-queue-Db61Fz6r.js";
import "./dangerous-tools-DdHZGmZW.js";
import "./skill-scanner-BJtREUzt.js";
import "./channels-status-issues-nZItD_o7.js";
import "./systemd-DeFKuzWX.js";
import "./service-YvL1TaFp.js";
import "./runtime-guard-CKgtFStW.js";
import { i as healthCommand } from "./health-BhCvC4yy.js";
import "./table-_G8aohdO.js";
import { t as sessionsCommand } from "./sessions-C1W3dHzX.js";
import "./update-check-DaKl8In7.js";
import { n as statusCommand } from "./status-BjI9PlAc.js";
import "./audit-Kkts_C7v.js";
import "./dm-policy-shared-CSPEZcSu.js";
import "./diagnostics-BKwqV6LW.js";
import "./node-service-X9F2sia1.js";
import "./status.update-B-YvuZDz.js";
import { n as parsePositiveIntOrUndefined } from "./helpers-KrWU5zpF.js";

//#region src/eval/bls-wages.json
var occupations = {
	"software_developer": {
		"soc": "15-1252",
		"title": "Software Developers",
		"medianHourly": 63.44,
		"meanHourly": 65.57
	},
	"devops_engineer": {
		"soc": "15-1244",
		"title": "Network and Computer Systems Administrators",
		"medianHourly": 46.26,
		"meanHourly": 48.55
	},
	"data_scientist": {
		"soc": "15-2051",
		"title": "Data Scientists",
		"medianHourly": 55.63,
		"meanHourly": 58.39
	},
	"technical_writer": {
		"soc": "27-3042",
		"title": "Technical Writers",
		"medianHourly": 40.82,
		"meanHourly": 43.15
	},
	"project_manager": {
		"soc": "11-9199",
		"title": "Computer and Information Systems Managers",
		"medianHourly": 82.69,
		"meanHourly": 87.02
	},
	"qa_engineer": {
		"soc": "15-1253",
		"title": "Software Quality Assurance Analysts and Testers",
		"medianHourly": 49.67,
		"meanHourly": 51.82
	},
	"customer_support": {
		"soc": "15-1232",
		"title": "Computer User Support Specialists",
		"medianHourly": 28.44,
		"meanHourly": 30.56
	},
	"general_office": {
		"soc": "43-9061",
		"title": "Office Clerks, General",
		"medianHourly": 19.28,
		"meanHourly": 20.86
	}
};

//#endregion
//#region src/eval/roi-estimator.ts
/**
* ROI estimator — calculate return on investment for AI agent usage.
*
* Compares the cost of running AI agents (API costs + infrastructure)
* against the human labor cost that would be required to perform the
* same tasks. Uses BLS wage data for occupation-based estimation.
*
* @module
*/
/**
* Get the median hourly wage for an occupation.
*/
function getHourlyWage(occupation) {
	return occupations[occupation]?.medianHourly ?? 0;
}
/**
* List all available occupation IDs.
*/
function listOccupations() {
	return Object.keys(occupations);
}
/**
* Get occupation display title.
*/
function getOccupationTitle(occupation) {
	return occupations[occupation]?.title ?? occupation;
}
/**
* Calculate ROI for automating work with AI agents.
*/
function calculateROI(input) {
	const hourlyRate = input.customHourlyRate ?? getHourlyWage(input.occupation);
	const monthlySavings = input.hoursAutomatedPerMonth * hourlyRate;
	const monthlyAiCost = input.monthlyApiCost + (input.monthlyInfraCost ?? 0);
	const netMonthlyBenefit = monthlySavings - monthlyAiCost;
	const roiPercent = monthlyAiCost > 0 ? Math.round(netMonthlyBenefit / monthlyAiCost * 1e4) / 100 : monthlySavings > 0 ? Infinity : 0;
	const paybackMonths = netMonthlyBenefit > 0 ? Math.round(monthlyAiCost / netMonthlyBenefit * 100) / 100 : null;
	return {
		monthlySavings: Math.round(monthlySavings * 100) / 100,
		monthlyAiCost: Math.round(monthlyAiCost * 100) / 100,
		netMonthlyBenefit: Math.round(netMonthlyBenefit * 100) / 100,
		roiPercent,
		paybackMonths,
		hourlyRate,
		annualNetBenefit: Math.round(netMonthlyBenefit * 12 * 100) / 100
	};
}
/**
* Format ROI result as a human-readable summary.
*/
function formatROISummary(result) {
	const lines = [
		`Monthly labor savings: $${result.monthlySavings.toLocaleString()}`,
		`Monthly AI cost: $${result.monthlyAiCost.toLocaleString()}`,
		`Net monthly benefit: $${result.netMonthlyBenefit.toLocaleString()}`,
		`ROI: ${result.roiPercent === Infinity ? "∞" : `${result.roiPercent}%`}`,
		`Annual net benefit: $${result.annualNetBenefit.toLocaleString()}`
	];
	if (result.paybackMonths !== null) lines.push(`Payback period: ${result.paybackMonths} months`);
	return lines.join("\n");
}

//#endregion
//#region src/cli/commands/roi.ts
/**
* CLI ROI command — calculate return on investment for AI agent usage.
*
* Wraps the ROI estimator module as `minion roi`.
*
* @module
*/
async function roiCommand(opts, runtime) {
	if (opts.listOccupations) {
		const occupations = listOccupations();
		if (opts.json) {
			const data = occupations.map((id) => ({
				id,
				title: getOccupationTitle(id),
				medianHourly: getHourlyWage(id)
			}));
			runtime.log(JSON.stringify(data, null, 2));
			return;
		}
		runtime.log("Available occupations:\n");
		for (const id of occupations) {
			const title = getOccupationTitle(id);
			const wage = getHourlyWage(id);
			runtime.log(`  ${id.padEnd(25)} ${title.padEnd(35)} $${wage.toFixed(2)}/hr`);
		}
		return;
	}
	if (!opts.hours) {
		runtime.error("--hours is required. Use --hours <n> to specify hours automated per month.");
		return;
	}
	const hours = Number(opts.hours);
	if (!Number.isFinite(hours) || hours < 0) {
		runtime.error("--hours must be a positive number.");
		return;
	}
	const apiCost = opts.apiCost ? Number(opts.apiCost) : 0;
	const infraCost = opts.infraCost ? Number(opts.infraCost) : 0;
	if (!Number.isFinite(apiCost) || apiCost < 0) {
		runtime.error("--api-cost must be a non-negative number.");
		return;
	}
	if (!Number.isFinite(infraCost) || infraCost < 0) {
		runtime.error("--infra-cost must be a non-negative number.");
		return;
	}
	const customRate = opts.rate ? Number(opts.rate) : void 0;
	if (customRate !== void 0 && (!Number.isFinite(customRate) || customRate <= 0)) {
		runtime.error("--rate must be a positive number.");
		return;
	}
	const occupation = opts.occupation ?? "software_developer";
	if (!customRate) {
		if (getHourlyWage(occupation) === 0) {
			runtime.error(`Unknown occupation "${occupation}". Use --list-occupations to see available IDs.`);
			return;
		}
	}
	const result = calculateROI({
		hoursAutomatedPerMonth: hours,
		occupation,
		monthlyApiCost: apiCost,
		monthlyInfraCost: infraCost,
		customHourlyRate: customRate
	});
	if (opts.json) {
		runtime.log(JSON.stringify(result, null, 2));
		return;
	}
	runtime.log(formatROISummary(result));
}

//#endregion
//#region src/tools/undo-stack.ts
const DEFAULT_MAX_SIZE = 50;
const DEFAULT_MAX_AGE_MS = 3600 * 1e3;
var UndoStack = class {
	constructor(config) {
		this.stack = [];
		this.config = {
			maxSize: config?.maxSize ?? DEFAULT_MAX_SIZE,
			maxAgeMs: config?.maxAgeMs ?? DEFAULT_MAX_AGE_MS
		};
	}
	/**
	* Record an undoable action.
	*/
	push(action) {
		this.pruneExpired();
		this.stack.push({
			...action,
			recordedAt: Date.now(),
			undone: false
		});
		while (this.stack.length > this.config.maxSize) this.stack.shift();
	}
	/**
	* Undo the most recent non-undone action.
	*
	* Returns the result of the undo operation, or null if no actions available.
	*/
	async undoLast() {
		this.pruneExpired();
		for (let i = this.stack.length - 1; i >= 0; i--) {
			const action = this.stack[i];
			if (!action.undone) return this.executeUndo(action);
		}
		return null;
	}
	/**
	* Undo a specific action by ID.
	*/
	async undoById(actionId) {
		const action = this.stack.find((a) => a.id === actionId && !a.undone);
		if (!action) return null;
		return this.executeUndo(action);
	}
	/**
	* Get all actions in the stack (newest first).
	*/
	getActions() {
		this.pruneExpired();
		return this.stack.map(({ undo: _, ...rest }) => rest).toReversed();
	}
	/**
	* Get the number of undoable (non-undone, non-expired) actions.
	*/
	undoableCount() {
		this.pruneExpired();
		return this.stack.filter((a) => !a.undone).length;
	}
	/**
	* Clear the entire undo stack.
	*/
	clear() {
		this.stack = [];
	}
	/**
	* Get the current stack size.
	*/
	get size() {
		return this.stack.length;
	}
	async executeUndo(action) {
		try {
			const success = await action.undo();
			action.undone = true;
			return {
				success,
				actionId: action.id,
				description: action.description
			};
		} catch (err) {
			return {
				success: false,
				actionId: action.id,
				description: action.description,
				error: err instanceof Error ? err.message : String(err)
			};
		}
	}
	pruneExpired() {
		const cutoff = Date.now() - this.config.maxAgeMs;
		this.stack = this.stack.filter((a) => a.recordedAt >= cutoff);
	}
};

//#endregion
//#region src/cli/commands/undo.ts
let sessionStack;
/**
* Get the session-scoped undo stack (creates one if needed).
*/
function getSessionUndoStack() {
	if (!sessionStack) sessionStack = new UndoStack();
	return sessionStack;
}
async function undoCommand(opts, runtime) {
	const stack = getSessionUndoStack();
	if (opts.list) {
		const actions = stack.getActions();
		if (actions.length === 0) {
			runtime.log("Nothing to undo.");
			return;
		}
		if (opts.json) {
			runtime.log(JSON.stringify(actions, null, 2));
			return;
		}
		runtime.log(`Undo history (${actions.length} actions, ${stack.undoableCount()} undoable):\n`);
		for (const action of actions) {
			const status = action.undone ? "✓ undone" : "pending";
			const time = new Date(action.recordedAt).toLocaleTimeString();
			runtime.log(`  [${action.id}] ${action.toolName}: ${action.description} (${status}, ${time})`);
		}
		return;
	}
	if (opts.all) {
		if (stack.undoableCount() === 0) {
			runtime.log("Nothing to undo.");
			return;
		}
		let undone = 0;
		let failed = 0;
		while (stack.undoableCount() > 0) {
			const result = await stack.undoLast();
			if (!result) break;
			if (result.success) {
				undone++;
				runtime.log(`Undone: ${result.description}`);
			} else {
				failed++;
				runtime.log(`Failed to undo: ${result.description} — ${result.error ?? "unknown error"}`);
			}
		}
		runtime.log(`\nUndone ${undone} action(s)${failed > 0 ? `, ${failed} failed` : ""}.`);
		return;
	}
	if (opts.id) {
		const result = await stack.undoById(opts.id);
		if (!result) {
			runtime.log(`No undoable action with ID "${opts.id}".`);
			return;
		}
		if (result.success) runtime.log(`Undone: ${result.description}`);
		else runtime.log(`Failed to undo: ${result.description} — ${result.error ?? "unknown error"}`);
		return;
	}
	const result = await stack.undoLast();
	if (!result) {
		runtime.log("Nothing to undo.");
		return;
	}
	if (result.success) runtime.log(`Undone: ${result.description}`);
	else runtime.log(`Failed to undo: ${result.description} — ${result.error ?? "unknown error"}`);
}

//#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([
		["minion status", "Show channel health + session summary."],
		["minion status --all", "Full diagnosis (read-only)."],
		["minion status --json", "Machine-readable output."],
		["minion status --usage", "Show model provider usage/quota snapshots."],
		["minion status --deep", "Run channel probes (WA + Telegram + Discord + Slack + Signal)."],
		["minion status --deep --timeout 5000", "Tighten probe timeout."]
	])}`).addHelpText("after", () => `\n${theme.muted("Docs:")} ${formatDocsLink("/cli/status", "docs.minion.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.minion.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([
		["minion sessions", "List all sessions."],
		["minion sessions --active 120", "Only last 2 hours."],
		["minion sessions --json", "Machine-readable output."],
		["minion 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.minion.ai/cli/sessions")}\n`).action(async (opts) => {
		setVerbose(Boolean(opts.verbose));
		await sessionsCommand({
			json: Boolean(opts.json),
			store: opts.store,
			active: opts.active
		}, defaultRuntime);
	});
	program.command("undo").description("Undo recent tool-call actions (file writes, deletes, etc.)").option("--list", "Show undo history without undoing anything", false).option("--all", "Undo all available actions", false).option("--id <actionId>", "Undo a specific action by ID").option("--json", "Output as JSON", false).addHelpText("after", () => `\n${theme.heading("Examples:")}\n${formatHelpExamples([
		["minion undo", "Undo the last action."],
		["minion undo --list", "Show undo history."],
		["minion undo --all", "Undo all available actions."],
		["minion undo --id abc123", "Undo a specific action by ID."]
	])}`).action(async (opts) => {
		await runCommandWithRuntime(defaultRuntime, async () => {
			await undoCommand({
				list: Boolean(opts.list),
				all: Boolean(opts.all),
				id: opts.id,
				json: Boolean(opts.json)
			}, defaultRuntime);
		});
	});
	program.command("roi").description("Calculate ROI for AI agent automation").requiredOption("--hours <n>", "Hours of human work automated per month").option("--occupation <id>", "BLS occupation ID for wage lookup (default: software_developer)").option("--rate <dollars>", "Custom hourly rate override (skips BLS lookup)").option("--api-cost <dollars>", "Monthly AI API cost in USD (default: 0)").option("--infra-cost <dollars>", "Monthly infrastructure cost in USD (default: 0)").option("--list-occupations", "List available occupation IDs with titles and wages", false).option("--json", "Output as JSON", false).addHelpText("after", () => `\n${theme.heading("Examples:")}\n${formatHelpExamples([
		["minion roi --hours 40 --api-cost 200", "ROI for 40h/month automation."],
		["minion roi --hours 20 --rate 75 --api-cost 100", "Custom hourly rate."],
		["minion roi --list-occupations", "Show available occupation IDs."],
		["minion roi --hours 40 --occupation customer_support --api-cost 50", "ROI for support automation."]
	])}`).action(async (opts) => {
		await runCommandWithRuntime(defaultRuntime, async () => {
			await roiCommand({
				hours: opts.hours,
				occupation: opts.occupation,
				rate: opts.rate,
				apiCost: opts.apiCost,
				infraCost: opts.infraCost,
				listOccupations: Boolean(opts.listOccupations),
				json: Boolean(opts.json)
			}, defaultRuntime);
		});
	});
}

//#endregion
export { registerStatusHealthSessionsCommands };