pi-farm 0.3.1 → 0.4.1
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/README.md +27 -0
- package/docs/architecture.md +2 -0
- package/docs/extension.md +73 -0
- package/docs/troubleshooting.md +32 -0
- package/extensions/pp-tmux.js +323 -0
- package/package.json +13 -6
- package/src/help.js +3 -0
- package/src/ppui.js +181 -0
package/README.md
CHANGED
|
@@ -146,6 +146,29 @@ pp mesh send backend "跑一下测试" --reply 60000 # 等它回话,收
|
|
|
146
146
|
`pp mesh send` 是走 agent 之间的消息通道(对方收到 `[agent-network] message from …` 信封)
|
|
147
147
|
- broker 没起来时会明确报 `no mesh broker at …`;`pp mesh ls/resolve` 可离线用来看地址
|
|
148
148
|
|
|
149
|
+
## 在 pi 里用 `/pp-*`(扩展)
|
|
150
|
+
|
|
151
|
+
`pp` 自带一个 pi 扩展:把 tmux 的 `Ctrl-b s`、`Ctrl-b d` 变成斜杠命令,不用离开对话。
|
|
152
|
+
|
|
153
|
+
```bash
|
|
154
|
+
pi install npm:pi-farm # 装进 ~/.pi/agent/settings.json,之后每个会话都有
|
|
155
|
+
pi -e npm:pi-farm # 只想这次带着它
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
| 命令 | tmux 等价 | 作用 |
|
|
159
|
+
| --- | --- | --- |
|
|
160
|
+
| `/pp-ls` | `Ctrl-b s` | 列出所有会话,上下选择、回车切换 |
|
|
161
|
+
| `/pp-sw <会话>` | `Ctrl-b s` + 回车 | 直接切,支持唯一前缀与参数补全 |
|
|
162
|
+
| `/pp-quit` | `Ctrl-b d` | 断开当前终端,会话和 pi 继续跑 |
|
|
163
|
+
| `/pp-status` | — | 当前会话/窗口/pane/cwd/pi 会话 id/remote-pi 名字/pp 版本 |
|
|
164
|
+
| `/pp-peek [会话] [-n N]` | — | 看另一个会话最近 N 行输出,不切换 |
|
|
165
|
+
|
|
166
|
+
细节与排障见 [docs/extension.md](docs/extension.md):
|
|
167
|
+
|
|
168
|
+
- 只操作"看着你"的那个 tmux client(`switch-client -c` / `detach-client -t`),没有 client 附着时给提示而不是报错;
|
|
169
|
+
- `/pp-status`、`/pp-peek` 用 `appendEntry` 渲染,**不占模型上下文**;`pi -p` 下改为写 stdout;
|
|
170
|
+
- 只在 tmux pane 里可用(靠 `$TMUX` 定位服务器)。
|
|
171
|
+
|
|
149
172
|
## 文档
|
|
150
173
|
|
|
151
174
|
| 文档 | 内容 |
|
|
@@ -156,6 +179,7 @@ pp mesh send backend "跑一下测试" --reply 60000 # 等它回话,收
|
|
|
156
179
|
| [docs/architecture.md](docs/architecture.md) | 内部实现:模块职责、`up` 数据流、名字解析、restart 状态机、tmux 目标规则 |
|
|
157
180
|
| [docs/troubleshooting.md](docs/troubleshooting.md) | 排障手册:按报错原文查(起不来、`can't find pane`、名字不对、自启没生效、attach 乱码…) |
|
|
158
181
|
| [docs/development.md](docs/development.md) | 开发指南:跑测试、改代码的规矩、测试分层、发布流程(含 npm staged publishing 的坑) |
|
|
182
|
+
| [docs/extension.md](docs/extension.md) | pi 扩展 `/pp-*`:在会话里切 tmux、看别人的屏幕、断开连接(安装与全部命令) |
|
|
159
183
|
|
|
160
184
|
## 配置参考
|
|
161
185
|
```yaml
|
|
@@ -459,6 +483,9 @@ Name overrides: `tmux_name`, `pi_session_name`, `remote_pi_name`.
|
|
|
459
483
|
remote-pi mode: `config` (default, writes `<cwd>/.pi/remote-pi/config.json`),
|
|
460
484
|
`env` (`REMOTE_PI_DIRECT_CONFIG`), `off`.
|
|
461
485
|
|
|
486
|
+
Inside pi, the bundled extension adds `/pp-ls`, `/pp-sw <session>`, `/pp-quit`,
|
|
487
|
+
`/pp-status` and `/pp-peek [session] [-n N]` (install with `pi install npm:pi-farm`).
|
|
488
|
+
|
|
462
489
|
Commands: `up`, `down`, `restart`, `status`, `attach`, `logs`, `send`, `check`,
|
|
463
490
|
`doctor`, `init`, `install`, `uninstall`. Options: `--config`, `--socket`,
|
|
464
491
|
`--json`, `--dry-run`, `--force`, `--watch`, `--lines`, `--quiet`, `--verbose`.
|
package/docs/architecture.md
CHANGED
|
@@ -25,6 +25,8 @@ src/help.js COMMANDS 单一数据源 + 总览/单命令页/拼写建议
|
|
|
25
25
|
src/aliases.js 备用命令名(pifarm/pi-plus/自定义软链)+ PATH 上 pp 归属判定
|
|
26
26
|
src/update.js 自升级:安装方式判定(npm/git/unknown)、registry 版本查询、命令规划
|
|
27
27
|
src/example.js `pp init` 写入的示例配置
|
|
28
|
+
src/ppui.js pi 扩展用的纯函数($TMUX 解析、会话标签、前缀匹配、peek 参数、client 选择)
|
|
29
|
+
extensions/pp-tmux.js pi 扩展入口:/pp-ls /pp-sw /pp-quit /pp-status /pp-peek
|
|
28
30
|
```
|
|
29
31
|
|
|
30
32
|
`src/help.js` 的 `COMMANDS` 是命令表的唯一来源:总览、单命令帮助、别名解析和拼写建议都由它生成,测试会断言「每个规范命令都有完整帮助页」,所以加命令时不会出现文档漂移。
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
# pi 扩展:在会话里用 `/pp-*`
|
|
2
|
+
|
|
3
|
+
`pp` 除了命令行,还带一个 pi 扩展(`extensions/pp-tmux.js`),把 tmux 里常用的几个
|
|
4
|
+
`prefix` 快捷键变成斜杠命令。这样不用离开 pi 就能切会话、看别的会话在干什么、断开连接。
|
|
5
|
+
|
|
6
|
+
## 安装
|
|
7
|
+
|
|
8
|
+
扩展随 npm 包一起发布,用 pi 自己的包管理器安装即可:
|
|
9
|
+
|
|
10
|
+
```bash
|
|
11
|
+
pi install npm:pi-farm # 写进 ~/.pi/agent/settings.json,之后每个会话都加载
|
|
12
|
+
pi -e npm:pi-farm # 只想这一次带着它启动
|
|
13
|
+
pi remove npm:pi-farm # 卸载
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
装好后在 pi 里执行 `/reload`,`/` 菜单里就会出现 `pp-ls`、`pp-sw`、`pp-quit`、
|
|
17
|
+
`pp-status`、`pp-peek`。启动横幅的 `[Extensions]` 一节里能看到 `pp-tmux.js`。
|
|
18
|
+
|
|
19
|
+
只在 **pi 跑在 tmux 里** 时可用:扩展靠 `$TMUX` 定位服务器和会话,不在 tmux 里会报
|
|
20
|
+
`not running inside tmux (TMUX is unset)`。
|
|
21
|
+
|
|
22
|
+
## 命令
|
|
23
|
+
|
|
24
|
+
| 命令 | tmux 等价 | 行为 |
|
|
25
|
+
|---|---|---|
|
|
26
|
+
| `/pp-ls` | `Ctrl-b s` | 列出所有会话(名称、路径、窗口数、当前/已死标记),上下选择、回车切换 |
|
|
27
|
+
| `/pp-sw <会话>` | `Ctrl-b s` + 回车 | 直接切换;支持唯一前缀(`/pp-sw risk`)、大小写不敏感 |
|
|
28
|
+
| `/pp-quit` | `Ctrl-b d` | 断开当前 client;**会话和 pi 都继续运行**,回来接上就能看到 |
|
|
29
|
+
| `/pp-status` | `Ctrl-b i` 的加强版 | 会话 / 窗口 / pane / cwd / 已连接 client 数 / socket / pi 会话 id 与文件 / remote-pi 名字 / pp 版本 |
|
|
30
|
+
| `/pp-peek [会话] [-n N]` | `Ctrl-b w` 的只读版 | 打印另一个会话最近 N 行输出(默认 30),不切换 |
|
|
31
|
+
|
|
32
|
+
`/pp-sw` 和 `/pp-peek` 带参数补全:输入 `/pp-sw ` 后按 Tab,会列出会话名并标注当前会话。
|
|
33
|
+
`/pp-peek` 省略会话名时看自己这个会话。
|
|
34
|
+
|
|
35
|
+
## 行为细节
|
|
36
|
+
|
|
37
|
+
- **只有“看着你”的 client 会被切换/断开。** 扩展先 `list-clients` 找到附着在当前会话上、
|
|
38
|
+
最近活跃的那个 client,再 `switch-client -c <client>` / `detach-client -t <client>`。
|
|
39
|
+
没有 client 附着(例如会话是 `up` 起来后没人 attach)时给提示而不是执行:
|
|
40
|
+
`cannot switch: no tmux client is attached — attach first (pp attach <session>)`。
|
|
41
|
+
- **切换不会影响 pi 本身。** `/pp-sw` 只是把终端视图切走,原来那格 pane 里的 pi 继续跑;
|
|
42
|
+
`/pp-quit` 同理,断开的是终端,不是进程。想真正结束会话用 `pp down <会话>`(或在
|
|
43
|
+
pi 里 `/quit` 后按会话的 `restart` 策略处理)。
|
|
44
|
+
- **`/pp-status` 和 `/pp-peek` 的输出不进模型上下文。** 它们用 `pi.appendEntry()` 写自定义
|
|
45
|
+
条目,只在界面上渲染;`/pp-peek` 不会把别的会话内容塞进当前对话。
|
|
46
|
+
- **非交互模式(`pi -p`)** 下两个输出类命令改为写到 stdout,方便脚本化:
|
|
47
|
+
|
|
48
|
+
```bash
|
|
49
|
+
tmux new -d -s probe -c ~/code/api "pi -e npm:pi-farm -p '/pp-status'"
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
## 实现
|
|
53
|
+
|
|
54
|
+
| 文件 | 作用 |
|
|
55
|
+
|---|---|
|
|
56
|
+
| `extensions/pp-tmux.js` | 扩展入口:注册 5 个命令、调 tmux、渲染结果 |
|
|
57
|
+
| `src/ppui.js` | 纯函数:`$TMUX` 解析、会话标签、前缀匹配、`/pp-peek` 参数解析、截断输出、挑 client |
|
|
58
|
+
|
|
59
|
+
`pp` 的执行逻辑和扩展互不依赖:扩展直接调 `tmux`,不经过 `pp` 二进制,所以 tmux 里的
|
|
60
|
+
进程用哪个版本的 `pp` 都不影响它(`/pp-status` 显示的 `pp` 版本来自扩展所在包的
|
|
61
|
+
`package.json`)。
|
|
62
|
+
|
|
63
|
+
测试:`node --test test/ppui.test.js`(解析、标签、匹配、参数、截断、client 选择)。
|
|
64
|
+
|
|
65
|
+
## 常见问题
|
|
66
|
+
|
|
67
|
+
| 现象 | 处理 |
|
|
68
|
+
|---|---|
|
|
69
|
+
| `/pp-*` 不在命令列表里 | 没装或没加载:`pi list` 看有没有 `npm:pi-farm`,装完 `/reload` |
|
|
70
|
+
| `not running inside tmux (TMUX is unset)` | pi 不在 tmux pane 里;先 `pp attach <会话>` 或 `tmux new -s x` 再起 pi |
|
|
71
|
+
| `cannot switch: no tmux client is attached` | 会话是后台起的、没人 attach;`pp attach <会话>` 接上再来 |
|
|
72
|
+
| `/pp-ls` 列表里没有某个会话 | 它在另一个 tmux socket 上;扩展只列当前 `$TMUX` 那个服务器的会话 |
|
|
73
|
+
| 切换后回到原点 | `/pp-sw` 换的是 client,pi 在原来的 pane 里继续跑;`/pp-ls` 里带 `(current)` 的就是 pi 所在会话 |
|
package/docs/troubleshooting.md
CHANGED
|
@@ -184,6 +184,38 @@ pp up backend # 点名启动会清掉这条记录,重新纳入巡检
|
|
|
184
184
|
- 远程:`ssh -t host 'pp attach backend'`(`-t` 必须有)
|
|
185
185
|
- 只想看输出:`pp logs backend -n 500` 或 `tail -f ~/.pi/plus/logs/backend.log`
|
|
186
186
|
|
|
187
|
+
## pi 扩展类
|
|
188
|
+
|
|
189
|
+
### pi 里没有 `/pp-ls`、`/pp-sw` 这些命令
|
|
190
|
+
|
|
191
|
+
扩展随 npm 包发布,但不会自动进 pi 的配置:
|
|
192
|
+
|
|
193
|
+
```bash
|
|
194
|
+
pi list # 看有没有 npm:pi-farm
|
|
195
|
+
pi install npm:pi-farm # 装(写 ~/.pi/agent/settings.json)
|
|
196
|
+
```
|
|
197
|
+
|
|
198
|
+
装完在运行的会话里 `/reload`,或重开 pi。启动横幅的 `[Extensions]` 一节应出现 `pp-tmux.js`。
|
|
199
|
+
|
|
200
|
+
### `not running inside tmux (TMUX is unset)`
|
|
201
|
+
|
|
202
|
+
扩展靠 `$TMUX` 定位 tmux 服务器。pi 不在 tmux pane 里就会这样报。
|
|
203
|
+
|
|
204
|
+
```bash
|
|
205
|
+
tmux new -s work -c ~/code/api "pi" # 在 tmux 里起
|
|
206
|
+
pp attach backend # 或者接到已有会话上
|
|
207
|
+
```
|
|
208
|
+
|
|
209
|
+
### `cannot switch: no tmux client is attached — attach first (pp attach <session>)`
|
|
210
|
+
|
|
211
|
+
会话是 `pp up` 在后台起的,没有终端 attach 在它上面,所以没有 client 可以切换/断开。
|
|
212
|
+
先 `pp attach <session>`,或在某个终端里 `tmux attach -t <session>`。
|
|
213
|
+
|
|
214
|
+
### `/pp-ls` 看不到某个会话
|
|
215
|
+
|
|
216
|
+
扩展只列**当前 `$TMUX` 指向的那个服务器**里的会话。`pp up --socket other` 起的会话在另一个
|
|
217
|
+
socket 上,`tmux -L other list-sessions` 才看得到。
|
|
218
|
+
|
|
187
219
|
## 发布 / 安装类
|
|
188
220
|
|
|
189
221
|
### `npm i -g pi-farm` 装到的是别的东西或 404
|
|
@@ -0,0 +1,323 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* pp-tmux — pi extension: drive the surrounding tmux session from slash commands.
|
|
3
|
+
*
|
|
4
|
+
* /pp-ls pick a tmux session (like Ctrl-b s) and switch to it
|
|
5
|
+
* /pp-sw <name> switch straight to a session (like Ctrl-b s + Enter)
|
|
6
|
+
* /pp-quit detach this client, session and pi keep running (Ctrl-b d)
|
|
7
|
+
* /pp-status where am I: session, pane, cwd, pi session, remote-pi name
|
|
8
|
+
* /pp-peek [name] [-n N] last N lines of another session's pane (default 30)
|
|
9
|
+
*
|
|
10
|
+
* Install with `pi install npm:pi-farm`, or try it once with `pi -e npm:pi-farm`.
|
|
11
|
+
*/
|
|
12
|
+
import { execFile } from "node:child_process";
|
|
13
|
+
import { readFileSync } from "node:fs";
|
|
14
|
+
import { dirname, join } from "node:path";
|
|
15
|
+
import { fileURLToPath } from "node:url";
|
|
16
|
+
import { promisify } from "node:util";
|
|
17
|
+
|
|
18
|
+
import { Box, Text } from "@earendil-works/pi-tui";
|
|
19
|
+
|
|
20
|
+
import {
|
|
21
|
+
SEP,
|
|
22
|
+
formatSessionLabel,
|
|
23
|
+
formatStatusLines,
|
|
24
|
+
matchSessionName,
|
|
25
|
+
parsePeekArgs,
|
|
26
|
+
parseTmuxEnv,
|
|
27
|
+
pickClient,
|
|
28
|
+
sessionNameFromLabel,
|
|
29
|
+
trimCapture,
|
|
30
|
+
} from "../src/ppui.js";
|
|
31
|
+
|
|
32
|
+
const execFileAsync = promisify(execFile);
|
|
33
|
+
|
|
34
|
+
function packageVersion() {
|
|
35
|
+
try {
|
|
36
|
+
const here = dirname(fileURLToPath(import.meta.url));
|
|
37
|
+
return JSON.parse(readFileSync(join(here, "..", "package.json"), "utf8")).version ?? "?";
|
|
38
|
+
} catch {
|
|
39
|
+
return "?";
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
async function tmux(args) {
|
|
44
|
+
try {
|
|
45
|
+
const { stdout } = await execFileAsync("tmux", args, { maxBuffer: 16 * 1024 * 1024 });
|
|
46
|
+
return stdout;
|
|
47
|
+
} catch (error) {
|
|
48
|
+
const detail = String(error?.stderr ?? "").trim() || String(error?.message ?? error).trim();
|
|
49
|
+
throw new Error(detail || `tmux ${args[0] ?? ""} failed`);
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function toRows(output) {
|
|
54
|
+
return String(output ?? "")
|
|
55
|
+
.split("\n")
|
|
56
|
+
.filter((line) => line.trim() !== "")
|
|
57
|
+
.map((line) => line.split(SEP));
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
async function currentSession() {
|
|
61
|
+
return (await tmux(["display-message", "-p", "#S"])).trim();
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
async function readSessions() {
|
|
65
|
+
const sessionFormat = ["#{session_name}", "#{session_attached}", "#{session_windows}", "#{session_activity}"].join(SEP);
|
|
66
|
+
const paneFormat = ["#{session_name}", "#{pane_current_path}", "#{pane_active}", "#{pane_dead}", "#{pane_current_command}"].join(SEP);
|
|
67
|
+
const [sessionsOut, panesOut, current] = await Promise.all([
|
|
68
|
+
tmux(["list-sessions", "-F", sessionFormat]),
|
|
69
|
+
tmux(["list-panes", "-a", "-F", paneFormat]),
|
|
70
|
+
currentSession(),
|
|
71
|
+
]);
|
|
72
|
+
const panes = new Map();
|
|
73
|
+
for (const [session, path, active, dead, command] of toRows(panesOut)) {
|
|
74
|
+
if (active !== "1" && panes.has(session)) continue;
|
|
75
|
+
panes.set(session, { path, dead: dead === "1", command });
|
|
76
|
+
}
|
|
77
|
+
const list = toRows(sessionsOut).map(([name, attached, windows, activity]) => ({
|
|
78
|
+
name,
|
|
79
|
+
attached: Number.parseInt(attached ?? "0", 10) || 0,
|
|
80
|
+
windows: Number.parseInt(windows ?? "0", 10) || 0,
|
|
81
|
+
activity: Number.parseInt(activity ?? "0", 10) || 0,
|
|
82
|
+
path: panes.get(name)?.path ?? "",
|
|
83
|
+
dead: panes.get(name)?.dead ?? false,
|
|
84
|
+
command: panes.get(name)?.command ?? "",
|
|
85
|
+
current: name === current,
|
|
86
|
+
}));
|
|
87
|
+
list.sort((a, b) => Number(b.current) - Number(a.current) || b.activity - a.activity);
|
|
88
|
+
return list;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
async function readClients() {
|
|
92
|
+
const out = await tmux(["list-clients", "-F", ["#{client_name}", "#{client_session}", "#{client_activity}"].join(SEP)]);
|
|
93
|
+
return toRows(out).map(([name, session, activity]) => ({
|
|
94
|
+
name,
|
|
95
|
+
session,
|
|
96
|
+
activity: Number.parseInt(activity ?? "0", 10) || 0,
|
|
97
|
+
}));
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** The client most likely looking at `session` (used to switch/detach it explicitly). */
|
|
101
|
+
async function attachedClient(session) {
|
|
102
|
+
const clients = await readClients().catch(() => []);
|
|
103
|
+
return { client: pickClient(clients, session), total: clients.length };
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function remotePiInfo(cwd) {
|
|
107
|
+
try {
|
|
108
|
+
const file = join(cwd, ".pi", "remote-pi", "config.json");
|
|
109
|
+
const config = JSON.parse(readFileSync(file, "utf8"));
|
|
110
|
+
const name = typeof config.agent_name === "string" ? config.agent_name : "";
|
|
111
|
+
if (!name) return "no agent_name in .pi/remote-pi/config.json";
|
|
112
|
+
const relay = config.auto_start_relay === false ? "relay off" : "relay on";
|
|
113
|
+
return `${name} (${cwd}@${name}, ${relay})`;
|
|
114
|
+
} catch {
|
|
115
|
+
return "not configured in this directory";
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** The extension only makes sense inside a tmux pane. */
|
|
120
|
+
function tmuxContext() {
|
|
121
|
+
const info = parseTmuxEnv(process.env.TMUX);
|
|
122
|
+
if (!info) {
|
|
123
|
+
throw new Error("not running inside tmux (TMUX is unset) — /pp-* needs a tmux pane");
|
|
124
|
+
}
|
|
125
|
+
return info;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** `…/--tmp-x--/01a1eeb5…` — the session directory plus a short id. */
|
|
129
|
+
function clipPath(path) {
|
|
130
|
+
if (!path) return undefined;
|
|
131
|
+
const parts = String(path).split("/").filter(Boolean);
|
|
132
|
+
const file = parts[parts.length - 1] ?? "";
|
|
133
|
+
const dir = parts[parts.length - 2] ?? "";
|
|
134
|
+
const match = file.match(/_([0-9a-f-]+)\.jsonl$/);
|
|
135
|
+
const id = match ? match[1].slice(0, 8) : file.slice(0, 8);
|
|
136
|
+
return dir ? `…/${dir}/${id}…` : `…${id}…`;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
function sessionCompletions(prefix) {
|
|
140
|
+
return readSessions()
|
|
141
|
+
.then((sessions) => {
|
|
142
|
+
const items = sessions.map((session) => ({ value: session.name, label: formatSessionLabel(session) }));
|
|
143
|
+
const filtered = items.filter((item) => item.value.startsWith(prefix ?? ""));
|
|
144
|
+
return filtered.length > 0 ? filtered : null;
|
|
145
|
+
})
|
|
146
|
+
.catch(() => null);
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/** Switch the client that is looking at our session to `target`. */
|
|
150
|
+
async function switchClient(ctx, target) {
|
|
151
|
+
const session = await currentSession();
|
|
152
|
+
const { client, total } = await attachedClient(session);
|
|
153
|
+
if (!client) {
|
|
154
|
+
const why = total === 0 ? "no tmux client is attached" : `the attached client is on another session`;
|
|
155
|
+
ctx.ui.notify(`cannot switch: ${why} — attach first (pp attach ${session})`, "warning");
|
|
156
|
+
return;
|
|
157
|
+
}
|
|
158
|
+
await tmux(["switch-client", "-c", client, "-t", target]);
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
export default function ppTmux(pi) {
|
|
162
|
+
const report = (ctx, title, body) => {
|
|
163
|
+
const text = String(body ?? "");
|
|
164
|
+
// Print mode has no transcript: write the report to stdout so scripts can use
|
|
165
|
+
// `pi -p "/pp-status"` (JSON mode stays untouched).
|
|
166
|
+
if (!ctx.hasUI && ctx.mode === "print") {
|
|
167
|
+
process.stdout.write(`${title}\n${text}\n`);
|
|
168
|
+
return;
|
|
169
|
+
}
|
|
170
|
+
pi.appendEntry("pp-report", { title, body: text });
|
|
171
|
+
};
|
|
172
|
+
|
|
173
|
+
pi.registerEntryRenderer("pp-report", (entry, _options, theme) => {
|
|
174
|
+
const data = entry.data ?? {};
|
|
175
|
+
const box = new Box(0, 0, (text) => theme.bg("customMessageBg", text));
|
|
176
|
+
box.addChild(new Text(theme.bold(data.title ?? "pp")));
|
|
177
|
+
box.addChild(new Text(theme.fg("dim", String(data.body ?? ""))));
|
|
178
|
+
return box;
|
|
179
|
+
});
|
|
180
|
+
|
|
181
|
+
const command = (name, definition) => {
|
|
182
|
+
const handler = definition.handler;
|
|
183
|
+
pi.registerCommand(name, {
|
|
184
|
+
...definition,
|
|
185
|
+
handler: async (args, ctx) => {
|
|
186
|
+
try {
|
|
187
|
+
await handler(args, ctx);
|
|
188
|
+
} catch (error) {
|
|
189
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
190
|
+
if (!ctx.hasUI && ctx.mode === "print") {
|
|
191
|
+
// no TUI to notify: surface the failure to the shell instead of exiting 0
|
|
192
|
+
process.stderr.write(`pp: ${message}\n`);
|
|
193
|
+
process.exitCode = 1;
|
|
194
|
+
return;
|
|
195
|
+
}
|
|
196
|
+
ctx.ui.notify(message, "error");
|
|
197
|
+
}
|
|
198
|
+
},
|
|
199
|
+
});
|
|
200
|
+
};
|
|
201
|
+
|
|
202
|
+
command("pp-ls", {
|
|
203
|
+
description: "List tmux sessions and switch to the one you pick (Ctrl-b s)",
|
|
204
|
+
handler: async (_args, ctx) => {
|
|
205
|
+
tmuxContext();
|
|
206
|
+
const sessions = await readSessions();
|
|
207
|
+
if (sessions.length === 0) {
|
|
208
|
+
ctx.ui.notify("no tmux sessions", "warning");
|
|
209
|
+
return;
|
|
210
|
+
}
|
|
211
|
+
const labels = sessions.map(formatSessionLabel);
|
|
212
|
+
if (!ctx.hasUI) {
|
|
213
|
+
report(ctx, "tmux sessions", labels.join("\n"));
|
|
214
|
+
return;
|
|
215
|
+
}
|
|
216
|
+
const choice = await ctx.ui.select("tmux sessions — Enter to switch, Esc to stay", labels);
|
|
217
|
+
if (!choice) return;
|
|
218
|
+
const name = sessionNameFromLabel(choice);
|
|
219
|
+
const session = sessions.find((item) => item.name === name);
|
|
220
|
+
if (!session) return;
|
|
221
|
+
if (session.current) {
|
|
222
|
+
ctx.ui.notify(`${name} is the current session`, "info");
|
|
223
|
+
return;
|
|
224
|
+
}
|
|
225
|
+
await switchClient(ctx, session.current ? name : name);
|
|
226
|
+
},
|
|
227
|
+
});
|
|
228
|
+
|
|
229
|
+
command("pp-sw", {
|
|
230
|
+
description: "Switch this client to another tmux session (Ctrl-b s + Enter)",
|
|
231
|
+
getArgumentCompletions: sessionCompletions,
|
|
232
|
+
handler: async (args, ctx) => {
|
|
233
|
+
tmuxContext();
|
|
234
|
+
const query = String(args ?? "").trim();
|
|
235
|
+
if (!query) {
|
|
236
|
+
ctx.ui.notify("usage: /pp-sw <session> (or /pp-ls to pick from a list)", "warning");
|
|
237
|
+
return;
|
|
238
|
+
}
|
|
239
|
+
const sessions = await readSessions();
|
|
240
|
+
const resolved = matchSessionName(sessions.map((session) => session.name), query);
|
|
241
|
+
if (resolved.error) {
|
|
242
|
+
ctx.ui.notify(resolved.error, "error");
|
|
243
|
+
return;
|
|
244
|
+
}
|
|
245
|
+
const session = sessions.find((item) => item.name === resolved.name);
|
|
246
|
+
if (session?.current) {
|
|
247
|
+
ctx.ui.notify(`${session.name} is already the current session`, "info");
|
|
248
|
+
return;
|
|
249
|
+
}
|
|
250
|
+
await switchClient(ctx, resolved.name);
|
|
251
|
+
},
|
|
252
|
+
});
|
|
253
|
+
|
|
254
|
+
command("pp-quit", {
|
|
255
|
+
description: "Detach this client from tmux — the session and pi keep running (Ctrl-b d)",
|
|
256
|
+
handler: async (_args, ctx) => {
|
|
257
|
+
const info = tmuxContext();
|
|
258
|
+
const session = await currentSession();
|
|
259
|
+
const clients = await readClients().catch(() => []);
|
|
260
|
+
const client = pickClient(clients, session);
|
|
261
|
+
if (client) await tmux(["detach-client", "-t", client]);
|
|
262
|
+
else await tmux(["detach-client", "-s", session]);
|
|
263
|
+
pi.appendEntry("pp-quit", { at: new Date().toISOString(), session, client, socket: info.socketPath });
|
|
264
|
+
if (ctx.hasUI) ctx.ui.notify(`detached from ${session} — it keeps running`, "info");
|
|
265
|
+
},
|
|
266
|
+
});
|
|
267
|
+
|
|
268
|
+
command("pp-status", {
|
|
269
|
+
description: "Show the tmux session, pane, cwd, pi session and remote-pi name of this agent",
|
|
270
|
+
handler: async (_args, ctx) => {
|
|
271
|
+
const info = tmuxContext();
|
|
272
|
+
const session = await currentSession();
|
|
273
|
+
const [window, paneId, clients] = await Promise.all([
|
|
274
|
+
tmux(["display-message", "-p", "#{window_index}:#{window_name}"]),
|
|
275
|
+
tmux(["display-message", "-p", "#{pane_id}"]),
|
|
276
|
+
readClients().catch(() => []),
|
|
277
|
+
]);
|
|
278
|
+
const attached = clients.filter((client) => client.session === session);
|
|
279
|
+
const lines = formatStatusLines({
|
|
280
|
+
session,
|
|
281
|
+
window: window.trim(),
|
|
282
|
+
pane: paneId.trim(),
|
|
283
|
+
cwd: process.cwd(),
|
|
284
|
+
clients: `${attached.length} attached${attached.length ? ` (${attached.map((client) => client.name).join(", ")})` : ""}`,
|
|
285
|
+
socketPath: info.socketPath,
|
|
286
|
+
piSessionName: pi.getSessionName?.() ?? undefined,
|
|
287
|
+
piSessionId: ctx.sessionManager?.getSessionId?.() ?? undefined,
|
|
288
|
+
piSessionFile: clipPath(ctx.sessionManager?.getSessionFile?.()),
|
|
289
|
+
remotePi: remotePiInfo(process.cwd()),
|
|
290
|
+
ppVersion: packageVersion(),
|
|
291
|
+
});
|
|
292
|
+
report(ctx, `pp status — ${session}`, lines.join("\n"));
|
|
293
|
+
},
|
|
294
|
+
});
|
|
295
|
+
|
|
296
|
+
command("pp-peek", {
|
|
297
|
+
description: "Show the last lines of another tmux session without switching to it",
|
|
298
|
+
getArgumentCompletions: sessionCompletions,
|
|
299
|
+
handler: async (args, ctx) => {
|
|
300
|
+
tmuxContext();
|
|
301
|
+
const parsed = parsePeekArgs(args);
|
|
302
|
+
if (parsed.error) {
|
|
303
|
+
ctx.ui.notify(`${parsed.error} usage: /pp-peek [session] [-n N]`, "error");
|
|
304
|
+
return;
|
|
305
|
+
}
|
|
306
|
+
let target = parsed.target;
|
|
307
|
+
if (target) {
|
|
308
|
+
const sessions = await readSessions();
|
|
309
|
+
const resolved = matchSessionName(sessions.map((session) => session.name), target);
|
|
310
|
+
if (resolved.error) {
|
|
311
|
+
ctx.ui.notify(resolved.error, "error");
|
|
312
|
+
return;
|
|
313
|
+
}
|
|
314
|
+
target = resolved.name;
|
|
315
|
+
} else {
|
|
316
|
+
target = await currentSession();
|
|
317
|
+
}
|
|
318
|
+
const captured = await tmux(["capture-pane", "-p", "-J", "-t", `=${target}:`, "-S", `-${parsed.lines}`]);
|
|
319
|
+
const text = trimCapture(captured, parsed.lines);
|
|
320
|
+
report(ctx, `pp peek — ${target} (last ${parsed.lines} lines)`, text === "" ? "(pane is empty)" : text);
|
|
321
|
+
},
|
|
322
|
+
});
|
|
323
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-farm",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.1",
|
|
4
4
|
"description": "Declarative tmux sessions for pi coding agents (CLI: pp). One YAML drives the tmux session, pi session id/name and remote-pi mesh name, and survives reboots.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
@@ -9,13 +9,14 @@
|
|
|
9
9
|
"pi-plus": "bin/pp.js"
|
|
10
10
|
},
|
|
11
11
|
"files": [
|
|
12
|
+
"LICENSE",
|
|
13
|
+
"README.md",
|
|
12
14
|
"bin",
|
|
13
|
-
"src",
|
|
14
|
-
"examples",
|
|
15
15
|
"completions",
|
|
16
16
|
"docs",
|
|
17
|
-
"
|
|
18
|
-
"
|
|
17
|
+
"examples",
|
|
18
|
+
"extensions",
|
|
19
|
+
"src"
|
|
19
20
|
],
|
|
20
21
|
"engines": {
|
|
21
22
|
"node": ">=18.0.0"
|
|
@@ -35,7 +36,8 @@
|
|
|
35
36
|
"cli",
|
|
36
37
|
"autostart",
|
|
37
38
|
"systemd",
|
|
38
|
-
"launchd"
|
|
39
|
+
"launchd",
|
|
40
|
+
"pi-package"
|
|
39
41
|
],
|
|
40
42
|
"author": "HardyDou",
|
|
41
43
|
"license": "MIT",
|
|
@@ -50,5 +52,10 @@
|
|
|
50
52
|
"publishConfig": {
|
|
51
53
|
"registry": "https://registry.npmjs.org/",
|
|
52
54
|
"access": "public"
|
|
55
|
+
},
|
|
56
|
+
"pi": {
|
|
57
|
+
"extensions": [
|
|
58
|
+
"./extensions/pp-tmux.js"
|
|
59
|
+
]
|
|
53
60
|
}
|
|
54
61
|
}
|
package/src/help.js
CHANGED
|
@@ -413,6 +413,9 @@ export function renderOverview(version) {
|
|
|
413
413
|
lines.push(" pi --name pi_session_name | name");
|
|
414
414
|
lines.push(" remote-pi remote_pi_name | name");
|
|
415
415
|
lines.push("");
|
|
416
|
+
lines.push("Inside a pi session (extension, `pi install npm:pi-farm`):");
|
|
417
|
+
lines.push(" /pp-ls /pp-sw <session> /pp-quit /pp-status /pp-peek [session] [-n N]");
|
|
418
|
+
lines.push("");
|
|
416
419
|
lines.push(`Run 'pp help <command>' for details, e.g. 'pp help install'.`);
|
|
417
420
|
return `${lines.join("\n")}\n`;
|
|
418
421
|
}
|
package/src/ppui.js
ADDED
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pure helpers behind the `/pp-*` pi extension commands.
|
|
3
|
+
*
|
|
4
|
+
* Kept separate from the extension itself so they can be unit tested without
|
|
5
|
+
* starting pi or tmux.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
/** Field separator used when asking tmux for machine-readable output. */
|
|
9
|
+
export const SEP = "\u001f";
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Parse the `TMUX` environment variable: `<socket-path>,<server-pid>,<session-index>`.
|
|
13
|
+
* @returns {{socketPath: string, serverPid: number|null, sessionIndex: number|null}|null}
|
|
14
|
+
*/
|
|
15
|
+
export function parseTmuxEnv(value) {
|
|
16
|
+
if (typeof value !== "string" || value.trim() === "") return null;
|
|
17
|
+
const parts = value.split(",");
|
|
18
|
+
if (parts.length < 2) return null;
|
|
19
|
+
const socketPath = parts.slice(0, parts.length - 2).join(",");
|
|
20
|
+
const serverPid = Number.parseInt(parts[parts.length - 2], 10);
|
|
21
|
+
const sessionIndex = Number.parseInt(parts[parts.length - 1], 10);
|
|
22
|
+
if (!socketPath) return null;
|
|
23
|
+
return {
|
|
24
|
+
socketPath,
|
|
25
|
+
serverPid: Number.isFinite(serverPid) ? serverPid : null,
|
|
26
|
+
sessionIndex: Number.isFinite(sessionIndex) ? sessionIndex : null,
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** Shorten a path to its last two segments: `/a/b/c/d` → `…/c/d`. */
|
|
31
|
+
export function shortPath(path, max = 34) {
|
|
32
|
+
if (!path) return "";
|
|
33
|
+
const text = String(path);
|
|
34
|
+
if (text.length <= max) return text;
|
|
35
|
+
const parts = text.split("/").filter(Boolean);
|
|
36
|
+
if (parts.length >= 2) {
|
|
37
|
+
const tail = `…/${parts.slice(-2).join("/")}`;
|
|
38
|
+
if (tail.length <= max) return tail;
|
|
39
|
+
}
|
|
40
|
+
return `…${text.slice(-(max - 1))}`;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** Pad to a visible width (no ANSI involved here). */
|
|
44
|
+
function pad(text, width) {
|
|
45
|
+
const value = String(text ?? "");
|
|
46
|
+
if (value.length >= width) return value;
|
|
47
|
+
return value + " ".repeat(width - value.length);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* One row of the `/pp-ls` picker.
|
|
52
|
+
* @param {{name: string, path?: string, windows?: number, attached?: number, current?: boolean, dead?: boolean, command?: string}} info
|
|
53
|
+
*/
|
|
54
|
+
export function formatSessionLabel(info) {
|
|
55
|
+
const marks = [];
|
|
56
|
+
if (info.current) marks.push("current");
|
|
57
|
+
if (info.dead) marks.push("dead");
|
|
58
|
+
if (info.attached > 1) marks.push(`${info.attached} clients`);
|
|
59
|
+
const suffix = marks.length ? ` (${marks.join(", ")})` : "";
|
|
60
|
+
const windows = Number.isFinite(info.windows) && info.windows > 0 ? `${info.windows}w` : "";
|
|
61
|
+
const name = info.current ? `* ${info.name}` : ` ${info.name}`;
|
|
62
|
+
return `${pad(name, 22)}${pad(shortPath(info.path), 35)}${pad(windows, 4)}${suffix}`.trimEnd();
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Parse `#<index>` or a plain name out of the picker label ("* backend /x 2w (current)").
|
|
67
|
+
* The index is not used for routing (tmux list order is activity based), so we
|
|
68
|
+
* only take the name.
|
|
69
|
+
*/
|
|
70
|
+
export function sessionNameFromLabel(label) {
|
|
71
|
+
const text = String(label ?? "").replace(/^\s*\*\s*/, "").trim();
|
|
72
|
+
return text.split(/\s{2,}/)[0]?.trim() ?? "";
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Resolve a user supplied session reference against known session names:
|
|
77
|
+
* exact match wins, then case-insensitive exact, then a unique prefix.
|
|
78
|
+
* @returns {{name: string}|{error: string}}
|
|
79
|
+
*/
|
|
80
|
+
export function matchSessionName(names, query) {
|
|
81
|
+
const wanted = String(query ?? "").trim();
|
|
82
|
+
if (!wanted) return { error: "no session name given" };
|
|
83
|
+
const list = names.filter((name) => typeof name === "string" && name !== "");
|
|
84
|
+
if (list.includes(wanted)) return { name: wanted };
|
|
85
|
+
const lower = wanted.toLowerCase();
|
|
86
|
+
const exact = list.filter((name) => name.toLowerCase() === lower);
|
|
87
|
+
if (exact.length === 1) return { name: exact[0] };
|
|
88
|
+
const prefixed = list.filter((name) => name.toLowerCase().startsWith(lower));
|
|
89
|
+
if (prefixed.length === 1) return { name: prefixed[0] };
|
|
90
|
+
if (prefixed.length > 1) {
|
|
91
|
+
return { error: `"${wanted}" is ambiguous: ${prefixed.slice(0, 5).join(", ")}` };
|
|
92
|
+
}
|
|
93
|
+
return { error: `no tmux session named "${wanted}"` };
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Parse `/pp-peek` arguments: `[session] [-n N] [--lines N] [-nN]`.
|
|
98
|
+
* @returns {{target: string|null, lines: number}|{error: string}}
|
|
99
|
+
*/
|
|
100
|
+
export function parsePeekArgs(text) {
|
|
101
|
+
const tokens = String(text ?? "").trim().split(/\s+/).filter(Boolean);
|
|
102
|
+
let target = null;
|
|
103
|
+
let lines = 30;
|
|
104
|
+
for (let i = 0; i < tokens.length; i += 1) {
|
|
105
|
+
const token = tokens[i];
|
|
106
|
+
if (token === "-n" || token === "--lines") {
|
|
107
|
+
const raw = tokens[i + 1];
|
|
108
|
+
if (raw === undefined) return { error: `${token} needs a number` };
|
|
109
|
+
const value = Number.parseInt(raw, 10);
|
|
110
|
+
if (!Number.isFinite(value)) return { error: `${token} needs a number, got "${raw}"` };
|
|
111
|
+
lines = value;
|
|
112
|
+
i += 1;
|
|
113
|
+
continue;
|
|
114
|
+
}
|
|
115
|
+
if (/^-\d+$/.test(token)) {
|
|
116
|
+
lines = Number.parseInt(token.slice(1), 10);
|
|
117
|
+
continue;
|
|
118
|
+
}
|
|
119
|
+
if (/^-n-?\d+$/.test(token)) {
|
|
120
|
+
lines = Number.parseInt(token.slice(2), 10);
|
|
121
|
+
continue;
|
|
122
|
+
}
|
|
123
|
+
if (token.startsWith("-")) return { error: `unknown option ${token}` };
|
|
124
|
+
if (target !== null) return { error: `unexpected argument "${token}"` };
|
|
125
|
+
target = token;
|
|
126
|
+
}
|
|
127
|
+
if (lines < 1 || lines > 500) return { error: "line count must be between 1 and 500" };
|
|
128
|
+
return { target, lines };
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** Drop trailing blank lines, then keep the last `lines` lines. */
|
|
132
|
+
export function trimCapture(text, lines = 30) {
|
|
133
|
+
const all = String(text ?? "").replace(/\r/g, "").split("\n");
|
|
134
|
+
while (all.length > 0 && all[all.length - 1].trim() === "") all.pop();
|
|
135
|
+
if (all.length <= lines) return all.join("\n");
|
|
136
|
+
return all.slice(all.length - lines).join("\n");
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* Pick the client most likely to be "us": the most recently active client
|
|
141
|
+
* attached to `session`.
|
|
142
|
+
* @param {Array<{name: string, session: string, activity?: number}>} clients
|
|
143
|
+
*/
|
|
144
|
+
export function pickClient(clients, session) {
|
|
145
|
+
const attached = clients.filter((client) => client.session === session);
|
|
146
|
+
if (attached.length === 0) return null;
|
|
147
|
+
const sorted = attached.slice().sort((a, b) => (b.activity ?? 0) - (a.activity ?? 0));
|
|
148
|
+
return sorted[0].name;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** `12:34:56` from a unix timestamp in seconds. */
|
|
152
|
+
export function clockTime(seconds) {
|
|
153
|
+
const value = Number(seconds);
|
|
154
|
+
if (!Number.isFinite(value) || value <= 0) return "";
|
|
155
|
+
const date = new Date(value * 1000);
|
|
156
|
+
const hh = String(date.getHours()).padStart(2, "0");
|
|
157
|
+
const mm = String(date.getMinutes()).padStart(2, "0");
|
|
158
|
+
return `${hh}:${mm}`;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** Build the `/pp-status` report lines (label + value pairs). */
|
|
162
|
+
export function formatStatusLines(info) {
|
|
163
|
+
const rows = [];
|
|
164
|
+
const push = (label, value) => {
|
|
165
|
+
if (value === undefined || value === null || value === "") return;
|
|
166
|
+
rows.push([label, String(value)]);
|
|
167
|
+
};
|
|
168
|
+
push("session", info.session);
|
|
169
|
+
push("window", info.window);
|
|
170
|
+
push("pane", info.pane);
|
|
171
|
+
push("cwd", info.cwd);
|
|
172
|
+
push("clients", info.clients);
|
|
173
|
+
push("socket", info.socketPath);
|
|
174
|
+
push("pi session", info.piSessionName);
|
|
175
|
+
push("pi id", info.piSessionId);
|
|
176
|
+
push("pi file", info.piSessionFile);
|
|
177
|
+
push("remote-pi", info.remotePi);
|
|
178
|
+
push("pp", info.ppVersion);
|
|
179
|
+
const width = rows.reduce((max, [label]) => Math.max(max, label.length), 0);
|
|
180
|
+
return rows.map(([label, value]) => `${label.padEnd(width)} ${value}`);
|
|
181
|
+
}
|