rodecaster-mcp 0.1.0__py3-none-any.whl

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.
Files changed (45) hide show
  1. rodecaster_mcp/__init__.py +9 -0
  2. rodecaster_mcp/app_guard.py +57 -0
  3. rodecaster_mcp/config.py +99 -0
  4. rodecaster_mcp/device.py +402 -0
  5. rodecaster_mcp/domain/__init__.py +9 -0
  6. rodecaster_mcp/domain/channels.py +210 -0
  7. rodecaster_mcp/domain/mute.py +85 -0
  8. rodecaster_mcp/handlers.py +688 -0
  9. rodecaster_mcp/model/__init__.py +12 -0
  10. rodecaster_mcp/model/capabilities.py +109 -0
  11. rodecaster_mcp/model/diff.py +98 -0
  12. rodecaster_mcp/model/layout.py +134 -0
  13. rodecaster_mcp/model/redaction.py +102 -0
  14. rodecaster_mcp/model/sanitize.py +86 -0
  15. rodecaster_mcp/model/tree.py +229 -0
  16. rodecaster_mcp/protocol/__init__.py +13 -0
  17. rodecaster_mcp/protocol/change.py +171 -0
  18. rodecaster_mcp/protocol/constants.py +128 -0
  19. rodecaster_mcp/protocol/errors.py +15 -0
  20. rodecaster_mcp/protocol/hid_framing.py +259 -0
  21. rodecaster_mcp/protocol/juce_var.py +361 -0
  22. rodecaster_mcp/protocol/tcp_frame.py +30 -0
  23. rodecaster_mcp/protocol/valuetree.py +89 -0
  24. rodecaster_mcp/py.typed +0 -0
  25. rodecaster_mcp/safety/__init__.py +71 -0
  26. rodecaster_mcp/safety/allowlist.py +332 -0
  27. rodecaster_mcp/safety/approval.py +222 -0
  28. rodecaster_mcp/safety/denylist.py +231 -0
  29. rodecaster_mcp/safety/gate.py +164 -0
  30. rodecaster_mcp/safety/verify.py +139 -0
  31. rodecaster_mcp/safety/writer.py +264 -0
  32. rodecaster_mcp/schemas.py +214 -0
  33. rodecaster_mcp/server.py +578 -0
  34. rodecaster_mcp/session.py +291 -0
  35. rodecaster_mcp/transport/__init__.py +37 -0
  36. rodecaster_mcp/transport/base.py +111 -0
  37. rodecaster_mcp/transport/errors.py +23 -0
  38. rodecaster_mcp/transport/hid_transport.py +338 -0
  39. rodecaster_mcp/transport/mock.py +122 -0
  40. rodecaster_mcp/transport/outbound.py +86 -0
  41. rodecaster_mcp-0.1.0.dist-info/METADATA +293 -0
  42. rodecaster_mcp-0.1.0.dist-info/RECORD +45 -0
  43. rodecaster_mcp-0.1.0.dist-info/WHEEL +4 -0
  44. rodecaster_mcp-0.1.0.dist-info/entry_points.txt +2 -0
  45. rodecaster_mcp-0.1.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,9 @@
1
+ """rodecaster-mcp: an unofficial MCP server for RØDECaster consoles (Duo; Pro II in progress).
2
+
3
+ Not affiliated with or endorsed by RØDE Microphones. See PLAN.md for the
4
+ architecture and CLAUDE.md for the non-negotiable safety rules.
5
+ """
6
+
7
+ __version__ = "0.1.0"
8
+
9
+ __all__ = ["__version__"]
@@ -0,0 +1,57 @@
1
+ """Refuse to use the console while the RØDECaster App is running (rule 7, #32).
2
+
3
+ macOS does not make the vendor HID interface exclusive: hidapi lets this server
4
+ and the RØDECaster App open the console at the same time, but they can't share
5
+ it. At the desk on 2026-11-27 (H15, DUO-PROTOCOL §8.9), while this server was
6
+ connected, the app's changes never reached the console and the app hung at
7
+ "Synchronizing device". So the server checks for the app's process before it
8
+ opens the console, before every write, and (at most every
9
+ :data:`CHECK_INTERVAL_S`) before reads. If the app is running, it releases the
10
+ console and stops with a clear message.
11
+
12
+ The check looks for the app's executable name (``CFBundleExecutable``) with
13
+ ``pgrep -x``. If ``pgrep`` is missing, or the platform has no such app, the
14
+ check reports nothing and logs that it could not check.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import logging
20
+ import subprocess
21
+ from typing import Final
22
+
23
+ log = logging.getLogger(__name__)
24
+
25
+ CONFLICTING_APPS: Final[tuple[str, ...]] = ("RODECaster App",)
26
+ """Process names that hold the console's control interface. ``RODECaster App`` is the
27
+ executable of ``/Applications/RODECaster App.app`` (bundle ``com.rode.rodecastercomp``).
28
+ RØDE Central (``RODE Central``) is not listed: H15 tested only the RØDECaster App."""
29
+
30
+ CHECK_INTERVAL_S: Final[float] = 2.0
31
+ """How long a "not running" answer is reused for reads. Opens and writes always re-check."""
32
+
33
+ APP_RUNNING_MESSAGE: Final[str] = (
34
+ "The RØDECaster App is running, and it can't share the console with this server: "
35
+ "while both are connected the app hangs at 'Synchronizing device' (CLAUDE.md rule 7, "
36
+ "H15). This server has released the console and sent nothing. Quit the RØDECaster "
37
+ "App, then call again."
38
+ )
39
+
40
+ _warned_unavailable = False
41
+
42
+
43
+ def running_conflicting_apps() -> list[str]:
44
+ """Names from :data:`CONFLICTING_APPS` that have a running process."""
45
+ global _warned_unavailable
46
+ found: list[str] = []
47
+ for name in CONFLICTING_APPS:
48
+ try:
49
+ r = subprocess.run(["pgrep", "-x", name], capture_output=True, timeout=2.0, check=False)
50
+ except (OSError, subprocess.SubprocessError) as exc:
51
+ if not _warned_unavailable:
52
+ log.warning("cannot check for the RØDECaster App (%s); rule 7 is unguarded", exc)
53
+ _warned_unavailable = True
54
+ return []
55
+ if r.returncode == 0:
56
+ found.append(name)
57
+ return found
@@ -0,0 +1,99 @@
1
+ """Environment flags shared by the server, session and safety layer."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ from collections.abc import Mapping
7
+ from typing import Final
8
+
9
+ ENV_DRY_RUN: Final[str] = "RCD_DRY_RUN"
10
+ """Encode and log writes instead of sending them. Default ON."""
11
+
12
+ ENV_READ_ONLY: Final[str] = "RCD_READ_ONLY"
13
+ """Register no mutating MCP tools. Default OFF."""
14
+
15
+ ENV_WRITE_TIER: Final[str] = "RCD_WRITE_TIER"
16
+ """Highest allowlist tier the MCP server's write gate accepts (1-3). Default 1.
17
+
18
+ Tier 1 is the Phase 3 smoke-test set (strip mute, HPF on/off). Raising it lets
19
+ more allowlisted properties through the gate; it never bypasses dry-run, the
20
+ denylist or the hardware-verified approval check."""
21
+
22
+ ENV_APPROVAL: Final[str] = "RCD_APPROVAL"
23
+ """How a first real write of an unverified property gets the owner's approval.
24
+
25
+ ``off`` (default): never; such writes are refused (CLAUDE.md rule 8).
26
+ ``elicit``: the server asks the human through MCP elicitation, with a typed
27
+ confirmation code (see :mod:`rodecaster_mcp.safety.approval`). Has no
28
+ effect while dry-run is on, because dry-run never sends."""
29
+
30
+ REMOVED_ENV_FLAGS: Final[dict[str, str]] = {
31
+ "RCD_SEND_MODE_APP": (
32
+ "removed: report 1 is never sent (checklist H1, fw 1.7.7: session-open alone "
33
+ "produces the full sync)"
34
+ ),
35
+ "RCD_MUTE_POLARITY": (
36
+ "removed: mute polarity is hardware-verified, true = muted "
37
+ "(checklist H3, fw 1.7.7, 2026-11-25)"
38
+ ),
39
+ }
40
+ """Flags that older versions read. Setting one now only logs a warning."""
41
+
42
+ _TRUE = frozenset({"1", "true", "yes", "on"})
43
+ _FALSE = frozenset({"0", "false", "no", "off"})
44
+
45
+
46
+ def env_flag(env: Mapping[str, str], name: str, *, default: bool) -> bool:
47
+ """Parse a boolean flag. Unset **or empty** means the default (PR #5 review L9):
48
+ an empty ``RCD_DRY_RUN=`` in a Desktop ``env`` block must not turn dry-run off."""
49
+ raw = env.get(name)
50
+ if raw is None or not raw.strip():
51
+ return default
52
+ value = raw.strip().lower()
53
+ if value in _TRUE:
54
+ return True
55
+ if value in _FALSE:
56
+ return False
57
+ raise ValueError(f"{name} must be one of {sorted(_TRUE | _FALSE)}, got {raw!r}")
58
+
59
+
60
+ def _env(env: Mapping[str, str] | None) -> Mapping[str, str]:
61
+ return os.environ if env is None else env
62
+
63
+
64
+ def dry_run_from_env(env: Mapping[str, str] | None = None) -> bool:
65
+ return env_flag(_env(env), ENV_DRY_RUN, default=True)
66
+
67
+
68
+ def read_only_from_env(env: Mapping[str, str] | None = None) -> bool:
69
+ return env_flag(_env(env), ENV_READ_ONLY, default=False)
70
+
71
+
72
+ def write_tier_from_env(env: Mapping[str, str] | None = None) -> int:
73
+ raw = _env(env).get(ENV_WRITE_TIER)
74
+ if raw is None or not raw.strip():
75
+ return 1
76
+ try:
77
+ tier = int(raw.strip())
78
+ except ValueError:
79
+ raise ValueError(f"{ENV_WRITE_TIER} must be 1, 2 or 3, got {raw!r}") from None
80
+ if tier not in (1, 2, 3):
81
+ raise ValueError(f"{ENV_WRITE_TIER} must be 1, 2 or 3, got {raw!r}")
82
+ return tier
83
+
84
+
85
+ def removed_flags_set(env: Mapping[str, str] | None = None) -> dict[str, str]:
86
+ """The removed flags present in ``env``, with why each was removed."""
87
+ e = _env(env)
88
+ return {name: why for name, why in REMOVED_ENV_FLAGS.items() if name in e}
89
+
90
+
91
+ def approval_from_env(env: Mapping[str, str] | None = None) -> str:
92
+ """``off`` or ``elicit``. Unset or empty means ``off``."""
93
+ raw = _env(env).get(ENV_APPROVAL)
94
+ if raw is None or not raw.strip():
95
+ return "off"
96
+ value = raw.strip().lower()
97
+ if value not in ("off", "elicit"):
98
+ raise ValueError(f"{ENV_APPROVAL} must be 'off' or 'elicit', got {raw!r}")
99
+ return value
@@ -0,0 +1,402 @@
1
+ """The MCP server's one long-lived device connection.
2
+
3
+ :class:`DeviceManager` owns a single :class:`~.session.DeviceSession` and the
4
+ :class:`~.safety.SafeWriter` built on it. MCP handlers get a tree to read and a
5
+ writer to write through; they never see the transport, and the session's
6
+ outbound path is only reachable through the writer (gate, allowlist, denylist,
7
+ dry-run, approval, verify).
8
+
9
+ **Lazy connect.** The device is opened on the first tool or resource call that
10
+ needs it, not when the server starts:
11
+
12
+ * Claude Code / Desktop start every configured MCP server with each session.
13
+ Opening at startup would hold the console even in sessions that never use
14
+ it. macOS does not make the handle exclusive (H15): the RØDECaster App can
15
+ open it too, but the two can't share it and the app hangs. So the manager
16
+ also refuses, and releases the console, while the app is running
17
+ (:mod:`~.app_guard`, rule 7, #32).
18
+ * Starting without a device still works: tools and prompts are listed, and a
19
+ call reports the reason clearly (not connected, busy, sync timeout).
20
+ * A failed open is not sticky. Quit the RØDE app, call again, and it connects.
21
+
22
+ **Release.** Once open, the session stays open until the server exits or
23
+ :meth:`release` is called (the ``release_device`` tool), which hands the
24
+ console back to the RØDE app. The next call reconnects lazily. An explicit
25
+ tool was chosen over an idle timeout: a timeout would silently end resource
26
+ subscriptions mid-show and reconnect (a full sync) at unpredictable times,
27
+ while the cost of an explicit release is only that the user has to ask.
28
+
29
+ **One transport for the manager's lifetime** (review L8). Reconnects reopen
30
+ the same transport object, so the HID transport's hung-reader orphan guard
31
+ (review N-3/P2-1) still applies after a reconnect.
32
+
33
+ **Locking** (review M1, M2, L1, L2). Lock order is always manager lock, then
34
+ session lock, and nothing holding the session lock takes the manager lock.
35
+
36
+ * Reads run inside :meth:`read`, which pumps and calls the reader *under the
37
+ session lock*, so the poller cannot mutate the tree mid-read.
38
+ * Writes run inside :meth:`write_txn`: resolve the target from the tree and
39
+ write it in one critical section (the session lock is an RLock that
40
+ ``SafeWriter.write`` re-enters).
41
+ * A failure only drops the session that failed, never a newer healthy one.
42
+ * A dropped session is closed for good (``DeviceSession.close``): a call that
43
+ still holds it is refused at its next pump or write, even though the shared
44
+ transport may have been reopened for the successor (re-review R-H1).
45
+ * ``release`` holds the manager lock while the session closes, which waits for
46
+ an in-flight write to finish; other calls queue behind it (re-review R-L1).
47
+ That is deliberate: releasing outside the lock would let a successor reopen
48
+ the shared transport under a write that is still verifying.
49
+
50
+ A background poller (:meth:`poll_changes`, driven by the server lifespan)
51
+ applies inbound notifications so the cache stays current and resource
52
+ subscribers hear about changes. The real transport's reader thread drains the
53
+ device independently of this (rule 3).
54
+ """
55
+
56
+ from __future__ import annotations
57
+
58
+ import json
59
+ import logging
60
+ import threading
61
+ import time
62
+ from collections.abc import Callable, Iterator
63
+ from contextlib import contextmanager
64
+ from dataclasses import dataclass, field
65
+
66
+ from rodecaster_mcp import app_guard
67
+ from rodecaster_mcp.domain import channels as chans
68
+ from rodecaster_mcp.model.layout import Layout, discover_layout
69
+ from rodecaster_mcp.model.tree import StateTree
70
+ from rodecaster_mcp.protocol import juce_var as jv
71
+ from rodecaster_mcp.safety.allowlist import Tier
72
+ from rodecaster_mcp.safety.approval import OneShotGrants, grants_then
73
+ from rodecaster_mcp.safety.gate import WriteGate
74
+ from rodecaster_mcp.safety.writer import (
75
+ ApprovalHook,
76
+ SafeWriter,
77
+ SentUnverifiedError,
78
+ refuse_unverified,
79
+ )
80
+ from rodecaster_mcp.session import DeviceSession, SessionNotReadyError, SyncTimeoutError
81
+ from rodecaster_mcp.transport.base import Transport
82
+ from rodecaster_mcp.transport.errors import (
83
+ DeviceBusyError,
84
+ DeviceNotFoundError,
85
+ TransportError,
86
+ )
87
+
88
+ log = logging.getLogger(__name__)
89
+
90
+ TransportFactory = Callable[[], Transport]
91
+
92
+ STATE_URI = "rodecaster://state"
93
+ PROTOCOL_URI = "rodecaster://protocol"
94
+ CHANNEL_URI_PREFIX = "rodecaster://channels/"
95
+
96
+
97
+ class DeviceUnavailableError(RuntimeError):
98
+ """The console could not be reached; the message says why and what to do."""
99
+
100
+
101
+ def default_transport_factory() -> Transport:
102
+ """The real USB HID transport. Imported lazily; tests always inject a mock."""
103
+ from rodecaster_mcp.transport.hid_transport import HidTransport
104
+
105
+ return HidTransport()
106
+
107
+
108
+ @dataclass
109
+ class _Snapshot:
110
+ session: DeviceSession | None = None
111
+ generation: int = -1
112
+ layout: Layout | None = None
113
+ channels: dict[str, str] = field(default_factory=dict)
114
+
115
+
116
+ class DeviceManager:
117
+ def __init__(
118
+ self,
119
+ *,
120
+ dry_run: bool,
121
+ write_tier: int = 1,
122
+ transport_factory: TransportFactory | None = None,
123
+ approval: ApprovalHook = refuse_unverified,
124
+ sync_timeout_s: float = 10.0,
125
+ ) -> None:
126
+ self.dry_run = dry_run
127
+ self.write_tier = Tier(write_tier)
128
+ self._factory = transport_factory or default_transport_factory
129
+ self._approval = approval
130
+ self.grants = OneShotGrants()
131
+ """One-shot owner approvals (``RCD_APPROVAL=elicit``), spent before ``approval``."""
132
+ self._sync_timeout = sync_timeout_s
133
+ self._lock = threading.RLock()
134
+ self._transport: Transport | None = None
135
+ self._session: DeviceSession | None = None
136
+ self._writer: SafeWriter | None = None
137
+ self.last_error: str | None = None
138
+ self.reconnects = 0
139
+ """Automatic reconnects after a session died under a read or resync (issue #34)."""
140
+ self.last_reconnect_reason: str | None = None
141
+ """Why the most recent automatic reconnect happened (kept after it succeeds)."""
142
+ self._snap = _Snapshot()
143
+ self._apps_checked_until = 0.0
144
+
145
+ # --- rule 7: the RØDECaster App ---------------------------------------------
146
+
147
+ def _guard_apps(self, *, fresh: bool) -> None:
148
+ """Raise (and release the console) if the RØDECaster App is running (#32).
149
+
150
+ ``fresh``: always check (opens, writes, resyncs). Otherwise a recent
151
+ "not running" answer is reused for :data:`~.app_guard.CHECK_INTERVAL_S`.
152
+ """
153
+ now = time.monotonic()
154
+ if not fresh and now < self._apps_checked_until:
155
+ return
156
+ running = app_guard.running_conflicting_apps()
157
+ if not running:
158
+ self._apps_checked_until = now + app_guard.CHECK_INTERVAL_S
159
+ return
160
+ self._apps_checked_until = 0.0
161
+ with self._lock:
162
+ if self._session is not None:
163
+ log.warning("releasing the console: %s is running (rule 7)", ", ".join(running))
164
+ self._drop()
165
+ self.last_error = f"{', '.join(running)} is running"
166
+ raise DeviceUnavailableError(app_guard.APP_RUNNING_MESSAGE)
167
+
168
+ # --- lifecycle -------------------------------------------------------------
169
+
170
+ @property
171
+ def connected(self) -> bool:
172
+ with self._lock:
173
+ return self._session is not None and self._session.tree is not None
174
+
175
+ def _ensure(self) -> tuple[DeviceSession, SafeWriter]:
176
+ """The open session and its writer, connecting on first use (one lock hold)."""
177
+ with self._lock:
178
+ if self._session is not None and self._writer is not None:
179
+ return self._session, self._writer
180
+ self._guard_apps(fresh=True)
181
+ if self._transport is None:
182
+ self._transport = self._factory()
183
+ session = DeviceSession(
184
+ self._transport, dry_run=self.dry_run, sync_timeout_s=self._sync_timeout
185
+ )
186
+ try:
187
+ session.open()
188
+ except BaseException as exc:
189
+ # Never leave a half-open, exclusive handle behind (review M3.2).
190
+ try:
191
+ session.close()
192
+ except Exception: # pragma: no cover - best effort cleanup
193
+ log.exception("closing a session that failed to open")
194
+ if isinstance(exc, TransportError | OSError | ImportError):
195
+ self.last_error = f"{type(exc).__name__}: {exc}"
196
+ raise DeviceUnavailableError(_unavailable(exc)) from exc
197
+ raise
198
+ writer = SafeWriter(
199
+ session,
200
+ gate=WriteGate(max_tier=self.write_tier),
201
+ dry_run=self.dry_run,
202
+ approval=grants_then(self.grants, self._approval),
203
+ )
204
+ tree = session.require_tree()
205
+ self._snap = _Snapshot(session, tree.generation, *_fingerprint(tree))
206
+ self._session, self._writer = session, writer
207
+ self.last_error = None
208
+ log.info("connected to the console; dry_run=%s", self.dry_run)
209
+ return session, writer
210
+
211
+ def read[T](self, fn: Callable[[StateTree], T]) -> T:
212
+ """Pump, then run ``fn`` on a consistent tree under the session lock (M1).
213
+
214
+ **Reconnects once** (issue #34). If the session dies under a read, for
215
+ example hidapi read errors stopped the reader, the dead session is
216
+ dropped and the read is retried on a fresh one. A read changes no
217
+ console state, so retrying is safe. Not retried: a session dropped by
218
+ :meth:`release` (the user handed the console back) and a failure on
219
+ the fresh session. Writes never retry automatically, because a failure
220
+ mid-write leaves it unknown whether the frame went out.
221
+ """
222
+ for attempt in range(2):
223
+ self._guard_apps(fresh=False)
224
+ session, _writer = self._ensure()
225
+ try:
226
+ with session.lock:
227
+ session.pump()
228
+ return fn(session.require_tree())
229
+ except (TransportError, SessionNotReadyError) as exc:
230
+ dropped = self._fail(exc, session)
231
+ if attempt == 0 and dropped:
232
+ self.reconnects += 1
233
+ self.last_reconnect_reason = f"{type(exc).__name__}: {exc}"
234
+ log.warning("reconnecting once after a failed read: %s", exc)
235
+ continue
236
+ raise DeviceUnavailableError(_unavailable(exc)) from exc
237
+ raise AssertionError("unreachable") # pragma: no cover
238
+
239
+ def tree(self) -> StateTree:
240
+ """The current tree, after applying pending notifications.
241
+
242
+ Only for callers that do not iterate it concurrently with the poller
243
+ (tests, single-threaded use). Handlers use :meth:`read`.
244
+ """
245
+ return self.read(lambda tree: tree)
246
+
247
+ @contextmanager
248
+ def write_txn(self) -> Iterator[tuple[StateTree, SafeWriter]]:
249
+ """Resolve-and-write in one critical section (review M2).
250
+
251
+ Yields the pumped tree and the SafeWriter of *that* session while the
252
+ session lock is held, so a resync or poll cannot shift paths between
253
+ the lookup and the write.
254
+ """
255
+ self._guard_apps(fresh=True)
256
+ session, writer = self._ensure()
257
+ try:
258
+ with session.lock:
259
+ session.pump()
260
+ yield session.require_tree(), writer
261
+ except SentUnverifiedError as exc:
262
+ # The frame went out; drop the dead session but keep the "sent" error (#47).
263
+ self._fail(exc.cause, session)
264
+ raise
265
+ except (TransportError, SessionNotReadyError) as exc:
266
+ self._fail(exc, session)
267
+ raise DeviceUnavailableError(_unavailable(exc)) from exc
268
+
269
+ def resync(self) -> StateTree:
270
+ """Request a fresh full sync (session-open only). Clears a stale tree.
271
+
272
+ Reconnects once on a dead session, like :meth:`read`: a resync only
273
+ sends session-open, which changes no console state (issue #34).
274
+ """
275
+ for attempt in range(2):
276
+ self._guard_apps(fresh=True)
277
+ session, _writer = self._ensure()
278
+ try:
279
+ return session.resync()
280
+ except TransportError as exc:
281
+ dropped = self._fail(exc, session)
282
+ # A sync timeout usually means something else holds the console
283
+ # (the RØDECaster App): reconnecting would send session-open again
284
+ # and take it back. Stop instead (#50).
285
+ if attempt == 0 and dropped and not isinstance(exc, SyncTimeoutError):
286
+ self.reconnects += 1
287
+ self.last_reconnect_reason = f"{type(exc).__name__}: {exc}"
288
+ log.warning("reconnecting once after a failed resync: %s", exc)
289
+ continue
290
+ raise DeviceUnavailableError(_unavailable(exc)) from exc
291
+ raise AssertionError("unreachable") # pragma: no cover
292
+
293
+ def release(self) -> bool:
294
+ """Close the session and release the console. True if one was open."""
295
+ with self._lock:
296
+ was_open = self._session is not None
297
+ self._drop()
298
+ return was_open
299
+
300
+ def close(self) -> None:
301
+ self.release()
302
+
303
+ def _drop(self) -> None:
304
+ if self._session is not None:
305
+ try:
306
+ self._session.close()
307
+ except Exception: # pragma: no cover - best effort cleanup
308
+ log.exception("error closing the device session")
309
+ self._session = None
310
+ self._writer = None
311
+ self._snap = _Snapshot()
312
+
313
+ def _fail(self, exc: BaseException, session: DeviceSession) -> bool:
314
+ """Drop ``session`` after a failure, but only if it is still the current one (L1).
315
+
316
+ True if this call dropped it; False if it was already gone (released, or
317
+ replaced by a newer session), in which case nothing should reconnect.
318
+ """
319
+ with self._lock:
320
+ if self._session is not session:
321
+ return False
322
+ self.last_error = f"{type(exc).__name__}: {exc}"
323
+ log.warning("device session failed; it will reconnect on the next call: %s", exc)
324
+ self._drop()
325
+ return True
326
+
327
+ # --- change polling (resource subscriptions) ------------------------------
328
+
329
+ def poll_changes(self) -> list[str]:
330
+ """Apply pending notifications; return the resource URIs whose content changed.
331
+
332
+ Never connects: subscriptions start reporting once something has opened
333
+ the device. Safe to call from a worker thread. The manager lock is not
334
+ held while pumping, so a long write never blocks other callers here.
335
+ """
336
+ with self._lock:
337
+ session = self._session
338
+ if session is None or session.closed:
339
+ return []
340
+ try:
341
+ # Hand the console back if the app was opened while we hold it (#32).
342
+ self._guard_apps(fresh=False)
343
+ except DeviceUnavailableError:
344
+ return [STATE_URI]
345
+ try:
346
+ with session.lock:
347
+ if session.closed: # released while we waited: never pump a dropped session
348
+ return []
349
+ session.pump()
350
+ tree = session.tree
351
+ if tree is None:
352
+ return []
353
+ return self._changed_uris(session, tree)
354
+ except TransportError as exc:
355
+ if session.closed:
356
+ return []
357
+ self._fail(exc, session)
358
+ return [STATE_URI]
359
+
360
+ def _changed_uris(self, session: DeviceSession, tree: StateTree) -> list[str]:
361
+ snap = self._snap
362
+ if snap.session is not session or tree.generation == snap.generation:
363
+ return []
364
+ layout, current = _fingerprint(tree)
365
+ uris = [STATE_URI]
366
+ if layout != snap.layout:
367
+ uris.append(PROTOCOL_URI)
368
+ for cid, fp in current.items():
369
+ if snap.channels.get(cid) != fp:
370
+ uris.append(CHANNEL_URI_PREFIX + cid)
371
+ self._snap = _Snapshot(session, tree.generation, layout, current)
372
+ return uris
373
+
374
+
375
+ def _fingerprint(tree: StateTree) -> tuple[Layout, dict[str, str]]:
376
+ layout = discover_layout(tree)
377
+ return layout, {c.id: _channel_fingerprint(tree, c.path) for c in chans.channels(tree)}
378
+
379
+
380
+ def _channel_fingerprint(tree: StateTree, path: tuple[int, ...]) -> str:
381
+ node = tree.node_at(path)
382
+ if node is None:
383
+ return ""
384
+ props = {k: jv.to_python(v) for k, v in node.properties.items()}
385
+ return json.dumps([tree.stale, props], sort_keys=True, default=str)
386
+
387
+
388
+ def _unavailable(exc: BaseException) -> str:
389
+ """A message that matches the actual cause (review L8)."""
390
+ head = "The RØDECaster console is not available"
391
+ if isinstance(exc, ImportError):
392
+ return f"{head}: the hidapi Python binding could not be loaded ({exc}). Run `uv sync`."
393
+ if isinstance(exc, DeviceBusyError):
394
+ return (
395
+ f"{head}: {exc} If another Claude session is using this server, call "
396
+ "release_device there."
397
+ )
398
+ if isinstance(exc, DeviceNotFoundError):
399
+ return f"{head}: {exc}"
400
+ if isinstance(exc, SyncTimeoutError):
401
+ return f"{head}: {exc}"
402
+ return f"{head}: {exc} Call the tool again to reconnect."
@@ -0,0 +1,9 @@
1
+ """Domain layer: friendly names <-> device paths, and mute polarity.
2
+
3
+ - :mod:`.mute`: the single place that maps "muted" to a wire bool
4
+ (hardware-verified, true = muted; CLAUDE.md rule 4).
5
+ - :mod:`.channels`: channel strips ("Channel N" by strip position), mix cells
6
+ and processing toggles, all discovered from the live tree. Source and bus
7
+ labels are prior-art hints only (checklists H7, H8); channels are never
8
+ looked up by them until the mapping is hardware-verified.
9
+ """