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/config.py ADDED
@@ -0,0 +1,183 @@
1
+ """Per-machine configuration, stored as JSON in ~/.config/nodehop/config.json."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ from dataclasses import asdict, dataclass, field
8
+ from pathlib import Path
9
+ from typing import Dict, List, Optional
10
+
11
+ DEFAULT_EXCLUDES = [
12
+ ".DS_Store",
13
+ "node_modules",
14
+ ".venv",
15
+ "venv",
16
+ "__pycache__",
17
+ ".pytest_cache",
18
+ ".mypy_cache",
19
+ ]
20
+
21
+ DEFAULT_RESUME_PROMPT = (
22
+ "NodeHop handoff: you were moved to another machine while working. "
23
+ "Check the current state of the project (git status, last files you touched), "
24
+ "then carry on with the task exactly where you left off."
25
+ )
26
+
27
+ # Non-interactive SSH shells on macOS usually miss Homebrew and ~/.local/bin.
28
+ DEFAULT_EXTRA_PATH = ["/opt/homebrew/bin", "/usr/local/bin", "$HOME/.local/bin", "/home/linuxbrew/.linuxbrew/bin"]
29
+
30
+ # Dedicated key, so pairing never touches the user's own SSH keys.
31
+ DEFAULT_SSH_KEY = "~/.ssh/nodehop_ed25519"
32
+
33
+
34
+ def home_dir() -> Path:
35
+ """Where NodeHop keeps its config, state, lock and log."""
36
+ env = os.environ.get("NODEHOP_HOME")
37
+ if env:
38
+ return Path(env)
39
+ return Path.home() / ".config" / "nodehop"
40
+
41
+
42
+ class ConfigError(Exception):
43
+ pass
44
+
45
+
46
+ @dataclass
47
+ class Peer:
48
+ name: str
49
+ host: str
50
+ user: Optional[str] = None
51
+ nodehop_bin: str = "nodehop"
52
+ port: Optional[int] = None # SSH port, when not 22
53
+
54
+ @property
55
+ def destination(self) -> str:
56
+ return f"{self.user}@{self.host}" if self.user else self.host
57
+
58
+
59
+ @dataclass
60
+ class Project:
61
+ name: str
62
+ path: str
63
+ module: str = "claude-code"
64
+ # Only active projects are pre-synced, handed off at sleep and covered by the fallback
65
+ # (`nodehop on` / `nodehop off`).
66
+ active: bool = True
67
+ # module "command": the shell command to run (a training script, a build…)
68
+ command: Optional[str] = None
69
+
70
+
71
+ @dataclass
72
+ class Config:
73
+ machine: str
74
+ primary: str
75
+ peers: Dict[str, Peer] = field(default_factory=dict)
76
+ projects: Dict[str, Project] = field(default_factory=dict)
77
+ default_target: Optional[str] = None
78
+ excludes: List[str] = field(default_factory=lambda: list(DEFAULT_EXCLUDES))
79
+ poll_seconds: int = 30
80
+ confirm_polls: int = 2
81
+ resume_prompt: str = DEFAULT_RESUME_PROMPT
82
+ claude_bin: str = "claude"
83
+ claude_args: List[str] = field(default_factory=list)
84
+ codex_bin: str = "codex"
85
+ codex_args: List[str] = field(default_factory=list)
86
+ extra_path: List[str] = field(default_factory=lambda: list(DEFAULT_EXTRA_PATH))
87
+ # Where projects received from another machine land. None = mirror the
88
+ # sender's path relative to its home folder (~/repos/app -> ~/repos/app),
89
+ # falling back to ~/NodeHop/<project> for paths outside home.
90
+ workspace: Optional[str] = None
91
+ # Primary: a copy of each active project goes to the server this often (seconds);
92
+ # in between, `nodehop sync` (every 30 s) only sends a heartbeat.
93
+ presync_seconds: int = 300
94
+ # Primary: macOS gives the sleep hook about 30 s. Past this budget the transfer
95
+ # stops and the server resumes from the last complete pre-sync copy instead.
96
+ sleep_budget_seconds: float = 22
97
+ # Primary: heartbeat period while a long copy runs (the sync itself runs every 30 s).
98
+ beat_seconds: float = 30
99
+ # How a resumed agent may act with nobody there: "auto" (Claude Code's auto mode decides
100
+ # permission prompts by itself), "acceptEdits", or "default" (ask as usual). None = not
101
+ # chosen yet. `nodehop config set unattended …` translates it into each agent's flags.
102
+ unattended: Optional[str] = None
103
+ # Claude Code: start NodeHop's sessions with Remote Control, so a resumed agent can be
104
+ # followed and answered from the Claude app (desktop, web, phone).
105
+ remote_control: bool = False
106
+ # Versions set aside after a fallback or a conflict, kept per project (oldest removed).
107
+ backups_keep: int = 5
108
+ # Server side: take over work the primary was doing when it has not been heard of
109
+ # for this long (heartbeats every 30 s). 0 turns the fallback off.
110
+ failover_minutes: float = 2
111
+ ssh_key: str = DEFAULT_SSH_KEY
112
+
113
+ # ---- lookups -------------------------------------------------------
114
+ def peer(self, name: str) -> Peer:
115
+ if name not in self.peers:
116
+ known = ", ".join(sorted(self.peers)) or "none"
117
+ raise ConfigError(f"unknown machine '{name}' (known peers: {known})")
118
+ return self.peers[name]
119
+
120
+ def project(self, name: str) -> Project:
121
+ if name not in self.projects:
122
+ known = ", ".join(sorted(self.projects)) or "none"
123
+ raise ConfigError(f"unknown project '{name}' (known projects: {known})")
124
+ return self.projects[name]
125
+
126
+ def ssh_key_path(self) -> Path:
127
+ return Path(os.path.expanduser(self.ssh_key))
128
+
129
+ def local_path_for(self, name: str, origin_path: str, origin_home: Optional[str]) -> str:
130
+ """Where a project coming from another machine should live on this one."""
131
+ if name in self.projects:
132
+ return self.projects[name].path
133
+ home = Path.home()
134
+ if self.workspace:
135
+ return str(Path(os.path.expanduser(self.workspace)) / name)
136
+ if origin_home:
137
+ try:
138
+ rel = Path(origin_path).relative_to(origin_home)
139
+ except ValueError:
140
+ rel = None
141
+ if rel is not None and rel.parts:
142
+ return str(home / rel)
143
+ return str(home / "NodeHop" / name)
144
+
145
+ def target(self, explicit: Optional[str] = None) -> str:
146
+ name = explicit or self.default_target
147
+ if not name:
148
+ if len(self.peers) == 1:
149
+ name = next(iter(self.peers))
150
+ else:
151
+ raise ConfigError("no target machine: pass --to or set one with `nodehop peer add --default`")
152
+ self.peer(name)
153
+ return name
154
+
155
+ # ---- persistence ---------------------------------------------------
156
+ @staticmethod
157
+ def path() -> Path:
158
+ return home_dir() / "config.json"
159
+
160
+ @classmethod
161
+ def load(cls) -> "Config":
162
+ p = cls.path()
163
+ if not p.exists():
164
+ raise ConfigError(f"no config at {p}: run `nodehop init` first")
165
+ raw = json.loads(p.read_text())
166
+ raw["peers"] = {k: Peer(name=k, **v) for k, v in raw.get("peers", {}).items()}
167
+ raw["projects"] = {k: Project(name=k, **v) for k, v in raw.get("projects", {}).items()}
168
+ return cls(**raw)
169
+
170
+ def to_dict(self) -> dict:
171
+ data = asdict(self)
172
+ for group in ("peers", "projects"):
173
+ for item in data[group].values():
174
+ item.pop("name", None)
175
+ return data
176
+
177
+ def save(self) -> Path:
178
+ p = self.path()
179
+ p.parent.mkdir(parents=True, exist_ok=True)
180
+ tmp = p.with_suffix(".tmp")
181
+ tmp.write_text(json.dumps(self.to_dict(), indent=2) + "\n")
182
+ tmp.replace(p)
183
+ return p