import { appendFileSync, existsSync, readdirSync, readFileSync, statSync, writeFileSync, } from "node:fs"; import { basename, isAbsolute, join, relative, resolve } from "node:path"; import { StringEnum } from "@earendil-works/pi-ai"; import { type ExtensionAPI, type ExtensionCommandContext, type ExtensionContext, getAgentDir, ProjectTrustStore, SessionManager, } from "@earendil-works/pi-coding-agent"; import { Container, Text } from "@earendil-works/pi-tui"; import { type Static, Type } from "typebox"; import { Check } from "typebox/value"; /** * Repository backends, such as the jj extension, answer these requests. Resolve sets `root` to the * main checkout of the repository holding `cwd`, and `workspace` to the root of the workspace * holding `cwd`. Create and remove set `result` to a promise. */ const RESOLVE_EVENT = "workspaces:resolve"; const CREATE_EVENT = "workspaces:create"; const REMOVE_EVENT = "workspaces:remove"; /** * Extensions add to `busy` a short description of running work that a session move cancels, such * as "2 subagents". */ const BUSY_EVENT = "workspaces:busy"; const ROOT = Type.String({ minLength: 1 }); const Config = Type.Object( { root: Type.Optional(Type.String({ minLength: 1 })), revision: Type.Optional(Type.String({ minLength: 1 })), setup: Type.Optional(Type.String({ minLength: 1 })), teardown: Type.Optional(Type.String({ minLength: 1 })), }, { additionalProperties: false }, ); const NAME_PATTERN = "^[A-Za-z0-9][A-Za-z0-9._-]*$"; /** The name of the main checkout. */ const MAIN = "default"; const Action = StringEnum(["create", "switch", "remove"] as const); const COMMANDS = ["switch", "remove"] as const; const Command = StringEnum(COMMANDS); const USAGE = "Usage: /workspace switch [revision] | remove "; const Params = Type.Object( { action: Action, name: Type.String({ pattern: NAME_PATTERN, maxLength: 100, description: `Workspace name. "${MAIN}" is the main checkout.`, }), revision: Type.Optional( Type.String({ minLength: 1, description: "Base revision for create" }), ), }, { additionalProperties: false }, ); interface Repository { main: string; workspaces: string; config: Static; } interface Removal { repo: Repository; path: string; } interface Move { target: string; remove?: Removal; /** A workspace that the tool created for this move, removed if the move cannot happen. */ created?: Removal; /** An existing session file to open instead of a fork. */ file?: string; parent?: string; workspace?: string; } interface Outcome { move?: Move; message: string; } interface ResolveRequest { cwd: string; root?: unknown; } interface BusyRequest { busy: string[]; } interface WorkspaceRequest { root: string; path: string; revision?: string; result?: unknown; } function repository(pi: ExtensionAPI, ctx: ExtensionContext): Repository { const request: ResolveRequest = { cwd: ctx.cwd }; pi.events.emit(RESOLVE_EVENT, request); if (!Check(ROOT, request.root)) { throw new Error("The working directory is not in a repository with workspace support."); } const main = request.root; const file = join(main, ".pi", "extensions", "workspaces", "config.json"); let config: Static = {}; // Trust of `cwd` does not cover the `.pi` directory of the main checkout. const trusted = main === ctx.cwd ? ctx.isProjectTrusted() : new ProjectTrustStore(getAgentDir()).get(main) === true; if (trusted && existsSync(file)) { const parsed: ReturnType = JSON.parse(readFileSync(file, "utf8")); if (!Check(Config, parsed)) { throw new Error(`Invalid workspace config: ${file}`); } config = parsed; } return { main, config, workspaces: resolve(main, config.root ?? ".workspaces") }; } function inside(dir: string, path: string): boolean { const rel = relative(dir, path); return !rel.startsWith("..") && !isAbsolute(rel); } function isDirectory(path: string): boolean { return statSync(path, { throwIfNoEntry: false })?.isDirectory() ?? false; } function named(repo: Repository, name: string): string { if (name === MAIN) { return repo.main; } if (!new RegExp(NAME_PATTERN).test(name)) { throw new Error(`Invalid workspace name: ${name}`); } return join(repo.workspaces, name); } function names(repo: Repository): string[] { const entries = existsSync(repo.workspaces) ? readdirSync(repo.workspaces, { withFileTypes: true }) : []; return [ MAIN, ...entries .filter((entry) => entry.isDirectory() && new RegExp(NAME_PATTERN).test(entry.name)) .map((entry) => entry.name), ]; } async function request(pi: ExtensionAPI, event: string, data: WorkspaceRequest): Promise { pi.events.emit(event, data); if (!data.result) { throw new Error("No repository backend handles workspaces here."); } await Promise.resolve(data.result); } /** Runs a repository script in `cwd`, and throws `failure` with the script output if it fails. */ async function run( pi: ExtensionAPI, repo: Repository, script: string, cwd: string, failure: string, ) { const result = await pi.exec(resolve(repo.main, script), [repo.main], { cwd, timeout: 300_000, }); if (result.code !== 0 || result.killed) { throw new Error(`${failure}:\n${(result.stderr || result.stdout).trim()}`); } } async function create(pi: ExtensionAPI, repo: Repository, target: string, revision?: string) { if (existsSync(target)) { throw new Error(`${target} exists. Use switch.`); } const data: WorkspaceRequest = { root: repo.main, path: target }; const base = revision ?? repo.config.revision; if (base) { data.revision = base; } await request(pi, CREATE_EVENT, data); if (repo.config.setup) { await run(pi, repo, repo.config.setup, target, `Created ${target}, but its setup failed`); } } async function remove(pi: ExtensionAPI, { repo, path }: Removal) { if (repo.config.teardown) { await run( pi, repo, repo.config.teardown, path, `Did not remove ${path}: its teardown failed`, ); } await request(pi, REMOVE_EVENT, { root: repo.main, path }); } /** The session that this session forked from, if it is in the repository. */ function parentSession(ctx: ExtensionContext, repo: Repository) { const file = ctx.sessionManager.getHeader()?.parentSession; if (!file || !existsSync(file)) { return undefined; } const cwd = SessionManager.open(file).getCwd(); return isDirectory(cwd) && [repo.main, repo.workspaces].some((dir) => inside(dir, cwd)) ? { file, cwd } : undefined; } /** Appends the conversation to `parent`, unless `parent` has entries that this session lacks. */ function rejoin(ctx: ExtensionCommandContext, parent: string): boolean { const before = SessionManager.open(parent); if (!before.getEntries().every((entry) => ctx.sessionManager.getEntry(entry.id))) { return false; } const added = ctx.sessionManager.getEntries().filter((entry) => !before.getEntry(entry.id)); appendFileSync(parent, added.map((entry) => `${JSON.stringify(entry)}\n`).join("")); const name = before.getSessionName(); if (name && ctx.sessionManager.getSessionName()?.endsWith(` [${basename(ctx.cwd)}]`)) { SessionManager.open(parent).appendSessionInfo(name); } return true; } /** A session file for `target` that continues the current conversation. */ function sessionIn( ctx: ExtensionCommandContext, target: string, workspace?: string, ): string | undefined { const file = ctx.sessionManager.getSessionFile(); const dir = ctx.sessionManager.getSessionDir(); if (file && existsSync(file)) { const session = SessionManager.forkFrom(file, target, dir); const name = ctx.sessionManager.getSessionName(); if (name) { const suffix = ` [${basename(ctx.cwd)}]`; const base = name.endsWith(suffix) ? name.slice(0, -suffix.length) : name; const next = workspace ? `${base} [${workspace}]` : base; if (next !== name) { session.appendSessionInfo(next); } } return session.getSessionFile(); } const session = SessionManager.create(target, dir); const path = session.getSessionFile(); if (path) { // Pi writes a session file after the first message, but a switch reads the cwd from it. writeFileSync(path, `${JSON.stringify(session.getHeader())}\n`, { flag: "wx" }); } return path; } function busyError(action: string, name: string, work: string): Error { const verb = action === "switch" ? "switch to" : action; return new Error( `Cannot ${verb} workspace ${name} while work runs: ${work}. Wait for the work to finish or stop it, then retry.`, ); } function busyWork(pi: ExtensionAPI): string { const request: BusyRequest = { busy: [] }; pi.events.emit(BUSY_EVENT, request); return request.busy.join(", "); } async function act( pi: ExtensionAPI, ctx: ExtensionContext, action: Static, name: string, cancelWork: (work: string) => Promise, revision?: string, ): Promise { const repo = repository(pi, ctx); const target = named(repo, name); if (action !== "remove" || inside(target, ctx.cwd)) { if (!ctx.sessionManager.getSessionFile()) { throw new Error("This session is not saved, so it cannot move to another workspace."); } const work = busyWork(pi); if (work && !(await cancelWork(work))) { throw busyError(action, name, work); } } const workspace = name === MAIN ? undefined : name; if (action === "create") { await create(pi, repo, target, revision); return { move: { target, workspace, created: { repo, path: target } }, message: `Created ${target}. The session moves there after this response.`, }; } if (!isDirectory(target)) { throw new Error(`No workspace is at ${target}.`); } if (action === "switch") { if (target === ctx.cwd) { throw new Error(`The session is already in ${target}.`); } const parent = parentSession(ctx, repo); return { move: { target, workspace, parent: parent?.cwd === target ? parent.file : undefined }, message: `The session moves to ${target} after this response.`, }; } if (target === repo.main) { throw new Error("The main checkout cannot be removed."); } if (inside(target, ctx.cwd)) { const parent = parentSession(ctx, repo); const back = parent && !inside(target, parent.cwd) ? parent : undefined; const home = back?.cwd ?? repo.main; return { move: { target: home, remove: { repo, path: target }, parent: back?.file, workspace: home === repo.main ? undefined : basename(home), }, message: `The session moves to ${home} and removes ${target} after this response.`, }; } await remove(pi, { repo, path: target }); return { message: `Removed ${target}. Its changes stay in the repository.` }; } async function move( pi: ExtensionAPI, ctx: ExtensionCommandContext, step: Move, resume: boolean, ): Promise { if (step.remove) { await remove(pi, step.remove); } const file = step.file ?? (step.parent && rejoin(ctx, step.parent) ? step.parent : sessionIn(ctx, step.target, step.workspace)); if (!file) { throw new Error("This session is not saved, so it cannot move."); } await ctx.switchSession(file, { withSession: async (next) => { if (resume) { await next.sendMessage( { customType: "workspace", content: `The session moved to ${step.target}. Continue the task.`, display: true, }, { triggerTurn: true }, ); } else if (step.remove) { next.ui.notify(`Removed ${step.remove.path}`, "info"); } }, }); } function text(value: string) { return { content: [{ type: "text" as const, text: value }], details: undefined }; } export default function workspaces(pi: ExtensionAPI) { let pending: Move | undefined; let context: ExtensionContext | undefined; pi.registerTool({ name: "workspace", label: "Workspace", annotations: { readOnlyHint: false, destructiveHint: true, openWorldHint: false }, description: "Create, switch to, or remove a workspace: a separate working copy of this repository. After create, switch, or remove of the current workspace, the session moves when your response ends.", promptSnippet: "Create, switch to, or remove separate working copies of the repository", promptGuidelines: [ "Use workspace create only when the user or project instructions ask for workspaces, or when another change is already in progress in this checkout.", "After workspace create, switch, or remove of the current workspace, end your response without other tool calls.", "Remove a workspace you created when its work is done. Its changes stay in the repository.", ], parameters: Params, renderCall(args, theme) { const revision = args.revision ? theme.fg("muted", ` from ${args.revision}`) : ""; return new Text( `${theme.fg("toolTitle", theme.bold("workspace"))} ${args.action ?? "..."} ${theme.fg("accent", args.name ?? "...")}${revision}`, 0, 0, ); }, renderResult(result, { expanded }, theme, { isError }) { const output = result.content.map((part) => (part.type === "text" ? part.text : "")); if (!isError && !expanded) { return new Container(); } return new Text(theme.fg(isError ? "error" : "toolOutput", output.join("\n")), 0, 0); }, async execute(_id, params, _signal, _onUpdate, ctx) { const outcome = await act( pi, ctx, params.action, params.name, async () => false, params.revision, ); pending = outcome.move; return text(outcome.message); }, }); pi.registerCommand("workspace", { description: "Switch to a workspace, creating it if needed, or remove one", getArgumentCompletions(prefix) { const match = /^(switch|remove)\s+(\S*)$/.exec(prefix); if (!match) { const items = COMMANDS.filter((action) => action.startsWith(prefix)).map( (action) => ({ value: action, label: action }), ); return items.length ? items : null; } const [, action, start = ""] = match; let repo: Repository; try { if (!context) { return null; } repo = repository(pi, context); } catch { return null; } const items = names(repo) .filter((name) => name.startsWith(start) && !(action === "remove" && name === MAIN)) .map((name) => ({ value: `${action} ${name}`, label: name })); return items.length ? items : null; }, handler: async (args, ctx) => { const step = pending; pending = undefined; if (step) { // The agent can start work after its workspace call, and a session move cancels that work. const work = busyWork(pi); if (work) { if (step.created) { await remove(pi, step.created); } const error = step.remove ? busyError("remove", basename(step.remove.path), work) : busyError( step.created ? "create" : "switch", step.workspace ?? MAIN, work, ); pi.sendMessage({ customType: "workspace", content: error.message, display: true, }); return; } // The agent continues after its own create or switch, not after removal or reopening. await move(pi, ctx, step, !step.remove && !step.file); return; } const [action, name, revision, ...rest] = args.trim().split(/\s+/); if ( !Check(Command, action) || !name || rest.length || (revision && action !== "switch") ) { throw new Error(USAGE); } const missing = action === "switch" && !existsSync(named(repository(pi, ctx), name)); const outcome = await act( pi, ctx, missing ? "create" : action, name, (work) => ctx.ui.confirm("Cancel running work?", `The session move cancels ${work}.`), revision, ); if (outcome.move) { await move(pi, ctx, outcome.move, false); } else { ctx.ui.notify(outcome.message, "info"); } }, }); pi.on("session_start", (event, ctx) => { context = ctx; const file = ctx.sessionManager.getSessionFile(); const recorded = ctx.sessionManager.getHeader()?.cwd; // `pi -c` continues the newest session in the launch directory, even a workspace session. if ( event.reason === "startup" && ctx.hasUI && file && recorded && recorded !== ctx.cwd && isDirectory(recorded) ) { pending = { target: recorded, file }; pi.sendUserMessage("/workspace", { expandPromptTemplates: true }); } }); pi.on("agent_settled", () => { if (pending) { pi.sendUserMessage("/workspace", { expandPromptTemplates: true }); } }); }