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:
commit
597ac432e1
30 files changed
+7541
No files matched your search
+230
@@ -0,0 +1,230 @@
|
||||
//! 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 std::time::Duration;
|
||||
|
||||
use strata_ctl::api::{router, ChatService};
|
||||
use strata_ctl::config::{Config, ConfigError};
|
||||
use strata_ctl::engine::Engine;
|
||||
use strata_ctl::inkling::{ChatTemplate, InklingFormatter, InklingTokenizer};
|
||||
|
||||
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 {
|
||||
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 {
|
||||
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(),
|
||||
));
|
||||
|
||||
let engine = match Engine::start(
|
||||
&cfg.exe,
|
||||
&cfg.engine_argv(),
|
||||
cfg.cwd.as_deref(),
|
||||
Duration::from_secs(600),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(e) => Arc::new(e),
|
||||
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 app = router(svc);
|
||||
let addr = format!("{}:{}", cfg.bind_host(cli_host), cfg.bind_port(cli_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)");
|
||||
|
||||
let shutdown_engine = engine.clone();
|
||||
let result = axum::serve(listener, app)
|
||||
.with_graceful_shutdown(async move {
|
||||
let _ = tokio::signal::ctrl_c().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(", "));
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
Reference in new issue
Block a user