// Launch the repository-local Pi with every piece of Pi state inside this repository. // Isolation contract: PI_CODING_AGENT_DIR points at .pi/agent (git-ignored), so // settings, models, auth, sessions, installed packages and managed binaries never // reach the user's global ~/.pi/agent. The global Pi stays untouched. import { spawnSync } from 'node:child_process'; import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'; import { homedir } from 'node:os'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); const packageDir = path.join(root, 'node_modules', '@earendil-works', 'pi-coding-agent'); const agentDir = process.env.PI_CODING_AGENT_DIR || path.join(root, '.pi', 'agent'); // Model endpoints, credentials and user settings move only by the explicit --setup step. const configFiles = ['models.json', 'auth.json', 'settings.json']; // Markers inherited from a parent Pi shell tool would describe the wrong session. const parentSessionVars = [ 'AI_AGENT', 'PI_CODING_AGENT', 'PI_SESSION_ID', 'PI_SESSION_FILE', 'PI_PROVIDER', 'PI_MODEL', 'PI_REASONING_LEVEL', ]; function fail(message) { console.error(`pi: ${message}`); process.exitCode = 1; } function cliPath() { const manifest = path.join(packageDir, 'package.json'); if (!existsSync(manifest)) return null; let bin; try { bin = JSON.parse(readFileSync(manifest, 'utf8')).bin; } catch { return null; } const entry = typeof bin === 'string' ? bin : bin?.pi; if (!entry) return null; const cli = path.join(packageDir, entry); return existsSync(cli) ? cli : null; } // Global settings declare the user's personal extensions; keeping them means the // isolated Pi installs those same packages into .pi/agent/npm on the next start. export function prepareSettings(text, dropPackages) { if (!dropPackages) return text; try { const settings = JSON.parse(text); if (settings && typeof settings === 'object' && !Array.isArray(settings)) delete settings.packages; return `${JSON.stringify(settings, null, 2)}\n`; } catch { return text; // Unparseable config moves verbatim instead of being rewritten. } } // Values are never printed: models.json and auth.json hold endpoints and tokens. function setup(force, dropPackages) { const source = path.join(homedir(), '.pi', 'agent'); mkdirSync(agentDir, { recursive: true }); const copied = []; for (const file of configFiles) { const target = path.join(agentDir, file); if (existsSync(target) && !force) continue; if (!existsSync(path.join(source, file))) continue; const text = readFileSync(path.join(source, file), 'utf8'); writeFileSync(target, file === 'settings.json' ? prepareSettings(text, dropPackages) : text, 'utf8'); copied.push(file); } console.log(`Каталог состояния Pi: ${agentDir}`); console.log(copied.length ? `Скопированы без показа значений: ${copied.join(', ')}.` : 'Файлы состояния уже на месте, ничего не перезаписано.'); console.log(dropPackages ? 'Объявления пакетов из settings.json убраны: локальный Pi стартует без личных расширений.' : 'Объявления пакетов из settings.json сохранены: Pi доустановит их в .pi/agent/npm при следующем запуске.'); console.log('Модель и endpoint проверяются в Pi (/model) или в models.json этого каталога.'); } // Importing this module must not launch Pi, so the entry point runs only when invoked. if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { const args = process.argv.slice(2); if (args[0] === '--setup' || args[0] === 'setup') { setup(args.includes('--force'), args.includes('--no-packages')); } else { const cli = cliPath(); if (!cli) { fail('Локальный Pi не установлен; выполните npm ci --ignore-scripts.'); } else { mkdirSync(agentDir, { recursive: true }); const env = { ...process.env, PI_CODING_AGENT_DIR: agentDir }; for (const name of parentSessionVars) delete env[name]; const result = spawnSync(process.execPath, [cli, ...args], { stdio: 'inherit', env, cwd: root }); if (result.error) fail('Не удалось запустить локальный Pi.'); else if (result.signal) { console.error(`pi: процесс завершён сигналом ${result.signal}.`); process.exitCode = 1; } else process.exitCode = result.status ?? 1; } } }