1
/**2
* One-time migrations that run on startup.3
*/5
import chalk from "chalk";6
import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "fs";7
import { dirname, join } from "path";8
import { CONFIG_DIR_NAME, getAgentDir, getBinDir } from "./config.ts";9
import { migrateKeybindingsConfig } from "./core/keybindings.ts";10
import { stripBom } from "./utils/text.ts";12
const MIGRATION_GUIDE_URL =13
"https://github.com/earendil-works/pi/blob/main/packages/coding-agent/CHANGELOG.md#extensions-migration";14
const EXTENSIONS_DOC_URL = "https://github.com/earendil-works/pi/blob/main/packages/coding-agent/docs/extensions.md";16
/**17
* Migrate legacy oauth.json and settings.json apiKeys to auth.json.18
*19
* @returns Array of provider names that were migrated20
*/21
export function migrateAuthToAuthJson(): string[] {22
const agentDir = getAgentDir();23
const authPath = join(agentDir, "auth.json");24
const oauthPath = join(agentDir, "oauth.json");25
const settingsPath = join(agentDir, "settings.json");27
// Skip if auth.json already exists28
if (existsSync(authPath)) return [];30
const migrated: Record<string, unknown> = {};31
const providers: string[] = [];33
// Migrate oauth.json34
if (existsSync(oauthPath)) {35
try {36
const oauth = JSON.parse(stripBom(readFileSync(oauthPath, "utf-8")));37
for (const [provider, cred] of Object.entries(oauth)) {38
migrated[provider] = { type: "oauth", ...(cred as object) };39
providers.push(provider);40
}41
renameSync(oauthPath, `${oauthPath}.migrated`);42
} catch {43
// Skip on error44
}45
}47
// Migrate settings.json apiKeys48
if (existsSync(settingsPath)) {49
try {50
const content = readFileSync(settingsPath, "utf-8");51
const settings = JSON.parse(stripBom(content));52
if (settings.apiKeys && typeof settings.apiKeys === "object") {53
for (const [provider, key] of Object.entries(settings.apiKeys)) {54
if (!migrated[provider] && typeof key === "string") {55
migrated[provider] = { type: "api_key", key };56
providers.push(provider);57
}58
}59
delete settings.apiKeys;60
writeFileSync(settingsPath, JSON.stringify(settings, null, 2));61
}62
} catch {63
// Skip on error64
}65
}67
if (Object.keys(migrated).length > 0) {68
mkdirSync(dirname(authPath), { recursive: true });69
writeFileSync(authPath, JSON.stringify(migrated, null, 2), { mode: 0o600 });70
}72
return providers;73
}75
/**76
* Migrate sessions from ~/.pi/agent/*.jsonl to proper session directories.77
*78
* Bug in v0.30.0: Sessions were saved to ~/.pi/agent/ instead of79
* ~/.pi/agent/sessions/<encoded-cwd>/. This migration moves them80
* to the correct location based on the cwd in their session header.81
*82
* See: https://github.com/earendil-works/pi-mono/issues/32083
*/84
export function migrateSessionsFromAgentRoot(): void {85
const agentDir = getAgentDir();87
// Find all .jsonl files directly in agentDir (not in subdirectories)88
let files: string[];89
try {90
files = readdirSync(agentDir)91
.filter((f) => f.endsWith(".jsonl"))92
.map((f) => join(agentDir, f));93
} catch {94
return;95
}97
if (files.length === 0) return;99
for (const file of files) {100
try {101
// Read first line to get session header102
const content = readFileSync(file, "utf8");103
const firstLine = content.split("\n")[0];104
if (!firstLine?.trim()) continue;106
const header = JSON.parse(firstLine);107
if (header.type !== "session" || !header.cwd) continue;109
const cwd: string = header.cwd;111
// Compute the correct session directory (same encoding as session-manager.ts)112
const safePath = `--${cwd.replace(/^[/\\]/, "").replace(/[/\\:]/g, "-")}--`;113
const correctDir = join(agentDir, "sessions", safePath);115
// Create directory if needed116
if (!existsSync(correctDir)) {117
mkdirSync(correctDir, { recursive: true });118
}120
// Move the file121
const fileName = file.split("/").pop() || file.split("\\").pop();122
const newPath = join(correctDir, fileName!);124
if (existsSync(newPath)) continue; // Skip if target exists126
renameSync(file, newPath);127
} catch {128
// Skip files that can't be migrated129
}130
}131
}133
/**134
* Migrate commands/ to prompts/ if needed.135
* Works for both regular directories and symlinks.136
*/137
function migrateCommandsToPrompts(baseDir: string, label: string): boolean {138
const commandsDir = join(baseDir, "commands");139
const promptsDir = join(baseDir, "prompts");141
if (existsSync(commandsDir) && !existsSync(promptsDir)) {142
try {143
renameSync(commandsDir, promptsDir);144
console.log(chalk.green(`Migrated ${label} commands/ → prompts/`));145
return true;146
} catch (err) {147
console.log(148
chalk.yellow(149
`Warning: Could not migrate ${label} commands/ to prompts/: ${err instanceof Error ? err.message : err}`,150
),151
);152
}153
}154
return false;155
}157
function migrateKeybindingsConfigFile(): void {158
const configPath = join(getAgentDir(), "keybindings.json");159
if (!existsSync(configPath)) return;161
try {162
const parsed = JSON.parse(stripBom(readFileSync(configPath, "utf-8"))) as unknown;163
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {164
return;165
}166
const { config, migrated } = migrateKeybindingsConfig(parsed as Record<string, unknown>);167
if (!migrated) return;168
writeFileSync(configPath, `${JSON.stringify(config, null, 2)}\n`, "utf-8");169
} catch {170
// Ignore malformed files during migration171
}172
}174
/**175
* Move fd/rg binaries from tools/ to bin/ if they exist.176
*/177
function migrateToolsToBin(): void {178
const agentDir = getAgentDir();179
const toolsDir = join(agentDir, "tools");180
const binDir = getBinDir();182
if (!existsSync(toolsDir)) return;184
const binaries = ["fd", "rg", "fd.exe", "rg.exe"];185
let movedAny = false;187
for (const bin of binaries) {188
const oldPath = join(toolsDir, bin);189
const newPath = join(binDir, bin);191
if (existsSync(oldPath)) {192
if (!existsSync(binDir)) {193
mkdirSync(binDir, { recursive: true });194
}195
if (!existsSync(newPath)) {196
try {197
renameSync(oldPath, newPath);198
movedAny = true;199
} catch {200
// Ignore errors201
}202
} else {203
// Target exists, just delete the old one204
try {205
rmSync?.(oldPath, { force: true });206
} catch {207
// Ignore208
}209
}210
}211
}213
if (movedAny) {214
console.log(chalk.green(`Migrated managed binaries tools/ → bin/`));215
}216
}218
/**219
* Check for deprecated hooks/ and tools/ directories.220
* Note: tools/ may contain fd/rg binaries extracted by pi, so only warn if it has other files.221
*/222
function checkDeprecatedExtensionDirs(baseDir: string, label: string): string[] {223
const hooksDir = join(baseDir, "hooks");224
const toolsDir = join(baseDir, "tools");225
const warnings: string[] = [];227
if (existsSync(hooksDir)) {228
warnings.push(`${label} hooks/ directory found. Hooks have been renamed to extensions.`);229
}231
if (existsSync(toolsDir)) {232
// Check if tools/ contains anything other than fd/rg (which are auto-extracted binaries)233
try {234
const entries = readdirSync(toolsDir);235
const customTools = entries.filter((e) => {236
const lower = e.toLowerCase();237
return (238
lower !== "fd" && lower !== "rg" && lower !== "fd.exe" && lower !== "rg.exe" && !e.startsWith(".") // Ignore .DS_Store and other hidden files239
);240
});241
if (customTools.length > 0) {242
warnings.push(243
`${label} tools/ directory contains custom tools. Custom tools have been merged into extensions.`,244
);245
}246
} catch {247
// Ignore read errors248
}249
}251
return warnings;252
}254
/**255
* Run extension system migrations (commands→prompts) and collect warnings about deprecated directories.256
*/257
function migrateExtensionSystem(cwd: string): string[] {258
const agentDir = getAgentDir();259
const projectDir = join(cwd, CONFIG_DIR_NAME);261
// Migrate commands/ to prompts/262
migrateCommandsToPrompts(agentDir, "Global");263
migrateCommandsToPrompts(projectDir, "Project");265
// Check for deprecated directories266
const warnings = [267
...checkDeprecatedExtensionDirs(agentDir, "Global"),268
...checkDeprecatedExtensionDirs(projectDir, "Project"),269
];271
return warnings;272
}274
/**275
* Print deprecation warnings and wait for keypress.276
*/277
export async function showDeprecationWarnings(warnings: string[]): Promise<void> {278
if (warnings.length === 0) return;280
for (const warning of warnings) {281
console.log(chalk.yellow(`Warning: ${warning}`));282
}283
console.log(chalk.yellow(`\nMove your extensions to the extensions/ directory.`));284
console.log(chalk.yellow(`Migration guide: ${MIGRATION_GUIDE_URL}`));285
console.log(chalk.yellow(`Documentation: ${EXTENSIONS_DOC_URL}`));286
console.log(chalk.dim(`\nPress any key to continue...`));288
await new Promise<void>((resolve) => {289
process.stdin.setRawMode?.(true);290
process.stdin.resume();291
process.stdin.once("data", () => {292
process.stdin.setRawMode?.(false);293
process.stdin.pause();294
resolve();295
});296
});297
console.log();298
}300
/**301
* Run all migrations. Called once on startup.302
*303
* @returns Object with migration results and deprecation warnings304
*/305
export function runMigrations(cwd: string): {306
migratedAuthProviders: string[];307
deprecationWarnings: string[];308
} {309
const migratedAuthProviders = migrateAuthToAuthJson();310
migrateSessionsFromAgentRoot();311
migrateToolsToBin();312
migrateKeybindingsConfigFile();313
const deprecationWarnings = migrateExtensionSystem(cwd);314
return { migratedAuthProviders, deprecationWarnings };315
}