agent_hub_runtime/core/agent_execution/
mod.rs1use anyhow::{Context, Result};
4use serde::{Deserialize, Serialize};
5use serde_json::Value;
6use std::{
7 io::{BufRead, BufReader, Write},
8 path::{Path, PathBuf},
9 process::{Command, Stdio},
10};
11
12#[derive(Debug, Deserialize, Serialize)]
13pub struct ExecutionRequest {
14 pub config_file: PathBuf,
15 pub prompt_file: PathBuf,
16 pub state_directory: PathBuf,
17 pub identity_directory: PathBuf,
19 pub workdir: PathBuf,
20 #[serde(default)]
21 pub prompt_context: String,
22 #[serde(default)]
24 pub reconcile_only: bool,
25 #[serde(default)]
27 pub continuation_prompt: String,
28 #[serde(default)]
29 pub continuation_id: String,
30 #[serde(default)]
32 pub recover_closed: bool,
33 #[serde(default)]
35 pub recovery_pane: String,
36}
37
38#[derive(Debug, Serialize)]
39pub struct ExecutionResult {
40 pub exit_code: i32,
41 pub checkpoint: Option<Value>,
42}
43
44#[cfg(feature = "herdr")]
45pub use super::herdr::hc::managed::{execute as execute_core_request, Request as CoreRequest};
46
47#[cfg(feature = "herdr")]
48pub fn core_available() -> bool {
49 super::herdr::hc::Core::discover().is_some()
50}
51
52pub fn python_module() -> Result<PathBuf> {
53 super::python_support::publish("agent_execution", include_str!("runtime.py"))
54}
55
56pub fn run(request: &ExecutionRequest, mut output: impl FnMut(&str)) -> Result<ExecutionResult> {
58 anyhow::ensure!(
59 request.continuation_prompt.is_empty()
60 || (request.reconcile_only
61 && !request.continuation_id.is_empty()
62 && request.continuation_id.len() <= 100
63 && request.continuation_prompt.len() <= 64 * 1024),
64 "Continuation requires an existing execution and a unique bounded ID"
65 );
66 anyhow::ensure!(
67 !request.recover_closed
68 || (request.reconcile_only && !request.continuation_prompt.trim().is_empty()),
69 "Closed Agent recovery requires an explicit continuation request"
70 );
71 for path in [
72 &request.config_file,
73 &request.prompt_file,
74 &request.state_directory,
75 &request.identity_directory,
76 &request.workdir,
77 ] {
78 anyhow::ensure!(path.is_absolute(), "Agent execution paths must be absolute");
79 }
80 anyhow::ensure!(request.workdir.is_dir(), "Agent workspace is unavailable");
81 let python = match std::env::var_os("AGENT_HUB_PYTHON") {
82 Some(path) => PathBuf::from(path),
83 None => super::python_support::interpreter()?,
84 };
85 let bridge = super::cli_bridge::validated_path()?;
86 let mut command = Command::new(python);
87 super::python_support::configure_utf8(&mut command);
88 #[cfg(windows)]
89 {
90 use std::os::windows::process::CommandExt;
91 command.creation_flags(0x08000000);
92 }
93 #[cfg(feature = "herdr")]
94 command.env(
95 "AGENT_HUB_HERDR_RUNTIME",
96 super::herdr::agents::execution_module()?,
97 );
98 #[cfg(not(feature = "herdr"))]
99 command.env_remove("AGENT_HUB_HERDR_RUNTIME");
100 #[cfg(feature = "herdr")]
101 command.env(
102 "AGENT_HUB_HC_RUNTIME",
103 super::python_support::publish(
104 "herdr_core_execution",
105 include_str!("../herdr/hc_execution.py"),
106 )?,
107 );
108 #[cfg(not(feature = "herdr"))]
109 command.env_remove("AGENT_HUB_HC_RUNTIME");
110
111 let mut child = command
112 .arg(python_module()?)
113 .current_dir(&request.workdir)
114 .env("AGENT_HUB_CLI", bridge)
115 .env(
116 "AGENT_HUB_STATE_RUNTIME",
117 super::state_store::python_module()?,
118 )
119 .env("PYTHONDONTWRITEBYTECODE", "1")
120 .stdin(Stdio::piped())
121 .stdout(Stdio::piped())
122 .stderr(Stdio::inherit())
123 .spawn()
124 .context("Cannot start the shared Agent executor")?;
125 let write = (|| -> Result<()> {
126 let mut stdin = child
127 .stdin
128 .take()
129 .context("Agent request input is unavailable")?;
130 serde_json::to_writer(&mut stdin, request)?;
131 stdin.flush()?;
132 Ok(())
133 })();
134 if let Err(error) = write {
135 let _ = child.kill();
136 let _ = child.wait();
137 return Err(error);
138 }
139 let stdout = child.stdout.take().context("Agent output is unavailable")?;
140 let read = (|| -> Result<()> {
141 for line in BufReader::new(stdout).lines() {
142 output(&line?);
143 }
144 Ok(())
145 })();
146 let status = child.wait()?;
147 read?;
148 Ok(ExecutionResult {
149 exit_code: status.code().unwrap_or(1),
150 checkpoint: status_at(&request.state_directory)?,
151 })
152}
153
154pub fn status_at(directory: &Path) -> Result<Option<Value>> {
156 super::state_store::read_json(&directory.join(".herdr-run.json"))
157}
158
159#[cfg(test)]
160mod tests;