import { execFile, type ExecException } from "node:child_process"; import semver from "semver"; export const CLAUDE_MINIMUM_VERSION = "2.0.12"; export const CLAUDE_MARKETPLACE_NAME = "whitespace-pony"; export const CLAUDE_MARKETPLACE_SOURCE = "https://unpkg.com/@whitespace/pony@latest/.claude-plugin/marketplace.json"; export const CLAUDE_PLUGIN_ID = `pony@${CLAUDE_MARKETPLACE_NAME}`; export const CLAUDE_PLUGIN_SCOPE = "user"; export interface ClaudeCommandResult { stderr: string; stdout: string; } export type ClaudeCommandRunner = ( args: string[], ) => Promise; export type ClaudeCommandExecutor = ( executable: string, args: string[], callback: ( error: ExecException | null, stdout: string, stderr: string, ) => void, ) => void; export type ClaudeSetupOutcome = "current" | "installed" | "newer" | "upgraded"; export interface ClaudeSetupResult { claudeVersion: string; installedVersion: string; marketplaceAction: "added" | "refreshed"; outcome: ClaudeSetupOutcome; pluginId: string; scope: typeof CLAUDE_PLUGIN_SCOPE; version: string; } interface ClaudeMarketplace { name: string; repo?: string; source: string; url?: string; } interface ClaudePlugin { pluginId: string; scope: string; version: string; } function isUsableString(value: unknown): value is string { return ( typeof value === "string" && value.length > 0 && value.trim() === value ); } /** * Claude Code renamed the list entry identifier from `pluginId` to `id`. * Accept both supported schemas, but reject ambiguous mixed entries so Pony * never guesses which installed plugin Claude Code meant. */ function normalizePlugin(entry: unknown): ClaudePlugin | null { if (typeof entry !== "object" || entry === null) return null; const record = entry as Record; const currentId = record.id; const legacyId = record.pluginId; if ( (currentId !== undefined && !isUsableString(currentId)) || (legacyId !== undefined && !isUsableString(legacyId)) || (isUsableString(currentId) && isUsableString(legacyId) && currentId !== legacyId) ) { return null; } const pluginId = currentId ?? legacyId; if ( !isUsableString(pluginId) || !isUsableString(record.scope) || !isUsableString(record.version) || !semver.valid(record.version) ) { return null; } return { pluginId, scope: record.scope, version: record.version, }; } function commandLabel(args: string[]): string { return `claude ${args.join(" ")}`; } const executeClaudeCommand: ClaudeCommandExecutor = ( executable, args, callback, ) => { execFile( executable, args, { encoding: "utf8", maxBuffer: 4 * 1024 * 1024 }, callback, ); }; export function runClaudeCommand( args: string[], execute: ClaudeCommandExecutor = executeClaudeCommand, ): Promise { return new Promise((resolve, reject) => { execute("claude", args, (error, stdout, stderr) => { if (!error) { resolve({ stdout, stderr }); return; } if (error.code === "ENOENT") { reject( new Error( `Claude Code CLI was not found. Install Claude Code ${CLAUDE_MINIMUM_VERSION} or newer and try again.`, ), ); return; } const detail = stderr.trim() || error.message; reject( new Error( `Claude setup failed during \`${commandLabel(args)}\`: ${detail}`, ), ); }); }); } function parseJson(stdout: string, args: string[]): unknown { try { return JSON.parse(stdout) as unknown; } catch { throw new Error( `Claude Code returned invalid JSON for \`${commandLabel(args)}\`. Update Claude Code and try again.`, ); } } function parseClaudeVersion(stdout: string): string { const match = stdout.match(/\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?/u)?.[0]; const version = match ? semver.valid(match) : null; if (!version) { throw new Error( "Claude Code returned an unrecognized version. Update Claude Code and try again.", ); } if (semver.lt(version, CLAUDE_MINIMUM_VERSION)) { throw new Error( `Claude Code ${version} is not supported. Install Claude Code ${CLAUDE_MINIMUM_VERSION} or newer and try again.`, ); } return version; } function parseMarketplaces(stdout: string): ClaudeMarketplace[] { const args = ["plugin", "marketplace", "list", "--json"]; const value = parseJson(stdout, args); if ( !Array.isArray(value) || !value.every( (entry) => typeof entry === "object" && entry !== null && typeof entry.name === "string" && typeof entry.source === "string", ) ) { throw new Error( `Claude Code returned unsupported JSON for \`${commandLabel(args)}\`. Update Claude Code and try again.`, ); } return value as ClaudeMarketplace[]; } function parsePlugins(stdout: string): ClaudePlugin[] { const args = ["plugin", "list", "--json"]; const value = parseJson(stdout, args); if (!Array.isArray(value)) { throw new Error( `Claude Code returned unsupported JSON for \`${commandLabel(args)}\`. Update Claude Code and try again.`, ); } const plugins = value.map(normalizePlugin); if (plugins.some((plugin) => plugin === null)) { throw new Error( `Claude Code returned unsupported JSON for \`${commandLabel(args)}\`. Update Claude Code and try again.`, ); } return plugins as ClaudePlugin[]; } function requirePonyMarketplaceSource(marketplace: ClaudeMarketplace): void { if ( marketplace.source !== "url" || marketplace.url !== CLAUDE_MARKETPLACE_SOURCE ) { throw new Error( `Claude marketplace ${CLAUDE_MARKETPLACE_NAME} already exists with another source. Remove or rename that marketplace before running setup again.`, ); } } async function prepareMarketplace( runner: ClaudeCommandRunner, ): Promise<"added" | "refreshed"> { const args = ["plugin", "marketplace", "list", "--json"]; const output = await runner(args); const marketplace = parseMarketplaces(output.stdout).find( ({ name }) => name === CLAUDE_MARKETPLACE_NAME, ); if (!marketplace) { await runner([ "plugin", "marketplace", "add", CLAUDE_MARKETPLACE_SOURCE, "--scope", CLAUDE_PLUGIN_SCOPE, ]); return "added"; } requirePonyMarketplaceSource(marketplace); await runner(["plugin", "marketplace", "update", CLAUDE_MARKETPLACE_NAME]); return "refreshed"; } async function listUserPlugin( runner: ClaudeCommandRunner, ): Promise { const args = ["plugin", "list", "--json"]; const output = await runner(args); return ( parsePlugins(output.stdout).find( ({ pluginId, scope }) => pluginId === CLAUDE_PLUGIN_ID && scope === CLAUDE_PLUGIN_SCOPE, ) ?? null ); } function targetVersion(version: string): string { const valid = semver.valid(version); if (!valid) { throw new Error(`Pony package version ${version} is not valid semver.`); } return valid; } async function changePlugin( current: ClaudePlugin | null, version: string, runner: ClaudeCommandRunner, ): Promise { if (current && semver.gt(current.version, version)) return "newer"; if (current?.version === version) return "current"; const outcome = current ? "upgraded" : "installed"; await runner([ "plugin", current ? "update" : "install", CLAUDE_PLUGIN_ID, "--scope", CLAUDE_PLUGIN_SCOPE, ]); return outcome; } async function verifyPlugin( outcome: ClaudeSetupOutcome, current: ClaudePlugin | null, version: string, runner: ClaudeCommandRunner, ): Promise { if ((outcome === "current" || outcome === "newer") && current) { return current.version; } const installed = await listUserPlugin(runner); if (!installed) { throw new Error( `Claude Code completed the plugin mutation, but ${CLAUDE_PLUGIN_ID} is not installed at user scope.`, ); } if (installed.version !== version) { throw new Error( `Claude Code installed ${CLAUDE_PLUGIN_ID} ${installed.version} instead of ${version}. Refresh the marketplace and run setup again.`, ); } return installed.version; } /** * Delegates every settings and cache mutation to Claude Code. Pony refreshes * only its own marketplace, targets user scope explicitly, and verifies the * resolved installed version before reporting a successful change. */ export async function setupClaudePlugin( version: string, runner: ClaudeCommandRunner = runClaudeCommand, ): Promise { const requestedVersion = targetVersion(version); const versionOutput = await runner(["--version"]); const claudeVersion = parseClaudeVersion(versionOutput.stdout); const marketplaceAction = await prepareMarketplace(runner); const current = await listUserPlugin(runner); const outcome = await changePlugin(current, requestedVersion, runner); const installedVersion = await verifyPlugin( outcome, current, requestedVersion, runner, ); return { claudeVersion, installedVersion, marketplaceAction, outcome, pluginId: CLAUDE_PLUGIN_ID, scope: CLAUDE_PLUGIN_SCOPE, version: requestedVersion, }; }