@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.
package/lib/cleanup.ts ADDED
@@ -0,0 +1,104 @@
1
+ // Remove the resume hook that pi-rex 0.4 installed.
2
+ //
3
+ // Rex now starts pi again in a restored pane by itself. The old hook and its
4
+ // records would start pi a second time, or open an old session, so the
5
+ // extension removes them. It removes only text that it wrote:
6
+ //
7
+ // - fish: the `conf.d/rex-resume.fish` file, when it starts with HOOK_MARKER.
8
+ // - zsh, bash, and PowerShell: the block between BLOCK_START and BLOCK_END.
9
+ // - the records in `<agent dir>/rex-resume`.
10
+
11
+ import { existsSync, readFileSync, rmSync, writeFileSync } from "node:fs";
12
+ import os from "node:os";
13
+ import path from "node:path";
14
+
15
+ /** First line of the fish hook file that pi-rex 0.4 wrote. */
16
+ export const HOOK_MARKER = "# Generated by @tian.zuo/pi-rex.";
17
+
18
+ /** Start of the block that pi-rex 0.4 added to a shell startup file. */
19
+ export const BLOCK_START = "# >>> tian.zuo/pi-rex >>>";
20
+
21
+ /** End of the block that pi-rex 0.4 added to a shell startup file. */
22
+ export const BLOCK_END = "# <<< tian.zuo/pi-rex <<<";
23
+
24
+ /** Folder below the pi agent directory that held one record per Rex pane. */
25
+ export const RESUME_DIR = "rex-resume";
26
+
27
+ export interface CleanupContext {
28
+ readonly agentDir: string;
29
+ readonly env?: NodeJS.ProcessEnv;
30
+ readonly home?: string;
31
+ }
32
+
33
+ /** Remove the marked block, and the blank line that was added before it. */
34
+ export function removeBlock(text: string): string {
35
+ const start = text.indexOf(BLOCK_START);
36
+ const end = text.indexOf(BLOCK_END);
37
+ if (start === -1 || end < start) return text;
38
+ let before = text.slice(0, start);
39
+ let after = text.slice(end + BLOCK_END.length);
40
+ if (after.startsWith("\r\n")) after = after.slice(2);
41
+ else if (after.startsWith("\n")) after = after.slice(1);
42
+ if (before.endsWith("\n\n")) before = before.slice(0, -1);
43
+ return before + after;
44
+ }
45
+
46
+ /** Every file where pi-rex 0.4 could write a block. */
47
+ export function blockFiles(env: NodeJS.ProcessEnv, home: string): string[] {
48
+ const configHome = env.XDG_CONFIG_HOME?.trim() || path.join(home, ".config");
49
+ return [
50
+ path.join(env.ZDOTDIR?.trim() || home, ".zshrc"),
51
+ path.join(home, ".bash_profile"),
52
+ path.join(home, ".bash_login"),
53
+ path.join(home, ".profile"),
54
+ path.join(configHome, "powershell", "profile.ps1"),
55
+ path.join(home, "Documents", "PowerShell", "profile.ps1"),
56
+ path.join(home, "Documents", "WindowsPowerShell", "profile.ps1"),
57
+ ];
58
+ }
59
+
60
+ /** The fish file that pi-rex 0.4 wrote. */
61
+ export function fishFile(env: NodeJS.ProcessEnv, home: string): string {
62
+ const configHome = env.XDG_CONFIG_HOME?.trim() || path.join(home, ".config");
63
+ return path.join(configHome, "fish", "conf.d", "rex-resume.fish");
64
+ }
65
+
66
+ /**
67
+ * Remove the old hook and records. Returns the hook files that changed. A
68
+ * file that cannot be read or written stays as it is.
69
+ */
70
+ export function removeLegacyResume(context: CleanupContext): string[] {
71
+ const env = context.env ?? process.env;
72
+ const home = context.home ?? os.homedir();
73
+ const changed: string[] = [];
74
+
75
+ const fish = fishFile(env, home);
76
+ try {
77
+ if (existsSync(fish) && readFileSync(fish, "utf8").startsWith(HOOK_MARKER)) {
78
+ rmSync(fish, { force: true });
79
+ changed.push(fish);
80
+ }
81
+ } catch {
82
+ // Keep the file.
83
+ }
84
+
85
+ for (const file of blockFiles(env, home)) {
86
+ try {
87
+ if (!existsSync(file)) continue;
88
+ const current = readFileSync(file, "utf8");
89
+ const next = removeBlock(current);
90
+ if (next === current) continue;
91
+ writeFileSync(file, next);
92
+ changed.push(file);
93
+ } catch {
94
+ // Keep the file.
95
+ }
96
+ }
97
+
98
+ try {
99
+ rmSync(path.join(context.agentDir, RESUME_DIR), { recursive: true, force: true });
100
+ } catch {
101
+ // The records do nothing without the hook.
102
+ }
103
+ return changed;
104
+ }
package/lib/naming.ts CHANGED
@@ -6,7 +6,7 @@
6
6
  // generated name in place and does not block the main agent run.
7
7
 
8
8
  import { namingPrompt } from "./prompt.ts";
9
- import { parseInspect, parseWhoami, type RexInspect, type RexWindow } from "./rex-output.ts";
9
+ import { parseInspect, parseLocation, type RexInspect, type RexWindow } from "./rex-output.ts";
10
10
  import { sessionLabel } from "./session-name.ts";
11
11
 
12
12
  /** Upper bound for the task text sent to the naming model. */
@@ -27,6 +27,7 @@ const WINDOW_LABEL = /^Window [0-9a-f]{4,}$/;
27
27
  export interface ExecResult {
28
28
  readonly code: number;
29
29
  readonly stdout: string;
30
+ readonly stderr?: string;
30
31
  }
31
32
 
32
33
  export type Exec = (
@@ -77,7 +78,7 @@ export function parseLabel(raw: string): string | undefined {
77
78
 
78
79
  /** Rename the current tab, and the session when this tab is the first one. */
79
80
  export async function nameSession(input: NameSessionInput): Promise<void> {
80
- const { session, cwd, exec } = input;
81
+ const { cwd, exec } = input;
81
82
  const options = { cwd, timeout: REX_TIMEOUT_MS };
82
83
  const rex = (args: string[]) => exec("rex", args, options);
83
84
 
@@ -86,8 +87,14 @@ export async function nameSession(input: NameSessionInput): Promise<void> {
86
87
 
87
88
  // Probe Rex before the model call, so a dead server costs no tokens. The
88
89
  // window ID does not change while the tab lives.
89
- const whoami = parseWhoami((await rex(["whoami", "--json"])).stdout);
90
- if (!whoami) return;
90
+ const here = parseLocation((await rex(["whoami", "--json"])).stdout);
91
+ if (!here) return;
92
+ const whoami = here.windowId;
93
+ // Pin the renames to the session of this moment. A block ID follows the tab,
94
+ // so after `rex_worktree_move` it would name the worktree session, and the
95
+ // old folder label would replace the worktree label. In the old session the
96
+ // tab is gone, so the lookup below stops the renames.
97
+ const session = here.sessionId ?? input.session;
91
98
 
92
99
  // The session label comes from the folder and the worktree, not the model.
93
100
  // A model failure then still renames the session.
package/lib/prompt.ts CHANGED
@@ -10,6 +10,55 @@ export const REX_SECTION = "rex";
10
10
  */
11
11
  export const AUTO_NAME_INSTRUCTION = `The session and tab names are set automatically. Do not run \`rex session rename\` or \`rex window rename\` unless the user asks.`;
12
12
 
13
+ /** Description of the `rex_worktree_move` tool. */
14
+ export const WORKTREE_MOVE_DESCRIPTION = `Move this pi agent into a git worktree, with the conversation. The tool opens a Rex session for the worktree, moves this Rex pane into it (other panes of the tab stay), and switches pi to the worktree when the current turn ends. After the switch, the tools, the system prompt, and the context files are for the worktree.`;
15
+
16
+ /** Rules for the `rex_worktree_move` tool. */
17
+ export const WORKTREE_MOVE_GUIDELINES = [
18
+ "Call rex_worktree_move immediately after you create a git worktree for a task, instead of `rex new` and `rex window move`. Set `label` to the short feature name.",
19
+ "After rex_worktree_move succeeds, end your turn with one short status line. Do not run more commands in the old folder. The next turn starts in the worktree.",
20
+ ];
21
+
22
+ /** Description of the `path` parameter. */
23
+ export const WORKTREE_PATH_DESCRIPTION =
24
+ "Path of the worktree folder. A leading ~ is the home folder. The folder must exist.";
25
+
26
+ /** Description of the `label` parameter. */
27
+ export const PANE_LABEL_DESCRIPTION =
28
+ "Short name of the feature that you work on in the worktree, such as pin-theme. The tool gives this name to the moved Rex pane. Without it, the pane gets the name of the worktree branch.";
29
+
30
+ /** Tool result after the pane moved. */
31
+ export function moveResult(
32
+ target: string,
33
+ moved: {
34
+ sessionLabel: string;
35
+ paneLabel?: string;
36
+ followed: readonly string[];
37
+ refused: readonly string[];
38
+ },
39
+ oldCwd: string,
40
+ ): string {
41
+ const lines = [`Moved this pane to the Rex session "${moved.sessionLabel}".`];
42
+ if (moved.paneLabel) lines.push(`Renamed this pane to "${moved.paneLabel}".`);
43
+ if (moved.followed.length > 0) {
44
+ lines.push(`These Rex apps now show the moved pane: ${moved.followed.join(", ")}.`);
45
+ }
46
+ if (moved.refused.length > 0) {
47
+ lines.push(
48
+ `These Rex apps still show the old session: ${moved.refused.join("; ")}. Tell the user to select the session "${moved.sessionLabel}" in Rex. To make Rex follow the pane next time, the user turns on Remote Control in Rex Settings > General.`,
49
+ );
50
+ }
51
+ lines.push(
52
+ `Pi switches to ${target} when this turn ends. End your turn now with one short status line. Do not run more commands in ${oldCwd}.`,
53
+ );
54
+ return lines.join("\n");
55
+ }
56
+
57
+ /** First user message in the worktree session. */
58
+ export function continuePrompt(target: string, session: string): string {
59
+ return `Pi now works in the worktree ${target}, in the Rex session "${session}". Continue the task from where you stopped. Do all work in this worktree.`;
60
+ }
61
+
13
62
  /**
14
63
  * Asks the naming model for one tab label. The task text is the user's first
15
64
  * prompt, trimmed by the caller.
package/lib/rex-output.ts CHANGED
@@ -51,6 +51,52 @@ export function parseInspect(json: string): RexInspect | undefined {
51
51
  return { label: record.label, windows };
52
52
  }
53
53
 
54
+ export interface RexLocation {
55
+ readonly windowId: string;
56
+ readonly sessionId?: string;
57
+ readonly blockId?: string;
58
+ }
59
+
60
+ /** Read `.window_id`, `.session_id`, and `.block_id` from `rex whoami --json` output. */
61
+ export function parseLocation(json: string): RexLocation | undefined {
62
+ const windowId = parseWhoami(json);
63
+ if (!windowId) return undefined;
64
+ const value = parse(json) as { session_id?: unknown; block_id?: unknown };
65
+ const text = (field: unknown): string | undefined =>
66
+ typeof field === "string" && field.length > 0 ? field : undefined;
67
+ const sessionId = text(value.session_id);
68
+ const blockId = text(value.block_id);
69
+ return { windowId, ...(sessionId ? { sessionId } : {}), ...(blockId ? { blockId } : {}) };
70
+ }
71
+
72
+ export interface RexWindowLayout {
73
+ readonly label?: string;
74
+ /** IDs of the panes in the window, from every layer. */
75
+ readonly blocks: readonly string[];
76
+ }
77
+
78
+ /** Read one window and its panes from `rex session inspect --json` output. */
79
+ export function parseWindowLayout(json: string, windowId: string): RexWindowLayout | undefined {
80
+ const value = parse(json) as { windows?: unknown } | undefined;
81
+ if (!Array.isArray(value?.windows)) return undefined;
82
+ const window = value.windows.find(
83
+ (entry: unknown) =>
84
+ typeof entry === "object" &&
85
+ entry !== null &&
86
+ (entry as { window_id?: unknown }).window_id === windowId,
87
+ ) as { label?: unknown; layers?: unknown } | undefined;
88
+ if (!window) return undefined;
89
+ const blocks: string[] = [];
90
+ for (const layer of Array.isArray(window.layers) ? window.layers : []) {
91
+ const entries = (layer as { blocks?: unknown } | null)?.blocks;
92
+ for (const block of Array.isArray(entries) ? entries : []) {
93
+ const id = (block as { block_id?: unknown } | null)?.block_id;
94
+ if (typeof id === "string") blocks.push(id);
95
+ }
96
+ }
97
+ return { ...(typeof window.label === "string" ? { label: window.label } : {}), blocks };
98
+ }
99
+
54
100
  function parse(json: string): unknown {
55
101
  try {
56
102
  return JSON.parse(json) as unknown;
@@ -0,0 +1,17 @@
1
+ // Read the pi settings in the `rex` section.
2
+
3
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
4
+
5
+ /** Names of the on/off switches in the `rex` settings section. */
6
+ export type RexSwitch = "autoName";
7
+
8
+ function rexSettings(pi: ExtensionAPI): Record<string, unknown> | undefined {
9
+ const rex = (pi.getSettings() as { rex?: unknown }).rex;
10
+ if (typeof rex !== "object" || rex === null) return undefined;
11
+ return rex as Record<string, unknown>;
12
+ }
13
+
14
+ /** Only an explicit `false` turns a feature off. */
15
+ export function rexSetting(pi: ExtensionAPI, key: RexSwitch): boolean {
16
+ return rexSettings(pi)?.[key] !== false;
17
+ }