aboutsummaryrefslogtreecommitdiffstats
path: root/src/config.rs
blob: 95c1a18cfd22bd162889fda29dd2d74f38ebd0bd (plain) (blame)
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
use std::env;

pub const TEMP_PATH: &str = "/tmp/senator_sperma";

#[derive(Debug, Clone)]
pub struct Config {
    pub token: String,
    pub status_channel_id: Option<u64>,
    pub assistant_keyword: String,
    pub copyparty_url: String,
    pub copyparty_url_upload: String,
    pub copyparty_password: Option<String>,
    /// Deprecated – use llm_api_key instead
    pub openrouter_api_key: Option<String>,
    /// Deprecated – use llm_model instead
    pub openrouter_model: Option<String>,
    pub llm_api_key: Option<String>,
    pub llm_model: Option<String>,
    pub llm_api_url: String,
    pub database_path: String,
    /// Optional path to the Piper TTS `.onnx` model (or a directory of models).
    /// When unset, TTS falls back to Google Translate TTS.
    pub tts_model_path: Option<String>,
    /// Piper voice name, used to resolve the model file when `tts_model_path`
    /// points at a directory. Ignored when it points at a `.onnx` file directly.
    pub tts_voice: String,
    pub recording_enabled: bool,
    pub recording_window_seconds: u64,
}

struct EnvVar {
    name: &'static str,
    required: bool,
    default: Option<&'static str>,
    description: &'static str,
}

const ENV_VARS: &[EnvVar] = &[
    EnvVar {
        name: "TOKEN",
        required: true,
        default: None,
        description: "Discord bot token",
    },
    EnvVar {
        name: "STATUS_CHANNEL_ID",
        required: false,
        default: None,
        description: "status channel ID",
    },
    EnvVar {
        name: "ASSISTANT_KEYWORD",
        required: false,
        default: Some("jarvis"),
        description: "keyword for AI assistant",
    },
    EnvVar {
        name: "COPYPARTY_URL",
        required: false,
        default: Some("http://localhost:3939"),
        description: "Copyparty base URL",
    },
    EnvVar {
        name: "COPYPARTY_URL_UPLOAD",
        required: false,
        default: Some("http://localhost:3939"),
        description: "Copyparty upload URL",
    },
    EnvVar {
        name: "COPYPARTY_PASSWORD",
        required: false,
        default: None,
        description: "Copyparty auth password",
    },
    EnvVar {
        name: "OPENROUTER_API_KEY",
        required: false,
        default: None,
        description: "OpenRouter API key (disables AI if missing)",
    },
    EnvVar {
        name: "OPENROUTER_MODEL",
        required: false,
        default: Some("cognitivecomputations/dolphin-mistral-24b-venice-edition:free"),
        description: "OpenRouter model",
    },
    EnvVar {
        name: "LLM_API_KEY",
        required: false,
        default: None,
        description: "LLM API key (takes priority over OPENROUTER_API_KEY)",
    },
    EnvVar {
        name: "LLM_MODEL",
        required: false,
        default: None,
        description: "LLM model name (takes priority over OPENROUTER_MODEL)",
    },
    EnvVar {
        name: "LLM_API_URL",
        required: false,
        default: Some("https://openrouter.ai/api/v1/chat/completions"),
        description: "LLM API full URL including /chat/completions path",
    },
    EnvVar {
        name: "SENATOR_DB_PATH",
        required: false,
        default: Some("data/senator.db"),
        description: "SQLite database path",
    },
    EnvVar {
        name: "TTS_MODEL_PATH",
        required: false,
        default: None,
        description: "Path to a Piper TTS .onnx model (or a models directory). Unset => Google TTS fallback",
    },
    EnvVar {
        name: "TTS_VOICE",
        required: false,
        default: Some("pl_PL-bass-high"),
        description: "Piper TTS voice name (used when TTS_MODEL_PATH points at a directory)",
    },
    EnvVar {
        name: "RUST_LOG",
        required: false,
        default: Some("info"),
        description: "tracing/logging level filter",
    },
    EnvVar {
        name: "RECORDING_ENABLED",
        required: false,
        default: Some("true"),
        description: "enable continuous voice recording while in a VC (set false to opt out)",
    },
    EnvVar {
        name: "RECORDING_WINDOW_SECONDS",
        required: false,
        default: Some("900"),
        description: "rolling recording buffer length in seconds (memory ~sample_rate*2 bytes/sec)",
    },
];

pub fn check_env_vars() {
    let mut missing_required = Vec::new();
    let mut missing_optional = Vec::new();

    for var in ENV_VARS {
        match env::var(var.name) {
            Ok(_) => continue,
            Err(_) => {
                if var.required {
                    tracing::error!("MISSING REQUIRED: {} ({})", var.name, var.description);
                    missing_required.push(var.name);
                } else {
                    match var.default {
                        Some(default) => {
                            tracing::warn!("{} not set, using default: {}", var.name, default)
                        }
                        None => tracing::warn!("{} not set ({})", var.name, var.description),
                    }
                    missing_optional.push(var.name);
                }
            }
        }
    }

    if !missing_required.is_empty() {
        tracing::error!(
            "Missing required environment variables: {}. The application will not function correctly.",
            missing_required.join(", ")
        );
    }

    if !missing_optional.is_empty() {
        tracing::warn!(
            "Missing optional environment variables: {}. Some features will be disabled or use defaults.",
            missing_optional.join(", ")
        );
    }
}

impl Config {
    pub fn from_env() -> Self {
        let openrouter_api_key = env::var("OPENROUTER_API_KEY").ok();
        let openrouter_model = env::var("OPENROUTER_MODEL").ok();
        let llm_api_key = env::var("LLM_API_KEY").ok();
        let llm_model = env::var("LLM_MODEL").ok();

        // Warn about deprecated env vars (mirrors Python's BACKWARD_COMPAT_MSG)
        if openrouter_api_key.is_some() && llm_api_key.is_none() {
            tracing::warn!("OPENROUTER_API_KEY is deprecated. Use LLM_API_KEY instead.");
        }
        if openrouter_model.is_some() && llm_model.is_none() {
            tracing::warn!("OPENROUTER_MODEL is deprecated. Use LLM_MODEL instead.");
        }

        Self {
            token: env::var("TOKEN").expect("Missing TOKEN"),
            status_channel_id: env::var("STATUS_CHANNEL_ID")
                .ok()
                .and_then(|v| v.parse().ok()),
            assistant_keyword: env::var("ASSISTANT_KEYWORD").unwrap_or_else(|_| "jarvis".into()),
            recording_enabled: env::var("RECORDING_ENABLED")
                .unwrap_or_else(|_| "true".into())
                .parse()
                .unwrap_or(true),
            recording_window_seconds: env::var("RECORDING_WINDOW_SECONDS")
                .unwrap_or_else(|_| "900".into())
                .parse()
                .unwrap_or(900),
            copyparty_url: env::var("COPYPARTY_URL")
                .unwrap_or_else(|_| "http://localhost:3939".into()),
            copyparty_url_upload: env::var("COPYPARTY_URL_UPLOAD")
                .unwrap_or_else(|_| "http://localhost:3939".into()),
            copyparty_password: env::var("COPYPARTY_PASSWORD").ok(),
            openrouter_api_key,
            openrouter_model,
            llm_api_key,
            llm_model,
            llm_api_url: env::var("LLM_API_URL")
                .unwrap_or_else(|_| "https://openrouter.ai/api/v1/chat/completions".into()),
            database_path: env::var("SENATOR_DB_PATH").unwrap_or_else(|_| "data/senator.db".into()),
            tts_model_path: env::var("TTS_MODEL_PATH").ok(),
            tts_voice: env::var("TTS_VOICE").unwrap_or_else(|_| "pl_PL-bass-high".into()),
        }
    }

    /// Resolve the Piper model path to pass to the `piper` CLI.
    ///
    /// - `TTS_MODEL_PATH` set to a `.onnx` file => used verbatim.
    /// - `TTS_MODEL_PATH` set to a directory => `{dir}/{TTS_VOICE}.onnx`.
    /// - `TTS_MODEL_PATH` unset => `None` (caller falls back to Google TTS).
    pub fn piper_model_path(&self) -> Option<std::path::PathBuf> {
        let configured = self.tts_model_path.as_ref()?;
        let path = std::path::PathBuf::from(configured);
        if path.is_dir() {
            Some(path.join(format!("{}.onnx", self.tts_voice)))
        } else {
            Some(path)
        }
    }

    /// Resolve the effective LLM config: (api_url, api_key, model).
    /// LLM_* vars take priority; falls back to OPENROUTER_* for backward compat.
    pub fn resolve_llm(&self) -> (String, String, String) {
        let api_url = self.llm_api_url.clone();
        let api_key = self
            .llm_api_key
            .clone()
            .or_else(|| self.openrouter_api_key.clone())
            .unwrap_or_default();
        let model = self
            .llm_model
            .clone()
            .or_else(|| self.openrouter_model.clone())
            .unwrap_or_else(|| {
                "cognitivecomputations/dolphin-mistral-24b-venice-edition:free".into()
            });
        (api_url, api_key, model)
    }
}