use super::Core;
use anyhow::{bail, ensure, Context, Result};
use serde::Deserialize;
use serde_json::{json, Value};
use std::path::PathBuf;
#[derive(Deserialize)]
#[serde(tag = "op", rename_all = "snake_case")]
pub enum Request {
Status,
Find {
token: String,
},
Get {
terminal: String,
},
Read {
terminal: String,
},
Start {
cwd: PathBuf,
token: String,
title: String,
agent: String,
scheme: Option<String>,
expected_plan: Option<String>,
arguments: Vec<String>,
prompt: String,
},
Send {
terminal: String,
identity: String,
cwd: PathBuf,
turn: u64,
prompt: String,
},
}
fn check_terminal(terminal: &str) -> Result<()> {
ensure!(
super::local_address(terminal),
"Expected a local Herdr Core terminal"
);
Ok(())
}
fn check_token(token: &str) -> Result<()> {
ensure!(
uuid::Uuid::parse_str(token).is_ok(),
"Invalid managed execution identity"
);
Ok(())
}
pub fn execute(request: Request) -> Result<Value> {
let core = Core::discover().context("Herdr Core (hc) is not installed")?;
match request {
Request::Status => core.call("server.status", json!({})),
Request::Find { token } => {
check_token(&token)?;
core.call(
"terminal.list",
json!({"all": true, "labels": {"agenthub.run": token}}),
)
}
Request::Get { terminal } => {
check_terminal(&terminal)?;
core.call("terminal.get", json!({"terminal": terminal}))
}
Request::Read { terminal } => {
check_terminal(&terminal)?;
core.call("terminal.read", json!({"terminal": terminal, "lines": 0}))
}
Request::Start {
cwd,
token,
title,
agent,
scheme,
expected_plan,
arguments,
prompt,
} => {
check_token(&token)?;
ensure!(
cwd.is_absolute() && cwd.is_dir(),
"Project directory is unavailable"
);
ensure!(!prompt.trim().is_empty(), "Agent task prompt is missing");
ensure!(
arguments.len() <= 256
&& arguments
.iter()
.all(|arg| arg.len() <= 8192 && !arg.chars().any(char::is_control)),
"Invalid Agent arguments"
);
let mut launch =
crate::core::agent_launch_config::resolve_scheme(&agent, scheme.as_deref())?;
crate::core::agent_launch_config::verify_plan(&launch, expected_plan.as_deref())?;
let skip = launch.arguments.len();
ensure!(
arguments.starts_with(&launch.arguments),
"Agent launch plan changed; review before retrying"
);
launch.arguments.extend(arguments.into_iter().skip(skip));
let cwd = cwd.canonicalize()?;
let argv = Core::agent_argv(&cwd, launch, Some(&prompt))?;
let address = core.run(
&cwd,
&argv,
None,
json!({
"agenthub.run": token, "agenthub.checkout": cwd, "where": title
}),
json!({}),
)?;
Ok(json!({"address": address}))
}
Request::Send {
terminal,
identity,
cwd,
turn,
prompt,
} => {
check_terminal(&terminal)?;
ensure!(
!prompt.trim().is_empty() && prompt.len() <= 64 * 1024 && !prompt.contains('\0'),
"Invalid continuation prompt"
);
let row = core.call("terminal.get", json!({"terminal": terminal}))?;
let actual = row["foreground"]["cwd"]
.as_str()
.and_then(|path| std::fs::canonicalize(path).ok());
let expected = cwd.canonicalize()?;
if row["state"] != "live"
|| row["identity"] != identity
|| row["turn"].as_u64() != Some(turn)
|| row["keep"] != false
|| row["reported"] != true
|| !matches!(row["status"]["state"].as_str(), Some("idle" | "done"))
|| row["pid"] != row["foreground"]["pid"]
|| actual.as_ref() != Some(&expected)
{
bail!("Agent identity, working directory or foreground status changed; no continuation was sent");
}
core.call(
"terminal.send",
json!({"terminal": terminal, "if": "idle", "text": prompt, "wait": false}),
)
}
}
}