lightfall-voice 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.
@@ -0,0 +1 @@
1
+ """Voice notifications plugin for Lightfall."""
@@ -0,0 +1,78 @@
1
+ """Audio helpers shared by the STT service and the recorder (no Qt)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import numpy as np
6
+
7
+ RATE = 16000
8
+ CHUNK_SAMPLES = 1600
9
+
10
+
11
+ def pcm16_to_float32(b: bytes) -> np.ndarray:
12
+ return np.frombuffer(b, dtype="<i2").astype(np.float32) / 32768.0
13
+
14
+
15
+ def float32_to_pcm16(a) -> bytes:
16
+ arr = np.clip(np.asarray(a, dtype=np.float32), -1.0, 1.0)
17
+ return np.round(arr * 32767.0).astype("<i2").tobytes()
18
+
19
+
20
+ def resample(a: np.ndarray, src_rate: int, dst_rate: int = RATE) -> np.ndarray:
21
+ """Linear resample via np.interp."""
22
+ a = np.asarray(a, dtype=np.float32)
23
+ if src_rate == dst_rate or len(a) == 0:
24
+ return a
25
+ n_out = int(round(len(a) * dst_rate / src_rate))
26
+ x_out = np.arange(n_out) * (src_rate / dst_rate)
27
+ return np.interp(x_out, np.arange(len(a)), a).astype(np.float32)
28
+
29
+
30
+ def rms(a) -> float:
31
+ arr = np.asarray(a, dtype=np.float64)
32
+ if arr.size == 0:
33
+ return 0.0
34
+ return float(np.sqrt(np.mean(arr * arr)))
35
+
36
+
37
+ class StreamResampler:
38
+ """Stateful mono resampler: windowed-sinc low-pass, then linear interpolation.
39
+
40
+ Filter history and the fractional read position carry across ``process`` calls,
41
+ so block size does not affect the output. numpy only.
42
+ """
43
+
44
+ TAPS = 65
45
+
46
+ def __init__(self, src_rate: int, dst_rate: int = RATE):
47
+ self.src_rate = src_rate
48
+ self.dst_rate = dst_rate
49
+ self._passthrough = src_rate == dst_rate
50
+ self._step = src_rate / dst_rate
51
+ fc = 0.45 * min(src_rate, dst_rate) / src_rate # cycles per input sample
52
+ n = np.arange(self.TAPS) - (self.TAPS - 1) / 2
53
+ h = 2 * fc * np.sinc(2 * fc * n) * np.hamming(self.TAPS)
54
+ self._h = h / h.sum()
55
+ self._hist = np.zeros(self.TAPS - 1, dtype=np.float64)
56
+ self._buf = np.zeros(0, dtype=np.float64)
57
+ self._pos = 0.0
58
+
59
+ def process(self, a) -> np.ndarray:
60
+ a = np.asarray(a, dtype=np.float32)
61
+ if self._passthrough or len(a) == 0:
62
+ return a
63
+ x = np.concatenate([self._hist, a.astype(np.float64)])
64
+ filtered = np.convolve(x, self._h, mode="valid") # len(a) samples
65
+ self._hist = x[-(self.TAPS - 1):]
66
+ buf = np.concatenate([self._buf, filtered])
67
+ last = len(buf) - 1
68
+ if self._pos > last:
69
+ self._buf = buf
70
+ return np.zeros(0, dtype=np.float32)
71
+ n_out = int((last - self._pos) // self._step) + 1
72
+ xs = self._pos + np.arange(n_out) * self._step
73
+ out = np.interp(xs, np.arange(len(buf)), buf).astype(np.float32)
74
+ new_pos = self._pos + n_out * self._step
75
+ k = min(int(new_pos), len(buf)) # excess stays in pos for the next block
76
+ self._buf = buf[k:]
77
+ self._pos = new_pos - k
78
+ return out
@@ -0,0 +1,80 @@
1
+ """Fire-and-forget TCP client for the voice daemon's JSON line protocol.
2
+
3
+ One background worker drains a queue; every send opens a short-lived
4
+ connection. Any failure drops the message -- a missed notification is
5
+ always better than a blocked or crashing GUI.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ import queue
12
+ import socket
13
+ import threading
14
+ import time
15
+
16
+ from lightfall.utils.logging import logger
17
+
18
+ _SENTINEL = object()
19
+
20
+
21
+ class DaemonClient:
22
+ def __init__(
23
+ self,
24
+ host: str = "127.0.0.1",
25
+ port: int = 52849,
26
+ connect_timeout: float = 2.0,
27
+ ) -> None:
28
+ self._host = host
29
+ self._port = port
30
+ self._timeout = connect_timeout
31
+ self._queue: queue.Queue = queue.Queue()
32
+ self._thread = threading.Thread(
33
+ target=self._run, name="lightfall-voice-daemon-client", daemon=True
34
+ )
35
+ self._thread.start()
36
+
37
+ def configure(self, host: str, port: int) -> None:
38
+ self._queue.put({"_configure": (host, int(port))})
39
+
40
+ def speak(self, message: str, voice: str | None = None, ttl: float | None = None) -> None:
41
+ deadline = time.monotonic() + ttl if ttl is not None else None
42
+ self._queue.put(
43
+ {
44
+ "action": "speak",
45
+ "args": {"message": message, "voice": voice},
46
+ "_deadline": deadline,
47
+ }
48
+ )
49
+
50
+ def stop(self) -> None:
51
+ self._queue.put(_SENTINEL)
52
+ self._thread.join(timeout=3)
53
+
54
+ def _run(self) -> None:
55
+ while True:
56
+ item = self._queue.get()
57
+ if item is _SENTINEL:
58
+ return
59
+ if isinstance(item, dict) and "_configure" in item:
60
+ # Apply configuration change (maintains queue ordering)
61
+ self._host, self._port = item["_configure"]
62
+ continue
63
+ deadline = item.get("_deadline") if isinstance(item, dict) else None
64
+ if deadline is not None and time.monotonic() >= deadline:
65
+ logger.debug("voice daemon message expired before send, dropping")
66
+ continue
67
+ request = {k: v for k, v in item.items() if k != "_deadline"}
68
+ try:
69
+ self._send(request)
70
+ except Exception as e:
71
+ logger.debug("voice daemon unreachable, dropping message: {}", e)
72
+
73
+ def _send(self, request: dict) -> None:
74
+ with socket.create_connection((self._host, self._port), timeout=self._timeout) as sock:
75
+ sock.sendall((json.dumps(request) + "\n").encode("utf-8"))
76
+ sock.settimeout(self._timeout)
77
+ try:
78
+ sock.recv(4096) # read-and-ignore the response line
79
+ except OSError:
80
+ pass
@@ -0,0 +1,32 @@
1
+ """Normalized voice events. Priority follows daemon semantics:
2
+ high = non-interruptible (permission, error); low = interruptible chatter."""
3
+
4
+ from __future__ import annotations
5
+
6
+ from dataclasses import dataclass
7
+
8
+
9
+ @dataclass(frozen=True)
10
+ class VoiceEvent:
11
+ agent_name: str
12
+ kind: str # "tool" | "summary" | "permission" | "error"
13
+ text: str
14
+ priority: str # "high" | "low"
15
+ timestamp: float
16
+ tool_name: str | None = None
17
+
18
+
19
+ def tool_event(agent_name: str, tool_name: str, text: str, now: float) -> VoiceEvent:
20
+ return VoiceEvent(agent_name, "tool", text, "low", now, tool_name)
21
+
22
+
23
+ def summary_event(agent_name: str, text: str, now: float) -> VoiceEvent:
24
+ return VoiceEvent(agent_name, "summary", text, "low", now)
25
+
26
+
27
+ def permission_event(agent_name: str, text: str, now: float) -> VoiceEvent:
28
+ return VoiceEvent(agent_name, "permission", text, "high", now)
29
+
30
+
31
+ def error_event(agent_name: str, text: str, now: float) -> VoiceEvent:
32
+ return VoiceEvent(agent_name, "error", text, "high", now)
@@ -0,0 +1,30 @@
1
+ """Plugin manifest for lightfall-voice."""
2
+
3
+ from importlib.metadata import PackageNotFoundError, version
4
+
5
+ from lightfall.plugins.manifest import PluginEntry, PluginManifest
6
+
7
+ try:
8
+ _version = version("lightfall-voice")
9
+ except PackageNotFoundError:
10
+ _version = "0.0.0"
11
+
12
+ manifest = PluginManifest(
13
+ name="lightfall-voice",
14
+ version=_version,
15
+ description="Spoken notifications for Claude agent sessions via the local voice daemon",
16
+ plugins=[
17
+ # preload=True so on_loaded() runs at startup and starts the VoiceService.
18
+ PluginEntry(
19
+ type_name="settings",
20
+ name="voice",
21
+ import_path="lightfall_voice.settings:VoiceSettingsPlugin",
22
+ preload=True,
23
+ ),
24
+ PluginEntry(
25
+ type_name="service",
26
+ name="stt",
27
+ import_path="lightfall_voice.stt_plugin:SttServicePlugin",
28
+ ),
29
+ ],
30
+ )
@@ -0,0 +1,141 @@
1
+ """Title-bar mute button on the Assistant panel, acting on the visible session.
2
+
3
+ A checkable QAction added through ``BasePanel.add_title_bar_action`` (rendered
4
+ as a ``PanelTitleButton``). Checked = the visible tab's agent is muted. It
5
+ follows tab switches via ``ClaudePanel.current_session_changed`` and mutes
6
+ made elsewhere (the preferences page) via ``VoiceService.settings_changed``.
7
+ Permission requests and errors still speak while muted (see policy.py).
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from typing import Callable
13
+
14
+ from PySide6.QtCore import QObject
15
+ from PySide6.QtGui import QAction
16
+
17
+ from lightfall.utils.logging import logger
18
+
19
+ from lightfall_voice.policy import _KEYS, VoiceSettings
20
+ from lightfall_voice.stt.controller import CLAUDE_PANEL_ID, _alive, _default_window_lookup
21
+
22
+ _ICON_SPEAKING = "mdi6.volume-high"
23
+ _ICON_MUTED = "mdi6.volume-off"
24
+
25
+
26
+ def save_agent_overrides(get_prefs: Callable[[], object]) -> Callable[[VoiceSettings], None]:
27
+ """A ``save`` for SessionMuteAction that writes only ``voice.agent_overrides``.
28
+
29
+ A mute click changes nothing else, so no other voice key is (re)written.
30
+ ``get_prefs`` is called on each save (the preferences store may be replaced).
31
+ """
32
+
33
+ def save(settings: VoiceSettings) -> None:
34
+ get_prefs().set(
35
+ _KEYS["agent_overrides"],
36
+ {name: {"muted": o.muted, "voice": o.voice} for name, o in settings.agent_overrides.items()},
37
+ )
38
+
39
+ return save
40
+
41
+
42
+ def _default_panel_lookup():
43
+ window = _default_window_lookup()
44
+ get_panel = getattr(window, "get_panel", None)
45
+ return get_panel(CLAUDE_PANEL_ID) if callable(get_panel) else None
46
+
47
+
48
+ def _icon(name: str):
49
+ try:
50
+ import qtawesome as qta
51
+
52
+ from lightfall.ui.theme import ThemeManager
53
+
54
+ color = ThemeManager.get_instance().colors.text_secondary
55
+ except Exception:
56
+ color = "#808080"
57
+ try:
58
+ return qta.icon(name, color=color)
59
+ except Exception:
60
+ return None
61
+
62
+
63
+ class SessionMuteAction(QObject):
64
+ def __init__(
65
+ self,
66
+ service,
67
+ save: Callable[[VoiceSettings], None],
68
+ panel_lookup: Callable[[], object] | None = None,
69
+ ) -> None:
70
+ super().__init__()
71
+ self._service = service
72
+ self._save = save
73
+ self._panel_lookup = panel_lookup or _default_panel_lookup
74
+ self._panel = None
75
+ self._action: QAction | None = None
76
+ service.settings_changed.connect(self.refresh)
77
+
78
+ @property
79
+ def action(self) -> QAction | None:
80
+ return self._action
81
+
82
+ def install(self) -> None:
83
+ """Add the button to the Assistant panel once it exists; later calls
84
+ (every AgentBus.agents_changed, e.g. a rebuilt session) just refresh."""
85
+ if self._panel is not None and _alive(self._panel):
86
+ self.refresh()
87
+ return
88
+ try:
89
+ panel = self._panel_lookup()
90
+ except Exception:
91
+ logger.exception("lightfall-voice: Assistant panel lookup failed")
92
+ return
93
+ if panel is None or not hasattr(panel, "add_title_bar_action"):
94
+ return
95
+ action = QAction(panel)
96
+ action.setCheckable(True)
97
+ action.triggered.connect(self._on_triggered)
98
+ panel.add_title_bar_action(action)
99
+ signal = getattr(panel, "current_session_changed", None)
100
+ if signal is not None:
101
+ signal.connect(self.refresh)
102
+ self._panel, self._action = panel, action
103
+ self.refresh()
104
+
105
+ def _current_agent_name(self) -> str | None:
106
+ if self._panel is None or not _alive(self._panel):
107
+ return None
108
+ widget = self._panel.current_assistant_widget()
109
+ return self._service.agent_name_of(widget) if widget is not None else None
110
+
111
+ def refresh(self) -> None:
112
+ action = self._action
113
+ if action is None or not _alive(action):
114
+ return
115
+ name = self._current_agent_name()
116
+ muted = name is not None and self._service.is_agent_muted(name)
117
+ action.setEnabled(name is not None)
118
+ action.setChecked(muted)
119
+ icon = _icon(_ICON_MUTED if muted else _ICON_SPEAKING)
120
+ if icon is not None:
121
+ action.setIcon(icon)
122
+ if name is None:
123
+ tip = "Voice notifications"
124
+ elif muted:
125
+ tip = f"Unmute voice notifications for '{name}'"
126
+ else:
127
+ tip = f"Mute voice notifications for '{name}'"
128
+ action.setToolTip(tip)
129
+ action.setText(tip)
130
+
131
+ def _on_triggered(self, checked: bool) -> None:
132
+ name = self._current_agent_name()
133
+ if name is None:
134
+ self.refresh()
135
+ return
136
+ try:
137
+ settings = self._service.set_agent_muted(name, checked)
138
+ self._save(settings)
139
+ except Exception:
140
+ logger.exception("lightfall-voice: toggling mute for '{}' failed", name)
141
+ self.refresh()
@@ -0,0 +1,151 @@
1
+ """Professional spoken-phrase set. Pure functions, no state.
2
+
3
+ Copy rules: neutral tone; permission phrases contain "permission" and error
4
+ phrases contain "attention" -- the daemon assigns HIGH (non-interruptible)
5
+ priority based on those words.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import re
11
+ from pathlib import PurePath
12
+
13
+ _MAX_SUMMARY = 200
14
+
15
+ # Tool -> announcement. None = silent. Tools absent from this table are
16
+ # announced from their humanized name (see _humanized_announcement), so new
17
+ # MCP tools speak by default; the per-(agent, tool) rate limit in policy.py
18
+ # bounds the chatter.
19
+ _TOOL_ACTIONS: dict[str, str | None] = {
20
+ "Read": "Reading {stem}",
21
+ "Edit": "Editing {stem}",
22
+ "MultiEdit": "Editing {stem}",
23
+ "Write": "Writing {stem}",
24
+ "NotebookEdit": "Editing {stem}",
25
+ "Bash": "Running a command",
26
+ "PowerShell": "Running a command",
27
+ "Grep": "Searching",
28
+ "Glob": "Searching",
29
+ "WebSearch": "Searching the web",
30
+ "WebFetch": "Fetching a web page",
31
+ "TodoWrite": None,
32
+ "Task": None,
33
+ "Agent": None,
34
+ "ToolSearch": None,
35
+ "AskUserQuestion": "Asking a question",
36
+ # Cosmetic avatar state, called on most turns.
37
+ "lightfall_set_emotion": None,
38
+ }
39
+
40
+ _MCP_PREFIX = re.compile(r"^mcp__.+?__")
41
+
42
+ # Leading/trailing words treated as verbs when humanizing a tool name.
43
+ _VERBS = frozenset(
44
+ "abort activate check clear click close create delete discover edit execute fetch "
45
+ "find fit get invoke launch list load manage move open pause plot push query read "
46
+ "record reload remove reset resume run save scan search send set show start stop "
47
+ "submit type unload update wait write".split()
48
+ )
49
+ # Verbs whose gerund doubles the final consonant.
50
+ _DOUBLED = frozenset("get plot run set stop".split())
51
+
52
+ # Server/namespace words dropped from the front of a tool name.
53
+ _NAMESPACES = frozenset({"lightfall"})
54
+
55
+ # Tool -> natural-language object for permission phrases.
56
+ _TOOL_OBJECTS = {
57
+ "Bash": "run a command",
58
+ "PowerShell": "run a command",
59
+ "Edit": "edit a file",
60
+ "MultiEdit": "edit a file",
61
+ "Write": "write a file",
62
+ "Read": "read a file",
63
+ "WebFetch": "access the web",
64
+ "WebSearch": "search the web",
65
+ }
66
+
67
+
68
+ def _stem(tool_input: dict) -> str | None:
69
+ path = tool_input.get("file_path") or tool_input.get("path") or tool_input.get("notebook_path")
70
+ if not path:
71
+ return None
72
+ return PurePath(str(path)).stem.replace("_", " ").replace("-", " ")
73
+
74
+
75
+ def _base_name(tool_name: str) -> str:
76
+ """Strip an ``mcp__<server>__`` prefix: ``mcp__lf__lightfall_read`` -> ``lightfall_read``."""
77
+ return _MCP_PREFIX.sub("", tool_name)
78
+
79
+
80
+ def _words(name: str) -> list[str]:
81
+ name = re.sub(r"(?<=[a-z0-9])(?=[A-Z])", "_", name)
82
+ words = [w.lower() for w in re.split(r"[_\-\s]+", name) if w]
83
+ while len(words) > 1 and words[0] in _NAMESPACES:
84
+ words.pop(0)
85
+ return words
86
+
87
+
88
+ def _gerund(verb: str) -> str:
89
+ if verb in _DOUBLED:
90
+ return verb + verb[-1] + "ing"
91
+ if verb.endswith("e") and not verb.endswith("ee"):
92
+ return verb[:-1] + "ing"
93
+ return verb + "ing"
94
+
95
+
96
+ def _humanized_announcement(base: str) -> str | None:
97
+ """Lead with the first verb found: ``read_device`` -> "Reading device",
98
+ ``ipython_execute`` -> "Executing ipython"; no verb -> "Using <words>"."""
99
+ words = _words(base)
100
+ if not words:
101
+ return None
102
+ i = next((i for i, w in enumerate(words) if w in _VERBS), None)
103
+ if i is None:
104
+ return "Using " + " ".join(words)
105
+ rest = words[:i] + words[i + 1:]
106
+ return " ".join([_gerund(words[i]).capitalize(), *rest])
107
+
108
+
109
+ def tool_announcement(tool_name: str, tool_input: dict) -> str | None:
110
+ """Short announcement for a tool call, or None to stay silent."""
111
+ base = _base_name(tool_name)
112
+ if base not in _TOOL_ACTIONS:
113
+ return _humanized_announcement(base)
114
+ template = _TOOL_ACTIONS[base]
115
+ if template is None:
116
+ return None
117
+ if "{stem}" in template:
118
+ stem = _stem(tool_input)
119
+ if not stem:
120
+ return template.replace(" {stem}", " a file")
121
+ return template.format(stem=stem)
122
+ return template
123
+
124
+
125
+ def permission_phrase(tool_name: str, agent_name: str | None = None) -> str:
126
+ base = _base_name(tool_name)
127
+ obj = _TOOL_OBJECTS.get(base) or "use " + (" ".join(_words(base)) or tool_name)
128
+ if agent_name:
129
+ return f"Agent {agent_name}: permission needed to {obj}"
130
+ return f"Permission needed to {obj}"
131
+
132
+
133
+ def completion_phrase(result_text: str | None) -> str | None:
134
+ """Spoken turn summary from the final assistant text."""
135
+ text = (result_text or "").strip()
136
+ if not text:
137
+ return "Task complete"
138
+ # Strip markdown emphasis/code markers and collapse whitespace.
139
+ text = re.sub(r"[*_`#]+", "", text)
140
+ text = re.sub(r"\s+", " ", text).strip()
141
+ if not text:
142
+ return "Task complete"
143
+ if len(text) > _MAX_SUMMARY:
144
+ text = text[:_MAX_SUMMARY].rstrip() + "..."
145
+ return text
146
+
147
+
148
+ def error_phrase(agent_name: str | None = None) -> str:
149
+ if agent_name:
150
+ return f"Agent {agent_name} error. Attention needed"
151
+ return "Agent error. Attention needed"
@@ -0,0 +1,165 @@
1
+ """Decides whether/how a VoiceEvent is spoken. Pure logic, injectable time."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+
7
+ from lightfall_voice.events import VoiceEvent
8
+ from lightfall_voice.voices import DEFAULT_VOICE
9
+
10
+ TTL_SECONDS = 10.0
11
+ TOOL_RATE_LIMIT_SECONDS = 3.0
12
+
13
+ _KEYS = {
14
+ "enabled": "voice.enabled",
15
+ "tools": "voice.events.tools",
16
+ "summary": "voice.events.summary",
17
+ "permission": "voice.events.permission",
18
+ "errors": "voice.events.errors",
19
+ "daemon_host": "voice.daemon_host",
20
+ "daemon_port": "voice.daemon_port",
21
+ "default_voice": "voice.default_voice",
22
+ "agent_overrides": "voice.agent_overrides",
23
+ }
24
+
25
+
26
+ @dataclass(frozen=True)
27
+ class AgentOverride:
28
+ muted: bool = False
29
+ voice: str | None = None
30
+
31
+
32
+ @dataclass
33
+ class VoiceSettings:
34
+ enabled: bool = True
35
+ tools: bool = True
36
+ summary: bool = True
37
+ permission: bool = True
38
+ errors: bool = True
39
+ daemon_host: str = "127.0.0.1"
40
+ daemon_port: int = 52849
41
+ # Voice for agents without their own; "" leaves it to the daemon's config.
42
+ default_voice: str = DEFAULT_VOICE
43
+ agent_overrides: dict[str, AgentOverride] = field(default_factory=dict)
44
+
45
+ @classmethod
46
+ def from_preferences(cls, prefs) -> "VoiceSettings":
47
+ raw_overrides = prefs.get(_KEYS["agent_overrides"], {}) or {}
48
+ overrides = {
49
+ name: AgentOverride(
50
+ muted=bool(o.get("muted", False)), voice=o.get("voice") or None
51
+ )
52
+ for name, o in raw_overrides.items()
53
+ }
54
+ return cls(
55
+ enabled=bool(prefs.get(_KEYS["enabled"], True)),
56
+ tools=bool(prefs.get(_KEYS["tools"], True)),
57
+ summary=bool(prefs.get(_KEYS["summary"], True)),
58
+ permission=bool(prefs.get(_KEYS["permission"], True)),
59
+ errors=bool(prefs.get(_KEYS["errors"], True)),
60
+ daemon_host=str(prefs.get(_KEYS["daemon_host"], "127.0.0.1")),
61
+ daemon_port=int(prefs.get(_KEYS["daemon_port"], 52849)),
62
+ default_voice=str(prefs.get(_KEYS["default_voice"], DEFAULT_VOICE) or ""),
63
+ agent_overrides=overrides,
64
+ )
65
+
66
+ def to_preferences(self, prefs) -> None:
67
+ prefs.set(_KEYS["enabled"], self.enabled)
68
+ prefs.set(_KEYS["tools"], self.tools)
69
+ prefs.set(_KEYS["summary"], self.summary)
70
+ prefs.set(_KEYS["permission"], self.permission)
71
+ prefs.set(_KEYS["errors"], self.errors)
72
+ prefs.set(_KEYS["daemon_host"], self.daemon_host)
73
+ prefs.set(_KEYS["daemon_port"], self.daemon_port)
74
+ prefs.set(_KEYS["default_voice"], self.default_voice)
75
+ prefs.set(
76
+ _KEYS["agent_overrides"],
77
+ {
78
+ name: {"muted": o.muted, "voice": o.voice}
79
+ for name, o in self.agent_overrides.items()
80
+ },
81
+ )
82
+
83
+
84
+ def muted_by_default(agent_name: str) -> bool:
85
+ """Mute state of an agent with no override in voice.agent_overrides.
86
+
87
+ Every session tab speaks unless muted: agent_overrides is a pure opt-out.
88
+ (Subagents never reach the policy: they have no widget, and their tool
89
+ calls arrive through the parent session's signals under its name.)
90
+ """
91
+ return False
92
+
93
+
94
+ def with_agent_voice(
95
+ overrides: dict[str, AgentOverride], agent_name: str, voice: str | None
96
+ ) -> dict[str, AgentOverride]:
97
+ """``overrides`` with ``agent_name``'s voice set (None/"" = the default
98
+ voice); its mute is kept. Entries restating the default are dropped."""
99
+ out = dict(overrides)
100
+ muted = out[agent_name].muted if agent_name in out else muted_by_default(agent_name)
101
+ voice = voice or None
102
+ if muted == muted_by_default(agent_name) and voice is None:
103
+ out.pop(agent_name, None)
104
+ else:
105
+ out[agent_name] = AgentOverride(muted=muted, voice=voice)
106
+ return out
107
+
108
+
109
+ def with_agent_muted(
110
+ overrides: dict[str, AgentOverride], agent_name: str, muted: bool
111
+ ) -> dict[str, AgentOverride]:
112
+ """``overrides`` with ``agent_name``'s mute set; its voice is kept.
113
+
114
+ An entry that would only restate the default is dropped, so the stored
115
+ overrides stay a pure opt-out list.
116
+ """
117
+ out = dict(overrides)
118
+ voice = out[agent_name].voice if agent_name in out else None
119
+ if muted == muted_by_default(agent_name) and voice is None:
120
+ out.pop(agent_name, None)
121
+ else:
122
+ out[agent_name] = AgentOverride(muted=muted, voice=voice)
123
+ return out
124
+
125
+
126
+ class VoicePolicy:
127
+ def __init__(self, settings: VoiceSettings) -> None:
128
+ self.settings = settings
129
+ self._last_tool_time: dict[tuple[str, str], float] = {}
130
+
131
+ def decide(self, event: VoiceEvent, now: float) -> tuple[str, str | None] | None:
132
+ s = self.settings
133
+ if not s.enabled:
134
+ return None
135
+
136
+ kind_enabled = {
137
+ "tool": s.tools,
138
+ "summary": s.summary,
139
+ "permission": s.permission,
140
+ "error": s.errors,
141
+ }.get(event.kind, False)
142
+ if not kind_enabled:
143
+ return None
144
+
145
+ override = s.agent_overrides.get(event.agent_name)
146
+ # Explicit overrides win; high-priority events (permission, error)
147
+ # always break through mutes.
148
+ if event.priority != "high":
149
+ muted = (
150
+ override.muted if override is not None
151
+ else muted_by_default(event.agent_name)
152
+ )
153
+ if muted:
154
+ return None
155
+ if now - event.timestamp > TTL_SECONDS:
156
+ return None
157
+ if event.kind == "tool" and event.tool_name:
158
+ key = (event.agent_name, event.tool_name)
159
+ last = self._last_tool_time.get(key, float("-inf"))
160
+ if now - last < TOOL_RATE_LIMIT_SECONDS:
161
+ return None
162
+ self._last_tool_time[key] = now
163
+
164
+ voice = (override.voice if override is not None else None) or s.default_voice
165
+ return (event.text, voice or None)