use crate::core::agent_launch_config as config;
use clap::{Args, Subcommand};
#[path = "launch/schemes.rs"]
mod schemes;
#[derive(Args, Clone, Debug)]
pub struct LaunchArgs {
#[command(subcommand)]
command: LaunchCommand,
}
#[derive(Subcommand, Clone, Debug)]
enum LaunchCommand {
Execute,
Reconcile,
Continue,
Recover,
Status {
#[arg(long)]
state_directory: std::path::PathBuf,
},
Runtime {
#[arg(value_enum)]
module: RuntimeModule,
},
Show,
Schemes(schemes::SchemeArgs),
DefaultAgent { agent: String },
Environment,
#[cfg(feature = "herdr")]
#[command(hide = true)]
CoreRequest,
Resolve {
agent: String,
#[arg(long)]
scheme: Option<String>,
},
#[cfg(feature = "herdr")]
Start {
agent: String,
#[arg(long)]
expected_plan: Option<String>,
#[arg(long)]
scheme: Option<String>,
#[arg(long)]
session: String,
#[arg(long)]
pane: String,
#[arg(long)]
name: String,
#[arg(long)]
arguments_json: Option<String>,
#[arg(long, default_value = "[]")]
extra_json: String,
},
Terminal {
agent: String,
#[arg(long)]
expected_plan: Option<String>,
#[arg(long)]
scheme: Option<String>,
#[arg(long)]
cwd: std::path::PathBuf,
#[arg(long)]
prompt_file: Option<std::path::PathBuf>,
#[arg(long)]
arguments_json: Option<String>,
#[arg(long)]
receipt_file: std::path::PathBuf,
},
#[command(hide = true)]
TerminalRun { id: String },
TerminalStatus { id: String },
Save {
#[arg(long)]
file: std::path::PathBuf,
#[arg(long)]
revision: String,
},
}
#[derive(clap::ValueEnum, Clone, Debug)]
enum RuntimeModule {
StateStore,
}
pub fn run(args: LaunchArgs, json: bool) -> anyhow::Result<()> {
match args.command {
LaunchCommand::Schemes(args) => schemes::run(args, json)?,
LaunchCommand::DefaultAgent { agent } => {
super::print_json(&config::set_default_agent(&agent)?, json)
}
command @ (LaunchCommand::Execute
| LaunchCommand::Reconcile
| LaunchCommand::Continue
| LaunchCommand::Recover) => {
use std::io::Read;
let mut bytes = Vec::new();
std::io::stdin()
.take(128 * 1024 + 1)
.read_to_end(&mut bytes)?;
anyhow::ensure!(
bytes.len() <= 128 * 1024,
"Agent execution request exceeds 128 KiB"
);
let mut request: crate::core::agent_execution::ExecutionRequest =
serde_json::from_slice(&bytes)?;
if matches!(command, LaunchCommand::Reconcile) {
request.reconcile_only = true;
request.continuation_prompt.clear();
request.recover_closed = false;
}
if matches!(command, LaunchCommand::Continue | LaunchCommand::Recover) {
request.recover_closed = matches!(command, LaunchCommand::Recover);
request.reconcile_only = true;
anyhow::ensure!(
!request.continuation_prompt.trim().is_empty(),
"Existing-session continuation requires continuation_prompt"
);
}
let result = crate::core::agent_execution::run(&request, |line| {
if json {
eprintln!("{line}");
} else {
println!("{line}");
}
})?;
if json {
super::print_json(&result, true);
}
if result.exit_code != 0 {
std::process::exit(result.exit_code);
}
}
LaunchCommand::Status { state_directory } => super::print_json(
&crate::core::agent_execution::status_at(&state_directory)?,
json,
),
LaunchCommand::Runtime { module } => {
let path = match module {
RuntimeModule::StateStore => crate::core::state_store::python_module()?,
};
super::print_json(&serde_json::json!({"path": path}), json);
}
LaunchCommand::Show => super::print_json(&config::load()?, json),
LaunchCommand::Environment => {
#[cfg(feature = "herdr")]
let herdr_path = crate::core::herdr::tools::HerdrTools::default()
.detect()
.ok()
.flatten()
.map(|installation| installation.path);
#[cfg(not(feature = "herdr"))]
let herdr_path: Option<String> = None;
#[cfg(feature = "herdr")]
let hc_available = crate::core::agent_execution::core_available();
#[cfg(not(feature = "herdr"))]
let hc_available = false;
super::print_json(
&serde_json::json!({ "herdr_path": herdr_path, "hc_available": hc_available }),
json,
);
}
#[cfg(feature = "herdr")]
LaunchCommand::CoreRequest => {
use std::io::Read;
let mut bytes = Vec::new();
std::io::stdin()
.take(256 * 1024 + 1)
.read_to_end(&mut bytes)?;
anyhow::ensure!(
bytes.len() <= 256 * 1024,
"Herdr Core request exceeds 256 KiB"
);
let request = serde_json::from_slice(&bytes)?;
let response = match crate::core::agent_execution::execute_core_request(request) {
Ok(result) => serde_json::json!({"result": result}),
Err(error) => serde_json::json!({"error": {"message": error.to_string()}}),
};
super::print_json(&response, true);
}
LaunchCommand::Resolve { agent, scheme } => {
let launch = config::resolve_scheme(&agent, scheme.as_deref())?;
let fingerprint = config::plan_fingerprint(&launch)?;
let mut value = serde_json::to_value(launch)?;
value["fingerprint"] = serde_json::Value::String(fingerprint);
super::print_json(&value, json);
}
#[cfg(feature = "herdr")]
LaunchCommand::Start {
agent,
expected_plan,
scheme,
session,
pane,
name,
arguments_json,
extra_json,
} => {
anyhow::ensure!(
!session.is_empty()
&& !session.starts_with('-')
&& !pane.starts_with('-')
&& !name.starts_with('-')
&& !name.is_empty(),
"Invalid Herdr target"
);
let mut launch = config::resolve_scheme(&agent, scheme.as_deref())?;
config::verify_plan(&launch, expected_plan.as_deref())?;
if let Some(raw) = arguments_json {
launch.arguments = serde_json::from_str(&raw)?;
}
let extra: Vec<String> = serde_json::from_str(&extra_json)?;
launch.arguments.extend(extra);
anyhow::ensure!(
launch.arguments.len() <= 256
&& launch
.arguments
.iter()
.all(|arg| arg.len() <= 8192 && !arg.chars().any(char::is_control)),
"Invalid Agent arguments"
);
let binary = crate::core::herdr::tools::HerdrTools::default()
.detect()?
.ok_or_else(|| anyhow::anyhow!("Herdr CLI is not installed"))?
.path;
let result = crate::core::herdr::agents::start_configured(
std::path::Path::new(&binary),
&session,
&launch,
&name,
&pane,
)?;
super::print_json(&result, json);
}
LaunchCommand::Terminal {
agent,
expected_plan,
scheme,
cwd,
prompt_file,
arguments_json,
receipt_file,
} => {
use crate::core::agent_launcher::external_terminal;
use std::io::Write;
let mut launch = config::resolve_scheme(&agent, scheme.as_deref())?;
config::verify_plan(&launch, expected_plan.as_deref())?;
if let Some(raw) = arguments_json {
launch.arguments = serde_json::from_str(&raw)?;
}
let prompt = prompt_file.map(std::fs::read_to_string).transpose()?;
let receipt = external_terminal::open(&launch, &cwd, prompt.as_deref(), |receipt| {
let parent = receipt_file
.parent()
.ok_or_else(|| anyhow::anyhow!("Missing receipt directory"))?;
let mut staged = tempfile::NamedTempFile::new_in(parent)?;
serde_json::to_writer(&mut staged, receipt)?;
staged.flush()?;
staged.persist(&receipt_file).map_err(|error| error.error)?;
Ok(())
})?;
super::print_json(&receipt, json);
}
LaunchCommand::TerminalRun { id } => {
let code = crate::core::agent_launcher::external_terminal::run(&id)?;
if code != 0 {
std::process::exit(code);
}
}
LaunchCommand::TerminalStatus { id } => super::print_json(
&crate::core::agent_launcher::external_terminal::status(&id)?,
json,
),
LaunchCommand::Save { file, revision } => {
let raw = std::fs::read(file)?;
anyhow::ensure!(
raw.len() <= 1024 * 1024,
"Agent launch configuration is too large"
);
let document = serde_json::from_slice(&raw)?;
super::print_json(&config::save(document, &revision)?, json)
}
}
Ok(())
}