kbd-signal 0.4.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 sora (Sora-bluesky)
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,167 @@
1
+ Metadata-Version: 2.4
2
+ Name: kbd-signal
3
+ Version: 0.4.0
4
+ Summary: Turn a VIA-compatible RGB keyboard's backlight into a status lamp for Claude Code / Codex (raw HID, stock firmware)
5
+ Author: sora (Sora-bluesky)
6
+ License: MIT
7
+ Project-URL: Repository, https://github.com/Sora-bluesky/kbd-signal
8
+ Keywords: keychron,via,qmk,rgb,claude-code,codex,hid
9
+ Classifier: Environment :: Console
10
+ Classifier: Operating System :: Microsoft :: Windows
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Topic :: System :: Hardware
13
+ Requires-Python: >=3.11
14
+ Description-Content-Type: text/markdown
15
+ License-File: LICENSE
16
+ Requires-Dist: hidapi>=0.14
17
+ Dynamic: license-file
18
+
19
+ # kbd-signal
20
+
21
+ [English](README.md) | [日本語](README.ja.md)
22
+
23
+ Turn a **VIA-compatible RGB keyboard's backlight into a status lamp** for AI coding agents on Windows (defaults target the Keychron K8 Pro). When Claude Code or Codex waits for your approval, your keyboard starts breathing orange — no need to watch the screen.
24
+
25
+ Works on **stock firmware** (no flashing) by speaking the VIA raw HID protocol directly.
26
+
27
+ ## Signals
28
+
29
+ | State | Trigger | Effect |
30
+ |-------|---------|--------|
31
+ | `waiting` | Claude Code / Codex shows a permission dialog (`PermissionRequest` hook) | Orange breathing |
32
+ | `done` | Main turn finished (`Stop` hook) | Solid green for 5 s, then auto-restore |
33
+ | `error` | Manual `kbd-signal set error` | Fast red breathing |
34
+
35
+ Before signaling, the current lighting (effect / speed / brightness / color) is snapshotted and restored afterwards. **Nothing is ever written to EEPROM** (RAM-only changes), so a power cycle always returns the keyboard to your saved settings.
36
+
37
+ ## Requirements & limitations
38
+
39
+ - Windows, Python 3.11+ (`hidapi` is the only dependency)
40
+ - Keychron K8 Pro connected via **USB cable with the rear switch set to "Cable"**. Raw HID is not available over Bluetooth — measured: in BT mode with the cable attached, the USB HID collections enumerate but the `0xFF60` raw interface does not
41
+ - When the keyboard is absent (BT mode, unplugged), the hook-facing commands (`hook`, `set`, `restore`) silently no-op with exit 0 — hooks are never blocked. Diagnostic commands (`detect`, `test`, `raw-effect`) report the missing device and exit 1
42
+ - Do not run the VIA app / Keychron Launcher at the same time (concurrent raw HID writes race)
43
+ - Codex requires a version with lifecycle hooks; run `codex features list` and confirm that `hooks` is enabled
44
+ - Concurrent Claude Code / Codex sessions and subagents are tracked independently; orange remains active while any approval is pending
45
+
46
+ ## Install
47
+
48
+ Recommended: [pipx](https://pipx.pypa.io/) — installs into an isolated environment and puts `kbd-signal` on PATH, which is exactly what the hook commands need:
49
+
50
+ ```powershell
51
+ py -m pip install --user pipx
52
+ py -m pipx ensurepath # then open a new terminal
53
+ pipx install kbd-signal
54
+ ```
55
+
56
+ Plain pip also works (`py -m pip install .`); in that case invoke the hooks with the **same interpreter** you installed into: `py -m kbd_signal hook claude`.
57
+
58
+ ## Usage
59
+
60
+ ```
61
+ kbd-signal detect # find the keyboard, show protocol & current lighting
62
+ kbd-signal set <waiting|done|error>
63
+ kbd-signal restore [--after N] [--gen G]
64
+ kbd-signal test # play all patterns, then restore
65
+ kbd-signal raw-effect <n> # set a raw effect index (debug)
66
+ kbd-signal hook claude # entry point for Claude Code hooks (JSON on stdin)
67
+ kbd-signal hook codex [<json>] # Codex hooks (stdin) / legacy notify (argv)
68
+ ```
69
+
70
+ ### Restore mode (`%LOCALAPPDATA%\kbd-signal\config.json`)
71
+
72
+ ```json
73
+ {"restore": "off"}
74
+ ```
75
+
76
+ - `"baseline"` (default): restore the pre-signal effect and brightness
77
+ - `"off"`: restore to brightness 0 (for people who normally keep the backlight dark). The stored effect/color/speed are still written back, so waking the backlight with Fn shows your own settings
78
+
79
+ The Fn backlight on/off flag is not readable over VIA, which is why `"off"` exists.
80
+
81
+ ## Claude Code integration
82
+
83
+ Register the same command for `PermissionRequest`, `PostToolUse`, `Stop`, and `SessionEnd` in your user-scope `settings.json` (events are dispatched internally by `hook_event_name`):
84
+
85
+ ```json
86
+ {"type": "command", "command": "kbd-signal hook claude", "timeout": 5}
87
+ ```
88
+
89
+ (pipx install — the `kbd-signal` shim is on PATH. With a plain pip install, use `py -m kbd_signal hook claude` instead, matching the interpreter you installed into.)
90
+
91
+ **Do not put a filesystem path in the program position.** Hook commands may run through either `cmd` or a POSIX shell: backslashed paths get eaten as escapes by the POSIX shell, and forward-slashed program paths fail under `cmd` with "Access is denied" — both silently, so the hook simply never signals (measured on Windows 11). PATH-resolved names (`kbd-signal`, `py -m kbd_signal`) work under both. The entry point is cheap when idle (the hidapi DLL is imported lazily), so the same command is fine for hot hooks like `PostToolUse`.
92
+
93
+ ## Codex integration (since v0.3.0)
94
+
95
+ Use Codex lifecycle hooks. They are separate from the `notify` entry in `~/.codex/config.toml`, so **leave the existing `notify` command unchanged**.
96
+
97
+ 1. Run `codex features list` and confirm that `hooks` is enabled
98
+ 2. Merge the events from [examples/codex-hooks.json](examples/codex-hooks.json) into the user-level `~/.codex/hooks.json`; do not overwrite an existing file
99
+ 3. Start the Codex CLI and choose `Review hooks` from the startup `Hooks need review` prompt, or open `/hooks`. Verify the source, event, and command before trusting them. Trust is tied to the hook definition hash, so review it again after any change
100
+ 4. In a new session, trigger an approval and verify orange while waiting and restoration after approval
101
+
102
+ Every event uses the same command:
103
+
104
+ ```json
105
+ {
106
+ "type": "command",
107
+ "command": "kbd-signal hook codex",
108
+ "timeout": 5
109
+ }
110
+ ```
111
+
112
+ The configuration uses:
113
+
114
+ - `PermissionRequest` to add a pending approval
115
+ - `PostToolUse` to release only the agent that completed its tool
116
+ - `Stop` to release the main session and signal completion only when no other session is waiting
117
+ - `SubagentStop` to clean up a child without flashing green for the whole task
118
+ - `SessionStart` / `UserPromptSubmit` to clean up stale entries for the same session after an interrupted run
119
+
120
+ Codex does not expose `SessionEnd`. If Codex is force-closed while an approval is pending and that session is never resumed, orange can remain active; run `kbd-signal restore` to recover.
121
+
122
+ The old `agent-turn-complete` notify payload remains supported for compatibility, but it cannot report approval waits and competes with the desktop app's notifier, so it is not recommended for new installations.
123
+
124
+ ### Concurrent sessions
125
+
126
+ Owners are keyed by product, `session_id`, and `agent_id`. A main-session completion therefore cannot clear another Claude/Codex session or one of its subagents. Updates to `state.json` remain serialized by the existing interprocess lock.
127
+
128
+ To roll back, remove only the entries whose command invokes `kbd_signal hook codex` from `~/.codex/hooks.json`, then restart Codex. The desktop app's `notify` configuration remains untouched.
129
+
130
+ ## Protocol notes (verified on hardware)
131
+
132
+ - Shipped K8 Pro stock firmware speaks **VIA protocol 9 (v2)** — not the v3 custom-channel layout found on the `wireless_playground` branch. The protocol is probed at open time (command `0x01`) and both layouts are supported:
133
+ - v2: `[report_id 0x00, cmd, value_id, data...]`, value ids `0x80` brightness / `0x81` effect / `0x82` speed / `0x83` color (hue, sat)
134
+ - v3 (protocol ≥ 11): `[report_id 0x00, cmd, channel=3, value_id, data...]`, value ids 1–4
135
+ - Commands: set `0x07`, get `0x08`, save `0x09` (**save is never used**)
136
+ - Effect indices are identical across firmware generations (`info.json` animation list matches): None=0, **Solid Color=1, Breathing=2**, … Solid Splash=22
137
+ - Device detection: VID `0x3434` + usage page `0xFF60` / usage `0x61` (PIDs differ per layout variant)
138
+
139
+ ## Other keyboards (since v0.2.0)
140
+
141
+ The protocol layer is not K8 Pro specific: VIA v2 value ids are fixed by the VIA spec and Solid Color is always effect 1 in QMK. Point kbd-signal at another VIA-compatible RGB keyboard via `config.json`:
142
+
143
+ ```json
144
+ {
145
+ "restore": "off",
146
+ "device": {
147
+ "vendor_id": "0x3434",
148
+ "product_id": null,
149
+ "product_match": "K8",
150
+ "v3_channel": 3,
151
+ "effects": {"solid": 1, "breathing": 2}
152
+ }
153
+ }
154
+ ```
155
+
156
+ Workflow for a new board:
157
+
158
+ 1. `kbd-signal detect --all` — list every raw-HID (0xFF60) device and copy its VID/PID into `config.json`
159
+ 2. `kbd-signal raw-effect <n>` — step through effect indices until you find solid/breathing, then set `effects`
160
+ 3. On a VIA v3 board, set `v3_channel` to the keyboard's `id_qmk_rgb_matrix` channel from its VIA definition (v2 boards ignore it)
161
+ 4. `kbd-signal test`
162
+
163
+ Boards without RGB (single-color backlight) are out of scope — states are color-coded.
164
+
165
+ ## License
166
+
167
+ MIT
@@ -0,0 +1,149 @@
1
+ # kbd-signal
2
+
3
+ [English](README.md) | [日本語](README.ja.md)
4
+
5
+ Turn a **VIA-compatible RGB keyboard's backlight into a status lamp** for AI coding agents on Windows (defaults target the Keychron K8 Pro). When Claude Code or Codex waits for your approval, your keyboard starts breathing orange — no need to watch the screen.
6
+
7
+ Works on **stock firmware** (no flashing) by speaking the VIA raw HID protocol directly.
8
+
9
+ ## Signals
10
+
11
+ | State | Trigger | Effect |
12
+ |-------|---------|--------|
13
+ | `waiting` | Claude Code / Codex shows a permission dialog (`PermissionRequest` hook) | Orange breathing |
14
+ | `done` | Main turn finished (`Stop` hook) | Solid green for 5 s, then auto-restore |
15
+ | `error` | Manual `kbd-signal set error` | Fast red breathing |
16
+
17
+ Before signaling, the current lighting (effect / speed / brightness / color) is snapshotted and restored afterwards. **Nothing is ever written to EEPROM** (RAM-only changes), so a power cycle always returns the keyboard to your saved settings.
18
+
19
+ ## Requirements & limitations
20
+
21
+ - Windows, Python 3.11+ (`hidapi` is the only dependency)
22
+ - Keychron K8 Pro connected via **USB cable with the rear switch set to "Cable"**. Raw HID is not available over Bluetooth — measured: in BT mode with the cable attached, the USB HID collections enumerate but the `0xFF60` raw interface does not
23
+ - When the keyboard is absent (BT mode, unplugged), the hook-facing commands (`hook`, `set`, `restore`) silently no-op with exit 0 — hooks are never blocked. Diagnostic commands (`detect`, `test`, `raw-effect`) report the missing device and exit 1
24
+ - Do not run the VIA app / Keychron Launcher at the same time (concurrent raw HID writes race)
25
+ - Codex requires a version with lifecycle hooks; run `codex features list` and confirm that `hooks` is enabled
26
+ - Concurrent Claude Code / Codex sessions and subagents are tracked independently; orange remains active while any approval is pending
27
+
28
+ ## Install
29
+
30
+ Recommended: [pipx](https://pipx.pypa.io/) — installs into an isolated environment and puts `kbd-signal` on PATH, which is exactly what the hook commands need:
31
+
32
+ ```powershell
33
+ py -m pip install --user pipx
34
+ py -m pipx ensurepath # then open a new terminal
35
+ pipx install kbd-signal
36
+ ```
37
+
38
+ Plain pip also works (`py -m pip install .`); in that case invoke the hooks with the **same interpreter** you installed into: `py -m kbd_signal hook claude`.
39
+
40
+ ## Usage
41
+
42
+ ```
43
+ kbd-signal detect # find the keyboard, show protocol & current lighting
44
+ kbd-signal set <waiting|done|error>
45
+ kbd-signal restore [--after N] [--gen G]
46
+ kbd-signal test # play all patterns, then restore
47
+ kbd-signal raw-effect <n> # set a raw effect index (debug)
48
+ kbd-signal hook claude # entry point for Claude Code hooks (JSON on stdin)
49
+ kbd-signal hook codex [<json>] # Codex hooks (stdin) / legacy notify (argv)
50
+ ```
51
+
52
+ ### Restore mode (`%LOCALAPPDATA%\kbd-signal\config.json`)
53
+
54
+ ```json
55
+ {"restore": "off"}
56
+ ```
57
+
58
+ - `"baseline"` (default): restore the pre-signal effect and brightness
59
+ - `"off"`: restore to brightness 0 (for people who normally keep the backlight dark). The stored effect/color/speed are still written back, so waking the backlight with Fn shows your own settings
60
+
61
+ The Fn backlight on/off flag is not readable over VIA, which is why `"off"` exists.
62
+
63
+ ## Claude Code integration
64
+
65
+ Register the same command for `PermissionRequest`, `PostToolUse`, `Stop`, and `SessionEnd` in your user-scope `settings.json` (events are dispatched internally by `hook_event_name`):
66
+
67
+ ```json
68
+ {"type": "command", "command": "kbd-signal hook claude", "timeout": 5}
69
+ ```
70
+
71
+ (pipx install — the `kbd-signal` shim is on PATH. With a plain pip install, use `py -m kbd_signal hook claude` instead, matching the interpreter you installed into.)
72
+
73
+ **Do not put a filesystem path in the program position.** Hook commands may run through either `cmd` or a POSIX shell: backslashed paths get eaten as escapes by the POSIX shell, and forward-slashed program paths fail under `cmd` with "Access is denied" — both silently, so the hook simply never signals (measured on Windows 11). PATH-resolved names (`kbd-signal`, `py -m kbd_signal`) work under both. The entry point is cheap when idle (the hidapi DLL is imported lazily), so the same command is fine for hot hooks like `PostToolUse`.
74
+
75
+ ## Codex integration (since v0.3.0)
76
+
77
+ Use Codex lifecycle hooks. They are separate from the `notify` entry in `~/.codex/config.toml`, so **leave the existing `notify` command unchanged**.
78
+
79
+ 1. Run `codex features list` and confirm that `hooks` is enabled
80
+ 2. Merge the events from [examples/codex-hooks.json](examples/codex-hooks.json) into the user-level `~/.codex/hooks.json`; do not overwrite an existing file
81
+ 3. Start the Codex CLI and choose `Review hooks` from the startup `Hooks need review` prompt, or open `/hooks`. Verify the source, event, and command before trusting them. Trust is tied to the hook definition hash, so review it again after any change
82
+ 4. In a new session, trigger an approval and verify orange while waiting and restoration after approval
83
+
84
+ Every event uses the same command:
85
+
86
+ ```json
87
+ {
88
+ "type": "command",
89
+ "command": "kbd-signal hook codex",
90
+ "timeout": 5
91
+ }
92
+ ```
93
+
94
+ The configuration uses:
95
+
96
+ - `PermissionRequest` to add a pending approval
97
+ - `PostToolUse` to release only the agent that completed its tool
98
+ - `Stop` to release the main session and signal completion only when no other session is waiting
99
+ - `SubagentStop` to clean up a child without flashing green for the whole task
100
+ - `SessionStart` / `UserPromptSubmit` to clean up stale entries for the same session after an interrupted run
101
+
102
+ Codex does not expose `SessionEnd`. If Codex is force-closed while an approval is pending and that session is never resumed, orange can remain active; run `kbd-signal restore` to recover.
103
+
104
+ The old `agent-turn-complete` notify payload remains supported for compatibility, but it cannot report approval waits and competes with the desktop app's notifier, so it is not recommended for new installations.
105
+
106
+ ### Concurrent sessions
107
+
108
+ Owners are keyed by product, `session_id`, and `agent_id`. A main-session completion therefore cannot clear another Claude/Codex session or one of its subagents. Updates to `state.json` remain serialized by the existing interprocess lock.
109
+
110
+ To roll back, remove only the entries whose command invokes `kbd_signal hook codex` from `~/.codex/hooks.json`, then restart Codex. The desktop app's `notify` configuration remains untouched.
111
+
112
+ ## Protocol notes (verified on hardware)
113
+
114
+ - Shipped K8 Pro stock firmware speaks **VIA protocol 9 (v2)** — not the v3 custom-channel layout found on the `wireless_playground` branch. The protocol is probed at open time (command `0x01`) and both layouts are supported:
115
+ - v2: `[report_id 0x00, cmd, value_id, data...]`, value ids `0x80` brightness / `0x81` effect / `0x82` speed / `0x83` color (hue, sat)
116
+ - v3 (protocol ≥ 11): `[report_id 0x00, cmd, channel=3, value_id, data...]`, value ids 1–4
117
+ - Commands: set `0x07`, get `0x08`, save `0x09` (**save is never used**)
118
+ - Effect indices are identical across firmware generations (`info.json` animation list matches): None=0, **Solid Color=1, Breathing=2**, … Solid Splash=22
119
+ - Device detection: VID `0x3434` + usage page `0xFF60` / usage `0x61` (PIDs differ per layout variant)
120
+
121
+ ## Other keyboards (since v0.2.0)
122
+
123
+ The protocol layer is not K8 Pro specific: VIA v2 value ids are fixed by the VIA spec and Solid Color is always effect 1 in QMK. Point kbd-signal at another VIA-compatible RGB keyboard via `config.json`:
124
+
125
+ ```json
126
+ {
127
+ "restore": "off",
128
+ "device": {
129
+ "vendor_id": "0x3434",
130
+ "product_id": null,
131
+ "product_match": "K8",
132
+ "v3_channel": 3,
133
+ "effects": {"solid": 1, "breathing": 2}
134
+ }
135
+ }
136
+ ```
137
+
138
+ Workflow for a new board:
139
+
140
+ 1. `kbd-signal detect --all` — list every raw-HID (0xFF60) device and copy its VID/PID into `config.json`
141
+ 2. `kbd-signal raw-effect <n>` — step through effect indices until you find solid/breathing, then set `effects`
142
+ 3. On a VIA v3 board, set `v3_channel` to the keyboard's `id_qmk_rgb_matrix` channel from its VIA definition (v2 boards ignore it)
143
+ 4. `kbd-signal test`
144
+
145
+ Boards without RGB (single-color backlight) are out of scope — states are color-coded.
146
+
147
+ ## License
148
+
149
+ MIT
@@ -0,0 +1,3 @@
1
+ """kbd-signal: Claude Code / Codex status -> Keychron K8 Pro backlight."""
2
+
3
+ __version__ = "0.4.0"
@@ -0,0 +1,5 @@
1
+ import sys
2
+
3
+ from .cli import main
4
+
5
+ sys.exit(main())
@@ -0,0 +1,128 @@
1
+ """kbd-signal CLI entry point."""
2
+
3
+ import argparse
4
+ import sys
5
+ import time
6
+
7
+ from . import states, via
8
+
9
+
10
+ def cmd_detect(args):
11
+ from . import config
12
+ if getattr(args, "all", False):
13
+ found = via.enumerate_raw_hid(None)
14
+ if not found:
15
+ print("No raw HID (0xFF60) interfaces found on any device.")
16
+ return 1
17
+ for d in found:
18
+ print(f"found: {d.get('manufacturer_string')} {d.get('product_string')} "
19
+ f"(VID={d['vendor_id']:#06x} PID={d['product_id']:#06x})")
20
+ print('\nPut vendor_id/product_id into config.json under "device" '
21
+ "to target one of these.")
22
+ return 0
23
+ found = via.enumerate_raw_hid(config.device()["vendor_id"])
24
+ if not found:
25
+ print("Configured keyboard's raw HID interface not found. "
26
+ "Connect via USB cable (rear switch on Cable). "
27
+ "Use `kbd-signal detect --all` to list every raw-HID device.")
28
+ return 1
29
+ for d in found:
30
+ print(f"found: {d.get('product_string')} "
31
+ f"(VID={d['vendor_id']:#06x} PID={d['product_id']:#06x})")
32
+ with via.Keyboard() as kb:
33
+ proto = kb.protocol
34
+ snap = kb.snapshot()
35
+ print(f"VIA protocol: {proto} ({'v3 custom channel' if proto >= 11 else 'v2 lighting'})")
36
+ print(f"current: effect={snap['effect']} speed={snap['speed']} "
37
+ f"brightness={snap['brightness']} hue,sat={snap['color']}")
38
+ return 0
39
+
40
+
41
+ def cmd_set(args):
42
+ ok = states.set_state(args.state)
43
+ if not ok and sys.stdout.isatty():
44
+ print("keyboard unavailable (see log)", file=sys.stderr)
45
+ return 0
46
+
47
+
48
+ def cmd_restore(args):
49
+ states.restore(after=args.after, generation=args.gen)
50
+ return 0
51
+
52
+
53
+ def cmd_test(_args):
54
+ for name in ("waiting", "done", "error"):
55
+ print(f"-> {name}")
56
+ if not states.set_state(name):
57
+ print("keyboard unavailable", file=sys.stderr)
58
+ return 1
59
+ time.sleep(3)
60
+ print("-> restore")
61
+ states.restore()
62
+ return 0
63
+
64
+
65
+ def cmd_raw_effect(args):
66
+ with via.Keyboard() as kb:
67
+ kb.set_value(via.VALUE_EFFECT, args.n)
68
+ print(f"effect set to {args.n}")
69
+ return 0
70
+
71
+
72
+ def cmd_hook(args):
73
+ from . import hooks
74
+ try:
75
+ if args.source == "claude":
76
+ hooks.handle_claude()
77
+ else:
78
+ hooks.handle_codex(args.rest)
79
+ except Exception as e: # never fail the calling agent
80
+ states.log(f"hook {args.source} error: {e!r}")
81
+ return 0
82
+
83
+
84
+ def main(argv=None):
85
+ p = argparse.ArgumentParser(prog="kbd-signal",
86
+ description="Agent status -> VIA keyboard backlight")
87
+ sub = p.add_subparsers(dest="command", required=True)
88
+
89
+ sp = sub.add_parser("detect", help="list device and current lighting")
90
+ sp.add_argument("--all", action="store_true",
91
+ help="list every raw-HID (0xFF60) device regardless of "
92
+ "the configured vendor id")
93
+ sp.set_defaults(fn=cmd_detect)
94
+
95
+ sp = sub.add_parser("set", help="enter a signal state")
96
+ sp.add_argument("state", choices=sorted(states.STATE_NAMES))
97
+ sp.set_defaults(fn=cmd_set)
98
+
99
+ sp = sub.add_parser("restore", help="restore baseline lighting")
100
+ sp.add_argument("--after", type=float, default=None)
101
+ sp.add_argument("--gen", type=int, default=None)
102
+ sp.set_defaults(fn=cmd_restore)
103
+
104
+ sub.add_parser("test", help="play all patterns then restore").set_defaults(fn=cmd_test)
105
+
106
+ sp = sub.add_parser("raw-effect", help="set a raw effect index (debug)")
107
+ sp.add_argument("n", type=int)
108
+ sp.set_defaults(fn=cmd_raw_effect)
109
+
110
+ sp = sub.add_parser("hook", help="entry point for agent hooks")
111
+ sp.add_argument("source", choices=["claude", "codex"])
112
+ sp.add_argument("rest", nargs=argparse.REMAINDER)
113
+ sp.set_defaults(fn=cmd_hook)
114
+
115
+ args = p.parse_args(argv)
116
+ try:
117
+ return args.fn(args)
118
+ except (via.DeviceNotFound, OSError) as e:
119
+ # Diagnostic commands report a missing or unopenable keyboard cleanly
120
+ # with exit 1 (OSError covers open_path/read/write failures, e.g. the
121
+ # device disappearing between enumeration and open).
122
+ # Hook paths never raise (cmd_hook catches everything itself).
123
+ print(f"kbd-signal: {e}", file=sys.stderr)
124
+ return 1
125
+
126
+
127
+ if __name__ == "__main__":
128
+ sys.exit(main())
@@ -0,0 +1,60 @@
1
+ """User configuration (%LOCALAPPDATA%/kbd-signal/config.json).
2
+
3
+ Defaults target the Keychron K8 Pro; every device-specific constant can be
4
+ overridden so other VIA-compatible RGB keyboards work without code changes:
5
+
6
+ {
7
+ "restore": "off", // or "baseline" (default)
8
+ "device": {
9
+ "vendor_id": "0x3434", // USB VID (int or hex string)
10
+ "product_id": null, // optional exact PID filter
11
+ "product_match": "K8", // preferred product-string substring
12
+ "v3_channel": 3, // VIA v3 custom channel for rgb_matrix
13
+ "effects": {"solid": 1, "breathing": 2}
14
+ }
15
+ }
16
+
17
+ Workflow for a new keyboard: `kbd-signal detect --all` to find VID/PID,
18
+ then `kbd-signal raw-effect <n>` to probe its effect indices.
19
+ """
20
+
21
+ import json
22
+ import os
23
+
24
+ STATE_DIR = os.path.join(os.environ.get("LOCALAPPDATA", os.path.expanduser("~")),
25
+ "kbd-signal")
26
+ CONFIG_FILE = os.path.join(STATE_DIR, "config.json")
27
+
28
+ DEFAULT_DEVICE = {
29
+ "vendor_id": 0x3434, # Keychron
30
+ "product_id": None,
31
+ "product_match": "K8",
32
+ "v3_channel": 3, # id_qmk_rgb_matrix_channel in Keychron via_json
33
+ "effects": {"solid": 1, "breathing": 2},
34
+ }
35
+
36
+
37
+ def _to_int(value):
38
+ if isinstance(value, str):
39
+ return int(value, 0) # accepts "0x3434" and "13364"
40
+ return value
41
+
42
+
43
+ def load():
44
+ try:
45
+ with open(CONFIG_FILE, encoding="utf-8") as f:
46
+ cfg = json.load(f)
47
+ except (OSError, ValueError):
48
+ cfg = {}
49
+ device = {**DEFAULT_DEVICE, **cfg.get("device", {})}
50
+ device["vendor_id"] = _to_int(device["vendor_id"])
51
+ if device.get("product_id") is not None:
52
+ device["product_id"] = _to_int(device["product_id"])
53
+ device["effects"] = {**DEFAULT_DEVICE["effects"],
54
+ **(device.get("effects") or {})}
55
+ cfg["device"] = device
56
+ return cfg
57
+
58
+
59
+ def device():
60
+ return load()["device"]
@@ -0,0 +1,131 @@
1
+ """Dispatch Claude Code and Codex lifecycle events to lighting states.
2
+
3
+ Design rule: hook entry points must NEVER block or fail the agent.
4
+ Every path exits 0, errors only go to the log file.
5
+ """
6
+
7
+ import hashlib
8
+ import json
9
+ import sys
10
+
11
+ from . import states
12
+
13
+
14
+ def _read_stdin(stdin, source):
15
+ try:
16
+ payload = json.load(stdin or sys.stdin)
17
+ except (TypeError, ValueError) as e:
18
+ states.log(f"hook {source}: stdin parse failed ({e})")
19
+ return None
20
+ if not isinstance(payload, dict):
21
+ states.log(f"hook {source}: stdin ignored (expected JSON object)")
22
+ return None
23
+ return payload
24
+
25
+
26
+ def _identity(source, payload):
27
+ """Return canonical owner, session scope, aliases, and subagent status.
28
+
29
+ New owner ids are namespaced by agent product so Claude and Codex cannot
30
+ collide. The raw session id is retained as an alias so an approval that
31
+ was already active during an upgrade from v0.2.0 can still be released.
32
+ """
33
+ session = (payload.get("session_id") or payload.get("thread-id")
34
+ or payload.get("thread_id"))
35
+ if not isinstance(session, str) or not session:
36
+ return None
37
+ agent = payload.get("agent_id")
38
+ is_subagent = isinstance(agent, str) and bool(agent)
39
+ agent = agent if is_subagent else "main"
40
+ session_scope = f"{source}:{session}:"
41
+ owner = f"{session_scope}{agent}"
42
+ return owner, session_scope, (session,), is_subagent
43
+
44
+
45
+ def _owner_tag(owner):
46
+ """Short non-reversible id for diagnostics without logging session ids."""
47
+ return hashlib.sha256(owner.encode("utf-8")).hexdigest()[:12]
48
+
49
+
50
+ def _handle_lifecycle(source, payload):
51
+ event = payload.get("hook_event_name", "")
52
+ identity = _identity(source, payload)
53
+ if identity is None:
54
+ states.log(f"hook {source}: event={event or '?'} ignored (missing session id)")
55
+ return
56
+
57
+ owner, session_scope, aliases, is_subagent = identity
58
+ states.log(
59
+ f"hook {source}: event={event or '?'} owner={_owner_tag(owner)}"
60
+ )
61
+
62
+ if event == "PermissionRequest":
63
+ states.set_state("waiting", session=owner, owner_aliases=aliases)
64
+ elif event == "PostToolUse":
65
+ # Only release this agent's approval. Other sessions keep waiting.
66
+ states.release_waiting(session=owner, owner_aliases=aliases)
67
+ elif event == "Stop":
68
+ if is_subagent:
69
+ # A child finishing must not flash green for the whole task.
70
+ states.release_waiting(session=owner, owner_aliases=aliases)
71
+ else:
72
+ states.set_state(
73
+ "done",
74
+ session=owner,
75
+ owner_prefix=session_scope,
76
+ owner_aliases=aliases,
77
+ )
78
+ elif event == "SubagentStop":
79
+ states.release_waiting(session=owner, owner_aliases=aliases)
80
+ elif event in ("SessionStart", "UserPromptSubmit", "SessionEnd"):
81
+ # A new main-session lifecycle edge proves an older approval from that
82
+ # same session is stale. Subagent lifecycle edges only clear the child.
83
+ states.release_waiting(
84
+ session=owner,
85
+ owner_prefix=None if is_subagent else session_scope,
86
+ owner_aliases=aliases,
87
+ )
88
+
89
+
90
+ def handle_claude(stdin=None):
91
+ """Handle Claude Code hook JSON received on stdin."""
92
+ payload = _read_stdin(stdin, "claude")
93
+ if payload is not None:
94
+ _handle_lifecycle("claude", payload)
95
+
96
+
97
+ def handle_codex(argv, stdin=None):
98
+ """Handle current Codex hooks or the legacy ``notify`` JSON argument.
99
+
100
+ Current lifecycle hooks write a Claude-compatible JSON object to stdin.
101
+ Older Codex versions append an ``agent-turn-complete`` object to argv.
102
+ """
103
+ if not argv:
104
+ payload = _read_stdin(stdin, "codex")
105
+ if payload is not None:
106
+ _handle_lifecycle("codex", payload)
107
+ return
108
+
109
+ try:
110
+ payload = json.loads(argv[-1])
111
+ except (TypeError, ValueError) as e:
112
+ states.log(f"hook codex: notify parse failed ({e})")
113
+ return
114
+ if not isinstance(payload, dict):
115
+ states.log("hook codex: notify ignored (expected JSON object)")
116
+ return
117
+ if payload.get("type") != "agent-turn-complete":
118
+ return
119
+
120
+ identity = _identity("codex", payload)
121
+ if identity is None:
122
+ states.log("hook codex: agent-turn-complete ignored (missing thread id)")
123
+ return
124
+ owner, session_scope, aliases, _ = identity
125
+ states.log(f"hook codex: legacy complete owner={_owner_tag(owner)}")
126
+ states.set_state(
127
+ "done",
128
+ session=owner,
129
+ owner_prefix=session_scope,
130
+ owner_aliases=aliases,
131
+ )