-
-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathaudio-hooks.py
More file actions
1440 lines (1279 loc) Β· 59.5 KB
/
Copy pathaudio-hooks.py
File metadata and controls
1440 lines (1279 loc) Β· 59.5 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
"""audio-hooks β single JSON CLI for the claude-code-audio-hooks project.
This binary is the canonical machine interface for the project. It is designed
for Claude Code (and other AI agents) to operate the project end-to-end without
any human interaction.
Hard rules:
- All output is JSON to stdout. No stderr in normal operation.
- Nonzero exit codes carry a JSON error body on stdout.
- No prompts, no colors, no spinners, no menus.
- Every config knob is settable in one shot via `set` or a typed setter.
- Every state read returns a single JSON document in <100ms.
The keystone subcommand is `manifest`: it returns the complete machine
description of every other subcommand, every config key, every hook, every
audio file, and every error code. Read it once and the entire surface area is
known.
"""
from __future__ import annotations
import json
import os
import platform
import re
import sys
import time
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple
# ---------------------------------------------------------------------------
# Path discovery β find the project root and import hook_runner helpers
# ---------------------------------------------------------------------------
def _find_project_root() -> Optional[Path]:
"""Discover the project root by walking up from this script.
Mirrors hook_runner.get_project_dir() but starts from bin/ instead of
hooks/. Honors CLAUDE_AUDIO_HOOKS_PROJECT for explicit override.
"""
explicit = os.environ.get("CLAUDE_AUDIO_HOOKS_PROJECT")
if explicit:
p = Path(explicit)
if (p / "hooks" / "hook_runner.py").exists():
return p
here = Path(__file__).resolve()
# Walk up looking for the project signature: hooks/hook_runner.py + config/
for ancestor in [here.parent] + list(here.parents):
if (ancestor / "hooks" / "hook_runner.py").exists() and (ancestor / "config").is_dir():
return ancestor
# Plugin install: ${CLAUDE_PLUGIN_ROOT}
plugin_root = os.environ.get("CLAUDE_PLUGIN_ROOT")
if plugin_root:
p = Path(plugin_root)
# The plugin layout symlinks hooks/ -> ../../../hooks/ so this works.
if (p / "hooks" / "hook_runner.py").exists():
return p
# Or the plugin might point at the runner subdir directly
runner = p / "runner" / "hook_runner.py"
if runner.exists():
return p.parent.parent.parent if (p.parent.parent.parent / "config").is_dir() else None
return None
PROJECT_ROOT = _find_project_root()
def _import_hook_runner():
"""Import the hook_runner module so we can reuse its helpers."""
if PROJECT_ROOT is None:
return None
hooks_dir = PROJECT_ROOT / "hooks"
if str(hooks_dir) not in sys.path:
sys.path.insert(0, str(hooks_dir))
try:
import hook_runner # type: ignore
return hook_runner
except ImportError:
return None
HR = _import_hook_runner()
# ---------------------------------------------------------------------------
# JSON output helpers
# ---------------------------------------------------------------------------
def emit(payload: Dict[str, Any]) -> None:
"""Print a JSON document to stdout. Compact, no trailing newline noise."""
sys.stdout.write(json.dumps(payload, ensure_ascii=False, separators=(",", ":")) + "\n")
sys.stdout.flush()
def emit_error(code: str, message: str, hint: str = "", suggested_command: str = "", **extra: Any) -> int:
"""Emit a JSON error to stdout and return exit code 1."""
err: Dict[str, Any] = {"ok": False, "error": {"code": code, "message": message}}
if hint:
err["error"]["hint"] = hint
if suggested_command:
err["error"]["suggested_command"] = suggested_command
for k, v in extra.items():
err[k] = v
emit(err)
return 1
def require_project_root() -> int:
"""Bail with a structured error if the project root could not be found."""
if PROJECT_ROOT is None:
return emit_error(
code="PROJECT_DIR_NOT_FOUND",
message="Could not locate the claude-code-audio-hooks project directory.",
hint="Set CLAUDE_AUDIO_HOOKS_PROJECT or run from inside the repo.",
suggested_command="audio-hooks status",
)
if HR is None:
return emit_error(
code="INTERNAL_ERROR",
message="Could not import hook_runner.py from the project directory.",
hint="The project layout may be corrupted.",
suggested_command="audio-hooks diagnose",
)
return 0
# ---------------------------------------------------------------------------
# Project state β version, install detection, hook catalogue
# ---------------------------------------------------------------------------
PROJECT_VERSION = "5.1.2"
# Canonical hook catalogue. Order matches CLAUDE.md and the install scripts.
HOOK_CATALOG: List[Dict[str, Any]] = [
{"name": "notification", "default": True, "audio": "notification-urgent.mp3", "description": "Authorization or plan confirmation requested"},
{"name": "stop", "default": True, "audio": "task-complete.mp3", "description": "Claude finished responding"},
{"name": "subagent_stop", "default": True, "audio": "subagent-complete.mp3", "description": "Background subagent task done"},
{"name": "permission_request", "default": True, "audio": "permission-request.mp3", "description": "Permission dialog appeared"},
{"name": "session_start", "default": False, "audio": "session-start.mp3", "description": "Session began (matchers: startup|resume|clear|compact)"},
{"name": "session_end", "default": False, "audio": "session-end.mp3", "description": "Session ended"},
{"name": "pretooluse", "default": False, "audio": "task-starting.mp3", "description": "Before each tool execution (noisy)"},
{"name": "posttooluse", "default": False, "audio": "task-progress.mp3", "description": "After each tool execution (very noisy)"},
{"name": "posttoolusefailure", "default": False, "audio": "tool-failed.mp3", "description": "Tool execution failed"},
{"name": "userpromptsubmit", "default": False, "audio": "prompt-received.mp3", "description": "User submitted a prompt"},
{"name": "precompact", "default": False, "audio": "notification-info.mp3", "description": "Before context compaction"},
{"name": "postcompact", "default": False, "audio": "post-compact.mp3", "description": "After context compaction"},
{"name": "subagent_start", "default": False, "audio": "subagent-start.mp3", "description": "Subagent spawned"},
{"name": "teammate_idle", "default": False, "audio": "teammate-idle.mp3", "description": "Agent Teams teammate going idle"},
{"name": "task_completed", "default": False, "audio": "team-task-done.mp3", "description": "Agent Teams task completed"},
{"name": "stop_failure", "default": False, "audio": "stop-failure.mp3", "description": "API error (matchers: rate_limit|authentication_failed|...)"},
{"name": "config_change", "default": False, "audio": "config-change.mp3", "description": "Configuration file changed"},
{"name": "instructions_loaded", "default": False, "audio": "instructions-loaded.mp3", "description": "CLAUDE.md or rules loaded"},
{"name": "worktree_create", "default": False, "audio": "worktree-create.mp3", "description": "Worktree created"},
{"name": "worktree_remove", "default": False, "audio": "worktree-remove.mp3", "description": "Worktree removed"},
{"name": "elicitation", "default": False, "audio": "elicitation.mp3", "description": "MCP server requested user input"},
{"name": "elicitation_result", "default": False, "audio": "elicitation-result.mp3", "description": "User responded to MCP elicitation"},
# New in v5.0 (dedicated audio shipped in v5.0.1, generated via ElevenLabs).
{"name": "permission_denied", "default": True, "audio": "permission-denied.mp3", "description": "Auto mode classifier denied a tool call (v5.0)"},
{"name": "cwd_changed", "default": False, "audio": "cwd-changed.mp3", "description": "Working directory changed (v5.0)"},
{"name": "file_changed", "default": False, "audio": "file-changed.mp3", "description": "Watched file changed on disk (v5.0)"},
{"name": "task_created", "default": True, "audio": "task-created.mp3", "description": "Task created via TaskCreate (v5.0)"},
]
def _detect_install_mode() -> Dict[str, Any]:
"""Detect whether the script install and/or plugin install are present.
The script install is detected by the legacy ~/.claude/hooks/hook_runner.py
file (placed there by scripts/install-complete.sh).
The plugin install is detected by:
1. CLAUDE_PLUGIN_ROOT being set (we're invoked from inside a hook), OR
2. ~/.claude/plugins/installed_plugins.json containing audio-hooks, OR
3. ~/.claude/plugins/cache/<id>/ existing for any audio-hooks plugin.
"""
home = Path.home()
script_install = (home / ".claude" / "hooks" / "hook_runner.py").exists()
plugin_install = bool(os.environ.get("CLAUDE_PLUGIN_ROOT"))
if not plugin_install:
installed_json = home / ".claude" / "plugins" / "installed_plugins.json"
if installed_json.exists():
try:
data = json.loads(installed_json.read_text(encoding="utf-8"))
# Schema may be {"plugins": {...}} or a flat dict; check both
blob = json.dumps(data).lower()
if "audio-hooks" in blob:
plugin_install = True
except Exception:
pass
if not plugin_install:
cache_dir = home / ".claude" / "plugins" / "cache"
if cache_dir.exists():
try:
for entry in cache_dir.rglob("plugin.json"):
try:
if "audio-hooks" in entry.parent.name.lower():
plugin_install = True
break
manifest = json.loads(entry.read_text(encoding="utf-8"))
if manifest.get("name") == "audio-hooks":
plugin_install = True
break
except Exception:
continue
except Exception:
pass
result: Dict[str, Any] = {"script_install": script_install, "plugin_install": plugin_install}
if script_install and plugin_install:
result["warning"] = {
"code": "DUAL_INSTALL_DETECTED",
"message": "Both the legacy script install and the plugin install are active. This causes double audio. Run `bash scripts/uninstall.sh --yes` from the project directory to remove the legacy script install.",
}
return result
def _redact_url(url: str) -> str:
"""Redact secrets from a webhook URL for safe display."""
if not url:
return ""
# Strip basic-auth and query strings that might contain tokens
out = re.sub(r"://[^@]+@", "://***@", url)
out = re.sub(r"\?.*$", "?***", out)
return out
def _is_running_from_plugin() -> bool:
"""True if this CLI is invoked from a plugin install context."""
if os.environ.get("CLAUDE_PLUGIN_DATA"):
return True
try:
here = Path(__file__).resolve()
# bin/audio-hooks.py -> plugin root is parent.parent
plugin_root = here.parent.parent
if (plugin_root / ".claude-plugin" / "plugin.json").exists():
return True
except Exception:
pass
return False
def _resolve_plugin_data_dir() -> Path:
"""Compute the plugin data dir even when CLAUDE_PLUGIN_DATA isn't set."""
home = Path.home()
data_root = home / ".claude" / "plugins" / "data"
canonical = data_root / "audio-hooks-chanmeng-audio-hooks"
if canonical.exists():
return canonical
if data_root.exists():
try:
for child in data_root.iterdir():
if child.is_dir() and "audio-hooks" in child.name:
return child
except OSError:
pass
return canonical
def _auto_init_user_prefs(target: Path) -> None:
"""Copy default_preferences.json into target if target doesn't exist."""
if target.exists():
return
try:
target.parent.mkdir(parents=True, exist_ok=True)
template = PROJECT_ROOT / "config" / "default_preferences.json"
if template.exists():
import shutil as _sh
_sh.copy2(str(template), str(target))
except OSError:
pass
def _config_path() -> Path:
"""Resolve user_preferences.json path.
Resolution order:
1. CLAUDE_PLUGIN_DATA env var (hook fire context).
2. Plugin context detected from script path (CLI via plugin bin/).
3. CLAUDE_AUDIO_HOOKS_DATA explicit override.
4. Legacy <project_dir>/config/user_preferences.json (script install).
Plugin contexts auto-init from default_preferences.json on first read.
"""
plugin_data = os.environ.get("CLAUDE_PLUGIN_DATA")
if plugin_data:
target = Path(plugin_data) / "user_preferences.json"
_auto_init_user_prefs(target)
return target
if _is_running_from_plugin():
target = _resolve_plugin_data_dir() / "user_preferences.json"
_auto_init_user_prefs(target)
return target
explicit = os.environ.get("CLAUDE_AUDIO_HOOKS_DATA")
if explicit:
return Path(explicit) / "user_preferences.json"
return PROJECT_ROOT / "config" / "user_preferences.json"
def _apply_plugin_option_overlay(config: Dict[str, Any]) -> Dict[str, Any]:
"""Overlay CLAUDE_PLUGIN_OPTION_* env vars onto the loaded config (v5.0.1).
Mirrors hook_runner._apply_plugin_option_overlay so the CLI sees the same
effective config as the hook runner. The plugin manifest declares
userConfig keys; Claude Code exposes them via CLAUDE_PLUGIN_OPTION_<KEY>.
"""
overlays = {
"CLAUDE_PLUGIN_OPTION_AUDIO_THEME": ("audio_theme", str),
"CLAUDE_PLUGIN_OPTION_WEBHOOK_URL": ("webhook_settings.url", str),
"CLAUDE_PLUGIN_OPTION_WEBHOOK_FORMAT": ("webhook_settings.format", str),
"CLAUDE_PLUGIN_OPTION_TTS_ENABLED": ("tts_settings.enabled", lambda v: v.lower() in ("1", "true", "yes")),
}
for env_var, (dotted_key, coerce) in overlays.items():
raw = os.environ.get(env_var, "").strip()
if not raw:
continue
try:
value = coerce(raw)
except (TypeError, ValueError):
continue
_set_dotted(config, dotted_key, value)
if env_var == "CLAUDE_PLUGIN_OPTION_WEBHOOK_URL" and value:
config.setdefault("webhook_settings", {})["enabled"] = True
return config
def _load_config_raw() -> Dict[str, Any]:
cp = _config_path()
if not cp.exists():
return _apply_plugin_option_overlay({})
try:
return _apply_plugin_option_overlay(json.loads(cp.read_text(encoding="utf-8")))
except json.JSONDecodeError:
return _apply_plugin_option_overlay({})
def _save_config_raw(cfg: Dict[str, Any]) -> Tuple[bool, str]:
cp = _config_path()
try:
cp.parent.mkdir(parents=True, exist_ok=True)
cp.write_text(json.dumps(cfg, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
return True, ""
except OSError as e:
return False, str(e)
def _get_dotted(cfg: Dict[str, Any], key: str) -> Any:
parts = key.split(".")
cur: Any = cfg
for p in parts:
if not isinstance(cur, dict) or p not in cur:
return None
cur = cur[p]
return cur
def _set_dotted(cfg: Dict[str, Any], key: str, value: Any) -> None:
parts = key.split(".")
cur: Dict[str, Any] = cfg
for p in parts[:-1]:
if p not in cur or not isinstance(cur[p], dict):
cur[p] = {}
cur = cur[p]
cur[parts[-1]] = value
def _coerce_value(raw: str) -> Any:
"""Best-effort coercion: bool, int, float, JSON, else string."""
s = raw.strip()
if s.lower() in ("true", "false"):
return s.lower() == "true"
if s.lower() in ("null", "none"):
return None
if s and (s[0] in "{[\"" or s.lstrip("-").replace(".", "").isdigit()):
try:
return json.loads(s)
except json.JSONDecodeError:
pass
return raw
# ---------------------------------------------------------------------------
# Snooze marker (matches hook_runner.is_snoozed)
# ---------------------------------------------------------------------------
def _queue_dir() -> Path:
if HR is not None:
return HR.QUEUE_DIR
return Path("/tmp/claude_audio_hooks_queue")
def _snooze_file() -> Path:
return _queue_dir() / "snooze_until"
def _snooze_status() -> Dict[str, Any]:
sf = _snooze_file()
if not sf.exists():
return {"active": False, "remaining_seconds": 0, "until": None}
try:
until = float(sf.read_text(encoding="utf-8").strip())
except (OSError, ValueError):
return {"active": False, "remaining_seconds": 0, "until": None}
now = time.time()
if now >= until:
return {"active": False, "remaining_seconds": 0, "until": until}
return {
"active": True,
"remaining_seconds": int(until - now),
"until": until,
"until_iso": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(until)),
}
def _parse_duration(s: str) -> Optional[int]:
"""Parse '30m', '1h', '90s', or bare integer (minutes). Return seconds."""
s = s.strip().lower()
if not s:
return None
m = re.match(r"^(\d+)\s*([smhd]?)$", s)
if not m:
return None
n = int(m.group(1))
unit = m.group(2) or "m"
if unit == "s":
return n
if unit == "m":
return n * 60
if unit == "h":
return n * 3600
if unit == "d":
return n * 86400
return None
# ---------------------------------------------------------------------------
# Subcommand: version
# ---------------------------------------------------------------------------
def cmd_version(_args: List[str]) -> int:
if require_project_root() != 0:
return 1
install = _detect_install_mode()
emit({
"ok": True,
"version": PROJECT_VERSION,
"hook_runner_version": getattr(HR, "HOOK_RUNNER_VERSION", PROJECT_VERSION),
"project_dir": str(PROJECT_ROOT),
"script_install": install["script_install"],
"plugin_install": install["plugin_install"],
})
return 0
# ---------------------------------------------------------------------------
# Subcommand: status
# ---------------------------------------------------------------------------
def cmd_status(_args: List[str]) -> int:
if require_project_root() != 0:
return 1
cfg = _load_config_raw()
enabled_hooks_cfg = cfg.get("enabled_hooks", {}) if isinstance(cfg.get("enabled_hooks"), dict) else {}
def is_on(name: str, default: bool) -> bool:
v = enabled_hooks_cfg.get(name)
return bool(v) if isinstance(v, bool) else default
enabled = [h["name"] for h in HOOK_CATALOG if is_on(h["name"], h["default"])]
webhook = cfg.get("webhook_settings", {}) or {}
tts = cfg.get("tts_settings", {}) or {}
focus = cfg.get("focus_flow", {}) or {}
rl = cfg.get("rate_limit_alerts", {}) or {}
sl = cfg.get("statusline_settings", {}) or {}
install = _detect_install_mode()
# Resolve the effective plugin data dir even when CLAUDE_PLUGIN_DATA isn't set
plugin_data_dir = os.environ.get("CLAUDE_PLUGIN_DATA")
if not plugin_data_dir and _is_running_from_plugin():
plugin_data_dir = str(_resolve_plugin_data_dir())
emit({
"ok": True,
"version": PROJECT_VERSION,
"project_dir": str(PROJECT_ROOT),
"plugin_data_dir": plugin_data_dir,
"queue_dir": str(_queue_dir()),
"log_dir": str(HR.get_log_dir()) if HR else None,
"theme": cfg.get("audio_theme", "default"),
"enabled_hooks": enabled,
"enabled_hook_count": len(enabled),
"total_hook_count": len(HOOK_CATALOG),
"snooze": _snooze_status(),
"focus_flow": {
"enabled": bool(focus.get("enabled")),
"mode": focus.get("mode", "disabled"),
},
"webhook": {
"enabled": bool(webhook.get("enabled")),
"format": webhook.get("format", "raw"),
"url_redacted": _redact_url(webhook.get("url", "")),
},
"tts": {
"enabled": bool(tts.get("enabled")),
"speak_assistant_message": bool(tts.get("speak_assistant_message")),
},
"rate_limit_alerts": {
"enabled": bool(rl.get("enabled", True)),
"five_hour_thresholds": rl.get("five_hour_thresholds", [80, 95]),
"seven_day_thresholds": rl.get("seven_day_thresholds", [80, 95]),
},
"install": install,
"statusline": {
"visible_segments": sl.get("visible_segments", []),
},
})
return 0
# ---------------------------------------------------------------------------
# Subcommand: get / set
# ---------------------------------------------------------------------------
def cmd_get(args: List[str]) -> int:
if require_project_root() != 0:
return 1
if not args:
return emit_error("INVALID_USAGE", "Usage: audio-hooks get <key>", suggested_command="audio-hooks manifest")
key = args[0]
cfg = _load_config_raw()
val = _get_dotted(cfg, key)
emit({"ok": True, "key": key, "value": val})
return 0
def cmd_set(args: List[str]) -> int:
if require_project_root() != 0:
return 1
if len(args) < 2:
return emit_error("INVALID_USAGE", "Usage: audio-hooks set <key> <value>", suggested_command="audio-hooks manifest")
key = args[0]
value = _coerce_value(args[1])
cfg = _load_config_raw()
old = _get_dotted(cfg, key)
_set_dotted(cfg, key, value)
ok, err = _save_config_raw(cfg)
if not ok:
return emit_error("CONFIG_READ_ERROR", f"Could not write config: {err}")
emit({"ok": True, "key": key, "old_value": old, "new_value": value, "restart_required": False})
return 0
# ---------------------------------------------------------------------------
# Subcommand: hooks list / enable / disable / enable-only
# ---------------------------------------------------------------------------
def _hooks_state() -> List[Dict[str, Any]]:
cfg = _load_config_raw()
enabled_cfg = cfg.get("enabled_hooks", {}) if isinstance(cfg.get("enabled_hooks"), dict) else {}
out = []
for h in HOOK_CATALOG:
v = enabled_cfg.get(h["name"])
enabled = bool(v) if isinstance(v, bool) else h["default"]
out.append({
"name": h["name"],
"enabled": enabled,
"default": h["default"],
"audio_file": h["audio"],
"description": h["description"],
})
return out
def cmd_hooks(args: List[str]) -> int:
if require_project_root() != 0:
return 1
if not args:
return emit_error("INVALID_USAGE", "Usage: audio-hooks hooks <list|enable|disable|enable-only> [name...]")
sub = args[0]
rest = args[1:]
if sub == "list":
emit({"ok": True, "hooks": _hooks_state()})
return 0
if sub in ("enable", "disable"):
if not rest:
return emit_error("INVALID_USAGE", f"Usage: audio-hooks hooks {sub} <name>")
name = rest[0]
valid = {h["name"] for h in HOOK_CATALOG}
if name not in valid:
return emit_error("UNKNOWN_HOOK_TYPE", f"Unknown hook: {name}", hint="Run `audio-hooks hooks list` to see all hooks.", suggested_command="audio-hooks hooks list")
cfg = _load_config_raw()
cfg.setdefault("enabled_hooks", {})[name] = (sub == "enable")
ok, err = _save_config_raw(cfg)
if not ok:
return emit_error("CONFIG_READ_ERROR", err)
emit({"ok": True, "hook": name, "enabled": sub == "enable"})
return 0
if sub == "enable-only":
if not rest:
return emit_error("INVALID_USAGE", "Usage: audio-hooks hooks enable-only <name1> [name2 ...]")
valid = {h["name"] for h in HOOK_CATALOG}
for n in rest:
if n not in valid:
return emit_error("UNKNOWN_HOOK_TYPE", f"Unknown hook: {n}", suggested_command="audio-hooks hooks list")
cfg = _load_config_raw()
eh = cfg.setdefault("enabled_hooks", {})
for h in HOOK_CATALOG:
eh[h["name"]] = h["name"] in rest
ok, err = _save_config_raw(cfg)
if not ok:
return emit_error("CONFIG_READ_ERROR", err)
emit({"ok": True, "enabled": list(rest), "disabled": [h["name"] for h in HOOK_CATALOG if h["name"] not in rest]})
return 0
return emit_error("INVALID_USAGE", f"Unknown hooks subcommand: {sub}")
# ---------------------------------------------------------------------------
# Subcommand: theme
# ---------------------------------------------------------------------------
def cmd_theme(args: List[str]) -> int:
if require_project_root() != 0:
return 1
if not args or args[0] == "list":
emit({"ok": True, "current": _load_config_raw().get("audio_theme", "default"), "available": ["default", "custom"]})
return 0
if args[0] == "set":
if len(args) < 2:
return emit_error("INVALID_USAGE", "Usage: audio-hooks theme set <default|custom>")
theme = args[1]
if theme not in ("default", "custom"):
return emit_error("INVALID_USAGE", f"Invalid theme: {theme}")
cfg = _load_config_raw()
cfg["audio_theme"] = theme
ok, err = _save_config_raw(cfg)
if not ok:
return emit_error("CONFIG_READ_ERROR", err)
emit({"ok": True, "theme": theme})
return 0
return emit_error("INVALID_USAGE", f"Unknown theme subcommand: {args[0]}")
# ---------------------------------------------------------------------------
# Subcommand: snooze
# ---------------------------------------------------------------------------
def cmd_snooze(args: List[str]) -> int:
if require_project_root() != 0:
return 1
arg = args[0] if args else "30m"
sf = _snooze_file()
sf.parent.mkdir(parents=True, exist_ok=True)
if arg in ("off", "resume", "cancel"):
try:
sf.unlink()
except FileNotFoundError:
pass
except OSError as e:
return emit_error("INTERNAL_ERROR", str(e))
emit({"ok": True, "active": False})
return 0
if arg == "status":
emit({"ok": True, **_snooze_status()})
return 0
secs = _parse_duration(arg)
if secs is None or secs <= 0:
return emit_error("INVALID_USAGE", f"Invalid duration: {arg}", hint="Use forms like 30m, 1h, 90s, 2d.")
until = time.time() + secs
try:
sf.write_text(str(until), encoding="utf-8")
except OSError as e:
return emit_error("INTERNAL_ERROR", str(e))
emit({
"ok": True,
"active": True,
"remaining_seconds": secs,
"until": until,
"until_iso": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(until)),
})
return 0
# ---------------------------------------------------------------------------
# Subcommand: webhook
# ---------------------------------------------------------------------------
def cmd_webhook(args: List[str]) -> int:
if require_project_root() != 0:
return 1
if not args:
cfg = _load_config_raw()
w = cfg.get("webhook_settings", {})
emit({
"ok": True,
"enabled": bool(w.get("enabled")),
"format": w.get("format", "raw"),
"url_redacted": _redact_url(w.get("url", "")),
"hook_types": w.get("hook_types", []),
})
return 0
sub = args[0]
rest = args[1:]
if sub == "set":
# Parse --url, --format, --hook-types flags
parsed: Dict[str, Any] = {}
i = 0
while i < len(rest):
tok = rest[i]
if tok == "--url" and i + 1 < len(rest):
parsed["url"] = rest[i + 1]; i += 2; continue
if tok == "--format" and i + 1 < len(rest):
parsed["format"] = rest[i + 1]; i += 2; continue
if tok == "--hook-types" and i + 1 < len(rest):
parsed["hook_types"] = [s.strip() for s in rest[i + 1].split(",") if s.strip()]
i += 2; continue
if tok == "--enabled" and i + 1 < len(rest):
parsed["enabled"] = rest[i + 1].lower() in ("true", "1", "yes")
i += 2; continue
i += 1
cfg = _load_config_raw()
w = cfg.setdefault("webhook_settings", {})
for k, v in parsed.items():
w[k] = v
if "url" in parsed and parsed["url"]:
w["enabled"] = True
ok, err = _save_config_raw(cfg)
if not ok:
return emit_error("CONFIG_READ_ERROR", err)
emit({"ok": True, "webhook_settings": {"enabled": bool(w.get("enabled")), "format": w.get("format", "raw"), "url_redacted": _redact_url(w.get("url", ""))}})
return 0
if sub == "clear":
cfg = _load_config_raw()
w = cfg.setdefault("webhook_settings", {})
w["enabled"] = False
w["url"] = ""
ok, err = _save_config_raw(cfg)
if not ok:
return emit_error("CONFIG_READ_ERROR", err)
emit({"ok": True, "enabled": False})
return 0
if sub == "test":
cfg = _load_config_raw()
w = cfg.get("webhook_settings", {})
url = w.get("url", "")
if not url:
return emit_error("INVALID_CONFIG", "No webhook URL configured.", suggested_command="audio-hooks webhook set --url ...")
try:
import urllib.request
payload = json.dumps({
"schema": "audio-hooks.webhook.v1",
"test": True,
"ts": time.time(),
"version": PROJECT_VERSION,
}).encode("utf-8")
req = urllib.request.Request(url, data=payload, headers={"Content-Type": "application/json"}, method="POST")
resp = urllib.request.urlopen(req, timeout=5)
emit({"ok": True, "status": resp.status, "url_redacted": _redact_url(url)})
return 0
except Exception as e:
return emit_error("WEBHOOK_HTTP_ERROR", str(e), url_redacted=_redact_url(url))
return emit_error("INVALID_USAGE", f"Unknown webhook subcommand: {sub}")
# ---------------------------------------------------------------------------
# Subcommand: tts / rate-limits
# ---------------------------------------------------------------------------
def _kv_flags(rest: List[str]) -> Dict[str, Any]:
out: Dict[str, Any] = {}
i = 0
while i < len(rest):
if rest[i].startswith("--") and i + 1 < len(rest):
key = rest[i][2:].replace("-", "_")
out[key] = _coerce_value(rest[i + 1])
i += 2
else:
i += 1
return out
def cmd_tts(args: List[str]) -> int:
if require_project_root() != 0:
return 1
if not args or args[0] == "set":
rest = args[1:] if args else []
flags = _kv_flags(rest)
cfg = _load_config_raw()
t = cfg.setdefault("tts_settings", {})
for k, v in flags.items():
t[k] = v
ok, err = _save_config_raw(cfg)
if not ok:
return emit_error("CONFIG_READ_ERROR", err)
emit({"ok": True, "tts_settings": t})
return 0
return emit_error("INVALID_USAGE", f"Unknown tts subcommand: {args[0]}")
def cmd_rate_limits(args: List[str]) -> int:
if require_project_root() != 0:
return 1
if not args or args[0] == "set":
rest = args[1:] if args else []
flags = _kv_flags(rest)
cfg = _load_config_raw()
r = cfg.setdefault("rate_limit_alerts", {})
for k, v in flags.items():
if k in ("five_hour_thresholds", "seven_day_thresholds") and isinstance(v, str):
v = [int(x.strip()) for x in v.split(",") if x.strip()]
r[k] = v
ok, err = _save_config_raw(cfg)
if not ok:
return emit_error("CONFIG_READ_ERROR", err)
emit({"ok": True, "rate_limit_alerts": r})
return 0
return emit_error("INVALID_USAGE", f"Unknown rate-limits subcommand: {args[0]}")
# ---------------------------------------------------------------------------
# Subcommand: test
# ---------------------------------------------------------------------------
_MOCK_STDIN: Dict[str, Dict[str, Any]] = {
"stop": {"hook_event_name": "Stop", "last_assistant_message": "Test complete.", "session_id": "test-session"},
"notification": {"hook_event_name": "Notification", "message": "Test notification", "notification_type": "permission_prompt", "session_id": "test-session"},
"permission_request": {"hook_event_name": "PermissionRequest", "tool_name": "Bash", "tool_input": {"command": "echo test"}, "session_id": "test-session"},
"permission_denied": {"hook_event_name": "PermissionDenied", "tool_name": "Bash", "reason": "auto mode classifier", "session_id": "test-session"},
"subagent_stop": {"hook_event_name": "SubagentStop", "agent_type": "Explore", "last_assistant_message": "Done.", "session_id": "test-session"},
"session_start": {"hook_event_name": "SessionStart", "source": "startup", "session_id": "test-session"},
"cwd_changed": {"hook_event_name": "CwdChanged", "new_cwd": "/tmp", "session_id": "test-session"},
"file_changed": {"hook_event_name": "FileChanged", "file_path": "/tmp/.env", "session_id": "test-session"},
"task_created": {"hook_event_name": "TaskCreated", "task_subject": "Test task", "session_id": "test-session"},
}
def _mock_for(hook_name: str) -> Dict[str, Any]:
return _MOCK_STDIN.get(hook_name, {"hook_event_name": hook_name, "session_id": "test-session"})
def _run_one_test(hook_name: str) -> Dict[str, Any]:
"""Invoke hook_runner.run_hook with a synthetic stdin payload."""
if HR is None:
return {"hook": hook_name, "ok": False, "error": "hook_runner not importable"}
start = time.time()
try:
rc = HR.run_hook(hook_name, _mock_for(hook_name))
elapsed_ms = int((time.time() - start) * 1000)
return {"hook": hook_name, "ok": rc == 0, "exit_code": rc, "duration_ms": elapsed_ms}
except Exception as e:
return {"hook": hook_name, "ok": False, "error": str(e)}
def cmd_test(args: List[str]) -> int:
if require_project_root() != 0:
return 1
if not args:
emit({"ok": False, "error": {"code": "INVALID_USAGE", "message": "Usage: audio-hooks test <hook_name|all>"}})
return 1
target = args[0]
if target == "all":
results = [_run_one_test(h["name"]) for h in HOOK_CATALOG]
passed = [r for r in results if r.get("ok")]
failed = [r for r in results if not r.get("ok")]
emit({"ok": len(failed) == 0, "passed": len(passed), "failed": failed, "total": len(results)})
return 0 if not failed else 1
valid = {h["name"] for h in HOOK_CATALOG}
if target not in valid:
return emit_error("UNKNOWN_HOOK_TYPE", f"Unknown hook: {target}", suggested_command="audio-hooks hooks list")
result = _run_one_test(target)
emit({"ok": result.get("ok", False), **result})
return 0 if result.get("ok") else 1
# ---------------------------------------------------------------------------
# Subcommand: diagnose
# ---------------------------------------------------------------------------
def _detect_audio_player() -> Dict[str, Any]:
sysname = platform.system()
import shutil as _sh
if sysname == "Windows":
return {"platform": sysname, "player": "powershell-mediaplayer", "available": bool(_sh.which("powershell.exe") or _sh.which("powershell"))}
if sysname == "Darwin":
return {"platform": sysname, "player": "afplay", "available": bool(_sh.which("afplay"))}
candidates = ["mpg123", "ffplay", "paplay", "aplay"]
found = next((c for c in candidates if _sh.which(c)), None)
return {"platform": sysname, "player": found, "available": found is not None}
def _check_settings_json() -> Dict[str, Any]:
settings_path = Path.home() / ".claude" / "settings.json"
if not settings_path.exists():
return {"path": str(settings_path), "exists": False}
try:
data = json.loads(settings_path.read_text(encoding="utf-8"))
except Exception as e:
return {"path": str(settings_path), "exists": True, "parse_error": str(e)}
return {
"path": str(settings_path),
"exists": True,
"disable_all_hooks": bool(data.get("disableAllHooks")),
"disable_skill_shell_execution": bool(data.get("disableSkillShellExecution")),
"hooks_registered": isinstance(data.get("hooks"), dict) and bool(data.get("hooks")),
}
def _check_audio_files() -> Dict[str, Any]:
if PROJECT_ROOT is None:
return {"missing": [], "present": 0}
audio_dir = PROJECT_ROOT / "audio"
missing = []
present = 0
cfg = _load_config_raw()
theme = cfg.get("audio_theme", "default")
for h in HOOK_CATALOG:
# Check both themes' file existence
default_p = audio_dir / "default" / h["audio"]
custom_p = audio_dir / "custom" / ("chime-" + h["audio"])
active = custom_p if theme == "custom" else default_p
if active.exists():
present += 1
else:
missing.append({"hook": h["name"], "expected": str(active)})
return {"missing": missing, "present": present, "expected": len(HOOK_CATALOG)}
def cmd_diagnose(_args: List[str]) -> int:
if require_project_root() != 0:
return 1
errors: List[Dict[str, Any]] = []
warnings: List[Dict[str, Any]] = []
settings = _check_settings_json()
install = _detect_install_mode()
if settings.get("disable_all_hooks"):
errors.append({
"code": "SETTINGS_DISABLE_ALL_HOOKS",
"message": "Claude Code settings.json has disableAllHooks: true; no hooks will fire.",
"hint": "Remove or set disableAllHooks: false in ~/.claude/settings.json.",
"suggested_command": "audio-hooks status",
})
# Only warn HOOKS_NOT_REGISTERED when neither install path is active.
# Plugin installs register their hooks in the plugin's own hooks/hooks.json,
# not in ~/.claude/settings.json β so an absent settings.json `hooks` key
# is normal and expected when only the plugin is installed.
if (settings.get("exists")
and not settings.get("hooks_registered")
and not install.get("plugin_install")
and not install.get("script_install")):
warnings.append({
"code": "HOOKS_NOT_REGISTERED",
"message": "No hooks block found in ~/.claude/settings.json and no plugin install detected.",
"suggested_command": "audio-hooks install --plugin",
})
audio_player = _detect_audio_player()
if not audio_player.get("available"):
errors.append({
"code": "AUDIO_PLAYER_NOT_FOUND",
"message": f"No audio player available on {audio_player.get('platform')}.",
"hint": "Install mpg123 (Linux) or ensure PowerShell is available (Windows).",
"suggested_command": "audio-hooks diagnose",
})
audio_files = _check_audio_files()
if audio_files["missing"]:
warnings.append({
"code": "AUDIO_FILE_MISSING",
"message": f"{len(audio_files['missing'])} audio files missing for the active theme.",
"hint": "Some hooks will be silent. Switch themes or restore the files.",
"suggested_command": "audio-hooks theme list",
"missing_count": len(audio_files["missing"]),
})
cfg = _load_config_raw()
if not cfg:
warnings.append({
"code": "INVALID_CONFIG",
"message": "user_preferences.json is missing or empty.",
"suggested_command": "audio-hooks manifest --schema",
})
if install.get("warning", {}).get("code") == "DUAL_INSTALL_DETECTED":
errors.append({
"code": "DUAL_INSTALL_DETECTED",
"message": install["warning"]["message"],
"hint": "Both legacy script install and plugin install fire on every event, causing duplicate audio.",
"suggested_command": "bash scripts/uninstall.sh --yes",
})
emit({
"ok": len(errors) == 0,
"version": PROJECT_VERSION,