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/cli.py ADDED
@@ -0,0 +1,807 @@
1
+ """Command-line interface: `nodehop <command>`."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import os
8
+ import shutil
9
+ import sys
10
+ import time
11
+ from pathlib import Path
12
+ from typing import Dict, List, Optional
13
+
14
+ from nodehop import __version__, deploy, doctor, hooks, pairing, ui
15
+ from nodehop.config import DEFAULT_EXTRA_PATH, Config, ConfigError, Peer, Project
16
+ from nodehop.core import NodeHop
17
+ from nodehop.modules import MODULES
18
+ from nodehop.modules.base import tmux as tmux_argv
19
+ from nodehop.runner import CommandError, Runner
20
+
21
+
22
+ def build_parser() -> argparse.ArgumentParser:
23
+ p = argparse.ArgumentParser(
24
+ prog="nodehop",
25
+ description="Hand off running agent work between your machines when you close the lid.",
26
+ )
27
+ p.add_argument("--version", action="version", version=f"nodehop {__version__}")
28
+ p.add_argument("-n", "--dry-run", action="store_true", help="print what would run, change nothing")
29
+ p.add_argument("-v", "--verbose", action="store_true", help="print every command")
30
+ sub = p.add_subparsers(dest="command", required=True)
31
+
32
+ s = sub.add_parser("setup", help="one-shot setup for this machine (safe to re-run): config, SSH key, checks, pairing token")
33
+ s.add_argument("--name", help="name of this machine, e.g. macbook (required the first time)")
34
+ s.add_argument("--primary", action="store_true", help="this is the machine you work on (it hands off when its lid closes)")
35
+ s.add_argument("--workspace", help="folder for projects received from other machines (default: same place as on the sender, relative to home)")
36
+ s.add_argument("--host", action="append", help="host name other machines should use to reach this one (repeatable)")
37
+ s.add_argument("--json", action="store_true", help="machine-readable output, for agents")
38
+ s.add_argument("--no-wizard", action="store_true", help="never ask questions, even in a terminal")
39
+
40
+ s = sub.add_parser("deploy", help="install NodeHop on another machine over SSH and pair both ways")
41
+ s.add_argument("destination", help="user@host[:port] of the other machine, e.g. alice@mac-mini.tailnet.ts.net")
42
+ s.add_argument("--name", help="name for that machine (default: from its host name)")
43
+ s.add_argument("--no-hooks", action="store_true", help="do not install its background job")
44
+ s.add_argument("--json", action="store_true")
45
+
46
+ s = sub.add_parser("onboard", help="guided setup, step by step (agents: --json, then run `next.command`)")
47
+ s.add_argument("--json", action="store_true", help="print the next step (questions + command) for an agent")
48
+ s.add_argument("--skip", action="append", default=[], help="treat this step as skipped (repeatable)")
49
+
50
+ s = sub.add_parser("config", help="read or change a setting")
51
+ s.add_argument("action", choices=["get", "set"])
52
+ s.add_argument("key", nargs="?")
53
+ s.add_argument("value", nargs="?", help="JSON (e.g. 5, true, [\"a\"]) or plain text")
54
+
55
+ s = sub.add_parser("uninstall", help="remove NodeHop from this machine (and, with --everywhere, from the paired ones)")
56
+ s.add_argument("--everywhere", action="store_true", help="also uninstall it on every paired machine (run on the primary)")
57
+ s.add_argument("--keep-key", action="store_true", help="keep NodeHop's SSH key")
58
+ s.add_argument("--yes", action="store_true", help="do not ask for confirmation")
59
+ s.add_argument("--json", action="store_true")
60
+
61
+ s = sub.add_parser("discover", help="list the other machines on your Tailscale network")
62
+ s.add_argument("--json", action="store_true")
63
+
64
+ s = sub.add_parser("invite", help="print this machine's pairing token")
65
+ s.add_argument("--host", action="append", help="host name other machines should use to reach this one (repeatable)")
66
+ s.add_argument("--json", action="store_true")
67
+
68
+ s = sub.add_parser("pair", help="pair with another machine using its token (run on both sides)")
69
+ s.add_argument("token")
70
+ s.add_argument("--host", help="override the host used to reach that machine")
71
+ s.add_argument("--default", action="store_true", help="hand off to that machine by default")
72
+ s.add_argument("--json", action="store_true")
73
+
74
+ s = sub.add_parser("doctor", help="check everything this machine needs, with fixes")
75
+ s.add_argument("--json", action="store_true", help="machine-readable output, for agents")
76
+ s.add_argument("--offline", action="store_true", help="skip contacting peers")
77
+
78
+ s = sub.add_parser("init", help="create this machine's config (low level; prefer setup)")
79
+ s.add_argument("--name", required=True, help="name of this machine, e.g. macbook")
80
+ s.add_argument("--primary", help="name of the main machine (default: this one)")
81
+ s.add_argument("--force", action="store_true", help="overwrite an existing config")
82
+
83
+ s = sub.add_parser("peer", help="manage the other machines")
84
+ peer_sub = s.add_subparsers(dest="peer_command", required=True)
85
+ a = peer_sub.add_parser("add", help="add or update a machine")
86
+ a.add_argument("name")
87
+ a.add_argument("--host", required=True, help="SSH host, e.g. the Tailscale name 'mac-mini'")
88
+ a.add_argument("--user", help="SSH user (default: your ssh config)")
89
+ a.add_argument("--bin", default="nodehop", help="path of nodehop on that machine")
90
+ a.add_argument("--default", action="store_true", help="hand off to this machine by default")
91
+ r = peer_sub.add_parser("remove")
92
+ r.add_argument("name")
93
+
94
+ s = sub.add_parser("project", help="manage tracked projects")
95
+ proj_sub = s.add_subparsers(dest="project_command", required=True)
96
+ a = proj_sub.add_parser("add", help="track a project (other machines pick their own path for it)")
97
+ a.add_argument("path", nargs="?", default=".")
98
+ a.add_argument("--name", help="short name (default: folder name)")
99
+ a.add_argument("--module", default="claude-code", choices=sorted(MODULES))
100
+ r = proj_sub.add_parser("remove")
101
+ r.add_argument("name")
102
+
103
+ s = sub.add_parser("on", help="protect a project: pre-sync, hand off at sleep, fallback (adds it if new)")
104
+ s.add_argument("target", nargs="?", default=".", help="project name or folder (default: current folder)")
105
+ s.add_argument("--name", help="short name when adding a folder (default: folder name)")
106
+ s.add_argument("--agent", choices=["claude", "codex"], help="which agent runs in this project (default: claude)")
107
+ s.add_argument("--command", dest="command_line", help="run this command instead of an agent (e.g. a training script)")
108
+
109
+ s = sub.add_parser("off", help="stop protecting a project (nothing is deleted)")
110
+ s.add_argument("target", nargs="?", default=".", help="project name or folder (default: current folder)")
111
+
112
+ sub.add_parser("status", help="show who owns what")
113
+
114
+ s = sub.add_parser("start", help="start the agent for a project in a managed tmux session")
115
+ s.add_argument("project")
116
+ s.add_argument("--resume", action="store_true", help="resume the latest session instead of a new one")
117
+
118
+ s = sub.add_parser("attach", help="open the agent's terminal (tmux attach)")
119
+ s.add_argument("project")
120
+
121
+ s = sub.add_parser("stop", help="stop the agent for a project")
122
+ s.add_argument("project")
123
+
124
+ s = sub.add_parser("handoff", help="move projects to another machine now")
125
+ s.add_argument("projects", nargs="*", help="default: every project owned here")
126
+ s.add_argument("--to", help="target machine (default: the default peer)")
127
+ s.add_argument("--reason", default="manual")
128
+ s.add_argument("--force", action="store_true", help="hand off even if not owned here")
129
+
130
+ s = sub.add_parser("pull", help="bring projects back to this machine (this machine connects; the other never has to)")
131
+ s.add_argument("projects", nargs="*", help="default: everything sent away from here at sleep")
132
+
133
+ s = sub.add_parser("sync", help="pre-copy owned projects to the target, without handing off")
134
+ s.add_argument("--to")
135
+
136
+ s = sub.add_parser("watch", help="server: resume the primary's work if it goes silent without going to sleep")
137
+ s.add_argument("--once", action="store_true")
138
+
139
+ sub.add_parser("on-sleep", help="called by SleepWatcher when the lid closes")
140
+ sub.add_parser("on-wake", help="called by SleepWatcher when the machine wakes up")
141
+
142
+ s = sub.add_parser("install-hooks", help="background jobs: sleep/wake + pre-sync (primary), fallback watcher (server)")
143
+ s.add_argument("--sync-interval", type=int, default=30, help="seconds between heartbeats (copies follow presync_seconds)")
144
+ s.add_argument("--apply", action="store_true", help="also run the follow-up commands that need no sudo (may brew install sleepwatcher)")
145
+ s.add_argument("--json", action="store_true")
146
+
147
+ sub.add_parser("ping", help="answer peers checking that this machine is awake")
148
+
149
+ s = sub.add_parser("prepare", help=argparse.SUPPRESS)
150
+ s.add_argument("project")
151
+ s.add_argument("--module", default="claude-code")
152
+ s.add_argument("--origin-path", required=True)
153
+ s.add_argument("--origin-home")
154
+
155
+ s = sub.add_parser("resolve", help="two agents worked in parallel: see both and choose which to keep")
156
+ s.add_argument("project", nargs="?")
157
+ s.add_argument("--keep", choices=["here", "there", "merge"], help="decide without asking (merge = keep here, brief it on the other's work)")
158
+ s.add_argument("--json", action="store_true")
159
+
160
+ s = sub.add_parser("gui-ask", help=argparse.SUPPRESS)
161
+ s.add_argument("project")
162
+
163
+ s = sub.add_parser("pause", help=argparse.SUPPRESS)
164
+ s.add_argument("project")
165
+
166
+ s = sub.add_parser("progress", help=argparse.SUPPRESS)
167
+ s.add_argument("project")
168
+ s.add_argument("--since", type=float, default=0)
169
+
170
+ s = sub.add_parser("heartbeat", help=argparse.SUPPRESS)
171
+ s.add_argument("--from", dest="origin", required=True)
172
+ s.add_argument("--meta", default="{}")
173
+
174
+ s = sub.add_parser("claims", help=argparse.SUPPRESS)
175
+ s.add_argument("--json", action="store_true")
176
+
177
+ s = sub.add_parser("abandon", help=argparse.SUPPRESS)
178
+ s.add_argument("project")
179
+ s.add_argument("--to", required=True)
180
+
181
+ s = sub.add_parser("release", help=argparse.SUPPRESS)
182
+ s.add_argument("project")
183
+ s.add_argument("--to", required=True)
184
+ s.add_argument("--json", action="store_true")
185
+
186
+ s = sub.add_parser("released", help=argparse.SUPPRESS)
187
+ s.add_argument("project")
188
+ s.add_argument("--to", required=True)
189
+
190
+ s = sub.add_parser("receive", help=argparse.SUPPRESS)
191
+ s.add_argument("project")
192
+ s.add_argument("--from", dest="origin", required=True)
193
+ s.add_argument("--meta", default="{}")
194
+ return p
195
+
196
+
197
+ def cmd_init(args) -> int:
198
+ if Config.path().exists() and not args.force:
199
+ print(f"config already exists at {Config.path()} (use --force to overwrite)", file=sys.stderr)
200
+ return 1
201
+ cfg = Config(machine=args.name, primary=args.primary or args.name)
202
+ print(f"wrote {cfg.save()}")
203
+ return 0
204
+
205
+
206
+ def cmd_peer(args, cfg: Config) -> int:
207
+ if args.peer_command == "add":
208
+ if args.name == cfg.machine:
209
+ raise ConfigError("a peer cannot have this machine's own name")
210
+ cfg.peers[args.name] = Peer(name=args.name, host=args.host, user=args.user, nodehop_bin=args.bin)
211
+ if args.default:
212
+ cfg.default_target = args.name
213
+ else:
214
+ cfg.peers.pop(args.name, None)
215
+ if cfg.default_target == args.name:
216
+ cfg.default_target = None
217
+ if pairing.revoke(args.name):
218
+ print(f"removed {args.name}'s key from {pairing.authorized_keys_path()}")
219
+ cfg.save()
220
+ return 0
221
+
222
+
223
+ def cmd_project(args, cfg: Config) -> int:
224
+ if args.project_command == "add":
225
+ path = Path(args.path).expanduser().resolve()
226
+ if not path.is_dir():
227
+ raise ConfigError(f"{path} is not a directory")
228
+ if path in (Path("/"), Path.home()) or len(path.parts) < 3:
229
+ raise ConfigError(f"refusing to track {path}: pick a project folder, not a top-level one")
230
+ name = args.name or path.name
231
+ cfg.projects[name] = Project(name=name, path=str(path), module=args.module)
232
+ print(f"tracking {name} -> {path} ({args.module})")
233
+ else:
234
+ cfg.projects.pop(args.name, None)
235
+ cfg.save()
236
+ return 0
237
+
238
+
239
+ def find_project(cfg: Config, target: str) -> Optional[str]:
240
+ if target in cfg.projects:
241
+ return target
242
+ path = str(Path(target).expanduser().resolve())
243
+ for name, project in cfg.projects.items():
244
+ if project.path == path or path.startswith(project.path.rstrip("/") + "/"):
245
+ return name
246
+ return None
247
+
248
+
249
+ def cmd_on_off(args, cfg: Config, runner: Runner) -> int:
250
+ name = find_project(cfg, args.target)
251
+ if args.command == "on" and name is None:
252
+ path = Path(args.target).expanduser().resolve()
253
+ if not path.is_dir() or path in (Path("/"), Path.home()) or len(path.parts) < 3:
254
+ raise ConfigError(f"{args.target}: not a project of NodeHop, nor a project folder")
255
+ name = args.name or path.name
256
+ cfg.projects[name] = Project(name=name, path=str(path))
257
+ if name is None:
258
+ raise ConfigError(f"{args.target}: not a project of NodeHop")
259
+ cfg.projects[name].active = args.command == "on"
260
+ if args.command == "on" and getattr(args, "command_line", None):
261
+ cfg.projects[name].command = args.command_line
262
+ cfg.projects[name].module = "command"
263
+ elif args.command == "on" and getattr(args, "agent", None):
264
+ from nodehop.modules import AGENTS
265
+
266
+ cfg.projects[name].module = AGENTS[args.agent]
267
+ cfg.save()
268
+ hop = NodeHop(cfg, runner)
269
+ if args.command == "on":
270
+ print(f"{name}: protected ({cfg.projects[name].path})")
271
+ else:
272
+ print(f"{name}: no longer protected (nothing deleted; `nodehop on {name}` to resume)")
273
+ if cfg.primary == cfg.machine and cfg.peers:
274
+ try: # tell the server now: first copy, or "stop covering this one"
275
+ hop.sync(cfg.target(), force_copy=args.command == "on")
276
+ except Exception as exc:
277
+ print(f"(could not reach the server now: {exc}; the next sync will)")
278
+ return 0
279
+
280
+
281
+ def show_conflict(report: dict) -> None:
282
+ from nodehop import gui
283
+
284
+ now = time.time()
285
+ ui.title(f"Two agents worked in parallel on {report['project']}")
286
+ print(" " + gui.headline(report) + "\n")
287
+ most = max([(report[k].get("tool_calls", report[k].get("actions")) or 0) for k in ("here", "there")] + [1])
288
+ for key in ("here", "there"):
289
+ p = report[key]
290
+ label = p["machine"] + (" · this machine" if key == "here" else "")
291
+ print(" " + ui.style(f"┌─ {label} ", "bold") + ui.style("─" * max(2, 56 - len(label)), "dim"))
292
+ for row, value in gui.side_lines(p, report["since"], now):
293
+ if row == "Status":
294
+ colour = "green" if p.get("busy") else ("cyan" if p.get("running") else "yellow")
295
+ value = ui.style("● " + value, colour)
296
+ print(f" │ {row:<14}{value}")
297
+ tools = p.get("tool_calls", p.get("actions")) or 0
298
+ bar = "█" * max(1 if tools else 0, round(30 * tools / most))
299
+ print(f" │ {'Work done':<14}{ui.style(bar.ljust(30), 'magenta')} {tools} actions")
300
+ print(" " + ui.style("└" + "─" * 59, "dim") + "\n")
301
+
302
+
303
+ def cmd_resolve(args, hop: NodeHop) -> int:
304
+ names = [args.project] if args.project else [n for n in hop.config.projects if hop.in_conflict(n)]
305
+ if not names:
306
+ print("no conflict: nothing to resolve")
307
+ return 0
308
+ for name in names:
309
+ report = hop.conflict_report(name)
310
+ keep = args.keep
311
+ if not keep and not args.json and ui.interactive():
312
+ show_conflict(report)
313
+ here, there = report["here"]["machine"], report["there"]["machine"]
314
+ pick = ui.select(
315
+ "Which one do you keep?",
316
+ [f"Keep {here}", f"Keep {there}", f"Keep {here} + give it {there}'s work", "Decide later"],
317
+ [f"{there}'s version is set aside in a backup", f"{here}'s version is set aside in a backup",
318
+ f"the agent compares both and brings in what is useful", "both stay paused/as they are"],
319
+ )
320
+ keep = ["here", "there", "merge", None][pick]
321
+ if not keep:
322
+ if args.json:
323
+ print(json.dumps(report))
324
+ else:
325
+ show_conflict(report) if not ui.interactive() else None
326
+ print(f" later: nodehop resolve {name} --keep here|there|merge")
327
+ continue
328
+ result = hop.resolve(name, keep)
329
+ if args.json:
330
+ print(json.dumps(dict(result, report=report)))
331
+ else:
332
+ ui.ok(f"{name}: kept {report['here']['machine'] if keep != 'there' else report['there']['machine']}'s version"
333
+ + (", agent briefed on the other's work" if keep == "merge" else ""))
334
+ return 0
335
+
336
+
337
+ def cfg_active(hop: NodeHop, name: str) -> bool:
338
+ return hop.config.projects[name].active
339
+
340
+
341
+ def cmd_status(hop: NodeHop) -> int:
342
+ rows = hop.status()
343
+ if not rows:
344
+ print("no projects yet: `nodehop project add <path>`")
345
+ return 0
346
+ print(f"this machine: {hop.me}")
347
+ for r in rows:
348
+ here = " (running here)" if r["running_here"] else ""
349
+ here += "" if cfg_active(hop, r["project"]) else " [off]"
350
+ here += " [CONFLICT: run `nodehop resolve`]" if hop.in_conflict(r["project"]) else ""
351
+ print(f" {r['project']:<20} on {r['owner']}{here} session={r['session_id'] or '-'} updated={r['updated'] or '-'}")
352
+ return 0
353
+
354
+
355
+ def emit(args, data: dict, text: str) -> None:
356
+ print(json.dumps(data, indent=2) if getattr(args, "json", False) else text)
357
+
358
+
359
+ def do_setup(runner: Runner, name: Optional[str], primary: Optional[bool], workspace: Optional[str] = None, hosts: Optional[List[str]] = None):
360
+ """Create or update this machine's config and key. primary=None keeps the current role."""
361
+ cfg = doctor.load_config()
362
+ if cfg is None:
363
+ if not name:
364
+ raise ConfigError("first run: pass --name <this machine>, e.g. --name macbook")
365
+ cfg = Config(machine=name, primary=name if primary else "")
366
+ elif name and name != cfg.machine:
367
+ if cfg.peers:
368
+ raise ConfigError(f"this machine is already set up and paired as '{cfg.machine}' ({Config.path()})")
369
+ cfg.machine = name
370
+ if primary:
371
+ cfg.primary = cfg.machine
372
+ elif primary is False and cfg.primary == cfg.machine:
373
+ cfg.primary = ""
374
+ if workspace:
375
+ cfg.workspace = workspace
376
+ if not runner.dry_run:
377
+ cfg.save()
378
+ pairing.ensure_key(cfg, runner)
379
+ hosts = hosts or pairing.local_hosts(runner)
380
+ token = pairing.make_token(cfg, hosts) if cfg.ssh_key_path().exists() else None
381
+ checks = doctor.run_checks(cfg, runner, peers=False)
382
+ role = "primary" if cfg.primary == cfg.machine else "secondary"
383
+ data = {"machine": cfg.machine, "role": role, "hosts": hosts, "token": token, "checks": checks, "healthy": doctor.healthy(checks)}
384
+ return cfg, data
385
+
386
+
387
+ def wizard(runner: Runner) -> int:
388
+ ui.title("NodeHop setup")
389
+ print(" Hands your running agents over to another machine when you close the lid.\n")
390
+ existing = doctor.load_config()
391
+ local_name = runner.run(["scutil", "--get", "ComputerName"], check=False, mutating=False).stdout.strip() or pairing.socket.gethostname()
392
+ default_name = existing.machine if existing else pairing.suggested_name(local_name or "macbook")
393
+ name = ui.ask("Name for this machine?", default_name)
394
+ is_primary = existing.primary == existing.machine if existing else True
395
+ choice = ui.select(
396
+ "What is this machine?",
397
+ ["Primary", "Secondary"],
398
+ ["the laptop you work on and close", "always on, takes over while the primary sleeps"],
399
+ default=0 if is_primary else 1,
400
+ )
401
+ primary = choice == 0
402
+ cfg, data = do_setup(runner, name, primary)
403
+ ui.ok(f"{cfg.machine} set up as {data['role']} (config: {Config.path()})")
404
+ for c in data["checks"]:
405
+ if c["status"] == "fail" and c["id"] != "peers":
406
+ ui.fail(f"{c['id']}: {c['detail']}")
407
+ ui.warn(f"fix: {c['fix']}")
408
+
409
+ other_role = "secondary" if primary else "primary"
410
+ peers = pairing.tailnet_peers(runner)
411
+ options, hints, hosts = [], [], []
412
+ for p in peers:
413
+ options.append(p["name"])
414
+ hints.append(f"{p['host']} · {p['os'] or '?'} · {'online' if p['online'] else 'offline'}")
415
+ hosts.append(p["host"])
416
+ options += ["Another address…", "Later"]
417
+ hints += ["a host name or IP reachable over SSH", "pair later with `nodehop invite` / `nodehop pair`"]
418
+ print()
419
+ if not primary:
420
+ ui.warn("Tip: run this wizard on the primary (the laptop) instead: it connects to this machine, never the reverse.")
421
+ pick = ui.select(f"Which machine is the {other_role}?", options, hints)
422
+ if pick == len(options) - 1:
423
+ ui.step("Later: run `nodehop deploy user@host` here, or `nodehop invite` and `nodehop pair` on each side.")
424
+ return 0
425
+ host = ui.ask("Host name or IP?") if pick == len(options) - 2 else hosts[pick]
426
+ user = ui.ask(f"User name on {host.split('.')[0]}?", pairing.getpass.getuser())
427
+ other_name = ui.ask("Name for that machine?", pairing.suggested_name(options[pick] if pick < len(peers) else host))
428
+ if not ui.confirm(f"Install NodeHop on {user}@{host} and pair it with {cfg.machine}?"):
429
+ return 0
430
+ print()
431
+ try:
432
+ report = deploy.deploy(cfg, runner, f"{user}@{host}", name=other_name, interactive=True, say=ui.step)
433
+ except deploy.DeployError as exc:
434
+ ui.fail(str(exc))
435
+ return 1
436
+ return show_deploy(report, cfg)
437
+
438
+
439
+ def show_deploy(report: dict, cfg: Config) -> int:
440
+ name = report.get("peer_name", report["peer"])
441
+ ui.ok(f"NodeHop installed on {name} ({report['install']})")
442
+ if report.get("this_to_peer"):
443
+ ui.ok(f"{cfg.machine} → {name}: ok")
444
+ else:
445
+ ui.fail(f"{cfg.machine} → {name}: no answer")
446
+ for c in report.get("remote_checks", []):
447
+ if c["status"] == "fail" and c["id"] not in ("peers",):
448
+ ui.warn(f"on {name}: {c['id']}: {c['detail']} → {c['fix']}")
449
+ print()
450
+ ui.step("Next, on the primary: `nodehop project add <folder>`, then `nodehop install-hooks`.")
451
+ return 0 if report.get("this_to_peer") else 1
452
+
453
+
454
+ def cmd_uninstall(args) -> int:
455
+ from nodehop import uninstall
456
+
457
+ runner = Runner(dry_run=args.dry_run, verbose=args.verbose)
458
+ cfg = doctor.load_config()
459
+ where = "this machine" + (f" and {', '.join(cfg.peers)}" if args.everywhere and cfg and cfg.peers else "")
460
+ if not (args.yes or args.dry_run):
461
+ if not ui.interactive():
462
+ raise ConfigError("pass --yes to uninstall without a terminal to confirm in")
463
+ print("NodeHop's background jobs, app, keys, config, backups and logs will be removed from "
464
+ f"{where}. Your projects, agents and their conversations stay.")
465
+ if not ui.confirm(f"Uninstall NodeHop from {where}?", default=False):
466
+ return 1
467
+ report = uninstall.uninstall(runner, cfg, everywhere=args.everywhere, keep_key=args.keep_key,
468
+ say=(lambda m: None) if args.json else ui.step)
469
+ if args.json:
470
+ print(json.dumps(report))
471
+ return 0
472
+ for line in report["done"]:
473
+ ui.ok(line)
474
+ if report["left"]:
475
+ ui.warn("left for you:")
476
+ for line in report["left"]:
477
+ print(" " + line)
478
+ return 0
479
+
480
+
481
+ def cmd_config(args) -> int:
482
+ cfg = Config.load()
483
+ data = cfg.to_dict()
484
+ if args.action == "get":
485
+ print(json.dumps(data if not args.key else data.get(args.key), indent=2))
486
+ return 0
487
+ if not args.key or args.value is None:
488
+ raise ConfigError("usage: nodehop config set <key> <value>")
489
+ if args.key not in data:
490
+ raise ConfigError(f"unknown setting '{args.key}' (known: {', '.join(sorted(data))})")
491
+ try:
492
+ value = json.loads(args.value)
493
+ except ValueError:
494
+ value = args.value
495
+ if args.key == "unattended":
496
+ # One setting, each agent's own flags: Claude Code's permission mode; for Codex, no
497
+ # approval prompts but a sandbox limited to the project folder.
498
+ args_wo = [a for i, a in enumerate(cfg.claude_args)
499
+ if a != "--permission-mode" and (i == 0 or cfg.claude_args[i - 1] != "--permission-mode")]
500
+ cfg.claude_args = args_wo + (["--permission-mode", str(value)] if value and value != "default" else [])
501
+ codex_wo = []
502
+ skip = False
503
+ for i, a in enumerate(cfg.codex_args):
504
+ if skip:
505
+ skip = False
506
+ continue
507
+ if a == "-c" and i + 1 < len(cfg.codex_args) and cfg.codex_args[i + 1].startswith(("approval_policy=", "sandbox_mode=")):
508
+ skip = True
509
+ continue
510
+ codex_wo.append(a)
511
+ cfg.codex_args = codex_wo + (["-c", 'approval_policy="never"', "-c", 'sandbox_mode="workspace-write"']
512
+ if value and value != "default" else [])
513
+ setattr(cfg, args.key, value)
514
+ cfg.save()
515
+ print(f"{args.key} = {json.dumps(value)}")
516
+ return 0
517
+
518
+
519
+ def onboard_wizard(runner: Runner) -> int:
520
+ """The same steps as `nodehop onboard --json`, asked in the terminal."""
521
+ import subprocess
522
+
523
+ from nodehop import onboard
524
+
525
+ skipped: List[str] = []
526
+ ui.title("NodeHop onboarding")
527
+ print(" Your agents keep working when you close the lid. A few questions, then NodeHop does the rest.\n")
528
+ while True:
529
+ p = onboard.plan(runner, skip=skipped)
530
+ marks = {"done": ui.style("✓", "green"), "skipped": ui.style("–", "dim"),
531
+ "todo": ui.style("○", "dim"), "needs-person": ui.style("!", "yellow")}
532
+ print(" " + " ".join(f"{marks[st['status']]} {st['title']}" for st in p["steps"]) + "\n")
533
+ step = p["next"]
534
+ if p["complete"] or step is None:
535
+ for line in p.get("summary", []):
536
+ ui.ok(line)
537
+ return 0
538
+ if step["id"] == "check":
539
+ cfg = doctor.load_config()
540
+ checks = doctor.run_checks(cfg, runner)
541
+ for c in checks:
542
+ if c["status"] != "ok":
543
+ (ui.fail if c["status"] == "fail" else ui.warn)(f"{c['id']}: {c['detail']}")
544
+ if c["fix"]:
545
+ print(ui.style(f" fix: {c['fix']}", "dim"))
546
+ if doctor.healthy(checks):
547
+ ui.ok("All good.")
548
+ return 0 if doctor.healthy(checks) else 1
549
+ print(ui.style(f" {step['title']}", "bold") + ui.style(f" — {step['why']}", "dim"))
550
+ answers: Dict[str, str] = {}
551
+ for q in step["questions"]:
552
+ if q.get("when") and any(answers.get(k) != v for k, v in q["when"].items()):
553
+ continue
554
+ default = q.get("default")
555
+ if q["id"] == "other_name" and not default and answers.get("host"):
556
+ default = pairing.suggested_name(answers["host"])
557
+ if q.get("choices"):
558
+ labels = [c["label"] for c in q["choices"]] + (["Other…"] if q["id"] == "host" else [])
559
+ values = [c["value"] for c in q["choices"]]
560
+ start = values.index(default) if default in values else 0
561
+ pick = ui.select(q["ask"], labels, default=start)
562
+ answers[q["id"]] = values[pick] if pick < len(values) else ui.ask("Host name or IP?")
563
+ else:
564
+ answers[q["id"]] = ui.ask(q["ask"], default)
565
+ command = onboard.fill_command(step, answers)
566
+ if command is None:
567
+ skipped.append(step["id"])
568
+ continue
569
+ command = command.replace(" --json", "")
570
+ print(ui.style(f" $ {command}", "dim"))
571
+ if subprocess.run(command, shell=True).returncode != 0:
572
+ if step.get("if_it_fails"):
573
+ ui.warn(step["if_it_fails"])
574
+ again = ui.select("That did not work. What now?", ["Try again", "Skip this step", "Stop here"])
575
+ if again == 1:
576
+ skipped.append(step["id"])
577
+ elif again == 2:
578
+ return 1
579
+ print()
580
+
581
+
582
+ def cmd_setup(args, runner: Runner) -> int:
583
+ if not (args.name or args.json or args.no_wizard) and ui.interactive():
584
+ return onboard_wizard(runner)
585
+ cfg, data = do_setup(runner, args.name, True if args.primary else None, args.workspace, args.host)
586
+ token = data["token"]
587
+ checks = data["checks"]
588
+ role = data["role"]
589
+ text = (
590
+ f"{cfg.machine} is set up ({role}), config in {Config.path()}\n\n{doctor.summary(checks)}\n\n"
591
+ f"Pairing token (run `nodehop pair <token>` on the other machine):\n{token}"
592
+ )
593
+ emit(args, data, text)
594
+ return 0
595
+
596
+
597
+ def cmd_invite(args, cfg: Config, runner: Runner) -> int:
598
+ hosts = args.host or pairing.local_hosts(runner)
599
+ token = pairing.make_token(cfg, hosts)
600
+ emit(args, {"machine": cfg.machine, "hosts": hosts, "token": token}, token)
601
+ return 0
602
+
603
+
604
+ def cmd_pair(args, cfg: Config, runner: Runner) -> int:
605
+ info = pairing.parse_token(args.token)
606
+ result = pairing.pair_with(cfg, info, host=args.host, default=args.default, dry_run=runner.dry_run)
607
+ name, host = result["peer"], result["host"]
608
+ if not runner.dry_run:
609
+ cfg.save()
610
+ is_primary = cfg.primary == cfg.machine
611
+ reachable = NodeHop(cfg, runner).transport(name).is_up() if is_primary else None
612
+ my_token = pairing.make_token(cfg, pairing.local_hosts(runner))
613
+ data = {
614
+ **result,
615
+ "peer_reachable": reachable,
616
+ "token": my_token,
617
+ "next": None if (reachable or not is_primary) else f"on {name}: nodehop pair {my_token}",
618
+ }
619
+ if is_primary:
620
+ lines = [f"paired with {name} ({info['user']}@{host})"]
621
+ if reachable:
622
+ lines.append(f"{name} answers over SSH: ready")
623
+ else:
624
+ lines.append(f"{name} does not accept this machine yet. On {name}, run:\n nodehop pair {my_token}")
625
+ else:
626
+ lines = [f"paired with {name}; {name} may now log in here to hand work over"]
627
+ emit(args, data, "\n".join(lines))
628
+ return 0
629
+
630
+
631
+ def cmd_doctor(args, runner: Runner) -> int:
632
+ cfg = doctor.load_config()
633
+ checks = doctor.run_checks(cfg, runner, peers=not args.offline)
634
+ ok = doctor.healthy(checks)
635
+ emit(args, {"healthy": ok, "checks": checks}, doctor.summary(checks))
636
+ return 0 if ok else 1
637
+
638
+
639
+ def widen_path(extra_path: List[str]) -> None:
640
+ """SleepWatcher, launchd and SSH start us with a bare PATH: add Homebrew, ~/.local/bin, etc."""
641
+ home = str(Path.home())
642
+ current = os.environ.get("PATH", "/usr/bin:/bin:/usr/sbin:/sbin").split(":")
643
+ extra = [p.replace("$HOME", home) for p in extra_path]
644
+ os.environ["PATH"] = ":".join(extra + [p for p in current if p not in extra])
645
+
646
+
647
+ def run(argv: Optional[List[str]] = None) -> int:
648
+ args = build_parser().parse_args(argv)
649
+ widen_path(doctor.load_config().extra_path if Config.path().exists() else list(DEFAULT_EXTRA_PATH))
650
+ if args.command == "init":
651
+ return cmd_init(args)
652
+ if args.command == "setup":
653
+ return cmd_setup(args, Runner(dry_run=args.dry_run, verbose=args.verbose))
654
+ if args.command == "doctor":
655
+ return cmd_doctor(args, Runner(dry_run=args.dry_run, verbose=args.verbose))
656
+ if args.command == "onboard":
657
+ from nodehop import onboard
658
+
659
+ runner = Runner(dry_run=args.dry_run, verbose=args.verbose)
660
+ if args.json or not ui.interactive():
661
+ print(json.dumps(onboard.plan(runner, skip=args.skip), indent=2))
662
+ return 0
663
+ return onboard_wizard(runner)
664
+ if args.command == "config":
665
+ return cmd_config(args)
666
+ if args.command == "uninstall":
667
+ return cmd_uninstall(args)
668
+ if args.command == "discover":
669
+ peers = pairing.tailnet_peers(Runner(dry_run=args.dry_run, verbose=args.verbose))
670
+ text = "\n".join(f"{p['name']:<28} {p['host']:<45} {p['os']:<8} {'online' if p['online'] else 'offline'}" for p in peers)
671
+ emit(args, {"tailscale": bool(peers), "peers": peers}, text or "no Tailscale peers found (is Tailscale running?)")
672
+ return 0
673
+ if args.command == "deploy":
674
+ runner = Runner(dry_run=args.dry_run, verbose=args.verbose)
675
+ cfg = Config.load()
676
+ report = deploy.deploy(cfg, runner, args.destination, name=args.name,
677
+ interactive=ui.interactive() and not args.json, hooks=not args.no_hooks)
678
+ if args.json:
679
+ print(json.dumps(report, indent=2))
680
+ return 0 if report.get("this_to_peer") or report.get("dry_run") else 1
681
+ return show_deploy(report, cfg) if not report.get("dry_run") else 0
682
+ if args.command == "ping":
683
+ try:
684
+ name = Config.load().machine
685
+ except ConfigError:
686
+ name = "unconfigured"
687
+ print(f"nodehop {__version__} on {name}: ok")
688
+ return 0
689
+
690
+ cfg = Config.load()
691
+ if args.command == "peer":
692
+ return cmd_peer(args, cfg)
693
+ if args.command == "project":
694
+ return cmd_project(args, cfg)
695
+
696
+ runner = Runner(dry_run=args.dry_run, verbose=args.verbose)
697
+ if args.command in ("on", "off"):
698
+ return cmd_on_off(args, cfg, runner)
699
+ if args.command == "invite":
700
+ return cmd_invite(args, cfg, runner)
701
+ if args.command == "pair":
702
+ return cmd_pair(args, cfg, runner)
703
+ hop = NodeHop(cfg, runner)
704
+ c = args.command
705
+ if c == "prepare":
706
+ print(json.dumps(hop.prepare(args.project, args.module, args.origin_path, args.origin_home)))
707
+ return 0
708
+ if c == "status":
709
+ return cmd_status(hop)
710
+ if c == "start":
711
+ hop.start(args.project, resume=args.resume)
712
+ print(f"attach with: nodehop attach {args.project}")
713
+ return 0
714
+ if c == "attach":
715
+ session = f"nh-{cfg.project(args.project).name}"
716
+ os.execvp("tmux", tmux_argv("attach", "-t", f"={session}"))
717
+ if c == "stop":
718
+ hop.stop(args.project)
719
+ return 0
720
+ if c == "handoff":
721
+ names = args.projects or hop.owned_here()
722
+ done = hop.handoff(names, cfg.target(args.to), reason=args.reason, force=args.force)
723
+ return 0 if len(done) == len(names) else 1
724
+ if c == "pull":
725
+ names = args.projects or hop.away_from_home()
726
+ if not names:
727
+ print("nothing to bring back")
728
+ return 0
729
+ done = hop.pull(names)
730
+ return 0 if len(done) == len(names) else 1
731
+ if c == "resolve":
732
+ return cmd_resolve(args, hop)
733
+ if c == "gui-ask":
734
+ from nodehop import gui
735
+
736
+ keep = gui.linux_choose(hop.conflict_report(args.project))
737
+ if keep:
738
+ hop.resolve(args.project, keep)
739
+ gui.notify(args.project, f"Kept {'the other machine' if keep == 'there' else 'this machine'}'s version")
740
+ return 0
741
+ if c == "pause":
742
+ hop.pause(args.project)
743
+ return 0
744
+ if c == "progress":
745
+ print(json.dumps(hop.progress(args.project, args.since)))
746
+ return 0
747
+ if c == "heartbeat":
748
+ hop.heartbeat(args.origin, json.loads(args.meta))
749
+ return 0
750
+ if c == "claims":
751
+ print(json.dumps(hop.claims()))
752
+ return 0
753
+ if c == "abandon":
754
+ hop.abandon(args.project, args.to)
755
+ return 0
756
+ if c == "release":
757
+ print(json.dumps(hop.release(args.project, args.to)))
758
+ return 0
759
+ if c == "released":
760
+ hop.released(args.project, args.to)
761
+ return 0
762
+ if c == "sync":
763
+ import signal as _signal
764
+
765
+ def _stop(signum, frame): # preempted by a sleep handoff: abort the copy, release the lock
766
+ raise SystemExit(0)
767
+
768
+ _signal.signal(_signal.SIGTERM, _stop)
769
+ hop.sync(cfg.target(args.to))
770
+ return 0
771
+ if c == "watch":
772
+ hop.watch(once=args.once)
773
+ return 0
774
+ if c in ("on-sleep", "on-wake"):
775
+ started = time.monotonic()
776
+ runner.log(f"{c}: start")
777
+ done = hop.on_sleep() if c == "on-sleep" else hop.on_wake()
778
+ runner.log(f"{c}: done in {time.monotonic() - started:.1f}s ({', '.join(done) or 'nothing to move'})")
779
+ return 0
780
+ if c == "receive":
781
+ hop.receive(args.project, args.origin, json.loads(args.meta))
782
+ return 0
783
+ if c == "install-hooks":
784
+ exe = shutil.which("nodehop") or os.path.abspath(sys.argv[0])
785
+ written, todo = hooks.install(exe, cfg.machine == cfg.primary, cfg.extra_path, args.sync_interval)
786
+ ran, left = hooks.apply(todo, runner) if args.apply else ([], todo)
787
+ if args.json:
788
+ print(json.dumps({"written": written, "ran": ran, "left": left, "ok": all(r["ok"] for r in ran)}))
789
+ return 0 if all(r["ok"] for r in ran) else 1
790
+ print("wrote:\n " + "\n ".join(written))
791
+ for r in ran:
792
+ print(("ran: " if r["ok"] else "FAILED: ") + r["command"] + ("" if r["ok"] else f"\n {r['output']}"))
793
+ if left:
794
+ print(("still to run (needs an administrator):" if args.apply else "now run:") + "\n " + "\n ".join(left))
795
+ return 0 if all(r["ok"] for r in ran) else 1
796
+ raise AssertionError(c)
797
+
798
+
799
+ def main(argv: Optional[List[str]] = None) -> int:
800
+ try:
801
+ return run(argv)
802
+ except KeyboardInterrupt:
803
+ print("\ncancelled", file=sys.stderr)
804
+ return 130
805
+ except (ConfigError, KeyError, ValueError, RuntimeError, CommandError, TimeoutError, deploy.DeployError) as exc:
806
+ print(f"nodehop: {exc}", file=sys.stderr)
807
+ return 1