-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
executable file
·1726 lines (1450 loc) · 61.9 KB
/
server.py
File metadata and controls
executable file
·1726 lines (1450 loc) · 61.9 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
#!/home/mfranc/.local/share/mise/installs/python/3.14.0/bin/python3
"""
Simple HTTP server that receives audio, transcribes via Deepgram, and runs Claude.
Usage:
./server.py <folder>
Arguments:
folder - Directory where Claude Code will operate (required)
Endpoints:
POST /transcribe - Send audio data in body, returns transcript and executes Claude
GET /health - Health check
WS /ws - WebSocket for real-time state updates
"""
import argparse
import asyncio
import base64
import json
import mimetypes
import os
import socket
import sys
import threading
import time
import uuid
from collections import OrderedDict
from datetime import datetime, timezone
from http.server import BaseHTTPRequestHandler, HTTPServer
from aiohttp import web
from claude_wrapper import ClaudeWrapper
from logger import logger
from tailscale_auth import verify_peer
# Load Deepgram API key from environment (set via EnvironmentFile in systemd)
if not os.environ.get("DEEPGRAM_API_KEY"):
print("Error: DEEPGRAM_API_KEY environment variable not set", file=sys.stderr)
sys.exit(1)
from deepgram import DeepgramClient
PORT = 5566
client = DeepgramClient()
def utc_now_iso() -> str:
"""Return current UTC time as ISO 8601 string with Z suffix (matches Claude JSONL format)."""
return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z"
# Guard against duplicate Claude launches
last_claude_launch = 0
LAUNCH_COOLDOWN = 5 # seconds
# Working directory for Claude (set via CLI argument)
claude_workdir = None
# Claude wrapper instance (created per request)
# Note: tmux session name kept for backwards compatibility reference
CLAUDE_TMUX_SESSION = "claude-watch"
# Request history for dashboard
request_history = []
MAX_HISTORY = 100
# Store responses from Claude (keyed by request ID)
claude_responses = {}
RESPONSE_TIMEOUT = 120 # seconds to keep response in memory
# Transcription configuration (modifiable via API)
transcription_config = {"model": "nova-3", "language": "en-US", "smart_format": True, "punctuate": True}
# Response configuration
response_config = {
"mode": "disabled", # 'text', 'audio', or 'disabled'
}
# Available options for configuration
CONFIG_OPTIONS = {
"models": ["nova-3", "nova-2", "nova", "enhanced", "base"],
"languages": ["en-US", "pl"],
"response_modes": ["text", "audio", "disabled"],
}
# Directory for temporary audio files
AUDIO_CACHE_DIR = "/tmp/claude-watch-audio"
os.makedirs(AUDIO_CACHE_DIR, exist_ok=True)
# Image store (in-memory, LRU eviction at MAX_IMAGES)
image_store = OrderedDict() # id -> {"data": bytes, "mime": str, "caption": str, "timestamp": str}
MAX_IMAGES = 20
# WebSocket state management
claude_state = {
"status": "idle", # idle, listening, thinking, speaking
"current_request_id": None,
"last_update": None,
}
# Chat history (in-memory, last 50 messages)
chat_history = []
MAX_CHAT_HISTORY = 50
# Connected WebSocket clients: ws -> {device_type, device_id, connected_at, ip}
websocket_clients = {}
# Active Claude wrapper (for cancellation)
active_claude_wrapper: ClaudeWrapper = None
# Terminal request tracking (for tmux-typed prompts)
terminal_request_id: str | None = None
# Current pending prompt (permission request from Claude)
current_prompt = None # {question, options: [{num, label, description, selected}], timestamp}
# Pending permission requests from hooks (keyed by request_id)
pending_permissions = {} # {request_id: {tool_name, tool_input, tool_use_id, status, decision, reason, timestamp}}
PERMISSION_TIMEOUT = 120 # seconds
# Event loop for WebSocket (set when server starts)
ws_loop = None
def broadcast_message(message: dict):
"""Broadcast a message to all connected WebSocket clients"""
if not websocket_clients or ws_loop is None:
return
async def _broadcast():
dead_clients = []
msg_json = json.dumps(message)
for ws in websocket_clients:
try:
await ws.send_str(msg_json)
except Exception as e:
logger.debug(f"WebSocket send error: {e}")
dead_clients.append(ws)
# Remove dead clients
for ws in dead_clients:
websocket_clients.pop(ws, None)
try:
asyncio.run_coroutine_threadsafe(_broadcast(), ws_loop)
except Exception as e:
logger.debug(f"Broadcast error: {e}")
def set_claude_state(status: str, request_id: str = None):
"""Update Claude state and broadcast to clients"""
claude_state["status"] = status
claude_state["current_request_id"] = request_id
claude_state["last_update"] = utc_now_iso()
broadcast_message({"type": "state", "status": status, "request_id": request_id})
logger.info(f"[STATE] Claude state: {status}")
def add_chat_message(role: str, content: str):
"""Add a message to chat history and broadcast"""
message = {"role": role, "content": content, "timestamp": utc_now_iso()}
chat_history.append(message)
# Trim to max size
while len(chat_history) > MAX_CHAT_HISTORY:
chat_history.pop(0)
broadcast_message({"type": "chat", **message})
logger.info(f"[CHAT] {role}: {content[:50]}...")
def set_current_prompt(prompt: dict):
"""Update current prompt and broadcast to clients"""
global current_prompt
current_prompt = prompt
broadcast_message({"type": "prompt", "prompt": prompt})
if prompt:
logger.info(f"[PROMPT] {prompt['question']} ({len(prompt['options'])} options)")
else:
logger.info("[PROMPT] Cleared")
def text_to_speech(text: str, request_id: str) -> str:
"""Convert text to speech using Deepgram TTS, returns file path"""
log_file = "/tmp/claude-watch-tts.log"
try:
with open(log_file, "a") as f:
f.write(f"\n=== TTS Request {request_id} ===\n")
f.write(f"Text: {text[:100]}...\n")
# Debug: log available methods
f.write(f"client.speak attrs: {[a for a in dir(client.speak) if not a.startswith('_')]}\n")
audio_path = os.path.join(AUDIO_CACHE_DIR, f"{request_id}.mp3")
# Truncate text if too long (Deepgram TTS has limits)
MAX_TTS_CHARS = 1500
if len(text) > MAX_TTS_CHARS:
text = text[:MAX_TTS_CHARS] + "..."
with open(log_file, "a") as f:
f.write(f"Truncated to {MAX_TTS_CHARS} chars\n")
# Use direct HTTP request to Deepgram TTS API
import urllib.error
import urllib.request
url = "https://api.deepgram.com/v1/speak?model=aura-asteria-en&mip_opt_out=true"
headers = {
"Authorization": f"Token {os.environ['DEEPGRAM_API_KEY']}",
"Content-Type": "application/json",
}
data = json.dumps({"text": text}).encode("utf-8")
req = urllib.request.Request(url, data=data, headers=headers, method="POST")
with urllib.request.urlopen(req, timeout=30) as response:
audio_data = response.read()
with open(audio_path, "wb") as f:
f.write(audio_data)
with open(log_file, "a") as f:
f.write(f"Success: {audio_path} ({len(audio_data)} bytes)\n")
print(f"[TTS] Generated audio: {audio_path}")
return audio_path
except Exception as e:
import traceback
error_msg = traceback.format_exc()
with open(log_file, "a") as f:
f.write(f"Error: {e}\n")
f.write(f"Traceback:\n{error_msg}\n")
print(f"[TTS] Error generating speech: {e}")
traceback.print_exc()
return None
def transcribe_audio(audio_data: bytes) -> str:
"""Transcribe m4a audio data using Deepgram (auto-detects format)"""
response = client.listen.v1.media.transcribe_file(
request=audio_data,
model=transcription_config["model"],
language=transcription_config["language"],
smart_format=transcription_config["smart_format"],
punctuate=transcription_config["punctuate"],
mip_opt_out=True,
)
transcript = ""
if hasattr(response, "results"):
channels = response.results.channels
if channels and len(channels) > 0:
alternatives = channels[0].alternatives
if alternatives and len(alternatives) > 0:
transcript = alternatives[0].transcript
return transcript
def add_response_step(request_id: str, step: dict):
"""Add a step to the request history for response tracking"""
for entry in request_history:
if entry.get("request_id") == request_id:
if "steps" not in entry:
entry["steps"] = []
entry["steps"].append(step)
break
def update_response_step(request_id: str, step_name: str, updates: dict):
"""Update an existing step in the request history"""
for entry in request_history:
if entry.get("request_id") == request_id:
for step in entry.get("steps", []):
if step.get("name") == step_name:
step.update(updates)
break
break
def update_permission_step(claude_request_id: str, permission_request_id: str, updates: dict):
"""Update a permission step in request history by permission_request_id"""
for entry in request_history:
if entry.get("request_id") == claude_request_id:
for step in entry.get("steps", []):
if step.get("permission_request_id") == permission_request_id:
step.update(updates)
break
break
def _summarize_tool_input(name, input_data):
"""Return a short summary string for a tool invocation."""
if not isinstance(input_data, dict):
return ""
if name == "Bash":
cmd = input_data.get("command", "")
return cmd[:80] + ("..." if len(cmd) > 80 else "")
if name in ("Read", "Write"):
return input_data.get("file_path", "")
if name == "Edit":
return input_data.get("file_path", "")
if name in ("Glob", "Grep"):
return input_data.get("pattern", "")
if name == "Task":
return input_data.get("description", "")
if name == "WebFetch":
return input_data.get("url", "")
# Fallback: first string value up to 80 chars
for v in input_data.values():
if isinstance(v, str) and v:
return v[:80] + ("..." if len(v) > 80 else "")
return ""
def init_claude_wrapper():
"""Initialize the Claude wrapper with global callbacks and start the background watcher.
Global callbacks broadcast all activity to WebSocket clients, regardless of
whether the prompt came from the server or was typed directly in tmux.
"""
model = transcription_config.get("claude_model")
wrapper = ClaudeWrapper.get_instance(claude_workdir, model=model)
def _store_claude_timestamp(req_id, claude_timestamp):
"""Store the first and last claude timestamp on the history entry."""
if not req_id or not claude_timestamp:
return
for entry in request_history:
if entry.get("request_id") == req_id:
if "first_claude_timestamp" not in entry:
entry["first_claude_timestamp"] = claude_timestamp
entry["last_claude_timestamp"] = claude_timestamp
break
def on_text(text_chunk, claude_timestamp=None):
req_id = claude_state.get("current_request_id")
msg = {"type": "text_chunk", "request_id": req_id, "text": text_chunk}
if claude_timestamp:
msg["claude_timestamp"] = claude_timestamp
_store_claude_timestamp(req_id, claude_timestamp)
broadcast_message(msg)
def on_tool(name, input_data, claude_timestamp=None):
req_id = claude_state.get("current_request_id")
broadcast_message({"type": "tool", "request_id": req_id, "tool": name})
_store_claude_timestamp(req_id, claude_timestamp)
# Add tool step to timeline for tracing
if req_id:
summary = _summarize_tool_input(name, input_data)
step = {
"name": "tool",
"label": f"Tool: {name}",
"status": "completed",
"timestamp": utc_now_iso(),
"details": summary,
"tool_name": name,
}
if claude_timestamp:
step["claude_timestamp"] = claude_timestamp
add_response_step(req_id, step)
def on_user_message(text):
"""Handle user messages from tmux-typed prompts (not server-initiated)."""
global terminal_request_id
add_chat_message("user", text)
# Create a timeline entry so terminal requests appear in the dashboard
request_id = str(uuid.uuid4())[:8]
terminal_request_id = request_id
entry = {
"id": len(request_history) + 1,
"request_id": request_id,
"timestamp": utc_now_iso(),
"input_type": "terminal",
"content_type": "text/plain",
"size_bytes": len(text.encode()),
"transcript": text,
"claude_launched": True,
"status": "processing",
"error": None,
"steps": [
{
"name": "received",
"label": "Terminal",
"status": "completed",
"timestamp": utc_now_iso(),
"details": f"Terminal input: {len(text)} chars",
},
{
"name": "claude",
"label": "Claude",
"status": "in_progress",
"timestamp": utc_now_iso(),
"details": "Processing...",
},
],
}
request_history.insert(0, entry)
if len(request_history) > MAX_HISTORY:
request_history.pop()
set_claude_state("thinking", request_id)
def on_usage(usage):
broadcast_message(
{
"type": "usage",
"input_tokens": usage["input_tokens"],
"output_tokens": usage["output_tokens"],
"cache_read_tokens": usage["cache_read_tokens"],
"cache_creation_tokens": usage["cache_creation_tokens"],
"total_context": usage["total_context"],
"context_window": usage["context_window"],
"context_percent": usage["context_percent"],
"cost_usd": usage["cost_usd"],
}
)
def on_turn_complete(result, server_initiated):
"""For tmux-typed prompts, add response to chat and return to idle."""
global terminal_request_id
if not server_initiated:
if result:
add_chat_message("claude", result)
# Finalize the terminal timeline entry
req_id = terminal_request_id
if req_id:
# Add Response Ready step with Claude's JSONL timestamp
claude_ts = None
for entry in request_history:
if entry.get("request_id") == req_id:
claude_ts = entry.get("last_claude_timestamp")
break
if claude_ts:
add_response_step(
req_id,
{
"name": "response_ready_claude",
"label": "Response Ready",
"status": "completed",
"timestamp": claude_ts,
"details": f"Claude produced response ({len(result)} chars)" if result else "No response",
},
)
update_response_step(
req_id,
"claude",
{
"status": "completed",
"details": f"Finished ({len(result)} chars)" if result else "No response",
},
)
client_count = len(websocket_clients)
add_response_step(
req_id,
{
"name": "response_broadcast",
"label": "Response Sent",
"status": "completed",
"timestamp": utc_now_iso(),
"details": (
f"Broadcast to {client_count} client{'s' if client_count != 1 else ''} via WebSocket"
),
},
)
# Mark the history entry as completed or error
for entry in request_history:
if entry.get("request_id") == req_id:
entry["status"] = "completed" if result else "error"
break
terminal_request_id = None
set_claude_state("idle")
wrapper.register_callbacks(
on_text=on_text,
on_tool=on_tool,
on_user_message=on_user_message,
on_usage=on_usage,
on_turn_complete=on_turn_complete,
)
wrapper.start_background_watcher()
logger.info("[SERVER] Claude wrapper initialized with background watcher")
return wrapper
def run_claude(text: str, request_id: str = None, response_mode: str = "text"):
"""Run Claude with a prompt using the JSON streaming wrapper."""
global last_claude_launch, active_claude_wrapper
now = time.time()
# Cooldown check
if now - last_claude_launch < LAUNCH_COOLDOWN:
print(f"[GUARD] Skipping Claude launch - cooldown active ({LAUNCH_COOLDOWN}s)")
return False
last_claude_launch = now
# Update state to thinking
set_claude_state("thinking", request_id)
# Add user message to chat
add_chat_message("user", text)
# Mark response as pending
if request_id:
claude_responses[request_id] = {"status": "pending", "timestamp": utc_now_iso()}
add_response_step(
request_id,
{
"name": "claude_started",
"label": "Claude Started",
"status": "in_progress",
"timestamp": utc_now_iso(),
"details": "Running Claude with JSON streaming...",
},
)
def run_in_thread():
global active_claude_wrapper
try:
# Get model from config if set
model = transcription_config.get("claude_model")
# Use singleton wrapper for persistent process
wrapper = ClaudeWrapper.get_instance(claude_workdir, model=model)
active_claude_wrapper = wrapper
accumulated_text = []
def on_text(text_chunk):
"""Per-request callback: accumulate text for result tracking."""
accumulated_text.append(text_chunk)
logger.debug(f"[CLAUDE] Text: {text_chunk[:50]}...")
def on_result(result):
logger.info(f"[CLAUDE] Result: {result[:100]}...")
# Run Claude - global callbacks handle broadcasting,
# per-request callbacks handle request-specific tracking
result = wrapper.run(text, on_text=on_text, on_result=on_result)
active_claude_wrapper = None
# Update step
if request_id:
update_response_step(
request_id,
"claude_started",
{"status": "completed", "details": f"Claude finished ({len(result)} chars)"},
)
# Handle response based on mode
if response_mode == "disabled":
claude_responses[request_id] = {"status": "disabled", "timestamp": utc_now_iso()}
set_claude_state("idle")
return
# Look up claude timestamps stored by global on_text/on_tool callbacks
claude_ts = None
if request_id:
for entry in request_history:
if entry.get("request_id") == request_id:
claude_ts = entry.get("last_claude_timestamp")
break
# Add "Response Ready" step with Claude's JSONL timestamp
if claude_ts:
add_response_step(
request_id,
{
"name": "response_ready_claude",
"label": "Response Ready",
"status": "completed",
"timestamp": claude_ts,
"details": f"Claude produced response ({len(result)} chars)",
},
)
# Add "Response Captured" step with server timestamp
captured_step = {
"name": "response_captured",
"label": "Response Captured",
"status": "completed",
"timestamp": utc_now_iso(),
"details": result[:200] + ("..." if len(result) > 200 else ""),
}
if claude_ts:
captured_step["claude_timestamp"] = claude_ts
add_response_step(request_id, captured_step)
# Add Claude's response to chat (broadcasts via WebSocket)
if result:
add_chat_message("claude", result)
# Track that the response was broadcast to connected devices
if request_id:
client_count = len(websocket_clients)
add_response_step(
request_id,
{
"name": "response_broadcast",
"label": "Response Sent",
"status": "completed",
"timestamp": utc_now_iso(),
"details": (
f"Broadcast to {client_count} client{'s' if client_count != 1 else ''} via WebSocket"
),
},
)
# Generate TTS if audio mode
audio_path = None
if response_mode == "audio" and result:
add_response_step(
request_id,
{
"name": "tts_generating",
"label": "Generating Audio",
"status": "in_progress",
"timestamp": utc_now_iso(),
"details": "Sending to Deepgram TTS...",
},
)
audio_path = text_to_speech(result, request_id)
update_response_step(
request_id,
"tts_generating",
{
"status": "completed" if audio_path else "error",
"details": "Audio generated" if audio_path else "TTS failed",
},
)
# Add final ready step
add_response_step(
request_id,
{
"name": "response_ready",
"label": "Ready for Watch",
"status": "completed",
"timestamp": utc_now_iso(),
"details": f"Type: {response_mode}",
},
)
claude_responses[request_id] = {
"status": "completed",
"response": result,
"audio_path": audio_path,
"timestamp": utc_now_iso(),
}
# Update state
set_claude_state("speaking", request_id)
def return_to_idle():
time.sleep(5)
if claude_state.get("status") == "speaking":
set_claude_state("idle")
idle_thread = threading.Thread(target=return_to_idle, daemon=True)
idle_thread.start()
except Exception as e:
logger.error(f"[CLAUDE] Error: {e}")
import traceback
traceback.print_exc()
if request_id:
claude_responses[request_id] = {
"status": "error",
"error": str(e),
"timestamp": utc_now_iso(),
}
add_response_step(
request_id,
{
"name": "error",
"label": "Error",
"status": "error",
"timestamp": utc_now_iso(),
"details": str(e),
},
)
set_claude_state("idle")
active_claude_wrapper = None
# Run in background thread
thread = threading.Thread(target=run_in_thread, daemon=True)
thread.start()
return True
class DictationHandler(BaseHTTPRequestHandler):
def handle(self):
# Peek at raw data before any parsing
print(f"\n{'=' * 50}")
print(f"[CONN] New connection from {self.client_address}")
try:
# Read first 500 bytes to debug
self.connection.setblocking(0)
import select
ready = select.select([self.connection], [], [], 1.0)
if ready[0]:
peek_data = self.connection.recv(500, socket.MSG_PEEK)
print("[RAW] First 500 bytes preview:")
print(f"[RAW] Hex: {peek_data[:100].hex()}")
print(f"[RAW] Text: {peek_data[:200]}")
self.connection.setblocking(1)
except Exception as e:
print(f"[DEBUG] Peek failed: {e}")
print(f"{'=' * 50}")
super().handle()
def parse_request(self):
print(f"[PARSE] Raw request line: {self.raw_requestline}")
result = super().parse_request()
if result:
print(f"[PARSE] Method: {self.command}, Path: {self.path}")
return result
def send_json(self, status_code, data, cors=True):
"""Send a JSON response with standard headers"""
self.send_response(status_code)
self.send_header("Content-Type", "application/json")
if cors:
self.send_header("Access-Control-Allow-Origin", "*")
self.end_headers()
self.wfile.write(json.dumps(data).encode())
def do_POST(self):
peer_ip = getattr(self, "client_address", ("127.0.0.1",))[0]
if not verify_peer(peer_ip):
self.send_error(403, "Unauthorized Tailscale node")
return
content_length = int(self.headers.get("Content-Length", 0))
content_type = self.headers.get("Content-Type", "unknown")
# Handle config update
if self.path == "/api/config":
self.handle_config_update(content_length)
return
# Handle response acknowledgment from watch
if self.path.startswith("/api/response/") and self.path.endswith("/ack"):
self.handle_response_ack()
return
# Handle text message from phone app
if self.path == "/api/message":
self.handle_text_message(content_length)
return
# Handle prompt response (selecting an option)
if self.path == "/api/prompt/respond":
self.handle_prompt_respond(content_length)
return
# Handle Claude restart
if self.path == "/api/claude/restart":
self.handle_claude_restart()
return
# Handle permission request from hook
if self.path == "/api/permission/request":
self.handle_permission_request(content_length)
return
# Handle permission response from mobile app
if self.path == "/api/permission/respond":
self.handle_permission_respond(content_length)
return
# Handle image upload
if self.path == "/api/image":
self.handle_image_upload(content_length)
return
print("=== Incoming Request ===")
print(f"Path: {self.path}")
print(f"Content-Type: {content_type}")
print(f"Content-Length: {content_length} bytes")
print(f"Headers: {dict(self.headers)}")
audio_data = self.rfile.read(content_length)
print(f"Received {len(audio_data)} bytes of audio data")
if len(audio_data) > 0:
print(f"First 20 bytes (hex): {audio_data[:20].hex()}")
print("========================")
request_id = str(uuid.uuid4())[:8] # Short unique ID
# Update state to listening (audio received, being transcribed)
set_claude_state("listening", request_id)
entry = {
"id": len(request_history) + 1,
"request_id": request_id,
"timestamp": utc_now_iso(),
"input_type": "voice",
"content_type": content_type,
"size_bytes": content_length,
"transcript": None,
"claude_launched": False,
"status": "processing",
"error": None,
"steps": [
{
"name": "received",
"label": "Watch",
"status": "completed",
"timestamp": utc_now_iso(),
"details": f"{content_length} bytes, {content_type}",
}
],
}
try:
# Step 2: Sending to Deepgram
sending_at = datetime.now()
entry["steps"].append(
{
"name": "sending",
"label": "Sent to Deepgram",
"status": "completed",
"timestamp": utc_now_iso(),
"details": "Audio sent to cloud",
}
)
transcript = transcribe_audio(audio_data)
transcribed_at = datetime.now()
print(f"Transcript: {transcript}")
entry["transcript"] = transcript or ""
# Step 3: Transcribed
duration_ms = int((transcribed_at - sending_at).total_seconds() * 1000)
entry["steps"].append(
{
"name": "transcribed",
"label": "Transcribed",
"status": "completed",
"timestamp": utc_now_iso(),
"duration_ms": duration_ms,
"details": transcript if transcript else "No speech detected",
}
)
# Insert into history BEFORE launching Claude so run_claude()
# can add steps (claude_started, permissions, etc.) to this entry
request_history.insert(0, entry)
if len(request_history) > MAX_HISTORY:
request_history.pop()
# Step 4: Claude
response_mode = self.headers.get("X-Response-Mode", "text")
if transcript:
launched = run_claude(transcript, request_id, response_mode)
entry["claude_launched"] = launched
entry["status"] = "completed"
entry["steps"].append(
{
"name": "claude",
"label": "Claude",
"status": "completed" if launched else "skipped",
"timestamp": utc_now_iso(),
"details": "Launched" if launched else "Skipped (duplicate)",
}
)
else:
entry["status"] = "no_speech"
entry["steps"].append(
{
"name": "claude",
"label": "Claude",
"status": "skipped",
"timestamp": utc_now_iso(),
"details": "Skipped (no speech)",
}
)
self.send_json(
200,
{
"status": "ok",
"request_id": request_id,
"transcript": transcript or "",
"response_enabled": response_mode != "disabled",
"response_mode": response_mode,
"message": "No speech detected" if not transcript else None,
},
cors=False,
)
except Exception as e:
print(f"Error: {e}")
entry["status"] = "error"
entry["error"] = str(e)
# Mark current step as failed
if len(entry["steps"]) > 0:
last_step = entry["steps"][-1]
if last_step["status"] != "completed":
last_step["status"] = "error"
last_step["error"] = str(e)
else:
# Error happened after last step
entry["steps"].append(
{
"name": "error",
"label": "Error",
"status": "error",
"timestamp": utc_now_iso(),
"details": str(e),
}
)
# Entry already in request_history (inserted before Claude launch)
# If error happened before that insert (early in try block),
# add it now as a fallback
if entry not in request_history:
request_history.insert(0, entry)
if len(request_history) > MAX_HISTORY:
request_history.pop()
self.send_json(500, {"status": "error", "message": str(e)}, cors=False)
def do_GET(self):
peer_ip = getattr(self, "client_address", ("127.0.0.1",))[0]
if not verify_peer(peer_ip):
self.send_error(403, "Unauthorized Tailscale node")
return
if self.path == "/health":
self.send_json(200, {"status": "ok"}, cors=False)
elif self.path.startswith("/api/response/"):
self.handle_response_check()
elif self.path.startswith("/api/permission/status/"):
self.handle_permission_status()
elif self.path.startswith("/api/audio/"):
self.handle_audio_file()
elif self.path == "/api/history":
self.send_json(200, {"history": request_history, "workdir": claude_workdir})
elif self.path == "/api/config":
self.send_json(
200, {"config": transcription_config, "response_config": response_config, "options": CONFIG_OPTIONS}
)
elif self.path == "/api/chat":
self.send_json(200, {"messages": chat_history, "state": claude_state, "prompt": current_prompt})
elif self.path.startswith("/api/image/"):
self.handle_image_serve()
elif self.path == "/" or self.path == "/dashboard":
self.serve_dashboard()
elif self.path == "/viewer":
self.serve_viewer()
else:
self.send_response(404)
self.end_headers()
def handle_claude_restart(self):
"""Handle POST /api/claude/restart to restart the Claude process"""
global active_claude_wrapper
try:
wrapper = ClaudeWrapper._instance
if wrapper:
wrapper.shutdown()
active_claude_wrapper = None
# Clear chat history
chat_history.clear()
set_claude_state("idle")
broadcast_message({"type": "history", "messages": []})
# Re-initialize wrapper with background watcher
init_claude_wrapper()
logger.info("[SERVER] Claude process restarted")
self.send_json(200, {"status": "restarted"})
except Exception as e:
logger.error(f"[SERVER] Error restarting Claude: {e}")
self.send_json(500, {"error": str(e)})
def handle_config_update(self, content_length):
"""Handle POST /api/config to update transcription settings"""
global transcription_config
try:
body = self.rfile.read(content_length)
new_config = json.loads(body.decode())
# Validate and update config