-
-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathhook_runner.py
More file actions
2165 lines (1883 loc) Β· 85.5 KB
/
Copy pathhook_runner.py
File metadata and controls
2165 lines (1883 loc) Β· 85.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
"""
Claude Code Audio Hooks - Python Hook Runner
Cross-platform hook runner that works on Windows, macOS, and Linux.
This replaces the bash-based hooks for better Windows compatibility.
Usage:
python hook_runner.py <hook_type>
Hook types: notification, stop, pretooluse, posttooluse, posttoolusefailure,
userpromptsubmit, subagent_stop, subagent_start, precompact,
session_start, session_end, permission_request,
teammate_idle, task_completed, stop_failure, postcompact,
config_change, instructions_loaded, worktree_create,
worktree_remove, elicitation, elicitation_result
Environment Variables:
CLAUDE_HOOKS_DEBUG=1 Enable debug logging
"""
import json
import os
import shutil
import sys
import time
import subprocess
import platform
import re
from pathlib import Path
from typing import Optional, Dict, Any, List, Tuple
# Version used for auto-sync: when the installed copy in ~/.claude/hooks/
# detects a newer version in the project directory, it self-updates.
HOOK_RUNNER_VERSION = "5.1.2"
# =============================================================================
# STRUCTURED LOGGING (NDJSON)
# =============================================================================
#
# All log events are written as one JSON object per line to events.ndjson.
# Schema is versioned ("audio-hooks.v1") so downstream consumers can pin.
# Error events include a stable `code` enum, a one-sentence `hint`, and an
# optional `suggested_command` Claude Code can run to fix the issue.
#
# Storage location, in priority order:
# 1. ${CLAUDE_PLUGIN_DATA}/logs/ (plugin install)
# 2. ${CLAUDE_AUDIO_HOOKS_DATA}/logs/ (explicit override)
# 3. <temp>/claude_audio_hooks_queue/logs/ (legacy script install)
DEBUG = os.environ.get("CLAUDE_HOOKS_DEBUG", "").lower() in ("1", "true", "yes")
LOG_SCHEMA = "audio-hooks.v1"
LOG_FILE_NAME = "events.ndjson"
LOG_ROTATE_BYTES = 5 * 1024 * 1024 # 5 MB
LOG_KEEP_FILES = 3
# Stable error code enum. Add new codes here, never rename existing ones.
class ErrorCode:
AUDIO_FILE_MISSING = "AUDIO_FILE_MISSING"
AUDIO_PLAYER_NOT_FOUND = "AUDIO_PLAYER_NOT_FOUND"
AUDIO_PLAY_FAILED = "AUDIO_PLAY_FAILED"
INVALID_CONFIG = "INVALID_CONFIG"
CONFIG_READ_ERROR = "CONFIG_READ_ERROR"
WEBHOOK_HTTP_ERROR = "WEBHOOK_HTTP_ERROR"
WEBHOOK_TIMEOUT = "WEBHOOK_TIMEOUT"
NOTIFICATION_FAILED = "NOTIFICATION_FAILED"
TTS_FAILED = "TTS_FAILED"
SETTINGS_DISABLE_ALL_HOOKS = "SETTINGS_DISABLE_ALL_HOOKS"
PROJECT_DIR_NOT_FOUND = "PROJECT_DIR_NOT_FOUND"
SELF_UPDATE_FAILED = "SELF_UPDATE_FAILED"
UNKNOWN_HOOK_TYPE = "UNKNOWN_HOOK_TYPE"
INTERNAL_ERROR = "INTERNAL_ERROR"
# Hints and suggested commands for each error code. Used by log_error_event().
_ERROR_HINTS: Dict[str, Dict[str, str]] = {
ErrorCode.AUDIO_FILE_MISSING: {
"hint": "The configured audio file does not exist on disk.",
"suggested_command": "audio-hooks diagnose",
},
ErrorCode.AUDIO_PLAYER_NOT_FOUND: {
"hint": "No audio player binary found on this system.",
"suggested_command": "audio-hooks diagnose",
},
ErrorCode.AUDIO_PLAY_FAILED: {
"hint": "The audio player exited with an error.",
"suggested_command": "audio-hooks test",
},
ErrorCode.INVALID_CONFIG: {
"hint": "user_preferences.json is missing or invalid JSON.",
"suggested_command": "audio-hooks manifest --schema",
},
ErrorCode.CONFIG_READ_ERROR: {
"hint": "Could not read user_preferences.json.",
"suggested_command": "audio-hooks status",
},
ErrorCode.WEBHOOK_HTTP_ERROR: {
"hint": "Webhook endpoint returned a non-2xx response.",
"suggested_command": "audio-hooks webhook test",
},
ErrorCode.WEBHOOK_TIMEOUT: {
"hint": "Webhook request timed out.",
"suggested_command": "audio-hooks webhook test",
},
ErrorCode.NOTIFICATION_FAILED: {
"hint": "Desktop notification dispatch failed.",
"suggested_command": "audio-hooks diagnose",
},
ErrorCode.TTS_FAILED: {
"hint": "Text-to-speech engine failed or is not installed.",
"suggested_command": "audio-hooks tts set --enabled false",
},
ErrorCode.SETTINGS_DISABLE_ALL_HOOKS: {
"hint": "Claude Code settings.json has disableAllHooks: true; no hooks fire.",
"suggested_command": "audio-hooks diagnose",
},
ErrorCode.PROJECT_DIR_NOT_FOUND: {
"hint": "Could not locate the project directory.",
"suggested_command": "audio-hooks status",
},
ErrorCode.SELF_UPDATE_FAILED: {
"hint": "Auto-sync from the project directory failed.",
"suggested_command": "audio-hooks update",
},
ErrorCode.UNKNOWN_HOOK_TYPE: {
"hint": "Hook runner was invoked with an unrecognized hook type.",
"suggested_command": "audio-hooks hooks list",
},
ErrorCode.INTERNAL_ERROR: {
"hint": "An unexpected internal error occurred.",
"suggested_command": "audio-hooks logs tail",
},
}
def get_log_dir() -> Path:
"""Resolve the log directory, creating it if necessary.
Priority: CLAUDE_PLUGIN_DATA > CLAUDE_AUDIO_HOOKS_DATA > legacy temp dir.
"""
plugin_data = os.environ.get("CLAUDE_PLUGIN_DATA")
if plugin_data:
log_dir = Path(plugin_data) / "logs"
else:
explicit = os.environ.get("CLAUDE_AUDIO_HOOKS_DATA")
if explicit:
log_dir = Path(explicit) / "logs"
else:
if platform.system() == "Windows":
base = Path(os.environ.get("TEMP", os.environ.get("TMP", "C:/Windows/Temp")))
else:
base = Path("/tmp")
log_dir = base / "claude_audio_hooks_queue" / "logs"
try:
log_dir.mkdir(parents=True, exist_ok=True)
except OSError:
pass
return log_dir
def _rotate_log_if_needed(log_file: Path) -> None:
"""Rotate the log file when it exceeds LOG_ROTATE_BYTES."""
try:
if not log_file.exists():
return
if log_file.stat().st_size < LOG_ROTATE_BYTES:
return
# Shift existing rotated files: events.ndjson.2 -> .3, .1 -> .2, base -> .1
for i in range(LOG_KEEP_FILES - 1, 0, -1):
src = log_file.with_suffix(log_file.suffix + f".{i}")
dst = log_file.with_suffix(log_file.suffix + f".{i + 1}")
if src.exists():
if dst.exists():
try:
dst.unlink()
except OSError:
pass
try:
src.rename(dst)
except OSError:
pass
try:
log_file.rename(log_file.with_suffix(log_file.suffix + ".1"))
except OSError:
pass
except Exception:
pass
# Per-process session_id, set by run_hook() once stdin has been parsed.
_current_session_id: Optional[str] = None
_current_hook_type: Optional[str] = None
def _set_log_context(session_id: Optional[str], hook_type: Optional[str]) -> None:
"""Set the per-process log context once at hook entry."""
global _current_session_id, _current_hook_type
_current_session_id = session_id
_current_hook_type = hook_type
def log_event(level: str, action: str, hook: Optional[str] = None, **fields: Any) -> None:
"""Write one NDJSON event line.
Always non-blocking on errors. Never raises. Never writes to stdout/stderr.
"""
if level == "debug" and not DEBUG:
return
try:
event: Dict[str, Any] = {
"ts": time.strftime("%Y-%m-%dT%H:%M:%S", time.gmtime()) + f".{int((time.time() % 1) * 1000):03d}Z",
"schema": LOG_SCHEMA,
"level": level,
"hook": hook if hook is not None else _current_hook_type,
}
if _current_session_id:
event["session_id"] = _current_session_id
event["action"] = action
for k, v in fields.items():
if v is not None:
event[k] = v
log_file = get_log_dir() / LOG_FILE_NAME
_rotate_log_if_needed(log_file)
with open(log_file, "a", encoding="utf-8") as f:
f.write(json.dumps(event, ensure_ascii=False) + "\n")
except Exception:
pass
def log_error_event(code: str, action: str, message: str = "", hook: Optional[str] = None, **fields: Any) -> None:
"""Emit a structured error event with hint and suggested_command."""
meta = _ERROR_HINTS.get(code, {})
error_obj: Dict[str, Any] = {"code": code, "message": message}
if meta.get("hint"):
error_obj["hint"] = meta["hint"]
if meta.get("suggested_command"):
error_obj["suggested_command"] = meta["suggested_command"]
log_event("error", action, hook=hook, error=error_obj, **fields)
# ---------------------------------------------------------------------------
# Backwards-compatible wrappers
# ---------------------------------------------------------------------------
# The legacy log_debug / log_error / log_trigger functions stay so existing
# call sites in this file (and any third-party patches) keep working.
# Internally they all funnel through log_event() now, so the on-disk format is
# always NDJSON regardless of which helper was called.
def log_debug(message: str) -> None:
if DEBUG:
log_event("debug", "debug", message=message)
def log_error(message: str) -> None:
log_event("error", "legacy_error", message=message)
def log_trigger(hook_type: str, status: str, details: str = "") -> None:
"""Legacy hook-status trigger. Maps to log_event with action=hook_status."""
fields: Dict[str, Any] = {"status": status}
if details:
fields["details"] = details
log_event("info", "hook_status", hook=hook_type, **fields)
# =============================================================================
# PATH UTILITIES
# =============================================================================
def normalize_path(path_str: str) -> str:
"""Convert various path formats to the platform's native format.
Handles:
- Git Bash/MSYS2: /c/Users/... -> C:/Users/...
- WSL2: /mnt/c/Users/... -> C:/Users/...
- Cygwin: /cygdrive/c/... -> C:/...
"""
if platform.system() != "Windows":
return path_str
path_str = path_str.strip()
log_debug(f"normalize_path input: {path_str}")
# Handle WSL2 style paths: /mnt/c/... -> C:/...
if path_str.startswith("/mnt/") and len(path_str) >= 6:
drive_letter = path_str[5].upper()
if drive_letter.isalpha():
rest = path_str[6:] if len(path_str) > 6 else "/"
result = f"{drive_letter}:{rest}"
log_debug(f"normalize_path WSL2: {path_str} -> {result}")
return result
# Handle Cygwin style paths: /cygdrive/c/... -> C:/...
if path_str.startswith("/cygdrive/") and len(path_str) >= 11:
drive_letter = path_str[10].upper()
if drive_letter.isalpha():
rest = path_str[11:] if len(path_str) > 11 else "/"
result = f"{drive_letter}:{rest}"
log_debug(f"normalize_path Cygwin: {path_str} -> {result}")
return result
# Handle Git Bash/MSYS2 style paths: /d/... -> D:/...
if len(path_str) >= 2 and path_str[0] == '/' and path_str[1].isalpha():
drive_letter = path_str[1].upper()
if len(path_str) == 2:
result = f"{drive_letter}:/"
elif path_str[2] == '/':
result = f"{drive_letter}:{path_str[2:]}"
else:
# Not a drive path, return as-is
return path_str
log_debug(f"normalize_path Git Bash: {path_str} -> {result}")
return result
return path_str
def escape_powershell_string(s: str) -> str:
"""Escape a string for safe use in PowerShell double-quoted strings."""
# Escape backticks, double quotes, and dollar signs
s = s.replace('`', '``')
s = s.replace('"', '`"')
s = s.replace('$', '`$')
return s
def get_safe_temp_dir() -> Path:
"""Get a safe temporary directory that exists and is writable."""
candidates: List[Path] = []
if platform.system() == "Windows":
# Windows: prefer TEMP, then TMP, then USERPROFILE/Temp, then fallback
for env_var in ["TEMP", "TMP"]:
val = os.environ.get(env_var)
if val:
candidates.append(Path(val))
userprofile = os.environ.get("USERPROFILE")
if userprofile:
candidates.append(Path(userprofile) / "AppData" / "Local" / "Temp")
# Windows fallback
windir = os.environ.get("WINDIR", "C:/Windows")
candidates.append(Path(windir) / "Temp")
candidates.append(Path("C:/Windows/Temp"))
else:
# Unix: prefer TMPDIR, then standard locations
tmpdir = os.environ.get("TMPDIR")
if tmpdir:
candidates.append(Path(tmpdir))
candidates.extend([
Path("/tmp"),
Path("/var/tmp"),
Path.home() / ".cache" / "claude_hooks_temp",
])
# Find first existing and writable directory
for candidate in candidates:
try:
if candidate.exists() and os.access(str(candidate), os.W_OK):
log_debug(f"Using temp dir: {candidate}")
return candidate
except Exception:
continue
# Last resort: create in home directory
fallback = Path.home() / ".cache" / "claude_hooks_temp"
fallback.mkdir(parents=True, exist_ok=True)
log_debug(f"Using fallback temp dir: {fallback}")
return fallback
# =============================================================================
# AUTO-SYNC (self-update from project directory)
# =============================================================================
def check_and_self_update() -> None:
"""If running from ~/.claude/hooks/, check the project copy for a newer version.
When a newer version is found in the project directory, copy it over the
installed copy and re-execute so the user always runs the latest code after
a `git pull`. The entire function is wrapped in a try/except so it never
blocks hook execution.
"""
try:
installed_path = Path(__file__).resolve()
# Only run when executing from ~/.claude/hooks/ (not the project dir)
claude_hooks_dir = Path.home() / ".claude" / "hooks"
if not str(installed_path).startswith(str(claude_hooks_dir)):
return
# Read .project_path to find the project copy
project_path_file = claude_hooks_dir / ".project_path"
if not project_path_file.exists():
return
raw_path = project_path_file.read_text(encoding="utf-8-sig").strip()
raw_path = normalize_path(raw_path)
project_runner = Path(raw_path) / "hooks" / "hook_runner.py"
if not project_runner.exists():
return
# Extract HOOK_RUNNER_VERSION from the project copy
project_source = project_runner.read_text(encoding="utf-8")
match = re.search(r'^HOOK_RUNNER_VERSION\s*=\s*["\']([^"\']+)["\']',
project_source, re.MULTILINE)
if not match:
return
project_version = match.group(1)
# Simple tuple comparison: "4.2.2" -> (4, 2, 2)
def ver_tuple(v: str):
return tuple(int(x) for x in v.split("."))
if ver_tuple(project_version) <= ver_tuple(HOOK_RUNNER_VERSION):
return
# Project copy is newer β update ourselves
shutil.copy2(str(project_runner), str(installed_path))
# Re-execute with the same arguments so the new code runs
os.execv(sys.executable, [sys.executable, str(installed_path)] + sys.argv[1:])
except Exception:
# Never block hook execution
pass
# =============================================================================
# CONFIGURATION
# =============================================================================
def get_project_dir() -> Path:
"""Determine the project directory."""
script_dir = Path(__file__).resolve().parent
log_debug(f"Script dir: {script_dir}")
# Strategy 1: Read from .project_path file
project_path_file = script_dir / ".project_path"
if project_path_file.exists():
try:
recorded_path = project_path_file.read_text(encoding="utf-8-sig").strip() # utf-8-sig handles BOM
log_debug(f"Read .project_path: {recorded_path}")
# Normalize path format for Windows compatibility
recorded_path = normalize_path(recorded_path)
recorded_path_obj = Path(recorded_path)
if recorded_path_obj.exists() and (recorded_path_obj / "config" / "user_preferences.json").exists():
log_debug(f"Using project dir from .project_path: {recorded_path_obj}")
return recorded_path_obj
else:
log_debug(f"Project path invalid or config missing: {recorded_path_obj}")
except Exception as e:
log_error(f"Failed to read .project_path: {e}")
# Strategy 2: Check if we're in the project structure
candidate = script_dir.parent
if (candidate / "config" / "user_preferences.json").exists():
log_debug(f"Using parent dir as project dir: {candidate}")
return candidate
# Strategy 3: Search common locations
home = Path.home()
common_locations = [
home / "claude-code-audio-hooks",
home / "projects" / "claude-code-audio-hooks",
home / "Documents" / "claude-code-audio-hooks",
home / "repos" / "claude-code-audio-hooks",
]
for loc in common_locations:
if loc.exists() and (loc / "config" / "user_preferences.json").exists():
log_debug(f"Found project in common location: {loc}")
return loc
# Fallback
log_debug(f"Using fallback project dir: {candidate}")
return candidate
# Initialize paths
PROJECT_DIR = get_project_dir()
AUDIO_DIR = PROJECT_DIR / "audio"
def _is_running_from_plugin() -> bool:
"""True if this script is being invoked from a plugin install context.
Two signals:
1. CLAUDE_PLUGIN_DATA is set (hook fire context β Claude Code injects it).
2. This file lives under <plugin_root>/hooks/ where
<plugin_root>/.claude-plugin/plugin.json exists.
"""
if os.environ.get("CLAUDE_PLUGIN_DATA"):
return True
try:
here = Path(__file__).resolve()
plugin_root = here.parent.parent # hooks/hook_runner.py -> plugin root
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.
Per Claude Code docs, the data dir is at ~/.claude/plugins/data/{id}/
where {id} is the plugin name with non-[a-zA-Z0-9_-] chars replaced by -.
For audio-hooks@chanmeng-audio-hooks the id is
'audio-hooks-chanmeng-audio-hooks'.
Used when the binary is invoked from a Bash tool call via the plugin's
bin/ PATH (which doesn't inherit CLAUDE_PLUGIN_DATA from the hook fire
context).
"""
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
# No data dir yet β return canonical so it can be created on first write
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_DIR / "config" / "default_preferences.json"
if template.exists():
import shutil as _sh
_sh.copy2(str(template), str(target))
except OSError:
pass
def _resolve_config_file() -> Path:
"""Resolve user_preferences.json path.
Resolution order:
1. CLAUDE_PLUGIN_DATA env var (set by Claude Code in hook fire context)
2. Plugin context detected from script path (CLI invocation via plugin bin/)
3. CLAUDE_AUDIO_HOOKS_DATA explicit override
4. Legacy <project_dir>/config/user_preferences.json (script install)
For plugin contexts, the file is auto-initialized 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_DIR / "config" / "user_preferences.json"
CONFIG_FILE = _resolve_config_file()
def _resolve_queue_dir() -> Path:
"""Resolve the runtime state directory.
Plugin installs set CLAUDE_PLUGIN_DATA, which is persistent across plugin
updates. CLAUDE_AUDIO_HOOKS_DATA is an explicit override for any install
type. Otherwise fall back to the legacy temp dir.
"""
plugin_data = os.environ.get("CLAUDE_PLUGIN_DATA")
if plugin_data:
return Path(plugin_data) / "queue"
explicit = os.environ.get("CLAUDE_AUDIO_HOOKS_DATA")
if explicit:
return Path(explicit) / "queue"
return get_safe_temp_dir() / "claude_audio_hooks_queue"
QUEUE_DIR = _resolve_queue_dir()
LOCK_FILE = QUEUE_DIR / "audio.lock"
_queue_dir_ensured = False
def ensure_queue_dir() -> None:
"""Ensure queue directory exists (lazy, called on first use)."""
global _queue_dir_ensured
if not _queue_dir_ensured:
QUEUE_DIR.mkdir(parents=True, exist_ok=True)
_queue_dir_ensured = True
# Default audio files for each hook type
DEFAULT_AUDIO_FILES = {
"notification": "notification-urgent.mp3",
"stop": "task-complete.mp3",
"pretooluse": "task-starting.mp3",
"posttooluse": "task-progress.mp3",
"userpromptsubmit": "prompt-received.mp3",
"subagent_stop": "subagent-complete.mp3",
"precompact": "notification-info.mp3",
"session_start": "session-start.mp3",
"session_end": "session-end.mp3",
"permission_request": "permission-request.mp3",
"posttoolusefailure": "tool-failed.mp3",
"subagent_start": "subagent-start.mp3",
"teammate_idle": "teammate-idle.mp3",
"task_completed": "team-task-done.mp3",
"stop_failure": "stop-failure.mp3",
"postcompact": "post-compact.mp3",
"config_change": "config-change.mp3",
"instructions_loaded": "instructions-loaded.mp3",
"worktree_create": "worktree-create.mp3",
"worktree_remove": "worktree-remove.mp3",
"elicitation": "elicitation.mp3",
"elicitation_result": "elicitation-result.mp3",
# v5.0 hooks (dedicated audio shipped in v5.0.1, generated via ElevenLabs)
"permission_denied": "permission-denied.mp3",
"cwd_changed": "cwd-changed.mp3",
"file_changed": "file-changed.mp3",
"task_created": "task-created.mp3",
}
# =============================================================================
# CONFIGURATION FUNCTIONS
# =============================================================================
_config_cache: Optional[Dict[str, Any]] = None
def _apply_plugin_option_overlay(config: Dict[str, Any]) -> Dict[str, Any]:
"""Overlay CLAUDE_PLUGIN_OPTION_* env vars onto the loaded config (v5.0).
The plugin manifest declares userConfig keys (audio_theme, webhook_url,
webhook_format, tts_enabled). Claude Code exposes them to the hook
runner as CLAUDE_PLUGIN_OPTION_<KEY> environment variables. This overlay
lets Claude Code populate plugin config at install time without writing
to user_preferences.json directly.
Env vars are case-sensitive lowercase per the Claude Code docs.
Empty string means "user did not set this β preserve existing value".
"""
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
# Walk into the config and set the dotted key
parts = dotted_key.split(".")
cur: Dict[str, Any] = config
for p in parts[:-1]:
if not isinstance(cur.get(p), dict):
cur[p] = {}
cur = cur[p]
cur[parts[-1]] = value
# Auto-enable webhook if a URL was provided via plugin options
if env_var == "CLAUDE_PLUGIN_OPTION_WEBHOOK_URL" and value:
config.setdefault("webhook_settings", {})["enabled"] = True
return config
def load_config() -> Dict[str, Any]:
"""Load configuration from user_preferences.json (cached per invocation)."""
global _config_cache
if _config_cache is not None:
return _config_cache
if not CONFIG_FILE.exists():
log_debug(f"Config file not found: {CONFIG_FILE}")
_config_cache = _apply_plugin_option_overlay({})
return _config_cache
try:
config = json.loads(CONFIG_FILE.read_text(encoding="utf-8"))
log_debug(f"Loaded config from {CONFIG_FILE}")
_config_cache = _apply_plugin_option_overlay(config)
return _config_cache
except json.JSONDecodeError as e:
log_error(f"Invalid JSON in config file: {e}")
_config_cache = _apply_plugin_option_overlay({})
return _config_cache
except PermissionError as e:
log_error(f"Permission denied reading config: {e}")
_config_cache = _apply_plugin_option_overlay({})
return _config_cache
except OSError as e:
log_error(f"OS error reading config: {e}")
_config_cache = _apply_plugin_option_overlay({})
return _config_cache
def is_hook_enabled(hook_type: str) -> bool:
"""Check if a hook is enabled in configuration."""
config = load_config()
# Default enabled hooks (v5.0 adds permission_denied + task_created)
default_enabled = {"notification", "stop", "subagent_stop", "permission_request",
"permission_denied", "task_created"}
enabled_hooks = config.get("enabled_hooks", {})
# Check if explicitly set, otherwise use default
if hook_type in enabled_hooks:
result = enabled_hooks[hook_type] is True
log_debug(f"Hook {hook_type} explicitly set to {result}")
return result
result = hook_type in default_enabled
log_debug(f"Hook {hook_type} using default: {result}")
return result
def is_snoozed() -> bool:
"""Check if hooks are temporarily snoozed via marker file."""
ensure_queue_dir()
snooze_file = QUEUE_DIR / "snooze_until"
if not snooze_file.exists():
return False
try:
snooze_until = float(snooze_file.read_text(encoding="utf-8").strip())
if time.time() < snooze_until:
remaining = snooze_until - time.time()
log_debug(f"Snoozed: {remaining:.0f}s remaining")
return True
else:
log_debug("Snooze expired")
return False
except (ValueError, OSError) as e:
log_debug(f"Error reading snooze file: {e}")
return False
# =============================================================================
# SYNTHETIC EVENT VARIANTS (v5.0 β native matcher routing)
# =============================================================================
#
# Claude Code's matcher engine fires hooks per source/notification_type/error
# subtype. Plugin hooks/hooks.json registers a separate handler per matcher
# value, each invoking hook_runner.py with a synthetic event name like
# "session_start_resume" or "stop_failure_rate_limit". The runner resolves
# the synthetic name to the canonical hook plus an audio file override and
# logs the variant. Legacy installs that still register one wildcard handler
# per event keep working unchanged because the canonical hook names are also
# accepted directly.
SYNTHETIC_EVENT_MAP: Dict[str, Tuple[str, Optional[str]]] = {
# session_start subtypes (matcher: source)
"session_start_startup": ("session_start", None),
"session_start_resume": ("session_start", None),
"session_start_clear": ("session_start", None),
"session_start_compact": ("session_start", "post-compact.mp3"),
# session_end subtypes (matcher: source)
"session_end_clear": ("session_end", None),
"session_end_resume": ("session_end", None),
"session_end_logout": ("session_end", None),
"session_end_prompt_input_exit": ("session_end", None),
# stop_failure subtypes (matcher: error_type)
"stop_failure_rate_limit": ("stop_failure", "notification-urgent.mp3"),
"stop_failure_authentication_failed": ("stop_failure", "notification-urgent.mp3"),
"stop_failure_billing_error": ("stop_failure", "tool-failed.mp3"),
"stop_failure_invalid_request": ("stop_failure", "tool-failed.mp3"),
"stop_failure_server_error": ("stop_failure", "tool-failed.mp3"),
"stop_failure_max_output_tokens": ("stop_failure", "tool-failed.mp3"),
"stop_failure_unknown": ("stop_failure", None),
"stop_failure_other": ("stop_failure", None),
# notification subtypes (matcher: notification_type)
"notification_permission_prompt": ("notification", "permission-request.mp3"),
"notification_idle_prompt": ("notification", "notification-info.mp3"),
"notification_auth_success": ("notification", "session-start.mp3"),
"notification_elicitation_dialog": ("notification", "elicitation.mp3"),
# precompact / postcompact subtypes (matcher: trigger)
"precompact_manual": ("precompact", None),
"precompact_auto": ("precompact", None),
"postcompact_manual": ("postcompact", None),
"postcompact_auto": ("postcompact", None),
}
def _resolve_synthetic_event(raw_arg: str) -> Tuple[str, Optional[str], Optional[str]]:
"""Map a synthetic event name to (canonical_hook, audio_override, variant_label)."""
entry = SYNTHETIC_EVENT_MAP.get(raw_arg)
if entry is None:
return raw_arg, None, None
canonical, audio = entry
return canonical, audio, raw_arg
# Module-level state set by main() before run_hook() is called.
_current_audio_override: Optional[str] = None
_current_synthetic_variant: Optional[str] = None
CUSTOM_AUDIO_FILES = {
"notification": "chime-notification-urgent.mp3",
"stop": "chime-task-complete.mp3",
"pretooluse": "chime-task-starting.mp3",
"posttooluse": "chime-task-progress.mp3",
"userpromptsubmit": "chime-prompt-received.mp3",
"subagent_stop": "chime-subagent-complete.mp3",
"precompact": "chime-notification-info.mp3",
"session_start": "chime-session-start.mp3",
"session_end": "chime-session-end.mp3",
"permission_request": "chime-permission-request.mp3",
"posttoolusefailure": "chime-tool-failed.mp3",
"subagent_start": "chime-subagent-start.mp3",
"teammate_idle": "chime-teammate-idle.mp3",
"task_completed": "chime-team-task-done.mp3",
"stop_failure": "chime-stop-failure.mp3",
"postcompact": "chime-post-compact.mp3",
"config_change": "chime-config-change.mp3",
"instructions_loaded": "chime-instructions-loaded.mp3",
"worktree_create": "chime-worktree-create.mp3",
"worktree_remove": "chime-worktree-remove.mp3",
"elicitation": "chime-elicitation.mp3",
"elicitation_result": "chime-elicitation-result.mp3",
# v5.0 hooks (dedicated chimes shipped in v5.0.1, generated via ElevenLabs)
"permission_denied": "chime-permission-denied.mp3",
"cwd_changed": "chime-cwd-changed.mp3",
"file_changed": "chime-file-changed.mp3",
"task_created": "chime-task-created.mp3",
}
def get_audio_file(hook_type: str) -> Optional[Path]:
"""Get the audio file path for a hook type.
Resolution order:
0. Synthetic-variant audio override (v5.0 native matchers)
1. Per-hook override in audio_files config (only if user customized it)
2. audio_theme setting ("default" or "custom")
3. Fallback to audio/default/
"""
config = load_config()
theme = config.get("audio_theme", "default")
# 0. v5.0 synthetic variant override (native matcher routing)
if _current_audio_override:
override_name = _current_audio_override
if theme == "custom":
candidates = [
AUDIO_DIR / "custom" / ("chime-" + override_name),
AUDIO_DIR / "default" / override_name,
]
else:
candidates = [
AUDIO_DIR / "default" / override_name,
AUDIO_DIR / "custom" / ("chime-" + override_name),
]
for cand in candidates:
if cand.exists():
log_event("debug", "audio_override_resolved",
variant=_current_synthetic_variant,
override=override_name,
path=str(cand))
return cand
default_file = DEFAULT_AUDIO_FILES.get(hook_type, "notification-info.mp3")
# 1. Check per-hook override β only if it differs from the default mapping
# Paths like "default/<filename>" match the default template and should
# not override the audio_theme setting.
audio_files = config.get("audio_files", {})
default_pattern = f"default/{default_file}"
if hook_type in audio_files and audio_files[hook_type] != default_pattern:
override_path = AUDIO_DIR / audio_files[hook_type]
if override_path.exists():
log_debug(f"Audio file for {hook_type} (override): {override_path}")
return override_path
# 2. Use audio_theme setting
if theme == "custom":
custom_file = CUSTOM_AUDIO_FILES.get(hook_type, default_file)
theme_path = AUDIO_DIR / "custom" / custom_file
else:
theme_path = AUDIO_DIR / "default" / default_file
if theme_path.exists():
log_debug(f"Audio file for {hook_type} (theme={theme}): {theme_path}")
return theme_path
# 3. Fallback to default
fallback_path = AUDIO_DIR / "default" / default_file
if fallback_path.exists():
log_debug(f"Using fallback audio for {hook_type}: {fallback_path}")
return fallback_path
log_debug(f"No audio file found for {hook_type}")
return None
def get_debounce_ms() -> int:
"""Get debounce time in milliseconds."""
config = load_config()
playback_settings = config.get("playback_settings", {})
return playback_settings.get("debounce_ms", 500)
# =============================================================================
# DEBOUNCE SYSTEM
# =============================================================================
def should_debounce(hook_type: str) -> bool:
"""Check if we should skip this notification due to debounce."""
ensure_queue_dir()
debounce_file = QUEUE_DIR / f"{hook_type}_last_played"
debounce_sec = get_debounce_ms() / 1000.0
current_time = time.time()
if debounce_file.exists():
try:
last_time = float(debounce_file.read_text(encoding="utf-8").strip())
if current_time - last_time < debounce_sec:
log_debug(f"Debouncing {hook_type}: {current_time - last_time:.2f}s < {debounce_sec}s")
return True
except (ValueError, OSError) as e:
log_debug(f"Error reading debounce file: {e}")
# Update debounce timestamp
try:
debounce_file.write_text(str(current_time), encoding="utf-8")
except OSError as e:
log_error(f"Failed to write debounce file: {e}")
return False
def should_filter(hook_type: str, stdin_data: dict, config: Dict[str, Any]) -> bool:
"""Check user-defined filters. Returns True if hook should be skipped.
Filters are per-hook regex patterns matched against stdin JSON fields.
A field ending with '_exclude' inverts the match (skip if pattern matches).
Otherwise, skip if the pattern does NOT match the field value.
"""
filters = config.get("filters", {}).get(hook_type, {})
if not filters:
return False
for field, pattern in filters.items():
if not isinstance(pattern, str) or not pattern:
continue
if field.startswith("_"):
continue # skip comment keys
try:
if field.endswith("_exclude"):
real_field = field[:-8]
value = str(stdin_data.get(real_field, ""))
if value and re.search(pattern, value):
log_debug(f"Filter: {hook_type} excluded by {real_field} matching '{pattern}'")
return True
else:
value = str(stdin_data.get(field, ""))
if value and not re.search(pattern, value):
log_debug(f"Filter: {hook_type} skipped β {field}='{value}' doesn't match '{pattern}'")
return True
except re.error as e:
log_debug(f"Filter regex error for {field}: {e}")
return False
# =============================================================================
# AUDIO PLAYBACK FUNCTIONS
# =============================================================================
def play_audio_windows(audio_file: Path) -> bool:
"""Play audio on Windows using multiple fallback methods."""
# Escape path for PowerShell
win_path = str(audio_file).replace("\\", "/")
win_path_escaped = escape_powershell_string(win_path)
log_debug(f"Windows audio playback: {win_path}")
# Method 1: Direct PowerShell command with MediaPlayer.
# MediaPlayer.Open() is async: we poll NaturalDuration.HasTimeSpan with a
# short ceiling, then sleep for the real clip length + a tail buffer so
# Stop()/Close() don't truncate playback (issue #14). Fallback to a