Files
leleka/control-plane/src/cli/model_text.rs
T
Pavlo Ratushnyi 3530208024 STRA-338 S7: AppState in four groups, app/ routes split by role, main.rs becomes a dispatcher plus the composition root
AppState (app/state.rs) is now lifecycle + EngineLink (client port, control channel, worker status, pool,
queue timeout) + HttpPolicy (api key, CORS, trusted origins) + ModelView (name, aliases, tokenizer, template,
vision port, prefix-cache and memory views) + Services (response store, monitor, MCP port, settings, clock,
started_at). Field uses were rewritten mechanically (state.worker -> state.engine.worker, ...); no handler logic
changed. The old impl_default_for_appstate.rs, which held the route table and the admin handlers, is app/routes.rs,
app/admin_routes.rs and app/readiness.rs.

main.rs (1156 lines: an 840-line argument match, the serve function, two helpers) is now 8 lines. The argument match
is split into command groups under src/cli/ (operations, model_fetch, model_inspect, model_ensure, model_prepare,
kar_inspect, kar_verify, kar_overlay, model_text; each owns its arms in their old order and answers Ok(false) for a
line it does not own), serve() and shutdown_signal() are src/serve.rs (the composition root), the usage text is
cli/usage.rs. The binary name and every command line are unchanged.

Architecture gate: control-plane/src/main.rs leaves the oversize list (1156 -> 8). --allow-increase was used because
the type change forces the AppState struct literals in seven already-oversize test/example files to nest by group:
cp_replay.rs +7, responses/tests.rs +11, backend_worker_http.rs +14, mcp_hub.rs +3, memory_gate_http.rs +7,
vision_http.rs +6, desktop-core api_over_runtime.rs +6 (55 lines in all, against 1148 lines removed from main.rs).
Test outcomes are unchanged (597 ok / 2 ignored before and after, 14 new tests from S16).
2026-11-05 20:22:10 +01:00

149 lines
6.2 KiB
Rust

//! `model` commands on the tokenizer and the chat template: extract, tokenize, detokenize, render.
use std::{io::Read, path::Path};
use strata_control::{BoxError, tokenizer, tokenizer_assets};
/// Run the command in `args` if this group owns it; `Ok(false)` when it does not.
pub async fn run(args: &[String]) -> Result<bool, BoxError> {
let handled: Result<(), BoxError> = match args {
[model, action, path, flag, output]
if model == "model" && action == "extract-tokenizer" && flag == "--output" =>
{
let destination = tokenizer_assets::extract(Path::new(path), Path::new(output))?;
println!("extracted {}", destination.display());
Ok(())
}
[model, action, path, input]
if model == "model" && action == "tokenize" && input != "--stdin" =>
{
let tokenizer = tokenizer::Tokenizer::from_assets(Path::new(path))?;
println!(
"{}",
serde_json::to_string(&tokenizer.encode(input, false)?)?
);
Ok(())
}
[model, action, path, input, flag]
if model == "model"
&& action == "tokenize"
&& input != "--stdin"
&& flag == "--special" =>
{
let tokenizer = tokenizer::Tokenizer::from_assets(Path::new(path))?;
println!(
"{}",
serde_json::to_string(&tokenizer.encode(input, true)?)?
);
Ok(())
}
[model, action, path, flag]
if model == "model" && action == "tokenize" && flag == "--stdin" =>
{
let tokenizer = tokenizer::Tokenizer::from_assets(Path::new(path))?;
let mut input = String::new();
std::io::stdin().read_to_string(&mut input)?;
println!(
"{}",
serde_json::to_string(&tokenizer.encode(&input, false)?)?
);
Ok(())
}
[model, action, path, stdin_flag, special_flag]
if model == "model"
&& action == "tokenize"
&& stdin_flag == "--stdin"
&& special_flag == "--special" =>
{
let tokenizer = tokenizer::Tokenizer::from_assets(Path::new(path))?;
let mut input = String::new();
std::io::stdin().read_to_string(&mut input)?;
println!(
"{}",
serde_json::to_string(&tokenizer.encode(&input, true)?)?
);
Ok(())
}
[model, action, path, ids] if model == "model" && action == "detokenize" => {
let tokenizer = tokenizer::Tokenizer::from_assets(Path::new(path))?;
let ids = if ids.is_empty() {
Vec::new()
} else {
ids.split(',')
.map(str::parse::<u32>)
.collect::<Result<Vec<_>, _>>()?
};
println!("{}", serde_json::to_string(&tokenizer.decode(&ids)?)?);
Ok(())
}
// Batch forms for the differential harness (scripts/offline/diff_tokenizer.py): one JSON value per line.
[model, action] if model == "model" && action == "pre-tokenize-batch" => {
for line in std::io::stdin().lines() {
let text: String = serde_json::from_str(&line?)?;
let pieces = tokenizer::pre_tokenize(&text);
println!("{}", serde_json::to_string(&pieces.ok())?);
}
Ok(())
}
[model, action, path, rest @ ..]
if model == "model"
&& action == "tokenize-batch"
&& rest.iter().all(|flag| flag == "--special") =>
{
let tokenizer = tokenizer::Tokenizer::from_assets(Path::new(path))?;
for line in std::io::stdin().lines() {
let text: String = serde_json::from_str(&line?)?;
let ids = tokenizer.encode(&text, !rest.is_empty()).ok();
println!("{}", serde_json::to_string(&ids)?);
}
Ok(())
}
// JSON lines {"messages": [...], "tools": [...]|null, "add_generation_prompt": true, "kwargs": {...}} ->
// {"ok": "<prompt>"} or {"error": "<message>"}: the pinned chat template, for scripts/offline/diff_chat_template.py.
[model, action] if model == "model" && action == "render-chat" => {
use strata_control::prompt::{ChatInput, Json, pinned};
for line in std::io::stdin().lines() {
let request: Json = serde_json::from_str(&line?)?;
let array = |key: &str| match request.get(key) {
Some(Json::Array(items)) => Some(items.as_slice()),
_ => None,
};
let kwargs = match request.get("kwargs") {
Some(Json::Object(fields)) => fields
.iter()
.map(|(k, v)| (k.as_str(), v.clone()))
.collect(),
_ => Vec::new(),
};
let rendered = pinned().render(&ChatInput {
messages: array("messages").unwrap_or(&[]),
tools: array("tools"),
add_generation_prompt: !matches!(
request.get("add_generation_prompt"),
Some(Json::Bool(false))
),
kwargs,
});
println!(
"{}",
match rendered {
Ok(text) => serde_json::json!({"ok": text}),
Err(message) => serde_json::json!({"error": message}),
}
);
}
Ok(())
}
[model, action, path] if model == "model" && action == "detokenize-batch" => {
let tokenizer = tokenizer::Tokenizer::from_assets(Path::new(path))?;
for line in std::io::stdin().lines() {
let ids: Vec<u32> = serde_json::from_str(&line?)?;
println!("{}", serde_json::to_string(&tokenizer.decode(&ids).ok())?);
}
Ok(())
}
_ => return Ok(false),
};
handled.map(|()| true)
}