@clementprevot/pi-ghostty-session 0.1.1 → 0.2.0

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 (3) hide show
  1. package/README.md +40 -6
  2. package/index.ts +314 -63
  3. package/package.json +2 -2
package/README.md CHANGED
@@ -1,8 +1,8 @@
1
1
  # @clementprevot/pi-ghostty-session
2
2
 
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.
3
+ A [Pi](https://pi.dev) extension that opens new pi sessions in Ghostty on macOS: one in a split, tab, or window, or several at once grouped in titled tabs. Each 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
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.
5
+ Use it when you want the agent to set up sessions for you to join, for example a parallel task in a fresh worktree, or one review session per pull request.
6
6
 
7
7
  ## Install
8
8
 
@@ -36,14 +36,48 @@ The agent calls the `open_session` tool:
36
36
 
37
37
  You can open one yourself with `/open-session <surface> [prompt]`, for example `/open-session split-right review the open TODOs`.
38
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`."
39
+ The result gives the id of the new session's tab and terminal. Pass the tab id to `open_sessions` to add sessions to that tab later.
40
+
41
+ ### Several sessions at once
42
+
43
+ The agent calls the `open_sessions` tool with one entry per tab:
44
+
45
+ ```json
46
+ {
47
+ "tabs": [
48
+ {
49
+ "title": "Jira",
50
+ "sessions": [
51
+ { "name": "review-web-ui-101", "cwd": "~/repos/web-ui", "prompt": "Review https://github.com/org/web-ui/pull/101." },
52
+ { "name": "review-api-202", "cwd": "~/repos/api", "prompt": "Review https://github.com/org/api/pull/202." }
53
+ ]
54
+ },
55
+ {
56
+ "title": "Billing",
57
+ "sessions": [
58
+ { "name": "review-api-203", "cwd": "~/repos/api", "prompt": "Review https://github.com/org/api/pull/203." }
59
+ ]
60
+ }
61
+ ]
62
+ }
63
+ ```
64
+
65
+ - `tabs`: each entry opens a new tab and gives every session its own pane in it.
66
+ - `title` (optional): the tab title, usually the topic. It also renames an existing tab.
67
+ - `tab` (optional): the id of a tab opened earlier by `open_session` or `open_sessions`. The sessions join that tab instead of a new one.
68
+ - `sessions`: the sessions of the tab, with the same `cwd`, `prompt`, `model` and `name` fields as `open_session`.
69
+ - `placement` (optional, top level): `tab` puts the new tabs in the window of the current session, which is the default. `window` puts them in a new window.
70
+
71
+ The panes of a tab sit in two columns, filled row by row: the second pane goes right of the first, the third under the first, and so on. Ghostty then evens out their sizes. The result lists each tab id and each session's terminal id.
72
+
73
+ To have your agent use them, add lines like these to your instructions: "When I ask for a new session I can join, open it with `open_session`. When I ask for several related sessions at once, open them with `open_sessions`: one tab per topic, one pane per session."
40
74
 
41
75
  ## How it works
42
76
 
43
- 1. The tool resolves the folder and checks that it exists.
77
+ 1. The tool resolves each folder and checks that it exists, before it asks Ghostty for anything.
44
78
  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.
79
+ 3. It runs one AppleScript through `osascript`, even for a batch. The script asks Ghostty for each new surface and types `pi [--model ...] [--name ...] "$(command cat <prompt file>)"` into it. Every value reaches the script as an argument, never as script source.
80
+ 4. For a split or a new 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 front window and says so. With no Ghostty window open, it opens a new window.
47
81
 
48
82
  The command runs in a fresh shell, so your PATH and shell setup apply, and the shell stays open when you quit pi.
49
83
 
package/index.ts CHANGED
@@ -8,16 +8,39 @@ import { Type } from "typebox";
8
8
  export const SURFACES = ["split-right", "split-down", "split-left", "split-up", "tab", "window"] as const;
9
9
  export type Surface = (typeof SURFACES)[number];
10
10
 
11
- export type SessionRequest = {
12
- surface: Surface;
11
+ export const PLACEMENTS = ["tab", "window"] as const;
12
+ export type Placement = (typeof PLACEMENTS)[number];
13
+
14
+ export type SessionSpec = {
13
15
  cwd?: string;
14
16
  prompt?: string;
15
17
  model?: string;
16
18
  name?: string;
17
19
  };
18
20
 
21
+ export type SessionRequest = SessionSpec & { surface: Surface };
22
+
23
+ export type TabRequest = {
24
+ title?: string;
25
+ tab?: string;
26
+ sessions: SessionSpec[];
27
+ };
28
+
29
+ export type BatchRequest = {
30
+ placement?: Placement;
31
+ tabs: TabRequest[];
32
+ };
33
+
34
+ export type OpenedTab = {
35
+ id: string;
36
+ title?: string;
37
+ sessions: { name?: string; directory: string; terminal: string }[];
38
+ };
39
+
19
40
  type Exec = Pick<ExtensionAPI, "exec">["exec"];
20
41
  type Env = Record<string, string | undefined>;
42
+ type ScriptOptions = { env?: Env; platform?: string; signal?: AbortSignal; promptDir?: string };
43
+ type PreparedSession = { directory: string; input: string; hasPrompt: boolean; name?: string };
21
44
 
22
45
  const SURFACE_LABELS: Record<Surface, string> = {
23
46
  "split-right": "a split to the right of this session",
@@ -28,49 +51,147 @@ const SURFACE_LABELS: Record<Surface, string> = {
28
51
  window: "a new window",
29
52
  };
30
53
 
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
54
+ const SCRIPT_HANDLERS = `on findOwn(ownTty)
55
+ tell application "Ghostty"
56
+ repeat with w in windows
57
+ repeat with t in terminals of w
58
+ if tty of t is ownTty then return {contents of w, contents of t}
59
+ end repeat
60
+ end repeat
61
+ end tell
62
+ return missing value
63
+ end findOwn
64
+
65
+ on findTab(tabId)
66
+ tell application "Ghostty"
67
+ repeat with w in windows
68
+ repeat with t in tabs of w
69
+ if id of t is tabId then return contents of t
70
+ end repeat
71
+ end repeat
72
+ end tell
73
+ error "No Ghostty tab has the id " & tabId & "."
74
+ end findTab
75
+
76
+ on tabIdOf(terminalId)
77
+ tell application "Ghostty"
78
+ repeat with w in windows
79
+ repeat with t in tabs of w
80
+ repeat with s in terminals of t
81
+ if id of s is terminalId then return id of t
82
+ end repeat
83
+ end repeat
84
+ end repeat
85
+ end tell
86
+ return ""
87
+ end tabIdOf
88
+
89
+ -- Ghostty lists the terminals of a tab column by column, so the panes stay in two columns filled row by row: the second
90
+ -- pane goes right of the first, and each later one goes under the bottom pane of the shorter column.
91
+ on addToGrid(targetTab, cfg)
92
+ tell application "Ghostty"
93
+ set existing to terminals of targetTab
94
+ set k to count of existing
95
+ if k is 1 then return split (item 1 of existing) direction right with configuration cfg
96
+ if k mod 2 is 0 then return split (item (k div 2) of existing) direction down with configuration cfg
97
+ return split (item k of existing) direction down with configuration cfg
98
+ end tell
99
+ end addToGrid
100
+ `;
101
+
102
+ // The scripts receive every value through argv, so nothing user-provided is ever spliced into AppleScript source.
103
+ export const GHOSTTY_SCRIPT = `${SCRIPT_HANDLERS}
104
+ on run argv
105
+ set sep to character id 9
33
106
  set {surfaceKind, workingDirectory, startInput, ownTty} to argv
34
107
  tell application "Ghostty"
35
108
  set cfg to new surface configuration
36
109
  set initial working directory of cfg to workingDirectory
37
110
  set initial input of cfg to startInput
38
111
  if surfaceKind is "window" or (count of windows) is 0 then
39
- new window with configuration cfg
40
- return "window"
112
+ set newWindow to new window with configuration cfg
113
+ set newTab to selected tab of newWindow
114
+ return "window" & sep & (id of newTab) & sep & (id of (focused terminal of newTab))
41
115
  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
116
  set located to "own"
55
- if targetTerminal is missing value then
117
+ set ownPair to my findOwn(ownTty)
118
+ if ownPair is missing value then
56
119
  set located to "front"
57
120
  set targetWindow to front window
58
121
  set targetTerminal to focused terminal of selected tab of targetWindow
122
+ else
123
+ set {targetWindow, targetTerminal} to ownPair
59
124
  end if
60
125
  if surfaceKind is "tab" then
61
- new tab in targetWindow with configuration cfg
126
+ set newTab to new tab in targetWindow with configuration cfg
127
+ return located & sep & (id of newTab) & sep & (id of (focused terminal of newTab))
62
128
  else if surfaceKind is "split-right" then
63
- split targetTerminal direction right with configuration cfg
129
+ set newTerminal to split targetTerminal direction right with configuration cfg
64
130
  else if surfaceKind is "split-down" then
65
- split targetTerminal direction down with configuration cfg
131
+ set newTerminal to split targetTerminal direction down with configuration cfg
66
132
  else if surfaceKind is "split-left" then
67
- split targetTerminal direction left with configuration cfg
133
+ set newTerminal to split targetTerminal direction left with configuration cfg
68
134
  else if surfaceKind is "split-up" then
69
- split targetTerminal direction up with configuration cfg
135
+ set newTerminal to split targetTerminal direction up with configuration cfg
70
136
  else
71
137
  error "Unknown surface: " & surfaceKind
72
138
  end if
73
- return located
139
+ return located & sep & (my tabIdOf(id of newTerminal)) & sep & (id of newTerminal)
140
+ end tell
141
+ end run`;
142
+
143
+ export const GHOSTTY_BATCH_SCRIPT = `${SCRIPT_HANDLERS}
144
+ on run argv
145
+ set sep to character id 9
146
+ set placement to item 1 of argv
147
+ set ownTty to item 2 of argv
148
+ set tabCount to (item 3 of argv) as integer
149
+ set pos to 4
150
+ tell application "Ghostty"
151
+ set targetWindow to missing value
152
+ set located to "window"
153
+ if placement is "tab" then
154
+ set ownPair to my findOwn(ownTty)
155
+ if ownPair is not missing value then
156
+ set targetWindow to item 1 of ownPair
157
+ set located to "own"
158
+ else if (count of windows) > 0 then
159
+ set targetWindow to front window
160
+ set located to "front"
161
+ end if
162
+ end if
163
+ set out to "located" & sep & located & linefeed
164
+ repeat tabCount times
165
+ set tabTitle to item pos of argv
166
+ set existingTabId to item (pos + 1) of argv
167
+ set sessionCount to (item (pos + 2) of argv) as integer
168
+ set pos to pos + 3
169
+ set targetTab to missing value
170
+ if existingTabId is not "" then set targetTab to my findTab(existingTabId)
171
+ set terminalLines to ""
172
+ repeat sessionCount times
173
+ set cfg to new surface configuration
174
+ set initial working directory of cfg to item pos of argv
175
+ set initial input of cfg to item (pos + 1) of argv
176
+ set pos to pos + 2
177
+ if targetTab is missing value then
178
+ if targetWindow is missing value then
179
+ set targetWindow to new window with configuration cfg
180
+ set targetTab to selected tab of targetWindow
181
+ else
182
+ set targetTab to new tab in targetWindow with configuration cfg
183
+ end if
184
+ set newTerminal to focused terminal of targetTab
185
+ else
186
+ set newTerminal to my addToGrid(targetTab, cfg)
187
+ end if
188
+ set terminalLines to terminalLines & "terminal" & sep & (id of newTerminal) & linefeed
189
+ end repeat
190
+ if tabTitle is not "" then set name override of targetTab to tabTitle
191
+ if (count of terminals of targetTab) > 1 then perform action "equalize_splits" on newTerminal
192
+ set out to out & "tab" & sep & (id of targetTab) & linefeed & terminalLines
193
+ end repeat
194
+ return out
74
195
  end tell
75
196
  end run`;
76
197
 
@@ -90,9 +211,10 @@ export function buildPiCommand(options: { promptFile?: string; model?: string; n
90
211
  if (options.name) {
91
212
  parts.push("--name", shellQuote(options.name));
92
213
  }
93
- // The prompt goes through a file so its quotes, newlines and length never reach the shell input line.
214
+ // The prompt goes through a file so its quotes, newlines and length never reach the shell input line. It follows no
215
+ // "--": Node 26.13.1 kills itself when "--" precedes an argument that reaches PATH_MAX once joined to the cwd.
94
216
  if (options.promptFile) {
95
- parts.push("--", `"$(cat ${shellQuote(options.promptFile)})"`);
217
+ parts.push(`"$(command cat ${shellQuote(options.promptFile)})"`);
96
218
  }
97
219
 
98
220
  return parts.join(" ");
@@ -120,11 +242,47 @@ export function isGhosttyOnMac(env: Env = process.env, platform: string = proces
120
242
  export function writePromptFile(prompt: string, dir = join(tmpdir(), "pi-ghostty-session")): string {
121
243
  mkdirSync(dir, { recursive: true, mode: 0o700 });
122
244
  const file = join(dir, `${randomUUID()}.md`);
123
- writeFileSync(file, prompt, { mode: 0o600 });
245
+ // Without "--", pi would read a leading "-" as an option and a leading "@" as a file to attach.
246
+ writeFileSync(file, /^[-@]/.test(prompt) ? `\n${prompt}` : prompt, { mode: 0o600 });
124
247
 
125
248
  return file;
126
249
  }
127
250
 
251
+ export function parseBatchOutput(stdout: string): { located: string; tabs: { id: string; terminals: string[] }[] } {
252
+ let located = "";
253
+ const tabs: { id: string; terminals: string[] }[] = [];
254
+ for (const line of stdout.split("\n")) {
255
+ const [kind, value = ""] = line.trim().split("\t");
256
+ if (kind === "located") {
257
+ located = value;
258
+ } else if (kind === "tab") {
259
+ tabs.push({ id: value, terminals: [] });
260
+ } else if (kind === "terminal") {
261
+ tabs.at(-1)?.terminals.push(value);
262
+ }
263
+ }
264
+
265
+ return { located, tabs };
266
+ }
267
+
268
+ function assertGhostty(tool: string, options: ScriptOptions): void {
269
+ if (!isGhosttyOnMac(options.env, options.platform)) {
270
+ throw new Error(`${tool} needs pi running inside Ghostty on macOS.`);
271
+ }
272
+ }
273
+
274
+ function prepareSession(spec: SessionSpec, cwd: string, promptDir?: string): PreparedSession {
275
+ const directory = resolveDirectory(spec.cwd, cwd);
276
+ if (!statSync(directory, { throwIfNoEntry: false })?.isDirectory()) {
277
+ throw new Error(`${directory} is not a directory.`);
278
+ }
279
+ const prompt = spec.prompt?.trim();
280
+ const name = spec.name?.trim() || undefined;
281
+ const command = buildPiCommand({ promptFile: prompt ? writePromptFile(prompt, promptDir) : undefined, model: spec.model?.trim(), name });
282
+
283
+ return { directory, input: `${command}\n`, hasPrompt: Boolean(prompt), name };
284
+ }
285
+
128
286
  async function ownTty(exec: Exec): Promise<string> {
129
287
  const result = await exec("ps", ["-o", "tty=", "-p", String(process.pid)], { timeout: 5000 });
130
288
  const tty = result.stdout.trim();
@@ -133,62 +291,115 @@ async function ownTty(exec: Exec): Promise<string> {
133
291
  return hasTty ? `/dev/${tty}` : "";
134
292
  }
135
293
 
136
- function scriptError(result: { stderr: string; code: number }): Error {
294
+ async function runScript(exec: Exec, script: string, args: string[], signal: AbortSignal | undefined, timeout: number): Promise<string> {
295
+ const result = await exec("osascript", ["-e", script, ...args], { signal, timeout });
296
+ if (result.code === 0) {
297
+ return result.stdout;
298
+ }
137
299
  const reason = result.stderr.trim() || `osascript exited with code ${result.code}`;
138
300
  if (reason.includes("-1743")) {
139
- return new Error(
301
+ throw new Error(
140
302
  "macOS blocked the AppleScript call to Ghostty. Allow it in System Settings > Privacy & Security > Automation, then retry.",
141
303
  );
142
304
  }
143
305
 
144
- return new Error(`Ghostty could not open the session: ${reason}`);
306
+ throw new Error(`Ghostty could not open the session: ${reason}`);
145
307
  }
146
308
 
147
- function describeOpened(surface: Surface, located: string, directory: string, hasPrompt: boolean): string {
309
+ function describeOpened(surface: Surface, stdout: string, directory: string, hasPrompt: boolean): string {
310
+ const [located, tabId, terminalId] = stdout.trim().split("\t");
148
311
  const isWindowFallback = located === "window" && surface !== "window";
149
312
  const where = isWindowFallback ? "a new window, since no Ghostty window was open" : SURFACE_LABELS[surface];
150
313
  const lines = [`Opened a new pi session in ${where}, in ${directory}, ${hasPrompt ? "started with the prompt" : "with no prompt"}.`];
151
314
  if (located === "front") {
152
315
  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
316
  }
317
+ if (tabId && terminalId) {
318
+ lines.push(`Its tab id is ${tabId} and its terminal id is ${terminalId}; pass the tab id to open_sessions to add sessions to that tab.`);
319
+ }
154
320
 
155
321
  return lines.join(" ");
156
322
  }
157
323
 
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.");
324
+ function describeBatch(tabs: OpenedTab[], located: string, opensTabs: boolean): string {
325
+ const count = tabs.reduce((total, tab) => total + tab.sessions.length, 0);
326
+ const lines = [`Opened ${count} pi session${count === 1 ? "" : "s"}:`];
327
+ for (const tab of tabs) {
328
+ const sessions = tab.sessions.map((session) => `${session.name ?? "unnamed"} in ${session.directory} (terminal id ${session.terminal})`);
329
+ lines.push(`- tab ${tab.title ? `"${tab.title}" ` : ""}(tab id ${tab.id}): ${sessions.join(", ")}`);
330
+ }
331
+ if (opensTabs && located === "front") {
332
+ lines.push("This session's own Ghostty terminal was not found, so the new tabs opened in the front window.");
167
333
  }
334
+ lines.push("Pass a tab id as `tab` to open_sessions to add sessions to that tab.");
335
+
336
+ return lines.join("\n");
337
+ }
338
+
339
+ /** Throws errors whose message is shown as-is to the model or the user. */
340
+ export async function openSession(exec: Exec, request: SessionRequest, cwd: string, options: ScriptOptions = {}): Promise<string> {
341
+ assertGhostty("open_session", options);
168
342
  if (!isSurface(request.surface)) {
169
343
  throw new Error(`Unknown surface "${request.surface}". Use one of: ${SURFACES.join(", ")}.`);
170
344
  }
171
- const directory = resolveDirectory(request.cwd, cwd);
172
- if (!statSync(directory, { throwIfNoEntry: false })?.isDirectory()) {
173
- throw new Error(`${directory} is not a directory.`);
345
+ const session = prepareSession(request, cwd, options.promptDir);
346
+ const stdout = await runScript(
347
+ exec,
348
+ GHOSTTY_SCRIPT,
349
+ [request.surface, session.directory, session.input, await ownTty(exec)],
350
+ options.signal,
351
+ 15_000,
352
+ );
353
+
354
+ return describeOpened(request.surface, stdout, session.directory, session.hasPrompt);
355
+ }
356
+
357
+ export async function openSessions(
358
+ exec: Exec,
359
+ request: BatchRequest,
360
+ cwd: string,
361
+ options: ScriptOptions = {},
362
+ ): Promise<{ text: string; tabs: OpenedTab[] }> {
363
+ assertGhostty("open_sessions", options);
364
+ const placement = request.placement ?? "tab";
365
+ if (!(PLACEMENTS as readonly string[]).includes(placement)) {
366
+ throw new Error(`Unknown placement "${placement}". Use one of: ${PLACEMENTS.join(", ")}.`);
367
+ }
368
+ if (!request.tabs?.length) {
369
+ throw new Error("open_sessions needs at least one tab.");
174
370
  }
371
+ const groups = request.tabs.map((group, index) => {
372
+ if (!group.sessions?.length) {
373
+ throw new Error(`Tab ${index + 1} has no sessions.`);
374
+ }
175
375
 
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(),
376
+ return {
377
+ title: group.title?.trim() ?? "",
378
+ tab: group.tab?.trim() ?? "",
379
+ sessions: group.sessions.map((session) => prepareSession(session, cwd, options.promptDir)),
380
+ };
181
381
  });
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);
382
+
383
+ const args = [placement, await ownTty(exec), String(groups.length)];
384
+ for (const group of groups) {
385
+ args.push(group.title, group.tab, String(group.sessions.length));
386
+ for (const session of group.sessions) {
387
+ args.push(session.directory, session.input);
388
+ }
189
389
  }
390
+ const sessionCount = groups.reduce((total, group) => total + group.sessions.length, 0);
391
+ const output = parseBatchOutput(await runScript(exec, GHOSTTY_BATCH_SCRIPT, args, options.signal, 10_000 + 5_000 * sessionCount));
392
+ const tabs = groups.map((group, index) => ({
393
+ id: output.tabs[index]?.id ?? "",
394
+ title: group.title || undefined,
395
+ sessions: group.sessions.map((session, position) => ({
396
+ name: session.name,
397
+ directory: session.directory,
398
+ terminal: output.tabs[index]?.terminals[position] ?? "",
399
+ })),
400
+ }));
190
401
 
191
- return describeOpened(request.surface, result.stdout.trim(), directory, Boolean(prompt));
402
+ return { text: describeBatch(tabs, output.located, groups.some((group) => !group.tab)), tabs };
192
403
  }
193
404
 
194
405
  export function parseCommandArgs(args: string): SessionRequest | undefined {
@@ -201,6 +412,15 @@ export function parseCommandArgs(args: string): SessionRequest | undefined {
201
412
  return prompt ? { surface, prompt } : { surface };
202
413
  }
203
414
 
415
+ const SESSION_FIELDS = {
416
+ cwd: Type.Optional(
417
+ Type.String({ description: "Folder to start in: absolute, relative to the working directory, or starting with ~/. Defaults to the working directory" }),
418
+ ),
419
+ prompt: Type.Optional(Type.String({ description: "First message the new session runs. Omit to open an idle session" })),
420
+ model: Type.Optional(Type.String({ description: "Model for the new session, as provider/id with an optional :<thinking> suffix" })),
421
+ name: Type.Optional(Type.String({ description: "Display name of the new session" })),
422
+ };
423
+
204
424
  export default function ghosttySessionExtension(pi: ExtensionAPI): void {
205
425
  pi.registerTool({
206
426
  name: "open_session",
@@ -218,12 +438,7 @@ export default function ghosttySessionExtension(pi: ExtensionAPI): void {
218
438
  enum: [...SURFACES],
219
439
  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
440
  }),
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" })),
441
+ ...SESSION_FIELDS,
227
442
  }),
228
443
  async execute(_toolCallId, params, signal, _onUpdate, ctx) {
229
444
  const text = await openSession(pi.exec.bind(pi), params, ctx.cwd, { signal });
@@ -232,6 +447,42 @@ export default function ghosttySessionExtension(pi: ExtensionAPI): void {
232
447
  },
233
448
  });
234
449
 
450
+ pi.registerTool({
451
+ name: "open_sessions",
452
+ label: "Open sessions",
453
+ description:
454
+ "Open several interactive pi sessions at once in Ghostty on macOS, grouped in tabs: each tab gets a title and holds one pane per session, laid out in two columns. Can also add sessions to a tab opened earlier, by its tab id.",
455
+ promptSnippet: "Open several related pi sessions for the user at once, one Ghostty tab per topic and one pane per session",
456
+ promptGuidelines: [
457
+ "Use open_sessions instead of several open_session calls when the user asks for several related sessions at once: one tab per topic, titled after it, with one pane per session.",
458
+ "To add sessions to a tab that open_session or open_sessions opened earlier, pass its tab id as `tab` in open_sessions.",
459
+ ],
460
+ parameters: Type.Object({
461
+ placement: Type.Optional(
462
+ Type.Unsafe<Placement>({
463
+ type: "string",
464
+ enum: [...PLACEMENTS],
465
+ description: "Where new tabs go: in this session's window (tab, the default) or in a new window",
466
+ }),
467
+ ),
468
+ tabs: Type.Array(
469
+ Type.Object({
470
+ title: Type.Optional(Type.String({ description: "Tab title, usually the topic. Also renames an existing tab" })),
471
+ tab: Type.Optional(
472
+ Type.String({ description: "Id of an existing tab, as returned by open_session or open_sessions, to add the sessions to it" }),
473
+ ),
474
+ sessions: Type.Array(Type.Object(SESSION_FIELDS), { minItems: 1, description: "Sessions of this tab, one pane each" }),
475
+ }),
476
+ { minItems: 1 },
477
+ ),
478
+ }),
479
+ async execute(_toolCallId, params, signal, _onUpdate, ctx) {
480
+ const { text, tabs } = await openSessions(pi.exec.bind(pi), params, ctx.cwd, { signal });
481
+
482
+ return { content: [{ type: "text", text }], details: { tabs } };
483
+ },
484
+ });
485
+
235
486
  pi.registerCommand("open-session", {
236
487
  description: `Open a new pi session in Ghostty: /open-session <${SURFACES.join("|")}> [prompt]`,
237
488
  getArgumentCompletions: (prefix) => {
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
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",
3
+ "version": "0.2.0",
4
+ "description": "Pi extension that opens new pi sessions in Ghostty on macOS, one in a split, tab, or window, or several grouped in titled tabs, started in the folder and with the prompt you choose",
5
5
  "keywords": [
6
6
  "pi-package",
7
7
  "pi-extension",