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

+137
View File
@@ -0,0 +1,137 @@
//! The seam between the HTTP/OpenAI layer and the token-level engine.
//!
//! The engine only ever sees and emits **token ids**. Everything that turns
//! chat messages into a token prompt, and the token stream back into text
//! split across reasoning / answer / tool calls, lives behind [`Formatter`] —
//! which the Inkling chat template + HF tokenizer + dialect parser will
//! implement. Keeping it a trait means the whole API layer (routing,
//! streaming, usage, finish reasons) is buildable and testable now, against a
//! trivial formatter, without the tokenizer wired up yet.
use crate::engine::{EngineError, Sampling};
use super::types::{ApiErrorEnvelope, ChatRequest};
/// What the engine needs for one generation: the prompt ids, a token budget,
/// and the per-request sampling keys.
#[derive(Debug, Clone)]
pub struct Prompt {
pub ids: Vec<u32>,
pub max_new: u32,
pub sampling: Sampling,
/// Per-request temp files (e.g. materialized images) the service removes
/// once generation is done. Empty for text-only requests.
pub temp_files: Vec<std::path::PathBuf>,
}
/// A decoded slice of the model's output, already classified. The formatter
/// decides what is thinking and what is the answer; the API layer just routes
/// them to `reasoning_content` vs `content`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Piece {
Reasoning(String),
Content(String),
/// A structured tool call parsed from the model output. `arguments` is the
/// JSON-encoded argument object, as OpenAI's `function.arguments` string.
ToolCall {
name: String,
arguments: String,
},
}
impl Piece {
pub fn is_empty(&self) -> bool {
match self {
Piece::Reasoning(s) | Piece::Content(s) => s.is_empty(),
Piece::ToolCall { .. } => false,
}
}
}
/// Incremental token->text decoder for one in-flight request. Fed one id at a
/// time as the engine streams `T`; may buffer (a BPE/dialect parser rarely
/// yields a whole grapheme per token) and returns zero or more pieces.
pub trait Decoder: Send {
fn push(&mut self, id: u32) -> Vec<Piece>;
/// Flush any held partial at end of stream. `reason` is the engine's finish
/// word (`"length"`, `"stop"`, ...): some dialects surface truncated
/// thinking only when the budget expired.
fn finish(&mut self, reason: Option<&str>) -> Vec<Piece>;
}
/// Messages <-> tokens + output parsing, for a specific model dialect.
pub trait Formatter: Send + Sync {
/// The id this formatter serves (reported in `/v1/models` and responses).
fn model_name(&self) -> &str;
/// The formatter's default token budget when the request sets none.
fn default_max_new(&self) -> u32 {
2048
}
/// Render the conversation to a prompt and derive the engine request.
/// Errors map straight to an HTTP 400.
fn build_prompt(&self, req: &ChatRequest) -> Result<Prompt, ApiErrorEnvelope>;
/// A fresh output decoder for one request.
fn decoder(&self) -> Box<dyn Decoder>;
}
/// Convenience: run a decoder over a whole id slice (the non-streaming path).
pub fn decode_all(dec: &mut dyn Decoder, ids: &[u32], reason: Option<&str>) -> Vec<Piece> {
let mut out = Vec::new();
for &id in ids {
out.extend(dec.push(id));
}
out.extend(dec.finish(reason));
out
}
/// Collapse pieces into (reasoning, content) strings.
pub fn split_pieces(pieces: Vec<Piece>) -> (String, String) {
let mut reasoning = String::new();
let mut content = String::new();
for p in pieces {
match p {
Piece::Reasoning(s) => reasoning.push_str(&s),
Piece::Content(s) => content.push_str(&s),
Piece::ToolCall { .. } => {}
}
}
(reasoning, content)
}
/// Everything a decoder produced, collapsed: reasoning text, answer text, and
/// the structured tool calls (name, JSON-encoded arguments) in emission order.
#[derive(Debug, Clone, Default)]
pub struct Decoded {
pub reasoning: String,
pub content: String,
pub tool_calls: Vec<(String, String)>,
}
/// Collapse pieces into a [`Decoded`], keeping tool calls structured.
pub fn decode_pieces(pieces: Vec<Piece>) -> Decoded {
let mut d = Decoded::default();
for p in pieces {
match p {
Piece::Reasoning(s) => d.reasoning.push_str(&s),
Piece::Content(s) => d.content.push_str(&s),
Piece::ToolCall { name, arguments } => d.tool_calls.push((name, arguments)),
}
}
d
}
/// Map an engine failure to an OpenAI error envelope + HTTP status code.
pub fn engine_error(err: EngineError) -> (u16, ApiErrorEnvelope) {
use crate::engine::EngineError::*;
let (status, kind, code) = match &err {
Refused(_) => (400, "invalid_request_error", Some("engine_refused")),
Silent(_) => (504, "engine_error", Some("engine_silent")),
Died | Spawn(_) => (503, "engine_error", Some("engine_unavailable")),
Startup(_) => (503, "engine_error", Some("engine_startup")),
};
let envelope = ApiErrorEnvelope::bad_request(err.to_string(), kind, code.map(str::to_string));
(status, envelope)
}