Skip to content

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

refactor: split schema catalogs and long impls\n\n

Steven Enamakelf95d4b8a7427
diff --git a/src/openhuman/agent/harness/session/turn/core.rs b/src/openhuman/agent/harness/session/turn/core.rs
index 96d752f481..61491b06df 100644
--- a/src/openhuman/agent/harness/session/turn/core.rs
+++ b/src/openhuman/agent/harness/session/turn/core.rs
@@ -157,1438 +157,5 @@ fn render_agent_context_status_note(sources: &[harness::AgentContextPreparedSour
)
}
-impl Agent {
- /// Executes a single interaction "turn" with the agent.
- ///
- /// This function is the primary driver of the agent's behavior. It manages the
- /// end-to-end lifecycle of a user request:
- ///
- /// 1. **Initialization**: Resumes from a session transcript if this is a new turn
- /// to preserve KV-cache stability.
- /// 2. **Prompt Construction**: Builds the system prompt (only on the first turn)
- /// incorporating learned context and tool instructions.
- /// 3. **Context Injection**: Enriches the user message with per-turn context
- /// such as situational preferences, the thread goal, and active sub-agents.
- /// Broad memory recall is available to the model on demand instead.
- /// 4. **Execution Loop**: Enters a loop (up to `max_tool_iterations`) where it:
- /// - Manages the context window (reduction/summarization).
- /// - Calls the LLM provider.
- /// - Parses and executes tool calls.
- /// - Accumulates results into history.
- /// 5. **Synthesis**: Returns the final assistant response after all tools have
- /// finished or the iteration budget is exhausted.
- /// 6. **Background Tasks**: Triggers episodic memory indexing and facts
- /// extraction asynchronously.
- pub async fn turn(&mut self, user_message: &str) -> Result<String> {
- // Consume any per-turn overrides the caller set for THIS turn (#1725).
- // Taking them resets the field to the default, so they apply to exactly
- // one turn — a chat/small-talk turn runs tool-less, memory-less and
- // goal-less without permanently altering the agent, and the following
- // turn is back to full-agentic behaviour. Callers that never opt in get
- // `TurnOverrides::default()` (all-false) and the unchanged path.
- let turn_overrides = std::mem::take(&mut self.pending_turn_overrides);
- if turn_overrides != super::super::types::TurnOverrides::default() {
- log::info!(
- "[agent_loop] per-turn overrides active: suppress_active_goal={} suppress_tools={} suppress_memory_agent={}",
- turn_overrides.suppress_active_goal,
- turn_overrides.suppress_tools,
- turn_overrides.suppress_memory_agent
- );
- }
- self.emit_progress(AgentProgress::TurnStarted).await;
- log::info!("[agent] turn started — awaiting user message processing");
- log::info!(
- "[agent_loop] turn start message_chars={} history_len={} max_tool_iterations={}",
- user_message.chars().count(),
- self.history.len(),
- self.config.max_tool_iterations
- );
- self.ensure_composio_integrations_listener();
- // Arm the installed-skills listener at turn start (not lazily inside
- // `drain_skill_events`, which is only reached after the first turn) —
- // broadcast subscriptions are not retroactive, so a skill installed
- // during turn 1 would otherwise be missed until a later subscribe.
- self.ensure_skill_events_listener();
- // ── Session transcript resume ─────────────────────────────────
- // On a fresh session (empty history), look for a previous
- // transcript to pre-populate the exact provider messages for
- // KV cache prefix reuse.
- if self.history.is_empty()
- && self.cached_transcript_messages.is_none()
- && !turn_overrides.suppress_transcript_autoload
- {
- self.try_load_session_transcript();
- }
-
- if self.history.is_empty() {
- // Learned context is only baked into the system prompt on the
- // very first turn — once the history is non-empty we reuse the
- // stored prompt verbatim to preserve the KV-cache prefix the
- // inference backend has already tokenised. Fetching it later
- // would just burn memory-store reads on data we throw away.
- if !self.connected_integrations_initialized {
- self.fetch_connected_integrations().await;
- // Sessions born without a cached Composio view still need
- // a one-shot delegation-surface reconcile before the system
- // prompt is frozen. The shared-Arc failure path returns
- // `false`, but on turn 1 the Arc should still be uniquely
- // owned; a `false` return here indicates a programmer error
- // and the warn-level log inside the helper already surfaces
- // it, so we keep the existing best-effort contract.
- let _ = self.refresh_delegation_tools();
- }
- let learned = self.fetch_learned_context().await;
- let rendered_prompt = self.build_system_prompt(learned)?;
- log::info!("[agent] system prompt built — initialising conversation history");
- log::info!(
- "[agent_loop] system prompt built chars={}",
- rendered_prompt.chars().count()
- );
- // User-file injection (PROFILE.md, MEMORY.md) puts
- // potentially-sensitive content (LinkedIn scrape output,
- // archivist-curated memories) into the system prompt. Avoid
- // leaking that to debug logs — log a length + content hash
- // instead. Narrow specialists (both flags off) keep the
- // full-body log so prompt-engineering iteration on
- // tools/safety sections stays easy.
- //
- // AGENTS.md instruction layers are also user/project-controlled and
- // can land in the prompt even when PROFILE/MEMORY are both omitted
- // (common for narrow specialists), so treat their presence as a
- // redaction trigger too — otherwise the full-body path would print
- // raw AGENTS.md contents verbatim.
- let contains_agents_md =
- rendered_prompt.contains("## Project instructions (AGENTS.md)");
- if self.omit_profile && self.omit_memory_md && !contains_agents_md {
- log::debug!("[agent_loop] system prompt body:\n{}", rendered_prompt);
- } else {
- let mut hasher = std::collections::hash_map::DefaultHasher::new();
- rendered_prompt.hash(&mut hasher);
- log::debug!(
- "[agent_loop] system prompt body redacted (contains PROFILE/MEMORY/AGENTS.md): chars={} hash={:016x}",
- rendered_prompt.chars().count(),
- hasher.finish()
- );
- }
- self.history
- .push(ConversationMessage::Chat(ChatMessage::system(
- rendered_prompt,
- )));
- // Seed the per-turn mid-session refresh baseline with the
- // hash of whatever Composio actually returned just now.
- // Subsequent turns short-circuit unless this hash changes.
- self.last_seen_integrations_hash =
- crate::openhuman::integrations::composio::connected_set_hash(
- &self.connected_integrations,
- );
- // Seed the announced set with the startup connected toolkits so
- // only genuinely-new mid-session connects get announced later.
- self.announced_integrations = self
- .connected_integrations
- .iter()
- .map(|i| i.toolkit.clone())
- .collect();
- // MCP analogue: seed the announced MCP set with the servers already
- // connected at startup. Those are already in the (turn-1) system
- // prompt's `## Connected MCP Servers` block, so only servers that
- // connect *mid-session* should later be announced on the user turn.
- self.announced_mcp_servers =
- crate::openhuman::mcp::registry::connections::connected_overview()
- .await
- .into_iter()
- .map(|s| s.qualified_name)
- .collect();
- } else {
- // Deliberately do NOT rebuild the system prompt on subsequent
- // turns. The rendered prompt is the KV-cache prefix the inference
- // backend has already tokenised; replacing its bytes (even
- // cosmetically) forces the backend to re-prefill from scratch.
- //
- // Dynamic turn-to-turn context rides on the user message assembled
- // below (`context`) — that is where anything varying between turns
- // belongs. Broad memory recall is not injected; the model calls the
- // memory tools when it needs stored context.
- //
- // *** Mid-session schema-only refresh ***
- //
- // The system prompt stays frozen, but the function-calling
- // schema (the `tools` field in the provider request) is sent
- // fresh on every API call — it's not part of the KV-cache
- // prefix. So we *can* react to Composio connect/disconnect
- // events mid-session by re-synthesising the `delegate_<toolkit>`
- // surface on `self.tools` / `self.tool_specs` and letting
- // the next provider call carry the new schema. KV cache stays
- // intact; the system prompt's `## Connected Integrations`
- // block goes mildly stale until the next session, but the
- // schema is the source of truth the model actually routes
- // against.
- //
- // The signal we react to is the process-wide
- // [`crate::openhuman::integrations::composio::INTEGRATIONS_CACHE`], kept
- // current by (a) the desktop UI's 5 s
- // `composio_list_connections` poll, (b) the post-OAuth
- // `ComposioConnectionCreatedSubscriber` invalidation, and
- // (c) the 60 s TTL fallback. We read it via the read-only
- // [`crate::openhuman::integrations::composio::cached_active_integrations`]
- // helper — never trigger a backend fetch ourselves, never
- // block on a writer.
- // Session agents built through `from_config_*` carry their
- // runtime `Config` snapshot directly, so this read avoids the
- // old `Config::load_or_init()` round-trip on every turn.
- //
- let _ = self.refresh_delegation_tools_from_cached_integrations("turn-boundary");
- // Same idea for installed skills. The system-prompt
- // `## Installed Skills` block is frozen at turn 1 for KV-cache
- // stability (history is non-empty here, so it is never rebuilt
- // mid-session), so — exactly like the MCP mechanism — the
- // user-turn announcement below is what surfaces a mid-session
- // install to the model. `refresh_workflows` updates the tracked
- // set (so the next refresh diffs correctly and a future fresh
- // session renders the new catalogue) and parks the announcement.
- // Event-driven (mirror of the composio path): only re-scan disk
- // when a `WorkflowsChanged` event was published since the last
- // turn — no per-turn filesystem walk on the steady-state hot path.
- if self.drain_skill_events() {
- let _ = self.refresh_workflows("event");
- }
- // Cache empty/expired or config unavailable => no signal.
- // We leave the current tool surface alone and pick up any
- // real change on the next turn after the UI's 5 s poll has
- // repopulated [`INTEGRATIONS_CACHE`].
-
- // MCP mid-session connect surfacing — the analogue of the Composio
- // path above. `use_mcp_server` is a single static delegate (no
- // per-server schema to refresh), so the whole mechanism is: diff
- // the live in-process connection map against what we've already
- // announced and queue a one-shot note for any newly-connected
- // server onto the next user message. The map is in-process (no
- // network, unlike Composio's cache), so reading it every turn is
- // cheap. Like the Composio block, the frozen `## Connected MCP
- // Servers` system-prompt section stays as the turn-1 snapshot.
- let connected_mcp: Vec<String> =
- crate::openhuman::mcp::registry::connections::connected_overview()
- .await
- .into_iter()
- .map(|s| s.qualified_name)
- .collect();
- for qn in newly_connected_slugs(&connected_mcp, &mut self.announced_mcp_servers) {
- if !self.pending_mcp_announcement.contains(&qn) {
- self.pending_mcp_announcement.push(qn);
- }
- }
-
- log::trace!(
- "[agent_loop] system prompt reused (history_len={}) — KV cache prefix preserved",
- self.history.len()
- );
- }
-
- if self.auto_save {
- // Fire-and-forget: persisting the user message to the memory store
- // does an embedding round-trip (Voyage) + memory-tree write that the
- // in-flight turn never reads back. Awaiting it delayed the start of
- // *every* turn before recall/LLM began, so spawn it and let the chat
- // continue immediately.
- //
- // Use a UNIQUE per-message key: the old fixed `"user_msg"` key
- // upserts a single document (`upsert_document` keys by namespace+key),
- // so concurrent turns would race on — and overwrite — one shared slot.
- // A unique key makes each user message its own conversation document,
- // which both removes the race and stops the autosave from only ever
- // retaining the latest message.
- let memory = self.memory.clone();
- let user_msg = user_message.to_string();
- let autosave_key = format!("user_msg:{}", uuid::Uuid::new_v4());
- let chars = user_msg.chars().count();
- // Captured *before* `tokio::spawn` — the ambient thread id is a
- // `tokio::task_local` (see `tinyagents::thread_context`)
- // and does not propagate into a spawned task, so it must be read
- // on this (still-scoped) task and moved in explicitly. Tagging
- // this document with the live chat thread id is what lets the
- // same-session exclusion filter (`UnifiedMemory::recall` /
- // `memory_hybrid_search`) recognize and drop it later this same
- // turn, so the agent's own on-demand memory search doesn't echo
- // its own triggering request back as a "relevant" result.
- let session_id_for_autosave =
- crate::openhuman::agent::tinyagents::thread_context::current_thread_id();
- log::debug!(
- "[agent_autosave] enqueue user-message store key={autosave_key} chars={chars} \
- session_id={}",
- session_id_for_autosave.as_deref().unwrap_or("<none>")
- );
- tokio::spawn(async move {
- match memory
- .store(
- crate::openhuman::agent::learning::transcript_ingest::CONVERSATION_RAW_NAMESPACE,
- &autosave_key,
- &user_msg,
- MemoryCategory::Conversation,
- session_id_for_autosave.as_deref(),
- )
- .await
- {
- Ok(()) => log::debug!(
- "[agent_autosave] stored user-message key={autosave_key} chars={chars}"
- ),
- Err(err) => log::warn!(
- "[agent_autosave] user-message memory autosave failed key={autosave_key} err={err}"
- ),
- }
- });
- }
-
- log::info!("[agent] spawning UI-only citation collection for user message");
- const MEMORY_CITATION_LIMIT: usize = 5;
- const MEMORY_CITATION_MIN_RELEVANCE: f64 = 0.4;
- // Spawned, not awaited: see `Agent::pending_citations`. The result is
- // UI-only, so the turn must not wait for it before calling the model.
- self.last_turn_citations.clear();
- if let Some(previous) = self.pending_citations.take() {
- // A turn that never had its citations collected leaves a task
- // behind; abort it rather than letting a stale recall outlive the
- // turn it belonged to.
- previous.abort();
- }
- let citation_memory = self.memory.clone();
- let citation_query = user_message.to_string();
- self.pending_citations = Some(tokio::spawn(async move {
- match collect_recall_citations(
- citation_memory.as_ref(),
- &citation_query,
- MEMORY_CITATION_LIMIT,
- MEMORY_CITATION_MIN_RELEVANCE,
- )
- .await
- {
- Ok(citations) => {
- log::debug!(
- "[agent_loop] memory citations collected count={}",
- citations.len()
- );
- citations
- }
- Err(_err) => {
- // Recall errors may include the user-authored query. Keep
- // warning logs free of raw external content.
- log::warn!("[agent_loop] memory citation collection failed");
- Vec::new()
- }
- }
- }));
- // No per-turn memory-context block is assembled here any more.
- //
- // `memory_loader.load_context()` used to prepend `[User working
- // memory]`, `[Prior conversations]` and `[Cross-chat context]` to every
- // user message. It cost two full scans of the `global` namespace per
- // turn — every document and every vector chunk, decoded and scored — to
- // contribute at most nine lines, and the cost grew with everything the
- // user had ever said. Benchmarked at ~10k memories it was the dominant
- // per-turn cost by a wide margin, and the `[User working memory]` arm
- // in particular scanned the whole namespace only to filter the results
- // down to a `working.user.` key prefix, so it returned nothing at all
- // once ordinary chat crowded the ranking.
- //
- // Memory is still available to the agent — `memory_recall` and the rest
- // of the memory tools are unchanged, so the model fetches what it needs
- // when it needs it, rather than every turn paying for a broad guess.
- let mut context = String::new();
-
- // ── Lane B: situational preferences (every turn) ─────────────────────
- // Recall topic-scoped preferences semantically relevant to THIS message
- // (model-aware embeddings, gated by vector similarity) and inject them
- // under a banner. Runs every turn — unlike the first-turn-gated tree/STM
- // blocks above — because the query changes per message; it rides the
- // per-turn context that's prepended to the user message (no KV-cache
- // cost). An unrelated message clears the similarity gate to nothing, so
- // no block is injected.
- {
- let situational =
- crate::openhuman::memory::preferences::recall_situational_preferences_on(
- &self.memory,
- user_message,
- )
- .await;
- if !situational.is_empty() {
- log::info!(
- "[pref_recall] situational block injected: {} item(s)",
- situational.len()
- );
- context.push_str("## Relevant preferences for this message\n\n");
- for pref in &situational {
- context.push_str("- ");
- context.push_str(pref.trim());
- context.push('\n');
- }
- context.push('\n');
- } else {
- log::debug!("[pref_recall] no situational preference relevant to this message");
- }
- }
-
- // ── Thread goal (Codex-style per-thread completion contract) ─────────
- // Load this thread's durable goal once per turn and prepend a compact
- // [active_goal] block so the objective + live status/budget steer the
- // turn. Rides the per-turn context (NOT the cached system-prompt prefix)
- // so edits take effect immediately. `active_goal` is reused below to arm
- // the budget stop hook around the engine call.
- // Capture the workspace path for the budget stop hook built after the
- // `turn_body` coroutine (which borrows `&mut self`) is constructed.
- let goal_workspace_dir = self.workspace_dir.clone();
- let active_goal = if turn_overrides.suppress_active_goal {
- // Chat / small-talk turn: do NOT load, auto-resume, inject, or
- // budget-arm this thread's goal. A goal an earlier task left
- // uncompleted must not steer an unrelated greeting (#1725, the
- // "stale goal replays every turn" half of the context leak).
- log::debug!(
- "[thread_goals] active_goal suppressed for this turn (chat/small-talk override)"
- );
- None
- } else {
- let loaded = crate::openhuman::threads::goals::runtime::load_for_current_thread(
- &self.workspace_dir,
- )
- .await;
- // Thread-resume semantics: the user re-engaging a thread reactivates a
- // paused goal (Codex's ThreadResumed). Best-effort; on failure keep
- // the loaded (paused) goal so we still surface it.
- match loaded {
- Some(goal)
- if matches!(
- goal.status,
- crate::openhuman::threads::goals::ThreadGoalStatus::Paused
- ) =>
- {
- crate::openhuman::threads::goals::runtime::resume_for_current_thread(
- &self.workspace_dir,
- )
- .await
- .unwrap_or(Some(goal))
- }
- other => other,
- }
- };
- if let Some(ref goal) = active_goal {
- if let Some(block) = tinyagents::graph::goals::active_goal_context_block(goal) {
- log::info!(
- "[thread_goals] injecting active_goal block status={} budget={:?} ({} chars)",
- goal.status.as_str(),
- goal.token_budget,
- block.chars().count()
- );
- context.push_str(&block);
- }
- }
-
- // ── Active sub-agents (ambient fleet awareness) ──────────────────────
- // When this agent has async/parallel workers registered under its own
- // session, prepend a compact `[active_subagents]` roster (agent type,
- // subagent_session_id, live status) so it tracks the fleet from the turn
- // context instead of relying on remembered `[async_subagent_ref]` blocks
- // that may have scrolled away. Children register under the parent's
- // `session_id`, which is this agent's `event_session_id` (see
- // `build_parent_execution_context`). Gated on presence: agents that never
- // spawn get an empty block and no injection. Rides per-turn context (like
- // the goal block) so status is always live.
- if let Some(block) =
- crate::openhuman::agent::orchestration::running_subagents::active_subagents_context_block(
- &self.event_session_id,
- &self.workspace_dir,
- )
- {
- log::info!(
- "[running_subagents] injecting active_subagents block session={} ({} chars)",
- self.event_session_id,
- block.chars().count()
- );
- context.push_str(&block);
- }
-
- let enriched = if context.is_empty() {
- log::info!("[agent] no memory context found — using raw user message");
- self.last_memory_context = None;
- user_message.to_string()
- } else {
- log::info!(
- "[agent] memory context loaded — enriching user message context_chars={}",
- context.chars().count()
- );
- self.last_memory_context = Some(context.clone());
- format!("{context}{user_message}")
- };
-
- let enriched = self
- .inject_agent_experience_context(user_message, enriched)
- .await;
-
- // ── SKILL.md body injection: REMOVED (was #781) ──────────────
- // We used to keyword-match installed skills against the user message
- // and prepend their full SKILL.md bodies onto the user turn. That
- // brittle name/description/tag match fired unintentionally and — by
- // baking the body into the stored user message — left full skill text
- // permanently in chat history (microcompact only clears tool results,
- // not user messages).
- //
- // Skills are now surfaced via the compact `## Installed Skills`
- // catalog in the orchestrator prompt and executed via `run_skill`,
- // which loads and follows the SKILL.md inside an isolated worker, so
- // the full body never enters this conversation. `self.workflows` still
- // feeds the catalog through `PromptContext`.
-
- // Consume any one-shot mid-session connect announcement parked by
- // `refresh_delegation_tools_from_cached_integrations`. It rides on the
- // user turn (NOT a system message — `trim_history` hoists system
- // messages to the front and would bust the KV-cache prefix) and
- // `.take()` clears it so it fires exactly once.
- let pending_slugs = std::mem::take(&mut self.pending_integration_announcement);
- let enriched = match integration_announcement_note(&pending_slugs) {
- Some(note) => format!("{note}\n\n{enriched}"),
- None => enriched,
- };
-
- // Same one-shot treatment for MCP servers connected mid-session
- // (queued above). `.take()` clears it so it fires exactly once.
- let pending_mcp = std::mem::take(&mut self.pending_mcp_announcement);
- let enriched = match mcp_announcement_note(&pending_mcp) {
- Some(note) => format!("{note}\n\n{enriched}"),
- None => enriched,
- };
-
- // Same one-shot pattern for skills installed mid-session (parked by
- // `refresh_workflows` above). Rides the user turn so the KV-cache
- // prefix stays stable; `.take()` fires it exactly once.
- let pending_skills = std::mem::take(&mut self.pending_skill_announcement);
- let enriched = match skill_announcement_note(&pending_skills) {
- Some(note) => format!("{note}\n\n{enriched}"),
- None => enriched,
- };
-
- // Same one-shot treatment for skills uninstalled mid-session (parked by
- // `refresh_workflows`). The model must know the skill is gone so it does
- // not attempt `run_skill` on a removed entry. Rides the user turn for
- // the same KV-cache reason as the install note above.
- let pending_retracted = std::mem::take(&mut self.pending_skill_retraction);
- let enriched = match skill_retraction_note(&pending_retracted) {
- Some(note) => format!("{note}\n\n{enriched}"),
- None => enriched,
- };
-
- // Pin the main agent to its configured model for the lifetime of
- // the session. Per-turn classification used to run here, but it
- // would flip `effective_model` mid-conversation (e.g. reasoning →
- // coding based on a single keyword). Every flip invalidates the
- // backend's KV cache namespace for this session, costing full
- // re-prefill on the very next turn. The main agent's job is to
- // decide *which sub-agent* to spawn — that routing lives in the
- // model prompt, not in the Rust-side classifier. Sub-agents pick
- // their own tier via `ModelSpec::Hint(...)` in their definition.
- let effective_model = self.model_name.clone();
- log::info!(
- "[agent_loop] model pinned model={} (per-turn classification disabled for KV cache stability)",
- effective_model
- );
-
- // Snapshot the parent's runtime once per turn so any
- // `spawn_subagent` invocation that fires inside this turn can
- // read it via the PARENT_CONTEXT task-local. We override the
- // model field with the post-classification effective model.
- let mut parent_context = self.build_parent_execution_context();
- parent_context.model_name = effective_model.clone();
- let session_memory_parent_context = parent_context.clone();
-
- let mut agent_context_prepared_sources: Vec<harness::AgentContextPreparedSource> =
- Vec::new();
- // Triggered memory-agent recall runs on EVERY channel, voice included:
- // dropping it on voice would strip the user's remembered context
- // (preferences, people, prior facts) from spoken answers — a real quality
- // loss the transcript alone can't replace. Recall adds a few seconds of
- // embedding + retrieval before the first model token, but on realtime
- // voice that latency is already covered end-to-end: the backend relay
- // streams an audible keepalive filler from t=0 so the cloud session never
- // sees a silent stall, and the desktop's ~8s ack-defer closes the spoken
- // turn and finishes in the background if the work runs long. So the recall
- // path is byte-for-byte identical across voice and chat.
- let (enriched, memory_agent_context_injected) = self
- .inject_triggered_memory_agent_context(
- user_message,
- enriched,
- &parent_context,
- turn_overrides.suppress_memory_agent,
- )
- .await;
- if memory_agent_context_injected {
- agent_context_prepared_sources.push(harness::AgentContextPreparedSource {
- source: "memory agent context retrieval".to_string(),
- has_enough_context: None,
- });
- }
-
- let enriched = if agent_context_prepared_sources.is_empty() {
- enriched
- } else {
- log::debug!(
- "[agent_loop] agent context already prepared sources={:?}",
- agent_context_prepared_sources
- );
- format!(
- "{}\n\n{enriched}",
- render_agent_context_status_note(&agent_context_prepared_sources)
- )
- };
-
- // #3602: stamp every turn's user message with the live local time
- // so time-relative phrasing (greetings, "today"/"tonight") is
- // grounded on the real clock. Rides the user message — not the
- // frozen system-prompt prefix (see core.rs KV-cache note above) — so
- // it stays fresh across a long-lived session without busting the
- // cached prefix. This path runs for every `turn()` caller, including
- // one-shot `run_single` flows (cron/morning-briefing/meet), so those
- // get a fresh stamp too. The grounding *rule* lives in the system
- // prompt's `## Current Date & Time` section.
- let enriched = format!(
- "{}\n\n{enriched}",
- crate::openhuman::agent::prompts::current_datetime_line()
- );
-
- self.history
- .push(ConversationMessage::Chat(ChatMessage::user(enriched)));
-
- // Bump the session-memory turn counter. Used later by
- // `should_extract_session_memory` to decide whether to spawn a
- // background archivist fork at end-of-turn.
- self.context.tick_turn();
-
- let turn_body = async {
- // Keep the scalar turn settings outside the pinned future arguments;
- // the TinyAgents session path reads provider/tool/multimodal state
- // directly from `self` when preparing the request.
- let temperature = self.temperature;
- let max_iterations = self.config.max_tool_iterations;
- let artifact_store = Some(
- crate::openhuman::agent::harness::tool_result_artifacts::ToolResultArtifactStore::new(
- self.action_dir.clone(),
- self.session_key.clone(),
- ),
- );
- // The whole turn runs through the tinyagents harness (issue #4249);
- // the legacy `run_turn_engine` has been removed. Heap-allocate the
- // (large) session-turn future so it isn't held inline on `turn()`'s
- // already-large frame — `run_single` and the cron wrappers nest more
- // layers on top, which would otherwise overflow the stack.
- Box::pin(self.run_turn_via_tinyagents_session(
- user_message,
- &effective_model,
- temperature,
- max_iterations,
- artifact_store,
- turn_overrides.suppress_tools,
- ))
- .await
- }; // end of `turn_body` async block
-
- // Run the turn body inside the parent-execution-context scope so
- // that any `spawn_subagent` tool call fired during the loop can
- // read the parent's provider, tools, model, and workspace via
- // the PARENT_CONTEXT task-local.
- // Arm the thread-goal budget stop hook for this turn when an active,
- // budgeted goal exists — it votes to stop the loop as soon as running
- // usage would exceed the cap. #4469 item 1: the stop is a graceful pause
- // drained at the next iteration boundary, not an instantaneous abort, so
- // the current tool round + one wrap-up summary call can still run past the
- // cap (a small, bounded overshoot) before the partial transcript returns.
- // Merge with any ambient stop hooks rather than clobbering them. No
- // budgeted active goal → no extra hook, no wrap.
- let mut turn_stop_hooks = crate::openhuman::agent::stop_hooks::current_stop_hooks();
- if let Some(ref goal) = active_goal {
- if let Some(hook) =
- crate::openhuman::threads::goals::runtime::GoalBudgetStopHook::for_goal(
- &goal_workspace_dir,
- goal,
- )
- {
- turn_stop_hooks.push(std::sync::Arc::new(hook));
- }
- }
- // Surface this turn's image-attachment placeholders so a delegation to a
- // vision sub-agent (which reads `current_turn_image_placeholders()` in
- // `agent_orchestration::tools::dispatch`) can forward the user's attached
- // image — the orchestrator itself keeps it as a text placeholder. Scoped
- // around the harness turn (the delegating tool fires inside it).
- let image_placeholders =
- crate::openhuman::agent::multimodal::extract_image_placeholders_in_text(user_message);
- let result = if turn_stop_hooks.is_empty() {
- harness::with_parent_context(
- parent_context,
- harness::with_agent_context_prepared_sources(
- agent_context_prepared_sources.clone(),
- harness::turn_attachments_context::with_current_turn_image_placeholders(
- image_placeholders,
- turn_body,
- ),
- ),
- )
- .await
- } else {
- harness::with_parent_context(
- parent_context,
- harness::with_agent_context_prepared_sources(
- agent_context_prepared_sources.clone(),
- harness::turn_attachments_context::with_current_turn_image_placeholders(
- image_placeholders,
- crate::openhuman::agent::stop_hooks::with_stop_hooks(
- turn_stop_hooks,
- turn_body,
- ),
- ),
- ),
- )
- .await
- };
-
- // Session transcript persistence lives INSIDE the turn body —
- // one write per provider response, fired right after the
- // response lands (see the tool-call and terminal branches in
- // `turn_body`). A crash during tool execution no longer drops
- // the assistant's reply because it was already flushed to
- // disk before tool dispatch started. No outer-loop save is
- // needed here.
-
- // ── Session-memory extraction (stage 5) ───────────────────────
- //
- // If the pipeline's deltas have crossed all three thresholds
- // (token growth, tool calls, turn count), spawn a *background*
- // archivist sub-agent that will distil durable facts into the
- // workspace MEMORY.md file via the `update_memory_md` tool.
- //
- // The spawn is fire-and-forget: the main turn returns the
- // user-visible response immediately, and the archivist runs
- // asynchronously on the `agentic` tier. We optimistically mark
- // the extraction complete right away — if it actually fails,
- // we'll just retry on the next threshold window (a few turns
- // later), which is the right amount of retry behaviour for a
- // librarian task that's idempotent across reruns.
- if result.is_ok() && self.context.should_extract_session_memory() {
- self.spawn_session_memory_extraction(session_memory_parent_context)
- .await;
- // Sibling pipeline (#1399): heuristic transcript ingestion
- // turns the just-written transcript into durable
- // conversational memory + reflections so a brand-new chat
- // can recover continuity. Background-only, never blocks the
- // user-facing turn return.
- self.spawn_transcript_ingestion();
- }
-
- result
- }
-
- /// Drive a full chat turn through the `tinyagents` harness (issue #4249).
- ///
- /// The frozen system+prior history is converted to provider messages, the
- /// user turn appended, and the loop run over the agent's resolved tools. The
- /// final reply + the user turn are recorded into `history`, the transcript
- /// is persisted, and `TurnCompleted` is emitted so the UI stops spinning.
- ///
- /// Full-fidelity with the legacy `run_turn_engine`: live tool-timeline /
- /// text-delta progress and the cost/token footer are mirrored from the
- /// harness event stream via `OpenhumanEventBridge` (tinyagents harness),
- /// `[IMAGE:…]`/`[FILE:…]` markers are expanded for the provider, and history
- /// is trimmed to the provider's context window.
- async fn run_turn_via_tinyagents_session(
- &mut self,
- user_message: &str,
- effective_model: &str,
- temperature: f64,
- max_iterations: usize,
- artifact_store: Option<
- crate::openhuman::agent::harness::tool_result_artifacts::ToolResultArtifactStore,
- >,
- suppress_tools: bool,
- ) -> Result<String> {
- let turn_started = std::time::Instant::now();
- // This turn's stamped user message is already the last entry in
- // `self.history` (pushed by `turn()` before the engine branch), so build
- // the provider messages straight from history — do NOT push the user
- // again. When a cached transcript prefix is present (a resumed session's
- // KV-cache warm-up), prepend it and clear it so the first request reuses
- // the cached prefix exactly once.
- let mut messages = self.tool_dispatcher.to_provider_messages(&self.history);
- if let Some(cached) = self.cached_transcript_messages.take() {
- // The cached prefix already carries the system prompt + prior
- // conversation, so drop the freshly-rendered leading system
- // message(s) and append only this turn's new (user) messages.
- let tail = messages
- .into_iter()
- .skip_while(|m| m.role == "system")
- .collect::<Vec<_>>();
- let mut combined = cached;
- combined.extend(tail);
- messages = combined;
- }
-
- // Multimodal prep (parity with the legacy engine): rehydrate image
- // placeholders for vision-capable providers, then expand `[IMAGE:…]` /
- // `[FILE:…]` markers into provider-ready content before dispatch. The
- // expanded copy is provider-only and never persisted to `history`.
- let multimodal = self
- .runtime_config
- .as_ref()
- .map(|c| c.multimodal.clone())
- .unwrap_or_default();
- let multimodal_files = self
- .runtime_config
- .as_ref()
- .map(|c| c.multimodal_files.clone())
- .unwrap_or_default();
- // Resolve the effective context window and build the turn's tiered crate
- // `ChatModel` set from the session source up front (issue #4249, Phase 3 /
- // Motion A) — the harness holds crate model types, and the vision read
- // below comes off the built models, not a raw provider.
- let context_window = self
- .turn_model_source
- .effective_context_window(effective_model)
- .await;
- let turn_models =
- self.turn_model_source
- .build(effective_model, temperature, context_window)?;
-
- // Honor custom/BYOK vision models too: they can set `model_vision` even
- // when the provider capability bit is false, and must still rehydrate
- // `[IMAGE:…]` placeholders (else image chat silently degrades to text).
- if (turn_models.supports_vision() || self.model_vision)
- && crate::openhuman::agent::multimodal::has_image_placeholders(&messages)
- {
- messages = crate::openhuman::agent::multimodal::rehydrate_image_placeholders(&messages);
- }
- let messages = crate::openhuman::agent::multimodal::prepare_messages_for_provider(
- &messages,
- &multimodal,
- &multimodal_files,
- )
- .await
- .map(|prepared| prepared.messages)
- .unwrap_or(messages);
-
- // Per-turn tool scope (#1725). A chat / small-talk turn runs with an
- // EMPTY tool set: the provider request carries no tool schema, so the
- // model cannot enter the tool loop and answers in a single call. The
- // agent's durable `self.tools` / `self.visible_tool_names` are left
- // untouched — the next un-overridden turn gets the full toolbelt back.
- let (turn_tools, turn_visible_tool_names) = if suppress_tools {
- (
- std::sync::Arc::new(Vec::new()),
- std::collections::HashSet::new(),
- )
- } else {
- (self.tools.clone(), self.visible_tool_names.clone())
- };
-
- tracing::info!(
- model = %effective_model,
- max_iterations,
- tools = turn_tools.len(),
- suppress_tools,
- "[agent_loop] routing chat turn through the tinyagents harness"
- );
-
- // Dispatch through the chat turn graph (this folder's `graph.rs`): a thin
- // wrapper over the shared tinyagents seam that pins the chat path's fixed
- // arguments (no child scope, no early-exit tools, graceful cap pause,
- // per-turn output cap) and runs the context-window summarization step.
- // Context middlewares sourced from this session's ContextManager: the
- // per-tool-result byte cap + payload summarizer (after_tool) and
- // microcompact tool-body clearing (before_model). KV-cache-prefix drift
- // detection is owned by the crate `PromptCacheGuardMiddleware` (fed by
- // `PromptCacheSegmentMiddleware`); the warn-only `CacheAlignMiddleware`
- // was deleted in C3.
- let context_mw = crate::openhuman::agent::tinyagents::TurnContextMiddleware {
- tool_result_budget_bytes: self.context.tool_result_budget_bytes(),
- payload_summarizer: self.payload_summarizer.clone(),
- artifact_store,
- tokenjuice_compaction_enabled: self.context.compaction_enabled(),
- tokenjuice_compression: self.tokenjuice_compression,
- microcompact_keep_recent: self.context.microcompact_keep_recent(),
- // Honor the [context].enabled / autocompact_enabled opt-outs: when off,
- // the summarization middleware is not installed (no summarizer tokens,
- // no history rewrite).
- autocompact_enabled: self.context.autocompact_enabled(),
- // Progressive-disclosure handoff is a sub-agent (integrations_agent)
- // concern; the top-level chat turn never sets it.
- handoff: None,
- // Live transcript snapshotting is a sub-agent error-recovery concern
- // (#4466); the chat path persists its transcript post-run.
- transcript_snapshot: None,
- };
-
- // Gather any sub-agent spend delegated during this turn (synchronous
- // `spawn_subagent` runs inline on this task and records into the collector)
- // so the turn's usage meters + the `chat_done` per-child breakdown include
- // it — the collector scope the legacy engine installed.
- // Install the turn's sub-agent dispatch guard around the same future
- // (#5804). It records two facts the turn already produces but never
- // wrote down — that a graceful pause has been requested at the
- // model-call cap, and how long this turn's sub-agents actually take —
- // so `run_subagent` can refuse a dispatch that cannot finish inside the
- // remaining wall-clock budget instead of taking the whole turn down
- // with it. Boxed at the call site: `with_dispatch_guard` takes its
- // future by value, and the collector future wraps the entire turn
- // generator, so passing it unboxed would move hundreds of KiB through
- // this frame — the same hazard `with_turn_collector`'s own comment
- // documents, with the gdb measurements behind it.
- let turn_future = Box::pin(
- crate::openhuman::agent::harness::turn_subagent_usage::with_turn_collector(
- super::graph::run_chat_turn_graph(super::graph::ChatTurnGraph {
- turn_models,
- model: effective_model.to_string(),
- messages,
- tools: turn_tools,
- visible_tool_names: turn_visible_tool_names,
- max_iterations,
- on_progress: self.on_progress.clone(),
- context_window,
- run_queue: self.run_queue.clone(),
- context_mw,
- // Enforce the builder-configured tool policy at the tool
- // boundary (the tinyagents path otherwise bypasses it).
- tool_policy: Some(crate::openhuman::agent::tinyagents::ToolPolicyEnforcement {
- policy: self.tool_policy.clone(),
- session: self.tool_policy_session.clone(),
- session_id: self.event_session_id.clone(),
- channel: self.event_channel().to_string(),
- agent_definition_id: self.agent_definition_id.clone(),
- }),
- // Section D: forward the session's per-profile workspace
- // descriptor (if any) so the top-level chat turn's acting
- // tools default their cwd to the profile's dedicated dir.
- workspace_descriptor: self.workspace_descriptor.clone(),
- // Scope direct Master-Agent calls under its declared
- // sandbox. `agent_definition_name` can carry a thread
- // suffix, so resolve with the stable definition id.
- sandbox_mode: crate::openhuman::agent::harness::definition::AgentDefinitionRegistry::global()
- .and_then(|registry| registry.get(&self.agent_definition_id))
- .map(|definition| definition.sandbox_mode)
- .unwrap_or(crate::openhuman::agent::harness::definition::SandboxMode::None),
- }),
- ),
- );
- let (outcome, subagent_usage_entries) =
- crate::openhuman::agent::harness::turn_dispatch_guard::with_dispatch_guard(
- crate::openhuman::agent::tinyagents::agent_turn_wall_clock_ms()
- .map(std::time::Duration::from_millis),
- turn_future,
- )
- .await;
- let outcome = outcome?;
-
- // Record whether this turn paused at the tool-call cap (vs. finishing
- // naturally) BEFORE anything below can early-return, so a caller
- // inspecting `last_turn_hit_cap()` after `run_single` always reflects
- // this turn, never a stale value from a prior one.
- self.last_turn_hit_cap = outcome.hit_cap;
-
- // The stamped user turn is already in `self.history` (pushed by `turn()`),
- // so append only the structured messages this turn produced — assistant
- // tool calls + tool results + (for a clean finish) the final assistant —
- // preserving tool-call history fidelity for the UI, persisted transcript,
- // and the next turn's KV-cache prefix.
- self.history.extend(outcome.conversation.iter().cloned());
-
- // Token accounting for the turn (the cap checkpoint call below folds in
- // its own usage).
- // Seed from the turn outcome (the harness observed real usage incl. cached
- // tokens and an estimated cost) rather than zero, so a normal non-cap turn
- // persists real cost instead of $0. The cap-checkpoint branch below folds
- // in its extra call's usage on top.
- let mut input_tokens = outcome.input_tokens;
- let mut output_tokens = outcome.output_tokens;
- let mut cached_input_tokens = outcome.cached_input_tokens;
- let mut charged_amount_usd = outcome.charged_amount_usd;
-
- let reply = if outcome.hit_cap {
- // The loop paused at the tool-call cap. Ask the model for a resumable
- // checkpoint (tools disabled), falling back to a deterministic
- // done/next summary so the thread never ends on a dangling tool
- // cycle. Fold the extra call's usage into the turn accounting.
- let base = self.tool_dispatcher.to_provider_messages(&self.history);
- let (summary, summary_usage) = self
- .summarize_turn_wrapup(
- &base,
- effective_model,
- outcome.model_calls as u32 + 1,
- super::super::turn_checkpoint::MAX_ITER_CHECKPOINT_INSTRUCTION,
- )
- .await;
- if let Some(u) = summary_usage {
- input_tokens += u.input_tokens;
- output_tokens += u.output_tokens;
- cached_input_tokens += u.cached_input_tokens;
- charged_amount_usd += u.charged_amount_usd;
- }
- let checkpoint = if summary.trim().is_empty() {
- super::super::turn_checkpoint::build_deterministic_checkpoint(
- &tool_records_from_conversation(&outcome.conversation, &outcome.tool_outcomes),
- max_iterations,
- )
- } else {
- summary
- };
- self.history
- .push(ConversationMessage::Chat(ChatMessage::assistant(
- checkpoint.clone(),
- )));
- checkpoint
- } else if outcome.text.trim().is_empty() && outcome.tool_calls == 0 {
- // A completion with no text and no tool calls is never a valid final
- // answer — surface it as an error instead of wedging the thread on a
- // blank reply (bug-report-2026-05-26 A1, defect B).
- //
- // #4457 (defect A): the empty terminal assistant response was already
- // folded into `self.history` via `outcome.conversation` at the
- // `history.extend` above (an empty `Chat(assistant(""))`). The #4093
- // branch below pops that dangling blank row before re-prompting, but
- // this `tool_calls == 0` path returned the error with the empty row
- // still in history — so the *next* request carried an empty-content
- // assistant message and strict providers (Anthropic: "text content
- // blocks must be non-empty") 400 the whole thread, not just this turn.
- // Pop the trailing empty assistant row before returning so a retry
- // sends a clean transcript.
- if matches!(
- self.history.last(),
- Some(ConversationMessage::Chat(msg))
- if msg.role == "assistant" && msg.content.trim().is_empty()
- ) {
- log::debug!(
- "[agent_loop] EmptyProviderResponse at iteration {}: popping dangling empty assistant row before returning — #4457 defect A",
- outcome.model_calls
- );
- self.history.pop();
- }
- return Err(anyhow::Error::new(
- crate::openhuman::agent::error::AgentError::EmptyProviderResponse {
- iteration: outcome.model_calls,
- },
- ));
- } else if outcome.text.trim().is_empty() {
- // #4093: the loop ran tool calls (tool_calls > 0, so the branch
- // above did not fire) and then yielded a terminating response with
- // no final text — the turn did work but would otherwise end
- // silently, leaving the user with nothing. Enforce the
- // "must produce a final response" terminal step: re-prompt the
- // model (tools disabled) for a closing summary of what it did,
- // falling back to a deterministic summary of the tool calls so the
- // synthesized message is never itself empty. Fold the extra call's
- // usage into the turn accounting, exactly like the cap path above.
- let base = self.tool_dispatcher.to_provider_messages(&self.history);
- let (summary, summary_usage) = self
- .summarize_turn_wrapup(
- &base,
- effective_model,
- outcome.model_calls as u32 + 1,
- super::super::turn_checkpoint::FINAL_ANSWER_INSTRUCTION,
- )
- .await;
- if let Some(u) = summary_usage {
- input_tokens += u.input_tokens;
- output_tokens += u.output_tokens;
- cached_input_tokens += u.cached_input_tokens;
- charged_amount_usd += u.charged_amount_usd;
- }
- let final_answer = if summary.trim().is_empty() {
- super::super::turn_checkpoint::build_deterministic_final_summary(
- &tool_records_from_conversation(&outcome.conversation, &outcome.tool_outcomes),
- )
- } else {
- summary
- };
- log::info!(
- "[agent_loop] turn produced no final text after {} tool call(s); synthesized a closing summary ({} chars) — #4093",
- outcome.tool_calls,
- final_answer.chars().count()
- );
- // The empty terminal assistant response was already folded into
- // `self.history` via `outcome.conversation` above (an empty
- // `Chat(assistant(""))` — see `messages_to_conversation`). Drop that
- // blank turn before appending the synthesized answer so the
- // transcript and the next prompt don't carry a dangling empty
- // assistant message immediately before the real reply (Codex review).
- if matches!(
- self.history.last(),
- Some(ConversationMessage::Chat(msg))
- if msg.role == "assistant" && msg.content.trim().is_empty()
- ) {
- self.history.pop();
- }
- self.history
- .push(ConversationMessage::Chat(ChatMessage::assistant(
- final_answer.clone(),
- )));
- final_answer
- } else {
- outcome.text.clone()
- };
-
- // Enforce the required structured-output contract (issue #4117) on the
- // accepted reply — for ALL of the branches above (normal finish, cap
- // checkpoint, #4093 synthesized close), since each delivers a reply
- // downstream parsing depends on. When this agent must emit a JSON block
- // every turn and the reply omitted it, validate-and-repair before the
- // turn is accepted, reconciling with streaming (append-only when a live
- // stream is attached, replace otherwise — see `enforce_required_output`).
- // The trailing assistant message is rewritten to match, and the repair
- // call's usage is folded into the turn accounting. `required_output`
- // defaults to `None`, so existing agents are entirely unaffected.
- // Converted to the crate contract at the read site: the enforcement
- // helpers below are part of the runtime slated to move into TinyAgents
- // and so speak the crate type, while the session still holds the host's
- // `AgentConfig`. See `tinyagents::config::required_output_from`.
- let reply = if let Some(contract) = self
- .config
- .required_output
- .as_ref()
- .map(crate::openhuman::agent::tinyagents::config::required_output_from)
- {
- match self
- .enforce_required_output(
- &reply,
- &contract,
- effective_model,
- outcome.model_calls as u32 + 1,
- )
- .await
- {
- Some((repaired, repair_usage)) => {
- if let Some(u) = repair_usage {
- input_tokens += u.input_tokens;
- output_tokens += u.output_tokens;
- cached_input_tokens += u.cached_input_tokens;
- charged_amount_usd += u.charged_amount_usd;
- }
- replace_last_assistant_reply(&mut self.history, &repaired);
- repaired
- }
- None => reply,
- }
- } else {
- reply
- };
- self.trim_history();
-
- // Fold this turn's sub-agent spend into the cumulative meters and capture
- // the holistic per-turn usage the web channel surfaces on `chat_done` (it
- // calls `take_last_turn_usage_totals()` right after the turn). Without this
- // the event reported `usage: None` despite the transcript being persisted
- // with real numbers.
- for entry in &subagent_usage_entries {
- input_tokens = input_tokens.saturating_add(entry.usage.input_tokens);
- output_tokens = output_tokens.saturating_add(entry.usage.output_tokens);
- cached_input_tokens =
- cached_input_tokens.saturating_add(entry.usage.cached_input_tokens);
- charged_amount_usd += entry.usage.charged_amount_usd;
- }
- self.last_turn_usage_totals = Some(
- crate::openhuman::agent::harness::turn_subagent_usage::LastTurnUsage {
- input_tokens,
- output_tokens,
- cached_input_tokens,
- cost_usd: charged_amount_usd,
- context_window: context_window.unwrap_or(0),
- subagents: subagent_usage_entries,
- },
- );
-
- let mut persisted = self.tool_dispatcher.to_provider_messages(&self.history);
- // Re-attach per-call failure outcomes (dropped when the engine folded
- // each tool result into a `role:"tool"` message) so the derived
- // transcript view renders failed tools as errors, not successes.
- stamp_tool_failures(&mut persisted, &outcome.tool_outcomes);
- // Carry the turn's provider (event channel) + effective model and usage
- // into the persisted transcript meta. Passing `None` here dropped
- // `provider`/`model` from every transcript (they are `TranscriptMeta`
- // fields sourced from the turn usage) — parity with the legacy engine,
- // which handed `self.last_turn_usage.as_ref()` to this call.
- let turn_usage = crate::openhuman::agent::harness::session::transcript::TurnUsage {
- provider: self.event_channel().to_string(),
- // The model that actually ran this turn (a per-turn override can
- // diverge from `self.model_name`); attribute usage to it.
- model: effective_model.to_string(),
- usage: crate::openhuman::agent::harness::session::transcript::MessageUsage {
- input: input_tokens,
- output: output_tokens,
- cached_input: cached_input_tokens,
- context_window: context_window.unwrap_or(0),
- cost_usd: charged_amount_usd,
- },
- ts: chrono::Utc::now().to_rfc3339(),
- reasoning_content: None,
- tool_calls: Vec::new(),
- iteration: outcome.model_calls as u32,
- };
- self.persist_session_transcript(
- &persisted,
- input_tokens,
- output_tokens,
- cached_input_tokens,
- charged_amount_usd,
- Some(&turn_usage),
- );
-
- // Charge this turn's usage against the thread's active goal (parity with
- // the legacy engine) so budgeted goals progress to `budget_limited` and
- // continuation scheduling reads a live budget. Self-guarding + best-effort
- // — a no-op when there is no active goal for the ambient thread.
- crate::openhuman::threads::goals::runtime::account_turn_against_goal(
- &self.workspace_dir,
- input_tokens,
- output_tokens,
- turn_started.elapsed().as_secs(),
- )
- .await;
-
- // Content (prompt + reply) rides its own event so a tracing consumer can
- // attach it to the turn span. Gated on the opt-in
- // `observability.agent_tracing.capture_content` flag (#4454): with the
- // default off, we don't even emit the content event, so prompt/reply text
- // never reaches the span store or any exporter. The collector applies the
- // same storage-level gate as defense in depth.
- let capture_content = self
- .runtime_config
- .as_ref()
- .map(|c| c.observability.agent_tracing.capture_content)
- .unwrap_or(false);
- if capture_content {
- log::debug!(
- target: "agent-tracing",
- "[agent-tracing] emitting TurnContent (capture_content=true)"
- );
- self.emit_progress(AgentProgress::TurnContent {
- input: Some(user_message.to_string()),
- output: Some(reply.clone()),
- })
- .await;
- } else {
- log::debug!(
- target: "agent-tracing",
- "[agent-tracing] skipping TurnContent emit (capture_content=false)"
- );
- }
-
- self.emit_progress(AgentProgress::TurnCompleted {
- iterations: outcome.model_calls as u32,
- })
- .await;
-
- if self.auto_save {
- let summary = truncate_with_ellipsis(&reply, 100);
- let autosave_key = format!("assistant_resp:{}", uuid::Uuid::new_v4());
- let _ = self
- .memory
- .store(
- crate::openhuman::agent::learning::transcript_ingest::CONVERSATION_RAW_NAMESPACE,
- &autosave_key,
- &summary,
- MemoryCategory::Daily,
- None,
- )
- .await;
- }
-
- // Fire post-turn hooks (non-blocking), matching the legacy engine.
- if !self.post_turn_hooks.is_empty() {
- let ctx = TurnContext {
- user_message: user_message.to_string(),
- assistant_response: reply.clone(),
- tool_calls: tool_records_from_conversation(
- &outcome.conversation,
- &outcome.tool_outcomes,
- ),
- turn_duration_ms: turn_started.elapsed().as_millis() as u64,
- session_id: Some(self.event_session_id.clone())
- .filter(|session_id| !session_id.trim().is_empty()),
- agent_id: Some(self.agent_definition_id.clone())
- .filter(|agent_id| !agent_id.trim().is_empty()),
- entrypoint: Some(self.event_channel.clone())
- .filter(|entrypoint| !entrypoint.trim().is_empty()),
- iteration_count: outcome.model_calls,
- };
- hooks::fire_hooks(&self.post_turn_hooks, ctx);
- }
-
- Ok(reply)
- }
-
- pub(super) async fn inject_agent_experience_context(
- &self,
- user_message: &str,
- enriched: String,
- ) -> String {
- const MAX_EXPERIENCE_HITS: usize = 3;
- const MAX_EXPERIENCE_BLOCK_BYTES: usize = 2048;
-
- if !self.learning_enabled {
- return enriched;
- }
-
- let tools = self
- .visible_tool_specs
- .iter()
- .map(|spec| spec.name.clone())
- .collect();
- let mut stores = vec![AgentExperienceStore::new(self.memory.clone())];
- if let Some(shared_memory) = &self.shared_experience_memory {
- stores.push(AgentExperienceStore::new(shared_memory.clone()));
- }
- let query = ExperienceQuery {
- query: user_message.to_string(),
- tools,
- tags: Vec::new(),
- agent_id: Some(self.agent_definition_id.clone()).filter(|id| !id.trim().is_empty()),
- entrypoint: Some(self.event_channel.clone())
- .filter(|entrypoint| !entrypoint.trim().is_empty()),
- // 1c — partition recall by the active profile: this turn sees records
- // stamped with its profile plus unstamped legacy records, and never a
- // sibling profile's. `None` (profile-less) recalls the whole pool.
- profile_id: self.active_profile_id.clone(),
- max_hits: MAX_EXPERIENCE_HITS,
- };
-
- match retrieve_across_stores(&stores, query).await {
- Ok(hits) => {
- let matched_hits: Vec<_> = hits
- .into_iter()
- .filter(|hit| !hit.match_reasons.is_empty())
- .collect();
- let block = render_experience_hits(&matched_hits, MAX_EXPERIENCE_BLOCK_BYTES);
- if block.is_empty() {
- return enriched;
- }
- log::debug!(
- "[agent-experience] injected {} experience hit(s) bytes={}",
- matched_hits.len(),
- block.len()
- );
- prepend_experience_block(&enriched, &block)
- }
- Err(err) => {
- log::warn!("[agent-experience] retrieval failed (non-fatal): {err}");
- enriched
- }
- }
- }
-
- async fn inject_triggered_memory_agent_context(
- &self,
- user_message: &str,
- enriched: String,
- parent_context: &ParentExecutionContext,
- force_skip: bool,
- ) -> (String, bool) {
- const MEMORY_AGENT_ID: &str = "agent_memory";
- const MAX_MEMORY_AGENT_BLOCK_CHARS: usize = 8000;
-
- if force_skip {
- // Per-turn override (#1725): a chat / small-talk turn skips the
- // pre-turn memory-agent retrieval even when this agent's policy is
- // `Always`, so a greeting never pulls a prior task's remembered
- // context into an unrelated reply.
- log::debug!(
- "[agent_memory:trigger] skipped agent_id={} (per-turn suppress_memory_agent override)",
- self.agent_definition_id
- );
- return (enriched, false);
- }
-
- if self.trigger_memory_agent != TriggerMemoryAgent::Always {
- log::debug!(
- "[agent_memory:trigger] skipped agent_id={} policy={:?}",
- self.agent_definition_id,
- self.trigger_memory_agent
- );
- return (enriched, false);
- }
-
- if self.agent_definition_id == MEMORY_AGENT_ID {
- log::debug!("[agent_memory:trigger] skipped recursive memory agent invocation");
- return (enriched, false);
- }
-
- let Some(registry) = harness::AgentDefinitionRegistry::global() else {
- log::warn!(
- "[agent_memory:trigger] AgentDefinitionRegistry unavailable; continuing without memory agent context"
- );
- return (enriched, false);
- };
- let Some(definition) = registry.get(MEMORY_AGENT_ID).cloned() else {
- log::warn!(
- "[agent_memory:trigger] `{MEMORY_AGENT_ID}` definition unavailable; continuing without memory agent context"
- );
- return (enriched, false);
- };
-
- let task_id = format!("mem-trigger-{}", uuid::Uuid::new_v4());
- let prompt = format!(
- "Search the user's memory tree and return only context relevant to the next agent turn.\n\nUser prompt:\n{user_message}"
- );
- let options = harness::SubagentRunOptions {
- task_id: Some(task_id.clone()),
- model_override: Some(parent_context.model_name.clone()),
- ..Default::default()
- };
-
- log::debug!(
- "[agent_memory:trigger] starting agent_id={} task_id={} user_message_chars={}",
- self.agent_definition_id,
- task_id,
- user_message.chars().count()
- );
-
- let started = std::time::Instant::now();
- let result = harness::with_parent_context(parent_context.clone(), async move {
- harness::run_subagent(&definition, &prompt, options).await
- })
- .await;
-
- match result {
- Ok(outcome) => {
- log::info!(
- "[agent_memory:trigger] completed agent_id={} task_id={} iterations={} elapsed={:?} status={:?} output_chars={}",
- self.agent_definition_id,
- task_id,
- outcome.iterations,
- started.elapsed(),
- outcome.status,
- outcome.output.chars().count()
- );
- let mut output =
- truncate_with_ellipsis(&outcome.output, MAX_MEMORY_AGENT_BLOCK_CHARS);
- if let harness::subagent_runner::SubagentRunStatus::AwaitingUser {
- question, ..
- } = &outcome.status
- {
- let question = question.trim();
- if !question.is_empty() {
- output.push_str("\n\nMemory agent needs clarification: ");
- output.push_str(question);
- }
- }
- output = truncate_with_ellipsis(&output, MAX_MEMORY_AGENT_BLOCK_CHARS);
- if output.trim().is_empty() {
- return (enriched, false);
- }
- (
- format!(
- "## Memory agent context\n\n{}\n\n---\n\n{}",
- output.trim(),
- enriched
- ),
- true,
- )
- }
- Err(err) => {
- log::warn!(
- "[agent_memory:trigger] failed agent_id={} task_id={}: {err:#}",
- self.agent_definition_id,
- task_id
- );
- (enriched, false)
- }
- }
- }
-}
+include!("core_turn.rs");
+include!("core_session.rs");
diff --git a/src/openhuman/agent/harness/session/turn/core_session.rs b/src/openhuman/agent/harness/session/turn/core_session.rs
new file mode 100644
index 0000000000..2a09c1d2ef
--- /dev/null
+++ b/src/openhuman/agent/harness/session/turn/core_session.rs
@@ -0,0 +1,713 @@
+impl Agent {
+ /// Drive a full chat turn through the `tinyagents` harness (issue #4249).
+ ///
+ /// The frozen system+prior history is converted to provider messages, the
+ /// user turn appended, and the loop run over the agent's resolved tools. The
+ /// final reply + the user turn are recorded into `history`, the transcript
+ /// is persisted, and `TurnCompleted` is emitted so the UI stops spinning.
+ ///
+ /// Full-fidelity with the legacy `run_turn_engine`: live tool-timeline /
+ /// text-delta progress and the cost/token footer are mirrored from the
+ /// harness event stream via `OpenhumanEventBridge` (tinyagents harness),
+ /// `[IMAGE:…]`/`[FILE:…]` markers are expanded for the provider, and history
+ /// is trimmed to the provider's context window.
+ async fn run_turn_via_tinyagents_session(
+ &mut self,
+ user_message: &str,
+ effective_model: &str,
+ temperature: f64,
+ max_iterations: usize,
+ artifact_store: Option<
+ crate::openhuman::agent::harness::tool_result_artifacts::ToolResultArtifactStore,
+ >,
+ suppress_tools: bool,
+ ) -> Result<String> {
+ let turn_started = std::time::Instant::now();
+ // This turn's stamped user message is already the last entry in
+ // `self.history` (pushed by `turn()` before the engine branch), so build
+ // the provider messages straight from history — do NOT push the user
+ // again. When a cached transcript prefix is present (a resumed session's
+ // KV-cache warm-up), prepend it and clear it so the first request reuses
+ // the cached prefix exactly once.
+ let mut messages = self.tool_dispatcher.to_provider_messages(&self.history);
+ if let Some(cached) = self.cached_transcript_messages.take() {
+ // The cached prefix already carries the system prompt + prior
+ // conversation, so drop the freshly-rendered leading system
+ // message(s) and append only this turn's new (user) messages.
+ let tail = messages
+ .into_iter()
+ .skip_while(|m| m.role == "system")
+ .collect::<Vec<_>>();
+ let mut combined = cached;
+ combined.extend(tail);
+ messages = combined;
+ }
+
+ // Multimodal prep (parity with the legacy engine): rehydrate image
+ // placeholders for vision-capable providers, then expand `[IMAGE:…]` /
+ // `[FILE:…]` markers into provider-ready content before dispatch. The
+ // expanded copy is provider-only and never persisted to `history`.
+ let multimodal = self
+ .runtime_config
+ .as_ref()
+ .map(|c| c.multimodal.clone())
+ .unwrap_or_default();
+ let multimodal_files = self
+ .runtime_config
+ .as_ref()
+ .map(|c| c.multimodal_files.clone())
+ .unwrap_or_default();
+ // Resolve the effective context window and build the turn's tiered crate
+ // `ChatModel` set from the session source up front (issue #4249, Phase 3 /
+ // Motion A) — the harness holds crate model types, and the vision read
+ // below comes off the built models, not a raw provider.
+ let context_window = self
+ .turn_model_source
+ .effective_context_window(effective_model)
+ .await;
+ let turn_models =
+ self.turn_model_source
+ .build(effective_model, temperature, context_window)?;
+
+ // Honor custom/BYOK vision models too: they can set `model_vision` even
+ // when the provider capability bit is false, and must still rehydrate
+ // `[IMAGE:…]` placeholders (else image chat silently degrades to text).
+ if (turn_models.supports_vision() || self.model_vision)
+ && crate::openhuman::agent::multimodal::has_image_placeholders(&messages)
+ {
+ messages = crate::openhuman::agent::multimodal::rehydrate_image_placeholders(&messages);
+ }
+ let messages = crate::openhuman::agent::multimodal::prepare_messages_for_provider(
+ &messages,
+ &multimodal,
+ &multimodal_files,
+ )
+ .await
+ .map(|prepared| prepared.messages)
+ .unwrap_or(messages);
+
+ // Per-turn tool scope (#1725). A chat / small-talk turn runs with an
+ // EMPTY tool set: the provider request carries no tool schema, so the
+ // model cannot enter the tool loop and answers in a single call. The
+ // agent's durable `self.tools` / `self.visible_tool_names` are left
+ // untouched — the next un-overridden turn gets the full toolbelt back.
+ let (turn_tools, turn_visible_tool_names) = if suppress_tools {
+ (
+ std::sync::Arc::new(Vec::new()),
+ std::collections::HashSet::new(),
+ )
+ } else {
+ (self.tools.clone(), self.visible_tool_names.clone())
+ };
+
+ tracing::info!(
+ model = %effective_model,
+ max_iterations,
+ tools = turn_tools.len(),
+ suppress_tools,
+ "[agent_loop] routing chat turn through the tinyagents harness"
+ );
+
+ // Dispatch through the chat turn graph (this folder's `graph.rs`): a thin
+ // wrapper over the shared tinyagents seam that pins the chat path's fixed
+ // arguments (no child scope, no early-exit tools, graceful cap pause,
+ // per-turn output cap) and runs the context-window summarization step.
+ // Context middlewares sourced from this session's ContextManager: the
+ // per-tool-result byte cap + payload summarizer (after_tool) and
+ // microcompact tool-body clearing (before_model). KV-cache-prefix drift
+ // detection is owned by the crate `PromptCacheGuardMiddleware` (fed by
+ // `PromptCacheSegmentMiddleware`); the warn-only `CacheAlignMiddleware`
+ // was deleted in C3.
+ let context_mw = crate::openhuman::agent::tinyagents::TurnContextMiddleware {
+ tool_result_budget_bytes: self.context.tool_result_budget_bytes(),
+ payload_summarizer: self.payload_summarizer.clone(),
+ artifact_store,
+ tokenjuice_compaction_enabled: self.context.compaction_enabled(),
+ tokenjuice_compression: self.tokenjuice_compression,
+ microcompact_keep_recent: self.context.microcompact_keep_recent(),
+ // Honor the [context].enabled / autocompact_enabled opt-outs: when off,
+ // the summarization middleware is not installed (no summarizer tokens,
+ // no history rewrite).
+ autocompact_enabled: self.context.autocompact_enabled(),
+ // Progressive-disclosure handoff is a sub-agent (integrations_agent)
+ // concern; the top-level chat turn never sets it.
+ handoff: None,
+ // Live transcript snapshotting is a sub-agent error-recovery concern
+ // (#4466); the chat path persists its transcript post-run.
+ transcript_snapshot: None,
+ };
+
+ // Gather any sub-agent spend delegated during this turn (synchronous
+ // `spawn_subagent` runs inline on this task and records into the collector)
+ // so the turn's usage meters + the `chat_done` per-child breakdown include
+ // it — the collector scope the legacy engine installed.
+ // Install the turn's sub-agent dispatch guard around the same future
+ // (#5804). It records two facts the turn already produces but never
+ // wrote down — that a graceful pause has been requested at the
+ // model-call cap, and how long this turn's sub-agents actually take —
+ // so `run_subagent` can refuse a dispatch that cannot finish inside the
+ // remaining wall-clock budget instead of taking the whole turn down
+ // with it. Boxed at the call site: `with_dispatch_guard` takes its
+ // future by value, and the collector future wraps the entire turn
+ // generator, so passing it unboxed would move hundreds of KiB through
+ // this frame — the same hazard `with_turn_collector`'s own comment
+ // documents, with the gdb measurements behind it.
+ let turn_future = Box::pin(
+ crate::openhuman::agent::harness::turn_subagent_usage::with_turn_collector(
+ super::graph::run_chat_turn_graph(super::graph::ChatTurnGraph {
+ turn_models,
+ model: effective_model.to_string(),
+ messages,
+ tools: turn_tools,
+ visible_tool_names: turn_visible_tool_names,
+ max_iterations,
+ on_progress: self.on_progress.clone(),
+ context_window,
+ run_queue: self.run_queue.clone(),
+ context_mw,
+ // Enforce the builder-configured tool policy at the tool
+ // boundary (the tinyagents path otherwise bypasses it).
+ tool_policy: Some(crate::openhuman::agent::tinyagents::ToolPolicyEnforcement {
+ policy: self.tool_policy.clone(),
+ session: self.tool_policy_session.clone(),
+ session_id: self.event_session_id.clone(),
+ channel: self.event_channel().to_string(),
+ agent_definition_id: self.agent_definition_id.clone(),
+ }),
+ // Section D: forward the session's per-profile workspace
+ // descriptor (if any) so the top-level chat turn's acting
+ // tools default their cwd to the profile's dedicated dir.
+ workspace_descriptor: self.workspace_descriptor.clone(),
+ // Scope direct Master-Agent calls under its declared
+ // sandbox. `agent_definition_name` can carry a thread
+ // suffix, so resolve with the stable definition id.
+ sandbox_mode: crate::openhuman::agent::harness::definition::AgentDefinitionRegistry::global()
+ .and_then(|registry| registry.get(&self.agent_definition_id))
+ .map(|definition| definition.sandbox_mode)
+ .unwrap_or(crate::openhuman::agent::harness::definition::SandboxMode::None),
+ }),
+ ),
+ );
+ let (outcome, subagent_usage_entries) =
+ crate::openhuman::agent::harness::turn_dispatch_guard::with_dispatch_guard(
+ crate::openhuman::agent::tinyagents::agent_turn_wall_clock_ms()
+ .map(std::time::Duration::from_millis),
+ turn_future,
+ )
+ .await;
+ let outcome = outcome?;
+
+ // Record whether this turn paused at the tool-call cap (vs. finishing
+ // naturally) BEFORE anything below can early-return, so a caller
+ // inspecting `last_turn_hit_cap()` after `run_single` always reflects
+ // this turn, never a stale value from a prior one.
+ self.last_turn_hit_cap = outcome.hit_cap;
+
+ // The stamped user turn is already in `self.history` (pushed by `turn()`),
+ // so append only the structured messages this turn produced — assistant
+ // tool calls + tool results + (for a clean finish) the final assistant —
+ // preserving tool-call history fidelity for the UI, persisted transcript,
+ // and the next turn's KV-cache prefix.
+ self.history.extend(outcome.conversation.iter().cloned());
+
+ // Token accounting for the turn (the cap checkpoint call below folds in
+ // its own usage).
+ // Seed from the turn outcome (the harness observed real usage incl. cached
+ // tokens and an estimated cost) rather than zero, so a normal non-cap turn
+ // persists real cost instead of $0. The cap-checkpoint branch below folds
+ // in its extra call's usage on top.
+ let mut input_tokens = outcome.input_tokens;
+ let mut output_tokens = outcome.output_tokens;
+ let mut cached_input_tokens = outcome.cached_input_tokens;
+ let mut charged_amount_usd = outcome.charged_amount_usd;
+
+ let reply = if outcome.hit_cap {
+ // The loop paused at the tool-call cap. Ask the model for a resumable
+ // checkpoint (tools disabled), falling back to a deterministic
+ // done/next summary so the thread never ends on a dangling tool
+ // cycle. Fold the extra call's usage into the turn accounting.
+ let base = self.tool_dispatcher.to_provider_messages(&self.history);
+ let (summary, summary_usage) = self
+ .summarize_turn_wrapup(
+ &base,
+ effective_model,
+ outcome.model_calls as u32 + 1,
+ super::super::turn_checkpoint::MAX_ITER_CHECKPOINT_INSTRUCTION,
+ )
+ .await;
+ if let Some(u) = summary_usage {
+ input_tokens += u.input_tokens;
+ output_tokens += u.output_tokens;
+ cached_input_tokens += u.cached_input_tokens;
+ charged_amount_usd += u.charged_amount_usd;
+ }
+ let checkpoint = if summary.trim().is_empty() {
+ super::super::turn_checkpoint::build_deterministic_checkpoint(
+ &tool_records_from_conversation(&outcome.conversation, &outcome.tool_outcomes),
+ max_iterations,
+ )
+ } else {
+ summary
+ };
+ self.history
+ .push(ConversationMessage::Chat(ChatMessage::assistant(
+ checkpoint.clone(),
+ )));
+ checkpoint
+ } else if outcome.text.trim().is_empty() && outcome.tool_calls == 0 {
+ // A completion with no text and no tool calls is never a valid final
+ // answer — surface it as an error instead of wedging the thread on a
+ // blank reply (bug-report-2026-05-26 A1, defect B).
+ //
+ // #4457 (defect A): the empty terminal assistant response was already
+ // folded into `self.history` via `outcome.conversation` at the
+ // `history.extend` above (an empty `Chat(assistant(""))`). The #4093
+ // branch below pops that dangling blank row before re-prompting, but
+ // this `tool_calls == 0` path returned the error with the empty row
+ // still in history — so the *next* request carried an empty-content
+ // assistant message and strict providers (Anthropic: "text content
+ // blocks must be non-empty") 400 the whole thread, not just this turn.
+ // Pop the trailing empty assistant row before returning so a retry
+ // sends a clean transcript.
+ if matches!(
+ self.history.last(),
+ Some(ConversationMessage::Chat(msg))
+ if msg.role == "assistant" && msg.content.trim().is_empty()
+ ) {
+ log::debug!(
+ "[agent_loop] EmptyProviderResponse at iteration {}: popping dangling empty assistant row before returning — #4457 defect A",
+ outcome.model_calls
+ );
+ self.history.pop();
+ }
+ return Err(anyhow::Error::new(
+ crate::openhuman::agent::error::AgentError::EmptyProviderResponse {
+ iteration: outcome.model_calls,
+ },
+ ));
+ } else if outcome.text.trim().is_empty() {
+ // #4093: the loop ran tool calls (tool_calls > 0, so the branch
+ // above did not fire) and then yielded a terminating response with
+ // no final text — the turn did work but would otherwise end
+ // silently, leaving the user with nothing. Enforce the
+ // "must produce a final response" terminal step: re-prompt the
+ // model (tools disabled) for a closing summary of what it did,
+ // falling back to a deterministic summary of the tool calls so the
+ // synthesized message is never itself empty. Fold the extra call's
+ // usage into the turn accounting, exactly like the cap path above.
+ let base = self.tool_dispatcher.to_provider_messages(&self.history);
+ let (summary, summary_usage) = self
+ .summarize_turn_wrapup(
+ &base,
+ effective_model,
+ outcome.model_calls as u32 + 1,
+ super::super::turn_checkpoint::FINAL_ANSWER_INSTRUCTION,
+ )
+ .await;
+ if let Some(u) = summary_usage {
+ input_tokens += u.input_tokens;
+ output_tokens += u.output_tokens;
+ cached_input_tokens += u.cached_input_tokens;
+ charged_amount_usd += u.charged_amount_usd;
+ }
+ let final_answer = if summary.trim().is_empty() {
+ super::super::turn_checkpoint::build_deterministic_final_summary(
+ &tool_records_from_conversation(&outcome.conversation, &outcome.tool_outcomes),
+ )
+ } else {
+ summary
+ };
+ log::info!(
+ "[agent_loop] turn produced no final text after {} tool call(s); synthesized a closing summary ({} chars) — #4093",
+ outcome.tool_calls,
+ final_answer.chars().count()
+ );
+ // The empty terminal assistant response was already folded into
+ // `self.history` via `outcome.conversation` above (an empty
+ // `Chat(assistant(""))` — see `messages_to_conversation`). Drop that
+ // blank turn before appending the synthesized answer so the
+ // transcript and the next prompt don't carry a dangling empty
+ // assistant message immediately before the real reply (Codex review).
+ if matches!(
+ self.history.last(),
+ Some(ConversationMessage::Chat(msg))
+ if msg.role == "assistant" && msg.content.trim().is_empty()
+ ) {
+ self.history.pop();
+ }
+ self.history
+ .push(ConversationMessage::Chat(ChatMessage::assistant(
+ final_answer.clone(),
+ )));
+ final_answer
+ } else {
+ outcome.text.clone()
+ };
+
+ // Enforce the required structured-output contract (issue #4117) on the
+ // accepted reply — for ALL of the branches above (normal finish, cap
+ // checkpoint, #4093 synthesized close), since each delivers a reply
+ // downstream parsing depends on. When this agent must emit a JSON block
+ // every turn and the reply omitted it, validate-and-repair before the
+ // turn is accepted, reconciling with streaming (append-only when a live
+ // stream is attached, replace otherwise — see `enforce_required_output`).
+ // The trailing assistant message is rewritten to match, and the repair
+ // call's usage is folded into the turn accounting. `required_output`
+ // defaults to `None`, so existing agents are entirely unaffected.
+ // Converted to the crate contract at the read site: the enforcement
+ // helpers below are part of the runtime slated to move into TinyAgents
+ // and so speak the crate type, while the session still holds the host's
+ // `AgentConfig`. See `tinyagents::config::required_output_from`.
+ let reply = if let Some(contract) = self
+ .config
+ .required_output
+ .as_ref()
+ .map(crate::openhuman::agent::tinyagents::config::required_output_from)
+ {
+ match self
+ .enforce_required_output(
+ &reply,
+ &contract,
+ effective_model,
+ outcome.model_calls as u32 + 1,
+ )
+ .await
+ {
+ Some((repaired, repair_usage)) => {
+ if let Some(u) = repair_usage {
+ input_tokens += u.input_tokens;
+ output_tokens += u.output_tokens;
+ cached_input_tokens += u.cached_input_tokens;
+ charged_amount_usd += u.charged_amount_usd;
+ }
+ replace_last_assistant_reply(&mut self.history, &repaired);
+ repaired
+ }
+ None => reply,
+ }
+ } else {
+ reply
+ };
+ self.trim_history();
+
+ // Fold this turn's sub-agent spend into the cumulative meters and capture
+ // the holistic per-turn usage the web channel surfaces on `chat_done` (it
+ // calls `take_last_turn_usage_totals()` right after the turn). Without this
+ // the event reported `usage: None` despite the transcript being persisted
+ // with real numbers.
+ for entry in &subagent_usage_entries {
+ input_tokens = input_tokens.saturating_add(entry.usage.input_tokens);
+ output_tokens = output_tokens.saturating_add(entry.usage.output_tokens);
+ cached_input_tokens =
+ cached_input_tokens.saturating_add(entry.usage.cached_input_tokens);
+ charged_amount_usd += entry.usage.charged_amount_usd;
+ }
+ self.last_turn_usage_totals = Some(
+ crate::openhuman::agent::harness::turn_subagent_usage::LastTurnUsage {
+ input_tokens,
+ output_tokens,
+ cached_input_tokens,
+ cost_usd: charged_amount_usd,
+ context_window: context_window.unwrap_or(0),
+ subagents: subagent_usage_entries,
+ },
+ );
+
+ let mut persisted = self.tool_dispatcher.to_provider_messages(&self.history);
+ // Re-attach per-call failure outcomes (dropped when the engine folded
+ // each tool result into a `role:"tool"` message) so the derived
+ // transcript view renders failed tools as errors, not successes.
+ stamp_tool_failures(&mut persisted, &outcome.tool_outcomes);
+ // Carry the turn's provider (event channel) + effective model and usage
+ // into the persisted transcript meta. Passing `None` here dropped
+ // `provider`/`model` from every transcript (they are `TranscriptMeta`
+ // fields sourced from the turn usage) — parity with the legacy engine,
+ // which handed `self.last_turn_usage.as_ref()` to this call.
+ let turn_usage = crate::openhuman::agent::harness::session::transcript::TurnUsage {
+ provider: self.event_channel().to_string(),
+ // The model that actually ran this turn (a per-turn override can
+ // diverge from `self.model_name`); attribute usage to it.
+ model: effective_model.to_string(),
+ usage: crate::openhuman::agent::harness::session::transcript::MessageUsage {
+ input: input_tokens,
+ output: output_tokens,
+ cached_input: cached_input_tokens,
+ context_window: context_window.unwrap_or(0),
+ cost_usd: charged_amount_usd,
+ },
+ ts: chrono::Utc::now().to_rfc3339(),
+ reasoning_content: None,
+ tool_calls: Vec::new(),
+ iteration: outcome.model_calls as u32,
+ };
+ self.persist_session_transcript(
+ &persisted,
+ input_tokens,
+ output_tokens,
+ cached_input_tokens,
+ charged_amount_usd,
+ Some(&turn_usage),
+ );
+
+ // Charge this turn's usage against the thread's active goal (parity with
+ // the legacy engine) so budgeted goals progress to `budget_limited` and
+ // continuation scheduling reads a live budget. Self-guarding + best-effort
+ // — a no-op when there is no active goal for the ambient thread.
+ crate::openhuman::threads::goals::runtime::account_turn_against_goal(
+ &self.workspace_dir,
+ input_tokens,
+ output_tokens,
+ turn_started.elapsed().as_secs(),
+ )
+ .await;
+
+ // Content (prompt + reply) rides its own event so a tracing consumer can
+ // attach it to the turn span. Gated on the opt-in
+ // `observability.agent_tracing.capture_content` flag (#4454): with the
+ // default off, we don't even emit the content event, so prompt/reply text
+ // never reaches the span store or any exporter. The collector applies the
+ // same storage-level gate as defense in depth.
+ let capture_content = self
+ .runtime_config
+ .as_ref()
+ .map(|c| c.observability.agent_tracing.capture_content)
+ .unwrap_or(false);
+ if capture_content {
+ log::debug!(
+ target: "agent-tracing",
+ "[agent-tracing] emitting TurnContent (capture_content=true)"
+ );
+ self.emit_progress(AgentProgress::TurnContent {
+ input: Some(user_message.to_string()),
+ output: Some(reply.clone()),
+ })
+ .await;
+ } else {
+ log::debug!(
+ target: "agent-tracing",
+ "[agent-tracing] skipping TurnContent emit (capture_content=false)"
+ );
+ }
+
+ self.emit_progress(AgentProgress::TurnCompleted {
+ iterations: outcome.model_calls as u32,
+ })
+ .await;
+
+ if self.auto_save {
+ let summary = truncate_with_ellipsis(&reply, 100);
+ let autosave_key = format!("assistant_resp:{}", uuid::Uuid::new_v4());
+ let _ = self
+ .memory
+ .store(
+ crate::openhuman::agent::learning::transcript_ingest::CONVERSATION_RAW_NAMESPACE,
+ &autosave_key,
+ &summary,
+ MemoryCategory::Daily,
+ None,
+ )
+ .await;
+ }
+
+ // Fire post-turn hooks (non-blocking), matching the legacy engine.
+ if !self.post_turn_hooks.is_empty() {
+ let ctx = TurnContext {
+ user_message: user_message.to_string(),
+ assistant_response: reply.clone(),
+ tool_calls: tool_records_from_conversation(
+ &outcome.conversation,
+ &outcome.tool_outcomes,
+ ),
+ turn_duration_ms: turn_started.elapsed().as_millis() as u64,
+ session_id: Some(self.event_session_id.clone())
+ .filter(|session_id| !session_id.trim().is_empty()),
+ agent_id: Some(self.agent_definition_id.clone())
+ .filter(|agent_id| !agent_id.trim().is_empty()),
+ entrypoint: Some(self.event_channel.clone())
+ .filter(|entrypoint| !entrypoint.trim().is_empty()),
+ iteration_count: outcome.model_calls,
+ };
+ hooks::fire_hooks(&self.post_turn_hooks, ctx);
+ }
+
+ Ok(reply)
+ }
+
+ pub(super) async fn inject_agent_experience_context(
+ &self,
+ user_message: &str,
+ enriched: String,
+ ) -> String {
+ const MAX_EXPERIENCE_HITS: usize = 3;
+ const MAX_EXPERIENCE_BLOCK_BYTES: usize = 2048;
+
+ if !self.learning_enabled {
+ return enriched;
+ }
+
+ let tools = self
+ .visible_tool_specs
+ .iter()
+ .map(|spec| spec.name.clone())
+ .collect();
+ let mut stores = vec![AgentExperienceStore::new(self.memory.clone())];
+ if let Some(shared_memory) = &self.shared_experience_memory {
+ stores.push(AgentExperienceStore::new(shared_memory.clone()));
+ }
+ let query = ExperienceQuery {
+ query: user_message.to_string(),
+ tools,
+ tags: Vec::new(),
+ agent_id: Some(self.agent_definition_id.clone()).filter(|id| !id.trim().is_empty()),
+ entrypoint: Some(self.event_channel.clone())
+ .filter(|entrypoint| !entrypoint.trim().is_empty()),
+ // 1c — partition recall by the active profile: this turn sees records
+ // stamped with its profile plus unstamped legacy records, and never a
+ // sibling profile's. `None` (profile-less) recalls the whole pool.
+ profile_id: self.active_profile_id.clone(),
+ max_hits: MAX_EXPERIENCE_HITS,
+ };
+
+ match retrieve_across_stores(&stores, query).await {
+ Ok(hits) => {
+ let matched_hits: Vec<_> = hits
+ .into_iter()
+ .filter(|hit| !hit.match_reasons.is_empty())
+ .collect();
+ let block = render_experience_hits(&matched_hits, MAX_EXPERIENCE_BLOCK_BYTES);
+ if block.is_empty() {
+ return enriched;
+ }
+ log::debug!(
+ "[agent-experience] injected {} experience hit(s) bytes={}",
+ matched_hits.len(),
+ block.len()
+ );
+ prepend_experience_block(&enriched, &block)
+ }
+ Err(err) => {
+ log::warn!("[agent-experience] retrieval failed (non-fatal): {err}");
+ enriched
+ }
+ }
+ }
+
+ async fn inject_triggered_memory_agent_context(
+ &self,
+ user_message: &str,
+ enriched: String,
+ parent_context: &ParentExecutionContext,
+ force_skip: bool,
+ ) -> (String, bool) {
+ const MEMORY_AGENT_ID: &str = "agent_memory";
+ const MAX_MEMORY_AGENT_BLOCK_CHARS: usize = 8000;
+
+ if force_skip {
+ // Per-turn override (#1725): a chat / small-talk turn skips the
+ // pre-turn memory-agent retrieval even when this agent's policy is
+ // `Always`, so a greeting never pulls a prior task's remembered
+ // context into an unrelated reply.
+ log::debug!(
+ "[agent_memory:trigger] skipped agent_id={} (per-turn suppress_memory_agent override)",
+ self.agent_definition_id
+ );
+ return (enriched, false);
+ }
+
+ if self.trigger_memory_agent != TriggerMemoryAgent::Always {
+ log::debug!(
+ "[agent_memory:trigger] skipped agent_id={} policy={:?}",
+ self.agent_definition_id,
+ self.trigger_memory_agent
+ );
+ return (enriched, false);
+ }
+
+ if self.agent_definition_id == MEMORY_AGENT_ID {
+ log::debug!("[agent_memory:trigger] skipped recursive memory agent invocation");
+ return (enriched, false);
+ }
+
+ let Some(registry) = harness::AgentDefinitionRegistry::global() else {
+ log::warn!(
+ "[agent_memory:trigger] AgentDefinitionRegistry unavailable; continuing without memory agent context"
+ );
+ return (enriched, false);
+ };
+ let Some(definition) = registry.get(MEMORY_AGENT_ID).cloned() else {
+ log::warn!(
+ "[agent_memory:trigger] `{MEMORY_AGENT_ID}` definition unavailable; continuing without memory agent context"
+ );
+ return (enriched, false);
+ };
+
+ let task_id = format!("mem-trigger-{}", uuid::Uuid::new_v4());
+ let prompt = format!(
+ "Search the user's memory tree and return only context relevant to the next agent turn.\n\nUser prompt:\n{user_message}"
+ );
+ let options = harness::SubagentRunOptions {
+ task_id: Some(task_id.clone()),
+ model_override: Some(parent_context.model_name.clone()),
+ ..Default::default()
+ };
+
+ log::debug!(
+ "[agent_memory:trigger] starting agent_id={} task_id={} user_message_chars={}",
+ self.agent_definition_id,
+ task_id,
+ user_message.chars().count()
+ );
+
+ let started = std::time::Instant::now();
+ let result = harness::with_parent_context(parent_context.clone(), async move {
+ harness::run_subagent(&definition, &prompt, options).await
+ })
+ .await;
+
+ match result {
+ Ok(outcome) => {
+ log::info!(
+ "[agent_memory:trigger] completed agent_id={} task_id={} iterations={} elapsed={:?} status={:?} output_chars={}",
+ self.agent_definition_id,
+ task_id,
+ outcome.iterations,
+ started.elapsed(),
+ outcome.status,
+ outcome.output.chars().count()
+ );
+ let mut output =
+ truncate_with_ellipsis(&outcome.output, MAX_MEMORY_AGENT_BLOCK_CHARS);
+ if let harness::subagent_runner::SubagentRunStatus::AwaitingUser {
+ question, ..
+ } = &outcome.status
+ {
+ let question = question.trim();
+ if !question.is_empty() {
+ output.push_str("\n\nMemory agent needs clarification: ");
+ output.push_str(question);
+ }
+ }
+ output = truncate_with_ellipsis(&output, MAX_MEMORY_AGENT_BLOCK_CHARS);
+ if output.trim().is_empty() {
+ return (enriched, false);
+ }
+ (
+ format!(
+ "## Memory agent context\n\n{}\n\n---\n\n{}",
+ output.trim(),
+ enriched
+ ),
+ true,
+ )
+ }
+ Err(err) => {
+ log::warn!(
+ "[agent_memory:trigger] failed agent_id={} task_id={}: {err:#}",
+ self.agent_definition_id,
+ task_id
+ );
+ (enriched, false)
+ }
+ }
+ }
+}
diff --git a/src/openhuman/agent/harness/session/turn/core_turn.rs b/src/openhuman/agent/harness/session/turn/core_turn.rs
new file mode 100644
index 0000000000..b4a10e5b12
--- /dev/null
+++ b/src/openhuman/agent/harness/session/turn/core_turn.rs
@@ -0,0 +1,723 @@
+impl Agent {
+ /// Executes a single interaction "turn" with the agent.
+ ///
+ /// This function is the primary driver of the agent's behavior. It manages the
+ /// end-to-end lifecycle of a user request:
+ ///
+ /// 1. **Initialization**: Resumes from a session transcript if this is a new turn
+ /// to preserve KV-cache stability.
+ /// 2. **Prompt Construction**: Builds the system prompt (only on the first turn)
+ /// incorporating learned context and tool instructions.
+ /// 3. **Context Injection**: Enriches the user message with per-turn context
+ /// such as situational preferences, the thread goal, and active sub-agents.
+ /// Broad memory recall is available to the model on demand instead.
+ /// 4. **Execution Loop**: Enters a loop (up to `max_tool_iterations`) where it:
+ /// - Manages the context window (reduction/summarization).
+ /// - Calls the LLM provider.
+ /// - Parses and executes tool calls.
+ /// - Accumulates results into history.
+ /// 5. **Synthesis**: Returns the final assistant response after all tools have
+ /// finished or the iteration budget is exhausted.
+ /// 6. **Background Tasks**: Triggers episodic memory indexing and facts
+ /// extraction asynchronously.
+ pub async fn turn(&mut self, user_message: &str) -> Result<String> {
+ // Consume any per-turn overrides the caller set for THIS turn (#1725).
+ // Taking them resets the field to the default, so they apply to exactly
+ // one turn — a chat/small-talk turn runs tool-less, memory-less and
+ // goal-less without permanently altering the agent, and the following
+ // turn is back to full-agentic behaviour. Callers that never opt in get
+ // `TurnOverrides::default()` (all-false) and the unchanged path.
+ let turn_overrides = std::mem::take(&mut self.pending_turn_overrides);
+ if turn_overrides != super::super::types::TurnOverrides::default() {
+ log::info!(
+ "[agent_loop] per-turn overrides active: suppress_active_goal={} suppress_tools={} suppress_memory_agent={}",
+ turn_overrides.suppress_active_goal,
+ turn_overrides.suppress_tools,
+ turn_overrides.suppress_memory_agent
+ );
+ }
+ self.emit_progress(AgentProgress::TurnStarted).await;
+ log::info!("[agent] turn started — awaiting user message processing");
+ log::info!(
+ "[agent_loop] turn start message_chars={} history_len={} max_tool_iterations={}",
+ user_message.chars().count(),
+ self.history.len(),
+ self.config.max_tool_iterations
+ );
+ self.ensure_composio_integrations_listener();
+ // Arm the installed-skills listener at turn start (not lazily inside
+ // `drain_skill_events`, which is only reached after the first turn) —
+ // broadcast subscriptions are not retroactive, so a skill installed
+ // during turn 1 would otherwise be missed until a later subscribe.
+ self.ensure_skill_events_listener();
+ // ── Session transcript resume ─────────────────────────────────
+ // On a fresh session (empty history), look for a previous
+ // transcript to pre-populate the exact provider messages for
+ // KV cache prefix reuse.
+ if self.history.is_empty()
+ && self.cached_transcript_messages.is_none()
+ && !turn_overrides.suppress_transcript_autoload
+ {
+ self.try_load_session_transcript();
+ }
+
+ if self.history.is_empty() {
+ // Learned context is only baked into the system prompt on the
+ // very first turn — once the history is non-empty we reuse the
+ // stored prompt verbatim to preserve the KV-cache prefix the
+ // inference backend has already tokenised. Fetching it later
+ // would just burn memory-store reads on data we throw away.
+ if !self.connected_integrations_initialized {
+ self.fetch_connected_integrations().await;
+ // Sessions born without a cached Composio view still need
+ // a one-shot delegation-surface reconcile before the system
+ // prompt is frozen. The shared-Arc failure path returns
+ // `false`, but on turn 1 the Arc should still be uniquely
+ // owned; a `false` return here indicates a programmer error
+ // and the warn-level log inside the helper already surfaces
+ // it, so we keep the existing best-effort contract.
+ let _ = self.refresh_delegation_tools();
+ }
+ let learned = self.fetch_learned_context().await;
+ let rendered_prompt = self.build_system_prompt(learned)?;
+ log::info!("[agent] system prompt built — initialising conversation history");
+ log::info!(
+ "[agent_loop] system prompt built chars={}",
+ rendered_prompt.chars().count()
+ );
+ // User-file injection (PROFILE.md, MEMORY.md) puts
+ // potentially-sensitive content (LinkedIn scrape output,
+ // archivist-curated memories) into the system prompt. Avoid
+ // leaking that to debug logs — log a length + content hash
+ // instead. Narrow specialists (both flags off) keep the
+ // full-body log so prompt-engineering iteration on
+ // tools/safety sections stays easy.
+ //
+ // AGENTS.md instruction layers are also user/project-controlled and
+ // can land in the prompt even when PROFILE/MEMORY are both omitted
+ // (common for narrow specialists), so treat their presence as a
+ // redaction trigger too — otherwise the full-body path would print
+ // raw AGENTS.md contents verbatim.
+ let contains_agents_md =
+ rendered_prompt.contains("## Project instructions (AGENTS.md)");
+ if self.omit_profile && self.omit_memory_md && !contains_agents_md {
+ log::debug!("[agent_loop] system prompt body:\n{}", rendered_prompt);
+ } else {
+ let mut hasher = std::collections::hash_map::DefaultHasher::new();
+ rendered_prompt.hash(&mut hasher);
+ log::debug!(
+ "[agent_loop] system prompt body redacted (contains PROFILE/MEMORY/AGENTS.md): chars={} hash={:016x}",
+ rendered_prompt.chars().count(),
+ hasher.finish()
+ );
+ }
+ self.history
+ .push(ConversationMessage::Chat(ChatMessage::system(
+ rendered_prompt,
+ )));
+ // Seed the per-turn mid-session refresh baseline with the
+ // hash of whatever Composio actually returned just now.
+ // Subsequent turns short-circuit unless this hash changes.
+ self.last_seen_integrations_hash =
+ crate::openhuman::integrations::composio::connected_set_hash(
+ &self.connected_integrations,
+ );
+ // Seed the announced set with the startup connected toolkits so
+ // only genuinely-new mid-session connects get announced later.
+ self.announced_integrations = self
+ .connected_integrations
+ .iter()
+ .map(|i| i.toolkit.clone())
+ .collect();
+ // MCP analogue: seed the announced MCP set with the servers already
+ // connected at startup. Those are already in the (turn-1) system
+ // prompt's `## Connected MCP Servers` block, so only servers that
+ // connect *mid-session* should later be announced on the user turn.
+ self.announced_mcp_servers =
+ crate::openhuman::mcp::registry::connections::connected_overview()
+ .await
+ .into_iter()
+ .map(|s| s.qualified_name)
+ .collect();
+ } else {
+ // Deliberately do NOT rebuild the system prompt on subsequent
+ // turns. The rendered prompt is the KV-cache prefix the inference
+ // backend has already tokenised; replacing its bytes (even
+ // cosmetically) forces the backend to re-prefill from scratch.
+ //
+ // Dynamic turn-to-turn context rides on the user message assembled
+ // below (`context`) — that is where anything varying between turns
+ // belongs. Broad memory recall is not injected; the model calls the
+ // memory tools when it needs stored context.
+ //
+ // *** Mid-session schema-only refresh ***
+ //
+ // The system prompt stays frozen, but the function-calling
+ // schema (the `tools` field in the provider request) is sent
+ // fresh on every API call — it's not part of the KV-cache
+ // prefix. So we *can* react to Composio connect/disconnect
+ // events mid-session by re-synthesising the `delegate_<toolkit>`
+ // surface on `self.tools` / `self.tool_specs` and letting
+ // the next provider call carry the new schema. KV cache stays
+ // intact; the system prompt's `## Connected Integrations`
+ // block goes mildly stale until the next session, but the
+ // schema is the source of truth the model actually routes
+ // against.
+ //
+ // The signal we react to is the process-wide
+ // [`crate::openhuman::integrations::composio::INTEGRATIONS_CACHE`], kept
+ // current by (a) the desktop UI's 5 s
+ // `composio_list_connections` poll, (b) the post-OAuth
+ // `ComposioConnectionCreatedSubscriber` invalidation, and
+ // (c) the 60 s TTL fallback. We read it via the read-only
+ // [`crate::openhuman::integrations::composio::cached_active_integrations`]
+ // helper — never trigger a backend fetch ourselves, never
+ // block on a writer.
+ // Session agents built through `from_config_*` carry their
+ // runtime `Config` snapshot directly, so this read avoids the
+ // old `Config::load_or_init()` round-trip on every turn.
+ //
+ let _ = self.refresh_delegation_tools_from_cached_integrations("turn-boundary");
+ // Same idea for installed skills. The system-prompt
+ // `## Installed Skills` block is frozen at turn 1 for KV-cache
+ // stability (history is non-empty here, so it is never rebuilt
+ // mid-session), so — exactly like the MCP mechanism — the
+ // user-turn announcement below is what surfaces a mid-session
+ // install to the model. `refresh_workflows` updates the tracked
+ // set (so the next refresh diffs correctly and a future fresh
+ // session renders the new catalogue) and parks the announcement.
+ // Event-driven (mirror of the composio path): only re-scan disk
+ // when a `WorkflowsChanged` event was published since the last
+ // turn — no per-turn filesystem walk on the steady-state hot path.
+ if self.drain_skill_events() {
+ let _ = self.refresh_workflows("event");
+ }
+ // Cache empty/expired or config unavailable => no signal.
+ // We leave the current tool surface alone and pick up any
+ // real change on the next turn after the UI's 5 s poll has
+ // repopulated [`INTEGRATIONS_CACHE`].
+
+ // MCP mid-session connect surfacing — the analogue of the Composio
+ // path above. `use_mcp_server` is a single static delegate (no
+ // per-server schema to refresh), so the whole mechanism is: diff
+ // the live in-process connection map against what we've already
+ // announced and queue a one-shot note for any newly-connected
+ // server onto the next user message. The map is in-process (no
+ // network, unlike Composio's cache), so reading it every turn is
+ // cheap. Like the Composio block, the frozen `## Connected MCP
+ // Servers` system-prompt section stays as the turn-1 snapshot.
+ let connected_mcp: Vec<String> =
+ crate::openhuman::mcp::registry::connections::connected_overview()
+ .await
+ .into_iter()
+ .map(|s| s.qualified_name)
+ .collect();
+ for qn in newly_connected_slugs(&connected_mcp, &mut self.announced_mcp_servers) {
+ if !self.pending_mcp_announcement.contains(&qn) {
+ self.pending_mcp_announcement.push(qn);
+ }
+ }
+
+ log::trace!(
+ "[agent_loop] system prompt reused (history_len={}) — KV cache prefix preserved",
+ self.history.len()
+ );
+ }
+
+ if self.auto_save {
+ // Fire-and-forget: persisting the user message to the memory store
+ // does an embedding round-trip (Voyage) + memory-tree write that the
+ // in-flight turn never reads back. Awaiting it delayed the start of
+ // *every* turn before recall/LLM began, so spawn it and let the chat
+ // continue immediately.
+ //
+ // Use a UNIQUE per-message key: the old fixed `"user_msg"` key
+ // upserts a single document (`upsert_document` keys by namespace+key),
+ // so concurrent turns would race on — and overwrite — one shared slot.
+ // A unique key makes each user message its own conversation document,
+ // which both removes the race and stops the autosave from only ever
+ // retaining the latest message.
+ let memory = self.memory.clone();
+ let user_msg = user_message.to_string();
+ let autosave_key = format!("user_msg:{}", uuid::Uuid::new_v4());
+ let chars = user_msg.chars().count();
+ // Captured *before* `tokio::spawn` — the ambient thread id is a
+ // `tokio::task_local` (see `tinyagents::thread_context`)
+ // and does not propagate into a spawned task, so it must be read
+ // on this (still-scoped) task and moved in explicitly. Tagging
+ // this document with the live chat thread id is what lets the
+ // same-session exclusion filter (`UnifiedMemory::recall` /
+ // `memory_hybrid_search`) recognize and drop it later this same
+ // turn, so the agent's own on-demand memory search doesn't echo
+ // its own triggering request back as a "relevant" result.
+ let session_id_for_autosave =
+ crate::openhuman::agent::tinyagents::thread_context::current_thread_id();
+ log::debug!(
+ "[agent_autosave] enqueue user-message store key={autosave_key} chars={chars} \
+ session_id={}",
+ session_id_for_autosave.as_deref().unwrap_or("<none>")
+ );
+ tokio::spawn(async move {
+ match memory
+ .store(
+ crate::openhuman::agent::learning::transcript_ingest::CONVERSATION_RAW_NAMESPACE,
+ &autosave_key,
+ &user_msg,
+ MemoryCategory::Conversation,
+ session_id_for_autosave.as_deref(),
+ )
+ .await
+ {
+ Ok(()) => log::debug!(
+ "[agent_autosave] stored user-message key={autosave_key} chars={chars}"
+ ),
+ Err(err) => log::warn!(
+ "[agent_autosave] user-message memory autosave failed key={autosave_key} err={err}"
+ ),
+ }
+ });
+ }
+
+ log::info!("[agent] spawning UI-only citation collection for user message");
+ const MEMORY_CITATION_LIMIT: usize = 5;
+ const MEMORY_CITATION_MIN_RELEVANCE: f64 = 0.4;
+ // Spawned, not awaited: see `Agent::pending_citations`. The result is
+ // UI-only, so the turn must not wait for it before calling the model.
+ self.last_turn_citations.clear();
+ if let Some(previous) = self.pending_citations.take() {
+ // A turn that never had its citations collected leaves a task
+ // behind; abort it rather than letting a stale recall outlive the
+ // turn it belonged to.
+ previous.abort();
+ }
+ let citation_memory = self.memory.clone();
+ let citation_query = user_message.to_string();
+ self.pending_citations = Some(tokio::spawn(async move {
+ match collect_recall_citations(
+ citation_memory.as_ref(),
+ &citation_query,
+ MEMORY_CITATION_LIMIT,
+ MEMORY_CITATION_MIN_RELEVANCE,
+ )
+ .await
+ {
+ Ok(citations) => {
+ log::debug!(
+ "[agent_loop] memory citations collected count={}",
+ citations.len()
+ );
+ citations
+ }
+ Err(_err) => {
+ // Recall errors may include the user-authored query. Keep
+ // warning logs free of raw external content.
+ log::warn!("[agent_loop] memory citation collection failed");
+ Vec::new()
+ }
+ }
+ }));
+ // No per-turn memory-context block is assembled here any more.
+ //
+ // `memory_loader.load_context()` used to prepend `[User working
+ // memory]`, `[Prior conversations]` and `[Cross-chat context]` to every
+ // user message. It cost two full scans of the `global` namespace per
+ // turn — every document and every vector chunk, decoded and scored — to
+ // contribute at most nine lines, and the cost grew with everything the
+ // user had ever said. Benchmarked at ~10k memories it was the dominant
+ // per-turn cost by a wide margin, and the `[User working memory]` arm
+ // in particular scanned the whole namespace only to filter the results
+ // down to a `working.user.` key prefix, so it returned nothing at all
+ // once ordinary chat crowded the ranking.
+ //
+ // Memory is still available to the agent — `memory_recall` and the rest
+ // of the memory tools are unchanged, so the model fetches what it needs
+ // when it needs it, rather than every turn paying for a broad guess.
+ let mut context = String::new();
+
+ // ── Lane B: situational preferences (every turn) ─────────────────────
+ // Recall topic-scoped preferences semantically relevant to THIS message
+ // (model-aware embeddings, gated by vector similarity) and inject them
+ // under a banner. Runs every turn — unlike the first-turn-gated tree/STM
+ // blocks above — because the query changes per message; it rides the
+ // per-turn context that's prepended to the user message (no KV-cache
+ // cost). An unrelated message clears the similarity gate to nothing, so
+ // no block is injected.
+ {
+ let situational =
+ crate::openhuman::memory::preferences::recall_situational_preferences_on(
+ &self.memory,
+ user_message,
+ )
+ .await;
+ if !situational.is_empty() {
+ log::info!(
+ "[pref_recall] situational block injected: {} item(s)",
+ situational.len()
+ );
+ context.push_str("## Relevant preferences for this message\n\n");
+ for pref in &situational {
+ context.push_str("- ");
+ context.push_str(pref.trim());
+ context.push('\n');
+ }
+ context.push('\n');
+ } else {
+ log::debug!("[pref_recall] no situational preference relevant to this message");
+ }
+ }
+
+ // ── Thread goal (Codex-style per-thread completion contract) ─────────
+ // Load this thread's durable goal once per turn and prepend a compact
+ // [active_goal] block so the objective + live status/budget steer the
+ // turn. Rides the per-turn context (NOT the cached system-prompt prefix)
+ // so edits take effect immediately. `active_goal` is reused below to arm
+ // the budget stop hook around the engine call.
+ // Capture the workspace path for the budget stop hook built after the
+ // `turn_body` coroutine (which borrows `&mut self`) is constructed.
+ let goal_workspace_dir = self.workspace_dir.clone();
+ let active_goal = if turn_overrides.suppress_active_goal {
+ // Chat / small-talk turn: do NOT load, auto-resume, inject, or
+ // budget-arm this thread's goal. A goal an earlier task left
+ // uncompleted must not steer an unrelated greeting (#1725, the
+ // "stale goal replays every turn" half of the context leak).
+ log::debug!(
+ "[thread_goals] active_goal suppressed for this turn (chat/small-talk override)"
+ );
+ None
+ } else {
+ let loaded = crate::openhuman::threads::goals::runtime::load_for_current_thread(
+ &self.workspace_dir,
+ )
+ .await;
+ // Thread-resume semantics: the user re-engaging a thread reactivates a
+ // paused goal (Codex's ThreadResumed). Best-effort; on failure keep
+ // the loaded (paused) goal so we still surface it.
+ match loaded {
+ Some(goal)
+ if matches!(
+ goal.status,
+ crate::openhuman::threads::goals::ThreadGoalStatus::Paused
+ ) =>
+ {
+ crate::openhuman::threads::goals::runtime::resume_for_current_thread(
+ &self.workspace_dir,
+ )
+ .await
+ .unwrap_or(Some(goal))
+ }
+ other => other,
+ }
+ };
+ if let Some(ref goal) = active_goal {
+ if let Some(block) = tinyagents::graph::goals::active_goal_context_block(goal) {
+ log::info!(
+ "[thread_goals] injecting active_goal block status={} budget={:?} ({} chars)",
+ goal.status.as_str(),
+ goal.token_budget,
+ block.chars().count()
+ );
+ context.push_str(&block);
+ }
+ }
+
+ // ── Active sub-agents (ambient fleet awareness) ──────────────────────
+ // When this agent has async/parallel workers registered under its own
+ // session, prepend a compact `[active_subagents]` roster (agent type,
+ // subagent_session_id, live status) so it tracks the fleet from the turn
+ // context instead of relying on remembered `[async_subagent_ref]` blocks
+ // that may have scrolled away. Children register under the parent's
+ // `session_id`, which is this agent's `event_session_id` (see
+ // `build_parent_execution_context`). Gated on presence: agents that never
+ // spawn get an empty block and no injection. Rides per-turn context (like
+ // the goal block) so status is always live.
+ if let Some(block) =
+ crate::openhuman::agent::orchestration::running_subagents::active_subagents_context_block(
+ &self.event_session_id,
+ &self.workspace_dir,
+ )
+ {
+ log::info!(
+ "[running_subagents] injecting active_subagents block session={} ({} chars)",
+ self.event_session_id,
+ block.chars().count()
+ );
+ context.push_str(&block);
+ }
+
+ let enriched = if context.is_empty() {
+ log::info!("[agent] no memory context found — using raw user message");
+ self.last_memory_context = None;
+ user_message.to_string()
+ } else {
+ log::info!(
+ "[agent] memory context loaded — enriching user message context_chars={}",
+ context.chars().count()
+ );
+ self.last_memory_context = Some(context.clone());
+ format!("{context}{user_message}")
+ };
+
+ let enriched = self
+ .inject_agent_experience_context(user_message, enriched)
+ .await;
+
+ // ── SKILL.md body injection: REMOVED (was #781) ──────────────
+ // We used to keyword-match installed skills against the user message
+ // and prepend their full SKILL.md bodies onto the user turn. That
+ // brittle name/description/tag match fired unintentionally and — by
+ // baking the body into the stored user message — left full skill text
+ // permanently in chat history (microcompact only clears tool results,
+ // not user messages).
+ //
+ // Skills are now surfaced via the compact `## Installed Skills`
+ // catalog in the orchestrator prompt and executed via `run_skill`,
+ // which loads and follows the SKILL.md inside an isolated worker, so
+ // the full body never enters this conversation. `self.workflows` still
+ // feeds the catalog through `PromptContext`.
+
+ // Consume any one-shot mid-session connect announcement parked by
+ // `refresh_delegation_tools_from_cached_integrations`. It rides on the
+ // user turn (NOT a system message — `trim_history` hoists system
+ // messages to the front and would bust the KV-cache prefix) and
+ // `.take()` clears it so it fires exactly once.
+ let pending_slugs = std::mem::take(&mut self.pending_integration_announcement);
+ let enriched = match integration_announcement_note(&pending_slugs) {
+ Some(note) => format!("{note}\n\n{enriched}"),
+ None => enriched,
+ };
+
+ // Same one-shot treatment for MCP servers connected mid-session
+ // (queued above). `.take()` clears it so it fires exactly once.
+ let pending_mcp = std::mem::take(&mut self.pending_mcp_announcement);
+ let enriched = match mcp_announcement_note(&pending_mcp) {
+ Some(note) => format!("{note}\n\n{enriched}"),
+ None => enriched,
+ };
+
+ // Same one-shot pattern for skills installed mid-session (parked by
+ // `refresh_workflows` above). Rides the user turn so the KV-cache
+ // prefix stays stable; `.take()` fires it exactly once.
+ let pending_skills = std::mem::take(&mut self.pending_skill_announcement);
+ let enriched = match skill_announcement_note(&pending_skills) {
+ Some(note) => format!("{note}\n\n{enriched}"),
+ None => enriched,
+ };
+
+ // Same one-shot treatment for skills uninstalled mid-session (parked by
+ // `refresh_workflows`). The model must know the skill is gone so it does
+ // not attempt `run_skill` on a removed entry. Rides the user turn for
+ // the same KV-cache reason as the install note above.
+ let pending_retracted = std::mem::take(&mut self.pending_skill_retraction);
+ let enriched = match skill_retraction_note(&pending_retracted) {
+ Some(note) => format!("{note}\n\n{enriched}"),
+ None => enriched,
+ };
+
+ // Pin the main agent to its configured model for the lifetime of
+ // the session. Per-turn classification used to run here, but it
+ // would flip `effective_model` mid-conversation (e.g. reasoning →
+ // coding based on a single keyword). Every flip invalidates the
+ // backend's KV cache namespace for this session, costing full
+ // re-prefill on the very next turn. The main agent's job is to
+ // decide *which sub-agent* to spawn — that routing lives in the
+ // model prompt, not in the Rust-side classifier. Sub-agents pick
+ // their own tier via `ModelSpec::Hint(...)` in their definition.
+ let effective_model = self.model_name.clone();
+ log::info!(
+ "[agent_loop] model pinned model={} (per-turn classification disabled for KV cache stability)",
+ effective_model
+ );
+
+ // Snapshot the parent's runtime once per turn so any
+ // `spawn_subagent` invocation that fires inside this turn can
+ // read it via the PARENT_CONTEXT task-local. We override the
+ // model field with the post-classification effective model.
+ let mut parent_context = self.build_parent_execution_context();
+ parent_context.model_name = effective_model.clone();
+ let session_memory_parent_context = parent_context.clone();
+
+ let mut agent_context_prepared_sources: Vec<harness::AgentContextPreparedSource> =
+ Vec::new();
+ // Triggered memory-agent recall runs on EVERY channel, voice included:
+ // dropping it on voice would strip the user's remembered context
+ // (preferences, people, prior facts) from spoken answers — a real quality
+ // loss the transcript alone can't replace. Recall adds a few seconds of
+ // embedding + retrieval before the first model token, but on realtime
+ // voice that latency is already covered end-to-end: the backend relay
+ // streams an audible keepalive filler from t=0 so the cloud session never
+ // sees a silent stall, and the desktop's ~8s ack-defer closes the spoken
+ // turn and finishes in the background if the work runs long. So the recall
+ // path is byte-for-byte identical across voice and chat.
+ let (enriched, memory_agent_context_injected) = self
+ .inject_triggered_memory_agent_context(
+ user_message,
+ enriched,
+ &parent_context,
+ turn_overrides.suppress_memory_agent,
+ )
+ .await;
+ if memory_agent_context_injected {
+ agent_context_prepared_sources.push(harness::AgentContextPreparedSource {
+ source: "memory agent context retrieval".to_string(),
+ has_enough_context: None,
+ });
+ }
+
+ let enriched = if agent_context_prepared_sources.is_empty() {
+ enriched
+ } else {
+ log::debug!(
+ "[agent_loop] agent context already prepared sources={:?}",
+ agent_context_prepared_sources
+ );
+ format!(
+ "{}\n\n{enriched}",
+ render_agent_context_status_note(&agent_context_prepared_sources)
+ )
+ };
+
+ // #3602: stamp every turn's user message with the live local time
+ // so time-relative phrasing (greetings, "today"/"tonight") is
+ // grounded on the real clock. Rides the user message — not the
+ // frozen system-prompt prefix (see core.rs KV-cache note above) — so
+ // it stays fresh across a long-lived session without busting the
+ // cached prefix. This path runs for every `turn()` caller, including
+ // one-shot `run_single` flows (cron/morning-briefing/meet), so those
+ // get a fresh stamp too. The grounding *rule* lives in the system
+ // prompt's `## Current Date & Time` section.
+ let enriched = format!(
+ "{}\n\n{enriched}",
+ crate::openhuman::agent::prompts::current_datetime_line()
+ );
+
+ self.history
+ .push(ConversationMessage::Chat(ChatMessage::user(enriched)));
+
+ // Bump the session-memory turn counter. Used later by
+ // `should_extract_session_memory` to decide whether to spawn a
+ // background archivist fork at end-of-turn.
+ self.context.tick_turn();
+
+ let turn_body = async {
+ // Keep the scalar turn settings outside the pinned future arguments;
+ // the TinyAgents session path reads provider/tool/multimodal state
+ // directly from `self` when preparing the request.
+ let temperature = self.temperature;
+ let max_iterations = self.config.max_tool_iterations;
+ let artifact_store = Some(
+ crate::openhuman::agent::harness::tool_result_artifacts::ToolResultArtifactStore::new(
+ self.action_dir.clone(),
+ self.session_key.clone(),
+ ),
+ );
+ // The whole turn runs through the tinyagents harness (issue #4249);
+ // the legacy `run_turn_engine` has been removed. Heap-allocate the
+ // (large) session-turn future so it isn't held inline on `turn()`'s
+ // already-large frame — `run_single` and the cron wrappers nest more
+ // layers on top, which would otherwise overflow the stack.
+ Box::pin(self.run_turn_via_tinyagents_session(
+ user_message,
+ &effective_model,
+ temperature,
+ max_iterations,
+ artifact_store,
+ turn_overrides.suppress_tools,
+ ))
+ .await
+ }; // end of `turn_body` async block
+
+ // Run the turn body inside the parent-execution-context scope so
+ // that any `spawn_subagent` tool call fired during the loop can
+ // read the parent's provider, tools, model, and workspace via
+ // the PARENT_CONTEXT task-local.
+ // Arm the thread-goal budget stop hook for this turn when an active,
+ // budgeted goal exists — it votes to stop the loop as soon as running
+ // usage would exceed the cap. #4469 item 1: the stop is a graceful pause
+ // drained at the next iteration boundary, not an instantaneous abort, so
+ // the current tool round + one wrap-up summary call can still run past the
+ // cap (a small, bounded overshoot) before the partial transcript returns.
+ // Merge with any ambient stop hooks rather than clobbering them. No
+ // budgeted active goal → no extra hook, no wrap.
+ let mut turn_stop_hooks = crate::openhuman::agent::stop_hooks::current_stop_hooks();
+ if let Some(ref goal) = active_goal {
+ if let Some(hook) =
+ crate::openhuman::threads::goals::runtime::GoalBudgetStopHook::for_goal(
+ &goal_workspace_dir,
+ goal,
+ )
+ {
+ turn_stop_hooks.push(std::sync::Arc::new(hook));
+ }
+ }
+ // Surface this turn's image-attachment placeholders so a delegation to a
+ // vision sub-agent (which reads `current_turn_image_placeholders()` in
+ // `agent_orchestration::tools::dispatch`) can forward the user's attached
+ // image — the orchestrator itself keeps it as a text placeholder. Scoped
+ // around the harness turn (the delegating tool fires inside it).
+ let image_placeholders =
+ crate::openhuman::agent::multimodal::extract_image_placeholders_in_text(user_message);
+ let result = if turn_stop_hooks.is_empty() {
+ harness::with_parent_context(
+ parent_context,
+ harness::with_agent_context_prepared_sources(
+ agent_context_prepared_sources.clone(),
+ harness::turn_attachments_context::with_current_turn_image_placeholders(
+ image_placeholders,
+ turn_body,
+ ),
+ ),
+ )
+ .await
+ } else {
+ harness::with_parent_context(
+ parent_context,
+ harness::with_agent_context_prepared_sources(
+ agent_context_prepared_sources.clone(),
+ harness::turn_attachments_context::with_current_turn_image_placeholders(
+ image_placeholders,
+ crate::openhuman::agent::stop_hooks::with_stop_hooks(
+ turn_stop_hooks,
+ turn_body,
+ ),
+ ),
+ ),
+ )
+ .await
+ };
+
+ // Session transcript persistence lives INSIDE the turn body —
+ // one write per provider response, fired right after the
+ // response lands (see the tool-call and terminal branches in
+ // `turn_body`). A crash during tool execution no longer drops
+ // the assistant's reply because it was already flushed to
+ // disk before tool dispatch started. No outer-loop save is
+ // needed here.
+
+ // ── Session-memory extraction (stage 5) ───────────────────────
+ //
+ // If the pipeline's deltas have crossed all three thresholds
+ // (token growth, tool calls, turn count), spawn a *background*
+ // archivist sub-agent that will distil durable facts into the
+ // workspace MEMORY.md file via the `update_memory_md` tool.
+ //
+ // The spawn is fire-and-forget: the main turn returns the
+ // user-visible response immediately, and the archivist runs
+ // asynchronously on the `agentic` tier. We optimistically mark
+ // the extraction complete right away — if it actually fails,
+ // we'll just retry on the next threshold window (a few turns
+ // later), which is the right amount of retry behaviour for a
+ // librarian task that's idempotent across reruns.
+ if result.is_ok() && self.context.should_extract_session_memory() {
+ self.spawn_session_memory_extraction(session_memory_parent_context)
+ .await;
+ // Sibling pipeline (#1399): heuristic transcript ingestion
+ // turns the just-written transcript into durable
+ // conversational memory + reflections so a brand-new chat
+ // can recover continuity. Background-only, never blocks the
+ // user-facing turn return.
+ self.spawn_transcript_ingestion();
+ }
+
+ result
+ }
+}
diff --git a/src/openhuman/agent/orchestration/tools/spawn_async_subagent.rs b/src/openhuman/agent/orchestration/tools/spawn_async_subagent.rs
index 923d3eb2a7..fbc0fdbf77 100644
--- a/src/openhuman/agent/orchestration/tools/spawn_async_subagent.rs
+++ b/src/openhuman/agent/orchestration/tools/spawn_async_subagent.rs
@@ -114,743 +114,16 @@ impl Tool for SpawnAsyncSubagentTool {
async fn execute_with_context(
&self,
args: serde_json::Value,
- _options: ToolCallOptions,
+ options: ToolCallOptions,
tool_context: Option<&dyn ToolRunContext>,
) -> anyhow::Result<ToolResult> {
- let agent_id = args
- .get("agent_id")
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .trim()
- .to_string();
- let prompt = args
- .get("prompt")
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .trim()
- .to_string();
- let context = args
- .get("context")
- .and_then(|v| v.as_str())
- .map(str::to_string);
- let model_override = args
- .get("model")
- .and_then(|v| v.as_str())
- .map(|s| s.trim().to_string())
- .filter(|s| !s.is_empty());
- let toolkit_override = args
- .get("toolkit")
- .and_then(|v| v.as_str())
- .map(|s| s.trim().to_string())
- .filter(|s| !s.is_empty());
- let task_title = args
- .get("task_title")
- .and_then(|v| v.as_str())
- .map(str::trim)
- .filter(|s| !s.is_empty())
- .unwrap_or("Background subagent")
- .to_string();
- let task_key_source = durable_task_key_source(&args, &prompt, context.as_deref());
- let task_key = subagent_sessions::normalize_task_key(&task_key_source);
- let force_fresh = args.get("fresh").and_then(|v| v.as_bool()).unwrap_or(false);
-
- if agent_id.is_empty() {
- return Ok(ToolResult::error(
- "spawn_async_subagent: `agent_id` is required",
- ));
- }
- if prompt.is_empty() {
- return Ok(ToolResult::error(
- "spawn_async_subagent: `prompt` is required",
- ));
- }
-
- let parent = match current_parent() {
- Some(parent) => parent,
- None => {
- return Ok(ToolResult::error(
- "spawn_async_subagent called outside of an agent turn",
- ));
- }
- };
-
- let registry = match AgentDefinitionRegistry::global() {
- Some(registry) => registry,
- None => {
- return Ok(ToolResult::error(
- "spawn_async_subagent: AgentDefinitionRegistry has not been initialised",
- ));
- }
- };
- let definition = match registry.get(&agent_id).cloned() {
- Some(definition) => definition,
- None => {
- let available: Vec<&str> = registry.list().iter().map(|d| d.id.as_str()).collect();
- return Ok(ToolResult::error(format!(
- "spawn_async_subagent: unknown agent_id '{agent_id}'. Available: {}",
- available.join(", ")
- )));
- }
- };
-
- if !parent.allowed_subagent_ids.contains(&definition.id) {
- log::warn!(
- "[spawn_async_subagent] blocked subagent outside allowlist parent={} requested={} allowed={:?}",
- parent.agent_definition_id,
- definition.id,
- parent.allowed_subagent_ids
- );
- return Ok(ToolResult::error(format!(
- "spawn_async_subagent: agent '{}' is not in parent agent '{}' subagents.allowlist",
- definition.id, parent.agent_definition_id
- )));
- }
-
- if definition.id == "integrations_agent" && toolkit_override.is_none() {
- return Ok(ToolResult::error(
- "spawn_async_subagent(integrations_agent): the `toolkit` argument is required",
- ));
- }
-
- let parent_session = parent.session_id.clone();
- let progress_sink = parent.on_progress.clone();
- let parent_thread_id =
- crate::openhuman::agent::tinyagents::thread_context::current_thread_id();
-
- // Async delivery is thread-addressed: the finished result is inserted
- // back into the parent chat thread as a follow-up turn
- // (`background_delivery`). Outside a chat turn (flow `agent` nodes,
- // CLI, cron) there is no `current_thread_id()` to deliver into, so
- // `background_delivery::deliver_batch` logs "dropping headless batch"
- // and the (possibly real, completed) work is silently discarded — the
- // caller sees "Accepted" and never learns the result never arrived.
- // Fail loudly instead: the caller has a synchronous alternative
- // (`spawn_subagent` with `blocking: true`, or a `delegate_*` tool).
- // Both of those self-heal to blocking dispatch in this situation
- // rather than reaching this guard — see the `has_delivery_thread`
- // checks in `spawn_subagent.rs` and `dispatch.rs::dispatch_subagent`.
- // Only a *direct* `spawn_async_subagent` call lands here.
- if parent_thread_id.is_none() {
- log::warn!(
- "[spawn_async_subagent] refusing fire-and-forget spawn with no delivery thread \
- parent={} requested={} — directing caller to synchronous delegation (flow node / \
- CLI / cron context, background result would be discarded)",
- parent.agent_definition_id,
- definition.id
- );
- return Ok(ToolResult::error(
- "spawn_async_subagent: no parent chat thread available to deliver the result \
- into (this looks like a flow node, CLI, or cron run rather than an interactive \
- chat turn). Fire-and-forget delegation has nowhere to land its result here and \
- the sub-agent's work would be silently discarded. Use synchronous delegation \
- instead: call `spawn_subagent` with `blocking: true`, or use a `delegate_*` \
- tool — both run the sub-agent inline and hand you its output in this turn. \
- For parallel work, model it as parallel flow nodes rather than background \
- sub-agents.",
- ));
- }
- let store = SubagentSessionStore::new(parent.workspace_dir.clone());
- let workspace_descriptor = tool_context.and_then(|ctx| ctx.workspace().cloned());
- let effective_action_root = workspace_descriptor
- .as_ref()
- .map(|workspace| {
- tracing::debug!(
- workspace_root = %workspace.root.display(),
- policy_id = %workspace.policy_id,
- "[spawn_async_subagent] using ToolExecutionContext workspace root"
- );
- workspace.root.clone()
- })
- .or_else(|| {
- crate::openhuman::security::live_policy::current()
- .map(|policy| policy.action_dir.clone())
- });
- let selector = SubagentSessionSelector {
- parent_session: parent_session.clone(),
- parent_thread_id: parent_thread_id.clone(),
- agent_id: definition.id.clone(),
- toolkit: toolkit_override.clone(),
- model: model_override.clone(),
- sandbox_mode: format!("{:?}", definition.sandbox_mode),
- action_root: subagent_sessions::action_root_key(effective_action_root.as_deref()),
- task_key: task_key.clone(),
- };
-
- let reusable = if force_fresh {
- match subagent_sessions::find_reusable(&store, &selector) {
- Ok(Some(session)) => {
- let _ = running_subagents::cancel_by_session_in_workspace(
- &session.subagent_session_id,
- &parent_session,
- &parent.workspace_dir,
- );
- if let Err(err) = subagent_sessions::close(&store, &session.subagent_session_id)
- {
- log::warn!(
- "[subagent_reuse] fresh close failed parent_thread_id={} subagent_session_id={} agent_id={} task_key={} error={}",
- parent_thread_id.as_deref().unwrap_or("none"),
- session.subagent_session_id,
- definition.id,
- task_key,
- err
- );
- }
- }
- Ok(None) => {}
- Err(err) => {
- log::warn!(
- "[subagent_reuse] fresh lookup failed parent_thread_id={} agent_id={} task_key={} error={}",
- parent_thread_id.as_deref().unwrap_or("none"),
- definition.id,
- task_key,
- err
- );
- }
- }
- None
- } else {
- match subagent_sessions::find_reusable(&store, &selector) {
- Ok(session) => session,
- Err(err) => {
- log::warn!(
- "[subagent_reuse] lookup failed parent_thread_id={} agent_id={} task_key={} error={}",
- parent_thread_id.as_deref().unwrap_or("none"),
- definition.id,
- task_key,
- err
- );
- None
- }
- }
- };
- let reuse_decision = subagent_sessions::reuse_decision(reusable.as_ref(), force_fresh);
- let follow_up_prompt = reusable_follow_up_message(&prompt, context.as_deref());
-
- if let Some(session) = reusable.as_ref() {
- if session.status == DurableSubagentStatus::Running {
- if let Some(ref running_task_id) = session.current_task_id {
- match running_subagents::steer(
- running_task_id,
- &parent_session,
- follow_up_prompt.clone(),
- crate::openhuman::agent::harness::run_queue::QueueMode::Steer,
- )
- .await
- {
- Ok(()) => {
- log::info!(
- "[subagent_reuse] parent_thread_id={} subagent_session_id={} task_id={} agent_id={} reuse_decision={}",
- parent_thread_id.as_deref().unwrap_or("none"),
- session.subagent_session_id,
- running_task_id,
- definition.id,
- reuse_decision.as_str()
- );
- let payload = async_subagent_ref_payload(
- running_task_id,
- &session.subagent_session_id,
- &definition.id,
- session.worker_thread_id.as_deref(),
- true,
- reuse_decision.as_str(),
- "running",
- );
- return Ok(ToolResult::success(format!(
- "Continued reusable async sub-agent `{}`. It is already running and will pick up the new instruction at its next step. \
- Use the structured reference below to send more input, wait, or perform a short timeout tick.\n\n[async_subagent_ref]\n{}\n[/async_subagent_ref]",
- payload["agent_id"].as_str().unwrap_or("subagent"),
- serde_json::to_string(&payload).unwrap_or_else(|_| "{}".to_string())
- )));
- }
- Err(err) => {
- log::warn!(
- "[subagent_reuse] running steer failed parent_thread_id={} subagent_session_id={} task_id={} agent_id={} error={:?}",
- parent_thread_id.as_deref().unwrap_or("none"),
- session.subagent_session_id,
- running_task_id,
- definition.id,
- err
- );
- }
- }
- }
- }
- }
-
- let task_id = format!("sub-{}", uuid::Uuid::new_v4());
- let worker_thread_id = reusable
- .as_ref()
- .and_then(|session| session.worker_thread_id.clone())
- .or_else(|| {
- parent_thread_id.as_ref().and_then(|parent_thread_id| {
- super::worker_thread::create_worker_thread(
- parent.workspace_dir.clone(),
- parent_thread_id,
- &definition.id,
- &task_title,
- &prompt,
- )
- .ok()
- })
- });
- if let (Some(session), Some(worker_thread_id)) =
- (reusable.as_ref(), worker_thread_id.as_ref())
- {
- if session.worker_thread_id.as_deref() == Some(worker_thread_id.as_str()) {
- if let Err(err) = super::worker_thread::append_worker_user_message(
- parent.workspace_dir.clone(),
- worker_thread_id,
- &definition.id,
- &task_id,
- &follow_up_prompt,
- ) {
- log::warn!(
- "[subagent_reuse] worker follow-up append failed parent_thread_id={} subagent_session_id={} worker_thread_id={} task_id={} error={}",
- parent_thread_id.as_deref().unwrap_or("none"),
- session.subagent_session_id,
- worker_thread_id,
- task_id,
- err
- );
- }
- }
- }
- let durable_session = match subagent_sessions::upsert_running(
- &store,
- SubagentSessionUpsert {
- selector,
- display_name: Some(definition.display_name().to_string()),
- task_title: task_title.clone(),
- worker_thread_id: worker_thread_id.clone(),
- task_id: task_id.clone(),
- },
- reusable.as_ref(),
- ) {
- Ok(session) => session,
- Err(err) => {
- log::warn!(
- "[subagent_reuse] upsert failed parent_thread_id={} task_id={} agent_id={} reuse_decision={} error={}",
- parent_thread_id.as_deref().unwrap_or("none"),
- task_id,
- definition.id,
- reuse_decision.as_str(),
- err
- );
- return Ok(ToolResult::error(format!(
- "spawn_async_subagent: failed to persist reusable sub-agent session: {err}"
- )));
- }
- };
-
- let initial_history = reusable
- .as_ref()
- .and_then(|session| session.latest_history.clone())
- .map(|mut history| {
- history.push(ChatMessage::user(follow_up_prompt.clone()));
- history
- });
-
- log::info!(
- "[subagent_reuse] parent_thread_id={} subagent_session_id={} task_id={} agent_id={} reuse_decision={} task_key={}",
- parent_thread_id.as_deref().unwrap_or("none"),
- durable_session.subagent_session_id,
- task_id,
- definition.id,
- reuse_decision.as_str(),
- task_key
- );
-
- crate::openhuman::agent::orchestration::subagent_events::publish_subagent_spawned(
- parent_session.clone(),
- definition.id.clone(),
- "async".to_string(),
- task_id.clone(),
- prompt.chars().count(),
- );
- if let Some(ref tx) = progress_sink {
- let _ = tx
- .send(AgentProgress::SubagentSpawned {
- agent_id: definition.id.clone(),
- task_id: task_id.clone(),
- mode: "async".to_string(),
- dedicated_thread: worker_thread_id.is_some(),
- prompt_chars: prompt.chars().count(),
- prompt: prompt.clone(),
- worker_thread_id: worker_thread_id.clone(),
- display_name: Some(definition.display_name().to_string()),
- })
- .await;
- }
-
- // Steering channel + status channel so the parent can `steer_subagent`
- // this run mid-flight and `wait_subagent` for its result. The engine
- // drains `steer_queue` at iteration boundaries; `status_tx` publishes
- // the terminal state to any waiter.
- let steer_queue = RunQueue::new();
- let task_queue = steer_queue.clone();
- let (status_tx, status_rx) = running_subagents::status_channel();
-
- let background_parent = parent.clone();
- let background_workspace_dir = parent.workspace_dir.clone();
- let background_definition = definition.clone();
- let background_agent_id = definition.id.clone();
- let background_task_id = task_id.clone();
- let background_parent_session = parent_session.clone();
- let background_progress = progress_sink.clone();
- let background_worker_thread_id = worker_thread_id.clone();
- let background_store = store.clone();
- let background_subagent_session_id = durable_session.subagent_session_id.clone();
- let background_workspace_descriptor = workspace_descriptor.clone();
- let background_worktree_action_dir = background_workspace_descriptor
- .as_ref()
- .map(|descriptor| descriptor.root.clone());
- let background_thread_affinity_id = background_worker_thread_id
- .clone()
- .unwrap_or_else(|| background_subagent_session_id.clone());
- let background_initial_history = initial_history;
- // Capture the parent chat thread NOW (the spawning turn's thread) so the
- // finished result can be delivered back into it as a system turn.
- let background_parent_thread_id = parent_thread_id.clone();
- // Kept on this side (the closure moves its own clone) so the registry
- // entry knows which parent thread owns this sub-agent — that's how
- // `cancel_for_thread` aborts it when the thread is deleted.
- let register_parent_thread_id = background_parent_thread_id.clone();
- // Lifecycle-critical wiring: log the parent-thread binding so the
- // thread-close cancellation path (`cancel_for_thread`) is grep-friendly.
- log::debug!(
- "[spawn_async_subagent] register task_id={} parent_session={} parent_thread_id={}",
- task_id,
- parent_session,
- register_parent_thread_id.as_deref().unwrap_or("none")
- );
- let background_prompt = add_background_contract(&prompt);
- // The detached child starts on a fresh task, and a `tokio::task_local`
- // does not cross `tokio::spawn`. The parent's execution context and
- // chat thread are already re-installed inside the task for exactly that
- // reason; the turn's origin label and its workspace root are the other
- // two that have to travel, and they are captured **here**, on the
- // spawning task, rather than inside the closure where they would
- // already be gone. Without the origin every external-effect tool the
- // child calls reaches the approval gate unlabelled and is refused,
- // which is the whole of why a delegated coding task could not run a
- // shell.
- let join = tokio::spawn(crate::openhuman::agent::turn_origin::propagate(
- crate::openhuman::agent::turn_workspace::propagate(async move {
- let options = SubagentRunOptions {
- skill_filter_override: None,
- toolkit_override,
- context,
- model_override,
- task_id: Some(background_task_id.clone()),
- worker_thread_id: background_worker_thread_id.clone(),
- initial_history: background_initial_history,
- checkpoint_dir: None,
- worktree_action_dir: background_worktree_action_dir,
- workspace_descriptor: background_workspace_descriptor,
- run_queue: Some(task_queue),
- };
-
- let result = with_parent_context(background_parent, async move {
- crate::openhuman::agent::tinyagents::thread_context::with_thread_id(
- background_thread_affinity_id,
- async move {
- run_subagent(&background_definition, &background_prompt, options).await
- },
- )
- .await
- })
- .await;
-
- match result {
- Ok(outcome) => match outcome.status {
- SubagentRunStatus::Completed => {
- if let Err(err) = subagent_sessions::mark_finished(
- &background_store,
- &background_subagent_session_id,
- &outcome.task_id,
- &outcome.status,
- outcome.final_history.clone(),
- ) {
- log::warn!(
- "[subagent_reuse] mark_completed failed subagent_session_id={} task_id={} agent_id={} error={}",
- background_subagent_session_id,
- outcome.task_id,
- outcome.agent_id,
- err
- );
- }
- let _ = status_tx.send(SubagentStatus::Completed {
- output: outcome.output.clone(),
- iterations: outcome.iterations,
- });
- // A workflow proposal produced inside the child's tool
- // history is durable state, not prose: persist it into
- // the parent chat thread (survives reload / reconnect —
- // the old socket-only delivery could silently drop it)
- // and carry the full payload in the delivery notice so
- // the follow-up turn can present it faithfully.
- let delivery_summary = attach_workflow_proposal(
- &background_workspace_dir,
- background_parent_thread_id.as_deref(),
- &outcome.task_id,
- &outcome.agent_id,
- &outcome.final_history,
- outcome.output.clone(),
- );
- // Queue the finished result for idle-gated, batched
- // delivery back into the parent chat (the session
- // runtime drains this when the session is next idle).
- crate::openhuman::agent::orchestration::background_completions::record_completion(
- background_parent_session.clone(),
- outcome.task_id.clone(),
- outcome.agent_id.clone(),
- delivery_summary,
- background_parent_thread_id.clone(),
- );
- crate::openhuman::agent::orchestration::subagent_events::publish_subagent_completed(
- background_parent_session,
- outcome.task_id.clone(),
- outcome.agent_id.clone(),
- outcome.elapsed.as_millis() as u64,
- outcome.output.chars().count(),
- outcome.iterations,
- );
- if let Some(ref tx) = background_progress {
- let _ = tx
- .send(AgentProgress::SubagentCompleted {
- agent_id: outcome.agent_id,
- task_id: outcome.task_id,
- elapsed_ms: outcome.elapsed.as_millis() as u64,
- iterations: outcome.iterations as u32,
- output_chars: outcome.output.chars().count(),
- output: outcome.output.clone(),
- worktree_path: None,
- changed_files: Vec::new(),
- dirty_status: None,
- })
- .await;
- }
- }
- SubagentRunStatus::Incomplete { ref reason } => {
- // Async sub-agent stopped short (stuck halt / iteration
- // cap). Mark the session finished and deliver the PARTIAL
- // progress back to the parent, framed so it is not
- // mistaken for a completed result (#4096).
- if let Err(err) = subagent_sessions::mark_finished(
- &background_store,
- &background_subagent_session_id,
- &outcome.task_id,
- &outcome.status,
- outcome.final_history.clone(),
- ) {
- log::warn!(
- "[subagent_reuse] mark_incomplete failed subagent_session_id={} task_id={} agent_id={} error={}",
- background_subagent_session_id,
- outcome.task_id,
- outcome.agent_id,
- err
- );
- }
- let framed = format!(
- "[SUBAGENT_INCOMPLETE] the sub-agent {reason} and did not finish. \
- Partial progress:\n{}",
- outcome.output
- );
- let _ = status_tx.send(SubagentStatus::Completed {
- output: framed.clone(),
- iterations: outcome.iterations,
- });
- // An incomplete run may still have produced a full
- // proposal before stalling — preserve it durably too.
- let framed = attach_workflow_proposal(
- &background_workspace_dir,
- background_parent_thread_id.as_deref(),
- &outcome.task_id,
- &outcome.agent_id,
- &outcome.final_history,
- framed,
- );
- crate::openhuman::agent::orchestration::background_completions::record_completion(
- background_parent_session.clone(),
- outcome.task_id.clone(),
- outcome.agent_id.clone(),
- framed,
- background_parent_thread_id.clone(),
- );
- crate::openhuman::agent::orchestration::subagent_events::publish_subagent_completed(
- background_parent_session,
- outcome.task_id.clone(),
- outcome.agent_id.clone(),
- outcome.elapsed.as_millis() as u64,
- outcome.output.chars().count(),
- outcome.iterations,
- );
- if let Some(ref tx) = background_progress {
- let _ = tx
- .send(AgentProgress::SubagentCompleted {
- agent_id: outcome.agent_id,
- task_id: outcome.task_id,
- elapsed_ms: outcome.elapsed.as_millis() as u64,
- iterations: outcome.iterations as u32,
- output_chars: outcome.output.chars().count(),
- output: outcome.output.clone(),
- worktree_path: None,
- changed_files: Vec::new(),
- dirty_status: None,
- })
- .await;
- }
- }
- SubagentRunStatus::AwaitingUser { ref question, .. } => {
- if let Err(err) = subagent_sessions::mark_finished(
- &background_store,
- &background_subagent_session_id,
- &outcome.task_id,
- &outcome.status,
- outcome.final_history.clone(),
- ) {
- log::warn!(
- "[subagent_reuse] mark_awaiting_user failed subagent_session_id={} task_id={} agent_id={} error={}",
- background_subagent_session_id,
- outcome.task_id,
- outcome.agent_id,
- err
- );
- }
- let _ = status_tx.send(SubagentStatus::AwaitingUser {
- question: question.clone(),
- });
- let error = format!(
- "async sub-agent requested user clarification and was not continued: {question}"
- );
- // #4896: a detached child that pauses for input won't
- // continue on its own — queue a framed notice so the
- // parent chat learns the delegated task needs input,
- // instead of finalizing silently on "Accepted". Rides the
- // same idle-gated background_delivery path as a success.
- crate::openhuman::agent::orchestration::background_completions::record_awaiting_input(
- background_parent_session.clone(),
- outcome.task_id.clone(),
- outcome.agent_id.clone(),
- question,
- background_parent_thread_id.clone(),
- );
- crate::openhuman::agent::orchestration::subagent_events::publish_subagent_failed(
- background_parent_session,
- outcome.task_id.clone(),
- outcome.agent_id.clone(),
- error.clone(),
- );
- if let Some(ref tx) = background_progress {
- let _ = tx
- .send(AgentProgress::SubagentFailed {
- agent_id: outcome.agent_id,
- task_id: outcome.task_id,
- error,
- })
- .await;
- }
- }
- },
- Err(err) => {
- let error = err.to_string();
- if let Err(store_err) = subagent_sessions::mark_failed(
- &background_store,
- &background_subagent_session_id,
- &background_task_id,
- error.clone(),
- ) {
- log::warn!(
- "[subagent_reuse] mark_failed failed subagent_session_id={} task_id={} agent_id={} error={}",
- background_subagent_session_id,
- background_task_id,
- background_agent_id,
- store_err
- );
- }
- let _ = status_tx.send(SubagentStatus::Failed {
- error: error.clone(),
- });
- // #4896: a detached child that errors previously only
- // published an event — nothing reached chat, so the parent
- // turn finalized on "Accepted" and the failure was lost.
- // Queue a framed failure notice so background_delivery
- // surfaces it as a follow-up chat turn.
- crate::openhuman::agent::orchestration::background_completions::record_failure(
- background_parent_session.clone(),
- background_task_id.clone(),
- background_agent_id.clone(),
- &error,
- background_parent_thread_id.clone(),
- );
- crate::openhuman::agent::orchestration::subagent_events::publish_subagent_failed(
- background_parent_session,
- background_task_id.clone(),
- background_agent_id.clone(),
- error.clone(),
- );
- if let Some(ref tx) = background_progress {
- let _ = tx
- .send(AgentProgress::SubagentFailed {
- agent_id: background_agent_id,
- task_id: background_task_id,
- error,
- })
- .await;
- }
- }
- }
- }),
- ));
-
- // Register *after* spawn so the AbortHandle is available. The task owns
- // `status_tx`; this side holds `status_rx` for `wait_subagent`.
- running_subagents::register(
- task_id.clone(),
- definition.id.clone(),
- parent_session.clone(),
- parent.session_parent_prefix.clone(),
- Some(durable_session.subagent_session_id.clone()),
- parent.workspace_dir.clone(),
- register_parent_thread_id,
- steer_queue,
- join.abort_handle(),
- status_rx,
- );
-
- let payload = async_subagent_ref_payload(
- &task_id,
- &durable_session.subagent_session_id,
- &definition.id,
- worker_thread_id.as_deref(),
- reusable.is_some(),
- reuse_decision.as_str(),
- "running",
- );
- let payload_json = match serde_json::to_string(&payload) {
- Ok(serialized) => {
- log::debug!(
- "[spawn_async_subagent] serialized async reference payload bytes={}",
- serialized.len()
- );
- serialized
- }
- Err(error) => {
- log::debug!(
- "[spawn_async_subagent] failed to serialize async reference payload: {}",
- error
- );
- "{}".to_string()
- }
- };
- log::debug!("[spawn_async_subagent] formatting accepted response");
- Ok(ToolResult::success(format_async_subagent_accepted(
- payload["agent_id"].as_str().unwrap_or("subagent"),
- &payload_json,
- )))
+ self.execute_with_context_inner(args, options, tool_context)
+ .await
}
}
+include!("spawn_async_subagent_execute.rs");
+
/// Format the user-facing acceptance text around a structured async sub-agent reference.
fn format_async_subagent_accepted(agent_id: &str, payload_json: &str) -> String {
format!(
diff --git a/src/openhuman/agent/orchestration/tools/spawn_async_subagent_execute.rs b/src/openhuman/agent/orchestration/tools/spawn_async_subagent_execute.rs
new file mode 100644
index 0000000000..f6e1cf83a2
--- /dev/null
+++ b/src/openhuman/agent/orchestration/tools/spawn_async_subagent_execute.rs
@@ -0,0 +1,740 @@
+impl SpawnAsyncSubagentTool {
+ async fn execute_with_context_inner(
+ &self,
+ args: serde_json::Value,
+ _options: ToolCallOptions,
+ tool_context: Option<&dyn ToolRunContext>,
+ ) -> anyhow::Result<ToolResult> {
+ let agent_id = args
+ .get("agent_id")
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .trim()
+ .to_string();
+ let prompt = args
+ .get("prompt")
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .trim()
+ .to_string();
+ let context = args
+ .get("context")
+ .and_then(|v| v.as_str())
+ .map(str::to_string);
+ let model_override = args
+ .get("model")
+ .and_then(|v| v.as_str())
+ .map(|s| s.trim().to_string())
+ .filter(|s| !s.is_empty());
+ let toolkit_override = args
+ .get("toolkit")
+ .and_then(|v| v.as_str())
+ .map(|s| s.trim().to_string())
+ .filter(|s| !s.is_empty());
+ let task_title = args
+ .get("task_title")
+ .and_then(|v| v.as_str())
+ .map(str::trim)
+ .filter(|s| !s.is_empty())
+ .unwrap_or("Background subagent")
+ .to_string();
+ let task_key_source = durable_task_key_source(&args, &prompt, context.as_deref());
+ let task_key = subagent_sessions::normalize_task_key(&task_key_source);
+ let force_fresh = args.get("fresh").and_then(|v| v.as_bool()).unwrap_or(false);
+
+ if agent_id.is_empty() {
+ return Ok(ToolResult::error(
+ "spawn_async_subagent: `agent_id` is required",
+ ));
+ }
+ if prompt.is_empty() {
+ return Ok(ToolResult::error(
+ "spawn_async_subagent: `prompt` is required",
+ ));
+ }
+
+ let parent = match current_parent() {
+ Some(parent) => parent,
+ None => {
+ return Ok(ToolResult::error(
+ "spawn_async_subagent called outside of an agent turn",
+ ));
+ }
+ };
+
+ let registry = match AgentDefinitionRegistry::global() {
+ Some(registry) => registry,
+ None => {
+ return Ok(ToolResult::error(
+ "spawn_async_subagent: AgentDefinitionRegistry has not been initialised",
+ ));
+ }
+ };
+ let definition = match registry.get(&agent_id).cloned() {
+ Some(definition) => definition,
+ None => {
+ let available: Vec<&str> = registry.list().iter().map(|d| d.id.as_str()).collect();
+ return Ok(ToolResult::error(format!(
+ "spawn_async_subagent: unknown agent_id '{agent_id}'. Available: {}",
+ available.join(", ")
+ )));
+ }
+ };
+
+ if !parent.allowed_subagent_ids.contains(&definition.id) {
+ log::warn!(
+ "[spawn_async_subagent] blocked subagent outside allowlist parent={} requested={} allowed={:?}",
+ parent.agent_definition_id,
+ definition.id,
+ parent.allowed_subagent_ids
+ );
+ return Ok(ToolResult::error(format!(
+ "spawn_async_subagent: agent '{}' is not in parent agent '{}' subagents.allowlist",
+ definition.id, parent.agent_definition_id
+ )));
+ }
+
+ if definition.id == "integrations_agent" && toolkit_override.is_none() {
+ return Ok(ToolResult::error(
+ "spawn_async_subagent(integrations_agent): the `toolkit` argument is required",
+ ));
+ }
+
+ let parent_session = parent.session_id.clone();
+ let progress_sink = parent.on_progress.clone();
+ let parent_thread_id =
+ crate::openhuman::agent::tinyagents::thread_context::current_thread_id();
+
+ // Async delivery is thread-addressed: the finished result is inserted
+ // back into the parent chat thread as a follow-up turn
+ // (`background_delivery`). Outside a chat turn (flow `agent` nodes,
+ // CLI, cron) there is no `current_thread_id()` to deliver into, so
+ // `background_delivery::deliver_batch` logs "dropping headless batch"
+ // and the (possibly real, completed) work is silently discarded — the
+ // caller sees "Accepted" and never learns the result never arrived.
+ // Fail loudly instead: the caller has a synchronous alternative
+ // (`spawn_subagent` with `blocking: true`, or a `delegate_*` tool).
+ // Both of those self-heal to blocking dispatch in this situation
+ // rather than reaching this guard — see the `has_delivery_thread`
+ // checks in `spawn_subagent.rs` and `dispatch.rs::dispatch_subagent`.
+ // Only a *direct* `spawn_async_subagent` call lands here.
+ if parent_thread_id.is_none() {
+ log::warn!(
+ "[spawn_async_subagent] refusing fire-and-forget spawn with no delivery thread \
+ parent={} requested={} — directing caller to synchronous delegation (flow node / \
+ CLI / cron context, background result would be discarded)",
+ parent.agent_definition_id,
+ definition.id
+ );
+ return Ok(ToolResult::error(
+ "spawn_async_subagent: no parent chat thread available to deliver the result \
+ into (this looks like a flow node, CLI, or cron run rather than an interactive \
+ chat turn). Fire-and-forget delegation has nowhere to land its result here and \
+ the sub-agent's work would be silently discarded. Use synchronous delegation \
+ instead: call `spawn_subagent` with `blocking: true`, or use a `delegate_*` \
+ tool — both run the sub-agent inline and hand you its output in this turn. \
+ For parallel work, model it as parallel flow nodes rather than background \
+ sub-agents.",
+ ));
+ }
+ let store = SubagentSessionStore::new(parent.workspace_dir.clone());
+ let workspace_descriptor = tool_context.and_then(|ctx| ctx.workspace().cloned());
+ let effective_action_root = workspace_descriptor
+ .as_ref()
+ .map(|workspace| {
+ tracing::debug!(
+ workspace_root = %workspace.root.display(),
+ policy_id = %workspace.policy_id,
+ "[spawn_async_subagent] using ToolExecutionContext workspace root"
+ );
+ workspace.root.clone()
+ })
+ .or_else(|| {
+ crate::openhuman::security::live_policy::current()
+ .map(|policy| policy.action_dir.clone())
+ });
+ let selector = SubagentSessionSelector {
+ parent_session: parent_session.clone(),
+ parent_thread_id: parent_thread_id.clone(),
+ agent_id: definition.id.clone(),
+ toolkit: toolkit_override.clone(),
+ model: model_override.clone(),
+ sandbox_mode: format!("{:?}", definition.sandbox_mode),
+ action_root: subagent_sessions::action_root_key(effective_action_root.as_deref()),
+ task_key: task_key.clone(),
+ };
+
+ let reusable = if force_fresh {
+ match subagent_sessions::find_reusable(&store, &selector) {
+ Ok(Some(session)) => {
+ let _ = running_subagents::cancel_by_session_in_workspace(
+ &session.subagent_session_id,
+ &parent_session,
+ &parent.workspace_dir,
+ );
+ if let Err(err) = subagent_sessions::close(&store, &session.subagent_session_id)
+ {
+ log::warn!(
+ "[subagent_reuse] fresh close failed parent_thread_id={} subagent_session_id={} agent_id={} task_key={} error={}",
+ parent_thread_id.as_deref().unwrap_or("none"),
+ session.subagent_session_id,
+ definition.id,
+ task_key,
+ err
+ );
+ }
+ }
+ Ok(None) => {}
+ Err(err) => {
+ log::warn!(
+ "[subagent_reuse] fresh lookup failed parent_thread_id={} agent_id={} task_key={} error={}",
+ parent_thread_id.as_deref().unwrap_or("none"),
+ definition.id,
+ task_key,
+ err
+ );
+ }
+ }
+ None
+ } else {
+ match subagent_sessions::find_reusable(&store, &selector) {
+ Ok(session) => session,
+ Err(err) => {
+ log::warn!(
+ "[subagent_reuse] lookup failed parent_thread_id={} agent_id={} task_key={} error={}",
+ parent_thread_id.as_deref().unwrap_or("none"),
+ definition.id,
+ task_key,
+ err
+ );
+ None
+ }
+ }
+ };
+ let reuse_decision = subagent_sessions::reuse_decision(reusable.as_ref(), force_fresh);
+ let follow_up_prompt = reusable_follow_up_message(&prompt, context.as_deref());
+
+ if let Some(session) = reusable.as_ref() {
+ if session.status == DurableSubagentStatus::Running {
+ if let Some(ref running_task_id) = session.current_task_id {
+ match running_subagents::steer(
+ running_task_id,
+ &parent_session,
+ follow_up_prompt.clone(),
+ crate::openhuman::agent::harness::run_queue::QueueMode::Steer,
+ )
+ .await
+ {
+ Ok(()) => {
+ log::info!(
+ "[subagent_reuse] parent_thread_id={} subagent_session_id={} task_id={} agent_id={} reuse_decision={}",
+ parent_thread_id.as_deref().unwrap_or("none"),
+ session.subagent_session_id,
+ running_task_id,
+ definition.id,
+ reuse_decision.as_str()
+ );
+ let payload = async_subagent_ref_payload(
+ running_task_id,
+ &session.subagent_session_id,
+ &definition.id,
+ session.worker_thread_id.as_deref(),
+ true,
+ reuse_decision.as_str(),
+ "running",
+ );
+ return Ok(ToolResult::success(format!(
+ "Continued reusable async sub-agent `{}`. It is already running and will pick up the new instruction at its next step. \
+ Use the structured reference below to send more input, wait, or perform a short timeout tick.\n\n[async_subagent_ref]\n{}\n[/async_subagent_ref]",
+ payload["agent_id"].as_str().unwrap_or("subagent"),
+ serde_json::to_string(&payload).unwrap_or_else(|_| "{}".to_string())
+ )));
+ }
+ Err(err) => {
+ log::warn!(
+ "[subagent_reuse] running steer failed parent_thread_id={} subagent_session_id={} task_id={} agent_id={} error={:?}",
+ parent_thread_id.as_deref().unwrap_or("none"),
+ session.subagent_session_id,
+ running_task_id,
+ definition.id,
+ err
+ );
+ }
+ }
+ }
+ }
+ }
+
+ let task_id = format!("sub-{}", uuid::Uuid::new_v4());
+ let worker_thread_id = reusable
+ .as_ref()
+ .and_then(|session| session.worker_thread_id.clone())
+ .or_else(|| {
+ parent_thread_id.as_ref().and_then(|parent_thread_id| {
+ super::worker_thread::create_worker_thread(
+ parent.workspace_dir.clone(),
+ parent_thread_id,
+ &definition.id,
+ &task_title,
+ &prompt,
+ )
+ .ok()
+ })
+ });
+ if let (Some(session), Some(worker_thread_id)) =
+ (reusable.as_ref(), worker_thread_id.as_ref())
+ {
+ if session.worker_thread_id.as_deref() == Some(worker_thread_id.as_str()) {
+ if let Err(err) = super::worker_thread::append_worker_user_message(
+ parent.workspace_dir.clone(),
+ worker_thread_id,
+ &definition.id,
+ &task_id,
+ &follow_up_prompt,
+ ) {
+ log::warn!(
+ "[subagent_reuse] worker follow-up append failed parent_thread_id={} subagent_session_id={} worker_thread_id={} task_id={} error={}",
+ parent_thread_id.as_deref().unwrap_or("none"),
+ session.subagent_session_id,
+ worker_thread_id,
+ task_id,
+ err
+ );
+ }
+ }
+ }
+ let durable_session = match subagent_sessions::upsert_running(
+ &store,
+ SubagentSessionUpsert {
+ selector,
+ display_name: Some(definition.display_name().to_string()),
+ task_title: task_title.clone(),
+ worker_thread_id: worker_thread_id.clone(),
+ task_id: task_id.clone(),
+ },
+ reusable.as_ref(),
+ ) {
+ Ok(session) => session,
+ Err(err) => {
+ log::warn!(
+ "[subagent_reuse] upsert failed parent_thread_id={} task_id={} agent_id={} reuse_decision={} error={}",
+ parent_thread_id.as_deref().unwrap_or("none"),
+ task_id,
+ definition.id,
+ reuse_decision.as_str(),
+ err
+ );
+ return Ok(ToolResult::error(format!(
+ "spawn_async_subagent: failed to persist reusable sub-agent session: {err}"
+ )));
+ }
+ };
+
+ let initial_history = reusable
+ .as_ref()
+ .and_then(|session| session.latest_history.clone())
+ .map(|mut history| {
+ history.push(ChatMessage::user(follow_up_prompt.clone()));
+ history
+ });
+
+ log::info!(
+ "[subagent_reuse] parent_thread_id={} subagent_session_id={} task_id={} agent_id={} reuse_decision={} task_key={}",
+ parent_thread_id.as_deref().unwrap_or("none"),
+ durable_session.subagent_session_id,
+ task_id,
+ definition.id,
+ reuse_decision.as_str(),
+ task_key
+ );
+
+ crate::openhuman::agent::orchestration::subagent_events::publish_subagent_spawned(
+ parent_session.clone(),
+ definition.id.clone(),
+ "async".to_string(),
+ task_id.clone(),
+ prompt.chars().count(),
+ );
+ if let Some(ref tx) = progress_sink {
+ let _ = tx
+ .send(AgentProgress::SubagentSpawned {
+ agent_id: definition.id.clone(),
+ task_id: task_id.clone(),
+ mode: "async".to_string(),
+ dedicated_thread: worker_thread_id.is_some(),
+ prompt_chars: prompt.chars().count(),
+ prompt: prompt.clone(),
+ worker_thread_id: worker_thread_id.clone(),
+ display_name: Some(definition.display_name().to_string()),
+ })
+ .await;
+ }
+
+ // Steering channel + status channel so the parent can `steer_subagent`
+ // this run mid-flight and `wait_subagent` for its result. The engine
+ // drains `steer_queue` at iteration boundaries; `status_tx` publishes
+ // the terminal state to any waiter.
+ let steer_queue = RunQueue::new();
+ let task_queue = steer_queue.clone();
+ let (status_tx, status_rx) = running_subagents::status_channel();
+
+ let background_parent = parent.clone();
+ let background_workspace_dir = parent.workspace_dir.clone();
+ let background_definition = definition.clone();
+ let background_agent_id = definition.id.clone();
+ let background_task_id = task_id.clone();
+ let background_parent_session = parent_session.clone();
+ let background_progress = progress_sink.clone();
+ let background_worker_thread_id = worker_thread_id.clone();
+ let background_store = store.clone();
+ let background_subagent_session_id = durable_session.subagent_session_id.clone();
+ let background_workspace_descriptor = workspace_descriptor.clone();
+ let background_worktree_action_dir = background_workspace_descriptor
+ .as_ref()
+ .map(|descriptor| descriptor.root.clone());
+ let background_thread_affinity_id = background_worker_thread_id
+ .clone()
+ .unwrap_or_else(|| background_subagent_session_id.clone());
+ let background_initial_history = initial_history;
+ // Capture the parent chat thread NOW (the spawning turn's thread) so the
+ // finished result can be delivered back into it as a system turn.
+ let background_parent_thread_id = parent_thread_id.clone();
+ // Kept on this side (the closure moves its own clone) so the registry
+ // entry knows which parent thread owns this sub-agent — that's how
+ // `cancel_for_thread` aborts it when the thread is deleted.
+ let register_parent_thread_id = background_parent_thread_id.clone();
+ // Lifecycle-critical wiring: log the parent-thread binding so the
+ // thread-close cancellation path (`cancel_for_thread`) is grep-friendly.
+ log::debug!(
+ "[spawn_async_subagent] register task_id={} parent_session={} parent_thread_id={}",
+ task_id,
+ parent_session,
+ register_parent_thread_id.as_deref().unwrap_or("none")
+ );
+ let background_prompt = add_background_contract(&prompt);
+ // The detached child starts on a fresh task, and a `tokio::task_local`
+ // does not cross `tokio::spawn`. The parent's execution context and
+ // chat thread are already re-installed inside the task for exactly that
+ // reason; the turn's origin label and its workspace root are the other
+ // two that have to travel, and they are captured **here**, on the
+ // spawning task, rather than inside the closure where they would
+ // already be gone. Without the origin every external-effect tool the
+ // child calls reaches the approval gate unlabelled and is refused,
+ // which is the whole of why a delegated coding task could not run a
+ // shell.
+ let join = tokio::spawn(crate::openhuman::agent::turn_origin::propagate(
+ crate::openhuman::agent::turn_workspace::propagate(async move {
+ let options = SubagentRunOptions {
+ skill_filter_override: None,
+ toolkit_override,
+ context,
+ model_override,
+ task_id: Some(background_task_id.clone()),
+ worker_thread_id: background_worker_thread_id.clone(),
+ initial_history: background_initial_history,
+ checkpoint_dir: None,
+ worktree_action_dir: background_worktree_action_dir,
+ workspace_descriptor: background_workspace_descriptor,
+ run_queue: Some(task_queue),
+ };
+
+ let result = with_parent_context(background_parent, async move {
+ crate::openhuman::agent::tinyagents::thread_context::with_thread_id(
+ background_thread_affinity_id,
+ async move {
+ run_subagent(&background_definition, &background_prompt, options).await
+ },
+ )
+ .await
+ })
+ .await;
+
+ match result {
+ Ok(outcome) => match outcome.status {
+ SubagentRunStatus::Completed => {
+ if let Err(err) = subagent_sessions::mark_finished(
+ &background_store,
+ &background_subagent_session_id,
+ &outcome.task_id,
+ &outcome.status,
+ outcome.final_history.clone(),
+ ) {
+ log::warn!(
+ "[subagent_reuse] mark_completed failed subagent_session_id={} task_id={} agent_id={} error={}",
+ background_subagent_session_id,
+ outcome.task_id,
+ outcome.agent_id,
+ err
+ );
+ }
+ let _ = status_tx.send(SubagentStatus::Completed {
+ output: outcome.output.clone(),
+ iterations: outcome.iterations,
+ });
+ // A workflow proposal produced inside the child's tool
+ // history is durable state, not prose: persist it into
+ // the parent chat thread (survives reload / reconnect —
+ // the old socket-only delivery could silently drop it)
+ // and carry the full payload in the delivery notice so
+ // the follow-up turn can present it faithfully.
+ let delivery_summary = attach_workflow_proposal(
+ &background_workspace_dir,
+ background_parent_thread_id.as_deref(),
+ &outcome.task_id,
+ &outcome.agent_id,
+ &outcome.final_history,
+ outcome.output.clone(),
+ );
+ // Queue the finished result for idle-gated, batched
+ // delivery back into the parent chat (the session
+ // runtime drains this when the session is next idle).
+ crate::openhuman::agent::orchestration::background_completions::record_completion(
+ background_parent_session.clone(),
+ outcome.task_id.clone(),
+ outcome.agent_id.clone(),
+ delivery_summary,
+ background_parent_thread_id.clone(),
+ );
+ crate::openhuman::agent::orchestration::subagent_events::publish_subagent_completed(
+ background_parent_session,
+ outcome.task_id.clone(),
+ outcome.agent_id.clone(),
+ outcome.elapsed.as_millis() as u64,
+ outcome.output.chars().count(),
+ outcome.iterations,
+ );
+ if let Some(ref tx) = background_progress {
+ let _ = tx
+ .send(AgentProgress::SubagentCompleted {
+ agent_id: outcome.agent_id,
+ task_id: outcome.task_id,
+ elapsed_ms: outcome.elapsed.as_millis() as u64,
+ iterations: outcome.iterations as u32,
+ output_chars: outcome.output.chars().count(),
+ output: outcome.output.clone(),
+ worktree_path: None,
+ changed_files: Vec::new(),
+ dirty_status: None,
+ })
+ .await;
+ }
+ }
+ SubagentRunStatus::Incomplete { ref reason } => {
+ // Async sub-agent stopped short (stuck halt / iteration
+ // cap). Mark the session finished and deliver the PARTIAL
+ // progress back to the parent, framed so it is not
+ // mistaken for a completed result (#4096).
+ if let Err(err) = subagent_sessions::mark_finished(
+ &background_store,
+ &background_subagent_session_id,
+ &outcome.task_id,
+ &outcome.status,
+ outcome.final_history.clone(),
+ ) {
+ log::warn!(
+ "[subagent_reuse] mark_incomplete failed subagent_session_id={} task_id={} agent_id={} error={}",
+ background_subagent_session_id,
+ outcome.task_id,
+ outcome.agent_id,
+ err
+ );
+ }
+ let framed = format!(
+ "[SUBAGENT_INCOMPLETE] the sub-agent {reason} and did not finish. \
+ Partial progress:\n{}",
+ outcome.output
+ );
+ let _ = status_tx.send(SubagentStatus::Completed {
+ output: framed.clone(),
+ iterations: outcome.iterations,
+ });
+ // An incomplete run may still have produced a full
+ // proposal before stalling — preserve it durably too.
+ let framed = attach_workflow_proposal(
+ &background_workspace_dir,
+ background_parent_thread_id.as_deref(),
+ &outcome.task_id,
+ &outcome.agent_id,
+ &outcome.final_history,
+ framed,
+ );
+ crate::openhuman::agent::orchestration::background_completions::record_completion(
+ background_parent_session.clone(),
+ outcome.task_id.clone(),
+ outcome.agent_id.clone(),
+ framed,
+ background_parent_thread_id.clone(),
+ );
+ crate::openhuman::agent::orchestration::subagent_events::publish_subagent_completed(
+ background_parent_session,
+ outcome.task_id.clone(),
+ outcome.agent_id.clone(),
+ outcome.elapsed.as_millis() as u64,
+ outcome.output.chars().count(),
+ outcome.iterations,
+ );
+ if let Some(ref tx) = background_progress {
+ let _ = tx
+ .send(AgentProgress::SubagentCompleted {
+ agent_id: outcome.agent_id,
+ task_id: outcome.task_id,
+ elapsed_ms: outcome.elapsed.as_millis() as u64,
+ iterations: outcome.iterations as u32,
+ output_chars: outcome.output.chars().count(),
+ output: outcome.output.clone(),
+ worktree_path: None,
+ changed_files: Vec::new(),
+ dirty_status: None,
+ })
+ .await;
+ }
+ }
+ SubagentRunStatus::AwaitingUser { ref question, .. } => {
+ if let Err(err) = subagent_sessions::mark_finished(
+ &background_store,
+ &background_subagent_session_id,
+ &outcome.task_id,
+ &outcome.status,
+ outcome.final_history.clone(),
+ ) {
+ log::warn!(
+ "[subagent_reuse] mark_awaiting_user failed subagent_session_id={} task_id={} agent_id={} error={}",
+ background_subagent_session_id,
+ outcome.task_id,
+ outcome.agent_id,
+ err
+ );
+ }
+ let _ = status_tx.send(SubagentStatus::AwaitingUser {
+ question: question.clone(),
+ });
+ let error = format!(
+ "async sub-agent requested user clarification and was not continued: {question}"
+ );
+ // #4896: a detached child that pauses for input won't
+ // continue on its own — queue a framed notice so the
+ // parent chat learns the delegated task needs input,
+ // instead of finalizing silently on "Accepted". Rides the
+ // same idle-gated background_delivery path as a success.
+ crate::openhuman::agent::orchestration::background_completions::record_awaiting_input(
+ background_parent_session.clone(),
+ outcome.task_id.clone(),
+ outcome.agent_id.clone(),
+ question,
+ background_parent_thread_id.clone(),
+ );
+ crate::openhuman::agent::orchestration::subagent_events::publish_subagent_failed(
+ background_parent_session,
+ outcome.task_id.clone(),
+ outcome.agent_id.clone(),
+ error.clone(),
+ );
+ if let Some(ref tx) = background_progress {
+ let _ = tx
+ .send(AgentProgress::SubagentFailed {
+ agent_id: outcome.agent_id,
+ task_id: outcome.task_id,
+ error,
+ })
+ .await;
+ }
+ }
+ },
+ Err(err) => {
+ let error = err.to_string();
+ if let Err(store_err) = subagent_sessions::mark_failed(
+ &background_store,
+ &background_subagent_session_id,
+ &background_task_id,
+ error.clone(),
+ ) {
+ log::warn!(
+ "[subagent_reuse] mark_failed failed subagent_session_id={} task_id={} agent_id={} error={}",
+ background_subagent_session_id,
+ background_task_id,
+ background_agent_id,
+ store_err
+ );
+ }
+ let _ = status_tx.send(SubagentStatus::Failed {
+ error: error.clone(),
+ });
+ // #4896: a detached child that errors previously only
+ // published an event — nothing reached chat, so the parent
+ // turn finalized on "Accepted" and the failure was lost.
+ // Queue a framed failure notice so background_delivery
+ // surfaces it as a follow-up chat turn.
+ crate::openhuman::agent::orchestration::background_completions::record_failure(
+ background_parent_session.clone(),
+ background_task_id.clone(),
+ background_agent_id.clone(),
+ &error,
+ background_parent_thread_id.clone(),
+ );
+ crate::openhuman::agent::orchestration::subagent_events::publish_subagent_failed(
+ background_parent_session,
+ background_task_id.clone(),
+ background_agent_id.clone(),
+ error.clone(),
+ );
+ if let Some(ref tx) = background_progress {
+ let _ = tx
+ .send(AgentProgress::SubagentFailed {
+ agent_id: background_agent_id,
+ task_id: background_task_id,
+ error,
+ })
+ .await;
+ }
+ }
+ }
+ }),
+ ));
+
+ // Register *after* spawn so the AbortHandle is available. The task owns
+ // `status_tx`; this side holds `status_rx` for `wait_subagent`.
+ running_subagents::register(
+ task_id.clone(),
+ definition.id.clone(),
+ parent_session.clone(),
+ parent.session_parent_prefix.clone(),
+ Some(durable_session.subagent_session_id.clone()),
+ parent.workspace_dir.clone(),
+ register_parent_thread_id,
+ steer_queue,
+ join.abort_handle(),
+ status_rx,
+ );
+
+ let payload = async_subagent_ref_payload(
+ &task_id,
+ &durable_session.subagent_session_id,
+ &definition.id,
+ worker_thread_id.as_deref(),
+ reusable.is_some(),
+ reuse_decision.as_str(),
+ "running",
+ );
+ let payload_json = match serde_json::to_string(&payload) {
+ Ok(serialized) => {
+ log::debug!(
+ "[spawn_async_subagent] serialized async reference payload bytes={}",
+ serialized.len()
+ );
+ serialized
+ }
+ Err(error) => {
+ log::debug!(
+ "[spawn_async_subagent] failed to serialize async reference payload: {}",
+ error
+ );
+ "{}".to_string()
+ }
+ };
+ log::debug!("[spawn_async_subagent] formatting accepted response");
+ Ok(ToolResult::success(format_async_subagent_accepted(
+ payload["agent_id"].as_str().unwrap_or("subagent"),
+ &payload_json,
+ )))
+ }
+}
diff --git a/src/openhuman/agent/orchestration/tools/spawn_subagent.rs b/src/openhuman/agent/orchestration/tools/spawn_subagent.rs
index 4a05157962..d1fcc1a532 100644
--- a/src/openhuman/agent/orchestration/tools/spawn_subagent.rs
+++ b/src/openhuman/agent/orchestration/tools/spawn_subagent.rs
@@ -67,700 +67,7 @@ impl SpawnSubagentTool {
}
}
-#[async_trait]
-impl Tool for SpawnSubagentTool {
-
- fn name(&self) -> &str {
- "spawn_subagent"
- }
-
- fn description(&self) -> &str {
- "Delegate a task to a specialised sub-agent only when direct \
- response or direct tools are insufficient. Handles ONE delegated task \
- per call: by default it runs as a reusable async worker and returns \
- immediately — pass `blocking: true` to run it inline and get the \
- sub-agent's final output back in this turn. To run several independent \
- workers at once (e.g. \"a separate researcher for each X\", a council \
- of opinions, or \"fan out over N items\"), use `spawn_parallel_agents` \
- with one task per worker — a SINGLE call that launches them \
- concurrently. Do NOT call this tool in a loop to fan out: repeated \
- `spawn_subagent` calls each delegate a single task and never launch \
- workers concurrently, which serializes the whole request. See the Delegation \
- Guide in the system prompt for available agent_ids and when to \
- use each. When delegating to `integrations_agent`, you MUST also pass \
- `toolkit=\"<name>\"` naming the Composio integration the \
- sub-task targets (e.g. `gmail`, `notion`); the sub-agent will \
- only see that toolkit's actions."
- }
-
- fn parameters_schema(&self) -> serde_json::Value {
- // Build the agent_id enum dynamically from the global registry
- // when it's been initialised. Falls back to a string-with-hint
- // when the registry hasn't been set up yet (e.g. early tests).
- let agent_ids: Vec<String> = AgentDefinitionRegistry::global()
- .map(|reg| reg.list().iter().map(|d| d.id.clone()).collect())
- .unwrap_or_default();
-
- let agent_id_schema = if agent_ids.is_empty() {
- json!({
- "type": "string",
- "description": "Sub-agent id (e.g. code_executor, researcher, critic)."
- })
- } else {
- json!({
- "type": "string",
- "enum": agent_ids,
- "description": "Sub-agent id from the registry."
- })
- };
-
- json!({
- "type": "object",
- "required": ["agent_id", "prompt"],
- "properties": {
- "agent_id": agent_id_schema,
- // Back-compat alias — older callers used `archetype`.
- "archetype": {
- "type": "string",
- "description": "Deprecated alias for `agent_id`. Use `agent_id` going forward."
- },
- "prompt": {
- "type": "string",
- "description": "Clear, specific instruction for the sub-agent. The sub-agent has no memory of the parent's conversation, so include all context the sub-agent needs to act."
- },
- "context": {
- "type": "string",
- "description": "Optional context blob from prior task results. Rendered as a `[Context]` block before the prompt."
- },
- "model": {
- "type": "string",
- "description": "Optional exact model id for this spawn only. Keeps the parent provider/routing, but pins the child agent to this model instead of the agent definition's default."
- },
- "toolkit": {
- "type": "string",
- "description": "Composio toolkit slug to scope this spawn to — e.g. `gmail`, `notion`, `slack`. REQUIRED when `agent_id = \"integrations_agent\"`. Narrows the sub-agent's visible Composio actions AND its Connected Integrations prompt section to only that toolkit's catalogue, so the sub-agent's context window only carries the platform it was asked to operate on. Must match a currently-connected integration (see the Delegation Guide)."
- },
- "dedicated_thread": {
- "type": "boolean",
- "description": "Legacy compatibility flag. Delegations now always create a persistent worker thread when parent context is available, so this flag no longer gates thread creation."
- },
- "blocking": {
- "type": "boolean",
- "description": "Explicitly run the sub-agent inline and return its final output. Defaults to false; reusable async delegation is the default."
- },
- "task_key": {
- "type": "string",
- "description": "Optional deterministic identity key for reusable async delegation. Defaults to a normalized prompt/title."
- },
- "fresh": {
- "type": "boolean",
- "description": "When true, bypass reusable subagent matching and create a fresh durable worker."
- }
- }
- })
- }
-
- fn permission_level(&self) -> PermissionLevel {
- PermissionLevel::Execute
- }
-
- async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {
- self.execute_with_context(args, ToolCallOptions::default(), None)
- .await
- }
-
- async fn execute_with_context(
- &self,
- args: serde_json::Value,
- _options: ToolCallOptions,
- tool_context: Option<&dyn ToolRunContext>,
- ) -> anyhow::Result<ToolResult> {
- // ── Argument extraction with back-compat ───────────────────────
- let agent_id = args
- .get("agent_id")
- .and_then(|v| v.as_str())
- .or_else(|| args.get("archetype").and_then(|v| v.as_str()))
- .unwrap_or("")
- .trim()
- .to_string();
-
- let prompt = args
- .get("prompt")
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .trim()
- .to_string();
-
- let context = args
- .get("context")
- .and_then(|v| v.as_str())
- .map(|s| s.to_string());
-
- let model_override = args
- .get("model")
- .and_then(|v| v.as_str())
- .map(|s| s.trim().to_string())
- .filter(|s| !s.is_empty());
-
- let toolkit_override = args
- .get("toolkit")
- .and_then(|v| v.as_str())
- .map(|s| s.trim().to_string())
- .filter(|s| !s.is_empty());
-
- // Worker threads are now always created for delegations that may
- // need follow-up (checkpoint + replay for ask_user_clarification).
- // The `dedicated_thread` parameter is accepted but no longer
- // gates thread creation — every delegation gets a persistent
- // worker thread. (#3049 supersedes the #1624 disable.)
- let dedicated_thread = args
- .get("dedicated_thread")
- .and_then(|v| v.as_bool())
- .unwrap_or(false);
- let blocking = args
- .get("blocking")
- .and_then(|v| v.as_bool())
- .unwrap_or(false);
-
- // ── Validation ─────────────────────────────────────────────────
- if agent_id.is_empty() {
- return Ok(ToolResult::error(
- "spawn_subagent: `agent_id` (or legacy `archetype`) is required",
- ));
- }
- if prompt.is_empty() {
- return Ok(ToolResult::error("spawn_subagent: `prompt` is required"));
- }
-
- let registry = match AgentDefinitionRegistry::global() {
- Some(reg) => reg,
- None => {
- return Ok(ToolResult::error(
- "spawn_subagent: AgentDefinitionRegistry has not been initialised. \
- This usually means the core process started without calling \
- AgentDefinitionRegistry::init_global at startup.",
- ));
- }
- };
-
- let definition = match registry.get(agent_id.as_str()) {
- Some(def) => def,
- None => {
- let available: Vec<&str> = registry.list().iter().map(|d| d.id.as_str()).collect();
- return Ok(ToolResult::error(format!(
- "spawn_subagent: unknown agent_id '{agent_id}'. Available: {}",
- available.join(", ")
- )));
- }
- };
-
- if let Some(parent_ctx) = current_parent() {
- if !parent_ctx.allowed_subagent_ids.contains(&definition.id) {
- log::warn!(
- "[spawn_subagent] blocked subagent outside parent allowlist parent_agent={} requested_agent={} allowed={:?}",
- parent_ctx.agent_definition_id,
- definition.id,
- parent_ctx.allowed_subagent_ids
- );
- return Ok(ToolResult::error(format!(
- "spawn_subagent: agent '{}' is not in parent agent '{}' subagents.allowlist",
- definition.id, parent_ctx.agent_definition_id
- )));
- }
- log::debug!(
- "[spawn_subagent] subagent allowlist check passed parent_agent={} requested_agent={}",
- parent_ctx.agent_definition_id,
- definition.id
- );
- }
-
- // ── integrations_agent toolkit gate ──────────────────────────────────
- // integrations_agent is a platform-parameterised specialist. Every
- // spawn MUST name a CONNECTED toolkit so the sub-agent only
- // sees one integration's tool catalogue instead of all of
- // them. We split validation into three cases so the model
- // gets a precise, actionable error on every failure mode —
- // nothing reaches the LLM loop unless the spawn is valid.
- if definition.id == "integrations_agent" {
- // The parent's `connected_integrations` Vec is frozen at
- // session-start (see `session/turn.rs::fetch_connected_integrations`),
- // so a toolkit the user authorised mid-thread isn't visible
- // here. Refresh from the global integrations cache —
- // invalidated by `ComposioConnectionCreatedSubscriber` once
- // OAuth reaches ACTIVE — so the pre-flight sees the latest
- // truth. Falls back to the parent's frozen list when the
- // live fetch returns empty (no signed-in user, backend
- // unreachable, …) so offline behaviour is unchanged.
- let parent_ctx = current_parent();
- let live_integrations: Vec<
- crate::openhuman::agent::context::prompt::ConnectedIntegration,
- > = {
- match crate::openhuman::config::Config::load_or_init().await {
- Ok(config) => {
- use crate::openhuman::integrations::composio::FetchConnectedIntegrationsStatus;
- // Use the status-discriminating fetch so we can
- // tell "user has zero active integrations" (truth
- // — adopt it) apart from "backend unavailable"
- // (preserve the parent's frozen snapshot so the
- // pre-flight doesn't reject every toolkit during
- // a transient 5xx).
- match crate::openhuman::integrations::composio::fetch_connected_integrations_status(
- &config,
- )
- .await
- {
- FetchConnectedIntegrationsStatus::Authoritative(fresh) => {
- tracing::debug!(
- target: "spawn_subagent",
- count = fresh.len(),
- "[spawn_subagent] refreshed connected_integrations for pre-flight"
- );
- fresh
- }
- FetchConnectedIntegrationsStatus::Unavailable => {
- tracing::debug!(
- target: "spawn_subagent",
- "[spawn_subagent] integrations backend unavailable; falling back to parent's frozen list"
- );
- parent_ctx
- .as_ref()
- .map(|p| p.connected_integrations.clone())
- .unwrap_or_default()
- }
- }
- }
- Err(e) => {
- tracing::debug!(
- target: "spawn_subagent",
- error = %e,
- "[spawn_subagent] config load failed; falling back to parent's frozen list"
- );
- parent_ctx
- .as_ref()
- .map(|p| p.connected_integrations.clone())
- .unwrap_or_default()
- }
- }
- };
- let allowlist: Vec<&crate::openhuman::agent::context::prompt::ConnectedIntegration> =
- live_integrations.iter().collect();
- let connected_slugs: Vec<String> = allowlist
- .iter()
- .filter(|ci| ci.connected)
- .map(|ci| ci.toolkit.clone())
- .collect();
-
- tracing::debug!(
- target: "spawn_subagent",
- toolkit = ?toolkit_override,
- allowlist_count = allowlist.len(),
- connected_count = connected_slugs.len(),
- connected = ?connected_slugs,
- "[spawn_subagent] integrations_agent gate: validating toolkit"
- );
-
- match toolkit_override.as_deref() {
- None => {
- return Ok(ToolResult::error(format!(
- "spawn_subagent(integrations_agent): the `toolkit` argument is required. \
- Pass one of the currently-connected toolkits: [{}]. \
- See the Delegation Guide in your system prompt for which toolkit \
- matches each task.",
- connected_slugs.join(", ")
- )));
- }
- Some(tk) => {
- let entry = allowlist
- .iter()
- .find(|ci| ci.toolkit.eq_ignore_ascii_case(tk));
- match entry {
- None => {
- // Toolkit isn't even in the backend allowlist.
- return Ok(ToolResult::error(format!(
- "spawn_subagent(integrations_agent): toolkit '{tk}' is not in \
- the backend allowlist. Valid toolkits: [{}]. Check the \
- Delegation Guide in your system prompt for the exact slug.",
- allowlist
- .iter()
- .map(|ci| ci.toolkit.as_str())
- .collect::<Vec<_>>()
- .join(", ")
- )));
- }
- Some(ci) if !ci.connected => {
- // Toolkit exists in the allowlist but isn't connected.
- // This is NOT a tool error — it's an expected condition
- // the orchestrator should communicate to the user. We
- // return `ToolResult::success` so:
- // 1. The agent loop doesn't prepend "Error: " to
- // the result text (which would bias the model
- // toward defensive failure language).
- // 2. The web channel emits `success: true` on the
- // `tool_result` socket event, so the frontend
- // doesn't render this as a failed tool call.
- // The model still reads the explanation and produces
- // an appropriate user-facing response.
- //
- // Split (#2365) into 4 cases driven by the upstream
- // status field on the most-informative connection
- // row, instead of the legacy generic
- // "not authorized yet" copy. Before this split,
- // an OAuth-in-progress / expired / failed Gmail
- // surfaced the same "you need to connect Gmail"
- // message — which Settings UI contradicted (it
- // shows the connection as initiated/expired), so
- // users concluded the agent was confused.
- tracing::debug!(
- target: "spawn_subagent",
- toolkit = %ci.toolkit,
- non_active_status = ?ci.non_active_status,
- "[spawn_subagent] integrations_agent gate: toolkit not connected — emitting status-specific message"
- );
- let message = describe_unconnected_state(
- &ci.toolkit,
- ci.non_active_status.as_deref(),
- );
- return Ok(ToolResult::success(message));
- }
- Some(_) => {
- tracing::debug!(
- target: "spawn_subagent",
- toolkit = %tk,
- "[spawn_subagent] integrations_agent gate: toolkit connected, proceeding with spawn"
- );
- }
- }
- }
- }
- }
-
- // Async-by-default only holds where the finished result has somewhere
- // to land. `spawn_async_subagent` delivers thread-addressed (see
- // `background_delivery`), so outside a chat turn (flow `agent` node,
- // CLI, cron) it now refuses outright (B40). Self-heal to blocking
- // dispatch here rather than forwarding into that guard: the caller
- // asked to delegate, and running the sub-agent inline is the one mode
- // that both executes it and returns its output. Mirrors the
- // `has_delivery_thread` fallback the `delegate_*` tools already do in
- // `dispatch.rs::dispatch_subagent`.
- let has_delivery_thread =
- crate::openhuman::agent::tinyagents::thread_context::current_thread_id().is_some();
- if !blocking && !has_delivery_thread {
- log::info!(
- "[spawn_subagent] async delegation requested for '{}' but no delivery thread \
- (flow node / CLI / cron context) — falling back to blocking dispatch",
- definition.id
- );
- }
- if !blocking && has_delivery_thread {
- let mut async_args = args;
- if let Some(obj) = async_args.as_object_mut() {
- obj.insert(
- "agent_id".to_string(),
- serde_json::Value::String(definition.id.clone()),
- );
- if obj.get("task_title").is_none() {
- let title =
- crate::openhuman::agent::orchestration::subagent_sessions::task_title_from_prompt(
- &prompt,
- );
- obj.insert("task_title".to_string(), serde_json::Value::String(title));
- }
- }
- tracing::info!(
- target: "spawn_subagent",
- agent_id = %definition.id,
- "[spawn_subagent] routing to reusable async sub-agent by default"
- );
- return super::spawn_async_subagent::SpawnAsyncSubagentTool::new()
- .execute_with_context(async_args, ToolCallOptions::default(), tool_context)
- .await;
- }
-
- // ── Publish SubagentSpawned event ──────────────────────────────
- let parent_session = current_parent()
- .map(|p| p.session_id.clone())
- .unwrap_or_else(|| "standalone".into());
- let task_id = format!("sub-{}", uuid::Uuid::new_v4());
-
- // Persist this delegation as a reopenable worker sub-thread, seeded
- // with the prompt, so the parent↔subagent conversation survives
- // navigation and restarts — the same machinery `spawn_worker_thread`
- // uses. Best-effort: with no parent context or thread store the run
- // still proceeds live-only (`worker_thread_id: None`).
- let worker_thread_id = current_parent().and_then(|p| {
- let parent_thread_id =
- crate::openhuman::agent::tinyagents::thread_context::current_thread_id()?;
- let title: String = prompt.chars().take(60).collect();
- super::worker_thread::create_worker_thread(
- p.workspace_dir.clone(),
- &parent_thread_id,
- &definition.id,
- &title,
- &prompt,
- )
- .ok()
- });
-
- crate::openhuman::agent::orchestration::subagent_events::publish_subagent_spawned(
- parent_session.clone(),
- definition.id.clone(),
- "typed".to_string(),
- task_id.clone(),
- prompt.chars().count(),
- );
-
- // Mirror the spawn onto the parent's per-turn progress sink so the
- // web-channel bridge can stream a live subagent row into the
- // parent thread's UI. Best-effort: a closed/missing sink is
- // silently ignored — the global DomainEvent above is the
- // authoritative record.
- if let Some(progress) = current_parent().and_then(|p| p.on_progress.clone()) {
- let _ = progress
- .send(AgentProgress::SubagentSpawned {
- agent_id: definition.id.clone(),
- task_id: task_id.clone(),
- mode: "typed".to_string(),
- dedicated_thread,
- prompt_chars: prompt.chars().count(),
- prompt: prompt.clone(),
- worker_thread_id: worker_thread_id.clone(),
- display_name: Some(definition.display_name().to_string()),
- })
- .await;
- }
-
- // ── Run the sub-agent ──────────────────────────────────────────
- let workspace_descriptor = tool_context.and_then(|ctx| ctx.workspace().cloned());
- let worktree_action_dir = workspace_descriptor
- .as_ref()
- .map(|descriptor| descriptor.root.clone());
- if let Some(descriptor) = workspace_descriptor.as_ref() {
- tracing::debug!(
- task_id = %task_id,
- agent_id = %definition.id,
- workspace_root = %descriptor.root.display(),
- policy_id = %descriptor.policy_id,
- "[spawn_subagent] using ToolExecutionContext workspace root"
- );
- }
- let options = SubagentRunOptions {
- skill_filter_override: None,
- toolkit_override,
- context,
- model_override,
- task_id: Some(task_id.clone()),
- worker_thread_id: worker_thread_id.clone(),
- initial_history: None,
- checkpoint_dir: None,
- worktree_action_dir,
- workspace_descriptor,
- run_queue: None,
- };
-
- let progress_sink = current_parent().and_then(|p| p.on_progress.clone());
-
- match run_subagent(definition, &prompt, options).await {
- Ok(outcome) => {
- match &outcome.status {
- SubagentRunStatus::AwaitingUser {
- question,
- options: _,
- } => {
- // Sub-agent paused for user input — publish
- // awaiting event and return structured envelope so
- // the orchestrator can relay the question and later
- // call continue_subagent.
- crate::openhuman::agent::orchestration::subagent_events::publish_subagent_awaiting_user(
- parent_session,
- outcome.task_id.clone(),
- outcome.agent_id.clone(),
- question.clone(),
- );
- if let Some(ref tx) = progress_sink {
- let _ = tx
- .send(AgentProgress::SubagentAwaitingUser {
- agent_id: outcome.agent_id.clone(),
- task_id: outcome.task_id.clone(),
- question: question.clone(),
- worker_thread_id: worker_thread_id.clone(),
- })
- .await;
- }
- let envelope = super::awaiting_user::awaiting_user_envelope(
- &outcome.task_id,
- &outcome.agent_id,
- worker_thread_id.as_deref(),
- question,
- );
- Ok(ToolResult::success(envelope))
- }
- SubagentRunStatus::Completed => {
- // #3883: log the orchestrator taking delivery of each
- // artifact path the child handed back, so a run journal
- // shows both ends of every `[artifact]` pointer. The
- // `consumed_by_parent` stage distinguishes this from the
- // child's `recorded_by_child` line for the same path.
- crate::openhuman::agent::harness::artifact_offload::note_artifact_handoff(
- crate::openhuman::agent::harness::artifact_offload::HANDOFF_STAGE_CONSUMED,
- &outcome.agent_id,
- &outcome.task_id,
- &outcome.artifact_paths,
- );
- crate::openhuman::agent::orchestration::subagent_events::publish_subagent_completed(
- parent_session,
- outcome.task_id.clone(),
- outcome.agent_id.clone(),
- outcome.elapsed.as_millis() as u64,
- outcome.output.chars().count(),
- outcome.iterations,
- );
-
- if let Some(ref tx) = progress_sink {
- let _ = tx
- .send(AgentProgress::SubagentCompleted {
- agent_id: outcome.agent_id.clone(),
- task_id: outcome.task_id.clone(),
- elapsed_ms: outcome.elapsed.as_millis() as u64,
- iterations: outcome.iterations as u32,
- output_chars: outcome.output.chars().count(),
- output: outcome.output.clone(),
- worktree_path: None,
- changed_files: Vec::new(),
- dirty_status: None,
- })
- .await;
- }
-
- if dedicated_thread {
- let workspace_dir = current_parent()
- .map(|p| p.workspace_dir.clone())
- .unwrap_or_else(|| PathBuf::from("."));
- let parent_visible = match persist_worker_thread(
- &workspace_dir,
- &definition.id,
- &prompt,
- &outcome,
- ) {
- Ok(thread_id) => render_worker_thread_result(
- &thread_id,
- &definition.id,
- &outcome,
- ),
- Err(error) => {
- tracing::error!(
- target: "spawn_subagent",
- agent_id = %definition.id,
- error = %error,
- "[spawn_subagent] dedicated_thread persistence failed; \
- returning full sub-agent output inline"
- );
- format!(
- "{}\n\n[worker_thread_error] failed to persist worker thread: {}",
- outcome.output, error
- )
- }
- };
- return Ok(ToolResult::success(parent_visible));
- }
-
- Ok(ToolResult::success(outcome.output))
- }
- SubagentRunStatus::Incomplete { reason } => {
- // The sub-agent stopped WITHOUT reaching its goal (a
- // no-progress circuit breaker halted it, or it hit the
- // iteration cap). Hand the orchestrator a structured
- // envelope carrying BOTH the blocker and the partial
- // progress — NOT the "nothing happened" failure envelope
- // (work WAS done) and NOT a bare success it would narrate
- // as done or re-spin (#4096).
- tracing::info!(
- agent_id = %outcome.agent_id,
- task_id = %outcome.task_id,
- iterations = outcome.iterations,
- "[spawn_subagent] sub-agent stopped incomplete — returning structured handback"
- );
- crate::openhuman::agent::orchestration::subagent_events::publish_subagent_completed(
- parent_session,
- outcome.task_id.clone(),
- outcome.agent_id.clone(),
- outcome.elapsed.as_millis() as u64,
- outcome.output.chars().count(),
- outcome.iterations,
- );
- if let Some(ref tx) = progress_sink {
- let _ = tx
- .send(AgentProgress::SubagentCompleted {
- agent_id: outcome.agent_id.clone(),
- task_id: outcome.task_id.clone(),
- elapsed_ms: outcome.elapsed.as_millis() as u64,
- iterations: outcome.iterations as u32,
- output_chars: outcome.output.chars().count(),
- output: outcome.output.clone(),
- worktree_path: None,
- changed_files: Vec::new(),
- dirty_status: None,
- })
- .await;
- }
- let envelope = format!(
- "[SUBAGENT_INCOMPLETE]\n\
- task_id: {}\n\
- agent_id: {}\n\
- reason: the sub-agent {reason}\n\
- progress:\n{}\n\
- [/SUBAGENT_INCOMPLETE]\n\n\
- The sub-agent did NOT finish. Above is the partial progress it \
- made. Do NOT report this as done or fabricate a result. Decide: \
- relay the partial result and the blocker to the user, continue with \
- a different approach, or escalate — but do not re-run the identical \
- delegation unchanged.",
- outcome.task_id, outcome.agent_id, outcome.output,
- );
- Ok(ToolResult::success(envelope))
- }
- }
- }
- Err(err) => {
- let message = err.to_string();
- let parent_visible_error = Self::classify_subagent_failure(&message);
- // Log only non-sensitive context: agent_id and task_id. The raw
- // error message and classified summary may contain user prompts or
- // payload fragments — emit only a short type/kind indicator.
- let error_kind = message
- .split(':')
- .next()
- .map(str::trim)
- .unwrap_or("unknown");
- tracing::error!(
- agent_id = %definition.id,
- task_id = %task_id,
- error_kind = %error_kind,
- "[spawn_subagent] sub-agent execution failed"
- );
- crate::openhuman::agent::orchestration::subagent_events::publish_subagent_failed(
- parent_session,
- task_id.clone(),
- definition.id.clone(),
- message.clone(),
- );
-
- if let Some(ref tx) = progress_sink {
- let _ = tx
- .send(AgentProgress::SubagentFailed {
- agent_id: definition.id.clone(),
- task_id: task_id.clone(),
- error: message.clone(),
- })
- .await;
- }
- // Surface as a non-fatal tool error so the parent model
- // can react and (e.g.) retry with different params.
- Ok(ToolResult::error(parent_visible_error))
- }
- }
- }
-}
+include!("spawn_subagent_tool_impl.rs");
/// Trim a raw prompt down to a thread-list-friendly title.
///
diff --git a/src/openhuman/agent/orchestration/tools/spawn_subagent_tool_impl.rs b/src/openhuman/agent/orchestration/tools/spawn_subagent_tool_impl.rs
new file mode 100644
index 0000000000..c00ddb1df7
--- /dev/null
+++ b/src/openhuman/agent/orchestration/tools/spawn_subagent_tool_impl.rs
@@ -0,0 +1,694 @@
+#[async_trait]
+impl Tool for SpawnSubagentTool {
+
+ fn name(&self) -> &str {
+ "spawn_subagent"
+ }
+
+ fn description(&self) -> &str {
+ "Delegate a task to a specialised sub-agent only when direct \
+ response or direct tools are insufficient. Handles ONE delegated task \
+ per call: by default it runs as a reusable async worker and returns \
+ immediately — pass `blocking: true` to run it inline and get the \
+ sub-agent's final output back in this turn. To run several independent \
+ workers at once (e.g. \"a separate researcher for each X\", a council \
+ of opinions, or \"fan out over N items\"), use `spawn_parallel_agents` \
+ with one task per worker — a SINGLE call that launches them \
+ concurrently. Do NOT call this tool in a loop to fan out: repeated \
+ `spawn_subagent` calls each delegate a single task and never launch \
+ workers concurrently, which serializes the whole request. See the Delegation \
+ Guide in the system prompt for available agent_ids and when to \
+ use each. When delegating to `integrations_agent`, you MUST also pass \
+ `toolkit=\"<name>\"` naming the Composio integration the \
+ sub-task targets (e.g. `gmail`, `notion`); the sub-agent will \
+ only see that toolkit's actions."
+ }
+
+ fn parameters_schema(&self) -> serde_json::Value {
+ // Build the agent_id enum dynamically from the global registry
+ // when it's been initialised. Falls back to a string-with-hint
+ // when the registry hasn't been set up yet (e.g. early tests).
+ let agent_ids: Vec<String> = AgentDefinitionRegistry::global()
+ .map(|reg| reg.list().iter().map(|d| d.id.clone()).collect())
+ .unwrap_or_default();
+
+ let agent_id_schema = if agent_ids.is_empty() {
+ json!({
+ "type": "string",
+ "description": "Sub-agent id (e.g. code_executor, researcher, critic)."
+ })
+ } else {
+ json!({
+ "type": "string",
+ "enum": agent_ids,
+ "description": "Sub-agent id from the registry."
+ })
+ };
+
+ json!({
+ "type": "object",
+ "required": ["agent_id", "prompt"],
+ "properties": {
+ "agent_id": agent_id_schema,
+ // Back-compat alias — older callers used `archetype`.
+ "archetype": {
+ "type": "string",
+ "description": "Deprecated alias for `agent_id`. Use `agent_id` going forward."
+ },
+ "prompt": {
+ "type": "string",
+ "description": "Clear, specific instruction for the sub-agent. The sub-agent has no memory of the parent's conversation, so include all context the sub-agent needs to act."
+ },
+ "context": {
+ "type": "string",
+ "description": "Optional context blob from prior task results. Rendered as a `[Context]` block before the prompt."
+ },
+ "model": {
+ "type": "string",
+ "description": "Optional exact model id for this spawn only. Keeps the parent provider/routing, but pins the child agent to this model instead of the agent definition's default."
+ },
+ "toolkit": {
+ "type": "string",
+ "description": "Composio toolkit slug to scope this spawn to — e.g. `gmail`, `notion`, `slack`. REQUIRED when `agent_id = \"integrations_agent\"`. Narrows the sub-agent's visible Composio actions AND its Connected Integrations prompt section to only that toolkit's catalogue, so the sub-agent's context window only carries the platform it was asked to operate on. Must match a currently-connected integration (see the Delegation Guide)."
+ },
+ "dedicated_thread": {
+ "type": "boolean",
+ "description": "Legacy compatibility flag. Delegations now always create a persistent worker thread when parent context is available, so this flag no longer gates thread creation."
+ },
+ "blocking": {
+ "type": "boolean",
+ "description": "Explicitly run the sub-agent inline and return its final output. Defaults to false; reusable async delegation is the default."
+ },
+ "task_key": {
+ "type": "string",
+ "description": "Optional deterministic identity key for reusable async delegation. Defaults to a normalized prompt/title."
+ },
+ "fresh": {
+ "type": "boolean",
+ "description": "When true, bypass reusable subagent matching and create a fresh durable worker."
+ }
+ }
+ })
+ }
+
+ fn permission_level(&self) -> PermissionLevel {
+ PermissionLevel::Execute
+ }
+
+ async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {
+ self.execute_with_context(args, ToolCallOptions::default(), None)
+ .await
+ }
+
+ async fn execute_with_context(
+ &self,
+ args: serde_json::Value,
+ _options: ToolCallOptions,
+ tool_context: Option<&dyn ToolRunContext>,
+ ) -> anyhow::Result<ToolResult> {
+ // ── Argument extraction with back-compat ───────────────────────
+ let agent_id = args
+ .get("agent_id")
+ .and_then(|v| v.as_str())
+ .or_else(|| args.get("archetype").and_then(|v| v.as_str()))
+ .unwrap_or("")
+ .trim()
+ .to_string();
+
+ let prompt = args
+ .get("prompt")
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .trim()
+ .to_string();
+
+ let context = args
+ .get("context")
+ .and_then(|v| v.as_str())
+ .map(|s| s.to_string());
+
+ let model_override = args
+ .get("model")
+ .and_then(|v| v.as_str())
+ .map(|s| s.trim().to_string())
+ .filter(|s| !s.is_empty());
+
+ let toolkit_override = args
+ .get("toolkit")
+ .and_then(|v| v.as_str())
+ .map(|s| s.trim().to_string())
+ .filter(|s| !s.is_empty());
+
+ // Worker threads are now always created for delegations that may
+ // need follow-up (checkpoint + replay for ask_user_clarification).
+ // The `dedicated_thread` parameter is accepted but no longer
+ // gates thread creation — every delegation gets a persistent
+ // worker thread. (#3049 supersedes the #1624 disable.)
+ let dedicated_thread = args
+ .get("dedicated_thread")
+ .and_then(|v| v.as_bool())
+ .unwrap_or(false);
+ let blocking = args
+ .get("blocking")
+ .and_then(|v| v.as_bool())
+ .unwrap_or(false);
+
+ // ── Validation ─────────────────────────────────────────────────
+ if agent_id.is_empty() {
+ return Ok(ToolResult::error(
+ "spawn_subagent: `agent_id` (or legacy `archetype`) is required",
+ ));
+ }
+ if prompt.is_empty() {
+ return Ok(ToolResult::error("spawn_subagent: `prompt` is required"));
+ }
+
+ let registry = match AgentDefinitionRegistry::global() {
+ Some(reg) => reg,
+ None => {
+ return Ok(ToolResult::error(
+ "spawn_subagent: AgentDefinitionRegistry has not been initialised. \
+ This usually means the core process started without calling \
+ AgentDefinitionRegistry::init_global at startup.",
+ ));
+ }
+ };
+
+ let definition = match registry.get(agent_id.as_str()) {
+ Some(def) => def,
+ None => {
+ let available: Vec<&str> = registry.list().iter().map(|d| d.id.as_str()).collect();
+ return Ok(ToolResult::error(format!(
+ "spawn_subagent: unknown agent_id '{agent_id}'. Available: {}",
+ available.join(", ")
+ )));
+ }
+ };
+
+ if let Some(parent_ctx) = current_parent() {
+ if !parent_ctx.allowed_subagent_ids.contains(&definition.id) {
+ log::warn!(
+ "[spawn_subagent] blocked subagent outside parent allowlist parent_agent={} requested_agent={} allowed={:?}",
+ parent_ctx.agent_definition_id,
+ definition.id,
+ parent_ctx.allowed_subagent_ids
+ );
+ return Ok(ToolResult::error(format!(
+ "spawn_subagent: agent '{}' is not in parent agent '{}' subagents.allowlist",
+ definition.id, parent_ctx.agent_definition_id
+ )));
+ }
+ log::debug!(
+ "[spawn_subagent] subagent allowlist check passed parent_agent={} requested_agent={}",
+ parent_ctx.agent_definition_id,
+ definition.id
+ );
+ }
+
+ // ── integrations_agent toolkit gate ──────────────────────────────────
+ // integrations_agent is a platform-parameterised specialist. Every
+ // spawn MUST name a CONNECTED toolkit so the sub-agent only
+ // sees one integration's tool catalogue instead of all of
+ // them. We split validation into three cases so the model
+ // gets a precise, actionable error on every failure mode —
+ // nothing reaches the LLM loop unless the spawn is valid.
+ if definition.id == "integrations_agent" {
+ // The parent's `connected_integrations` Vec is frozen at
+ // session-start (see `session/turn.rs::fetch_connected_integrations`),
+ // so a toolkit the user authorised mid-thread isn't visible
+ // here. Refresh from the global integrations cache —
+ // invalidated by `ComposioConnectionCreatedSubscriber` once
+ // OAuth reaches ACTIVE — so the pre-flight sees the latest
+ // truth. Falls back to the parent's frozen list when the
+ // live fetch returns empty (no signed-in user, backend
+ // unreachable, …) so offline behaviour is unchanged.
+ let parent_ctx = current_parent();
+ let live_integrations: Vec<
+ crate::openhuman::agent::context::prompt::ConnectedIntegration,
+ > = {
+ match crate::openhuman::config::Config::load_or_init().await {
+ Ok(config) => {
+ use crate::openhuman::integrations::composio::FetchConnectedIntegrationsStatus;
+ // Use the status-discriminating fetch so we can
+ // tell "user has zero active integrations" (truth
+ // — adopt it) apart from "backend unavailable"
+ // (preserve the parent's frozen snapshot so the
+ // pre-flight doesn't reject every toolkit during
+ // a transient 5xx).
+ match crate::openhuman::integrations::composio::fetch_connected_integrations_status(
+ &config,
+ )
+ .await
+ {
+ FetchConnectedIntegrationsStatus::Authoritative(fresh) => {
+ tracing::debug!(
+ target: "spawn_subagent",
+ count = fresh.len(),
+ "[spawn_subagent] refreshed connected_integrations for pre-flight"
+ );
+ fresh
+ }
+ FetchConnectedIntegrationsStatus::Unavailable => {
+ tracing::debug!(
+ target: "spawn_subagent",
+ "[spawn_subagent] integrations backend unavailable; falling back to parent's frozen list"
+ );
+ parent_ctx
+ .as_ref()
+ .map(|p| p.connected_integrations.clone())
+ .unwrap_or_default()
+ }
+ }
+ }
+ Err(e) => {
+ tracing::debug!(
+ target: "spawn_subagent",
+ error = %e,
+ "[spawn_subagent] config load failed; falling back to parent's frozen list"
+ );
+ parent_ctx
+ .as_ref()
+ .map(|p| p.connected_integrations.clone())
+ .unwrap_or_default()
+ }
+ }
+ };
+ let allowlist: Vec<&crate::openhuman::agent::context::prompt::ConnectedIntegration> =
+ live_integrations.iter().collect();
+ let connected_slugs: Vec<String> = allowlist
+ .iter()
+ .filter(|ci| ci.connected)
+ .map(|ci| ci.toolkit.clone())
+ .collect();
+
+ tracing::debug!(
+ target: "spawn_subagent",
+ toolkit = ?toolkit_override,
+ allowlist_count = allowlist.len(),
+ connected_count = connected_slugs.len(),
+ connected = ?connected_slugs,
+ "[spawn_subagent] integrations_agent gate: validating toolkit"
+ );
+
+ match toolkit_override.as_deref() {
+ None => {
+ return Ok(ToolResult::error(format!(
+ "spawn_subagent(integrations_agent): the `toolkit` argument is required. \
+ Pass one of the currently-connected toolkits: [{}]. \
+ See the Delegation Guide in your system prompt for which toolkit \
+ matches each task.",
+ connected_slugs.join(", ")
+ )));
+ }
+ Some(tk) => {
+ let entry = allowlist
+ .iter()
+ .find(|ci| ci.toolkit.eq_ignore_ascii_case(tk));
+ match entry {
+ None => {
+ // Toolkit isn't even in the backend allowlist.
+ return Ok(ToolResult::error(format!(
+ "spawn_subagent(integrations_agent): toolkit '{tk}' is not in \
+ the backend allowlist. Valid toolkits: [{}]. Check the \
+ Delegation Guide in your system prompt for the exact slug.",
+ allowlist
+ .iter()
+ .map(|ci| ci.toolkit.as_str())
+ .collect::<Vec<_>>()
+ .join(", ")
+ )));
+ }
+ Some(ci) if !ci.connected => {
+ // Toolkit exists in the allowlist but isn't connected.
+ // This is NOT a tool error — it's an expected condition
+ // the orchestrator should communicate to the user. We
+ // return `ToolResult::success` so:
+ // 1. The agent loop doesn't prepend "Error: " to
+ // the result text (which would bias the model
+ // toward defensive failure language).
+ // 2. The web channel emits `success: true` on the
+ // `tool_result` socket event, so the frontend
+ // doesn't render this as a failed tool call.
+ // The model still reads the explanation and produces
+ // an appropriate user-facing response.
+ //
+ // Split (#2365) into 4 cases driven by the upstream
+ // status field on the most-informative connection
+ // row, instead of the legacy generic
+ // "not authorized yet" copy. Before this split,
+ // an OAuth-in-progress / expired / failed Gmail
+ // surfaced the same "you need to connect Gmail"
+ // message — which Settings UI contradicted (it
+ // shows the connection as initiated/expired), so
+ // users concluded the agent was confused.
+ tracing::debug!(
+ target: "spawn_subagent",
+ toolkit = %ci.toolkit,
+ non_active_status = ?ci.non_active_status,
+ "[spawn_subagent] integrations_agent gate: toolkit not connected — emitting status-specific message"
+ );
+ let message = describe_unconnected_state(
+ &ci.toolkit,
+ ci.non_active_status.as_deref(),
+ );
+ return Ok(ToolResult::success(message));
+ }
+ Some(_) => {
+ tracing::debug!(
+ target: "spawn_subagent",
+ toolkit = %tk,
+ "[spawn_subagent] integrations_agent gate: toolkit connected, proceeding with spawn"
+ );
+ }
+ }
+ }
+ }
+ }
+
+ // Async-by-default only holds where the finished result has somewhere
+ // to land. `spawn_async_subagent` delivers thread-addressed (see
+ // `background_delivery`), so outside a chat turn (flow `agent` node,
+ // CLI, cron) it now refuses outright (B40). Self-heal to blocking
+ // dispatch here rather than forwarding into that guard: the caller
+ // asked to delegate, and running the sub-agent inline is the one mode
+ // that both executes it and returns its output. Mirrors the
+ // `has_delivery_thread` fallback the `delegate_*` tools already do in
+ // `dispatch.rs::dispatch_subagent`.
+ let has_delivery_thread =
+ crate::openhuman::agent::tinyagents::thread_context::current_thread_id().is_some();
+ if !blocking && !has_delivery_thread {
+ log::info!(
+ "[spawn_subagent] async delegation requested for '{}' but no delivery thread \
+ (flow node / CLI / cron context) — falling back to blocking dispatch",
+ definition.id
+ );
+ }
+ if !blocking && has_delivery_thread {
+ let mut async_args = args;
+ if let Some(obj) = async_args.as_object_mut() {
+ obj.insert(
+ "agent_id".to_string(),
+ serde_json::Value::String(definition.id.clone()),
+ );
+ if obj.get("task_title").is_none() {
+ let title =
+ crate::openhuman::agent::orchestration::subagent_sessions::task_title_from_prompt(
+ &prompt,
+ );
+ obj.insert("task_title".to_string(), serde_json::Value::String(title));
+ }
+ }
+ tracing::info!(
+ target: "spawn_subagent",
+ agent_id = %definition.id,
+ "[spawn_subagent] routing to reusable async sub-agent by default"
+ );
+ return super::spawn_async_subagent::SpawnAsyncSubagentTool::new()
+ .execute_with_context(async_args, ToolCallOptions::default(), tool_context)
+ .await;
+ }
+
+ // ── Publish SubagentSpawned event ──────────────────────────────
+ let parent_session = current_parent()
+ .map(|p| p.session_id.clone())
+ .unwrap_or_else(|| "standalone".into());
+ let task_id = format!("sub-{}", uuid::Uuid::new_v4());
+
+ // Persist this delegation as a reopenable worker sub-thread, seeded
+ // with the prompt, so the parent↔subagent conversation survives
+ // navigation and restarts — the same machinery `spawn_worker_thread`
+ // uses. Best-effort: with no parent context or thread store the run
+ // still proceeds live-only (`worker_thread_id: None`).
+ let worker_thread_id = current_parent().and_then(|p| {
+ let parent_thread_id =
+ crate::openhuman::agent::tinyagents::thread_context::current_thread_id()?;
+ let title: String = prompt.chars().take(60).collect();
+ super::worker_thread::create_worker_thread(
+ p.workspace_dir.clone(),
+ &parent_thread_id,
+ &definition.id,
+ &title,
+ &prompt,
+ )
+ .ok()
+ });
+
+ crate::openhuman::agent::orchestration::subagent_events::publish_subagent_spawned(
+ parent_session.clone(),
+ definition.id.clone(),
+ "typed".to_string(),
+ task_id.clone(),
+ prompt.chars().count(),
+ );
+
+ // Mirror the spawn onto the parent's per-turn progress sink so the
+ // web-channel bridge can stream a live subagent row into the
+ // parent thread's UI. Best-effort: a closed/missing sink is
+ // silently ignored — the global DomainEvent above is the
+ // authoritative record.
+ if let Some(progress) = current_parent().and_then(|p| p.on_progress.clone()) {
+ let _ = progress
+ .send(AgentProgress::SubagentSpawned {
+ agent_id: definition.id.clone(),
+ task_id: task_id.clone(),
+ mode: "typed".to_string(),
+ dedicated_thread,
+ prompt_chars: prompt.chars().count(),
+ prompt: prompt.clone(),
+ worker_thread_id: worker_thread_id.clone(),
+ display_name: Some(definition.display_name().to_string()),
+ })
+ .await;
+ }
+
+ // ── Run the sub-agent ──────────────────────────────────────────
+ let workspace_descriptor = tool_context.and_then(|ctx| ctx.workspace().cloned());
+ let worktree_action_dir = workspace_descriptor
+ .as_ref()
+ .map(|descriptor| descriptor.root.clone());
+ if let Some(descriptor) = workspace_descriptor.as_ref() {
+ tracing::debug!(
+ task_id = %task_id,
+ agent_id = %definition.id,
+ workspace_root = %descriptor.root.display(),
+ policy_id = %descriptor.policy_id,
+ "[spawn_subagent] using ToolExecutionContext workspace root"
+ );
+ }
+ let options = SubagentRunOptions {
+ skill_filter_override: None,
+ toolkit_override,
+ context,
+ model_override,
+ task_id: Some(task_id.clone()),
+ worker_thread_id: worker_thread_id.clone(),
+ initial_history: None,
+ checkpoint_dir: None,
+ worktree_action_dir,
+ workspace_descriptor,
+ run_queue: None,
+ };
+
+ let progress_sink = current_parent().and_then(|p| p.on_progress.clone());
+
+ match run_subagent(definition, &prompt, options).await {
+ Ok(outcome) => {
+ match &outcome.status {
+ SubagentRunStatus::AwaitingUser {
+ question,
+ options: _,
+ } => {
+ // Sub-agent paused for user input — publish
+ // awaiting event and return structured envelope so
+ // the orchestrator can relay the question and later
+ // call continue_subagent.
+ crate::openhuman::agent::orchestration::subagent_events::publish_subagent_awaiting_user(
+ parent_session,
+ outcome.task_id.clone(),
+ outcome.agent_id.clone(),
+ question.clone(),
+ );
+ if let Some(ref tx) = progress_sink {
+ let _ = tx
+ .send(AgentProgress::SubagentAwaitingUser {
+ agent_id: outcome.agent_id.clone(),
+ task_id: outcome.task_id.clone(),
+ question: question.clone(),
+ worker_thread_id: worker_thread_id.clone(),
+ })
+ .await;
+ }
+ let envelope = super::awaiting_user::awaiting_user_envelope(
+ &outcome.task_id,
+ &outcome.agent_id,
+ worker_thread_id.as_deref(),
+ question,
+ );
+ Ok(ToolResult::success(envelope))
+ }
+ SubagentRunStatus::Completed => {
+ // #3883: log the orchestrator taking delivery of each
+ // artifact path the child handed back, so a run journal
+ // shows both ends of every `[artifact]` pointer. The
+ // `consumed_by_parent` stage distinguishes this from the
+ // child's `recorded_by_child` line for the same path.
+ crate::openhuman::agent::harness::artifact_offload::note_artifact_handoff(
+ crate::openhuman::agent::harness::artifact_offload::HANDOFF_STAGE_CONSUMED,
+ &outcome.agent_id,
+ &outcome.task_id,
+ &outcome.artifact_paths,
+ );
+ crate::openhuman::agent::orchestration::subagent_events::publish_subagent_completed(
+ parent_session,
+ outcome.task_id.clone(),
+ outcome.agent_id.clone(),
+ outcome.elapsed.as_millis() as u64,
+ outcome.output.chars().count(),
+ outcome.iterations,
+ );
+
+ if let Some(ref tx) = progress_sink {
+ let _ = tx
+ .send(AgentProgress::SubagentCompleted {
+ agent_id: outcome.agent_id.clone(),
+ task_id: outcome.task_id.clone(),
+ elapsed_ms: outcome.elapsed.as_millis() as u64,
+ iterations: outcome.iterations as u32,
+ output_chars: outcome.output.chars().count(),
+ output: outcome.output.clone(),
+ worktree_path: None,
+ changed_files: Vec::new(),
+ dirty_status: None,
+ })
+ .await;
+ }
+
+ if dedicated_thread {
+ let workspace_dir = current_parent()
+ .map(|p| p.workspace_dir.clone())
+ .unwrap_or_else(|| PathBuf::from("."));
+ let parent_visible = match persist_worker_thread(
+ &workspace_dir,
+ &definition.id,
+ &prompt,
+ &outcome,
+ ) {
+ Ok(thread_id) => render_worker_thread_result(
+ &thread_id,
+ &definition.id,
+ &outcome,
+ ),
+ Err(error) => {
+ tracing::error!(
+ target: "spawn_subagent",
+ agent_id = %definition.id,
+ error = %error,
+ "[spawn_subagent] dedicated_thread persistence failed; \
+ returning full sub-agent output inline"
+ );
+ format!(
+ "{}\n\n[worker_thread_error] failed to persist worker thread: {}",
+ outcome.output, error
+ )
+ }
+ };
+ return Ok(ToolResult::success(parent_visible));
+ }
+
+ Ok(ToolResult::success(outcome.output))
+ }
+ SubagentRunStatus::Incomplete { reason } => {
+ // The sub-agent stopped WITHOUT reaching its goal (a
+ // no-progress circuit breaker halted it, or it hit the
+ // iteration cap). Hand the orchestrator a structured
+ // envelope carrying BOTH the blocker and the partial
+ // progress — NOT the "nothing happened" failure envelope
+ // (work WAS done) and NOT a bare success it would narrate
+ // as done or re-spin (#4096).
+ tracing::info!(
+ agent_id = %outcome.agent_id,
+ task_id = %outcome.task_id,
+ iterations = outcome.iterations,
+ "[spawn_subagent] sub-agent stopped incomplete — returning structured handback"
+ );
+ crate::openhuman::agent::orchestration::subagent_events::publish_subagent_completed(
+ parent_session,
+ outcome.task_id.clone(),
+ outcome.agent_id.clone(),
+ outcome.elapsed.as_millis() as u64,
+ outcome.output.chars().count(),
+ outcome.iterations,
+ );
+ if let Some(ref tx) = progress_sink {
+ let _ = tx
+ .send(AgentProgress::SubagentCompleted {
+ agent_id: outcome.agent_id.clone(),
+ task_id: outcome.task_id.clone(),
+ elapsed_ms: outcome.elapsed.as_millis() as u64,
+ iterations: outcome.iterations as u32,
+ output_chars: outcome.output.chars().count(),
+ output: outcome.output.clone(),
+ worktree_path: None,
+ changed_files: Vec::new(),
+ dirty_status: None,
+ })
+ .await;
+ }
+ let envelope = format!(
+ "[SUBAGENT_INCOMPLETE]\n\
+ task_id: {}\n\
+ agent_id: {}\n\
+ reason: the sub-agent {reason}\n\
+ progress:\n{}\n\
+ [/SUBAGENT_INCOMPLETE]\n\n\
+ The sub-agent did NOT finish. Above is the partial progress it \
+ made. Do NOT report this as done or fabricate a result. Decide: \
+ relay the partial result and the blocker to the user, continue with \
+ a different approach, or escalate — but do not re-run the identical \
+ delegation unchanged.",
+ outcome.task_id, outcome.agent_id, outcome.output,
+ );
+ Ok(ToolResult::success(envelope))
+ }
+ }
+ }
+ Err(err) => {
+ let message = err.to_string();
+ let parent_visible_error = Self::classify_subagent_failure(&message);
+ // Log only non-sensitive context: agent_id and task_id. The raw
+ // error message and classified summary may contain user prompts or
+ // payload fragments — emit only a short type/kind indicator.
+ let error_kind = message
+ .split(':')
+ .next()
+ .map(str::trim)
+ .unwrap_or("unknown");
+ tracing::error!(
+ agent_id = %definition.id,
+ task_id = %task_id,
+ error_kind = %error_kind,
+ "[spawn_subagent] sub-agent execution failed"
+ );
+ crate::openhuman::agent::orchestration::subagent_events::publish_subagent_failed(
+ parent_session,
+ task_id.clone(),
+ definition.id.clone(),
+ message.clone(),
+ );
+
+ if let Some(ref tx) = progress_sink {
+ let _ = tx
+ .send(AgentProgress::SubagentFailed {
+ agent_id: definition.id.clone(),
+ task_id: task_id.clone(),
+ error: message.clone(),
+ })
+ .await;
+ }
+ // Surface as a non-fatal tool error so the parent model
+ // can react and (e.g.) retry with different params.
+ Ok(ToolResult::error(parent_visible_error))
+ }
+ }
+ }
+}
diff --git a/src/openhuman/config/schemas/schema_defs.rs b/src/openhuman/config/schemas/schema_defs.rs
index 27a3d25918..89c8fc6f24 100644
--- a/src/openhuman/config/schemas/schema_defs.rs
+++ b/src/openhuman/config/schemas/schema_defs.rs
@@ -2,757 +2,28 @@ use crate::core::{ControllerSchema, FieldSchema, TypeSchema};
use super::helpers::{json_output, optional_bool, optional_json, optional_string};
+#[path = "schemas_schema_part_01.rs"]
+mod schemas_schema_part_01;
+#[path = "schemas_schema_part_02.rs"]
+mod schemas_schema_part_02;
+
pub fn schemas(function: &str) -> ControllerSchema {
- match function {
- "get_config" => ControllerSchema {
- namespace: "config",
- function: "get",
- description: "Read persisted config snapshot and resolved paths.",
- inputs: vec![],
- outputs: vec![FieldSchema {
- name: "snapshot",
- ty: TypeSchema::Json,
- comment: "Config snapshot with workspace and config paths.",
- required: true,
- }],
- },
- "get_client_config" => ControllerSchema {
- namespace: "config",
- function: "get_client_config",
- description: "Read safe client-facing config fields (api_url, feature flags). No secrets.",
- inputs: vec![],
- outputs: vec![
- FieldSchema {
- name: "api_url",
- ty: TypeSchema::Option(Box::new(TypeSchema::String)),
- comment: "Configured OpenHuman product backend URL, if any.",
- required: false,
- },
- FieldSchema {
- name: "inference_url",
- ty: TypeSchema::Option(Box::new(TypeSchema::String)),
- comment: "Custom OpenAI-compatible LLM endpoint, if any. When set together with an api_key, inference goes direct to this URL.",
- required: false,
- },
- FieldSchema {
- name: "default_model",
- ty: TypeSchema::Option(Box::new(TypeSchema::String)),
- comment: "Default model identifier.",
- required: false,
- },
- FieldSchema {
- name: "app_version",
- ty: TypeSchema::String,
- comment: "OpenHuman core version.",
- required: true,
- },
- FieldSchema {
- name: "api_key_set",
- ty: TypeSchema::Bool,
- comment: "True when a custom backend api_key is stored locally. The key itself is never returned over RPC.",
- required: true,
- },
- FieldSchema {
- name: "model_routes",
- ty: TypeSchema::Json,
- comment: "Persisted task-hint -> model id pairs the core router will obey. Empty when the OpenHuman built-in router is active.",
- required: true,
- },
- ],
- },
- "update_model_settings" => ControllerSchema {
- namespace: "config",
- function: "update_model_settings",
- description: "Update model and backend connection settings, including a custom OpenAI-compatible backend (api_url + api_key).",
- inputs: vec![
- optional_string("api_url", "OpenHuman product backend URL (auth/billing/voice). Almost always left blank; the inference URL is a separate `inference_url` field."),
- optional_string("inference_url", "Custom OpenAI-compatible LLM endpoint. When set together with `api_key`, inference goes direct to this URL instead of the OpenHuman backend. Pass an empty string to clear."),
- optional_string("api_key", "Optional API key for the configured inference endpoint. Pass an empty string to clear a previously stored key."),
- optional_string("default_model", "Default model id."),
- FieldSchema {
- name: "default_temperature",
- ty: TypeSchema::Option(Box::new(TypeSchema::F64)),
- comment: "Default model temperature.",
- required: false,
- },
- FieldSchema {
- name: "model_routes",
- ty: TypeSchema::Option(Box::new(TypeSchema::Json)),
- comment: "Optional list of {hint, model} pairs mapping task hints (reasoning, agentic, coding, summarization) to provider-specific model ids. Replaces config.model_routes wholesale; send [] to clear (e.g. when switching back to the OpenHuman built-in router).",
- required: false,
- },
- FieldSchema {
- name: "cloud_providers",
- ty: TypeSchema::Option(Box::new(TypeSchema::Json)),
- comment: "Optional list of cloud provider entries {id, slug, label, endpoint, auth_style}. API keys are stored separately via cloud_provider_set_key. Replaces config.cloud_providers wholesale.",
- required: false,
- },
- optional_string("primary_cloud", "id of the cloud_providers entry used when a workload routes to 'cloud'. Empty string clears."),
- optional_string("chat_provider", "Provider string for direct conversational chat workloads."),
- optional_string("reasoning_provider", "Provider string for the main reasoning workload (e.g. 'cloud', 'ollama:llama3.1:8b', 'openai:gpt-4o')."),
- optional_string("agentic_provider", "Provider string for sub-agent / tool-loop workloads."),
- optional_string("coding_provider", "Provider string for code-generation workloads."),
- optional_string("vision_provider", "Provider string for the vision / multimodal workload (managed default: vision-v1)."),
- optional_string("memory_provider", "Provider string for memory-tree extract + summarise."),
- optional_string("embeddings_provider", "Provider string for embedding generation."),
- optional_string("heartbeat_provider", "Provider string for the heartbeat background-reasoning loop."),
- optional_string("learning_provider", "Provider string for learning / reflection passes."),
- optional_string("subconscious_provider", "Provider string for subconscious evaluation."),
- ],
- outputs: vec![json_output("snapshot", "Updated config snapshot.")],
- },
- "update_memory_settings" => ControllerSchema {
- namespace: "config",
- function: "update_memory_settings",
- description: "Update memory backend and embedding settings.",
- inputs: vec![
- optional_string("backend", "Memory backend identifier."),
- FieldSchema {
- name: "auto_save",
- ty: TypeSchema::Option(Box::new(TypeSchema::Bool)),
- comment: "Enable auto-save.",
- required: false,
- },
- optional_string("embedding_provider", "Embedding provider identifier."),
- optional_string("embedding_model", "Embedding model identifier."),
- FieldSchema {
- name: "embedding_dimensions",
- ty: TypeSchema::Option(Box::new(TypeSchema::U64)),
- comment: "Embedding dimensions.",
- required: false,
- },
- optional_string(
- "memory_window",
- "Stepped long-term memory window preset: minimal | balanced | extended | maximum.",
- ),
- ],
- outputs: vec![json_output("snapshot", "Updated config snapshot.")],
- },
- "update_runtime_settings" => ControllerSchema {
- namespace: "config",
- function: "update_runtime_settings",
- description: "Update runtime execution strategy settings.",
- inputs: vec![
- optional_string("kind", "Runtime kind."),
- optional_bool("reasoning_enabled", "Enable reasoning mode."),
- ],
- outputs: vec![json_output("snapshot", "Updated config snapshot.")],
- },
- "get_autonomy_settings" => ControllerSchema {
- namespace: "config",
- function: "get_autonomy_settings",
- description: "Get the agent access-mode settings (autonomy level, workspace confinement, trusted roots, command allow-list, forbidden paths).",
- inputs: vec![],
- outputs: vec![json_output("autonomy", "Current [autonomy] config block.")],
- },
- "update_autonomy_settings" => ControllerSchema {
- namespace: "config",
- function: "update_autonomy_settings",
- description: "Update the agent access mode: autonomy level, workspace confinement, trusted-roots allow-list, command allow-list, forbidden paths, and OS-install permission. Applies live to active sessions.",
- inputs: vec![
- optional_string("level", "Autonomy level: readonly | supervised | full."),
- optional_bool("workspace_only", "Confine file/path access to the workspace directory."),
- FieldSchema {
- name: "allowed_commands",
- ty: TypeSchema::Option(Box::new(TypeSchema::Array(Box::new(TypeSchema::String)))),
- comment: "Replace the shell command allow-list (array of base command names).",
- required: false,
- },
- FieldSchema {
- name: "forbidden_paths",
- ty: TypeSchema::Option(Box::new(TypeSchema::Array(Box::new(TypeSchema::String)))),
- comment: "Replace the forbidden-paths denylist (array of path prefixes).",
- required: false,
- },
- FieldSchema {
- name: "trusted_roots",
- ty: TypeSchema::Option(Box::new(TypeSchema::Json)),
- comment: "Replace the trusted-roots allow-list: array of {path, access: read|readwrite}. Grants access outside the workspace; credential dirs (~/.ssh, ~/.gnupg, ~/.aws) stay blocked regardless.",
- required: false,
- },
- optional_bool("allow_tool_install", "Allow the agent to install OS packages via install_tool (intended for Full mode)."),
- FieldSchema {
- name: "max_actions_per_hour",
- ty: TypeSchema::Option(Box::new(TypeSchema::U64)),
- comment: "Rate limit for side-effecting actions per hour.",
- required: false,
- },
- FieldSchema {
- name: "auto_approve",
- ty: TypeSchema::Option(Box::new(TypeSchema::Array(Box::new(TypeSchema::String)))),
- comment: "Replace the \"Always allow\" allowlist (array of tool names the agent runs without an approval prompt). Empty array clears it.",
- required: false,
- },
- optional_bool("require_task_plan_approval", "Require approval before an agent executes a task-board plan."),
- optional_bool("auto_approve_all", "When true, auto-approve all tool calls without prompting. SubconsciousTainted and Unknown origins still denied. Hard security blocks unaffected."),
- ],
- outputs: vec![json_output("snapshot", "Updated config snapshot.")],
- },
- "get_privacy_mode" => ControllerSchema {
- namespace: "config",
- function: "get_privacy_mode",
- description: "Get the active Privacy Mode (data-egress posture): local_only | standard | sensitive. Distinct from the autonomy access mode.",
- inputs: vec![],
- outputs: vec![json_output("mode", "Current privacy mode: local_only | standard | sensitive.")],
- },
- "set_privacy_mode" => ControllerSchema {
- namespace: "config",
- function: "set_privacy_mode",
- description: "Set the Privacy Mode (data-egress posture). local_only blocks external model calls at the inference chokepoint. Applies live to active sessions without a restart.",
- inputs: vec![
- optional_string("mode", "Privacy mode: local_only | standard | sensitive."),
- ],
- outputs: vec![json_output("mode", "Updated privacy mode.")],
- },
- "get_agent_settings" => ControllerSchema {
- namespace: "config",
- function: "get_agent_settings",
- description: "Read agent execution settings: the action/tool wall-clock timeout, the runtime-effective value, and whether the OPENHUMAN_TOOL_TIMEOUT_SECS env var overrides it.",
- inputs: vec![],
- outputs: vec![json_output(
- "settings",
- "Agent settings: agent_timeout_secs, effective_timeout_secs, env_override, min_timeout_secs, max_timeout_secs.",
- )],
- },
- "update_agent_settings" => ControllerSchema {
- namespace: "config",
- function: "update_agent_settings",
- description: "Update agent execution settings. Currently the action/tool wall-clock timeout (seconds). Applies to the next tool call without a restart; the OPENHUMAN_TOOL_TIMEOUT_SECS env var still overrides it when set.",
- inputs: vec![FieldSchema {
- name: "agent_timeout_secs",
- ty: TypeSchema::Option(Box::new(TypeSchema::U64)),
- comment: "Wall-clock timeout for a single tool/action execution, in seconds (1–3600). Extend this when large local models are interrupted before finishing.",
- required: false,
- }],
- outputs: vec![json_output("snapshot", "Updated config snapshot.")],
- },
- "update_browser_settings" => ControllerSchema {
- namespace: "config",
- function: "update_browser_settings",
- description: "Update browser automation settings.",
- inputs: vec![
- optional_bool("enabled", "Enable browser integration."),
- optional_string(
- "backend",
- "Browser backend: agent_browser, playwright, rust_native, computer_use, or auto.",
- ),
- ],
- outputs: vec![json_output("snapshot", "Updated config snapshot.")],
- },
- "update_local_ai_settings" => ControllerSchema {
- namespace: "config",
- function: "update_local_ai_settings",
- description:
- "Update the local AI runtime master switch and per-feature usage flags.",
- inputs: vec![
- optional_bool(
- "runtime_enabled",
- "Master switch — when false, no subsystem uses the selected local AI runtime.",
- ),
- optional_bool(
- "opt_in_confirmed",
- "MVP opt-in marker. Bootstrap hard-overrides to disabled when this is false, \
- regardless of `runtime_enabled`. Set in tandem with `runtime_enabled` from the \
- unified AI panel.",
- ),
- optional_string(
- "provider",
- "Local provider identifier. Supported values: ollama, lm_studio, omlx.",
- ),
- optional_json(
- "base_url",
- "Provider base URL string, or null to clear. For LM Studio this defaults to http://localhost:1234/v1.",
- ),
- optional_string(
- "api_key",
- "Bearer credential for keyed local runtimes such as OMLX. Pass an empty string to clear.",
- ),
- optional_string("model_id", "Default local chat model identifier."),
- optional_string("chat_model_id", "Local chat model identifier."),
- optional_bool(
- "usage_embeddings",
- "Use the local model for embedding generation (when runtime_enabled).",
- ),
- optional_bool(
- "usage_heartbeat",
- "Use the local model inside the heartbeat loop (when runtime_enabled).",
- ),
- optional_bool(
- "usage_learning_reflection",
- "Use the local model for learning/reflection passes (when runtime_enabled).",
- ),
- optional_bool(
- "usage_subconscious",
- "Use the local model for subconscious evaluation (when runtime_enabled).",
- ),
- ],
- outputs: vec![json_output("snapshot", "Updated config snapshot.")],
- },
- "resolve_api_url" => ControllerSchema {
- namespace: "config",
- function: "resolve_api_url",
- description: "Resolve effective API base URL using config/env/default from core.",
- inputs: vec![],
- outputs: vec![FieldSchema {
- name: "api_url",
- ty: TypeSchema::String,
- comment: "Resolved backend API URL.",
- required: true,
- }],
- },
- "get_runtime_flags" => ControllerSchema {
- namespace: "config",
- function: "get_runtime_flags",
- description: "Read environment-driven runtime flags.",
- inputs: vec![],
- outputs: vec![FieldSchema {
- name: "flags",
- ty: TypeSchema::Ref("RuntimeFlagsOut"),
- comment: "Runtime flag state.",
- required: true,
- }],
- },
- "set_browser_allow_all" => ControllerSchema {
- namespace: "config",
- function: "set_browser_allow_all",
- description: "Disable browser allow-all mode, or enable it only when operator opt-in is present.",
- inputs: vec![FieldSchema {
- name: "enabled",
- ty: TypeSchema::Bool,
- comment: "Whether to enable browser allow-all mode. Runtime enable is refused unless OPENHUMAN_BROWSER_ALLOW_ALL_RPC_ENABLE=1.",
- required: true,
- }],
- outputs: vec![FieldSchema {
- name: "flags",
- ty: TypeSchema::Ref("RuntimeFlagsOut"),
- comment: "Updated runtime flag state.",
- required: true,
- }],
- },
- "workspace_onboarding_flag_exists" => ControllerSchema {
- namespace: "config",
- function: "workspace_onboarding_flag_exists",
- description: "Check if onboarding flag file exists in workspace.",
- inputs: vec![FieldSchema {
- name: "flag_name",
- ty: TypeSchema::Option(Box::new(TypeSchema::String)),
- comment: "Optional onboarding flag name override.",
- required: false,
- }],
- outputs: vec![FieldSchema {
- name: "exists",
- ty: TypeSchema::Bool,
- comment: "True when the flag file is present.",
- required: true,
- }],
- },
- "workspace_onboarding_flag_set" => ControllerSchema {
- namespace: "config",
- function: "workspace_onboarding_flag_set",
- description: "Create or remove the onboarding flag file in workspace.",
- inputs: vec![
- FieldSchema {
- name: "flag_name",
- ty: TypeSchema::Option(Box::new(TypeSchema::String)),
- comment: "Optional onboarding flag name override.",
- required: false,
- },
- FieldSchema {
- name: "value",
- ty: TypeSchema::Bool,
- comment: "True to create, false to remove.",
- required: true,
- },
- ],
- outputs: vec![FieldSchema {
- name: "exists",
- ty: TypeSchema::Bool,
- comment: "True when the flag file is present after the operation.",
- required: true,
- }],
- },
- "update_analytics_settings" => ControllerSchema {
- namespace: "config",
- function: "update_analytics_settings",
- description: "Enable or disable anonymized analytics and error reporting.",
- inputs: vec![optional_bool(
- "enabled",
- "Enable anonymized analytics and crash reports.",
- )],
- outputs: vec![json_output("snapshot", "Updated config snapshot.")],
- },
- "get_analytics_settings" => ControllerSchema {
- namespace: "config",
- function: "get_analytics_settings",
- description: "Read current analytics settings.",
- inputs: vec![],
- outputs: vec![FieldSchema {
- name: "enabled",
- ty: TypeSchema::Bool,
- comment: "Whether anonymized analytics is enabled.",
- required: true,
- }],
- },
- "get_dashboard_settings" => ControllerSchema {
- namespace: "config",
- function: "get_dashboard_settings",
- description: "Read dashboard settings, including the local architecture diagram viewer.",
- inputs: vec![],
- outputs: vec![FieldSchema {
- name: "dashboard",
- ty: TypeSchema::Json,
- comment: "Current [dashboard] config block.",
- required: true,
- }],
- },
- "update_search_settings" => ControllerSchema {
- namespace: "config",
- function: "update_search_settings",
- description: "Update search engine selection and BYO API credentials.",
- inputs: vec![
- optional_string(
- "engine",
- "Active engine: disabled | managed | parallel | brave | querit | exa.",
- ),
- FieldSchema {
- name: "max_results",
- ty: TypeSchema::Option(Box::new(TypeSchema::U64)),
- comment: "Maximum results per query (1-20).",
- required: false,
- },
- FieldSchema {
- name: "timeout_secs",
- ty: TypeSchema::Option(Box::new(TypeSchema::U64)),
- comment: "Per-request timeout in seconds (1-120).",
- required: false,
- },
- optional_string(
- "parallel_api_key",
- "Parallel API key (empty string clears the stored key).",
- ),
- optional_string(
- "brave_api_key",
- "Brave Search API key (empty string clears the stored key).",
- ),
- optional_string(
- "querit_api_key",
- "Querit API key (empty string clears the stored key).",
- ),
- optional_string(
- "exa_api_key",
- "Exa API key (empty string clears the stored key).",
- ),
- FieldSchema {
- name: "allowed_domains",
- ty: TypeSchema::Option(Box::new(TypeSchema::Array(Box::new(
- TypeSchema::String,
- )))),
- comment: "Websites the assistant may open/read (web_fetch/curl). Exact hosts match their subdomains; \"*\" allows all public sites; empty blocks all web access.",
- required: false,
- },
- FieldSchema {
- name: "allow_all",
- ty: TypeSchema::Option(Box::new(TypeSchema::Bool)),
- comment: "\"Allow all sites\" toggle. true sets the allowlist to [\"*\"]; false drops the wildcard, keeping explicit hosts.",
- required: false,
- },
- ],
- outputs: vec![json_output("snapshot", "Updated config snapshot.")],
- },
- "get_search_settings" => ControllerSchema {
- namespace: "config",
- function: "get_search_settings",
- description:
- "Read search engine settings. API keys are surfaced as presence booleans only.",
- inputs: vec![],
- outputs: vec![json_output(
- "settings",
- "Engine, effective engine, limits, and per-provider configuration flags.",
- )],
- },
- "get_activity_level_settings" => ControllerSchema {
- namespace: "config",
- function: "get_activity_level_settings",
- description: "Get the agent activity level (0–4) and its derived settings: sync cadence, heartbeat/subconscious toggles, token budget, estimated monthly cost.",
- inputs: vec![],
- outputs: vec![json_output("settings", "Activity level settings with cost estimates.")],
- },
- "update_activity_level_settings" => ControllerSchema {
- namespace: "config",
- function: "update_activity_level_settings",
- description: "Set the agent activity level. Immediately updates the scheduler gate mode and persists the change.",
- inputs: vec![optional_string("level", "Activity level: off | minimal | moderate | active | always_on (or 0–4).")],
- outputs: vec![json_output("settings", "Updated activity level settings with cost estimates.")],
- },
- "get_memory_sync_settings" => ControllerSchema {
- namespace: "config",
- function: "get_memory_sync_settings",
- description: "Get the global memory-sync cadence applied to all opted-in sources: stored value, resolved selected cadence, manual/default flags, the 24h default, and the preset options (4h/12h/24h).",
- inputs: vec![],
- outputs: vec![json_output("settings", "Memory sync schedule settings.")],
- },
- "update_memory_sync_settings" => ControllerSchema {
- namespace: "config",
- function: "update_memory_sync_settings",
- description: "Set the global memory-sync cadence. Omit/null resets to the default; 0 means Manual only (auto-sync disabled); a positive value is seconds between syncs. Takes effect on the next scheduler tick.",
- inputs: vec![FieldSchema {
- name: "sync_interval_secs",
- ty: TypeSchema::Option(Box::new(TypeSchema::U64)),
- comment: "Seconds between auto-syncs. null = default (24h); 0 = Manual only; n>0 = sync every n seconds.",
- required: false,
- }],
- outputs: vec![json_output("settings", "Updated memory sync schedule settings.")],
- },
- "get_sandbox_settings" => ControllerSchema {
- namespace: "config",
- function: "get_sandbox_settings",
- description: "Get sandbox execution backend settings: selected backend, Docker image/limits, env passthrough, Docker availability, and detected OS backend.",
- inputs: vec![],
- outputs: vec![json_output("settings", "Sandbox settings with status.")],
- },
- "update_sandbox_settings" => ControllerSchema {
- namespace: "config",
- function: "update_sandbox_settings",
- description: "Update sandbox execution backend settings: backend selection, Docker image, memory/CPU limits, and env passthrough. Applies to new agent sessions.",
- inputs: vec![
- optional_string("backend", "Sandbox backend: auto | landlock | firejail | bubblewrap | docker | none."),
- optional_bool("enabled", "Enable or disable sandbox execution."),
- optional_string("docker_image", "Docker image for sandboxed execution (e.g. alpine:3.20)."),
- FieldSchema {
- name: "docker_memory_limit_mb",
- ty: TypeSchema::Option(Box::new(TypeSchema::U64)),
- comment: "Docker container memory limit in MB.",
- required: false,
- },
- FieldSchema {
- name: "docker_cpu_limit",
- ty: TypeSchema::Option(Box::new(TypeSchema::F64)),
- comment: "Docker container CPU limit (e.g. 1.0 = one core).",
- required: false,
- },
- FieldSchema {
- name: "env_passthrough",
- ty: TypeSchema::Option(Box::new(TypeSchema::Array(Box::new(TypeSchema::String)))),
- comment: "Environment variables to pass through into the sandbox.",
- required: false,
- },
- ],
- outputs: vec![json_output("snapshot", "Updated config snapshot.")],
- },
- "agent_server_status" => ControllerSchema {
- namespace: "config",
- function: "agent_server_status",
- description: "Return agent server runtime URL and status.",
- inputs: vec![],
- outputs: vec![json_output("status", "Agent server status payload.")],
- },
- "reset_local_data" => ControllerSchema {
- namespace: "config",
- function: "reset_local_data",
- description:
- "Delete local OpenHuman data for the active config/workspace so the next restart boots clean.",
- inputs: vec![],
- outputs: vec![json_output("result", "Reset result with removed paths.")],
- },
- "get_data_paths" => ControllerSchema {
- namespace: "config",
- function: "get_data_paths",
- description:
- "Resolve the OpenHuman data directories (current workspace, default ~/.openhuman, active workspace marker) that reset_local_data would remove. Read-only — performs no filesystem changes.",
- inputs: vec![optional_string(
- "user_id",
- "Resolve paths for this specific user id (users/<id>) instead of the active-user marker. Clear App Data passes this because it signs the user out — removing the marker — before deleting the data.",
- )],
- outputs: vec![json_output(
- "paths",
- "Resolved data paths: current_openhuman_dir, default_openhuman_dir, active_workspace_marker_path.",
- )],
- },
- "get_agent_paths" => ControllerSchema {
- namespace: "config",
- function: "get_agent_paths",
- description:
- "Resolve the agent's filesystem roots (action_dir, workspace_dir, projects_dir) so the UI can render live values instead of hard-coded strings. Read-only. Also returns `action_dir_env_override: bool` so the UI knows when OPENHUMAN_ACTION_DIR is forcing the value (Settings → action_dir editing disabled in that case).",
- inputs: vec![],
- outputs: vec![json_output(
- "paths",
- "Resolved agent paths: action_dir (acting-tool CWD), workspace_dir (internal state, agent-blocked), projects_dir (default projects home), action_dir_source (env | override | default).",
- )],
- },
- "update_agent_paths" => ControllerSchema {
- namespace: "config",
- function: "update_agent_paths",
- description:
- "Update the agent's editable filesystem roots. Currently only action_dir (the acting-tool sandbox). The path must be absolute; a missing directory is auto-created; it cannot equal the internal workspace_dir. An empty string clears the override and reverts to the default. Applies to new sessions immediately (live policy hot-swap), no restart. OPENHUMAN_ACTION_DIR still overrides at runtime when set.",
- inputs: vec![FieldSchema {
- name: "action_dir",
- ty: TypeSchema::Option(Box::new(TypeSchema::String)),
- comment: "New absolute action sandbox path. Empty string clears the override (revert to default). Omit to leave unchanged.",
- required: false,
- }],
- outputs: vec![json_output(
- "paths",
- "Updated agent paths (same shape as get_agent_paths): action_dir, workspace_dir, projects_dir, action_dir_source.",
- )],
- },
- "get_onboarding_completed" => ControllerSchema {
- namespace: "config",
- function: "get_onboarding_completed",
- description: "Read whether the user has completed the onboarding flow.",
- inputs: vec![],
- outputs: vec![FieldSchema {
- name: "completed",
- ty: TypeSchema::Bool,
- comment: "True when onboarding has been completed.",
- required: true,
- }],
- },
- "get_dictation_settings" => ControllerSchema {
- namespace: "config",
- function: "get_dictation_settings",
- description: "Read current voice dictation settings.",
- inputs: vec![],
- outputs: vec![json_output("settings", "Dictation settings payload.")],
- },
- "update_dictation_settings" => ControllerSchema {
- namespace: "config",
- function: "update_dictation_settings",
- description: "Update voice dictation settings.",
- inputs: vec![
- optional_bool("enabled", "Enable voice dictation."),
- optional_string("hotkey", "Global hotkey string (e.g. Fn)."),
- optional_string("activation_mode", "Activation mode: toggle or push."),
- optional_bool("llm_refinement", "Enable LLM post-processing of transcription."),
- optional_bool("streaming", "Enable WebSocket streaming transcription."),
- FieldSchema {
- name: "streaming_interval_ms",
- ty: TypeSchema::Option(Box::new(TypeSchema::U64)),
- comment: "Interval between streaming inference passes (ms).",
- required: false,
- },
- ],
- outputs: vec![json_output("snapshot", "Updated config snapshot.")],
- },
- "get_voice_server_settings" => ControllerSchema {
- namespace: "config",
- function: "get_voice_server_settings",
- description: "Read current voice server settings.",
- inputs: vec![],
- outputs: vec![json_output("settings", "Voice server settings payload.")],
- },
- "update_voice_server_settings" => ControllerSchema {
- namespace: "config",
- function: "update_voice_server_settings",
- description: "Update voice server settings.",
- inputs: vec![
- optional_bool("auto_start", "Start the voice server automatically with the core."),
- optional_string("hotkey", "Voice server hotkey string (e.g. Fn)."),
- optional_string("activation_mode", "Activation mode: tap or push."),
- optional_bool("skip_cleanup", "Skip LLM cleanup and keep dictation verbatim."),
- FieldSchema {
- name: "min_duration_secs",
- ty: TypeSchema::Option(Box::new(TypeSchema::F64)),
- comment: "Minimum recording duration in seconds.",
- required: false,
- },
- FieldSchema {
- name: "silence_threshold",
- ty: TypeSchema::Option(Box::new(TypeSchema::F64)),
- comment: "RMS energy threshold for silence detection.",
- required: false,
- },
- FieldSchema {
- name: "custom_dictionary",
- ty: TypeSchema::Option(Box::new(TypeSchema::Json)),
- comment: "Custom vocabulary words to bias the STT engine toward.",
- required: false,
- },
- optional_bool(
- "always_on_enabled",
- "Continuous always-on listening (no hotkey). Opt-in.",
- ),
- optional_string(
- "wake_word",
- "Always-on wake word; utterances must contain it (default 'Hey Tiny').",
- ),
- optional_string(
- "stt_engine",
- "Hosted speech-to-text engine: backend, elevenlabs, or openai.",
- ),
- ],
- outputs: vec![json_output("snapshot", "Updated config snapshot.")],
- },
- "set_onboarding_completed" => ControllerSchema {
- namespace: "config",
- function: "set_onboarding_completed",
- description: "Mark the onboarding flow as completed or reset it.",
- inputs: vec![FieldSchema {
- name: "value",
- ty: TypeSchema::Bool,
- comment: "True to mark completed, false to reset.",
- required: true,
- }],
- outputs: vec![FieldSchema {
- name: "completed",
- ty: TypeSchema::Bool,
- comment: "Updated onboarding completed state.",
- required: true,
- }],
- },
- "update_composio_trigger_settings" => ControllerSchema {
- namespace: "config",
- function: "update_composio_trigger_settings",
- description:
- "Update Composio trigger-triage settings. When triage is disabled the \
- local LLM is NOT invoked per trigger — events are still archived to \
- trigger history.",
- inputs: vec![
- optional_bool(
- "triage_disabled",
- "When true, skip the LLM triage turn for all Composio triggers globally.",
- ),
- FieldSchema {
- name: "triage_disabled_toolkits",
- ty: TypeSchema::Option(Box::new(TypeSchema::Array(Box::new(
- TypeSchema::String,
- )))),
- comment: "Toolkit slugs that skip LLM triage (e.g. [\"gmail\", \"slack\"]).",
- required: false,
- },
- ],
- outputs: vec![json_output("snapshot", "Updated config snapshot.")],
- },
- "get_composio_trigger_settings" => ControllerSchema {
- namespace: "config",
- function: "get_composio_trigger_settings",
- description: "Read current Composio trigger-triage settings.",
- inputs: vec![],
- outputs: vec![
- FieldSchema {
- name: "triage_disabled",
- ty: TypeSchema::Bool,
- comment: "Whether the global triage-disabled flag is set.",
- required: true,
- },
- FieldSchema {
- name: "triage_disabled_toolkits",
- ty: TypeSchema::Array(Box::new(TypeSchema::String)),
- comment: "Toolkit slugs that skip LLM triage.",
- required: true,
- },
- ],
- },
- _ => ControllerSchema {
- namespace: "config",
- function: "unknown",
- description: "Unknown config controller function.",
- inputs: vec![],
- outputs: vec![FieldSchema {
- name: "error",
- ty: TypeSchema::String,
- comment: "Lookup error details.",
- required: true,
- }],
- },
+ if let Some(schema) = schemas_schema_part_01::lookup(function) {
+ return schema;
+ }
+ if let Some(schema) = schemas_schema_part_02::lookup(function) {
+ return schema;
+ }
+ ControllerSchema {
+ namespace: "config",
+ function: "unknown",
+ description: "Unknown config controller function.",
+ inputs: vec![],
+ outputs: vec![FieldSchema {
+ name: "error",
+ ty: TypeSchema::String,
+ comment: "Lookup error details.",
+ required: true,
+ }],
}
}
diff --git a/src/openhuman/config/schemas/schemas_schema_part_01.rs b/src/openhuman/config/schemas/schemas_schema_part_01.rs
new file mode 100644
index 0000000000..52e150bcc2
--- /dev/null
+++ b/src/openhuman/config/schemas/schemas_schema_part_01.rs
@@ -0,0 +1,617 @@
+use super::*;
+
+pub(super) fn lookup(function: &str) -> Option<ControllerSchema> {
+ match function {
+"get_config" => Some( ControllerSchema {
+ namespace: "config",
+ function: "get",
+ description: "Read persisted config snapshot and resolved paths.",
+ inputs: vec![],
+ outputs: vec![FieldSchema {
+ name: "snapshot",
+ ty: TypeSchema::Json,
+ comment: "Config snapshot with workspace and config paths.",
+ required: true,
+ }],
+ }),
+"get_client_config" => Some( ControllerSchema {
+ namespace: "config",
+ function: "get_client_config",
+ description: "Read safe client-facing config fields (api_url, feature flags). No secrets.",
+ inputs: vec![],
+ outputs: vec![
+ FieldSchema {
+ name: "api_url",
+ ty: TypeSchema::Option(Box::new(TypeSchema::String)),
+ comment: "Configured OpenHuman product backend URL, if any.",
+ required: false,
+ },
+ FieldSchema {
+ name: "inference_url",
+ ty: TypeSchema::Option(Box::new(TypeSchema::String)),
+ comment: "Custom OpenAI-compatible LLM endpoint, if any. When set together with an api_key, inference goes direct to this URL.",
+ required: false,
+ },
+ FieldSchema {
+ name: "default_model",
+ ty: TypeSchema::Option(Box::new(TypeSchema::String)),
+ comment: "Default model identifier.",
+ required: false,
+ },
+ FieldSchema {
+ name: "app_version",
+ ty: TypeSchema::String,
+ comment: "OpenHuman core version.",
+ required: true,
+ },
+ FieldSchema {
+ name: "api_key_set",
+ ty: TypeSchema::Bool,
+ comment: "True when a custom backend api_key is stored locally. The key itself is never returned over RPC.",
+ required: true,
+ },
+ FieldSchema {
+ name: "model_routes",
+ ty: TypeSchema::Json,
+ comment: "Persisted task-hint -> model id pairs the core router will obey. Empty when the OpenHuman built-in router is active.",
+ required: true,
+ },
+ ],
+ }),
+"update_model_settings" => Some( ControllerSchema {
+ namespace: "config",
+ function: "update_model_settings",
+ description: "Update model and backend connection settings, including a custom OpenAI-compatible backend (api_url + api_key).",
+ inputs: vec![
+ optional_string("api_url", "OpenHuman product backend URL (auth/billing/voice). Almost always left blank; the inference URL is a separate `inference_url` field."),
+ optional_string("inference_url", "Custom OpenAI-compatible LLM endpoint. When set together with `api_key`, inference goes direct to this URL instead of the OpenHuman backend. Pass an empty string to clear."),
+ optional_string("api_key", "Optional API key for the configured inference endpoint. Pass an empty string to clear a previously stored key."),
+ optional_string("default_model", "Default model id."),
+ FieldSchema {
+ name: "default_temperature",
+ ty: TypeSchema::Option(Box::new(TypeSchema::F64)),
+ comment: "Default model temperature.",
+ required: false,
+ },
+ FieldSchema {
+ name: "model_routes",
+ ty: TypeSchema::Option(Box::new(TypeSchema::Json)),
+ comment: "Optional list of {hint, model} pairs mapping task hints (reasoning, agentic, coding, summarization) to provider-specific model ids. Replaces config.model_routes wholesale; send [] to clear (e.g. when switching back to the OpenHuman built-in router).",
+ required: false,
+ },
+ FieldSchema {
+ name: "cloud_providers",
+ ty: TypeSchema::Option(Box::new(TypeSchema::Json)),
+ comment: "Optional list of cloud provider entries {id, slug, label, endpoint, auth_style}. API keys are stored separately via cloud_provider_set_key. Replaces config.cloud_providers wholesale.",
+ required: false,
+ },
+ optional_string("primary_cloud", "id of the cloud_providers entry used when a workload routes to 'cloud'. Empty string clears."),
+ optional_string("chat_provider", "Provider string for direct conversational chat workloads."),
+ optional_string("reasoning_provider", "Provider string for the main reasoning workload (e.g. 'cloud', 'ollama:llama3.1:8b', 'openai:gpt-4o')."),
+ optional_string("agentic_provider", "Provider string for sub-agent / tool-loop workloads."),
+ optional_string("coding_provider", "Provider string for code-generation workloads."),
+ optional_string("vision_provider", "Provider string for the vision / multimodal workload (managed default: vision-v1)."),
+ optional_string("memory_provider", "Provider string for memory-tree extract + summarise."),
+ optional_string("embeddings_provider", "Provider string for embedding generation."),
+ optional_string("heartbeat_provider", "Provider string for the heartbeat background-reasoning loop."),
+ optional_string("learning_provider", "Provider string for learning / reflection passes."),
+ optional_string("subconscious_provider", "Provider string for subconscious evaluation."),
+ ],
+ outputs: vec![json_output("snapshot", "Updated config snapshot.")],
+ }),
+"update_memory_settings" => Some( ControllerSchema {
+ namespace: "config",
+ function: "update_memory_settings",
+ description: "Update memory backend and embedding settings.",
+ inputs: vec![
+ optional_string("backend", "Memory backend identifier."),
+ FieldSchema {
+ name: "auto_save",
+ ty: TypeSchema::Option(Box::new(TypeSchema::Bool)),
+ comment: "Enable auto-save.",
+ required: false,
+ },
+ optional_string("embedding_provider", "Embedding provider identifier."),
+ optional_string("embedding_model", "Embedding model identifier."),
+ FieldSchema {
+ name: "embedding_dimensions",
+ ty: TypeSchema::Option(Box::new(TypeSchema::U64)),
+ comment: "Embedding dimensions.",
+ required: false,
+ },
+ optional_string(
+ "memory_window",
+ "Stepped long-term memory window preset: minimal | balanced | extended | maximum.",
+ ),
+ ],
+ outputs: vec![json_output("snapshot", "Updated config snapshot.")],
+ }),
+"update_runtime_settings" => Some( ControllerSchema {
+ namespace: "config",
+ function: "update_runtime_settings",
+ description: "Update runtime execution strategy settings.",
+ inputs: vec![
+ optional_string("kind", "Runtime kind."),
+ optional_bool("reasoning_enabled", "Enable reasoning mode."),
+ ],
+ outputs: vec![json_output("snapshot", "Updated config snapshot.")],
+ }),
+"get_autonomy_settings" => Some( ControllerSchema {
+ namespace: "config",
+ function: "get_autonomy_settings",
+ description: "Get the agent access-mode settings (autonomy level, workspace confinement, trusted roots, command allow-list, forbidden paths).",
+ inputs: vec![],
+ outputs: vec![json_output("autonomy", "Current [autonomy] config block.")],
+ }),
+"update_autonomy_settings" => Some( ControllerSchema {
+ namespace: "config",
+ function: "update_autonomy_settings",
+ description: "Update the agent access mode: autonomy level, workspace confinement, trusted-roots allow-list, command allow-list, forbidden paths, and OS-install permission. Applies live to active sessions.",
+ inputs: vec![
+ optional_string("level", "Autonomy level: readonly | supervised | full."),
+ optional_bool("workspace_only", "Confine file/path access to the workspace directory."),
+ FieldSchema {
+ name: "allowed_commands",
+ ty: TypeSchema::Option(Box::new(TypeSchema::Array(Box::new(TypeSchema::String)))),
+ comment: "Replace the shell command allow-list (array of base command names).",
+ required: false,
+ },
+ FieldSchema {
+ name: "forbidden_paths",
+ ty: TypeSchema::Option(Box::new(TypeSchema::Array(Box::new(TypeSchema::String)))),
+ comment: "Replace the forbidden-paths denylist (array of path prefixes).",
+ required: false,
+ },
+ FieldSchema {
+ name: "trusted_roots",
+ ty: TypeSchema::Option(Box::new(TypeSchema::Json)),
+ comment: "Replace the trusted-roots allow-list: array of {path, access: read|readwrite}. Grants access outside the workspace; credential dirs (~/.ssh, ~/.gnupg, ~/.aws) stay blocked regardless.",
+ required: false,
+ },
+ optional_bool("allow_tool_install", "Allow the agent to install OS packages via install_tool (intended for Full mode)."),
+ FieldSchema {
+ name: "max_actions_per_hour",
+ ty: TypeSchema::Option(Box::new(TypeSchema::U64)),
+ comment: "Rate limit for side-effecting actions per hour.",
+ required: false,
+ },
+ FieldSchema {
+ name: "auto_approve",
+ ty: TypeSchema::Option(Box::new(TypeSchema::Array(Box::new(TypeSchema::String)))),
+ comment: "Replace the \"Always allow\" allowlist (array of tool names the agent runs without an approval prompt). Empty array clears it.",
+ required: false,
+ },
+ optional_bool("require_task_plan_approval", "Require approval before an agent executes a task-board plan."),
+ optional_bool("auto_approve_all", "When true, auto-approve all tool calls without prompting. SubconsciousTainted and Unknown origins still denied. Hard security blocks unaffected."),
+ ],
+ outputs: vec![json_output("snapshot", "Updated config snapshot.")],
+ }),
+"get_privacy_mode" => Some( ControllerSchema {
+ namespace: "config",
+ function: "get_privacy_mode",
+ description: "Get the active Privacy Mode (data-egress posture): local_only | standard | sensitive. Distinct from the autonomy access mode.",
+ inputs: vec![],
+ outputs: vec![json_output("mode", "Current privacy mode: local_only | standard | sensitive.")],
+ }),
+"set_privacy_mode" => Some( ControllerSchema {
+ namespace: "config",
+ function: "set_privacy_mode",
+ description: "Set the Privacy Mode (data-egress posture). local_only blocks external model calls at the inference chokepoint. Applies live to active sessions without a restart.",
+ inputs: vec![
+ optional_string("mode", "Privacy mode: local_only | standard | sensitive."),
+ ],
+ outputs: vec![json_output("mode", "Updated privacy mode.")],
+ }),
+"get_agent_settings" => Some( ControllerSchema {
+ namespace: "config",
+ function: "get_agent_settings",
+ description: "Read agent execution settings: the action/tool wall-clock timeout, the runtime-effective value, and whether the OPENHUMAN_TOOL_TIMEOUT_SECS env var overrides it.",
+ inputs: vec![],
+ outputs: vec![json_output(
+ "settings",
+ "Agent settings: agent_timeout_secs, effective_timeout_secs, env_override, min_timeout_secs, max_timeout_secs.",
+ )],
+ }),
+"update_agent_settings" => Some( ControllerSchema {
+ namespace: "config",
+ function: "update_agent_settings",
+ description: "Update agent execution settings. Currently the action/tool wall-clock timeout (seconds). Applies to the next tool call without a restart; the OPENHUMAN_TOOL_TIMEOUT_SECS env var still overrides it when set.",
+ inputs: vec![FieldSchema {
+ name: "agent_timeout_secs",
+ ty: TypeSchema::Option(Box::new(TypeSchema::U64)),
+ comment: "Wall-clock timeout for a single tool/action execution, in seconds (1–3600). Extend this when large local models are interrupted before finishing.",
+ required: false,
+ }],
+ outputs: vec![json_output("snapshot", "Updated config snapshot.")],
+ }),
+"update_browser_settings" => Some( ControllerSchema {
+ namespace: "config",
+ function: "update_browser_settings",
+ description: "Update browser automation settings.",
+ inputs: vec![
+ optional_bool("enabled", "Enable browser integration."),
+ optional_string(
+ "backend",
+ "Browser backend: agent_browser, playwright, rust_native, computer_use, or auto.",
+ ),
+ ],
+ outputs: vec![json_output("snapshot", "Updated config snapshot.")],
+ }),
+"update_local_ai_settings" => Some( ControllerSchema {
+ namespace: "config",
+ function: "update_local_ai_settings",
+ description:
+ "Update the local AI runtime master switch and per-feature usage flags.",
+ inputs: vec![
+ optional_bool(
+ "runtime_enabled",
+ "Master switch — when false, no subsystem uses the selected local AI runtime.",
+ ),
+ optional_bool(
+ "opt_in_confirmed",
+ "MVP opt-in marker. Bootstrap hard-overrides to disabled when this is false, \
+ regardless of `runtime_enabled`. Set in tandem with `runtime_enabled` from the \
+ unified AI panel.",
+ ),
+ optional_string(
+ "provider",
+ "Local provider identifier. Supported values: ollama, lm_studio, omlx.",
+ ),
+ optional_json(
+ "base_url",
+ "Provider base URL string, or null to clear. For LM Studio this defaults to http://localhost:1234/v1.",
+ ),
+ optional_string(
+ "api_key",
+ "Bearer credential for keyed local runtimes such as OMLX. Pass an empty string to clear.",
+ ),
+ optional_string("model_id", "Default local chat model identifier."),
+ optional_string("chat_model_id", "Local chat model identifier."),
+ optional_bool(
+ "usage_embeddings",
+ "Use the local model for embedding generation (when runtime_enabled).",
+ ),
+ optional_bool(
+ "usage_heartbeat",
+ "Use the local model inside the heartbeat loop (when runtime_enabled).",
+ ),
+ optional_bool(
+ "usage_learning_reflection",
+ "Use the local model for learning/reflection passes (when runtime_enabled).",
+ ),
+ optional_bool(
+ "usage_subconscious",
+ "Use the local model for subconscious evaluation (when runtime_enabled).",
+ ),
+ ],
+ outputs: vec![json_output("snapshot", "Updated config snapshot.")],
+ }),
+"resolve_api_url" => Some( ControllerSchema {
+ namespace: "config",
+ function: "resolve_api_url",
+ description: "Resolve effective API base URL using config/env/default from core.",
+ inputs: vec![],
+ outputs: vec![FieldSchema {
+ name: "api_url",
+ ty: TypeSchema::String,
+ comment: "Resolved backend API URL.",
+ required: true,
+ }],
+ }),
+"get_runtime_flags" => Some( ControllerSchema {
+ namespace: "config",
+ function: "get_runtime_flags",
+ description: "Read environment-driven runtime flags.",
+ inputs: vec![],
+ outputs: vec![FieldSchema {
+ name: "flags",
+ ty: TypeSchema::Ref("RuntimeFlagsOut"),
+ comment: "Runtime flag state.",
+ required: true,
+ }],
+ }),
+"set_browser_allow_all" => Some( ControllerSchema {
+ namespace: "config",
+ function: "set_browser_allow_all",
+ description: "Disable browser allow-all mode, or enable it only when operator opt-in is present.",
+ inputs: vec![FieldSchema {
+ name: "enabled",
+ ty: TypeSchema::Bool,
+ comment: "Whether to enable browser allow-all mode. Runtime enable is refused unless OPENHUMAN_BROWSER_ALLOW_ALL_RPC_ENABLE=1.",
+ required: true,
+ }],
+ outputs: vec![FieldSchema {
+ name: "flags",
+ ty: TypeSchema::Ref("RuntimeFlagsOut"),
+ comment: "Updated runtime flag state.",
+ required: true,
+ }],
+ }),
+"workspace_onboarding_flag_exists" => Some( ControllerSchema {
+ namespace: "config",
+ function: "workspace_onboarding_flag_exists",
+ description: "Check if onboarding flag file exists in workspace.",
+ inputs: vec![FieldSchema {
+ name: "flag_name",
+ ty: TypeSchema::Option(Box::new(TypeSchema::String)),
+ comment: "Optional onboarding flag name override.",
+ required: false,
+ }],
+ outputs: vec![FieldSchema {
+ name: "exists",
+ ty: TypeSchema::Bool,
+ comment: "True when the flag file is present.",
+ required: true,
+ }],
+ }),
+"workspace_onboarding_flag_set" => Some( ControllerSchema {
+ namespace: "config",
+ function: "workspace_onboarding_flag_set",
+ description: "Create or remove the onboarding flag file in workspace.",
+ inputs: vec![
+ FieldSchema {
+ name: "flag_name",
+ ty: TypeSchema::Option(Box::new(TypeSchema::String)),
+ comment: "Optional onboarding flag name override.",
+ required: false,
+ },
+ FieldSchema {
+ name: "value",
+ ty: TypeSchema::Bool,
+ comment: "True to create, false to remove.",
+ required: true,
+ },
+ ],
+ outputs: vec![FieldSchema {
+ name: "exists",
+ ty: TypeSchema::Bool,
+ comment: "True when the flag file is present after the operation.",
+ required: true,
+ }],
+ }),
+"update_analytics_settings" => Some( ControllerSchema {
+ namespace: "config",
+ function: "update_analytics_settings",
+ description: "Enable or disable anonymized analytics and error reporting.",
+ inputs: vec![optional_bool(
+ "enabled",
+ "Enable anonymized analytics and crash reports.",
+ )],
+ outputs: vec![json_output("snapshot", "Updated config snapshot.")],
+ }),
+"get_analytics_settings" => Some( ControllerSchema {
+ namespace: "config",
+ function: "get_analytics_settings",
+ description: "Read current analytics settings.",
+ inputs: vec![],
+ outputs: vec![FieldSchema {
+ name: "enabled",
+ ty: TypeSchema::Bool,
+ comment: "Whether anonymized analytics is enabled.",
+ required: true,
+ }],
+ }),
+"get_dashboard_settings" => Some( ControllerSchema {
+ namespace: "config",
+ function: "get_dashboard_settings",
+ description: "Read dashboard settings, including the local architecture diagram viewer.",
+ inputs: vec![],
+ outputs: vec![FieldSchema {
+ name: "dashboard",
+ ty: TypeSchema::Json,
+ comment: "Current [dashboard] config block.",
+ required: true,
+ }],
+ }),
+"update_search_settings" => Some( ControllerSchema {
+ namespace: "config",
+ function: "update_search_settings",
+ description: "Update search engine selection and BYO API credentials.",
+ inputs: vec![
+ optional_string(
+ "engine",
+ "Active engine: disabled | managed | parallel | brave | querit | exa.",
+ ),
+ FieldSchema {
+ name: "max_results",
+ ty: TypeSchema::Option(Box::new(TypeSchema::U64)),
+ comment: "Maximum results per query (1-20).",
+ required: false,
+ },
+ FieldSchema {
+ name: "timeout_secs",
+ ty: TypeSchema::Option(Box::new(TypeSchema::U64)),
+ comment: "Per-request timeout in seconds (1-120).",
+ required: false,
+ },
+ optional_string(
+ "parallel_api_key",
+ "Parallel API key (empty string clears the stored key).",
+ ),
+ optional_string(
+ "brave_api_key",
+ "Brave Search API key (empty string clears the stored key).",
+ ),
+ optional_string(
+ "querit_api_key",
+ "Querit API key (empty string clears the stored key).",
+ ),
+ optional_string(
+ "exa_api_key",
+ "Exa API key (empty string clears the stored key).",
+ ),
+ FieldSchema {
+ name: "allowed_domains",
+ ty: TypeSchema::Option(Box::new(TypeSchema::Array(Box::new(
+ TypeSchema::String,
+ )))),
+ comment: "Websites the assistant may open/read (web_fetch/curl). Exact hosts match their subdomains; \"*\" allows all public sites; empty blocks all web access.",
+ required: false,
+ },
+ FieldSchema {
+ name: "allow_all",
+ ty: TypeSchema::Option(Box::new(TypeSchema::Bool)),
+ comment: "\"Allow all sites\" toggle. true sets the allowlist to [\"*\"]; false drops the wildcard, keeping explicit hosts.",
+ required: false,
+ },
+ ],
+ outputs: vec![json_output("snapshot", "Updated config snapshot.")],
+ }),
+"get_search_settings" => Some( ControllerSchema {
+ namespace: "config",
+ function: "get_search_settings",
+ description:
+ "Read search engine settings. API keys are surfaced as presence booleans only.",
+ inputs: vec![],
+ outputs: vec![json_output(
+ "settings",
+ "Engine, effective engine, limits, and per-provider configuration flags.",
+ )],
+ }),
+"get_activity_level_settings" => Some( ControllerSchema {
+ namespace: "config",
+ function: "get_activity_level_settings",
+ description: "Get the agent activity level (0–4) and its derived settings: sync cadence, heartbeat/subconscious toggles, token budget, estimated monthly cost.",
+ inputs: vec![],
+ outputs: vec![json_output("settings", "Activity level settings with cost estimates.")],
+ }),
+"update_activity_level_settings" => Some( ControllerSchema {
+ namespace: "config",
+ function: "update_activity_level_settings",
+ description: "Set the agent activity level. Immediately updates the scheduler gate mode and persists the change.",
+ inputs: vec![optional_string("level", "Activity level: off | minimal | moderate | active | always_on (or 0–4).")],
+ outputs: vec![json_output("settings", "Updated activity level settings with cost estimates.")],
+ }),
+"get_memory_sync_settings" => Some( ControllerSchema {
+ namespace: "config",
+ function: "get_memory_sync_settings",
+ description: "Get the global memory-sync cadence applied to all opted-in sources: stored value, resolved selected cadence, manual/default flags, the 24h default, and the preset options (4h/12h/24h).",
+ inputs: vec![],
+ outputs: vec![json_output("settings", "Memory sync schedule settings.")],
+ }),
+"update_memory_sync_settings" => Some( ControllerSchema {
+ namespace: "config",
+ function: "update_memory_sync_settings",
+ description: "Set the global memory-sync cadence. Omit/null resets to the default; 0 means Manual only (auto-sync disabled); a positive value is seconds between syncs. Takes effect on the next scheduler tick.",
+ inputs: vec![FieldSchema {
+ name: "sync_interval_secs",
+ ty: TypeSchema::Option(Box::new(TypeSchema::U64)),
+ comment: "Seconds between auto-syncs. null = default (24h); 0 = Manual only; n>0 = sync every n seconds.",
+ required: false,
+ }],
+ outputs: vec![json_output("settings", "Updated memory sync schedule settings.")],
+ }),
+"get_sandbox_settings" => Some( ControllerSchema {
+ namespace: "config",
+ function: "get_sandbox_settings",
+ description: "Get sandbox execution backend settings: selected backend, Docker image/limits, env passthrough, Docker availability, and detected OS backend.",
+ inputs: vec![],
+ outputs: vec![json_output("settings", "Sandbox settings with status.")],
+ }),
+"update_sandbox_settings" => Some( ControllerSchema {
+ namespace: "config",
+ function: "update_sandbox_settings",
+ description: "Update sandbox execution backend settings: backend selection, Docker image, memory/CPU limits, and env passthrough. Applies to new agent sessions.",
+ inputs: vec![
+ optional_string("backend", "Sandbox backend: auto | landlock | firejail | bubblewrap | docker | none."),
+ optional_bool("enabled", "Enable or disable sandbox execution."),
+ optional_string("docker_image", "Docker image for sandboxed execution (e.g. alpine:3.20)."),
+ FieldSchema {
+ name: "docker_memory_limit_mb",
+ ty: TypeSchema::Option(Box::new(TypeSchema::U64)),
+ comment: "Docker container memory limit in MB.",
+ required: false,
+ },
+ FieldSchema {
+ name: "docker_cpu_limit",
+ ty: TypeSchema::Option(Box::new(TypeSchema::F64)),
+ comment: "Docker container CPU limit (e.g. 1.0 = one core).",
+ required: false,
+ },
+ FieldSchema {
+ name: "env_passthrough",
+ ty: TypeSchema::Option(Box::new(TypeSchema::Array(Box::new(TypeSchema::String)))),
+ comment: "Environment variables to pass through into the sandbox.",
+ required: false,
+ },
+ ],
+ outputs: vec![json_output("snapshot", "Updated config snapshot.")],
+ }),
+"agent_server_status" => Some( ControllerSchema {
+ namespace: "config",
+ function: "agent_server_status",
+ description: "Return agent server runtime URL and status.",
+ inputs: vec![],
+ outputs: vec![json_output("status", "Agent server status payload.")],
+ }),
+"reset_local_data" => Some( ControllerSchema {
+ namespace: "config",
+ function: "reset_local_data",
+ description:
+ "Delete local OpenHuman data for the active config/workspace so the next restart boots clean.",
+ inputs: vec![],
+ outputs: vec![json_output("result", "Reset result with removed paths.")],
+ }),
+"get_data_paths" => Some( ControllerSchema {
+ namespace: "config",
+ function: "get_data_paths",
+ description:
+ "Resolve the OpenHuman data directories (current workspace, default ~/.openhuman, active workspace marker) that reset_local_data would remove. Read-only — performs no filesystem changes.",
+ inputs: vec![optional_string(
+ "user_id",
+ "Resolve paths for this specific user id (users/<id>) instead of the active-user marker. Clear App Data passes this because it signs the user out — removing the marker — before deleting the data.",
+ )],
+ outputs: vec![json_output(
+ "paths",
+ "Resolved data paths: current_openhuman_dir, default_openhuman_dir, active_workspace_marker_path.",
+ )],
+ }),
+"get_agent_paths" => Some( ControllerSchema {
+ namespace: "config",
+ function: "get_agent_paths",
+ description:
+ "Resolve the agent's filesystem roots (action_dir, workspace_dir, projects_dir) so the UI can render live values instead of hard-coded strings. Read-only. Also returns `action_dir_env_override: bool` so the UI knows when OPENHUMAN_ACTION_DIR is forcing the value (Settings → action_dir editing disabled in that case).",
+ inputs: vec![],
+ outputs: vec![json_output(
+ "paths",
+ "Resolved agent paths: action_dir (acting-tool CWD), workspace_dir (internal state, agent-blocked), projects_dir (default projects home), action_dir_source (env | override | default).",
+ )],
+ }),
+"update_agent_paths" => Some( ControllerSchema {
+ namespace: "config",
+ function: "update_agent_paths",
+ description:
+ "Update the agent's editable filesystem roots. Currently only action_dir (the acting-tool sandbox). The path must be absolute; a missing directory is auto-created; it cannot equal the internal workspace_dir. An empty string clears the override and reverts to the default. Applies to new sessions immediately (live policy hot-swap), no restart. OPENHUMAN_ACTION_DIR still overrides at runtime when set.",
+ inputs: vec![FieldSchema {
+ name: "action_dir",
+ ty: TypeSchema::Option(Box::new(TypeSchema::String)),
+ comment: "New absolute action sandbox path. Empty string clears the override (revert to default). Omit to leave unchanged.",
+ required: false,
+ }],
+ outputs: vec![json_output(
+ "paths",
+ "Updated agent paths (same shape as get_agent_paths): action_dir, workspace_dir, projects_dir, action_dir_source.",
+ )],
+ }),
+"get_onboarding_completed" => Some( ControllerSchema {
+ namespace: "config",
+ function: "get_onboarding_completed",
+ description: "Read whether the user has completed the onboarding flow.",
+ inputs: vec![],
+ outputs: vec![FieldSchema {
+ name: "completed",
+ ty: TypeSchema::Bool,
+ comment: "True when onboarding has been completed.",
+ required: true,
+ }],
+ }),
+"get_dictation_settings" => Some( ControllerSchema {
+ namespace: "config",
+ function: "get_dictation_settings",
+ description: "Read current voice dictation settings.",
+ inputs: vec![],
+ outputs: vec![json_output("settings", "Dictation settings payload.")],
+ }),
+ _ => None,
+ }
+}
diff --git a/src/openhuman/config/schemas/schemas_schema_part_02.rs b/src/openhuman/config/schemas/schemas_schema_part_02.rs
new file mode 100644
index 0000000000..a60f5814e9
--- /dev/null
+++ b/src/openhuman/config/schemas/schemas_schema_part_02.rs
@@ -0,0 +1,143 @@
+use super::*;
+
+pub(super) fn lookup(function: &str) -> Option<ControllerSchema> {
+ match function {
+ "update_dictation_settings" => Some(ControllerSchema {
+ namespace: "config",
+ function: "update_dictation_settings",
+ description: "Update voice dictation settings.",
+ inputs: vec![
+ optional_bool("enabled", "Enable voice dictation."),
+ optional_string("hotkey", "Global hotkey string (e.g. Fn)."),
+ optional_string("activation_mode", "Activation mode: toggle or push."),
+ optional_bool(
+ "llm_refinement",
+ "Enable LLM post-processing of transcription.",
+ ),
+ optional_bool("streaming", "Enable WebSocket streaming transcription."),
+ FieldSchema {
+ name: "streaming_interval_ms",
+ ty: TypeSchema::Option(Box::new(TypeSchema::U64)),
+ comment: "Interval between streaming inference passes (ms).",
+ required: false,
+ },
+ ],
+ outputs: vec![json_output("snapshot", "Updated config snapshot.")],
+ }),
+ "get_voice_server_settings" => Some(ControllerSchema {
+ namespace: "config",
+ function: "get_voice_server_settings",
+ description: "Read current voice server settings.",
+ inputs: vec![],
+ outputs: vec![json_output("settings", "Voice server settings payload.")],
+ }),
+ "update_voice_server_settings" => Some(ControllerSchema {
+ namespace: "config",
+ function: "update_voice_server_settings",
+ description: "Update voice server settings.",
+ inputs: vec![
+ optional_bool(
+ "auto_start",
+ "Start the voice server automatically with the core.",
+ ),
+ optional_string("hotkey", "Voice server hotkey string (e.g. Fn)."),
+ optional_string("activation_mode", "Activation mode: tap or push."),
+ optional_bool(
+ "skip_cleanup",
+ "Skip LLM cleanup and keep dictation verbatim.",
+ ),
+ FieldSchema {
+ name: "min_duration_secs",
+ ty: TypeSchema::Option(Box::new(TypeSchema::F64)),
+ comment: "Minimum recording duration in seconds.",
+ required: false,
+ },
+ FieldSchema {
+ name: "silence_threshold",
+ ty: TypeSchema::Option(Box::new(TypeSchema::F64)),
+ comment: "RMS energy threshold for silence detection.",
+ required: false,
+ },
+ FieldSchema {
+ name: "custom_dictionary",
+ ty: TypeSchema::Option(Box::new(TypeSchema::Json)),
+ comment: "Custom vocabulary words to bias the STT engine toward.",
+ required: false,
+ },
+ optional_bool(
+ "always_on_enabled",
+ "Continuous always-on listening (no hotkey). Opt-in.",
+ ),
+ optional_string(
+ "wake_word",
+ "Always-on wake word; utterances must contain it (default 'Hey Tiny').",
+ ),
+ optional_string(
+ "stt_engine",
+ "Hosted speech-to-text engine: backend, elevenlabs, or openai.",
+ ),
+ ],
+ outputs: vec![json_output("snapshot", "Updated config snapshot.")],
+ }),
+ "set_onboarding_completed" => Some(ControllerSchema {
+ namespace: "config",
+ function: "set_onboarding_completed",
+ description: "Mark the onboarding flow as completed or reset it.",
+ inputs: vec![FieldSchema {
+ name: "value",
+ ty: TypeSchema::Bool,
+ comment: "True to mark completed, false to reset.",
+ required: true,
+ }],
+ outputs: vec![FieldSchema {
+ name: "completed",
+ ty: TypeSchema::Bool,
+ comment: "Updated onboarding completed state.",
+ required: true,
+ }],
+ }),
+ "update_composio_trigger_settings" => Some(ControllerSchema {
+ namespace: "config",
+ function: "update_composio_trigger_settings",
+ description: "Update Composio trigger-triage settings. When triage is disabled the \
+ local LLM is NOT invoked per trigger — events are still archived to \
+ trigger history.",
+ inputs: vec![
+ optional_bool(
+ "triage_disabled",
+ "When true, skip the LLM triage turn for all Composio triggers globally.",
+ ),
+ FieldSchema {
+ name: "triage_disabled_toolkits",
+ ty: TypeSchema::Option(Box::new(TypeSchema::Array(Box::new(
+ TypeSchema::String,
+ )))),
+ comment: "Toolkit slugs that skip LLM triage (e.g. [\"gmail\", \"slack\"]).",
+ required: false,
+ },
+ ],
+ outputs: vec![json_output("snapshot", "Updated config snapshot.")],
+ }),
+ "get_composio_trigger_settings" => Some(ControllerSchema {
+ namespace: "config",
+ function: "get_composio_trigger_settings",
+ description: "Read current Composio trigger-triage settings.",
+ inputs: vec![],
+ outputs: vec![
+ FieldSchema {
+ name: "triage_disabled",
+ ty: TypeSchema::Bool,
+ comment: "Whether the global triage-disabled flag is set.",
+ required: true,
+ },
+ FieldSchema {
+ name: "triage_disabled_toolkits",
+ ty: TypeSchema::Array(Box::new(TypeSchema::String)),
+ comment: "Toolkit slugs that skip LLM triage.",
+ required: true,
+ },
+ ],
+ }),
+ _ => None,
+ }
+}
diff --git a/src/openhuman/flows/flows_schema_part_01.rs b/src/openhuman/flows/flows_schema_part_01.rs
new file mode 100644
index 0000000000..caf574b56b
--- /dev/null
+++ b/src/openhuman/flows/flows_schema_part_01.rs
@@ -0,0 +1,621 @@
+use super::*;
+
+pub(super) fn lookup(function: &str) -> Option<ControllerSchema> {
+ match function {
+"create" => Some( ControllerSchema {
+ namespace: "flows",
+ function: "create",
+ description: "Create a new saved automation workflow from a tinyflows graph.",
+ inputs: vec![
+ FieldSchema {
+ name: "name",
+ ty: TypeSchema::String,
+ comment: "Human-readable flow name.",
+ required: true,
+ },
+ FieldSchema {
+ name: "graph",
+ ty: TypeSchema::Json,
+ comment:
+ "A tinyflows WorkflowGraph (nodes + edges); validated and migrated on save.",
+ required: true,
+ },
+ require_approval_input(),
+ strict_input(),
+ ],
+ outputs: vec![flow_output()],
+ }),
+"duplicate" => Some( ControllerSchema {
+ namespace: "flows",
+ function: "duplicate",
+ description: "Duplicate a saved flow: create an independent copy of its graph under a \
+ new id, with the name suffixed \" (copy)\". The copy is created DISABLED \
+ and is NOT schedule/trigger-bound, so it never immediately fires — the \
+ user enables it explicitly once reviewed. Run history does not carry over.",
+ inputs: vec![id_input("Identifier of the flow to duplicate.")],
+ outputs: vec![flow_output()],
+ }),
+"validate" => Some( ControllerSchema {
+ namespace: "flows",
+ function: "validate",
+ description: "Validate a tinyflows graph without saving it: reports structural \
+ validity plus non-fatal warnings (e.g. a trigger kind that does not \
+ fire automatically yet).",
+ inputs: vec![FieldSchema {
+ name: "graph",
+ ty: TypeSchema::Json,
+ comment: "A tinyflows WorkflowGraph (nodes + edges) to validate and migrate.",
+ required: true,
+ }],
+ outputs: vec![
+ FieldSchema {
+ name: "valid",
+ ty: TypeSchema::Bool,
+ comment: "True when the graph is structurally valid.",
+ required: true,
+ },
+ FieldSchema {
+ name: "errors",
+ ty: TypeSchema::Array(Box::new(TypeSchema::String)),
+ comment: "Structural validation errors; empty when `valid`.",
+ required: true,
+ },
+ FieldSchema {
+ name: "warnings",
+ ty: TypeSchema::Array(Box::new(TypeSchema::String)),
+ comment: "Non-fatal warnings (e.g. an unfired trigger kind); the graph is \
+ still saveable/enable-able.",
+ required: true,
+ },
+ ],
+ }),
+"import" => Some( ControllerSchema {
+ namespace: "flows",
+ function: "import",
+ description: "Import a workflow definition WITHOUT saving it: parse a native tinyflows \
+ graph or an n8n workflow export, migrate + validate it, and return the \
+ normalized WorkflowGraph plus non-fatal import warnings. The caller opens \
+ the result on the canvas as a draft and Saves via the normal gate — \
+ import never persists or enables anything.",
+ inputs: vec![
+ FieldSchema {
+ name: "graph",
+ ty: TypeSchema::Json,
+ comment: "The workflow JSON to import: a tinyflows WorkflowGraph (native) or \
+ an n8n workflow export.",
+ required: true,
+ },
+ FieldSchema {
+ name: "format",
+ ty: TypeSchema::Option(Box::new(TypeSchema::Enum {
+ variants: vec!["native", "n8n", "auto"],
+ })),
+ comment: "Source format: `native` (tinyflows), `n8n`, or `auto` (default — \
+ detect by shape).",
+ required: false,
+ },
+ ],
+ outputs: vec![
+ FieldSchema {
+ name: "graph",
+ ty: TypeSchema::Json,
+ comment: "The normalized, migrated + validated WorkflowGraph, ready to open \
+ as an editable draft.",
+ required: true,
+ },
+ FieldSchema {
+ name: "warnings",
+ ty: TypeSchema::Array(Box::new(TypeSchema::String)),
+ comment: "Non-fatal import warnings (unmapped n8n node types, untranslated \
+ expressions, a synthesized/demoted trigger). Empty for a clean \
+ native import.",
+ required: true,
+ },
+ ],
+ }),
+"get" => Some( ControllerSchema {
+ namespace: "flows",
+ function: "get",
+ description: "Load one saved flow by id.",
+ inputs: vec![id_input("Identifier of the flow to load.")],
+ outputs: vec![flow_output()],
+ }),
+"list" => Some( ControllerSchema {
+ namespace: "flows",
+ function: "list",
+ description: "List all saved flows.",
+ inputs: vec![],
+ outputs: vec![FieldSchema {
+ name: "flows",
+ ty: TypeSchema::Array(Box::new(TypeSchema::Ref("Flow"))),
+ comment: "Flows currently stored in the workspace.",
+ required: true,
+ }],
+ }),
+"list_connections" => Some( ControllerSchema {
+ namespace: "flows",
+ function: "list_connections",
+ description: "List the connection sources a flow node's `connection_ref` can attach \
+ to: Composio connected accounts (kind `composio`) and stored HTTP \
+ credentials (kind `http`). Returns only non-secret metadata — ids, \
+ display labels, kind, and (for Composio) the connected account's own \
+ `platform_user_id` — never any secret material (OAuth/bearer tokens, \
+ passwords, and API keys stay server-side and are injected only at \
+ execution time).",
+ inputs: vec![],
+ outputs: vec![FieldSchema {
+ name: "connections",
+ ty: TypeSchema::Array(Box::new(TypeSchema::Object {
+ fields: flow_connection_fields(),
+ })),
+ comment: "Resolvable connections for the flows picker (composio + http), \
+ secret-free.",
+ required: true,
+ }],
+ }),
+"update" => Some( ControllerSchema {
+ namespace: "flows",
+ function: "update",
+ description: "Update a saved flow's name and/or graph; re-validates before persisting.",
+ inputs: vec![
+ id_input("Identifier of the flow to update."),
+ FieldSchema {
+ name: "name",
+ ty: TypeSchema::Option(Box::new(TypeSchema::String)),
+ comment: "New name, if changing it.",
+ required: false,
+ },
+ FieldSchema {
+ name: "graph",
+ ty: TypeSchema::Option(Box::new(TypeSchema::Json)),
+ comment: "Replacement WorkflowGraph, if changing it.",
+ required: false,
+ },
+ require_approval_input(),
+ strict_input(),
+ expected_version_input(),
+ ],
+ outputs: vec![flow_output()],
+ }),
+"delete" => Some( ControllerSchema {
+ namespace: "flows",
+ function: "delete",
+ description: "Delete a saved flow by id.",
+ inputs: vec![id_input("Identifier of the flow to delete.")],
+ outputs: vec![FieldSchema {
+ name: "result",
+ ty: TypeSchema::Object {
+ fields: vec![
+ FieldSchema {
+ name: "id",
+ ty: TypeSchema::String,
+ comment: "Identifier that was requested for removal.",
+ required: true,
+ },
+ FieldSchema {
+ name: "removed",
+ ty: TypeSchema::Bool,
+ comment: "True when the flow was removed.",
+ required: true,
+ },
+ ],
+ },
+ comment: "Removal result payload.",
+ required: true,
+ }],
+ }),
+"set_enabled" => Some( ControllerSchema {
+ namespace: "flows",
+ function: "set_enabled",
+ description: "Enable or disable a saved flow.",
+ inputs: vec![
+ id_input("Identifier of the flow to toggle."),
+ FieldSchema {
+ name: "enabled",
+ ty: TypeSchema::Bool,
+ comment: "New enabled state.",
+ required: true,
+ },
+ ],
+ outputs: vec![flow_output()],
+ }),
+"run" => Some( ControllerSchema {
+ namespace: "flows",
+ function: "run",
+ description:
+ "Run a saved flow to completion (or until it pauses on a human-approval gate).",
+ inputs: vec![
+ id_input("Identifier of the flow to run."),
+ FieldSchema {
+ name: "input",
+ ty: TypeSchema::Option(Box::new(TypeSchema::Json)),
+ comment: "Trigger payload seeded into the run; defaults to null.",
+ required: false,
+ },
+ FieldSchema {
+ name: "inputs",
+ ty: TypeSchema::Option(Box::new(TypeSchema::Json)),
+ comment: "Values for the flow's declared workflow inputs, keyed by name \
+ (read the flow's `graph.inputs` for the declarations). Missing \
+ required values, wrong types, and undeclared names are rejected \
+ before the run starts. Distinct from `input`, which is the \
+ free-form trigger payload.",
+ required: false,
+ },
+ ],
+ outputs: vec![FieldSchema {
+ name: "result",
+ ty: TypeSchema::Object {
+ fields: run_output_fields(),
+ },
+ comment: "Run outcome payload.",
+ required: true,
+ }],
+ }),
+"run_detached" => Some( ControllerSchema {
+ namespace: "flows",
+ function: "run_detached",
+ description: "Start a saved flow WITHOUT waiting for it to finish: validates + \
+ compile-checks the flow, registers the run, inserts its `running` row, \
+ and returns the run id immediately. Use this from any UI that wants to \
+ show live per-node progress (`flow:run_progress`) or that must not block \
+ on a run that can take minutes — poll `flows_get_run(run_id)` or the \
+ progress event stream for completion. `run` remains available for callers \
+ that genuinely want to await the final result.",
+ inputs: vec![
+ id_input("Identifier of the flow to run."),
+ FieldSchema {
+ name: "input",
+ ty: TypeSchema::Option(Box::new(TypeSchema::Json)),
+ comment: "Trigger payload seeded into the run; defaults to null.",
+ required: false,
+ },
+ FieldSchema {
+ name: "inputs",
+ ty: TypeSchema::Option(Box::new(TypeSchema::Json)),
+ comment: "Values for the flow's declared workflow inputs, keyed by name (read the flow's `graph.inputs` for the declarations). Validated synchronously, so a bad set is refused here rather than surfacing later as a failed background run. Distinct from `input`, which is the free-form trigger payload.",
+ required: false,
+ },
+ ],
+ outputs: vec![FieldSchema {
+ name: "result",
+ ty: TypeSchema::Object {
+ fields: run_detached_output_fields(),
+ },
+ comment: "Immediate start-of-run payload — returned as soon as the run is \
+ registered, without waiting for it to finish.",
+ required: true,
+ }],
+ }),
+"resume" => Some( ControllerSchema {
+ namespace: "flows",
+ function: "resume",
+ description: "Resume a flow run paused at a human-in-the-loop approval gate, \
+ continuing from its durable checkpoint.",
+ inputs: vec![
+ id_input("Identifier of the flow to resume."),
+ FieldSchema {
+ name: "thread_id",
+ ty: TypeSchema::String,
+ comment:
+ "The checkpoint thread id returned by `flows_run` / a prior `flows_resume`.",
+ required: true,
+ },
+ FieldSchema {
+ name: "approvals",
+ ty: TypeSchema::Option(Box::new(TypeSchema::Array(Box::new(
+ TypeSchema::String,
+ )))),
+ comment: "Node ids being approved; defaults to an empty list.",
+ required: false,
+ },
+ FieldSchema {
+ name: "rejections",
+ ty: TypeSchema::Option(Box::new(TypeSchema::Array(Box::new(
+ TypeSchema::String,
+ )))),
+ comment: "Node ids being denied; each routes to its `error` port (or fails \
+ the run if it has none). Defaults to an empty list.",
+ required: false,
+ },
+ ],
+ outputs: vec![FieldSchema {
+ name: "result",
+ ty: TypeSchema::Object {
+ fields: run_output_fields(),
+ },
+ comment: "Resume outcome payload (same shape as `run`'s).",
+ required: true,
+ }],
+ }),
+"cancel_run" => Some( ControllerSchema {
+ namespace: "flows",
+ function: "cancel_run",
+ description: "Cancel a flow run: settle it to a terminal `cancelled` status, abort \
+ the in-flight run task if one is executing, and drop its durable \
+ checkpoint so it can't be resumed.",
+ inputs: vec![FieldSchema {
+ name: "run_id",
+ ty: TypeSchema::String,
+ comment: "Identifier of the run to cancel (== its checkpoint thread id).",
+ required: true,
+ }],
+ outputs: vec![FieldSchema {
+ name: "result",
+ ty: TypeSchema::Object {
+ fields: vec![
+ FieldSchema {
+ name: "run_id",
+ ty: TypeSchema::String,
+ comment: "Identifier of the run that was cancelled.",
+ required: true,
+ },
+ FieldSchema {
+ name: "cancelled",
+ ty: TypeSchema::Bool,
+ comment:
+ "True once the run is cancelled or its cancellation requested.",
+ required: true,
+ },
+ FieldSchema {
+ name: "was_in_flight",
+ ty: TypeSchema::Bool,
+ comment:
+ "True when a live run task was signalled to abort; false when \
+ a parked/stale run row was settled directly.",
+ required: true,
+ },
+ ],
+ },
+ comment: "Cancellation result payload.",
+ required: true,
+ }],
+ }),
+"list_runs" => Some( ControllerSchema {
+ namespace: "flows",
+ function: "list_runs",
+ description: "List the most recent runs for a flow, newest first.",
+ inputs: vec![
+ id_input("Identifier of the flow whose runs to list."),
+ FieldSchema {
+ name: "limit",
+ ty: TypeSchema::Option(Box::new(TypeSchema::U64)),
+ comment: "Maximum number of runs to return; defaults to 20.",
+ required: false,
+ },
+ ],
+ outputs: vec![FieldSchema {
+ name: "runs",
+ ty: TypeSchema::Array(Box::new(TypeSchema::Ref("FlowRun"))),
+ comment: "Persisted run records for this flow, newest first.",
+ required: true,
+ }],
+ }),
+"list_all_runs" => Some( ControllerSchema {
+ namespace: "flows",
+ function: "list_all_runs",
+ description: "List the most recent runs across all flows, newest first.",
+ inputs: vec![FieldSchema {
+ name: "limit",
+ ty: TypeSchema::Option(Box::new(TypeSchema::U64)),
+ comment: "Maximum number of runs to return; defaults to 100.",
+ required: false,
+ }],
+ outputs: vec![FieldSchema {
+ name: "runs",
+ ty: TypeSchema::Array(Box::new(TypeSchema::Ref("FlowRun"))),
+ comment: "Persisted run records across all flows, newest first.",
+ required: true,
+ }],
+ }),
+"get_run" => Some( ControllerSchema {
+ namespace: "flows",
+ function: "get_run",
+ description: "Load one persisted flow run record by its (checkpoint thread) id.",
+ inputs: vec![FieldSchema {
+ name: "run_id",
+ ty: TypeSchema::String,
+ comment: "Identifier of the run to load (== its checkpoint thread id).",
+ required: true,
+ }],
+ outputs: vec![FieldSchema {
+ name: "run",
+ ty: TypeSchema::Ref("FlowRun"),
+ comment: "The persisted run record.",
+ required: true,
+ }],
+ }),
+"prune_runs" => Some( ControllerSchema {
+ namespace: "flows",
+ function: "prune_runs",
+ description: "Manually prune a flow's run history down to the retention cap, deleting \
+ only terminal runs (completed/failed/cancelled) outside the newest-N \
+ window. Never removes a running or pending_approval run. Pruning also \
+ happens automatically on every new run; this is an explicit on-demand \
+ sweep.",
+ inputs: vec![id_input("Identifier of the flow whose run history to prune.")],
+ outputs: vec![FieldSchema {
+ name: "result",
+ ty: TypeSchema::Object {
+ fields: vec![
+ FieldSchema {
+ name: "flow_id",
+ ty: TypeSchema::String,
+ comment: "Identifier of the flow whose runs were pruned.",
+ required: true,
+ },
+ FieldSchema {
+ name: "pruned",
+ ty: TypeSchema::U64,
+ comment: "Number of run records removed.",
+ required: true,
+ },
+ FieldSchema {
+ name: "kept",
+ ty: TypeSchema::U64,
+ comment: "The retention cap (most-recent runs kept).",
+ required: true,
+ },
+ ],
+ },
+ comment: "Prune result payload.",
+ required: true,
+ }],
+ }),
+"build" => Some( ControllerSchema {
+ namespace: "flows",
+ function: "build",
+ description: "Run the workflow_builder agent for one authoring turn. `mode` selects \
+ create (first draft from `instruction`), revise (refine the injected \
+ `graph`), repair (diagnose a failed `run_id` and fix), or build \
+ (instant-create: build + dry-run + propose against `flow_id`; \
+ propose-only, see #4596). The server renders the agent's brief — the \
+ frontend no longer crafts prompts. Returns `{ proposal, assistant_text, \
+ error }`, where `proposal` is the `{ type: 'workflow_proposal', name, \
+ graph, require_approval, summary, warnings }` the agent produced (or \
+ null). No mode auto-persists a graph; save/enable/run stay behind the \
+ user's explicit action.",
+ inputs: vec![
+ FieldSchema {
+ name: "mode",
+ ty: TypeSchema::String,
+ comment: "One of: `create` | `revise` | `repair` | `build`.",
+ required: true,
+ },
+ FieldSchema {
+ name: "instruction",
+ ty: TypeSchema::String,
+ comment: "The user's ask: description (create/build) or change instruction \
+ (revise); optional note for repair.",
+ required: false,
+ },
+ FieldSchema {
+ name: "graph",
+ ty: TypeSchema::Option(Box::new(TypeSchema::Json)),
+ comment: "The current draft WorkflowGraph, injected as context for \
+ revise/repair/build.",
+ required: false,
+ },
+ FieldSchema {
+ name: "flow_id",
+ ty: TypeSchema::Option(Box::new(TypeSchema::String)),
+ comment: "Saved flow id — required for `build` (save target); optional \
+ elsewhere (lets the agent run_flow it to test, with confirmation).",
+ required: false,
+ },
+ FieldSchema {
+ name: "run_id",
+ ty: TypeSchema::Option(Box::new(TypeSchema::String)),
+ comment: "Failed run id (== thread id) for `repair`, so the agent can \
+ get_flow_run it.",
+ required: false,
+ },
+ FieldSchema {
+ name: "error",
+ ty: TypeSchema::Option(Box::new(TypeSchema::String)),
+ comment: "Run-level error message for `repair`, if known.",
+ required: false,
+ },
+ FieldSchema {
+ name: "failing_node_ids",
+ ty: TypeSchema::Option(Box::new(TypeSchema::Json)),
+ comment: "Node ids implicated in the failure, for `repair` (array of strings).",
+ required: false,
+ },
+ stream_thread_id_input(),
+ stream_request_id_input(),
+ ],
+ outputs: vec![FieldSchema {
+ name: "result",
+ ty: TypeSchema::Json,
+ comment: "`{ proposal, assistant_text, error }` — `proposal` is the workflow \
+ proposal the agent produced (or null); `error` is set if the run failed \
+ but a prior proposal was still captured.",
+ required: true,
+ }],
+ }),
+"build_cancel" => Some( ControllerSchema {
+ namespace: "flows",
+ function: "build_cancel",
+ description: "Cancel the in-flight `flows_build` (Workflow Copilot) turn streaming \
+ into `thread_id` — the real cancellation behind the composer's Stop \
+ button. When `request_id` is given, the cancel only fires if it \
+ matches the turn currently registered on the thread (a stale Stop for \
+ a superseded request can't kill a newer turn); omit it to cancel \
+ whatever turn is on the thread. `cancelled: false` is not an error — it \
+ just means nothing was in flight (already settled, or never started).",
+ inputs: vec![
+ FieldSchema {
+ name: "thread_id",
+ ty: TypeSchema::String,
+ comment: "The copilot's dedicated chat thread id (the same `thread_id` \
+ passed to `flows.build`'s streaming params).",
+ required: true,
+ },
+ FieldSchema {
+ name: "request_id",
+ ty: TypeSchema::Option(Box::new(TypeSchema::String)),
+ comment: "Per-turn correlation id to scope the cancel to (matches the \
+ `request_id` `flows.build` streamed with). Omit to cancel \
+ unscoped.",
+ required: false,
+ },
+ ],
+ outputs: vec![FieldSchema {
+ name: "result",
+ ty: TypeSchema::Object {
+ fields: vec![FieldSchema {
+ name: "cancelled",
+ ty: TypeSchema::Bool,
+ comment: "True when an in-flight build turn was found and signalled to \
+ cancel.",
+ required: true,
+ }],
+ },
+ comment: "Cancellation result payload.",
+ required: true,
+ }],
+ }),
+"discover" => Some( ControllerSchema {
+ namespace: "flows",
+ function: "discover",
+ description: "Run the read-only Flow Scout: it reads the user's \
+ memory/threads/people/connections/existing flows and records a handful \
+ of concrete, buildable workflow suggestions for the Flows page. It never \
+ creates, enables, or runs a flow — turning a suggestion into a real flow \
+ is the user's separate 'Build this' action. Returns the active (new) \
+ suggestions after the run.",
+ inputs: vec![stream_thread_id_input(), stream_request_id_input()],
+ outputs: vec![suggestions_output()],
+ }),
+"list_suggestions" => Some( ControllerSchema {
+ namespace: "flows",
+ function: "list_suggestions",
+ description: "List persisted workflow suggestions. Filter by lifecycle `status` \
+ (`new` | `dismissed` | `built`); omit to return every status.",
+ inputs: vec![FieldSchema {
+ name: "status",
+ ty: TypeSchema::Option(Box::new(TypeSchema::String)),
+ comment: "Lifecycle filter: `new` (active cards) | `dismissed` | `built`. \
+ Omit for all.",
+ required: false,
+ }],
+ outputs: vec![suggestions_output()],
+ }),
+"dismiss_suggestion" => Some( ControllerSchema {
+ namespace: "flows",
+ function: "dismiss_suggestion",
+ description: "Dismiss a workflow suggestion (the user rejected the card). The row is \
+ kept so a later discovery run dedupes against it and won't re-surface \
+ the idea.",
+ inputs: vec![id_input("Identifier of the suggestion to dismiss.")],
+ outputs: vec![FieldSchema {
+ name: "result",
+ ty: TypeSchema::Json,
+ comment: "`{ id, dismissed }` — `dismissed` is false if the id was unknown.",
+ required: true,
+ }],
+ }),
+ _ => None,
+ }
+}
diff --git a/src/openhuman/flows/flows_schema_part_02.rs b/src/openhuman/flows/flows_schema_part_02.rs
new file mode 100644
index 0000000000..19e9951358
--- /dev/null
+++ b/src/openhuman/flows/flows_schema_part_02.rs
@@ -0,0 +1,286 @@
+use super::*;
+
+pub(super) fn lookup(function: &str) -> Option<ControllerSchema> {
+ match function {
+"mark_suggestion_built" => Some( ControllerSchema {
+ namespace: "flows",
+ function: "mark_suggestion_built",
+ description: "Mark a suggestion as built — called after the user saves a flow authored \
+ from it, so it drops out of the active cards.",
+ inputs: vec![id_input("Identifier of the suggestion that was built.")],
+ outputs: vec![FieldSchema {
+ name: "result",
+ ty: TypeSchema::Json,
+ comment: "`{ id, built }` — `built` is false if the id was unknown.",
+ required: true,
+ }],
+ }),
+"approval_manifest" => Some( ControllerSchema {
+ namespace: "flows",
+ function: "approval_manifest",
+ description:
+ "Compute the approval manifest for a saved flow (by id) or a candidate graph: \
+ every ApprovalGate permission a run will prompt for, joined against the flow's \
+ existing flow_tool_trust grants — the data behind the consolidated save+enable \
+ pre-authorization card. Entries carry kind approvable|blocked|dynamic|agent.",
+ inputs: vec![
+ FieldSchema {
+ name: "id",
+ ty: TypeSchema::Option(Box::new(TypeSchema::String)),
+ comment: "Saved flow id. Provide this or 'graph'.",
+ required: false,
+ },
+ FieldSchema {
+ name: "graph",
+ ty: TypeSchema::Option(Box::new(TypeSchema::Json)),
+ comment: "Candidate WorkflowGraph to inspect (no trust join without an id).",
+ required: false,
+ },
+ ],
+ outputs: vec![
+ FieldSchema {
+ name: "entries",
+ ty: TypeSchema::Array(Box::new(TypeSchema::Json)),
+ comment:
+ "One per relevant node/tool: {kind: approvable|blocked|dynamic|agent, \
+ node_id, tool_name?, label, class?}.",
+ required: true,
+ },
+ FieldSchema {
+ name: "missing",
+ ty: TypeSchema::Array(Box::new(TypeSchema::String)),
+ comment: "Approvable trust keys the flow does not yet hold.",
+ required: true,
+ },
+ FieldSchema {
+ name: "already_trusted",
+ ty: TypeSchema::Array(Box::new(TypeSchema::String)),
+ comment: "Approvable trust keys already granted to this flow.",
+ required: true,
+ },
+ FieldSchema {
+ name: "gate_installed",
+ ty: TypeSchema::Bool,
+ comment:
+ "False when the approval gate is disabled — nothing ever prompts, so \
+ missing is empty by definition.",
+ required: true,
+ },
+ ],
+ }),
+"required_connections" => Some( ControllerSchema {
+ namespace: "flows",
+ function: "required_connections",
+ description: "Compute which Composio toolkits a candidate graph needs and whether each \
+ is connected — the data behind the canvas/proposal \"Connect <toolkit>\" \
+ CTAs. Native oh: tools and http_request nodes need no connection.",
+ inputs: vec![FieldSchema {
+ name: "graph",
+ ty: TypeSchema::Json,
+ comment: "The WorkflowGraph to inspect.",
+ required: true,
+ }],
+ outputs: vec![FieldSchema {
+ name: "required_connections",
+ ty: TypeSchema::Array(Box::new(TypeSchema::Json)),
+ comment: "One per needed toolkit: { toolkit, status: connected|missing }.",
+ required: true,
+ }],
+ }),
+"search_tool_catalog" => Some( ControllerSchema {
+ namespace: "flows",
+ function: "search_tool_catalog",
+ description: "Search the live Composio tool catalog (secret-free) for the in-canvas \
+ tool browser — the same core as the agent's search_tool_catalog tool.",
+ inputs: vec![
+ FieldSchema {
+ name: "query",
+ ty: TypeSchema::String,
+ comment: "Keyword query matched against slug / toolkit / description.",
+ required: true,
+ },
+ FieldSchema {
+ name: "toolkit",
+ ty: TypeSchema::Option(Box::new(TypeSchema::String)),
+ comment: "Restrict to one toolkit slug (e.g. `gmail`); omit to search all.",
+ required: false,
+ },
+ FieldSchema {
+ name: "limit",
+ ty: TypeSchema::Option(Box::new(TypeSchema::U64)),
+ comment: "Max results (default 25).",
+ required: false,
+ },
+ ],
+ outputs: vec![FieldSchema {
+ name: "tools",
+ ty: TypeSchema::Array(Box::new(TypeSchema::Json)),
+ comment: "Matches: { slug, toolkit, description, required_args, output_fields, primary_array_path, featured }.",
+ required: true,
+ }],
+ }),
+"get_tool_contract" => Some( ControllerSchema {
+ namespace: "flows",
+ function: "get_tool_contract",
+ description: "Fetch one Composio action's full contract (secret-free) for the canvas \
+ tool browser — the same core as the agent's get_tool_contract tool.",
+ inputs: vec![FieldSchema {
+ name: "slug",
+ ty: TypeSchema::String,
+ comment: "The exact Composio action slug (e.g. `GMAIL_SEND_EMAIL`).",
+ required: true,
+ }],
+ outputs: vec![FieldSchema {
+ name: "contract",
+ ty: TypeSchema::Json,
+ comment: "The action contract: { slug, toolkit, description, required_args, input_schema, output_fields, output_schema, primary_array_path, is_curated }.",
+ required: true,
+ }],
+ }),
+"get_history" => Some( ControllerSchema {
+ namespace: "flows",
+ function: "get_history",
+ description: "List a flow's revision history — prior graph snapshots captured on each \
+ update (capped, newest first). The safety rail behind rollback.",
+ inputs: vec![
+ id_input("Identifier of the flow whose history to list."),
+ FieldSchema {
+ name: "limit",
+ ty: TypeSchema::Option(Box::new(TypeSchema::U64)),
+ comment: "Max revisions to return (defaults to the retention cap).",
+ required: false,
+ },
+ ],
+ outputs: vec![FieldSchema {
+ name: "revisions",
+ ty: TypeSchema::Array(Box::new(TypeSchema::Json)),
+ comment: "Revision snapshots: { id, flow_id, graph, name, require_approval, created_at }.",
+ required: true,
+ }],
+ }),
+"rollback" => Some( ControllerSchema {
+ namespace: "flows",
+ function: "rollback",
+ description: "Roll a flow back to a prior revision (restores that revision's graph \
+ through the normal update path — itself snapshotted, so rollback is \
+ undoable). Honours optimistic concurrency via expected_version.",
+ inputs: vec![
+ id_input("Identifier of the flow to roll back."),
+ FieldSchema {
+ name: "revision_id",
+ ty: TypeSchema::String,
+ comment: "The revision (from get_history) to restore.",
+ required: true,
+ },
+ expected_version_input(),
+ ],
+ outputs: vec![flow_output()],
+ }),
+"draft_create" => Some( ControllerSchema {
+ namespace: "flows",
+ function: "draft_create",
+ description: "Create a core-managed draft (a durable, non-live working copy of a graph) \
+ shared by the agent tools and the canvas. Never persists a flow.",
+ inputs: vec![
+ FieldSchema {
+ name: "name",
+ ty: TypeSchema::String,
+ comment: "Human-readable draft name (carried into the flow on promote).",
+ required: true,
+ },
+ FieldSchema {
+ name: "graph",
+ ty: TypeSchema::Json,
+ comment: "The (possibly incomplete) WorkflowGraph JSON to hold in the draft.",
+ required: true,
+ },
+ FieldSchema {
+ name: "flow_id",
+ ty: TypeSchema::Option(Box::new(TypeSchema::String)),
+ comment: "The saved flow this draft edits, if any (promote → update vs create).",
+ required: false,
+ },
+ FieldSchema {
+ name: "origin",
+ ty: TypeSchema::Option(Box::new(TypeSchema::String)),
+ comment: "Where the draft came from: `chat` | `canvas` | `import`. Defaults to `canvas`.",
+ required: false,
+ },
+ ],
+ outputs: vec![draft_output()],
+ }),
+"draft_get" => Some( ControllerSchema {
+ namespace: "flows",
+ function: "draft_get",
+ description: "Fetch a draft by id.",
+ inputs: vec![id_input("Identifier of the draft to fetch.")],
+ outputs: vec![draft_output()],
+ }),
+"draft_update" => Some( ControllerSchema {
+ namespace: "flows",
+ function: "draft_update",
+ description: "Patch a draft's name/graph/flow_id (any provided field) and bump its \
+ updated_at. Never persists a flow.",
+ inputs: vec![
+ id_input("Identifier of the draft to update."),
+ FieldSchema {
+ name: "name",
+ ty: TypeSchema::Option(Box::new(TypeSchema::String)),
+ comment: "New name, if changing it.",
+ required: false,
+ },
+ FieldSchema {
+ name: "graph",
+ ty: TypeSchema::Option(Box::new(TypeSchema::Json)),
+ comment: "New graph JSON, if changing it.",
+ required: false,
+ },
+ FieldSchema {
+ name: "flow_id",
+ ty: TypeSchema::Option(Box::new(TypeSchema::String)),
+ comment: "New linked flow id, if changing it.",
+ required: false,
+ },
+ ],
+ outputs: vec![draft_output()],
+ }),
+"draft_list" => Some( ControllerSchema {
+ namespace: "flows",
+ function: "draft_list",
+ description: "List all drafts, newest-updated first.",
+ inputs: vec![],
+ outputs: vec![FieldSchema {
+ name: "drafts",
+ ty: TypeSchema::Array(Box::new(TypeSchema::Json)),
+ comment: "The drafts (each { id, flow_id?, name, graph, origin, created_at, updated_at }).",
+ required: true,
+ }],
+ }),
+"draft_delete" => Some( ControllerSchema {
+ namespace: "flows",
+ function: "draft_delete",
+ description: "Delete a draft by id (idempotent).",
+ inputs: vec![id_input("Identifier of the draft to delete.")],
+ outputs: vec![FieldSchema {
+ name: "result",
+ ty: TypeSchema::Json,
+ comment: "`{ id, deleted }` — `deleted` is false if the id was already absent.",
+ required: true,
+ }],
+ }),
+"draft_promote" => Some( ControllerSchema {
+ namespace: "flows",
+ function: "draft_promote",
+ description: "Promote a draft into a saved flow through the same create/update gates \
+ (structural validation, forced require_approval floor, born-disabled for \
+ automatic triggers), then delete the draft file. A draft with a flow_id \
+ updates that flow; otherwise it creates a new one.",
+ inputs: vec![
+ id_input("Identifier of the draft to promote."),
+ require_approval_input(),
+ ],
+ outputs: vec![flow_output()],
+ }),
+ _ => None,
+ }
+}
diff --git a/src/openhuman/flows/schemas.rs b/src/openhuman/flows/schemas.rs
index 8dc632e69d..a8012dfa76 100644
--- a/src/openhuman/flows/schemas.rs
+++ b/src/openhuman/flows/schemas.rs
@@ -496,1475 +496,35 @@ pub fn all_registered_controllers() -> Vec<RegisteredController> {
]
}
+#[path = "flows_schema_part_01.rs"]
+mod flows_schema_part_01;
+#[path = "flows_schema_part_02.rs"]
+mod flows_schema_part_02;
+
pub fn schemas(function: &str) -> ControllerSchema {
- match function {
- "create" => ControllerSchema {
- namespace: "flows",
- function: "create",
- description: "Create a new saved automation workflow from a tinyflows graph.",
- inputs: vec![
- FieldSchema {
- name: "name",
- ty: TypeSchema::String,
- comment: "Human-readable flow name.",
- required: true,
- },
- FieldSchema {
- name: "graph",
- ty: TypeSchema::Json,
- comment:
- "A tinyflows WorkflowGraph (nodes + edges); validated and migrated on save.",
- required: true,
- },
- require_approval_input(),
- strict_input(),
- ],
- outputs: vec![flow_output()],
- },
- "duplicate" => ControllerSchema {
- namespace: "flows",
- function: "duplicate",
- description: "Duplicate a saved flow: create an independent copy of its graph under a \
- new id, with the name suffixed \" (copy)\". The copy is created DISABLED \
- and is NOT schedule/trigger-bound, so it never immediately fires — the \
- user enables it explicitly once reviewed. Run history does not carry over.",
- inputs: vec![id_input("Identifier of the flow to duplicate.")],
- outputs: vec![flow_output()],
- },
- "validate" => ControllerSchema {
- namespace: "flows",
- function: "validate",
- description: "Validate a tinyflows graph without saving it: reports structural \
- validity plus non-fatal warnings (e.g. a trigger kind that does not \
- fire automatically yet).",
- inputs: vec![FieldSchema {
- name: "graph",
- ty: TypeSchema::Json,
- comment: "A tinyflows WorkflowGraph (nodes + edges) to validate and migrate.",
- required: true,
- }],
- outputs: vec![
- FieldSchema {
- name: "valid",
- ty: TypeSchema::Bool,
- comment: "True when the graph is structurally valid.",
- required: true,
- },
- FieldSchema {
- name: "errors",
- ty: TypeSchema::Array(Box::new(TypeSchema::String)),
- comment: "Structural validation errors; empty when `valid`.",
- required: true,
- },
- FieldSchema {
- name: "warnings",
- ty: TypeSchema::Array(Box::new(TypeSchema::String)),
- comment: "Non-fatal warnings (e.g. an unfired trigger kind); the graph is \
- still saveable/enable-able.",
- required: true,
- },
- ],
- },
- "import" => ControllerSchema {
- namespace: "flows",
- function: "import",
- description: "Import a workflow definition WITHOUT saving it: parse a native tinyflows \
- graph or an n8n workflow export, migrate + validate it, and return the \
- normalized WorkflowGraph plus non-fatal import warnings. The caller opens \
- the result on the canvas as a draft and Saves via the normal gate — \
- import never persists or enables anything.",
- inputs: vec![
- FieldSchema {
- name: "graph",
- ty: TypeSchema::Json,
- comment: "The workflow JSON to import: a tinyflows WorkflowGraph (native) or \
- an n8n workflow export.",
- required: true,
- },
- FieldSchema {
- name: "format",
- ty: TypeSchema::Option(Box::new(TypeSchema::Enum {
- variants: vec!["native", "n8n", "auto"],
- })),
- comment: "Source format: `native` (tinyflows), `n8n`, or `auto` (default — \
- detect by shape).",
- required: false,
- },
- ],
- outputs: vec![
- FieldSchema {
- name: "graph",
- ty: TypeSchema::Json,
- comment: "The normalized, migrated + validated WorkflowGraph, ready to open \
- as an editable draft.",
- required: true,
- },
- FieldSchema {
- name: "warnings",
- ty: TypeSchema::Array(Box::new(TypeSchema::String)),
- comment: "Non-fatal import warnings (unmapped n8n node types, untranslated \
- expressions, a synthesized/demoted trigger). Empty for a clean \
- native import.",
- required: true,
- },
- ],
- },
- "get" => ControllerSchema {
- namespace: "flows",
- function: "get",
- description: "Load one saved flow by id.",
- inputs: vec![id_input("Identifier of the flow to load.")],
- outputs: vec![flow_output()],
- },
- "list" => ControllerSchema {
- namespace: "flows",
- function: "list",
- description: "List all saved flows.",
- inputs: vec![],
- outputs: vec![FieldSchema {
- name: "flows",
- ty: TypeSchema::Array(Box::new(TypeSchema::Ref("Flow"))),
- comment: "Flows currently stored in the workspace.",
- required: true,
- }],
- },
- "list_connections" => ControllerSchema {
- namespace: "flows",
- function: "list_connections",
- description: "List the connection sources a flow node's `connection_ref` can attach \
- to: Composio connected accounts (kind `composio`) and stored HTTP \
- credentials (kind `http`). Returns only non-secret metadata — ids, \
- display labels, kind, and (for Composio) the connected account's own \
- `platform_user_id` — never any secret material (OAuth/bearer tokens, \
- passwords, and API keys stay server-side and are injected only at \
- execution time).",
- inputs: vec![],
- outputs: vec![FieldSchema {
- name: "connections",
- ty: TypeSchema::Array(Box::new(TypeSchema::Object {
- fields: flow_connection_fields(),
- })),
- comment: "Resolvable connections for the flows picker (composio + http), \
- secret-free.",
- required: true,
- }],
- },
- "update" => ControllerSchema {
- namespace: "flows",
- function: "update",
- description: "Update a saved flow's name and/or graph; re-validates before persisting.",
- inputs: vec![
- id_input("Identifier of the flow to update."),
- FieldSchema {
- name: "name",
- ty: TypeSchema::Option(Box::new(TypeSchema::String)),
- comment: "New name, if changing it.",
- required: false,
- },
- FieldSchema {
- name: "graph",
- ty: TypeSchema::Option(Box::new(TypeSchema::Json)),
- comment: "Replacement WorkflowGraph, if changing it.",
- required: false,
- },
- require_approval_input(),
- strict_input(),
- expected_version_input(),
- ],
- outputs: vec![flow_output()],
- },
- "delete" => ControllerSchema {
- namespace: "flows",
- function: "delete",
- description: "Delete a saved flow by id.",
- inputs: vec![id_input("Identifier of the flow to delete.")],
- outputs: vec![FieldSchema {
- name: "result",
- ty: TypeSchema::Object {
- fields: vec![
- FieldSchema {
- name: "id",
- ty: TypeSchema::String,
- comment: "Identifier that was requested for removal.",
- required: true,
- },
- FieldSchema {
- name: "removed",
- ty: TypeSchema::Bool,
- comment: "True when the flow was removed.",
- required: true,
- },
- ],
- },
- comment: "Removal result payload.",
- required: true,
- }],
- },
- "set_enabled" => ControllerSchema {
- namespace: "flows",
- function: "set_enabled",
- description: "Enable or disable a saved flow.",
- inputs: vec![
- id_input("Identifier of the flow to toggle."),
- FieldSchema {
- name: "enabled",
- ty: TypeSchema::Bool,
- comment: "New enabled state.",
- required: true,
- },
- ],
- outputs: vec![flow_output()],
- },
- "run" => ControllerSchema {
- namespace: "flows",
- function: "run",
- description:
- "Run a saved flow to completion (or until it pauses on a human-approval gate).",
- inputs: vec![
- id_input("Identifier of the flow to run."),
- FieldSchema {
- name: "input",
- ty: TypeSchema::Option(Box::new(TypeSchema::Json)),
- comment: "Trigger payload seeded into the run; defaults to null.",
- required: false,
- },
- FieldSchema {
- name: "inputs",
- ty: TypeSchema::Option(Box::new(TypeSchema::Json)),
- comment: "Values for the flow's declared workflow inputs, keyed by name \
- (read the flow's `graph.inputs` for the declarations). Missing \
- required values, wrong types, and undeclared names are rejected \
- before the run starts. Distinct from `input`, which is the \
- free-form trigger payload.",
- required: false,
- },
- ],
- outputs: vec![FieldSchema {
- name: "result",
- ty: TypeSchema::Object {
- fields: run_output_fields(),
- },
- comment: "Run outcome payload.",
- required: true,
- }],
- },
- "run_detached" => ControllerSchema {
- namespace: "flows",
- function: "run_detached",
- description: "Start a saved flow WITHOUT waiting for it to finish: validates + \
- compile-checks the flow, registers the run, inserts its `running` row, \
- and returns the run id immediately. Use this from any UI that wants to \
- show live per-node progress (`flow:run_progress`) or that must not block \
- on a run that can take minutes — poll `flows_get_run(run_id)` or the \
- progress event stream for completion. `run` remains available for callers \
- that genuinely want to await the final result.",
- inputs: vec![
- id_input("Identifier of the flow to run."),
- FieldSchema {
- name: "input",
- ty: TypeSchema::Option(Box::new(TypeSchema::Json)),
- comment: "Trigger payload seeded into the run; defaults to null.",
- required: false,
- },
- FieldSchema {
- name: "inputs",
- ty: TypeSchema::Option(Box::new(TypeSchema::Json)),
- comment: "Values for the flow's declared workflow inputs, keyed by name (read the flow's `graph.inputs` for the declarations). Validated synchronously, so a bad set is refused here rather than surfacing later as a failed background run. Distinct from `input`, which is the free-form trigger payload.",
- required: false,
- },
- ],
- outputs: vec![FieldSchema {
- name: "result",
- ty: TypeSchema::Object {
- fields: run_detached_output_fields(),
- },
- comment: "Immediate start-of-run payload — returned as soon as the run is \
- registered, without waiting for it to finish.",
- required: true,
- }],
- },
- "resume" => ControllerSchema {
- namespace: "flows",
- function: "resume",
- description: "Resume a flow run paused at a human-in-the-loop approval gate, \
- continuing from its durable checkpoint.",
- inputs: vec![
- id_input("Identifier of the flow to resume."),
- FieldSchema {
- name: "thread_id",
- ty: TypeSchema::String,
- comment:
- "The checkpoint thread id returned by `flows_run` / a prior `flows_resume`.",
- required: true,
- },
- FieldSchema {
- name: "approvals",
- ty: TypeSchema::Option(Box::new(TypeSchema::Array(Box::new(
- TypeSchema::String,
- )))),
- comment: "Node ids being approved; defaults to an empty list.",
- required: false,
- },
- FieldSchema {
- name: "rejections",
- ty: TypeSchema::Option(Box::new(TypeSchema::Array(Box::new(
- TypeSchema::String,
- )))),
- comment: "Node ids being denied; each routes to its `error` port (or fails \
- the run if it has none). Defaults to an empty list.",
- required: false,
- },
- ],
- outputs: vec![FieldSchema {
- name: "result",
- ty: TypeSchema::Object {
- fields: run_output_fields(),
- },
- comment: "Resume outcome payload (same shape as `run`'s).",
- required: true,
- }],
- },
- "cancel_run" => ControllerSchema {
- namespace: "flows",
- function: "cancel_run",
- description: "Cancel a flow run: settle it to a terminal `cancelled` status, abort \
- the in-flight run task if one is executing, and drop its durable \
- checkpoint so it can't be resumed.",
- inputs: vec![FieldSchema {
- name: "run_id",
- ty: TypeSchema::String,
- comment: "Identifier of the run to cancel (== its checkpoint thread id).",
- required: true,
- }],
- outputs: vec![FieldSchema {
- name: "result",
- ty: TypeSchema::Object {
- fields: vec![
- FieldSchema {
- name: "run_id",
- ty: TypeSchema::String,
- comment: "Identifier of the run that was cancelled.",
- required: true,
- },
- FieldSchema {
- name: "cancelled",
- ty: TypeSchema::Bool,
- comment:
- "True once the run is cancelled or its cancellation requested.",
- required: true,
- },
- FieldSchema {
- name: "was_in_flight",
- ty: TypeSchema::Bool,
- comment:
- "True when a live run task was signalled to abort; false when \
- a parked/stale run row was settled directly.",
- required: true,
- },
- ],
- },
- comment: "Cancellation result payload.",
- required: true,
- }],
- },
- "list_runs" => ControllerSchema {
- namespace: "flows",
- function: "list_runs",
- description: "List the most recent runs for a flow, newest first.",
- inputs: vec![
- id_input("Identifier of the flow whose runs to list."),
- FieldSchema {
- name: "limit",
- ty: TypeSchema::Option(Box::new(TypeSchema::U64)),
- comment: "Maximum number of runs to return; defaults to 20.",
- required: false,
- },
- ],
- outputs: vec![FieldSchema {
- name: "runs",
- ty: TypeSchema::Array(Box::new(TypeSchema::Ref("FlowRun"))),
- comment: "Persisted run records for this flow, newest first.",
- required: true,
- }],
- },
- "list_all_runs" => ControllerSchema {
- namespace: "flows",
- function: "list_all_runs",
- description: "List the most recent runs across all flows, newest first.",
- inputs: vec![FieldSchema {
- name: "limit",
- ty: TypeSchema::Option(Box::new(TypeSchema::U64)),
- comment: "Maximum number of runs to return; defaults to 100.",
- required: false,
- }],
- outputs: vec![FieldSchema {
- name: "runs",
- ty: TypeSchema::Array(Box::new(TypeSchema::Ref("FlowRun"))),
- comment: "Persisted run records across all flows, newest first.",
- required: true,
- }],
- },
- "get_run" => ControllerSchema {
- namespace: "flows",
- function: "get_run",
- description: "Load one persisted flow run record by its (checkpoint thread) id.",
- inputs: vec![FieldSchema {
- name: "run_id",
- ty: TypeSchema::String,
- comment: "Identifier of the run to load (== its checkpoint thread id).",
- required: true,
- }],
- outputs: vec![FieldSchema {
- name: "run",
- ty: TypeSchema::Ref("FlowRun"),
- comment: "The persisted run record.",
- required: true,
- }],
- },
- "prune_runs" => ControllerSchema {
- namespace: "flows",
- function: "prune_runs",
- description: "Manually prune a flow's run history down to the retention cap, deleting \
- only terminal runs (completed/failed/cancelled) outside the newest-N \
- window. Never removes a running or pending_approval run. Pruning also \
- happens automatically on every new run; this is an explicit on-demand \
- sweep.",
- inputs: vec![id_input("Identifier of the flow whose run history to prune.")],
- outputs: vec![FieldSchema {
- name: "result",
- ty: TypeSchema::Object {
- fields: vec![
- FieldSchema {
- name: "flow_id",
- ty: TypeSchema::String,
- comment: "Identifier of the flow whose runs were pruned.",
- required: true,
- },
- FieldSchema {
- name: "pruned",
- ty: TypeSchema::U64,
- comment: "Number of run records removed.",
- required: true,
- },
- FieldSchema {
- name: "kept",
- ty: TypeSchema::U64,
- comment: "The retention cap (most-recent runs kept).",
- required: true,
- },
- ],
- },
- comment: "Prune result payload.",
- required: true,
- }],
- },
- "build" => ControllerSchema {
- namespace: "flows",
- function: "build",
- description: "Run the workflow_builder agent for one authoring turn. `mode` selects \
- create (first draft from `instruction`), revise (refine the injected \
- `graph`), repair (diagnose a failed `run_id` and fix), or build \
- (instant-create: build + dry-run + propose against `flow_id`; \
- propose-only, see #4596). The server renders the agent's brief — the \
- frontend no longer crafts prompts. Returns `{ proposal, assistant_text, \
- error }`, where `proposal` is the `{ type: 'workflow_proposal', name, \
- graph, require_approval, summary, warnings }` the agent produced (or \
- null). No mode auto-persists a graph; save/enable/run stay behind the \
- user's explicit action.",
- inputs: vec![
- FieldSchema {
- name: "mode",
- ty: TypeSchema::String,
- comment: "One of: `create` | `revise` | `repair` | `build`.",
- required: true,
- },
- FieldSchema {
- name: "instruction",
- ty: TypeSchema::String,
- comment: "The user's ask: description (create/build) or change instruction \
- (revise); optional note for repair.",
- required: false,
- },
- FieldSchema {
- name: "graph",
- ty: TypeSchema::Option(Box::new(TypeSchema::Json)),
- comment: "The current draft WorkflowGraph, injected as context for \
- revise/repair/build.",
- required: false,
- },
- FieldSchema {
- name: "flow_id",
- ty: TypeSchema::Option(Box::new(TypeSchema::String)),
- comment: "Saved flow id — required for `build` (save target); optional \
- elsewhere (lets the agent run_flow it to test, with confirmation).",
- required: false,
- },
- FieldSchema {
- name: "run_id",
- ty: TypeSchema::Option(Box::new(TypeSchema::String)),
- comment: "Failed run id (== thread id) for `repair`, so the agent can \
- get_flow_run it.",
- required: false,
- },
- FieldSchema {
- name: "error",
- ty: TypeSchema::Option(Box::new(TypeSchema::String)),
- comment: "Run-level error message for `repair`, if known.",
- required: false,
- },
- FieldSchema {
- name: "failing_node_ids",
- ty: TypeSchema::Option(Box::new(TypeSchema::Json)),
- comment: "Node ids implicated in the failure, for `repair` (array of strings).",
- required: false,
- },
- stream_thread_id_input(),
- stream_request_id_input(),
- ],
- outputs: vec![FieldSchema {
- name: "result",
- ty: TypeSchema::Json,
- comment: "`{ proposal, assistant_text, error }` — `proposal` is the workflow \
- proposal the agent produced (or null); `error` is set if the run failed \
- but a prior proposal was still captured.",
- required: true,
- }],
- },
- "build_cancel" => ControllerSchema {
- namespace: "flows",
- function: "build_cancel",
- description: "Cancel the in-flight `flows_build` (Workflow Copilot) turn streaming \
- into `thread_id` — the real cancellation behind the composer's Stop \
- button. When `request_id` is given, the cancel only fires if it \
- matches the turn currently registered on the thread (a stale Stop for \
- a superseded request can't kill a newer turn); omit it to cancel \
- whatever turn is on the thread. `cancelled: false` is not an error — it \
- just means nothing was in flight (already settled, or never started).",
- inputs: vec![
- FieldSchema {
- name: "thread_id",
- ty: TypeSchema::String,
- comment: "The copilot's dedicated chat thread id (the same `thread_id` \
- passed to `flows.build`'s streaming params).",
- required: true,
- },
- FieldSchema {
- name: "request_id",
- ty: TypeSchema::Option(Box::new(TypeSchema::String)),
- comment: "Per-turn correlation id to scope the cancel to (matches the \
- `request_id` `flows.build` streamed with). Omit to cancel \
- unscoped.",
- required: false,
- },
- ],
- outputs: vec![FieldSchema {
- name: "result",
- ty: TypeSchema::Object {
- fields: vec![FieldSchema {
- name: "cancelled",
- ty: TypeSchema::Bool,
- comment: "True when an in-flight build turn was found and signalled to \
- cancel.",
- required: true,
- }],
- },
- comment: "Cancellation result payload.",
- required: true,
- }],
- },
- "discover" => ControllerSchema {
- namespace: "flows",
- function: "discover",
- description: "Run the read-only Flow Scout: it reads the user's \
- memory/threads/people/connections/existing flows and records a handful \
- of concrete, buildable workflow suggestions for the Flows page. It never \
- creates, enables, or runs a flow — turning a suggestion into a real flow \
- is the user's separate 'Build this' action. Returns the active (new) \
- suggestions after the run.",
- inputs: vec![stream_thread_id_input(), stream_request_id_input()],
- outputs: vec![suggestions_output()],
- },
- "list_suggestions" => ControllerSchema {
- namespace: "flows",
- function: "list_suggestions",
- description: "List persisted workflow suggestions. Filter by lifecycle `status` \
- (`new` | `dismissed` | `built`); omit to return every status.",
- inputs: vec![FieldSchema {
- name: "status",
- ty: TypeSchema::Option(Box::new(TypeSchema::String)),
- comment: "Lifecycle filter: `new` (active cards) | `dismissed` | `built`. \
- Omit for all.",
- required: false,
- }],
- outputs: vec![suggestions_output()],
- },
- "dismiss_suggestion" => ControllerSchema {
- namespace: "flows",
- function: "dismiss_suggestion",
- description: "Dismiss a workflow suggestion (the user rejected the card). The row is \
- kept so a later discovery run dedupes against it and won't re-surface \
- the idea.",
- inputs: vec![id_input("Identifier of the suggestion to dismiss.")],
- outputs: vec![FieldSchema {
- name: "result",
- ty: TypeSchema::Json,
- comment: "`{ id, dismissed }` — `dismissed` is false if the id was unknown.",
- required: true,
- }],
- },
- "mark_suggestion_built" => ControllerSchema {
- namespace: "flows",
- function: "mark_suggestion_built",
- description: "Mark a suggestion as built — called after the user saves a flow authored \
- from it, so it drops out of the active cards.",
- inputs: vec![id_input("Identifier of the suggestion that was built.")],
- outputs: vec![FieldSchema {
- name: "result",
- ty: TypeSchema::Json,
- comment: "`{ id, built }` — `built` is false if the id was unknown.",
- required: true,
- }],
- },
- "approval_manifest" => ControllerSchema {
- namespace: "flows",
- function: "approval_manifest",
- description:
- "Compute the approval manifest for a saved flow (by id) or a candidate graph: \
- every ApprovalGate permission a run will prompt for, joined against the flow's \
- existing flow_tool_trust grants — the data behind the consolidated save+enable \
- pre-authorization card. Entries carry kind approvable|blocked|dynamic|agent.",
- inputs: vec![
- FieldSchema {
- name: "id",
- ty: TypeSchema::Option(Box::new(TypeSchema::String)),
- comment: "Saved flow id. Provide this or 'graph'.",
- required: false,
- },
- FieldSchema {
- name: "graph",
- ty: TypeSchema::Option(Box::new(TypeSchema::Json)),
- comment: "Candidate WorkflowGraph to inspect (no trust join without an id).",
- required: false,
- },
- ],
- outputs: vec![
- FieldSchema {
- name: "entries",
- ty: TypeSchema::Array(Box::new(TypeSchema::Json)),
- comment:
- "One per relevant node/tool: {kind: approvable|blocked|dynamic|agent, \
- node_id, tool_name?, label, class?}.",
- required: true,
- },
- FieldSchema {
- name: "missing",
- ty: TypeSchema::Array(Box::new(TypeSchema::String)),
- comment: "Approvable trust keys the flow does not yet hold.",
- required: true,
- },
- FieldSchema {
- name: "already_trusted",
- ty: TypeSchema::Array(Box::new(TypeSchema::String)),
- comment: "Approvable trust keys already granted to this flow.",
- required: true,
- },
- FieldSchema {
- name: "gate_installed",
- ty: TypeSchema::Bool,
- comment:
- "False when the approval gate is disabled — nothing ever prompts, so \
- missing is empty by definition.",
- required: true,
- },
- ],
- },
- "required_connections" => ControllerSchema {
- namespace: "flows",
- function: "required_connections",
- description: "Compute which Composio toolkits a candidate graph needs and whether each \
- is connected — the data behind the canvas/proposal \"Connect <toolkit>\" \
- CTAs. Native oh: tools and http_request nodes need no connection.",
- inputs: vec![FieldSchema {
- name: "graph",
- ty: TypeSchema::Json,
- comment: "The WorkflowGraph to inspect.",
- required: true,
- }],
- outputs: vec![FieldSchema {
- name: "required_connections",
- ty: TypeSchema::Array(Box::new(TypeSchema::Json)),
- comment: "One per needed toolkit: { toolkit, status: connected|missing }.",
- required: true,
- }],
- },
- "search_tool_catalog" => ControllerSchema {
- namespace: "flows",
- function: "search_tool_catalog",
- description: "Search the live Composio tool catalog (secret-free) for the in-canvas \
- tool browser — the same core as the agent's search_tool_catalog tool.",
- inputs: vec![
- FieldSchema {
- name: "query",
- ty: TypeSchema::String,
- comment: "Keyword query matched against slug / toolkit / description.",
- required: true,
- },
- FieldSchema {
- name: "toolkit",
- ty: TypeSchema::Option(Box::new(TypeSchema::String)),
- comment: "Restrict to one toolkit slug (e.g. `gmail`); omit to search all.",
- required: false,
- },
- FieldSchema {
- name: "limit",
- ty: TypeSchema::Option(Box::new(TypeSchema::U64)),
- comment: "Max results (default 25).",
- required: false,
- },
- ],
- outputs: vec![FieldSchema {
- name: "tools",
- ty: TypeSchema::Array(Box::new(TypeSchema::Json)),
- comment: "Matches: { slug, toolkit, description, required_args, output_fields, primary_array_path, featured }.",
- required: true,
- }],
- },
- "get_tool_contract" => ControllerSchema {
- namespace: "flows",
- function: "get_tool_contract",
- description: "Fetch one Composio action's full contract (secret-free) for the canvas \
- tool browser — the same core as the agent's get_tool_contract tool.",
- inputs: vec![FieldSchema {
- name: "slug",
- ty: TypeSchema::String,
- comment: "The exact Composio action slug (e.g. `GMAIL_SEND_EMAIL`).",
- required: true,
- }],
- outputs: vec![FieldSchema {
- name: "contract",
- ty: TypeSchema::Json,
- comment: "The action contract: { slug, toolkit, description, required_args, input_schema, output_fields, output_schema, primary_array_path, is_curated }.",
- required: true,
- }],
- },
- "get_history" => ControllerSchema {
- namespace: "flows",
- function: "get_history",
- description: "List a flow's revision history — prior graph snapshots captured on each \
- update (capped, newest first). The safety rail behind rollback.",
- inputs: vec![
- id_input("Identifier of the flow whose history to list."),
- FieldSchema {
- name: "limit",
- ty: TypeSchema::Option(Box::new(TypeSchema::U64)),
- comment: "Max revisions to return (defaults to the retention cap).",
- required: false,
- },
- ],
- outputs: vec![FieldSchema {
- name: "revisions",
- ty: TypeSchema::Array(Box::new(TypeSchema::Json)),
- comment: "Revision snapshots: { id, flow_id, graph, name, require_approval, created_at }.",
- required: true,
- }],
- },
- "rollback" => ControllerSchema {
- namespace: "flows",
- function: "rollback",
- description: "Roll a flow back to a prior revision (restores that revision's graph \
- through the normal update path — itself snapshotted, so rollback is \
- undoable). Honours optimistic concurrency via expected_version.",
- inputs: vec![
- id_input("Identifier of the flow to roll back."),
- FieldSchema {
- name: "revision_id",
- ty: TypeSchema::String,
- comment: "The revision (from get_history) to restore.",
- required: true,
- },
- expected_version_input(),
- ],
- outputs: vec![flow_output()],
- },
- "draft_create" => ControllerSchema {
- namespace: "flows",
- function: "draft_create",
- description: "Create a core-managed draft (a durable, non-live working copy of a graph) \
- shared by the agent tools and the canvas. Never persists a flow.",
- inputs: vec![
- FieldSchema {
- name: "name",
- ty: TypeSchema::String,
- comment: "Human-readable draft name (carried into the flow on promote).",
- required: true,
- },
- FieldSchema {
- name: "graph",
- ty: TypeSchema::Json,
- comment: "The (possibly incomplete) WorkflowGraph JSON to hold in the draft.",
- required: true,
- },
- FieldSchema {
- name: "flow_id",
- ty: TypeSchema::Option(Box::new(TypeSchema::String)),
- comment: "The saved flow this draft edits, if any (promote → update vs create).",
- required: false,
- },
- FieldSchema {
- name: "origin",
- ty: TypeSchema::Option(Box::new(TypeSchema::String)),
- comment: "Where the draft came from: `chat` | `canvas` | `import`. Defaults to `canvas`.",
- required: false,
- },
- ],
- outputs: vec![draft_output()],
- },
- "draft_get" => ControllerSchema {
- namespace: "flows",
- function: "draft_get",
- description: "Fetch a draft by id.",
- inputs: vec![id_input("Identifier of the draft to fetch.")],
- outputs: vec![draft_output()],
- },
- "draft_update" => ControllerSchema {
- namespace: "flows",
- function: "draft_update",
- description: "Patch a draft's name/graph/flow_id (any provided field) and bump its \
- updated_at. Never persists a flow.",
- inputs: vec![
- id_input("Identifier of the draft to update."),
- FieldSchema {
- name: "name",
- ty: TypeSchema::Option(Box::new(TypeSchema::String)),
- comment: "New name, if changing it.",
- required: false,
- },
- FieldSchema {
- name: "graph",
- ty: TypeSchema::Option(Box::new(TypeSchema::Json)),
- comment: "New graph JSON, if changing it.",
- required: false,
- },
- FieldSchema {
- name: "flow_id",
- ty: TypeSchema::Option(Box::new(TypeSchema::String)),
- comment: "New linked flow id, if changing it.",
- required: false,
- },
- ],
- outputs: vec![draft_output()],
- },
- "draft_list" => ControllerSchema {
- namespace: "flows",
- function: "draft_list",
- description: "List all drafts, newest-updated first.",
- inputs: vec![],
- outputs: vec![FieldSchema {
- name: "drafts",
- ty: TypeSchema::Array(Box::new(TypeSchema::Json)),
- comment: "The drafts (each { id, flow_id?, name, graph, origin, created_at, updated_at }).",
- required: true,
- }],
- },
- "draft_delete" => ControllerSchema {
- namespace: "flows",
- function: "draft_delete",
- description: "Delete a draft by id (idempotent).",
- inputs: vec![id_input("Identifier of the draft to delete.")],
- outputs: vec![FieldSchema {
- name: "result",
- ty: TypeSchema::Json,
- comment: "`{ id, deleted }` — `deleted` is false if the id was already absent.",
- required: true,
- }],
- },
- "draft_promote" => ControllerSchema {
- namespace: "flows",
- function: "draft_promote",
- description: "Promote a draft into a saved flow through the same create/update gates \
- (structural validation, forced require_approval floor, born-disabled for \
- automatic triggers), then delete the draft file. A draft with a flow_id \
- updates that flow; otherwise it creates a new one.",
- inputs: vec![
- id_input("Identifier of the draft to promote."),
- require_approval_input(),
- ],
- outputs: vec![flow_output()],
- },
- _other => ControllerSchema {
- namespace: "flows",
- function: "unknown",
- description: "Unknown flows controller function.",
- inputs: vec![FieldSchema {
- name: "function",
- ty: TypeSchema::String,
- comment: "Unknown function requested for schema lookup.",
- required: true,
- }],
- outputs: vec![FieldSchema {
- name: "error",
- ty: TypeSchema::String,
- comment: "Lookup error details.",
- required: true,
- }],
- },
+ if let Some(schema) = flows_schema_part_01::lookup(function) {
+ return schema;
}
-}
-
-fn handle_create(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
- let name = read_required::<String>(&params, "name")?;
- let graph = read_required::<Value>(&params, "graph")?;
- let require_approval = params
- .get("require_approval")
- .and_then(Value::as_bool)
- .unwrap_or(false);
- // Opt-in strict mode (F3): run the same author hard-gates an agent save
- // must pass, before persisting. Default off — the human canvas save
- // path stays permissive.
- if params
- .get("strict")
- .and_then(Value::as_bool)
- .unwrap_or(false)
- {
- ops::strict_gate(&config, &graph).await?;
- }
- to_json(ops::flows_create(&config, name, graph, require_approval).await?)
- })
-}
-
-fn handle_validate(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- // No config load: validation is pure (no persistence, no workspace).
- let graph = read_required::<Value>(&params, "graph")?;
- to_json(ops::flows_validate(graph))
- })
-}
-
-fn handle_import(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- // No config load: import is pure (no persistence, no workspace).
- let graph = read_required::<Value>(&params, "graph")?;
- let format = params
- .get("format")
- .filter(|v| !v.is_null())
- .map(|v| serde_json::from_value::<String>(v.clone()))
- .transpose()
- .map_err(|e| format!("invalid 'format': {e}"))?;
- to_json(ops::flows_import(graph, format)?)
- })
-}
-
-fn handle_duplicate(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
- let id = read_required::<String>(&params, "id")?;
- to_json(ops::flows_duplicate(&config, id.trim()).await?)
- })
-}
-
-fn handle_get(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
- let id = read_required::<String>(&params, "id")?;
- to_json(ops::flows_get(&config, id.trim()).await?)
- })
-}
-
-fn handle_list(_params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
- to_json(ops::flows_list(&config).await?)
- })
-}
-
-fn handle_list_connections(_params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
- to_json(ops::flows_list_connections(&config).await?)
- })
-}
-
-fn handle_update(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
- let id = read_required::<String>(&params, "id")?;
- let name = params
- .get("name")
- .filter(|v| !v.is_null())
- .map(|v| serde_json::from_value(v.clone()))
- .transpose()
- .map_err(|e| format!("invalid 'name': {e}"))?;
- let graph = params.get("graph").filter(|v| !v.is_null()).cloned();
- let require_approval = params.get("require_approval").and_then(Value::as_bool);
- let expected_version = params
- .get("expected_version")
- .and_then(Value::as_str)
- .filter(|s| !s.is_empty())
- .map(str::to_string);
- // Opt-in strict mode (F3): when a new graph is supplied, run the same
- // author hard-gates an agent save must pass, before persisting.
- if params
- .get("strict")
- .and_then(Value::as_bool)
- .unwrap_or(false)
- {
- if let Some(graph_json) = graph.as_ref() {
- ops::strict_gate(&config, graph_json).await?;
- }
- }
- to_json(
- ops::flows_update(
- &config,
- id.trim(),
- name,
- graph,
- require_approval,
- expected_version,
- )
- .await?,
- )
- })
-}
-
-fn handle_delete(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
- let id = read_required::<String>(&params, "id")?;
- to_json(ops::flows_delete(&config, id.trim()).await?)
- })
-}
-
-fn handle_set_enabled(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
- let id = read_required::<String>(&params, "id")?;
- let enabled = params
- .get("enabled")
- .and_then(Value::as_bool)
- .ok_or_else(|| "missing required param 'enabled'".to_string())?;
- to_json(ops::flows_set_enabled(&config, id.trim(), enabled).await?)
- })
-}
-
-fn handle_run(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
- let id = read_required::<String>(&params, "id")?;
- let input = params.get("input").cloned().unwrap_or(Value::Null);
- let inputs = read_declared_inputs(&params)?;
- to_json(
- ops::flows_run(
- &config,
- id.trim(),
- input,
- inputs,
- crate::openhuman::flows::FlowRunTrigger::Rpc,
- )
- .await?,
- )
- })
-}
-
-fn handle_run_detached(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
- let id = read_required::<String>(&params, "id")?;
- let input = params.get("input").cloned().unwrap_or(Value::Null);
- let inputs = read_declared_inputs(&params)?;
- to_json(
- ops::flows_run_detached(
- &config,
- id.trim(),
- input,
- inputs,
- crate::openhuman::flows::FlowRunTrigger::Rpc,
- )
- .await?,
- )
- })
-}
-
-/// Reads the optional `inputs` param — values for the flow's declared workflow
-/// inputs, keyed by name.
-///
-/// Absent or `null` means "supplied nothing", which is valid for a flow whose
-/// inputs are all optional or defaulted. A present-but-non-object value is a
-/// caller error rejected here, before it reaches `ops`, so the message names the
-/// parameter rather than surfacing as a confusing per-input complaint.
-fn read_declared_inputs(params: &Map<String, Value>) -> Result<Map<String, Value>, String> {
- match params.get("inputs") {
- None | Some(Value::Null) => Ok(Map::new()),
- Some(Value::Object(map)) => Ok(map.clone()),
- Some(other) => Err(format!(
- "param 'inputs' must be an object keyed by declared input name, got {}",
- match other {
- Value::Array(_) => "an array",
- Value::String(_) => "a string",
- Value::Number(_) => "a number",
- Value::Bool(_) => "a boolean",
- _ => "a non-object",
- }
- )),
+ if let Some(schema) = flows_schema_part_02::lookup(function) {
+ return schema;
}
-}
-
-fn handle_resume(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
- let id = read_required::<String>(&params, "id")?;
- let thread_id = read_required::<String>(&params, "thread_id")?;
- let approvals: Vec<String> = params
- .get("approvals")
- .filter(|v| !v.is_null())
- .cloned()
- .map(serde_json::from_value)
- .transpose()
- .map_err(|e| format!("invalid 'approvals': {e}"))?
- .unwrap_or_default();
- let rejections: Vec<String> = params
- .get("rejections")
- .filter(|v| !v.is_null())
- .cloned()
- .map(serde_json::from_value)
- .transpose()
- .map_err(|e| format!("invalid 'rejections': {e}"))?
- .unwrap_or_default();
- to_json(
- ops::flows_resume(&config, id.trim(), thread_id.trim(), approvals, rejections).await?,
- )
- })
-}
-
-fn handle_cancel_run(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
- let run_id = read_required::<String>(&params, "run_id")?;
- to_json(ops::flows_cancel_run(&config, run_id.trim()).await?)
- })
-}
-
-fn handle_list_runs(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
- let id = read_required::<String>(&params, "id")?;
- let limit = params
- .get("limit")
- .and_then(Value::as_u64)
- .and_then(|n| usize::try_from(n).ok())
- .unwrap_or(20);
- to_json(ops::flows_list_runs(&config, id.trim(), limit).await?)
- })
-}
-
-fn handle_list_all_runs(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
- let limit = params
- .get("limit")
- .and_then(Value::as_u64)
- .and_then(|n| usize::try_from(n).ok())
- .unwrap_or(100);
- to_json(ops::flows_list_all_runs(&config, limit).await?)
- })
-}
-
-fn handle_get_run(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
- let run_id = read_required::<String>(&params, "run_id")?;
- to_json(ops::flows_get_run(&config, run_id.trim()).await?)
- })
-}
-
-fn handle_prune_runs(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
- let id = read_required::<String>(&params, "id")?;
- to_json(ops::flows_prune_runs(&config, id.trim()).await?)
- })
-}
-
-fn handle_build(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
- // Optional streaming target: when the copilot passes its chat `thread_id`
- // the builder turn streams live text/tool/proposal events into that
- // thread (Phase B). Read + strip the transport-only keys before the rest
- // of the object is deserialized into the structured BuilderRequest.
- let stream = read_flow_stream_target(&params);
- // Deserialize the remaining param object into the structured BuilderRequest
- // (mode/instruction/graph/flow_id/run_id/error/failing_node_ids). The
- // stream keys are ignored (BuilderRequest doesn't declare them).
- let req: crate::openhuman::flows::agents::workflow_builder::builder_prompt::BuilderRequest =
- serde_json::from_value(Value::Object(params))
- .map_err(|e| format!("invalid flows.build params: {e}"))?;
- to_json(ops::flows_build(&config, req, stream).await?)
- })
-}
-
-fn handle_build_cancel(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let thread_id = read_required::<String>(&params, "thread_id")?;
- let request_id = params
- .get("request_id")
- .and_then(Value::as_str)
- .map(str::to_string);
- to_json(ops::flows_build_cancel(thread_id.trim(), request_id.as_deref()).await?)
- })
-}
-
-fn handle_discover(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
- // Optional streaming target for the Flow Scout run (Phase B) — same
- // `thread_id`/`request_id` convention as `flows.build`.
- let stream = read_flow_stream_target(&params);
- to_json(ops::flows_discover(&config, stream).await?)
- })
-}
-
-/// Read the optional `thread_id` / `request_id` streaming params shared by
-/// `flows.build` and `flows.discover` into an [`ops::FlowStreamTarget`].
-/// Returns `None` (headless run) when no usable `thread_id` is present; a
-/// missing `request_id` is filled with a fresh uuid inside `from_params`.
-fn read_flow_stream_target(params: &Map<String, Value>) -> Option<ops::FlowStreamTarget> {
- let thread_id = params
- .get("thread_id")
- .and_then(Value::as_str)
- .map(str::to_string);
- let request_id = params
- .get("request_id")
- .and_then(Value::as_str)
- .map(str::to_string);
- ops::FlowStreamTarget::from_params(thread_id, request_id)
-}
-
-fn handle_list_suggestions(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
- let status = params
- .get("status")
- .and_then(Value::as_str)
- .map(str::trim)
- .filter(|s| !s.is_empty())
- .map(crate::openhuman::flows::SuggestionStatus::from_str_lossy);
- to_json(ops::flows_list_suggestions(&config, status).await?)
- })
-}
-
-fn handle_dismiss_suggestion(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
- let id = read_required::<String>(&params, "id")?;
- to_json(ops::flows_dismiss_suggestion(&config, id.trim()).await?)
- })
-}
-
-fn handle_mark_suggestion_built(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
- let id = read_required::<String>(&params, "id")?;
- to_json(ops::flows_mark_suggestion_built(&config, id.trim()).await?)
- })
-}
-
-fn handle_required_connections(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
- let graph = read_required::<Value>(&params, "graph")?;
- to_json(ops::flows_required_connections(&config, graph).await?)
- })
-}
-
-fn handle_approval_manifest(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
- let id = params
- .get("id")
- .and_then(Value::as_str)
- .filter(|s| !s.trim().is_empty())
- .map(str::to_string);
- let graph = params.get("graph").filter(|v| !v.is_null()).cloned();
- to_json(ops::flows_approval_manifest(&config, id.as_deref(), graph).await?)
- })
-}
-
-fn handle_search_tool_catalog(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
- let query = read_required::<String>(&params, "query")?;
- let toolkit = params
- .get("toolkit")
- .and_then(Value::as_str)
- .filter(|s| !s.is_empty());
- let limit = params
- .get("limit")
- .and_then(Value::as_u64)
- .map(|n| n as usize)
- .unwrap_or(25);
- to_json(ops::flows_search_tool_catalog(&config, query.trim(), toolkit, limit).await?)
- })
-}
-
-fn handle_get_tool_contract(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
- let slug = read_required::<String>(&params, "slug")?;
- to_json(ops::flows_get_tool_contract(&config, slug.trim()).await?)
- })
-}
-
-fn handle_get_history(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
- let id = read_required::<String>(&params, "id")?;
- let limit = params
- .get("limit")
- .and_then(Value::as_u64)
- .map(|n| n as usize)
- .unwrap_or(20);
- to_json(ops::flows_get_history(&config, id.trim(), limit)?)
- })
-}
-
-fn handle_rollback(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
- let id = read_required::<String>(&params, "id")?;
- let revision_id = read_required::<String>(&params, "revision_id")?;
- let expected_version = params
- .get("expected_version")
- .and_then(Value::as_str)
- .filter(|s| !s.is_empty())
- .map(str::to_string);
- to_json(
- ops::flows_rollback(&config, id.trim(), revision_id.trim(), expected_version).await?,
- )
- })
-}
-
-fn handle_draft_create(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
- let name = read_required::<String>(&params, "name")?;
- let graph = read_required::<Value>(&params, "graph")?;
- let flow_id = params
- .get("flow_id")
- .and_then(Value::as_str)
- .filter(|s| !s.is_empty())
- .map(str::to_string);
- let origin = params
- .get("origin")
- .and_then(Value::as_str)
- .and_then(|s| serde_json::from_value(Value::String(s.to_string())).ok())
- .unwrap_or(crate::openhuman::flows::DraftOrigin::Canvas);
- to_json(ops::flows_draft_create(
- &config, flow_id, name, graph, origin,
- )?)
- })
-}
-
-fn handle_draft_get(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
- let id = read_required::<String>(&params, "id")?;
- to_json(ops::flows_draft_get(&config, id.trim())?)
- })
-}
-
-fn handle_draft_update(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
- let id = read_required::<String>(&params, "id")?;
- let name = params
- .get("name")
- .filter(|v| !v.is_null())
- .map(|v| serde_json::from_value(v.clone()))
- .transpose()
- .map_err(|e| format!("invalid 'name': {e}"))?;
- let graph = params.get("graph").filter(|v| !v.is_null()).cloned();
- // A present `flow_id` (even null) re-links the draft; absent leaves it.
- let flow_id = parse_draft_update_flow_id(&params)?;
- to_json(ops::flows_draft_update(
- &config,
- id.trim(),
- name,
- graph,
- flow_id,
- )?)
- })
-}
-
-fn handle_draft_list(_params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
- to_json(ops::flows_draft_list(&config)?)
- })
-}
-
-fn handle_draft_delete(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
- let id = read_required::<String>(&params, "id")?;
- to_json(ops::flows_draft_delete(&config, id.trim())?)
- })
-}
-
-fn handle_draft_promote(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
- let id = read_required::<String>(&params, "id")?;
- let require_approval = params.get("require_approval").and_then(Value::as_bool);
- to_json(ops::flows_draft_promote(&config, id.trim(), require_approval).await?)
- })
-}
-
-fn read_required<T: DeserializeOwned>(params: &Map<String, Value>, key: &str) -> Result<T, String> {
- let value = params
- .get(key)
- .cloned()
- .ok_or_else(|| format!("missing required param '{key}'"))?;
- serde_json::from_value(value).map_err(|e| format!("invalid '{key}': {e}"))
-}
-
-fn to_json<T: serde::Serialize>(outcome: RpcOutcome<T>) -> Result<Value, String> {
- outcome.into_cli_compatible_json()
-}
-
-/// Parses `draft_update`'s `flow_id` param (R-m7). The outer `Option`
-/// mirrors `ops::flows_draft_update`'s "present vs absent" contract — absent
-/// leaves the draft's existing link untouched; the inner `Option` is the new
-/// link (`None` unlinks).
-///
-/// A present-but-non-string `flow_id` (a number, or an object from a buggy
-/// client) is REJECTED rather than silently coerced into `Some(None)` via
-/// `Value::as_str()` returning `None` on a type mismatch — that shape used
-/// to be indistinguishable from an explicit `flow_id: null` unlink, and
-/// `update_draft` treats `Some(None)` as exactly that: unlinking the draft
-/// from its flow. A later `draft_promote` then creates a brand-new flow
-/// instead of updating the one the caller actually meant.
-fn parse_draft_update_flow_id(
- params: &Map<String, Value>,
-) -> Result<Option<Option<String>>, String> {
- match params.get("flow_id") {
- None => Ok(None),
- Some(Value::Null) => Ok(Some(None)),
- Some(Value::String(s)) => {
- let s = s.trim();
- Ok(Some(if s.is_empty() {
- None
- } else {
- Some(s.to_string())
- }))
- }
- Some(other) => Err(format!(
- "invalid 'flow_id': expected a string or null, got {other}"
- )),
+ ControllerSchema {
+ namespace: "flows",
+ function: "unknown",
+ description: "Unknown flows controller function.",
+ inputs: vec![FieldSchema {
+ name: "function",
+ ty: TypeSchema::String,
+ comment: "Unknown function requested for schema lookup.",
+ required: true,
+ }],
+ outputs: vec![FieldSchema {
+ name: "error",
+ ty: TypeSchema::String,
+ comment: "Lookup error details.",
+ required: true,
+ }],
}
}
-#[cfg(test)]
-#[path = "schemas_tests.rs"]
-mod tests;
+include!("schemas_handlers.rs");
diff --git a/src/openhuman/flows/schemas_handlers.rs b/src/openhuman/flows/schemas_handlers.rs
new file mode 100644
index 0000000000..f4aa302cb5
--- /dev/null
+++ b/src/openhuman/flows/schemas_handlers.rs
@@ -0,0 +1,557 @@
+fn handle_create(params: Map<String, Value>) -> ControllerFuture {
+ Box::pin(async move {
+ let config = config_rpc::load_config_with_timeout().await?;
+ let name = read_required::<String>(&params, "name")?;
+ let graph = read_required::<Value>(&params, "graph")?;
+ let require_approval = params
+ .get("require_approval")
+ .and_then(Value::as_bool)
+ .unwrap_or(false);
+ // Opt-in strict mode (F3): run the same author hard-gates an agent save
+ // must pass, before persisting. Default off — the human canvas save
+ // path stays permissive.
+ if params
+ .get("strict")
+ .and_then(Value::as_bool)
+ .unwrap_or(false)
+ {
+ ops::strict_gate(&config, &graph).await?;
+ }
+ to_json(ops::flows_create(&config, name, graph, require_approval).await?)
+ })
+}
+
+fn handle_validate(params: Map<String, Value>) -> ControllerFuture {
+ Box::pin(async move {
+ // No config load: validation is pure (no persistence, no workspace).
+ let graph = read_required::<Value>(&params, "graph")?;
+ to_json(ops::flows_validate(graph))
+ })
+}
+
+fn handle_import(params: Map<String, Value>) -> ControllerFuture {
+ Box::pin(async move {
+ // No config load: import is pure (no persistence, no workspace).
+ let graph = read_required::<Value>(&params, "graph")?;
+ let format = params
+ .get("format")
+ .filter(|v| !v.is_null())
+ .map(|v| serde_json::from_value::<String>(v.clone()))
+ .transpose()
+ .map_err(|e| format!("invalid 'format': {e}"))?;
+ to_json(ops::flows_import(graph, format)?)
+ })
+}
+
+fn handle_duplicate(params: Map<String, Value>) -> ControllerFuture {
+ Box::pin(async move {
+ let config = config_rpc::load_config_with_timeout().await?;
+ let id = read_required::<String>(&params, "id")?;
+ to_json(ops::flows_duplicate(&config, id.trim()).await?)
+ })
+}
+
+fn handle_get(params: Map<String, Value>) -> ControllerFuture {
+ Box::pin(async move {
+ let config = config_rpc::load_config_with_timeout().await?;
+ let id = read_required::<String>(&params, "id")?;
+ to_json(ops::flows_get(&config, id.trim()).await?)
+ })
+}
+
+fn handle_list(_params: Map<String, Value>) -> ControllerFuture {
+ Box::pin(async move {
+ let config = config_rpc::load_config_with_timeout().await?;
+ to_json(ops::flows_list(&config).await?)
+ })
+}
+
+fn handle_list_connections(_params: Map<String, Value>) -> ControllerFuture {
+ Box::pin(async move {
+ let config = config_rpc::load_config_with_timeout().await?;
+ to_json(ops::flows_list_connections(&config).await?)
+ })
+}
+
+fn handle_update(params: Map<String, Value>) -> ControllerFuture {
+ Box::pin(async move {
+ let config = config_rpc::load_config_with_timeout().await?;
+ let id = read_required::<String>(&params, "id")?;
+ let name = params
+ .get("name")
+ .filter(|v| !v.is_null())
+ .map(|v| serde_json::from_value(v.clone()))
+ .transpose()
+ .map_err(|e| format!("invalid 'name': {e}"))?;
+ let graph = params.get("graph").filter(|v| !v.is_null()).cloned();
+ let require_approval = params.get("require_approval").and_then(Value::as_bool);
+ let expected_version = params
+ .get("expected_version")
+ .and_then(Value::as_str)
+ .filter(|s| !s.is_empty())
+ .map(str::to_string);
+ // Opt-in strict mode (F3): when a new graph is supplied, run the same
+ // author hard-gates an agent save must pass, before persisting.
+ if params
+ .get("strict")
+ .and_then(Value::as_bool)
+ .unwrap_or(false)
+ {
+ if let Some(graph_json) = graph.as_ref() {
+ ops::strict_gate(&config, graph_json).await?;
+ }
+ }
+ to_json(
+ ops::flows_update(
+ &config,
+ id.trim(),
+ name,
+ graph,
+ require_approval,
+ expected_version,
+ )
+ .await?,
+ )
+ })
+}
+
+fn handle_delete(params: Map<String, Value>) -> ControllerFuture {
+ Box::pin(async move {
+ let config = config_rpc::load_config_with_timeout().await?;
+ let id = read_required::<String>(&params, "id")?;
+ to_json(ops::flows_delete(&config, id.trim()).await?)
+ })
+}
+
+fn handle_set_enabled(params: Map<String, Value>) -> ControllerFuture {
+ Box::pin(async move {
+ let config = config_rpc::load_config_with_timeout().await?;
+ let id = read_required::<String>(&params, "id")?;
+ let enabled = params
+ .get("enabled")
+ .and_then(Value::as_bool)
+ .ok_or_else(|| "missing required param 'enabled'".to_string())?;
+ to_json(ops::flows_set_enabled(&config, id.trim(), enabled).await?)
+ })
+}
+
+fn handle_run(params: Map<String, Value>) -> ControllerFuture {
+ Box::pin(async move {
+ let config = config_rpc::load_config_with_timeout().await?;
+ let id = read_required::<String>(&params, "id")?;
+ let input = params.get("input").cloned().unwrap_or(Value::Null);
+ let inputs = read_declared_inputs(&params)?;
+ to_json(
+ ops::flows_run(
+ &config,
+ id.trim(),
+ input,
+ inputs,
+ crate::openhuman::flows::FlowRunTrigger::Rpc,
+ )
+ .await?,
+ )
+ })
+}
+
+fn handle_run_detached(params: Map<String, Value>) -> ControllerFuture {
+ Box::pin(async move {
+ let config = config_rpc::load_config_with_timeout().await?;
+ let id = read_required::<String>(&params, "id")?;
+ let input = params.get("input").cloned().unwrap_or(Value::Null);
+ let inputs = read_declared_inputs(&params)?;
+ to_json(
+ ops::flows_run_detached(
+ &config,
+ id.trim(),
+ input,
+ inputs,
+ crate::openhuman::flows::FlowRunTrigger::Rpc,
+ )
+ .await?,
+ )
+ })
+}
+
+/// Reads the optional `inputs` param — values for the flow's declared workflow
+/// inputs, keyed by name.
+///
+/// Absent or `null` means "supplied nothing", which is valid for a flow whose
+/// inputs are all optional or defaulted. A present-but-non-object value is a
+/// caller error rejected here, before it reaches `ops`, so the message names the
+/// parameter rather than surfacing as a confusing per-input complaint.
+fn read_declared_inputs(params: &Map<String, Value>) -> Result<Map<String, Value>, String> {
+ match params.get("inputs") {
+ None | Some(Value::Null) => Ok(Map::new()),
+ Some(Value::Object(map)) => Ok(map.clone()),
+ Some(other) => Err(format!(
+ "param 'inputs' must be an object keyed by declared input name, got {}",
+ match other {
+ Value::Array(_) => "an array",
+ Value::String(_) => "a string",
+ Value::Number(_) => "a number",
+ Value::Bool(_) => "a boolean",
+ _ => "a non-object",
+ }
+ )),
+ }
+}
+
+fn handle_resume(params: Map<String, Value>) -> ControllerFuture {
+ Box::pin(async move {
+ let config = config_rpc::load_config_with_timeout().await?;
+ let id = read_required::<String>(&params, "id")?;
+ let thread_id = read_required::<String>(&params, "thread_id")?;
+ let approvals: Vec<String> = params
+ .get("approvals")
+ .filter(|v| !v.is_null())
+ .cloned()
+ .map(serde_json::from_value)
+ .transpose()
+ .map_err(|e| format!("invalid 'approvals': {e}"))?
+ .unwrap_or_default();
+ let rejections: Vec<String> = params
+ .get("rejections")
+ .filter(|v| !v.is_null())
+ .cloned()
+ .map(serde_json::from_value)
+ .transpose()
+ .map_err(|e| format!("invalid 'rejections': {e}"))?
+ .unwrap_or_default();
+ to_json(
+ ops::flows_resume(&config, id.trim(), thread_id.trim(), approvals, rejections).await?,
+ )
+ })
+}
+
+fn handle_cancel_run(params: Map<String, Value>) -> ControllerFuture {
+ Box::pin(async move {
+ let config = config_rpc::load_config_with_timeout().await?;
+ let run_id = read_required::<String>(&params, "run_id")?;
+ to_json(ops::flows_cancel_run(&config, run_id.trim()).await?)
+ })
+}
+
+fn handle_list_runs(params: Map<String, Value>) -> ControllerFuture {
+ Box::pin(async move {
+ let config = config_rpc::load_config_with_timeout().await?;
+ let id = read_required::<String>(&params, "id")?;
+ let limit = params
+ .get("limit")
+ .and_then(Value::as_u64)
+ .and_then(|n| usize::try_from(n).ok())
+ .unwrap_or(20);
+ to_json(ops::flows_list_runs(&config, id.trim(), limit).await?)
+ })
+}
+
+fn handle_list_all_runs(params: Map<String, Value>) -> ControllerFuture {
+ Box::pin(async move {
+ let config = config_rpc::load_config_with_timeout().await?;
+ let limit = params
+ .get("limit")
+ .and_then(Value::as_u64)
+ .and_then(|n| usize::try_from(n).ok())
+ .unwrap_or(100);
+ to_json(ops::flows_list_all_runs(&config, limit).await?)
+ })
+}
+
+fn handle_get_run(params: Map<String, Value>) -> ControllerFuture {
+ Box::pin(async move {
+ let config = config_rpc::load_config_with_timeout().await?;
+ let run_id = read_required::<String>(&params, "run_id")?;
+ to_json(ops::flows_get_run(&config, run_id.trim()).await?)
+ })
+}
+
+fn handle_prune_runs(params: Map<String, Value>) -> ControllerFuture {
+ Box::pin(async move {
+ let config = config_rpc::load_config_with_timeout().await?;
+ let id = read_required::<String>(&params, "id")?;
+ to_json(ops::flows_prune_runs(&config, id.trim()).await?)
+ })
+}
+
+fn handle_build(params: Map<String, Value>) -> ControllerFuture {
+ Box::pin(async move {
+ let config = config_rpc::load_config_with_timeout().await?;
+ // Optional streaming target: when the copilot passes its chat `thread_id`
+ // the builder turn streams live text/tool/proposal events into that
+ // thread (Phase B). Read + strip the transport-only keys before the rest
+ // of the object is deserialized into the structured BuilderRequest.
+ let stream = read_flow_stream_target(&params);
+ // Deserialize the remaining param object into the structured BuilderRequest
+ // (mode/instruction/graph/flow_id/run_id/error/failing_node_ids). The
+ // stream keys are ignored (BuilderRequest doesn't declare them).
+ let req: crate::openhuman::flows::agents::workflow_builder::builder_prompt::BuilderRequest =
+ serde_json::from_value(Value::Object(params))
+ .map_err(|e| format!("invalid flows.build params: {e}"))?;
+ to_json(ops::flows_build(&config, req, stream).await?)
+ })
+}
+
+fn handle_build_cancel(params: Map<String, Value>) -> ControllerFuture {
+ Box::pin(async move {
+ let thread_id = read_required::<String>(&params, "thread_id")?;
+ let request_id = params
+ .get("request_id")
+ .and_then(Value::as_str)
+ .map(str::to_string);
+ to_json(ops::flows_build_cancel(thread_id.trim(), request_id.as_deref()).await?)
+ })
+}
+
+fn handle_discover(params: Map<String, Value>) -> ControllerFuture {
+ Box::pin(async move {
+ let config = config_rpc::load_config_with_timeout().await?;
+ // Optional streaming target for the Flow Scout run (Phase B) — same
+ // `thread_id`/`request_id` convention as `flows.build`.
+ let stream = read_flow_stream_target(&params);
+ to_json(ops::flows_discover(&config, stream).await?)
+ })
+}
+
+/// Read the optional `thread_id` / `request_id` streaming params shared by
+/// `flows.build` and `flows.discover` into an [`ops::FlowStreamTarget`].
+/// Returns `None` (headless run) when no usable `thread_id` is present; a
+/// missing `request_id` is filled with a fresh uuid inside `from_params`.
+fn read_flow_stream_target(params: &Map<String, Value>) -> Option<ops::FlowStreamTarget> {
+ let thread_id = params
+ .get("thread_id")
+ .and_then(Value::as_str)
+ .map(str::to_string);
+ let request_id = params
+ .get("request_id")
+ .and_then(Value::as_str)
+ .map(str::to_string);
+ ops::FlowStreamTarget::from_params(thread_id, request_id)
+}
+
+fn handle_list_suggestions(params: Map<String, Value>) -> ControllerFuture {
+ Box::pin(async move {
+ let config = config_rpc::load_config_with_timeout().await?;
+ let status = params
+ .get("status")
+ .and_then(Value::as_str)
+ .map(str::trim)
+ .filter(|s| !s.is_empty())
+ .map(crate::openhuman::flows::SuggestionStatus::from_str_lossy);
+ to_json(ops::flows_list_suggestions(&config, status).await?)
+ })
+}
+
+fn handle_dismiss_suggestion(params: Map<String, Value>) -> ControllerFuture {
+ Box::pin(async move {
+ let config = config_rpc::load_config_with_timeout().await?;
+ let id = read_required::<String>(&params, "id")?;
+ to_json(ops::flows_dismiss_suggestion(&config, id.trim()).await?)
+ })
+}
+
+fn handle_mark_suggestion_built(params: Map<String, Value>) -> ControllerFuture {
+ Box::pin(async move {
+ let config = config_rpc::load_config_with_timeout().await?;
+ let id = read_required::<String>(&params, "id")?;
+ to_json(ops::flows_mark_suggestion_built(&config, id.trim()).await?)
+ })
+}
+
+fn handle_required_connections(params: Map<String, Value>) -> ControllerFuture {
+ Box::pin(async move {
+ let config = config_rpc::load_config_with_timeout().await?;
+ let graph = read_required::<Value>(&params, "graph")?;
+ to_json(ops::flows_required_connections(&config, graph).await?)
+ })
+}
+
+fn handle_approval_manifest(params: Map<String, Value>) -> ControllerFuture {
+ Box::pin(async move {
+ let config = config_rpc::load_config_with_timeout().await?;
+ let id = params
+ .get("id")
+ .and_then(Value::as_str)
+ .filter(|s| !s.trim().is_empty())
+ .map(str::to_string);
+ let graph = params.get("graph").filter(|v| !v.is_null()).cloned();
+ to_json(ops::flows_approval_manifest(&config, id.as_deref(), graph).await?)
+ })
+}
+
+fn handle_search_tool_catalog(params: Map<String, Value>) -> ControllerFuture {
+ Box::pin(async move {
+ let config = config_rpc::load_config_with_timeout().await?;
+ let query = read_required::<String>(&params, "query")?;
+ let toolkit = params
+ .get("toolkit")
+ .and_then(Value::as_str)
+ .filter(|s| !s.is_empty());
+ let limit = params
+ .get("limit")
+ .and_then(Value::as_u64)
+ .map(|n| n as usize)
+ .unwrap_or(25);
+ to_json(ops::flows_search_tool_catalog(&config, query.trim(), toolkit, limit).await?)
+ })
+}
+
+fn handle_get_tool_contract(params: Map<String, Value>) -> ControllerFuture {
+ Box::pin(async move {
+ let config = config_rpc::load_config_with_timeout().await?;
+ let slug = read_required::<String>(&params, "slug")?;
+ to_json(ops::flows_get_tool_contract(&config, slug.trim()).await?)
+ })
+}
+
+fn handle_get_history(params: Map<String, Value>) -> ControllerFuture {
+ Box::pin(async move {
+ let config = config_rpc::load_config_with_timeout().await?;
+ let id = read_required::<String>(&params, "id")?;
+ let limit = params
+ .get("limit")
+ .and_then(Value::as_u64)
+ .map(|n| n as usize)
+ .unwrap_or(20);
+ to_json(ops::flows_get_history(&config, id.trim(), limit)?)
+ })
+}
+
+fn handle_rollback(params: Map<String, Value>) -> ControllerFuture {
+ Box::pin(async move {
+ let config = config_rpc::load_config_with_timeout().await?;
+ let id = read_required::<String>(&params, "id")?;
+ let revision_id = read_required::<String>(&params, "revision_id")?;
+ let expected_version = params
+ .get("expected_version")
+ .and_then(Value::as_str)
+ .filter(|s| !s.is_empty())
+ .map(str::to_string);
+ to_json(
+ ops::flows_rollback(&config, id.trim(), revision_id.trim(), expected_version).await?,
+ )
+ })
+}
+
+fn handle_draft_create(params: Map<String, Value>) -> ControllerFuture {
+ Box::pin(async move {
+ let config = config_rpc::load_config_with_timeout().await?;
+ let name = read_required::<String>(&params, "name")?;
+ let graph = read_required::<Value>(&params, "graph")?;
+ let flow_id = params
+ .get("flow_id")
+ .and_then(Value::as_str)
+ .filter(|s| !s.is_empty())
+ .map(str::to_string);
+ let origin = params
+ .get("origin")
+ .and_then(Value::as_str)
+ .and_then(|s| serde_json::from_value(Value::String(s.to_string())).ok())
+ .unwrap_or(crate::openhuman::flows::DraftOrigin::Canvas);
+ to_json(ops::flows_draft_create(
+ &config, flow_id, name, graph, origin,
+ )?)
+ })
+}
+
+fn handle_draft_get(params: Map<String, Value>) -> ControllerFuture {
+ Box::pin(async move {
+ let config = config_rpc::load_config_with_timeout().await?;
+ let id = read_required::<String>(&params, "id")?;
+ to_json(ops::flows_draft_get(&config, id.trim())?)
+ })
+}
+
+fn handle_draft_update(params: Map<String, Value>) -> ControllerFuture {
+ Box::pin(async move {
+ let config = config_rpc::load_config_with_timeout().await?;
+ let id = read_required::<String>(&params, "id")?;
+ let name = params
+ .get("name")
+ .filter(|v| !v.is_null())
+ .map(|v| serde_json::from_value(v.clone()))
+ .transpose()
+ .map_err(|e| format!("invalid 'name': {e}"))?;
+ let graph = params.get("graph").filter(|v| !v.is_null()).cloned();
+ // A present `flow_id` (even null) re-links the draft; absent leaves it.
+ let flow_id = parse_draft_update_flow_id(&params)?;
+ to_json(ops::flows_draft_update(
+ &config,
+ id.trim(),
+ name,
+ graph,
+ flow_id,
+ )?)
+ })
+}
+
+fn handle_draft_list(_params: Map<String, Value>) -> ControllerFuture {
+ Box::pin(async move {
+ let config = config_rpc::load_config_with_timeout().await?;
+ to_json(ops::flows_draft_list(&config)?)
+ })
+}
+
+fn handle_draft_delete(params: Map<String, Value>) -> ControllerFuture {
+ Box::pin(async move {
+ let config = config_rpc::load_config_with_timeout().await?;
+ let id = read_required::<String>(&params, "id")?;
+ to_json(ops::flows_draft_delete(&config, id.trim())?)
+ })
+}
+
+fn handle_draft_promote(params: Map<String, Value>) -> ControllerFuture {
+ Box::pin(async move {
+ let config = config_rpc::load_config_with_timeout().await?;
+ let id = read_required::<String>(&params, "id")?;
+ let require_approval = params.get("require_approval").and_then(Value::as_bool);
+ to_json(ops::flows_draft_promote(&config, id.trim(), require_approval).await?)
+ })
+}
+
+fn read_required<T: DeserializeOwned>(params: &Map<String, Value>, key: &str) -> Result<T, String> {
+ let value = params
+ .get(key)
+ .cloned()
+ .ok_or_else(|| format!("missing required param '{key}'"))?;
+ serde_json::from_value(value).map_err(|e| format!("invalid '{key}': {e}"))
+}
+
+fn to_json<T: serde::Serialize>(outcome: RpcOutcome<T>) -> Result<Value, String> {
+ outcome.into_cli_compatible_json()
+}
+
+/// Parses `draft_update`'s `flow_id` param (R-m7). The outer `Option`
+/// mirrors `ops::flows_draft_update`'s "present vs absent" contract — absent
+/// leaves the draft's existing link untouched; the inner `Option` is the new
+/// link (`None` unlinks).
+///
+/// A present-but-non-string `flow_id` (a number, or an object from a buggy
+/// client) is REJECTED rather than silently coerced into `Some(None)` via
+/// `Value::as_str()` returning `None` on a type mismatch — that shape used
+/// to be indistinguishable from an explicit `flow_id: null` unlink, and
+/// `update_draft` treats `Some(None)` as exactly that: unlinking the draft
+/// from its flow. A later `draft_promote` then creates a brand-new flow
+/// instead of updating the one the caller actually meant.
+fn parse_draft_update_flow_id(
+ params: &Map<String, Value>,
+) -> Result<Option<Option<String>>, String> {
+ match params.get("flow_id") {
+ None => Ok(None),
+ Some(Value::Null) => Ok(Some(None)),
+ Some(Value::String(s)) => {
+ let s = s.trim();
+ Ok(Some(if s.is_empty() {
+ None
+ } else {
+ Some(s.to_string())
+ }))
+ }
+ Some(other) => Err(format!(
+ "invalid 'flow_id': expected a string or null, got {other}"
+ )),
+ }
+}
+
+#[cfg(test)]
+#[path = "schemas_tests.rs"]
+mod tests;
diff --git a/src/openhuman/integrations/test_support.rs b/src/openhuman/integrations/test_support.rs
index 4e78fd870f..eabee0258b 100644
--- a/src/openhuman/integrations/test_support.rs
+++ b/src/openhuman/integrations/test_support.rs
@@ -53,745 +53,4 @@ fn as_string_array(value: &Value, key: &str) -> Vec<String> {
.unwrap_or_default()
}
-pub async fn spawn_fake_integration_backend() -> FakeIntegrationBackend {
- let state = FakeIntegrationState {
- requests: Arc::new(Mutex::new(Vec::new())),
- };
-
- let app = Router::new()
- .route(
- "/agent-integrations/apify/run",
- post({
- let state = state.clone();
- move |Json(body): Json<Value>| async move {
- record(
- &state,
- "POST",
- "/agent-integrations/apify/run".to_string(),
- body.clone(),
- );
- let actor_id = body
- .get("actorId")
- .and_then(Value::as_str)
- .unwrap_or("unknown-actor");
- let run_id = format!("run-{}", actor_id.replace('/', "-"));
- let input = body.get("input").cloned().unwrap_or(Value::Null);
- Json(json!({
- "success": true,
- "data": {
- "runId": run_id,
- "actorId": actor_id,
- "status": if body.get("sync").and_then(Value::as_bool).unwrap_or(true) { "SUCCEEDED" } else { "RUNNING" },
- "datasetId": format!("dataset-{}", actor_id.replace('/', "-")),
- "items": [
- {
- "actorId": actor_id,
- "inputEcho": input
- }
- ],
- "costUsd": 0.31
- }
- }))
- }
- }),
- )
- .route(
- "/agent-integrations/apify/runs/{run_id}",
- get({
- let state = state.clone();
- move |Path(run_id): Path<String>| async move {
- record(
- &state,
- "GET",
- format!("/agent-integrations/apify/runs/{run_id}"),
- Value::Null,
- );
- Json(json!({
- "success": true,
- "data": {
- "runId": run_id,
- "actorId": "apify/linkedin-profile-scraper",
- "status": "SUCCEEDED",
- "datasetId": format!("dataset-{run_id}"),
- "costUsd": 0.02
- }
- }))
- }
- }),
- )
- .route(
- "/agent-integrations/apify/runs/{run_id}/results",
- get({
- let state = state.clone();
- move |Path(run_id): Path<String>,
- Query(params): Query<HashMap<String, String>>| async move {
- let limit = params
- .get("limit")
- .and_then(|v| v.parse::<usize>().ok())
- .unwrap_or(3);
- let offset = params
- .get("offset")
- .and_then(|v| v.parse::<usize>().ok())
- .unwrap_or(0);
- record(
- &state,
- "GET",
- format!(
- "/agent-integrations/apify/runs/{run_id}/results?limit={limit}&offset={offset}"
- ),
- Value::Null,
- );
- let items: Vec<Value> = (0..limit)
- .map(|idx| {
- let n = offset + idx;
- json!({
- "runId": run_id,
- "index": n,
- "url": format!("https://example.com/{run_id}/{n}")
- })
- })
- .collect();
- Json(json!({
- "success": true,
- "data": {
- "items": items,
- "total": offset + limit + 5
- }
- }))
- }
- }),
- )
- .route(
- "/agent-integrations/google-places/search",
- post({
- let state = state.clone();
- move |Json(body): Json<Value>| async move {
- record(
- &state,
- "POST",
- "/agent-integrations/google-places/search".to_string(),
- body.clone(),
- );
- let query = body.get("query").and_then(Value::as_str).unwrap_or("unknown");
- let max_results =
- body.get("maxResults").and_then(Value::as_u64).unwrap_or(10).min(3);
- let results: Vec<Value> = (1..=max_results)
- .map(|idx| {
- json!({
- "placeId": format!("place-{idx}-{query}"),
- "name": format!("{query} Result {idx}"),
- "formattedAddress": format!("{idx} {query} Street"),
- "rating": 4.0 + (idx as f64 / 10.0),
- "userRatingCount": idx * 111,
- "googleMapsUri": format!("https://maps.google.com/?q={query}+{idx}")
- })
- })
- .collect();
- Json(json!({
- "success": true,
- "data": {
- "results": results,
- "costUsd": 0.01
- }
- }))
- }
- }),
- )
- .route(
- "/agent-integrations/google-places/details",
- post({
- let state = state.clone();
- move |Json(body): Json<Value>| async move {
- record(
- &state,
- "POST",
- "/agent-integrations/google-places/details".to_string(),
- body.clone(),
- );
- let place_id = body.get("placeId").and_then(Value::as_str).unwrap_or("place");
- Json(json!({
- "success": true,
- "data": {
- "place": {
- "placeId": place_id,
- "name": format!("Details for {place_id}"),
- "formattedAddress": format!("1 {place_id} Plaza"),
- "rating": 4.8,
- "userRatingCount": 321,
- "googleMapsUri": format!("https://maps.google.com/?cid={place_id}"),
- "websiteUri": format!("https://{place_id}.example.com"),
- "nationalPhoneNumber": "+1 555-0100",
- "businessStatus": "OPERATIONAL",
- "regularOpeningHours": {
- "openNow": true,
- "weekdayDescriptions": ["Monday: 9:00 AM - 5:00 PM"]
- }
- },
- "costUsd": 0.01
- }
- }))
- }
- }),
- )
- .route(
- "/agent-integrations/parallel/search",
- post({
- let state = state.clone();
- move |Json(body): Json<Value>| async move {
- record(
- &state,
- "POST",
- "/agent-integrations/parallel/search".to_string(),
- body.clone(),
- );
- let objective = body
- .get("objective")
- .and_then(Value::as_str)
- .unwrap_or("unknown objective");
- let queries = as_string_array(&body, "searchQueries");
- let results: Vec<Value> = queries
- .iter()
- .enumerate()
- .map(|(idx, query)| {
- json!({
- "url": format!("https://search.example.com/{idx}"),
- "title": format!("Result for {query}"),
- "publish_date": "2026-05-16",
- "excerpts": [format!("Objective: {objective}; query: {query}")]
- })
- })
- .collect();
- Json(json!({
- "success": true,
- "data": {
- "searchId": format!("search-{}", queries.len()),
- "results": results,
- "costUsd": 0.02
- }
- }))
- }
- }),
- )
- .route(
- "/agent-integrations/parallel/extract",
- post({
- let state = state.clone();
- move |Json(body): Json<Value>| async move {
- record(
- &state,
- "POST",
- "/agent-integrations/parallel/extract".to_string(),
- body.clone(),
- );
- let urls = as_string_array(&body, "urls");
- let objective = body.get("objective").and_then(Value::as_str).unwrap_or("");
- let include_full = body
- .get("fullContent")
- .and_then(Value::as_bool)
- .unwrap_or(false);
- let results: Vec<Value> = urls
- .iter()
- .map(|url| {
- json!({
- "url": url,
- "title": format!("Extracted {url}"),
- "excerpts": [format!("Focused on {objective}")],
- "full_content": if include_full {
- Value::String(format!("Full content for {url}"))
- } else {
- Value::Null
- }
- })
- })
- .collect();
- Json(json!({
- "success": true,
- "data": {
- "extractId": "extract-1",
- "results": results,
- "errors": [],
- "costUsd": 0.03
- }
- }))
- }
- }),
- )
- .route(
- "/agent-integrations/parallel/chat",
- post({
- let state = state.clone();
- move |Json(body): Json<Value>| async move {
- record(
- &state,
- "POST",
- "/agent-integrations/parallel/chat".to_string(),
- body.clone(),
- );
- let model = body.get("model").and_then(Value::as_str).unwrap_or("base");
- let last_message = body
- .get("messages")
- .and_then(Value::as_array)
- .and_then(|messages| messages.last())
- .and_then(|message| message.get("content"))
- .and_then(Value::as_str)
- .unwrap_or("");
- Json(json!({
- "success": true,
- "data": {
- "choices": [
- {
- "message": {
- "role": "assistant",
- "content": format!("Model {model} answered: {last_message}")
- },
- "finish_reason": "stop"
- }
- ],
- "basis": {
- "sources": ["https://search.example.com/0"]
- },
- "costUsd": 0.04
- }
- }))
- }
- }),
- )
- .route(
- "/agent-integrations/parallel/research",
- post({
- let state = state.clone();
- move |Json(body): Json<Value>| async move {
- record(
- &state,
- "POST",
- "/agent-integrations/parallel/research".to_string(),
- body.clone(),
- );
- let processor = body
- .get("processor")
- .and_then(Value::as_str)
- .unwrap_or("base");
- let input = body.get("input").cloned().unwrap_or(Value::Null);
- Json(json!({
- "success": true,
- "data": {
- "runId": format!("research-{processor}"),
- "status": "completed",
- "result": {
- "processor": processor,
- "inputEcho": input
- },
- "costUsd": 0.05
- }
- }))
- }
- }),
- )
- .route(
- "/agent-integrations/parallel/enrich",
- post({
- let state = state.clone();
- move |Json(body): Json<Value>| async move {
- record(
- &state,
- "POST",
- "/agent-integrations/parallel/enrich".to_string(),
- body.clone(),
- );
- let input = body.get("input").cloned().unwrap_or(Value::Null);
- Json(json!({
- "success": true,
- "data": {
- "runId": "enrich-1",
- "status": "completed",
- "output": {
- "inputEcho": input,
- "summary": "Enriched entity"
- },
- "costUsd": 0.06
- }
- }))
- }
- }),
- )
- .route(
- "/agent-integrations/parallel/dataset",
- post({
- let state = state.clone();
- move |Json(body): Json<Value>| async move {
- record(
- &state,
- "POST",
- "/agent-integrations/parallel/dataset".to_string(),
- body.clone(),
- );
- let entity_type = body
- .get("entityType")
- .and_then(Value::as_str)
- .unwrap_or("entity");
- let match_limit = body
- .get("matchLimit")
- .and_then(Value::as_u64)
- .unwrap_or(10);
- Json(json!({
- "success": true,
- "data": {
- "findallId": format!("dataset-{entity_type}"),
- "status": {
- "state": "queued",
- "entityType": entity_type
- },
- "matchLimit": match_limit,
- "costUsd": 0.07
- }
- }))
- }
- }),
- )
- .route(
- "/agent-integrations/financial-apis/quote",
- post({
- let state = state.clone();
- move |Json(body): Json<Value>| async move {
- record(
- &state,
- "POST",
- "/agent-integrations/financial-apis/quote".to_string(),
- body.clone(),
- );
- let symbol = body.get("symbol").and_then(Value::as_str).unwrap_or("AAPL");
- let base = 100.0 + symbol.len() as f64;
- Json(json!({
- "success": true,
- "data": {
- "quote": {
- "symbol": symbol,
- "price": base + 1.25,
- "open": base,
- "high": base + 2.0,
- "low": base - 1.0,
- "volume": 123456.0,
- "previousClose": base - 0.75,
- "change": 2.0,
- "changePercent": "1.95%",
- "latestTradingDay": "2026-05-16"
- },
- "costUsd": 0.001
- }
- }))
- }
- }),
- )
- .route(
- "/agent-integrations/financial-apis/exchange-rate",
- post({
- let state = state.clone();
- move |Json(body): Json<Value>| async move {
- record(
- &state,
- "POST",
- "/agent-integrations/financial-apis/exchange-rate".to_string(),
- body.clone(),
- );
- let from = body
- .get("fromCurrency")
- .and_then(Value::as_str)
- .unwrap_or("BTC");
- let to = body
- .get("toCurrency")
- .and_then(Value::as_str)
- .unwrap_or("USD");
- Json(json!({
- "success": true,
- "data": {
- "rate": {
- "fromCurrency": from,
- "toCurrency": to,
- "rate": 42.5,
- "bid": 42.4,
- "ask": 42.6,
- "lastRefreshed": "2026-05-16 12:00:00",
- "timeZone": "UTC"
- },
- "costUsd": 0.001
- }
- }))
- }
- }),
- )
- .route(
- "/agent-integrations/financial-apis/options",
- post({
- let state = state.clone();
- move |Json(body): Json<Value>| async move {
- record(
- &state,
- "POST",
- "/agent-integrations/financial-apis/options".to_string(),
- body.clone(),
- );
- let symbol = body.get("symbol").and_then(Value::as_str).unwrap_or("AAPL");
- let require_greeks = body
- .get("requireGreeks")
- .and_then(Value::as_bool)
- .unwrap_or(false);
- Json(json!({
- "success": true,
- "data": {
- "symbol": symbol,
- "contracts": [
- {
- "type": "call",
- "expiration": "2026-06-19",
- "strike": "250",
- "last": "5.10",
- "bid": "5.00",
- "ask": "5.20",
- "delta": if require_greeks { json!("0.42") } else { Value::Null }
- }
- ],
- "costUsd": 0.002
- }
- }))
- }
- }),
- )
- .route(
- "/agent-integrations/financial-apis/crypto-series",
- post({
- let state = state.clone();
- move |Json(body): Json<Value>| async move {
- record(
- &state,
- "POST",
- "/agent-integrations/financial-apis/crypto-series".to_string(),
- body.clone(),
- );
- let symbol = body.get("symbol").and_then(Value::as_str).unwrap_or("BTC");
- let market = body.get("market").and_then(Value::as_str).unwrap_or("USD");
- Json(json!({
- "success": true,
- "data": {
- "series": {
- "symbol": symbol,
- "market": market,
- "series": [
- {
- "date": "2026-05-16",
- "open": 100.0,
- "high": 110.0,
- "low": 95.0,
- "close": 105.0,
- "volume": 1234.0
- },
- {
- "date": "2026-05-15",
- "open": 90.0,
- "high": 101.0,
- "low": 88.0,
- "close": 100.0,
- "volume": 1111.0
- }
- ]
- },
- "costUsd": 0.003
- }
- }))
- }
- }),
- )
- .route(
- "/agent-integrations/financial-apis/commodity",
- post({
- let state = state.clone();
- move |Json(body): Json<Value>| async move {
- record(
- &state,
- "POST",
- "/agent-integrations/financial-apis/commodity".to_string(),
- body.clone(),
- );
- let commodity = body
- .get("commodity")
- .and_then(Value::as_str)
- .unwrap_or("WTI");
- let interval = body
- .get("interval")
- .and_then(Value::as_str)
- .unwrap_or("daily");
- Json(json!({
- "success": true,
- "data": {
- "series": {
- "commodity": commodity,
- "interval": interval,
- "unit": "USD",
- "series": [
- { "date": "2026-05-16", "value": 80.1 },
- { "date": "2026-05-15", "value": 79.8 }
- ]
- },
- "costUsd": 0.004
- }
- }))
- }
- }),
- )
- .route(
- "/agent-integrations/twilio/call",
- post({
- let state = state.clone();
- move |Json(body): Json<Value>| async move {
- record(
- &state,
- "POST",
- "/agent-integrations/twilio/call".to_string(),
- body.clone(),
- );
- let to = body.get("to").and_then(Value::as_str).unwrap_or("+10000000000");
- let suffix: String = to.chars().filter(|c| c.is_ascii_digit()).rev().take(4).collect();
- let suffix: String = suffix.chars().rev().collect();
- Json(json!({
- "success": true,
- "data": {
- "callSid": format!("CA{suffix}"),
- "status": "queued",
- "costUsd": 0.03
- }
- }))
- }
- }),
- )
- .route(
- "/agent-integrations/tinyfish/search",
- post({
- let state = state.clone();
- move |Json(body): Json<Value>| async move {
- record(
- &state,
- "POST",
- "/agent-integrations/tinyfish/search".to_string(),
- body.clone(),
- );
- let query = body
- .get("query")
- .and_then(Value::as_str)
- .unwrap_or("unknown");
- Json(json!({
- "success": true,
- "data": {
- "query": query,
- "results": [
- {
- "position": 1,
- "site_name": "example.com",
- "title": format!("TinyFish result for {query}"),
- "snippet": "Rendered search result from fake backend",
- "url": "https://example.com/tinyfish"
- }
- ],
- "total_results": 1,
- "costUsd": 0.0
- }
- }))
- }
- }),
- )
- .route(
- "/agent-integrations/tinyfish/fetch",
- post({
- let state = state.clone();
- move |Json(body): Json<Value>| async move {
- record(
- &state,
- "POST",
- "/agent-integrations/tinyfish/fetch".to_string(),
- body.clone(),
- );
- let urls = as_string_array(&body, "urls");
- let format = body
- .get("format")
- .and_then(Value::as_str)
- .unwrap_or("markdown");
- let results: Vec<Value> = urls
- .iter()
- .map(|url| {
- json!({
- "url": url,
- "final_url": url,
- "title": format!("Fetched {url}"),
- "description": "Fake TinyFish rendered page",
- "language": "en",
- "format": format,
- "latency_ms": 42,
- "text": format!("# Fetched\n\nTinyFish content for {url}"),
- "links": ["https://example.com/next"],
- "image_links": ["https://example.com/image.png"]
- })
- })
- .collect();
- Json(json!({
- "success": true,
- "data": {
- "results": results,
- "errors": [],
- "costUsd": 0.0
- }
- }))
- }
- }),
- )
- .route(
- "/agent-integrations/tinyfish/agent/run",
- post({
- let state = state.clone();
- move |Json(body): Json<Value>| async move {
- record(
- &state,
- "POST",
- "/agent-integrations/tinyfish/agent/run".to_string(),
- body.clone(),
- );
- let url = body
- .get("url")
- .and_then(Value::as_str)
- .unwrap_or("https://example.com");
- let goal = body
- .get("goal")
- .and_then(Value::as_str)
- .unwrap_or("unknown goal");
- Json(json!({
- "success": true,
- "data": {
- "run_id": "run_tinyfish_fake",
- "status": "COMPLETED",
- "num_of_steps": 3,
- "result": {
- "url": url,
- "goal": goal,
- "ok": true
- },
- "costUsd": 0.12
- }
- }))
- }
- }),
- );
-
- let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
- .await
- .expect("bind fake integration backend");
- let addr = listener.local_addr().expect("fake backend local addr");
- tokio::spawn(async move {
- let _ = axum::serve(listener, app).await;
- });
-
- FakeIntegrationBackend {
- base_url: format!("http://127.0.0.1:{}", addr.port()),
- state,
- }
-}
-
-#[cfg(test)]
-#[path = "test_support_tests.rs"]
-mod tests;
+include!("test_support_backend.rs");
diff --git a/src/openhuman/integrations/test_support_backend.rs b/src/openhuman/integrations/test_support_backend.rs
new file mode 100644
index 0000000000..7c3bc9068b
--- /dev/null
+++ b/src/openhuman/integrations/test_support_backend.rs
@@ -0,0 +1,742 @@
+pub async fn spawn_fake_integration_backend() -> FakeIntegrationBackend {
+ let state = FakeIntegrationState {
+ requests: Arc::new(Mutex::new(Vec::new())),
+ };
+
+ let app = Router::new()
+ .route(
+ "/agent-integrations/apify/run",
+ post({
+ let state = state.clone();
+ move |Json(body): Json<Value>| async move {
+ record(
+ &state,
+ "POST",
+ "/agent-integrations/apify/run".to_string(),
+ body.clone(),
+ );
+ let actor_id = body
+ .get("actorId")
+ .and_then(Value::as_str)
+ .unwrap_or("unknown-actor");
+ let run_id = format!("run-{}", actor_id.replace('/', "-"));
+ let input = body.get("input").cloned().unwrap_or(Value::Null);
+ Json(json!({
+ "success": true,
+ "data": {
+ "runId": run_id,
+ "actorId": actor_id,
+ "status": if body.get("sync").and_then(Value::as_bool).unwrap_or(true) { "SUCCEEDED" } else { "RUNNING" },
+ "datasetId": format!("dataset-{}", actor_id.replace('/', "-")),
+ "items": [
+ {
+ "actorId": actor_id,
+ "inputEcho": input
+ }
+ ],
+ "costUsd": 0.31
+ }
+ }))
+ }
+ }),
+ )
+ .route(
+ "/agent-integrations/apify/runs/{run_id}",
+ get({
+ let state = state.clone();
+ move |Path(run_id): Path<String>| async move {
+ record(
+ &state,
+ "GET",
+ format!("/agent-integrations/apify/runs/{run_id}"),
+ Value::Null,
+ );
+ Json(json!({
+ "success": true,
+ "data": {
+ "runId": run_id,
+ "actorId": "apify/linkedin-profile-scraper",
+ "status": "SUCCEEDED",
+ "datasetId": format!("dataset-{run_id}"),
+ "costUsd": 0.02
+ }
+ }))
+ }
+ }),
+ )
+ .route(
+ "/agent-integrations/apify/runs/{run_id}/results",
+ get({
+ let state = state.clone();
+ move |Path(run_id): Path<String>,
+ Query(params): Query<HashMap<String, String>>| async move {
+ let limit = params
+ .get("limit")
+ .and_then(|v| v.parse::<usize>().ok())
+ .unwrap_or(3);
+ let offset = params
+ .get("offset")
+ .and_then(|v| v.parse::<usize>().ok())
+ .unwrap_or(0);
+ record(
+ &state,
+ "GET",
+ format!(
+ "/agent-integrations/apify/runs/{run_id}/results?limit={limit}&offset={offset}"
+ ),
+ Value::Null,
+ );
+ let items: Vec<Value> = (0..limit)
+ .map(|idx| {
+ let n = offset + idx;
+ json!({
+ "runId": run_id,
+ "index": n,
+ "url": format!("https://example.com/{run_id}/{n}")
+ })
+ })
+ .collect();
+ Json(json!({
+ "success": true,
+ "data": {
+ "items": items,
+ "total": offset + limit + 5
+ }
+ }))
+ }
+ }),
+ )
+ .route(
+ "/agent-integrations/google-places/search",
+ post({
+ let state = state.clone();
+ move |Json(body): Json<Value>| async move {
+ record(
+ &state,
+ "POST",
+ "/agent-integrations/google-places/search".to_string(),
+ body.clone(),
+ );
+ let query = body.get("query").and_then(Value::as_str).unwrap_or("unknown");
+ let max_results =
+ body.get("maxResults").and_then(Value::as_u64).unwrap_or(10).min(3);
+ let results: Vec<Value> = (1..=max_results)
+ .map(|idx| {
+ json!({
+ "placeId": format!("place-{idx}-{query}"),
+ "name": format!("{query} Result {idx}"),
+ "formattedAddress": format!("{idx} {query} Street"),
+ "rating": 4.0 + (idx as f64 / 10.0),
+ "userRatingCount": idx * 111,
+ "googleMapsUri": format!("https://maps.google.com/?q={query}+{idx}")
+ })
+ })
+ .collect();
+ Json(json!({
+ "success": true,
+ "data": {
+ "results": results,
+ "costUsd": 0.01
+ }
+ }))
+ }
+ }),
+ )
+ .route(
+ "/agent-integrations/google-places/details",
+ post({
+ let state = state.clone();
+ move |Json(body): Json<Value>| async move {
+ record(
+ &state,
+ "POST",
+ "/agent-integrations/google-places/details".to_string(),
+ body.clone(),
+ );
+ let place_id = body.get("placeId").and_then(Value::as_str).unwrap_or("place");
+ Json(json!({
+ "success": true,
+ "data": {
+ "place": {
+ "placeId": place_id,
+ "name": format!("Details for {place_id}"),
+ "formattedAddress": format!("1 {place_id} Plaza"),
+ "rating": 4.8,
+ "userRatingCount": 321,
+ "googleMapsUri": format!("https://maps.google.com/?cid={place_id}"),
+ "websiteUri": format!("https://{place_id}.example.com"),
+ "nationalPhoneNumber": "+1 555-0100",
+ "businessStatus": "OPERATIONAL",
+ "regularOpeningHours": {
+ "openNow": true,
+ "weekdayDescriptions": ["Monday: 9:00 AM - 5:00 PM"]
+ }
+ },
+ "costUsd": 0.01
+ }
+ }))
+ }
+ }),
+ )
+ .route(
+ "/agent-integrations/parallel/search",
+ post({
+ let state = state.clone();
+ move |Json(body): Json<Value>| async move {
+ record(
+ &state,
+ "POST",
+ "/agent-integrations/parallel/search".to_string(),
+ body.clone(),
+ );
+ let objective = body
+ .get("objective")
+ .and_then(Value::as_str)
+ .unwrap_or("unknown objective");
+ let queries = as_string_array(&body, "searchQueries");
+ let results: Vec<Value> = queries
+ .iter()
+ .enumerate()
+ .map(|(idx, query)| {
+ json!({
+ "url": format!("https://search.example.com/{idx}"),
+ "title": format!("Result for {query}"),
+ "publish_date": "2026-05-16",
+ "excerpts": [format!("Objective: {objective}; query: {query}")]
+ })
+ })
+ .collect();
+ Json(json!({
+ "success": true,
+ "data": {
+ "searchId": format!("search-{}", queries.len()),
+ "results": results,
+ "costUsd": 0.02
+ }
+ }))
+ }
+ }),
+ )
+ .route(
+ "/agent-integrations/parallel/extract",
+ post({
+ let state = state.clone();
+ move |Json(body): Json<Value>| async move {
+ record(
+ &state,
+ "POST",
+ "/agent-integrations/parallel/extract".to_string(),
+ body.clone(),
+ );
+ let urls = as_string_array(&body, "urls");
+ let objective = body.get("objective").and_then(Value::as_str).unwrap_or("");
+ let include_full = body
+ .get("fullContent")
+ .and_then(Value::as_bool)
+ .unwrap_or(false);
+ let results: Vec<Value> = urls
+ .iter()
+ .map(|url| {
+ json!({
+ "url": url,
+ "title": format!("Extracted {url}"),
+ "excerpts": [format!("Focused on {objective}")],
+ "full_content": if include_full {
+ Value::String(format!("Full content for {url}"))
+ } else {
+ Value::Null
+ }
+ })
+ })
+ .collect();
+ Json(json!({
+ "success": true,
+ "data": {
+ "extractId": "extract-1",
+ "results": results,
+ "errors": [],
+ "costUsd": 0.03
+ }
+ }))
+ }
+ }),
+ )
+ .route(
+ "/agent-integrations/parallel/chat",
+ post({
+ let state = state.clone();
+ move |Json(body): Json<Value>| async move {
+ record(
+ &state,
+ "POST",
+ "/agent-integrations/parallel/chat".to_string(),
+ body.clone(),
+ );
+ let model = body.get("model").and_then(Value::as_str).unwrap_or("base");
+ let last_message = body
+ .get("messages")
+ .and_then(Value::as_array)
+ .and_then(|messages| messages.last())
+ .and_then(|message| message.get("content"))
+ .and_then(Value::as_str)
+ .unwrap_or("");
+ Json(json!({
+ "success": true,
+ "data": {
+ "choices": [
+ {
+ "message": {
+ "role": "assistant",
+ "content": format!("Model {model} answered: {last_message}")
+ },
+ "finish_reason": "stop"
+ }
+ ],
+ "basis": {
+ "sources": ["https://search.example.com/0"]
+ },
+ "costUsd": 0.04
+ }
+ }))
+ }
+ }),
+ )
+ .route(
+ "/agent-integrations/parallel/research",
+ post({
+ let state = state.clone();
+ move |Json(body): Json<Value>| async move {
+ record(
+ &state,
+ "POST",
+ "/agent-integrations/parallel/research".to_string(),
+ body.clone(),
+ );
+ let processor = body
+ .get("processor")
+ .and_then(Value::as_str)
+ .unwrap_or("base");
+ let input = body.get("input").cloned().unwrap_or(Value::Null);
+ Json(json!({
+ "success": true,
+ "data": {
+ "runId": format!("research-{processor}"),
+ "status": "completed",
+ "result": {
+ "processor": processor,
+ "inputEcho": input
+ },
+ "costUsd": 0.05
+ }
+ }))
+ }
+ }),
+ )
+ .route(
+ "/agent-integrations/parallel/enrich",
+ post({
+ let state = state.clone();
+ move |Json(body): Json<Value>| async move {
+ record(
+ &state,
+ "POST",
+ "/agent-integrations/parallel/enrich".to_string(),
+ body.clone(),
+ );
+ let input = body.get("input").cloned().unwrap_or(Value::Null);
+ Json(json!({
+ "success": true,
+ "data": {
+ "runId": "enrich-1",
+ "status": "completed",
+ "output": {
+ "inputEcho": input,
+ "summary": "Enriched entity"
+ },
+ "costUsd": 0.06
+ }
+ }))
+ }
+ }),
+ )
+ .route(
+ "/agent-integrations/parallel/dataset",
+ post({
+ let state = state.clone();
+ move |Json(body): Json<Value>| async move {
+ record(
+ &state,
+ "POST",
+ "/agent-integrations/parallel/dataset".to_string(),
+ body.clone(),
+ );
+ let entity_type = body
+ .get("entityType")
+ .and_then(Value::as_str)
+ .unwrap_or("entity");
+ let match_limit = body
+ .get("matchLimit")
+ .and_then(Value::as_u64)
+ .unwrap_or(10);
+ Json(json!({
+ "success": true,
+ "data": {
+ "findallId": format!("dataset-{entity_type}"),
+ "status": {
+ "state": "queued",
+ "entityType": entity_type
+ },
+ "matchLimit": match_limit,
+ "costUsd": 0.07
+ }
+ }))
+ }
+ }),
+ )
+ .route(
+ "/agent-integrations/financial-apis/quote",
+ post({
+ let state = state.clone();
+ move |Json(body): Json<Value>| async move {
+ record(
+ &state,
+ "POST",
+ "/agent-integrations/financial-apis/quote".to_string(),
+ body.clone(),
+ );
+ let symbol = body.get("symbol").and_then(Value::as_str).unwrap_or("AAPL");
+ let base = 100.0 + symbol.len() as f64;
+ Json(json!({
+ "success": true,
+ "data": {
+ "quote": {
+ "symbol": symbol,
+ "price": base + 1.25,
+ "open": base,
+ "high": base + 2.0,
+ "low": base - 1.0,
+ "volume": 123456.0,
+ "previousClose": base - 0.75,
+ "change": 2.0,
+ "changePercent": "1.95%",
+ "latestTradingDay": "2026-05-16"
+ },
+ "costUsd": 0.001
+ }
+ }))
+ }
+ }),
+ )
+ .route(
+ "/agent-integrations/financial-apis/exchange-rate",
+ post({
+ let state = state.clone();
+ move |Json(body): Json<Value>| async move {
+ record(
+ &state,
+ "POST",
+ "/agent-integrations/financial-apis/exchange-rate".to_string(),
+ body.clone(),
+ );
+ let from = body
+ .get("fromCurrency")
+ .and_then(Value::as_str)
+ .unwrap_or("BTC");
+ let to = body
+ .get("toCurrency")
+ .and_then(Value::as_str)
+ .unwrap_or("USD");
+ Json(json!({
+ "success": true,
+ "data": {
+ "rate": {
+ "fromCurrency": from,
+ "toCurrency": to,
+ "rate": 42.5,
+ "bid": 42.4,
+ "ask": 42.6,
+ "lastRefreshed": "2026-05-16 12:00:00",
+ "timeZone": "UTC"
+ },
+ "costUsd": 0.001
+ }
+ }))
+ }
+ }),
+ )
+ .route(
+ "/agent-integrations/financial-apis/options",
+ post({
+ let state = state.clone();
+ move |Json(body): Json<Value>| async move {
+ record(
+ &state,
+ "POST",
+ "/agent-integrations/financial-apis/options".to_string(),
+ body.clone(),
+ );
+ let symbol = body.get("symbol").and_then(Value::as_str).unwrap_or("AAPL");
+ let require_greeks = body
+ .get("requireGreeks")
+ .and_then(Value::as_bool)
+ .unwrap_or(false);
+ Json(json!({
+ "success": true,
+ "data": {
+ "symbol": symbol,
+ "contracts": [
+ {
+ "type": "call",
+ "expiration": "2026-06-19",
+ "strike": "250",
+ "last": "5.10",
+ "bid": "5.00",
+ "ask": "5.20",
+ "delta": if require_greeks { json!("0.42") } else { Value::Null }
+ }
+ ],
+ "costUsd": 0.002
+ }
+ }))
+ }
+ }),
+ )
+ .route(
+ "/agent-integrations/financial-apis/crypto-series",
+ post({
+ let state = state.clone();
+ move |Json(body): Json<Value>| async move {
+ record(
+ &state,
+ "POST",
+ "/agent-integrations/financial-apis/crypto-series".to_string(),
+ body.clone(),
+ );
+ let symbol = body.get("symbol").and_then(Value::as_str).unwrap_or("BTC");
+ let market = body.get("market").and_then(Value::as_str).unwrap_or("USD");
+ Json(json!({
+ "success": true,
+ "data": {
+ "series": {
+ "symbol": symbol,
+ "market": market,
+ "series": [
+ {
+ "date": "2026-05-16",
+ "open": 100.0,
+ "high": 110.0,
+ "low": 95.0,
+ "close": 105.0,
+ "volume": 1234.0
+ },
+ {
+ "date": "2026-05-15",
+ "open": 90.0,
+ "high": 101.0,
+ "low": 88.0,
+ "close": 100.0,
+ "volume": 1111.0
+ }
+ ]
+ },
+ "costUsd": 0.003
+ }
+ }))
+ }
+ }),
+ )
+ .route(
+ "/agent-integrations/financial-apis/commodity",
+ post({
+ let state = state.clone();
+ move |Json(body): Json<Value>| async move {
+ record(
+ &state,
+ "POST",
+ "/agent-integrations/financial-apis/commodity".to_string(),
+ body.clone(),
+ );
+ let commodity = body
+ .get("commodity")
+ .and_then(Value::as_str)
+ .unwrap_or("WTI");
+ let interval = body
+ .get("interval")
+ .and_then(Value::as_str)
+ .unwrap_or("daily");
+ Json(json!({
+ "success": true,
+ "data": {
+ "series": {
+ "commodity": commodity,
+ "interval": interval,
+ "unit": "USD",
+ "series": [
+ { "date": "2026-05-16", "value": 80.1 },
+ { "date": "2026-05-15", "value": 79.8 }
+ ]
+ },
+ "costUsd": 0.004
+ }
+ }))
+ }
+ }),
+ )
+ .route(
+ "/agent-integrations/twilio/call",
+ post({
+ let state = state.clone();
+ move |Json(body): Json<Value>| async move {
+ record(
+ &state,
+ "POST",
+ "/agent-integrations/twilio/call".to_string(),
+ body.clone(),
+ );
+ let to = body.get("to").and_then(Value::as_str).unwrap_or("+10000000000");
+ let suffix: String = to.chars().filter(|c| c.is_ascii_digit()).rev().take(4).collect();
+ let suffix: String = suffix.chars().rev().collect();
+ Json(json!({
+ "success": true,
+ "data": {
+ "callSid": format!("CA{suffix}"),
+ "status": "queued",
+ "costUsd": 0.03
+ }
+ }))
+ }
+ }),
+ )
+ .route(
+ "/agent-integrations/tinyfish/search",
+ post({
+ let state = state.clone();
+ move |Json(body): Json<Value>| async move {
+ record(
+ &state,
+ "POST",
+ "/agent-integrations/tinyfish/search".to_string(),
+ body.clone(),
+ );
+ let query = body
+ .get("query")
+ .and_then(Value::as_str)
+ .unwrap_or("unknown");
+ Json(json!({
+ "success": true,
+ "data": {
+ "query": query,
+ "results": [
+ {
+ "position": 1,
+ "site_name": "example.com",
+ "title": format!("TinyFish result for {query}"),
+ "snippet": "Rendered search result from fake backend",
+ "url": "https://example.com/tinyfish"
+ }
+ ],
+ "total_results": 1,
+ "costUsd": 0.0
+ }
+ }))
+ }
+ }),
+ )
+ .route(
+ "/agent-integrations/tinyfish/fetch",
+ post({
+ let state = state.clone();
+ move |Json(body): Json<Value>| async move {
+ record(
+ &state,
+ "POST",
+ "/agent-integrations/tinyfish/fetch".to_string(),
+ body.clone(),
+ );
+ let urls = as_string_array(&body, "urls");
+ let format = body
+ .get("format")
+ .and_then(Value::as_str)
+ .unwrap_or("markdown");
+ let results: Vec<Value> = urls
+ .iter()
+ .map(|url| {
+ json!({
+ "url": url,
+ "final_url": url,
+ "title": format!("Fetched {url}"),
+ "description": "Fake TinyFish rendered page",
+ "language": "en",
+ "format": format,
+ "latency_ms": 42,
+ "text": format!("# Fetched\n\nTinyFish content for {url}"),
+ "links": ["https://example.com/next"],
+ "image_links": ["https://example.com/image.png"]
+ })
+ })
+ .collect();
+ Json(json!({
+ "success": true,
+ "data": {
+ "results": results,
+ "errors": [],
+ "costUsd": 0.0
+ }
+ }))
+ }
+ }),
+ )
+ .route(
+ "/agent-integrations/tinyfish/agent/run",
+ post({
+ let state = state.clone();
+ move |Json(body): Json<Value>| async move {
+ record(
+ &state,
+ "POST",
+ "/agent-integrations/tinyfish/agent/run".to_string(),
+ body.clone(),
+ );
+ let url = body
+ .get("url")
+ .and_then(Value::as_str)
+ .unwrap_or("https://example.com");
+ let goal = body
+ .get("goal")
+ .and_then(Value::as_str)
+ .unwrap_or("unknown goal");
+ Json(json!({
+ "success": true,
+ "data": {
+ "run_id": "run_tinyfish_fake",
+ "status": "COMPLETED",
+ "num_of_steps": 3,
+ "result": {
+ "url": url,
+ "goal": goal,
+ "ok": true
+ },
+ "costUsd": 0.12
+ }
+ }))
+ }
+ }),
+ );
+
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
+ .await
+ .expect("bind fake integration backend");
+ let addr = listener.local_addr().expect("fake backend local addr");
+ tokio::spawn(async move {
+ let _ = axum::serve(listener, app).await;
+ });
+
+ FakeIntegrationBackend {
+ base_url: format!("http://127.0.0.1:{}", addr.port()),
+ state,
+ }
+}
+
+#[cfg(test)]
+#[path = "test_support_tests.rs"]
+mod tests;
diff --git a/src/openhuman/memory/schema/definitions.rs b/src/openhuman/memory/schema/definitions.rs
index aad1cf474d..1b0a21d822 100644
--- a/src/openhuman/memory/schema/definitions.rs
+++ b/src/openhuman/memory/schema/definitions.rs
@@ -9,970 +9,33 @@ use crate::core::{ControllerSchema, FieldSchema, TypeSchema};
pub(crate) const NAMESPACE: &str = "memory_tree";
/// Lookup the [`ControllerSchema`] for a single `memory_tree` function name.
+#[path = "schema_schema_part_01.rs"]
+mod schema_schema_part_01;
+#[path = "schema_schema_part_02.rs"]
+mod schema_schema_part_02;
+
pub fn schemas(function: &str) -> ControllerSchema {
- match function {
- "ingest" => ControllerSchema {
- namespace: NAMESPACE,
- function: "ingest",
- description: "Ingest a source into canonical chunks. \
- Dispatches on `source_kind`; `payload` shape depends on the kind \
- (chat → ChatBatch, email → EmailThread, document → DocumentInput).",
- inputs: vec![
- FieldSchema {
- name: "source_kind",
- ty: TypeSchema::Enum {
- variants: vec!["chat", "email", "document"],
- },
- comment: "Which source kind the payload represents.",
- required: true,
- },
- FieldSchema {
- name: "source_id",
- ty: TypeSchema::String,
- comment: "Stable logical source id (channel, thread, document id).",
- required: true,
- },
- FieldSchema {
- name: "owner",
- ty: TypeSchema::String,
- comment: "Optional account / user this content belongs to.",
- required: false,
- },
- FieldSchema {
- name: "tags",
- ty: TypeSchema::Array(Box::new(TypeSchema::String)),
- comment: "Optional tags or labels carried through.",
- required: false,
- },
- FieldSchema {
- name: "payload",
- ty: TypeSchema::Json,
- comment: "Adapter-specific payload. \
- chat: {platform, channel_label, messages[]}. \
- email: {provider, thread_subject, messages[]}. \
- document: {provider, title, body, modified_at, source_ref}.",
- required: true,
- },
- ],
- outputs: vec![
- FieldSchema {
- name: "source_id",
- ty: TypeSchema::String,
- comment: "Logical source id the ingest was scoped to.",
- required: true,
- },
- FieldSchema {
- name: "chunks_written",
- ty: TypeSchema::U64,
- comment: "Number of chunks persisted after admission.",
- required: true,
- },
- FieldSchema {
- name: "chunks_dropped",
- ty: TypeSchema::U64,
- comment: "Number of chunks rejected by the admission gate.",
- required: true,
- },
- FieldSchema {
- name: "chunk_ids",
- ty: TypeSchema::Array(Box::new(TypeSchema::String)),
- comment: "IDs of all chunks persisted after admission.",
- required: true,
- },
- ],
- },
- "list_chunks" => ControllerSchema {
- namespace: NAMESPACE,
- function: "list_chunks",
- description: "Paginated list of chunks with optional filters by source kind / source id / \
- entity ids / time window / keyword. Returns chunks plus total match count for \
- pagination.",
- inputs: vec![
- FieldSchema {
- name: "source_kinds",
- ty: TypeSchema::Option(Box::new(TypeSchema::Array(Box::new(
- TypeSchema::String,
- )))),
- comment: "Restrict to one or more source kinds (chat / email / document).",
- required: false,
- },
- FieldSchema {
- name: "source_ids",
- ty: TypeSchema::Option(Box::new(TypeSchema::Array(Box::new(
- TypeSchema::String,
- )))),
- comment: "Restrict to one or more logical source ids.",
- required: false,
- },
- FieldSchema {
- name: "entity_ids",
- ty: TypeSchema::Option(Box::new(TypeSchema::Array(Box::new(
- TypeSchema::String,
- )))),
- comment: "Restrict to chunks indexed against any of these canonical entity ids.",
- required: false,
- },
- FieldSchema {
- name: "since_ms",
- ty: TypeSchema::Option(Box::new(TypeSchema::I64)),
- comment: "Inclusive lower bound on chunk timestamp (ms since epoch).",
- required: false,
- },
- FieldSchema {
- name: "until_ms",
- ty: TypeSchema::Option(Box::new(TypeSchema::I64)),
- comment: "Inclusive upper bound on chunk timestamp (ms since epoch).",
- required: false,
- },
- FieldSchema {
- name: "query",
- ty: TypeSchema::Option(Box::new(TypeSchema::String)),
- comment: "Substring keyword filter over chunk preview content.",
- required: false,
- },
- FieldSchema {
- name: "limit",
- ty: TypeSchema::Option(Box::new(TypeSchema::U64)),
- comment: "Maximum rows per page (defaults to 50, capped at 1000).",
- required: false,
- },
- FieldSchema {
- name: "offset",
- ty: TypeSchema::Option(Box::new(TypeSchema::U64)),
- comment: "Pagination offset (defaults to 0).",
- required: false,
- },
- ],
- outputs: vec![
- FieldSchema {
- name: "chunks",
- ty: TypeSchema::Array(Box::new(TypeSchema::Ref("Chunk"))),
- comment: "Page of matching chunks ordered by timestamp DESC.",
- required: true,
- },
- FieldSchema {
- name: "total",
- ty: TypeSchema::U64,
- comment: "Total number of chunks matching the filter (pre-pagination).",
- required: true,
- },
- ],
- },
- "get_chunk" => ControllerSchema {
- namespace: NAMESPACE,
- function: "get_chunk",
- description: "Fetch a single chunk by its deterministic id.",
- inputs: vec![FieldSchema {
- name: "id",
- ty: TypeSchema::String,
- comment: "Chunk id (32 hex chars).",
- required: true,
- }],
- outputs: vec![FieldSchema {
- name: "chunk",
- ty: TypeSchema::Option(Box::new(TypeSchema::Ref("Chunk"))),
- comment: "The chunk if found, otherwise null.",
- required: false,
- }],
- },
- "list_sources" => ControllerSchema {
- namespace: NAMESPACE,
- function: "list_sources",
- description: "Distinct (source_kind, source_id) pairs with chunk counts and most-recent timestamps. \
- `display_name` is computed from the source_id (un-slug + strip user email when known).",
- inputs: vec![FieldSchema {
- name: "user_email_hint",
- ty: TypeSchema::Option(Box::new(TypeSchema::String)),
- comment: "When provided, source ids that contain this email get it stripped from \
- their display name so the UI shows the other party of an email thread.",
- required: false,
- }],
- outputs: vec![FieldSchema {
- name: "sources",
- ty: TypeSchema::Array(Box::new(TypeSchema::Ref("Source"))),
- comment: "All distinct ingest sources, newest activity first.",
- required: true,
- }],
- },
- "search" => ControllerSchema {
- namespace: NAMESPACE,
- function: "search",
- description: "Keyword LIKE-search over chunk bodies. Cheap, deterministic; useful as a \
- fallback when semantic recall is unavailable.",
- inputs: vec![
- FieldSchema {
- name: "query",
- ty: TypeSchema::String,
- comment: "Substring to match against chunk content.",
- required: true,
- },
- FieldSchema {
- name: "k",
- ty: TypeSchema::U64,
- comment: "Maximum chunks to return.",
- required: true,
- },
- ],
- outputs: vec![FieldSchema {
- name: "chunks",
- ty: TypeSchema::Array(Box::new(TypeSchema::Ref("Chunk"))),
- comment: "Matching chunks ordered by recency.",
- required: true,
- }],
- },
- "recall" => ControllerSchema {
- namespace: NAMESPACE,
- function: "recall",
- description: "Semantic recall — runs the Phase 4 cosine rerank against the query embedding \
- and returns leaf chunks (not summaries) for UI display.",
- inputs: vec![
- FieldSchema {
- name: "query",
- ty: TypeSchema::String,
- comment: "Free-text query — embedded once and reranked against summary embeddings.",
- required: true,
- },
- FieldSchema {
- name: "k",
- ty: TypeSchema::U64,
- comment: "Maximum chunks to return.",
- required: true,
- },
- ],
- outputs: vec![
- FieldSchema {
- name: "chunks",
- ty: TypeSchema::Array(Box::new(TypeSchema::Ref("Chunk"))),
- comment: "Recalled chunks, sorted in the same order as the rerank.",
- required: true,
- },
- FieldSchema {
- name: "scores",
- ty: TypeSchema::Array(Box::new(TypeSchema::Json)),
- comment: "Parallel array of similarity scores (one per chunk).",
- required: true,
- },
- ],
- },
- "entity_index_for" => ControllerSchema {
- namespace: NAMESPACE,
- function: "entity_index_for",
- description: "Return all canonical entities indexed against a chunk (or summary node) id.",
- inputs: vec![FieldSchema {
- name: "chunk_id",
- ty: TypeSchema::String,
- comment: "Chunk id (32 hex chars).",
- required: true,
- }],
- outputs: vec![FieldSchema {
- name: "entities",
- ty: TypeSchema::Array(Box::new(TypeSchema::Ref("EntityRef"))),
- comment: "Entities attached to the node, ordered by mention count DESC.",
- required: true,
- }],
- },
- "chunks_for_entity" => ControllerSchema {
- namespace: NAMESPACE,
- function: "chunks_for_entity",
- description: "Return chunk IDs that reference an entity_id (inverse of entity_index_for). \
- Used by the Memory tab's People/Topics lenses to filter the chunk list.",
- inputs: vec![FieldSchema {
- name: "entity_id",
- ty: TypeSchema::String,
- comment: "Canonical entity id (e.g. `person:Steven Enamakel`, \
- `email:[email protected]`).",
- required: true,
- }],
- outputs: vec![FieldSchema {
- name: "chunk_ids",
- ty: TypeSchema::Array(Box::new(TypeSchema::String)),
- comment: "Chunk ids that mention the entity, ordered by recency DESC.",
- required: true,
- }],
- },
- "top_entities" => ControllerSchema {
- namespace: NAMESPACE,
- function: "top_entities",
- description: "Most-frequent canonical entities across the workspace, optionally narrowed by kind.",
- inputs: vec![
- FieldSchema {
- name: "kind",
- ty: TypeSchema::Option(Box::new(TypeSchema::String)),
- comment: "Restrict to a single entity_kind (`person`, `email`, `topic`, …).",
- required: false,
- },
- FieldSchema {
- name: "limit",
- ty: TypeSchema::U64,
- comment: "Maximum rows to return.",
- required: true,
- },
- ],
- outputs: vec![FieldSchema {
- name: "entities",
- ty: TypeSchema::Array(Box::new(TypeSchema::Ref("EntityRef"))),
- comment: "Top entities, ordered by mention count DESC.",
- required: true,
- }],
- },
- "chunk_score" => ControllerSchema {
- namespace: NAMESPACE,
- function: "chunk_score",
- description: "Score breakdown stored in `mem_tree_score` for one chunk — used by the Memory \
- tab's 'why was this kept / dropped' panel.",
- inputs: vec![FieldSchema {
- name: "chunk_id",
- ty: TypeSchema::String,
- comment: "Chunk id (32 hex chars).",
- required: true,
- }],
- outputs: vec![FieldSchema {
- name: "breakdown",
- ty: TypeSchema::Option(Box::new(TypeSchema::Ref("ScoreBreakdown"))),
- comment: "Per-signal weight + value array, total, threshold, kept flag, llm_consulted flag.",
- required: false,
- }],
- },
- "delete_chunk" => ControllerSchema {
- namespace: NAMESPACE,
- function: "delete_chunk",
- description: "Purge one chunk plus its score row, entity-index rows, and on-disk .md file. \
- Idempotent — missing chunk returns deleted=false. Does NOT cascade through \
- sealed summaries; UIs warn the user.",
- inputs: vec![FieldSchema {
- name: "chunk_id",
- ty: TypeSchema::String,
- comment: "Chunk id to remove.",
- required: true,
- }],
- outputs: vec![
- FieldSchema {
- name: "deleted",
- ty: TypeSchema::Bool,
- comment: "True when the chunk row was found and removed.",
- required: true,
- },
- FieldSchema {
- name: "score_rows_removed",
- ty: TypeSchema::U64,
- comment: "Count of rows removed from `mem_tree_score`.",
- required: true,
- },
- FieldSchema {
- name: "entity_index_rows_removed",
- ty: TypeSchema::U64,
- comment: "Count of rows removed from `mem_tree_entity_index`.",
- required: true,
- },
- ],
- },
- "delete_source" => ControllerSchema {
- namespace: NAMESPACE,
- function: "delete_source",
- description: "Fully delete one document source by its EXACT source_id: every chunk \
- plus its score / entity-index / embedding / reembed-skip side rows and chunk \
- content files, the ingest dedup gates (bare source_id AND versioned \
- source_id@version), and (when the source becomes fully orphaned) its \
- source-scoped summary tree — summaries, summary embeddings + reembed-skip, \
- tree entity-index, buffers, the tree row, and summary content files. Unlike \
- delete_chunk this cascades, so stale summaries of the deleted source cannot \
- resurface in recall, and it also finishes legacy partial deletes (chunks already \
- gone, tree/gate left behind). Exact match only (never a prefix); shared \
- collection/path_scope trees that summarise multiple documents are left intact. \
- Idempotent — an unknown source_id returns deleted=false.",
- inputs: vec![FieldSchema {
- name: "source_id",
- ty: TypeSchema::String,
- comment: "Exact source id to remove (e.g. a Telegram note/event/meeting id).",
- required: true,
- }],
- outputs: vec![
- FieldSchema {
- name: "deleted",
- ty: TypeSchema::Bool,
- comment: "True when the call did real work: chunks were removed OR a stale \
- orphaned source tree was cleaned (legacy case, chunks_removed=0).",
- required: true,
- },
- FieldSchema {
- name: "chunks_removed",
- ty: TypeSchema::U64,
- comment: "Number of chunk rows removed for the source.",
- required: true,
- },
- ],
- },
- "wipe_all" => ControllerSchema {
- namespace: NAMESPACE,
- function: "wipe_all",
- description: "Destructive reset: truncate every mem_tree_* table, remove the \
- on-disk content folders (raw / wiki / email / chat / document / \
- legacy summaries) under the workspace memory_tree content root, \
- and clear every Composio sync-state KV row so the next sync \
- re-fetches all upstream items. Used by the Memory tab's 'Reset \
- memory' button.",
- inputs: vec![],
- outputs: vec![
- FieldSchema {
- name: "rows_deleted",
- ty: TypeSchema::U64,
- comment: "Total mem_tree_* rows removed across all tables.",
- required: true,
- },
- FieldSchema {
- name: "dirs_removed",
- ty: TypeSchema::Array(Box::new(TypeSchema::String)),
- comment: "Top-level directories under content_root that were deleted.",
- required: true,
- },
- FieldSchema {
- name: "sync_state_cleared",
- ty: TypeSchema::U64,
- comment: "Composio sync-state KV rows deleted (cursors + synced-id sets).",
- required: true,
- },
- ],
- },
- "reset_tree" => ControllerSchema {
- namespace: NAMESPACE,
- function: "reset_tree",
- description: "Wipe summary-tree state but keep chunks + raw archive + sync state, \
- then re-enqueue every chunk through the extraction pipeline so the \
- tree rebuilds from scratch. Useful after changing the summariser \
- backend (e.g. enabling a local LLM) without paying the upstream \
- re-sync cost.",
- inputs: vec![],
- outputs: vec![
- FieldSchema {
- name: "tree_rows_deleted",
- ty: TypeSchema::U64,
- comment: "Tree-state rows removed (summaries + trees + buffers + jobs).",
- required: true,
- },
- FieldSchema {
- name: "chunks_requeued",
- ty: TypeSchema::U64,
- comment: "Chunks reset to lifecycle_status = 'pending_extraction'.",
- required: true,
- },
- FieldSchema {
- name: "jobs_enqueued",
- ty: TypeSchema::U64,
- comment: "extract_chunk jobs enqueued (one per chunk).",
- required: true,
- },
- ],
- },
- "flush_source" => ControllerSchema {
- namespace: NAMESPACE,
- function: "flush_source",
- description: "Immediately seal one source tree's L0 buffer, bypassing the job \
- queue. Mutex per source scope so concurrent clicks are serialised. \
- Returns the number of seal cascades that fired.",
- inputs: vec![FieldSchema {
- name: "source_scope",
- ty: TypeSchema::String,
- comment: "Source tree scope (e.g. `github:org/repo`, `slack:#eng`).",
- required: true,
- }],
- outputs: vec![
- FieldSchema {
- name: "tree_scope",
- ty: TypeSchema::String,
- comment: "Echo of the source scope.",
- required: true,
- },
- FieldSchema {
- name: "seals_fired",
- ty: TypeSchema::U64,
- comment: "Number of seal cascades that fired.",
- required: true,
- },
- ],
- },
- "flush_now" => ControllerSchema {
- namespace: NAMESPACE,
- function: "flush_now",
- description: "Manually trigger the summary-tree build. Enqueues a flush_stale \
- job with max_age_secs=0 so every L0 buffer force-seals immediately; \
- the seal worker runs each through the configured (cloud or local) \
- summariser. Idempotent — same UTC-day dedupe key as the scheduled \
- flush so spamming the button is safe.",
- inputs: vec![],
- outputs: vec![
- FieldSchema {
- name: "enqueued",
- ty: TypeSchema::Bool,
- comment: "True when a fresh job row was inserted; false when an active \
- flush job already exists for today.",
- required: true,
- },
- FieldSchema {
- name: "stale_buffers",
- ty: TypeSchema::U64,
- comment: "Count of L0 buffers that currently qualify for force-seal.",
- required: true,
- },
- ],
- },
- "graph_export" => ControllerSchema {
- namespace: NAMESPACE,
- function: "graph_export",
- description: "Return either the summary tree (parent→child links between sealed \
- summary nodes) or the document↔contact graph (chunks linked to \
- person entities they mention). Includes the absolute path to the \
- on-disk content root so deep links can point Obsidian at the same \
- files.",
- inputs: vec![FieldSchema {
- name: "mode",
- ty: TypeSchema::Option(Box::new(TypeSchema::Enum {
- variants: vec!["tree", "contacts"],
- })),
- comment: "Which graph to return. Defaults to `tree`.",
- required: false,
- }],
- outputs: vec![
- FieldSchema {
- name: "nodes",
- ty: TypeSchema::Array(Box::new(TypeSchema::Ref("GraphNode"))),
- comment: "Summary, chunk, or contact nodes depending on mode.",
- required: true,
- },
- FieldSchema {
- name: "edges",
- ty: TypeSchema::Array(Box::new(TypeSchema::Ref("GraphEdge"))),
- comment: "Explicit edges. Empty in tree mode (parent_id encodes \
- edges); chunk→contact mention edges in contacts mode.",
- required: true,
- },
- FieldSchema {
- name: "content_root_abs",
- ty: TypeSchema::String,
- comment: "Absolute path to <workspace>/memory_tree/content/.",
- required: true,
- },
- ],
- },
- "obsidian_vault_status" => ControllerSchema {
- namespace: NAMESPACE,
- function: "obsidian_vault_status",
- description: "Best-effort check of whether the memory-tree content root is \
- already a registered Obsidian vault. `obsidian://open?path=` only \
- resolves vaults present in Obsidian's obsidian.json registry — it \
- cannot register a new one — so the Memory tab calls this before \
- firing the deep link and guides the user to 'Open folder as vault' \
- when it isn't registered. Never errors; a probe miss reports \
- registered=false.",
- inputs: vec![FieldSchema {
- name: "obsidian_config_dir",
- ty: TypeSchema::Option(Box::new(TypeSchema::String)),
- comment: "Optional override for Obsidian's config directory (where \
- obsidian.json lives), for non-standard installs \
- (Flatpak / Snap / portable). Omitted ⇒ probe the standard per-OS \
- location plus known sandbox paths.",
- required: false,
- }],
- outputs: vec![
- FieldSchema {
- name: "registered",
- ty: TypeSchema::Bool,
- comment: "True when the content root (or an ancestor) is a registered \
- Obsidian vault, so the deep link will resolve.",
- required: true,
- },
- FieldSchema {
- name: "config_found",
- ty: TypeSchema::Bool,
- comment: "True when an obsidian.json was found and parsed (Obsidian is \
- set up). Lets the UI offer add-as-vault vs. install.",
- required: true,
- },
- FieldSchema {
- name: "content_root_abs",
- ty: TypeSchema::String,
- comment: "Absolute path to <workspace>/memory_tree/content/ — the folder \
- to add to Obsidian and the deep-link target.",
- required: true,
- },
- ],
- },
- "vault_health_check" => ControllerSchema {
- namespace: NAMESPACE,
- function: "vault_health_check",
- description: "Consolidated workspace-vault health snapshot for onboarding and \
- settings. Checks whether <workspace>/memory_tree/content exists, is \
- readable, and is writable (via temp-file probe), whether Obsidian has \
- the vault registered, and whether the Memory Tree pipeline is healthy.",
- inputs: vec![FieldSchema {
- name: "obsidian_config_dir",
- ty: TypeSchema::Option(Box::new(TypeSchema::String)),
- comment: "Optional override for Obsidian's config directory (where \
- obsidian.json lives). Omitted ⇒ standard per-OS probe.",
- required: false,
- }],
- outputs: vec![
- FieldSchema {
- name: "content_root_abs",
- ty: TypeSchema::String,
- comment: "Absolute path to <workspace>/memory_tree/content/.",
- required: true,
- },
- FieldSchema {
- name: "exists",
- ty: TypeSchema::Bool,
- comment: "True when the workspace vault directory exists on disk.",
- required: true,
- },
- FieldSchema {
- name: "readable",
- ty: TypeSchema::Bool,
- comment: "True when the workspace vault directory can be read.",
- required: true,
- },
- FieldSchema {
- name: "writable",
- ty: TypeSchema::Bool,
- comment: "True when the vault accepts a create+delete temp-file probe.",
- required: true,
- },
- FieldSchema {
- name: "obsidian_registered",
- ty: TypeSchema::Bool,
- comment: "True when Obsidian has this folder (or an ancestor) registered \
- as a vault.",
- required: true,
- },
- FieldSchema {
- name: "pipeline_healthy",
- ty: TypeSchema::Bool,
- comment: "True when Memory Tree pipeline is not paused and not in error.",
- required: true,
- },
- FieldSchema {
- name: "last_sync_ms",
- ty: TypeSchema::I64,
- comment: "Epoch ms of the newest chunk timestamp; 0 when empty.",
- required: true,
- },
- ],
- },
- "pipeline_status" => ControllerSchema {
- namespace: NAMESPACE,
- function: "pipeline_status",
- description: "Aggregated Memory Tree health snapshot (#1856 Part 1). \
- Returns a coarse `status` string (running/paused/syncing/error/idle), \
- an optional human-readable reason, the most-recent chunk timestamp, \
- the total chunk count, the on-disk wiki size in bytes, and per-state \
- job counters from `mem_tree_jobs`. Polled by the Memory Tree status \
- panel; cheap enough to call every couple of seconds.",
- inputs: vec![],
- outputs: vec![
- FieldSchema {
- name: "status",
- ty: TypeSchema::Enum {
- variants: vec![
- "running", "paused", "syncing", "degraded", "error", "idle",
- ],
- },
- comment: "Coarse, UI-shaped status. Precedence: paused > error > \
- degraded > syncing > running > idle. `degraded` (#002) = \
- the pipeline runs but recall/structure is reduced.",
- required: true,
- },
- FieldSchema {
- name: "reason",
- ty: TypeSchema::Option(Box::new(TypeSchema::String)),
- comment: "Human-readable reason for the current status — present \
- for `paused` (gate mode) and `error` (failed-job count).",
- required: false,
- },
- FieldSchema {
- name: "last_sync_ms",
- ty: TypeSchema::I64,
- comment: "Epoch ms of the newest chunk timestamp across all \
- sources; 0 when the store is empty.",
- required: true,
- },
- FieldSchema {
- name: "total_chunks",
- ty: TypeSchema::U64,
- comment: "Total rows in `mem_tree_chunks`.",
- required: true,
- },
- FieldSchema {
- name: "wiki_size_bytes",
- ty: TypeSchema::U64,
- comment: "Recursive on-disk size of the `wiki/` sub-tree under the \
- memory_tree content root. 0 when the directory does not exist yet.",
- required: true,
- },
- FieldSchema {
- name: "pipeline_jobs",
- ty: TypeSchema::Json,
- comment: "Object with `ready` / `running` / `failed` counters \
- from `mem_tree_jobs`.",
- required: true,
- },
- FieldSchema {
- name: "is_syncing",
- ty: TypeSchema::Bool,
- comment: "True when at least one job is in `running` state.",
- required: true,
- },
- FieldSchema {
- name: "is_paused",
- ty: TypeSchema::Bool,
- comment: "True when scheduler-gate mode is `off`.",
- required: true,
- },
- FieldSchema {
- name: "degraded",
- ty: TypeSchema::Json,
- comment: "#002 (FR-002/FR-004): object `{ semantic_recall: bool, \
- structure: bool, cause?: PipelineFailure }`. The pipeline \
- ran but output quality is reduced — `semantic_recall` when \
- embeddings were skipped, `structure` when extraction \
- yielded nothing. `cause` is the single precedence-resolved \
- failure (structure over semantic_recall) and is OMITTED \
- when no degradation is active; the recall/structure flags \
- are tracked independently behind it. The object itself is \
- always present (serde default). Distinct from a hard `error`.",
- required: true,
- },
- FieldSchema {
- name: "first_blocking_cause",
- ty: TypeSchema::Option(Box::new(TypeSchema::Json)),
- comment: "#002 (FR-004): the single most-urgent typed cause as a \
- `PipelineFailure` object `{ code, class, remediation_key }`. \
- A failed job's classified reason wins over a soft \
- degradation cause. null when healthy. The UI resolves \
- `remediation_key` and renders it verbatim.",
- required: false,
- },
- FieldSchema {
- name: "extraction_coverage",
- ty: TypeSchema::Option(Box::new(TypeSchema::F64)),
- comment: "#002 (FR-010): fraction [0.0, 1.0] of chunks with ≥1 \
- indexed entity. Near 0 with total_chunks > 0 means \
- extraction produces no structure. `null` when the metric \
- could not be measured (DB read error) — deliberately \
- distinct from a genuine `0.0` so a broken measurement is \
- never misreported as a structure failure.",
- required: false,
- },
- FieldSchema {
- name: "quarantine",
- ty: TypeSchema::Option(Box::new(TypeSchema::Json)),
- comment: "openhuman#5820: the most recent corrupt-store quarantine, derived from disk \
- (`quarantined_at_ms`, `quarantined_path`, `resynced`). Absent when nothing \
- was quarantined; reported until a chunk lands after it.",
- required: false,
- },
- ],
- },
- "set_enabled" => ControllerSchema {
- namespace: NAMESPACE,
- function: "set_enabled",
- description: "Toggle Memory Tree auto-sync (#1856 Part 1). \
- Flips `config.scheduler_gate().mode` between `auto` (enabled=true) \
- and `off` (enabled=false), persists the change, and hot-reloads \
- the live scheduler-gate so in-flight workers observe the new \
- policy at their next `wait_for_capacity` await. The 20-min \
- Composio fetch loop is NOT paused by this toggle yet — that \
- lands in #1856 Part 2.",
- inputs: vec![FieldSchema {
- name: "enabled",
- ty: TypeSchema::Bool,
- comment: "True ⇒ scheduler-gate mode = auto. False ⇒ mode = off.",
- required: true,
- }],
- outputs: vec![
- FieldSchema {
- name: "enabled",
- ty: TypeSchema::Bool,
- comment: "Echo of the requested enabled state.",
- required: true,
- },
- FieldSchema {
- name: "changed",
- ty: TypeSchema::Bool,
- comment: "True when the persisted mode actually flipped; \
- false for no-ops.",
- required: true,
- },
- FieldSchema {
- name: "mode",
- ty: TypeSchema::String,
- comment: "New scheduler-gate mode as wire string (`auto` / `off`).",
- required: true,
- },
- ],
- },
- "doctor" => ControllerSchema {
- namespace: NAMESPACE,
- function: "doctor",
- description: "One-shot Memory pipeline diagnostic (#002). Walks each \
- stage (embeddings config, scheduler gate, job queue, extraction/recall \
- degradation, summary-tree precondition) and returns per-stage health, \
- the single first blocking cause (typed code + i18n remediation key), the \
- degraded snapshot, and counters. Exposed for the agent's self-diagnosis \
- and the CLI; cheap (config + queue counters + degraded flags, no live \
- network probe).",
- inputs: vec![],
- outputs: vec![
- FieldSchema {
- name: "healthy",
- ty: TypeSchema::Bool,
- comment: "True when no stage is blocking (first_blocking_cause is null).",
- required: true,
- },
- FieldSchema {
- name: "stages",
- ty: TypeSchema::Json,
- comment: "Ordered array of { stage, ok, failure?, note } — pipeline \
- order, so the first non-ok stage is the first blocking cause.",
- required: true,
- },
- FieldSchema {
- name: "first_blocking_cause",
- ty: TypeSchema::Option(Box::new(TypeSchema::Json)),
- comment: "Typed { code, class, remediation_key, detail? } of the first \
- non-ok stage; null when healthy. Mirrors \
- pipeline_status.first_blocking_cause as an explicit Option.",
- required: false,
- },
- FieldSchema {
- name: "degraded",
- ty: TypeSchema::Json,
- comment: "{ semantic_recall, structure, cause? } degradation snapshot.",
- required: true,
- },
- FieldSchema {
- name: "counters",
- ty: TypeSchema::Json,
- comment: "{ total_chunks, jobs_ready, jobs_running, jobs_failed, \
- extraction_coverage: number|null }. extraction_coverage \
- is the fraction [0,1] of chunks with ≥1 indexed entity; \
- null when the metric could not be measured (DB error).",
- required: true,
- },
- ],
- },
- "retry_failed" => ControllerSchema {
- namespace: NAMESPACE,
- function: "retry_failed",
- description: "Requeue every terminally-failed mem_tree_jobs row back to \
- `ready` (#002 FR-011) so jobs that failed under a now-fixed config \
- (e.g. after adding an embeddings key) re-run without re-ingesting \
- source data. Resets the attempt budget and clears the typed failure \
- reason. Manual, on-demand retry — there is no automatic \
- requeue-on-sync yet.",
- inputs: vec![],
- outputs: vec![FieldSchema {
- name: "requeued",
- ty: TypeSchema::U64,
- comment: "Number of failed jobs flipped back to ready for retry.",
- required: true,
- }],
- },
- "memory_backfill_status" => ControllerSchema {
- namespace: NAMESPACE,
- function: "memory_backfill_status",
- description: "Report whether a per-model embedding re-embed \
- backfill (#1574) is in flight. The UI polls this while the \
- re-embed modal is open: semantic recall over not-yet-\
- re-embedded memory is reduced until the chain drains.",
- inputs: vec![],
- outputs: vec![
- FieldSchema {
- name: "in_progress",
- ty: TypeSchema::Bool,
- comment: "True while a re-embed backfill still has work \
- pending (flag set or a ready/running job).",
- required: true,
- },
- FieldSchema {
- name: "pending_jobs",
- ty: TypeSchema::U64,
- comment: "Count of reembed_backfill jobs in ready or \
- running state; 0 with in_progress=false means the \
- active embedding space is fully covered.",
- required: true,
- },
- ],
- },
- "smart_walk" => ControllerSchema {
- namespace: NAMESPACE,
- function: "smart_walk",
- description: "Deterministic E2GraphRAG memory retrieval — extracts \
- query entities (spaCy, with regex fallback), routes between \
- entity-graph (local) and dense-summary (global) search with no \
- LLM, and returns ranked evidence hits for a natural-language \
- query.",
- inputs: vec![
- FieldSchema {
- name: "query",
- ty: TypeSchema::String,
- comment: "Natural-language question to answer.",
- required: true,
- },
- FieldSchema {
- name: "limit",
- ty: TypeSchema::U64,
- comment: "Max evidence hits to return. Default 10.",
- required: false,
- },
- FieldSchema {
- name: "time_window_days",
- ty: TypeSchema::U64,
- comment: "Restrict the global/dense branch to the last N days.",
- required: false,
- },
- FieldSchema {
- name: "max_hops",
- ty: TypeSchema::U64,
- comment: "Entity-graph relatedness hop threshold. Default 2.",
- required: false,
- },
- ],
- outputs: vec![
- FieldSchema {
- name: "hits",
- ty: TypeSchema::Array(Box::new(TypeSchema::Json)),
- comment: "Ranked RetrievalHit evidence (node_id, content, \
- entities, score, time range, ...).",
- required: true,
- },
- FieldSchema {
- name: "total",
- ty: TypeSchema::U64,
- comment: "Pre-truncation match count.",
- required: true,
- },
- FieldSchema {
- name: "truncated",
- ty: TypeSchema::Bool,
- comment: "True when total exceeds the returned hit count.",
- required: true,
- },
- ],
- },
- _ => ControllerSchema {
- namespace: NAMESPACE,
- function: "unknown",
- description: "Unknown memory_tree controller function.",
- inputs: vec![FieldSchema {
- name: "function",
- ty: TypeSchema::String,
- comment: "Unknown function requested for schema lookup.",
- required: true,
- }],
- outputs: vec![FieldSchema {
- name: "error",
- ty: TypeSchema::String,
- comment: "Lookup error details.",
- required: true,
- }],
- },
+ if let Some(schema) = schema_schema_part_01::lookup(function) {
+ return schema;
+ }
+ if let Some(schema) = schema_schema_part_02::lookup(function) {
+ return schema;
+ }
+ ControllerSchema {
+ namespace: NAMESPACE,
+ function: "unknown",
+ description: "Unknown memory_tree controller function.",
+ inputs: vec![FieldSchema {
+ name: "function",
+ ty: TypeSchema::String,
+ comment: "Unknown function requested for schema lookup.",
+ required: true,
+ }],
+ outputs: vec![FieldSchema {
+ name: "error",
+ ty: TypeSchema::String,
+ comment: "Lookup error details.",
+ required: true,
+ }],
}
}
diff --git a/src/openhuman/memory/schema/schema_schema_part_01.rs b/src/openhuman/memory/schema/schema_schema_part_01.rs
new file mode 100644
index 0000000000..f85721b994
--- /dev/null
+++ b/src/openhuman/memory/schema/schema_schema_part_01.rs
@@ -0,0 +1,592 @@
+use super::*;
+
+pub(super) fn lookup(function: &str) -> Option<ControllerSchema> {
+ match function {
+"ingest" => Some( ControllerSchema {
+ namespace: NAMESPACE,
+ function: "ingest",
+ description: "Ingest a source into canonical chunks. \
+ Dispatches on `source_kind`; `payload` shape depends on the kind \
+ (chat → ChatBatch, email → EmailThread, document → DocumentInput).",
+ inputs: vec![
+ FieldSchema {
+ name: "source_kind",
+ ty: TypeSchema::Enum {
+ variants: vec!["chat", "email", "document"],
+ },
+ comment: "Which source kind the payload represents.",
+ required: true,
+ },
+ FieldSchema {
+ name: "source_id",
+ ty: TypeSchema::String,
+ comment: "Stable logical source id (channel, thread, document id).",
+ required: true,
+ },
+ FieldSchema {
+ name: "owner",
+ ty: TypeSchema::String,
+ comment: "Optional account / user this content belongs to.",
+ required: false,
+ },
+ FieldSchema {
+ name: "tags",
+ ty: TypeSchema::Array(Box::new(TypeSchema::String)),
+ comment: "Optional tags or labels carried through.",
+ required: false,
+ },
+ FieldSchema {
+ name: "payload",
+ ty: TypeSchema::Json,
+ comment: "Adapter-specific payload. \
+ chat: {platform, channel_label, messages[]}. \
+ email: {provider, thread_subject, messages[]}. \
+ document: {provider, title, body, modified_at, source_ref}.",
+ required: true,
+ },
+ ],
+ outputs: vec![
+ FieldSchema {
+ name: "source_id",
+ ty: TypeSchema::String,
+ comment: "Logical source id the ingest was scoped to.",
+ required: true,
+ },
+ FieldSchema {
+ name: "chunks_written",
+ ty: TypeSchema::U64,
+ comment: "Number of chunks persisted after admission.",
+ required: true,
+ },
+ FieldSchema {
+ name: "chunks_dropped",
+ ty: TypeSchema::U64,
+ comment: "Number of chunks rejected by the admission gate.",
+ required: true,
+ },
+ FieldSchema {
+ name: "chunk_ids",
+ ty: TypeSchema::Array(Box::new(TypeSchema::String)),
+ comment: "IDs of all chunks persisted after admission.",
+ required: true,
+ },
+ ],
+ }),
+"list_chunks" => Some( ControllerSchema {
+ namespace: NAMESPACE,
+ function: "list_chunks",
+ description: "Paginated list of chunks with optional filters by source kind / source id / \
+ entity ids / time window / keyword. Returns chunks plus total match count for \
+ pagination.",
+ inputs: vec![
+ FieldSchema {
+ name: "source_kinds",
+ ty: TypeSchema::Option(Box::new(TypeSchema::Array(Box::new(
+ TypeSchema::String,
+ )))),
+ comment: "Restrict to one or more source kinds (chat / email / document).",
+ required: false,
+ },
+ FieldSchema {
+ name: "source_ids",
+ ty: TypeSchema::Option(Box::new(TypeSchema::Array(Box::new(
+ TypeSchema::String,
+ )))),
+ comment: "Restrict to one or more logical source ids.",
+ required: false,
+ },
+ FieldSchema {
+ name: "entity_ids",
+ ty: TypeSchema::Option(Box::new(TypeSchema::Array(Box::new(
+ TypeSchema::String,
+ )))),
+ comment: "Restrict to chunks indexed against any of these canonical entity ids.",
+ required: false,
+ },
+ FieldSchema {
+ name: "since_ms",
+ ty: TypeSchema::Option(Box::new(TypeSchema::I64)),
+ comment: "Inclusive lower bound on chunk timestamp (ms since epoch).",
+ required: false,
+ },
+ FieldSchema {
+ name: "until_ms",
+ ty: TypeSchema::Option(Box::new(TypeSchema::I64)),
+ comment: "Inclusive upper bound on chunk timestamp (ms since epoch).",
+ required: false,
+ },
+ FieldSchema {
+ name: "query",
+ ty: TypeSchema::Option(Box::new(TypeSchema::String)),
+ comment: "Substring keyword filter over chunk preview content.",
+ required: false,
+ },
+ FieldSchema {
+ name: "limit",
+ ty: TypeSchema::Option(Box::new(TypeSchema::U64)),
+ comment: "Maximum rows per page (defaults to 50, capped at 1000).",
+ required: false,
+ },
+ FieldSchema {
+ name: "offset",
+ ty: TypeSchema::Option(Box::new(TypeSchema::U64)),
+ comment: "Pagination offset (defaults to 0).",
+ required: false,
+ },
+ ],
+ outputs: vec![
+ FieldSchema {
+ name: "chunks",
+ ty: TypeSchema::Array(Box::new(TypeSchema::Ref("Chunk"))),
+ comment: "Page of matching chunks ordered by timestamp DESC.",
+ required: true,
+ },
+ FieldSchema {
+ name: "total",
+ ty: TypeSchema::U64,
+ comment: "Total number of chunks matching the filter (pre-pagination).",
+ required: true,
+ },
+ ],
+ }),
+"get_chunk" => Some( ControllerSchema {
+ namespace: NAMESPACE,
+ function: "get_chunk",
+ description: "Fetch a single chunk by its deterministic id.",
+ inputs: vec![FieldSchema {
+ name: "id",
+ ty: TypeSchema::String,
+ comment: "Chunk id (32 hex chars).",
+ required: true,
+ }],
+ outputs: vec![FieldSchema {
+ name: "chunk",
+ ty: TypeSchema::Option(Box::new(TypeSchema::Ref("Chunk"))),
+ comment: "The chunk if found, otherwise null.",
+ required: false,
+ }],
+ }),
+"list_sources" => Some( ControllerSchema {
+ namespace: NAMESPACE,
+ function: "list_sources",
+ description: "Distinct (source_kind, source_id) pairs with chunk counts and most-recent timestamps. \
+ `display_name` is computed from the source_id (un-slug + strip user email when known).",
+ inputs: vec![FieldSchema {
+ name: "user_email_hint",
+ ty: TypeSchema::Option(Box::new(TypeSchema::String)),
+ comment: "When provided, source ids that contain this email get it stripped from \
+ their display name so the UI shows the other party of an email thread.",
+ required: false,
+ }],
+ outputs: vec![FieldSchema {
+ name: "sources",
+ ty: TypeSchema::Array(Box::new(TypeSchema::Ref("Source"))),
+ comment: "All distinct ingest sources, newest activity first.",
+ required: true,
+ }],
+ }),
+"search" => Some( ControllerSchema {
+ namespace: NAMESPACE,
+ function: "search",
+ description: "Keyword LIKE-search over chunk bodies. Cheap, deterministic; useful as a \
+ fallback when semantic recall is unavailable.",
+ inputs: vec![
+ FieldSchema {
+ name: "query",
+ ty: TypeSchema::String,
+ comment: "Substring to match against chunk content.",
+ required: true,
+ },
+ FieldSchema {
+ name: "k",
+ ty: TypeSchema::U64,
+ comment: "Maximum chunks to return.",
+ required: true,
+ },
+ ],
+ outputs: vec![FieldSchema {
+ name: "chunks",
+ ty: TypeSchema::Array(Box::new(TypeSchema::Ref("Chunk"))),
+ comment: "Matching chunks ordered by recency.",
+ required: true,
+ }],
+ }),
+"recall" => Some( ControllerSchema {
+ namespace: NAMESPACE,
+ function: "recall",
+ description: "Semantic recall — runs the Phase 4 cosine rerank against the query embedding \
+ and returns leaf chunks (not summaries) for UI display.",
+ inputs: vec![
+ FieldSchema {
+ name: "query",
+ ty: TypeSchema::String,
+ comment: "Free-text query — embedded once and reranked against summary embeddings.",
+ required: true,
+ },
+ FieldSchema {
+ name: "k",
+ ty: TypeSchema::U64,
+ comment: "Maximum chunks to return.",
+ required: true,
+ },
+ ],
+ outputs: vec![
+ FieldSchema {
+ name: "chunks",
+ ty: TypeSchema::Array(Box::new(TypeSchema::Ref("Chunk"))),
+ comment: "Recalled chunks, sorted in the same order as the rerank.",
+ required: true,
+ },
+ FieldSchema {
+ name: "scores",
+ ty: TypeSchema::Array(Box::new(TypeSchema::Json)),
+ comment: "Parallel array of similarity scores (one per chunk).",
+ required: true,
+ },
+ ],
+ }),
+"entity_index_for" => Some( ControllerSchema {
+ namespace: NAMESPACE,
+ function: "entity_index_for",
+ description: "Return all canonical entities indexed against a chunk (or summary node) id.",
+ inputs: vec![FieldSchema {
+ name: "chunk_id",
+ ty: TypeSchema::String,
+ comment: "Chunk id (32 hex chars).",
+ required: true,
+ }],
+ outputs: vec![FieldSchema {
+ name: "entities",
+ ty: TypeSchema::Array(Box::new(TypeSchema::Ref("EntityRef"))),
+ comment: "Entities attached to the node, ordered by mention count DESC.",
+ required: true,
+ }],
+ }),
+"chunks_for_entity" => Some( ControllerSchema {
+ namespace: NAMESPACE,
+ function: "chunks_for_entity",
+ description: "Return chunk IDs that reference an entity_id (inverse of entity_index_for). \
+ Used by the Memory tab's People/Topics lenses to filter the chunk list.",
+ inputs: vec![FieldSchema {
+ name: "entity_id",
+ ty: TypeSchema::String,
+ comment: "Canonical entity id (e.g. `person:Steven Enamakel`, \
+ `email:[email protected]`).",
+ required: true,
+ }],
+ outputs: vec![FieldSchema {
+ name: "chunk_ids",
+ ty: TypeSchema::Array(Box::new(TypeSchema::String)),
+ comment: "Chunk ids that mention the entity, ordered by recency DESC.",
+ required: true,
+ }],
+ }),
+"top_entities" => Some( ControllerSchema {
+ namespace: NAMESPACE,
+ function: "top_entities",
+ description: "Most-frequent canonical entities across the workspace, optionally narrowed by kind.",
+ inputs: vec![
+ FieldSchema {
+ name: "kind",
+ ty: TypeSchema::Option(Box::new(TypeSchema::String)),
+ comment: "Restrict to a single entity_kind (`person`, `email`, `topic`, …).",
+ required: false,
+ },
+ FieldSchema {
+ name: "limit",
+ ty: TypeSchema::U64,
+ comment: "Maximum rows to return.",
+ required: true,
+ },
+ ],
+ outputs: vec![FieldSchema {
+ name: "entities",
+ ty: TypeSchema::Array(Box::new(TypeSchema::Ref("EntityRef"))),
+ comment: "Top entities, ordered by mention count DESC.",
+ required: true,
+ }],
+ }),
+"chunk_score" => Some( ControllerSchema {
+ namespace: NAMESPACE,
+ function: "chunk_score",
+ description: "Score breakdown stored in `mem_tree_score` for one chunk — used by the Memory \
+ tab's 'why was this kept / dropped' panel.",
+ inputs: vec![FieldSchema {
+ name: "chunk_id",
+ ty: TypeSchema::String,
+ comment: "Chunk id (32 hex chars).",
+ required: true,
+ }],
+ outputs: vec![FieldSchema {
+ name: "breakdown",
+ ty: TypeSchema::Option(Box::new(TypeSchema::Ref("ScoreBreakdown"))),
+ comment: "Per-signal weight + value array, total, threshold, kept flag, llm_consulted flag.",
+ required: false,
+ }],
+ }),
+"delete_chunk" => Some( ControllerSchema {
+ namespace: NAMESPACE,
+ function: "delete_chunk",
+ description: "Purge one chunk plus its score row, entity-index rows, and on-disk .md file. \
+ Idempotent — missing chunk returns deleted=false. Does NOT cascade through \
+ sealed summaries; UIs warn the user.",
+ inputs: vec![FieldSchema {
+ name: "chunk_id",
+ ty: TypeSchema::String,
+ comment: "Chunk id to remove.",
+ required: true,
+ }],
+ outputs: vec![
+ FieldSchema {
+ name: "deleted",
+ ty: TypeSchema::Bool,
+ comment: "True when the chunk row was found and removed.",
+ required: true,
+ },
+ FieldSchema {
+ name: "score_rows_removed",
+ ty: TypeSchema::U64,
+ comment: "Count of rows removed from `mem_tree_score`.",
+ required: true,
+ },
+ FieldSchema {
+ name: "entity_index_rows_removed",
+ ty: TypeSchema::U64,
+ comment: "Count of rows removed from `mem_tree_entity_index`.",
+ required: true,
+ },
+ ],
+ }),
+"delete_source" => Some( ControllerSchema {
+ namespace: NAMESPACE,
+ function: "delete_source",
+ description: "Fully delete one document source by its EXACT source_id: every chunk \
+ plus its score / entity-index / embedding / reembed-skip side rows and chunk \
+ content files, the ingest dedup gates (bare source_id AND versioned \
+ source_id@version), and (when the source becomes fully orphaned) its \
+ source-scoped summary tree — summaries, summary embeddings + reembed-skip, \
+ tree entity-index, buffers, the tree row, and summary content files. Unlike \
+ delete_chunk this cascades, so stale summaries of the deleted source cannot \
+ resurface in recall, and it also finishes legacy partial deletes (chunks already \
+ gone, tree/gate left behind). Exact match only (never a prefix); shared \
+ collection/path_scope trees that summarise multiple documents are left intact. \
+ Idempotent — an unknown source_id returns deleted=false.",
+ inputs: vec![FieldSchema {
+ name: "source_id",
+ ty: TypeSchema::String,
+ comment: "Exact source id to remove (e.g. a Telegram note/event/meeting id).",
+ required: true,
+ }],
+ outputs: vec![
+ FieldSchema {
+ name: "deleted",
+ ty: TypeSchema::Bool,
+ comment: "True when the call did real work: chunks were removed OR a stale \
+ orphaned source tree was cleaned (legacy case, chunks_removed=0).",
+ required: true,
+ },
+ FieldSchema {
+ name: "chunks_removed",
+ ty: TypeSchema::U64,
+ comment: "Number of chunk rows removed for the source.",
+ required: true,
+ },
+ ],
+ }),
+"wipe_all" => Some( ControllerSchema {
+ namespace: NAMESPACE,
+ function: "wipe_all",
+ description: "Destructive reset: truncate every mem_tree_* table, remove the \
+ on-disk content folders (raw / wiki / email / chat / document / \
+ legacy summaries) under the workspace memory_tree content root, \
+ and clear every Composio sync-state KV row so the next sync \
+ re-fetches all upstream items. Used by the Memory tab's 'Reset \
+ memory' button.",
+ inputs: vec![],
+ outputs: vec![
+ FieldSchema {
+ name: "rows_deleted",
+ ty: TypeSchema::U64,
+ comment: "Total mem_tree_* rows removed across all tables.",
+ required: true,
+ },
+ FieldSchema {
+ name: "dirs_removed",
+ ty: TypeSchema::Array(Box::new(TypeSchema::String)),
+ comment: "Top-level directories under content_root that were deleted.",
+ required: true,
+ },
+ FieldSchema {
+ name: "sync_state_cleared",
+ ty: TypeSchema::U64,
+ comment: "Composio sync-state KV rows deleted (cursors + synced-id sets).",
+ required: true,
+ },
+ ],
+ }),
+"reset_tree" => Some( ControllerSchema {
+ namespace: NAMESPACE,
+ function: "reset_tree",
+ description: "Wipe summary-tree state but keep chunks + raw archive + sync state, \
+ then re-enqueue every chunk through the extraction pipeline so the \
+ tree rebuilds from scratch. Useful after changing the summariser \
+ backend (e.g. enabling a local LLM) without paying the upstream \
+ re-sync cost.",
+ inputs: vec![],
+ outputs: vec![
+ FieldSchema {
+ name: "tree_rows_deleted",
+ ty: TypeSchema::U64,
+ comment: "Tree-state rows removed (summaries + trees + buffers + jobs).",
+ required: true,
+ },
+ FieldSchema {
+ name: "chunks_requeued",
+ ty: TypeSchema::U64,
+ comment: "Chunks reset to lifecycle_status = 'pending_extraction'.",
+ required: true,
+ },
+ FieldSchema {
+ name: "jobs_enqueued",
+ ty: TypeSchema::U64,
+ comment: "extract_chunk jobs enqueued (one per chunk).",
+ required: true,
+ },
+ ],
+ }),
+"flush_source" => Some( ControllerSchema {
+ namespace: NAMESPACE,
+ function: "flush_source",
+ description: "Immediately seal one source tree's L0 buffer, bypassing the job \
+ queue. Mutex per source scope so concurrent clicks are serialised. \
+ Returns the number of seal cascades that fired.",
+ inputs: vec![FieldSchema {
+ name: "source_scope",
+ ty: TypeSchema::String,
+ comment: "Source tree scope (e.g. `github:org/repo`, `slack:#eng`).",
+ required: true,
+ }],
+ outputs: vec![
+ FieldSchema {
+ name: "tree_scope",
+ ty: TypeSchema::String,
+ comment: "Echo of the source scope.",
+ required: true,
+ },
+ FieldSchema {
+ name: "seals_fired",
+ ty: TypeSchema::U64,
+ comment: "Number of seal cascades that fired.",
+ required: true,
+ },
+ ],
+ }),
+"flush_now" => Some( ControllerSchema {
+ namespace: NAMESPACE,
+ function: "flush_now",
+ description: "Manually trigger the summary-tree build. Enqueues a flush_stale \
+ job with max_age_secs=0 so every L0 buffer force-seals immediately; \
+ the seal worker runs each through the configured (cloud or local) \
+ summariser. Idempotent — same UTC-day dedupe key as the scheduled \
+ flush so spamming the button is safe.",
+ inputs: vec![],
+ outputs: vec![
+ FieldSchema {
+ name: "enqueued",
+ ty: TypeSchema::Bool,
+ comment: "True when a fresh job row was inserted; false when an active \
+ flush job already exists for today.",
+ required: true,
+ },
+ FieldSchema {
+ name: "stale_buffers",
+ ty: TypeSchema::U64,
+ comment: "Count of L0 buffers that currently qualify for force-seal.",
+ required: true,
+ },
+ ],
+ }),
+"graph_export" => Some( ControllerSchema {
+ namespace: NAMESPACE,
+ function: "graph_export",
+ description: "Return either the summary tree (parent→child links between sealed \
+ summary nodes) or the document↔contact graph (chunks linked to \
+ person entities they mention). Includes the absolute path to the \
+ on-disk content root so deep links can point Obsidian at the same \
+ files.",
+ inputs: vec![FieldSchema {
+ name: "mode",
+ ty: TypeSchema::Option(Box::new(TypeSchema::Enum {
+ variants: vec!["tree", "contacts"],
+ })),
+ comment: "Which graph to return. Defaults to `tree`.",
+ required: false,
+ }],
+ outputs: vec![
+ FieldSchema {
+ name: "nodes",
+ ty: TypeSchema::Array(Box::new(TypeSchema::Ref("GraphNode"))),
+ comment: "Summary, chunk, or contact nodes depending on mode.",
+ required: true,
+ },
+ FieldSchema {
+ name: "edges",
+ ty: TypeSchema::Array(Box::new(TypeSchema::Ref("GraphEdge"))),
+ comment: "Explicit edges. Empty in tree mode (parent_id encodes \
+ edges); chunk→contact mention edges in contacts mode.",
+ required: true,
+ },
+ FieldSchema {
+ name: "content_root_abs",
+ ty: TypeSchema::String,
+ comment: "Absolute path to <workspace>/memory_tree/content/.",
+ required: true,
+ },
+ ],
+ }),
+"obsidian_vault_status" => Some( ControllerSchema {
+ namespace: NAMESPACE,
+ function: "obsidian_vault_status",
+ description: "Best-effort check of whether the memory-tree content root is \
+ already a registered Obsidian vault. `obsidian://open?path=` only \
+ resolves vaults present in Obsidian's obsidian.json registry — it \
+ cannot register a new one — so the Memory tab calls this before \
+ firing the deep link and guides the user to 'Open folder as vault' \
+ when it isn't registered. Never errors; a probe miss reports \
+ registered=false.",
+ inputs: vec![FieldSchema {
+ name: "obsidian_config_dir",
+ ty: TypeSchema::Option(Box::new(TypeSchema::String)),
+ comment: "Optional override for Obsidian's config directory (where \
+ obsidian.json lives), for non-standard installs \
+ (Flatpak / Snap / portable). Omitted ⇒ probe the standard per-OS \
+ location plus known sandbox paths.",
+ required: false,
+ }],
+ outputs: vec![
+ FieldSchema {
+ name: "registered",
+ ty: TypeSchema::Bool,
+ comment: "True when the content root (or an ancestor) is a registered \
+ Obsidian vault, so the deep link will resolve.",
+ required: true,
+ },
+ FieldSchema {
+ name: "config_found",
+ ty: TypeSchema::Bool,
+ comment: "True when an obsidian.json was found and parsed (Obsidian is \
+ set up). Lets the UI offer add-as-vault vs. install.",
+ required: true,
+ },
+ FieldSchema {
+ name: "content_root_abs",
+ ty: TypeSchema::String,
+ comment: "Absolute path to <workspace>/memory_tree/content/ — the folder \
+ to add to Obsidian and the deep-link target.",
+ required: true,
+ },
+ ],
+ }),
+ _ => None,
+ }
+}
diff --git a/src/openhuman/memory/schema/schema_schema_part_02.rs b/src/openhuman/memory/schema/schema_schema_part_02.rs
new file mode 100644
index 0000000000..f07fda0f92
--- /dev/null
+++ b/src/openhuman/memory/schema/schema_schema_part_02.rs
@@ -0,0 +1,368 @@
+use super::*;
+
+pub(super) fn lookup(function: &str) -> Option<ControllerSchema> {
+ match function {
+"vault_health_check" => Some( ControllerSchema {
+ namespace: NAMESPACE,
+ function: "vault_health_check",
+ description: "Consolidated workspace-vault health snapshot for onboarding and \
+ settings. Checks whether <workspace>/memory_tree/content exists, is \
+ readable, and is writable (via temp-file probe), whether Obsidian has \
+ the vault registered, and whether the Memory Tree pipeline is healthy.",
+ inputs: vec![FieldSchema {
+ name: "obsidian_config_dir",
+ ty: TypeSchema::Option(Box::new(TypeSchema::String)),
+ comment: "Optional override for Obsidian's config directory (where \
+ obsidian.json lives). Omitted ⇒ standard per-OS probe.",
+ required: false,
+ }],
+ outputs: vec![
+ FieldSchema {
+ name: "content_root_abs",
+ ty: TypeSchema::String,
+ comment: "Absolute path to <workspace>/memory_tree/content/.",
+ required: true,
+ },
+ FieldSchema {
+ name: "exists",
+ ty: TypeSchema::Bool,
+ comment: "True when the workspace vault directory exists on disk.",
+ required: true,
+ },
+ FieldSchema {
+ name: "readable",
+ ty: TypeSchema::Bool,
+ comment: "True when the workspace vault directory can be read.",
+ required: true,
+ },
+ FieldSchema {
+ name: "writable",
+ ty: TypeSchema::Bool,
+ comment: "True when the vault accepts a create+delete temp-file probe.",
+ required: true,
+ },
+ FieldSchema {
+ name: "obsidian_registered",
+ ty: TypeSchema::Bool,
+ comment: "True when Obsidian has this folder (or an ancestor) registered \
+ as a vault.",
+ required: true,
+ },
+ FieldSchema {
+ name: "pipeline_healthy",
+ ty: TypeSchema::Bool,
+ comment: "True when Memory Tree pipeline is not paused and not in error.",
+ required: true,
+ },
+ FieldSchema {
+ name: "last_sync_ms",
+ ty: TypeSchema::I64,
+ comment: "Epoch ms of the newest chunk timestamp; 0 when empty.",
+ required: true,
+ },
+ ],
+ }),
+"pipeline_status" => Some( ControllerSchema {
+ namespace: NAMESPACE,
+ function: "pipeline_status",
+ description: "Aggregated Memory Tree health snapshot (#1856 Part 1). \
+ Returns a coarse `status` string (running/paused/syncing/error/idle), \
+ an optional human-readable reason, the most-recent chunk timestamp, \
+ the total chunk count, the on-disk wiki size in bytes, and per-state \
+ job counters from `mem_tree_jobs`. Polled by the Memory Tree status \
+ panel; cheap enough to call every couple of seconds.",
+ inputs: vec![],
+ outputs: vec![
+ FieldSchema {
+ name: "status",
+ ty: TypeSchema::Enum {
+ variants: vec![
+ "running", "paused", "syncing", "degraded", "error", "idle",
+ ],
+ },
+ comment: "Coarse, UI-shaped status. Precedence: paused > error > \
+ degraded > syncing > running > idle. `degraded` (#002) = \
+ the pipeline runs but recall/structure is reduced.",
+ required: true,
+ },
+ FieldSchema {
+ name: "reason",
+ ty: TypeSchema::Option(Box::new(TypeSchema::String)),
+ comment: "Human-readable reason for the current status — present \
+ for `paused` (gate mode) and `error` (failed-job count).",
+ required: false,
+ },
+ FieldSchema {
+ name: "last_sync_ms",
+ ty: TypeSchema::I64,
+ comment: "Epoch ms of the newest chunk timestamp across all \
+ sources; 0 when the store is empty.",
+ required: true,
+ },
+ FieldSchema {
+ name: "total_chunks",
+ ty: TypeSchema::U64,
+ comment: "Total rows in `mem_tree_chunks`.",
+ required: true,
+ },
+ FieldSchema {
+ name: "wiki_size_bytes",
+ ty: TypeSchema::U64,
+ comment: "Recursive on-disk size of the `wiki/` sub-tree under the \
+ memory_tree content root. 0 when the directory does not exist yet.",
+ required: true,
+ },
+ FieldSchema {
+ name: "pipeline_jobs",
+ ty: TypeSchema::Json,
+ comment: "Object with `ready` / `running` / `failed` counters \
+ from `mem_tree_jobs`.",
+ required: true,
+ },
+ FieldSchema {
+ name: "is_syncing",
+ ty: TypeSchema::Bool,
+ comment: "True when at least one job is in `running` state.",
+ required: true,
+ },
+ FieldSchema {
+ name: "is_paused",
+ ty: TypeSchema::Bool,
+ comment: "True when scheduler-gate mode is `off`.",
+ required: true,
+ },
+ FieldSchema {
+ name: "degraded",
+ ty: TypeSchema::Json,
+ comment: "#002 (FR-002/FR-004): object `{ semantic_recall: bool, \
+ structure: bool, cause?: PipelineFailure }`. The pipeline \
+ ran but output quality is reduced — `semantic_recall` when \
+ embeddings were skipped, `structure` when extraction \
+ yielded nothing. `cause` is the single precedence-resolved \
+ failure (structure over semantic_recall) and is OMITTED \
+ when no degradation is active; the recall/structure flags \
+ are tracked independently behind it. The object itself is \
+ always present (serde default). Distinct from a hard `error`.",
+ required: true,
+ },
+ FieldSchema {
+ name: "first_blocking_cause",
+ ty: TypeSchema::Option(Box::new(TypeSchema::Json)),
+ comment: "#002 (FR-004): the single most-urgent typed cause as a \
+ `PipelineFailure` object `{ code, class, remediation_key }`. \
+ A failed job's classified reason wins over a soft \
+ degradation cause. null when healthy. The UI resolves \
+ `remediation_key` and renders it verbatim.",
+ required: false,
+ },
+ FieldSchema {
+ name: "extraction_coverage",
+ ty: TypeSchema::Option(Box::new(TypeSchema::F64)),
+ comment: "#002 (FR-010): fraction [0.0, 1.0] of chunks with ≥1 \
+ indexed entity. Near 0 with total_chunks > 0 means \
+ extraction produces no structure. `null` when the metric \
+ could not be measured (DB read error) — deliberately \
+ distinct from a genuine `0.0` so a broken measurement is \
+ never misreported as a structure failure.",
+ required: false,
+ },
+ FieldSchema {
+ name: "quarantine",
+ ty: TypeSchema::Option(Box::new(TypeSchema::Json)),
+ comment: "openhuman#5820: the most recent corrupt-store quarantine, derived from disk \
+ (`quarantined_at_ms`, `quarantined_path`, `resynced`). Absent when nothing \
+ was quarantined; reported until a chunk lands after it.",
+ required: false,
+ },
+ ],
+ }),
+"set_enabled" => Some( ControllerSchema {
+ namespace: NAMESPACE,
+ function: "set_enabled",
+ description: "Toggle Memory Tree auto-sync (#1856 Part 1). \
+ Flips `config.scheduler_gate().mode` between `auto` (enabled=true) \
+ and `off` (enabled=false), persists the change, and hot-reloads \
+ the live scheduler-gate so in-flight workers observe the new \
+ policy at their next `wait_for_capacity` await. The 20-min \
+ Composio fetch loop is NOT paused by this toggle yet — that \
+ lands in #1856 Part 2.",
+ inputs: vec![FieldSchema {
+ name: "enabled",
+ ty: TypeSchema::Bool,
+ comment: "True ⇒ scheduler-gate mode = auto. False ⇒ mode = off.",
+ required: true,
+ }],
+ outputs: vec![
+ FieldSchema {
+ name: "enabled",
+ ty: TypeSchema::Bool,
+ comment: "Echo of the requested enabled state.",
+ required: true,
+ },
+ FieldSchema {
+ name: "changed",
+ ty: TypeSchema::Bool,
+ comment: "True when the persisted mode actually flipped; \
+ false for no-ops.",
+ required: true,
+ },
+ FieldSchema {
+ name: "mode",
+ ty: TypeSchema::String,
+ comment: "New scheduler-gate mode as wire string (`auto` / `off`).",
+ required: true,
+ },
+ ],
+ }),
+"doctor" => Some( ControllerSchema {
+ namespace: NAMESPACE,
+ function: "doctor",
+ description: "One-shot Memory pipeline diagnostic (#002). Walks each \
+ stage (embeddings config, scheduler gate, job queue, extraction/recall \
+ degradation, summary-tree precondition) and returns per-stage health, \
+ the single first blocking cause (typed code + i18n remediation key), the \
+ degraded snapshot, and counters. Exposed for the agent's self-diagnosis \
+ and the CLI; cheap (config + queue counters + degraded flags, no live \
+ network probe).",
+ inputs: vec![],
+ outputs: vec![
+ FieldSchema {
+ name: "healthy",
+ ty: TypeSchema::Bool,
+ comment: "True when no stage is blocking (first_blocking_cause is null).",
+ required: true,
+ },
+ FieldSchema {
+ name: "stages",
+ ty: TypeSchema::Json,
+ comment: "Ordered array of { stage, ok, failure?, note } — pipeline \
+ order, so the first non-ok stage is the first blocking cause.",
+ required: true,
+ },
+ FieldSchema {
+ name: "first_blocking_cause",
+ ty: TypeSchema::Option(Box::new(TypeSchema::Json)),
+ comment: "Typed { code, class, remediation_key, detail? } of the first \
+ non-ok stage; null when healthy. Mirrors \
+ pipeline_status.first_blocking_cause as an explicit Option.",
+ required: false,
+ },
+ FieldSchema {
+ name: "degraded",
+ ty: TypeSchema::Json,
+ comment: "{ semantic_recall, structure, cause? } degradation snapshot.",
+ required: true,
+ },
+ FieldSchema {
+ name: "counters",
+ ty: TypeSchema::Json,
+ comment: "{ total_chunks, jobs_ready, jobs_running, jobs_failed, \
+ extraction_coverage: number|null }. extraction_coverage \
+ is the fraction [0,1] of chunks with ≥1 indexed entity; \
+ null when the metric could not be measured (DB error).",
+ required: true,
+ },
+ ],
+ }),
+"retry_failed" => Some( ControllerSchema {
+ namespace: NAMESPACE,
+ function: "retry_failed",
+ description: "Requeue every terminally-failed mem_tree_jobs row back to \
+ `ready` (#002 FR-011) so jobs that failed under a now-fixed config \
+ (e.g. after adding an embeddings key) re-run without re-ingesting \
+ source data. Resets the attempt budget and clears the typed failure \
+ reason. Manual, on-demand retry — there is no automatic \
+ requeue-on-sync yet.",
+ inputs: vec![],
+ outputs: vec![FieldSchema {
+ name: "requeued",
+ ty: TypeSchema::U64,
+ comment: "Number of failed jobs flipped back to ready for retry.",
+ required: true,
+ }],
+ }),
+"memory_backfill_status" => Some( ControllerSchema {
+ namespace: NAMESPACE,
+ function: "memory_backfill_status",
+ description: "Report whether a per-model embedding re-embed \
+ backfill (#1574) is in flight. The UI polls this while the \
+ re-embed modal is open: semantic recall over not-yet-\
+ re-embedded memory is reduced until the chain drains.",
+ inputs: vec![],
+ outputs: vec![
+ FieldSchema {
+ name: "in_progress",
+ ty: TypeSchema::Bool,
+ comment: "True while a re-embed backfill still has work \
+ pending (flag set or a ready/running job).",
+ required: true,
+ },
+ FieldSchema {
+ name: "pending_jobs",
+ ty: TypeSchema::U64,
+ comment: "Count of reembed_backfill jobs in ready or \
+ running state; 0 with in_progress=false means the \
+ active embedding space is fully covered.",
+ required: true,
+ },
+ ],
+ }),
+"smart_walk" => Some( ControllerSchema {
+ namespace: NAMESPACE,
+ function: "smart_walk",
+ description: "Deterministic E2GraphRAG memory retrieval — extracts \
+ query entities (spaCy, with regex fallback), routes between \
+ entity-graph (local) and dense-summary (global) search with no \
+ LLM, and returns ranked evidence hits for a natural-language \
+ query.",
+ inputs: vec![
+ FieldSchema {
+ name: "query",
+ ty: TypeSchema::String,
+ comment: "Natural-language question to answer.",
+ required: true,
+ },
+ FieldSchema {
+ name: "limit",
+ ty: TypeSchema::U64,
+ comment: "Max evidence hits to return. Default 10.",
+ required: false,
+ },
+ FieldSchema {
+ name: "time_window_days",
+ ty: TypeSchema::U64,
+ comment: "Restrict the global/dense branch to the last N days.",
+ required: false,
+ },
+ FieldSchema {
+ name: "max_hops",
+ ty: TypeSchema::U64,
+ comment: "Entity-graph relatedness hop threshold. Default 2.",
+ required: false,
+ },
+ ],
+ outputs: vec![
+ FieldSchema {
+ name: "hits",
+ ty: TypeSchema::Array(Box::new(TypeSchema::Json)),
+ comment: "Ranked RetrievalHit evidence (node_id, content, \
+ entities, score, time range, ...).",
+ required: true,
+ },
+ FieldSchema {
+ name: "total",
+ ty: TypeSchema::U64,
+ comment: "Pre-truncation match count.",
+ required: true,
+ },
+ FieldSchema {
+ name: "truncated",
+ ty: TypeSchema::Bool,
+ comment: "True when total exceeds the returned hit count.",
+ required: true,
+ },
+ ],
+ }),
+ _ => None,
+ }
+}
diff --git a/src/openhuman/platform/about_app/catalog.rs b/src/openhuman/platform/about_app/catalog.rs
index b1a82391ea..9389e5a083 100644
--- a/src/openhuman/platform/about_app/catalog.rs
+++ b/src/openhuman/platform/about_app/catalog.rs
@@ -13,7 +13,7 @@ static VALIDATED: OnceLock<()> = OnceLock::new();
pub fn all_capabilities() -> &'static [Capability] {
ensure_validated();
- CAPABILITIES
+ CAPABILITIES.as_slice()
}
pub fn capabilities_by_category(category: CapabilityCategory) -> Vec<Capability> {
@@ -65,7 +65,7 @@ fn searchable_text(capability: &Capability) -> String {
fn ensure_validated() {
VALIDATED.get_or_init(|| {
let mut ids = BTreeSet::new();
- for capability in CAPABILITIES {
+ for capability in CAPABILITIES.iter() {
assert!(
!capability.id.trim().is_empty(),
"about_app capability id must not be empty"
diff --git a/src/openhuman/platform/about_app/catalog_data.rs b/src/openhuman/platform/about_app/catalog_data.rs
index 9407f06fc1..4619ee7928 100644
--- a/src/openhuman/platform/about_app/catalog_data.rs
+++ b/src/openhuman/platform/about_app/catalog_data.rs
@@ -140,1592 +140,20 @@ const EMBEDDING_PROBE_TO_CONFIGURED_PROVIDER: Option<CapabilityPrivacy> = Some(C
],
});
-pub(super) const CAPABILITIES: &[Capability] = &[
- Capability {
- id: "conversation.create",
- name: "Create Conversations",
- domain: "conversation",
- category: CapabilityCategory::Conversation,
- description: "Start a new conversation thread with the assistant.",
- how_to: "Conversations",
- status: CapabilityStatus::Stable,
- privacy: None,
- },
- Capability {
- id: "conversation.send_text",
- name: "Send Text Messages",
- domain: "conversation",
- category: CapabilityCategory::Conversation,
- description: "Send typed messages to the assistant in a conversation.",
- how_to: "Conversations > Message composer",
- status: CapabilityStatus::Stable,
- privacy: DERIVED_TO_BACKEND,
- },
- Capability {
- id: "conversation.prompt_injection_guard",
- name: "Prompt Injection Guard",
- domain: "conversation",
- category: CapabilityCategory::Conversation,
- description: "Detect and block prompt-injection attempts before agent/model execution.",
- how_to: "Conversations > Message composer",
- status: CapabilityStatus::Stable,
- privacy: DERIVED_TO_BACKEND,
- },
- Capability {
- id: "conversation.send_voice",
- name: "Send Voice Messages",
- domain: "conversation",
- category: CapabilityCategory::Conversation,
- description: "Record or attach voice input and send it as a message.",
- how_to: "Conversations > Voice input",
- status: CapabilityStatus::Beta,
- privacy: DERIVED_TO_BACKEND,
- },
- Capability {
- id: "voice.stt_engine",
- name: "Speech Recognition Engine",
- domain: "voice",
- category: CapabilityCategory::Conversation,
- description: "Choose which hosted engine transcribes your speech. \"Backend\" uses \
- OpenHuman's transcription proxy and needs no setup; ElevenLabs and OpenAI \
- call the provider directly with your own API key. Audio always leaves the \
- device — the bundled offline whisper.cpp engine was removed, so there is \
- no local option.",
- how_to: "Settings → Voice → Speech recognition engine",
- status: CapabilityStatus::Beta,
- privacy: DERIVED_TO_BACKEND,
- },
- Capability {
- id: "voice.ptt",
- name: "Global push-to-talk",
- domain: "voice",
- category: CapabilityCategory::Conversation,
- description: "Hold a global hotkey from anywhere on the desktop to dictate into the \
- active chat thread. Press opens the mic, release commits the transcript, \
- and an always-on-top overlay shows listening/idle state without stealing \
- focus. Cross-platform via tauri-plugin-global-shortcut (macOS, Windows, \
- Linux/X11); requires microphone access and a global shortcut binding. \
- Optional speak_reply plays the agent's response through local TTS.",
- how_to: "Settings → Voice → Push-to-Talk: pick a shortcut, grant microphone access, \
- then hold the configured hotkey from any window.",
- status: CapabilityStatus::Beta,
- privacy: DERIVED_TO_BACKEND,
- },
- Capability {
- id: "conversation.copy_messages",
- name: "Copy Messages",
- domain: "conversation",
- category: CapabilityCategory::Conversation,
- description: "Copy individual assistant or user messages for reuse elsewhere.",
- how_to: "Conversations > Message actions",
- status: CapabilityStatus::Stable,
- privacy: None,
- },
- Capability {
- id: "conversation.delete_conversations",
- name: "Delete Conversations",
- domain: "conversation",
- category: CapabilityCategory::Conversation,
- description: "Remove existing conversation threads from the app.",
- how_to: "Conversations > Thread actions",
- status: CapabilityStatus::Stable,
- privacy: None,
- },
- Capability {
- id: "conversation.terminal_chat",
- name: "Tabbed Terminal UI",
- domain: "tui",
- category: CapabilityCategory::Conversation,
- description: "Operate OpenHuman from a terminal through four tabs: live core logs, \
- orchestrator chat, safe configuration, and account settings. Bare \
- `openhuman` opens it on an interactive non-container host; `openhuman tui` \
- (alias `chat`) forces it. The chat streams replies, thinking, and tools live.",
- how_to: "Run `openhuman`, or `openhuman tui` to force the UI. Use Tab/Shift+Tab or Alt+1-4 \
- to switch Logs, Chat, Config, and Settings. `--thread <id>` resumes a chat and \
- `--new` starts one. Settings accepts a one-time login token and supports account \
- refresh and logout. Use `openhuman --no-tui` to suppress automatic launch.",
- status: CapabilityStatus::Beta,
- privacy: DERIVED_TO_BACKEND,
- },
- Capability {
- id: "conversation.suggested_questions",
- name: "Suggested Questions",
- domain: "conversation",
- category: CapabilityCategory::Conversation,
- description: "Offer prompt suggestions to help continue a conversation.",
- how_to: "Home or Conversations > Suggested prompts",
- status: CapabilityStatus::Beta,
- privacy: None,
- },
- Capability {
- id: "conversation.tool_execution_timeline",
- name: "Tool Execution Timeline",
- domain: "conversation",
- category: CapabilityCategory::Conversation,
- description: "Show the sequence of tool calls and actions used to answer a request.",
- how_to: "Conversations > Tool timeline",
- status: CapabilityStatus::Beta,
- privacy: None,
- },
- Capability {
- id: "conversation.plan_review",
- name: "Plan Review",
- domain: "conversation",
- category: CapabilityCategory::Conversation,
- description: "Pause an interactive turn for review whenever the assistant proposes a thread-scoped plan (a multi-step to-do list with its objective). Review the whole plan once above the composer, then Approve to run it, Reject to discard it, or send feedback to have the assistant revise and re-propose — nothing executes until you approve. Background and scheduled runs are never gated.",
- how_to: "Conversations > review the plan card above the composer when the assistant lays out a multi-step plan",
- status: CapabilityStatus::Beta,
- privacy: None,
- },
- Capability {
- id: "conversation.subagent_mascots",
- name: "Subagent Mascots",
- domain: "conversation",
- category: CapabilityCategory::Conversation,
- description: "Show delegated sub-agents as colored mascots with compact activity bubbles and running, completed, or failed states.",
- how_to: "Human > ask the assistant to delegate work to sub-agents",
- status: CapabilityStatus::Beta,
- privacy: None,
- },
- Capability {
- id: "intelligence.vision_subagent",
- name: "Vision Sub-agent",
- domain: "agent",
- category: CapabilityCategory::Intelligence,
- description: "Delegate image / screenshot understanding to a dedicated vision sub-agent — describe, OCR, read charts/diagrams, compare images, or locate UI elements. Rides the multimodal `vision-v1` tier so attached images are always analyzed.",
- how_to: "Attach an image in chat, or ask the assistant to look at a screenshot / image file",
- status: CapabilityStatus::Beta,
- privacy: IMAGE_TO_BACKEND,
- },
- Capability {
- id: "intelligence.image_generation",
- name: "Image Generation",
- domain: "agent",
- category: CapabilityCategory::Intelligence,
- description: "Delegate image creation to a dedicated image sub-agent — generate images from a text prompt, or edit/restyle reference images, using hosted GMI models (Seedream / SeedEdit). Results are saved to the workspace.",
- how_to: "Ask the assistant to generate, draw, or edit an image",
- status: CapabilityStatus::Beta,
- privacy: MEDIA_GEN_TO_BACKEND,
- },
- Capability {
- id: "intelligence.video_generation",
- name: "Video Generation",
- domain: "agent",
- category: CapabilityCategory::Intelligence,
- description: "Delegate short-video creation to a dedicated video sub-agent — text-to-video or animate a reference image using hosted GMI models (Seedance / Veo). Generation is asynchronous; the finished clip is saved to the workspace.",
- how_to: "Ask the assistant to generate a video or animate an image",
- status: CapabilityStatus::Beta,
- privacy: MEDIA_GEN_TO_BACKEND,
- },
- Capability {
- id: "conversation.label_filter",
- name: "Thread Label Filters",
- domain: "conversation",
- category: CapabilityCategory::Conversation,
- description: "Filter the thread list by label (Work, Briefing, Notification) using the tab bar at the top of the thread list.",
- how_to: "Conversations > Label tabs",
- status: CapabilityStatus::Beta,
- privacy: None,
- },
- Capability {
- id: "intelligence.analyze_actionable_items",
- name: "Analyze Actionable Items",
- domain: "intelligence",
- category: CapabilityCategory::Intelligence,
- description: "Extract and summarize actionable items from your activity and conversations.",
- how_to: "Intelligence",
- status: CapabilityStatus::Stable,
- privacy: DERIVED_TO_BACKEND,
- },
- Capability {
- id: "intelligence.filter_actionable_items",
- name: "Filter Actionable Items",
- domain: "intelligence",
- category: CapabilityCategory::Intelligence,
- description: "Search and filter actionable items to focus on what matters now.",
- how_to: "Intelligence > Filters and search",
- status: CapabilityStatus::Stable,
- privacy: None,
- },
- Capability {
- id: "intelligence.mark_actionable_item_complete",
- name: "Mark Items Complete",
- domain: "intelligence",
- category: CapabilityCategory::Intelligence,
- description: "Mark an actionable item as completed.",
- how_to: "Intelligence > Item actions",
- status: CapabilityStatus::Stable,
- privacy: None,
- },
- Capability {
- id: "intelligence.dismiss_actionable_item",
- name: "Dismiss Items",
- domain: "intelligence",
- category: CapabilityCategory::Intelligence,
- description: "Dismiss irrelevant or already handled actionable items.",
- how_to: "Intelligence > Item actions",
- status: CapabilityStatus::Stable,
- privacy: None,
- },
- Capability {
- id: "intelligence.snooze_actionable_item",
- name: "Snooze Items",
- domain: "intelligence",
- category: CapabilityCategory::Intelligence,
- description: "Temporarily hide an actionable item until later.",
- how_to: "Intelligence > Item actions",
- status: CapabilityStatus::Stable,
- privacy: None,
- },
- Capability {
- id: "intelligence.undo_action",
- name: "Undo Item Actions",
- domain: "intelligence",
- category: CapabilityCategory::Intelligence,
- description: "Undo a recent complete, dismiss, or snooze action.",
- how_to: "Intelligence > Undo snackbar or item history",
- status: CapabilityStatus::Beta,
- privacy: None,
- },
- Capability {
- id: "intelligence.agentmemory_backend",
- name: "agentmemory Memory Backend",
- domain: "intelligence",
- category: CapabilityCategory::Intelligence,
- description: "Opt-in Memory trait backend that delegates every store/recall/get/list/forget \
- call to a locally-running agentmemory REST server. Selected via \
- `memory.backend = \"agentmemory\"` in config.toml. Allows users who self-host \
- agentmemory across Claude Code, Cursor, Codex, and OpenCode to share a single durable \
- memory store. Default backend remains sqlite; selecting agentmemory is non-breaking.",
- how_to: "Set `memory.backend = \"agentmemory\"` in config.toml. \
- See gitbooks/features/obsidian-wiki/agentmemory-backend.md for setup and config keys.",
- status: CapabilityStatus::Beta,
- privacy: LOCAL_RAW,
- },
- Capability {
- id: "intelligence.memory_workspace",
- name: "Memory Workspace",
- domain: "intelligence",
- category: CapabilityCategory::Intelligence,
- description: "Inspect or debug the app's memory workspace and stored knowledge.",
- how_to: "Settings > Memory Debug",
- status: CapabilityStatus::Beta,
- privacy: None,
- },
- Capability {
- id: "intelligence.agents_md_instructions",
- name: "AGENTS.md Project Instructions",
- domain: "intelligence",
- category: CapabilityCategory::Intelligence,
- description: "Load configurable standing instructions from AGENTS.md files into the agent's \
- system prompt — OpenHuman's analog of Claude Code's CLAUDE.md / Codex's AGENTS.md. Two \
- layers are read once at session start: a global layer from the OpenHuman workspace \
- (<workspace_dir>/AGENTS.md) and a project layer from the folder the agent is operating \
- in (<action_dir>/AGENTS.md, or a sub-agent's isolated worktree). The global layer is \
- injected first, the project layer second (project instructions take precedence). \
- Missing or empty files are silently skipped, and each layer is capped so a large file \
- can't crowd out the rest of the prompt. On by default; disable via \
- `agent.agents_md_enabled = false`.",
- how_to: "Create an AGENTS.md file in your OpenHuman workspace and/or your project's action \
- directory. Toggle off with `agent.agents_md_enabled = false` in config.toml.",
- status: CapabilityStatus::Stable,
- privacy: AGENTS_MD_TO_INFERENCE_PROVIDER,
- },
- Capability {
- id: "intelligence.tool_scoped_memory",
- name: "Tool-Scoped Memory Rules",
- domain: "intelligence",
- category: CapabilityCategory::Intelligence,
- description: "Store durable, tool-specific rules and corrections that survive context \
- compression. Critical-priority rules (e.g. 'never email Sarah') are pinned into the \
- system prompt at session start. Captured automatically from user edicts and repeated \
- tool failures; also writable programmatically via the memory.tool_rule_* RPC surface.",
- how_to: "Automatic — user edicts are captured after every turn. Manage via \
- memory.tool_rule_put / memory.tool_rule_list / memory.tool_rule_delete (RPC).",
- status: CapabilityStatus::Beta,
- privacy: LOCAL_RAW,
- },
- Capability {
- id: "intelligence.long_term_goals",
- name: "Long-term Goals",
- domain: "intelligence",
- category: CapabilityCategory::Intelligence,
- description: "An editable list of the assistant's durable long-term goals for working with \
- you, stored locally in MEMORY_GOALS.md (capped ~500 tokens). A background goals agent \
- keeps the list fresh: it runs when the conversation context is summarized, and on first \
- run populates initial goals from context. Items can be added/edited/deleted explicitly \
- via RPC or agent tools.",
- how_to: "Automatic — refreshed on context summarization. Manage via \
- memory_goals.list / memory_goals.add / memory_goals.edit / memory_goals.delete / \
- memory_goals.reflect (RPC), or the goals_* agent tools.",
- status: CapabilityStatus::Beta,
- // Enrichment runs a cloud agentic model, so goal/context text can leave
- // the device during a reflect pass (CRUD/storage stays local).
- privacy: DERIVED_TO_BACKEND,
- },
- Capability {
- id: "conversation.thread_goal",
- name: "Thread Goal",
- domain: "conversation",
- category: CapabilityCategory::Conversation,
- description: "A single, thread-scoped goal (Codex-style \"completion contract\") the \
- assistant keeps pursuing across turns, interrupts, resumes, and budget boundaries — \
- distinct from the long-term goals list and the per-thread task board. Stored locally \
- (one goal per thread), with a lifecycle (active/paused/budget_limited/complete) and an \
- optional token budget. The active goal is injected into context each turn; the context \
- scout proposes a goal on a fresh thread (only if none is set) and the orchestrator can \
- set/refine it. When enabled, idle threads can autonomously continue toward the goal.",
- how_to: "Set/edit via the goal chip above the composer in Conversations, or the \
- thread_goals.* RPC (get/set/complete/pause/resume/clear); the assistant manages it via \
- the goal_set / goal_get / goal_complete tools. Autonomous continuation is opt-in via \
- heartbeat.goal_continuation_enabled.",
- status: CapabilityStatus::Beta,
- // Goal CRUD/storage is local; autonomous continuation (opt-in) runs a
- // cloud agentic model, so objective/context can leave the device then.
- privacy: DERIVED_TO_BACKEND,
- },
- Capability {
- id: "intelligence.memory_tree_retrieval",
- name: "Memory Tree Retrieval (chat)",
- domain: "intelligence",
- category: CapabilityCategory::Intelligence,
- description: "Ask questions about your ingested email/chat/document memory in chat. The orchestrator can resolve names to canonical ids, query summaries by source/topic/global window, drill into details, and cite raw chunks.",
- how_to: "Chat > ask the assistant about people, conversations, or windows",
- status: CapabilityStatus::Beta,
- privacy: LOCAL_RAW,
- },
- Capability {
- id: "intelligence.memory_pipeline_doctor",
- name: "Memory Pipeline Doctor",
- domain: "intelligence",
- category: CapabilityCategory::Intelligence,
- description: "Diagnose why the memory tree / wiki is empty or stalled. Walks each pipeline stage (embeddings config, scheduler gate, job queue, extraction/recall degradation, summary-tree precondition) and reports the single first blocking cause with an actionable fix, plus counters and extraction coverage. The agent can run it on itself; a typed 'first blocking cause' is surfaced in the Memory status panel, and jobs that failed under a now-fixed config can be requeued on demand via the `memory_tree_retry_failed` RPC.",
- how_to: "Memory status panel shows the cause + fix; or ask the agent to diagnose memory; or `openhuman-core` RPC `memory_tree_doctor`",
- status: CapabilityStatus::Beta,
- privacy: LOCAL_RAW,
- },
- Capability {
- id: "intelligence.github_repo_memory_source",
- name: "GitHub Repo Memory Source",
- domain: "memory_sources",
- category: CapabilityCategory::Intelligence,
- description: "Sync a GitHub repository's project activity — commits, issues, and \
- pull requests (not source code) — into your memory. Items are archived verbatim \
- under a browsable, repo-grouped vault layout \
- (raw/github-com-<owner>-<repo>/{commits,issues,prs}/) and ingested into the \
- memory tree for recall. Contributors are surfaced as @handle entities, and \
- commit messages plus closed/merged issues & PRs get a priority boost so \
- high-signal history leads at summary time. Pulls up to 2000 items of each type \
- per sync by default, overridable per source via max_commits / max_issues / \
- max_prs.",
- how_to: "Settings > Memory & Data > Memory Sources — add a GitHub repository URL. \
- Programmatic: openhuman.memory_sources_add (RPC).",
- status: CapabilityStatus::Beta,
- privacy: GITHUB_REPO_SOURCE,
- },
- Capability {
- id: "intelligence.memory_source_sync_controls",
- name: "Memory Source Sync Defaults & Controls",
- domain: "memory_sources",
- category: CapabilityCategory::Intelligence,
- description: "Connected memory sources are enabled by default with conservative, \
- per-kind sync caps so the first sync stays cheap (e.g. Gmail ~100 recent emails, \
- GitHub repo 10 PRs / 10 issues / 50 commits, RSS 20 items). Each source row exposes \
- an inline settings panel to adjust the limit fields that apply to its kind \
- (max_items, sync_depth_days, max_prs/issues/commits, since_days). \
- An \"All In\" action enables every source and removes the caps to build the richest \
- memory graph, then triggers a full sync. Already-connected sources are migrated to \
- the new defaults once.",
- how_to: "Intelligence > Memory Sources — toggle a source, open its gear for per-source \
- limits, or use \"All In\". Programmatic: openhuman.memory_sources_update and \
- openhuman.memory_sources_apply_all_in (RPC).",
- status: CapabilityStatus::Beta,
- privacy: LOCAL_RAW,
- },
- Capability {
- id: "intelligence.coding_session_memory",
- name: "Coding-Agent Session Memory",
- domain: "memory_sources",
- category: CapabilityCategory::Intelligence,
- description: "Discover local Codex and Claude Code session histories, retain only human-authored decisions and corrections, and distill them into a durable TinyCortex persona memory pack. Tool output, reasoning, developer prompts, and subagent traffic are excluded before inference.",
- how_to: "Brain > Sources > Coding-agent sessions > Ingest new sessions. Programmatic: openhuman.memory_sources_coding_session_status and openhuman.memory_sources_ingest_coding_sessions (RPC).",
- status: CapabilityStatus::Beta,
- privacy: CODING_SESSION_TO_BACKEND,
- },
- Capability {
- id: "intelligence.memory_sync_schedule",
- name: "Memory Sync Schedule",
- domain: "config",
- category: CapabilityCategory::Intelligence,
- description: "Pick a single global cadence for how often all opted-in memory sources \
- auto-sync, presented like a backup schedule (\"Last synced … · Sync every …\"). \
- Presets are every 4h / 12h / 24h, plus \"Manual only\" which disables background \
- auto-sync entirely (you can still sync on demand). The chosen interval overrides each \
- provider's built-in cadence but is floored at it, so syncs never run more often than \
- the provider intends — handy for keeping credit spend predictable. Unset defaults to \
- every 24h.",
- how_to: "Intelligence > Memory Sources — choose a Sync every… preset or Manual only. \
- Programmatic: openhuman.config_get_memory_sync_settings / \
- openhuman.config_update_memory_sync_settings (RPC); ops override via the \
- OPENHUMAN_MEMORY_SYNC_INTERVAL_SECS env var (0 = manual).",
- status: CapabilityStatus::Beta,
- privacy: LOCAL_RAW,
- },
- Capability {
- id: "intelligence.embedding_provider_config",
- name: "Configure Embedding Provider",
- domain: "embeddings",
- category: CapabilityCategory::Intelligence,
- description:
- "Pick which embedding provider drives semantic search across your memory: \
- managed cloud (default, Voyage-backed via api.tinyhumans.ai), OpenAI, \
- Cohere, local Ollama, or a custom OpenAI-compatible endpoint. API keys \
- are stored encrypted via the local keyring under `embeddings:<slug>`; \
- model name and embedding dimensions are tunable per provider. The \
- legacy `inference_embed` RPC is aliased to `embeddings_embed` so \
- existing callers continue to work.",
- how_to: "Connections → API keys → Embeddings",
- status: CapabilityStatus::Beta,
- // Privacy depends on the selected provider — see
- // `intelligence.embedding_provider_test` for the per-provider data
- // destinations. The configuration surface itself only writes to the
- // local keyring and config, so leaving this `None` (treat-as-unknown)
- // would under-report; we annotate the credential side here and the
- // network side on the test action.
- privacy: LOCAL_CREDENTIALS,
- },
- Capability {
- id: "intelligence.embedding_provider_test",
- name: "Test Embedding Provider",
- domain: "embeddings",
- category: CapabilityCategory::Intelligence,
- description:
- "Verify a configured embedding provider before committing it to \
- memory ingestion. Sends a small one-shot embed request and reports \
- the model, dimensions, and any auth/error surface so a \
- misconfigured key doesn't get discovered halfway through a 50k \
- chunk backfill.",
- how_to: "Connections → API keys → Embeddings → Test Connection",
- // The probe payload routes to whichever provider the user has
- // selected — managed cloud (default), OpenAI, Cohere, or a custom
- // OpenAI-compatible endpoint. Using `DERIVED_TO_BACKEND` here would
- // under-report by only listing the managed path; the dedicated
- // constant enumerates every reachable destination so the Privacy
- // surface renders the full set.
- status: CapabilityStatus::Beta,
- privacy: EMBEDDING_PROBE_TO_CONFIGURED_PROVIDER,
- },
- Capability {
- id: "intelligence.mcp_server",
- name: "MCP Server",
- domain: "intelligence",
- category: CapabilityCategory::Intelligence,
- description: "Expose a curated OpenHuman tool surface over stdio MCP or Streamable HTTP/SSE for MCP-compatible clients.",
- how_to: "Run `openhuman-core mcp` (stdio) or `openhuman-core mcp --transport http --port 9300` for remote clients.",
- status: CapabilityStatus::Beta,
- privacy: LOCAL_RAW,
- },
- Capability {
- id: "intelligence.searxng_search",
- name: "SearXNG Search",
- domain: "intelligence",
- category: CapabilityCategory::Intelligence,
- description: "Search a configured self-hosted SearXNG instance from agent and MCP tools, returning normalized title, URL, snippet, and source results.",
- how_to: "Set `[searxng] enabled = true` and `base_url` in config.toml, or use OPENHUMAN_SEARXNG_* environment variables.",
- status: CapabilityStatus::Beta,
- privacy: SEARXNG_RAW_TO_CONFIGURED_INSTANCE,
- },
- Capability {
- id: "intelligence.tool_registry",
- name: "Tool Registry",
- domain: "intelligence",
- category: CapabilityCategory::Intelligence,
- description: "Discover OpenHuman's MCP stdio tools and controller-backed tools from one local registry, including versions, routes, input/output schemas, allowed agents, and health state.",
- how_to: "Call openhuman.tool_registry_list over core JSON-RPC, or openhuman.tool_registry_get with a tool_id such as memory.search.",
- status: CapabilityStatus::Beta,
- privacy: LOCAL_RAW,
- },
- Capability {
- id: "intelligence.orchestrator_worker_thread",
- name: "Worker Thread Delegation",
- domain: "intelligence",
- category: CapabilityCategory::Intelligence,
- description: "When a delegated sub-task is long or complex, the orchestrator can route it into a fresh worker-labeled conversation thread instead of flooding the parent thread. The user opens the worker thread from the thread list (or via the reference card in the parent) to read the sub-agent's full transcript.",
- how_to: "Conversations > tap the worker reference card in the parent thread, or open the worker-labeled thread from the thread list",
- status: CapabilityStatus::Beta,
- privacy: DERIVED_TO_BACKEND,
- },
- Capability {
- id: "intelligence.workflow_orchestration",
- name: "Workflow Orchestration",
- domain: "workflow_runs",
- category: CapabilityCategory::Intelligence,
- description: "Run declarative multi-agent workflows such as parallel research with cross-checking: a question is decomposed into angles, researched in parallel, adversarially cross-checked, and synthesized into one cited report. Watch each phase progress with its child agent results, stop or resume a run, and read the final synthesis. High-cost / high-concurrency runs require explicit approval before starting.",
- how_to: "Intelligence > Orchestration > pick a workflow and Start",
- status: CapabilityStatus::Beta,
- privacy: DERIVED_TO_BACKEND,
- },
- Capability {
- id: "intelligence.agent_library",
- name: "Agents Library",
- domain: "intelligence",
- category: CapabilityCategory::Intelligence,
- description: "Browse safe display metadata for registered agent definitions, compare worker capabilities, and start a one-off task with an explicitly selected agent.",
- how_to: "Intelligence > Agent Tasks > Agents Library",
- status: CapabilityStatus::Beta,
- privacy: DERIVED_TO_BACKEND,
- },
- Capability {
- id: "intelligence.worktree_manager",
- name: "Agent Worktrees",
- domain: "intelligence",
- category: CapabilityCategory::Intelligence,
- description: "Inspect and clean up the isolated git worktrees that parallel sub-agents check out under <repo>/.claude/worktrees. Each row shows the worktree's branch, dirty state, and changed files, plus a cross-worktree overlap warning when two workers touched the same file. Open, diff, or remove a worktree (a dirty worktree requires an explicit discard confirmation; the worker branch is preserved).",
- how_to: "Intelligence > Worktrees",
- status: CapabilityStatus::Beta,
- privacy: None,
- },
- Capability {
- id: "intelligence.slack_memory_ingest",
- name: "Slack Memory Ingestion",
- domain: "intelligence",
- category: CapabilityCategory::Intelligence,
- description: "Backfill the last 6 days of Slack history into the memory tree and keep it up to date by flushing each closed 6-hour UTC bucket. Driven by an authenticated Slack connection (OAuth via Composio).",
- how_to: "Connections > OAuth > Slack",
- status: CapabilityStatus::Beta,
- privacy: LOCAL_RAW,
- },
- Capability {
- id: "intelligence.clickup_memory_ingest",
- name: "ClickUp Memory Ingestion",
- domain: "intelligence",
- category: CapabilityCategory::Intelligence,
- description: "Incrementally sync ClickUp tasks assigned to the authenticated user into the Memory Tree on a 30-minute cadence, with an initial backfill on first connect. Only tasks the user is directly assigned to are ingested. Driven by an authenticated ClickUp connection (OAuth via Composio).",
- how_to: "Connections > OAuth > ClickUp",
- status: CapabilityStatus::Beta,
- privacy: LOCAL_RAW,
- },
- Capability {
- id: "intelligence.notifications_dismiss",
- name: "Dismiss Notifications",
- domain: "intelligence",
- category: CapabilityCategory::Intelligence,
- description: "Dismiss low-value notifications from the intelligence inbox.",
- how_to: "Notifications > Item actions",
- status: CapabilityStatus::Beta,
- privacy: None,
- },
- Capability {
- id: "intelligence.notifications_mark_acted",
- name: "Mark Notifications Acted",
- domain: "intelligence",
- category: CapabilityCategory::Intelligence,
- description: "Mark a notification as acted upon after taking follow-up action.",
- how_to: "Notifications > Item actions",
- status: CapabilityStatus::Beta,
- privacy: None,
- },
- Capability {
- id: "intelligence.notifications_stats",
- name: "View Notification Stats",
- domain: "intelligence",
- category: CapabilityCategory::Intelligence,
- description: "View aggregate unread, unscored, and provider/action notification stats.",
- how_to: "Notifications > Summary cards",
- status: CapabilityStatus::Beta,
- privacy: None,
- },
- Capability {
- id: "workflows.discover",
- name: "Discover Workflows",
- domain: "workflows",
- category: CapabilityCategory::Workflows,
- description: "Browse available workflows that can extend the app.",
- how_to: "Intelligence > Workflows",
- status: CapabilityStatus::Stable,
- privacy: None,
- },
- Capability {
- id: "workflows.install",
- name: "Install Workflows",
- domain: "workflows",
- category: CapabilityCategory::Workflows,
- description: "Install a workflow into the local workspace.",
- how_to: "Intelligence > Workflows > Install",
- status: CapabilityStatus::Stable,
- privacy: None,
- },
- Capability {
- id: "workflows.configure",
- name: "Configure Workflows",
- domain: "workflows",
- category: CapabilityCategory::Workflows,
- description: "Open workflow setup and update workflow-specific configuration.",
- how_to: "Intelligence > Workflows > Setup or Connections",
- status: CapabilityStatus::Stable,
- privacy: None,
- },
- Capability {
- id: "workflows.connection_status",
- name: "Monitor Workflow Connection Status",
- domain: "workflows",
- category: CapabilityCategory::Workflows,
- description: "See whether a workflow-backed integration is connected, offline, or needs setup.",
- how_to: "Intelligence > Workflows or Connections",
- status: CapabilityStatus::Beta,
- privacy: None,
- },
- Capability {
- id: "workflows.sync_manual",
- name: "Manually Sync Workflow Data",
- domain: "workflows",
- category: CapabilityCategory::Workflows,
- description: "Trigger a manual data sync for a workflow integration.",
- how_to: "Intelligence > Workflows > Workflow card > Sync",
- status: CapabilityStatus::Beta,
- privacy: DERIVED_TO_BACKEND,
- },
- Capability {
- id: "workflows.tinyfish_web_automation",
- name: "TinyFish Web Automation",
- domain: "workflows",
- category: CapabilityCategory::Workflows,
- description:
- "Search the web, render JavaScript-heavy pages, and run goal-based browser automations through TinyFish.",
- how_to: "Conversations > Ask the assistant to search, fetch, or automate a website with TinyFish",
- status: CapabilityStatus::Beta,
- privacy: DERIVED_TO_BACKEND,
- },
- Capability {
- id: "workflows.toggle_enabled",
- name: "Enable or Disable Workflows",
- domain: "workflows",
- category: CapabilityCategory::Workflows,
- description: "Turn individual workflows on or off without uninstalling them.",
- how_to: "Settings > Developer Options > Workflows",
- status: CapabilityStatus::Stable,
- privacy: None,
- },
- Capability {
- id: "workflows.open_connections_hub",
- name: "Open Connections Hub",
- domain: "workflows",
- category: CapabilityCategory::Workflows,
- description: "Browse the dedicated connections hub for external workflow-backed integrations.",
- how_to: "Connections",
- status: CapabilityStatus::Beta,
- privacy: None,
- },
- // ── Composio direct mode (BYO API key) ──────────────────────────
- //
- // Composio shipped with two integration paths:
- // 1. Backend-proxied (default) — calls through api.tinyhumans.ai;
- // backend owns the Composio API key, billing, allowlist, and
- // HMAC-verified trigger fan-out via socket.io.
- // 2. Direct (BYO key) — core calls backend.composio.dev directly
- // with the user's own key. Sovereign / offline-friendly, but
- // tool execution only — real-time trigger webhooks are NOT
- // routed in direct mode (they still require the backend).
- Capability {
- id: "composio.direct_mode",
- name: "Composio Direct Mode (BYO API Key)",
- domain: "workflows",
- category: CapabilityCategory::Workflows,
- description:
- "Route Composio tool calls directly to backend.composio.dev with your own API key, \
- bypassing the OpenHuman backend proxy. Tool execution only — trigger webhooks still \
- require backend mode.",
- how_to: "Settings > Skills > Composio > Direct mode",
- status: CapabilityStatus::Beta,
- privacy: COMPOSIO_DIRECT_CREDENTIALS,
- },
- Capability {
- id: "composio.direct_mode_triggers_gap",
- name: "Composio Triggers (Direct Mode — Limited)",
- domain: "workflows",
- category: CapabilityCategory::Workflows,
- description:
- "Composio real-time trigger webhooks (Gmail new-message, Slack new-message, …) \
- currently arrive over wss://api.tinyhumans.ai/socket.io and require backend mode. \
- Direct-mode users get synchronous tool execution but not async trigger push in \
- this release.",
- how_to: "Switch to Backend mode to receive triggers, or wait for the direct trigger sink follow-up",
- status: CapabilityStatus::ComingSoon,
- privacy: None,
- },
- Capability {
- id: "workflows.connect_google",
- name: "Connect Google",
- domain: "workflows",
- category: CapabilityCategory::Workflows,
- description: "Connect Google services for email, contacts, and calendar workflows.",
- how_to: "Connections > OAuth",
- status: CapabilityStatus::ComingSoon,
- privacy: LOCAL_CREDENTIALS,
- },
- Capability {
- id: "workflows.connect_notion",
- name: "Connect Notion",
- domain: "workflows",
- category: CapabilityCategory::Workflows,
- description: "Connect Notion for workspace sync and productivity workflows.",
- how_to: "Connections > OAuth",
- status: CapabilityStatus::ComingSoon,
- privacy: LOCAL_CREDENTIALS,
- },
- Capability {
- id: "workflows.connect_web3_wallet",
- name: "Connect Web3 Wallet",
- domain: "workflows",
- category: CapabilityCategory::Workflows,
- description: "Set up local EVM, BTC, Solana, and Tron wallet identities from one recovery phrase.",
- how_to: "Settings > Crypto > Recovery Phrase or Connections",
- status: CapabilityStatus::Beta,
- privacy: LOCAL_CREDENTIALS,
- },
- Capability {
- id: "workflows.wallet_execution",
- name: "Wallet Execution Tools",
- domain: "wallet",
- category: CapabilityCategory::Workflows,
- description: "Read addresses and balances, prepare/confirm/execute native + token transfers (ERC20/SPL/TRC20/BEP20), and inspect transactions (status, receipt, lookup) across the connected wallet (EVM, BTC, Solana, Tron). Quote-first; signing stays local.",
- how_to: "Use wallet.* RPC methods (balances, prepare_transfer, execute_prepared, tx_status, tx_receipt, lookup_tx) via the agent or core_rpc_relay, or via Settings > Crypto > Wallet Balances.",
- status: CapabilityStatus::Beta,
- privacy: LOCAL_CREDENTIALS,
- },
- Capability {
- id: "workflows.web3_defi",
- name: "Web3 Swaps & Bridges",
- domain: "web3",
- category: CapabilityCategory::Workflows,
- description: "Quote and execute cross-chain swaps and bridges (deBridge) plus generic EVM dapp contract calls, built on the local wallet's signing. EVM/Solana(/BTC); signing stays local.",
- how_to: "Use web3_swap.* / web3_bridge.* / web3_dapp.* RPC methods (quote/execute, web3_swap.routes) via the agent or core_rpc_relay.",
- status: CapabilityStatus::Beta,
- privacy: LOCAL_CREDENTIALS,
- },
- Capability {
- id: "workflows.x402_payments",
- name: "x402 Machine Payments",
- domain: "x402",
- category: CapabilityCategory::Workflows,
- description: "Automatic HTTP 402 payment handling for machine-payable APIs via the x402 protocol. When an API returns 402 Payment Required, the agent pays with USDC on Solana using the local wallet and retries. Budget enforcement with per-request, daily, and monthly caps.",
- how_to: "Use x402.* RPC methods (get_summary, list_payments, update_budget) to manage spending. Payments happen automatically when the http_request tool encounters a 402 with a PAYMENT-REQUIRED header.",
- status: CapabilityStatus::Beta,
- privacy: LOCAL_CREDENTIALS,
- },
- Capability {
- id: "workflows.connect_crypto_exchange",
- name: "Connect Crypto Exchange",
- domain: "workflows",
- category: CapabilityCategory::Workflows,
- description: "Connect supported exchanges for trading and portfolio workflows.",
- how_to: "Connections",
- status: CapabilityStatus::ComingSoon,
- privacy: None,
- },
- Capability {
- id: "local_ai.download_model",
- name: "Download Local Models",
- domain: "local_ai",
- category: CapabilityCategory::LocalAI,
- description: "Download and bootstrap local AI runtimes and model bundles.",
- how_to: "Settings > Local AI Model",
- status: CapabilityStatus::Beta,
- privacy: MODEL_DOWNLOAD,
- },
- Capability {
- id: "local_ai.configure_provider",
- name: "Configure Local Provider",
- domain: "local_ai",
- category: CapabilityCategory::LocalAI,
- description: "Select Ollama, LM Studio, MLX, or a generic local OpenAI-compatible server as the local model provider and configure the endpoint.",
- how_to: "Connections → API keys → LLM, or use provider strings: ollama:<model>, lmstudio:<model>, mlx:<model>, local-openai:<model>",
- status: CapabilityStatus::Beta,
- privacy: None,
- },
- Capability {
- id: "local_ai.manage_model_assets",
- name: "Manage Model Assets",
- domain: "local_ai",
- category: CapabilityCategory::LocalAI,
- description: "Inspect asset status and download specific chat, vision, embedding, STT, or TTS assets.",
- how_to: "Settings > Local AI Model > Advanced > Capability Assets",
- status: CapabilityStatus::Beta,
- privacy: None,
- },
- Capability {
- id: "local_ai.model_context_check",
- name: "Model Context Requirement Check",
- domain: "local_ai",
- category: CapabilityCategory::LocalAI,
- description: "Diagnostics report each installed Ollama model's native context window and reject any model below the minimum the memory layer requires (so short-context models can't silently truncate and corrupt recall).",
- how_to: "Settings > Local AI Model > Run Diagnostics",
- status: CapabilityStatus::Beta,
- privacy: None,
- },
- Capability {
- id: "local_ai.embed_text",
- name: "Generate Text Embeddings",
- domain: "local_ai",
- category: CapabilityCategory::LocalAI,
- description: "Create local vector embeddings for text input.",
- how_to: "Settings > Local AI Model > Advanced > Test Embeddings",
- status: CapabilityStatus::Beta,
- privacy: LOCAL_RAW,
- },
- Capability {
- id: "local_ai.text_to_speech",
- name: "Text to Speech (Local)",
- domain: "local_ai",
- category: CapabilityCategory::LocalAI,
- description:
- "Synthesize speech locally with Piper via the voice TTS factory. PIPER_BIN points \
- at the binary; the voice .onnx ships with the installer. Returns a synthetic \
- viseme timeline (full forced-alignment lives behind the cloud provider for now).",
- how_to: "Settings > Voice > TTS Provider = Piper",
- status: CapabilityStatus::Beta,
- privacy: None,
- },
- Capability {
- id: "local_ai.vision_processing",
- name: "Vision Processing",
- domain: "local_ai",
- category: CapabilityCategory::LocalAI,
- description: "Run vision prompts against images using a local multimodal model.",
- how_to: "Settings > Local AI Model > Advanced > Test Vision Prompt",
- status: CapabilityStatus::Beta,
- privacy: None,
- },
- Capability {
- id: "local_ai.direct_prompting",
- name: "Direct Model Prompting",
- domain: "local_ai",
- category: CapabilityCategory::LocalAI,
- description: "Send a direct prompt to the local model without using the cloud API.",
- how_to: "Settings > Local AI Model > Advanced > Test Custom Prompt",
- status: CapabilityStatus::Beta,
- privacy: None,
- },
- Capability {
- id: "local_ai.piper_installer",
- name: "Piper Installer (Local TTS)",
- domain: "local_ai",
- category: CapabilityCategory::LocalAI,
- description:
- "One-click download of the Piper binary archive and the bundled en_US-lessac-medium \
- voice (.onnx + .onnx.json) into the workspace so local Text-to-Speech runs without \
- manual setup. Atomic rename guarantees no half-written voice files are ever read \
- by the runtime.",
- how_to: "Settings > Voice > Voice Providers > Install Piper",
- status: CapabilityStatus::Beta,
- privacy: MODEL_DOWNLOAD,
- },
- Capability {
- id: "local_ai.python_runtime_installer",
- name: "Managed Python Runtime",
- domain: "runtime_python",
- category: CapabilityCategory::LocalAI,
- description:
- "Download and reuse an OpenHuman-managed CPython runtime for Python-backed local integrations such as MCP servers, with a system-Python override reserved for development.",
- how_to: "Configured by the core `runtime_python` module; future UI surfaces can expose install state and overrides.",
- status: CapabilityStatus::Beta,
- privacy: MODEL_DOWNLOAD,
- },
- Capability {
- id: "team.create",
- name: "Create Teams",
- domain: "team",
- category: CapabilityCategory::Team,
- description: "Create a team and start collaborating with shared billing and members.",
- how_to: "Settings > Team",
- status: CapabilityStatus::Stable,
- privacy: None,
- },
- Capability {
- id: "team.join_via_invite_code",
- name: "Join Teams via Invite Code",
- domain: "team",
- category: CapabilityCategory::Team,
- description: "Join an existing team using an invite code.",
- how_to: "Invites > Redeem an Invite Code",
- status: CapabilityStatus::Stable,
- privacy: None,
- },
- Capability {
- id: "team.switch_active_team",
- name: "Switch Active Team",
- domain: "team",
- category: CapabilityCategory::Team,
- description: "Switch which team is currently active in the app.",
- how_to: "Settings > Team",
- status: CapabilityStatus::Stable,
- privacy: None,
- },
- Capability {
- id: "team.leave",
- name: "Leave Teams",
- domain: "team",
- category: CapabilityCategory::Team,
- description: "Leave a team that you no longer want to participate in.",
- how_to: "Settings > Team",
- status: CapabilityStatus::Stable,
- privacy: None,
- },
- Capability {
- id: "team.manage_members",
- name: "Manage Team Members",
- domain: "team",
- category: CapabilityCategory::Team,
- description: "Review members and change team roles when you have permission.",
- how_to: "Settings > Team > Manage team > Members",
- status: CapabilityStatus::Stable,
- privacy: None,
- },
- Capability {
- id: "team.generate_invite_codes",
- name: "Generate Invite Codes",
- domain: "team",
- category: CapabilityCategory::Team,
- description: "Create invite codes to bring new members into a team.",
- how_to: "Settings > Team > Manage team > Invites",
- status: CapabilityStatus::Stable,
- privacy: None,
- },
- Capability {
- id: "team.track_invite_usage",
- name: "Track Invite Usage",
- domain: "team",
- category: CapabilityCategory::Team,
- description: "View invite usage counts, limits, and revoke team invites.",
- how_to: "Settings > Team > Manage team > Invites",
- status: CapabilityStatus::Stable,
- privacy: None,
- },
- Capability {
- id: "auth.login_oauth",
- name: "Login via OAuth",
- domain: "auth",
- category: CapabilityCategory::Auth,
- description: "Sign in with the app's supported provider-based authentication flow.",
- how_to: "Welcome",
- status: CapabilityStatus::Stable,
- privacy: None,
- },
- Capability {
- id: "auth.onboarding_setup",
- name: "Onboarding Setup",
- domain: "auth",
- category: CapabilityCategory::Auth,
- description: "Walk through onboarding to configure initial permissions and preferences.",
- how_to: "Onboarding",
- status: CapabilityStatus::Stable,
- privacy: None,
- },
- Capability {
- id: "auth.configure_tool_access",
- name: "Configure Tool Access",
- domain: "auth",
- category: CapabilityCategory::Auth,
- description: "Choose which built-in tools OpenHuman can use on your behalf during setup.",
- how_to: "Onboarding > Enable Tools",
- status: CapabilityStatus::Stable,
- privacy: None,
- },
- Capability {
- id: "auth.backup_recovery_phrase",
- name: "Back Up Recovery Phrase",
- domain: "auth",
- category: CapabilityCategory::Auth,
- description: "Generate and save a recovery phrase used to secure and restore encrypted app data.",
- how_to: "Onboarding > Recovery Phrase",
- status: CapabilityStatus::Stable,
- privacy: None,
- },
- Capability {
- id: "auth.import_recovery_phrase",
- name: "Import Recovery Phrase",
- domain: "auth",
- category: CapabilityCategory::Auth,
- description: "Import an existing recovery phrase to restore encrypted app data.",
- how_to: "Onboarding > Recovery Phrase > I already have a recovery phrase",
- status: CapabilityStatus::Stable,
- privacy: None,
- },
- Capability {
- id: "auth.logout",
- name: "Logout",
- domain: "auth",
- category: CapabilityCategory::Auth,
- description: "Sign out of the current session.",
- how_to: "Settings > Log out",
- status: CapabilityStatus::Stable,
- privacy: None,
- },
- Capability {
- id: "channels.connect_platform",
- name: "Connect Messaging Platforms",
- domain: "channels",
- category: CapabilityCategory::Channels,
- description: "Connect supported messaging platforms such as Telegram or Discord.",
- how_to: "Connections > Channels",
- status: CapabilityStatus::Beta,
- privacy: None,
- },
- Capability {
- id: "channels.telegram_remote_control",
- name: "Telegram Remote Control",
- domain: "channels",
- category: CapabilityCategory::Channels,
- description:
- "Operate OpenHuman from Telegram with slash commands: /status, /sessions, /new, and /help.",
- how_to: "Connections > Channels > Telegram (connect), then message the bot",
- status: CapabilityStatus::Beta,
- privacy: None,
- },
- Capability {
- id: "channels.disconnect_platform",
- name: "Disconnect Messaging Platforms",
- domain: "channels",
- category: CapabilityCategory::Channels,
- description: "Disconnect a previously configured messaging platform.",
- how_to: "Connections > Channels",
- status: CapabilityStatus::Beta,
- privacy: None,
- },
- Capability {
- id: "channels.test_credentials",
- name: "Test Channel Credentials",
- domain: "channels",
- category: CapabilityCategory::Channels,
- description: "Validate platform credentials or connection state before using a channel.",
- how_to: "Connections > Channels",
- status: CapabilityStatus::Beta,
- privacy: None,
- },
- Capability {
- id: "channels.set_default_channel",
- name: "Set Default Messaging Channel",
- domain: "channels",
- category: CapabilityCategory::Channels,
- description: "Choose which messaging channel should be used by default.",
- how_to: "Connections > Channels",
- status: CapabilityStatus::Beta,
- privacy: None,
- },
- Capability {
- id: "channels.whatsapp_read_messages",
- name: "Read WhatsApp Messages",
- domain: "channels",
- category: CapabilityCategory::Channels,
- description: "Read and search WhatsApp Web conversations and messages after connecting WhatsApp in OpenHuman. Data is stored locally only and never transmitted.",
- how_to: "Connect WhatsApp Web via Channels, then ask the agent to read or summarise your messages.",
- status: CapabilityStatus::Beta,
- privacy: LOCAL_RAW,
- },
- Capability {
- id: "channels.mcp_registry_browse",
- name: "Browse MCP Server Registry",
- domain: "channels",
- category: CapabilityCategory::Channels,
- description: "Search and discover MCP servers from the Smithery.ai and official modelcontextprotocol registries.",
- how_to: "Skills > MCP > Browse catalog",
- status: CapabilityStatus::Beta,
- privacy: Some(CapabilityPrivacy {
- leaves_device: true,
- data_kind: PrivacyDataKind::Metadata,
- destinations: &["Smithery.ai registry API", "modelcontextprotocol registry API"],
- }),
- },
- Capability {
- id: "channels.mcp_server_install",
- name: "Install MCP Servers",
- domain: "channels",
- category: CapabilityCategory::Channels,
- description: "Install MCP servers locally — both local stdio subprocesses and hosted HTTP-remote servers. Required env vars are stored encrypted and never included in logs or responses. Can also be done conversationally via the MCP setup assistant.",
- how_to: "Skills > MCP > Browse catalog > Install, or ask the assistant to \"set up the <name> MCP server\"",
- status: CapabilityStatus::Beta,
- privacy: LOCAL_CREDENTIALS,
- },
- Capability {
- id: "channels.mcp_server_connect",
- name: "Connect / Reconfigure MCP Servers",
- domain: "channels",
- category: CapabilityCategory::Channels,
- description: "Spawn and manage MCP server connections (stdio subprocess or HTTP-remote). Reconfigure stored env vars and reconnect without uninstalling.",
- how_to: "Skills > MCP > select a server > Connect / Reconfigure",
- status: CapabilityStatus::Beta,
- privacy: Some(CapabilityPrivacy {
- leaves_device: true,
- data_kind: PrivacyDataKind::Derived,
- destinations: &["Configured MCP endpoint(s)"],
- }),
- },
- Capability {
- id: "channels.mcp_tool_call",
- name: "Invoke MCP Server Tools",
- domain: "channels",
- category: CapabilityCategory::Channels,
- description: "Call tools exposed by connected MCP servers. Tools are surfaced to the agent and runnable from the tool playground.",
- how_to: "Skills > MCP > select a connected server > Tools > Try, or ask the assistant in Chat",
- status: CapabilityStatus::Beta,
- privacy: Some(CapabilityPrivacy {
- leaves_device: true,
- data_kind: PrivacyDataKind::Derived,
- destinations: &["Configured MCP endpoint(s)"],
- }),
- },
- Capability {
- id: "settings.configure_ai",
- name: "Configure AI",
- domain: "settings",
- category: CapabilityCategory::Settings,
- description: "Configure managed, local, custom, and built-in BYOK LLM providers, including SumoPod and other OpenAI-compatible gateways, plus per-workload routing preferences.",
- how_to: "Connections → API keys → LLM",
- status: CapabilityStatus::Stable,
- privacy: None,
- },
- Capability {
- id: "settings.core_connection",
- name: "Run the Core Somewhere Else",
- domain: "settings",
- category: CapabilityCategory::Settings,
- description: "Choose where the OpenHuman core runs: inside this app, at a URL \
- you point it at, in a Docker container, on another machine over SSH, or in a \
- container on another machine. OpenHuman starts the core, connects to it, and \
- shuts it down when you switch away. Where it runs and what contains it are \
- separate choices, so SSH and Docker combine without being a third option.",
- how_to: "Settings > Core connection",
- status: CapabilityStatus::Beta,
- privacy: Some(CapabilityPrivacy {
- leaves_device: true,
- data_kind: PrivacyDataKind::Raw,
- // `Raw`, because everything the core holds - the conversations
- // themselves, memory, stored credentials - lives wherever the core
- // runs. Choosing a machine over SSH is choosing to put all of it
- // there. That is the disclosure that matters here and the one a
- // hostname field makes easy to overlook, so it is stated at the
- // strongest kind rather than softened to `Derived`.
- destinations: &["The machine you configure, when the core runs off this device"],
- }),
- },
- Capability {
- id: "settings.persona_pack",
- name: "Persona Pack",
- domain: "settings",
- category: CapabilityCategory::Settings,
- description: "Personalize the assistant across one or more agent profiles: set a display name and description, edit or reset each profile's SOUL.md identity (kept in its own home under personalities/<id>/ and re-read every message), give a profile its own dedicated memory subtree or its own working directory, drop private skills under personalities/<id>/skills/ that only that profile can discover, attribute a scheduled cron job to a profile so it runs with that profile's identity, memory, and permissions, and reach mascot avatar and voice settings. Multiple profiles can run with isolated identity, memory, skills, and workspace state.",
- how_to: "Settings > Persona",
- status: CapabilityStatus::Beta,
- privacy: GITHUB_MASCOT_MANIFEST,
- },
- Capability {
- id: "settings.manage_privacy_analytics",
- name: "Manage Privacy and Analytics",
- domain: "settings",
- category: CapabilityCategory::Settings,
- description: "Control privacy, analytics, and related data handling preferences. \
- When enabled, anonymous crash reports are sent to Sentry and anonymous usage \
- analytics (page views, feature engagement) are sent to Google Analytics. \
- No personal data, messages, or credentials are ever included.",
- how_to: "Settings > Privacy (direct route)",
- status: CapabilityStatus::Stable,
- privacy: DIAGNOSTICS_TO_BACKEND,
- },
- Capability {
- id: "settings.view_billing",
- name: "View Billing",
- domain: "settings",
- category: CapabilityCategory::Settings,
- description: "Open subscription, included usage, and pay-as-you-go billing views for your active team.",
- how_to: "Settings > Billing & Usage",
- status: CapabilityStatus::Stable,
- privacy: None,
- },
- Capability {
- id: "settings.manage_subscription_plan",
- name: "Manage Subscription Plan",
- domain: "settings",
- category: CapabilityCategory::Settings,
- description: "Upgrade plans or open the billing portal to manage subscription-backed usage tiers.",
- how_to: "Settings > Billing & Usage",
- status: CapabilityStatus::Stable,
- privacy: None,
- },
- Capability {
- id: "settings.manage_credits",
- name: "Manage Credits",
- domain: "settings",
- category: CapabilityCategory::Settings,
- description: "View pay-as-you-go credit balances, top up overage credits, and configure auto-recharge.",
- how_to: "Settings > Billing & Usage",
- status: CapabilityStatus::Stable,
- privacy: None,
- },
- Capability {
- id: "settings.add_payment_methods",
- name: "Add Payment Methods",
- domain: "settings",
- category: CapabilityCategory::Settings,
- description: "Add or manage saved payment methods for billing and auto-recharge.",
- how_to: "Settings > Billing & Usage > Payment Methods",
- status: CapabilityStatus::Stable,
- privacy: None,
- },
- Capability {
- id: "settings.developer_options",
- name: "Developer Options",
- domain: "settings",
- category: CapabilityCategory::Settings,
- description: "Open developer-focused panels for diagnostics, workflows, AI config, and memory tools.",
- how_to: "Settings > Developer Options",
- status: CapabilityStatus::Beta,
- privacy: None,
- },
- Capability {
- id: "settings.debug_webhooks",
- name: "Debug Webhooks",
- domain: "settings",
- category: CapabilityCategory::Settings,
- description:
- "Inspect Composio trigger history and find the daily JSONL archive files stored by the app.",
- how_to: "Settings > Developer Options > Webhooks",
- status: CapabilityStatus::Beta,
- privacy: None,
- },
- Capability {
- id: "settings.manage_service",
- name: "Manage Desktop Service",
- domain: "settings",
- category: CapabilityCategory::Settings,
- description: "Install, start, stop, restart, uninstall, or inspect the optional desktop background service.",
- how_to: "Settings > Developer Options > Tauri Commands",
- status: CapabilityStatus::Stable,
- privacy: None,
- },
- Capability {
- id: "settings.clear_app_data",
- name: "Log Out and Clear App Data",
- domain: "settings",
- category: CapabilityCategory::Settings,
- description: "Sign out and permanently clear local app data, including workflow data.",
- how_to: "Settings > Log Out & Clear App Data",
- status: CapabilityStatus::Stable,
- privacy: None,
- },
- Capability {
- id: "settings.delete_all_data",
- name: "Delete All Data",
- domain: "settings",
- category: CapabilityCategory::Settings,
- description: "Delete all local data and reset the app from the destructive settings section.",
- how_to: "Settings > Delete All Data",
- status: CapabilityStatus::ComingSoon,
- privacy: None,
- },
- Capability {
- id: "automation.task_sources",
- name: "Task Sources",
- domain: "automation",
- category: CapabilityCategory::Automation,
- description: "Pull work items from GitHub, Notion, Linear, and ClickUp using per-source \
- filters, then enrich them onto the agent's todo board and (for proactive \
- sources) start an agent working on them.",
- how_to: "Settings > Task Sources",
- status: CapabilityStatus::Beta,
- privacy: DERIVED_TO_BACKEND,
- },
- Capability {
- id: "automation.discover_workflows",
- name: "Suggested Workflows (Flow Scout)",
- domain: "flows",
- category: CapabilityCategory::Automation,
- description: "A read-only discovery agent (\"Flow Scout\") reads your memory, past \
- conversations, known people, connected apps, and existing flows to figure \
- out which automations would actually help you, then proposes a handful of \
- concrete, buildable workflow suggestions. Each card explains why it was \
- suggested; \"Build this\" hands it to the workflow builder to author a real \
- flow you review and save. Discovery never creates, enables, or runs a flow.",
- how_to: "Flows > Suggested for you > Discover",
- status: CapabilityStatus::Beta,
- privacy: DERIVED_TO_BACKEND,
- },
- Capability {
- id: "automation.flow_memory_node",
- name: "Memory Node (Flows)",
- domain: "flows",
- category: CapabilityCategory::Automation,
- description: "A `memory` node inside a saved workflow graph, giving the flow direct, \
- in-graph memory access with no agent turn involved. It can recall/search/ \
- read style-flavour/look up people from your durable, cross-flow memory \
- (read-only — a flow can never write there) or from other flows' own \
- memory (also read-only), and can remember/forget entries in its OWN \
- private, flow-scoped memory namespace — never the user's personal memory, \
- never another flow's. Every operation is gated by the flow's autonomy \
- tier; a flow-scoped write can require human approval.",
- how_to: "Flows editor > add a `memory` node; set `config.operation` and `config.scope`.",
- status: CapabilityStatus::Beta,
- privacy: LOCAL_RAW,
- },
- Capability {
- id: "automation.flow_dedup_node",
- name: "Dedup Node (Flows)",
- domain: "flows",
- category: CapabilityCategory::Automation,
- description: "A `dedup` node inside a saved workflow graph, giving the flow durable \
- exactly-once processing per item with no agent turn or extra plumbing \
- involved. It drops an item whose per-item key was already committed by a \
- prior successful run, and otherwise passes it through. Committing happens \
- automatically: keys the node passes through are marked done only once the \
- whole run finishes successfully; a failed/cancelled/interrupted/unknown (or \
- any other non-success) run leaves them unmarked so the same items retry next \
- time. Only the resolved per-item key value is stored, locally, in the flow's \
- own private, flow-scoped state — never the item's full content, and never \
- the user's personal memory. The key is whatever the workflow author's \
- `config.key` expression resolves to, so it can carry item-derived data if \
- keyed off a sensitive field — author flows to key off an opaque, \
- non-sensitive stable id (an issue number, message id, url) rather than \
- personal data.",
- how_to: "Flows editor > add a `dedup` node right after the item source; set config.key \
- to a stable per-item id expression, e.g. \"=item.id\".",
- status: CapabilityStatus::Beta,
- privacy: LOCAL_RAW,
- },
- Capability {
- id: "automation.view_cron_jobs",
- name: "View Cron Jobs",
- domain: "automation",
- category: CapabilityCategory::Automation,
- description: "Review scheduled jobs available to the runtime.",
- how_to: "Settings > Cron Jobs",
- status: CapabilityStatus::Stable,
- privacy: None,
- },
- Capability {
- id: "automation.set_job_intervals",
- name: "Set Job Intervals",
- domain: "automation",
- category: CapabilityCategory::Automation,
- description: "Configure how often a scheduled job should run.",
- how_to: "Settings > Cron Jobs",
- status: CapabilityStatus::Stable,
- privacy: None,
- },
- Capability {
- id: "automation.view_execution_history",
- name: "View Execution History",
- domain: "automation",
- category: CapabilityCategory::Automation,
- description: "Inspect past runs and results for scheduled jobs.",
- how_to: "Settings > Cron Jobs",
- status: CapabilityStatus::Beta,
- privacy: None,
- },
- // ── Proactive agents ─────────────────────────────────────────────────────
- Capability {
- id: "automation.morning_briefing",
- name: "Morning Briefing",
- domain: "automation",
- category: CapabilityCategory::Automation,
- description: "Daily proactive agent that reviews calendar, tasks, emails, and market context to deliver a morning summary.",
- how_to: "Automatic after onboarding (runs daily at 7 AM). Adjust schedule via Settings > Cron Jobs.",
- status: CapabilityStatus::Beta,
- privacy: None,
- },
- Capability {
- id: "automation.crypto_agent",
- name: "Crypto Agent",
- domain: "automation",
- category: CapabilityCategory::Automation,
- description: "Dedicated wallet & market specialist sub-agent. The orchestrator \
- routes transfers, swaps, contract calls, balance lookups, and \
- exchange trading requests here. The agent enforces a read → \
- simulate → confirm → execute flow, refuses to fabricate chain ids \
- or token addresses, and gates every write call behind explicit \
- user confirmation.",
- how_to: "Automatic — invoked by the orchestrator when a crypto wallet or market action is requested. Connect a wallet via Settings > Recovery Phrase first.",
- status: CapabilityStatus::Beta,
- privacy: LOCAL_CREDENTIALS,
- },
- // ── Update ──────────────────────────────────────────────────────────────
- // ── Mobile (iOS client) ─────────────────────────────────────────────────
- Capability {
- id: "mobile.device_pairing",
- name: "Device Pairing",
- domain: "devices",
- category: CapabilityCategory::Mobile,
- description: "Pair iOS phones with the desktop core via QR code. The desktop generates a \
- short-lived pairing token; the iOS app scans the QR, completes an X25519 \
- key agreement, and stores the session for reconnects.",
- how_to: "Settings > Devices > Pair iPhone",
- status: CapabilityStatus::Beta,
- privacy: None,
- },
- Capability {
- id: "mobile.ios_client",
- name: "iOS Client",
- domain: "devices",
- category: CapabilityCategory::Mobile,
- description: "iOS app for chatting with your assistant on the go. Connects to the desktop \
- core via LAN HTTP, an E2E-encrypted socket.io tunnel, or a cloud HTTP \
- fallback — no Rust core ships on the device.",
- how_to: "Pair via Settings > Devices, then open the OpenHuman iOS app.",
- status: CapabilityStatus::Beta,
- privacy: None,
- },
- Capability {
- id: "mobile.push_to_talk",
- name: "Push-to-Talk",
- domain: "devices",
- category: CapabilityCategory::Mobile,
- description: "Hold-to-talk voice input on iOS. Activates AVAudioEngine and \
- SFSpeechRecognizer on the device; partial transcripts appear while \
- speaking and the final transcript is sent as a chat message.",
- how_to: "Hold the microphone button on the iOS mascot screen.",
- status: CapabilityStatus::Beta,
- privacy: Some(CapabilityPrivacy {
- leaves_device: false,
- data_kind: PrivacyDataKind::Raw,
- destinations: &[],
- }),
- },
- // ── Update ──────────────────────────────────────────────────────────────
- Capability {
- id: "update.check",
- name: "Check for Core Updates",
- domain: "update",
- category: CapabilityCategory::Settings,
- description: "Query GitHub Releases to see if a newer core binary is available. \
- Available to the orchestrator agent as the `update_check` tool so the \
- user can ask 'am I up to date?' in chat.",
- how_to: "Settings > Developer Options > Check for Updates, or ask the orchestrator in chat.",
- status: CapabilityStatus::Beta,
- privacy: GITHUB_RELEASES_METADATA,
- },
- Capability {
- id: "update.apply",
- name: "Apply Core Update",
- domain: "update",
- category: CapabilityCategory::Settings,
- description: "Download and stage a newer core binary. Desktop builds can self-restart; \
- headless deployments can hand restart off to a supervisor. Exposed to \
- the orchestrator agent as the `update_apply` tool, gated behind explicit \
- user consent (the agent must confirm via `ask_user_clarification` before \
- invoking) and the `config.update.rpc_mutations_enabled` policy switch.",
- how_to: "Settings > Developer Options > Apply Update, or confirm an in-chat update prompt from the orchestrator.",
- status: CapabilityStatus::Beta,
- privacy: GITHUB_RELEASES_METADATA,
- },
- Capability {
- id: "filesystem.access_mode",
- name: "Agent OS Access Mode",
- domain: "security",
- category: CapabilityCategory::Settings,
- description: "Choose how much filesystem and shell access the agent has: Read-Only, \
- Workspace, Trusted Roots (grant specific folders outside the workspace), \
- or Full Access. Credential stores stay blocked in every mode.",
- how_to: "Settings → Agent OS access",
- status: CapabilityStatus::Stable,
- privacy: None,
- },
- Capability {
- id: "agent.action_timeout",
- name: "Action Timeout",
- domain: "agent",
- category: CapabilityCategory::Settings,
- description: "Set how long a single tool or action may run before it is cancelled \
- (1–3600 seconds, default 120). Increase it when a large local model is \
- interrupted before finishing its response. Applies to the next tool call \
- without a restart; the OPENHUMAN_TOOL_TIMEOUT_SECS env var still overrides it.",
- how_to: "Settings → Agent OS access → Action timeout",
- status: CapabilityStatus::Stable,
- privacy: None,
- },
- Capability {
- id: "security.always_allow_tool",
- name: "Always Allow a Tool",
- domain: "security",
- category: CapabilityCategory::Settings,
- description: "On an approval prompt, choose \"Always allow\" to stop being asked for that \
- tool. The choice is saved to your allow-list and persists across restarts; \
- remove it any time under Settings → Agent OS access to be prompted again. \
- Policy still blocks forbidden paths and high-risk commands regardless.",
- how_to: "Click \"Always allow\" on an approval prompt; manage the list in Settings → Agent OS access.",
- status: CapabilityStatus::Stable,
- privacy: None,
- },
- Capability {
- id: "security.approval_history",
- name: "Approval History",
- domain: "security",
- category: CapabilityCategory::Settings,
- description: "Review a read-only audit trail of past tool-approval decisions \
- (Approve once / Always allow / Deny), newest first. Summaries are \
- scrubbed of chat content and arguments are shown as redacted shape only.",
- how_to: "Settings → Agent OS access → View approval history",
- status: CapabilityStatus::Stable,
- privacy: None,
- },
- Capability {
- id: "tool.detect_tools",
- name: "Detect Installed Tools",
- domain: "tools",
- category: CapabilityCategory::Settings,
- description: "Probe the host PATH to report which developer tools and language \
- runtimes are installed (node, python, cargo, docker, git, …).",
- how_to: "Used by the agent automatically; gated by the tool toggle list.",
- status: CapabilityStatus::Stable,
- privacy: None,
- },
- Capability {
- id: "tool.install_tool",
- name: "Install OS Packages",
- domain: "tools",
- category: CapabilityCategory::Settings,
- description: "Install OS or language packages (apt/dnf/brew/winget/pipx/npm/cargo). \
- High impact: only available when Full access / tool installation is enabled.",
- how_to: "Enable in Settings → Agent OS access (Full access mode).",
- status: CapabilityStatus::Beta,
- privacy: None,
- },
- Capability {
- id: "security.action_sandbox",
- name: "Action Sandbox",
- domain: "security",
- category: CapabilityCategory::Settings,
- description: "Dedicated action directory for agent tools (shell, file, git), separate \
- from internal application state. Agent tools default their working directory \
- and path resolution to the action sandbox, preventing accidental modification \
- of memory databases, session transcripts, tokens, and other internal state.",
- how_to: "Settings → Agent OS access",
- status: CapabilityStatus::Stable,
- privacy: None,
- },
- Capability {
- id: "security.sandbox_backends",
- name: "Sandbox Execution Backends",
- domain: "security",
- category: CapabilityCategory::Settings,
- description: "Route agent tool execution (shell, filesystem, process) through sandbox \
- backends — Docker containers or OS-level jails (Landlock/Seatbelt) — for \
- reduced blast radius on remote, channel, cron, or background sessions. \
- Configurable per agent/session/channel with safe defaults for non-main sessions.",
- how_to: "Set sandbox_mode = \"sandboxed\" in agent.toml, or configure runtime.kind = \
- \"docker\" in the TOML config. Use openhuman.sandbox_status / \
- openhuman.sandbox_resolve_policy RPC to inspect.",
- status: CapabilityStatus::Beta,
- privacy: None,
- },
- Capability {
- id: "intelligence.remember_preferences",
- name: "Remember Preferences",
- domain: "memory",
- category: CapabilityCategory::Intelligence,
- description: "Remember preferences you state in chat and apply them automatically — \
- general preferences shape every reply (tone, language, standing habits); \
- situational ones surface only when relevant to your current message.",
- how_to: "State a preference in chat, e.g. \"always reply in British English\" or \
- \"when writing Rust, prefer Result over unwrap\".",
- status: CapabilityStatus::Stable,
- privacy: LOCAL_RAW,
- },
-];
+use std::sync::LazyLock;
+
+#[path = "catalog_part_01.rs"]
+mod catalog_part_01;
+#[path = "catalog_part_02.rs"]
+mod catalog_part_02;
+#[path = "catalog_part_03.rs"]
+mod catalog_part_03;
+
+pub(super) static CAPABILITIES: LazyLock<Vec<Capability>> = LazyLock::new(|| {
+ [
+ catalog_part_01::CAPABILITIES,
+ catalog_part_02::CAPABILITIES,
+ catalog_part_03::CAPABILITIES,
+ ]
+ .concat()
+});
diff --git a/src/openhuman/platform/about_app/catalog_part_01.rs b/src/openhuman/platform/about_app/catalog_part_01.rs
new file mode 100644
index 0000000000..684f5bb111
--- /dev/null
+++ b/src/openhuman/platform/about_app/catalog_part_01.rs
@@ -0,0 +1,618 @@
+use super::*;
+
+pub(super) const CAPABILITIES: &[Capability] = &[
+Capability {
+ id: "conversation.create",
+ name: "Create Conversations",
+ domain: "conversation",
+ category: CapabilityCategory::Conversation,
+ description: "Start a new conversation thread with the assistant.",
+ how_to: "Conversations",
+ status: CapabilityStatus::Stable,
+ privacy: None,
+ },
+ Capability {
+ id: "conversation.send_text",
+ name: "Send Text Messages",
+ domain: "conversation",
+ category: CapabilityCategory::Conversation,
+ description: "Send typed messages to the assistant in a conversation.",
+ how_to: "Conversations > Message composer",
+ status: CapabilityStatus::Stable,
+ privacy: DERIVED_TO_BACKEND,
+ },
+ Capability {
+ id: "conversation.prompt_injection_guard",
+ name: "Prompt Injection Guard",
+ domain: "conversation",
+ category: CapabilityCategory::Conversation,
+ description: "Detect and block prompt-injection attempts before agent/model execution.",
+ how_to: "Conversations > Message composer",
+ status: CapabilityStatus::Stable,
+ privacy: DERIVED_TO_BACKEND,
+ },
+ Capability {
+ id: "conversation.send_voice",
+ name: "Send Voice Messages",
+ domain: "conversation",
+ category: CapabilityCategory::Conversation,
+ description: "Record or attach voice input and send it as a message.",
+ how_to: "Conversations > Voice input",
+ status: CapabilityStatus::Beta,
+ privacy: DERIVED_TO_BACKEND,
+ },
+ Capability {
+ id: "voice.stt_engine",
+ name: "Speech Recognition Engine",
+ domain: "voice",
+ category: CapabilityCategory::Conversation,
+ description: "Choose which hosted engine transcribes your speech. \"Backend\" uses \
+ OpenHuman's transcription proxy and needs no setup; ElevenLabs and OpenAI \
+ call the provider directly with your own API key. Audio always leaves the \
+ device — the bundled offline whisper.cpp engine was removed, so there is \
+ no local option.",
+ how_to: "Settings → Voice → Speech recognition engine",
+ status: CapabilityStatus::Beta,
+ privacy: DERIVED_TO_BACKEND,
+ },
+ Capability {
+ id: "voice.ptt",
+ name: "Global push-to-talk",
+ domain: "voice",
+ category: CapabilityCategory::Conversation,
+ description: "Hold a global hotkey from anywhere on the desktop to dictate into the \
+ active chat thread. Press opens the mic, release commits the transcript, \
+ and an always-on-top overlay shows listening/idle state without stealing \
+ focus. Cross-platform via tauri-plugin-global-shortcut (macOS, Windows, \
+ Linux/X11); requires microphone access and a global shortcut binding. \
+ Optional speak_reply plays the agent's response through local TTS.",
+ how_to: "Settings → Voice → Push-to-Talk: pick a shortcut, grant microphone access, \
+ then hold the configured hotkey from any window.",
+ status: CapabilityStatus::Beta,
+ privacy: DERIVED_TO_BACKEND,
+ },
+ Capability {
+ id: "conversation.copy_messages",
+ name: "Copy Messages",
+ domain: "conversation",
+ category: CapabilityCategory::Conversation,
+ description: "Copy individual assistant or user messages for reuse elsewhere.",
+ how_to: "Conversations > Message actions",
+ status: CapabilityStatus::Stable,
+ privacy: None,
+ },
+ Capability {
+ id: "conversation.delete_conversations",
+ name: "Delete Conversations",
+ domain: "conversation",
+ category: CapabilityCategory::Conversation,
+ description: "Remove existing conversation threads from the app.",
+ how_to: "Conversations > Thread actions",
+ status: CapabilityStatus::Stable,
+ privacy: None,
+ },
+ Capability {
+ id: "conversation.terminal_chat",
+ name: "Tabbed Terminal UI",
+ domain: "tui",
+ category: CapabilityCategory::Conversation,
+ description: "Operate OpenHuman from a terminal through four tabs: live core logs, \
+ orchestrator chat, safe configuration, and account settings. Bare \
+ `openhuman` opens it on an interactive non-container host; `openhuman tui` \
+ (alias `chat`) forces it. The chat streams replies, thinking, and tools live.",
+ how_to: "Run `openhuman`, or `openhuman tui` to force the UI. Use Tab/Shift+Tab or Alt+1-4 \
+ to switch Logs, Chat, Config, and Settings. `--thread <id>` resumes a chat and \
+ `--new` starts one. Settings accepts a one-time login token and supports account \
+ refresh and logout. Use `openhuman --no-tui` to suppress automatic launch.",
+ status: CapabilityStatus::Beta,
+ privacy: DERIVED_TO_BACKEND,
+ },
+ Capability {
+ id: "conversation.suggested_questions",
+ name: "Suggested Questions",
+ domain: "conversation",
+ category: CapabilityCategory::Conversation,
+ description: "Offer prompt suggestions to help continue a conversation.",
+ how_to: "Home or Conversations > Suggested prompts",
+ status: CapabilityStatus::Beta,
+ privacy: None,
+ },
+ Capability {
+ id: "conversation.tool_execution_timeline",
+ name: "Tool Execution Timeline",
+ domain: "conversation",
+ category: CapabilityCategory::Conversation,
+ description: "Show the sequence of tool calls and actions used to answer a request.",
+ how_to: "Conversations > Tool timeline",
+ status: CapabilityStatus::Beta,
+ privacy: None,
+ },
+ Capability {
+ id: "conversation.plan_review",
+ name: "Plan Review",
+ domain: "conversation",
+ category: CapabilityCategory::Conversation,
+ description: "Pause an interactive turn for review whenever the assistant proposes a thread-scoped plan (a multi-step to-do list with its objective). Review the whole plan once above the composer, then Approve to run it, Reject to discard it, or send feedback to have the assistant revise and re-propose — nothing executes until you approve. Background and scheduled runs are never gated.",
+ how_to: "Conversations > review the plan card above the composer when the assistant lays out a multi-step plan",
+ status: CapabilityStatus::Beta,
+ privacy: None,
+ },
+ Capability {
+ id: "conversation.subagent_mascots",
+ name: "Subagent Mascots",
+ domain: "conversation",
+ category: CapabilityCategory::Conversation,
+ description: "Show delegated sub-agents as colored mascots with compact activity bubbles and running, completed, or failed states.",
+ how_to: "Human > ask the assistant to delegate work to sub-agents",
+ status: CapabilityStatus::Beta,
+ privacy: None,
+ },
+ Capability {
+ id: "intelligence.vision_subagent",
+ name: "Vision Sub-agent",
+ domain: "agent",
+ category: CapabilityCategory::Intelligence,
+ description: "Delegate image / screenshot understanding to a dedicated vision sub-agent — describe, OCR, read charts/diagrams, compare images, or locate UI elements. Rides the multimodal `vision-v1` tier so attached images are always analyzed.",
+ how_to: "Attach an image in chat, or ask the assistant to look at a screenshot / image file",
+ status: CapabilityStatus::Beta,
+ privacy: IMAGE_TO_BACKEND,
+ },
+ Capability {
+ id: "intelligence.image_generation",
+ name: "Image Generation",
+ domain: "agent",
+ category: CapabilityCategory::Intelligence,
+ description: "Delegate image creation to a dedicated image sub-agent — generate images from a text prompt, or edit/restyle reference images, using hosted GMI models (Seedream / SeedEdit). Results are saved to the workspace.",
+ how_to: "Ask the assistant to generate, draw, or edit an image",
+ status: CapabilityStatus::Beta,
+ privacy: MEDIA_GEN_TO_BACKEND,
+ },
+ Capability {
+ id: "intelligence.video_generation",
+ name: "Video Generation",
+ domain: "agent",
+ category: CapabilityCategory::Intelligence,
+ description: "Delegate short-video creation to a dedicated video sub-agent — text-to-video or animate a reference image using hosted GMI models (Seedance / Veo). Generation is asynchronous; the finished clip is saved to the workspace.",
+ how_to: "Ask the assistant to generate a video or animate an image",
+ status: CapabilityStatus::Beta,
+ privacy: MEDIA_GEN_TO_BACKEND,
+ },
+ Capability {
+ id: "conversation.label_filter",
+ name: "Thread Label Filters",
+ domain: "conversation",
+ category: CapabilityCategory::Conversation,
+ description: "Filter the thread list by label (Work, Briefing, Notification) using the tab bar at the top of the thread list.",
+ how_to: "Conversations > Label tabs",
+ status: CapabilityStatus::Beta,
+ privacy: None,
+ },
+ Capability {
+ id: "intelligence.analyze_actionable_items",
+ name: "Analyze Actionable Items",
+ domain: "intelligence",
+ category: CapabilityCategory::Intelligence,
+ description: "Extract and summarize actionable items from your activity and conversations.",
+ how_to: "Intelligence",
+ status: CapabilityStatus::Stable,
+ privacy: DERIVED_TO_BACKEND,
+ },
+ Capability {
+ id: "intelligence.filter_actionable_items",
+ name: "Filter Actionable Items",
+ domain: "intelligence",
+ category: CapabilityCategory::Intelligence,
+ description: "Search and filter actionable items to focus on what matters now.",
+ how_to: "Intelligence > Filters and search",
+ status: CapabilityStatus::Stable,
+ privacy: None,
+ },
+ Capability {
+ id: "intelligence.mark_actionable_item_complete",
+ name: "Mark Items Complete",
+ domain: "intelligence",
+ category: CapabilityCategory::Intelligence,
+ description: "Mark an actionable item as completed.",
+ how_to: "Intelligence > Item actions",
+ status: CapabilityStatus::Stable,
+ privacy: None,
+ },
+ Capability {
+ id: "intelligence.dismiss_actionable_item",
+ name: "Dismiss Items",
+ domain: "intelligence",
+ category: CapabilityCategory::Intelligence,
+ description: "Dismiss irrelevant or already handled actionable items.",
+ how_to: "Intelligence > Item actions",
+ status: CapabilityStatus::Stable,
+ privacy: None,
+ },
+ Capability {
+ id: "intelligence.snooze_actionable_item",
+ name: "Snooze Items",
+ domain: "intelligence",
+ category: CapabilityCategory::Intelligence,
+ description: "Temporarily hide an actionable item until later.",
+ how_to: "Intelligence > Item actions",
+ status: CapabilityStatus::Stable,
+ privacy: None,
+ },
+ Capability {
+ id: "intelligence.undo_action",
+ name: "Undo Item Actions",
+ domain: "intelligence",
+ category: CapabilityCategory::Intelligence,
+ description: "Undo a recent complete, dismiss, or snooze action.",
+ how_to: "Intelligence > Undo snackbar or item history",
+ status: CapabilityStatus::Beta,
+ privacy: None,
+ },
+ Capability {
+ id: "intelligence.agentmemory_backend",
+ name: "agentmemory Memory Backend",
+ domain: "intelligence",
+ category: CapabilityCategory::Intelligence,
+ description: "Opt-in Memory trait backend that delegates every store/recall/get/list/forget \
+ call to a locally-running agentmemory REST server. Selected via \
+ `memory.backend = \"agentmemory\"` in config.toml. Allows users who self-host \
+ agentmemory across Claude Code, Cursor, Codex, and OpenCode to share a single durable \
+ memory store. Default backend remains sqlite; selecting agentmemory is non-breaking.",
+ how_to: "Set `memory.backend = \"agentmemory\"` in config.toml. \
+ See gitbooks/features/obsidian-wiki/agentmemory-backend.md for setup and config keys.",
+ status: CapabilityStatus::Beta,
+ privacy: LOCAL_RAW,
+ },
+ Capability {
+ id: "intelligence.memory_workspace",
+ name: "Memory Workspace",
+ domain: "intelligence",
+ category: CapabilityCategory::Intelligence,
+ description: "Inspect or debug the app's memory workspace and stored knowledge.",
+ how_to: "Settings > Memory Debug",
+ status: CapabilityStatus::Beta,
+ privacy: None,
+ },
+ Capability {
+ id: "intelligence.agents_md_instructions",
+ name: "AGENTS.md Project Instructions",
+ domain: "intelligence",
+ category: CapabilityCategory::Intelligence,
+ description: "Load configurable standing instructions from AGENTS.md files into the agent's \
+ system prompt — OpenHuman's analog of Claude Code's CLAUDE.md / Codex's AGENTS.md. Two \
+ layers are read once at session start: a global layer from the OpenHuman workspace \
+ (<workspace_dir>/AGENTS.md) and a project layer from the folder the agent is operating \
+ in (<action_dir>/AGENTS.md, or a sub-agent's isolated worktree). The global layer is \
+ injected first, the project layer second (project instructions take precedence). \
+ Missing or empty files are silently skipped, and each layer is capped so a large file \
+ can't crowd out the rest of the prompt. On by default; disable via \
+ `agent.agents_md_enabled = false`.",
+ how_to: "Create an AGENTS.md file in your OpenHuman workspace and/or your project's action \
+ directory. Toggle off with `agent.agents_md_enabled = false` in config.toml.",
+ status: CapabilityStatus::Stable,
+ privacy: AGENTS_MD_TO_INFERENCE_PROVIDER,
+ },
+ Capability {
+ id: "intelligence.tool_scoped_memory",
+ name: "Tool-Scoped Memory Rules",
+ domain: "intelligence",
+ category: CapabilityCategory::Intelligence,
+ description: "Store durable, tool-specific rules and corrections that survive context \
+ compression. Critical-priority rules (e.g. 'never email Sarah') are pinned into the \
+ system prompt at session start. Captured automatically from user edicts and repeated \
+ tool failures; also writable programmatically via the memory.tool_rule_* RPC surface.",
+ how_to: "Automatic — user edicts are captured after every turn. Manage via \
+ memory.tool_rule_put / memory.tool_rule_list / memory.tool_rule_delete (RPC).",
+ status: CapabilityStatus::Beta,
+ privacy: LOCAL_RAW,
+ },
+ Capability {
+ id: "intelligence.long_term_goals",
+ name: "Long-term Goals",
+ domain: "intelligence",
+ category: CapabilityCategory::Intelligence,
+ description: "An editable list of the assistant's durable long-term goals for working with \
+ you, stored locally in MEMORY_GOALS.md (capped ~500 tokens). A background goals agent \
+ keeps the list fresh: it runs when the conversation context is summarized, and on first \
+ run populates initial goals from context. Items can be added/edited/deleted explicitly \
+ via RPC or agent tools.",
+ how_to: "Automatic — refreshed on context summarization. Manage via \
+ memory_goals.list / memory_goals.add / memory_goals.edit / memory_goals.delete / \
+ memory_goals.reflect (RPC), or the goals_* agent tools.",
+ status: CapabilityStatus::Beta,
+ // Enrichment runs a cloud agentic model, so goal/context text can leave
+ // the device during a reflect pass (CRUD/storage stays local).
+ privacy: DERIVED_TO_BACKEND,
+ },
+ Capability {
+ id: "conversation.thread_goal",
+ name: "Thread Goal",
+ domain: "conversation",
+ category: CapabilityCategory::Conversation,
+ description: "A single, thread-scoped goal (Codex-style \"completion contract\") the \
+ assistant keeps pursuing across turns, interrupts, resumes, and budget boundaries — \
+ distinct from the long-term goals list and the per-thread task board. Stored locally \
+ (one goal per thread), with a lifecycle (active/paused/budget_limited/complete) and an \
+ optional token budget. The active goal is injected into context each turn; the context \
+ scout proposes a goal on a fresh thread (only if none is set) and the orchestrator can \
+ set/refine it. When enabled, idle threads can autonomously continue toward the goal.",
+ how_to: "Set/edit via the goal chip above the composer in Conversations, or the \
+ thread_goals.* RPC (get/set/complete/pause/resume/clear); the assistant manages it via \
+ the goal_set / goal_get / goal_complete tools. Autonomous continuation is opt-in via \
+ heartbeat.goal_continuation_enabled.",
+ status: CapabilityStatus::Beta,
+ // Goal CRUD/storage is local; autonomous continuation (opt-in) runs a
+ // cloud agentic model, so objective/context can leave the device then.
+ privacy: DERIVED_TO_BACKEND,
+ },
+ Capability {
+ id: "intelligence.memory_tree_retrieval",
+ name: "Memory Tree Retrieval (chat)",
+ domain: "intelligence",
+ category: CapabilityCategory::Intelligence,
+ description: "Ask questions about your ingested email/chat/document memory in chat. The orchestrator can resolve names to canonical ids, query summaries by source/topic/global window, drill into details, and cite raw chunks.",
+ how_to: "Chat > ask the assistant about people, conversations, or windows",
+ status: CapabilityStatus::Beta,
+ privacy: LOCAL_RAW,
+ },
+ Capability {
+ id: "intelligence.memory_pipeline_doctor",
+ name: "Memory Pipeline Doctor",
+ domain: "intelligence",
+ category: CapabilityCategory::Intelligence,
+ description: "Diagnose why the memory tree / wiki is empty or stalled. Walks each pipeline stage (embeddings config, scheduler gate, job queue, extraction/recall degradation, summary-tree precondition) and reports the single first blocking cause with an actionable fix, plus counters and extraction coverage. The agent can run it on itself; a typed 'first blocking cause' is surfaced in the Memory status panel, and jobs that failed under a now-fixed config can be requeued on demand via the `memory_tree_retry_failed` RPC.",
+ how_to: "Memory status panel shows the cause + fix; or ask the agent to diagnose memory; or `openhuman-core` RPC `memory_tree_doctor`",
+ status: CapabilityStatus::Beta,
+ privacy: LOCAL_RAW,
+ },
+ Capability {
+ id: "intelligence.github_repo_memory_source",
+ name: "GitHub Repo Memory Source",
+ domain: "memory_sources",
+ category: CapabilityCategory::Intelligence,
+ description: "Sync a GitHub repository's project activity — commits, issues, and \
+ pull requests (not source code) — into your memory. Items are archived verbatim \
+ under a browsable, repo-grouped vault layout \
+ (raw/github-com-<owner>-<repo>/{commits,issues,prs}/) and ingested into the \
+ memory tree for recall. Contributors are surfaced as @handle entities, and \
+ commit messages plus closed/merged issues & PRs get a priority boost so \
+ high-signal history leads at summary time. Pulls up to 2000 items of each type \
+ per sync by default, overridable per source via max_commits / max_issues / \
+ max_prs.",
+ how_to: "Settings > Memory & Data > Memory Sources — add a GitHub repository URL. \
+ Programmatic: openhuman.memory_sources_add (RPC).",
+ status: CapabilityStatus::Beta,
+ privacy: GITHUB_REPO_SOURCE,
+ },
+ Capability {
+ id: "intelligence.memory_source_sync_controls",
+ name: "Memory Source Sync Defaults & Controls",
+ domain: "memory_sources",
+ category: CapabilityCategory::Intelligence,
+ description: "Connected memory sources are enabled by default with conservative, \
+ per-kind sync caps so the first sync stays cheap (e.g. Gmail ~100 recent emails, \
+ GitHub repo 10 PRs / 10 issues / 50 commits, RSS 20 items). Each source row exposes \
+ an inline settings panel to adjust the limit fields that apply to its kind \
+ (max_items, sync_depth_days, max_prs/issues/commits, since_days). \
+ An \"All In\" action enables every source and removes the caps to build the richest \
+ memory graph, then triggers a full sync. Already-connected sources are migrated to \
+ the new defaults once.",
+ how_to: "Intelligence > Memory Sources — toggle a source, open its gear for per-source \
+ limits, or use \"All In\". Programmatic: openhuman.memory_sources_update and \
+ openhuman.memory_sources_apply_all_in (RPC).",
+ status: CapabilityStatus::Beta,
+ privacy: LOCAL_RAW,
+ },
+ Capability {
+ id: "intelligence.coding_session_memory",
+ name: "Coding-Agent Session Memory",
+ domain: "memory_sources",
+ category: CapabilityCategory::Intelligence,
+ description: "Discover local Codex and Claude Code session histories, retain only human-authored decisions and corrections, and distill them into a durable TinyCortex persona memory pack. Tool output, reasoning, developer prompts, and subagent traffic are excluded before inference.",
+ how_to: "Brain > Sources > Coding-agent sessions > Ingest new sessions. Programmatic: openhuman.memory_sources_coding_session_status and openhuman.memory_sources_ingest_coding_sessions (RPC).",
+ status: CapabilityStatus::Beta,
+ privacy: CODING_SESSION_TO_BACKEND,
+ },
+ Capability {
+ id: "intelligence.memory_sync_schedule",
+ name: "Memory Sync Schedule",
+ domain: "config",
+ category: CapabilityCategory::Intelligence,
+ description: "Pick a single global cadence for how often all opted-in memory sources \
+ auto-sync, presented like a backup schedule (\"Last synced … · Sync every …\"). \
+ Presets are every 4h / 12h / 24h, plus \"Manual only\" which disables background \
+ auto-sync entirely (you can still sync on demand). The chosen interval overrides each \
+ provider's built-in cadence but is floored at it, so syncs never run more often than \
+ the provider intends — handy for keeping credit spend predictable. Unset defaults to \
+ every 24h.",
+ how_to: "Intelligence > Memory Sources — choose a Sync every… preset or Manual only. \
+ Programmatic: openhuman.config_get_memory_sync_settings / \
+ openhuman.config_update_memory_sync_settings (RPC); ops override via the \
+ OPENHUMAN_MEMORY_SYNC_INTERVAL_SECS env var (0 = manual).",
+ status: CapabilityStatus::Beta,
+ privacy: LOCAL_RAW,
+ },
+ Capability {
+ id: "intelligence.embedding_provider_config",
+ name: "Configure Embedding Provider",
+ domain: "embeddings",
+ category: CapabilityCategory::Intelligence,
+ description:
+ "Pick which embedding provider drives semantic search across your memory: \
+ managed cloud (default, Voyage-backed via api.tinyhumans.ai), OpenAI, \
+ Cohere, local Ollama, or a custom OpenAI-compatible endpoint. API keys \
+ are stored encrypted via the local keyring under `embeddings:<slug>`; \
+ model name and embedding dimensions are tunable per provider. The \
+ legacy `inference_embed` RPC is aliased to `embeddings_embed` so \
+ existing callers continue to work.",
+ how_to: "Connections → API keys → Embeddings",
+ status: CapabilityStatus::Beta,
+ // Privacy depends on the selected provider — see
+ // `intelligence.embedding_provider_test` for the per-provider data
+ // destinations. The configuration surface itself only writes to the
+ // local keyring and config, so leaving this `None` (treat-as-unknown)
+ // would under-report; we annotate the credential side here and the
+ // network side on the test action.
+ privacy: LOCAL_CREDENTIALS,
+ },
+ Capability {
+ id: "intelligence.embedding_provider_test",
+ name: "Test Embedding Provider",
+ domain: "embeddings",
+ category: CapabilityCategory::Intelligence,
+ description:
+ "Verify a configured embedding provider before committing it to \
+ memory ingestion. Sends a small one-shot embed request and reports \
+ the model, dimensions, and any auth/error surface so a \
+ misconfigured key doesn't get discovered halfway through a 50k \
+ chunk backfill.",
+ how_to: "Connections → API keys → Embeddings → Test Connection",
+ // The probe payload routes to whichever provider the user has
+ // selected — managed cloud (default), OpenAI, Cohere, or a custom
+ // OpenAI-compatible endpoint. Using `DERIVED_TO_BACKEND` here would
+ // under-report by only listing the managed path; the dedicated
+ // constant enumerates every reachable destination so the Privacy
+ // surface renders the full set.
+ status: CapabilityStatus::Beta,
+ privacy: EMBEDDING_PROBE_TO_CONFIGURED_PROVIDER,
+ },
+ Capability {
+ id: "intelligence.mcp_server",
+ name: "MCP Server",
+ domain: "intelligence",
+ category: CapabilityCategory::Intelligence,
+ description: "Expose a curated OpenHuman tool surface over stdio MCP or Streamable HTTP/SSE for MCP-compatible clients.",
+ how_to: "Run `openhuman-core mcp` (stdio) or `openhuman-core mcp --transport http --port 9300` for remote clients.",
+ status: CapabilityStatus::Beta,
+ privacy: LOCAL_RAW,
+ },
+ Capability {
+ id: "intelligence.searxng_search",
+ name: "SearXNG Search",
+ domain: "intelligence",
+ category: CapabilityCategory::Intelligence,
+ description: "Search a configured self-hosted SearXNG instance from agent and MCP tools, returning normalized title, URL, snippet, and source results.",
+ how_to: "Set `[searxng] enabled = true` and `base_url` in config.toml, or use OPENHUMAN_SEARXNG_* environment variables.",
+ status: CapabilityStatus::Beta,
+ privacy: SEARXNG_RAW_TO_CONFIGURED_INSTANCE,
+ },
+ Capability {
+ id: "intelligence.tool_registry",
+ name: "Tool Registry",
+ domain: "intelligence",
+ category: CapabilityCategory::Intelligence,
+ description: "Discover OpenHuman's MCP stdio tools and controller-backed tools from one local registry, including versions, routes, input/output schemas, allowed agents, and health state.",
+ how_to: "Call openhuman.tool_registry_list over core JSON-RPC, or openhuman.tool_registry_get with a tool_id such as memory.search.",
+ status: CapabilityStatus::Beta,
+ privacy: LOCAL_RAW,
+ },
+ Capability {
+ id: "intelligence.orchestrator_worker_thread",
+ name: "Worker Thread Delegation",
+ domain: "intelligence",
+ category: CapabilityCategory::Intelligence,
+ description: "When a delegated sub-task is long or complex, the orchestrator can route it into a fresh worker-labeled conversation thread instead of flooding the parent thread. The user opens the worker thread from the thread list (or via the reference card in the parent) to read the sub-agent's full transcript.",
+ how_to: "Conversations > tap the worker reference card in the parent thread, or open the worker-labeled thread from the thread list",
+ status: CapabilityStatus::Beta,
+ privacy: DERIVED_TO_BACKEND,
+ },
+ Capability {
+ id: "intelligence.workflow_orchestration",
+ name: "Workflow Orchestration",
+ domain: "workflow_runs",
+ category: CapabilityCategory::Intelligence,
+ description: "Run declarative multi-agent workflows such as parallel research with cross-checking: a question is decomposed into angles, researched in parallel, adversarially cross-checked, and synthesized into one cited report. Watch each phase progress with its child agent results, stop or resume a run, and read the final synthesis. High-cost / high-concurrency runs require explicit approval before starting.",
+ how_to: "Intelligence > Orchestration > pick a workflow and Start",
+ status: CapabilityStatus::Beta,
+ privacy: DERIVED_TO_BACKEND,
+ },
+ Capability {
+ id: "intelligence.agent_library",
+ name: "Agents Library",
+ domain: "intelligence",
+ category: CapabilityCategory::Intelligence,
+ description: "Browse safe display metadata for registered agent definitions, compare worker capabilities, and start a one-off task with an explicitly selected agent.",
+ how_to: "Intelligence > Agent Tasks > Agents Library",
+ status: CapabilityStatus::Beta,
+ privacy: DERIVED_TO_BACKEND,
+ },
+ Capability {
+ id: "intelligence.worktree_manager",
+ name: "Agent Worktrees",
+ domain: "intelligence",
+ category: CapabilityCategory::Intelligence,
+ description: "Inspect and clean up the isolated git worktrees that parallel sub-agents check out under <repo>/.claude/worktrees. Each row shows the worktree's branch, dirty state, and changed files, plus a cross-worktree overlap warning when two workers touched the same file. Open, diff, or remove a worktree (a dirty worktree requires an explicit discard confirmation; the worker branch is preserved).",
+ how_to: "Intelligence > Worktrees",
+ status: CapabilityStatus::Beta,
+ privacy: None,
+ },
+ Capability {
+ id: "intelligence.slack_memory_ingest",
+ name: "Slack Memory Ingestion",
+ domain: "intelligence",
+ category: CapabilityCategory::Intelligence,
+ description: "Backfill the last 6 days of Slack history into the memory tree and keep it up to date by flushing each closed 6-hour UTC bucket. Driven by an authenticated Slack connection (OAuth via Composio).",
+ how_to: "Connections > OAuth > Slack",
+ status: CapabilityStatus::Beta,
+ privacy: LOCAL_RAW,
+ },
+ Capability {
+ id: "intelligence.clickup_memory_ingest",
+ name: "ClickUp Memory Ingestion",
+ domain: "intelligence",
+ category: CapabilityCategory::Intelligence,
+ description: "Incrementally sync ClickUp tasks assigned to the authenticated user into the Memory Tree on a 30-minute cadence, with an initial backfill on first connect. Only tasks the user is directly assigned to are ingested. Driven by an authenticated ClickUp connection (OAuth via Composio).",
+ how_to: "Connections > OAuth > ClickUp",
+ status: CapabilityStatus::Beta,
+ privacy: LOCAL_RAW,
+ },
+ Capability {
+ id: "intelligence.notifications_dismiss",
+ name: "Dismiss Notifications",
+ domain: "intelligence",
+ category: CapabilityCategory::Intelligence,
+ description: "Dismiss low-value notifications from the intelligence inbox.",
+ how_to: "Notifications > Item actions",
+ status: CapabilityStatus::Beta,
+ privacy: None,
+ },
+ Capability {
+ id: "intelligence.notifications_mark_acted",
+ name: "Mark Notifications Acted",
+ domain: "intelligence",
+ category: CapabilityCategory::Intelligence,
+ description: "Mark a notification as acted upon after taking follow-up action.",
+ how_to: "Notifications > Item actions",
+ status: CapabilityStatus::Beta,
+ privacy: None,
+ },
+ Capability {
+ id: "intelligence.notifications_stats",
+ name: "View Notification Stats",
+ domain: "intelligence",
+ category: CapabilityCategory::Intelligence,
+ description: "View aggregate unread, unscored, and provider/action notification stats.",
+ how_to: "Notifications > Summary cards",
+ status: CapabilityStatus::Beta,
+ privacy: None,
+ },
+ Capability {
+ id: "workflows.discover",
+ name: "Discover Workflows",
+ domain: "workflows",
+ category: CapabilityCategory::Workflows,
+ description: "Browse available workflows that can extend the app.",
+ how_to: "Intelligence > Workflows",
+ status: CapabilityStatus::Stable,
+ privacy: None,
+ },
+ Capability {
+ id: "workflows.install",
+ name: "Install Workflows",
+ domain: "workflows",
+ category: CapabilityCategory::Workflows,
+ description: "Install a workflow into the local workspace.",
+ how_to: "Intelligence > Workflows > Install",
+ status: CapabilityStatus::Stable,
+ privacy: None,
+ },
+];
diff --git a/src/openhuman/platform/about_app/catalog_part_02.rs b/src/openhuman/platform/about_app/catalog_part_02.rs
new file mode 100644
index 0000000000..d5f0388ad0
--- /dev/null
+++ b/src/openhuman/platform/about_app/catalog_part_02.rs
@@ -0,0 +1,620 @@
+use super::*;
+
+pub(super) const CAPABILITIES: &[Capability] = &[
+Capability {
+ id: "workflows.configure",
+ name: "Configure Workflows",
+ domain: "workflows",
+ category: CapabilityCategory::Workflows,
+ description: "Open workflow setup and update workflow-specific configuration.",
+ how_to: "Intelligence > Workflows > Setup or Connections",
+ status: CapabilityStatus::Stable,
+ privacy: None,
+ },
+ Capability {
+ id: "workflows.connection_status",
+ name: "Monitor Workflow Connection Status",
+ domain: "workflows",
+ category: CapabilityCategory::Workflows,
+ description: "See whether a workflow-backed integration is connected, offline, or needs setup.",
+ how_to: "Intelligence > Workflows or Connections",
+ status: CapabilityStatus::Beta,
+ privacy: None,
+ },
+ Capability {
+ id: "workflows.sync_manual",
+ name: "Manually Sync Workflow Data",
+ domain: "workflows",
+ category: CapabilityCategory::Workflows,
+ description: "Trigger a manual data sync for a workflow integration.",
+ how_to: "Intelligence > Workflows > Workflow card > Sync",
+ status: CapabilityStatus::Beta,
+ privacy: DERIVED_TO_BACKEND,
+ },
+ Capability {
+ id: "workflows.tinyfish_web_automation",
+ name: "TinyFish Web Automation",
+ domain: "workflows",
+ category: CapabilityCategory::Workflows,
+ description:
+ "Search the web, render JavaScript-heavy pages, and run goal-based browser automations through TinyFish.",
+ how_to: "Conversations > Ask the assistant to search, fetch, or automate a website with TinyFish",
+ status: CapabilityStatus::Beta,
+ privacy: DERIVED_TO_BACKEND,
+ },
+ Capability {
+ id: "workflows.toggle_enabled",
+ name: "Enable or Disable Workflows",
+ domain: "workflows",
+ category: CapabilityCategory::Workflows,
+ description: "Turn individual workflows on or off without uninstalling them.",
+ how_to: "Settings > Developer Options > Workflows",
+ status: CapabilityStatus::Stable,
+ privacy: None,
+ },
+ Capability {
+ id: "workflows.open_connections_hub",
+ name: "Open Connections Hub",
+ domain: "workflows",
+ category: CapabilityCategory::Workflows,
+ description: "Browse the dedicated connections hub for external workflow-backed integrations.",
+ how_to: "Connections",
+ status: CapabilityStatus::Beta,
+ privacy: None,
+ },
+ // ── Composio direct mode (BYO API key) ──────────────────────────
+ //
+ // Composio shipped with two integration paths:
+ // 1. Backend-proxied (default) — calls through api.tinyhumans.ai;
+ // backend owns the Composio API key, billing, allowlist, and
+ // HMAC-verified trigger fan-out via socket.io.
+ // 2. Direct (BYO key) — core calls backend.composio.dev directly
+ // with the user's own key. Sovereign / offline-friendly, but
+ // tool execution only — real-time trigger webhooks are NOT
+ // routed in direct mode (they still require the backend).
+ Capability {
+ id: "composio.direct_mode",
+ name: "Composio Direct Mode (BYO API Key)",
+ domain: "workflows",
+ category: CapabilityCategory::Workflows,
+ description:
+ "Route Composio tool calls directly to backend.composio.dev with your own API key, \
+ bypassing the OpenHuman backend proxy. Tool execution only — trigger webhooks still \
+ require backend mode.",
+ how_to: "Settings > Skills > Composio > Direct mode",
+ status: CapabilityStatus::Beta,
+ privacy: COMPOSIO_DIRECT_CREDENTIALS,
+ },
+ Capability {
+ id: "composio.direct_mode_triggers_gap",
+ name: "Composio Triggers (Direct Mode — Limited)",
+ domain: "workflows",
+ category: CapabilityCategory::Workflows,
+ description:
+ "Composio real-time trigger webhooks (Gmail new-message, Slack new-message, …) \
+ currently arrive over wss://api.tinyhumans.ai/socket.io and require backend mode. \
+ Direct-mode users get synchronous tool execution but not async trigger push in \
+ this release.",
+ how_to: "Switch to Backend mode to receive triggers, or wait for the direct trigger sink follow-up",
+ status: CapabilityStatus::ComingSoon,
+ privacy: None,
+ },
+ Capability {
+ id: "workflows.connect_google",
+ name: "Connect Google",
+ domain: "workflows",
+ category: CapabilityCategory::Workflows,
+ description: "Connect Google services for email, contacts, and calendar workflows.",
+ how_to: "Connections > OAuth",
+ status: CapabilityStatus::ComingSoon,
+ privacy: LOCAL_CREDENTIALS,
+ },
+ Capability {
+ id: "workflows.connect_notion",
+ name: "Connect Notion",
+ domain: "workflows",
+ category: CapabilityCategory::Workflows,
+ description: "Connect Notion for workspace sync and productivity workflows.",
+ how_to: "Connections > OAuth",
+ status: CapabilityStatus::ComingSoon,
+ privacy: LOCAL_CREDENTIALS,
+ },
+ Capability {
+ id: "workflows.connect_web3_wallet",
+ name: "Connect Web3 Wallet",
+ domain: "workflows",
+ category: CapabilityCategory::Workflows,
+ description: "Set up local EVM, BTC, Solana, and Tron wallet identities from one recovery phrase.",
+ how_to: "Settings > Crypto > Recovery Phrase or Connections",
+ status: CapabilityStatus::Beta,
+ privacy: LOCAL_CREDENTIALS,
+ },
+ Capability {
+ id: "workflows.wallet_execution",
+ name: "Wallet Execution Tools",
+ domain: "wallet",
+ category: CapabilityCategory::Workflows,
+ description: "Read addresses and balances, prepare/confirm/execute native + token transfers (ERC20/SPL/TRC20/BEP20), and inspect transactions (status, receipt, lookup) across the connected wallet (EVM, BTC, Solana, Tron). Quote-first; signing stays local.",
+ how_to: "Use wallet.* RPC methods (balances, prepare_transfer, execute_prepared, tx_status, tx_receipt, lookup_tx) via the agent or core_rpc_relay, or via Settings > Crypto > Wallet Balances.",
+ status: CapabilityStatus::Beta,
+ privacy: LOCAL_CREDENTIALS,
+ },
+ Capability {
+ id: "workflows.web3_defi",
+ name: "Web3 Swaps & Bridges",
+ domain: "web3",
+ category: CapabilityCategory::Workflows,
+ description: "Quote and execute cross-chain swaps and bridges (deBridge) plus generic EVM dapp contract calls, built on the local wallet's signing. EVM/Solana(/BTC); signing stays local.",
+ how_to: "Use web3_swap.* / web3_bridge.* / web3_dapp.* RPC methods (quote/execute, web3_swap.routes) via the agent or core_rpc_relay.",
+ status: CapabilityStatus::Beta,
+ privacy: LOCAL_CREDENTIALS,
+ },
+ Capability {
+ id: "workflows.x402_payments",
+ name: "x402 Machine Payments",
+ domain: "x402",
+ category: CapabilityCategory::Workflows,
+ description: "Automatic HTTP 402 payment handling for machine-payable APIs via the x402 protocol. When an API returns 402 Payment Required, the agent pays with USDC on Solana using the local wallet and retries. Budget enforcement with per-request, daily, and monthly caps.",
+ how_to: "Use x402.* RPC methods (get_summary, list_payments, update_budget) to manage spending. Payments happen automatically when the http_request tool encounters a 402 with a PAYMENT-REQUIRED header.",
+ status: CapabilityStatus::Beta,
+ privacy: LOCAL_CREDENTIALS,
+ },
+ Capability {
+ id: "workflows.connect_crypto_exchange",
+ name: "Connect Crypto Exchange",
+ domain: "workflows",
+ category: CapabilityCategory::Workflows,
+ description: "Connect supported exchanges for trading and portfolio workflows.",
+ how_to: "Connections",
+ status: CapabilityStatus::ComingSoon,
+ privacy: None,
+ },
+ Capability {
+ id: "local_ai.download_model",
+ name: "Download Local Models",
+ domain: "local_ai",
+ category: CapabilityCategory::LocalAI,
+ description: "Download and bootstrap local AI runtimes and model bundles.",
+ how_to: "Settings > Local AI Model",
+ status: CapabilityStatus::Beta,
+ privacy: MODEL_DOWNLOAD,
+ },
+ Capability {
+ id: "local_ai.configure_provider",
+ name: "Configure Local Provider",
+ domain: "local_ai",
+ category: CapabilityCategory::LocalAI,
+ description: "Select Ollama, LM Studio, MLX, or a generic local OpenAI-compatible server as the local model provider and configure the endpoint.",
+ how_to: "Connections → API keys → LLM, or use provider strings: ollama:<model>, lmstudio:<model>, mlx:<model>, local-openai:<model>",
+ status: CapabilityStatus::Beta,
+ privacy: None,
+ },
+ Capability {
+ id: "local_ai.manage_model_assets",
+ name: "Manage Model Assets",
+ domain: "local_ai",
+ category: CapabilityCategory::LocalAI,
+ description: "Inspect asset status and download specific chat, vision, embedding, STT, or TTS assets.",
+ how_to: "Settings > Local AI Model > Advanced > Capability Assets",
+ status: CapabilityStatus::Beta,
+ privacy: None,
+ },
+ Capability {
+ id: "local_ai.model_context_check",
+ name: "Model Context Requirement Check",
+ domain: "local_ai",
+ category: CapabilityCategory::LocalAI,
+ description: "Diagnostics report each installed Ollama model's native context window and reject any model below the minimum the memory layer requires (so short-context models can't silently truncate and corrupt recall).",
+ how_to: "Settings > Local AI Model > Run Diagnostics",
+ status: CapabilityStatus::Beta,
+ privacy: None,
+ },
+ Capability {
+ id: "local_ai.embed_text",
+ name: "Generate Text Embeddings",
+ domain: "local_ai",
+ category: CapabilityCategory::LocalAI,
+ description: "Create local vector embeddings for text input.",
+ how_to: "Settings > Local AI Model > Advanced > Test Embeddings",
+ status: CapabilityStatus::Beta,
+ privacy: LOCAL_RAW,
+ },
+ Capability {
+ id: "local_ai.text_to_speech",
+ name: "Text to Speech (Local)",
+ domain: "local_ai",
+ category: CapabilityCategory::LocalAI,
+ description:
+ "Synthesize speech locally with Piper via the voice TTS factory. PIPER_BIN points \
+ at the binary; the voice .onnx ships with the installer. Returns a synthetic \
+ viseme timeline (full forced-alignment lives behind the cloud provider for now).",
+ how_to: "Settings > Voice > TTS Provider = Piper",
+ status: CapabilityStatus::Beta,
+ privacy: None,
+ },
+ Capability {
+ id: "local_ai.vision_processing",
+ name: "Vision Processing",
+ domain: "local_ai",
+ category: CapabilityCategory::LocalAI,
+ description: "Run vision prompts against images using a local multimodal model.",
+ how_to: "Settings > Local AI Model > Advanced > Test Vision Prompt",
+ status: CapabilityStatus::Beta,
+ privacy: None,
+ },
+ Capability {
+ id: "local_ai.direct_prompting",
+ name: "Direct Model Prompting",
+ domain: "local_ai",
+ category: CapabilityCategory::LocalAI,
+ description: "Send a direct prompt to the local model without using the cloud API.",
+ how_to: "Settings > Local AI Model > Advanced > Test Custom Prompt",
+ status: CapabilityStatus::Beta,
+ privacy: None,
+ },
+ Capability {
+ id: "local_ai.piper_installer",
+ name: "Piper Installer (Local TTS)",
+ domain: "local_ai",
+ category: CapabilityCategory::LocalAI,
+ description:
+ "One-click download of the Piper binary archive and the bundled en_US-lessac-medium \
+ voice (.onnx + .onnx.json) into the workspace so local Text-to-Speech runs without \
+ manual setup. Atomic rename guarantees no half-written voice files are ever read \
+ by the runtime.",
+ how_to: "Settings > Voice > Voice Providers > Install Piper",
+ status: CapabilityStatus::Beta,
+ privacy: MODEL_DOWNLOAD,
+ },
+ Capability {
+ id: "local_ai.python_runtime_installer",
+ name: "Managed Python Runtime",
+ domain: "runtime_python",
+ category: CapabilityCategory::LocalAI,
+ description:
+ "Download and reuse an OpenHuman-managed CPython runtime for Python-backed local integrations such as MCP servers, with a system-Python override reserved for development.",
+ how_to: "Configured by the core `runtime_python` module; future UI surfaces can expose install state and overrides.",
+ status: CapabilityStatus::Beta,
+ privacy: MODEL_DOWNLOAD,
+ },
+ Capability {
+ id: "team.create",
+ name: "Create Teams",
+ domain: "team",
+ category: CapabilityCategory::Team,
+ description: "Create a team and start collaborating with shared billing and members.",
+ how_to: "Settings > Team",
+ status: CapabilityStatus::Stable,
+ privacy: None,
+ },
+ Capability {
+ id: "team.join_via_invite_code",
+ name: "Join Teams via Invite Code",
+ domain: "team",
+ category: CapabilityCategory::Team,
+ description: "Join an existing team using an invite code.",
+ how_to: "Invites > Redeem an Invite Code",
+ status: CapabilityStatus::Stable,
+ privacy: None,
+ },
+ Capability {
+ id: "team.switch_active_team",
+ name: "Switch Active Team",
+ domain: "team",
+ category: CapabilityCategory::Team,
+ description: "Switch which team is currently active in the app.",
+ how_to: "Settings > Team",
+ status: CapabilityStatus::Stable,
+ privacy: None,
+ },
+ Capability {
+ id: "team.leave",
+ name: "Leave Teams",
+ domain: "team",
+ category: CapabilityCategory::Team,
+ description: "Leave a team that you no longer want to participate in.",
+ how_to: "Settings > Team",
+ status: CapabilityStatus::Stable,
+ privacy: None,
+ },
+ Capability {
+ id: "team.manage_members",
+ name: "Manage Team Members",
+ domain: "team",
+ category: CapabilityCategory::Team,
+ description: "Review members and change team roles when you have permission.",
+ how_to: "Settings > Team > Manage team > Members",
+ status: CapabilityStatus::Stable,
+ privacy: None,
+ },
+ Capability {
+ id: "team.generate_invite_codes",
+ name: "Generate Invite Codes",
+ domain: "team",
+ category: CapabilityCategory::Team,
+ description: "Create invite codes to bring new members into a team.",
+ how_to: "Settings > Team > Manage team > Invites",
+ status: CapabilityStatus::Stable,
+ privacy: None,
+ },
+ Capability {
+ id: "team.track_invite_usage",
+ name: "Track Invite Usage",
+ domain: "team",
+ category: CapabilityCategory::Team,
+ description: "View invite usage counts, limits, and revoke team invites.",
+ how_to: "Settings > Team > Manage team > Invites",
+ status: CapabilityStatus::Stable,
+ privacy: None,
+ },
+ Capability {
+ id: "auth.login_oauth",
+ name: "Login via OAuth",
+ domain: "auth",
+ category: CapabilityCategory::Auth,
+ description: "Sign in with the app's supported provider-based authentication flow.",
+ how_to: "Welcome",
+ status: CapabilityStatus::Stable,
+ privacy: None,
+ },
+ Capability {
+ id: "auth.onboarding_setup",
+ name: "Onboarding Setup",
+ domain: "auth",
+ category: CapabilityCategory::Auth,
+ description: "Walk through onboarding to configure initial permissions and preferences.",
+ how_to: "Onboarding",
+ status: CapabilityStatus::Stable,
+ privacy: None,
+ },
+ Capability {
+ id: "auth.configure_tool_access",
+ name: "Configure Tool Access",
+ domain: "auth",
+ category: CapabilityCategory::Auth,
+ description: "Choose which built-in tools OpenHuman can use on your behalf during setup.",
+ how_to: "Onboarding > Enable Tools",
+ status: CapabilityStatus::Stable,
+ privacy: None,
+ },
+ Capability {
+ id: "auth.backup_recovery_phrase",
+ name: "Back Up Recovery Phrase",
+ domain: "auth",
+ category: CapabilityCategory::Auth,
+ description: "Generate and save a recovery phrase used to secure and restore encrypted app data.",
+ how_to: "Onboarding > Recovery Phrase",
+ status: CapabilityStatus::Stable,
+ privacy: None,
+ },
+ Capability {
+ id: "auth.import_recovery_phrase",
+ name: "Import Recovery Phrase",
+ domain: "auth",
+ category: CapabilityCategory::Auth,
+ description: "Import an existing recovery phrase to restore encrypted app data.",
+ how_to: "Onboarding > Recovery Phrase > I already have a recovery phrase",
+ status: CapabilityStatus::Stable,
+ privacy: None,
+ },
+ Capability {
+ id: "auth.logout",
+ name: "Logout",
+ domain: "auth",
+ category: CapabilityCategory::Auth,
+ description: "Sign out of the current session.",
+ how_to: "Settings > Log out",
+ status: CapabilityStatus::Stable,
+ privacy: None,
+ },
+ Capability {
+ id: "channels.connect_platform",
+ name: "Connect Messaging Platforms",
+ domain: "channels",
+ category: CapabilityCategory::Channels,
+ description: "Connect supported messaging platforms such as Telegram or Discord.",
+ how_to: "Connections > Channels",
+ status: CapabilityStatus::Beta,
+ privacy: None,
+ },
+ Capability {
+ id: "channels.telegram_remote_control",
+ name: "Telegram Remote Control",
+ domain: "channels",
+ category: CapabilityCategory::Channels,
+ description:
+ "Operate OpenHuman from Telegram with slash commands: /status, /sessions, /new, and /help.",
+ how_to: "Connections > Channels > Telegram (connect), then message the bot",
+ status: CapabilityStatus::Beta,
+ privacy: None,
+ },
+ Capability {
+ id: "channels.disconnect_platform",
+ name: "Disconnect Messaging Platforms",
+ domain: "channels",
+ category: CapabilityCategory::Channels,
+ description: "Disconnect a previously configured messaging platform.",
+ how_to: "Connections > Channels",
+ status: CapabilityStatus::Beta,
+ privacy: None,
+ },
+ Capability {
+ id: "channels.test_credentials",
+ name: "Test Channel Credentials",
+ domain: "channels",
+ category: CapabilityCategory::Channels,
+ description: "Validate platform credentials or connection state before using a channel.",
+ how_to: "Connections > Channels",
+ status: CapabilityStatus::Beta,
+ privacy: None,
+ },
+ Capability {
+ id: "channels.set_default_channel",
+ name: "Set Default Messaging Channel",
+ domain: "channels",
+ category: CapabilityCategory::Channels,
+ description: "Choose which messaging channel should be used by default.",
+ how_to: "Connections > Channels",
+ status: CapabilityStatus::Beta,
+ privacy: None,
+ },
+ Capability {
+ id: "channels.whatsapp_read_messages",
+ name: "Read WhatsApp Messages",
+ domain: "channels",
+ category: CapabilityCategory::Channels,
+ description: "Read and search WhatsApp Web conversations and messages after connecting WhatsApp in OpenHuman. Data is stored locally only and never transmitted.",
+ how_to: "Connect WhatsApp Web via Channels, then ask the agent to read or summarise your messages.",
+ status: CapabilityStatus::Beta,
+ privacy: LOCAL_RAW,
+ },
+ Capability {
+ id: "channels.mcp_registry_browse",
+ name: "Browse MCP Server Registry",
+ domain: "channels",
+ category: CapabilityCategory::Channels,
+ description: "Search and discover MCP servers from the Smithery.ai and official modelcontextprotocol registries.",
+ how_to: "Skills > MCP > Browse catalog",
+ status: CapabilityStatus::Beta,
+ privacy: Some(CapabilityPrivacy {
+ leaves_device: true,
+ data_kind: PrivacyDataKind::Metadata,
+ destinations: &["Smithery.ai registry API", "modelcontextprotocol registry API"],
+ }),
+ },
+ Capability {
+ id: "channels.mcp_server_install",
+ name: "Install MCP Servers",
+ domain: "channels",
+ category: CapabilityCategory::Channels,
+ description: "Install MCP servers locally — both local stdio subprocesses and hosted HTTP-remote servers. Required env vars are stored encrypted and never included in logs or responses. Can also be done conversationally via the MCP setup assistant.",
+ how_to: "Skills > MCP > Browse catalog > Install, or ask the assistant to \"set up the <name> MCP server\"",
+ status: CapabilityStatus::Beta,
+ privacy: LOCAL_CREDENTIALS,
+ },
+ Capability {
+ id: "channels.mcp_server_connect",
+ name: "Connect / Reconfigure MCP Servers",
+ domain: "channels",
+ category: CapabilityCategory::Channels,
+ description: "Spawn and manage MCP server connections (stdio subprocess or HTTP-remote). Reconfigure stored env vars and reconnect without uninstalling.",
+ how_to: "Skills > MCP > select a server > Connect / Reconfigure",
+ status: CapabilityStatus::Beta,
+ privacy: Some(CapabilityPrivacy {
+ leaves_device: true,
+ data_kind: PrivacyDataKind::Derived,
+ destinations: &["Configured MCP endpoint(s)"],
+ }),
+ },
+ Capability {
+ id: "channels.mcp_tool_call",
+ name: "Invoke MCP Server Tools",
+ domain: "channels",
+ category: CapabilityCategory::Channels,
+ description: "Call tools exposed by connected MCP servers. Tools are surfaced to the agent and runnable from the tool playground.",
+ how_to: "Skills > MCP > select a connected server > Tools > Try, or ask the assistant in Chat",
+ status: CapabilityStatus::Beta,
+ privacy: Some(CapabilityPrivacy {
+ leaves_device: true,
+ data_kind: PrivacyDataKind::Derived,
+ destinations: &["Configured MCP endpoint(s)"],
+ }),
+ },
+ Capability {
+ id: "settings.configure_ai",
+ name: "Configure AI",
+ domain: "settings",
+ category: CapabilityCategory::Settings,
+ description: "Configure managed, local, custom, and built-in BYOK LLM providers, including SumoPod and other OpenAI-compatible gateways, plus per-workload routing preferences.",
+ how_to: "Connections → API keys → LLM",
+ status: CapabilityStatus::Stable,
+ privacy: None,
+ },
+ Capability {
+ id: "settings.core_connection",
+ name: "Run the Core Somewhere Else",
+ domain: "settings",
+ category: CapabilityCategory::Settings,
+ description: "Choose where the OpenHuman core runs: inside this app, at a URL \
+ you point it at, in a Docker container, on another machine over SSH, or in a \
+ container on another machine. OpenHuman starts the core, connects to it, and \
+ shuts it down when you switch away. Where it runs and what contains it are \
+ separate choices, so SSH and Docker combine without being a third option.",
+ how_to: "Settings > Core connection",
+ status: CapabilityStatus::Beta,
+ privacy: Some(CapabilityPrivacy {
+ leaves_device: true,
+ data_kind: PrivacyDataKind::Raw,
+ // `Raw`, because everything the core holds - the conversations
+ // themselves, memory, stored credentials - lives wherever the core
+ // runs. Choosing a machine over SSH is choosing to put all of it
+ // there. That is the disclosure that matters here and the one a
+ // hostname field makes easy to overlook, so it is stated at the
+ // strongest kind rather than softened to `Derived`.
+ destinations: &["The machine you configure, when the core runs off this device"],
+ }),
+ },
+ Capability {
+ id: "settings.persona_pack",
+ name: "Persona Pack",
+ domain: "settings",
+ category: CapabilityCategory::Settings,
+ description: "Personalize the assistant across one or more agent profiles: set a display name and description, edit or reset each profile's SOUL.md identity (kept in its own home under personalities/<id>/ and re-read every message), give a profile its own dedicated memory subtree or its own working directory, drop private skills under personalities/<id>/skills/ that only that profile can discover, attribute a scheduled cron job to a profile so it runs with that profile's identity, memory, and permissions, and reach mascot avatar and voice settings. Multiple profiles can run with isolated identity, memory, skills, and workspace state.",
+ how_to: "Settings > Persona",
+ status: CapabilityStatus::Beta,
+ privacy: GITHUB_MASCOT_MANIFEST,
+ },
+ Capability {
+ id: "settings.manage_privacy_analytics",
+ name: "Manage Privacy and Analytics",
+ domain: "settings",
+ category: CapabilityCategory::Settings,
+ description: "Control privacy, analytics, and related data handling preferences. \
+ When enabled, anonymous crash reports are sent to Sentry and anonymous usage \
+ analytics (page views, feature engagement) are sent to Google Analytics. \
+ No personal data, messages, or credentials are ever included.",
+ how_to: "Settings > Privacy (direct route)",
+ status: CapabilityStatus::Stable,
+ privacy: DIAGNOSTICS_TO_BACKEND,
+ },
+ Capability {
+ id: "settings.view_billing",
+ name: "View Billing",
+ domain: "settings",
+ category: CapabilityCategory::Settings,
+ description: "Open subscription, included usage, and pay-as-you-go billing views for your active team.",
+ how_to: "Settings > Billing & Usage",
+ status: CapabilityStatus::Stable,
+ privacy: None,
+ },
+ Capability {
+ id: "settings.manage_subscription_plan",
+ name: "Manage Subscription Plan",
+ domain: "settings",
+ category: CapabilityCategory::Settings,
+ description: "Upgrade plans or open the billing portal to manage subscription-backed usage tiers.",
+ how_to: "Settings > Billing & Usage",
+ status: CapabilityStatus::Stable,
+ privacy: None,
+ },
+ Capability {
+ id: "settings.manage_credits",
+ name: "Manage Credits",
+ domain: "settings",
+ category: CapabilityCategory::Settings,
+ description: "View pay-as-you-go credit balances, top up overage credits, and configure auto-recharge.",
+ how_to: "Settings > Billing & Usage",
+ status: CapabilityStatus::Stable,
+ privacy: None,
+ },
+ Capability {
+ id: "settings.add_payment_methods",
+ name: "Add Payment Methods",
+ domain: "settings",
+ category: CapabilityCategory::Settings,
+ description: "Add or manage saved payment methods for billing and auto-recharge.",
+ how_to: "Settings > Billing & Usage > Payment Methods",
+ status: CapabilityStatus::Stable,
+ privacy: None,
+ },
+];
diff --git a/src/openhuman/platform/about_app/catalog_part_03.rs b/src/openhuman/platform/about_app/catalog_part_03.rs
new file mode 100644
index 0000000000..8568616fd7
--- /dev/null
+++ b/src/openhuman/platform/about_app/catalog_part_03.rs
@@ -0,0 +1,361 @@
+use super::*;
+
+pub(super) const CAPABILITIES: &[Capability] = &[
+Capability {
+ id: "settings.developer_options",
+ name: "Developer Options",
+ domain: "settings",
+ category: CapabilityCategory::Settings,
+ description: "Open developer-focused panels for diagnostics, workflows, AI config, and memory tools.",
+ how_to: "Settings > Developer Options",
+ status: CapabilityStatus::Beta,
+ privacy: None,
+ },
+ Capability {
+ id: "settings.debug_webhooks",
+ name: "Debug Webhooks",
+ domain: "settings",
+ category: CapabilityCategory::Settings,
+ description:
+ "Inspect Composio trigger history and find the daily JSONL archive files stored by the app.",
+ how_to: "Settings > Developer Options > Webhooks",
+ status: CapabilityStatus::Beta,
+ privacy: None,
+ },
+ Capability {
+ id: "settings.manage_service",
+ name: "Manage Desktop Service",
+ domain: "settings",
+ category: CapabilityCategory::Settings,
+ description: "Install, start, stop, restart, uninstall, or inspect the optional desktop background service.",
+ how_to: "Settings > Developer Options > Tauri Commands",
+ status: CapabilityStatus::Stable,
+ privacy: None,
+ },
+ Capability {
+ id: "settings.clear_app_data",
+ name: "Log Out and Clear App Data",
+ domain: "settings",
+ category: CapabilityCategory::Settings,
+ description: "Sign out and permanently clear local app data, including workflow data.",
+ how_to: "Settings > Log Out & Clear App Data",
+ status: CapabilityStatus::Stable,
+ privacy: None,
+ },
+ Capability {
+ id: "settings.delete_all_data",
+ name: "Delete All Data",
+ domain: "settings",
+ category: CapabilityCategory::Settings,
+ description: "Delete all local data and reset the app from the destructive settings section.",
+ how_to: "Settings > Delete All Data",
+ status: CapabilityStatus::ComingSoon,
+ privacy: None,
+ },
+ Capability {
+ id: "automation.task_sources",
+ name: "Task Sources",
+ domain: "automation",
+ category: CapabilityCategory::Automation,
+ description: "Pull work items from GitHub, Notion, Linear, and ClickUp using per-source \
+ filters, then enrich them onto the agent's todo board and (for proactive \
+ sources) start an agent working on them.",
+ how_to: "Settings > Task Sources",
+ status: CapabilityStatus::Beta,
+ privacy: DERIVED_TO_BACKEND,
+ },
+ Capability {
+ id: "automation.discover_workflows",
+ name: "Suggested Workflows (Flow Scout)",
+ domain: "flows",
+ category: CapabilityCategory::Automation,
+ description: "A read-only discovery agent (\"Flow Scout\") reads your memory, past \
+ conversations, known people, connected apps, and existing flows to figure \
+ out which automations would actually help you, then proposes a handful of \
+ concrete, buildable workflow suggestions. Each card explains why it was \
+ suggested; \"Build this\" hands it to the workflow builder to author a real \
+ flow you review and save. Discovery never creates, enables, or runs a flow.",
+ how_to: "Flows > Suggested for you > Discover",
+ status: CapabilityStatus::Beta,
+ privacy: DERIVED_TO_BACKEND,
+ },
+ Capability {
+ id: "automation.flow_memory_node",
+ name: "Memory Node (Flows)",
+ domain: "flows",
+ category: CapabilityCategory::Automation,
+ description: "A `memory` node inside a saved workflow graph, giving the flow direct, \
+ in-graph memory access with no agent turn involved. It can recall/search/ \
+ read style-flavour/look up people from your durable, cross-flow memory \
+ (read-only — a flow can never write there) or from other flows' own \
+ memory (also read-only), and can remember/forget entries in its OWN \
+ private, flow-scoped memory namespace — never the user's personal memory, \
+ never another flow's. Every operation is gated by the flow's autonomy \
+ tier; a flow-scoped write can require human approval.",
+ how_to: "Flows editor > add a `memory` node; set `config.operation` and `config.scope`.",
+ status: CapabilityStatus::Beta,
+ privacy: LOCAL_RAW,
+ },
+ Capability {
+ id: "automation.flow_dedup_node",
+ name: "Dedup Node (Flows)",
+ domain: "flows",
+ category: CapabilityCategory::Automation,
+ description: "A `dedup` node inside a saved workflow graph, giving the flow durable \
+ exactly-once processing per item with no agent turn or extra plumbing \
+ involved. It drops an item whose per-item key was already committed by a \
+ prior successful run, and otherwise passes it through. Committing happens \
+ automatically: keys the node passes through are marked done only once the \
+ whole run finishes successfully; a failed/cancelled/interrupted/unknown (or \
+ any other non-success) run leaves them unmarked so the same items retry next \
+ time. Only the resolved per-item key value is stored, locally, in the flow's \
+ own private, flow-scoped state — never the item's full content, and never \
+ the user's personal memory. The key is whatever the workflow author's \
+ `config.key` expression resolves to, so it can carry item-derived data if \
+ keyed off a sensitive field — author flows to key off an opaque, \
+ non-sensitive stable id (an issue number, message id, url) rather than \
+ personal data.",
+ how_to: "Flows editor > add a `dedup` node right after the item source; set config.key \
+ to a stable per-item id expression, e.g. \"=item.id\".",
+ status: CapabilityStatus::Beta,
+ privacy: LOCAL_RAW,
+ },
+ Capability {
+ id: "automation.view_cron_jobs",
+ name: "View Cron Jobs",
+ domain: "automation",
+ category: CapabilityCategory::Automation,
+ description: "Review scheduled jobs available to the runtime.",
+ how_to: "Settings > Cron Jobs",
+ status: CapabilityStatus::Stable,
+ privacy: None,
+ },
+ Capability {
+ id: "automation.set_job_intervals",
+ name: "Set Job Intervals",
+ domain: "automation",
+ category: CapabilityCategory::Automation,
+ description: "Configure how often a scheduled job should run.",
+ how_to: "Settings > Cron Jobs",
+ status: CapabilityStatus::Stable,
+ privacy: None,
+ },
+ Capability {
+ id: "automation.view_execution_history",
+ name: "View Execution History",
+ domain: "automation",
+ category: CapabilityCategory::Automation,
+ description: "Inspect past runs and results for scheduled jobs.",
+ how_to: "Settings > Cron Jobs",
+ status: CapabilityStatus::Beta,
+ privacy: None,
+ },
+ // ── Proactive agents ─────────────────────────────────────────────────────
+ Capability {
+ id: "automation.morning_briefing",
+ name: "Morning Briefing",
+ domain: "automation",
+ category: CapabilityCategory::Automation,
+ description: "Daily proactive agent that reviews calendar, tasks, emails, and market context to deliver a morning summary.",
+ how_to: "Automatic after onboarding (runs daily at 7 AM). Adjust schedule via Settings > Cron Jobs.",
+ status: CapabilityStatus::Beta,
+ privacy: None,
+ },
+ Capability {
+ id: "automation.crypto_agent",
+ name: "Crypto Agent",
+ domain: "automation",
+ category: CapabilityCategory::Automation,
+ description: "Dedicated wallet & market specialist sub-agent. The orchestrator \
+ routes transfers, swaps, contract calls, balance lookups, and \
+ exchange trading requests here. The agent enforces a read → \
+ simulate → confirm → execute flow, refuses to fabricate chain ids \
+ or token addresses, and gates every write call behind explicit \
+ user confirmation.",
+ how_to: "Automatic — invoked by the orchestrator when a crypto wallet or market action is requested. Connect a wallet via Settings > Recovery Phrase first.",
+ status: CapabilityStatus::Beta,
+ privacy: LOCAL_CREDENTIALS,
+ },
+ // ── Update ──────────────────────────────────────────────────────────────
+ // ── Mobile (iOS client) ─────────────────────────────────────────────────
+ Capability {
+ id: "mobile.device_pairing",
+ name: "Device Pairing",
+ domain: "devices",
+ category: CapabilityCategory::Mobile,
+ description: "Pair iOS phones with the desktop core via QR code. The desktop generates a \
+ short-lived pairing token; the iOS app scans the QR, completes an X25519 \
+ key agreement, and stores the session for reconnects.",
+ how_to: "Settings > Devices > Pair iPhone",
+ status: CapabilityStatus::Beta,
+ privacy: None,
+ },
+ Capability {
+ id: "mobile.ios_client",
+ name: "iOS Client",
+ domain: "devices",
+ category: CapabilityCategory::Mobile,
+ description: "iOS app for chatting with your assistant on the go. Connects to the desktop \
+ core via LAN HTTP, an E2E-encrypted socket.io tunnel, or a cloud HTTP \
+ fallback — no Rust core ships on the device.",
+ how_to: "Pair via Settings > Devices, then open the OpenHuman iOS app.",
+ status: CapabilityStatus::Beta,
+ privacy: None,
+ },
+ Capability {
+ id: "mobile.push_to_talk",
+ name: "Push-to-Talk",
+ domain: "devices",
+ category: CapabilityCategory::Mobile,
+ description: "Hold-to-talk voice input on iOS. Activates AVAudioEngine and \
+ SFSpeechRecognizer on the device; partial transcripts appear while \
+ speaking and the final transcript is sent as a chat message.",
+ how_to: "Hold the microphone button on the iOS mascot screen.",
+ status: CapabilityStatus::Beta,
+ privacy: Some(CapabilityPrivacy {
+ leaves_device: false,
+ data_kind: PrivacyDataKind::Raw,
+ destinations: &[],
+ }),
+ },
+ // ── Update ──────────────────────────────────────────────────────────────
+ Capability {
+ id: "update.check",
+ name: "Check for Core Updates",
+ domain: "update",
+ category: CapabilityCategory::Settings,
+ description: "Query GitHub Releases to see if a newer core binary is available. \
+ Available to the orchestrator agent as the `update_check` tool so the \
+ user can ask 'am I up to date?' in chat.",
+ how_to: "Settings > Developer Options > Check for Updates, or ask the orchestrator in chat.",
+ status: CapabilityStatus::Beta,
+ privacy: GITHUB_RELEASES_METADATA,
+ },
+ Capability {
+ id: "update.apply",
+ name: "Apply Core Update",
+ domain: "update",
+ category: CapabilityCategory::Settings,
+ description: "Download and stage a newer core binary. Desktop builds can self-restart; \
+ headless deployments can hand restart off to a supervisor. Exposed to \
+ the orchestrator agent as the `update_apply` tool, gated behind explicit \
+ user consent (the agent must confirm via `ask_user_clarification` before \
+ invoking) and the `config.update.rpc_mutations_enabled` policy switch.",
+ how_to: "Settings > Developer Options > Apply Update, or confirm an in-chat update prompt from the orchestrator.",
+ status: CapabilityStatus::Beta,
+ privacy: GITHUB_RELEASES_METADATA,
+ },
+ Capability {
+ id: "filesystem.access_mode",
+ name: "Agent OS Access Mode",
+ domain: "security",
+ category: CapabilityCategory::Settings,
+ description: "Choose how much filesystem and shell access the agent has: Read-Only, \
+ Workspace, Trusted Roots (grant specific folders outside the workspace), \
+ or Full Access. Credential stores stay blocked in every mode.",
+ how_to: "Settings → Agent OS access",
+ status: CapabilityStatus::Stable,
+ privacy: None,
+ },
+ Capability {
+ id: "agent.action_timeout",
+ name: "Action Timeout",
+ domain: "agent",
+ category: CapabilityCategory::Settings,
+ description: "Set how long a single tool or action may run before it is cancelled \
+ (1–3600 seconds, default 120). Increase it when a large local model is \
+ interrupted before finishing its response. Applies to the next tool call \
+ without a restart; the OPENHUMAN_TOOL_TIMEOUT_SECS env var still overrides it.",
+ how_to: "Settings → Agent OS access → Action timeout",
+ status: CapabilityStatus::Stable,
+ privacy: None,
+ },
+ Capability {
+ id: "security.always_allow_tool",
+ name: "Always Allow a Tool",
+ domain: "security",
+ category: CapabilityCategory::Settings,
+ description: "On an approval prompt, choose \"Always allow\" to stop being asked for that \
+ tool. The choice is saved to your allow-list and persists across restarts; \
+ remove it any time under Settings → Agent OS access to be prompted again. \
+ Policy still blocks forbidden paths and high-risk commands regardless.",
+ how_to: "Click \"Always allow\" on an approval prompt; manage the list in Settings → Agent OS access.",
+ status: CapabilityStatus::Stable,
+ privacy: None,
+ },
+ Capability {
+ id: "security.approval_history",
+ name: "Approval History",
+ domain: "security",
+ category: CapabilityCategory::Settings,
+ description: "Review a read-only audit trail of past tool-approval decisions \
+ (Approve once / Always allow / Deny), newest first. Summaries are \
+ scrubbed of chat content and arguments are shown as redacted shape only.",
+ how_to: "Settings → Agent OS access → View approval history",
+ status: CapabilityStatus::Stable,
+ privacy: None,
+ },
+ Capability {
+ id: "tool.detect_tools",
+ name: "Detect Installed Tools",
+ domain: "tools",
+ category: CapabilityCategory::Settings,
+ description: "Probe the host PATH to report which developer tools and language \
+ runtimes are installed (node, python, cargo, docker, git, …).",
+ how_to: "Used by the agent automatically; gated by the tool toggle list.",
+ status: CapabilityStatus::Stable,
+ privacy: None,
+ },
+ Capability {
+ id: "tool.install_tool",
+ name: "Install OS Packages",
+ domain: "tools",
+ category: CapabilityCategory::Settings,
+ description: "Install OS or language packages (apt/dnf/brew/winget/pipx/npm/cargo). \
+ High impact: only available when Full access / tool installation is enabled.",
+ how_to: "Enable in Settings → Agent OS access (Full access mode).",
+ status: CapabilityStatus::Beta,
+ privacy: None,
+ },
+ Capability {
+ id: "security.action_sandbox",
+ name: "Action Sandbox",
+ domain: "security",
+ category: CapabilityCategory::Settings,
+ description: "Dedicated action directory for agent tools (shell, file, git), separate \
+ from internal application state. Agent tools default their working directory \
+ and path resolution to the action sandbox, preventing accidental modification \
+ of memory databases, session transcripts, tokens, and other internal state.",
+ how_to: "Settings → Agent OS access",
+ status: CapabilityStatus::Stable,
+ privacy: None,
+ },
+ Capability {
+ id: "security.sandbox_backends",
+ name: "Sandbox Execution Backends",
+ domain: "security",
+ category: CapabilityCategory::Settings,
+ description: "Route agent tool execution (shell, filesystem, process) through sandbox \
+ backends — Docker containers or OS-level jails (Landlock/Seatbelt) — for \
+ reduced blast radius on remote, channel, cron, or background sessions. \
+ Configurable per agent/session/channel with safe defaults for non-main sessions.",
+ how_to: "Set sandbox_mode = \"sandboxed\" in agent.toml, or configure runtime.kind = \
+ \"docker\" in the TOML config. Use openhuman.sandbox_status / \
+ openhuman.sandbox_resolve_policy RPC to inspect.",
+ status: CapabilityStatus::Beta,
+ privacy: None,
+ },
+ Capability {
+ id: "intelligence.remember_preferences",
+ name: "Remember Preferences",
+ domain: "memory",
+ category: CapabilityCategory::Intelligence,
+ description: "Remember preferences you state in chat and apply them automatically — \
+ general preferences shape every reply (tone, language, standing habits); \
+ situational ones surface only when relevant to your current message.",
+ how_to: "State a preference in chat, e.g. \"always reply in British English\" or \
+ \"when writing Rust, prefer Result over unwrap\".",
+ status: CapabilityStatus::Stable,
+ privacy: LOCAL_RAW,
+ },
+];
diff --git a/src/openhuman/security/approval/gate.rs b/src/openhuman/security/approval/gate.rs
index 350ba779c8..b738318b96 100644
--- a/src/openhuman/security/approval/gate.rs
+++ b/src/openhuman/security/approval/gate.rs
@@ -260,1112 +260,9 @@ impl Drop for WaiterGuard<'_> {
}
}
-impl ApprovalGate {
- /// Install the process-global gate. Returns the existing gate if
- /// one was already installed (re-install is a no-op so repeated
- /// `bootstrap_core_runtime` calls in tests don't panic).
- ///
- /// Rows from prior launches are intentionally NOT purged on
- /// install — the issue #1339 acceptance criterion requires they
- /// survive restart so the UI can show / dismiss them. Orphan
- /// rows have no live parked future, so a `decide` is a DB-only
- /// audit update; no side effect can fire across processes.
- pub fn init_global(config: Config, session_id: impl Into<String>) -> Arc<ApprovalGate> {
- let session_id = session_id.into();
- if let Some(existing) = GLOBAL_GATE.get() {
- return existing.clone();
- }
- let gate = Arc::new(ApprovalGate::new(config, session_id, DEFAULT_APPROVAL_TTL));
- let _ = GLOBAL_GATE.set(gate.clone());
- GLOBAL_GATE.get().cloned().unwrap_or(gate)
- }
-
- /// Returns the global gate when installed; tools and harness
- /// branches that don't care about supervised mode treat `None`
- /// as "no gating".
- pub fn try_global() -> Option<Arc<ApprovalGate>> {
- GLOBAL_GATE.get().cloned()
- }
-
- fn new(config: Config, session_id: String, ttl: Duration) -> Self {
- // Regression guard: the gate's session_id must be the per-launch
- // UUID minted by `bootstrap_core_runtime` (shape:
- // `session-<uuid>`). Any other shape risks re-introducing the
- // credential leak that was fixed by switching off the RPC bearer
- // — fail loudly in debug builds the moment a caller wires up a
- // raw token (or any other ad-hoc string).
- #[cfg(debug_assertions)]
- debug_assert!(
- session_id.starts_with("session-"),
- "ApprovalGate session_id must be a per-launch UUID prefix, not a credential",
- );
- Self {
- config,
- session_id,
- ttl,
- waiters: Mutex::new(HashMap::new()),
- thread_to_request: Mutex::new(HashMap::new()),
- }
- }
-
- /// TTL for parking an approval. In debug builds `OPENHUMAN_APPROVAL_TTL_SECS`
- /// overrides the boot-time default per intercept so E2E tests can exercise
- /// the timeout path without waiting the full `DEFAULT_APPROVAL_TTL`.
- ///
- /// The override is compiled out of release builds (`#[cfg(debug_assertions)]`):
- /// the shipped product never reads this env var, so a hostile process
- /// environment cannot shorten the supervised-mode approval window. This
- /// mirrors the host-aware discipline of the `OPENHUMAN_APPROVAL_GATE`
- /// kill-switch — neither override can make the gate fail open; the timeout
- /// path always denies.
- fn effective_ttl(&self) -> Duration {
- #[cfg(debug_assertions)]
- if let Some(ttl) = std::env::var("OPENHUMAN_APPROVAL_TTL_SECS")
- .ok()
- .and_then(|v| v.parse::<u64>().ok())
- .map(Duration::from_secs)
- {
- tracing::debug!(
- ttl_secs = ttl.as_secs(),
- "[approval::gate] TTL env override active (debug build)"
- );
- return ttl;
- }
- self.ttl
- }
-
- /// Resolve the actual park duration from the gate's own `effective_ttl`
- /// plus the `copilot_stream` clamp ([`COPILOT_APPROVAL_TTL`]) when that
- /// origin is active. A clamp only ever *shortens* the park — it can never
- /// extend `effective_ttl` past what the gate itself allows (e.g. a debug
- /// env override). Split out (rather than inlined at the call site) so it is
- /// unit testable without needing to actually park a future.
- fn resolve_park_ttl(effective_ttl: Duration, copilot_stream: bool) -> Duration {
- let mut ttl = effective_ttl;
- if copilot_stream {
- ttl = ttl.min(COPILOT_APPROVAL_TTL);
- }
- ttl
- }
-
- /// Whether `tool_name` is on the user's "Always allow" list. Prefers the
- /// process-global live policy (so a grant made this session is seen
- /// immediately) and falls back to the gate's boot-time config snapshot.
- fn tool_is_auto_approved(&self, tool_name: &str) -> bool {
- if let Some(policy) = crate::openhuman::security::live_policy::current() {
- return policy.auto_approve.iter().any(|t| t == tool_name);
- }
- self.config
- .autonomy
- .auto_approve
- .iter()
- .any(|t| t == tool_name)
- }
-
- /// Whether the user has opted into "auto-approve everything" — a
- /// blanket bypass of the human approval prompt. Mirrors
- /// [`Self::tool_is_auto_approved`]'s live-policy-first, boot-config-
- /// fallback pattern so a toggle made this session (config save + live
- /// policy reload) takes effect on the very next tool call.
- ///
- /// Callers MUST still exclude `TrustedAutomationSource::SubconsciousTainted`
- /// and `AgentTurnOrigin::Unknown` before trusting this flag — see the
- /// `matches!` guard at the call site below. This method only reports the
- /// user's setting; it does not know about origin.
- fn is_auto_approve_all_enabled(&self) -> bool {
- if let Some(policy) = crate::openhuman::security::live_policy::current() {
- return policy.auto_approve_all;
- }
- self.config.autonomy.auto_approve_all
- }
-
- /// Intercept a tool call. Blocks until the user decides or the
- /// TTL elapses (timeout → `Deny`).
- ///
- /// Use [`Self::intercept_audited`] instead when the caller can
- /// also record the *terminal* status of the tool — the audit
- /// trail in `pending_approvals` only carries before-and-after
- /// rows when both sides report in. See #2135.
- pub async fn intercept(
- &self,
- tool_name: &str,
- action_summary: &str,
- args_redacted: serde_json::Value,
- ) -> GateOutcome {
- // Drop the request_id; callers using the legacy entry point
- // don't record execution.
- self.intercept_audited(tool_name, action_summary, args_redacted)
- .await
- .0
- }
-
- /// Audited variant of [`Self::intercept`].
- ///
- /// Returns `(outcome, Some(request_id))` when the call was
- /// allowed AND a `pending_approvals` row was persisted — pass
- /// the id back to [`Self::record_execution`] once the tool
- /// finishes so the audit row carries both the approval and the
- /// terminal status (issue #2135).
- ///
- /// Returns `(outcome, None)` when no DB row was created (session
- /// allowlist shortcut) OR when the call was denied. In either
- /// case there is nothing to record afterward, so the caller can
- /// pattern-match `(GateOutcome::Allow, Some(id))` to decide
- /// whether to invoke `record_execution`.
- pub async fn intercept_audited(
- &self,
- tool_name: &str,
- action_summary: &str,
- args_redacted: serde_json::Value,
- ) -> (GateOutcome, Option<String>) {
- // No caller-supplied park bound: identical behavior to before. With
- // `park_bound = None` the inner never takes the caller-bound abandon
- // path, so the out-flag stays `false` and is discarded here.
- let mut _park_bound_elapsed = false;
- self.intercept_audited_inner(
- tool_name,
- action_summary,
- args_redacted,
- None,
- &mut _park_bound_elapsed,
- )
- .await
- }
-
- /// Like [`Self::intercept_audited`] but the caller may cap how long the
- /// gate parks (issue #4756).
- ///
- /// When `park_bound` is `Some` and shorter than the gate's own effective
- /// TTL and it elapses before a decision arrives, the gate abandons the park
- /// in a **cancellation-safe** way — it evicts the in-memory waiter and
- /// clears the thread routing mapping (so a later chat reply
- /// is not mis-routed to this now-abandoned request) but deliberately LEAVES
- /// the `pending_approvals` row open, so a later human card-click can still
- /// resolve it in the DB — and returns `None`. This is why callers must bound
- /// the park through the gate rather than racing an outer
- /// `tokio::time::timeout` against [`Self::intercept_audited`]: dropping the
- /// parked future would skip that cleanup and orphan the waiter + routing
- /// mappings (chatgpt-codex review on #4756).
- ///
- /// A `None` bound (or one `>=` the effective TTL) behaves exactly like
- /// [`Self::intercept_audited`] and always returns `Some`.
- pub async fn intercept_audited_bounded(
- &self,
- tool_name: &str,
- action_summary: &str,
- args_redacted: serde_json::Value,
- park_bound: Option<Duration>,
- ) -> Option<(GateOutcome, Option<String>)> {
- let mut park_bound_elapsed = false;
- let resolved = self
- .intercept_audited_inner(
- tool_name,
- action_summary,
- args_redacted,
- park_bound,
- &mut park_bound_elapsed,
- )
- .await;
- if park_bound_elapsed {
- None
- } else {
- Some(resolved)
- }
- }
-
- /// Shared core of [`Self::intercept_audited`] and
- /// [`Self::intercept_audited_bounded`]. When `park_bound` is `Some` and
- /// shorter than the effective TTL, the park is capped at it; on that bound
- /// elapsing the park is abandoned cancellation-safely (waiter evicted,
- /// thread routing cleared, `pending_approvals` row left open) and
- /// `*park_bound_elapsed` is set so the bounded caller can render its own
- /// fast-path result instead of a `Deny`.
- async fn intercept_audited_inner(
- &self,
- tool_name: &str,
- action_summary: &str,
- args_redacted: serde_json::Value,
- park_bound: Option<Duration>,
- park_bound_elapsed: &mut bool,
- ) -> (GateOutcome, Option<String>) {
- // Origin tells us who scheduled this turn. Entry points (web channel,
- // channel runtime, subconscious, cron, CLI) scope a typed
- // `AgentTurnOrigin` around `run_turn`. Unlabelled callers map to
- // `Unknown`, which is denied — the gate refuses to execute an
- // external_effect tool from an unlabelled call site.
- let origin = turn_origin::current().unwrap_or(AgentTurnOrigin::Unknown);
- tracing::debug!(
- tool = tool_name,
- ?origin,
- auto_approve_all = self.is_auto_approve_all_enabled(),
- bypass_auto = matches!(
- &origin,
- AgentTurnOrigin::TrustedAutomation {
- source: TrustedAutomationSource::GoalContinuation,
- ..
- } | AgentTurnOrigin::TrustedAutomation {
- source: TrustedAutomationSource::Workflow {
- require_approval: true
- },
- ..
- }
- ),
- chat_context = APPROVAL_CHAT_CONTEXT.try_with(|c| c.clone()).is_ok(),
- "[approval::gate] evaluating approval request"
- );
-
- // Per-flow tool trust shortcut (flow-approval-surface, PR2): a prior
- // `ApproveAlwaysForFlow` decision on this exact `(flow_id, tool_name)`
- // pair short-circuits to `Allow` for every future Workflow-origin call
- // of that tool from that flow — including a `require_approval: true`
- // flow and a Supervised-tier `caps.rs::gate_call_for_tier` escalation,
- // both of which otherwise force the park below. The trust is scoped to
- // the *flow*, never the tool alone, so it cannot leak into a different
- // workflow that happens to call the same tool (that stays gated, or
- // uses the separate global `autonomy.auto_approve` allowlist). Checked
- // before any other origin branching so it wins regardless of which
- // arm of the match below would otherwise fire.
- if let AgentTurnOrigin::TrustedAutomation {
- source: TrustedAutomationSource::Workflow { .. },
- job_id: flow_id,
- } = &origin
- {
- match store::is_flow_tool_trusted(&self.config, flow_id, tool_name) {
- Ok(true) => {
- tracing::debug!(
- tool = tool_name,
- flow_id = %flow_id,
- "[approval::gate] flow_tool_trust hit — auto-allowing without prompt"
- );
- return (GateOutcome::Allow, None);
- }
- Ok(false) => {}
- Err(err) => {
- tracing::warn!(
- tool = tool_name,
- flow_id = %flow_id,
- error = %err,
- "[approval::gate] flow_tool_trust lookup failed — falling through to \
- normal gating (fail-safe: still gated, not silently allowed)"
- );
- }
- }
- }
-
- // An autonomous goal continuation runs with no user present, so an
- // irreversible external action must never be auto-allowed — not even via
- // the `autonomy.auto_approve` allowlist. Skip the shortcut for that
- // origin and fall through to the parking flow below. A workflow run
- // whose flow has `require_approval` set gets the same treatment — the
- // user explicitly asked for every outbound action on that flow to be
- // gated, and a global tool allowlist must not silently override that
- // per-flow choice.
- let bypass_auto_approve_shortcut = matches!(
- &origin,
- AgentTurnOrigin::TrustedAutomation {
- source: TrustedAutomationSource::GoalContinuation,
- ..
- } | AgentTurnOrigin::TrustedAutomation {
- source: TrustedAutomationSource::Workflow {
- require_approval: true
- },
- ..
- }
- );
-
- // Blanket "auto-approve everything" bypass (opt-in, off by default).
- // Sits ABOVE the origin match below so it prevents parking entirely
- // for every origin except the two that must never be silently
- // allowed: a subconscious tick whose memory context is tainted by
- // external-sync content (indirect prompt injection defense) and an
- // unlabelled call site (fail-closed default). Both are excluded here
- // so they still fall through to the origin match and hit their Deny
- // arms unchanged. This check is independent of — and does not
- // weaken — `is_always_forbidden`, `is_workspace_internal_path`, or
- // `ToolPolicyMiddleware`, which all run inside the tool
- // implementation itself, not the approval gate.
- //
- // Known and accepted: a **remote-origin triage** dispatch is not in the
- // protected set either. Since openhuman#5634 a Composio/webhook payload
- // reaching `triage.escalate` carries
- // `TrustedAutomation { Workflow { require_approval: true } }`, which
- // normally parks and writes a `pending_approvals` row — and with this
- // flag on it is allowed here instead, leaving no approval trail for
- // those dispatches. The gate owner ruled that enabling a blanket
- // "approve everything" switch opts into that globally rather than
- // carving out an exception, because the alternatives either narrow what
- // the flag means for every user who set it or turn it into "approve
- // everything except…". Decision and the options weighed:
- // https://github.com/tinyhumansai/openhuman/issues/5634#issuecomment-5396604125
- //
- // `auto_approve_all_allows_a_remote_triage_dispatch_without_an_audit_row`
- // below pins that outcome, so a change to this exclusion list has to
- // confront the decision rather than discover it.
- let auto_all = self.is_auto_approve_all_enabled()
- && !matches!(
- &origin,
- AgentTurnOrigin::TrustedAutomation {
- source: TrustedAutomationSource::SubconsciousTainted,
- ..
- } | AgentTurnOrigin::Unknown
- );
-
- if auto_all {
- // `origin_class` is the sanitized variant label (no thread/client
- // ids, channel sender, reply target, or message id) — safe at
- // `info`. The full `?origin` (with those identifiers) is still
- // available at `debug` for local troubleshooting.
- tracing::info!(
- tool = tool_name,
- origin_class = %origin.class(),
- auto_approved = true,
- "[approval::gate] auto_approve_all enabled — auto-approving without prompt"
- );
- tracing::debug!(
- tool = tool_name,
- origin = ?origin,
- "[approval::gate] auto_approve_all full origin (debug-only)"
- );
- return (GateOutcome::Allow, None);
- }
-
- // "Always allow" allowlist shortcut — the user's persisted
- // `autonomy.auto_approve` set. Read from the live policy first so a
- // grant made earlier in this session (which writes config + reloads the
- // live policy) takes effect on the very next tool call; fall back to the
- // gate's boot-time config when no live policy is installed (e.g. a CLI
- // invocation that never started a session runtime, or a unit test).
- if !bypass_auto_approve_shortcut && self.tool_is_auto_approved(tool_name) {
- tracing::debug!(
- tool = tool_name,
- "[approval::gate] auto_approve allowlist hit, skipping prompt"
- );
- return (GateOutcome::Allow, None);
- }
-
- // Chat context (thread/client id) for routing the yes/no reply — set by
- // the web channel around the agent run; absent for non-chat callers.
- //
- // Fallback (#5499): when the task-local is absent but the turn is
- // `WebChat`, route via the thread/client the origin itself carries. The
- // web channel scopes `APPROVAL_CHAT_CONTEXT` and builds the `WebChat`
- // origin from the *same* thread_id/client_id (`web_chat::start_chat`),
- // so the two are identical whenever both are present. They diverge only
- // when a turn is carried across a `tokio::spawn` boundary that
- // propagates the origin but not the approval context — most importantly
- // an async-delegated sub-agent (`spawn_async_subagent`, reached when the
- // orchestrator routes "remind me…" to `scheduler_agent`): the origin
- // travels but this task-local does not. Without the fallback the gate
- // parks with `thread_id: None`, the web-channel surface drops the
- // `ApprovalRequested` event ("thread/client absent — NOT surfacing"),
- // and the park silently TTL-denies — so a `cron_add` scheduled from a
- // chat turn never completes.
- let chat_ctx = APPROVAL_CHAT_CONTEXT.try_with(|c| c.clone()).ok();
- let origin_chat_route = match &origin {
- AgentTurnOrigin::WebChat {
- thread_id,
- client_id,
- ..
- } => Some((thread_id.clone(), client_id.clone())),
- _ => None,
- };
- if chat_ctx.is_none() && origin_chat_route.is_some() {
- tracing::debug!(
- tool = tool_name,
- "[approval::gate] APPROVAL_CHAT_CONTEXT absent on a WebChat turn — routing the \
- approval via the origin's thread/client (async-delegated sub-agent path, #5499)"
- );
- }
- let chat_thread_id = chat_ctx
- .as_ref()
- .map(|c| c.thread_id.clone())
- .or_else(|| origin_chat_route.as_ref().map(|(t, _)| t.clone()));
- let chat_client_id = chat_ctx
- .as_ref()
- .map(|c| c.client_id.clone())
- .or_else(|| origin_chat_route.as_ref().map(|(_, c)| c.clone()));
-
- // Copilot-streaming context — set by `flows::ops::flows_build` around
- // the streaming `run_single` call. Presence alone clamps the park
- // window to `COPILOT_APPROVAL_TTL`; see that task-local's doc.
- let copilot_stream = APPROVAL_COPILOT_STREAM_CONTEXT.try_with(|_| ()).is_ok();
-
- // Branch by origin. Web chat parks for an in-app approval; external
- // channel persists an audit row and TTL-denies (no routable approval
- // surface yet); trusted automation (cron, internal-only subconscious)
- // is allowed through unchanged; tainted subconscious — a tick whose
- // memory context contains external-sync chunks — is denied because
- // remote text could otherwise steer it into an external_effect tool;
- // CLI keeps the legacy allow; Unknown fails closed.
- match &origin {
- AgentTurnOrigin::WebChat { .. } => {
- // Fall through to the existing chat-routed parking flow below.
- }
- AgentTurnOrigin::ExternalChannel {
- channel,
- sender,
- reply_target,
- message_id,
- } => {
- tracing::info!(
- tool = tool_name,
- channel = %channel,
- sender = %sender.as_deref().unwrap_or("<unknown>"),
- reply_target = %reply_target,
- message_id = %message_id,
- "[approval::gate] external channel turn — persisting audit row and parking"
- );
- // Fall through to the parking flow: a `pending_approvals` row
- // is persisted (audit trail) and the future parks. We do NOT
- // short-circuit to Allow here — remote inputs are untrusted.
- // Without a routable surface the park TTL-denies; a decision
- // can still arrive via the thread card before the TTL.
- }
- AgentTurnOrigin::TrustedAutomation {
- source: TrustedAutomationSource::Cron,
- job_id,
- } => {
- tracing::debug!(
- tool = tool_name,
- job_id = %job_id,
- "[approval::gate] trusted cron automation — allowing without prompt"
- );
- return (GateOutcome::Allow, None);
- }
- AgentTurnOrigin::TrustedAutomation {
- source: TrustedAutomationSource::Subconscious,
- job_id,
- } => {
- tracing::debug!(
- tool = tool_name,
- job_id = %job_id,
- "[approval::gate] trusted internal subconscious tick — allowing without prompt"
- );
- return (GateOutcome::Allow, None);
- }
- AgentTurnOrigin::TrustedAutomation {
- source: TrustedAutomationSource::SubconsciousTainted,
- job_id,
- } => {
- tracing::warn!(
- tool = tool_name,
- job_id = %job_id,
- "[approval::gate] subconscious tick with external-sync memory in context — \
- rejecting external_effect tool"
- );
- return (
- GateOutcome::Deny {
- reason: format!(
- "{POLICY_DENIED_MARKER} Tool '{tool_name}' rejected: subconscious turn \
- whose memory context includes external-sync chunks may not run \
- external_effect tools."
- ),
- },
- None,
- );
- }
- AgentTurnOrigin::TrustedAutomation {
- source: TrustedAutomationSource::GoalContinuation,
- job_id,
- } => {
- tracing::debug!(
- tool = tool_name,
- job_id = %job_id,
- "[approval::gate] autonomous goal continuation — external_effect tool parks \
- (no present user to authorize); TTL-denies without a routable surface"
- );
- // Fall through to the parking flow: an autonomous continuation
- // runs with no user present, so we must NOT auto-allow an
- // irreversible external action. Read/compute tools (not gated
- // here) still make progress on the goal.
- }
- AgentTurnOrigin::TrustedAutomation {
- source:
- TrustedAutomationSource::Workflow {
- require_approval: false,
- },
- job_id,
- } => {
- tracing::debug!(
- tool = tool_name,
- flow_id = %job_id,
- "[approval::gate] trusted workflow automation — pre-declared action, \
- allowing without prompt"
- );
- return (GateOutcome::Allow, None);
- }
- AgentTurnOrigin::TrustedAutomation {
- source:
- TrustedAutomationSource::Workflow {
- require_approval: true,
- },
- job_id,
- } => {
- tracing::info!(
- tool = tool_name,
- flow_id = %job_id,
- "[approval::gate] workflow run has require_approval enabled — parking for \
- HITL review instead of auto-allowing the trust root"
- );
- // Fall through to the parking flow (same shape as
- // GoalContinuation): persists a `pending_approvals` audit row
- // and publishes `ApprovalRequested`. There is no chat thread to
- // route the prompt to for a background/triggered flow run yet
- // (B3 will add a dedicated review surface) — a caller can still
- // decide it via `approval_decide` (e.g. a generic pending-
- // approvals list) before the TTL elapses; absent a decision this
- // TTL-denies, the conservative fail-closed default for a
- // user-forced HITL gate.
- }
- AgentTurnOrigin::Cli => {
- tracing::debug!(
- tool = tool_name,
- "[approval::gate] CLI / sub-agent caller — allowing without prompt"
- );
- return (GateOutcome::Allow, None);
- }
- AgentTurnOrigin::Unknown => {
- tracing::warn!(
- tool = tool_name,
- "[approval::gate] agent turn has no origin label — refusing to execute \
- external_effect tool from unlabelled call site"
- );
- return (
- GateOutcome::Deny {
- reason: format!(
- "{POLICY_DENIED_MARKER} '{tool_name}' was blocked because this agent \
- turn is missing its origin label, so the approval gate cannot decide \
- who requested the action. Scheduling and other external-effect tools \
- (e.g. cron_add / cron_update) are refused when the turn has no origin. \
- This is an internal wiring gap, not something you did — the work most \
- likely ran on a background task that did not carry the turn's origin \
- forward; retry from a normal chat turn, or report it so the spawn site \
- can be fixed."
- ),
- },
- None,
- );
- }
- }
-
- let request_id = uuid::Uuid::new_v4().to_string();
- let now = chrono::Utc::now();
- // Resolve the clamped park TTL up front so the persisted `expires_at`
- // and the actual wait below (see `resolve_park_ttl` further down)
- // use the same value — see `Self::resolve_park_ttl` and the
- // COPILOT_APPROVAL_TTL clamp. Computing this
- // only after persisting the pending row let a copilot-streaming park
- // advertise the old 10-minute `expires_at` while only actually
- // waiting 180s, so a core restart or an `expire_stale` sweep mid-park
- // could leave the row "actionable" for the wrong window (CodeRabbit
- // + Codex review on PR #5112).
- let effective_ttl = Self::resolve_park_ttl(self.effective_ttl(), copilot_stream);
- let expires_at = Some(now + chrono::Duration::from_std(effective_ttl).unwrap_or_default());
-
- // Correlation context (flow-approval-surface, PR2): a Workflow-origin
- // park carries the flow id on the origin itself, but not the run id —
- // that comes from the `APPROVAL_FLOW_RUN_CONTEXT` task-local
- // `flows::ops::flows_run`/`flows_resume` scope alongside `with_origin`.
- // `try_with` returns `Err` for every non-flow caller (chat, cron,
- // subconscious, CLI, and even a Workflow origin reached without the
- // flows module's scope, which "should never happen" but must not
- // panic), so `source_context` stays `None` there — unchanged chat
- // behavior.
- let source_context = match &origin {
- AgentTurnOrigin::TrustedAutomation {
- source: TrustedAutomationSource::Workflow { .. },
- job_id: flow_id,
- } => APPROVAL_FLOW_RUN_CONTEXT
- .try_with(|ctx| ApprovalSourceContext::Flow {
- flow_id: flow_id.clone(),
- run_id: ctx.run_id.clone(),
- node_id: None,
- })
- .ok(),
- _ => None,
- };
-
- let pending = PendingApproval {
- request_id: request_id.clone(),
- tool_name: tool_name.to_string(),
- action_summary: action_summary.to_string(),
- args_redacted: args_redacted.clone(),
- created_at: now,
- expires_at,
- source_context: source_context.clone(),
- };
-
- // Register the waiter BEFORE persisting the row so a fast
- // `approval_decide` cannot mark the request approved while
- // no waiter exists — would otherwise leave the parked call
- // to time out and return `Deny` incorrectly. (CodeRabbit
- // review on PR #2149.)
- let (tx, rx) = oneshot::channel::<ApprovalDecision>();
- {
- let mut waiters = self.waiters.lock();
- waiters.insert(request_id.clone(), tx);
- }
- // Record the thread → request mapping so an inbound chat reply on this
- // thread can be routed to `approval_decide` (see web channel ingress).
- if let Some(thread_id) = chat_thread_id.as_ref() {
- self.thread_to_request
- .lock()
- .insert(thread_id.clone(), request_id.clone());
- }
- if let Err(err) = store::insert_pending(&self.config, &pending, &self.session_id) {
- self.evict_waiter(&request_id);
- self.clear_thread(&chat_thread_id, &request_id);
- tracing::error!(
- error = %err,
- tool = tool_name,
- "[approval::gate] failed to persist pending row — failing closed"
- );
- return (
- GateOutcome::Deny {
- reason: format!(
- "{POLICY_DENIED_MARKER} Approval gate could not persist the request — \
- denying for safety: {err}"
- ),
- },
- None,
- );
- }
-
- tracing::info!(
- request_id = %request_id,
- tool = tool_name,
- thread_id = chat_thread_id.as_deref().unwrap_or("<none>"),
- client_id = chat_client_id.as_deref().unwrap_or("<none>"),
- "[approval::gate] publishing ApprovalRequested (surface fires only if thread_id+client_id are both set)"
- );
- BUS.publish(DomainEvent::ApprovalRequested {
- request_id: request_id.clone(),
- tool_name: tool_name.to_string(),
- action_summary: action_summary.to_string(),
- args_redacted,
- thread_id: chat_thread_id.clone(),
- client_id: chat_client_id.clone(),
- });
-
- // Flow-origin surface bridge (flow-approval-surface, PR3): a flow run
- // has no chat thread/client to route the generic `ApprovalRequested`
- // through (both are `None` above, so the web-channel bridge silently
- // drops it — see `web_chat::event_bus`'s
- // `ApprovalSurfaceSubscriber`), which is exactly the silent-deadlock
- // bug this correlation fixes. Broadcast a dedicated
- // `flow_approval_request` socket event (no thread/client required,
- // unlike the chat path) plus a `CoreNotification` with the three
- // flow-scoped decision actions, so the Workflows UI can surface and
- // resolve the park without polling.
- if let Some(ApprovalSourceContext::Flow {
- flow_id, run_id, ..
- }) = &source_context
- {
- tracing::info!(
- request_id = %request_id,
- flow_id = %flow_id,
- run_id = %run_id,
- tool = tool_name,
- "[approval::gate] flow-origin park — surfacing flow_approval_request + notification"
- );
- BUS.publish(DomainEvent::FlowApprovalRequested {
- request_id: request_id.clone(),
- flow_id: flow_id.clone(),
- run_id: run_id.clone(),
- tool_name: tool_name.to_string(),
- summary: action_summary.to_string(),
- });
- publish_flow_gate_notification(&request_id, flow_id, run_id, tool_name, action_summary);
- }
-
- tracing::info!(
- request_id = %request_id,
- tool = tool_name,
- "[approval::gate] tool call parked, waiting for decision"
- );
-
- // Copilot-streaming flows_build runs get a clamped park window — see
- // COPILOT_APPROVAL_TTL and `Self::resolve_park_ttl`. `effective_ttl` was resolved above
- // (before `expires_at` was built) so the persisted expiry and this
- // wait use the identical clamped duration; `effective_ttl()` applies
- // the debug-only env override, and the clamp is applied on top so a
- // longer override can't extend either park past its clamp.
- if copilot_stream {
- tracing::debug!(
- tool = tool_name,
- ttl_secs = COPILOT_APPROVAL_TTL.as_secs(),
- "[approval::gate] flows_build copilot-streaming park — clamping park window to \
- COPILOT_APPROVAL_TTL"
- );
- }
-
- // Optional caller-supplied park bound (issue #4756). A caller
- // (`composio_connect`) can cap how long the gate parks so a turn
- // degrades to a fast prompt instead of blocking to the full TTL.
- // Bounding must never *extend* the park, so we wait `min(bound, ttl)`;
- // the caller-bound abandon path fires only when the bound is what
- // elapses (`park_bound_active`).
- let park_bound_active = matches!(park_bound, Some(b) if b < effective_ttl);
- let wait = match park_bound {
- Some(b) => b.min(effective_ttl),
- None => effective_ttl,
- };
-
- // RAII cleanup for external teardown (#4774): if the turn future is
- // dropped while parked on the await below (the #4746/#4751 wall-clock
- // backstop firing), the match arms never run, so this guard evicts the
- // waiter, clears routing, and denies the pending row on drop. Disarmed
- // right after the match on every normal exit.
- let mut waiter_guard = WaiterGuard {
- gate: self,
- request_id: request_id.clone(),
- thread_id: chat_thread_id.clone(),
- armed: true,
- };
-
- let outcome = match tokio::time::timeout(wait, rx).await {
- Ok(Ok(decision)) => {
- tracing::info!(
- request_id = %request_id,
- tool = tool_name,
- decision = decision.as_str(),
- "[approval::gate] decision received"
- );
- if decision.is_approve() {
- (GateOutcome::Allow, Some(request_id.clone()))
- } else {
- (
- GateOutcome::Deny {
- reason: format!(
- "{POLICY_DENIED_MARKER} User denied '{tool_name}' execution. Do \
- not re-request the same call this turn; take a different approach \
- or stop."
- ),
- },
- None,
- )
- }
- }
- Ok(Err(_canceled)) => {
- // Sender dropped — treat as denial so the agent does
- // not silently no-op.
- tracing::warn!(
- request_id = %request_id,
- tool = tool_name,
- "[approval::gate] decision channel dropped — denying"
- );
- let _ = store::decide(&self.config, &request_id, ApprovalDecision::Deny);
- (
- GateOutcome::Deny {
- reason: format!(
- "{POLICY_DENIED_MARKER} Approval channel for '{tool_name}' closed \
- before a decision was made."
- ),
- },
- None,
- )
- }
- Err(_elapsed) if park_bound_active => {
- // Caller park bound elapsed (#4756) — NOT the gate's own TTL.
- // Abandon the park cancellation-safely: evict the in-memory
- // waiter and (via `clear_thread` below, on every
- // exit) drop the routing mappings so a later chat/voice reply is
- // not mis-routed to this now-abandoned request. Deliberately do
- // NOT `store::decide(Deny)` — the `pending_approvals` row stays
- // open so a later human card-click still resolves it in the DB
- // and a re-ask sees it already-connected. Signal the elapse so
- // the bounded caller renders its own fast-path result rather than
- // a `Deny`.
- self.evict_waiter(&request_id);
- *park_bound_elapsed = true;
- tracing::info!(
- request_id = %request_id,
- tool = tool_name,
- bound_secs = wait.as_secs(),
- "[approval::gate] caller park bound elapsed — abandoning park (row left \
- pending for a later card-click; waiter + routing cleared) (#4756)"
- );
- // Placeholder outcome; the bounded caller discards it once
- // `*park_bound_elapsed` is set (returns `None`).
- (
- GateOutcome::Deny {
- reason: format!(
- "{POLICY_DENIED_MARKER} Approval for '{tool_name}' exceeded the caller \
- park bound ({}s).",
- wait.as_secs()
- ),
- },
- None,
- )
- }
- Err(_elapsed) => {
- self.evict_waiter(&request_id);
- // Race: `decide()` may have committed an Approve in
- // SQLite right as the TTL elapsed. `store::decide(Deny)`
- // has `WHERE decided_at IS NULL` so it won't overwrite,
- // but without a re-read we'd return Deny here while the
- // durable audit row says Approved (CodeRabbit review on
- // #2367). Try to deny; if the row was already decided,
- // honor the persisted decision.
- let denied = store::decide(&self.config, &request_id, ApprovalDecision::Deny);
- let persisted = match &denied {
- Ok(Some(_)) => Some(ApprovalDecision::Deny),
- Ok(None) => store::get_decision(&self.config, &request_id)
- .ok()
- .flatten(),
- Err(_) => None,
- };
- if matches!(persisted, Some(d) if d.is_approve()) {
- tracing::info!(
- request_id = %request_id,
- tool = tool_name,
- ttl_secs = effective_ttl.as_secs(),
- "[approval::gate] timeout race: persisted decision was Approve, honoring approval"
- );
- // Fall through (no early return) so `clear_thread` below runs
- // on this path too — otherwise the stale thread→request
- // mapping survives and the next yes/no on the thread could be
- // routed to this already-finished request.
- (GateOutcome::Allow, Some(request_id.clone()))
- } else {
- tracing::warn!(
- request_id = %request_id,
- tool = tool_name,
- ttl_secs = effective_ttl.as_secs(),
- "[approval::gate] approval timed out, denying"
- );
- (
- GateOutcome::Deny {
- reason: format!(
- "{POLICY_DENIED_MARKER} Approval for '{tool_name}' timed out after \
- {}s. Do not re-request the same call this turn; take a different \
- approach or stop.",
- effective_ttl.as_secs()
- ),
- },
- None,
- )
- }
- }
- };
- // Reached only on a normal park resolution: the match arm above already
- // ran the exact teardown for its outcome, so disarm the RAII guard (its
- // Drop is reserved for external cancellation — see `WaiterGuard`).
- waiter_guard.disarm();
- // The routing mappings are only needed while parked; clear them on
- // every exit (decision, channel drop, or timeout).
- self.clear_thread(&chat_thread_id, &request_id);
- outcome
- }
-
- /// Write the *terminal* status of a tool call onto its approval
- /// audit row — see [`store::record_execution`] for semantics.
- ///
- /// Logs (but does not propagate) write errors: the tool has
- /// already run, so audit-log loss should never bubble up as a
- /// tool execution failure to the agent. If durable audit storage
- /// is required for compliance, callers wire it via a stronger
- /// guarantee than this best-effort hook.
- pub fn record_execution(
- &self,
- request_id: &str,
- outcome: ExecutionOutcome,
- error: Option<&str>,
- ) {
- match store::record_execution(&self.config, request_id, outcome, error) {
- Ok(true) => tracing::debug!(
- request_id = %request_id,
- outcome = outcome.as_str(),
- "[approval::gate] recorded terminal execution"
- ),
- Ok(false) => tracing::warn!(
- request_id = %request_id,
- outcome = outcome.as_str(),
- "[approval::gate] record_execution found no matching decided row"
- ),
- Err(err) => tracing::error!(
- request_id = %request_id,
- outcome = outcome.as_str(),
- error = %err,
- "[approval::gate] record_execution write failed"
- ),
- }
- }
-
- /// Apply a user decision. Returns the now-decided
- /// [`PendingApproval`] row when one was found.
- pub fn decide(
- &self,
- request_id: &str,
- decision: ApprovalDecision,
- ) -> anyhow::Result<Option<PendingApproval>> {
- let decided = store::decide(&self.config, request_id, decision)?;
- if let Some(row) = &decided {
- // `ApproveAlwaysForTool` persistence (append to `autonomy.auto_approve`
- // + reload the live policy) is handled by the `approval_decide` RPC
- // handler, which is async and owns the config save+reload path. The
- // gate only resolves the parked future and emits the audit event.
- if let Some(tx) = self.take_waiter(request_id) {
- let _ = tx.send(decision);
- }
- BUS.publish(DomainEvent::ApprovalDecided {
- request_id: row.request_id.clone(),
- tool_name: row.tool_name.clone(),
- decision: decision.as_str().to_string(),
- });
- }
- Ok(decided)
- }
-
- /// Classify a [`Self::decide`] miss — i.e. when `decide` returned
- /// `Ok(None)` because its conditional `UPDATE ... WHERE decided_at IS NULL`
- /// matched 0 rows. Two very different states collapse into that `None`:
- ///
- /// - [`DecideMiss::AlreadyResolved`] — the row exists but was **already
- /// decided, lazily expired (denied), or superseded**. This is the benign
- /// double-tap / two-operator / expiry-while-live race the inline-approvals
- /// design spec classifies as benign (TAURI-RUST-5EH).
- /// - [`DecideMiss::NeverRegistered`] — no row was ever persisted for this
- /// request_id. That is a genuine lost registration (a core restart dropped
- /// the parked future before persisting, or a stray id) and must stay a
- /// Sentry signal.
- ///
- /// We disambiguate by consulting [`store::get_decision`], which returns a
- /// decision only when `decided_at IS NOT NULL` — exactly the already-resolved
- /// case (expiry writes a `Deny` decision, so expired rows report here too).
- /// A `decide` miss can't be an undecided-but-present row: that row would have
- /// matched the `UPDATE`. If the lookup itself errors we conservatively keep
- /// the event visible (`NeverRegistered`) rather than silently demoting.
- pub fn classify_decide_miss(&self, request_id: &str) -> DecideMiss {
- match store::get_decision(&self.config, request_id) {
- Ok(Some(_)) => DecideMiss::AlreadyResolved,
- Ok(None) => DecideMiss::NeverRegistered,
- Err(err) => {
- tracing::warn!(
- request_id = %request_id,
- error = %err,
- "[approval::gate] classify_decide_miss: get_decision failed; treating as never-registered (keep visible)"
- );
- DecideMiss::NeverRegistered
- }
- }
- }
-
- /// List all undecided rows, including orphans from prior launches.
- /// Orphan rows have no live parked future so a `decide` on them
- /// updates the DB but cannot resume an action — see [`store::list_pending`].
- pub fn list_pending(&self) -> anyhow::Result<Vec<PendingApproval>> {
- store::list_pending(&self.config)
- }
-
- /// List recently decided rows for durable audit views.
- pub fn list_recent_decisions(
- &self,
- limit: usize,
- ) -> anyhow::Result<Vec<super::types::ApprovalAuditEntry>> {
- store::list_recent_decisions(&self.config, limit)
- }
-
- /// List undecided rows correlated with a specific flow run (issue
- /// flow-approval-surface, PR2) — lets a dedicated Workflows review
- /// surface fetch just the gates blocking one run instead of filtering
- /// [`Self::list_pending`] client-side.
- pub fn list_pending_for_flow_run(
- &self,
- flow_id: &str,
- run_id: &str,
- ) -> anyhow::Result<Vec<PendingApproval>> {
- store::list_pending_for_flow_run(&self.config, flow_id, run_id)
- }
-
- /// Grant "approve always for this flow" trust to `(flow_id, tool_name)`.
- /// Called by the `approval_decide` RPC handler after an
- /// [`ApprovalDecision::ApproveAlwaysForFlow`] decides a flow-origin row —
- /// mirrors the RPC-owns-persistence split documented on
- /// [`Self::decide`] for `ApproveAlwaysForTool`.
- pub fn insert_flow_trust(&self, flow_id: &str, tool_name: &str) -> anyhow::Result<()> {
- store::insert_flow_trust(&self.config, flow_id, tool_name)
- }
-
- /// Whether `(flow_id, tool_name)` currently holds "approve always for
- /// this flow" trust. Exposed for tests and diagnostics; `intercept_audited`
- /// consults [`store::is_flow_tool_trusted`] directly.
- pub fn is_flow_tool_trusted(&self, flow_id: &str, tool_name: &str) -> anyhow::Result<bool> {
- store::is_flow_tool_trusted(&self.config, flow_id, tool_name)
- }
-
- /// Every `tool_name` currently trusted for `flow_id`, sorted. Consumed by
- /// `flows_approval_manifest` to diff the graph's required permissions
- /// against grants that already exist (re-save asks only for what's new).
- pub fn list_flow_trust(&self, flow_id: &str) -> anyhow::Result<Vec<String>> {
- store::list_flow_trust(&self.config, flow_id)
- }
-
- /// Revoke flow trust: all grants for `flow_id` when `tool_names` is
- /// `None` (flow deletion cleanup), or only the named grants. Returns the
- /// number of rows removed.
- pub fn delete_flow_trust(
- &self,
- flow_id: &str,
- tool_names: Option<&[String]>,
- ) -> anyhow::Result<usize> {
- store::delete_flow_trust(&self.config, flow_id, tool_names)
- }
-
- /// Write the durable audit record for one save-time pre-authorization
- /// grant (a born-decided `approve_always_for_flow` row) so blanket
- /// grants stay inspectable in Settings → Approval history.
- pub fn record_flow_preauthorization(
- &self,
- flow_id: &str,
- tool_name: &str,
- ) -> anyhow::Result<()> {
- store::record_flow_preauthorization(&self.config, flow_id, tool_name, &self.session_id)
- }
-
- /// Return the session id this gate was installed with (used by
- /// RPC handlers for diagnostics).
- pub fn session_id(&self) -> &str {
- &self.session_id
- }
-
- fn take_waiter(&self, request_id: &str) -> Option<oneshot::Sender<ApprovalDecision>> {
- let mut waiters = self.waiters.lock();
- waiters.remove(request_id)
- }
-
- fn evict_waiter(&self, request_id: &str) {
- let mut waiters = self.waiters.lock();
- waiters.remove(request_id);
- }
-
- /// The request_id of the approval currently parked on `thread_id`, if any.
- /// Used by the web channel to route an inbound yes/no reply to a decision.
- pub fn pending_for_thread(&self, thread_id: &str) -> Option<String> {
- self.thread_to_request.lock().get(thread_id).cloned()
- }
-
- /// Drop the thread → request mapping when it still belongs to this request.
- fn clear_thread(&self, thread_id: &Option<String>, request_id: &str) {
- if let Some(t) = thread_id {
- self.clear_thread_route_if_owned(t, request_id);
- }
- }
-
- /// Drop the thread → request mapping **only if** it still points at
- /// `request_id`. Used by [`WaiterGuard::drop`] on external teardown, where a
- /// replacement turn may have already parked a new approval on the same
- /// thread and overwritten the entry; clearing unconditionally would delete
- /// the *new* request's routing (#4774).
- fn clear_thread_route_if_owned(&self, thread_id: &str, request_id: &str) {
- let mut map = self.thread_to_request.lock();
- if map.get(thread_id).is_some_and(|rid| rid == request_id) {
- map.remove(thread_id);
- }
- }
-}
-
-/// Wall-clock milliseconds since the Unix epoch, for `CoreNotificationEvent::timestamp_ms`.
+include!("gate_setup.rs");
+include!("gate_intercept.rs");
+include!("gate_state.rs");
fn now_ms() -> u64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
diff --git a/src/openhuman/security/approval/gate_intercept.rs b/src/openhuman/security/approval/gate_intercept.rs
new file mode 100644
index 0000000000..64ffeeaf7f
--- /dev/null
+++ b/src/openhuman/security/approval/gate_intercept.rs
@@ -0,0 +1,686 @@
+impl ApprovalGate {
+ /// Shared core of [`Self::intercept_audited`] and
+ /// [`Self::intercept_audited_bounded`]. When `park_bound` is `Some` and
+ /// shorter than the effective TTL, the park is capped at it; on that bound
+ /// elapsing the park is abandoned cancellation-safely (waiter evicted,
+ /// thread routing cleared, `pending_approvals` row left open) and
+ /// `*park_bound_elapsed` is set so the bounded caller can render its own
+ /// fast-path result instead of a `Deny`.
+ async fn intercept_audited_inner(
+ &self,
+ tool_name: &str,
+ action_summary: &str,
+ args_redacted: serde_json::Value,
+ park_bound: Option<Duration>,
+ park_bound_elapsed: &mut bool,
+ ) -> (GateOutcome, Option<String>) {
+ // Origin tells us who scheduled this turn. Entry points (web channel,
+ // channel runtime, subconscious, cron, CLI) scope a typed
+ // `AgentTurnOrigin` around `run_turn`. Unlabelled callers map to
+ // `Unknown`, which is denied — the gate refuses to execute an
+ // external_effect tool from an unlabelled call site.
+ let origin = turn_origin::current().unwrap_or(AgentTurnOrigin::Unknown);
+ tracing::debug!(
+ tool = tool_name,
+ ?origin,
+ auto_approve_all = self.is_auto_approve_all_enabled(),
+ bypass_auto = matches!(
+ &origin,
+ AgentTurnOrigin::TrustedAutomation {
+ source: TrustedAutomationSource::GoalContinuation,
+ ..
+ } | AgentTurnOrigin::TrustedAutomation {
+ source: TrustedAutomationSource::Workflow {
+ require_approval: true
+ },
+ ..
+ }
+ ),
+ chat_context = APPROVAL_CHAT_CONTEXT.try_with(|c| c.clone()).is_ok(),
+ "[approval::gate] evaluating approval request"
+ );
+
+ // Per-flow tool trust shortcut (flow-approval-surface, PR2): a prior
+ // `ApproveAlwaysForFlow` decision on this exact `(flow_id, tool_name)`
+ // pair short-circuits to `Allow` for every future Workflow-origin call
+ // of that tool from that flow — including a `require_approval: true`
+ // flow and a Supervised-tier `caps.rs::gate_call_for_tier` escalation,
+ // both of which otherwise force the park below. The trust is scoped to
+ // the *flow*, never the tool alone, so it cannot leak into a different
+ // workflow that happens to call the same tool (that stays gated, or
+ // uses the separate global `autonomy.auto_approve` allowlist). Checked
+ // before any other origin branching so it wins regardless of which
+ // arm of the match below would otherwise fire.
+ if let AgentTurnOrigin::TrustedAutomation {
+ source: TrustedAutomationSource::Workflow { .. },
+ job_id: flow_id,
+ } = &origin
+ {
+ match store::is_flow_tool_trusted(&self.config, flow_id, tool_name) {
+ Ok(true) => {
+ tracing::debug!(
+ tool = tool_name,
+ flow_id = %flow_id,
+ "[approval::gate] flow_tool_trust hit — auto-allowing without prompt"
+ );
+ return (GateOutcome::Allow, None);
+ }
+ Ok(false) => {}
+ Err(err) => {
+ tracing::warn!(
+ tool = tool_name,
+ flow_id = %flow_id,
+ error = %err,
+ "[approval::gate] flow_tool_trust lookup failed — falling through to \
+ normal gating (fail-safe: still gated, not silently allowed)"
+ );
+ }
+ }
+ }
+
+ // An autonomous goal continuation runs with no user present, so an
+ // irreversible external action must never be auto-allowed — not even via
+ // the `autonomy.auto_approve` allowlist. Skip the shortcut for that
+ // origin and fall through to the parking flow below. A workflow run
+ // whose flow has `require_approval` set gets the same treatment — the
+ // user explicitly asked for every outbound action on that flow to be
+ // gated, and a global tool allowlist must not silently override that
+ // per-flow choice.
+ let bypass_auto_approve_shortcut = matches!(
+ &origin,
+ AgentTurnOrigin::TrustedAutomation {
+ source: TrustedAutomationSource::GoalContinuation,
+ ..
+ } | AgentTurnOrigin::TrustedAutomation {
+ source: TrustedAutomationSource::Workflow {
+ require_approval: true
+ },
+ ..
+ }
+ );
+
+ // Blanket "auto-approve everything" bypass (opt-in, off by default).
+ // Sits ABOVE the origin match below so it prevents parking entirely
+ // for every origin except the two that must never be silently
+ // allowed: a subconscious tick whose memory context is tainted by
+ // external-sync content (indirect prompt injection defense) and an
+ // unlabelled call site (fail-closed default). Both are excluded here
+ // so they still fall through to the origin match and hit their Deny
+ // arms unchanged. This check is independent of — and does not
+ // weaken — `is_always_forbidden`, `is_workspace_internal_path`, or
+ // `ToolPolicyMiddleware`, which all run inside the tool
+ // implementation itself, not the approval gate.
+ //
+ // Known and accepted: a **remote-origin triage** dispatch is not in the
+ // protected set either. Since openhuman#5634 a Composio/webhook payload
+ // reaching `triage.escalate` carries
+ // `TrustedAutomation { Workflow { require_approval: true } }`, which
+ // normally parks and writes a `pending_approvals` row — and with this
+ // flag on it is allowed here instead, leaving no approval trail for
+ // those dispatches. The gate owner ruled that enabling a blanket
+ // "approve everything" switch opts into that globally rather than
+ // carving out an exception, because the alternatives either narrow what
+ // the flag means for every user who set it or turn it into "approve
+ // everything except…". Decision and the options weighed:
+ // https://github.com/tinyhumansai/openhuman/issues/5634#issuecomment-5396604125
+ //
+ // `auto_approve_all_allows_a_remote_triage_dispatch_without_an_audit_row`
+ // below pins that outcome, so a change to this exclusion list has to
+ // confront the decision rather than discover it.
+ let auto_all = self.is_auto_approve_all_enabled()
+ && !matches!(
+ &origin,
+ AgentTurnOrigin::TrustedAutomation {
+ source: TrustedAutomationSource::SubconsciousTainted,
+ ..
+ } | AgentTurnOrigin::Unknown
+ );
+
+ if auto_all {
+ // `origin_class` is the sanitized variant label (no thread/client
+ // ids, channel sender, reply target, or message id) — safe at
+ // `info`. The full `?origin` (with those identifiers) is still
+ // available at `debug` for local troubleshooting.
+ tracing::info!(
+ tool = tool_name,
+ origin_class = %origin.class(),
+ auto_approved = true,
+ "[approval::gate] auto_approve_all enabled — auto-approving without prompt"
+ );
+ tracing::debug!(
+ tool = tool_name,
+ origin = ?origin,
+ "[approval::gate] auto_approve_all full origin (debug-only)"
+ );
+ return (GateOutcome::Allow, None);
+ }
+
+ // "Always allow" allowlist shortcut — the user's persisted
+ // `autonomy.auto_approve` set. Read from the live policy first so a
+ // grant made earlier in this session (which writes config + reloads the
+ // live policy) takes effect on the very next tool call; fall back to the
+ // gate's boot-time config when no live policy is installed (e.g. a CLI
+ // invocation that never started a session runtime, or a unit test).
+ if !bypass_auto_approve_shortcut && self.tool_is_auto_approved(tool_name) {
+ tracing::debug!(
+ tool = tool_name,
+ "[approval::gate] auto_approve allowlist hit, skipping prompt"
+ );
+ return (GateOutcome::Allow, None);
+ }
+
+ // Chat context (thread/client id) for routing the yes/no reply — set by
+ // the web channel around the agent run; absent for non-chat callers.
+ //
+ // Fallback (#5499): when the task-local is absent but the turn is
+ // `WebChat`, route via the thread/client the origin itself carries. The
+ // web channel scopes `APPROVAL_CHAT_CONTEXT` and builds the `WebChat`
+ // origin from the *same* thread_id/client_id (`web_chat::start_chat`),
+ // so the two are identical whenever both are present. They diverge only
+ // when a turn is carried across a `tokio::spawn` boundary that
+ // propagates the origin but not the approval context — most importantly
+ // an async-delegated sub-agent (`spawn_async_subagent`, reached when the
+ // orchestrator routes "remind me…" to `scheduler_agent`): the origin
+ // travels but this task-local does not. Without the fallback the gate
+ // parks with `thread_id: None`, the web-channel surface drops the
+ // `ApprovalRequested` event ("thread/client absent — NOT surfacing"),
+ // and the park silently TTL-denies — so a `cron_add` scheduled from a
+ // chat turn never completes.
+ let chat_ctx = APPROVAL_CHAT_CONTEXT.try_with(|c| c.clone()).ok();
+ let origin_chat_route = match &origin {
+ AgentTurnOrigin::WebChat {
+ thread_id,
+ client_id,
+ ..
+ } => Some((thread_id.clone(), client_id.clone())),
+ _ => None,
+ };
+ if chat_ctx.is_none() && origin_chat_route.is_some() {
+ tracing::debug!(
+ tool = tool_name,
+ "[approval::gate] APPROVAL_CHAT_CONTEXT absent on a WebChat turn — routing the \
+ approval via the origin's thread/client (async-delegated sub-agent path, #5499)"
+ );
+ }
+ let chat_thread_id = chat_ctx
+ .as_ref()
+ .map(|c| c.thread_id.clone())
+ .or_else(|| origin_chat_route.as_ref().map(|(t, _)| t.clone()));
+ let chat_client_id = chat_ctx
+ .as_ref()
+ .map(|c| c.client_id.clone())
+ .or_else(|| origin_chat_route.as_ref().map(|(_, c)| c.clone()));
+
+ // Copilot-streaming context — set by `flows::ops::flows_build` around
+ // the streaming `run_single` call. Presence alone clamps the park
+ // window to `COPILOT_APPROVAL_TTL`; see that task-local's doc.
+ let copilot_stream = APPROVAL_COPILOT_STREAM_CONTEXT.try_with(|_| ()).is_ok();
+
+ // Branch by origin. Web chat parks for an in-app approval; external
+ // channel persists an audit row and TTL-denies (no routable approval
+ // surface yet); trusted automation (cron, internal-only subconscious)
+ // is allowed through unchanged; tainted subconscious — a tick whose
+ // memory context contains external-sync chunks — is denied because
+ // remote text could otherwise steer it into an external_effect tool;
+ // CLI keeps the legacy allow; Unknown fails closed.
+ match &origin {
+ AgentTurnOrigin::WebChat { .. } => {
+ // Fall through to the existing chat-routed parking flow below.
+ }
+ AgentTurnOrigin::ExternalChannel {
+ channel,
+ sender,
+ reply_target,
+ message_id,
+ } => {
+ tracing::info!(
+ tool = tool_name,
+ channel = %channel,
+ sender = %sender.as_deref().unwrap_or("<unknown>"),
+ reply_target = %reply_target,
+ message_id = %message_id,
+ "[approval::gate] external channel turn — persisting audit row and parking"
+ );
+ // Fall through to the parking flow: a `pending_approvals` row
+ // is persisted (audit trail) and the future parks. We do NOT
+ // short-circuit to Allow here — remote inputs are untrusted.
+ // Without a routable surface the park TTL-denies; a decision
+ // can still arrive via the thread card before the TTL.
+ }
+ AgentTurnOrigin::TrustedAutomation {
+ source: TrustedAutomationSource::Cron,
+ job_id,
+ } => {
+ tracing::debug!(
+ tool = tool_name,
+ job_id = %job_id,
+ "[approval::gate] trusted cron automation — allowing without prompt"
+ );
+ return (GateOutcome::Allow, None);
+ }
+ AgentTurnOrigin::TrustedAutomation {
+ source: TrustedAutomationSource::Subconscious,
+ job_id,
+ } => {
+ tracing::debug!(
+ tool = tool_name,
+ job_id = %job_id,
+ "[approval::gate] trusted internal subconscious tick — allowing without prompt"
+ );
+ return (GateOutcome::Allow, None);
+ }
+ AgentTurnOrigin::TrustedAutomation {
+ source: TrustedAutomationSource::SubconsciousTainted,
+ job_id,
+ } => {
+ tracing::warn!(
+ tool = tool_name,
+ job_id = %job_id,
+ "[approval::gate] subconscious tick with external-sync memory in context — \
+ rejecting external_effect tool"
+ );
+ return (
+ GateOutcome::Deny {
+ reason: format!(
+ "{POLICY_DENIED_MARKER} Tool '{tool_name}' rejected: subconscious turn \
+ whose memory context includes external-sync chunks may not run \
+ external_effect tools."
+ ),
+ },
+ None,
+ );
+ }
+ AgentTurnOrigin::TrustedAutomation {
+ source: TrustedAutomationSource::GoalContinuation,
+ job_id,
+ } => {
+ tracing::debug!(
+ tool = tool_name,
+ job_id = %job_id,
+ "[approval::gate] autonomous goal continuation — external_effect tool parks \
+ (no present user to authorize); TTL-denies without a routable surface"
+ );
+ // Fall through to the parking flow: an autonomous continuation
+ // runs with no user present, so we must NOT auto-allow an
+ // irreversible external action. Read/compute tools (not gated
+ // here) still make progress on the goal.
+ }
+ AgentTurnOrigin::TrustedAutomation {
+ source:
+ TrustedAutomationSource::Workflow {
+ require_approval: false,
+ },
+ job_id,
+ } => {
+ tracing::debug!(
+ tool = tool_name,
+ flow_id = %job_id,
+ "[approval::gate] trusted workflow automation — pre-declared action, \
+ allowing without prompt"
+ );
+ return (GateOutcome::Allow, None);
+ }
+ AgentTurnOrigin::TrustedAutomation {
+ source:
+ TrustedAutomationSource::Workflow {
+ require_approval: true,
+ },
+ job_id,
+ } => {
+ tracing::info!(
+ tool = tool_name,
+ flow_id = %job_id,
+ "[approval::gate] workflow run has require_approval enabled — parking for \
+ HITL review instead of auto-allowing the trust root"
+ );
+ // Fall through to the parking flow (same shape as
+ // GoalContinuation): persists a `pending_approvals` audit row
+ // and publishes `ApprovalRequested`. There is no chat thread to
+ // route the prompt to for a background/triggered flow run yet
+ // (B3 will add a dedicated review surface) — a caller can still
+ // decide it via `approval_decide` (e.g. a generic pending-
+ // approvals list) before the TTL elapses; absent a decision this
+ // TTL-denies, the conservative fail-closed default for a
+ // user-forced HITL gate.
+ }
+ AgentTurnOrigin::Cli => {
+ tracing::debug!(
+ tool = tool_name,
+ "[approval::gate] CLI / sub-agent caller — allowing without prompt"
+ );
+ return (GateOutcome::Allow, None);
+ }
+ AgentTurnOrigin::Unknown => {
+ tracing::warn!(
+ tool = tool_name,
+ "[approval::gate] agent turn has no origin label — refusing to execute \
+ external_effect tool from unlabelled call site"
+ );
+ return (
+ GateOutcome::Deny {
+ reason: format!(
+ "{POLICY_DENIED_MARKER} '{tool_name}' was blocked because this agent \
+ turn is missing its origin label, so the approval gate cannot decide \
+ who requested the action. Scheduling and other external-effect tools \
+ (e.g. cron_add / cron_update) are refused when the turn has no origin. \
+ This is an internal wiring gap, not something you did — the work most \
+ likely ran on a background task that did not carry the turn's origin \
+ forward; retry from a normal chat turn, or report it so the spawn site \
+ can be fixed."
+ ),
+ },
+ None,
+ );
+ }
+ }
+
+ let request_id = uuid::Uuid::new_v4().to_string();
+ let now = chrono::Utc::now();
+ // Resolve the clamped park TTL up front so the persisted `expires_at`
+ // and the actual wait below (see `resolve_park_ttl` further down)
+ // use the same value — see `Self::resolve_park_ttl` and the
+ // COPILOT_APPROVAL_TTL clamp. Computing this
+ // only after persisting the pending row let a copilot-streaming park
+ // advertise the old 10-minute `expires_at` while only actually
+ // waiting 180s, so a core restart or an `expire_stale` sweep mid-park
+ // could leave the row "actionable" for the wrong window (CodeRabbit
+ // + Codex review on PR #5112).
+ let effective_ttl = Self::resolve_park_ttl(self.effective_ttl(), copilot_stream);
+ let expires_at = Some(now + chrono::Duration::from_std(effective_ttl).unwrap_or_default());
+
+ // Correlation context (flow-approval-surface, PR2): a Workflow-origin
+ // park carries the flow id on the origin itself, but not the run id —
+ // that comes from the `APPROVAL_FLOW_RUN_CONTEXT` task-local
+ // `flows::ops::flows_run`/`flows_resume` scope alongside `with_origin`.
+ // `try_with` returns `Err` for every non-flow caller (chat, cron,
+ // subconscious, CLI, and even a Workflow origin reached without the
+ // flows module's scope, which "should never happen" but must not
+ // panic), so `source_context` stays `None` there — unchanged chat
+ // behavior.
+ let source_context = match &origin {
+ AgentTurnOrigin::TrustedAutomation {
+ source: TrustedAutomationSource::Workflow { .. },
+ job_id: flow_id,
+ } => APPROVAL_FLOW_RUN_CONTEXT
+ .try_with(|ctx| ApprovalSourceContext::Flow {
+ flow_id: flow_id.clone(),
+ run_id: ctx.run_id.clone(),
+ node_id: None,
+ })
+ .ok(),
+ _ => None,
+ };
+
+ let pending = PendingApproval {
+ request_id: request_id.clone(),
+ tool_name: tool_name.to_string(),
+ action_summary: action_summary.to_string(),
+ args_redacted: args_redacted.clone(),
+ created_at: now,
+ expires_at,
+ source_context: source_context.clone(),
+ };
+
+ // Register the waiter BEFORE persisting the row so a fast
+ // `approval_decide` cannot mark the request approved while
+ // no waiter exists — would otherwise leave the parked call
+ // to time out and return `Deny` incorrectly. (CodeRabbit
+ // review on PR #2149.)
+ let (tx, rx) = oneshot::channel::<ApprovalDecision>();
+ {
+ let mut waiters = self.waiters.lock();
+ waiters.insert(request_id.clone(), tx);
+ }
+ // Record the thread → request mapping so an inbound chat reply on this
+ // thread can be routed to `approval_decide` (see web channel ingress).
+ if let Some(thread_id) = chat_thread_id.as_ref() {
+ self.thread_to_request
+ .lock()
+ .insert(thread_id.clone(), request_id.clone());
+ }
+ if let Err(err) = store::insert_pending(&self.config, &pending, &self.session_id) {
+ self.evict_waiter(&request_id);
+ self.clear_thread(&chat_thread_id, &request_id);
+ tracing::error!(
+ error = %err,
+ tool = tool_name,
+ "[approval::gate] failed to persist pending row — failing closed"
+ );
+ return (
+ GateOutcome::Deny {
+ reason: format!(
+ "{POLICY_DENIED_MARKER} Approval gate could not persist the request — \
+ denying for safety: {err}"
+ ),
+ },
+ None,
+ );
+ }
+
+ tracing::info!(
+ request_id = %request_id,
+ tool = tool_name,
+ thread_id = chat_thread_id.as_deref().unwrap_or("<none>"),
+ client_id = chat_client_id.as_deref().unwrap_or("<none>"),
+ "[approval::gate] publishing ApprovalRequested (surface fires only if thread_id+client_id are both set)"
+ );
+ BUS.publish(DomainEvent::ApprovalRequested {
+ request_id: request_id.clone(),
+ tool_name: tool_name.to_string(),
+ action_summary: action_summary.to_string(),
+ args_redacted,
+ thread_id: chat_thread_id.clone(),
+ client_id: chat_client_id.clone(),
+ });
+
+ // Flow-origin surface bridge (flow-approval-surface, PR3): a flow run
+ // has no chat thread/client to route the generic `ApprovalRequested`
+ // through (both are `None` above, so the web-channel bridge silently
+ // drops it — see `web_chat::event_bus`'s
+ // `ApprovalSurfaceSubscriber`), which is exactly the silent-deadlock
+ // bug this correlation fixes. Broadcast a dedicated
+ // `flow_approval_request` socket event (no thread/client required,
+ // unlike the chat path) plus a `CoreNotification` with the three
+ // flow-scoped decision actions, so the Workflows UI can surface and
+ // resolve the park without polling.
+ if let Some(ApprovalSourceContext::Flow {
+ flow_id, run_id, ..
+ }) = &source_context
+ {
+ tracing::info!(
+ request_id = %request_id,
+ flow_id = %flow_id,
+ run_id = %run_id,
+ tool = tool_name,
+ "[approval::gate] flow-origin park — surfacing flow_approval_request + notification"
+ );
+ BUS.publish(DomainEvent::FlowApprovalRequested {
+ request_id: request_id.clone(),
+ flow_id: flow_id.clone(),
+ run_id: run_id.clone(),
+ tool_name: tool_name.to_string(),
+ summary: action_summary.to_string(),
+ });
+ publish_flow_gate_notification(&request_id, flow_id, run_id, tool_name, action_summary);
+ }
+
+ tracing::info!(
+ request_id = %request_id,
+ tool = tool_name,
+ "[approval::gate] tool call parked, waiting for decision"
+ );
+
+ // Copilot-streaming flows_build runs get a clamped park window — see
+ // COPILOT_APPROVAL_TTL and `Self::resolve_park_ttl`. `effective_ttl` was resolved above
+ // (before `expires_at` was built) so the persisted expiry and this
+ // wait use the identical clamped duration; `effective_ttl()` applies
+ // the debug-only env override, and the clamp is applied on top so a
+ // longer override can't extend either park past its clamp.
+ if copilot_stream {
+ tracing::debug!(
+ tool = tool_name,
+ ttl_secs = COPILOT_APPROVAL_TTL.as_secs(),
+ "[approval::gate] flows_build copilot-streaming park — clamping park window to \
+ COPILOT_APPROVAL_TTL"
+ );
+ }
+
+ // Optional caller-supplied park bound (issue #4756). A caller
+ // (`composio_connect`) can cap how long the gate parks so a turn
+ // degrades to a fast prompt instead of blocking to the full TTL.
+ // Bounding must never *extend* the park, so we wait `min(bound, ttl)`;
+ // the caller-bound abandon path fires only when the bound is what
+ // elapses (`park_bound_active`).
+ let park_bound_active = matches!(park_bound, Some(b) if b < effective_ttl);
+ let wait = match park_bound {
+ Some(b) => b.min(effective_ttl),
+ None => effective_ttl,
+ };
+
+ // RAII cleanup for external teardown (#4774): if the turn future is
+ // dropped while parked on the await below (the #4746/#4751 wall-clock
+ // backstop firing), the match arms never run, so this guard evicts the
+ // waiter, clears routing, and denies the pending row on drop. Disarmed
+ // right after the match on every normal exit.
+ let mut waiter_guard = WaiterGuard {
+ gate: self,
+ request_id: request_id.clone(),
+ thread_id: chat_thread_id.clone(),
+ armed: true,
+ };
+
+ let outcome = match tokio::time::timeout(wait, rx).await {
+ Ok(Ok(decision)) => {
+ tracing::info!(
+ request_id = %request_id,
+ tool = tool_name,
+ decision = decision.as_str(),
+ "[approval::gate] decision received"
+ );
+ if decision.is_approve() {
+ (GateOutcome::Allow, Some(request_id.clone()))
+ } else {
+ (
+ GateOutcome::Deny {
+ reason: format!(
+ "{POLICY_DENIED_MARKER} User denied '{tool_name}' execution. Do \
+ not re-request the same call this turn; take a different approach \
+ or stop."
+ ),
+ },
+ None,
+ )
+ }
+ }
+ Ok(Err(_canceled)) => {
+ // Sender dropped — treat as denial so the agent does
+ // not silently no-op.
+ tracing::warn!(
+ request_id = %request_id,
+ tool = tool_name,
+ "[approval::gate] decision channel dropped — denying"
+ );
+ let _ = store::decide(&self.config, &request_id, ApprovalDecision::Deny);
+ (
+ GateOutcome::Deny {
+ reason: format!(
+ "{POLICY_DENIED_MARKER} Approval channel for '{tool_name}' closed \
+ before a decision was made."
+ ),
+ },
+ None,
+ )
+ }
+ Err(_elapsed) if park_bound_active => {
+ // Caller park bound elapsed (#4756) — NOT the gate's own TTL.
+ // Abandon the park cancellation-safely: evict the in-memory
+ // waiter and (via `clear_thread` below, on every
+ // exit) drop the routing mappings so a later chat/voice reply is
+ // not mis-routed to this now-abandoned request. Deliberately do
+ // NOT `store::decide(Deny)` — the `pending_approvals` row stays
+ // open so a later human card-click still resolves it in the DB
+ // and a re-ask sees it already-connected. Signal the elapse so
+ // the bounded caller renders its own fast-path result rather than
+ // a `Deny`.
+ self.evict_waiter(&request_id);
+ *park_bound_elapsed = true;
+ tracing::info!(
+ request_id = %request_id,
+ tool = tool_name,
+ bound_secs = wait.as_secs(),
+ "[approval::gate] caller park bound elapsed — abandoning park (row left \
+ pending for a later card-click; waiter + routing cleared) (#4756)"
+ );
+ // Placeholder outcome; the bounded caller discards it once
+ // `*park_bound_elapsed` is set (returns `None`).
+ (
+ GateOutcome::Deny {
+ reason: format!(
+ "{POLICY_DENIED_MARKER} Approval for '{tool_name}' exceeded the caller \
+ park bound ({}s).",
+ wait.as_secs()
+ ),
+ },
+ None,
+ )
+ }
+ Err(_elapsed) => {
+ self.evict_waiter(&request_id);
+ // Race: `decide()` may have committed an Approve in
+ // SQLite right as the TTL elapsed. `store::decide(Deny)`
+ // has `WHERE decided_at IS NULL` so it won't overwrite,
+ // but without a re-read we'd return Deny here while the
+ // durable audit row says Approved (CodeRabbit review on
+ // #2367). Try to deny; if the row was already decided,
+ // honor the persisted decision.
+ let denied = store::decide(&self.config, &request_id, ApprovalDecision::Deny);
+ let persisted = match &denied {
+ Ok(Some(_)) => Some(ApprovalDecision::Deny),
+ Ok(None) => store::get_decision(&self.config, &request_id)
+ .ok()
+ .flatten(),
+ Err(_) => None,
+ };
+ if matches!(persisted, Some(d) if d.is_approve()) {
+ tracing::info!(
+ request_id = %request_id,
+ tool = tool_name,
+ ttl_secs = effective_ttl.as_secs(),
+ "[approval::gate] timeout race: persisted decision was Approve, honoring approval"
+ );
+ // Fall through (no early return) so `clear_thread` below runs
+ // on this path too — otherwise the stale thread→request
+ // mapping survives and the next yes/no on the thread could be
+ // routed to this already-finished request.
+ (GateOutcome::Allow, Some(request_id.clone()))
+ } else {
+ tracing::warn!(
+ request_id = %request_id,
+ tool = tool_name,
+ ttl_secs = effective_ttl.as_secs(),
+ "[approval::gate] approval timed out, denying"
+ );
+ (
+ GateOutcome::Deny {
+ reason: format!(
+ "{POLICY_DENIED_MARKER} Approval for '{tool_name}' timed out after \
+ {}s. Do not re-request the same call this turn; take a different \
+ approach or stop.",
+ effective_ttl.as_secs()
+ ),
+ },
+ None,
+ )
+ }
+ }
+ };
+ // Reached only on a normal park resolution: the match arm above already
+ // ran the exact teardown for its outcome, so disarm the RAII guard (its
+ // Drop is reserved for external cancellation — see `WaiterGuard`).
+ waiter_guard.disarm();
+ // The routing mappings are only needed while parked; clear them on
+ // every exit (decision, channel drop, or timeout).
+ self.clear_thread(&chat_thread_id, &request_id);
+ outcome
+ }
+}
diff --git a/src/openhuman/security/approval/gate_setup.rs b/src/openhuman/security/approval/gate_setup.rs
new file mode 100644
index 0000000000..37a31e99a3
--- /dev/null
+++ b/src/openhuman/security/approval/gate_setup.rs
@@ -0,0 +1,213 @@
+impl ApprovalGate {
+ /// Install the process-global gate. Returns the existing gate if
+ /// one was already installed (re-install is a no-op so repeated
+ /// `bootstrap_core_runtime` calls in tests don't panic).
+ ///
+ /// Rows from prior launches are intentionally NOT purged on
+ /// install — the issue #1339 acceptance criterion requires they
+ /// survive restart so the UI can show / dismiss them. Orphan
+ /// rows have no live parked future, so a `decide` is a DB-only
+ /// audit update; no side effect can fire across processes.
+ pub fn init_global(config: Config, session_id: impl Into<String>) -> Arc<ApprovalGate> {
+ let session_id = session_id.into();
+ if let Some(existing) = GLOBAL_GATE.get() {
+ return existing.clone();
+ }
+ let gate = Arc::new(ApprovalGate::new(config, session_id, DEFAULT_APPROVAL_TTL));
+ let _ = GLOBAL_GATE.set(gate.clone());
+ GLOBAL_GATE.get().cloned().unwrap_or(gate)
+ }
+
+ /// Returns the global gate when installed; tools and harness
+ /// branches that don't care about supervised mode treat `None`
+ /// as "no gating".
+ pub fn try_global() -> Option<Arc<ApprovalGate>> {
+ GLOBAL_GATE.get().cloned()
+ }
+
+ fn new(config: Config, session_id: String, ttl: Duration) -> Self {
+ // Regression guard: the gate's session_id must be the per-launch
+ // UUID minted by `bootstrap_core_runtime` (shape:
+ // `session-<uuid>`). Any other shape risks re-introducing the
+ // credential leak that was fixed by switching off the RPC bearer
+ // — fail loudly in debug builds the moment a caller wires up a
+ // raw token (or any other ad-hoc string).
+ #[cfg(debug_assertions)]
+ debug_assert!(
+ session_id.starts_with("session-"),
+ "ApprovalGate session_id must be a per-launch UUID prefix, not a credential",
+ );
+ Self {
+ config,
+ session_id,
+ ttl,
+ waiters: Mutex::new(HashMap::new()),
+ thread_to_request: Mutex::new(HashMap::new()),
+ }
+ }
+
+ /// TTL for parking an approval. In debug builds `OPENHUMAN_APPROVAL_TTL_SECS`
+ /// overrides the boot-time default per intercept so E2E tests can exercise
+ /// the timeout path without waiting the full `DEFAULT_APPROVAL_TTL`.
+ ///
+ /// The override is compiled out of release builds (`#[cfg(debug_assertions)]`):
+ /// the shipped product never reads this env var, so a hostile process
+ /// environment cannot shorten the supervised-mode approval window. This
+ /// mirrors the host-aware discipline of the `OPENHUMAN_APPROVAL_GATE`
+ /// kill-switch — neither override can make the gate fail open; the timeout
+ /// path always denies.
+ fn effective_ttl(&self) -> Duration {
+ #[cfg(debug_assertions)]
+ if let Some(ttl) = std::env::var("OPENHUMAN_APPROVAL_TTL_SECS")
+ .ok()
+ .and_then(|v| v.parse::<u64>().ok())
+ .map(Duration::from_secs)
+ {
+ tracing::debug!(
+ ttl_secs = ttl.as_secs(),
+ "[approval::gate] TTL env override active (debug build)"
+ );
+ return ttl;
+ }
+ self.ttl
+ }
+
+ /// Resolve the actual park duration from the gate's own `effective_ttl`
+ /// plus the `copilot_stream` clamp ([`COPILOT_APPROVAL_TTL`]) when that
+ /// origin is active. A clamp only ever *shortens* the park — it can never
+ /// extend `effective_ttl` past what the gate itself allows (e.g. a debug
+ /// env override). Split out (rather than inlined at the call site) so it is
+ /// unit testable without needing to actually park a future.
+ fn resolve_park_ttl(effective_ttl: Duration, copilot_stream: bool) -> Duration {
+ let mut ttl = effective_ttl;
+ if copilot_stream {
+ ttl = ttl.min(COPILOT_APPROVAL_TTL);
+ }
+ ttl
+ }
+
+ /// Whether `tool_name` is on the user's "Always allow" list. Prefers the
+ /// process-global live policy (so a grant made this session is seen
+ /// immediately) and falls back to the gate's boot-time config snapshot.
+ fn tool_is_auto_approved(&self, tool_name: &str) -> bool {
+ if let Some(policy) = crate::openhuman::security::live_policy::current() {
+ return policy.auto_approve.iter().any(|t| t == tool_name);
+ }
+ self.config
+ .autonomy
+ .auto_approve
+ .iter()
+ .any(|t| t == tool_name)
+ }
+
+ /// Whether the user has opted into "auto-approve everything" — a
+ /// blanket bypass of the human approval prompt. Mirrors
+ /// [`Self::tool_is_auto_approved`]'s live-policy-first, boot-config-
+ /// fallback pattern so a toggle made this session (config save + live
+ /// policy reload) takes effect on the very next tool call.
+ ///
+ /// Callers MUST still exclude `TrustedAutomationSource::SubconsciousTainted`
+ /// and `AgentTurnOrigin::Unknown` before trusting this flag — see the
+ /// `matches!` guard at the call site below. This method only reports the
+ /// user's setting; it does not know about origin.
+ fn is_auto_approve_all_enabled(&self) -> bool {
+ if let Some(policy) = crate::openhuman::security::live_policy::current() {
+ return policy.auto_approve_all;
+ }
+ self.config.autonomy.auto_approve_all
+ }
+
+ /// Intercept a tool call. Blocks until the user decides or the
+ /// TTL elapses (timeout → `Deny`).
+ ///
+ /// Use [`Self::intercept_audited`] instead when the caller can
+ /// also record the *terminal* status of the tool — the audit
+ /// trail in `pending_approvals` only carries before-and-after
+ /// rows when both sides report in. See #2135.
+ pub async fn intercept(
+ &self,
+ tool_name: &str,
+ action_summary: &str,
+ args_redacted: serde_json::Value,
+ ) -> GateOutcome {
+ // Drop the request_id; callers using the legacy entry point
+ // don't record execution.
+ self.intercept_audited(tool_name, action_summary, args_redacted)
+ .await
+ .0
+ }
+
+ /// Audited variant of [`Self::intercept`].
+ ///
+ /// Returns `(outcome, Some(request_id))` when the call was
+ /// allowed AND a `pending_approvals` row was persisted — pass
+ /// the id back to [`Self::record_execution`] once the tool
+ /// finishes so the audit row carries both the approval and the
+ /// terminal status (issue #2135).
+ ///
+ /// Returns `(outcome, None)` when no DB row was created (session
+ /// allowlist shortcut) OR when the call was denied. In either
+ /// case there is nothing to record afterward, so the caller can
+ /// pattern-match `(GateOutcome::Allow, Some(id))` to decide
+ /// whether to invoke `record_execution`.
+ pub async fn intercept_audited(
+ &self,
+ tool_name: &str,
+ action_summary: &str,
+ args_redacted: serde_json::Value,
+ ) -> (GateOutcome, Option<String>) {
+ // No caller-supplied park bound: identical behavior to before. With
+ // `park_bound = None` the inner never takes the caller-bound abandon
+ // path, so the out-flag stays `false` and is discarded here.
+ let mut _park_bound_elapsed = false;
+ self.intercept_audited_inner(
+ tool_name,
+ action_summary,
+ args_redacted,
+ None,
+ &mut _park_bound_elapsed,
+ )
+ .await
+ }
+
+ /// Like [`Self::intercept_audited`] but the caller may cap how long the
+ /// gate parks (issue #4756).
+ ///
+ /// When `park_bound` is `Some` and shorter than the gate's own effective
+ /// TTL and it elapses before a decision arrives, the gate abandons the park
+ /// in a **cancellation-safe** way — it evicts the in-memory waiter and
+ /// clears the thread routing mapping (so a later chat reply
+ /// is not mis-routed to this now-abandoned request) but deliberately LEAVES
+ /// the `pending_approvals` row open, so a later human card-click can still
+ /// resolve it in the DB — and returns `None`. This is why callers must bound
+ /// the park through the gate rather than racing an outer
+ /// `tokio::time::timeout` against [`Self::intercept_audited`]: dropping the
+ /// parked future would skip that cleanup and orphan the waiter + routing
+ /// mappings (chatgpt-codex review on #4756).
+ ///
+ /// A `None` bound (or one `>=` the effective TTL) behaves exactly like
+ /// [`Self::intercept_audited`] and always returns `Some`.
+ pub async fn intercept_audited_bounded(
+ &self,
+ tool_name: &str,
+ action_summary: &str,
+ args_redacted: serde_json::Value,
+ park_bound: Option<Duration>,
+ ) -> Option<(GateOutcome, Option<String>)> {
+ let mut park_bound_elapsed = false;
+ let resolved = self
+ .intercept_audited_inner(
+ tool_name,
+ action_summary,
+ args_redacted,
+ park_bound,
+ &mut park_bound_elapsed,
+ )
+ .await;
+ if park_bound_elapsed {
+ None
+ } else {
+ Some(resolved)
+ }
+ }
+}
diff --git a/src/openhuman/security/approval/gate_state.rs b/src/openhuman/security/approval/gate_state.rs
new file mode 100644
index 0000000000..df5f59d0e8
--- /dev/null
+++ b/src/openhuman/security/approval/gate_state.rs
@@ -0,0 +1,207 @@
+impl ApprovalGate {
+ /// Write the *terminal* status of a tool call onto its approval
+ /// audit row — see [`store::record_execution`] for semantics.
+ ///
+ /// Logs (but does not propagate) write errors: the tool has
+ /// already run, so audit-log loss should never bubble up as a
+ /// tool execution failure to the agent. If durable audit storage
+ /// is required for compliance, callers wire it via a stronger
+ /// guarantee than this best-effort hook.
+ pub fn record_execution(
+ &self,
+ request_id: &str,
+ outcome: ExecutionOutcome,
+ error: Option<&str>,
+ ) {
+ match store::record_execution(&self.config, request_id, outcome, error) {
+ Ok(true) => tracing::debug!(
+ request_id = %request_id,
+ outcome = outcome.as_str(),
+ "[approval::gate] recorded terminal execution"
+ ),
+ Ok(false) => tracing::warn!(
+ request_id = %request_id,
+ outcome = outcome.as_str(),
+ "[approval::gate] record_execution found no matching decided row"
+ ),
+ Err(err) => tracing::error!(
+ request_id = %request_id,
+ outcome = outcome.as_str(),
+ error = %err,
+ "[approval::gate] record_execution write failed"
+ ),
+ }
+ }
+
+ /// Apply a user decision. Returns the now-decided
+ /// [`PendingApproval`] row when one was found.
+ pub fn decide(
+ &self,
+ request_id: &str,
+ decision: ApprovalDecision,
+ ) -> anyhow::Result<Option<PendingApproval>> {
+ let decided = store::decide(&self.config, request_id, decision)?;
+ if let Some(row) = &decided {
+ // `ApproveAlwaysForTool` persistence (append to `autonomy.auto_approve`
+ // + reload the live policy) is handled by the `approval_decide` RPC
+ // handler, which is async and owns the config save+reload path. The
+ // gate only resolves the parked future and emits the audit event.
+ if let Some(tx) = self.take_waiter(request_id) {
+ let _ = tx.send(decision);
+ }
+ BUS.publish(DomainEvent::ApprovalDecided {
+ request_id: row.request_id.clone(),
+ tool_name: row.tool_name.clone(),
+ decision: decision.as_str().to_string(),
+ });
+ }
+ Ok(decided)
+ }
+
+ /// Classify a [`Self::decide`] miss — i.e. when `decide` returned
+ /// `Ok(None)` because its conditional `UPDATE ... WHERE decided_at IS NULL`
+ /// matched 0 rows. Two very different states collapse into that `None`:
+ ///
+ /// - [`DecideMiss::AlreadyResolved`] — the row exists but was **already
+ /// decided, lazily expired (denied), or superseded**. This is the benign
+ /// double-tap / two-operator / expiry-while-live race the inline-approvals
+ /// design spec classifies as benign (TAURI-RUST-5EH).
+ /// - [`DecideMiss::NeverRegistered`] — no row was ever persisted for this
+ /// request_id. That is a genuine lost registration (a core restart dropped
+ /// the parked future before persisting, or a stray id) and must stay a
+ /// Sentry signal.
+ ///
+ /// We disambiguate by consulting [`store::get_decision`], which returns a
+ /// decision only when `decided_at IS NOT NULL` — exactly the already-resolved
+ /// case (expiry writes a `Deny` decision, so expired rows report here too).
+ /// A `decide` miss can't be an undecided-but-present row: that row would have
+ /// matched the `UPDATE`. If the lookup itself errors we conservatively keep
+ /// the event visible (`NeverRegistered`) rather than silently demoting.
+ pub fn classify_decide_miss(&self, request_id: &str) -> DecideMiss {
+ match store::get_decision(&self.config, request_id) {
+ Ok(Some(_)) => DecideMiss::AlreadyResolved,
+ Ok(None) => DecideMiss::NeverRegistered,
+ Err(err) => {
+ tracing::warn!(
+ request_id = %request_id,
+ error = %err,
+ "[approval::gate] classify_decide_miss: get_decision failed; treating as never-registered (keep visible)"
+ );
+ DecideMiss::NeverRegistered
+ }
+ }
+ }
+
+ /// List all undecided rows, including orphans from prior launches.
+ /// Orphan rows have no live parked future so a `decide` on them
+ /// updates the DB but cannot resume an action — see [`store::list_pending`].
+ pub fn list_pending(&self) -> anyhow::Result<Vec<PendingApproval>> {
+ store::list_pending(&self.config)
+ }
+
+ /// List recently decided rows for durable audit views.
+ pub fn list_recent_decisions(
+ &self,
+ limit: usize,
+ ) -> anyhow::Result<Vec<super::types::ApprovalAuditEntry>> {
+ store::list_recent_decisions(&self.config, limit)
+ }
+
+ /// List undecided rows correlated with a specific flow run (issue
+ /// flow-approval-surface, PR2) — lets a dedicated Workflows review
+ /// surface fetch just the gates blocking one run instead of filtering
+ /// [`Self::list_pending`] client-side.
+ pub fn list_pending_for_flow_run(
+ &self,
+ flow_id: &str,
+ run_id: &str,
+ ) -> anyhow::Result<Vec<PendingApproval>> {
+ store::list_pending_for_flow_run(&self.config, flow_id, run_id)
+ }
+
+ /// Grant "approve always for this flow" trust to `(flow_id, tool_name)`.
+ /// Called by the `approval_decide` RPC handler after an
+ /// [`ApprovalDecision::ApproveAlwaysForFlow`] decides a flow-origin row —
+ /// mirrors the RPC-owns-persistence split documented on
+ /// [`Self::decide`] for `ApproveAlwaysForTool`.
+ pub fn insert_flow_trust(&self, flow_id: &str, tool_name: &str) -> anyhow::Result<()> {
+ store::insert_flow_trust(&self.config, flow_id, tool_name)
+ }
+
+ /// Whether `(flow_id, tool_name)` currently holds "approve always for
+ /// this flow" trust. Exposed for tests and diagnostics; `intercept_audited`
+ /// consults [`store::is_flow_tool_trusted`] directly.
+ pub fn is_flow_tool_trusted(&self, flow_id: &str, tool_name: &str) -> anyhow::Result<bool> {
+ store::is_flow_tool_trusted(&self.config, flow_id, tool_name)
+ }
+
+ /// Every `tool_name` currently trusted for `flow_id`, sorted. Consumed by
+ /// `flows_approval_manifest` to diff the graph's required permissions
+ /// against grants that already exist (re-save asks only for what's new).
+ pub fn list_flow_trust(&self, flow_id: &str) -> anyhow::Result<Vec<String>> {
+ store::list_flow_trust(&self.config, flow_id)
+ }
+
+ /// Revoke flow trust: all grants for `flow_id` when `tool_names` is
+ /// `None` (flow deletion cleanup), or only the named grants. Returns the
+ /// number of rows removed.
+ pub fn delete_flow_trust(
+ &self,
+ flow_id: &str,
+ tool_names: Option<&[String]>,
+ ) -> anyhow::Result<usize> {
+ store::delete_flow_trust(&self.config, flow_id, tool_names)
+ }
+
+ /// Write the durable audit record for one save-time pre-authorization
+ /// grant (a born-decided `approve_always_for_flow` row) so blanket
+ /// grants stay inspectable in Settings → Approval history.
+ pub fn record_flow_preauthorization(
+ &self,
+ flow_id: &str,
+ tool_name: &str,
+ ) -> anyhow::Result<()> {
+ store::record_flow_preauthorization(&self.config, flow_id, tool_name, &self.session_id)
+ }
+
+ /// Return the session id this gate was installed with (used by
+ /// RPC handlers for diagnostics).
+ pub fn session_id(&self) -> &str {
+ &self.session_id
+ }
+
+ fn take_waiter(&self, request_id: &str) -> Option<oneshot::Sender<ApprovalDecision>> {
+ let mut waiters = self.waiters.lock();
+ waiters.remove(request_id)
+ }
+
+ fn evict_waiter(&self, request_id: &str) {
+ let mut waiters = self.waiters.lock();
+ waiters.remove(request_id);
+ }
+
+ /// The request_id of the approval currently parked on `thread_id`, if any.
+ /// Used by the web channel to route an inbound yes/no reply to a decision.
+ pub fn pending_for_thread(&self, thread_id: &str) -> Option<String> {
+ self.thread_to_request.lock().get(thread_id).cloned()
+ }
+
+ /// Drop the thread → request mapping when it still belongs to this request.
+ fn clear_thread(&self, thread_id: &Option<String>, request_id: &str) {
+ if let Some(t) = thread_id {
+ self.clear_thread_route_if_owned(t, request_id);
+ }
+ }
+
+ /// Drop the thread → request mapping **only if** it still points at
+ /// `request_id`. Used by [`WaiterGuard::drop`] on external teardown, where a
+ /// replacement turn may have already parked a new approval on the same
+ /// thread and overwritten the entry; clearing unconditionally would delete
+ /// the *new* request's routing (#4774).
+ fn clear_thread_route_if_owned(&self, thread_id: &str, request_id: &str) {
+ let mut map = self.thread_to_request.lock();
+ if map.get(thread_id).is_some_and(|rid| rid == request_id) {
+ map.remove(thread_id);
+ }
+ }
+}
diff --git a/src/openhuman/security/approval/gate_tests_part_03_tests.rs b/src/openhuman/security/approval/gate_tests_part_03_tests.rs
index 62750314c2..bf015dcc05 100644
--- a/src/openhuman/security/approval/gate_tests_part_03_tests.rs
+++ b/src/openhuman/security/approval/gate_tests_part_03_tests.rs
@@ -439,9 +439,7 @@ async fn decide_approve_always_for_flow_then_insert_flow_trust_composes_to_auto_
assert!(!gate.is_flow_tool_trusted("flow-2", "composio").unwrap());
match &decided.source_context {
- Some(super::super::super::types::ApprovalSourceContext::Flow {
- flow_id, ..
- }) => {
+ Some(super::super::super::types::ApprovalSourceContext::Flow { flow_id, .. }) => {
gate.insert_flow_trust(flow_id, &decided.tool_name).unwrap();
}
other => panic!("expected Flow source_context, got {other:?}"),