The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
refactor(cli): extract serve command handling into its own module
Steven Enamakela363cdfecff7
diff --git a/crates/openhuman-core/src/core/cli.rs b/crates/openhuman-core/src/core/cli.rsindex 2dd702a21a..13d6c688cf 100644--- a/crates/openhuman-core/src/core/cli.rs+++ b/crates/openhuman-core/src/core/cli.rs@@ -78,7 +78,7 @@ pub fn run_from_cli_args_with(// Match on the first argument to determine the subcommand.match args[0].as_str() {- "run" | "serve" => run_server_command(&args[1..], host_boot),+ "run" | "serve" => super::cli_serve::run_server_command(&args[1..], host_boot),"mcp" | "mcp-server" => crate::mcp::server::run_stdio_from_cli(&args[1..]),// Keep the historical names as a migration diagnostic now that the// terminal frontend is its own workspace crate and executable.@@ -312,147 +312,6 @@ pub fn load_dotenv_for_cli() -> Result<()> {Ok(())}-/// Handles the `run` subcommand to start the core HTTP/JSON-RPC server.-///-/// This command boots the main application server, including its JSON-RPC-/// endpoint, Socket.IO bridge, and background services (voice, vision, etc.).-///-/// # Arguments-///-/// * `args` - Command-line arguments for the `run` command (e.g., `--port`).-fn run_server_command(- args: &[String],- host_boot: Option<crate::core::server_launcher::HostBoot>,-) -> Result<()> {- let Some((request, verbose)) = parse_serve_args(- args,- std::env::var("OPENHUMAN_MODE").ok().as_deref(),- host_boot,- )?- else {- return Ok(());- };- let log_scope = CliLogDefault::Global;- crate::core::logging::init_for_cli_run(verbose, log_scope);- launch_server(request)-}--/// Parse the `run` / `serve` flags into the [`ServeRequest`] the launcher-/// receives, plus the `--verbose` switch. `None` means `--help` was printed.-///-/// Only flags the operator typed set a request field; everything else stays-/// unset so the launcher's builder (see `ServeRequest::host_boot`) keeps its-/// own value.-fn parse_serve_args(- args: &[String],- env_mode: Option<&str>,- host_boot: Option<crate::core::server_launcher::HostBoot>,-) -> Result<Option<(crate::core::server_launcher::ServeRequest, bool)>> {- let mut port: Option<u16> = None;- let mut host: Option<String> = None;- let mut socketio_enabled = true;- let mut headless_api = false;- let mut mode_flag: Option<String> = None;- let mut saas_config: Option<std::path::PathBuf> = None;- let mut verbose = false;- let mut i = 0usize;-- // Manual argument parsing loop for specific flags.- while i < args.len() {- match args[i].as_str() {- "--port" => {- let raw = args- .get(i + 1)- .ok_or_else(|| anyhow::anyhow!("missing value for --port"))?;- port = Some(- raw.parse::<u16>()- .map_err(|e| anyhow::anyhow!("invalid --port: {e}"))?,- );- i += 2;- }- "--host" => {- host = Some(- args.get(i + 1)- .ok_or_else(|| anyhow::anyhow!("missing value for --host"))?- .clone(),- );- i += 2;- }- "--jsonrpc-only" => {- socketio_enabled = false;- i += 1;- }- "--headless-api" => {- socketio_enabled = false;- headless_api = true;- i += 1;- }- "-v" | "--verbose" => {- verbose = true;- i += 1;- }- "--mode" | "--saas-config" => {- let value = args- .get(i + 1)- .ok_or_else(|| anyhow::anyhow!("missing value for {}", args[i]))?- .clone();- if args[i] == "--mode" {- mode_flag = Some(value);- } else {- saas_config = Some(value.into());- }- i += 2;- }- "-h" | "--help" => {- println!("{}", crate::core::server_launcher::RUN_HELP);- return Ok(None);- }- other => return Err(anyhow::anyhow!("unknown run arg: {other}")),- }- }-- let (mode, saas_config) =- crate::core::server_launcher::resolve_mode(mode_flag.as_deref(), env_mode, saas_config)?;- Ok(Some((- crate::core::server_launcher::ServeRequest {- host,- port,- socketio_enabled,- headless_api,- mode,- saas_config,- host_boot,- },- verbose,- )))-}--/// Start the installed server launcher for `request` on a fresh tokio runtime.-fn launch_server(request: crate::core::server_launcher::ServeRequest) -> Result<()> {- // Initialize the Tokio multi-threaded runtime.- //- // A single agent turn is a very large async state machine (system prompt +- // hundreds of tool specs + the nested provider/tool loop), and delegating- // to a sub-agent runs another full turn one level down. Even with the inner- // sub-agent future boxed (`subagent_host::ops`), that nesting overflows- // tokio's default 2 MiB worker-thread stack and aborts the whole process- // (SIGABRT: "thread 'tokio-rt-worker' has overflowed its stack"), taking- // the JSON-RPC server down mid-request. Give workers a roomier stack.- let rt = tokio::runtime::Builder::new_multi_thread()- .enable_all()- .thread_stack_size(crate::core::runtime::AGENT_WORKER_STACK_BYTES)- .max_blocking_threads(crate::core::runtime::MAX_BLOCKING_THREADS)- .build()?;- let launcher = crate::core::server_launcher::installed_server_launcher().ok_or_else(|| {- anyhow::anyhow!(- "this binary has no JSON-RPC server linked in; the host must call \- openhuman_rpc::server::install_cli_server() before run_core_from_args"- )- })?;- rt.block_on(launcher(request))?;- Ok(())-}-/// Handles the `call` subcommand to invoke a JSON-RPC method directly from the CLI.////// This is used for one-off commands and debugging, bypassing the HTTP transportdiff --git a/crates/openhuman-core/src/core/cli_serve.rs b/crates/openhuman-core/src/core/cli_serve.rsnew file mode 100644index 0000000000..db513360a4--- /dev/null+++ b/crates/openhuman-core/src/core/cli_serve.rs@@ -0,0 +1,152 @@+//! The `run` / `serve` subcommand: flag parsing and the hand-off to the+//! installed server launcher. Split from `cli.rs` to keep that file under its+//! line cap.++use anyhow::Result;++use crate::core::logging::CliLogDefault;++/// Handles the `run` subcommand to start the core HTTP/JSON-RPC server.+///+/// This command boots the main application server, including its JSON-RPC+/// endpoint, Socket.IO bridge, and background services (voice, vision, etc.).+///+/// # Arguments+///+/// * `args` - Command-line arguments for the `run` command (e.g., `--port`).+pub(super) fn run_server_command(+ args: &[String],+ host_boot: Option<crate::core::server_launcher::HostBoot>,+) -> Result<()> {+ let Some((request, verbose)) = parse_serve_args(+ args,+ std::env::var("OPENHUMAN_MODE").ok().as_deref(),+ host_boot,+ )?+ else {+ return Ok(());+ };+ let log_scope = CliLogDefault::Global;+ crate::core::logging::init_for_cli_run(verbose, log_scope);+ launch_server(request)+}++/// Parse the `run` / `serve` flags into the [`ServeRequest`] the launcher+/// receives, plus the `--verbose` switch. `None` means `--help` was printed.+///+/// Only flags the operator typed set a request field; everything else stays+/// unset so the launcher's builder (see `ServeRequest::host_boot`) keeps its+/// own value.+pub(super) fn parse_serve_args(+ args: &[String],+ env_mode: Option<&str>,+ host_boot: Option<crate::core::server_launcher::HostBoot>,+) -> Result<Option<(crate::core::server_launcher::ServeRequest, bool)>> {+ let mut port: Option<u16> = None;+ let mut host: Option<String> = None;+ let mut socketio_enabled = true;+ let mut headless_api = false;+ let mut mode_flag: Option<String> = None;+ let mut saas_config: Option<std::path::PathBuf> = None;+ let mut verbose = false;+ let mut i = 0usize;++ // Manual argument parsing loop for specific flags.+ while i < args.len() {+ match args[i].as_str() {+ "--port" => {+ let raw = args+ .get(i + 1)+ .ok_or_else(|| anyhow::anyhow!("missing value for --port"))?;+ port = Some(+ raw.parse::<u16>()+ .map_err(|e| anyhow::anyhow!("invalid --port: {e}"))?,+ );+ i += 2;+ }+ "--host" => {+ host = Some(+ args.get(i + 1)+ .ok_or_else(|| anyhow::anyhow!("missing value for --host"))?+ .clone(),+ );+ i += 2;+ }+ "--jsonrpc-only" => {+ socketio_enabled = false;+ i += 1;+ }+ "--headless-api" => {+ socketio_enabled = false;+ headless_api = true;+ i += 1;+ }+ "-v" | "--verbose" => {+ verbose = true;+ i += 1;+ }+ "--mode" | "--saas-config" => {+ let value = args+ .get(i + 1)+ .ok_or_else(|| anyhow::anyhow!("missing value for {}", args[i]))?+ .clone();+ if args[i] == "--mode" {+ mode_flag = Some(value);+ } else {+ saas_config = Some(value.into());+ }+ i += 2;+ }+ "-h" | "--help" => {+ println!("{}", crate::core::server_launcher::RUN_HELP);+ return Ok(None);+ }+ other => return Err(anyhow::anyhow!("unknown run arg: {other}")),+ }+ }++ let (mode, saas_config) =+ crate::core::server_launcher::resolve_mode(mode_flag.as_deref(), env_mode, saas_config)?;+ Ok(Some((+ crate::core::server_launcher::ServeRequest {+ host,+ port,+ socketio_enabled,+ headless_api,+ mode,+ saas_config,+ host_boot,+ },+ verbose,+ )))+}++/// Start the installed server launcher for `request` on a fresh tokio runtime.+fn launch_server(request: crate::core::server_launcher::ServeRequest) -> Result<()> {+ // Initialize the Tokio multi-threaded runtime.+ //+ // A single agent turn is a very large async state machine (system prompt ++ // hundreds of tool specs + the nested provider/tool loop), and delegating+ // to a sub-agent runs another full turn one level down. Even with the inner+ // sub-agent future boxed (`subagent_host::ops`), that nesting overflows+ // tokio's default 2 MiB worker-thread stack and aborts the whole process+ // (SIGABRT: "thread 'tokio-rt-worker' has overflowed its stack"), taking+ // the JSON-RPC server down mid-request. Give workers a roomier stack.+ let rt = tokio::runtime::Builder::new_multi_thread()+ .enable_all()+ .thread_stack_size(crate::core::runtime::AGENT_WORKER_STACK_BYTES)+ .max_blocking_threads(crate::core::runtime::MAX_BLOCKING_THREADS)+ .build()?;+ let launcher = crate::core::server_launcher::installed_server_launcher().ok_or_else(|| {+ anyhow::anyhow!(+ "this binary has no JSON-RPC server linked in; the host must call \+ openhuman_rpc::server::install_cli_server() before run_core_from_args"+ )+ })?;+ rt.block_on(launcher(request))?;+ Ok(())+}++#[cfg(test)]+#[path = "cli_serve_tests.rs"]+mod tests;diff --git a/crates/openhuman-core/src/core/cli_serve_tests.rs b/crates/openhuman-core/src/core/cli_serve_tests.rsnew file mode 100644index 0000000000..aba00d24ce--- /dev/null+++ b/crates/openhuman-core/src/core/cli_serve_tests.rs@@ -0,0 +1,75 @@+use super::*;++fn strings(args: &[&str]) -> Vec<String> {+ args.iter().map(|s| s.to_string()).collect()+}++#[test]+fn serve_args_without_flags_leave_every_override_unset() {+ let boot = crate::core::server_launcher::HostBoot::new(1u8);+ let (request, verbose) = parse_serve_args(&[], None, Some(boot.clone()))+ .unwrap()+ .expect("a request");+ assert!(!verbose);+ // Nothing explicit: the host's builder keeps its own listener and services.+ assert_eq!(request.host, None);+ assert_eq!(request.port, None);+ assert!(request.socketio_enabled);+ assert!(!request.headless_api);+ assert_eq!(request.mode, crate::core::runtime::Mode::SingleUser);+ assert_eq!(request.host_boot, Some(boot), "the builder rides along");+}++#[test]+fn serve_args_flags_are_explicit_overrides_on_top_of_the_host_boot() {+ let boot = crate::core::server_launcher::HostBoot::new(1u8);+ let (request, verbose) = parse_serve_args(+ &strings(&[+ "--port",+ "7801",+ "--host",+ "0.0.0.0",+ "--jsonrpc-only",+ "-v",+ ]),+ None,+ Some(boot.clone()),+ )+ .unwrap()+ .unwrap();+ assert!(verbose);+ assert_eq!(request.port, Some(7801));+ assert_eq!(request.host.as_deref(), Some("0.0.0.0"));+ assert!(!request.socketio_enabled);+ assert_eq!(request.host_boot, Some(boot));++ let (headless, _) = parse_serve_args(&strings(&["--headless-api"]), None, None)+ .unwrap()+ .unwrap();+ assert!(headless.headless_api && !headless.socketio_enabled);+ assert!(headless.host_boot.is_none());+}++#[test]+fn serve_args_mode_precedence_is_unchanged_by_the_host_boot() {+ let boot = crate::core::server_launcher::HostBoot::new(1u8);+ // The environment can raise a run to SaaS but a flag cannot lower it.+ let err = parse_serve_args(&[], Some("saas"), Some(boot.clone())).unwrap_err();+ assert!(err.to_string().contains("--saas-config"), "{err}");+ let (request, _) = parse_serve_args(+ &strings(&["--mode", "saas", "--saas-config", "/etc/oh.toml"]),+ None,+ Some(boot),+ )+ .unwrap()+ .unwrap();+ assert_eq!(request.mode, crate::core::runtime::Mode::Saas);+}++#[test]+fn serve_args_reject_unknown_flags_and_print_help_without_a_request() {+ assert!(parse_serve_args(&strings(&["--bogus"]), None, None).is_err());+ assert!(parse_serve_args(&strings(&["--help"]), None, None)+ .unwrap()+ .is_none());+}diff --git a/crates/openhuman-core/src/core/cli_tests.rs b/crates/openhuman-core/src/core/cli_tests.rsindex ae565580dc..e451e4f522 100644--- a/crates/openhuman-core/src/core/cli_tests.rs+++ b/crates/openhuman-core/src/core/cli_tests.rs@@ -1,6 +1,6 @@use super::{grouped_schemas, load_dotenv_for_cli, parse_function_params, parse_input_value,- parse_launch_options, parse_serve_args,+ parse_launch_options,};use crate::config::test_env::EnvVarGuard;use crate::core::{ControllerSchema, FieldSchema, TypeSchema};@@ -336,77 +336,3 @@ fn default_build_leaves_the_generic_namespace_path_unchanged() {"`memory_diff` was removed and must not be listed");}--fn strings(args: &[&str]) -> Vec<String> {- args.iter().map(|s| s.to_string()).collect()-}--#[test]-fn serve_args_without_flags_leave_every_override_unset() {- let boot = crate::core::server_launcher::HostBoot::new(1u8);- let (request, verbose) = parse_serve_args(&[], None, Some(boot.clone()))- .unwrap()- .expect("a request");- assert!(!verbose);- // Nothing explicit: the host's builder keeps its own listener and services.- assert_eq!(request.host, None);- assert_eq!(request.port, None);- assert!(request.socketio_enabled);- assert!(!request.headless_api);- assert_eq!(request.mode, crate::core::runtime::Mode::SingleUser);- assert_eq!(request.host_boot, Some(boot), "the builder rides along");-}--#[test]-fn serve_args_flags_are_explicit_overrides_on_top_of_the_host_boot() {- let boot = crate::core::server_launcher::HostBoot::new(1u8);- let (request, verbose) = parse_serve_args(- &strings(&[- "--port",- "7801",- "--host",- "0.0.0.0",- "--jsonrpc-only",- "-v",- ]),- None,- Some(boot.clone()),- )- .unwrap()- .unwrap();- assert!(verbose);- assert_eq!(request.port, Some(7801));- assert_eq!(request.host.as_deref(), Some("0.0.0.0"));- assert!(!request.socketio_enabled);- assert_eq!(request.host_boot, Some(boot));-- let (headless, _) = parse_serve_args(&strings(&["--headless-api"]), None, None)- .unwrap()- .unwrap();- assert!(headless.headless_api && !headless.socketio_enabled);- assert!(headless.host_boot.is_none());-}--#[test]-fn serve_args_mode_precedence_is_unchanged_by_the_host_boot() {- let boot = crate::core::server_launcher::HostBoot::new(1u8);- // The environment can raise a run to SaaS but a flag cannot lower it.- let err = parse_serve_args(&[], Some("saas"), Some(boot.clone())).unwrap_err();- assert!(err.to_string().contains("--saas-config"), "{err}");- let (request, _) = parse_serve_args(- &strings(&["--mode", "saas", "--saas-config", "/etc/oh.toml"]),- None,- Some(boot),- )- .unwrap()- .unwrap();- assert_eq!(request.mode, crate::core::runtime::Mode::Saas);-}--#[test]-fn serve_args_reject_unknown_flags_and_print_help_without_a_request() {- assert!(parse_serve_args(&strings(&["--bogus"]), None, None).is_err());- assert!(parse_serve_args(&strings(&["--help"]), None, None)- .unwrap()- .is_none());-}diff --git a/crates/openhuman-core/src/core/mod.rs b/crates/openhuman-core/src/core/mod.rsindex 6b8421ed1a..b8503de8c7 100644--- a/crates/openhuman-core/src/core/mod.rs+++ b/crates/openhuman-core/src/core/mod.rs@@ -12,6 +12,7 @@ pub mod auth;pub mod bus;pub mod bus_testing;pub mod cli;+mod cli_serve;pub mod dispatch;pub mod domain_group;pub mod envelope;