UNPKG

@code-yeongyu/senpi

Version:

Coding agent CLI with read, bash, edit, write tools and session management

237 lines • 8.88 kB
/** * One-time migrations that run on startup. */ import chalk from "chalk"; import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "fs"; import { dirname, join } from "path"; import { migrateEngineStateForBrand } from "./brand-dir-migration.js"; import { getAgentDir, getBinDir } from "./config.js"; import { migrateKeybindingsConfig } from "./core/keybindings.js"; import { migrateExtensionSystem } from "./extension-system-migration.js"; import { migrateLegacySenpiDirs } from "./legacy-senpi-dir-migration.js"; import { readCompletedScanMigrations, SCAN_MIGRATIONS, writeCompletedScanMigrations } from "./migrations-state.js"; import { restoreDrainedPiDirs } from "./pi-dir-restore.js"; import { stripBom } from "./utils/text.js"; const MIGRATION_GUIDE_URL = "https://github.com/earendil-works/pi/blob/main/packages/coding-agent/CHANGELOG.md#extensions-migration"; const EXTENSIONS_DOC_URL = "https://github.com/earendil-works/pi/blob/main/packages/coding-agent/docs/extensions.md"; /** * Migrate legacy oauth.json and settings.json apiKeys to auth.json. * * @returns Array of provider names that were migrated */ export function migrateAuthToAuthJson() { const agentDir = getAgentDir(); const authPath = join(agentDir, "auth.json"); const oauthPath = join(agentDir, "oauth.json"); const settingsPath = join(agentDir, "settings.json"); // Skip if auth.json already exists if (existsSync(authPath)) return []; const migrated = {}; const providers = []; // Migrate oauth.json if (existsSync(oauthPath)) { try { const oauth = JSON.parse(stripBom(readFileSync(oauthPath, "utf-8"))); for (const [provider, cred] of Object.entries(oauth)) { migrated[provider] = { type: "oauth", ...cred }; providers.push(provider); } renameSync(oauthPath, `${oauthPath}.migrated`); } catch { // Skip on error } } // Migrate settings.json apiKeys if (existsSync(settingsPath)) { try { const content = readFileSync(settingsPath, "utf-8"); const settings = JSON.parse(stripBom(content)); if (settings.apiKeys && typeof settings.apiKeys === "object") { for (const [provider, key] of Object.entries(settings.apiKeys)) { if (!migrated[provider] && typeof key === "string") { migrated[provider] = { type: "api_key", key }; providers.push(provider); } } delete settings.apiKeys; writeFileSync(settingsPath, JSON.stringify(settings, null, 2)); } } catch { // Skip on error } } if (Object.keys(migrated).length > 0) { mkdirSync(dirname(authPath), { recursive: true }); writeFileSync(authPath, JSON.stringify(migrated, null, 2), { mode: 0o600 }); } return providers; } /** * Migrate sessions from ~/.pi/agent/*.jsonl to proper session directories. * * Bug in v0.30.0: Sessions were saved to ~/.pi/agent/ instead of * ~/.pi/agent/sessions/<encoded-cwd>/. This migration moves them * to the correct location based on the cwd in their session header. * * See: https://github.com/earendil-works/pi-mono/issues/320 */ export function migrateSessionsFromAgentRoot() { const agentDir = getAgentDir(); // Find all .jsonl files directly in agentDir (not in subdirectories) let files; try { files = readdirSync(agentDir) .filter((f) => f.endsWith(".jsonl")) .map((f) => join(agentDir, f)); } catch { return; } if (files.length === 0) return; for (const file of files) { try { // Read first line to get session header const content = readFileSync(file, "utf8"); const firstLine = content.split("\n")[0]; if (!firstLine?.trim()) continue; const header = JSON.parse(firstLine); if (header.type !== "session" || !header.cwd) continue; const cwd = header.cwd; // Compute the correct session directory (same encoding as session-manager.ts) const safePath = `--${cwd.replace(/^[/\\]/, "").replace(/[/\\:]/g, "-")}--`; const correctDir = join(agentDir, "sessions", safePath); // Create directory if needed if (!existsSync(correctDir)) { mkdirSync(correctDir, { recursive: true }); } // Move the file const fileName = file.split("/").pop() || file.split("\\").pop(); const newPath = join(correctDir, fileName); if (existsSync(newPath)) continue; // Skip if target exists renameSync(file, newPath); } catch { // Skip files that can't be migrated } } } function migrateKeybindingsConfigFile() { const configPath = join(getAgentDir(), "keybindings.json"); if (!existsSync(configPath)) return; try { const parsed = JSON.parse(stripBom(readFileSync(configPath, "utf-8"))); if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) { return; } const { config, migrated } = migrateKeybindingsConfig(parsed); if (!migrated) return; writeFileSync(configPath, `${JSON.stringify(config, null, 2)}\n`, "utf-8"); } catch { // Ignore malformed files during migration } } /** * Move fd/rg binaries from tools/ to bin/ if they exist. */ function migrateToolsToBin() { const agentDir = getAgentDir(); const toolsDir = join(agentDir, "tools"); const binDir = getBinDir(); if (!existsSync(toolsDir)) return; const binaries = ["fd", "rg", "fd.exe", "rg.exe"]; let movedAny = false; for (const bin of binaries) { const oldPath = join(toolsDir, bin); const newPath = join(binDir, bin); if (existsSync(oldPath)) { if (!existsSync(binDir)) { mkdirSync(binDir, { recursive: true }); } if (!existsSync(newPath)) { try { renameSync(oldPath, newPath); movedAny = true; } catch { // Ignore errors } } else { // Target exists, just delete the old one try { rmSync?.(oldPath, { force: true }); } catch { // Ignore } } } } if (movedAny) { console.log(chalk.green(`Migrated managed binaries tools/ → bin/`)); } } /** * Print deprecation warnings and wait for keypress. */ export async function showDeprecationWarnings(warnings) { if (warnings.length === 0) return; for (const warning of warnings) { console.log(chalk.yellow(`Warning: ${warning}`)); } console.log(chalk.yellow(`\nMove your extensions to the extensions/ directory.`)); console.log(chalk.yellow(`Migration guide: ${MIGRATION_GUIDE_URL}`)); console.log(chalk.yellow(`Documentation: ${EXTENSIONS_DOC_URL}`)); console.log(chalk.dim(`\nPress any key to continue...`)); await new Promise((resolve) => { process.stdin.setRawMode?.(true); process.stdin.resume(); process.stdin.once("data", () => { process.stdin.setRawMode?.(false); process.stdin.pause(); resolve(); }); }); console.log(); } /** * Run all migrations. Called once on startup. * * @returns Object with migration results and deprecation warnings */ export function runMigrations(cwd) { // Runs first: everything below resolves paths through the agent directory, which the // branded install only populates once this copy-forward has happened. migrateEngineStateForBrand(); const migratedAuthProviders = migrateAuthToAuthJson(); const completed = readCompletedScanMigrations(); if (!completed.has("restoreDrainedPiDirs")) { restoreDrainedPiDirs(completed); } if (!completed.has("migrateLegacySenpiDirs")) { migrateLegacySenpiDirs(cwd); } if (!completed.has("migrateSessionsFromAgentRoot")) { migrateSessionsFromAgentRoot(); } migrateToolsToBin(); migrateKeybindingsConfigFile(); const deprecationWarnings = migrateExtensionSystem(cwd); if (completed.size !== SCAN_MIGRATIONS.length) { writeCompletedScanMigrations(SCAN_MIGRATIONS); } return { migratedAuthProviders, deprecationWarnings }; } //# sourceMappingURL=migrations.js.map