Skip to main content

sim_run_core/
lib.rs

1#![forbid(unsafe_code)]
2#![deny(missing_docs)]
3//! Core command entry API for the SIM bootloader.
4//!
5//! # Bootloader frame
6//!
7//! The shipped `sim` binary is a **bootloader frame, not a batteries-included
8//! runtime**. [`run`] builds a [`LoadSession`] whose only registered loader is
9//! the in-process [`LoadSession::add_host_factory`] host loader: with no host
10//! factory and no injected artifact loader it can boot **no codec and no
11//! library**, so `run(["sim", "run"])` fails with `no codec 'lisp' available`.
12//! This is by design: behavior lives in loadable libraries, not baked into the
13//! frame. The default frame loads a codec when an explicit source, cache
14//! artifact, registry resolver, or host factory supplies it.
15//!
16//! A working session therefore comes from one of:
17//!
18//! - an explicitly provided source: `--load path/to/artifact.simlib` (needs an
19//!   artifact loader registered via [`LoadSession::with_loader`]), or
20//! - a seeded cache resolved by the cache-only [`CratesIoResolver`] (it never
21//!   reaches the network unless an explicit registry resolver is installed; the
22//!   cache must otherwise already hold the artifact), or
23//! - a host factory registered through [`LoadSession::with_host_factory`] and
24//!   driven via [`run_with_session`] -- the path every functional test uses.
25//!
26//! The `registry` feature adds a git registry artifact resolver, but it is active
27//! only when the host installs it. Nothing here bakes in a codec.
28
29use std::{ffi::OsString, fmt};
30
31mod args;
32mod boot;
33mod bootloader;
34mod codec_boot;
35mod config;
36mod crates_io;
37mod device_host;
38pub mod device_options;
39mod envelope;
40mod exit;
41#[cfg(feature = "registry")]
42mod git_registry;
43mod handoff;
44mod host;
45mod introspect;
46mod load;
47mod receipt;
48mod report;
49mod source;
50
51#[cfg(test)]
52mod codec_boot_tests;
53#[cfg(test)]
54mod config_report_tests;
55#[cfg(test)]
56mod config_site_tests;
57#[cfg(test)]
58mod config_tests;
59#[cfg(test)]
60mod device_host_tests;
61#[cfg(test)]
62mod handoff_tests;
63#[cfg(test)]
64mod introspect_tests;
65#[cfg(test)]
66mod lib_tests;
67#[cfg(test)]
68mod load_tests;
69#[cfg(test)]
70mod publish_tests;
71#[cfg(test)]
72mod scenario_tests;
73
74pub use args::{CliCommand, parse_args};
75pub use boot::{CliBoot, CliEnvelope, Payload};
76pub use bootloader::Bootloader;
77pub use codec_boot::{DEFAULT_CODEC_NAME, boot_codec_name, codec_lib_symbol};
78pub use config::{
79    ConfigLoadOptions, RuntimeConfigState, load_config_sources, load_config_sources_with_probes,
80    run_config_probe,
81};
82pub use crates_io::{CratesIoResolver, CratesIoSpec, ResolvedCratesIoSource, VersionReq};
83pub use device_host::{
84    AdapterTick, DeviceAdapterLoopPlan, DeviceConsentPolicy, DeviceEdgeSession, DeviceHostSpec,
85    DeviceHostStalePolicy, DevicePlacement, DevicePlacementError, DeviceProfile, DeviceProvider,
86    DeviceProviderKind, DeviceRateClass, DeviceSession, DeviceSite, DeviceSiteLocality,
87    DeviceSurfaceHubJoin, RouteArg, StubProvider, StubSession, compose_device_host,
88    compose_device_host_with_provider, derive_device_rate_class, install_device_bases,
89};
90pub use envelope::cli_envelope_args;
91#[cfg(feature = "registry")]
92pub use git_registry::{GIT_REGISTRY_ENDPOINT_ENV, GitRegistryResolver};
93pub use handoff::{CLI_MAIN_ENTRYPOINT, CliEntrypoint, cli_main_entrypoint_symbol};
94pub use load::LoadSession;
95pub use receipt::{LoadReceipt, LoadReceiptRole};
96pub use report::{
97    ConfigReportKind, ConfigReportRequest, ConfigSourceReport, LoadedLibReport, LoadedStateReport,
98    SourceStatus, format_config_sources, format_config_sources_json, format_config_status,
99    format_config_status_json, format_effective_config, format_effective_config_json,
100    render_config_report,
101};
102pub use source::LibSourceSpec;
103
104const HELP: &str = "\
105Usage: sim [OPTIONS] [PAYLOAD...]
106
107Options:
108  --help              Print this help text.
109  --version           Print the binary version.
110  --codec NAME        Select the boot codec name.
111  --load SRC          Add a library source to load.
112  --native-audio-provider SRC
113                      Try a native audio provider source and degrade if absent.
114  --config-home PATH  Read home config from PATH.
115  --config-work PATH  Read working config from PATH.
116  --config-file PATH  Read one shared config Dir file after root files.
117  --config-site SYMBOL
118                      Read a config Dir from a loaded site export.
119  --no-config-files   Skip filesystem config discovery.
120  --list              Request a loaded-lib list.
121  --inspect SYMBOL    Request inspection of a loaded lib or export.
122  config status       Report loaded libs, config sources, probes, and diagnostics.
123  config effective LIB
124                      Report the effective config table for LIB.
125  config sources      Report config source provenance and diagnostics.
126  --json              Render a config report command as stable JSON.
127  --eval TEXT         Carry eval text for loaded-lib handoff.
128  --script PATH       Carry a script path for loaded-lib handoff.
129  --stdin TEXT        Carry stdin text for loaded-lib handoff.
130
131Note: the bootloader bakes in no codec. By default it fetches nothing over
132the network and boots only libraries provided via --load (an artifact source) or
133already present in the local cache. A build with the registry feature can fetch from
134an explicit git registry endpoint installed by the host. With no source it reports
135`no codec '<name>' available`.
136";
137
138/// Command-line error returned by the bootloader core.
139#[derive(Debug, Clone, PartialEq, Eq)]
140pub struct CliError {
141    message: String,
142}
143
144impl CliError {
145    /// Builds a command-line error from a user-facing message.
146    pub fn new(message: impl Into<String>) -> Self {
147        Self {
148            message: message.into(),
149        }
150    }
151
152    pub(crate) fn unsupported(arg: &str) -> Self {
153        Self::new(format!("unsupported argument: {arg}"))
154    }
155
156    pub(crate) fn missing_value(flag: &str) -> Self {
157        Self::new(format!("{flag} requires a value"))
158    }
159
160    pub(crate) fn duplicate(flag: &str) -> Self {
161        Self::new(format!("{flag} was provided more than once"))
162    }
163}
164
165impl fmt::Display for CliError {
166    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
167        f.write_str(&self.message)
168    }
169}
170
171impl std::error::Error for CliError {}
172
173/// Returns the version line for the `sim-run-core` package.
174///
175/// Product binaries whose package version can differ from the core crate use
176/// [`version_line_for`] through [`run_command_with_session_at_version`].
177pub fn version_line() -> String {
178    version_line_for(env!("CARGO_PKG_VERSION"))
179}
180
181/// Returns the `sim --version` line for the binary-owned `version`.
182pub fn version_line_for(version: &str) -> String {
183    format!("sim {version}\n")
184}
185
186/// Runs the command entry API with process arguments.
187///
188/// This is the one public boot path, expressed through [`Bootloader`]: the default
189/// `sim` runtime is `Bootloader::standard()` (the in-process host loader only), so it
190/// boots no codec or library unless a loadable source is supplied via `--load` or
191/// already cached. A `Boot` command with no available codec returns
192/// `no codec '<name>' available`. To boot a real codec or library in-process, compose
193/// a [`Bootloader`] with [`Bootloader::host_verb`]/[`Bootloader::host_lib`] (or build a
194/// session with [`LoadSession::with_host_factory`]/[`LoadSession::with_loader`] and
195/// call [`run_with_session`]).
196pub fn run<I, S>(args: I) -> Result<i32, CliError>
197where
198    I: IntoIterator<Item = S>,
199    S: Into<OsString>,
200{
201    Bootloader::standard().run(args)
202}
203
204/// Runs the command entry API with an injected loader session.
205pub fn run_with_session<I, S>(args: I, session: &mut LoadSession) -> Result<i32, CliError>
206where
207    I: IntoIterator<Item = S>,
208    S: Into<OsString>,
209{
210    run_command_with_session(parse_args(args)?, session)
211}
212
213/// Runs an already-parsed command with an injected loader session.
214pub fn run_command_with_session(
215    command: CliCommand,
216    session: &mut LoadSession,
217) -> Result<i32, CliError> {
218    run_command_with_session_at_version(command, session, env!("CARGO_PKG_VERSION"))
219}
220
221/// Runs an already-parsed command using the product binary's own `version`.
222///
223/// The version belongs to the executable, not to this reusable core crate. This
224/// entry point keeps `--version` correct when the two packages release on
225/// independent schedules.
226pub fn run_command_with_session_at_version(
227    command: CliCommand,
228    session: &mut LoadSession,
229    version: &str,
230) -> Result<i32, CliError> {
231    match command {
232        CliCommand::Help => {
233            print!("{HELP}");
234            Ok(0)
235        }
236        CliCommand::Version => {
237            print!("{}", version_line_for(version));
238            Ok(0)
239        }
240        CliCommand::Boot(boot) => session.run_loaded_boot(&boot),
241    }
242}