strata-ctl: Rust control layer for the Strata engine (OpenAI-compatible API)

From-scratch rewrite of the Python serve (Python kept as behavioral spec).

- engine: line-protocol supervisor (GEN/T/DONE/STOP/QUIT), silence watchdog,
  abort, is_idle probe.
- config: tolerant shared-JSON loader; foreign keys ignored so one file drives
  strata-ctl and uostream; CLI --config/--host/--port/--serve.
- inkling: o200k tokenizer wrapper + incremental UTF-8-safe detok; chat template
  via minijinja; channel-token dialect (reasoning streamed live); image bridge
  (in-process Vision, image=<path>); formatter assembling the API seam.
- api: /v1/chat/completions (stream SSE + non-stream), /v1/models, /health;
  reasoning_content; structured tool_calls (llama.cpp --jinja style, client-side
  execution); stop sequences with hold-back; abort on client disconnect.

69 tests green + 2 real-file ignored; clippy clean. Text, images and tools
validated live against the real Inkling engine.
This commit is contained in:
adm committed 2026-11-24 05:28:56 +01:00
commit 597ac432e1
30 files changed
+7541

No files matched your search

+284
View File
@@ -0,0 +1,284 @@
//! 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 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<f64>,
#[serde(default)]
pub top_p: Option<f64>,
#[serde(default)]
pub min_p: Option<f64>,
#[serde(default)]
pub repetition_penalty: Option<f64>,
#[serde(flatten)]
pub extra: BTreeMap<String, serde_json::Value>,
}
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<String>,
#[serde(default)]
pub cwd: Option<String>,
/// HF tokenizer directory (consumed by the Inkling formatter, later).
#[serde(default)]
pub tokenizer: Option<String>,
#[serde(default)]
pub model_name: Option<String>,
/// Bind overrides (a CLI flag still wins over these).
#[serde(default)]
pub host: Option<String>,
#[serde(default)]
pub port: Option<u16>,
/// Chain-of-thought effort; the formatter applies it (was the Python
/// launcher's monkey-patch).
#[serde(default)]
pub reasoning_effort: Option<String>,
#[serde(default)]
pub sampling: SamplingDefaults,
/// 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<String, serde_json::Value>,
}
#[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<Config, ConfigError> {
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<Config, ConfigError> {
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<String> {
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>) -> u16 {
cli.or(self.port).unwrap_or(8095)
}
/// 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",
"allowed_hosts",
"drafting",
"mcp_servers",
] {
assert!(cfg.extra.contains_key(k), "{k} should be in ignored extras");
}
}
#[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");
}
}