pi-farm 0.2.2 → 0.3.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.
@@ -0,0 +1,226 @@
1
+ # 排障手册
2
+
3
+ 按「你看到的原文」查。每条都附上验证命令。
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
+ ### `session "backend" exited immediately`
30
+
31
+ ```
32
+ error: session "backend" exited immediately
33
+ [backend] ...(pane 最后几行输出)
34
+ ```
35
+
36
+ `pp up` 在创建会话 600ms 后会检查 pane 是否还活着,死了就把截到的输出打出来。常见原因依次排查:
37
+
38
+ ```bash
39
+ pp up backend -v --dry-run # ① 打印真实 argv,确认 agent/参数/目录
40
+ pp check backend # ② cwd 是否存在、agent 是否在 PATH
41
+ ```
42
+
43
+ - **agent 不在 PATH 上**:systemd/非交互 shell 的 PATH 很短。用绝对路径:`agent: /home/you/.nvm/versions/node/v26.13.1/bin/pi`
44
+ - **pi 参数不合法**:例如 `pi_session` 里有大写以外非法字符,或 `pi_session_dir` 指向不可写的目录。pi 会直接退出
45
+ - **cwd 不存在**:`cwd does not exist: /path`
46
+ - 想看到完整报错:临时加 `remain_on_exit: true`,然后 `pp logs backend -n 200`
47
+
48
+ ### `cwd does not exist: /home/you/code/backend`
49
+
50
+ 配置文件里的目录在这台机器上不存在(典型:`pp init` 生成的模板)。改 `cwd` 或先 `mkdir -p`。
51
+
52
+ ### `directory does not exist: /tmp/x`(`pp new -C`)
53
+
54
+ `-C` 只接受已存在的目录,不会替你创建。
55
+
56
+ ### `error: unknown session "9" (7 session(s) configured; see pp ls)`
57
+
58
+ 序号从 1 开始,且只按**配置文件里的顺序**,不是 `pp ls` 筛过之后的顺序(筛过时请用名字)。
59
+
60
+ ### `tmux session "api" already exists (--force to recreate, or pick another name)`
61
+
62
+ `pp new api` 撞名。`--force` 重建,或换个名字。
63
+
64
+ ## tmux 类
65
+
66
+ ### `tmux ... can't find pane: =backend`
67
+
68
+ 0.2 之前的 bug:`send-keys` / `capture-pane` 的目标必须是 `=name:`(带冒号),而 `has-session` / `kill-session` 用 `=name`。升级即可。自查:
69
+
70
+ ```bash
71
+ tmux list-panes -a -F '#{session_name}:#{pane_id}' | head
72
+ tmux send-keys -t '=backend:' 'echo ok' Enter # 冒号不能少
73
+ ```
74
+
75
+ ### `no server running on /tmp/tmux-1000/pi-plus`
76
+
77
+ ```bash
78
+ pp ls # 空表 = 确实没有会话
79
+ pp doctor # tmux server 那行会写 not running (starts on demand)
80
+ ```
81
+
82
+ 用了 `--socket pi-plus` 时,你的 shell 里 `tmux ls` 看不到这些会话——需要 `tmux -L pi-plus ls`。
83
+
84
+ ### 会话在 `tmux ls` 里有,但 `pp ls` 显示 `off`
85
+
86
+ 两边看的不是同一个 socket。检查配置里的 `tmux.socket` 和你 `tmux ls` 用的 socket 是否一致;另外自启单元不会带命令行 `--socket`(只认配置文件里的 `tmux.socket`)。
87
+
88
+ ### `STATE=dead`
89
+
90
+ pane 里的进程退出了,`remain-on-exit` 把 pane 留在那儿。看怎么回事:
91
+
92
+ ```bash
93
+ pp logs backend -n 200
94
+ pp up backend # 重建(restart: no 的会话必须点名)
95
+ ```
96
+
97
+ ## 名字 / remote-pi 类
98
+
99
+ ### mesh 里看到的不是我配的名字
100
+
101
+ 1. `cat <cwd>/.pi/remote-pi/config.json` 看 `agent_name`
102
+ 2. 同一目录两个会话要求不同名字 → 必须 `remote_pi_mode: env`(文件只有一个 `agent_name`,`config` 模式最后一次写赢)
103
+ 3. broker 侧同名冲突会临时显示 `name#2`,不会写回配置
104
+
105
+ ```bash
106
+ pp check # 共享 cwd + config 模式会给出警告
107
+ ```
108
+
109
+ ### 想彻底不进 mesh
110
+
111
+ ```yaml
112
+ remote_pi_mode: off
113
+ # 或
114
+ remote_pi_name: false
115
+ ```
116
+
117
+ `pp new` 加 `--no-remote-pi`。
118
+
119
+ ### pi 里 `/session` 看到的名字不是我想的
120
+
121
+ 那是 `pi_session_name`(`--name`),不是 tmux 名,也不是 remote-pi 名。看 [configuration.md](configuration.md#名字映射速查)。
122
+
123
+ ## 自启类
124
+
125
+ ### 重启后一个会话都没有,但 `systemctl --user is-enabled pi-plus` 说 enabled
126
+
127
+ 三种可能,按概率:
128
+
129
+ 1. **没开 linger**(服务器/无图形登录):`sudo loginctl enable-linger "$USER"`
130
+ 2. **WSL2**:发行版要有人调 `wsl.exe` 才会起来的,Windows 侧必须配触发(见 [autostart.md](autostart.md#wsl2只有里面装是不够的))
131
+ 3. **单元里没有 `KillMode=none`**:现象是 `Result=success` 但 tmux server 被 systemd 连坐杀掉了。老版本升级后请重装单元:`pp uninstall && pp install`
132
+
133
+ 验证是不是第 3 种:
134
+
135
+ ```bash
136
+ systemctl --user show pi-plus -p Result -p ExecMainStatus # success
137
+ tmux ls # 空的 → 就是它
138
+ grep KillMode ~/.config/systemd/user/pi-plus.service # 应该 =none
139
+ ```
140
+
141
+ ### 会话起来但立刻又被杀
142
+
143
+ `pp install` 之后又手动 `systemctl --user restart pi-plus.service`:oneshot 每次执行都会跑 `up --reconcile`,如果配置文件里某会话已 dead 且 `restart: always`,会被重建——这是预期行为,不是杀。
144
+
145
+ ### 手动 `down` 的会话,巡检又起来了
146
+
147
+ 只有 `always` 会。`unless-stopped` / `on-failure` 的手动停止记录在 `~/.local/state/pi-plus/state.json`:
148
+
149
+ ```bash
150
+ cat ~/.local/state/pi-plus/state.json
151
+ pp up backend # 点名启动会清掉这条记录,重新纳入巡检
152
+ ```
153
+
154
+ ## attach 类
155
+
156
+ ### 从脚本 / agent 里 `pp attach` 输出乱码或卡住
157
+
158
+ `attach` 需要真正的终端(pty + termios)。非 TTY 直接拒绝,用 `script`、`expect`、管道都不行——你会得到 cooked mode,方向键变成 `ESC [ A` 之类的字面量。
159
+
160
+ - 本机:在真终端里跑 `pp attach backend`
161
+ - 远程:`ssh -t host 'pp attach backend'`(`-t` 必须有)
162
+ - 只想看输出:`pp logs backend -n 500` 或 `tail -f ~/.pi/plus/logs/backend.log`
163
+
164
+ ## 发布 / 安装类
165
+
166
+ ### `npm i -g pi-farm` 装到的是别的东西或 404
167
+
168
+ 内网镜像 `npm config get registry` 指向 Nexus 时拿不到公网包:
169
+
170
+ ```bash
171
+ npm i -g pi-farm --registry https://registry.npmjs.org/
172
+ ```
173
+
174
+ ### `pp: command not found`
175
+
176
+ ```bash
177
+ npm bin -g 2>/dev/null || echo "$(npm root -g)/../bin"
178
+ echo "$PATH" | tr ':' '\n' | grep -i node
179
+ ```
180
+
181
+ nvm 的全局 bin 通常在 `~/.nvm/versions/node/vX/bin`,装完要重开 shell 或 `hash -r`。
182
+
183
+ ### `pp -V` 的版本和 GitHub 上不一致
184
+
185
+ ```bash
186
+ which -a pp # 可能还有旧的 ~/.local/bin/pp 符号链接
187
+ npm ls -g --depth=0 | grep pi-farm
188
+ ```
189
+
190
+ ## 配置类
191
+
192
+ ### `unknown key "pi_sesion" (ignored)` 之类的警告
193
+
194
+ 拼写错误被忽略而不是报错(故意这么设计,免得升级时新增字段导致旧配置无法解析)。`pp check` 会列出所有警告。
195
+
196
+ ### `config file not found`
197
+
198
+ ```bash
199
+ pp check # 会打印实际搜索过的路径
200
+ PI_PLUS_CONFIG=/path/to/plus.yml pp ls
201
+ pp init # 写一份模板到 ~/.pi/plus.yml
202
+ ```
203
+
204
+ ### 想确认某个字段到底被解析成了什么
205
+
206
+ ```bash
207
+ pp check --json | jq '.sessions[]? // .' # 或
208
+ pp up backend --dry-run -v # 打印最终 argv + env
209
+ ```
210
+
211
+ `--dry-run` 会显示形如:
212
+
213
+ ```
214
+ [backend] cwd=/home/you/code/backend tmux=backend pi-session=backend remote-pi=backend(mode=config)
215
+ [dry-run] tmux new-session -d -s backend -c /home/you/code/backend -- env ... pi --name backend
216
+ ```
217
+
218
+ ## 还是不行
219
+
220
+ ```bash
221
+ pp doctor --json | jq
222
+ pp check --json | jq
223
+ pp up <name> -v --dry-run
224
+ ```
225
+
226
+ 把这四条的输出贴到 issue(记得先脱敏路径)。
package/package.json CHANGED
@@ -1,16 +1,19 @@
1
1
  {
2
2
  "name": "pi-farm",
3
- "version": "0.2.2",
3
+ "version": "0.3.0",
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",
11
13
  "src",
12
14
  "examples",
13
15
  "completions",
16
+ "docs",
14
17
  "README.md",
15
18
  "LICENSE"
16
19
  ],
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/autostart.js CHANGED
@@ -229,7 +229,13 @@ export function installAutostart({ scriptPath, configPath, watch = false, print
229
229
  if (timer) {
230
230
  run("systemctl", ["--user", "enable", "--now", `${SERVICE_NAME}.timer`], { allowFailure: true });
231
231
  } else {
232
- run("systemctl", ["--user", "start", `${SERVICE_NAME}.service`], { allowFailure: true });
232
+ // `restart` (not `start`): the oneshot stays "active (exited)" after a
233
+ // run, so `start` would be a no-op when installing over an old unit —
234
+ // which is exactly the "I ran `pp down`, then `pp install`" case.
235
+ const restarted = run("systemctl", ["--user", "restart", `${SERVICE_NAME}.service`], { allowFailure: true });
236
+ if (restarted.status !== 0) {
237
+ run("systemctl", ["--user", "start", `${SERVICE_NAME}.service`], { allowFailure: true });
238
+ }
233
239
  }
234
240
  run("loginctl", ["enable-linger", process.env.USER || ""], { allowFailure: true });
235
241
  }