pi-farm 0.4.0 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +28 -0
- package/bin/pp.js +11 -0
- package/completions/_pp +2 -0
- package/completions/pp.bash +6 -2
- package/docs/architecture.md +1 -0
- package/docs/cli.md +54 -0
- package/docs/configuration.md +15 -0
- package/docs/troubleshooting.md +14 -0
- package/extensions/pp-tmux.js +6 -0
- package/package.json +1 -1
- package/src/commands.js +187 -0
- package/src/config.js +17 -1
- package/src/help.js +75 -0
- package/src/push.js +393 -0
package/README.md
CHANGED
|
@@ -28,6 +28,7 @@ pi-plus.yml ──► tmux new-session -d -s backend -c ~/code/backend -- pi --n
|
|
|
28
28
|
- **可脚本化**:`--json`、`--dry-run`、`--quiet`,退出码可用(`up` 有失败即 1)。
|
|
29
29
|
- **安全默认**:不经过 shell 拼接命令;tmux 名做白名单校验;重建前先 `check`。
|
|
30
30
|
- **直接跟别的 agent 说话**:`pp mesh ls/send` 直连 remote-pi 的本地 broker,按会话名或跨机地址发消息、拿 ACK、等回复。
|
|
31
|
+
- **本机截图直接进远端会话**:`pp shot --push host:session` 用 ssh 把图送到 `~/.pi/plus/drops/`,再把路径打进 pane(不打回车)。
|
|
31
32
|
|
|
32
33
|
## 安装
|
|
33
34
|
|
|
@@ -146,6 +147,31 @@ pp mesh send backend "跑一下测试" --reply 60000 # 等它回话,收
|
|
|
146
147
|
`pp mesh send` 是走 agent 之间的消息通道(对方收到 `[agent-network] message from …` 信封)
|
|
147
148
|
- broker 没起来时会明确报 `no mesh broker at …`;`pp mesh ls/resolve` 可离线用来看地址
|
|
148
149
|
|
|
150
|
+
## 把图片/文件推进远端会话(pp shot / pp push)
|
|
151
|
+
|
|
152
|
+
pi 跑在远端机器、你坐在本机,截了一张图想直接送进那个会话:
|
|
153
|
+
|
|
154
|
+
```bash
|
|
155
|
+
pp shot --push hardy@1.2.3.4:delta # macOS 截图 → 推到 delta,路径已经打进输入框
|
|
156
|
+
pp shot --clipboard --push mybox:ops # 用剪贴板里已有的图(不是新截的)
|
|
157
|
+
pp push ./crash.log --push mybox#risk-01 # 任意文件,任何系统
|
|
158
|
+
```
|
|
159
|
+
|
|
160
|
+
发生的事:截图 → `scp` 到远端 `~/.pi/plus/drops/<会话>/<时间戳>-xxx.png` →
|
|
161
|
+
在远端 pane 里**只打字、不回车**(`tmux send-keys -l`)。路径就停在那儿,
|
|
162
|
+
你看得见,自己决定什么时候发送。
|
|
163
|
+
|
|
164
|
+
- 目标怎么定:`--push` → `$PP_PUSH_TARGET` → 配置里的 `push:` 块 →
|
|
165
|
+
**本机进程表里最近那条 `ssh` 的目标** → 主机名兜底。目标写法
|
|
166
|
+
`[user@]host[:port][#session]`,`--to <会话>` 可单独指定远端会话
|
|
167
|
+
- 认证完全交给 ssh:`pp` 在 `~/.ssh/cm-pp-*` 下复用 ControlMaster 连接
|
|
168
|
+
(默认保活 600 秒,`--persist` 改),所以密码只输一次;**不需要改
|
|
169
|
+
`~/.ssh/config`**,`pp` 也不保存任何凭据
|
|
170
|
+
- 没给 `--to` 时取"正附着 client 的那个会话";一个都没附着会报错并让你指定,
|
|
171
|
+
不会瞎猜
|
|
172
|
+
- `--no-prefill` 只传文件、不动输入框;`--dry-run` 把所有 ssh/scp 命令打出来
|
|
173
|
+
- `pp shot` 的截图步骤要 macOS(`screencapture`);`pp push` 在任何系统都能用
|
|
174
|
+
|
|
149
175
|
## 在 pi 里用 `/pp-*`(扩展)
|
|
150
176
|
|
|
151
177
|
`pp` 自带一个 pi 扩展:把 tmux 的 `Ctrl-b s`、`Ctrl-b d` 变成斜杠命令,不用离开对话。
|
|
@@ -328,6 +354,8 @@ pp status [name|#...] 状态表,第一列是 # 序号(--json 机器可
|
|
|
328
354
|
pp attach <name|#> 进入;不存在则先启动
|
|
329
355
|
pp logs <name|#> [-n 200] 打印滚动输出
|
|
330
356
|
pp send <name|#> "文本" 往 pane 里打字并回车(--no-enter 不回车)
|
|
357
|
+
pp push <file> [opts] 推到远端并预填路径(--push/--to/--no-prefill)
|
|
358
|
+
pp shot [opts] 截图(macOS)→ pp push
|
|
331
359
|
pp mesh ls|resolve|send 直连 remote-pi broker:看谁在线 / 查地址 / 发消息(--reply 等回复)
|
|
332
360
|
pp check 校验配置
|
|
333
361
|
pp doctor 环境诊断(含自启状态、WSL 提示)
|
package/bin/pp.js
CHANGED
|
@@ -72,6 +72,17 @@ function parseArgs(argv) {
|
|
|
72
72
|
case "--check": options.check = true; break;
|
|
73
73
|
case "--registry": options.registry = takeValue(flag, inline); break;
|
|
74
74
|
case "--reply": options.reply = Number(takeValue(flag, inline)) || 0; break;
|
|
75
|
+
case "--push": options.push = takeValue(flag, inline); break;
|
|
76
|
+
case "--to": options.to = takeValue(flag, inline); break;
|
|
77
|
+
case "--port": options.port = Number(takeValue(flag, inline)) || null; break;
|
|
78
|
+
case "--remote-dir": options.remoteDir = takeValue(flag, inline); break;
|
|
79
|
+
case "--out-dir": options.outDir = takeValue(flag, inline); break;
|
|
80
|
+
case "--control-path": options.controlPath = takeValue(flag, inline); break;
|
|
81
|
+
case "--persist": options.persist = Number(takeValue(flag, inline)) || 600; break;
|
|
82
|
+
case "--clipboard": options.clipboard = true; break;
|
|
83
|
+
case "--full": options.full = true; break;
|
|
84
|
+
case "--no-prefill": options.prefill = false; break;
|
|
85
|
+
case "--no-detect": options.noDetect = true; break;
|
|
75
86
|
case "--local": options.local = true; break;
|
|
76
87
|
case "--path": options.path = takeValue(flag, inline); break;
|
|
77
88
|
case "--help": process.exit(showHelp(command));
|
package/completions/_pp
CHANGED
|
@@ -16,6 +16,8 @@ _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
|
+
'push:copy a file to another machine and prefill it'
|
|
20
|
+
'shot:screenshot (macOS) and push it'
|
|
19
21
|
'mesh:remote-pi mesh (ls/send/resolve/inbox)'
|
|
20
22
|
'check:validate the config'
|
|
21
23
|
'doctor:environment diagnostics'
|
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 alias link update upgrade version help"
|
|
7
|
+
local commands="new n create up start down stop restart status ls list attach a logs log send push put shot snap 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)
|
|
@@ -14,6 +14,10 @@ _pp() {
|
|
|
14
14
|
--socket|--lines|-n|--agent|-C|--dir)
|
|
15
15
|
return 0
|
|
16
16
|
;;
|
|
17
|
+
push|put|shot|snap)
|
|
18
|
+
COMPREPLY=( $(compgen -f -- "$cur") )
|
|
19
|
+
return 0
|
|
20
|
+
;;
|
|
17
21
|
mesh)
|
|
18
22
|
COMPREPLY=( $(compgen -W "ls list resolve send inbox listen watch" -- "$cur") )
|
|
19
23
|
return 0
|
|
@@ -42,7 +46,7 @@ _pp() {
|
|
|
42
46
|
esac
|
|
43
47
|
|
|
44
48
|
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 --check --registry --help --version" -- "$cur") )
|
|
49
|
+
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 --push --to --port --persist --remote-dir --out-dir --control-path --clipboard --full --no-prefill --no-detect --help --version" -- "$cur") )
|
|
46
50
|
return 0
|
|
47
51
|
fi
|
|
48
52
|
if [[ $COMP_CWORD -eq 2 && "${COMP_WORDS[1]}" == "help" ]]; then
|
package/docs/architecture.md
CHANGED
|
@@ -24,6 +24,7 @@ src/commands.js 各子命令实现(up/down/restart/status/attach/logs/send/
|
|
|
24
24
|
src/help.js COMMANDS 单一数据源 + 总览/单命令页/拼写建议
|
|
25
25
|
src/aliases.js 备用命令名(pifarm/pi-plus/自定义软链)+ PATH 上 pp 归属判定
|
|
26
26
|
src/update.js 自升级:安装方式判定(npm/git/unknown)、registry 版本查询、命令规划
|
|
27
|
+
src/push.js 跨机传送:目标解析(参数/环境/配置/进程表)、ControlMaster 复用、scp + `tmux send-keys -l` 预填
|
|
27
28
|
src/example.js `pp init` 写入的示例配置
|
|
28
29
|
src/ppui.js pi 扩展用的纯函数($TMUX 解析、会话标签、前缀匹配、peek 参数、client 选择)
|
|
29
30
|
extensions/pp-tmux.js pi 扩展入口:/pp-ls /pp-sw /pp-quit /pp-status /pp-peek
|
package/docs/cli.md
CHANGED
|
@@ -135,6 +135,60 @@ pp mesh send api --body-json '{"task":"test","id":42}' # 结构化消息
|
|
|
135
135
|
- 地址后缀 `#N` 是 broker 对同 `(cwd, name)` 重复身份的自动去重,`livePeersFor` 会把它一并算作同一个会话
|
|
136
136
|
- 跨机投递走 broker leader 的 relay 桥,发送端不需要做任何配对
|
|
137
137
|
|
|
138
|
+
### `pp push <file>`
|
|
139
|
+
|
|
140
|
+
把一个本地文件送到另一台机器,并把远端路径打进那个 tmux 会话的输入框
|
|
141
|
+
(打字不打回车,你自己决定何时发送)。
|
|
142
|
+
|
|
143
|
+
```bash
|
|
144
|
+
pp push ./crash.log --push hardy@1.2.3.4:delta
|
|
145
|
+
pp push ./screen.png --push delta # 别名在 ~/.ssh/config 里即可
|
|
146
|
+
PP_PUSH_TARGET=mybox#risk-01 pp push ./a.png
|
|
147
|
+
pp push ./a.png --push mybox --to risk-01 --no-prefill
|
|
148
|
+
pp push ./a.png --push mybox:delta --dry-run
|
|
149
|
+
```
|
|
150
|
+
|
|
151
|
+
| 选项 | 说明 |
|
|
152
|
+
|---|---|
|
|
153
|
+
| `--push <target>` | `[user@]host[:port][#session]` |
|
|
154
|
+
| `--to <会话>` | 远端 tmux 会话(默认:正附着 client 的那个) |
|
|
155
|
+
| `--remote-dir <dir>` | 远端目录(默认 `~/.pi/plus/drops/<会话>`) |
|
|
156
|
+
| `--no-prefill` | 只传文件,不动输入框 |
|
|
157
|
+
| `--persist <秒>` | ControlMaster 保活时间(默认 600) |
|
|
158
|
+
| `--control-path <p>` | ControlMaster socket(默认 `~/.ssh/cm-pp-%r@%h-%p`) |
|
|
159
|
+
| `--no-detect` | 不从进程表猜目标 |
|
|
160
|
+
| `--socket <name>` | 远端 tmux socket |
|
|
161
|
+
| `--dry-run` / `--json` | 打印命令 / 机器可读结果 |
|
|
162
|
+
|
|
163
|
+
目标解析顺序:`--push` → `$PP_PUSH_TARGET` → 配置 `push:` 块 →
|
|
164
|
+
本机进程表里最近一条 `ssh` 的目标 → 主机名。
|
|
165
|
+
|
|
166
|
+
认证不归 pp 管:它用 `ssh -M -N -f -o ControlPersist=…` 起一个后台 master,
|
|
167
|
+
之后所有 `scp`/`ssh` 都挂在这个 socket 上,所以**密码最多输一次**,
|
|
168
|
+
而且不需要改 `~/.ssh/config`。key/agent 照旧生效。
|
|
169
|
+
|
|
170
|
+
远端路径里的 `~` 会先问一次远端 `$HOME` 再转成绝对路径(`scp` 与 `mkdir` 对
|
|
171
|
+
`~` 的展开规则不一致,转绝对路径能避开这个坑)。
|
|
172
|
+
|
|
173
|
+
### `pp shot`
|
|
174
|
+
|
|
175
|
+
macOS 上截图并立刻 `pp push`。
|
|
176
|
+
|
|
177
|
+
```bash
|
|
178
|
+
pp shot --push hardy@1.2.3.4:delta
|
|
179
|
+
pp shot --clipboard --push mybox:ops
|
|
180
|
+
PP_PUSH_TARGET=mybox:delta pp shot
|
|
181
|
+
```
|
|
182
|
+
|
|
183
|
+
| 选项 | 说明 |
|
|
184
|
+
|---|---|
|
|
185
|
+
| `--clipboard` | 用剪贴板里已有的图(`NSPasteboard`),不再截图 |
|
|
186
|
+
| `--full` | 整屏截图(默认 `-i` 选区) |
|
|
187
|
+
| `--out-dir <dir>` | 本地暂存目录(默认 `~/.pi/plus/cache`) |
|
|
188
|
+
|
|
189
|
+
其余选项与 `pp push` 相同。取消截图 → `screenshot cancelled`(退出码 2);
|
|
190
|
+
非 macOS 上直接报错并提示改用 `pp push <file>`。
|
|
191
|
+
|
|
138
192
|
### `pp update [--check]`
|
|
139
193
|
|
|
140
194
|
升级到最新发布版。先判断这份是从哪装的,再跑对应命令:
|
package/docs/configuration.md
CHANGED
|
@@ -57,6 +57,21 @@ sessions: # 必填,非空列表
|
|
|
57
57
|
|
|
58
58
|
未知键不会让命令失败,但会作为警告出现(`unknown key "xxx" (ignored)`),方便发现拼写错误。
|
|
59
59
|
|
|
60
|
+
## `push:` 块(可选)
|
|
61
|
+
|
|
62
|
+
`pp push` / `pp shot` 的默认目标。没有这块也能用:命令会去进程表里找你最近
|
|
63
|
+
那条 `ssh` 的目标,再不行就用主机名。
|
|
64
|
+
|
|
65
|
+
```yaml
|
|
66
|
+
push:
|
|
67
|
+
target: hardy@192.168.1.88#delta # [user@]host[:port][#session]
|
|
68
|
+
session: delta # 可选,覆盖 target 里的 #session
|
|
69
|
+
dir: ~/.pi/plus/drops/delta # 可选,远端落盘目录
|
|
70
|
+
port: 22 # 可选
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
优先级:`--push` > `$PP_PUSH_TARGET` > 这里 > 进程表 > 主机名。
|
|
74
|
+
|
|
60
75
|
## `restart` 策略
|
|
61
76
|
|
|
62
77
|
语义对齐 docker compose:
|
package/docs/troubleshooting.md
CHANGED
|
@@ -216,6 +216,20 @@ pp attach backend # 或者接到已有会话上
|
|
|
216
216
|
扩展只列**当前 `$TMUX` 指向的那个服务器**里的会话。`pp up --socket other` 起的会话在另一个
|
|
217
217
|
socket 上,`tmux -L other list-sessions` 才看得到。
|
|
218
218
|
|
|
219
|
+
## push / shot 类
|
|
220
|
+
|
|
221
|
+
| 现象 | 原因 / 解决 |
|
|
222
|
+
|---|---|
|
|
223
|
+
| `cannot open an ssh connection to X (exit 255)` | 目标错、网络不通,或认证失败。先手动 `ssh X true` 试一下 |
|
|
224
|
+
| 每次都要输密码 | 没有 key,且 master 已经过期。`--persist 3600` 拉长保活,或改用 `ssh-copy-id` |
|
|
225
|
+
| `Bad local forwarding specification` | 老版本 bug(远端命令以 `-L` 开头被 ssh 当成自己的选项)。升级到 0.5.0+ |
|
|
226
|
+
| `no session is attached — pick one` | 远端没有 client 附着,用 `--to <会话>` 指定 |
|
|
227
|
+
| `cannot resolve $HOME on X` | 远端 shell 回不出 `$HOME`(极少见),用 `--remote-dir` 给绝对路径 |
|
|
228
|
+
| `screenshot cancelled` | 你按了 Esc。`--full` 可跳过选区 |
|
|
229
|
+
| `pp shot needs macOS` | 截图步骤依赖 `screencapture`;其它系统用 `pp push <file>` |
|
|
230
|
+
| 图推过去了但 pane 里没变 | 远端会话可能在别的 tmux socket,加 `--socket <name>` |
|
|
231
|
+
| 目标猜错了 | 加 `--no-detect` 关掉进程表探测,显式写 `--push` 或设 `PP_PUSH_TARGET` |
|
|
232
|
+
|
|
219
233
|
## 发布 / 安装类
|
|
220
234
|
|
|
221
235
|
### `npm i -g pi-farm` 装到的是别的东西或 404
|
package/extensions/pp-tmux.js
CHANGED
|
@@ -187,6 +187,12 @@ export default function ppTmux(pi) {
|
|
|
187
187
|
await handler(args, ctx);
|
|
188
188
|
} catch (error) {
|
|
189
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
|
+
}
|
|
190
196
|
ctx.ui.notify(message, "error");
|
|
191
197
|
}
|
|
192
198
|
},
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-farm",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.5.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": {
|
package/src/commands.js
CHANGED
|
@@ -57,6 +57,23 @@ import {
|
|
|
57
57
|
sessionMeshAddress,
|
|
58
58
|
} from "./mesh.js";
|
|
59
59
|
import { findCommand, suggestCommand } from "./help.js";
|
|
60
|
+
import {
|
|
61
|
+
assertReadableFile,
|
|
62
|
+
CONTROL_PATH_TEMPLATE,
|
|
63
|
+
controlPathPath,
|
|
64
|
+
DEFAULT_PERSIST_SECONDS,
|
|
65
|
+
detectActiveSshTarget,
|
|
66
|
+
dropName,
|
|
67
|
+
ensureLocalDir,
|
|
68
|
+
ensureMaster,
|
|
69
|
+
parseAttachedSession,
|
|
70
|
+
PushError,
|
|
71
|
+
pushFile,
|
|
72
|
+
remoteDropsDir,
|
|
73
|
+
resolvePushTarget,
|
|
74
|
+
shellQuoteArgs,
|
|
75
|
+
tmuxPrefillArgs,
|
|
76
|
+
} from "./push.js";
|
|
60
77
|
import { EXAMPLE_CONFIG } from "./example.js";
|
|
61
78
|
|
|
62
79
|
const COLORS = {
|
|
@@ -1304,6 +1321,155 @@ function assertAliasNameSafe(name) {
|
|
|
1304
1321
|
}
|
|
1305
1322
|
}
|
|
1306
1323
|
|
|
1324
|
+
/**
|
|
1325
|
+
* Capture a screenshot on macOS. `--clipboard` grabs the image currently on the
|
|
1326
|
+
* pasteboard, otherwise screencapture opens the interactive selection UI.
|
|
1327
|
+
*/
|
|
1328
|
+
function captureScreenshot(path, { clipboard = false, full = false } = {}) {
|
|
1329
|
+
if (clipboard) {
|
|
1330
|
+
const script = [
|
|
1331
|
+
"ObjC.import('AppKit');",
|
|
1332
|
+
"const pb = $.NSPasteboard.generalPasteboard;",
|
|
1333
|
+
"const data = pb.dataForType('public.png') || pb.dataForType('public.tiff');",
|
|
1334
|
+
"if (!data) { throw new Error('no image in the clipboard'); }",
|
|
1335
|
+
`data.writeToFileAtomically('${path.replace(/'/g, "\\'")}', true);`,
|
|
1336
|
+
].join("\n");
|
|
1337
|
+
const result = spawnSync("osascript", ["-l", "JavaScript", "-e", script], { encoding: "utf8" });
|
|
1338
|
+
if (result.status !== 0) {
|
|
1339
|
+
const detail = (result.stderr || "").trim().split("\n").pop();
|
|
1340
|
+
throw new PushError(`cannot read the clipboard image${detail ? `: ${detail}` : ""}`, "capture");
|
|
1341
|
+
}
|
|
1342
|
+
return;
|
|
1343
|
+
}
|
|
1344
|
+
const args = full ? ["-x", path] : ["-i", "-x", path];
|
|
1345
|
+
const result = spawnSync("screencapture", args, { encoding: "utf8" });
|
|
1346
|
+
if (result.status !== 0) {
|
|
1347
|
+
throw new PushError(`screencapture failed (exit ${result.status})`, "capture");
|
|
1348
|
+
}
|
|
1349
|
+
if (!existsSync(path) || statSync(path).size === 0) {
|
|
1350
|
+
throw new PushError("screenshot cancelled", "capture");
|
|
1351
|
+
}
|
|
1352
|
+
}
|
|
1353
|
+
|
|
1354
|
+
/** Resolve where a push goes, honouring --push, $PP_PUSH_TARGET, `push:` and the process table. */
|
|
1355
|
+
function pushTargetFor(config, options) {
|
|
1356
|
+
const spec = options.push ?? null;
|
|
1357
|
+
const detected = options.noDetect ? null : detectActiveSshTarget();
|
|
1358
|
+
const target = resolvePushTarget({
|
|
1359
|
+
spec,
|
|
1360
|
+
env: process.env,
|
|
1361
|
+
configPush: config?.push ?? null,
|
|
1362
|
+
detected,
|
|
1363
|
+
});
|
|
1364
|
+
const session = options.to ?? target.session ?? config?.push?.session ?? null;
|
|
1365
|
+
return { target, session, detected };
|
|
1366
|
+
}
|
|
1367
|
+
|
|
1368
|
+
/** Shared implementation for `pp shot --push` and `pp push`. */
|
|
1369
|
+
async function doPush(config, options, ui, { file, sessionHint = null } = {}) {
|
|
1370
|
+
const { target, session, detected } = pushTargetFor(config, options);
|
|
1371
|
+
const wanted = sessionHint ?? session;
|
|
1372
|
+
const controlPath = controlPathPath(options.controlPath ?? CONTROL_PATH_TEMPLATE);
|
|
1373
|
+
const remoteDir = options.remoteDir ?? config?.push?.dir ?? remoteDropsDir({ session: wanted });
|
|
1374
|
+
const persist = options.persist ?? DEFAULT_PERSIST_SECONDS;
|
|
1375
|
+
const prefill = options.prefill !== false;
|
|
1376
|
+
const abs = assertReadableFile(file);
|
|
1377
|
+
const remotePath = `${remoteDir}/${basename(abs)}`;
|
|
1378
|
+
const plan = {
|
|
1379
|
+
file: abs,
|
|
1380
|
+
host: target.target,
|
|
1381
|
+
port: target.port ?? null,
|
|
1382
|
+
session: wanted,
|
|
1383
|
+
remotePath,
|
|
1384
|
+
source: target.source,
|
|
1385
|
+
via: controlPath,
|
|
1386
|
+
};
|
|
1387
|
+
|
|
1388
|
+
if (options.dryRun) {
|
|
1389
|
+
ui.out(`[dry-run] target ${target.target}${target.port ? `:${target.port}` : ""} (from ${target.source})`);
|
|
1390
|
+
ui.out(`[dry-run] ssh -o ControlPath=${controlPath} -M -N -f -o ControlPersist=${persist} ${target.target}`);
|
|
1391
|
+
ui.out(`[dry-run] ssh ${target.target} "mkdir -p ${remoteDir}"`);
|
|
1392
|
+
const portFlag = target.port ? `-P ${target.port}` : "";
|
|
1393
|
+
ui.out(`[dry-run] scp ${portFlag} ${abs} ${target.target}:${remotePath}`);
|
|
1394
|
+
if (prefill) {
|
|
1395
|
+
const command = shellQuoteArgs(tmuxPrefillArgs({ session: wanted ?? "<attached>", path: remotePath, socket: options.socket ?? null }));
|
|
1396
|
+
ui.out(`[dry-run] ssh ${target.target} ${command}`);
|
|
1397
|
+
}
|
|
1398
|
+
if (ui.json) ui.out(JSON.stringify({ dryRun: true, ...plan }, null, 2));
|
|
1399
|
+
return plan;
|
|
1400
|
+
}
|
|
1401
|
+
|
|
1402
|
+
ensureMaster(target, { controlPath, port: target.port, persistSeconds: persist, ui });
|
|
1403
|
+
const result = await pushFile({
|
|
1404
|
+
file: abs,
|
|
1405
|
+
target,
|
|
1406
|
+
session: wanted,
|
|
1407
|
+
remoteDir,
|
|
1408
|
+
socket: options.socket ?? null,
|
|
1409
|
+
prefill,
|
|
1410
|
+
controlPath,
|
|
1411
|
+
});
|
|
1412
|
+
|
|
1413
|
+
const shown = { ...plan, session: result.session, remotePath: result.remotePath };
|
|
1414
|
+
if (ui.json) {
|
|
1415
|
+
ui.out(JSON.stringify(shown, null, 2));
|
|
1416
|
+
return shown;
|
|
1417
|
+
}
|
|
1418
|
+
if (target.source === "detected" && detected) {
|
|
1419
|
+
ui.info(ui.paint("dim", `target detected from your ssh session: ${detected.raw}`));
|
|
1420
|
+
}
|
|
1421
|
+
ui.out(
|
|
1422
|
+
`pushed ${basename(abs)} → ${target.target}:${result.remotePath}` +
|
|
1423
|
+
(result.session && prefill ? ` (prefilled into ${result.session})` : ""),
|
|
1424
|
+
);
|
|
1425
|
+
if (!prefill) ui.info(ui.paint("dim", "the file is on the remote side; nothing was typed into a pane"));
|
|
1426
|
+
return shown;
|
|
1427
|
+
}
|
|
1428
|
+
|
|
1429
|
+
/** `pp push <file> [--push host[:session]]` */
|
|
1430
|
+
async function cmdPush(baseConfig, options, ui) {
|
|
1431
|
+
let config = baseConfig;
|
|
1432
|
+
if (!config) {
|
|
1433
|
+
try {
|
|
1434
|
+
config = loadConfig({ configPath: options.config, cwd: options.cwd });
|
|
1435
|
+
} catch {
|
|
1436
|
+
config = null;
|
|
1437
|
+
}
|
|
1438
|
+
}
|
|
1439
|
+
const file = options.names[0] ?? options.file;
|
|
1440
|
+
if (!file) {
|
|
1441
|
+
ui.error("usage: pp push <file> [--push host[:session]] [--no-prefill]");
|
|
1442
|
+
process.exit(2);
|
|
1443
|
+
}
|
|
1444
|
+
return await doPush(config, options, ui, { file });
|
|
1445
|
+
}
|
|
1446
|
+
|
|
1447
|
+
/** `pp shot [--push host[:session]]` — macOS screenshot straight into a remote pane. */
|
|
1448
|
+
async function cmdShot(baseConfig, options, ui) {
|
|
1449
|
+
let config = baseConfig;
|
|
1450
|
+
if (!config) {
|
|
1451
|
+
try {
|
|
1452
|
+
config = loadConfig({ configPath: options.config, cwd: options.cwd });
|
|
1453
|
+
} catch {
|
|
1454
|
+
config = null;
|
|
1455
|
+
}
|
|
1456
|
+
}
|
|
1457
|
+
if (process.platform !== "darwin" && !options.clipboard) {
|
|
1458
|
+
ui.error("pp shot needs macOS (screencapture). Use `pp push <file>` on this machine instead.");
|
|
1459
|
+
process.exit(2);
|
|
1460
|
+
}
|
|
1461
|
+
|
|
1462
|
+
const cacheDir = ensureLocalDir(expandPath(options.outDir ?? join(homedir(), ".pi", "plus", "cache")));
|
|
1463
|
+
const file = join(cacheDir, dropName(`shot-${Date.now()}.png`));
|
|
1464
|
+
if (!options.dryRun) {
|
|
1465
|
+
captureScreenshot(file, { clipboard: Boolean(options.clipboard), full: Boolean(options.full) });
|
|
1466
|
+
if (!ui.json && !options.quiet) ui.info(ui.paint("dim", `captured ${file}`));
|
|
1467
|
+
} else {
|
|
1468
|
+
ui.info(`[dry-run] screencapture → ${file}`);
|
|
1469
|
+
}
|
|
1470
|
+
return await doPush(config, options, ui, { file });
|
|
1471
|
+
}
|
|
1472
|
+
|
|
1307
1473
|
export async function runCommand(command, options) {
|
|
1308
1474
|
const ui = makeUi(options);
|
|
1309
1475
|
if (options.json) ui.quiet = true;
|
|
@@ -1356,6 +1522,27 @@ export async function runCommand(command, options) {
|
|
|
1356
1522
|
const config = requireConfig(options, ui);
|
|
1357
1523
|
return cmdSend(config, options, ui);
|
|
1358
1524
|
}
|
|
1525
|
+
case "push":
|
|
1526
|
+
case "put":
|
|
1527
|
+
case "upload": {
|
|
1528
|
+
let config = null;
|
|
1529
|
+
try {
|
|
1530
|
+
config = loadConfig({ configPath: options.config, cwd: options.cwd });
|
|
1531
|
+
} catch {
|
|
1532
|
+
config = null;
|
|
1533
|
+
}
|
|
1534
|
+
return cmdPush(config, options, ui);
|
|
1535
|
+
}
|
|
1536
|
+
case "shot":
|
|
1537
|
+
case "snap": {
|
|
1538
|
+
let config = null;
|
|
1539
|
+
try {
|
|
1540
|
+
config = loadConfig({ configPath: options.config, cwd: options.cwd });
|
|
1541
|
+
} catch {
|
|
1542
|
+
config = null;
|
|
1543
|
+
}
|
|
1544
|
+
return cmdShot(config, options, ui);
|
|
1545
|
+
}
|
|
1359
1546
|
case "mesh": {
|
|
1360
1547
|
let config = null;
|
|
1361
1548
|
try {
|
package/src/config.js
CHANGED
|
@@ -5,7 +5,8 @@ import { parseYaml, YamlError } from "./yaml.js";
|
|
|
5
5
|
|
|
6
6
|
const CONFIG_BASENAMES = ["pi-plus.yml", "pi-plus.yaml", "plus.yml", "plus.yaml"];
|
|
7
7
|
|
|
8
|
-
const
|
|
8
|
+
const PUSH_KEYS = new Set(["target", "session", "port", "dir"]);
|
|
9
|
+
const TOP_LEVEL_KEYS = new Set(["version", "tmux", "defaults", "sessions", "push"]);
|
|
9
10
|
const SESSION_KEYS = new Set([
|
|
10
11
|
"name",
|
|
11
12
|
"cwd",
|
|
@@ -333,10 +334,25 @@ export function normalizeConfig(raw, { configPath = "<config>" } = {}) {
|
|
|
333
334
|
}
|
|
334
335
|
}
|
|
335
336
|
|
|
337
|
+
const pushRaw = raw.push && typeof raw.push === "object" && !Array.isArray(raw.push) ? raw.push : {};
|
|
338
|
+
for (const key of Object.keys(pushRaw)) {
|
|
339
|
+
if (!PUSH_KEYS.has(key)) warnings.push(`${configPath}: unknown push key "${key}" (ignored)`);
|
|
340
|
+
}
|
|
341
|
+
const push = {
|
|
342
|
+
target: pushRaw.target ? String(pushRaw.target) : null,
|
|
343
|
+
session: pushRaw.session ? String(pushRaw.session) : null,
|
|
344
|
+
port: pushRaw.port === undefined || pushRaw.port === null ? null : Number(pushRaw.port),
|
|
345
|
+
dir: pushRaw.dir ? String(pushRaw.dir) : null,
|
|
346
|
+
};
|
|
347
|
+
if (push.port !== null && (!Number.isInteger(push.port) || push.port < 1 || push.port > 65535)) {
|
|
348
|
+
throw new ConfigError(`${configPath}: push.port must be a port number (got "${pushRaw.port}")`);
|
|
349
|
+
}
|
|
350
|
+
|
|
336
351
|
return {
|
|
337
352
|
path: configPath,
|
|
338
353
|
version: raw.version ?? 1,
|
|
339
354
|
tmuxSocket: tmux.socket ? String(tmux.socket) : null,
|
|
355
|
+
push,
|
|
340
356
|
sessions,
|
|
341
357
|
warnings,
|
|
342
358
|
};
|
package/src/help.js
CHANGED
|
@@ -154,6 +154,81 @@ export const COMMANDS = [
|
|
|
154
154
|
examples: ['pp send backend "run the tests"', 'pp send 3 "yes" --no-enter'],
|
|
155
155
|
see: ["logs", "attach"],
|
|
156
156
|
},
|
|
157
|
+
{
|
|
158
|
+
name: "push",
|
|
159
|
+
aliases: ["put", "upload"],
|
|
160
|
+
summary: "Copy a file to another machine and type its path into a tmux pane",
|
|
161
|
+
usage: "pp push <file> [options]",
|
|
162
|
+
details: [
|
|
163
|
+
"Sends one file over ssh and prefills its remote path into a tmux session,",
|
|
164
|
+
"so a screenshot or a log lands exactly where you would have typed it.",
|
|
165
|
+
"",
|
|
166
|
+
"Where it goes, in order: --push <target>, $PP_PUSH_TARGET, the `push:` block",
|
|
167
|
+
"in the config, the ssh client found in this shell's process table, and",
|
|
168
|
+
"finally the local hostname. A target is [user@]host[:port][#session] —",
|
|
169
|
+
"`pp push a.png --push hardy@1.2.3.4:2222#delta` is allowed.",
|
|
170
|
+
"",
|
|
171
|
+
"Authentication is left entirely to ssh: the command opens (or reuses) a",
|
|
172
|
+
"ControlMaster connection under ~/.ssh/cm-pp-*, so a password typed once",
|
|
173
|
+
"keeps working for --persist seconds (default 600) without touching",
|
|
174
|
+
"~/.ssh/config. Keys and the agent work as usual.",
|
|
175
|
+
"",
|
|
176
|
+
"Files land in ~/.pi/plus/drops/<session>/ by default (override with",
|
|
177
|
+
"--remote-dir or `push.dir`). The path is typed into the pane with",
|
|
178
|
+
"`tmux send-keys -l` and no Enter is pressed — you decide when to send it.",
|
|
179
|
+
].join("\n"),
|
|
180
|
+
options: [
|
|
181
|
+
"--push <target> [user@]host[:port][#session]",
|
|
182
|
+
"--to <session> tmux session on the remote side (default: the attached one)",
|
|
183
|
+
"--remote-dir <dir> remote directory (default ~/.pi/plus/drops/<session>)",
|
|
184
|
+
"--no-prefill copy the file but type nothing",
|
|
185
|
+
"--persist <secs> how long the ssh master connection stays alive (default 600)",
|
|
186
|
+
"--control-path <p> ControlMaster socket (~/.ssh/cm-pp-%r@%h-%p)",
|
|
187
|
+
"--no-detect never guess the target from the process table",
|
|
188
|
+
"--socket <name> tmux socket on the remote side",
|
|
189
|
+
"--dry-run print every ssh/scp command instead of running it",
|
|
190
|
+
"--json machine-readable result",
|
|
191
|
+
],
|
|
192
|
+
examples: [
|
|
193
|
+
"pp push ./crash.log --push hardy@1.2.3.4:delta",
|
|
194
|
+
"pp push ./screen.png --push delta",
|
|
195
|
+
"PP_PUSH_TARGET=mybox:delta pp push ./a.png",
|
|
196
|
+
"pp push ./a.png --push mybox --to risk-01 --no-prefill",
|
|
197
|
+
"pp push ./a.png --push mybox:delta --dry-run",
|
|
198
|
+
],
|
|
199
|
+
see: ["shot", "send", "status"],
|
|
200
|
+
},
|
|
201
|
+
{
|
|
202
|
+
name: "shot",
|
|
203
|
+
aliases: ["snap"],
|
|
204
|
+
summary: "Screenshot on macOS and push it into a remote pi session",
|
|
205
|
+
usage: "pp shot [options]",
|
|
206
|
+
details: [
|
|
207
|
+
"Takes a screenshot (screencapture -i: pick an area) and runs `pp push` on",
|
|
208
|
+
"it, so the remote pane receives the path of the image — no clipboard, no",
|
|
209
|
+
"paste, no upload. `--clipboard` uses the image already on the pasteboard",
|
|
210
|
+
"instead of taking a new shot; `--full` captures the whole screen.",
|
|
211
|
+
"",
|
|
212
|
+
"This is the macOS side of the workflow: pi runs on the machine you ssh",
|
|
213
|
+
"into, you take screenshots on the machine you sit at. Because the path is",
|
|
214
|
+
"typed rather than pasted, it survives any terminal, multiplexer or latency.",
|
|
215
|
+
"",
|
|
216
|
+
"Needs macOS for the capture step (pp push works everywhere); the target",
|
|
217
|
+
"resolution, ssh connection reuse and prefill behave exactly like `pp push`.",
|
|
218
|
+
].join("\n"),
|
|
219
|
+
options: [
|
|
220
|
+
"--clipboard use the image already on the clipboard",
|
|
221
|
+
"--full capture the whole screen (no area selection)",
|
|
222
|
+
"--out-dir <dir> where the local copy is written (~/.pi/plus/cache)",
|
|
223
|
+
"plus every option of `pp push` (--push/--to/--no-prefill/--dry-run/--json)",
|
|
224
|
+
],
|
|
225
|
+
examples: [
|
|
226
|
+
"pp shot --push hardy@1.2.3.4:delta",
|
|
227
|
+
"pp shot --clipboard --push mybox",
|
|
228
|
+
"PP_PUSH_TARGET=mybox:delta pp shot",
|
|
229
|
+
],
|
|
230
|
+
see: ["push", "attach"],
|
|
231
|
+
},
|
|
157
232
|
{
|
|
158
233
|
name: "mesh",
|
|
159
234
|
aliases: [],
|
package/src/push.js
ADDED
|
@@ -0,0 +1,393 @@
|
|
|
1
|
+
// Push a local file to another machine over ssh and prefill it into a tmux
|
|
2
|
+
// session there. Almost nothing here knows about ssh authentication: the
|
|
3
|
+
// strings are handed to the system `ssh` / `scp`, which read ~/.ssh/config,
|
|
4
|
+
// the agent and the ControlMaster socket on its own.
|
|
5
|
+
import { spawnSync } from "node:child_process";
|
|
6
|
+
import { existsSync, mkdirSync, statSync } from "node:fs";
|
|
7
|
+
import { homedir, hostname as osHostname } from "node:os";
|
|
8
|
+
import { basename, dirname, join } from "node:path";
|
|
9
|
+
import { expandPath, resolve, shellQuote } from "./config.js";
|
|
10
|
+
|
|
11
|
+
/** How long the reused ssh master connection is kept alive. */
|
|
12
|
+
export const DEFAULT_PERSIST_SECONDS = 600;
|
|
13
|
+
/** ControlMaster socket template: one per user@host:port. */
|
|
14
|
+
export const CONTROL_PATH_TEMPLATE = "~/.ssh/cm-pp-%r@%h-%p";
|
|
15
|
+
/** Where drops land on the remote side, before the per-session directory. */
|
|
16
|
+
export const DEFAULT_DROPS_ROOT = "~/.pi/plus/drops";
|
|
17
|
+
|
|
18
|
+
export class PushError extends Error {
|
|
19
|
+
constructor(message, code = "push") {
|
|
20
|
+
super(message);
|
|
21
|
+
this.name = "PushError";
|
|
22
|
+
this.code = code;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Parse a push target. Accepted shapes:
|
|
28
|
+
*
|
|
29
|
+
* host host
|
|
30
|
+
* user@host user@host
|
|
31
|
+
* host:2222 port
|
|
32
|
+
* host:delta tmux session on the remote side
|
|
33
|
+
* user@host:2222#delta port and session
|
|
34
|
+
*/
|
|
35
|
+
export function parsePushTarget(spec) {
|
|
36
|
+
const raw = String(spec ?? "").trim();
|
|
37
|
+
if (!raw) throw new PushError("empty ssh target", "target");
|
|
38
|
+
|
|
39
|
+
let rest = raw;
|
|
40
|
+
let session = null;
|
|
41
|
+
const hash = rest.lastIndexOf("#");
|
|
42
|
+
if (hash !== -1) {
|
|
43
|
+
session = rest.slice(hash + 1) || null;
|
|
44
|
+
rest = rest.slice(0, hash);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
let port = null;
|
|
48
|
+
const colon = rest.lastIndexOf(":");
|
|
49
|
+
if (colon !== -1) {
|
|
50
|
+
const head = rest.slice(0, colon);
|
|
51
|
+
const tail = rest.slice(colon + 1);
|
|
52
|
+
if (head.includes(":")) {
|
|
53
|
+
throw new PushError(`"${spec}" has too many ":" — use [user@]host[:port][#session]`, "target");
|
|
54
|
+
}
|
|
55
|
+
if (!head) throw new PushError(`"${spec}" has no host part`, "target");
|
|
56
|
+
if (!tail) throw new PushError(`"${spec}" ends with ":" — use host:port or host#session`, "target");
|
|
57
|
+
rest = head;
|
|
58
|
+
if (/^\d+$/.test(tail)) port = Number(tail);
|
|
59
|
+
else session = tail;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
const at = rest.lastIndexOf("@");
|
|
63
|
+
const user = at === -1 ? null : rest.slice(0, at);
|
|
64
|
+
const host = at === -1 ? rest : rest.slice(at + 1);
|
|
65
|
+
if (!host) throw new PushError(`"${spec}" has no host part`, "target");
|
|
66
|
+
if (user === "") throw new PushError(`"${spec}" has an empty user part`, "target");
|
|
67
|
+
if (port !== null && (!Number.isInteger(port) || port < 1 || port > 65535)) {
|
|
68
|
+
throw new PushError(`"${spec}" has an invalid port`, "target");
|
|
69
|
+
}
|
|
70
|
+
if (session !== null && !/^[A-Za-z0-9][A-Za-z0-9_-]*$/.test(session)) {
|
|
71
|
+
throw new PushError(`"${spec}" has an invalid tmux session name "${session}"`, "target");
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
return {
|
|
75
|
+
raw,
|
|
76
|
+
user,
|
|
77
|
+
host,
|
|
78
|
+
port,
|
|
79
|
+
session,
|
|
80
|
+
target: `${user ? `${user}@` : ""}${host}`,
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** Resolve the ControlMaster socket path (~ expanded by the caller's shell normally). */
|
|
85
|
+
export function controlPathPath(template = CONTROL_PATH_TEMPLATE, home = homedir()) {
|
|
86
|
+
return expandPath(template, process.env, home);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** Options every ssh/scp call shares, so they all land on the same master. */
|
|
90
|
+
export function sshBaseArgs(target, { controlPath = null, port = null } = {}) {
|
|
91
|
+
const args = [];
|
|
92
|
+
if (port) args.push("-p", String(port));
|
|
93
|
+
if (controlPath) args.push("-o", `ControlPath=${controlPath}`);
|
|
94
|
+
return args;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** Parse `ps -axo pid=,command=` output for the most recent ssh client. */
|
|
98
|
+
export function parseActiveSsh(psOutput) {
|
|
99
|
+
const found = [];
|
|
100
|
+
for (const line of String(psOutput).split("\n")) {
|
|
101
|
+
const match = /^\s*(\d+)\s+(.+)$/.exec(line);
|
|
102
|
+
if (!match) continue;
|
|
103
|
+
const pid = Number(match[1]);
|
|
104
|
+
const argv = match[2].trim().split(/\s+/);
|
|
105
|
+
if (!argv.length) continue;
|
|
106
|
+
const binary = argv[0];
|
|
107
|
+
if (binary !== "ssh" && !binary.endsWith("/ssh")) continue;
|
|
108
|
+
const rest = argv.slice(1);
|
|
109
|
+
// `ssh -O check`, `ssh -M -N -f` and friends are connection plumbing, not logins.
|
|
110
|
+
if (rest.includes("-O") || rest.includes("-N") || rest.includes("-M")) continue;
|
|
111
|
+
const operand = sshOperand(rest);
|
|
112
|
+
if (!operand?.operand) continue;
|
|
113
|
+
try {
|
|
114
|
+
const parsed = parsePushTarget(operand.operand);
|
|
115
|
+
found.push({ pid, ...parsed, port: parsed.port ?? operand.port });
|
|
116
|
+
} catch {
|
|
117
|
+
// not something we can push to (ProxyJump hosts, `ssh -O`, …)
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
if (!found.length) return null;
|
|
121
|
+
found.sort((a, b) => b.pid - a.pid);
|
|
122
|
+
return found[0];
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** First non-option operand of an ssh argv (options that take a value are skipped). */
|
|
126
|
+
function sshOperand(args) {
|
|
127
|
+
const withValue = new Set([
|
|
128
|
+
"-b", "-c", "-D", "-e", "-F", "-I", "-i", "-J", "-L", "-l", "-m", "-O",
|
|
129
|
+
"-o", "-p", "-Q", "-R", "-S", "-W", "-w",
|
|
130
|
+
]);
|
|
131
|
+
let port = null;
|
|
132
|
+
for (let i = 0; i < args.length; i += 1) {
|
|
133
|
+
const arg = args[i];
|
|
134
|
+
if (arg.startsWith("-")) {
|
|
135
|
+
if (withValue.has(arg)) {
|
|
136
|
+
if (arg === "-p") port = Number(args[i + 1]) || null;
|
|
137
|
+
i += 1;
|
|
138
|
+
}
|
|
139
|
+
continue;
|
|
140
|
+
}
|
|
141
|
+
return { operand: arg, port };
|
|
142
|
+
}
|
|
143
|
+
return null;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** Detect the ssh host this shell most likely belongs to, from the process table. */
|
|
147
|
+
export function detectActiveSshTarget({ psOutput = null } = {}) {
|
|
148
|
+
if (psOutput !== null) return parseActiveSsh(psOutput);
|
|
149
|
+
const result = spawnSync("ps", ["-axo", "pid=,command="], { encoding: "utf8" });
|
|
150
|
+
if (result.status !== 0) return null;
|
|
151
|
+
return parseActiveSsh(result.stdout || "");
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* Work out where a push goes. Precedence:
|
|
156
|
+
* --push/--to spec → $PP_PUSH_TARGET → config `push:` block → detected ssh → hostname
|
|
157
|
+
*/
|
|
158
|
+
export function resolvePushTarget({
|
|
159
|
+
spec = null,
|
|
160
|
+
env = process.env,
|
|
161
|
+
configPush = null,
|
|
162
|
+
detected = null,
|
|
163
|
+
host = osHostname(),
|
|
164
|
+
} = {}) {
|
|
165
|
+
let chosen = spec ?? env.PP_PUSH_TARGET ?? configPush?.target ?? null;
|
|
166
|
+
let source = spec ? "argument" : env.PP_PUSH_TARGET ? "PP_PUSH_TARGET" : configPush?.target ? "config" : null;
|
|
167
|
+
if (!chosen && detected) {
|
|
168
|
+
chosen = detected.raw ?? detected.target;
|
|
169
|
+
source = "detected";
|
|
170
|
+
}
|
|
171
|
+
if (!chosen) {
|
|
172
|
+
chosen = host;
|
|
173
|
+
source = "hostname";
|
|
174
|
+
}
|
|
175
|
+
const parsed = parsePushTarget(chosen);
|
|
176
|
+
const session = configPush?.session && !parsed.session ? parsePushTarget(`x@x#${configPush.session}`).session : parsed.session;
|
|
177
|
+
return { ...parsed, session, source, port: parsed.port ?? (configPush?.port ? Number(configPush.port) : null) };
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/** Remote directory a drop lands in. */
|
|
181
|
+
export function remoteDropsDir({ session = null, dir = null, dropsRoot = DEFAULT_DROPS_ROOT } = {}) {
|
|
182
|
+
const root = dir || join(dropsRoot, session || "inbox");
|
|
183
|
+
return root;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/** Remote argv that types the path into a tmux pane (literal, no Enter). */
|
|
187
|
+
export function tmuxPrefillArgs({ session, path, socket = null }) {
|
|
188
|
+
if (!session) throw new PushError("a tmux session name is required to prefill", "target");
|
|
189
|
+
const args = [];
|
|
190
|
+
if (socket) args.push("-L", socket);
|
|
191
|
+
args.push("send-keys", "-t", `=${session}:`, "-l", "--", path);
|
|
192
|
+
return args;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/** Remote command that prints the most recently active attached session. */
|
|
196
|
+
export function attachedSessionArgs({ socket = null } = {}) {
|
|
197
|
+
const args = [];
|
|
198
|
+
if (socket) args.push("-L", socket);
|
|
199
|
+
args.push("list-clients", "-F", "#{client_activity} #{client_session}");
|
|
200
|
+
return args;
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/** Pick the newest attached session from `list-clients` output. */
|
|
204
|
+
export function parseAttachedSession(output) {
|
|
205
|
+
const rows = String(output)
|
|
206
|
+
.split("\n")
|
|
207
|
+
.map((line) => line.trim())
|
|
208
|
+
.filter(Boolean)
|
|
209
|
+
.map((line) => {
|
|
210
|
+
const [activity, session] = line.split(/\s+/, 2);
|
|
211
|
+
return { activity: Number(activity) || 0, session };
|
|
212
|
+
})
|
|
213
|
+
.filter((row) => row.session);
|
|
214
|
+
if (!rows.length) return null;
|
|
215
|
+
rows.sort((a, b) => b.activity - a.activity);
|
|
216
|
+
return rows[0].session;
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/** A file that is safe to hand to scp and to type into a shell. */
|
|
220
|
+
export function assertReadableFile(path) {
|
|
221
|
+
const abs = resolve(expandPath(String(path)));
|
|
222
|
+
if (!existsSync(abs)) throw new PushError(`no such file: ${abs}`, "file");
|
|
223
|
+
const info = statSync(abs);
|
|
224
|
+
if (!info.isFile()) throw new PushError(`not a regular file: ${abs}`, "file");
|
|
225
|
+
return abs;
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/** Timestamped name used for drops, derived from whatever the editor gave us. */
|
|
229
|
+
export function dropName(file, now = new Date()) {
|
|
230
|
+
const stamp = [
|
|
231
|
+
now.getFullYear(),
|
|
232
|
+
String(now.getMonth() + 1).padStart(2, "0"),
|
|
233
|
+
String(now.getDate()).padStart(2, "0"),
|
|
234
|
+
].join("-");
|
|
235
|
+
const clock = [now.getHours(), now.getMinutes(), now.getSeconds()].map((n) => String(n).padStart(2, "0")).join("");
|
|
236
|
+
const base = basename(file).replace(/[^A-Za-z0-9._-]+/g, "-").replace(/^-+|-+$/g, "") || "drop";
|
|
237
|
+
return `${stamp}_${clock}-${base}`;
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/** Whether an ssh master is alive for this target. */
|
|
241
|
+
export function masterAlive(target, { controlPath, port = null } = {}) {
|
|
242
|
+
const result = spawnSync(
|
|
243
|
+
"ssh",
|
|
244
|
+
[...sshBaseArgs(target.target, { controlPath, port }), "-O", "check", target.target],
|
|
245
|
+
{ encoding: "utf8" },
|
|
246
|
+
);
|
|
247
|
+
return result.status === 0;
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
/** Start (or reuse) a background master connection; may prompt for a password once. */
|
|
251
|
+
export function ensureMaster(target, { controlPath, port = null, persistSeconds = DEFAULT_PERSIST_SECONDS, ui = null } = {}) {
|
|
252
|
+
if (masterAlive(target, { controlPath, port })) {
|
|
253
|
+
ui?.info?.(`reusing ssh connection to ${target.target}`);
|
|
254
|
+
return { reused: true };
|
|
255
|
+
}
|
|
256
|
+
if (ui?.verbose) ui.info?.(`opening a connection to ${target.target} (a password prompt can appear here once)`);
|
|
257
|
+
const args = [
|
|
258
|
+
...sshBaseArgs(target.target, { controlPath, port }),
|
|
259
|
+
"-M",
|
|
260
|
+
"-N",
|
|
261
|
+
"-f",
|
|
262
|
+
"-o",
|
|
263
|
+
`ControlPersist=${persistSeconds}`,
|
|
264
|
+
target.target,
|
|
265
|
+
];
|
|
266
|
+
const result = spawnSync("ssh", args, { stdio: "inherit" });
|
|
267
|
+
if (result.status !== 0) {
|
|
268
|
+
throw new PushError(
|
|
269
|
+
`cannot open an ssh connection to ${target.target} (exit ${result.status ?? "?"}); check the host and your key/password`,
|
|
270
|
+
"auth",
|
|
271
|
+
);
|
|
272
|
+
}
|
|
273
|
+
return { reused: false };
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
/** Run a command on the remote side and return stdout. */
|
|
277
|
+
export function sshRun(target, command, { controlPath, port = null, inherit = false } = {}) {
|
|
278
|
+
// A remote command that starts with "-" (tmux -L …) would be eaten by the
|
|
279
|
+
// remote login shell's own option parsing; hand it to `sh -c` instead.
|
|
280
|
+
const remote = String(command).startsWith("-") ? `sh -c -- ${shellQuote(command)}` : String(command);
|
|
281
|
+
const argv = [...sshBaseArgs(target.target, { controlPath, port }), "--", target.target, remote];
|
|
282
|
+
const result = spawnSync("ssh", argv, {
|
|
283
|
+
encoding: "utf8",
|
|
284
|
+
stdio: inherit ? "inherit" : ["ignore", "pipe", "pipe"],
|
|
285
|
+
});
|
|
286
|
+
if (result.status !== 0) {
|
|
287
|
+
const detail = (result.stderr || "").trim();
|
|
288
|
+
throw new PushError(
|
|
289
|
+
`ssh ${target.target} failed (exit ${result.status ?? "?"})${detail ? `: ${detail.split("\n")[0]}` : ""}`,
|
|
290
|
+
"remote",
|
|
291
|
+
);
|
|
292
|
+
}
|
|
293
|
+
return result.stdout || "";
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
/** Copy one file to the remote side. */
|
|
297
|
+
export function scpTo(target, file, remotePath, { controlPath, port = null } = {}) {
|
|
298
|
+
const result = spawnSync(
|
|
299
|
+
"scp",
|
|
300
|
+
[...sshBaseArgs(target.target, { controlPath, port }).map((arg) => (arg === "-p" ? "-P" : arg)), file, `${target.target}:${remotePath}`],
|
|
301
|
+
{ encoding: "utf8" },
|
|
302
|
+
);
|
|
303
|
+
if (result.status !== 0) {
|
|
304
|
+
const detail = (result.stderr || "").trim();
|
|
305
|
+
throw new PushError(
|
|
306
|
+
`scp to ${target.target} failed (exit ${result.status ?? "?"})${detail ? `: ${detail.split("\n")[0]}` : ""}`,
|
|
307
|
+
"remote",
|
|
308
|
+
);
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
/**
|
|
313
|
+
* Turn `~/x` into an absolute remote path: scp and `mkdir` both run under a
|
|
314
|
+
* remote shell that may quote differently, so we ask the remote side for $HOME
|
|
315
|
+
* once and use absolute paths everywhere afterwards.
|
|
316
|
+
*/
|
|
317
|
+
export async function resolveRemoteDir(dir, target, controlPath = null, runner = sshRun) {
|
|
318
|
+
const path = String(dir ?? "");
|
|
319
|
+
if (!path.startsWith("~")) return path;
|
|
320
|
+
if (path !== "~" && !path.startsWith("~/")) return path;
|
|
321
|
+
const home = runner(target, 'printf %s "$HOME"', { controlPath, port: target.port }).trim();
|
|
322
|
+
if (!home) throw new PushError(`cannot resolve $HOME on ${target.target}`, "remote");
|
|
323
|
+
return path === "~" ? home : `${home}/${path.slice(2)}`;
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
/**
|
|
327
|
+
* Full push: mkdir remote dir, scp the file, then type its path into a tmux pane.
|
|
328
|
+
* Returns a description of what was done (also used for --json).
|
|
329
|
+
*/
|
|
330
|
+
export async function pushFile({
|
|
331
|
+
file,
|
|
332
|
+
target,
|
|
333
|
+
session = null,
|
|
334
|
+
remoteDir = null,
|
|
335
|
+
socket = null,
|
|
336
|
+
prefill = true,
|
|
337
|
+
controlPath = controlPathPath(),
|
|
338
|
+
typeIntoPane = true,
|
|
339
|
+
} = {}) {
|
|
340
|
+
const abs = assertReadableFile(file);
|
|
341
|
+
const dir = await resolveRemoteDir(remoteDir ?? remoteDropsDir({ session }), target, controlPath);
|
|
342
|
+
const remotePath = `${dir}/${basename(abs)}`;
|
|
343
|
+
const steps = [];
|
|
344
|
+
|
|
345
|
+
sshRun(target, `mkdir -p ${shellQuote(dir)}`, { controlPath, port: target.port });
|
|
346
|
+
steps.push(`mkdir ${dir}`);
|
|
347
|
+
|
|
348
|
+
scpTo(target, abs, remotePath, { controlPath, port: target.port });
|
|
349
|
+
steps.push(`scp ${abs} → ${target.target}:${remotePath}`);
|
|
350
|
+
|
|
351
|
+
let usedSession = session;
|
|
352
|
+
if (!usedSession) {
|
|
353
|
+
const attached = parseAttachedSession(
|
|
354
|
+
sshRun(target, shellQuoteArgs(["tmux", ...attachedSessionArgs({ socket })]), { controlPath, port: target.port }),
|
|
355
|
+
);
|
|
356
|
+
usedSession = attached;
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
if (prefill && typeIntoPane) {
|
|
360
|
+
if (!usedSession) {
|
|
361
|
+
throw new PushError(
|
|
362
|
+
`copied to ${target.target}:${remotePath}, but nothing is attached there; pass --to <session>`,
|
|
363
|
+
"target",
|
|
364
|
+
);
|
|
365
|
+
}
|
|
366
|
+
sshRun(target, shellQuoteArgs(["tmux", ...tmuxPrefillArgs({ session: usedSession, path: remotePath, socket })]), {
|
|
367
|
+
controlPath,
|
|
368
|
+
port: target.port,
|
|
369
|
+
});
|
|
370
|
+
steps.push(`prefilled ${usedSession}`);
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
return { host: target.target, session: usedSession, remotePath, steps };
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
/** Join argv into a single shell command string for the remote side. */
|
|
377
|
+
export function shellQuoteArgs(args) {
|
|
378
|
+
return args.map((arg) => shellQuote(arg)).join(" ");
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
/** Directory helper shared with the CLI so --dir/--name behave predictably. */
|
|
382
|
+
export function dropDir({ root = DEFAULT_DROPS_ROOT, session = null, dir = null } = {}) {
|
|
383
|
+
const target = dir || (session ? join(root, session) : root);
|
|
384
|
+
return target;
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
/** Make sure the local directory for a screenshot exists. */
|
|
388
|
+
export function ensureLocalDir(dir) {
|
|
389
|
+
mkdirSync(dir, { recursive: true });
|
|
390
|
+
return dir;
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
export { dirname, join };
|