1 //! inf3r-bind — the declarative compatibility adapter for an existing engine.2 //!3 //! A bound bundle must not need authored inference code. This crate reads the4 //! bundle and the model file, turns them into the same catalogue that an5 //! authored plugin sends, and maps every capability that the model declares to6 //! the runtime in `engine/`. The protocol stays the boundary; the runtime keeps7 //! its language.8 //!9 //! An HTTP runtime uses the OpenAI-shaped bridges for the seven capabilities10 //! that have one, and the neutral JSON bridge for the other five. A binary11 //! runtime reads one JSON request per job; with `worker = "jsonl"` it stays12 //! resident and reads one request per line. The bridge never names an engine,13 //! a vendor flag, or a model.14 15 mod cache;16 mod caps;17 pub mod catalogue;18 mod http;19 pub mod manifest;20 21 use std::fmt;22 use std::io::{BufRead, BufReader, Read, Write};23 use std::net::TcpListener;24 use std::os::fd::{AsFd, AsRawFd, OwnedFd};25 use std::os::unix::process::CommandExt;26 use std::path::{Path, PathBuf};27 use std::process::{Child, ChildStdin, ChildStdout, Command, Stdio};28 use std::sync::atomic::{AtomicU32, Ordering};29 use std::sync::mpsc::{self, Receiver, RecvTimeoutError};30 use std::sync::{Arc, Mutex, MutexGuard};31 use std::thread::JoinHandle;32 use std::time::{Duration, Instant};33 34 use inf3r_bundle::{Bundle, EngineKind};35 use inf3r_json::Value;36 use inf3r_plugin_sdk::Failure;37 use inf3r_plugin_sdk::cache::CacheCodec;38 use inf3r_plugin_sdk::capability::{Artifact, Report, Request};39 use inf3r_plugin_sdk::emitter::{EmitError, Emitter};40 use inf3r_plugin_sdk::serve::Plugin;41 use inf3r_plugin_sdk::{USAGE_FIRST_TOKEN_MS, USAGE_TOKENS_OUT, USAGE_TOKENS_PER_S};42 use inf3r_proto::Emit;43 use inf3r_proto::body::{Catalogue, ErrorCode, Grant, Ready};44 use rustix::io::{FdFlags, fcntl_getfd, fcntl_setfd};45 46 pub use catalogue::{CHAT, PROGRESS_CHANNEL, TEXT_CHANNEL, TEXT_MIME, build, read_catalogue};47 pub use manifest::{CapabilitySpec, ModelSpec, TargetProfile, read_models, read_target};48 49 /// The variable that an operator uses to point the binder at a bundle.50 pub const BUNDLE_DIR: &str = "INF3R_BUNDLE_DIR";51 52 /// The private exchange directory that the binder gives an HTTP runtime which53 /// advertises the engine cache bridge. It is one generic name, not a vendor54 /// flag: a runtime that does not use the bridge ignores it.55 pub const CACHE_DIR_ENV: &str = "INF3R_CACHE_DIR";56 57 /// The path that a bound bundle uses for its runtime.58 const ENTRY: &str = "engine/entry";59 60 /// The address that a local runtime listens on. A bound runtime is a child of61 /// this process, so it is reachable on the loopback interface and nowhere else.62 const LOOPBACK: [u8; 4] = [127, 0, 0, 1];63 64 /// Port zero asks the operating system for an unused port.65 const EPHEMERAL_PORT: u16 = 0;66 67 /// The role that an HTTP message gets when the part names none.68 const DEFAULT_ROLE: &str = "user";69 70 /// Whole milliseconds in one second, the denominator of a rate.71 const MS_PER_SECOND: u64 = 1_000;72 73 /// The usage field is an integer, so a rate keeps two decimal places as74 /// hundredths.75 const HUNDREDTHS: u64 = 100;76 77 /// The pause between two connection attempts.78 const PORT_POLL: Duration = Duration::from_millis(10);79 80 /// The longest wait for one `/health` reply on loopback.81 const HEALTH_TIMEOUT: Duration = Duration::from_secs(1);82 83 /// How often a job checks cancellation and its own deadline while it waits for84 /// a line. A fixed job deadline, not a per-read timeout, is what stops a85 /// chatty worker from extending its own budget.86 const JOB_POLL: Duration = Duration::from_millis(20);87 88 /// The largest bridge line that the binder accepts. A frame payload is at most89 /// 16 MiB; base64 adds a third, and the JSON wrapper needs room above that.90 const MAX_BRIDGE_LINE: usize = 32 << 20;91 92 /// The largest request body that the binder writes to a bridge.93 pub(crate) const MAX_BRIDGE_BODY: usize = 32 << 20;94 95 /// The most jobs that one bound runtime runs at once when the target declares96 /// no limit. A bound engine is one child per job, so one is the safe answer.97 const ONE_JOB: u16 = 1;98 99 /// The fallback readiness budget.100 ///101 /// It is the web's `START` deadline, because the binder cannot see the clock of102 /// the caller that is already waiting. A target that declares `start_ms` uses103 /// that number instead.104 const LOAD_WAIT: Duration = Duration::from_secs(120);105 106 /// One spawn at a time, because clearing `CLOEXEC` is process-wide.107 static SPAWN: Mutex<()> = Mutex::new(());108 109 /// One descriptor that the core granted, with the path that names it.110 struct Granted {111 fd: OwnedFd,112 path: Option<PathBuf>,113 }114 115 impl Granted {116 fn path(&self) -> String {117 self.path118 .as_ref()119 .map(|path| path.to_string_lossy().into_owned())120 .unwrap_or_else(|| format!("/proc/self/fd/{}", self.fd.as_raw_fd()))121 }122 }123 124 /// The three standard streams that one engine gets.125 struct ChildIo {126 stdin: Stdio,127 stdout: Stdio,128 }129 130 /// One engine process and the thread that forwards its stderr.131 struct Running {132 child: Child,133 stderr: JoinHandle<()>,134 }135 136 impl Running {137 /// Ends the process and waits for the stderr thread to reach end of file.138 fn stop(mut self) {139 kill(&mut self.child);140 let _ = self.stderr.join();141 }142 }143 144 /// A resident line-delimited JSON worker.145 ///146 /// The child loads its weights once. The binder writes one request line and147 /// reads event lines until one carries `done` or `error`. A crash, a timeout,148 /// or a cancel drops the whole worker; the next job starts a fresh one.149 struct Worker {150 child: Child,151 stdin: ChildStdin,152 lines: Receiver<std::io::Result<String>>,153 reader: JoinHandle<()>,154 stderr: JoinHandle<()>,155 }156 157 impl Worker {158 /// Whether the process is still running.159 fn alive(&mut self) -> bool {160 self.child.try_wait().is_ok_and(|status| status.is_none())161 }162 163 /// Ends the worker and waits for its reader and stderr threads.164 fn stop(mut self) {165 kill(&mut self.child);166 drop(self.stdin);167 let _ = self.reader.join();168 let _ = self.stderr.join();169 }170 }171 172 /// The reason a bundle could not become a plugin.173 #[derive(Clone, PartialEq, Eq, Debug)]174 pub enum BindError {175 /// A file could not be read.176 Io {177 /// The file that failed.178 path: PathBuf,179 /// The operating system's sentence.180 why: String,181 },182 /// `bundle.toml` was refused by `inf3r-bundle`.183 Bundle {184 /// The directory that was read.185 dir: PathBuf,186 /// The reason from the bundle parser.187 why: String,188 },189 /// A model file is outside the subset that the binder reads.190 Manifest {191 /// The model file.192 path: PathBuf,193 /// The one-based line number.194 line: usize,195 /// What the parser expected.196 message: String,197 },198 /// The bundle has no model file.199 NoModel {200 /// The models directory.201 dir: PathBuf,202 },203 /// A model file is an alias that the binder cannot resolve.204 Alias {205 /// The models directory.206 dir: PathBuf,207 /// The alias and its source.208 why: String,209 },210 /// A shared library cannot be reached without an authored shim.211 Library {212 /// The bundle that was refused.213 dir: PathBuf,214 },215 /// The bundle directory could not be found, or the SDK refused to start.216 Launch(String),217 }218 219 impl fmt::Display for BindError {220 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {221 match self {222 BindError::Io { path, why } => write!(f, "{}: {why}", path.display()),223 BindError::Bundle { dir, why } => {224 write!(f, "{}: {why}", dir.join("bundle.toml").display())225 }226 BindError::Manifest {227 path,228 line,229 message,230 } => write!(f, "{}:{line}: {message}", path.display()),231 BindError::NoModel { dir } => {232 write!(f, "{} has no model file", dir.display())233 }234 BindError::Alias { dir, why } => write!(f, "{}: {why}", dir.display()),235 BindError::Library { dir } => write!(236 f,237 "{} binds a shared library, which needs an authored shim; override src/main.rs",238 dir.display()239 ),240 BindError::Launch(why) => f.write_str(why),241 }242 }243 }244 245 impl std::error::Error for BindError {}246 247 /// The plugin that a bound bundle starts.248 pub struct Bound {249 bundle: Bundle,250 dir: PathBuf,251 model: ModelSpec,252 aliases: Vec<ModelSpec>,253 target: TargetProfile,254 granted: Mutex<Vec<Granted>>,255 endpoint: Arc<Mutex<Option<String>>>,256 child: Mutex<Option<Running>>,257 worker: Arc<Mutex<Option<Worker>>>,258 worker_job: Mutex<()>,259 load_ms: AtomicU32,260 staging: PathBuf,261 cache: Option<Arc<cache::BoundCache>>,262 }263 264 impl Bound {265 /// Reads a bundle and prepares the one plugin process that it serves.266 ///267 /// A library is refused here because the refusal must happen before a268 /// socket exists; an author who wants one overrides `src/main.rs`.269 pub fn new(dir: &Path) -> Result<Bound, BindError> {270 let bundle = Bundle::read(dir).map_err(|why| BindError::Bundle {271 dir: dir.to_path_buf(),272 why: why.to_string(),273 })?;274 if bundle.engine == EngineKind::Library {275 return Err(BindError::Library {276 dir: dir.to_path_buf(),277 });278 }279 let models = read_models(dir)?;280 let (model, aliases) = catalogue::split(&models, dir)?;281 let model = model.clone();282 let aliases: Vec<ModelSpec> = aliases.into_iter().cloned().collect();283 let target = read_target(dir, &bundle.target);284 let endpoint = Arc::new(Mutex::new(None));285 let (staging, cache) = if bundle.engine == EngineKind::Http286 && model.context.unwrap_or(0) > 0287 && model.kv_bytes_per_token.unwrap_or(0) > 0288 {289 let staging = cache::staging_dir(&bundle).map_err(|why| BindError::Io {290 path: dir.to_path_buf(),291 why: why.to_string(),292 })?;293 let codec = Arc::new(294 cache::BoundCache::new(295 &bundle,296 &model,297 &target,298 dir,299 staging.clone(),300 Arc::clone(&endpoint),301 )302 .map_err(|why| BindError::Io {303 path: dir.to_path_buf(),304 why: why.to_string(),305 })?,306 );307 (staging, Some(codec))308 } else {309 (PathBuf::new(), None)310 };311 Ok(Bound {312 bundle,313 dir: dir.to_path_buf(),314 model,315 aliases,316 target,317 granted: Mutex::new(Vec::new()),318 endpoint,319 child: Mutex::new(None),320 worker: Arc::new(Mutex::new(None)),321 worker_job: Mutex::new(()),322 load_ms: AtomicU32::new(0),323 staging,324 cache,325 })326 }327 328 /// The directory from which this plugin was built.329 pub fn dir(&self) -> &Path {330 &self.dir331 }332 333 /// The longest wait for a started HTTP engine to answer `/health`.334 ///335 /// The target declares it when the author knows the load time. Without a336 /// declaration the binder waits as long as the web's own load deadline,337 /// so a slow engine is not failed before its caller would be.338 fn start_budget(&self) -> Duration {339 self.target340 .start_ms341 .map(|ms| Duration::from_millis(u64::from(ms)))342 .unwrap_or(LOAD_WAIT)343 }344 345 fn catalogue_now(&self) -> Catalogue {346 let aliases: Vec<&ModelSpec> = self.aliases.iter().collect();347 let mut catalogue = build(348 &self.bundle,349 &self.model,350 &aliases,351 self.target.clone(),352 self.load_ms.load(Ordering::SeqCst),353 );354 if let Some(cache) = &self.cache {355 catalogue.cache = Some(cache.spec());356 }357 catalogue358 }359 360 fn entry_file(&self) -> Result<PathBuf, Failure> {361 let Some(entry) = &self.bundle.entry else {362 return Err(missing(&self.dir.join(ENTRY)));363 };364 let path = if entry.is_absolute() {365 entry.clone()366 } else {367 self.dir.join(entry)368 };369 if !path.is_file() {370 return Err(missing(&path));371 }372 Ok(path)373 }374 375 fn entry_name(&self) -> Result<String, Failure> {376 let Some(entry) = &self.bundle.entry else {377 return Err(missing(&self.dir.join(ENTRY)));378 };379 Ok(entry.to_string_lossy().into_owned())380 }381 382 /// The base URL of the HTTP runtime, with the chat route removed.383 fn base_url(&self) -> Result<String, Failure> {384 let endpoint = lock(&self.endpoint).clone();385 endpoint386 .map(|url| base_url(&url))387 .ok_or_else(|| Failure::new(ErrorCode::Dependency, "the http engine is not loaded"))388 }389 390 /// The URL of one capability on the loaded runtime.391 fn endpoint_for(&self, capability: &str) -> Result<String, Failure> {392 Ok(format!("{}{}", self.base_url()?, route(capability)))393 }394 395 fn expand(&self, port: u16) -> Vec<String> {396 let paths: Vec<String> = lock(&self.granted)397 .iter()398 .map(|grant| grant.path())399 .collect();400 let model = paths.first().cloned().unwrap_or_default();401 let weights = paths.join(",");402 let port = port.to_string();403 self.bundle404 .args405 .iter()406 .map(|arg| {407 let mut arg = arg408 .replace("{model}", &model)409 .replace("{weights}", &weights)410 .replace("{port}", &port);411 for (index, path) in paths.iter().enumerate() {412 arg = arg.replace(&format!("{{weight{index}}}"), path);413 }414 arg415 })416 .collect()417 }418 419 /// Spawns one engine with every granted descriptor inheritable.420 ///421 /// The descriptors arrive with `CLOEXEC`, which is right for the binder but422 /// wrong for the engine that must open them. The flag is cleared around423 /// the one spawn and put back at once, so a descriptor is inherited by the424 /// engine and by no later process. A path-shaped grant still names its425 /// original file; a descriptor-only grant names `/proc/self/fd/<n>`, which426 /// resolves inside the child to the inherited descriptor.427 fn spawn_engine(&self, entry: &Path, args: &[String], io: ChildIo) -> std::io::Result<Running> {428 let granted = lock(&self.granted);429 let _spawn = lock(&SPAWN);430 let mut saved = Vec::with_capacity(granted.len());431 for grant in granted.iter() {432 saved.push(fcntl_getfd(grant.fd.as_fd()).map_err(io_error)?);433 }434 for grant in granted.iter() {435 if let Err(why) = fcntl_setfd(grant.fd.as_fd(), FdFlags::empty()) {436 restore(&granted, &saved);437 return Err(io_error(why));438 }439 }440 let mut command = Command::new(entry);441 command442 .args(args)443 .stdin(io.stdin)444 .stdout(io.stdout)445 .stderr(Stdio::piped())446 .process_group(0);447 if self.bundle.engine == EngineKind::Http && self.cache.is_some() {448 command.env(CACHE_DIR_ENV, &self.staging);449 }450 let child = command.spawn();451 restore(&granted, &saved);452 let mut child = child?;453 let stderr = match child.stderr.take() {454 Some(stderr) => std::thread::spawn(move || forward_stderr(stderr)),455 None => std::thread::spawn(|| {}),456 };457 Ok(Running { child, stderr })458 }459 460 /// Whether this bundle's binary entry is a resident JSON-lines worker.461 fn worker_mode(&self) -> bool {462 self.bundle.worker.as_deref() == Some("jsonl")463 }464 465 /// Starts the resident worker and waits for its ready line.466 ///467 /// The descriptors are already in `granted`, so the worker inherits them468 /// exactly as a one-shot binary would. `load_ms` covers the process start469 /// and the weight load that the worker reports with its ready line.470 fn spawn_worker(&self) -> Result<(Worker, Ready), Failure> {471 let entry = self.entry_file()?;472 let port = free_port().map_err(|why| {473 Failure::new(474 ErrorCode::Dependency,475 format!("no free port for the engine: {why}"),476 )477 })?;478 let args = self.expand(port);479 let started = Instant::now();480 let mut running = self481 .spawn_engine(482 &entry,483 &args,484 ChildIo {485 stdin: Stdio::piped(),486 stdout: Stdio::piped(),487 },488 )489 .map_err(|why| {490 Failure::new(491 ErrorCode::Dependency,492 format!("could not start {}: {why}", entry.display()),493 )494 })?;495 let Some(stdin) = running.child.stdin.take() else {496 kill(&mut running.child);497 let _ = running.stderr.join();498 return Err(Failure::new(499 ErrorCode::Dependency,500 "the worker has no standard input",501 ));502 };503 let Some(stdout) = running.child.stdout.take() else {504 kill(&mut running.child);505 let _ = running.stderr.join();506 return Err(Failure::new(507 ErrorCode::Dependency,508 "the worker has no standard output",509 ));510 };511 let (lines, reader) = line_reader(stdout, true);512 let mut worker = Worker {513 child: running.child,514 stdin,515 lines,516 reader,517 stderr: running.stderr,518 };519 if let Err(why) = wait_ready(&mut worker, self.start_budget()) {520 worker.stop();521 return Err(why);522 }523 let load_ms = u32::try_from(started.elapsed().as_millis()).unwrap_or(u32::MAX);524 Ok((525 worker,526 Ready {527 load_ms,528 cache_fingerprint: None,529 },530 ))531 }532 533 /// Makes sure one live worker exists. A dead one is removed first.534 fn ensure_worker(&self) -> Result<(), Failure> {535 let slot = Arc::clone(&self.worker);536 let stale = {537 let mut guard = lock(&slot);538 if guard.as_mut().is_some_and(|worker| worker.alive()) {539 return Ok(());540 }541 guard.take()542 };543 if let Some(worker) = stale {544 worker.stop();545 }546 let (worker, ready) = self.spawn_worker()?;547 self.load_ms.store(ready.load_ms, Ordering::SeqCst);548 *lock(&slot) = Some(worker);549 Ok(())550 }551 552 /// Whether a line is already waiting from a job that has ended. Such a553 /// line is stale: a clean worker has nothing to say between jobs. It is554 /// discarded by restarting the worker before the next request.555 fn worker_stale(&self) -> bool {556 let slot = Arc::clone(&self.worker);557 let mut guard = lock(&slot);558 let Some(worker) = guard.as_mut() else {559 return false;560 };561 match worker.lines.try_recv() {562 Ok(_) => true,563 Err(std::sync::mpsc::TryRecvError::Empty) => false,564 Err(std::sync::mpsc::TryRecvError::Disconnected) => true,565 }566 }567 568 /// Stops the resident worker, if one is running.569 fn stop_worker(&self) {570 let slot = Arc::clone(&self.worker);571 let worker = lock(&slot).take();572 if let Some(worker) = worker {573 worker.stop();574 }575 }576 577 fn start_http(&self) -> Result<Ready, Failure> {578 let entry = self.entry_file()?;579 let port = free_port().map_err(|why| {580 Failure::new(581 ErrorCode::Dependency,582 format!("no free port for the engine: {why}"),583 )584 })?;585 let started = Instant::now();586 let args = self.expand(port);587 let mut running = self588 .spawn_engine(589 &entry,590 &args,591 ChildIo {592 stdin: Stdio::null(),593 stdout: Stdio::null(),594 },595 )596 .map_err(|why| {597 Failure::new(598 ErrorCode::Dependency,599 format!("could not start {}: {why}", entry.display()),600 )601 })?;602 let budget = self.start_budget();603 if !wait_for_ready(&mut running.child, port, budget) {604 running.stop();605 return Err(Failure::new(606 ErrorCode::Dependency,607 format!(608 "{} did not answer /health within {} ms",609 entry.display(),610 budget.as_millis()611 ),612 ));613 }614 let host = std::net::Ipv4Addr::from(LOOPBACK);615 let endpoint = format!("http://{host}:{port}/v1");616 if let Some(old) = lock(&self.child).take() {617 old.stop();618 }619 *lock(&self.child) = Some(running);620 *lock(&self.endpoint) = Some(endpoint);621 let load_ms = u32::try_from(started.elapsed().as_millis()).unwrap_or(u32::MAX);622 self.load_ms.store(load_ms, Ordering::SeqCst);623 Ok(Ready {624 load_ms,625 cache_fingerprint: None,626 })627 }628 }629 630 impl Plugin for Bound {631 fn max_inflight(&self) -> u16 {632 if self.worker_mode() {633 // One resident worker owns one model and one request line at a634 // time. Declaring more would promise a concurrency it cannot keep.635 return 1;636 }637 if self.cache.is_some() {638 // One engine slot is one cache. Two jobs would race restore/save.639 return 1;640 }641 self.target.max_inflight.unwrap_or(ONE_JOB)642 }643 644 fn catalogue(&self) -> Catalogue {645 self.catalogue_now()646 }647 648 fn cache(&self) -> Option<Arc<dyn CacheCodec>> {649 self.cache.clone().map(|cache| cache as Arc<dyn CacheCodec>)650 }651 652 fn load(&self, grant: &Grant) -> Result<Ready, Failure> {653 self.load_fds(grant, &[])654 }655 656 fn load_fds(&self, grant: &Grant, fds: &[std::os::fd::OwnedFd]) -> Result<Ready, Failure> {657 if self.worker_mode() {658 self.stop_worker();659 }660 let mut granted = Vec::with_capacity(grant.deps.len());661 for dep in &grant.deps {662 let index = usize::try_from(dep.fd).map_err(|_| {663 Failure::new(ErrorCode::Dependency, "a weight descriptor is out of range")664 })?;665 let fd = fds.get(index).ok_or_else(|| {666 Failure::new(667 ErrorCode::Dependency,668 format!(669 "the grant names descriptor {} but only {} arrived",670 dep.fd,671 fds.len()672 ),673 )674 })?;675 granted.push(Granted {676 fd: fd.try_clone().map_err(|why| {677 Failure::new(678 ErrorCode::Dependency,679 format!("could not keep weight descriptor {}: {why}", dep.fd),680 )681 })?,682 path: (!dep.path.is_empty()).then(|| PathBuf::from(&dep.path)),683 });684 }685 *lock(&self.granted) = granted;686 match self.bundle.engine {687 EngineKind::Binary if self.worker_mode() => {688 let (worker, ready) = self.spawn_worker()?;689 self.load_ms.store(ready.load_ms, Ordering::SeqCst);690 *lock(&self.worker) = Some(worker);691 Ok(ready)692 }693 EngineKind::Binary => {694 self.entry_file()?;695 self.load_ms.store(0, Ordering::SeqCst);696 Ok(Ready {697 load_ms: 0,698 cache_fingerprint: None,699 })700 }701 EngineKind::Http => {702 let name = self.entry_name()?;703 if name.starts_with("https://") {704 return Err(Failure::new(705 ErrorCode::Dependency,706 "https needs a TLS stack; bind a local http runtime instead",707 ));708 }709 if name.starts_with("http://") {710 *lock(&self.endpoint) = Some(base_url(&name));711 self.load_ms.store(0, Ordering::SeqCst);712 Ok(Ready {713 load_ms: 0,714 cache_fingerprint: None,715 })716 } else {717 self.start_http()718 }719 }720 EngineKind::Library => Err(Failure::new(721 ErrorCode::Capability,722 "a shared library needs an authored shim",723 )),724 EngineKind::Authored => Err(Failure::new(725 ErrorCode::Capability,726 "an authored bundle does not use the binder",727 )),728 }729 }730 731 fn run(732 &self,733 capability: &str,734 req: Request<'_>,735 out: &mut dyn Emitter,736 ) -> Result<Report, Failure> {737 if !self.model.capabilities.contains_key(capability) {738 return Err(Failure::capability(capability));739 }740 match self.bundle.engine {741 EngineKind::Binary if self.worker_mode() => self.run_worker(capability, req, out),742 EngineKind::Binary => {743 if capability == CHAT {744 self.run_binary(req, out)745 } else {746 self.run_binary_capability(capability, req, out)747 }748 }749 EngineKind::Http => {750 if capability == CHAT {751 self.run_http(req, out)752 } else {753 let base = self.base_url()?;754 let timeout = Duration::from_millis(u64::from(out.remaining_ms()).max(1));755 caps::run(&base, capability, &self.model, &req, out, timeout)756 }757 }758 EngineKind::Library => Err(Failure::new(759 ErrorCode::Capability,760 "a shared library needs an authored shim",761 )),762 EngineKind::Authored => Err(Failure::new(763 ErrorCode::Capability,764 "an authored bundle does not use the binder",765 )),766 }767 }768 }769 770 impl Drop for Bound {771 fn drop(&mut self) {772 self.stop_worker();773 if let Some(running) = lock(&self.child).take() {774 running.stop();775 }776 if !self.staging.as_os_str().is_empty() {777 let _ = std::fs::remove_dir_all(&self.staging);778 }779 }780 }781 782 impl Bound {783 /// Runs one job on the resident JSON-lines worker.784 ///785 /// The job lock is the declared single-flight capacity. A cancel, a786 /// timeout, a malformed line, or an engine error drops the worker, so a787 /// job never inherits a half-read response. The next job starts a new one.788 fn run_worker(789 &self,790 capability: &str,791 req: Request<'_>,792 out: &mut dyn Emitter,793 ) -> Result<Report, Failure> {794 let _job = lock(&self.worker_job);795 let expected = req.request_id;796 let mut input = bridge_body(&self.model, capability, &req, Some(expected));797 input.push('\n');798 if input.len() > MAX_BRIDGE_BODY {799 return Err(Failure::new(800 ErrorCode::Size,801 format!(802 "the worker request is {} bytes, above the {MAX_BRIDGE_BODY} byte bridge cap",803 input.len()804 ),805 ));806 }807 let input = input.into_bytes();808 self.ensure_worker()?;809 if self.worker_stale() {810 self.stop_worker();811 self.ensure_worker()?;812 }813 let (deadline, budget) = job_deadline(out);814 let mut restart = false;815 let mut writer: Option<JoinHandle<()>> = None;816 let result = (|| -> Result<Report, Failure> {817 let slot = Arc::clone(&self.worker);818 let mut guard = lock(&slot);819 let Some(worker) = guard.as_mut() else {820 return Err(Failure::new(821 ErrorCode::Dependency,822 "the worker disappeared before the request",823 ));824 };825 let stdin = match worker.stdin.as_fd().try_clone_to_owned() {826 Ok(fd) => ChildStdin::from(fd),827 Err(why) => {828 restart = true;829 return Err(Failure::new(830 ErrorCode::Dependency,831 format!("the worker could not take the request: {why}"),832 ));833 }834 };835 writer = write_input(Some(stdin), input);836 loop {837 if writer.as_ref().is_some_and(|writer| writer.is_finished()) {838 break;839 }840 if out.cancelled() {841 restart = true;842 return Ok(Report::default());843 }844 if Instant::now() >= deadline {845 restart = true;846 return Err(Failure::new(847 ErrorCode::Timeout,848 format!(849 "the worker did not read the request within {} ms",850 budget.as_millis()851 ),852 ));853 }854 std::thread::sleep(JOB_POLL);855 }856 join_writer(writer.take());857 loop {858 if out.cancelled() {859 restart = true;860 return Ok(Report::default());861 }862 let left = deadline.saturating_duration_since(Instant::now());863 if left.is_zero() {864 restart = true;865 return Err(Failure::new(866 ErrorCode::Timeout,867 format!(868 "the worker sent no terminal line within {} ms",869 budget.as_millis()870 ),871 ));872 }873 match worker.lines.recv_timeout(left.min(JOB_POLL)) {874 Ok(Ok(line)) => {875 let Ok(value) = inf3r_json::parse(&line) else {876 restart = true;877 return Err(Failure::new(878 ErrorCode::Dependency,879 "the worker sent a line that is not JSON",880 ));881 };882 let Some(id) = value.get("id").and_then(inf3r_json::Value::as_str) else {883 restart = true;884 return Err(Failure::new(885 ErrorCode::Dependency,886 "the worker sent a line without the request id",887 ));888 };889 if id != expected {890 restart = true;891 return Err(Failure::new(892 ErrorCode::Dependency,893 format!("the worker answered id {id:?}, not {expected:?}"),894 ));895 }896 match bridge_event(out, &value) {897 Ok(Some(report)) => return Ok(report),898 Ok(None) => {}899 Err(why) => {900 restart = true;901 return Err(why);902 }903 }904 }905 Ok(Err(why)) => {906 restart = true;907 return Err(Failure::new(908 ErrorCode::Dependency,909 format!("could not read the worker: {why}"),910 ));911 }912 Err(RecvTimeoutError::Timeout) => {}913 Err(RecvTimeoutError::Disconnected) => {914 restart = true;915 return Err(Failure::new(916 ErrorCode::Dependency,917 "the worker exited before it finished the job",918 ));919 }920 }921 }922 })();923 if restart {924 self.stop_worker();925 }926 join_writer(writer);927 result928 }929 930 fn run_binary(&self, req: Request<'_>, out: &mut dyn Emitter) -> Result<Report, Failure> {931 let entry = self.entry_file()?;932 let mut input = prompt(&req).into_bytes();933 input.push(b'\n');934 if input.len() > MAX_BRIDGE_BODY {935 return Err(Failure::new(936 ErrorCode::Size,937 format!(938 "the engine request is {} bytes, above the {MAX_BRIDGE_BODY} byte bridge cap",939 input.len()940 ),941 ));942 }943 let port = free_port().map_err(|why| {944 Failure::new(945 ErrorCode::Dependency,946 format!("no free port for the engine: {why}"),947 )948 })?;949 let args = self.expand(port);950 let mut running = self951 .spawn_engine(952 &entry,953 &args,954 ChildIo {955 stdin: Stdio::piped(),956 stdout: Stdio::piped(),957 },958 )959 .map_err(|why| {960 Failure::new(961 ErrorCode::Dependency,962 format!("could not start {}: {why}", entry.display()),963 )964 })?;965 let writer = write_input(running.child.stdin.take(), input);966 let Some(stdout) = running.child.stdout.take() else {967 kill(&mut running.child);968 join_writer(writer);969 let _ = running.stderr.join();970 return Err(Failure::new(971 ErrorCode::Dependency,972 "the engine has no standard output",973 ));974 };975 let (lines, _reader) = line_reader(stdout, false);976 let (deadline, budget) = job_deadline(out);977 loop {978 match wait_line(&lines, deadline, out) {979 Ok(Line::Data(line)) => match emit(out, TEXT_CHANNEL, line.as_bytes()) {980 Ok(true) => {}981 Ok(false) => {982 kill(&mut running.child);983 join_writer(writer);984 let _ = running.stderr.join();985 return Ok(Report::default());986 }987 Err(why) => {988 kill(&mut running.child);989 join_writer(writer);990 let _ = running.stderr.join();991 return Err(why);992 }993 },994 Ok(Line::End) => break,995 Ok(Line::Cancelled) => {996 kill(&mut running.child);997 join_writer(writer);998 let _ = running.stderr.join();999 return Ok(Report::default());1000 }1001 Ok(Line::Timeout) => {1002 kill(&mut running.child);1003 join_writer(writer);1004 let _ = running.stderr.join();1005 return Err(Failure::new(1006 ErrorCode::Timeout,1007 format!("the engine sent no line within {} ms", budget.as_millis()),1008 ));1009 }1010 Err(why) => {1011 kill(&mut running.child);1012 join_writer(writer);1013 let _ = running.stderr.join();1014 return Err(why);1015 }1016 }1017 }1018 if out.cancelled() {1019 kill(&mut running.child);1020 join_writer(writer);1021 let _ = running.stderr.join();1022 return Ok(Report::default());1023 }1024 let status = match wait_child(&mut running.child, deadline) {1025 Ok(Some(status)) => status,1026 Ok(None) => {1027 kill(&mut running.child);1028 join_writer(writer);1029 let _ = running.stderr.join();1030 return Err(Failure::new(1031 ErrorCode::Timeout,1032 format!("the engine did not exit within {} ms", budget.as_millis()),1033 ));1034 }1035 Err(why) => {1036 kill(&mut running.child);1037 join_writer(writer);1038 let _ = running.stderr.join();1039 return Err(why);1040 }1041 };1042 join_writer(writer);1043 let _ = running.stderr.join();1044 if !status.success() {1045 return Err(Failure::new(1046 ErrorCode::Dependency,1047 format!("{} exited with {status}", entry.display()),1048 ));1049 }1050 Ok(Report::default())1051 }1052 1053 /// Runs one non-chat capability through a binary engine.1054 ///1055 /// The request is one JSON object on stdin. Each stdout line is either a1056 /// JSON object that names a channel and base64 bytes, or text. A JSON1057 /// object with `"event": true` is an event; without it the bytes are one1058 /// artifact. This keeps the child free of Rust and free of a fixed shape1059 /// beyond JSON.1060 fn run_binary_capability(1061 &self,1062 capability: &str,1063 req: Request<'_>,1064 out: &mut dyn Emitter,1065 ) -> Result<Report, Failure> {1066 let entry = self.entry_file()?;1067 let mut input = binary_body(&self.model, capability, &req).into_bytes();1068 input.push(b'\n');1069 if input.len() > MAX_BRIDGE_BODY {1070 return Err(Failure::new(1071 ErrorCode::Size,1072 format!(1073 "the engine request is {} bytes, above the {MAX_BRIDGE_BODY} byte bridge cap",1074 input.len()1075 ),1076 ));1077 }1078 let port = free_port().map_err(|why| {1079 Failure::new(1080 ErrorCode::Dependency,1081 format!("no free port for the engine: {why}"),1082 )1083 })?;1084 let args = self.expand(port);1085 let mut running = self1086 .spawn_engine(1087 &entry,1088 &args,1089 ChildIo {1090 stdin: Stdio::piped(),1091 stdout: Stdio::piped(),1092 },1093 )1094 .map_err(|why| {1095 Failure::new(1096 ErrorCode::Dependency,1097 format!("could not start {}: {why}", entry.display()),1098 )1099 })?;1100 let writer = write_input(running.child.stdin.take(), input);1101 let Some(stdout) = running.child.stdout.take() else {1102 kill(&mut running.child);1103 join_writer(writer);1104 let _ = running.stderr.join();1105 return Err(Failure::new(1106 ErrorCode::Dependency,1107 "the engine has no standard output",1108 ));1109 };1110 let (lines, _reader) = line_reader(stdout, true);1111 let (deadline, budget) = job_deadline(out);1112 loop {1113 match wait_line(&lines, deadline, out) {1114 Ok(Line::Data(line)) => match binary_line(out, &line) {1115 Ok(Some(report)) => {1116 kill(&mut running.child);1117 join_writer(writer);1118 let _ = running.stderr.join();1119 return Ok(report);1120 }1121 Ok(None) => {}1122 Err(why) => {1123 kill(&mut running.child);1124 join_writer(writer);1125 let _ = running.stderr.join();1126 return Err(why);1127 }1128 },1129 Ok(Line::End) => break,1130 Ok(Line::Cancelled) => {1131 kill(&mut running.child);1132 join_writer(writer);1133 let _ = running.stderr.join();1134 return Ok(Report::default());1135 }1136 Ok(Line::Timeout) => {1137 kill(&mut running.child);1138 join_writer(writer);1139 let _ = running.stderr.join();1140 return Err(Failure::new(1141 ErrorCode::Timeout,1142 format!("the engine sent no line within {} ms", budget.as_millis()),1143 ));1144 }1145 Err(why) => {1146 kill(&mut running.child);1147 join_writer(writer);1148 let _ = running.stderr.join();1149 return Err(why);1150 }1151 }1152 }1153 if out.cancelled() {1154 kill(&mut running.child);1155 join_writer(writer);1156 let _ = running.stderr.join();1157 return Ok(Report::default());1158 }1159 let status = match wait_child(&mut running.child, deadline) {1160 Ok(Some(status)) => status,1161 Ok(None) => {1162 kill(&mut running.child);1163 join_writer(writer);1164 let _ = running.stderr.join();1165 return Err(Failure::new(1166 ErrorCode::Timeout,1167 format!("the engine did not exit within {} ms", budget.as_millis()),1168 ));1169 }1170 Err(why) => {1171 kill(&mut running.child);1172 join_writer(writer);1173 let _ = running.stderr.join();1174 return Err(why);1175 }1176 };1177 join_writer(writer);1178 let _ = running.stderr.join();1179 if !status.success() {1180 return Err(Failure::new(1181 ErrorCode::Dependency,1182 format!("{} exited with {status}", entry.display()),1183 ));1184 }1185 Ok(Report::default())1186 }1187 1188 fn run_http(&self, req: Request<'_>, out: &mut dyn Emitter) -> Result<Report, Failure> {1189 let url = self.endpoint_for(CHAT)?;1190 let remaining = Duration::from_millis(u64::from(out.remaining_ms()).max(1));1191 if let Some(cache) = &self.cache {1192 let prepare_timeout = remaining.min(cache::PREFIX_BUDGET);1193 cache1194 .restore(&req, Duration::from_secs(2), prepare_timeout)1195 .map_err(|why| {1196 Failure::new(1197 ErrorCode::Dependency,1198 format!("the cache slot could not be made clean: {why}"),1199 )1200 })?;1201 if cache.cached_tokens() > 0 {1202 out.usage("cached_tokens", cache.cached_tokens());1203 }1204 }1205 // The prefix prepare may have consumed real prefill time; the chat1206 // gets what is left, not the budget from before the cache work.1207 let timeout = Duration::from_millis(u64::from(out.remaining_ms()).max(1));1208 let body = chat_body(&self.model, &req);1209 let reply = http::post(1210 &url,1211 "application/json",1212 "text/event-stream",1213 body.as_bytes(),1214 timeout,1215 )1216 .map_err(|why| {1217 Failure::new(1218 ErrorCode::Dependency,1219 format!("the engine at {url} could not be reached: {why}"),1220 )1221 })?;1222 let content_type = reply.content_type.clone().unwrap_or_default();1223 let mut reader = reply.reader;1224 let started = Instant::now();1225 let mut first_token_ms = None;1226 let mut tokens_out = 0;1227 let mut tokens_in = 0;1228 let mut answer = String::new();1229 if !content_type.contains("text/event-stream") {1230 let mut text = String::new();1231 reader.read_to_string(&mut text).map_err(|why| {1232 Failure::new(1233 ErrorCode::Dependency,1234 format!("the engine at {url} stopped: {why}"),1235 )1236 })?;1237 let value = inf3r_json::parse(&text).map_err(|why| {1238 Failure::new(1239 ErrorCode::Dependency,1240 format!("the engine at {url} sent no JSON: {why}"),1241 )1242 })?;1243 if let Some(tokens) = value1244 .get("usage")1245 .and_then(|usage| usage.get("completion_tokens"))1246 .and_then(inf3r_json::Value::as_u64)1247 {1248 tokens_out = tokens;1249 }1250 if let Some(tokens) = value1251 .get("usage")1252 .and_then(|usage| usage.get("prompt_tokens"))1253 .and_then(inf3r_json::Value::as_u64)1254 {1255 tokens_in = tokens;1256 }1257 if let Some(message) = value1258 .get("choices")1259 .and_then(inf3r_json::Value::as_array)1260 .and_then(|choices| choices.first())1261 .and_then(|choice| choice.get("message"))1262 {1263 if let Some(text) = message1264 .get("reasoning_content")1265 .and_then(inf3r_json::Value::as_str)1266 && !text.is_empty()1267 {1268 first_token_ms.get_or_insert_with(|| elapsed_ms(started));1269 if !emit(out, PROGRESS_CHANNEL, text.as_bytes())? {1270 if let Some(cache) = &self.cache {1271 cache.taint();1272 }1273 return Ok(Report::default());1274 }1275 }1276 if let Some(text) = message.get("content").and_then(inf3r_json::Value::as_str)1277 && !text.is_empty()1278 {1279 first_token_ms.get_or_insert_with(|| elapsed_ms(started));1280 answer.push_str(text);1281 if !emit(out, TEXT_CHANNEL, text.as_bytes())? {1282 if let Some(cache) = &self.cache {1283 cache.taint();1284 }1285 return Ok(Report::default());1286 }1287 }1288 }1289 let elapsed = elapsed_ms(started);1290 out.usage(USAGE_TOKENS_OUT, tokens_out);1291 if tokens_in > 0 {1292 out.usage("tokens_in", tokens_in);1293 }1294 out.usage(USAGE_FIRST_TOKEN_MS, first_token_ms.unwrap_or(elapsed));1295 out.usage(USAGE_TOKENS_PER_S, tokens_per_s(tokens_out, elapsed));1296 if let Some(cache) = &self.cache {1297 let prefill_ms = if cache.cached_tokens() > 0 {1298 01299 } else {1300 first_token_ms.unwrap_or(elapsed).min(u64::from(u32::MAX)) as u321301 };1302 let _ = cache.after_turn(1303 &req,1304 &answer,1305 prefill_ms,1306 tokens_in.saturating_add(tokens_out),1307 timeout,1308 );1309 }1310 return Ok(Report::default());1311 }1312 for line in reader.lines() {1313 if out.cancelled() {1314 if let Some(cache) = &self.cache {1315 cache.taint();1316 }1317 return Ok(Report::default());1318 }1319 let line = line.map_err(|why| {1320 Failure::new(1321 ErrorCode::Dependency,1322 format!("the engine at {url} stopped: {why}"),1323 )1324 })?;1325 let Some(data) = line.strip_prefix("data:") else {1326 continue;1327 };1328 let data = data.trim();1329 if data == "[DONE]" {1330 break;1331 }1332 let Ok(value) = inf3r_json::parse(data) else {1333 continue;1334 };1335 if let Some(tokens) = value1336 .get("usage")1337 .and_then(|usage| usage.get("completion_tokens"))1338 .and_then(Value::as_u64)1339 {1340 tokens_out = tokens;1341 out.usage(USAGE_TOKENS_OUT, tokens);1342 }1343 if let Some(tokens) = value1344 .get("usage")1345 .and_then(|usage| usage.get("prompt_tokens"))1346 .and_then(Value::as_u64)1347 {1348 tokens_in = tokens;1349 out.usage("tokens_in", tokens);1350 }1351 let Some(delta) = value1352 .get("choices")1353 .and_then(Value::as_array)1354 .and_then(|choices| choices.first())1355 .and_then(|choice| choice.get("delta"))1356 else {1357 continue;1358 };1359 if let Some(text) = delta.get("content").and_then(Value::as_str)1360 && !text.is_empty()1361 {1362 first_token_ms.get_or_insert_with(|| elapsed_ms(started));1363 answer.push_str(text);1364 if !emit(out, TEXT_CHANNEL, text.as_bytes())? {1365 if let Some(cache) = &self.cache {1366 cache.taint();1367 }1368 return Ok(Report::default());1369 }1370 }1371 if let Some(text) = delta.get("reasoning_content").and_then(Value::as_str)1372 && !text.is_empty()1373 {1374 first_token_ms.get_or_insert_with(|| elapsed_ms(started));1375 if !emit(out, PROGRESS_CHANNEL, text.as_bytes())? {1376 if let Some(cache) = &self.cache {1377 cache.taint();1378 }1379 return Ok(Report::default());1380 }1381 }1382 }1383 let elapsed = elapsed_ms(started);1384 if tokens_in > 0 {1385 out.usage("tokens_in", tokens_in);1386 }1387 out.usage(USAGE_FIRST_TOKEN_MS, first_token_ms.unwrap_or(elapsed));1388 out.usage(USAGE_TOKENS_PER_S, tokens_per_s(tokens_out, elapsed));1389 if let Some(cache) = &self.cache {1390 let prefill_ms = if cache.cached_tokens() > 0 {1391 01392 } else {1393 first_token_ms.unwrap_or(elapsed).min(u64::from(u32::MAX)) as u321394 };1395 let _ = cache.after_turn(1396 &req,1397 &answer,1398 prefill_ms,1399 tokens_in.saturating_add(tokens_out),1400 timeout,1401 );1402 }1403 Ok(Report::default())1404 }1405 }1406 1407 /// The binder entry point.1408 ///1409 /// A bound bundle contains one line that calls this function. Everything that1410 /// the bundle declares is read here, so the entry point cannot drift from the1411 /// manifests that the author signs.1412 pub fn main() -> std::process::ExitCode {1413 match start(None) {1414 Ok(()) => std::process::ExitCode::SUCCESS,1415 Err(why) => {1416 eprintln!("{why}");1417 std::process::ExitCode::FAILURE1418 }1419 }1420 }1421 1422 /// The entry point for a bundle that is built from a source tree.1423 ///1424 /// `inf3r_bind::main()` cannot see the bundle's own `CARGO_MANIFEST_DIR`: the1425 /// library was compiled once, in its own crate. The bundle passes the value1426 /// that its `main.rs` sees, so a checkout needs no environment variable and an1427 /// installed package still finds `bundle.toml` beside the binary.1428 pub fn main_at(dir: &'static str) -> std::process::ExitCode {1429 match start(Some(Path::new(dir))) {1430 Ok(()) => std::process::ExitCode::SUCCESS,1431 Err(why) => {1432 eprintln!("{why}");1433 std::process::ExitCode::FAILURE1434 }1435 }1436 }1437 1438 fn start(home: Option<&Path>) -> Result<(), BindError> {1439 let dir = find_bundle_dir(home)?;1440 let plugin = Bound::new(&dir)?;1441 inf3r_plugin_sdk::launch(Arc::new(plugin)).map_err(|why| BindError::Launch(why.to_string()))1442 }1443 1444 /// Finds the bundle directory in the order that the operator expects.1445 fn find_bundle_dir(home: Option<&Path>) -> Result<PathBuf, BindError> {1446 if let Some(dir) = std::env::var_os(BUNDLE_DIR) {1447 return Ok(PathBuf::from(dir));1448 }1449 if let Some(dir) = home1450 && dir.join("bundle.toml").is_file()1451 {1452 return Ok(dir.to_path_buf());1453 }1454 if let Ok(exe) = std::env::current_exe()1455 && let Some(parent) = exe.parent()1456 && parent.join("bundle.toml").is_file()1457 {1458 return Ok(parent.to_path_buf());1459 }1460 Err(BindError::Launch(format!(1461 "no bundle.toml in {BUNDLE_DIR}, in the build directory, or beside the binary"1462 )))1463 }1464 1465 /// The base URL of a runtime, from the chat endpoint or a base.1466 fn base_url(endpoint: &str) -> String {1467 let trimmed = endpoint.trim_end_matches('/');1468 let route = "/chat/completions";1469 let versioned = format!("/v1{route}");1470 for suffix in [versioned.as_str(), route] {1471 if let Some(base) = trimmed.strip_suffix(suffix) {1472 return base.to_string();1473 }1474 }1475 trimmed.to_string()1476 }1477 1478 /// The route of one capability below the base URL.1479 pub(crate) fn route(capability: &str) -> &'static str {1480 match capability {1481 "embed" => "/embeddings",1482 "rerank" => "/rerank",1483 "stt" => "/audio/transcriptions",1484 "tts" => "/audio/speech",1485 "image-gen" => "/images/generations",1486 "image-edit" => "/images/edits",1487 "music" => "/music",1488 "t2v-gen" => "/t2v-gen",1489 "i2v-gen" => "/i2v-gen",1490 "decide" => "/decide",1491 "extract" => "/extract",1492 _ => "/chat/completions",1493 }1494 }1495 1496 /// Writes the whole request on a thread, so a child that writes more than a1497 /// pipe buffer before it reads cannot deadlock the binder.1498 fn write_input(stdin: Option<std::process::ChildStdin>, bytes: Vec<u8>) -> Option<JoinHandle<()>> {1499 stdin.map(|mut stdin| {1500 std::thread::spawn(move || {1501 let _ = stdin.write_all(&bytes);1502 })1503 })1504 }1505 1506 fn join_writer(writer: Option<JoinHandle<()>>) {1507 if let Some(writer) = writer {1508 let _ = writer.join();1509 }1510 }1511 1512 /// The JSON request that a binary or generic bridge reads.1513 ///1514 /// `id` is present for a resident worker, which needs to answer one job at a1515 /// time without a new process. A one-shot binary does not need it.1516 fn bridge_body(model: &ModelSpec, capability: &str, req: &Request<'_>, id: Option<&str>) -> String {1517 let mut body = inf3r_json::Value::object();1518 if let Some(id) = id {1519 body = body.put("id", inf3r_json::Value::str(id));1520 }1521 let body = body1522 .put("model", inf3r_json::Value::str(model.serve.clone()))1523 .put("capability", inf3r_json::Value::str(capability))1524 .put("params", inf3r_proto::mirror::to_json(req.params))1525 .put("parts", bridge_parts(req))1526 .build();1527 inf3r_json::to_string(&body)1528 }1529 1530 /// The parts of one request in the neutral bridge shape.1531 fn bridge_parts(req: &Request<'_>) -> inf3r_json::Value {1532 let mut parts = Vec::new();1533 for part in req.parts {1534 let mut item = inf3r_json::Value::object()1535 .put("kind", inf3r_json::Value::str(kind_word(part.kind)))1536 .put("mime", inf3r_json::Value::str(part.mime));1537 if let Some(role) = part.role {1538 item = item.put("role", inf3r_json::Value::str(role));1539 }1540 let bytes = match part.body {1541 inf3r_plugin_sdk::capability::PartBody::Inline(bytes) => bytes.to_vec(),1542 inf3r_plugin_sdk::capability::PartBody::File(_) => {1543 let mut bytes = Vec::new();1544 let _ = part.reader().take(part.len).read_to_end(&mut bytes);1545 bytes1546 }1547 };1548 item = if part.kind == inf3r_proto::body::PartKind::Text {1549 item.put(1550 "text",1551 inf3r_json::Value::str(String::from_utf8_lossy(&bytes).into_owned()),1552 )1553 } else {1554 item.put(1555 "b64",1556 inf3r_json::Value::str(inf3r_json::b64::encode(&bytes)),1557 )1558 };1559 parts.push(item.build());1560 }1561 inf3r_json::Value::Array(parts)1562 }1563 1564 /// The JSON request that a one-shot binary engine reads.1565 fn binary_body(model: &ModelSpec, capability: &str, req: &Request<'_>) -> String {1566 bridge_body(model, capability, req, None)1567 }1568 1569 fn binary_line(out: &mut dyn Emitter, line: &str) -> Result<Option<Report>, Failure> {1570 let Ok(value) = inf3r_json::parse(line) else {1571 let _ = emit(out, TEXT_CHANNEL, line.as_bytes())?;1572 return Ok(None);1573 };1574 if value.as_object().is_none() {1575 let _ = emit(out, TEXT_CHANNEL, line.as_bytes())?;1576 return Ok(None);1577 }1578 let Some(channel) = value.get("channel").and_then(inf3r_json::Value::as_str) else {1579 if let Some(text) = value.get("text").and_then(inf3r_json::Value::as_str) {1580 let _ = emit(out, TEXT_CHANNEL, text.as_bytes())?;1581 }1582 return Ok(None);1583 };1584 let Some(encoded) = value.get("b64").and_then(inf3r_json::Value::as_str) else {1585 return Ok(None);1586 };1587 let bytes = inf3r_json::b64::decode(encoded)1588 .ok_or_else(|| Failure::new(ErrorCode::Dependency, "the engine sent bad base64"))?;1589 let mime = value1590 .get("mime")1591 .and_then(inf3r_json::Value::as_str)1592 .unwrap_or("application/octet-stream");1593 let event = value1594 .get("event")1595 .and_then(inf3r_json::Value::as_bool)1596 .unwrap_or(false);1597 if event {1598 let _ = emit_mime(out, channel, mime, &bytes)?;1599 } else {1600 out.artifact(channel, mime, Artifact::Bytes(bytes))1601 .map_err(|why| Failure::new(ErrorCode::Dependency, why.to_string()))?;1602 }1603 if let Some(meta) = value.get("meta").and_then(inf3r_json::Value::as_object) {1604 let mut report = Report::default();1605 for (key, value) in meta {1606 if let Some(value) = inf3r_proto::mirror::from_json(value) {1607 report.meta.insert(key.clone(), value);1608 }1609 }1610 return Ok(Some(report));1611 }1612 Ok(None)1613 }1614 1615 /// Handles one neutral bridge event.1616 ///1617 /// The same shape is used by a resident binary worker and by the generic HTTP1618 /// bridge: a channel with bytes, a terminal `done` with usage and meta, or an1619 /// `error`. A text field is a convenience for a line of text; a channel with1620 /// `b64` is the general form.1621 pub(crate) fn bridge_event(1622 out: &mut dyn Emitter,1623 value: &inf3r_json::Value,1624 ) -> Result<Option<Report>, Failure> {1625 if let Some(error) = value.get("error") {1626 let code = error1627 .get("code")1628 .and_then(inf3r_json::Value::as_str)1629 .map(error_code)1630 .unwrap_or(ErrorCode::Dependency);1631 let detail = error1632 .get("message")1633 .or_else(|| error.get("detail"))1634 .and_then(inf3r_json::Value::as_str)1635 .map(str::to_string)1636 .unwrap_or_else(|| "the worker refused the job".to_string());1637 return Err(Failure::new(code, detail));1638 }1639 if value.get("done").and_then(inf3r_json::Value::as_bool) == Some(true) {1640 return Ok(Some(report_from_value(value)));1641 }1642 let Some(channel) = value.get("channel").and_then(inf3r_json::Value::as_str) else {1643 if let Some(text) = value.get("text").and_then(inf3r_json::Value::as_str) {1644 let _ = emit(out, TEXT_CHANNEL, text.as_bytes())?;1645 }1646 return Ok(None);1647 };1648 let mime = value1649 .get("mime")1650 .and_then(inf3r_json::Value::as_str)1651 .unwrap_or("application/octet-stream");1652 let bytes = if let Some(encoded) = value.get("b64").and_then(inf3r_json::Value::as_str) {1653 inf3r_json::b64::decode(encoded)1654 .ok_or_else(|| Failure::new(ErrorCode::Dependency, "the worker sent bad base64"))?1655 } else if let Some(text) = value.get("text").and_then(inf3r_json::Value::as_str) {1656 text.as_bytes().to_vec()1657 } else {1658 Vec::new()1659 };1660 let event = value1661 .get("event")1662 .and_then(inf3r_json::Value::as_bool)1663 .unwrap_or(false);1664 if event {1665 let _ = emit_mime(out, channel, mime, &bytes)?;1666 } else {1667 out.artifact(channel, mime, Artifact::Bytes(bytes))1668 .map_err(|why| Failure::new(ErrorCode::Dependency, why.to_string()))?;1669 }1670 Ok(None)1671 }1672 1673 fn report_from_value(value: &inf3r_json::Value) -> Report {1674 let mut report = Report::default();1675 if let Some(usage) = value.get("usage").and_then(inf3r_json::Value::as_object) {1676 for (key, value) in usage {1677 if let Some(number) = value.as_u64() {1678 report.usage.insert(key.clone(), number);1679 }1680 }1681 }1682 if let Some(meta) = value.get("meta").and_then(inf3r_json::Value::as_object) {1683 for (key, value) in meta {1684 if let Some(value) = inf3r_proto::mirror::from_json(value) {1685 report.meta.insert(key.clone(), value);1686 }1687 }1688 }1689 report1690 }1691 1692 fn error_code(word: &str) -> ErrorCode {1693 match word {1694 "version" => ErrorCode::Version,1695 "frame" => ErrorCode::Frame,1696 "stream" => ErrorCode::Stream,1697 "size" => ErrorCode::Size,1698 "credit" => ErrorCode::Credit,1699 "busy" => ErrorCode::Busy,1700 "unknown_model" => ErrorCode::UnknownModel,1701 "capability" => ErrorCode::Capability,1702 "part" => ErrorCode::Part,1703 "dependency" => ErrorCode::Dependency,1704 "timeout" => ErrorCode::Timeout,1705 "cancelled" => ErrorCode::Cancelled,1706 _ => ErrorCode::Internal,1707 }1708 }1709 1710 fn kind_word(kind: inf3r_proto::body::PartKind) -> &'static str {1711 match kind {1712 inf3r_proto::body::PartKind::Text => "text",1713 inf3r_proto::body::PartKind::Image => "image",1714 inf3r_proto::body::PartKind::Audio => "audio",1715 inf3r_proto::body::PartKind::Video => "video",1716 inf3r_proto::body::PartKind::Tokens => "tokens",1717 inf3r_proto::body::PartKind::Json => "json",1718 }1719 }1720 1721 fn prompt(req: &Request<'_>) -> String {1722 let mut lines = Vec::new();1723 for part in req.parts {1724 let Some(text) = part.text() else {1725 continue;1726 };1727 match part.role {1728 Some(role) => lines.push(format!("{role}: {text}")),1729 None => lines.push(text.to_string()),1730 }1731 }1732 lines.join("\n")1733 }1734 1735 fn chat_body(model: &ModelSpec, req: &Request<'_>) -> String {1736 let (messages, tools) = chat_messages(req.parts);1737 let params = inf3r_proto::mirror::to_json(req.params);1738 let mut body = inf3r_json::Value::object();1739 let param_object = params.as_object();1740 if let Some(entries) = param_object {1741 for (key, value) in entries {1742 body = body.put(key.clone(), value.clone());1743 }1744 }1745 if !model.stops.is_empty() && !param_object.is_some_and(|map| map.contains_key("stop")) {1746 body = body.put(1747 "stop",1748 inf3r_json::Value::Array(1749 model1750 .stops1751 .iter()1752 .map(|stop| inf3r_json::Value::str(stop.clone()))1753 .collect(),1754 ),1755 );1756 }1757 body = body1758 .put("model", inf3r_json::Value::str(model.serve.clone()))1759 .put("stream", inf3r_json::Value::bool(true))1760 .put(1761 "stream_options",1762 inf3r_json::Value::object()1763 .put("include_usage", inf3r_json::Value::bool(true))1764 .build(),1765 )1766 .put("messages", inf3r_json::Value::Array(messages));1767 if let Some(tools) = tools {1768 body = body.put("tools", tools);1769 }1770 inf3r_json::to_string(&body.build())1771 }1772 1773 /// The messages and the separate tools field of one prompt.1774 ///1775 /// The binder and the prefix bridge share this so the engine is asked to1776 /// render exactly the prompt that the chat request will send.1777 pub(crate) fn chat_messages(1778 parts: &[inf3r_plugin_sdk::capability::Part<'_>],1779 ) -> (Vec<inf3r_json::Value>, Option<inf3r_json::Value>) {1780 let mut messages = Vec::new();1781 let mut tools = None;1782 for part in parts {1783 let role = part.role.unwrap_or(DEFAULT_ROLE);1784 match part.kind {1785 inf3r_proto::body::PartKind::Text => {1786 let text = text_of(part);1787 messages.push(1788 inf3r_json::Value::object()1789 .put("role", inf3r_json::Value::str(role))1790 .put("content", inf3r_json::Value::str(text))1791 .build(),1792 );1793 }1794 inf3r_proto::body::PartKind::Image => {1795 let bytes = bytes_of(part);1796 let url = format!(1797 "data:{};base64,{}",1798 part.mime,1799 inf3r_json::b64::encode(&bytes)1800 );1801 let content = inf3r_json::Value::object()1802 .put("type", inf3r_json::Value::str("image_url"))1803 .put(1804 "image_url",1805 inf3r_json::Value::object()1806 .put("url", inf3r_json::Value::str(url))1807 .build(),1808 )1809 .build();1810 messages.push(1811 inf3r_json::Value::object()1812 .put("role", inf3r_json::Value::str(role))1813 .put("content", inf3r_json::Value::Array(vec![content]))1814 .build(),1815 );1816 }1817 inf3r_proto::body::PartKind::Audio => {1818 let bytes = bytes_of(part);1819 let content = inf3r_json::Value::object()1820 .put("type", inf3r_json::Value::str("input_audio"))1821 .put(1822 "input_audio",1823 inf3r_json::Value::object()1824 .put(1825 "data",1826 inf3r_json::Value::str(inf3r_json::b64::encode(&bytes)),1827 )1828 .put("format", inf3r_json::Value::str(audio_format(part.mime)))1829 .build(),1830 )1831 .build();1832 messages.push(1833 inf3r_json::Value::object()1834 .put("role", inf3r_json::Value::str(role))1835 .put("content", inf3r_json::Value::Array(vec![content]))1836 .build(),1837 );1838 }1839 inf3r_proto::body::PartKind::Json => {1840 let value =1841 inf3r_json::parse_bytes(&bytes_of(part)).unwrap_or(inf3r_json::Value::Null);1842 if role == "tools" {1843 if let Some(array) = value.get("tools") {1844 tools = Some(array.clone());1845 }1846 } else {1847 messages.push(1848 inf3r_json::Value::object()1849 .put("role", inf3r_json::Value::str(role))1850 .put(1851 "content",1852 inf3r_json::Value::str(inf3r_json::to_string(&value)),1853 )1854 .build(),1855 );1856 }1857 }1858 _ => {}1859 }1860 }1861 (messages, tools)1862 }1863 1864 fn text_of(part: &inf3r_plugin_sdk::capability::Part<'_>) -> String {1865 if let Some(text) = part.text() {1866 return text.to_string();1867 }1868 String::from_utf8_lossy(&bytes_of(part)).into_owned()1869 }1870 1871 fn bytes_of(part: &inf3r_plugin_sdk::capability::Part<'_>) -> Vec<u8> {1872 let mut bytes = Vec::with_capacity(usize::try_from(part.len).unwrap_or(0));1873 let _ = part.reader().take(part.len).read_to_end(&mut bytes);1874 bytes1875 }1876 1877 fn audio_format(mime: &str) -> &str {1878 match mime {1879 "audio/wav" | "audio/x-wav" => "wav",1880 "audio/mpeg" => "mp3",1881 "audio/pcm" | "audio/L16" => "pcm",1882 other => other.rsplit('/').next().unwrap_or("wav"),1883 }1884 }1885 1886 fn emit(out: &mut dyn Emitter, channel: &str, bytes: &[u8]) -> Result<bool, Failure> {1887 emit_mime(out, channel, TEXT_MIME, bytes)1888 }1889 1890 fn emit_mime(1891 out: &mut dyn Emitter,1892 channel: &str,1893 mime: &str,1894 bytes: &[u8],1895 ) -> Result<bool, Failure> {1896 match out.emit(channel, mime, bytes) {1897 Ok(Emit::Sent) => Ok(true),1898 Ok(Emit::Blocked) => Ok(true),1899 Ok(Emit::Cancelled) => Ok(false),1900 Err(EmitError::Cancelled) => Ok(false),1901 Err(EmitError::Blocked) => Err(Failure::new(ErrorCode::Timeout, "the window never opened")),1902 }1903 }1904 1905 fn free_port() -> std::io::Result<u16> {1906 let listener = TcpListener::bind(std::net::SocketAddr::from((LOOPBACK, EPHEMERAL_PORT)))?;1907 let port = listener.local_addr()?.port();1908 drop(listener);1909 Ok(port)1910 }1911 1912 /// Waits until `/health` answers below 500, or the child exits.1913 ///1914 /// A port that accepts a connection is not a loaded model: a runtime may listen1915 /// first and answer 503 until the weights are in place. A 4xx means the server1916 /// is up but has no health route, so any answer below 500 is ready. A 5xx or a1917 /// closed port is retried until the budget ends.1918 fn wait_for_ready(child: &mut Child, port: u16, budget: Duration) -> bool {1919 let deadline = Instant::now() + budget;1920 let health = format!(1921 "http://{}:{port}/health",1922 std::net::Ipv4Addr::from(LOOPBACK)1923 );1924 while Instant::now() < deadline {1925 if let Ok(Some(_)) = child.try_wait() {1926 return false;1927 }1928 if let Ok(status) = http::status(1929 &health,1930 HEALTH_TIMEOUT.min(1931 deadline1932 .saturating_duration_since(Instant::now())1933 .max(PORT_POLL),1934 ),1935 ) && status < 5001936 {1937 return true;1938 }1939 std::thread::sleep(PORT_POLL);1940 }1941 false1942 }1943 1944 /// What a job saw while it waited for one line.1945 enum Line {1946 /// One complete line, with the trailing newline removed when requested.1947 Data(String),1948 /// The engine closed its standard output.1949 End,1950 /// The caller cancelled; the caller returns a cancelled report, not an1951 /// error.1952 Cancelled,1953 /// The job deadline passed before a line arrived.1954 Timeout,1955 }1956 1957 /// The end of one job, counted once from the emitter's initial budget.1958 fn job_deadline(out: &dyn Emitter) -> (Instant, Duration) {1959 let budget = Duration::from_millis(u64::from(out.remaining_ms()).max(1));1960 (Instant::now() + budget, budget)1961 }1962 1963 /// Waits for one line, polling cancellation and the fixed job deadline.1964 fn wait_line(1965 lines: &Receiver<std::io::Result<String>>,1966 deadline: Instant,1967 out: &dyn Emitter,1968 ) -> Result<Line, Failure> {1969 loop {1970 if out.cancelled() {1971 return Ok(Line::Cancelled);1972 }1973 let left = deadline.saturating_duration_since(Instant::now());1974 if left.is_zero() {1975 return Ok(Line::Timeout);1976 }1977 match lines.recv_timeout(left.min(JOB_POLL)) {1978 Ok(Ok(line)) => return Ok(Line::Data(line)),1979 Ok(Err(why)) => {1980 return Err(Failure::new(1981 ErrorCode::Dependency,1982 format!("could not read the engine: {why}"),1983 ));1984 }1985 Err(RecvTimeoutError::Timeout) => {}1986 Err(RecvTimeoutError::Disconnected) => return Ok(Line::End),1987 }1988 }1989 }1990 1991 /// Waits for a child after its output has ended, still inside the job deadline.1992 fn wait_child(1993 child: &mut Child,1994 deadline: Instant,1995 ) -> Result<Option<std::process::ExitStatus>, Failure> {1996 loop {1997 match child.try_wait() {1998 Ok(Some(status)) => return Ok(Some(status)),1999 Ok(None) => {}2000 Err(why) => {2001 return Err(Failure::new(2002 ErrorCode::Dependency,2003 format!("could not wait for the engine: {why}"),2004 ));2005 }2006 }2007 let left = deadline.saturating_duration_since(Instant::now());2008 if left.is_zero() {2009 return Ok(None);2010 }2011 std::thread::sleep(left.min(JOB_POLL));2012 }2013 }2014 2015 /// Reads one line with a hard ceiling, preserving the newline. The reader2016 /// returns an error instead of growing without bound when an engine sends a2017 /// line it never terminates.2018 fn read_capped_line<R: BufRead>(reader: &mut R, cap: usize) -> std::io::Result<Option<String>> {2019 let mut bytes = Vec::new();2020 loop {2021 let available = reader.fill_buf()?;2022 if available.is_empty() {2023 if bytes.is_empty() {2024 return Ok(None);2025 }2026 break;2027 }2028 let newline = available.iter().position(|byte| *byte == b'\n');2029 let take = newline.map_or(available.len(), |index| index + 1);2030 if bytes.len().saturating_add(take) > cap {2031 return Err(std::io::Error::new(2032 std::io::ErrorKind::InvalidData,2033 format!("a line is above {cap} bytes"),2034 ));2035 }2036 bytes.extend_from_slice(&available[..take]);2037 reader.consume(take);2038 if newline.is_some() {2039 break;2040 }2041 }2042 String::from_utf8(bytes)2043 .map(Some)2044 .map_err(|_| std::io::Error::new(std::io::ErrorKind::InvalidData, "a line is not UTF-8"))2045 }2046 2047 /// Reads an engine's standard output into a receiver of capped lines.2048 fn line_reader(2049 stdout: ChildStdout,2050 strip_newline: bool,2051 ) -> (Receiver<std::io::Result<String>>, JoinHandle<()>) {2052 let (sender, receiver) = mpsc::channel();2053 let reader = std::thread::spawn(move || {2054 let mut reader = BufReader::new(stdout);2055 loop {2056 match read_capped_line(&mut reader, MAX_BRIDGE_LINE) {2057 Ok(Some(mut line)) => {2058 if strip_newline {2059 if line.ends_with('\n') {2060 line.pop();2061 }2062 if line.ends_with('\r') {2063 line.pop();2064 }2065 }2066 if sender.send(Ok(line)).is_err() {2067 break;2068 }2069 }2070 Ok(None) => break,2071 Err(why) => {2072 let _ = sender.send(Err(why));2073 break;2074 }2075 }2076 }2077 });2078 (receiver, reader)2079 }2080 2081 /// Waits for the worker's one ready line, within the target's start budget.2082 fn wait_ready(worker: &mut Worker, budget: Duration) -> Result<(), Failure> {2083 if budget.is_zero() {2084 return Err(Failure::new(2085 ErrorCode::Timeout,2086 "the worker has no start budget",2087 ));2088 }2089 if let Ok(Some(status)) = worker.child.try_wait() {2090 return Err(Failure::new(2091 ErrorCode::Dependency,2092 format!("the worker exited before ready: {status}"),2093 ));2094 }2095 match worker.lines.recv_timeout(budget) {2096 Ok(Ok(line)) => {2097 let Ok(value) = inf3r_json::parse(&line) else {2098 return Err(Failure::new(2099 ErrorCode::Dependency,2100 "the worker sent a line that is not JSON before ready",2101 ));2102 };2103 if value.get("ready").and_then(inf3r_json::Value::as_bool) == Some(true) {2104 return Ok(());2105 }2106 if let Some(error) = value.get("error") {2107 let code = error2108 .get("code")2109 .and_then(inf3r_json::Value::as_str)2110 .map(error_code)2111 .unwrap_or(ErrorCode::Dependency);2112 let detail = error2113 .get("message")2114 .or_else(|| error.get("detail"))2115 .and_then(inf3r_json::Value::as_str)2116 .unwrap_or("the worker did not load");2117 return Err(Failure::new(code, detail));2118 }2119 Err(Failure::new(2120 ErrorCode::Dependency,2121 "the worker sent no ready line",2122 ))2123 }2124 Ok(Err(why)) => Err(Failure::new(2125 ErrorCode::Dependency,2126 format!("could not read the worker before ready: {why}"),2127 )),2128 Err(RecvTimeoutError::Timeout) => Err(Failure::new(2129 ErrorCode::Timeout,2130 format!("the worker was not ready within {} ms", budget.as_millis()),2131 )),2132 Err(RecvTimeoutError::Disconnected) => Err(Failure::new(2133 ErrorCode::Dependency,2134 "the worker exited before ready",2135 )),2136 }2137 }2138 2139 /// Copies an engine's stderr to this process, one line per line.2140 fn forward_stderr(stderr: std::process::ChildStderr) {2141 forward_stderr_to(BufReader::new(stderr), std::io::stderr());2142 }2143 2144 /// The writer-parameterised form, so a unit test can read the forwarded line.2145 fn forward_stderr_to<R: BufRead, W: Write>(reader: R, mut out: W) {2146 for line in reader.lines().map_while(Result::ok) {2147 let _ = writeln!(out, "inf3r-bind: engine: {line}");2148 }2149 }2150 2151 fn kill(child: &mut Child) {2152 if let Ok(pid) = i32::try_from(child.id())2153 && let Some(pid) = rustix::process::Pid::from_raw(pid)2154 {2155 let _ = rustix::process::kill_process_group(pid, rustix::process::Signal::KILL);2156 }2157 let _ = child.kill();2158 let _ = child.wait();2159 }2160 2161 fn elapsed_ms(started: Instant) -> u64 {2162 u64::try_from(started.elapsed().as_millis())2163 .unwrap_or(u64::MAX)2164 .max(1)2165 }2166 2167 fn tokens_per_s(tokens_out: u64, elapsed_ms: u64) -> u64 {2168 tokens_out2169 .saturating_mul(MS_PER_SECOND)2170 .saturating_mul(HUNDREDTHS)2171 / elapsed_ms2172 }2173 2174 fn restore(granted: &[Granted], saved: &[FdFlags]) {2175 for (grant, flags) in granted.iter().zip(saved) {2176 let _ = fcntl_setfd(grant.fd.as_fd(), *flags);2177 }2178 }2179 2180 fn io_error(why: rustix::io::Errno) -> std::io::Error {2181 std::io::Error::from(why)2182 }2183 2184 fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {2185 m.lock().unwrap_or_else(|poisoned| poisoned.into_inner())2186 }2187 2188 /// The load failure whose sentence names the path that the bundle promised.2189 fn missing(path: &Path) -> Failure {2190 Failure::new(2191 ErrorCode::Dependency,2192 format!("missing engine entry {}", path.display()),2193 )2194 }2195 2196 #[cfg(test)]2197 mod tests {2198 use super::forward_stderr_to;2199 2200 #[test]2201 fn an_engine_stderr_line_is_forwarded_with_its_prefix() {2202 let mut out = Vec::new();2203 forward_stderr_to(std::io::Cursor::new(b"loading weights\nsecond\n"), &mut out);2204 assert_eq!(2205 String::from_utf8(out).unwrap(),2206 "inf3r-bind: engine: loading weights\ninf3r-bind: engine: second\n"2207 );2208 }2209 }