返回源码地图

packages/coding-agent/src/migrations.ts

v1.3.0 · 71023aec1546 · 15:启动一次性文件迁移,与设置读时迁移分层

完整原文供逐行核对;页面收录不代表每行都经过人工语义审核。MIT 许可见 许可证。

1/**
2 * One-time migrations that run on startup.
3 */
4
5import chalk from "chalk";
6import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "fs";
7import { dirname, join } from "path";
8import { CONFIG_DIR_NAME, getAgentDir, getBinDir } from "./config.ts";
9import { migrateKeybindingsConfig } from "./core/keybindings.ts";
10import { stripBom } from "./utils/text.ts";
11
12const MIGRATION_GUIDE_URL =
13 "https://github.com/earendil-works/pi/blob/main/packages/coding-agent/CHANGELOG.md#extensions-migration";
14const EXTENSIONS_DOC_URL = "https://github.com/earendil-works/pi/blob/main/packages/coding-agent/docs/extensions.md";
15
16/**
17 * Migrate legacy oauth.json and settings.json apiKeys to auth.json.
18 *
19 * @returns Array of provider names that were migrated
20 */
21export 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");
26
27 // Skip if auth.json already exists
28 if (existsSync(authPath)) return [];
29
30 const migrated: Record<string, unknown> = {};
31 const providers: string[] = [];
32
33 // Migrate oauth.json
34 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 error
44 }
45 }
46
47 // Migrate settings.json apiKeys
48 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 error
64 }
65 }
66
67 if (Object.keys(migrated).length > 0) {
68 mkdirSync(dirname(authPath), { recursive: true });
69 writeFileSync(authPath, JSON.stringify(migrated, null, 2), { mode: 0o600 });
70 }
71
72 return providers;
73}
74
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 of
79 * ~/.pi/agent/sessions/<encoded-cwd>/. This migration moves them
80 * to the correct location based on the cwd in their session header.
81 *
82 * See: https://github.com/earendil-works/pi-mono/issues/320
83 */
84export function migrateSessionsFromAgentRoot(): void {
85 const agentDir = getAgentDir();
86
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 }
96
97 if (files.length === 0) return;
98
99 for (const file of files) {
100 try {
101 // Read first line to get session header
102 const content = readFileSync(file, "utf8");
103 const firstLine = content.split("\n")[0];
104 if (!firstLine?.trim()) continue;
105
106 const header = JSON.parse(firstLine);
107 if (header.type !== "session" || !header.cwd) continue;
108
109 const cwd: string = header.cwd;
110
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);
114
115 // Create directory if needed
116 if (!existsSync(correctDir)) {
117 mkdirSync(correctDir, { recursive: true });
118 }
119
120 // Move the file
121 const fileName = file.split("/").pop() || file.split("\\").pop();
122 const newPath = join(correctDir, fileName!);
123
124 if (existsSync(newPath)) continue; // Skip if target exists
125
126 renameSync(file, newPath);
127 } catch {
128 // Skip files that can't be migrated
129 }
130 }
131}
132
133/**
134 * Migrate commands/ to prompts/ if needed.
135 * Works for both regular directories and symlinks.
136 */
137function migrateCommandsToPrompts(baseDir: string, label: string): boolean {
138 const commandsDir = join(baseDir, "commands");
139 const promptsDir = join(baseDir, "prompts");
140
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}
156
157function migrateKeybindingsConfigFile(): void {
158 const configPath = join(getAgentDir(), "keybindings.json");
159 if (!existsSync(configPath)) return;
160
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 migration
171 }
172}
173
174/**
175 * Move fd/rg binaries from tools/ to bin/ if they exist.
176 */
177function migrateToolsToBin(): void {
178 const agentDir = getAgentDir();
179 const toolsDir = join(agentDir, "tools");
180 const binDir = getBinDir();
181
182 if (!existsSync(toolsDir)) return;
183
184 const binaries = ["fd", "rg", "fd.exe", "rg.exe"];
185 let movedAny = false;
186
187 for (const bin of binaries) {
188 const oldPath = join(toolsDir, bin);
189 const newPath = join(binDir, bin);
190
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 errors
201 }
202 } else {
203 // Target exists, just delete the old one
204 try {
205 rmSync?.(oldPath, { force: true });
206 } catch {
207 // Ignore
208 }
209 }
210 }
211 }
212
213 if (movedAny) {
214 console.log(chalk.green(`Migrated managed binaries tools/ → bin/`));
215 }
216}
217
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 */
222function checkDeprecatedExtensionDirs(baseDir: string, label: string): string[] {
223 const hooksDir = join(baseDir, "hooks");
224 const toolsDir = join(baseDir, "tools");
225 const warnings: string[] = [];
226
227 if (existsSync(hooksDir)) {
228 warnings.push(`${label} hooks/ directory found. Hooks have been renamed to extensions.`);
229 }
230
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 files
239 );
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 errors
248 }
249 }
250
251 return warnings;
252}
253
254/**
255 * Run extension system migrations (commands→prompts) and collect warnings about deprecated directories.
256 */
257function migrateExtensionSystem(cwd: string): string[] {
258 const agentDir = getAgentDir();
259 const projectDir = join(cwd, CONFIG_DIR_NAME);
260
261 // Migrate commands/ to prompts/
262 migrateCommandsToPrompts(agentDir, "Global");
263 migrateCommandsToPrompts(projectDir, "Project");
264
265 // Check for deprecated directories
266 const warnings = [
267 ...checkDeprecatedExtensionDirs(agentDir, "Global"),
268 ...checkDeprecatedExtensionDirs(projectDir, "Project"),
269 ];
270
271 return warnings;
272}
273
274/**
275 * Print deprecation warnings and wait for keypress.
276 */
277export async function showDeprecationWarnings(warnings: string[]): Promise<void> {
278 if (warnings.length === 0) return;
279
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...`));
287
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}
299
300/**
301 * Run all migrations. Called once on startup.
302 *
303 * @returns Object with migration results and deprecation warnings
304 */
305export 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}