pi-farm 0.2.3 → 0.3.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 +29 -0
- package/bin/pp.js +3 -0
- package/completions/_pp +8 -1
- package/completions/pp.bash +7 -3
- package/docs/architecture.md +3 -1
- package/docs/cli.md +40 -0
- package/docs/troubleshooting.md +45 -0
- package/package.json +4 -2
- package/src/aliases.js +204 -0
- package/src/commands.js +290 -3
- package/src/help.js +58 -4
- package/src/mesh.js +15 -0
- package/src/update.js +106 -0
package/README.md
CHANGED
|
@@ -46,6 +46,32 @@ cd pi-plus && ./install.sh
|
|
|
46
46
|
|
|
47
47
|
依赖:Node.js ≥ 18、tmux、pi(非 pi 的 agent 也可以,见 `agent` 字段)。
|
|
48
48
|
|
|
49
|
+
### 升级
|
|
50
|
+
|
|
51
|
+
```bash
|
|
52
|
+
pp update # 查最新版并升级(npm 全局装的就 npm i -g,git clone 的就 git pull)
|
|
53
|
+
pp update --check # 只看有没有新版;有则退出码 1,适合脚本/定时任务
|
|
54
|
+
pp update --dry-run # 只打印会跑的升级命令
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
> 内网镜像访问不到公共源时:`PP_NPM_REGISTRY=https://nexus.../npm-group pp update`;若报 `notarget`,是 npm 的 packument 缓存过期,`npm cache clean --force` 后重试。
|
|
58
|
+
|
|
59
|
+
### 命令名被别的程序占了?(macOS 自带 `/usr/bin/pp`)
|
|
60
|
+
|
|
61
|
+
macOS 上 `/usr/bin/pp` 是一个 ASN.1 转换工具,`pp ls` 会打出它的用法说明。除了 `pp`,安装时还会一起装两个名字:
|
|
62
|
+
|
|
63
|
+
```bash
|
|
64
|
+
pifarm ls # 等价于 pp ls
|
|
65
|
+
pi-plus ls
|
|
66
|
+
|
|
67
|
+
pp alias add pif # 或者自己起个短名字(软链到同一个脚本,升级不会失效)
|
|
68
|
+
pp alias ls # 看有哪些别名、目录是否在 PATH 里
|
|
69
|
+
pp alias rm pif
|
|
70
|
+
pp doctor # 会提示 PATH 上的 pp 到底是不是我们
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
`install.sh` 也支持换名字:`PP_BIN_NAME=pifarm ./install.sh`(或 `PP_BIN_NAME="pp pif"`)。
|
|
74
|
+
|
|
49
75
|
> 若你的 `npm config get registry` 指向内网镜像(例如 Nexus),装不到这个包时显式指定公共源:
|
|
50
76
|
> `npm i -g pi-farm --registry https://registry.npmjs.org/`
|
|
51
77
|
|
|
@@ -284,6 +310,8 @@ pp doctor 环境诊断(含自启状态、WSL 提示)
|
|
|
284
310
|
pp init 写示例配置
|
|
285
311
|
pp install [--watch N] 安装开机自启(别名 autostart)
|
|
286
312
|
pp uninstall 卸载自启
|
|
313
|
+
pp alias [ls|add|rm] 换/加一个命令名(pp 被别的程序占用时用)
|
|
314
|
+
pp update [--check] 升级到最新发布版(npm / git 安装自动判断)
|
|
287
315
|
pp help [命令] 帮助(不带参数为总览)
|
|
288
316
|
pp version 打印版本
|
|
289
317
|
```
|
|
@@ -378,6 +406,7 @@ sessions:
|
|
|
378
406
|
| remote-pi 名字不对 | 看 `<cwd>/.pi/remote-pi/config.json` 的 `agent_name`;同名冲突时 broker 可能显示 `name#2` |
|
|
379
407
|
| 自启没生效 | `systemctl --user status pi-plus`;WSL 确认 systemd 开启;`pp doctor` |
|
|
380
408
|
| pi 找不到 | systemd 的 PATH 由 `install` 自动写入 node 所在目录;自定义路径用 `agent: /abs/path/pi` |
|
|
409
|
+
| `pp ls` 打出一大段 ASN.1 用法 | 那是 macOS 自带的 `/usr/bin/pp`。用 `pifarm ls`,或 `pp alias add pif` 换个名字(见[安装](#命令名被别的程序占了macos-自带-usrbinpp)) |
|
|
381
410
|
|
|
382
411
|
## 开发
|
|
383
412
|
|
package/bin/pp.js
CHANGED
|
@@ -68,6 +68,9 @@ function parseArgs(argv) {
|
|
|
68
68
|
case "--wait": options.wait = Number(takeValue(flag, inline)) || 5000; break;
|
|
69
69
|
case "--no-wait": options.noWait = true; break;
|
|
70
70
|
case "--body-json": options.bodyJson = takeValue(flag, inline); break;
|
|
71
|
+
case "--bin-dir": options.binDir = takeValue(flag, inline); break;
|
|
72
|
+
case "--check": options.check = true; break;
|
|
73
|
+
case "--registry": options.registry = takeValue(flag, inline); break;
|
|
71
74
|
case "--reply": options.reply = Number(takeValue(flag, inline)) || 0; break;
|
|
72
75
|
case "--local": options.local = true; break;
|
|
73
76
|
case "--path": options.path = takeValue(flag, inline); break;
|
package/completions/_pp
CHANGED
|
@@ -16,12 +16,16 @@ _pp() {
|
|
|
16
16
|
'attach:attach to a session (starts it if needed)'
|
|
17
17
|
'logs:print pane output'
|
|
18
18
|
'send:type text into a pane'
|
|
19
|
-
'mesh:remote-pi mesh (ls/send/resolve)'
|
|
19
|
+
'mesh:remote-pi mesh (ls/send/resolve/inbox)'
|
|
20
20
|
'check:validate the config'
|
|
21
21
|
'doctor:environment diagnostics'
|
|
22
22
|
'init:write an example config'
|
|
23
23
|
'install:install reboot autostart'
|
|
24
24
|
'uninstall:remove autostart'
|
|
25
|
+
'update:upgrade to the newest published version'
|
|
26
|
+
'upgrade:alias for update'
|
|
27
|
+
'alias:add another command name (ls/add/rm)'
|
|
28
|
+
'link:alias for alias'
|
|
25
29
|
'version:print version'
|
|
26
30
|
'help:show help (help <command> for one command)'
|
|
27
31
|
)
|
|
@@ -51,6 +55,9 @@ _pp() {
|
|
|
51
55
|
'--reply[wait for a reply after the ACK]:ms:' \
|
|
52
56
|
'--no-wait[do not wait for the mesh ACK]' \
|
|
53
57
|
'--body-json[mesh body as JSON]:json:' \
|
|
58
|
+
'--bin-dir[directory for pp alias symlinks]:dir:_files -/' \
|
|
59
|
+
'--check[report only; exit 1 when an update is available]' \
|
|
60
|
+
'--registry[npm registry for pp update]:url:' \
|
|
54
61
|
'--watch[reconcile interval for install]:seconds:' \
|
|
55
62
|
'--print[print autostart unit and exit]' \
|
|
56
63
|
'1:command:->command' \
|
package/completions/pp.bash
CHANGED
|
@@ -4,7 +4,7 @@ _pp() {
|
|
|
4
4
|
COMPREPLY=()
|
|
5
5
|
cur="${COMP_WORDS[COMP_CWORD]}"
|
|
6
6
|
prev="${COMP_WORDS[COMP_CWORD-1]}"
|
|
7
|
-
local commands="new n create up start down stop restart status ls list attach a logs log send mesh check validate doctor init install autostart uninstall version help"
|
|
7
|
+
local commands="new n create up start down stop restart status ls list attach a logs log send mesh check validate doctor init install autostart uninstall alias link update upgrade version help"
|
|
8
8
|
|
|
9
9
|
case "$prev" in
|
|
10
10
|
-c|--config)
|
|
@@ -15,7 +15,11 @@ _pp() {
|
|
|
15
15
|
return 0
|
|
16
16
|
;;
|
|
17
17
|
mesh)
|
|
18
|
-
COMPREPLY=( $(compgen -W "ls list resolve send" -- "$cur") )
|
|
18
|
+
COMPREPLY=( $(compgen -W "ls list resolve send inbox listen watch" -- "$cur") )
|
|
19
|
+
return 0
|
|
20
|
+
;;
|
|
21
|
+
alias|link)
|
|
22
|
+
COMPREPLY=( $(compgen -W "ls list add create link rm remove delete unlink" -- "$cur") )
|
|
19
23
|
return 0
|
|
20
24
|
;;
|
|
21
25
|
attach|a|logs|log|send|down|stop|restart|up|start)
|
|
@@ -38,7 +42,7 @@ _pp() {
|
|
|
38
42
|
esac
|
|
39
43
|
|
|
40
44
|
if [[ "$cur" == -* ]]; then
|
|
41
|
-
COMPREPLY=( $(compgen -W "--config --socket --json --dry-run --force --reconcile --quiet --verbose --lines --watch --print --path --no-enter --attach --log --save --no-remote-pi --dir --agent --as --wait --reply --no-wait --body-json --help --version" -- "$cur") )
|
|
45
|
+
COMPREPLY=( $(compgen -W "--config --socket --json --dry-run --force --reconcile --quiet --verbose --lines --watch --print --path --no-enter --attach --log --save --no-remote-pi --dir --agent --as --wait --reply --no-wait --body-json --bin-dir --check --registry --help --version" -- "$cur") )
|
|
42
46
|
return 0
|
|
43
47
|
fi
|
|
44
48
|
if [[ $COMP_CWORD -eq 2 && "${COMP_WORDS[1]}" == "help" ]]; then
|
package/docs/architecture.md
CHANGED
|
@@ -20,8 +20,10 @@ src/remote-pi.js 读写 <cwd>/.pi/remote-pi/config.json,构造 REMOTE_PI_DIR
|
|
|
20
20
|
src/state.js 手动停止记录(XDG state),给 restart 策略用
|
|
21
21
|
src/mesh.js remote-pi broker 的零依赖客户端(探测 / 注册 / 发送 / ACK)
|
|
22
22
|
src/autostart.js systemd / launchd 单元渲染与安装/卸载/状态查询
|
|
23
|
-
src/commands.js 各子命令实现(up/down/restart/status/attach/logs/send/mesh/check/doctor/init/install/new)
|
|
23
|
+
src/commands.js 各子命令实现(up/down/restart/status/attach/logs/send/mesh/check/doctor/init/install/new/alias)
|
|
24
24
|
src/help.js COMMANDS 单一数据源 + 总览/单命令页/拼写建议
|
|
25
|
+
src/aliases.js 备用命令名(pifarm/pi-plus/自定义软链)+ PATH 上 pp 归属判定
|
|
26
|
+
src/update.js 自升级:安装方式判定(npm/git/unknown)、registry 版本查询、命令规划
|
|
25
27
|
src/example.js `pp init` 写入的示例配置
|
|
26
28
|
```
|
|
27
29
|
|
package/docs/cli.md
CHANGED
|
@@ -31,6 +31,9 @@ pp <command> [names...] [options]
|
|
|
31
31
|
| `--reply <ms>` | `mesh send` 收到 ACK 后继续监听回复的时长(单播收到第一条即返回) |
|
|
32
32
|
| `--no-wait` | `mesh send` 只发不等 ACK |
|
|
33
33
|
| `--body-json <json>` | `mesh send` 发结构化 JSON(默认发纯文本) |
|
|
34
|
+
| `--bin-dir <dir>` | `alias` 的软链目录,默认 `~/.local/bin` 或 `$PP_BIN_DIR` |
|
|
35
|
+
| `--check` | `update` 只报告:有新版时退出码 1 |
|
|
36
|
+
| `--registry <url>` | `update` 查询/安装用的 npm 源,默认 `https://registry.npmjs.org`(也可用 `$PP_NPM_REGISTRY`) |
|
|
34
37
|
| `--print` | `install` 只打印单元文件 |
|
|
35
38
|
| `--watch [secs]` | `install` 额外装一个定时器,每 N 秒(默认 300)巡检一次 |
|
|
36
39
|
| `-h, --help` | 帮助(`pp help`、`pp <cmd> --help` 等价) |
|
|
@@ -132,6 +135,43 @@ pp mesh send api --body-json '{"task":"test","id":42}' # 结构化消息
|
|
|
132
135
|
- 地址后缀 `#N` 是 broker 对同 `(cwd, name)` 重复身份的自动去重,`livePeersFor` 会把它一并算作同一个会话
|
|
133
136
|
- 跨机投递走 broker leader 的 relay 桥,发送端不需要做任何配对
|
|
134
137
|
|
|
138
|
+
### `pp update [--check]`
|
|
139
|
+
|
|
140
|
+
升级到最新发布版。先判断这份是从哪装的,再跑对应命令:
|
|
141
|
+
|
|
142
|
+
| 安装方式 | 判断依据 | 执行的命令 |
|
|
143
|
+
|---|---|---|
|
|
144
|
+
| npm 全局 | 脚本路径含 `node_modules/pi-farm/bin/pp.js` | `npm i -g pi-farm@<latest> --registry <url>` |
|
|
145
|
+
| git clone + `install.sh` | `<root>/bin/pp.js` 且 `<root>/.git` 存在 | `git -C <root> pull --ff-only` |
|
|
146
|
+
| 其它 | — | 不猜,打印手动升级提示并退出 1 |
|
|
147
|
+
|
|
148
|
+
```bash
|
|
149
|
+
pp update # 已是最新则什么都不做
|
|
150
|
+
pp update --check # 0=最新,1=有新版(会打印将要执行的命令),2=查不到
|
|
151
|
+
pp update --dry-run # 只打印命令
|
|
152
|
+
pp --json update --check
|
|
153
|
+
PP_NPM_REGISTRY=https://nexus.local/repository/npm-group pp update
|
|
154
|
+
```
|
|
155
|
+
|
|
156
|
+
升级不动配置文件、tmux 会话和自启单元——单元里的 ExecStart 指向安装路径,下次运行自然用新版。
|
|
157
|
+
|
|
158
|
+
### `pp alias [ls|add|rm]`
|
|
159
|
+
|
|
160
|
+
管理备用命令名。macOS 自带 `/usr/bin/pp`(ASN.1 工具),所以包内自带 `pifarm`、`pi-plus` 两个名字;`alias` 再加任意短名。
|
|
161
|
+
|
|
162
|
+
```bash
|
|
163
|
+
pp alias ls # 列出指向本 CLI 的软链 + 目录是否在 PATH
|
|
164
|
+
pp alias add pif # ~/.local/bin/pif → 本 CLI
|
|
165
|
+
pp alias add p --bin-dir /usr/local/bin
|
|
166
|
+
pp alias rm pif
|
|
167
|
+
pp alias ls --json
|
|
168
|
+
```
|
|
169
|
+
|
|
170
|
+
- 默认目录 `~/.local/bin`,可用 `$PP_BIN_DIR` 或 `--bin-dir` 覆盖;不在 PATH 时会提示怎么加
|
|
171
|
+
- 软链指向脚本本身,`npm i -g` 升级后别名自动跟随
|
|
172
|
+
- `add` 遇到同名**非软链**文件会拒绝(`--force` 才替换);`rm` 遇到指向别的程序的软链也会拒绝
|
|
173
|
+
- `pp doctor` 的 `command name` 行会写明哪个名字是我们的、哪个是别人的,以及装在 PATH 上那份的版本
|
|
174
|
+
|
|
135
175
|
### `pp check [name|#...]`
|
|
136
176
|
|
|
137
177
|
只校验配置,不碰 tmux。失败项进 stderr 并退出 1;`notes` 是提示(`restart: no`、手动停过、共享目录写同名等)。JSON:`{ "ok": true, "problems": [], "notes": [], "config": "..." }`。
|
package/docs/troubleshooting.md
CHANGED
|
@@ -2,6 +2,51 @@
|
|
|
2
2
|
|
|
3
3
|
按「你看到的原文」查。每条都附上验证命令。
|
|
4
4
|
|
|
5
|
+
## 命令名类
|
|
6
|
+
|
|
7
|
+
### 敲 `pp ls` 却打出 `Usage: pp [-t type] [-a] [-i input] ...`
|
|
8
|
+
|
|
9
|
+
那是 macOS(以及部分发行版)自带的 ASN.1 工具 `/usr/bin/pp`,不是我们。PATH 里谁靠前谁生效,而 `/usr/bin` 常常压过 npm 的全局 bin。
|
|
10
|
+
|
|
11
|
+
```bash
|
|
12
|
+
type -a pp # 看 PATH 上有几个 pp
|
|
13
|
+
pp doctor # 会直接写:ours: pp 0.3.0 (installed) / pp → /usr/bin/pp (not pi-plus)
|
|
14
|
+
pifarm ls # 安装时就带的备用名字(另一个是 pi-plus)
|
|
15
|
+
pp alias add pif # 自己起名字:~/.local/bin/pif → 同一个脚本
|
|
16
|
+
pp alias ls # 看已有别名 + 目录是否在 PATH
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
- 别名的默认目录是 `~/.local/bin`(可用 `--bin-dir` 或 `$PP_BIN_DIR` 改),它会提示该目录是否在 PATH 里
|
|
20
|
+
- `pp alias rm <name>` 只删指向本 CLI 的软链;指向别的东西会拒绝,交给你自己处理
|
|
21
|
+
- `install.sh` 也能一步换名:`PP_BIN_NAME=pifarm ./install.sh`,或 `PP_BIN_NAME="pp pif" ./install.sh`
|
|
22
|
+
|
|
23
|
+
### `error: ... is not a valid command name`
|
|
24
|
+
|
|
25
|
+
别名只接受 `[A-Za-z0-9._-]`,且不能以 `-` 开头(避免被当成 flag)。
|
|
26
|
+
|
|
27
|
+
## 升级类
|
|
28
|
+
|
|
29
|
+
### `pp update` 报 `notarget No matching version found`
|
|
30
|
+
|
|
31
|
+
npm 的 packument 缓存过期(刚发布时很常见):
|
|
32
|
+
|
|
33
|
+
```bash
|
|
34
|
+
npm cache clean --force
|
|
35
|
+
pp update
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
### `pp update` 报 `cannot reach https://registry.npmjs.org/pi-farm/latest`
|
|
39
|
+
|
|
40
|
+
内网拿不到公共源。换源即可,包只在 npmjs 上有:
|
|
41
|
+
|
|
42
|
+
```bash
|
|
43
|
+
PP_NPM_REGISTRY=https://nexus.inner.example.com/repository/npm-group pp update
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
### `pp update` 提示 `cannot tell how this copy was installed`
|
|
47
|
+
|
|
48
|
+
脚本既不在 `node_modules/pi-farm/` 下,也不在 git 检出里(比如被手工拷过)。按提示手动升级:`npm i -g pi-farm@latest`,或重新 `git clone` + `./install.sh`。
|
|
49
|
+
|
|
5
50
|
## 启动类
|
|
6
51
|
|
|
7
52
|
### `session "backend" exited immediately`
|
package/package.json
CHANGED
|
@@ -1,10 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-farm",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.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": {
|
|
7
|
-
"pp": "bin/pp.js"
|
|
7
|
+
"pp": "bin/pp.js",
|
|
8
|
+
"pifarm": "bin/pp.js",
|
|
9
|
+
"pi-plus": "bin/pp.js"
|
|
8
10
|
},
|
|
9
11
|
"files": [
|
|
10
12
|
"bin",
|
package/src/aliases.js
ADDED
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
// Alternate command names for people whose `pp` is already taken.
|
|
2
|
+
//
|
|
3
|
+
// macOS ships /usr/bin/pp (an ASN.1 pretty printer) and a few Linux distros
|
|
4
|
+
// do too, so `pp ls` can land on a binary that knows nothing about sessions.
|
|
5
|
+
// The package ships `pifarm` and `pi-plus` as well, and this module manages
|
|
6
|
+
// extra symlinks (pp alias add pif) plus the doctor check that notices when
|
|
7
|
+
// the name on PATH is not us.
|
|
8
|
+
import {
|
|
9
|
+
lstatSync,
|
|
10
|
+
readFileSync,
|
|
11
|
+
mkdirSync,
|
|
12
|
+
readdirSync,
|
|
13
|
+
readlinkSync,
|
|
14
|
+
realpathSync,
|
|
15
|
+
symlinkSync,
|
|
16
|
+
unlinkSync,
|
|
17
|
+
} from "node:fs";
|
|
18
|
+
import { homedir } from "node:os";
|
|
19
|
+
import { delimiter, dirname, join, resolve } from "node:path";
|
|
20
|
+
import { expandPath } from "./config.js";
|
|
21
|
+
import { resolveExecutable } from "./tmux.js";
|
|
22
|
+
|
|
23
|
+
const ALIAS_NAME_RE = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
|
|
24
|
+
|
|
25
|
+
/** Names `npm i -g pi-farm` / install.sh create without any extra work. */
|
|
26
|
+
export const BUILTIN_NAMES = ["pp", "pifarm", "pi-plus"];
|
|
27
|
+
|
|
28
|
+
export class AliasError extends Error {
|
|
29
|
+
constructor(message, code = "alias") {
|
|
30
|
+
super(message);
|
|
31
|
+
this.name = "AliasError";
|
|
32
|
+
this.code = code;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function aliasDir(env = process.env, override = null) {
|
|
37
|
+
if (override) return resolve(expandPath(override));
|
|
38
|
+
if (env.PP_BIN_DIR) return resolve(expandPath(env.PP_BIN_DIR));
|
|
39
|
+
return join(homedir(), ".local", "bin");
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export function assertAliasName(name) {
|
|
43
|
+
if (!name || name.startsWith("-")) {
|
|
44
|
+
throw new AliasError("alias name is required, e.g. pp alias add pif", "usage");
|
|
45
|
+
}
|
|
46
|
+
if (!ALIAS_NAME_RE.test(name) || name === "." || name === "..") {
|
|
47
|
+
throw new AliasError(
|
|
48
|
+
`"${name}" is not a valid command name; use letters, digits, "-", "_" and "."`,
|
|
49
|
+
"invalid_name",
|
|
50
|
+
);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function readlink(path) {
|
|
55
|
+
try {
|
|
56
|
+
return readlinkSync(path);
|
|
57
|
+
} catch {
|
|
58
|
+
return null;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export function sameTarget(linkPath, target) {
|
|
63
|
+
try {
|
|
64
|
+
return realpathSync(linkPath) === realpathSync(target);
|
|
65
|
+
} catch {
|
|
66
|
+
return false;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** `{name, path, symlink, target}` or null when nothing is there. */
|
|
71
|
+
export function readAlias(dir, name) {
|
|
72
|
+
const path = join(dir, name);
|
|
73
|
+
let stat;
|
|
74
|
+
try {
|
|
75
|
+
stat = lstatSync(path);
|
|
76
|
+
} catch {
|
|
77
|
+
return null;
|
|
78
|
+
}
|
|
79
|
+
const symlink = stat.isSymbolicLink();
|
|
80
|
+
return { name, path, symlink, target: symlink ? readlink(path) : null };
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export function listAliases({ dir, target }) {
|
|
84
|
+
let entries;
|
|
85
|
+
try {
|
|
86
|
+
entries = readdirSync(dir);
|
|
87
|
+
} catch {
|
|
88
|
+
return [];
|
|
89
|
+
}
|
|
90
|
+
const aliases = [];
|
|
91
|
+
for (const name of entries.sort()) {
|
|
92
|
+
const alias = readAlias(dir, name);
|
|
93
|
+
if (!alias?.symlink) continue;
|
|
94
|
+
if (target && !sameTarget(alias.path, target)) continue;
|
|
95
|
+
aliases.push(alias);
|
|
96
|
+
}
|
|
97
|
+
return aliases;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
export function addAlias(name, { dir, target, force = false }) {
|
|
101
|
+
assertAliasName(name);
|
|
102
|
+
const path = join(dir, name);
|
|
103
|
+
mkdirSync(dir, { recursive: true });
|
|
104
|
+
const existing = readAlias(dir, name);
|
|
105
|
+
if (existing && !existing.symlink && !force) {
|
|
106
|
+
throw new AliasError(`${path} already exists and is not a symlink (use --force to replace)`, "exists");
|
|
107
|
+
}
|
|
108
|
+
if (existing?.symlink && sameTarget(path, target)) return { path, changed: false };
|
|
109
|
+
if (existing) unlinkSync(path); // a symlink (re-point) or, with --force, a real file
|
|
110
|
+
symlinkSync(target, path);
|
|
111
|
+
return { path, changed: true };
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
export function removeAlias(name, { dir, target }) {
|
|
115
|
+
assertAliasName(name);
|
|
116
|
+
const path = join(dir, name);
|
|
117
|
+
const existing = readAlias(dir, name);
|
|
118
|
+
if (!existing) return false;
|
|
119
|
+
if (!existing.symlink) {
|
|
120
|
+
throw new AliasError(`${path} is not a symlink; remove it yourself`, "not_symlink");
|
|
121
|
+
}
|
|
122
|
+
if (target && !sameTarget(path, target)) {
|
|
123
|
+
throw new AliasError(`${path} points at ${existing.target}, not at ${target}; remove it yourself`, "foreign");
|
|
124
|
+
}
|
|
125
|
+
unlinkSync(path);
|
|
126
|
+
return true;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
export function dirOnPath(dir, env = process.env) {
|
|
130
|
+
const wanted = (() => {
|
|
131
|
+
try {
|
|
132
|
+
return realpathSync(dir);
|
|
133
|
+
} catch {
|
|
134
|
+
return dir;
|
|
135
|
+
}
|
|
136
|
+
})();
|
|
137
|
+
return String(env.PATH ?? "")
|
|
138
|
+
.split(delimiter)
|
|
139
|
+
.filter(Boolean)
|
|
140
|
+
.some((entry) => {
|
|
141
|
+
try {
|
|
142
|
+
return realpathSync(entry) === wanted;
|
|
143
|
+
} catch {
|
|
144
|
+
return entry === dir;
|
|
145
|
+
}
|
|
146
|
+
});
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
function installedVersion(realPath) {
|
|
150
|
+
try {
|
|
151
|
+
const manifest = JSON.parse(readFileSync(join(dirname(dirname(realPath)), "package.json"), "utf8"));
|
|
152
|
+
return typeof manifest.version === "string" ? manifest.version : null;
|
|
153
|
+
} catch {
|
|
154
|
+
return null;
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* Is `path` one of ours? `this` is the running script, `installed` is another
|
|
160
|
+
* copy of pi-farm (npm global, ~/.local/bin) — a dev checkout running the repo
|
|
161
|
+
* copy still owns the globally installed `pp`.
|
|
162
|
+
*/
|
|
163
|
+
export function installInfo(path, target) {
|
|
164
|
+
let real;
|
|
165
|
+
try {
|
|
166
|
+
real = realpathSync(path);
|
|
167
|
+
} catch {
|
|
168
|
+
return null;
|
|
169
|
+
}
|
|
170
|
+
const version = installedVersion(real);
|
|
171
|
+
if (sameTarget(path, target)) return { kind: "this", version };
|
|
172
|
+
if (/(^|\/)node_modules\/pi-farm\/bin\/pp(\.js)?$/.test(real)) return { kind: "installed", version };
|
|
173
|
+
return null;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/**
|
|
177
|
+
* Which of the shipped names point at *us*? A machine can have our `pifarm`
|
|
178
|
+
* on PATH and Apple's `pp` earlier in PATH at the same time.
|
|
179
|
+
*/
|
|
180
|
+
export function inspectCommandNames({ target, env = process.env, names = BUILTIN_NAMES }) {
|
|
181
|
+
const resolved = names.map((name) => {
|
|
182
|
+
const found = resolveExecutable(name, env);
|
|
183
|
+
const path = found && found.includes("/") ? found : null;
|
|
184
|
+
const info = path ? installInfo(path, target) : null;
|
|
185
|
+
return { name, path, ours: Boolean(info), kind: info?.kind ?? null, version: info?.version ?? null };
|
|
186
|
+
});
|
|
187
|
+
return { ok: resolved.some((entry) => entry.ours), names: resolved };
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
export function describeCommandNames(info) {
|
|
191
|
+
const ours = info.names.filter((entry) => entry.ours);
|
|
192
|
+
const foreign = info.names.filter((entry) => entry.path && !entry.ours);
|
|
193
|
+
const parts = [];
|
|
194
|
+
if (ours.length > 0) {
|
|
195
|
+
parts.push(
|
|
196
|
+
`ours: ${ours
|
|
197
|
+
.map((entry) => `${entry.name}${entry.version ? ` ${entry.version}` : ""}${entry.kind === "installed" ? " (installed)" : ""}`)
|
|
198
|
+
.join(", ")}`,
|
|
199
|
+
);
|
|
200
|
+
}
|
|
201
|
+
for (const entry of foreign) parts.push(`${entry.name} → ${entry.path} (not pi-plus)`);
|
|
202
|
+
if (parts.length === 0) return "not on PATH";
|
|
203
|
+
return parts.join("; ");
|
|
204
|
+
}
|
package/src/commands.js
CHANGED
|
@@ -13,6 +13,17 @@ import {
|
|
|
13
13
|
shellQuote,
|
|
14
14
|
} from "./config.js";
|
|
15
15
|
import { readRemotePiConfig, remotePiConfigPath, writeRemotePiName } from "./remote-pi.js";
|
|
16
|
+
import {
|
|
17
|
+
addAlias,
|
|
18
|
+
aliasDir,
|
|
19
|
+
BUILTIN_NAMES,
|
|
20
|
+
AliasError,
|
|
21
|
+
describeCommandNames,
|
|
22
|
+
dirOnPath,
|
|
23
|
+
inspectCommandNames,
|
|
24
|
+
listAliases,
|
|
25
|
+
removeAlias,
|
|
26
|
+
} from "./aliases.js";
|
|
16
27
|
import { resolveExecutable, Tmux } from "./tmux.js";
|
|
17
28
|
import {
|
|
18
29
|
installAutostart,
|
|
@@ -25,7 +36,26 @@ import {
|
|
|
25
36
|
systemdUserDir,
|
|
26
37
|
} from "./autostart.js";
|
|
27
38
|
import { clearStopped, isStopped, markStopped } from "./state.js";
|
|
28
|
-
import {
|
|
39
|
+
import {
|
|
40
|
+
compareVersions,
|
|
41
|
+
fetchLatestVersion,
|
|
42
|
+
installKind,
|
|
43
|
+
packageRoot,
|
|
44
|
+
planUpdate,
|
|
45
|
+
readManifest,
|
|
46
|
+
UpdateError,
|
|
47
|
+
} from "./update.js";
|
|
48
|
+
import { spawnSync } from "node:child_process";
|
|
49
|
+
import {
|
|
50
|
+
BROADCAST_TARGET,
|
|
51
|
+
connectPeer,
|
|
52
|
+
describeEnvelope,
|
|
53
|
+
livePeersFor,
|
|
54
|
+
MeshError,
|
|
55
|
+
peerPc,
|
|
56
|
+
probePeers,
|
|
57
|
+
sessionMeshAddress,
|
|
58
|
+
} from "./mesh.js";
|
|
29
59
|
import { findCommand, suggestCommand } from "./help.js";
|
|
30
60
|
import { EXAMPLE_CONFIG } from "./example.js";
|
|
31
61
|
|
|
@@ -573,6 +603,10 @@ async function cmdMesh(config, options, ui) {
|
|
|
573
603
|
case "resolve":
|
|
574
604
|
case "addr":
|
|
575
605
|
return cmdMeshResolve(config, { ...options, names: rest }, ui);
|
|
606
|
+
case "inbox":
|
|
607
|
+
case "listen":
|
|
608
|
+
case "watch":
|
|
609
|
+
return cmdMeshInbox(config, { ...options, names: rest }, ui);
|
|
576
610
|
default:
|
|
577
611
|
ui.error(`unknown mesh subcommand: ${sub}`);
|
|
578
612
|
return meshUsage(ui);
|
|
@@ -660,6 +694,70 @@ async function cmdMeshResolve(config, options, ui) {
|
|
|
660
694
|
}
|
|
661
695
|
}
|
|
662
696
|
|
|
697
|
+
async function cmdMeshInbox(config, options, ui) {
|
|
698
|
+
const name = options.as ?? "pp-inbox";
|
|
699
|
+
let peer;
|
|
700
|
+
try {
|
|
701
|
+
peer = await connectPeer({ name, cwd: options.cwd ?? process.cwd(), timeoutMs: options.wait ?? 5000 });
|
|
702
|
+
} catch (err) {
|
|
703
|
+
ui.error(err.message);
|
|
704
|
+
process.exit(1);
|
|
705
|
+
}
|
|
706
|
+
let received = 0;
|
|
707
|
+
let closing = false;
|
|
708
|
+
const leave = (reason) => {
|
|
709
|
+
if (closing) return;
|
|
710
|
+
closing = true;
|
|
711
|
+
try {
|
|
712
|
+
peer.close();
|
|
713
|
+
} catch {
|
|
714
|
+
/* socket already gone */
|
|
715
|
+
}
|
|
716
|
+
if (reason === "signal") {
|
|
717
|
+
if (!ui.json) ui.info(`left the mesh as ${peer.address} (${received} message(s))`);
|
|
718
|
+
process.exit(0);
|
|
719
|
+
}
|
|
720
|
+
};
|
|
721
|
+
const onBrokerFrame = (envelope) => {
|
|
722
|
+
if (!ui.verbose) return;
|
|
723
|
+
const event = envelope?.body ?? {};
|
|
724
|
+
ui.out(ui.paint("dim", `${event.type ?? "event"}: ${event.address ?? event.name ?? "?"}`));
|
|
725
|
+
};
|
|
726
|
+
peer.onMessage((envelope) => {
|
|
727
|
+
// The broker pushes its own lifecycle events as envelopes from "broker"
|
|
728
|
+
// (peer_joined / peer_left); they are not messages for us.
|
|
729
|
+
const eventType = envelope?.body?.type;
|
|
730
|
+
if (envelope?.from === "broker" || eventType === "peer_joined" || eventType === "peer_left") {
|
|
731
|
+
onBrokerFrame(envelope);
|
|
732
|
+
return;
|
|
733
|
+
}
|
|
734
|
+
if (!envelope || eventType === "ack") return; // ACKs belong to senders
|
|
735
|
+
received += 1;
|
|
736
|
+
const message = describeEnvelope(envelope);
|
|
737
|
+
if (ui.json) {
|
|
738
|
+
ui.out(JSON.stringify(message));
|
|
739
|
+
return;
|
|
740
|
+
}
|
|
741
|
+
const header = message.re ? `from ${message.from} re=${message.re}` : `from ${message.from}`;
|
|
742
|
+
ui.out(`${ui.paint("green", header)}`);
|
|
743
|
+
for (const line of message.body.split("\n")) ui.out(` ${line}`);
|
|
744
|
+
});
|
|
745
|
+
for (const signal of ["SIGINT", "SIGTERM"]) process.on(signal, () => leave("signal"));
|
|
746
|
+
peer.socket.on("close", () => {
|
|
747
|
+
if (closing) return;
|
|
748
|
+
ui.error(`mesh connection closed by the broker (was ${peer.address})`);
|
|
749
|
+
process.exitCode = 1;
|
|
750
|
+
process.exit(1);
|
|
751
|
+
});
|
|
752
|
+
if (!ui.json) {
|
|
753
|
+
const where = config?.path ? ` config: ${config.path}` : "";
|
|
754
|
+
ui.out(`${ui.paint("green", `listening as ${peer.address}`)}${where}`);
|
|
755
|
+
ui.out(ui.paint("dim", "Ctrl-C to leave; messages are printed as they arrive"));
|
|
756
|
+
}
|
|
757
|
+
// keep the process alive while the socket is open
|
|
758
|
+
await new Promise(() => {});
|
|
759
|
+
}
|
|
760
|
+
|
|
663
761
|
async function cmdMeshSend(config, options, ui) {
|
|
664
762
|
const hasBodyJson = options.bodyJson !== undefined;
|
|
665
763
|
if (options.names.length < (hasBodyJson ? 1 : 2)) {
|
|
@@ -923,6 +1021,8 @@ function cmdDoctor(config, options, ui) {
|
|
|
923
1021
|
// A missing server is normal (tmux starts on demand) — not a failure.
|
|
924
1022
|
add("tmux server", true, hasServer ? "running" : "not running (starts on demand)");
|
|
925
1023
|
add("pi", commandExists("pi"), resolveExecutable("pi"));
|
|
1024
|
+
const names = inspectCommandNames({ target: scriptPath(options) });
|
|
1025
|
+
add("command name", names.ok, describeCommandNames(names));
|
|
926
1026
|
add("config", Boolean(config), config?.path ?? "not found");
|
|
927
1027
|
const autostart = autostartState();
|
|
928
1028
|
add("autostart", Boolean(autostart.kind) && autostart.installed && autostart.enabled, describeAutostart(autostart));
|
|
@@ -940,6 +1040,12 @@ function cmdDoctor(config, options, ui) {
|
|
|
940
1040
|
ui.out(`${mark} ${check.label.padEnd(14)} ${ui.paint("dim", check.detail ?? "")}`);
|
|
941
1041
|
}
|
|
942
1042
|
if (!config) ui.out(`\n${ui.paint("dim", "hint:")} no config found; run pp init`);
|
|
1043
|
+
if (!names.ok) {
|
|
1044
|
+
ui.out(
|
|
1045
|
+
`${ui.paint("dim", "hint:")} another program owns the name on PATH; pick one with ` +
|
|
1046
|
+
`pp alias add pif (or use pifarm / pi-plus) — see pp help alias`,
|
|
1047
|
+
);
|
|
1048
|
+
}
|
|
943
1049
|
if (autostart.kind === "systemd") {
|
|
944
1050
|
ui.out(`\n${ui.paint("dim", "systemd unit dir:")} ${systemdUserDir()}`);
|
|
945
1051
|
ui.out(`${ui.paint("dim", "hint:")} systemctl --user status pi-plus`);
|
|
@@ -970,15 +1076,19 @@ function cmdInit(options, ui) {
|
|
|
970
1076
|
ui.info(`start with: pp up --config ${target}`);
|
|
971
1077
|
}
|
|
972
1078
|
|
|
1079
|
+
function scriptPath(options = {}) {
|
|
1080
|
+
return options.scriptPath ?? resolve(process.argv[1]);
|
|
1081
|
+
}
|
|
1082
|
+
|
|
973
1083
|
function cmdInstall(config, options, ui) {
|
|
974
|
-
const
|
|
1084
|
+
const scriptPath_ = scriptPath(options);
|
|
975
1085
|
const watch = options.watch === true ? 300 : Number(options.watch) || 0;
|
|
976
1086
|
if (options.watch !== undefined && watch < 30) {
|
|
977
1087
|
ui.error("--watch interval must be at least 30 seconds");
|
|
978
1088
|
process.exit(2);
|
|
979
1089
|
}
|
|
980
1090
|
const result = installAutostart({
|
|
981
|
-
scriptPath,
|
|
1091
|
+
scriptPath: scriptPath_,
|
|
982
1092
|
configPath: config.path,
|
|
983
1093
|
watch,
|
|
984
1094
|
print: options.print,
|
|
@@ -1025,6 +1135,175 @@ function cmdUninstall(options, ui) {
|
|
|
1025
1135
|
ui.info(`removed ${result.removed.join(", ")}`);
|
|
1026
1136
|
}
|
|
1027
1137
|
|
|
1138
|
+
async function cmdUpdate(options, ui) {
|
|
1139
|
+
const current = readManifest(packageRoot()).version;
|
|
1140
|
+
const info = installKind(scriptPath(options));
|
|
1141
|
+
const registry = options.registry ?? process.env.PP_NPM_REGISTRY ?? undefined;
|
|
1142
|
+
|
|
1143
|
+
let latest = null;
|
|
1144
|
+
try {
|
|
1145
|
+
latest = await fetchLatestVersion(registry ? { registry } : undefined);
|
|
1146
|
+
} catch (error) {
|
|
1147
|
+
if (!(error instanceof UpdateError)) throw error;
|
|
1148
|
+
if (ui.json) ui.out(JSON.stringify({ current, latest: null, error: error.message }, null, 2));
|
|
1149
|
+
else ui.error(error.message);
|
|
1150
|
+
if (options.json) return;
|
|
1151
|
+
ui.info(ui.paint("dim", "hint: upgrade by hand: npm i -g pi-farm@latest"));
|
|
1152
|
+
process.exit(2);
|
|
1153
|
+
}
|
|
1154
|
+
|
|
1155
|
+
const behind = compareVersions(latest, current) > 0;
|
|
1156
|
+
const plan = planUpdate({
|
|
1157
|
+
kind: info.kind,
|
|
1158
|
+
currentVersion: current,
|
|
1159
|
+
latestVersion: latest,
|
|
1160
|
+
registry: registry ?? "https://registry.npmjs.org",
|
|
1161
|
+
root: info.root,
|
|
1162
|
+
path: info.path,
|
|
1163
|
+
});
|
|
1164
|
+
|
|
1165
|
+
if (options.json) {
|
|
1166
|
+
ui.out(
|
|
1167
|
+
JSON.stringify(
|
|
1168
|
+
{ current, latest, upToDate: !behind, installKind: info.kind, command: plan ? [plan.command, ...plan.args] : null },
|
|
1169
|
+
null,
|
|
1170
|
+
2,
|
|
1171
|
+
),
|
|
1172
|
+
);
|
|
1173
|
+
process.exitCode = behind ? 1 : 0;
|
|
1174
|
+
return;
|
|
1175
|
+
}
|
|
1176
|
+
|
|
1177
|
+
if (!behind) {
|
|
1178
|
+
ui.info(`pi-farm ${current} is up to date (latest ${latest})`);
|
|
1179
|
+
return;
|
|
1180
|
+
}
|
|
1181
|
+
ui.info(`update available: ${current} → ${latest} (${info.kind} install)`);
|
|
1182
|
+
if (!plan) {
|
|
1183
|
+
ui.error(`cannot tell how this copy was installed (${info.path})`);
|
|
1184
|
+
ui.info(ui.paint("dim", `upgrade by hand: npm i -g ${"pi-farm"}@${latest}`));
|
|
1185
|
+
process.exit(1);
|
|
1186
|
+
}
|
|
1187
|
+
const line = [plan.command, ...plan.args].join(" ");
|
|
1188
|
+
if (plan.note) ui.info(ui.paint("dim", `note: ${plan.note}`));
|
|
1189
|
+
|
|
1190
|
+
if (options.check) {
|
|
1191
|
+
ui.info(ui.paint("dim", `would run: ${line}`));
|
|
1192
|
+
process.exitCode = 1; // 1 = "an update is available", handy for scripts
|
|
1193
|
+
return;
|
|
1194
|
+
}
|
|
1195
|
+
if (options.dryRun) {
|
|
1196
|
+
ui.info(`[dry-run] ${line}`);
|
|
1197
|
+
return;
|
|
1198
|
+
}
|
|
1199
|
+
|
|
1200
|
+
ui.info(ui.paint("dim", `$ ${line}`));
|
|
1201
|
+
const result = spawnSync(plan.command, plan.args, { stdio: "inherit", cwd: plan.cwd ?? process.cwd() });
|
|
1202
|
+
if (result.error) {
|
|
1203
|
+
ui.error(`failed to run ${plan.command}: ${result.error.message}`);
|
|
1204
|
+
process.exit(1);
|
|
1205
|
+
}
|
|
1206
|
+
if (plan.kind === "git") {
|
|
1207
|
+
// A checkout upgraded in place: the running process is still the old code.
|
|
1208
|
+
ui.info(`pulled; restart pp to use ${latest}`);
|
|
1209
|
+
return;
|
|
1210
|
+
}
|
|
1211
|
+
const after = readManifest(packageRoot()).version;
|
|
1212
|
+
if (compareVersions(after, latest) >= 0) ui.info(`now pi-farm ${after}`);
|
|
1213
|
+
else if (result.status === 0) {
|
|
1214
|
+
ui.error(`npm finished but this copy is still ${after} (another pi-farm may shadow it: type -a pp)`);
|
|
1215
|
+
process.exitCode = 1;
|
|
1216
|
+
} else {
|
|
1217
|
+
process.exitCode = result.status ?? 1;
|
|
1218
|
+
}
|
|
1219
|
+
}
|
|
1220
|
+
|
|
1221
|
+
function cmdAlias(config, options, ui) {
|
|
1222
|
+
const sub = options.names[0] ?? "ls";
|
|
1223
|
+
const rest = options.names.slice(1);
|
|
1224
|
+
const target = scriptPath(options);
|
|
1225
|
+
const dir = aliasDir(process.env, options.binDir);
|
|
1226
|
+
const onPath = dirOnPath(dir);
|
|
1227
|
+
|
|
1228
|
+
const show = (payload) => {
|
|
1229
|
+
if (ui.json) {
|
|
1230
|
+
ui.out(JSON.stringify(payload, null, 2));
|
|
1231
|
+
return true;
|
|
1232
|
+
}
|
|
1233
|
+
return false;
|
|
1234
|
+
};
|
|
1235
|
+
|
|
1236
|
+
try {
|
|
1237
|
+
switch (sub) {
|
|
1238
|
+
case "ls":
|
|
1239
|
+
case "list": {
|
|
1240
|
+
const aliases = listAliases({ dir, target });
|
|
1241
|
+
if (show({ dir, onPath, aliases })) return;
|
|
1242
|
+
if (aliases.length === 0) {
|
|
1243
|
+
ui.out(`no aliases in ${dir}`);
|
|
1244
|
+
} else {
|
|
1245
|
+
for (const alias of aliases) {
|
|
1246
|
+
ui.out(`${ui.paint("bold", alias.name.padEnd(12))} ${ui.paint("dim", alias.path)}`);
|
|
1247
|
+
}
|
|
1248
|
+
}
|
|
1249
|
+
ui.out(
|
|
1250
|
+
ui.paint(
|
|
1251
|
+
"dim",
|
|
1252
|
+
`${onPath ? "" : `note: ${dir} is not on PATH; `}built in: ${BUILTIN_NAMES.join(", ")}`,
|
|
1253
|
+
),
|
|
1254
|
+
);
|
|
1255
|
+
ui.out(ui.paint("dim", "add one with: pp alias add pif"));
|
|
1256
|
+
return;
|
|
1257
|
+
}
|
|
1258
|
+
case "add":
|
|
1259
|
+
case "create":
|
|
1260
|
+
case "link": {
|
|
1261
|
+
const name = rest[0];
|
|
1262
|
+
assertAliasNameSafe(name);
|
|
1263
|
+
const result = addAlias(name, { dir, target, force: options.force });
|
|
1264
|
+
if (show({ ...result, dir, onPath })) return;
|
|
1265
|
+
ui.info(`${result.changed ? "linked" : "already linked"} ${result.path} → ${target}`);
|
|
1266
|
+
if (!onPath) {
|
|
1267
|
+
ui.info(ui.paint("yellow", `note: ${dir} is not on PATH; add it, e.g. export PATH="${dir}:$PATH"`));
|
|
1268
|
+
}
|
|
1269
|
+
ui.info(ui.paint("dim", `try: ${name} ls`));
|
|
1270
|
+
return;
|
|
1271
|
+
}
|
|
1272
|
+
case "rm":
|
|
1273
|
+
case "remove":
|
|
1274
|
+
case "delete":
|
|
1275
|
+
case "unlink": {
|
|
1276
|
+
const name = rest[0];
|
|
1277
|
+
assertAliasNameSafe(name);
|
|
1278
|
+
const removed = removeAlias(name, { dir, target });
|
|
1279
|
+
if (show({ name, removed, dir })) return;
|
|
1280
|
+
if (!removed) {
|
|
1281
|
+
ui.info(`nothing to remove at ${join(dir, name)}`);
|
|
1282
|
+
return;
|
|
1283
|
+
}
|
|
1284
|
+
ui.info(`removed ${join(dir, name)}`);
|
|
1285
|
+
return;
|
|
1286
|
+
}
|
|
1287
|
+
default:
|
|
1288
|
+
ui.error(`unknown alias subcommand: ${sub}`);
|
|
1289
|
+
ui.error("usage: pp alias [ls | add <name> | rm <name>] [--bin-dir <dir>]");
|
|
1290
|
+
process.exit(2);
|
|
1291
|
+
}
|
|
1292
|
+
} catch (err) {
|
|
1293
|
+
if (err instanceof AliasError) {
|
|
1294
|
+
ui.error(err.message);
|
|
1295
|
+
process.exit(err.code === "usage" ? 2 : 1);
|
|
1296
|
+
}
|
|
1297
|
+
throw err;
|
|
1298
|
+
}
|
|
1299
|
+
}
|
|
1300
|
+
|
|
1301
|
+
function assertAliasNameSafe(name) {
|
|
1302
|
+
if (!name) {
|
|
1303
|
+
throw new AliasError("alias name is required, e.g. pp alias add pif", "usage");
|
|
1304
|
+
}
|
|
1305
|
+
}
|
|
1306
|
+
|
|
1028
1307
|
export async function runCommand(command, options) {
|
|
1029
1308
|
const ui = makeUi(options);
|
|
1030
1309
|
if (options.json) ui.quiet = true;
|
|
@@ -1109,6 +1388,14 @@ export async function runCommand(command, options) {
|
|
|
1109
1388
|
const config = requireConfig(options, ui);
|
|
1110
1389
|
return cmdInstall(config, options, ui);
|
|
1111
1390
|
}
|
|
1391
|
+
case "update":
|
|
1392
|
+
case "upgrade": {
|
|
1393
|
+
return cmdUpdate(options, ui);
|
|
1394
|
+
}
|
|
1395
|
+
case "alias":
|
|
1396
|
+
case "link": {
|
|
1397
|
+
return cmdAlias(null, options, ui); // aliasing does not need a config
|
|
1398
|
+
}
|
|
1112
1399
|
case "uninstall": {
|
|
1113
1400
|
return cmdUninstall(options, ui);
|
|
1114
1401
|
}
|
package/src/help.js
CHANGED
|
@@ -157,8 +157,8 @@ export const COMMANDS = [
|
|
|
157
157
|
{
|
|
158
158
|
name: "mesh",
|
|
159
159
|
aliases: [],
|
|
160
|
-
summary: "Talk to the remote-pi agent mesh (ls / send / resolve)",
|
|
161
|
-
usage: "pp mesh <ls|send|resolve> ...",
|
|
160
|
+
summary: "Talk to the remote-pi agent mesh (ls / send / resolve / inbox)",
|
|
161
|
+
usage: "pp mesh <ls|send|resolve|inbox> ...",
|
|
162
162
|
details: [
|
|
163
163
|
"pp talks to remote-pi's local broker directly over its UNIX socket",
|
|
164
164
|
"(~/.pi/remote/sessions/local/broker.sock) — no dependencies, no pi needed.",
|
|
@@ -168,6 +168,8 @@ export const COMMANDS = [
|
|
|
168
168
|
" resolve map a configured session to its mesh address and online state",
|
|
169
169
|
" send register as an ephemeral peer (default name pp-mesh), deliver the",
|
|
170
170
|
" text, and wait for the broker ACK",
|
|
171
|
+
" inbox register and stay online, printing every message that arrives",
|
|
172
|
+
" (default name pp-inbox; Ctrl-C to leave)",
|
|
171
173
|
"",
|
|
172
174
|
"Targets may be a session name or #index (resolved through the config), a raw",
|
|
173
175
|
"mesh address (<cwd>@<name>, or macbook:/path@name for cross-PC), `all`, or",
|
|
@@ -178,8 +180,8 @@ export const COMMANDS = [
|
|
|
178
180
|
"Cross-PC delivery rides the broker leader's relay bridge, so no pairing.",
|
|
179
181
|
].join("\n"),
|
|
180
182
|
options: [
|
|
181
|
-
"--json JSON output (ls/resolve)",
|
|
182
|
-
"--as <name> mesh name to register as (default: pp-mesh)",
|
|
183
|
+
"--json JSON output (ls/resolve; one JSON object per line for inbox)",
|
|
184
|
+
"--as <name> mesh name to register as (default: pp-mesh / pp-inbox)",
|
|
183
185
|
"--wait <ms> ACK timeout, default 5000",
|
|
184
186
|
"--no-wait fire-and-forget: do not wait for the ACK",
|
|
185
187
|
"--reply <ms> keep listening after the ACK and print the reply envelope(s)",
|
|
@@ -193,6 +195,8 @@ export const COMMANDS = [
|
|
|
193
195
|
'pp mesh send 1 3 "heads up: rebooting the box"',
|
|
194
196
|
'pp mesh send all "standup in 5"',
|
|
195
197
|
"pp mesh send macbook:/Users/me/code/api@api \"ping\" --wait 2000",
|
|
198
|
+
"pp mesh inbox --as pp-worker",
|
|
199
|
+
"pp mesh inbox --json --as pp-worker | tee mesh.jsonl",
|
|
196
200
|
],
|
|
197
201
|
see: ["send", "status"],
|
|
198
202
|
},
|
|
@@ -264,6 +268,56 @@ export const COMMANDS = [
|
|
|
264
268
|
examples: ["pp uninstall"],
|
|
265
269
|
see: ["install"],
|
|
266
270
|
},
|
|
271
|
+
{
|
|
272
|
+
name: "update",
|
|
273
|
+
aliases: ["upgrade"],
|
|
274
|
+
summary: "Upgrade this install to the newest published version",
|
|
275
|
+
usage: "pp update [--check] [--dry-run] [--registry <url>]",
|
|
276
|
+
details: [
|
|
277
|
+
"Asks the registry for the newest version and upgrades whichever way this copy was installed: an npm global install runs `npm i -g pi-farm@<latest>`, a git checkout (install.sh) runs `git pull --ff-only`.",
|
|
278
|
+
"Nothing runs when you are already current. `--check` only reports and exits 1 when an update exists, which makes it usable from a script or a cron job.",
|
|
279
|
+
"The version check needs network access; set PP_NPM_REGISTRY or --registry when the default https://registry.npmjs.org is not reachable.",
|
|
280
|
+
"Upgrading does not touch your config, your sessions or the autostart unit — the unit points at the installed script, so it picks up the new version on the next run.",
|
|
281
|
+
].join("\n"),
|
|
282
|
+
options: [
|
|
283
|
+
"--check report only; exit 1 when an update is available",
|
|
284
|
+
"--dry-run print the upgrade command without running it",
|
|
285
|
+
"--registry <url> registry to ask (default https://registry.npmjs.org)",
|
|
286
|
+
"--json machine-readable output",
|
|
287
|
+
],
|
|
288
|
+
examples: [
|
|
289
|
+
"pp update",
|
|
290
|
+
"pp update --check",
|
|
291
|
+
"pp update --dry-run",
|
|
292
|
+
"PP_NPM_REGISTRY=https://nexus.local/repository/npm-group pp update",
|
|
293
|
+
],
|
|
294
|
+
see: ["version", "doctor"],
|
|
295
|
+
},
|
|
296
|
+
{
|
|
297
|
+
name: "alias",
|
|
298
|
+
aliases: ["link"],
|
|
299
|
+
summary: "Add another command name when `pp` is taken by another program",
|
|
300
|
+
usage: "pp alias [ls | add <name> | rm <name>] [--bin-dir <dir>]",
|
|
301
|
+
details: [
|
|
302
|
+
"macOS ships /usr/bin/pp (an ASN.1 pretty printer) and a few Linux distros do too, so typing `pp ls` can reach a binary that knows nothing about sessions. npm already installs two extra names for this reason: `pifarm` and `pi-plus`.",
|
|
303
|
+
"`pp alias add <name>` puts a symlink to this CLI into a bin directory that is on PATH, so any short name you like works: pp alias add pif → pif ls.",
|
|
304
|
+
"Default directory: ~/.local/bin, or $PP_BIN_DIR; `--bin-dir` overrides it for one call. The symlink points at this script, so upgrading through npm keeps the alias valid.",
|
|
305
|
+
"`pp alias rm <name>` removes only symlinks that point at this CLI; anything else is left alone (delete it yourself).",
|
|
306
|
+
"pp doctor reports which names resolve to us and which belong to another program.",
|
|
307
|
+
].join("\n"),
|
|
308
|
+
options: [
|
|
309
|
+
"--bin-dir <dir> directory to link into (default ~/.local/bin)",
|
|
310
|
+
"--force replace an existing non-symlink file",
|
|
311
|
+
"--json machine-readable output",
|
|
312
|
+
],
|
|
313
|
+
examples: [
|
|
314
|
+
"pp alias ls",
|
|
315
|
+
"pp alias add pif",
|
|
316
|
+
"pp alias add p --bin-dir /usr/local/bin",
|
|
317
|
+
"pp alias rm pif",
|
|
318
|
+
],
|
|
319
|
+
see: ["doctor", "install"],
|
|
320
|
+
},
|
|
267
321
|
{
|
|
268
322
|
name: "version",
|
|
269
323
|
summary: "Print the version",
|
package/src/mesh.js
CHANGED
|
@@ -50,6 +50,21 @@ export function sessionMeshAddress(session) {
|
|
|
50
50
|
* two agents in the same directory ask for the same name, so an exact match is
|
|
51
51
|
* not enough.
|
|
52
52
|
*/
|
|
53
|
+
/**
|
|
54
|
+
* Normalise an inbound envelope for display: remote-pi renders string bodies
|
|
55
|
+
* verbatim and JSON-stringifies everything else, so we do the same.
|
|
56
|
+
*/
|
|
57
|
+
export function describeEnvelope(envelope) {
|
|
58
|
+
const body =
|
|
59
|
+
typeof envelope?.body === "string" ? envelope.body : JSON.stringify(envelope?.body ?? null);
|
|
60
|
+
return {
|
|
61
|
+
from: typeof envelope?.from === "string" ? envelope.from : "unknown",
|
|
62
|
+
re: typeof envelope?.re === "string" ? envelope.re : null,
|
|
63
|
+
id: typeof envelope?.id === "string" ? envelope.id : null,
|
|
64
|
+
body,
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
|
|
53
68
|
export function livePeersFor(peers, address) {
|
|
54
69
|
if (!address) return [];
|
|
55
70
|
return peers.filter((peer) => peer === address || peer.startsWith(`${address}#`));
|
package/src/update.js
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
// Self-update support for `pp update`.
|
|
2
|
+
//
|
|
3
|
+
// The CLI is distributed three ways (npm global, `install.sh` symlink into a
|
|
4
|
+
// git checkout, and `node bin/pp.js` from a checkout). Each one is upgraded
|
|
5
|
+
// differently, so first figure out *how* this copy was installed, then ask the
|
|
6
|
+
// registry what the newest version is, then run the matching command.
|
|
7
|
+
import { existsSync, readFileSync, realpathSync } from "node:fs";
|
|
8
|
+
import { dirname, join, resolve } from "node:path";
|
|
9
|
+
import { fileURLToPath } from "node:url";
|
|
10
|
+
|
|
11
|
+
export const PACKAGE_NAME = "pi-farm";
|
|
12
|
+
export const DEFAULT_REGISTRY = "https://registry.npmjs.org";
|
|
13
|
+
|
|
14
|
+
export class UpdateError extends Error {
|
|
15
|
+
constructor(message, code = "update") {
|
|
16
|
+
super(message);
|
|
17
|
+
this.name = "UpdateError";
|
|
18
|
+
this.code = code;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** `<repo|node_modules>/pi-farm` — the directory holding this package.json. */
|
|
23
|
+
export function packageRoot(from = import.meta.url) {
|
|
24
|
+
return resolve(dirname(fileURLToPath(from)), "..");
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function readManifest(root = packageRoot()) {
|
|
28
|
+
return JSON.parse(readFileSync(join(root, "package.json"), "utf8"));
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Numeric-aware compare; returns -1, 0 or 1. Pre-release tags are ignored. */
|
|
32
|
+
export function compareVersions(a, b) {
|
|
33
|
+
const parse = (value) =>
|
|
34
|
+
String(value ?? "")
|
|
35
|
+
.split("-")[0]
|
|
36
|
+
.split(".")
|
|
37
|
+
.map((part) => Number.parseInt(part, 10) || 0);
|
|
38
|
+
const left = parse(a);
|
|
39
|
+
const right = parse(b);
|
|
40
|
+
for (let index = 0; index < Math.max(left.length, right.length); index += 1) {
|
|
41
|
+
const one = left[index] ?? 0;
|
|
42
|
+
const other = right[index] ?? 0;
|
|
43
|
+
if (one > other) return 1;
|
|
44
|
+
if (one < other) return -1;
|
|
45
|
+
}
|
|
46
|
+
return 0;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export async function fetchLatestVersion({ registry = DEFAULT_REGISTRY, timeoutMs = 8000 } = {}) {
|
|
50
|
+
const url = `${String(registry).replace(/\/+$/, "")}/${PACKAGE_NAME}/latest`;
|
|
51
|
+
const controller = new AbortController();
|
|
52
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
53
|
+
try {
|
|
54
|
+
const response = await fetch(url, { signal: controller.signal, headers: { accept: "application/json" } });
|
|
55
|
+
if (!response.ok) throw new UpdateError(`registry answered HTTP ${response.status} for ${url}`);
|
|
56
|
+
const body = await response.json();
|
|
57
|
+
if (!body || typeof body.version !== "string") throw new UpdateError(`no version field in ${url}`);
|
|
58
|
+
return body.version;
|
|
59
|
+
} catch (error) {
|
|
60
|
+
if (error instanceof UpdateError) throw error;
|
|
61
|
+
const reason = error?.name === "AbortError" ? `timeout after ${timeoutMs}ms` : error?.message ?? String(error);
|
|
62
|
+
throw new UpdateError(`cannot reach ${url} (${reason})`, "offline");
|
|
63
|
+
} finally {
|
|
64
|
+
clearTimeout(timer);
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* How was this copy installed?
|
|
70
|
+
* npm — <prefix>/lib/node_modules/pi-farm/bin/pp.js
|
|
71
|
+
* git — a checkout that `install.sh` symlinked (has .git next to bin/)
|
|
72
|
+
* unknown — anything else; the user has to upgrade by hand
|
|
73
|
+
*/
|
|
74
|
+
export function installKind(scriptPath, { exists = existsSync } = {}) {
|
|
75
|
+
let real = scriptPath;
|
|
76
|
+
try {
|
|
77
|
+
real = realpathSync(scriptPath);
|
|
78
|
+
} catch {
|
|
79
|
+
/* keep the given path */
|
|
80
|
+
}
|
|
81
|
+
if (/[\\/]node_modules[\\/]pi-farm[\\/]bin[\\/]pp\.js$/.test(real)) return { kind: "npm", path: real };
|
|
82
|
+
const root = dirname(dirname(real));
|
|
83
|
+
if (exists(join(root, ".git")) && exists(join(root, "package.json"))) return { kind: "git", path: real, root };
|
|
84
|
+
return { kind: "unknown", path: real };
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export function isHomebrewPath(scriptPath) {
|
|
88
|
+
return /[\\/](Cellar|homebrew|linuxbrew)[\\/]/.test(String(scriptPath));
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** The command that upgrades this copy, or null when we cannot know. */
|
|
92
|
+
export function planUpdate({ kind, currentVersion, latestVersion, registry = DEFAULT_REGISTRY, root, path }) {
|
|
93
|
+
if (kind === "npm") {
|
|
94
|
+
return {
|
|
95
|
+
kind,
|
|
96
|
+
command: "npm",
|
|
97
|
+
args: ["i", "-g", `${PACKAGE_NAME}@${latestVersion}`, "--registry", registry],
|
|
98
|
+
cwd: undefined,
|
|
99
|
+
note: isHomebrewPath(path) ? "this copy looks Homebrew-managed; brew upgrade may be the right move" : undefined,
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
if (kind === "git") {
|
|
103
|
+
return { kind, command: "git", args: ["-C", root, "pull", "--ff-only"], cwd: root };
|
|
104
|
+
}
|
|
105
|
+
return null;
|
|
106
|
+
}
|