repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

chore: remove ghost extension

a83e2475b7c5df310ab62c15584beb69ca4ead30

Oliver Jan Krylow <oliver@bugabinga.net> ·

unsigned

Browse filesCompare with HEAD

Changed files (13)

.github/dependabot.yml

Modified
40 40 directory: "/extensions/footer"
41 41 schedule:
42 42 interval: "weekly"
43 - - package-ecosystem: "npm"
44 - directory: "/extensions/ghost"
45 - schedule:
46 - interval: "weekly"
47 43 - package-ecosystem: "npm"
48 44 directory: "/extensions/git-safe"
49 45 schedule:

README.md

Modified
70 70 | `diff-review` | Browser UI for reviewing git diffs and sending findings back to Pi. | [README](extensions/diff-review/README.md) |
71 71 | `fast` | OpenAI Codex priority service tier for Pi. | [README](extensions/fast/README.md) |
72 72 | `footer` | Shared stable footer renderer for Pi. | [README](extensions/footer/README.md) |
73 -| `ghost` | Background Pi agent overlay for quick side-channel prompts. | [README](extensions/ghost/README.md) |
74 73 | `git-safe` | Hardened git clone tool for Pi. | [README](extensions/git-safe/README.md) |
75 74 | `goal` | Persistent standing-goal loop for Pi sessions. | [README](extensions/goal/README.md) |
76 75 | `leaks` | Provider-bound secret redaction for Pi. | [README](extensions/leaks/README.md) |

extensions/ghost/CHANGELOG.md

Deleted
deleted file mode 100644
1 -# Changelog
3 -## 0.0.2
5 -- Tag has no commits touching `extensions/ghost` since `v0.0.1`
6 -- Source, README, and tests unchanged; `/ghost` behavior same
7 -- Package metadata unchanged; no new commands, tools, hooks, or settings
9 -## 0.1.0 - 2026-05-21
11 -- a40a427 prepare extensions for npm release
12 -- 133cb7d chore(pi):
13 - migrate extensions to earendil packages
14 -- db7b1c5 Update agent and terminal configs
15 -- 5ca1296 Rework Pi agent extensions
16 -- b045a6b fix(pi/mux):
17 - cooldown exhausted keys on provider usage-limit errors
18 -- b87a61a feat(pi):
19 - monorepo workspace — all extensions are proper packages
20 -- 5fbf178 pi(ext):
21 - add remaining extensions (angel, animations, code-actions, files-widget,
22 - ghost, git-safe, neko, prune, web, etc.)

extensions/ghost/README.md

Deleted
deleted file mode 100644
1 -# ghost
3 -Background Pi agent overlay for quick side-channel prompts.
5 -## Install / load
7 -Loaded through the root pi-ext package.
8 -See [root README](../../README.md).
10 -## Commands / tools / settings
12 -Commands:
14 -- `/ghost` opens the ghost overlay.
15 - If it is already open, it focuses it.
16 -- `/ghost <prompt>` opens the overlay if needed and sends `<prompt>` to the
17 - ghost session.
18 - If the overlay is already open, it sends the prompt to the existing session.
19 -- `/ghost` requires interactive mode.
21 -Shortcuts:
23 -- `alt+g` opens the ghost overlay in interactive mode.
25 -Tools:
27 -- none
29 -Hooks:
31 -- `session_start` loads ghost config.
32 -- `session_shutdown` disposes the ghost session and clears its widget.
34 -Settings:
36 -- global:
37 - `ghost` object in Pi agent `settings.json`
38 -- project:
39 - `.pi/ghost.json`
40 -- project config overrides global config field by field
41 -- invalid project JSON or non-object project config is reported as a warning and
42 - ignored
43 -- invalid global JSON is ignored
45 -Supported config fields:
47 -- `model.provider`
48 -- `model.id`
49 -- `overlay.anchor`:
50 - `center`, `top-left`, `top-center`, `top-right`, `right-center`,
51 - `bottom-right`, `bottom-center`, `bottom-left`, `left-center`
52 -- `overlay.width`:
53 - positive number or positive percent string
54 -- `overlay.maxHeight`:
55 - positive number or positive percent string
56 -- `overlay.margin.top`:
57 - non-negative number
58 -- `overlay.margin.bottom`:
59 - non-negative number
60 -- `overlay.margin.left`:
61 - non-negative number
62 -- `overlay.margin.right`:
63 - non-negative number
65 -Default config:
67 -```json
69 - "overlay": {
70 - "anchor": "bottom-center",
71 - "width": "100%",
72 - "maxHeight": "55%",
73 - "margin": { "top": 0, "bottom": 1, "left": 0, "right": 0 }
74 - }
76 -```
78 -## Behavior
80 -Ghost starts a secondary in-memory Pi agent session in the current cwd.
81 -It uses the active model unless both `model.provider` and `model.id` match a
82 -model in the registry.
83 -If the configured model is missing, it falls back to the active model.
85 -The overlay renders user messages, assistant streaming updates, and tool
86 -execution output from that secondary session.
87 -It keeps an event log so hidden overlays can reopen with current session state.
89 -Input behavior:
91 -- Enter submits trimmed input.
92 -- empty input is ignored.
93 -- `ctrl+s` hides the overlay and keeps the ghost session running.
94 -- `esc` closes the overlay and disposes the ghost session.
95 -- Up/down/page-up/page-down/home/end scroll transcript history.
97 -When hidden, ghost shows a small widget above the editor:
98 -`/ghost is running • run /ghost to bring it back`.
100 -Closing the overlay or Pi session shutdown cleans up the overlay, widget, event
101 -log, subscription, and ghost session.
102 -Overlay failure also cleans up that state.

extensions/ghost/__tests__/config.test.ts

Deleted
deleted file mode 100644
1 -import { describe, expect, it } from "vitest";
2 -import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
3 -import { tmpdir } from "node:os";
4 -import { join } from "node:path";
5 -import {
6 - defaultConfig,
7 - loadGhostConfig,
8 - normalizeGhostConfig,
9 -} from "../config.ts";
11 -describe("normalizeGhostConfig", () => {
12 - it("uses strict defaults for empty config", () => {
13 - expect(normalizeGhostConfig()).toEqual(defaultConfig);
14 - });
16 - it("lets project config override global config field by field", () => {
17 - const config = normalizeGhostConfig(
18 - {
19 - model: { provider: "anthropic", id: "global-model" },
20 - overlay: {
21 - anchor: "top-left",
22 - width: "50%",
23 - maxHeight: "40%",
24 - margin: { top: 1, bottom: 2, left: 3, right: 4 },
25 - },
26 - },
27 - {
28 - model: { id: "project-model" },
29 - overlay: { width: "90%", margin: { bottom: 9 } },
30 - },
31 - );
33 - expect(config).toEqual({
34 - model: { provider: "anthropic", id: "project-model" },
35 - overlay: {
36 - anchor: "top-left",
37 - width: "90%",
38 - maxHeight: "40%",
39 - margin: { top: 1, bottom: 9, left: 3, right: 4 },
40 - },
41 - });
42 - });
44 - it("rejects invalid anchors, sizes, margins, and model values", () => {
45 - const config = normalizeGhostConfig(
46 - {
47 - model: { provider: "", id: 42 },
48 - overlay: {
49 - anchor: "bottom",
50 - width: "wide",
51 - maxHeight: "0%",
52 - margin: { top: -1, bottom: Number.NaN, left: "2", right: Infinity },
53 - },
54 - },
55 - {},
56 - );
58 - expect(config).toEqual(defaultConfig);
59 - });
61 - it("accepts every real pi overlay anchor", () => {
62 - for (const anchor of [
63 - "center",
64 - "top-left",
65 - "top-center",
66 - "top-right",
67 - "right-center",
68 - "bottom-right",
69 - "bottom-center",
70 - "bottom-left",
71 - "left-center",
72 - ]) {
73 - expect(
74 - normalizeGhostConfig({}, { overlay: { anchor } }).overlay.anchor,
75 - ).toBe(anchor);
76 - }
77 - });
79 - it("accepts numeric and percentage sizes only", () => {
80 - expect(
81 - normalizeGhostConfig({}, { overlay: { width: 72, maxHeight: "33.5%" } })
82 - .overlay,
83 - ).toMatchObject({ width: 72, maxHeight: "33.5%" });
84 - expect(
85 - normalizeGhostConfig({}, { overlay: { width: 0, maxHeight: -1 } })
86 - .overlay,
87 - ).toMatchObject({
88 - width: defaultConfig.overlay.width,
89 - maxHeight: defaultConfig.overlay.maxHeight,
90 - });
91 - });
93 - it("ignores deleted legacy junk without shaping config", () => {
94 - const config = normalizeGhostConfig(
95 - {},
96 - { documents: ["x"], interval: 10, behavior: { hideOnClose: false } },
97 - );
98 - expect(config).toEqual(defaultConfig);
99 - });
100 -});
102 -describe("loadGhostConfig", () => {
103 - it("reports invalid project JSON instead of silently swallowing it", () => {
104 - const cwd = mkdtempSync(join(tmpdir(), "ghost-config-"));
105 - const piDir = join(cwd, ".pi");
106 - const errors: string[] = [];
108 - mkdirSync(piDir);
109 - writeFileSync(join(piDir, "ghost.json"), "{ nope", "utf-8");
111 - try {
112 - const config = loadGhostConfig(cwd, (error) =>
113 - errors.push(`${error.path}: ${error.message}`),
114 - );
115 - expect(config).toEqual(defaultConfig);
116 - expect(errors).toHaveLength(1);
117 - expect(errors[0]).toContain("ghost.json");
118 - } finally {
119 - rmSync(cwd, { recursive: true, force: true });
120 - }
121 - });
122 -});

extensions/ghost/__tests__/harness.test.ts

Deleted
deleted file mode 100644
1 -import { afterEach, describe, expect, it } from "vitest";
2 -import path from "node:path";
3 -import {
4 - createTestSession,
5 - type TestSession,
6 -} from "@marcfargas/pi-test-harness";
8 -describe("ghost pi-test-harness", () => {
9 - let t: TestSession | undefined;
11 - afterEach(() => {
12 - t?.dispose();
13 - t = undefined;
14 - });
16 - it("loads in real Pi extension runtime", async () => {
17 - const extensionPath = path.resolve(import.meta.dir, "../index.ts");
18 - t = await createTestSession({ extensions: [extensionPath] });
20 - expect(t.session.extensionRunner.extensions).toHaveLength(1);
21 - expect(t.session.extensionRunner.extensions[0].path).toBe(extensionPath);
22 - });
23 -});

extensions/ghost/__tests__/overlay-harness.ts

Deleted
deleted file mode 100644
1 -import { expect } from "vitest";
2 -import type { AssistantMessage } from "@earendil-works/pi-ai";
3 -import type { ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
4 -import {
5 - type AgentSessionEvent,
6 - initTheme,
7 -} from "@earendil-works/pi-coding-agent";
8 -import type { TUI } from "@earendil-works/pi-tui";
9 -import { visibleWidth } from "@earendil-works/pi-tui";
10 -import { GhostOverlayComponent } from "../overlay.ts";
12 -initTheme("dark", false);
14 -type Theme = ExtensionCommandContext["ui"]["theme"];
15 -type MessageStartEvent = Extract<AgentSessionEvent, { type: "message_start" }>;
16 -type MessageUpdateEvent = Extract<
17 - AgentSessionEvent,
18 - { type: "message_update" }
19 ->;
20 -type MessageEndEvent = Extract<AgentSessionEvent, { type: "message_end" }>;
21 -type ToolStartEvent = Extract<
22 - AgentSessionEvent,
23 - { type: "tool_execution_start" }
24 ->;
25 -type ToolUpdateEvent = Extract<
26 - AgentSessionEvent,
27 - { type: "tool_execution_update" }
28 ->;
29 -type ToolEndEvent = Extract<AgentSessionEvent, { type: "tool_execution_end" }>;
31 -export interface OverlayHarness {
32 - overlay: GhostOverlayComponent;
33 - submitted: string[];
34 - hiddenCount(): number;
35 - closedCount(): number;
38 -export const plainTheme = {
39 - fg: (_color: string, text: string) => text,
40 - bg: (_color: string, text: string) => text,
41 - bold: (text: string) => text,
42 - italic: (text: string) => text,
43 - underline: (text: string) => text,
44 - inverse: (text: string) => text,
45 - strikethrough: (text: string) => text,
46 - getFgAnsi: () => "",
47 - getBgAnsi: () => "",
48 - getColorMode: () => "truecolor",
49 - getThinkingBorderColor: () => (text: string) => text,
50 - getBashModeBorderColor: () => (text: string) => text,
51 -} as Theme;
53 -export function createOverlay(
54 - rows = 30,
55 - columns = 100,
56 - maxHeight: `${number}%` | number = "55%",
57 -): OverlayHarness {
58 - const submitted: string[] = [];
59 - let hidden = 0;
60 - let closed = 0;
62 - const overlay = new GhostOverlayComponent({
63 - tui: minimalTui(rows, columns),
64 - theme: plainTheme,
65 - sessionCwd: `${process.env.HOME ?? "/home/me"}/repo/with/a/very/very/very/long/path`,
66 - modelLabel:
67 - "provider/some-ridiculously-long-model-name-that-must-never-break-render-width",
68 - maxHeight,
69 - margin: { top: 0, bottom: 1 },
70 - onSubmitMessage: (text) => submitted.push(text),
71 - onHideOverlay: () => {
72 - hidden++;
73 - },
74 - onCloseOverlay: () => {
75 - closed++;
76 - },
77 - });
79 - return {
80 - overlay,
81 - submitted,
82 - hiddenCount: () => hidden,
83 - closedCount: () => closed,
84 - };
87 -export function expectLinesFit(lines: string[], width: number): void {
88 - for (const line of lines)
89 - expect(visibleWidth(line)).toBeLessThanOrEqual(width);
92 -export function assistantMessage(text: string): AssistantMessage {
93 - return {
94 - role: "assistant",
95 - content: [{ type: "text", text }],
96 - api: "test",
97 - provider: "test",
98 - model: "test",
99 - usage: emptyUsage(),
100 - stopReason: "stop",
101 - timestamp: 0,
102 - };
105 -export function userStart(text: string): MessageStartEvent {
106 - return {
107 - type: "message_start",
108 - message: { role: "user", content: [{ type: "text", text }], timestamp: 0 },
109 - } as MessageStartEvent;
112 -export function assistantStart(text: string): MessageStartEvent {
113 - return {
114 - type: "message_start",
115 - message: assistantMessage(text),
116 - } as MessageStartEvent;
119 -export function assistantUpdate(text: string): MessageUpdateEvent {
120 - return {
121 - type: "message_update",
122 - message: assistantMessage(text),
123 - } as MessageUpdateEvent;
126 -export function assistantEnd(text: string): MessageEndEvent {
127 - return {
128 - type: "message_end",
129 - message: assistantMessage(text),
130 - } as MessageEndEvent;
133 -export function toolStart(args: unknown = {}): ToolStartEvent {
134 - return {
135 - type: "tool_execution_start",
136 - toolCallId: "tool-1",
137 - toolName: "ghost_tool",
138 - args,
139 - } as ToolStartEvent;
142 -export function toolUpdate(text: string): ToolUpdateEvent {
143 - return {
144 - type: "tool_execution_update",
145 - toolCallId: "tool-1",
146 - toolName: "ghost_tool",
147 - args: {},
148 - partialResult: { content: [{ type: "text", text }] },
149 - } as ToolUpdateEvent;
152 -export function toolEnd(text: string): ToolEndEvent {
153 - return {
154 - type: "tool_execution_end",
155 - toolCallId: "tool-1",
156 - toolName: "ghost_tool",
157 - args: {},
158 - result: { content: [{ type: "text", text }] },
159 - isError: false,
160 - } as ToolEndEvent;
163 -function minimalTui(rows: number, columns: number): TUI {
164 - return {
165 - terminal: { rows, columns },
166 - requestRender: () => {},
167 - } as TUI;
170 -function emptyUsage(): AssistantMessage["usage"] {
171 - return {
172 - input: 0,
173 - output: 0,
174 - cacheRead: 0,
175 - cacheWrite: 0,
176 - totalTokens: 0,
177 - cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
178 - };

extensions/ghost/__tests__/overlay-render.test.ts

Deleted
deleted file mode 100644
1 -import { describe, expect, it } from "vitest";
2 -import { visibleWidth } from "@earendil-works/pi-tui";
3 -import { extractMessageText, fitLine, formatGhostCwd } from "../overlay.ts";
4 -import {
5 - assistantEnd,
6 - assistantMessage,
7 - assistantStart,
8 - assistantUpdate,
9 - createOverlay,
10 - expectLinesFit,
11 - toolEnd,
12 - toolStart,
13 - toolUpdate,
14 - userStart,
15 -} from "./overlay-harness.ts";
17 -describe("fitLine", () => {
18 - it("truncates and pads to exact visible width", () => {
19 - expect(visibleWidth(fitLine("abcdef", 3))).toBe(3);
20 - expect(visibleWidth(fitLine("x", 3))).toBe(3);
21 - expect(fitLine("x", 0)).toBe("");
22 - });
23 -});
25 -describe("GhostOverlayComponent rendering", () => {
26 - it("never emits a line wider than render(width), including brutal tiny widths", () => {
27 - for (let rows = 1; rows <= 24; rows++) {
28 - for (let width = 0; width <= 120; width++) {
29 - const { overlay } = createOverlay(rows, width);
30 - overlay.setStatus("status ".repeat(80));
31 - const lines = overlay.render(width);
32 - expectLinesFit(lines, width);
33 - expect(lines.length).toBeLessThanOrEqual(Math.max(1, rows));
34 - }
35 - }
36 - });
38 - it("keeps all lines fitted after long transcript, tool, status, and input churn", () => {
39 - const { overlay } = createOverlay(18, 60);
40 - overlay.setStatus("S".repeat(500));
42 - for (let i = 0; i < 30; i++) {
43 - overlay.handleSessionEvent(userStart(`user ${i} ${"u".repeat(120)}`));
44 - overlay.handleSessionEvent(
45 - assistantStart(`assistant ${i} ${"a".repeat(120)}`),
46 - );
47 - overlay.handleSessionEvent(
48 - assistantUpdate(`assistant update ${i} ${"b".repeat(120)}`),
49 - );
50 - overlay.handleSessionEvent(
51 - assistantEnd(`assistant end ${i} ${"c".repeat(120)}`),
52 - );
53 - }
55 - overlay.handleSessionEvent(toolStart({ huge: "x".repeat(200) }));
56 - overlay.handleSessionEvent(toolUpdate("partial".repeat(80)));
57 - overlay.handleSessionEvent(toolEnd("done".repeat(80)));
59 - for (const width of [4, 5, 8, 13, 20, 40, 80]) {
60 - expectLinesFit(overlay.render(width), width);
61 - }
62 - });
64 - it("invalidates transcript cache on assistant streaming updates", () => {
65 - const { overlay } = createOverlay(24, 90);
67 - overlay.handleSessionEvent(assistantStart("first token"));
68 - expect(overlay.render(90).join("\n")).toContain("first token");
70 - overlay.handleSessionEvent(assistantUpdate("second token"));
71 - const rendered = overlay.render(90).join("\n");
73 - expect(rendered).toContain("second token");
74 - expect(rendered).not.toContain("first token");
75 - });
77 - it("invalidates transcript cache on partial tool output", () => {
78 - const { overlay } = createOverlay(24, 90);
80 - overlay.handleSessionEvent(toolStart());
81 - expect(overlay.render(90).join("\n")).toContain("ghost_tool");
83 - overlay.handleSessionEvent(toolUpdate("partial-output-visible"));
84 - expect(overlay.render(90).join("\n")).toContain("partial-output-visible");
85 - });
87 - it("does not emit shell prompt OSC markers inside overlay transcript", () => {
88 - const { overlay } = createOverlay(24, 90);
90 - overlay.handleSessionEvent(userStart("hi"));
91 - overlay.handleSessionEvent(assistantStart("hello"));
93 - expect(overlay.render(90).join("\n")).not.toContain("\x1b]133;");
94 - });
96 - it("replays events captured while overlay was hidden", () => {
97 - const first = createOverlay(24, 90).overlay;
98 - const events = [
99 - userStart("hidden question"),
100 - assistantStart(""),
101 - assistantUpdate("hidden partial"),
102 - assistantUpdate("hidden final"),
103 - ];
105 - first.loadEvents(events);
106 - expect(first.render(90).join("\n")).toContain("hidden final");
108 - const reopened = createOverlay(24, 90).overlay;
109 - reopened.loadEvents(events);
110 - const rendered = reopened.render(90).join("\n");
111 - expect(rendered).toContain("hidden question");
112 - expect(rendered).toContain("hidden final");
113 - expect(rendered).not.toContain("hidden partial");
114 - });
116 - it("hydrates prior session messages when reopened", () => {
117 - const { overlay } = createOverlay(24, 90);
119 - overlay.loadMessages(
120 - [
121 - {
122 - role: "user",
123 - content: [{ type: "text", text: "previous question" }],
124 - },
125 - assistantMessage("partial prior answer"),
126 - ],
127 - true,
128 - );
130 - expect(overlay.render(90).join("\n")).toContain("previous question");
131 - expect(overlay.render(90).join("\n")).toContain("partial prior answer");
133 - overlay.handleSessionEvent(assistantUpdate("continued prior answer"));
134 - const rendered = overlay.render(90).join("\n");
135 - expect(rendered).toContain("continued prior answer");
136 - expect(rendered).not.toContain("partial prior answer");
137 - });
139 - it("submits trimmed input, hides on ctrl+s, closes on escape", () => {
140 - const harness = createOverlay(20, 80);
142 - for (const char of " hello ghost ") harness.overlay.handleInput(char);
143 - harness.overlay.handleInput("\r");
144 - harness.overlay.handleInput("\x13");
145 - harness.overlay.handleInput("\x1b");
147 - expect(harness.submitted).toEqual(["hello ghost"]);
148 - expect(harness.hiddenCount()).toBe(1);
149 - expect(harness.closedCount()).toBe(1);
150 - });
151 -});
153 -describe("message/cwd helpers", () => {
154 - it("extracts only text content", () => {
155 - expect(
156 - extractMessageText({
157 - content: [
158 - { type: "image" },
159 - { type: "text", text: " a " },
160 - { type: "text", text: "b" },
161 - ],
162 - }),
163 - ).toBe("a \nb");
164 - });
166 - it("formats home cwd compactly", () => {
167 - const home = process.env.HOME;
168 - if (!home) return;
170 - expect(formatGhostCwd(home)).toBe("~");
171 - expect(formatGhostCwd(`${home}/repo`)).toBe("~/repo");
172 - });
173 -});

extensions/ghost/config.ts

Deleted
deleted file mode 100644
1 -import { existsSync, readFileSync } from "node:fs";
2 -import { join } from "node:path";
3 -import { getAgentDir } from "@earendil-works/pi-coding-agent";
4 -import type {
5 - OverlayAnchor,
6 - OverlayMargin,
7 - SizeValue,
8 -} from "@earendil-works/pi-tui";
10 -const ANCHORS = new Set<OverlayAnchor>([
11 - "center",
12 - "top-left",
13 - "top-center",
14 - "top-right",
15 - "right-center",
16 - "bottom-right",
17 - "bottom-center",
18 - "bottom-left",
19 - "left-center",
20 -]);
22 -export interface GhostModelConfig {
23 - provider?: string;
24 - id?: string;
27 -export interface GhostOverlayConfig {
28 - anchor: OverlayAnchor;
29 - width: SizeValue;
30 - maxHeight: SizeValue;
31 - margin: Required<OverlayMargin>;
34 -export interface GhostConfig {
35 - model?: GhostModelConfig;
36 - overlay: GhostOverlayConfig;
39 -export const defaultConfig: GhostConfig = {
40 - overlay: {
41 - anchor: "bottom-center",
42 - width: "100%",
43 - maxHeight: "55%",
44 - margin: { top: 0, bottom: 1, left: 0, right: 0 },
45 - },
46 -};
48 -type RawConfig = Record<string, unknown>;
50 -export interface GhostConfigError {
51 - path: string;
52 - message: string;
55 -interface ProjectConfigResult {
56 - config: RawConfig;
57 - error?: GhostConfigError;
60 -function readProjectConfig(path: string): ProjectConfigResult {
61 - if (!existsSync(path)) return { config: {} };
63 - try {
64 - const parsed = JSON.parse(readFileSync(path, "utf-8"));
65 - return isObject(parsed)
66 - ? { config: parsed }
67 - : { config: {}, error: { path, message: "root must be an object" } };
68 - } catch (error) {
69 - const message = error instanceof Error ? error.message : String(error);
70 - return { config: {}, error: { path, message } };
71 - }
74 -function readGlobalGhostConfig(): RawConfig {
75 - const path = join(getAgentDir(), "settings.json");
76 - if (!existsSync(path)) return {};
77 - try {
78 - const parsed = JSON.parse(readFileSync(path, "utf-8"));
79 - return isObject(parsed?.ghost) ? parsed.ghost : {};
80 - } catch {
81 - return {};
82 - }
85 -export function loadGhostConfig(
86 - cwd: string,
87 - onError?: (error: GhostConfigError) => void,
88 -): GhostConfig {
89 - const global = readGlobalGhostConfig();
90 - const project = readProjectConfig(join(cwd, ".pi", "ghost.json"));
91 - if (project.error) onError?.(project.error);
92 - return normalizeGhostConfig(global, project.config);
95 -export function normalizeGhostConfig(
96 - global: RawConfig = {},
97 - project: RawConfig = {},
98 -): GhostConfig {
99 - const globalOverlay = objectValue(global.overlay);
100 - const projectOverlay = objectValue(project.overlay);
101 - const model = pickModel(
102 - objectValue(global.model),
103 - objectValue(project.model),
104 - );
105 - const overlay = {
106 - anchor: pickAnchor(
107 - projectOverlay.anchor,
108 - globalOverlay.anchor,
109 - defaultConfig.overlay.anchor,
110 - ),
111 - width: pickSize(
112 - projectOverlay.width,
113 - globalOverlay.width,
114 - defaultConfig.overlay.width,
115 - ),
116 - maxHeight: pickSize(
117 - projectOverlay.maxHeight,
118 - globalOverlay.maxHeight,
119 - defaultConfig.overlay.maxHeight,
120 - ),
121 - margin: pickMargin(
122 - objectValue(globalOverlay.margin),
123 - objectValue(projectOverlay.margin),
124 - ),
125 - };
127 - return model ? { model, overlay } : { overlay };
130 -function pickModel(
131 - global: RawConfig,
132 - project: RawConfig,
133 -): GhostModelConfig | undefined {
134 - const provider = pickString(project.provider, global.provider);
135 - const id = pickString(project.id, global.id);
136 - return provider || id ? { provider, id } : undefined;
139 -function pickMargin(
140 - global: RawConfig,
141 - project: RawConfig,
142 -): Required<OverlayMargin> {
143 - const fallback = defaultConfig.overlay.margin;
144 - return {
145 - top: pickNonNegativeNumber(project.top, global.top, fallback.top),
146 - bottom: pickNonNegativeNumber(
147 - project.bottom,
148 - global.bottom,
149 - fallback.bottom,
150 - ),
151 - left: pickNonNegativeNumber(project.left, global.left, fallback.left),
152 - right: pickNonNegativeNumber(project.right, global.right, fallback.right),
153 - };
156 -function pickAnchor(...values: unknown[]): OverlayAnchor {
157 - for (const value of values) {
158 - if (typeof value === "string" && ANCHORS.has(value as OverlayAnchor))
159 - return value as OverlayAnchor;
160 - }
161 - return defaultConfig.overlay.anchor;
164 -function pickSize(...values: unknown[]): SizeValue {
165 - for (const value of values) {
166 - if (isSize(value)) return value;
167 - }
168 - return defaultConfig.overlay.width;
171 -function pickString(...values: unknown[]): string | undefined {
172 - for (const value of values) {
173 - if (typeof value === "string" && value.trim()) return value;
174 - }
175 - return undefined;
178 -function pickNonNegativeNumber(...values: unknown[]): number {
179 - for (const value of values) {
180 - if (typeof value === "number" && Number.isFinite(value) && value >= 0)
181 - return value;
182 - }
183 - return 0;
186 -function objectValue(value: unknown): RawConfig {
187 - return isObject(value) ? value : {};
190 -function isObject(value: unknown): value is RawConfig {
191 - return typeof value === "object" && value !== null && !Array.isArray(value);
194 -function isSize(value: unknown): value is SizeValue {
195 - if (typeof value === "number") return Number.isFinite(value) && value > 0;
196 - if (typeof value !== "string") return false;
198 - const match = /^(\d+(?:\.\d+)?)%$/.exec(value);
199 - return match !== null && Number(match[1]) > 0;

extensions/ghost/index.ts

Deleted
deleted file mode 100644
1 -import {
2 - type AgentSession,
3 - type AgentSessionEvent,
4 - createAgentSession,
5 - type ExtensionAPI,
6 - type ExtensionContext,
7 - SessionManager,
8 -} from "@earendil-works/pi-coding-agent";
9 -import {
10 - type OverlayHandle,
11 - type TUI,
12 - truncateToWidth,
13 -} from "@earendil-works/pi-tui";
14 -import {
15 - type GhostConfig,
16 - type GhostConfigError,
17 - loadGhostConfig,
18 -} from "./config.js";
19 -import { GhostOverlayComponent } from "./overlay.js";
21 -type GhostUi = Pick<ExtensionContext["ui"], "notify" | "setWidget">;
23 -type GhostContext = Pick<
24 - ExtensionContext,
25 - "cwd" | "model" | "modelRegistry" | "ui"
26 ->;
28 -interface GhostRuntimeState {
29 - session: AgentSession | null;
30 - sessionCwd: string | null;
31 - modelLabel: string | null;
32 - overlayHandle: OverlayHandle | null;
33 - overlay: GhostOverlayComponent | null;
34 - unsubscribeSession: (() => void) | null;
35 - eventLog: AgentSessionEvent[];
36 - config: GhostConfig | null;
39 -type GhostOverlayResult = "hide" | "close";
41 -const WIDGET_KEY = "pi-ghost";
42 -const COMMAND = "ghost";
43 -const UNKNOWN_MODEL = "unknown-model";
44 -const HIDDEN_WIDGET_TEXT = "is running • run /ghost to bring it back";
46 -export default function (pi: ExtensionAPI) {
47 - const state: GhostRuntimeState = {
48 - session: null,
49 - sessionCwd: null,
50 - modelLabel: null,
51 - overlayHandle: null,
52 - overlay: null,
53 - unsubscribeSession: null,
54 - eventLog: [],
55 - config: null,
56 - };
58 - const loadConfig = (ctx: GhostContext): GhostConfig => {
59 - const config = loadGhostConfig(ctx.cwd, (error) =>
60 - notifyConfigError(ctx.ui, error),
61 - );
62 - state.config = config;
63 - return config;
64 - };
66 - const cleanupGhost = (ui?: Pick<GhostUi, "setWidget">): void => {
67 - state.overlayHandle?.hide();
68 - state.overlayHandle = null;
69 - state.overlay = null;
70 - state.unsubscribeSession?.();
71 - state.unsubscribeSession = null;
72 - state.session?.dispose();
73 - state.session = null;
74 - state.sessionCwd = null;
75 - state.modelLabel = null;
76 - state.eventLog = [];
77 - ui?.setWidget(WIDGET_KEY, undefined);
78 - };
80 - const ensureGhostSession = async (
81 - ctx: ExtensionContext,
82 - ): Promise<AgentSession> => {
83 - if (state.session) return state.session;
84 - if (!ctx.model) throw new Error("No model selected");
86 - const config = state.config ?? loadConfig(ctx);
87 - const model =
88 - config.model?.provider && config.model?.id
89 - ? (ctx.modelRegistry.find(config.model.provider, config.model.id) ??
90 - ctx.model)
91 - : ctx.model;
93 - const result = await createAgentSession({
94 - cwd: ctx.cwd,
95 - model,
96 - modelRegistry: ctx.modelRegistry,
97 - sessionManager: SessionManager.inMemory(ctx.cwd),
98 - });
100 - state.session = result.session;
101 - state.sessionCwd = ctx.cwd;
102 - state.modelLabel = model.id;
103 - state.eventLog = [];
104 - state.unsubscribeSession = result.session.subscribe((event) => {
105 - state.eventLog.push(event);
106 - state.overlay?.handleSessionEvent(event);
107 - });
108 - return result.session;
109 - };
111 - const openGhostOverlay = async (
112 - ctx: ExtensionContext,
113 - initialPrompt?: string,
114 - ): Promise<void> => {
115 - const config = state.config ?? loadConfig(ctx);
116 - const session = await ensureGhostSession(ctx);
117 - const prompt = initialPrompt?.trim();
119 - ctx.ui.setWidget(WIDGET_KEY, undefined);
121 - void ctx.ui
122 - .custom<GhostOverlayResult>(
123 - (tui, theme, _keybindings, done) => {
124 - const overlay = new GhostOverlayComponent({
125 - tui,
126 - theme,
127 - sessionCwd: state.sessionCwd ?? ctx.cwd,
128 - modelLabel: state.modelLabel ?? ctx.model?.id ?? UNKNOWN_MODEL,
129 - maxHeight: config.overlay.maxHeight,
130 - margin: config.overlay.margin,
131 - onSubmitMessage: (text) =>
132 - void session.prompt(text, { images: [] }),
133 - onHideOverlay: () => {
134 - state.overlayHandle = null;
135 - done("hide");
136 - },
137 - onCloseOverlay: () => {
138 - state.overlayHandle = null;
139 - done("close");
140 - },
141 - });
142 - state.overlay = overlay;
143 - if (state.eventLog.length > 0) overlay.loadEvents(state.eventLog);
144 - else overlay.loadMessages(session.messages, session.isStreaming);
146 - if (prompt) void session.prompt(prompt, { images: [] });
148 - return {
149 - render: (width: number) => overlay.render(width),
150 - invalidate: () => overlay.invalidate(),
151 - handleInput: (data: string) => overlay.handleInput(data),
152 - get focused() {
153 - return overlay.focused;
154 - },
155 - set focused(value: boolean) {
156 - overlay.focused = value;
157 - },
158 - dispose: () => {
159 - if (state.overlay === overlay) state.overlay = null;
160 - },
161 - };
162 - },
163 - {
164 - overlay: true,
165 - overlayOptions: {
166 - anchor: config.overlay.anchor,
167 - width: config.overlay.width,
168 - maxHeight: config.overlay.maxHeight,
169 - margin: config.overlay.margin,
170 - },
171 - onHandle: (handle) => {
172 - state.overlayHandle = handle;
173 - },
174 - },
175 - )
176 - .then((result) => {
177 - state.overlayHandle = null;
178 - if (result === "hide" && state.session) {
179 - ctx.ui.setWidget(WIDGET_KEY, hiddenWidget, {
180 - placement: "aboveEditor",
181 - });
182 - return;
183 - }
184 - cleanupGhost(ctx.ui);
185 - })
186 - .catch(() => cleanupGhost(ctx.ui));
187 - };
189 - const showOrPromptGhost = async (
190 - ctx: ExtensionContext,
191 - prompt?: string,
192 - ): Promise<void> => {
193 - const handle = state.overlayHandle;
194 - if (!handle) return openGhostOverlay(ctx, prompt);
196 - if (!prompt) {
197 - handle.focus();
198 - return;
199 - }
201 - const session = await ensureGhostSession(ctx);
202 - void session.prompt(prompt, { images: [] });
203 - };
205 - pi.registerCommand(COMMAND, {
206 - description: "Open ghost pi overlay",
207 - handler: async (args, ctx) => {
208 - if (!ctx.hasUI) {
209 - ctx.ui.notify("/ghost requires interactive mode", "error");
210 - return;
211 - }
213 - await showOrPromptGhost(ctx, args.trim() || undefined);
214 - },
215 - });
217 - pi.registerShortcut("alt+g", {
218 - description: "Open ghost pi overlay",
219 - handler: async (ctx) => {
220 - if (!ctx.hasUI) return;
221 - await showOrPromptGhost(ctx);
222 - },
223 - });
225 - pi.on("session_start", async (_event, ctx) => {
226 - loadConfig(ctx);
227 - });
229 - pi.on("session_shutdown", async (_event, ctx) => {
230 - cleanupGhost(ctx.ui);
231 - });
234 -function hiddenWidget(_tui: TUI, theme: ExtensionContext["ui"]["theme"]) {
235 - return {
236 - render: (width: number) => [
237 - truncateToWidth(
238 - theme.fg("accent", "/ghost ") + theme.fg("dim", HIDDEN_WIDGET_TEXT),
239 - width,
240 - ),
241 - ],
242 - invalidate: () => {},
243 - };
246 -function notifyConfigError(
247 - ui: Pick<GhostUi, "notify">,
248 - error: GhostConfigError,
249 -): void {
250 - ui.notify(`Ignored ${error.path}: ${error.message}`, "warning");

extensions/ghost/overlay.ts

Deleted
deleted file mode 100644
1 -import type { AssistantMessage } from "@earendil-works/pi-ai";
2 -import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
3 -import {
4 - type AgentSessionEvent,
5 - ToolExecutionComponent,
6 -} from "@earendil-works/pi-coding-agent";
7 -import {
8 - Container,
9 - type Focusable,
10 - Input,
11 - Key,
12 - matchesKey,
13 - type OverlayMargin,
14 - type SizeValue,
15 - Text,
16 - type TUI,
17 - truncateToWidth,
18 - visibleWidth,
19 -} from "@earendil-works/pi-tui";
21 -const DEFAULT_STATUS = "Ask something quick.";
22 -const MIN_FRAME_WIDTH = 4;
23 -const MIN_FRAME_HEIGHT = 6;
24 -const MIN_TRANSCRIPT_ROWS = 0;
25 -const FRAME_CHROME_ROWS = 5;
26 -const HEIGHT_RATIO = 0.55;
27 -const DEFAULT_VERTICAL_MARGIN = 2;
28 -const DEFAULT_WIDTH_RATIO = 1;
29 -const DEFAULT_MAX_HEIGHT: SizeValue = "55%";
30 -const PAGE_SCROLL_ROWS = 10;
31 -const BOTTOM_SCROLL = Number.MAX_SAFE_INTEGER;
33 -type GhostHistoryMessage = {
34 - role: string;
35 - content: unknown;
36 -};
38 -type GhostTheme = ExtensionContext["ui"]["theme"];
40 -type MessageStartEvent = Extract<AgentSessionEvent, { type: "message_start" }>;
41 -type MessageUpdateEvent = Extract<
42 - AgentSessionEvent,
43 - { type: "message_update" }
44 ->;
45 -type MessageEndEvent = Extract<AgentSessionEvent, { type: "message_end" }>;
46 -type ToolUpdateEvent = Extract<
47 - AgentSessionEvent,
48 - { type: "tool_execution_update" }
49 ->;
50 -type ToolEndEvent = Extract<AgentSessionEvent, { type: "tool_execution_end" }>;
52 -function safeDisplayText(text: string): string {
53 - return text
54 - .replace(
55 - /\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~]|\][^\x07]*(?:\x07|\x1B\\))/g,
56 - "",
57 - )
58 - .replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x9F]/g, " ")
59 - .trim();
62 -interface GhostOverlayLayout {
63 - innerWidth: number;
64 - frameHeight: number;
65 - inputLines: string[];
66 - transcriptRows: number;
67 - transcriptLines: string[];
68 - maxScroll: number;
71 -export interface GhostOverlayOptions {
72 - tui: TUI;
73 - theme: GhostTheme;
74 - sessionCwd: string;
75 - modelLabel: string;
76 - maxHeight?: SizeValue;
77 - margin?: OverlayMargin;
78 - onSubmitMessage(text: string): void;
79 - onHideOverlay(): void;
80 - onCloseOverlay(): void;
83 -class GhostMessageComponent {
84 - private readonly text = new Text("", 0, 0);
86 - constructor(
87 - private readonly role: "user" | "assistant",
88 - private readonly theme: GhostTheme,
89 - message: { content: unknown },
90 - ) {
91 - this.updateContent(message);
92 - }
94 - updateContent(message: { content: unknown }): void {
95 - const label =
96 - this.role === "user"
97 - ? this.theme.fg("accent", "you")
98 - : this.theme.fg("muted", "ghost");
99 - const body = extractMessageText(message);
100 - this.text.setText(body ? `${label} ${body}` : label);
101 - }
103 - render(width: number): string[] {
104 - return this.text.render(width);
105 - }
107 - invalidate(): void {
108 - this.text.invalidate();
109 - }
112 -export class GhostOverlayComponent implements Focusable {
113 - private readonly transcriptContainer = new Container();
114 - private readonly input = new Input();
115 - private readonly tui: TUI;
116 - private readonly theme: GhostTheme;
117 - private readonly sessionCwd: string;
118 - private readonly modelLabel: string;
119 - private readonly maxHeight: SizeValue;
120 - private readonly verticalMargin: number;
121 - private readonly onSubmitMessage: (text: string) => void;
122 - private readonly onHideOverlay: () => void;
123 - private readonly onCloseOverlay: () => void;
124 - private streamingComponent?: GhostMessageComponent;
125 - private pendingTools = new Map<string, ToolExecutionComponent>();
126 - private statusText = DEFAULT_STATUS;
127 - private scrollOffset = BOTTOM_SCROLL;
128 - private followMode = true;
129 - private cachedTranscriptLines?: string[];
130 - private cachedTranscriptWidth?: number;
131 - private lastInnerWidth = 0;
132 - private _focused = false;
134 - get focused(): boolean {
135 - return this._focused;
136 - }
138 - set focused(value: boolean) {
139 - this._focused = value;
140 - this.input.focused = value;
141 - }
143 - constructor(options: GhostOverlayOptions) {
144 - this.tui = options.tui;
145 - this.theme = options.theme;
146 - this.sessionCwd = options.sessionCwd;
147 - this.modelLabel = options.modelLabel;
148 - this.maxHeight = options.maxHeight ?? DEFAULT_MAX_HEIGHT;
149 - this.verticalMargin = marginHeight(options.margin);
150 - this.onSubmitMessage = options.onSubmitMessage;
151 - this.onHideOverlay = options.onHideOverlay;
152 - this.onCloseOverlay = options.onCloseOverlay;
154 - this.input.onSubmit = (value) => this.submit(value);
155 - this.input.onEscape = () => this.closeOverlay("close");
156 - }
158 - loadMessages(messages: readonly unknown[], isStreaming = false): void {
159 - this.resetTranscript();
161 - const history = messages.map(toHistoryMessage);
162 - const lastAssistantIndex = findLastAssistantIndex(history);
163 - for (let index = 0; index < history.length; index++) {
164 - const message = history[index];
165 - if (!message) continue;
167 - if (message.role === "user") {
168 - this.transcriptContainer.addChild(
169 - new GhostMessageComponent("user", this.theme, message),
170 - );
171 - continue;
172 - }
174 - if (message.role !== "assistant") continue;
176 - const component = new GhostMessageComponent(
177 - "assistant",
178 - this.theme,
179 - message,
180 - );
181 - this.transcriptContainer.addChild(component);
182 - if (isStreaming && index === lastAssistantIndex)
183 - this.streamingComponent = component;
184 - }
186 - this.setStatus(isStreaming ? "Streaming response..." : DEFAULT_STATUS);
187 - this.markTranscriptChanged();
188 - }
190 - loadEvents(events: readonly AgentSessionEvent[]): void {
191 - this.resetTranscript();
192 - for (const event of events) this.handleSessionEvent(event);
193 - this.tui.requestRender(true);
194 - }
196 - private resetTranscript(): void {
197 - this.transcriptContainer.clear();
198 - this.streamingComponent = undefined;
199 - this.pendingTools.clear();
200 - this.statusText = DEFAULT_STATUS;
201 - this.invalidateTranscriptCache();
202 - this.scrollToBottom();
203 - }
205 - private closeOverlay(result: "hide" | "close"): void {
206 - if (result === "hide") this.onHideOverlay();
207 - else this.onCloseOverlay();
208 - this.tui.requestRender(true);
209 - }
211 - private submit(value: string): void {
212 - const text = value.trim();
213 - if (!text) return;
215 - this.input.setValue("");
216 - this.scrollToBottom();
217 - this.onSubmitMessage(text);
218 - }
220 - private invalidateTranscriptCache(): void {
221 - this.cachedTranscriptLines = undefined;
222 - this.cachedTranscriptWidth = undefined;
223 - }
225 - private markTranscriptChanged(): void {
226 - this.invalidateTranscriptCache();
227 - if (this.followMode) this.scrollToBottom();
228 - }
230 - private scrollToBottom(): void {
231 - this.followMode = true;
232 - this.scrollOffset = BOTTOM_SCROLL;
233 - }
235 - private getFrameHeight(): number {
236 - const rows = Math.max(1, this.tui.terminal.rows);
237 - const available = Math.max(1, rows - this.verticalMargin);
238 - const configured =
239 - parseSize(this.maxHeight, rows) ?? Math.floor(rows * HEIGHT_RATIO);
240 - return Math.max(1, Math.min(configured, available));
241 - }
243 - private getFallbackInnerWidth(): number {
244 - const columns = Math.max(MIN_FRAME_WIDTH, this.tui.terminal.columns);
245 - return Math.max(1, Math.floor(columns * DEFAULT_WIDTH_RATIO) - 2);
246 - }
248 - private getTranscriptLines(width: number): string[] {
249 - if (this.cachedTranscriptLines && this.cachedTranscriptWidth === width) {
250 - return this.cachedTranscriptLines;
251 - }
253 - const lines = this.transcriptContainer
254 - .render(width)
255 - .map((line) => fitLine(line, width).trimEnd());
256 - this.cachedTranscriptLines = lines;
257 - this.cachedTranscriptWidth = width;
258 - return lines;
259 - }
261 - private getCurrentMaxScroll(): number {
262 - const innerWidth = this.lastInnerWidth || this.getFallbackInnerWidth();
263 - return this.calculateLayout(innerWidth + 2).maxScroll;
264 - }
266 - setStatus(text: string): void {
267 - this.statusText = text;
268 - this.tui.requestRender();
269 - }
271 - handleInput(data: string): void {
272 - if (matchesKey(data, Key.ctrl("s"))) return this.closeOverlay("hide");
273 - if (this.tryHandleScrollKey(data)) return;
275 - this.input.handleInput(data);
276 - this.tui.requestRender();
277 - }
279 - private tryHandleScrollKey(data: string): boolean {
280 - if (matchesKey(data, Key.up)) return this.scrollBy(-1);
281 - if (matchesKey(data, Key.down)) return this.scrollBy(1);
282 - if (matchesKey(data, Key.pageUp)) return this.scrollBy(-PAGE_SCROLL_ROWS);
283 - if (matchesKey(data, Key.pageDown)) return this.scrollBy(PAGE_SCROLL_ROWS);
284 - if (matchesKey(data, Key.home)) return this.scrollHome();
285 - if (matchesKey(data, Key.end)) return this.scrollEnd();
286 - return false;
287 - }
289 - private scrollBy(delta: number): true {
290 - const maxScroll = this.getCurrentMaxScroll();
292 - if (delta < 0) {
293 - this.followMode = false;
294 - this.scrollOffset = Math.max(
295 - 0,
296 - Math.min(this.scrollOffset, maxScroll) + delta,
297 - );
298 - this.tui.requestRender();
299 - return true;
300 - }
302 - if (!this.followMode) {
303 - this.scrollOffset = Math.min(maxScroll, this.scrollOffset + delta);
304 - if (this.scrollOffset >= maxScroll) this.scrollToBottom();
305 - }
307 - this.tui.requestRender();
308 - return true;
309 - }
311 - private scrollHome(): true {
312 - this.followMode = false;
313 - this.scrollOffset = 0;
314 - this.tui.requestRender();
315 - return true;
316 - }
318 - private scrollEnd(): true {
319 - this.scrollToBottom();
320 - this.tui.requestRender();
321 - return true;
322 - }
324 - handleSessionEvent(event: AgentSessionEvent): void {
325 - switch (event.type) {
326 - case "message_start":
327 - this.handleMessageStart(event.message);
328 - break;
329 - case "message_update":
330 - this.handleMessageUpdate(event.message);
331 - break;
332 - case "message_end":
333 - this.handleMessageEnd(event.message);
334 - break;
335 - case "tool_execution_start":
336 - this.handleToolStart(event.toolCallId, event.toolName, event.args);
337 - break;
338 - case "tool_execution_update":
339 - this.handleToolUpdate(event.toolCallId, event.partialResult);
340 - break;
341 - case "tool_execution_end":
342 - this.handleToolEnd(event.toolCallId, event.result, event.isError);
343 - break;
344 - case "agent_end":
345 - this.handleAgentEnd();
346 - return;
347 - }
349 - this.tui.requestRender();
350 - }
352 - private handleMessageStart(message: MessageStartEvent["message"]): void {
353 - if (message.role === "user") {
354 - this.transcriptContainer.addChild(
355 - new GhostMessageComponent("user", this.theme, message),
356 - );
357 - this.setStatus("Thinking...");
358 - this.markTranscriptChanged();
359 - return;
360 - }
362 - if (message.role !== "assistant") return;
364 - this.streamingComponent = new GhostMessageComponent(
365 - "assistant",
366 - this.theme,
367 - message,
368 - );
369 - this.transcriptContainer.addChild(this.streamingComponent);
370 - this.setStatus("Streaming response...");
371 - this.markTranscriptChanged();
372 - }
374 - private handleMessageUpdate(message: MessageUpdateEvent["message"]): void {
375 - if (message.role !== "assistant" || !this.streamingComponent) return;
377 - this.streamingComponent.updateContent(message);
378 - this.markTranscriptChanged();
379 - }
381 - private handleMessageEnd(message: MessageEndEvent["message"]): void {
382 - if (message.role !== "assistant") return;
384 - this.streamingComponent?.updateContent(message);
385 - this.finishPendingTools(message);
386 - this.streamingComponent = undefined;
387 - this.setStatus(DEFAULT_STATUS);
388 - this.markTranscriptChanged();
389 - }
391 - private finishPendingTools(message: AssistantMessage): void {
392 - if (!this.pendingTools.size) return;
394 - if (message.stopReason === "aborted" || message.stopReason === "error") {
395 - this.failPendingTools(message.errorMessage || "Error");
396 - return;
397 - }
399 - for (const component of this.pendingTools.values())
400 - component.setArgsComplete();
401 - }
403 - private failPendingTools(errorMessage: string): void {
404 - for (const component of this.pendingTools.values()) {
405 - component.updateResult({
406 - content: [{ type: "text", text: errorMessage }],
407 - isError: true,
408 - });
409 - }
410 - this.pendingTools.clear();
411 - }
413 - private handleToolStart(
414 - toolCallId: string,
415 - toolName: string,
416 - args: unknown,
417 - ): void {
418 - let component = this.pendingTools.get(toolCallId);
420 - if (!component) {
421 - component = new ToolExecutionComponent(
422 - toolName,
423 - toolCallId,
424 - args,
425 - { showImages: true },
426 - undefined,
427 - this.tui,
428 - this.sessionCwd,
429 - );
430 - this.transcriptContainer.addChild(component);
431 - this.pendingTools.set(toolCallId, component);
432 - }
434 - component.markExecutionStarted();
435 - this.setStatus(`Running ${toolName}...`);
436 - this.markTranscriptChanged();
437 - }
439 - private handleToolUpdate(
440 - toolCallId: string,
441 - partialResult: ToolUpdateEvent["partialResult"],
442 - ): void {
443 - const component = this.pendingTools.get(toolCallId);
444 - if (!component) return;
446 - component.updateResult({ ...partialResult, isError: false }, true);
447 - this.markTranscriptChanged();
448 - }
450 - private handleToolEnd(
451 - toolCallId: string,
452 - result: ToolEndEvent["result"],
453 - isError: boolean,
454 - ): void {
455 - const component = this.pendingTools.get(toolCallId);
456 - if (!component) return;
458 - component.updateResult({ ...result, isError });
459 - this.pendingTools.delete(toolCallId);
460 - this.markTranscriptChanged();
461 - }
463 - private handleAgentEnd(): void {
464 - this.streamingComponent = undefined;
465 - this.pendingTools.clear();
466 - this.setStatus(DEFAULT_STATUS);
467 - this.markTranscriptChanged();
468 - this.tui.requestRender();
469 - }
471 - invalidate(): void {
472 - this.transcriptContainer.invalidate();
473 - this.input.invalidate();
474 - this.invalidateTranscriptCache();
475 - }
477 - render(width: number): string[] {
478 - if (width <= 0) return [];
479 - if (width < MIN_FRAME_WIDTH) return this.renderTiny(width);
481 - const layout = this.calculateLayout(width);
482 - if (layout.frameHeight < MIN_FRAME_HEIGHT)
483 - return this.renderCompact(width, layout.frameHeight);
485 - this.lastInnerWidth = layout.innerWidth;
486 - this.updateScroll(layout.maxScroll);
488 - const transcript = layout.transcriptLines.slice(
489 - this.scrollOffset,
490 - this.scrollOffset + layout.transcriptRows,
491 - );
493 - return [
494 - this.renderHeader(layout.innerWidth),
495 - this.borderLine("├", "┤", layout.innerWidth),
496 - ...this.renderTranscript(
497 - transcript,
498 - layout.transcriptRows,
499 - layout.innerWidth,
500 - ),
501 - this.borderLine("├", "┤", layout.innerWidth),
502 - this.renderFooter(layout),
503 - ...layout.inputLines.map((line) =>
504 - this.boxedLine(line, layout.innerWidth),
505 - ),
506 - this.borderLine("╰", "╯", layout.innerWidth),
507 - ].slice(0, layout.frameHeight);
508 - }
510 - private calculateLayout(width: number): GhostOverlayLayout {
511 - const innerWidth = Math.max(1, width - 2);
512 - const frameHeight = this.getFrameHeight();
513 - const maxInputRows = Math.max(
514 - 1,
515 - frameHeight - FRAME_CHROME_ROWS - MIN_TRANSCRIPT_ROWS,
516 - );
517 - const inputLines = this.input
518 - .render(innerWidth)
519 - .slice(-maxInputRows)
520 - .map((line) => fitLine(line, innerWidth).trimEnd());
521 - const transcriptRows = Math.max(
522 - MIN_TRANSCRIPT_ROWS,
523 - frameHeight - FRAME_CHROME_ROWS - inputLines.length,
524 - );
525 - const transcriptLines = this.getTranscriptLines(innerWidth);
526 - const maxScroll = Math.max(0, transcriptLines.length - transcriptRows);
528 - return {
529 - innerWidth,
530 - frameHeight,
531 - inputLines,
532 - transcriptRows,
533 - transcriptLines,
534 - maxScroll,
535 - };
536 - }
538 - private updateScroll(maxScroll: number): void {
539 - if (this.followMode) {
540 - this.scrollOffset = maxScroll;
541 - return;
542 - }
544 - this.scrollOffset = Math.max(0, Math.min(this.scrollOffset, maxScroll));
545 - if (this.scrollOffset >= maxScroll) this.scrollToBottom();
546 - }
548 - private renderTiny(width: number): string[] {
549 - return [truncateToWidth(this.theme.fg("accent", "ghost"), width, "")];
550 - }
552 - private renderCompact(width: number, height: number): string[] {
553 - const content = `${this.theme.fg("accent", "ghost")} ${this.theme.fg("dim", this.statusText)}`;
554 - return Array.from({ length: Math.max(1, height) }, (_, index) =>
555 - index === 0 ? fitLine(content, width) : fitLine("", width),
556 - );
557 - }
559 - private renderHeader(innerWidth: number): string {
560 - const content = truncateToWidth(
561 - this.theme.fg("accent", ` ${this.theme.bold("ghost pi")} `) +
562 - this.theme.fg(
563 - "dim",
564 - "same model • ephemeral session • ↑↓ scroll • ctrl+s hide • esc close",
565 - ),
566 - innerWidth,
567 - );
568 - const pad = "─".repeat(Math.max(0, innerWidth - visibleWidth(content)));
569 - return (
570 - this.theme.fg("border", "╭") +
571 - content +
572 - this.theme.fg("border", pad + "╮")
573 - );
574 - }
576 - private renderTranscript(
577 - lines: string[],
578 - rowCount: number,
579 - innerWidth: number,
580 - ): string[] {
581 - const rows: string[] = [];
582 - for (const line of lines) rows.push(this.boxedLine(line, innerWidth));
583 - while (rows.length < rowCount) rows.push(this.boxedLine("", innerWidth));
584 - return rows;
585 - }
587 - private renderFooter(layout: GhostOverlayLayout): string {
588 - const info =
589 - layout.transcriptLines.length > layout.transcriptRows &&
590 - layout.transcriptRows > 0
591 - ? `${this.scrollOffset + 1}-${Math.min(this.scrollOffset + layout.transcriptRows, layout.transcriptLines.length)}/${layout.transcriptLines.length}`
592 - : `${layout.transcriptLines.length}L`;
593 - const followIcon = this.followMode
594 - ? this.theme.fg("success", "●")
595 - : this.theme.fg("dim", "○");
596 - const content = [
597 - this.theme.fg("dim", this.statusText),
598 - this.theme.fg("accent", this.modelLabel),
599 - this.theme.fg("dim", formatGhostCwd(this.sessionCwd)),
600 - this.theme.fg("dim", info),
601 - followIcon,
602 - ].join(` ${this.theme.fg("border", "│")} `);
604 - return this.boxedLine(content, layout.innerWidth);
605 - }
607 - private borderLine(left: string, right: string, innerWidth: number): string {
608 - return this.theme.fg("border", left + "─".repeat(innerWidth) + right);
609 - }
611 - private boxedLine(line: string, innerWidth: number): string {
612 - return (
613 - this.theme.fg("border", "│") +
614 - fitLine(line, innerWidth) +
615 - this.theme.fg("border", "│")
616 - );
617 - }
620 -export function fitLine(line: string, width: number): string {
621 - if (width <= 0) return "";
623 - const truncated = truncateToWidth(line, width, "");
624 - return truncated + " ".repeat(Math.max(0, width - visibleWidth(truncated)));
627 -export function extractMessageText(message: { content: unknown }): string {
628 - if (typeof message.content === "string")
629 - return safeDisplayText(message.content);
630 - if (!Array.isArray(message.content)) return "";
632 - return safeDisplayText(
633 - message.content
634 - .filter(
635 - (part): part is { type: "text"; text: string } =>
636 - typeof part === "object" &&
637 - part !== null &&
638 - (part as { type?: unknown }).type === "text" &&
639 - typeof (part as { text?: unknown }).text === "string",
640 - )
641 - .map((part) => part.text)
642 - .join("\n"),
643 - );
646 -export function formatGhostCwd(cwd: string): string {
647 - const home = process.env.HOME;
648 - if (home && cwd.startsWith(home)) {
649 - return `~${cwd.slice(home.length)}` || "~";
650 - }
651 - return cwd;
654 -function parseSize(value: SizeValue, reference: number): number | undefined {
655 - if (typeof value === "number") return Math.floor(value);
657 - const match = /^(\d+(?:\.\d+)?)%$/.exec(value);
658 - if (!match) return undefined;
659 - return Math.floor((reference * Number(match[1])) / 100);
662 -function toHistoryMessage(message: unknown): GhostHistoryMessage | undefined {
663 - if (typeof message !== "object" || message === null) return undefined;
664 - const candidate = message as { role?: unknown; content?: unknown };
665 - if (typeof candidate.role !== "string") return undefined;
666 - return { role: candidate.role, content: candidate.content };
669 -function findLastAssistantIndex(
670 - messages: readonly (GhostHistoryMessage | undefined)[],
671 -): number {
672 - for (let index = messages.length - 1; index >= 0; index--) {
673 - if (messages[index]?.role === "assistant") return index;
674 - }
675 - return -1;
678 -function marginHeight(margin: OverlayMargin | undefined): number {
679 - return Math.max(
680 - DEFAULT_VERTICAL_MARGIN,
681 - Math.max(0, margin?.top ?? 0) + Math.max(0, margin?.bottom ?? 0),
682 - );

extensions/ghost/package.json

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

package-lock.json

Modified
124 124 "@earendil-works/pi-tui": "*"
127 - "extensions/ghost": {
128 - "name": "@bugabinga/pi-ext-ghost",
129 - "license": "MIT",
130 - "devDependencies": {
131 - "@marcfargas/pi-test-harness": "^0.6.1"
132 - },
133 - "peerDependencies": {
134 - "@earendil-works/pi-ai": "*",
135 - "@earendil-works/pi-coding-agent": "*",
136 - "@earendil-works/pi-tui": "*"
138 - },
139 127 "extensions/git-safe": {
140 128 "name": "@bugabinga/pi-ext-git-safe",
141 129 "license": "MIT",
935 923 "resolved": "extensions/footer",
936 924 "link": true
938 - "node_modules/@bugabinga/pi-ext-ghost": {
939 - "resolved": "extensions/ghost",
940 - "link": true
941 - },
942 926 "node_modules/@bugabinga/pi-ext-git-safe": {
943 927 "resolved": "extensions/git-safe",
944 928 "link": true