import { Command } from 'commander'; import { execFileSync } from 'child_process'; import { existsSync, readFileSync } from 'fs'; import { dirname, resolve } from 'path'; import { fileURLToPath } from 'url'; const NPM_INSTALL_TIMEOUT_MS = 30_000; export interface UpgradeDeps { installLatest: () => void; readInstalledCliVersion: () => string; } export interface UpgradeResult { version?: string; error?: string; } export function runUpgrade(deps: UpgradeDeps): UpgradeResult { try { deps.installLatest(); } catch (err: any) { return { error: `npm install failed: ${err?.message ?? String(err)}` }; } let version: string; try { version = deps.readInstalledCliVersion(); } catch (err: any) { return { error: `read installed cli version failed: ${err?.message ?? String(err)}` }; } return { version }; } function npmBin(): string { return process.platform === 'win32' ? 'npm.cmd' : 'npm'; } type ExecFileSyncLike = (file: string, args: string[], options: Record) => unknown; function escapeCmdArg(arg: string): string { if (/\s/.test(arg)) throw new Error(`npm argument contains whitespace: ${arg}`); return arg.replace(/[()^!%<>&|]/g, '^$&'); } function execNpmSync(args: string[], options: Record, execFile: ExecFileSyncLike = execFileSync): unknown { if (process.platform !== 'win32') { return execFile(npmBin(), args, { ...options, shell: false }); } const command = [npmBin(), ...args].map(escapeCmdArg).join(' '); return execFile('cmd.exe', ['/d', '/c', command], { ...options, shell: false }); } function currentPackageName(): string { const __filename = fileURLToPath(import.meta.url); const pkgPath = resolve(dirname(__filename), '..', '..', 'package.json'); const pkg = JSON.parse(readFileSync(pkgPath, 'utf8')); const name = String(pkg?.name ?? '').trim(); if (!name) throw new Error(`package name not found: ${pkgPath}`); return name; } export function installLatestFromNpm(packageName: string, execFile: ExecFileSyncLike = execFileSync): void { execNpmSync( [ 'install', '-g', `${packageName}@latest`, '--foreground-scripts', '--loglevel=error', ], { timeout: NPM_INSTALL_TIMEOUT_MS, windowsHide: true, stdio: ['ignore', 'ignore', 'inherit'] }, execFile, ); } function readInstalledCliVersionFromNpm(packageName: string): string { const npmRoot = String(execNpmSync(['root', '-g'], { encoding: 'utf8', windowsHide: true })).trim(); const pkgPath = resolve(npmRoot, packageName, 'package.json'); if (!existsSync(pkgPath)) throw new Error(`installed package not found: ${pkgPath}`); const pkg = JSON.parse(readFileSync(pkgPath, 'utf8')); if (!pkg?.version) throw new Error(`installed package has no version: ${pkgPath}`); return pkg.version; } export function syncSkillFromInstalledPackage(packageName: string, execFile: ExecFileSyncLike = execFileSync): void { const npmRoot = String(execNpmSync(['root', '-g'], { encoding: 'utf8', windowsHide: true }, execFile)).trim(); const installDir = resolve(npmRoot, packageName); const syncScript = resolve(installDir, 'scripts', 'sync-bundled-skill.mjs'); if (!existsSync(syncScript)) throw new Error(`bundled skill sync script not found: ${syncScript}`); execFile( process.execPath, [syncScript], { cwd: installDir, timeout: 120_000, windowsHide: true, stdio: 'inherit', }, ); } export function runDefaultUpgrade(): UpgradeResult { const packageName = currentPackageName(); return runUpgrade({ installLatest: () => installLatestFromNpm(packageName), readInstalledCliVersion: () => readInstalledCliVersionFromNpm(packageName), }); } export function createUpgradeCommand(): Command { const cmd = new Command('upgrade') .description('Install latest @myclaw163/clawclaw-cli from npm.') .action(async () => { const result = runDefaultUpgrade(); if (result.error) { console.error(result.error); process.exit(1); } console.log(result.version); }); cmd.command('skill') .description('Sync all bundled ClawClaw skills from the installed CLI package.') .action(() => { try { syncSkillFromInstalledPackage(currentPackageName()); } catch (err: any) { console.error(err?.message ?? String(err)); process.exit(1); } }); return cmd; }