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/__init__.py +3 -0
- nodehop/__main__.py +3 -0
- nodehop/cli.py +807 -0
- nodehop/config.py +183 -0
- nodehop/core.py +642 -0
- nodehop/deploy.py +205 -0
- nodehop/doctor.py +285 -0
- nodehop/gui.py +338 -0
- nodehop/hooks.py +193 -0
- nodehop/icon.py +148 -0
- nodehop/modules/__init__.py +26 -0
- nodehop/modules/base.py +214 -0
- nodehop/modules/claude_code.py +309 -0
- nodehop/modules/codex.py +209 -0
- nodehop/modules/command.py +81 -0
- nodehop/onboard.py +210 -0
- nodehop/pairing.py +217 -0
- nodehop/runner.py +72 -0
- nodehop/state.py +120 -0
- nodehop/system.py +41 -0
- nodehop/train.py +200 -0
- nodehop/transport.py +107 -0
- nodehop/ui.py +140 -0
- nodehop/uninstall.py +145 -0
- nodehop-0.2.0.dist-info/METADATA +261 -0
- nodehop-0.2.0.dist-info/RECORD +30 -0
- nodehop-0.2.0.dist-info/WHEEL +5 -0
- nodehop-0.2.0.dist-info/entry_points.txt +2 -0
- nodehop-0.2.0.dist-info/licenses/LICENSE +21 -0
- nodehop-0.2.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
"""Task modules: each one knows how to stop, snapshot and resume one kind of work."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Dict, Type
|
|
6
|
+
|
|
7
|
+
from nodehop.modules.base import Module
|
|
8
|
+
from nodehop.modules.claude_code import ClaudeCodeModule
|
|
9
|
+
from nodehop.modules.codex import CodexModule
|
|
10
|
+
from nodehop.modules.command import CommandModule
|
|
11
|
+
|
|
12
|
+
MODULES: Dict[str, Type[Module]] = {
|
|
13
|
+
ClaudeCodeModule.name: ClaudeCodeModule,
|
|
14
|
+
CodexModule.name: CodexModule,
|
|
15
|
+
CommandModule.name: CommandModule,
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def get_module(name: str) -> Type[Module]:
|
|
20
|
+
if name not in MODULES:
|
|
21
|
+
raise KeyError(f"unknown module '{name}' (available: {', '.join(sorted(MODULES))})")
|
|
22
|
+
return MODULES[name]
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
# `nodehop on --agent <name>`: friendly names for the modules that run an agent.
|
|
26
|
+
AGENTS = {"claude": "claude-code", "claude-code": "claude-code", "codex": "codex"}
|
nodehop/modules/base.py
ADDED
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
"""Base class for task modules, with the tmux plumbing they share.
|
|
2
|
+
|
|
3
|
+
Every agent NodeHop manages runs inside a tmux session called `nh-<project>`
|
|
4
|
+
on NodeHop's own tmux server (`tmux -L nodehop`), so it keeps running with no
|
|
5
|
+
terminal attached, can be stopped cleanly before a handoff, and never mixes
|
|
6
|
+
with the person's own tmux sessions.
|
|
7
|
+
|
|
8
|
+
Where that server runs matters:
|
|
9
|
+
- macOS: an agent started from an SSH session cannot read the login keychain,
|
|
10
|
+
so Claude Code reports "Not logged in". NodeHop's tmux server is therefore
|
|
11
|
+
started by launchd inside the graphical session (a LaunchAgent), which has
|
|
12
|
+
the keychain; sessions created over SSH are spawned by that server.
|
|
13
|
+
- Linux: started from SSH, tmux would be killed at logout where logind kills
|
|
14
|
+
user processes, so it is started in a systemd user scope.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import os
|
|
20
|
+
import shutil
|
|
21
|
+
from pathlib import Path
|
|
22
|
+
from typing import List, Tuple
|
|
23
|
+
|
|
24
|
+
from nodehop.config import Config, Project
|
|
25
|
+
from nodehop.runner import Runner
|
|
26
|
+
from nodehop.system import has_systemd_run, os_name
|
|
27
|
+
|
|
28
|
+
TMUX_SOCKET = "nodehop"
|
|
29
|
+
TMUX_AGENT_LABEL = "dev.nodehop.tmux"
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def changed_files(root: str, since: float, excludes: List[str]) -> List[Tuple[str, float]]:
|
|
33
|
+
"""Files under `root` modified after `since`, as (relative path, mtime)."""
|
|
34
|
+
out: List[Tuple[str, float]] = []
|
|
35
|
+
skip = set(excludes) | {".git"}
|
|
36
|
+
for dirpath, dirnames, filenames in os.walk(root):
|
|
37
|
+
dirnames[:] = [d for d in dirnames if d not in skip]
|
|
38
|
+
for f in filenames:
|
|
39
|
+
if f in skip:
|
|
40
|
+
continue
|
|
41
|
+
full = os.path.join(dirpath, f)
|
|
42
|
+
try:
|
|
43
|
+
mtime = os.stat(full).st_mtime
|
|
44
|
+
except OSError:
|
|
45
|
+
continue
|
|
46
|
+
if mtime >= since:
|
|
47
|
+
out.append((os.path.relpath(full, root), mtime))
|
|
48
|
+
return out
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def tmux(*args: str) -> List[str]:
|
|
52
|
+
return ["tmux", "-L", TMUX_SOCKET, *args]
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class Module:
|
|
56
|
+
name = ""
|
|
57
|
+
|
|
58
|
+
def __init__(self, config: Config, runner: Runner):
|
|
59
|
+
self.config = config
|
|
60
|
+
self.runner = runner
|
|
61
|
+
|
|
62
|
+
# ---- what each module implements -----------------------------------
|
|
63
|
+
def snapshot(self, project: Project) -> dict:
|
|
64
|
+
"""Metadata the other machine needs to resume (called after stop)."""
|
|
65
|
+
return {}
|
|
66
|
+
|
|
67
|
+
def payload(self, project: Project, meta: dict) -> List[Tuple[str, Path]]:
|
|
68
|
+
"""Directories outside the project to send along: (label, local dir).
|
|
69
|
+
|
|
70
|
+
Each one lands in the receiver's inbox under <label>/, and
|
|
71
|
+
accept_payload() puts it in place there (paths may differ per machine).
|
|
72
|
+
"""
|
|
73
|
+
return []
|
|
74
|
+
|
|
75
|
+
def accept_payload(self, project: Project, inbox: Path, meta: dict) -> None:
|
|
76
|
+
"""Receiver side: move what payload() sent from the inbox into place."""
|
|
77
|
+
|
|
78
|
+
def command(self, project: Project, meta: dict, resume: bool) -> List[str]:
|
|
79
|
+
raise NotImplementedError
|
|
80
|
+
|
|
81
|
+
def should_resume(self, meta: dict) -> bool:
|
|
82
|
+
"""After a handoff, start it again over there? (Claude Code: reopen even if idle.)"""
|
|
83
|
+
return True
|
|
84
|
+
|
|
85
|
+
def environment(self, project: Project, meta: dict, resume: bool) -> dict:
|
|
86
|
+
"""Variables for the agent's process (tmux new-session -e)."""
|
|
87
|
+
return {"NODEHOP_MACHINE": self.config.machine, "NODEHOP_RESUMED": "1" if resume else "0"}
|
|
88
|
+
|
|
89
|
+
# ---- shared tmux lifecycle --------------------------------------------
|
|
90
|
+
@staticmethod
|
|
91
|
+
def session(project: Project) -> str:
|
|
92
|
+
return f"nh-{project.name}"
|
|
93
|
+
|
|
94
|
+
def is_running(self, project: Project) -> bool:
|
|
95
|
+
result = self.runner.run(tmux("has-session", "-t", f"={self.session(project)}"), check=False, mutating=False)
|
|
96
|
+
return result.returncode == 0
|
|
97
|
+
|
|
98
|
+
def screen(self, project: Project) -> str:
|
|
99
|
+
"""What the agent's terminal shows right now (empty if not running)."""
|
|
100
|
+
result = self.runner.run(
|
|
101
|
+
tmux("capture-pane", "-p", "-t", f"={self.session(project)}:"), check=False, mutating=False
|
|
102
|
+
)
|
|
103
|
+
return result.stdout if result.returncode == 0 else ""
|
|
104
|
+
|
|
105
|
+
def is_busy(self, project: Project) -> bool:
|
|
106
|
+
"""Was the agent in the middle of something? Modules that can tell override this.
|
|
107
|
+
|
|
108
|
+
True means "resume and tell it to carry on" (costs a turn); False means
|
|
109
|
+
"reopen the conversation and wait" (costs nothing).
|
|
110
|
+
"""
|
|
111
|
+
return True
|
|
112
|
+
|
|
113
|
+
def progress(self, project: Project, since: float) -> dict:
|
|
114
|
+
"""How far this machine's copy got since `since` (epoch): shown when two agents ran in parallel."""
|
|
115
|
+
files = sorted(changed_files(project.path, since, self.config.excludes), key=lambda x: -x[1])
|
|
116
|
+
running = self.is_running(project)
|
|
117
|
+
details = []
|
|
118
|
+
for rel, _ in files[:5]:
|
|
119
|
+
full = os.path.join(project.path, rel)
|
|
120
|
+
try:
|
|
121
|
+
if os.path.getsize(full) <= 2_000_000:
|
|
122
|
+
with open(full, "rb") as fh:
|
|
123
|
+
details.append({"path": rel, "lines": fh.read().count(b"\n")})
|
|
124
|
+
continue
|
|
125
|
+
except OSError:
|
|
126
|
+
pass
|
|
127
|
+
details.append({"path": rel, "lines": None})
|
|
128
|
+
return {"running": running, "busy": running and self.is_busy(project), "actions": None,
|
|
129
|
+
"last_activity": max((m for _, m in files), default=None), "last_message": None,
|
|
130
|
+
"files": [f for f, _ in files][:5], "file_details": details, "files_count": len(files)}
|
|
131
|
+
|
|
132
|
+
def send_message(self, project: Project, text: str) -> bool:
|
|
133
|
+
"""Type a message into the agent's terminal (it is queued if the agent is busy)."""
|
|
134
|
+
if not self.is_running(project):
|
|
135
|
+
return False
|
|
136
|
+
target = f"={self.session(project)}:"
|
|
137
|
+
self.runner.run(tmux("send-keys", "-t", target, "-l", text), check=False)
|
|
138
|
+
self.runner.run(tmux("send-keys", "-t", target, "Enter"), check=False)
|
|
139
|
+
return True
|
|
140
|
+
|
|
141
|
+
def ensure_server(self) -> None:
|
|
142
|
+
"""macOS: make sure NodeHop's tmux server lives in the graphical session (keychain access)."""
|
|
143
|
+
if os_name() != "macos":
|
|
144
|
+
return
|
|
145
|
+
domain = f"gui/{os.getuid()}"
|
|
146
|
+
if self.runner.run(["launchctl", "print", f"{domain}/{TMUX_AGENT_LABEL}"], check=False, mutating=False).returncode == 0:
|
|
147
|
+
return
|
|
148
|
+
from nodehop.hooks import launch_agent # avoid a module cycle at import time
|
|
149
|
+
|
|
150
|
+
home = Path.home()
|
|
151
|
+
path = ":".join(p.replace("$HOME", str(home)) for p in self.config.extra_path) + ":/usr/bin:/bin:/usr/sbin:/sbin"
|
|
152
|
+
tmux_bin = shutil.which("tmux", path=path) or "tmux"
|
|
153
|
+
plist = home / "Library" / "LaunchAgents" / f"{TMUX_AGENT_LABEL}.plist"
|
|
154
|
+
if self.runner.dry_run:
|
|
155
|
+
self.runner.log(f"[dry-run] would start NodeHop's tmux server in the graphical session ({plist})")
|
|
156
|
+
return
|
|
157
|
+
if self.runner.run(["tmux", "-L", TMUX_SOCKET, "list-sessions"], check=False, mutating=False).returncode == 0:
|
|
158
|
+
# A server started outside launchd (e.g. from SSH) would hand out sessions without keychain access.
|
|
159
|
+
self.runner.log("tmux -L nodehop is running outside the graphical session: agents there may not be logged in")
|
|
160
|
+
plist.parent.mkdir(parents=True, exist_ok=True)
|
|
161
|
+
plist.write_bytes(launch_agent(TMUX_AGENT_LABEL, [tmux_bin, "-L", TMUX_SOCKET, "-D"], self.config.extra_path, None))
|
|
162
|
+
result = self.runner.run(["launchctl", "bootstrap", domain, str(plist)], check=False)
|
|
163
|
+
if result.returncode != 0:
|
|
164
|
+
self.runner.log(
|
|
165
|
+
"no graphical session open here (nobody logged in on the screen): the agent may not reach "
|
|
166
|
+
"the keychain and report 'Not logged in'. Turn on automatic login for this user."
|
|
167
|
+
)
|
|
168
|
+
return
|
|
169
|
+
socket = Path(f"/tmp/tmux-{os.getuid()}") / TMUX_SOCKET
|
|
170
|
+
for _ in range(20):
|
|
171
|
+
if socket.exists():
|
|
172
|
+
break
|
|
173
|
+
self.runner.sleep(0.25)
|
|
174
|
+
|
|
175
|
+
def start(self, project: Project, meta: dict, resume: bool) -> None:
|
|
176
|
+
if self.is_running(project):
|
|
177
|
+
self.runner.log(f"{project.name}: already running in tmux session {self.session(project)}")
|
|
178
|
+
return
|
|
179
|
+
self.ensure_server()
|
|
180
|
+
argv = self.command(project, meta, resume)
|
|
181
|
+
env = [arg for k, v in self.environment(project, meta, resume).items() for arg in ("-e", f"{k}={v}")]
|
|
182
|
+
new = tmux("new-session", "-d", "-s", self.session(project), "-c", project.path, *env, *argv)
|
|
183
|
+
if has_systemd_run():
|
|
184
|
+
# Linux: started from an SSH session, tmux would die at logout where logind kills
|
|
185
|
+
# user processes; a scope of the user's systemd keeps it alive (with lingering on).
|
|
186
|
+
if self.runner.run(["systemd-run", "--user", "--scope", "--quiet", "--collect", *new], check=False).returncode == 0:
|
|
187
|
+
self.runner.log(f"{project.name}: started in tmux session {self.session(project)}")
|
|
188
|
+
return
|
|
189
|
+
self.runner.run(new)
|
|
190
|
+
self.runner.log(f"{project.name}: started in tmux session {self.session(project)}")
|
|
191
|
+
|
|
192
|
+
def stop(self, project: Project, attempts: int = 6, interval: float = 0.4, grace_seconds: float = 2.0) -> bool:
|
|
193
|
+
"""Ask the agent to exit, then kill the session if it is still there. Returns True if it was running.
|
|
194
|
+
|
|
195
|
+
Claude Code needs one Ctrl-C to interrupt its current step and two more to
|
|
196
|
+
quit (measured: ~0.7 s when idle, ~1.4 s while working), so Ctrl-C is sent
|
|
197
|
+
every `interval` seconds until the session is gone.
|
|
198
|
+
"""
|
|
199
|
+
if not self.is_running(project):
|
|
200
|
+
return False
|
|
201
|
+
target = f"={self.session(project)}"
|
|
202
|
+
for _ in range(attempts):
|
|
203
|
+
self.runner.run(tmux("send-keys", "-t", f"{target}:", "C-c"), check=False)
|
|
204
|
+
self.runner.sleep(interval)
|
|
205
|
+
if self.runner.dry_run or not self.is_running(project):
|
|
206
|
+
break
|
|
207
|
+
waited = 0.0
|
|
208
|
+
while waited < grace_seconds and not self.runner.dry_run and self.is_running(project):
|
|
209
|
+
self.runner.sleep(0.25)
|
|
210
|
+
waited += 0.25
|
|
211
|
+
if self.runner.dry_run or self.is_running(project):
|
|
212
|
+
self.runner.run(tmux("kill-session", "-t", target), check=False)
|
|
213
|
+
self.runner.log(f"{project.name}: stopped")
|
|
214
|
+
return True
|
|
@@ -0,0 +1,309 @@
|
|
|
1
|
+
"""Claude Code module.
|
|
2
|
+
|
|
3
|
+
Claude Code keeps each conversation as a JSONL file under
|
|
4
|
+
~/.claude/projects/<encoded project path>/<session id>.jsonl, where the
|
|
5
|
+
encoded path is the absolute project path with every non-alphanumeric
|
|
6
|
+
character replaced by '-'. Copying that folder to the folder matching the
|
|
7
|
+
project's path on the other machine (and rewriting the `cwd` recorded in each
|
|
8
|
+
line when the path differs) lets `claude --resume <session id>` pick the
|
|
9
|
+
conversation up there.
|
|
10
|
+
|
|
11
|
+
This layout is Claude Code's internal format and may change between
|
|
12
|
+
versions, so the lookup falls back to scanning session files for their
|
|
13
|
+
recorded working directory.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import json
|
|
19
|
+
import os
|
|
20
|
+
import re
|
|
21
|
+
import shutil
|
|
22
|
+
from pathlib import Path
|
|
23
|
+
from typing import List, Optional, Tuple
|
|
24
|
+
|
|
25
|
+
from nodehop.config import Project
|
|
26
|
+
from nodehop.modules.base import Module
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def claude_home() -> Path:
|
|
30
|
+
return Path(os.environ.get("CLAUDE_CONFIG_DIR") or Path.home() / ".claude")
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def claude_settings_file() -> Path:
|
|
34
|
+
"""Claude Code's own state file, which records per-folder trust."""
|
|
35
|
+
env = os.environ.get("CLAUDE_CONFIG_DIR")
|
|
36
|
+
return Path(env) / ".claude.json" if env else Path.home() / ".claude.json"
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def is_trusted(project_path: str) -> bool:
|
|
40
|
+
try:
|
|
41
|
+
data = json.loads(claude_settings_file().read_text())
|
|
42
|
+
except (OSError, ValueError):
|
|
43
|
+
return False
|
|
44
|
+
return bool((data.get("projects") or {}).get(project_path, {}).get("hasTrustDialogAccepted"))
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def mark_trusted(project_path: str) -> bool:
|
|
48
|
+
"""Record that the person trusts this folder, so a resumed agent is not stuck on the trust prompt.
|
|
49
|
+
|
|
50
|
+
Only called when the folder was already trusted on the machine it came from.
|
|
51
|
+
Returns True if the file changed.
|
|
52
|
+
"""
|
|
53
|
+
path = claude_settings_file()
|
|
54
|
+
try:
|
|
55
|
+
data = json.loads(path.read_text())
|
|
56
|
+
except OSError:
|
|
57
|
+
data = {}
|
|
58
|
+
except ValueError:
|
|
59
|
+
return False # never overwrite a file we cannot read
|
|
60
|
+
projects = data.setdefault("projects", {})
|
|
61
|
+
entry = projects.setdefault(project_path, {})
|
|
62
|
+
if entry.get("hasTrustDialogAccepted"):
|
|
63
|
+
return False
|
|
64
|
+
entry["hasTrustDialogAccepted"] = True
|
|
65
|
+
tmp = path.with_name(path.name + ".nodehop-tmp")
|
|
66
|
+
tmp.write_text(json.dumps(data, indent=2))
|
|
67
|
+
tmp.replace(path)
|
|
68
|
+
return True
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def encode_project_path(path: str) -> str:
|
|
72
|
+
return re.sub(r"[^A-Za-z0-9]", "-", path)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _session_cwd(session_file: Path, max_lines: int = 50) -> Optional[str]:
|
|
76
|
+
try:
|
|
77
|
+
with open(session_file, encoding="utf-8", errors="replace") as fh:
|
|
78
|
+
for i, line in enumerate(fh):
|
|
79
|
+
if i >= max_lines:
|
|
80
|
+
break
|
|
81
|
+
try:
|
|
82
|
+
cwd = json.loads(line).get("cwd")
|
|
83
|
+
except (ValueError, AttributeError):
|
|
84
|
+
continue
|
|
85
|
+
if cwd:
|
|
86
|
+
return cwd
|
|
87
|
+
except OSError:
|
|
88
|
+
pass
|
|
89
|
+
return None
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def find_project_dir(project_path: str, home: Optional[Path] = None) -> Optional[Path]:
|
|
93
|
+
projects = (home or claude_home()) / "projects"
|
|
94
|
+
direct = projects / encode_project_path(project_path)
|
|
95
|
+
if direct.is_dir():
|
|
96
|
+
return direct
|
|
97
|
+
if not projects.is_dir():
|
|
98
|
+
return None
|
|
99
|
+
wanted = os.path.normpath(project_path)
|
|
100
|
+
for candidate in sorted(projects.iterdir()):
|
|
101
|
+
if not candidate.is_dir():
|
|
102
|
+
continue
|
|
103
|
+
for session_file in candidate.glob("*.jsonl"):
|
|
104
|
+
cwd = _session_cwd(session_file)
|
|
105
|
+
if cwd and os.path.normpath(cwd) == wanted:
|
|
106
|
+
return candidate
|
|
107
|
+
return None
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def latest_session(project_dir: Optional[Path]) -> Optional[str]:
|
|
111
|
+
if not project_dir or not project_dir.is_dir():
|
|
112
|
+
return None
|
|
113
|
+
sessions = sorted(project_dir.glob("*.jsonl"), key=lambda p: p.stat().st_mtime, reverse=True)
|
|
114
|
+
return sessions[0].stem if sessions else None
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
NOT_REQUESTS = ("NodeHop", "This session is being continued", "Caveat:", "<")
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def _is_request(text: str) -> bool:
|
|
121
|
+
"""A message the person typed (not a NodeHop prompt, a context summary or a command echo)."""
|
|
122
|
+
text = text.strip()
|
|
123
|
+
return bool(text) and not text.startswith(NOT_REQUESTS)
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def _describe_tool(block: dict) -> str:
|
|
127
|
+
"""One line for a tool call: the command it ran, or the file it touched."""
|
|
128
|
+
data = block.get("input") or {}
|
|
129
|
+
for key in ("command", "file_path", "path", "pattern", "url", "description"):
|
|
130
|
+
if isinstance(data.get(key), str) and data[key].strip():
|
|
131
|
+
return " ".join(data[key].split())[:120]
|
|
132
|
+
return block.get("name", "tool")
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def _epoch(stamp) -> Optional[float]:
|
|
136
|
+
"""Claude Code timestamps look like 2026-12-04T13:44:27.123Z."""
|
|
137
|
+
if not isinstance(stamp, str):
|
|
138
|
+
return None
|
|
139
|
+
try:
|
|
140
|
+
from datetime import datetime, timezone
|
|
141
|
+
|
|
142
|
+
return datetime.strptime(stamp[:19], "%Y-%m-%dT%H:%M:%S").replace(tzinfo=timezone.utc).timestamp()
|
|
143
|
+
except ValueError:
|
|
144
|
+
return None
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def _rebase(value: str, old: str, new: str) -> str:
|
|
148
|
+
if value == old:
|
|
149
|
+
return new
|
|
150
|
+
if value.startswith(old.rstrip("/") + "/"):
|
|
151
|
+
return new.rstrip("/") + value[len(old.rstrip("/")):]
|
|
152
|
+
return value
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def _rebase_cwd_keys(obj, old_root: str, new_root: str) -> bool:
|
|
156
|
+
"""Rebase every value stored under a key named `cwd`, at any depth. Returns True if any changed."""
|
|
157
|
+
changed = False
|
|
158
|
+
if isinstance(obj, dict):
|
|
159
|
+
for key, value in obj.items():
|
|
160
|
+
if key == "cwd" and isinstance(value, str):
|
|
161
|
+
new = _rebase(value, old_root, new_root)
|
|
162
|
+
if new != value:
|
|
163
|
+
obj[key] = new
|
|
164
|
+
changed = True
|
|
165
|
+
elif isinstance(value, (dict, list)):
|
|
166
|
+
changed = _rebase_cwd_keys(value, old_root, new_root) or changed
|
|
167
|
+
elif isinstance(obj, list):
|
|
168
|
+
for value in obj:
|
|
169
|
+
changed = _rebase_cwd_keys(value, old_root, new_root) or changed
|
|
170
|
+
return changed
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def rewrite_session_file(path: Path, old_root: str, new_root: str) -> int:
|
|
174
|
+
"""Point the `cwd` of every line at the new project path. Returns lines changed.
|
|
175
|
+
|
|
176
|
+
Only values under `cwd` keys are touched (top-level and tool metadata):
|
|
177
|
+
message content is left as is (some blocks are signed, and the resume
|
|
178
|
+
prompt tells the agent the project moved).
|
|
179
|
+
"""
|
|
180
|
+
if old_root == new_root:
|
|
181
|
+
return 0
|
|
182
|
+
changed = 0
|
|
183
|
+
out = []
|
|
184
|
+
with open(path, encoding="utf-8") as fh:
|
|
185
|
+
for line in fh:
|
|
186
|
+
stripped = line.rstrip("\n")
|
|
187
|
+
try:
|
|
188
|
+
obj = json.loads(stripped)
|
|
189
|
+
except ValueError:
|
|
190
|
+
out.append(line)
|
|
191
|
+
continue
|
|
192
|
+
if _rebase_cwd_keys(obj, old_root, new_root):
|
|
193
|
+
changed += 1
|
|
194
|
+
out.append(json.dumps(obj, ensure_ascii=False, separators=(",", ":")) + "\n")
|
|
195
|
+
continue
|
|
196
|
+
out.append(line)
|
|
197
|
+
if changed:
|
|
198
|
+
tmp = path.with_suffix(path.suffix + ".tmp")
|
|
199
|
+
tmp.write_text("".join(out), encoding="utf-8")
|
|
200
|
+
tmp.replace(path)
|
|
201
|
+
return changed
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
# What Claude Code's terminal shows while it works, or while it waits on a permission
|
|
205
|
+
# (both mean the task is not finished). Idle at its prompt, none of these appear.
|
|
206
|
+
BUSY_MARKERS = ("esc to interrupt", "do you want to proceed", "esc to cancel")
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
class ClaudeCodeModule(Module):
|
|
210
|
+
name = "claude-code"
|
|
211
|
+
|
|
212
|
+
def progress(self, project: Project, since: float) -> dict:
|
|
213
|
+
info = super().progress(project, since)
|
|
214
|
+
project_dir = find_project_dir(project.path)
|
|
215
|
+
session = latest_session(project_dir)
|
|
216
|
+
if not session:
|
|
217
|
+
return info
|
|
218
|
+
tools, texts, first, last = 0, [], None, None
|
|
219
|
+
task, last_action = None, None
|
|
220
|
+
with open(project_dir / f"{session}.jsonl", encoding="utf-8", errors="replace") as fh:
|
|
221
|
+
for line in fh:
|
|
222
|
+
try:
|
|
223
|
+
o = json.loads(line)
|
|
224
|
+
except ValueError:
|
|
225
|
+
continue
|
|
226
|
+
content = (o.get("message") or {}).get("content")
|
|
227
|
+
if o.get("type") == "user" and isinstance(content, str) and _is_request(content):
|
|
228
|
+
task = content.strip() # the last thing the person asked, whenever it was
|
|
229
|
+
ts = _epoch(o.get("timestamp"))
|
|
230
|
+
if ts is None or ts < since or not isinstance(content, list):
|
|
231
|
+
continue
|
|
232
|
+
for block in content:
|
|
233
|
+
if block.get("type") == "tool_use":
|
|
234
|
+
tools += 1
|
|
235
|
+
last_action = _describe_tool(block)
|
|
236
|
+
elif block.get("type") == "text" and o.get("type") == "assistant" and block.get("text", "").strip():
|
|
237
|
+
texts.append(block["text"].strip())
|
|
238
|
+
else:
|
|
239
|
+
continue
|
|
240
|
+
first = first or ts
|
|
241
|
+
last = ts
|
|
242
|
+
info.update(
|
|
243
|
+
actions=tools, tool_calls=tools, messages=len(texts), task=task, last_action=last_action,
|
|
244
|
+
first_activity=first, last_message=(texts[-1] if texts else None), recent_messages=texts[-3:],
|
|
245
|
+
)
|
|
246
|
+
if last and (info["last_activity"] is None or last > info["last_activity"]):
|
|
247
|
+
info["last_activity"] = last
|
|
248
|
+
return info
|
|
249
|
+
|
|
250
|
+
def is_busy(self, project: Project) -> bool:
|
|
251
|
+
screen = self.screen(project).lower()
|
|
252
|
+
return any(marker in screen for marker in BUSY_MARKERS)
|
|
253
|
+
|
|
254
|
+
def snapshot(self, project: Project) -> dict:
|
|
255
|
+
project_dir = find_project_dir(project.path)
|
|
256
|
+
return {
|
|
257
|
+
"path": project.path,
|
|
258
|
+
"trusted": is_trusted(project.path),
|
|
259
|
+
"session_id": latest_session(project_dir),
|
|
260
|
+
"claude_dir": str(project_dir) if project_dir else None,
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
def payload(self, project: Project, meta: dict) -> List[Tuple[str, Path]]:
|
|
264
|
+
claude_dir = meta.get("claude_dir")
|
|
265
|
+
if not claude_dir:
|
|
266
|
+
return []
|
|
267
|
+
return [("claude", Path(claude_dir))]
|
|
268
|
+
|
|
269
|
+
def accept_payload(self, project: Project, inbox: Path, meta: dict) -> None:
|
|
270
|
+
source = inbox / "claude"
|
|
271
|
+
if not source.is_dir():
|
|
272
|
+
return
|
|
273
|
+
dest = claude_home() / "projects" / encode_project_path(project.path)
|
|
274
|
+
if self.runner.dry_run:
|
|
275
|
+
self.runner.log(f"[dry-run] would copy {source} to {dest}")
|
|
276
|
+
return
|
|
277
|
+
shutil.copytree(source, dest, dirs_exist_ok=True)
|
|
278
|
+
if meta.get("trusted") and mark_trusted(project.path):
|
|
279
|
+
self.runner.log(f"{project.name}: folder trusted on the sending machine, trusted here too")
|
|
280
|
+
old_root = meta.get("path") or project.path
|
|
281
|
+
changed = sum(rewrite_session_file(f, old_root, project.path) for f in dest.rglob("*.jsonl"))
|
|
282
|
+
if changed:
|
|
283
|
+
self.runner.log(f"{project.name}: session paths moved from {old_root} to {project.path}")
|
|
284
|
+
|
|
285
|
+
def command(self, project: Project, meta: dict, resume: bool) -> List[str]:
|
|
286
|
+
argv = [self.config.claude_bin, *self.config.claude_args]
|
|
287
|
+
if self.config.remote_control:
|
|
288
|
+
# Visible in the Claude app as "<project> · <machine>": follow it, answer it from anywhere.
|
|
289
|
+
argv += ["--remote-control", f"{project.name} · {self.config.machine}"]
|
|
290
|
+
if not resume:
|
|
291
|
+
return argv
|
|
292
|
+
session_id = meta.get("session_id")
|
|
293
|
+
if not meta.get("was_busy", True):
|
|
294
|
+
# It was idle at its prompt: reopen the conversation and wait, without spending a turn.
|
|
295
|
+
return argv + (["--resume", session_id] if session_id else ["--continue"])
|
|
296
|
+
prompt = self.config.resume_prompt
|
|
297
|
+
old_path = meta.get("path")
|
|
298
|
+
if meta.get("failover"):
|
|
299
|
+
prompt = (
|
|
300
|
+
"NodeHop fallback: the machine you were working on stopped responding, so you were restarted "
|
|
301
|
+
f"on another machine from a copy taken at {meta.get('copy_time', 'its last sync')}. Anything done "
|
|
302
|
+
"after that copy is missing. Check the actual state of the project (git status, the files you "
|
|
303
|
+
"were editing) before continuing the task where it really stands."
|
|
304
|
+
)
|
|
305
|
+
if old_path and old_path != project.path:
|
|
306
|
+
prompt += f" Note: the project folder is now {project.path} on this machine (it was {old_path})."
|
|
307
|
+
if session_id:
|
|
308
|
+
return argv + ["--resume", session_id, prompt]
|
|
309
|
+
return argv + ["--continue", prompt]
|