repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by bugabinga

pi/agent/extensions/context-size/index.ts

Raw
File outline
import type {
  ContextUsage,
  ExtensionAPI,
  ExtensionContext,
  ThemeColor,
} from "@earendil-works/pi-coding-agent";

const FOOTER_SEGMENT = {
  id: "context-size",
  icon: "",
  zone: "llm",
  order: 1,
} as const;

const LIMITS = {
  warningPercent: 70,
  errorPercent: 85,
} as const;

const TOKEN_UNIT = 1000;

const BAR = {
  width: 10,
  cellSteps: 8,
  empty: "⠀",
  full: "⣿",
  partials: ["⠀", "⡀", "⡄", "⡆", "⡇", "⣇", "⣧", "⣷", "⣿"],
} as const;

const UPDATE_EVENTS = [
  "session_start",
  "agent_start",
  "turn_end",
  "agent_end",
  "model_select",
  "session_compact",
] as const;

type SegmentView = {
  text: string;
  color: ThemeColor;
};

function clamp(value: number, min: number, max: number): number {
  return Math.min(max, Math.max(min, value));
}

function toneForPercent(percent: number | null): ThemeColor {
  if (percent === null) return "muted";
  if (percent >= LIMITS.errorPercent) return "error";
  if (percent >= LIMITS.warningPercent) return "warning";
  return "muted";
}

function barTone(textTone: ThemeColor): ThemeColor {
  return textTone === "muted" ? "dim" : textTone;
}

function percentToBrailleSteps(percent: number | null): number {
  if (percent === null) return 0;
  const maxSteps = BAR.width * BAR.cellSteps;
  return clamp(Math.round((percent / 100) * maxSteps), 0, maxSteps);
}

function renderBrailleBar(percent: number | null): string {
  const steps = percentToBrailleSteps(percent);
  const fullCells = Math.floor(steps / BAR.cellSteps);
  const partialSteps = steps % BAR.cellSteps;
  const partialCell = fullCells < BAR.width ? BAR.partials[partialSteps] : "";
  const emptyCells = BAR.empty.repeat(Math.max(0, BAR.width - fullCells - 1));

  return BAR.full.repeat(fullCells) + partialCell + emptyCells;
}

function formatTokenRatio(tokens: number | null, contextWindow: number): string {
  const total = String(Math.round(contextWindow / TOKEN_UNIT));
  const used = tokens === null
    ? "?".repeat(total.length)
    : String(Math.round(tokens / TOKEN_UNIT)).padStart(total.length, "0");

  return `${used}⁄${total}`;
}

function buildSegment(ctx: ExtensionContext, usage: ContextUsage): SegmentView {
  const percent = usage.percent ?? null;
  const textTone = toneForPercent(percent);
  const ratio = formatTokenRatio(usage.tokens, usage.contextWindow);
  const bar = ctx.ui.theme.fg(barTone(textTone), renderBrailleBar(percent));

  return {
    text: `${ratio} ${bar}`,
    color: textTone,
  };
}

export default function contextSizeExtension(pi: ExtensionAPI) {
  function clearSegment() {
    pi.events.emit("footer:segment", { id: FOOTER_SEGMENT.id, text: undefined });
  }

  function updateSegment(ctx: ExtensionContext) {
    try {
      if (!ctx.hasUI) return;

      const usage = ctx.getContextUsage();
      if (!usage) {
        clearSegment();
        return;
      }

      const view = buildSegment(ctx, usage);
      pi.events.emit("footer:segment", {
        ...FOOTER_SEGMENT,
        text: view.text,
        color: view.color,
      });
    } catch {
      // Ignore late events during reload/switch/shutdown; Pi marks old ctx/pi stale.
    }
  }

  for (const eventName of UPDATE_EVENTS) {
    pi.on(eventName, async (_event, ctx) => updateSegment(ctx));
  }

  // Footer owns its own teardown. Emitting through `pi.events` during session_shutdown
  // can trip Pi's stale-context guard after reload/switch.
}