@tian.zuo/pi-rex 0.1.1 → 0.3.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/CHANGELOG.md CHANGED
@@ -1,5 +1,19 @@
1
1
  # @tian.zuo/pi-rex
2
2
 
3
+ ## 0.3.0
4
+
5
+ ### Minor Changes
6
+
7
+ - [#207](https://github.com/TianZuo555/pi-extensions/pull/207) [`9b6cf44`](https://github.com/TianZuo555/pi-extensions/commit/9b6cf44c29505b8c4fad9d874a6120514efd2d1c) Thanks [@TianZuo555](https://github.com/TianZuo555)! - Name the Rex session after the project folder instead of a task label. A linked git worktree uses `Wrktree—<main repository folder>—<branch>`. The tab keeps the model-generated task label, and the session is renamed even when the model call fails.
8
+
9
+ - [#206](https://github.com/TianZuo555/pi-extensions/pull/206) [`d128174`](https://github.com/TianZuo555/pi-extensions/commit/d128174b5f0938e1997e529af7f505b882e33bd8) Thanks [@TianZuo555](https://github.com/TianZuo555)! - Resume pi in its Rex pane after a Rex restart. In TUI mode, the extension records the pi session of each Rex pane in `~/.pi/agent/rex-resume/<block id>`. The record stays when pi stops because of SIGHUP, SIGTERM, or a lost terminal, and for `/reload`, `/resume`, and `/fork`. It is removed when you quit pi and when `/new` replaces the session. A shell hook, shown in the README for fish, reads the record when Rex starts a new shell in the restored pane and runs `pi --session <file>`.
10
+
11
+ ## 0.2.0
12
+
13
+ ### Minor Changes
14
+
15
+ - [#204](https://github.com/TianZuo555/pi-extensions/pull/204) [`c801328`](https://github.com/TianZuo555/pi-extensions/commit/c8013289dc6f333032695a9bd0b6eb1b527e12e1) Thanks [@TianZuo555](https://github.com/TianZuo555)! - Name the Rex session and tab from the first prompt. The extension asks the current session model for one label, then runs `rex session rename` for the first tab and `rex window rename` for the current tab. The model call runs in the background, so the first response is not delayed. A hand-set label is kept. Set `rex.autoName` to `false` to turn automatic naming off. The `rex.renameTab` setting is removed.
16
+
3
17
  ## 0.1.1
4
18
 
5
19
  ### Patch Changes
package/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  Release notes: [changelog](https://github.com/TianZuo555/pi-extensions/blob/main/packages/pi-rex/CHANGELOG.md) · [GitHub releases](https://github.com/TianZuo555/pi-extensions/releases)
4
4
 
5
- The [Rex](https://www.superlogical.com/rex/docs/automate/agent-skill) session-start hook for the [pi coding agent](https://pi.dev).
5
+ The [Rex](https://www.superlogical.com/rex/docs/automate/agent-skill) session-start hook for the [pi coding agent](https://pi.dev). The extension also names the Rex session after the project folder or worktree, names the tab from the first prompt, and records each pane's pi session so pi can resume after a Rex restart.
6
6
 
7
7
  ```bash
8
8
  pi install npm:@tian.zuo/pi-rex
@@ -22,53 +22,104 @@ The extension adds the output to the system prompt as a `<rex>` section. Outside
22
22
 
23
23
  Run `rex skill setup` to install the skill. This extension does not install the skill.
24
24
 
25
- ## Settings
25
+ ## Naming
26
26
 
27
- The extension reads the `rex` section of the pi settings file. Add the section to `~/.pi/agent/settings.json`.
27
+ Rex gives each session and each tab a generated name. The extension names the session after the project folder, and gives each tab a task name from the first prompt. The agent does not run a rename command.
28
28
 
29
- | Key | Type | Default | Description |
30
- | --------------- | ------- | ------- | ---------------------------- |
31
- | `rex.renameTab` | boolean | `false` | Tell pi to name the Rex tab. |
29
+ The session name is the current folder name, as-is. In a linked git worktree, the name is `Wrktree—<main repository folder>—<branch>`, such as `Wrktree—pi-tian-extensions—docs/pi-layerfs-spec`. A detached worktree uses the first seven characters of the commit. The extension finds the worktree with `git worktree list --porcelain`. If git fails or the folder is not a git repository, the folder name is used.
32
30
 
33
- Example:
31
+ On the first user prompt of a pi session, the extension runs `rex whoami --json` as a cheap check that the Rex server answers. If it does, the extension reads the folder and worktree, then makes one model call on the current session model. The call asks for a tab label: 2 to 4 lowercase English words, joined by hyphens. The call runs in the background, so the first response is not delayed. After the model replies, the extension reads the current labels and runs:
34
32
 
35
- ```json
36
- {
37
- "rex": {
38
- "renameTab": true
39
- }
40
- }
33
+ ```bash
34
+ rex session inspect "$REX_SESSION" --json
35
+ rex session rename "$REX_SESSION" SESSION_LABEL # first tab only
36
+ rex window rename -s "$REX_SESSION" WINDOW_ID TAB_LABEL
41
37
  ```
42
38
 
43
- Any value other than `true` keeps tab naming off.
39
+ The session name does not depend on the model. If the model call fails or returns no label, the session is still renamed; only the tab keeps its old name.
44
40
 
45
- ## Naming
41
+ The labels are read after the model call. A rename made while the call runs wins.
46
42
 
47
- Rex gives each session and each tab a generated name. The agent can replace these names with task names.
43
+ Rex orders tabs by ID, which comes from the creation time. The first tab carries the session label. A later tab gets its own label and never renames the parent session.
48
44
 
49
- ### Session naming
45
+ The extension replaces a label only when the label is still generated:
50
46
 
51
- Session naming is on for a session with one tab. Rex supplies the naming instructions in the session-start output. The extension does not run `rex session rename`. No setting controls session naming.
47
+ - A session label is generated when it is two lowercase words, such as `shy-strait`, or a worktree label from this extension that starts with `Wrktree—`.
48
+ - A tab label is generated when it is `Window <id>`, such as `Window 629d2113`.
52
49
 
53
- When the session has more than one tab, the extension removes the session-naming paragraph. It adds a second instruction instead: keep the session label and do not rename the session. A session is the parent of its tabs, so a tab must not rename the parent.
50
+ A hand-set label is kept. A one-word folder label, such as `repo`, is not recognized as generated, so a later pi session in the same tab keeps it. Naming runs once per pi session. If a Rex command fails, the old name stays and the agent continues.
54
51
 
55
- The extension counts the tabs with `rex session inspect "$REX_SESSION" --json`. If that command fails, the Rex text stays unchanged.
52
+ Because the extension names the session, it removes the Rex naming paragraph from the `<rex>` section. It adds one line instead: the names are automatic, and the agent must not rename them unless the user asks. This also overrides the `rex` skill rule that says to rename only when the user asks.
56
53
 
57
- ### Tab naming
54
+ ## Resume after a Rex restart
58
55
 
59
- Set `rex.renameTab` to `true` to let pi name the tab. The extension then adds tab instructions to the `<rex>` section. The instructions tell pi to run:
56
+ Rex restores sessions, tabs, panes, and scrollback after a restart. Each pane keeps its block ID, but Rex starts a new shell in the pane, not pi. The extension records the pi session of each pane, so a shell hook can start pi again.
60
57
 
61
- ```bash
62
- rex window rename -s "$REX_SESSION" WINDOW_ID LABEL
58
+ When `REX_BLOCK` is set in TUI mode, the extension writes `~/.pi/agent/rex-resume/<block id>` (below `PI_CODING_AGENT_DIR` when it is set). It writes the record when a session starts and after each prompt, because pi creates the session file only after the first message. The record holds the working directory on line 1, then the command, one argument per line:
59
+
60
+ ```text
61
+ /Users/you/src/app
62
+ pi
63
+ --session
64
+ /Users/you/.pi/agent/sessions/--Users-you-src-app--/2026-11-05T05-52-27-656Z_01a1....jsonl
65
+ ```
66
+
67
+ The record stays when pi stops because of SIGHUP or SIGTERM, or because the terminal is gone. A Rex restart does one of these. The record stays for `/reload`, `/resume`, and `/fork`, and the next session writes its own record. `/new` removes the record until the new session has a file, so a restart right after `/new` does not reopen the previous session. The record is removed when you quit pi (Ctrl+D, Ctrl+C twice, `/quit`). Print, JSON, and RPC runs write no record.
68
+
69
+ The extension cannot start a program in a Rex pane, so the shell must read the record. Add this hook to `~/.config/fish/config.fish` (or a file in `conf.d/`):
70
+
71
+ ```fish
72
+ if status is-interactive; and set -q REX_BLOCK
73
+ function __rex_resume --on-event fish_prompt
74
+ functions -e __rex_resume
75
+ set -l agent_dir $HOME/.pi/agent
76
+ # Expand ~ as pi does: fish does not expand it inside a variable.
77
+ set -q PI_CODING_AGENT_DIR; and set agent_dir (string replace -r -- '^~(?=/|$)' $HOME $PI_CODING_AGENT_DIR)
78
+ set -l file $agent_dir/rex-resume/(string replace -- 'block:' '' $REX_BLOCK)
79
+ test -f $file; or return
80
+ set -l record (cat $file)
81
+ test -n "$record[1]"; or return
82
+ cd -- $record[1]; or return
83
+ rm -f $file
84
+ $record[2..]
85
+ end
86
+ end
87
+ ```
88
+
89
+ The hook runs once, before the first prompt, after the rest of the config is loaded. A new pane has a new block ID, so it has no record. Only a pane that Rex restored while pi ran in it has one. The hook removes the record before it starts pi, and pi writes a new one. The hook always runs `pi --session <file>`: it does not restore the flags of the first launch, so a pane that ran `pi -e ./packages/pi-rex` resumes with plain `pi`.
90
+
91
+ ## Settings
92
+
93
+ The extension reads the `rex` section of the pi settings file. Add the section to `~/.pi/agent/settings.json`.
94
+
95
+ | Key | Type | Default | Description |
96
+ | -------------- | ------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
97
+ | `rex.autoName` | boolean | `true` | Name the Rex session after the folder or worktree, and the tab from the first prompt. `false` keeps the Rex names and the Rex naming text. |
98
+
99
+ Example:
100
+
101
+ ```json
102
+ {
103
+ "rex": {
104
+ "autoName": false
105
+ }
106
+ }
63
107
  ```
64
108
 
65
- A session is the parent. A tab is the child. pi names the session first. Then pi reads its window ID with `rex whoami --json`. It compares that ID with the window IDs of the session from `rex window ls`. The first tab takes the session label. A later tab gets its own label. pi keeps a label that already fits the work. If the rename fails, pi continues the task and does not show a message.
109
+ Any value other than `false` keeps automatic naming on.
66
110
 
67
111
  ## Known limits
68
112
 
69
- - The Rex CLI does not report whether a label is generated or set by hand. The extension decides from the tab count only. A session with one tab and a hand-set label can still lose that label.
70
- - The session rule reads one string from the Rex output: the paragraph that holds `rex session rename`. A change to that wording stops the removal.
71
- - The two instructions are prompt text. An agent can ignore them. The extension never runs a rename command itself.
113
+ - The extension decides "generated" from the shape of the label. A hand-set two-word session label, such as `fix-login`, is replaced.
114
+ - A one-word folder label is not recognized as generated. If you start a new pi session in another folder in the same Rex tab, the session keeps the old folder name.
115
+ - The model reply must be one tab label. A prose reply leaves the old tab name in place; the session is still renamed.
116
+ - The naming call uses the current session model. A reasoning model can spend part of the token budget before it writes the label.
117
+ - The `<rex>` removal reads one string from the Rex output: the paragraph that holds `rex session rename`. A change to that wording stops the removal.
118
+ - Resume needs the shell hook. Without it, the records do nothing.
119
+ - The hook starts `pi --session <file>`, so it does not restore the flags of the first launch. A pane that ran `pi -e ./packages/pi-rex` resumes without the local extension.
120
+ - A second interactive fish in the same pane, started while pi runs, also reads the record. It can start a second pi on the same session and remove the record; the next prompt in the first pi writes the record again.
121
+ - When you close a pane while pi runs in it, pi gets SIGHUP and its record stays. The file is small, and Rex never reuses a block ID.
122
+ - A pi started by the fish hook runs inside a prompt event, so Ctrl+Z may not suspend it.
72
123
 
73
124
  ## License
74
125
 
package/index.ts CHANGED
@@ -5,54 +5,82 @@
5
5
  // in. Rex has no hook for pi, so this extension runs the same command and adds
6
6
  // its output to the system prompt as a `<rex>` section.
7
7
  //
8
- // Two additions on top of the Rex output:
9
- // - When the session has more than one tab, the session label is kept. A tab
10
- // must not rename its parent session.
11
- // - Set `rex.renameTab` to true in the pi settings to also tell pi to name the
12
- // Rex tab. Tab naming is off by default.
8
+ // The extension also names the Rex session and tab. The session takes its name
9
+ // from the project folder, or from the worktree and branch. On the first user
10
+ // prompt of a pi session it asks the current model for one short tab label,
11
+ // then runs `rex window rename` and, for the first tab of a session,
12
+ // `rex session rename`. Naming runs in the background, so the first response is
13
+ // not delayed. Set `rex.autoName` to false to turn it off.
14
+ //
15
+ // The extension also records the pi session of each Rex pane, so a shell hook
16
+ // can resume pi in that pane after a Rex restart. See `lib/resume.ts`.
13
17
 
14
- import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
15
- import { countWindows, stripSessionNaming } from "./lib/rex-output.ts";
16
- import { KEEP_SESSION_INSTRUCTION, REX_SECTION, TAB_RENAME_INSTRUCTION } from "./lib/prompt.ts";
18
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
19
+ import { nameSession, REX_TIMEOUT_MS, type ExecResult } from "./lib/naming.ts";
20
+ import { AUTO_NAME_INSTRUCTION, REX_SECTION } from "./lib/prompt.ts";
21
+ import { registerResume } from "./lib/resume.ts";
22
+ import { stripSessionNaming } from "./lib/rex-output.ts";
17
23
 
18
- interface RexSettings {
19
- renameTab?: boolean;
20
- }
24
+ /** Timeout for the naming model call. */
25
+ const NAMING_TIMEOUT_MS = 15000;
21
26
 
22
- /** Read `rex.renameTab`. Anything other than `true` keeps tab naming off. */
23
- function renameTabEnabled(pi: ExtensionAPI): boolean {
27
+ /** Name one session and tab. `true` unless the user turns it off. */
28
+ function autoNameEnabled(pi: ExtensionAPI): boolean {
24
29
  const rex = (pi.getSettings() as { rex?: unknown }).rex;
25
- if (typeof rex !== "object" || rex === null) return false;
26
- return (rex as RexSettings).renameTab === true;
30
+ if (typeof rex !== "object" || rex === null) return true;
31
+ return (rex as { autoName?: unknown }).autoName !== false;
27
32
  }
28
33
 
29
34
  /**
30
- * Count the tabs of the session. A missing answer keeps the Rex behavior, so a
31
- * failure never hides the session-naming instructions.
35
+ * Ask the session model for one label. Returns an empty string when the model
36
+ * is missing or the request fails.
32
37
  */
33
- async function countSessionWindows(
34
- pi: ExtensionAPI,
35
- session: string,
36
- cwd: string,
37
- ): Promise<number | undefined> {
38
- const result = await pi.exec("rex", ["session", "inspect", session, "--json"], {
39
- cwd,
40
- timeout: 5000,
41
- });
42
- if (result.code !== 0) return undefined;
43
- return countWindows(result.stdout);
38
+ async function askModel(ctx: ExtensionContext, prompt: string): Promise<string> {
39
+ const model = ctx.model;
40
+ if (!model) return "";
41
+ try {
42
+ const message = await ctx.modelRegistry.complete(
43
+ model,
44
+ {
45
+ messages: [
46
+ { role: "user", content: [{ type: "text", text: prompt }], timestamp: Date.now() },
47
+ ],
48
+ },
49
+ {
50
+ maxTokens: 200,
51
+ reasoning: "minimal",
52
+ timeoutMs: NAMING_TIMEOUT_MS,
53
+ maxRetries: 0,
54
+ ...(ctx.signal ? { signal: ctx.signal } : {}),
55
+ },
56
+ );
57
+ if (message.stopReason === "error") return "";
58
+ return message.content
59
+ .filter((part) => part.type === "text")
60
+ .map((part) => part.text)
61
+ .join(" ")
62
+ .trim();
63
+ } catch {
64
+ return "";
65
+ }
44
66
  }
45
67
 
46
68
  export default function rexExtension(pi: ExtensionAPI): void {
47
69
  let context = "";
70
+ let autoName = true;
71
+ let naming: Promise<void> | undefined;
72
+
73
+ registerResume(pi);
48
74
 
49
75
  pi.on("session_start", async (_event, ctx) => {
50
76
  context = "";
77
+ autoName = true;
78
+ naming = undefined;
51
79
  const session = process.env.REX_SESSION;
52
80
  if (!session) return;
53
81
  const result = await pi.exec("rex", ["__internal", "session-start", "--agent", "pi"], {
54
82
  cwd: ctx.cwd,
55
- timeout: 5000,
83
+ timeout: REX_TIMEOUT_MS,
56
84
  });
57
85
  if (result.code !== 0) {
58
86
  ctx.ui.notify(
@@ -63,15 +91,25 @@ export default function rexExtension(pi: ExtensionAPI): void {
63
91
  }
64
92
  let output = result.stdout.trim();
65
93
  if (!output) return;
66
- const windows = await countSessionWindows(pi, session, ctx.cwd);
67
- if (windows !== undefined && windows > 1) {
68
- output = `${stripSessionNaming(output)}\n\n${KEEP_SESSION_INSTRUCTION}`;
69
- }
70
- if (renameTabEnabled(pi)) output = `${output}\n\n${TAB_RENAME_INSTRUCTION}`;
94
+ autoName = autoNameEnabled(pi);
95
+ if (autoName) output = `${stripSessionNaming(output)}\n\n${AUTO_NAME_INSTRUCTION}`;
71
96
  context = output;
72
97
  });
73
98
 
74
- pi.on("before_agent_start", (event) => {
99
+ pi.on("before_agent_start", (event, ctx) => {
75
100
  if (context) event.systemPromptOptions.sections[REX_SECTION] = context;
101
+ const session = process.env.REX_SESSION;
102
+ if (!context || !autoName || naming || !session) return;
103
+ if (event.messageType !== "user" || event.prompt.trim().length === 0) return;
104
+ naming = nameSession({
105
+ session,
106
+ cwd: ctx.cwd,
107
+ task: event.prompt,
108
+ exec: async (command, args, options): Promise<ExecResult> => {
109
+ const result = await pi.exec(command, args, options);
110
+ return { code: result.code, stdout: result.stdout };
111
+ },
112
+ ask: (prompt) => askModel(ctx, prompt),
113
+ }).catch(() => undefined);
76
114
  });
77
115
  }
package/lib/naming.ts ADDED
@@ -0,0 +1,130 @@
1
+ // Orchestrates automatic Rex naming. The extension names the session after the
2
+ // project folder, or after the worktree and its branch, and asks the session
3
+ // model for one tab label.
4
+ //
5
+ // Every Rex call is best-effort: a failing command or model call leaves the
6
+ // generated name in place and does not block the main agent run.
7
+
8
+ import { namingPrompt } from "./prompt.ts";
9
+ import { parseInspect, parseWhoami, type RexInspect, type RexWindow } from "./rex-output.ts";
10
+ import { sessionLabel } from "./session-name.ts";
11
+
12
+ /** Upper bound for the task text sent to the naming model. */
13
+ export const MAX_TASK_LENGTH = 4000;
14
+
15
+ /** Timeout for one Rex CLI call. */
16
+ export const REX_TIMEOUT_MS = 5000;
17
+
18
+ /** Default Rex session labels are two lowercase words, such as `shy-strait`. */
19
+ const SESSION_LABEL = /^[a-z]+-[a-z]+$/;
20
+
21
+ /** Worktree labels this extension writes, so a branch change can replace them. */
22
+ const WORKTREE_LABEL = /^Wrktree—/;
23
+
24
+ /** Default Rex tab labels are `Window <id suffix>`. */
25
+ const WINDOW_LABEL = /^Window [0-9a-f]{4,}$/;
26
+
27
+ export interface ExecResult {
28
+ readonly code: number;
29
+ readonly stdout: string;
30
+ }
31
+
32
+ export type Exec = (
33
+ command: string,
34
+ args: string[],
35
+ options: { cwd: string; timeout: number },
36
+ ) => Promise<ExecResult>;
37
+
38
+ /** Returns the raw model reply for one naming prompt. */
39
+ export type Ask = (prompt: string) => Promise<string>;
40
+
41
+ export interface NameSessionInput {
42
+ readonly session: string;
43
+ readonly cwd: string;
44
+ readonly task: string;
45
+ readonly exec: Exec;
46
+ readonly ask: Ask;
47
+ }
48
+
49
+ /** A generated session label may be replaced. A hand-set label may not. */
50
+ export function isGeneratedSessionLabel(label: string): boolean {
51
+ return SESSION_LABEL.test(label) || WORKTREE_LABEL.test(label);
52
+ }
53
+
54
+ /** A generated tab label may be replaced. A hand-set label may not. */
55
+ export function isGeneratedWindowLabel(label: string): boolean {
56
+ return WINDOW_LABEL.test(label);
57
+ }
58
+
59
+ /** Sanitize one model reply into a Rex label, or reject it. */
60
+ export function parseLabel(raw: string): string | undefined {
61
+ const firstLine =
62
+ raw
63
+ .trim()
64
+ .split(/\r?\n/)
65
+ .map((line) => line.trim())
66
+ .find((line) => line.length > 0 && !line.startsWith("```")) ?? "";
67
+ const label = firstLine
68
+ .replace(/^```[a-z]*\s*/i, "")
69
+ .replace(/```\s*$/, "")
70
+ .replace(/^label:\s*/i, "")
71
+ .replace(/^["'`\s]+|["'`.,;:\s]+$/g, "")
72
+ .toLowerCase();
73
+ if (label.length === 0 || label.length > 40) return undefined;
74
+ if (!/^[a-z0-9]+(?:-[a-z0-9]+){1,3}$/.test(label)) return undefined;
75
+ return label;
76
+ }
77
+
78
+ /** Rename the current tab, and the session when this tab is the first one. */
79
+ export async function nameSession(input: NameSessionInput): Promise<void> {
80
+ const { session, cwd, exec } = input;
81
+ const options = { cwd, timeout: REX_TIMEOUT_MS };
82
+ const rex = (args: string[]) => exec("rex", args, options);
83
+
84
+ const task = input.task.slice(0, MAX_TASK_LENGTH).trim();
85
+ if (task.length === 0) return;
86
+
87
+ // Probe Rex before the model call, so a dead server costs no tokens. The
88
+ // window ID does not change while the tab lives.
89
+ const whoami = parseWhoami((await rex(["whoami", "--json"])).stdout);
90
+ if (!whoami) return;
91
+
92
+ // The session label comes from the folder and the worktree, not the model.
93
+ // A model failure then still renames the session.
94
+ const nextSessionLabel = await sessionLabel(exec, cwd, REX_TIMEOUT_MS);
95
+
96
+ let tabLabel: string | undefined;
97
+ try {
98
+ tabLabel = parseLabel(await input.ask(namingPrompt(task)));
99
+ } catch {
100
+ tabLabel = undefined;
101
+ }
102
+
103
+ // Read the labels after the model call. A user or the main agent can rename
104
+ // while it runs, and those labels must win.
105
+ const state = parseInspect((await rex(["session", "inspect", session, "--json"])).stdout);
106
+ if (!state) return;
107
+ const current = findWindow(state, whoami);
108
+ if (!current) return;
109
+
110
+ if (
111
+ state.label !== nextSessionLabel &&
112
+ isGeneratedSessionLabel(state.label) &&
113
+ isFirstWindow(state, whoami)
114
+ ) {
115
+ await rex(["session", "rename", session, nextSessionLabel]);
116
+ }
117
+ if (tabLabel && (current.label === undefined || isGeneratedWindowLabel(current.label))) {
118
+ await rex(["window", "rename", "-s", session, whoami, tabLabel]);
119
+ }
120
+ }
121
+
122
+ /** Windows are ordered by ID, which Rex derives from creation time. */
123
+ function isFirstWindow(state: RexInspect, windowId: string): boolean {
124
+ const ids = state.windows.map((window) => window.window_id).sort();
125
+ return ids[0] === windowId;
126
+ }
127
+
128
+ function findWindow(state: RexInspect, windowId: string): RexWindow | undefined {
129
+ return state.windows.find((window) => window.window_id === windowId);
130
+ }
package/lib/prompt.ts CHANGED
@@ -5,23 +5,26 @@
5
5
  export const REX_SECTION = "rex";
6
6
 
7
7
  /**
8
- * Replaces the Rex session-naming paragraph when the session has more than one
9
- * tab. A session is the parent of its tabs, so a later tab must not rename it.
8
+ * Replaces the Rex session-naming paragraph when automatic naming is on.
9
+ * The extension does the naming, so the agent must not compete with it.
10
10
  */
11
- export const KEEP_SESSION_INSTRUCTION = `The session already has more than one tab. Do not rename the session. Do not run \`rex session rename\`. Keep the current session label.`;
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
13
  /**
14
- * Appended to the Rex session-start output when `rex.renameTab` is true.
15
- *
16
- * A session is the parent and a tab is the child: the first tab carries the
17
- * session label, later tabs get their own label.
14
+ * Asks the naming model for one tab label. The task text is the user's first
15
+ * prompt, trimmed by the caller.
18
16
  */
19
- export const TAB_RENAME_INSTRUCTION = `Name the tab (window) too. Do it in the same step as the session rename. Do not wait for the user to ask.
17
+ export function namingPrompt(task: string): string {
18
+ return `Name the coding task below for a terminal label.
20
19
 
21
- A Rex session is the parent and a tab is the child. The first tab of a session takes the session label. A later tab gets its own label.
20
+ Rules:
21
+ - Reply with the label only. No quotes, no punctuation, no explanation.
22
+ - Use 2 to 4 English words in lowercase, joined by hyphens.
23
+ - Use ASCII letters and digits only.
24
+ - Name the task or project, not the tool or the agent.
22
25
 
23
- 1. Run \`rex whoami --json\` and read \`.window_id\`.
24
- 2. Run \`rex window ls -s "$REX_SESSION" --json\` and sort the window IDs.
25
- 3. If your window ID is the first ID, use the session label. If not, choose a label for the work in this tab. Use two to four lowercase words joined by hyphens.
26
- 4. Rename with \`rex window rename -s "$REX_SESSION" WINDOW_ID LABEL\`.
27
- 5. Keep a label that already fits the work. If the rename fails, continue the task and do not mention it.`;
26
+ Task:
27
+ <task>
28
+ ${task}
29
+ </task>`;
30
+ }
package/lib/resume.ts ADDED
@@ -0,0 +1,90 @@
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
+ }
package/lib/rex-output.ts CHANGED
@@ -1,4 +1,14 @@
1
- // Helpers that read and reshape the Rex session-start output.
1
+ // Helpers that read and reshape the Rex CLI output.
2
+
3
+ export interface RexWindow {
4
+ readonly window_id: string;
5
+ readonly label?: string;
6
+ }
7
+
8
+ export interface RexInspect {
9
+ readonly label: string;
10
+ readonly windows: readonly RexWindow[];
11
+ }
2
12
 
3
13
  /**
4
14
  * Remove the paragraph that asks pi to rename the session.
@@ -14,13 +24,36 @@ export function stripSessionNaming(output: string): string {
14
24
  .trim();
15
25
  }
16
26
 
17
- /** Read `.windows` from `rex session inspect --json` output. */
18
- export function countWindows(json: string): number | undefined {
27
+ /** Read `.window_id` from `rex whoami --json` output. */
28
+ export function parseWhoami(json: string): string | undefined {
29
+ const value = parse(json);
30
+ if (typeof value !== "object" || value === null) return undefined;
31
+ const windowId = (value as { window_id?: unknown }).window_id;
32
+ return typeof windowId === "string" && windowId.length > 0 ? windowId : undefined;
33
+ }
34
+
35
+ /** Read `.label` and `.windows` from `rex session inspect --json` output. */
36
+ export function parseInspect(json: string): RexInspect | undefined {
37
+ const value = parse(json);
38
+ if (typeof value !== "object" || value === null) return undefined;
39
+ const record = value as { label?: unknown; windows?: unknown };
40
+ if (typeof record.label !== "string" || !Array.isArray(record.windows)) return undefined;
41
+ const windows: RexWindow[] = [];
42
+ for (const entry of record.windows) {
43
+ if (typeof entry !== "object" || entry === null) return undefined;
44
+ const window = entry as { window_id?: unknown; label?: unknown };
45
+ if (typeof window.window_id !== "string") return undefined;
46
+ windows.push({
47
+ window_id: window.window_id,
48
+ ...(typeof window.label === "string" ? { label: window.label } : {}),
49
+ });
50
+ }
51
+ return { label: record.label, windows };
52
+ }
53
+
54
+ function parse(json: string): unknown {
19
55
  try {
20
- const parsed: unknown = JSON.parse(json);
21
- if (typeof parsed !== "object" || parsed === null) return undefined;
22
- const windows = (parsed as { windows?: unknown }).windows;
23
- return Array.isArray(windows) ? windows.length : undefined;
56
+ return JSON.parse(json) as unknown;
24
57
  } catch {
25
58
  return undefined;
26
59
  }
@@ -0,0 +1,63 @@
1
+ // Session labels from the project folder, or from the worktree and its branch.
2
+ //
3
+ // Rex labels a new session with two lowercase words. The extension replaces
4
+ // that name with the folder name, so the session matches the project. A linked
5
+ // worktree adds the main repository folder and the branch, because the folder
6
+ // alone does not tell two worktrees apart: `Wrktree—<repo>—<branch>`.
7
+
8
+ import path from "node:path";
9
+
10
+ export type GitExec = (
11
+ command: string,
12
+ args: string[],
13
+ options: { cwd: string; timeout: number },
14
+ ) => Promise<{ code: number; stdout: string }>;
15
+
16
+ export interface WorktreeEntry {
17
+ readonly path: string;
18
+ readonly head: string;
19
+ readonly branch?: string;
20
+ }
21
+
22
+ /** Parse `git worktree list --porcelain` into one entry per worktree. */
23
+ export function parseWorktrees(porcelain: string): WorktreeEntry[] {
24
+ const entries: WorktreeEntry[] = [];
25
+ let current: { path: string; head: string; branch?: string } | undefined;
26
+ for (const line of porcelain.split(/\r?\n/)) {
27
+ if (line.startsWith("worktree ")) {
28
+ current = { path: line.slice("worktree ".length), head: "" };
29
+ entries.push(current);
30
+ } else if (current && line.startsWith("HEAD ")) {
31
+ current.head = line.slice("HEAD ".length);
32
+ } else if (current && line.startsWith("branch ")) {
33
+ current.branch = line.slice("branch ".length);
34
+ }
35
+ }
36
+ return entries;
37
+ }
38
+
39
+ /** Session label: the folder name, or the worktree label inside a linked worktree. */
40
+ export async function sessionLabel(exec: GitExec, cwd: string, timeout: number): Promise<string> {
41
+ const folder = path.basename(cwd) || cwd;
42
+ let entries: WorktreeEntry[];
43
+ try {
44
+ const result = await exec("git", ["worktree", "list", "--porcelain"], { cwd, timeout });
45
+ if (result.code !== 0) return folder;
46
+ entries = parseWorktrees(result.stdout);
47
+ } catch {
48
+ return folder;
49
+ }
50
+ const main = entries[0];
51
+ const current = entries.find((entry) => contains(entry.path, cwd));
52
+ // A main checkout keeps the folder name. A linked worktree adds the branch.
53
+ if (!main || !current || current === main) return folder;
54
+ const branch = current.branch?.replace(/^refs\/heads\//, "") || current.head.slice(0, 7);
55
+ if (!branch) return folder;
56
+ return `Wrktree—${path.basename(main.path) || main.path}—${branch}`;
57
+ }
58
+
59
+ /** True when `cwd` is `root` or inside it. */
60
+ function contains(root: string, cwd: string): boolean {
61
+ const relative = path.relative(root, cwd);
62
+ return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative));
63
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@tian.zuo/pi-rex",
3
- "version": "0.1.1",
4
- "description": "Tells the pi coding agent that it runs in a Rex terminal, like the Rex hook for Claude Code and Codex.",
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.",
5
5
  "type": "module",
6
6
  "keywords": [
7
7
  "pi",