#!/usr/bin/env node import { spawn } from "node:child_process"; import { realpathSync } from "node:fs"; import { dirname, join, resolve } from "node:path"; import { fileURLToPath } from "node:url"; const piPackageCommands = new Set(["install", "remove", "uninstall", "update", "list", "config"]); export function resolvePackageRootFromCliUrl(cliUrl: string): string { return dirname(dirname(fileURLToPath(cliUrl))); } export function resolvePiCliPath(piEntrypointUrl: string): string { return join(dirname(fileURLToPath(piEntrypointUrl)), "cli.js"); } export function shouldInjectLinlicPackage(userArgs: string[]): boolean { return !piPackageCommands.has(userArgs[0] ?? ""); } export function buildPiArgs(packageRoot: string, userArgs: string[]): string[] { if (!shouldInjectLinlicPackage(userArgs)) { return userArgs; } return ["--extension", packageRoot, ...userArgs]; } function resolveExecutablePath(path: string): string { const resolvedPath = resolve(path); try { return realpathSync(resolvedPath); } catch { return resolvedPath; } } export function isMainModule(moduleUrl: string, argvPath = process.argv[1]): boolean { return argvPath ? resolveExecutablePath(fileURLToPath(moduleUrl)) === resolveExecutablePath(argvPath) : false; } export async function runPiCli(options: { piCliPath: string; packageRoot: string; userArgs: string[]; env?: NodeJS.ProcessEnv; }): Promise { const child = spawn(process.execPath, [options.piCliPath, ...buildPiArgs(options.packageRoot, options.userArgs)], { stdio: "inherit", env: { ...process.env, ...options.env, LINLIC_AGENT: "true" }, }); return new Promise((resolveExitCode) => { child.on("error", (error) => { console.error(`linlic-agent failed to start Pi CLI: ${error.message}`); resolveExitCode(1); }); child.on("exit", (code, signal) => { if (signal) { process.kill(process.pid, signal); resolveExitCode(1); return; } resolveExitCode(code ?? 0); }); }); } if (isMainModule(import.meta.url)) { const packageRoot = resolvePackageRootFromCliUrl(import.meta.url); const piCliPath = resolvePiCliPath(import.meta.resolve("@earendil-works/pi-coding-agent")); process.exitCode = await runPiCli({ piCliPath, packageRoot, userArgs: process.argv.slice(2), }); }