Menu

Cosmo Wiki

Architecture

System architecture, source structure, and startup/bootstrap flow.

System Architecture

High-Level Runtime

flowchart LR
    ArchMain["main.py"] --> ArchBootstrap["Bootstrap"]
    ArchBootstrap --> ArchRuntime["Async Runtime"]
    ArchBootstrap --> ArchEvents["Event Buses"]
    ArchBootstrap --> ArchLifecycle["Lifecycle"]
    ArchRuntime --> ArchVoice["Voice Pipeline"]
    ArchRuntime --> ArchVision["Vision Auto-Capture"]
    ArchRuntime --> ArchCognition["Cognition"]
    ArchRuntime --> ArchWebUI["WebUI"]
    ArchVision --> ArchDiagnostics["Diagnostics"]
    ArchDiagnostics --> ArchWebUI
    ArchCognition --> ArchPersistence["Persistence"]

Voice Pipeline

flowchart LR
    VoiceWake["Wakeword"] --> VoiceCapture["Capture"]
    VoiceCapture --> VoiceSTT["STT"]
    VoiceSTT --> VoiceTranscript["Transcript"]
    VoiceTranscript --> VoiceConversation["Conversation"]
    VoiceConversation --> VoiceResponse["Response"]
    VoiceResponse --> VoiceTTS["TTS"]
    VoiceTTS --> VoiceSpeaker["Speaker"]

WakewordManager owns the microphone only while the runtime mode is idle. When runtime moves into listening, transcribing, thinking, speaking, or cooldown, the wakeword PyAudio stream is closed so STT can own capture without wakeword backlog or stream-draining conflicts. After wakeword detection, the wakeword stream is closed before the listen/STT handoff.

Vision Pipeline

flowchart LR
    Camera["CameraManager"] --> FrameStore["FrameStore"]
    Camera --> Analyzer["VisionAnalyzer"]
    Analyzer --> Metrics["Image Metrics"]
    Analyzer --> FaceReady["face_ready"]
    Camera --> Detector["FaceDetector"]
    Detector --> FacePayload["face_detection"]
    Metrics --> Diagnostics["DiagnosticsManager"]
    FacePayload --> Diagnostics
    Diagnostics --> WebUI["/vision WebUI"]

The vision pipeline is implemented as an experimental local camera pipeline. VisionAutoCapture keeps a periodic capture loop when enabled, and CameraManager may keep the camera session open while that loop is active.

Cognition and Persistence

  • ResponseGenerator routes text through local commands, personality commands, or the configured LLM provider.
  • MemoryManager extracts and filters durable facts before persistence.
  • SQLite stores conversations, memories, events, logs, and command metadata.
  • FaceRepository exists as a persistence layer for future face enrollment/recognition, but enrollment and identity matching are not active yet.

Observability

  • The WebUI reads diagnostics snapshots, runtime state, event-bus metrics, and SQLite repositories.
  • The /vision page reads compact diagnostics and renders image quality, face detection counters, reject reasons, and bounding boxes over the latest snapshot.
  • Endpoints stay read-only; operational changes happen through voice commands or direct database access.

Core Responsibilities

ComponentPathPurpose
Entry pointcosmo/main.pyStarts async bootstrap.
Bootstrapcosmo/core/bootstrap/bootstrap.pyInitializes lifecycle, imports listeners, starts event bus and wakeword task.
Runtime statecosmo/core/runtime/runtime_state.py7-state machine; guards wake, capture, thinking, speaking.
Async event buscosmo/core/events/async_event_bus.pyPriority queue, listener dispatch, metrics, resilience.
Wakewordcosmo/audio/wakeword/Vosk-based word detection with energy thresholding.
Audio capturecosmo/audio/capture/audio_capture_manager.pyRecords user speech with RMS silence detection.
STTcosmo/audio/stt/Vosk transcription engine.
Vision managercosmo/vision/vision_manager.pyStarts/stops camera capture, saves snapshots, emits vision events.
Vision auto-capturecosmo/vision/vision_auto_capture.pyPeriodic snapshot/analysis loop when vision.auto_capture is enabled.
Cameracosmo/vision/camera/Camera access, fresh frame reading, frame store, snapshot saving.
Vision analysiscosmo/vision/analysis/Image metrics, blur/backlight/exposure classification, face readiness.
Face detectioncosmo/vision/detection/Experimental Haar Cascade baseline with filters and eye validation.
Conversationcosmo/cognition/conversation/Short-term history and pipeline orchestration.
Response generationcosmo/cognition/response/response_generator.pyCommand/personality/LLM routing.
TTScosmo/audio/tts/Provider-based synthesis with Piper and Espeak.
Memorycosmo/cognition/memory/Rule-based extraction, filtering, persistence.
Databasecosmo/data/database/SQLite connection and repository types.
Diagnosticscosmo/data/diagnostics/diagnostics_manager.pyRuntime snapshots.
WebUIcosmo/interfaces/webui/FastAPI page-based observability dashboard.
Loggingcosmo/core/logger/Console, file, and SQLite handlers.
Configurationcosmo/core/config/YAML settings loader.

Source Code Structure

PathStatusResponsibility
cosmo/main.pyActiveApplication entry point.
cosmo/core/bootstrap/ActiveLifecycle startup and listener registration.
cosmo/core/events/ActiveEvent types, buses, and listener modules.
cosmo/core/runtime/ActiveRuntime state machine, task registry, thread helpers.
cosmo/audio/vad/PresentWebRTC VAD wrapper; not used because capture uses RMS.
cosmo/interfaces/webui/templates/ActivePage-based templates: dashboard, vision, logs, events, memory, conversations, status.
cosmo/interfaces/webui/static/js/ActivePage-specific JavaScript plus shared helpers.
cosmo/interfaces/webui/static/css/ActiveModular CSS split into base.css, layout.css, components.css, tables.css, dashboard.css, inspectors.css, vision.css, with webui.css as import entrypoint.
cosmo/vision/camera/ActiveCamera access, fresh frame reading, frame store, snapshot saving.
cosmo/vision/analysis/ActiveImage quality metrics, blur/backlight/exposure classification, face readiness.
cosmo/vision/detection/Active / ExperimentalHaar-based face detection baseline with filtering and eye validation.
cosmo/vision/recognition/PendingFuture embeddings, enrollment, and identity matching.
cosmo/vision/tracking/PendingFuture tracking and temporal smoothing.
cosmo/cognition/planner/PendingFuture task planning.

Startup and Bootstrap Flow

Startup begins in cosmo/main.py:

import asyncio
from cosmo.core.bootstrap.bootstrap import bootstrap

if __name__ == "__main__":
    asyncio.run(bootstrap.start())

Listener registration happens through import side effects in bootstrap.py.

ModuleBusEventHandler
system_listener.pysyncsystem_startedon_system_started
system_async_listener.pyasyncsystem_startedon_system_started
wakeword_listener.pyasyncwake_word_detectedon_wake_word_detected
stt_listener.pyasyncaudio_capturedon_audio_captured
transcript_listener.pyasynctranscript_readyon_transcript_ready
tts_listener.pyasyncresponse_generatedon_response_generated
conversation_listener.pysynccommand_receivedon_command_received (legacy)
vision_listener.pysyncuser_recognized, face_unknownLegacy recognition events are registered; recognition/enrollment producers are pending.

Shutdown sets lifecycle.running = False, emits system_shutdown on the sync bus, calls async_runtime.shutdown(), and logs completion.