import "./paths-C9FmTW1x.js";
import { M as info, T as shortenHomePath, U as theme, j as danger } from "./agent-paths-BySKyq9I.js";
import { Dn as loadConfig, d as resolveDefaultAgentId, dd as formatCliCommand, u as resolveAgentWorkspaceDir } from "./agent-scope-CLn_Ws3B.js";
import { d as defaultRuntime } from "./errors-Dx3S3Nrp.js";
import "./github-copilot-token-BA45-q56.js";
import "./chat-envelope-D_wSv26N.js";
import "./pairing-token-BFGorDQo.js";
import "./path-alias-guards-DivKBvV8.js";
import "./skills-D1Qdj69-.js";
import { c as formatArchiveScanFindings, l as formatMarketplacePermissionSummary, n as previewSkillInstallFromClawHub, r as previewSkillsUpdateFromClawHub, s as updateSkillsFromClawHub, t as installSkillFromClawHub } from "./skills-clawhub-kuGAFKgL.js";
import "./config-eval-CuVkTCse.js";
import { t as formatDocsLink } from "./links-BeUKckiL.js";
import { t as getRemoteSkillEligibility } from "./skills-remote-DkdYN-8J.js";
import { t as renderTable } from "./table-DEEHcEaS.js";
import { i as runSkillsWalletGrant, o as runSkillsMarketplaceInspect, s as runSkillsMarketplaceList } from "./skills-wallet-grant-Bt47-Hrw.js";

//#region src/cli/skills-cli.format.ts
function appendClawHubHint(output, json) {
	if (json) return output;
	return `${output}\n\nTip: use \`fased skills marketplace install <slug>\` to install skills and \`fased skills marketplace update --dry-run\` to preview updates.`;
}
function formatSkillStatus(skill) {
	if (skill.eligible) return theme.success("✓ ready");
	if (skill.disabled) return theme.warn("⏸ disabled");
	if (skill.blockedByAllowlist) return theme.warn("🚫 blocked");
	return theme.error("✗ missing");
}
function formatSkillName(skill) {
	return `${skill.emoji ?? "📦"} ${theme.command(skill.name)}`;
}
function formatSkillMissingSummary(skill) {
	const missing = [];
	if (skill.missing.bins.length > 0) missing.push(`bins: ${skill.missing.bins.join(", ")}`);
	if (skill.missing.anyBins.length > 0) missing.push(`anyBins: ${skill.missing.anyBins.join(", ")}`);
	if (skill.missing.env.length > 0) missing.push(`env: ${skill.missing.env.join(", ")}`);
	if (skill.missing.config.length > 0) missing.push(`config: ${skill.missing.config.join(", ")}`);
	if (skill.missing.os.length > 0) missing.push(`os: ${skill.missing.os.join(", ")}`);
	return missing.join("; ");
}
function formatSkillsList(report, opts) {
	const skills = opts.eligible ? report.skills.filter((s) => s.eligible) : report.skills;
	if (opts.json) {
		const jsonReport = {
			workspaceDir: report.workspaceDir,
			managedSkillsDir: report.managedSkillsDir,
			skills: skills.map((s) => ({
				name: s.name,
				description: s.description,
				emoji: s.emoji,
				eligible: s.eligible,
				disabled: s.disabled,
				blockedByAllowlist: s.blockedByAllowlist,
				source: s.source,
				bundled: s.bundled,
				primaryEnv: s.primaryEnv,
				homepage: s.homepage,
				missing: s.missing
			}))
		};
		return JSON.stringify(jsonReport, null, 2);
	}
	if (skills.length === 0) return appendClawHubHint(opts.eligible ? `No eligible skills found. Run \`${formatCliCommand("fased skills list")}\` to see all skills.` : "No skills found.", opts.json);
	const eligible = skills.filter((s) => s.eligible);
	const tableWidth = Math.max(60, (process.stdout.columns ?? 120) - 1);
	const rows = skills.map((skill) => {
		const missing = formatSkillMissingSummary(skill);
		return {
			Status: formatSkillStatus(skill),
			Skill: formatSkillName(skill),
			Description: theme.muted(skill.description),
			Source: skill.source ?? "",
			Missing: missing ? theme.warn(missing) : ""
		};
	});
	const columns = [
		{
			key: "Status",
			header: "Status",
			minWidth: 10
		},
		{
			key: "Skill",
			header: "Skill",
			minWidth: 18,
			flex: true
		},
		{
			key: "Description",
			header: "Description",
			minWidth: 24,
			flex: true
		},
		{
			key: "Source",
			header: "Source",
			minWidth: 10
		}
	];
	if (opts.verbose) columns.push({
		key: "Missing",
		header: "Missing",
		minWidth: 18,
		flex: true
	});
	const lines = [];
	lines.push(`${theme.heading("Skills")} ${theme.muted(`(${eligible.length}/${skills.length} ready)`)}`);
	lines.push(renderTable({
		width: tableWidth,
		columns,
		rows
	}).trimEnd());
	return appendClawHubHint(lines.join("\n"), opts.json);
}
function formatSkillInfo(report, skillName, opts) {
	const skill = report.skills.find((s) => s.name === skillName || s.skillKey === skillName);
	if (!skill) {
		if (opts.json) return JSON.stringify({
			error: "not found",
			skill: skillName
		}, null, 2);
		return appendClawHubHint(`Skill "${skillName}" not found. Run \`${formatCliCommand("fased skills list")}\` to see available skills.`, opts.json);
	}
	if (opts.json) return JSON.stringify(skill, null, 2);
	const lines = [];
	const emoji = skill.emoji ?? "📦";
	const status = skill.eligible ? theme.success("✓ Ready") : skill.disabled ? theme.warn("⏸ Disabled") : skill.blockedByAllowlist ? theme.warn("🚫 Blocked by allowlist") : theme.error("✗ Missing requirements");
	lines.push(`${emoji} ${theme.heading(skill.name)} ${status}`);
	lines.push("");
	lines.push(skill.description);
	lines.push("");
	lines.push(theme.heading("Details:"));
	lines.push(`${theme.muted("  Source:")} ${skill.source}`);
	lines.push(`${theme.muted("  Path:")} ${shortenHomePath(skill.filePath)}`);
	if (skill.homepage) lines.push(`${theme.muted("  Homepage:")} ${skill.homepage}`);
	if (skill.primaryEnv) lines.push(`${theme.muted("  Primary env:")} ${skill.primaryEnv}`);
	if (skill.requirements.bins.length > 0 || skill.requirements.anyBins.length > 0 || skill.requirements.env.length > 0 || skill.requirements.config.length > 0 || skill.requirements.os.length > 0) {
		lines.push("");
		lines.push(theme.heading("Requirements:"));
		if (skill.requirements.bins.length > 0) {
			const binsStatus = skill.requirements.bins.map((bin) => {
				return skill.missing.bins.includes(bin) ? theme.error(`✗ ${bin}`) : theme.success(`✓ ${bin}`);
			});
			lines.push(`${theme.muted("  Binaries:")} ${binsStatus.join(", ")}`);
		}
		if (skill.requirements.anyBins.length > 0) {
			const anyBinsMissing = skill.missing.anyBins.length > 0;
			const anyBinsStatus = skill.requirements.anyBins.map((bin) => {
				return anyBinsMissing ? theme.error(`✗ ${bin}`) : theme.success(`✓ ${bin}`);
			});
			lines.push(`${theme.muted("  Any binaries:")} ${anyBinsStatus.join(", ")}`);
		}
		if (skill.requirements.env.length > 0) {
			const envStatus = skill.requirements.env.map((env) => {
				return skill.missing.env.includes(env) ? theme.error(`✗ ${env}`) : theme.success(`✓ ${env}`);
			});
			lines.push(`${theme.muted("  Environment:")} ${envStatus.join(", ")}`);
		}
		if (skill.requirements.config.length > 0) {
			const configStatus = skill.requirements.config.map((cfg) => {
				return skill.missing.config.includes(cfg) ? theme.error(`✗ ${cfg}`) : theme.success(`✓ ${cfg}`);
			});
			lines.push(`${theme.muted("  Config:")} ${configStatus.join(", ")}`);
		}
		if (skill.requirements.os.length > 0) {
			const osStatus = skill.requirements.os.map((osName) => {
				return skill.missing.os.includes(osName) ? theme.error(`✗ ${osName}`) : theme.success(`✓ ${osName}`);
			});
			lines.push(`${theme.muted("  OS:")} ${osStatus.join(", ")}`);
		}
	}
	if (skill.install.length > 0 && !skill.eligible) {
		lines.push("");
		lines.push(theme.heading("Install options:"));
		for (const inst of skill.install) lines.push(`  ${theme.warn("→")} ${inst.label}`);
	}
	return appendClawHubHint(lines.join("\n"), opts.json);
}
function formatSkillsCheck(report, opts) {
	const eligible = report.skills.filter((s) => s.eligible);
	const disabled = report.skills.filter((s) => s.disabled);
	const blocked = report.skills.filter((s) => s.blockedByAllowlist && !s.disabled);
	const missingReqs = report.skills.filter((s) => !s.eligible && !s.disabled && !s.blockedByAllowlist);
	if (opts.json) return JSON.stringify({
		summary: {
			total: report.skills.length,
			eligible: eligible.length,
			disabled: disabled.length,
			blocked: blocked.length,
			missingRequirements: missingReqs.length
		},
		eligible: eligible.map((s) => s.name),
		disabled: disabled.map((s) => s.name),
		blocked: blocked.map((s) => s.name),
		missingRequirements: missingReqs.map((s) => ({
			name: s.name,
			missing: s.missing,
			install: s.install
		}))
	}, null, 2);
	const lines = [];
	lines.push(theme.heading("Skills Status Check"));
	lines.push("");
	lines.push(`${theme.muted("Total:")} ${report.skills.length}`);
	lines.push(`${theme.success("✓")} ${theme.muted("Eligible:")} ${eligible.length}`);
	lines.push(`${theme.warn("⏸")} ${theme.muted("Disabled:")} ${disabled.length}`);
	lines.push(`${theme.warn("🚫")} ${theme.muted("Blocked by allowlist:")} ${blocked.length}`);
	lines.push(`${theme.error("✗")} ${theme.muted("Missing requirements:")} ${missingReqs.length}`);
	if (eligible.length > 0) {
		lines.push("");
		lines.push(theme.heading("Ready to use:"));
		for (const skill of eligible) {
			const emoji = skill.emoji ?? "📦";
			lines.push(`  ${emoji} ${skill.name}`);
		}
	}
	if (missingReqs.length > 0) {
		lines.push("");
		lines.push(theme.heading("Missing requirements:"));
		for (const skill of missingReqs) {
			const emoji = skill.emoji ?? "📦";
			const missing = formatSkillMissingSummary(skill);
			lines.push(`  ${emoji} ${skill.name} ${theme.muted(`(${missing})`)}`);
		}
	}
	return appendClawHubHint(lines.join("\n"), opts.json);
}

//#endregion
//#region src/cli/skills-marketplace-actions.ts
function readMarketplaceAllowRegistries(config) {
	return config.skills?.marketplace?.allowRegistries;
}
function formatInstallResult(result, opts = {}) {
	if (!result.ok) return `${opts.dryRun ? "Install preview" : "Install"} failed: ${result.error}`;
	const review = result.updateReview.approvalRequired ? `approval required: ${result.updateReview.reasons.join(", ")}` : "approval required: no";
	return [
		`${opts.dryRun ? "Install preview" : "Installed"} ${result.slug}@${result.version}`,
		`Target: ${result.targetDir}`,
		`Review: ${review}`,
		`Permissions: ${formatMarketplacePermissionSummary(result.permissions)}`,
		`Archive: ${formatArchiveScanFindings(result.installScan)}`
	].join("\n");
}
function formatUpdateReview(result) {
	if (!result.ok) return `Update failed: ${result.error}`;
	const review = result.updateReview.approvalRequired ? `approval required: ${result.updateReview.reasons.join(", ")}` : "approval required: no";
	const addedWarnings = result.updateReview.addedScanFindings.length > 0 ? result.updateReview.addedScanFindings.map((finding) => `${finding.code} at ${finding.path}`).join(", ") : "none";
	const addedPermissions = (result.updateReview.permissionDiff?.added ?? []).length > 0 ? (result.updateReview.permissionDiff?.added ?? []).join(", ") : "none";
	const removedPermissions = (result.updateReview.permissionDiff?.removed ?? []).length > 0 ? (result.updateReview.permissionDiff?.removed ?? []).join(", ") : "none";
	return [
		`${result.slug}: ${result.previousVersion ?? "unknown"} -> ${result.version}${result.changed ? "" : " (unchanged)"}`,
		`  ${review}`,
		`  Permissions: ${formatMarketplacePermissionSummary(result.permissions)}`,
		`  Added permissions: ${addedPermissions}`,
		`  Removed permissions: ${removedPermissions}`,
		`  Archive: ${formatArchiveScanFindings(result.installScan)}`,
		`  New scan warnings: ${addedWarnings}`
	].join("\n");
}
function hasFailures(results) {
	return results.some((result) => !result.ok);
}
async function runSkillsMarketplaceInstall(params) {
	const runtime = params.runtime ?? defaultRuntime;
	try {
		const config = loadConfig();
		const common = {
			workspaceDir: resolveAgentWorkspaceDir(config, resolveDefaultAgentId(config)),
			slug: params.slug,
			version: params.opts.version,
			baseUrl: params.opts.registry,
			allowRegistries: readMarketplaceAllowRegistries(config),
			logger: params.opts.json ? void 0 : { info: (message) => runtime.log(info(message)) }
		};
		const result = params.opts.dryRun === true ? await previewSkillInstallFromClawHub(common) : await installSkillFromClawHub({
			...common,
			allowPermissionChanges: params.opts.approvePermissionChange === true,
			force: params.opts.force === true
		});
		runtime.log(params.opts.json ? JSON.stringify(params.opts.dryRun === true ? {
			dryRun: true,
			result
		} : result, null, 2) : formatInstallResult(result, { dryRun: params.opts.dryRun === true }));
		if (!result.ok) runtime.exit(1);
	} catch (err) {
		runtime.error(danger(String(err)));
		runtime.exit(1);
	}
}
async function runSkillsMarketplaceUpdate(params) {
	const runtime = params.runtime ?? defaultRuntime;
	try {
		const config = loadConfig();
		const common = {
			workspaceDir: resolveAgentWorkspaceDir(config, resolveDefaultAgentId(config)),
			slug: params.slug,
			baseUrl: params.opts.registry,
			allowRegistries: readMarketplaceAllowRegistries(config),
			logger: params.opts.json ? void 0 : { info: (message) => runtime.log(info(message)) }
		};
		const results = params.opts.dryRun === true ? await previewSkillsUpdateFromClawHub(common) : await updateSkillsFromClawHub({
			...common,
			allowPermissionChanges: params.opts.approvePermissionChange === true
		});
		runtime.log(params.opts.json ? JSON.stringify({
			dryRun: params.opts.dryRun === true,
			results
		}, null, 2) : results.map((result) => formatUpdateReview(result)).join("\n\n"));
		if (hasFailures(results)) runtime.exit(1);
	} catch (err) {
		runtime.error(danger(String(err)));
		runtime.exit(1);
	}
}

//#endregion
//#region src/cli/skills-cli.ts
async function loadSkillsStatusReport() {
	const config = loadConfig();
	const workspaceDir = resolveAgentWorkspaceDir(config, resolveDefaultAgentId(config));
	const { buildWorkspaceSkillStatus } = await import("./skills-status-Bgumcv_3.js").then((n) => n.n);
	return buildWorkspaceSkillStatus(workspaceDir, {
		config,
		eligibility: { remote: getRemoteSkillEligibility() }
	});
}
async function runSkillsAction(render) {
	try {
		const report = await loadSkillsStatusReport();
		defaultRuntime.log(render(report));
	} catch (err) {
		defaultRuntime.error(String(err));
		defaultRuntime.exit(1);
	}
}
/**
* Register the skills CLI commands
*/
function registerSkillsCli(program) {
	const skills = program.command("skills").description("List and inspect available skills").addHelpText("after", () => `\n${theme.muted("Docs:")} ${formatDocsLink("/cli/skills", "docs.fased.ai/cli/skills")}\n`);
	skills.command("list").description("List all available skills").option("--json", "Output as JSON", false).option("--eligible", "Show only eligible (ready to use) skills", false).option("-v, --verbose", "Show more details including missing requirements", false).action(async (opts) => {
		await runSkillsAction((report) => formatSkillsList(report, opts));
	});
	skills.command("inspect").description("Inspect a skill, including marketplace source and permissions when tracked").argument("<name>", "Skill name").option("--json", "Output as JSON", false).action(async (name, opts) => {
		await runSkillsAction((report) => formatSkillInfo(report, name, opts));
	});
	skills.command("permissions").description("Show marketplace source, requested permissions, grants, and update review").argument("<skill-id>", "Skill id").option("--json", "Output JSON", false).action(async (skillId, opts) => {
		await runSkillsMarketplaceInspect({
			skillId,
			opts
		});
	});
	skills.command("info").description("Show detailed information about a skill").argument("<name>", "Skill name").option("--json", "Output as JSON", false).action(async (name, opts) => {
		await runSkillsAction((report) => formatSkillInfo(report, name, opts));
	});
	skills.command("check").description("Check which skills are ready vs missing requirements").option("--json", "Output as JSON", false).action(async (opts) => {
		await runSkillsAction((report) => formatSkillsCheck(report, opts));
	});
	const wallet = skills.command("wallet").description("Manage skill wallet-action permissions");
	const marketplace = skills.command("marketplace").description("Inspect installed marketplace skill sources and permissions");
	marketplace.command("list").description("List tracked ClawHub skills, requested permissions, and wallet grants").option("--json", "Output JSON", false).action(async (opts) => {
		await runSkillsMarketplaceList({ opts });
	});
	marketplace.command("install").description("Install a skill from ClawHub with Fased marketplace safety checks").argument("<slug>", "ClawHub skill slug").option("--version <version>", "Install a specific ClawHub skill version").option("--registry <url>", "ClawHub registry URL", void 0).option("--force", "Replace an existing installed skill", false).option("--dry-run", "Preview install permission review without installing", false).option("--approve-permission-change", "Explicitly approve risky permission changes when --force updates an existing skill", false).option("--json", "Output JSON", false).action(async (slug, opts) => {
		await runSkillsMarketplaceInstall({
			slug,
			opts
		});
	});
	marketplace.command("update").description("Update tracked ClawHub skills with permission-review enforcement").argument("[slug]", "Optional tracked ClawHub skill slug").option("--registry <url>", "ClawHub registry URL for legacy lockfile-only entries", void 0).option("--dry-run", "Preview update permission review without installing", false).option("--approve-permission-change", "Explicitly approve risky permission changes", false).option("--json", "Output JSON", false).action(async (slug, opts) => {
		await runSkillsMarketplaceUpdate({
			slug,
			opts
		});
	});
	wallet.command("grant").description("Grant a skill narrow wallet-action permissions").argument("<skill-id>", "Skill id").option("--actions <list>", "Comma-separated wallet actions such as quote,swap,schedule_plan,schedule_send").option("--action <name>", "Wallet action to allow; repeatable", (value, previous) => [...previous, value], []).option("--registry <url>", "Allowed ClawHub registry origin; repeatable", (value, previous) => [...previous, value], []).option("--role <role>", "Wallet role to allow; only agent is supported", "agent").option("--wallet-id <id>", "Agent wallet id this skill may use; repeatable", (value, previous) => [...previous, value], []).option("--chain <chain>", "Wallet chain to allow; repeatable or comma-separated", (value, previous) => [...previous, value], []).option("--input-mint <mint>", "Allowed input mint; repeatable", (value, previous) => [...previous, value], []).option("--output-mint <mint>", "Allowed output mint; repeatable", (value, previous) => [...previous, value], []).option("--max-amount <base-units>", "Maximum input amount in base units").option("--max-slippage-bps <bps>", "Maximum slippage in basis points").option("--autonomous", "Allow autonomous execution", false).option("--cron", "Allow scheduled wallet-action plans", false).option("--dry-run", "Print/write nothing; use with --json to preview", false).option("--json", "Output JSON", false).action(async (skillId, opts) => {
		await runSkillsWalletGrant({
			skillId,
			opts
		});
	});
	skills.action(async () => {
		await runSkillsAction((report) => formatSkillsList(report, {}));
	});
}

//#endregion
export { registerSkillsCli };