import "./tool-display-DMBmPBI-.js";
import { v as resolveStateDir } from "./paths-WcYpcMAY.js";
import { Dt as theme, _ as defaultRuntime, w as DEFAULT_CHAT_CHANNEL, xt as setVerbose } from "./entry.js";
import "./auth-profiles-CaNK0cUT.js";
import { t as formatCliCommand } from "./command-format-C8jrlG0z.js";
import { u as normalizeAgentId } from "./session-key-Fto5gqqw.js";
import "./exec-CmvuUufz.js";
import { l as resolveAgentWorkspaceDir, n as listAgentIds, u as resolveDefaultAgentId } from "./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 "./validation-B00oOkJ3.js";
import { o as loadConfig } from "./config-CoCeK5B2.js";
import "./client-DtQEs2_8.js";
import { i as randomIdempotencyKey, n as callGateway } from "./call-CkgY6Bq7.js";
import { h as GATEWAY_CLIENT_NAMES, l as normalizeMessageChannel, m as GATEWAY_CLIENT_MODES } from "./message-channel-DKXbq8GH.js";
import { jt as validateTemplate } from "./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 { n as withProgress } from "./progress-Dh4aWkCA.js";
import "./active-listener-Bqb34bVB.js";
import "./env-file-Dk0_93lQ.js";
import "./deliver-i2e9PiiC.js";
import "./delivery-queue-Db61Fz6r.js";
import { r as readManifest } from "./orchestration-manifest-qOFXJrth.js";
import { t as hasExplicitOptions } from "./command-options-CjC8Pp3r.js";
import "./catalog-Cd-lskrP.js";
import "./note-DWT0BShu.js";
import "./clack-prompter-BhG0EDVO.js";
import "./plugin-auto-enable-B80kKDWG.js";
import "./install-safe-path-D9nN_mdy.js";
import "./npm-registry-spec-CPq_jPVk.js";
import "./skill-scanner-BJtREUzt.js";
import "./installs-UNHq0xKX.js";
import "./onboard-channels-FVO39EHT.js";
import "./config-validation-8Iy6ScNI.js";
import { a as agentsAddCommand, i as agentsDeleteCommand, n as agentsListCommand, r as agentsSetIdentityCommand } from "./agents-BLNWTYaj.js";
import "./logging-pdRgYr5v.js";
import "./auth-choice-BBMz5Rfl.js";
import "./onboard-auth-VL7a_G7F.js";
import "./github-copilot-auth-BatuvWyD.js";
import "./openai-model-default-CIdWgasf.js";
import "./shared-Co9hFJPL.js";
import "./vllm-setup-BfUGZi4G.js";
import "./agents.config-CtYh7F5Y.js";
import { t as collectOption } from "./helpers-KrWU5zpF.js";
import { n as createDefaultDeps } from "./outbound-send-deps-BOpEOnYa.js";
import { n as resolveSessionKeyForRequest, t as agentCommand } from "./agent-DW-bfNgA.js";
import * as path$1 from "node:path";
import path from "node:path";
import * as fs$1 from "node:fs";
import fs from "node:fs";
import { parse } from "yaml";
import * as readline$1 from "node:readline";

//#region src/cli/commands/agent-via-gateway.ts
const NO_GATEWAY_TIMEOUT_MS = 2147e6;
function parseTimeoutSeconds(opts) {
	const raw = opts.timeout !== void 0 ? Number.parseInt(String(opts.timeout), 10) : opts.cfg.agents?.defaults?.timeoutSeconds ?? 600;
	if (Number.isNaN(raw) || raw < 0) throw new Error("--timeout must be a non-negative integer (seconds; 0 means no timeout)");
	return raw;
}
function formatPayloadForLog(payload) {
	const lines = [];
	if (payload.text) lines.push(payload.text.trimEnd());
	const mediaUrl = typeof payload.mediaUrl === "string" && payload.mediaUrl.trim() ? payload.mediaUrl.trim() : void 0;
	const media = payload.mediaUrls ?? (mediaUrl ? [mediaUrl] : []);
	for (const url of media) lines.push(`MEDIA:${url}`);
	return lines.join("\n").trimEnd();
}
async function agentViaGatewayCommand(opts, runtime) {
	const body = (opts.message ?? "").trim();
	if (!body) throw new Error("Message (--message) is required");
	if (!opts.to && !opts.sessionId && !opts.agent) throw new Error("Pass --to <E.164>, --session-id, or --agent to choose a session");
	const cfg = loadConfig();
	const agentIdRaw = opts.agent?.trim();
	const agentId = agentIdRaw ? normalizeAgentId(agentIdRaw) : void 0;
	if (agentId) {
		if (!listAgentIds(cfg).includes(agentId)) throw new Error(`Unknown agent id "${agentIdRaw}". Use "${formatCliCommand("minion agents list")}" to see configured agents.`);
	}
	const timeoutSeconds = parseTimeoutSeconds({
		cfg,
		timeout: opts.timeout
	});
	const gatewayTimeoutMs = timeoutSeconds === 0 ? NO_GATEWAY_TIMEOUT_MS : Math.max(1e4, (timeoutSeconds + 30) * 1e3);
	const sessionKey = resolveSessionKeyForRequest({
		cfg,
		agentId,
		to: opts.to,
		sessionId: opts.sessionId
	}).sessionKey;
	const channel = normalizeMessageChannel(opts.channel) ?? DEFAULT_CHAT_CHANNEL;
	const idempotencyKey = opts.runId?.trim() || randomIdempotencyKey();
	const response = await withProgress({
		label: "Waiting for agent reply…",
		indeterminate: true,
		enabled: opts.json !== true
	}, async () => await callGateway({
		method: "agent",
		params: {
			message: body,
			agentId,
			to: opts.to,
			replyTo: opts.replyTo,
			sessionId: opts.sessionId,
			sessionKey,
			thinking: opts.thinking,
			deliver: Boolean(opts.deliver),
			channel,
			replyChannel: opts.replyChannel,
			replyAccountId: opts.replyAccount,
			timeout: timeoutSeconds,
			lane: opts.lane,
			extraSystemPrompt: opts.extraSystemPrompt,
			idempotencyKey
		},
		expectFinal: true,
		timeoutMs: gatewayTimeoutMs,
		clientName: GATEWAY_CLIENT_NAMES.CLI,
		mode: GATEWAY_CLIENT_MODES.CLI
	}));
	if (opts.json) {
		runtime.log(JSON.stringify(response, null, 2));
		return response;
	}
	const payloads = (response?.result)?.payloads ?? [];
	if (payloads.length === 0) {
		runtime.log(response?.summary ? String(response.summary) : "No reply from agent.");
		return response;
	}
	for (const payload of payloads) {
		const out = formatPayloadForLog(payload);
		if (out) runtime.log(out);
	}
	return response;
}
async function agentCliCommand(opts, runtime, deps) {
	const localOpts = {
		...opts,
		agentId: opts.agent,
		replyAccountId: opts.replyAccount,
		workspaceId: opts.workspaceId
	};
	if (opts.local === true) return await agentCommand(localOpts, runtime, deps);
	try {
		return await agentViaGatewayCommand(opts, runtime);
	} catch (err) {
		runtime.error?.(`Gateway agent failed; falling back to embedded: ${String(err)}`);
		return await agentCommand(localOpts, runtime, deps);
	}
}

//#endregion
//#region src/cli/commands/orchestrations.commands.list.ts
function registerOrchestrationsListCommand(parent) {
	parent.command("list").description("List orchestrations").option("--status <status>", "Filter by status (pending, running, completed, failed, interrupted)").option("--since <date>", "Show orchestrations started after this date (ISO 8601)").option("--agent <id>", "Agent id").option("--json", "Output raw JSON", false).action(async (opts) => {
		try {
			const params = {};
			if (opts.status) params.status = opts.status;
			if (opts.since) {
				const sinceMs = new Date(opts.since).getTime();
				if (Number.isNaN(sinceMs)) {
					console.error(theme.error("Invalid --since date. Use ISO 8601 format."));
					process.exitCode = 1;
					return;
				}
				params.since = sinceMs;
			}
			if (opts.agent) params.agentId = opts.agent;
			const result = await withProgress({
				label: "Gateway pi-agent.orchestrations.list",
				indeterminate: true,
				enabled: !opts.json
			}, async () => await callGateway({
				method: "pi-agent.orchestrations.list",
				params,
				timeoutMs: 1e4
			}));
			if (!result) {
				console.error(theme.error("Failed to fetch orchestrations from gateway."));
				process.exitCode = 1;
				return;
			}
			if (opts.json) {
				console.log(JSON.stringify(result, null, 2));
				return;
			}
			const { orchestrations } = result;
			if (orchestrations.length === 0) {
				console.log(theme.muted("No orchestrations found."));
				return;
			}
			const idWidth = Math.max(2, 8);
			const statusWidth = Math.max(6, ...orchestrations.map((o) => o.status.length));
			const tasksWidth = 5;
			const modeWidth = Math.max(4, ...orchestrations.map((o) => o.mode.length));
			const startedWidth = 19;
			const durationWidth = 10;
			const header = [
				"ID".padEnd(idWidth),
				"Status".padEnd(statusWidth),
				"Tasks".padEnd(tasksWidth),
				"Mode".padEnd(modeWidth),
				"Started".padEnd(startedWidth),
				"Duration".padEnd(durationWidth)
			].join("  ");
			const separator = [
				"-".repeat(idWidth),
				"-".repeat(statusWidth),
				"-".repeat(modeWidth),
				"-".repeat(tasksWidth),
				"-".repeat(startedWidth),
				"-".repeat(durationWidth)
			].join("  ");
			console.log(theme.heading("\nOrchestrations:\n"));
			console.log(theme.muted(header));
			console.log(theme.muted(separator));
			for (const o of orchestrations) {
				const shortId = o.orchestrationId.slice(0, 8);
				const started = new Date(o.startedAt).toISOString().slice(0, 19).replace("T", " ");
				const duration = o.completedAt ? formatDuration$1(o.completedAt - o.startedAt) : theme.muted("running");
				const row = [
					shortId.padEnd(idWidth),
					o.status.padEnd(statusWidth),
					String(o.taskCount).padEnd(tasksWidth),
					o.mode.padEnd(modeWidth),
					started.padEnd(startedWidth),
					duration.padEnd(durationWidth)
				].join("  ");
				console.log(row);
			}
			console.log(theme.muted(`\n${orchestrations.length} orchestration(s).`));
		} catch (err) {
			console.error(theme.error(`Failed to connect to gateway: ${err instanceof Error ? err.message : String(err)}`));
			process.exitCode = 1;
		}
	});
}
function formatDuration$1(ms) {
	if (ms < 1e3) return `${ms}ms`;
	const seconds = Math.floor(ms / 1e3);
	if (seconds < 60) return `${seconds}s`;
	return `${Math.floor(seconds / 60)}m${seconds % 60}s`;
}

//#endregion
//#region src/cli/commands/orchestrations.commands.get.ts
function registerOrchestrationsGetCommand(parent) {
	parent.command("get <id>").description("Show full manifest detail for an orchestration").option("--agent <agentId>", "Agent id").option("--json", "Output full JSON", false).action(async (id, opts) => {
		try {
			const params = { orchestrationId: id };
			if (opts.agent) params.agentId = opts.agent;
			const result = await withProgress({
				label: "Gateway pi-agent.orchestrations.get",
				indeterminate: true,
				enabled: !opts.json
			}, async () => await callGateway({
				method: "pi-agent.orchestrations.get",
				params,
				timeoutMs: 1e4
			}));
			if (!result?.orchestration) {
				console.error(theme.error(`Orchestration not found: ${id}`));
				process.exitCode = 1;
				return;
			}
			if (opts.json) {
				console.log(JSON.stringify(result, null, 2));
				return;
			}
			const o = result.orchestration;
			console.log(theme.heading(`\nOrchestration: ${o.orchestrationId}\n`));
			console.log(`  ${theme.muted("Mode:")}         ${o.mode}`);
			console.log(`  ${theme.muted("Status:")}       ${o.status}`);
			console.log(`  ${theme.muted("Tasks:")}        ${o.taskCount}`);
			console.log(`  ${theme.muted("Started:")}      ${new Date(o.startedAt).toISOString()}`);
			if (o.completedAt) {
				console.log(`  ${theme.muted("Completed:")}    ${new Date(o.completedAt).toISOString()}`);
				const durationMs = o.completedAt - o.startedAt;
				console.log(`  ${theme.muted("Duration:")}     ${formatDuration(durationMs)}`);
			}
			if (o.tasks.length > 0) {
				console.log(theme.heading("\n  Tasks:\n"));
				const idxWidth = 3;
				const labelWidth = Math.max(5, ...o.tasks.map((t) => t.label.length));
				const templateWidth = Math.max(8, ...o.tasks.map((t) => (t.template ?? "").length));
				const statusWidth = Math.max(6, ...o.tasks.map((t) => t.status.length));
				const durationWidth = 10;
				const header = [
					"#".padEnd(idxWidth),
					"Label".padEnd(labelWidth),
					"Template".padEnd(templateWidth),
					"Status".padEnd(statusWidth),
					"Duration".padEnd(durationWidth)
				].join("  ");
				const sep = [
					"-".repeat(idxWidth),
					"-".repeat(labelWidth),
					"-".repeat(templateWidth),
					"-".repeat(statusWidth),
					"-".repeat(durationWidth)
				].join("  ");
				console.log(`  ${theme.muted(header)}`);
				console.log(`  ${theme.muted(sep)}`);
				for (const t of o.tasks) {
					const dur = t.startedAt && t.completedAt ? formatDuration(t.completedAt - t.startedAt) : theme.muted("-");
					const row = [
						String(t.index).padEnd(idxWidth),
						t.label.padEnd(labelWidth),
						(t.template ?? theme.muted("(none)")).padEnd(templateWidth),
						t.status.padEnd(statusWidth),
						dur.padEnd(durationWidth)
					].join("  ");
					console.log(`  ${row}`);
					if (t.error) console.log(`    ${theme.error(`Error: ${t.error}`)}`);
				}
			}
			console.log("");
		} catch (err) {
			const msg = err instanceof Error ? err.message : String(err);
			if (msg.includes("orchestration not found")) console.error(theme.error(msg));
			else console.error(theme.error(`Failed to connect to gateway: ${msg}`));
			process.exitCode = 1;
		}
	});
}
function formatDuration(ms) {
	if (ms < 1e3) return `${ms}ms`;
	const seconds = Math.floor(ms / 1e3);
	if (seconds < 60) return `${seconds}s`;
	return `${Math.floor(seconds / 60)}m${seconds % 60}s`;
}

//#endregion
//#region src/cli/commands/orchestrations.commands.inspect.ts
function registerOrchestrationsInspectCommand(parent) {
	parent.command("inspect <id>").description("Show directory tree with file sizes for an orchestration").option("--agent <agentId>", "Agent id").action(async (id, opts) => {
		try {
			const cfg = loadConfig();
			const workspaceDir = resolveAgentWorkspaceDir(cfg, opts.agent || resolveDefaultAgentId(cfg));
			const orchestrationDir = path$1.join(workspaceDir, "orchestrations", id);
			if (!fs$1.existsSync(orchestrationDir)) {
				console.error(theme.error(`Orchestration directory not found: ${orchestrationDir}`));
				process.exitCode = 1;
				return;
			}
			console.log(theme.heading(`\nOrchestration: ${id}\n`));
			printTree(orchestrationDir, `orchestrations/${id}/`, "");
			console.log("");
		} catch (err) {
			console.error(theme.error(`Failed to inspect orchestration: ${err instanceof Error ? err.message : String(err)}`));
			process.exitCode = 1;
		}
	});
}
function printTree(dirPath, displayPath, indent) {
	console.log(`${indent}${theme.heading(displayPath)}`);
	let entries;
	try {
		entries = fs$1.readdirSync(dirPath, { withFileTypes: true });
	} catch {
		return;
	}
	const dirs = entries.filter((e) => e.isDirectory()).toSorted((a, b) => a.name.localeCompare(b.name));
	const files = entries.filter((e) => e.isFile()).toSorted((a, b) => a.name.localeCompare(b.name));
	for (const file of files) {
		const filePath = path$1.join(dirPath, file.name);
		const size = formatSize(filePath);
		let suffix = "";
		if (file.name === "status.json") try {
			const content = fs$1.readFileSync(filePath, "utf-8");
			const parsed = JSON.parse(content);
			if (typeof parsed.status === "string") suffix = ` - ${parsed.status}`;
		} catch {}
		console.log(`${indent}  ${file.name} ${theme.muted(`(${size})`)}${suffix}`);
	}
	for (const dir of dirs) printTree(path$1.join(dirPath, dir.name), `${dir.name}/`, `${indent}  `);
}
function formatSize(filePath) {
	try {
		const bytes = fs$1.statSync(filePath).size;
		if (bytes < 1024) return `${bytes} B`;
		const kb = bytes / 1024;
		if (kb < 1024) return `${kb.toFixed(1)} KB`;
		return `${(kb / 1024).toFixed(1)} MB`;
	} catch {
		return "? B";
	}
}

//#endregion
//#region src/cli/commands/orchestrations.commands.cleanup.ts
const DISK_WARNING_THRESHOLD_BYTES = 500 * 1024 * 1024;
function registerOrchestrationsCleanupCommand(parent) {
	parent.command("cleanup").description("Delete old completed/failed orchestration directories").option("--older-than <days>", "Delete orchestrations older than N days (default: 7)", "7").option("--dry-run", "Show what would be deleted without deleting", false).option("--force", "Skip confirmation prompt", false).option("--agent <id>", "Agent id").action(async (opts) => {
		try {
			const cfg = loadConfig();
			const workspaceDir = resolveAgentWorkspaceDir(cfg, opts.agent || resolveDefaultAgentId(cfg));
			const orchestrationsDir = path$1.join(workspaceDir, "orchestrations");
			if (!fs$1.existsSync(orchestrationsDir)) {
				console.log(theme.muted("No orchestrations directory found."));
				return;
			}
			const olderThanDays = Number.parseInt(opts.olderThan, 10);
			if (Number.isNaN(olderThanDays) || olderThanDays < 0) {
				console.error(theme.error("Invalid --older-than value. Must be a non-negative number."));
				process.exitCode = 1;
				return;
			}
			const cutoffMs = Date.now() - olderThanDays * 24 * 60 * 60 * 1e3;
			let entries;
			try {
				entries = fs$1.readdirSync(orchestrationsDir, { withFileTypes: true });
			} catch {
				console.log(theme.muted("No orchestrations found."));
				return;
			}
			const candidates = [];
			let totalDirSize = 0;
			for (const entry of entries) {
				if (!entry.isDirectory()) continue;
				const dirPath = path$1.join(orchestrationsDir, entry.name);
				const dirSize = getDirSize(dirPath);
				totalDirSize += dirSize;
				const manifest = readManifest(dirPath);
				if (!manifest) continue;
				if (manifest.status !== "completed" && manifest.status !== "failed" && manifest.status !== "interrupted") continue;
				const completedAt = manifest.completedAt ?? manifest.startedAt;
				if (completedAt > cutoffMs) continue;
				candidates.push({
					orchestrationId: manifest.orchestrationId,
					dirPath,
					status: manifest.status,
					completedAt,
					sizeBytes: dirSize
				});
			}
			if (totalDirSize > DISK_WARNING_THRESHOLD_BYTES) {
				const totalMB = (totalDirSize / (1024 * 1024)).toFixed(1);
				console.log(theme.warn(`Warning: orchestrations/ directory is ${totalMB} MB (threshold: ${(DISK_WARNING_THRESHOLD_BYTES / (1024 * 1024)).toFixed(0)} MB)`));
			}
			if (candidates.length === 0) {
				console.log(theme.muted(`No orchestrations older than ${olderThanDays} day(s) eligible for cleanup.`));
				return;
			}
			const totalStr = formatBytes(candidates.reduce((sum, c) => sum + c.sizeBytes, 0));
			console.log(theme.heading(`\n${opts.dryRun ? "[DRY RUN] " : ""}Orchestrations to ${opts.dryRun ? "be " : ""}delete${opts.dryRun ? "d" : ""}:\n`));
			for (const c of candidates) {
				const shortId = c.orchestrationId.slice(0, 8);
				const age = Math.floor((Date.now() - c.completedAt) / (1440 * 60 * 1e3));
				console.log(`  ${shortId}  ${c.status.padEnd(12)}  ${formatBytes(c.sizeBytes).padEnd(10)}  ${age}d ago`);
			}
			console.log(theme.muted(`\n${candidates.length} orchestration(s), ${totalStr} total.`));
			if (opts.dryRun) return;
			if (!opts.force) {
				if (!await promptConfirm(`Delete ${candidates.length} orchestration(s) (${totalStr})?`)) {
					console.log(theme.muted("Cleanup cancelled."));
					return;
				}
			}
			let deleted = 0;
			let freedBytes = 0;
			for (const c of candidates) try {
				fs$1.rmSync(c.dirPath, {
					recursive: true,
					force: true
				});
				deleted++;
				freedBytes += c.sizeBytes;
			} catch (err) {
				console.error(theme.error(`Failed to delete ${c.orchestrationId}: ${err instanceof Error ? err.message : String(err)}`));
			}
			console.log(theme.muted(`\nDeleted ${deleted} orchestration(s), freed ${formatBytes(freedBytes)}.`));
		} catch (err) {
			console.error(theme.error(`Cleanup failed: ${err instanceof Error ? err.message : String(err)}`));
			process.exitCode = 1;
		}
	});
}
function getDirSize(dirPath) {
	let totalSize = 0;
	try {
		const entries = fs$1.readdirSync(dirPath, { withFileTypes: true });
		for (const entry of entries) {
			const entryPath = path$1.join(dirPath, entry.name);
			if (entry.isFile()) try {
				totalSize += fs$1.statSync(entryPath).size;
			} catch {}
			else if (entry.isDirectory()) totalSize += getDirSize(entryPath);
		}
	} catch {}
	return totalSize;
}
function formatBytes(bytes) {
	if (bytes < 1024) return `${bytes} B`;
	const kb = bytes / 1024;
	if (kb < 1024) return `${kb.toFixed(1)} KB`;
	const mb = kb / 1024;
	if (mb < 1024) return `${mb.toFixed(1)} MB`;
	return `${(mb / 1024).toFixed(1)} GB`;
}
function promptConfirm(message) {
	return new Promise((resolve) => {
		const rl = readline$1.createInterface({
			input: process.stdin,
			output: process.stdout
		});
		rl.question(`${message} [y/N] `, (answer) => {
			rl.close();
			resolve(answer.trim().toLowerCase() === "y");
		});
	});
}

//#endregion
//#region src/cli/commands/templates.commands.list.ts
function registerTemplatesListCommand(parent) {
	parent.command("list").description("List available subagent templates").option("--tag <tag>", "Filter by tag").option("--json", "Output raw JSON", false).action(async (opts) => {
		try {
			const result = await withProgress({
				label: "Gateway templates.list",
				indeterminate: true,
				enabled: !opts.json
			}, async () => await callGateway({
				method: "templates.list",
				params: opts.tag ? { tag: opts.tag } : {},
				timeoutMs: 1e4
			}));
			if (!result) {
				console.error(theme.error("Failed to fetch templates from gateway."));
				process.exitCode = 1;
				return;
			}
			if (opts.json) {
				console.log(JSON.stringify(result, null, 2));
				return;
			}
			const { templates, loadErrors, lastReloadAt } = result;
			if (templates.length === 0) {
				console.log(theme.muted("No templates found."));
				if (loadErrors.length > 0) {
					console.log(theme.warn(`\n${loadErrors.length} load error(s):`));
					for (const err of loadErrors) console.log(`  ${theme.error(err.path)}: ${err.error}`);
				}
				return;
			}
			const nameWidth = Math.max(4, ...templates.map((t) => t.name.length));
			const modelWidth = Math.max(5, ...templates.map((t) => (t.model ?? "").length));
			const sourceWidth = Math.max(6, ...templates.map((t) => shortenPath(t.source).length));
			const tagsWidth = Math.max(4, ...templates.map((t) => (t.tags ?? []).join(", ").length));
			const header = [
				"Name".padEnd(nameWidth),
				"Model".padEnd(modelWidth),
				"Source".padEnd(sourceWidth),
				"Tags".padEnd(tagsWidth)
			].join("  ");
			const separator = [
				"-".repeat(nameWidth),
				"-".repeat(modelWidth),
				"-".repeat(sourceWidth),
				"-".repeat(tagsWidth)
			].join("  ");
			console.log(theme.heading("\nTemplates:\n"));
			console.log(theme.muted(header));
			console.log(theme.muted(separator));
			for (const t of templates) {
				const row = [
					t.name.padEnd(nameWidth),
					(t.model ?? theme.muted("(none)")).padEnd(modelWidth),
					shortenPath(t.source).padEnd(sourceWidth),
					(t.tags ?? []).join(", ").padEnd(tagsWidth)
				].join("  ");
				console.log(row);
			}
			console.log(theme.muted(`\n${templates.length} template(s) loaded.`));
			if (loadErrors.length > 0) {
				console.log(theme.warn(`\n${loadErrors.length} load error(s):`));
				for (const err of loadErrors) console.log(`  ${theme.error(err.path)}: ${err.error}`);
			}
			if (lastReloadAt) {
				const ago = Math.round((Date.now() - lastReloadAt) / 1e3);
				console.log(theme.muted(`Last reload: ${ago}s ago`));
			}
		} catch (err) {
			console.error(theme.error(`Failed to connect to gateway: ${err instanceof Error ? err.message : String(err)}`));
			process.exitCode = 1;
		}
	});
}
function shortenPath(source) {
	const home = process.env.HOME ?? process.env.USERPROFILE ?? "";
	if (home && source.startsWith(home)) return `~${source.slice(home.length)}`;
	return source;
}

//#endregion
//#region src/cli/commands/templates.commands.get.ts
function registerTemplatesGetCommand(parent) {
	parent.command("get <name>").description("Show full resolved detail for a template").option("--json", "Output full JSON", false).action(async (name, opts) => {
		try {
			const result = await withProgress({
				label: "Gateway templates.get",
				indeterminate: true,
				enabled: !opts.json
			}, async () => await callGateway({
				method: "templates.get",
				params: { name },
				timeoutMs: 1e4
			}));
			if (!result?.template) {
				console.error(theme.error(`Template not found: ${name}`));
				process.exitCode = 1;
				return;
			}
			if (opts.json) {
				console.log(JSON.stringify(result, null, 2));
				return;
			}
			const t = result.template;
			console.log(theme.heading(`\nTemplate: ${t.name}\n`));
			console.log(`  ${theme.muted("Description:")}  ${t.description}`);
			console.log(`  ${theme.muted("Version:")}      ${t.version}`);
			console.log(`  ${theme.muted("Source:")}       ${t.source}`);
			if (t.icon) console.log(`  ${theme.muted("Icon:")}         ${t.icon}`);
			if (t.color) console.log(`  ${theme.muted("Color:")}        ${t.color}`);
			if (t.tags?.length) console.log(`  ${theme.muted("Tags:")}         ${t.tags.join(", ")}`);
			const modelStr = formatModel(t.model);
			if (modelStr) console.log(`  ${theme.muted("Model:")}        ${modelStr}`);
			if (t.thinking) console.log(`  ${theme.muted("Thinking:")}     ${t.thinking}`);
			if (t.tools) {
				if (t.tools.allow?.length) console.log(`  ${theme.muted("Tools allow:")}  ${t.tools.allow.join(", ")}`);
				if (t.tools.deny?.length) console.log(`  ${theme.muted("Tools deny:")}   ${t.tools.deny.join(", ")}`);
			}
			if (t.skills?.length) console.log(`  ${theme.muted("Skills:")}       ${t.skills.join(", ")}`);
			if (t.runtime) {
				const parts = [];
				if (t.runtime.timeoutSeconds != null) parts.push(`timeout=${t.runtime.timeoutSeconds}s`);
				if (t.runtime.cleanup) parts.push(`cleanup=${t.runtime.cleanup}`);
				if (t.runtime.maxSpawnDepth != null) parts.push(`maxDepth=${t.runtime.maxSpawnDepth}`);
				if (parts.length > 0) console.log(`  ${theme.muted("Runtime:")}      ${parts.join(", ")}`);
			}
			if (t.resolvedFrom && t.resolvedFrom.length > 0) console.log(`  ${theme.muted("Resolved from:")} ${t.resolvedFrom.join(" -> ")}`);
			if (t.systemPrompt) {
				const lines = t.systemPrompt.split("\n");
				const MAX_LINES = 5;
				const excerpt = lines.slice(0, MAX_LINES);
				console.log(`\n  ${theme.muted("System Prompt:")}`);
				for (const line of excerpt) console.log(`    ${line}`);
				if (lines.length > MAX_LINES) console.log(theme.muted(`    ... (${lines.length - MAX_LINES} more lines)`));
			}
			console.log("");
		} catch (err) {
			const msg = err instanceof Error ? err.message : String(err);
			if (msg.includes("template not found")) console.error(theme.error(msg));
			else console.error(theme.error(`Failed to connect to gateway: ${msg}`));
			process.exitCode = 1;
		}
	});
}
function formatModel(model) {
	if (typeof model === "string") return model;
	if (model && typeof model === "object" && "primary" in model) {
		const parts = [model.primary];
		if (model.fallbacks?.length) parts.push(`(fallbacks: ${model.fallbacks.join(", ")})`);
		return parts.join(" ");
	}
	return null;
}

//#endregion
//#region src/cli/commands/templates.commands.validate.ts
function registerTemplatesValidateCommand(parent) {
	parent.command("validate <path>").description("Validate a YAML template file (offline)").option("--live", "Also check for name conflicts against the gateway", false).option("--fix", "Suggest migration for old template versions", false).action(async (filePath, opts) => {
		if (!fs.existsSync(filePath)) {
			console.error(theme.error(`File not found: ${filePath}`));
			process.exitCode = 1;
			return;
		}
		let content;
		try {
			content = fs.readFileSync(filePath, "utf-8");
		} catch (err) {
			console.error(theme.error(`Failed to read file: ${err instanceof Error ? err.message : String(err)}`));
			process.exitCode = 1;
			return;
		}
		let raw;
		try {
			raw = parse(content);
		} catch (err) {
			console.error(theme.error(`YAML parse error: ${err instanceof Error ? err.message : String(err)}`));
			process.exitCode = 1;
			return;
		}
		const result = validateTemplate(raw);
		if (result.valid) {
			console.log(theme.success("PASS") + ` ${filePath}`);
			if (result.warnings.length > 0) {
				console.log(theme.warn(`\n${result.warnings.length} warning(s):`));
				for (const w of result.warnings) console.log(`  ${theme.warn("!")} ${w}`);
			}
			if (opts.fix && result.template) console.log(theme.muted("\nTemplate is at the latest version (v1). No fixes needed."));
			if (opts.live && result.template) try {
				const listResult = await callGateway({
					method: "templates.list",
					params: {},
					timeoutMs: 1e4
				});
				if (listResult?.templates) if (listResult.templates.find((t) => t.name === result.template.name)) console.log(theme.warn(`\nName conflict: template "${result.template.name}" already exists in the gateway.`));
				else console.log(theme.muted(`\nNo name conflicts found (name "${result.template.name}" is available).`));
			} catch {
				console.log(theme.muted("\nCould not connect to gateway for live conflict check."));
			}
		} else {
			console.error(theme.error("FAIL") + ` ${filePath}`);
			console.error(`\n${result.errors.length} error(s):`);
			for (const e of result.errors) console.error(`  ${theme.error("x")} ${e}`);
			if (result.warnings.length > 0) {
				console.log(`\n${result.warnings.length} warning(s):`);
				for (const w of result.warnings) console.log(`  ${theme.warn("!")} ${w}`);
			}
			process.exitCode = 1;
		}
	});
}

//#endregion
//#region src/cli/commands/templates.commands.create.ts
const SCAFFOLD_TEMPLATE = (name, opts) => `\
version: 1
name: ${name}
description: ${opts.description || "A custom subagent template"}

model: ${opts.model || "anthropic/claude-sonnet-4-6"}
thinking: medium

runtime:
  timeoutSeconds: ${opts.timeout || "300"}
  cleanup: delete

systemPrompt: |
  You are a specialized subagent. Follow the task instructions carefully.

  **Task:** {{task}}
`;
function registerTemplatesCreateCommand(parent) {
	parent.command("create <name>").description("Scaffold a new YAML template file").option("--model <model>", "Model id for the template").option("--description <text>", "Template description").option("--timeout <seconds>", "Runtime timeout in seconds").option("--force", "Overwrite existing file", false).action(async (name, opts) => {
		const stateDir = resolveStateDir();
		const templatesDir = path.join(stateDir, "templates");
		const filePath = path.join(templatesDir, `${name}.yaml`);
		if (!fs.existsSync(templatesDir)) try {
			fs.mkdirSync(templatesDir, { recursive: true });
		} catch (err) {
			console.error(theme.error(`Failed to create templates directory: ${err instanceof Error ? err.message : String(err)}`));
			process.exitCode = 1;
			return;
		}
		if (fs.existsSync(filePath) && !opts.force) {
			console.error(theme.error(`Template already exists: ${filePath}\nUse --force to overwrite.`));
			process.exitCode = 1;
			return;
		}
		const content = SCAFFOLD_TEMPLATE(name, {
			model: opts.model,
			description: opts.description,
			timeout: opts.timeout
		});
		try {
			fs.writeFileSync(filePath, content, "utf-8");
			console.log(theme.success("Created") + ` ${filePath}`);
			console.log(theme.muted("\nEdit the file to customize your template."));
			console.log(theme.muted(`Validate with: minion templates validate ${filePath}`));
		} catch (err) {
			console.error(theme.error(`Failed to write template: ${err instanceof Error ? err.message : String(err)}`));
			process.exitCode = 1;
		}
	});
}

//#endregion
//#region src/cli/program/register.agent.ts
function registerAgentCommands(program, args) {
	program.command("agent").description("Run an agent turn via the Gateway (use --local for embedded)").requiredOption("-m, --message <text>", "Message body for the agent").option("-t, --to <number>", "Recipient number in E.164 used to derive the session key").option("--session-id <id>", "Use an explicit session id").option("--agent <id>", "Agent id (overrides routing bindings)").option("--workspace-id <id>", "Named workspace for context switching").option("--thinking <level>", "Thinking level: off | minimal | low | medium | high").option("--verbose <on|off>", "Persist agent verbose level for the session").option("--channel <channel>", `Delivery channel: ${args.agentChannelOptions} (default: ${DEFAULT_CHAT_CHANNEL})`).option("--reply-to <target>", "Delivery target override (separate from session routing)").option("--reply-channel <channel>", "Delivery channel override (separate from routing)").option("--reply-account <id>", "Delivery account id override").option("--local", "Run the embedded agent locally (requires model provider API keys in your shell)", false).option("--deliver", "Send the agent's reply back to the selected channel", false).option("--json", "Output result as JSON", false).option("--timeout <seconds>", "Override agent command timeout (seconds, default 600 or config value)").addHelpText("after", () => `
${theme.heading("Examples:")}
${formatHelpExamples([
		["minion agent --to +15555550123 --message \"status update\"", "Start a new session."],
		["minion agent --agent ops --message \"Summarize logs\"", "Use a specific agent."],
		["minion agent --session-id 1234 --message \"Summarize inbox\" --thinking medium", "Target a session with explicit thinking level."],
		["minion agent --to +15555550123 --message \"Trace logs\" --verbose on --json", "Enable verbose logging and JSON output."],
		["minion agent --to +15555550123 --message \"Summon reply\" --deliver", "Deliver reply."],
		["minion agent --agent ops --message \"Generate report\" --deliver --reply-channel slack --reply-to \"#reports\"", "Send reply to a different channel/target."]
	])}

${theme.muted("Docs:")} ${formatDocsLink("/cli/agent", "docs.minion.ai/cli/agent")}`).action(async (opts) => {
		setVerbose((typeof opts.verbose === "string" ? opts.verbose.toLowerCase() : "") === "on");
		const deps = createDefaultDeps();
		await runCommandWithRuntime(defaultRuntime, async () => {
			await agentCliCommand(opts, defaultRuntime, deps);
		});
	});
	const agents = program.command("agents").description("Manage isolated agents (workspaces + auth + routing)").addHelpText("after", () => `\n${theme.muted("Docs:")} ${formatDocsLink("/cli/agents", "docs.minion.ai/cli/agents")}\n`);
	agents.command("list").description("List configured agents").option("--json", "Output JSON instead of text", false).option("--bindings", "Include routing bindings", false).action(async (opts) => {
		await runCommandWithRuntime(defaultRuntime, async () => {
			await agentsListCommand({
				json: Boolean(opts.json),
				bindings: Boolean(opts.bindings)
			}, defaultRuntime);
		});
	});
	agents.command("add [name]").description("Add a new isolated agent").option("--workspace <dir>", "Workspace directory for the new agent").option("--model <id>", "Model id for this agent").option("--agent-dir <dir>", "Agent state directory for this agent").option("--bind <channel[:accountId]>", "Route channel binding (repeatable)", collectOption, []).option("--non-interactive", "Disable prompts; requires --workspace", false).option("--json", "Output JSON summary", false).action(async (name, opts, command) => {
		await runCommandWithRuntime(defaultRuntime, async () => {
			const hasFlags = hasExplicitOptions(command, [
				"workspace",
				"model",
				"agentDir",
				"bind",
				"nonInteractive"
			]);
			await agentsAddCommand({
				name: typeof name === "string" ? name : void 0,
				workspace: opts.workspace,
				model: opts.model,
				agentDir: opts.agentDir,
				bind: Array.isArray(opts.bind) ? opts.bind : void 0,
				nonInteractive: Boolean(opts.nonInteractive),
				json: Boolean(opts.json)
			}, defaultRuntime, { hasFlags });
		});
	});
	agents.command("set-identity").description("Update an agent identity (name/theme/emoji/avatar)").option("--agent <id>", "Agent id to update").option("--workspace <dir>", "Workspace directory used to locate the agent + IDENTITY.md").option("--identity-file <path>", "Explicit IDENTITY.md path to read").option("--from-identity", "Read values from IDENTITY.md", false).option("--name <name>", "Identity name").option("--theme <theme>", "Identity theme").option("--emoji <emoji>", "Identity emoji").option("--avatar <value>", "Identity avatar (workspace path, http(s) URL, or data URI)").option("--json", "Output JSON summary", false).addHelpText("after", () => `
${theme.heading("Examples:")}
${formatHelpExamples([
		["minion agents set-identity --agent main --name \"Minion\" --emoji \"🦑\"", "Set name + emoji."],
		["minion agents set-identity --agent main --avatar avatars/minion.png", "Set avatar path."],
		["minion agents set-identity --workspace ~/.minion/workspace --from-identity", "Load from IDENTITY.md."],
		["minion agents set-identity --identity-file ~/.minion/workspace/IDENTITY.md --agent main", "Use a specific IDENTITY.md."]
	])}
`).action(async (opts) => {
		await runCommandWithRuntime(defaultRuntime, async () => {
			await agentsSetIdentityCommand({
				agent: opts.agent,
				workspace: opts.workspace,
				identityFile: opts.identityFile,
				fromIdentity: Boolean(opts.fromIdentity),
				name: opts.name,
				theme: opts.theme,
				emoji: opts.emoji,
				avatar: opts.avatar,
				json: Boolean(opts.json)
			}, defaultRuntime);
		});
	});
	agents.command("delete <id>").description("Delete an agent and prune workspace/state").option("--force", "Skip confirmation", false).option("--json", "Output JSON summary", false).action(async (id, opts) => {
		await runCommandWithRuntime(defaultRuntime, async () => {
			await agentsDeleteCommand({
				id: String(id),
				force: Boolean(opts.force),
				json: Boolean(opts.json)
			}, defaultRuntime);
		});
	});
	agents.action(async () => {
		await runCommandWithRuntime(defaultRuntime, async () => {
			await agentsListCommand({}, defaultRuntime);
		});
	});
	const templatesCmd = program.command("templates").description("Manage subagent templates");
	registerTemplatesListCommand(templatesCmd);
	registerTemplatesGetCommand(templatesCmd);
	registerTemplatesValidateCommand(templatesCmd);
	registerTemplatesCreateCommand(templatesCmd);
	const orchestrationsCmd = program.command("orchestrations").description("Manage multi-agent orchestrations");
	registerOrchestrationsListCommand(orchestrationsCmd);
	registerOrchestrationsGetCommand(orchestrationsCmd);
	registerOrchestrationsInspectCommand(orchestrationsCmd);
	registerOrchestrationsCleanupCommand(orchestrationsCmd);
}

//#endregion
export { registerAgentCommands };