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/transport.py ADDED
@@ -0,0 +1,107 @@
1
+ """Talking to another machine: SSH for commands, rsync for files.
2
+
3
+ Works over any network where `ssh <host>` works without a password prompt
4
+ (NodeHop's own key from `nodehop pair`, Tailscale SSH, or any key in
5
+ ~/.ssh/authorized_keys). Paths may differ between machines: the sender asks
6
+ the receiver where each project lives there (`nodehop prepare`).
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ import shlex
13
+ from pathlib import Path
14
+ from typing import List, Optional, Sequence
15
+
16
+ from nodehop.config import Peer
17
+ from nodehop.runner import Runner
18
+
19
+ BASE_SSH_OPTS = [
20
+ "-o", "BatchMode=yes",
21
+ "-o", "ConnectTimeout=5",
22
+ "-o", "ServerAliveInterval=10",
23
+ # First contact must not stop on a yes/no prompt nobody is there to answer.
24
+ "-o", "StrictHostKeyChecking=accept-new",
25
+ ]
26
+ SSH_OPTS = BASE_SSH_OPTS # kept for backwards compatibility
27
+
28
+ # A transfer cut short (sleep, lost network) must leave the other side exactly as it was:
29
+ # new files are put in place, and old ones deleted, only once everything has arrived.
30
+ SAFE_UPDATES = ["--delay-updates"]
31
+
32
+
33
+ def quote(arg: str) -> str:
34
+ """shlex.quote, plus the words zsh (macOS's login shell) would expand: `=cmd` and `~user`."""
35
+ quoted = shlex.quote(arg)
36
+ if quoted == arg and arg[:1] in ("=", "~"):
37
+ return "'" + arg + "'"
38
+ return quoted
39
+
40
+
41
+ def ssh_opts(key: Optional[Path]) -> List[str]:
42
+ opts = list(BASE_SSH_OPTS)
43
+ if key is not None and key.exists():
44
+ opts += ["-i", str(key)]
45
+ return opts
46
+
47
+
48
+ class SSHTransport:
49
+ def __init__(self, peer: Peer, runner: Runner, extra_path: List[str], ssh_key: Optional[Path] = None):
50
+ self.peer = peer
51
+ self.runner = runner
52
+ self.extra_path = extra_path
53
+ self.opts = ssh_opts(ssh_key) + (["-p", str(peer.port)] if peer.port else [])
54
+
55
+ def _wrap(self, argv: Sequence[str]) -> str:
56
+ path = ":".join(self.extra_path + ["$PATH"])
57
+ return f'export PATH="{path}"; ' + " ".join(quote(str(a)) for a in argv)
58
+
59
+ def remote(self, argv: Sequence[str], check: bool = True, timeout: float = 120, mutating: bool = True):
60
+ return self.runner.run(
61
+ ["ssh", *self.opts, self.peer.destination, self._wrap(argv)],
62
+ check=check,
63
+ timeout=timeout,
64
+ mutating=mutating,
65
+ )
66
+
67
+ def nodehop(self, *args: str, check: bool = True, timeout: float = 120, mutating: bool = True):
68
+ return self.remote([self.peer.nodehop_bin, *args], check=check, timeout=timeout, mutating=mutating)
69
+
70
+ def is_up(self) -> bool:
71
+ """True when the peer answers and has NodeHop installed (i.e. it is awake)."""
72
+ result = self.nodehop("ping", check=False, timeout=20, mutating=False)
73
+ return result.returncode == 0
74
+
75
+ def prepare(self, name: str, module: str, origin_path: str, origin_home: str) -> dict:
76
+ """Ask the peer where `name` lives there (registering it if new) and where its inbox is.
77
+
78
+ Runs even in dry-run (passing -n along) so the plan shows real paths.
79
+ """
80
+ args = ["prepare", name, "--module", module, "--origin-path", origin_path, "--origin-home", origin_home]
81
+ if self.runner.dry_run:
82
+ args = ["-n", *args]
83
+ result = self.nodehop(*args, timeout=60, mutating=False)
84
+ return json.loads(result.stdout.strip().splitlines()[-1])
85
+
86
+ def push_dir(self, local: Path, remote: str, delete: bool, excludes: Sequence[str] = (),
87
+ timeout: float = 1800) -> None:
88
+ if not local.is_dir():
89
+ raise FileNotFoundError(f"{local} is not a directory")
90
+ self.remote(["mkdir", "-p", remote])
91
+ argv = ["rsync", "-az", *SAFE_UPDATES]
92
+ if delete:
93
+ argv.append("--delete-after")
94
+ argv += [f"--exclude={pattern}" for pattern in excludes]
95
+ # The remote side of (open)rsync splits paths on spaces: quote them.
96
+ argv += ["-e", shlex.join(["ssh", *self.opts]), f"{local}/", f"{self.peer.destination}:{shlex.quote(remote + '/')}"]
97
+ self.runner.run(argv, timeout=timeout)
98
+
99
+ def pull_dir(self, remote: str, local: Path, delete: bool, excludes: Sequence[str] = ()) -> None:
100
+ """Copy a directory of the peer into `local` (the reverse of push_dir)."""
101
+ self.runner.run(["mkdir", "-p", str(local)])
102
+ argv = ["rsync", "-az", *SAFE_UPDATES]
103
+ if delete:
104
+ argv.append("--delete-after")
105
+ argv += [f"--exclude={pattern}" for pattern in excludes]
106
+ argv += ["-e", shlex.join(["ssh", *self.opts]), f"{self.peer.destination}:{shlex.quote(remote + '/')}", f"{local}/"]
107
+ self.runner.run(argv, timeout=1800)
nodehop/ui.py ADDED
@@ -0,0 +1,140 @@
1
+ """Small terminal UI for the setup wizard: arrow-key menus, prompts with defaults.
2
+
3
+ Standard library only. Falls back to numbered choices when the terminal does
4
+ not support raw key reading (or stdin is not a terminal).
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import os
10
+ import sys
11
+ from typing import List, Optional, Sequence
12
+
13
+ try: # POSIX only; the fallback covers the rest
14
+ import termios
15
+ import tty
16
+ except ImportError: # pragma: no cover
17
+ termios = None # type: ignore
18
+ tty = None # type: ignore
19
+
20
+
21
+ def _color() -> bool:
22
+ return sys.stdout.isatty() and os.environ.get("NO_COLOR") is None and os.environ.get("TERM") != "dumb"
23
+
24
+
25
+ def style(text: str, *codes: str) -> str:
26
+ if not _color():
27
+ return text
28
+ table = {"bold": "1", "dim": "2", "green": "32", "yellow": "33", "red": "31", "cyan": "36", "magenta": "35"}
29
+ return "".join(f"\033[{table[c]}m" for c in codes) + text + "\033[0m"
30
+
31
+
32
+ def title(text: str) -> None:
33
+ print()
34
+ print(style(f" {text}", "bold", "magenta"))
35
+ print(style(" " + "─" * len(text), "dim"))
36
+
37
+
38
+ def step(text: str) -> None:
39
+ print(style(" ▸ ", "cyan") + text)
40
+
41
+
42
+ def ok(text: str) -> None:
43
+ print(style(" ✓ ", "green") + text)
44
+
45
+
46
+ def warn(text: str) -> None:
47
+ print(style(" ! ", "yellow") + text)
48
+
49
+
50
+ def fail(text: str) -> None:
51
+ print(style(" ✗ ", "red") + text)
52
+
53
+
54
+ def interactive() -> bool:
55
+ return sys.stdin.isatty() and sys.stdout.isatty()
56
+
57
+
58
+ def ask(question: str, default: Optional[str] = None) -> str:
59
+ hint = style(f" [{default}]", "dim") if default else ""
60
+ while True:
61
+ answer = input(style(" ? ", "cyan") + style(question, "bold") + hint + " ").strip()
62
+ if answer:
63
+ return answer
64
+ if default is not None:
65
+ return default
66
+
67
+
68
+ def _read_key() -> str:
69
+ fd = sys.stdin.fileno()
70
+ ch = os.read(fd, 1).decode(errors="ignore")
71
+ if ch == "\x1b":
72
+ seq = os.read(fd, 2).decode(errors="ignore")
73
+ return {"[A": "up", "[B": "down"}.get(seq, "")
74
+ if ch in ("\r", "\n"):
75
+ return "enter"
76
+ if ch == "\x03":
77
+ raise KeyboardInterrupt
78
+ if ch in ("k", "j"):
79
+ return "up" if ch == "k" else "down"
80
+ return ch
81
+
82
+
83
+ def select(question: str, options: Sequence[str], hints: Optional[Sequence[str]] = None, default: int = 0) -> int:
84
+ """Let the user pick one option; returns its index."""
85
+ hints = list(hints or [""] * len(options))
86
+ print(style(" ? ", "cyan") + style(question, "bold") + style(" (↑/↓, Enter)", "dim"))
87
+ if termios is None or not interactive():
88
+ return _select_numbered(options, hints, default)
89
+ fd = sys.stdin.fileno()
90
+ try:
91
+ saved = termios.tcgetattr(fd)
92
+ except termios.error:
93
+ return _select_numbered(options, hints, default)
94
+ current = default
95
+
96
+ def draw(first: bool) -> None:
97
+ if not first:
98
+ sys.stdout.write(f"\033[{len(options)}A")
99
+ for i, (opt, hint) in enumerate(zip(options, hints)):
100
+ mark = style("❯ ", "cyan") if i == current else " "
101
+ label = style(opt, "bold", "cyan") if i == current else opt
102
+ extra = style(f" {hint}", "dim") if hint else ""
103
+ sys.stdout.write(f"\r\033[2K {mark}{label}{extra}\n")
104
+ sys.stdout.flush()
105
+
106
+ draw(True)
107
+ try:
108
+ tty.setcbreak(fd)
109
+ while True:
110
+ key = _read_key()
111
+ if key == "up":
112
+ current = (current - 1) % len(options)
113
+ elif key == "down":
114
+ current = (current + 1) % len(options)
115
+ elif key == "enter":
116
+ break
117
+ elif key.isdigit() and 1 <= int(key) <= len(options):
118
+ current = int(key) - 1
119
+ else:
120
+ continue
121
+ draw(False)
122
+ finally:
123
+ termios.tcsetattr(fd, termios.TCSADRAIN, saved)
124
+ return current
125
+
126
+
127
+ def _select_numbered(options: Sequence[str], hints: List[str], default: int) -> int:
128
+ for i, (opt, hint) in enumerate(zip(options, hints), 1):
129
+ extra = f" ({hint})" if hint else ""
130
+ print(f" {i}. {opt}{extra}")
131
+ while True:
132
+ raw = input(f" choice [{default + 1}]: ").strip()
133
+ if not raw:
134
+ return default
135
+ if raw.isdigit() and 1 <= int(raw) <= len(options):
136
+ return int(raw) - 1
137
+
138
+
139
+ def confirm(question: str, default: bool = True) -> bool:
140
+ return select(question, ["Yes", "No"], default=0 if default else 1) == 0
nodehop/uninstall.py ADDED
@@ -0,0 +1,145 @@
1
+ """`nodehop uninstall`: remove everything NodeHop added, and nothing else.
2
+
3
+ Removed: NodeHop's agents' tmux server (their conversations are saved and can be
4
+ resumed with the agent itself), background jobs (launchd / systemd), its lines
5
+ in ~/.sleep and ~/.wakeup, NodeHop.app, the keys it authorized in
6
+ ~/.ssh/authorized_keys, its own SSH key, its folder (~/.config/nodehop: config,
7
+ state, backups, logs) and, last, the nodehop program itself.
8
+
9
+ Kept: your projects, your agents (Claude Code, Codex) and their conversations,
10
+ SleepWatcher, tmux and anything you installed yourself.
11
+
12
+ With --everywhere (from the primary), each paired machine is uninstalled first,
13
+ while NodeHop's key still opens it.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import os
19
+ import shutil
20
+ from pathlib import Path
21
+ from typing import Callable, List, Optional
22
+
23
+ from nodehop import pairing
24
+ from nodehop.config import Config, home_dir
25
+ from nodehop.hooks import BEGIN, END
26
+ from nodehop.modules.base import TMUX_SOCKET
27
+ from nodehop.runner import Runner
28
+ from nodehop.system import os_name, sleep_hook_path
29
+ from nodehop.transport import SSHTransport
30
+
31
+ LABELS = ("dev.nodehop.sync", "dev.nodehop.watch", "dev.nodehop.tmux")
32
+ UNITS = ("nodehop-sync.timer", "nodehop-sync.service", "nodehop-watch.service")
33
+
34
+
35
+ def remove_block(path: Path) -> bool:
36
+ """Take NodeHop's block out of a shell script, keeping the person's own lines.
37
+
38
+ A script that held nothing else (NodeHop created it) is deleted.
39
+ """
40
+ if not path.exists():
41
+ return False
42
+ text = path.read_text()
43
+ if BEGIN not in text or END not in text:
44
+ return False
45
+ head, rest = text.split(BEGIN, 1)
46
+ _, tail = rest.split(END, 1)
47
+ remainder = head + tail.lstrip("\n")
48
+ if remainder.strip() in ("", "#!/bin/sh"):
49
+ path.unlink()
50
+ else:
51
+ path.write_text(remainder)
52
+ return True
53
+
54
+
55
+ def _uninstall_with_this_version(transport: SSHTransport):
56
+ from nodehop.deploy import make_bundle
57
+
58
+ bundle = make_bundle()
59
+ try:
60
+ transport.push_dir(bundle, ".cache/nodehop-uninstall", delete=True)
61
+ finally:
62
+ shutil.rmtree(bundle, ignore_errors=True)
63
+ script = ('cd "$HOME/.cache/nodehop-uninstall" && python3 -m nodehop uninstall --yes --json; '
64
+ 'code=$?; cd / && rm -rf "$HOME/.cache/nodehop-uninstall"; exit $code')
65
+ return transport.remote(["sh", "-c", script], check=False, timeout=300)
66
+
67
+
68
+ def uninstall(runner: Runner, cfg: Optional[Config], everywhere: bool = False, keep_key: bool = False,
69
+ system: Optional[str] = None, say: Optional[Callable[[str], None]] = None) -> dict:
70
+ system = system or os_name()
71
+ say = say or runner.log
72
+ home = Path.home()
73
+ done: List[str] = []
74
+ left: List[str] = []
75
+ dry = runner.dry_run
76
+
77
+ def rm(path: Path, what: str) -> None:
78
+ if not path.exists() and not path.is_symlink():
79
+ return
80
+ if not dry:
81
+ shutil.rmtree(path) if path.is_dir() and not path.is_symlink() else path.unlink()
82
+ done.append(f"removed {what}: {path}")
83
+
84
+ # 1. the other machines first, while our key still opens them -------------------
85
+ if everywhere and cfg is not None:
86
+ for name, peer in cfg.peers.items():
87
+ transport = SSHTransport(peer, runner, cfg.extra_path, ssh_key=cfg.ssh_key_path())
88
+ say(f"Uninstalling NodeHop on {name}…")
89
+ result = transport.nodehop("uninstall", "--yes", "--json", check=False, timeout=300)
90
+ if result.returncode != 0 and transport.remote(["true"], check=False, mutating=False).returncode == 0:
91
+ # Reachable, but its NodeHop predates `uninstall`: send this version and run it from there.
92
+ result = _uninstall_with_this_version(transport)
93
+ if result.returncode == 0:
94
+ done.append(f"uninstalled on {name}")
95
+ else:
96
+ why = (result.stderr or result.stdout or "").strip().splitlines()
97
+ left.append(f"on {name}: nodehop uninstall ({why[-1] if why else 'could not reach it now'})")
98
+
99
+ # 2. agents and background jobs ---------------------------------------------------------
100
+ runner.run(["tmux", "-L", TMUX_SOCKET, "kill-server"], check=False)
101
+ done.append("stopped NodeHop's tmux server (conversations are saved)")
102
+ if system == "macos":
103
+ uid = os.getuid()
104
+ for label in LABELS:
105
+ runner.run(["launchctl", "bootout", f"gui/{uid}/{label}"], check=False)
106
+ rm(home / "Library" / "LaunchAgents" / f"{label}.plist", "launchd job")
107
+ for script in (home / ".sleep", home / ".wakeup"):
108
+ if not dry and remove_block(script):
109
+ done.append(f"removed NodeHop's lines from {script}")
110
+ rm(home / "Applications" / "NodeHop.app", "app")
111
+ if shutil.which("sleepwatcher") or Path("/opt/homebrew/sbin/sleepwatcher").exists():
112
+ left.append("brew services stop sleepwatcher && brew uninstall sleepwatcher # if nothing else uses it")
113
+ elif system == "linux":
114
+ runner.run(["systemctl", "--user", "disable", "--now", *UNITS], check=False)
115
+ for unit in UNITS:
116
+ rm(home / ".config" / "systemd" / "user" / unit, "systemd unit")
117
+ runner.run(["systemctl", "--user", "daemon-reload"], check=False)
118
+ if sleep_hook_path().exists():
119
+ left.append(f"sudo rm {sleep_hook_path()}")
120
+
121
+ # 3. keys --------------------------------------------------------------------------------
122
+ auth = pairing.authorized_keys_path()
123
+ if auth.exists():
124
+ lines = auth.read_text().splitlines()
125
+ kept = [l for l in lines if f" {pairing.KEY_TAG}" not in l]
126
+ if len(kept) != len(lines):
127
+ if not dry:
128
+ auth.write_text("\n".join(kept) + ("\n" if kept else ""))
129
+ done.append(f"removed {len(lines) - len(kept)} NodeHop key(s) from {auth}")
130
+ if not keep_key:
131
+ key = cfg.ssh_key_path() if cfg else home / ".ssh" / "nodehop_ed25519"
132
+ rm(key, "NodeHop's SSH key")
133
+ rm(Path(str(key) + ".pub"), "NodeHop's SSH key")
134
+
135
+ # 4. NodeHop's folder, then the program ------------------------------------------------------
136
+ rm(home_dir(), "config, state, backups and logs")
137
+ src = home / ".local" / "share" / "nodehop-src"
138
+ if shutil.which("pipx") and not dry:
139
+ if runner.run(["pipx", "uninstall", "nodehop"], check=False).returncode == 0:
140
+ done.append("removed the nodehop program (pipx)")
141
+ wrapper = home / ".local" / "bin" / "nodehop"
142
+ if wrapper.exists() and not wrapper.is_symlink() and "nodehop-src" in wrapper.read_text(errors="ignore"):
143
+ rm(wrapper, "nodehop launcher")
144
+ rm(src, "NodeHop's copy of its source")
145
+ return {"done": done, "left": left}
@@ -0,0 +1,261 @@
1
+ Metadata-Version: 2.4
2
+ Name: nodehop
3
+ Version: 0.2.0
4
+ Summary: Close your laptop, your agents keep working: hand off Claude Code sessions and training jobs between your machines.
5
+ License: MIT
6
+ Project-URL: Homepage, https://github.com/BuildRunnerFr/NodeHop
7
+ Project-URL: Issues, https://github.com/BuildRunnerFr/NodeHop/issues
8
+ Project-URL: Changelog, https://github.com/BuildRunnerFr/NodeHop/blob/main/CHANGELOG.md
9
+ Keywords: claude-code,ai-agents,handoff,tmux,ssh,tailscale,machine-learning,checkpoint
10
+ Classifier: Development Status :: 3 - Alpha
11
+ Classifier: Environment :: Console
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: License :: OSI Approved :: MIT License
14
+ Classifier: Operating System :: MacOS
15
+ Classifier: Operating System :: POSIX :: Linux
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3 :: Only
18
+ Classifier: Programming Language :: Python :: 3.9
19
+ Classifier: Programming Language :: Python :: 3.10
20
+ Classifier: Programming Language :: Python :: 3.11
21
+ Classifier: Programming Language :: Python :: 3.12
22
+ Classifier: Programming Language :: Python :: 3.13
23
+ Classifier: Topic :: Software Development
24
+ Classifier: Topic :: System :: Distributed Computing
25
+ Requires-Python: >=3.9
26
+ Description-Content-Type: text/markdown
27
+ License-File: LICENSE
28
+ Dynamic: license-file
29
+
30
+ <p align="center">
31
+ <img src="https://raw.githubusercontent.com/BuildRunnerFr/NodeHop/main/docs/logo.png" width="112" alt="NodeHop logo">
32
+ </p>
33
+
34
+ <h1 align="center">NodeHop</h1>
35
+
36
+ <p align="center">
37
+ <b>Close your laptop. Your agents keep working.</b><br>
38
+ <sub>Hands Claude Code and Codex sessions from your laptop to an always-on Mac or Linux box, and back.</sub>
39
+ </p>
40
+
41
+ <p align="center">
42
+ <a href="https://github.com/BuildRunnerFr/NodeHop/actions/workflows/tests.yml"><img src="https://github.com/BuildRunnerFr/NodeHop/actions/workflows/tests.yml/badge.svg" alt="Tests"></a>
43
+ <img src="https://img.shields.io/badge/python-3.9%2B-blue" alt="Python 3.9+">
44
+ <img src="https://img.shields.io/badge/platform-macOS%20%7C%20Linux-lightgrey" alt="macOS | Linux">
45
+ <img src="https://img.shields.io/badge/dependencies-none-brightgreen" alt="No dependencies">
46
+ <a href="LICENSE"><img src="https://img.shields.io/badge/license-MIT-green" alt="MIT license"></a>
47
+ </p>
48
+
49
+ ---
50
+
51
+ NodeHop hands running work from your laptop to an always-on machine, and back.
52
+ Close the lid while Claude Code or Codex is in the middle of a task: the
53
+ session is stopped, copied to your Mac mini or Linux box, and resumed there with
54
+ the same conversation. Open the lid: your laptop takes it back. Training jobs work the
55
+ same way, resuming from their last checkpoint at the other machine's pace.
56
+
57
+ ```
58
+ laptop (primary) always-on machine (server)
59
+ ──────────────── ──────────────────────────
60
+ lid closes ─► stop the agent
61
+ copy project + conversation ──────► resume it, same conversation
62
+ lid opens ─► ask the server to stop
63
+ copy everything back ◄─────────────
64
+ resume it here
65
+ ```
66
+
67
+ ## Highlights
68
+
69
+ - **Your agents never stop** — Claude Code and Codex sessions (conversation
70
+ included) and long commands such as training jobs move between machines and
71
+ resume.
72
+ - **Set up by an agent, from one machine** — it asks you a few questions and
73
+ installs NodeHop on the other machine over SSH. No agent needed over there.
74
+ - **The laptop needs no SSH server** — it pushes work when it sleeps and pulls it
75
+ back when it wakes; only the always-on machine accepts connections.
76
+ - **Safe on slow networks** — transfers are all-or-nothing; if the newest state
77
+ cannot be sent before sleep, the server resumes from its last complete copy.
78
+ - **Fallback** — if the laptop dies without going to sleep, the server resumes
79
+ the work in progress after 2 minutes.
80
+ - **You decide conflicts** — if two agents worked in parallel, a native window
81
+ shows what each one did and lets you pick (the other version is kept).
82
+ - **A Mac mini or a Linux server takes over** — the always-on machine can be a
83
+ Mac or a Linux box, with or without a screen.
84
+ - **Paths may differ** — different user names and folders on each machine.
85
+ - **Zero dependencies** — Python 3.9+ standard library, `ssh`, `rsync`, `tmux`.
86
+
87
+ ## Before you start
88
+
89
+ NodeHop does almost everything itself. You only prepare three things, once,
90
+ on **both machines**:
91
+
92
+ 1. **Your agent, installed and signed in.** NodeHop is built for Claude Code
93
+ first, and Codex works the same way: use either, or both. Install it on each
94
+ machine, sign in with your account, and open it once (`claude`, then its
95
+ first screens). NodeHop never moves your login from one machine to the other.
96
+ 2. **SSH on the always-on machine.** macOS: System Settings › General › Sharing ›
97
+ Remote Login. Linux: `sudo apt install -y openssh-server`. The laptop needs no
98
+ SSH server. When asked, you type that machine's password once into
99
+ `ssh-copy-id`.
100
+ 3. **[Tailscale](https://tailscale.com) on both machines**, signed in to the
101
+ same account, so they find each other at home and away (recommended; a
102
+ local network works too).
103
+
104
+ That's all. Installing NodeHop on the other machine, pairing both machines and
105
+ hooking into sleep and wake are done for you.
106
+
107
+ ## Get started
108
+
109
+ ### With an agent (recommended)
110
+
111
+ Ask your coding agent (Claude Code or any other), on your laptop:
112
+
113
+ > Install NodeHop from https://github.com/BuildRunnerFr/NodeHop by following its AGENT_SETUP.md.
114
+
115
+ It installs NodeHop, asks you whether this is the laptop or the always-on
116
+ machine, which machine is the other one (your Tailscale machines are offered),
117
+ and which project to protect, then sets up both machines. All you may have to
118
+ do: type the other machine's password once into `ssh-copy-id`, and run anything
119
+ that needs `sudo`. Details for agents: [AGENT_SETUP.md](AGENT_SETUP.md).
120
+
121
+ ### By hand
122
+
123
+ ```sh
124
+ pipx install git+https://github.com/BuildRunnerFr/NodeHop
125
+ nodehop onboard # the same questions, with arrow-key menus
126
+ ```
127
+
128
+ ## Daily use
129
+
130
+ ```sh
131
+ cd ~/code/my-app
132
+ nodehop on # protect this project (Claude Code; --agent codex for Codex)
133
+ nodehop start my-app # run its agent, inside NodeHop's tmux
134
+ nodehop attach my-app # open its terminal (detach: Ctrl-b d)
135
+ nodehop status # where each project runs right now
136
+ ```
137
+
138
+ Then just close the lid. A few more:
139
+
140
+ ```sh
141
+ nodehop handoff --to server # hand off now, without closing the lid
142
+ nodehop pull my-app # bring a project back here
143
+ nodehop resolve # two agents worked in parallel: choose
144
+ nodehop doctor # check everything, with fixes
145
+ nodehop -n handoff # dry run: print every command, change nothing
146
+ ```
147
+
148
+ ## Training jobs
149
+
150
+ ```sh
151
+ nodehop on ~/code/my-model --command ".venv/bin/python train.py"
152
+ nodehop start my-model
153
+ ```
154
+
155
+ With `from nodehop import train` (standard library, PyTorch optional) a script
156
+ saves a checkpoint and exits cleanly when NodeHop stops it, resumes from it on
157
+ the other machine, and picks a micro-batch that fits that machine's memory —
158
+ gradient accumulation keeps the effective batch, and so the training, identical.
159
+ A 40,000-step run moved between a MacBook (128 × 4) and a Mac mini (64 × 8)
160
+ with the same loss curve. See [examples/train_relay.py](examples/train_relay.py).
161
+
162
+ ## How it works
163
+
164
+ | When | What NodeHop does |
165
+ | --- | --- |
166
+ | Every 30 s | The laptop tells the server it is alive; every 5 min it also copies the active projects there. |
167
+ | Lid closes | Stop the agent (Claude Code quits in ~1 s; a training job saves a checkpoint), copy what changed, resume it on the server. Budget: ~22 s, because macOS sleeps soon after. |
168
+ | Lid opens | Ask the server to stop, copy everything back, resume here. Retries while the network comes back. |
169
+ | Laptop silent 2 min without sleeping | The server resumes, from the last copy, the work that was in progress. |
170
+ | Laptop back, both agents worked | The server's agent is paused and you choose which version to keep. |
171
+
172
+ Agents run in NodeHop's own tmux server, so they keep running with no terminal
173
+ open and can be stopped cleanly. A resumed Claude Code gets a short "carry on"
174
+ message only if it was in the middle of something; an idle one is just reopened.
175
+
176
+ ## Requirements
177
+
178
+ | | The machine you work on (primary) | The always-on machine (server) |
179
+ | --- | --- | --- |
180
+ | System | a Mac, usually a laptop | a Mac (e.g. a Mac mini) or a Linux server, headless is fine |
181
+ | Needs | Python 3.9+ (the system one works), `rsync`, `tmux`, and your agent (Claude Code and/or Codex) signed in | the same, plus an SSH server (Remote Login on macOS; `openssh-server` on Linux) |
182
+ | Notes | [SleepWatcher](https://www.bernhard-baehr.de/), installed for you by `nodehop onboard` | Mac: keep a user session open (automatic login) so agents can read the login keychain. Linux: `loginctl enable-linger` so agents keep running with nobody logged in |
183
+
184
+ - **[Tailscale](https://tailscale.com)** recommended, so it also works away
185
+ from home.
186
+
187
+ A Linux machine can also be the primary (a systemd sleep hook replaces
188
+ SleepWatcher), but that setup is less tested.
189
+
190
+ ## Configuration
191
+
192
+ `nodehop config get` shows everything; `nodehop config set <key> <value>`
193
+ changes it. The useful ones:
194
+
195
+ | Key | Default | Meaning |
196
+ | --- | --- | --- |
197
+ | `presync_seconds` | `300` | how often active projects are copied to the server |
198
+ | `failover_minutes` | `2` | server: resume the laptop's work after this much silence (`0` = off) |
199
+ | `sleep_budget_seconds` | `22` | time allowed to hand off when the lid closes |
200
+ | `unattended` | unset (asked) | how a resumed agent handles permission prompts with nobody there: `auto` (Claude Code's auto mode; Codex sandboxed to the project), `acceptEdits`, or `default` |
201
+ | `remote_control` | `false` | show NodeHop's Claude Code sessions in the Claude app, to follow and answer them from anywhere |
202
+ | `backups_keep` | `5` | versions set aside after a fallback or conflict, kept per project |
203
+ | `excludes` | `node_modules`, `.venv`, … | never copied (rebuild them on each machine) |
204
+ | `workspace` | unset | where received projects go (unset: same place relative to the home folder) |
205
+ | `claude_args` / `codex_args` | `[]` | extra flags for Claude Code / Codex (e.g. `["-c", "model=\"…\""]`) |
206
+
207
+ ## FAQ
208
+
209
+ **Does the other machine need an agent to be set up?** No. The agent on your
210
+ laptop installs and configures NodeHop over there through SSH. Claude Code (or
211
+ Codex) must simply be installed and signed in there too, since that machine
212
+ runs your agent while the laptop sleeps.
213
+
214
+ **Does it work on battery?** Yes. Closing the lid hands off on battery as on
215
+ power: NodeHop finishes before macOS goes to sleep (a few seconds, within a
216
+ 22-second budget).
217
+
218
+ **What does NodeHop do with my passwords?** Nothing: it never asks for, types or
219
+ stores one, and agents' logins never leave their machine. It uses its own SSH
220
+ key, restricted on the server; see [SECURITY.md](SECURITY.md).
221
+
222
+ **What if the resumed agent needs a permission with nobody there?** Set
223
+ `unattended` to `auto` (the onboarding suggests it): Claude Code's auto mode
224
+ decides by itself, so work does not stall. With `remote_control` on, you can
225
+ also follow and answer it from the Claude app.
226
+
227
+ **My network is slow; will a big checkpoint make me lose work?** A transfer cut
228
+ by sleep changes nothing on the other side, and the server resumes from the
229
+ last complete copy (at most `presync_seconds` old).
230
+
231
+ **What if I edit the project on both machines?** Don't: the receiving copy is
232
+ made identical to the sender's. If two agents ever worked in parallel, NodeHop
233
+ asks you which version to keep and saves the other.
234
+
235
+ **Which agents?** Claude Code (the main target) and Codex, each with its
236
+ conversation, as long as it is signed in on both machines; anything
237
+ else as a plain command (`nodehop on --command "…"`), restarted on the other
238
+ machine. Adding another agent is one module: see [CONTRIBUTING.md](CONTRIBUTING.md).
239
+
240
+ **Does it rely on agents' internals?** Yes: session files (`~/.claude/projects`,
241
+ `~/.codex/sessions`) are not public APIs and may change. NodeHop keeps each
242
+ agent's details in its own module.
243
+
244
+ ## Uninstall
245
+
246
+ ```sh
247
+ nodehop uninstall --everywhere # from the laptop: this machine and the paired ones
248
+ ```
249
+
250
+ It removes NodeHop's background jobs, app, keys, config, backups and logs, then
251
+ the program itself. Your projects, your agents and their conversations stay.
252
+
253
+ ## Contributing
254
+
255
+ Issues and pull requests are welcome: see [CONTRIBUTING.md](CONTRIBUTING.md)
256
+ and the design notes in [CLAUDE.md](CLAUDE.md). Changes are listed in
257
+ [CHANGELOG.md](CHANGELOG.md).
258
+
259
+ ## License
260
+
261
+ [MIT](LICENSE)