-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
1510 lines (1334 loc) · 61.1 KB
/
server.py
File metadata and controls
1510 lines (1334 loc) · 61.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Claude Code WebUI Server — Transcript-driven, Tmux-only architecture.
Maintains a session registry, parses transcript JSONL files incrementally,
and serves a multi-session dashboard UI.
Usage: python3 server.py
Then open http://localhost:19836
"""
import argparse
import json
import glob
import os
import re
import signal
import subprocess
import sys
import time
import threading
import urllib.request
from http.server import HTTPServer, BaseHTTPRequestHandler
from socketserver import ThreadingMixIn
from urllib.parse import parse_qs, urlparse
import uuid
import cgi
from frontend import HTML_PAGE
from platform_utils import IS_WINDOWS, get_queue_dir, get_image_dir, is_process_alive, is_terminal_alive, find_claude_pid, get_process_children, get_process_name, encode_project_path, send_prompt, send_interrupt
import permission_rules
try:
from channel_feishu import start_feishu_channel
_has_feishu = True
except ImportError:
_has_feishu = False
QUEUE_DIR = get_queue_dir()
IMAGE_DIR = get_image_dir()
PORT = 19836
server_name = "local"
# ── Federation ──
remote_servers = [] # [{"name": str, "url": str}]
session_machine_map = {} # {session_id: remote_url or None(local)}
# ── Session registry ──
sessions = {}
# sessions[session_id] = {
# "transcript_path": str,
# "terminal_id": str, # stable terminal anchor: tmux pane ID (Linux) or shell PID (Windows)
# "tmux_socket": str, # Linux only: tmux socket path for send-keys
# "cwd": str,
# "registered_at": float,
# "transcript_offset": int,
# "transcript_entries": list, # parsed entries (kept for rendering)
# "derived_state": str, # idle|busy|permission_prompt|elicitation|plan_review
# "last_activity": float,
# "last_summary": str, # brief summary of last assistant message
# "slug": str, # session slug from transcript (auto-generated name)
# "custom_title": str, # user-set name via /rename in Claude Code (from transcript custom-title entry)
# }
sessions_lock = threading.Lock()
# Per-session locks for update_session_state: prevents concurrent transcript reads
# for the same session from duplicating entries or racing on the offset.
_session_update_locks = {}
_session_update_locks_lock = threading.Lock()
def _get_session_update_lock(sid):
with _session_update_locks_lock:
if sid not in _session_update_locks:
_session_update_locks[sid] = threading.Lock()
return _session_update_locks[sid]
# Session-level auto-allow rules: { session_id: {"rules": [...], "smart_rules": {...}} }
# These are volatile (in-memory only, cleared on session end/clear/server restart).
# The hook queries these via GET /api/check-auto-allow.
# For persistent rules, see the 4-level rule system in permission_rules.py.
session_auto_allow = {}
def proxy_to_remote(remote_url, path, method="GET", body=None, headers=None):
"""Forward a request to a remote WebUI server."""
url = remote_url.rstrip("/") + path
req = urllib.request.Request(url, data=body, method=method)
req.add_header("Content-Type", "application/json")
if headers:
for k, v in headers.items():
req.add_header(k, v)
resp = urllib.request.urlopen(req, timeout=5)
return resp.status, resp.read(), resp.headers.get("Content-Type", "application/json")
def fetch_remote_sessions():
"""Fetch sessions from all remote servers. Returns list of (remote_config, sessions_or_None)."""
results = []
for remote in remote_servers:
try:
url = remote["url"].rstrip("/") + "/api/sessions"
req = urllib.request.Request(url)
resp = urllib.request.urlopen(req, timeout=3)
data = json.loads(resp.read())
results.append((remote, data.get("sessions", [])))
except Exception as e:
print(f"[!] Federation: {remote['name']} unreachable: {e}")
results.append((remote, None))
return results
def _get_remote_url_for_session(session_id):
"""Return remote URL if session is remote, None if local."""
return session_machine_map.get(session_id)
def _get_original_session_id(session_id):
"""Strip the machine prefix to get the original remote session ID."""
if ":" in session_id:
return session_id.split(":", 1)[1]
return session_id
# ── Transcript parsing ──
def update_session_state(sid):
"""Read new transcript entries incrementally and derive session state.
Uses a per-session lock so concurrent requests for the same session
serialise cleanly: the second caller waits, then finds the offset
already advanced and returns with near-zero cost.
"""
lock = _get_session_update_lock(sid)
with lock:
_update_session_state_locked(sid)
def _update_session_state_locked(sid):
with sessions_lock:
s = sessions.get(sid)
if not s:
return
path = s["transcript_path"]
offset = s["transcript_offset"]
if not path or not os.path.isfile(path):
with sessions_lock:
s = sessions.get(sid)
if s:
s["derived_state"] = "idle"
return
try:
with open(path, "rb") as f:
# Defend against /compact and /clear race: if the file was rewritten
# shorter than our offset, reset to 0 (the hook registration will
# also reset, but this closes the race window before it arrives).
f.seek(0, 2) # seek to end
file_size = f.tell()
if offset > file_size:
offset = 0
with sessions_lock:
s = sessions.get(sid)
if s:
s["transcript_offset"] = 0
s["transcript_entries"] = []
f.seek(offset)
new_data = f.read()
except IOError:
# On Windows, mandatory file locking can cause IOError when Claude Code
# is writing. Skip this poll cycle; next poll will retry. Do NOT sleep
# here — it blocks the single-threaded HTTP server.
new_data = b""
if new_data:
text = new_data.decode("utf-8", errors="replace")
lines = text.split("\n")
new_entries = []
bytes_consumed = 0
for i, line in enumerate(lines):
# +1 for the \n delimiter, but the last element from split() has no trailing \n
nl = 1 if i < len(lines) - 1 else 0
if not line.strip():
bytes_consumed += len(line.encode("utf-8")) + nl
continue
try:
entry = json.loads(line)
new_entries.append(entry)
bytes_consumed += len(line.encode("utf-8")) + nl
except (json.JSONDecodeError, ValueError):
if i == len(lines) - 1:
# Last line may be incomplete (still being written) — stop here
break
# Mid-file bad line — skip it
bytes_consumed += len(line.encode("utf-8")) + nl
if new_entries:
with sessions_lock:
s = sessions.get(sid)
if not s:
return
s["transcript_offset"] = offset + bytes_consumed
s["transcript_entries"].extend(new_entries)
s["last_activity"] = time.time()
# Extract slug (first seen) and custom title (latest /rename)
for e in new_entries:
if e.get("slug") and not s["slug"]:
s["slug"] = e["slug"]
if e.get("type") == "custom-title" and e.get("customTitle"):
s["custom_title"] = e["customTitle"]
# Always derive state — .request.json is an external signal independent of transcript changes
with sessions_lock:
s = sessions.get(sid)
if not s:
return
s["derived_state"], s["last_summary"], s["last_user_prompt"] = _derive_state(sid, s)
def _extract_user_text(entry):
"""Extract meaningful user text from a transcript entry, stripping system/command tags.
Returns empty string for local commands (/context, /help etc.) that don't need a response.
"""
msg = entry.get("message", {})
content = msg.get("content", "")
if isinstance(content, str):
text = content
elif isinstance(content, list):
parts = []
for c in content:
if isinstance(c, dict):
if c.get("type") == "text":
parts.append(c.get("text", ""))
elif c.get("type") == "tool_result":
return "" # tool_results are not user prompts
elif isinstance(c, str):
parts.append(c)
text = " ".join(parts)
else:
return ""
# Strip known system/command XML tags
for tag in ("system-reminder", "local-command-caveat", "local-command-stdout",
"task-notification", "command-name", "command-message", "command-args"):
text = re.sub(rf"<{tag}>.*?</{tag}>", "", text, flags=re.DOTALL)
text = re.sub(r"<[^>]+>", "", text)
text = re.sub(r"\s+", " ", text).strip()
return text
def _derive_state(sid, s):
"""Derive session state from transcript entries + pending request files."""
entries = s["transcript_entries"]
summary = s.get("last_summary", "")
user_prompt = s.get("last_user_prompt", "")
# Find last meaningful entries (skip file-history-snapshot, queue-operation)
last_assistant = None
last_user = None
for entry in reversed(entries):
etype = entry.get("type", "")
if etype == "assistant" and last_assistant is None:
last_assistant = entry
elif etype == "user" and last_user is None:
last_user = entry
if last_assistant and last_user:
break
# Extract last user prompt text (skip tool_results and system-injected messages)
for entry in reversed(entries):
if entry.get("type") != "user":
continue
msg = entry.get("message", {})
content = msg.get("content", "")
text = ""
if isinstance(content, str):
text = content
elif isinstance(content, list):
parts = []
for c in content:
if isinstance(c, dict) and c.get("type") == "text":
parts.append(c.get("text", ""))
elif isinstance(c, str):
parts.append(c)
text = " ".join(parts)
if not text.strip():
continue
# Strip XML tags and their content for known system tags
clean = re.sub(r"<system-reminder>.*?</system-reminder>", "", text, flags=re.DOTALL)
clean = re.sub(r"<local-command-caveat>.*?</local-command-caveat>", "", clean, flags=re.DOTALL)
clean = re.sub(r"<local-command-stdout>.*?</local-command-stdout>", "", clean, flags=re.DOTALL)
clean = re.sub(r"<task-notification>.*?</task-notification>", "", clean, flags=re.DOTALL)
clean = re.sub(r"<command-name>.*?</command-name>", "", clean, flags=re.DOTALL)
clean = re.sub(r"<command-message>.*?</command-message>", "", clean, flags=re.DOTALL)
clean = re.sub(r"<command-args>.*?</command-args>", "", clean, flags=re.DOTALL)
# Strip any remaining XML tags
clean = re.sub(r"<[^>]+>", "", clean)
# Collapse runs of spaces/tabs (preserve newlines)
clean = re.sub(r"[^\S\n]+", " ", clean)
# Collapse 3+ newlines into 2
clean = re.sub(r"\n{3,}", "\n\n", clean)
clean = clean.strip()
if clean:
user_prompt = clean
break
# Check if the last user message is after the last assistant message.
# When true, the assistant's summary is stale (from a previous turn).
user_after_assistant = False
if last_user and last_assistant:
for i, entry in enumerate(entries):
if entry is last_user:
user_idx = i
if entry is last_assistant:
asst_idx = i
if user_idx > asst_idx:
# Check if the last user message is a local command (e.g. /context, /help)
# that doesn't require a response from Claude. These contain
# <local-command-caveat> or <command-name> tags and have no real user text
# after stripping those tags.
last_user_text = _extract_user_text(last_user)
if last_user_text:
# Ctrl-C interrupt produces "[Request interrupted by user]" — treat as idle
if last_user_text.strip().startswith('[Request interrupted by user'):
return "idle", "", ""
user_after_assistant = True
# Invariant: summary is only shown when it follows the displayed user_prompt
if user_after_assistant:
return "busy", "", user_prompt
# Extract info from last assistant message
if last_assistant:
msg = last_assistant.get("message", {})
content = msg.get("content", [])
stop_reason = msg.get("stop_reason", "")
# Get tool_use blocks
tool_uses = [c for c in content if isinstance(c, dict) and c.get("type") == "tool_use"]
# Extract summary from text content
for c in content:
if isinstance(c, dict) and c.get("type") == "text":
text = c.get("text", "")
if text:
summary = text
# Check for pending permission request
pending_request = _find_pending_request(sid)
if pending_request:
# Check if the tool_use has already been resolved in transcript
req_tool = pending_request.get("tool_name", "")
req_input = pending_request.get("tool_input", {})
if _tool_use_resolved_in_transcript(entries, req_tool, req_input):
req_id = pending_request.get("id", "")
_cleanup_stale_request(req_id)
else:
return "permission_prompt", summary, user_prompt
if tool_uses:
last_tool = tool_uses[-1]
tool_name = last_tool.get("name", "")
if tool_name == "AskUserQuestion":
return "elicitation", summary, user_prompt
if tool_name == "ExitPlanMode":
return "plan_review", summary, user_prompt
# Has unresolved tool_use — check if there's a matching tool_result
tool_id = last_tool.get("id", "")
if not _has_tool_result(entries, tool_id):
return "busy", summary, user_prompt
# Last tool_use is resolved — fall through to idle
if stop_reason == "end_turn" or not tool_uses or _all_tool_uses_resolved(entries, tool_uses):
return "idle", summary, user_prompt
# No assistant message yet — idle if no meaningful user input
# (e.g. session just started, or after /clear which only has system XML)
if not last_assistant and not user_prompt:
return "idle", "", ""
return "busy", "", user_prompt
def _find_pending_request(sid):
"""Find a pending .request.json for this session (no .response.json yet)."""
for path in glob.glob(os.path.join(QUEUE_DIR, "*.request.json")):
resp_path = path.replace(".request.json", ".response.json")
if os.path.exists(resp_path):
continue
try:
with open(path) as f:
data = json.load(f)
if str(data.get("session_id", "")) != str(sid):
continue
# Check if the hook process that wrote this request is still alive.
# If it's dead (SIGKILL, OOM, etc.), atexit cleanup didn't fire and
# the file is orphaned — no process is waiting for the response.
hook_pid = data.get("pid")
if hook_pid:
try:
if not is_process_alive(int(hook_pid)):
try:
os.remove(path)
except OSError:
pass
continue
except (ValueError, TypeError):
pass
return data
except (json.JSONDecodeError, IOError):
continue
return None
def _tool_use_resolved_in_transcript(entries, tool_name, tool_input):
"""Check if the most recent tool_use matching this request has a tool_result."""
# Walk backwards — only check the LAST tool_use with this name
for i in range(len(entries) - 1, -1, -1):
entry = entries[i]
if entry.get("type") != "assistant":
continue
msg = entry.get("message", {})
content = msg.get("content", [])
for c in content:
if not isinstance(c, dict) or c.get("type") != "tool_use":
continue
if c.get("name") != tool_name:
continue
tool_id = c.get("id", "")
# Only check the most recent matching tool_use — don't continue to older ones
return _has_tool_result(entries[i:], tool_id)
return False
def _has_tool_result(entries, tool_id):
"""Check if any user entry has a tool_result matching this tool_use_id."""
for entry in entries:
if entry.get("type") != "user":
continue
msg = entry.get("message", {})
content = msg.get("content", [])
for c in content:
if isinstance(c, dict) and c.get("type") == "tool_result":
if c.get("tool_use_id") == tool_id:
return True
return False
def _all_tool_uses_resolved(entries, tool_uses):
"""Check if all tool_use blocks have matching tool_results."""
if not tool_uses:
return True
return all(_has_tool_result(entries, tu.get("id", "")) for tu in tool_uses)
def _cleanup_stale_request(request_id):
"""Remove stale request/response files."""
if not request_id:
return
for suffix in (".request.json", ".response.json"):
path = os.path.join(QUEUE_DIR, f"{request_id}{suffix}")
try:
os.remove(path)
except OSError:
pass
# ── Zombie session cleanup ──
def _is_session_alive(sid, session_data):
"""Check if a session is still active."""
# Quick path: if session_id is a numeric PID and it's alive, session is definitely alive
try:
if is_process_alive(int(sid)):
return True
except ValueError:
pass # Non-numeric (UUID) session ID
terminal_id = session_data.get("terminal_id", "")
tmux_socket = session_data.get("tmux_socket", "")
if is_terminal_alive(terminal_id, tmux_socket):
return True
# Fallback for sessions without terminal_id (auto-discovered on Windows)
if IS_WINDOWS and not terminal_id:
transcript_path = session_data.get("transcript_path", "")
if transcript_path:
try:
mtime = os.path.getmtime(transcript_path)
if time.time() - mtime < 7200: # active within last 2 hours
return True
except OSError:
pass
# Grace period for sessions still registering
registered_at = session_data.get("registered_at", 0)
if time.time() - registered_at < 60:
return True
return False
def zombie_cleanup_loop():
"""Background thread: remove dead sessions and discover new ones every 30s."""
while True:
time.sleep(30)
dead = []
with sessions_lock:
for sid in list(sessions.keys()):
if not _is_session_alive(sid, sessions[sid]):
dead.append(sid)
for sid in dead:
del sessions[sid]
# Clear auto-allow rules
session_auto_allow.pop(sid, None)
if dead:
print(f"[~] Cleaned up {len(dead)} zombie session(s): {dead}")
# On Windows, periodically scan for new sessions from transcript files.
# This is the fallback for when the SessionStart hook fails to register
# (e.g., Ctrl-C sends CTRL_C_EVENT to all console processes including
# the hook subprocess, killing it before the POST completes).
if IS_WINDOWS:
try:
_restore_sessions_from_terminal_mappings()
except Exception:
pass
# ── HTTP Handler ──
class WebUIHandler(BaseHTTPRequestHandler):
def log_message(self, format, *args):
pass
def do_GET(self):
parsed = urlparse(self.path)
path = parsed.path
if path == "/":
self._respond_html(HTML_PAGE)
elif path == "/api/sessions":
# Update all session states from transcripts
with sessions_lock:
sids = list(sessions.keys())
for sid in sids:
update_session_state(sid)
result = []
with sessions_lock:
for sid, s in sessions.items():
can_prompt = bool(s.get("terminal_id"))
entry = {
"session_id": sid,
"cwd": s["cwd"],
"state": s["derived_state"],
"last_summary": s["last_summary"],
"last_user_prompt": s["last_user_prompt"],
"last_activity": s["last_activity"],
"registered_at": s["registered_at"],
"prompt_capable": can_prompt,
"slug": s.get("slug", ""),
"custom_title": s.get("custom_title", ""),
}
# Attach pending request if in permission_prompt state
if s["derived_state"] == "permission_prompt":
pr = _find_pending_request(sid)
if pr:
entry["pending_request"] = pr
result.append(entry)
# Federation: tag local sessions and merge remote sessions
for entry in result:
entry["machine"] = server_name
session_machine_map[entry["session_id"]] = None
qs = parse_qs(parsed.query)
local_only = qs.get("local_only", [""])[0] == "1"
if remote_servers and not local_only:
remote_results = fetch_remote_sessions()
for remote, remote_sessions in remote_results:
if remote_sessions is None:
continue
for rs in remote_sessions:
rs["machine"] = remote["name"]
original_sid = rs["session_id"]
rs["session_id"] = remote["name"] + ":" + str(original_sid)
rs["_remote_session_id"] = original_sid
session_machine_map[rs["session_id"]] = remote["url"]
result.append(rs)
remote_names = [r["name"] for r in remote_servers]
self._respond_json({"sessions": result, "name": server_name, "remote_names": remote_names})
elif path.startswith("/api/session/") and path.endswith("/transcript"):
# /api/session/<id>/transcript?limit=50&after=0
parts = path.split("/")
sid = parts[3] if len(parts) > 3 else ""
# Federation proxy
remote_url = _get_remote_url_for_session(sid)
if remote_url:
try:
original_sid = _get_original_session_id(sid)
proxy_path = f"/api/session/{original_sid}/transcript"
if parsed.query:
proxy_path += "?" + parsed.query
status, resp_body, ct = proxy_to_remote(remote_url, proxy_path)
self.send_response(status)
self.send_header("Content-Type", ct)
self.end_headers()
self.wfile.write(resp_body)
except Exception as e:
self.send_error(502, f"Remote proxy failed: {e}")
return
params = parse_qs(parsed.query)
limit = int(params.get("limit", [50])[0])
with sessions_lock:
s = sessions.get(sid)
if not s:
self.send_error(404, "Session not found")
return
entries = list(s["transcript_entries"])
# Filter to user/assistant only, take last N
filtered = [e for e in entries if e.get("type") in ("user", "assistant")]
filtered = filtered[-limit:]
self._respond_json({"entries": filtered})
elif path == "/api/check-auto-allow":
params = parse_qs(parsed.query)
sid = params.get("session_id", [""])[0]
tname = params.get("tool_name", [""])[0]
tool_input_str = params.get("tool_input", [""])[0]
try:
tool_input = json.loads(tool_input_str) if tool_input_str else {}
except (json.JSONDecodeError, ValueError):
tool_input = {}
session_rules = session_auto_allow.get(sid)
if session_rules and tname:
result = permission_rules.check_level(tname, tool_input, session_rules)
self._respond_json({
"auto_allow": result == "allow",
"auto_deny": result == "deny",
})
else:
self._respond_json({"auto_allow": False, "auto_deny": False})
elif path == "/api/permissions":
params = parse_qs(parsed.query)
project_dir = params.get("project_dir", [""])[0]
sid = params.get("session_id", [""])[0]
result = {
"repo": permission_rules.load_rules(permission_rules.repo_rules_path()),
"user": permission_rules.load_rules(permission_rules.user_rules_path()),
}
if project_dir:
result["project"] = permission_rules.load_rules(
permission_rules.project_rules_path(project_dir))
if sid:
result["session"] = session_auto_allow.get(sid, {"rules": [], "smart_rules": {}})
self._respond_json(result)
elif path == "/api/pending":
# Legacy endpoint — scan .request.json files
requests = []
for fpath in sorted(glob.glob(os.path.join(QUEUE_DIR, "*.request.json"))):
try:
with open(fpath) as f:
data = json.load(f)
resp_path = fpath.replace(".request.json", ".response.json")
if os.path.exists(resp_path):
continue
pid = data.get("pid")
if pid:
try:
if not is_process_alive(int(pid)):
os.remove(fpath)
continue
except (ValueError, TypeError):
os.remove(fpath)
continue
requests.append(data)
except (json.JSONDecodeError, IOError):
continue
# Federation: aggregate remote pending requests
if remote_servers:
for remote in remote_servers:
try:
url = remote["url"].rstrip("/") + "/api/pending"
req = urllib.request.Request(url)
resp = urllib.request.urlopen(req, timeout=3)
data = json.loads(resp.read())
for r in data.get("requests", []):
r["machine"] = remote["name"]
if "session_id" in r:
r["session_id"] = remote["name"] + ":" + str(r["session_id"])
requests.append(r)
except Exception:
pass
self._respond_json({"requests": requests})
elif path.startswith("/api/image"):
params = parse_qs(parsed.query)
# Federation: route to remote if machine param specified
machine = params.get("machine", [""])[0]
if machine and machine != server_name:
remote_url = next((r["url"] for r in remote_servers if r["name"] == machine), None)
if remote_url:
try:
proxy_path = "/api/image?" + parsed.query
status, resp_body, ct = proxy_to_remote(remote_url, proxy_path)
self.send_response(status)
self.send_header("Content-Type", ct)
self.end_headers()
self.wfile.write(resp_body)
except Exception:
self.send_error(502, "Remote image proxy failed")
return
# Existing local logic continues...
img_path = params.get("path", [""])[0]
if not img_path or not img_path.startswith(IMAGE_DIR) or not os.path.isfile(img_path):
self.send_error(404)
return
ext = os.path.splitext(img_path)[1].lower()
ct = {".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg",
".gif": "image/gif", ".webp": "image/webp"}.get(ext, "application/octet-stream")
self.send_response(200)
self.send_header("Content-Type", ct)
self.end_headers()
with open(img_path, "rb") as f:
self.wfile.write(f.read())
else:
self.send_error(404)
def do_POST(self):
parsed = urlparse(self.path)
path = parsed.path
if path == "/api/session/register":
body = self._read_json()
sid = str(body.get("session_id", ""))
source = body.get("source", "unknown")
if not sid:
self.send_error(400, "Missing session_id")
return
transcript_path = body.get("transcript_path", "")
terminal_id = body.get("terminal_id", "")
tmux_socket = body.get("tmux_socket", "")
cwd = body.get("cwd", "")
with sessions_lock:
# Evict other sessions on the same terminal (new session_id on same pane/tab)
if source in ("startup", "resume", "clear") and terminal_id:
evict = [k for k, v in sessions.items() if k != sid and v.get("terminal_id") == terminal_id]
for k in evict:
del sessions[k]
session_auto_allow.pop(k, None)
if evict:
print(f"[~] Evicted session(s) on terminal {terminal_id}: {evict}")
if source == "startup" or sid not in sessions:
sessions[sid] = {
"transcript_path": transcript_path,
"terminal_id": terminal_id,
"tmux_socket": tmux_socket,
"cwd": cwd,
"registered_at": time.time(),
"transcript_offset": 0,
"transcript_entries": [],
"derived_state": "idle",
"last_activity": time.time(),
"last_summary": "",
"last_user_prompt": "",
"slug": "",
"custom_title": "",
}
else:
# resume/clear/compact — update path and reset offset
s = sessions[sid]
s["transcript_path"] = transcript_path
s["transcript_offset"] = 0
s["transcript_entries"] = []
s["last_activity"] = time.time()
if terminal_id:
s["terminal_id"] = terminal_id
if tmux_socket:
s["tmux_socket"] = tmux_socket
if cwd:
s["cwd"] = cwd
if source == "clear":
# Clear auto-allow rules
session_auto_allow.pop(sid, None)
# Clean up request files for this session
for fpath in glob.glob(os.path.join(QUEUE_DIR, "*.request.json")):
try:
with open(fpath) as f:
data = json.load(f)
if str(data.get("session_id", "")) == sid:
resp_path = fpath.replace(".request.json", ".response.json")
for p in (fpath, resp_path):
try:
os.remove(p)
except OSError:
pass
except (json.JSONDecodeError, IOError):
continue
pane_info = f"terminal={terminal_id}" if terminal_id else "no-terminal"
print(f"[*] Session registered: {sid} source={source} {pane_info}")
self._respond_json({"ok": True})
elif path == "/api/session/deregister":
body = self._read_json()
sid = str(body.get("session_id", ""))
if not sid:
self.send_error(400, "Missing session_id")
return
with sessions_lock:
sessions.pop(sid, None)
session_auto_allow.pop(sid, None)
# Clean up request files
for fpath in glob.glob(os.path.join(QUEUE_DIR, "*.request.json")):
try:
with open(fpath) as f:
data = json.load(f)
if str(data.get("session_id", "")) == sid:
resp_path = fpath.replace(".request.json", ".response.json")
for p in (fpath, resp_path):
try:
os.remove(p)
except OSError:
pass
except (json.JSONDecodeError, IOError):
continue
print(f"[*] Session deregistered: {sid}")
self._respond_json({"ok": True})
elif path == "/api/respond":
body = self._read_json()
request_id = body.get("id", "")
decision = body.get("decision", "deny")
message = body.get("message", "")
# Federation: check if this should be proxied
sid = str(body.get("session_id", ""))
remote_url = _get_remote_url_for_session(sid) if sid else None
if remote_url:
try:
proxy_body = dict(body)
proxy_body.pop("session_id", None)
status, resp_body, ct = proxy_to_remote(
remote_url, "/api/respond", method="POST",
body=json.dumps(proxy_body).encode()
)
self.send_response(status)
self.send_header("Content-Type", ct)
self.end_headers()
self.wfile.write(resp_body)
except Exception as e:
self.send_error(502, f"Remote proxy failed: {e}")
return
request_file = os.path.join(QUEUE_DIR, f"{request_id}.request.json")
if not os.path.exists(request_file):
self.send_error(404, "Request not found")
return
# "always" → write to webui-allow.json (user-level by default)
if decision == "always":
try:
with open(request_file) as f:
req_data = json.load(f)
level = body.get("level", "user")
# Accept structured rules from the new UI
allow_rules = body.get("allow_rules") or []
if not allow_rules:
allow_rule = body.get("allow_rule") or req_data.get("allow_rule")
if allow_rule:
allow_rules = [allow_rule]
project_dir = req_data.get("project_dir", "")
if level == "project" and project_dir:
target_path = permission_rules.project_rules_path(project_dir)
elif level == "repo":
target_path = permission_rules.repo_rules_path()
else:
target_path = permission_rules.user_rules_path()
for rule in allow_rules:
if isinstance(rule, dict) and rule.get("tool"):
permission_rules.add_rule(target_path, rule)
print(f"[+] Added rule to {level}: {rule}")
except (json.JSONDecodeError, IOError) as e:
print(f"[!] Failed to save always-allow rule: {e}")
response_file = os.path.join(QUEUE_DIR, f"{request_id}.response.json")
resp_data = {"decision": decision}
if message:
resp_data["message"] = message
with open(response_file, "w") as f:
json.dump(resp_data, f)
# "always" added a new rule — recheck other pending requests
if decision == "always":
self._recheck_pending_requests()
self._respond_json({"ok": True})
elif path == "/api/session-allow":
body = self._read_json()
sid = str(body.get("session_id", ""))
tool_name = body.get("tool_name", "")
request_id = body.get("id", "")
# Federation proxy
remote_url = _get_remote_url_for_session(sid)
if remote_url:
try:
proxy_body = {"session_id": _get_original_session_id(sid), "tool_name": tool_name, "id": request_id}
status, resp_body, ct = proxy_to_remote(
remote_url, "/api/session-allow", method="POST",
body=json.dumps(proxy_body).encode()
)
self.send_response(status)
self.send_header("Content-Type", ct)
self.end_headers()
self.wfile.write(resp_body)
except Exception as e:
self.send_error(502, f"Remote proxy failed: {e}")
return
if sid and tool_name:
if sid not in session_auto_allow:
session_auto_allow[sid] = {"rules": [], "smart_rules": {}}
rule = body.get("rule") or {"tool": tool_name, "action": "allow"}
session_auto_allow[sid]["rules"].append(rule)
print(f"[+] Session auto-allow: {rule} for session {sid}")
if request_id:
resp_file = os.path.join(QUEUE_DIR, f"{request_id}.response.json")
req_file = os.path.join(QUEUE_DIR, f"{request_id}.request.json")
if os.path.exists(req_file):
with open(resp_file, "w") as f:
json.dump({"decision": "allow"}, f)
# Recheck other pending requests that may now match the new session rule
self._recheck_pending_requests()
self._respond_json({"ok": True})
elif path == "/api/send-prompt":
body = self._read_json()
sid = str(body.get("session_id", ""))
prompt = body.get("prompt", "")
if not sid or not prompt:
self.send_error(400, "Missing session_id or prompt")
return
# Federation proxy
remote_url = _get_remote_url_for_session(sid)
if remote_url:
try:
proxy_body = {"session_id": _get_original_session_id(sid), "prompt": prompt}
status, resp_body, ct = proxy_to_remote(
remote_url, "/api/send-prompt", method="POST",
body=json.dumps(proxy_body).encode()
)
self.send_response(status)
self.send_header("Content-Type", ct)
self.end_headers()
self.wfile.write(resp_body)
except Exception as e:
self.send_error(502, f"Remote proxy failed: {e}")
return
with sessions_lock:
s = sessions.get(sid)
if not s:
self.send_error(404, "Session not found")
return
# Check session state before delivery to avoid pasting into busy terminal
update_session_state(sid)
with sessions_lock:
state = sessions[sid]["derived_state"] if sid in sessions else "unknown"
if state not in ("idle", "elicitation", "plan_review"):
self.send_error(409, f"Session is {state}, not idle")
return