The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
refactor(agent): remove split graph-part files after subagent runner consolidation
Steven Enamakelcc999d21c3a0
diff --git a/crates/openhuman-core/src/agent/harness/subagent_runner/ops/graph_part_01.rs b/crates/openhuman-core/src/agent/harness/subagent_runner/ops/graph_part_01.rsdeleted file mode 100644index 192645fee5..0000000000--- a/crates/openhuman-core/src/agent/harness/subagent_runner/ops/graph_part_01.rs+++ /dev/null@@ -1,652 +0,0 @@-use std::collections::HashSet;-use std::sync::Arc;--use crate::agent::harness::agent_graph::{- AgentTurnRequest, AgentTurnResult, AgentTurnUsage,-};-use crate::agent::harness::subagent_runner::types::SubagentRunError;-use crate::agent::messages::{ChatMessage, ConversationMessage};-use crate::agent::progress::AgentProgress;-use crate::agent::tinyagents::{run_turn_via_tinyagents_shared, SubagentScope};-use crate::inference::tokenjuice::AgentTokenjuiceCompression;-use crate::tools::{Tool, ToolSpec};-use tinyagents_harness::workspace::WorkspaceDescriptor;--/// Cumulative usage stats gathered across a sub-agent graph run.-#[derive(Debug, Clone, Default)]-pub(super) struct AggregatedUsage {- pub(super) input_tokens: u64,- pub(super) output_tokens: u64,- pub(super) cached_input_tokens: u64,- pub(super) charged_amount_usd: f64,-}--/// Run an assembled custom per-agent turn through the shared default sub-agent-/// leaf. Bespoke `AgentGraph::Custom` graphs use this after their own routing-/// nodes so transcript persistence, worker-thread mirroring, progress events,-/// handoff middleware, cap summaries, and usage aggregation stay byte-for-byte-/// on the default path.-pub(crate) async fn run_agent_turn_request_via_default_graph(- req: AgentTurnRequest,-) -> Result<AgentTurnResult, SubagentRunError> {- let AgentTurnRequest {- turn_model_source,- model,- temperature,- mut history,- parent_tools,- dynamic_tools,- specs,- allowed_names,- max_iterations,- run_queue,- on_progress,- agent_id,- task_id,- extended_policy,- worker_thread_id,- workspace_dir,- workspace_descriptor,- max_output_tokens,- model_vision,- transcript_stem,- provider_label,- handoff_cache,- tokenjuice_compression,- config,- } = req;-- let (output, iterations, usage, early_exit_tool, hit_cap, breaker_halt) =- run_subagent_via_graph(- turn_model_source,- &model,- temperature,- &mut history,- parent_tools,- dynamic_tools,- specs,- allowed_names,- max_iterations,- run_queue,- on_progress,- &agent_id,- &task_id,- extended_policy,- worker_thread_id,- workspace_dir,- workspace_descriptor,- max_output_tokens,- model_vision,- &transcript_stem,- &provider_label,- handoff_cache,- tokenjuice_compression,- config.as_deref(),- )- .await?;-- Ok(AgentTurnResult {- history,- output,- iterations,- usage: AgentTurnUsage {- input_tokens: usage.input_tokens,- output_tokens: usage.output_tokens,- cached_input_tokens: usage.cached_input_tokens,- charged_amount_usd: usage.charged_amount_usd,- },- early_exit_tool,- hit_cap,- breaker_halt,- })-}--/// Drive a sub-agent turn on the tinyagents harness. Returns-/// `(text, model_calls, AggregatedUsage, early_exit_tool, hit_cap)` — `hit_cap`-/// is `true` when the run stopped at the model-call cap with work still pending-/// (the caller surfaces this as `SubagentRunStatus::Incomplete`, #4096).-#[allow(clippy::too_many_arguments)]-pub(super) async fn run_subagent_via_graph(- source: crate::agent::tinyagents::TurnModelSource,- model: &str,- temperature: f64,- history: &mut Vec<ChatMessage>,- parent_tools: Arc<Vec<Box<dyn Tool>>>,- dynamic_tools: Vec<Box<dyn Tool>>,- specs: Vec<ToolSpec>,- allowed_names: HashSet<String>,- max_iterations: usize,- run_queue: Option<Arc<crate::agent::harness::run_queue::RunQueue>>,- on_progress: Option<tokio::sync::mpsc::Sender<AgentProgress>>,- agent_id: &str,- task_id: &str,- extended_policy: bool,- worker_thread_id: Option<String>,- workspace_dir: std::path::PathBuf,- workspace_descriptor: Option<WorkspaceDescriptor>,- max_output_tokens: u32,- model_vision: bool,- // Transcript-persistence provenance: the resolved child transcript stem- // (`{parent_chain}__{child_session_key}`) and the provider label (the parent- // turn's event channel) so the child's raw transcript lands in `session_raw`- // with the right stem + provider/model meta — parity with the removed- // `SubagentObserver::persist_transcript`.- transcript_stem: &str,- provider_label: &str,- // Progressive-disclosure handoff cache (integrations_agent with a resolved- // toolkit); `Some` installs the `HandoffMiddleware` that stashes oversized- // tool results and shares the cache with the `extract_from_result` tool.- handoff_cache: Option<- std::sync::Arc<crate::agent::harness::subagent_runner::ResultHandoffCache>,- >,- // Agent-level TokenJuice profile (`definition.effective_tokenjuice_compression()`,- // #4466). Threaded into the sub-agent `TurnContextMiddleware` so sub-agent- // tool outputs get the same content-aware compaction the chat path applies- // instead of a blunt byte-cap truncation.- tokenjuice_compression: AgentTokenjuiceCompression,- // Host config for the `[context]` middleware knobs. Passed in rather than- // loaded here (plan-agents Phase 3): this function is slated to move into- // TinyAgents, where there is no config file. `None` yields the safe- // byte-cap-only defaults.- config: Option<&crate::config::Config>,-) -> Result<- (- String,- usize,- AggregatedUsage,- Option<String>,- bool,- // Breaker-halt reason (#4466): `Some` when the repeated-failure /- // repeat-progress circuit breaker stopped the run; the caller reports- // `Incomplete` instead of `Completed`.- Option<String>,- ),- SubagentRunError,-> {- tracing::info!(- model,- max_iterations,- agent_id,- task_id,- model_vision,- observed = on_progress.is_some(),- "[subagent_runner:graph] routing sub-agent turn through tinyagents harness"- );- // `specs` is derived from the registry inside the runner; the tinyagents- // adapters advertise each tool via its own `spec()`, so it's unused here.- let _ = &specs;-- // Child-progress attribution: mirror this sub-agent's iterations / tool calls- // / text + thinking deltas as `Subagent*` events scoped to (`agent_id`,- // `task_id`) so the parent thread can nest them under the live subagent row.- // Always set (not gated on `on_progress`): the scope also tells the shared- // seam this is a sub-agent turn, so the unknown-tool recovery uses the- // sub-agent wording. With no progress sink the scoped events simply have- // nowhere to go, which is harmless.- let subagent_scope = Some(SubagentScope {- agent_id: agent_id.to_string(),- task_id: task_id.to_string(),- extended_policy,- });-- // A standalone summarizer model for the cap-hit checkpoint call below (the- // turn's own model set is consumed by the run). Built off the same source, so- // the checkpoint invokes a crate `ChatModel` without naming `Provider`- // (issue #4249, Phase 3 / Motion A).- let summary_model = source.build_summarizer(model, temperature)?;-- // Resolve the sub-agent model's effective context window so the harness runs- // the context-window summarization step (issue #4249) on sub-agent turns too.- // A long-running / resumed sub-agent (worker threads, durable sessions) can- // accumulate a transcript past its own window; summarize before each model- // call rather than relying solely on the parent's one-time trim.- let context_window = source.effective_context_window(model).await;-- // Build the child turn's crate `ChatModel` set from the source; capability- // reads (vision/native-tools) + telemetry id now come off the built bundle,- // so the sub-agent path names crate model types only.- let turn_models = source.build(model, temperature, context_window)?;-- // Vision forwarding (parity with the legacy `run_inner_loop`): rehydrate- // `[IMAGE:…]` placeholders in the sub-agent's history when either the model- // advertises vision or the sub-agent model is user-flagged as vision-capable- // (BYOK/custom). The expanded copy is provider-only — the persisted `history`- // written back below keeps the original markers.- let dispatch_history = if (turn_models.supports_vision() || model_vision)- && crate::agent::multimodal::has_image_placeholders(history)- {- crate::agent::multimodal::rehydrate_image_placeholders(history)- } else {- history.clone()- };-- // Build the sub-agent's context middleware from the live `[context]` config +- // the agent's TokenJuice profile (#4466), matching how the chat path wires- // `TurnContextMiddleware` (session/turn/core.rs). The migrated sub-agent path- // had regressed to `TurnContextMiddleware::defaults()` — compression Off — so- // sub-agent tool outputs took a blunt 16 KiB truncation instead of the- // content-aware TokenJuice compaction the definition asked for. Honor the- // `[context]` enabled / autocompact opt-outs, microcompact keep-recent, and- // per-result byte budget too, so a sub-agent turn compacts like a chat turn.- let context_mw = build_subagent_context_mw(tokenjuice_compression, config);-- // Live transcript snapshot sink (#4466): the harness owns the working message- // vector and drops it on a mid-run `Err`, so a failed sub-agent run used to- // persist NOTHING (breaking `learning/transcript_ingest`) and leave an empty- // worker thread. Attach a snapshot middleware that mirrors each `before_model`- // request's transcript here, so the error path below can still persist the- // rounds that completed before the failure.- let transcript_snapshot: crate::agent::tinyagents::TranscriptSnapshotSink =- std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));-- // A sub-agent turn runs *nested inside* the parent agent's turn (parent- // harness → spawn_subagent tool → here), so the child's full- // `run_turn_via_tinyagents_shared` future would otherwise sit on the parent's- // poll stack. Heap-allocate it (as the legacy `run_inner_loop` did) so the- // parent+child harness drives don't overflow the stack.- // Native-tool support drives the durable-history suffix dispatcher; capture it- // (and the telemetry id) before `turn_models` is moved into the runner.- let native_tools = turn_models.native_tools();- let provider_id = turn_models.provider_id().to_string();- let run_result = Box::pin(run_turn_via_tinyagents_shared(- turn_models,- provider_id,- model,- dispatch_history,- // Dynamic (per-spawn) tools first so a dynamic tool that intentionally- // shadows a parent-registry tool of the same name is the one that- // *executes* — matching the advertisement order (`dedup_tool_specs_by_name`- // lists dynamic specs before parent specs in `runner.rs`). The shared- // adapter resolves a name by scanning the sets in order, so a- // parent-first order would run the parent impl for a shadowed name.- vec![Arc::new(dynamic_tools), parent_tools],- // Fail-closed (issue #4452): a sub-agent ALWAYS carries a concrete,- // resolved allowlist (`allowed_names`), so pass it as `Some(..)`. An empty- // set is therefore a genuine deny-all — a tool-less agent- // (`ToolScope::Named([])`), a zero-match `skill_filter`, or a `named` list- // that resolved to nothing registers ZERO tools instead of implicitly- // inheriting the parent's full surface (shell/file-write/spawn).- Some(allowed_names),- max_iterations,- // Parent's progress sink — child events ride it, scoped below.- on_progress,- subagent_scope,- // Resolved above — drives the sub-agent context-window summarization step.- context_window,- // Mid-flight steering: forward queued steer messages into the run.- run_queue,- // Pause + checkpoint when the child asks the user a clarifying question.- &["ask_user_clarification"],- // Pause gracefully at the model-call cap so we can summarize a resumable- // checkpoint (below) instead of erroring — legacy cap-summary parity.- true,- // Bound the sub-agent's per-call output at its configured budget.- Some(max_output_tokens),- // Context middlewares (#4466): config-sourced TokenJuice compaction +- // tool-result byte cap + microcompact + summarization opt-outs (built- // above), plus the progressive-disclosure handoff when a cache is- // attached, plus the live transcript-snapshot sink for error recovery.- {- let mut mw = context_mw;- if let Some(cache) = handoff_cache {- mw.handoff = Some(crate::agent::tinyagents::HandoffConfig {- cache,- agent_id: agent_id.to_string(),- task_id: task_id.to_string(),- });- }- mw.transcript_snapshot = Some(transcript_snapshot.clone());- mw- },- // Sub-agents gate via their own SubagentToolSource policy path, not the- // session `.tool_policy()`; no enforcement threaded here.- None,- // Isolated worker descriptor, when worktree isolation prepared one.- workspace_descriptor,- // Sub-agent turns run tools with external effects; not a deterministic- // internal run, so response caching stays off (safe default).- false,- // #4457 (defect C): irrelevant for sub-agents — they carry a- // `subagent_scope`, so the seam never emits a top-level `TurnCompleted`- // (they report via `Subagent*` events). Pass `false` for clarity.- false,- ))- .await;-- let mut outcome = match run_result {- Ok(outcome) => outcome,- Err(err) => {- // #4466: the harness dropped its partial transcript, but the snapshot- // middleware mirrored every completed round. Persist those rounds to- // `session_raw` (so `learning/transcript_ingest` can still read a- // failed run) and mirror them onto the worker thread, THEN surface the- // error. Previously the `?`-return skipped both persistence steps, so- // a failed run left no transcript and an empty worker thread.- let mapped = map_tinyagents_subagent_error(err);- let recovered = transcript_snapshot- .lock()- .map(|g| g.clone())- .unwrap_or_default();- tracing::warn!(- agent_id,- task_id,- error = %mapped,- recovered_rounds = recovered.len(),- "[subagent_runner:graph] sub-agent run errored; persisting recovered transcript before returning (#4466)"- );- persist_failed_run(- &workspace_dir,- transcript_stem,- agent_id,- task_id,- provider_label,- model,- &recovered,- context_window.unwrap_or(0),- if native_tools { "native" } else { "xml" },- worker_thread_id.as_deref(),- &mapped,- );- return Err(mapped);- }- };-- // Write the final conversation back so the caller can checkpoint / persist.- // Keep the original (un-expanded) prior turns and append only this turn's typed- // suffix, serialized with the matching dispatcher so a native tool round- // persists as the `{content, tool_calls}` / `{tool_call_id, content}` envelope- // (re-parsed by `convert::chat_message_to_message` next turn) instead of an- // assistant with no `tool_calls` followed by an orphan `tool` row. Appending- // the typed `outcome.conversation` (messages-since-last-user) also avoids- // indexing a post-trim `outcome.history` with the pre-trim length, and the- // durable `[IMAGE:…]` markers stay put since the prior user turns are untouched.- use crate::agent::dispatcher::ToolDispatcher;- let suffix = if native_tools {- crate::agent::dispatcher::NativeToolDispatcher- .to_provider_messages(&outcome.conversation)- } else {- crate::agent::dispatcher::XmlToolDispatcher- .to_provider_messages(&outcome.conversation)- };- history.extend(suffix);-- let mut usage = AggregatedUsage {- input_tokens: outcome.input_tokens,- output_tokens: outcome.output_tokens,- // Carry the child's cached-prefix tokens + estimated cost (the turn- // outcome now reports both) so sub-agent spend rolls into the parent- // instead of being recorded as uncached and $0.- cached_input_tokens: outcome.cached_input_tokens,- charged_amount_usd: outcome.charged_amount_usd,- };-- // Cap hit with work still pending: summarize the run-so-far into a resumable- // checkpoint (the delegating agent continues from partial progress) rather- // than surfacing an empty/partial answer — the legacy `SubagentCheckpoint`.- if outcome.hit_cap {- let digest = build_cap_digest(&outcome.conversation, &outcome.tool_outcomes);- let strategy = super::checkpoint::SubagentCheckpoint {- chat_model: summary_model.clone(),- agent_id: agent_id.to_string(),- // The checkpoint summary call's output cap. #4469 item 5: honour this- // sub-agent definition's own per-call output budget (the same- // `max_output_tokens` bounding every task model call above) instead of- // the process-global `AGENT_TURN_MAX_OUTPUT_TOKENS` floor, so a- // definition that raised or lowered its output cap is respected by the- // cap-summary call too.- max_output_tokens,- };- match strategy.summarize_cap_hit(&digest, max_iterations).await {- Ok(co) => {- if let Some(u) = co.usage {- // Fold ALL four token fields (the legacy cap-summary folded- // cached tokens too, not just input/output), then price the- // call and feed the global cost tracker directly (#4467,- // item 2). The checkpoint summary call bypasses the harness so- // the observability bridge never sees it — without this record- // its cached tokens are lost and it costs $0 in the footer /- // transcript meta / cost dashboard.- usage.input_tokens += u.input_tokens;- usage.output_tokens += u.output_tokens;- usage.cached_input_tokens += u.cached_input_tokens;- let call_cost =- if u.charged_amount_usd.is_finite() && u.charged_amount_usd > 0.0 {- u.charged_amount_usd- } else {- crate::platform::cost::catalog::estimate_cost_usd(- model,- u.input_tokens,- u.output_tokens,- u.cached_input_tokens,- )- };- usage.charged_amount_usd += call_cost;- crate::platform::cost::record_provider_usage(- model,- &crate::inference::provider::UsageInfo {- input_tokens: u.input_tokens,- output_tokens: u.output_tokens,- context_window: u.context_window,- cached_input_tokens: u.cached_input_tokens,- cache_creation_tokens: u.cache_creation_tokens,- reasoning_tokens: u.reasoning_tokens,- charged_amount_usd: call_cost,- },- );- tracing::debug!(- agent_id,- input_tokens = u.input_tokens,- output_tokens = u.output_tokens,- cached_input_tokens = u.cached_input_tokens,- call_cost,- "[subagent] cap-hit summary call folded + priced + recorded into cost tracker (#4467, item 2)"- );- }- outcome.text = co.text;- }- Err(e) => return Err(SubagentRunError::Provider(e)),- }- }-- // Persist the sub-agent's raw transcript to `session_raw` (parity with the- // removed `SubagentObserver::persist_transcript`). The graph runner replaced- // the observer but only mirrored to the worker thread, so per-child- // transcripts stopped being written — breaking downstream learning ingestion- // (`learning/transcript_ingest`, which reads `session_raw/*.jsonl`).- // On a cap-hit / early-exit, `outcome.text` is the checkpoint (or clarifying- // question) that stands in for a final assistant turn — append it so the- // persisted transcript reflects the actual final state, not the pre-checkpoint- // history. `history` already carries this turn's typed suffix.- let transcript_history;- let history_for_transcript: &[ChatMessage] = if (outcome.hit_cap- || outcome.early_exit_tool.is_some())- && !outcome.text.trim().is_empty()- {- transcript_history = {- let mut messages = history.clone();- messages.push(ChatMessage::assistant(outcome.text.clone()));- messages- };- &transcript_history- } else {- history.as_slice()- };- persist_subagent_transcript(- &workspace_dir,- transcript_stem,- agent_id,- task_id,- provider_label,- model,- history_for_transcript,- &usage,- context_window.unwrap_or(0),- // Match the dispatcher the history was actually serialized with (text-mode- // integrations turns write XML), and the real iteration count.- if native_tools { "native" } else { "xml" },- outcome.model_calls as u32,- );-- // Mirror this turn's conversation to the spawn's worker thread (when one is- // attached), matching the legacy `SubagentObserver`: assistant intents +- // final answer as `agent` messages, tool results as `user` messages. The- // initial user prompt was already written when the worker thread was created.- if let Some(thread_id) = worker_thread_id {- mirror_worker_thread(- &workspace_dir,- &thread_id,- agent_id,- task_id,- &outcome.conversation,- // On a cap/early-exit, `outcome.text` is the checkpoint/question that- // replaced (or stands in for) a final assistant turn.- if outcome.hit_cap || outcome.early_exit_tool.is_some() {- Some(outcome.text.as_str())- } else {- None- },- );- }-- // On an early-exit (`ask_user_clarification`), `outcome.text` is the question- // and the runner checkpoints + returns AwaitingUser. `None` = ran to a final- // answer (or a cap-hit checkpoint summary).- Ok((- outcome.text,- outcome.model_calls,- usage,- outcome.early_exit_tool,- outcome.hit_cap,- // #4466: propagate a circuit-breaker halt so the runner reports Incomplete.- outcome.breaker_halt,- ))-}--/// Build the sub-agent turn's [`TurnContextMiddleware`] from the live-/// `[context]` config and the agent's TokenJuice profile (#4466), mirroring the-/// chat path (`session/turn/core.rs`). Falls back to-/// [`TurnContextMiddleware::defaults`] when the config can't be loaded so a-/// config glitch degrades to the safe (byte-cap-only) behavior rather than-/// erroring the run.-fn build_subagent_context_mw(- tokenjuice_compression: AgentTokenjuiceCompression,- config: Option<&crate::config::Config>,-) -> crate::agent::tinyagents::TurnContextMiddleware {- let mut mw = crate::agent::tinyagents::TurnContextMiddleware::defaults();- // Always thread the agent's compression profile — even on the config-default- // path — so the definition's TokenJuice choice is honored.- mw.tokenjuice_compression = tokenjuice_compression;- match config {- Some(config) => {- let ctx = &config.context;- // TokenJuice content-aware compaction gates on the same master- // `[context].compaction_enabled` the chat path reads- // (`ContextManager::compaction_enabled`).- mw.tokenjuice_compaction_enabled = ctx.compaction_enabled;- mw.tool_result_budget_bytes = ctx.tool_result_budget_bytes;- // Microcompact keep-recent is `0` (disabled) unless microcompact is on.- mw.microcompact_keep_recent = if ctx.microcompact_enabled {- ctx.microcompact_keep_recent- } else {- 0- };- // Summarization step honors the `[context].enabled` + autocompact- // opt-outs, same as `ContextManager::autocompact_enabled`.- mw.autocompact_enabled = ctx.enabled && ctx.autocompact_enabled;- tracing::debug!(- tokenjuice_compaction_enabled = mw.tokenjuice_compaction_enabled,- compression = ?mw.tokenjuice_compression,- tool_result_budget_bytes = mw.tool_result_budget_bytes,- microcompact_keep_recent = mw.microcompact_keep_recent,- autocompact_enabled = mw.autocompact_enabled,- "[subagent_runner:graph] built sub-agent context middleware from config (#4466)"- );- }- None => {- tracing::debug!(- "[subagent_runner:graph] no config available building sub-agent context mw; using defaults + compression profile"- );- }- }- mw-}--fn map_tinyagents_subagent_error(err: anyhow::Error) -> SubagentRunError {- match err.downcast::<SubagentRunError>() {- Ok(run_err) => run_err,- Err(err) => SubagentRunError::Provider(err),- }-}--/// Persist a sub-agent turn's raw transcript to `session_raw`, mirroring the-/// removed `SubagentObserver::persist_transcript`: `agent_type:"subagent"`, the-/// `task_id`, and the provider/model + usage carried on the last assistant-/// message so per-thread usage reads price the sub-agent at its own model.-#[allow(clippy::too_many_arguments)]-fn persist_subagent_transcript(- workspace_dir: &std::path::Path,- transcript_stem: &str,- agent_id: &str,- task_id: &str,- provider_label: &str,- model: &str,- history: &[ChatMessage],- usage: &AggregatedUsage,- context_window: u64,- dispatcher: &str,- iteration: u32,-) {- use crate::agent::harness::session::transcript;-- let path = match transcript::resolve_keyed_transcript_path(workspace_dir, transcript_stem) {- Ok(p) => p,- Err(err) => {- tracing::debug!(- agent_id,- error = %err,- "[subagent_runner:graph] failed to resolve child transcript path"- );- return;- }- };- let now = chrono::Utc::now().to_rfc3339();- let turn_usage = transcript::TurnUsage {- provider: provider_label.to_string(),- model: model.to_string(),- usage: transcript::MessageUsage {- input: usage.input_tokens,- output: usage.output_tokens,- cached_input: usage.cached_input_tokens,- context_window,- cost_usd: usage.charged_amount_usd,- },- ts: now.clone(),- reasoning_content: None,- tool_calls: Vec::new(),- iteration,- };- let meta = transcript::TranscriptMeta {- agent_name: agent_id.to_string(),- agent_id: Some(agent_id.to_string()),- agent_type: Some("subagent".to_string()),- dispatcher: dispatcher.into(),- provider: Some(turn_usage.provider.clone()),- model: Some(turn_usage.model.clone()),- created: now.clone(),- updated: now,- turn_count: 1,- input_tokens: usage.input_tokens,- output_tokens: usage.output_tokens,- cached_input_tokens: usage.cached_input_tokens,- charged_amount_usd: usage.charged_amount_usd,- thread_id: crate::agent::tinyagents::thread_context::current_thread_id(),- task_id: Some(task_id.to_string()),- };- if let Err(err) = transcript::write_transcript(&path, history, &meta, Some(&turn_usage)) {- tracing::debug!(- agent_id,- error = %err,- "[subagent_runner:graph] failed to write child transcript"- );- }-}diff --git a/crates/openhuman-core/src/agent/harness/subagent_runner/ops/graph_part_02.rs b/crates/openhuman-core/src/agent/harness/subagent_runner/ops/graph_part_02.rsdeleted file mode 100644index f7a1b99d8f..0000000000--- a/crates/openhuman-core/src/agent/harness/subagent_runner/ops/graph_part_02.rs+++ /dev/null@@ -1,330 +0,0 @@-/// Persist a **failed** sub-agent run (#4466): write whatever rounds the live-/// transcript-snapshot middleware captured before the harness error to-/// `session_raw` (so `learning/transcript_ingest` can still ingest a failed run,-/// not skip an absent file), mirror those rounds onto the worker thread, and-/// append a trailing failure marker so the record is self-describing. Usage is-/// zeroed — the harness reported no totals on the error path — and the iteration-/// count is the number of completed rounds recovered.-#[allow(clippy::too_many_arguments)]-fn persist_failed_run(- workspace_dir: &std::path::Path,- transcript_stem: &str,- agent_id: &str,- task_id: &str,- provider_label: &str,- model: &str,- recovered: &[ChatMessage],- context_window: u64,- dispatcher: &str,- worker_thread_id: Option<&str>,- error: &SubagentRunError,-) {- let marker = format!("[subagent run failed before completion: {error}]");- let mut history = recovered.to_vec();- history.push(ChatMessage::assistant(marker.clone()));-- // A failed run has no usage totals; record zeros so the transcript is still a- // valid, ingestable `session_raw` record with the failure surfaced.- let usage = AggregatedUsage::default();- persist_subagent_transcript(- workspace_dir,- transcript_stem,- agent_id,- task_id,- provider_label,- model,- &history,- &usage,- context_window,- dispatcher,- recovered.len() as u32,- );-- if let Some(thread_id) = worker_thread_id {- mirror_worker_thread_from_history(- workspace_dir,- thread_id,- agent_id,- task_id,- recovered,- Some(marker.as_str()),- );- }-}--/// Append a worker-thread [`StoredMessage`](crate::memory::conversations::ConversationMessage)-/// with the restored legacy [`SubagentObserver`] metadata (#4466): `scope`,-/// `agent_id`, `task_id`, plus the per-message `iteration`, `final`, `mode`, and-/// (for assistant tool rounds / tool results) `tool_calls` / `tool_call_id` /-/// `tool_name`. The migrated path had reduced this to `{scope, agent_id,-/// task_id}` only, dropping the fields worker-thread consumers key on.-#[allow(clippy::too_many_arguments)]-fn append_worker_message(- workspace_dir: &std::path::Path,- thread_id: &str,- agent_id: &str,- task_id: &str,- content: String,- sender: &str,- metadata: serde_json::Value,-) {- use crate::memory::conversations::{- append_message, ConversationMessage as StoredMessage,- };- let mut extra = serde_json::json!({- "scope": "worker_thread",- "agent_id": agent_id,- "task_id": task_id,- "mode": "typed",- // #5934: a mirror row that is not the sub-agent speaking is a tool- // result, and the renderer maps every non-`"agent"` sender to- // `role: 'user'` (`assistantUiMessages.ts`) — so without this flag a- // tool's raw output is painted, in an openable worker thread, as- // something the human typed. `hidden` keeps the row in the log for the- // process rail and the process-source view; it only stops being chat.- // Genuine worker-thread user turns are written by- // `worker_thread::{create_worker_thread, append_worker_user_message}`,- // not here, so they are unaffected. Overridable by `metadata` below.- "hidden": sender != "agent",- });- if let (Some(base), Some(extra_fields)) = (extra.as_object_mut(), metadata.as_object()) {- for (k, v) in extra_fields {- base.insert(k.clone(), v.clone());- }- }- let message = StoredMessage {- id: format!("{sender}:{}", uuid::Uuid::new_v4()),- content,- message_type: "text".to_string(),- extra_metadata: extra,- sender: sender.to_string(),- created_at: chrono::Utc::now().to_rfc3339(),- };- if let Err(err) = append_message(workspace_dir.to_path_buf(), thread_id, message) {- tracing::debug!(- agent_id,- thread_id,- error = %err,- "[subagent_runner:graph] failed to append worker-thread message"- );- }-}--/// Mirror a sub-agent turn's structured conversation to its worker thread,-/// matching the legacy [`SubagentObserver`]: assistant turns (intents + final)-/// become `agent` messages, tool results become `user` messages. `extra_final`,-/// when set, is appended as a trailing `agent` message (the cap checkpoint or-/// clarifying question, which isn't a plain assistant turn in the transcript).-///-/// Each message carries the restored legacy metadata (#4466): a per-round-/// `iteration` counter, `final` on the trailing message, `tool_calls` on an-/// assistant round, and `tool_call_id` / `tool_name` on each tool result.-fn mirror_worker_thread(- workspace_dir: &std::path::Path,- thread_id: &str,- agent_id: &str,- task_id: &str,- conversation: &[ConversationMessage],- extra_final: Option<&str>,-) {- use std::collections::HashMap;-- // call_id -> tool name, so each tool result records the tool it came from.- let mut names: HashMap<&str, &str> = HashMap::new();- for msg in conversation {- if let ConversationMessage::AssistantToolCalls { tool_calls, .. } = msg {- for call in tool_calls {- names.insert(call.id.as_str(), call.name.as_str());- }- }- }-- let mut iteration: u64 = 0;- for msg in conversation {- match msg {- ConversationMessage::AssistantToolCalls {- text, tool_calls, ..- } => {- iteration += 1;- if let Some(t) = text.as_deref().filter(|t| !t.trim().is_empty()) {- let call_names: Vec<&str> =- tool_calls.iter().map(|c| c.name.as_str()).collect();- append_worker_message(- workspace_dir,- thread_id,- agent_id,- task_id,- t.to_string(),- "agent",- serde_json::json!({- "iteration": iteration,- "final": false,- "tool_calls": call_names,- }),- );- }- }- ConversationMessage::ToolResults(results) => {- for r in results {- let tool_name = names- .get(r.tool_call_id.as_str())- .copied()- .unwrap_or("tool");- append_worker_message(- workspace_dir,- thread_id,- agent_id,- task_id,- r.content.clone(),- "user",- serde_json::json!({- "iteration": iteration,- "final": false,- "tool_call_id": r.tool_call_id,- "tool_name": tool_name,- }),- );- }- }- ConversationMessage::Chat(c)- if c.role == "assistant" && !c.content.trim().is_empty() =>- {- iteration += 1;- append_worker_message(- workspace_dir,- thread_id,- agent_id,- task_id,- c.content.clone(),- "agent",- serde_json::json!({- "iteration": iteration,- "final": extra_final.is_none(),- }),- );- }- _ => {}- }- }-- if let Some(text) = extra_final.filter(|t| !t.trim().is_empty()) {- append_worker_message(- workspace_dir,- thread_id,- agent_id,- task_id,- text.to_string(),- "agent",- serde_json::json!({ "iteration": iteration + 1, "final": true }),- );- }-}--/// Worker-thread mirror from a flat [`ChatMessage`] history (the error-recovery-/// path, #4466): assistant messages become `agent` rows, tool messages become-/// `user` rows. Used when only the recovered snapshot (not the typed-/// `conversation`) is available. `failure_final`, when set, is appended as a-/// trailing `agent` failure marker.-fn mirror_worker_thread_from_history(- workspace_dir: &std::path::Path,- thread_id: &str,- agent_id: &str,- task_id: &str,- history: &[ChatMessage],- failure_final: Option<&str>,-) {- let mut iteration: u64 = 0;- for m in history {- match m.role.as_str() {- "assistant" if !m.content.trim().is_empty() => {- iteration += 1;- append_worker_message(- workspace_dir,- thread_id,- agent_id,- task_id,- m.content.clone(),- "agent",- serde_json::json!({ "iteration": iteration, "final": false }),- );- }- "tool" if !m.content.trim().is_empty() => {- append_worker_message(- workspace_dir,- thread_id,- agent_id,- task_id,- m.content.clone(),- "user",- serde_json::json!({ "iteration": iteration, "final": false }),- );- }- _ => {}- }- }- if let Some(text) = failure_final.filter(|t| !t.trim().is_empty()) {- append_worker_message(- workspace_dir,- thread_id,- agent_id,- task_id,- text.to_string(),- "agent",- serde_json::json!({ "iteration": iteration + 1, "final": true }),- );- }-}--/// Build the `tool → outcome` digest the cap-hit summary call summarizes, in the-/// legacy `- {name} [{ok|failed}]: {output}` format (engine `run_tool_digest`),-/// pairing each tool result back to its call by id. Per-tool success is derived-/// from the turn's captured [`ToolCallOutcome`]s (#4467, item 7) rather than-/// reported optimistically as `ok`: a result whose call has no captured outcome-/// — e.g. a hallucinated/unknown tool the crate recovered without running-/// `after_tool` — is marked `failed`, so the summary no longer tells the model-/// every call succeeded.-fn build_cap_digest(- conversation: &[ConversationMessage],- tool_outcomes: &[crate::agent::tinyagents::ToolCallOutcome],-) -> String {- use std::collections::HashMap;- use std::fmt::Write as _;-- // call_id -> tool name, from this turn's assistant tool-call rounds.- let mut names: HashMap<&str, &str> = HashMap::new();- for msg in conversation {- if let ConversationMessage::AssistantToolCalls { tool_calls, .. } = msg {- for call in tool_calls {- names.insert(call.id.as_str(), call.name.as_str());- }- }- }-- // call_id -> success, from the captured per-call outcomes.- let success_by_id: HashMap<&str, bool> = tool_outcomes- .iter()- .map(|o| (o.call_id.as_str(), o.success))- .collect();-- let mut out = String::new();- for msg in conversation {- if let ConversationMessage::ToolResults(results) = msg {- for r in results {- let name = names- .get(r.tool_call_id.as_str())- .copied()- .unwrap_or("tool");- // Missing outcome → `false` (unknown/hallucinated tool): honest- // failed status rather than an optimistic `[ok]`.- let ok = success_by_id- .get(r.tool_call_id.as_str())- .copied()- .unwrap_or(false);- let tag = if ok { "ok" } else { "failed" };- let body = crate::util::truncate_with_ellipsis(&r.content, 800);- let _ = writeln!(out, "- {name} [{tag}]: {body}");- }- }- }- out.trim_end().to_string()-}diff --git a/crates/openhuman-core/src/agent/orchestration/running_subagents_part_01.rs b/crates/openhuman-core/src/agent/orchestration/running_subagents_part_01.rsdeleted file mode 100644index 66b57ec27b..0000000000--- a/crates/openhuman-core/src/agent/orchestration/running_subagents_part_01.rs+++ /dev/null@@ -1,591 +0,0 @@-use std::collections::HashSet;-use std::path::{Path, PathBuf};-use std::sync::{Arc, OnceLock};-use std::time::Duration;--use tokio::sync::watch;-use tokio::task::AbortHandle;--use crate::agent::harness::run_queue::{QueueMode, QueuedMessage, RunQueue};-use crate::agent::tinyagents::orchestration::{- open_jsonl_task_store_or_memory, reconcile_orphaned_tasks, shared_steering_registry,- DetachedTaskRegistry, DetachedTaskRegistryError, DetachedTaskWaitOutcome, InMemoryTaskStore,- OrchestrationTaskFilter, OrchestrationTaskKind, OrchestrationTaskRecord,- OrchestrationTaskResult, OrchestrationTaskSpec, OrchestrationTaskStatus, SteeringCommand,- SteeringCommandKind, TaskStore, TaskStoreRegistry,-};-use tinyagents_harness::ids::TaskId;-use tinyinference::message::Message as TaMessage;-use tinyagents_harness::CancellationToken;--/// Where a workspace's detached-task ledger lives.-///-/// A product path, not a generic one: TinyAgents opens whatever file it is-/// given, and this is where OpenHuman keeps it.-fn task_store_path(workspace_dir: &Path) -> PathBuf {- workspace_dir- .join(".openhuman")- .join("orchestration_tasks.jsonl")-}--#[cfg(test)]-fn default_task_store_workspace() -> PathBuf {- crate::config::default_root_openhuman_dir()- .map(|root| root.join("workspace"))- .unwrap_or_else(|_| PathBuf::from(".openhuman").join("workspace"))-}--/// Process-wide typed lifecycle ledger for detached sub-agents (issue #4249),-/// one durable store per workspace.-///-/// The caching and the durable→memory fallback are TinyAgents'-/// (`TaskStoreRegistry` / `open_jsonl_task_store_or_memory`): opening a second-/// store over the same append log would give two writers with independently-/// replayed state, and a workspace that cannot be written should degrade to an-/// in-memory ledger rather than take orchestration down. What stays here is the-/// path layout above.-static TASK_STORES: OnceLock<TaskStoreRegistry<PathBuf>> = OnceLock::new();--fn task_stores() -> &'static TaskStoreRegistry<PathBuf> {- TASK_STORES.get_or_init(|| {- TaskStoreRegistry::new(|workspace_dir: &PathBuf| {- open_jsonl_task_store_or_memory(&task_store_path(workspace_dir))- })- })-}--/// The ledger for `workspace_dir`, opening it on first use.-///-/// A poisoned registry lock is degraded to a throwaway in-memory store rather-/// than propagated: every caller here is a best-effort bookkeeping path, and a-/// panic in an unrelated task must not turn sub-agent spawning into a second-/// panic.-fn task_store_for_workspace(workspace_dir: &Path) -> Arc<dyn TaskStore> {- let key = workspace_dir.to_path_buf();- match task_stores().get_or_open(&key) {- Ok(store) => store,- Err(err) => {- log::warn!(- "[running_subagents] task store registry unavailable for {}; using a detached in-memory ledger: {}",- workspace_dir.display(),- err- );- Arc::new(InMemoryTaskStore::new())- }- }-}--#[cfg(test)]-fn task_store() -> Arc<dyn TaskStore> {- let workspace = default_task_store_workspace();- task_store_for_workspace(&workspace)-}--/// Record a freshly-spawned sub-agent in the store (`Pending` → `Running`).-/// Insert errors (e.g. a re-used task id across tests) are intentionally ignored.-fn record_spawned(- task_id: &str,- agent_id: &str,- parent_session: &str,- session_parent_prefix: Option<&str>,- subagent_session_id: Option<&str>,- workspace_dir: &Path,- parent_thread_id: Option<&str>,-) {- let store = task_store_for_workspace(workspace_dir);- let root_run_id = session_parent_prefix- .and_then(|prefix| prefix.split("__").next())- .filter(|root| !root.is_empty())- .unwrap_or(parent_session);- let mut spec = OrchestrationTaskSpec::new(- task_id.to_string(),- OrchestrationTaskKind::SubAgent {- agent: agent_id.to_string(),- },- )- .with_lineage(parent_session.to_string(), root_run_id.to_string())- .with_timeout_ms(DETACHED_LEDGER_TIMEOUT_MS)- .with_metadata("parentSession", parent_session.to_string())- .with_metadata("rootSession", root_run_id.to_string())- .with_metadata(- "defaultWaitTimeoutMs",- DETACHED_LEDGER_TIMEOUT_MS.to_string(),- )- .with_metadata("workspaceDir", workspace_dir.display().to_string());- if let Some(session_parent_prefix) = session_parent_prefix {- spec = spec.with_metadata("sessionParentPrefix", session_parent_prefix.to_string());- }- if let Some(parent_thread_id) = parent_thread_id {- spec = spec- .with_thread(parent_thread_id.to_string())- .with_metadata("parentThreadId", parent_thread_id.to_string());- }- if let Some(subagent_session_id) = subagent_session_id {- spec = spec.with_metadata("subagentSessionId", subagent_session_id.to_string());- }- let _ = store.insert(spec);- let _ = store.mark_running(&TaskId::new(task_id));-}--/// Mirror a child's published [`SubagentStatus`] into the typed store. Transition-/// errors (already terminal / cancelled) are ignored — first writer wins.-fn record_status(workspace_dir: &Path, task_id: &str, status: &SubagentStatus) {- let store = task_store_for_workspace(workspace_dir);- let id = TaskId::new(task_id);- log::debug!(- "[running_subagents] recording task status task_id={} workspace_dir={} terminal={}",- task_id,- workspace_dir.display(),- status.is_terminal()- );- match status {- SubagentStatus::Completed { output, .. } => {- let _ = store.complete(&id, OrchestrationTaskResult::text(output.clone()));- }- SubagentStatus::Failed { error } => {- let _ = store.fail(&id, error.clone());- }- SubagentStatus::AwaitingUser { .. } => {- let _ = store.mark_awaiting(&id);- }- SubagentStatus::Running => {}- }-}--/// Record a cancellation (`CancelRequested` → `Cancelled`) for `task_id`.-fn record_cancelled(workspace_dir: &Path, task_id: &str) {- let store = task_store_for_workspace(workspace_dir);- let id = TaskId::new(task_id);- log::debug!(- "[running_subagents] recording task cancellation task_id={} workspace_dir={}",- task_id,- workspace_dir.display()- );- let _ = store.request_cancel(&id);- let _ = store.mark_cancelled(&id);-}--fn list_task_records(workspace_dir: &Path) -> Vec<OrchestrationTaskRecord> {- let store = task_store_for_workspace(workspace_dir);- store.list(OrchestrationTaskFilter::default().with_kind("sub_agent"))-}--/// Restart/resume reconciliation for detached sub-agents (issue #4249 / 07.2-/// steps 2 & 4).-///-/// A detached sub-agent runs as a `tokio` task owned by the process that spawned-/// it. When the core restarts, that task — and its live [`AbortHandle`] /-/// [`CancellationToken`] — is gone, but the durable [`JsonlTaskStore`] still-/// holds a non-terminal (`Pending`/`Running`/`Awaiting`/`CancelRequested`)-/// record for it. Such a record is **orphaned**: there is no live executor to-/// re-attach to (OpenHuman spawns child processes, so an in-flight run from a-/// dead parent cannot be resumed), and the run-ledger finalizer never observed a-/// terminal event, so it would otherwise render as a perpetual "running" entry.-///-/// This scans the workspace-scoped store for those orphans and reconciles each-/// to a terminal state — `Cancelled` if a cancel had been requested, otherwise-/// `Failed` with an "orphaned by restart" reason — then emits the existing typed-/// terminal lifecycle event ([`subagent_events::publish_subagent_failed`]) so the-/// run ledger finalizes. Best-effort and non-fatal: per-task transition errors-/// (e.g. a record that raced to terminal) are logged and skipped, and a-/// store-open failure simply reconciles nothing. Returns the count reconciled.-/// The reason an orphaned sub-agent record is settled with.-///-/// Built in one place because it is written twice — into the store by the-/// reconciler, and into the lifecycle event the run ledger reads. If those two-/// ever disagreed, the ledger would explain a failure differently from the-/// record behind it.-fn orphaned_subagent_reason(prior_status: OrchestrationTaskStatus) -> String {- format!(- "sub-agent orphaned by core restart (was `{}`)",- task_status_label(prior_status)- )-}--pub(crate) fn reconcile_orphaned_tasks_on_boot(workspace_dir: &Path) -> usize {- let store = task_store_for_workspace(workspace_dir);-- // The sweep itself — which statuses are live, and which terminal state each- // becomes — is TinyAgents'. What stays here is the reason a *sub-agent*- // orphan carries, and the lifecycle event that finalizes OpenHuman's run- // ledger afterwards.- let report = reconcile_orphaned_tasks(- store.as_ref(),- OrchestrationTaskFilter::default().with_kind("sub_agent"),- &|record| orphaned_subagent_reason(record.status),- );-- if report.is_empty() {- log::debug!(- "[running_subagents] reconcile found no orphaned sub-agent tasks workspace_dir={}",- workspace_dir.display()- );- return 0;- }-- for task in report.settled() {- let task_id = task.task_id.as_str().to_string();- let prior = task_status_label(task.prior_status);- let reason = orphaned_subagent_reason(task.prior_status);- let parent_session = record_parent_session(&task.record)- .unwrap_or_default()- .to_string();- let agent_id = record_agent_id(&task.record);- // Reuse the 05.2 typed terminal lifecycle helper so the run ledger- // finalizes exactly as it would for a live failure.- super::subagent_events::publish_subagent_failed(- parent_session,- task_id.clone(),- agent_id,- reason,- );- log::info!(- "[running_subagents] reconciled orphaned sub-agent task_id={} prior_status={} -> terminal",- task_id,- prior- );- }-- let reconciled = report.reconciled_count();- log::info!(- "[running_subagents] reconciled {reconciled} orphaned sub-agent task(s) on boot workspace_dir={} errors={}",- workspace_dir.display(),- report.error_count()- );- reconciled-}--fn record_parent_session(record: &OrchestrationTaskRecord) -> Option<&str> {- record- .spec- .metadata- .get("parentSession")- .map(String::as_str)-}--fn record_subagent_session_id(record: &OrchestrationTaskRecord) -> Option<&str> {- record- .spec- .metadata- .get("subagentSessionId")- .map(String::as_str)-}--fn record_agent_id(record: &OrchestrationTaskRecord) -> String {- match &record.spec.kind {- OrchestrationTaskKind::SubAgent { agent } => agent.clone(),- _ => "subagent".to_string(),- }-}--pub(crate) fn task_record_for_task_in_workspace(- workspace_dir: &Path,- task_id: &str,- parent_session: &str,-) -> Result<OrchestrationTaskRecord, WaitError> {- let id = TaskId::new(task_id);- let Some(record) = task_store_for_workspace(workspace_dir).get(&id) else {- return Err(WaitError::Unknown);- };- if !matches!(record.spec.kind, OrchestrationTaskKind::SubAgent { .. }) {- return Err(WaitError::Unknown);- }- if record_parent_session(&record) != Some(parent_session) {- return Err(WaitError::NotOwned);- }- Ok(record)-}--fn record_to_status(record: OrchestrationTaskRecord) -> WaitOutcome {- match record.status {- OrchestrationTaskStatus::Completed => {- let output = record- .result- .and_then(|result| {- result- .text- .or_else(|| result.output.map(|output| output.to_string()))- })- .unwrap_or_default();- WaitOutcome::Terminal(SubagentStatus::Completed {- output,- iterations: 0,- })- }- OrchestrationTaskStatus::Awaiting => WaitOutcome::Terminal(SubagentStatus::AwaitingUser {- question: record.error.unwrap_or_else(|| {- "sub-agent is awaiting user input; no clarification text was available from the durable task store".to_string()- }),- }),- OrchestrationTaskStatus::Failed- | OrchestrationTaskStatus::TimedOut- | OrchestrationTaskStatus::Abandoned => WaitOutcome::Terminal(SubagentStatus::Failed {- error: record.error.unwrap_or_else(|| {- format!(- "sub-agent reached durable task status `{}`",- task_status_label(record.status)- )- }),- }),- OrchestrationTaskStatus::Cancelled => WaitOutcome::Terminal(SubagentStatus::Failed {- error: "sub-agent was cancelled".to_string(),- }),- OrchestrationTaskStatus::Pending- | OrchestrationTaskStatus::Running- | OrchestrationTaskStatus::CancelRequested => WaitOutcome::TimedOut(SubagentStatus::Running),- }-}--fn task_status_label(status: OrchestrationTaskStatus) -> &'static str {- match status {- OrchestrationTaskStatus::Pending => "pending",- OrchestrationTaskStatus::Running => "running",- OrchestrationTaskStatus::Awaiting => "awaiting",- OrchestrationTaskStatus::Completed => "completed",- OrchestrationTaskStatus::Failed => "failed",- OrchestrationTaskStatus::CancelRequested => "cancel_requested",- OrchestrationTaskStatus::Cancelled => "cancelled",- OrchestrationTaskStatus::TimedOut => "timed_out",- OrchestrationTaskStatus::Abandoned => "abandoned",- }-}--/// Snapshot the typed lifecycle records, optionally scoped to a `parent_session`.-#[cfg(test)]-fn task_records(parent_session: Option<&str>) -> Vec<OrchestrationTaskRecord> {- let _ = task_store();- let stores: Vec<Arc<dyn TaskStore>> = task_stores().values().unwrap_or_default();- let all: Vec<OrchestrationTaskRecord> = stores- .into_iter()- .flat_map(|store| store.list(OrchestrationTaskFilter::default()))- .collect();- log::trace!(- "[running_subagents] task_records loaded records={} parent_session_filter={:?}",- all.len(),- parent_session- );- match parent_session {- Some(ps) => all- .into_iter()- .filter(|r| r.spec.metadata.get("parentSession").map(String::as_str) == Some(ps))- .collect(),- None => all,- }-}--/// Terminal/transient state of a running async sub-agent, published by the-/// spawner's background task and observed by `wait_subagent`.-#[derive(Debug, Clone)]-pub(crate) enum SubagentStatus {- /// Still executing its inner tool-call loop.- Running,- /// Finished normally with a final response.- Completed { output: String, iterations: usize },- /// Paused on `ask_user_clarification`; resume via `continue_subagent`.- AwaitingUser { question: String },- /// The run errored out.- Failed { error: String },-}--impl SubagentStatus {- fn is_terminal(&self) -> bool {- !matches!(self, SubagentStatus::Running)- }-}--#[derive(Clone)]-struct RunningSubagentMetadata {- agent_id: String,- subagent_session_id: Option<String>,- workspace_dir: PathBuf,- /// Parent chat thread that spawned this sub-agent, captured at registration.- /// `None` for a headless spawn with no originating thread. Used to abort the- /// sub-agent when its parent thread is deleted (see [`cancel_for_thread`]).- parent_thread_id: Option<String>,- run_queue: Arc<RunQueue>,-}--#[derive(Debug, Clone, PartialEq, Eq)]-pub(crate) struct SubagentResumeRef {- pub(crate) task_id: String,- pub(crate) agent_id: String,- pub(crate) subagent_session_id: Option<String>,-}--/// Soft cap on registry size. Terminal entries are only swept when the table-/// grows past this, so the common case (a handful of live sub-agents) never-/// evicts a still-uncollected terminal result out from under a `wait`/`steer`.-const REGISTRY_SOFT_CAP: usize = 256;-/// Metadata-only timeout mirrored into the TinyAgents task ledger. It matches-/// `wait_subagent`'s default wait window; execution remains governed by the-/// existing detached task and wait-tool paths.-const DETACHED_LEDGER_TIMEOUT_MS: u64 = 120_000;--static REGISTRY: OnceLock<DetachedTaskRegistry<RunningSubagentMetadata, SubagentStatus>> =- OnceLock::new();--fn registry() -> &'static DetachedTaskRegistry<RunningSubagentMetadata, SubagentStatus> {- REGISTRY.get_or_init(|| {- DetachedTaskRegistry::new(- shared_steering_registry().clone(),- REGISTRY_SOFT_CAP,- SubagentStatus::is_terminal,- )- })-}--/// Create the status channel a spawner threads into [`register`].-///-/// The spawner moves the [`watch::Sender`] into its detached task and `send`s a-/// terminal [`SubagentStatus`] on completion. Dropping the sender (e.g. a-/// panicked/aborted task) closes the channel, which `wait_subagent` surfaces as-/// a failure rather than hanging.-pub(crate) fn status_channel() -> (- watch::Sender<SubagentStatus>,- watch::Receiver<SubagentStatus>,-) {- watch::channel(SubagentStatus::Running)-}--/// Register a running async sub-agent so it can be steered and waited on.-///-/// Call this *after* `tokio::spawn` so the [`AbortHandle`] is available; the-/// task owns the matching [`watch::Sender`] from [`status_channel`]. Once the-/// table passes [`REGISTRY_SOFT_CAP`], registration sweeps already-terminal-/// entries so it stays bounded even if a parent never calls `wait_subagent`.-pub(crate) fn register(- task_id: String,- agent_id: String,- parent_session: String,- session_parent_prefix: Option<String>,- subagent_session_id: Option<String>,- workspace_dir: PathBuf,- parent_thread_id: Option<String>,- run_queue: Arc<RunQueue>,- abort: AbortHandle,- status: watch::Receiver<SubagentStatus>,-) {- // Typed lifecycle ledger: record the spawn and mirror the child's terminal- // status into the store via a lightweight watcher (issue #4249). Done before- // the entry is moved into the map so the metadata is still in scope.- record_spawned(- &task_id,- &agent_id,- &parent_session,- session_parent_prefix.as_deref(),- subagent_session_id.as_deref(),- &workspace_dir,- parent_thread_id.as_deref(),- );- spawn_status_watcher(task_id.clone(), workspace_dir.clone(), status.clone());-- let metadata = RunningSubagentMetadata {- agent_id,- subagent_session_id,- workspace_dir,- parent_thread_id,- run_queue,- };- registry()- .register(- TaskId::new(task_id.clone()),- parent_session,- metadata,- status,- // Cooperative cancellation is flipped before the registry invokes- // the hard abort. The child executor can adopt this token without- // changing the registry/control API.- CancellationToken::new(),- abort,- )- .expect("duplicate detached sub-agent task id");- log::debug!(- "[running_subagents] registered task_id={} live_entries={}",- task_id,- registry()- .len()- .expect("detached task registry lock poisoned")- );-}--/// Watch a child's status channel and mirror the first terminal status into the-/// typed lifecycle store. A dropped sender (aborted/panicked task) without a-/// terminal status is recorded as a failure, matching [`wait`].-fn spawn_status_watcher(- task_id: String,- workspace_dir: PathBuf,- mut status: watch::Receiver<SubagentStatus>,-) {- tokio::spawn(async move {- loop {- let snapshot = status.borrow_and_update().clone();- if snapshot.is_terminal() {- record_status(&workspace_dir, &task_id, &snapshot);- break;- }- if status.changed().await.is_err() {- record_status(- &workspace_dir,- &task_id,- &SubagentStatus::Failed {- error: "sub-agent task ended without reporting a result".to_string(),- },- );- break;- }- }- });-}--/// Compact, read-only view of one registered sub-agent, for ambient injection-/// into a parent's turn context (see [`active_subagents_context_block`]).-#[derive(Debug, Clone)]-pub(crate) struct SubagentSnapshot {- /// Worker *type* (e.g. `researcher`). Not unique — two parallel researchers- /// share this; disambiguate on `subagent_session_id` / `task_id`.- pub(crate) agent_id: String,- /// Durable, stable per-worker reference the prompt steers/waits/closes by.- pub(crate) subagent_session_id: Option<String>,- /// Transient registry key.- pub(crate) task_id: String,- /// Stable status label: `running` / `awaiting_user` / `completed` / `failed`.- pub(crate) status: &'static str,-}--/// Snapshot the sub-agents registered under `parent_session`, with each status-/// read live from its watch channel. Read-only: it takes the registry lock only-/// long enough to clone out the small summaries, never blocks on a child, and-/// never mutates the table. Ordered by `agent_id` then `task_id` so the rendered-/// roster is stable across turns (the underlying map is unordered).-pub(crate) fn snapshot_for_parent(parent_session: &str) -> Vec<SubagentSnapshot> {- let mut out: Vec<SubagentSnapshot> = registry()- .snapshots(Some(parent_session))- .expect("detached task registry lock poisoned")- .into_iter()- .map(|entry| {- let status = match &entry.status {- SubagentStatus::Running => "running",- SubagentStatus::Completed { .. } => "completed",- SubagentStatus::AwaitingUser { .. } => "awaiting_user",- SubagentStatus::Failed { .. } => "failed",- };- SubagentSnapshot {- agent_id: entry.metadata.agent_id,- subagent_session_id: entry.metadata.subagent_session_id,- task_id: entry.task_id.as_str().to_string(),- status,- }- })- .collect();- out.sort_by(|a, b| {- a.agent_id- .cmp(&b.agent_id)- .then_with(|| a.task_id.cmp(&b.task_id))- });- out-}--/// Most-recent durable sessions surfaced in the roster when they are not in-/// the live registry (cold boot / later turn). Bounds prompt growth on-/// threads with a long delegation history.-const DURABLE_ROSTER_CAP: usize = 12;diff --git a/crates/openhuman-core/src/agent/orchestration/running_subagents_part_02.rs b/crates/openhuman-core/src/agent/orchestration/running_subagents_part_02.rsdeleted file mode 100644index b0d7d50ee2..0000000000--- a/crates/openhuman-core/src/agent/orchestration/running_subagents_part_02.rs+++ /dev/null@@ -1,653 +0,0 @@--/// Build the ambient `[active_subagents]` block prepended to a parent's turn-/// context. Returns `None` when the parent owns no sub-agents at all, so the-/// block only appears when it is actionable — turns for agents that never-/// spawn are untouched. Mirrors the thread-goal `[active_goal]` block: it-/// rides the per-turn context (not the cached system-prompt prefix), so it-/// reflects live status every turn.-///-/// The roster merges two sources:-/// 1. the in-memory registry (live async workers spawned this process), and-/// 2. the durable per-workspace `subagent_sessions` store — workers from-/// EARLIER turns / process lifetimes. Without this second source a-/// cold-booted parent had no idea its previous sub-agents existed and-/// would re-delegate from scratch instead of resuming by-/// `subagent_session_id` (the "fresh context from day 0" bug).-pub(crate) fn active_subagents_context_block(- parent_session: &str,- workspace_dir: &std::path::Path,-) -> Option<String> {- let workers = snapshot_for_parent(parent_session);-- // Durable sessions not already represented by a live registry entry.- let live_session_ids: std::collections::HashSet<String> = workers- .iter()- .filter_map(|w| w.subagent_session_id.clone())- .collect();- let store = crate::agent::orchestration::subagent_sessions::SubagentSessionStore {- workspace_dir: workspace_dir.to_path_buf(),- };- let durable: Vec<_> =- match crate::agent::orchestration::subagent_sessions::list_for_parent(- &store,- parent_session,- None,- ) {- Ok(sessions) => sessions- .into_iter()- .filter(|s| {- use crate::agent::orchestration::subagent_sessions::DurableSubagentStatus;- s.status != DurableSubagentStatus::Closed- && !live_session_ids.contains(&s.subagent_session_id)- })- .take(DURABLE_ROSTER_CAP)- .collect(),- Err(err) => {- log::warn!(- "[running_subagents] durable roster load failed parent_session={parent_session} error={err}"- );- Vec::new()- }- };-- if workers.is_empty() && durable.is_empty() {- return None;- }- let mut block = format!(- "[active_subagents]\n\- You have {} sub-agent worker(s) for this conversation (live and/or from earlier \- turns). This is your authoritative roster — trust it over memory. Track each by \- subagent_session_id; use wait_subagent to collect a `completed` one, steer_subagent \- to redirect a `running` one, continue_subagent to answer an `awaiting_user` one or \- to RESUME an `idle` one with a follow-up (it keeps its full prior context — do NOT \- re-delegate the same task from scratch), close_subagent when done, and \- list_subagents to re-enumerate. Never fabricate a result for a worker still running \- or one that has failed.\n",- workers.len() + durable.len()- );- for w in &workers {- let session = w.subagent_session_id.as_deref().unwrap_or("(none)");- block.push_str(&format!(- "- {} · session={} · task={} · status={}\n",- w.agent_id, session, w.task_id, w.status- ));- }- for s in &durable {- use crate::agent::orchestration::subagent_sessions::DurableSubagentStatus;- let status = match s.status {- DurableSubagentStatus::Running => "running",- DurableSubagentStatus::Idle => "idle",- DurableSubagentStatus::AwaitingUser => "awaiting_user",- DurableSubagentStatus::Failed => "failed",- DurableSubagentStatus::Closed => "closed",- };- let task = s.current_task_id.as_deref().unwrap_or("(none)");- block.push_str(&format!(- "- {} · session={} · task={} · status={} · about: {}\n",- s.agent_id, s.subagent_session_id, task, status, s.task_title- ));- }- block.push_str("[/active_subagents]\n\n");- Some(block)-}--/// Resolve a durable `subagent_session_id` to the currently-running transient-/// `task_id`, enforcing parent-session ownership.-pub(crate) fn task_id_for_session(- subagent_session_id: &str,- parent_session: &str,-) -> Result<String, WaitError> {- let mut saw_unowned = false;- let mut owned_terminal: Option<String> = None;- for snapshot in registry()- .snapshots(None)- .expect("detached task registry lock poisoned")- .into_iter()- .filter(|snapshot| {- snapshot.metadata.subagent_session_id.as_deref() == Some(subagent_session_id)- })- {- if snapshot.owner_id != parent_session {- saw_unowned = true;- continue;- }- let task_id = snapshot.task_id.as_str().to_string();- if !snapshot.status.is_terminal() {- return Ok(task_id);- }- owned_terminal.get_or_insert(task_id);- }- if let Some(task_id) = owned_terminal {- return Ok(task_id);- }- if saw_unowned {- return Err(WaitError::NotOwned);- }- Err(WaitError::Unknown)-}--pub(crate) fn task_id_for_session_in_workspace(- subagent_session_id: &str,- parent_session: &str,- workspace_dir: &Path,-) -> Result<String, WaitError> {- match task_id_for_session(subagent_session_id, parent_session) {- Ok(task_id) => return Ok(task_id),- Err(WaitError::NotOwned) => return Err(WaitError::NotOwned),- Err(WaitError::Unknown) => {}- }-- let mut saw_unowned = false;- let mut matches: Vec<OrchestrationTaskRecord> = list_task_records(workspace_dir)- .into_iter()- .filter(|record| record_subagent_session_id(record) == Some(subagent_session_id))- .collect();- matches.sort_by_key(|item| std::cmp::Reverse(item.updated_at));-- for record in matches {- if record_parent_session(&record) != Some(parent_session) {- saw_unowned = true;- continue;- }- let task_id = record.spec.task_id.as_str().to_string();- log::debug!(- "[running_subagents] resolved session from task store subagent_session_id={} task_id={} workspace_dir={}",- subagent_session_id,- task_id,- workspace_dir.display()- );- return Ok(task_id);- }- if saw_unowned {- return Err(WaitError::NotOwned);- }- Err(WaitError::Unknown)-}--pub(crate) fn resume_ref_for_task(- task_id: &str,- parent_session: &str,-) -> Result<SubagentResumeRef, WaitError> {- let snapshot = registry()- .snapshot(&TaskId::new(task_id), parent_session)- .map_err(wait_error_from_registry)?;- Ok(SubagentResumeRef {- task_id: task_id.to_string(),- agent_id: snapshot.metadata.agent_id,- subagent_session_id: snapshot.metadata.subagent_session_id,- })-}--pub(crate) fn resume_ref_for_task_in_workspace(- task_id: &str,- parent_session: &str,- workspace_dir: &Path,-) -> Result<SubagentResumeRef, WaitError> {- match resume_ref_for_task(task_id, parent_session) {- Ok(reference) => return Ok(reference),- Err(WaitError::NotOwned) => return Err(WaitError::NotOwned),- Err(WaitError::Unknown) => {}- }-- let record = task_record_for_task_in_workspace(workspace_dir, task_id, parent_session)?;- log::debug!(- "[running_subagents] resolved resume ref from task store task_id={} workspace_dir={}",- task_id,- workspace_dir.display()- );- Ok(SubagentResumeRef {- task_id: task_id.to_string(),- agent_id: record_agent_id(&record),- subagent_session_id: record_subagent_session_id(&record).map(ToOwned::to_owned),- })-}--/// Why a steer could not be delivered.-#[derive(Debug, PartialEq, Eq)]-pub enum SteerError {- /// No such sub-agent — never existed, or already finished and pruned.- Unknown,- /// The caller's `parent_session` does not own this sub-agent.- NotOwned,- /// The sub-agent already reached a terminal status.- AlreadyDone,-}--fn steering_command_for_mode(mode: QueueMode, text: String) -> Option<SteeringCommand> {- match mode {- QueueMode::Steer => Some(SteeringCommand::InjectMessage(TaMessage::user(format!(- "[User steering message]: {text}"- )))),- QueueMode::Collect => Some(SteeringCommand::InjectMessage(TaMessage::user(format!(- "[Additional context from user]: {text}"- )))),- QueueMode::Interrupt | QueueMode::Followup | QueueMode::Parallel => None,- }-}--fn send_registered_steering(- handle: &tinyagents_harness::steering::SteeringHandle,- text: String,- mode: QueueMode,-) -> bool {- let Some(command) = steering_command_for_mode(mode, text) else {- return false;- };- handle.send(command);- true-}--/// Crate-native steering directives beyond the `InjectMessage`/collect lanes.-///-/// These map 1:1 onto the tinyagents [`SteeringCommand`] control variants that-/// the crate exposes (`Redirect`, `Pause`, `Resume`, `Cancel`). They are-/// delivered **only** through a registered [`SteeringHandle`] and therefore land-/// only at a safe loop boundary (the crate drains before each model call) —-/// never mid-stream, and never through the `RunQueue` fallback (which has no-/// equivalent lane). Approval/security is never bypassed: `Redirect` lowers to a-/// system instruction the normal approval-gated loop still governs, and-/// `Pause`/`Resume`/`Cancel` are pure control-flow.-///-/// The crate's `SetMetadata` command is intentionally *not* mapped here: no-/// OpenHuman control surface owns run-metadata mutation yet.-#[derive(Debug, Clone, PartialEq, Eq)]-pub(crate) enum SteeringDirective {- /// Redirect the run toward a new instruction (`SteeringCommand::Redirect`).- Redirect(String),- /// Cooperatively pause at the next checkpoint (`SteeringCommand::Pause`).- Pause,- /// Clear a pending pause (`SteeringCommand::Resume`).- Resume,- /// Cooperatively terminate at the next checkpoint (`SteeringCommand::Cancel`) —- /// a graceful, safe-boundary alternative to the hard `AbortHandle` cancel.- Cancel,-}--impl SteeringDirective {- fn kind(&self) -> SteeringCommandKind {- match self {- SteeringDirective::Redirect(_) => SteeringCommandKind::Redirect,- SteeringDirective::Pause => SteeringCommandKind::Pause,- SteeringDirective::Resume => SteeringCommandKind::Resume,- SteeringDirective::Cancel => SteeringCommandKind::Cancel,- }- }-- fn into_command(self) -> SteeringCommand {- match self {- SteeringDirective::Redirect(instruction) => SteeringCommand::Redirect { instruction },- SteeringDirective::Pause => SteeringCommand::Pause,- SteeringDirective::Resume => SteeringCommand::Resume,- SteeringDirective::Cancel => SteeringCommand::Cancel,- }- }-}--/// Why a crate-native steering directive could not be delivered.-#[derive(Debug, PartialEq, Eq)]-pub(crate) enum SteerDirectiveError {- /// No such sub-agent — never existed, or already finished and pruned.- Unknown,- /// The caller's `parent_session` does not own this sub-agent.- NotOwned,- /// The sub-agent already reached a terminal status.- AlreadyDone,- /// The sub-agent has no live crate-native `SteeringHandle` registered- /// (e.g. a legacy `RunQueue`-only run), so control-flow steering that has no- /// `RunQueue` lane cannot be delivered.- NoRegisteredHandle,- /// The run's [`SteeringPolicy`] does not permit this directive's command- /// kind. Enqueuing it anyway would abort the run with- /// `TinyAgentsError::Steering`, so we refuse up front.- PolicyRejected,-}--/// Deliver a crate-native control-flow [`SteeringDirective`] to a running-/// sub-agent through its registered TinyAgents [`SteeringHandle`].-///-/// Unlike [`steer`], this has **no** `RunQueue` fallback: the crate control-/// variants (`Redirect`/`Pause`/`Resume`/`Cancel`) have no OpenHuman queue lane,-/// so a run must have a live registered handle to receive them. The directive's-/// command kind is checked against the run's own `SteeringPolicy` *before*-/// enqueue — a disallowed command would otherwise abort the run — so this can-/// never smuggle a control kind past a policy that a tighter run class installed.-pub(crate) fn steer_directive(- task_id: &str,- parent_session: &str,- directive: SteeringDirective,-) -> Result<(), SteerDirectiveError> {- let handle = registry()- .steering_handle(&TaskId::new(task_id), parent_session)- .map_err(steer_directive_error_from_registry)?;- let kind = directive.kind();- if !handle.policy().is_allowed(kind) {- log::warn!(- "[running_subagents] directive rejected by run policy task_id={} kind={}",- task_id,- kind.as_str()- );- return Err(SteerDirectiveError::PolicyRejected);- }- handle.send(directive.into_command());- log::info!(- "[running_subagents] steered task_id={} directive={} via=tinyagents_registry",- task_id,- kind.as_str()- );- Ok(())-}--/// Inject a message into a running sub-agent. Prefer the crate-native-/// TinyAgents steering registry when the child run has registered its live-/// handle, and fall back to the OpenHuman `RunQueue` compatibility path.-pub async fn steer(- task_id: &str,- parent_session: &str,- text: String,- mode: QueueMode,-) -> Result<(), SteerError> {- let task_id_key = TaskId::new(task_id);- let snapshot = registry()- .snapshot(&task_id_key, parent_session)- .map_err(steer_error_from_registry)?;- if snapshot.status.is_terminal() {- return Err(SteerError::AlreadyDone);- }-- let steered_via_registry = registry()- .steering_handle(&task_id_key, parent_session)- .map(|handle| send_registered_steering(&handle, text.clone(), mode))- .unwrap_or(false);- if steered_via_registry {- log::info!(- "[running_subagents] steered task_id={} mode={} via=tinyagents_registry",- task_id,- mode- );- return Ok(());- }-- snapshot- .metadata- .run_queue- .push(QueuedMessage {- text,- mode,- client_id: "steer_subagent".to_string(),- thread_id: task_id.to_string(),- queued_at_ms: now_ms(),- model_override: None,- temperature: None,- profile_id: None,- locale: None,- })- .await;- log::info!(- "[running_subagents] steered task_id={} mode={}",- task_id,- mode- );- Ok(())-}--/// Trusted-control variant used by JSON-RPC sub-agent controls.-///-/// This intentionally does not require the caller to provide `parent_session`:-/// the RPC layer is already bearer-protected and mirrors the existing-/// `subagent_cancel` control surface, which can abort a task by id. The function-/// still refuses unknown or terminal tasks and never logs the steered text.-pub(crate) async fn steer_control(- task_id: &str,- text: String,- mode: QueueMode,-) -> Result<(), SteerError> {- let task_id_key = TaskId::new(task_id);- let snapshot = registry()- .snapshot_trusted(&task_id_key)- .map_err(steer_error_from_registry)?;- if snapshot.status.is_terminal() {- return Err(SteerError::AlreadyDone);- }-- let steered_via_registry = registry()- .steering_handle_trusted(&task_id_key)- .map(|handle| send_registered_steering(&handle, text.clone(), mode))- .unwrap_or(false);- if steered_via_registry {- log::info!(- "[running_subagents] control_steered task_id={} mode={} via=tinyagents_registry",- task_id,- mode- );- return Ok(());- }-- snapshot- .metadata- .run_queue- .push(QueuedMessage {- text,- mode,- client_id: "subagent_control_rpc".to_string(),- thread_id: task_id.to_string(),- queued_at_ms: now_ms(),- model_override: None,- temperature: None,- profile_id: None,- locale: None,- })- .await;- log::info!(- "[running_subagents] control_steered task_id={} mode={}",- task_id,- mode- );- Ok(())-}--/// Why a wait could not be set up.-#[derive(Debug, PartialEq, Eq)]-pub(crate) enum WaitError {- Unknown,- NotOwned,-}--fn wait_error_from_registry(error: DetachedTaskRegistryError) -> WaitError {- match error {- DetachedTaskRegistryError::NotOwned => WaitError::NotOwned,- _ => WaitError::Unknown,- }-}--fn steer_error_from_registry(error: DetachedTaskRegistryError) -> SteerError {- match error {- DetachedTaskRegistryError::NotOwned => SteerError::NotOwned,- DetachedTaskRegistryError::AlreadyDone => SteerError::AlreadyDone,- _ => SteerError::Unknown,- }-}--fn steer_directive_error_from_registry(error: DetachedTaskRegistryError) -> SteerDirectiveError {- match error {- DetachedTaskRegistryError::NotOwned => SteerDirectiveError::NotOwned,- DetachedTaskRegistryError::AlreadyDone => SteerDirectiveError::AlreadyDone,- DetachedTaskRegistryError::NoSteeringHandle => SteerDirectiveError::NoRegisteredHandle,- _ => SteerDirectiveError::Unknown,- }-}--/// Result of waiting on a sub-agent.-#[derive(Debug)]-pub(crate) enum WaitOutcome {- /// The sub-agent reached a terminal status (entry pruned).- Terminal(SubagentStatus),- /// The timeout elapsed first; the entry is left intact so the parent can- /// wait again. Carries the latest (non-terminal) status snapshot.- TimedOut(SubagentStatus),-}--/// Block until `task_id` reaches a terminal status or `timeout` elapses.-pub(crate) async fn wait(- task_id: &str,- parent_session: &str,- timeout: Duration,-) -> Result<WaitOutcome, WaitError> {- match registry()- .wait(&TaskId::new(task_id), parent_session, timeout)- .await- {- Ok(DetachedTaskWaitOutcome::Terminal(status)) => Ok(WaitOutcome::Terminal(status)),- Ok(DetachedTaskWaitOutcome::TimedOut(status)) => Ok(WaitOutcome::TimedOut(status)),- Err(DetachedTaskRegistryError::StatusChannelClosed) => {- Ok(WaitOutcome::Terminal(SubagentStatus::Failed {- error: "sub-agent task ended without reporting a result".to_string(),- }))- }- Err(error) => Err(wait_error_from_registry(error)),- }-}--pub(crate) async fn wait_in_workspace(- task_id: &str,- parent_session: &str,- workspace_dir: &Path,- timeout: Duration,-) -> Result<WaitOutcome, WaitError> {- match wait(task_id, parent_session, timeout).await {- Ok(outcome) => return Ok(outcome),- Err(WaitError::NotOwned) => return Err(WaitError::NotOwned),- Err(WaitError::Unknown) => {}- }-- let record = task_record_for_task_in_workspace(workspace_dir, task_id, parent_session)?;- log::debug!(- "[running_subagents] resolved wait from task store task_id={} status={} workspace_dir={}",- task_id,- task_status_label(record.status),- workspace_dir.display()- );- Ok(record_to_status(record))-}--/// Metadata captured when a sub-agent is cancelled, so the caller can surface-/// the cancellation back in the parent chat (record a "cancelled" completion-/// for idle-gated delivery).-#[derive(Debug, Clone, PartialEq, Eq)]-pub(crate) struct CancelledSubagent {- pub(crate) agent_id: String,- pub(crate) parent_session: String,- pub(crate) subagent_session_id: Option<String>,- pub(crate) workspace_dir: PathBuf,- pub(crate) parent_thread_id: Option<String>,-}--/// Abort and drop the sub-agent with `task_id`, returning its metadata so the-/// caller can deliver a "cancelled" notice into the parent chat. Returns `None`-/// if no such sub-agent is registered (already finished, or unknown id).-///-/// Unlike the parent-session-owned steering and close paths, this is keyed by-/// `task_id` alone with no ownership check — it backs the user-facing "Cancel"-/// affordance, and the desktop user owns every sub-agent in their own core.-pub(crate) fn cancel_by_task(task_id: &str) -> Option<CancelledSubagent> {- let cancelled = registry().cancel_trusted(&TaskId::new(task_id)).ok()?;- let metadata = cancelled.metadata;- record_cancelled(&metadata.workspace_dir, task_id);- log::debug!(- "[running_subagents] cancel_by_task task_id={} agent_id={} parent_thread_id={:?} live_entries={}",- task_id,- metadata.agent_id,- metadata.parent_thread_id,- registry()- .len()- .expect("detached task registry lock poisoned")- );- Some(CancelledSubagent {- agent_id: metadata.agent_id,- parent_session: cancelled.owner_id,- subagent_session_id: metadata.subagent_session_id,- workspace_dir: metadata.workspace_dir,- parent_thread_id: metadata.parent_thread_id,- })-}--pub(crate) fn cancel_by_session(- subagent_session_id: &str,- parent_session: &str,-) -> Option<CancelledSubagent> {- let task_id = task_id_for_session(subagent_session_id, parent_session).ok()?;- cancel_by_task(&task_id)-}--pub(crate) fn cancel_by_session_in_workspace(- subagent_session_id: &str,- parent_session: &str,- workspace_dir: &Path,-) -> Option<CancelledSubagent> {- let task_id =- task_id_for_session_in_workspace(subagent_session_id, parent_session, workspace_dir)- .ok()?;- cancel_by_task(&task_id)-}--/// Abort and drop every running sub-agent whose parent chat thread is-/// `thread_id`. Called when that thread is deleted so detached children don't-/// keep running (and later try to deliver) against a thread that no longer-/// exists. Returns the number of sub-agents cancelled.-pub(crate) fn cancel_for_thread(thread_id: &str) -> usize {- let cancelled = registry()- .cancel_where(|metadata| metadata.parent_thread_id.as_deref() == Some(thread_id))- .expect("detached task registry lock poisoned");- for entry in &cancelled {- record_cancelled(&entry.metadata.workspace_dir, entry.task_id.as_str());- }- let count = cancelled.len();- log::debug!(- "[running_subagents] cancel_for_thread thread_id={} cancelled={} live_entries={}",- thread_id,- count,- registry()- .len()- .expect("detached task registry lock poisoned")- );- count-}--/// Abort and drop **every** registered sub-agent. Called on a full thread purge-/// where no parent thread survives. Returns the **distinct parent thread ids**-/// that had sub-agents, so the purge path can tombstone them in-/// [`super::background_completions`] and drop any straggler completion that wins-/// the cooperative-abort race. Headless sub-agents (no parent thread) are still-/// aborted but contribute no id.-pub(crate) fn cancel_all() -> Vec<String> {- let cancelled = registry()- .cancel_all()- .expect("detached task registry lock poisoned");- let count = cancelled.len();- let mut thread_ids: Vec<String> = Vec::new();- let mut seen: HashSet<String> = HashSet::new();- for entry in cancelled {- record_cancelled(&entry.metadata.workspace_dir, entry.task_id.as_str());- if let Some(thread_id) = entry.metadata.parent_thread_id {- if seen.insert(thread_id.clone()) {- thread_ids.push(thread_id);- }- }- }- log::debug!(- "[running_subagents] cancel_all cancelled={} distinct_threads={}",- count,- thread_ids.len()- );- thread_ids-}--fn prune(task_id: &str) {- let _ = registry().cancel_trusted(&TaskId::new(task_id));-}--fn now_ms() -> u64 {- std::time::SystemTime::now()- .duration_since(std::time::UNIX_EPOCH)- .map(|d| d.as_millis() as u64)- .unwrap_or(0)-}