import { existsSync } from "node:fs"; import { join } from "node:path"; import { withOwner } from "./historyOwner.js"; type Outcome = { ok: true; value: T } | { ok: false; error: unknown }; async function settle(write: () => Promise | T): Promise> { try { return { ok: true, value: await write() }; } catch (error) { return { ok: false, error }; } } // One history entry labelled with the command; an open agent turn already takes the writes. // Best effort: a busy or unreadable history never fails the command. export async function withCliWrites( projectDir: string, command: string, write: () => Promise | T, ): Promise { let outcome: Outcome | undefined; if (existsSync(join(projectDir, "index.html"))) { await withOwner( projectDir, async (owner, turn) => { const close = turn ? null : await owner.window(`hyperframes ${command}`); outcome = await settle(write); await close?.(); }, { ownerWaitMs: 0 }, ).catch(() => {}); } outcome ??= await settle(write); if (!outcome.ok) throw outcome.error; return outcome.value; }