Files
strata-ctl/src/main.rs
T
adm 65f8111ba2 feat: file/image upload + separated framework root (sessions/data/uploads)
- POST /api/uploads: base64 -> shared ~/.strata-ctl/uploads store (uuid+ext),
  content-sniffed kind (image/text/binary), text token-counted via the model
  tokenizer; metadata persisted in a new uploads table.
- Chat attachments routed by kind: images -> Vision bridge (multipart image_url),
  small text (<=2000 tokens) inlined, large text/binary -> path + shell_exec
  reminder; binaries never inlined. Attachment context persisted with the turn.
- GUI: attach button + file picker, removable chips, attachments sent with the
  turn and shown on the user bubble; cleared on session switch.
- Framework root ~/.strata-ctl separated by type: sessions/<name>/, data/ (SQLite,
  moved from ~/.config/strata-ctl), uploads/. Legacy DB copied once on first run.
- count_tokens seam on Formatter (real tokenizer override) + ChatService.
- i18n: upload errors + attachment markers (backend) and attach.* (GUI), it+en.
- 121 tests + 2 ignored; clippy/fmt clean; validated live (upload routing, real
  tokenizer count, image->Vision answered "Rosso", new layout).
2026-11-25 16:25:55 +01:00

354 lines
12 KiB
Rust

//! strata-ctl CLI.
//!
//! Resolves the shared JSON config and either reports the launch plan (default)
//! or serves the OpenAI-compatible API (`--serve`): config -> Inkling
//! tokenizer + chat template -> formatter -> engine supervisor -> axum router.
use std::path::Path;
use std::process::ExitCode;
use std::sync::Arc;
use strata_ctl::api::{router_with_store, AuthConfig, ChatService};
use strata_ctl::config::{Config, ConfigError};
use strata_ctl::engine::Engine;
use strata_ctl::inkling::{ChatTemplate, InklingFormatter, InklingTokenizer};
use strata_ctl::store::{SqliteStore, Store};
const USAGE: &str = "\
strata-ctl — Rust control layer for the Strata engine (OpenAI-compatible API)
USAGE:
strata-ctl [OPTIONS]
OPTIONS:
--config <PATH> model config JSON (default: ~/.config/strata-inkling/strata-inkling.json)
--host <HOST> override the bind host from the config
--port <PORT> override the bind port from the config
--serve start the engine and serve the API (default: print the launch plan)
-h, --help show this help
";
struct Args {
config: Option<String>,
host: Option<String>,
port: Option<u16>,
serve: bool,
help: bool,
}
/// Hand-rolled flag parser: the surface mirrors the Python launcher and is far
/// smaller than a dependency on a CLI framework would justify.
fn parse_args<I: Iterator<Item = String>>(mut it: I) -> Result<Args, String> {
let mut args = Args {
config: None,
host: None,
port: None,
serve: false,
help: false,
};
while let Some(a) = it.next() {
match a.as_str() {
"-h" | "--help" => args.help = true,
"--serve" => args.serve = true,
"--config" => args.config = Some(it.next().ok_or("--config needs a value")?),
"--host" => args.host = Some(it.next().ok_or("--host needs a value")?),
"--port" => {
let v = it.next().ok_or("--port needs a value")?;
args.port = Some(v.parse().map_err(|_| format!("invalid --port: {v}"))?);
}
other if other.starts_with("--config=") => {
args.config = Some(other["--config=".len()..].to_string())
}
other if other.starts_with("--host=") => {
args.host = Some(other["--host=".len()..].to_string())
}
other if other.starts_with("--port=") => {
let v = &other["--port=".len()..];
args.port = Some(v.parse().map_err(|_| format!("invalid --port: {v}"))?);
}
other => return Err(format!("unknown argument: {other}")),
}
}
Ok(args)
}
#[tokio::main]
async fn main() -> ExitCode {
// Without a subscriber every tracing event (engine INFO, stream errors)
// would be silently dropped. RUST_LOG overrides the default `info` level.
tracing_subscriber::fmt()
.with_env_filter(
tracing_subscriber::EnvFilter::try_from_default_env()
.unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("info")),
)
.init();
let args = match parse_args(std::env::args().skip(1)) {
Ok(a) => a,
Err(e) => {
eprintln!("error: {e}\n\n{USAGE}");
return ExitCode::FAILURE;
}
};
if args.help {
print!("{USAGE}");
return ExitCode::SUCCESS;
}
let path = match &args.config {
Some(p) => std::path::PathBuf::from(p),
None => Config::default_path(),
};
let cfg = match Config::load(&path) {
Ok(c) => c,
Err(e) => return report_config_error(&path, e),
};
print_plan(&cfg, &path, args.host.as_deref(), args.port);
if args.serve {
serve(&cfg, args.host.as_deref(), args.port).await
} else {
ExitCode::SUCCESS
}
}
/// Start the engine from the config and serve the OpenAI-compatible API.
async fn serve(cfg: &Config, cli_host: Option<&str>, cli_port: Option<u16>) -> ExitCode {
strata_ctl::i18n::init(&cfg.language());
let dir = match &cfg.tokenizer {
Some(d) => d.clone(),
None => {
eprintln!("error: config has no `tokenizer` directory; cannot build the formatter");
return ExitCode::FAILURE;
}
};
let tok = match InklingTokenizer::load_dir(Path::new(&dir)) {
Ok(t) => Arc::new(t),
Err(e) => {
eprintln!("error: {e}");
return ExitCode::FAILURE;
}
};
let tpl_path = Path::new(&dir).join("chat_template.jinja");
let src = match std::fs::read_to_string(&tpl_path) {
Ok(s) => s,
Err(e) => {
eprintln!("error: cannot read {}: {e}", tpl_path.display());
return ExitCode::FAILURE;
}
};
let template = match ChatTemplate::new(&src) {
Ok(t) => t,
Err(e) => {
eprintln!("error: chat template: {e}");
return ExitCode::FAILURE;
}
};
let fmt = Arc::new(InklingFormatter::new(
tok,
template,
cfg.model_name().to_string(),
cfg.reasoning_effort.clone(),
cfg.sampling.to_sampling(),
));
let engine = match Engine::start(
&cfg.exe,
&cfg.engine_argv(),
cfg.cwd.as_deref(),
cfg.startup_timeout(),
)
.await
{
Ok(e) => Arc::new(e.with_silence(cfg.silence_timeout())),
Err(e) => {
eprintln!("error: the engine failed to start: {e}");
return ExitCode::FAILURE;
}
};
println!(
"\nengine READY (context {} tokens); serving model {}",
engine.ready().max_context,
cfg.model_name()
);
let svc = ChatService::new(engine.clone(), fmt);
let auth = AuthConfig {
api_key: cfg.api_key.clone(),
allowed_hosts: cfg.allowed_hosts.clone().unwrap_or_default(),
};
// Open the GUI session store (SQLite). The web GUI + session API are mounted
// only when this succeeds; the standard /v1 API is unaffected either way.
let db_path = cfg.gui_db_path();
migrate_legacy_db(&db_path);
let store: Arc<dyn Store> = match SqliteStore::open(&db_path) {
Ok(s) => Arc::new(s),
Err(e) => {
eprintln!(
"error: cannot open session database {}: {e}",
db_path.display()
);
return ExitCode::FAILURE;
}
};
// Seed the global default settings template from the config (once). Each
// new session snapshots these defaults at creation (copy-on-create).
if matches!(store.get_defaults(), Ok(None)) {
let _ = store.set_defaults(&cfg.default_settings());
}
let app = router_with_store(svc, store, auth, cfg.workspace_root());
let host = cfg.bind_host(cli_host);
let port = cfg.bind_port(cli_port);
if !is_loopback_host(&host) && cfg.api_key.is_none() {
tracing::warn!(
host = %host,
"binding a non-loopback address with NO API key: anyone on the network \
can use the API (set `api_key` in the config to require authentication)"
);
}
let addr = format!("{host}:{port}");
let listener = match tokio::net::TcpListener::bind(&addr).await {
Ok(l) => l,
Err(e) => {
eprintln!("error: cannot bind {addr}: {e}");
return ExitCode::FAILURE;
}
};
println!("listening on http://{addr} (Ctrl-C to stop)");
println!(
"web GUI: http://{addr}/ (sessions db: {})",
db_path.display()
);
let shutdown_engine = engine.clone();
let result = axum::serve(listener, app)
.with_graceful_shutdown(async move {
wait_for_shutdown_signal().await;
println!("\nshutting down");
let _ = shutdown_engine.shutdown().await;
})
.await;
if let Err(e) = result {
eprintln!("error: server: {e}");
return ExitCode::FAILURE;
}
ExitCode::SUCCESS
}
fn print_plan(cfg: &Config, path: &std::path::Path, cli_host: Option<&str>, cli_port: Option<u16>) {
let host = cfg.bind_host(cli_host);
let port = cfg.bind_port(cli_port);
let ignored = cfg.ignored_keys();
println!("config: {}", path.display());
println!("model: {}", cfg.model_name());
println!("bind: {host}:{port}");
println!("cwd: {}", cfg.cwd.as_deref().unwrap_or("(process cwd)"));
println!(
"tokenizer: {}",
cfg.tokenizer.as_deref().unwrap_or("(none configured)")
);
println!(
"reasoning_effort: {}",
cfg.reasoning_effort.as_deref().unwrap_or("(default)")
);
println!(
"sampling: temp={:?} top_p={:?} min_p={:?} rep_pen={:?}",
cfg.sampling.temperature,
cfg.sampling.top_p,
cfg.sampling.min_p,
cfg.sampling.repetition_penalty
);
println!("\nwould spawn:");
println!(" {} {}", cfg.exe, cfg.engine_argv().join(" "));
if !ignored.is_empty() {
println!("\nignored keys (left for other tools / not yet acted on):");
println!(" {}", ignored.join(", "));
}
}
/// One-time relocation of the session DB from the old default
/// (`~/.config/strata-ctl/sessions.db`) into the framework `data/` dir. Copies
/// (never deletes) the legacy file plus any WAL/SHM siblings, so existing
/// history is preserved. A no-op once the new path exists or no legacy DB is
/// present.
fn migrate_legacy_db(db_path: &Path) {
if db_path.exists() {
return;
}
let home = std::env::var("HOME").unwrap_or_default();
let legacy = Path::new(&home).join(".config/strata-ctl/sessions.db");
if !legacy.exists() || legacy == db_path {
return;
}
if let Some(parent) = db_path.parent() {
let _ = std::fs::create_dir_all(parent);
}
for suffix in ["", "-wal", "-shm"] {
let mut from = legacy.as_os_str().to_os_string();
from.push(suffix);
let mut to = db_path.as_os_str().to_os_string();
to.push(suffix);
if Path::new(&from).exists() {
let _ = std::fs::copy(&from, &to);
}
}
tracing::info!(
from = %legacy.display(),
to = %db_path.display(),
"relocated legacy session database into the framework data dir"
);
}
fn report_config_error(path: &std::path::Path, err: ConfigError) -> ExitCode {
eprintln!("error: {err}");
if let ConfigError::MissingExe = err {
eprintln!(" (check the `exe` field in {})", path.display());
}
ExitCode::FAILURE
}
/// Resolve on Ctrl-C (SIGINT) or SIGTERM (systemd's default stop signal).
async fn wait_for_shutdown_signal() {
let ctrl_c = tokio::signal::ctrl_c();
let mut sigterm = match tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())
{
Ok(s) => s,
Err(e) => {
tracing::warn!(error = %e, "cannot install SIGTERM handler; SIGINT only");
let _ = ctrl_c.await;
return;
}
};
tokio::select! {
_ = ctrl_c => {},
_ = sigterm.recv() => {},
}
}
/// True for `localhost` and literal loopback IPs (127.0.0.1, ::1). Wildcard
/// binds (0.0.0.0, ::) and LAN addresses are NOT loopback.
fn is_loopback_host(host: &str) -> bool {
if host.eq_ignore_ascii_case("localhost") {
return true;
}
host.parse::<std::net::IpAddr>()
.map(|ip| ip.is_loopback())
.unwrap_or(false)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn loopback_detection() {
for h in ["127.0.0.1", "::1", "localhost", "LOCALHOST"] {
assert!(is_loopback_host(h), "{h} should be loopback");
}
for h in ["0.0.0.0", "::", "192.168.1.10", "10.0.0.5"] {
assert!(!is_loopback_host(h), "{h} should NOT be loopback");
}
}
}