-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdaemon.py
More file actions
2582 lines (2331 loc) · 86.4 KB
/
Copy pathdaemon.py
File metadata and controls
2582 lines (2331 loc) · 86.4 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
import array
import base64
import binascii
import importlib.util
import json
import os
import queue
import re
import resource
import shlex
import shutil
import signal
import subprocess
import sys
import tempfile
import threading
import time
import traceback
import urllib.parse
import urllib.request
import wave
from collections import OrderedDict
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from voice_features import (
adaptive_word_budget,
apply_pronunciations,
classify_intent,
detect_build_signal,
earcon_pcm,
enforce_spoken_contract,
git_change_summary,
git_snapshot,
redact_sensitive,
request_intent,
transcript_tool_evidence,
trim_to_words,
)
ROOT = Path(__file__).resolve().parent
HOST = "127.0.0.1"
PORT = 7333
TABLE_FALLBACK_TEXT = (
"I made a table for this, but I won't read the whole thing out loud. "
"Take a look and tell me what you think."
)
PREFIX_TEMPLATES = ("In {project}: ", "From {project}: ", "Update from {project}: ")
LOG_PATH = ROOT / ".voice.log"
CONFIG_PATH = ROOT / "config.json"
TURN_STATE_PATH = ROOT / ".turns.json"
TIMELINE_PATH = ROOT / ".timeline.json"
INBOX_PATH = ROOT / ".voice-inbox.json"
DUCK_LEASE_PATH = ROOT / ".media-duck-lease.json"
CONTROLLER_PATH = ROOT / "controller.html"
RING_DIR = ROOT / ".clips"
VOICES_DIR = ROOT / "voices"
KILL_PATH = ROOT / ".voice-disabled"
AUDITION_TEXT = "This is {voice}, speaking for your coding agents."
FFPLAY = shutil.which("ffplay")
FFMPEG = shutil.which("ffmpeg")
RING_SIZE = 8
PEAK_TARGET = 160
SAMPLE_RATE = 24000
DEFAULT_CONDENSE_PROMPT = (
"You are speaking for a coding agent after it has finished a turn. "
"The user hears this out loud, so speak the smallest truthful thing that lets them continue without looking. "
"Lead with the result, blocker, or exact decision required. Mention evidence and uncertainty when they matter. "
"Never discuss summarizing, prompts, the assistant, or the user. "
"If the reply contains a table, summarize the table's meaning conversationally. "
)
CATALOG_VOICES = (
"alba",
"anna",
"azelma",
"bill_boerst",
"caro_davy",
"charles",
"cosette",
"eponine",
"estelle",
"eve",
"fantine",
"george",
"giovanni",
"jane",
"javert",
"jean",
"juergen",
"lola",
"marius",
"mary",
"michael",
"paul",
"peter_yearsley",
"rafael",
"stuart_bell",
"vera",
)
KOKORO_VOICES = (
"af_alloy",
"af_aoede",
"af_bella",
"af_heart",
"af_jessica",
"af_kore",
"af_nicole",
"af_nova",
"af_river",
"af_sarah",
"af_sky",
"am_adam",
"am_echo",
"am_eric",
"am_fenrir",
"am_liam",
"am_michael",
"am_onyx",
"am_puck",
"am_santa",
"bf_alice",
"bf_emma",
"bf_isabella",
"bf_lily",
"bm_daniel",
"bm_fable",
"bm_george",
"bm_lewis",
"ef_dora",
"em_alex",
"em_santa",
"ff_siwis",
"hf_alpha",
"hf_beta",
"hm_omega",
"hm_psi",
"if_sara",
"im_nicola",
"jf_alpha",
"jf_gongitsune",
"jf_nezumi",
"jf_tebukuro",
"jm_kumo",
"pf_dora",
"pm_alex",
"pm_santa",
"zf_xiaobei",
"zf_xiaoni",
"zf_xiaoxiao",
"zf_xiaoyi",
"zm_yunjian",
"zm_yunxi",
"zm_yunxia",
"zm_yunyang",
)
def torch_to_pcm(audio) -> bytes:
data = audio.detach().cpu().clamp(-1, 1).numpy()
return (data * 32767).astype("<i2").tobytes()
class TTSEngine:
name = ""
sample_rate = SAMPLE_RATE
install_command = ""
def installed(self) -> bool:
return True
def loaded(self) -> bool:
return False
def load(self):
raise NotImplementedError
def voices(self) -> list:
raise NotImplementedError
def synth(self, text: str, voice: str):
raise NotImplementedError
class PocketEngine(TTSEngine):
name = "pocket"
sample_rate = SAMPLE_RATE
install_command = "uv add pocket-tts"
def __init__(self):
self.model = None
self.voice_states = {}
def loaded(self) -> bool:
return self.model is not None
def load(self):
if self.model is None:
from pocket_tts.models.tts_model import TTSModel
self.model = TTSModel.load_model(
language="english", temp=float(config["temperature"])
)
self.sample_rate = self.model.sample_rate
return self.model
def voices(self) -> list:
return list(CATALOG_VOICES) + [
v for v in custom_voices() if v not in CATALOG_VOICES
]
def voice_source(self, name: str) -> str:
custom = VOICES_DIR / f"{name}.wav"
return str(custom) if custom.exists() else name
def voice_state_for(self, name: str):
model = self.load()
if name not in self.voice_states:
self.voice_states[name] = model.get_state_for_audio_prompt(
self.voice_source(name)
)
return self.voice_states[name]
def synth(self, text: str, voice: str):
model = self.load()
voice_state = self.voice_state_for(voice)
for chunk in model.generate_audio_stream(
model_state=voice_state, text_to_generate=text
):
yield torch_to_pcm(chunk)
def reset(self) -> None:
self.model = None
self.voice_states = {}
def drop_voice(self, name: str) -> None:
self.voice_states.pop(name, None)
class KokoroEngine(TTSEngine):
name = "kokoro"
sample_rate = SAMPLE_RATE
install_command = "uv add 'kokoro>=0.9.4'"
def __init__(self):
self.pipelines = {}
def installed(self) -> bool:
return importlib.util.find_spec("kokoro") is not None
def loaded(self) -> bool:
return bool(self.pipelines)
def load(self, lang_code: str = "a"):
if not self.installed():
raise RuntimeError(f"kokoro is not installed. Run: {self.install_command}")
if lang_code not in self.pipelines:
os.environ.setdefault("PYTORCH_ENABLE_MPS_FALLBACK", "1")
import torch
from kokoro import KPipeline
device = "cpu"
if (
getattr(torch.backends, "mps", None)
and torch.backends.mps.is_available()
):
device = "mps"
self.pipelines[lang_code] = KPipeline(
lang_code=lang_code, repo_id="hexgrad/Kokoro-82M", device=device
)
return self.pipelines[lang_code]
def voices(self) -> list:
return list(KOKORO_VOICES)
def synth(self, text: str, voice: str):
if voice not in KOKORO_VOICES:
voice = "af_heart"
pipeline = self.load(voice[0])
for result in pipeline(text, voice=voice, speed=1, split_pattern=r"\n+"):
if result.audio is not None:
yield torch_to_pcm(result.audio)
ENGINES = {"pocket": PocketEngine(), "kokoro": KokoroEngine()}
def custom_voices() -> list:
try:
return sorted(p.stem for p in VOICES_DIR.glob("*.wav"))
except Exception:
return []
def all_voices() -> list:
return active_engine().voices()
CONFIG_SPEC = {
"engine": {"default": "pocket", "kind": "engine"},
"max_direct_chars": {"default": 400, "kind": "int", "min": 50, "max": 5000},
"idle_exit_s": {"default": 600, "kind": "int", "min": 60, "max": 86400},
"project_window_s": {"default": 600, "kind": "int", "min": 30, "max": 7200},
"condense_provider": {"default": "ollama", "kind": "condense_provider"},
"condense_ollama_model": {"default": "qwen3.5:4b", "kind": "str"},
"condense_timeout_s": {"default": 30, "kind": "int", "min": 2, "max": 60},
"rate": {"default": 1.0, "kind": "float", "min": 0.5, "max": 3.0},
"volume": {"default": 1.0, "kind": "float", "min": 0.0, "max": 1.0},
"temperature": {"default": 0.7, "kind": "float", "min": 0.1, "max": 1.5},
"ducking_enabled": {"default": False, "kind": "bool"},
"browser_youtube_ducking_enabled": {"default": False, "kind": "bool"},
"browser_youtube_duck_target_volume": {"default": 15, "kind": "int", "min": 0, "max": 100},
"repo_earcons_enabled": {"default": True, "kind": "bool"},
"intent_earcons_enabled": {"default": True, "kind": "bool"},
"build_sonification_enabled": {"default": True, "kind": "bool"},
"adaptive_brevity_enabled": {"default": True, "kind": "bool"},
"diff_narration_enabled": {"default": True, "kind": "bool"},
"privacy_sentinel_enabled": {"default": True, "kind": "bool"},
"radio_bulletins_enabled": {"default": True, "kind": "bool"},
"radio_batch_window_ms": {"default": 450, "kind": "int", "min": 0, "max": 3000},
"voice_inbox_enabled": {"default": False, "kind": "bool"},
"duck_target_volume": {"default": 25, "kind": "int", "min": 0, "max": 100},
"duck_fade_ms": {"default": 400, "kind": "int", "min": 0, "max": 3000},
"duck_restore_delay_ms": {"default": 150, "kind": "int", "min": 0, "max": 3000},
"quiet_hours": {"default": None, "kind": "quiet"},
"voices": {
"default": {"claude": "alba", "codex": "michael", "notification": "eve"},
"kind": "voices",
},
"condense_prompt": {"default": DEFAULT_CONDENSE_PROMPT, "kind": "str"},
"stream_playback": {"default": True, "kind": "bool"},
}
def git_rev() -> str | None:
try:
out = subprocess.run(
["git", "-C", str(ROOT), "rev-parse", "--short", "HEAD"],
capture_output=True,
text=True,
timeout=2,
)
return out.stdout.strip() or None
except Exception:
return None
GIT_REV = git_rev()
def git_runtime_state() -> dict:
try:
branch = subprocess.run(
["git", "-C", str(ROOT), "branch", "--show-current"],
capture_output=True,
text=True,
timeout=2,
).stdout.strip()
dirty = bool(
subprocess.run(
["git", "-C", str(ROOT), "status", "--porcelain"],
capture_output=True,
text=True,
timeout=2,
).stdout.strip()
)
return {"rev": git_rev(), "branch": branch or "detached", "dirty": dirty}
except Exception:
return {"rev": GIT_REV, "branch": "unknown", "dirty": None}
def hook_install_status() -> dict:
expected = str(ROOT / "hook.py")
events = ("Stop", "UserPromptSubmit", "Notification")
status = {"claude": {}, "codex": {}}
try:
data = json.loads((Path.home() / ".claude" / "settings.json").read_text())
hooks = data.get("hooks") or {}
for event in events:
status["claude"][event] = expected in json.dumps(hooks.get(event) or [])
except Exception:
status["claude"] = {event: False for event in events}
try:
text = (Path.home() / ".codex" / "config.toml").read_text()
has_command = expected in text
for event in events:
status["codex"][event] = has_command and f"[[hooks.{event}]]" in text
except Exception:
status["codex"] = {event: False for event in events}
return status
def ollama_reachable() -> bool:
try:
urllib.request.urlopen("http://127.0.0.1:11434/api/tags", timeout=0.5).read(1)
return True
except Exception:
return False
def doctor_snapshot() -> dict:
hooks = hook_install_status()
provider = config.get("condense_provider", "none")
ollama = ollama_reachable()
condense_ok = provider == "none" or (provider == "ollama" and ollama)
condense_detail = {
"none": "disabled · local",
"ollama": f"ollama · local · {'reachable' if ollama else 'not running'}",
}.get(provider, provider)
checks = [
{"name": "daemon", "ok": True, "detail": f"127.0.0.1:{PORT}", "required": True},
{
"name": "tts",
"ok": active_engine().installed(),
"detail": f"{active_engine_name()} · {'loaded' if active_engine().loaded() else 'cold'}",
"required": True,
},
{
"name": "claude hooks",
"ok": all(hooks["claude"].values()),
"detail": ", ".join(name for name, ok in hooks["claude"].items() if not ok) or "all events",
"required": True,
},
{
"name": "codex hooks",
"ok": all(hooks["codex"].values()),
"detail": ", ".join(name for name, ok in hooks["codex"].items() if not ok) or "all events",
"required": True,
},
{
"name": "condense",
"ok": condense_ok,
"detail": condense_detail,
"required": provider != "none",
},
{
"name": "speech switch",
"ok": not muted(),
"detail": "enabled" if not muted() else "shut up is on",
"required": False,
},
{
"name": "browser adapter",
"ok": (ROOT / "browser-extension" / "manifest.json").exists(),
"detail": "packaged, browser load is manual",
"required": False,
},
{
"name": "playback",
"ok": bool(FFPLAY or shutil.which("afplay")),
"detail": "ffplay" if FFPLAY else "afplay",
"required": True,
},
]
required_ok = all(check["ok"] for check in checks if check["required"])
return {
"ok": required_ok,
"checks": checks,
"hooks": hooks,
"git": git_runtime_state(),
"provider": provider,
"locality": "local",
}
state_lock = threading.Lock()
pending = {}
worker_running = False
generation = 0
generations = {}
active_player = None
active_cwd = None
active_cwds = set()
working_cwd = None
working_cwds = set()
last_activity = time.monotonic()
started_at = time.monotonic()
last_spoken_ts = None
last_spoken_text = None
last_spoken_clip = None
last_stages = None
now_speaking = None
sse_subscribers = []
sse_lock = threading.Lock()
recent_projects = {}
turn_records = {}
timeline_events = []
voice_inbox = []
prefix_counter = 0
clip_ring = OrderedDict()
def turn_key(cwd=None, session_id=None, turn_id=None) -> str:
return "|".join(str(value or "") for value in (session_id, turn_id, cwd))
def job_key(cwd=None, kind="reply", session_id=None, turn_id=None) -> tuple:
if kind == "reply" and (session_id or turn_id):
return (cwd, kind, session_id, turn_id)
return (cwd, kind)
def save_turn_records() -> None:
try:
cutoff = time.time() - 86400
records = [
{key: value for key, value in record.items() if key != "prompt"}
for record in turn_records.values()
if float(record.get("started_at") or 0) >= cutoff
][-64:]
TURN_STATE_PATH.write_text(json.dumps(records, indent=2) + "\n")
except Exception:
append_log("turn_state_error", action="save")
def load_turn_records() -> None:
try:
records = json.loads(TURN_STATE_PATH.read_text()) if TURN_STATE_PATH.exists() else []
cutoff = time.time() - 86400
for record in records:
if float(record.get("started_at") or 0) >= cutoff:
turn_records[record["key"]] = record
except Exception:
append_log("turn_state_error", action="load")
def store_turn(data: dict) -> dict:
cwd = data.get("cwd")
prompt, _ = redact_sensitive(str(data.get("prompt") or ""), cwd)
key = turn_key(cwd, data.get("session_id"), data.get("turn_id"))
record = {
"key": key,
"cwd": cwd,
"session_id": data.get("session_id"),
"turn_id": data.get("turn_id"),
"transcript_path": data.get("transcript_path"),
"started_at": time.time(),
"request_intent": request_intent(prompt),
"git": None,
"git_state": "pending" if cwd else "unavailable",
"prompt": prompt,
}
with state_lock:
turn_records[key] = record
save_turn_records()
def capture() -> None:
snapshot = git_snapshot(cwd)
with state_lock:
current = turn_records.get(key)
if not current:
return
current["git"] = snapshot or None
current["git_state"] = "ready" if snapshot else "unavailable"
save_turn_records()
threading.Thread(target=capture, daemon=True).start()
return record
def take_turn(job: dict) -> dict:
cwd = job.get("cwd")
exact = turn_key(cwd, job.get("session_id"), job.get("turn_id"))
with state_lock:
record = turn_records.pop(exact, None)
if not record:
candidates = [
item for item in turn_records.values()
if item.get("cwd") == cwd
and (not job.get("session_id") or item.get("session_id") == job.get("session_id"))
]
if candidates:
record = max(candidates, key=lambda item: item.get("started_at", 0))
turn_records.pop(record["key"], None)
save_turn_records()
return record or {}
def load_timeline() -> None:
global timeline_events
try:
raw = json.loads(TIMELINE_PATH.read_text()) if TIMELINE_PATH.exists() else []
cutoff = time.time() - 7 * 86400
timeline_events = [event for event in raw if float(event.get("ts") or 0) >= cutoff][-200:]
except Exception:
timeline_events = []
append_log("timeline_error", action="load")
def save_timeline() -> None:
try:
TIMELINE_PATH.write_text(json.dumps(timeline_events[-200:], indent=2) + "\n")
except Exception:
append_log("timeline_error", action="save")
def temporal_context(cwd: str | None, verification: str, intent: str) -> str:
recent = [event for event in timeline_events if event.get("cwd") == cwd][-8:]
if not recent:
return ""
prior = recent[-1]
if prior.get("verification") == "failed" and verification == "passed":
return "Earlier verification failed; this turn resolves it with passing checks."
if prior.get("intent") == "blocker" and intent == "success":
return "The previous turn was blocked; this turn reports the resolution."
return ""
def remember_timeline(cwd: str | None, meta: dict, intent: str, build_signal: str | None) -> None:
event = {
"ts": round(time.time(), 3),
"cwd": cwd,
"project": project_name(cwd),
"intent": intent,
"request_intent": meta.get("request_intent") or "",
"verification": meta.get("verification") or "unknown",
"tests": meta.get("verification_tests") or [],
"semantic": meta.get("semantic") or [],
"diff_files": int(meta.get("diff_files") or 0),
"build_signal": build_signal,
}
timeline_events.append(event)
del timeline_events[:-200]
save_timeline()
def recap_text(cwd: str | None = None) -> str:
events = [event for event in timeline_events if not cwd or event.get("cwd") == cwd][-12:]
if not events:
return "No recent work is recorded."
projects = []
for event in events:
name = event.get("project") or "project"
if name not in projects:
projects.append(name)
latest = events[-1]
failures = [event for event in events if event.get("verification") == "failed" or event.get("intent") == "blocker"]
passed_after = failures and latest.get("verification") == "passed"
facts = [fact for event in events for fact in event.get("semantic") or []]
prefix = f"Recent work across {', '.join(projects[:3])}. " if len(projects) > 1 else f"In {projects[0]}. "
if passed_after:
prefix += "An earlier failure was resolved and the latest checks passed. "
elif failures:
prefix += "A blocker or failed check remains in the recent arc. "
elif latest.get("verification") == "passed":
prefix += "The latest checks passed. "
if facts:
prefix += facts[-1].rstrip(".") + "."
return trim_to_words(prefix, 38)
def load_voice_inbox() -> None:
global voice_inbox
try:
raw = json.loads(INBOX_PATH.read_text()) if INBOX_PATH.exists() else []
voice_inbox = raw[-100:] if isinstance(raw, list) else []
except Exception:
voice_inbox = []
append_log("inbox_error", action="load")
def save_voice_inbox() -> None:
try:
INBOX_PATH.write_text(json.dumps(voice_inbox[-100:], indent=2) + "\n")
except Exception:
append_log("inbox_error", action="save")
def inbox_add(cwd: str | None, text: str, meta: dict, intent: str) -> None:
entry = {
"ts": round(time.time(), 3),
"cwd": cwd,
"project": project_name(cwd) or "project",
"text": trim_to_words(text, 42),
"intent": intent,
"verification": meta.get("verification") or "unknown",
"tests": meta.get("verification_tests") or [],
"semantic": meta.get("semantic") or [],
}
with state_lock:
voice_inbox.append(entry)
del voice_inbox[:-100]
save_voice_inbox()
append_log("inbox_add", project=entry["project"], intent=intent)
publish({"event": "inbox", "count": len(voice_inbox)})
def inbox_briefing(entries: list[dict]) -> str:
if not entries:
return "You're caught up. No agent updates are waiting."
latest_by_project = {}
for entry in entries:
latest_by_project[entry.get("project") or "project"] = entry
ordered = sorted(
latest_by_project.values(),
key=lambda item: item.get("intent") not in {"blocker", "needs_input", "warning"},
)
clauses = []
for entry in ordered[:5]:
text = str(entry.get("text") or "update ready").strip().rstrip(".")
clauses.append(f"{entry.get('project') or 'project'}: {text}")
opening = f"{len(entries)} update{'s' if len(entries) != 1 else ''} while you were away. "
return trim_to_words(opening + ". ".join(clauses) + ".", 72)
def drain_voice_inbox() -> tuple[str, int]:
with state_lock:
entries = list(voice_inbox)
voice_inbox.clear()
save_voice_inbox()
text = inbox_briefing(entries)
append_log(
"return_briefing",
count=len(entries),
projects=sorted({e.get("project") for e in entries if e.get("project")}),
)
publish({"event": "inbox", "count": 0})
return text, len(entries)
def should_hold_for_inbox(kind: str, prepared: bool = False) -> bool:
return bool(config.get("voice_inbox_enabled") and kind == "reply" and not prepared)
config = {key: spec["default"] for key, spec in CONFIG_SPEC.items()}
duck_state = {
"spotify": {
"did_duck": False,
"saved_volume": None,
"ducked_at": None,
"restoring": False,
},
"browser_youtube": {"active": False, "generation": 0},
}
duck_lock = threading.Lock()
def active_engine_name() -> str:
return config.get("engine", "pocket")
def engine_by_name(name: str | None = None) -> TTSEngine:
return ENGINES[name or active_engine_name()]
def active_engine() -> TTSEngine:
return engine_by_name()
def rss_mb() -> float:
return round(resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1024 / 1024, 1)
def now() -> float:
return time.monotonic()
def bump_activity() -> None:
global last_activity
last_activity = now()
def json_response(handler: BaseHTTPRequestHandler, status: int, body: dict) -> None:
payload = json.dumps(body).encode("utf-8")
handler.send_response(status)
handler.send_header("Content-Type", "application/json")
handler.send_header("Content-Length", str(len(payload)))
handler.end_headers()
handler.wfile.write(payload)
def read_json(handler: BaseHTTPRequestHandler) -> dict:
length = int(handler.headers.get("Content-Length", "0") or 0)
if length <= 0:
return {}
return json.loads(handler.rfile.read(length).decode("utf-8"))
def publish(event: dict) -> None:
with sse_lock:
subs = list(sse_subscribers)
for sub in subs:
try:
sub.put_nowait(event)
except Exception:
pass
def append_log(event: str, **fields) -> None:
payload = {"ts": round(time.time(), 3), "event": event, **fields}
publish(payload)
try:
if LOG_PATH.exists():
lines = LOG_PATH.read_text().splitlines()
if len(lines) > 500:
LOG_PATH.write_text("\n".join(lines[-250:]) + "\n")
with LOG_PATH.open("a") as handle:
handle.write(json.dumps(payload, ensure_ascii=True) + "\n")
except Exception:
return
def log_error(where: str) -> None:
append_log("error", where=where, trace=traceback.format_exc()[-1500:])
def validate_field(key: str, value):
spec = CONFIG_SPEC[key]
kind = spec["kind"]
if kind == "int":
value = int(value)
if not spec["min"] <= value <= spec["max"]:
raise ValueError(key)
return value
if kind == "float":
value = float(value)
if not spec["min"] <= value <= spec["max"]:
raise ValueError(key)
return value
if kind == "str":
value = str(value).strip()
if not value:
raise ValueError(key)
return value
if kind == "bool":
if not isinstance(value, bool):
raise ValueError(key)
return value
if kind == "quiet":
if value is None:
return None
start = str(value.get("start", ""))
end = str(value.get("end", ""))
for stamp in (start, end):
if not re.fullmatch(r"\d{2}:\d{2}", stamp):
raise ValueError(key)
hours, minutes = int(stamp[:2]), int(stamp[3:])
if hours > 23 or minutes > 59:
raise ValueError(key)
return {"start": start, "end": end}
if kind == "voices":
merged = dict(spec["default"])
catalog = set(all_voices())
for slot, name in dict(value).items():
if slot not in merged or name not in catalog:
raise ValueError(key)
merged[slot] = name
return merged
if kind == "engine":
value = str(value).strip()
if value not in ENGINES or not ENGINES[value].installed():
raise ValueError(key)
return value
if kind == "condense_provider":
value = str(value).strip().lower()
if value not in {"ollama", "none"}:
raise ValueError(key)
return value
raise ValueError(key)
def load_config() -> None:
global config
cfg = {key: spec["default"] for key, spec in CONFIG_SPEC.items()}
raw = {}
if CONFIG_PATH.exists():
try:
raw = json.loads(CONFIG_PATH.read_text())
if not isinstance(raw, dict):
raise ValueError("config.json")
except Exception:
append_log("config_error", field="_file")
raw = {}
for key, value in raw.items():
if key not in CONFIG_SPEC:
continue
try:
cfg[key] = validate_field(key, value)
except Exception:
append_log("config_error", field=key)
config = cfg
def save_config() -> None:
try:
CONFIG_PATH.write_text(json.dumps(config, indent=2) + "\n")
except Exception:
append_log("config_error", field="_write")
def apply_config(data: dict) -> tuple[dict, list]:
global config
errors = []
new = dict(config)
drop_model = False
for key, value in dict(data).items():
if key not in CONFIG_SPEC:
errors.append(key)
continue
try:
cleaned = validate_field(key, value)
except Exception:
errors.append(key)
append_log("config_error", field=key)
continue
if key == "temperature" and cleaned != new.get(key):
drop_model = True
new[key] = cleaned
with state_lock:
config = new
if drop_model:
engine = ENGINES.get("pocket")
if hasattr(engine, "reset"):
engine.reset()
save_config()
return new, errors
def in_quiet_hours() -> bool:
quiet = config.get("quiet_hours")
if not quiet:
return False
local = time.localtime()
cur = local.tm_hour * 60 + local.tm_min
sh, sm = quiet["start"].split(":")
eh, em = quiet["end"].split(":")
start = int(sh) * 60 + int(sm)
end = int(eh) * 60 + int(em)
if start == end:
return False
if start < end:
return start <= cur < end
return cur >= start or cur < end
def is_table_line(line: str) -> bool:
s = line.strip()
if not s:
return False
if s.count("|") < 2:
return False
return s.startswith("|") or s.endswith("|") or bool(re.search(r"\w\s*\|\s*\w", s))
def strip_markdown_tables(raw: str) -> tuple[str, dict]:
kept = []
table_lines = 0
separator_lines = 0
for line in raw.splitlines():
if is_table_line(line):
table_lines += 1
if re.fullmatch(r"\s*\|?[\s:|-]+\|[\s:|-|]*", line.strip()):
separator_lines += 1
continue
kept.append(line)
data_rows = max(0, table_lines - separator_lines - 1) if table_lines else 0
return "\n".join(kept), {
"table_lines": table_lines,
"table_rows": data_rows,
"table_skipped": table_lines > 0,
}
def strip_markdown(text: str) -> str:
text = re.sub(r"```[\s\S]*?```", " ", text)
clean_lines = []
for line in text.splitlines():
s = line.strip()
if not s:
continue
if s.startswith(("+++", "---", "@@", "diff ", "Traceback ", 'File "')):
continue
s = re.sub(r"\bhttps?://\S+", " ", s)
s = re.sub(r"(?:~|\.)?/[\w .-]+(?:/[\w .-]+)+(?:[:]\d+)?", " ", s)
s = re.sub(r"(?:\./|\../)?[\w.-]+(?:/[\w.-]+)+(?:[:]\d+)?", " ", s)
s = re.sub(
r"\b[\w.-]+\.(?:py|js|ts|tsx|jsx|json|toml|md|html|css|sh)(?::\d+)?\b",
" ",
s,
)
s = re.sub(r"\s+", " ", s).strip()
if not s:
continue
clean_lines.append(s)
text = " ".join(clean_lines)
text = re.sub(r"`([^`]+)`", r"\1", text)
text = re.sub(r"\*\*([^*]+)\*\*", r"\1", text)
text = re.sub(r"[*_#>\[\]()]", " ", text)
text = re.sub(r"\s+", " ", text).strip()
return text
def first_sentence(text: str) -> str:
match = re.search(r"(.{30,}?[.!?])\s", text + " ")
if match:
return match.group(1).strip()
return text[: config["max_direct_chars"]].strip()