#!/usr/bin/env node import { spawn } from "node:child_process"; import { realpath } from "node:fs/promises"; import path from "node:path"; import { findProjectRoot } from "../core/index.js"; import { PONY_COMMAND_MANIFEST_FLAG, createPonyCommandManifest, isCliEntrypoint, runPonyCli, type PonyCliOutput, type PonyCliRuntime, } from "./index.js"; import { argsWithoutWorkspace, commandTokens } from "./launcher-args.js"; import { checkPackageCompatibility, ensureLocalPonyPackage, readPackageVersion, resolveLocalPonyPackage, runPackageCommand, type LocalPonyPackage, type PackageCommandRunner, } from "./local-package.js"; import { startUpdateCheck } from "./update-check.js"; import { upgradePony, type LatestVersionResolver } from "./upgrade.js"; import { findPackageRoot } from "./web.js"; import { captureTerminalState, type ProcessSignalTarget } from "./terminal.js"; const LAUNCHER_ACTIVE_ENV = "PONY_LAUNCHER_ACTIVE"; interface ProcessResult { status: number; stderr: string; stdout: string; } export interface LocalProcessRuntime { captureTerminalState(): () => void; signalTarget: ProcessSignalTarget; spawnProcess( command: string, args: string[], options: { cwd: string; env: NodeJS.ProcessEnv; stdio: "inherit" | ["ignore", "pipe", "pipe"]; }, ): ReturnType; } export interface LauncherRuntime extends PonyCliRuntime { cwd: string; execPath?: string; nodeVersion?: string; platform?: NodeJS.Platform; readLauncherVersion?: () => Promise; resolveLatestVersion?: LatestVersionResolver; runLocalProcess?: ( binPath: string, args: string[], options: { capture: boolean; cwd: string; env: NodeJS.ProcessEnv }, ) => Promise; runPackageCommand?: PackageCommandRunner; } const processRuntime: LauncherRuntime = { cwd: process.cwd(), env: process.env, stdin: process.stdin, stdout: process.stdout, stderr: process.stderr, }; const localProcessRuntime: LocalProcessRuntime = { captureTerminalState: () => captureTerminalState(process.stdin, process.stdout), signalTarget: process, spawnProcess: (command, args, options) => spawn(command, args, options), }; function writeLine(output: PonyCliOutput, value = ""): void { output.write(`${value}\n`); } function workspaceCwd(args: string[], runtime: LauncherRuntime): string { const explicitIndex = args.findIndex((arg) => arg === "--cwd"); if (explicitIndex >= 0 && args[explicitIndex + 1]) { return path.resolve(runtime.cwd, args[explicitIndex + 1]); } const explicit = args.find((arg) => arg.startsWith("--cwd=")); if (explicit) return path.resolve(runtime.cwd, explicit.slice("--cwd=".length)); return path.resolve(runtime.env.PONY_WORKSPACE_CWD ?? runtime.cwd); } function withWorkspaceCwd(args: string[], cwd: string): string[] { return args.some((arg) => arg === "--cwd" || arg.startsWith("--cwd=")) ? args : ["--cwd", cwd, ...args]; } /** * Delegated commands inherit the launcher's process group and TTY. Catching * termination signals here prevents the shell from resuming before the local * runtime has stopped its own children and restored terminal state. */ export async function runLocalProcess( binPath: string, args: string[], options: { capture: boolean; cwd: string; env: NodeJS.ProcessEnv }, runtime: LocalProcessRuntime = localProcessRuntime, ): Promise { return new Promise((resolve, reject) => { const child = runtime.spawnProcess(process.execPath, [binPath, ...args], { cwd: options.cwd, env: options.env, stdio: options.capture ? ["ignore", "pipe", "pipe"] : "inherit", }); let stdout = ""; let stderr = ""; let receivedSignal: NodeJS.Signals | null = null; let settled = false; const restoreTerminal = options.capture ? () => undefined : runtime.captureTerminalState(); const forwardSignal = (signal: NodeJS.Signals) => { receivedSignal ??= signal; if (child.exitCode === null && child.signalCode === null) { child.kill(signal); } }; const onSigint = () => forwardSignal("SIGINT"); const onSigterm = () => forwardSignal("SIGTERM"); const cleanup = () => { if (!options.capture) { runtime.signalTarget.off("SIGINT", onSigint); runtime.signalTarget.off("SIGTERM", onSigterm); } restoreTerminal(); }; const finish = (callback: () => void) => { if (settled) return; settled = true; cleanup(); callback(); }; if (!options.capture) { runtime.signalTarget.on("SIGINT", onSigint); runtime.signalTarget.on("SIGTERM", onSigterm); } child.stdout?.on("data", (chunk) => (stdout += chunk.toString())); child.stderr?.on("data", (chunk) => (stderr += chunk.toString())); child.once("error", (error) => finish(() => reject(error))); child.once("exit", (code, signal) => { const status = receivedSignal === "SIGINT" ? 130 : receivedSignal === "SIGTERM" ? 143 : (code ?? (signal === "SIGINT" ? 130 : signal === "SIGTERM" ? 143 : 1)); finish(() => resolve({ status, stderr, stdout })); }); }); } async function localStatus( cwd: string, launcherVersion: string, ): Promise<{ compatibility: ReturnType | null; localPackage: LocalPonyPackage | null; projectRoot: string | null; }> { const projectRoot = await findProjectRoot(cwd); if (!projectRoot) return { compatibility: null, localPackage: null, projectRoot }; const localPackage = await resolveLocalPonyPackage(projectRoot); return { compatibility: localPackage ? checkPackageCompatibility(launcherVersion, localPackage.version) : null, localPackage, projectRoot, }; } async function printVersion( cwd: string, launcherVersion: string, runtime: LauncherRuntime, ): Promise { writeLine(runtime.stdout, `Pony launcher ${launcherVersion}`); const status = await localStatus(cwd, launcherVersion); if (!status.projectRoot) { writeLine(runtime.stdout, "Pony project not found"); } else if (!status.localPackage) { writeLine(runtime.stdout, "Pony project package not installed"); } else if (status.compatibility?.compatible) { writeLine( runtime.stdout, `Pony project ${status.localPackage.version} (compatible)`, ); } else { writeLine( runtime.stdout, `Pony project ${status.localPackage.version} (incompatible: ${status.compatibility?.reason})`, ); } } function printLauncherCommands(runtime: LauncherRuntime): void { writeLine(runtime.stdout, "Launcher commands:"); writeLine( runtime.stdout, " init initialize Pony and install the local package", ); writeLine( runtime.stdout, " setup chatgpt configure the ChatGPT plugin marketplace", ); writeLine( runtime.stdout, " setup claude install the Claude Code plugin at user scope", ); writeLine( runtime.stdout, " setup codex configure the optional Codex CLI plugin", ); writeLine( runtime.stdout, " upgrade upgrade the launcher and project runtime", ); writeLine( runtime.stdout, " help, --help, -h show launcher and project commands", ); writeLine( runtime.stdout, " --version, -v show launcher and project versions", ); } function printUpgradeHelp(runtime: LauncherRuntime): void { writeLine(runtime.stdout, "Usage: pony upgrade [options]"); writeLine(runtime.stdout); writeLine( runtime.stdout, "Upgrade the Pony launcher and compatible project runtime to npm latest.", ); writeLine(runtime.stdout); writeLine(runtime.stdout, "Options:"); writeLine( runtime.stdout, " --launcher-only upgrade only the global launcher", ); writeLine( runtime.stdout, " --project-only upgrade only the project runtime", ); writeLine(runtime.stdout, " -h, --help display help for command"); } async function printMergedHelp( cwd: string, launcherVersion: string, runtime: LauncherRuntime, ): Promise { writeLine(runtime.stdout, "Usage: pony [options] [command]"); writeLine(runtime.stdout); writeLine(runtime.stdout, "Git-backed agent-native project workspace"); writeLine(runtime.stdout); printLauncherCommands(runtime); writeLine(runtime.stdout); const status = await localStatus(cwd, launcherVersion); if (!status.projectRoot) { writeLine( runtime.stdout, "Project commands unavailable: no .pony/config.yml found", ); return; } if (!status.localPackage) { writeLine( runtime.stdout, "Project commands unavailable: local @whitespace/pony is not installed", ); return; } if (!status.compatibility?.compatible) { writeLine( runtime.stdout, `Project commands unavailable: ${status.compatibility?.reason}`, ); return; } const execute = runtime.runLocalProcess ?? runLocalProcess; const env = { ...runtime.env, [LAUNCHER_ACTIVE_ENV]: "1" }; const manifest = await execute( status.localPackage.binPath, [PONY_COMMAND_MANIFEST_FLAG], { capture: true, cwd: status.projectRoot, env }, ); if (manifest.status === 0) { try { const parsed = JSON.parse(manifest.stdout) as { commands: Array<{ description: string; name: string }>; protocolVersion: number; }; if (parsed.protocolVersion === 1 && Array.isArray(parsed.commands)) { writeLine( runtime.stdout, `Project commands (Pony ${status.localPackage.version}):`, ); for (const command of parsed.commands) { writeLine( runtime.stdout, ` ${command.name.padEnd(20)} ${command.description}`.trimEnd(), ); } return; } } catch { // Older local packages do not expose the launcher manifest protocol. } } const legacyHelp = await execute(status.localPackage.binPath, ["--help"], { capture: true, cwd: status.projectRoot, env, }); writeLine( runtime.stdout, `Project commands (Pony ${status.localPackage.version}, legacy help):`, ); runtime.stdout.write(legacyHelp.stdout || legacyHelp.stderr); } async function delegate( args: string[], cwd: string, launcherRoot: string, launcherVersion: string, runtime: LauncherRuntime, ): Promise { const status = await localStatus(cwd, launcherVersion); if (!status.projectRoot) { writeLine( runtime.stderr, "No .pony/config.yml found. Run `pony init` first.", ); return 1; } if (!status.localPackage) { writeLine( runtime.stderr, "Local @whitespace/pony is not installed. Run `pony init` again to install it.", ); return 1; } if (!status.compatibility?.compatible) { writeLine( runtime.stderr, `Cannot run project command: ${status.compatibility?.reason}.`, ); writeLine( runtime.stderr, status.compatibility?.reason.startsWith("local version") ? "Update the global launcher before retrying." : "Install matching Pony major versions before retrying.", ); return 1; } if (status.localPackage.packageRoot === (await realpath(launcherRoot))) { return runPonyCli(withWorkspaceCwd(args, cwd), runtime); } const execute = runtime.runLocalProcess ?? runLocalProcess; const result = await execute(status.localPackage.binPath, args, { capture: false, cwd: status.projectRoot, env: { ...runtime.env, [LAUNCHER_ACTIVE_ENV]: "1" }, }); return result.status; } async function initializeProject( args: string[], cwd: string, launcherVersion: string, runtime: LauncherRuntime, ): Promise { if (args.includes("--help") || args.includes("-h")) { return runPonyCli(withWorkspaceCwd(args, cwd), runtime); } const status = await runPonyCli(withWorkspaceCwd(args, cwd), runtime); if (status !== 0) return status; try { const result = await ensureLocalPonyPackage( cwd, launcherVersion, runtime.runPackageCommand ?? runPackageCommand, ); writeLine( runtime.stdout, result.installed ? `Installed local ${result.localPackage.version} as a development dependency.` : `Local Pony ${result.localPackage.version} is ready.`, ); return 0; } catch (error) { writeLine( runtime.stderr, error instanceof Error ? error.message : String(error), ); return 1; } } async function upgradeInstallations( args: string[], cwd: string, launcherRoot: string, launcherVersion: string, runtime: LauncherRuntime, ): Promise { if (args.includes("--help") || args.includes("-h")) { printUpgradeHelp(runtime); return 0; } const allowed = new Set(["upgrade", "--launcher-only", "--project-only"]); const unknown = argsWithoutWorkspace(args).find( (value) => !allowed.has(value), ); if (unknown) { throw new Error(`Unknown option for pony upgrade: ${unknown}`); } const result = await upgradePony( cwd, launcherRoot, launcherVersion, { launcherOnly: args.includes("--launcher-only"), projectOnly: args.includes("--project-only"), }, { execPath: runtime.execPath, nodeVersion: runtime.nodeVersion, onWarning: (message) => writeLine(runtime.stderr, message), readLauncherVersion: runtime.readLauncherVersion, resolveLatestVersion: runtime.resolveLatestVersion, runPackageCommand: runtime.runPackageCommand, }, ); if (result.launcher.selected) { writeLine( runtime.stdout, result.launcher.changed ? `Launcher: ${result.launcher.before} → ${result.launcher.after}` : `Launcher: ${result.launcher.after} (unchanged)`, ); } if (result.project?.selected) { writeLine( runtime.stdout, result.project.changed ? `Project: ${result.project.before} → ${result.project.after}` : `Project: ${result.project.after} (unchanged)`, ); } else if (!result.projectFound && !args.includes("--launcher-only")) { writeLine(runtime.stdout, "Project: not selected (no Pony project found)"); } return 0; } async function runLauncherPrelude( args: string[], runtime: LauncherRuntime, ): Promise { if (args.includes(PONY_COMMAND_MANIFEST_FLAG)) { writeLine( runtime.stdout, JSON.stringify(await createPonyCommandManifest()), ); return 0; } if (runtime.env[LAUNCHER_ACTIVE_ENV] === "1") { return runPonyCli(args, runtime); } return null; } function startLauncherUpdateCheck( args: string[], cwd: string, launcherVersion: string, runtime: LauncherRuntime, ): void { startUpdateCheck(args, cwd, launcherVersion, { env: runtime.env, homeDir: runtime.homeDir, isTTY: runtime.stdout.isTTY === true && runtime.stderr.isTTY === true, platform: runtime.platform, resolveLatestVersion: runtime.resolveLatestVersion, writeNotice: (notice) => writeLine(runtime.stderr, notice), }); } async function dispatchLauncherCommand( args: string[], command: string, helpTarget: string | undefined, cwd: string, launcherRoot: string, launcherVersion: string, runtime: LauncherRuntime, ): Promise { if (command === "init") { return initializeProject(args, cwd, launcherVersion, runtime); } if (command === "upgrade") { return upgradeInstallations( args, cwd, launcherRoot, launcherVersion, runtime, ); } if (command === "help" && helpTarget === "upgrade") { printUpgradeHelp(runtime); return 0; } const localHelpTargets = new Set(["init", "setup"]); if ( command === "setup" || (command === "help" && helpTarget && localHelpTargets.has(helpTarget)) ) { return runPonyCli(withWorkspaceCwd(args, cwd), runtime); } return delegate(args, cwd, launcherRoot, launcherVersion, runtime); } async function runPonyLauncherInternal( args: string[], runtime: LauncherRuntime = processRuntime, ): Promise { const preludeStatus = await runLauncherPrelude(args, runtime); if (preludeStatus !== null) return preludeStatus; const cwd = workspaceCwd(args, runtime); const launcherRoot = await findPackageRoot(import.meta.url); const launcherVersion = await readPackageVersion(launcherRoot); const tokens = commandTokens(args); const command = tokens[0]; const helpTarget = command === "help" ? tokens[1] : undefined; startLauncherUpdateCheck(args, cwd, launcherVersion, runtime); if (args.includes("--version") || args.includes("-v")) { await printVersion(cwd, launcherVersion, runtime); return 0; } if (!command || (command === "help" && !helpTarget)) { await printMergedHelp(cwd, launcherVersion, runtime); return 0; } return dispatchLauncherCommand( args, command, helpTarget, cwd, launcherRoot, launcherVersion, runtime, ); } export async function runPonyLauncher( args: string[], runtime: LauncherRuntime = processRuntime, ): Promise { try { return await runPonyLauncherInternal(args, runtime); } catch (error) { writeLine( runtime.stderr, error instanceof Error ? error.message : String(error), ); return 1; } } if (await isCliEntrypoint(process.argv[1], import.meta.url)) { process.exitCode = await runPonyLauncher(process.argv.slice(2)); }