@tian.zuo/pi-rex 0.2.0 → 0.4.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 +18 -0
- package/README.md +83 -13
- package/index.ts +14 -13
- package/lib/hook.ts +257 -0
- package/lib/naming.ts +23 -11
- package/lib/resume.ts +105 -0
- package/lib/session-name.ts +63 -0
- package/lib/settings.ts +17 -0
- package/package.json +2 -2
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,23 @@
|
|
|
1
1
|
# @tian.zuo/pi-rex
|
|
2
2
|
|
|
3
|
+
## 0.4.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- [#211](https://github.com/TianZuo555/pi-extensions/pull/211) [`6d55a59`](https://github.com/TianZuo555/pi-extensions/commit/6d55a595c99d06ad6a2bc9bd2ae2742d6df46083) Thanks [@TianZuo555](https://github.com/TianZuo555)! - Install the shell hook that resumes pi after a Rex restart. On the first pi session inside a Rex pane, the extension writes the hook for `fish`, `zsh`, `bash`, or PowerShell, and changes only text it wrote itself. The new `rex.resume` setting turns the record and the hook off.
|
|
8
|
+
|
|
9
|
+
### Patch Changes
|
|
10
|
+
|
|
11
|
+
- [#212](https://github.com/TianZuo555/pi-extensions/pull/212) [`7b88eb3`](https://github.com/TianZuo555/pi-extensions/commit/7b88eb36e34534c79adf587a4623c2233d9dbd04) Thanks [@TianZuo555](https://github.com/TianZuo555)! - Fix three problems in the resume hook install. The bash block now uses POSIX syntax, so a `/bin/sh` that reads `.profile` can parse it. The Windows PowerShell 5.1 profile goes to `Documents\WindowsPowerShell`. Turning `rex.resume` off removes the pane's record, so the hook does not reopen the session.
|
|
12
|
+
|
|
13
|
+
## 0.3.0
|
|
14
|
+
|
|
15
|
+
### Minor Changes
|
|
16
|
+
|
|
17
|
+
- [#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.
|
|
18
|
+
|
|
19
|
+
- [#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>`.
|
|
20
|
+
|
|
3
21
|
## 0.2.0
|
|
4
22
|
|
|
5
23
|
### Minor 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). The extension also names the Rex session
|
|
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 resumes pi in each pane after a Rex restart. You install nothing else: the extension also writes the shell hook that resumes pi.
|
|
6
6
|
|
|
7
7
|
```bash
|
|
8
8
|
pi install npm:@tian.zuo/pi-rex
|
|
@@ -24,55 +24,125 @@ Run `rex skill setup` to install the skill. This extension does not install the
|
|
|
24
24
|
|
|
25
25
|
## Naming
|
|
26
26
|
|
|
27
|
-
Rex gives each session and each tab a generated name. The extension
|
|
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
|
-
|
|
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.
|
|
30
|
+
|
|
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:
|
|
30
32
|
|
|
31
33
|
```bash
|
|
32
34
|
rex session inspect "$REX_SESSION" --json
|
|
33
|
-
rex session rename "$REX_SESSION"
|
|
34
|
-
rex window rename -s "$REX_SESSION" WINDOW_ID
|
|
35
|
+
rex session rename "$REX_SESSION" SESSION_LABEL # first tab only
|
|
36
|
+
rex window rename -s "$REX_SESSION" WINDOW_ID TAB_LABEL
|
|
35
37
|
```
|
|
36
38
|
|
|
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.
|
|
40
|
+
|
|
37
41
|
The labels are read after the model call. A rename made while the call runs wins.
|
|
38
42
|
|
|
39
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.
|
|
40
44
|
|
|
41
45
|
The extension replaces a label only when the label is still generated:
|
|
42
46
|
|
|
43
|
-
- A session label is generated when it is two lowercase words, such as `shy-strait
|
|
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—`.
|
|
44
48
|
- A tab label is generated when it is `Window <id>`, such as `Window 629d2113`.
|
|
45
49
|
|
|
46
|
-
A hand-set label is kept. Naming runs once per pi session. If
|
|
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.
|
|
47
51
|
|
|
48
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.
|
|
49
53
|
|
|
54
|
+
## Resume after a Rex restart
|
|
55
|
+
|
|
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. A dead process cannot start itself, so the work needs two parts. The extension records the pi session of each pane, and it writes a shell hook. The hook starts pi again in the restored pane.
|
|
57
|
+
|
|
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 shell hook
|
|
70
|
+
|
|
71
|
+
On the first pi session in a Rex pane, the extension writes the hook for the pane's shell and shows one notice. It reads the shell from `SHELL`. A Windows pane has no `SHELL`, so there it reads `PSModulePath`.
|
|
72
|
+
|
|
73
|
+
| Shell | File | How the hook is stored |
|
|
74
|
+
| ---------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------- |
|
|
75
|
+
| fish | `~/.config/fish/conf.d/rex-resume.fish`, below `XDG_CONFIG_HOME` | The whole file. It starts with the marker line `# Generated by @tian.zuo/pi-rex.` |
|
|
76
|
+
| zsh | `.zshrc` in `ZDOTDIR` or the home folder | A block between the lines `# >>> tian.zuo/pi-rex >>>` and `# <<< tian.zuo/pi-rex <<<` |
|
|
77
|
+
| bash | The startup file a login shell reads first: `.bash_profile`, `.bash_login`, or `.profile`; `.profile` when none exists | The same marked block |
|
|
78
|
+
| PowerShell | `profile.ps1` in `Documents\PowerShell` for PowerShell 7 and `Documents\WindowsPowerShell` for Windows PowerShell 5.1, both on Windows; the `powershell` folder of the config home on macOS and Linux | The same marked block |
|
|
79
|
+
|
|
80
|
+
The extension never creates `.bash_profile`, because that file would hide an existing `.profile`. It changes only its own text: a fish file without the marker, or a startup file without the block, stays as it is.
|
|
81
|
+
|
|
82
|
+
The bash block uses POSIX syntax only. A desktop session can run `.profile` through `/bin/sh`, and that shell must parse the file even when it never starts pi.
|
|
83
|
+
|
|
84
|
+
The hook runs when a new shell starts in a restored pane. A new pane has a new block ID, so it has no record and the hook does nothing. 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`.
|
|
85
|
+
|
|
86
|
+
This is the fish hook the extension writes. The `zsh`, `bash`, and PowerShell hooks do the same work in the syntax of their shell.
|
|
87
|
+
|
|
88
|
+
```fish
|
|
89
|
+
if status is-interactive; and set -q REX_BLOCK
|
|
90
|
+
function __rex_resume --on-event fish_prompt
|
|
91
|
+
functions -e __rex_resume
|
|
92
|
+
set -l agent_dir $HOME/.pi/agent
|
|
93
|
+
# Expand ~ as pi does: fish does not expand it inside a variable.
|
|
94
|
+
set -q PI_CODING_AGENT_DIR; and set agent_dir (string replace -r -- '^~(?=/|$)' $HOME $PI_CODING_AGENT_DIR)
|
|
95
|
+
set -l file $agent_dir/rex-resume/(string replace -- 'block:' '' $REX_BLOCK)
|
|
96
|
+
test -f $file; or return
|
|
97
|
+
set -l record (cat $file)
|
|
98
|
+
test -n "$record[1]"; or return
|
|
99
|
+
cd -- $record[1]; or return
|
|
100
|
+
rm -f $file
|
|
101
|
+
$record[2..]
|
|
102
|
+
end
|
|
103
|
+
end
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
The hook runs before the first prompt, after the rest of the config is loaded. For fish it waits at that prompt; for zsh and bash it runs at the end of the startup file.
|
|
107
|
+
|
|
108
|
+
A bash hook runs only in an interactive shell, so a script that sources `.profile` does not start pi.
|
|
109
|
+
|
|
50
110
|
## Settings
|
|
51
111
|
|
|
52
112
|
The extension reads the `rex` section of the pi settings file. Add the section to `~/.pi/agent/settings.json`.
|
|
53
113
|
|
|
54
|
-
| Key | Type | Default | Description
|
|
55
|
-
| -------------- | ------- | ------- |
|
|
56
|
-
| `rex.autoName` | boolean | `true` | Name the Rex
|
|
114
|
+
| Key | Type | Default | Description |
|
|
115
|
+
| -------------- | ------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
|
|
116
|
+
| `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. |
|
|
117
|
+
| `rex.resume` | boolean | `true` | Record each pane's pi session, and write the fish hook that resumes pi after a Rex restart. `false` writes no record and no hook file. |
|
|
57
118
|
|
|
58
119
|
Example:
|
|
59
120
|
|
|
60
121
|
```json
|
|
61
122
|
{
|
|
62
123
|
"rex": {
|
|
63
|
-
"autoName": false
|
|
124
|
+
"autoName": false,
|
|
125
|
+
"resume": false
|
|
64
126
|
}
|
|
65
127
|
}
|
|
66
128
|
```
|
|
67
129
|
|
|
68
|
-
Any value other than `false` keeps
|
|
130
|
+
Any value other than `false` keeps the feature on.
|
|
69
131
|
|
|
70
132
|
## Known limits
|
|
71
133
|
|
|
72
134
|
- The extension decides "generated" from the shape of the label. A hand-set two-word session label, such as `fix-login`, is replaced.
|
|
73
|
-
-
|
|
135
|
+
- 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.
|
|
136
|
+
- The model reply must be one tab label. A prose reply leaves the old tab name in place; the session is still renamed.
|
|
74
137
|
- The naming call uses the current session model. A reasoning model can spend part of the token budget before it writes the label.
|
|
75
138
|
- 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.
|
|
139
|
+
- Resume writes a hook for `fish`, `zsh`, `bash`, and PowerShell. A pane that runs `sh`, `cmd.exe`, or another shell starts no pi after a restart. The records still exist, so a shell hook you write by hand can use them.
|
|
140
|
+
- The fish, zsh, and bash hooks ran in real shells. The PowerShell hook did not: it is written from the PowerShell syntax alone. A Windows pane needs `pi` on `PATH`, which is the `.cmd` shim that pi installs.
|
|
141
|
+
- The extension writes the hook only in the TUI, inside a Rex pane. A machine that never starts pi in a Rex pane gets no hook file.
|
|
142
|
+
- 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.
|
|
143
|
+
- 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.
|
|
144
|
+
- 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.
|
|
145
|
+
- A pi started by the fish hook runs inside a prompt event, so Ctrl+Z may not suspend it.
|
|
76
146
|
|
|
77
147
|
## License
|
|
78
148
|
|
package/index.ts
CHANGED
|
@@ -5,27 +5,26 @@
|
|
|
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
|
-
// The extension also names the Rex
|
|
9
|
-
//
|
|
10
|
-
//
|
|
11
|
-
//
|
|
12
|
-
//
|
|
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
18
|
import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
15
19
|
import { nameSession, REX_TIMEOUT_MS, type ExecResult } from "./lib/naming.ts";
|
|
16
20
|
import { AUTO_NAME_INSTRUCTION, REX_SECTION } from "./lib/prompt.ts";
|
|
21
|
+
import { registerResume } from "./lib/resume.ts";
|
|
17
22
|
import { stripSessionNaming } from "./lib/rex-output.ts";
|
|
23
|
+
import { rexSetting } from "./lib/settings.ts";
|
|
18
24
|
|
|
19
25
|
/** Timeout for the naming model call. */
|
|
20
26
|
const NAMING_TIMEOUT_MS = 15000;
|
|
21
27
|
|
|
22
|
-
/** Name one session and tab. `true` unless the user turns it off. */
|
|
23
|
-
function autoNameEnabled(pi: ExtensionAPI): boolean {
|
|
24
|
-
const rex = (pi.getSettings() as { rex?: unknown }).rex;
|
|
25
|
-
if (typeof rex !== "object" || rex === null) return true;
|
|
26
|
-
return (rex as { autoName?: unknown }).autoName !== false;
|
|
27
|
-
}
|
|
28
|
-
|
|
29
28
|
/**
|
|
30
29
|
* Ask the session model for one label. Returns an empty string when the model
|
|
31
30
|
* is missing or the request fails.
|
|
@@ -65,6 +64,8 @@ export default function rexExtension(pi: ExtensionAPI): void {
|
|
|
65
64
|
let autoName = true;
|
|
66
65
|
let naming: Promise<void> | undefined;
|
|
67
66
|
|
|
67
|
+
registerResume(pi);
|
|
68
|
+
|
|
68
69
|
pi.on("session_start", async (_event, ctx) => {
|
|
69
70
|
context = "";
|
|
70
71
|
autoName = true;
|
|
@@ -84,7 +85,7 @@ export default function rexExtension(pi: ExtensionAPI): void {
|
|
|
84
85
|
}
|
|
85
86
|
let output = result.stdout.trim();
|
|
86
87
|
if (!output) return;
|
|
87
|
-
autoName =
|
|
88
|
+
autoName = rexSetting(pi, "autoName");
|
|
88
89
|
if (autoName) output = `${stripSessionNaming(output)}\n\n${AUTO_NAME_INSTRUCTION}`;
|
|
89
90
|
context = output;
|
|
90
91
|
});
|
package/lib/hook.ts
ADDED
|
@@ -0,0 +1,257 @@
|
|
|
1
|
+
// Install the shell hook that resumes pi in its Rex pane.
|
|
2
|
+
//
|
|
3
|
+
// pi cannot start itself after a Rex restart: Rex starts a new shell in each
|
|
4
|
+
// restored pane, so the pi process that ran there is gone. The shell reads the
|
|
5
|
+
// record that `lib/resume.ts` writes, and starts `pi --session <file>`.
|
|
6
|
+
//
|
|
7
|
+
// The user should not write that hook by hand. On the first pi session inside a
|
|
8
|
+
// Rex pane, this module writes the hook for the pane's shell:
|
|
9
|
+
//
|
|
10
|
+
// - fish: a drop-in file below `conf.d`.
|
|
11
|
+
// - zsh and bash: a marked block at the end of the shell's startup file.
|
|
12
|
+
//
|
|
13
|
+
// A file that this extension wrote starts with HOOK_MARKER or holds a marked
|
|
14
|
+
// block. Everything else belongs to the user and stays unchanged.
|
|
15
|
+
|
|
16
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
17
|
+
import os from "node:os";
|
|
18
|
+
import path from "node:path";
|
|
19
|
+
|
|
20
|
+
/** First line of a fish hook file that this extension wrote. */
|
|
21
|
+
export const HOOK_MARKER =
|
|
22
|
+
"# Generated by @tian.zuo/pi-rex. Edit or delete this file to stop the hook.";
|
|
23
|
+
|
|
24
|
+
/** Start of the block this extension appends to a shell startup file. */
|
|
25
|
+
export const BLOCK_START = "# >>> tian.zuo/pi-rex >>>";
|
|
26
|
+
|
|
27
|
+
/** End of the block this extension appends to a shell startup file. */
|
|
28
|
+
export const BLOCK_END = "# <<< tian.zuo/pi-rex <<<";
|
|
29
|
+
|
|
30
|
+
/** Shells that get a hook. */
|
|
31
|
+
export type Shell = "fish" | "zsh" | "bash" | "powershell";
|
|
32
|
+
|
|
33
|
+
const FISH_HOOK = `# Start pi again after the Rex server restarts this pane.
|
|
34
|
+
# The pi-rex extension writes <agent dir>/rex-resume/<block id>.
|
|
35
|
+
if status is-interactive; and set -q REX_BLOCK
|
|
36
|
+
function __rex_resume --on-event fish_prompt
|
|
37
|
+
functions -e __rex_resume
|
|
38
|
+
set -l agent_dir $HOME/.pi/agent
|
|
39
|
+
# Expand ~ as pi does: fish does not expand it inside a variable.
|
|
40
|
+
set -q PI_CODING_AGENT_DIR; and set agent_dir (string replace -r -- '^~(?=/|$)' $HOME $PI_CODING_AGENT_DIR)
|
|
41
|
+
set -l file $agent_dir/rex-resume/(string replace -- 'block:' '' $REX_BLOCK)
|
|
42
|
+
test -f $file; or return
|
|
43
|
+
set -l record (cat $file)
|
|
44
|
+
test -n "$record[1]"; or return
|
|
45
|
+
cd -- $record[1]; or return
|
|
46
|
+
rm -f $file
|
|
47
|
+
$record[2..]
|
|
48
|
+
end
|
|
49
|
+
end
|
|
50
|
+
`;
|
|
51
|
+
|
|
52
|
+
const ZSH_HOOK = `# Start pi again after the Rex server restarts this pane.
|
|
53
|
+
if [[ -n \${REX_BLOCK:-} ]]; then
|
|
54
|
+
__rex_dir=\${PI_CODING_AGENT_DIR:-$HOME/.pi/agent}
|
|
55
|
+
[[ $__rex_dir == '~'/* ]] && __rex_dir=$HOME/\${__rex_dir#\\~/}
|
|
56
|
+
__rex_file=$__rex_dir/rex-resume/\${REX_BLOCK#block:}
|
|
57
|
+
if [[ -f $__rex_file ]]; then
|
|
58
|
+
__rex_lines=("\${(@f)$(<$__rex_file)}")
|
|
59
|
+
if [[ -n \${__rex_lines[1]:-} ]] && cd -- \${__rex_lines[1]} 2>/dev/null; then
|
|
60
|
+
__rex_cmd=("\${__rex_lines[@]:1}")
|
|
61
|
+
rm -f $__rex_file
|
|
62
|
+
(( \${#__rex_cmd} )) && "\${__rex_cmd[@]}"
|
|
63
|
+
fi
|
|
64
|
+
fi
|
|
65
|
+
unset __rex_dir __rex_file __rex_lines __rex_cmd
|
|
66
|
+
fi`;
|
|
67
|
+
|
|
68
|
+
const BASH_HOOK = `# Start pi again after the Rex server restarts this pane.
|
|
69
|
+
# Keep this block POSIX: a desktop session can run .profile through /bin/sh.
|
|
70
|
+
case $- in
|
|
71
|
+
*i*)
|
|
72
|
+
__rex_resume() {
|
|
73
|
+
[ -n "\${REX_BLOCK:-}" ] || return 0
|
|
74
|
+
__rex_dir="\${PI_CODING_AGENT_DIR:-$HOME/.pi/agent}"
|
|
75
|
+
case "$__rex_dir" in
|
|
76
|
+
"~"/*) __rex_dir="$HOME/\${__rex_dir#\\~/}" ;;
|
|
77
|
+
esac
|
|
78
|
+
__rex_file="$__rex_dir/rex-resume/\${REX_BLOCK#block:}"
|
|
79
|
+
[ -f "$__rex_file" ] || return 0
|
|
80
|
+
__rex_cwd=""
|
|
81
|
+
__rex_first=1
|
|
82
|
+
set --
|
|
83
|
+
while IFS= read -r __rex_line || [ -n "$__rex_line" ]; do
|
|
84
|
+
if [ "$__rex_first" = 1 ]; then
|
|
85
|
+
__rex_cwd="$__rex_line"
|
|
86
|
+
__rex_first=0
|
|
87
|
+
else
|
|
88
|
+
set -- "$@" "$__rex_line"
|
|
89
|
+
fi
|
|
90
|
+
done < "$__rex_file"
|
|
91
|
+
[ -n "$__rex_cwd" ] || return 0
|
|
92
|
+
cd -- "$__rex_cwd" 2>/dev/null || return 0
|
|
93
|
+
rm -f "$__rex_file"
|
|
94
|
+
if [ "$#" -gt 0 ]; then
|
|
95
|
+
"$@"
|
|
96
|
+
fi
|
|
97
|
+
}
|
|
98
|
+
__rex_resume
|
|
99
|
+
unset -f __rex_resume
|
|
100
|
+
unset __rex_dir __rex_file __rex_cwd __rex_first __rex_line
|
|
101
|
+
;;
|
|
102
|
+
esac`;
|
|
103
|
+
|
|
104
|
+
const POWERSHELL_HOOK = `# Start pi again after the Rex server restarts this pane.
|
|
105
|
+
if ($env:REX_BLOCK) {
|
|
106
|
+
$dir = if ($env:PI_CODING_AGENT_DIR) {
|
|
107
|
+
$env:PI_CODING_AGENT_DIR -replace '^~(?=[\\\\/]|$)', $HOME
|
|
108
|
+
} else {
|
|
109
|
+
Join-Path $HOME '.pi/agent'
|
|
110
|
+
}
|
|
111
|
+
$file = Join-Path (Join-Path $dir 'rex-resume') ($env:REX_BLOCK -replace '^block:', '')
|
|
112
|
+
if (Test-Path -LiteralPath $file) {
|
|
113
|
+
$lines = @(Get-Content -LiteralPath $file)
|
|
114
|
+
if ($lines.Count -ge 2 -and (Test-Path -LiteralPath $lines[0])) {
|
|
115
|
+
$arguments = @()
|
|
116
|
+
if ($lines.Count -gt 2) { $arguments = @($lines[2..($lines.Count - 1)]) }
|
|
117
|
+
Set-Location -LiteralPath $lines[0]
|
|
118
|
+
Remove-Item -LiteralPath $file -Force
|
|
119
|
+
& $lines[1] @arguments
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
}`;
|
|
123
|
+
|
|
124
|
+
/** Hook source for each shell, below the marker or between the block markers. */
|
|
125
|
+
export const HOOKS: Readonly<Record<Shell, string>> = {
|
|
126
|
+
fish: FISH_HOOK,
|
|
127
|
+
zsh: ZSH_HOOK,
|
|
128
|
+
bash: BASH_HOOK,
|
|
129
|
+
powershell: POWERSHELL_HOOK,
|
|
130
|
+
};
|
|
131
|
+
|
|
132
|
+
/** What happened to the hook file. */
|
|
133
|
+
export type HookInstall = {
|
|
134
|
+
readonly path: string;
|
|
135
|
+
readonly status: "created" | "updated" | "kept";
|
|
136
|
+
};
|
|
137
|
+
|
|
138
|
+
/** Where the hook goes, and how this extension recognizes its own text there. */
|
|
139
|
+
export type HookTarget = {
|
|
140
|
+
readonly path: string;
|
|
141
|
+
/** `drop-in` owns the whole file; `block` adds a marked block to it. */
|
|
142
|
+
readonly kind: "drop-in" | "block";
|
|
143
|
+
};
|
|
144
|
+
|
|
145
|
+
/** What this module reads from its surroundings. */
|
|
146
|
+
export interface HookContext {
|
|
147
|
+
readonly env?: NodeJS.ProcessEnv;
|
|
148
|
+
readonly home?: string;
|
|
149
|
+
readonly platform?: NodeJS.Platform;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** Shell file name from `$SHELL`, without a folder, a `.exe`, or a case difference. */
|
|
153
|
+
function shellName(env: NodeJS.ProcessEnv): string {
|
|
154
|
+
// Windows paths use a backslash, which path.basename ignores on POSIX.
|
|
155
|
+
return path
|
|
156
|
+
.basename((env.SHELL ?? "").replace(/\\/g, "/"))
|
|
157
|
+
.replace(/\.exe$/i, "")
|
|
158
|
+
.toLowerCase();
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** Shell of the pane, from `$SHELL`. Undefined for a shell without a hook. */
|
|
162
|
+
export function detectShell(context: HookContext = {}): Shell | undefined {
|
|
163
|
+
const env = context.env ?? process.env;
|
|
164
|
+
const name = shellName(env);
|
|
165
|
+
if (name === "fish" || name === "zsh" || name === "bash") return name;
|
|
166
|
+
if (name === "pwsh" || name === "powershell") return "powershell";
|
|
167
|
+
// A Windows pane has no SHELL. PowerShell exports PSModulePath to the
|
|
168
|
+
// programs it starts, and cmd.exe panes keep the one Windows sets.
|
|
169
|
+
if ((context.platform ?? process.platform) === "win32" && env.PSModulePath?.trim())
|
|
170
|
+
return "powershell";
|
|
171
|
+
return undefined;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/**
|
|
175
|
+
* Startup file for a bash login shell: the file bash reads first, and
|
|
176
|
+
* `~/.profile` when none exists. A new `~/.bash_profile` would hide the files a
|
|
177
|
+
* user already has, so this never creates one.
|
|
178
|
+
*/
|
|
179
|
+
function bashStartupFile(home: string): string {
|
|
180
|
+
for (const name of [".bash_profile", ".bash_login", ".profile"]) {
|
|
181
|
+
const file = path.join(home, name);
|
|
182
|
+
if (existsSync(file)) return file;
|
|
183
|
+
}
|
|
184
|
+
return path.join(home, ".profile");
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/** File that holds the hook for a shell, and how the hook is kept there. */
|
|
188
|
+
export function hookTarget(shell: Shell, context: HookContext = {}): HookTarget {
|
|
189
|
+
const env = context.env ?? process.env;
|
|
190
|
+
const home = context.home ?? os.homedir();
|
|
191
|
+
const platform = context.platform ?? process.platform;
|
|
192
|
+
if (shell === "fish") {
|
|
193
|
+
const configHome = env.XDG_CONFIG_HOME?.trim() || path.join(home, ".config");
|
|
194
|
+
return { path: path.join(configHome, "fish", "conf.d", "rex-resume.fish"), kind: "drop-in" };
|
|
195
|
+
}
|
|
196
|
+
if (shell === "zsh") {
|
|
197
|
+
// Zsh reads .zshrc for interactive shells, and ZDOTDIR moves that file.
|
|
198
|
+
const dotdir = env.ZDOTDIR?.trim() || home;
|
|
199
|
+
return { path: path.join(dotdir, ".zshrc"), kind: "block" };
|
|
200
|
+
}
|
|
201
|
+
if (shell === "powershell") {
|
|
202
|
+
// PowerShell reads `$PROFILE.CurrentUserAllHosts`: Documents on Windows,
|
|
203
|
+
// and the config folder on macOS and Linux. Windows PowerShell 5.1 reads a
|
|
204
|
+
// different folder from PowerShell 7.
|
|
205
|
+
if (platform === "win32") {
|
|
206
|
+
const folder = shellName(env) === "powershell" ? "WindowsPowerShell" : "PowerShell";
|
|
207
|
+
return { path: path.join(home, "Documents", folder, "profile.ps1"), kind: "block" };
|
|
208
|
+
}
|
|
209
|
+
const configHome = env.XDG_CONFIG_HOME?.trim() || path.join(home, ".config");
|
|
210
|
+
return { path: path.join(configHome, "powershell", "profile.ps1"), kind: "block" };
|
|
211
|
+
}
|
|
212
|
+
return { path: bashStartupFile(home), kind: "block" };
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
/** Add or replace the marked block in a shell startup file. */
|
|
216
|
+
export function upsertBlock(current: string, hook: string): string {
|
|
217
|
+
const block = `${BLOCK_START}\n${hook}\n${BLOCK_END}`;
|
|
218
|
+
const start = current.indexOf(BLOCK_START);
|
|
219
|
+
const end = current.indexOf(BLOCK_END);
|
|
220
|
+
if (start !== -1 && end > start) {
|
|
221
|
+
return `${current.slice(0, start)}${block}${current.slice(end + BLOCK_END.length)}`;
|
|
222
|
+
}
|
|
223
|
+
if (current === "") return `${block}\n`;
|
|
224
|
+
const separator = current.endsWith("\n") ? "\n" : "\n\n";
|
|
225
|
+
return `${current}${separator}${block}\n`;
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/**
|
|
229
|
+
* Write the hook for the pane's shell. `created` and `updated` mean this call
|
|
230
|
+
* changed a file; `kept` means the file already holds the hook, or the user
|
|
231
|
+
* wrote it. Returns undefined for a shell without a hook, and when the write
|
|
232
|
+
* fails.
|
|
233
|
+
*/
|
|
234
|
+
export function installShellHook(context: HookContext = {}): HookInstall | undefined {
|
|
235
|
+
const shell = detectShell(context);
|
|
236
|
+
if (!shell) return undefined;
|
|
237
|
+
const target = hookTarget(shell, context);
|
|
238
|
+
try {
|
|
239
|
+
const current = existsSync(target.path) ? readFileSync(target.path, "utf8") : undefined;
|
|
240
|
+
// A drop-in file without the marker belongs to the user.
|
|
241
|
+
if (target.kind === "drop-in" && current !== undefined && !current.startsWith(HOOK_MARKER)) {
|
|
242
|
+
return { path: target.path, status: "kept" };
|
|
243
|
+
}
|
|
244
|
+
const next =
|
|
245
|
+
target.kind === "drop-in"
|
|
246
|
+
? `${HOOK_MARKER}\n${HOOKS[shell]}`
|
|
247
|
+
: upsertBlock(current ?? "", HOOKS[shell]);
|
|
248
|
+
if (current === next) return { path: target.path, status: "kept" };
|
|
249
|
+
mkdirSync(path.dirname(target.path), { recursive: true });
|
|
250
|
+
writeFileSync(target.path, next);
|
|
251
|
+
return { path: target.path, status: current === undefined ? "created" : "updated" };
|
|
252
|
+
} catch {
|
|
253
|
+
// A hook that cannot be written must not break the agent. The records stay,
|
|
254
|
+
// and the user can add the hook by hand.
|
|
255
|
+
return undefined;
|
|
256
|
+
}
|
|
257
|
+
}
|
package/lib/naming.ts
CHANGED
|
@@ -1,11 +1,13 @@
|
|
|
1
|
-
// Orchestrates automatic Rex naming. The extension
|
|
2
|
-
//
|
|
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.
|
|
3
4
|
//
|
|
4
5
|
// Every Rex call is best-effort: a failing command or model call leaves the
|
|
5
6
|
// generated name in place and does not block the main agent run.
|
|
6
7
|
|
|
7
8
|
import { namingPrompt } from "./prompt.ts";
|
|
8
9
|
import { parseInspect, parseWhoami, type RexInspect, type RexWindow } from "./rex-output.ts";
|
|
10
|
+
import { sessionLabel } from "./session-name.ts";
|
|
9
11
|
|
|
10
12
|
/** Upper bound for the task text sent to the naming model. */
|
|
11
13
|
export const MAX_TASK_LENGTH = 4000;
|
|
@@ -16,6 +18,9 @@ export const REX_TIMEOUT_MS = 5000;
|
|
|
16
18
|
/** Default Rex session labels are two lowercase words, such as `shy-strait`. */
|
|
17
19
|
const SESSION_LABEL = /^[a-z]+-[a-z]+$/;
|
|
18
20
|
|
|
21
|
+
/** Worktree labels this extension writes, so a branch change can replace them. */
|
|
22
|
+
const WORKTREE_LABEL = /^Wrktree—/;
|
|
23
|
+
|
|
19
24
|
/** Default Rex tab labels are `Window <id suffix>`. */
|
|
20
25
|
const WINDOW_LABEL = /^Window [0-9a-f]{4,}$/;
|
|
21
26
|
|
|
@@ -43,7 +48,7 @@ export interface NameSessionInput {
|
|
|
43
48
|
|
|
44
49
|
/** A generated session label may be replaced. A hand-set label may not. */
|
|
45
50
|
export function isGeneratedSessionLabel(label: string): boolean {
|
|
46
|
-
return SESSION_LABEL.test(label);
|
|
51
|
+
return SESSION_LABEL.test(label) || WORKTREE_LABEL.test(label);
|
|
47
52
|
}
|
|
48
53
|
|
|
49
54
|
/** A generated tab label may be replaced. A hand-set label may not. */
|
|
@@ -84,13 +89,16 @@ export async function nameSession(input: NameSessionInput): Promise<void> {
|
|
|
84
89
|
const whoami = parseWhoami((await rex(["whoami", "--json"])).stdout);
|
|
85
90
|
if (!whoami) return;
|
|
86
91
|
|
|
87
|
-
|
|
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;
|
|
88
97
|
try {
|
|
89
|
-
|
|
98
|
+
tabLabel = parseLabel(await input.ask(namingPrompt(task)));
|
|
90
99
|
} catch {
|
|
91
|
-
|
|
100
|
+
tabLabel = undefined;
|
|
92
101
|
}
|
|
93
|
-
if (!label) return;
|
|
94
102
|
|
|
95
103
|
// Read the labels after the model call. A user or the main agent can rename
|
|
96
104
|
// while it runs, and those labels must win.
|
|
@@ -99,11 +107,15 @@ export async function nameSession(input: NameSessionInput): Promise<void> {
|
|
|
99
107
|
const current = findWindow(state, whoami);
|
|
100
108
|
if (!current) return;
|
|
101
109
|
|
|
102
|
-
if (
|
|
103
|
-
|
|
110
|
+
if (
|
|
111
|
+
state.label !== nextSessionLabel &&
|
|
112
|
+
isGeneratedSessionLabel(state.label) &&
|
|
113
|
+
isFirstWindow(state, whoami)
|
|
114
|
+
) {
|
|
115
|
+
await rex(["session", "rename", session, nextSessionLabel]);
|
|
104
116
|
}
|
|
105
|
-
if (current.label === undefined || isGeneratedWindowLabel(current.label)) {
|
|
106
|
-
await rex(["window", "rename", "-s", session, whoami,
|
|
117
|
+
if (tabLabel && (current.label === undefined || isGeneratedWindowLabel(current.label))) {
|
|
118
|
+
await rex(["window", "rename", "-s", session, whoami, tabLabel]);
|
|
107
119
|
}
|
|
108
120
|
}
|
|
109
121
|
|
package/lib/resume.ts
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
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>`, and installs the shell hook that reads
|
|
7
|
+
// the record (see `lib/hook.ts`).
|
|
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
|
+
import { installShellHook } from "./hook.ts";
|
|
22
|
+
import { rexSetting } from "./settings.ts";
|
|
23
|
+
|
|
24
|
+
/** Folder below the pi agent directory that holds one record per Rex pane. */
|
|
25
|
+
export const RESUME_DIR = "rex-resume";
|
|
26
|
+
|
|
27
|
+
const SIGNALS = ["SIGHUP", "SIGTERM"] as const;
|
|
28
|
+
/** A block ID becomes a file name, so accept a plain ID and not a path. */
|
|
29
|
+
const BLOCK_ID = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
|
|
30
|
+
|
|
31
|
+
/** Record file for a Rex block, such as `block:01a1...`. Undefined for a malformed ID. */
|
|
32
|
+
export function recordPath(agentDir: string, block: string): string | undefined {
|
|
33
|
+
const id = block.replace(/^block:/, "");
|
|
34
|
+
if (!BLOCK_ID.test(id)) return undefined;
|
|
35
|
+
return path.join(agentDir, RESUME_DIR, id);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** Record text: the working directory, then the resume command, one argument per line. */
|
|
39
|
+
export function recordText(cwd: string, sessionFile: string): string {
|
|
40
|
+
return `${[cwd, "pi", "--session", sessionFile].join("\n")}\n`;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function registerResume(pi: ExtensionAPI, agentDir: string = getAgentDir()): void {
|
|
44
|
+
let record: string | undefined;
|
|
45
|
+
let signaled = false;
|
|
46
|
+
const onSignal = (): void => {
|
|
47
|
+
signaled = true;
|
|
48
|
+
};
|
|
49
|
+
|
|
50
|
+
// Pi writes the session file only after the first message, so save again
|
|
51
|
+
// after each prompt. Until then, remove the record: after `/new` it still
|
|
52
|
+
// names the previous session, which the hook must not reopen.
|
|
53
|
+
const save = (ctx: ExtensionContext): void => {
|
|
54
|
+
if (!record) return;
|
|
55
|
+
const session = ctx.sessionManager.getSessionFile();
|
|
56
|
+
// The hook runs the last lines as one command. A line break in a path
|
|
57
|
+
// would move the arguments, so write no record for such a path.
|
|
58
|
+
if (!session || !existsSync(session) || /[\r\n]/.test(ctx.cwd) || /[\r\n]/.test(session)) {
|
|
59
|
+
rmSync(record, { force: true });
|
|
60
|
+
return;
|
|
61
|
+
}
|
|
62
|
+
mkdirSync(path.dirname(record), { recursive: true });
|
|
63
|
+
// Write and rename, so a stop during the write cannot leave half a record.
|
|
64
|
+
const temp = `${record}.tmp`;
|
|
65
|
+
writeFileSync(temp, recordText(ctx.cwd, session));
|
|
66
|
+
renameSync(temp, record);
|
|
67
|
+
};
|
|
68
|
+
|
|
69
|
+
pi.on("session_start", (_event, ctx) => {
|
|
70
|
+
const block = process.env.REX_BLOCK;
|
|
71
|
+
// Print, JSON, and RPC runs inherit REX_BLOCK from the agent's shell, but
|
|
72
|
+
// they are not the agent of the pane. `hasUI` is also true in RPC mode.
|
|
73
|
+
const file =
|
|
74
|
+
block !== undefined && ctx.mode === "tui" ? recordPath(agentDir, block) : undefined;
|
|
75
|
+
const enabled = file !== undefined && rexSetting(pi, "resume");
|
|
76
|
+
// Turning resume off in a live session must remove the record too, or the
|
|
77
|
+
// hook would reopen the session on the next Rex restart.
|
|
78
|
+
if (file !== undefined && !enabled) rmSync(file, { force: true });
|
|
79
|
+
record = enabled ? file : undefined;
|
|
80
|
+
if (record === undefined) return;
|
|
81
|
+
// The extension is the only part of the resume chain that runs on its own,
|
|
82
|
+
// so it installs the shell half too.
|
|
83
|
+
const hook = installShellHook();
|
|
84
|
+
if (hook && hook.status !== "kept") {
|
|
85
|
+
const verb = hook.status === "created" ? "installed" : "updated";
|
|
86
|
+
ctx.ui.notify(`pi-rex: ${verb} the resume hook ${hook.path}`, "info");
|
|
87
|
+
}
|
|
88
|
+
signaled = false;
|
|
89
|
+
for (const signal of SIGNALS) process.on(signal, onSignal);
|
|
90
|
+
save(ctx);
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
pi.on("agent_end", (_event, ctx) => save(ctx));
|
|
94
|
+
|
|
95
|
+
pi.on("session_shutdown", async (event) => {
|
|
96
|
+
if (!record) return;
|
|
97
|
+
// Pi's own signal handler runs first and starts the shutdown. Wait one tick
|
|
98
|
+
// so onSignal, a later listener for the same signal, can set the flag.
|
|
99
|
+
await new Promise((resolve) => setImmediate(resolve));
|
|
100
|
+
for (const signal of SIGNALS) process.off(signal, onSignal);
|
|
101
|
+
// `/new` replaces the session, so the record must not reopen the old one.
|
|
102
|
+
if (event.reason === "new" || (event.reason === "quit" && !signaled))
|
|
103
|
+
rmSync(record, { force: true });
|
|
104
|
+
});
|
|
105
|
+
}
|
|
@@ -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/lib/settings.ts
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
// The pi settings that pi-rex reads. One place, so both features read the same
|
|
2
|
+
// `rex` section and the same on/off rule: only `false` turns a feature off.
|
|
3
|
+
|
|
4
|
+
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
5
|
+
|
|
6
|
+
/** Names of the on/off switches in the `rex` settings section. */
|
|
7
|
+
export type RexSwitch = "autoName" | "resume";
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Read one `rex` switch. Returns `false` only for a JSON `false`; a missing
|
|
11
|
+
* section or any other value keeps the feature on.
|
|
12
|
+
*/
|
|
13
|
+
export function rexSetting(pi: ExtensionAPI, key: RexSwitch): boolean {
|
|
14
|
+
const rex = (pi.getSettings() as { rex?: unknown }).rex;
|
|
15
|
+
if (typeof rex !== "object" || rex === null) return true;
|
|
16
|
+
return (rex as Record<string, unknown>)[key] !== false;
|
|
17
|
+
}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tian.zuo/pi-rex",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "Tells the pi coding agent that it runs in a Rex terminal,
|
|
3
|
+
"version": "0.4.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",
|