migrations.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  1. /**
  2. * One-time migrations that run on startup.
  3. */
  4. import chalk from "chalk";
  5. import { chmodSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "fs";
  6. import { dirname, join } from "path";
  7. import { CONFIG_DIR_NAME, getAgentDir, getBinDir } from "./config.ts";
  8. import { migrateKeybindingsConfig } from "./core/keybindings.ts";
  9. import { isLegacyEnvVarNameConfigValue } from "./core/resolve-config-value.ts";
  10. import { stripJsonComments } from "./utils/json.ts";
  11. const MIGRATION_GUIDE_URL =
  12. "https://github.com/earendil-works/pi-mono/blob/main/packages/coding-agent/CHANGELOG.md#extensions-migration";
  13. const EXTENSIONS_DOC_URL =
  14. "https://github.com/earendil-works/pi-mono/blob/main/packages/coding-agent/docs/extensions.md";
  15. /**
  16. * Migrate legacy oauth.json and settings.json apiKeys to auth.json.
  17. *
  18. * @returns Array of provider names that were migrated
  19. */
  20. export function migrateAuthToAuthJson(): string[] {
  21. const agentDir = getAgentDir();
  22. const authPath = join(agentDir, "auth.json");
  23. const oauthPath = join(agentDir, "oauth.json");
  24. const settingsPath = join(agentDir, "settings.json");
  25. // Skip if auth.json already exists
  26. if (existsSync(authPath)) return [];
  27. const migrated: Record<string, unknown> = {};
  28. const providers: string[] = [];
  29. // Migrate oauth.json
  30. if (existsSync(oauthPath)) {
  31. try {
  32. const oauth = JSON.parse(readFileSync(oauthPath, "utf-8"));
  33. for (const [provider, cred] of Object.entries(oauth)) {
  34. migrated[provider] = { type: "oauth", ...(cred as object) };
  35. providers.push(provider);
  36. }
  37. renameSync(oauthPath, `${oauthPath}.migrated`);
  38. } catch {
  39. // Skip on error
  40. }
  41. }
  42. // Migrate settings.json apiKeys
  43. if (existsSync(settingsPath)) {
  44. try {
  45. const content = readFileSync(settingsPath, "utf-8");
  46. const settings = JSON.parse(content);
  47. if (settings.apiKeys && typeof settings.apiKeys === "object") {
  48. for (const [provider, key] of Object.entries(settings.apiKeys)) {
  49. if (!migrated[provider] && typeof key === "string") {
  50. migrated[provider] = { type: "api_key", key };
  51. providers.push(provider);
  52. }
  53. }
  54. delete settings.apiKeys;
  55. writeFileSync(settingsPath, JSON.stringify(settings, null, 2));
  56. }
  57. } catch {
  58. // Skip on error
  59. }
  60. }
  61. if (Object.keys(migrated).length > 0) {
  62. mkdirSync(dirname(authPath), { recursive: true });
  63. writeFileSync(authPath, JSON.stringify(migrated, null, 2), { mode: 0o600 });
  64. }
  65. return providers;
  66. }
  67. interface ConfigValueMigration {
  68. location: string;
  69. from: string;
  70. to: string;
  71. }
  72. function migrateLegacyEnvVarString(value: string): string | undefined {
  73. return isLegacyEnvVarNameConfigValue(value) ? `$${value}` : undefined;
  74. }
  75. function migrateStringProperty(
  76. record: Record<string, unknown>,
  77. key: string,
  78. location: string,
  79. migrations: ConfigValueMigration[],
  80. ): boolean {
  81. const value = record[key];
  82. if (typeof value !== "string") return false;
  83. const migrated = migrateLegacyEnvVarString(value);
  84. if (migrated === undefined) return false;
  85. record[key] = migrated;
  86. migrations.push({ location, from: value, to: migrated });
  87. return true;
  88. }
  89. function migrateHeadersConfig(headers: unknown, location: string, migrations: ConfigValueMigration[]): boolean {
  90. if (typeof headers !== "object" || headers === null || Array.isArray(headers)) return false;
  91. const headerRecord = headers as Record<string, unknown>;
  92. let migrated = false;
  93. for (const [key, value] of Object.entries(headerRecord)) {
  94. if (typeof value !== "string") continue;
  95. const migratedValue = migrateLegacyEnvVarString(value);
  96. if (migratedValue === undefined) continue;
  97. headerRecord[key] = migratedValue;
  98. migrations.push({ location: `${location}[${JSON.stringify(key)}]`, from: value, to: migratedValue });
  99. migrated = true;
  100. }
  101. return migrated;
  102. }
  103. function migrateAuthJsonConfigValues(agentDir: string): ConfigValueMigration[] {
  104. const authPath = join(agentDir, "auth.json");
  105. if (!existsSync(authPath)) return [];
  106. try {
  107. const parsed = JSON.parse(readFileSync(authPath, "utf-8")) as unknown;
  108. if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return [];
  109. const authData = parsed as Record<string, unknown>;
  110. const migrations: ConfigValueMigration[] = [];
  111. for (const [provider, credential] of Object.entries(authData)) {
  112. if (typeof credential !== "object" || credential === null || Array.isArray(credential)) continue;
  113. const credentialRecord = credential as Record<string, unknown>;
  114. if (credentialRecord.type !== "api_key") continue;
  115. migrateStringProperty(credentialRecord, "key", `auth.json[${JSON.stringify(provider)}].key`, migrations);
  116. }
  117. if (migrations.length === 0) return [];
  118. writeFileSync(authPath, `${JSON.stringify(parsed, null, 2)}\n`, "utf-8");
  119. chmodSync(authPath, 0o600);
  120. return migrations;
  121. } catch {
  122. return [];
  123. }
  124. }
  125. function migrateModelsJsonConfigValues(agentDir: string): ConfigValueMigration[] {
  126. const modelsPath = join(agentDir, "models.json");
  127. if (!existsSync(modelsPath)) return [];
  128. try {
  129. const parsed = JSON.parse(stripJsonComments(readFileSync(modelsPath, "utf-8"))) as unknown;
  130. if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return [];
  131. const modelsData = parsed as Record<string, unknown>;
  132. const providers = modelsData.providers;
  133. if (typeof providers !== "object" || providers === null || Array.isArray(providers)) return [];
  134. const migrations: ConfigValueMigration[] = [];
  135. for (const [provider, providerConfig] of Object.entries(providers)) {
  136. if (typeof providerConfig !== "object" || providerConfig === null || Array.isArray(providerConfig)) continue;
  137. const providerRecord = providerConfig as Record<string, unknown>;
  138. const providerLocation = `models.json.providers[${JSON.stringify(provider)}]`;
  139. migrateStringProperty(providerRecord, "apiKey", `${providerLocation}.apiKey`, migrations);
  140. migrateHeadersConfig(providerRecord.headers, `${providerLocation}.headers`, migrations);
  141. if (Array.isArray(providerRecord.models)) {
  142. for (let index = 0; index < providerRecord.models.length; index++) {
  143. const modelConfig = providerRecord.models[index];
  144. if (typeof modelConfig !== "object" || modelConfig === null || Array.isArray(modelConfig)) continue;
  145. const modelRecord = modelConfig as Record<string, unknown>;
  146. const modelKey = typeof modelRecord.id === "string" ? JSON.stringify(modelRecord.id) : String(index);
  147. migrateHeadersConfig(modelRecord.headers, `${providerLocation}.models[${modelKey}].headers`, migrations);
  148. }
  149. }
  150. const modelOverrides = providerRecord.modelOverrides;
  151. if (typeof modelOverrides === "object" && modelOverrides !== null && !Array.isArray(modelOverrides)) {
  152. for (const [modelId, modelOverride] of Object.entries(modelOverrides)) {
  153. if (typeof modelOverride !== "object" || modelOverride === null || Array.isArray(modelOverride))
  154. continue;
  155. const modelOverrideRecord = modelOverride as Record<string, unknown>;
  156. migrateHeadersConfig(
  157. modelOverrideRecord.headers,
  158. `${providerLocation}.modelOverrides[${JSON.stringify(modelId)}].headers`,
  159. migrations,
  160. );
  161. }
  162. }
  163. }
  164. if (migrations.length === 0) return [];
  165. writeFileSync(modelsPath, `${JSON.stringify(parsed, null, 2)}\n`, "utf-8");
  166. return migrations;
  167. } catch {
  168. return [];
  169. }
  170. }
  171. function migrateExplicitEnvVarConfigValues(): void {
  172. const agentDir = getAgentDir();
  173. const migrations = [...migrateAuthJsonConfigValues(agentDir), ...migrateModelsJsonConfigValues(agentDir)];
  174. if (migrations.length === 0) return;
  175. const details = migrations.map((migration) => ` - ${migration.location}: ${migration.from} -> ${migration.to}`);
  176. console.log(
  177. chalk.yellow(
  178. [
  179. "Warning: Migrated API key/header environment references to explicit $ENV_VAR syntax. Plain strings will be treated as literals.",
  180. ...details,
  181. ].join("\n"),
  182. ),
  183. );
  184. }
  185. /**
  186. * Migrate sessions from ~/.pi/agent/*.jsonl to proper session directories.
  187. *
  188. * Bug in v0.30.0: Sessions were saved to ~/.pi/agent/ instead of
  189. * ~/.pi/agent/sessions/<encoded-cwd>/. This migration moves them
  190. * to the correct location based on the cwd in their session header.
  191. *
  192. * See: https://github.com/earendil-works/pi-mono/issues/320
  193. */
  194. export function migrateSessionsFromAgentRoot(): void {
  195. const agentDir = getAgentDir();
  196. // Find all .jsonl files directly in agentDir (not in subdirectories)
  197. let files: string[];
  198. try {
  199. files = readdirSync(agentDir)
  200. .filter((f) => f.endsWith(".jsonl"))
  201. .map((f) => join(agentDir, f));
  202. } catch {
  203. return;
  204. }
  205. if (files.length === 0) return;
  206. for (const file of files) {
  207. try {
  208. // Read first line to get session header
  209. const content = readFileSync(file, "utf8");
  210. const firstLine = content.split("\n")[0];
  211. if (!firstLine?.trim()) continue;
  212. const header = JSON.parse(firstLine);
  213. if (header.type !== "session" || !header.cwd) continue;
  214. const cwd: string = header.cwd;
  215. // Compute the correct session directory (same encoding as session-manager.ts)
  216. const safePath = `--${cwd.replace(/^[/\\]/, "").replace(/[/\\:]/g, "-")}--`;
  217. const correctDir = join(agentDir, "sessions", safePath);
  218. // Create directory if needed
  219. if (!existsSync(correctDir)) {
  220. mkdirSync(correctDir, { recursive: true });
  221. }
  222. // Move the file
  223. const fileName = file.split("/").pop() || file.split("\\").pop();
  224. const newPath = join(correctDir, fileName!);
  225. if (existsSync(newPath)) continue; // Skip if target exists
  226. renameSync(file, newPath);
  227. } catch {
  228. // Skip files that can't be migrated
  229. }
  230. }
  231. }
  232. /**
  233. * Migrate commands/ to prompts/ if needed.
  234. * Works for both regular directories and symlinks.
  235. */
  236. function migrateCommandsToPrompts(baseDir: string, label: string): boolean {
  237. const commandsDir = join(baseDir, "commands");
  238. const promptsDir = join(baseDir, "prompts");
  239. if (existsSync(commandsDir) && !existsSync(promptsDir)) {
  240. try {
  241. renameSync(commandsDir, promptsDir);
  242. console.log(chalk.green(`Migrated ${label} commands/ → prompts/`));
  243. return true;
  244. } catch (err) {
  245. console.log(
  246. chalk.yellow(
  247. `Warning: Could not migrate ${label} commands/ to prompts/: ${err instanceof Error ? err.message : err}`,
  248. ),
  249. );
  250. }
  251. }
  252. return false;
  253. }
  254. function migrateKeybindingsConfigFile(): void {
  255. const configPath = join(getAgentDir(), "keybindings.json");
  256. if (!existsSync(configPath)) return;
  257. try {
  258. const parsed = JSON.parse(readFileSync(configPath, "utf-8")) as unknown;
  259. if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
  260. return;
  261. }
  262. const { config, migrated } = migrateKeybindingsConfig(parsed as Record<string, unknown>);
  263. if (!migrated) return;
  264. writeFileSync(configPath, `${JSON.stringify(config, null, 2)}\n`, "utf-8");
  265. } catch {
  266. // Ignore malformed files during migration
  267. }
  268. }
  269. /**
  270. * Move fd/rg binaries from tools/ to bin/ if they exist.
  271. */
  272. function migrateToolsToBin(): void {
  273. const agentDir = getAgentDir();
  274. const toolsDir = join(agentDir, "tools");
  275. const binDir = getBinDir();
  276. if (!existsSync(toolsDir)) return;
  277. const binaries = ["fd", "rg", "fd.exe", "rg.exe"];
  278. let movedAny = false;
  279. for (const bin of binaries) {
  280. const oldPath = join(toolsDir, bin);
  281. const newPath = join(binDir, bin);
  282. if (existsSync(oldPath)) {
  283. if (!existsSync(binDir)) {
  284. mkdirSync(binDir, { recursive: true });
  285. }
  286. if (!existsSync(newPath)) {
  287. try {
  288. renameSync(oldPath, newPath);
  289. movedAny = true;
  290. } catch {
  291. // Ignore errors
  292. }
  293. } else {
  294. // Target exists, just delete the old one
  295. try {
  296. rmSync?.(oldPath, { force: true });
  297. } catch {
  298. // Ignore
  299. }
  300. }
  301. }
  302. }
  303. if (movedAny) {
  304. console.log(chalk.green(`Migrated managed binaries tools/ → bin/`));
  305. }
  306. }
  307. /**
  308. * Check for deprecated hooks/ and tools/ directories.
  309. * Note: tools/ may contain fd/rg binaries extracted by pi, so only warn if it has other files.
  310. */
  311. function checkDeprecatedExtensionDirs(baseDir: string, label: string): string[] {
  312. const hooksDir = join(baseDir, "hooks");
  313. const toolsDir = join(baseDir, "tools");
  314. const warnings: string[] = [];
  315. if (existsSync(hooksDir)) {
  316. warnings.push(`${label} hooks/ directory found. Hooks have been renamed to extensions.`);
  317. }
  318. if (existsSync(toolsDir)) {
  319. // Check if tools/ contains anything other than fd/rg (which are auto-extracted binaries)
  320. try {
  321. const entries = readdirSync(toolsDir);
  322. const customTools = entries.filter((e) => {
  323. const lower = e.toLowerCase();
  324. return (
  325. lower !== "fd" && lower !== "rg" && lower !== "fd.exe" && lower !== "rg.exe" && !e.startsWith(".") // Ignore .DS_Store and other hidden files
  326. );
  327. });
  328. if (customTools.length > 0) {
  329. warnings.push(
  330. `${label} tools/ directory contains custom tools. Custom tools have been merged into extensions.`,
  331. );
  332. }
  333. } catch {
  334. // Ignore read errors
  335. }
  336. }
  337. return warnings;
  338. }
  339. /**
  340. * Run extension system migrations (commands→prompts) and collect warnings about deprecated directories.
  341. */
  342. function migrateExtensionSystem(cwd: string): string[] {
  343. const agentDir = getAgentDir();
  344. const projectDir = join(cwd, CONFIG_DIR_NAME);
  345. // Migrate commands/ to prompts/
  346. migrateCommandsToPrompts(agentDir, "Global");
  347. migrateCommandsToPrompts(projectDir, "Project");
  348. // Check for deprecated directories
  349. const warnings = [
  350. ...checkDeprecatedExtensionDirs(agentDir, "Global"),
  351. ...checkDeprecatedExtensionDirs(projectDir, "Project"),
  352. ];
  353. return warnings;
  354. }
  355. /**
  356. * Print deprecation warnings and wait for keypress.
  357. */
  358. export async function showDeprecationWarnings(warnings: string[]): Promise<void> {
  359. if (warnings.length === 0) return;
  360. for (const warning of warnings) {
  361. console.log(chalk.yellow(`Warning: ${warning}`));
  362. }
  363. console.log(chalk.yellow(`\nMove your extensions to the extensions/ directory.`));
  364. console.log(chalk.yellow(`Migration guide: ${MIGRATION_GUIDE_URL}`));
  365. console.log(chalk.yellow(`Documentation: ${EXTENSIONS_DOC_URL}`));
  366. console.log(chalk.dim(`\nPress any key to continue...`));
  367. await new Promise<void>((resolve) => {
  368. process.stdin.setRawMode?.(true);
  369. process.stdin.resume();
  370. process.stdin.once("data", () => {
  371. process.stdin.setRawMode?.(false);
  372. process.stdin.pause();
  373. resolve();
  374. });
  375. });
  376. console.log();
  377. }
  378. /**
  379. * Run all migrations. Called once on startup.
  380. *
  381. * @returns Object with migration results and deprecation warnings
  382. */
  383. export function runMigrations(cwd: string): {
  384. migratedAuthProviders: string[];
  385. deprecationWarnings: string[];
  386. } {
  387. const migratedAuthProviders = migrateAuthToAuthJson();
  388. migrateExplicitEnvVarConfigValues();
  389. migrateSessionsFromAgentRoot();
  390. migrateToolsToBin();
  391. migrateKeybindingsConfigFile();
  392. const deprecationWarnings = migrateExtensionSystem(cwd);
  393. return { migratedAuthProviders, deprecationWarnings };
  394. }