mod agent;
mod client;
mod config;
mod daemon;
mod identity;
mod ipc;
mod mcp;
mod paths;
mod platform;
mod plugin;
mod skill;
mod store;
use std::io::Read;
use std::path::PathBuf;
use std::time::Duration;
use anyhow::{Context, Result, bail};
use clap::{Parser, Subcommand};
use ipc::{Agent, Request, Tier};
#[derive(Parser)]
#[command(
name = "axiopera",
version,
about = "Dispatch coding agents as sub-agents of each other"
)]
struct Cli {
#[arg(long, global = true)]
json: bool,
#[command(subcommand)]
command: Command,
}
#[derive(Subcommand)]
enum Command {
Models {
agent: Agent,
#[arg(long)]
cwd: Option<PathBuf>,
},
Spawn {
agent: Agent,
task: Vec<String>,
#[arg(short = 'f', long = "file")]
file: Option<PathBuf>,
#[arg(long, value_enum, default_value = "work")]
tier: Tier,
#[arg(long)]
model: Option<String>,
#[arg(long)]
effort: Option<String>,
#[arg(long)]
cwd: Option<PathBuf>,
#[arg(long)]
name: Option<String>,
#[arg(long, value_parser = parse_duration)]
timeout: Option<Duration>,
},
Send {
task: String,
#[arg(long, value_enum)]
tier: Option<Tier>,
message: Vec<String>,
#[arg(short = 'f', long = "file")]
file: Option<PathBuf>,
},
Wait {
tasks: Vec<String>,
#[arg(long, value_parser = parse_duration)]
timeout: Option<Duration>,
},
Inbox {
tasks: Vec<String>,
},
Watch {
#[arg(long)]
caller: Option<String>,
},
Status {
task: Option<String>,
#[arg(long)]
all: bool,
},
Log {
task: String,
#[arg(long, default_value_t = 30)]
tail: usize,
},
Result {
task: String,
#[arg(long)]
turn: Option<u32>,
#[arg(long)]
force: bool,
},
Cancel { task: String },
Ask { question: Vec<String> },
Reply {
id: String,
answer: Vec<String>,
#[arg(short = 'f', long = "file")]
file: Option<PathBuf>,
},
Answers,
Approve { id: String },
Deny {
id: String,
#[arg(long)]
reason: Option<String>,
},
Tell { to: String, message: Vec<String> },
Detach { task: String },
Gc {
#[arg(long, default_value_t = 0)]
days: u64,
},
Guide {
#[arg(long, value_enum)]
host: Option<Agent>,
},
#[command(hide = true)]
Mcp {
#[arg(long)]
codex_hooks: bool,
},
Daemon {
#[command(subcommand)]
command: DaemonCommand,
},
Plugin {
#[command(subcommand)]
command: PluginCommand,
},
Skill {
#[command(subcommand)]
command: SkillCommand,
},
}
#[derive(Subcommand)]
enum SkillCommand {
Install {
#[arg(value_enum)]
host: skill::Host,
#[arg(long)]
force: bool,
},
}
#[derive(Subcommand)]
enum PluginCommand {
Cleanup,
}
#[derive(Subcommand)]
enum DaemonCommand {
Status,
Stop {
#[arg(long)]
force: bool,
},
#[command(hide = true)]
Run {
#[arg(long)]
home: PathBuf,
#[arg(long)]
idle_secs: Option<u64>,
},
}
fn parse_duration(s: &str) -> Result<Duration, String> {
let (num, unit) = s.split_at(s.find(|c: char| !c.is_ascii_digit()).unwrap_or(s.len()));
let n: u64 = num.parse().map_err(|_| format!("bad duration {s:?}"))?;
let secs = match unit {
"" | "s" => n,
"m" => n * 60,
"h" => n * 3600,
_ => return Err(format!("bad duration {s:?}; use e.g. 90s, 10m, 2h")),
};
Ok(Duration::from_secs(secs))
}
fn task_text(words: Vec<String>, file: Option<PathBuf>) -> Result<String> {
let text = match (file, words.as_slice()) {
(Some(f), []) => {
std::fs::read_to_string(&f).with_context(|| format!("reading {}", f.display()))?
}
(None, [dash]) if dash == "-" => {
let mut s = String::new();
std::io::stdin().read_to_string(&mut s)?;
s
}
(None, words) if !words.is_empty() => words.join(" "),
_ => bail!("give the text as arguments, with -f FILE, or as - for stdin"),
};
if text.trim().is_empty() {
bail!("the text is empty");
}
Ok(text)
}
fn main() {
let cli = Cli::parse();
let runtime = tokio::runtime::Builder::new_multi_thread()
.enable_all()
.build()
.expect("tokio runtime");
let code = match runtime.block_on(run(cli)) {
Ok(code) => code,
Err(e) => {
eprintln!("axiopera: {e:#}");
ipc::exit::ERROR
}
};
std::process::exit(code);
}
async fn run(cli: Cli) -> Result<i32> {
let home = paths::default_home();
let mut caller = None;
let request = match cli.command {
Command::Models { agent, cwd } => Request::Models {
agent,
cwd: match cwd {
Some(c) => std::path::absolute(c)?,
None => std::env::current_dir()?,
},
},
Command::Guide { host } => {
print!("{}", guide(host, &client::detect_caller()));
return Ok(0);
}
Command::Plugin {
command: PluginCommand::Cleanup,
} => return plugin::cleanup(&home).await,
Command::Skill {
command: SkillCommand::Install { host, force },
} => return Ok(skill::install(host, force, cli.json)),
Command::Mcp { codex_hooks } => {
return mcp::serve(client::Client { home, json: false }, codex_hooks).await;
}
Command::Daemon {
command: DaemonCommand::Run { home, idle_secs },
} => {
let mut opts = daemon::options(home)?;
if let Some(s) = idle_secs {
opts.idle = Duration::from_secs(s);
}
daemon::run(opts).await?;
return Ok(0);
}
Command::Daemon {
command: DaemonCommand::Status,
} => Request::Ping,
Command::Daemon {
command: DaemonCommand::Stop { force },
} => Request::Stop { force },
Command::Spawn {
agent,
task,
file,
tier,
model,
effort,
cwd,
name,
timeout,
} => {
let cwd = match cwd {
Some(c) => std::path::absolute(c)?,
None => std::env::current_dir()?,
};
Request::Spawn(ipc::Spawn {
agent,
tier,
task: task_text(task, file)?,
cwd,
name,
model,
effort,
timeout_secs: timeout.map(|d| d.as_secs()),
})
}
Command::Send {
task,
tier,
message,
file,
} => Request::Send {
task,
tier,
message: task_text(message, file)?,
},
Command::Wait { tasks, timeout } => Request::Wait {
tasks,
timeout_ms: timeout.map(|d| d.as_millis() as u64),
},
Command::Inbox { tasks } => Request::Inbox { tasks },
Command::Watch { caller: c } => {
caller = c;
Request::Watch
}
Command::Status { task, all } => Request::Status { task, all },
Command::Log { task, tail } => Request::Log { task, tail },
Command::Result { task, turn, force } => Request::Result { task, turn, force },
Command::Cancel { task } => Request::Cancel { task },
Command::Ask { question } => Request::Ask {
text: task_text(question, None)?,
},
Command::Reply { id, answer, file } => Request::Reply {
id,
text: task_text(answer, file)?,
},
Command::Answers => Request::Answers,
Command::Approve { id } => Request::Approve { id },
Command::Deny { id, reason } => Request::Deny { id, reason },
Command::Gc { days } => Request::Gc { days },
Command::Tell { to, message } => Request::Tell {
to,
text: task_text(message, None)?,
},
Command::Detach { task } => Request::Detach { task },
};
client::Client {
home,
json: cli.json,
}
.run(caller, request)
.await
}
fn guide(host: Option<Agent>, caller: &str) -> String {
let mut text = String::new();
let mut labelled = None;
for line in include_str!("guide.md").lines() {
let Some((tag, rest)) = line.strip_prefix('@').and_then(|l| l.split_once(' ')) else {
text.push_str(line);
text.push('\n');
labelled = None;
continue;
};
let (name, label) = match tag {
"claude" => (Agent::Claude, "Claude Code"),
"codex" => (Agent::Codex, "Codex"),
_ => (Agent::Grok, "Grok"),
};
match host {
Some(h) if h == name => text.push_str(" "),
Some(_) => continue,
None => {
if labelled != Some(name) {
text.push_str(&format!(" {label}:\n"));
labelled = Some(name);
}
text.push_str(" ");
}
}
text.push_str(rest);
text.push('\n');
}
if caller.starts_with("grok:") || caller.starts_with("task:") {
text = text.replace("grok:<session>", caller);
}
text
}
#[cfg(test)]
mod tests {
use super::*;
struct TextFile(PathBuf);
impl TextFile {
fn new(contents: &[u8]) -> Self {
let path =
std::env::temp_dir().join(format!("axiopera message {}.md", uuid::Uuid::new_v4()));
std::fs::write(&path, contents).unwrap();
Self(path)
}
}
impl Drop for TextFile {
fn drop(&mut self) {
std::fs::remove_file(&self.0).unwrap();
}
}
#[test]
fn skill_install_arguments() {
for (name, expected) in [
("claude", skill::Host::Claude),
("codex", skill::Host::Codex),
("grok", skill::Host::Grok),
("all", skill::Host::All),
] {
for force in [false, true] {
let mut args = vec!["axiopera", "--json", "skill", "install", name];
if force {
args.push("--force");
}
let cli = Cli::try_parse_from(args).unwrap();
assert!(cli.json);
match cli.command {
Command::Skill {
command:
SkillCommand::Install {
host,
force: actual,
},
} => {
assert_eq!(host, expected);
assert_eq!(actual, force);
}
_ => unreachable!(),
}
}
}
assert!(Cli::try_parse_from(["axiopera", "skill", "install"]).is_err());
assert!(Cli::try_parse_from(["axiopera", "skill", "install", "other"]).is_err());
}
#[test]
fn message_file_options_match_spawn() {
let text = " 审查意见\r\n\"C:\\work dir\\src\\main.rs\"\n'quoted'\n";
let source = TextFile::new(text.as_bytes());
for (command, id) in [("spawn", "codex"), ("send", "task"), ("reply", "question")] {
for option in ["-f", "--file"] {
let cli = Cli::try_parse_from([
"axiopera",
command,
id,
option,
source.0.to_str().unwrap(),
])
.unwrap();
let (words, file) = match cli.command {
Command::Spawn { task, file, .. } => (task, file),
Command::Send {
task,
message,
file,
..
} => {
assert_eq!(task, id);
(message, file)
}
Command::Reply {
id: question,
answer,
file,
} => {
assert_eq!(question, id);
(answer, file)
}
_ => unreachable!(),
};
assert_eq!(file.as_ref(), Some(&source.0));
assert_eq!(task_text(words, file).unwrap(), text);
}
}
}
#[tokio::test]
async fn message_file_errors_precede_daemon_connection() {
for (command, id) in [("spawn", "codex"), ("send", "task"), ("reply", "question")] {
for contents in [b"".as_slice(), b" \r\n\t", b"\xff"] {
let source = TextFile::new(contents);
let cli = Cli::try_parse_from([
"axiopera",
command,
id,
"-f",
source.0.to_str().unwrap(),
])
.unwrap();
let error = run(cli).await.unwrap_err().to_string();
if contents == b"\xff" {
assert_eq!(error, format!("reading {}", source.0.display()));
} else {
assert_eq!(error, "the text is empty");
}
}
let missing = std::env::temp_dir().join(uuid::Uuid::new_v4().to_string());
for words in [vec![], vec!["extra"], vec!["-"]] {
let mut args = vec!["axiopera", command, id, "--file", missing.to_str().unwrap()];
args.extend_from_slice(&words);
let error = run(Cli::try_parse_from(args).unwrap())
.await
.unwrap_err()
.to_string();
let expected = if words.is_empty() {
format!("reading {}", missing.display())
} else {
"give the text as arguments, with -f FILE, or as - for stdin".into()
};
assert_eq!(error, expected);
}
}
}
#[test]
fn the_guide_gives_each_host_its_part() {
let all = guide(None, "user");
assert!(!all.contains('@'));
for label in [" Claude Code:\n ", " Codex:\n ", " Grok:\n "] {
assert_eq!(all.matches(label).count(), 1, "{label}");
}
let claude = guide(Some(Agent::Claude), "claude:s0");
assert!(claude.contains("\n Run `axiopera wait` as a background command"));
assert!(!claude.contains("Codex:") && !claude.contains("watch --caller"));
let grok = guide(Some(Agent::Grok), "grok:s1");
assert!(grok.contains("`axiopera watch --caller grok:s1`"));
assert!(!grok.contains("background command"));
assert!(all.contains("`axiopera watch --caller grok:<session>`"));
let sub_agent = guide(Some(Agent::Grok), "task:t1");
assert!(sub_agent.contains("`axiopera watch --caller task:t1`"));
let native = guide(Some(Agent::Grok), "task:t1/grok:child");
assert!(native.contains("`axiopera watch --caller task:t1/grok:child`"));
}
#[test]
fn durations() {
assert_eq!(parse_duration("90").unwrap(), Duration::from_secs(90));
assert_eq!(parse_duration("10m").unwrap(), Duration::from_secs(600));
assert_eq!(parse_duration("2h").unwrap(), Duration::from_secs(7200));
assert!(parse_duration("5d").is_err());
assert!(parse_duration("m").is_err());
}
}