@clementprevot/pi-ghostty-session 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (4) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +75 -2
  3. package/index.ts +258 -0
  4. package/package.json +47 -5
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Clément Prévot
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,76 @@
1
- # Temporary Holding Version
1
+ # @clementprevot/pi-ghostty-session
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A [Pi](https://pi.dev) extension that opens a new pi session in a Ghostty split, tab, or window on macOS. The session starts in the folder you pick, runs the prompt you give it, and stays a normal interactive session: you switch to it and carry on.
4
+
5
+ Use it when you want the agent to set up a session for you to join, for example a parallel task in a fresh worktree.
6
+
7
+ ## Install
8
+
9
+ ```bash
10
+ pi install npm:@clementprevot/pi-ghostty-session
11
+ ```
12
+
13
+ Updates ship with `pi update --extensions`. The extension applies to your next session (quit and relaunch, or run `/reload`).
14
+
15
+ Requirements: macOS, Ghostty 1.3 or later (AppleScript support), and pi running inside Ghostty.
16
+
17
+ ## Usage
18
+
19
+ The agent calls the `open_session` tool:
20
+
21
+ ```json
22
+ {
23
+ "surface": "split-down",
24
+ "cwd": "~/worktrees/my-repo/fix-login",
25
+ "prompt": "Fix the login redirect bug described in TICKET-123, then run the tests.",
26
+ "model": "anthropic/claude-sonnet-4-5",
27
+ "name": "fix-login"
28
+ }
29
+ ```
30
+
31
+ - `surface`: `split-right`, `split-down`, `split-left`, `split-up` (a split of the pane that runs the current session), `tab` (a new tab in its window), or `window`.
32
+ - `cwd` (optional): folder to start in, absolute, relative to the working directory, or starting with `~/`. Defaults to the working directory.
33
+ - `prompt` (optional): the first message of the new session. Without it, pi opens idle.
34
+ - `model` (optional): passed to `pi --model`, so `provider/id` and a `:<thinking>` suffix work.
35
+ - `name` (optional): the session display name, passed to `pi --name`.
36
+
37
+ You can open one yourself with `/open-session <surface> [prompt]`, for example `/open-session split-right review the open TODOs`.
38
+
39
+ To have your agent use it, add a line like this one to your instructions: "When I ask for a new session I can join, open it with `open_session`."
40
+
41
+ ## How it works
42
+
43
+ 1. The tool resolves the folder and checks that it exists.
44
+ 2. If there is a prompt, it writes it to a private file (mode 600) in `pi-ghostty-session/` under the system temp directory.
45
+ 3. It runs one AppleScript through `osascript`. The script asks Ghostty for a new surface and types `pi [--model ...] [--name ...] -- "$(cat <prompt file>)"` into it. Every value reaches the script as an argument, never as script source.
46
+ 4. For a split or a tab, the script finds the terminal of the current session by its TTY. The new surface lands next to this session even when another pane has the focus. If the script cannot find that terminal (inside tmux, for example), it uses the focused terminal of the front window and says so. With no Ghostty window open, it opens a new window.
47
+
48
+ The command runs in a fresh shell, so your PATH and shell setup apply, and the shell stays open when you quit pi.
49
+
50
+ ## Limits
51
+
52
+ - macOS and Ghostty only. Elsewhere the tool reports an error.
53
+ - macOS may ask once whether your terminal may control Ghostty. If you declined, allow it in System Settings, Privacy & Security, Automation.
54
+ - The prompt files stay in the temp directory, which macOS cleans up on its own.
55
+
56
+ ## Privacy and data
57
+
58
+ The extension writes the prompts you send to the temp directory and talks to Ghostty through AppleScript. It makes no network calls and collects no data.
59
+
60
+ ## Local development
61
+
62
+ ```bash
63
+ npm install
64
+ npm test
65
+ npm run typecheck
66
+ ```
67
+
68
+ To try the extension in a live session without installing it:
69
+
70
+ ```bash
71
+ pi -e /path/to/this/repo
72
+ ```
73
+
74
+ ## License
75
+
76
+ [MIT](LICENSE)
package/index.ts ADDED
@@ -0,0 +1,258 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { mkdirSync, statSync, writeFileSync } from "node:fs";
3
+ import { homedir, tmpdir } from "node:os";
4
+ import { join, resolve } from "node:path";
5
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
6
+ import { Type } from "typebox";
7
+
8
+ export const SURFACES = ["split-right", "split-down", "split-left", "split-up", "tab", "window"] as const;
9
+ export type Surface = (typeof SURFACES)[number];
10
+
11
+ export type SessionRequest = {
12
+ surface: Surface;
13
+ cwd?: string;
14
+ prompt?: string;
15
+ model?: string;
16
+ name?: string;
17
+ };
18
+
19
+ type Exec = Pick<ExtensionAPI, "exec">["exec"];
20
+ type Env = Record<string, string | undefined>;
21
+
22
+ const SURFACE_LABELS: Record<Surface, string> = {
23
+ "split-right": "a split to the right of this session",
24
+ "split-down": "a split below this session",
25
+ "split-left": "a split to the left of this session",
26
+ "split-up": "a split above this session",
27
+ tab: "a new tab of this session's window",
28
+ window: "a new window",
29
+ };
30
+
31
+ // The script receives every value through argv, so nothing user-provided is ever spliced into AppleScript source.
32
+ export const GHOSTTY_SCRIPT = `on run argv
33
+ set {surfaceKind, workingDirectory, startInput, ownTty} to argv
34
+ tell application "Ghostty"
35
+ set cfg to new surface configuration
36
+ set initial working directory of cfg to workingDirectory
37
+ set initial input of cfg to startInput
38
+ if surfaceKind is "window" or (count of windows) is 0 then
39
+ new window with configuration cfg
40
+ return "window"
41
+ end if
42
+ set targetWindow to missing value
43
+ set targetTerminal to missing value
44
+ repeat with w in windows
45
+ repeat with t in terminals of w
46
+ if tty of t is ownTty then
47
+ set targetWindow to contents of w
48
+ set targetTerminal to contents of t
49
+ exit repeat
50
+ end if
51
+ end repeat
52
+ if targetTerminal is not missing value then exit repeat
53
+ end repeat
54
+ set located to "own"
55
+ if targetTerminal is missing value then
56
+ set located to "front"
57
+ set targetWindow to front window
58
+ set targetTerminal to focused terminal of selected tab of targetWindow
59
+ end if
60
+ if surfaceKind is "tab" then
61
+ new tab in targetWindow with configuration cfg
62
+ else if surfaceKind is "split-right" then
63
+ split targetTerminal direction right with configuration cfg
64
+ else if surfaceKind is "split-down" then
65
+ split targetTerminal direction down with configuration cfg
66
+ else if surfaceKind is "split-left" then
67
+ split targetTerminal direction left with configuration cfg
68
+ else if surfaceKind is "split-up" then
69
+ split targetTerminal direction up with configuration cfg
70
+ else
71
+ error "Unknown surface: " & surfaceKind
72
+ end if
73
+ return located
74
+ end tell
75
+ end run`;
76
+
77
+ export function isSurface(value: string): value is Surface {
78
+ return (SURFACES as readonly string[]).includes(value);
79
+ }
80
+
81
+ export function shellQuote(value: string): string {
82
+ return `'${value.replaceAll("'", `'\\''`)}'`;
83
+ }
84
+
85
+ export function buildPiCommand(options: { promptFile?: string; model?: string; name?: string }): string {
86
+ const parts = ["pi"];
87
+ if (options.model) {
88
+ parts.push("--model", shellQuote(options.model));
89
+ }
90
+ if (options.name) {
91
+ parts.push("--name", shellQuote(options.name));
92
+ }
93
+ // The prompt goes through a file so its quotes, newlines and length never reach the shell input line.
94
+ if (options.promptFile) {
95
+ parts.push("--", `"$(cat ${shellQuote(options.promptFile)})"`);
96
+ }
97
+
98
+ return parts.join(" ");
99
+ }
100
+
101
+ export function resolveDirectory(input: string | undefined, cwd: string, home = homedir()): string {
102
+ const path = input?.trim();
103
+ if (!path) {
104
+ return cwd;
105
+ }
106
+ if (path === "~") {
107
+ return home;
108
+ }
109
+ if (path.startsWith("~/")) {
110
+ return resolve(home, path.slice(2));
111
+ }
112
+
113
+ return resolve(cwd, path);
114
+ }
115
+
116
+ export function isGhosttyOnMac(env: Env = process.env, platform: string = process.platform): boolean {
117
+ return platform === "darwin" && (env.TERM_PROGRAM === "ghostty" || Boolean(env.GHOSTTY_RESOURCES_DIR));
118
+ }
119
+
120
+ export function writePromptFile(prompt: string, dir = join(tmpdir(), "pi-ghostty-session")): string {
121
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
122
+ const file = join(dir, `${randomUUID()}.md`);
123
+ writeFileSync(file, prompt, { mode: 0o600 });
124
+
125
+ return file;
126
+ }
127
+
128
+ async function ownTty(exec: Exec): Promise<string> {
129
+ const result = await exec("ps", ["-o", "tty=", "-p", String(process.pid)], { timeout: 5000 });
130
+ const tty = result.stdout.trim();
131
+ const hasTty = result.code === 0 && tty !== "" && !tty.startsWith("?");
132
+
133
+ return hasTty ? `/dev/${tty}` : "";
134
+ }
135
+
136
+ function scriptError(result: { stderr: string; code: number }): Error {
137
+ const reason = result.stderr.trim() || `osascript exited with code ${result.code}`;
138
+ if (reason.includes("-1743")) {
139
+ return new Error(
140
+ "macOS blocked the AppleScript call to Ghostty. Allow it in System Settings > Privacy & Security > Automation, then retry.",
141
+ );
142
+ }
143
+
144
+ return new Error(`Ghostty could not open the session: ${reason}`);
145
+ }
146
+
147
+ function describeOpened(surface: Surface, located: string, directory: string, hasPrompt: boolean): string {
148
+ const isWindowFallback = located === "window" && surface !== "window";
149
+ const where = isWindowFallback ? "a new window, since no Ghostty window was open" : SURFACE_LABELS[surface];
150
+ const lines = [`Opened a new pi session in ${where}, in ${directory}, ${hasPrompt ? "started with the prompt" : "with no prompt"}.`];
151
+ if (located === "front") {
152
+ lines.push("This session's own Ghostty terminal was not found, so the new session opened next to the focused terminal of the front window.");
153
+ }
154
+
155
+ return lines.join(" ");
156
+ }
157
+
158
+ /** Throws errors whose message is shown as-is to the model or the user. */
159
+ export async function openSession(
160
+ exec: Exec,
161
+ request: SessionRequest,
162
+ cwd: string,
163
+ options: { env?: Env; platform?: string; signal?: AbortSignal; promptDir?: string } = {},
164
+ ): Promise<string> {
165
+ if (!isGhosttyOnMac(options.env, options.platform)) {
166
+ throw new Error("open_session needs pi running inside Ghostty on macOS.");
167
+ }
168
+ if (!isSurface(request.surface)) {
169
+ throw new Error(`Unknown surface "${request.surface}". Use one of: ${SURFACES.join(", ")}.`);
170
+ }
171
+ const directory = resolveDirectory(request.cwd, cwd);
172
+ if (!statSync(directory, { throwIfNoEntry: false })?.isDirectory()) {
173
+ throw new Error(`${directory} is not a directory.`);
174
+ }
175
+
176
+ const prompt = request.prompt?.trim();
177
+ const command = buildPiCommand({
178
+ promptFile: prompt ? writePromptFile(prompt, options.promptDir) : undefined,
179
+ model: request.model?.trim(),
180
+ name: request.name?.trim(),
181
+ });
182
+ const result = await exec(
183
+ "osascript",
184
+ ["-e", GHOSTTY_SCRIPT, request.surface, directory, `${command}\n`, await ownTty(exec)],
185
+ { signal: options.signal, timeout: 15_000 },
186
+ );
187
+ if (result.code !== 0) {
188
+ throw scriptError(result);
189
+ }
190
+
191
+ return describeOpened(request.surface, result.stdout.trim(), directory, Boolean(prompt));
192
+ }
193
+
194
+ export function parseCommandArgs(args: string): SessionRequest | undefined {
195
+ const surface = args.trim().split(/\s+/)[0] ?? "";
196
+ if (!isSurface(surface)) {
197
+ return undefined;
198
+ }
199
+ const prompt = args.trim().slice(surface.length).trim();
200
+
201
+ return prompt ? { surface, prompt } : { surface };
202
+ }
203
+
204
+ export default function ghosttySessionExtension(pi: ExtensionAPI): void {
205
+ pi.registerTool({
206
+ name: "open_session",
207
+ label: "Open session",
208
+ description:
209
+ "Open a new interactive pi session in a Ghostty split, tab, or window on macOS, in the folder you choose and started with your prompt. The user can then join and drive it directly.",
210
+ promptSnippet: "Open a new interactive pi session for the user in a Ghostty split, tab, or window",
211
+ promptGuidelines: [
212
+ "Use open_session when the user asks for a new session or agent they can join, not for a background subagent.",
213
+ "Write the open_session prompt so it stands alone: the new session knows nothing about this conversation.",
214
+ ],
215
+ parameters: Type.Object({
216
+ surface: Type.Unsafe<Surface>({
217
+ type: "string",
218
+ enum: [...SURFACES],
219
+ description: "Where to open it: a split of this session's pane in a direction, a new tab in this window, or a new window",
220
+ }),
221
+ cwd: Type.Optional(
222
+ Type.String({ description: "Folder to start in: absolute, relative to the working directory, or starting with ~/. Defaults to the working directory" }),
223
+ ),
224
+ prompt: Type.Optional(Type.String({ description: "First message the new session runs. Omit to open an idle session" })),
225
+ model: Type.Optional(Type.String({ description: "Model for the new session, as provider/id with an optional :<thinking> suffix" })),
226
+ name: Type.Optional(Type.String({ description: "Display name of the new session" })),
227
+ }),
228
+ async execute(_toolCallId, params, signal, _onUpdate, ctx) {
229
+ const text = await openSession(pi.exec.bind(pi), params, ctx.cwd, { signal });
230
+
231
+ return { content: [{ type: "text", text }], details: undefined };
232
+ },
233
+ });
234
+
235
+ pi.registerCommand("open-session", {
236
+ description: `Open a new pi session in Ghostty: /open-session <${SURFACES.join("|")}> [prompt]`,
237
+ getArgumentCompletions: (prefix) => {
238
+ if (/\s/.test(prefix)) {
239
+ return null;
240
+ }
241
+ const items = SURFACES.filter((surface) => surface.startsWith(prefix)).map((surface) => ({ value: surface, label: surface }));
242
+
243
+ return items.length > 0 ? items : null;
244
+ },
245
+ handler: async (args, ctx) => {
246
+ const request = parseCommandArgs(args);
247
+ if (!request) {
248
+ ctx.ui.notify(`Usage: /open-session <${SURFACES.join("|")}> [prompt]`, "error");
249
+ return;
250
+ }
251
+ try {
252
+ ctx.ui.notify(await openSession(pi.exec.bind(pi), request, ctx.cwd), "info");
253
+ } catch (error) {
254
+ ctx.ui.notify(error instanceof Error ? error.message : String(error), "error");
255
+ }
256
+ },
257
+ });
258
+ }
package/package.json CHANGED
@@ -1,6 +1,48 @@
1
1
  {
2
- "name": "@clementprevot/pi-ghostty-session",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
2
+ "name": "@clementprevot/pi-ghostty-session",
3
+ "version": "0.1.1",
4
+ "description": "Pi extension that opens a new pi session in a Ghostty split, tab, or window on macOS, started in the folder and with the prompt you choose",
5
+ "keywords": [
6
+ "pi-package",
7
+ "pi-extension",
8
+ "ghostty",
9
+ "terminal",
10
+ "session",
11
+ "split",
12
+ "applescript"
13
+ ],
14
+ "license": "MIT",
15
+ "type": "module",
16
+ "repository": {
17
+ "type": "git",
18
+ "url": "git+https://github.com/clementprevot/pi-ghostty-session.git"
19
+ },
20
+ "engines": {
21
+ "node": ">=22.6"
22
+ },
23
+ "files": [
24
+ "index.ts"
25
+ ],
26
+ "pi": {
27
+ "extensions": [
28
+ "./index.ts"
29
+ ]
30
+ },
31
+ "peerDependencies": {
32
+ "@earendil-works/pi-coding-agent": "*",
33
+ "typebox": "*"
34
+ },
35
+ "devDependencies": {
36
+ "@earendil-works/pi-coding-agent": "*",
37
+ "@types/node": "^24.0.0",
38
+ "typebox": "*",
39
+ "typescript": "^5.9.0"
40
+ },
41
+ "scripts": {
42
+ "test": "node --test test/*.test.ts",
43
+ "typecheck": "tsc --noEmit"
44
+ },
45
+ "publishConfig": {
46
+ "access": "public"
47
+ }
48
+ }