feat: запускать Pi из локальной копии с состоянием в .pi/

Держать всё состояние Pi — настройки, модели, ключи, сессии, установленные пакеты и служебные бинарники — в игнорируемом .pi/ этого репозитория, чтобы рабочий агент лаборатории не читал и не менял глобальный ~/.pi/agent. Версионировать только .pi/agent/settings.json: проверочный скрипт дочитывает его явно и проверяет приватность наравне с остальными файлами. Переносить креды по явному --setup без вывода значений, а ланчеру — снимать маркеры родительской сессии. Обновление версии Pi, подключение супервизора и оценка его полезности остаются отдельными поручениями.
This commit is contained in:
Suslov-MD
2026-11-28 14:21:09 +03:00
parent 8cb433daa9
commit 936a702127
10 changed files with 1869 additions and 9 deletions
+13 -1
View File
@@ -82,7 +82,9 @@ export function checkRepository(directory) {
try { entries = readdirSync(path.join(root, relative), { withFileTypes: true }); }
catch { error(slash(relative) || '.', 1, 'read', 'Не удалось прочитать каталог.'); return; }
for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
if (entry.name === '.git' || entry.name === 'node_modules') continue;
// Local runtime state: Pi keeps transcripts, credentials and installed
// packages under .pi, and none of that is library material.
if (entry.name === '.git' || entry.name === '.pi' || entry.name === 'node_modules') continue;
const file = slash(path.join(relative, entry.name));
if (entry.isDirectory()) { walk(file); continue; }
if (!entry.isFile()) continue; // Do not traverse symlinks or external trees.
@@ -111,6 +113,16 @@ export function checkRepository(directory) {
}
walk();
// .pi holds Pi runtime state, but the project's Pi settings are versioned:
// that one file gets the same privacy review as any other tracked file.
for (const file of ['.pi/agent/settings.json']) {
try {
const text = readFileSync(path.join(root, file), 'utf8');
files.set(file, text);
privacyWarnings(file, text, warn);
} catch { /* Absent local state is not a structural problem. */ }
}
function metadata(file) {
if (!files.has(file)) { error(file, 1, 'missing-file', 'Обязательный текстовый файл отсутствует.'); return null; }
const text = files.get(file);
+93
View File
@@ -0,0 +1,93 @@
// 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;
}
}
}