Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

refactor(subagent_host): extract driver adapter into its own module

Steven Enamakel4753c501520f
diff --git a/crates/openhuman-core/src/agent/subagent_host/lifecycle.rs b/crates/openhuman-core/src/agent/subagent_host/lifecycle.rs
index 7e56ebad66..d37076d816 100644
--- a/crates/openhuman-core/src/agent/subagent_host/lifecycle.rs
+++ b/crates/openhuman-core/src/agent/subagent_host/lifecycle.rs
@@ -925,1021 +925,12 @@ impl OpenHumanSubagentHost {
/// dispatchers reuse the same planner, executor and persistence adapters
/// without routing through `OpenHumanSubagentHost::run` (which would create a
/// second generic driver).
-pub(crate) struct OpenHumanDriverBundle {
- pub(crate) driver:
- Arc<SubagentDriver<crate::agent::tinyagents::host::OpenHumanRunContext, HostRequest>>,
- pub(crate) failures: Arc<Mutex<HashMap<SubagentTaskKey, SubagentRunError>>>,
- pub(crate) host_outcome: Arc<Mutex<HashMap<SubagentTaskKey, SubagentRunOutcome>>>,
- configured_tool_result: Arc<Mutex<HashMap<SubagentTaskKey, tinytools::ToolResult>>>,
- pub(crate) persistence: Arc<OpenHumanPersistence>,
-}
-
-impl OpenHumanDriverBundle {
- pub(crate) fn new(checkpoint_dir: PathBuf) -> Result<Self, SubagentRunError> {
- let failures = Arc::new(Mutex::new(HashMap::new()));
- let host_outcome = Arc::new(Mutex::new(HashMap::new()));
- let configured_tool_result = Arc::new(Mutex::new(HashMap::new()));
- let plans = Arc::new(Mutex::new(HashMap::new()));
- let planner = Arc::new(OpenHumanPlanner {
- plans: Arc::clone(&plans),
- });
- let executor = Arc::new(OpenHumanExecutor {
- plans,
- failures: Arc::clone(&failures),
- host_outcome: Arc::clone(&host_outcome),
- configured_tool_result: Arc::clone(&configured_tool_result),
- });
- let persistence = Arc::new(
- OpenHumanPersistence::new(checkpoint_dir).with_host_outcome(Arc::clone(&host_outcome)),
- );
- let lifecycle_persistence: Arc<
- dyn tinyagents_orchestration::subagent::SubagentPersistence,
- > = persistence.clone();
- let driver = Arc::new(
- SubagentDriver::new(SubagentCapabilities {
- planner: Some(planner),
- executor: Some(executor),
- persistence: Some(lifecycle_persistence),
- })
- .map_err(map_lifecycle_error)?,
- );
- Ok(Self {
- driver,
- failures,
- host_outcome,
- configured_tool_result,
- persistence,
- })
- }
-}
-
-#[derive(Clone)]
-pub(crate) struct HostRequest {
- invocation: HostInvocation,
- pub(crate) options: SubagentRunOptions,
-}
-
-#[derive(Clone)]
-enum HostInvocation {
- Agent(crate::agent_registry::host_definition::AgentDefinition),
- ConfiguredTool {
- agent_id: String,
- tool: Arc<dyn tinytools::Tool>,
- arguments: serde_json::Value,
- },
-}
-
-impl HostRequest {
- fn agent_id(&self) -> &str {
- match &self.invocation {
- HostInvocation::Agent(definition) => &definition.id,
- HostInvocation::ConfiguredTool { agent_id, .. } => agent_id,
- }
- }
-}
-
-struct PreparedHostPlan {
- invocation: HostInvocation,
- options: SubagentRunOptions,
-}
-
-struct OpenHumanPlanner {
- plans: Arc<Mutex<HashMap<SubagentTaskKey, PreparedHostPlan>>>,
-}
-
-/// Appends the new continuation input to the exact durable history supplied by
-/// TinyAgents. Kept separate so the no-drop/no-duplicate resume contract has a
-/// focused regression test independent of provider execution.
-pub(super) fn merged_resume_history(mut history: Vec<Message>, input: String) -> Vec<Message> {
- if !input.is_empty() {
- history.push(Message::user(input));
- }
- history
-}
-
-#[async_trait]
-impl SubagentPlanner<crate::agent::tinyagents::host::OpenHumanRunContext, HostRequest>
- for OpenHumanPlanner
-{
- async fn prepare(
- &self,
- request: SubagentRequest<crate::agent::tinyagents::host::OpenHumanRunContext, HostRequest>,
- ) -> Result<PreparedSubagent<crate::agent::tinyagents::host::OpenHumanRunContext>, SubagentError>
- {
- let request = request.into_parts();
- let task_key = request.task_key.clone();
- let agent_id = request.host_request.agent_id().to_owned();
- let mut options = request.host_request.options;
- let input = request.input;
- // The generic persistence seam supplies the pause *before* host
- // options are prepared. A continuation's new user answer belongs
- // after that durable history, exactly once; never overwrite a
- // caller-provided answer with the loaded checkpoint.
- let planned_input = if let Some(resume) = request.resume {
- let history = merged_resume_history(resume.history, input);
- options.initial_history = Some(
- history
- .iter()
- .filter_map(tinyagents_runtime::transcript::message_to_native_transcript)
- .collect(),
- );
- history
- } else {
- vec![Message::user(input)]
- };
- options.task_id = Some(request.task_key.task_id.clone());
- options.run_context = request.run_context.data.clone();
- self.plans.lock().unwrap_or_else(|p| p.into_inner()).insert(
- task_key,
- PreparedHostPlan {
- invocation: request.host_request.invocation.clone(),
- options,
- },
- );
- // The host leaf resolves the real tool snapshot and policy; an empty
- // declaration here advertises no unresolved authority.
- Ok(PreparedSubagent::new(
- request.task_key.task_id,
- agent_id,
- planned_input,
- ToolSnapshot::default(),
- request.run_context,
- ))
- }
-}
+#[path = "lifecycle/driver_adapter.rs"]
+mod driver_adapter;
-struct OpenHumanExecutor {
- plans: Arc<Mutex<HashMap<SubagentTaskKey, PreparedHostPlan>>>,
- failures: Arc<Mutex<HashMap<SubagentTaskKey, SubagentRunError>>>,
- host_outcome: Arc<Mutex<HashMap<SubagentTaskKey, SubagentRunOutcome>>>,
- configured_tool_result: Arc<Mutex<HashMap<SubagentTaskKey, tinytools::ToolResult>>>,
-}
-
-#[async_trait]
-impl SubagentExecutor<crate::agent::tinyagents::host::OpenHumanRunContext> for OpenHumanExecutor {
- async fn execute(
- &self,
- execution: SubagentExecution<crate::agent::tinyagents::host::OpenHumanRunContext>,
- ) -> Result<SubagentOutcome, SubagentError> {
- let task_key = execution.task_key.clone();
- let PreparedHostPlan {
- invocation,
- mut options,
- } = self
- .plans
- .lock()
- .unwrap_or_else(|p| p.into_inner())
- .remove(&task_key)
- .ok_or_else(|| {
- SubagentError::Execution("OpenHuman subagent plan was consumed".into())
- })?;
- // Both carriers observe one token. The generic driver installs this
- // token on the prepared RunContext; the host graph polls the copy in
- // its explicit OpenHuman carrier.
- options.run_context = execution.prepared.run_context.data.clone();
- options.run_context.cancellation = execution.cancellation.clone();
- options.message_run_queue = execution.prepared.run_context.run_queue.clone();
- let dispatch = options.run_context.dispatch_ctx();
- let origin = options.run_context.origin.clone();
- let input = execution
- .prepared
- .input
- .last()
- .map(Message::text)
- .unwrap_or_default();
- match invocation {
- HostInvocation::Agent(definition) => {
- let run = Box::pin(super::ops::run_subagent_direct(
- &definition,
- &input,
- options.clone(),
- ));
- let result = match dispatch.into_core() {
- Some(core) => {
- crate::core::runtime::CoreContext::scope_with_turn_origin(core, origin, run)
- .await
- }
- None => run.await,
- };
- match result {
- Ok(outcome) => {
- self.host_outcome
- .lock()
- .unwrap_or_else(|p| p.into_inner())
- .insert(task_key, outcome.clone());
- Ok(host_outcome_to_neutral(outcome, &definition, &options))
- }
- Err(error) => {
- self.failures
- .lock()
- .unwrap_or_else(|p| p.into_inner())
- .insert(task_key, error);
- Err(SubagentError::Execution(
- "OpenHuman execution failed".into(),
- ))
- }
- }
- }
- HostInvocation::ConfiguredTool {
- agent_id,
- tool,
- arguments,
- } => {
- let tool_context = tinyagents_harness::tool::ToolExecutionContext::from_run_context(
- &execution.prepared.run_context,
- tinyagents_harness::CallId::new(format!("delegate-{}", task_key.task_id)),
- );
- let cancellation = execution.cancellation.clone();
- let invoke = Box::pin(async move {
- tokio::select! {
- _ = cancellation.cancelled() => (
- Ok(tinytools::ToolResult::error(
- "delegate: cancelled before the configured agent completed"
- )),
- true,
- ),
- result = tool.execute_with_context(
- arguments,
- tinytools::ToolCallOptions::default(),
- Some(&tool_context),
- ) => (result, false),
- }
- });
- let result = match dispatch.into_core() {
- Some(core) => {
- crate::core::runtime::CoreContext::scope_with_turn_origin(
- core, origin, invoke,
- )
- .await
- }
- None => invoke.await,
- };
- match result {
- (Ok(tool_result), cancelled) => {
- let output = tool_result.output();
- let status = if cancelled {
- SubagentRunStatus::Cancelled
- } else if tool_result.is_error {
- SubagentRunStatus::Incomplete {
- reason: "configured delegate reported failure".into(),
- }
- } else {
- SubagentRunStatus::Completed
- };
- self.host_outcome
- .lock()
- .unwrap_or_else(|p| p.into_inner())
- .insert(
- task_key.clone(),
- SubagentRunOutcome {
- task_id: task_key.task_id.clone(),
- agent_id: agent_id.clone(),
- output: output.clone(),
- iterations: 1,
- elapsed: std::time::Duration::ZERO,
- mode: super::SubagentMode::Typed,
- status,
- final_history: Vec::new(),
- usage: SubagentUsage::default(),
- artifact_paths: Vec::new(),
- persistence_disposition: tinyagents_orchestration::subagent::SubagentPersistenceDisposition::TerminalInserted,
- },
- );
- let mut neutral = SubagentOutcome::cancelled(task_key.task_id.clone());
- neutral.output = output;
- neutral
- .extensions
- .insert("agent_id".into(), serde_json::Value::String(agent_id));
- neutral
- .extensions
- .insert("iterations".into(), serde_json::Value::Number(1.into()));
- neutral.status = if cancelled {
- SubagentOutcomeKind::Cancelled
- } else if tool_result.is_error {
- SubagentOutcomeKind::Incomplete(SubagentIncomplete::new(
- "configured delegate reported failure",
- ))
- } else {
- SubagentOutcomeKind::Completed
- };
- self.configured_tool_result
- .lock()
- .unwrap_or_else(|p| p.into_inner())
- .insert(task_key, tool_result);
- Ok(neutral)
- }
- (Err(error), _) => {
- self.failures
- .lock()
- .unwrap_or_else(|p| p.into_inner())
- .insert(task_key, SubagentRunError::Provider(error));
- Err(SubagentError::Execution(
- "configured delegate execution failed".into(),
- ))
- }
- }
- }
- }
- }
-}
-
-/// Durable OpenHuman pause/terminal records scoped by the complete neutral
-/// task key. The key is encoded rather than using a task id as a filename, so
-/// equally named children of separate roots/parents can never resume or close
-/// one another's lifecycle.
-pub(super) struct OpenHumanPersistence {
- checkpoint_dir: std::path::PathBuf,
- host_outcome: Arc<Mutex<HashMap<SubagentTaskKey, SubagentRunOutcome>>>,
-}
-
-#[derive(serde::Serialize, serde::Deserialize)]
-struct TerminalRecord {
- outcome: SubagentOutcome,
- #[serde(default)]
- agent_id: String,
- #[serde(default)]
- elapsed_ms: u64,
-}
-
-#[derive(serde::Deserialize)]
-#[serde(untagged)]
-enum CompatibleTerminalRecord {
- Current(TerminalRecord),
- Legacy(SubagentOutcome),
-}
-
-impl OpenHumanPersistence {
- pub(super) fn new(checkpoint_dir: std::path::PathBuf) -> Self {
- Self {
- checkpoint_dir,
- host_outcome: Arc::new(Mutex::new(HashMap::new())),
- }
- }
-
- fn with_host_outcome(
- mut self,
- host_outcome: Arc<Mutex<HashMap<SubagentTaskKey, SubagentRunOutcome>>>,
- ) -> Self {
- self.host_outcome = host_outcome;
- self
- }
-
- fn key_component(key: &SubagentTaskKey) -> String {
- fn hex(value: &str) -> String {
- value
- .as_bytes()
- .iter()
- .map(|byte| format!("{byte:02x}"))
- .collect()
- }
- let encoded = format!(
- "{}-{}-{}-{}",
- hex(&key.root_run_id),
- hex(&key.parent_run_id),
- hex(key.thread_id.as_deref().unwrap_or("")),
- hex(&key.task_id),
- );
- // A task key normally contains short UUID-like identifiers, for which
- // the reversible encoding preserves existing checkpoint paths. A
- // background child may inherit a rendered parent identifier, however;
- // hex-encoding that value can exceed the filesystem filename limit.
- // Hash only that exceptional form while keeping all key fields in the
- // digest input so distinct lifecycle scopes cannot alias.
- if encoded.len() <= 180 {
- encoded
- } else {
- format!("sha256-{:x}", Sha256::digest(encoded.as_bytes()))
- }
- }
-
- fn pause_path(&self, key: &SubagentTaskKey) -> std::path::PathBuf {
- self.checkpoint_dir
- .join("lifecycle")
- .join(format!("{}.pause.json", Self::key_component(key)))
- }
-
- fn terminal_path(&self, key: &SubagentTaskKey) -> std::path::PathBuf {
- self.checkpoint_dir
- .join("lifecycle")
- .join(format!("{}.terminal.json", Self::key_component(key)))
- }
-
- fn index_path(&self, task_id: &str) -> std::path::PathBuf {
- self.checkpoint_dir
- .join("lifecycle")
- .join(format!("task-{}.index.json", Self::task_component(task_id)))
- }
-
- fn lock_path(&self, key: &SubagentTaskKey) -> std::path::PathBuf {
- self.checkpoint_dir
- .join("lifecycle")
- .join(format!("{}.lock", Self::key_component(key)))
- }
-
- fn index_lock_path(&self, task_id: &str) -> std::path::PathBuf {
- self.checkpoint_dir
- .join("lifecycle")
- .join(format!("task-{}.index.lock", Self::task_component(task_id)))
- }
-
- fn task_component(task_id: &str) -> String {
- let encoded = task_id
- .as_bytes()
- .iter()
- .map(|byte| format!("{byte:02x}"))
- .collect::<String>();
- if encoded.len() <= 180 {
- encoded
- } else {
- format!("sha256-{:x}", Sha256::digest(encoded.as_bytes()))
- }
- }
-
- fn lock_file(path: &std::path::Path) -> Result<std::fs::File, SubagentError> {
- let parent = path.parent().expect("lifecycle lock path has a parent");
- std::fs::create_dir_all(parent)
- .map_err(|error| SubagentError::Persistence(error.to_string()))?;
- let file = OpenOptions::new()
- .create(true)
- .truncate(false)
- .read(true)
- .write(true)
- .open(path)
- .map_err(|error| SubagentError::Persistence(error.to_string()))?;
- file.lock_exclusive()
- .map_err(|error| SubagentError::Persistence(error.to_string()))?;
- Ok(file)
- }
-
- fn key_lock(&self, key: &SubagentTaskKey) -> Result<std::fs::File, SubagentError> {
- Self::lock_file(&self.lock_path(key))
- }
-
- fn index_lock(&self, task_id: &str) -> Result<std::fs::File, SubagentError> {
- Self::lock_file(&self.index_lock_path(task_id))
- }
-
- fn read_index_keys(&self, task_id: &str) -> Result<Vec<SubagentTaskKey>, SubagentError> {
- let raw = match std::fs::read_to_string(self.index_path(task_id)) {
- Ok(raw) => raw,
- Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
- Err(error) => return Err(SubagentError::Persistence(error.to_string())),
- };
- let value: serde_json::Value = serde_json::from_str(&raw)
- .map_err(|error| SubagentError::Persistence(error.to_string()))?;
- // Accept the short-lived single-key format written by the first
- // lifecycle extraction, but immediately write the collision-safe
- // vector format on the next mutation.
- let keys = value
- .get("keys")
- .cloned()
- .map(serde_json::from_value)
- .transpose()
- .map_err(|error| SubagentError::Persistence(error.to_string()))?
- .or_else(|| {
- value
- .get("key")
- .cloned()
- .and_then(|key| serde_json::from_value(key).ok())
- .map(|key| vec![key])
- })
- .unwrap_or_default();
- Ok(keys)
- }
-
- fn write_index_keys(
- &self,
- task_id: &str,
- keys: &[SubagentTaskKey],
- ) -> Result<(), SubagentError> {
- let path = self.index_path(task_id);
- if keys.is_empty() {
- match std::fs::remove_file(path) {
- Ok(()) => return Ok(()),
- Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
- Err(error) => return Err(SubagentError::Persistence(error.to_string())),
- }
- }
- Self::replace_file(
- &path,
- serde_json::to_vec(&serde_json::json!({"keys": keys}))
- .map_err(|error| SubagentError::Persistence(error.to_string()))?,
- )
- }
-
- fn add_index_key(&self, key: &SubagentTaskKey) -> Result<(), SubagentError> {
- let _index_lock = self.index_lock(&key.task_id)?;
- let mut keys = self.read_index_keys(&key.task_id)?;
- if !keys.contains(key) {
- keys.push(key.clone());
- self.write_index_keys(&key.task_id, &keys)?;
- }
- Ok(())
- }
-
- fn remove_index_key(&self, key: &SubagentTaskKey) -> Result<(), SubagentError> {
- let _index_lock = self.index_lock(&key.task_id)?;
- let mut keys = self.read_index_keys(&key.task_id)?;
- keys.retain(|candidate| candidate != key);
- self.write_index_keys(&key.task_id, &keys)
- }
-
- fn replace_file(path: &std::path::Path, bytes: Vec<u8>) -> Result<(), SubagentError> {
- let parent = path.parent().expect("lifecycle state path has a parent");
- std::fs::create_dir_all(parent)
- .map_err(|error| SubagentError::Persistence(error.to_string()))?;
- let temporary = path.with_extension(format!("{}.tmp", uuid::Uuid::new_v4()));
- std::fs::write(&temporary, bytes)
- .map_err(|error| SubagentError::Persistence(error.to_string()))?;
- match std::fs::rename(&temporary, path) {
- Ok(()) => Ok(()),
- Err(error) => {
- let _ = std::fs::remove_file(&temporary);
- Err(SubagentError::Persistence(error.to_string()))
- }
- }
- }
-
- fn insert_file(path: &std::path::Path, bytes: Vec<u8>) -> Result<bool, SubagentError> {
- let parent = path.parent().expect("lifecycle state path has a parent");
- std::fs::create_dir_all(parent)
- .map_err(|error| SubagentError::Persistence(error.to_string()))?;
- let temporary = path.with_extension(format!("{}.tmp", uuid::Uuid::new_v4()));
- std::fs::write(&temporary, bytes)
- .map_err(|error| SubagentError::Persistence(error.to_string()))?;
- match std::fs::hard_link(&temporary, path) {
- Ok(()) => {
- let _ = std::fs::remove_file(&temporary);
- Ok(true)
- }
- Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {
- let _ = std::fs::remove_file(&temporary);
- Ok(false)
- }
- Err(error) => {
- let _ = std::fs::remove_file(&temporary);
- Err(SubagentError::Persistence(error.to_string()))
- }
- }
- }
-
- fn read_pause_checkpoint(
- &self,
- key: &SubagentTaskKey,
- ) -> Result<Option<super::SubagentCheckpointData>, SubagentError> {
- let raw = match std::fs::read_to_string(self.pause_path(key)) {
- Ok(raw) => raw,
- Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
- Err(error) => return Err(SubagentError::Persistence(error.to_string())),
- };
- let checkpoint = serde_json::from_str::<super::SubagentCheckpointData>(&raw)
- .map_err(|error| SubagentError::Persistence(error.to_string()))?;
- if checkpoint.task_key.as_ref() != Some(key) {
- return Err(SubagentError::Persistence("checkpoint key mismatch".into()));
- }
- Ok(Some(checkpoint))
- }
-
- fn read_terminal_record(
- &self,
- key: &SubagentTaskKey,
- ) -> Result<Option<TerminalRecord>, SubagentError> {
- let raw = match std::fs::read_to_string(self.terminal_path(key)) {
- Ok(raw) => raw,
- Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
- Err(error) => return Err(SubagentError::Persistence(error.to_string())),
- };
- match serde_json::from_str(&raw)
- .map_err(|error| SubagentError::Persistence(error.to_string()))?
- {
- CompatibleTerminalRecord::Current(record) => Ok(Some(record)),
- CompatibleTerminalRecord::Legacy(outcome) => Ok(Some(TerminalRecord {
- outcome,
- agent_id: String::new(),
- elapsed_ms: 0,
- })),
- }
- }
-
- fn durable_host_metadata(
- &self,
- key: &SubagentTaskKey,
- ) -> Result<Option<(String, u64)>, SubagentError> {
- let _key_lock = self.key_lock(key)?;
- if let Some(record) = self.read_terminal_record(key)? {
- return Ok(
- (!record.agent_id.is_empty()).then_some((record.agent_id, record.elapsed_ms))
- );
- }
- Ok(self.read_pause_checkpoint(key)?.and_then(|checkpoint| {
- (!checkpoint.agent_id.is_empty())
- .then_some((checkpoint.agent_id, checkpoint.elapsed_ms))
- }))
- }
-
- pub(crate) fn checkpoint_resume(checkpoint: &super::SubagentCheckpointData) -> SubagentResume {
- SubagentResume {
- history: checkpoint
- .history
- .iter()
- .map(crate::agent::message_convert::chat_message_to_message)
- .collect(),
- checkpoint: checkpoint.resume_checkpoint.clone(),
- metadata: checkpoint.resume_metadata.clone(),
- }
- }
-
- fn checkpoint_outcome(checkpoint: super::SubagentCheckpointData) -> SubagentOutcome {
- let resume = Self::checkpoint_resume(&checkpoint);
- SubagentOutcome {
- task_id: checkpoint.task_id,
- output: checkpoint.output,
- history: checkpoint
- .history
- .iter()
- .map(crate::agent::message_convert::chat_message_to_message)
- .collect(),
- status: SubagentOutcomeKind::AwaitingInput(SubagentPause {
- reason: checkpoint.question,
- resume,
- }),
- usage: UsageTotals {
- calls: checkpoint.iterations as u64,
- usage: Usage {
- input_tokens: checkpoint.usage.input_tokens,
- output_tokens: checkpoint.usage.output_tokens,
- total_tokens: checkpoint
- .usage
- .input_tokens
- .saturating_add(checkpoint.usage.output_tokens),
- cache_read_tokens: checkpoint.usage.cached_input_tokens,
- // An unknown cost crosses as no charge at all, never as $0.
- charged_amount: checkpoint
- .usage
- .cost()
- .usd()
- .map(|usd| ChargedAmount::usd_micros((usd * 1_000_000.0).round() as i64)),
- ..Usage::default()
- },
- },
- artifacts: checkpoint
- .artifact_paths
- .into_iter()
- .map(|id| ArtifactReference {
- id,
- ..ArtifactReference::default()
- })
- .collect(),
- ..SubagentOutcome::cancelled(String::new())
- }
- }
-
- fn live_checkpoint(
- &self,
- key: &SubagentTaskKey,
- ) -> Result<Option<super::SubagentCheckpointData>, SubagentError> {
- let _key_lock = self.key_lock(key)?;
- if self.terminal_path(key).exists() {
- return Ok(None);
- }
- self.read_pause_checkpoint(key)
- }
-
- fn checkpoint_for_task(
- &self,
- task_id: &str,
- ) -> Result<super::SubagentCheckpointData, SubagentRunError> {
- if !super::ops::is_safe_task_id(task_id) {
- return Err(SubagentRunError::Provider(anyhow::anyhow!(
- "unsafe task id"
- )));
- }
- let keys = {
- let _index_lock = self.index_lock(task_id).map_err(map_lifecycle_error)?;
- self.read_index_keys(task_id).map_err(map_lifecycle_error)?
- };
- let mut live = Vec::new();
- for key in keys {
- if let Some(checkpoint) = self.live_checkpoint(&key).map_err(map_lifecycle_error)? {
- live.push(checkpoint);
- }
- }
- match live.len() {
- 1 => Ok(live.remove(0)),
- 0 => Err(SubagentRunError::Provider(anyhow::anyhow!(
- "no live subagent pause checkpoint for task id"
- ))),
- _ => Err(SubagentRunError::Provider(anyhow::anyhow!(
- "ambiguous subagent task id; select a scoped lifecycle key"
- ))),
- }
- }
-
- pub(crate) fn recover_key(
- checkpoint_dir: &std::path::Path,
- task_id: &str,
- ) -> Result<SubagentTaskKey, SubagentRunError> {
- let persistence = Self::new(checkpoint_dir.to_path_buf());
- let checkpoint = persistence.checkpoint_for_task(task_id)?;
- checkpoint.task_key.ok_or_else(|| {
- SubagentRunError::Provider(anyhow::anyhow!("checkpoint omitted original task key"))
- })
- }
-}
-
-#[async_trait]
-impl tinyagents_orchestration::subagent::SubagentPersistence for OpenHumanPersistence {
- async fn load_terminal(
- &self,
- key: &SubagentTaskKey,
- ) -> Result<Option<SubagentOutcome>, SubagentError> {
- let _key_lock = self.key_lock(key)?;
- Ok(self.read_terminal_record(key)?.map(|record| record.outcome))
- }
- async fn load(&self, key: &SubagentTaskKey) -> Result<Option<SubagentResume>, SubagentError> {
- let _key_lock = self.key_lock(key)?;
- if self.terminal_path(key).exists() {
- return Ok(None);
- }
- Ok(self
- .read_pause_checkpoint(key)?
- .as_ref()
- .map(Self::checkpoint_resume))
- }
-
- async fn load_pause(
- &self,
- key: &SubagentTaskKey,
- ) -> Result<Option<SubagentOutcome>, SubagentError> {
- let _key_lock = self.key_lock(key)?;
- if self.terminal_path(key).exists() {
- return Ok(None);
- }
- Ok(self
- .read_pause_checkpoint(key)?
- .map(Self::checkpoint_outcome))
- }
-
- async fn save_pause(
- &self,
- pause: tinyagents_orchestration::subagent::PersistedSubagentPause,
- ) -> Result<SubagentPausePersistenceDisposition, SubagentError> {
- let _key_lock = self.key_lock(&pause.key)?;
- if self.terminal_path(&pause.key).exists() {
- return Ok(SubagentPausePersistenceDisposition::TerminalExisting);
- }
- let paused = match &pause.outcome.status {
- SubagentOutcomeKind::AwaitingInput(paused) => paused,
- _ => {
- return Err(SubagentError::Persistence(
- "attempted to persist a non-paused subagent outcome as a pause".into(),
- ));
- }
- };
- let metadata = &paused.resume.metadata;
- let optional_metadata = |name: &str| {
- metadata
- .get(name)
- .filter(|value| !value.is_empty())
- .cloned()
- };
- let checkpoint = super::SubagentCheckpointData {
- task_key: Some(pause.key.clone()),
- task_id: pause.key.task_id.clone(),
- agent_id: optional_metadata("agent_id").unwrap_or_default(),
- worker_thread_id: optional_metadata("worker_thread_id"),
- history: pause
- .outcome
- .history
- .iter()
- .filter_map(tinyagents_runtime::transcript::message_to_native_transcript)
- .collect(),
- question: paused.reason.clone(),
- options: None,
- skill_filter_override: optional_metadata("skill_filter_override"),
- model_override: optional_metadata("model_override"),
- created_at: chrono::Utc::now().to_rfc3339(),
- resume_checkpoint: paused.resume.checkpoint.clone(),
- resume_metadata: metadata.clone(),
- output: pause.outcome.output.clone(),
- iterations: pause.outcome.usage.calls as usize,
- usage: SubagentUsage {
- input_tokens: pause.outcome.usage.usage.input_tokens,
- output_tokens: pause.outcome.usage.usage.output_tokens,
- cached_input_tokens: pause.outcome.usage.usage.cache_read_tokens,
- charged_amount_usd: pause
- .outcome
- .usage
- .usage
- .charged_amount
- .map(|amount| amount.micros as f64 / 1_000_000.0)
- .unwrap_or_default(),
- cost_source: cost_source_of(pause.outcome.usage.usage.charged_amount.as_ref()),
- },
- artifact_paths: pause
- .outcome
- .artifacts
- .iter()
- .map(|artifact| artifact.id.clone())
- .collect(),
- elapsed_ms: self
- .host_outcome
- .lock()
- .unwrap_or_else(|poisoned| poisoned.into_inner())
- .get(&pause.key)
- .map(|outcome| outcome.elapsed.as_millis() as u64)
- .unwrap_or_default(),
- };
- let json = serde_json::to_vec_pretty(&checkpoint)
- .map_err(|error| SubagentError::Persistence(error.to_string()))?;
- let path = self.pause_path(&pause.key);
- let existing = self.read_pause_checkpoint(&pause.key)?;
- match (pause.replaces.as_ref(), existing) {
- (None, None) => {
- // Index first: a failed data write can leave a stale index,
- // which readers filter by the live pause record. A successful
- // pause can never be unresumable through a missing index.
- self.add_index_key(&pause.key)?;
- if Self::insert_file(&path, json)? {
- Ok(SubagentPausePersistenceDisposition::Inserted)
- } else {
- Ok(SubagentPausePersistenceDisposition::Existing)
- }
- }
- (Some(expected), Some(current)) if Self::checkpoint_resume(&current) == *expected => {
- self.add_index_key(&pause.key)?;
- Self::replace_file(&path, json)?;
- Ok(SubagentPausePersistenceDisposition::Replaced)
- }
- _ => Ok(SubagentPausePersistenceDisposition::Existing),
- }
- }
-
- async fn record_terminal(
- &self,
- key: &SubagentTaskKey,
- outcome: &SubagentOutcome,
- replaces: Option<&SubagentResume>,
- ) -> Result<SubagentTerminalPersistenceDisposition, SubagentError> {
- let _key_lock = self.key_lock(key)?;
- if self.terminal_path(key).exists() {
- return Ok(SubagentTerminalPersistenceDisposition::Existing);
- }
- if let Some(current) = self.read_pause_checkpoint(key)? {
- let can_consume_pause =
- replaces.is_some_and(|expected| Self::checkpoint_resume(&current) == *expected);
- if !can_consume_pause {
- return Ok(SubagentTerminalPersistenceDisposition::PauseExisting);
- }
- } else if replaces.is_some() {
- return Err(SubagentError::Persistence(
- "terminal continuation lost its expected durable pause".into(),
- ));
- }
- let path = self.terminal_path(key);
- let host = self
- .host_outcome
- .lock()
- .unwrap_or_else(|poisoned| poisoned.into_inner())
- .get(key)
- .cloned();
- let record = serde_json::to_vec(&TerminalRecord {
- outcome: outcome.clone(),
- agent_id: host
- .as_ref()
- .map(|outcome| outcome.agent_id.clone())
- .unwrap_or_default(),
- elapsed_ms: host
- .as_ref()
- .map(|outcome| outcome.elapsed.as_millis() as u64)
- .unwrap_or_default(),
- })
- .map_err(|error| SubagentError::Persistence(error.to_string()))?;
- match Self::insert_file(&path, record)? {
- true => {
- // Terminal is the durable winner. Retiring a matching pause
- // afterwards cannot reopen the lifecycle because `load` first
- // observes this terminal marker.
- let _ = std::fs::remove_file(self.pause_path(key));
- // A stale task-id index is harmless because recovery filters
- // terminal keys. Never turn a durable terminal success into an
- // error merely because cleanup of a derived index failed.
- if let Err(error) = self.remove_index_key(key) {
- tracing::warn!(task_id = %key.task_id, error = %error, "[subagent] terminal committed but task-id index cleanup failed");
- }
- Ok(SubagentTerminalPersistenceDisposition::Inserted)
- }
- false => Ok(SubagentTerminalPersistenceDisposition::Existing),
- }
- }
-}
-
-#[path = "lifecycle_outcome.rs"]
-mod outcome;
-use outcome::{HostInFlightMap, host_outcome_to_neutral};
-
-fn outcome_to_host(
- result: SubagentRunResult,
- host: Option<SubagentRunOutcome>,
- persistence: &OpenHumanPersistence,
- task_key: &SubagentTaskKey,
- fallback_agent_id: &str,
-) -> SubagentRunOutcome {
- let persistence_disposition = result.disposition;
- let outcome = result.outcome;
- // A driver that lost a pause/terminal CAS may have a perfectly valid local
- // execution result, but it is not the authoritative lifecycle outcome.
- // Reconstruct the durable winner instead of leaking the loser’s output,
- // usage, or artifacts to an observer.
- let host = if persistence_disposition.should_emit_host_effects() {
- host
- } else {
- None
- };
- let durable_metadata = if host.is_none() {
- persistence.durable_host_metadata(task_key).ok().flatten()
- } else {
- None
- };
- let mut host = host.unwrap_or_else(|| SubagentRunOutcome {
- task_id: outcome.task_id.clone(),
- agent_id: durable_metadata
- .as_ref()
- .map(|(agent_id, _)| agent_id.clone())
- .unwrap_or_else(|| fallback_agent_id.to_owned()),
- output: outcome.output.clone(),
- iterations: outcome.usage.calls as usize,
- elapsed: std::time::Duration::from_millis(
- durable_metadata
- .map(|(_, elapsed_ms)| elapsed_ms)
- .unwrap_or_default(),
- ),
- mode: super::SubagentMode::Typed,
- status: SubagentRunStatus::Completed,
- final_history: outcome
- .history
- .iter()
- .filter_map(tinyagents_runtime::transcript::message_to_native_transcript)
- .collect(),
- usage: SubagentUsage {
- input_tokens: outcome.usage.usage.input_tokens,
- output_tokens: outcome.usage.usage.output_tokens,
- cached_input_tokens: outcome.usage.usage.cache_read_tokens,
- charged_amount_usd: outcome
- .usage
- .usage
- .charged_amount
- .map(|amount| amount.micros as f64 / 1_000_000.0)
- .unwrap_or_default(),
- cost_source: cost_source_of(outcome.usage.usage.charged_amount.as_ref()),
- },
- artifact_paths: outcome
- .artifacts
- .iter()
- .map(|artifact| artifact.id.clone())
- .collect(),
- persistence_disposition,
- });
- let is_awaiting_input = matches!(outcome.status, SubagentOutcomeKind::AwaitingInput(_));
- let status = match outcome.status {
- SubagentOutcomeKind::Completed => SubagentRunStatus::Completed,
- SubagentOutcomeKind::AwaitingInput(pause) => SubagentRunStatus::AwaitingUser {
- question: pause.reason,
- options: None,
- checkpoint: None,
- },
- SubagentOutcomeKind::Incomplete(incomplete) => SubagentRunStatus::Incomplete {
- reason: incomplete.reason,
- },
- SubagentOutcomeKind::Cancelled => SubagentRunStatus::Cancelled,
- };
- host.status = status;
- host.persistence_disposition = persistence_disposition;
- if is_awaiting_input {
- host.status = SubagentRunStatus::AwaitingUser {
- question: match host.status {
- SubagentRunStatus::AwaitingUser { ref question, .. } => question.clone(),
- _ => String::new(),
- },
- options: None,
- checkpoint: Some(persistence.pause_path(task_key)),
- };
- }
- host
-}
-
-fn map_lifecycle_error(error: SubagentError) -> SubagentRunError {
- SubagentRunError::Provider(anyhow::anyhow!(error.to_string()))
-}
-/// A child run's cost as it comes back across the orchestration boundary.
-/// That `Usage` can only say whether a charge is present, so a present one is
-/// read as charged and an absent one as unknown (it was sent as absent).
-fn cost_source_of(charged: Option<&ChargedAmount>) -> tinyagents_harness::cost::CostSource {
- match charged {
- Some(_) => tinyagents_harness::cost::CostSource::Charged,
- None => tinyagents_harness::cost::CostSource::Unknown,
- }
-}
-
-#[path = "lifecycle_checkpoint.rs"]
-mod checkpoint;
+pub(super) use driver_adapter::{
+ HostRequest, OpenHumanDriverBundle, OpenHumanPersistence, checkpoint_resume,
+ decode_driver_job_result, load_subagent_checkpoint, merged_resume_history,
+ outcome_to_host,
+};
+use driver_adapter::map_lifecycle_error;
diff --git a/crates/openhuman-core/src/agent/subagent_host/lifecycle/driver_adapter.rs b/crates/openhuman-core/src/agent/subagent_host/lifecycle/driver_adapter.rs
new file mode 100644
index 0000000000..64affe2b83
--- /dev/null
+++ b/crates/openhuman-core/src/agent/subagent_host/lifecycle/driver_adapter.rs
@@ -0,0 +1,1020 @@
+use super::*;
+
+pub(crate) struct OpenHumanDriverBundle {
+ pub(crate) driver:
+ Arc<SubagentDriver<crate::agent::tinyagents::host::OpenHumanRunContext, HostRequest>>,
+ pub(crate) failures: Arc<Mutex<HashMap<SubagentTaskKey, SubagentRunError>>>,
+ pub(crate) host_outcome: Arc<Mutex<HashMap<SubagentTaskKey, SubagentRunOutcome>>>,
+ configured_tool_result: Arc<Mutex<HashMap<SubagentTaskKey, tinytools::ToolResult>>>,
+ pub(crate) persistence: Arc<OpenHumanPersistence>,
+}
+
+impl OpenHumanDriverBundle {
+ pub(crate) fn new(checkpoint_dir: PathBuf) -> Result<Self, SubagentRunError> {
+ let failures = Arc::new(Mutex::new(HashMap::new()));
+ let host_outcome = Arc::new(Mutex::new(HashMap::new()));
+ let configured_tool_result = Arc::new(Mutex::new(HashMap::new()));
+ let plans = Arc::new(Mutex::new(HashMap::new()));
+ let planner = Arc::new(OpenHumanPlanner {
+ plans: Arc::clone(&plans),
+ });
+ let executor = Arc::new(OpenHumanExecutor {
+ plans,
+ failures: Arc::clone(&failures),
+ host_outcome: Arc::clone(&host_outcome),
+ configured_tool_result: Arc::clone(&configured_tool_result),
+ });
+ let persistence = Arc::new(
+ OpenHumanPersistence::new(checkpoint_dir).with_host_outcome(Arc::clone(&host_outcome)),
+ );
+ let lifecycle_persistence: Arc<
+ dyn tinyagents_orchestration::subagent::SubagentPersistence,
+ > = persistence.clone();
+ let driver = Arc::new(
+ SubagentDriver::new(SubagentCapabilities {
+ planner: Some(planner),
+ executor: Some(executor),
+ persistence: Some(lifecycle_persistence),
+ })
+ .map_err(map_lifecycle_error)?,
+ );
+ Ok(Self {
+ driver,
+ failures,
+ host_outcome,
+ configured_tool_result,
+ persistence,
+ })
+ }
+}
+
+#[derive(Clone)]
+pub(crate) struct HostRequest {
+ invocation: HostInvocation,
+ pub(crate) options: SubagentRunOptions,
+}
+
+#[derive(Clone)]
+enum HostInvocation {
+ Agent(crate::agent_registry::host_definition::AgentDefinition),
+ ConfiguredTool {
+ agent_id: String,
+ tool: Arc<dyn tinytools::Tool>,
+ arguments: serde_json::Value,
+ },
+}
+
+impl HostRequest {
+ fn agent_id(&self) -> &str {
+ match &self.invocation {
+ HostInvocation::Agent(definition) => &definition.id,
+ HostInvocation::ConfiguredTool { agent_id, .. } => agent_id,
+ }
+ }
+}
+
+struct PreparedHostPlan {
+ invocation: HostInvocation,
+ options: SubagentRunOptions,
+}
+
+struct OpenHumanPlanner {
+ plans: Arc<Mutex<HashMap<SubagentTaskKey, PreparedHostPlan>>>,
+}
+
+/// Appends the new continuation input to the exact durable history supplied by
+/// TinyAgents. Kept separate so the no-drop/no-duplicate resume contract has a
+/// focused regression test independent of provider execution.
+pub(super) fn merged_resume_history(mut history: Vec<Message>, input: String) -> Vec<Message> {
+ if !input.is_empty() {
+ history.push(Message::user(input));
+ }
+ history
+}
+
+#[async_trait]
+impl SubagentPlanner<crate::agent::tinyagents::host::OpenHumanRunContext, HostRequest>
+ for OpenHumanPlanner
+{
+ async fn prepare(
+ &self,
+ request: SubagentRequest<crate::agent::tinyagents::host::OpenHumanRunContext, HostRequest>,
+ ) -> Result<PreparedSubagent<crate::agent::tinyagents::host::OpenHumanRunContext>, SubagentError>
+ {
+ let request = request.into_parts();
+ let task_key = request.task_key.clone();
+ let agent_id = request.host_request.agent_id().to_owned();
+ let mut options = request.host_request.options;
+ let input = request.input;
+ // The generic persistence seam supplies the pause *before* host
+ // options are prepared. A continuation's new user answer belongs
+ // after that durable history, exactly once; never overwrite a
+ // caller-provided answer with the loaded checkpoint.
+ let planned_input = if let Some(resume) = request.resume {
+ let history = merged_resume_history(resume.history, input);
+ options.initial_history = Some(
+ history
+ .iter()
+ .filter_map(tinyagents_runtime::transcript::message_to_native_transcript)
+ .collect(),
+ );
+ history
+ } else {
+ vec![Message::user(input)]
+ };
+ options.task_id = Some(request.task_key.task_id.clone());
+ options.run_context = request.run_context.data.clone();
+ self.plans.lock().unwrap_or_else(|p| p.into_inner()).insert(
+ task_key,
+ PreparedHostPlan {
+ invocation: request.host_request.invocation.clone(),
+ options,
+ },
+ );
+ // The host leaf resolves the real tool snapshot and policy; an empty
+ // declaration here advertises no unresolved authority.
+ Ok(PreparedSubagent::new(
+ request.task_key.task_id,
+ agent_id,
+ planned_input,
+ ToolSnapshot::default(),
+ request.run_context,
+ ))
+ }
+}
+
+struct OpenHumanExecutor {
+ plans: Arc<Mutex<HashMap<SubagentTaskKey, PreparedHostPlan>>>,
+ failures: Arc<Mutex<HashMap<SubagentTaskKey, SubagentRunError>>>,
+ host_outcome: Arc<Mutex<HashMap<SubagentTaskKey, SubagentRunOutcome>>>,
+ configured_tool_result: Arc<Mutex<HashMap<SubagentTaskKey, tinytools::ToolResult>>>,
+}
+
+#[async_trait]
+impl SubagentExecutor<crate::agent::tinyagents::host::OpenHumanRunContext> for OpenHumanExecutor {
+ async fn execute(
+ &self,
+ execution: SubagentExecution<crate::agent::tinyagents::host::OpenHumanRunContext>,
+ ) -> Result<SubagentOutcome, SubagentError> {
+ let task_key = execution.task_key.clone();
+ let PreparedHostPlan {
+ invocation,
+ mut options,
+ } = self
+ .plans
+ .lock()
+ .unwrap_or_else(|p| p.into_inner())
+ .remove(&task_key)
+ .ok_or_else(|| {
+ SubagentError::Execution("OpenHuman subagent plan was consumed".into())
+ })?;
+ // Both carriers observe one token. The generic driver installs this
+ // token on the prepared RunContext; the host graph polls the copy in
+ // its explicit OpenHuman carrier.
+ options.run_context = execution.prepared.run_context.data.clone();
+ options.run_context.cancellation = execution.cancellation.clone();
+ options.message_run_queue = execution.prepared.run_context.run_queue.clone();
+ let dispatch = options.run_context.dispatch_ctx();
+ let origin = options.run_context.origin.clone();
+ let input = execution
+ .prepared
+ .input
+ .last()
+ .map(Message::text)
+ .unwrap_or_default();
+ match invocation {
+ HostInvocation::Agent(definition) => {
+ let run = Box::pin(super::ops::run_subagent_direct(
+ &definition,
+ &input,
+ options.clone(),
+ ));
+ let result = match dispatch.into_core() {
+ Some(core) => {
+ crate::core::runtime::CoreContext::scope_with_turn_origin(core, origin, run)
+ .await
+ }
+ None => run.await,
+ };
+ match result {
+ Ok(outcome) => {
+ self.host_outcome
+ .lock()
+ .unwrap_or_else(|p| p.into_inner())
+ .insert(task_key, outcome.clone());
+ Ok(host_outcome_to_neutral(outcome, &definition, &options))
+ }
+ Err(error) => {
+ self.failures
+ .lock()
+ .unwrap_or_else(|p| p.into_inner())
+ .insert(task_key, error);
+ Err(SubagentError::Execution(
+ "OpenHuman execution failed".into(),
+ ))
+ }
+ }
+ }
+ HostInvocation::ConfiguredTool {
+ agent_id,
+ tool,
+ arguments,
+ } => {
+ let tool_context = tinyagents_harness::tool::ToolExecutionContext::from_run_context(
+ &execution.prepared.run_context,
+ tinyagents_harness::CallId::new(format!("delegate-{}", task_key.task_id)),
+ );
+ let cancellation = execution.cancellation.clone();
+ let invoke = Box::pin(async move {
+ tokio::select! {
+ _ = cancellation.cancelled() => (
+ Ok(tinytools::ToolResult::error(
+ "delegate: cancelled before the configured agent completed"
+ )),
+ true,
+ ),
+ result = tool.execute_with_context(
+ arguments,
+ tinytools::ToolCallOptions::default(),
+ Some(&tool_context),
+ ) => (result, false),
+ }
+ });
+ let result = match dispatch.into_core() {
+ Some(core) => {
+ crate::core::runtime::CoreContext::scope_with_turn_origin(
+ core, origin, invoke,
+ )
+ .await
+ }
+ None => invoke.await,
+ };
+ match result {
+ (Ok(tool_result), cancelled) => {
+ let output = tool_result.output();
+ let status = if cancelled {
+ SubagentRunStatus::Cancelled
+ } else if tool_result.is_error {
+ SubagentRunStatus::Incomplete {
+ reason: "configured delegate reported failure".into(),
+ }
+ } else {
+ SubagentRunStatus::Completed
+ };
+ self.host_outcome
+ .lock()
+ .unwrap_or_else(|p| p.into_inner())
+ .insert(
+ task_key.clone(),
+ SubagentRunOutcome {
+ task_id: task_key.task_id.clone(),
+ agent_id: agent_id.clone(),
+ output: output.clone(),
+ iterations: 1,
+ elapsed: std::time::Duration::ZERO,
+ mode: super::SubagentMode::Typed,
+ status,
+ final_history: Vec::new(),
+ usage: SubagentUsage::default(),
+ artifact_paths: Vec::new(),
+ persistence_disposition: tinyagents_orchestration::subagent::SubagentPersistenceDisposition::TerminalInserted,
+ },
+ );
+ let mut neutral = SubagentOutcome::cancelled(task_key.task_id.clone());
+ neutral.output = output;
+ neutral
+ .extensions
+ .insert("agent_id".into(), serde_json::Value::String(agent_id));
+ neutral
+ .extensions
+ .insert("iterations".into(), serde_json::Value::Number(1.into()));
+ neutral.status = if cancelled {
+ SubagentOutcomeKind::Cancelled
+ } else if tool_result.is_error {
+ SubagentOutcomeKind::Incomplete(SubagentIncomplete::new(
+ "configured delegate reported failure",
+ ))
+ } else {
+ SubagentOutcomeKind::Completed
+ };
+ self.configured_tool_result
+ .lock()
+ .unwrap_or_else(|p| p.into_inner())
+ .insert(task_key, tool_result);
+ Ok(neutral)
+ }
+ (Err(error), _) => {
+ self.failures
+ .lock()
+ .unwrap_or_else(|p| p.into_inner())
+ .insert(task_key, SubagentRunError::Provider(error));
+ Err(SubagentError::Execution(
+ "configured delegate execution failed".into(),
+ ))
+ }
+ }
+ }
+ }
+ }
+}
+
+/// Durable OpenHuman pause/terminal records scoped by the complete neutral
+/// task key. The key is encoded rather than using a task id as a filename, so
+/// equally named children of separate roots/parents can never resume or close
+/// one another's lifecycle.
+pub(super) struct OpenHumanPersistence {
+ checkpoint_dir: std::path::PathBuf,
+ host_outcome: Arc<Mutex<HashMap<SubagentTaskKey, SubagentRunOutcome>>>,
+}
+
+#[derive(serde::Serialize, serde::Deserialize)]
+struct TerminalRecord {
+ outcome: SubagentOutcome,
+ #[serde(default)]
+ agent_id: String,
+ #[serde(default)]
+ elapsed_ms: u64,
+}
+
+#[derive(serde::Deserialize)]
+#[serde(untagged)]
+enum CompatibleTerminalRecord {
+ Current(TerminalRecord),
+ Legacy(SubagentOutcome),
+}
+
+impl OpenHumanPersistence {
+ pub(super) fn new(checkpoint_dir: std::path::PathBuf) -> Self {
+ Self {
+ checkpoint_dir,
+ host_outcome: Arc::new(Mutex::new(HashMap::new())),
+ }
+ }
+
+ fn with_host_outcome(
+ mut self,
+ host_outcome: Arc<Mutex<HashMap<SubagentTaskKey, SubagentRunOutcome>>>,
+ ) -> Self {
+ self.host_outcome = host_outcome;
+ self
+ }
+
+ fn key_component(key: &SubagentTaskKey) -> String {
+ fn hex(value: &str) -> String {
+ value
+ .as_bytes()
+ .iter()
+ .map(|byte| format!("{byte:02x}"))
+ .collect()
+ }
+ let encoded = format!(
+ "{}-{}-{}-{}",
+ hex(&key.root_run_id),
+ hex(&key.parent_run_id),
+ hex(key.thread_id.as_deref().unwrap_or("")),
+ hex(&key.task_id),
+ );
+ // A task key normally contains short UUID-like identifiers, for which
+ // the reversible encoding preserves existing checkpoint paths. A
+ // background child may inherit a rendered parent identifier, however;
+ // hex-encoding that value can exceed the filesystem filename limit.
+ // Hash only that exceptional form while keeping all key fields in the
+ // digest input so distinct lifecycle scopes cannot alias.
+ if encoded.len() <= 180 {
+ encoded
+ } else {
+ format!("sha256-{:x}", Sha256::digest(encoded.as_bytes()))
+ }
+ }
+
+ fn pause_path(&self, key: &SubagentTaskKey) -> std::path::PathBuf {
+ self.checkpoint_dir
+ .join("lifecycle")
+ .join(format!("{}.pause.json", Self::key_component(key)))
+ }
+
+ fn terminal_path(&self, key: &SubagentTaskKey) -> std::path::PathBuf {
+ self.checkpoint_dir
+ .join("lifecycle")
+ .join(format!("{}.terminal.json", Self::key_component(key)))
+ }
+
+ fn index_path(&self, task_id: &str) -> std::path::PathBuf {
+ self.checkpoint_dir
+ .join("lifecycle")
+ .join(format!("task-{}.index.json", Self::task_component(task_id)))
+ }
+
+ fn lock_path(&self, key: &SubagentTaskKey) -> std::path::PathBuf {
+ self.checkpoint_dir
+ .join("lifecycle")
+ .join(format!("{}.lock", Self::key_component(key)))
+ }
+
+ fn index_lock_path(&self, task_id: &str) -> std::path::PathBuf {
+ self.checkpoint_dir
+ .join("lifecycle")
+ .join(format!("task-{}.index.lock", Self::task_component(task_id)))
+ }
+
+ fn task_component(task_id: &str) -> String {
+ let encoded = task_id
+ .as_bytes()
+ .iter()
+ .map(|byte| format!("{byte:02x}"))
+ .collect::<String>();
+ if encoded.len() <= 180 {
+ encoded
+ } else {
+ format!("sha256-{:x}", Sha256::digest(encoded.as_bytes()))
+ }
+ }
+
+ fn lock_file(path: &std::path::Path) -> Result<std::fs::File, SubagentError> {
+ let parent = path.parent().expect("lifecycle lock path has a parent");
+ std::fs::create_dir_all(parent)
+ .map_err(|error| SubagentError::Persistence(error.to_string()))?;
+ let file = OpenOptions::new()
+ .create(true)
+ .truncate(false)
+ .read(true)
+ .write(true)
+ .open(path)
+ .map_err(|error| SubagentError::Persistence(error.to_string()))?;
+ file.lock_exclusive()
+ .map_err(|error| SubagentError::Persistence(error.to_string()))?;
+ Ok(file)
+ }
+
+ fn key_lock(&self, key: &SubagentTaskKey) -> Result<std::fs::File, SubagentError> {
+ Self::lock_file(&self.lock_path(key))
+ }
+
+ fn index_lock(&self, task_id: &str) -> Result<std::fs::File, SubagentError> {
+ Self::lock_file(&self.index_lock_path(task_id))
+ }
+
+ fn read_index_keys(&self, task_id: &str) -> Result<Vec<SubagentTaskKey>, SubagentError> {
+ let raw = match std::fs::read_to_string(self.index_path(task_id)) {
+ Ok(raw) => raw,
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
+ Err(error) => return Err(SubagentError::Persistence(error.to_string())),
+ };
+ let value: serde_json::Value = serde_json::from_str(&raw)
+ .map_err(|error| SubagentError::Persistence(error.to_string()))?;
+ // Accept the short-lived single-key format written by the first
+ // lifecycle extraction, but immediately write the collision-safe
+ // vector format on the next mutation.
+ let keys = value
+ .get("keys")
+ .cloned()
+ .map(serde_json::from_value)
+ .transpose()
+ .map_err(|error| SubagentError::Persistence(error.to_string()))?
+ .or_else(|| {
+ value
+ .get("key")
+ .cloned()
+ .and_then(|key| serde_json::from_value(key).ok())
+ .map(|key| vec![key])
+ })
+ .unwrap_or_default();
+ Ok(keys)
+ }
+
+ fn write_index_keys(
+ &self,
+ task_id: &str,
+ keys: &[SubagentTaskKey],
+ ) -> Result<(), SubagentError> {
+ let path = self.index_path(task_id);
+ if keys.is_empty() {
+ match std::fs::remove_file(path) {
+ Ok(()) => return Ok(()),
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
+ Err(error) => return Err(SubagentError::Persistence(error.to_string())),
+ }
+ }
+ Self::replace_file(
+ &path,
+ serde_json::to_vec(&serde_json::json!({"keys": keys}))
+ .map_err(|error| SubagentError::Persistence(error.to_string()))?,
+ )
+ }
+
+ fn add_index_key(&self, key: &SubagentTaskKey) -> Result<(), SubagentError> {
+ let _index_lock = self.index_lock(&key.task_id)?;
+ let mut keys = self.read_index_keys(&key.task_id)?;
+ if !keys.contains(key) {
+ keys.push(key.clone());
+ self.write_index_keys(&key.task_id, &keys)?;
+ }
+ Ok(())
+ }
+
+ fn remove_index_key(&self, key: &SubagentTaskKey) -> Result<(), SubagentError> {
+ let _index_lock = self.index_lock(&key.task_id)?;
+ let mut keys = self.read_index_keys(&key.task_id)?;
+ keys.retain(|candidate| candidate != key);
+ self.write_index_keys(&key.task_id, &keys)
+ }
+
+ fn replace_file(path: &std::path::Path, bytes: Vec<u8>) -> Result<(), SubagentError> {
+ let parent = path.parent().expect("lifecycle state path has a parent");
+ std::fs::create_dir_all(parent)
+ .map_err(|error| SubagentError::Persistence(error.to_string()))?;
+ let temporary = path.with_extension(format!("{}.tmp", uuid::Uuid::new_v4()));
+ std::fs::write(&temporary, bytes)
+ .map_err(|error| SubagentError::Persistence(error.to_string()))?;
+ match std::fs::rename(&temporary, path) {
+ Ok(()) => Ok(()),
+ Err(error) => {
+ let _ = std::fs::remove_file(&temporary);
+ Err(SubagentError::Persistence(error.to_string()))
+ }
+ }
+ }
+
+ fn insert_file(path: &std::path::Path, bytes: Vec<u8>) -> Result<bool, SubagentError> {
+ let parent = path.parent().expect("lifecycle state path has a parent");
+ std::fs::create_dir_all(parent)
+ .map_err(|error| SubagentError::Persistence(error.to_string()))?;
+ let temporary = path.with_extension(format!("{}.tmp", uuid::Uuid::new_v4()));
+ std::fs::write(&temporary, bytes)
+ .map_err(|error| SubagentError::Persistence(error.to_string()))?;
+ match std::fs::hard_link(&temporary, path) {
+ Ok(()) => {
+ let _ = std::fs::remove_file(&temporary);
+ Ok(true)
+ }
+ Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {
+ let _ = std::fs::remove_file(&temporary);
+ Ok(false)
+ }
+ Err(error) => {
+ let _ = std::fs::remove_file(&temporary);
+ Err(SubagentError::Persistence(error.to_string()))
+ }
+ }
+ }
+
+ fn read_pause_checkpoint(
+ &self,
+ key: &SubagentTaskKey,
+ ) -> Result<Option<super::SubagentCheckpointData>, SubagentError> {
+ let raw = match std::fs::read_to_string(self.pause_path(key)) {
+ Ok(raw) => raw,
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
+ Err(error) => return Err(SubagentError::Persistence(error.to_string())),
+ };
+ let checkpoint = serde_json::from_str::<super::SubagentCheckpointData>(&raw)
+ .map_err(|error| SubagentError::Persistence(error.to_string()))?;
+ if checkpoint.task_key.as_ref() != Some(key) {
+ return Err(SubagentError::Persistence("checkpoint key mismatch".into()));
+ }
+ Ok(Some(checkpoint))
+ }
+
+ fn read_terminal_record(
+ &self,
+ key: &SubagentTaskKey,
+ ) -> Result<Option<TerminalRecord>, SubagentError> {
+ let raw = match std::fs::read_to_string(self.terminal_path(key)) {
+ Ok(raw) => raw,
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
+ Err(error) => return Err(SubagentError::Persistence(error.to_string())),
+ };
+ match serde_json::from_str(&raw)
+ .map_err(|error| SubagentError::Persistence(error.to_string()))?
+ {
+ CompatibleTerminalRecord::Current(record) => Ok(Some(record)),
+ CompatibleTerminalRecord::Legacy(outcome) => Ok(Some(TerminalRecord {
+ outcome,
+ agent_id: String::new(),
+ elapsed_ms: 0,
+ })),
+ }
+ }
+
+ fn durable_host_metadata(
+ &self,
+ key: &SubagentTaskKey,
+ ) -> Result<Option<(String, u64)>, SubagentError> {
+ let _key_lock = self.key_lock(key)?;
+ if let Some(record) = self.read_terminal_record(key)? {
+ return Ok(
+ (!record.agent_id.is_empty()).then_some((record.agent_id, record.elapsed_ms))
+ );
+ }
+ Ok(self.read_pause_checkpoint(key)?.and_then(|checkpoint| {
+ (!checkpoint.agent_id.is_empty())
+ .then_some((checkpoint.agent_id, checkpoint.elapsed_ms))
+ }))
+ }
+
+ pub(crate) fn checkpoint_resume(checkpoint: &super::SubagentCheckpointData) -> SubagentResume {
+ SubagentResume {
+ history: checkpoint
+ .history
+ .iter()
+ .map(crate::agent::message_convert::chat_message_to_message)
+ .collect(),
+ checkpoint: checkpoint.resume_checkpoint.clone(),
+ metadata: checkpoint.resume_metadata.clone(),
+ }
+ }
+
+ fn checkpoint_outcome(checkpoint: super::SubagentCheckpointData) -> SubagentOutcome {
+ let resume = Self::checkpoint_resume(&checkpoint);
+ SubagentOutcome {
+ task_id: checkpoint.task_id,
+ output: checkpoint.output,
+ history: checkpoint
+ .history
+ .iter()
+ .map(crate::agent::message_convert::chat_message_to_message)
+ .collect(),
+ status: SubagentOutcomeKind::AwaitingInput(SubagentPause {
+ reason: checkpoint.question,
+ resume,
+ }),
+ usage: UsageTotals {
+ calls: checkpoint.iterations as u64,
+ usage: Usage {
+ input_tokens: checkpoint.usage.input_tokens,
+ output_tokens: checkpoint.usage.output_tokens,
+ total_tokens: checkpoint
+ .usage
+ .input_tokens
+ .saturating_add(checkpoint.usage.output_tokens),
+ cache_read_tokens: checkpoint.usage.cached_input_tokens,
+ // An unknown cost crosses as no charge at all, never as $0.
+ charged_amount: checkpoint
+ .usage
+ .cost()
+ .usd()
+ .map(|usd| ChargedAmount::usd_micros((usd * 1_000_000.0).round() as i64)),
+ ..Usage::default()
+ },
+ },
+ artifacts: checkpoint
+ .artifact_paths
+ .into_iter()
+ .map(|id| ArtifactReference {
+ id,
+ ..ArtifactReference::default()
+ })
+ .collect(),
+ ..SubagentOutcome::cancelled(String::new())
+ }
+ }
+
+ fn live_checkpoint(
+ &self,
+ key: &SubagentTaskKey,
+ ) -> Result<Option<super::SubagentCheckpointData>, SubagentError> {
+ let _key_lock = self.key_lock(key)?;
+ if self.terminal_path(key).exists() {
+ return Ok(None);
+ }
+ self.read_pause_checkpoint(key)
+ }
+
+ fn checkpoint_for_task(
+ &self,
+ task_id: &str,
+ ) -> Result<super::SubagentCheckpointData, SubagentRunError> {
+ if !super::ops::is_safe_task_id(task_id) {
+ return Err(SubagentRunError::Provider(anyhow::anyhow!(
+ "unsafe task id"
+ )));
+ }
+ let keys = {
+ let _index_lock = self.index_lock(task_id).map_err(map_lifecycle_error)?;
+ self.read_index_keys(task_id).map_err(map_lifecycle_error)?
+ };
+ let mut live = Vec::new();
+ for key in keys {
+ if let Some(checkpoint) = self.live_checkpoint(&key).map_err(map_lifecycle_error)? {
+ live.push(checkpoint);
+ }
+ }
+ match live.len() {
+ 1 => Ok(live.remove(0)),
+ 0 => Err(SubagentRunError::Provider(anyhow::anyhow!(
+ "no live subagent pause checkpoint for task id"
+ ))),
+ _ => Err(SubagentRunError::Provider(anyhow::anyhow!(
+ "ambiguous subagent task id; select a scoped lifecycle key"
+ ))),
+ }
+ }
+
+ pub(crate) fn recover_key(
+ checkpoint_dir: &std::path::Path,
+ task_id: &str,
+ ) -> Result<SubagentTaskKey, SubagentRunError> {
+ let persistence = Self::new(checkpoint_dir.to_path_buf());
+ let checkpoint = persistence.checkpoint_for_task(task_id)?;
+ checkpoint.task_key.ok_or_else(|| {
+ SubagentRunError::Provider(anyhow::anyhow!("checkpoint omitted original task key"))
+ })
+ }
+}
+
+#[async_trait]
+impl tinyagents_orchestration::subagent::SubagentPersistence for OpenHumanPersistence {
+ async fn load_terminal(
+ &self,
+ key: &SubagentTaskKey,
+ ) -> Result<Option<SubagentOutcome>, SubagentError> {
+ let _key_lock = self.key_lock(key)?;
+ Ok(self.read_terminal_record(key)?.map(|record| record.outcome))
+ }
+ async fn load(&self, key: &SubagentTaskKey) -> Result<Option<SubagentResume>, SubagentError> {
+ let _key_lock = self.key_lock(key)?;
+ if self.terminal_path(key).exists() {
+ return Ok(None);
+ }
+ Ok(self
+ .read_pause_checkpoint(key)?
+ .as_ref()
+ .map(Self::checkpoint_resume))
+ }
+
+ async fn load_pause(
+ &self,
+ key: &SubagentTaskKey,
+ ) -> Result<Option<SubagentOutcome>, SubagentError> {
+ let _key_lock = self.key_lock(key)?;
+ if self.terminal_path(key).exists() {
+ return Ok(None);
+ }
+ Ok(self
+ .read_pause_checkpoint(key)?
+ .map(Self::checkpoint_outcome))
+ }
+
+ async fn save_pause(
+ &self,
+ pause: tinyagents_orchestration::subagent::PersistedSubagentPause,
+ ) -> Result<SubagentPausePersistenceDisposition, SubagentError> {
+ let _key_lock = self.key_lock(&pause.key)?;
+ if self.terminal_path(&pause.key).exists() {
+ return Ok(SubagentPausePersistenceDisposition::TerminalExisting);
+ }
+ let paused = match &pause.outcome.status {
+ SubagentOutcomeKind::AwaitingInput(paused) => paused,
+ _ => {
+ return Err(SubagentError::Persistence(
+ "attempted to persist a non-paused subagent outcome as a pause".into(),
+ ));
+ }
+ };
+ let metadata = &paused.resume.metadata;
+ let optional_metadata = |name: &str| {
+ metadata
+ .get(name)
+ .filter(|value| !value.is_empty())
+ .cloned()
+ };
+ let checkpoint = super::SubagentCheckpointData {
+ task_key: Some(pause.key.clone()),
+ task_id: pause.key.task_id.clone(),
+ agent_id: optional_metadata("agent_id").unwrap_or_default(),
+ worker_thread_id: optional_metadata("worker_thread_id"),
+ history: pause
+ .outcome
+ .history
+ .iter()
+ .filter_map(tinyagents_runtime::transcript::message_to_native_transcript)
+ .collect(),
+ question: paused.reason.clone(),
+ options: None,
+ skill_filter_override: optional_metadata("skill_filter_override"),
+ model_override: optional_metadata("model_override"),
+ created_at: chrono::Utc::now().to_rfc3339(),
+ resume_checkpoint: paused.resume.checkpoint.clone(),
+ resume_metadata: metadata.clone(),
+ output: pause.outcome.output.clone(),
+ iterations: pause.outcome.usage.calls as usize,
+ usage: SubagentUsage {
+ input_tokens: pause.outcome.usage.usage.input_tokens,
+ output_tokens: pause.outcome.usage.usage.output_tokens,
+ cached_input_tokens: pause.outcome.usage.usage.cache_read_tokens,
+ charged_amount_usd: pause
+ .outcome
+ .usage
+ .usage
+ .charged_amount
+ .map(|amount| amount.micros as f64 / 1_000_000.0)
+ .unwrap_or_default(),
+ cost_source: cost_source_of(pause.outcome.usage.usage.charged_amount.as_ref()),
+ },
+ artifact_paths: pause
+ .outcome
+ .artifacts
+ .iter()
+ .map(|artifact| artifact.id.clone())
+ .collect(),
+ elapsed_ms: self
+ .host_outcome
+ .lock()
+ .unwrap_or_else(|poisoned| poisoned.into_inner())
+ .get(&pause.key)
+ .map(|outcome| outcome.elapsed.as_millis() as u64)
+ .unwrap_or_default(),
+ };
+ let json = serde_json::to_vec_pretty(&checkpoint)
+ .map_err(|error| SubagentError::Persistence(error.to_string()))?;
+ let path = self.pause_path(&pause.key);
+ let existing = self.read_pause_checkpoint(&pause.key)?;
+ match (pause.replaces.as_ref(), existing) {
+ (None, None) => {
+ // Index first: a failed data write can leave a stale index,
+ // which readers filter by the live pause record. A successful
+ // pause can never be unresumable through a missing index.
+ self.add_index_key(&pause.key)?;
+ if Self::insert_file(&path, json)? {
+ Ok(SubagentPausePersistenceDisposition::Inserted)
+ } else {
+ Ok(SubagentPausePersistenceDisposition::Existing)
+ }
+ }
+ (Some(expected), Some(current)) if Self::checkpoint_resume(&current) == *expected => {
+ self.add_index_key(&pause.key)?;
+ Self::replace_file(&path, json)?;
+ Ok(SubagentPausePersistenceDisposition::Replaced)
+ }
+ _ => Ok(SubagentPausePersistenceDisposition::Existing),
+ }
+ }
+
+ async fn record_terminal(
+ &self,
+ key: &SubagentTaskKey,
+ outcome: &SubagentOutcome,
+ replaces: Option<&SubagentResume>,
+ ) -> Result<SubagentTerminalPersistenceDisposition, SubagentError> {
+ let _key_lock = self.key_lock(key)?;
+ if self.terminal_path(key).exists() {
+ return Ok(SubagentTerminalPersistenceDisposition::Existing);
+ }
+ if let Some(current) = self.read_pause_checkpoint(key)? {
+ let can_consume_pause =
+ replaces.is_some_and(|expected| Self::checkpoint_resume(&current) == *expected);
+ if !can_consume_pause {
+ return Ok(SubagentTerminalPersistenceDisposition::PauseExisting);
+ }
+ } else if replaces.is_some() {
+ return Err(SubagentError::Persistence(
+ "terminal continuation lost its expected durable pause".into(),
+ ));
+ }
+ let path = self.terminal_path(key);
+ let host = self
+ .host_outcome
+ .lock()
+ .unwrap_or_else(|poisoned| poisoned.into_inner())
+ .get(key)
+ .cloned();
+ let record = serde_json::to_vec(&TerminalRecord {
+ outcome: outcome.clone(),
+ agent_id: host
+ .as_ref()
+ .map(|outcome| outcome.agent_id.clone())
+ .unwrap_or_default(),
+ elapsed_ms: host
+ .as_ref()
+ .map(|outcome| outcome.elapsed.as_millis() as u64)
+ .unwrap_or_default(),
+ })
+ .map_err(|error| SubagentError::Persistence(error.to_string()))?;
+ match Self::insert_file(&path, record)? {
+ true => {
+ // Terminal is the durable winner. Retiring a matching pause
+ // afterwards cannot reopen the lifecycle because `load` first
+ // observes this terminal marker.
+ let _ = std::fs::remove_file(self.pause_path(key));
+ // A stale task-id index is harmless because recovery filters
+ // terminal keys. Never turn a durable terminal success into an
+ // error merely because cleanup of a derived index failed.
+ if let Err(error) = self.remove_index_key(key) {
+ tracing::warn!(task_id = %key.task_id, error = %error, "[subagent] terminal committed but task-id index cleanup failed");
+ }
+ Ok(SubagentTerminalPersistenceDisposition::Inserted)
+ }
+ false => Ok(SubagentTerminalPersistenceDisposition::Existing),
+ }
+ }
+}
+
+#[path = "lifecycle_outcome.rs"]
+mod outcome;
+use outcome::{HostInFlightMap, host_outcome_to_neutral};
+
+pub(super) fn outcome_to_host(
+ result: SubagentRunResult,
+ host: Option<SubagentRunOutcome>,
+ persistence: &OpenHumanPersistence,
+ task_key: &SubagentTaskKey,
+ fallback_agent_id: &str,
+) -> SubagentRunOutcome {
+ let persistence_disposition = result.disposition;
+ let outcome = result.outcome;
+ // A driver that lost a pause/terminal CAS may have a perfectly valid local
+ // execution result, but it is not the authoritative lifecycle outcome.
+ // Reconstruct the durable winner instead of leaking the loser’s output,
+ // usage, or artifacts to an observer.
+ let host = if persistence_disposition.should_emit_host_effects() {
+ host
+ } else {
+ None
+ };
+ let durable_metadata = if host.is_none() {
+ persistence.durable_host_metadata(task_key).ok().flatten()
+ } else {
+ None
+ };
+ let mut host = host.unwrap_or_else(|| SubagentRunOutcome {
+ task_id: outcome.task_id.clone(),
+ agent_id: durable_metadata
+ .as_ref()
+ .map(|(agent_id, _)| agent_id.clone())
+ .unwrap_or_else(|| fallback_agent_id.to_owned()),
+ output: outcome.output.clone(),
+ iterations: outcome.usage.calls as usize,
+ elapsed: std::time::Duration::from_millis(
+ durable_metadata
+ .map(|(_, elapsed_ms)| elapsed_ms)
+ .unwrap_or_default(),
+ ),
+ mode: super::SubagentMode::Typed,
+ status: SubagentRunStatus::Completed,
+ final_history: outcome
+ .history
+ .iter()
+ .filter_map(tinyagents_runtime::transcript::message_to_native_transcript)
+ .collect(),
+ usage: SubagentUsage {
+ input_tokens: outcome.usage.usage.input_tokens,
+ output_tokens: outcome.usage.usage.output_tokens,
+ cached_input_tokens: outcome.usage.usage.cache_read_tokens,
+ charged_amount_usd: outcome
+ .usage
+ .usage
+ .charged_amount
+ .map(|amount| amount.micros as f64 / 1_000_000.0)
+ .unwrap_or_default(),
+ cost_source: cost_source_of(outcome.usage.usage.charged_amount.as_ref()),
+ },
+ artifact_paths: outcome
+ .artifacts
+ .iter()
+ .map(|artifact| artifact.id.clone())
+ .collect(),
+ persistence_disposition,
+ });
+ let is_awaiting_input = matches!(outcome.status, SubagentOutcomeKind::AwaitingInput(_));
+ let status = match outcome.status {
+ SubagentOutcomeKind::Completed => SubagentRunStatus::Completed,
+ SubagentOutcomeKind::AwaitingInput(pause) => SubagentRunStatus::AwaitingUser {
+ question: pause.reason,
+ options: None,
+ checkpoint: None,
+ },
+ SubagentOutcomeKind::Incomplete(incomplete) => SubagentRunStatus::Incomplete {
+ reason: incomplete.reason,
+ },
+ SubagentOutcomeKind::Cancelled => SubagentRunStatus::Cancelled,
+ };
+ host.status = status;
+ host.persistence_disposition = persistence_disposition;
+ if is_awaiting_input {
+ host.status = SubagentRunStatus::AwaitingUser {
+ question: match host.status {
+ SubagentRunStatus::AwaitingUser { ref question, .. } => question.clone(),
+ _ => String::new(),
+ },
+ options: None,
+ checkpoint: Some(persistence.pause_path(task_key)),
+ };
+ }
+ host
+}
+
+pub(super) fn map_lifecycle_error(error: SubagentError) -> SubagentRunError {
+ SubagentRunError::Provider(anyhow::anyhow!(error.to_string()))
+}
+/// A child run's cost as it comes back across the orchestration boundary.
+/// That `Usage` can only say whether a charge is present, so a present one is
+/// read as charged and an absent one as unknown (it was sent as absent).
+fn cost_source_of(charged: Option<&ChargedAmount>) -> tinyagents_harness::cost::CostSource {
+ match charged {
+ Some(_) => tinyagents_harness::cost::CostSource::Charged,
+ None => tinyagents_harness::cost::CostSource::Unknown,
+ }
+}
+
+#[path = "lifecycle_checkpoint.rs"]
+mod checkpoint;