notify.ts 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. /**
  2. * Pi Notify Extension
  3. *
  4. * Sends a native terminal notification when Pi agent is done and waiting for input.
  5. * Supports multiple terminal protocols:
  6. * - OSC 777: Ghostty, iTerm2, WezTerm, rxvt-unicode
  7. * - OSC 99: Kitty
  8. * - Windows toast: Windows Terminal (WSL)
  9. */
  10. import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
  11. function windowsToastScript(title: string, body: string): string {
  12. const type = "Windows.UI.Notifications";
  13. const mgr = `[${type}.ToastNotificationManager, ${type}, ContentType = WindowsRuntime]`;
  14. const template = `[${type}.ToastTemplateType]::ToastText01`;
  15. const toast = `[${type}.ToastNotification]::new($xml)`;
  16. return [
  17. `${mgr} > $null`,
  18. `$xml = [${type}.ToastNotificationManager]::GetTemplateContent(${template})`,
  19. `$xml.GetElementsByTagName('text')[0].AppendChild($xml.CreateTextNode('${body}')) > $null`,
  20. `[${type}.ToastNotificationManager]::CreateToastNotifier('${title}').Show(${toast})`,
  21. ].join("; ");
  22. }
  23. function notifyOSC777(title: string, body: string): void {
  24. process.stdout.write(`\x1b]777;notify;${title};${body}\x07`);
  25. }
  26. function notifyOSC99(title: string, body: string): void {
  27. // Kitty OSC 99: i=notification id, d=0 means not done yet, p=body for second part
  28. process.stdout.write(`\x1b]99;i=1:d=0;${title}\x1b\\`);
  29. process.stdout.write(`\x1b]99;i=1:p=body;${body}\x1b\\`);
  30. }
  31. function notifyWindows(title: string, body: string): void {
  32. const { execFile } = require("child_process");
  33. execFile("powershell.exe", ["-NoProfile", "-Command", windowsToastScript(title, body)]);
  34. }
  35. function notify(title: string, body: string): void {
  36. if (process.env.WT_SESSION) {
  37. notifyWindows(title, body);
  38. } else if (process.env.KITTY_WINDOW_ID) {
  39. notifyOSC99(title, body);
  40. } else {
  41. notifyOSC777(title, body);
  42. }
  43. }
  44. export default function (pi: ExtensionAPI) {
  45. pi.on("agent_end", async () => {
  46. notify("Pi", "Ready for input");
  47. });
  48. }