@tian.zuo/pi-rex 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/hook.ts DELETED
@@ -1,257 +0,0 @@
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/resume.ts DELETED
@@ -1,105 +0,0 @@
1
- // Resume pi in its Rex pane after a Rex restart.
2
- //
3
- // Rex restores sessions, tabs, panes, and scrollback after a restart. Each
4
- // pane keeps its block ID, but Rex starts a new shell in it, not the program
5
- // that ran there. This module records the pi session of the pane in
6
- // `<agent dir>/rex-resume/<block id>`, 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
- }