Skip to main content

robonix_pilot/
config.rs

1// SPDX-License-Identifier: MulanPSL-2.0
2// Author: wheatfox <wheatfox17@icloud.com>
3//
4// Pilot config: how a launched pilot process figures out where atlas is,
5// what address to bind, and how to reach the LLM upstream.
6//
7// Three sources, from lowest to highest priority:
8//   1. compiled defaults (atlas endpoint, listen address, id, …)
9//   2. optional YAML at `$ROBONIX_CONFIG_PATH` or `--config <path>`
10//      (used by `rbnx boot` to write a slice of `system.pilot` from
11//      `robonix_manifest.yaml`)
12//   3. CLI flags / per-field env vars
13//
14// Higher-priority source overrides lower. Manual launch only needs the
15// minimum: an atlas endpoint, a VLM upstream URL, and an API key.
16
17use anyhow::{Context, Result, bail};
18use clap::Parser;
19use robonix_llm_catalog::{
20    ModelSpec, Requirements, api_key_for, catalog_from_env, resolve_from_env,
21};
22use serde::Deserialize;
23use std::path::{Path, PathBuf};
24
25pub const DEFAULT_PILOT_PROVIDER_ID: &str = "pilot";
26pub const PILOT_NAMESPACE: &str = "robonix/system/pilot";
27pub const DEFAULT_ATLAS_ENDPOINT: &str = "127.0.0.1:50051";
28pub const DEFAULT_LISTEN: &str = "127.0.0.1:50071";
29pub const DEFAULT_VLM_FORMAT: &str = "openai";
30
31/// Fully-resolved settings the pilot binary runs against.
32#[derive(Debug, Clone)]
33pub struct PilotConfig {
34    pub atlas_endpoint: String,
35    pub listen: String,
36    pub id: String,
37    pub vlm: VlmConfig,
38}
39
40/// Connection settings used by Pilot's model client.
41#[derive(Debug, Clone)]
42pub struct VlmConfig {
43    pub upstream: String,
44    pub api_key: String,
45    pub model: String,
46    /// Optional OpenAI-compatible reasoning effort sent with each request.
47    pub reasoning_effort: Option<String>,
48    /// Selected catalog id; `None` means an explicit endpoint was configured.
49    pub catalog_id: Option<String>,
50    /// Context limit declared by the deployment. This wins over provider
51    /// metadata and the built-in registry because a proxy may expose a logical
52    /// model name while routing to a smaller physical context window.
53    pub context_window_tokens: Option<usize>,
54    /// Wire dialect. Currently only "openai" is implemented; checked at
55    /// `resolve` time, kept on the struct for diagnostics / future routing.
56    #[allow(dead_code)]
57    pub api_format: String,
58}
59
60impl VlmConfig {
61    /// The upstream URL without credentials or a query, safe to log.
62    pub fn endpoint_for_log(&self) -> String {
63        let url = self.upstream.split(['?', '#']).next().unwrap_or("");
64        let Some((scheme, rest)) = url.split_once("://") else {
65            return url.to_string();
66        };
67        let (authority, path) = rest.split_once('/').map_or((rest, ""), |(a, p)| (a, p));
68        let host = authority
69            .rsplit_once('@')
70            .map_or(authority, |(_, host)| host);
71        if path.is_empty() {
72            format!("{scheme}://{host}")
73        } else {
74            format!("{scheme}://{host}/{path}")
75        }
76    }
77}
78
79/// CLI surface; every field is optional so config-file mode stays usable
80/// without spelling out flags. clap also reads the listed env vars.
81#[derive(Parser, Debug)]
82#[command(name = "robonix-pilot", about = "Robonix Pilot — VLM planner")]
83pub struct Args {
84    /// Atlas control-plane endpoint. Also reads `ROBONIX_ATLAS` (the var rbnx /
85    /// the Python API / liaison use) as an alias; see `env_atlas`.
86    #[arg(long, env = "ROBONIX_ATLAS_ENDPOINT")]
87    pub atlas: Option<String>,
88
89    /// Address pilot's SystemPilot gRPC binds to.
90    #[arg(long, env = "ROBONIX_PILOT_LISTEN")]
91    pub listen: Option<String>,
92
93    /// Override pilot's id (singleton, rarely needed).
94    #[arg(long, env = "ROBONIX_PILOT_PROVIDER_ID")]
95    pub id: Option<String>,
96
97    /// LLM API base URL (e.g. <https://api.openai.com/v1>).
98    #[arg(long, env = "ROBONIX_VLM_UPSTREAM")]
99    pub vlm_upstream: Option<String>,
100
101    /// LLM API key.
102    #[arg(long, env = "ROBONIX_VLM_API_KEY")]
103    pub vlm_api_key: Option<String>,
104
105    /// LLM model identifier.
106    #[arg(long, env = "ROBONIX_VLM_MODEL")]
107    pub vlm_model: Option<String>,
108
109    /// Model reasoning effort (low, medium, high, etc.), when supported.
110    #[arg(long, env = "ROBONIX_VLM_REASONING_EFFORT")]
111    pub vlm_reasoning_effort: Option<String>,
112
113    /// Deployment-specific total context window. Required when Pilot cannot
114    /// obtain a capacity from provider metadata.
115    #[arg(long, env = "ROBONIX_VLM_CONTEXT_WINDOW_TOKENS")]
116    pub vlm_context_window_tokens: Option<usize>,
117
118    /// LLM API dialect ("openai" only for now).
119    #[arg(long, env = "ROBONIX_VLM_FORMAT")]
120    pub vlm_format: Option<String>,
121
122    /// YAML config file (rbnx writes this; CLI/env still override individual fields).
123    #[arg(long, env = "ROBONIX_CONFIG_PATH")]
124    pub config: Option<PathBuf>,
125
126    /// Log level for this component (`debug`/`info`/`warn`/`error`). Sets the
127    /// scribe log-file floor; falls back to `SCRIBE_FILE_LEVEL` / `info`.
128    /// Normally arrives inside `--config-json`, not as a standalone flag.
129    #[arg(long)]
130    pub log: Option<String>,
131
132    /// The component's `system.pilot` manifest block, serialized to JSON by
133    /// rbnx and passed as one arg (`--config-json '{…}'`). Parsed by the
134    /// binary itself — see `robonix_scribe::init_from_config`, which reads the
135    /// `log` key from it so the manifest's per-component level reaches the log.
136    #[arg(long)]
137    pub config_json: Option<String>,
138}
139
140/// Optional YAML schema. Field names match `PilotConfig` (flat) so a
141/// hand-written file looks like the manifest's `system.pilot` block.
142#[derive(Default, Deserialize)]
143struct FileConfig {
144    #[serde(default)]
145    atlas_endpoint: Option<String>,
146    #[serde(default)]
147    listen: Option<String>,
148    #[serde(default)]
149    id: Option<String>,
150    #[serde(default)]
151    vlm: Option<FileVlmConfig>,
152}
153
154#[derive(Default, Deserialize)]
155struct FileVlmConfig {
156    #[serde(default)]
157    upstream: Option<String>,
158    #[serde(default)]
159    api_key: Option<String>,
160    #[serde(default)]
161    model: Option<String>,
162    /// Optional API reasoning effort supplied by the configuration file.
163    #[serde(default)]
164    reasoning_effort: Option<String>,
165    #[serde(default)]
166    api_format: Option<String>,
167    #[serde(default)]
168    context_window_tokens: Option<usize>,
169}
170
171impl PilotConfig {
172    /// Build the resolved config from CLI args (which already pulled env
173    /// vars). Reads optional YAML; CLI/env still override file fields.
174    pub fn resolve(args: Args) -> Result<Self> {
175        let file_cfg: FileConfig = match &args.config {
176            Some(path) => load_yaml(path)?,
177            None => FileConfig::default(),
178        };
179        let file_vlm = file_cfg.vlm.unwrap_or_default();
180
181        let atlas_endpoint = args
182            .atlas
183            .or_else(env_atlas)
184            .or(file_cfg.atlas_endpoint)
185            .unwrap_or_else(|| DEFAULT_ATLAS_ENDPOINT.to_string());
186        let listen = args
187            .listen
188            .or(file_cfg.listen)
189            .unwrap_or_else(|| DEFAULT_LISTEN.to_string());
190        let id = args
191            .id
192            .or(file_cfg.id)
193            .unwrap_or_else(|| DEFAULT_PILOT_PROVIDER_ID.to_string());
194        let api_format = args
195            .vlm_format
196            .or(file_vlm.api_format)
197            .unwrap_or_else(|| DEFAULT_VLM_FORMAT.to_string());
198        if api_format != "openai" {
199            bail!("vlm api_format='{api_format}' not supported (only 'openai')");
200        }
201
202        let explicit_upstream = args
203            .vlm_upstream
204            .or(file_vlm.upstream)
205            .filter(|value| !value.trim().is_empty());
206        let explicit_model = args
207            .vlm_model
208            .or(file_vlm.model)
209            .filter(|value| !value.trim().is_empty());
210        let explicit_key = args
211            .vlm_api_key
212            .or(file_vlm.api_key)
213            .filter(|value| !value.trim().is_empty());
214        let explicit_context = args
215            .vlm_context_window_tokens
216            .or(file_vlm.context_window_tokens)
217            .filter(|tokens| *tokens > 0);
218        let reasoning_effort = args
219            .vlm_reasoning_effort
220            .or(file_vlm.reasoning_effort)
221            .filter(|s| !s.trim().is_empty());
222
223        let vlm = if let Some(upstream) = explicit_upstream {
224            // A complete vlm block is explicit deployment config: use it as-is
225            // and never let a user-level catalog override it.
226            let model = explicit_model
227                .ok_or_else(|| missing_field("vlm.model", "ROBONIX_VLM_MODEL", "--vlm-model"))?;
228            let api_key = explicit_key.ok_or_else(|| {
229                missing_field("vlm.api_key", "ROBONIX_VLM_API_KEY", "--vlm-api-key")
230            })?;
231            VlmConfig {
232                upstream,
233                api_key,
234                model,
235                reasoning_effort,
236                catalog_id: None,
237                context_window_tokens: explicit_context,
238                api_format,
239            }
240        } else {
241            // A model name without an upstream selects a catalog entry: the
242            // caller picks the model, the catalog supplies endpoint and key.
243            // With neither, resolve by requirements.
244            let target = match explicit_model {
245                Some(model_id) => {
246                    let catalog = catalog_from_env()?.ok_or_else(|| {
247                        anyhow::anyhow!(
248                            "vlm.model {model_id:?} names a catalog id, but ROBONIX_LLM_CATALOG is unset"
249                        )
250                    })?;
251                    catalog
252                        .model(&model_id)
253                        .with_context(|| format!("vlm.model {model_id:?} is not a catalog id"))?
254                        .clone()
255                }
256                None => {
257                    // Pilot handles schema refusal at request time, so it does
258                    // not require the json_schema feature here.
259                    let requirements = Requirements::from_env("vision,tools,stream");
260                    resolve_from_env(&requirements)?.ok_or_else(|| {
261                        missing_field("vlm.upstream", "ROBONIX_VLM_UPSTREAM", "--vlm-upstream")
262                    })?
263                }
264            };
265            vlm_from_catalog(
266                &target,
267                explicit_key,
268                explicit_context,
269                reasoning_effort,
270                api_format,
271            )?
272        };
273        Ok(Self {
274            atlas_endpoint,
275            listen,
276            id,
277            vlm,
278        })
279    }
280}
281
282/// Build Pilot's VLM config from a catalog entry. The explicit key, when
283/// present, wins over the catalog's `api_key_env`; a keyless entry needs none.
284fn vlm_from_catalog(
285    target: &ModelSpec,
286    explicit_key: Option<String>,
287    context_override: Option<usize>,
288    reasoning_effort: Option<String>,
289    api_format: String,
290) -> Result<VlmConfig> {
291    if target.protocol != "openai-chat" {
292        bail!(
293            "catalog target {} uses protocol {}; pilot only speaks openai-chat",
294            target.id,
295            target.protocol
296        );
297    }
298    let api_key = explicit_key.unwrap_or_else(|| api_key_for(target));
299    if target.api_key_env.is_some() && api_key.is_empty() {
300        bail!(
301            "missing {} for catalog target {}",
302            target.api_key_env.as_deref().unwrap_or(""),
303            target.id
304        );
305    }
306    let context_window_tokens = context_override.or(target.context.map(|tokens| tokens as usize));
307    Ok(VlmConfig {
308        upstream: target.base_url.clone(),
309        api_key,
310        model: target.model.clone(),
311        reasoning_effort,
312        catalog_id: Some(target.id.clone()),
313        context_window_tokens,
314        api_format,
315    })
316}
317
318/// Read the `ROBONIX_ATLAS` env var as an atlas-endpoint alias.
319///
320/// rbnx, the Python API, and liaison all configure the atlas endpoint via
321/// `ROBONIX_ATLAS`, while executor/pilot historically only honored
322/// `ROBONIX_ATLAS_ENDPOINT` (the clap `env`). Accepting `ROBONIX_ATLAS` here as
323/// well means a single env var configures every component. Without it, setting
324/// only `ROBONIX_ATLAS` left pilot silently falling back to
325/// `DEFAULT_ATLAS_ENDPOINT` (127.0.0.1:50051) — it would then dial the wrong
326/// atlas and log 127.0.0.1 even after the operator "changed" the endpoint.
327/// Empty values are ignored so an exported-but-blank var doesn't shadow later
328/// sources.
329fn env_atlas() -> Option<String> {
330    std::env::var("ROBONIX_ATLAS")
331        .ok()
332        .filter(|v| !v.is_empty())
333}
334
335fn load_yaml(path: &Path) -> Result<FileConfig> {
336    let raw = std::fs::read_to_string(path)
337        .with_context(|| format!("read pilot config '{}'", path.display()))?;
338    serde_yaml::from_str(&raw).with_context(|| format!("parse pilot config '{}'", path.display()))
339}
340
341fn missing_field(yaml_path: &str, env_var: &str, flag: &str) -> anyhow::Error {
342    anyhow::anyhow!(
343        "missing required field '{yaml_path}': set it in --config YAML, env {env_var}, or pass {flag}"
344    )
345}
346
347#[cfg(test)]
348mod tests {
349    use super::*;
350    use std::sync::{Mutex, MutexGuard};
351
352    static ENV_LOCK: Mutex<()> = Mutex::new(());
353
354    struct EnvGuard {
355        _lock: MutexGuard<'static, ()>,
356        path: Option<PathBuf>,
357    }
358
359    impl Drop for EnvGuard {
360        fn drop(&mut self) {
361            unsafe {
362                for name in ["ROBONIX_LLM_CATALOG", "CAT_KEY", "ROBONIX_LLM_FEATURES"] {
363                    std::env::remove_var(name);
364                }
365            }
366            if let Some(path) = &self.path {
367                let _ = std::fs::remove_file(path);
368            }
369        }
370    }
371
372    fn catalog_env(name: &str, body: &str) -> EnvGuard {
373        let lock = ENV_LOCK.lock().expect("env lock");
374        let path = std::env::temp_dir().join(format!(
375            "robonix-pilot-config-{}-{name}.json",
376            std::process::id()
377        ));
378        std::fs::write(&path, body).expect("write catalog");
379        unsafe {
380            std::env::set_var("ROBONIX_LLM_CATALOG", &path);
381            std::env::set_var("CAT_KEY", "secret");
382            std::env::remove_var("ROBONIX_LLM_FEATURES");
383        }
384        EnvGuard {
385            _lock: lock,
386            path: Some(path),
387        }
388    }
389
390    fn base_args() -> Args {
391        Args {
392            atlas: Some("127.0.0.1:1".into()),
393            listen: Some("127.0.0.1:0".into()),
394            id: Some("pilot".into()),
395            vlm_upstream: None,
396            vlm_api_key: None,
397            vlm_model: None,
398            vlm_reasoning_effort: None,
399            vlm_context_window_tokens: None,
400            vlm_format: Some("openai".into()),
401            config: None,
402            log: None,
403            config_json: None,
404        }
405    }
406
407    fn catalog_body(features: &str, key_env: Option<&str>) -> String {
408        let key = key_env
409            .map(|name| format!(r#""api_key_env": "{name}","#))
410            .unwrap_or_default();
411        format!(
412            r#"{{"models":[{{"id":"catalog/model","provider":"test",
413            "base_url":"http://catalog.example/v1","model":"catalog-model",
414            {key}"features":{{{features}}},"context":8192}}]}}"#
415        )
416    }
417
418    #[test]
419    fn explicit_vlm_block_does_not_consult_the_catalog() {
420        let _env = catalog_env(
421            "explicit",
422            r#"{"models":[{"id":"text/model","provider":"test",
423            "base_url":"http://text.example/v1","model":"text",
424            "features":{"tools":true}}]}"#,
425        );
426        let mut args = base_args();
427        args.vlm_upstream = Some("http://explicit.example/v1".into());
428        args.vlm_api_key = Some("explicit-key".into());
429        args.vlm_model = Some("explicit-model".into());
430        args.vlm_context_window_tokens = Some(4096);
431        let config = PilotConfig::resolve(args).expect("explicit config");
432        assert_eq!(config.vlm.upstream, "http://explicit.example/v1");
433        assert_eq!(config.vlm.api_key, "explicit-key");
434        assert_eq!(config.vlm.model, "explicit-model");
435        assert_eq!(config.vlm.context_window_tokens, Some(4096));
436    }
437
438    #[test]
439    fn model_id_selects_a_catalog_entry() {
440        let _env = catalog_env(
441            "model-id",
442            &catalog_body(
443                r#""vision":true,"tools":true,"stream":true"#,
444                Some("CAT_KEY"),
445            ),
446        );
447        let mut args = base_args();
448        args.vlm_model = Some("catalog/model".into());
449        let config = PilotConfig::resolve(args).expect("catalog id");
450        assert_eq!(config.vlm.upstream, "http://catalog.example/v1");
451        assert_eq!(config.vlm.api_key, "secret");
452        assert_eq!(config.vlm.model, "catalog-model");
453        assert_eq!(config.vlm.context_window_tokens, Some(8192));
454    }
455
456    #[test]
457    fn no_vlm_block_resolves_by_requirements() {
458        let _env = catalog_env(
459            "default",
460            &catalog_body(
461                r#""vision":true,"tools":true,"stream":true"#,
462                Some("CAT_KEY"),
463            ),
464        );
465        let config = PilotConfig::resolve(base_args()).expect("catalog default");
466        assert_eq!(config.vlm.model, "catalog-model");
467    }
468
469    #[test]
470    fn partial_explicit_block_is_an_error() {
471        let _env = catalog_env(
472            "partial",
473            &catalog_body(
474                r#""vision":true,"tools":true,"stream":true"#,
475                Some("CAT_KEY"),
476            ),
477        );
478        let mut args = base_args();
479        args.vlm_upstream = Some("http://explicit.example/v1".into());
480        let error = PilotConfig::resolve(args).expect_err("partial vlm");
481        assert!(format!("{error:#}").contains("vlm.model"), "{error:#}");
482    }
483
484    #[test]
485    fn unknown_catalog_id_is_an_error() {
486        let _env = catalog_env(
487            "unknown",
488            &catalog_body(
489                r#""vision":true,"tools":true,"stream":true"#,
490                Some("CAT_KEY"),
491            ),
492        );
493        let mut args = base_args();
494        args.vlm_model = Some("missing/model".into());
495        let error = PilotConfig::resolve(args).expect_err("unknown catalog id");
496        assert!(
497            format!("{error:#}").contains("not a catalog id"),
498            "{error:#}"
499        );
500    }
501
502    #[test]
503    fn keyless_catalog_entry_needs_no_key() {
504        let _env = catalog_env(
505            "keyless",
506            &catalog_body(r#""vision":true,"tools":true,"stream":true"#, None),
507        );
508        let mut args = base_args();
509        args.vlm_model = Some("catalog/model".into());
510        let config = PilotConfig::resolve(args).expect("keyless catalog");
511        assert_eq!(config.vlm.api_key, "");
512    }
513
514    #[test]
515    fn explicit_key_wins_over_catalog_key() {
516        let _env = catalog_env(
517            "explicit-key",
518            &catalog_body(
519                r#""vision":true,"tools":true,"stream":true"#,
520                Some("CAT_KEY"),
521            ),
522        );
523        let mut args = base_args();
524        args.vlm_model = Some("catalog/model".into());
525        args.vlm_api_key = Some("explicit-key".into());
526        let config = PilotConfig::resolve(args).expect("explicit key");
527        assert_eq!(config.vlm.api_key, "explicit-key");
528    }
529}
浙ICP备2023005800号-2 浙公网安备33010902005384号