repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by bugabinga

pi/agent/extensions/notify.ts

Raw
File outline
/**
 * Pi Notify Extension
 *
 * Sends a native terminal notification when Pi agent is done and waiting for input.
 * Notifications are suppressed when the terminal is focused — you're already looking.
 *
 * Also relays `notify:send` events from other extensions.
 *
 * Supports: OSC 777 (Ghostty, iTerm2, WezTerm), OSC 99 (Kitty), Windows toast.
 *
 * Focus detection via DECSET ?1004 from lib/focus.ts.
 * Based on tmustier/pi-extensions (session-recap).
 * MIT License — https://github.com/tmustier/pi-extensions
 */

import type { ExtensionAPI } from "@mariozechner/pi-coding-agent";
import * as focus from "../../lib/focus";

export interface NotifyPayload {
  message: string;
  severity?: "info" | "warning" | "error";
  source?: string;
}

function windowsToastScript(title: string, body: string): string {
  const type = "Windows.UI.Notifications";
  const mgr =
    `[${type}.ToastNotificationManager, ${type}, ContentType = WindowsRuntime]`;
  const template = `[${type}.ToastTemplateType]::ToastText01`;
  const toast = `[${type}.ToastNotification]::new($xml)`;
  return [
    `${mgr} > $null`,
    `$xml = [${type}.ToastNotificationManager]::GetTemplateContent(${template})`,
    `$xml.GetElementsByTagName('text')[0].AppendChild($xml.CreateTextNode('${body}')) > $null`,
    `[${type}.ToastNotificationManager]::CreateToastNotifier('${title}').Show(${toast})`,
  ].join("; ");
}

function notifyOSC777(title: string, body: string): void {
  process.stdout.write(`\x1b]777;notify;${title};${body}\x07`);
}

function notifyOSC99(title: string, body: string): void {
  process.stdout.write(`\x1b]99;i=1:d=0;${title}\x1b\\`);
  process.stdout.write(`\x1b]99;i=1:p=body;${body}\x1b\\`);
}

function notifyWindows(title: string, body: string): void {
  const { execFile } = require("child_process");
  execFile("powershell.exe", [
    "-NoProfile",
    "-Command",
    windowsToastScript(title, body),
  ]);
}

function notify(title: string, body: string): void {
  if (process.env.WT_SESSION) {
    notifyWindows(title, body);
  } else if (process.env.KITTY_WINDOW_ID) {
    notifyOSC99(title, body);
  } else {
    notifyOSC777(title, body);
  }
}

export default function (pi: ExtensionAPI) {
  pi.on("session_start", async () => {
    focus.attach();
  });

  // Notify when agent finishes — only if terminal is unfocused
  pi.on("agent_end", async () => {
    if (!focus.isFocused()) {
      notify("Pi", "Ready for input");
    }
  });

  // Also notify on focus-in if agent had already finished while away
  const onFocusChange = (isFocused: boolean) => {
    // No need to notify when coming back — terminal-signals handles
    // the tab badge. This is for external events via notify:send.
  };

  focus.onFocus(onFocusChange);

  // Relay notify:send events from other extensions (always send regardless of focus)
  pi.events.on("notify:send", (data: unknown) => {
    const payload = data as NotifyPayload;
    const source = payload.source ?? "unknown";
    const message = payload.message ?? "";
    const severity = payload.severity ?? "info";

    pi.events.emit("notify:ui", { message, severity, source });

    const prefix = severity === "warning" ? "⚠️ " : severity === "error" ? "❌ " : "";
    notify(source, `${prefix}${message}`);
  });

  pi.on("session_shutdown", async () => {
    focus.offFocus(onFocusChange);
    focus.detach();
  });
}