import { spawnSync } from "node:child_process"; import { randomUUID } from "node:crypto"; import { existsSync, promises as fs } from "node:fs"; import path from "node:path"; import type { ExtensionAPI, ExtensionCommandContext, } from "@earendil-works/pi-coding-agent"; const GHOSTTY_SPLIT_SCRIPT = `on run argv set targetCwd to item 1 of argv set startupInput to item 2 of argv tell application "Ghostty" set cfg to new surface configuration set initial working directory of cfg to targetCwd set initial input of cfg to startupInput if (count of windows) > 0 then try set frontWindow to front window set targetTerminal to focused terminal of selected tab of frontWindow split targetTerminal direction right with configuration cfg on error new window with configuration cfg end try else new window with configuration cfg end if activate end tell end run`; function shellQuote(value: string): string { if (value.length === 0) return "''"; return `'${value.replace(/'/g, `'"'"'`)}'`; } function getPiInvocationParts(): string[] { const currentScript = process.argv[1]; if (currentScript && existsSync(currentScript)) { return [process.execPath, currentScript]; } const execName = path.basename(process.execPath).toLowerCase(); if (!/^(node|bun)(\.exe)?$/.test(execName)) return [process.execPath]; return ["pi"]; } function buildPiStartupInput( sessionFile: string | undefined, prompt: string, ): string { const commandParts = [...getPiInvocationParts()]; if (sessionFile) commandParts.push("--session", sessionFile); if (prompt) commandParts.push("--", prompt); return `${commandParts.map(shellQuote).join(" ")}\n`; } function hasOsascript(): boolean { const result = spawnSync("osascript", ["-e", "return 1"], { stdio: "ignore", }); return !result.error && result.status === 0; } async function createForkedSession( ctx: ExtensionCommandContext, ): Promise { const sessionFile = ctx.sessionManager.getSessionFile(); if (!sessionFile) return undefined; const sessionDir = path.dirname(sessionFile); const branchEntries = ctx.sessionManager.getBranch(); const currentHeader = ctx.sessionManager.getHeader(); const timestamp = new Date().toISOString(); const newSessionId = randomUUID(); const newSessionFile = path.join( sessionDir, `${timestamp.replace(/[:.]/g, "-")}_${newSessionId}.jsonl`, ); const newHeader = { type: "session", version: currentHeader?.version ?? 3, id: newSessionId, timestamp, cwd: currentHeader?.cwd ?? ctx.cwd, parentSession: sessionFile, }; const lines = [ JSON.stringify(newHeader), ...branchEntries.map((entry) => JSON.stringify(entry)), ].join("\n"); await fs.mkdir(sessionDir, { recursive: true }); await fs.writeFile(newSessionFile, `${lines}\n`, "utf8"); return newSessionFile; } export const __test = { buildPiStartupInput, shellQuote }; export default function splitForkExtension(pi: ExtensionAPI) { pi.on("session_start", (_event, ctx) => { if (process.platform === "darwin" && !hasOsascript() && ctx.hasUI) { ctx.ui.notify( "split-fork: osascript not found; /split-fork unavailable", "warning", ); } }); pi.registerCommand("split-fork", { description: "Fork this session into a new Pi process in a right-hand Ghostty split. Usage: /split-fork [prompt]", handler: async (args, ctx) => { if (process.platform !== "darwin") { ctx.ui.notify( "/split-fork requires macOS, Ghostty, and osascript.", "warning", ); return; } if (!hasOsascript()) { ctx.ui.notify("/split-fork requires osascript on PATH.", "error"); return; } const wasBusy = !ctx.isIdle(); const prompt = args.trim(); const forkedSessionFile = await createForkedSession(ctx); const startupInput = buildPiStartupInput(forkedSessionFile, prompt); const result = await pi.exec("osascript", [ "-e", GHOSTTY_SPLIT_SCRIPT, "--", ctx.cwd, startupInput, ]); if (result.code !== 0) { const reason = result.stderr?.trim() || result.stdout?.trim() || "unknown osascript error"; ctx.ui.notify(`Failed to launch Ghostty split: ${reason}`, "error"); if (forkedSessionFile) { ctx.ui.notify( `Forked session was created: ${forkedSessionFile}`, "info", ); } return; } if (!forkedSessionFile) { ctx.ui.notify( "Opened a Ghostty split without a persisted session.", "warning", ); return; } const suffix = prompt ? " and sent prompt" : ""; ctx.ui.notify( `Forked to ${path.basename(forkedSessionFile)} in a Ghostty split${suffix}.`, "info", ); if (wasBusy) { ctx.ui.notify( "Forked from committed session state; in-flight turn continues here.", "info", ); } }, }); }