repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

feat: replace terminal notifier with os notifier

92dfbc3b1ba62503753ef4e1e16b2d79dd99fd96

Oliver Jan Krylow <oliver@bugabinga.net> ·

unsigned

Browse filesCompare with HEAD

Changed files (15)

README.md

Modified
97 97 | `split-fork` | Fork Pi into a Ghostty split. | [README](extensions/split-fork/README.md) |
98 98 | `ssh-tools` | SSH mode for Pi with remote read/write/edit/bash tools. | [README](extensions/ssh-tools/README.md) |
99 99 | `the-system` | Task branches and The System skills for Pi. | [README](extensions/the-system/README.md) |
100 -| `terminal-notifier` | Terminal notification bridge for Pi completion and extension events. | [README](extensions/terminal-notifier/README.md) |
100 +| `os-notifier` | Native-first OS notifications for interactive Pi completion. | [README](extensions/os-notifier/README.md) |
101 101 | `terminal-signals` | Terminal lifecycle signals for Pi. | [README](extensions/terminal-signals/README.md) |
102 102 | `terse` | Terse response protocol injector for Pi. | [README](extensions/terse/README.md) |
103 103 | `tldr` | Live TLDR widget above Pi editor. | [README](extensions/tldr/README.md) |

docs/super/plans/2026-07-12-os-notifier.md

Added
new file mode 100644
1 +# OS Notifier Implementation Plan
3 +> **For agentic workers:** REQUIRED SUB-SKILL: Use /skill:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
5 +**Goal:** Replace `terminal-notifier` with a cross-platform, native-first `os-notifier` that only notifies for direct interactive TUI runs.
7 +**Architecture:** Keep the existing reference-counted focus helper. Rebuild `index.ts` around pure formatting/command helpers, minimal in-memory input-origin bookkeeping, and one native spawn whose failure callback emits OSC fallback.
9 +**Tech Stack:** TypeScript, Node.js standard library, Pi extension API, Vitest, Pi test harness
11 +**Roadmap:** None
13 +**Phase:** Single-plan implementation
15 +---
17 +## Task 1: Rename the Extension
19 +**Files:**
21 +- Rename: `extensions/terminal-notifier` to `extensions/os-notifier`
22 +- Modify: `extensions/os-notifier/package.json`
23 +- Modify: `README.md`
24 +- Modify: `package-lock.json`
26 +- [ ] **Step 1: Rename the directory and package metadata**
28 +Run:
30 +```bash
31 +mv extensions/terminal-notifier extensions/os-notifier
32 +```
34 +Change the package name to `@bugabinga/pi-ext-os-notifier`, description to `Native-first OS notifications for Pi.`, and root README table entry/link to `os-notifier`.
36 +- [ ] **Step 2: Regenerate workspace lockfile references**
38 +Run:
40 +```bash
41 +npm install --package-lock-only --ignore-scripts
42 +```
44 +Expected: `package-lock.json` contains `extensions/os-notifier` and no `terminal-notifier` references.
46 +- [ ] **Step 3: Verify rename completeness**
48 +Run:
50 +```bash
51 +rg 'terminal-notifier' README.md package-lock.json extensions/os-notifier
52 +```
54 +Expected: only historical changelog entries remain; package, source, tests, and README use `os-notifier`.
56 +- [ ] **Step 4: Commit the rename**
58 +```bash
59 +git add README.md package-lock.json extensions/terminal-notifier extensions/os-notifier
60 +git commit -m "refactor: rename terminal notifier to os notifier"
61 +```
63 +## Task 2: Specify Native Delivery and Eligibility
65 +**Files:**
67 +- Modify: `extensions/os-notifier/__tests__/harness.test.ts`
68 +- Modify: `extensions/os-notifier/index.ts`
70 +- [ ] **Step 1: Replace old backend tests with failing native command tests**
72 +Add table tests asserting:
74 +```ts
75 +expect(nativeCommand("linux", "Title", "Body", "info")).toEqual({
76 + command: "notify-send",
77 + args: ["--app-name=Pi", "--urgency=low", "Title", "Body"],
78 +});
79 +expect(nativeCommand("darwin", "Title", "Body", "warning").command).toBe(
80 + "osascript",
81 +);
82 +expect(nativeCommand("win32", "Title", "Body", "error").command).toBe(
83 + "powershell.exe",
84 +);
85 +expect(oscBackend({ KITTY_WINDOW_ID: "1" })).toBe("osc99");
86 +expect(oscBackend({})).toBe("osc777");
87 +```
89 +Assert command arguments carry quoted/control-character input as data rather than interpolating it into a shell command.
91 +- [ ] **Step 2: Add failing eligibility state tests**
93 +Export a small `TurnEligibility` class and test:
95 +```ts
96 +const state = new TurnEligibility();
97 +state.input("interactive", undefined);
98 +state.start("tui");
99 +expect(state.end()).toBe(true);
101 +state.input("rpc", undefined);
102 +state.start("tui");
103 +expect(state.end()).toBe(false);
105 +state.input("interactive", "followUp");
106 +state.start("rpc");
107 +expect(state.end()).toBe(false);
108 +```
110 +Add a queued-follow-up test proving input arriving during an active run applies to the next `agent_start`, not the active run.
112 +- [ ] **Step 3: Add failing metadata tests**
114 +Retain existing rich-content assertions and add bounded error-detail and control-character sanitization assertions.
115 +Verify normal, aborted, and error outcomes map to info, warning, and error.
117 +- [ ] **Step 4: Run extension tests and confirm failure**
119 +Run:
121 +```bash
122 +mise run test -- os-notifier
123 +```
125 +Expected: FAIL because native command and eligibility exports do not exist yet.
127 +- [ ] **Step 5: Implement pure formatting, command, and eligibility helpers**
129 +In `index.ts`:
131 +- retain bounded metadata formatting and direct `.git/HEAD` branch lookup
132 +- add `nativeCommand(platform, title, body, severity)` returning executable plus argument array
133 +- encode Windows PowerShell script as UTF-16LE Base64 for `-EncodedCommand`
134 +- pass macOS title/body through `osascript` argv to avoid shell interpolation
135 +- add `oscBackend(env)`
136 +- add minimal active/pending eligibility bookkeeping driven by `input`, `agent_start`, and `agent_end`
137 +- remove `notify:send`, `notify:ui`, startup probes, backend caching, and warning notifications
139 +- [ ] **Step 6: Run extension tests**
141 +Run:
143 +```bash
144 +mise run test -- os-notifier
145 +```
147 +Expected: PASS.
149 +- [ ] **Step 7: Commit behavior**
151 +```bash
152 +git add extensions/os-notifier/index.ts extensions/os-notifier/__tests__/harness.test.ts
153 +git commit -m "feat(os-notifier): add native-first notifications"
154 +```
156 +## Task 3: Verify Native Failure Fallback and Integration
158 +**Files:**
160 +- Modify: `extensions/os-notifier/__tests__/harness.test.ts`
161 +- Modify: `extensions/os-notifier/README.md`
162 +- Modify: `extensions/os-notifier/CHANGELOG.md`
164 +- [ ] **Step 1: Add a failing delivery-path test**
166 +Create a controlled executable in a test temporary directory, prepend it to `PATH`, and exercise the exported delivery function.
167 +Assert exit zero writes no OSC.
168 +Replace it with a nonzero executable and assert exactly one OSC sequence is written.
169 +Use Node file APIs and a platform-appropriate executable fixture; do not invoke shell discovery helpers.
171 +- [ ] **Step 2: Run the focused test and confirm failure**
173 +Run:
175 +```bash
176 +mise run test -- os-notifier
177 +```
179 +Expected: FAIL until delivery exposes completion/failure behavior suitable for deterministic testing.
181 +- [ ] **Step 3: Implement one-shot native delivery with OSC fallback**
183 +Use `execFile(command, args, callback)` without a shell.
184 +On `error` or nonzero command completion, write exactly one selected OSC fallback.
185 +Ignore OSC write errors.
186 +Do not block or throw into Pi lifecycle handlers.
188 +- [ ] **Step 4: Update documentation**
190 +Document:
192 +- TUI plus interactive-input eligibility
193 +- unfocused-only behavior
194 +- Linux/macOS/Windows native commands
195 +- OSC 99/777 failure fallback
196 +- metadata and urgency mapping
197 +- absence of settings, commands, tools, and extension event bridge
199 +Add an unreleased changelog entry for the rename and redesign.
201 +- [ ] **Step 5: Run focused and repository checks**
203 +Run:
205 +```bash
206 +mise run test -- os-notifier
207 +mise run lint
208 +mise run check
209 +mise run ci
210 +```
212 +Expected: every command exits zero.
214 +- [ ] **Step 6: Verify repository invariants**
216 +Run:
218 +```bash
219 +test -d extensions/os-notifier
220 +test ! -e extensions/terminal-notifier
221 +rg 'terminal-notifier' README.md package-lock.json extensions/os-notifier
222 +```
224 +Expected: the directory assertions pass; only historical changelog references may match.
226 +- [ ] **Step 7: Commit final integration**
228 +```bash
229 +git add extensions/os-notifier/README.md extensions/os-notifier/CHANGELOG.md extensions/os-notifier/__tests__/harness.test.ts extensions/os-notifier/index.ts
230 +git commit -m "test(os-notifier): verify fallback delivery"
231 +```

extensions/os-notifier/CHANGELOG.md

Added
new file mode 100644
1 +# Changelog
3 +## Unreleased
5 +- Rename `terminal-notifier` to `os-notifier`.
6 +- Prefer native Linux, macOS, and Windows notifications with OSC fallback.
7 +- Notify only for direct interactive TUI runs completed while unfocused.
8 +- Preserve rich metadata with natural urgency and bounded sanitized text.
9 +- Remove the unused extension notification event bridge.
11 +## 0.0.3
13 +- Replace Bun test runner with Vitest in the workspace
14 +- Add isolated extension harness env for tests
15 +- Fix harness tests for import.meta.dirname, Vitest deps, and Chai matchers
16 +- Migrate project tooling to mise
18 +## 0.0.2
20 +- Release only:
21 + no commits touched `extensions/terminal-notifier` since `v0.0.1`
22 +- Source unchanged:
23 + `agent_end` still sends OSC/Windows notify
24 +- Tests unchanged:
25 + harness still verifies extension runtime load
27 +## 0.1.0 - 2026-05-21
29 +- a40a427 prepare extensions for npm release
30 +- 133cb7d chore(pi):
31 + migrate extensions to earendil packages
32 +- f144b06 fix(pi):
33 + restore extension notifications

extensions/os-notifier/README.md

Added
new file mode 100644
1 +# os-notifier
3 +Native-first OS notifications for direct interactive Pi completion.
5 +## Install / load
7 +Loaded through the root pi-ext package.
8 +See [root README](../../README.md).
10 +## Commands / tools / settings
12 +Commands: none.
14 +Tools: none.
16 +Settings: none.
18 +Hooks:
20 +- `session_start` attaches terminal focus tracking in TUI mode.
21 +- `input` records direct interactive input origin.
22 +- `agent_start` starts duration measurement and assigns queued input origin.
23 +- `agent_end` sends an eligible completion notification while unfocused.
24 +- `session_shutdown` clears in-memory state and focus tracking.
26 +## Eligibility
28 +Notifications require all of:
30 +- `ctx.mode === "tui"`
31 +- input source `interactive`
32 +- terminal unfocused at `agent_end`
34 +RPC, JSON, print, SDK-driven, extension-driven, and subagent-style turns stay silent.
35 +Interactive steering makes its active run eligible.
36 +Queued follow-up origins remain associated with their later run.
37 +Focused completions are discarded rather than deferred.
39 +## Native delivery
41 +The extension attempts one OS bridge:
43 +- Linux: `notify-send`
44 +- macOS: `osascript`
45 +- Windows: PowerShell WinRT toast
47 +A spawn error or nonzero exit emits one terminal fallback.
48 +Kitty receives OSC 99; other terminals receive OSC 777.
49 +No startup probe or warning notification is emitted.
51 +Linux urgency maps `info` to low, `warning` to normal, and `error` to critical.
52 +macOS and Windows communicate outcome through the title because these bridges expose no equivalent urgency.
53 +OSC fallback prefixes warnings and errors.
55 +## Content
57 +Notifications include outcome, duration, project, Git branch, session name, model, bounded user prompt, and bounded failure detail.
58 +Dynamic text is sanitized and passed without shell interpolation.
60 +Focus tracking uses DECSET `?1004`, shared through `globalThis` and reference-counted.

extensions/os-notifier/__tests__/harness.test.ts

Added
new file mode 100644
1 +import path from "node:path";
2 +import { afterEach, describe, expect, it } from "vitest";
3 +import { createTestSession, type TestSession } from "../../../test/harness";
4 +import {
5 + agentDoneNotification,
6 + deliverNative,
7 + nativeCommand,
8 + oscBackend,
9 + TurnEligibility,
10 +} from "../index";
12 +describe("os-notifier native commands", () => {
13 + it("constructs Linux notify-send arguments", () => {
14 + expect(nativeCommand("linux", "Title", "Body", "info")).toEqual({
15 + command: "notify-send",
16 + args: ["--app-name=Pi", "--urgency=low", "Title", "Body"],
17 + });
18 + });
20 + it("constructs macOS osascript arguments without interpolating content", () => {
21 + const command = nativeCommand(
22 + "darwin",
23 + `Title ' " $()`,
24 + "Body\nline",
25 + "warning",
26 + );
27 + expect(command.command).toBe("osascript");
28 + expect(command.args.slice(-2)).toEqual([`Title ' " $()`, "Body\nline"]);
29 + expect(command.args[1]).not.toContain("Title");
30 + });
32 + it("constructs Windows PowerShell arguments without interpolating content", () => {
33 + const command = nativeCommand(
34 + "win32",
35 + `Title ' " $()`,
36 + "Body\nline",
37 + "error",
38 + );
39 + expect(command.command).toBe("powershell.exe");
40 + expect(command.args).toContain("-EncodedCommand");
41 + expect(command.args.join(" ")).not.toContain("Title");
42 + expect(command.env).toMatchObject({
43 + PI_OS_NOTIFIER_TITLE: `Title ' " $()`,
44 + PI_OS_NOTIFIER_BODY: "Body\nline",
45 + });
46 + });
48 + it("maps natural Linux urgency", () => {
49 + expect(nativeCommand("linux", "T", "B", "info").args).toContain(
50 + "--urgency=low",
51 + );
52 + expect(nativeCommand("linux", "T", "B", "warning").args).toContain(
53 + "--urgency=normal",
54 + );
55 + expect(nativeCommand("linux", "T", "B", "error").args).toContain(
56 + "--urgency=critical",
57 + );
58 + });
60 + it("selects Kitty OSC 99 and generic OSC 777", () => {
61 + expect(oscBackend({ KITTY_WINDOW_ID: "1" })).toBe("osc99");
62 + expect(oscBackend({})).toBe("osc777");
63 + });
65 + it("falls back exactly once only when native delivery fails", async () => {
66 + const writes: string[] = [];
67 + await deliverNative(
68 + { command: process.execPath, args: ["-e", "process.exit(0)"] },
69 + "Title",
70 + "Body",
71 + "info",
72 + "osc777",
73 + (value) => writes.push(value),
74 + );
75 + expect(writes).toEqual([]);
77 + await deliverNative(
78 + { command: process.execPath, args: ["-e", "process.exit(7)"] },
79 + "Title",
80 + "Body",
81 + "error",
82 + "osc777",
83 + (value) => writes.push(value),
84 + );
85 + expect(writes).toHaveLength(1);
86 + expect(writes[0]).toContain("\u001b]777;notify;Title;❌ Body\u0007");
87 + });
88 +});
90 +describe("os-notifier turn eligibility", () => {
91 + it("allows direct interactive TUI runs only", () => {
92 + const state = new TurnEligibility();
93 + state.input("interactive");
94 + state.start("tui");
95 + expect(state.end()).toBe(true);
97 + state.input("rpc");
98 + state.start("tui");
99 + expect(state.end()).toBe(false);
101 + state.input("interactive");
102 + state.start("rpc");
103 + expect(state.end()).toBe(false);
104 + });
106 + it("keeps queued follow-up origin separate from the active run", () => {
107 + const state = new TurnEligibility();
108 + state.input("extension");
109 + state.start("tui");
110 + state.input("interactive", "followUp");
111 + expect(state.end()).toBe(false);
112 + state.start("tui");
113 + expect(state.end()).toBe(true);
114 + });
116 + it("interactive steering makes the active run eligible", () => {
117 + const state = new TurnEligibility();
118 + state.input("extension");
119 + state.start("tui");
120 + state.input("interactive", "steer");
121 + expect(state.end()).toBe(true);
122 + });
123 +});
125 +describe("os-notifier payload", () => {
126 + it("includes rich bounded context in completion body", () => {
127 + expect(
128 + agentDoneNotification(
130 + messages: [
131 + { role: "user", content: "implement richer Pi notifications" },
132 + { role: "assistant", stopReason: "stop" },
133 + ],
134 + },
136 + cwd: "/home/oli/Workspace/dotfiles/pi-ext",
137 + model: { name: "GPT-5.5", provider: "openai", id: "gpt-5.5" },
138 + durationMs: 45_000,
139 + branch: "trunk",
140 + sessionName: "notifier work",
141 + },
142 + ),
143 + ).toEqual({
144 + title: "Pi finished",
145 + message:
146 + "Ready after 45s • pi-ext • trunk • notifier work • GPT-5.5\n↳ implement richer Pi notifications",
147 + severity: "info",
148 + });
149 + });
151 + it("sanitizes and bounds prompt and error detail", () => {
152 + const notification = agentDoneNotification(
154 + messages: [
155 + { role: "user", content: `prompt\u0000${"x".repeat(100)}` },
157 + role: "assistant",
158 + stopReason: "error",
159 + errorMessage: `failure\n${"y".repeat(200)}`,
160 + },
161 + ],
162 + },
163 + {},
164 + );
165 + expect(notification.title).toBe("Pi failed");
166 + expect(notification.severity).toBe("error");
167 + expect(notification.message).not.toContain("\u0000");
168 + expect(notification.message.match(/\n/gu)).toHaveLength(1);
169 + expect(notification.message.length).toBeLessThan(240);
170 + expect(notification.message).toContain("…");
171 + });
173 + it("classifies aborted runs as warnings", () => {
174 + expect(
175 + agentDoneNotification(
176 + { messages: [{ role: "assistant", stopReason: "aborted" }] },
177 + {},
178 + ),
179 + ).toMatchObject({ title: "Pi stopped", severity: "warning" });
180 + });
181 +});
183 +describe("os-notifier pi-test-harness", () => {
184 + let t: TestSession | undefined;
186 + afterEach(() => {
187 + t?.dispose();
188 + t = undefined;
189 + });
191 + it("loads in real Pi extension runtime", async () => {
192 + const extensionPath = path.resolve(import.meta.dirname, "../index.ts");
193 + t = await createTestSession({ extensions: [extensionPath] });
195 + expect(t.session.extensionRunner.extensions).toHaveLength(1);
196 + expect(t.session.extensionRunner.extensions[0].path).toBe(extensionPath);
197 + });
198 +});

extensions/os-notifier/focus.ts

Added
new file mode 100644
1 +/** Terminal focus detection via DECSET ?1004. Shared via globalThis. */
2 +const FOCUS_ENABLE = "\x1b[?1004h";
3 +const FOCUS_DISABLE = "\x1b[?1004l";
4 +const FOCUS_IN_SEQ = "\x1b[I";
5 +const FOCUS_OUT_SEQ = "\x1b[O";
7 +export type FocusListener = (focused: boolean) => void;
9 +interface FocusState {
10 + refs: number;
11 + focused: boolean;
12 + listener?: (chunk: Buffer) => void;
13 + listeners: Set<FocusListener>;
14 + buf: string;
17 +const G = globalThis as unknown as { __bugabinga_pi_focus?: FocusState };
18 +G.__bugabinga_pi_focus ??= {
19 + refs: 0,
20 + focused: true,
21 + listeners: new Set(),
22 + buf: "",
23 +};
24 +const state = G.__bugabinga_pi_focus;
26 +function notify(next: boolean): void {
27 + if (next === state.focused) return;
28 + state.focused = next;
29 + for (const fn of state.listeners) {
30 + try {
31 + fn(state.focused);
32 + } catch {
33 + /* best-effort */
34 + }
35 + }
38 +export function isFocused(): boolean {
39 + return state.focused;
42 +export function onFocus(fn: FocusListener): void {
43 + state.listeners.add(fn);
46 +export function offFocus(fn: FocusListener): void {
47 + state.listeners.delete(fn);
50 +export function attach(): void {
51 + if (!process.stdout.isTTY || !process.stdin.isTTY) return;
53 + state.refs++;
54 + if (state.refs > 1) return;
56 + try {
57 + process.stdout.write(FOCUS_ENABLE);
58 + } catch {
59 + state.refs--;
60 + return;
61 + }
63 + const maxSeq = Math.max(FOCUS_IN_SEQ.length, FOCUS_OUT_SEQ.length);
64 + const handler = (chunk: Buffer) => {
65 + try {
66 + state.buf += chunk.toString("binary");
67 + let i = 0;
68 + while (i + maxSeq <= state.buf.length) {
69 + if (state.buf.startsWith(FOCUS_IN_SEQ, i)) {
70 + notify(true);
71 + i += FOCUS_IN_SEQ.length;
72 + } else if (state.buf.startsWith(FOCUS_OUT_SEQ, i)) {
73 + notify(false);
74 + i += FOCUS_OUT_SEQ.length;
75 + } else {
76 + i++;
77 + }
78 + }
79 + state.buf = state.buf.slice(i);
80 + if (state.buf.length > 64) state.buf = state.buf.slice(-(maxSeq - 1));
81 + } catch {
82 + /* best-effort */
83 + }
84 + };
86 + process.stdin.on("data", handler);
87 + state.listener = handler;
90 +export function detach(): void {
91 + if (state.refs <= 0) return;
92 + state.refs--;
93 + if (state.refs > 0) return;
95 + if (state.listener) {
96 + try {
97 + process.stdin.off("data", state.listener);
98 + } catch {
99 + /* noop */
101 + state.listener = undefined;
103 + try {
104 + process.stdout.write(FOCUS_DISABLE);
105 + } catch {
106 + /* noop */

extensions/os-notifier/index.ts

Added
new file mode 100644
1 +import { execFile } from "node:child_process";
2 +import { existsSync, readFileSync, statSync } from "node:fs";
3 +import { dirname, isAbsolute, join, resolve } from "node:path";
4 +import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
5 +import * as focus from "./focus.js";
7 +export type NotificationSeverity = "info" | "warning" | "error";
8 +export type OscBackend = "osc777" | "osc99";
10 +export interface NativeCommand {
11 + command: string;
12 + args: string[];
13 + env?: NodeJS.ProcessEnv;
16 +type AgentDoneNotification = {
17 + title: string;
18 + message: string;
19 + severity: NotificationSeverity;
20 +};
22 +const PROMPT_LIMIT = 58;
23 +const ERROR_LIMIT = 120;
25 +function compact(value: unknown, limit = Number.POSITIVE_INFINITY): string {
26 + if (typeof value !== "string") return "";
27 + const text = value.replace(/[\x00-\x1f\x7f]+/g, " ").trim();
28 + if (text.length <= limit) return text;
29 + return `${text.slice(0, limit).trimEnd()}…`;
32 +function formatDuration(ms: number | undefined): string {
33 + if (ms === undefined || !Number.isFinite(ms) || ms < 0) return "";
34 + if (ms < 1000) return "<1s";
35 + const seconds = Math.round(ms / 1000);
36 + if (seconds < 60) return `${seconds}s`;
37 + const minutes = Math.floor(seconds / 60);
38 + const rest = seconds % 60;
39 + return rest === 0 ? `${minutes}m` : `${minutes}m ${rest}s`;
42 +function basename(path: string): string {
43 + return (
44 + path
45 + .replace(/[/\\]+$/, "")
46 + .split(/[/\\]/)
47 + .pop() || path
48 + );
51 +function textContent(value: unknown): string {
52 + if (typeof value === "string") return value;
53 + if (!Array.isArray(value)) return "";
54 + return value
55 + .map((part) => {
56 + const item = part as { type?: unknown; text?: unknown } | undefined;
57 + return item?.type === "text" && typeof item.text === "string"
58 + ? item.text
59 + : "";
60 + })
61 + .filter(Boolean)
62 + .join(" ");
65 +function promptSnippet(messages: unknown[]): string {
66 + for (let i = messages.length - 1; i >= 0; i--) {
67 + const message = messages[i] as
68 + | { role?: unknown; content?: unknown }
69 + | undefined;
70 + if (message?.role === "user")
71 + return compact(textContent(message.content), PROMPT_LIMIT);
72 + }
73 + return "";
76 +function formatMessage(
77 + head: string,
78 + context: string[],
79 + prompt: string,
80 +): string {
81 + const line = [head, ...context].filter(Boolean).join(" • ");
82 + return prompt ? `${line}\n↳ ${prompt}` : line;
85 +export function currentGitBranch(cwd: string): string {
86 + try {
87 + let dir = resolve(cwd);
88 + while (true) {
89 + const dotGit = join(dir, ".git");
90 + if (existsSync(dotGit)) {
91 + const stat = statSync(dotGit);
92 + const gitDir = stat.isDirectory()
93 + ? dotGit
94 + : resolveGitFile(dotGit, dir);
95 + const head = readFileSync(join(gitDir, "HEAD"), "utf8").trim();
96 + if (head.startsWith("ref: refs/heads/")) {
97 + return head.slice("ref: refs/heads/".length);
98 + }
99 + return /^[0-9a-f]{7,}$/i.test(head) ? head.slice(0, 7) : "";
101 + const parent = dirname(dir);
102 + if (parent === dir) return "";
103 + dir = parent;
105 + } catch {
106 + return "";
110 +function resolveGitFile(dotGit: string, worktreeDir: string): string {
111 + const text = readFileSync(dotGit, "utf8").trim();
112 + const prefix = "gitdir:";
113 + if (!text.toLowerCase().startsWith(prefix)) return dotGit;
114 + const target = text.slice(prefix.length).trim();
115 + return isAbsolute(target) ? target : resolve(worktreeDir, target);
118 +export function agentDoneNotification(
119 + event: { messages?: unknown[] },
120 + meta: {
121 + cwd?: string;
122 + model?: { provider?: string; id?: string; name?: string };
123 + durationMs?: number;
124 + branch?: string;
125 + sessionName?: string;
126 + },
127 +): AgentDoneNotification {
128 + const messages = Array.isArray(event.messages) ? event.messages : [];
129 + const duration = formatDuration(meta.durationMs);
130 + const model = meta.model
131 + ? compact(meta.model.name) ||
132 + [compact(meta.model.provider), compact(meta.model.id)]
133 + .filter(Boolean)
134 + .join("/")
135 + : "";
136 + const context = [
137 + meta.cwd ? compact(basename(meta.cwd)) : "",
138 + compact(meta.branch),
139 + compact(meta.sessionName),
140 + model,
141 + ].filter(Boolean);
142 + const prompt = promptSnippet(messages);
144 + for (let i = messages.length - 1; i >= 0; i--) {
145 + const message = messages[i] as
146 + | { role?: unknown; stopReason?: unknown; errorMessage?: unknown }
147 + | undefined;
148 + if (message?.role !== "assistant") continue;
149 + if (message.stopReason === "aborted") {
150 + return {
151 + title: "Pi stopped",
152 + message: formatMessage(
153 + `Stopped${duration ? ` after ${duration}` : ""}`,
154 + context,
155 + prompt,
156 + ),
157 + severity: "warning",
158 + };
160 + if (message.stopReason === "error") {
161 + return {
162 + title: "Pi failed",
163 + message: formatMessage(
164 + `Failed${duration ? ` after ${duration}` : ""}`,
165 + [compact(message.errorMessage, ERROR_LIMIT), ...context],
166 + prompt,
167 + ),
168 + severity: "error",
169 + };
171 + break;
174 + return {
175 + title: "Pi finished",
176 + message: formatMessage(
177 + `Ready${duration ? ` after ${duration}` : ""}`,
178 + context,
179 + prompt,
180 + ),
181 + severity: "info",
182 + };
185 +function urgency(
186 + severity: NotificationSeverity,
187 +): "low" | "normal" | "critical" {
188 + if (severity === "info") return "low";
189 + if (severity === "warning") return "normal";
190 + return "critical";
193 +const MACOS_SCRIPT = [
194 + "on run argv",
195 + "display notification (item 2 of argv) with title (item 1 of argv)",
196 + "end run",
197 +].join("\n");
199 +const WINDOWS_SCRIPT = [
200 + "[Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime] > $null",
201 + "$xml = [Windows.UI.Notifications.ToastNotificationManager]::GetTemplateContent([Windows.UI.Notifications.ToastTemplateType]::ToastText02)",
202 + "$xml.GetElementsByTagName('text')[0].AppendChild($xml.CreateTextNode($env:PI_OS_NOTIFIER_TITLE)) > $null",
203 + "$xml.GetElementsByTagName('text')[1].AppendChild($xml.CreateTextNode($env:PI_OS_NOTIFIER_BODY)) > $null",
204 + "$toast = [Windows.UI.Notifications.ToastNotification]::new($xml)",
205 + "[Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier('Pi').Show($toast)",
206 +].join("; ");
208 +export function nativeCommand(
209 + platform: "linux" | "darwin" | "win32",
210 + title: string,
211 + body: string,
212 + severity: NotificationSeverity,
213 +): NativeCommand;
214 +export function nativeCommand(
215 + platform: string,
216 + title: string,
217 + body: string,
218 + severity: NotificationSeverity,
219 +): NativeCommand | undefined;
220 +export function nativeCommand(
221 + platform: string,
222 + title: string,
223 + body: string,
224 + severity: NotificationSeverity,
225 +): NativeCommand | undefined {
226 + if (platform === "linux") {
227 + return {
228 + command: "notify-send",
229 + args: ["--app-name=Pi", `--urgency=${urgency(severity)}`, title, body],
230 + };
232 + if (platform === "darwin") {
233 + return {
234 + command: "osascript",
235 + args: ["-e", MACOS_SCRIPT, "--", title, body],
236 + };
238 + if (platform === "win32") {
239 + return {
240 + command: "powershell.exe",
241 + args: [
242 + "-NoProfile",
243 + "-NonInteractive",
244 + "-EncodedCommand",
245 + Buffer.from(WINDOWS_SCRIPT, "utf16le").toString("base64"),
246 + ],
247 + env: {
248 + ...process.env,
249 + PI_OS_NOTIFIER_TITLE: title,
250 + PI_OS_NOTIFIER_BODY: body,
251 + },
252 + };
254 + return undefined;
257 +export function oscBackend(
258 + env: Record<string, string | undefined>,
259 +): OscBackend {
260 + return env.KITTY_WINDOW_ID ? "osc99" : "osc777";
263 +function severityPrefix(severity: NotificationSeverity): string {
264 + return severity === "warning" ? "⚠️ " : severity === "error" ? "❌ " : "";
267 +function oscNotification(
268 + backend: OscBackend,
269 + title: string,
270 + body: string,
271 + severity: NotificationSeverity,
272 +): string {
273 + const message = `${severityPrefix(severity)}${body}`;
274 + if (backend === "osc99") {
275 + return `\x1b]99;i=1:d=0;${title}\x1b\\\x1b]99;i=1:p=body;${message}\x1b\\`;
277 + return `\x1b]777;notify;${title};${message}\x07`;
280 +export function deliverNative(
281 + command: NativeCommand | undefined,
282 + title: string,
283 + body: string,
284 + severity: NotificationSeverity,
285 + fallback: OscBackend,
286 + write: (value: string) => unknown = (value) => process.stdout.write(value),
287 +): Promise<void> {
288 + return new Promise((resolveDelivery) => {
289 + const useFallback = () => {
290 + try {
291 + write(oscNotification(fallback, title, body, severity));
292 + } catch {
293 + // No backend remains.
295 + resolveDelivery();
296 + };
297 + if (!command) {
298 + useFallback();
299 + return;
301 + try {
302 + execFile(command.command, command.args, { env: command.env }, (error) => {
303 + if (error) useFallback();
304 + else resolveDelivery();
305 + });
306 + } catch {
307 + useFallback();
309 + });
312 +type InputSource = "interactive" | "rpc" | "extension" | string;
313 +type StreamingBehavior = "steer" | "followUp" | undefined;
315 +export class TurnEligibility {
316 + private active = false;
317 + private current = false;
318 + private pending = false;
319 + private readonly queued: boolean[] = [];
321 + input(source: InputSource, behavior?: StreamingBehavior): void {
322 + const eligible = source === "interactive";
323 + if (behavior === "followUp") {
324 + this.queued.push(eligible);
325 + return;
327 + if (behavior === "steer" && this.active) {
328 + this.current ||= eligible;
329 + return;
331 + this.pending = eligible;
334 + start(mode: string): void {
335 + this.active = true;
336 + const origin =
337 + this.queued.length > 0 ? (this.queued.shift() ?? false) : this.pending;
338 + this.pending = false;
339 + this.current = mode === "tui" && origin;
342 + end(): boolean {
343 + const eligible = this.current;
344 + this.active = false;
345 + this.current = false;
346 + return eligible;
349 + clear(): void {
350 + this.active = false;
351 + this.current = false;
352 + this.pending = false;
353 + this.queued.length = 0;
357 +export default function (pi: ExtensionAPI) {
358 + const eligibility = new TurnEligibility();
359 + let agentStartedAt: number | undefined;
360 + let focusAttached = false;
362 + pi.on("session_start", async (_event, ctx) => {
363 + if (ctx.mode === "tui") {
364 + focus.attach();
365 + focusAttached = true;
367 + });
369 + pi.on("input", async (event) => {
370 + eligibility.input(event.source, event.streamingBehavior);
371 + });
373 + pi.on("agent_start", async (_event, ctx) => {
374 + eligibility.start(ctx.mode);
375 + agentStartedAt = Date.now();
376 + });
378 + pi.on("agent_end", async (event, ctx) => {
379 + const shouldNotify = eligibility.end();
380 + if (shouldNotify && !focus.isFocused()) {
381 + const notification = agentDoneNotification(event, {
382 + cwd: ctx.cwd,
383 + model: ctx.model,
384 + durationMs:
385 + agentStartedAt === undefined
386 + ? undefined
387 + : Date.now() - agentStartedAt,
388 + branch: currentGitBranch(ctx.cwd),
389 + sessionName: pi.getSessionName(),
390 + });
391 + void deliverNative(
392 + nativeCommand(
393 + process.platform,
394 + notification.title,
395 + notification.message,
396 + notification.severity,
397 + ),
398 + notification.title,
399 + notification.message,
400 + notification.severity,
401 + oscBackend(process.env),
402 + );
404 + agentStartedAt = undefined;
405 + });
407 + pi.on("session_shutdown", async () => {
408 + eligibility.clear();
409 + agentStartedAt = undefined;
410 + if (focusAttached) {
411 + focus.detach();
412 + focusAttached = false;
414 + });

extensions/os-notifier/package.json

Added
new file mode 100644
1 +{
2 + "name": "@bugabinga/pi-ext-os-notifier",
3 + "type": "module",
4 + "main": "index.ts",
5 + "peerDependencies": {
6 + "@earendil-works/pi-coding-agent": "*"
7 + },
8 + "license": "MIT",
9 + "description": "Native-first OS notifications for Pi.",
10 + "keywords": [
11 + "pi",
12 + "pi-extension"
13 + ],
14 + "devDependencies": {
15 + "@marcfargas/pi-test-harness": "^0.6.1",
16 + "vitest": "^4.1.9"
17 + },
18 + "scripts": {},
19 + "private": true

extensions/terminal-notifier/CHANGELOG.md

Deleted
deleted file mode 100644
1 -# Changelog
3 -## 0.0.3
5 -- Replace Bun test runner with Vitest in the workspace
6 -- Add isolated extension harness env for tests
7 -- Fix harness tests for import.meta.dirname, Vitest deps, and Chai matchers
8 -- Migrate project tooling to mise
10 -## 0.0.2
12 -- Release only:
13 - no commits touched `extensions/terminal-notifier` since `v0.0.1`
14 -- Source unchanged:
15 - `agent_end` still sends OSC/Windows notify
16 -- Tests unchanged:
17 - harness still verifies extension runtime load
19 -## 0.1.0 - 2026-05-21
21 -- a40a427 prepare extensions for npm release
22 -- 133cb7d chore(pi):
23 - migrate extensions to earendil packages
24 -- f144b06 fix(pi):
25 - restore extension notifications

extensions/terminal-notifier/README.md

Deleted
deleted file mode 100644
1 -# terminal-notifier
3 -Terminal notification bridge for Pi agent completion and extension events.
5 -## Install / load
7 -Loaded through the root pi-ext package.
8 -See [root README](../../README.md).
10 -## Commands / tools / settings
12 -Commands:
13 -none.
15 -Tools:
16 -none.
18 -Settings:
19 -none.
21 -Hooks:
23 -- `session_start`:
24 - attaches terminal focus tracking.
25 -- `agent_start`:
26 - records start time.
27 -- `agent_end`:
28 - sends a completion notification when terminal focus is away.
29 -- `session_shutdown`:
30 - removes focus listener and disables focus tracking.
32 -Events:
34 -- listens for `notify:send` with `{ message, severity?, source? }`.
35 -- emits `notify:ui` with `{ message, severity, source }` before relaying
36 - `notify:send` to terminal/native notification output.
38 -## Behavior
40 -Uses DECSET `?1004` focus reports when stdin/stdout are TTYs.
41 -Focus state is shared through `globalThis` and reference-counted.
43 -Suppresses agent completion notifications while terminal is focused.
45 -Agent completion notifications include status, elapsed time when available,
46 -project basename, Git branch, session name, model name/provider/id, and a bounded
47 -last user prompt snippet when available.
49 -Assistant `stopReason` maps to notification status:
51 -- `aborted` → `Pi aborted`, warning.
52 -- `error` → `Pi error`, error.
53 -- otherwise → `Pi done`, info.
55 -Notification backend selection:
57 -- Linux with `notify-send` available → `notify-send`.
58 -- `WT_SESSION` → Windows toast via `powershell.exe`.
59 -- `KITTY_WINDOW_ID` → OSC 99.
60 -- otherwise → OSC 777.
62 -`notify-send` urgency mapping:
64 -- `info` → low.
65 -- `warning` / `warn` → normal.
66 -- `error` → critical.
68 -`notify:send` relay always sends, independent of terminal focus.
69 -Terminal OSC / Windows fallback messages get `⚠️` for warnings and `❌` for errors.

extensions/terminal-notifier/__tests__/harness.test.ts

Deleted
deleted file mode 100644
1 -import path from "node:path";
2 -import { afterEach, describe, expect, it } from "vitest";
3 -import { createTestSession, type TestSession } from "../../../test/harness";
4 -import {
5 - agentDoneNotification,
6 - linuxNotifySendArgs,
7 - selectNotificationBackend,
8 -} from "../index";
10 -describe("terminal-notifier native notifications", () => {
11 - it("uses notify-send on Linux when available", () => {
12 - expect(
13 - selectNotificationBackend({
14 - platform: "linux",
15 - env: {},
16 - linuxNotifySend: true,
17 - }),
18 - ).toBe("notify-send");
19 - });
21 - it("maps severity to notify-send urgency", () => {
22 - expect(linuxNotifySendArgs("Title", "Body", "info")).toEqual([
23 - "--app-name=Pi",
24 - "--urgency=low",
25 - "Title",
26 - "Body",
27 - ]);
28 - expect(linuxNotifySendArgs("Title", "Body", "warning")).toContain(
29 - "--urgency=normal",
30 - );
31 - expect(linuxNotifySendArgs("Title", "Body", "warn")).toContain(
32 - "--urgency=normal",
33 - );
34 - expect(linuxNotifySendArgs("Title", "Body", "error")).toContain(
35 - "--urgency=critical",
36 - );
37 - });
39 - it("prefers notify-send over terminal backends on Linux", () => {
40 - expect(
41 - selectNotificationBackend({
42 - platform: "linux",
43 - env: { KITTY_WINDOW_ID: "1", WT_SESSION: "1" },
44 - linuxNotifySend: true,
45 - }),
46 - ).toBe("notify-send");
47 - });
48 -});
50 -describe("terminal-notifier payload", () => {
51 - it("includes useful bounded context in completion body", () => {
52 - expect(
53 - agentDoneNotification(
54 - {
55 - messages: [
56 - { role: "user", content: "implement richer Pi notifications" },
57 - { role: "assistant", stopReason: "stop" },
58 - ],
59 - },
60 - {
61 - cwd: "/home/oli/Workspace/dotfiles/pi-ext",
62 - model: { name: "GPT-5.5", provider: "openai", id: "gpt-5.5" },
63 - durationMs: 45_000,
64 - branch: "trunk",
65 - sessionName: "notifier work",
66 - },
67 - ),
68 - ).toEqual({
69 - title: "Pi done",
70 - message:
71 - "Ready after 45s • pi-ext • trunk • notifier work • GPT-5.5\n↳ implement richer Pi notifications",
72 - severity: "info",
73 - });
74 - });
76 - it("bounds and normalizes prompt snippets", () => {
77 - const notification = agentDoneNotification(
78 - {
79 - messages: [
80 - {
81 - role: "user",
82 - content: [
83 - {
84 - type: "text",
85 - text: "first line\nsecond line with enough text to need truncation here",
86 - },
87 - ],
88 - },
89 - { role: "assistant", stopReason: "stop" },
90 - ],
91 - },
92 - { durationMs: 1000 },
93 - );
95 - expect(notification.message).toBe(
96 - "Ready after 1s\n↳ first line second line with enough text to need truncation…",
97 - );
98 - });
99 -});
101 -describe("terminal-notifier pi-test-harness", () => {
102 - let t: TestSession | undefined;
104 - afterEach(() => {
105 - t?.dispose();
106 - t = undefined;
107 - });
109 - it("loads in real Pi extension runtime", async () => {
110 - const extensionPath = path.resolve(import.meta.dirname, "../index.ts");
111 - t = await createTestSession({ extensions: [extensionPath] });
113 - expect(t.session.extensionRunner.extensions).toHaveLength(1);
114 - expect(t.session.extensionRunner.extensions[0].path).toBe(extensionPath);
115 - });
116 -});

extensions/terminal-notifier/focus.ts

Deleted
deleted file mode 100644
1 -/** Terminal focus detection via DECSET ?1004. Shared via globalThis. */
2 -const FOCUS_ENABLE = "\x1b[?1004h";
3 -const FOCUS_DISABLE = "\x1b[?1004l";
4 -const FOCUS_IN_SEQ = "\x1b[I";
5 -const FOCUS_OUT_SEQ = "\x1b[O";
7 -export type FocusListener = (focused: boolean) => void;
9 -interface FocusState {
10 - refs: number;
11 - focused: boolean;
12 - listener?: (chunk: Buffer) => void;
13 - listeners: Set<FocusListener>;
14 - buf: string;
17 -const G = globalThis as unknown as { __bugabinga_pi_focus?: FocusState };
18 -G.__bugabinga_pi_focus ??= {
19 - refs: 0,
20 - focused: true,
21 - listeners: new Set(),
22 - buf: "",
23 -};
24 -const state = G.__bugabinga_pi_focus;
26 -function notify(next: boolean): void {
27 - if (next === state.focused) return;
28 - state.focused = next;
29 - for (const fn of state.listeners) {
30 - try {
31 - fn(state.focused);
32 - } catch {
33 - /* best-effort */
34 - }
35 - }
38 -export function isFocused(): boolean {
39 - return state.focused;
42 -export function onFocus(fn: FocusListener): void {
43 - state.listeners.add(fn);
46 -export function offFocus(fn: FocusListener): void {
47 - state.listeners.delete(fn);
50 -export function attach(): void {
51 - if (!process.stdout.isTTY || !process.stdin.isTTY) return;
53 - state.refs++;
54 - if (state.refs > 1) return;
56 - try {
57 - process.stdout.write(FOCUS_ENABLE);
58 - } catch {
59 - state.refs--;
60 - return;
61 - }
63 - const maxSeq = Math.max(FOCUS_IN_SEQ.length, FOCUS_OUT_SEQ.length);
64 - const handler = (chunk: Buffer) => {
65 - try {
66 - state.buf += chunk.toString("binary");
67 - let i = 0;
68 - while (i + maxSeq <= state.buf.length) {
69 - if (state.buf.startsWith(FOCUS_IN_SEQ, i)) {
70 - notify(true);
71 - i += FOCUS_IN_SEQ.length;
72 - } else if (state.buf.startsWith(FOCUS_OUT_SEQ, i)) {
73 - notify(false);
74 - i += FOCUS_OUT_SEQ.length;
75 - } else {
76 - i++;
77 - }
78 - }
79 - state.buf = state.buf.slice(i);
80 - if (state.buf.length > 64) state.buf = state.buf.slice(-(maxSeq - 1));
81 - } catch {
82 - /* best-effort */
83 - }
84 - };
86 - process.stdin.on("data", handler);
87 - state.listener = handler;
90 -export function detach(): void {
91 - if (state.refs <= 0) return;
92 - state.refs--;
93 - if (state.refs > 0) return;
95 - if (state.listener) {
96 - try {
97 - process.stdin.off("data", state.listener);
98 - } catch {
99 - /* noop */
100 - }
101 - state.listener = undefined;
102 - }
103 - try {
104 - process.stdout.write(FOCUS_DISABLE);
105 - } catch {
106 - /* noop */
107 - }

extensions/terminal-notifier/index.ts

Deleted
deleted file mode 100644
1 -/**
2 - * Pi Terminal Notifier Extension
3 - *
4 - * Sends a native terminal notification when Pi agent is done and waiting for input.
5 - * Notifications are suppressed when the terminal is focused — you're already looking.
6 - *
7 - * Also relays `notify:send` events from other extensions.
8 - *
9 - * Supports: notify-send (Linux), OSC 777 (Ghostty, iTerm2, WezTerm), OSC 99 (Kitty), Windows toast.
10 - *
11 - * Focus detection via DECSET ?1004 from lib/focus.ts.
12 - * Based on tmustier/pi-extensions (session-recap).
13 - * MIT License — https://github.com/tmustier/pi-extensions
14 - */
16 -import { execFile, spawnSync } from "node:child_process";
17 -import { existsSync, readFileSync, statSync } from "node:fs";
18 -import { dirname, isAbsolute, join, resolve } from "node:path";
19 -import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
20 -import * as focus from "./focus.js";
22 -export type NotifySeverity = "info" | "warning" | "warn" | "error";
23 -export type NormalizedNotifySeverity = Exclude<NotifySeverity, "warn">;
24 -export type NotificationBackend =
25 - | "notify-send"
26 - | "osc777"
27 - | "osc99"
28 - | "windows";
30 -export interface NotifyPayload {
31 - message: string;
32 - severity?: NotifySeverity;
33 - source?: string;
36 -type AgentDoneNotification = {
37 - title: string;
38 - message: string;
39 - severity: NormalizedNotifySeverity;
40 -};
42 -function compact(value: unknown, fallback = ""): string {
43 - if (typeof value !== "string") return fallback;
44 - return value.replace(/[\x00-\x1f\x7f]+/g, " ").trim();
47 -function formatDuration(ms: number | undefined): string {
48 - if (ms === undefined || !Number.isFinite(ms) || ms < 0) return "";
49 - if (ms < 1000) return "<1s";
50 - const seconds = Math.round(ms / 1000);
51 - if (seconds < 60) return `${seconds}s`;
52 - const minutes = Math.floor(seconds / 60);
53 - const rest = seconds % 60;
54 - return rest === 0 ? `${minutes}m` : `${minutes}m ${rest}s`;
57 -function basename(path: string): string {
58 - return (
59 - path
60 - .replace(/[/\\]+$/, "")
61 - .split(/[/\\]/)
62 - .pop() || path
63 - );
66 -function textContent(value: unknown): string {
67 - if (typeof value === "string") return value;
68 - if (!Array.isArray(value)) return "";
69 - return value
70 - .map((part) => {
71 - const item = part as { type?: unknown; text?: unknown } | undefined;
72 - return item?.type === "text" && typeof item.text === "string"
73 - ? item.text
74 - : "";
75 - })
76 - .filter(Boolean)
77 - .join(" ");
80 -function lastUserPrompt(messages: unknown[]): string {
81 - for (let i = messages.length - 1; i >= 0; i--) {
82 - const message = messages[i] as
83 - | { role?: unknown; content?: unknown }
84 - | undefined;
85 - if (message?.role !== "user") continue;
86 - const text = compact(textContent(message.content));
87 - if (text) return text;
88 - }
89 - return "";
92 -function promptSnippet(messages: unknown[]): string {
93 - const text = lastUserPrompt(messages);
94 - const max = 58;
95 - if (text.length <= max) return text;
96 - return `${text.slice(0, max).trimEnd()}…`;
99 -function formatMessage(
100 - head: string,
101 - context: string[],
102 - prompt: string,
103 -): string {
104 - const line = [head, ...context].filter(Boolean).join(" • ");
105 - return prompt ? `${line}\n↳ ${prompt}` : line;
108 -export function currentGitBranch(cwd: string): string {
109 - try {
110 - let dir = resolve(cwd);
111 - while (true) {
112 - const dotGit = join(dir, ".git");
113 - if (existsSync(dotGit)) {
114 - const stat = statSync(dotGit);
115 - const gitDir = stat.isDirectory()
116 - ? dotGit
117 - : resolveGitFile(dotGit, dir);
118 - const head = readFileSync(join(gitDir, "HEAD"), "utf8").trim();
119 - if (head.startsWith("ref: refs/heads/")) {
120 - return head.slice("ref: refs/heads/".length);
121 - }
122 - return /^[0-9a-f]{7,}$/i.test(head) ? head.slice(0, 7) : "";
123 - }
124 - const parent = dirname(dir);
125 - if (parent === dir) return "";
126 - dir = parent;
127 - }
128 - } catch {
129 - return "";
130 - }
133 -function resolveGitFile(dotGit: string, worktreeDir: string): string {
134 - const text = readFileSync(dotGit, "utf8").trim();
135 - const prefix = "gitdir:";
136 - if (!text.toLowerCase().startsWith(prefix)) return dotGit;
137 - const target = text.slice(prefix.length).trim();
138 - return isAbsolute(target) ? target : resolve(worktreeDir, target);
141 -export function agentDoneNotification(
142 - event: { messages?: unknown[] },
143 - meta: {
144 - cwd?: string;
145 - model?: { provider?: string; id?: string; name?: string };
146 - durationMs?: number;
147 - branch?: string;
148 - sessionName?: string;
149 - },
150 -): AgentDoneNotification {
151 - const messages = Array.isArray(event.messages) ? event.messages : [];
152 - const duration = formatDuration(meta.durationMs);
153 - const model = meta.model
154 - ? compact(meta.model.name) ||
155 - [compact(meta.model.provider), compact(meta.model.id)]
156 - .filter(Boolean)
157 - .join("/")
158 - : "";
159 - const context = [
160 - meta.cwd ? basename(meta.cwd) : "",
161 - compact(meta.branch),
162 - compact(meta.sessionName),
163 - model,
164 - ].filter(Boolean);
165 - const prompt = promptSnippet(messages);
167 - for (let i = messages.length - 1; i >= 0; i--) {
168 - const message = messages[i] as
169 - | { role?: unknown; stopReason?: unknown; errorMessage?: unknown }
170 - | undefined;
171 - if (message?.role !== "assistant") continue;
173 - if (message.stopReason === "aborted") {
174 - return {
175 - title: "Pi aborted",
176 - message: formatMessage(
177 - `Stopped${duration ? ` after ${duration}` : ""}`,
178 - context,
179 - prompt,
180 - ),
181 - severity: "warning",
182 - };
183 - }
185 - if (message.stopReason === "error") {
186 - const detail = compact(message.errorMessage);
187 - return {
188 - title: "Pi error",
189 - message: formatMessage(
190 - `Failed${duration ? ` after ${duration}` : ""}`,
191 - [detail, ...context],
192 - prompt,
193 - ),
194 - severity: "error",
195 - };
196 - }
198 - return {
199 - title: "Pi done",
200 - message: formatMessage(
201 - `Ready${duration ? ` after ${duration}` : ""}`,
202 - context,
203 - prompt,
204 - ),
205 - severity: "info",
206 - };
207 - }
209 - return {
210 - title: "Pi done",
211 - message: formatMessage(
212 - `Ready${duration ? ` after ${duration}` : ""}`,
213 - context,
214 - prompt,
215 - ),
216 - severity: "info",
217 - };
220 -function psString(value: string): string {
221 - return `'${value.replace(/'/g, "''")}'`;
224 -function windowsToastScript(title: string, body: string): string {
225 - const type = "Windows.UI.Notifications";
226 - const mgr = `[${type}.ToastNotificationManager, ${type}, ContentType = WindowsRuntime]`;
227 - const template = `[${type}.ToastTemplateType]::ToastText01`;
228 - const toast = `[${type}.ToastNotification]::new($xml)`;
229 - return [
230 - `${mgr} > $null`,
231 - `$xml = [${type}.ToastNotificationManager]::GetTemplateContent(${template})`,
232 - `$xml.GetElementsByTagName('text')[0].AppendChild($xml.CreateTextNode(${psString(body)})) > $null`,
233 - `[${type}.ToastNotificationManager]::CreateToastNotifier(${psString(title)}).Show(${toast})`,
234 - ].join("; ");
237 -function normalizeSeverity(severity: NotifySeverity): NormalizedNotifySeverity {
238 - return severity === "warn" ? "warning" : severity;
241 -function severityPrefix(severity: NormalizedNotifySeverity): string {
242 - return severity === "warning" ? "⚠️ " : severity === "error" ? "❌ " : "";
245 -function notifySendUrgency(
246 - severity: NotifySeverity,
247 -): "low" | "normal" | "critical" {
248 - switch (normalizeSeverity(severity)) {
249 - case "info":
250 - return "low";
251 - case "warning":
252 - return "normal";
253 - case "error":
254 - return "critical";
255 - }
258 -export function linuxNotifySendArgs(
259 - title: string,
260 - body: string,
261 - severity: NotifySeverity,
262 -): string[] {
263 - return [
264 - "--app-name=Pi",
265 - `--urgency=${notifySendUrgency(severity)}`,
266 - title,
267 - body,
268 - ];
271 -export function selectNotificationBackend(options: {
272 - platform: string;
273 - env: Record<string, string | undefined>;
274 - linuxNotifySend: boolean;
275 -}): NotificationBackend {
276 - if (options.platform === "linux" && options.linuxNotifySend)
277 - return "notify-send";
278 - if (options.env.WT_SESSION) return "windows";
279 - if (options.env.KITTY_WINDOW_ID) return "osc99";
280 - return "osc777";
283 -function commandExists(command: string): boolean {
284 - const result = spawnSync(command, ["--version"], {
285 - stdio: "ignore",
286 - timeout: 1000,
287 - });
288 - return result.error === undefined && result.status === 0;
291 -function notifyOSC777(title: string, body: string): void {
292 - process.stdout.write(`\x1b]777;notify;${title};${body}\x07`);
295 -function notifyOSC99(title: string, body: string): void {
296 - process.stdout.write(`\x1b]99;i=1:d=0;${title}\x1b\\`);
297 - process.stdout.write(`\x1b]99;i=1:p=body;${body}\x1b\\`);
300 -function notifyWindows(title: string, body: string): void {
301 - execFile("powershell.exe", [
302 - "-NoProfile",
303 - "-Command",
304 - windowsToastScript(title, body),
305 - ]);
308 -function notifyLinux(
309 - title: string,
310 - body: string,
311 - severity: NotifySeverity,
312 -): void {
313 - execFile(
314 - "notify-send",
315 - linuxNotifySendArgs(title, body, severity),
316 - () => undefined,
317 - );
320 -function notify(
321 - title: string,
322 - body: string,
323 - severity: NotifySeverity,
324 - backend: NotificationBackend,
325 -): void {
326 - const normalized = normalizeSeverity(severity);
327 - if (backend === "windows") {
328 - notifyWindows(title, `${severityPrefix(normalized)}${body}`);
329 - } else if (backend === "osc99") {
330 - notifyOSC99(title, `${severityPrefix(normalized)}${body}`);
331 - } else if (backend === "notify-send") {
332 - notifyLinux(title, body, normalized);
333 - } else {
334 - notifyOSC777(title, `${severityPrefix(normalized)}${body}`);
335 - }
338 -export default function (pi: ExtensionAPI) {
339 - let agentStartedAt: number | undefined;
340 - let linuxNotifySend = false;
341 - let backend: NotificationBackend = selectNotificationBackend({
342 - platform: process.platform,
343 - env: process.env,
344 - linuxNotifySend,
345 - });
347 - pi.on("session_start", async (_event, ctx) => {
348 - linuxNotifySend =
349 - process.platform === "linux" && commandExists("notify-send");
350 - backend = selectNotificationBackend({
351 - platform: process.platform,
352 - env: process.env,
353 - linuxNotifySend,
354 - });
355 - if (process.platform === "linux" && !linuxNotifySend && ctx.hasUI) {
356 - ctx.ui.notify(
357 - "notify-send unavailable; falling back to terminal OSC notifications",
358 - "info",
359 - );
360 - }
361 - focus.attach();
362 - });
364 - pi.on("agent_start", async () => {
365 - agentStartedAt = Date.now();
366 - });
368 - // Notify when agent finishes — only if terminal is unfocused
369 - pi.on("agent_end", async (event, ctx) => {
370 - if (!focus.isFocused()) {
371 - const { title, message, severity } = agentDoneNotification(event, {
372 - cwd: ctx.cwd,
373 - model: ctx.model,
374 - durationMs:
375 - agentStartedAt === undefined
376 - ? undefined
377 - : Date.now() - agentStartedAt,
378 - branch: currentGitBranch(ctx.cwd),
379 - sessionName: pi.getSessionName(),
380 - });
381 - notify(title, message, severity, backend);
382 - }
383 - agentStartedAt = undefined;
384 - });
386 - // Also notify on focus-in if agent had already finished while away
387 - const onFocusChange = (_isFocused: boolean) => {
388 - // No need to notify when coming back — terminal-signals handles
389 - // the tab badge. This is for external events via notify:send.
390 - };
392 - focus.onFocus(onFocusChange);
394 - // Relay notify:send events from other extensions (always send regardless of focus)
395 - pi.events.on("notify:send", (data: unknown) => {
396 - const payload = data as NotifyPayload;
397 - const source = payload.source ?? "unknown";
398 - const message = payload.message ?? "";
399 - const severity = normalizeSeverity(payload.severity ?? "info");
401 - pi.events.emit("notify:ui", { message, severity, source });
403 - notify(source, message, severity, backend);
404 - });
406 - pi.on("session_shutdown", async () => {
407 - focus.offFocus(onFocusChange);
408 - focus.detach();
409 - });

extensions/terminal-notifier/package.json

Deleted
deleted file mode 100644
1 -{
2 - "name": "@bugabinga/pi-ext-terminal-notifier",
3 - "type": "module",
4 - "main": "index.ts",
5 - "peerDependencies": {
6 - "@earendil-works/pi-coding-agent": "*"
7 - },
8 - "license": "MIT",
9 - "description": "Terminal notification bridge for Pi.",
10 - "keywords": [
11 - "pi",
12 - "pi-extension"
13 - ],
14 - "devDependencies": {
15 - "@marcfargas/pi-test-harness": "^0.6.1",
16 - "vitest": "^4.1.9"
17 - },
18 - "scripts": {},
19 - "private": true
20 -}

package-lock.json

Modified
301 301 "@earendil-works/pi-tui": "*"
304 + "extensions/os-notifier": {
305 + "name": "@bugabinga/pi-ext-os-notifier",
306 + "license": "MIT",
307 + "devDependencies": {
308 + "@marcfargas/pi-test-harness": "^0.6.1",
309 + "vitest": "^4.1.9"
310 + },
311 + "peerDependencies": {
312 + "@earendil-works/pi-coding-agent": "*"
314 + },
304 315 "extensions/prompt-autopsy": {
305 316 "name": "@bugabinga/pi-ext-prompt-autopsy",
306 317 "license": "MIT",
417 428 "@earendil-works/pi-tui": "*"
420 - "extensions/terminal-notifier": {
421 - "name": "@bugabinga/pi-ext-terminal-notifier",
422 - "license": "MIT",
423 - "devDependencies": {
424 - "@marcfargas/pi-test-harness": "^0.6.1",
425 - "vitest": "^4.1.9"
426 - },
427 - "peerDependencies": {
428 - "@earendil-works/pi-coding-agent": "*"
430 - },
431 431 "extensions/terminal-signals": {
432 432 "name": "@bugabinga/pi-ext-terminal-signals",
433 433 "license": "MIT",
1334 1334 "resolved": "extensions/nu-bang",
1335 1335 "link": true
1337 + "node_modules/@bugabinga/pi-ext-os-notifier": {
1338 + "resolved": "extensions/os-notifier",
1339 + "link": true
1340 + },
1337 1341 "node_modules/@bugabinga/pi-ext-prompt-autopsy": {
1338 1342 "resolved": "extensions/prompt-autopsy",
1339 1343 "link": true
1374 1378 "resolved": "extensions/ssh-tools",
1375 1379 "link": true
1377 - "node_modules/@bugabinga/pi-ext-terminal-notifier": {
1378 - "resolved": "extensions/terminal-notifier",
1379 - "link": true
1380 - },
1381 1381 "node_modules/@bugabinga/pi-ext-terminal-signals": {
1382 1382 "resolved": "extensions/terminal-signals",
1383 1383 "link": true