Skip to main content

superfluid_daemon/
serve.rs

1//! `superfluid serve`: the server, as a library function so that another
2//! program can run it.
3
4use crate as superfluid_daemon;
5
6use std::os::unix::net::UnixListener;
7use std::path::{Path, PathBuf};
8use std::sync::Arc;
9
10use superfluid_daemon::runtime_pick::{RuntimeId, RuntimePick};
11use superfluid_daemon::{api, Daemon, EngineHost, SessionStore};
12
13fn retired(flag: &str, why: &str) {
14    eprintln!("superfluid: {flag} is retired — {why}");
15}
16
17fn sampling_f32(flag: &str, raw: &str, lo: f32, hi: f32) -> f32 {
18    let v: f32 = raw.parse().unwrap_or_else(|_| {
19        eprintln!("superfluid: {flag} expects a number, got {raw:?}");
20        std::process::exit(2);
21    });
22    if !v.is_finite() || v < lo || v > hi {
23        eprintln!("superfluid: {flag} must be a finite number in [{lo}, {hi}], got {v}");
24        std::process::exit(2);
25    }
26    v
27}
28
29fn usage_error(msg: &str, command: &str) -> ! {
30    eprintln!("superfluid: {msg}");
31    eprintln!("Run 'superfluid {command} --help' for its options.");
32    std::process::exit(2);
33}
34
35fn needs_value(flag: &str) -> ! {
36    usage_error(&format!("{flag} needs a value"), "serve")
37}
38
39fn num<T: std::str::FromStr>(flag: &str, raw: String) -> T {
40    raw.parse().unwrap_or_else(|_| usage_error(&format!("{flag} expects a number, got {raw:?}"), "serve"))
41}
42
43fn unknown_serve_flag(flag: &str) -> ! {
44    let hint = superfluid_daemon::cli::suggest(flag, superfluid_daemon::cli::serve_flag_names())
45        .map(|s| format!(" (did you mean {s}?)"))
46        .unwrap_or_default();
47    usage_error(&format!("serve has no option {flag}{hint}"), "serve")
48}
49
50fn human_bytes(n: u64) -> String {
51    const GIB: f64 = (1u64 << 30) as f64;
52    const MIB: f64 = (1u64 << 20) as f64;
53    if n as f64 >= GIB {
54        format!("{:.1} GiB", n as f64 / GIB)
55    } else {
56        format!("{:.0} MiB", n as f64 / MIB)
57    }
58}
59
60pub(crate) fn settle_park_dir(dir: &std::path::Path, parking: bool, budget_gb: u64) {
61    if parking {
62        let budget = budget_gb.saturating_mul(1 << 30);
63        if budget == 0 {
64            return;
65        }
66        let freed = superfluid_daemon::park::sweep(dir, budget);
67        if freed > 0 {
68            eprintln!(
69                "superfluid: park retention sweep freed {} in {} at startup (budget {budget_gb} GiB)",
70                human_bytes(freed),
71                dir.display()
72            );
73        }
74        return;
75    }
76    let stale: u64 = std::fs::read_dir(dir)
77        .map(|rd| {
78            rd.filter_map(|e| e.ok())
79                .filter(|e| {
80                    let n = e.file_name();
81                    let n = n.to_string_lossy();
82                    n.ends_with(".park") || n.ends_with(".park.tmp")
83                })
84                .filter_map(|e| e.metadata().ok().map(|m| m.len()))
85                .sum()
86        })
87        .unwrap_or(0);
88    if stale > 0 {
89        eprintln!(
90            "superfluid: {} of park artifacts in {} are from an earlier run with --park; \
91             nothing reads or reclaims them while parking is off. Delete them, or pass \
92             --park to put them back under --park-budget-gb.",
93            human_bytes(stale),
94            dir.display()
95        );
96    }
97}
98
99pub const SUN_PATH_LEN: usize = if cfg!(target_os = "linux") { 108 } else { 104 };
100
101fn listen_or_exit(flag: &str, addr: &str) -> std::net::TcpListener {
102    std::net::TcpListener::bind(addr).unwrap_or_else(|e| {
103        let hint = match e.kind() {
104            std::io::ErrorKind::AddrInUse => " (another process listens there: stop it or pick another port, e.g. --port 8454)",
105            std::io::ErrorKind::AddrNotAvailable => " (no interface on this machine has that address)",
106            std::io::ErrorKind::PermissionDenied => " (a port under 1024 needs privileges)",
107            _ => "",
108        };
109        eprintln!("superfluid: cannot listen on {flag} {addr}: {e}{hint}");
110        std::process::exit(1);
111    })
112}
113
114/// What a program running [`run`] in place of `superfluid serve` changes.
115/// [`Embedding::default`] is `superfluid serve` itself.
116#[derive(Debug, Clone)]
117pub struct Embedding {
118    /// The APIs served beside the OpenAI-compatible routes.
119    pub http: superfluid_daemon::openai::HttpSurface,
120    /// How a request's `model` picks the model that serves it.
121    pub model_naming: superfluid_daemon::openai::ModelNaming,
122    /// Names registered artifacts (initial, additional and model-dir models).
123    /// Receives already registered names so an embedding can disambiguate
124    /// variants. Explicit HTTP model IDs are not rewritten.
125    pub model_name: fn(&Path, &std::collections::HashSet<String>) -> String,
126    /// Sampling policy for omitted parameters; None is superfluid's default.
127    pub sampling_fallback: Option<superfluid_daemon::openai::SamplingFallback>,
128    /// The name and version the HTTP API reports for the server.
129    pub identity: superfluid_daemon::openai::ServerIdentity,
130    /// Whether the native session API listens on a unix socket (`--socket`).
131    /// Without it the HTTP API is all there is, and `--no-http` is refused.
132    pub session_socket: bool,
133    /// The program that runs a linked runtime's worker, in place of the `superfluid-workerd`
134    /// beside this executable; it passes [`crate::workerd::main`]'s arguments to it.
135    pub workerd: Option<PathBuf>,
136}
137
138impl Default for Embedding {
139    fn default() -> Embedding {
140        Embedding {
141            http: superfluid_daemon::openai::HttpSurface::default(),
142            model_naming: superfluid_daemon::openai::ModelNaming::default(),
143            model_name: superfluid_daemon::registry::distinct_name,
144            sampling_fallback: None,
145            identity: superfluid_daemon::openai::ServerIdentity::default(),
146            session_socket: true,
147            workerd: None,
148        }
149    }
150}
151
152/// Runs `superfluid serve`; `args` is its command line after `serve`.
153pub fn run(args: &[String], embedding: &Embedding) {
154    let mut models: Vec<PathBuf> = Vec::new();
155    let mut pull_flags = superfluid_daemon::pulls::PullFlags::default();
156    let mut runtime_pick = RuntimePick::default();
157    let mut api_key: Option<String> = None;
158    let mut rate_limit: u32 = 0;
159    let mut host: Option<String> = None;
160    let mut port: Option<u16> = None;
161    let mut files_max_bytes: Option<u64> = None;
162    let mut files_expiry: Option<u64> = None;
163    let mut files_sweep: u64 = 300;
164    let mut drain_timeout: u64 = 60;
165    let mut nonstream_keepalive: u64 = 0;
166    let mut default_max_tokens: Option<u32> = None;
167    let mut log_file: Option<PathBuf> = None;
168    let mut model_dir: Option<PathBuf> = None;
169    let mut tool_envelope: Option<superfluid_daemon::codec::ToolEnvelope> = None;
170    let mut idle_timeout: u64 = 0;
171    let mut sessions: Option<PathBuf> = None;
172    let mut socket: Option<PathBuf> = None;
173    let mut http: Option<String> = None;
174    let mut no_http = false;
175    let mut max_context: Option<i32> = None;
176    let mut max_context_auto_flag = false;
177    let mut max_batch: u32 = 8;
178    let mut op_temperature: Option<f32> = None;
179    let mut op_top_p: Option<f32> = None;
180    let mut op_top_k: Option<u32> = None;
181    let mut op_min_p: Option<f32> = None;
182    let mut op_repeat_penalty: Option<f32> = None;
183    let mut op_spec_max_temperature: Option<f32> = None;
184    let mut park = false;
185    let mut sessions_cache = false;
186    let mut park_lossy = false;
187    let mut park_budget_gb: u64 = 20;
188    let mut tool_lease_ms: u64 = 0;
189    let mut prefix_blob_budget_mb: u64 = 0;
190    let mut kv_bits_arg: Option<i32> = None;
191    let mut worker_process = true;
192    let mut os_pressure = true;
193    let mut dialect = String::from("auto");
194    let mut pressure_high: u8 = 0;
195    let mut pressure_low: u8 = 0;
196    let mut pin_budget_pct: u8 = superfluid_daemon::DaemonOptions::default().pin_budget_pct;
197    let mut tick_decode_budget: u32 = 0;
198    let mut tick_target_ms: u32 = 0;
199    let mut prefill_budget: u32 = superfluid_daemon::DaemonOptions::default().prefill_budget;
200    let mut starvation_ticks: u32 = 8;
201    let mut class_lanes_spec: Option<String> = None;
202    let mut http_default_qos = superfluid_daemon::openai::RequestQos::AGENT;
203    let mut http_qos_header = true;
204    let mut http_allow_batch_invariant = false;
205    let mut key_policy_path: Option<PathBuf> = None;
206    let mut qos_flags: Vec<&'static str> = Vec::new();
207    let mut log_dir: Option<PathBuf> = None;
208    let mut log_filter = String::from("info");
209    let mut speculate: Option<String> = None;
210    let mut speculation = superfluid_daemon::SpeculationOptions::default();
211    let mut spec_bitexact: Option<bool> = None;
212    let mut completion_deadline_ms: u64 = 0;
213    let mut completion_bucket = superfluid_daemon::completion_bucket::BucketConfig::default();
214    let mut fim_model: Option<PathBuf> = None;
215    let mut fim_max_context: Option<i32> = None;
216    let mut fim_max_batch: u32 = 2;
217    let mut web: Option<String> = None;
218    let mut web_origins: Vec<String> = Vec::new();
219    let mut otlp_metrics: Option<String> = None;
220    let mut otlp_interval_ms: u64 = 15_000;
221    let mut otlp_endpoint: Option<String> = None;
222    let mut otlp_cfg = superfluid_daemon::otlp::OtlpConfig::default();
223    let mut tui_flag = false;
224    let mut no_tui = false;
225    let mut fleet: Option<String> = None;
226    let mut fleet_auth: Option<PathBuf> = None;
227    let mut fleet_listen: Option<String> = None;
228    let mut fleet_policy = String::from("load-aware");
229    let mut fleet_pool_high: u32 = superfluid_daemon::fleet_manager::DEFAULT_POOL_HIGH_PCT;
230    let mut fleet_conns: usize = superfluid_daemon::fleet_manager::DEFAULT_CONNS_PER_NODE;
231    let args = superfluid_daemon::cli::split_equals(args, superfluid_daemon::cli::serve_takes_value);
232    let mut it = args.iter();
233    while let Some(a) = it.next() {
234        let mut val = || it.next().cloned().unwrap_or_else(|| needs_value(a));
235        // SERVE-FLAGS-BEGIN: every flag `serve` reads is listed in superfluid_daemon::cli (a test checks).
236        match a.as_str() {
237            "--model" => models.push(PathBuf::from(val())),
238            "--offline" => pull_flags.offline = true,
239            flag if flag.starts_with("--pull-") => {
240                let spec = &flag["--pull-".len()..];
241                let (name, value) = match spec.split_once('=') {
242                    Some((n, v)) => (n.to_string(), Some(v.to_string())),
243                    None => (spec.to_string(), it.clone().next().filter(|v| !v.starts_with("--")).cloned()),
244                };
245                if value.is_some() && !spec.contains('=') {
246                    it.next();
247                }
248                if name.is_empty() {
249                    unknown_serve_flag(a);
250                }
251                pull_flags.options.push((name, value));
252            }
253            "--runtime" => {
254                let v = val();
255                if let Err(e) = runtime_pick.add(&v) {
256                    eprintln!("superfluid: --runtime: {e}");
257                    std::process::exit(2);
258                }
259            }
260            "--api-key" => api_key = Some(val()),
261            "--rate-limit" => rate_limit = num(a, val()),
262            "--files-max-bytes" => {
263                files_max_bytes = Some(num(a, val()))
264            }
265            "--files-expiry" => files_expiry = Some(num(a, val())),
266            "--files-sweep" => files_sweep = num(a, val()),
267            "--drain-timeout" => drain_timeout = num(a, val()),
268            "--nonstream-keepalive" => {
269                nonstream_keepalive = num(a, val())
270            }
271            "--max-tokens" => {
272                default_max_tokens = Some(num(a, val()))
273            }
274            "--log-file" => log_file = Some(PathBuf::from(val())),
275            "--model-dir" => model_dir = Some(PathBuf::from(val())),
276            "--tool-call-parser" => {
277                let v = val();
278                if v != "auto" {
279                    tool_envelope = Some(
280                        superfluid_daemon::codec::ToolEnvelope::from_name(&v).unwrap_or_else(|| {
281                            eprintln!(
282                                "superfluid: unknown --tool-call-parser '{v}' (have: auto, {})",
283                                superfluid_daemon::codec::ToolEnvelope::names().join(", ")
284                            );
285                            std::process::exit(2);
286                        }),
287                    );
288                }
289            }
290            "--idle-timeout" => idle_timeout = num(a, val()),
291            "--host" => host = Some(val()),
292            "--port" => port = Some(num(a, val())),
293            "--max-batch-size" => max_batch = num(a, val()),
294            "--request-timeout" => {
295                completion_deadline_ms = num(a, val())
296            }
297            "--verbose" | "-v" => log_filter = "debug".into(),
298            "--help" | "-h" => {
299                print!("{}", superfluid_daemon::cli::serve_help());
300                return;
301            }
302            "--sessions" => sessions = Some(PathBuf::from(val())),
303            "--socket" => socket = Some(PathBuf::from(val())),
304            "--http" => http = Some(val()),
305            "--no-http" => no_http = true,
306            "--max-context" => {
307                let v = val();
308                max_context_auto_flag = v == "auto";
309                max_context = if v == "auto" { None } else { Some(num(a, v)) };
310            }
311            "--max-batch" => max_batch = num(a, val()),
312            "--temperature" => op_temperature = Some(sampling_f32("--temperature", &val(), 0.0, 2.0)),
313            "--top-p" => op_top_p = Some(sampling_f32("--top-p", &val(), 0.0, 1.0)),
314            "--top-k" => op_top_k = Some(num(a, val())),
315            "--min-p" => op_min_p = Some(sampling_f32("--min-p", &val(), 0.0, 1.0)),
316            "--repeat-penalty" => {
317                op_repeat_penalty = Some(sampling_f32("--repeat-penalty", &val(), 0.0, 2.0))
318            }
319            "--park" => park = true,
320            "--no-park" => park = false,
321            "--sessions-cache" => sessions_cache = true,
322            "--park-lossy" => {
323                park = true;
324                park_lossy = true;
325            }
326            "--park-budget-gb" => park_budget_gb = num(a, val()),
327            "--tool-lease-ms" => tool_lease_ms = num(a, val()),
328            "--prefix-blob-budget-mb" => {
329                prefix_blob_budget_mb = num(a, val())
330            }
331            "--kv-bits" => kv_bits_arg = Some(num(a, val())),
332            "--dialect" => dialect = val(),
333            "--worker-process" => worker_process = true,
334            "--no-worker-process" => worker_process = false,
335            "--os-pressure" => os_pressure = true,
336            "--no-os-pressure" => os_pressure = false,
337            "--pressure-high" => pressure_high = num(a, val()),
338            "--pressure-low" => pressure_low = num(a, val()),
339            "--pin-budget-pct" => pin_budget_pct = num(a, val()),
340            "--log-dir" => log_dir = Some(PathBuf::from(val())),
341            "--basert-lib" => std::env::set_var("BASERT_LIB", val()),
342            "--speculate" => {
343                let v = val();
344                speculate = if v == "off" { None } else { Some(v) };
345            }
346            "--spec-draft-tokens" => {
347                let n: u32 = num(a, val());
348                if !(1..=15).contains(&n) {
349                    eprintln!("superfluid: --spec-draft-tokens must be in 1..=15");
350                    std::process::exit(2);
351                }
352                speculation.max_draft = Some(n);
353            }
354            "--spec-adaptive" => speculation.adaptive = Some(true),
355            "--no-spec-adaptive" => speculation.adaptive = Some(false),
356            "--spec-min-yield" => {
357                let v: f64 = num(a, val());
358                if !v.is_finite() || v < 0.0 {
359                    eprintln!("superfluid: --spec-min-yield must be finite and non-negative");
360                    std::process::exit(2);
361                }
362                speculation.min_yield = Some(v);
363            }
364            "--spec-yield-rounds" => {
365                let n: u32 = num(a, val());
366                if n == 0 {
367                    eprintln!("superfluid: --spec-yield-rounds must be at least 1");
368                    std::process::exit(2);
369                }
370                speculation.yield_rounds = Some(n);
371            }
372            "--spec-throughput-gate" => speculation.throughput_gate = Some(true),
373            "--no-spec-throughput-gate" => speculation.throughput_gate = Some(false),
374            "--spec-gate-probe-tokens" => {
375                speculation.gate_probe_tokens = Some(num(a, val()))
376            }
377            "--spec-max-temperature" => {
378                op_spec_max_temperature = Some(sampling_f32("--spec-max-temperature", &val(), 0.0, 2.0))
379            }
380            "--spec-min-speedup" => {
381                let v: f64 = num(a, val());
382                if !v.is_finite() || v < 1.0 {
383                    eprintln!("superfluid: --spec-min-speedup must be finite and at least 1.0");
384                    std::process::exit(2);
385                }
386                speculation.min_speedup = Some(v);
387            }
388            "--spec-gate-reprobe" => {
389                speculation.gate_reprobe = Some(num(a, val()))
390            }
391            "--spec-gate-reprobe-max" => {
392                speculation.gate_reprobe_max = Some(num(a, val()))
393            }
394            "--dspark-confidence" => {
395                let v: f32 = num(a, val());
396                if !v.is_finite() || v <= 0.0 {
397                    eprintln!("superfluid: --dspark-confidence must be finite and positive");
398                    std::process::exit(2);
399                }
400                speculation.dspark_confidence = Some(v);
401            }
402            "--spec-bitexact" => spec_bitexact = Some(true),
403            "--no-spec-bitexact" => spec_bitexact = Some(false),
404            "--log-filter" => log_filter = val(),
405            "--tick-decode-budget" => {
406                tick_decode_budget = num(a, val())
407            }
408            "--tick-target-ms" => tick_target_ms = num(a, val()),
409            "--prefill-budget" => prefill_budget = num(a, val()),
410            "--starvation-ticks" => starvation_ticks = num(a, val()),
411            "--class-lanes" => {
412                class_lanes_spec = Some(val());
413                qos_flags.push("--class-lanes");
414            }
415            "--http-default-qos" => {
416                qos_flags.push("--http-default-qos");
417                let v = val();
418                http_default_qos.class = superfluid_daemon::qos::parse(&v).unwrap_or_else(|| {
419                    eprintln!(
420                        "superfluid: --http-default-qos expects one of {}, got {v:?}",
421                        superfluid_daemon::qos::NAMES.join(", ")
422                    );
423                    std::process::exit(2);
424                });
425            }
426            "--no-http-qos-header" => {
427                http_qos_header = false;
428                qos_flags.push("--no-http-qos-header");
429            }
430            "--http-allow-batch-invariant" => {
431                http_allow_batch_invariant = true;
432                qos_flags.push("--http-allow-batch-invariant");
433            }
434            "--key-policy" => key_policy_path = Some(PathBuf::from(val())),
435            "--completion-deadline-ms" => {
436                completion_deadline_ms = num(a, val())
437            }
438            "--completion-rate" => {
439                completion_bucket.rate_per_sec = num(a, val())
440            }
441            "--completion-burst" => {
442                completion_bucket.burst = num(a, val())
443            }
444            "--fim-model" => fim_model = Some(PathBuf::from(val())),
445            "--fim-max-context" => {
446                fim_max_context = Some(num(a, val()))
447            }
448            "--fim-max-batch" => fim_max_batch = num(a, val()),
449            "--web" => web = Some(val()),
450            "--web-origin" => web_origins.push(val()),
451            "--otlp-metrics" => otlp_metrics = Some(val()),
452            "--tui" => tui_flag = true,
453            "--no-tui" => no_tui = true,
454            "--otlp-interval-ms" => otlp_interval_ms = num(a, val()),
455            "--otlp-endpoint" => otlp_endpoint = Some(val()),
456            "--otlp-header" => {
457                let kv = val();
458                let (k, v) = kv.split_once('=').unwrap_or_else(|| usage_error(&format!("--otlp-header expects k=v, got {kv:?}"), "serve"));
459                otlp_cfg.headers.push((k.trim().to_string(), v.trim().to_string()));
460            }
461            "--otlp-service-name" => otlp_cfg.service_name = val(),
462            "--otlp-filter" => otlp_cfg.filter = val(),
463            "--otlp-queue" => otlp_cfg.queue = num(a, val()),
464            "--otlp-batch-ms" => {
465                let ms = num(a, val());
466                otlp_cfg.interval = std::time::Duration::from_millis(ms);
467            }
468            "--otlp-timeout-ms" => {
469                let ms = num(a, val());
470                otlp_cfg.timeout = std::time::Duration::from_millis(ms);
471            }
472            "--fleet" => fleet = Some(val()),
473            "--fleet-auth" => fleet_auth = Some(PathBuf::from(val())),
474            "--fleet-listen" => fleet_listen = Some(val()),
475            "--fleet-policy" => fleet_policy = val(),
476            "--fleet-pool-high" => fleet_pool_high = num(a, val()),
477            "--fleet-conns-per-node" => {
478                fleet_conns = num(a, val())
479            }
480            "--paged-kv" => retired(a, "paged KV is always on"),
481            "--prefix-cache" => retired(a, "prefix reuse is always on"),
482            "--continuous-batching" => {
483                if let Some(n) = it.clone().next().and_then(|v| v.parse::<u32>().ok()) {
484                    let _ = it.next();
485                    max_batch = n;
486                    retired(a, "always on; its width became --max-batch");
487                } else {
488                    retired(a, "continuous batching is always on");
489                }
490            }
491            "--prefix-cache-file" | "--prefix-cache-save-interval" => {
492                let _ = val();
493                retired(
494                    a,
495                    "superseded by the WAL session log (tokens, always durable) and the \
496                     in-memory prefix cache; KV on disk is --park, which is OFF by default \
497                     and applies to sessions resumed by id through the session API",
498                );
499            }
500            "--files-dir" => {
501                let _ = val();
502                retired(a, "the file store lives under --sessions");
503            }
504            "--media-dir" => {
505                let _ = val();
506                retired(
507                    a,
508                    "superfluid accepts only data: image URLs and never reads a local path, so there is nothing to allow-list",
509                );
510            }
511            "--metallib" | "--prefill-chunk" | "--gpu-wait-timeout-ms"
512            | "--decode-replay" => {
513                let _ = val();
514                retired(a, "an engine-level knob superfluid does not expose");
515            }
516            "--paged-weights" | "--no-paged-weights-retry" | "--no-baked-decode" => {
517                retired(a, "an engine-level knob superfluid does not expose")
518            }
519            other if !other.starts_with('-') => models.push(PathBuf::from(other)),
520            _ => unknown_serve_flag(a),
521        }
522        // SERVE-FLAGS-END
523    }
524    if models.is_empty() {
525        usage_error(
526            "serve needs a model: superfluid serve <path|org/model[:tag]>, e.g. \
527             superfluid serve unsloth/Qwen3.8-27B-GGUF:UD-Q4_K_M",
528            "serve",
529        );
530    }
531    superfluid_daemon::speculate_resolve::allow_catalog_fetch(!pull_flags.offline);
532    let catalog = Arc::new(match &embedding.workerd {
533        Some(workerd) => superfluid_daemon::runtimes::Catalog::with_workerd(workerd.clone()),
534        None => superfluid_daemon::runtimes::Catalog::from_env(),
535    });
536    let sessions = Some(sessions.unwrap_or_else(|| superfluid_daemon::cli::default_sessions(catalog.home())));
537    let socket = if embedding.session_socket {
538        Some(socket.unwrap_or_else(|| superfluid_daemon::cli::default_socket(catalog.home(), SUN_PATH_LEN)))
539    } else {
540        if socket.is_some() {
541            usage_error("--socket: this server has no session socket", "serve");
542        }
543        if no_http {
544            usage_error("--no-http leaves nothing to serve: this server has no session socket", "serve");
545        }
546        None
547    };
548    if no_http && (http.is_some() || host.is_some() || port.is_some()) {
549        usage_error("--no-http contradicts --http/--host/--port", "serve");
550    }
551    let mut pulled_names: std::collections::HashMap<PathBuf, String> = std::collections::HashMap::new();
552    for m in models.iter_mut() {
553        let token = m.to_string_lossy().into_owned();
554        if !superfluid_daemon::pulls::looks_like_id(&token) {
555            continue;
556        }
557        let runtime = match runtime_pick.explicit(m) {
558            Some(name) => catalog.named(name).ok().or_else(|| RuntimeId::parse(name)).unwrap_or_else(|| {
559                eprintln!("superfluid: --runtime '{name}' is not a runtime id");
560                std::process::exit(2);
561            }),
562            None => RuntimeId::new(superfluid_daemon::cli::runtime_for_id(&token)),
563        };
564        let path = superfluid_daemon::pulls::pull(&catalog, runtime, &token, &pull_flags).unwrap_or_else(|e| {
565            eprintln!("superfluid: {e}");
566            std::process::exit(1);
567        });
568        if let Err(e) = runtime_pick.add(&format!("{}={}", path.display(), runtime.name())) {
569            eprintln!("superfluid: {e}");
570            std::process::exit(2);
571        }
572        pulled_names.insert(path.clone(), superfluid_daemon::pulls::served_name(&token));
573        *m = path;
574    }
575    if !pull_flags.options.is_empty() && pulled_names.is_empty() {
576        eprintln!("superfluid: --pull-* options apply to models given by id; no --model here is one");
577        std::process::exit(2);
578    }
579    let (Some(model), Some(sessions)) = (models.first().cloned(), sessions) else {
580        unreachable!("a model and sessions are both set above");
581    };
582    if http.is_none() && !no_http {
583        http = Some(format!(
584            "{}:{}",
585            host.unwrap_or_else(|| "127.0.0.1".into()),
586            port.unwrap_or(8453)
587        ));
588    }
589    if let Some(socket) = socket.as_ref().filter(|s| s.as_os_str().len() >= SUN_PATH_LEN) {
590        eprintln!(
591            "superfluid: --socket {} is {} bytes; a unix socket path must be under {SUN_PATH_LEN} bytes here \
592             (pick a shorter one)",
593            socket.display(),
594            socket.as_os_str().len()
595        );
596        std::process::exit(2);
597    }
598    for (flag, addr) in [("--http", &http), ("--web", &web)] {
599        if let Some(addr) = addr {
600            drop(listen_or_exit(flag, addr));
601        }
602    }
603    let picked = runtime_pick.explicit(&model).is_some();
604    let runtime = runtime_pick
605        .resolve(&model, &catalog)
606        .map_err(|e| if picked { e } else { not_there(&model).unwrap_or(e) })
607        .and_then(|rt| match (catalog.require(rt), not_there(&model)) {
608            (Ok(rt), _) => Ok(rt),
609            (Err(_), Some(why)) => Err(why),
610            (Err(_), None) => superfluid_daemon::pulls::ensure_installed(&catalog, rt, pull_flags.offline),
611        })
612        .and_then(|rt| refuse_statically(&rt, park_lossy, kv_bits_arg, speculate.as_deref()).map(|()| rt))
613        .unwrap_or_else(|e| {
614            eprintln!("superfluid: {e}");
615            std::process::exit(2);
616        });
617    eprintln!("superfluid: runtime {} serves {} ({})", runtime.id.name(), model.display(), describe_worker(&runtime));
618    if let Some(on) = spec_bitexact {
619        std::env::set_var("BASERT_SPEC_BITEXACT", if on { "1" } else { "0" });
620    }
621    let (speculate_primary, speculate_fallbacks): (Option<String>, Vec<String>) = match speculation_for(
622        speculate.as_deref(),
623        &runtime.static_capabilities(),
624        &model,
625        runtime.id.name(),
626    )
627    .map(|d| superfluid_daemon::speculate_resolve::resolve_all(d, &model))
628    {
629        None => (None, Vec::new()),
630        Some(Ok(mut ranked)) => {
631            if let Some(r) = ranked.first() {
632                eprintln!("superfluid: speculation: {r}");
633            } else {
634                let dirs = superfluid_daemon::speculate_resolve::auto_search_dirs(&model);
635                let dirs: Vec<_> = dirs.iter().map(|(d, _)| d.display().to_string()).collect();
636                eprintln!(
637                    "superfluid: speculation: auto found no head in {} and no fitting drafter in {} — decoding plainly",
638                    model.display(),
639                    dirs.join(", ")
640                );
641            }
642            let primary = (!ranked.is_empty()).then(|| ranked.remove(0));
643            (primary, ranked)
644        }
645        Some(Err(e)) => {
646            eprintln!("superfluid: {e}");
647            std::process::exit(2);
648        }
649    };
650    if op_spec_max_temperature.is_some() && speculate.is_none() {
651        eprintln!("superfluid: --spec-max-temperature ignored: no --speculate strategy is configured");
652    }
653    if tui_flag && !cfg!(feature = "tui") {
654        eprintln!(
655            "superfluid: --tui: this build carries no TUI (build superfluid-daemon with the `tui` feature, \
656             which `basert` includes)"
657        );
658        std::process::exit(2);
659    }
660    let class_lanes = match class_lanes_spec.as_deref() {
661        None => [0; 4],
662        Some(spec) => superfluid_daemon::qos::parse_class_lanes(spec, max_batch as usize).unwrap_or_else(|e| {
663            eprintln!("superfluid: --class-lanes: {e}");
664            std::process::exit(2);
665        }),
666    };
667    let key_policy = key_policy_path.as_deref().map(|p| {
668        let table = superfluid_daemon::keypolicy::KeyTable::load(p, api_key.as_deref())
669            .unwrap_or_else(|e| {
670                eprintln!("superfluid: --key-policy {e}");
671                std::process::exit(2);
672            });
673        eprintln!("superfluid: key policy: {} key(s) from {}", table.len(), p.display());
674        Arc::new(table)
675    });
676    if let Err(e) = completion_bucket.validate() {
677        eprintln!("superfluid: --completion-rate/--completion-burst: {e}");
678        std::process::exit(2);
679    }
680    if fim_max_batch == 0 {
681        eprintln!("superfluid: --fim-max-batch must be at least 1");
682        std::process::exit(2);
683    }
684    if sessions_cache && park {
685        eprintln!(
686            "superfluid: --sessions-cache discards the session log at each start, which \
687             --park{} needs to resume parked sessions. Use one or the other.",
688            if park_lossy { "-lossy" } else { "" }
689        );
690        std::process::exit(2);
691    }
692    if models.len() > 1 && !worker_process {
693        eprintln!("superfluid: {} models — enabling --worker-process (each needs its own address space)", models.len());
694        worker_process = true;
695    }
696    if fim_model.is_some() && !worker_process {
697        eprintln!("superfluid: --fim-model needs its own worker — enabling --worker-process");
698        worker_process = true;
699    }
700    if model_dir.is_some() && !worker_process {
701        eprintln!("superfluid: --model-dir needs a per-model worker — enabling --worker-process");
702        worker_process = true;
703    }
704    if let Some(path) = &log_file {
705        use std::os::fd::AsRawFd;
706        match std::fs::OpenOptions::new().create(true).append(true).open(path) {
707            Ok(f) => {
708                // SAFETY: `f` is an open, valid fd for the duration of the
709                // call; dup2 onto STDERR_FILENO is the documented way to
710                // redirect a stream. The original stderr is closed by dup2.
711                unsafe {
712                    libc::dup2(f.as_raw_fd(), libc::STDERR_FILENO);
713                }
714                drop(f);
715            }
716            Err(e) => {
717                eprintln!("superfluid: could not open --log-file {}: {e}", path.display());
718                std::process::exit(1);
719            }
720        }
721    }
722    if api_key.is_none() && key_policy.is_none() {
723        let loopback = |addr: &str| {
724            addr.starts_with("localhost:") || addr.parse::<std::net::SocketAddr>().is_ok_and(|a| a.ip().is_loopback())
725        };
726        if http.as_deref().is_none_or(loopback) && web.as_deref().is_none_or(loopback) {
727            eprintln!("superfluid: no --api-key: the HTTP API is open to every process on this machine");
728        } else {
729            eprintln!(
730                "superfluid: WARNING --api-key not set. Authentication is OFF — anyone \
731                 who can reach this port can use the API. Bind loopback or set --api-key."
732            );
733        }
734    }
735    let fleet_mode = fleet.is_some() || fleet_listen.is_some();
736    if park && !fleet_mode {
737        let budget = if park_budget_gb == 0 {
738            "NO budget: --park-budget-gb 0 disables the retention sweep, so the \
739             directory grows without limit"
740                .to_string()
741        } else {
742            format!("budget {park_budget_gb} GiB, oldest evicted first")
743        };
744        eprintln!(
745            "superfluid: WARNING --park is on. Every finishing DURABLE session copies its \
746             whole KV off the GPU on the tick thread before it retires — seconds and \
747             gigabytes at agent context, and every other lane waits — then keeps an \
748             artifact under <sessions>/park ({budget}). A /v1/* request mints a fresh \
749             session and can never resume it, so its TERMINAL park is skipped; one \
750             PREEMPTED under load still parks, because it is requeued under the same id \
751             and adopts that artifact. This pays off only for sessions you resume by id \
752             through the session API."
753        );
754    }
755
756    let model_name = pulled_names.get(&model).cloned().unwrap_or_else(|| (embedding.model_name)(&model, &Default::default()));
757    if prefix_blob_budget_mb > 0 {
758        std::env::set_var("BASERT_PREFIX_BLOB_BUDGET_MB", prefix_blob_budget_mb.to_string());
759    }
760    if std::env::var_os("BASERT_YARN").is_some() {
761        eprintln!(
762            "superfluid: WARNING: BASERT_YARN is set but has no effect on this path — the rope \
763             kernels disable YaRN under paged/batched dispatch, which serving always uses. \
764             Long requests run UNSCALED past the trained window."
765        );
766    }
767
768    let tui_on =
769        cfg!(feature = "tui") && !no_tui && (tui_flag || std::io::IsTerminal::is_terminal(&std::io::stdout()));
770    let tui_ring = if tui_on {
771        Some(superfluid_daemon::telemetry::new_log_ring())
772    } else {
773        None
774    };
775    #[cfg(feature = "tui")]
776    let stderr_capture = tui_ring.as_ref().and_then(|ring| {
777        match superfluid_daemon::tui::capture_stderr(ring.clone()) {
778            Ok(guard) => Some(guard),
779            Err(e) => {
780                eprintln!("superfluid: stderr capture unavailable, engine output may overdraw the TUI: {e}");
781                None
782            }
783        }
784    });
785    #[cfg(feature = "tui")]
786    let worker_stderr = stderr_capture.as_ref().map(|c| c.worker_stderr());
787    #[cfg(not(feature = "tui"))]
788    let worker_stderr: Option<std::sync::Arc<std::os::fd::OwnedFd>> = None;
789    let log_dir_eff = log_dir.or(if tui_on { Some(sessions.join("logs")) } else { None });
790    if let Some(url) = &otlp_metrics {
791        if let Err(e) = superfluid_daemon::otlp::validate_http_url(url) {
792            eprintln!("superfluid: --otlp-metrics: {e}");
793            std::process::exit(2);
794        }
795        if otlp_interval_ms == 0 {
796            eprintln!("superfluid: --otlp-interval-ms must be > 0");
797            std::process::exit(2);
798        }
799    }
800    if fleet_mode && otlp_endpoint.is_some() {
801        eprintln!(
802            "superfluid: --otlp-endpoint is not supported in fleet-head mode (the fleet head \
803             has no scheduler to trace); set it on each node's superfluid instead"
804        );
805        std::process::exit(2);
806    }
807    let otlp = otlp_endpoint.map(|endpoint| {
808        let mut cfg = otlp_cfg;
809        cfg.endpoint = endpoint;
810        if let Err(e) = cfg.validate() {
811            eprintln!("superfluid: --otlp-endpoint: {e}");
812            std::process::exit(2);
813        }
814        eprintln!(
815            "superfluid: pushing operational traces to {} ({}an EGRESS: ids, lengths, timings and \
816             codes only, never session content; spans: {})",
817            cfg.traces_url(),
818            if cfg.is_loopback() { "" } else { "NON-LOOPBACK, " },
819            cfg.filter
820        );
821        cfg
822    });
823    use superfluid_daemon::telemetry::{LogConfig, LogSink};
824    let sink = match log_dir_eff {
825        Some(dir) => LogSink::File(LogConfig {
826            dir,
827            filter: log_filter,
828            ..Default::default()
829        }),
830        None => LogSink::Stderr(log_filter),
831    };
832    if let Err(e) = superfluid_daemon::telemetry::init_sinks(sink, tui_ring.clone(), otlp) {
833        eprintln!("superfluid: telemetry: {e}");
834    }
835    std::fs::create_dir_all(&sessions).expect("create sessions dir");
836    let _sessions_lock = if !fleet_mode { Some(lock_sessions_dir(&sessions)) } else { None };
837    if sessions_cache && !fleet_mode {
838        rotate_session_wal(&sessions);
839        if let Ok(rd) = std::fs::read_dir(sessions.join("models")) {
840            for dir in rd.filter_map(|e| e.ok()).map(|e| e.path()).filter(|d| d.is_dir()) {
841                rotate_session_wal(&dir);
842            }
843        }
844    }
845    if !fleet_mode {
846        settle_park_dir(&sessions.join("park"), park, park_budget_gb);
847        if let Ok(rd) = std::fs::read_dir(sessions.join("models")) {
848            let mut dirs: Vec<std::path::PathBuf> = rd
849                .filter_map(|e| e.ok())
850                .map(|e| e.path().join("park"))
851                .filter(|d| d.is_dir())
852                .collect();
853            dirs.sort();
854            for dir in dirs {
855                settle_park_dir(&dir, park, park_budget_gb);
856            }
857        }
858    }
859
860    if let Some(b) = kv_bits_arg {
861        if ![0, 4, 8, 16, 84].contains(&b) {
862            eprintln!("--kv-bits {b}: expected 0 (auto), 4 (q4_0), 8 (q8_0), 16 (f16) or 84 (K q8_0 / V q4_0)");
863            std::process::exit(2);
864        }
865    }
866    let kv_bits = match (park_lossy, kv_bits_arg) {
867        (true, None) | (true, Some(16)) => 16,
868        (true, Some(other)) => {
869            eprintln!("--park-lossy requires F16 KV pools; --kv-bits {other} conflicts");
870            std::process::exit(2);
871        }
872        (false, v) => v.unwrap_or(0),
873    };
874
875    let dir_default = max_context.is_none() && !max_context_auto_flag && model_dir.is_some();
876    // A fleet head holds no model; its window is the nodes', learned when it reaches them.
877    let max_context_auto = max_context.is_none() && !dir_default && !fleet_mode;
878    let sizing_lanes = if fim_model.is_some() { max_batch.max(fim_max_batch) } else { max_batch };
879    // (the window each lane's share of the device holds, the model's
880    // trained window)
881    let mut worker_sized: Option<(u64, u64)> = None;
882    let unsized_why: Option<(String, String)> = if max_context_auto {
883        let sizing = runtime.id.base();
884        let elsewhere = models.iter().chain(fim_model.iter()).find_map(|m| {
885            let on = if fim_model.as_ref() == Some(m) { catalog.reader_of(m) } else { runtime_pick.resolve(m, &catalog) };
886            on.ok().filter(|id| id.base() != sizing).map(|id| (m, id))
887        });
888        match elsewhere {
889            Some((m, id)) => Some((
890                format!(
891                    "--max-context auto sizes the window for the {} runtime, and {} is served by {}",
892                    sizing.name(),
893                    m.display(),
894                    id.base().name()
895                ),
896                format!(
897                    "not sized for this device: the {} runtime sizes it, and {} is served by {}",
898                    sizing.name(),
899                    m.display(),
900                    id.base().name()
901                ),
902            )),
903            None if !superfluid_daemon::linked::sizes_context(sizing) => {
904                let set: Vec<&PathBuf> = models.iter().chain(fim_model.iter()).collect();
905                let sized = set
906                    .iter()
907                    .map(|m| superfluid_daemon::runtimes::sizing_of(&runtime, m))
908                    .collect::<Result<Vec<_>, String>>()
909                    .and_then(|each| {
910                        let trained = each.iter().map(|s| s.trained_context).min().unwrap_or(0);
911                        superfluid_adapter_kit::sizing::window(&each, sizing_lanes).map(|n| (n, trained)).ok_or_else(|| {
912                            format!("the {} runtime reported no device budget to size a window against", sizing.name())
913                        })
914                    });
915                match sized {
916                    Ok(n) => {
917                        worker_sized = Some(n);
918                        None
919                    }
920                    Err(why) => Some((format!("--max-context auto: {why}"), why)),
921                }
922            }
923            None => None,
924        }
925    } else {
926        None
927    };
928    let max_context_auto = max_context_auto && unsized_why.is_none();
929    let ctx = if let Some(n) = max_context {
930        n
931    } else if fleet_mode {
932        8192
933    } else if dir_default {
934        eprintln!(
935            "superfluid: context window 8192 tokens (--model-dir loads models on demand at this window, so it is not \
936             sized to fill the device with the startup model; --max-context N|auto overrides)"
937        );
938        8192
939    } else if let Some((asked, kept)) = unsized_why {
940        if max_context_auto_flag {
941            eprintln!("superfluid: {asked}: pass --max-context <tokens>");
942            std::process::exit(2);
943        }
944        eprintln!("superfluid: context window 8192 tokens ({kept}; --max-context N pins it)");
945        8192
946    } else if let Some((per_lane, trained)) = worker_sized {
947        // One conversation may grow past its share of the pool, up to the trained window.
948        let whole = per_lane.saturating_mul(u64::from(sizing_lanes.max(1)));
949        let n = i32::try_from(whole.min(trained.max(per_lane))).unwrap_or(i32::MAX);
950        eprintln!(
951            "superfluid: context window {n} tokens (auto: sized for this device, {per_lane} for each of {sizing_lanes} lanes{}{}, \
952             one conversation up to the trained {trained}; --max-context N pins it)",
953            if models.len() > 1 { format!(", {} models", models.len()) } else { String::new() },
954            if fim_model.is_some() { ", FIM satellite included" } else { "" },
955        );
956        n
957    } else {
958        use superfluid_daemon::speculate_resolve::{resolve_all, sizing_path, SpecLoad};
959        let ranked: Vec<Vec<String>> = models
960            .iter()
961            .map(|m| {
962                if *m == model {
963                    speculate_primary.iter().chain(speculate_fallbacks.iter()).cloned().collect()
964                } else {
965                    speculate.as_deref().and_then(|d| resolve_all(d, m).ok()).unwrap_or_default()
966                }
967            })
968            .collect();
969        let sizing_models: Vec<PathBuf> = models.iter().cloned().chain(fim_model.iter().cloned()).collect();
970        let lanes = if fim_model.is_some() { max_batch.max(fim_max_batch) } else { max_batch } as i32;
971        let speculator_entry = |i: usize, r: &str| -> Option<(PathBuf, bool, Option<usize>)> {
972            let (path, load) = sizing_path(r, &models[i])?;
973            Some((path, load == SpecLoad::EmbeddedHead, (load == SpecLoad::Sidecar).then_some(i)))
974        };
975        let speculators_for = |choice: &[Option<&String>]| -> Vec<(PathBuf, bool, Option<usize>)> {
976            (0..models.len()).filter_map(|i| speculator_entry(i, choice[i].or(ranked[i].first())?)).collect()
977        };
978        let sizing = runtime.id.base();
979        let size = |speculators: &[(PathBuf, bool, Option<usize>)]| {
980            superfluid_daemon::linked::suggest_max_context(sizing, &sizing_models, speculators, lanes, kv_bits).unwrap_or_else(|e| {
981                eprintln!("superfluid: {e}");
982                std::process::exit(2);
983            })
984        };
985        let first_picks: Vec<Option<&String>> = vec![None; models.len()];
986        let n_spec = speculators_for(&first_picks).len();
987        const MAX_COMBINATIONS: usize = 16;
988        let counts: Vec<usize> = ranked.iter().map(|c| c.len().max(1)).collect();
989        let few_enough = counts
990            .iter()
991            .try_fold(1usize, |p, &c| p.checked_mul(c).filter(|p| *p <= MAX_COMBINATIONS))
992            .is_some();
993        let (sized, note) = if few_enough {
994            let mut best: Option<(i32, Vec<Option<&String>>)> = None;
995            let mut idx = vec![0usize; models.len()];
996            loop {
997                let choice: Vec<Option<&String>> =
998                    idx.iter().enumerate().map(|(i, &k)| (k > 0).then(|| &ranked[i][k])).collect();
999                if let Some(n) = size(&speculators_for(&choice)) {
1000                    if best.as_ref().is_none_or(|(b, _)| n < *b) {
1001                        best = Some((n, choice));
1002                    }
1003                }
1004                let mut i = 0;
1005                while i < idx.len() {
1006                    idx[i] += 1;
1007                    if idx[i] < counts[i] {
1008                        break;
1009                    }
1010                    idx[i] = 0;
1011                    i += 1;
1012                }
1013                if i == idx.len() {
1014                    break;
1015                }
1016            }
1017            let fallbacks: Vec<&str> =
1018                best.iter().flat_map(|(_, c)| c.iter().flatten().map(|s| s.as_str())).collect();
1019            let note = if fallbacks.is_empty() {
1020                String::new()
1021            } else {
1022                format!(", sized for the fallback {}", fallbacks.join(" + "))
1023            };
1024            (best.map(|(n, _)| n), note)
1025        } else {
1026            let all: Vec<(PathBuf, bool, Option<usize>)> = (0..models.len())
1027                .flat_map(|i| ranked[i].iter().filter_map(move |r| speculator_entry(i, r)))
1028                .collect();
1029            let note = format!(", every one of {} drafter candidates charged at once", all.len());
1030            (size(&all), note)
1031        };
1032        match sized {
1033            Some(n) => {
1034                eprintln!(
1035                    "superfluid: context window {n} tokens (auto: sized for this device, {lanes} lanes{}{}{}; --max-context N pins it)",
1036                    if n_spec == 0 { String::new() } else { format!(", {n_spec} speculator(s)") },
1037                    if fim_model.is_some() { ", FIM satellite included" } else { "" },
1038                    note
1039                );
1040                n
1041            }
1042            None => {
1043                eprintln!(
1044                    "superfluid: context window 8192 tokens (auto could not size this device/model set; --max-context N pins it)"
1045                );
1046                8192
1047            }
1048        }
1049    }
1050    .max(512);
1051    if let Some(n) = max_context {
1052        eprintln!("superfluid: context window {ctx} tokens (--max-context {n})");
1053    }
1054    // A worker process starts loading now, while the tokenizer and chat
1055    // template are built: the two do not depend on each other, and the load
1056    // is most of startup.
1057    let spawns_worker = !runtime.in_process_capable() || (worker_process && runtime.worker.bin.is_file());
1058    let early_host = (!fleet_mode && spawns_worker).then(|| {
1059        let spec = superfluid_daemon::WorkerSpec {
1060            bin: runtime.worker.bin.clone(),
1061            args: runtime.serve_args(&model, ctx, max_batch, kv_bits),
1062            stderr: worker_stderr.clone(),
1063        };
1064        std::thread::spawn(move || EngineHost::spawn_process(spec))
1065    });
1066    let tokenizer = open_tokenizer(&runtime, &model).unwrap_or_else(|e| {
1067        eprintln!("superfluid: {e}");
1068        std::process::exit(2);
1069    });
1070    let codec: Box<dyn superfluid_daemon::TextCodec + Send + Sync> = match codec_for_dialect(&dialect, tokenizer) {
1071        Ok((c, kind)) => {
1072            if dialect == "auto" {
1073                match kind {
1074                    "template" => eprintln!("superfluid: serving via the model's own chat template"),
1075                    "raw" => eprintln!(
1076                        "superfluid: model has no chat template; serving raw (chat routes will refuse)"
1077                    ),
1078                    _ => {}
1079                }
1080            }
1081            c
1082        }
1083        Err(e) => {
1084            eprintln!("superfluid: {e}");
1085            std::process::exit(2);
1086        }
1087    };
1088
1089    if fleet_mode {
1090        let fleet_addrs = fleet.clone().unwrap_or_default();
1091        use superfluid_daemon::fleet_manager::{FleetManager, NodeSpec, PlacementPolicy};
1092        let auth: Vec<u8> = match &fleet_auth {
1093            Some(pth) => std::fs::read(pth)
1094                .map(|t| t.trim_ascii().to_vec())
1095                .unwrap_or_else(|e| {
1096                    eprintln!("superfluid: cannot read --fleet-auth {}: {e}", pth.display());
1097                    std::process::exit(2);
1098                }),
1099            None => superfluid_daemon::fleet_token::read(catalog.home()).unwrap_or_default(),
1100        };
1101        if auth.is_empty() {
1102            eprintln!("superfluid: no fleet token (`superfluid fleet token` makes one): the links to the nodes are not encrypted, and only nodes on this machine may join");
1103        }
1104        let specs: Vec<NodeSpec> = fleet_addrs
1105            .split(',')
1106            .map(str::trim)
1107            .filter(|a| !a.is_empty())
1108            .map(|a| NodeSpec { addr: a.to_string(), auth: auth.clone() })
1109            .collect();
1110        if specs.is_empty() && fleet_listen.is_none() {
1111            eprintln!("superfluid: --fleet needs at least one host:port, or --fleet-listen for nodes that join");
1112            std::process::exit(2);
1113        }
1114        let policy = match fleet_policy.as_str() {
1115            "load-aware" => PlacementPolicy::LoadAware,
1116            "least-loaded" => PlacementPolicy::LeastLoaded,
1117            "round-robin" => PlacementPolicy::RoundRobin,
1118            other => {
1119                eprintln!(
1120                    "superfluid: unknown --fleet-policy '{other}' \
1121                     (load-aware|least-loaded|round-robin)"
1122                );
1123                std::process::exit(2);
1124            }
1125        };
1126        let Some(addr) = http else {
1127            eprintln!("superfluid: --fleet requires --http <addr> (the fleet OpenAI endpoint)");
1128            std::process::exit(2);
1129        };
1130        let lease = superfluid_proto::linkf::Lease { duration_ms: 60_000, renew_by_ms: 40_000 };
1131        let n_nodes = specs.len();
1132        let manager = Arc::new(FleetManager::with_options(
1133            specs,
1134            policy,
1135            lease,
1136            fleet_pool_high,
1137            fleet_conns,
1138        ));
1139        let mut reached = 0;
1140        for node in manager.probe() {
1141            match node {
1142                Ok(n) => {
1143                    reached += 1;
1144                    eprintln!(
1145                        "superfluid: fleet node '{}' at {}: {}, context window {} tokens, {} lanes",
1146                        n.identity,
1147                        n.addr,
1148                        n.models.join(", "),
1149                        n.max_context_tokens,
1150                        n.max_lanes
1151                    );
1152                    if !n.models.contains(&model_name) {
1153                        eprintln!(
1154                            "superfluid: fleet node '{}' serves {}, not {model_name}, so nothing is placed \
1155                             there; start it with --model-name {model_name}",
1156                            n.identity,
1157                            n.models.join(", ")
1158                        );
1159                    }
1160                }
1161                Err(e) => eprintln!("superfluid: {e}; retrying it in the background"),
1162            }
1163        }
1164        if max_context.is_none() {
1165            match manager.advertised_context(&model_name) {
1166                Some(n) => eprintln!("superfluid: context window {n} tokens (the largest node's)"),
1167                None => eprintln!(
1168                    "superfluid: context window unknown until a node serving {model_name} answers"
1169                ),
1170            }
1171        }
1172        manager.spawn_keepalive();
1173        let _announced = fleet_listen.as_deref().map(|listen| {
1174            let listener = std::net::TcpListener::bind(listen).unwrap_or_else(|e| {
1175                eprintln!("superfluid: --fleet-listen {listen}: {e}");
1176                std::process::exit(1);
1177            });
1178            let port = listener.local_addr().map(|a| a.port()).unwrap_or_default();
1179            eprintln!("superfluid: fleet head takes joining nodes on {listen}");
1180            let (m, a, name) = (Arc::clone(&manager), auth.clone(), model_name.clone());
1181            std::thread::spawn(move || superfluid_daemon::fleet_join::accept_nodes(listener, m, a, name));
1182            match superfluid_daemon::fleet_mdns::advertise(port, &model_name) {
1183                Ok(d) => Some(d),
1184                Err(e) => {
1185                    eprintln!("superfluid: not announced on the local network ({e}); give nodes this head's address");
1186                    None
1187                }
1188            }
1189        });
1190        if !qos_flags.is_empty() {
1191            eprintln!(
1192                "superfluid: {} not supported in fleet-head mode (the fleet head has no \
1193                 local scheduler and Link F carries no QoS class); set them on each \
1194                 node's own `superfluid serve` instead",
1195                qos_flags.join(", ")
1196            );
1197            std::process::exit(2);
1198        }
1199        if op_spec_max_temperature.is_some() {
1200            eprintln!(
1201                "superfluid: --spec-max-temperature is not supported in fleet-head mode; \
1202                 set it on each node's own `superfluid serve` instead"
1203            );
1204            std::process::exit(2);
1205        }
1206        if fim_model.is_some() {
1207            eprintln!(
1208                "superfluid: --fim-model is not supported in fleet-head mode (the head hosts no \
1209                 engine); set it on a node's own `superfluid serve` instead"
1210            );
1211            std::process::exit(2);
1212        }
1213        if op_repeat_penalty.is_some() {
1214            eprintln!(
1215                "superfluid: --repeat-penalty is not supported in fleet-head mode \
1216                 (the fleet protocol carries no per-request penalty); \
1217                 set it on each node's own `superfluid serve` instead"
1218            );
1219            std::process::exit(2);
1220        }
1221        let http_listener = listen_or_exit("--http", &addr);
1222        eprintln!(
1223            "superfluid: fleet-head openai api on http://{addr} over {n_nodes} node(s), {reached} reachable"
1224        );
1225        if key_policy.is_some() {
1226            eprintln!(
1227                "superfluid: --key-policy at the fleet head: keys, rate and concurrency limits \
1228                 apply; class and max_class do not (the head has no local scheduler)"
1229            );
1230        }
1231        let codec_arc: Arc<dyn superfluid_daemon::TextCodec + Send + Sync> = Arc::from(codec);
1232        superfluid_daemon::fleet_openai::serve_blocking(
1233            http_listener,
1234            manager,
1235            codec_arc,
1236            "raw".to_string(),
1237            model_name.clone(),
1238            max_context.map_or(0, |n| n.max(512) as u32),
1239            superfluid_daemon::openai::ServeConfig {
1240                api_key: api_key.clone(),
1241                rate_limit_per_minute: rate_limit,
1242                keys: key_policy.clone(),
1243                sampling: superfluid_daemon::openai::SamplingOverrides {
1244                    temperature: op_temperature,
1245                    top_p: op_top_p,
1246                    top_k: op_top_k,
1247                    min_p: op_min_p,
1248                    repeat_penalty: op_repeat_penalty,
1249                    spec_max_temperature: None,
1250                    fallback: embedding.sampling_fallback,
1251                },
1252                ..Default::default()
1253            },
1254        )
1255        .expect("fleet serve");
1256        return;
1257    }
1258
1259    let wal_path = sessions.join("wal.log");
1260    let store = match SessionStore::open(&wal_path) {
1261        Ok(store) => store,
1262        Err(e @ (superfluid_daemon::DaemonError::WalCorrupt | superfluid_daemon::DaemonError::Codec(_))) => {
1263            eprintln!(
1264                "superfluid: the session log {} is damaged ({e}). A record with more of the log \
1265                 after it fails its checksum, or a whole record does not decode, so this was not a \
1266                 crash mid-write (a torn last record is dropped on its own); this server won't guess \
1267                 which history to keep. Move the file aside to start fresh, or run with \
1268                 --sessions-cache if sessions don't need to survive a restart.",
1269                wal_path.display()
1270            );
1271            std::process::exit(1);
1272        }
1273        Err(e) => {
1274            eprintln!("superfluid: could not open the session log {}: {e}", wal_path.display());
1275            std::process::exit(1);
1276        }
1277    };
1278
1279    let workerd_bin = catalog.workerd().to_path_buf();
1280    let worker_process = if !runtime.in_process_capable() {
1281        if !worker_process {
1282            eprintln!(
1283                "superfluid: --no-worker-process: the {} runtime runs in its own worker ({})",
1284                runtime.id.name(),
1285                runtime.worker.bin.display()
1286            );
1287        }
1288        true
1289    } else if worker_process && !runtime.worker.bin.is_file() {
1290        if fim_model.is_some() {
1291            eprintln!(
1292                "superfluid: --fim-model needs superfluid-workerd (the satellite runs in its own \
1293                 worker), not found at {}",
1294                workerd_bin.display()
1295            );
1296            std::process::exit(1);
1297        }
1298        if models.len() > 1 {
1299            eprintln!(
1300                "superfluid: {} models need superfluid-workerd (one address space each), \
1301                 not found at {}",
1302                models.len(),
1303                workerd_bin.display()
1304            );
1305            std::process::exit(1);
1306        }
1307        eprintln!(
1308            "superfluid: superfluid-workerd not found at {}; running the engine in-process \
1309             (install the bundled workerd or pass --no-worker-process to silence)",
1310            workerd_bin.display()
1311        );
1312        false
1313    } else {
1314        worker_process
1315    };
1316    let model_display = model.display().to_string();
1317    let model_source = model.to_string_lossy().into_owned();
1318    let host = if worker_process {
1319        match early_host {
1320            Some(started) => started.join().expect("worker start thread"),
1321            None => EngineHost::spawn_process(superfluid_daemon::WorkerSpec {
1322                bin: runtime.worker.bin.clone(),
1323                args: runtime.serve_args(&model, ctx, max_batch, kv_bits),
1324                stderr: worker_stderr.clone(),
1325            }),
1326        }
1327        .unwrap_or_else(|e| {
1328            #[cfg(feature = "tui")]
1329            if let Some(c) = stderr_capture.as_ref() {
1330                c.drain(std::time::Duration::from_secs(2));
1331            }
1332            eprintln!(
1333                "superfluid: could not start the engine worker for '{model_display}': {e} \
1334                 (the worker's stderr above carries the engine's reason)"
1335            );
1336            std::process::exit(1);
1337        })
1338    } else {
1339        superfluid_daemon::linked::spawn(runtime.id, model, ctx, max_batch, kv_bits)
1340            .unwrap_or_else(|| Err(format!("this build does not link the {} runtime", runtime.id)))
1341            .unwrap_or_else(|e| {
1342                eprintln!("superfluid: could not load '{model_display}': {e}");
1343                std::process::exit(1);
1344            })
1345    };
1346
1347    let caps = host.capabilities().read().expect("capability record").clone();
1348    if let Err(e) = caps.check_startup_flags(park_lossy, kv_bits_arg, speculate.as_deref()) {
1349        eprintln!("superfluid: {e}");
1350        std::process::exit(2);
1351    }
1352    if prefix_blob_budget_mb > 0 {
1353        if let superfluid_daemon::capabilities::Cap::No(why) = caps.get("ops", "space_promote") {
1354            eprintln!("superfluid: --prefix-blob-budget-mb has no effect on runtime {}: {why}", runtime.id.name());
1355        }
1356    }
1357
1358    let listener = socket.as_ref().map(|socket| {
1359        let _ = std::fs::remove_file(socket);
1360        let listener = UnixListener::bind(socket).unwrap_or_else(|e| {
1361            eprintln!("superfluid: cannot listen on --socket {}: {e}", socket.display());
1362            std::process::exit(1);
1363        });
1364        eprintln!("superfluid: serving on {}", socket.display());
1365        listener
1366    });
1367    let park_dir = park.then(|| sessions.join("park"));
1368
1369    let codec: Box<dyn superfluid_daemon::TextCodec + Send + Sync> = match tool_envelope {
1370        Some(env) => {
1371            if let Some(why) = superfluid_daemon::codec::tool_envelope_override_conflict(&*codec, env) {
1372                eprintln!("superfluid: {why}");
1373                std::process::exit(2);
1374            }
1375            eprintln!("superfluid: tool-call envelope overridden to '{}'", env.name());
1376            Box::new(superfluid_daemon::codec::WithToolEnvelope::new(codec, env))
1377        }
1378        None => codec,
1379    };
1380    let daemon = Arc::new(
1381        Daemon::with_options(
1382            store,
1383            host,
1384            codec,
1385            superfluid_daemon::DaemonOptions {
1386                max_lanes: max_batch as usize,
1387                park_dir,
1388                park_lossy,
1389                park_budget_bytes: park_budget_gb.saturating_mul(1 << 30),
1390                tool_lease_ms,
1391                tick_decode_budget,
1392                tick_target_ms,
1393                runtime_id: Some(runtime.id.name()),
1394                prefill_budget,
1395                agent_starvation_ticks: starvation_ticks,
1396                class_lanes,
1397                pressure_high_pct: if pressure_high > 0 { pressure_high } else { 85 },
1398                pressure_low_pct: if pressure_low > 0 { pressure_low } else { 70 },
1399                pin_budget_pct,
1400                pressure_source: if os_pressure {
1401                    superfluid_daemon::pressure::PressureConfig::Os
1402                } else {
1403                    superfluid_daemon::pressure::PressureConfig::None
1404                },
1405                speculate: speculate_primary.clone(),
1406                speculate_auto: speculate.as_deref().map(str::trim) == Some("auto"),
1407                speculate_fallbacks: speculate_fallbacks.clone(),
1408                speculation: speculation.clone(),
1409                media_dir: Some(sessions.join("media")),
1410                files_max_bytes,
1411                files_expiry_secs: files_expiry,
1412                completion_deadline_ms,
1413                trace_scope: superfluid_daemon::otlp::TraceScope::model(&model_name),
1414                completion_bucket,
1415            },
1416        )
1417        .unwrap_or_else(|e| {
1418            #[cfg(feature = "tui")]
1419            if let Some(c) = stderr_capture.as_ref() {
1420                c.drain(std::time::Duration::from_secs(2));
1421            }
1422            eprintln!("superfluid: cannot serve '{model_display}': {e}");
1423            std::process::exit(2);
1424        }),
1425    );
1426    {
1427        let bits = daemon.sched_stats().kv_bits.load(std::sync::atomic::Ordering::Relaxed);
1428        match superfluid_daemon::scheduler::kv_bits_label(bits) {
1429            Some(label) if kv_bits != 0 && bits != kv_bits as u64 => {
1430                eprintln!("superfluid: kv cache {label} (--kv-bits {kv_bits} overridden by the engine, see above)")
1431            }
1432            Some(label) => eprintln!("superfluid: kv cache {label}"),
1433            None => {}
1434        }
1435    }
1436    let fim_satellite: Option<(String, Arc<Daemon>)> = fim_model.as_ref().map(|path| {
1437        let runtime = catalog.reader_of(path).and_then(|id| catalog.require(id)).unwrap_or_else(|e| {
1438            eprintln!("superfluid: --fim-model {}: {e}", path.display());
1439            std::process::exit(2);
1440        });
1441        let mut fim_ctx = fim_max_context.unwrap_or(ctx.min(8192)).max(512);
1442        if max_context_auto && fim_ctx > ctx {
1443            eprintln!(
1444                "superfluid: --fim-max-context {fim_ctx} is above the window sized for this device; \
1445                 the FIM satellite runs at {ctx}"
1446            );
1447            fim_ctx = ctx;
1448        }
1449        let sat = build_fim_satellite(&FimSatelliteCfg {
1450            model: path.clone(),
1451            runtime,
1452            sessions: sessions.clone(),
1453            ctx: fim_ctx,
1454            max_batch: fim_max_batch,
1455            kv_bits,
1456            pressure_high,
1457            pressure_low,
1458            os_pressure,
1459            completion_deadline_ms,
1460            worker_stderr: worker_stderr.clone(),
1461        })
1462        .unwrap_or_else(|e| {
1463            #[cfg(feature = "tui")]
1464            if let Some(c) = stderr_capture.as_ref() {
1465                c.drain(std::time::Duration::from_secs(2));
1466            }
1467            eprintln!("superfluid: could not start the --fim-model satellite '{}': {e}", path.display());
1468            std::process::exit(1);
1469        });
1470        let name = superfluid_daemon::registry::model_id_for(path);
1471        eprintln!("superfluid: FIM completions served by satellite '{name}'");
1472        (name, sat)
1473    });
1474    if let Some((name, sat)) = &fim_satellite {
1475        if let Err(e) = daemon.attach_fim_satellite(name.clone(), Arc::clone(sat)) {
1476            eprintln!(
1477                "superfluid: --fim-model {}: {e} (its tokenizer has no atomic <|fim_prefix|>/<|fim_suffix|>/<|fim_middle|> tokens)",
1478                fim_model.as_ref().map(|p| p.display().to_string()).unwrap_or_default()
1479            );
1480            std::process::exit(2);
1481        }
1482    }
1483    let state_names: StateNames = Arc::default();
1484    let registry = if worker_process {
1485        let cfg = ModelBuildCfg {
1486            model_name: embedding.model_name,
1487            base_sessions: sessions.clone(),
1488            state_names: Arc::clone(&state_names),
1489            catalog: Arc::clone(&catalog),
1490            pick: runtime_pick.clone(),
1491            dialect: dialect.clone(),
1492            ctx,
1493            max_batch,
1494            kv_bits,
1495            park,
1496            park_lossy,
1497            park_budget_gb,
1498            tool_lease_ms,
1499            tick_decode_budget,
1500            tick_target_ms,
1501            prefill_budget,
1502            starvation_ticks,
1503            class_lanes,
1504            os_pressure,
1505            pressure_high_pct: if pressure_high > 0 { pressure_high } else { 85 },
1506            pressure_low_pct: if pressure_low > 0 { pressure_low } else { 70 },
1507            pin_budget_pct,
1508            speculate: speculate.clone(),
1509            speculation: speculation.clone(),
1510            completion_deadline_ms,
1511            completion_bucket,
1512            fim_satellite: fim_satellite.clone(),
1513            worker_stderr: worker_stderr.clone(),
1514        };
1515        let reload_cfg = cfg.clone();
1516        let loader: superfluid_daemon::registry::ModelLoader =
1517            Box::new(move |id: &str, runtime| build_loaded_daemon(&cfg, std::path::Path::new(id), runtime));
1518        let registry = superfluid_daemon::registry::ModelRegistry::with_initial(model_name.clone(), Arc::clone(&daemon), loader);
1519        registry.remember_source_on(&model_name, &model_source, Some(runtime.id));
1520        let names = Arc::clone(&catalog);
1521        registry.set_runtime_names(Box::new(move |name: &str| {
1522            names.named(name).map_err(|why| format!("{why} ({})", names.here_described()))
1523        }));
1524        registry.set_reloader(Box::new(move |id: &str, runtime, retired: &Daemon| {
1525            reload_daemon(&reload_cfg, std::path::Path::new(id), runtime, retired)
1526        }));
1527        Arc::new(registry)
1528    } else {
1529        Arc::new(superfluid_daemon::registry::ModelRegistry::single(
1530            model_name.clone(),
1531            Arc::clone(&daemon),
1532        ))
1533    };
1534    {
1535        let (registry, name) = (Arc::downgrade(&registry), model_name.clone());
1536        daemon.on_retired(Box::new(move || {
1537            if let Some(registry) = registry.upgrade() {
1538                let _ = registry.resolve(Some(&name));
1539            }
1540        }));
1541    }
1542    let same = |p: &std::path::Path| p.canonicalize().unwrap_or_else(|_| p.to_path_buf());
1543    let mut taken: std::collections::HashSet<String> = std::collections::HashSet::from([model_name.clone()]);
1544    let mut given: std::collections::HashSet<PathBuf> = models.first().map(|m| same(m)).into_iter().collect();
1545    for extra in models.iter().skip(1) {
1546        if !given.insert(same(extra)) {
1547            eprintln!("superfluid: model '{}' already loaded, skipping", (embedding.model_name)(extra, &Default::default()));
1548            continue;
1549        }
1550        let name = match pulled_names.get(extra) {
1551            Some(name) => name.clone(),
1552            None => {
1553                let name = (embedding.model_name)(extra, &taken);
1554                // The worker names the model again with nothing taken, so a
1555                // name the collision chose is recorded for it to find.
1556                if name != (embedding.model_name)(extra, &Default::default()) {
1557                    eprintln!("superfluid: {} is registered as '{name}' (another model took its stem)", extra.display());
1558                    state_names.lock().expect("state names").insert(extra.clone(), name.clone());
1559                }
1560                name
1561            }
1562        };
1563        taken.insert(name.clone());
1564        match registry.load_as(&name, &extra.to_string_lossy()) {
1565            Ok(true) => eprintln!("superfluid: loaded model '{name}'"),
1566            Ok(false) => eprintln!("superfluid: model '{name}' already loaded, skipping"),
1567            Err(e) => {
1568                #[cfg(feature = "tui")]
1569                if let Some(c) = stderr_capture.as_ref() {
1570                    c.drain(std::time::Duration::from_secs(2));
1571                }
1572                eprintln!("superfluid: could not load '{}': {e}", extra.display());
1573                std::process::exit(1);
1574            }
1575        }
1576    }
1577    if let Some(dir) = &model_dir {
1578        let mut n = 0;
1579        let here = catalog.survey();
1580        match artifacts_under(dir, &here, MODEL_DIR_DEPTH) {
1581            Ok(paths) => {
1582                for path in paths {
1583                    let refused = runtime_pick
1584                        .resolve(&path, &catalog)
1585                        .and_then(|rt| catalog.require(rt))
1586                        .and_then(|rt| refuse_statically(&rt, park_lossy, kv_bits_arg, speculate.as_deref()));
1587                    if let Err(e) = refused {
1588                        eprintln!("superfluid: --model-dir: skipping {}: {e}", path.display());
1589                        continue;
1590                    }
1591                    if !given.insert(same(&path)) {
1592                        continue;
1593                    }
1594                    let name = (embedding.model_name)(&path, &taken);
1595                    if registry.is_loaded(&name) {
1596                        taken.insert(name);
1597                        continue;
1598                    }
1599                    if name != (embedding.model_name)(&path, &Default::default()) {
1600                        eprintln!(
1601                            "superfluid: --model-dir: {} is registered as '{name}' (another artifact took its stem)",
1602                            path.display()
1603                        );
1604                        state_names.lock().expect("state names").insert(path.clone(), name.clone());
1605                    }
1606                    registry.register_known(&name, &path);
1607                    taken.insert(name);
1608                    n += 1;
1609                }
1610            }
1611            Err(e) => {
1612                eprintln!("superfluid: --model-dir {}: {e}", dir.display());
1613                std::process::exit(1);
1614            }
1615        }
1616        eprintln!("superfluid: {n} model(s) known from {} (loaded on first use)", dir.display());
1617    }
1618    if idle_timeout > 0 {
1619        registry.track_idle();
1620        let reg = Arc::clone(&registry);
1621        let max_idle = std::time::Duration::from_secs(idle_timeout);
1622        let tick = std::time::Duration::from_secs((idle_timeout / 4).max(1));
1623        std::thread::spawn(move || loop {
1624            std::thread::sleep(tick);
1625            for name in reg.sweep_idle(max_idle) {
1626                eprintln!("superfluid: unloaded idle model '{name}'");
1627            }
1628        });
1629    }
1630    if files_expiry.is_some() && files_sweep > 0 {
1631        let d = Arc::clone(&daemon);
1632        std::thread::spawn(move || loop {
1633            std::thread::sleep(std::time::Duration::from_secs(files_sweep));
1634            let n = d.files().sweep();
1635            if n > 0 {
1636                eprintln!("superfluid: files sweep removed {n} expired file(s)");
1637            }
1638        });
1639    }
1640    let mut http_thread = None;
1641    if let Some(addr) = http {
1642        let http_listener = listen_or_exit("--http", &addr);
1643        eprintln!("superfluid: openai api on http://{addr}{}", embedding.http.also_served());
1644        if nonstream_keepalive > 0 {
1645            eprintln!(
1646                "superfluid: non-streaming keep-alive on: 200 at admission, then a space every \
1647                 {nonstream_keepalive}s until the JSON body (x-superfluid-keepalive: whitespace)"
1648            );
1649        }
1650        let reg = Arc::clone(&registry);
1651        let serve_cfg = superfluid_daemon::openai::ServeConfig {
1652            api_key: api_key.clone(),
1653            rate_limit_per_minute: rate_limit,
1654            drain_timeout_secs: drain_timeout,
1655            default_max_tokens,
1656            max_context: ctx as u32,
1657            sampling: superfluid_daemon::openai::SamplingOverrides {
1658                temperature: op_temperature,
1659                top_p: op_top_p,
1660                top_k: op_top_k,
1661                min_p: op_min_p,
1662                repeat_penalty: op_repeat_penalty,
1663                spec_max_temperature: op_spec_max_temperature,
1664                fallback: embedding.sampling_fallback,
1665            },
1666            qos: superfluid_daemon::openai::HttpQosPolicy {
1667                default: http_default_qos,
1668                honor_headers: http_qos_header,
1669                allow_batch_invariant: http_allow_batch_invariant,
1670            },
1671            keys: key_policy.clone(),
1672            nonstream_keepalive_secs: nonstream_keepalive,
1673            surface: embedding.http,
1674            model_naming: embedding.model_naming,
1675            identity: embedding.identity.clone(),
1676        };
1677        http_thread = Some(std::thread::spawn(move || {
1678            superfluid_daemon::openai::serve_blocking_config(http_listener, reg, serve_cfg)
1679        }));
1680    }
1681    if let Some(addr) = web {
1682        if !addr.starts_with("127.0.0.1:") && !addr.starts_with("[::1]:") && !addr.starts_with("localhost:") {
1683            eprintln!("superfluid: --web must bind loopback (127.0.0.1/::1)");
1684            std::process::exit(2);
1685        }
1686        let token_path = sessions.join("web-token");
1687        let token = superfluid_daemon::apiweb::mint_token(&token_path).expect("mint web token");
1688        let web_listener = listen_or_exit("--web", &addr);
1689        eprintln!("superfluid: api-web on http://{addr} (token: {})", token_path.display());
1690        let d = Arc::clone(&daemon);
1691        std::thread::spawn(move || {
1692            let _ = superfluid_daemon::apiweb::serve_blocking(web_listener, d, token, web_origins);
1693        });
1694    }
1695    let _otlp_pusher = otlp_metrics.map(|url| {
1696        eprintln!(
1697            "superfluid: pushing metrics to {url}/v1/metrics every {otlp_interval_ms}ms (an EGRESS)"
1698        );
1699        superfluid_daemon::export::MetricsPusher::start(
1700            url,
1701            std::time::Duration::from_millis(otlp_interval_ms),
1702            daemon.sched_stats(),
1703        )
1704    });
1705    #[cfg(feature = "tui")]
1706    if let Some(ring) = tui_ring {
1707        if let Some(listener) = listener {
1708            let serve_daemon = Arc::clone(&daemon);
1709            std::thread::spawn(move || {
1710                let _ = api::serve(listener, serve_daemon);
1711            });
1712        }
1713        let node = superfluid_daemon::tui::NodeInfo {
1714            identity: hostname(),
1715            model: model_name.clone(),
1716            engine: if worker_process { "native (worker)".into() } else { "native".into() },
1717            max_lanes: max_batch,
1718        };
1719        superfluid_daemon::tui::run(daemon, ring, node, stderr_capture.as_ref()).expect("tui");
1720        drop(stderr_capture);
1721        return;
1722    }
1723    let Some(listener) = listener else {
1724        // No session socket: the HTTP API is the server, and the process
1725        // lasts as long as it does.
1726        match http_thread.map(std::thread::JoinHandle::join) {
1727            Some(Ok(Ok(()))) => return,
1728            Some(Ok(Err(e))) => eprintln!("superfluid: the HTTP API stopped: {e}"),
1729            Some(Err(_)) => eprintln!("superfluid: the HTTP API stopped: its thread panicked"),
1730            None => unreachable!("without a session socket --no-http is refused"),
1731        }
1732        std::process::exit(1);
1733    };
1734    api::serve(listener, daemon).expect("serve");
1735}
1736
1737#[cfg(feature = "tui")]
1738fn hostname() -> String {
1739    let mut buf = [0u8; 256];
1740    // SAFETY: `buf` is a valid 256-byte writable buffer and `buf.len()` is its
1741    // exact capacity; gethostname writes at most that many bytes and NUL-
1742    // terminates within it. We only read `buf` after checking rc == 0.
1743    let rc = unsafe { libc::gethostname(buf.as_mut_ptr().cast::<libc::c_char>(), buf.len()) };
1744    if rc == 0 {
1745        let end = buf.iter().position(|&b| b == 0).unwrap_or(buf.len());
1746        String::from_utf8_lossy(&buf[..end]).into_owned()
1747    } else {
1748        "local".into()
1749    }
1750}
1751
1752type StateNames = Arc<std::sync::Mutex<std::collections::HashMap<PathBuf, String>>>;
1753
1754#[derive(Clone)]
1755struct ModelBuildCfg {
1756    model_name: fn(&Path, &std::collections::HashSet<String>) -> String,
1757    base_sessions: std::path::PathBuf,
1758    state_names: StateNames,
1759    catalog: Arc<superfluid_daemon::runtimes::Catalog>,
1760    pick: RuntimePick,
1761    dialect: String,
1762    ctx: i32,
1763    max_batch: u32,
1764    kv_bits: i32,
1765    park: bool,
1766    park_lossy: bool,
1767    park_budget_gb: u64,
1768    tool_lease_ms: u64,
1769    tick_decode_budget: u32,
1770    tick_target_ms: u32,
1771    prefill_budget: u32,
1772    starvation_ticks: u32,
1773    class_lanes: [usize; 4],
1774    os_pressure: bool,
1775    pressure_high_pct: u8,
1776    pressure_low_pct: u8,
1777    pin_budget_pct: u8,
1778    speculate: Option<String>,
1779    speculation: superfluid_daemon::SpeculationOptions,
1780    completion_deadline_ms: u64,
1781    completion_bucket: superfluid_daemon::completion_bucket::BucketConfig,
1782    fim_satellite: Option<(String, Arc<Daemon>)>,
1783    worker_stderr: Option<std::sync::Arc<std::os::fd::OwnedFd>>,
1784}
1785
1786struct FimSatelliteCfg {
1787    model: PathBuf,
1788    runtime: superfluid_daemon::runtimes::Runtime,
1789    sessions: PathBuf,
1790    ctx: i32,
1791    max_batch: u32,
1792    kv_bits: i32,
1793    pressure_high: u8,
1794    pressure_low: u8,
1795    os_pressure: bool,
1796    completion_deadline_ms: u64,
1797    worker_stderr: Option<std::sync::Arc<std::os::fd::OwnedFd>>,
1798}
1799
1800fn build_fim_satellite(cfg: &FimSatelliteCfg) -> Result<Arc<Daemon>, superfluid_daemon::DaemonError> {
1801    use superfluid_daemon::DaemonError;
1802    let tok = open_tokenizer(&cfg.runtime, &cfg.model)
1803        .map_err(|e| DaemonError::Generation(format!("satellite tokenizer load failed: {e}")))?;
1804    let codec = superfluid_daemon::BundleCodec::from_tokenizer(tok);
1805    let host = EngineHost::spawn_process(superfluid_daemon::WorkerSpec {
1806        bin: cfg.runtime.worker.bin.clone(),
1807        args: cfg.runtime.serve_args(&cfg.model, cfg.ctx, cfg.max_batch, cfg.kv_bits),
1808        stderr: cfg.worker_stderr.clone(),
1809    })?;
1810    let daemon = Daemon::with_options(
1811        SessionStore::ephemeral(),
1812        host,
1813        Box::new(codec),
1814        superfluid_daemon::DaemonOptions {
1815            max_lanes: cfg.max_batch as usize,
1816            park_dir: None,
1817            pressure_high_pct: if cfg.pressure_high > 0 { cfg.pressure_high } else { 85 },
1818            pressure_low_pct: if cfg.pressure_low > 0 { cfg.pressure_low } else { 70 },
1819            pressure_source: if cfg.os_pressure {
1820                superfluid_daemon::pressure::PressureConfig::Os
1821            } else {
1822                superfluid_daemon::pressure::PressureConfig::None
1823            },
1824            media_dir: Some(cfg.sessions.join("fim").join("media")),
1825            completion_deadline_ms: cfg.completion_deadline_ms,
1826            trace_scope: superfluid_daemon::otlp::TraceScope::model(
1827                &superfluid_daemon::registry::model_id_for(&cfg.model),
1828            ),
1829            ..Default::default()
1830        },
1831    )?;
1832    Ok(Arc::new(daemon))
1833}
1834
1835fn build_codec_for(
1836    dialect: &str,
1837    runtime: &superfluid_daemon::runtimes::Runtime,
1838    model: &std::path::Path,
1839) -> Result<Box<dyn superfluid_daemon::TextCodec + Send + Sync>, superfluid_daemon::DaemonError> {
1840    use superfluid_daemon::DaemonError;
1841    let tok = open_tokenizer(runtime, model).map_err(DaemonError::Generation)?;
1842    let (codec, _) = codec_for_dialect(dialect, tok).map_err(DaemonError::Generation)?;
1843    Ok(codec)
1844}
1845
1846fn refuse_statically(
1847    runtime: &superfluid_daemon::runtimes::Runtime,
1848    park_lossy: bool,
1849    kv_bits: Option<i32>,
1850    speculate: Option<&str>,
1851) -> Result<(), String> {
1852    runtime.static_capabilities().check_startup_flags(park_lossy, kv_bits, speculate)
1853}
1854
1855fn describe_worker(runtime: &superfluid_daemon::runtimes::Runtime) -> String {
1856    let version = runtime.version.as_deref().map(|v| format!("{v}, ")).unwrap_or_default();
1857    format!("{version}{}: {}", runtime.worker.source.name(), runtime.worker.bin.display())
1858}
1859
1860fn open_tokenizer(
1861    runtime: &superfluid_daemon::runtimes::Runtime,
1862    model: &std::path::Path,
1863) -> Result<Arc<dyn superfluid_engine::Tokenizer>, String> {
1864    use superfluid_engine::artifact::TokenizerSource;
1865    if let Some(why) = not_there(model) {
1866        return Err(why);
1867    }
1868    if let Some(lib) = &runtime.tokenizer {
1869        let tok = superfluid_daemon::dylib_tokenizer::DylibTokenizer::open(lib, model)?;
1870        return Ok(Arc::new(tok));
1871    }
1872    if runtime.info.tokenizer == Some(TokenizerSource::HuggingFace) {
1873        let tok = superfluid_tokenizer_hf::HfTokenizer::load(model)
1874            .map_err(|e| format!("tokenizer load failed for {}: {e}", model.display()))?;
1875        return Ok(Arc::new(tok));
1876    }
1877    superfluid_daemon::linked::tokenizer(runtime.id, model).unwrap_or_else(|| {
1878        Err(format!(
1879            "no tokenizer for {} here: the {} runtime ships none beside its worker, and this superfluid does not link it",
1880            model.display(),
1881            runtime.id
1882        ))
1883    })
1884}
1885
1886/// How deep `--model-dir` looks: a hub cache nests a model three levels
1887/// down (`<org>/<repo>/<variant>/model.base`).
1888const MODEL_DIR_DEPTH: usize = 8;
1889
1890/// The artifacts under `dir` that a runtime here reads, in name order. An
1891/// entry that one reads is taken whole (an MLX model is a directory); a
1892/// directory that none reads is looked into.
1893fn artifacts_under(
1894    dir: &std::path::Path,
1895    here: &[superfluid_daemon::runtimes::Found],
1896    depth: usize,
1897) -> std::io::Result<Vec<PathBuf>> {
1898    let mut paths: Vec<PathBuf> = std::fs::read_dir(dir)?.flatten().map(|e| e.path()).collect();
1899    paths.sort();
1900    let mut found = Vec::new();
1901    for path in paths {
1902        if !superfluid_daemon::runtimes::readers_in(here, &path).is_empty() {
1903            found.push(path);
1904        } else if depth > 0 && path.is_dir() {
1905            found.extend(artifacts_under(&path, here, depth - 1).unwrap_or_default());
1906        }
1907    }
1908    Ok(found)
1909}
1910
1911fn not_there(model: &std::path::Path) -> Option<String> {
1912    (!model.exists()).then(|| format!("{}: no such file or directory", model.display()))
1913}
1914
1915fn codec_for_dialect(
1916    dialect: &str,
1917    tok: Arc<dyn superfluid_engine::Tokenizer>,
1918) -> Result<(Box<dyn superfluid_daemon::TextCodec + Send + Sync>, &'static str), String> {
1919    Ok(match dialect {
1920        "chatml" => (
1921            Box::new(
1922                superfluid_daemon::codec::chatml_codec_from_tokenizer(tok)
1923                    .map_err(|e| format!("--dialect chatml refused: {e}"))?,
1924            ),
1925            "chatml",
1926        ),
1927        "atem" => (
1928            Box::new(
1929                superfluid_daemon::atem::AtemCodec::from_tokenizer(tok)
1930                    .map_err(|_| "--dialect atem refused: the tokenizer lacks the ATEM markers".to_string())?,
1931            ),
1932            "atem",
1933        ),
1934        "raw" => (Box::new(superfluid_daemon::BundleCodec::from_tokenizer(tok)), "raw"),
1935        "template" => (
1936            Box::new(
1937                superfluid_daemon::template_codec::TemplateCodec::from_tokenizer(tok)
1938                    .map_err(|_| "--dialect template refused: the model carries no usable chat template".to_string())?,
1939            ),
1940            "template",
1941        ),
1942        "auto" => superfluid_daemon::codec::auto_codec_from_tokenizer(tok),
1943        other => return Err(format!("unknown dialect '{other}' (chatml|atem|raw|template|auto)")),
1944    })
1945}
1946
1947fn speculation_for<'a>(
1948    directive: Option<&'a str>,
1949    caps: &superfluid_daemon::capabilities::Capabilities,
1950    model: &std::path::Path,
1951    runtime: &str,
1952) -> Option<&'a str> {
1953    let d = directive?;
1954    if d.trim() != "auto" {
1955        return Some(d);
1956    }
1957    match caps.declines_auto_speculation() {
1958        Some(why) => {
1959            eprintln!("superfluid: speculation: auto: {} on the {runtime} runtime verifies no drafts ({why}) — decoding plainly", model.display());
1960            None
1961        }
1962        // The other runtimes draft from the prompt alone: there is no
1963        // drafter artifact for `auto` to look for.
1964        None if runtime != "basert" => {
1965            eprintln!("superfluid: speculation: auto: prompt-lookup on the {runtime} runtime");
1966            Some("prompt-lookup")
1967        }
1968        None => Some(d),
1969    }
1970}
1971
1972fn unsupported_runtime(param: Option<&'static str>) -> impl Fn(String) -> superfluid_daemon::DaemonError {
1973    move |m: String| superfluid_daemon::DaemonError::Unsupported(superfluid_daemon::Refusal::new("unsupported_runtime", param, m))
1974}
1975
1976fn runtime_for(
1977    cfg: &ModelBuildCfg,
1978    model_path: &std::path::Path,
1979    requested: Option<RuntimeId>,
1980) -> Result<superfluid_daemon::runtimes::Runtime, superfluid_daemon::DaemonError> {
1981    let runtime = cfg
1982        .pick
1983        .resolve_with(model_path, requested, &cfg.catalog)
1984        .and_then(|rt| cfg.catalog.require(rt))
1985        .map_err(unsupported_runtime(Some(if requested.is_some() { "runtime" } else { "model" })))?;
1986    refuse_statically(&runtime, cfg.park_lossy, Some(cfg.kv_bits), cfg.speculate.as_deref()).map_err(unsupported_runtime(None))?;
1987    Ok(runtime)
1988}
1989
1990fn engine_on(
1991    cfg: &ModelBuildCfg,
1992    runtime: &superfluid_daemon::runtimes::Runtime,
1993    model_path: &std::path::Path,
1994) -> Result<(Box<dyn superfluid_daemon::TextCodec + Send + Sync>, EngineHost), superfluid_daemon::DaemonError> {
1995    use superfluid_daemon::DaemonError;
1996    let codec = build_codec_for(&cfg.dialect, runtime, model_path)?;
1997    let host = EngineHost::spawn_process(superfluid_daemon::WorkerSpec {
1998        bin: runtime.worker.bin.clone(),
1999        args: runtime.serve_args(model_path, cfg.ctx.max(512), cfg.max_batch, cfg.kv_bits),
2000        stderr: cfg.worker_stderr.clone(),
2001    })
2002    .map_err(|_| DaemonError::Generation("engine worker spawn failed".to_string()))?;
2003    host.capabilities()
2004        .read()
2005        .expect("capability record")
2006        .check_startup_flags(cfg.park_lossy, Some(cfg.kv_bits), cfg.speculate.as_deref())
2007        .map_err(unsupported_runtime(None))?;
2008    Ok((codec, host))
2009}
2010
2011fn reload_daemon(
2012    cfg: &ModelBuildCfg,
2013    model_path: &std::path::Path,
2014    requested: Option<RuntimeId>,
2015    retired: &Daemon,
2016) -> Result<(), superfluid_daemon::DaemonError> {
2017    retired.reload_with(|| {
2018        let runtime = runtime_for(cfg, model_path, requested)?;
2019        let (codec, host) = engine_on(cfg, &runtime, model_path)?;
2020        Ok((host, codec))
2021    })
2022}
2023
2024fn build_loaded_daemon(
2025    cfg: &ModelBuildCfg,
2026    model_path: &std::path::Path,
2027    requested: Option<RuntimeId>,
2028) -> Result<Arc<Daemon>, superfluid_daemon::DaemonError> {
2029    use superfluid_daemon::DaemonError;
2030    let id: String = cfg
2031        .state_names
2032        .lock()
2033        .expect("state names")
2034        .get(model_path)
2035        .cloned()
2036        .unwrap_or_else(|| (cfg.model_name)(model_path, &Default::default()));
2037    let mdir = superfluid_daemon::registry::state_dir(&cfg.base_sessions.join("models"), &id)?;
2038    let runtime = runtime_for(cfg, model_path, requested)?;
2039    settle_park_dir(&mdir.join("park"), cfg.park, cfg.park_budget_gb);
2040    let store = SessionStore::open(&mdir.join("wal.log"))?;
2041    let (codec, host) = engine_on(cfg, &runtime, model_path)?;
2042    let park_dir = cfg.park.then(|| mdir.join("park"));
2043    let caps = host.capabilities().read().expect("capability record").clone();
2044    let mut speculate_ranked = match speculation_for(cfg.speculate.as_deref(), &caps, model_path, runtime.id.name()) {
2045        Some(d) => superfluid_daemon::speculate_resolve::resolve_all(d, model_path).map_err(DaemonError::Generation)?,
2046        None => Vec::new(),
2047    };
2048    let speculate_first = (!speculate_ranked.is_empty()).then(|| speculate_ranked.remove(0));
2049    let daemon = Daemon::with_options(
2050        store,
2051        host,
2052        codec,
2053        superfluid_daemon::DaemonOptions {
2054            max_lanes: cfg.max_batch as usize,
2055            park_dir,
2056            park_lossy: cfg.park_lossy,
2057            park_budget_bytes: cfg.park_budget_gb.saturating_mul(1 << 30),
2058            tool_lease_ms: cfg.tool_lease_ms,
2059            tick_decode_budget: cfg.tick_decode_budget,
2060            tick_target_ms: cfg.tick_target_ms,
2061            prefill_budget: cfg.prefill_budget,
2062            agent_starvation_ticks: cfg.starvation_ticks,
2063            class_lanes: cfg.class_lanes,
2064            pressure_high_pct: cfg.pressure_high_pct,
2065            pressure_low_pct: cfg.pressure_low_pct,
2066            pin_budget_pct: cfg.pin_budget_pct,
2067            pressure_source: if cfg.os_pressure {
2068                superfluid_daemon::pressure::PressureConfig::Os
2069            } else {
2070                superfluid_daemon::pressure::PressureConfig::None
2071            },
2072            speculate: speculate_first,
2073            speculate_auto: cfg.speculate.as_deref().map(str::trim) == Some("auto"),
2074            speculate_fallbacks: speculate_ranked,
2075            speculation: cfg.speculation.clone(),
2076            media_dir: Some(mdir.join("media")),
2077            completion_deadline_ms: cfg.completion_deadline_ms,
2078            trace_scope: superfluid_daemon::otlp::TraceScope::model(&id),
2079            completion_bucket: cfg.completion_bucket,
2080            runtime_id: Some(runtime.id.name()),
2081            ..Default::default()
2082        },
2083    )?;
2084    if let Some((name, sat)) = &cfg.fim_satellite {
2085        daemon.attach_fim_satellite(name.clone(), Arc::clone(sat))?;
2086    }
2087    Ok(Arc::new(daemon))
2088}
2089
2090fn lock_sessions_dir(sessions: &std::path::Path) -> std::fs::File {
2091    use std::os::fd::AsRawFd;
2092    let path = sessions.join("serve.lock");
2093    let file = match std::fs::OpenOptions::new().read(true).write(true).create(true).truncate(false).open(&path) {
2094        Ok(file) => file,
2095        Err(e) => {
2096            eprintln!("superfluid: could not open {}: {e}", path.display());
2097            std::process::exit(1);
2098        }
2099    };
2100    loop {
2101        // SAFETY: `file` is an open descriptor for the duration of the call.
2102        let rc = unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) };
2103        if rc == 0 {
2104            return file;
2105        }
2106        let err = std::io::Error::last_os_error();
2107        match err.kind() {
2108            std::io::ErrorKind::Interrupted => continue,
2109            std::io::ErrorKind::WouldBlock => {
2110                eprintln!(
2111                    "superfluid: another server is already using the sessions directory {}. \
2112                     Stop it, or give this one its own --sessions directory.",
2113                    sessions.display()
2114                );
2115                std::process::exit(1);
2116            }
2117            _ => {
2118                eprintln!("superfluid: could not lock {}: {err}", path.display());
2119                std::process::exit(1);
2120            }
2121        }
2122    }
2123}
2124
2125fn rotate_session_wal(dir: &std::path::Path) {
2126    use superfluid_daemon::store_id::store_id_path;
2127    let wal = dir.join("wal.log");
2128    let prev = dir.join("wal.log.prev");
2129    let keep = std::fs::metadata(&wal).is_ok_and(|m| m.len() > 0);
2130    let aside = |from: &std::path::Path, to: Option<&std::path::Path>| -> bool {
2131        if !from.exists() {
2132            return false;
2133        }
2134        if to.is_some_and(|to| std::fs::rename(from, to).is_ok()) {
2135            return true;
2136        }
2137        if let Err(e) = std::fs::remove_file(from) {
2138            eprintln!(
2139                "superfluid: --sessions-cache could not set aside or remove {} ({e}); \
2140                 remove it, or run without --sessions-cache.",
2141                from.display()
2142            );
2143            std::process::exit(1);
2144        }
2145        false
2146    };
2147    if keep {
2148        let _ = std::fs::remove_file(store_id_path(&prev));
2149    }
2150    if keep && aside(&wal, Some(&prev)) {
2151        aside(&store_id_path(&wal), Some(&store_id_path(&prev)));
2152    } else {
2153        aside(&wal, None);
2154        aside(&store_id_path(&wal), None);
2155    }
2156}
2157#[cfg(test)]
2158mod tests {
2159    use super::*;
2160    use superfluid_daemon::runtimes::{Found, Info};
2161    use superfluid_engine::artifact::Format;
2162
2163    fn reads(id: &'static str, format: Format) -> Found {
2164        let info = Info { aliases: Vec::new(), formats: vec![format], tokenizer: None, named: None };
2165        Found { id: RuntimeId::new(id), worker: None, info: Some(info), usable: Err("not started".into()) }
2166    }
2167
2168    #[test]
2169    fn model_dir_looks_into_a_hub_cache_and_takes_a_directory_model_whole() {
2170        let root = std::env::temp_dir().join(format!("superfluid-model-dir-{}", std::process::id()));
2171        let _ = std::fs::remove_dir_all(&root);
2172        let file = |rel: &str| {
2173            let p = root.join(rel);
2174            std::fs::create_dir_all(p.parent().unwrap()).unwrap();
2175            std::fs::write(&p, b"BASE....").unwrap();
2176            p
2177        };
2178        let flat = file("Flat-Q4.base");
2179        let q4 = file("org/Model/default-q4/model.base");
2180        file("org/Model/default-q4/hub.json");
2181        let q8 = file("org/Model/default-q8/model.base");
2182        file("notes.txt");
2183        file("mlx-model/config.json");
2184        file("mlx-model/weights.safetensors");
2185        file("mlx-model/stray.base");
2186        let here = [
2187            reads("basert", Format::file("base", "a .base bundle", &["base"], None)),
2188            reads("mlx", Format::directory("mlx", "an MLX model", &["config.json"], &["safetensors"])),
2189        ];
2190        let found = artifacts_under(&root, &here, MODEL_DIR_DEPTH).unwrap();
2191        assert_eq!(found, vec![flat, root.join("mlx-model"), q4, q8]);
2192        assert!(artifacts_under(&root, &here, 0).unwrap().len() == 2, "depth 0 reads only the top level");
2193    }
2194}