import { M as info, j as danger } from "./agent-paths-BySKyq9I.js";
import { An as readConfigFileSnapshotForWrite, Dn as loadConfig, Mn as writeConfigFile, d as resolveDefaultAgentId, u as resolveAgentWorkspaceDir } from "./agent-scope-CLn_Ws3B.js";
import { d as defaultRuntime } from "./errors-Dx3S3Nrp.js";
import { a as readTrackedClawHubSkillSlugs, c as formatArchiveScanFindings, i as readClawHubSkillOrigin, l as formatMarketplacePermissionSummary } from "./skills-clawhub-kuGAFKgL.js";
import path from "node:path";

//#region src/cli/skills-marketplace-list.ts
function readGrantedWalletActions(cfg, skillId) {
	const raw = cfg.skills?.entries?.[skillId]?.config?.walletActions;
	return raw && typeof raw === "object" && !Array.isArray(raw) ? raw : null;
}
function summarizeGrant(grant) {
	if (!grant) return "grant: none";
	return `grant: ${Array.isArray(grant.actions) ? grant.actions.join(",") : "unspecified"}; autonomous: ${grant.autonomous === true ? "yes" : "no"}; cron: ${grant.cron === true ? "yes" : "no"}`;
}
async function readOrigin(workspaceDir, skillId) {
	return await readClawHubSkillOrigin(path.join(workspaceDir, "skills", skillId));
}
async function buildSkillsMarketplaceRows(params) {
	const slugs = await readTrackedClawHubSkillSlugs(params.workspaceDir);
	const rows = [];
	for (const skillId of slugs) {
		const origin = await readOrigin(params.workspaceDir, skillId);
		const requested = origin?.permissions?.walletActions ?? null;
		const grant = readGrantedWalletActions(params.config, skillId);
		rows.push({
			skillId,
			source: "clawhub",
			registry: origin?.registry ?? null,
			version: origin?.installedVersion ?? null,
			requestedWalletActions: requested,
			requestedToolAccess: origin?.permissions?.toolAccess ?? null,
			requestedInstall: origin?.permissions?.install && typeof origin.permissions.install === "object" ? origin.permissions.install : null,
			requestedPermissionRisky: origin?.permissions?.risky === true,
			requestedPermissionDigest: origin?.permissions?.digest ?? null,
			grantedWalletActions: grant,
			installScan: origin?.installScan ?? null,
			lastUpdateReview: origin?.lastUpdateReview ?? null,
			autonomousRequested: requested?.autonomous === true,
			autonomousGranted: grant?.autonomous === true,
			cronRequested: requested?.cron === true,
			cronGranted: grant?.cron === true
		});
	}
	return rows;
}
function formatMarketplaceRow(row) {
	const requested = formatMarketplacePermissionSummary(row.requestedWalletActions || row.requestedToolAccess || row.requestedInstall ? {
		version: 1,
		...row.requestedWalletActions ? { walletActions: row.requestedWalletActions } : {},
		...row.requestedToolAccess ? { toolAccess: row.requestedToolAccess } : {},
		...row.requestedInstall ? { install: row.requestedInstall } : {},
		risky: row.requestedPermissionRisky,
		digest: row.requestedPermissionDigest ?? ""
	} : void 0);
	const review = row.lastUpdateReview ? row.lastUpdateReview.approvalRequired ? `review: required (${row.lastUpdateReview.reasons.join(", ")})` : "review: clean" : "review: not recorded";
	return [
		row.skillId,
		`  source: ClawHub${row.registry ? ` (${row.registry})` : ""}`,
		`  version: ${row.version ?? "unknown"}`,
		`  scan: ${row.installScan ? formatArchiveScanFindings(row.installScan) : "not recorded"}`,
		`  requested: ${requested}`,
		`  ${summarizeGrant(row.grantedWalletActions)}`,
		`  ${review}`
	].join("\n");
}
function formatMarketplaceRows(rows) {
	if (rows.length === 0) return "No tracked ClawHub skills found.";
	return rows.map((row) => formatMarketplaceRow(row)).join("\n\n");
}
async function runSkillsMarketplaceList(params) {
	const runtime = params.runtime ?? defaultRuntime;
	try {
		const config = loadConfig();
		const rows = await buildSkillsMarketplaceRows({
			workspaceDir: resolveAgentWorkspaceDir(config, resolveDefaultAgentId(config)),
			config
		});
		runtime.log(params.opts.json ? JSON.stringify({ skills: rows }, null, 2) : formatMarketplaceRows(rows));
	} catch (err) {
		runtime.error(danger(String(err)));
		runtime.exit(1);
	}
}
async function runSkillsMarketplaceInspect(params) {
	const runtime = params.runtime ?? defaultRuntime;
	try {
		const config = loadConfig();
		const row = (await buildSkillsMarketplaceRows({
			workspaceDir: resolveAgentWorkspaceDir(config, resolveDefaultAgentId(config)),
			config
		})).find((candidate) => candidate.skillId === params.skillId);
		if (!row) throw new Error(`No tracked ClawHub skill found for "${params.skillId}".`);
		runtime.log(params.opts.json ? JSON.stringify({ skill: row }, null, 2) : formatMarketplaceRow(row));
	} catch (err) {
		runtime.error(danger(String(err)));
		runtime.exit(1);
	}
}

//#endregion
//#region src/cli/skills-wallet-grant.ts
const RISKY_WALLET_ACTIONS = new Set([
	"send",
	"swap",
	"schedule_plan",
	"schedule_send",
	"limit_order"
]);
const VALID_ACTIONS = new Set([
	"prepare",
	"send",
	"plan",
	"quote",
	"swap",
	"schedule_plan",
	"schedule_send",
	"limit_order",
	"limit_cancel",
	"limit_history"
]);
const VALID_CHAINS = new Set(["solana"]);
function splitList(values) {
	const raw = Array.isArray(values) ? values : values ? [values] : [];
	return [...new Set(raw.flatMap((value) => value.split(",")).map((value) => value.trim()).filter(Boolean))];
}
function normalizeRegistryUrl(value) {
	const raw = value.trim();
	if (!raw) throw new Error("registry cannot be empty");
	try {
		const url = new URL(raw);
		url.hash = "";
		url.search = "";
		url.pathname = url.pathname.replace(/\/+$/, "");
		return url.toString().replace(/\/+$/, "");
	} catch {
		return raw.replace(/\/+$/, "");
	}
}
function validateSkillId(skillId) {
	const id = skillId.trim();
	if (!id || id.includes("/") || id.includes("\\") || id.includes("..")) throw new Error(`invalid skill id: ${skillId}`);
	return id;
}
function parseMaxSlippageBps(value) {
	if (value === void 0 || value === "") return;
	const parsed = typeof value === "number" ? value : Number(value);
	if (!Number.isFinite(parsed) || parsed < 0) throw new Error("max slippage bps must be a non-negative number");
	return Math.floor(parsed);
}
function buildWalletActionsGrant(opts) {
	const actions = splitList([...opts.action ?? [], ...splitList(opts.actions)]);
	if (actions.length === 0) throw new Error("at least one wallet action is required");
	for (const action of actions) if (!VALID_ACTIONS.has(action)) throw new Error(`invalid wallet action: ${action}`);
	if ((opts.role?.trim() || "agent") !== "agent") throw new Error("wallet skills can only be granted role=agent");
	const walletIds = splitList(opts.walletId);
	if (walletIds.length === 0) throw new Error("at least one Agent wallet id is required");
	const chains = splitList(opts.chain).length > 0 ? splitList(opts.chain) : ["solana"];
	for (const chain of chains) if (!VALID_CHAINS.has(chain)) throw new Error(`invalid wallet chain: ${chain}`);
	const maxAmount = opts.maxAmount?.trim();
	if (actions.some((action) => RISKY_WALLET_ACTIONS.has(action)) && !maxAmount) throw new Error("max amount is required for send/swap/schedule_plan/schedule_send/limit_order grants");
	return {
		actions,
		roles: ["agent"],
		walletIds,
		chains,
		registries: splitList(opts.registry).map(normalizeRegistryUrl),
		inputMints: splitList(opts.inputMint),
		outputMints: splitList(opts.outputMint),
		maxAmount: maxAmount || void 0,
		maxSlippageBps: parseMaxSlippageBps(opts.maxSlippageBps),
		autonomous: opts.autonomous === true ? true : void 0,
		cron: opts.cron === true ? true : void 0
	};
}
function compactWalletActionsGrant(grant) {
	return Object.fromEntries(Object.entries(grant).filter(([, value]) => {
		if (Array.isArray(value)) return value.length > 0;
		return value !== void 0;
	}));
}
function applySkillWalletGrantConfig(params) {
	const skillId = validateSkillId(params.skillId);
	const next = structuredClone(params.config);
	next.skills = next.skills ?? {};
	next.skills.entries = next.skills.entries ?? {};
	next.skills.entries[skillId] = next.skills.entries[skillId] ?? {};
	const skillEntry = next.skills.entries[skillId];
	skillEntry.config = {
		...skillEntry.config,
		walletActions: compactWalletActionsGrant(params.grant)
	};
	const registries = params.grant.registries ?? [];
	if (registries.length > 0) {
		next.skills.marketplace = next.skills.marketplace ?? {};
		const existing = next.skills.marketplace.allowRegistries ?? [];
		next.skills.marketplace.allowRegistries = [...new Set([...existing, ...registries])];
	}
	return next;
}
function clearSkillWalletGrantConfig(params) {
	const skillId = validateSkillId(params.skillId);
	const next = structuredClone(params.config);
	const skillEntry = next.skills?.entries?.[skillId];
	if (skillEntry?.config && typeof skillEntry.config === "object") delete skillEntry.config.walletActions;
	return next;
}
async function runSkillsWalletGrant(params) {
	const runtime = params.runtime ?? defaultRuntime;
	try {
		const grant = buildWalletActionsGrant(params.opts);
		const writeSnapshot = await readConfigFileSnapshotForWrite();
		if (!writeSnapshot.snapshot.valid) {
			runtime.error(danger(`Config invalid at ${writeSnapshot.snapshot.path}.`));
			for (const issue of writeSnapshot.snapshot.issues) runtime.error(danger(`- ${issue.path || "<root>"}: ${issue.message}`));
			runtime.exit(1);
			return;
		}
		const next = applySkillWalletGrantConfig({
			config: writeSnapshot.snapshot.resolved,
			skillId: params.skillId,
			grant
		});
		if (params.opts.json) runtime.log(JSON.stringify({
			skillId: validateSkillId(params.skillId),
			walletActions: compactWalletActionsGrant(grant),
			dryRun: params.opts.dryRun === true
		}, null, 2));
		if (!params.opts.dryRun) {
			await writeConfigFile(next, writeSnapshot.writeOptions);
			if (!params.opts.json) runtime.log(info(`Granted wallet actions for skill "${validateSkillId(params.skillId)}".`));
		}
	} catch (err) {
		runtime.error(danger(String(err)));
		runtime.exit(1);
	}
}

//#endregion
export { buildSkillsMarketplaceRows as a, runSkillsWalletGrant as i, buildWalletActionsGrant as n, runSkillsMarketplaceInspect as o, clearSkillWalletGrantConfig as r, runSkillsMarketplaceList as s, applySkillWalletGrantConfig as t };