Skip to content

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

refactor(agent): delete cancellation task local

Steven Enamakelb61713d2bfcc
diff --git a/crates/openhuman-core/src/agent/orchestration/tools.rs b/crates/openhuman-core/src/agent/orchestration/tools.rs
index 31f234cde8..d74cf81882 100644
--- a/crates/openhuman-core/src/agent/orchestration/tools.rs
+++ b/crates/openhuman-core/src/agent/orchestration/tools.rs
@@ -74,6 +74,7 @@ pub use delegate_graph::DelegateGraphTool;
pub use list_subagents::ListSubagentsTool;
pub use skill_delegation::{SkillDelegationTool, INTEGRATIONS_DELEGATE_TOOL_NAME};
pub use spawn_async_subagent::SpawnAsyncSubagentTool;
+pub(crate) use spawn_parallel_agents::SpawnParallelAgentsDispatch;
pub use spawn_parallel_agents::SpawnParallelAgentsTool;
pub use spawn_subagent::SpawnSubagentTool;
pub use spawn_worker_thread::SpawnWorkerThreadTool;
diff --git a/crates/openhuman-core/src/agent/orchestration/tools/spawn_parallel_agents.rs b/crates/openhuman-core/src/agent/orchestration/tools/spawn_parallel_agents.rs
index 26c721eec2..a9cf1cd22f 100644
--- a/crates/openhuman-core/src/agent/orchestration/tools/spawn_parallel_agents.rs
+++ b/crates/openhuman-core/src/agent/orchestration/tools/spawn_parallel_agents.rs
@@ -13,9 +13,11 @@ use crate::agent::orchestration::spawn_parallel_graph::{
format_spawn_parallel_success, run_spawn_parallel_graph_with_cancellation_and_workspace,
SpawnParallelGraphOutcome, SpawnParallelTaskValidationError,
};
-use crate::agent::tinyagents::current_run_cancellation;
use async_trait::async_trait;
use serde_json::json;
+use std::sync::Arc;
+use tinyagents_harness::context::RunContext;
+use tinyagents_harness::tool::ToolDispatch;
use tinytools::ToolRunContext;
use tinytools::{PermissionLevel, Tool, ToolCallOptions, ToolResult, ToolTimeout};
@@ -33,6 +35,91 @@ impl Default for SpawnParallelAgentsTool {
}
}
+/// Typed-parent dispatch for `spawn_parallel_agents`.
+///
+/// The canonical `Tool` declaration remains usable for schema, policy, and
+/// capability registration, while this dispatch is the only harness execution
+/// path. It receives the live parent run rather than recovering cancellation
+/// from a task-local, so nested graph fan-out observes the exact parent token
+/// and workspace grant.
+pub(crate) struct SpawnParallelAgentsDispatch {
+ tool: Arc<dyn Tool>,
+}
+
+impl SpawnParallelAgentsDispatch {
+ pub(crate) fn new(tool: Arc<dyn Tool>) -> Self {
+ Self { tool }
+ }
+}
+
+#[async_trait]
+impl ToolDispatch<(), crate::agent::tinyagents::host::OpenHumanRunContext>
+ for SpawnParallelAgentsDispatch
+{
+ fn tool(&self) -> Arc<dyn Tool> {
+ self.tool.clone()
+ }
+
+ async fn execute(
+ &self,
+ _state: &(),
+ arguments: serde_json::Value,
+ _options: ToolCallOptions,
+ parent: &RunContext<crate::agent::tinyagents::host::OpenHumanRunContext>,
+ ) -> anyhow::Result<ToolResult> {
+ execute_spawn_parallel_agents(
+ arguments,
+ parent.cancellation.clone(),
+ parent.workspace.clone(),
+ )
+ .await
+ }
+}
+
+/// Executes the graph from explicitly supplied parent-run values.
+///
+/// This is shared by the typed harness dispatch and standalone tool execution;
+/// neither path consults ambient run state.
+pub(crate) async fn execute_spawn_parallel_agents(
+ args: serde_json::Value,
+ cancellation: tinyagents_harness::CancellationToken,
+ workspace_descriptor: Option<tinytools::WorkspaceDescriptor>,
+) -> anyhow::Result<ToolResult> {
+ tracing::debug!("[spawn_parallel_agents] execute entry");
+ let outcome = run_spawn_parallel_graph_with_cancellation_and_workspace(
+ args,
+ cancellation,
+ workspace_descriptor,
+ )
+ .await
+ .map_err(|e| anyhow::anyhow!(e))?;
+ match outcome {
+ SpawnParallelGraphOutcome::Collected(collected) => Ok(ToolResult::success(
+ format_spawn_parallel_success(&collected),
+ )),
+ SpawnParallelGraphOutcome::InvalidRequest(
+ SpawnParallelTaskValidationError::MissingTasks(message),
+ ) => {
+ tracing::debug!("[spawn_parallel_agents] missing_tasks_parameter");
+ Err(anyhow::anyhow!(message))
+ }
+ SpawnParallelGraphOutcome::InvalidRequest(
+ SpawnParallelTaskValidationError::InvalidTasks(message),
+ ) => {
+ tracing::debug!(error = %message, "[spawn_parallel_agents] invalid_tasks_array");
+ Err(anyhow::anyhow!(message))
+ }
+ SpawnParallelGraphOutcome::InvalidRequest(SpawnParallelTaskValidationError::Rejected(
+ message,
+ )) => {
+ tracing::debug!("[spawn_parallel_agents] rejected_too_few_tasks");
+ Ok(ToolResult::error(message))
+ }
+ SpawnParallelGraphOutcome::Rejected(message) => Ok(ToolResult::error(message)),
+ SpawnParallelGraphOutcome::Cancelled(message) => Ok(ToolResult::error(message)),
+ }
+}
+
#[async_trait]
impl Tool for SpawnParallelAgentsTool {
fn name(&self) -> &str {
@@ -120,46 +207,13 @@ impl Tool for SpawnParallelAgentsTool {
_options: ToolCallOptions,
tool_context: Option<&dyn ToolRunContext>,
) -> anyhow::Result<ToolResult> {
- tracing::debug!("[spawn_parallel_agents] execute entry");
let workspace_descriptor = tool_context.and_then(|ctx| ctx.workspace().cloned());
- let cancellation = current_run_cancellation().unwrap_or_else(|| {
- tracing::debug!(
- "[spawn_parallel_agents] no active tinyagents run cancellation token; using local token"
- );
- tinyagents_harness::CancellationToken::new()
- });
- let outcome = run_spawn_parallel_graph_with_cancellation_and_workspace(
+ execute_spawn_parallel_agents(
args,
- cancellation,
+ tinyagents_harness::CancellationToken::new(),
workspace_descriptor,
)
.await
- .map_err(|e| anyhow::anyhow!(e))?;
- match outcome {
- SpawnParallelGraphOutcome::Collected(collected) => Ok(ToolResult::success(
- format_spawn_parallel_success(&collected),
- )),
- SpawnParallelGraphOutcome::InvalidRequest(
- SpawnParallelTaskValidationError::MissingTasks(message),
- ) => {
- tracing::debug!("[spawn_parallel_agents] missing_tasks_parameter");
- Err(anyhow::anyhow!(message))
- }
- SpawnParallelGraphOutcome::InvalidRequest(
- SpawnParallelTaskValidationError::InvalidTasks(message),
- ) => {
- tracing::debug!(error = %message, "[spawn_parallel_agents] invalid_tasks_array");
- Err(anyhow::anyhow!(message))
- }
- SpawnParallelGraphOutcome::InvalidRequest(
- SpawnParallelTaskValidationError::Rejected(message),
- ) => {
- tracing::debug!("[spawn_parallel_agents] rejected_too_few_tasks");
- Ok(ToolResult::error(message))
- }
- SpawnParallelGraphOutcome::Rejected(message) => Ok(ToolResult::error(message)),
- SpawnParallelGraphOutcome::Cancelled(message) => Ok(ToolResult::error(message)),
- }
}
}
diff --git a/crates/openhuman-core/src/agent/orchestration/tools/spawn_parallel_agents_tests.rs b/crates/openhuman-core/src/agent/orchestration/tools/spawn_parallel_agents_tests.rs
index ee33be98d6..afd9c36a25 100644
--- a/crates/openhuman-core/src/agent/orchestration/tools/spawn_parallel_agents_tests.rs
+++ b/crates/openhuman-core/src/agent/orchestration/tools/spawn_parallel_agents_tests.rs
@@ -10,6 +10,7 @@ use crate::agent::orchestration::spawn_parallel_graph::{
WorkerDispatchMode,
};
use crate::agent::prompts::ToolCallFormat;
+use crate::agent::tinyagents::host::OpenHumanRunContext;
use crate::agent::Agent;
use crate::config::AgentConfig;
use crate::memory::{Memory, MemoryCategory, MemoryEntry, NamespaceSummary, RecallOpts};
@@ -21,8 +22,9 @@ use std::sync::{
atomic::{AtomicUsize, Ordering},
Arc,
};
+use tinyagents_harness::tool::ToolDispatch;
use tinyinference_llm::message::{AssistantMessage, Message};
-use tinyinference_llm::model::{ChatModel, ModelProfile, ModelRequest, ModelResponse};
+use tinyinference_llm::model::{ChatModel, ModelProfile, ModelRequest, ModelResponse, ModelStream};
use tinyinference_llm::tool::ToolCall;
use tinytools::ToolTimeout;
use tinytools::{PermissionLevel, Tool, ToolResult};
@@ -154,6 +156,91 @@ fn parent_context_with_tools(
parent
}
+/// A child model that signals once fan-out has entered a worker, then remains
+/// in flight until the graph cancellation token drops its invocation future.
+struct BlockingFanoutModel {
+ started: Arc<tokio::sync::Notify>,
+}
+
+#[async_trait]
+impl ChatModel<()> for BlockingFanoutModel {
+ async fn invoke(
+ &self,
+ _state: &(),
+ _request: ModelRequest,
+ ) -> tinyinference_llm::Result<ModelResponse> {
+ self.started.notify_waiters();
+ std::future::pending().await
+ }
+
+ async fn stream(
+ &self,
+ _state: &(),
+ _request: ModelRequest,
+ ) -> tinyinference_llm::Result<ModelStream> {
+ panic!("the unobserved fan-out test must use unary model invocation")
+ }
+}
+
+/// The live harness does not recover cancellation from a task-local. Its typed
+/// dispatch receives the parent `RunContext`, so a token cancelled while a
+/// child worker is in flight stops the fan-out at its worker safe point with
+/// the same workspace grant.
+#[tokio::test]
+async fn typed_dispatch_uses_the_parent_token_for_fanout_cancellation() {
+ let _ = AgentDefinitionRegistry::init_global_builtins();
+ let cancellation = tinyagents_harness::CancellationToken::new();
+ let workspace = tinytools::WorkspaceDescriptor::new("/work/parent-action");
+ let started = Arc::new(tokio::sync::Notify::new());
+ let parent_run = OpenHumanRunContext::new()
+ .with_cancellation(cancellation.clone())
+ .with_workspace(workspace.clone())
+ .into_tinyagents(tinyagents_harness::context::RunConfig::new("parent"));
+ let dispatch = SpawnParallelAgentsDispatch::new(Arc::new(SpawnParallelAgentsTool::new()));
+ let mut parent = parent_context(4);
+ parent.turn_model_source =
+ crate::agent::tinyagents::TurnModelSource::from_model(Arc::new(BlockingFanoutModel {
+ started: started.clone(),
+ }));
+
+ let run = with_parent_context(parent, async {
+ dispatch
+ .execute(
+ &(),
+ json!({
+ "tasks": [
+ { "agent_id": "researcher", "prompt": "one" },
+ { "agent_id": "critic", "prompt": "two" }
+ ]
+ }),
+ tinytools::ToolCallOptions::default(),
+ &parent_run,
+ )
+ .await
+ });
+ tokio::pin!(run);
+ let worker_started = started.notified();
+ tokio::pin!(worker_started);
+ tokio::select! {
+ result = &mut run => panic!("fan-out completed before its worker entered: {result:?}"),
+ _ = &mut worker_started => {}
+ }
+
+ cancellation.cancel();
+ let result = timeout(Duration::from_secs(5), &mut run)
+ .await
+ .expect("cancelled fan-out must finish")
+ .expect("typed dispatch result");
+
+ assert_eq!(parent_run.workspace, Some(workspace));
+ assert!(result.is_error, "{}", result.output());
+ assert!(
+ result.output().contains("cancelled at worker"),
+ "typed dispatch must pass the parent token into fan-out: {}",
+ result.output()
+ );
+}
+
fn definition_with_tool_scope(
id: &str,
tools: ToolScope,
diff --git a/crates/openhuman-core/src/agent/tinyagents/README.md b/crates/openhuman-core/src/agent/tinyagents/README.md
index 40151b6565..237979b3fb 100644
--- a/crates/openhuman-core/src/agent/tinyagents/README.md
+++ b/crates/openhuman-core/src/agent/tinyagents/README.md
@@ -41,7 +41,7 @@ The **adapter seam** between OpenHuman and the vendored [`tinyagents`](../../../
| `payload_summarizer.rs` | `PayloadSummarizer` trait, `SummarizeOutcome`/`UnavailableReason`, and the default `SubagentPayloadSummarizer` that compresses oversized tool results through the `summarizer` sub-agent instead of hard-truncating them. |
| `policy_denial.rs` | `maybe_enrich_policy_block`: rewrites `[policy-blocked]` tool results into structured what/why/workaround messages that tell the model to relay the denial rather than fabricate output. Called from `ToolOutcomeCaptureMiddleware`. |
| `abort_guard.rs` | `AbortOnDrop`: ties a detached streaming-producer task's lifetime to its consumer stream so a dropped turn aborts the in-flight provider call (issue #4460). |
-| `run_cancellation_context.rs` | Task-local carrier for the current run's `CancellationToken`, for tools that fan out nested graph work. |
+| `host/run_context.rs` + typed tool dispatch | `OpenHumanRunContext` owns one root `CancellationToken`; child contexts share it and recursive tools receive it from their typed parent `RunContext`. |
| `steering_forwarder.rs` | `SteeringForwarderGuard`: forwards `RunQueue` steer/collect messages into the harness `SteeringHandle`; abort-on-drop so drop-based cancellation always deregisters it (issue #4456). |
| `stop_hooks.rs` | `StopHookMiddleware`: evaluates OpenHuman `StopHook`s after each model call and pauses the run via steering on the first `Stop` decision. |
| `summarize.rs` | `ModelSummarizer` / `FaultTolerantCachingSummarizer` plus a context-window-aware `SummarizationPolicy` driving the crate's `ContextCompressionMiddleware`. |
@@ -106,10 +106,10 @@ Responses project the crate's own `AgentObservation` and `HarnessRunStatus` serd
attachments, artifacts, dispatch, cancellation, thread, workspace and stop
hooks) across the OpenHuman turn boundary. The shared runner builds
`RunContext<OpenHumanRunContext>` with `into_tinyagents`, and the OpenHuman
-assembly plus middleware stack are specialized to that context. Route, thread,
-and cancellation task-local scopes remain only around the drive while legacy
-tool/model consumers still require them; they are seeded solely from the typed
-carrier.
+assembly plus middleware stack are specialized to that context. Route and
+thread task-local scopes remain only around the drive while legacy tool/model
+consumers still require them. Cancellation reaches recursive tools solely
+through the typed parent run.
## Notes
diff --git a/crates/openhuman-core/src/agent/tinyagents/harness_tool_registration.rs b/crates/openhuman-core/src/agent/tinyagents/harness_tool_registration.rs
index 76765da299..a4e0889dda 100644
--- a/crates/openhuman-core/src/agent/tinyagents/harness_tool_registration.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/harness_tool_registration.rs
@@ -11,6 +11,7 @@ use tinyagents_registry::{
CapabilityRegistry, ComponentKind, RegistryDiagnostic, RegistrySnapshot,
};
+use crate::agent::orchestration::tools::SpawnParallelAgentsDispatch;
use crate::agent::tinyagents::host::OpenHumanRunContext;
use crate::agent::tinyagents::tools::{CanonicalSharedToolAdapter, EarlyExitHook};
use crate::agent::tinyagents::turn_policy::is_subagent_spawn_or_delegate_tool;
@@ -91,7 +92,13 @@ pub(super) fn register_turn_tools_and_agents(
registered.insert(name.to_string());
let adapter = Arc::new(adapter);
capability_registry.replace_tool(adapter.clone());
- harness.register_tool(adapter);
+ if name == "spawn_parallel_agents" {
+ harness.register_tool_dispatch(Arc::new(SpawnParallelAgentsDispatch::new(
+ adapter,
+ )));
+ } else {
+ harness.register_tool(adapter);
+ }
}
}
}
diff --git a/crates/openhuman-core/src/agent/tinyagents/host/run_context.rs b/crates/openhuman-core/src/agent/tinyagents/host/run_context.rs
index 3e363223c4..94bd506f49 100644
--- a/crates/openhuman-core/src/agent/tinyagents/host/run_context.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/host/run_context.rs
@@ -93,9 +93,6 @@ impl OpenHumanRunContext {
context.stop_hooks = crate::agent::stop_hooks::current_stop_hooks();
context.dispatch = crate::agent::harness::turn_dispatch_guard::current();
context.thread_id = crate::agent::tinyagents::thread_context::current_thread_id();
- if let Some(cancellation) = crate::agent::tinyagents::current_run_cancellation() {
- context.cancellation = cancellation;
- }
context.workspace = crate::agent::turn_workspace::current()
.filter(|root| root.is_dir())
.map(|root| tinytools::WorkspaceDescriptor::new(root).with_policy_id("turn-workspace"));
diff --git a/crates/openhuman-core/src/agent/tinyagents/host/run_context_tests.rs b/crates/openhuman-core/src/agent/tinyagents/host/run_context_tests.rs
index 8760f40ef3..ecf97b7a2b 100644
--- a/crates/openhuman-core/src/agent/tinyagents/host/run_context_tests.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/host/run_context_tests.rs
@@ -68,7 +68,6 @@ async fn snapshots_scoped_stop_hooks_into_the_explicit_carrier() {
async fn snapshots_live_root_scopes_before_child_dispatch() {
let root = tempfile::tempdir().expect("workspace");
let (progress, _rx) = tokio::sync::mpsc::channel(1);
- let cancellation = tinyagents_harness::cancel::CancellationToken::new();
crate::agent::turn_origin::with_origin(
crate::agent::turn_origin::AgentTurnOrigin::Cli,
@@ -78,39 +77,28 @@ async fn snapshots_live_root_scopes_before_child_dispatch() {
progress.clone(),
crate::agent::tinyagents::thread_context::with_thread_id(
"thread-a",
- crate::agent::tinyagents::run_cancellation_context::with_run_cancellation(
- cancellation.clone(),
- crate::agent::harness::turn_dispatch_guard::with_dispatch_guard(
- None,
- async {
- let expected_dispatch =
- crate::agent::harness::turn_dispatch_guard::current()
- .expect("dispatch scope");
- let captured = OpenHumanRunContext::from_current_scopes();
- assert!(matches!(
- captured.origin,
- Some(crate::agent::turn_origin::AgentTurnOrigin::Cli)
- ));
- assert!(captured.progress.is_some());
- assert_eq!(captured.thread_id.as_deref(), Some("thread-a"));
- assert_eq!(
- captured.workspace.expect("workspace").root,
- root.path()
- );
- assert!(std::sync::Arc::ptr_eq(
- captured.dispatch.as_ref().expect("dispatch"),
- &expected_dispatch,
- ));
- assert!(captured
- .resolved_route
- .lock()
- .expect("route lock")
- .is_none());
- cancellation.cancel();
- assert!(captured.cancellation.is_cancelled());
- },
- ),
- ),
+ crate::agent::harness::turn_dispatch_guard::with_dispatch_guard(None, async {
+ let expected_dispatch =
+ crate::agent::harness::turn_dispatch_guard::current()
+ .expect("dispatch scope");
+ let captured = OpenHumanRunContext::from_current_scopes();
+ assert!(matches!(
+ captured.origin,
+ Some(crate::agent::turn_origin::AgentTurnOrigin::Cli)
+ ));
+ assert!(captured.progress.is_some());
+ assert_eq!(captured.thread_id.as_deref(), Some("thread-a"));
+ assert_eq!(captured.workspace.expect("workspace").root, root.path());
+ assert!(std::sync::Arc::ptr_eq(
+ captured.dispatch.as_ref().expect("dispatch"),
+ &expected_dispatch,
+ ));
+ assert!(captured
+ .resolved_route
+ .lock()
+ .expect("route lock")
+ .is_none());
+ }),
),
),
),
diff --git a/crates/openhuman-core/src/agent/tinyagents/mod.rs b/crates/openhuman-core/src/agent/tinyagents/mod.rs
index 15a93dd53c..999829b0bb 100644
--- a/crates/openhuman-core/src/agent/tinyagents/mod.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/mod.rs
@@ -49,7 +49,6 @@ pub(crate) mod reaper;
pub(crate) mod replay;
pub(crate) mod retriever;
mod routes;
-pub(crate) mod run_cancellation_context;
mod steering_forwarder;
pub(crate) mod stop_hooks;
mod summarize;
@@ -75,7 +74,6 @@ pub(crate) use middleware::{
TurnContextMiddleware,
};
pub(crate) use observability::SubagentScope;
-pub(crate) use run_cancellation_context::current_run_cancellation;
pub(crate) use topology::all_graph_topologies;
pub use turn_models::TurnModelSource;
pub(crate) use turn_models::TurnModels;
diff --git a/crates/openhuman-core/src/agent/tinyagents/run_cancellation_context.rs b/crates/openhuman-core/src/agent/tinyagents/run_cancellation_context.rs
deleted file mode 100644
index 60378fca8c..0000000000
--- a/crates/openhuman-core/src/agent/tinyagents/run_cancellation_context.rs
+++ /dev/null
@@ -1,27 +0,0 @@
-//! Task-local carrier for the current TinyAgents run cancellation token.
-//!
-//! TinyAgents keeps cooperative cancellation on `RunContext`, while the
-//! tool-visible `ToolExecutionContext` intentionally exposes only stable run
-//! metadata. OpenHuman tools that need to fan out nested graph work can read this
-//! scoped token and pass the same live cancellation signal into graph helpers.
-
-use tinyagents_harness::CancellationToken;
-
-tokio::task_local! {
- static CURRENT_RUN_CANCELLATION: CancellationToken;
-}
-
-/// Cancellation token for the current TinyAgents run, when executing inside the
-/// shared harness drive.
-pub(crate) fn current_run_cancellation() -> Option<CancellationToken> {
- CURRENT_RUN_CANCELLATION.try_with(Clone::clone).ok()
-}
-
-/// Run `future` with `token` installed as the current TinyAgents run
-/// cancellation signal.
-pub(crate) async fn with_run_cancellation<F, R>(token: CancellationToken, future: F) -> R
-where
- F: std::future::Future<Output = R>,
-{
- CURRENT_RUN_CANCELLATION.scope(token, future).await
-}
diff --git a/crates/openhuman-core/src/agent/tinyagents/turn_runner.rs b/crates/openhuman-core/src/agent/tinyagents/turn_runner.rs
index a3a9a5cf49..21b6f025a4 100644
--- a/crates/openhuman-core/src/agent/tinyagents/turn_runner.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/turn_runner.rs
@@ -29,7 +29,6 @@ use crate::agent::tinyagents::host::steering::shared_steering_registry;
use crate::agent::tinyagents::host::OpenHumanRunContext;
use crate::agent::tinyagents::middleware::TurnContextMiddleware;
use crate::agent::tinyagents::observability::{CapPauser, OpenhumanEventBridge, SubagentScope};
-use crate::agent::tinyagents::run_cancellation_context::with_run_cancellation;
use crate::agent::tinyagents::turn_models::TurnModels;
use crate::agent::tinyagents::turn_outcome::TinyagentsTurnOutcome;
use crate::agent::tinyagents::turn_policy::effective_max_iterations;
@@ -363,7 +362,6 @@ pub(crate) async fn run_turn_via_tinyagents_shared(
// Build the run context: an optional event sink feeds the progress/cost
// bridge (streaming) and/or the model-call-cap pauser; the shared steering
// handle carries mid-flight, early-exit, and cap pauses.
- let cancellation = run_context.cancellation.clone();
let mut run_context = run_context;
run_context.tool_result_artifact_index = tool_result_artifact_index.clone();
run_context.tool_outcomes = Some(tool_outcome_sink.clone());
@@ -580,41 +578,38 @@ pub(crate) async fn run_turn_via_tinyagents_shared(
// nested inside its parent's drive future — leaving it inline on the stack
// overflows when the parent + child drives compose. Boxing keeps only a
// pointer on the stack at each level.
- // Thread and cancellation scopes remain for legacy tool/model APIs outside
- // the typed TinyAgents surface. Route metadata is carried exclusively by
- // the typed run context and canonical model response.
+ // The legacy thread scope remains for APIs outside the typed TinyAgents
+ // surface. Cancellation is carried solely by the canonical run context and
+ // reaches recursive tools through typed parent dispatch. Route metadata is
+ // likewise carried by the typed run context and canonical model response.
let run_thread_id = run_context.thread_id.clone().unwrap_or_default();
let resolved_route_slot = run_context.resolved_route.clone();
let run_result =
crate::agent::tinyagents::thread_context::with_thread_id(run_thread_id, async move {
- with_run_cancellation(cancellation.clone(), async {
- if streaming {
- let mut stream = Box::pin(harness.invoke_stream_in_context(&(), ctx, input));
- let mut terminal = None;
- while let Some(item) = stream.next().await {
- match item {
- AgentStreamItem::Event(_) => {}
- AgentStreamItem::Completed(run) => {
- terminal = Some(Ok(*run));
- break;
- }
- AgentStreamItem::Failed { error, .. } => {
- terminal =
- Some(Err(tinyagents_harness::TinyAgentsError::Model(error)));
- break;
- }
+ if streaming {
+ let mut stream = Box::pin(harness.invoke_stream_in_context(&(), ctx, input));
+ let mut terminal = None;
+ while let Some(item) = stream.next().await {
+ match item {
+ AgentStreamItem::Event(_) => {}
+ AgentStreamItem::Completed(run) => {
+ terminal = Some(Ok(*run));
+ break;
+ }
+ AgentStreamItem::Failed { error, .. } => {
+ terminal = Some(Err(tinyagents_harness::TinyAgentsError::Model(error)));
+ break;
}
}
- terminal.unwrap_or_else(|| {
- Err(tinyagents_harness::TinyAgentsError::Model(
- "tinyagents stream ended without terminal run".to_string(),
- ))
- })
- } else {
- Box::pin(harness.invoke_in_context(&(), ctx, input)).await
}
- })
- .await
+ terminal.unwrap_or_else(|| {
+ Err(tinyagents_harness::TinyAgentsError::Model(
+ "tinyagents stream ended without terminal run".to_string(),
+ ))
+ })
+ } else {
+ Box::pin(harness.invoke_in_context(&(), ctx, input)).await
+ }
})
.await;
// Drive future returned: run cleanup now (abort poll task + deregister +
diff --git a/docs/plans/migrate-agent-runtime-to-tinyagents.md b/docs/plans/migrate-agent-runtime-to-tinyagents.md
index 28e6384711..09568099d9 100644
--- a/docs/plans/migrate-agent-runtime-to-tinyagents.md
+++ b/docs/plans/migrate-agent-runtime-to-tinyagents.md
@@ -225,7 +225,7 @@ observer. Replace reads of:
- `fork_context`, `sandbox_context`, `spawn_depth_context`,
`task_recency_context`, `turn_attachments_context`, `turn_dispatch_guard`,
`turn_subagent_usage`;
-- `progress_sink`, `resolved_route`, `run_cancellation_context`,
+- `progress_sink`, `resolved_route`,
`thread_context`, `turn_origin`, and `turn_workspace` task-local scopes.
Delete each task-local module once its final caller receives context directly.
diff --git a/docs/specs/agent-runtime-upstream-boundary.md b/docs/specs/agent-runtime-upstream-boundary.md
index a269425264..fb143e7cd1 100644
--- a/docs/specs/agent-runtime-upstream-boundary.md
+++ b/docs/specs/agent-runtime-upstream-boundary.md
@@ -149,7 +149,11 @@ vocabulary. `tinyagents-harness` must not expose a second public Tool trait or
ToolResult shape. Harness-only correlation (`call_id`, elapsed time, run id)
belongs to an internal invocation record/event, not the tool result.
-`AgentHarness::register_tool` accepts `Arc<dyn tinytools::Tool>`. The harness
+`AgentHarness::register_tool` accepts `Arc<dyn tinytools::Tool>`. A recursive
+canonical tool that needs its typed parent (for example OpenHuman's
+`spawn_parallel_agents`) uses `AgentHarness::register_tool_dispatch` and an
+explicit `ToolDispatch<State, Ctx>` instead of recovering state from a
+task-local. The harness
implements its execution context as `tinytools::ToolRunContext` and performs
injected-argument, timeout, cancellation, and event handling around the
canonical call. OpenHuman tools implement `tinytools::Tool` directly; the
@@ -324,7 +328,7 @@ all consumers import the owner directly, not that behavior is dropped.
| `payload_summarizer.rs`, `summarize.rs` | Move generic summarizer orchestration/trait to harness; OpenHuman model selection/config adapter stays. |
| `turn_policy.rs`, `turn_outcome.rs`, `turn_run_error.rs`, `turn_run_finalize.rs` | Move generic run policy/outcome/finalization upstream; retain product error/progress/cost projection only. |
| `turn_models.rs`, remaining `routes.rs` | Keep as `ModelResolver` implementation/config projection, then relocate under the host adapter rather than an integration facade. |
-| `thread_context.rs`, `run_cancellation_context.rs`, `stop_hooks.rs`, `steering_forwarder.rs` | Replace with explicit run/child context; keep only product stop-hook adapter. |
+| `thread_context.rs`, `stop_hooks.rs`, `steering_forwarder.rs` | Replace with explicit run/child context; keep only product stop-hook adapter. The former cancellation task-local is deleted: recursive fan-out receives the parent token through typed tool dispatch. |
| `orchestration.rs`, `delegation.rs`, `topology.rs` | Move generic lifecycle/helpers to graph; keep product topology composition only where it genuinely names product graphs. |
| `observability/*` | Keep OpenHuman projection (`AgentProgress`, cost, Langfuse); move reusable graph/event/cap mechanics upstream and import directly. |
| `journal.rs`, `reaper.rs`, `replay/*` | Keep because layout/RPC are product durability contracts; use upstream journal traits directly. |
diff --git a/gitbooks/developing/architecture/agent-harness.md b/gitbooks/developing/architecture/agent-harness.md
index 09687c5143..0317252059 100644
--- a/gitbooks/developing/architecture/agent-harness.md
+++ b/gitbooks/developing/architecture/agent-harness.md
@@ -490,15 +490,17 @@ When the backend doesn't surface a charged amount (older builds, providers that
`OpenHumanRunContext` is now the live carrier at the shared chat, channel, and
sub-agent turn seam. Roots snapshot their currently scoped origin, progress,
-stop hooks, dispatch state, thread, route slot, cancellation token, and workspace grant,
-then pass an owned context to the runner; a recursive sub-agent forks it with
+stop hooks, dispatch state, thread, route slot, and workspace grant, then own
+or explicitly receive one cancellation token before passing the context to the
+runner; a recursive sub-agent forks it with
`child()`, preserving shared cancellation/policy handles while isolating route
observation and usage accounting. The shared runner creates
`RunContext<OpenHumanRunContext>` through `into_tinyagents`, and the OpenHuman
assembly and middleware registry consume that typed context directly. Route,
-thread, and cancellation scopes still surround the drive only for legacy
-tool/model APIs outside the typed harness boundary; their values are seeded
-from the carrier rather than rediscovered by the middleware.
+and thread scopes still surround the drive only for legacy tool/model APIs
+outside the typed harness boundary. Recursive fan-out receives cancellation and
+workspace from its typed parent `RunContext` through `ToolDispatch`; it never
+reads a cancellation task-local.
`OpenHumanHostBundleFactory` is the B1 host composition point. It constructs
the context, definition, security, model, memory, budget, progress, learning,
diff --git a/scripts/ci/agent-runtime-boundary-baseline.json b/scripts/ci/agent-runtime-boundary-baseline.json
index 2dc32f0d38..1fda13147c 100644
--- a/scripts/ci/agent-runtime-boundary-baseline.json
+++ b/scripts/ci/agent-runtime-boundary-baseline.json
@@ -72,7 +72,7 @@
{
"rule": "openhuman-runtime-bridge",
"path": "crates/openhuman-core/src/agent/tinyagents/mod.rs",
- "line": 86,
+ "line": 84,
"text": "pub(crate) use turn_runner::run_turn_via_tinyagents_shared;",
"occurrence": 1
},
@@ -86,14 +86,14 @@
{
"rule": "openhuman-runtime-bridge",
"path": "crates/openhuman-core/src/agent/tinyagents/turn_runner.rs",
- "line": 200,
+ "line": 199,
"text": "pub(crate) async fn run_turn_via_tinyagents_shared(",
"occurrence": 1
},
{
"rule": "openhuman-runtime-bridge",
"path": "crates/openhuman-core/src/agent/tinyagents/turn_runner.rs",
- "line": 258,
+ "line": 257,
"text": "} = assemble_turn_harness(",
"occurrence": 1
},
@@ -1035,20 +1035,6 @@
"text": "use crate::agent::harness::fork_context::{current_parent, with_parent_context};",
"occurrence": 1
},
- {
- "rule": "openhuman-task-local",
- "path": "crates/openhuman-core/src/agent/orchestration/tools/spawn_parallel_agents.rs",
- "line": 16,
- "text": "use crate::agent::tinyagents::current_run_cancellation;",
- "occurrence": 1
- },
- {
- "rule": "openhuman-task-local",
- "path": "crates/openhuman-core/src/agent/orchestration/tools/spawn_parallel_agents.rs",
- "line": 125,
- "text": "let cancellation = current_run_cancellation().unwrap_or_else(|| {",
- "occurrence": 1
- },
{
"rule": "openhuman-task-local",
"path": "crates/openhuman-core/src/agent/orchestration/tools/spawn_subagent_tool_impl.rs",
@@ -1298,72 +1284,16 @@
"rule": "openhuman-task-local",
"path": "crates/openhuman-core/src/agent/tinyagents/host/run_context.rs",
"line": 96,
- "text": "if let Some(cancellation) = crate::agent::tinyagents::current_run_cancellation() {",
- "occurrence": 1
- },
- {
- "rule": "openhuman-task-local",
- "path": "crates/openhuman-core/src/agent/tinyagents/host/run_context.rs",
- "line": 99,
"text": "context.workspace = crate::agent::turn_workspace::current()",
"occurrence": 1
},
{
"rule": "openhuman-task-local",
"path": "crates/openhuman-core/src/agent/tinyagents/mod.rs",
- "line": 52,
- "text": "pub(crate) mod run_cancellation_context;",
- "occurrence": 1
- },
- {
- "rule": "openhuman-task-local",
- "path": "crates/openhuman-core/src/agent/tinyagents/mod.rs",
- "line": 56,
+ "line": 55,
"text": "pub mod thread_context;",
"occurrence": 1
},
- {
- "rule": "openhuman-task-local",
- "path": "crates/openhuman-core/src/agent/tinyagents/mod.rs",
- "line": 78,
- "text": "pub(crate) use run_cancellation_context::current_run_cancellation;",
- "occurrence": 1
- },
- {
- "rule": "openhuman-task-local",
- "path": "crates/openhuman-core/src/agent/tinyagents/run_cancellation_context.rs",
- "line": 10,
- "text": "tokio::task_local! {",
- "occurrence": 1
- },
- {
- "rule": "openhuman-task-local",
- "path": "crates/openhuman-core/src/agent/tinyagents/run_cancellation_context.rs",
- "line": 11,
- "text": "static CURRENT_RUN_CANCELLATION: CancellationToken;",
- "occurrence": 1
- },
- {
- "rule": "openhuman-task-local",
- "path": "crates/openhuman-core/src/agent/tinyagents/run_cancellation_context.rs",
- "line": 16,
- "text": "pub(crate) fn current_run_cancellation() -> Option<CancellationToken> {",
- "occurrence": 1
- },
- {
- "rule": "openhuman-task-local",
- "path": "crates/openhuman-core/src/agent/tinyagents/run_cancellation_context.rs",
- "line": 17,
- "text": "CURRENT_RUN_CANCELLATION.try_with(Clone::clone).ok()",
- "occurrence": 1
- },
- {
- "rule": "openhuman-task-local",
- "path": "crates/openhuman-core/src/agent/tinyagents/run_cancellation_context.rs",
- "line": 26,
- "text": "CURRENT_RUN_CANCELLATION.scope(token, future).await",
- "occurrence": 1
- },
{
"rule": "openhuman-task-local",
"path": "crates/openhuman-core/src/agent/tinyagents/thread_context.rs",
@@ -1402,24 +1332,10 @@
{
"rule": "openhuman-task-local",
"path": "crates/openhuman-core/src/agent/tinyagents/turn_runner.rs",
- "line": 32,
- "text": "use crate::agent::tinyagents::run_cancellation_context::with_run_cancellation;",
- "occurrence": 1
- },
- {
- "rule": "openhuman-task-local",
- "path": "crates/openhuman-core/src/agent/tinyagents/turn_runner.rs",
- "line": 589,
+ "line": 588,
"text": "crate::agent::tinyagents::thread_context::with_thread_id(run_thread_id, async move {",
"occurrence": 1
},
- {
- "rule": "openhuman-task-local",
- "path": "crates/openhuman-core/src/agent/tinyagents/turn_runner.rs",
- "line": 590,
- "text": "with_run_cancellation(cancellation.clone(), async {",
- "occurrence": 1
- },
{
"rule": "openhuman-task-local",
"path": "crates/openhuman-core/src/agent/tools/delegate_to_personality.rs",
@@ -2389,7 +2305,7 @@
{
"rule": "tinyagents-tool-calling-facade",
"path": "vendor/tinyagents/crates/tinyagents-harness/src/agent_loop/run_loop.rs",
- "line": 999,
+ "line": 1001,
"text": "use tinytools_agent::dialect::{DialectResponse, ToolDialect, XmlDialect};",
"occurrence": 1
},