nodehop 0.2.0__py3-none-any.whl

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.
nodehop/deploy.py ADDED
@@ -0,0 +1,205 @@
1
+ """`nodehop deploy user@host`: set up the other machine from this one, over SSH.
2
+
3
+ One agent (or one person) on one machine is enough: as soon as this machine
4
+ can open an SSH session on the other one, NodeHop copies itself there,
5
+ installs itself, runs `setup` there and pairs the two machines. No token has
6
+ to be carried by hand. Run it from the primary: the other machine must accept
7
+ SSH, the primary never has to.
8
+
9
+ The very first SSH access is the only human step. If NodeHop's key is not
10
+ accepted yet, an interactive run offers `ssh-copy-id`: the password is typed
11
+ by the person into ssh itself, never seen or stored by NodeHop.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import getpass
17
+ import json
18
+ import shutil
19
+ import tempfile
20
+ from pathlib import Path
21
+ from typing import Callable, Optional, Tuple
22
+
23
+ import nodehop
24
+ from nodehop import pairing
25
+ from nodehop.config import Config, ConfigError, Peer
26
+ from nodehop.runner import Runner
27
+ from nodehop.transport import SSHTransport
28
+
29
+ REMOTE_SRC = ".local/share/nodehop-src" # relative to the remote home folder
30
+
31
+ MINIMAL_PYPROJECT = f"""[build-system]
32
+ requires = ["setuptools>=61"]
33
+ build-backend = "setuptools.build_meta"
34
+
35
+ [project]
36
+ name = "nodehop"
37
+ version = "{nodehop.__version__}"
38
+ requires-python = ">=3.9"
39
+ dependencies = []
40
+
41
+ [project.scripts]
42
+ nodehop = "nodehop.cli:main"
43
+
44
+ [tool.setuptools.packages.find]
45
+ include = ["nodehop*"]
46
+ """
47
+
48
+ # Used when pipx is missing on the other machine: runs NodeHop straight from the copied source.
49
+ WRAPPER = """#!/bin/sh
50
+ DIR="$HOME/.local/share/nodehop-src"
51
+ PYTHONPATH="$DIR${PYTHONPATH:+:$PYTHONPATH}" exec python3 -m nodehop "$@"
52
+ """
53
+
54
+ INSTALL_SCRIPT = (
55
+ f'if command -v pipx >/dev/null 2>&1 && pipx install --force "$HOME/{REMOTE_SRC}" >/dev/null 2>&1; '
56
+ f"then echo pipx; "
57
+ f'else mkdir -p "$HOME/.local/bin" && cp "$HOME/{REMOTE_SRC}/bin/nodehop" "$HOME/.local/bin/nodehop" '
58
+ f'&& chmod +x "$HOME/.local/bin/nodehop" && echo wrapper; fi'
59
+ )
60
+
61
+
62
+ class DeployError(Exception):
63
+ pass
64
+
65
+
66
+ def split_destination(destination: str) -> Tuple[str, str, Optional[int]]:
67
+ """user@host[:port] -> (user, host, port). The user defaults to this machine's."""
68
+ if "@" in destination:
69
+ user, host = destination.split("@", 1)
70
+ else:
71
+ user, host = getpass.getuser(), destination
72
+ port = None
73
+ if host.count(":") == 1: # host:port (a bare IPv6 address has several colons)
74
+ host, raw = host.split(":")
75
+ if not raw.isdigit():
76
+ raise ConfigError(f"bad port in '{destination}'")
77
+ port = int(raw)
78
+ if not user or not host:
79
+ raise ConfigError(f"bad destination '{destination}': expected user@host[:port]")
80
+ return user, host, port
81
+
82
+
83
+ def make_bundle() -> Path:
84
+ """A copy of this NodeHop, installable on the other machine."""
85
+ pkg = Path(nodehop.__file__).resolve().parent
86
+ out = Path(tempfile.mkdtemp(prefix="nodehop-bundle-"))
87
+ shutil.copytree(pkg, out / "nodehop", ignore=shutil.ignore_patterns("__pycache__", "*.pyc"))
88
+ repo_pyproject = pkg.parent / "pyproject.toml"
89
+ if repo_pyproject.exists() and "nodehop" in repo_pyproject.read_text():
90
+ shutil.copy(repo_pyproject, out / "pyproject.toml")
91
+ else:
92
+ (out / "pyproject.toml").write_text(MINIMAL_PYPROJECT)
93
+ for extra in ("README.md", "LICENSE"):
94
+ if (pkg.parent / extra).exists():
95
+ shutil.copy(pkg.parent / extra, out / extra)
96
+ (out / "bin").mkdir()
97
+ (out / "bin" / "nodehop").write_text(WRAPPER)
98
+ (out / "bin" / "nodehop").chmod(0o755)
99
+ return out
100
+
101
+
102
+ def _json(result) -> dict:
103
+ lines = [l for l in (result.stdout or "").strip().splitlines() if l.strip()]
104
+ text = "\n".join(lines)
105
+ start = text.find("{")
106
+ if start < 0:
107
+ raise DeployError(f"unexpected answer: {text or result.stderr}")
108
+ return json.loads(text[start:])
109
+
110
+
111
+ def deploy(
112
+ cfg: Config,
113
+ runner: Runner,
114
+ destination: str,
115
+ name: Optional[str] = None,
116
+ interactive: bool = False,
117
+ say: Optional[Callable[[str], None]] = None,
118
+ hooks: bool = True,
119
+ ) -> dict:
120
+ """Install, set up and pair the machine at `destination` (user@host) with this one."""
121
+ say = say or runner.log
122
+ user, host, port = split_destination(destination)
123
+ peer = Peer(name=name or pairing.suggested_name(host), host=host, user=user, port=port)
124
+ transport = SSHTransport(peer, runner, cfg.extra_path, ssh_key=cfg.ssh_key_path())
125
+ report = {"peer": peer.name, "destination": peer.destination}
126
+
127
+ # 1. SSH access ---------------------------------------------------------------
128
+ say(f"Connecting to {peer.destination}…")
129
+ if transport.remote(["true"], check=False, timeout=30, mutating=False).returncode != 0:
130
+ pub = str(cfg.ssh_key_path()) + ".pub"
131
+ if not interactive:
132
+ raise DeployError(
133
+ f"cannot open an SSH session on {peer.destination} without a password yet. "
134
+ f"Ask the person to run, in a terminal: ssh-copy-id -i {pub}{f' -p {port}' if port else ''} {peer.destination} "
135
+ f"(they type the password of '{user}' once), and to check that Remote Login is on there."
136
+ )
137
+ say(f"First contact: ssh will ask for {user}'s password on {host}, once (NodeHop never sees it).")
138
+ runner.run(
139
+ # -f: ssh-copy-id's own "already installed?" probe is fooled by keys in ssh-agent.
140
+ ["ssh-copy-id", "-f", "-i", pub, *(["-p", str(port)] if port else []),
141
+ "-o", "StrictHostKeyChecking=accept-new", peer.destination],
142
+ check=False, timeout=300, interactive=True,
143
+ )
144
+ if transport.remote(["true"], check=False, timeout=30, mutating=False).returncode != 0:
145
+ raise DeployError(
146
+ f"still no SSH access to {peer.destination}. Check that Remote Login is on there "
147
+ f"(System Settings > General > Sharing) and that the user name is right."
148
+ )
149
+ report["ssh"] = "ok"
150
+
151
+ # 2. install NodeHop there ------------------------------------------------------
152
+ say(f"Installing NodeHop {nodehop.__version__} on {peer.name}…")
153
+ bundle = make_bundle()
154
+ try:
155
+ transport.push_dir(bundle, REMOTE_SRC, delete=True)
156
+ finally:
157
+ shutil.rmtree(bundle, ignore_errors=True)
158
+ method = transport.remote(["sh", "-c", INSTALL_SCRIPT], timeout=600).stdout.strip() or "dry-run"
159
+ report["install"] = method
160
+ if not runner.dry_run:
161
+ transport.nodehop("--version", mutating=False)
162
+
163
+ # 3. setup there -------------------------------------------------------------------
164
+ remote_primary = cfg.primary != cfg.machine
165
+ probe = transport.nodehop("invite", "--json", check=False, mutating=False)
166
+ if probe.returncode == 0 and not runner.dry_run:
167
+ existing = _json(probe)["machine"]
168
+ if existing != peer.name:
169
+ say(f"{host} is already set up as '{existing}': keeping that name.")
170
+ peer.name = existing
171
+ args = ["setup", "--json"]
172
+ else:
173
+ args = ["setup", "--name", peer.name, "--json"]
174
+ if remote_primary:
175
+ args.append("--primary")
176
+ say(f"Setting up {peer.name} as {'primary' if remote_primary else 'secondary'}…")
177
+ remote_setup = transport.nodehop(*args, timeout=120)
178
+ if runner.dry_run:
179
+ report["dry_run"] = True
180
+ return report
181
+ remote = _json(remote_setup)
182
+ report["remote_checks"] = remote.get("checks", [])
183
+
184
+ # 4. pair both ways ---------------------------------------------------------------
185
+ say("Pairing both machines…")
186
+ info = pairing.parse_token(remote["token"])
187
+ # The host that just worked; an existing default target is kept (adding a second server
188
+ # must not silently change where work goes when the lid closes).
189
+ pairing.pair_with(cfg, info, host=host)
190
+ cfg.peers[info["name"]].port = port
191
+ cfg.save()
192
+ my_token = pairing.make_token(cfg, pairing.local_hosts(runner))
193
+ transport.nodehop("pair", my_token, "--json", timeout=120) # there: records us, authorizes our key
194
+ report["peer_name"] = info["name"]
195
+ report["this_to_peer"] = transport.is_up()
196
+
197
+ # 5. its background job (the fallback watcher on a server; sleep hooks on a primary)
198
+ if hooks:
199
+ say(f"Installing the background job on {info['name']}…")
200
+ result = transport.nodehop("install-hooks", "--apply", "--json", check=False, timeout=900)
201
+ try:
202
+ report["remote_hooks"] = _json(result)
203
+ except (DeployError, ValueError):
204
+ report["remote_hooks"] = {"ok": False, "left": [], "error": (result.stderr or result.stdout).strip()[-300:]}
205
+ return report
nodehop/doctor.py ADDED
@@ -0,0 +1,285 @@
1
+ """`nodehop doctor`: everything a machine needs, checked one by one.
2
+
3
+ Built for agents as much as people: `--json` gives a stable list of checks,
4
+ each with a status (ok / warn / fail), what was found, and how to fix it.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import getpass
10
+ import os
11
+ import shutil
12
+ import sys
13
+ from pathlib import Path
14
+ from typing import Callable, Dict, List, Optional
15
+
16
+ from nodehop import pairing, system
17
+ from nodehop.config import Config, ConfigError
18
+ from nodehop.runner import Runner
19
+ from nodehop.transport import SSHTransport
20
+
21
+ OK, WARN, FAIL = "ok", "warn", "fail"
22
+
23
+ # What a non-interactive SSH shell or launchd sees, before NodeHop adds extra_path.
24
+ SYSTEM_PATH = ["/usr/bin", "/bin", "/usr/sbin", "/sbin"]
25
+
26
+ TOOL_FIXES = {
27
+ "ssh": "macOS: built in; Linux: `sudo apt install -y openssh-client`",
28
+ "rsync": "macOS: built in; Linux: `sudo apt install -y rsync` (or dnf/pacman)",
29
+ "tmux": "macOS: `brew install tmux`; Linux: `sudo apt install -y tmux` (or dnf/pacman)",
30
+ "claude": "install Claude Code (https://claude.com/claude-code) and log in once with `claude`",
31
+ "codex": "install Codex (https://developers.openai.com/codex/cli) and sign in with `codex login`",
32
+ "nodehop": "install NodeHop where SSH can find it: `pipx install <path-to-repo>` (lands in ~/.local/bin), or `nodehop deploy` from the primary",
33
+ }
34
+
35
+
36
+ def check(id: str, status: str, detail: str, fix: str = "") -> Dict[str, str]:
37
+ return {"id": id, "status": status, "detail": detail, "fix": fix}
38
+
39
+
40
+ def search_path(cfg: Optional[Config]) -> str:
41
+ extra = cfg.extra_path if cfg else []
42
+ home = str(Path.home())
43
+ return ":".join([p.replace("$HOME", home) for p in extra] + SYSTEM_PATH)
44
+
45
+
46
+ def run_checks(
47
+ cfg: Optional[Config],
48
+ runner: Runner,
49
+ probe: Optional[Callable[[str], bool]] = None,
50
+ peers: bool = True,
51
+ ) -> List[Dict[str, str]]:
52
+ probe = probe or pairing.tcp_open
53
+ out: List[Dict[str, str]] = []
54
+
55
+ ok_py = sys.version_info >= (3, 9)
56
+ out.append(check("python", OK if ok_py else FAIL, sys.version.split()[0], "" if ok_py else "Python 3.9+ is required"))
57
+
58
+ if cfg is None:
59
+ out.append(check("config", FAIL, f"no config at {Config.path()}", "run `nodehop setup --name <this machine>`"))
60
+ else:
61
+ role = "primary" if cfg.primary == cfg.machine else f"secondary (primary: {cfg.primary or 'not paired yet'})"
62
+ out.append(check("config", OK, f"machine '{cfg.machine}', {role}"))
63
+
64
+ path = search_path(cfg)
65
+ for tool in ("ssh", "rsync", "tmux", "nodehop"):
66
+ found = shutil.which(tool, path=path)
67
+ status = OK if found else FAIL
68
+ detail = found or "not found on the PATH that SSH sessions and background jobs use"
69
+ out.append(check(f"tool:{tool}", status, detail, "" if found else TOOL_FIXES[tool]))
70
+
71
+ # Agents: needed only if a project here uses them; at least one must be installed.
72
+ used = {p.module for p in cfg.projects.values()} if cfg else set()
73
+ agents = {"claude": "claude-code", "codex": "codex"}
74
+ found_any = False
75
+ for tool, module in agents.items():
76
+ found = shutil.which(getattr(cfg, f"{tool}_bin", tool) if cfg else tool, path=path)
77
+ found_any = found_any or bool(found)
78
+ if found:
79
+ out.append(check(f"tool:{tool}", OK, found))
80
+ elif module in used:
81
+ out.append(check(f"tool:{tool}", FAIL, f"a project here uses {tool}, which is not installed", TOOL_FIXES[tool]))
82
+ if not found_any:
83
+ out.append(check("agent", FAIL, "no agent installed (Claude Code or Codex)", TOOL_FIXES["claude"] + "; or " + TOOL_FIXES["codex"]))
84
+
85
+ if shutil.which("codex", path=path):
86
+ from nodehop.modules.codex import codex_home
87
+
88
+ signed = (codex_home() / "auth.json").exists()
89
+ out.append(check("codex-login", OK if signed else FAIL,
90
+ "Codex is signed in" if signed else "Codex is not signed in here",
91
+ "" if signed else "run `codex login` on this machine (on a headless server, over SSH, then open the link it prints)"))
92
+
93
+ if shutil.which("claude", path=path):
94
+ done = claude_first_run_done()
95
+ out.append(
96
+ check(
97
+ "claude-first-run",
98
+ OK if done else FAIL,
99
+ "Claude Code has been opened here once" if done
100
+ else "Claude Code was never opened here: a resumed agent would wait on its welcome screens",
101
+ "" if done else "run `claude` once on this machine (over SSH is fine), answer its first questions "
102
+ "(theme, sign-in…), then quit with /exit",
103
+ )
104
+ )
105
+
106
+ if cfg is not None:
107
+ key = cfg.ssh_key_path()
108
+ out.append(
109
+ check("ssh-key", OK if key.exists() else FAIL, str(key), "" if key.exists() else "run `nodehop setup`")
110
+ )
111
+
112
+ is_primary = cfg is not None and cfg.primary == cfg.machine
113
+ login = probe("127.0.0.1")
114
+ if login:
115
+ out.append(check("ssh-server", OK, "SSH server answers on port 22"))
116
+ elif is_primary:
117
+ out.append(check("ssh-server", OK, "off, and not needed: the primary only makes outgoing connections"))
118
+ else:
119
+ out.append(
120
+ check(
121
+ "ssh-server",
122
+ FAIL,
123
+ "SSH server is off: the primary cannot hand work over to this machine",
124
+ system.ssh_server_fix(),
125
+ )
126
+ )
127
+
128
+ if cfg is None:
129
+ return out
130
+
131
+ if not cfg.peers:
132
+ out.append(check("peers", FAIL, "no paired machine", "from the primary: `nodehop deploy user@host`"))
133
+ for name, peer in cfg.peers.items():
134
+ if not is_primary:
135
+ # The always-on machine must accept the primary; it never connects to it.
136
+ authorized = pairing.is_authorized(name)
137
+ out.append(
138
+ check(
139
+ f"peer:{name}:authorized",
140
+ OK if authorized else WARN,
141
+ f"{name} may log in here" if authorized
142
+ else f"{name}'s NodeHop key is not in ~/.ssh/authorized_keys (fine with Tailscale SSH or another key)",
143
+ "" if authorized else f"from {name}: `nodehop deploy` again, or `nodehop pair <token of {name}>` here",
144
+ )
145
+ )
146
+ continue
147
+ if not peers:
148
+ continue
149
+ transport = SSHTransport(peer, runner, cfg.extra_path, ssh_key=cfg.ssh_key_path())
150
+ result = transport.nodehop("ping", check=False, timeout=20, mutating=False)
151
+ reached = result.returncode == 0
152
+ detail = (result.stdout or result.stderr or "").strip().splitlines()
153
+ out.append(
154
+ check(
155
+ f"peer:{name}:reachable",
156
+ OK if reached else FAIL,
157
+ f"{peer.destination}: " + (detail[-1] if detail else f"exit {result.returncode}"),
158
+ "" if reached else f"is {name} on and connected? Otherwise on {name}: SSH server on, NodeHop "
159
+ f"installed; or run `nodehop deploy {peer.destination}` again from here",
160
+ )
161
+ )
162
+
163
+ for name, project in cfg.projects.items():
164
+ exists = Path(project.path).is_dir()
165
+ out.append(
166
+ check(
167
+ f"project:{name}",
168
+ OK if exists else WARN,
169
+ project.path if exists else f"{project.path} does not exist here yet (created on first handoff)",
170
+ )
171
+ )
172
+
173
+ home = Path.home()
174
+ os_name = system.os_name()
175
+ if is_primary and os_name == "macos":
176
+ sw = shutil.which("sleepwatcher", path=path + ":/opt/homebrew/sbin:/usr/local/sbin:/opt/homebrew/opt/sleepwatcher/sbin")
177
+ hooked = (home / ".sleep").exists() and "nodehop" in (home / ".sleep").read_text()
178
+ out.append(
179
+ check(
180
+ "lid-hooks",
181
+ OK if (sw and hooked) else WARN,
182
+ "SleepWatcher calls nodehop on sleep and wake" if (sw and hooked) else "closing the lid does not hand off yet",
183
+ "" if (sw and hooked) else "`brew install sleepwatcher`, then `nodehop install-hooks` and run what it prints",
184
+ )
185
+ )
186
+ plist = home / "Library" / "LaunchAgents" / "dev.nodehop.sync.plist"
187
+ out.append(
188
+ check(
189
+ "pre-sync",
190
+ OK if plist.exists() else WARN,
191
+ "launchd pre-sync installed" if plist.exists() else "no pre-sync: handoffs at sleep copy everything",
192
+ "" if plist.exists() else "`nodehop install-hooks`, then run what it prints",
193
+ )
194
+ )
195
+ elif is_primary and os_name == "linux":
196
+ hooked = system.sleep_hook_path().exists()
197
+ out.append(
198
+ check(
199
+ "lid-hooks",
200
+ OK if hooked else WARN,
201
+ f"{system.sleep_hook_path()} installed" if hooked else "suspend does not hand off yet",
202
+ "" if hooked else "`nodehop install-hooks`, then run what it prints (one sudo command)",
203
+ )
204
+ )
205
+ timer = home / ".config" / "systemd" / "user" / "nodehop-sync.timer"
206
+ out.append(
207
+ check(
208
+ "pre-sync",
209
+ OK if timer.exists() else WARN,
210
+ "systemd user timer installed" if timer.exists() else "no pre-sync: handoffs at sleep copy everything",
211
+ "" if timer.exists() else "`nodehop install-hooks`, then run what it prints",
212
+ )
213
+ )
214
+ if not is_primary and os_name in ("macos", "linux"):
215
+ unit = (home / "Library" / "LaunchAgents" / "dev.nodehop.watch.plist") if os_name == "macos" \
216
+ else (home / ".config" / "systemd" / "user" / "nodehop-watch.service")
217
+ on = unit.exists() and cfg.failover_minutes > 0
218
+ out.append(
219
+ check(
220
+ "fallback",
221
+ OK if on else WARN,
222
+ f"takes over after {cfg.failover_minutes} min of silence from the primary" if on
223
+ else "if the primary dies without going to sleep, its work is not resumed here",
224
+ "" if on else "`nodehop install-hooks` here, then run what it prints",
225
+ )
226
+ )
227
+ if not is_primary and os_name == "macos":
228
+ gui = runner.run(["launchctl", "print", f"gui/{os.getuid()}"], check=False, mutating=False).returncode == 0
229
+ out.append(
230
+ check(
231
+ "gui-session",
232
+ OK if gui else FAIL,
233
+ "a graphical session is open: agents run there and can read the keychain (Claude Code login)"
234
+ if gui else "nobody is logged in on the screen: agents started over SSH cannot read the keychain "
235
+ "and Claude Code reports 'Not logged in'",
236
+ "" if gui else "log in once on this Mac (Screen Sharing works), and turn on automatic login: "
237
+ "System Settings > Users & Groups > Automatically log in as (FileVault must be off)",
238
+ )
239
+ )
240
+ elif not is_primary and os_name == "linux":
241
+ linger = runner.run(["loginctl", "show-user", getpass.getuser(), "-p", "Linger", "--value"], check=False, mutating=False)
242
+ on = linger.stdout.strip() == "yes"
243
+ out.append(
244
+ check(
245
+ "linger",
246
+ OK if on else WARN,
247
+ "agents survive when no one is logged in" if on else "agents may be stopped when the last SSH session closes",
248
+ "" if on else f"`sudo loginctl enable-linger {getpass.getuser()}`",
249
+ )
250
+ )
251
+ return out
252
+
253
+
254
+ def claude_first_run_done() -> bool:
255
+ """Claude Code records the end of its first-run screens in ~/.claude.json (not a public API)."""
256
+ import json
257
+ import os
258
+
259
+ env = os.environ.get("CLAUDE_CONFIG_DIR")
260
+ settings = Path(env) / ".claude.json" if env else Path.home() / ".claude.json"
261
+ try:
262
+ return bool(json.loads(settings.read_text()).get("hasCompletedOnboarding"))
263
+ except (OSError, ValueError):
264
+ return False
265
+
266
+
267
+ def load_config() -> Optional[Config]:
268
+ try:
269
+ return Config.load()
270
+ except ConfigError:
271
+ return None
272
+
273
+
274
+ def summary(checks: List[Dict[str, str]]) -> str:
275
+ marks = {OK: "ok ", WARN: "warn", FAIL: "FAIL"}
276
+ lines = []
277
+ for c in checks:
278
+ lines.append(f"[{marks[c['status']]}] {c['id']}: {c['detail']}")
279
+ if c["fix"] and c["status"] != OK:
280
+ lines.append(f" fix: {c['fix']}")
281
+ return "\n".join(lines)
282
+
283
+
284
+ def healthy(checks: List[Dict[str, str]]) -> bool:
285
+ return all(c["status"] != FAIL for c in checks)