A high-performance inference engine for AI models
More cli stuff (astra slop) (#847)
uuuvn25e42ad75166
diff --git a/crates/legacy/cli/src/interactive/app.rs b/crates/legacy/cli/src/interactive/app.rsindex 67e103454..a96b54cf1 100644--- a/crates/legacy/cli/src/interactive/app.rs+++ b/crates/legacy/cli/src/interactive/app.rs@@ -7,7 +7,7 @@ use uzu::{settings::SettingsError,};-use crate::interactive::{components::Application, model::ModelResolutionError};+use crate::interactive::components::Application;#[derive(Debug, Clone, PartialEq, thiserror::Error)]#[non_exhaustive]@@ -15,8 +15,6 @@ pub enum CliError {#[error(transparent)]Engine(#[from] EngineError),#[error(transparent)]- ModelResolution(#[from] ModelResolutionError),- #[error(transparent)]Settigs(#[from] SettingsError),#[error("Rendering error: {message}")]RenderingError {diff --git a/crates/legacy/cli/src/interactive/components/application.rs b/crates/legacy/cli/src/interactive/components/application.rsindex 6ff310fc3..7bea57406 100644--- a/crates/legacy/cli/src/interactive/components/application.rs+++ b/crates/legacy/cli/src/interactive/components/application.rs@@ -18,7 +18,6 @@ use crate::{components::{CommandInput, HistoryCell, HistoryCellType, Logo, Preferences, SelectedModel, Theme},flows::{AuthFlow, ExitFlow, Flow, FlowEvent, FlowRegistry, ModelRegistriesFlow, SettingsFlow, ThemeFlow},helpers::SYMBOL_COMMAND,- model::resolve_model_id,sessions::{self, SessionState},},};@@ -148,21 +147,7 @@ pub fn Application(let engine = state.read().engine.clone();let mut state = state;async move {- let initial_model = match requested_model {- Some(model) => match resolve_model_id(&engine, model).await {- Ok(model) => model,- Err(error) => {- state.write().history.push(HistoryCellType::CommandResult {- result: format!("Failed to resolve model: {error}"),- });- state.write().flow = Some(Box::new(ModelRegistriesFlow));- return;- },- },- None => None,- };-- let Some(identifier) = initial_model else {+ let Some(identifier) = requested_model else {state.write().flow = Some(Box::new(ModelRegistriesFlow));return;};diff --git a/crates/legacy/cli/src/interactive/components/history_cell.rs b/crates/legacy/cli/src/interactive/components/history_cell.rsindex bff600704..f3721a2c8 100644--- a/crates/legacy/cli/src/interactive/components/history_cell.rs+++ b/crates/legacy/cli/src/interactive/components/history_cell.rs@@ -116,7 +116,7 @@ pub fn HistoryCell(view}-fn chat_transcript_component(+pub fn chat_transcript_component(items: Vec<TranscriptItem>,stats: Option<ChatReplyStats>,subtitle_color: Color,diff --git a/crates/legacy/cli/src/interactive/components/mod.rs b/crates/legacy/cli/src/interactive/components/mod.rsindex 1bf68cb53..ecd75465a 100644--- a/crates/legacy/cli/src/interactive/components/mod.rs+++ b/crates/legacy/cli/src/interactive/components/mod.rs@@ -16,7 +16,7 @@ mod thinking_support_ext;pub use application::{Application, ApplicationState, ModelState};pub use command_input::CommandInput;pub use gradient::Gradient;-pub use history_cell::{HistoryCell, HistoryCellType, TranscriptItem};+pub use history_cell::{HistoryCell, HistoryCellType, TranscriptItem, chat_transcript_component};pub use loading::Loading;pub use logo::Logo;pub use preferences::Preferences;diff --git a/crates/legacy/cli/src/interactive/flows/auth.rs b/crates/legacy/cli/src/interactive/flows/auth.rsindex 9ff3b4afe..2bfc76cf5 100644--- a/crates/legacy/cli/src/interactive/flows/auth.rs+++ b/crates/legacy/cli/src/interactive/flows/auth.rs@@ -1,6 +1,6 @@use iocraft::prelude::*;use uzu::engine::config::{- KEY_ANTHROPIC_API_KEY, KEY_BASETEN_API_KEY, KEY_GEMINI_API_KEY, KEY_HF_TOKEN, KEY_LALAMO_PATH, KEY_MIRAI_API_KEY,+ KEY_ANTHROPIC_API_KEY, KEY_BASETEN_API_KEY, KEY_GEMINI_API_KEY, KEY_HF_TOKEN, KEY_LOCAL_PATH, KEY_MIRAI_API_KEY,KEY_OPENAI_API_KEY, KEY_OPENROUTER_API_KEY, KEY_XAI_API_KEY,};@@ -73,6 +73,6 @@ fn auth_providers() -> Vec<AuthProvider> {AuthProvider::key("Baseten", KEY_BASETEN_API_KEY),AuthProvider::key("OpenRouter", KEY_OPENROUTER_API_KEY),AuthProvider::key("HuggingFace", KEY_HF_TOKEN),- AuthProvider::path("lalamo", KEY_LALAMO_PATH),+ AuthProvider::path("Local", KEY_LOCAL_PATH),]}diff --git a/crates/legacy/cli/src/interactive/mod.rs b/crates/legacy/cli/src/interactive/mod.rsindex 119ce8511..c98d83516 100644--- a/crates/legacy/cli/src/interactive/mod.rs+++ b/crates/legacy/cli/src/interactive/mod.rs@@ -16,11 +16,13 @@ mod components;mod flows;mod helpers;mod list;-mod model;+mod non_interactive;mod sampling;mod sessions;mod util;+pub use non_interactive::run_non_interactive;+const APP_IDENTIFIER: &str = "com.trymirai.cli";pub async fn run_interactive(diff --git a/crates/legacy/cli/src/interactive/non_interactive.rs b/crates/legacy/cli/src/interactive/non_interactive.rsnew file mode 100644index 000000000..9018b9795--- /dev/null+++ b/crates/legacy/cli/src/interactive/non_interactive.rs@@ -0,0 +1,186 @@+use std::io::{self, Write};++use anyhow::{Context, Result, bail};+use iocraft::prelude::*;+use nagare::chat::ChatSessionStreamChunk;+use shoji::types::{+ basic::ReasoningEffort,+ session::chat::{ChatMessage, ChatReplyConfig},+};+use uzu::{+ engine::{Engine, EngineConfig},+ storage::DownloadPhase,+};++use crate::{+ common::thinking::ThinkingSupport,+ interactive::{+ APP_IDENTIFIER,+ components::{ApplicationState, TranscriptItem, chat_transcript_component},+ sessions::chat::{build_transcript, create_session},+ },+};++pub async fn run_non_interactive(+ model: String,+ message: String,+ reasoning_effort: Option<ReasoningEffort>,+ seed: Option<i64>,+) -> Result<()> {+ let preferences = ApplicationState::load_preferences().unwrap_or_default();+ let config = EngineConfig::default().with_application_identifier(APP_IDENTIFIER.to_string());+ let engine = Engine::new(config).await?;+ let model = engine.model(model.clone()).await?.with_context(|| format!("Model not found: {model}"))?;+ if !model.is_chat_capable() {+ bail!("--message requires a chat model");+ }++ if model.is_downloadable() {+ let download = engine.download(&model).await?;+ let mut announced = false;+ while let Some(update) = download.next().await {+ if !announced && update.is_in_progress() {+ eprintln!("Downloading {}", model.identifier);+ announced = true;+ }+ }+ if !engine.download_state(&model).await.is_some_and(|state| matches!(state.phase, DownloadPhase::Downloaded {}))+ {+ bail!("Model download did not complete: {}", model.identifier);+ }+ }++ let support = ThinkingSupport::for_model(&model);+ let effort = match reasoning_effort {+ Some(effort) => support+ .fulfill_requested_effort(effort)+ .map_err(|error| anyhow::anyhow!("Invalid --reasoning-effort: {error}"))?,+ None => support.with_preference(&preferences.thinking).reasoning_effort(),+ };+ let session = create_session(&engine, &model, seed, true).await?;+ let mut messages = Vec::new();+ if let Some(effort) = effort {+ messages.push(ChatMessage::system().with_reasoning_effort(effort));+ }+ messages.push(ChatMessage::user().with_text(message));+ let config = ChatReplyConfig::default().with_sampling_policy(preferences.sampling.policy());+ let stream = session.reply_with_stream(messages, config).await;+ let cancel_token = stream.cancel_token();+ let theme = preferences.theme;+ let result = async move {+ let mut stdout = io::stdout();+ let mut plain = PlainTranscript::default();+ let mut stats = None;+ while let Some(chunk) = stream.next().await {+ match chunk {+ ChatSessionStreamChunk::Replies {+ replies,+ } => {+ if let Some(reply) = replies.last() {+ stats = Some(reply.stats.clone());+ }+ let items = build_transcript(&session.messages().await, 0);+ plain.write(&mut stdout, items, false)?;+ },+ ChatSessionStreamChunk::Error {+ error,+ } => return Err(error.into()),+ }+ }++ let stats = stats.context("No response generated")?;+ let items = build_transcript(&session.messages().await, 0);+ plain.write(&mut stdout, items, true)?;+ writeln!(stdout)?;+ chat_transcript_component(+ Vec::new(),+ Some(stats),+ theme.subtitle_color,+ theme.overlay_color(),+ theme.padding(),+ false,+ )+ .write(&mut stdout)?;+ stdout.flush()?;+ Ok(())+ }+ .await;+ cancel_token.cancel();+ result+}++#[derive(Default)]+struct PlainTranscript {+ reasoning: String,+ text: String,+ last_was_thinking: Option<bool>,+}++impl PlainTranscript {+ fn write(+ &mut self,+ output: &mut impl Write,+ items: Vec<TranscriptItem>,+ finished: bool,+ ) -> io::Result<()> {+ let mut reasoning = String::new();+ let mut text = String::new();+ for item in items {+ match item {+ TranscriptItem::Thinking(value) => reasoning.push_str(&value),+ TranscriptItem::Text(value) => text.push_str(&value),+ TranscriptItem::ToolCall {+ ..+ } => {},+ }+ }+ if self.last_was_thinking == Some(false)+ && reasoning.trim_end_matches(|ch: char| ch == '\u{fffd}' || ch.is_whitespace()).len()+ > self.reasoning.len()+ {+ self.write_part(output, &text, false, true)?;+ }+ self.write_part(output, &reasoning, true, finished)?;+ if self.last_was_thinking == Some(true) && text.trim_end_matches('\u{fffd}').len() > self.text.len() {+ self.write_part(output, &reasoning, true, true)?;+ }+ self.write_part(output, &text, false, finished)?;+ output.flush()+ }++ fn write_part(+ &mut self,+ output: &mut impl Write,+ text: &str,+ is_thinking: bool,+ finished: bool,+ ) -> io::Result<()> {+ let previous = if is_thinking {+ &mut self.reasoning+ } else {+ &mut self.text+ };+ let delta = text.strip_prefix(previous.as_str()).ok_or_else(|| {+ io::Error::new(io::ErrorKind::InvalidData, "Model output changed text that was already written")+ })?;+ let delta = if finished {+ delta+ } else {+ delta.trim_end_matches(|ch: char| ch == '\u{fffd}' || (is_thinking && ch.is_whitespace()))+ };+ if delta.is_empty() {+ return Ok(());+ }+ if self.last_was_thinking.is_some_and(|last| last != is_thinking) {+ writeln!(output)?;+ }+ output.write_all(delta.as_bytes())?;+ previous.push_str(delta);+ self.last_was_thinking = Some(is_thinking);+ Ok(())+ }+}++#[cfg(test)]+#[path = "../../unit/interactive/non_interactive_test.rs"]+mod tests;diff --git a/crates/legacy/cli/src/interactive/sessions/chat.rs b/crates/legacy/cli/src/interactive/sessions/chat.rsindex 8dbfb7d28..dd9824498 100644--- a/crates/legacy/cli/src/interactive/sessions/chat.rs+++ b/crates/legacy/cli/src/interactive/sessions/chat.rs@@ -11,6 +11,7 @@ use shoji::types::{model::Model,session::chat::{ChatConfig, ChatMessage, ChatReplyConfig, ChatReplyStats, ChatRole},};+use uzu::engine::Engine;use crate::interactive::{components::{ApplicationState, HistoryCellType, TranscriptItem},@@ -120,22 +121,7 @@ pub async fn ensure_session(let state = state.read();(state.engine.clone(), state.seed, state.no_tools)};- let session = match async {- let mut config = ChatConfig::default();- if let Some(seed) = seed {- config = config.with_sampling_seed(SamplingSeed::Custom {- seed,- });- }- let mut session = engine.chat(model.clone(), config).await?;- if !no_tools && session.supports_tool_calls().await {- session.add_tool(get_current_date_time).await?;- session.add_tool(sleep).await?;- }- Ok::<_, anyhow::Error>(session)- }- .await- {+ let session = match create_session(&engine, model, seed, no_tools).await {Ok(session) => session,Err(error) => {let mut state = state.write();@@ -160,6 +146,26 @@ pub async fn ensure_session(Some(session)}+pub async fn create_session(+ engine: &Engine,+ model: &Model,+ seed: Option<i64>,+ no_tools: bool,+) -> anyhow::Result<ChatSession> {+ let mut config = ChatConfig::default();+ if let Some(seed) = seed {+ config = config.with_sampling_seed(SamplingSeed::Custom {+ seed,+ });+ }+ let mut session = engine.chat(model.clone(), config).await?;+ if !no_tools && session.supports_tool_calls().await {+ session.add_tool(get_current_date_time).await?;+ session.add_tool(sleep).await?;+ }+ Ok(session)+}+pub async fn run_session(state: State<ApplicationState>,session: ChatSession,@@ -265,7 +271,7 @@ pub async fn run_session(/// A tool call is `calling` until its result message shows up in the history,/// then it becomes `called`.-fn build_transcript(+pub fn build_transcript(messages: &[ChatMessage],history_offset: usize,) -> Vec<TranscriptItem> {diff --git a/crates/legacy/cli/src/main.rs b/crates/legacy/cli/src/main.rsindex 11dc4388e..99a73219a 100644--- a/crates/legacy/cli/src/main.rs+++ b/crates/legacy/cli/src/main.rs@@ -9,16 +9,19 @@ mod server;mod storage;#[derive(Parser)]-#[command(name = "cli", bin_name = "cli", version)]+#[command(name = "cli", bin_name = "cli", version, args_conflicts_with_subcommands = true)]struct Cli {- /// Identifier of the model to start with (e.g. "alibaba:qwen3.5:0.8b:mirai:mirai-m:4").+ /// Model identifier, repository ID, or local model directory.#[arg(long, value_name = "MODEL")]model: Option<String>,+ /// Send one chat message, stream the reply, and exit.+ #[arg(short, long, value_name = "TEXT", requires = "model")]+ message: Option<String>,/// Reasoning effort: disabled, default, low, medium or high./// Overrides the saved preference for this run only; never persisted.#[arg(long, value_name = "EFFORT")]reasoning_effort: Option<ReasoningEffort>,- /// Sampling seed for interactive chat sessions.+ /// Sampling seed for chat sessions.#[arg(long, value_name = "SEED", allow_negative_numbers = true)]seed: Option<i64>,/// Disable built-in tools in interactive chat sessions.@@ -42,6 +45,7 @@ enum Commands {},ListModels,Server {+ /// Model identifier, repository ID, or local model directory.#[arg(long, value_name = "MODEL")]model: String,#[arg(long, default_value_t = 8000)]@@ -89,7 +93,18 @@ async fn main() -> Result<()> {Some(Commands::Storage {download_manager,}) => storage::run(download_manager).await?,- None => interactive::run_interactive(cli.model, cli.reasoning_effort, cli.seed, cli.no_tools).await?,+ None => match cli.message {+ Some(message) => {+ interactive::run_non_interactive(+ cli.model.expect("--message requires --model"),+ message,+ cli.reasoning_effort,+ cli.seed,+ )+ .await?;+ },+ None => interactive::run_interactive(cli.model, cli.reasoning_effort, cli.seed, cli.no_tools).await?,+ },}Ok(())diff --git a/crates/legacy/cli/src/server/runner.rs b/crates/legacy/cli/src/server/runner.rsindex 185448289..e58d1ab85 100644--- a/crates/legacy/cli/src/server/runner.rs+++ b/crates/legacy/cli/src/server/runner.rs@@ -174,10 +174,7 @@ pub async fn run_server(let engine_config = EngineConfig::default().with_application_identifier("com.trymirai.cli".to_string());let engine = Engine::new(engine_config).await.context("Failed to create engine")?;- let resolved = match engine.model(model.clone()).await? {- Some(model) => model,- None => engine.model_by_path(model.clone()).await?.with_context(|| format!("Model not found: {model}"))?,- };+ let resolved = engine.model(model.clone()).await?.with_context(|| format!("Model not found: {model}"))?;let spinner = ProgressBar::new_spinner();spinner.enable_steady_tick(Duration::from_millis(100));diff --git a/crates/legacy/cli/unit/interactive/non_interactive_test.rs b/crates/legacy/cli/unit/interactive/non_interactive_test.rsnew file mode 100644index 000000000..b994f5a70--- /dev/null+++ b/crates/legacy/cli/unit/interactive/non_interactive_test.rs@@ -0,0 +1,329 @@+use shoji::types::session::chat::ChatReplyStats;++use super::*;+use crate::interactive::components::Theme;++#[test]+fn completed_transcript_renders_without_a_terminal_or_ansi_sequences() {+ let messages = [+ ChatMessage::user().with_text("Do not echo this prompt".to_string()),+ ChatMessage::assistant().with_reasoning("Let me think".to_string()).with_text("Hello, 世界!".to_string()),+ ];+ let theme = Theme::default();+ let mut output = Vec::new();+ chat_transcript_component(+ build_transcript(&messages, 0),+ Some(ChatReplyStats {+ duration: 1.25,+ ..Default::default()+ }),+ theme.subtitle_color,+ theme.overlay_color(),+ theme.padding(),+ false,+ )+ .write(&mut output)+ .unwrap();+ let output = String::from_utf8(output).unwrap();+ assert!(output.contains("Let me think"));+ assert!(output.contains("Hello, 世界!"));+ assert!(output.contains("duration: 1.25 s"));+ assert!(!output.contains("Do not echo this prompt"));+ assert!(!output.contains('\u{1b}'));++ let mut output = std::io::BufWriter::new(Vec::new());+ let mut transcript = PlainTranscript::default();+ transcript.write(&mut output, vec![TranscriptItem::Thinking("Let me".to_string())], false).unwrap();+ assert_eq!(output.get_ref(), b"Let me");+ transcript+ .write(+ &mut output,+ vec![TranscriptItem::Thinking("Let me think".to_string()), TranscriptItem::Text("Hello, 世".to_string())],+ false,+ )+ .unwrap();+ assert_eq!(output.get_ref(), "Let me think\nHello, 世".as_bytes());+ transcript.write(&mut output, build_transcript(&messages, 0), true).unwrap();+ assert_eq!(output.get_ref(), "Let me think\nHello, 世界!".as_bytes());++ let mut output = std::io::BufWriter::new(Vec::new());+ let mut transcript = PlainTranscript::default();+ let emoji = "🙂".as_bytes();+ for end in 1..emoji.len() {+ let partial = format!("Hello, {}", String::from_utf8_lossy(&emoji[..end]));+ transcript.write(&mut output, vec![TranscriptItem::Text(partial)], false).unwrap();+ assert_eq!(output.get_ref(), b"Hello, ");+ }+ transcript.write(&mut output, vec![TranscriptItem::Text("Hello, 🙂".to_string())], false).unwrap();+ assert_eq!(output.get_ref(), "Hello, 🙂".as_bytes());++ let error = transcript.write(&mut output, vec![TranscriptItem::Text("Changed prefix".to_string())], false);+ assert_eq!(error.unwrap_err().kind(), std::io::ErrorKind::InvalidData);+ assert_eq!(output.get_ref(), "Hello, 🙂".as_bytes());+ assert_eq!(transcript.write(&mut output, Vec::new(), true).unwrap_err().kind(), std::io::ErrorKind::InvalidData);+ assert_eq!(output.get_ref(), "Hello, 🙂".as_bytes());++ transcript.write(&mut output, vec![TranscriptItem::Text("Hello, 🙂�".to_string())], false).unwrap();+ assert_eq!(output.get_ref(), "Hello, 🙂".as_bytes());+ transcript.write(&mut output, vec![TranscriptItem::Text("Hello, 🙂�".to_string())], true).unwrap();+ assert_eq!(output.get_ref(), "Hello, 🙂�".as_bytes());+}++#[test]+fn byte_by_byte_transcripts_only_append() {+ let cases = [+ ("ascii", "Plain text with punctuation."),+ ("newlines", "first\nsecond\n"),+ ("tabs", "one\ttwo\tthree"),+ ("surrounding_spaces", " padded text "),+ ("unicode_punctuation", "“quotes”—an ellipsis…"),+ ("two_byte_boundaries", "\u{80}\u{7ff}"),+ ("three_byte_boundaries", "\u{800}\u{d7ff}\u{e000}\u{ffff}"),+ ("four_byte_boundaries", "\u{10000}\u{10ffff}"),+ ("precomposed_accents", "café déjà vu"),+ ("combining_accent", "Cafe\u{301}"),+ ("stacked_combining_marks", "a\u{301}\u{323}\u{304}"),+ ("leading_combining_mark", "\u{301}accent"),+ ("hangul_syllables", "안녕하세요"),+ ("hangul_jamo", "\u{1100}\u{1161}\u{11a8}"),+ ("chinese", "你好,世界"),+ ("japanese", "こんにちは世界"),+ ("devanagari", "नमस्ते दुनिया"),+ ("arabic", "مرحبا بالعالم"),+ ("hebrew", "שלום עולם"),+ ("thai", "สวัสดีโลก"),+ ("georgian", "გამარჯობა"),+ ("cyrillic", "Привет, мир"),+ ("greek", "Καλημέρα κόσμε"),+ ("math_symbols", "∑ π √∞ ≠ ≤ ≥"),+ ("supplementary_math", "𝔘𝕫𝕦 𝟘𝟙𝟚"),+ ("musical_symbols", "𝄞𝄢"),+ ("single_emoji", "🙂"),+ ("adjacent_emoji", "🙂🙃😉"),+ ("emoji_in_text", "A🙂B🚀C"),+ ("skin_tone", "👍🏽"),+ ("different_skin_tones", "👋🏻👋🏿"),+ ("text_variation_selector", "\u{2764}\u{fe0e}"),+ ("emoji_variation_selector", "❤️"),+ ("digit_keycap", "1\u{fe0f}\u{20e3}"),+ ("symbol_keycaps", "#\u{20e3}*\u{fe0f}\u{20e3}"),+ ("country_flag", "🇬🇪"),+ ("adjacent_flags", "🇺🇸🇯🇵🇺🇳"),+ ("single_regional_indicator", "🇬"),+ ("profession_zwj", "👩🏽💻"),+ ("family_zwj", "👨👩👧👦"),+ ("rainbow_flag_zwj", "🏳️🌈"),+ ("pirate_flag_zwj", "🏴☠️"),+ ("couple_zwj", "👩❤️💋👨"),+ ("gender_and_skin_tone", "🏃🏽♀️"),+ ("head_shaking_zwj", "🙂↔️"),+ ("tag_sequence_flag", "\u{1f3f4}\u{e0067}\u{e0062}\u{e0065}\u{e006e}\u{e0067}\u{e007f}"),+ ("literal_replacement_inside", "before � after"),+ ("literal_replacement_at_end", "literal �"),+ ("replacements_around_emoji", "��🙂��"),+ ("mixed_multiline", "你好 👩🏽💻\nCafe\u{301} 🇬🇪\nDone ✅"),+ ("space_before_nonbreaking_space", "a \u{a0}z"),+ ("newline_before_em_space", "a\n\u{2003}z"),+ ("adjacent_unicode_spaces", "a\u{2003}\u{3000}z"),+ ("trailing_unicode_space", "a \u{a0}"),+ ("replacement_between_spaces", "a � \u{2003}z"),+ ("leading_unicode_spaces", " \u{a0}\u{2003}🙂"),+ ("only_unicode_spaces", "\u{a0} \u{2003}"),+ ];++ for (name, text) in cases {+ for reasoning in [false, true] {+ let message = |text: String| {+ if reasoning {+ ChatMessage::assistant().with_reasoning(text)+ } else {+ ChatMessage::assistant().with_reasoning("Thinking".to_string()).with_text(text)+ }+ };+ let expected = if reasoning {+ text.trim().to_string()+ } else {+ format!("Thinking\n{text}")+ };+ let mut output = std::io::BufWriter::new(Vec::new());+ let mut transcript = PlainTranscript::default();+ let mut previous = Vec::new();++ for end in 0..=text.len() {+ let at = format!("{name}, reasoning={reasoning}, byte={end}");+ let bytes = &text.as_bytes()[..end];+ let partial = String::from_utf8_lossy(bytes).into_owned();+ let items = build_transcript(&[message(partial)], 0);+ transcript.write(&mut output, items.clone(), false).unwrap_or_else(|error| panic!("{at}: {error}"));++ let rendered = output.get_ref();+ assert!(rendered.starts_with(&previous), "output rewound: {at}");+ assert!(expected.as_bytes().starts_with(rendered), "output diverged from final text: {at}");+ assert!(std::str::from_utf8(rendered).is_ok(), "partial UTF-8 was emitted: {at}");+ assert!(!rendered.contains(&0x1b), "escape code was emitted: {at}");++ if let Ok(valid) = std::str::from_utf8(bytes) {+ let visible = if reasoning {+ valid.trim()+ } else {+ valid+ };+ if !visible.ends_with('\u{fffd}') {+ let expected_partial = if reasoning {+ visible.to_string()+ } else if visible.is_empty() {+ "Thinking".to_string()+ } else {+ format!("Thinking\n{visible}")+ };+ assert_eq!(rendered, expected_partial.as_bytes(), "complete text was not flushed: {at}");+ }+ }++ previous = rendered.clone();+ transcript.write(&mut output, items, false).unwrap_or_else(|error| panic!("{at}: {error}"));+ assert_eq!(output.get_ref(), &previous, "repeated update duplicated output: {at}");+ }++ let final_items = build_transcript(&[message(text.to_string())], 0);+ transcript.write(&mut output, final_items, true).unwrap();+ assert!(output.get_ref().starts_with(&previous), "completion rewound: {name}, reasoning={reasoning}");+ assert_eq!(output.get_ref(), expected.as_bytes(), "incomplete output: {name}, reasoning={reasoning}");+ }+ }+}++#[test]+fn reasoning_and_text_transitions_only_append() {+ let cases: &[(&str, &[(bool, &str)], &str)] = &[+ ("reasoning_then_text", &[(true, "Think"), (false, "Answer")], "Think\nAnswer"),+ ("text_then_reasoning", &[(false, "Before"), (true, "Think"), (false, "After")], "Before\nThink\nAfter"),+ ("alternating", &[(true, "One"), (false, "Answer"), (true, "Two"), (false, "Tail")], "One\nAnswer\nTwo\nTail"),+ ("identical_content", &[(false, "same"), (true, "same"), (false, " more")], "same\nsame\n more"),+ (+ "resumed_reasoning_emoji",+ &[(true, "Think"), (false, "Answer"), (true, "🙂"), (false, "Done")],+ "Think\nAnswer\n🙂\nDone",+ ),+ ("resumed_text_emoji", &[(false, "Hello"), (true, "Think"), (false, "🙂")], "Hello\nThink\n🙂"),+ (+ "resumed_reasoning_whitespace",+ &[(true, "One "), (false, "Answer"), (true, "\u{a0}Two"), (false, "Tail")],+ "One\nAnswer\n \u{a0}Two\nTail",+ ),+ ("initial_empty_reasoning", &[(true, " \n"), (false, "Answer"), (true, "Think")], "Answer\nThink"),+ ("reasoning_ends_with_replacement", &[(true, "Think�"), (false, "Answer")], "Think�\nAnswer"),+ ("text_ends_with_replacement", &[(false, "Answer�"), (true, "Think")], "Answer�\nThink"),+ ];++ for &(name, parts, expected) in cases {+ let mut reasoning = Vec::new();+ let mut text = Vec::new();+ let mut output = std::io::BufWriter::new(Vec::new());+ let mut transcript = PlainTranscript::default();+ let mut previous = Vec::new();+ let message = |reasoning: &[u8], text: &[u8]| {+ ChatMessage::assistant()+ .with_reasoning(String::from_utf8_lossy(reasoning).into_owned())+ .with_text(String::from_utf8_lossy(text).into_owned())+ };+ for &(is_thinking, part) in parts {+ for &byte in part.as_bytes() {+ if is_thinking {+ reasoning.push(byte);+ } else {+ text.push(byte);+ }+ let items = build_transcript(&[message(&reasoning, &text)], 0);+ transcript.write(&mut output, items.clone(), false).unwrap_or_else(|error| panic!("{name}: {error}"));+ let rendered = output.get_ref();+ assert!(rendered.starts_with(&previous), "output rewound: {name}");+ assert!(expected.as_bytes().starts_with(rendered), "output diverged: {name}: {rendered:?}");+ assert!(std::str::from_utf8(rendered).is_ok(), "partial UTF-8 was emitted: {name}");+ assert!(!rendered.contains(&0x1b), "escape code was emitted: {name}");+ previous = rendered.clone();+ transcript.write(&mut output, items, false).unwrap();+ assert_eq!(output.get_ref(), &previous, "repeated update duplicated output: {name}");+ }+ }+ transcript.write(&mut output, build_transcript(&[message(&reasoning, &text)], 0), true).unwrap();+ assert_eq!(output.get_ref(), expected.as_bytes(), "{name}");+ }+}++#[test]+#[ignore = "exhaustive Unicode and malformed UTF-8 sweep"]+fn exhaustive_byte_streams_only_append() {+ let mut bytes = "a � ".as_bytes().to_vec();+ let prefix_len = bytes.len();+ let mut encoded = [0; 4];+ for codepoint in 0..=0x10ffff {+ if let Some(ch) = char::from_u32(codepoint) {+ bytes.truncate(prefix_len);+ bytes.extend_from_slice(ch.encode_utf8(&mut encoded).as_bytes());+ assert_decoded_bytes_only_append(&bytes);+ }+ }+ eprintln!("All 1,112,064 Unicode scalar values passed");++ for pair in 0..=u16::MAX {+ bytes.truncate(prefix_len);+ bytes.extend_from_slice(&pair.to_be_bytes());+ assert_decoded_bytes_only_append(&bytes);+ }+ eprintln!("All 65,536 byte pairs passed");++ let boundaries = [+ b' ', b'a', 0x7f, 0x80, 0x8f, 0x90, 0x9f, 0xa0, 0xbf, 0xc0, 0xc1, 0xc2, 0xdf, 0xe0, 0xe1, 0xec, 0xed, 0xee,+ 0xef, 0xf0, 0xf1, 0xf3, 0xf4, 0xf5, 0xff,+ ];+ for a in boundaries {+ for b in boundaries {+ for c in boundaries {+ for d in boundaries {+ bytes.truncate(prefix_len);+ bytes.extend_from_slice(&[a, b, c, d]);+ assert_decoded_bytes_only_append(&bytes);+ }+ }+ }+ }+ eprintln!("All 390,625 four-byte combinations of UTF-8 boundary bytes passed");+}++fn assert_decoded_bytes_only_append(bytes: &[u8]) {+ let decoded = String::from_utf8_lossy(bytes);+ for reasoning in [false, true] {+ let message = |text: String| {+ if reasoning {+ ChatMessage::assistant().with_reasoning(text)+ } else {+ ChatMessage::assistant().with_text(text)+ }+ };+ let expected = if reasoning {+ decoded.trim()+ } else {+ &decoded+ };+ let mut output = std::io::BufWriter::new(Vec::new());+ let mut transcript = PlainTranscript::default();+ for end in 0..=bytes.len() {+ let partial = String::from_utf8_lossy(&bytes[..end]).into_owned();+ let items = build_transcript(&[message(partial)], 0);+ let previous_len = output.get_ref().len();+ transcript+ .write(&mut output, items, false)+ .unwrap_or_else(|error| panic!("{bytes:02x?}, reasoning={reasoning}, byte={end}: {error}"));+ let rendered = std::str::from_utf8(output.get_ref()).unwrap();+ assert!(rendered.len() >= previous_len, "output rewound: {bytes:02x?}, byte={end}");+ assert!(+ expected.starts_with(rendered),+ "output diverged: {bytes:02x?}, reasoning={reasoning}, byte={end}, rendered={rendered:?}, expected={expected:?}"+ );+ }+ let items = build_transcript(&[message(decoded.to_string())], 0);+ transcript.write(&mut output, items, true).unwrap();+ assert_eq!(output.get_ref(), expected.as_bytes(), "{bytes:02x?}, reasoning={reasoning}");+ }+}diff --git a/crates/legacy/uzu/bindings/python/uzu/__init__.pyi b/crates/legacy/uzu/bindings/python/uzu/__init__.pyiindex fee31c7a1..62f9a244a 100644--- a/crates/legacy/uzu/bindings/python/uzu/__init__.pyi+++ b/crates/legacy/uzu/bindings/python/uzu/__init__.pyi@@ -731,8 +731,6 @@ class EngineConfig:@propertydef mirai_api_key(self) -> typing.Optional[builtins.str]: ...@property- def lalamo_path(self) -> typing.Optional[builtins.str]: ...- @propertydef local_path(self) -> typing.Optional[builtins.str]: ...@propertydef huggingface_api_key(self) -> typing.Optional[builtins.str]: ...@@ -754,12 +752,11 @@ class EngineConfig:def allow_lmstudio_usage(self) -> builtins.bool: ...@propertydef download_manager_type(self) -> DownloadManagerType: ...- def __new__(cls, application_identifier: typing.Optional[builtins.str], mirai_api_key: typing.Optional[builtins.str], lalamo_path: typing.Optional[builtins.str], local_path: typing.Optional[builtins.str], huggingface_api_key: typing.Optional[builtins.str], openai_api_key: typing.Optional[builtins.str], anthropic_api_key: typing.Optional[builtins.str], gemini_api_key: typing.Optional[builtins.str], xai_api_key: typing.Optional[builtins.str], baseten_api_key: typing.Optional[builtins.str], openrouter_api_key: typing.Optional[builtins.str], allow_ollama_usage: builtins.bool, allow_lmstudio_usage: builtins.bool, download_manager_type: DownloadManagerType) -> EngineConfig: ...+ def __new__(cls, application_identifier: typing.Optional[builtins.str], mirai_api_key: typing.Optional[builtins.str], local_path: typing.Optional[builtins.str], huggingface_api_key: typing.Optional[builtins.str], openai_api_key: typing.Optional[builtins.str], anthropic_api_key: typing.Optional[builtins.str], gemini_api_key: typing.Optional[builtins.str], xai_api_key: typing.Optional[builtins.str], baseten_api_key: typing.Optional[builtins.str], openrouter_api_key: typing.Optional[builtins.str], allow_ollama_usage: builtins.bool, allow_lmstudio_usage: builtins.bool, download_manager_type: DownloadManagerType) -> EngineConfig: ...@staticmethoddef create() -> EngineConfig: ...def with_application_identifier(self, application_identifier: builtins.str) -> EngineConfig: ...def with_mirai_api_key(self, mirai_api_key: builtins.str) -> EngineConfig: ...- def with_lalamo_path(self, lalamo_path: builtins.str) -> EngineConfig: ...def with_local_path(self, local_path: builtins.str) -> EngineConfig: ...def with_huggingface_api_key(self, huggingface_api_key: builtins.str) -> EngineConfig: ...def with_openai_api_key(self, openai_api_key: builtins.str) -> EngineConfig: ...diff --git a/crates/legacy/uzu/bindings/swift/Sources/Uzu/Generated/uzu/uzu.swift b/crates/legacy/uzu/bindings/swift/Sources/Uzu/Generated/uzu/uzu.swiftindex e9f0f13ed..022daa3e0 100644--- a/crates/legacy/uzu/bindings/swift/Sources/Uzu/Generated/uzu/uzu.swift+++ b/crates/legacy/uzu/bindings/swift/Sources/Uzu/Generated/uzu/uzu.swift@@ -1985,7 +1985,6 @@ public func FfiConverterTypeDevice_lower(_ value: Device) -> RustBuffer {public struct EngineConfig: Equatable, Hashable, Codable {public var applicationIdentifier: String?public var miraiApiKey: String?- public var lalamoPath: String?public var localPath: String?public var huggingfaceApiKey: String?public var openaiApiKey: String?@@ -2000,10 +1999,9 @@ public struct EngineConfig: Equatable, Hashable, Codable {// Default memberwise initializers are never public by default, so we// declare one manually.- public init(applicationIdentifier: String?, miraiApiKey: String?, lalamoPath: String?, localPath: String?, huggingfaceApiKey: String?, openaiApiKey: String?, anthropicApiKey: String?, geminiApiKey: String?, xaiApiKey: String?, basetenApiKey: String?, openrouterApiKey: String?, allowOllamaUsage: Bool, allowLmstudioUsage: Bool, downloadManagerType: DownloadManagerType) {+ public init(applicationIdentifier: String?, miraiApiKey: String?, localPath: String?, huggingfaceApiKey: String?, openaiApiKey: String?, anthropicApiKey: String?, geminiApiKey: String?, xaiApiKey: String?, basetenApiKey: String?, openrouterApiKey: String?, allowOllamaUsage: Bool, allowLmstudioUsage: Bool, downloadManagerType: DownloadManagerType) {self.applicationIdentifier = applicationIdentifierself.miraiApiKey = miraiApiKey- self.lalamoPath = lalamoPathself.localPath = localPathself.huggingfaceApiKey = huggingfaceApiKeyself.openaiApiKey = openaiApiKey@@ -2090,15 +2088,6 @@ public func withHuggingfaceApiKey(huggingfaceApiKey: String) -> EngineConfig {})}-public func withLalamoPath(lalamoPath: String) -> EngineConfig {- return try! FfiConverterTypeEngineConfig_lift(try! rustCall() {- uniffi_uzu_fn_method_engineconfig_with_lalamo_path(- FfiConverterTypeEngineConfig_lower(self),- FfiConverterString.lower(lalamoPath),$0- )-})-}-public func withLocalPath(localPath: String) -> EngineConfig {return try! FfiConverterTypeEngineConfig_lift(try! rustCall() {uniffi_uzu_fn_method_engineconfig_with_local_path(@@ -2161,7 +2150,6 @@ public struct FfiConverterTypeEngineConfig: FfiConverterRustBuffer {try EngineConfig(applicationIdentifier: FfiConverterOptionString.read(from: &buf),miraiApiKey: FfiConverterOptionString.read(from: &buf),- lalamoPath: FfiConverterOptionString.read(from: &buf),localPath: FfiConverterOptionString.read(from: &buf),huggingfaceApiKey: FfiConverterOptionString.read(from: &buf),openaiApiKey: FfiConverterOptionString.read(from: &buf),@@ -2179,7 +2167,6 @@ public struct FfiConverterTypeEngineConfig: FfiConverterRustBuffer {public static func write(_ value: EngineConfig, into buf: inout [UInt8]) {FfiConverterOptionString.write(value.applicationIdentifier, into: &buf)FfiConverterOptionString.write(value.miraiApiKey, into: &buf)- FfiConverterOptionString.write(value.lalamoPath, into: &buf)FfiConverterOptionString.write(value.localPath, into: &buf)FfiConverterOptionString.write(value.huggingfaceApiKey, into: &buf)FfiConverterOptionString.write(value.openaiApiKey, into: &buf)diff --git a/crates/legacy/uzu/bindings/typescript/src/napi/index.d.mts b/crates/legacy/uzu/bindings/typescript/src/napi/index.d.mtsindex 5134aa10d..81d0fa73b 100644--- a/crates/legacy/uzu/bindings/typescript/src/napi/index.d.mts+++ b/crates/legacy/uzu/bindings/typescript/src/napi/index.d.mts@@ -980,7 +980,6 @@ export declare class EngineCallback {export declare class EngineConfig {applicationIdentifier?: stringmiraiApiKey?: string- lalamoPath?: stringlocalPath?: stringhuggingfaceApiKey?: stringopenaiApiKey?: string@@ -992,12 +991,11 @@ export declare class EngineConfig {allowOllamaUsage: booleanallowLmstudioUsage: booleandownloadManagerType: DownloadManagerType- constructor(applicationIdentifier?: string, miraiApiKey?: string, lalamoPath?: string, localPath?: string, huggingfaceApiKey?: string, openaiApiKey?: string, anthropicApiKey?: string, geminiApiKey?: string, xaiApiKey?: string, basetenApiKey?: string, openrouterApiKey?: string, allowOllamaUsage: boolean, allowLmstudioUsage: boolean, downloadManagerType: DownloadManagerType)+ constructor(applicationIdentifier?: string, miraiApiKey?: string, localPath?: string, huggingfaceApiKey?: string, openaiApiKey?: string, anthropicApiKey?: string, geminiApiKey?: string, xaiApiKey?: string, basetenApiKey?: string, openrouterApiKey?: string, allowOllamaUsage: boolean, allowLmstudioUsage: boolean, downloadManagerType: DownloadManagerType)static create(): EngineConfigwithApplicationIdentifier(applicationIdentifier: string): EngineConfigwithMiraiApiKey(miraiApiKey: string): EngineConfig- withLalamoPath(lalamoPath: string): EngineConfigwithLocalPath(localPath: string): EngineConfigwithHuggingfaceApiKey(huggingfaceApiKey: string): EngineConfigwithOpenaiApiKey(openaiApiKey: string): EngineConfigdiff --git a/crates/legacy/uzu/bindings/typescript/src/napi/index.d.ts b/crates/legacy/uzu/bindings/typescript/src/napi/index.d.tsindex 5134aa10d..81d0fa73b 100644--- a/crates/legacy/uzu/bindings/typescript/src/napi/index.d.ts+++ b/crates/legacy/uzu/bindings/typescript/src/napi/index.d.ts@@ -980,7 +980,6 @@ export declare class EngineCallback {export declare class EngineConfig {applicationIdentifier?: stringmiraiApiKey?: string- lalamoPath?: stringlocalPath?: stringhuggingfaceApiKey?: stringopenaiApiKey?: string@@ -992,12 +991,11 @@ export declare class EngineConfig {allowOllamaUsage: booleanallowLmstudioUsage: booleandownloadManagerType: DownloadManagerType- constructor(applicationIdentifier?: string, miraiApiKey?: string, lalamoPath?: string, localPath?: string, huggingfaceApiKey?: string, openaiApiKey?: string, anthropicApiKey?: string, geminiApiKey?: string, xaiApiKey?: string, basetenApiKey?: string, openrouterApiKey?: string, allowOllamaUsage: boolean, allowLmstudioUsage: boolean, downloadManagerType: DownloadManagerType)+ constructor(applicationIdentifier?: string, miraiApiKey?: string, localPath?: string, huggingfaceApiKey?: string, openaiApiKey?: string, anthropicApiKey?: string, geminiApiKey?: string, xaiApiKey?: string, basetenApiKey?: string, openrouterApiKey?: string, allowOllamaUsage: boolean, allowLmstudioUsage: boolean, downloadManagerType: DownloadManagerType)static create(): EngineConfigwithApplicationIdentifier(applicationIdentifier: string): EngineConfigwithMiraiApiKey(miraiApiKey: string): EngineConfig- withLalamoPath(lalamoPath: string): EngineConfigwithLocalPath(localPath: string): EngineConfigwithHuggingfaceApiKey(huggingfaceApiKey: string): EngineConfigwithOpenaiApiKey(openaiApiKey: string): EngineConfigdiff --git a/crates/legacy/uzu/src/engine/config.rs b/crates/legacy/uzu/src/engine/config.rsindex 7fa559993..c4fbc1e5b 100644--- a/crates/legacy/uzu/src/engine/config.rs+++ b/crates/legacy/uzu/src/engine/config.rs@@ -8,7 +8,6 @@ use crate::{};pub const KEY_MIRAI_API_KEY: &str = "MIRAI_API_KEY";-pub const KEY_LALAMO_PATH: &str = "LALAMO_PATH";pub const KEY_LOCAL_PATH: &str = "LOCAL_PATH";pub const KEY_HF_TOKEN: &str = "HF_TOKEN";pub const KEY_OPENAI_API_KEY: &str = "OPENAI_API_KEY";@@ -24,7 +23,6 @@ pub const KEY_OPENROUTER_API_KEY: &str = "OPENROUTER_API_KEY";pub struct EngineConfig {pub application_identifier: Option<String>,pub mirai_api_key: Option<String>,- pub lalamo_path: Option<String>,pub local_path: Option<String>,pub huggingface_api_key: Option<String>,pub openai_api_key: Option<String>,@@ -44,7 +42,6 @@ impl Default for EngineConfig {Self {application_identifier: None,mirai_api_key: env::var(KEY_MIRAI_API_KEY).ok(),- lalamo_path: env::var(KEY_LALAMO_PATH).ok(),local_path: env::var(KEY_LOCAL_PATH).ok(),huggingface_api_key: env::var(KEY_HF_TOKEN).ok(),openai_api_key: env::var(KEY_OPENAI_API_KEY).ok(),@@ -74,7 +71,7 @@ impl EngineConfig {}synchronize_field!(SettingKind::Secret, mirai_api_key, KEY_MIRAI_API_KEY.to_string());- synchronize_field!(SettingKind::Config, lalamo_path, KEY_LALAMO_PATH.to_string());+ synchronize_field!(SettingKind::Config, local_path, KEY_LOCAL_PATH.to_string());synchronize_field!(SettingKind::Secret, huggingface_api_key, KEY_HF_TOKEN.to_string());synchronize_field!(SettingKind::Secret, openai_api_key, KEY_OPENAI_API_KEY.to_string());synchronize_field!(SettingKind::Secret, anthropic_api_key, KEY_ANTHROPIC_API_KEY.to_string());@@ -119,17 +116,6 @@ impl EngineConfig {}}- #[bindings::export(Method)]- pub fn with_lalamo_path(- &self,- lalamo_path: String,- ) -> Self {- Self {- lalamo_path: Some(lalamo_path),- ..self.clone()- }- }-#[bindings::export(Method)]pub fn with_local_path(&self,diff --git a/crates/legacy/uzu/src/engine/mod.rs b/crates/legacy/uzu/src/engine/mod.rsindex e9ca1ad56..5af2c1806 100644--- a/crates/legacy/uzu/src/engine/mod.rs+++ b/crates/legacy/uzu/src/engine/mod.rs@@ -4,8 +4,9 @@ pub mod config;mod downloader;mod downloader_stream;mod error;+mod shorthand;-use std::{collections::HashMap, sync::Arc};+use std::{collections::HashMap, path::Path, sync::Arc};use backend_remote::openai::Backend as OpenAIBackend;pub use callback::{EngineCallback, EngineCallbackType};@@ -28,6 +29,7 @@ use shoji::{session::chat::ChatConfig,},};+use sysinfo::System;use tokio_stream::{StreamExt, wrappers::BroadcastStream};use crate::{@@ -40,6 +42,7 @@ use crate::{local::{Config as LocalRegistryConfig, Registry as LocalRegistry},mirai::{Backend as MiraiBackend, Registry as MiraiRegistry, TELEMETRY_URL},openai::{Config as OpenAIConfig, Registry as OpenAIRegistry},+ unique_model,},settings::Settings,storage::{Config as StorageConfig, DownloadPhase, DownloadState, Storage},@@ -125,16 +128,8 @@ impl Engine {engine.add_backend(Arc::new(uzu_backend) as Arc<dyn Backend>).await;engine.add_registry(mirai_registry).await?;- if let Some(lalamo_path) = config.lalamo_path {- let lalamo_registry = LocalRegistry::new(LocalRegistryConfig::lalamo(- uzu_backend_identifier.clone(),- uzu_backend_version.clone(),- lalamo_path,- ))?;- engine.add_registry(Box::new(lalamo_registry)).await?;- }if let Some(local_path) = config.local_path {- let local_registry = LocalRegistry::new(LocalRegistryConfig::local(+ let local_registry = LocalRegistry::new(LocalRegistryConfig::new(uzu_backend_identifier.clone(),uzu_backend_version.clone(),local_path,@@ -374,13 +369,24 @@ impl Engine {&self,identifier: String,) -> Result<Option<Model>, EngineError> {- if let Some(model) = self.model_by_identifier(identifier.clone()).await? {- return Ok(Some(model));+ let registered = self.registry.lock().await.model(&identifier).await?;+ if registered.is_some() && Path::new(&identifier).is_dir() {+ return Err(RegistryError::UnableToGetModels {+ message: format!(+ "Ambiguous model reference `{identifier}`: matches both a registered model and a directory"+ ),+ }+ .into());}- if let Some(model) = self.model_by_repo_id(identifier.clone()).await? {+ let by_path = self.model_by_path(identifier.clone()).await?;+ if let Some(model) = unique_model(&identifier, registered.into_iter().chain(by_path))? {return Ok(Some(model));}- self.model_by_path(identifier).await++ let models = self.models().await?;+ let mut system = System::new();+ system.refresh_memory();+ Ok(shorthand::resolve_model_shorthand(&models, &identifier, system.total_memory())?.cloned())}#[bindings::export(Method)]@@ -405,11 +411,21 @@ impl Engine {path: String,) -> Result<Option<Model>, EngineError> {let models = self.models().await?;+ let mut matches = Vec::new();for model in models {if self.model_path(&model).await.is_some_and(|model_path| model_path == path) {- return Ok(Some(model));+ matches.push(model);}}+ if let Some(model) = unique_model(&path, matches.into_iter())? {+ return Ok(Some(model));+ }+ if Path::new(&path).is_dir() {+ let backend = UzuLlmBackend::new();+ return LocalRegistry::model_at_path(Path::new(&path), backend.identifier(), backend.version())+ .map(Some)+ .map_err(EngineError::from);+ }Ok(None)}}diff --git a/crates/legacy/cli/src/interactive/model.rs b/crates/legacy/uzu/src/engine/shorthand.rssimilarity index 77%rename from crates/legacy/cli/src/interactive/model.rsrename to crates/legacy/uzu/src/engine/shorthand.rsindex cd124bb39..b622a18cc 100644--- a/crates/legacy/cli/src/interactive/model.rs+++ b/crates/legacy/uzu/src/engine/shorthand.rs@@ -1,40 +1,12 @@use shoji::types::model::{Model, ModelAccessibility, ModelReference};-use sysinfo::System;-use uzu::engine::{Engine, EngineError};--#[derive(Debug, Clone, PartialEq, thiserror::Error)]-pub enum ModelResolutionError {- #[error(transparent)]- Engine(#[from] EngineError),- #[error("model `{model}` has checkpoints, but none fit in {memory_total} bytes of total memory")]- InsufficientMemory {- model: String,- memory_total: u64,- },-}-pub async fn resolve_model_id(- engine: &Engine,- model: String,-) -> Result<Option<String>, ModelResolutionError> {- let models = engine.models().await?;- let mut system = System::new();- system.refresh_memory();- let resolved = if let Some(model) = models.iter().find(|candidate| candidate.identifier == model) {- model.identifier.clone()- } else if let Some(model) = resolve_model_shorthand(&models, &model, system.total_memory())? {- model.identifier.clone()- } else {- model- };- Ok(Some(resolved))-}+use crate::registry::RegistryError;-fn resolve_model_shorthand<'a>(+pub(super) fn resolve_model_shorthand<'a>(models: &'a [Model],requested: &str,memory_total: u64,-) -> Result<Option<&'a Model>, ModelResolutionError> {+) -> Result<Option<&'a Model>, RegistryError> {let mut candidates = models.iter().filter(|model| model_shorthand_matches(model, requested)).collect::<Vec<_>>();if candidates.is_empty() {return Ok(None);@@ -42,9 +14,10 @@ fn resolve_model_shorthand<'a>(candidates.retain(|model| checkpoint_size_bytes(model).is_some_and(|size| size <= memory_total));if candidates.is_empty() {- return Err(ModelResolutionError::InsufficientMemory {- model: requested.to_string(),- memory_total,+ return Err(RegistryError::UnableToGetModels {+ message: format!(+ "model `{requested}` has checkpoints, but none fit in {memory_total} bytes of total memory"+ ),});}@@ -152,5 +125,5 @@ fn quantization_bits(model: &Model) -> u32 {}#[cfg(test)]-#[path = "../../unit/interactive/model_test.rs"]+#[path = "../../tests/engine/shorthand.rs"]mod tests;diff --git a/crates/legacy/uzu/src/registry/local/config.rs b/crates/legacy/uzu/src/registry/local/config.rsindex b6c189a6a..855baa3f8 100644--- a/crates/legacy/uzu/src/registry/local/config.rs+++ b/crates/legacy/uzu/src/registry/local/config.rs@@ -1,88 +1,20 @@-use std::{- path::{Path, PathBuf},- sync::Arc,-};--use shoji::types::model::{Model, ModelSpecialization};-use uzu_engine::engine::{ModelType, resolve_model_type};--use crate::registry::RegistryError;--pub type ModelResolver = Arc<dyn Fn(Model) -> Result<Model, RegistryError> + Send + Sync>;-#[derive(Clone)]pub struct Config {- pub identifier: String,pub backend_identifier: String,pub backend_version: String,- pub name: String,pub path: String,- pub resolver: Option<ModelResolver>,}impl Config {pub fn new(- identifier: String,backend_identifier: String,backend_version: String,- name: String,path: String,- resolver: Option<ModelResolver>,) -> Self {Self {- identifier,backend_identifier,backend_version,- name,path,- resolver,}}-- pub fn lalamo(- backend_identifier: String,- backend_version: String,- path: String,- ) -> Self {- let models_path = PathBuf::from(&path).join("models");- let resolver: ModelResolver = Arc::new(Self::resolve_model);- Self::new(- "lalamo".to_string(),- backend_identifier,- backend_version,- "Lalamo".to_string(),- models_path.to_string_lossy().to_string(),- Some(resolver),- )- }-- pub fn local(- backend_identifier: String,- backend_version: String,- path: String,- ) -> Self {- let resolver: ModelResolver = Arc::new(Self::resolve_model);- Self::new("local".to_string(), backend_identifier, backend_version, "Local".to_string(), path, Some(resolver))- }-- fn resolve_model_specialization(model_path: &Path) -> Result<ModelSpecialization, RegistryError> {- resolve_model_type(model_path)- .map(|model_type| match model_type {- ModelType::LanguageModel => ModelSpecialization::Chat {},- ModelType::Classifier => ModelSpecialization::Classification {},- })- .map_err(|error| RegistryError::UnableToGetModels {- message: format!("Unable to resolve specialization for {}: {error}", model_path.display()),- })- }-- fn resolve_model(mut model: Model) -> Result<Model, RegistryError> {- let model_path = model.local_external_path().ok_or_else(|| RegistryError::UnableToGetModels {- message: format!("Local model {} has no local path", model.identifier),- })?;- let model_path = PathBuf::from(model_path);- let specialization = Self::resolve_model_specialization(&model_path)?;- model.specializations = vec![specialization];- Ok(model)- }}diff --git a/crates/legacy/uzu/src/registry/local/mod.rs b/crates/legacy/uzu/src/registry/local/mod.rsindex 1c52548db..45a68b580 100644--- a/crates/legacy/uzu/src/registry/local/mod.rs+++ b/crates/legacy/uzu/src/registry/local/mod.rs@@ -11,6 +11,7 @@ use shoji::{model::{Model, ModelAccessibility, ModelReference, ModelSpecialization},},};+use uzu_engine::engine::{ModelType, resolve_model_type};use crate::registry::RegistryError;@@ -19,7 +20,24 @@ pub struct Registry {}impl Registry {- pub fn new(config: Config) -> Result<Self, RegistryError> {+ pub(crate) fn model_at_path(+ path: &Path,+ backend_identifier: String,+ backend_version: String,+ ) -> Result<Model, RegistryError> {+ let registry =+ Self::new(Config::new(backend_identifier, backend_version, path.to_string_lossy().into_owned()))?;+ registry.model(Path::new(®istry.config.path))+ }++ pub fn new(mut config: Config) -> Result<Self, RegistryError> {+ config.path = Path::new(&config.path)+ .canonicalize()+ .map_err(|error| RegistryError::UnableToGetModels {+ message: format!("Unable to open local model path {}: {error}", config.path),+ })?+ .to_string_lossy()+ .into_owned();Ok(Self {config,})@@ -30,16 +48,14 @@ impl RegistryTrait for Registry {type Error = RegistryError;fn identifier(&self) -> String {- self.config.identifier.clone()+ "local".to_string()}fn models(&self) -> Pin<Box<dyn Future<Output = Result<Vec<Model>, RegistryError>> + Send + '_>> {Box::pin(async {let path = Path::new(&self.config.path);- if !path.exists() {- Err(RegistryError::UnableToGetModels {- message: format!("Path not found: {}", path.display()),- })?;+ if path.join("config.json").is_file() {+ return Ok(vec![self.model(path)?]);}let entries = fs::read_dir(path).map_err(|error| RegistryError::UnableToGetModels {@@ -58,24 +74,12 @@ impl RegistryTrait for Registry {if !file_type.is_dir() {continue;}- let name = path.file_name().and_then(|name| name.to_str()).ok_or_else(|| {- RegistryError::UnableToGetModels {- message: format!("Invalid local model path: {}", path.display()),- }- })?;-- let model = self.model(name);- let model = match self.config.resolver.as_ref() {- Some(resolver) => match resolver(model) {- Ok(model) => model,- Err(error) => {- tracing::warn!(?error, path = %path.display(), "skipping invalid local model");- continue;- },+ match self.model(&path) {+ Ok(model) => models.push(model),+ Err(error) => {+ tracing::warn!(?error, path = %path.display(), "skipping invalid local model");},- None => model,- };- models.push(model);+ }}Ok(models)@@ -86,25 +90,34 @@ impl RegistryTrait for Registry {impl Registry {fn model(&self,- name: &str,- ) -> Model {- let path = Path::new(&self.config.path).join(name);- let identifier = name.to_string();- Model::external(- identifier.clone(),- self.config.identifier.clone(),- self.config.name.clone(),+ path: &Path,+ ) -> Result<Model, RegistryError> {+ let name = path.file_name().and_then(|name| name.to_str()).ok_or_else(|| RegistryError::UnableToGetModels {+ message: format!("Invalid local model path: {}", path.display()),+ })?;+ let specialization = resolve_model_type(path)+ .map(|model_type| match model_type {+ ModelType::LanguageModel => ModelSpecialization::Chat {},+ ModelType::Classifier => ModelSpecialization::Classification {},+ })+ .map_err(|error| RegistryError::UnableToGetModels {+ message: format!("Unable to resolve specialization for {}: {error}", path.display()),+ })?;+ Ok(Model::external(+ name.to_string(),+ self.identifier(),+ "Local".to_string(),self.config.backend_identifier.clone(),self.config.backend_identifier.clone(),self.config.backend_version.clone(),- vec![ModelSpecialization::Chat {}],+ vec![specialization],ModelAccessibility::Local {reference: ModelReference::Local {path: path.to_string_lossy().to_string(),},},- load_encoding(&path),- )+ load_encoding(path),+ ))}}diff --git a/crates/legacy/uzu/src/registry/merged.rs b/crates/legacy/uzu/src/registry/merged.rsindex eb801c233..c8b669a4a 100644--- a/crates/legacy/uzu/src/registry/merged.rs+++ b/crates/legacy/uzu/src/registry/merged.rs@@ -1,6 +1,9 @@use std::{future::Future, pin::Pin};-use shoji::{traits::Registry, types::model::Model};+use shoji::{+ traits::Registry,+ types::model::{Model, ModelIdentifier},+};use crate::registry::RegistryError;@@ -35,6 +38,31 @@ impl MergedRegistry {self.registries.retain(|registry| registry.identifier() != identifier);Ok(())}++ pub async fn model(+ &self,+ identifier: &str,+ ) -> Result<Option<Model>, RegistryError> {+ unique_model(+ identifier,+ self.models().await?.into_iter().filter(|model| {+ model.identifier == identifier || model.repo_ids().iter().any(|repo_id| repo_id == identifier)+ }),+ )+ }+}++pub(crate) fn unique_model(+ identifier: &str,+ mut models: impl Iterator<Item = Model>,+) -> Result<Option<Model>, RegistryError> {+ let model = models.next();+ if models.next().is_some() {+ return Err(RegistryError::UnableToGetModels {+ message: format!("Ambiguous model reference `{identifier}`: matches multiple models"),+ });+ }+ Ok(model)}impl Registry for MergedRegistry {@@ -44,6 +72,26 @@ impl Registry for MergedRegistry {self.registries.iter().map(|registry| registry.identifier()).collect::<Vec<String>>().join(":")}+ fn model_by_identifier(+ &self,+ identifier: &ModelIdentifier,+ ) -> Pin<Box<dyn Future<Output = Result<Option<Model>, RegistryError>> + Send + '_>> {+ let identifier = identifier.clone();+ Box::pin(async move {+ unique_model(&identifier, self.models().await?.into_iter().filter(|model| model.identifier == identifier))+ })+ }++ fn model_by_repo_id(+ &self,+ repo_id: &str,+ ) -> Pin<Box<dyn Future<Output = Result<Option<Model>, RegistryError>> + Send + '_>> {+ let repo_id = repo_id.to_string();+ Box::pin(async move {+ unique_model(&repo_id, self.models().await?.into_iter().filter(|model| model.repo_ids().contains(&repo_id)))+ })+ }+fn models(&self) -> Pin<Box<dyn Future<Output = Result<Vec<Model>, RegistryError>> + Send + '_>> {Box::pin(async {let results = futures::future::join_all(self.registries.iter().map(|registry| registry.models())).await;diff --git a/crates/legacy/uzu/src/registry/mod.rs b/crates/legacy/uzu/src/registry/mod.rsindex e634651b9..679586365 100644--- a/crates/legacy/uzu/src/registry/mod.rs+++ b/crates/legacy/uzu/src/registry/mod.rs@@ -8,3 +8,4 @@ pub mod openai;pub use cached::CachedRegistry;pub use error::RegistryError;pub use merged::MergedRegistry;+pub(crate) use merged::unique_model;diff --git a/crates/legacy/cli/unit/interactive/model_test.rs b/crates/legacy/uzu/tests/engine/shorthand.rssimilarity index 96%rename from crates/legacy/cli/unit/interactive/model_test.rsrename to crates/legacy/uzu/tests/engine/shorthand.rsindex 960a9824d..68d634c75 100644--- a/crates/legacy/cli/unit/interactive/model_test.rs+++ b/crates/legacy/uzu/tests/engine/shorthand.rs@@ -66,9 +66,8 @@ fn valid_shorthand_returns_insufficient_memory_when_no_checkpoint_fits() {assert_eq!(result,- Err(ModelResolutionError::InsufficientMemory {- model: "qwen3.5:4b".to_string(),- memory_total: GB as u64,+ Err(RegistryError::UnableToGetModels {+ message: format!("model `qwen3.5:4b` has checkpoints, but none fit in {GB} bytes of total memory"),}));}