repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by bugabinga

pi/agent/extensions/ghost/index.ts

Raw
File outline
import {
  type AgentSession,
  type AgentSessionEvent,
  createAgentSession,
  type ExtensionAPI,
  type ExtensionContext,
  SessionManager,
} from "@earendil-works/pi-coding-agent";
import { truncateToWidth, type OverlayHandle, type TUI } from "@earendil-works/pi-tui";
import { GhostOverlayComponent } from "./overlay.js";
import { loadGhostConfig, type GhostConfig, type GhostConfigError } from "./config.js";

type GhostUi = Pick<ExtensionContext["ui"], "notify" | "setWidget">;

type GhostContext = Pick<ExtensionContext, "cwd" | "model" | "modelRegistry" | "ui">;

interface GhostRuntimeState {
  session: AgentSession | null;
  sessionCwd: string | null;
  modelLabel: string | null;
  overlayHandle: OverlayHandle | null;
  overlay: GhostOverlayComponent | null;
  unsubscribeSession: (() => void) | null;
  eventLog: AgentSessionEvent[];
  config: GhostConfig | null;
}

type GhostOverlayResult = "hide" | "close";

const WIDGET_KEY = "pi-ghost";
const COMMAND = "ghost";
const UNKNOWN_MODEL = "unknown-model";
const HIDDEN_WIDGET_TEXT = "is running • run /ghost to bring it back";

export default function (pi: ExtensionAPI) {
  const state: GhostRuntimeState = {
    session: null,
    sessionCwd: null,
    modelLabel: null,
    overlayHandle: null,
    overlay: null,
    unsubscribeSession: null,
    eventLog: [],
    config: null,
  };

  const loadConfig = (ctx: GhostContext): GhostConfig => {
    const config = loadGhostConfig(ctx.cwd, (error) => notifyConfigError(ctx.ui, error));
    state.config = config;
    return config;
  };

  const cleanupGhost = (ui?: Pick<GhostUi, "setWidget">): void => {
    state.overlayHandle?.hide();
    state.overlayHandle = null;
    state.overlay = null;
    state.unsubscribeSession?.();
    state.unsubscribeSession = null;
    state.session?.dispose();
    state.session = null;
    state.sessionCwd = null;
    state.modelLabel = null;
    state.eventLog = [];
    ui?.setWidget(WIDGET_KEY, undefined);
  };

  const ensureGhostSession = async (ctx: ExtensionContext): Promise<AgentSession> => {
    if (state.session) return state.session;
    if (!ctx.model) throw new Error("No model selected");

    const config = state.config ?? loadConfig(ctx);
    const model = config.model?.provider && config.model?.id
      ? ctx.modelRegistry.find(config.model.provider, config.model.id) ?? ctx.model
      : ctx.model;

    const result = await createAgentSession({
      cwd: ctx.cwd,
      model,
      modelRegistry: ctx.modelRegistry,
      sessionManager: SessionManager.inMemory(ctx.cwd),
    });

    state.session = result.session;
    state.sessionCwd = ctx.cwd;
    state.modelLabel = model.id;
    state.eventLog = [];
    state.unsubscribeSession = result.session.subscribe((event) => {
      state.eventLog.push(event);
      state.overlay?.handleSessionEvent(event);
    });
    return result.session;
  };

  const openGhostOverlay = async (
    ctx: ExtensionContext,
    initialPrompt?: string,
  ): Promise<void> => {
    const config = state.config ?? loadConfig(ctx);
    const session = await ensureGhostSession(ctx);
    const prompt = initialPrompt?.trim();

    ctx.ui.setWidget(WIDGET_KEY, undefined);

    void ctx.ui.custom<GhostOverlayResult>(
      (tui, theme, _keybindings, done) => {
        const overlay = new GhostOverlayComponent({
          tui,
          theme,
          sessionCwd: state.sessionCwd ?? ctx.cwd,
          modelLabel: state.modelLabel ?? ctx.model?.id ?? UNKNOWN_MODEL,
          maxHeight: config.overlay.maxHeight,
          margin: config.overlay.margin,
          onSubmitMessage: (text) => void session.prompt(text, { images: [] }),
          onHideOverlay: () => {
            state.overlayHandle = null;
            done("hide");
          },
          onCloseOverlay: () => {
            state.overlayHandle = null;
            done("close");
          },
        });
        state.overlay = overlay;
        if (state.eventLog.length > 0) overlay.loadEvents(state.eventLog);
        else overlay.loadMessages(session.messages, session.isStreaming);

        if (prompt) void session.prompt(prompt, { images: [] });

        return {
          render: (width: number) => overlay.render(width),
          invalidate: () => overlay.invalidate(),
          handleInput: (data: string) => overlay.handleInput(data),
          get focused() {
            return overlay.focused;
          },
          set focused(value: boolean) {
            overlay.focused = value;
          },
          dispose: () => {
            if (state.overlay === overlay) state.overlay = null;
          },
        };
      },
      {
        overlay: true,
        overlayOptions: {
          anchor: config.overlay.anchor,
          width: config.overlay.width,
          maxHeight: config.overlay.maxHeight,
          margin: config.overlay.margin,
        },
        onHandle: (handle) => {
          state.overlayHandle = handle;
        },
      },
    )
      .then((result) => {
        state.overlayHandle = null;
        if (result === "hide" && state.session) {
          ctx.ui.setWidget(WIDGET_KEY, hiddenWidget, { placement: "aboveEditor" });
          return;
        }
        cleanupGhost(ctx.ui);
      })
      .catch(() => cleanupGhost(ctx.ui));
  };

  const showOrPromptGhost = async (
    ctx: ExtensionContext,
    prompt?: string,
  ): Promise<void> => {
    const handle = state.overlayHandle;
    if (!handle) return openGhostOverlay(ctx, prompt);

    if (!prompt) {
      handle.focus();
      return;
    }

    const session = await ensureGhostSession(ctx);
    void session.prompt(prompt, { images: [] });
  };

  pi.registerCommand(COMMAND, {
    description: "Open ghost pi overlay",
    handler: async (args, ctx) => {
      if (!ctx.hasUI) {
        ctx.ui.notify("/ghost requires interactive mode", "error");
        return;
      }

      await showOrPromptGhost(ctx, args.trim() || undefined);
    },
  });

  pi.registerShortcut("alt+g", {
    description: "Open ghost pi overlay",
    handler: async (ctx) => {
      if (!ctx.hasUI) return;
      await showOrPromptGhost(ctx);
    },
  });

  pi.on("session_start", async (_event, ctx) => {
    loadConfig(ctx);
  });

  pi.on("session_shutdown", async (_event, ctx) => {
    cleanupGhost(ctx.ui);
  });
}

function hiddenWidget(_tui: TUI, theme: ExtensionContext["ui"]["theme"]) {
  return {
    render: (width: number) => [
      truncateToWidth(
        theme.fg("accent", "/ghost ") + theme.fg("dim", HIDDEN_WIDGET_TEXT),
        width,
      ),
    ],
    invalidate: () => {},
  };
}

function notifyConfigError(ui: Pick<GhostUi, "notify">, error: GhostConfigError): void {
  ui.notify(`Ignored ${error.path}: ${error.message}`, "warning");
}