sayna
CLAUDE.md314 starsChanged 12 months agoApache-2.0View on GitHub
Sayna is a real-time voice processing server built in Rust that provides unified Speech-to-Text (STT) and Text-to-Speech (TTS) services through WebSocket and REST APIs. It integrates with LiveKit for real-time audio streaming and includes advanced noise filtering using DeepFilterNet. The codebase includes detailed development rules in .cursor/rules/: - rust.mdc: Rust best practices, design patterns, performance, security, testing - core.mdc: STT/TTS provider abstractions (BaseSTT, TTSProvider traits) - axum.mdc: Axum framework patterns for WebSocket and REST APIs - livekit.mdc: LiveKit integration patterns…
- Reads credentials
In this repository5 other files it gives its agents.
- .cursor/rules/axum.mdcCursor rule
- .cursor/rules/core.mdcCursor rule
- .cursor/rules/livekit.mdcCursor rule
- .cursor/rules/openapi.mdcCursor rule
- .cursor/rules/rust.mdcCursor rule
The file
We split this CLAUDE.md into the rules it gives an agent
9 rules. About 0 are common, 5 are distinctive, and 4 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈5
Distinctive · estimate
This author's own choices. Worth a look.
4
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 49
Always consult these rule files when implementing new features.
- Very specific: line 86
When stt-vad feature is enabled, Sayna provides both Silero-VAD for audio-level silence detection and smart-turn v3 model for semantic turn …
- Distinctive: line 111
When configurable silence threshold (default: 200ms per PipeCat recommendation) is detected, the smart-turn model is triggered
- Very specific: line 113
If confirmed, an artificial speech_final event is emitted
- Distinctive: line 114
If smart-turn returns false (turn incomplete), the system resets and waits for the next silence detection
- Distinctive: line 200
Create provider-specific config struct
- Distinctive: line 201
Add factory function following existing pattern
- Very specific: line 209
Update VoiceManager configuration support
- Very specific: line 266
Use #[tokio::test] for async tests
≈ “Common” is an estimate: at least 1 in 5 of the 12,729 CLAUDE.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
Project Overview
Sayna is a real-time voice processing server built in Rust that provides unified Speech-to-Text (STT) and Text-to-Speech (TTS) services through WebSocket and REST APIs. It integrates with LiveKit for real-time audio streaming and includes advanced noise filtering using DeepFilterNet.
Development Commands
cargo run # Run development server
cargo run -- -c config.yaml # Run with YAML config file
cargo test # Run all tests
cargo test test_name # Run specific test
cargo build --release # Build for release
cargo check # Check without building
cargo fmt # Format code
cargo clippy # Run linter
docker build -t saynaai/sayna . # Build Docker imageFeature Flags
By default, no optional features are enabled.
stt-vad(disabled by default): Silero-VAD voice activity detection with integrated ONNX-based turn detection. When enabled, VAD monitors audio for silence and triggers the turn detection model to confirm if the speaker's turn is complete.noise-filter(disabled by default): DeepFilterNet noise suppression. Disable to reduce dependencies.openapi(disabled by default): OpenAPI 3.1 specification generation using utoipa crate.
cargo check # Default build, no optional features
cargo check --no-default-features # Explicitly disable optional features
cargo build --features stt-vad # Enable VAD with turn detection
cargo build --features stt-vad,openapi # Enable specific features
cargo run --features openapi -- openapi -o docs/openapi.yaml # Generate OpenAPI specHigh-Level Architecture
Development Rules
The codebase includes detailed development rules in .cursor/rules/:
rust.mdc: Rust best practices, design patterns, performance, security, testingcore.mdc: STT/TTS provider abstractions (BaseSTT,TTSProvidertraits)axum.mdc: Axum framework patterns for WebSocket and REST APIslivekit.mdc: LiveKit integration patterns and WebSocket API detailsopenapi.mdc: OpenAPI 3.1 documentation guidelines using utoipa
Always consult these rule files when implementing new features.
Core Components
- VoiceManager (
src/core/voice_manager/): Central coordinator for STT/TTS- Manages provider lifecycle and switching
- Thread-safe with
Arc<RwLock<>>for concurrent access - Handles callbacks for STT results and audio output
- Provider System (
src/core/stt/andsrc/core/tts/):- Trait-based abstraction for pluggable providers
- STT: Deepgram, Google (gRPC), ElevenLabs, Microsoft Azure, Cartesia
- TTS: Deepgram, ElevenLabs, Google, Microsoft Azure, Cartesia
- WebSocket Handler (
src/handlers/ws/):- Real-time bidirectional communication at
/ws - Processes audio streams, config updates, control messages
- Real-time bidirectional communication at
- LiveKit Integration (
src/livekit/):- WebRTC audio streaming with room/participant management
- Audio track subscription and data message forwarding
- DeepFilterNet (
src/utils/noise_filter.rs):- Advanced noise reduction with thread pool for CPU-intensive operations
- Authentication (
src/auth/andsrc/middleware/auth.rs):- Optional JWT-based auth with external validation service
- VAD + Turn Detection (
src/core/vad/,src/core/turn_detect/) - Feature-gated:stt-vad:- SileroVAD: ONNX-based voice activity detection model
- SilenceTracker: Tracks continuous silence duration from VAD
- Turn Detection: ONNX-based model that confirms turn completion when silence is detected
- Integrates with VoiceManager for audio processing
- VAD and turn detection are always bundled together under
stt-vadfeature
Voice Activity Detection (VAD) with Turn Detection
When stt-vad feature is enabled, Sayna provides both Silero-VAD for audio-level silence detection and smart-turn v3 model for semantic turn detection. Both features are always bundled together under the stt-vad feature flag.
Why Use Both VAD and Smart-Turn?
VAD (Silero) provides:
- Fast, efficient silence detection (~2ms per frame)
- Low latency feedback on speech activity
- Immediate signal when user stops speaking
Smart-Turn provides:
- Semantic understanding of turn completion
- Higher accuracy (>90% for most languages)
- Context-aware decision making
Combined Pattern: VAD detects silence first (fast, cheap), then smart-turn confirms if the turn is semantically complete (more accurate, slightly slower). This two-stage approach provides both speed and accuracy.
How it works:
Audio In -> VAD -> SilenceTracker -> TurnEnd Event -> Smart-Turn -> speech_final
^ |
| |
+-- If false, reset and wait ---+- Audio frames are processed through Silero-VAD ONNX model
- When configurable silence threshold (default: 200ms per PipeCat recommendation) is detected, the smart-turn model is triggered
- The smart-turn model analyzes the accumulated audio to confirm if the turn is complete
- If confirmed, an artificial
speech_finalevent is emitted - If smart-turn returns false (turn incomplete), the system resets and waits for the next silence detection
Smart-Turn Model:
- Model: pipecat-ai/smart-turn-v3
- Version:
smart-turn-v3.2-cpu.onnx(quantized int8) - Input: Up to 8 seconds of 16kHz mono PCM audio (minimum 0.5 seconds required)
- Input Format: Mel spectrogram (1, 80, 800) via Whisper-style preprocessing
- Output: Probability that the speaker has finished their turn (0.0-1.0)
- Architecture: Whisper Tiny encoder + linear classifier (~8M parameters)
- Performance: Feature extraction ~10-30ms + model inference ~12-20ms = ~50ms total (release build)
Filler Sound Handling:
- Smart-Turn v2/v3 is explicitly trained on filler words ("um", "mmm", "ehhh")
- The model recognizes these as "user still thinking" patterns
- Audio buffer is preserved across speech pauses for full context analysis
- Minimum 0.5 seconds of audio required before turn detection runs
Mel Spectrogram Parameters (Whisper Standard):
- Sample Rate: 16000 Hz
- FFT Size: 400
- Hop Length: 160
- Mel Bins: 80
- Max Frames: 800 (8 seconds)
Configuration:
vad:
threshold: 0.5 # Speech probability threshold for VAD (0.0-1.0)
silence_duration_ms: 200 # Silence duration to trigger turn detection (PipeCat: stop_secs=0.2)
min_speech_duration_ms: 250 # Minimum speech before checking silence (filters filler sounds)
turn_detect:
threshold: 0.6 # Turn completion probability threshold (0.0-1.0), increased for robustness
num_threads: 4 # ONNX inference threads (default: 4)
# Advanced options (rarely need changing):
# model_path: /path/to/model.onnx # Override model location
# model_url: https://... # Override download URL
# use_quantized: true # Use int8 quantized model (default: true)Note: When
stt-vadis compiled, VAD and turn detection are always active. There is no runtimeenabledtoggle.
WebSocket API:
{
"type": "config",
"vad": {
"silence_duration_ms": 200
}
}Request Flow
- Client connects to
/wsWebSocket endpoint - Client sends config with provider selection
- Server sends
Readymessage withstream_idand LiveKit room info - Audio processing: Incoming audio → DeepFilterNet (optional) → STT → Text
- TTS: Text → TTS Provider → Audio → Client
- For LiveKit: Call
POST /livekit/tokento get participant token
Key Design Patterns
- Factory Pattern: Provider creation through factory functions
- Observer Pattern: Callback registration for STT/TTS events
- Singleton Pattern: Lazy static for DeepFilterNet model
- Actor Pattern: Message passing for WebSocket communication
Configuration
See config.example.yaml for all available options.
Priority: YAML File > Environment Variables > .env File > Defaults
Key environment variables:
DEEPGRAM_API_KEY,ELEVENLABS_API_KEY,CARTESIA_API_KEYGOOGLE_APPLICATION_CREDENTIALS(path to service account JSON)AZURE_SPEECH_SUBSCRIPTION_KEY,AZURE_SPEECH_REGIONLIVEKIT_URL,LIVEKIT_API_KEY,LIVEKIT_API_SECRETAUTH_REQUIRED,AUTH_SERVICE_URL,AUTH_SIGNING_KEY_PATH
Adding New Providers
STT Providers
- Implement
BaseSTTtrait insrc/core/stt/ - Create provider-specific config struct
- Add factory function following existing pattern
- Register in
src/core/stt/mod.rs(enum + factory) - Add tests
TTS Providers
- Implement
TTSProvidertrait insrc/core/tts/ - Add factory function
- Update
VoiceManagerconfiguration support - Add tests
See existing implementations for patterns:
- WebSocket-based: Deepgram, ElevenLabs, Cartesia, Azure
- gRPC-based: Google
API Endpoints
REST
GET /- Health check (public)GET /voices- List TTS voicesPOST /speak- Generate speech from textPOST /livekit/token- Generate LiveKit participant tokenGET /recording/{stream_id}- Download recording from S3GET/POST /sip/hooks- Manage SIP webhook hooks
WebSocket
/ws- Real-time voice processing- Receives: Config (optionally with
loading_audio), audio data, speak commands, clear command, loading_start, loading_stop, send_message, sip_transfer - Sends: Ready, STT results, TTS audio, messages, participant_connected, participant_disconnected, track_subscribed, tts_playback_complete, vad_event, error, sip_transfer_error
- Clear command: Immediately stops TTS and clears audio buffers (fire-and-forget, respects
allow_interruptionsetting) - Loading commands:
loading_start/loading_stopcontrol a looping loading-indicator audio clip that is mixed into the single published audio track (fire-and-forget, independent ofspeak/clear). It is summed under TTS by the audio pump so any single-track subscriber (browser or SIP) hears it
- Receives: Config (optionally with
Webhooks
POST /livekit/webhook- LiveKit event receiver (signature verified)
See docs/ for detailed API documentation.
Critical Files
src/core/voice_manager/manager.rs: Central voice processing orchestrationsrc/core/voice_manager/stt_result.rs: STT result processing with VAD integrationsrc/core/vad/detector.rs: Silero-VAD detector (feature-gated:stt-vad)src/core/vad/silence_tracker.rs: Silence duration tracking for turn detectionsrc/core/turn_detect/assets.rs: Model download and hash verification for smart-turn (feature-gated:stt-vad)src/core/turn_detect/config.rs: Configuration and constants for smart-turn detectionsrc/core/turn_detect/detector.rs: Smart-turn audio-based turn detection (feature-gated:stt-vad)src/core/turn_detect/feature_extractor.rs: Mel spectrogram extraction for smart-turn (feature-gated:stt-vad)src/core/turn_detect/model_manager.rs: ONNX model management for smart-turn (feature-gated:stt-vad)src/handlers/ws/handler.rs: WebSocket message handlingsrc/livekit/manager.rs: LiveKit room managementsrc/config/mod.rs: Configuration loading and mergingsrc/errors/mod.rs: Centralized error types (thiserror)src/docs/openapi.rs: OpenAPI spec generation (feature-gated:openapi)
Testing
cargo test # All tests
cargo test test_name # Specific test
cargo test -- --nocapture # With output
cargo test --features stt-vad # Tests including VAD feature tests- Unit tests: Embedded in modules using
#[cfg(test)] - Integration tests: In
/tests/directory - Use
#[tokio::test]for async tests
OpenAPI Documentation
# Generate YAML spec
cargo run --features openapi -- openapi -o docs/openapi.yaml
# Generate JSON spec
cargo run --features openapi -- openapi --format json -o docs/openapi.jsonSee .cursor/rules/openapi.mdc for annotation guidelines.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

