//! Polymorphic model engine unifying closed 48-class and open bi-encoder artifacts. //! //! Basis: Single runtime dispatch over `Closed(ModelBundle)` and `BiEncoder(BiEncoderBundle)` //! producing canonical `OpenProgram` values (`to_lisp()` and `to_json()`). use std::fs; use std::path::Path; use serde_json::Value; use sha2::{Digest, Sha256}; use crate::biencoder::{BIENCODER_MODEL_TYPE, BiEncoderBundle, CompiledCatalog}; use crate::catalog::{ActionCatalog, CatalogError, OpenAction, OpenProgram}; use crate::config::{ConfigError, Thresholds}; use crate::episodic::EpisodicMemory; use crate::inference::{InferenceError, predict_with_episodic}; use crate::model::{ModelBundle, ModelError}; /// Polymorphic inference engine supporting both historical 48-action and open bi-encoder models. pub enum ModelEngine { /// Legacy fixed 48-action linear classifier. Closed { /// Loaded closed-set model bundle. bundle: ModelBundle, /// Builtin 48-action catalog for uniform `OpenProgram` conversion. builtin: ActionCatalog, }, /// Open-vocabulary dual-tower bi-encoder with pre-encoded catalog embeddings. BiEncoder { /// Loaded dual-tower weights and tokenizer metadata. bundle: BiEncoderBundle, /// Pre-encoded active catalog matrix. compiled: CompiledCatalog, /// SHA-256 of the last external `catalog.json` compiled into `compiled`. compiled_digest: Option<[u8; 32]>, }, } /// Inspect `/config.json` to determine whether it names a bi-encoder artifact. pub fn is_biencoder_artifact(directory: &Path) -> Result { let raw = fs::read(directory.join("config.json"))?; let value: Value = serde_json::from_slice(&raw).map_err(ConfigError::Json)?; Ok(value.get("model_type").and_then(Value::as_str) == Some(BIENCODER_MODEL_TYPE)) } impl ModelEngine { /// Load either a `BiEncoder` or legacy `Closed` model from `directory`. pub fn load(directory: impl AsRef) -> Result { let directory = directory.as_ref(); if is_biencoder_artifact(directory)? { let bundle = BiEncoderBundle::load(directory)?; let compiled = bundle .compile_catalog(&bundle.default_catalog) .map_err(|_| ConfigError::Metadata("failed to compile default catalog"))?; Ok(Self::BiEncoder { bundle, compiled, compiled_digest: None, }) } else { let bundle = ModelBundle::load(directory)?; Ok(Self::Closed { bundle, builtin: ActionCatalog::builtin(), }) } } /// Replace the active `ActionCatalog` on a `BiEncoder` engine without reloading weights. pub fn set_catalog(&mut self, catalog: &ActionCatalog) -> Result<(), InferenceError> { if let Self::BiEncoder { bundle, compiled, compiled_digest, } = self { *compiled = bundle.compile_catalog(catalog)?; *compiled_digest = None; } Ok(()) } /// Hot-reload `` into `compiled` only when its SHA-256 digest changes on disk. pub fn refresh_catalog_optional(&mut self, path: &Path) -> Result<(), String> { let Self::BiEncoder { bundle, compiled, compiled_digest, } = self else { return Ok(()); }; match fs::read(path) { Ok(bytes) => { let hash: [u8; 32] = Sha256::digest(&bytes).into(); if *compiled_digest == Some(hash) { return Ok(()); } let catalog = ActionCatalog::from_bytes(&bytes).map_err(|err: CatalogError| err.to_string())?; *compiled = bundle .compile_catalog(&catalog) .map_err(|err| err.to_string())?; *compiled_digest = Some(hash); Ok(()) } Err(err) if err.kind() == std::io::ErrorKind::NotFound => { if compiled_digest.is_some() { *compiled = bundle .compile_catalog(&bundle.default_catalog) .map_err(|e| e.to_string())?; *compiled_digest = None; } Ok(()) } Err(err) => Err(err.to_string()), } } /// Return whether this engine supports open-vocabulary catalogs (`BiEncoder`). pub const fn is_open(&self) -> bool { matches!(self, Self::BiEncoder { .. }) } /// Return calibrated runtime thresholds of the loaded model. pub fn thresholds(&self) -> Thresholds { match self { Self::Closed { bundle, .. } => bundle.metadata.thresholds, Self::BiEncoder { bundle, .. } => bundle.metadata.thresholds, } } /// Borrow the active `ActionCatalog` (48 builtin for `Closed`, dynamic for `BiEncoder`). pub fn catalog(&self) -> &ActionCatalog { match self { Self::Closed { builtin, .. } => builtin, Self::BiEncoder { compiled, .. } => &compiled.catalog, } } /// Predict one or two validated operations, consulting optional `episodic` and `active_modes`. pub fn predict( &self, command: &str, episodic: Option<&EpisodicMemory>, active_modes: Option<&[String]>, ) -> Result { match self { Self::Closed { bundle, builtin } => { let program = predict_with_episodic(bundle, episodic, command)?; let mut open_actions = Vec::with_capacity(program.actions().len()); for act in program.actions() { let spec = builtin .get(act.kind().label()) .ok_or(InferenceError::InvalidScores)?; open_actions.push(OpenAction::new(spec, act.name().map(str::to_owned))?); } Ok(OpenProgram::new(open_actions)?) } Self::BiEncoder { bundle, compiled, .. } => bundle.predict_open(compiled, episodic, active_modes, command), } } }