musubi-livekit 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,23 @@
1
+ """LiveKit session callback adapter backed by the Musubi Python SDK.
2
+
3
+ This package is a library for a LiveKit worker to call from its event
4
+ handlers. It does not install or start a LiveKit worker by itself.
5
+ """
6
+
7
+ from musubi_livekit.adapter import LiveKitAdapter
8
+ from musubi_livekit.cache import ContextCache
9
+ from musubi_livekit.config import LiveKitAdapterConfig
10
+ from musubi_livekit.fast_talker import FastTalker
11
+ from musubi_livekit.heuristics import detect_interesting_fact
12
+ from musubi_livekit.redaction import redact_pii
13
+ from musubi_livekit.slow_thinker import SlowThinker
14
+
15
+ __all__ = [
16
+ "ContextCache",
17
+ "FastTalker",
18
+ "LiveKitAdapter",
19
+ "LiveKitAdapterConfig",
20
+ "SlowThinker",
21
+ "detect_interesting_fact",
22
+ "redact_pii",
23
+ ]
@@ -0,0 +1,204 @@
1
+ """LiveKitAdapter — glues LiveKit session events to Musubi SDK calls.
2
+
3
+ The adapter owns a :class:`SlowThinker` + :class:`FastTalker` pair sharing one
4
+ :class:`ContextCache`, plus the session-end artifact-upload pipeline
5
+ with bounded retry + a deferred-retry queue for hard failures.
6
+
7
+ The artifact upload path can be patched via ``client._upload_handler``;
8
+ the fallback captures the transcript in episodic memory.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import asyncio
14
+ import logging
15
+ from typing import Any
16
+
17
+ from musubi_sdk.exceptions import MusubiError
18
+
19
+ try:
20
+ # The old in-tree adapter accepted the in-tree SDK client. Keep its error
21
+ # hierarchy during the import-path transition without requiring the server.
22
+ from musubi.sdk.exceptions import MusubiError as CoreMusubiError
23
+ except ImportError:
24
+ CoreMusubiError = MusubiError
25
+
26
+ from musubi_livekit.cache import ContextCache, RetrievalStatus
27
+ from musubi_livekit.config import LiveKitAdapterConfig
28
+ from musubi_livekit.fast_talker import FastTalker
29
+ from musubi_livekit.heuristics import detect_interesting_fact
30
+ from musubi_livekit.redaction import redact_pii
31
+ from musubi_livekit.slow_thinker import SlowThinker
32
+
33
+ log = logging.getLogger("musubi_livekit")
34
+
35
+ _EPISODE_CONTEXT_TAGS = ["kind:episode", "staleness:episodic"]
36
+
37
+
38
+ class LiveKitAdapter:
39
+ """Per-session wiring of LiveKit events to Musubi SDK calls."""
40
+
41
+ def __init__(
42
+ self,
43
+ *,
44
+ client: Any,
45
+ namespace: str,
46
+ artifact_namespace: str,
47
+ config: LiveKitAdapterConfig,
48
+ ) -> None:
49
+ self.client = client
50
+ self.namespace = namespace
51
+ self.artifact_namespace = artifact_namespace
52
+ self.config = config
53
+ self.cache = ContextCache(max_entries=config.cache_max_entries)
54
+ # RET-007 — the ONE authoritative agent-facing channel; both talkers publish to it (last
55
+ # retrieval wins = current-turn semantics), so a Slow Thinker pre-fetch failure is visible.
56
+ self._retrieval_status = RetrievalStatus()
57
+ self.slow_thinker = SlowThinker(
58
+ client=client,
59
+ namespace=namespace,
60
+ cache=self.cache,
61
+ deep_limit=config.deep_limit,
62
+ cache_ttl_s=config.cache_default_ttl_s,
63
+ status=self._retrieval_status,
64
+ )
65
+ self.fast_talker = FastTalker(
66
+ client=client,
67
+ namespace=namespace,
68
+ cache=self.cache,
69
+ fast_limit=config.fast_limit,
70
+ match_threshold=config.fast_match_threshold,
71
+ status=self._retrieval_status,
72
+ )
73
+ # Observability/state attached to the adapter for assertions in
74
+ # tests and for an operator dashboard wiring later.
75
+ self.upload_history: list[dict[str, Any]] = []
76
+ self.failed_upload_queue: list[dict[str, Any]] = []
77
+
78
+ @property
79
+ def retrieval_status(self) -> list[str]:
80
+ """RET-007 — the agent-facing degradation status for the CURRENT turn: the ONE authoritative
81
+ channel both talkers publish to (most recent retrieval wins). Empty = healthy; bounded
82
+ ``plane_*`` / ``sparse_embedding_failed`` / ``reranker_failed`` = partial degradation;
83
+ ``[RETRIEVAL_UNAVAILABLE]`` = no memory this turn (a Slow Thinker pre-fetch failure surfaces
84
+ here immediately, not only in the talker's own ``last_warnings``). This is the consumer the
85
+ LiveKit agent reads to render a status message."""
86
+ return list(self._retrieval_status.warnings)
87
+
88
+ # ------------------------------------------------------------------
89
+ # LiveKit event hooks
90
+ # ------------------------------------------------------------------
91
+
92
+ async def on_transcript_segment(self, transcript_so_far: str) -> None:
93
+ """``transcript_segment_received`` event — Slow Thinker restart."""
94
+ await self.slow_thinker.on_user_utterance_segment(transcript_so_far)
95
+
96
+ async def on_user_turn_completed(self, full_utterance: str) -> None:
97
+ """``on_user_turn_completed`` — final deep pre-fetch on the
98
+ completed utterance. The Fast Talker reads this on the next
99
+ speech tick."""
100
+ await self.slow_thinker.on_user_utterance_segment(full_utterance)
101
+
102
+ async def on_session_end(
103
+ self,
104
+ *,
105
+ session_id: str,
106
+ vtt_transcript: str,
107
+ ) -> None:
108
+ """``session_ends`` — upload the transcript as an artifact and
109
+ send a summary thought. Both writes are gated by the privacy
110
+ flags on :class:`LiveKitAdapterConfig`."""
111
+ if self.config.capture_transcripts:
112
+ await self._upload_transcript_with_retry(
113
+ session_id=session_id, vtt_transcript=vtt_transcript
114
+ )
115
+ await self._send_session_thought(session_id=session_id)
116
+
117
+ async def maybe_capture_fact(self, utterance: str) -> None:
118
+ """Heuristic memory capture — runs if ``capture_facts`` is on
119
+ AND the utterance matches an "interesting fact" pattern."""
120
+ if not self.config.capture_facts:
121
+ return
122
+ if not detect_interesting_fact(utterance):
123
+ return
124
+ scrubbed = self.maybe_redact(utterance)
125
+ try:
126
+ await self.client.episodic.capture(
127
+ namespace=self.namespace,
128
+ content=scrubbed,
129
+ tags=["livekit-voice", "heuristic-fact", *_EPISODE_CONTEXT_TAGS],
130
+ importance=6,
131
+ )
132
+ except (MusubiError, CoreMusubiError):
133
+ log.warning("livekit fact-capture failed", exc_info=True)
134
+
135
+ # ------------------------------------------------------------------
136
+ # Helpers
137
+ # ------------------------------------------------------------------
138
+
139
+ def maybe_redact(self, payload: str) -> str:
140
+ """Pass-through unless ``redact_pii`` is on."""
141
+ return redact_pii(payload) if self.config.redact_pii else payload
142
+
143
+ async def _upload_transcript_with_retry(
144
+ self,
145
+ *,
146
+ session_id: str,
147
+ vtt_transcript: str,
148
+ ) -> None:
149
+ """Upload the VTT transcript with bounded exponential retry.
150
+ On exhaustion, enqueue for deferred retry instead of dropping."""
151
+ scrubbed = self.maybe_redact(vtt_transcript)
152
+ if not scrubbed.strip():
153
+ return
154
+ payload = {
155
+ "namespace": self.artifact_namespace,
156
+ "title": f"Voice session {session_id}",
157
+ "content_type": "text/vtt",
158
+ "source_system": "livekit-session",
159
+ "source_ref": session_id,
160
+ "content": scrubbed.encode("utf-8"),
161
+ }
162
+ last_exc: Exception | None = None
163
+ for attempt in range(1, self.config.upload_max_attempts + 1):
164
+ if attempt > 1 and self.config.upload_backoff_s > 0:
165
+ await asyncio.sleep(self.config.upload_backoff_s)
166
+ try:
167
+ handler = getattr(self.client, "_upload_handler", None)
168
+ if callable(handler):
169
+ handler(**payload)
170
+ else:
171
+ # Fall back to the SDK's canonical artifacts.upload
172
+ # surface when it ships; until then, route through
173
+ # episodic.capture so the adapter is always live.
174
+ await self.client.episodic.capture(
175
+ namespace=self.namespace,
176
+ content=scrubbed,
177
+ tags=["livekit-voice", "session-transcript", *_EPISODE_CONTEXT_TAGS],
178
+ importance=4,
179
+ )
180
+ self.upload_history.append(payload)
181
+ return
182
+ except (MusubiError, CoreMusubiError) as exc:
183
+ last_exc = exc
184
+ continue
185
+ # Retries exhausted — enqueue for deferred retry instead of
186
+ # losing the session.
187
+ log.warning("livekit transcript upload exhausted retries; queued for deferred retry")
188
+ self.failed_upload_queue.append(
189
+ {"session_id": session_id, "payload": payload, "last_error": last_exc}
190
+ )
191
+
192
+ async def _send_session_thought(self, *, session_id: str) -> None:
193
+ """Optional summary thought emitted at session end."""
194
+ try:
195
+ await self.client.thoughts.send(
196
+ namespace=self.namespace,
197
+ from_presence="livekit-voice",
198
+ to_presence="all",
199
+ channel="scheduler",
200
+ content=f"Session {session_id} captured.",
201
+ importance=3,
202
+ )
203
+ except (MusubiError, CoreMusubiError):
204
+ log.warning("livekit summary thought failed", exc_info=True)
@@ -0,0 +1,120 @@
1
+ """In-memory per-session retrieval cache for the LiveKit voice adapter.
2
+
3
+ Per [[07-interfaces/livekit-adapter]] § ContextCache. Bounded
4
+ (`max_entries` defaults to 10), TTL'd, and ages out the oldest
5
+ entries first when full. ``get_best_match`` does a cheap token-overlap
6
+ match — not a vector lookup, since pre-fetch queries are usually
7
+ substrings or rephrasings of the live query.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import time
13
+ from collections import deque
14
+ from dataclasses import dataclass, field
15
+ from typing import Any
16
+
17
+ #: RET-007 — the agent-facing status code for a TOTAL retrieval failure (the SDK call raised / returned
18
+ #: no usable body). Distinct from the bounded per-plane degradation codes; it means "no memory this turn".
19
+ RETRIEVAL_UNAVAILABLE = "retrieval_unavailable"
20
+
21
+
22
+ class RetrievalStatus:
23
+ """The ONE authoritative agent-facing retrieval status for the current turn (RET-007 Blocker 4).
24
+
25
+ Both the Slow Thinker (pre-fetch) and the Fast Talker (speech turn) publish to it on EVERY
26
+ retrieval — success, degraded, or total failure. To get correct current-turn semantics under
27
+ OVERLAP (requests can complete out of order — an older slow request may finish after a newer fast
28
+ one), publication is guarded by a monotonic GENERATION: a caller allocates a generation with
29
+ :meth:`begin` at retrieval START, and :meth:`publish` only takes effect if that generation is not
30
+ older than the last one published. So a stale (older) completion can never clobber the status of
31
+ the context actually delivered, while a newer completion (healthy or degraded) always wins.
32
+
33
+ All mutation is synchronous (no ``await`` inside), so under asyncio's single-threaded scheduling
34
+ ``begin``/``publish`` are atomic and no lock is needed.
35
+ """
36
+
37
+ def __init__(self) -> None:
38
+ self.warnings: list[str] = []
39
+ self._counter = 0
40
+ self._published_generation = 0
41
+
42
+ def begin(self) -> int:
43
+ """Allocate a monotonically increasing generation at the START of a retrieval."""
44
+ self._counter += 1
45
+ return self._counter
46
+
47
+ def publish(self, generation: int, warnings: list[str]) -> None:
48
+ """Publish ``warnings`` only if ``generation`` is not older than the last published one."""
49
+ if generation >= self._published_generation:
50
+ self._published_generation = generation
51
+ self.warnings = list(warnings)
52
+
53
+
54
+ @dataclass(frozen=True)
55
+ class _CacheEntry:
56
+ key: str
57
+ results: list[dict[str, Any]]
58
+ expires_at: float
59
+ #: RET-007 — the retrieval degradation warnings that accompanied these cached results, so a Fast
60
+ #: Talker cache-hit surfaces the SAME degradation status the Slow Thinker recorded (not a stale one).
61
+ warnings: list[str] = field(default_factory=list)
62
+
63
+
64
+ def _token_overlap(a: str, b: str) -> float:
65
+ """Cheap Jaccard-ish overlap of lowercased token sets. Returns 0.0
66
+ if either side has no tokens — keeps the threshold gate honest
67
+ instead of a divide-by-zero."""
68
+ ta = {t for t in a.lower().split() if t}
69
+ tb = {t for t in b.lower().split() if t}
70
+ if not ta or not tb:
71
+ return 0.0
72
+ inter = len(ta & tb)
73
+ union = len(ta | tb)
74
+ return inter / union if union else 0.0
75
+
76
+
77
+ class ContextCache:
78
+ """Bounded TTL'd retrieval cache. One per voice session."""
79
+
80
+ def __init__(self, max_entries: int = 10) -> None:
81
+ self._max_entries = max_entries
82
+ self._entries: deque[_CacheEntry] = deque(maxlen=max_entries)
83
+
84
+ def put(
85
+ self,
86
+ key: str,
87
+ results: list[dict[str, Any]],
88
+ ttl: float,
89
+ warnings: list[str] | None = None,
90
+ ) -> None:
91
+ """Store results (+ their RET-007 degradation ``warnings``) under ``key`` with a TTL. When
92
+ full, the oldest entry is evicted (FIFO via ``deque(maxlen=...)``)."""
93
+ self._entries.append(
94
+ _CacheEntry(
95
+ key=key,
96
+ results=results,
97
+ expires_at=time.monotonic() + ttl,
98
+ warnings=list(warnings or []),
99
+ )
100
+ )
101
+
102
+ def match(self, query: str, threshold: float) -> _CacheEntry | None:
103
+ """Return the highest-overlap unexpired ENTRY (results + warnings), if any beat ``threshold``.
104
+ The Fast Talker uses this so a cache-hit carries the cached degradation status."""
105
+ now = time.monotonic()
106
+ best_score = 0.0
107
+ best: _CacheEntry | None = None
108
+ for entry in self._entries:
109
+ if entry.expires_at <= now:
110
+ continue
111
+ score = _token_overlap(query, entry.key)
112
+ if score > best_score:
113
+ best_score = score
114
+ best = entry
115
+ return best if best is not None and best_score >= threshold else None
116
+
117
+ def get_best_match(self, query: str, threshold: float) -> list[dict[str, Any]] | None:
118
+ """Backward-compatible results-only view of :meth:`match` (``None`` on miss)."""
119
+ entry = self.match(query, threshold)
120
+ return entry.results if entry is not None else None
@@ -0,0 +1,37 @@
1
+ """Adapter-local configuration for the LiveKit voice adapter.
2
+
3
+ Configuration is passed at construction time. A consuming worker owns
4
+ environment loading and secret handling.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from dataclasses import dataclass
10
+
11
+
12
+ @dataclass(frozen=True)
13
+ class LiveKitAdapterConfig:
14
+ """Tunables for a single :class:`LiveKitAdapter` instance."""
15
+
16
+ # --- Privacy gates (per spec § Privacy) -------------------------------
17
+ capture_transcripts: bool = True
18
+ """If False, ``on_session_end`` never uploads the VTT transcript."""
19
+
20
+ capture_facts: bool = True
21
+ """If False, the heuristic ``maybe_capture_fact`` never writes."""
22
+
23
+ redact_pii: bool = False
24
+ """If True, payloads pass through ``redact_pii`` before any write."""
25
+
26
+ # --- Cache shape (per spec § ContextCache) ---------------------------
27
+ cache_max_entries: int = 10
28
+ cache_default_ttl_s: float = 120.0
29
+
30
+ # --- Retrieval shape (per spec § Components) -------------------------
31
+ deep_limit: int = 15
32
+ fast_limit: int = 5
33
+ fast_match_threshold: float = 0.5
34
+
35
+ # --- Upload retry (per spec § Error handling) ------------------------
36
+ upload_max_attempts: int = 3
37
+ upload_backoff_s: float = 0.5
@@ -0,0 +1,84 @@
1
+ """Fast Talker — speech-generation context fetch with hard 200ms budget.
2
+
3
+ Per [[07-interfaces/livekit-adapter]] § FastTalker. Reads from the
4
+ shared :class:`ContextCache` first; on miss, falls back to a
5
+ fast-path SDK call (mode="fast", ~150ms p50). Never blocks speech
6
+ on Musubi: any retrieval failure surfaces as an empty result list
7
+ and the agent speaks generically.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import logging
13
+ from typing import Any
14
+
15
+ from musubi_livekit.cache import (
16
+ RETRIEVAL_UNAVAILABLE,
17
+ ContextCache,
18
+ RetrievalStatus,
19
+ )
20
+
21
+ log = logging.getLogger("musubi_livekit.fast_talker")
22
+
23
+
24
+ class FastTalker:
25
+ """Per-session fast-path retrieval wrapper."""
26
+
27
+ def __init__(
28
+ self,
29
+ *,
30
+ client: Any,
31
+ namespace: str,
32
+ cache: ContextCache,
33
+ fast_limit: int = 5,
34
+ match_threshold: float = 0.5,
35
+ status: RetrievalStatus | None = None,
36
+ ) -> None:
37
+ self.client = client
38
+ self.namespace = namespace
39
+ self.cache = cache
40
+ self._fast_limit = fast_limit
41
+ self._match_threshold = match_threshold
42
+ #: RET-007 — the allowlisted degradation codes from the most recent retrieval, surfaced so the
43
+ #: agent can render a non-memory status message. Empty when the last retrieval was healthy.
44
+ self.last_warnings: list[str] = []
45
+ #: The shared authoritative agent channel (set by the adapter). The Fast Talker drives the turn.
46
+ self._status = status
47
+
48
+ def _publish(self, warnings: list[str], generation: int) -> None:
49
+ self.last_warnings = list(warnings)
50
+ if self._status is not None:
51
+ self._status.publish(generation, self.last_warnings)
52
+
53
+ async def get_context(self, query_text: str) -> list[dict[str, Any]]:
54
+ """Return retrieval results for the live query — cache first,
55
+ SDK fast path on miss. Returns ``[]`` on any error so the
56
+ speech loop is never blocked."""
57
+ # Allocate the generation at the START so an out-of-order completion cannot clobber a newer turn.
58
+ generation = self._status.begin() if self._status is not None else 0
59
+ cached = self.cache.match(query_text, threshold=self._match_threshold)
60
+ if cached is not None:
61
+ # RET-007: a cache-hit must reflect the CACHED degradation status, not a stale one from a
62
+ # previous turn — the Slow Thinker stored the warnings alongside the results.
63
+ self._publish(list(cached.warnings), generation)
64
+ return cached.results
65
+ try:
66
+ response = await self.client.retrieve(
67
+ namespace=self.namespace,
68
+ query_text=query_text,
69
+ mode="fast",
70
+ limit=self._fast_limit,
71
+ )
72
+ except Exception:
73
+ log.warning("fast-talker fallback failed", exc_info=True)
74
+ # RET-007: a total failure is VISIBLE on the agent-facing channel — never a silent [] that
75
+ # leaves a stale "healthy" (or stale-degraded) status from the previous turn.
76
+ self._publish([RETRIEVAL_UNAVAILABLE], generation)
77
+ return []
78
+ if not isinstance(response, dict):
79
+ self._publish([RETRIEVAL_UNAVAILABLE], generation)
80
+ return []
81
+ warnings = response.get("warnings", [])
82
+ self._publish(warnings if isinstance(warnings, list) else [], generation)
83
+ results = response.get("results", [])
84
+ return results if isinstance(results, list) else []
@@ -0,0 +1,24 @@
1
+ """Cheap heuristics for opportunistic memory capture during voice sessions.
2
+
3
+ Per [[07-interfaces/livekit-adapter]] § Event mapping —
4
+ ``interesting_fact_detected`` is described as optional and pattern-based.
5
+ Keeping it as a small, explicit regex set lets the adapter capture
6
+ "remember…" / "I always forget…" style asides without needing an
7
+ LLM judge in the speech loop.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import re
13
+
14
+ _INTERESTING_PATTERNS: tuple[re.Pattern[str], ...] = (
15
+ re.compile(r"\bremember\b", re.IGNORECASE),
16
+ re.compile(r"\bI (?:always )?forget\b", re.IGNORECASE),
17
+ re.compile(r"\b(?:save|store|note) (?:this|that) (?:to|in) memory\b", re.IGNORECASE),
18
+ re.compile(r"\bnever forget\b", re.IGNORECASE),
19
+ )
20
+
21
+
22
+ def detect_interesting_fact(utterance: str) -> bool:
23
+ """True if the utterance matches any of the heuristic patterns."""
24
+ return any(p.search(utterance) for p in _INTERESTING_PATTERNS)
File without changes
@@ -0,0 +1,32 @@
1
+ """Minimal PII redaction pass for the LiveKit voice adapter.
2
+
3
+ Per [[07-interfaces/livekit-adapter]] § Privacy. Off by default; the
4
+ adapter only invokes this when ``LiveKitAdapterConfig.redact_pii=True``.
5
+ Patterns cover the common voice-transcript cases (email, US SSN,
6
+ phone-ish digit groups). The full canonical redactor lives in
7
+ [[10-security/redaction]] and is not in scope for this slice.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import re
13
+
14
+ _REDACTED = "[REDACTED]"
15
+
16
+ _PII_PATTERNS: tuple[re.Pattern[str], ...] = (
17
+ # Emails.
18
+ re.compile(r"\b[\w.+-]+@[\w-]+\.[\w.-]+\b"),
19
+ # US SSN-shaped digit groups.
20
+ re.compile(r"\b\d{3}-\d{2}-\d{4}\b"),
21
+ # Phone-ish 10-digit groups with separators.
22
+ re.compile(r"\b\d{3}[-.\s]\d{3}[-.\s]\d{4}\b"),
23
+ )
24
+
25
+
26
+ def redact_pii(text: str) -> str:
27
+ """Return ``text`` with email / SSN / phone shapes replaced by
28
+ ``[REDACTED]``. Idempotent — running twice is a no-op."""
29
+ out = text
30
+ for pattern in _PII_PATTERNS:
31
+ out = pattern.sub(_REDACTED, out)
32
+ return out
@@ -0,0 +1,92 @@
1
+ """Slow Thinker — pre-fetches deep-path retrieval between turns.
2
+
3
+ Per [[07-interfaces/livekit-adapter]] § The dual-agent pattern. Runs
4
+ its own asyncio task that the caller cancels and restarts whenever
5
+ new transcript material arrives. Cancellation is silent: the cancelled
6
+ task does not propagate ``CancelledError`` into the LiveKit event
7
+ loop, so a fast user-interrupt never crashes the speech path.
8
+
9
+ Read-only against Musubi (calls ``client.retrieve(mode="deep")``);
10
+ result writes land in the shared :class:`ContextCache` for the Fast
11
+ Talker to consume on the next 200ms tick.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import asyncio
17
+ import logging
18
+ from typing import Any
19
+
20
+ from musubi_livekit.cache import (
21
+ RETRIEVAL_UNAVAILABLE,
22
+ ContextCache,
23
+ RetrievalStatus,
24
+ )
25
+
26
+ log = logging.getLogger("musubi_livekit.slow_thinker")
27
+
28
+
29
+ class SlowThinker:
30
+ """Per-session deep-pre-fetch worker."""
31
+
32
+ def __init__(
33
+ self,
34
+ *,
35
+ client: Any,
36
+ namespace: str,
37
+ cache: ContextCache,
38
+ deep_limit: int = 15,
39
+ cache_ttl_s: float = 120.0,
40
+ status: RetrievalStatus | None = None,
41
+ ) -> None:
42
+ self.client = client
43
+ self.namespace = namespace
44
+ self.cache = cache
45
+ self._deep_limit = deep_limit
46
+ self._cache_ttl_s = cache_ttl_s
47
+ #: RET-007 — allowlisted degradation codes from the most recent pre-fetch (empty when healthy).
48
+ self.last_warnings: list[str] = []
49
+ #: The shared authoritative agent channel (set by the adapter) — a pre-fetch total failure must
50
+ #: be visible on it, not only on ``last_warnings``.
51
+ self._status = status
52
+ self._task: asyncio.Task[None] | None = None
53
+
54
+ def _publish(self, warnings: list[str], generation: int) -> None:
55
+ self.last_warnings = list(warnings)
56
+ if self._status is not None:
57
+ self._status.publish(generation, self.last_warnings)
58
+
59
+ async def on_user_utterance_segment(self, transcript_so_far: str) -> None:
60
+ """Cancel any in-flight pre-fetch, then start a new one with
61
+ the latest transcript. Idempotent if the same string lands
62
+ twice in a row — the new task simply replays the deep call."""
63
+ if self._task is not None and not self._task.done():
64
+ self._task.cancel()
65
+ self._task = asyncio.create_task(self._prefetch(transcript_so_far))
66
+
67
+ async def _prefetch(self, transcript: str) -> None:
68
+ # Allocate the generation at the START so a slow request that completes AFTER a newer request
69
+ # cannot clobber the newer one's status.
70
+ generation = self._status.begin() if self._status is not None else 0
71
+ try:
72
+ response = await self.client.retrieve(
73
+ namespace=self.namespace,
74
+ query_text=transcript,
75
+ mode="deep",
76
+ limit=self._deep_limit,
77
+ )
78
+ except asyncio.CancelledError:
79
+ # Surfacing this as a normal cancel keeps the LiveKit loop
80
+ # quiet — the new task replaces us.
81
+ raise
82
+ except Exception:
83
+ log.warning("slow-thinker pre-fetch failed", exc_info=True)
84
+ # RET-007: a total pre-fetch failure is a visible impairment on the agent channel, not a
85
+ # silent no-op that leaves a stale status from the previous turn.
86
+ self._publish([RETRIEVAL_UNAVAILABLE], generation)
87
+ return
88
+ warnings = response.get("warnings", []) if isinstance(response, dict) else []
89
+ self._publish(warnings if isinstance(warnings, list) else [], generation)
90
+ results = response.get("results", []) if isinstance(response, dict) else []
91
+ # Cache the warnings WITH the results so a later Fast Talker cache-hit preserves the status.
92
+ self.cache.put(transcript, results, ttl=self._cache_ttl_s, warnings=self.last_warnings)
@@ -0,0 +1,108 @@
1
+ Metadata-Version: 2.5
2
+ Name: musubi-livekit
3
+ Version: 0.1.0
4
+ Summary: LiveKit session callback adapter for the Musubi memory SDK
5
+ Project-URL: Homepage, https://github.com/sourceblender/musubi-livekit
6
+ Project-URL: Repository, https://github.com/sourceblender/musubi-livekit
7
+ Project-URL: Issues, https://github.com/sourceblender/musubi-livekit/issues
8
+ License-Expression: Apache-2.0
9
+ License-File: LICENSE
10
+ Requires-Python: >=3.12
11
+ Requires-Dist: musubi-sdk>=0.1.0
12
+ Description-Content-Type: text/markdown
13
+
14
+ # musubi-livekit
15
+
16
+ `musubi-livekit` connects a LiveKit voice session's callbacks to the Musubi
17
+ memory API. It provides a `LiveKitAdapter`, a slow prefetcher, a fast context
18
+ reader, a bounded cache, optional fact capture, and transcript handling. The
19
+ package is a Python library: your LiveKit worker still owns the session,
20
+ event subscriptions, credentials, and user-facing responses.
21
+
22
+ ## Install
23
+
24
+ Requires Python 3.12 or later. The adapter depends on the standalone
25
+ [`musubi-sdk`](https://pypi.org/project/musubi-sdk/) client, not the Musubi server.
26
+ The SDK is installed from PyPI as a dependency:
27
+
28
+ ```bash
29
+ pip install 'git+https://github.com/sourceblender/musubi-livekit.git'
30
+ ```
31
+
32
+ The plugin itself is not published to PyPI yet; the GitHub install above is
33
+ the current supported install path.
34
+
35
+ ## Use in a worker
36
+
37
+ Construct one adapter per voice session. Feed it the transcript and session
38
+ events from your own LiveKit worker. These are callbacks to wire into the
39
+ worker, not an automatically installed LiveKit plugin.
40
+
41
+ ```python
42
+ from musubi_sdk import AsyncMusubiClient
43
+ from musubi_livekit import LiveKitAdapter, LiveKitAdapterConfig
44
+
45
+ client = AsyncMusubiClient(base_url=api_url, token=token)
46
+ adapter = LiveKitAdapter(
47
+ client=client,
48
+ namespace="assistant/voice/episodic",
49
+ artifact_namespace="assistant/voice/artifact",
50
+ config=LiveKitAdapterConfig(
51
+ capture_transcripts=False,
52
+ capture_facts=False,
53
+ ),
54
+ )
55
+
56
+ # Call from the matching LiveKit worker events:
57
+ await adapter.on_transcript_segment(partial_text)
58
+ await adapter.on_user_turn_completed(final_text)
59
+ context = await adapter.fast_talker.get_context(final_text)
60
+ warnings = adapter.retrieval_status
61
+ await adapter.on_session_end(session_id=session_id, vtt_transcript=vtt_text)
62
+ ```
63
+
64
+ Fact and transcript capture are enabled in the default config. Set the privacy
65
+ flags deliberately for your application before handling a real session.
66
+ `retrieval_status` exposes degradation warnings so the worker can tell the
67
+ user when memory is unavailable. A successful callback call is not a guarantee
68
+ that a transcript reached artifact storage: until the SDK has `artifacts.upload`,
69
+ the adapter falls back to episodic capture. See the code and tests before
70
+ promising artifact storage or delivery guarantees.
71
+
72
+ ## Development
73
+
74
+ ```bash
75
+ uv sync --locked --python 3.12
76
+ uv run pytest -q
77
+ uv run ruff check src tests
78
+ uv run ruff format --check src tests
79
+ uv run mypy src/musubi_livekit
80
+ ```
81
+
82
+ The unit suite exercises the extracted adapter and retrieval degradation
83
+ channel. Three historical tests remain skipped because they require a running
84
+ Musubi stack and a LiveKit session simulator; they are not release evidence.
85
+
86
+ Five integration tests exercise the adapter through the real Musubi SDK and API.
87
+ They write memories and thoughts, so point them only at a disposable test stack
88
+ with an operator-scoped test token:
89
+
90
+ ```bash
91
+ MUSUBI_TEST_API_URL=http://127.0.0.1:8100/v1 \
92
+ MUSUBI_TEST_TOKEN=<disposable-test-token> \
93
+ uv run pytest -q -m integration tests/integration/test_livekit_e2e.py
94
+ ```
95
+
96
+ The default test command excludes these integration tests. Their fixture
97
+ skips when either variable is missing. Linux CI also runs them against
98
+ Musubi's disposable Docker integration stack; the pinned TEI test image has
99
+ no ARM64 manifest, so that stack does not boot natively on Apple Silicon.
100
+
101
+ ## Contributing and security
102
+
103
+ Discuss substantial changes in an issue first. Follow the
104
+ [Sourceblender contributing guide](https://github.com/sourceblender/.github/blob/main/CONTRIBUTING.md).
105
+ Report security issues privately through the repository Security tab or the
106
+ [organization policy](https://github.com/sourceblender/.github/blob/main/SECURITY.md).
107
+
108
+ Licensed under Apache-2.0. See [LICENSE](LICENSE).
@@ -0,0 +1,13 @@
1
+ musubi_livekit/__init__.py,sha256=B-mGo20pZJqz_DnJrhf03txvRSzKoz6Oe8iMjYbl5bs,746
2
+ musubi_livekit/adapter.py,sha256=Ypcf9Ei2HZJGXdoeGVTjgfCw_j5evgMtWeYeb2rsHHU,8608
3
+ musubi_livekit/cache.py,sha256=MnklF10zaefgiozSUJhsS4yRCH-pFMEA6tnhOPxDC2Y,5047
4
+ musubi_livekit/config.py,sha256=lEodaRpn7dq9zRy4owBNReOLufteDkikSFvTmFppPHw,1224
5
+ musubi_livekit/fast_talker.py,sha256=YzvY4azzaq7ALGu-zqeVa9MNhTcfP8zCpA5NiKvqk7s,3508
6
+ musubi_livekit/heuristics.py,sha256=kXLzU_IhR7MIFWeM_0k-rOJXLOvyjicxXpk-Cpdy_ok,928
7
+ musubi_livekit/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
8
+ musubi_livekit/redaction.py,sha256=0xraLjc8ZRoQaaPYeEHTIdBEsJPC54UbVwjdZAIaB_E,1034
9
+ musubi_livekit/slow_thinker.py,sha256=eho3msSlD-RyMG8j2wRY7iWUYG6McBtzdfUFHpDyPUw,3889
10
+ musubi_livekit-0.1.0.dist-info/METADATA,sha256=E8Uh_yrC_sFwPObuHRhqKx3v-_8DkaSp1Qdd7pJwFoE,4250
11
+ musubi_livekit-0.1.0.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
12
+ musubi_livekit-0.1.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
13
+ musubi_livekit-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.32.4
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.