//! Tolerant loader for the shared model config (`strata-inkling.json`). //! //! The same file configures several tools — this control layer, the upstream //! web shell, and the user's "uostream" front-end. So the contract is: //! **read what we understand, ignore everything else without failing.** In //! serde terms that means no `deny_unknown_fields`; every key we don't consume //! is captured in [`Config::extra`] so `--check` can report exactly what was //! skipped, and an unknown or future key can never break startup. //! //! We deliberately do NOT declare fields we don't act on yet (`arch`, //! `drafting`, `mcp_servers`, `cors_origins`, `allowed_hosts`, ...): they fall //! into `extra` untouched, which is precisely the "ignore what isn't ours" //! behaviour requested. use std::collections::BTreeMap; use std::path::{Path, PathBuf}; use std::time::Duration; use serde::Deserialize; use crate::engine::protocol::Sampling; /// Per-request sampling defaults, the shape found under the JSON's `sampling` /// key. Extra knobs inside `sampling` are likewise tolerated and kept. #[derive(Debug, Clone, Default, Deserialize)] pub struct SamplingDefaults { #[serde(default)] pub temperature: Option, #[serde(default)] pub top_p: Option, #[serde(default)] pub min_p: Option, #[serde(default)] pub repetition_penalty: Option, #[serde(flatten)] pub extra: BTreeMap, } impl SamplingDefaults { /// The engine `GEN` sampling keys implied by these defaults. Only /// meaningful values become keys (e.g. `repetition_penalty = 1.0` is the /// neutral value and is dropped, matching the engine's own spelling). pub fn to_sampling(&self) -> Sampling { Sampling { temperature: self.temperature, top_p: self.top_p, min_p: self.min_p, repetition_penalty: self.repetition_penalty, ..Default::default() } } } /// The subset of the config this layer acts on; everything else lives in /// [`Config::extra`]. #[derive(Debug, Clone, Deserialize)] pub struct Config { /// Engine binary to spawn (required). #[serde(default)] pub exe: String, /// Arguments passed verbatim after `--serve`. #[serde(default)] pub args: Vec, #[serde(default)] pub cwd: Option, /// HF tokenizer directory (consumed by the Inkling formatter, later). #[serde(default)] pub tokenizer: Option, #[serde(default)] pub model_name: Option, /// Bind overrides (a CLI flag still wins over these). #[serde(default)] pub host: Option, #[serde(default)] pub port: Option, /// Chain-of-thought effort; the formatter applies it (was the Python /// launcher's monkey-patch). #[serde(default)] pub reasoning_effort: Option, /// Default generation budget (`max_new` tokens) when neither the request nor /// the session sets one. Reasoning + answer share it; the default is raised /// (16384) so chain-of-thought is not truncated mid-reasoning at the old 2048. #[serde(default)] pub max_new: Option, #[serde(default)] pub sampling: SamplingDefaults, /// General default System Prompt, snapshotted into each new GUI session. #[serde(default)] pub system_prompt: Option, /// Framework root (default `~/.strata-ctl`, the Linux user's home). Content /// is separated into subfolders by type: `sessions/` (agent workspace /// folders), `data/` (SQLite), `uploads/` (uploaded files). #[serde(default)] pub workspace_root: Option, /// UI / model-prompt language (catalog key, e.g. "it", "en"). Defaults to Italian. #[serde(default)] pub language: Option, /// Startup (wait for `READY`) and silence-watchdog timeouts, in seconds. /// Optional: both default to 600s when absent. #[serde(default)] pub startup_timeout_secs: Option, #[serde(default)] pub silence_timeout_secs: Option, /// Optional bearer API key. When set, every request except `/health` must /// carry it (`Authorization: Bearer ...` or `x-api-key`). #[serde(default)] pub api_key: Option, /// Host-header allowlist. Absent/empty or `["*"]` allows any host; otherwise /// the request `Host` must match one of these (DNS-rebinding protection). #[serde(default)] pub allowed_hosts: Option>, /// Path to the GUI session database (SQLite). Defaults to /// `/data/sessions.db`. #[serde(default)] pub db_path: Option, /// Keys we understand but don't act on yet are NOT listed above, so they /// arrive here untouched — the "ignore what isn't ours" guarantee. #[serde(flatten)] pub extra: BTreeMap, } #[derive(Debug, thiserror::Error)] pub enum ConfigError { #[error("cannot read {path}: {source}")] Io { path: String, #[source] source: std::io::Error, }, #[error("invalid JSON in {path}: {source}")] Parse { path: String, #[source] source: serde_json::Error, }, #[error("`exe` is required (the Strata engine binary to spawn)")] MissingExe, } impl Config { /// Read and validate a config file. pub fn load(path: &Path) -> Result { let text = std::fs::read_to_string(path).map_err(|source| ConfigError::Io { path: path.display().to_string(), source, })?; let cfg = Self::parse(&text, &path.display().to_string())?; Ok(cfg) } /// Parse from a JSON string (the `path` argument is only for error text). pub fn parse(text: &str, path: &str) -> Result { let cfg: Config = serde_json::from_str(text).map_err(|source| ConfigError::Parse { path: path.to_string(), source, })?; if cfg.exe.trim().is_empty() { return Err(ConfigError::MissingExe); } Ok(cfg) } /// Default config location, mirroring the Python launcher. pub fn default_path() -> PathBuf { let home = std::env::var("HOME").unwrap_or_default(); PathBuf::from(home).join(".config/strata-inkling/strata-inkling.json") } /// The full argv for the engine child: `--serve` first (once), then the /// configured args. Idempotent — many configs already include `--serve`. pub fn engine_argv(&self) -> Vec { let mut argv = Vec::with_capacity(self.args.len() + 1); if !self.args.iter().any(|a| a == "--serve") { argv.push("--serve".to_string()); } argv.extend(self.args.iter().cloned()); argv } /// Model id to advertise, defaulting to the exe's file name. pub fn model_name(&self) -> &str { self.model_name.as_deref().unwrap_or_else(|| { Path::new(&self.exe) .file_name() .and_then(|s| s.to_str()) .unwrap_or("strata") }) } /// Effective bind host: CLI override > config > `127.0.0.1`. pub fn bind_host(&self, cli: Option<&str>) -> String { cli.or(self.host.as_deref()) .unwrap_or("127.0.0.1") .to_string() } /// Effective bind port: CLI override > config > `8095`. pub fn bind_port(&self, cli: Option) -> u16 { cli.or(self.port).unwrap_or(8095) } /// Timeout waiting for the engine's `READY` line (default 600s). pub fn startup_timeout(&self) -> Duration { Duration::from_secs(self.startup_timeout_secs.unwrap_or(600)) } /// Silence watchdog: max gap between engine output lines (default 600s). pub fn silence_timeout(&self) -> Duration { Duration::from_secs(self.silence_timeout_secs.unwrap_or(600)) } /// Effective GUI database path: config > `/data/sessions.db`. pub fn gui_db_path(&self) -> PathBuf { if let Some(p) = &self.db_path { return PathBuf::from(p); } self.data_dir().join("sessions.db") } /// The global default settings template for new GUI sessions, seeded from /// the config's general system prompt and sampling defaults. Each session /// snapshots this at creation (copy-on-create) and then owns its instance. pub fn default_settings(&self) -> crate::store::SessionSettings { crate::store::SessionSettings { system_prompt: self.system_prompt.clone(), temperature: self.sampling.temperature, top_p: self.sampling.top_p, min_p: self.sampling.min_p, repetition_penalty: self.sampling.repetition_penalty, ..Default::default() } } /// Effective framework root: config > `~/.strata-ctl` (the Linux user's /// home). Content is separated into subfolders by type. pub fn workspace_root(&self) -> PathBuf { if let Some(p) = &self.workspace_root { return PathBuf::from(p); } let home = std::env::var("HOME").unwrap_or_default(); PathBuf::from(home).join(".strata-ctl") } /// Per-session personal workspace folders: `/sessions/`. pub fn sessions_dir(&self) -> PathBuf { self.workspace_root().join("sessions") } /// SQLite store directory: `/data`. pub fn data_dir(&self) -> PathBuf { self.workspace_root().join("data") } /// Shared upload store: `/uploads`. pub fn upload_dir(&self) -> PathBuf { self.workspace_root().join("uploads") } /// Effective language: config > `it`. pub fn language(&self) -> String { self.language.clone().unwrap_or_else(|| "it".to_string()) } /// Effective default generation budget: config `max_new` > 16384. This is the /// ceiling on reasoning + answer tokens when a request/session sets none. pub fn max_new_default(&self) -> u32 { self.max_new.unwrap_or(16384) } /// The top-level keys present in the file that we are not acting on — /// reported by `--check` so the shared-file contract stays visible. pub fn ignored_keys(&self) -> Vec<&str> { self.extra.keys().map(|k| k.as_str()).collect() } } #[cfg(test)] mod tests { use super::*; // The user's real config, verbatim shape. const REAL: &str = r#"{ "arch": "inkling2_loop", "exe": "/home/federico/Sviluppo/Progetti/strata/build-inkling/strata-inkling", "args": ["--serve", "--native", "/mnt/models/Inkling/model.gguf", "--max-context", "262144", "--parallel", "1"], "cwd": "/home/federico/Sviluppo/Progetti/strata/build-inkling", "tokenizer": "/home/federico/.config/strata-inkling/inkling-tok", "model_name": "Inkling-2-Mini", "host": "0.0.0.0", "cors_origins": ["*"], "allowed_hosts": ["*"], "reasoning_effort": "low", "drafting": "off", "mcp_servers": { "web_shell": { "command": "python3", "args": ["web_shell_mcp.py"] } }, "sampling": { "temperature": 1.0, "top_p": 1.0, "min_p": 0.0, "repetition_penalty": 1.0 } }"#; #[test] fn reads_the_fields_we_care_about() { let cfg = Config::parse(REAL, "test").unwrap(); assert!(cfg.exe.ends_with("strata-inkling")); assert_eq!(cfg.args.len(), 7); assert_eq!(cfg.model_name(), "Inkling-2-Mini"); assert_eq!(cfg.host.as_deref(), Some("0.0.0.0")); assert_eq!(cfg.reasoning_effort.as_deref(), Some("low")); assert_eq!(cfg.sampling.temperature, Some(1.0)); assert_eq!( cfg.tokenizer.as_deref().unwrap(), "/home/federico/.config/strata-inkling/inkling-tok" ); } #[test] fn foreign_keys_are_captured_not_fatal() { // the same file also carries uostream / other-tool settings let with_other = r#"{ "exe": "/x/strata-inkling", "uostream": { "theme": "dark", "telemetry": true }, "future_key": [1, 2, 3], "args": ["--serve"] }"#; let cfg = Config::parse(with_other, "test").unwrap(); assert_eq!(cfg.exe, "/x/strata-inkling"); assert!(cfg.extra.contains_key("uostream")); assert!(cfg.extra.contains_key("future_key")); let ignored = cfg.ignored_keys(); assert!(ignored.contains(&"uostream") && ignored.contains(&"future_key")); } #[test] fn known_but_unused_fields_report_as_ignored() { let cfg = Config::parse(REAL, "test").unwrap(); // we don't act on these yet, so they must not be lost or cause errors for k in ["arch", "cors_origins", "drafting", "mcp_servers"] { assert!(cfg.extra.contains_key(k), "{k} should be in ignored extras"); } } #[test] fn auth_fields_are_read() { let cfg = Config::parse( r#"{"exe":"/x/e","api_key":"secret","allowed_hosts":["a.com","b.com"]}"#, "test", ) .unwrap(); assert_eq!(cfg.api_key.as_deref(), Some("secret")); assert_eq!( cfg.allowed_hosts.as_deref(), Some(["a.com".to_string(), "b.com".to_string()].as_slice()) ); // the real config: no key, wildcard hosts (open) let real = Config::parse(REAL, "test").unwrap(); assert!(real.api_key.is_none()); assert_eq!( real.allowed_hosts.as_deref(), Some(["*".to_string()].as_slice()) ); } #[test] fn engine_argv_adds_serve_once() { // REAL args already contain --serve -> no duplicate let cfg = Config::parse(REAL, "test").unwrap(); let argv = cfg.engine_argv(); assert_eq!(argv.iter().filter(|a| *a == "--serve").count(), 1); // a config without --serve gets it prepended let no_serve = r#"{"exe":"/x/e","args":["--native","m.gguf"]}"#; let argv = Config::parse(no_serve, "test").unwrap().engine_argv(); assert_eq!(argv, vec!["--serve", "--native", "m.gguf"]); } #[test] fn missing_exe_is_an_error() { let err = Config::parse(r#"{"args":["--serve"]}"#, "test").unwrap_err(); assert!(matches!(err, ConfigError::MissingExe)); let err = Config::parse(r#"{"exe":" "}"#, "test").unwrap_err(); assert!(matches!(err, ConfigError::MissingExe)); } #[test] fn bind_precedence_cli_over_config_over_default() { let cfg = Config::parse(REAL, "test").unwrap(); assert_eq!(cfg.bind_host(None), "0.0.0.0"); assert_eq!(cfg.bind_host(Some("127.0.0.1")), "127.0.0.1"); assert_eq!(cfg.bind_port(None), 8095); // not in JSON -> default assert_eq!(cfg.bind_port(Some(1234)), 1234); } #[test] fn sampling_defaults_map_to_engine_keys() { let cfg = Config::parse(REAL, "test").unwrap(); let s = cfg.sampling.to_sampling(); // temperature 1.0 is > 0 so it is sent; repetition_penalty 1.0 is the // neutral value so the engine-spelling builder drops it; min_p 0.0 off. assert_eq!(s.temperature, Some(1.0)); assert_eq!(s.repetition_penalty, Some(1.0)); let keys = s.keys(); assert_eq!(keys, " temperature=1.0"); } #[test] fn max_new_default_and_override() { let cfg = Config::parse(REAL, "test").unwrap(); assert_eq!(cfg.max_new_default(), 16384); // absent -> raised default let cfg2 = Config::parse(r#"{"exe":"/x/e","max_new":8192}"#, "test").unwrap(); assert_eq!(cfg2.max_new_default(), 8192); } #[test] fn timeouts_default_and_override() { let cfg = Config::parse(REAL, "test").unwrap(); assert_eq!(cfg.startup_timeout(), Duration::from_secs(600)); assert_eq!(cfg.silence_timeout(), Duration::from_secs(600)); let cfg2 = Config::parse( r#"{"exe":"/x/e","startup_timeout_secs":30,"silence_timeout_secs":120}"#, "test", ) .unwrap(); assert_eq!(cfg2.startup_timeout(), Duration::from_secs(30)); assert_eq!(cfg2.silence_timeout(), Duration::from_secs(120)); } #[test] fn gui_db_path_default_and_override() { let cfg = Config::parse(REAL, "test").unwrap(); assert!(cfg.gui_db_path().ends_with(".strata-ctl/data/sessions.db")); let cfg2 = Config::parse(r#"{"exe":"/x/e","db_path":"/tmp/x.db"}"#, "test").unwrap(); assert_eq!(cfg2.gui_db_path(), PathBuf::from("/tmp/x.db")); } #[test] fn framework_root_separates_content_types() { let cfg = Config::parse(r#"{"exe":"/x/e","workspace_root":"/tmp/fwk"}"#, "test").unwrap(); assert_eq!(cfg.workspace_root(), PathBuf::from("/tmp/fwk")); assert_eq!(cfg.sessions_dir(), PathBuf::from("/tmp/fwk/sessions")); assert_eq!(cfg.data_dir(), PathBuf::from("/tmp/fwk/data")); assert_eq!(cfg.upload_dir(), PathBuf::from("/tmp/fwk/uploads")); assert_eq!( cfg.gui_db_path(), PathBuf::from("/tmp/fwk/data/sessions.db") ); } }