@tian.zuo/pi-rex 0.3.0 → 0.5.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.
@@ -0,0 +1,447 @@
1
+ // Move the running pi agent into a git worktree.
2
+ //
3
+ // The agent calls one tool, `rex_worktree_move`, after it creates a worktree.
4
+ // The tool opens a Rex session for the worktree and moves this Rex pane into it.
5
+ // Pi keeps running during the move, so the conversation stays.
6
+ //
7
+ // The move alone does not change the folder pi works in. Only a command
8
+ // context can replace the pi session, so the tool also starts an internal
9
+ // command. The command waits until the turn ends, copies the conversation into
10
+ // a session for the worktree, and switches to it. Pi then builds its tools,
11
+ // system prompt, and context files for the worktree.
12
+
13
+ import { realpathSync, statSync } from "node:fs";
14
+ import os from "node:os";
15
+ import path from "node:path";
16
+ import {
17
+ SessionManager,
18
+ type ExtensionAPI,
19
+ type ExtensionCommandContext,
20
+ } from "@earendil-works/pi-coding-agent";
21
+ import { Type } from "typebox";
22
+ import type { Exec, ExecResult } from "./naming.ts";
23
+ import { REX_TIMEOUT_MS } from "./naming.ts";
24
+ import {
25
+ continuePrompt,
26
+ moveResult,
27
+ WORKTREE_MOVE_DESCRIPTION,
28
+ WORKTREE_MOVE_GUIDELINES,
29
+ PANE_LABEL_DESCRIPTION,
30
+ WORKTREE_PATH_DESCRIPTION,
31
+ } from "./prompt.ts";
32
+ import { parseLocation, parseWindowLayout, type RexWindowLayout } from "./rex-output.ts";
33
+ import { sessionLabel } from "./session-name.ts";
34
+
35
+ /** Name of the tool the agent calls. */
36
+ export const WORKTREE_MOVE_TOOL = "rex_worktree_move";
37
+
38
+ /** Internal command that switches the pi session. The tool starts it. */
39
+ export const SWITCH_COMMAND = "rex-worktree-switch";
40
+
41
+ export interface MoveInput {
42
+ /** Absolute path of the worktree. */
43
+ readonly target: string;
44
+ readonly exec: Exec;
45
+ /** Pane label from the agent: the feature name. */
46
+ readonly label?: string;
47
+ }
48
+
49
+ /** Longest pane label. Rex shows the label in the pane title. */
50
+ export const MAX_PANE_LABEL = 40;
51
+
52
+ /** Clean a pane label to one short line. Undefined when nothing is left. */
53
+ export function cleanPaneLabel(raw: string | undefined): string | undefined {
54
+ const label = (raw ?? "").replace(/\s+/g, " ").trim().slice(0, MAX_PANE_LABEL).trim();
55
+ return label.length > 0 ? label : undefined;
56
+ }
57
+
58
+ /**
59
+ * Pane label: the feature name from the agent, else the worktree branch, else
60
+ * the folder name. A feature branch usually has the feature name.
61
+ */
62
+ export async function paneLabel(exec: Exec, target: string, label?: string): Promise<string> {
63
+ const given = cleanPaneLabel(label);
64
+ if (given) return given;
65
+ try {
66
+ const branch = await exec("git", ["branch", "--show-current"], {
67
+ cwd: target,
68
+ timeout: REX_TIMEOUT_MS,
69
+ });
70
+ const name = branch.code === 0 ? cleanPaneLabel(branch.stdout) : undefined;
71
+ if (name) return name;
72
+ } catch {
73
+ // Use the folder name.
74
+ }
75
+ return cleanPaneLabel(path.basename(target)) ?? "pi";
76
+ }
77
+
78
+ export interface MoveOutput {
79
+ readonly sessionId: string;
80
+ readonly sessionLabel: string;
81
+ /** New label of the moved pane, when Rex accepted the rename. */
82
+ readonly paneLabel?: string;
83
+ /** Labels of the Rex apps that now show the moved pane. */
84
+ readonly followed: readonly string[];
85
+ /** One message for each Rex app that refused to show the moved pane. */
86
+ readonly refused: readonly string[];
87
+ }
88
+
89
+ export interface RexApp {
90
+ readonly id: string;
91
+ readonly label: string;
92
+ }
93
+
94
+ /** Read the Rex apps from `rex client ls --json` output. CLI clients are not apps. */
95
+ export function parseApps(json: string): RexApp[] {
96
+ let value: unknown;
97
+ try {
98
+ value = JSON.parse(json) as unknown;
99
+ } catch {
100
+ return [];
101
+ }
102
+ const clients = (value as { clients?: unknown } | null)?.clients;
103
+ if (!Array.isArray(clients)) return [];
104
+ const apps: RexApp[] = [];
105
+ for (const client of clients) {
106
+ if (typeof client !== "object" || client === null) continue;
107
+ const record = client as { client_id?: unknown; info?: { kind?: unknown; label?: unknown } };
108
+ if (typeof record.client_id !== "string" || record.info?.kind !== "app") continue;
109
+ const label = typeof record.info.label === "string" ? record.info.label : record.client_id;
110
+ apps.push({ id: record.client_id, label });
111
+ }
112
+ return apps;
113
+ }
114
+
115
+ /** Read `.session_id` and the first window from `rex new --json` output. */
116
+ export function parseNewSession(
117
+ json: string,
118
+ ): { sessionId: string; windowId?: string } | undefined {
119
+ let value: unknown;
120
+ try {
121
+ value = JSON.parse(json) as unknown;
122
+ } catch {
123
+ return undefined;
124
+ }
125
+ if (typeof value !== "object" || value === null) return undefined;
126
+ const record = value as { session_id?: unknown; initial_windows?: unknown };
127
+ if (typeof record.session_id !== "string" || record.session_id.length === 0) return undefined;
128
+ const first = Array.isArray(record.initial_windows) ? record.initial_windows[0] : undefined;
129
+ const windowId =
130
+ typeof first === "object" && first !== null
131
+ ? (first as { window_id?: unknown }).window_id
132
+ : undefined;
133
+ return {
134
+ sessionId: record.session_id,
135
+ ...(typeof windowId === "string" && windowId.length > 0 ? { windowId } : {}),
136
+ };
137
+ }
138
+
139
+ /** True when `rex session inspect --json` output shows a session without tabs. */
140
+ export function isEmptySession(json: string): boolean {
141
+ try {
142
+ // Rex leaves out `windows` for a session without tabs.
143
+ const value = JSON.parse(json) as { session_id?: unknown; windows?: unknown } | null;
144
+ if (typeof value?.session_id !== "string") return false;
145
+ const windows = value.windows;
146
+ return windows == null || (Array.isArray(windows) && windows.length === 0);
147
+ } catch {
148
+ return false;
149
+ }
150
+ }
151
+
152
+ /** Expand a leading `~` to the home folder, as a shell does. */
153
+ export function expandHome(input: string, home: string = os.homedir()): string {
154
+ if (input === "~") return home;
155
+ if (input.startsWith("~/") || input.startsWith("~\\")) return path.join(home, input.slice(2));
156
+ return input;
157
+ }
158
+
159
+ /** Resolve the tool argument to an existing folder. Throws a message for the model. */
160
+ export function resolveTarget(input: string, cwd: string): string {
161
+ const absolute = path.resolve(cwd, expandHome(input.trim()));
162
+ let real: string;
163
+ try {
164
+ real = realpathSync(absolute);
165
+ } catch {
166
+ throw new Error(`The folder ${absolute} does not exist. Create the worktree first.`);
167
+ }
168
+ if (!statSync(real).isDirectory()) throw new Error(`${absolute} is not a folder.`);
169
+ let current = cwd;
170
+ try {
171
+ current = realpathSync(cwd);
172
+ } catch {
173
+ // Compare the path as given when the current folder is gone.
174
+ }
175
+ if (real === current) throw new Error(`Pi already works in ${real}.`);
176
+ return real;
177
+ }
178
+
179
+ /**
180
+ * Open a Rex session for the worktree and move this pane into it.
181
+ *
182
+ * Rex moves only whole tabs to another session. When the tab of this pane has
183
+ * other panes, the pane first goes to a new tab of its own in the old session.
184
+ * The other panes stay where they are. The new session starts with a shell
185
+ * tab, which the move makes extra, so close it. A session that the move leaves
186
+ * without tabs is removed too.
187
+ *
188
+ * A Rex app keeps the session that it shows, so after the move it shows the
189
+ * old session. Each app that had the old session open goes to the moved pane.
190
+ * An app accepts this only when its Remote Control setting is on.
191
+ */
192
+ export async function movePane(input: MoveInput): Promise<MoveOutput> {
193
+ const { target, exec } = input;
194
+ const rex = (args: string[]) => exec("rex", args, { cwd: target, timeout: REX_TIMEOUT_MS });
195
+
196
+ const here = parseLocation((await rex(["whoami", "--json"])).stdout);
197
+ if (!here) throw new Error("Rex does not answer, or it cannot find this pane.");
198
+
199
+ // Read the apps and the layout before the move: a removed old session has
200
+ // no apps.
201
+ let layout: RexWindowLayout | undefined;
202
+ let apps: RexApp[] = [];
203
+ if (here.sessionId) {
204
+ apps = parseApps((await rex(["client", "ls", "-s", here.sessionId, "--json"])).stdout);
205
+ const state = await rex(["session", "inspect", here.sessionId, "--json"]);
206
+ if (state.code === 0) layout = parseWindowLayout(state.stdout, here.windowId);
207
+ }
208
+
209
+ const label = await sessionLabel(exec, target, REX_TIMEOUT_MS);
210
+ const created = await rex(["new", label, "--cwd", target, "--json"]);
211
+ const session = created.code === 0 ? parseNewSession(created.stdout) : undefined;
212
+ if (!session) throw new Error(`rex new failed (exit ${created.code}).`);
213
+
214
+ let windowId = here.windowId;
215
+ if (here.sessionId && here.blockId && layout && layout.blocks.length > 1) {
216
+ try {
217
+ windowId = await detachPane(rex, here.sessionId, here.blockId, layout.label);
218
+ } catch (error) {
219
+ // Do not leave an empty session behind.
220
+ await rex(["kill", session.sessionId]);
221
+ throw error;
222
+ }
223
+ }
224
+
225
+ const moved = await rex(["window", "move", windowId, "--to", session.sessionId, "--focus"]);
226
+ if (moved.code !== 0) {
227
+ await rex(["kill", session.sessionId]);
228
+ throw new Error(`rex window move failed (exit ${moved.code}).`);
229
+ }
230
+ if (session.windowId) await rex(["window", "close", "-s", session.sessionId, session.windowId]);
231
+
232
+ // Name the pane after the feature. A failed rename does not stop the move.
233
+ let renamed: string | undefined;
234
+ if (here.blockId) {
235
+ const name = await paneLabel(exec, target, input.label);
236
+ const result = await rex(["block", "rename", "-s", session.sessionId, here.blockId, name]);
237
+ if (result.code === 0) renamed = name;
238
+ }
239
+
240
+ if (here.sessionId) {
241
+ const old = await rex(["session", "inspect", here.sessionId, "--json"]);
242
+ if (old.code === 0 && isEmptySession(old.stdout)) await rex(["kill", here.sessionId]);
243
+ }
244
+
245
+ const followed: string[] = [];
246
+ const refused: string[] = [];
247
+ for (const app of apps) {
248
+ const select = await rex([
249
+ "-C",
250
+ app.id,
251
+ "do",
252
+ "session.select",
253
+ `session_id=${session.sessionId}`,
254
+ `window_id=${windowId}`,
255
+ ]);
256
+ if (select.code === 0) {
257
+ followed.push(app.label);
258
+ } else {
259
+ const reason =
260
+ (select.stderr ?? "")
261
+ .trim()
262
+ .replace(/^Error:\s*/, "")
263
+ .replace(/[.\s]+$/, "") || `exit ${select.code}`;
264
+ refused.push(`${app.label}: ${reason}`);
265
+ }
266
+ }
267
+ return {
268
+ sessionId: session.sessionId,
269
+ sessionLabel: label,
270
+ ...(renamed ? { paneLabel: renamed } : {}),
271
+ followed,
272
+ refused,
273
+ };
274
+ }
275
+
276
+ /**
277
+ * Give a pane a tab of its own in its session, and return the new tab. The
278
+ * new tab starts with a shell pane. The pane goes next to that shell pane,
279
+ * then the shell pane closes. The new tab keeps the label of the old tab.
280
+ */
281
+ async function detachPane(
282
+ rex: (args: string[]) => Promise<ExecResult>,
283
+ sessionId: string,
284
+ blockId: string,
285
+ label: string | undefined,
286
+ ): Promise<string> {
287
+ const opened = await rex([
288
+ "window",
289
+ "new",
290
+ "-s",
291
+ sessionId,
292
+ ...(label ? [label] : []),
293
+ "--focus=false",
294
+ "--json",
295
+ ]);
296
+ const tab = opened.code === 0 ? parseNewWindow(opened.stdout) : undefined;
297
+ if (!tab) throw new Error(`rex window new failed (exit ${opened.code}).`);
298
+ const moved = await rex(["move", "-s", sessionId, blockId, "right", tab.blockId]);
299
+ if (moved.code !== 0) {
300
+ await rex(["window", "close", "-s", sessionId, tab.windowId]);
301
+ throw new Error(`rex move failed (exit ${moved.code}).`);
302
+ }
303
+ await rex(["block", "close", "-s", sessionId, tab.blockId]);
304
+ return tab.windowId;
305
+ }
306
+
307
+ /** Read `.window_id` and the first block from `rex window new --json` output. */
308
+ export function parseNewWindow(json: string): { windowId: string; blockId: string } | undefined {
309
+ let value: unknown;
310
+ try {
311
+ value = JSON.parse(json) as unknown;
312
+ } catch {
313
+ return undefined;
314
+ }
315
+ const record = value as { window_id?: unknown; block_ids?: unknown } | null;
316
+ const blockId = Array.isArray(record?.block_ids) ? record.block_ids[0] : undefined;
317
+ if (typeof record?.window_id !== "string" || typeof blockId !== "string") return undefined;
318
+ return { windowId: record.window_id, blockId };
319
+ }
320
+
321
+ /** Copy the conversation into a session for the worktree, then switch to it. */
322
+ export async function switchToWorktree(
323
+ ctx: ExtensionCommandContext,
324
+ target: string,
325
+ sessionName: string,
326
+ ): Promise<void> {
327
+ await ctx.waitForIdle();
328
+ const file = ctx.sessionManager.getSessionFile();
329
+ if (!file) {
330
+ ctx.ui.notify("pi-rex: this pi session has no file, so it cannot move.", "error");
331
+ return;
332
+ }
333
+ const next = SessionManager.forkFrom(file, target).getSessionFile();
334
+ if (!next) {
335
+ ctx.ui.notify("pi-rex: pi did not write the worktree session.", "error");
336
+ return;
337
+ }
338
+ const prompt = continuePrompt(target, sessionName);
339
+ // Pi builds the new runtime from the session cwd, but it does not change the
340
+ // folder of the process. An extension that reads process.cwd() would stay in
341
+ // the old folder. Change it before the switch, so the new extension
342
+ // instances see the worktree at session start.
343
+ const previous = enterFolder(target);
344
+ let cancelled = true;
345
+ try {
346
+ cancelled = (
347
+ await ctx.switchSession(next, {
348
+ withSession: async (replaced) => {
349
+ await replaced.sendUserMessage(prompt);
350
+ },
351
+ })
352
+ ).cancelled;
353
+ } finally {
354
+ // An extension can cancel the switch. Pi then stays in the old session.
355
+ if (cancelled && previous !== undefined) {
356
+ try {
357
+ enterFolder(previous);
358
+ } catch {
359
+ // The old folder is gone. Stay in the worktree.
360
+ }
361
+ }
362
+ }
363
+ }
364
+
365
+ /**
366
+ * Change the folder of the process and `PWD`, as `cd` does. Returns the old
367
+ * folder, or undefined when the old folder is gone.
368
+ */
369
+ export function enterFolder(folder: string): string | undefined {
370
+ let previous: string | undefined;
371
+ try {
372
+ previous = process.cwd();
373
+ } catch {
374
+ previous = undefined;
375
+ }
376
+ process.chdir(folder);
377
+ process.env.PWD = folder;
378
+ return previous;
379
+ }
380
+
381
+ export function registerWorktreeMove(pi: ExtensionAPI): void {
382
+ // The session label of the last move, for the message after the switch.
383
+ let movedTo = "";
384
+
385
+ pi.registerTool({
386
+ name: WORKTREE_MOVE_TOOL,
387
+ label: "Rex Worktree Move",
388
+ description: WORKTREE_MOVE_DESCRIPTION,
389
+ promptGuidelines: WORKTREE_MOVE_GUIDELINES,
390
+ parameters: Type.Object({
391
+ path: Type.String({ description: WORKTREE_PATH_DESCRIPTION }),
392
+ label: Type.Optional(Type.String({ description: PANE_LABEL_DESCRIPTION })),
393
+ }),
394
+ exposure: "codemode",
395
+ executionMode: "sequential",
396
+ async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
397
+ if (!process.env.REX_BLOCK && !process.env.REX_SESSION) {
398
+ throw new Error("Pi does not run in a Rex terminal.");
399
+ }
400
+ const target = resolveTarget(params.path, ctx.cwd);
401
+ const moved = await movePane({
402
+ target,
403
+ ...(params.label !== undefined ? { label: params.label } : {}),
404
+ exec: async (command, args, options) => {
405
+ const result = await pi.exec(command, args, options);
406
+ return { code: result.code, stdout: result.stdout, stderr: result.stderr };
407
+ },
408
+ });
409
+ // A session ID set at start names the old session. Rex finds the
410
+ // session of REX_BLOCK by itself, so only a set value needs a change.
411
+ if (process.env.REX_SESSION) process.env.REX_SESSION = moved.sessionId;
412
+ movedTo = moved.sessionLabel;
413
+ // Pi runs the command at once, also during a turn. The command waits
414
+ // until this turn ends.
415
+ pi.sendUserMessage(`/${SWITCH_COMMAND} ${target}`, {
416
+ deliverAs: "followUp",
417
+ expandPromptTemplates: true,
418
+ });
419
+ return {
420
+ content: [{ type: "text", text: moveResult(target, moved, ctx.cwd) }],
421
+ details: undefined,
422
+ terminate: true,
423
+ };
424
+ },
425
+ });
426
+
427
+ pi.registerCommand(SWITCH_COMMAND, {
428
+ description: "Switch pi to a worktree (rex_worktree_move runs this)",
429
+ handler: async (args, ctx) => {
430
+ const input = args.trim();
431
+ if (!input) {
432
+ ctx.ui.notify(`Usage: /${SWITCH_COMMAND} <worktree path>`, "warning");
433
+ return;
434
+ }
435
+ let target: string;
436
+ try {
437
+ target = resolveTarget(input, ctx.cwd);
438
+ } catch (error) {
439
+ ctx.ui.notify(`pi-rex: ${error instanceof Error ? error.message : String(error)}`, "error");
440
+ return;
441
+ }
442
+ const name = movedTo || path.basename(target);
443
+ movedTo = "";
444
+ await switchToWorktree(ctx, target, name);
445
+ },
446
+ });
447
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@tian.zuo/pi-rex",
3
- "version": "0.3.0",
4
- "description": "Tells the pi coding agent that it runs in a Rex terminal, names the Rex session after the project folder or worktree, names the tab from the first prompt, and resumes pi after a Rex restart.",
3
+ "version": "0.5.0",
4
+ "description": "Tells the pi coding agent that it runs in a Rex terminal, reports prompt activity to Rex, names the Rex session and tab, and moves the agent into a git worktree with one tool.",
5
5
  "type": "module",
6
6
  "keywords": [
7
7
  "pi",
@@ -32,7 +32,8 @@
32
32
  ]
33
33
  },
34
34
  "peerDependencies": {
35
- "@earendil-works/pi-coding-agent": "*"
35
+ "@earendil-works/pi-coding-agent": "*",
36
+ "typebox": "*"
36
37
  },
37
38
  "devDependencies": {
38
39
  "@effect/language-service": "^0.87.5",
package/lib/resume.ts DELETED
@@ -1,90 +0,0 @@
1
- // Resume pi in its Rex pane after a Rex restart.
2
- //
3
- // Rex restores sessions, tabs, panes, and scrollback after a restart. Each
4
- // pane keeps its block ID, but Rex starts a new shell in it, not the program
5
- // that ran there. This module records the pi session of the pane in
6
- // `<agent dir>/rex-resume/<block id>`. A shell hook (see the README) reads the
7
- // record when a new shell starts in the pane and runs the command.
8
- //
9
- // The record is the working directory on line 1, then the command, one
10
- // argument per line. It stays when pi stops because of SIGHUP or SIGTERM, or
11
- // because the terminal is gone, which is what a Rex restart does. It is removed
12
- // when the user quits pi, and when `/new` replaces the session.
13
-
14
- import { existsSync, mkdirSync, renameSync, rmSync, writeFileSync } from "node:fs";
15
- import path from "node:path";
16
- import {
17
- getAgentDir,
18
- type ExtensionAPI,
19
- type ExtensionContext,
20
- } from "@earendil-works/pi-coding-agent";
21
-
22
- /** Folder below the pi agent directory that holds one record per Rex pane. */
23
- export const RESUME_DIR = "rex-resume";
24
-
25
- const SIGNALS = ["SIGHUP", "SIGTERM"] as const;
26
- /** A block ID becomes a file name, so accept a plain ID and not a path. */
27
- const BLOCK_ID = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
28
-
29
- /** Record file for a Rex block, such as `block:01a1...`. Undefined for a malformed ID. */
30
- export function recordPath(agentDir: string, block: string): string | undefined {
31
- const id = block.replace(/^block:/, "");
32
- if (!BLOCK_ID.test(id)) return undefined;
33
- return path.join(agentDir, RESUME_DIR, id);
34
- }
35
-
36
- /** Record text: the working directory, then the resume command, one argument per line. */
37
- export function recordText(cwd: string, sessionFile: string): string {
38
- return `${[cwd, "pi", "--session", sessionFile].join("\n")}\n`;
39
- }
40
-
41
- export function registerResume(pi: ExtensionAPI, agentDir: string = getAgentDir()): void {
42
- let record: string | undefined;
43
- let signaled = false;
44
- const onSignal = (): void => {
45
- signaled = true;
46
- };
47
-
48
- // Pi writes the session file only after the first message, so save again
49
- // after each prompt. Until then, remove the record: after `/new` it still
50
- // names the previous session, which the hook must not reopen.
51
- const save = (ctx: ExtensionContext): void => {
52
- if (!record) return;
53
- const session = ctx.sessionManager.getSessionFile();
54
- // The hook runs the last lines as one command. A line break in a path
55
- // would move the arguments, so write no record for such a path.
56
- if (!session || !existsSync(session) || /[\r\n]/.test(ctx.cwd) || /[\r\n]/.test(session)) {
57
- rmSync(record, { force: true });
58
- return;
59
- }
60
- mkdirSync(path.dirname(record), { recursive: true });
61
- // Write and rename, so a stop during the write cannot leave half a record.
62
- const temp = `${record}.tmp`;
63
- writeFileSync(temp, recordText(ctx.cwd, session));
64
- renameSync(temp, record);
65
- };
66
-
67
- pi.on("session_start", (_event, ctx) => {
68
- const block = process.env.REX_BLOCK;
69
- // Print, JSON, and RPC runs inherit REX_BLOCK from the agent's shell, but
70
- // they are not the agent of the pane. `hasUI` is also true in RPC mode.
71
- record = block && ctx.mode === "tui" ? recordPath(agentDir, block) : undefined;
72
- if (!record) return;
73
- signaled = false;
74
- for (const signal of SIGNALS) process.on(signal, onSignal);
75
- save(ctx);
76
- });
77
-
78
- pi.on("agent_end", (_event, ctx) => save(ctx));
79
-
80
- pi.on("session_shutdown", async (event) => {
81
- if (!record) return;
82
- // Pi's own signal handler runs first and starts the shutdown. Wait one tick
83
- // so onSignal, a later listener for the same signal, can set the flag.
84
- await new Promise((resolve) => setImmediate(resolve));
85
- for (const signal of SIGNALS) process.off(signal, onSignal);
86
- // `/new` replaces the session, so the record must not reopen the old one.
87
- if (event.reason === "new" || (event.reason === "quit" && !signaled))
88
- rmSync(record, { force: true });
89
- });
90
- }