-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathcodec_dashboard.py
More file actions
3160 lines (2840 loc) · 135 KB
/
codec_dashboard.py
File metadata and controls
3160 lines (2840 loc) · 135 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""CODEC v2.1 — Phone Dashboard & PWA"""
import os, json, sqlite3, time, subprocess, hmac, threading, uuid, asyncio, re
from datetime import datetime, timedelta
from pathlib import Path
from fastapi import FastAPI, Request
from fastapi.responses import HTMLResponse, JSONResponse, FileResponse
from fastapi.middleware.cors import CORSMiddleware
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.responses import JSONResponse as StarletteJSONResponse
import uvicorn
# ── Shared state (canonical source: routes/_shared.py) ──
from routes._shared import (
log, DASHBOARD_DIR, CONFIG_PATH, AUDIT_LOG, _NO_CACHE, _audit_write,
_notif_lock, _load_notifications, _write_notifications,
_append_schedule_run_log,
AUTH_ENABLED, AUTH_SESSION_HOURS, AUTH_COOKIE_NAME,
_auth_sessions, _auth_lock, _e2e_keys,
_auth_available, _verify_biometric_session,
_save_sessions, _save_e2e_keys,
get_db,
_pending_approvals, _approval_lock,
)
try:
from codec_audit import log_event
except ImportError:
def log_event(*a, **kw): pass
from pydantic import BaseModel, Field
from typing import Optional, List
# ── Pydantic Response Models ───────────────────────────────────────────
class HealthResponse(BaseModel):
status: str = Field(description="Service status", example="ok")
service: str = Field(description="Service name", example="CODEC Dashboard")
timestamp: str = Field(description="ISO 8601 timestamp")
class StatusResponse(BaseModel):
running: bool = Field(description="Whether CODEC main process is running")
pm2_status: Optional[str] = Field(None, description="PM2 process status")
class SkillItem(BaseModel):
name: str = Field(description="Skill identifier")
description: str = Field(description="Human-readable description")
triggers: List[str] = Field(description="Trigger phrases")
class ConversationItem(BaseModel):
id: int
session_id: str
timestamp: str
role: str = Field(description="'user' or 'assistant'")
content: str
class ScheduleItem(BaseModel):
id: str = Field(description="Unique schedule ID")
name: str = Field(description="Schedule name")
cron: str = Field(description="Cron expression")
command: str = Field(description="Command to execute")
enabled: bool = Field(default=True)
class ServiceStatus(BaseModel):
running: bool
last_tick: Optional[str] = None
errors: int = 0
class CommandRequest(BaseModel):
command: str = Field(description="Command text to execute")
source: str = Field(default="api", description="Request source identifier")
class ChatRequest(BaseModel):
message: str = Field(default="", description="User message text")
messages: Optional[list] = Field(None, description="Full conversation history")
session_id: Optional[str] = Field(None, description="Session ID for context")
class AgentRunRequest(BaseModel):
crew: str = Field(description="Crew name from registry")
task: str = Field(default="", description="Task description")
context: Optional[str] = Field(None, description="Additional context")
class ErrorResponse(BaseModel):
error: str = Field(description="Error message")
app = FastAPI(
title="CODEC Dashboard",
description="CODEC voice-controlled computer agent — dashboard API. "
"Full documentation at /docs. Auth via Bearer token or biometric session.",
version="2.1.0",
docs_url="/docs",
redoc_url="/redoc",
)
app.add_middleware(CORSMiddleware, allow_origins=["http://localhost:8090", "http://127.0.0.1:8090", "https://codec.lucyvpa.com"], allow_methods=["GET", "POST", "PUT", "DELETE", "OPTIONS"], allow_headers=["Content-Type", "Authorization", "X-Session-Token", "X-Requested-With"])
# ── Background Services (replaces PM2 daemons for scheduler, heartbeat, watcher) ──
_bg_tasks: dict = {}
_bg_status: dict = {
"scheduler": {"running": False, "last_tick": None, "errors": 0},
"heartbeat": {"running": False, "last_tick": None, "errors": 0},
"watcher": {"running": False, "last_tick": None, "errors": 0},
}
class AuthMiddleware(BaseHTTPMiddleware):
"""Combined auth: bearer token (API) + biometric Touch ID sessions (dashboard)."""
# Routes that never require authentication
PUBLIC_ROUTES = {"/", "/chat", "/vibe", "/voice", "/auth", "/health", "/api/health", "/metrics", "/favicon.ico", "/manifest.json", "/docs", "/redoc", "/openapi.json"}
PUBLIC_PREFIXES = ("/api/auth/", "/static")
# CSRF-exempt paths (auth endpoints handle their own protection)
CSRF_EXEMPT = {"/api/auth/verify", "/api/auth/pin", "/api/auth/logout",
"/api/auth/totp/setup", "/api/auth/totp/confirm", "/api/auth/totp/verify",
"/api/auth/totp/enable", "/api/auth/keyexchange"}
async def dispatch(self, request, call_next):
from codec_config import DASHBOARD_TOKEN
from codec_metrics import metrics
path = request.url.path
metrics.inc("codec_http_requests_total", {"method": request.method, "path": path})
# Always allow public routes
if path in self.PUBLIC_ROUTES:
return await call_next(request)
if any(path.startswith(p) for p in self.PUBLIC_PREFIXES):
return await call_next(request)
# Allow internal localhost requests (scheduler, heartbeat, MCP)
client_ip = request.client.host if request.client else ""
if client_ip in ("127.0.0.1", "::1", "localhost") and request.headers.get("x-internal") == "codec":
return await call_next(request)
# Allow static assets
if path.endswith(('.css', '.js', '.png', '.ico', '.svg', '.woff2', '.woff', '.ttf')):
return await call_next(request)
# ── CSRF check for state-changing requests ──
# Only enforce CSRF if the user has a valid auth session (avoids blocking expired sessions
# with stale CSRF cookies — let them fall through to the 401 auth check instead)
if request.method in ("POST", "PUT", "DELETE") and path not in self.CSRF_EXEMPT:
csrf_cookie = request.cookies.get("codec_csrf", "")
csrf_header = request.headers.get("x-csrf-token", "")
session_cookie = request.cookies.get(AUTH_COOKIE_NAME, "")
if (DASHBOARD_TOKEN or AUTH_ENABLED) and csrf_cookie and session_cookie:
if not csrf_header or not hmac.compare_digest(csrf_cookie, csrf_header):
return StarletteJSONResponse(
{"error": "CSRF token mismatch. Refresh the page."},
status_code=403
)
# ── Layer 0: No auth configured → allow all ──
if not DASHBOARD_TOKEN and (not AUTH_ENABLED or not _auth_available()):
return await call_next(request)
# ── Layer 1: Token check (API key — works as standalone auth for API) ──
if DASHBOARD_TOKEN and path.startswith("/api/"):
auth = request.headers.get("Authorization", "")
if auth and hmac.compare_digest(auth, f"Bearer {DASHBOARD_TOKEN}"):
return await call_next(request)
# ── Layer 2: Biometric / PIN session check ──
if AUTH_ENABLED and _auth_available():
if _verify_biometric_session(request):
return await call_next(request)
# Fallback: accept session token as ?s= query param (for img/stream URLs on mobile)
qs_token = request.query_params.get("s", "")
if qs_token and request.method == "GET":
with _auth_lock:
if qs_token in _auth_sessions:
session = _auth_sessions[qs_token]
if datetime.now() - session["created"] <= timedelta(hours=AUTH_SESSION_HOURS):
return await call_next(request)
# Biometric failed — reject
cookie_val = request.cookies.get(AUTH_COOKIE_NAME, "<missing>")
log.warning("AUTH REJECTED: path=%s method=%s ip=%s cookie=%s...",
path, request.method, request.client.host if request.client else "?",
cookie_val[:12] if cookie_val else "<empty>")
if path.startswith("/api/") or path.startswith("/ws"):
return StarletteJSONResponse({"error": "Not authenticated"}, status_code=401)
from starlette.responses import RedirectResponse
return RedirectResponse(url="/auth")
# ── Layer 3: No biometric available — token-only mode ──
if DASHBOARD_TOKEN and path.startswith("/api/"):
# Token was already checked above and didn't match
return StarletteJSONResponse(
{"error": "Unauthorized. Set dashboard_token in config.json and use the Authorization header."},
status_code=401
)
return await call_next(request)
class CSPMiddleware(BaseHTTPMiddleware):
"""Add Content-Security-Policy header to all HTML responses."""
CSP = (
"default-src 'self'; "
"script-src 'self' 'unsafe-inline' https://cdnjs.cloudflare.com; "
"style-src 'self' 'unsafe-inline' https://fonts.googleapis.com https://cdnjs.cloudflare.com; "
"font-src 'self' https://fonts.gstatic.com https://cdnjs.cloudflare.com; "
"img-src 'self' data: https:; "
"connect-src 'self' ws: wss: http://localhost:* http://127.0.0.1:*; "
"worker-src 'self' blob:"
)
async def dispatch(self, request, call_next):
response = await call_next(request)
content_type = response.headers.get("content-type", "")
if "text/html" in content_type:
response.headers["Content-Security-Policy"] = self.CSP
return response
app.add_middleware(CSPMiddleware)
app.add_middleware(AuthMiddleware)
# (Shared state: DB_PATH, AUDIT_LOG, CONFIG_PATH, etc. imported from routes._shared)
# (Auth helpers, DB, notifications loaded from routes._shared)
# (Auth endpoints moved to routes/auth.py)
# ═══════════════════════════════════════════════════════════════
# E2E ENCRYPTION — AES-256-GCM middleware (key exchange in routes/auth.py)
# ═══════════════════════════════════════════════════════════════
class E2EMiddleware(BaseHTTPMiddleware):
"""Transparent AES-256-GCM encryption/decryption for requests with X-E2E: 1 header."""
async def dispatch(self, request, call_next):
if request.headers.get("x-e2e") != "1":
return await call_next(request)
token = request.cookies.get(AUTH_COOKIE_NAME, "")
aes_key = _e2e_keys.get(token) if token else None
if not aes_key:
# E2E header present but server lost key (e.g. after restart) — tell client to re-negotiate
if request.method in ("POST", "PUT", "DELETE"):
log.warning(f"[E2E] Key missing for session, requesting re-negotiation")
return StarletteJSONResponse(
{"error": "E2E key expired. Refreshing encryption.", "e2e_renew": True},
status_code=428, # Precondition Required
headers={"x-e2e-renew": "1"}
)
return await call_next(request)
try:
import base64
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
except ImportError:
return await call_next(request)
# Decrypt request body if present
if request.method in ("POST", "PUT", "DELETE"):
raw = await request.body()
if raw:
try:
envelope = json.loads(raw)
if "iv" in envelope and "ct" in envelope:
iv = base64.b64decode(envelope["iv"])
ct = base64.b64decode(envelope["ct"])
plaintext = AESGCM(aes_key).decrypt(iv, ct, None)
# Replace request body with decrypted content
request._body = plaintext
except Exception:
pass # Not E2E-encrypted or malformed — pass through
response = await call_next(request)
# Encrypt response body
if response.headers.get("content-type", "").startswith("application/json"):
body_parts = []
async for chunk in response.body_iterator:
body_parts.append(chunk if isinstance(chunk, bytes) else chunk.encode())
resp_body = b"".join(body_parts)
iv = os.urandom(12)
ct = AESGCM(aes_key).encrypt(iv, resp_body, None)
enc = json.dumps({"iv": base64.b64encode(iv).decode(), "ct": base64.b64encode(ct).decode()})
return StarletteJSONResponse(
content=json.loads(enc),
status_code=response.status_code,
headers={"x-e2e": "1"}
)
return response
app.add_middleware(E2EMiddleware)
# ═══════════════════════════════════════════════════════════════
# ROUTE MODULES
# ═══════════════════════════════════════════════════════════════
from routes.auth import router as auth_router
from routes.skills import router as skills_router
from routes.agents import router as agents_router
from routes.memory import router as memory_router
from routes.websocket import router as websocket_router
app.include_router(auth_router)
app.include_router(skills_router)
app.include_router(agents_router)
app.include_router(memory_router)
app.include_router(websocket_router)
# ═══════════════════════════════════════════════════════════════
# DASHBOARD ROUTES (remaining in codec_dashboard.py)
# ═══════════════════════════════════════════════════════════════
@app.get("/", response_class=HTMLResponse)
async def index():
html_path = os.path.join(DASHBOARD_DIR, "codec_dashboard.html")
with open(html_path) as f:
return HTMLResponse(f.read(), headers=_NO_CACHE)
@app.get("/favicon.png")
@app.get("/favicon.ico")
async def favicon():
fav_path = os.path.join(DASHBOARD_DIR, "favicon.png")
if os.path.exists(fav_path):
return FileResponse(fav_path, media_type="image/png", headers={"Cache-Control": "public, max-age=86400"})
return JSONResponse({"error": "not found"}, status_code=404)
@app.get("/manifest.json")
async def manifest():
return JSONResponse({
"name": "CODEC",
"short_name": "CODEC",
"description": "CODEC — Your Open-Source Intelligent Command Layer",
"start_url": "/",
"display": "standalone",
"background_color": "#0a0a0a",
"theme_color": "#E8711A",
"icons": [
{"src": "/favicon.png", "sizes": "2048x2048", "type": "image/png"}
]
})
@app.get("/metrics")
async def prometheus_metrics():
from starlette.responses import PlainTextResponse
from codec_metrics import metrics
return PlainTextResponse(metrics.render(), media_type="text/plain; version=0.0.4")
@app.get("/api/status")
async def status():
"""Check if CODEC is running and return config"""
config = {}
try:
with open(CONFIG_PATH) as f:
config = json.load(f)
except Exception as e:
log.warning(f"Non-critical error: {e}")
# Check if CODEC process is alive
import subprocess
try:
r = subprocess.run(["pgrep", "-f", "codec.py"], capture_output=True, text=True, timeout=3)
alive = bool(r.stdout.strip())
except Exception as e:
log.warning(f"Non-critical error: {e}")
alive = False
return {
"alive": alive,
"config": {
"llm_provider": config.get("llm_provider", "unknown"),
"llm_model": config.get("llm_model", "unknown"),
"tts_engine": config.get("tts_engine", "unknown"),
"tts_voice": config.get("tts_voice", "unknown"),
"key_toggle": config.get("key_toggle", "f13"),
"key_voice": config.get("key_voice", "f18"),
"key_text": config.get("key_text", "f16"),
"wake_word_enabled": config.get("wake_word_enabled", False),
"streaming": config.get("streaming", True),
}
}
def _mask_sensitive(value: str) -> str:
"""Mask sensitive field values, showing only last 4 characters."""
if not value or not isinstance(value, str):
return ""
if len(value) <= 4:
return "****"
return "*" * (len(value) - 4) + value[-4:]
# Fields that contain secrets and must be masked in GET responses
_SENSITIVE_FIELDS = {"llm_api_key", "dashboard_token", "auth_pin_hash"}
# Validation rules: field -> (type, required, extra_checks)
# extra_checks is a callable returning (ok, error_msg)
_VALIDATION_RULES = {
"agent_name": (str, True, lambda v: (len(v.strip()) > 0, "agent_name cannot be empty")),
"llm_provider": (str, True, lambda v: (len(v.strip()) > 0, "llm_provider cannot be empty")),
"llm_model": (str, False, None),
"llm_base_url": (str, False, lambda v: (v == "" or v.startswith("http"), "llm_base_url must be a valid URL")),
"llm_api_key": (str, False, None),
"streaming": (bool, False, None),
"vision_base_url": (str, False, lambda v: (v == "" or v.startswith("http"), "vision_base_url must be a valid URL")),
"vision_model": (str, False, None),
"tts_engine": (str, False, None),
"tts_url": (str, False, lambda v: (v == "" or v.startswith("http"), "tts_url must be a valid URL")),
"tts_model": (str, False, None),
"tts_voice": (str, False, None),
"stt_engine": (str, False, None),
"stt_url": (str, False, lambda v: (v == "" or v.startswith("http"), "stt_url must be a valid URL")),
"key_toggle": (str, True, lambda v: (len(v.strip()) > 0, "key_toggle cannot be empty")),
"key_voice": (str, True, lambda v: (len(v.strip()) > 0, "key_voice cannot be empty")),
"key_text": (str, True, lambda v: (len(v.strip()) > 0, "key_text cannot be empty")),
"wake_word_enabled": (bool, False, None),
"wake_phrases": (list, False, None),
"wake_energy": ((int, float), False, lambda v: (v >= 0, "wake_energy cannot be negative")),
"auth_enabled": (bool, False, None),
"auth_session_hours": ((int, float), False, lambda v: (v > 0, "auth_session_hours must be positive")),
"dashboard_token": (str, False, None),
}
def _validate_config_updates(flat: dict) -> list:
"""Validate flattened config values. Returns list of error strings."""
errors = []
for key, value in flat.items():
rule = _VALIDATION_RULES.get(key)
if not rule:
continue # allow unknown keys through (forward compat)
expected_type, required, check_fn = rule
# Skip masked sensitive values (client didn't change them)
if key in _SENSITIVE_FIELDS and isinstance(value, str) and value.startswith("*"):
continue
if not isinstance(value, expected_type):
errors.append(f"{key}: expected {expected_type.__name__ if isinstance(expected_type, type) else 'number'}, got {type(value).__name__}")
continue
if check_fn:
ok, msg = check_fn(value)
if not ok:
errors.append(msg)
return errors
@app.get("/api/config")
async def get_config():
"""Return full editable config for Settings UI (sensitive fields masked)."""
config = {}
try:
with open(CONFIG_PATH) as f:
config = json.load(f)
except Exception:
pass
# Group into sections for the UI
result = {
"llm": {
"llm_provider": config.get("llm_provider", "mlx"),
"llm_model": config.get("llm_model", ""),
"llm_base_url": config.get("llm_base_url", "http://localhost:8081/v1"),
"llm_api_key": config.get("llm_api_key", ""),
"streaming": config.get("streaming", True),
},
"vision": {
"vision_base_url": config.get("vision_base_url", "http://localhost:8082/v1"),
"vision_model": config.get("vision_model", ""),
},
"tts": {
"tts_engine": config.get("tts_engine", "kokoro"),
"tts_url": config.get("tts_url", "http://localhost:8085/v1/audio/speech"),
"tts_model": config.get("tts_model", ""),
"tts_voice": config.get("tts_voice", "am_adam"),
},
"stt": {
"stt_engine": config.get("stt_engine", "whisper_http"),
"stt_url": config.get("stt_url", "http://localhost:8084/v1/audio/transcriptions"),
},
"keys": {
"key_toggle": config.get("key_toggle", "f13"),
"key_voice": config.get("key_voice", "f18"),
"key_text": config.get("key_text", "f16"),
},
"wake": {
"wake_word_enabled": config.get("wake_word_enabled", True),
"wake_phrases": config.get("wake_phrases", []),
"wake_energy": config.get("wake_energy", 200),
},
"auth": {
"auth_enabled": config.get("auth_enabled", False),
"auth_session_hours": config.get("auth_session_hours", 24),
"dashboard_token": config.get("dashboard_token", ""),
},
"identity": {
"agent_name": config.get("agent_name", "C"),
},
}
# Mask sensitive fields before sending to the client
for section in result.values():
if isinstance(section, dict):
for key in section:
if key in _SENSITIVE_FIELDS:
section[key] = _mask_sensitive(section[key])
return result
@app.put("/api/config")
async def update_config(request: Request):
"""Update config.json from Settings UI with input validation."""
try:
updates = await request.json()
config = {}
try:
with open(CONFIG_PATH) as f:
config = json.load(f)
except Exception:
pass
# Flatten sections for validation and merge
flat = {}
for section_vals in updates.values():
if isinstance(section_vals, dict):
for k, v in section_vals.items():
flat[k] = v
# Validate all incoming values
errors = _validate_config_updates(flat)
if errors:
return JSONResponse({"error": "Validation failed", "details": errors}, status_code=422)
# Merge validated values, skipping masked sensitive fields
changed_keys = []
for k, v in flat.items():
# If a sensitive field is still masked, the user did not change it — skip
if k in _SENSITIVE_FIELDS and isinstance(v, str) and v.startswith("*"):
continue
config[k] = v
changed_keys.append(k)
with open(CONFIG_PATH, "w") as f:
json.dump(config, f, indent=2)
return {
"saved": True,
"message": f"Configuration saved successfully ({len(changed_keys)} field(s) updated).",
"updated_fields": changed_keys,
}
except json.JSONDecodeError:
return JSONResponse({"error": "Invalid JSON in request body"}, status_code=400)
except Exception as e:
return JSONResponse({"error": str(e)}, status_code=500)
@app.get("/api/history")
async def history(limit: int = 50):
"""Get recent task history"""
limit = min(limit, 500)
try:
c = get_db()
rows = c.execute(
"SELECT id, timestamp, task, app, response FROM sessions ORDER BY id DESC LIMIT ?",
(limit,)
).fetchall()
return [{"id": r[0], "timestamp": r[1], "task": r[2], "app": r[3], "response": r[4]} for r in rows]
except Exception as e:
return JSONResponse({"error": str(e)}, status_code=500)
# ---------------------------------------------------------------------------
# System Prompts API — view and edit all CODEC personality prompts
# ---------------------------------------------------------------------------
PROMPTS_FILE = os.path.join(str(Path.home()), ".codec", "prompt_overrides.json")
def _load_prompt_overrides():
try:
with open(PROMPTS_FILE) as f:
return json.load(f)
except (FileNotFoundError, json.JSONDecodeError):
return {}
def _save_prompt_overrides(data):
os.makedirs(os.path.dirname(PROMPTS_FILE), exist_ok=True)
with open(PROMPTS_FILE, "w") as f:
json.dump(data, f, indent=2)
def _get_all_prompts():
"""Collect all system prompts from source files + any user overrides."""
overrides = _load_prompt_overrides()
prompts = {}
# 1. CODEC Identity (base)
try:
from codec_identity import CODEC_IDENTITY
prompts["identity_base"] = {
"label": "CODEC Identity (Base)",
"description": "Core identity shared by all interfaces — who CODEC is, personality, memory rules",
"file": "codec_identity.py",
"default": CODEC_IDENTITY.strip(),
}
except Exception:
pass
# 2. Voice prompt
try:
from codec_identity import CODEC_VOICE_PROMPT
prompts["voice"] = {
"label": "Voice Mode",
"description": "Real-time voice calls — spoken output rules, concise answers, TTS formatting",
"file": "codec_voice.py",
"default": CODEC_VOICE_PROMPT.strip(),
}
except Exception:
pass
# 3. Chat prompt
prompts["chat"] = {
"label": "Chat Mode",
"description": "Web chat interface — skill awareness, tool calling, personality",
"file": "codec_dashboard.py",
"default": CHAT_SYSTEM_PROMPT.strip(),
}
# 4. Vibe IDE prompt (multi-line JS string concatenation)
try:
vibe_path = os.path.join(DASHBOARD_DIR, "codec_vibe.html")
import re as _re
with open(vibe_path, "r") as f:
content = f.read()
# Match: var SYSP = "..." + \n"..." + ... "...";
m = _re.search(r'var SYSP\s*=\s*((?:"[^"]*"\s*\+?\s*\n?\s*)+);', content)
if m:
raw_block = m.group(1)
# Extract all quoted strings and join them
parts = _re.findall(r'"([^"]*)"', raw_block)
joined = "".join(parts)
# Unescape \n
joined = joined.replace('\\n', '\n')
prompts["vibe"] = {
"label": "Vibe IDE",
"description": "AI coding assistant — code output rules, operational modes, Canvas requirements",
"file": "codec_vibe.html",
"default": joined.strip(),
}
except Exception:
pass
# 5. Text Assist modes
ta_prompts = {
"textassist_proofread": ("Proofread", "Fix spelling, grammar, punctuation — keep same tone"),
"textassist_elevate": ("Elevate", "Polish text to professional quality"),
"textassist_explain": ("Explain", "Simplify and summarize text"),
"textassist_reply": ("Reply", "Craft a natural reply matching tone"),
"textassist_translate": ("Translate", "Translate any language to English"),
"textassist_prompt": ("Prompt Engineer", "Optimize text as an AI prompt"),
}
try:
# Read the prompts dict from the file directly
ta_path = os.path.join(DASHBOARD_DIR, "codec_textassist.py")
with open(ta_path, "r") as f:
ta_content = f.read()
import ast
tree = ast.parse(ta_content)
for node in ast.walk(tree):
if isinstance(node, ast.Dict):
keys = [k.value for k in node.keys if isinstance(k, ast.Constant)]
if "proofread" in keys and "elevate" in keys:
for k, v in zip(node.keys, node.values):
if isinstance(k, ast.Constant) and isinstance(v, ast.Constant):
key = f"textassist_{k.value}"
if key in ta_prompts:
label, desc = ta_prompts[key]
prompts[key] = {
"label": f"Text Assist: {label}",
"description": desc,
"file": "codec_textassist.py",
"default": v.value.strip(),
}
break
except Exception:
pass
# Apply overrides
for key, prompt_data in prompts.items():
prompt_data["value"] = overrides.get(key, prompt_data["default"])
prompt_data["modified"] = key in overrides
return prompts
@app.get("/api/prompts")
async def get_prompts():
"""Return all system prompts with defaults and any user overrides."""
try:
return _get_all_prompts()
except Exception as e:
return JSONResponse({"error": str(e)}, status_code=500)
@app.put("/api/prompts")
async def update_prompts(request: Request):
"""Save user prompt overrides. Send {key: new_value} pairs."""
try:
updates = await request.json()
overrides = _load_prompt_overrides()
all_prompts = _get_all_prompts()
for key, value in updates.items():
if key not in all_prompts:
continue
# If value matches default, remove override
if value.strip() == all_prompts[key]["default"]:
overrides.pop(key, None)
else:
overrides[key] = value.strip()
_save_prompt_overrides(overrides)
return {"ok": True, "overrides_count": len(overrides)}
except Exception as e:
return JSONResponse({"error": str(e)}, status_code=500)
@app.post("/api/prompts/reset")
async def reset_prompt(request: Request):
"""Reset a prompt to its default. Send {key: "prompt_key"}."""
try:
body = await request.json()
key = body.get("key")
overrides = _load_prompt_overrides()
overrides.pop(key, None)
_save_prompt_overrides(overrides)
return {"ok": True, "reset": key}
except Exception as e:
return JSONResponse({"error": str(e)}, status_code=500)
@app.get("/api/conversations")
async def conversations(limit: int = 100, source: str = ""):
"""Get recent conversations. source=flash filters to Flash Chat only."""
limit = min(limit, 500)
try:
c = get_db()
if source == "flash":
rows = c.execute(
"SELECT id, session_id, timestamp, role, content FROM conversations WHERE session_id LIKE 'flash-%' ORDER BY id DESC LIMIT ?",
(limit,)
).fetchall()
else:
rows = c.execute(
"SELECT id, session_id, timestamp, role, content FROM conversations ORDER BY id DESC LIMIT ?",
(limit,)
).fetchall()
return [{"id": r[0], "session_id": r[1], "timestamp": r[2], "role": r[3], "content": r[4]} for r in rows]
except Exception as e:
return JSONResponse({"error": str(e)}, status_code=500)
@app.get("/api/audit")
async def audit(limit: int = 50):
"""Get recent audit log entries"""
limit = min(limit, 500)
try:
if not os.path.exists(AUDIT_LOG):
return []
with open(AUDIT_LOG) as f:
lines = f.readlines()
return [{"line": l.strip()} for l in lines[-limit:]][::-1]
except Exception as e:
return JSONResponse({"error": str(e)}, status_code=500)
@app.get("/api/audit/stream")
async def audit_stream(
categories: str = "",
level: str = "",
search: str = "",
since: str = "",
until: str = "",
limit: int = 200
):
"""Query audit events with filters."""
from codec_audit import read_events
cats = [c.strip() for c in categories.split(",") if c.strip()] or None
events = read_events(
categories=cats,
level=level or None,
search=search or None,
since=since or None,
until=until or None,
limit=min(limit, 1000)
)
return {"events": events}
@app.get("/api/audit/stats")
async def audit_stats():
"""Get audit event statistics for the last 24 hours."""
from codec_audit import get_stats
return get_stats(hours=24)
@app.post("/api/command")
async def send_command(request: Request):
"""Queue a command for CODEC to execute (used by heartbeat, scheduler, and PWA)."""
body = await request.json()
# Accept both 'command' (heartbeat/scheduler) and 'task' (PWA) keys
task = (body.get("command") or body.get("task") or "").strip()
if not task:
return JSONResponse({"error": "No command provided"}, status_code=400)
source = body.get("source", "pwa")
# ── Safety: reject dangerous commands before queueing ──
from codec_config import is_dangerous
if is_dangerous(task):
log.warning(f"[Command] BLOCKED dangerous command from {source}: {task[:80]}")
_audit_write(f"[{datetime.now().isoformat()}] BLOCKED[{source}]: {task[:200]}\n")
return JSONResponse(
{"error": "Command blocked: matches a dangerous pattern. Use the terminal directly for system commands."},
status_code=403
)
# Process command directly via LLM
try:
import requests as rq
config = {}
try:
with open(CONFIG_PATH) as f: config = json.load(f)
except Exception:
pass
base_url = config.get("llm_base_url", "http://localhost:8081/v1")
model = config.get("llm_model", "mlx-community/Qwen3.5-35B-A3B-4bit")
api_key = config.get("llm_api_key", "")
kwargs = config.get("llm_kwargs", {})
headers_llm = {"Content-Type": "application/json"}
if api_key: headers_llm["Authorization"] = f"Bearer {api_key}"
# Use persistent session_id from frontend (keeps conversation context)
session_id = body.get("session_id") or f"quickchat-{__import__('uuid').uuid4().hex[:8]}"
now = datetime.now().isoformat()
# Save user message to conversations table (so it appears in chat list)
c = get_db()
c.execute(
"INSERT INTO conversations (session_id, timestamp, role, content) VALUES (?,?,?,?)",
(session_id, now, "user", task[:2000])
)
c.commit()
# Load recent conversation history for context (last 20 messages in this session)
_history_rows = c.execute(
"SELECT role, content FROM conversations WHERE session_id=? ORDER BY timestamp DESC LIMIT 20",
(session_id,)
).fetchall()
_history_msgs = [{"role": r[0], "content": r[1]} for r in reversed(_history_rows)]
_audit_write(f"[{now}] CMD[{source}]: {task[:200]}\n")
log.info(f"[Command] Processing from {source}: {task[:80]}")
log_event("command", "codec-dashboard", f"Command from {source}: {task[:80]}", {"source": source, "task": task[:200]})
# Call LLM in background so response returns fast
import asyncio
resp_file = os.path.expanduser("~/.codec/pwa_response.json")
# Clear stale response from previous command
try:
if os.path.exists(resp_file):
os.unlink(resp_file)
except Exception:
pass
async def _process_command():
try:
# ── Try skills first (weather, web_search, bitcoin, etc.) ──
# Skip memory_search — Flash Chat already injects memory context into LLM
# Skip skills that open terminal windows (not appropriate for Flash Chat)
_FLASH_SKIP_SKILLS = {"memory_search", "open_terminal", "run_command"}
skill_answer = None
try:
skill_name, skill_result = await asyncio.to_thread(_try_skill, task)
if skill_result and skill_name not in _FLASH_SKIP_SKILLS:
skill_answer = f"⚡ {skill_name}: {skill_result}"
log.info(f"[Command] Skill '{skill_name}' handled: {skill_result[:80]}")
log_event("skill", "codec-dashboard", f"Dashboard skill: {skill_name}", {"skill": skill_name, "result_len": len(skill_answer)})
elif skill_name in _FLASH_SKIP_SKILLS:
log.info(f"[Command] Skipped skill '{skill_name}' — not suitable for Flash Chat")
except Exception as sk_err:
log.warning(f"[Command] Skill check failed: {sk_err}")
if skill_answer:
answer = skill_answer
else:
# ── Fall back to LLM ──
now_str = datetime.now().strftime("%A %B %d, %Y at %H:%M")
sys_msg = {"role": "system", "content": f"You are CODEC Flash, a fast local AI assistant running on the user's Mac. Today is {now_str}. Be concise and direct. Answer in 1-3 sentences max. You DO have memory of this conversation — the chat history is included in these messages. Refer to previous messages naturally when the user asks follow-up questions."}
# Build messages: system + cross-session context + current session
# Keep it compact — Flash Chat has max_tokens=300, don't overload context
_cross_rows = c.execute(
"SELECT role, content, timestamp FROM conversations "
"WHERE session_id != ? AND timestamp >= ? "
"ORDER BY timestamp DESC LIMIT 10",
(session_id, (datetime.now() - timedelta(hours=12)).isoformat())
).fetchall()
if _cross_rows:
_cross_lines = ["[EARLIER CONVERSATIONS TODAY — you DO remember these]"]
for cr in reversed(_cross_rows):
ts = (cr[2] or "")[:16].replace("T", " ")
_cross_lines.append(f" [{ts}] {(cr[0] or '').upper()}: {(cr[1] or '')[:120]}")
_cross_lines.append("[END]")
sys_msg["content"] += "\n\n" + "\n".join(_cross_lines)
log.info(f"[Command] Injected {len(_cross_rows)} cross-session messages into system prompt")
# Cap history to last 10 messages to avoid context overflow
llm_messages = [sys_msg] + _history_msgs[-10:]
log.info(f"[Command] Final: {len(llm_messages)} messages to LLM")
payload = {
"model": model,
"messages": llm_messages,
"max_tokens": 300,
"temperature": 0.7,
"stream": False,
"chat_template_kwargs": {"enable_thinking": False},
}
payload.update({k: v for k, v in kwargs.items() if k != "chat_template_kwargs"})
r = await asyncio.to_thread(
lambda: rq.post(f"{base_url}/chat/completions", json=payload,
headers=headers_llm, timeout=120)
)
data = r.json()
if "error" in data:
log.error(f"[Command] LLM error: {data['error']}")
answer = f"Sorry, the AI model returned an error. Please try again."
elif "choices" not in data or not data["choices"]:
log.error(f"[Command] LLM returned no choices: {str(data)[:200]}")
answer = "Sorry, the AI model returned an empty response. Please try again."
else:
msg = data["choices"][0]["message"]
answer = (msg.get("content") or "").strip()
if not answer and msg.get("reasoning"):
answer = msg["reasoning"].strip()
import re as _re
answer = _re.sub(r'<think>[\s\S]*?</think>', '', answer).strip()
# Write response for /api/response polling
with open(resp_file, "w") as f:
json.dump({"response": answer, "task": task, "ts": datetime.now().isoformat()}, f)
# Save assistant response to conversations table
c2 = get_db()
c2.execute(
"INSERT INTO conversations (session_id, timestamp, role, content) VALUES (?,?,?,?)",
(session_id, datetime.now().isoformat(), "assistant", answer[:2000])
)
c2.commit()
log.info(f"[Command] Response ready: {answer[:80]}")
log_event("llm", "codec-dashboard", f"Flash response ready", {"model": model, "answer_len": len(answer)})
except Exception as e:
log.error(f"[Command] LLM call failed: {e}")
log_event("error", "codec-dashboard", f"Flash LLM failed: {e}", level="error")
with open(resp_file, "w") as f:
json.dump({"response": f"Error: {e}", "task": task}, f)
asyncio.create_task(_process_command())
return {"status": "processing", "command": task, "source": source}
except Exception as e:
log.error(f"[Command] Failed: {e}")
return JSONResponse({"error": str(e)}, status_code=500)
@app.post("/api/vision")
async def vision_analyze(request: Request):
"""Send image to Qwen Vision model for analysis"""
body = await request.json()
image_b64 = body.get("image", "")
prompt = body.get("prompt", "Describe and analyze this image in detail.")
if not image_b64:
return JSONResponse({"error": "No image data"}, status_code=400)
try:
import requests as rq
config = {}
try:
with open(CONFIG_PATH) as f: config = json.load(f)
except Exception as e:
log.warning(f"Non-critical error: {e}")
vision_url = config.get("vision_base_url", "http://localhost:8082/v1")
vision_model = config.get("vision_model", "mlx-community/Qwen2.5-VL-7B-Instruct-4bit")
payload = {
"model": vision_model,
"messages": [{
"role": "user",
"content": [
{"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{image_b64}"}},
{"type": "text", "text": prompt}
]
}],
"max_tokens": 4000,
"temperature": 0.7
}
headers = {"Content-Type": "application/json"}
r = rq.post(f"{vision_url}/chat/completions", json=payload, headers=headers, timeout=120)
data = r.json()
answer = data["choices"][0]["message"]["content"].strip()
_audit_write(f"[{datetime.now().isoformat()}] VISION: {prompt[:100]}\n")
log_event("vision", "codec-dashboard", f"Vision analysis: {prompt[:60]}")
return {"response": answer, "model": vision_model}
except Exception as e:
import traceback; traceback.print_exc()
return JSONResponse({"error": str(e)}, status_code=500)
@app.get("/api/response")
async def get_response(session_id: str = "", after: str = ""):
"""Get latest PWA command response — file-based + DB fallback for reliability."""
headers = {"Cache-Control": "no-cache, no-store, must-revalidate", "Pragma": "no-cache"}
try:
# Primary: check response file (fast path)
resp_file = os.path.expanduser("~/.codec/pwa_response.json")
if os.path.exists(resp_file):