@tian.zuo/pi-rex 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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,11 @@
1
1
  # @tian.zuo/pi-rex
2
2
 
3
+ ## 0.2.0
4
+
5
+ ### Minor Changes
6
+
7
+ - [#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.
8
+
3
9
  ## 0.1.1
4
10
 
5
11
  ### 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 and tab from the first prompt.
6
6
 
7
7
  ```bash
8
8
  pi install npm:@tian.zuo/pi-rex
@@ -22,53 +22,57 @@ 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
26
-
27
- The extension reads the `rex` section of the pi settings file. Add the section to `~/.pi/agent/settings.json`.
25
+ ## Naming
28
26
 
29
- | Key | Type | Default | Description |
30
- | --------------- | ------- | ------- | ---------------------------- |
31
- | `rex.renameTab` | boolean | `false` | Tell pi to name the Rex tab. |
27
+ Rex gives each session and each tab a generated name. The extension replaces these names with task names. The agent does not run a rename command.
32
28
 
33
- Example:
29
+ 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 makes one model call on the current session model. The call asks for a 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
30
 
35
- ```json
36
- {
37
- "rex": {
38
- "renameTab": true
39
- }
40
- }
31
+ ```bash
32
+ rex session inspect "$REX_SESSION" --json
33
+ rex session rename "$REX_SESSION" LABEL # first tab only
34
+ rex window rename -s "$REX_SESSION" WINDOW_ID LABEL
41
35
  ```
42
36
 
43
- Any value other than `true` keeps tab naming off.
37
+ The labels are read after the model call. A rename made while the call runs wins.
44
38
 
45
- ## Naming
39
+ 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.
46
40
 
47
- Rex gives each session and each tab a generated name. The agent can replace these names with task names.
41
+ The extension replaces a label only when the label is still generated:
48
42
 
49
- ### Session naming
43
+ - A session label is generated when it is two lowercase words, such as `shy-strait`.
44
+ - A tab label is generated when it is `Window <id>`, such as `Window 629d2113`.
50
45
 
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.
46
+ A hand-set label is kept. Naming runs once per pi session. If the model call or a Rex command fails, the old name stays and the agent continues.
52
47
 
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.
48
+ 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.
54
49
 
55
- The extension counts the tabs with `rex session inspect "$REX_SESSION" --json`. If that command fails, the Rex text stays unchanged.
50
+ ## Settings
56
51
 
57
- ### Tab naming
52
+ The extension reads the `rex` section of the pi settings file. Add the section to `~/.pi/agent/settings.json`.
58
53
 
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:
54
+ | Key | Type | Default | Description |
55
+ | -------------- | ------- | ------- | -------------------------------------------------------------------------------------------------------- |
56
+ | `rex.autoName` | boolean | `true` | Name the Rex tab and session from the first prompt. `false` keeps the Rex names and the Rex naming text. |
60
57
 
61
- ```bash
62
- rex window rename -s "$REX_SESSION" WINDOW_ID LABEL
58
+ Example:
59
+
60
+ ```json
61
+ {
62
+ "rex": {
63
+ "autoName": false
64
+ }
65
+ }
63
66
  ```
64
67
 
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.
68
+ Any value other than `false` keeps automatic naming on.
66
69
 
67
70
  ## Known limits
68
71
 
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.
72
+ - The extension decides "generated" from the shape of the label. A hand-set two-word session label, such as `fix-login`, is replaced.
73
+ - The model reply must be one label. A prose reply leaves the old name in place.
74
+ - The naming call uses the current session model. A reasoning model can spend part of the token budget before it writes the label.
75
+ - 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.
72
76
 
73
77
  ## License
74
78
 
package/index.ts CHANGED
@@ -5,54 +5,75 @@
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 tab and session. On the first user prompt of
9
+ // a pi session it asks the current model for one short label, then runs
10
+ // `rex window rename` and, for the first tab of a session, `rex session
11
+ // rename`. Naming runs in the background, so the first response is not delayed.
12
+ // Set `rex.autoName` to false to turn it off.
13
13
 
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";
14
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
15
+ import { nameSession, REX_TIMEOUT_MS, type ExecResult } from "./lib/naming.ts";
16
+ import { AUTO_NAME_INSTRUCTION, REX_SECTION } from "./lib/prompt.ts";
17
+ import { stripSessionNaming } from "./lib/rex-output.ts";
17
18
 
18
- interface RexSettings {
19
- renameTab?: boolean;
20
- }
19
+ /** Timeout for the naming model call. */
20
+ const NAMING_TIMEOUT_MS = 15000;
21
21
 
22
- /** Read `rex.renameTab`. Anything other than `true` keeps tab naming off. */
23
- function renameTabEnabled(pi: ExtensionAPI): boolean {
22
+ /** Name one session and tab. `true` unless the user turns it off. */
23
+ function autoNameEnabled(pi: ExtensionAPI): boolean {
24
24
  const rex = (pi.getSettings() as { rex?: unknown }).rex;
25
- if (typeof rex !== "object" || rex === null) return false;
26
- return (rex as RexSettings).renameTab === true;
25
+ if (typeof rex !== "object" || rex === null) return true;
26
+ return (rex as { autoName?: unknown }).autoName !== false;
27
27
  }
28
28
 
29
29
  /**
30
- * Count the tabs of the session. A missing answer keeps the Rex behavior, so a
31
- * failure never hides the session-naming instructions.
30
+ * Ask the session model for one label. Returns an empty string when the model
31
+ * is missing or the request fails.
32
32
  */
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);
33
+ async function askModel(ctx: ExtensionContext, prompt: string): Promise<string> {
34
+ const model = ctx.model;
35
+ if (!model) return "";
36
+ try {
37
+ const message = await ctx.modelRegistry.complete(
38
+ model,
39
+ {
40
+ messages: [
41
+ { role: "user", content: [{ type: "text", text: prompt }], timestamp: Date.now() },
42
+ ],
43
+ },
44
+ {
45
+ maxTokens: 200,
46
+ reasoning: "minimal",
47
+ timeoutMs: NAMING_TIMEOUT_MS,
48
+ maxRetries: 0,
49
+ ...(ctx.signal ? { signal: ctx.signal } : {}),
50
+ },
51
+ );
52
+ if (message.stopReason === "error") return "";
53
+ return message.content
54
+ .filter((part) => part.type === "text")
55
+ .map((part) => part.text)
56
+ .join(" ")
57
+ .trim();
58
+ } catch {
59
+ return "";
60
+ }
44
61
  }
45
62
 
46
63
  export default function rexExtension(pi: ExtensionAPI): void {
47
64
  let context = "";
65
+ let autoName = true;
66
+ let naming: Promise<void> | undefined;
48
67
 
49
68
  pi.on("session_start", async (_event, ctx) => {
50
69
  context = "";
70
+ autoName = true;
71
+ naming = undefined;
51
72
  const session = process.env.REX_SESSION;
52
73
  if (!session) return;
53
74
  const result = await pi.exec("rex", ["__internal", "session-start", "--agent", "pi"], {
54
75
  cwd: ctx.cwd,
55
- timeout: 5000,
76
+ timeout: REX_TIMEOUT_MS,
56
77
  });
57
78
  if (result.code !== 0) {
58
79
  ctx.ui.notify(
@@ -63,15 +84,25 @@ export default function rexExtension(pi: ExtensionAPI): void {
63
84
  }
64
85
  let output = result.stdout.trim();
65
86
  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}`;
87
+ autoName = autoNameEnabled(pi);
88
+ if (autoName) output = `${stripSessionNaming(output)}\n\n${AUTO_NAME_INSTRUCTION}`;
71
89
  context = output;
72
90
  });
73
91
 
74
- pi.on("before_agent_start", (event) => {
92
+ pi.on("before_agent_start", (event, ctx) => {
75
93
  if (context) event.systemPromptOptions.sections[REX_SECTION] = context;
94
+ const session = process.env.REX_SESSION;
95
+ if (!context || !autoName || naming || !session) return;
96
+ if (event.messageType !== "user" || event.prompt.trim().length === 0) return;
97
+ naming = nameSession({
98
+ session,
99
+ cwd: ctx.cwd,
100
+ task: event.prompt,
101
+ exec: async (command, args, options): Promise<ExecResult> => {
102
+ const result = await pi.exec(command, args, options);
103
+ return { code: result.code, stdout: result.stdout };
104
+ },
105
+ ask: (prompt) => askModel(ctx, prompt),
106
+ }).catch(() => undefined);
76
107
  });
77
108
  }
package/lib/naming.ts ADDED
@@ -0,0 +1,118 @@
1
+ // Orchestrates automatic Rex naming. The extension asks the session model for
2
+ // one label, then renames the tab and, for the first tab, the session.
3
+ //
4
+ // Every Rex call is best-effort: a failing command or model call leaves the
5
+ // generated name in place and does not block the main agent run.
6
+
7
+ import { namingPrompt } from "./prompt.ts";
8
+ import { parseInspect, parseWhoami, type RexInspect, type RexWindow } from "./rex-output.ts";
9
+
10
+ /** Upper bound for the task text sent to the naming model. */
11
+ export const MAX_TASK_LENGTH = 4000;
12
+
13
+ /** Timeout for one Rex CLI call. */
14
+ export const REX_TIMEOUT_MS = 5000;
15
+
16
+ /** Default Rex session labels are two lowercase words, such as `shy-strait`. */
17
+ const SESSION_LABEL = /^[a-z]+-[a-z]+$/;
18
+
19
+ /** Default Rex tab labels are `Window <id suffix>`. */
20
+ const WINDOW_LABEL = /^Window [0-9a-f]{4,}$/;
21
+
22
+ export interface ExecResult {
23
+ readonly code: number;
24
+ readonly stdout: string;
25
+ }
26
+
27
+ export type Exec = (
28
+ command: string,
29
+ args: string[],
30
+ options: { cwd: string; timeout: number },
31
+ ) => Promise<ExecResult>;
32
+
33
+ /** Returns the raw model reply for one naming prompt. */
34
+ export type Ask = (prompt: string) => Promise<string>;
35
+
36
+ export interface NameSessionInput {
37
+ readonly session: string;
38
+ readonly cwd: string;
39
+ readonly task: string;
40
+ readonly exec: Exec;
41
+ readonly ask: Ask;
42
+ }
43
+
44
+ /** A generated session label may be replaced. A hand-set label may not. */
45
+ export function isGeneratedSessionLabel(label: string): boolean {
46
+ return SESSION_LABEL.test(label);
47
+ }
48
+
49
+ /** A generated tab label may be replaced. A hand-set label may not. */
50
+ export function isGeneratedWindowLabel(label: string): boolean {
51
+ return WINDOW_LABEL.test(label);
52
+ }
53
+
54
+ /** Sanitize one model reply into a Rex label, or reject it. */
55
+ export function parseLabel(raw: string): string | undefined {
56
+ const firstLine =
57
+ raw
58
+ .trim()
59
+ .split(/\r?\n/)
60
+ .map((line) => line.trim())
61
+ .find((line) => line.length > 0 && !line.startsWith("```")) ?? "";
62
+ const label = firstLine
63
+ .replace(/^```[a-z]*\s*/i, "")
64
+ .replace(/```\s*$/, "")
65
+ .replace(/^label:\s*/i, "")
66
+ .replace(/^["'`\s]+|["'`.,;:\s]+$/g, "")
67
+ .toLowerCase();
68
+ if (label.length === 0 || label.length > 40) return undefined;
69
+ if (!/^[a-z0-9]+(?:-[a-z0-9]+){1,3}$/.test(label)) return undefined;
70
+ return label;
71
+ }
72
+
73
+ /** Rename the current tab, and the session when this tab is the first one. */
74
+ export async function nameSession(input: NameSessionInput): Promise<void> {
75
+ const { session, cwd, exec } = input;
76
+ const options = { cwd, timeout: REX_TIMEOUT_MS };
77
+ const rex = (args: string[]) => exec("rex", args, options);
78
+
79
+ const task = input.task.slice(0, MAX_TASK_LENGTH).trim();
80
+ if (task.length === 0) return;
81
+
82
+ // Probe Rex before the model call, so a dead server costs no tokens. The
83
+ // window ID does not change while the tab lives.
84
+ const whoami = parseWhoami((await rex(["whoami", "--json"])).stdout);
85
+ if (!whoami) return;
86
+
87
+ let label: string | undefined;
88
+ try {
89
+ label = parseLabel(await input.ask(namingPrompt(task)));
90
+ } catch {
91
+ return;
92
+ }
93
+ if (!label) return;
94
+
95
+ // Read the labels after the model call. A user or the main agent can rename
96
+ // while it runs, and those labels must win.
97
+ const state = parseInspect((await rex(["session", "inspect", session, "--json"])).stdout);
98
+ if (!state) return;
99
+ const current = findWindow(state, whoami);
100
+ if (!current) return;
101
+
102
+ if (isGeneratedSessionLabel(state.label) && isFirstWindow(state, whoami)) {
103
+ await rex(["session", "rename", session, label]);
104
+ }
105
+ if (current.label === undefined || isGeneratedWindowLabel(current.label)) {
106
+ await rex(["window", "rename", "-s", session, whoami, label]);
107
+ }
108
+ }
109
+
110
+ /** Windows are ordered by ID, which Rex derives from creation time. */
111
+ function isFirstWindow(state: RexInspect, windowId: string): boolean {
112
+ const ids = state.windows.map((window) => window.window_id).sort();
113
+ return ids[0] === windowId;
114
+ }
115
+
116
+ function findWindow(state: RexInspect, windowId: string): RexWindow | undefined {
117
+ return state.windows.find((window) => window.window_id === windowId);
118
+ }
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/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
  }
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.2.0",
4
+ "description": "Tells the pi coding agent that it runs in a Rex terminal, and names the Rex session and tab from the first prompt.",
5
5
  "type": "module",
6
6
  "keywords": [
7
7
  "pi",