pi-farm 0.3.0 → 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 CHANGED
@@ -46,6 +46,16 @@ 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
+
49
59
  ### 命令名被别的程序占了?(macOS 自带 `/usr/bin/pp`)
50
60
 
51
61
  macOS 上 `/usr/bin/pp` 是一个 ASN.1 转换工具,`pp ls` 会打出它的用法说明。除了 `pp`,安装时还会一起装两个名字:
@@ -301,6 +311,7 @@ pp init 写示例配置
301
311
  pp install [--watch N] 安装开机自启(别名 autostart)
302
312
  pp uninstall 卸载自启
303
313
  pp alias [ls|add|rm] 换/加一个命令名(pp 被别的程序占用时用)
314
+ pp update [--check] 升级到最新发布版(npm / git 安装自动判断)
304
315
  pp help [命令] 帮助(不带参数为总览)
305
316
  pp version 打印版本
306
317
  ```
package/bin/pp.js CHANGED
@@ -69,6 +69,8 @@ function parseArgs(argv) {
69
69
  case "--no-wait": options.noWait = true; break;
70
70
  case "--body-json": options.bodyJson = takeValue(flag, inline); break;
71
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;
72
74
  case "--reply": options.reply = Number(takeValue(flag, inline)) || 0; break;
73
75
  case "--local": options.local = true; break;
74
76
  case "--path": options.path = takeValue(flag, inline); break;
package/completions/_pp CHANGED
@@ -22,6 +22,8 @@ _pp() {
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'
25
27
  'alias:add another command name (ls/add/rm)'
26
28
  'link:alias for alias'
27
29
  'version:print version'
@@ -54,6 +56,8 @@ _pp() {
54
56
  '--no-wait[do not wait for the mesh ACK]' \
55
57
  '--body-json[mesh body as JSON]:json:' \
56
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:' \
57
61
  '--watch[reconcile interval for install]:seconds:' \
58
62
  '--print[print autostart unit and exit]' \
59
63
  '1:command:->command' \
@@ -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 alias link 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)
@@ -42,7 +42,7 @@ _pp() {
42
42
  esac
43
43
 
44
44
  if [[ "$cur" == -* ]]; then
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 --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") )
46
46
  return 0
47
47
  fi
48
48
  if [[ $COMP_CWORD -eq 2 && "${COMP_WORDS[1]}" == "help" ]]; then
@@ -23,6 +23,7 @@ src/autostart.js systemd / launchd 单元渲染与安装/卸载/状态查询
23
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
25
  src/aliases.js 备用命令名(pifarm/pi-plus/自定义软链)+ PATH 上 pp 归属判定
26
+ src/update.js 自升级:安装方式判定(npm/git/unknown)、registry 版本查询、命令规划
26
27
  src/example.js `pp init` 写入的示例配置
27
28
  ```
28
29
 
package/docs/cli.md CHANGED
@@ -32,6 +32,8 @@ pp <command> [names...] [options]
32
32
  | `--no-wait` | `mesh send` 只发不等 ACK |
33
33
  | `--body-json <json>` | `mesh send` 发结构化 JSON(默认发纯文本) |
34
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`) |
35
37
  | `--print` | `install` 只打印单元文件 |
36
38
  | `--watch [secs]` | `install` 额外装一个定时器,每 N 秒(默认 300)巡检一次 |
37
39
  | `-h, --help` | 帮助(`pp help`、`pp <cmd> --help` 等价) |
@@ -133,6 +135,26 @@ pp mesh send api --body-json '{"task":"test","id":42}' # 结构化消息
133
135
  - 地址后缀 `#N` 是 broker 对同 `(cwd, name)` 重复身份的自动去重,`livePeersFor` 会把它一并算作同一个会话
134
136
  - 跨机投递走 broker leader 的 relay 桥,发送端不需要做任何配对
135
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
+
136
158
  ### `pp alias [ls|add|rm]`
137
159
 
138
160
  管理备用命令名。macOS 自带 `/usr/bin/pp`(ASN.1 工具),所以包内自带 `pifarm`、`pi-plus` 两个名字;`alias` 再加任意短名。
@@ -24,6 +24,29 @@ pp alias ls # 看已有别名 + 目录是否在 PATH
24
24
 
25
25
  别名只接受 `[A-Za-z0-9._-]`,且不能以 `-` 开头(避免被当成 flag)。
26
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
+
27
50
  ## 启动类
28
51
 
29
52
  ### `session "backend" exited immediately`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-farm",
3
- "version": "0.3.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": {
package/src/commands.js CHANGED
@@ -36,6 +36,16 @@ import {
36
36
  systemdUserDir,
37
37
  } from "./autostart.js";
38
38
  import { clearStopped, isStopped, markStopped } from "./state.js";
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";
39
49
  import {
40
50
  BROADCAST_TARGET,
41
51
  connectPeer,
@@ -1125,6 +1135,89 @@ function cmdUninstall(options, ui) {
1125
1135
  ui.info(`removed ${result.removed.join(", ")}`);
1126
1136
  }
1127
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
+
1128
1221
  function cmdAlias(config, options, ui) {
1129
1222
  const sub = options.names[0] ?? "ls";
1130
1223
  const rest = options.names.slice(1);
@@ -1295,6 +1388,10 @@ export async function runCommand(command, options) {
1295
1388
  const config = requireConfig(options, ui);
1296
1389
  return cmdInstall(config, options, ui);
1297
1390
  }
1391
+ case "update":
1392
+ case "upgrade": {
1393
+ return cmdUpdate(options, ui);
1394
+ }
1298
1395
  case "alias":
1299
1396
  case "link": {
1300
1397
  return cmdAlias(null, options, ui); // aliasing does not need a config
package/src/help.js CHANGED
@@ -268,6 +268,31 @@ export const COMMANDS = [
268
268
  examples: ["pp uninstall"],
269
269
  see: ["install"],
270
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
+ },
271
296
  {
272
297
  name: "alias",
273
298
  aliases: ["link"],
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
+ }