Skip to content

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

feat(embed): enforce shared budgets and ordered bounded fanout

Steven Enamakelb221179319de
diff --git a/crates/openhuman-core/src/agent/subagent_host/ops/runner.rs b/crates/openhuman-core/src/agent/subagent_host/ops/runner.rs
index 1d482da102..e93f116026 100644
--- a/crates/openhuman-core/src/agent/subagent_host/ops/runner.rs
+++ b/crates/openhuman-core/src/agent/subagent_host/ops/runner.rs
@@ -259,7 +259,7 @@ pub(crate) async fn run_subagent_direct(
// This surfaces `SpawnDepthExceeded` before a provider round-trip and
// across the MCP process hop; the crate's `TinyAgentsError::SubAgentDepth`
// maps onto this same error shape for over-deep in-process runs.
- if attempted_depth > MAX_SPAWN_DEPTH {
+ if attempted_depth > crate::agent::tinyagents::budget::depth(&options.run_context) {
tracing::warn!(
agent_id = %definition.id,
task_id = %task_id,
@@ -269,7 +269,7 @@ pub(crate) async fn run_subagent_direct(
);
return Err(SubagentRunError::SpawnDepthExceeded {
attempted_depth,
- max_depth: MAX_SPAWN_DEPTH,
+ max_depth: crate::agent::tinyagents::budget::depth(&options.run_context),
});
}
diff --git a/crates/openhuman-core/src/agent/tinyagents/budget.rs b/crates/openhuman-core/src/agent/tinyagents/budget.rs
new file mode 100644
index 0000000000..968d765698
--- /dev/null
+++ b/crates/openhuman-core/src/agent/tinyagents/budget.rs
@@ -0,0 +1,61 @@
+//! Host budget policy, scoped once at admission and carried explicitly to children.
+use std::sync::Arc;
+pub use tinyinference_llm::model::budget::{
+ Budget, BudgetExceeded, BudgetSnapshot, CallBudget, Spend, SpendLimits,
+};
+use tinyinference_llm::model::ChatModel;
+
+/// A shared ledger and conservative reservation bounds for every physical call.
+#[derive(Debug, Clone)]
+pub struct ModelBudget {
+ /// Run/turn ledger. Children of a turn share it.
+ pub ledger: Budget,
+ /// Per-call input, output and charge upper bounds for all allowed routes.
+ pub call: CallBudget,
+}
+impl ModelBudget {
+ /// Apply the policy below retries and fallback selection.
+ pub(crate) fn wrap(&self, model: Arc<dyn ChatModel<()>>) -> Arc<dyn ChatModel<()>> {
+ Arc::new(tinyinference_llm::model::budget::BudgetedModel::new(
+ model,
+ self.ledger.clone(),
+ self.call,
+ ))
+ }
+}
+tokio::task_local! { static MODEL_BUDGET: ModelBudget; }
+/// Scope host policy around turn admission; the explicit run carrier copies it.
+pub async fn with_budget<F: std::future::Future>(budget: ModelBudget, future: F) -> F::Output {
+ MODEL_BUDGET.scope(budget, Box::pin(future)).await
+}
+pub(crate) fn current() -> Option<ModelBudget> {
+ MODEL_BUDGET.try_with(Clone::clone).ok()
+}
+
+// Fanout leaves narrow the existing host depth policy at admission.
+tokio::task_local! { static SPAWN_DEPTH_LIMIT: usize; }
+/// Run a typed fanout call with a narrower model-directed child-depth ceiling.
+pub async fn with_spawn_depth_limit<F: std::future::Future>(limit: usize, future: F) -> F::Output {
+ SPAWN_DEPTH_LIMIT.scope(limit, Box::pin(future)).await
+}
+pub(crate) fn spawn_depth_limit() -> Option<usize> {
+ SPAWN_DEPTH_LIMIT.try_with(|limit| *limit).ok()
+}
+
+/// Effective host depth ceiling, never wider than product policy.
+pub(crate) fn depth(context: &super::host::OpenHumanRunContext) -> usize {
+ context
+ .max_spawn_depth
+ .unwrap_or(crate::agent::harness::MAX_SPAWN_DEPTH)
+ .min(crate::agent::harness::MAX_SPAWN_DEPTH)
+}
+pub(super) fn install_depth(
+ harness: &mut tinyagents_harness::runtime::AgentHarness<(), super::host::OpenHumanRunContext>,
+ context: &super::host::OpenHumanRunContext,
+) {
+ if let Some(max_depth) = context.max_spawn_depth {
+ let mut policy = harness.policy().clone();
+ policy.limits.max_depth = policy.limits.max_depth.min(max_depth);
+ harness.with_policy(policy);
+ }
+}
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 fb577d6aa5..89958014d1 100644
--- a/crates/openhuman-core/src/agent/tinyagents/host/run_context.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/host/run_context.rs
@@ -270,6 +270,10 @@ impl TurnDispatchState {
/// the provider route or cost roll-up subsequently read by its parent.
#[derive(Clone)]
pub struct OpenHumanRunContext {
+ /// Explicit shared model-call budget inherited by synchronous children.
+ pub model_budget: Option<super::super::budget::ModelBudget>,
+ /// A host can narrow synchronous delegation depth; children inherit this.
+ pub max_spawn_depth: Option<usize>,
/// Trust/routing source used by OpenHuman approval and attribution policy.
pub origin: Option<AgentTurnOrigin>,
/// UI/event progress receiver for this turn tree.
@@ -384,6 +388,8 @@ impl OpenHumanRunContext {
/// actually owns; `None` is an explicit absence, not an ambient fallback.
pub fn new() -> Self {
Self {
+ model_budget: super::super::budget::current(),
+ max_spawn_depth: super::super::budget::spawn_depth_limit(),
origin: None,
progress: None,
stop_hooks: crate::agent::stop_hooks::current_stop_hooks(),
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 916e39454a..d72e60b5c5 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
@@ -382,3 +382,43 @@ fn attach_parent_keeps_the_snapshot_sink_when_the_run_has_none() {
CLI/cron receiver that snapshot was carrying",
);
}
+
+#[test]
+fn child_inherits_shared_model_budget_and_narrowed_depth_limit() {
+ use crate::agent::tinyagents::budget::{Budget, CallBudget, ModelBudget, Spend, SpendLimits};
+ let ledger = Budget::new(SpendLimits {
+ tokens: Some(100),
+ cost_micros: None,
+ });
+ let mut parent = OpenHumanRunContext::new();
+ parent.model_budget = Some(ModelBudget {
+ ledger: ledger.clone(),
+ call: CallBudget {
+ input_tokens: 50,
+ output_tokens: 10,
+ cost_micros: 1,
+ },
+ });
+ parent.max_spawn_depth = Some(1);
+ let child = parent.child();
+ assert_eq!(child.max_spawn_depth, Some(1));
+ assert_eq!(child.spawn_depth, 1);
+ let reservation = child
+ .model_budget
+ .unwrap()
+ .ledger
+ .reserve(Spend {
+ tokens: 60,
+ cost_micros: 0,
+ })
+ .unwrap();
+ assert_eq!(ledger.snapshot().reserved.tokens, 60);
+ reservation.settle(Spend {
+ tokens: 10,
+ cost_micros: 0,
+ });
+ assert_eq!(
+ parent.model_budget.unwrap().ledger.snapshot().spent.tokens,
+ 10
+ );
+}
diff --git a/crates/openhuman-core/src/agent/tinyagents/mod.rs b/crates/openhuman-core/src/agent/tinyagents/mod.rs
index 754e4d2610..0b17e6d78d 100644
--- a/crates/openhuman-core/src/agent/tinyagents/mod.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/mod.rs
@@ -49,6 +49,7 @@ pub mod run_mode;
// embedder may be unable to do (OpenCompany withholds spawn tools under
// multi-tenancy), so "bring your own summarizer" is the case this seam exists
// for rather than an exotic one.
+pub mod budget;
pub mod payload_summarizer;
mod policy_denial;
pub(crate) mod reaper;
diff --git a/crates/openhuman-core/src/agent/tinyagents/payload_summarizer.rs b/crates/openhuman-core/src/agent/tinyagents/payload_summarizer.rs
index 70b0ce4890..3eb86f6698 100644
--- a/crates/openhuman-core/src/agent/tinyagents/payload_summarizer.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/payload_summarizer.rs
@@ -142,8 +142,14 @@ impl PayloadSummarizer for SubagentPayloadSummarizer {
)?,
max_output_tokens,
);
+ let provider_model: Arc<dyn tinyinference_llm::model::ChatModel<()>> =
+ Arc::new(provider_model);
+ let provider_model = match &child_context.data.model_budget {
+ Some(budget) => budget.wrap(provider_model),
+ None => provider_model,
+ };
harness
- .register_model(&model, Arc::new(provider_model))
+ .register_model(&model, provider_model)
.set_default_model(&model);
// Unary, never streaming. A chat turn's parent is streaming, and
diff --git a/crates/openhuman-core/src/agent/tinyagents/turn_models.rs b/crates/openhuman-core/src/agent/tinyagents/turn_models.rs
index 538825807e..26cbb4a568 100644
--- a/crates/openhuman-core/src/agent/tinyagents/turn_models.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/turn_models.rs
@@ -67,6 +67,19 @@ pub(crate) struct TurnModels {
}
impl TurnModels {
+ /// Wrap every concrete route and summarizer below harness retries/fallback.
+ pub(crate) fn with_budget(mut self, budget: Option<&super::budget::ModelBudget>) -> Self {
+ let Some(budget) = budget else {
+ return self;
+ };
+ self.primary = budget.wrap(self.primary);
+ self.summarizer = budget.wrap(self.summarizer);
+ for (_, route) in &mut self.routes {
+ *route = budget.wrap(route.clone());
+ }
+ self
+ }
+
/// Whether the primary provider is local / self-hosted.
pub(crate) fn is_local(&self) -> bool {
self.is_local
diff --git a/crates/openhuman-core/src/agent/tinyagents/turn_runner.rs b/crates/openhuman-core/src/agent/tinyagents/turn_runner.rs
index 80f18c57f3..70bf02f4f8 100644
--- a/crates/openhuman-core/src/agent/tinyagents/turn_runner.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/turn_runner.rs
@@ -16,7 +16,6 @@ use tinyagents_harness::store::StoreRegistry;
use tinyagents_registry::DiagnosticSeverity;
use crate::agent::harness::tool_result_artifacts::TINYAGENTS_TOOL_RESULT_ARTIFACT_STORE;
-use crate::agent::harness::MAX_SPAWN_DEPTH;
use crate::agent::tinyagents::harness_assembly::{assemble_turn_harness, AssembledTurnHarness};
use crate::agent::tinyagents::host::steering::shared_steering_registry;
use crate::agent::tinyagents::host::OpenHumanRunContext;
@@ -222,9 +221,8 @@ pub(super) async fn run_turn_via_tinyagents_body(
// otherwise the harness model-call cap would be zero and abort the run before
// the first provider call.
let max_iterations = effective_max_iterations(max_iterations);
- // Hosted resolution must expose this turn's already-selected primary and
- // fallback models. Build the resolver before assembly consumes the model
- // bundle; it is installed only on the invocation-local host bundle.
+ // Wrap concrete routes before the invocation-local hosted resolver captures them.
+ let turn_models = turn_models.with_budget(run_context.model_budget.as_ref());
let hosted_model_resolver = hosted_root.as_ref().map(|_| {
Arc::new(
crate::agent::tinyagents::turn_models::TurnModelResolver::from_turn_models(
@@ -299,6 +297,7 @@ pub(super) async fn run_turn_via_tinyagents_body(
run_context.tool_rules.clone(),
);
super::response_shape::install(&mut harness, hosted_root.is_some());
+ super::budget::install_depth(&mut harness, &run_context);
super::deadline_wind_down::install(&mut harness, &handle, &run_context, &subagent_scope);
// Fail-closed registry validation gate (issue #4249, Workstream 10 — registry).
// The projected `CapabilityRegistry` produced these diagnostics during
@@ -357,7 +356,7 @@ pub(super) async fn run_turn_via_tinyagents_body(
})
.with_max_model_calls(max_iterations)
.with_max_tool_calls(crate::agent::stop_hooks::tool_call_limit(max_iterations))
- .with_max_depth(MAX_SPAWN_DEPTH)
+ .with_max_depth(super::budget::depth(&run_context))
.with_tag("openhuman")
.with_tag(if subagent_scope.is_some() {
"scope:subagent"
diff --git a/crates/openhuman-core/src/inference/host_runtime/ops/complete_once.rs b/crates/openhuman-core/src/inference/host_runtime/ops/complete_once.rs
index 04dd1a23d0..7d0e8b1854 100644
--- a/crates/openhuman-core/src/inference/host_runtime/ops/complete_once.rs
+++ b/crates/openhuman-core/src/inference/host_runtime/ops/complete_once.rs
@@ -95,6 +95,11 @@ pub async fn complete_once(
"[inference] complete_once invoking chat model"
);
+ let model: std::sync::Arc<dyn ChatModel<()>> = std::sync::Arc::new(model);
+ let model = match crate::agent::tinyagents::budget::current() {
+ Some(budget) => budget.wrap(model),
+ None => model,
+ };
model
.invoke(&(), request)
.await
diff --git a/crates/openhuman-embed/src/budget.rs b/crates/openhuman-embed/src/budget.rs
new file mode 100644
index 0000000000..688dc45025
--- /dev/null
+++ b/crates/openhuman-embed/src/budget.rs
@@ -0,0 +1,15 @@
+//! Enforced shared budgets for completion calls, tool loops and synchronous children.
+//!
+//! Attach [`ModelBudget`] to a turn or completer. Use [`Budget::child`] for a
+//! per-turn ledger charged to a shared review/run ledger. Each concrete route
+//! and summarizer reserves before calling its provider, including every retry.
+//! Unknown usage, errors and cancellation consume the full reservation. Cost
+//! bounds are host-supplied upper bounds for every allowed route, not billing
+//! estimates; providers cannot be forced to honour a monetary cap locally.
+//!
+//! Budgeted calls currently accept text only. Input bounds use serialized-byte
+//! counts conservatively; multimodal requests fail before dispatch. Choose
+//! bounds that include model framing and the maximum price on allowed routes.
+pub use openhuman_core::agent::tinyagents::budget::{
+ Budget, BudgetExceeded, BudgetSnapshot, CallBudget, ModelBudget, Spend, SpendLimits,
+};
diff --git a/crates/openhuman-embed/src/complete.rs b/crates/openhuman-embed/src/complete.rs
index 3343058dc6..094fc1dd7f 100644
--- a/crates/openhuman-embed/src/complete.rs
+++ b/crates/openhuman-embed/src/complete.rs
@@ -407,6 +407,7 @@ pub struct Completer {
timeout: Option<Duration>,
observer: Option<Arc<dyn CompletionObserver>>,
cancellation: crate::cancellation::Cancellation,
+ budget: Option<crate::budget::ModelBudget>,
}
impl std::fmt::Debug for Completer {
@@ -429,6 +430,7 @@ impl Completer {
timeout: None,
observer: None,
cancellation: Default::default(),
+ budget: None,
}
}
@@ -451,6 +453,12 @@ impl Completer {
self
}
+ /// Enforce a shared run or per-turn budget before every provider call.
+ pub fn budget(mut self, budget: crate::budget::ModelBudget) -> Self {
+ self.budget = Some(budget);
+ self
+ }
+
/// Report every call to `observer`.
pub fn observer(mut self, observer: Arc<dyn CompletionObserver>) -> Self {
self.observer = Some(observer);
@@ -559,8 +567,30 @@ impl Completer {
&endpoint,
request.into_wire(),
);
+ let budget = self
+ .budget
+ .as_ref()
+ .map(|budget| crate::budget::ModelBudget {
+ ledger: budget.ledger.child(crate::budget::SpendLimits::default()),
+ call: budget.call,
+ });
+ let call = async {
+ match &budget {
+ Some(budget) => {
+ openhuman_core::agent::tinyagents::budget::with_budget(budget.clone(), call)
+ .await
+ }
+ None => call.await,
+ }
+ };
let started = std::time::Instant::now();
let response = call.await.map_err(|message| {
+ if let Some(source) = budget.as_ref().and_then(|budget| budget.ledger.refusal()) {
+ return CoreError::BudgetExceeded {
+ method: COMPLETE,
+ source,
+ };
+ }
log::warn!(
"[embed] complete failed method={COMPLETE} model={model} elapsed_ms={}",
started.elapsed().as_millis()
diff --git a/crates/openhuman-embed/src/error.rs b/crates/openhuman-embed/src/error.rs
index e3baa343fc..de7a178f89 100644
--- a/crates/openhuman-embed/src/error.rs
+++ b/crates/openhuman-embed/src/error.rs
@@ -47,6 +47,14 @@ pub enum CoreError {
failure: crate::structured::StructuredOutputFailure,
},
+ /// Model call refused before dispatch by a shared run or turn budget.
+ #[error("{method}: {source}")]
+ BudgetExceeded {
+ /// Method that attempted the call.
+ method: &'static str,
+ /// Refusal including spend so far and outstanding reservations.
+ source: crate::budget::BudgetExceeded,
+ },
/// The domain returned a structured error envelope.
#[error("{method}: {message}")]
Domain {
@@ -184,6 +192,7 @@ impl CoreError {
CoreError::Cancelled { method }
| CoreError::DeadlineExceeded { method }
| CoreError::StructuredOutput { method, .. }
+ | CoreError::BudgetExceeded { method, .. }
| CoreError::Domain { method, .. }
| CoreError::Unavailable { method }
| CoreError::Rpc { method, .. }
@@ -206,10 +215,11 @@ impl CoreError {
pub fn is_expected_user_state(&self) -> bool {
matches!(
self,
- CoreError::Domain {
- expected_user_state: true,
- ..
- }
+ CoreError::BudgetExceeded { .. }
+ | CoreError::Domain {
+ expected_user_state: true,
+ ..
+ }
)
}
diff --git a/crates/openhuman-embed/src/fanout.rs b/crates/openhuman-embed/src/fanout.rs
new file mode 100644
index 0000000000..2ce48ff007
--- /dev/null
+++ b/crates/openhuman-embed/src/fanout.rs
@@ -0,0 +1,177 @@
+//! Bounded concurrent calls with ordered results, isolated sessions and a shared budget.
+//!
+//! A branch can declare one level of leaf children. Leaves expose no child
+//! builder. Runtime-owned agent calls keep their own agent/session policy;
+//! this primitive does not enable model-directed subagent tools.
+use crate::budget::{ModelBudget, SpendLimits};
+use crate::complete::{Completer, CompletionRequest, CompletionResponse};
+use crate::{CoreError, Runtime, Turn, TurnOutcome};
+use std::num::NonZeroUsize;
+
+/// One leaf call. It cannot declare further children.
+///
+/// ```compile_fail
+/// use openhuman_embed::fanout::LeafCall;
+/// fn recurse(leaf: LeafCall) { leaf.children(Vec::new()); }
+/// ```
+pub enum LeafCall {
+ /// Stateless model request on its explicit route.
+ Completion {
+ /// The route and completion options.
+ completer: Completer,
+ /// The model request.
+ request: CompletionRequest,
+ },
+ /// Independent agent turn. An unset session gets a fresh identity.
+ Turn(Turn),
+}
+/// Either model-call result, retaining usage and answering-model metadata.
+#[derive(Debug)]
+pub enum CallOutcome {
+ /// Completed stateless request.
+ Completion(CompletionResponse),
+ /// Completed agent turn.
+ Turn(TurnOutcome),
+}
+/// A root call and an optional single level of child calls.
+pub struct Branch {
+ call: LeafCall,
+ children: Vec<LeafCall>,
+ limits: SpendLimits,
+}
+impl Branch {
+ /// An independent branch with no children or local ceilings.
+ pub fn new(call: LeafCall) -> Self {
+ Self {
+ call,
+ children: Vec::new(),
+ limits: SpendLimits::default(),
+ }
+ }
+ /// Declare direct children. A child has no further child-building API.
+ pub fn children(mut self, children: Vec<LeafCall>) -> Self {
+ self.children = children;
+ self
+ }
+ /// Apply a branch/turn ceiling in addition to the shared run ceiling.
+ pub fn limits(mut self, limits: SpendLimits) -> Self {
+ self.limits = limits;
+ self
+ }
+}
+/// A successful root and individually isolated, ordered child results.
+#[derive(Debug)]
+pub struct BranchOutcome {
+ /// The root call's response.
+ pub root: CallOutcome,
+ /// Direct children, in declared order. One failure leaves siblings running.
+ pub children: Vec<Result<CallOutcome, CoreError>>,
+}
+type CallFuture =
+ std::pin::Pin<Box<dyn std::future::Future<Output = Result<CallOutcome, CoreError>> + Send>>;
+fn call(call: LeafCall, budget: ModelBudget, leaf: bool) -> CallFuture {
+ match call {
+ LeafCall::Completion { completer, request } => Box::pin(async move {
+ Box::pin(completer.budget(budget).complete(request))
+ .await
+ .map(CallOutcome::Completion)
+ }),
+ LeafCall::Turn(turn) => Box::pin(async move {
+ openhuman_core::agent::tinyagents::budget::with_spawn_depth_limit(
+ if leaf { 0 } else { 1 },
+ Box::pin(turn.budget(budget).send()),
+ )
+ .await
+ .map(CallOutcome::Turn)
+ }),
+ }
+}
+
+async fn branch(branch: Branch, budget: ModelBudget) -> Result<BranchOutcome, CoreError> {
+ let budget = ModelBudget {
+ ledger: budget.ledger.child(branch.limits),
+ call: budget.call,
+ };
+ let root = call(branch.call, budget.clone(), false).await?;
+ let mut children = Vec::with_capacity(branch.children.len());
+ for child in branch.children {
+ children.push(call(child, budget.clone(), true).await);
+ }
+ Ok(BranchOutcome { root, children })
+}
+/// Run branches concurrently without booting a runtime (useful for completers).
+///
+/// At most `concurrency` branches run at once; each branch processes its root
+/// then its children sequentially. Input order is retained regardless of finish
+/// order. A root failure skips only that root's children. A cancelled outer
+/// future drops every in-flight future and conservatively charges reservations.
+pub async fn fanout(
+ branches: Vec<Branch>,
+ concurrency: NonZeroUsize,
+ budget: ModelBudget,
+) -> Vec<Result<BranchOutcome, CoreError>> {
+ let futures = branches
+ .into_iter()
+ .map(|branch_input| {
+ Box::pin(branch(branch_input, budget.clone()))
+ as BranchFuture<'_, BranchOutcome, CoreError>
+ })
+ .collect();
+ fanout_futures(futures, concurrency).await
+}
+
+/// A borrowed branch future. It need not be `'static` or spawn a task.
+pub type BranchFuture<'a, T, E> =
+ std::pin::Pin<Box<dyn std::future::Future<Output = Result<T, E>> + Send + 'a>>;
+
+/// Poll borrowed host futures concurrently and retain input-order results.
+///
+/// A future owns its own call/budget policy; this scheduler makes no assumption
+/// that an opaque future is a model call. Configure `Turn::budget` or
+/// `Completer::budget` inside each model future. Dropping this scheduler drops
+/// every active future and never detaches work.
+pub async fn fanout_futures<'a, T, E>(
+ futures: Vec<BranchFuture<'a, T, E>>,
+ concurrency: NonZeroUsize,
+) -> Vec<Result<T, E>> {
+ let mut pending = futures.into_iter().enumerate();
+ let mut active: Vec<(usize, BranchFuture<'a, T, E>)> = Vec::new();
+ let mut results = Vec::new();
+ for (index, future) in pending.by_ref().take(concurrency.get()) {
+ active.push((index, future));
+ results.push(None);
+ }
+ while !active.is_empty() {
+ let (slot, outcome) = std::future::poll_fn(|cx| {
+ for (slot, (_, future)) in active.iter_mut().enumerate() {
+ if let std::task::Poll::Ready(result) = future.as_mut().poll(cx) {
+ return std::task::Poll::Ready((slot, result));
+ }
+ }
+ std::task::Poll::Pending
+ })
+ .await;
+ let (index, _) = active.swap_remove(slot);
+ results[index] = Some(outcome);
+ if let Some((index, future)) = pending.next() {
+ active.push((index, future));
+ results.push(None);
+ }
+ }
+ results
+ .into_iter()
+ .map(|result| result.expect("each admitted branch settled"))
+ .collect()
+}
+
+impl Runtime {
+ /// Run independent model/agent branches with ordered results and a shared ledger.
+ pub async fn fanout(
+ &self,
+ branches: Vec<Branch>,
+ concurrency: NonZeroUsize,
+ budget: ModelBudget,
+ ) -> Vec<Result<BranchOutcome, CoreError>> {
+ fanout(branches, concurrency, budget).await
+ }
+}
diff --git a/crates/openhuman-embed/src/lib.rs b/crates/openhuman-embed/src/lib.rs
index 8f7508e228..0e21a78857 100644
--- a/crates/openhuman-embed/src/lib.rs
+++ b/crates/openhuman-embed/src/lib.rs
@@ -98,6 +98,7 @@ pub mod skill_registry {
mod agent;
pub mod artifacts;
mod auth;
+pub mod budget;
mod call;
#[cfg(feature = "channels")]
pub mod channels;
@@ -108,6 +109,7 @@ mod core_agent;
pub mod cron;
pub mod embeddings;
mod error;
+pub mod fanout;
mod harness;
pub mod identity;
pub mod memory;
diff --git a/crates/openhuman-embed/src/turn.rs b/crates/openhuman-embed/src/turn.rs
index 124691b34c..631ace0e29 100644
--- a/crates/openhuman-embed/src/turn.rs
+++ b/crates/openhuman-embed/src/turn.rs
@@ -248,6 +248,7 @@ pub(crate) enum TurnTarget {
/// Owned rather than borrowed: it holds an `Arc` to whatever it dispatches
/// on, so a host can build it in one place and send it from another.
pub struct Turn {
+ budget: Option<crate::budget::ModelBudget>,
target: TurnTarget,
request: TurnRequest,
session_id: Option<String>,
@@ -267,6 +268,7 @@ impl Turn {
pub(crate) fn new(target: TurnTarget, message: impl Into<String>) -> Self {
Self {
target,
+ budget: None,
request: TurnRequest::new(message),
session_id: None,
origin: None,
@@ -441,6 +443,12 @@ impl Turn {
self
}
+ /// Enforce the ledger across this tool loop, retries and synchronous children.
+ pub fn budget(mut self, budget: crate::budget::ModelBudget) -> Self {
+ self.budget = Some(budget);
+ self
+ }
+
/// Set the sampling temperature for this turn.
pub fn temperature(mut self, temperature: f64) -> Self {
self.request.temperature = Some(temperature);
@@ -581,7 +589,20 @@ impl Turn {
),
untrusted_input: self.untrusted_input,
};
+ let budget = self.budget.take().map(|budget| crate::budget::ModelBudget {
+ ledger: budget.ledger.child(crate::budget::SpendLimits::default()),
+ call: budget.call,
+ });
let dispatch = dispatch(self.target, self.request, self.seed.take(), &usage, options);
+ let dispatch = async {
+ match &budget {
+ Some(budget) => {
+ openhuman_core::agent::tinyagents::budget::with_budget(budget.clone(), dispatch)
+ .await
+ }
+ None => dispatch.await,
+ }
+ };
let reply = match (self.origin, self.progress) {
(Some(origin), Some(sink)) => {
@@ -610,6 +631,7 @@ impl Turn {
crate::error::CoreError::Cancelled { .. } => "cancelled",
crate::error::CoreError::DeadlineExceeded { .. } => "deadline",
crate::error::CoreError::StructuredOutput { .. } => "structured_output",
+ crate::error::CoreError::BudgetExceeded { .. } => "budget_exceeded",
crate::error::CoreError::Domain { .. } => "domain",
crate::error::CoreError::Unavailable { .. } => "unavailable",
crate::error::CoreError::Rpc { .. } => "rpc",
@@ -633,6 +655,15 @@ impl Turn {
.clone(),
);
}
+ let reply = reply.map_err(|error| {
+ match budget.as_ref().and_then(|budget| budget.ledger.refusal()) {
+ Some(source) => CoreError::BudgetExceeded {
+ method: AGENT_CHAT,
+ source,
+ },
+ None => error,
+ }
+ });
let (reply, report) = reply?;
let structured = if wants_json {
serde_json::from_str(reply.trim()).ok()
diff --git a/crates/openhuman-embed/tests/budget_fanout.rs b/crates/openhuman-embed/tests/budget_fanout.rs
new file mode 100644
index 0000000000..1bf25e046d
--- /dev/null
+++ b/crates/openhuman-embed/tests/budget_fanout.rs
@@ -0,0 +1,227 @@
+//! Physical-call budget admission and bounded, ordered completion fanout.
+use openhuman_embed::budget::{Budget, CallBudget, ModelBudget, SpendLimits};
+use openhuman_embed::complete::{ChatMessage, Completer, CompletionRequest};
+use openhuman_embed::fanout::{fanout, Branch, CallOutcome, LeafCall};
+use openhuman_embed::{CoreError, Route};
+use serde_json::json;
+use std::num::NonZeroUsize;
+use wiremock::matchers::{method, path};
+use wiremock::{Mock, MockServer, ResponseTemplate};
+
+fn policy(cost_micros: u64) -> ModelBudget {
+ ModelBudget {
+ ledger: Budget::new(SpendLimits {
+ tokens: None,
+ cost_micros: Some(cost_micros),
+ }),
+ call: CallBudget {
+ input_tokens: 1_000,
+ output_tokens: 20,
+ cost_micros: 100,
+ },
+ }
+}
+fn completer(server: &MockServer) -> Completer {
+ Completer::new(Route::openai_compatible(
+ format!("{}/v1", server.uri()),
+ "fixture",
+ ))
+}
+fn request(model: &str) -> CompletionRequest {
+ CompletionRequest::new(model, vec![ChatMessage::user("review")]).max_tokens(30)
+}
+fn leaf(server: &MockServer, model: &str) -> LeafCall {
+ LeafCall::Completion {
+ completer: completer(server),
+ request: request(model),
+ }
+}
+async fn provider() -> MockServer {
+ let server = MockServer::start().await;
+ Mock::given(method("POST")).and(path("/v1/chat/completions")).respond_with(ResponseTemplate::new(200).set_body_json(json!({ "id":"fixture", "object":"chat.completion", "model":"fixture", "choices":[{"index":0,"message":{"role":"assistant","content":"ok"},"finish_reason":"stop"}], "usage":{"prompt_tokens":10,"completion_tokens":5,"total_tokens":15} }))).mount(&server).await;
+ server
+}
+#[tokio::test]
+async fn unknown_cost_consumes_reservation_and_blocks_next_call_before_http() {
+ let server = provider().await;
+ let policy = policy(100);
+ let client = completer(&server).budget(policy.clone());
+ client.complete(request("fixture")).await.unwrap();
+ let error = client.complete(request("fixture")).await.unwrap_err();
+ assert!(
+ matches!(error, CoreError::BudgetExceeded { source, .. } if source.snapshot.spent.cost_micros == 100)
+ );
+ assert_eq!(server.received_requests().await.unwrap().len(), 1);
+ let body: serde_json::Value =
+ serde_json::from_slice(&server.received_requests().await.unwrap()[0].body).unwrap();
+ assert_eq!(body["max_tokens"], 20);
+}
+#[tokio::test]
+async fn fanout_retains_input_order_and_isolates_invalid_branch() {
+ let server = provider().await;
+ let results = fanout(
+ vec![
+ Branch::new(leaf(&server, "first")),
+ Branch::new(leaf(&server, "")),
+ Branch::new(leaf(&server, "last")),
+ ],
+ NonZeroUsize::new(2).unwrap(),
+ policy(1_000),
+ )
+ .await;
+ assert_eq!(results.len(), 3);
+ assert!(results[0].is_ok());
+ assert!(matches!(results[1], Err(CoreError::InvalidRoute { .. })));
+ assert!(results[2].is_ok());
+}
+#[tokio::test]
+async fn fanout_children_share_parent_ceiling_and_isolate_errors() {
+ let server = provider().await;
+ let shared = policy(1_000);
+ let results = fanout(
+ vec![Branch::new(leaf(&server, "root"))
+ .limits(SpendLimits {
+ tokens: None,
+ cost_micros: Some(200),
+ })
+ .children(vec![leaf(&server, "child"), leaf(&server, "blocked")])],
+ NonZeroUsize::new(1).unwrap(),
+ shared.clone(),
+ )
+ .await;
+ let outcome = results.into_iter().next().unwrap().unwrap();
+ assert!(matches!(outcome.root, CallOutcome::Completion(_)));
+ assert!(outcome.children[0].is_ok());
+ assert!(matches!(
+ outcome.children[1],
+ Err(CoreError::BudgetExceeded { .. })
+ ));
+ assert_eq!(shared.ledger.snapshot().spent.cost_micros, 200);
+ assert_eq!(server.received_requests().await.unwrap().len(), 2);
+}
+#[tokio::test]
+async fn concurrent_branches_cannot_all_admit_against_one_reservation() {
+ let server = provider().await;
+ let results = fanout(
+ (0..8)
+ .map(|_| Branch::new(leaf(&server, "fixture")))
+ .collect(),
+ NonZeroUsize::new(8).unwrap(),
+ policy(100),
+ )
+ .await;
+ assert_eq!(results.iter().filter(|result| result.is_ok()).count(), 1);
+ assert_eq!(
+ results
+ .iter()
+ .filter(|result| matches!(result, Err(CoreError::BudgetExceeded { .. })))
+ .count(),
+ 7
+ );
+ assert_eq!(server.received_requests().await.unwrap().len(), 1);
+}
+#[tokio::test]
+async fn exhausted_turn_ceiling_refuses_first_call_without_debiting_parent() {
+ let server = provider().await;
+ let shared = policy(100);
+ let limited = ModelBudget {
+ ledger: shared.ledger.child(SpendLimits {
+ tokens: Some(0),
+ cost_micros: None,
+ }),
+ call: shared.call,
+ };
+ assert!(matches!(
+ completer(&server)
+ .budget(limited)
+ .complete(request("fixture"))
+ .await,
+ Err(CoreError::BudgetExceeded { .. })
+ ));
+ assert!(server.received_requests().await.unwrap().is_empty());
+ assert_eq!(shared.ledger.snapshot().spent.tokens, 0);
+}
+#[tokio::test]
+async fn empty_fanout_returns_without_calls() {
+ assert!(fanout(vec![], NonZeroUsize::new(1).unwrap(), policy(0))
+ .await
+ .is_empty());
+}
+
+#[tokio::test]
+async fn provider_internal_shape_retry_requires_another_reservation_before_http() {
+ let server = MockServer::start().await;
+ Mock::given(method("POST"))
+ .and(path("/v1/chat/completions"))
+ .respond_with(
+ ResponseTemplate::new(400)
+ .set_body_json(json!({"error":{"message":"response_format is unsupported"}})),
+ )
+ .mount(&server)
+ .await;
+ let shared = policy(100);
+ let error = completer(&server)
+ .budget(shared.clone())
+ .complete(
+ request("fixture")
+ .response_format(openhuman_embed::complete::ResponseFormat::JsonObject),
+ )
+ .await
+ .unwrap_err();
+ assert!(
+ matches!(error, CoreError::BudgetExceeded { .. }),
+ "{error:?}"
+ );
+ assert_eq!(server.received_requests().await.unwrap().len(), 1);
+ assert_eq!(shared.ledger.snapshot().spent.cost_micros, 100);
+}
+
+#[tokio::test]
+async fn borrowed_branch_futures_overlap_within_the_declared_bound() {
+ use openhuman_embed::fanout::{fanout_futures, BranchFuture};
+ use std::sync::atomic::{AtomicUsize, Ordering};
+ let values = [10, 20, 30, 40, 50, 60];
+ let active = AtomicUsize::new(0);
+ let peak = AtomicUsize::new(0);
+ let permits = tokio::sync::Semaphore::new(0);
+ let (started, mut received) = tokio::sync::mpsc::channel(values.len());
+ let futures: Vec<BranchFuture<'_, i32, &str>> = values
+ .iter()
+ .enumerate()
+ .map(|(index, value)| {
+ let active = &active;
+ let peak = &peak;
+ let permits = &permits;
+ let started = started.clone();
+ Box::pin(async move {
+ let count = active.fetch_add(1, Ordering::SeqCst) + 1;
+ peak.fetch_max(count, Ordering::SeqCst);
+ started.send(index).await.unwrap();
+ permits.acquire().await.unwrap().forget();
+ active.fetch_sub(1, Ordering::SeqCst);
+ if index == 2 {
+ Err("branch failed")
+ } else {
+ Ok(*value)
+ }
+ }) as BranchFuture<'_, i32, &str>
+ })
+ .collect();
+ let controller = async {
+ for _ in 0..3 {
+ received.recv().await.unwrap();
+ received.recv().await.unwrap();
+ assert_eq!(active.load(Ordering::SeqCst), 2);
+ permits.add_permits(2);
+ }
+ };
+ let (results, ()) = tokio::join!(
+ fanout_futures(futures, NonZeroUsize::new(2).unwrap()),
+ controller
+ );
+ assert_eq!(peak.load(Ordering::SeqCst), 2);
+ assert_eq!(
+ results,
+ vec![Ok(10), Ok(20), Err("branch failed"), Ok(40), Ok(50), Ok(60)]
+ );
+}
diff --git a/crates/openhuman-embed/tests/structured_turns.rs b/crates/openhuman-embed/tests/structured_turns.rs
index b876afa4ab..8d78d85020 100644
--- a/crates/openhuman-embed/tests/structured_turns.rs
+++ b/crates/openhuman-embed/tests/structured_turns.rs
@@ -349,3 +349,32 @@ fn a_complete_json_value_with_a_length_finish_is_not_a_valid_review() {
.unwrap();
});
}
+
+#[test]
+fn shared_budget_stops_the_tool_loop_before_its_next_provider_call() {
+ let _guard = RUNTIME_LOCK
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
+ runtime().block_on(async {
+ tokio::spawn(async {
+ use openhuman_embed::budget::{Budget, CallBudget, ModelBudget, SpendLimits};
+ let backend = stub_backend().await;
+ let provider = provider(vec![completion(json!({
+ "role":"assistant", "content":null,
+ "tool_calls":[{"id":"read-budget","type":"function","function":{"name":"read_file","arguments":"{\"path\":\"src/main.rs\"}"}}]
+ }),"tool_calls","fixture",0)]).await;
+ let runtime = build_runtime(&backend).await;
+ let reads = Arc::new(AtomicUsize::new(0));
+ let agent = runtime.agent(reviewer("budgeted",&provider,reads.clone())).unwrap();
+ let ledger = Budget::new(SpendLimits { tokens:None,cost_micros:Some(100) });
+ let outcome = agent.turn("Review this diff.").budget(ModelBudget {
+ ledger:ledger.clone(),
+ call:CallBudget {input_tokens:200_000,output_tokens:512,cost_micros:100},
+ }).send().await;
+ assert!(matches!(outcome,Err(CoreError::BudgetExceeded { .. })),"{outcome:?}");
+ assert_eq!(reads.load(Ordering::SeqCst),1);
+ assert_eq!(chat_requests(&provider).await.len(),1);
+ assert_eq!(ledger.snapshot().spent.cost_micros,100);
+ }).await.unwrap();
+ });
+}
diff --git a/docs/TEST-COVERAGE-MATRIX.md b/docs/TEST-COVERAGE-MATRIX.md
index 0e465b9428..87b8dddc3e 100644
--- a/docs/TEST-COVERAGE-MATRIX.md
+++ b/docs/TEST-COVERAGE-MATRIX.md
@@ -664,6 +664,8 @@ The thread JSONL store moved to `tinyagents_session::threads` (`vendor/tinyagent
| 16.1.15 | Strict structured output and bounded repair | RI | `crates/openhuman-embed/tests/structured_validation.rs`, `crates/openhuman-embed/tests/structured_turns.rs` | ✅ | Wrong types and numeric combinators refused, invalid/external schemas make no call, repair bounded with usage, terminal length rejected even for complete JSON. |
| 16.1.16 | Explicit routing ladders and required exploration | RI | `crates/openhuman-embed/tests/completion_routing.rs`, `crates/openhuman-embed/tests/tool_required_routing.rs`, `crates/openhuman-embed/tests/structured_turns.rs` | ✅ | Ordered fallbacks, bounded truncation retries, unpinned terminal provider selection, image/options preservation, accumulated reported costs, actual answering model and refusal of schema-valid output before successful tool execution |
| 16.1.19 | Pinned standalone Embed source consumer | Script+RI | `scripts/__tests__/embed-consumer-bootstrap.test.mjs` | ✅ | Exact SHA verification, inherited workspace edition, generated active patches, stable locked offline builds with optional Embed enabled/disabled, default dependency tree without HTTP, no untracked secrets or Git metadata, refused malformed/escaping patches and existing destinations |
+| 16.1.17 | Enforced shared turn/run budgets | RU+RI | `crates/openhuman-embed/tests/budget_fanout.rs`, `vendor/tinyagents/vendor/tinyinference/crates/tinyinference-llm/src/model/budget_tests.rs` | ✅ | Atomic parent/child reservations, physical provider admission, conservative unknown spend, cancellation and output cap |
+| 16.1.18 | Ordered bounded fanout | RI | `crates/openhuman-embed/tests/budget_fanout.rs` | ✅ | Input-order results, per-branch and child error isolation, branch ceilings, shared-budget concurrent refusal and empty fanout |
## Summary
diff --git a/docs/embed-budget-fanout.md b/docs/embed-budget-fanout.md
new file mode 100644
index 0000000000..c7ec4e6db3
--- /dev/null
+++ b/docs/embed-budget-fanout.md
@@ -0,0 +1,78 @@
+# Embedded budgets and fanout
+
+`Completer::budget` and `Turn::budget` accept `budget::ModelBudget`. Its ledger
+is shared by clones, tool-loop calls, retries, fallback routes, compaction and
+synchronous subagents. `Budget::child` adds a local ceiling while every call
+also debits every ancestor. Use one fresh root ledger per review/run.
+
+```rust,no_run
+use openhuman_embed::budget::{Budget, CallBudget, ModelBudget, SpendLimits};
+let run = Budget::new(SpendLimits {
+ tokens: Some(200_000),
+ cost_micros: Some(2_000_000), // $2
+});
+let turn = ModelBudget {
+ ledger: run.child(SpendLimits {
+ tokens: Some(40_000),
+ cost_micros: Some(400_000),
+ }),
+ call: CallBudget {
+ input_tokens: 10_000,
+ output_tokens: 1_000,
+ cost_micros: 100_000,
+ },
+};
+```
+
+Each physical provider call reserves input plus its capped output tokens and
+the cost upper bound under one shared lock. Completed spend plus every live
+reservation must fit the turn and ancestor ceilings. Usage reconciliation is
+atomic too. Once refused, no provider request is sent; the facade returns
+`CoreError::BudgetExceeded` with completed spend, outstanding reservations,
+requested reservation and refusing limits.
+
+Choose conservative per-call bounds for **all allowed routes**, including
+fallback prices, reasoning and cached-input billing. This is pre-call admission,
+not a provider-side monetary cap: an incorrect bound or a provider violating its
+output cap can exceed the reservation. Actual excess is recorded and refuses
+further calls. Missing cost, failed requests and cancellation retain the cost
+reservation; unknown token usage retains the token reservation. This prevents
+lost responses from quietly restoring spend that may already have been billed.
+
+Budgeted calls currently accept text input. Serialized message and tool-schema
+bytes bound input tokens conservatively; the host's input bound must also leave
+room for provider framing. Non-text inputs and pass-through output cap overrides
+are refused before dispatch. Normal calls without a budget retain their existing
+modality support.
+
+## Ordered bounded fanout
+
+`Runtime::fanout` and `fanout::fanout` accept `Vec<Branch>`, a `NonZeroUsize`
+concurrency bound and a shared `ModelBudget`. The free function suits stateless
+completers without a runtime. `LeafCall` carries a completion or an owned turn;
+`Branch::limits` adds a branch ceiling to the shared ledger.
+
+Every result occupies its input slot regardless of finish order. A root error
+skips only its own children; errors in children are individually returned and
+leave later children running. At most the declared number of branches execute
+at once. A branch runs its root then its children sequentially. Dropping fanout
+drops the in-flight futures; it leaves no spawned background calls.
+
+`Branch::children` accepts only `LeafCall`, which has no children method. Model
+subagent depth is also narrowed at turn admission: root calls permit at most one
+level and declared leaf calls permit none. The explicit host carrier inherits
+the ceiling; TinyAgents and the OpenHuman spawn boundary check it before calls.
+An unset agent session gets a fresh session ID. Hosts should supply distinct
+session identities when setting them explicitly.
+
+Validation lives in `crates/openhuman-embed/tests/budget_fanout.rs`,
+`structured_turns.rs`, the explicit run-carrier tests, and TinyInference's
+`model/budget_tests.rs`. All provider fixtures run locally with wiremock or
+scripted models.
+
+Hosts with borrowed tree readers or custom mock model futures can use
+`fanout_futures(Vec<BranchFuture<'a, T, E>>, concurrency)` instead. Its boxed
+futures may borrow local inputs and retain their own error type. This scheduler
+is also used by the typed primitive. Configure each model future's budget
+explicitly; an opaque future may be entirely offline and is not assumed to
+perform inference.
diff --git a/vendor/tinyagents b/vendor/tinyagents
index 5db9caf3b2..47111f9896 160000
--- a/vendor/tinyagents
+++ b/vendor/tinyagents
@@ -1 +1 @@
-Subproject commit 5db9caf3b2224d8c49cdb29fe57196f9c3d34ca2
+Subproject commit 47111f9896e7ce68c1bd74aa9ffea417f3f61d9a