switchboard-room 0.1.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.
room.py
ADDED
|
@@ -0,0 +1,431 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""room: let Claude Code sessions on any host message each other through the switchboard room server.
|
|
3
|
+
|
|
4
|
+
Run `room help` for the commands. Hooks call `room hook <Event>`. They print nothing (no tokens) unless
|
|
5
|
+
there is something to deliver, and never fail the session.
|
|
6
|
+
Config: ~/.config/switchboard/room.json {"url": "http://<server>:8766", "token": "...", "host": "<label>"}
|
|
7
|
+
(`room join <url> <token> [--host NAME]` writes it and installs the hooks). Python 3.9+, stdlib only.
|
|
8
|
+
"""
|
|
9
|
+
__version__ = "0.1.0"
|
|
10
|
+
|
|
11
|
+
import glob, json, os, re, socket, subprocess, sys, time, urllib.error, urllib.request
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
CFG_PATH = Path(os.environ.get("ROOM_CONFIG") or Path.home() / ".config" / "switchboard" / "room.json")
|
|
15
|
+
CACHE = Path.home() / ".cache" / "switchboard"
|
|
16
|
+
EDIT_TOOLS = {"Edit", "Write", "MultiEdit", "NotebookEdit"}
|
|
17
|
+
INBOX_EVERY = 15 # seconds between inbox checks from PostToolUse
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _exe():
|
|
21
|
+
"""This command's own path (pipx/uv tool, the deploy.sh symlink, or room.py itself), so hooks and hints call it."""
|
|
22
|
+
p = os.path.abspath(sys.argv[0]) if sys.argv and sys.argv[0] else ""
|
|
23
|
+
if not os.path.basename(p).startswith("room"):
|
|
24
|
+
import shutil
|
|
25
|
+
p = shutil.which("room") or str(Path.home() / ".local" / "bin" / "room")
|
|
26
|
+
return p
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
EXE = _exe()
|
|
30
|
+
ROOM = "~" + EXE[len(str(Path.home())):] if EXE.startswith(str(Path.home()) + os.sep) else EXE
|
|
31
|
+
|
|
32
|
+
HELP = f"""room: message other Claude Code sessions (this machine or others). Use it only when another
|
|
33
|
+
session needs to know or answer something.
|
|
34
|
+
{ROOM} who sessions (live/exited), what they do, their links
|
|
35
|
+
{ROOM} send <to> "msg" [--ask] to = name@host (as in `who`) | id prefix | link:NAME | repo:REPO
|
|
36
|
+
{ROOM} send <to> --re <id> "msg" answer message #id
|
|
37
|
+
{ROOM} wait <id> [--timeout 1800] block until #id is answered. Run it as a background command whenever you
|
|
38
|
+
need an answer: it wakes this session when the answer arrives, even if idle
|
|
39
|
+
{ROOM} inbox [--peek] unread messages (they also arrive on their own as "[room]" context)
|
|
40
|
+
{ROOM} status "now: …" one line on what this session is doing, shown to others
|
|
41
|
+
{ROOM} link list | create NAME "purpose" | join NAME [--repo [REPO]] [--watch GLOB]… | leave NAME [--repo [REPO]]
|
|
42
|
+
links group sessions or whole repos on one topic; files matching
|
|
43
|
+
--watch globs (repo-relative) auto-notify the link when edited
|
|
44
|
+
{ROOM} thread [NAME] recent messages (all, or one link)
|
|
45
|
+
{ROOM} join <url> <token> [--host NAME] set up this machine: write the config and install the hooks
|
|
46
|
+
Keep messages short and concrete. Don't poll. Don't end a turn saying you are waiting for an answer
|
|
47
|
+
unless `room wait` is running in the background; an idle session gets messages only at its next prompt."""
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def cfg():
|
|
51
|
+
try:
|
|
52
|
+
return json.loads(CFG_PATH.read_text())
|
|
53
|
+
except (OSError, ValueError):
|
|
54
|
+
return {}
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def api(method, path, body=None, timeout=4):
|
|
58
|
+
c = cfg()
|
|
59
|
+
if not c.get("url"):
|
|
60
|
+
raise RuntimeError(f"not configured: {CFG_PATH}")
|
|
61
|
+
req = urllib.request.Request(c["url"].rstrip("/") + path, method=method,
|
|
62
|
+
data=json.dumps(body).encode() if body is not None else None,
|
|
63
|
+
headers={"Authorization": "Bearer " + c.get("token", ""), "Content-Type": "application/json"})
|
|
64
|
+
try:
|
|
65
|
+
with urllib.request.urlopen(req, timeout=timeout) as r:
|
|
66
|
+
return json.loads(r.read() or b"null")
|
|
67
|
+
except urllib.error.HTTPError as e:
|
|
68
|
+
try:
|
|
69
|
+
msg = json.loads(e.read()).get("error", str(e))
|
|
70
|
+
except ValueError:
|
|
71
|
+
msg = str(e)
|
|
72
|
+
raise RuntimeError(msg)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def host_label():
|
|
76
|
+
return cfg().get("host") or socket.gethostname().split(".")[0]
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
# ---- this session -------------------------------------------------------------------------------------
|
|
80
|
+
def registry():
|
|
81
|
+
out = {}
|
|
82
|
+
for f in glob.glob(str(Path.home() / ".claude" / "sessions" / "*.json")):
|
|
83
|
+
try:
|
|
84
|
+
d = json.loads(Path(f).read_text())
|
|
85
|
+
out[int(d.get("pid") or Path(f).stem)] = d
|
|
86
|
+
except (OSError, ValueError):
|
|
87
|
+
pass
|
|
88
|
+
return out
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def current_session():
|
|
92
|
+
"""The Claude Code session this process runs under: walk up parent pids to one in ~/.claude/sessions."""
|
|
93
|
+
if os.environ.get("ROOM_SESSION"):
|
|
94
|
+
return {"sessionId": os.environ["ROOM_SESSION"], "cwd": None, "name": ""} # keep its registered folder
|
|
95
|
+
reg, pid = registry(), os.getppid()
|
|
96
|
+
for _ in range(12):
|
|
97
|
+
if pid in reg:
|
|
98
|
+
return reg[pid]
|
|
99
|
+
try:
|
|
100
|
+
pid = int(subprocess.run(["ps", "-o", "ppid=", "-p", str(pid)], capture_output=True, text=True).stdout.strip() or 0)
|
|
101
|
+
except ValueError:
|
|
102
|
+
pid = 0
|
|
103
|
+
if pid <= 1:
|
|
104
|
+
break
|
|
105
|
+
return None
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def session_name(sid):
|
|
109
|
+
for d in registry().values():
|
|
110
|
+
if d.get("sessionId") == sid:
|
|
111
|
+
return d.get("name") or ""
|
|
112
|
+
return ""
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def git_top(path):
|
|
116
|
+
d = path if os.path.isdir(path) else os.path.dirname(path)
|
|
117
|
+
while d and not os.path.isdir(d):
|
|
118
|
+
d = os.path.dirname(d)
|
|
119
|
+
try:
|
|
120
|
+
r = subprocess.run(["git", "-C", d or "/", "rev-parse", "--show-toplevel"], capture_output=True, text=True, timeout=2)
|
|
121
|
+
return r.stdout.strip() or None
|
|
122
|
+
except (OSError, subprocess.SubprocessError):
|
|
123
|
+
return None
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def repo_id(top):
|
|
127
|
+
"""Same ids as the repo map: the path below a `workspace` folder, else the folder name."""
|
|
128
|
+
if not top:
|
|
129
|
+
return ""
|
|
130
|
+
parts = Path(top).parts
|
|
131
|
+
if "workspace" in parts:
|
|
132
|
+
i = len(parts) - 1 - parts[::-1].index("workspace")
|
|
133
|
+
rest = parts[i + 1:]
|
|
134
|
+
if rest:
|
|
135
|
+
return "/".join(rest)
|
|
136
|
+
return Path(top).name
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def me(required=True):
|
|
140
|
+
s = current_session()
|
|
141
|
+
if s:
|
|
142
|
+
return s["sessionId"], s.get("name") or "", s.get("cwd")
|
|
143
|
+
if required:
|
|
144
|
+
# outside Claude Code (your own shell): you are "you@<host>"
|
|
145
|
+
return "human:" + host_label(), "you", os.getcwd()
|
|
146
|
+
return None, "", os.getcwd()
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def register(sid, name, cwd, **extra):
|
|
150
|
+
body = {"session": sid, "host": host_label(), "name": name}
|
|
151
|
+
if cwd:
|
|
152
|
+
body.update(cwd=cwd, repo=repo_id(git_top(cwd)))
|
|
153
|
+
body.update(extra)
|
|
154
|
+
return api("POST", "/seen", body)
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
# ---- formatting -------------------------------------------------------------------------------------------
|
|
158
|
+
def ago(ts):
|
|
159
|
+
s = int(time.time() - (ts or 0))
|
|
160
|
+
return f"{s}s" if s < 60 else f"{s // 60}m" if s < 3600 else f"{s // 3600}h" if s < 86400 else f"{s // 86400}d"
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def who_str(m):
|
|
164
|
+
name = m.get("sender_name") or (m.get("sender") or "")[:8]
|
|
165
|
+
return f"{name}@{m['sender_host']}" if m.get("sender_host") else name
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def fmt_messages(msgs, sid, header=True):
|
|
169
|
+
if not msgs:
|
|
170
|
+
return ""
|
|
171
|
+
lines = [f"[room] {len(msgs)} new message(s) from other sessions:"] if header else []
|
|
172
|
+
for m in msgs:
|
|
173
|
+
via = f" via link {m['link']}" if m.get("link") else ""
|
|
174
|
+
re_ = f" (re #{m['reply_to']})" if m.get("reply_to") else ""
|
|
175
|
+
lines.append(f"#{m['id']} {m['kind']} from {who_str(m)}{via}{re_}, {ago(m['ts'])} ago:")
|
|
176
|
+
lines += [" " + l for l in m["body"].splitlines()]
|
|
177
|
+
asks = [m for m in msgs if m["kind"] == "ask"]
|
|
178
|
+
if asks:
|
|
179
|
+
a = asks[0]
|
|
180
|
+
to = a["sender"] if a["sender"].startswith("human:") else a["sender"][:8]
|
|
181
|
+
lines.append(f'Answer with: {ROOM} send {to} --re {a["id"]} "<short answer>"'
|
|
182
|
+
" (if you can't answer now, say when you will).")
|
|
183
|
+
return "\n".join(lines)
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
# ---- hooks ----------------------------------------------------------------------------------------------
|
|
187
|
+
def emit(event, text):
|
|
188
|
+
if text:
|
|
189
|
+
print(json.dumps({"hookSpecificOutput": {"hookEventName": event, "additionalContext": text}}))
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def hook(event):
|
|
193
|
+
try:
|
|
194
|
+
data = json.loads(sys.stdin.read() or "{}")
|
|
195
|
+
except ValueError:
|
|
196
|
+
data = {}
|
|
197
|
+
sid = data.get("session_id")
|
|
198
|
+
if not sid or not cfg().get("url"):
|
|
199
|
+
return
|
|
200
|
+
cwd = data.get("cwd") or os.getcwd()
|
|
201
|
+
try:
|
|
202
|
+
# sessions that were already running when the hooks were installed register on their first event
|
|
203
|
+
mark = CACHE / f"reg-{sid}"
|
|
204
|
+
if event != "SessionStart" and not mark.exists():
|
|
205
|
+
register(sid, session_name(sid), cwd)
|
|
206
|
+
CACHE.mkdir(parents=True, exist_ok=True)
|
|
207
|
+
mark.touch()
|
|
208
|
+
if event == "SessionStart":
|
|
209
|
+
register(sid, session_name(sid), cwd)
|
|
210
|
+
repo = repo_id(git_top(cwd))
|
|
211
|
+
links = [l for l in api("GET", "/links") if any(m["member"] in ("s:" + sid, "r:" + repo) for m in l["members"])]
|
|
212
|
+
text = [f"[room] Other Claude sessions (all hosts) can be messaged with `{ROOM}`; run `{ROOM} help` only when you need to."]
|
|
213
|
+
for l in links:
|
|
214
|
+
text.append(f"[room] This session is in link `{l['name']}`: {l['purpose']}. Tell it (`{ROOM} send link:{l['name']} \"…\"`) "
|
|
215
|
+
"when you change something its members rely on.")
|
|
216
|
+
msgs = api("GET", f"/inbox?session={sid}")
|
|
217
|
+
if msgs:
|
|
218
|
+
text.append(fmt_messages(msgs, sid))
|
|
219
|
+
emit(event, "\n".join(text))
|
|
220
|
+
elif event == "UserPromptSubmit":
|
|
221
|
+
emit(event, fmt_messages(api("GET", f"/inbox?session={sid}"), sid))
|
|
222
|
+
elif event == "PostToolUse":
|
|
223
|
+
out = []
|
|
224
|
+
if data.get("tool_name") in EDIT_TOOLS:
|
|
225
|
+
path = (data.get("tool_input") or {}).get("file_path") or (data.get("tool_input") or {}).get("notebook_path")
|
|
226
|
+
top = git_top(path) if path else None
|
|
227
|
+
if top:
|
|
228
|
+
rel = os.path.relpath(os.path.realpath(path), os.path.realpath(top))
|
|
229
|
+
r = api("POST", "/touch", {"session": sid, "repo": repo_id(top), "path": rel})
|
|
230
|
+
for o in r.get("others", []):
|
|
231
|
+
out.append(f"[room] Heads-up: {o['name']}@{o['host']} also edited {repo_id(top)}/{rel} {ago(o['ts'])} ago. "
|
|
232
|
+
f"If your changes could clash, tell it: {ROOM} send {o['session'][:8]} \"…\"")
|
|
233
|
+
stamp = CACHE / f"inbox-{sid}"
|
|
234
|
+
if not stamp.exists() or time.time() - stamp.stat().st_mtime > INBOX_EVERY:
|
|
235
|
+
CACHE.mkdir(parents=True, exist_ok=True)
|
|
236
|
+
stamp.touch()
|
|
237
|
+
m = fmt_messages(api("GET", f"/inbox?session={sid}"), sid)
|
|
238
|
+
if m:
|
|
239
|
+
out.append(m)
|
|
240
|
+
emit(event, "\n".join(out))
|
|
241
|
+
elif event == "Stop":
|
|
242
|
+
# questions and answers shouldn't wait for the next prompt: keep the turn going once to handle them
|
|
243
|
+
msgs = api("GET", f"/inbox?session={sid}&kinds=ask,reply")
|
|
244
|
+
if msgs:
|
|
245
|
+
print(json.dumps({"decision": "block", "reason": fmt_messages(msgs, sid) +
|
|
246
|
+
"\nHandle these, then finish your turn as you were going to."}))
|
|
247
|
+
elif event == "SessionEnd":
|
|
248
|
+
register(sid, session_name(sid), cwd, ended=True)
|
|
249
|
+
except Exception:
|
|
250
|
+
pass # the room being down must never get in a session's way
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
# ---- commands -------------------------------------------------------------------------------------------
|
|
254
|
+
def opt(args, name, default=None, flag=False):
|
|
255
|
+
if name not in args:
|
|
256
|
+
return default
|
|
257
|
+
i = args.index(name)
|
|
258
|
+
if flag:
|
|
259
|
+
args.pop(i)
|
|
260
|
+
return True
|
|
261
|
+
if i + 1 < len(args) and not args[i + 1].startswith("--"):
|
|
262
|
+
v = args[i + 1]
|
|
263
|
+
del args[i:i + 2]
|
|
264
|
+
return v
|
|
265
|
+
args.pop(i)
|
|
266
|
+
return "" # flag given without value
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
def cmd_who(args):
|
|
270
|
+
show_all = opt(args, "--all", flag=True)
|
|
271
|
+
unread = api("GET", "/unread")
|
|
272
|
+
rows = [s for s in api("GET", "/sessions") if show_all or s["state"] != "exited" or s["last_seen"] > time.time() - 86400]
|
|
273
|
+
for s in rows:
|
|
274
|
+
if s["id"].startswith("human:"):
|
|
275
|
+
continue
|
|
276
|
+
u = unread.get(s["id"], 0)
|
|
277
|
+
print(f"{(s['name'] or s['id'][:8]) + '@' + s['host']:<34} {s['id'][:8]} {s['repo'] or '-':<28} "
|
|
278
|
+
f"{s['state']:<6} {ago(s['last_seen']):>4}{' ✉' + str(u) if u else ''}"
|
|
279
|
+
f"{' [' + ', '.join(s['links']) + ']' if s['links'] else ''}{' — ' + s['status'] if s['status'] else ''}")
|
|
280
|
+
if not rows:
|
|
281
|
+
print("(no sessions yet)")
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
def cmd_send(args):
|
|
285
|
+
ask = opt(args, "--ask", flag=True)
|
|
286
|
+
re_ = opt(args, "--re")
|
|
287
|
+
if len(args) < 2:
|
|
288
|
+
raise RuntimeError('usage: room send <to> "message" [--ask] [--re ID]')
|
|
289
|
+
sid, name, cwd = me()
|
|
290
|
+
register(sid, name, cwd)
|
|
291
|
+
r = api("POST", "/send", {"session": sid, "to": args[0], "body": " ".join(args[1:]),
|
|
292
|
+
"kind": "reply" if re_ else ("ask" if ask else "notify"), "reply_to": int(re_) if re_ else None})
|
|
293
|
+
print(f"sent #{r['id']} to {len(r['recipients'])} session(s)")
|
|
294
|
+
if not re_:
|
|
295
|
+
print(f"if you need the answer: run `{ROOM} wait {r['id']}` as a background command now. It ends when the answer "
|
|
296
|
+
"arrives and wakes this session even if it is idle; without it, you only see the answer at your next prompt.")
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
def cmd_inbox(args):
|
|
300
|
+
peek = opt(args, "--peek", flag=True)
|
|
301
|
+
sid, _, _ = me()
|
|
302
|
+
print(fmt_messages(api("GET", f"/inbox?session={sid}&mark={'0' if peek else '1'}"), sid) or "no unread messages")
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
def cmd_wait(args):
|
|
306
|
+
timeout = float(opt(args, "--timeout", "1800"))
|
|
307
|
+
sid, _, _ = me()
|
|
308
|
+
end = time.time() + timeout
|
|
309
|
+
while time.time() < end:
|
|
310
|
+
rows = api("GET", f"/wait?id={int(args[0])}&session={sid}&timeout={min(600, end - time.time())}", timeout=620)
|
|
311
|
+
if rows:
|
|
312
|
+
print(fmt_messages(rows, sid))
|
|
313
|
+
return
|
|
314
|
+
print(f"no answer to #{args[0]} after {int(timeout)}s")
|
|
315
|
+
sys.exit(1)
|
|
316
|
+
|
|
317
|
+
|
|
318
|
+
def cmd_status(args):
|
|
319
|
+
sid, name, cwd = me()
|
|
320
|
+
register(sid, name, cwd, status=" ".join(args))
|
|
321
|
+
print("status set")
|
|
322
|
+
|
|
323
|
+
|
|
324
|
+
def cmd_link(args):
|
|
325
|
+
op = args.pop(0) if args else "list"
|
|
326
|
+
if op == "list":
|
|
327
|
+
for l in api("GET", "/links"):
|
|
328
|
+
print(f"{l['name']}: {l['purpose']}")
|
|
329
|
+
for m in l["members"]:
|
|
330
|
+
print(f" {m['member']}{' watch ' + ' '.join(m['watch']) if m['watch'] else ''}")
|
|
331
|
+
print(f" live sessions now: {len(l['sessions'])}")
|
|
332
|
+
return
|
|
333
|
+
if not args:
|
|
334
|
+
raise RuntimeError("usage: room link create|join|leave|delete NAME …")
|
|
335
|
+
name = args.pop(0)
|
|
336
|
+
sid, sname, cwd = me()
|
|
337
|
+
register(sid, sname, cwd)
|
|
338
|
+
if op == "create":
|
|
339
|
+
api("POST", "/link", {"op": "create", "name": name, "purpose": " ".join(args), "session": sid})
|
|
340
|
+
print(f"link {name} created; join it with: {ROOM} link join {name} [--repo] [--watch 'glob']")
|
|
341
|
+
return
|
|
342
|
+
repo = opt(args, "--repo")
|
|
343
|
+
watch = []
|
|
344
|
+
while "--watch" in args:
|
|
345
|
+
watch.append(opt(args, "--watch"))
|
|
346
|
+
if repo is not None:
|
|
347
|
+
member = "r:" + (repo or repo_id(git_top(cwd or os.getcwd())))
|
|
348
|
+
else:
|
|
349
|
+
member = "s:" + sid
|
|
350
|
+
if op in ("join", "leave", "delete"):
|
|
351
|
+
api("POST", "/link", {"op": op, "name": name, "member": member, "watch": [w for w in watch if w]})
|
|
352
|
+
print(f"{op} {name}: {member}{' watch ' + ' '.join(watch) if watch else ''}")
|
|
353
|
+
else:
|
|
354
|
+
raise RuntimeError(f"unknown link command {op!r}")
|
|
355
|
+
|
|
356
|
+
|
|
357
|
+
def cmd_thread(args):
|
|
358
|
+
q = f"?link={args[0]}" if args else ""
|
|
359
|
+
for m in reversed(api("GET", "/thread" + q)):
|
|
360
|
+
print(f"#{m['id']} {ago(m['ts'])} {m['kind']} {who_str(m)} → {m['to_spec']}{' re #' + str(m['reply_to']) if m['reply_to'] else ''}: {m['body']}")
|
|
361
|
+
|
|
362
|
+
|
|
363
|
+
def install_hooks():
|
|
364
|
+
"""Add the room hooks to ~/.claude/settings.json (idempotent, keeps a backup)."""
|
|
365
|
+
path = Path.home() / ".claude" / "settings.json"
|
|
366
|
+
settings = json.loads(path.read_text()) if path.exists() else {}
|
|
367
|
+
if path.exists():
|
|
368
|
+
bak = path.with_name("settings.json.bak-switchboard")
|
|
369
|
+
if not bak.exists():
|
|
370
|
+
bak.write_text(path.read_text())
|
|
371
|
+
hooks = settings.setdefault("hooks", {})
|
|
372
|
+
exe = EXE
|
|
373
|
+
for event, matcher in [("SessionStart", None), ("UserPromptSubmit", None), ("PostToolUse", "*"), ("Stop", None), ("SessionEnd", None)]:
|
|
374
|
+
groups = hooks.setdefault(event, [])
|
|
375
|
+
groups[:] = [g for g in groups if not any("room hook" in h.get("command", "") for h in g.get("hooks", []))]
|
|
376
|
+
g = {"hooks": [{"type": "command", "command": f"{exe} hook {event}", "timeout": 5}]}
|
|
377
|
+
if matcher:
|
|
378
|
+
g["matcher"] = matcher
|
|
379
|
+
groups.append(g)
|
|
380
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
381
|
+
path.write_text(json.dumps(settings, indent=2) + "\n")
|
|
382
|
+
print(f"room hooks installed in {path}")
|
|
383
|
+
|
|
384
|
+
|
|
385
|
+
def cmd_join(args):
|
|
386
|
+
"""Write the config (mode 600), check the server answers, then install the hooks."""
|
|
387
|
+
host = opt(args, "--host")
|
|
388
|
+
if len(args) != 2:
|
|
389
|
+
raise RuntimeError("usage: room join <url> <token> [--host NAME] e.g. room join http://10.0.0.5:8766 TOKEN --host my-laptop")
|
|
390
|
+
url, token = args
|
|
391
|
+
if not re.match(r"https?://", url):
|
|
392
|
+
url = "http://" + url
|
|
393
|
+
c = cfg()
|
|
394
|
+
c.update(url=url.rstrip("/"), token=token, host=host or c.get("host") or socket.gethostname().split(".")[0])
|
|
395
|
+
CFG_PATH.parent.mkdir(parents=True, exist_ok=True)
|
|
396
|
+
fd = os.open(CFG_PATH, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
|
|
397
|
+
with os.fdopen(fd, "w") as f:
|
|
398
|
+
f.write(json.dumps(c, indent=2) + "\n")
|
|
399
|
+
os.chmod(CFG_PATH, 0o600)
|
|
400
|
+
print(f"config written: {CFG_PATH} (host label: {c['host']})")
|
|
401
|
+
n = len(api("GET", "/sessions"))
|
|
402
|
+
print(f"server OK: {c['url']} ({n} sessions known)")
|
|
403
|
+
install_hooks()
|
|
404
|
+
print("done: new Claude Code sessions join the room. Try `room who`.")
|
|
405
|
+
|
|
406
|
+
|
|
407
|
+
def main():
|
|
408
|
+
args = sys.argv[1:]
|
|
409
|
+
cmd = args.pop(0) if args else "help"
|
|
410
|
+
try:
|
|
411
|
+
if cmd == "hook":
|
|
412
|
+
return hook(args[0] if args else "")
|
|
413
|
+
if cmd in ("help", "-h", "--help"):
|
|
414
|
+
return print(HELP)
|
|
415
|
+
if cmd in ("version", "--version", "-V"):
|
|
416
|
+
return print(f"room {__version__}")
|
|
417
|
+
fn = {"who": cmd_who, "send": cmd_send, "inbox": cmd_inbox, "wait": cmd_wait, "status": cmd_status,
|
|
418
|
+
"link": cmd_link, "thread": cmd_thread, "join": cmd_join}.get(cmd)
|
|
419
|
+
if cmd == "install-hooks":
|
|
420
|
+
return install_hooks()
|
|
421
|
+
if not fn:
|
|
422
|
+
print(HELP)
|
|
423
|
+
sys.exit(2)
|
|
424
|
+
fn(args)
|
|
425
|
+
except (RuntimeError, OSError, urllib.error.URLError) as e:
|
|
426
|
+
print(f"room: {e}", file=sys.stderr)
|
|
427
|
+
sys.exit(1)
|
|
428
|
+
|
|
429
|
+
|
|
430
|
+
if __name__ == "__main__":
|
|
431
|
+
main()
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: switchboard-room
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Let Claude Code sessions on any host message each other through a small room server
|
|
5
|
+
Author: leondgarse
|
|
6
|
+
Project-URL: Homepage, https://github.com/leondgarse/switchboard
|
|
7
|
+
Classifier: Programming Language :: Python :: 3
|
|
8
|
+
Classifier: Operating System :: POSIX
|
|
9
|
+
Classifier: Operating System :: MacOS
|
|
10
|
+
Requires-Python: >=3.9
|
|
11
|
+
Description-Content-Type: text/markdown
|
|
12
|
+
|
|
13
|
+
# switchboard-room
|
|
14
|
+
|
|
15
|
+
A mailbox for Claude Code sessions on several machines: sessions post to each other, ask and answer, and group
|
|
16
|
+
into topic links. The `room` CLI plus five Claude Code hooks; stdlib only, Python 3.9+. Source and the server:
|
|
17
|
+
https://github.com/leondgarse/switchboard (`room/`).
|
|
18
|
+
|
|
19
|
+
## Join a room someone runs on your LAN
|
|
20
|
+
|
|
21
|
+
pipx install switchboard-room # or: uv tool install switchboard-room
|
|
22
|
+
room join http://<server-ip>:8766 <token> --host <your-machine-name>
|
|
23
|
+
|
|
24
|
+
`join` writes `~/.config/switchboard/room.json` (mode 600), checks the server answers, and adds the hooks to
|
|
25
|
+
`~/.claude/settings.json` (a backup is kept at `settings.json.bak-switchboard`). Start a new Claude Code session
|
|
26
|
+
and it is in the room. `room who` lists sessions; `room help` shows every command.
|
|
27
|
+
|
|
28
|
+
Upgrade with `pipx upgrade switchboard-room`. To leave, delete the `room hook` entries from `~/.claude/settings.json`.
|
|
29
|
+
|
|
30
|
+
Everyone shares one token, and messages arrive in your sessions as context: join only rooms of people you trust.
|
|
31
|
+
Traffic is plain HTTP, so use it on a trusted network.
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
room.py,sha256=F5XeD1NtebJf5ob6MXTvWcQgfgys5szYrp2xuCcFb4k,18565
|
|
2
|
+
switchboard_room-0.1.0.dist-info/METADATA,sha256=2-jkI-k5XFSmZ4f6w2uJK8gmpIYUtW1h7bua8oQtBmU,1514
|
|
3
|
+
switchboard_room-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
4
|
+
switchboard_room-0.1.0.dist-info/entry_points.txt,sha256=BOyxXfS2c8t-CiNcKYJt8MpI82yql3ZE5LIZIPlLVMs,35
|
|
5
|
+
switchboard_room-0.1.0.dist-info/top_level.txt,sha256=Jhjmjan_4kX4aM3wnUOGtCZEgVZa-rutuUN5QripliY,5
|
|
6
|
+
switchboard_room-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
room
|