Repository navigation
Expand file tree
/
Copy pathcli.py
More file actions
executable file
·2005 lines (1837 loc) · 82.9 KB
/
Copy pathcli.py
File metadata and controls
executable file
·2005 lines (1837 loc) · 82.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Claudio Symphony — control CLI.
Ambient music that sonifies Claude Code, Codex, and Gemini CLI hook events.
Commands below tune what you hear, where it plays, and how to capture it.
Quick on/off
off Silence everything (hooks short-circuit, kills drone + afplay)
on Restore enabled state (auto-restarts drone if preset has one)
toggle Flip between on and off
Setup
install [agent...] Add hooks (auto-detect; claude/codex/gemini/all)
uninstall [agent...] Remove Claudio hooks without touching others
status Show install + drone + preset state, hooks, sessions, songs, quant
doctor [--fix] Preflight check (python/numpy/player/samples/hooks); --fix renders if needed
start Start the drone daemon for the active preset (no-op if no drone)
stop Stop the drone process and kill afplay
drone [on|off|status] Drone bed — always follows the live root note (~½s retune)
drone follow on|off Drone also walks the chord progression's roots (off = A pedal)
regen [preset] Re-render samples for a preset (active if unspecified)
reset [--yes|-y] Full reset to shipped defaults; clears songs/quant/pins/rules/sessions
Presets
preset list Available presets (* marks active)
preset current Print the active preset name
preset use <name>|default Switch global default preset (live: stops old drone, starts new)
preset reset [name] Restore a preset.json from its preset.default.json
audition Hear every preset, optionally pick one (safe anytime)
Per-session routing
sessions List active sessions from the last 4h (presets + cwd)
session list Same as `sessions`
session pin <id|idx> <preset> Pin one session to a specific preset
session unpin <id|idx> Remove a session's preset pin
session song <id|idx> <name|off> Pin a song to one session (overrides preset)
session scale <id|idx> <name|off> Pin a scale to one session
here <preset> Add a cwd rule for the current directory → preset
Directory rules (routing by cwd, optionally time/idle gated)
rule list Show all cwd-pattern → preset rules
rule add <pattern> <preset> Add or replace a rule (glob or path-prefix)
rule add <pattern> <preset> --time HH:MM-HH:MM Time-of-day rule (apply only in window)
rule add <pattern> <preset> --idle-after <secs> Idle-only rule (apply after N secs idle)
rule rm <pattern> Remove all rules matching pattern (alias: rules)
Live tuning
volume <0..1> Master gain
drone-volume <0..1> Drone gain (apply requires drone restart)
voice <name> gain <0..1> Per-voice gain
voice <name> mioi <seconds> Per-voice minimum-interval rate-limit
voice <name> reverb <wet> [decay] [bright]|off Per-voice reverb (regenerates that voice)
voice <name> delay <ms> [fb] [count]|off Per-voice delay/echo (live, no regen)
voice <name> fx Show this voice's reverb + delay (alias: show)
voice <name> play Preview one random sample from this voice
test [voice] Walk all events of the active preset (or only those on voice)
demo 60-second showcase of the active preset with musical pacing
Event mapping
map <event>[:<tool>] <voice|none> Map event[/tool] to a voice (none/-/null/silent = silent)
mute <event>[:<tool>] Set an event/tool mapping to silent
unmute <event>[:<tool>] [voice] Restore a mapping (defaults to first voice)
event show Show current per-event effects (alias: list, ls)
event delay <Event> <ms> [fb] [count] Per-event delay/echo (40-2000ms, 0..0.85 fb, 0..8 count)
event delay <Event> off Remove an event's delay
Key, scales & chords
scale list Available scales (* marks active)
scale use <name> Set global scale override (or just `scale <name>`)
scale off Clear global scale override (off/stop/disable/clear)
scale show Print active override + session pins (show/current/status)
root <note|±semis|off> Live-transpose the key off A (e.g. `root C`, `root -2`, `root off`)
chords [pop|list|off|A E F#m D] Cycle the room through a chord progression (`chords every 8` sets pace)
preset reverb <0..2> Set active preset reverb_scale multiplier and regenerate
MIDI songs (melody source for events)
song list List imported songs (* = global default)
song import <file.mid> [name] Import a MIDI file (auto-detects lead channel)
song import-dir <folder> Import every *.mid in a folder
song use <name> Set as global default (events cycle through notes)
song off Clear global default → Markov picker (off/stop/disable)
song current Show position + channel + preset/session pins (current/status/show)
song reset [name] Restart a song's pointer (default: global song)
song channel <name> <lead|all|N> Pick which MIDI channel drives melody (lead = auto-detect)
song info <name> Show channel summary + detected lead
preset song <preset> <name|off> Per-preset default song (overrides global)
Quantization
quant on|off|toggle Enable/disable master quantization
quant status Show current quant state (status/show)
tempo <bpm> Set master quantization tempo
grid <subdivision> Beats per cell (0.25=16th, 0.5=8th, 1=quarter, half=2.0)
Jukebox — perform a MIDI file through the active preset (easter egg)
play list Songs you can perform (alias: jukebox)
play <name> [--preset X] [--tempo 1.0] [--loop] [--map ch=Event,...]
Perform a MIDI now; each channel → event type → its voice
play stop Stop the current performance (stop/halt)
play status Show JSON status of current playback
Session replay — re-run a captured session as music
replay list Captured sessions with event counts + density (alias: session-replay)
replay <id|latest> [--preset X] [--tempo 1] [--loop] [--render]
Replay one session; --render captures it to WAV
replay stop Stop the current replay (stop/halt)
replay export <id|latest> [label] Export a session as a tiny shareable score.json
Record & share
record [seconds] [--drone] Record a clip of your session (default 30s, max 300s)
--drone bakes in a faded drone bed (off by default)
record stop Finish the current recording now and save (stop/end/finish)
record status Show recording state + saved clips (status/show)
record list List saved clips in recordings/ as .wav + .m4a (alias: rec)
Control surfaces
web [--port N] [--no-open] Open the browser control panel (default port 8788; alias: ui)
tune Open the curses TUI for live parameter editing
status-line Print one-line live state, for tmux/etc. (alias: statusline)
Support
coffee Show on-chain tip addresses (alias: tip, donate)
"""
import os, sys, json, time, fnmatch, shlex, shutil, subprocess
from pathlib import Path
HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE))
import song as song_mod # noqa: E402
import audio # noqa: E402 (cross-platform playback + process helpers)
import midiplay as midiplay_mod # noqa: E402
import timeline as timeline_mod # noqa: E402
import hook_events # noqa: E402
PRESETS = HERE / "presets"
STATE = HERE / "state"
LOGS = HERE / "logs"
CLAUDE_SETTINGS = Path.home() / ".claude" / "settings.json"
CODEX_HOOKS = Path.home() / ".codex" / "hooks.json"
GEMINI_SETTINGS = Path.home() / ".gemini" / "settings.json"
CONFIG = HERE / "config.json"
SESSIONS_FILE = STATE / "sessions.json"
RULES_FILE = STATE / "rules.json"
EVENT_PATH = str(HERE / "event.py")
DRONE_PATH = str(HERE / "drone.py")
TUNE_PATH = str(HERE / "tune.py")
PID_FILE = STATE / "drone.pid"
MARKER = "__claudio_symphony__"
GEMINI_MARKER = "claudio-symphony"
SUPPORTED_RUNTIMES = ("claude", "codex", "gemini")
RUNTIME_LABELS = {
"claude": "Claude Code",
"codex": "Codex",
"gemini": "Gemini CLI",
}
RUNTIME_EXECUTABLES = {"claude": "claude", "codex": "codex", "gemini": "gemini"}
RUNTIME_EVENTS = {
"claude": hook_events.CLAUDE_EVENTS,
"codex": hook_events.CODEX_EVENTS,
"gemini": hook_events.GEMINI_EVENTS,
}
# ---------- json helpers ----------
def load_json(p, default):
try: return json.loads(p.read_text()) if p.exists() else default
except Exception: return default
def save_json(p, d):
tmp = p.with_suffix(p.suffix + ".tmp")
tmp.write_text(json.dumps(d, indent=2) + "\n")
tmp.rename(p)
import event as event_mod # noqa: E402 (owns DEFAULT_CONFIG so hooks/CLI/web can't drift)
DEFAULT_PRESET = event_mod.DEFAULT_PRESET
DEFAULT_CONFIG = event_mod.DEFAULT_CONFIG
def load_config():
cfg = load_json(CONFIG, None)
return cfg if isinstance(cfg, dict) else json.loads(json.dumps(DEFAULT_CONFIG))
def save_config(d): save_json(CONFIG, d)
def active_preset_name(): return load_config().get("preset", DEFAULT_PRESET)
def list_preset_names():
if not PRESETS.exists(): return []
return sorted(d.name for d in PRESETS.iterdir() if (d / "preset.json").exists())
def load_preset(name):
p = PRESETS / name / "preset.json"
return load_json(p, None) if p.exists() else None
def save_preset(name, d): save_json(PRESETS / name / "preset.json", d)
# ---------- multi-agent hook install ----------
def runtime_settings_path(runtime):
return {
"claude": CLAUDE_SETTINGS,
"codex": CODEX_HOOKS,
"gemini": GEMINI_SETTINGS,
}[runtime]
def load_settings(path):
if path.exists():
return json.loads(path.read_text())
return {}
def save_settings(path, data):
"""Preserve the existing file and atomically write one agent config."""
path.parent.mkdir(parents=True, exist_ok=True)
if path.exists():
backups = path.parent / "backups"
backups.mkdir(exist_ok=True)
ts = time.strftime("%Y%m%d-%H%M%S") + f"-{time.time_ns() % 1_000_000_000:09d}"
(backups / f"{path.name}.claudio-{ts}").write_bytes(path.read_bytes())
tmp = path.with_suffix(path.suffix + ".tmp")
tmp.write_text(json.dumps(data, indent=2) + "\n")
if path.exists():
os.chmod(tmp, path.stat().st_mode & 0o777)
tmp.replace(path)
def hook_command(runtime):
argv = [sys.executable, EVENT_PATH, "--runtime", runtime]
if os.name == "nt":
return subprocess.list2cmdline(argv)
return " ".join(shlex.quote(part) for part in argv)
def handler_is_claudio(handler, runtime):
if not isinstance(handler, dict):
return False
if runtime == "claude" and handler.get(MARKER): # legacy/manual Claude hook
return True
if runtime == "gemini" and handler.get("name") == GEMINI_MARKER:
return True
command = handler.get("command", "")
return (isinstance(command, str)
and f"--runtime {runtime}" in command
and "event.py" in command)
def block_has_claudio(block, runtime):
return (isinstance(block, dict)
and any(handler_is_claudio(h, runtime)
for h in block.get("hooks", [])))
def hook_block_for(runtime):
handler = {
"type": "command",
"command": hook_command(runtime),
}
if runtime == "claude":
# Claude supports true asynchronous side-effect hooks.
handler.update({"async": True, "timeout": 1, MARKER: True})
return {"matcher": "*", "hooks": [handler]}
if runtime == "codex":
# Codex timeouts are seconds and async command hooks are not yet
# supported. event.py detaches playback before this process exits.
handler["timeout"] = 1
if os.name == "nt":
handler["commandWindows"] = hook_command(runtime)
return {"hooks": [handler]}
# Gemini CLI timeouts are milliseconds; a name gives us a schema-supported
# marker for safe uninstall without custom fields.
handler.update({
"name": GEMINI_MARKER,
"description": "Play Claudio Symphony lifecycle audio",
"timeout": 1000,
})
return {"hooks": [handler]}
def installed_hook_events(runtime):
path = runtime_settings_path(runtime)
try:
data = load_settings(path)
except Exception:
return []
return sorted(
event for event, blocks in (data.get("hooks", {}) or {}).items()
if isinstance(blocks, list)
and any(block_has_claudio(block, runtime) for block in blocks)
)
def install_runtime(runtime):
path = runtime_settings_path(runtime)
data = load_settings(path)
hooks = data.setdefault("hooks", {})
if not isinstance(hooks, dict):
raise ValueError(f"{path}: hooks must be an object")
added = []
for event in RUNTIME_EVENTS[runtime]:
blocks = hooks.get(event, [])
if not isinstance(blocks, list):
raise ValueError(f"{path}: hooks.{event} must be an array")
if any(block_has_claudio(block, runtime) for block in blocks):
continue
blocks.append(hook_block_for(runtime))
hooks[event] = blocks
added.append(event)
save_settings(path, data)
return path, added
def uninstall_runtime(runtime):
path = runtime_settings_path(runtime)
if not path.exists():
return path, []
data = load_settings(path)
hooks = data.get("hooks", {})
if not isinstance(hooks, dict):
raise ValueError(f"{path}: hooks must be an object")
removed = []
for event in list(hooks):
blocks = hooks[event]
if not isinstance(blocks, list):
continue
kept_blocks = []
for block in blocks:
if not isinstance(block, dict):
kept_blocks.append(block)
continue
old_handlers = block.get("hooks", [])
new_handlers = [h for h in old_handlers
if not handler_is_claudio(h, runtime)]
if len(new_handlers) != len(old_handlers):
removed.append(event)
if new_handlers:
updated = dict(block)
updated["hooks"] = new_handlers
kept_blocks.append(updated)
else:
kept_blocks.append(block)
if kept_blocks:
hooks[event] = kept_blocks
else:
del hooks[event]
if not hooks:
data.pop("hooks", None)
if removed:
save_settings(path, data)
return path, sorted(set(removed))
def detected_runtimes():
found = []
for runtime in SUPPORTED_RUNTIMES:
path = runtime_settings_path(runtime)
if path.parent.exists() or shutil.which(RUNTIME_EXECUTABLES[runtime]):
found.append(runtime)
return found
def requested_runtimes(args, *, uninstall=False):
names = [arg[2:] if arg.startswith("--") else arg for arg in args]
if names and "all" in names:
return list(SUPPORTED_RUNTIMES)
if names:
unknown = [name for name in names if name not in SUPPORTED_RUNTIMES]
if unknown:
print(f"unknown agent: {', '.join(unknown)}")
print("usage: claudio install [claude|codex|gemini|all] ...")
return []
return list(dict.fromkeys(names))
if uninstall:
return [runtime for runtime in SUPPORTED_RUNTIMES
if runtime_settings_path(runtime).exists()]
# Preserve the old zero-argument behavior when nothing can be detected,
# while installing every agent that is actually present on mixed setups.
return detected_runtimes() or ["claude"]
def cmd_install(args):
runtimes = requested_runtimes(args)
if not runtimes:
return
installed_codex = False
for runtime in runtimes:
try:
path, added = install_runtime(runtime)
except Exception as exc:
print(f"✗ {RUNTIME_LABELS[runtime]}: {exc}")
continue
installed_codex = installed_codex or runtime == "codex"
detail = f"{len(added)} events" if added else "already installed"
print(f"✓ {RUNTIME_LABELS[runtime]}: {detail} — {path}")
print("\nStart a new agent session to load hook changes; sound settings stay live.")
if installed_codex:
print("Codex: open /hooks once and trust the Claudio hook definitions.")
def cmd_uninstall(args):
runtimes = requested_runtimes(args, uninstall=True)
if not runtimes:
print("no supported agent settings found")
return
for runtime in runtimes:
try:
path, removed = uninstall_runtime(runtime)
except Exception as exc:
print(f"✗ {RUNTIME_LABELS[runtime]}: {exc}")
continue
detail = f"{len(removed)} events" if removed else "not installed"
print(f"✓ {RUNTIME_LABELS[runtime]}: {detail} — {path}")
# ---------- drone control ----------
def drone_pid():
try:
if not PID_FILE.exists(): return None
pid = int(PID_FILE.read_text().strip())
return pid if audio.pid_alive(pid) else None
except Exception:
return None
def cmd_start():
pid = drone_pid()
if pid: print(f"drone already running pid={pid}"); return
name = active_preset_name()
preset = load_preset(name)
if preset is None: print(f"active preset '{name}' not found"); return
if not preset.get("drone"):
print(f"preset '{name}' has no continuous drone — nothing to start")
return
LOGS.mkdir(exist_ok=True)
out = LOGS / "drone.out"
audio.spawn_python(DRONE_PATH, detached=True, log_file=str(out))
time.sleep(0.4)
pid = drone_pid()
print(f"drone started pid={pid}" if pid else f"launch attempted; check {LOGS / 'drone.log'}")
def cmd_drone(args):
"""Drone bed control. The drone always follows the live root note (mic-jam
included, retuning in ~½s); `follow on` makes it walk the chord progression
roots too. Usage: claudio drone [on|off|status|follow on|off]."""
sub = args[0] if args else "status"
if sub in ("on", "start"):
return cmd_start()
if sub in ("off", "stop"):
return cmd_stop()
if sub == "follow":
cfg = load_config()
if len(args) > 1 and args[1] in ("on", "off"):
cfg["drone_chords"] = args[1] == "on"; save_config(cfg)
print(f"drone follows chords: {'on' if cfg.get('drone_chords') else 'off'}"
f" (always follows the root note)")
return
pid = drone_pid()
cfg = load_config()
name = active_preset_name()
has = bool((load_preset(name) or {}).get("drone"))
print(f"drone: {'running pid=' + str(pid) if pid else 'off'} · preset {name}"
f"{'' if has else ' (no drone in this preset)'} · gain {cfg.get('drone_gain', 0.45)}"
f" · follows chords: {'on' if cfg.get('drone_chords') else 'off'}")
def cmd_stop():
pid = drone_pid()
if not pid: print("drone not running"); return
try:
audio.terminate_pid(pid)
if audio.IS_WIN:
# Windows has no deliverable SIGTERM handler; ask the loop to stop.
(audio.STATE / "drone.stop").write_text("1")
time.sleep(0.3)
audio.stop_drone() # silence the in-flight drone player now
print(f"drone stopped pid={pid}")
except Exception as e:
print(f"stop failed: {e}")
# ---------- on/off ----------
def cmd_off():
cfg = load_config()
if cfg.get("muted"):
print("🔇 already off")
return
cfg["muted"] = True
save_config(cfg)
# stop drone if running
if drone_pid():
cmd_stop()
# kill any in-flight players so existing tails go silent now, not at end
audio.stop_all()
print("🔇 OFF — run `claudio on` to restore")
def cmd_on():
cfg = load_config()
cfg.pop("muted", None)
save_config(cfg)
name = cfg.get("preset", DEFAULT_PRESET)
preset = load_preset(name)
# auto-start drone if active preset has one
if preset and preset.get("drone") and not drone_pid():
cmd_start()
print(f"🔊 ON — preset: {name}")
def cmd_toggle():
if load_config().get("muted"):
cmd_on()
else:
cmd_off()
# ---------- status ----------
def cmd_doctor(args):
"""Preflight: verify everything Claudio needs is in place and say exactly
how to fix whatever isn't. `--fix` renders the active preset if its samples
are missing. Safe to run anytime; the /claudio skill runs this on silence."""
fix = "--fix" in args or "-f" in args
ok = True
def line(good, label, detail=""):
nonlocal ok
if not good: ok = False
print(f" {'✓' if good else '✗'} {label}{(' — ' + detail) if detail else ''}")
print("Claudio doctor\n")
# 1. Python
v = sys.version_info
line(v >= (3, 9), f"Python {v.major}.{v.minor}", "" if v >= (3, 9) else "need 3.9+")
# 2. numpy (only needed to render/record — not to play)
try:
import numpy as _np
line(True, f"numpy {_np.__version__}")
have_np = True
except Exception:
line(False, "numpy", "render needs it → python3 -m pip install numpy")
have_np = False
# 3. audio player
try:
be = audio.get_backend()
line(be.kind != "null", f"audio player: {be.name}",
"" if be.kind != "null" else "install ffmpeg (Linux/Win) — see README requirements")
except Exception as e:
line(False, "audio player", str(e))
# 4. samples for the active preset
name = active_preset_name()
sdir = PRESETS / name / "samples"
wavs = list(sdir.rglob("*.wav")) if sdir.exists() else []
line(bool(wavs), f"sounds for '{name}'", "" if wavs else f"not rendered yet → claudio regen {name}")
# 5. config writable
try:
cfg = load_config(); save_config(cfg); line(True, "config writable")
except Exception as e:
line(False, "config writable", str(e))
# 6. hooks (manual installs only; plugin hooks are host-managed)
wired = {runtime: installed_hook_events(runtime)
for runtime in SUPPORTED_RUNTIMES}
wired = {runtime: events for runtime, events in wired.items() if events}
if wired:
for runtime, events in wired.items():
line(True, f"{RUNTIME_LABELS[runtime]} hooks", f"{len(events)} events")
else:
print(" • hooks: no manual Claudio hooks found — that's expected for a")
print(" plugin install. Otherwise run `claudio install` (auto-detect),")
print(" or `claudio install codex` / `claudio install gemini`.")
if fix and not wavs and have_np:
render = PRESETS / name / "render.py"
if render.exists():
print(f"\n→ rendering '{name}' …")
r = subprocess_run_render(render)
print(" done." if r else " render failed — see output above.")
print("\n" + ("✓ all set — start (or restart) an agent session and listen."
if ok else "✗ fix the ✗ items above, then run `claudio doctor` again."))
return 0 if ok else 1
def subprocess_run_render(render_path):
import subprocess
try:
r = subprocess.run([sys.executable, str(render_path)], cwd=str(HERE),
capture_output=True, text=True, timeout=600)
if r.returncode != 0:
print(r.stdout[-500:]); print(r.stderr[-500:], file=sys.stderr)
return r.returncode == 0
except Exception as e:
print(f" {e}", file=sys.stderr); return False
def cmd_status():
cfg = load_config()
name = cfg.get("preset", DEFAULT_PRESET)
preset = load_preset(name)
pid = drone_pid()
muted = cfg.get("muted", False)
print(f"state: {'🔇 OFF' if muted else '🔊 ON'}")
print(f"active preset: {name}{' (✓)' if preset else ' (NOT FOUND)'}")
if preset:
print(f" description: {preset.get('description','')}")
print(f" drone: {preset.get('drone') or 'none'}")
print(f" voices: {', '.join(preset.get('voices', {}).keys())}")
print(f"available: {', '.join(list_preset_names()) or '(none)'}")
hook_bits = []
for runtime in SUPPORTED_RUNTIMES:
events = installed_hook_events(runtime)
if events:
hook_bits.append(f"{RUNTIME_LABELS[runtime]} ({len(events)})")
print(f"manual hooks: {', '.join(hook_bits) if hook_bits else '(none; plugin hooks may be active)'}")
print(f"drone: {'running pid='+str(pid) if pid else 'stopped'}")
print(f"master_gain: {cfg.get('master_gain', preset.get('master_gain', 0.5) if preset else 0.5)}")
print(f"drone_gain: {cfg.get('drone_gain', preset.get('drone_gain', 0.45) if preset else 0.45)}")
rules = load_json(RULES_FILE, {"rules": []}).get("rules", [])
if rules:
print("cwd rules:")
for r in rules:
print(f" {r.get('pattern','?'):<60} → {r.get('preset','?')}")
sessions = load_json(SESSIONS_FILE, {"active": {}}).get("active", {})
fresh = {sid: s for sid, s in sessions.items() if s.get("last_seen", 0) > time.time() - 4*3600}
print(f"active sessions: {len(fresh)} (last 4h) (run `claudio sessions` for details)")
g = song_mod.global_song()
if g:
n_total = len(song_mod.notes_for(g))
s = song_mod.load_song(g) or {}
print(f"song (global): {g} ({song_mod.position(g)}/{n_total} notes, bpm={s.get('bpm')})")
else:
print(f"song (global): (off — Markov picker)")
if preset and preset.get("song"):
print(f" preset song: {preset['song']} (overrides global for {name})")
q = song_mod.quant_settings()
print(f"quant: {'ON' if q['enabled'] else 'off'} tempo={q['bpm']} bpm grid={q['grid']} beats")
print(f"event log: {LOGS / 'event.log'}")
# ---------- presets ----------
def cmd_preset(args):
if not args or args[0] in ("list", "ls"):
names = list_preset_names()
active = active_preset_name()
for n in names:
preset = load_preset(n)
tag = " *" if n == active else " "
desc = preset.get("description", "") if preset else "(broken)"
print(f"{tag} {n:<14} {desc}")
return
if args[0] in ("current", "show"):
print(active_preset_name()); return
if args[0] == "song":
if len(args) < 3:
print("usage: claudio preset song <preset> <song-name|off>"); return
pname, song_name = args[1], args[2]
preset = load_preset(pname)
if preset is None:
print(f"unknown preset '{pname}'"); return
if song_name in ("off", "none", "-"):
preset.pop("song", None)
save_preset(pname, preset)
print(f"preset '{pname}' song cleared")
return
if not song_mod.has_song(song_name):
print(f"unknown song '{song_name}'. available: {', '.join(song_mod.list_songs()) or '(none)'}")
return
preset["song"] = song_name
save_preset(pname, preset)
print(f"preset '{pname}' song → {song_name}")
return
if args[0] == "reset":
target = args[1] if len(args) > 1 else active_preset_name()
return cmd_preset_reset(target)
if args[0] == "reverb":
return cmd_preset_reverb(args[1:])
if args[0] in ("use", "set", "switch"):
if len(args) < 2: print("usage: claudio preset use <name>"); return
name = args[1]
if name == "default":
name = DEFAULT_PRESET
if not (PRESETS / name / "preset.json").exists():
print(f"unknown preset '{name}'. available: {', '.join(list_preset_names())}")
return
cfg = load_config()
cfg["preset"] = name
cfg.pop("master_gain", None)
cfg.pop("drone_gain", None)
save_config(cfg)
print(f"active preset → {name}")
if drone_pid():
print("(stopping drone — preset changed)"); cmd_stop()
preset = load_preset(name)
if preset and preset.get("drone"):
print("(starting drone for new preset)"); cmd_start()
return
print(f"unknown preset subcommand: {args[0]}")
# ---------- reset ----------
def cmd_preset_reset(name):
src = PRESETS / name / "preset.default.json"
dst = PRESETS / name / "preset.json"
if not src.exists():
print(f"no shipped default for '{name}' (looking for {src.name})")
return
dst.write_bytes(src.read_bytes())
print(f"preset '{name}' restored from {src.name}")
def cmd_reset(args):
"""Full reset to shipped defaults — equivalent of a fresh install
state. Asks for confirmation unless --yes is passed."""
confirm = ("--yes" in args) or ("-y" in args)
if not confirm:
print("This will:")
print(f" · restore preset.json for ALL presets from preset.default.json")
print(f" · rewrite config.json to shipped defaults "
f"(preset={DEFAULT_PRESET}, drone_gain=0.0, chords=pop on, "
f"volume follows the preset)")
print(f" · clear song positions, channel overrides, global song")
print(f" · clear session pins (sessions.json) and cwd rules (rules.json)")
print(f" · NOT touch installed hooks, samples, imported songs, or logs")
print()
print("Re-run with --yes to confirm: claudio reset --yes")
return
# restore presets
for name in list_preset_names():
cmd_preset_reset(name)
# config
save_config(dict(DEFAULT_CONFIG))
print(f"config.json → shipped defaults")
# song state
song_state = STATE / "song.json"
if song_state.exists(): song_state.unlink()
print(f"song state cleared")
# session pins
if SESSIONS_FILE.exists(): SESSIONS_FILE.unlink()
if RULES_FILE.exists(): RULES_FILE.unlink()
print(f"session pins + cwd rules cleared")
# bounce drone
if drone_pid():
cmd_stop()
preset = load_preset(DEFAULT_PRESET)
if preset and preset.get("drone"):
cmd_start()
print()
print(f"✓ reset complete — active preset: {DEFAULT_PRESET}")
# ---------- sessions / rules ----------
def _load_active_sessions():
return load_json(SESSIONS_FILE, {"active": {}}).get("active", {})
def _resolve_session(target):
"""Resolve target (numeric index or id-prefix) to a session_id."""
sessions = _load_active_sessions()
rows = sorted(sessions.items(), key=lambda kv: -kv[1].get("last_seen", 0))
if target.isdigit():
idx = int(target) - 1
if 0 <= idx < len(rows): return rows[idx][0]
return None
matches = [sid for sid, _ in rows if sid.startswith(target)]
if len(matches) == 1: return matches[0]
if len(matches) > 1:
print(f"ambiguous prefix '{target}'; matches {len(matches)} sessions")
return None
def cmd_sessions():
sessions = _load_active_sessions()
cutoff = time.time() - 4 * 3600
fresh = sorted(
((sid, s) for sid, s in sessions.items() if s.get("last_seen", 0) > cutoff),
key=lambda kv: -kv[1].get("last_seen", 0),
)
if not fresh:
print("no active sessions seen in last 4h")
return
print(f"{'#':>2} {'sid':<10} {'pin':<3} {'preset':<12} {'ago':<6} {'src':<12} cwd")
for i, (sid, s) in enumerate(fresh, 1):
ago = max(0, int((time.time() - s.get("last_seen", 0)) / 60))
pin = "📌" if s.get("preset_pinned") else " "
preset = s.get("preset_resolved", "?")
src = (s.get("preset_source", "") or "")[:11]
cwd = s.get("cwd", "?")
print(f"{i:>2} {sid[:8]} {pin} {preset:<12} {ago:>3}m {src:<12} {cwd}")
def cmd_session(args):
if not args:
cmd_sessions(); return
sub = args[0]; rest = args[1:]
if sub in ("list", "ls"):
cmd_sessions(); return
if sub == "pin":
if len(rest) < 2: print("usage: claudio session pin <id|index> <preset>"); return
sid = _resolve_session(rest[0])
if not sid: print(f"no session matches '{rest[0]}'"); return
preset = rest[1]
if not (PRESETS / preset / "preset.json").exists():
print(f"unknown preset '{preset}'"); return
d = load_json(SESSIONS_FILE, {"active": {}})
d.setdefault("active", {}).setdefault(sid, {})["preset_pinned"] = preset
save_json(SESSIONS_FILE, d)
print(f"pinned {sid[:8]} → {preset}")
return
if sub == "scale":
if len(rest) < 2:
print("usage: claudio session scale <id|index> <scale|off>"); return
sid = _resolve_session(rest[0])
if not sid: print(f"no session matches '{rest[0]}'"); return
d = load_json(SESSIONS_FILE, {"active": {}})
rec = d.setdefault("active", {}).setdefault(sid, {})
target = rest[1]
if target in ("off", "none", "-"):
rec.pop("scale_override", None)
save_json(SESSIONS_FILE, d)
print(f"session {sid[:8]} scale cleared")
return
if target not in _scale_names():
print(f"unknown scale '{target}'. available: {', '.join(_scale_names())}")
return
rec["scale_override"] = target
save_json(SESSIONS_FILE, d)
print(f"session {sid[:8]} scale → {target}")
return
if sub == "song":
if len(rest) < 2:
print("usage: claudio session song <id|index> <song-name|off>"); return
sid = _resolve_session(rest[0])
if not sid: print(f"no session matches '{rest[0]}'"); return
d = load_json(SESSIONS_FILE, {"active": {}})
rec = d.setdefault("active", {}).setdefault(sid, {})
target = rest[1]
if target in ("off", "none", "-"):
rec.pop("song_pinned", None)
save_json(SESSIONS_FILE, d)
print(f"session {sid[:8]} song cleared")
return
if not song_mod.has_song(target):
print(f"unknown song '{target}'"); return
rec["song_pinned"] = target
save_json(SESSIONS_FILE, d)
print(f"session {sid[:8]} song → {target}")
return
if sub == "unpin":
if not rest: print("usage: claudio session unpin <id|index>"); return
sid = _resolve_session(rest[0])
if not sid: print(f"no session matches '{rest[0]}'"); return
d = load_json(SESSIONS_FILE, {"active": {}})
if sid in d.get("active", {}):
d["active"][sid].pop("preset_pinned", None)
save_json(SESSIONS_FILE, d)
print(f"unpinned {sid[:8]}")
return
print(f"unknown session subcommand: {sub}")
def cmd_here(args):
if not args: print("usage: claudio here <preset>"); return
preset = args[0]
if not (PRESETS / preset / "preset.json").exists():
print(f"unknown preset '{preset}'"); return
cwd = os.environ.get("CLAUDIO_CWD") or os.getcwd()
cmd_rule(["add", cwd, preset])
def _format_rule(r):
parts = [f" {r.get('pattern','?'):<48} → {r.get('preset','?'):<10}"]
extras = []
if "time" in r: extras.append(f"time={r['time']}")
if "idle_after_s" in r: extras.append(f"idle≥{r['idle_after_s']}s")
if extras: parts.append(" " + " ".join(extras))
return "".join(parts)
def cmd_rule(args):
if not args or args[0] in ("list", "ls"):
rules = load_json(RULES_FILE, {"rules": []}).get("rules", [])
if not rules: print("(no rules)"); return
print("rules are evaluated top-to-bottom; first match wins")
for r in rules:
print(_format_rule(r))
return
sub = args[0]
rest = list(args[1:])
if sub == "add":
# parse positional + flag args.
# syntax: claudio rule add <pattern> <preset> [--time HH:MM-HH:MM] [--idle-after N]
time_val = None
idle_val = None
positional = []
i = 0
while i < len(rest):
a = rest[i]
if a == "--time" and i + 1 < len(rest):
time_val = rest[i + 1]; i += 2; continue
if a in ("--idle-after", "--idle") and i + 1 < len(rest):
idle_val = int(rest[i + 1]); i += 2; continue
positional.append(a); i += 1
if len(positional) < 2:
print("usage: claudio rule add <pattern> <preset> [--time HH:MM-HH:MM] [--idle-after N]")
return
pattern, preset = positional[0], positional[1]
if not (PRESETS / preset / "preset.json").exists():
print(f"unknown preset '{preset}'"); return
new_rule = {"pattern": pattern, "preset": preset}
if time_val:
try:
start_s, end_s = time_val.split("-")
for s in (start_s, end_s):
h, m = s.split(":")
int(h); int(m)
except Exception:
print(f"--time must be HH:MM-HH:MM (got '{time_val}')"); return
new_rule["time"] = time_val
if idle_val is not None:
if idle_val < 30:
print(f"--idle-after below 30s is too jumpy; pick a higher value"); return
new_rule["idle_after_s"] = idle_val
d = load_json(RULES_FILE, {"rules": []})
# de-dup by pattern + time + idle (allow multiple rules for same pattern with different conditions)
key = (new_rule["pattern"], new_rule.get("time"), new_rule.get("idle_after_s"))
rules = [r for r in d.get("rules", [])
if (r.get("pattern"), r.get("time"), r.get("idle_after_s")) != key]
rules.append(new_rule)
d["rules"] = rules
save_json(RULES_FILE, d)
print(f"rule added:")
print(_format_rule(new_rule))
return
if sub in ("rm", "remove"):
if not rest: print("usage: claudio rule rm <pattern>"); return
pattern = rest[0]
d = load_json(RULES_FILE, {"rules": []})
before = len(d.get("rules", []))
d["rules"] = [r for r in d.get("rules", []) if r.get("pattern") != pattern]
save_json(RULES_FILE, d)
print(f"removed {before - len(d['rules'])} rule(s) matching '{pattern}'")
return
print(f"unknown rule subcommand: {sub}")
# ---------- voice / mapping subcommands ----------
def _require_voice(preset, name):
voices = preset.get("voices", {})
if name not in voices:
print(f"unknown voice '{name}'. available: {', '.join(voices)}")
return None
return voices[name]
def _regen_voice(pname, vname):
"""Re-render a single voice's samples (used after a reverb change)."""
render = PRESETS / pname / "render.py"
if not render.exists():
print(f" (preset '{pname}' has no render.py; reverb change saved but "
f"samples not regenerated)"); return
audio.spawn_python(render, [vname])
def cmd_voice(args):
if len(args) < 2:
print("usage: claudio voice <name> <gain|mioi|reverb|delay|fx|play> [value]"); return
name = args[0]; sub = args[1]; rest = args[2:]
pname = active_preset_name()
preset = load_preset(pname)
if preset is None: print(f"preset {pname} not found"); return
v = _require_voice(preset, name)
if v is None: return
if sub == "reverb":
# claudio voice <name> reverb <wet> [decay] [brightness] | off
# baked at render → regenerates just this voice's samples.
rv = v.setdefault("reverb", {})
if rest and rest[0] in ("off", "dry", "none", "0"):
rv["wet"] = 0.0
elif not rest:
print("usage: claudio voice <name> reverb <wet 0..1> [decay s] [brightness 0..1] | off"); return
else:
rv["wet"] = round(max(0.0, min(1.0, float(rest[0]))), 3)
if len(rest) > 1: rv["decay"] = round(max(0.1, min(8.0, float(rest[1]))), 2)
if len(rest) > 2: rv["brightness"] = round(max(0.0, min(1.0, float(rest[2]))), 2)
save_preset(pname, preset)
print(f"{name}.reverb = {rv} (regenerating…)")
_regen_voice(pname, name)
return
if sub == "delay":
# claudio voice <name> delay <ms> [feedback] [count] | off
# live playback echo — no re-render needed.
if rest and rest[0] in ("off", "none", "0"):
v.pop("delay", None)
save_preset(pname, preset)
print(f"{name}.delay = off"); return
if not rest:
print("usage: claudio voice <name> delay <ms> [feedback 0..0.85] [count 1..8] | off"); return
d = v.setdefault("delay", {})
d["ms"] = int(max(40, min(2000, float(rest[0]))))
if len(rest) > 1: d["feedback"] = round(max(0.0, min(0.85, float(rest[1]))), 2)
if len(rest) > 2: d["count"] = int(max(1, min(8, float(rest[2]))))
d.setdefault("feedback", 0.30); d.setdefault("count", 3)
save_preset(pname, preset)
print(f"{name}.delay = {d} (live — no regen)")
return
if sub in ("fx", "show"):
rv = v.get("reverb"); d = v.get("delay")
rtxt = (f"wet={rv.get('wet')} decay={rv.get('decay','?')}s "
f"bright={rv.get('brightness','?')}" if isinstance(rv, dict) else "(default)")
dtxt = (f"{d.get('ms')}ms fb={d.get('feedback')} x{d.get('count')}"
if isinstance(d, dict) else "off")
print(f"{name}: reverb {rtxt} | delay {dtxt}")
return
if sub == "gain":
if not rest: print("usage: claudio voice <name> gain <0..1>"); return
v["gain"] = round(max(0.0, min(1.0, float(rest[0]))), 3)
save_preset(pname, preset)
print(f"{name}.gain = {v['gain']}")
return