openvoiceui 1.0.0

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 (185) hide show
  1. package/.env.example +104 -0
  2. package/Dockerfile +30 -0
  3. package/LICENSE +21 -0
  4. package/README.md +638 -0
  5. package/SETUP.md +360 -0
  6. package/app.py +232 -0
  7. package/auto-approve-devices.js +111 -0
  8. package/cli/index.js +372 -0
  9. package/config/__init__.py +4 -0
  10. package/config/default.yaml +43 -0
  11. package/config/flags.yaml +67 -0
  12. package/config/loader.py +203 -0
  13. package/config/providers.yaml +71 -0
  14. package/config/speech_normalization.yaml +182 -0
  15. package/config/theme.json +4 -0
  16. package/data/greetings.json +25 -0
  17. package/default-pages/ai-image-creator.html +915 -0
  18. package/default-pages/bulk-image-uploader.html +492 -0
  19. package/default-pages/desktop.html +2865 -0
  20. package/default-pages/file-explorer.html +854 -0
  21. package/default-pages/interactive-map.html +655 -0
  22. package/default-pages/style-guide.html +1005 -0
  23. package/default-pages/website-setup.html +1623 -0
  24. package/deploy/openclaw/Dockerfile +46 -0
  25. package/deploy/openvoiceui.service +30 -0
  26. package/deploy/setup-nginx.sh +50 -0
  27. package/deploy/setup-sudo.sh +306 -0
  28. package/deploy/skill-runner/Dockerfile +19 -0
  29. package/deploy/skill-runner/requirements.txt +14 -0
  30. package/deploy/skill-runner/server.py +269 -0
  31. package/deploy/supertonic/Dockerfile +22 -0
  32. package/deploy/supertonic/server.py +79 -0
  33. package/docker-compose.pinokio.yml +11 -0
  34. package/docker-compose.yml +59 -0
  35. package/greetings.json +25 -0
  36. package/index.html +65 -0
  37. package/inject-device-identity.js +142 -0
  38. package/package.json +82 -0
  39. package/profiles/default.json +114 -0
  40. package/profiles/manager.py +354 -0
  41. package/profiles/schema.json +337 -0
  42. package/prompts/voice-system-prompt.md +149 -0
  43. package/providers/__init__.py +39 -0
  44. package/providers/base.py +63 -0
  45. package/providers/llm/__init__.py +12 -0
  46. package/providers/llm/base.py +71 -0
  47. package/providers/llm/clawdbot_provider.py +112 -0
  48. package/providers/llm/zai_provider.py +115 -0
  49. package/providers/registry.py +320 -0
  50. package/providers/stt/__init__.py +12 -0
  51. package/providers/stt/base.py +58 -0
  52. package/providers/stt/webspeech_provider.py +49 -0
  53. package/providers/stt/whisper_provider.py +100 -0
  54. package/providers/tts/__init__.py +20 -0
  55. package/providers/tts/base.py +91 -0
  56. package/providers/tts/groq_provider.py +74 -0
  57. package/providers/tts/supertonic_provider.py +72 -0
  58. package/requirements.txt +38 -0
  59. package/routes/__init__.py +10 -0
  60. package/routes/admin.py +515 -0
  61. package/routes/canvas.py +1315 -0
  62. package/routes/chat.py +51 -0
  63. package/routes/conversation.py +2158 -0
  64. package/routes/elevenlabs_hybrid.py +306 -0
  65. package/routes/greetings.py +98 -0
  66. package/routes/icons.py +279 -0
  67. package/routes/image_gen.py +364 -0
  68. package/routes/instructions.py +190 -0
  69. package/routes/music.py +838 -0
  70. package/routes/onboarding.py +43 -0
  71. package/routes/pi.py +62 -0
  72. package/routes/profiles.py +215 -0
  73. package/routes/report_issue.py +68 -0
  74. package/routes/static_files.py +533 -0
  75. package/routes/suno.py +664 -0
  76. package/routes/theme.py +81 -0
  77. package/routes/transcripts.py +199 -0
  78. package/routes/vision.py +348 -0
  79. package/routes/workspace.py +288 -0
  80. package/server.py +1510 -0
  81. package/services/__init__.py +1 -0
  82. package/services/auth.py +143 -0
  83. package/services/canvas_versioning.py +239 -0
  84. package/services/db_pool.py +107 -0
  85. package/services/gateway.py +16 -0
  86. package/services/gateway_manager.py +333 -0
  87. package/services/gateways/__init__.py +12 -0
  88. package/services/gateways/base.py +110 -0
  89. package/services/gateways/compat.py +264 -0
  90. package/services/gateways/openclaw.py +1134 -0
  91. package/services/health.py +100 -0
  92. package/services/memory_client.py +455 -0
  93. package/services/paths.py +26 -0
  94. package/services/speech_normalizer.py +285 -0
  95. package/services/tts.py +270 -0
  96. package/setup-config.js +262 -0
  97. package/sounds/air_horn.mp3 +0 -0
  98. package/sounds/bruh.mp3 +0 -0
  99. package/sounds/crowd_cheer.mp3 +0 -0
  100. package/sounds/gunshot.mp3 +0 -0
  101. package/sounds/impact.mp3 +0 -0
  102. package/sounds/lets_go.mp3 +0 -0
  103. package/sounds/record_stop.mp3 +0 -0
  104. package/sounds/rewind.mp3 +0 -0
  105. package/sounds/sad_trombone.mp3 +0 -0
  106. package/sounds/scratch_long.mp3 +0 -0
  107. package/sounds/yeah.mp3 +0 -0
  108. package/src/adapters/ClawdBotAdapter.js +264 -0
  109. package/src/adapters/_template.js +133 -0
  110. package/src/adapters/elevenlabs-classic.js +841 -0
  111. package/src/adapters/elevenlabs-hybrid.js +812 -0
  112. package/src/adapters/hume-evi.js +676 -0
  113. package/src/admin.html +1339 -0
  114. package/src/app.js +8802 -0
  115. package/src/core/Config.js +173 -0
  116. package/src/core/EmotionEngine.js +307 -0
  117. package/src/core/EventBridge.js +180 -0
  118. package/src/core/EventBus.js +117 -0
  119. package/src/core/VoiceSession.js +607 -0
  120. package/src/face/BaseFace.js +259 -0
  121. package/src/face/EyeFace.js +208 -0
  122. package/src/face/HaloSmokeFace.js +509 -0
  123. package/src/face/manifest.json +27 -0
  124. package/src/face/previews/eyes.svg +16 -0
  125. package/src/face/previews/orb.svg +29 -0
  126. package/src/features/MusicPlayer.js +620 -0
  127. package/src/features/Soundboard.js +128 -0
  128. package/src/providers/DeepgramSTT.js +472 -0
  129. package/src/providers/DeepgramStreamingSTT.js +766 -0
  130. package/src/providers/GroqSTT.js +559 -0
  131. package/src/providers/TTSPlayer.js +323 -0
  132. package/src/providers/WebSpeechSTT.js +479 -0
  133. package/src/providers/tts/BaseTTSProvider.js +81 -0
  134. package/src/providers/tts/HumeProvider.js +77 -0
  135. package/src/providers/tts/SupertonicProvider.js +174 -0
  136. package/src/providers/tts/index.js +140 -0
  137. package/src/shell/adapter-registry.js +154 -0
  138. package/src/shell/caller-bridge.js +35 -0
  139. package/src/shell/camera-bridge.js +28 -0
  140. package/src/shell/canvas-bridge.js +32 -0
  141. package/src/shell/commercial-bridge.js +44 -0
  142. package/src/shell/face-bridge.js +44 -0
  143. package/src/shell/music-bridge.js +60 -0
  144. package/src/shell/orchestrator.js +233 -0
  145. package/src/shell/profile-discovery.js +303 -0
  146. package/src/shell/sounds-bridge.js +28 -0
  147. package/src/shell/transcript-bridge.js +61 -0
  148. package/src/shell/waveform-bridge.js +33 -0
  149. package/src/styles/base.css +2862 -0
  150. package/src/styles/face.css +417 -0
  151. package/src/styles/pi-overrides.css +89 -0
  152. package/src/styles/theme-dark.css +67 -0
  153. package/src/test-tts.html +175 -0
  154. package/src/ui/AppShell.js +544 -0
  155. package/src/ui/ProfileSwitcher.js +228 -0
  156. package/src/ui/SessionControl.js +240 -0
  157. package/src/ui/face/FacePicker.js +195 -0
  158. package/src/ui/face/FaceRenderer.js +309 -0
  159. package/src/ui/settings/PlaylistEditor.js +366 -0
  160. package/src/ui/settings/SettingsPanel.css +684 -0
  161. package/src/ui/settings/SettingsPanel.js +419 -0
  162. package/src/ui/settings/TTSVoicePreview.js +210 -0
  163. package/src/ui/themes/ThemeManager.js +213 -0
  164. package/src/ui/visualizers/BaseVisualizer.js +29 -0
  165. package/src/ui/visualizers/PartyFXVisualizer.css +291 -0
  166. package/src/ui/visualizers/PartyFXVisualizer.js +637 -0
  167. package/static/emulators/jsdos/js-dos.css +1 -0
  168. package/static/emulators/jsdos/js-dos.js +22 -0
  169. package/static/favicon.svg +55 -0
  170. package/static/icons/apple-touch-icon.png +0 -0
  171. package/static/icons/favicon-32.png +0 -0
  172. package/static/icons/icon-192.png +0 -0
  173. package/static/icons/icon-512.png +0 -0
  174. package/static/install.html +449 -0
  175. package/static/manifest.json +26 -0
  176. package/static/sw.js +21 -0
  177. package/tts_providers/__init__.py +136 -0
  178. package/tts_providers/base_provider.py +319 -0
  179. package/tts_providers/groq_provider.py +155 -0
  180. package/tts_providers/hume_provider.py +226 -0
  181. package/tts_providers/providers_config.json +119 -0
  182. package/tts_providers/qwen3_provider.py +371 -0
  183. package/tts_providers/resemble_provider.py +315 -0
  184. package/tts_providers/supertonic_provider.py +557 -0
  185. package/tts_providers/supertonic_tts.py +399 -0
@@ -0,0 +1,100 @@
1
+ """
2
+ Health probe endpoints for liveness and readiness checks.
3
+ ADR-006: Separate liveness + readiness probes (Kubernetes-compatible).
4
+
5
+ Liveness (/health/live) — is the process running?
6
+ Readiness (/health/ready) — can it serve requests? (Gateway + TTS loaded)
7
+ """
8
+
9
+ import os
10
+ import time
11
+ from dataclasses import dataclass, field
12
+ from typing import Dict, Optional
13
+
14
+
15
+ @dataclass
16
+ class CheckResult:
17
+ healthy: bool
18
+ message: str
19
+ details: Optional[Dict] = field(default=None)
20
+
21
+
22
+ class HealthChecker:
23
+ """Liveness and readiness health checks."""
24
+
25
+ def __init__(self):
26
+ self.start_time = time.time()
27
+
28
+ def liveness(self) -> CheckResult:
29
+ """Liveness probe — always 200 if the process is alive."""
30
+ return CheckResult(
31
+ healthy=True,
32
+ message="Process is running",
33
+ details={"uptime_seconds": round(time.time() - self.start_time, 1)},
34
+ )
35
+
36
+ def readiness(self) -> CheckResult:
37
+ """Readiness probe — 200 only when Gateway configured + TTS loaded."""
38
+ checks: Dict[str, Dict] = {}
39
+ all_ok = True
40
+
41
+ # --- Gateway check ---
42
+ try:
43
+ gateway_ok = _check_gateway()
44
+ checks["gateway"] = gateway_ok.__dict__
45
+ if not gateway_ok.healthy:
46
+ all_ok = False
47
+ except Exception as exc:
48
+ checks["gateway"] = {"healthy": False, "message": str(exc)}
49
+ all_ok = False
50
+
51
+ # --- TTS providers check ---
52
+ try:
53
+ tts_ok = _check_tts()
54
+ checks["tts"] = tts_ok.__dict__
55
+ if not tts_ok.healthy:
56
+ all_ok = False
57
+ except Exception as exc:
58
+ checks["tts"] = {"healthy": False, "message": str(exc)}
59
+ all_ok = False
60
+
61
+ return CheckResult(
62
+ healthy=all_ok,
63
+ message="All checks passed" if all_ok else "One or more checks failed",
64
+ details=checks,
65
+ )
66
+
67
+
68
+ # ---------------------------------------------------------------------------
69
+ # Individual check helpers
70
+ # ---------------------------------------------------------------------------
71
+
72
+ def _check_gateway() -> CheckResult:
73
+ """Check that the Gateway auth token is configured."""
74
+ token = os.getenv("CLAWDBOT_AUTH_TOKEN")
75
+ if not token:
76
+ return CheckResult(healthy=False, message="CLAWDBOT_AUTH_TOKEN not set")
77
+ gateway_url = os.getenv("CLAWDBOT_GATEWAY_URL", "")
78
+ if not gateway_url:
79
+ return CheckResult(healthy=False, message="CLAWDBOT_GATEWAY_URL not set")
80
+ return CheckResult(healthy=True, message="Gateway configured")
81
+
82
+
83
+ def _check_tts() -> CheckResult:
84
+ """Check that at least one TTS provider is available."""
85
+ try:
86
+ from tts_providers import list_providers
87
+ providers = list_providers()
88
+ if not providers:
89
+ return CheckResult(healthy=False, message="No TTS providers available")
90
+ return CheckResult(
91
+ healthy=True,
92
+ message=f"{len(providers)} TTS provider(s) loaded",
93
+ details={"providers": [str(p) for p in providers]},
94
+ )
95
+ except ImportError:
96
+ return CheckResult(healthy=False, message="tts_providers module not importable")
97
+
98
+
99
+ # Module-level singleton — imported by server.py
100
+ health_checker = HealthChecker()
@@ -0,0 +1,455 @@
1
+ """
2
+ Memory Client for OpenVoiceUI
3
+
4
+ Direct access to clawdbot's memory system:
5
+ - SQLite FTS5 full-text search
6
+ - Discord session search
7
+ - Ambient transcript retrieval
8
+ - Combined context compilation
9
+
10
+ This gives the voice agent the same memory access as the Discord agent.
11
+ """
12
+
13
+ import os
14
+ import sqlite3
15
+ import json
16
+ import logging
17
+ from pathlib import Path
18
+ from datetime import datetime, timedelta
19
+ from typing import List, Dict, Optional
20
+
21
+ logger = logging.getLogger(__name__)
22
+
23
+ # Paths to clawdbot data (configure via env vars or leave empty if not using memory features)
24
+ _home = Path.home()
25
+ MEMORY_DB = Path(os.getenv('CLAWDBOT_MEMORY_DB', str(_home / '.clawdbot/memory/main.sqlite')))
26
+ SESSIONS_DIR = Path(os.getenv('CLAWDBOT_SESSIONS_DIR', str(_home / '.clawdbot/agents/main/sessions/')))
27
+ VOICE_EVENTS = Path('/tmp/openvoiceui-events.jsonl')
28
+
29
+ # Ambient transcripts directory
30
+ AMBIENT_DIR = Path(__file__).parent / "ambient_transcripts"
31
+
32
+
33
+ class MemoryClient:
34
+ """Direct access to clawdbot memory and sessions."""
35
+
36
+ def __init__(self):
37
+ self.memory_db = str(MEMORY_DB)
38
+ self.sessions_dir = SESSIONS_DIR
39
+
40
+ def search_memory(self, query: str, limit: int = 5) -> List[Dict]:
41
+ """
42
+ Search memory chunks using FTS5.
43
+
44
+ Args:
45
+ query: Search query (FTS5 syntax supported)
46
+ limit: Max results to return
47
+
48
+ Returns:
49
+ List of {text, source, score} dicts
50
+ """
51
+ if not MEMORY_DB.exists():
52
+ logger.warning(f"Memory DB not found: {MEMORY_DB}")
53
+ return []
54
+
55
+ try:
56
+ conn = sqlite3.connect(self.memory_db)
57
+ conn.row_factory = sqlite3.Row
58
+ cursor = conn.cursor()
59
+
60
+ # Clean query for FTS5 (remove special chars that break it)
61
+ clean_query = ''.join(c for c in query if c.isalnum() or c.isspace())
62
+ if not clean_query:
63
+ return []
64
+
65
+ # FTS5 search - the table has all columns, no join needed
66
+ cursor.execute("""
67
+ SELECT text, path, bm25(chunks_fts) as score
68
+ FROM chunks_fts
69
+ WHERE chunks_fts MATCH ?
70
+ ORDER BY bm25(chunks_fts)
71
+ LIMIT ?
72
+ """, (clean_query, limit))
73
+
74
+ results = []
75
+ for row in cursor.fetchall():
76
+ results.append({
77
+ 'text': row['text'][:500], # Truncate long chunks
78
+ 'source': row['path'].split('/')[-1] if row['path'] else 'memory',
79
+ 'score': row['score']
80
+ })
81
+
82
+ conn.close()
83
+ logger.info(f"Memory search for '{query}': {len(results)} results")
84
+ return results
85
+
86
+ except Exception as e:
87
+ logger.error(f"Memory search error: {e}")
88
+ return []
89
+
90
+ def search_sessions(self, query: str, limit: int = 3) -> List[Dict]:
91
+ """
92
+ Search Discord session files for relevant conversations.
93
+
94
+ Args:
95
+ query: Search terms
96
+ limit: Max results
97
+
98
+ Returns:
99
+ List of {content, role, session} dicts
100
+ """
101
+ if not self.sessions_dir.exists():
102
+ logger.warning(f"Sessions dir not found: {self.sessions_dir}")
103
+ return []
104
+
105
+ results = []
106
+ query_lower = query.lower()
107
+
108
+ # Get most recent sessions first
109
+ session_files = sorted(
110
+ self.sessions_dir.glob('*.jsonl'),
111
+ key=lambda p: p.stat().st_mtime,
112
+ reverse=True
113
+ )[:20] # Only search last 20 sessions
114
+
115
+ for session_file in session_files:
116
+ try:
117
+ with open(session_file, 'r') as f:
118
+ for line in f:
119
+ try:
120
+ entry = json.loads(line)
121
+ if entry.get('type') != 'message':
122
+ continue
123
+
124
+ msg = entry.get('message', {})
125
+ content = msg.get('content', '')
126
+ role = msg.get('role', 'unknown')
127
+
128
+ if query_lower in content.lower():
129
+ results.append({
130
+ 'content': content[:400],
131
+ 'role': role,
132
+ 'session': session_file.stem[:20]
133
+ })
134
+
135
+ if len(results) >= limit:
136
+ return results
137
+
138
+ except json.JSONDecodeError:
139
+ continue
140
+ except Exception as e:
141
+ logger.debug(f"Error reading session {session_file}: {e}")
142
+ continue
143
+
144
+ logger.info(f"Session search for '{query}': {len(results)} results")
145
+ return results
146
+
147
+ def get_recent_ambient(self, user_id: str, minutes: int = 30, max_chars: int = 1500) -> List[Dict]:
148
+ """
149
+ Get recent ambient transcripts for a user.
150
+
151
+ These are background audio recordings that were transcribed while the
152
+ user was not actively conversing with the agent.
153
+
154
+ Args:
155
+ user_id: Clerk user ID
156
+ minutes: How many minutes back to look (default: 30)
157
+ max_chars: Maximum total characters to return
158
+
159
+ Returns:
160
+ List of {transcript, timestamp, has_wake_word} dicts
161
+ """
162
+ if not user_id:
163
+ return []
164
+
165
+ user_dir = AMBIENT_DIR / user_id
166
+ if not user_dir.exists():
167
+ return []
168
+
169
+ threshold = datetime.now() - timedelta(minutes=minutes)
170
+ entries = []
171
+ total_chars = 0
172
+
173
+ # Check today's file and yesterday's
174
+ for days_ago in [0, 1]:
175
+ date = datetime.now() - timedelta(days=days_ago)
176
+ date_str = date.strftime('%Y-%m-%d')
177
+ transcript_file = user_dir / f"{date_str}.jsonl"
178
+
179
+ if not transcript_file.exists():
180
+ continue
181
+
182
+ try:
183
+ with open(transcript_file, 'r') as f:
184
+ for line in reversed(list(f)): # Start from newest
185
+ try:
186
+ entry = json.loads(line)
187
+
188
+ # Parse timestamp
189
+ ts_str = entry.get('timestamp', '')
190
+ try:
191
+ # Handle various ISO formats
192
+ entry_time = datetime.fromisoformat(
193
+ ts_str.replace('Z', '+00:00').replace('+00:00', '')
194
+ )
195
+ if entry_time < threshold:
196
+ continue
197
+ except ValueError:
198
+ pass # Include if we can't parse timestamp
199
+
200
+ text = entry.get('transcript', '')
201
+ if total_chars + len(text) > max_chars:
202
+ break
203
+
204
+ entries.append({
205
+ 'transcript': text,
206
+ 'timestamp': entry.get('timestamp', ''),
207
+ 'has_wake_word': entry.get('has_wake_word', False),
208
+ 'duration_seconds': entry.get('duration_seconds', 0)
209
+ })
210
+ total_chars += len(text)
211
+
212
+ except json.JSONDecodeError:
213
+ continue
214
+ except Exception as e:
215
+ logger.debug(f"Error reading ambient transcripts: {e}")
216
+
217
+ # Reverse to chronological order
218
+ entries.reverse()
219
+ logger.info(f"Retrieved {len(entries)} ambient transcripts for user {user_id}")
220
+ return entries
221
+
222
+ def search_voice_transcripts(self, query: str, limit: int = 3) -> List[Dict]:
223
+ """
224
+ Search past voice conversations from events file.
225
+
226
+ Args:
227
+ query: Search terms
228
+ limit: Max results
229
+
230
+ Returns:
231
+ List of {content, role, time} dicts
232
+ """
233
+ if not VOICE_EVENTS.exists():
234
+ return []
235
+
236
+ results = []
237
+ query_lower = query.lower()
238
+
239
+ try:
240
+ with open(VOICE_EVENTS, 'r') as f:
241
+ for line in f:
242
+ try:
243
+ event = json.loads(line)
244
+ if event.get('type') != 'conversation':
245
+ continue
246
+
247
+ message = event.get('message', '')
248
+ if query_lower in message.lower():
249
+ results.append({
250
+ 'content': message[:300],
251
+ 'role': event.get('role', 'unknown'),
252
+ 'time': event.get('timestamp', 'unknown')
253
+ })
254
+
255
+ if len(results) >= limit:
256
+ break
257
+ except:
258
+ continue
259
+ except Exception as e:
260
+ logger.error(f"Voice transcript search error: {e}")
261
+
262
+ return results
263
+
264
+ def get_full_context(self, user_message: str, user_id: str = None) -> Dict:
265
+ """
266
+ Get combined context from all sources.
267
+
268
+ Args:
269
+ user_message: What user just said
270
+ user_id: Optional Clerk user ID for ambient transcripts
271
+
272
+ Returns:
273
+ Dict with memory, sessions, transcripts, and ambient context
274
+ """
275
+ # Extract key terms from message
276
+ key_terms = self._extract_keywords(user_message)
277
+ search_query = ' '.join(key_terms[:5])
278
+
279
+ context = {
280
+ 'query': search_query,
281
+ 'memory': self.search_memory(search_query, limit=5),
282
+ 'sessions': self.search_sessions(search_query, limit=3),
283
+ 'voice_transcripts': self.search_voice_transcripts(search_query, limit=2),
284
+ 'generated_at': datetime.now().isoformat()
285
+ }
286
+
287
+ # Add ambient transcripts if user_id provided
288
+ if user_id:
289
+ context['ambient'] = self.get_recent_ambient(user_id, minutes=30, max_chars=1000)
290
+
291
+ return context
292
+
293
+ def format_context_for_prompt(self, context: Dict, max_tokens: int = 1500) -> str:
294
+ """
295
+ Format context for injection into system prompt.
296
+
297
+ Args:
298
+ context: Context dict from get_full_context()
299
+ max_tokens: Approximate max tokens (chars / 4)
300
+
301
+ Returns:
302
+ Formatted string for prompt injection
303
+ """
304
+ parts = ["\n--- RELEVANT CONTEXT ---"]
305
+
306
+ char_limit = max_tokens * 4 # Rough chars estimate
307
+ current_chars = 0
308
+
309
+ # Add memory results
310
+ if context.get('memory'):
311
+ parts.append("\nFrom memory:")
312
+ for item in context['memory'][:3]:
313
+ text = f"\n- [{item['source']}] {item['text'][:200]}"
314
+ if current_chars + len(text) > char_limit:
315
+ break
316
+ parts.append(text)
317
+ current_chars += len(text)
318
+
319
+ # Add session results
320
+ if context.get('sessions'):
321
+ parts.append("\nFrom Discord conversations:")
322
+ for item in context['sessions'][:2]:
323
+ text = f"\n- {item['role']}: {item['content'][:150]}"
324
+ if current_chars + len(text) > char_limit:
325
+ break
326
+ parts.append(text)
327
+ current_chars += len(text)
328
+
329
+ # Add voice transcripts
330
+ if context.get('voice_transcripts'):
331
+ parts.append("\nFrom past voice calls:")
332
+ for item in context['voice_transcripts'][:2]:
333
+ text = f"\n- {item['role']}: {item['content'][:100]}"
334
+ if current_chars + len(text) > char_limit:
335
+ break
336
+ parts.append(text)
337
+ current_chars += len(text)
338
+
339
+ # Add ambient transcripts (background audio context)
340
+ # This is special context about what was heard around the user
341
+ if context.get('ambient'):
342
+ ambient_intro = """
343
+ --- SURROUNDING AUDIO CONTEXT ---
344
+ You have ears that can hear the sounds and audio around you when the user has this feature enabled.
345
+ This is what you recently heard in the background. Determine if this requires a response or is just
346
+ background noise (TV, music, other people talking, etc). Use this to understand the user's context
347
+ and make relevant comments when they wake you up. Be playful and observant!
348
+ """
349
+ parts.append(ambient_intro)
350
+
351
+ for item in context['ambient'][:5]:
352
+ # Format timestamp for readability
353
+ ts = item.get('timestamp', '')
354
+ if 'T' in ts:
355
+ ts = ts.split('T')[1][:8] # Just the time HH:MM:SS
356
+
357
+ text = f"\n[{ts}] \"{item.get('transcript', '')[:200]}\""
358
+ if item.get('has_wake_word'):
359
+ text += " [WAKE WORD DETECTED]"
360
+
361
+ if current_chars + len(text) > char_limit:
362
+ break
363
+ parts.append(text)
364
+ current_chars += len(text)
365
+
366
+ parts.append("\n--- END SURROUNDING AUDIO ---")
367
+
368
+ parts.append("\n--- END CONTEXT ---")
369
+
370
+ return '\n'.join(parts) if current_chars > 0 else ""
371
+
372
+ def _extract_keywords(self, text: str) -> List[str]:
373
+ """Extract meaningful keywords from text."""
374
+ # Stop words to ignore
375
+ stop_words = {
376
+ 'the', 'a', 'an', 'is', 'are', 'was', 'were', 'be', 'been',
377
+ 'being', 'have', 'has', 'had', 'do', 'does', 'did', 'will',
378
+ 'would', 'could', 'should', 'may', 'might', 'must', 'can',
379
+ 'what', 'which', 'who', 'whom', 'when', 'where', 'why', 'how',
380
+ 'this', 'that', 'these', 'those', 'i', 'me', 'my', 'we', 'our',
381
+ 'you', 'your', 'he', 'him', 'his', 'she', 'her', 'it', 'its',
382
+ 'they', 'them', 'their', 'and', 'or', 'but', 'if', 'then',
383
+ 'else', 'so', 'for', 'with', 'about', 'into', 'to', 'from',
384
+ 'up', 'down', 'in', 'out', 'on', 'off', 'over', 'under',
385
+ 'again', 'further', 'once', 'here', 'there', 'all', 'each',
386
+ 'few', 'more', 'most', 'other', 'some', 'such', 'only', 'just'
387
+ }
388
+
389
+ # Extract words
390
+ words = []
391
+ for word in text.lower().split():
392
+ # Clean word
393
+ clean = ''.join(c for c in word if c.isalnum())
394
+ # Keep if long enough and not stop word
395
+ if len(clean) > 3 and clean not in stop_words:
396
+ words.append(clean)
397
+
398
+ # Return unique words, preserving order
399
+ seen = set()
400
+ keywords = []
401
+ for w in words:
402
+ if w not in seen:
403
+ seen.add(w)
404
+ keywords.append(w)
405
+
406
+ return keywords[:10]
407
+
408
+
409
+ # Singleton instance
410
+ _client = None
411
+
412
+ def get_memory_client() -> MemoryClient:
413
+ """Get or create memory client instance."""
414
+ global _client
415
+ if _client is None:
416
+ _client = MemoryClient()
417
+ return _client
418
+
419
+
420
+ # Convenience functions for direct import
421
+ def search_memory(query: str, limit: int = 5) -> List[Dict]:
422
+ return get_memory_client().search_memory(query, limit)
423
+
424
+ def search_sessions(query: str, limit: int = 3) -> List[Dict]:
425
+ return get_memory_client().search_sessions(query, limit)
426
+
427
+ def get_full_context(user_message: str, user_id: str = None) -> Dict:
428
+ return get_memory_client().get_full_context(user_message, user_id=user_id)
429
+
430
+ def format_context_for_prompt(context: Dict, max_tokens: int = 1500) -> str:
431
+ return get_memory_client().format_context_for_prompt(context, max_tokens)
432
+
433
+
434
+ if __name__ == '__main__':
435
+ # Test the client
436
+ logging.basicConfig(level=logging.INFO)
437
+
438
+ client = get_memory_client()
439
+
440
+ # Test memory search
441
+ print("Testing memory search...")
442
+ results = client.search_memory("steve call project")
443
+ for r in results:
444
+ print(f" [{r['source']}] {r['text'][:100]}...")
445
+
446
+ # Test session search
447
+ print("\nTesting session search...")
448
+ results = client.search_sessions("discord bot")
449
+ for r in results:
450
+ print(f" {r['role']}: {r['content'][:100]}...")
451
+
452
+ # Test full context
453
+ print("\nTesting full context...")
454
+ context = client.get_full_context("what did we talk about yesterday")
455
+ print(client.format_context_for_prompt(context))
@@ -0,0 +1,26 @@
1
+ """Canonical path constants for all runtime and asset directories."""
2
+ import os
3
+ from pathlib import Path
4
+
5
+ APP_ROOT = Path(__file__).parent.parent
6
+
7
+ # Runtime data (gitignored, docker-mounted)
8
+ RUNTIME_DIR = APP_ROOT / "runtime"
9
+ UPLOADS_DIR = RUNTIME_DIR / "uploads"
10
+ CANVAS_PAGES_DIR = Path(os.getenv("CANVAS_PAGES_DIR", str(RUNTIME_DIR / "canvas-pages")))
11
+ KNOWN_FACES_DIR = RUNTIME_DIR / "known_faces"
12
+ MUSIC_DIR = RUNTIME_DIR / "music"
13
+ GENERATED_MUSIC_DIR = RUNTIME_DIR / "generated_music"
14
+ FACES_DIR = RUNTIME_DIR / "faces"
15
+ TRANSCRIPTS_DIR = RUNTIME_DIR / "transcripts"
16
+ DB_PATH = RUNTIME_DIR / "usage.db"
17
+ CANVAS_MANIFEST_PATH = RUNTIME_DIR / "canvas-manifest.json"
18
+ VOICE_CLONES_DIR = RUNTIME_DIR / "voice-clones"
19
+ VOICE_SESSION_FILE = str(RUNTIME_DIR / ".voice-session-counter")
20
+ ACTIVE_PROFILE_FILE = RUNTIME_DIR / ".active-profile"
21
+ WORKSPACE_DIR = Path(os.getenv('WORKSPACE_DIR', str(RUNTIME_DIR / 'workspace')))
22
+
23
+ # Bundled assets (git-tracked, stay at root)
24
+ SOUNDS_DIR = APP_ROOT / "sounds"
25
+ STATIC_DIR = APP_ROOT / "static"
26
+ DEFAULT_PAGES_DIR = APP_ROOT / "default-pages"