1use serde::{Deserialize, Serialize};
6use std::collections::BTreeMap;
7
8fn default_true() -> bool {
9 true
10}
11
12#[derive(Serialize, Deserialize, Default, Clone, Copy, Debug, PartialEq)]
13pub enum PermissionMode {
14 #[default]
15 Developer,
16 ReadOnly,
17 SystemAdmin,
18}
19
20#[derive(Serialize, Deserialize, Default, Clone, Debug)]
21pub struct HematiteConfig {
22 #[serde(default)]
24 pub mode: PermissionMode,
25 pub permissions: Option<PermissionRules>,
27 #[serde(default)]
29 pub trust: WorkspaceTrustConfig,
30 pub model: Option<String>,
32 pub fast_model: Option<String>,
34 pub think_model: Option<String>,
36 #[serde(default = "default_true")]
38 pub gemma_native_auto: bool,
39 #[serde(default)]
41 pub gemma_native_formatting: bool,
42 pub api_url: Option<String>,
45 pub voice: Option<String>,
47 pub voice_speed: Option<f32>,
49 pub voice_volume: Option<f32>,
51 pub context_hint: Option<String>,
53 pub deno_path: Option<String>,
57 #[serde(default)]
59 pub verify: VerifyProfilesConfig,
60 #[serde(default)]
62 pub hooks: crate::agent::hooks::RuntimeHookConfig,
63}
64
65#[derive(Serialize, Deserialize, Clone, Debug)]
66pub struct WorkspaceTrustConfig {
67 #[serde(default = "default_trusted_workspace_roots")]
69 pub allow: Vec<String>,
70 #[serde(default)]
72 pub deny: Vec<String>,
73}
74
75impl Default for WorkspaceTrustConfig {
76 fn default() -> Self {
77 Self {
78 allow: default_trusted_workspace_roots(),
79 deny: Vec::new(),
80 }
81 }
82}
83
84fn default_trusted_workspace_roots() -> Vec<String> {
85 vec![".".to_string()]
86}
87
88#[derive(Serialize, Deserialize, Default, Clone, Debug)]
89pub struct VerifyProfilesConfig {
90 pub default_profile: Option<String>,
92 #[serde(default)]
94 pub profiles: BTreeMap<String, VerifyProfile>,
95}
96
97#[derive(Serialize, Deserialize, Default, Clone, Debug)]
98pub struct VerifyProfile {
99 pub build: Option<String>,
101 pub test: Option<String>,
103 pub lint: Option<String>,
105 pub fix: Option<String>,
107 pub timeout_secs: Option<u64>,
109}
110
111#[derive(Serialize, Deserialize, Default, Clone, Debug)]
112pub struct PermissionRules {
113 #[serde(default)]
115 pub allow: Vec<String>,
116 #[serde(default)]
118 pub ask: Vec<String>,
119 #[serde(default)]
121 pub deny: Vec<String>,
122}
123
124pub fn settings_path() -> std::path::PathBuf {
125 crate::tools::file_ops::hematite_dir().join("settings.json")
126}
127
128fn load_global_config() -> Option<HematiteConfig> {
130 let home = std::env::var_os("USERPROFILE").or_else(|| std::env::var_os("HOME"))?;
131 let path = std::path::PathBuf::from(home)
132 .join(".hematite")
133 .join("settings.json");
134 let data = std::fs::read_to_string(&path).ok()?;
135 serde_json::from_str(&data).ok()
136}
137
138pub fn load_config() -> HematiteConfig {
142 let path = settings_path();
143
144 let workspace: Option<HematiteConfig> = if path.exists() {
145 std::fs::read_to_string(&path)
146 .ok()
147 .and_then(|d| serde_json::from_str(&d).ok())
148 } else {
149 write_default_config(&path);
150 None
151 };
152
153 let global = load_global_config();
154
155 match (workspace, global) {
156 (Some(ws), Some(gb)) => {
157 HematiteConfig {
159 model: ws.model.or(gb.model),
160 fast_model: ws.fast_model.or(gb.fast_model),
161 think_model: ws.think_model.or(gb.think_model),
162 api_url: ws.api_url.or(gb.api_url),
163 voice: if ws.voice != HematiteConfig::default().voice {
164 ws.voice
165 } else {
166 gb.voice
167 },
168 voice_speed: ws.voice_speed.or(gb.voice_speed),
169 voice_volume: ws.voice_volume.or(gb.voice_volume),
170 context_hint: ws.context_hint.or(gb.context_hint),
171 gemma_native_auto: ws.gemma_native_auto,
172 gemma_native_formatting: ws.gemma_native_formatting,
173 ..ws
174 }
175 }
176 (Some(ws), None) => ws,
177 (None, Some(gb)) => gb,
178 (None, None) => HematiteConfig::default(),
179 }
180}
181
182pub fn save_config(config: &HematiteConfig) -> Result<(), String> {
183 let path = settings_path();
184 if let Some(parent) = path.parent() {
185 std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;
186 }
187 let json = serde_json::to_string_pretty(config).map_err(|e| e.to_string())?;
188 std::fs::write(&path, json).map_err(|e| e.to_string())
189}
190
191pub fn set_gemma_native_formatting(enabled: bool) -> Result<(), String> {
192 set_gemma_native_mode(if enabled { "on" } else { "off" })
193}
194
195pub fn set_gemma_native_mode(mode: &str) -> Result<(), String> {
196 let mut config = load_config();
197 match mode {
198 "on" => {
199 config.gemma_native_auto = false;
200 config.gemma_native_formatting = true;
201 }
202 "off" => {
203 config.gemma_native_auto = false;
204 config.gemma_native_formatting = false;
205 }
206 "auto" => {
207 config.gemma_native_auto = true;
208 config.gemma_native_formatting = false;
209 }
210 _ => return Err(format!("Unknown gemma native mode: {}", mode)),
211 }
212 save_config(&config)
213}
214
215pub fn set_voice(voice_id: &str) -> Result<(), String> {
216 let mut config = load_config();
217 config.voice = Some(voice_id.to_string());
218 save_config(&config)
219}
220
221pub fn effective_voice(config: &HematiteConfig) -> String {
222 config.voice.clone().unwrap_or_else(|| "af_sky".to_string())
223}
224
225pub fn effective_voice_speed(config: &HematiteConfig) -> f32 {
226 config.voice_speed.unwrap_or(1.0).clamp(0.5, 2.0)
227}
228
229pub fn effective_voice_volume(config: &HematiteConfig) -> f32 {
230 config.voice_volume.unwrap_or(1.0).clamp(0.0, 3.0)
231}
232
233pub fn effective_gemma_native_formatting(config: &HematiteConfig, model_name: &str) -> bool {
234 crate::agent::inference::is_gemma4_model_name(model_name)
235 && (config.gemma_native_formatting || config.gemma_native_auto)
236}
237
238pub fn gemma_native_mode_label(config: &HematiteConfig, model_name: &str) -> &'static str {
239 if !crate::agent::inference::is_gemma4_model_name(model_name) {
240 "inactive"
241 } else if config.gemma_native_formatting {
242 "on"
243 } else if config.gemma_native_auto {
244 "auto"
245 } else {
246 "off"
247 }
248}
249
250fn write_default_config(path: &std::path::Path) {
252 if let Some(parent) = path.parent() {
253 let _ = std::fs::create_dir_all(parent);
254 }
255 let default = r#"{
256 "_comment": "Hematite settings — edit and save, changes apply immediately without restart.",
257
258 "permissions": {
259 "allow": [
260 "cargo *",
261 "git status",
262 "git log *",
263 "git diff *",
264 "git branch *"
265 ],
266 "ask": [],
267 "deny": []
268 },
269
270 "trust": {
271 "allow": ["."],
272 "deny": []
273 },
274
275 "auto_approve_moderate": false,
276
277 "api_url": null,
278 "voice": null,
279 "voice_speed": null,
280 "voice_volume": null,
281 "context_hint": null,
282 "model": null,
283 "fast_model": null,
284 "think_model": null,
285 "gemma_native_auto": true,
286 "gemma_native_formatting": false,
287
288 "verify": {
289 "default_profile": null,
290 "profiles": {
291 "rust": {
292 "build": "cargo build --color never",
293 "test": "cargo test --color never",
294 "lint": "cargo clippy --all-targets --all-features -- -D warnings",
295 "fix": "cargo fmt",
296 "timeout_secs": 120
297 }
298 }
299 },
300
301 "hooks": {
302 "pre_tool_use": [],
303 "post_tool_use": []
304 }
305}
306"#;
307 let _ = std::fs::write(path, default);
308}
309
310pub fn permission_for_shell(cmd: &str, config: &HematiteConfig) -> PermissionDecision {
318 if let Some(rules) = &config.permissions {
319 for pattern in &rules.deny {
320 if glob_matches(pattern, cmd) {
321 return PermissionDecision::Deny;
322 }
323 }
324 for pattern in &rules.allow {
325 if glob_matches(pattern, cmd) {
326 return PermissionDecision::Allow;
327 }
328 }
329 for pattern in &rules.ask {
330 if glob_matches(pattern, cmd) {
331 return PermissionDecision::Ask;
332 }
333 }
334 }
335 PermissionDecision::UseRiskClassifier
336}
337
338#[derive(Debug, PartialEq)]
339pub enum PermissionDecision {
340 Allow,
341 Deny,
342 Ask,
343 UseRiskClassifier,
344}
345
346pub fn glob_matches(pattern: &str, text: &str) -> bool {
349 let p = pattern.to_lowercase();
350 let t = text.to_lowercase();
351 if p == "*" {
352 return true;
353 }
354 if let Some(star) = p.find('*') {
355 let prefix = &p[..star];
356 let suffix = &p[star + 1..];
357 t.starts_with(prefix) && (suffix.is_empty() || t.ends_with(suffix))
358 } else {
359 t.contains(&p)
360 }
361}