import { existsSync, mkdirSync, statSync, writeFileSync } from "node:fs"; import { homedir } from "node:os"; import { dirname, resolve } from "node:path"; import type { ExtensionAPI, ExtensionCommandContext, SessionEntry, SessionHeader, } from "@earendil-works/pi-coding-agent"; import { CURRENT_SESSION_VERSION, getAgentDir, SessionManager, SettingsManager, } from "@earendil-works/pi-coding-agent"; function expandTilde(path: string): string { if (path === "~") return homedir(); if (path.startsWith("~/")) return resolve(homedir(), path.slice(2)); return path; } function resolveTarget(raw: string, cwd: string): string { const input = raw.trim() || "."; const expanded = expandTilde(input); return resolve(cwd, expanded); } function assertDirectory(path: string): string | undefined { if (!existsSync(path)) return `cwd not found: ${path}`; let stats; try { stats = statSync(path); } catch (error) { return `cannot stat cwd: ${error instanceof Error ? error.message : String(error)}`; } if (!stats.isDirectory()) return `cwd is not a directory: ${path}`; return undefined; } function sessionFileExists(ctx: ExtensionCommandContext): string | undefined { const file = ctx.sessionManager.getSessionFile(); return file && existsSync(file) ? file : undefined; } function configuredSessionDir(targetCwd: string): string | undefined { try { return SettingsManager.create(targetCwd, getAgentDir()).getSessionDir(); } catch { return undefined; } } function createSessionFileFromMemory( ctx: ExtensionCommandContext, targetCwd: string, sessionDir?: string, ): string { const manager = SessionManager.create(targetCwd, sessionDir); const sessionFile = manager.getSessionFile(); if (!sessionFile) throw new Error("Failed to allocate target session file"); const timestamp = new Date().toISOString(); const header: SessionHeader = { type: "session", version: CURRENT_SESSION_VERSION, id: manager.getSessionId(), timestamp, cwd: targetCwd, parentSession: ctx.sessionManager.getSessionFile(), }; const entries = ctx.sessionManager.getEntries() as SessionEntry[]; mkdirSync(dirname(sessionFile), { recursive: true }); writeFileSync( sessionFile, `${[header, ...entries].map((entry) => JSON.stringify(entry)).join("\n")}\n`, ); return sessionFile; } function createTargetSession( ctx: ExtensionCommandContext, targetCwd: string, ): string { const sessionDir = configuredSessionDir(targetCwd); const sourceFile = sessionFileExists(ctx); if (sourceFile) { const forked = SessionManager.forkFrom(sourceFile, targetCwd, sessionDir); const forkedFile = forked.getSessionFile(); if (!forkedFile) throw new Error("Failed to fork session into target cwd"); return forkedFile; } return createSessionFileFromMemory(ctx, targetCwd, sessionDir); } export default function (pi: ExtensionAPI) { pi.registerCommand("cwd", { description: "Switch Pi cwd by moving current session into target directory", getArgumentCompletions: (prefix) => { if (prefix.trim().length > 0) return null; return [ { value: ".", label: ".", description: "current cwd" }, { value: "..", label: "..", description: "parent cwd" }, { value: "~", label: "~", description: "home cwd" }, ]; }, handler: async (args, ctx) => { if (!args.trim()) { ctx.ui.notify(`cwd: ${ctx.cwd}`, "info"); return; } const targetCwd = resolveTarget(args, ctx.cwd); const error = assertDirectory(targetCwd); if (error) { ctx.ui.notify(error, "error"); return; } if (targetCwd === ctx.cwd) { ctx.ui.notify(`cwd already: ${targetCwd}`, "info"); return; } await ctx.waitForIdle(); const targetSessionFile = createTargetSession(ctx, targetCwd); await ctx.switchSession(targetSessionFile, { withSession: async (ctx) => { ctx.ui.notify(`cwd → ${ctx.cwd}`, "info"); }, }); }, }); }