Skip to content

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

fix: correct credential handling and schema validation in core modules

Steven Enamakel96bfd552da22
diff --git a/crates/openhuman-core/src/agent/tinyagents/turn_runner.rs b/crates/openhuman-core/src/agent/tinyagents/turn_runner.rs
new file mode 100644
index 0000000000..723115fdaf
--- /dev/null
+++ b/crates/openhuman-core/src/agent/tinyagents/turn_runner.rs
@@ -0,0 +1,642 @@
+//! Drive an openhuman agent turn through the `tinyagents` agent-loop harness.
+//!
+//! [`run_turn_via_tinyagents_shared`] is the entry point the channel/session/
+//! sub-agent routes use; [`run_turn_via_tinyagents`] is a thin test-only
+//! variant with no middleware stack.
+
+use std::collections::HashSet;
+use std::sync::Arc;
+
+use anyhow::Result;
+use futures::StreamExt;
+use tinyagents_harness::agent_loop::AgentStreamItem;
+use tinyagents_harness::context::{RunConfig, RunContext};
+use tinyagents_harness::events::EventSink;
+use tinyagents_harness::store::StoreRegistry;
+use tinyagents_harness::workspace::WorkspaceDescriptor;
+use tinyagents_registry::DiagnosticSeverity;
+use tokio::sync::mpsc::Sender;
+
+use crate::agent::harness::tool_result_artifacts::TINYAGENTS_TOOL_RESULT_ARTIFACT_STORE;
+use crate::agent::harness::{run_queue::RunQueue, MAX_SPAWN_DEPTH};
+use crate::agent::messages::ChatMessage;
+use crate::agent::progress::AgentProgress;
+use crate::agent::tinyagents::harness_assembly::{assemble_turn_harness, AssembledTurnHarness};
+use crate::agent::tinyagents::middleware::TurnContextMiddleware;
+use crate::agent::tinyagents::model::{ProfileOverrideModel, TurnChatModel};
+use crate::agent::tinyagents::observability::{CapPauser, OpenhumanEventBridge, SubagentScope};
+use crate::agent::tinyagents::run_cancellation_context::with_run_cancellation;
+#[cfg(test)]
+use crate::agent::tinyagents::tools::ToolAdapter;
+use crate::agent::tinyagents::turn_models::TurnModels;
+use crate::agent::tinyagents::turn_outcome::TinyagentsTurnOutcome;
+use crate::agent::tinyagents::turn_policy::{effective_max_iterations, run_policy_for};
+use crate::agent::tinyagents::turn_run_error::map_turn_run_error;
+use crate::agent::tinyagents::turn_run_finalize::finalize_turn_outcome;
+use crate::agent::tinyagents::{journal, orchestration, routes, steering_forwarder};
+
+use super::ToolPolicyEnforcement;
+
+/// Drive an agent turn through the `tinyagents` agent-loop harness.
+///
+/// Registers `provider` as the default model and every entry in `resolved_tools`
+/// as a harness tool, seeds the loop with `history`, and runs the loop bounded
+/// by `max_iterations` model calls. Returns the final text plus the resulting
+/// transcript translated back to openhuman [`ChatMessage`]s.
+#[cfg(test)]
+pub(crate) async fn run_turn_via_tinyagents(
+ chat_model: TurnChatModel,
+ model: &str,
+ temperature: f64,
+ history: Vec<ChatMessage>,
+ resolved_tools: Vec<Arc<dyn crate::tools::Tool>>,
+ max_iterations: usize,
+) -> Result<TinyagentsTurnOutcome> {
+ // `0` means "unset" → the legacy default; otherwise the harness cap would be
+ // zero and the run would abort before the first model call.
+ let max_iterations = effective_max_iterations(max_iterations);
+ let mut harness: tinyagents_harness::runtime::AgentHarness<()> =
+ tinyagents_harness::runtime::AgentHarness::new();
+ // Thin test variant: no response cache (chat-safe default).
+ harness.with_policy(run_policy_for(max_iterations, false));
+ let profile = chat_model.profile().cloned().unwrap_or_default();
+ let chat_model: TurnChatModel = Arc::new(
+ ProfileOverrideModel::new(chat_model, profile)
+ .with_request_model(model)
+ .with_request_temperature(temperature),
+ );
+ let error_slot = Arc::new(std::sync::Mutex::new(None));
+ harness
+ .register_model(model, chat_model)
+ .set_default_model(model);
+ let tool_count = resolved_tools.len();
+ for tool in resolved_tools {
+ harness.register_tool(Arc::new(ToolAdapter::new(tool)));
+ }
+
+ // Bound the run: one model call per legacy "iteration", and allow generous
+ // tool calls (the loop also stops when the model stops requesting tools).
+ let config = RunConfig::new("agent_turn")
+ .with_max_model_calls(max_iterations)
+ .with_max_tool_calls(max_iterations.saturating_mul(8).max(8))
+ .with_max_depth(MAX_SPAWN_DEPTH)
+ .with_tag("openhuman")
+ .with_tag("scope:root")
+ .with_tag("unobserved");
+
+ tracing::info!(
+ model,
+ max_iterations,
+ tools = tool_count,
+ "[tinyagents] routing agent turn through tinyagents harness"
+ );
+
+ let input = crate::agent::message_convert::history_to_messages(&history);
+ // Explicit persistence boundary (issue #4455): the request transcript length,
+ // captured *before* the run consumes `input`. Everything the harness appends
+ // after this index — assistant/tool rounds plus any mid-turn steer messages —
+ // is this turn's persisted `conversation`. Anchoring on this index instead of
+ // the last-user-message suffix keeps injected steers (which move that
+ // boundary) from truncating persisted history.
+ let request_base_len = input.len();
+ // Box the (large) harness drive future — see `run_turn_via_tinyagents_shared`.
+ let run = match Box::pin(harness.invoke(&(), (), config, input)).await {
+ Ok(run) => run,
+ Err(e) => {
+ // #4469 item 3: recover from a poisoned slot instead of panicking.
+ // A thread that panicked mid-run while holding this mutex would
+ // otherwise turn every subsequent error-recovery read into a second
+ // panic, masking the original provider failure. `into_inner` yields
+ // the guarded value regardless of poison so we still re-surface the
+ // typed error.
+ if let Some(original) = error_slot
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .take()
+ {
+ return Err(original);
+ }
+ return Err(anyhow::anyhow!("tinyagents harness run failed: {e}"));
+ }
+ };
+
+ let text = run.text().unwrap_or_default();
+ let out_history = crate::agent::message_convert::messages_to_history(&run.messages);
+ let conversation = crate::agent::message_convert::messages_to_conversation(
+ crate::agent::message_convert::messages_since_request(&run.messages, request_base_len),
+ );
+ tracing::debug!(
+ request_base_len,
+ transcript_len = run.messages.len(),
+ persisted_messages = run.messages.len().saturating_sub(request_base_len),
+ "[tinyagents] persisting post-request transcript (thin path; steer-safe boundary)"
+ );
+
+ Ok(TinyagentsTurnOutcome {
+ text,
+ history: out_history,
+ conversation,
+ model_calls: run.model_calls,
+ tool_calls: run.tool_calls,
+ input_tokens: run.usage.usage.input_tokens,
+ output_tokens: run.usage.usage.output_tokens,
+ cached_input_tokens: run.usage.usage.cache_read_tokens,
+ charged_amount_usd: crate::platform::cost::catalog::estimate_cost_usd(
+ model,
+ run.usage.usage.input_tokens,
+ run.usage.usage.output_tokens,
+ run.usage.usage.cache_read_tokens,
+ ),
+ early_exit_tool: None,
+ hit_cap: false,
+ // The thin (test-only) variant installs no middleware, so nothing could
+ // have injected a conclusion.
+ wrap_up_injected: false,
+ // This thin (test-only) variant does not install the breaker middleware.
+ breaker_halt: None,
+ // This thin variant carries no per-call outcome capture middleware.
+ tool_outcomes: Vec::new(),
+ })
+}
+
+/// Drive a turn through the tinyagents harness over the routes' **shared**,
+/// `Arc`-owned tool registry sets (`Arc<Vec<Box<dyn Tool>>>`), advertising
+/// exactly `specs` (already filtered/deduped by the caller's visibility rules).
+///
+/// This is the entry point the channel/sub-agent routes use to retire the
+/// in-house `live` turn machine: it registers a [`SharedToolAdapter`](super::tools::SharedToolAdapter)
+/// per advertised spec so the same `Arc`-shared tools the legacy loop runs are
+/// reused without cloning.
+///
+/// `allowed` is the callable tool-name whitelist. Its semantics are
+/// **fail-closed** (issue #4452): `None` means "no filter supplied" → every tool
+/// visible in `tool_sets` is registered; `Some(set)` registers *exactly* the
+/// named tools, so `Some(empty)` is an explicit **deny-all** (zero tools). This
+/// distinction is what stops a tool-less sub-agent (`ToolScope::Named([])`, a
+/// zero-match `skill_filter`, or a `named` list that resolves to nothing) from
+/// silently inheriting the parent's full tool surface (shell/file-write/spawn).
+/// Each registered tool is advertised via its own `spec()`.
+///
+/// When `on_progress` is `Some`, the run streams (`invoke_stream_in_context`)
+/// and a [`OpenhumanEventBridge`] mirrors the harness event stream onto
+/// `AgentProgress` (live tool timeline, text deltas, cost/token footer) and the
+/// global cost tracker — restoring the seams the legacy `run_turn_engine`
+/// produced. Pass `None` for fire-and-forget turns (channel/sub-agent) that
+/// only need the final text.
+///
+/// When `context_window` is known, an
+/// [`ImageAwareMessageTrimMiddleware`](super::middleware::ImageAwareMessageTrimMiddleware)
+/// keeps history under budget (autocompaction parity).
+///
+/// `run_queue` forwards mid-flight steer messages into the run; `subagent_scope`
+/// re-scopes progress to the `Subagent*` variants (child runs); `early_exit_tools`
+/// name the tools that pause the loop (e.g. `ask_user_clarification`) and surface
+/// the question via [`TinyagentsTurnOutcome::early_exit_tool`].
+#[allow(clippy::too_many_arguments)]
+pub(crate) async fn run_turn_via_tinyagents_shared(
+ turn_models: TurnModels,
+ provider_id: String,
+ model: &str,
+ history: Vec<ChatMessage>,
+ tool_sets: Vec<Arc<Vec<Box<dyn crate::tools::Tool>>>>,
+ allowed: Option<HashSet<String>>,
+ max_iterations: usize,
+ on_progress: Option<Sender<AgentProgress>>,
+ subagent_scope: Option<SubagentScope>,
+ context_window: Option<u64>,
+ run_queue: Option<Arc<RunQueue>>,
+ early_exit_tools: &[&str],
+ pause_at_cap: bool,
+ max_output_tokens: Option<u32>,
+ context_mw: TurnContextMiddleware,
+ tool_policy: Option<ToolPolicyEnforcement>,
+ workspace_descriptor: Option<WorkspaceDescriptor>,
+ deterministic_cacheable: bool,
+ // #4457 (defect C): when `true`, the seam does NOT emit the terminal
+ // `TurnCompleted` — the caller emits it itself *after* its post-run wrap-up
+ // (e.g. the chat/session path streams a cap/#4093 checkpoint via
+ // `summarize_turn_wrapup` after this seam returns, so a seam-level emit here
+ // would land `turn_active = false` before that checkpoint finishes
+ // streaming, and the web bridge would record two ledger events + two
+ // Completed upserts). Callers with no post-run streaming (channel/CLI) pass
+ // `false` and rely on this seam's emit for parity with the legacy engine.
+ defer_turn_completed_to_caller: bool,
+) -> Result<TinyagentsTurnOutcome> {
+ // `0` means "unset" → the legacy default (a native-bus / test convention);
+ // 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);
+ // The turn's crate `ChatModel` set (`turn_models`) and the provider telemetry
+ // id are built by the caller via `build_turn_models` — the seam entry is
+ // crate-native and no longer names `Provider` (issue #4249, Phase 5). The
+ // telemetry id (`{provider_id}.{model}` in Langfuse) rides in as a param.
+ let AssembledTurnHarness {
+ harness,
+ cursor,
+ tool_names,
+ failure_map,
+ provider_usage_carry,
+ error_slot,
+ halt_summary,
+ tool_outcome_sink,
+ handle,
+ early_exit_hook,
+ wrap_up_fired,
+ tool_count,
+ registry_snapshot: _,
+ registry_diagnostics,
+ tool_result_artifact_index,
+ compression_mw,
+ prompt_cache_guard,
+ } = assemble_turn_harness(
+ turn_models,
+ model,
+ tool_sets,
+ allowed,
+ max_iterations,
+ on_progress.clone(),
+ subagent_scope.clone(),
+ context_window,
+ early_exit_tools,
+ context_mw,
+ tool_policy,
+ routes::turn_required_capabilities(model),
+ deterministic_cacheable,
+ pause_at_cap,
+ );
+
+ // Fail-closed registry validation gate (issue #4249, Workstream 10 — registry).
+ // The projected `CapabilityRegistry` produced these diagnostics during
+ // assembly; enforce them here, *before* the first model dispatch, so an
+ // ambiguous/broken tool surface (duplicate name across native/MCP/Composio/
+ // generated tools, dangling alias, etc.) aborts the turn instead of silently
+ // resolving to an unintended component while a provider call is in flight.
+ if !registry_diagnostics.is_empty() {
+ let (errors, warnings): (Vec<&tinyagents_registry::RegistryDiagnostic>, Vec<&tinyagents_registry::RegistryDiagnostic>) =
+ registry_diagnostics
+ .iter()
+ .partition(|d| matches!(d.severity, DiagnosticSeverity::Error));
+ for diag in &warnings {
+ tracing::warn!(
+ kind = diag.kind.as_str(),
+ name = %diag.name,
+ "[registry] non-fatal diagnostic: {}",
+ diag.message
+ );
+ }
+ if !errors.is_empty() {
+ let messages: Vec<String> = errors
+ .iter()
+ .map(|d| format!("[{}] {}: {}", d.kind.as_str(), d.name, d.message))
+ .collect();
+ for msg in &messages {
+ tracing::error!("[registry] error-severity diagnostic aborting turn: {msg}");
+ }
+ tracing::error!(
+ error_count = messages.len(),
+ warning_count = warnings.len(),
+ "[registry] aborting turn before model dispatch: capability registry validation failed"
+ );
+ return Err(anyhow::Error::new(
+ crate::agent::error::AgentError::RegistryValidationFailed {
+ diagnostics: messages,
+ },
+ ));
+ }
+ tracing::debug!(
+ warning_count = warnings.len(),
+ "[registry] registry diagnostics present (warnings only); proceeding with turn"
+ );
+ }
+
+ let mut config = RunConfig::new("agent_turn")
+ .with_max_model_calls(max_iterations)
+ .with_max_tool_calls(max_iterations.saturating_mul(8).max(8))
+ .with_max_depth(MAX_SPAWN_DEPTH)
+ .with_tag("openhuman")
+ .with_tag(if subagent_scope.is_some() {
+ "scope:subagent"
+ } else {
+ "scope:root"
+ })
+ .with_tag(if on_progress.is_some() {
+ "observed"
+ } else {
+ "unobserved"
+ });
+ // Per-turn output cap rides RunConfig now (Phase 5 groundwork): the loop
+ // stamps it onto every `ModelRequest.max_tokens` and the native model adapter
+ // adapter honors it, so the cap no longer bakes into the primary + route
+ // models. Mirrors the legacy `AGENT_TURN_MAX_OUTPUT_TOKENS` / sub-agent cap.
+ if let Some(cap) = max_output_tokens {
+ config = config.with_max_turn_output_tokens(cap);
+ }
+
+ tracing::info!(
+ model,
+ max_iterations,
+ tools = tool_count,
+ observed = on_progress.is_some(),
+ "[tinyagents] routing turn through tinyagents harness (shared tools)"
+ );
+
+ let input = crate::agent::message_convert::history_to_messages(&history);
+ // Explicit persistence boundary (issue #4455): the request transcript length,
+ // captured *before* the run consumes `input`. The turn's persisted
+ // `conversation` is everything appended past this index — assistant/tool
+ // rounds plus any mid-turn steer/collect messages injected as user turns.
+ // Anchoring here (instead of the last-user-message suffix) keeps injected
+ // steers from moving the boundary and truncating persisted history on both
+ // the parent (`session/turn/core.rs`) and subagent (`subagent_runner`) paths.
+ let request_base_len = input.len();
+
+ // 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 = tinyagents_harness::CancellationToken::new();
+ let mut ctx = RunContext::new(config, ()).with_cancellation(cancellation.clone());
+ if let Some(descriptor) = workspace_descriptor {
+ tracing::debug!(
+ root = %descriptor.root.display(),
+ policy_id = %descriptor.policy_id,
+ "[tinyagents] attaching workspace descriptor"
+ );
+ ctx = ctx.with_workspace(descriptor);
+ }
+ // Assemble the run's store registry: the tool-result artifact index (when
+ // present) and — behind the default-ON session dual-write flag — the
+ // session KV store, so the harness carries a handle to the same
+ // `{workspace}/tinyagents_store/kv` tree the live dual-write mirrors into
+ // (issue #4249, 04.1). Both stores share one registry so neither clobbers
+ // the other. Reads stay legacy until 04.2; this registration is additive
+ // and best-effort (a workspace-resolve failure just skips it).
+ let mut stores: Option<StoreRegistry> = None;
+ if let Some(index) = tool_result_artifact_index {
+ stores
+ .get_or_insert_with(StoreRegistry::new)
+ .register(TINYAGENTS_TOOL_RESULT_ARTIFACT_STORE, index);
+ }
+ // `session_kv_store` self-gates on the dual-write flag (config default ON +
+ // env kill switch), returning `None` when disabled or unresolvable.
+ if let Some(session_kv) = crate::agent::session_import::live::session_kv_store().await {
+ stores.get_or_insert_with(StoreRegistry::new).register(
+ crate::agent::session_import::live::TINYAGENTS_SESSION_KV_STORE,
+ session_kv,
+ );
+ tracing::debug!(
+ "[session-store] registered session kv store on RunContext.stores under '{}'",
+ crate::agent::session_import::live::TINYAGENTS_SESSION_KV_STORE
+ );
+ }
+ if let Some(stores) = stores {
+ ctx = ctx.with_stores(stores);
+ }
+
+ let streaming = on_progress.is_some();
+ // Retain a clone of the progress sink so the turn can emit a terminal
+ // `TurnCompleted` after the run (the harness event stream the bridge mirrors
+ // has no run-completed event). Parent turns only — a sub-agent turn reports
+ // via its `Subagent*` events, not a top-level `TurnCompleted`.
+ //
+ // #4457 (defect C): suppressed entirely when `defer_turn_completed_to_caller`
+ // is set — the caller (chat/session path) emits the single terminal
+ // `TurnCompleted` itself, after its post-run wrap-up finishes streaming.
+ let turn_completed_sink = (subagent_scope.is_none() && !defer_turn_completed_to_caller)
+ .then(|| on_progress.clone())
+ .flatten();
+ // A sink is needed to mirror progress (bridge), to observe model-call
+ // completions for the cap pauser, or to persist a durable event journal
+ // (issue #4249, 05.1). The journal must attach even for an unobserved
+ // (`on_progress = None`) turn so the run stays reconstructable, so the
+ // EventSink is now created unconditionally — cheap (an empty sink) and, if
+ // no consumer subscribes, inert.
+ //
+ // Mint the durable run id *before* the sink and seed the sink stream prefix
+ // with it (`with_stream_id`), so every persisted observation's `event_id` is
+ // the restart-stable `{run_id}-evt-{offset}` a late-attach replay
+ // reconstructs the timeline from (05.1). The same id keys the journal + status.
+ let journal_run_id = journal::mint_run_id();
+ let events = Some(EventSink::with_stream_id(journal_run_id.as_str()));
+
+ // Attach the event bridge for EVERY turn — including an unobserved
+ // (`on_progress = None`) background/cron turn (#4467, item 3). The bridge's
+ // `record_usage` feeds the global cost tracker on each `UsageRecorded` event
+ // *during* the run, so a run that burns N model calls and then fails still
+ // contributes that spend to the wallet/cost surfaces — the post-run
+ // `record_unobserved_turn_usage` fallback below only runs on the success path
+ // and never sees a failed run's usage. With `on_progress = None` the bridge
+ // still records cost but its progress `send`s are inert no-ops, so there is
+ // no spurious streaming. `events` is created unconditionally above, so the
+ // bridge is always present.
+ let bridge = events.as_ref().map(|events| {
+ let bridge = OpenhumanEventBridge::with_scope(
+ on_progress,
+ model,
+ provider_id.clone(),
+ max_iterations,
+ subagent_scope.clone(),
+ cursor.clone(),
+ tool_names.clone(),
+ failure_map.clone(),
+ provider_usage_carry.clone(),
+ );
+ events.subscribe(bridge.clone());
+ bridge
+ });
+
+ // Cap pauser: stop gracefully at the model-call budget (returning the partial
+ // transcript) so the caller can summarize a checkpoint instead of erroring.
+ //
+ // It is also handed the turn's dispatch guard, so the pause is *recorded* and
+ // not merely requested. `SteeringCommand::Pause` is advisory — honoured at the
+ // loop boundary — and nothing consulted it before dispatching a new sub-agent,
+ // so a dispatch issued in the same instant raced it and took the whole turn
+ // down with the run's remaining wall-clock budget (#5804). The guard is
+ // resolved here rather than inside the listener because this future runs on
+ // the turn's task, where the task-local is in scope; the listener need not.
+ if pause_at_cap {
+ if let (Some(events), Some(handle)) = (&events, &handle) {
+ // Only the TOP-LEVEL turn's cap pause is binding on dispatch. A
+ // sub-agent reaching its own model-call cap is a routine outcome —
+ // it summarises and hands its result back (`hit_cap`) — and the
+ // parent may legitimately keep delegating afterwards. Recording a
+ // child's cap here would stop the whole turn's fan-out on a signal
+ // that says nothing about the parent's budget, so `subagent_scope`
+ // gates it: `None` is the chat turn, `Some` is a delegated child.
+ // The child still gets its advisory `Pause` either way.
+ let dispatch_guard = subagent_scope
+ .is_none()
+ .then(crate::agent::harness::turn_dispatch_guard::current)
+ .flatten();
+ events.subscribe(CapPauser::new(
+ handle.clone(),
+ max_iterations,
+ dispatch_guard,
+ ));
+ }
+ }
+
+ // Durable event journal + status store (issue #4249, 05.1). Attached *in
+ // addition to* the bridge above: the EventSink fans out to both, so the
+ // existing progress/global-bus path is untouched. Best-effort and non-fatal
+ // — a failure to open/attach the journal returns `None` and the turn runs
+ // unaffected. The handle stamps the terminal status once the run returns.
+ // A sub-agent turn records under its task scope as the status thread id, so
+ // `list_by_thread` can enumerate a task's runs (full parent/root lineage is
+ // a 05.2/05.3 follow-up).
+ let journal_thread_id = subagent_scope
+ .as_ref()
+ .map(|scope| tinyagents_harness::ids::ThreadId::new(scope.task_id.clone()));
+ let turn_journal = match &events {
+ Some(events) => {
+ journal::attach_turn_journal(events, model, journal_run_id.clone(), journal_thread_id)
+ .await
+ }
+ None => None,
+ };
+ if subagent_scope.is_none() {
+ if let Some(crate::agent::turn_origin::AgentTurnOrigin::WebChat {
+ request_id: Some(request_id),
+ ..
+ }) = crate::agent::turn_origin::current()
+ {
+ journal::register_request_journal_run(&request_id, journal_run_id.as_str());
+ }
+ }
+
+ if let Some(events) = &events {
+ ctx = ctx.with_events(events.clone());
+ }
+
+ // Steering: attach the shared handle (when present), drain any already-queued
+ // steer messages into it (so a pre-run steer lands before the first model
+ // call), and forward mid-flight steers via a poll loop. The same handle
+ // carries the early-exit `Pause`.
+ //
+ // Best-effort thread label for the delivery/requeue observability events and
+ // the metadata on any requeued steer: a sub-agent uses its task id; the
+ // interactive/channel parent turn reads the task-local turn origin.
+ let steer_thread_label = subagent_scope
+ .as_ref()
+ .map(|s| s.task_id.clone())
+ .or_else(|| match crate::agent::turn_origin::current() {
+ Some(crate::agent::turn_origin::AgentTurnOrigin::WebChat { thread_id, .. }) => {
+ Some(thread_id)
+ }
+ Some(crate::agent::turn_origin::AgentTurnOrigin::ExternalChannel {
+ reply_target,
+ ..
+ }) => Some(reply_target),
+ _ => None,
+ })
+ .unwrap_or_default();
+
+ // The forwarder is wrapped in an abort-on-drop RAII guard (issue #4456): its
+ // `Drop` aborts the poll task, deregisters the sub-agent steering handle, and
+ // drains residual (delivered-but-unapplied) steers back into the session run
+ // queue. Because the guard is held across the drive future, that cleanup runs
+ // identically on normal return, error, AND drop-cancellation — the previous
+ // manual `forwarder.abort()` after the drive future only ran on normal
+ // return, so a cancelled turn (web interrupt / sub-agent abort, both
+ // drop-based) leaked a forwarder task that looped forever and raced the next
+ // turn for the shared run queue.
+ let steering_forwarder_guard = if let Some(handle) = handle {
+ let registry_task_id = if let Some(scope) = &subagent_scope {
+ let task_id = orchestration::TaskId::new(scope.task_id.clone());
+ orchestration::shared_steering_registry().register(task_id.clone(), handle.clone());
+ tracing::debug!(
+ task_id = scope.task_id.as_str(),
+ "[tinyagents] registered subagent steering handle"
+ );
+ Some(task_id)
+ } else {
+ None
+ };
+ // Pre-run drain so a steer/collect queued before the turn started lands
+ // ahead of the first model call.
+ if let Some(queue) = run_queue.clone() {
+ steering_forwarder::forward_steers(&queue, &handle, &steer_thread_label).await;
+ steering_forwarder::forward_collects(&queue, &handle, &steer_thread_label).await;
+ }
+ ctx = ctx.with_steering(handle.clone());
+ Some(steering_forwarder::SteeringForwarderGuard::new(
+ handle,
+ run_queue,
+ registry_task_id,
+ steer_thread_label.clone(),
+ ))
+ } else {
+ None
+ };
+
+ // Heap-allocate the harness drive future. It is large (it owns the whole run
+ // context, middleware stack, and loop state), and a sub-agent turn runs
+ // 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.
+ let run_result = 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;
+ }
+ }
+ }
+ 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 +
+ // requeue residual steers) rather than deferring to end-of-scope so the poll
+ // loop cannot deliver into the no-longer-drained handle during post-run
+ // journal/mapping work. On a *cancelled* turn this line is never reached; the
+ // guard's `Drop` fires as the turn future unwinds, giving identical cleanup.
+ drop(steering_forwarder_guard);
+ let run = match run_result {
+ Ok(run) => run,
+ Err(e) => {
+ return Err(map_turn_run_error(
+ e,
+ model,
+ max_iterations,
+ &error_slot,
+ turn_journal.as_ref(),
+ )
+ .await);
+ }
+ };
+
+ Ok(finalize_turn_outcome(
+ run,
+ model,
+ max_iterations,
+ &subagent_scope,
+ pause_at_cap,
+ turn_journal.as_ref(),
+ compression_mw.as_ref(),
+ &prompt_cache_guard,
+ turn_completed_sink,
+ bridge,
+ early_exit_hook,
+ &halt_summary,
+ &wrap_up_fired,
+ &tool_outcome_sink,
+ request_base_len,
+ )
+ .await)
+}
diff --git a/crates/openhuman-core/src/integrations/file_storage/tools/delete.rs b/crates/openhuman-core/src/integrations/file_storage/tools/delete.rs
new file mode 100644
index 0000000000..ca954881a8
--- /dev/null
+++ b/crates/openhuman-core/src/integrations/file_storage/tools/delete.rs
@@ -0,0 +1,91 @@
+//! `storage_delete_file` — permanently delete a stored file.
+
+use std::sync::Arc;
+
+use async_trait::async_trait;
+use serde_json::{json, Value};
+
+use super::helpers::{file_path, readonly_autonomy_block, validate_file_id};
+use crate::integrations::IntegrationClient;
+use crate::security::SecurityPolicy;
+use crate::tools::traits::{PermissionLevel, Tool, ToolCategory, ToolResult};
+
+use super::types::DeleteResponse;
+
+pub struct StorageDeleteFileTool {
+ client: Arc<IntegrationClient>,
+ security: Arc<SecurityPolicy>,
+}
+
+impl StorageDeleteFileTool {
+ pub fn new(client: Arc<IntegrationClient>) -> Self {
+ Self::new_with_security(client, Arc::new(SecurityPolicy::default()))
+ }
+
+ pub fn new_with_security(
+ client: Arc<IntegrationClient>,
+ security: Arc<SecurityPolicy>,
+ ) -> Self {
+ Self { client, security }
+ }
+}
+
+#[async_trait]
+impl Tool for StorageDeleteFileTool {
+ fn name(&self) -> &str {
+ "storage_delete_file"
+ }
+
+ fn description(&self) -> &str {
+ "Permanently delete a file from managed cloud file storage, freeing quota. \
+ Deletion is free and cannot be undone."
+ }
+
+ fn parameters_schema(&self) -> Value {
+ json!({
+ "type": "object",
+ "properties": {
+ "file_id": { "type": "string", "description": "The stored file's id" }
+ },
+ "required": ["file_id"]
+ })
+ }
+
+ fn permission_level(&self) -> PermissionLevel {
+ PermissionLevel::Write
+ }
+
+ fn category(&self) -> ToolCategory {
+ ToolCategory::Workflow
+ }
+
+ fn external_effect(&self) -> bool {
+ true
+ }
+
+ async fn execute(&self, args: Value) -> anyhow::Result<ToolResult> {
+ if let Some(blocked) = readonly_autonomy_block(&self.security) {
+ return Ok(blocked);
+ }
+
+ let file_id = match validate_file_id(&args) {
+ Ok(id) => id,
+ Err(e) => return Ok(ToolResult::error(e)),
+ };
+ tracing::debug!("[file_storage] deleting file_id={file_id}");
+ match self
+ .client
+ .delete::<DeleteResponse>(&file_path(&file_id, ""))
+ .await
+ {
+ Ok(resp) if resp.deleted => Ok(ToolResult::success_with_markdown(
+ json!({ "file_id": file_id, "deleted": true }),
+ format!("Deleted file {file_id}."),
+ )),
+ Ok(_) => Ok(ToolResult::error(format!(
+ "Backend did not confirm deletion of file {file_id}"
+ ))),
+ Err(e) => Ok(ToolResult::error(format!("Failed to delete file: {e}"))),
+ }
+ }
+}
diff --git a/crates/openhuman-core/src/memory/sources/schemas/registry_schemas.rs b/crates/openhuman-core/src/memory/sources/schemas/registry_schemas.rs
new file mode 100644
index 0000000000..d13fcd03d7
--- /dev/null
+++ b/crates/openhuman-core/src/memory/sources/schemas/registry_schemas.rs
@@ -0,0 +1,338 @@
+//! Schemas and handlers for the source-registry CRUD controllers: list, get,
+//! add, update, remove, list_items, read_item.
+
+use serde_json::{Map, Value};
+
+use crate::core::all::ControllerFuture;
+use crate::core::{ControllerSchema, FieldSchema, TypeSchema};
+use crate::memory::sources::rpc;
+
+use super::{parse_value, to_json, NAMESPACE};
+
+pub(super) fn kind_specific_fields() -> Vec<FieldSchema> {
+ vec![
+ FieldSchema {
+ name: "toolkit",
+ ty: TypeSchema::Option(Box::new(TypeSchema::String)),
+ comment: "Composio toolkit slug.",
+ required: false,
+ },
+ FieldSchema {
+ name: "connection_id",
+ ty: TypeSchema::Option(Box::new(TypeSchema::String)),
+ comment: "Composio connection id.",
+ required: false,
+ },
+ FieldSchema {
+ name: "path",
+ ty: TypeSchema::Option(Box::new(TypeSchema::String)),
+ comment: "Local folder path.",
+ required: false,
+ },
+ FieldSchema {
+ name: "glob",
+ ty: TypeSchema::Option(Box::new(TypeSchema::String)),
+ comment: "Glob pattern for folder sources.",
+ required: false,
+ },
+ FieldSchema {
+ name: "url",
+ ty: TypeSchema::Option(Box::new(TypeSchema::String)),
+ comment: "URL for github_repo, rss_feed, or web_page sources.",
+ required: false,
+ },
+ FieldSchema {
+ name: "branch",
+ ty: TypeSchema::Option(Box::new(TypeSchema::String)),
+ comment: "Git branch for github_repo sources.",
+ required: false,
+ },
+ FieldSchema {
+ name: "paths",
+ ty: TypeSchema::Array(Box::new(TypeSchema::String)),
+ comment: "Path filters for github_repo sources.",
+ required: false,
+ },
+ FieldSchema {
+ name: "max_commits",
+ ty: TypeSchema::Option(Box::new(TypeSchema::U64)),
+ comment: "Max commits per sync for github_repo sources.",
+ required: false,
+ },
+ FieldSchema {
+ name: "max_issues",
+ ty: TypeSchema::Option(Box::new(TypeSchema::U64)),
+ comment: "Max issues per sync for github_repo sources.",
+ required: false,
+ },
+ FieldSchema {
+ name: "max_prs",
+ ty: TypeSchema::Option(Box::new(TypeSchema::U64)),
+ comment: "Max pull requests per sync for github_repo sources.",
+ required: false,
+ },
+ FieldSchema {
+ name: "query",
+ ty: TypeSchema::Option(Box::new(TypeSchema::String)),
+ comment: "Search query for twitter_query sources.",
+ required: false,
+ },
+ FieldSchema {
+ name: "since_days",
+ ty: TypeSchema::Option(Box::new(TypeSchema::U64)),
+ comment: "Lookback window in days for twitter_query.",
+ required: false,
+ },
+ FieldSchema {
+ name: "max_items",
+ ty: TypeSchema::Option(Box::new(TypeSchema::U64)),
+ comment: "Maximum items for rss_feed or composio sources.",
+ required: false,
+ },
+ FieldSchema {
+ name: "selector",
+ ty: TypeSchema::Option(Box::new(TypeSchema::String)),
+ comment: "CSS selector for web_page sources.",
+ required: false,
+ },
+ FieldSchema {
+ name: "max_tokens_per_sync",
+ ty: TypeSchema::Option(Box::new(TypeSchema::U64)),
+ comment: "Max tokens per sync run.",
+ required: false,
+ },
+ FieldSchema {
+ name: "max_cost_per_sync_usd",
+ ty: TypeSchema::Option(Box::new(TypeSchema::F64)),
+ comment: "Max cost per sync run in USD.",
+ required: false,
+ },
+ FieldSchema {
+ name: "sync_depth_days",
+ ty: TypeSchema::Option(Box::new(TypeSchema::U64)),
+ comment: "Only sync items from the last N days.",
+ required: false,
+ },
+ ]
+}
+
+pub(super) fn schema(function: &str) -> Option<ControllerSchema> {
+ Some(match function {
+ "list" => ControllerSchema {
+ namespace: NAMESPACE,
+ function: "list",
+ description: "List all configured memory sources.",
+ inputs: vec![],
+ outputs: vec![FieldSchema {
+ name: "sources",
+ ty: TypeSchema::Array(Box::new(TypeSchema::Ref("MemorySourceEntry"))),
+ comment: "All configured sources.",
+ required: true,
+ }],
+ },
+ "get" => ControllerSchema {
+ namespace: NAMESPACE,
+ function: "get",
+ description: "Get a single memory source by id.",
+ inputs: vec![FieldSchema {
+ name: "id",
+ ty: TypeSchema::String,
+ comment: "Source id.",
+ required: true,
+ }],
+ outputs: vec![FieldSchema {
+ name: "source",
+ ty: TypeSchema::Option(Box::new(TypeSchema::Ref("MemorySourceEntry"))),
+ comment: "The source if found.",
+ required: false,
+ }],
+ },
+ "add" => {
+ let mut inputs = vec![
+ FieldSchema {
+ name: "kind",
+ ty: TypeSchema::Enum {
+ variants: vec![
+ "composio",
+ "conversation",
+ "folder",
+ "github_repo",
+ "twitter_query",
+ "rss_feed",
+ "web_page",
+ ],
+ },
+ comment: "Source kind.",
+ required: true,
+ },
+ FieldSchema {
+ name: "label",
+ ty: TypeSchema::String,
+ comment: "User-facing display name.",
+ required: true,
+ },
+ FieldSchema {
+ name: "enabled",
+ ty: TypeSchema::Bool,
+ comment: "Whether the source is active. Defaults to true.",
+ required: false,
+ },
+ ];
+ inputs.extend(kind_specific_fields());
+ ControllerSchema {
+ namespace: NAMESPACE,
+ function: "add",
+ description:
+ "Add a new memory source. Kind-specific fields are flat on the request.",
+ inputs,
+ outputs: vec![FieldSchema {
+ name: "source",
+ ty: TypeSchema::Ref("MemorySourceEntry"),
+ comment: "The newly created source.",
+ required: true,
+ }],
+ }
+ }
+ "update" => {
+ let mut inputs = vec![
+ FieldSchema {
+ name: "id",
+ ty: TypeSchema::String,
+ comment: "Source id to update.",
+ required: true,
+ },
+ FieldSchema {
+ name: "label",
+ ty: TypeSchema::Option(Box::new(TypeSchema::String)),
+ comment: "New label.",
+ required: false,
+ },
+ FieldSchema {
+ name: "enabled",
+ ty: TypeSchema::Option(Box::new(TypeSchema::Bool)),
+ comment: "Enable or disable.",
+ required: false,
+ },
+ ];
+ inputs.extend(kind_specific_fields());
+ ControllerSchema {
+ namespace: NAMESPACE,
+ function: "update",
+ description: "Partial update of a memory source.",
+ inputs,
+ outputs: vec![FieldSchema {
+ name: "source",
+ ty: TypeSchema::Ref("MemorySourceEntry"),
+ comment: "The updated source.",
+ required: true,
+ }],
+ }
+ }
+ "remove" => ControllerSchema {
+ namespace: NAMESPACE,
+ function: "remove",
+ description: "Remove a memory source.",
+ inputs: vec![FieldSchema {
+ name: "id",
+ ty: TypeSchema::String,
+ comment: "Source id to remove.",
+ required: true,
+ }],
+ outputs: vec![FieldSchema {
+ name: "removed",
+ ty: TypeSchema::Bool,
+ comment: "True if the source was found and removed.",
+ required: true,
+ }],
+ },
+ "list_items" => ControllerSchema {
+ namespace: NAMESPACE,
+ function: "list_items",
+ description: "List readable items from a memory source via its reader.",
+ inputs: vec![FieldSchema {
+ name: "source_id",
+ ty: TypeSchema::String,
+ comment: "Source id to list items from.",
+ required: true,
+ }],
+ outputs: vec![FieldSchema {
+ name: "items",
+ ty: TypeSchema::Array(Box::new(TypeSchema::Ref("SourceItem"))),
+ comment: "Items available in the source.",
+ required: true,
+ }],
+ },
+ "read_item" => ControllerSchema {
+ namespace: NAMESPACE,
+ function: "read_item",
+ description: "Read one item's content from a memory source.",
+ inputs: vec![
+ FieldSchema {
+ name: "source_id",
+ ty: TypeSchema::String,
+ comment: "Source id.",
+ required: true,
+ },
+ FieldSchema {
+ name: "item_id",
+ ty: TypeSchema::String,
+ comment: "Item id within the source.",
+ required: true,
+ },
+ ],
+ outputs: vec![FieldSchema {
+ name: "content",
+ ty: TypeSchema::Ref("SourceContent"),
+ comment: "The item's content.",
+ required: true,
+ }],
+ },
+ _ => return None,
+ })
+}
+
+pub(super) fn handle_list(_params: Map<String, Value>) -> ControllerFuture {
+ Box::pin(async move { to_json(rpc::list_rpc().await?) })
+}
+
+pub(super) fn handle_get(params: Map<String, Value>) -> ControllerFuture {
+ Box::pin(async move {
+ let req = parse_value::<rpc::GetRequest>(Value::Object(params))?;
+ to_json(rpc::get_rpc(req).await?)
+ })
+}
+
+pub(super) fn handle_add(params: Map<String, Value>) -> ControllerFuture {
+ Box::pin(async move {
+ let req = parse_value::<rpc::AddRequest>(Value::Object(params))?;
+ to_json(rpc::add_rpc(req).await?)
+ })
+}
+
+pub(super) fn handle_update(params: Map<String, Value>) -> ControllerFuture {
+ Box::pin(async move {
+ let req = parse_value::<rpc::UpdateRequest>(Value::Object(params))?;
+ to_json(rpc::update_rpc(req).await?)
+ })
+}
+
+pub(super) fn handle_remove(params: Map<String, Value>) -> ControllerFuture {
+ Box::pin(async move {
+ let req = parse_value::<rpc::RemoveRequest>(Value::Object(params))?;
+ to_json(rpc::remove_rpc(req).await?)
+ })
+}
+
+pub(super) fn handle_list_items(params: Map<String, Value>) -> ControllerFuture {
+ Box::pin(async move {
+ let req = parse_value::<rpc::ListItemsRequest>(Value::Object(params))?;
+ to_json(rpc::list_items_rpc(req).await?)
+ })
+}
+
+pub(super) fn handle_read_item(params: Map<String, Value>) -> ControllerFuture {
+ Box::pin(async move {
+ let req = parse_value::<rpc::ReadItemRequest>(Value::Object(params))?;
+ to_json(rpc::read_item_rpc(req).await?)
+ })
+}
diff --git a/crates/openhuman-core/src/security/credentials/ops/provider_credentials.rs b/crates/openhuman-core/src/security/credentials/ops/provider_credentials.rs
new file mode 100644
index 0000000000..644a1dc59e
--- /dev/null
+++ b/crates/openhuman-core/src/security/credentials/ops/provider_credentials.rs
@@ -0,0 +1,149 @@
+//! Storing, removing, and listing provider (non-app-session) credentials.
+
+use serde_json::json;
+
+use crate::config::Config;
+use crate::rpc::RpcOutcome;
+use crate::security::credentials::session_support::{
+ parse_fields_value, profile_name_or_default, summarize_auth_profile,
+};
+use crate::security::credentials::{normalize_provider, AuthService, APP_SESSION_PROVIDER};
+
+pub async fn store_provider_credentials(
+ config: &Config,
+ provider: &str,
+ profile: Option<&str>,
+ token: Option<String>,
+ fields: Option<serde_json::Value>,
+ set_active: Option<bool>,
+) -> Result<RpcOutcome<super::super::responses::AuthProfileSummary>, String> {
+ let provider = provider.trim().to_string();
+ if provider.is_empty() {
+ return Err("provider is required".to_string());
+ }
+
+ let profile_name = profile_name_or_default(profile);
+ let mut metadata = parse_fields_value(fields)?;
+ let token = token
+ .as_ref()
+ .map(|v| v.trim().to_string())
+ .filter(|v| !v.is_empty())
+ .or_else(|| metadata.get("token").cloned())
+ .or_else(|| metadata.get("api_key").cloned())
+ .unwrap_or_default();
+ if token.is_empty() && metadata.is_empty() {
+ return Err("provide at least one credential via token or fields".to_string());
+ }
+ metadata.remove("token");
+
+ let auth = AuthService::from_config(config);
+ let stored = auth
+ .store_provider_token(
+ &provider,
+ profile_name,
+ &token,
+ metadata,
+ set_active.unwrap_or(true),
+ )
+ .map_err(|e| e.to_string())?;
+ // A freshly-stored key supersedes any prior auth rejection for this
+ // provider — clear the recorded BYO auth error so the AI-settings notice
+ // disappears and the notification latch re-arms (a future rejection will
+ // notify again). Credentials are keyed `provider:<slug>`; the auth-error
+ // registry is keyed by the bare provider slug used by the chat factory.
+ clear_provider_auth_error(&provider);
+ Ok(RpcOutcome::single_log(
+ summarize_auth_profile(&stored),
+ "provider credentials stored",
+ ))
+}
+
+/// Clear any recorded BYO provider auth error for a credentials `provider`
+/// key. Strips the `provider:` namespace prefix so the lookup matches the
+/// bare slug (`openrouter`) the inference classifier records under.
+fn clear_provider_auth_error(provider: &str) {
+ let slug = provider.strip_prefix("provider:").unwrap_or(provider);
+ crate::inference::auth_error_registry::clear(slug);
+}
+
+pub async fn remove_provider_credentials(
+ config: &Config,
+ provider: &str,
+ profile: Option<&str>,
+) -> Result<RpcOutcome<serde_json::Value>, String> {
+ let profile_name = profile_name_or_default(profile);
+ let auth = AuthService::from_config(config);
+ let removed = auth
+ .remove_profile(provider, profile_name)
+ .map_err(|e| e.to_string())?;
+ // Removing the key clears any recorded BYO auth error for this provider —
+ // there is no longer a key to be "rejected", so the stale notice must go.
+ clear_provider_auth_error(provider);
+ Ok(RpcOutcome::single_log(
+ json!({
+ "removed": removed,
+ "provider": provider,
+ "profile": profile_name,
+ }),
+ "provider credentials removed",
+ ))
+}
+
+pub async fn list_provider_credentials(
+ config: &Config,
+ provider_filter: Option<String>,
+) -> Result<RpcOutcome<Vec<super::super::responses::AuthProfileSummary>>, String> {
+ let auth = AuthService::from_config(config);
+ let provider_filter = provider_filter
+ .map(|provider| normalize_provider(&provider))
+ .transpose()
+ .map_err(|e| e.to_string())?;
+ let profiles = auth.load_profiles().map_err(|e| e.to_string())?;
+ let mut items = profiles
+ .profiles
+ .values()
+ .filter(|profile| profile.provider != APP_SESSION_PROVIDER)
+ .filter(|profile| {
+ provider_filter
+ .as_ref()
+ .is_none_or(|provider| profile.provider == *provider)
+ })
+ .map(summarize_auth_profile)
+ .collect::<Vec<_>>();
+ items.sort_by(|a, b| {
+ a.provider
+ .cmp(&b.provider)
+ .then_with(|| a.profile_name.cmp(&b.profile_name))
+ });
+
+ Ok(RpcOutcome::single_log(items, "provider credentials listed"))
+}
+
+/// List credentials whose provider key starts with `prefix`.
+///
+/// Pure prefix variant of [`list_provider_credentials`] for namespaces
+/// that group multiple providers under a common stem (e.g.
+/// `"channel:"` covers `channel:telegram:managed_dm`,
+/// `channel:slack:bot_token`, …). The exact-match filter on
+/// `list_provider_credentials` cannot express this without enumerating
+/// every concrete provider key up front.
+pub async fn list_provider_credentials_by_prefix(
+ config: &Config,
+ prefix: &str,
+) -> Result<Vec<super::super::responses::AuthProfileSummary>, String> {
+ let auth = AuthService::from_config(config);
+ let profiles = auth.load_profiles().map_err(|e| e.to_string())?;
+ let mut items = profiles
+ .profiles
+ .values()
+ .filter(|profile| profile.provider != APP_SESSION_PROVIDER)
+ .filter(|profile| profile.provider.starts_with(prefix))
+ .map(summarize_auth_profile)
+ .collect::<Vec<_>>();
+ items.sort_by(|a, b| {
+ a.provider
+ .cmp(&b.provider)
+ .then_with(|| a.profile_name.cmp(&b.profile_name))
+ });
+ Ok(items)
+}