Skip to content

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

Merge remote-tracking branch 'origin/main' into epic-8055-70-caps-host

Steven Enamakel72fe6674b3da
diff --cc Cargo.lock
index 111436c1a7,6f1dcac50f..971f3ace81
--- a/Cargo.lock
+++ b/Cargo.lock
@@@ -9597,7 -9610,7 +9617,7 @@@ dependencies =
[[package]]
name = "tinymemory-api"
--version = "1.28.0"
++version = "1.29.0"
dependencies = [
"async-trait",
"chrono",
@@@ -9611,7 -9624,7 +9631,7 @@@
[[package]]
name = "tinymemory-integrations"
--version = "1.28.0"
++version = "1.29.0"
dependencies = [
"async-trait",
"chrono",
@@@ -9636,9 -9648,8 +9656,9 @@@
[[package]]
name = "tinymemory-tools"
--version = "1.28.0"
++version = "1.29.0"
dependencies = [
+ "async-lock",
"async-trait",
"chrono",
"futures",
@@@ -9653,7 -9663,7 +9673,7 @@@
[[package]]
name = "tinyredact"
--version = "1.28.0"
++version = "1.29.0"
dependencies = [
"log",
"regex",
diff --cc Cargo.toml
index 5d976ce171,ffbd623d36..11fed53906
--- a/Cargo.toml
+++ b/Cargo.toml
@@@ -43,6 -43,7 +43,7 @@@ repository = "https://github.com/tinyhu
openhuman-rpc = { path = "crates/openhuman-rpc", default-features = false }
openhuman-embed = { path = "crates/openhuman-embed", default-features = false }
openhuman-tinyhumans = { path = "crates/openhuman-tinyhumans", default-features = false }
-tinyagents-hooks = { path = "vendor/tinyagents/crates/tinyagents-hooks" }
++tinyagents-hooks = { path = "vendor/tinyagents/crates/tinyagents-hooks", default-features = false }
# Patches are workspace-root settings; Cargo ignores them in member manifests.
[patch."https://github.com/tinyhumansai/tinytools"]
diff --cc crates/openhuman-app/Cargo.lock
index 25b53a7c04,0d57f52778..a63ad6b57c
--- a/crates/openhuman-app/Cargo.lock
+++ b/crates/openhuman-app/Cargo.lock
@@@ -7199,7 -7169,7 +7170,7 @@@ dependencies =
[[package]]
name = "tinymemory-api"
--version = "1.28.0"
++version = "1.29.0"
dependencies = [
"async-trait",
"chrono",
@@@ -7213,7 -7183,7 +7184,7 @@@
[[package]]
name = "tinymemory-integrations"
--version = "1.28.0"
++version = "1.29.0"
dependencies = [
"async-trait",
"chrono",
@@@ -7238,9 -7207,8 +7209,9 @@@
[[package]]
name = "tinymemory-tools"
--version = "1.28.0"
++version = "1.29.0"
dependencies = [
+ "async-lock",
"async-trait",
"chrono",
"futures",
@@@ -7255,7 -7222,7 +7226,7 @@@
[[package]]
name = "tinyredact"
--version = "1.28.0"
++version = "1.29.0"
dependencies = [
"log",
"regex",
diff --cc crates/openhuman-core/src/agent/README.md
index 791bee9480,7a570cd3d0..593499d85e
--- a/crates/openhuman-core/src/agent/README.md
+++ b/crates/openhuman-core/src/agent/README.md
@@@ -218,15 -218,13 +218,15 @@@ coding workers, and background completi
### Agent definitions, registry and prompts
- An `AgentDefinition` ([`harness/host_definition.rs`](./harness/host_definition.rs), vocabulary in `tinyagents-definition`) is an archetype: id, tier,
+ An `AgentDefinition` ([`../agent_registry/host_definition.rs`](../agent_registry/host_definition.rs), vocabulary in `tinyagents-definition`) is an archetype: id, tier,
prompt source, model spec, `ToolScope`, `SandboxMode`, iteration policy and
- allowed sub-agents. Built-ins live in `registry/agents/<id>/` as an
+ allowed sub-agents. Built-ins live in `../agent_registry/agents/<id>/` as an
-`agent.toml` plus `prompt.md` (orchestrator, planner, critic, summarizer,
-trigger_triage, trigger_reactor, vision_agent and others). Custom
+`agent.toml` plus a prompt builder. Most use a sibling `prompt.md` for their
+archetype (orchestrator, planner, critic, summarizer, trigger_triage,
+trigger_reactor, vision_agent and others); the workflow builder and discovery
+agents fetch their archetypes from TinyFlows Copilot over the module bus. Custom
definitions are TOML files under `<workspace>/agents/*.toml`, with
- `~/.openhuman/agents/*.toml` as a fallback (`tinyagents_definition::DefinitionSet::load_dirs`, driven from [`harness/host_definition.rs`](./harness/host_definition.rs)).
+ `~/.openhuman/agents/*.toml` as a fallback (`tinyagents_definition::DefinitionSet::load_dirs`, driven from [`../agent_registry/host_definition.rs`](../agent_registry/host_definition.rs)).
`AgentDefinitionRegistry` holds the merged set; `agent.reload_definitions`
rebuilds it.
diff --cc crates/openhuman-core/src/agent/context/README.md
index 04d1a2f86e,2644661d86..1d030eaa50
--- a/crates/openhuman-core/src/agent/context/README.md
+++ b/crates/openhuman-core/src/agent/context/README.md
@@@ -15,79 -10,16 +10,81 @@@ owns transcript reduction and middlewar
| File | Role |
| --- | --- |
- | [`crates/openhuman-core/src/agent/context/mod.rs`](./mod.rs) | Module docstring, `pub mod` decls, `pub use` re-exports, and the three shared constants (`DEFAULT_TOOL_RESULT_BUDGET_BYTES`, `CLEARED_PLACEHOLDER`, `DEFAULT_KEEP_RECENT_TOOL_RESULTS`). No other logic. |
- | [`crates/openhuman-core/src/agent/context/manager.rs`](./manager.rs) | `ContextManager`: per-session handle agents hold. Owns the default prompt builder, `ContextStatsState`, and the `ContextConfig`-derived knobs. Surfaces `build_system_prompt` / `build_system_prompt_tiered`, `stats()`, the getters the tinyagents turn reads (`tool_result_budget_bytes`, `compaction_enabled`, `autocompact_enabled`, `microcompact_keep_recent`, `autocompact_enabled`, `compaction()` (trigger override and strategy), `prefer_markdown_tool_output`), and the session-memory trigger/mark methods. |
- | `crates/openhuman-core/src/agent/context/stats.rs` | `ContextStatsState`: last provider usage, context-window utilisation, and the shared `SessionMemoryHandle` (`Arc<Mutex<SessionMemoryState>>`). Pure state; issues no LLM calls and does not mutate history. |
- | `crates/openhuman-core/src/agent/context/session_memory.rs` | `SessionMemoryState` / `SessionMemoryConfig`: threshold-gated `should_extract` decision (token growth, tool calls, and turns must all cross) and extraction bookkeeping. Holds `ARCHIVIST_EXTRACTION_PROMPT`. State-tracking only; does not spawn the archivist. |
- | `crates/openhuman-core/src/agent/context/channels_prompt.rs` | Bespoke free functions `build_system_prompt(...)` / `build_system_prompt_with_identity(...)` (plus `PromptIdentityOverride`, `ProjectContextPlacement`, `render_project_context`) for channel runtimes (Discord/Slack/Telegram/…). Byte-stable for prefix-cache hits; injects workspace bootstrap files (`SOUL.md`, `IDENTITY.md`, optional `PROFILE.md`/`MEMORY.md`, with profile overrides for `SOUL.md`/`MEMORY.md`), tools, safety, skills, runtime, and channel-capabilities sections. |
- | [`crates/openhuman-core/src/agent/context/manager_tests.rs`](./manager_tests.rs), [`channels_prompt_tests.rs`](./channels_prompt_tests.rs), `session_memory_tests.rs` | Sibling test files wired via `#[cfg(test)] #[path = "..."] mod tests;` from their source file (the layout check rejects inline test modules). |
+ | [`mod.rs`](./mod.rs) | Module documentation and `DEFAULT_KEEP_RECENT_TOOL_RESULTS`. |
- ## History (#4249)
+ There is no per-session `ContextManager` here. The former manager, statistics,
+ session-memory state, tool-result budget constant, and cleared-placeholder
+ constant were removed as their responsibilities moved to the config schema,
+ TinyAgents middleware, and `tinyagents-harness`.
- Live history reduction/summarization moved out of this directory into the tinyagents turn path:
+ ## Consumers
+- `pipeline.rs`: removed; live context reduction moved to tinyagents middleware, stats state lives in `stats.rs`.
+- `guard.rs`: removed; the live 0.90 compression threshold is `SUMMARIZE_THRESHOLD_FRACTION` in `agent/tinyagents/summarize.rs`.
+- `microcompact.rs`: removed; live tool-result body clearing is owned by `tinyagents_harness::middleware::MicrocompactMiddleware`, only the shared constants remain in `mod.rs`.
+- `tool_result_budget.rs`: removed; UTF-8-safe per-result truncation moved next to action-workspace artifact preview/fallback handling in `agent/harness/tool_result_artifacts`.
+- `summarizer.rs`: removed; live summarization moved to `agent/tinyagents/summarize.rs` (`ModelSummarizer`, which also carries the summarizer system prompt).
+- `segment_recap_summarizer.rs`: removed; the recap-backed compaction wrapper is gone.
+- `summarizer_tests.rs` / `segment_recap_summarizer_tests.rs`: removed along with the files above.
+
+## Public surface
+
+From `mod.rs` re-exports:
+
+- Manager: `ContextManager`, `ContextStats`.
+- Microcompact config: `CLEARED_PLACEHOLDER`, `DEFAULT_KEEP_RECENT_TOOL_RESULTS`.
+- Prompt: `SystemPromptBuilder`, `PromptSection`, `PromptContext`, `PromptTool`, `ArchetypePromptSection`, `DateTimeSection`, `IdentitySection`, `LearnedContextData`, `RuntimeSection`, `SafetySection`, `ToolsSection`, and `WorkspaceSection` are imported directly from `agent::prompts`.
+- Tool-result budget: `DEFAULT_TOOL_RESULT_BUDGET_BYTES` config default only; live truncation is owned by `ToolOutputMiddleware` / `tool_result_artifacts`.
+
+`ContextStatsState` is `pub(crate)` and not re-exported.
+
+## RPC / controllers
+
+None. No `schemas.rs`, no `all_controller_schemas`, no `handle_*`. The `ContextStats` doc comment mentions an "optional `context.get_stats` RPC", but no such schema or handler exists anywhere in the crate.
+
+## Agent tools
+
+None. No `tools.rs`.
+
+## Events
+
+None. No `bus.rs`; no `DomainEvent`s published or subscribed.
+
+## Persistence
+
+No `store.rs`. State is per-session and in-memory:
+
+- `ContextStatsState` holds last token counts and the context window.
+
+## Dependencies
+
+- `crate::config`: `ContextConfig` ([`config/schema/context.rs`](../../config/schema/context.rs)): `enabled`, `microcompact_enabled` / `microcompact_keep_recent`, `autocompact_enabled`, `compaction_trigger_tokens` (absolute summarization trigger for benchmarks; env `OPENHUMAN_COMPACTION_TRIGGER_TOKENS`), `compaction_strategy` (env `OPENHUMAN_COMPACTION_STRATEGY`), `compaction_enabled`, `tool_result_budget_bytes`, `prefer_markdown_tool_output`, `summarizer_model`, and the embedded `session_memory: SessionMemoryConfig`.
+- `crate::inference::provider::UsageInfo`: fed into `record_usage`.
+- `crate::agent::prompts`: owns prompt rendering; `channels_prompt.rs` uses `inject_inline_content`.
+- `crate::skills::Workflow`: `channels_prompt.rs` renders the available-skills section from a `&[Workflow]`.
+
+## Used by
+
+- `agent::harness`: the primary consumer: `session/builder/builder_build.rs` constructs the `ContextManager`; `session/turn/core/harness_turn.rs` reads the budget/compaction getters into the tinyagents turn config; `session/turn/session_io/{transcript_persist,background_tasks}.rs` read `stats()`; `fork_context.rs` and [`../subagent_host/`](../subagent_host/) consume prompt types.
+- `agent::tinyagents`: `turn_middleware.rs` reads `CLEARED_PLACEHOLDER` when configuring `MicrocompactMiddleware`; `payload_summarizer.rs` and `host/context_composer.rs` build `PromptContext`s through `agent::prompts`.
- - **`agent::registry::agents/*/prompt.rs`**, `skills/*/agent/*/prompt.rs`: archetype prompt modules pull prompt sections/builder through `agent::prompts`.
++- **`agent_registry::agents/*/prompt.rs`**, `skills/*/agent/*/prompt.rs`: archetype prompt modules pull prompt sections/builder through `agent::prompts`.
+- `channels`: [`channels/system_prompt.rs`](../../channels/system_prompt.rs) (`ChannelSystemPrompt`, used by [`channels/runtime/startup/start_channels.rs`](../../channels/runtime/startup/start_channels.rs)) calls `channels_prompt::build_system_prompt_with_identity`; [`channels/mod.rs`](../../channels/mod.rs) re-exports `build_system_prompt`; the `channels/tests/*` prompt/identity tests call it directly.
+- `agent::triage`, `agent::debug`, `agent::orchestration::tools` (spawn_subagent and friends), `tools::orchestrator_tools`, `integrations::composio`: consume prompt types (`PromptContext`, `PromptSection`, `ToolCallFormat`, `ConnectedIntegration`, …) via `agent::prompts`.
+
+## Notes / gotchas
+
+- **The context stats state issues no LLM calls and does not mutate history.** Live reduction is owned by the tinyagents middleware stack.
+- **Tool-result budgeting is not a context pipeline stage.** The tinyagents path applies per-result budgets in `ToolOutputMiddleware` ([`agent/tinyagents/middleware/tool_output.rs`](../tinyagents/middleware/tool_output.rs)), and artifact-preview fallback truncation lives in `agent/harness/tool_result_artifacts`.
+- **`autocompact_enabled()` is `config.enabled && config.autocompact_enabled`**, and `microcompact_keep_recent()` is `0` when `microcompact_enabled` is off: the manager folds the config gates so the turn reads one value per knob.
+- Prompt rendering does not belong in this module; add it to `agent::prompts`.
+- **`channels_prompt::build_system_prompt` deliberately bypasses `SystemPromptBuilder`** to keep production channel prompt bytes stable for prefix-cache hits; it is a standalone free function despite living under `context/`.
+
+## Further reading
+
+- [Parent module README](../README.md)
+- [Agent harness architecture](../../../../../docs/gitbooks/en/developing/architecture/agent-harness.md)
+- [Smart token compression](../../../../../docs/gitbooks/en/features/token-compression.md)
+ The TinyAgents host maps configured context options into harness middleware.
+ Channel and agent prompts use `agent::prompts`; live transcript compaction and
+ tool-result clearing run in TinyAgents. This module owns no persistence,
+ controllers, tools, or event subscribers.
diff --cc crates/openhuman-core/src/agent/harness/README.md
index b642eed663,4843cccf0f..01782b51c6
--- a/crates/openhuman-core/src/agent/harness/README.md
+++ b/crates/openhuman-core/src/agent/harness/README.md
@@@ -78,11 -77,12 +77,11 @@@ turn lifecycle are in `../session_host/
(`<tool_call>` tags, fenced blocks, bare JSON, `<invoke>` XML, GLM grammar,
p-format). This crate is a test-only dependency of `harness/`; the parsers
are not called from production code here.
- - `crate::agent::registry::agents`: built-in agent archetype TOML/prompt
- bundles loaded by `tinyagents_definition` (user TOML) and `builtin_definitions`.
+ - `crate::agent_registry::agents`: built-in agent archetype TOML/prompt
+ bundles; custom bundles are loaded by `tinyagents_definition`.
- `crate::security::SecurityPolicy`: workspace containment policy plumbed
into `artifact_offload::new_artifact_offload`.
-- `tinymemory-api`: provenance classification and untrusted-context wrapping,
- configured with connector prefixes from `memory::provenance`.
+- `tinymemory-api`: provenance classification and untrusted-context wrapping.
- `crate::memory`: text
sanitization (`artifact_offload::SanitizingRedactor` wraps `memory::safety::sanitize_text` for both artifact stores).
- `crate::config::AgentConfig`, `crate::skills::Workflow`,
diff --cc crates/openhuman-core/src/agent/harness/graph.rs
index e1d41a4204,29ab4c31b3..ed014dc4a1
--- a/crates/openhuman-core/src/agent/harness/graph.rs
+++ b/crates/openhuman-core/src/agent/harness/graph.rs
@@@ -56,10 -56,10 +56,10 @@@ pub(crate) async fn run_channel_turn_vi
multimodal: MultimodalConfig,
multimodal_files: MultimodalFileConfig,
on_progress: Option<Sender<AgentProgress>>,
- origin: Option<crate::agent::turn_origin::AgentTurnOrigin>,
+ origin: Option<crate::security::turn_origin::AgentTurnOrigin>,
sandbox_mode: tinyagents_definition::SandboxMode,
approval: crate::security::approval::ApprovalTurnContext,
- memory_identity: crate::memory::scope::MemoryIdentity,
+ memory_identity: tinymemory_tools::layout::identity::Identity,
) -> Result<crate::agent::tinyagents::TinyagentsTurnOutcome> {
let extra_arc = Arc::new(extra_tools);
// A channel/CLI turn is entered without a run context: the model source
diff --cc crates/openhuman-core/src/agent/harness/test_support.rs
index 1509a6278c,b573b3ffe9..03548c4111
--- a/crates/openhuman-core/src/agent/harness/test_support.rs
+++ b/crates/openhuman-core/src/agent/harness/test_support.rs
@@@ -1,47 -1,8 +1,14 @@@
- //! Built-in [`AgentDefinition`]s.
+ //! Test-only agent definitions used by harness and orchestration tests.
+//!
- //! The authoritative list of built-in agents lives in
- //! [`crate::agent::registry::agents`] — each agent is a subfolder
- //! containing `agent.toml` and a prompt builder. Most builders embed a
- //! sibling `prompt.md`; the flow builders fetch their archetypes from
- //! TinyFlows Copilot through the module bus. This module is a thin
- //! wrapper that loads that set.
- //!
- //! Custom TOML definitions loaded later by
- //! [`super::definition_loader`] override any built-in with the same id.
++//! The authoritative built-in list lives in
++//! [`crate::agent_registry::agents`]. Flow agent prompts are fetched from
++//! TinyFlows Copilot through the module bus; the test fixtures here let
++//! orchestration tests exercise those definitions without moving registry
++//! ownership into the agent harness.
- use super::host_definition::AgentDefinition;
- #[cfg(test)]
+ use crate::agent_registry::host_definition::AgentDefinition;
use tinyagents_definition::DefinitionSource;
- /// All built-in definitions, in stable order.
- ///
- /// Panics if the baked-in built-in TOML fails to parse. `include_str!`
- /// guarantees at compile time that each file exists, but the actual
- /// TOML parse happens at runtime; the unit tests in
- /// [`crate::agent::registry::agents`] verify in CI that every entry in
- /// [`crate::agent::registry::agents::BUILTINS`] still parses cleanly.
- ///
- /// In `#[cfg(test)]` builds the list additionally contains
- /// [`test_inherit_echo_def`] — a sub-agent with `ModelSpec::Inherit`
- /// that exists solely so the spawn-subagent end-to-end test can
- /// exercise the dispatch/threading plumbing with the *parent's*
- /// provider (every shipped builtin uses `Hint(...)`, which after
- /// #1710 builds a fresh factory provider and therefore can't share a
- /// test's `MockProvider`). It is never compiled into release builds.
- pub fn all() -> Vec<AgentDefinition> {
- #[allow(unused_mut)]
- let mut defs = crate::agent::registry::agents::load_builtins()
- .expect("built-in agent TOML must always parse (see agents/*/agent.toml)");
- #[cfg(test)]
- {
- defs.push(test_main_def());
- defs.push(test_inherit_echo_def());
- defs.push(test_inherit_parallel_worker_def());
- }
- defs
- }
-
/// Test-only parent used by `AgentBuilder`'s default `agent_definition_name = "main"`.
///
/// Production builds do not ship a `main` agent definition. In tests, the
diff --cc crates/openhuman-core/src/agent/orchestration/delegation.rs
index 70ad0ea907,7c3e4a48fb..8022188c84
--- a/crates/openhuman-core/src/agent/orchestration/delegation.rs
+++ b/crates/openhuman-core/src/agent/orchestration/delegation.rs
@@@ -144,76 -140,142 +140,142 @@@ pub(crate) async fn run_subagent_delega
outcome.agent_id.clone(),
question.clone(),
);
- if let Some(progress) = stage_parent.data.progress.clone() {
- let _ = progress
- .send(AgentProgress::SubagentAwaitingUser {
- agent_id: outcome.agent_id.clone(),
- task_id: outcome.task_id.clone(),
- question: question.clone(),
- worker_thread_id: None,
- checkpoint_path: checkpoint
- .as_ref()
- .map(|path| path.to_string_lossy().to_string()),
- })
- .await;
- }
+ if let Some(progress) = stage_parent.data.progress.clone() {
+ let _ = progress
+ .send(AgentProgress::SubagentAwaitingUser {
+ agent_id: outcome.agent_id.clone(),
+ task_id: outcome.task_id.clone(),
+ question: question.clone(),
+ worker_thread_id: None,
+ checkpoint_path: checkpoint
+ .as_ref()
+ .map(|path| path.to_string_lossy().to_string()),
+ })
+ .await;
}
- return Err(format!(
- "[SUBAGENT_AWAITING_USER]\nagent_id: {}\ntask_id: {}\nquestion: {}\ncheckpointed: {}\n[/SUBAGENT_AWAITING_USER]\n\
+ }
+ return Err(format!(
+ "[SUBAGENT_AWAITING_USER]\nagent_id: {}\ntask_id: {}\nquestion: {}\ncheckpointed: {}\n[/SUBAGENT_AWAITING_USER]\n\
delegation stage {stage:?} is awaiting user input; relay the answer with continue_subagent using this task_id.",
- outcome.agent_id,
- outcome.task_id,
- serde_json::to_string(&question).unwrap_or_else(|_| {
- "\"<unserializable question>\"".to_string()
- }),
- checkpoint.is_some(),
+ outcome.agent_id,
+ outcome.task_id,
+ serde_json::to_string(&question).unwrap_or_else(|_| {
+ "\"<unserializable question>\"".to_string()
+ }),
+ checkpoint.is_some(),
- ));
- }
- SubagentRunStatus::Incomplete { reason, .. } => {
- return Err(format!(
- "delegation stage {stage:?} stopped incomplete: {reason}"
- ));
- }
- SubagentRunStatus::Cancelled => {
- return Err(format!("delegation stage {stage:?} was cancelled"));
- }
+ ));
+ }
- SubagentRunStatus::Incomplete { reason } => {
++ SubagentRunStatus::Incomplete { reason, .. } => {
+ return Err(format!(
+ "delegation stage {stage:?} stopped incomplete: {reason}"
+ ));
+ }
+ SubagentRunStatus::Cancelled => {
+ return Err(format!("delegation stage {stage:?} was cancelled"));
}
- let approved = matches!(stage, DelegationStage::Review)
- && review_approves(&outcome.output);
- Ok(DelegationStageOutput {
- text: outcome.output,
- approved,
- // Persist the exact prompt this stage sent so the
- // execute step's `StepRecord` carries its provenance
- // (read only for the execute stage; #3884).
- prompt: Some(prompt),
- })
}
- Err(e) => Err(format!("delegation stage {stage:?} failed: {e}")),
+ let approved = matches!(stage, DelegationStage::Review)
+ && review_approves(&outcome.output);
+ Ok(DelegationStageOutput {
+ text: outcome.output,
+ approved,
+ // Persist the exact prompt this stage sent so the
+ // execute step's `StepRecord` carries its provenance
+ // (read only for the execute stage; #3884).
+ prompt: Some(prompt),
+ })
}
+ Err(e) => Err(format!("delegation stage {stage:?} failed: {e}")),
}
- };
-
- let delegation_config = DelegationConfig {
- max_revisions,
- checkpointer: Some(checkpointer),
- thread_id: Some(thread_id),
- cancel: graph_cancellation,
- // Automated (non-human-gated) delegation: the reviewer stage decides
- // approve/revise on its own. The durable human-approval interrupt
- // (see `tinyagents_graph::delegation::run_delegation_durable`) is opt-in and
- // stays off here until a human-review delegation surface wires it.
- ..DelegationConfig::default()
- };
- // Resume-aware entry (#3884): with today's fresh-per-run `thread_id` this
- // is always a fresh run; reusing a stable `thread_id` resumes from the
- // last checkpoint boundary instead of restarting.
- run_or_resume_with_tracing(delegation_config, run_stage)
- .await
- .map(|outcome| outcome.state)
+ }
};
+ let config_checkpointer = Arc::clone(&checkpointer);
+ let config_thread_id = thread_id.clone();
+ let config_factory =
+ move |_state: &(), parent: &RunContext<OpenHumanRunContext>, _args: &serde_json::Value| {
+ let mut delegation_config = DelegationConfig {
+ max_revisions,
+ checkpointer: Some(Arc::clone(&config_checkpointer)),
+ thread_id: Some(config_thread_id.clone()),
+ cancel: parent.cancellation.clone(),
+ // Automated delegation: preserve the host's existing worker-output
+ // review policy while the generic tool owns graph lifecycle mechanics.
+ ..DelegationConfig::default()
+ };
+ delegation_config.event_sink = Some(Arc::new(tinyagents_graph::GraphTracingSink::new(
+ "delegation:graph",
+ )));
+ delegation_config
+ };
+ let result_agent_id = invocation_agent_id.clone();
+ let tool = tinyagents_orchestration::subagent::DelegationTool::new(config_factory, run_stage)
+ .with_tool_name("delegate_graph")
+ .with_description("Durable plan, execute, review, and finalize delegation.")
+ .with_parameters(serde_json::json!({
+ "type": "object",
+ "required": ["task"],
+ "properties": {"task": {"type": "string"}}
+ }))
+ .with_resumable_execution()
+ .with_review_approval_policy(
+ tinyagents_orchestration::subagent::ReviewApprovalPolicy::WorkerOutput,
+ )
+ .with_metadata(
+ PermissionLevel::Execute,
+ ToolScope::All,
+ ToolCategory::System,
+ ToolTimeout::Unbounded,
+ )
+ .with_result_projection(move |result| match result {
+ Ok(outcome) if outcome.pending.is_some() => {
+ let pending = outcome.pending.expect("checked above");
+ ToolResult::json(serde_json::json!({
+ "status": "pending",
+ "state": outcome.state,
+ "pending": {
+ "interrupt_id": pending.interrupt_id,
+ "node": pending.node,
+ "payload": pending.payload,
+ "thread_id": pending.thread_id,
+ }
+ }))
+ }
+ Ok(outcome) if outcome.state.cancelled => {
+ ToolResult::error(format!("delegate_graph cancelled for '{result_agent_id}'."))
+ }
+ Ok(outcome) => {
+ let state = outcome.state;
+ let final_output = state
+ .final_output
+ .unwrap_or_else(|| "(delegation produced no final output)".to_string());
+ let note = if state.revisions > 0 {
+ " (after revision)"
+ } else {
+ ""
+ };
+ ToolResult::success(format!(
+ "[Delegated to {result_agent_id}{note}, {} review pass(es)]\n{final_output}",
+ state.reviews.len()
+ ))
+ }
+ Err(error) => ToolResult::error(format!(
+ "delegate_graph failed for '{result_agent_id}': {error}"
+ )),
+ });
- run.await
+ tool.execute(
+ &(),
+ tinyagents_harness::CallId::new(format!("delegation-{thread_id}")),
+ serde_json::json!({
+ "agent_id": invocation_agent_id,
+ "task": invocation_task_prompt,
+ "max_revisions": max_revisions
+ }),
+ ToolCallOptions::default(),
+ &live_parent,
+ )
+ .await
+ .map_err(|error| format!("delegate_graph failed: {error}"))
}
/// Per-stage prompt builder: each stage sees the task plus the accumulated state
diff --cc crates/openhuman-core/src/agent/orchestration/spawn_parallel/staging.rs
index d243067540,910385706c..7ead1fff89
--- a/crates/openhuman-core/src/agent/orchestration/spawn_parallel/staging.rs
+++ b/crates/openhuman-core/src/agent/orchestration/spawn_parallel/staging.rs
@@@ -337,9 -324,19 +342,19 @@@ pub(crate) async fn prepare_spawn_paral
);
let policy = SpawnParallelPolicy {
parent,
- kinds: Mutex::new(HashMap::new()),
+ kinds: RejectionKinds::default(),
};
- let staged = plan.stage(&policy);
+ // Resolve product definitions and normalize the prompt in the owner's
+ // async staging seam. This preparation is side-effect free, so the shared
+ // workspace admission/arbitration still completes before dispatch creates
+ // any worktrees or publishes spawn effects.
+ let staged = plan
+ .stage_with_preflight(&policy, |_, mut task| async move {
+ task.payload.definition = definitions.get(&task.payload.agent_id).cloned();
+ task.prompt = task.prompt.trim().to_string();
+ Ok(task)
+ })
+ .await;
let kinds = policy.kinds.into_inner();
staged
.into_iter()
diff --cc crates/openhuman-core/src/agent/orchestration/subagent_sessions/ops.rs
index 606636de7c,6093af3359..b75c1224b0
--- a/crates/openhuman-core/src/agent/orchestration/subagent_sessions/ops.rs
+++ b/crates/openhuman-core/src/agent/orchestration/subagent_sessions/ops.rs
@@@ -94,79 -104,63 +104,76 @@@ pub fn upsert_running
let _guard = store_write_lock()
.lock()
.map_err(|_| "subagent session store lock poisoned".to_string())?;
+ if let Some(reuse) = reuse {
+ let selector = upsert.selector.clone();
+ let worker_thread_id = upsert.worker_thread_id.clone();
+ let display_name = upsert.display_name.clone();
+ let task_id = upsert.task_id.clone();
++ let expected_task_id = reuse.current_task_id.clone();
++ let expected_lifecycle_key = reuse.lifecycle_key.clone();
+ if let Some(updated) =
- store.update_session(&reuse.subagent_session_id, move |session, now| {
++ store.update_session_if(&reuse.subagent_session_id, move |session, now| {
++ if session.status == DurableSubagentStatus::Closed
++ || session.current_task_id != expected_task_id
++ || session.lifecycle_key != expected_lifecycle_key
++ || !session.matches_selector(&selector)
++ {
++ return false;
++ }
+ session.parent_session = selector.parent_session.clone();
+ session.parent_thread_id = selector.parent_thread_id.clone();
+ session.worker_thread_id = worker_thread_id
+ .clone()
+ .or_else(|| session.worker_thread_id.clone());
+ session.display_name = display_name
+ .clone()
+ .or_else(|| session.display_name.clone());
+ session.current_task_id = Some(task_id.clone());
+ session.status = DurableSubagentStatus::Running;
+ session.reusable = true;
+ session.latest_error = None;
+ session.updated_at = now.clone();
+ session.last_used_at = now;
++ true
+ })?
+ {
+ return Ok(updated);
+ }
++ if store
++ .load()?
++ .iter()
++ .any(|session| session.subagent_session_id == reuse.subagent_session_id)
++ {
++ return Err("stale reusable sub-agent session changed during upsert".into());
++ }
+ }
let mut sessions = store.load()?;
let now = chrono::Utc::now().to_rfc3339();
-- let session_id = reuse
-- .map(|session| session.subagent_session_id.clone())
-- .unwrap_or_else(|| format!("subsess-{}", uuid::Uuid::new_v4()));
++ let session_id = format!("subsess-{}", uuid::Uuid::new_v4());
-- let mut session = if let Some(existing) = sessions
-- .iter()
-- .find(|session| session.subagent_session_id == session_id)
-- .cloned()
-- {
- if let Some(reuse) = reuse {
- if existing.status == DurableSubagentStatus::Closed
- || existing.current_task_id != reuse.current_task_id
- || existing.lifecycle_key != reuse.lifecycle_key
- {
- return Err("stale reusable sub-agent session changed during upsert".into());
- }
- }
-- existing
-- } else {
-- DurableSubagentSession {
-- subagent_session_id: session_id.clone(),
-- parent_session: upsert.selector.parent_session.clone(),
-- parent_thread_id: upsert.selector.parent_thread_id.clone(),
-- worker_thread_id: upsert.worker_thread_id.clone(),
-- agent_id: upsert.selector.agent_id.clone(),
-- display_name: upsert.display_name.clone(),
-- model: upsert.selector.model.clone(),
-- sandbox_mode: upsert.selector.sandbox_mode.clone(),
-- action_root: upsert.selector.action_root.clone(),
-- task_key: upsert.selector.task_key.clone(),
-- task_title: upsert.task_title.clone(),
-- current_task_id: None,
- lifecycle_key: None,
-- status: DurableSubagentStatus::Running,
-- reusable: true,
-- latest_history: None,
-- latest_error: None,
-- created_at: now.clone(),
-- updated_at: now.clone(),
-- last_used_at: now.clone(),
-- }
++ let mut session = DurableSubagentSession {
++ subagent_session_id: session_id.clone(),
++ parent_session: upsert.selector.parent_session.clone(),
++ parent_thread_id: upsert.selector.parent_thread_id.clone(),
++ worker_thread_id: upsert.worker_thread_id.clone(),
++ agent_id: upsert.selector.agent_id.clone(),
++ display_name: upsert.display_name.clone(),
++ model: upsert.selector.model.clone(),
++ sandbox_mode: upsert.selector.sandbox_mode.clone(),
++ action_root: upsert.selector.action_root.clone(),
++ task_key: upsert.selector.task_key.clone(),
++ task_title: upsert.task_title.clone(),
++ current_task_id: Some(upsert.task_id),
++ lifecycle_key: upsert.lifecycle_key,
++ status: DurableSubagentStatus::Running,
++ reusable: true,
++ latest_history: None,
++ latest_error: None,
++ created_at: now.clone(),
++ updated_at: now.clone(),
++ last_used_at: now.clone(),
};
-- session.parent_session = upsert.selector.parent_session;
-- session.parent_thread_id = upsert.selector.parent_thread_id;
-- session.worker_thread_id = upsert.worker_thread_id.or(session.worker_thread_id);
-- session.display_name = upsert.display_name.or(session.display_name);
-- session.current_task_id = Some(upsert.task_id);
- session.lifecycle_key = upsert.lifecycle_key.or(session.lifecycle_key);
-- session.status = DurableSubagentStatus::Running;
-- session.reusable = true;
-- session.latest_error = None;
-- session.updated_at = now.clone();
-- session.last_used_at = now;
--
sessions.retain(|existing| existing.subagent_session_id != session_id);
sessions.push(session.clone());
store.save(&sessions)?;
@@@ -180,16 -174,13 +187,17 @@@ pub fn mark_finished
run_status: &SubagentRunStatus,
history: Vec<TranscriptMessage>,
) -> Result<(), String> {
- let updated = update_session_for_task(store, subagent_session_id, task_id, |session, now| {
- session.status = DurableSubagentStatus::from_run_status(run_status);
- session.latest_history = Some(history);
- session.latest_error = None;
- session.updated_at = now.clone();
- session.last_used_at = now;
- })?;
+ let task_id = task_id.to_owned();
+ let status = DurableSubagentStatus::from_run_status(run_status);
- let updated = update_session(store, subagent_session_id, move |session, now| {
- session.current_task_id = Some(task_id.clone());
- session.status = status;
- session.latest_history = Some(history.clone());
- session.latest_error = None;
- session.updated_at = now.clone();
- session.last_used_at = now;
- })?;
++ let updated =
++ update_session_for_task(store, subagent_session_id, &task_id, move |session, now| {
++ session.current_task_id = Some(task_id.clone());
++ session.status = status;
++ session.latest_history = Some(history.clone());
++ session.latest_error = None;
++ session.updated_at = now.clone();
++ session.last_used_at = now;
++ })?;
if updated {
Ok(())
} else {
@@@ -205,14 -196,12 +213,15 @@@ pub fn mark_failed
task_id: &str,
error: String,
) -> Result<(), String> {
- let updated = update_session_for_task(store, subagent_session_id, task_id, |session, now| {
- session.status = DurableSubagentStatus::Failed;
- session.latest_error = Some(error);
- session.updated_at = now.clone();
- session.last_used_at = now;
- })?;
+ let task_id = task_id.to_owned();
- let updated = update_session(store, subagent_session_id, move |session, now| {
- session.current_task_id = Some(task_id.clone());
- session.status = DurableSubagentStatus::Failed;
- session.latest_error = Some(error.clone());
- session.updated_at = now.clone();
- session.last_used_at = now;
- })?;
++ let updated =
++ update_session_for_task(store, subagent_session_id, &task_id, move |session, now| {
++ session.current_task_id = Some(task_id.clone());
++ session.status = DurableSubagentStatus::Failed;
++ session.latest_error = Some(error.clone());
++ session.updated_at = now.clone();
++ session.last_used_at = now;
++ })?;
if updated {
Ok(())
} else {
@@@ -231,6 -220,42 +240,35 @@@ pub fn close(store: &SubagentSessionSto
})
}
+ /// Closes a session only if it still contains the lifecycle snapshot that the
+ /// caller observed and cancelled. `false` means a concurrent reuse or close
+ /// won the race and this stale request did not alter the newer row.
+ pub fn close_if_current(
+ store: &SubagentSessionStore,
+ observed: &DurableSubagentSession,
+ ) -> Result<bool, String> {
+ let _guard = store_write_lock()
+ .lock()
+ .map_err(|_| "subagent session store lock poisoned".to_string())?;
- let mut sessions = store.load()?;
- let now = chrono::Utc::now().to_rfc3339();
- let Some(session) = sessions
- .iter_mut()
- .find(|session| session.subagent_session_id == observed.subagent_session_id)
- else {
- return Ok(false);
- };
- if session.parent_session != observed.parent_session
- || session.parent_thread_id != observed.parent_thread_id
- || session.current_task_id != observed.current_task_id
- || session.lifecycle_key != observed.lifecycle_key
- {
- return Ok(false);
- }
- if session.status == DurableSubagentStatus::Closed {
- return Ok(true);
- }
- session.status = DurableSubagentStatus::Closed;
- session.reusable = false;
- session.updated_at = now.clone();
- session.last_used_at = now;
- store.save(&sessions)?;
- Ok(true)
++ let observed = observed.clone();
++ Ok(store
++ .update_session_if(&observed.subagent_session_id, move |session, now| {
++ if session.parent_session != observed.parent_session
++ || session.parent_thread_id != observed.parent_thread_id
++ || session.current_task_id != observed.current_task_id
++ || session.lifecycle_key != observed.lifecycle_key
++ {
++ return false;
++ }
++ session.status = DurableSubagentStatus::Closed;
++ session.reusable = false;
++ session.updated_at = now.clone();
++ session.last_used_at = now;
++ true
++ })?
++ .is_some())
+ }
+
pub fn list_for_parent(
store: &SubagentSessionStore,
parent_session: &str,
@@@ -272,11 -297,52 +310,40 @@@ wher
let _guard = store_write_lock()
.lock()
.map_err(|_| "subagent session store lock poisoned".to_string())?;
- let mut sessions = store.load()?;
- let now = chrono::Utc::now().to_rfc3339();
- if let Some(session) = sessions
- .iter_mut()
- .find(|session| session.subagent_session_id == subagent_session_id)
- {
- update(session, now);
- store.save(&sessions)?;
- return Ok(true);
- }
- Ok(false)
+ store
+ .update_session(subagent_session_id, update)
+ .map(|updated| updated.is_some())
}
+ /// Apply a terminal write only while it still belongs to the current task.
+ /// The check and write share the store lock so a late completion cannot
+ /// overwrite a reused session or revive one that has already been closed.
+ fn update_session_for_task<F>(
+ store: &SubagentSessionStore,
+ subagent_session_id: &str,
+ task_id: &str,
+ update: F,
+ ) -> Result<bool, String>
+ where
- F: FnOnce(&mut DurableSubagentSession, String),
++ F: FnMut(&mut DurableSubagentSession, String) + Send + 'static,
+ {
+ let _guard = store_write_lock()
+ .lock()
+ .map_err(|_| "subagent session store lock poisoned".to_string())?;
- let mut sessions = store.load()?;
- let now = chrono::Utc::now().to_rfc3339();
- if let Some(session) = sessions
- .iter_mut()
- .find(|session| session.subagent_session_id == subagent_session_id)
- {
- if session.status == DurableSubagentStatus::Closed
- || session.current_task_id.as_deref() != Some(task_id)
- {
- return Ok(false);
- }
- update(session, now);
- store.save(&sessions)?;
- return Ok(true);
- }
- Ok(false)
++ let task_id = task_id.to_owned();
++ Ok(store
++ .update_session_if(subagent_session_id, move |session, now| {
++ if session.status == DurableSubagentStatus::Closed
++ || session.current_task_id.as_deref() != Some(task_id.as_str())
++ {
++ return false;
++ }
++ update(session, now);
++ true
++ })?
++ .is_some())
+ }
+
fn store_write_lock() -> &'static Mutex<()> {
static LOCK: OnceLock<Mutex<()>> = OnceLock::new();
LOCK.get_or_init(|| Mutex::new(()))
diff --cc crates/openhuman-core/src/agent/orchestration/subagent_sessions/ops_driver.rs
index 0000000000,6fbdee1e73..a8b6e1200d
mode 000000,100644..100644
--- a/crates/openhuman-core/src/agent/orchestration/subagent_sessions/ops_driver.rs
+++ b/crates/openhuman-core/src/agent/orchestration/subagent_sessions/ops_driver.rs
@@@ -1,0 -1,390 +1,394 @@@
+ use std::path::Path;
+
+ use super::*;
+
+ /// Requests cancellation of driver-backed children owned by a thread being
+ /// removed. The TinyAgents registry owns cancellation and settlement; this
+ /// adapter only selects durable rows and resolves their authenticated keys.
+ pub fn cancel_driver_jobs_for_thread(
+ store: &SubagentSessionStore,
+ workspace_dir: &Path,
+ jobs: &tinyagents_orchestration::subagent::SubAgentJobRegistry,
+ thread_id: &str,
+ ) -> Vec<String> {
+ let sessions = match store.load() {
+ Ok(sessions) => sessions,
+ Err(error) => {
+ log::warn!(
+ "[subagent_sessions] failed to load sessions for thread cancellation: {error}"
+ );
+ return Vec::new();
+ }
+ };
+ let mut cancelled = Vec::new();
+ for session in sessions.into_iter().filter(|session| {
+ session.parent_thread_id.as_deref() == Some(thread_id)
+ && matches!(
+ session.status,
+ DurableSubagentStatus::Running | DurableSubagentStatus::AwaitingUser
+ )
+ }) {
+ let Some(task_id) = session.current_task_id.as_deref() else {
+ continue;
+ };
+ let key = session
+ .lifecycle_key
+ .filter(|key| key.task_id == task_id)
+ .or_else(|| {
+ resolve_lifecycle_key(
+ store,
+ &session.subagent_session_id,
+ &session.parent_session,
+ Some(thread_id),
+ &workspace_dir.join(".openhuman/subagent_checkpoints"),
+ )
+ .ok()
+ .filter(|key| key.task_id == task_id)
+ });
+ let Some(key) = key else {
+ continue;
+ };
+ let owner = crate::agent::tinyagents::tool_registration::subagent_owner_key(
+ workspace_dir,
+ &session.parent_session,
+ Some(thread_id),
+ );
+ if jobs.cancel_key_owned(&key, owner).is_ok() {
+ cancelled.push(task_id.to_owned());
+ }
+ }
+ cancelled
+ }
+
+ /// Requests cancellation for the exact durable row observed by the caller.
+ /// Keeping this separate from a fresh session-id lookup prevents concurrent
+ /// reuse from redirecting cancellation to a replacement child.
+ pub fn cancel_driver_job_for_observed_session(
+ store: &SubagentSessionStore,
+ checkpoint_dir: &Path,
+ jobs: &tinyagents_orchestration::subagent::SubAgentJobRegistry,
+ session: &DurableSubagentSession,
+ parent_session: &str,
+ parent_thread_id: Option<&str>,
+ ) -> bool {
+ if session.parent_session != parent_session
+ || session.parent_thread_id.as_deref() != parent_thread_id
+ {
+ return false;
+ }
+ let Some(task_id) = session.current_task_id.as_deref() else {
+ return false;
+ };
+ let key = session
+ .lifecycle_key
+ .clone()
+ .filter(|key| key.task_id == task_id && key.thread_id.as_deref() == parent_thread_id)
+ .or_else(|| {
+ resolve_lifecycle_key(
+ store,
+ &session.subagent_session_id,
+ parent_session,
+ parent_thread_id,
+ checkpoint_dir,
+ )
+ .ok()
+ .filter(|key| key.task_id == task_id)
+ });
+ let Some(key) = key else {
+ return false;
+ };
+ let owner = crate::agent::tinyagents::tool_registration::subagent_owner_key(
+ &store.workspace_dir,
+ parent_session,
+ parent_thread_id,
+ );
+ jobs.cancel_key_owned(&key, owner).is_ok()
+ }
+
+ /// A driver-backed child selected and cancelled by its public task id.
+ ///
+ /// The selector is scoped to the caller's durable session store and refuses
+ /// ambiguous task IDs. The actual cancellation remains keyed by the full
+ /// authenticated TinyAgents lifecycle key.
+ #[derive(Debug, Clone, PartialEq, Eq)]
+ pub struct DriverTaskCancellation {
+ pub task_id: String,
+ pub agent_id: String,
+ pub parent_session: String,
+ pub subagent_session_id: String,
+ pub workspace_dir: std::path::PathBuf,
+ pub parent_thread_id: Option<String>,
+ pub already_finished: Option<tinyagents_orchestration::subagent::FinishedOutcome>,
+ pub was_paused: bool,
+ pub lifecycle_key: Option<tinyagents_orchestration::subagent::SubagentTaskKey>,
+ }
+
+ pub fn cancel_driver_job_by_task(
+ store: &SubagentSessionStore,
+ checkpoint_dir: &Path,
+ jobs: &tinyagents_orchestration::subagent::SubAgentJobRegistry,
+ task_id: &str,
+ reason: Option<&str>,
+ ) -> Result<Option<DriverTaskCancellation>, String> {
+ let mut matches = store
+ .load()
+ .map_err(|error| format!("failed to load subagent sessions for cancellation: {error}"))?
+ .into_iter()
+ .filter(|session| session.current_task_id.as_deref() == Some(task_id));
+ let Some(session) = matches.next() else {
+ return Ok(None);
+ };
+ if matches.next().is_some() {
+ return Ok(None);
+ }
+ let was_paused = session.status == DurableSubagentStatus::AwaitingUser;
+ if session.status == DurableSubagentStatus::Closed {
+ return Ok(None);
+ }
+ let lifecycle_key = match session.lifecycle_key.clone() {
+ Some(key) => Some(key),
+ None if session.current_task_id.is_some()
+ && matches!(
+ session.status,
+ DurableSubagentStatus::Idle
+ | DurableSubagentStatus::Running
+ | DurableSubagentStatus::AwaitingUser
+ ) =>
+ {
+ Some(
+ resolve_lifecycle_key(
+ store,
+ task_id,
+ &session.parent_session,
+ session.parent_thread_id.as_deref(),
+ checkpoint_dir,
+ )
+ .map_err(|error| {
+ format!("failed to resolve subagent lifecycle for cancellation: {error}")
+ })?,
+ )
+ }
+ None => None,
+ };
+ if lifecycle_key
+ .as_ref()
+ .is_some_and(|key| key.task_id != task_id || key.thread_id != session.parent_thread_id)
+ {
+ return Ok(None);
+ }
+ let typed_finished =
+ || -> Result<Option<tinyagents_orchestration::subagent::FinishedOutcome>, String> {
+ let Some(key) = lifecycle_key.as_ref() else {
+ return Ok(None);
+ };
+ let Some(outcome) =
+ crate::agent::subagent_host::load_terminal_outcome(&store.workspace_dir, key)?
+ else {
+ return Ok(None);
+ };
+ Ok(match outcome.status {
+ tinyagents_orchestration::subagent::SubagentOutcomeKind::Completed => {
+ Some(tinyagents_orchestration::subagent::FinishedOutcome::Completed)
+ }
+ tinyagents_orchestration::subagent::SubagentOutcomeKind::Incomplete(_) => {
+ Some(tinyagents_orchestration::subagent::FinishedOutcome::Failed)
+ }
+ tinyagents_orchestration::subagent::SubagentOutcomeKind::Cancelled
+ | tinyagents_orchestration::subagent::SubagentOutcomeKind::AwaitingInput(_) => None,
+ })
+ };
+ let already_finished = match session.status {
+ DurableSubagentStatus::Idle => {
+ let finished = typed_finished()?;
+ if finished.is_none() {
+ return Ok(None);
+ }
+ finished
+ }
+ DurableSubagentStatus::Failed => match typed_finished()? {
+ Some(finished) => Some(finished),
+ // Pre-driver failures have a failed product row but no typed
+ // lifecycle record. Keep that legacy outcome reportable.
+ None if session.lifecycle_key.is_none() => {
+ Some(tinyagents_orchestration::subagent::FinishedOutcome::Failed)
+ }
+ None => return Ok(None),
+ },
+ DurableSubagentStatus::Running | DurableSubagentStatus::AwaitingUser => None,
+ DurableSubagentStatus::Closed => unreachable!("closed handled above"),
+ };
+ if already_finished.is_none()
+ && reason.is_some()
+ && !record_cancel_reason(store, &session, reason.expect("checked above").trim())?
+ {
+ return Ok(None);
+ }
+ if already_finished.is_none()
+ && !cancel_driver_job_for_observed_session(
+ store,
+ checkpoint_dir,
+ jobs,
+ &session,
+ &session.parent_session,
+ session.parent_thread_id.as_deref(),
+ )
+ {
+ if reason.is_some() {
+ clear_cancel_reason(store, &session);
+ }
+ return Ok(None);
+ }
+ Ok(Some(DriverTaskCancellation {
+ task_id: task_id.to_owned(),
+ agent_id: session.agent_id,
+ parent_session: session.parent_session,
+ subagent_session_id: session.subagent_session_id,
+ workspace_dir: store.workspace_dir.clone(),
+ parent_thread_id: session.parent_thread_id,
+ already_finished,
+ was_paused,
+ lifecycle_key,
+ }))
+ }
+
+ /// Mark a paused driver's durable product row cancelled only if it is still
+ /// the same lifecycle selected by the RPC. Paused driver completion has
+ /// already returned, so there is no live callback left to project this host
+ /// state transition.
+ pub fn mark_driver_pause_cancelled(
+ store: &SubagentSessionStore,
+ observed: &DriverTaskCancellation,
+ ) -> Result<bool, String> {
+ if !observed.was_paused {
+ return Ok(false);
+ }
+ let _guard = store_write_lock()
+ .lock()
+ .map_err(|_| "subagent session store lock poisoned".to_string())?;
+ let mut sessions = store.load()?;
+ let Some(session) = sessions
+ .iter_mut()
+ .find(|session| session.subagent_session_id == observed.subagent_session_id)
+ else {
+ return Ok(false);
+ };
+ if session.parent_session != observed.parent_session
+ || session.parent_thread_id != observed.parent_thread_id
+ || session.current_task_id.as_deref() != Some(observed.task_id.as_str())
+ || session.lifecycle_key != observed.lifecycle_key
+ || session.status != DurableSubagentStatus::AwaitingUser
+ {
+ return Ok(false);
+ }
+ session.status = DurableSubagentStatus::Failed;
+ session
+ .latest_error
+ .get_or_insert_with(|| "cancelled by user".into());
+ session.updated_at = chrono::Utc::now().to_rfc3339();
+ session.last_used_at = session.updated_at.clone();
+ store.save(&sessions)?;
+ Ok(true)
+ }
+
+ /// Persist an optional RPC cancellation reason before signaling TinyAgents so
+ /// the awaited completion callback can include it in the single cancellation
+ /// notice. The current task check prevents a stale cancel from annotating a
+ /// later reuse of the same durable session.
+ pub(crate) fn record_cancel_reason(
+ store: &SubagentSessionStore,
+ observed: &DurableSubagentSession,
+ reason: &str,
+ ) -> Result<bool, String> {
+ if reason.is_empty() {
+ return Ok(true);
+ }
+ mutate_observed_session(store, observed, |session, now| {
+ if matches!(
+ session.status,
+ DurableSubagentStatus::Running | DurableSubagentStatus::AwaitingUser
+ ) {
+ session.latest_error = Some(reason.to_owned());
+ session.updated_at = now;
+ }
+ })
+ }
+
+ fn clear_cancel_reason(store: &SubagentSessionStore, observed: &DurableSubagentSession) {
+ let _ = mutate_observed_session(store, observed, |session, now| {
+ session.latest_error = None;
+ session.updated_at = now;
+ });
+ }
+
+ fn mutate_observed_session<F>(
+ store: &SubagentSessionStore,
+ observed: &DurableSubagentSession,
+ update: F,
+ ) -> Result<bool, String>
+ where
+ F: FnOnce(&mut DurableSubagentSession, String),
+ {
+ let _guard = store_write_lock()
+ .lock()
+ .map_err(|_| "subagent session store lock poisoned".to_string())?;
+ let mut sessions = store.load()?;
+ let Some(session) = sessions
+ .iter_mut()
+ .find(|session| session.subagent_session_id == observed.subagent_session_id)
+ else {
+ return Ok(false);
+ };
+ if session.parent_session != observed.parent_session
+ || session.parent_thread_id != observed.parent_thread_id
+ || session.current_task_id != observed.current_task_id
+ || session.lifecycle_key != observed.lifecycle_key
+ || session.status != observed.status
+ {
+ return Ok(false);
+ }
+ update(session, chrono::Utc::now().to_rfc3339());
+ store.save(&sessions)?;
+ Ok(true)
+ }
+
+ /// Resolve a saved product session to its exact TinyAgents lifecycle key.
+ ///
+ /// The product session lookup is scoped by the authenticated parent session,
+ /// optional parent thread, and the workspace-specific store. Rows written
+ /// before `lifecycle_key` was added recover it only from the matching host
+ /// checkpoint; a public task id alone is never treated as a lifecycle key.
+ pub fn resolve_lifecycle_key(
+ store: &SubagentSessionStore,
+ session_or_task_id: &str,
+ parent_session: &str,
+ parent_thread_id: Option<&str>,
+ checkpoint_dir: &Path,
+ ) -> Result<tinyagents_orchestration::subagent::SubagentTaskKey, String> {
+ let session = list_for_parent(store, parent_session, parent_thread_id)?
+ .into_iter()
+ .find(|session| {
+ session.subagent_session_id == session_or_task_id
+ || session.current_task_id.as_deref() == Some(session_or_task_id)
+ })
+ .ok_or_else(|| "durable subagent session not found".to_string())?;
+ let task_id = session
+ .current_task_id
+ .as_deref()
+ .ok_or_else(|| "durable subagent session has no current task".to_string())?;
+ let key = if let Some(key) = session.lifecycle_key {
+ key
+ } else {
+ crate::agent::subagent_host::load_subagent_checkpoint(checkpoint_dir, task_id)
+ .map_err(|error| format!("legacy subagent checkpoint unavailable: {error}"))?
+ .task_key
+ .ok_or_else(|| "legacy subagent checkpoint has no lifecycle key".to_string())?
+ };
+ if key.task_id != task_id || key.thread_id.as_deref() != session.parent_thread_id.as_deref() {
+ return Err("durable subagent lifecycle key does not match its owned session".into());
+ }
+ Ok(key)
+ }
++
++#[cfg(test)]
++#[path = "ops_driver_tests.rs"]
++mod tests;
diff --cc crates/openhuman-core/src/agent/orchestration/subagent_sessions/ops_driver_tests.rs
index 0000000000,0000000000..e9555755a8
new file mode 100644
--- /dev/null
+++ b/crates/openhuman-core/src/agent/orchestration/subagent_sessions/ops_driver_tests.rs
@@@ -1,0 -1,0 +1,110 @@@
++use super::*;
++
++const FIXED_TIMESTAMP: &str = "2026-10-19T12:00:00.000Z";
++
++fn session(updated_at: &str) -> DurableSubagentSession {
++ DurableSubagentSession {
++ subagent_session_id: "session-1".into(),
++ parent_session: "parent-1".into(),
++ parent_thread_id: Some("thread-1".into()),
++ worker_thread_id: Some("worker-1".into()),
++ agent_id: "researcher".into(),
++ display_name: None,
++ model: Some("model-1".into()),
++ sandbox_mode: "read_only".into(),
++ action_root: None,
++ task_key: "task-key".into(),
++ task_title: "Task title".into(),
++ current_task_id: Some("task-1".into()),
++ lifecycle_key: Some(tinyagents_orchestration::subagent::SubagentTaskKey {
++ root_run_id: "root-1".into(),
++ parent_run_id: "parent-run-1".into(),
++ thread_id: Some("thread-1".into()),
++ task_id: "task-1".into(),
++ }),
++ status: DurableSubagentStatus::Running,
++ reusable: true,
++ latest_history: None,
++ latest_error: None,
++ created_at: updated_at.into(),
++ updated_at: updated_at.into(),
++ last_used_at: updated_at.into(),
++ }
++}
++
++#[test]
++fn observed_mutation_persists_when_the_timestamp_does_not_advance() {
++ let dir = tempfile::tempdir().unwrap();
++ let store = SubagentSessionStore::new(dir.path().to_path_buf());
++ let observed = session(FIXED_TIMESTAMP);
++ store.save(std::slice::from_ref(&observed)).unwrap();
++
++ let updated = mutate_observed_session(&store, &observed, |current, _now| {
++ // This models the equal-millisecond case without sleeping or relying
++ // on clock scheduling: the requested field changes, but its persisted
++ // updated_at remains exactly the stored timestamp.
++ current.latest_error = Some("cancel reason".into());
++ })
++ .unwrap();
++
++ assert!(updated);
++ let persisted = store.load().unwrap().pop().unwrap();
++ assert_eq!(persisted.updated_at, FIXED_TIMESTAMP);
++ assert_eq!(persisted.latest_error.as_deref(), Some("cancel reason"));
++}
++
++fn change_parent(session: &mut DurableSubagentSession) {
++ session.parent_session = "replacement-parent".into();
++}
++
++fn change_thread(session: &mut DurableSubagentSession) {
++ session.parent_thread_id = Some("replacement-thread".into());
++}
++
++fn change_task(session: &mut DurableSubagentSession) {
++ session.current_task_id = Some("replacement-task".into());
++}
++
++fn change_lifecycle(session: &mut DurableSubagentSession) {
++ session.lifecycle_key.as_mut().unwrap().root_run_id = "replacement-root".into();
++}
++
++fn change_status(session: &mut DurableSubagentSession) {
++ session.status = DurableSubagentStatus::AwaitingUser;
++}
++
++#[test]
++fn observed_mutation_rejects_a_stale_parent_thread_task_lifecycle_or_status() {
++ let changes: [(&str, fn(&mut DurableSubagentSession)); 5] = [
++ ("parent", change_parent),
++ ("thread", change_thread),
++ ("task", change_task),
++ ("lifecycle", change_lifecycle),
++ ("status", change_status),
++ ];
++
++ for (field, change_current) in changes {
++ let dir = tempfile::tempdir().unwrap();
++ let store = SubagentSessionStore::new(dir.path().to_path_buf());
++ let observed = session(FIXED_TIMESTAMP);
++ let mut current = observed.clone();
++ change_current(&mut current);
++ store.save(std::slice::from_ref(&current)).unwrap();
++
++ let mut closure_called = false;
++ let updated = mutate_observed_session(&store, &observed, |session, _now| {
++ closure_called = true;
++ session.latest_error = Some("stale mutation".into());
++ })
++ .unwrap();
++
++ assert!(!updated, "stale {field} must not update the current row");
++ assert!(!closure_called, "stale {field} must reject before mutation");
++ let persisted = store.load().unwrap().pop().unwrap();
++ assert_eq!(
++ serde_json::to_value(&persisted).unwrap(),
++ serde_json::to_value(&current).unwrap(),
++ "stale {field} must leave the current row unchanged"
++ );
++ }
++}
diff --cc crates/openhuman-core/src/agent/orchestration/subagent_sessions/store.rs
index 2a80f78818,3daca14f75..b05dcff1f6
--- a/crates/openhuman-core/src/agent/orchestration/subagent_sessions/store.rs
+++ b/crates/openhuman-core/src/agent/orchestration/subagent_sessions/store.rs
@@@ -56,19 -56,4 +56,34 @@@ impl SubagentSessionStore
self.import_legacy(&docs)?;
docs.save(sessions).map_err(|err| format!("{err:#}"))
}
+
+ pub fn update_session<F>(
+ &self,
+ subagent_session_id: &str,
+ update: F,
+ ) -> Result<Option<DurableSubagentSession>, String>
+ where
+ F: FnMut(&mut DurableSubagentSession, String) + Send + 'static,
+ {
+ let docs = super::store_documents::current(&self.workspace_dir)
+ .map_err(|err| format!("{err:#}"))?;
+ self.import_legacy(&docs)?;
+ docs.update_session(subagent_session_id, update)
+ .map_err(|err| format!("{err:#}"))
+ }
++
++ pub fn update_session_if<F>(
++ &self,
++ subagent_session_id: &str,
++ update: F,
++ ) -> Result<Option<DurableSubagentSession>, String>
++ where
++ F: FnMut(&mut DurableSubagentSession, String) -> bool + Send + 'static,
++ {
++ let docs = super::store_documents::current(&self.workspace_dir)
++ .map_err(|err| format!("{err:#}"))?;
++ self.import_legacy(&docs)?;
++ docs.update_session_if(subagent_session_id, update)
++ .map_err(|err| format!("{err:#}"))
++ }
}
diff --cc crates/openhuman-core/src/agent/orchestration/subagent_sessions/store_documents.rs
index 301b0d36f5,72cbe0dfee..108aa4e33d
--- a/crates/openhuman-core/src/agent/orchestration/subagent_sessions/store_documents.rs
+++ b/crates/openhuman-core/src/agent/orchestration/subagent_sessions/store_documents.rs
@@@ -198,43 -202,6 +202,61 @@@ impl Docs
.collect()
}
+ /// Atomically mutate one session from its current stored value. Live
+ /// lifecycle changes use this path so millisecond timestamp precision
+ /// cannot discard an equal-millisecond state transition. Whole-list saves
+ /// remain guarded by `write_if_newer` for stale snapshot/import protection.
+ pub(super) fn update_session<F>(
+ &self,
+ subagent_session_id: &str,
+ mut update: F,
+ ) -> Result<Option<DurableSubagentSession>>
+ where
+ F: FnMut(&mut DurableSubagentSession, String) + Send + 'static,
++ {
++ self.update_session_if(subagent_session_id, move |session, now| {
++ update(session, now);
++ true
++ })
++ }
++
++ /// Atomically mutate a session only when `update` accepts its latest
++ /// stored value. A rejected callback performs no write or timestamp bump.
++ pub(super) fn update_session_if<F>(
++ &self,
++ subagent_session_id: &str,
++ mut update: F,
++ ) -> Result<Option<DurableSubagentSession>>
++ where
++ F: FnMut(&mut DurableSubagentSession, String) -> bool + Send + 'static,
+ {
+ let id = key_of(subagent_session_id)?;
+ let updated = self.0.run(|docs| async move {
+ let repo = tinystoragedrivers::Repo::<Value>::new(&docs, SESSIONS)?;
+ repo.update(&id, move |current| {
+ let Some(current) = current else {
+ return Ok(None);
+ };
+ let stored: StoredSession = serde_json::from_value(current)
+ .map_err(|error| crate::storage::StorageError::backend(error.to_string()))?;
+ let mut session = DurableSubagentSession::from(stored);
- update(&mut session, chrono::Utc::now().to_rfc3339());
++ if !update(&mut session, chrono::Utc::now().to_rfc3339()) {
++ return Ok(None);
++ }
+ let next = serde_json::to_value(StoredSession::from(&session))
+ .map_err(|error| crate::storage::StorageError::backend(error.to_string()))?;
+ Ok(Some(next))
+ })
+ .await
+ .map(|updated| updated.map(|(value, _)| value))
+ })?;
+ Ok(updated
+ .map(|value| {
+ serde_json::from_value::<StoredSession>(value).map(DurableSubagentSession::from)
+ })
+ .transpose()?)
+ }
+
/// Whether the one-time legacy file import finished in this scope.
pub(super) fn legacy_imported(&self, source: &std::path::Path) -> Result<bool> {
import_state::is_done(&self.0, OWNER, &import_step(source))
diff --cc crates/openhuman-core/src/agent/orchestration/tools.rs
index a1842782c7,67b81f2222..3fa665b6db
--- a/crates/openhuman-core/src/agent/orchestration/tools.rs
+++ b/crates/openhuman-core/src/agent/orchestration/tools.rs
@@@ -39,16 -32,12 +32,14 @@@ mod dispatch
mod spawn_async_subagent;
#[path = "tools/spawn_parallel_agents.rs"]
mod spawn_parallel_agents;
- #[path = "tools/spawn_subagent.rs"]
+ #[path = "tools/spawn_subagent_surface.rs"]
mod spawn_subagent;
- #[path = "tools/spawn_worker_thread.rs"]
- pub mod spawn_worker_thread;
- #[path = "tools/steer_subagent.rs"]
- mod steer_subagent;
+#[path = "tools/structured_payload.rs"]
+pub(crate) mod structured_payload;
#[path = "tools/subagent_abort_report.rs"]
mod subagent_abort_report;
+ #[path = "tools/subagent_control_surfaces.rs"]
+ mod subagent_control_surfaces;
#[cfg(test)]
#[path = "tools/tools_e2e_tests.rs"]
mod tools_e2e_tests;
diff --cc crates/openhuman-core/src/agent/orchestration/tools/continue_subagent_host.rs
index 99c80474bd,743720165a..41aa551984
--- a/crates/openhuman-core/src/agent/orchestration/tools/continue_subagent_host.rs
+++ b/crates/openhuman-core/src/agent/orchestration/tools/continue_subagent_host.rs
@@@ -594,7 -587,10 +590,7 @@@ impl ContinueSubagentTool
worktree_path: None,
changed_files: Vec::new(),
dirty_status: None,
- stop: incomplete_stop(reason, failure_cause.as_ref()),
- stop: incomplete_stop(
- reason,
- outcome.failure_cause.clone(),
- ),
++ stop: incomplete_stop(reason, failure_cause.clone()),
})
.await;
}
@@@ -616,7 -612,7 +612,7 @@@
&outcome.agent_id,
&outcome.task_id,
reason,
- failure_cause.as_ref(),
- outcome.failure_cause.clone(),
++ failure_cause.clone(),
envelope,
))
}
diff --cc crates/openhuman-core/src/agent/orchestration/tools/dispatch_outcomes.rs
index ca25f7594f,dce7011e39..7cbda01199
--- a/crates/openhuman-core/src/agent/orchestration/tools/dispatch_outcomes.rs
+++ b/crates/openhuman-core/src/agent/orchestration/tools/dispatch_outcomes.rs
@@@ -97,10 -99,13 +99,10 @@@ pub(crate) fn stopped_subagent_result
agent_id: &str,
task_id: &str,
reason: &str,
- failure_cause: Option<&tinyagents_harness::no_progress::ClassifiedStopCause>,
+ failure_cause: Option<tinyagents_harness::no_progress::ClassifiedStopCause>,
envelope: String,
) -> ToolResult {
- let stop = crate::agent::session_host::stop_summary::stop_from_incomplete_with_cause(
- reason,
- failure_cause,
- );
+ let stop = incomplete_stop(reason, failure_cause).expect("incomplete stop is present");
log::debug!(
"[subagent] {tool_name} child stopped early agent_id={agent_id} task_id={task_id} \
{}; returning a failed tool result",
diff --cc crates/openhuman-core/src/agent/orchestration/tools/spawn_subagent_host_impl.rs
index 7788011281,bf16f0b61d..123edf175c
--- a/crates/openhuman-core/src/agent/orchestration/tools/spawn_subagent_host_impl.rs
+++ b/crates/openhuman-core/src/agent/orchestration/tools/spawn_subagent_host_impl.rs
@@@ -479,7 -475,10 +475,10 @@@ impl SpawnSubagentTool
worktree_path: None,
changed_files: Vec::new(),
dirty_status: None,
- stop: incomplete_stop(reason, failure_cause.as_ref()),
+ stop: incomplete_stop(
+ reason,
- outcome.failure_cause.clone(),
++ failure_cause.clone(),
+ ),
})
.await;
}
@@@ -503,7 -502,7 +502,7 @@@
&outcome.agent_id,
&outcome.task_id,
reason,
- failure_cause.as_ref(),
- outcome.failure_cause.clone(),
++ failure_cause.clone(),
envelope,
))
}
diff --cc crates/openhuman-core/src/agent/orchestration/tools/subagent_dispatch_host.rs
index 9993507698,4124c84cbc..9ebd1633ab
--- a/crates/openhuman-core/src/agent/orchestration/tools/subagent_dispatch_host.rs
+++ b/crates/openhuman-core/src/agent/orchestration/tools/subagent_dispatch_host.rs
@@@ -580,7 -558,7 +561,7 @@@ pub(crate) async fn dispatch_subagent_w
worktree_path: None,
changed_files: Vec::new(),
dirty_status: None,
- stop: incomplete_stop(reason, failure_cause.as_ref()),
- stop: incomplete_stop(reason, outcome.failure_cause.clone()),
++ stop: incomplete_stop(reason, failure_cause.clone()),
})
.await;
}
@@@ -598,7 -576,7 +579,7 @@@
&outcome.agent_id,
&outcome.task_id,
reason,
- failure_cause.as_ref(),
- outcome.failure_cause.clone(),
++ failure_cause.clone(),
incomplete_envelope(tool_name, reason, &outcome.output, mode),
))
}
diff --cc crates/openhuman-core/src/agent/prompts/README.md
index 795227ff17,1a0a1c6761..7b0ef8bac3
--- a/crates/openhuman-core/src/agent/prompts/README.md
+++ b/crates/openhuman-core/src/agent/prompts/README.md
@@@ -40,121 -31,20 +31,118 @@@ message boundaries
## Bundled assets
- `IDENTITY.md`, `ROLE.md`, `SOUL.md`, [`STYLE.md`](./STYLE.md) are the bundled copies of the
- master agent's identity, role brief, personality, and writing style. They are
- embedded with `include_str!` in [`render_helpers/workspace_files.rs`](./render_helpers/workspace_files.rs)
- (`default_workspace_file_content`) and, for `STYLE.md`, again in [`builder.rs`](./builder.rs)
- as `GLOBAL_STYLE_SUFFIX`. There are two uses:
-
- - Seed and refresh: `sync_workspace_file(workspace_dir, filename)` writes the
- bundled text to `<workspace_dir>/<filename>` when it is missing and records
- a hash of the bundled content in a `.<filename>.builtin-hash` sidecar. On
- later runs the file is left alone unless the bundled default changed (hash
- mismatch), in which case the disk copy is overwritten, so a user edit
- survives until the next release that touches that asset. Only absolute
- `workspace_dir`s are seeded. `IdentitySection` syncs
- `SOUL.md`/`IDENTITY.md`/`ROLE.md` (`ROLE.md` is injected only when
- `visible_tool_names` is non-empty, i.e. for the orchestrator); `builder.rs`
- syncs `STYLE.md` on every build so agents that set `omit_identity` still get
- the style rules.
- - Compile-time fallback: `GLOBAL_STYLE_SUFFIX` is used when the workspace
- `STYLE.md` cannot be read.
+ `IDENTITY.md`, `ROLE.md`, `SOUL.md`, and [`STYLE.md`](./STYLE.md) are the
+ bundled prompt assets. `sync_workspace_file` seeds a workspace copy, refreshes
+ an unmodified copy when bundled content changes, and preserves user edits.
+ The product prompt
+ composition reads the workspace `STYLE.md`, falling back to the bundled copy
+ when the file cannot be read. [`USER.md`](./USER.md) is exposed as an MCP
+ resource and is not read by this module.
+
+ Built-in archetype prompts generally live in
+ `agent_registry/agents/<name>/prompt.rs`; flow prompts live with their flow
+ agents. `PromptSource::Dynamic` functions provide product content, and the
+ OpenHuman adapter adds the shared AGENTS.md, grounding, and style content.
+[`USER.md`](./USER.md) is different: nothing in this module reads it. It is exposed as the
+`openhuman://prompts/user` MCP resource by [`mcp/server/resources.rs`](../../mcp/server/resources.rs)
+(`include_str!("../../agent/prompts/USER.md")`).
+
+The user's memory is not part of the system prompt: memory v2 injects the
+compiled `context.md` as the first user message of a new session (gated by
+`AgentDefinition::omit_memory_context`), and agents reach anything deeper
+through the `memory` tool.
+
+Editing these files changes the shipped default agent's persona and style
+without a code change.
+
+## Canonical module
+
+`agent::prompts` is the canonical prompt-plumbing module. Prompt logic lives
+here so it sits next to the agents that consume it; do not add a forwarding
+module for this API.
+
+## Extension points (owned elsewhere)
+
+Other domains contribute prompt content without living in this directory:
+
+- [`tools/agent_policy/prompt.rs`](../../tools/agent_policy/prompt.rs): `render_tool_policy_boundary` is not a
+ section. [`agent/session_host/turn/context.rs`](../session_host/turn/context.rs) string-appends its
+ `## Tool Policy Boundary` block after the builder output so the
+ session-scoped bytes land at the tail of the prompt.
+
+Built-in archetype system prompts (orchestrator, planner, image_agent,
+and so on), including the flow builtins, live in
+`agent/registry/agents/<name>/prompt.rs`, not here. Each is a
+`PromptSource::Dynamic` function that hand-assembles its body via the
+`render_*` helpers; [`agent/session_host/builder/factory.rs`](../session_host/builder/factory.rs) wraps it with
+`SystemPromptBuilder::from_dynamic`.
+
+## Builder entry points
+
+- `SystemPromptBuilder::with_defaults()`: the primary-agent chain (identity,
+ `AGENTS.md`, tools, safety, workspace, datetime, runtime).
+- `SystemPromptBuilder::for_subagent(archetype_prompt_text, omit_identity,
+ omit_safety_preamble)`: narrow chain driven by a sub-agent definition's
+ `omit_*` flags. It deliberately excludes `DateTimeSection` so repeat spawns
+ of the same definition stay byte-identical for prefix-cache reuse.
+- `SystemPromptBuilder::from_dynamic(builder)`: wraps a
+ `PromptSource::Dynamic` fn pointer in a `DynamicPromptSection` and still
+ injects the shared `AgentsInstructionsSection`. `from_final_body(body)`
+ wraps an already-rendered string the same way; it currently has only test
+ callers.
+
+Every `build()` appends the grounding contract (unless the body already
+carries the `GROUNDING_HEADING`) and the workspace `STYLE.md` block, so all
+three chains share the same anti-fabrication floor and style rules.
+
+## KV-cache and prefix stability
+
+The rendered prompt is built once per session and reused on every turn
+(`agent/session_host/runtime_session.rs::prepare`) so the inference backend's
+prefix cache hits. `PromptSection::tier()` (`PromptTier::Stable` / `Context` /
+`Volatile`, default `Stable`) controls emission order in
+`SystemPromptBuilder::build_tiered`: every section renders once through
+`PromptSection::build_parts` and its parts are bucketed by tier. Stable bytes
+(identity, rules, tool protocol, datetime rules, the shared grounding contract
+and `STYLE.md`) come first, then per-session context (`AGENTS.md`, workspace,
+model-gated execution discipline), then volatile bytes (the signed-in user,
+installed skills, connected integrations and MCP servers) last.
+
+A `PromptSource::Dynamic` builder declares its own tiers by emitting
+`PROMPT_TIER_CONTEXT_MARKER` / `PROMPT_TIER_VOLATILE_MARKER` on their own lines
+(`split_prompt_tiers`); a builder that emits neither stays wholly `Volatile`.
+The orchestrator does this so its identity and rules lead the stable tier
+instead of trailing the volatile sections.
+
+`TieredPrompt::system_messages()` hands the session one system message for
+`Stable + Context` and a second for `Volatile`. The tinyagents harness gives
+each leading system message its own cacheable segment
+(`PromptBuilder::push_system_messages`), so a newly
+connected service changes the second segment and leaves the first
+byte-identical (`system`, `system.1`). A prefix is reusable only up to the first differing
+byte, so a volatile section rendered early invalidates every stable byte
+behind it. One consequence is visible in this module: `DateTimeSection`
+renders only the clock *rules* and is `Stable` (the live timestamp rides the
+user message via `current_datetime_line`).
+
+## Used by
+
+- `agent/session_host/turn/context.rs`: loads `AGENTS.md` layers and
+ connected identities into `PromptContext`, calls the builder, and appends
+ the tool-policy boundary.
+- `agent/session_host/builder/factory.rs`: picks the entry point per
+ `PromptSource`.
+- [`agent/debug/`](../debug/): `dump_agent_prompt` / `dump_all_agent_prompts` ([`mod.rs`](./mod.rs))
+ build the same `PromptContext` to render each agent's prompt,
+ `dump_writer.rs` writes it to disk, `prompt_size.rs` measures it.
+
+## Further reading
+
+- [Parent module README](../README.md)
+- [Agent harness architecture](../../../../../docs/gitbooks/en/developing/architecture/agent-harness.md)
+- [Personalization and self-learning](../../../../../docs/gitbooks/en/features/personalization.md)
+ The session host builds a prompt once for a session. Stable and Context
+ content forms the first system message, and Volatile content forms the second.
+ Resumed sessions reuse persisted system messages verbatim, preserving their
+ provider cache prefix.
diff --cc crates/openhuman-core/src/agent/prompts/mod.rs
index 72c6077973,1930b5d0cf..30a204c051
--- a/crates/openhuman-core/src/agent/prompts/mod.rs
+++ b/crates/openhuman-core/src/agent/prompts/mod.rs
@@@ -4,28 -2,15 +2,18 @@@
pub mod types;
pub use types::*;
- mod connected_identities;
+#[cfg(feature = "flows")]
+pub(crate) mod flow_archetype;
- pub use connected_identities::render_connected_identities;
++pub use crate::integrations::render_connected_identities;
pub mod agents_md;
- pub use agents_md::{load_agents_md, load_agents_md_layers, AgentsMdContent, AGENTS_MD_FILENAME};
+ pub use agents_md::{load_agents_md, load_agents_md_layers};
- pub mod builder;
- pub use builder::{SystemPromptBuilder, TieredPrompt, GLOBAL_STYLE_SUFFIX};
+ pub use crate::prompts::composition::{SystemPromptBuilder, TieredPrompt, GLOBAL_STYLE_SUFFIX};
- pub mod sections;
- pub use sections::*;
-
- pub mod render_helpers;
- pub use render_helpers::{
- current_datetime_line, default_workspace_file_content, inject_inline_content,
- inject_workspace_file, inject_workspace_file_capped, render_ambient_environment,
- render_datetime, render_identity, render_runtime, render_safety, render_subagent_system_prompt,
- render_subagent_system_prompt_with_format, render_tools, render_user_identity,
- render_workspace, sync_workspace_file, turn_preamble,
- };
+ #[path = "render_helpers/subagent.rs"]
+ mod subagent;
+ pub use subagent::{render_subagent_system_prompt, render_subagent_system_prompt_with_format};
#[cfg(test)]
#[path = "mod_tests.rs"]
diff --cc crates/openhuman-core/src/agent/session_host/runtime_session.rs
index ddb9257b3f,610d719b72..ede5bf4bb1
--- a/crates/openhuman-core/src/agent/session_host/runtime_session.rs
+++ b/crates/openhuman-core/src/agent/session_host/runtime_session.rs
@@@ -1,17 -1,19 +1,21 @@@
//! The live OpenHuman composition over `tinyagents_runtime::Session`.
//!
- //! The mutex is intentionally narrow: it carries host preparation and
- //! finalization observations only. Generic model history, transcript rows,
- //! prefix reconciliation, tool snapshots, resume and persistence remain inside
- //! the runtime session.
+ //! Host hooks carry product state; `tinyagents_runtime` owns history,
+ //! transcripts, prefixes, snapshots, resume, and persistence.
- #[path = "runtime_session_attachment_input.rs"]
- mod attachment_input;
- mod memory_ingest;
mod permanent;
mod post_commit;
+ #[path = "runtime_session/prelude.rs"]
+ mod prelude;
+#[path = "runtime_session/prompt.rs"]
+mod prompt;
+ #[path = "runtime_session/prompt_surface.rs"]
+ mod prompt_surface;
+ #[path = "runtime_session_usage.rs"]
+ mod usage;
+ pub(super) use usage::{account_committed_turn_against_goal, holistic_last_turn_usage};
+ #[path = "../../memory/lifecycle/session_hooks.rs"]
+ mod session_hooks;
mod tool_rules;
mod transcript;
#[path = "runtime_session_turn.rs"]
diff --cc crates/openhuman-core/src/agent/session_host/runtime_session/prelude.rs
index 0000000000,bed289433c..1bf3127378
mode 000000,100644..100644
--- a/crates/openhuman-core/src/agent/session_host/runtime_session/prelude.rs
+++ b/crates/openhuman-core/src/agent/session_host/runtime_session/prelude.rs
@@@ -1,0 -1,348 +1,358 @@@
+ //! Host-specific model/tool/prompt preparation for one runtime turn.
+
+ use super::*;
+
+ impl OpenHumanTurnPrelude {
+ #[allow(clippy::type_complexity)]
+ pub(super) fn current_tool_source(
+ &self,
+ ) -> (
+ Arc<Vec<Box<dyn tinytools::Tool>>>,
+ Arc<Vec<Box<dyn tinytools::Tool>>>,
+ tinytools::ToolPolicySession,
+ String,
+ ) {
+ let surface = self
+ .tool_surface
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
+ (
+ surface.tools.clone(),
+ surface.synthesized_tools.clone(),
+ surface.tool_policy_session.clone(),
+ surface.event_channel.clone(),
+ )
+ }
+
+ /// The session's deferred set for this turn; see
+ /// `OpenHumanRunContext::deferred_tool_names`.
+ pub(super) fn current_deferred_tool_names(&self) -> std::collections::HashSet<String> {
+ self.tool_surface
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .deferred_tool_names
+ .clone()
+ }
+
+ pub(super) fn replace_tool_surface(&self, surface: OpenHumanTurnToolSurface) {
+ *self
+ .tool_surface
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner) = surface;
+ }
+
+ pub(super) async fn prepare(&self, cold: bool) -> Result<TurnPreparation> {
+ let tools = {
+ let surface = self
+ .tool_surface
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
+ // The snapshot is the declaration set the session grants — the
+ // driver reads it back as the harness allowlist — so it carries
+ // the deferred tools beside the advertised ones. The harness
+ // still advertises only the `Direct` registrations and reaches
+ // the rest through its `tool_search` bridge.
+ ToolSnapshot::new(
+ surface
+ .visible_tool_specs
+ .iter()
+ .chain(
+ surface
+ .tool_specs
+ .iter()
+ .filter(|spec| surface.deferred_tool_names.contains(&spec.name)),
+ )
+ .filter(|spec| {
+ self.thread_id.is_some()
+ || !crate::agent::tinyagents::tool_registration::is_thread_goal_tool(
+ &spec.name,
+ )
+ })
+ .map(|spec| spec.as_ref().clone())
+ .collect(),
+ )
+ .map_err(|error| anyhow::anyhow!(error.to_string()))?
+ };
++ let flow_archetype_text = super::prompt::flow_archetype_text(self, cold).await?;
+ let prefix = if cold {
- let tiered = self.build_system_prompt_tiered()?;
++ let tiered = self
++ .build_system_prompt_tiered_with_flow_archetype(flow_archetype_text.as_deref())?;
+ Some(tinyagents_runtime::PrefixSnapshot::new(
+ tiered
+ .system_messages()
+ .into_iter()
+ .map(Message::system)
+ .collect(),
+ ))
+ } else {
+ None
+ };
+ Ok(TurnPreparation {
+ prefix,
+ tools: Some(tools),
+ })
+ }
+
+ pub(super) fn build_system_prompt_tiered(&self) -> Result<crate::agent::prompts::TieredPrompt> {
++ self.build_system_prompt_tiered_with_flow_archetype(None)
++ }
++
++ pub(super) fn build_system_prompt_tiered_with_flow_archetype(
++ &self,
++ flow_archetype_text: Option<&str>,
++ ) -> Result<crate::agent::prompts::TieredPrompt> {
+ use crate::agent::prompts::{PromptContext, PromptTool};
+ let surface = self
+ .tool_surface
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
+ let withheld = self.rule_withheld_tools(&surface);
+ let specs = surface
+ .visible_tool_specs
+ .iter()
+ .filter(|spec| !withheld.contains(&spec.name))
+ .filter(|spec| {
+ self.thread_id.is_some()
+ || !crate::agent::tinyagents::tool_registration::is_thread_goal_tool(&spec.name)
+ })
+ .map(|spec| spec.as_ref().clone())
+ .collect::<Vec<_>>();
+ let instructions = self.tool_dispatcher.prompt_instructions(&specs);
+ let tool_refs = surface
+ .tools
+ .iter()
+ .chain(surface.synthesized_tools.iter())
+ .filter(|tool| {
+ self.thread_id.is_some()
+ || !crate::agent::tinyagents::tool_registration::is_thread_goal_tool(
+ tool.name(),
+ )
+ })
+ .map(|tool| tool.as_ref())
+ .collect::<Vec<_>>();
+ let mut prompt_tools = PromptTool::from_tool_refs(tool_refs.iter().copied());
+ prompt_tools.retain(|tool| !surface.permanent_tool_names.contains(tool.name.as_ref()));
+ prompt_tools.retain(|tool| !withheld.contains(tool.name.as_ref()));
+ let mut visible_tool_names = surface.tool_policy_session.visible_tool_names_for_prompt();
+ visible_tool_names.retain(|name| !withheld.contains(name));
+ visible_tool_names.retain(|name| !surface.permanent_tool_names.contains(name));
+ if self.thread_id.is_none() {
+ visible_tool_names.retain(|name| {
+ !crate::agent::tinyagents::tool_registration::is_thread_goal_tool(name)
+ });
+ }
+ crate::agent::prompts::swap_deferred_for_discovery_bridge(
+ &mut prompt_tools,
+ &mut visible_tool_names,
+ &surface.deferred_tool_names,
+ );
+ let agents_md = if self.config.agents_md_enabled {
+ crate::agent::prompts::load_agents_md_layers(&self.workspace_dir, &self.action_dir)
+ } else {
+ Default::default()
+ };
+ let mutable = self
+ .mutable
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
+ let context = PromptContext {
+ workspace_dir: &self.workspace_dir,
+ model_name: &self.model_name,
+ agent_id: &self.agent_definition_name,
++ flow_archetype_text,
+ tools: &prompt_tools,
+ workflows: &mutable.workflows,
+ dispatcher_instructions: &instructions,
+ visible_tool_names: &visible_tool_names,
+ tool_call_format: self.tool_dispatcher.tool_call_format(),
+ connected_integrations: &mutable.connected_integrations,
+ connected_identities_md: self.connected_identities_md(),
+ user_identity: crate::security::credentials::identity::peek_credential_user_identity(),
+ personality_roster: vec![],
+ agents_md_global: agents_md.global,
+ agents_md_local: agents_md.local,
+ };
+ self.prompt_builder.build_tiered(&context)
+ }
+
+ pub(super) fn drain_host_events(&self) -> bool {
+ let mut mutable = self
+ .mutable
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
+ if mutable.composio_events.is_none() {
+ mutable.composio_events = crate::core::bus::BUS.get().map(|bus| bus.receiver());
+ }
+ if mutable.skill_events.is_none() {
+ mutable.skill_events = crate::core::bus::BUS.get().map(|bus| bus.receiver());
+ }
+ let drain = |receiver: &mut Option<
+ tinybus::events::EventReceiver<crate::core::events::DomainEvent>,
+ >| {
+ let Some(receiver) = receiver.as_mut() else {
+ return false;
+ };
+ let mut skills_changed = false;
+ loop {
+ use tinybus::TryRecvError;
+ match receiver.try_recv() {
+ Ok(crate::core::events::DomainEvent::WorkflowsChanged { .. }) => {
+ skills_changed = true
+ }
+ Ok(crate::core::events::DomainEvent::ComposioIntegrationsChanged {
+ ..
+ })
+ | Ok(_) => {}
+ Err(TryRecvError::Empty) => break,
+ Err(TryRecvError::Lagged(_)) => {
+ skills_changed = true;
+ break;
+ }
+ Err(TryRecvError::Closed) => break,
+ }
+ }
+ skills_changed
+ };
+ let composio_skills_changed = drain(&mut mutable.composio_events);
+ composio_skills_changed | drain(&mut mutable.skill_events)
+ }
+
+ /// Assemble every dynamic, host-owned user-turn addition after the runtime
+ /// has selected/resumed its transcript. The returned message is then the
+ /// sole input which `Session` appends to generic history.
+ pub(super) async fn enrich_request(
+ &self,
+ original_user_message: &str,
+ turn: &super::super::types::TurnInputs,
+ run_context: &mut OpenHumanRunContext,
+ ) -> String {
+ let mut context = String::new();
+
+ let active_goal = if turn.overrides.suppress_active_goal {
+ None
+ } else {
+ let loaded = crate::agent::goals::runtime::load_for_thread(
+ &self.workspace_dir,
+ self.thread_id.as_deref(),
+ )
+ .await;
+ match loaded {
+ Some(goal) if matches!(goal.status, ThreadGoalStatus::Paused) => {
+ crate::agent::goals::runtime::resume_for_thread(
+ &self.workspace_dir,
+ self.thread_id.as_deref(),
+ )
+ .await
+ .unwrap_or(Some(goal))
+ }
+ other => other,
+ }
+ };
+ if let Some(goal) = &active_goal {
+ if let Some(block) = tinyagents_graph::goals::active_goal_context_block(goal) {
+ context.push_str(&block);
+ }
+ if let Some(hook) = tinyagents_hooks::stop::GoalBudgetStopHook::for_goal(
+ crate::storage::sessions::stores_or_ephemeral(&self.workspace_dir).kv,
+ goal,
+ ) {
+ run_context.stop_hooks.push(Arc::new(hook));
+ }
+ }
+ // Build the roster from this turn's *effective* visible tool set
+ // (snapshotted under the tool-surface lock, then released), not the
+ // definition's static scope: a hide or named restriction can narrow what
+ // this turn can call, and the roster must not advertise a control it cannot invoke.
+ let turn_fleet = {
+ let visible = self
+ .tool_surface
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .visible_tool_names
+ .clone();
+ if visible.is_empty() {
+ crate::agent::orchestration::fleet_tools::FleetToolSet::for_parent(
+ &self.agent_definition_id,
+ )
+ } else {
+ crate::agent::orchestration::fleet_tools::FleetToolSet::from_visible_tool_names(
+ &visible,
+ )
+ }
+ };
+ if let Some(block) =
+ crate::agent::orchestration::running_subagents::active_subagents_context_block(
+ &self.dispatch_ctx(),
+ &self.event_session_id,
+ &self.workspace_dir,
+ &turn_fleet,
+ )
+ {
+ context.push_str(&block);
+ }
+
+ let mut enriched = if context.is_empty() {
+ original_user_message.to_string()
+ } else {
+ format!("{context}{original_user_message}")
+ };
+ {
+ let mut mutable = self
+ .mutable
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
+ mutable.last_memory_context = (!context.is_empty()).then_some(context);
+ }
+ run_context.response_shape = turn.response_shape.clone();
+ run_context.attach_parent(self.parent_context(run_context.parent.as_ref()));
+ self.apply_pending_announcements(&mut enriched);
+ run_context.attachment_placeholders =
+ Arc::new(extract_image_placeholders_in_text(original_user_message));
+ run_context.dispatch = Some(Arc::new(
+ crate::agent::tinyagents::host::TurnDispatchState::new(
+ crate::agent::tinyagents::agent_turn_wall_clock_ms_for(
+ self.runtime_config
+ .as_deref()
+ .is_some_and(crate::agent::tinyagents::chat_provider_is_local),
+ )
+ .map(std::time::Duration::from_millis),
+ ),
+ ));
+ run_context.sandbox_mode = Some(self.sandbox_mode);
+ // Same pin as `SessionDriver::run_turn`: the harness speaks the dialect
+ // the prompt was composed for, so a text dialect keeps its schemas off
+ // the wire and renders the catalogue itself (`ToolsSection` no longer
+ // does), and a code call is recovered against the positional registry.
+ run_context.tool_dialect = tinyagents_harness::dialect::dispatcher_for_format(
+ self.tool_dispatcher.tool_call_format(),
+ );
+ format!("{}\n\n{enriched}", turn.preamble())
+ }
+
+ fn apply_pending_announcements(&self, enriched: &mut String) {
+ let mut mutable = self
+ .mutable
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
+ for note in [
+ integration_announcement_note(&std::mem::take(
+ &mut mutable.pending_integration_announcement,
+ )),
+ mcp_announcement_note(&std::mem::take(&mut mutable.pending_mcp_announcement)),
+ skill_announcement_note(&std::mem::take(&mut mutable.pending_skill_announcement)),
+ skill_retraction_note(&std::mem::take(&mut mutable.pending_skill_retraction)),
+ ]
+ .into_iter()
+ .flatten()
+ {
+ *enriched = format!("{note}\n\n{enriched}");
+ }
+ }
+
+ pub(super) async fn finalize_after_durable_commit(
+ &self,
+ receipt: &CommitReceipt<OpenHumanRunContext>,
+ ) {
+ self.memory_post_turn(receipt);
+ }
+ }
diff --cc crates/openhuman-core/src/agent/session_host/runtime_session/prompt.rs
index 9ce2474c37,0000000000..ce8fad298b
mode 100644,000000..100644
--- a/crates/openhuman-core/src/agent/session_host/runtime_session/prompt.rs
+++ b/crates/openhuman-core/src/agent/session_host/runtime_session/prompt.rs
@@@ -1,92 -1,0 +1,33 @@@
- //! Cold prompt rendering for the host-owned session prelude.
++//! Loads the module-owned prompt fragment for a cold TinyFlows session turn.
+
- use crate::agent::prompts::{PromptContext, PromptTool, TieredPrompt};
+use anyhow::Result;
+
+use super::OpenHumanTurnPrelude;
+
- impl OpenHumanTurnPrelude {
- pub(super) fn build_system_prompt_tiered(&self) -> Result<TieredPrompt> {
- self.build_system_prompt_tiered_with_flow_archetype(None)
++pub(super) async fn flow_archetype_text(
++ prelude: &OpenHumanTurnPrelude,
++ cold: bool,
++) -> Result<Option<String>> {
++ if !cold {
++ return Ok(None);
+ }
+
- pub(super) fn build_system_prompt_tiered_with_flow_archetype(
- &self,
- flow_archetype_text: Option<&str>,
- ) -> Result<TieredPrompt> {
- let surface = self
- .tool_surface
- .lock()
- .unwrap_or_else(std::sync::PoisonError::into_inner);
- let withheld = self.rule_withheld_tools(&surface);
- let specs = surface
- .visible_tool_specs
- .iter()
- .filter(|spec| !withheld.contains(&spec.name))
- .filter(|spec| {
- self.thread_id.is_some()
- || !crate::agent::tinyagents::tool_registration::is_thread_goal_tool(&spec.name)
- })
- .map(|spec| spec.as_ref().clone())
- .collect::<Vec<_>>();
- let instructions = self.tool_dispatcher.prompt_instructions(&specs);
- let tool_refs = surface
- .tools
- .iter()
- .chain(surface.synthesized_tools.iter())
- .filter(|tool| {
- self.thread_id.is_some()
- || !crate::agent::tinyagents::tool_registration::is_thread_goal_tool(
- tool.name(),
- )
- })
- .map(|tool| tool.as_ref())
- .collect::<Vec<_>>();
- let mut prompt_tools = PromptTool::from_tool_refs(tool_refs.iter().copied());
- prompt_tools.retain(|tool| !surface.permanent_tool_names.contains(tool.name.as_ref()));
- prompt_tools.retain(|tool| !withheld.contains(tool.name.as_ref()));
- let mut visible_tool_names = surface.tool_policy_session.visible_tool_names_for_prompt();
- visible_tool_names.retain(|name| !withheld.contains(name));
- visible_tool_names.retain(|name| !surface.permanent_tool_names.contains(name));
- if self.thread_id.is_none() {
- visible_tool_names.retain(|name| {
- !crate::agent::tinyagents::tool_registration::is_thread_goal_tool(name)
- });
++ #[cfg(feature = "flows")]
++ {
++ match prelude.definition.as_deref() {
++ Some(definition) => {
++ crate::agent::prompts::flow_archetype::load_for_definition(
++ prelude.runtime_config.as_deref(),
++ definition,
++ )
++ .await
++ }
++ None => Ok(None),
+ }
- crate::agent::prompts::swap_deferred_for_discovery_bridge(
- &mut prompt_tools,
- &mut visible_tool_names,
- &surface.deferred_tool_names,
- );
- let agents_md = if self.config.agents_md_enabled {
- crate::agent::prompts::load_agents_md_layers(&self.workspace_dir, &self.action_dir)
- } else {
- Default::default()
- };
- let mutable = self
- .mutable
- .lock()
- .unwrap_or_else(std::sync::PoisonError::into_inner);
- let context = PromptContext {
- workspace_dir: &self.workspace_dir,
- model_name: &self.model_name,
- agent_id: &self.agent_definition_name,
- flow_archetype_text,
- tools: &prompt_tools,
- workflows: &mutable.workflows,
- dispatcher_instructions: &instructions,
- visible_tool_names: &visible_tool_names,
- tool_call_format: self.tool_dispatcher.tool_call_format(),
- connected_integrations: &mutable.connected_integrations,
- connected_identities_md: self.connected_identities_md(),
- user_identity: crate::security::credentials::identity::peek_credential_user_identity(),
- personality_roster: vec![],
- agents_md_global: agents_md.global,
- agents_md_local: agents_md.local,
- };
- self.context
- .lock()
- .unwrap_or_else(std::sync::PoisonError::into_inner)
- .build_system_prompt_tiered(&context)
++ }
++ #[cfg(not(feature = "flows"))]
++ {
++ let _ = prelude;
++ Ok(None)
+ }
+}
diff --cc crates/openhuman-core/src/agent/session_host/runtime_session_tests.rs
index ed09a97b4e,f30ce5039e..d3e7ba8e47
--- a/crates/openhuman-core/src/agent/session_host/runtime_session_tests.rs
+++ b/crates/openhuman-core/src/agent/session_host/runtime_session_tests.rs
@@@ -5,9 -5,19 +5,22 @@@ use std::sync::Arc
use tinyagents_runtime::ToolSnapshot;
use tinytools::ToolSpec;
+#[cfg(feature = "flows")]
+#[path = "runtime_session_flow_prompt_tests.rs"]
+mod flow_prompt_tests;
+ #[path = "runtime_session_terminal_tests.rs"]
+ mod terminal_tests;
+
+ fn synthesized_tool_names(
+ prelude: &super::OpenHumanTurnPrelude,
+ ) -> std::collections::HashSet<String> {
+ prelude
+ .tool_surface
+ .lock()
+ .expect("tool surface")
+ .synthesized_tool_names
+ .clone()
+ }
#[tokio::test]
async fn committed_progress_uses_each_turns_receipt_sender() {
diff --cc crates/openhuman-core/src/agent/subagent_host/lifecycle.rs
index 461053aaf2,07dec4e70e..1770cdd3c1
--- a/crates/openhuman-core/src/agent/subagent_host/lifecycle.rs
+++ b/crates/openhuman-core/src/agent/subagent_host/lifecycle.rs
@@@ -922,99 -737,7 +737,9 @@@ mod persistence
#[path = "lifecycle_store.rs"]
mod store;
+#[path = "lifecycle_outcome.rs"]
+mod outcome;
- use outcome::{host_outcome_to_neutral, HostInFlightMap};
-
- fn outcome_to_host(
- result: SubagentRunResult,
- host: Option<SubagentRunOutcome>,
- persistence: &OpenHumanPersistence,
- task_key: &SubagentTaskKey,
- fallback_agent_id: &str,
- ) -> SubagentRunOutcome {
- let persistence_disposition = result.disposition;
- let outcome = result.outcome;
- // A driver that lost a pause/terminal CAS may have a perfectly valid local
- // execution result, but it is not the authoritative lifecycle outcome.
- // Reconstruct the durable winner instead of leaking the loser’s output,
- // usage, or artifacts to an observer.
- let host = if persistence_disposition.should_emit_host_effects() {
- host
- } else {
- None
- };
- let durable_metadata = if host.is_none() {
- persistence.durable_host_metadata(task_key).ok().flatten()
- } else {
- None
- };
- let mut host = host.unwrap_or_else(|| SubagentRunOutcome {
- task_id: outcome.task_id.clone(),
- agent_id: durable_metadata
- .as_ref()
- .map(|(agent_id, _)| agent_id.clone())
- .unwrap_or_else(|| fallback_agent_id.to_owned()),
- output: outcome.output.clone(),
- iterations: outcome.usage.calls as usize,
- elapsed: std::time::Duration::from_millis(
- durable_metadata
- .map(|(_, elapsed_ms)| elapsed_ms)
- .unwrap_or_default(),
- ),
- mode: super::SubagentMode::Typed,
- status: SubagentRunStatus::Completed,
- final_history: outcome
- .history
- .iter()
- .filter_map(tinyagents_runtime::transcript::message_to_native_transcript)
- .collect(),
- usage: SubagentUsage {
- input_tokens: outcome.usage.usage.input_tokens,
- output_tokens: outcome.usage.usage.output_tokens,
- cached_input_tokens: outcome.usage.usage.cache_read_tokens,
- charged_amount_usd: outcome
- .usage
- .usage
- .charged_amount
- .map(|amount| amount.micros as f64 / 1_000_000.0)
- .unwrap_or_default(),
- cost_source: cost_source_of(outcome.usage.usage.charged_amount.as_ref()),
- },
- artifact_paths: outcome
- .artifacts
- .iter()
- .map(|artifact| artifact.id.clone())
- .collect(),
- persistence_disposition,
- });
- let is_awaiting_input = matches!(outcome.status, SubagentOutcomeKind::AwaitingInput(_));
- let status = match outcome.status {
- SubagentOutcomeKind::Completed => SubagentRunStatus::Completed,
- SubagentOutcomeKind::AwaitingInput(pause) => SubagentRunStatus::AwaitingUser {
- question: pause.reason,
- options: None,
- checkpoint: None,
- },
- SubagentOutcomeKind::Incomplete(incomplete) => {
- outcome::incomplete_run_status(incomplete.reason, &outcome.extensions)
- }
- SubagentOutcomeKind::Cancelled => SubagentRunStatus::Cancelled,
- };
- host.status = status;
- host.persistence_disposition = persistence_disposition;
- if is_awaiting_input {
- host.status = SubagentRunStatus::AwaitingUser {
- question: match host.status {
- SubagentRunStatus::AwaitingUser { ref question, .. } => question.clone(),
- _ => String::new(),
- },
- options: None,
- checkpoint: Some(persistence.pause_path(task_key)),
- };
- }
- host
- }
+ pub(super) use driver_adapter::{HostRequest, OpenHumanDriverBundle};
fn map_lifecycle_error(error: SubagentError) -> SubagentRunError {
SubagentRunError::Provider(anyhow::anyhow!(error.to_string()))
diff --cc crates/openhuman-core/src/agent/subagent_host/lifecycle_outcome.rs
index 5d52d1e55f,0d14e45659..05c52579c0
--- a/crates/openhuman-core/src/agent/subagent_host/lifecycle_outcome.rs
+++ b/crates/openhuman-core/src/agent/subagent_host/lifecycle_outcome.rs
@@@ -2,57 -2,50 +2,92 @@@
use super::*;
- /// The host's in-flight subagent runs of one agent context.
- pub(super) type HostInFlightMap = AsyncMutex<HashMap<HostLifecycleKey, Arc<HostInFlight>>>;
-
+pub(super) const CLASSIFIED_STOP_CAUSE_EXTENSION: &str = "openhuman.classified_stop_cause";
+
+pub(super) fn encode_classified_stop_cause(
+ cause: &tinyagents_harness::no_progress::ClassifiedStopCause,
+) -> serde_json::Value {
- let stop = crate::agent::turn_projection::breaker_stop_with_cause(cause.clone());
+ serde_json::json!({
- "class": stop.failure_class.as_deref(),
- "operation": stop.operation,
++ "class": cause.class,
++ "operation": cause.operation,
+ })
+}
+
+pub(super) fn decode_classified_stop_cause(
+ value: &serde_json::Value,
+ summary: &str,
+) -> Option<tinyagents_harness::no_progress::ClassifiedStopCause> {
+ Some(tinyagents_harness::no_progress::ClassifiedStopCause {
+ class: value.get("class")?.as_str()?.to_string(),
+ operation: value.get("operation")?.as_str()?.to_string(),
+ summary: summary.to_string(),
+ })
+}
+
+pub(super) fn incomplete_run_status(
+ reason: String,
+ extensions: &std::collections::BTreeMap<String, serde_json::Value>,
+) -> SubagentRunStatus {
+ let failure_cause = extensions
+ .get(CLASSIFIED_STOP_CAUSE_EXTENSION)
++ .or_else(|| extensions.get("failure_cause"))
+ .and_then(|value| decode_classified_stop_cause(value, &reason));
+ SubagentRunStatus::Incomplete {
+ reason,
+ failure_cause,
+ }
+}
+
pub(super) fn host_outcome_to_neutral(
outcome: SubagentRunOutcome,
- definition: &crate::agent::harness::host_definition::AgentDefinition,
+ definition: &crate::agent_registry::host_definition::AgentDefinition,
options: &SubagentRunOptions,
) -> SubagentOutcome {
- let failure_cause = match &outcome.status {
- SubagentRunStatus::Incomplete { failure_cause, .. } => failure_cause.clone(),
- _ => None,
- };
++ let failure_cause = outcome
++ .failure_cause
++ .clone()
++ .or_else(|| match &outcome.status {
++ SubagentRunStatus::Incomplete { failure_cause, .. } => failure_cause.clone(),
++ _ => None,
++ });
+ let usage_cost = outcome.usage.cost();
+ let mut extensions = std::collections::BTreeMap::from_iter([
+ ("agent_id".into(), serde_json::json!(definition.id)),
+ ("iterations".into(), serde_json::json!(outcome.iterations)),
+ (
+ "skill_filter_override".into(),
+ serde_json::json!(options.skill_filter_override),
+ ),
+ (
+ "elapsed_ms".into(),
+ serde_json::json!(outcome.elapsed.as_millis() as u64),
+ ),
+ (
+ "elapsed_ns".into(),
+ serde_json::json!(outcome.elapsed.as_nanos().min(u64::MAX as u128) as u64),
+ ),
+ (
+ "artifact_paths".into(),
+ serde_json::json!(outcome.artifact_paths),
+ ),
+ ]);
- if let Some(cause) = &outcome.failure_cause {
++ if let Some(cause) = &failure_cause {
+ extensions.insert(
+ "failure_cause".into(),
+ serde_json::json!({
+ "class": cause.class,
+ "operation": cause.operation,
- "summary": cause.summary,
+ }),
+ );
+ }
let status = match outcome.status {
SubagentRunStatus::Completed => SubagentOutcomeKind::Completed,
- SubagentRunStatus::AwaitingUser { question, .. } => {
+ SubagentRunStatus::AwaitingUser {
+ question,
+ options: answer_options,
+ ..
+ } => {
+ extensions.insert("options".into(), serde_json::json!(answer_options));
SubagentOutcomeKind::AwaitingInput(SubagentPause {
reason: question,
resume: SubagentResume {
@@@ -85,8 -78,14 +120,14 @@@
}
SubagentRunStatus::Cancelled => SubagentOutcomeKind::Cancelled,
};
- SubagentOutcome {
+ let mut neutral = SubagentOutcome {
task_id: outcome.task_id,
+ worker_thread_id: options.worker_thread_id.clone(),
+ tier: Some(definition.agent_tier.as_str().to_owned()),
+ model_override: options.model_override.clone(),
+ cost_usd: usage_cost.usd(),
+ cost_source: Some(usage_cost.source),
+ extensions: std::mem::take(&mut extensions),
output: outcome.output,
history: outcome
.final_history
diff --cc crates/openhuman-core/src/agent/subagent_host/lifecycle_outcome_tests.rs
index e04652cef5,499cfca33f..7b58337218
--- a/crates/openhuman-core/src/agent/subagent_host/lifecycle_outcome_tests.rs
+++ b/crates/openhuman-core/src/agent/subagent_host/lifecycle_outcome_tests.rs
@@@ -1,112 -1,138 +1,221 @@@
use super::*;
+ #[test]
+ fn paused_outcomes_preserve_answer_choices_and_worker_resume_options() {
+ let definitions =
+ crate::agent_registry::host_definition::AgentDefinitionRegistry::builtins_only();
+ let definition = definitions.get("orchestrator").unwrap();
+ let options = SubagentRunOptions {
+ worker_thread_id: Some("worker-thread".into()),
+ skill_filter_override: Some("docs".into()),
+ model_override: Some("worker-model".into()),
+ ..SubagentRunOptions::default()
+ };
+ let outcome = SubagentRunOutcome {
+ task_id: "paused-task".into(),
+ agent_id: definition.id.clone(),
+ output: "partial work".into(),
+ iterations: 2,
+ failure_cause: None,
+ elapsed: std::time::Duration::from_millis(25),
+ mode: crate::agent::subagent_host::SubagentMode::Typed,
+ status: SubagentRunStatus::AwaitingUser {
+ question: "Which version?".into(),
+ options: Some(vec!["stable".into(), "preview".into()]),
+ checkpoint: None,
+ },
+ final_history: Vec::new(),
+ usage: SubagentUsage::default(),
+ artifact_paths: vec!["report.md".into()],
+ persistence_disposition:
+ tinyagents_orchestration::subagent::SubagentPersistenceDisposition::PauseCommitted,
+ };
+
+ let neutral = host_outcome_to_neutral(outcome, definition, &options);
+ assert_eq!(neutral.worker_thread_id.as_deref(), Some("worker-thread"));
+ assert_eq!(neutral.model_override.as_deref(), Some("worker-model"));
+ assert_eq!(
+ neutral.extensions["options"],
+ serde_json::json!(["stable", "preview"])
+ );
+ assert_eq!(
+ neutral.extensions["artifact_paths"],
+ serde_json::json!(["report.md"])
+ );
+ assert_eq!(neutral.extensions["elapsed_ms"], 25);
+ let SubagentOutcomeKind::AwaitingInput(pause) = neutral.status else {
+ panic!("a paused host outcome must remain resumable");
+ };
+ assert_eq!(pause.reason, "Which version?");
+ assert_eq!(pause.resume.metadata["worker_thread_id"], "worker-thread");
+ assert_eq!(pause.resume.metadata["skill_filter_override"], "docs");
+ assert_eq!(pause.resume.metadata["model_override"], "worker-model");
+ }
+
+ #[test]
+ fn host_outcome_terminal_record_round_trips_through_json_bytes() {
+ let definitions =
+ crate::agent_registry::host_definition::AgentDefinitionRegistry::builtins_only();
+ let definition = definitions.get("orchestrator").unwrap();
+ let options = SubagentRunOptions {
+ worker_thread_id: Some("worker-thread".into()),
+ model_override: Some("worker-model".into()),
+ ..SubagentRunOptions::default()
+ };
+ let outcome = SubagentRunOutcome {
+ task_id: "task-123".into(),
+ agent_id: definition.id.clone(),
+ output: "durable".into(),
+ iterations: 2,
+ failure_cause: None,
+ elapsed: std::time::Duration::from_millis(25),
+ mode: crate::agent::subagent_host::SubagentMode::Typed,
+ status: SubagentRunStatus::Completed,
+ final_history: Vec::new(),
+ usage: SubagentUsage::default(),
+ artifact_paths: vec![],
+ persistence_disposition:
+ tinyagents_orchestration::subagent::SubagentPersistenceDisposition::TerminalInserted,
+ };
+
+ let neutral = host_outcome_to_neutral(outcome, definition, &options);
+ assert_eq!(neutral.extensions["agent_id"], definition.id);
+ assert_eq!(neutral.extensions["iterations"], 2);
+ assert!(!neutral.extensions.contains_key("task_id"));
+ assert!(!neutral.extensions.contains_key("tier"));
+ assert!(!neutral.extensions.contains_key("worker_thread_id"));
+ assert!(!neutral.extensions.contains_key("model_override"));
+ let encoded = serde_json::to_vec(&neutral).unwrap();
+ let decoded: tinyagents_orchestration::subagent::SubagentOutcome =
+ serde_json::from_slice(&encoded)
+ .expect("terminal outcomes written as bytes must deserialize");
+ assert_eq!(decoded.task_id, "task-123");
+ assert_eq!(decoded.worker_thread_id.as_deref(), Some("worker-thread"));
+ assert_eq!(decoded.model_override.as_deref(), Some("worker-model"));
+ assert_eq!(
+ decoded.tier.as_deref(),
+ Some(definition.agent_tier.as_str())
+ );
+ }
+
+ #[test]
+ fn classified_stop_cause_survives_the_neutral_subagent_projection() {
+ let definitions =
+ crate::agent_registry::host_definition::AgentDefinitionRegistry::builtins_only();
+ let definition = definitions.get("orchestrator").unwrap();
+ let cause = tinyagents_harness::no_progress::ClassifiedStopCause {
+ class: "permission".into(),
+ operation: "shell".into(),
+ summary: "permission blocked shell".into(),
+ };
+ let outcome = SubagentRunOutcome {
+ task_id: "stopped-task".into(),
+ agent_id: definition.id.clone(),
+ output: "partial progress".into(),
+ iterations: 1,
+ failure_cause: Some(cause),
+ elapsed: std::time::Duration::ZERO,
+ mode: crate::agent::subagent_host::SubagentMode::Typed,
+ status: SubagentRunStatus::Incomplete {
+ reason: "permission blocked shell".into(),
++ failure_cause: None,
+ },
+ final_history: Vec::new(),
+ usage: SubagentUsage::default(),
+ artifact_paths: Vec::new(),
+ persistence_disposition:
+ tinyagents_orchestration::subagent::SubagentPersistenceDisposition::TerminalInserted,
+ };
+
+ let neutral = host_outcome_to_neutral(outcome, definition, &SubagentRunOptions::default());
+ assert_eq!(
+ neutral.extensions["failure_cause"],
+ serde_json::json!({
+ "class": "permission",
+ "operation": "shell",
- "summary": "permission blocked shell",
+ })
+ );
+ }
++
+#[test]
+fn classified_stop_extension_round_trips_without_the_private_summary() {
+ let cause = tinyagents_harness::no_progress::ClassifiedStopCause {
+ class: "uncertain_side_effect".into(),
+ operation: "web_answer_tool".into(),
+ summary: "private URL https://example.com/private?q=secret".into(),
+ };
+ let extension = encode_classified_stop_cause(&cause);
+ let mut neutral = SubagentOutcome::cancelled("task");
+ neutral
+ .extensions
+ .insert(CLASSIFIED_STOP_CAUSE_EXTENSION.into(), extension);
+
+ let serialized = serde_json::to_string(&neutral).expect("neutral outcome serializes");
+ assert!(!serialized.contains("example.com"));
+ assert!(!serialized.contains("private URL"));
+ let reloaded: SubagentOutcome =
+ serde_json::from_str(&serialized).expect("neutral outcome reloads");
+ let reloaded_extension = reloaded
+ .extensions
+ .get(CLASSIFIED_STOP_CAUSE_EXTENSION)
+ .expect("namespaced stop cause extension");
+ let restored = decode_classified_stop_cause(reloaded_extension, "persisted reason")
+ .expect("typed cause reloads");
+
+ assert_eq!(restored.class, "uncertain_side_effect");
+ assert_eq!(restored.operation, "web_answer_tool");
+ assert_eq!(restored.summary, "persisted reason");
+}
+
+#[test]
- fn host_incomplete_status_round_trips_through_neutral_persistence() {
++fn host_incomplete_status_round_trips_with_a_sanitized_stop_cause() {
++ let definitions =
++ crate::agent_registry::host_definition::AgentDefinitionRegistry::builtins_only();
++ let definition = definitions.get("orchestrator").unwrap();
++ let reason = "stopped before finishing; reconcile external state";
+ let cause = tinyagents_harness::no_progress::ClassifiedStopCause {
+ class: "uncertain_side_effect".into(),
+ operation: "web_answer_tool".into(),
+ summary: "private URL https://example.com/private?q=secret".into(),
+ };
- let host = SubagentRunOutcome {
++ let outcome = SubagentRunOutcome {
+ task_id: "task".into(),
- agent_id: "researcher".into(),
++ agent_id: definition.id.clone(),
+ output: "partial".into(),
+ iterations: 2,
++ failure_cause: Some(cause.clone()),
+ elapsed: std::time::Duration::from_millis(10),
+ mode: crate::agent::subagent_host::SubagentMode::Typed,
+ status: SubagentRunStatus::Incomplete {
- reason: "stopped before finishing; reconcile external state".into(),
++ reason: reason.into(),
+ failure_cause: Some(cause),
+ },
+ final_history: Vec::new(),
+ usage: SubagentUsage::default(),
+ artifact_paths: Vec::new(),
+ persistence_disposition:
+ tinyagents_orchestration::subagent::SubagentPersistenceDisposition::TerminalInserted,
+ };
- let definition = crate::agent::harness::host_definition::AgentDefinition {
- id: "researcher".into(),
- when_to_use: "research".into(),
- display_name: None,
- system_prompt: tinyagents_definition::PromptSource::Inline("prompt".into()),
- model: tinyagents_definition::ModelSpec::Inherit,
- temperature: 0.0,
- tools: tinyagents_definition::ToolScope::Named(Vec::new()),
- disallowed_tools: Vec::new(),
- skill_filter: None,
- extra_tools: Vec::new(),
- deferred_tools: Vec::new(),
- tool_rules: None,
- max_iterations: 2,
- iteration_policy: Default::default(),
- max_result_chars: None,
- max_turn_output_tokens: None,
- timeout_secs: None,
- sandbox_mode: tinyagents_definition::SandboxMode::None,
- background: false,
- subagents: Vec::new(),
- delegate_name: None,
- agent_tier: tinyagents_definition::AgentTier::Worker,
- source: tinyagents_definition::DefinitionSource::Builtin,
- extensions: crate::agent::harness::host_definition::AgentExt {
- omit_identity: true,
- omit_memory_context: true,
- omit_safety_preamble: true,
- tokenjuice_compression: tinyjuice_bus::types::AgentTokenjuiceCompression::Auto,
- searches_connected_mcp: false,
- ..Default::default()
- },
- role: None,
- };
- let neutral = host_outcome_to_neutral(host, &definition, &SubagentRunOptions::default());
++
++ let neutral = host_outcome_to_neutral(outcome, definition, &SubagentRunOptions::default());
+ let serialized = serde_json::to_string(&neutral).expect("neutral outcome serializes");
+ assert!(!serialized.contains("example.com"));
+ let reloaded: SubagentOutcome =
+ serde_json::from_str(&serialized).expect("neutral outcome reloads");
+ let SubagentOutcomeKind::Incomplete(incomplete) = reloaded.status else {
+ panic!("incomplete status survives neutral persistence");
+ };
+ let restored = incomplete_run_status(incomplete.reason, &reloaded.extensions);
+ let SubagentRunStatus::Incomplete {
- reason,
++ reason: restored_reason,
+ failure_cause: Some(cause),
+ } = restored
+ else {
+ panic!("typed stop cause survives neutral persistence");
+ };
+
- assert_eq!(reason, "stopped before finishing; reconcile external state");
++ assert_eq!(restored_reason, reason);
+ assert_eq!(cause.class, "uncertain_side_effect");
+ assert_eq!(cause.operation, "web_answer_tool");
+ assert_eq!(cause.summary, reason);
+}
diff --cc crates/openhuman-core/src/agent/subagent_host/ops/runner.rs
index c100e7338d,41c68062c3..986f985de9
--- a/crates/openhuman-core/src/agent/subagent_host/ops/runner.rs
+++ b/crates/openhuman-core/src/agent/subagent_host/ops/runner.rs
@@@ -9,15 -9,13 +9,13 @@@
use std::collections::HashSet;
use std::time::Instant;
- use crate::agent::harness::artifact_offload::offload_run_result;
use crate::agent::harness::fork_context::ParentExecutionContext;
- use crate::agent::harness::host_definition::{AgentDefinition, AgentDefinitionRegistry};
- use crate::agent::prompts::{
- render_subagent_system_prompt_with_format, PromptContext, SubagentRenderOptions,
- };
+ use crate::agent::prompts::render_subagent_system_prompt_with_format;
+ use crate::agent::prompts::{PromptContext, SubagentRenderOptions};
+ use crate::agent::session_host::dedup_visible_tool_specs;
use crate::agent::subagent_host::definition_iter_cap;
use crate::agent::subagent_host::tool_prep::{
- filter_tool_indices, is_subagent_spawn_tool, load_prompt_source, subagent_prompt_protocol,
+ filter_tool_indices, is_subagent_spawn_tool, subagent_prompt_protocol,
};
use crate::agent::subagent_host::types::{
SubagentMode, SubagentRunError, SubagentRunOptions, SubagentRunOutcome,
@@@ -36,15 -31,9 +31,13 @@@ use tinyagents_harness::context::{curre
use tinytools::{SandboxMode as TinyagentsSandboxMode, ToolSpec, WorkspaceDescriptor};
use tinytools_std::file_state::with_file_state_agent_id;
- use super::prompt::{
- append_artifact_offload_contract, append_subagent_role_contract, dedup_tool_specs_by_name,
- };
- use super::provider::{resolve_subagent_source, user_is_signed_in_to_composio};
+ use super::prompt::compose_subagent_system_prompt;
+ use super::provider::resolve_subagent_source;
+#[path = "runner_prompt.rs"]
+mod runner_prompt;
- use runner_prompt::{load_typed_prompt_source, LoadedConfig};
++use runner_prompt::load_typed_prompt_source;
+
/// Runtime spawn-hierarchy gate decision for one delegation hop.
///
/// `parent_def` is the resolved parent agent definition (looked up from the
@@@ -529,6 -408,22 +408,21 @@@ fn workspace_descriptor_for_subagent
)
}
+ /// One spawn's snapshot of the host config, loaded once by [`run_subagent`].
+ ///
+ /// `Config::load_or_init()` is **not cached** — it re-resolves the config dirs
+ /// and re-reads `config.toml` on every call. `run_typed_mode` needed it in six
+ /// places, so a single sub-agent spawn used to hit the disk six times and could
+ /// observe six *different* configs if the file changed mid-spawn.
+ ///
+ /// The error is captured as a `String` rather than dropped to `Option` so the
+ /// sites that log it can say why the config was unavailable; every site
+ /// degrades without it.
+ ///
+ /// Threading this in as a parameter (rather than loading it inside the runtime)
+ /// is `docs/specs/plan-agents.md` Phase 3: the sub-agent runner is slated to
+ /// move into TinyAgents, and a generic runtime has no config file to load.
+ type LoadedConfig = Result<std::sync::Arc<crate::config::Config>, String>;
-
// ─────────────────────────────────────────────────────────────────────────────
// Typed mode — narrow prompt, filtered tools, cheaper model
// ─────────────────────────────────────────────────────────────────────────────
@@@ -1025,11 -920,3 +922,6 @@@ async fn run_typed_mode
tinyagents_orchestration::subagent::SubagentPersistenceDisposition::TerminalExisting,
})
}
-
- #[cfg(test)]
- #[path = "runner_result_cap_tests.rs"]
- mod result_cap_tests;
-
+#[cfg(test)]
+#[path = "runner_flow_prompt_tests.rs"]
+mod flow_prompt_tests;
diff --cc crates/openhuman-core/src/agent/tinyagents/middleware/repeated_failure.rs
index 0bd5e62aa5,44d3d50e2f..ec60cd56eb
--- a/crates/openhuman-core/src/agent/tinyagents/middleware/repeated_failure.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/middleware/repeated_failure.rs
@@@ -112,29 -72,16 +72,24 @@@ impl RepeatedToolFailureMiddleware
identical_threshold: usize,
halt_summary: tinyagents_harness::turn_outcome::HaltSummarySlot,
) -> Self {
- Self {
- stop: StopLatch::new(handle, halt_summary),
- tracker: NoProgressTracker::new(identical_threshold),
- classified: ClassifiedFailureTracker::default(),
- last_exit_report: std::sync::Mutex::default(),
- step: AtomicUsize::new(0),
- arg_sigs: std::sync::Mutex::new(std::collections::HashMap::new()),
- target_scopes: std::sync::Mutex::new(std::collections::HashMap::new()),
- recoverable: RecoverableFailureLadder::default(),
- pending_nudges: EphemeralInstructionQueue::new(),
- call_effects: std::sync::Mutex::new(std::collections::HashMap::new()),
- tool_facts: None,
- }
+ let policy = Arc::new(HostFailurePolicy::new(handle.clone(), halt_summary.clone()));
+ let owner = FailureScopeMiddleware::with_identical_threshold(
+ handle,
+ halt_summary,
+ policy.clone(),
+ identical_threshold,
+ );
+ Self { owner, policy }
}
+ /// Return typed classified facts only while this middleware still owns
+ /// the halt note recorded for the current run.
+ pub(crate) fn current_classified_cause(
+ &self,
+ ) -> Option<tinyagents_harness::no_progress::ClassifiedStopCause> {
+ self.stop.current_classified_cause()
+ }
+
/// Judge each call's side effect from the registered tools' own
/// declarations ([`tinyagents_harness::middleware::tool_sets_lookup`]) rather than
/// from tool names alone.
diff --cc crates/openhuman-core/src/agent/tinyagents/turn_middleware.rs
index c4cfd879cd,9c09d36470..fd948a961d
--- a/crates/openhuman-core/src/agent/tinyagents/turn_middleware.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/turn_middleware.rs
@@@ -275,13 -294,29 +294,24 @@@ pub(super) fn install_turn_middleware
harness.push_middleware(mw.clone());
}
- stop_hooks::install(
- harness,
- handle.as_ref(),
- model,
- stop_hooks,
- halt_summary.clone(),
- );
+ if handle.is_some() && !stop_hooks.is_empty() {
+ let summary = halt_summary.clone();
+ harness.push_middleware(Arc::new(
+ tinyagents_hooks::stop::StopHookMiddleware::new(model, stop_hooks)
+ .with_metrics_seed(crate::agent::cost::turn_cost())
+ .with_stop_observer(move |report| {
+ tracing::warn!(
+ target: "stop_hooks",
+ hook = %report.hook,
+ iteration = report.iteration,
+ model = %report.model,
+ "[stop_hooks] hook voted to stop the turn — pausing run: {}",
+ report.reason
+ );
- *summary
- .lock()
- .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(format!(
- "Stopping after {} model call(s): {}",
- report.iteration, report.reason
- ));
++ record_stop_summary(&summary, report.iteration, &report.reason);
+ }),
+ ));
+ }
// SHADOW tool-exposure layer (issue #4249, 01.3 — dynamic exposure). Compose
// the OpenHuman exposure policy as a crate-native selection layer
// (ToolAllowlistMiddleware + a ContextualToolSelectionMiddleware built via
@@@ -598,3 -633,3 +628,15 @@@
prompt_cache_guard,
}
}
++
++fn record_stop_summary(summary: &HaltSummarySlot, iteration: u32, reason: &str) {
++ *summary
++ .lock()
++ .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(format!(
++ "Stopping after {iteration} model call(s): {reason}"
++ ));
++}
++
++#[cfg(test)]
++#[path = "turn_middleware_tests.rs"]
++mod tests;
diff --cc crates/openhuman-core/src/agent/tinyagents/turn_middleware_tests.rs
index 0000000000,0000000000..6d2ddcdabd
new file mode 100644
--- /dev/null
+++ b/crates/openhuman-core/src/agent/tinyagents/turn_middleware_tests.rs
@@@ -1,0 -1,0 +1,22 @@@
++use super::*;
++
++#[test]
++fn a_poisoned_halt_summary_does_not_abort_stop_reporting() {
++ let slot: HaltSummarySlot = Arc::new(std::sync::Mutex::new(None));
++ let poisoned = Arc::clone(&slot);
++ assert!(std::thread::spawn(move || {
++ let _guard = poisoned.lock().unwrap();
++ panic!("synthetic prior writer failure");
++ })
++ .join()
++ .is_err());
++
++ record_stop_summary(&slot, 1, "limit reached");
++
++ assert_eq!(
++ slot.lock()
++ .unwrap_or_else(std::sync::PoisonError::into_inner)
++ .as_deref(),
++ Some("Stopping after 1 model call(s): limit reached")
++ );
++}
diff --cc crates/openhuman-core/src/agent/tinyagents/turn_run_finalize.rs
index 7e880d58e3,a71046e7fd..bd60e759f9
--- a/crates/openhuman-core/src/agent/tinyagents/turn_run_finalize.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/turn_run_finalize.rs
@@@ -163,10 -161,9 +161,10 @@@ pub(super) async fn finalize_turn_outco
// A run the harness stopped (breaker / cap) is traced as stopped, not as a
// clean completion. No deadline wind-down on this path: only the session
// turn carries one, and it records the stop through its sidecar.
+ let failure_cause = run.failure_cause.clone();
- let stop = crate::agent::turn_projection::classify_stop_with_cause(
+ let stop = crate::agent::session_host::stop_summary::classify_stop_with_cause(
breaker_halt.as_deref(),
- run.failure_cause.clone(),
+ failure_cause.clone(),
false,
hit_cap,
);
diff --cc crates/openhuman-core/src/agent_registry/README.md
index 9f6776d87d,b4bc599860..50f1d8bcf1
--- a/crates/openhuman-core/src/agent_registry/README.md
+++ b/crates/openhuman-core/src/agent_registry/README.md
@@@ -60,12 -60,11 +60,12 @@@ the harness runs come from [`agents/`](
Each built-in agent owns a subfolder with an `agent.toml` (id, `when_to_use`,
model, tool scope, sandbox mode, iteration cap, tier, `omit_*` flags, parsed
- directly into `AgentDefinition`) and a `prompt.rs` that exposes
- `pub fn build(&PromptContext) -> anyhow::Result<String>`. Most builders include
- their archetype from a sibling `prompt.md`; the two flow builders receive their
- archetype text from TinyFlows Copilot through an explicit prompt context value.
- Builders append runtime-dependent sections such as the rendered tool list and
- workspace to that archetype.
-through `tinyagents_definition::parse_str` into `AgentDefinition`), a
-`prompt.md` holding the static archetype body, and a `prompt.rs` that
-`include_str!`s that body and exposes
-`pub fn build(&PromptContext) -> anyhow::Result<String>`, appending
-runtime-dependent sections (rendered tool list, workspace) to it.
++through `tinyagents_definition::parse_str` into `AgentDefinition`), and a
++`prompt.rs` that exposes `pub fn build(&PromptContext) -> anyhow::Result<String>`.
++Most builders include their archetype from a sibling `prompt.md`; the two flow
++builders receive their archetype text from TinyFlows Copilot through an
++explicit prompt context value. Builders append runtime-dependent sections such
++as the rendered tool list and workspace to that archetype.
Every archetype uses the shared sub-agent turn graph.
[`agents/loader.rs`](agents/loader.rs) owns the `BUILTINS` slice and
diff --cc crates/openhuman-core/src/agent_registry/agents/fleet_prompt_tests.rs
index 257645b87f,c561ed789d..3596c2ddc3
--- a/crates/openhuman-core/src/agent_registry/agents/fleet_prompt_tests.rs
+++ b/crates/openhuman-core/src/agent_registry/agents/fleet_prompt_tests.rs
@@@ -6,9 -6,9 +6,9 @@@
//! anyone writing a test for it.
use super::load_builtins;
- use crate::agent::harness::host_definition::AgentDefinition;
use crate::agent::prompts::PromptContext;
+ use crate::agent_registry::host_definition::AgentDefinition;
-use std::collections::{BTreeMap, BTreeSet, HashSet};
+use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
use std::sync::Arc;
use tinyagents_definition::{PromptSource, SubagentEntry, ToolScope};
use tinytools_agent::dialect::ToolCallFormat;
diff --cc crates/openhuman-core/src/agent_registry/agents/flow_discovery/mod.rs
index 3ee4a69dc4,0000000000..3ee4a69dc4
mode 100644,000000..100644
--- a/crates/openhuman-core/src/agent_registry/agents/flow_discovery/mod.rs
+++ b/crates/openhuman-core/src/agent_registry/agents/flow_discovery/mod.rs
diff --cc crates/openhuman-core/src/agent_registry/agents/flow_discovery/prompt.rs
index adc2887e7c,0000000000..adc2887e7c
mode 100644,000000..100644
--- a/crates/openhuman-core/src/agent_registry/agents/flow_discovery/prompt.rs
+++ b/crates/openhuman-core/src/agent_registry/agents/flow_discovery/prompt.rs
diff --cc crates/openhuman-core/src/agent_registry/agents/flow_discovery/prompt_tests.rs
index f8a85a1cf2,0000000000..98d3ca84ac
mode 100644,000000..100644
--- a/crates/openhuman-core/src/agent_registry/agents/flow_discovery/prompt_tests.rs
+++ b/crates/openhuman-core/src/agent_registry/agents/flow_discovery/prompt_tests.rs
@@@ -1,69 -1,0 +1,69 @@@
+use crate::agent::prompts::PromptContext;
- use crate::agent::registry::agents::flow_discovery::prompt::build;
++use crate::agent_registry::agents::flow_discovery::prompt::build;
+use tinytools_agent::dialect::ToolCallFormat;
+
+fn ctx<'a>(
+ workspace: &'a std::path::Path,
+ visible: &'a std::collections::HashSet<String>,
+ archetype: Option<&'a str>,
+) -> PromptContext<'a> {
+ PromptContext {
+ workspace_dir: workspace,
+ model_name: "test",
+ agent_id: "flow_discovery",
+ flow_archetype_text: archetype,
+ tools: &[],
+ workflows: &[],
+ dispatcher_instructions: "",
+ visible_tool_names: visible,
+ tool_call_format: ToolCallFormat::PFormat,
+ connected_integrations: &[],
+ connected_identities_md: String::new(),
+ user_identity: None,
+ personality_roster: vec![],
+ agents_md_global: None,
+ agents_md_local: None,
+ }
+}
+
+#[tokio::test]
+async fn module_prompt_teaches_the_read_only_emit_invariant() {
+ let workspace = tempfile::tempdir().expect("workspace");
+ let config = crate::config::Config {
+ workspace_dir: workspace.path().to_path_buf(),
+ ..crate::config::Config::default()
+ };
+ let registry = crate::agent::harness::host_definition::AgentDefinitionRegistry::builtins_only();
+ let definition = registry
+ .get("flow_discovery")
+ .expect("flow_discovery builtin");
+ let archetype =
+ crate::agent::prompts::flow_archetype::load_for_definition(Some(&config), definition)
+ .await
+ .expect("TinyFlows GetPrompt succeeds")
+ .expect("flow builtin prompt");
+ let body = build(&ctx(
+ workspace.path(),
+ &std::collections::HashSet::new(),
+ Some(&archetype),
+ ))
+ .expect("compose module prompt");
+ let lc = body.to_lowercase();
+ assert!(lc.contains("suggest_workflows"), "must name the emit tool");
+ assert!(
+ lc.contains("read-only") || lc.contains("never act") || lc.contains("never build"),
+ "prompt must teach the read-only invariant"
+ );
+}
+
+#[test]
+fn flow_discovery_requires_an_explicit_archetype_override() {
+ let workspace = tempfile::tempdir().expect("workspace");
+ let error = build(&ctx(
+ workspace.path(),
+ &std::collections::HashSet::new(),
+ None,
+ ))
+ .expect_err("no static or host fallback is allowed");
+ assert!(error.to_string().contains("GetPrompt"));
+}
diff --cc crates/openhuman-core/src/agent_registry/agents/flow_prompts.rs
index 49b159195f,0000000000..49b159195f
mode 100644,000000..100644
--- a/crates/openhuman-core/src/agent_registry/agents/flow_prompts.rs
+++ b/crates/openhuman-core/src/agent_registry/agents/flow_prompts.rs
diff --cc crates/openhuman-core/src/agent_registry/agents/loader.rs
index 432641f938,259b7ee175..c0e7f49fa3
--- a/crates/openhuman-core/src/agent_registry/agents/loader.rs
+++ b/crates/openhuman-core/src/agent_registry/agents/loader.rs
@@@ -190,93 -193,14 +193,19 @@@ fn builtin_enabled(_b: &BuiltinAgent) -
/// Parse a single [`BuiltinAgent`] triple into a finished [`AgentDefinition`].
fn parse_builtin(b: &BuiltinAgent) -> Result<AgentDefinition> {
// The TOML ships without `system_prompt` — serde falls back to
- // `defaults::empty_inline_prompt` — and the loader installs its dynamic
- // prompt builder below. Most builders include a sibling `prompt.md`; flow
- // builders receive their archetype text from TinyFlows Copilot.
- let mut def: AgentDefinition = toml::from_str(b.toml)
- // `defaults::empty_inline_prompt` — and the loader injects the
- // rendered sibling `prompt.md` immediately below.
++ // `defaults::empty_inline_prompt` — and the loader installs a dynamic
++ // host-owned prompt builder below. Most builders include a sibling
++ // `prompt.md`; flow builders receive their archetype text from TinyFlows.
+ let mut def: AgentDefinition = parse_str(b.toml, DefinitionSource::Builtin)
.with_context(|| format!("parsing built-in agent `{}` TOML", b.id))?;
- // Install the function-driven prompt builder and stamp the source.
+ // Install the host-owned function-driven prompt builder.
def.system_prompt = PromptSource::Dynamic(());
def.extensions.prompt_builder = Some(b.prompt_fn);
+ def.extensions.tinyflows_prompt_owner = match b.id {
+ "workflow_builder" | "flow_discovery" => Some(b.id.to_owned()),
+ _ => None,
+ };
- def.source = DefinitionSource::Builtin;
// Sanity check: file layout id must match declared TOML id. This
// catches copy-paste mistakes where someone forgets to update the
diff --cc crates/openhuman-core/src/agent_registry/agents/mod.rs
index 0000000000,2a6e698482..5d744b4d23
mode 000000,100644..100644
--- a/crates/openhuman-core/src/agent_registry/agents/mod.rs
+++ b/crates/openhuman-core/src/agent_registry/agents/mod.rs
@@@ -1,0 -1,56 +1,65 @@@
+ //! Built-in agent archetypes.
+ //!
+ //! Each submodule below is one shipped agent and generally has the same three
+ //! files, so none of the leaf `mod.rs` files need their own doc comment. The
+ //! trigger prompt builders live with the triage domain instead:
+ //!
+ //! * `agent.toml` — id, `when_to_use`, model, tool scope, sandbox mode,
+ //! iteration cap, tier, and `omit_*` flags. Parsed directly into
+ //! [`crate::agent_registry::host_definition::AgentDefinition`]; ships without
+ //! a `system_prompt`.
+ //! * `prompt.md` — the static archetype body. `prompt.rs` embeds it with
+ //! `include_str!`; nothing else reads it.
+ //! * `prompt.rs` — exposes `pub fn build(&PromptContext) ->
+ //! anyhow::Result<String>`, which appends runtime-dependent sections
+ //! (rendered tool list, workspace) to the `prompt.md` body.
+ //! [`BUILTINS`] pairs the parsed definition with its host prompt callback.
+ //! The loader records `PromptSource::Dynamic(())` and stores that callback
+ //! in the host-only prompt-builder extension. Most archetypes keep a
+ //! `prompt_tests.rs` beside it.
+ //!
+ //! `loader.rs` holds [`BUILTINS`] and [`load_builtins`]. It delegates tier
+ //! validation to `tinyagents_definition::DefinitionSet`. The slice also
+ //! registers archetypes that live with other domains (`skills/*/agent/`,
+ //! `flows/agents/`), so this directory is not the full built-in set. The
+ //! package `README.md` one level up describes what each archetype does.
+
+ mod loader;
+
+ #[cfg(test)]
+ #[path = "fleet_prompt_tests.rs"]
+ mod fleet_prompt_tests;
+
+ #[path = "critic/prompt.rs"]
+ pub mod critic;
+ #[path = "image_agent/prompt.rs"]
+ pub mod image_agent;
+ #[path = "morning_briefing/prompt.rs"]
+ pub mod morning_briefing;
+ #[path = "orchestrator/prompt.rs"]
+ pub mod orchestrator;
+ #[path = "planner/prompt.rs"]
+ pub mod planner;
+ #[path = "presentation_agent/prompt.rs"]
+ pub mod presentation_agent;
+ #[path = "summarizer/prompt.rs"]
+ pub mod summarizer;
+ #[path = "task_manager_agent/prompt.rs"]
+ pub mod task_manager_agent;
+ pub use crate::triage::trigger_reactor_prompt as trigger_reactor;
+ pub use crate::triage::trigger_triage_prompt as trigger_triage;
+ #[path = "video_agent/prompt.rs"]
+ pub mod video_agent;
+ #[path = "vision_agent/prompt.rs"]
+ pub mod vision_agent;
+
++#[cfg(feature = "flows")]
++#[path = "flow_discovery/mod.rs"]
++pub mod flow_discovery;
++#[cfg(feature = "flows")]
++mod flow_prompts;
++#[cfg(feature = "flows")]
++#[path = "workflow_builder/mod.rs"]
++pub mod workflow_builder;
++
+ pub use loader::{load_builtins, BuiltinAgent, BUILTINS};
diff --cc crates/openhuman-core/src/agent_registry/agents/workflow_builder/mod.rs
index 7d63a3395e,0000000000..7d63a3395e
mode 100644,000000..100644
--- a/crates/openhuman-core/src/agent_registry/agents/workflow_builder/mod.rs
+++ b/crates/openhuman-core/src/agent_registry/agents/workflow_builder/mod.rs
diff --cc crates/openhuman-core/src/agent_registry/agents/workflow_builder/prompt.rs
index e8b7610eb6,0000000000..e8b7610eb6
mode 100644,000000..100644
--- a/crates/openhuman-core/src/agent_registry/agents/workflow_builder/prompt.rs
+++ b/crates/openhuman-core/src/agent_registry/agents/workflow_builder/prompt.rs
diff --cc crates/openhuman-core/src/agent_registry/agents/workflow_builder/prompt_tests.rs
index 3bca18cf47,0000000000..3bca18cf47
mode 100644,000000..100644
--- a/crates/openhuman-core/src/agent_registry/agents/workflow_builder/prompt_tests.rs
+++ b/crates/openhuman-core/src/agent_registry/agents/workflow_builder/prompt_tests.rs
diff --cc crates/openhuman-core/src/core/README.md
index aa95253d3e,d277e68724..e934c90f1e
--- a/crates/openhuman-core/src/core/README.md
+++ b/crates/openhuman-core/src/core/README.md
@@@ -155,7 -155,7 +155,7 @@@ and the host is the one that knows `E`
`DomainEvent`, a `#[non_exhaustive]` enum whose `domain()` value is appended
to `EVENTS_ROOT` (`/ai/tinyhumans/openhuman/events`) as the routing key.
The catalog is published under `EVENTS_INTERFACE`
- (`ai.tinyhumans.openhuman.Events2`) at `EVENTS_VERSION`, currently `2.1.0`.
-(`ai.tinyhumans.openhuman.Events`) at `EVENTS_VERSION`, currently `2.0.0`.
++(`ai.tinyhumans.openhuman.Events`) at `EVENTS_VERSION`, currently `2.1.0`.
`bus::init()` starts the in-process broker and announces a peer manifest
(advisory; failure only logs). Every accessor is safe before `init`:
diff --cc crates/openhuman-core/src/core/agent_cli/debug/mod.rs
index 94142ae6f1,a3f8185199..c7912f47a4
--- a/crates/openhuman-core/src/core/agent_cli/debug/mod.rs
+++ b/crates/openhuman-core/src/core/agent_cli/debug/mod.rs
@@@ -180,39 -174,20 +180,34 @@@ async fn load_dump_config
/// Build a real [`Agent`] via `from_config_for_agent`, populate live
/// connected integrations, and render the turn-1 system prompt.
-async fn render_via_session(config: &Config, agent_id: &str) -> Result<DumpedPrompt> {
- let mut agent = OpenHumanSessionHost::from_config_for_agent(
- &crate::core::runtime::DispatchCtx::host_default(),
- config,
- agent_id,
- )
- .with_context(|| format!("building session agent for `{agent_id}`"))?;
+async fn render_via_session(
+ ctx: &crate::core::runtime::DispatchCtx,
+ config: &Config,
+ agent_id: &str,
+) -> Result<DumpedPrompt> {
+ let mut agent = OpenHumanSessionHost::from_config_for_agent(ctx, config, agent_id)
+ .with_context(|| format!("building session agent for `{agent_id}`"))?;
- // Match turn-1 behaviour: fetch the user's active Composio
- // connections so the rendered prompt mirrors what the LLM actually
- // sees. Best-effort — failures degrade to an empty integration
- // list, same as the live runtime.
- agent.fetch_connected_integrations().await;
- // Mirror turn-1: synthesise `delegate_*` tools for connected
- // Composio toolkits now that we know what's actually authorised.
- agent.refresh_delegation_tools();
+ // Use the live turn prelude's hydration and surface reconciliation so this
+ // snapshot matches what the runtime will send, without starting a model turn.
+ agent.refresh_prompt_surface().await;
+ #[cfg(feature = "flows")]
+ let flow_archetype_text = match agent.resolved_definition() {
+ Some(definition) => {
+ crate::agent::prompts::flow_archetype::load_for_definition(
+ Some(config),
+ definition.as_ref(),
+ )
+ .await?
+ }
+ None => None,
+ };
+ #[cfg(not(feature = "flows"))]
+ let flow_archetype_text: Option<String> = None;
+
let text = agent
- .build_system_prompt()
+ .build_system_prompt_with_flow_archetype(flow_archetype_text.as_deref())
.with_context(|| format!("rendering system prompt for `{agent_id}`"))?;
Ok(session_dump(&agent, agent_id, text))
diff --cc crates/openhuman-core/src/core/agent_cli/debug/mod_tests.rs
index 8b103ac8e4,0000000000..8b103ac8e4
mode 100644,000000..100644
--- a/crates/openhuman-core/src/core/agent_cli/debug/mod_tests.rs
+++ b/crates/openhuman-core/src/core/agent_cli/debug/mod_tests.rs
diff --cc crates/openhuman-core/src/core/bus.rs
index 0dcf80165d,90dbbbeeed..12099744b0
--- a/crates/openhuman-core/src/core/bus.rs
+++ b/crates/openhuman-core/src/core/bus.rs
@@@ -94,10 -95,8 +95,11 @@@ pub const EVENTS_INTERFACE: &str = "ai.
/// `ComposioConnectionCreated` and `ComposioConfigChanged` (additive): a
/// subscriber rebuilds its dispatch context from it instead of reading an
/// ambient one.
-/// `2.0.0` retires the obsolete desktop push-to-talk transcript event.
-pub const EVENTS_VERSION: Version = Version::new(2, 0, 0);
+/// `2.0.0` removes `CronDeliveryRequested`; announce delivery now sends
+/// synchronously through the cron channel bridge.
+/// `2.1.0` adds optional `CronJobCompleted` tenant ownership.
++/// `2.0.0` also retires the obsolete desktop push-to-talk transcript event.
+pub const EVENTS_VERSION: Version = Version::new(2, 1, 0);
/// The bus. Initialised once by [`init`]; safe to touch before that.
pub static BUS: OnceBus<DomainEvent> = OnceBus::new();
diff --cc crates/openhuman-core/src/core/observability/progress_tracing.rs
index 0000000000,4bff63f513..b361468dba
mode 000000,100644..100644
--- a/crates/openhuman-core/src/core/observability/progress_tracing.rs
+++ b/crates/openhuman-core/src/core/observability/progress_tracing.rs
@@@ -1,0 -1,23 +1,50 @@@
+ //! Native trace export for completed TinyAgents runs.
+ //!
+ //! OpenHuman gates and sends native TinyAgents trace exports.
+
+ mod export;
+
+ #[cfg(test)]
+ #[path = "trace_export_adoption_tests.rs"]
+ mod adoption_tests;
+
++use serde_json::Value;
++use tinyagents_graph::{GraphLangfuseExporter, GraphObservation};
+ use tinyagents_harness::observability::trace_export::ExportBrand;
++use tinyagents_harness::observability::LangfuseTraceConfig;
+
+ /// Product identity stamped onto exported telemetry.
+ pub(crate) fn export_brand() -> ExportBrand<'static> {
+ ExportBrand {
+ product: "openhuman",
+ version: env!("CARGO_PKG_VERSION"),
+ }
+ }
+
+ #[cfg(test)]
+ pub(crate) use export::build_subagent_trace;
+ pub(crate) use export::{export_run_trace_from_journal, export_subagent_journal_trace};
++
++/// Build the generic graph-to-OTLP projection with OpenHuman's product name.
++/// Flow identity and metadata stay with the flow adapter; this layer owns the
++/// shared projection boundary used by both durable graph event sources.
++pub(crate) fn build_graph_otlp_requests(
++ exporter: &GraphLangfuseExporter,
++ trace: LangfuseTraceConfig,
++ observations: &[GraphObservation],
++) -> tinyagents_harness::error::Result<Vec<Value>> {
++ exporter.build_otlp_requests(trace, observations, export_brand().product)
++}
++
++/// Send a generic graph trace through the exporter’s authenticated OTLP
++/// client. Callers own timeout and best-effort policy for their run lifecycle.
++pub(crate) async fn send_graph_otlp_requests(
++ exporter: &GraphLangfuseExporter,
++ requests: Vec<Value>,
++) -> tinyagents_harness::error::Result<usize> {
++ let count = requests.len();
++ for request in requests {
++ exporter.client().send_otlp(request).await?;
++ }
++ Ok(count)
++}
diff --cc crates/openhuman-core/src/core/runtime/context.rs
index 17bab2fb4a,79016c98fb..8714008268
--- a/crates/openhuman-core/src/core/runtime/context.rs
+++ b/crates/openhuman-core/src/core/runtime/context.rs
@@@ -21,6 -21,6 +21,9 @@@ use std::sync::{Arc, OnceLock, RwLock}
use crate::core::runtime::TokenSource;
use crate::core::types::HostKind;
++#[path = "context_accessors.rs"]
++mod accessors;
++
/// The process-wide default context — the first one built. Callers that dispatch
/// RPC without an explicit per-call context (the desktop shell, the CLI, tests)
/// resolve to this. Multi-tenant hosts override it per dispatch via
@@@ -291,16 -284,11 +292,17 @@@ impl CoreContext
}))),
domains,
tool_groups,
+ autonomy_tier_source: if embedder_config.is_some() {
+ super::AutonomyTierSource::Captured
+ } else {
+ super::AutonomyTierSource::LiveConfig
+ },
+ autonomy_tier_ceiling: None,
components,
embedder_config,
+ latest_embedder_config,
user_skill_roots: true,
- backend_transport,
+ extensions: Default::default(),
turn_origin: None,
channel_thread: None,
session_agent: None,
@@@ -429,17 -435,11 +449,18 @@@
workspace_binding: RwLock::new(shared_binding),
domains,
tool_groups: overlay.tool_groups,
+ autonomy_tier_source: overlay
+ .autonomy_tier_source
+ .unwrap_or(self.autonomy_tier_source),
+ autonomy_tier_ceiling: overlay::stricter_autonomy_ceiling(
+ self.autonomy_tier_ceiling,
+ overlay.autonomy_tier_ceiling,
+ ),
components: self.components,
embedder_config: Some(overlay.config),
+ latest_embedder_config,
user_skill_roots: overlay.user_skill_roots,
- backend_transport: self.backend_transport.clone(),
+ extensions: self.extensions.clone(),
turn_origin: self.turn_origin.clone(),
channel_thread: self.channel_thread.clone(),
session_agent: overlay.session_agent.or_else(|| self.session_agent.clone()),
@@@ -455,23 -455,27 +476,6 @@@
self.session_agent.as_deref()
}
- /// Source binding for autonomy-tier decisions made by long-lived adapters.
- pub fn autonomy_tier_source(&self) -> super::AutonomyTierSource {
- self.autonomy_tier_source
- }
-
- /// The fixed autonomy ceiling inherited by this context, if any.
- pub fn autonomy_tier_ceiling(&self) -> Option<crate::security::AutonomyLevel> {
- self.autonomy_tier_ceiling
- /// The hook registrations bound to this context. Shared (not copied) by
- /// derived contexts.
- pub fn extensions(&self) -> &crate::core::slots::Extensions {
- &self.extensions
-- }
--
- /// The backend transport bound to this context, if the host supplied one.
- pub fn backend_transport(
- &self,
- ) -> Option<Arc<dyn crate::backend::transport::BackendTransport>> {
- self.backend_transport.clone()
- /// The hook registrations of the context this call runs under, for
- /// [`HookSlot`](crate::core::slots::HookSlot) lookups.
- ///
- /// Outside SaaS that is the ambient context (the process default when the
- /// task has no scope). In SaaS only the task's own scope counts: a task that
- /// lost its scope must not read the operator's registrations.
- pub fn current_extensions() -> Option<crate::core::slots::Extensions> {
- let ctx = if crate::core::runtime::is_saas() {
- Self::scoped()
- } else {
- Self::current()
- };
- ctx.map(|ctx| ctx.extensions.clone())
-- }
--
/// The resolved per-user workspace directory this context is bound to.
pub fn workspace_dir(&self) -> Result<std::path::PathBuf, String> {
self.workspace_binding
@@@ -734,8 -722,11 +722,11 @@@ mod agent_parts
#[path = "context_overlay.rs"]
mod overlay;
-pub use overlay::ContextOverlay;
+pub use overlay::{AutonomyTierSource, ContextOverlay};
+ #[path = "context_config.rs"]
+ mod config_access;
+
#[cfg(test)]
#[path = "context_test_support.rs"]
mod test_support;
diff --cc crates/openhuman-core/src/core/runtime/context_accessors.rs
index 0000000000,0000000000..c64d5269ce
new file mode 100644
--- /dev/null
+++ b/crates/openhuman-core/src/core/runtime/context_accessors.rs
@@@ -1,0 -1,0 +1,34 @@@
++use super::CoreContext;
++
++impl CoreContext {
++ /// Source binding for autonomy-tier decisions made by long-lived adapters.
++ pub fn autonomy_tier_source(&self) -> super::AutonomyTierSource {
++ self.autonomy_tier_source
++ }
++
++ /// The fixed autonomy ceiling inherited by this context, if any.
++ pub fn autonomy_tier_ceiling(&self) -> Option<crate::security::AutonomyLevel> {
++ self.autonomy_tier_ceiling
++ }
++
++ /// The hook registrations bound to this context. Shared (not copied) by
++ /// derived contexts.
++ pub fn extensions(&self) -> &crate::core::slots::Extensions {
++ &self.extensions
++ }
++
++ /// The hook registrations of the context this call runs under, for
++ /// [`HookSlot`](crate::core::slots::HookSlot) lookups.
++ ///
++ /// Outside SaaS that is the ambient context (the process default when the
++ /// task has no scope). In SaaS only the task's own scope counts: a task that
++ /// lost its scope must not read the operator's registrations.
++ pub fn current_extensions() -> Option<crate::core::slots::Extensions> {
++ let ctx = if crate::core::runtime::is_saas() {
++ Self::scoped()
++ } else {
++ Self::current()
++ };
++ ctx.map(|ctx| ctx.extensions.clone())
++ }
++}
diff --cc crates/openhuman-core/src/core/runtime/context_for_agent.rs
index 3ff0ac05ab,89242b4bf4..897a962608
--- a/crates/openhuman-core/src/core/runtime/context_for_agent.rs
+++ b/crates/openhuman-core/src/core/runtime/context_for_agent.rs
@@@ -30,12 -30,11 +30,13 @@@ impl CoreContext
workspace_binding: RwLock::new(binding),
domains: self.domains,
tool_groups: self.tool_groups.clone(),
+ autonomy_tier_source: self.autonomy_tier_source,
+ autonomy_tier_ceiling: self.autonomy_tier_ceiling,
components: self.components,
embedder_config: self.embedder_config.clone(),
+ latest_embedder_config: self.latest_embedder_config.as_ref().map(Arc::clone),
user_skill_roots: self.user_skill_roots,
- backend_transport: self.backend_transport.clone(),
+ extensions: self.extensions.clone(),
turn_origin: self.turn_origin.clone(),
channel_thread: self.channel_thread.clone(),
session_agent: Some(agent.to_string()),
diff --cc crates/openhuman-core/src/core/runtime/context_test_support.rs
index f7e554bb9a,5529b73c5a..12d2a8f3c9
--- a/crates/openhuman-core/src/core/runtime/context_test_support.rs
+++ b/crates/openhuman-core/src/core/runtime/context_test_support.rs
@@@ -20,12 -20,11 +20,13 @@@ impl CoreContext
}))),
domains,
tool_groups: Default::default(),
+ autonomy_tier_source: AutonomyTierSource::LiveConfig,
+ autonomy_tier_ceiling: None,
components: Default::default(),
embedder_config: None,
+ latest_embedder_config: None,
user_skill_roots: true,
- backend_transport: None,
+ extensions: Default::default(),
turn_origin: None,
channel_thread: None,
session_agent: None,
@@@ -68,12 -82,11 +84,13 @@@
}))),
domains,
tool_groups: Default::default(),
+ autonomy_tier_source: AutonomyTierSource::Captured,
+ autonomy_tier_ceiling: None,
components: Default::default(),
embedder_config: Some(config),
+ latest_embedder_config: Some(latest_embedder_config),
user_skill_roots: true,
- backend_transport: None,
+ extensions: Default::default(),
turn_origin: None,
channel_thread: None,
session_agent: None,
diff --cc crates/openhuman-core/src/core/runtime/context_tests.rs
index e9747a9d44,256ad5ef55..075d4e6df1
--- a/crates/openhuman-core/src/core/runtime/context_tests.rs
+++ b/crates/openhuman-core/src/core/runtime/context_tests.rs
@@@ -9,12 -9,11 +9,13 @@@ fn ctx(dir: &str) -> Arc<CoreContext>
}))),
domains: crate::core::runtime::DomainSet::full(),
tool_groups: Default::default(),
+ autonomy_tier_source: AutonomyTierSource::LiveConfig,
+ autonomy_tier_ceiling: None,
components: Default::default(),
embedder_config: None,
+ latest_embedder_config: None,
user_skill_roots: true,
- backend_transport: None,
+ extensions: Default::default(),
turn_origin: None,
channel_thread: None,
session_agent: None,
@@@ -390,12 -370,11 +372,13 @@@ fn degraded_context_rejects_workspace_b
}))),
domains: crate::core::runtime::DomainSet::full(),
tool_groups: Default::default(),
+ autonomy_tier_source: AutonomyTierSource::LiveConfig,
+ autonomy_tier_ceiling: None,
components: Default::default(),
embedder_config: None,
+ latest_embedder_config: None,
user_skill_roots: true,
- backend_transport: None,
+ extensions: Default::default(),
turn_origin: None,
channel_thread: None,
session_agent: None,
diff --cc crates/openhuman-core/src/core/runtime/context_turn_origin.rs
index 6360b20172,84f47bed94..c4f85620cc
--- a/crates/openhuman-core/src/core/runtime/context_turn_origin.rs
+++ b/crates/openhuman-core/src/core/runtime/context_turn_origin.rs
@@@ -39,12 -39,11 +39,13 @@@ impl CoreContext
}))),
domains: crate::core::runtime::DomainSet::full(),
tool_groups: Default::default(),
+ autonomy_tier_source: AutonomyTierSource::LiveConfig,
+ autonomy_tier_ceiling: None,
components: Default::default(),
embedder_config: None,
+ latest_embedder_config: None,
user_skill_roots: true,
- backend_transport: None,
+ extensions: Default::default(),
turn_origin: None,
channel_thread: None,
session_agent: None,
@@@ -103,12 -102,11 +104,13 @@@
),
domains: ctx.domains,
tool_groups: ctx.tool_groups.clone(),
+ autonomy_tier_source: ctx.autonomy_tier_source,
+ autonomy_tier_ceiling: ctx.autonomy_tier_ceiling,
components: ctx.components,
embedder_config: ctx.embedder_config.clone(),
+ latest_embedder_config: ctx.latest_embedder_config.as_ref().map(Arc::clone),
user_skill_roots: ctx.user_skill_roots,
- backend_transport: ctx.backend_transport.clone(),
+ extensions: ctx.extensions.clone(),
turn_origin: origin.or_else(|| ctx.turn_origin.clone()),
channel_thread: thread.or_else(|| ctx.channel_thread.clone()),
session_agent: ctx.session_agent.clone(),
diff --cc crates/openhuman-core/src/cron/bus_host_tests.rs
index 40ac96556e,a577e80956..22a3e9fb0c
--- a/crates/openhuman-core/src/cron/bus_host_tests.rs
+++ b/crates/openhuman-core/src/cron/bus_host_tests.rs
@@@ -1,9 -1,9 +1,9 @@@
-//! The callback adapter, driven the way the module drives it: over the bus, on
-//! the contract's `ScheduleHost` interface, against the real (linked) module.
-
use super::*;
+// The callback adapter, driven the way the module drives it: over the bus, on
+// the contract's `ScheduleHost` interface, against the real (linked) module.
+
use crate::cron::handlers::{
- kind_handler, register_kind, JobKindHandler, JobOutcome, JobRunContext,
+ kind_handler, register_kind, JobKindHandler, JobOutcome, JobRunContext, KIND_REGISTRY_TEST_LOCK,
};
use async_trait::async_trait;
use std::sync::atomic::{AtomicUsize, Ordering};
diff --cc crates/openhuman-core/src/cron/scheduler/run_delivery.rs
index ad99f10497,1c4aefb86d..2309ad1813
--- a/crates/openhuman-core/src/cron/scheduler/run_delivery.rs
+++ b/crates/openhuman-core/src/cron/scheduler/run_delivery.rs
@@@ -25,63 -65,48 +25,64 @@@ pub(crate) async fn send
.await
}
-/// A `flow` row standing in for a trigger whose stored row cannot be read (it
-/// was removed between the claim and the tick). The handler needs only the
-/// bound flow id, which is the row's `command`.
-fn stand_in(flow_id: &str) -> CronJob {
- let now = Utc::now();
- CronJob {
- claim_generation: 0,
- policy: JobPolicy::default(),
- id: flow_id.to_string(),
- expression: String::new(),
- schedule: Schedule::Every { every_ms: 60_000 },
- command: flow_id.to_string(),
- prompt: None,
- name: None,
- job_type: JobType::Flow,
- session_target: SessionTarget::default(),
- model: None,
- agent_id: None,
- enabled: true,
- delivery: DeliveryConfig::default(),
- delete_after_run: false,
- created_at: now,
- next_run: now,
- last_run: None,
- last_status: None,
- last_output: None,
- origin: None,
- }
+/// Project the schedule module's authoritative terminal decision and event.
+pub(crate) async fn deliver(binding: &Binding, projection: &DeliveryProjection) {
+ binding
+ .within(async {
+ let ctx = binding.dispatch_ctx();
+ binding.finish_triggered_run(&projection.run_id);
+ publish_completion(
+ &ctx,
+ &projection.job,
+ projection.success,
+ &projection.attempt.output,
+ );
+ })
+ .await;
}
-/// A stand-in `flow` row with `command`, for tests of handlers.
-#[cfg(test)]
-pub(crate) fn stand_in_for_test(command: &str) -> CronJob {
- stand_in(command)
+/// Publish the final status shared by scheduled and manual runs.
+pub(crate) fn publish_completion(
+ ctx: &crate::core::runtime::DispatchCtx,
+ job: &CronJob,
+ success: bool,
+ output: &str,
+) {
++ crate::cron::completion_owner::note(ctx, &job.id);
+ BUS.publish(DomainEvent::CronJobCompleted {
+ job_id: job.id.clone(),
+ success,
+ output: crate::util::truncate_with_ellipsis(output, 512),
+ tenant: ctx.event_tenant(),
+ });
+ BUS.publish(DomainEvent::HealthChanged {
+ component: "scheduler".to_string(),
+ healthy: success,
+ message: (!success).then(|| {
+ if output.is_empty() {
+ format!("job {} failed", job.id)
+ } else {
+ crate::util::truncate_with_ellipsis(output, 256)
+ }
+ }),
+ });
}
-/// Fire the `flow` row bound to `flow_id` through the registered `flow`
-/// handler.
-pub(crate) async fn trigger(binding: &Binding, flow_id: &str, run_id: &str) -> Attempt {
+/// Fire the captured flow definition through the registered kind handler.
+pub(crate) async fn trigger(binding: &Binding, job: &CronJob, run_id: &str) -> Attempt {
binding
.within(async {
- if let Some(refusal) = kind_refusal(binding, &JobType::Flow) {
+ binding.publish_triggered_once(job, run_id);
+ let config = binding.config();
+ if let Err(error) = crate::cron::limits::check_run(&config, job) {
+ return Attempt {
+ success: false,
+ output: error.to_string(),
+ retryable: false,
+ raw_detail: None,
+ };
+ }
+ if let Some(refusal) = kind_refusal(binding, job) {
return Attempt {
success: false,
output: refusal,
diff --cc crates/openhuman-core/src/desktop/notifications/bus.rs
index ddc48396d3,91031d62e5..3a766f6cf7
--- a/crates/openhuman-core/src/desktop/notifications/bus.rs
+++ b/crates/openhuman-core/src/desktop/notifications/bus.rs
@@@ -469,71 -469,44 +469,72 @@@ fn translate(event: &DomainEvent) -> Op
}
}
-/// The agent whose storage scope a notification raised by `event` belongs
-/// in: the owner of the cron job a `CronJobCompleted` names, when a storage
-/// backend is installed and an agent's scope holds the job; `None` (`local`)
-/// otherwise — including a job found in `local` or found nowhere.
-///
-/// # Errors
-///
-/// When no scope reported the job and a scope's lookup failed.
-async fn event_owner(
- ctx: &crate::core::runtime::DispatchCtx,
- config: &crate::config::Config,
+/// The event's captured owner. Missing ownership on older wire events stays
+/// unknown; the bridge never guesses from whichever agent is currently live.
+fn event_owner(event: &DomainEvent) -> Option<String> {
+ match event {
- DomainEvent::CronJobCompleted { tenant, .. } => {
- tenant.as_ref().and_then(|tenant| tenant.agent.clone())
- }
++ DomainEvent::CronJobCompleted { job_id, tenant, .. } => tenant
++ .as_ref()
++ .and_then(|tenant| tenant.agent.clone())
++ .or_else(|| crate::cron::completion_owner::take(job_id)),
+ _ => None,
+ }
+}
+
+/// Apply the event's agent to its resolved profile context. Agent ids are
+/// profile-local, so consulting the process-wide agent registry here can
+/// select an identically named agent from a different profile.
+fn profile_agent_dispatch(
+ dispatch: crate::core::runtime::DispatchCtx,
event: &DomainEvent,
-) -> Result<Option<String>, crate::storage::agents::LookupFailed> {
- let DomainEvent::CronJobCompleted { job_id, .. } = event else {
- return Ok(None);
+) -> Option<crate::core::runtime::DispatchCtx> {
+ let tenant = match event {
+ DomainEvent::CronJobCompleted { tenant, .. } => tenant.as_ref(),
+ _ => return Some(dispatch),
+ };
+ let Some(tenant) = tenant else {
+ return Some(dispatch);
};
- // Noted by the scheduler as the job completed — the only record of a
- // one-shot job, which is deleted before the event is published.
- if let Some(agent) = crate::cron::completion_owner::take(job_id) {
- return Ok(Some(agent));
+ if tenant.profile.is_none() {
+ return Some(dispatch);
}
- if crate::storage::installed().is_none() {
- return Ok(None);
+ let Some(agent) = event_owner(event) else {
+ return Some(dispatch);
+ };
+ let core = dispatch.core()?;
+ Some(crate::core::runtime::DispatchCtx::new(
+ core.for_agent(&agent),
+ ))
+}
+
+/// Rebuild the dispatch context captured by a cron completion. Older events
+/// without a tenant are handled only by single-tenant hosts; SaaS fails closed.
+fn event_dispatch(event: &DomainEvent) -> Option<crate::core::runtime::DispatchCtx> {
+ match event {
+ DomainEvent::CronJobCompleted { tenant, .. } => profile_agent_dispatch(
+ crate::core::runtime::DispatchCtx::for_event(tenant.as_ref())?,
+ event,
+ ),
+ _ => Some(crate::core::runtime::DispatchCtx::host_default()),
+ }
+}
+
+/// Persist cron notifications in the context reconstructed from the event.
+/// `within_agent` is intentionally not used for these events: it resolves an
+/// agent id in the process-wide registry and loses the captured profile.
+async fn persist_in_event_context(
+ dispatch: &crate::core::runtime::DispatchCtx,
+ config: &Config,
+ event: &CoreNotificationEvent,
+) -> Option<anyhow::Result<bool>> {
+ let persist = async { super::store::insert_core_notification(config, event) };
+ match dispatch.core() {
+ Some(core) => Some(
+ crate::core::runtime::CoreContext::scope(std::sync::Arc::clone(core), persist).await,
+ ),
+ None if !crate::core::runtime::is_saas() => Some(persist.await),
+ None => None,
}
- let owner = crate::storage::agents::find_owner(ctx, "notification owner", |_| async {
- match crate::cron::get_job(config, job_id) {
- Ok(_) => Ok(true),
- // tinyflows reports a missing job as `Cron job '<id>' not found`
- // (an untyped `anyhow` error in the vendored crate); match that
- // whole shape for this job rather than any message mentioning it.
- Err(error) if error.to_string() == format!("Cron job '{job_id}' not found") => {
- Ok(false)
- }
- Err(error) => Err(error.to_string()),
- }
- })
- .await?;
- Ok(owner.flatten())
}
#[async_trait]
diff --cc crates/openhuman-core/src/flows/README.md
index ecec97c5d2,fa9d15bdd1..4cd9ae59aa
--- a/crates/openhuman-core/src/flows/README.md
+++ b/crates/openhuman-core/src/flows/README.md
@@@ -178,11 -191,9 +178,11 @@@ state as part of its winning run lifecy
### Authoring and discovery agents
- Two built-in sub-agents live under `../agent/registry/agents/`, each with an
-Two built-in sub-agents live under `agents/`, each with an `agent.toml` and a
-`prompt::build`, registered by path from the `BUILTINS` slice in
++Two built-in sub-agents live under `../agent_registry/agents/`, each with an
+`agent.toml` and a synchronous `prompt::build`. Their archetype text is fetched
+from the TinyFlows Copilot bus by async host entrypoints, then supplied to the
+renderer. Both are registered by path from the `BUILTINS` slice in
- [`agent/registry/agents/loader.rs`](../agent/registry/agents/loader.rs):
+ [`agent_registry/agents/loader.rs`](../agent_registry/agents/loader.rs):
- `workflow_builder` is the authoring copilot. `flows_build` (in
[`ops/builder.rs`](./ops/builder.rs)) runs one turn of it from a structured request (create,
diff --cc crates/openhuman-core/src/flows/builder_host.rs
index 96723e8b99,7e866ec3b3..f43b240854
--- a/crates/openhuman-core/src/flows/builder_host.rs
+++ b/crates/openhuman-core/src/flows/builder_host.rs
@@@ -20,290 -31,124 +20,290 @@@ struct FlowsHost
}
impl FlowsHost {
- /// Binds the ports to `config`'s workspace.
- pub fn new(config: Arc<Config>) -> Arc<Self> {
- Arc::new(Self { config })
- }
-
- /// The context a port call runs under. The copilot ports carry none, so
- /// this is the one place the host reads the calling task's ambient scope
- /// (#7801) until the ports take a carrier.
- fn ctx(&self) -> crate::core::runtime::DispatchCtx {
- crate::core::runtime::DispatchCtx::ambient()
- }
-}
-
-#[async_trait]
-impl DraftStore for FlowsHost {
- async fn get(&self, id: &str) -> PortResult<FlowDraft> {
- ops::flows_draft_get(&self.config, id).map(|o| o.value)
+ async fn in_context<T, F>(&self, work: F) -> Result<T, String>
+ where
+ T: Send + 'static,
+ F: Future<Output = Result<T, String>> + Send + 'static,
+ {
+ let context = self.context.clone();
+ let work = async move {
+ if let Some(core) = context.core().cloned() {
+ CoreContext::scope(core, work).await
+ } else {
+ work.await
+ }
+ };
+ match &self.runtime {
+ Some(runtime) => runtime
+ .spawn(work)
+ .await
+ .map_err(|error| format!("the Copilot host callback did not finish: {error}"))?,
+ None => work.await,
+ }
}
- async fn create(
- &self,
- flow_id: Option<String>,
- name: String,
- graph: Value,
- origin: DraftOrigin,
- ) -> PortResult<FlowDraft> {
- ops::flows_draft_create(&self.config, flow_id, name, graph, origin).map(|o| o.value)
+ async fn dispatch_call_port(&self, request: copilot::PortCallRequest) -> Result<Value, String> {
+ let config = Arc::clone(&self.config);
+ let context = self.context.clone();
+ self.in_context(async move {
+ let payload = request.payload;
+ macro_rules! wire {
+ ($value:expr) => {
+ serde_json::to_value($value).map_err(|error| error.to_string())?
+ };
+ }
+ let value = match request.operation {
+ PortOperation::DraftGet => {
+ wire!(ops::flows_draft_get(&config, &required::<String>(&payload, "id")?)?.value)
+ }
+ PortOperation::DraftCreate => {
+ ops::flows_draft_create_from_copilot(
+ &config,
+ optional_field(&payload, "flow_id")?,
+ required(&payload, "name")?,
+ required(&payload, "graph")?,
+ required(&payload, "origin")?,
+ )?
+ }
+ PortOperation::DraftUpdate => {
+ wire!(ops::flows_draft_update(
+ &config,
+ &required::<String>(&payload, "id")?,
+ optional_field(&payload, "name")?,
+ optional_field(&payload, "graph")?,
+ None,
+ )?
+ .value)
+ }
+ PortOperation::FlowsGet => {
+ wire!(ops::flows_get(&config, &required::<String>(&payload, "id")?)
+ .await?
+ .value)
+ }
+ PortOperation::FlowsList => wire!(ops::flows_list(&config).await?.value),
+ PortOperation::FlowsLoadGraph => {
+ wire!(ops::load_flow_graph(&config, &required::<String>(&payload, "id")?)?)
+ }
+ PortOperation::FlowsCreate => {
+ wire!(ops::flows_create_with_context(
+ &context,
+ &config,
+ required(&payload, "name")?,
+ required(&payload, "graph")?,
+ optional_field::<bool>(&payload, "require_approval")?.unwrap_or(true),
+ )
+ .await?
+ .value)
+ }
+ PortOperation::FlowsUpdate => {
+ let outcome = ops::flows_update_with_context(
+ &context,
+ &config,
+ &required::<String>(&payload, "id")?,
+ optional_field(&payload, "name")?,
+ optional_field(&payload, "graph")?,
+ None,
+ None,
+ )
+ .await?;
+ json!({"value": outcome.value, "logs": outcome.logs})
+ }
+ PortOperation::FlowsSetEnabled => {
+ wire!(ops::flows_set_enabled(
+ &config,
+ &required::<String>(&payload, "id")?,
+ required(&payload, "enabled")?,
+ )
+ .await?
+ .value)
+ }
+ PortOperation::FlowsDuplicate => {
+ wire!(ops::flows_duplicate(&config, &required::<String>(&payload, "id")?)
+ .await?
+ .value)
+ }
+ PortOperation::FlowsHistory => wire!(ops::flows_get_history(
+ &config,
+ &required::<String>(&payload, "id")?,
+ optional_field::<usize>(&payload, "limit")?.unwrap_or(20),
+ )?
+ .value),
+ PortOperation::FlowsListRuns => wire!(ops::flows_list_runs(
+ &config,
+ &required::<String>(&payload, "flow_id")?,
+ optional_field::<usize>(&payload, "limit")?.unwrap_or(20),
+ )
+ .await?
+ .value),
+ PortOperation::FlowsGetRun => {
+ wire!(ops::flows_get_run(&config, &required::<String>(&payload, "run_id")?)
+ .await?
+ .value)
+ }
+ PortOperation::FlowsResume => {
+ wire!(ops::flows_resume(
+ &context,
+ &config,
+ &required::<String>(&payload, "flow_id")?,
+ &required::<String>(&payload, "run_id")?,
+ optional_field(&payload, "approve")?.unwrap_or_default(),
+ optional_field(&payload, "reject")?.unwrap_or_default(),
+ )
+ .await?
+ .value)
+ }
+ PortOperation::FlowsCancelRun => {
+ wire!(ops::flows_cancel_run(&config, &required::<String>(&payload, "run_id")?)
+ .await?
+ .value)
+ }
+ PortOperation::AgentsList => {
- let agents = crate::agent::registry::list_agents(&context, false)
++ let agents = crate::agent_registry::list_agents(&context, false)
+ .await
+ .map_err(|error| error.to_string())?;
+ wire!(agents
+ .iter()
+ .map(|agent| {
+ json!({
+ "id": agent.id,
+ "name": agent.name,
+ "description": agent.description,
+ "model": serde_json::to_value(&agent.model).unwrap_or(Value::Null),
+ "tools": serde_json::to_value(&agent.tool_allowlist).unwrap_or(Value::Null),
+ "tags": serde_json::to_value(&agent.tags).unwrap_or(Value::Null),
+ })
+ })
+ .collect::<Vec<_>>())
+ }
+ PortOperation::SuggestionsUpsert => {
+ json!(ops::flows_suggestions_upsert_from_copilot(
+ &config, payload
+ )?)
+ }
+ PortOperation::GatesValidate => wire!(ops::flows_validate(&context, &config, payload).await.value),
+ PortOperation::GatesRun => {
+ wire!(ops::run_builder_gates_json(&context, &config, payload).await?)
+ }
+ PortOperation::GatesStrict => {
+ ops::strict_gate(&context, &config, &payload).await?;
+ json!(true)
+ }
+ PortOperation::GatesEngineCompatibility => {
+ wire!(ops::engine_compatibility_errors_json(&context, &config, payload).await?)
+ }
+ PortOperation::GatesWiringWarnings => {
+ wire!(ops::wiring_warnings_json(&context, &config, payload).await?)
+ }
+ PortOperation::GatesApprovalManifest => {
+ wire!(ops::approval_manifest_json(&context, &config, payload).await?)
+ }
+ };
+ Ok(value)
+ })
+ .await
}
- async fn update(
+ async fn dispatch_build_proposal(
&self,
- id: &str,
- name: Option<String>,
- graph: Option<Value>,
- ) -> PortResult<FlowDraft> {
- ops::flows_draft_update(&self.config, id, name, graph, None).map(|o| o.value)
- }
-}
-
-#[async_trait]
-impl FlowStore for FlowsHost {
- async fn get(&self, id: &str) -> PortResult<Flow> {
- ops::flows_get(&self.config, id).await.map(|o| o.value)
- }
-
- async fn list(&self) -> PortResult<Vec<Flow>> {
- ops::flows_list(&self.config).await.map(|o| o.value)
- }
-
- async fn load_graph(&self, id: &str) -> PortResult<Option<WorkflowGraph>> {
- ops::load_flow_graph(&self.config, id)
- }
-
- async fn create(&self, name: String, graph: Value, require_approval: bool) -> PortResult<Flow> {
- ops::flows_create(&self.config, name, graph, require_approval)
+ request: copilot::BuildProposalRequest,
+ ) -> Result<Value, String> {
+ let config = Arc::clone(&self.config);
+ let context = self.context.clone();
+ self.in_context(async move {
+ ops::build_builder_proposal_json(
+ &context,
+ &config,
+ request.retry_tool,
+ request.name,
+ request.graph,
+ request.require_approval,
+ request.revision,
+ request.instruction,
+ request.draft_id,
+ request.flow_id,
+ )
.await
- .map(|o| o.value)
+ })
+ .await
}
- async fn update(
- &self,
- id: &str,
- name: Option<String>,
- graph: Option<Value>,
- ) -> PortResult<Written<Flow>> {
- ops::flows_update(&self.config, id, name, graph, None, None)
+ async fn dispatch_run_flow(&self, request: copilot::RunFlowRequest) -> Result<Value, String> {
+ let config = Arc::clone(&self.config);
+ let context = self.context.clone();
+ self.in_context(async move {
+ ops::flows_run_copilot(
+ &context,
+ &config,
+ &request.flow_id,
+ request.input,
+ request.inputs,
+ )
.await
- .map(|o| Written {
- value: o.value,
- logs: o.logs,
- })
+ .map(|outcome| outcome.value)
+ })
+ .await
}
- async fn set_enabled(&self, id: &str, enabled: bool) -> PortResult<Flow> {
- ops::flows_set_enabled(&self.config, id, enabled)
- .await
- .map(|o| o.value)
+ async fn preflight_tool(&self, slug: String, args: Value) -> Result<Value, String> {
+ let config = Arc::clone(&self.config);
+ self.in_context(async move {
+ preflight_mock_tool(&config, &slug, &args).await?;
+ // The module discards this acknowledgement and returns only its
+ // deterministic MockTools result. Never invoke the real backend.
+ Ok(Value::Null)
+ })
+ .await
}
+}
- async fn duplicate(&self, id: &str) -> PortResult<Flow> {
- ops::flows_duplicate(&self.config, id)
+async fn preflight_mock_tool(config: &Config, slug: &str, args: &Value) -> Result<(), String> {
+ if let Some(backend) = crate::flows::caps_host::tools::backend_for(slug) {
+ backend
+ .preflight(config, slug, args)
.await
- .map(|o| o.value)
+ .map_err(|error| error.to_string())?;
}
+ Ok(())
+}
- async fn history(&self, id: &str, limit: usize) -> PortResult<Vec<FlowRevision>> {
- ops::flows_get_history(&self.config, id, limit).map(|o| o.value)
- }
+fn required<T: DeserializeOwned>(value: &Value, key: &str) -> Result<T, String> {
+ optional_field(value, key)?.ok_or_else(|| format!("missing `{key}`"))
+}
- async fn list_runs(&self, flow_id: &str, limit: usize) -> PortResult<Vec<FlowRun>> {
- ops::flows_list_runs(&self.config, flow_id, limit)
- .await
- .map(|o| o.value)
+fn optional_field<T: DeserializeOwned>(value: &Value, key: &str) -> Result<Option<T>, String> {
+ match value.get(key) {
+ None | Some(Value::Null) => Ok(None),
+ Some(value) => serde_json::from_value(value.clone())
+ .map(Some)
+ .map_err(|error| format!("bad `{key}`: {error}")),
}
+}
- async fn get_run(&self, run_id: &str) -> PortResult<FlowRun> {
- ops::flows_get_run(&self.config, run_id)
+fn bus_error(member: &str, error: impl std::fmt::Display) -> tinybus::Error {
+ tracing::debug!(callback = member, %error, "[flows:copilot] host callback failed");
+ tinybus::Error::failed(error)
+}
+
+struct CopilotCapsHost(FlowsHost);
+
+#[tinybus::interface(name = "ai.tinyhumans.tinyflows.CopilotHost")]
+impl FlowsHost {
+ async fn call_port(&self, request: copilot::PortCallRequest) -> BusResult<Value> {
+ self.dispatch_call_port(request)
.await
- .map(|o| o.value)
+ .map_err(|error| bus_error("CallPort", error))
}
- async fn resume(
- &self,
- flow_id: &str,
- run_id: &str,
- approve: Vec<String>,
- reject: Vec<String>,
- ) -> PortResult<Value> {
- let ctx = self.ctx();
- ops::flows_resume(&ctx, &self.config, flow_id, run_id, approve, reject)
+ async fn build_proposal(&self, request: copilot::BuildProposalRequest) -> BusResult<Value> {
+ self.dispatch_build_proposal(request)
.await
- .map(|o| o.value)
+ .map_err(|error| bus_error("BuildProposal", error))
}
- async fn cancel_run(&self, run_id: &str) -> PortResult<Value> {
- ops::flows_cancel_run(&self.config, run_id)
+ async fn run_flow(&self, request: copilot::RunFlowRequest) -> BusResult<Value> {
+ self.dispatch_run_flow(request)
.await
- .map(|o| o.value)
+ .map_err(|error| bus_error("RunFlow", error))
}
}
diff --cc crates/openhuman-core/src/flows/builder_tools_reads_and_catalog_tests.rs
index 9486fd6089,779adc941f..1bbb46f0ff
--- a/crates/openhuman-core/src/flows/builder_tools_reads_and_catalog_tests.rs
+++ b/crates/openhuman-core/src/flows/builder_tools_reads_and_catalog_tests.rs
@@@ -140,11 -140,11 +140,14 @@@ async fn get_flow_run_missing_id_is_err
#[tokio::test]
async fn list_flow_connections_is_read_only() {
+ // Reaches the connector module, whose route is process-wide: hold the module
+ // lock (before TEST_ENV_LOCK, the established order) for the whole test.
+ let _module = crate::integrations::composio::module_client::module_guard().await;
let tmp = TempDir::new().unwrap();
- let tool = ListFlowConnectionsTool::new(test_config(&tmp));
+ let tool = ListFlowConnectionsTool::new(
+ test_config(&tmp),
+ Arc::new(crate::flows::builder_tools_connection_reads::FlowsConnectionProvider),
+ );
assert_eq!(tool.permission_level(), PermissionLevel::None);
assert!(!tool.external_effect());
diff --cc crates/openhuman-core/src/flows/caps_host/memory.rs
index 44fd80dbb9,ceca1d61ff..0a4c795f13
--- a/crates/openhuman-core/src/flows/caps_host/memory.rs
+++ b/crates/openhuman-core/src/flows/caps_host/memory.rs
@@@ -33,11 -33,11 +33,8 @@@
use std::sync::Arc;
-use async_trait::async_trait;
use serde_json::{json, Value};
-use tinyflows::caps::MemoryProvider;
-use tinyflows::error::{EngineError, Result};
- #[cfg(test)]
- use crate::agent::turn_origin;
- use crate::agent::turn_origin::{AgentTurnOrigin, TrustedAutomationSource};
use crate::config::Config;
use crate::flows::{
cross_flow_filter, flow_filter, flow_key_of, flow_key_tag, forget_matching, remember_keyed,
diff --cc crates/openhuman-core/src/flows/caps_host/ops_tier_gate_and_timeouts_tests.rs
index ee4d22e1d3,baa0957f33..d22727e749
--- a/crates/openhuman-core/src/flows/caps_host/ops_tier_gate_and_timeouts_tests.rs
+++ b/crates/openhuman-core/src/flows/caps_host/ops_tier_gate_and_timeouts_tests.rs
@@@ -373,13 -407,13 +382,13 @@@ fn nested_harness_does_not_escalate_wit
/// default (10). This mirrors the exact build step `run_via_harness` takes
/// before dispatching the turn (so it doesn't require a live model
/// provider to exercise).
-#[test]
-fn agent_node_runtime_resolves_to_the_definitions_effective_iteration_cap() {
+#[tokio::test]
+async fn agent_node_runtime_resolves_to_the_definitions_effective_iteration_cap() {
let tmp = tempfile::TempDir::new().unwrap();
- let config = resolver_test_config(&tmp);
+ let config = agent_test_config(&tmp);
assert_eq!(config.agent.max_tool_iterations, 10);
- crate::agent::harness::host_definition::AgentDefinitionRegistry::init_global(
+ crate::agent_registry::host_definition::AgentDefinitionRegistry::init_global(
&config.workspace_dir,
)
.expect("agent registry init");
diff --cc crates/openhuman-core/src/flows/memory_tools.rs
index ed0253644c,c2073b06a4..2b62cbcc34
--- a/crates/openhuman-core/src/flows/memory_tools.rs
+++ b/crates/openhuman-core/src/flows/memory_tools.rs
@@@ -27,15 -27,17 +27,15 @@@ use std::sync::Arc
use async_trait::async_trait;
use serde_json::json;
-use tinymemory_api::{
- Citation, ForgetTarget, LearningKind, MemoryMeta, MetaFilter, SourceKind, SourceRef,
-};
+use tinymemory_api::{Citation, LearningKind, MemoryMeta, MetaFilter, SourceKind, SourceRef};
use tinytools::{PermissionLevel, Tool, ToolResult};
- use crate::agent::turn_origin::{AgentTurnOrigin, TrustedAutomationSource};
use crate::config::Config;
-use crate::memory::types::{LearnParams, RecallParams};
-use crate::memory::{MemoryError, MemoryResult};
+use crate::memory::types::{ForgetParams, ItemsListParams, LearnParams, RecallParams, MAX_LIMIT};
use crate::security::policy::ToolOperation;
+ use crate::security::turn_origin::{AgentTurnOrigin, TrustedAutomationSource};
use crate::security::SecurityPolicy;
+use tinymemory_api::{Error, Result};
/// Prefix of a flow's own tag (see [`flow_tag`]).
pub const FLOW_TAG_PREFIX: &str = "flow:";
diff --cc crates/openhuman-core/src/flows/ops.rs
index 0b394e44be,e56bae5358..921f7f460f
--- a/crates/openhuman-core/src/flows/ops.rs
+++ b/crates/openhuman-core/src/flows/ops.rs
@@@ -34,20 -36,33 +34,29 @@@
use std::collections::HashSet;
use std::sync::{Arc, LazyLock};
-use chrono::Utc;
use serde_json::{json, Value};
-use tinyflows::authoring::validate_and_migrate_graph;
use tinyflows::model::{NodeKind, TriggerKind, WorkflowGraph};
+// Generic graph analysis used for UI notes and authoring summaries comes from
+// the TinyFlows bus. OpenHuman-specific save and dispatch policy stays here.
+ use tinyflows::triggers::graph_trigger_warnings;
+ // The save/run safety predicates are `tinyflows-catalog`'s: whether a graph
+ // fires unattended, whether it can act on the world, whether it has anything to
+ // do at all are properties of the graph, not of this host. Re-exported at
+ // `ops::` scope because the agent tools and this module's tests already name
+ // them there.
-pub(crate) use tinyflows_catalog::graph_policy::{
- enforce_side_effect_approval, graph_has_actionable_nodes, trigger_is_automatic,
-};
-use tokio_util::sync::CancellationToken;
-
use crate::config::Config;
use crate::core::Outcome;
use crate::flows::bus;
use crate::flows::draft_store;
use crate::flows::store;
+ use crate::security::approval::{ApprovalChatContext, ApprovalTurnContext, FlowRunContext};
+ use crate::security::turn_origin::{with_origin, AgentTurnOrigin, TrustedAutomationSource};
use tinyflows_catalog::build_registry;
-use tinyflows_catalog::run_registry;
-use tinyflows_catalog::types::{
- FlowConnection, FlowRunStep, FlowRunTrigger, FlowSuggestion, SuggestionStatus,
+pub(crate) use tinyflows_catalog::graph_policy::{
- enforce_side_effect_approval, trigger_is_automatic,
++ enforce_side_effect_approval, graph_has_actionable_nodes, trigger_is_automatic,
};
+use tinyflows_catalog::types::{FlowConnection, FlowRunTrigger, FlowSuggestion, SuggestionStatus};
++use tokio_util::sync::CancellationToken;
use {tinyflows_catalog::Flow, tinyflows_catalog::FlowRun};
/// Overall safety bound on a single `flows_run` / `flows_resume`. Individual
diff --cc crates/openhuman-core/src/flows/ops/execution.rs
index 5e8d1a5212,1d73c60368..9b7b843f12
--- a/crates/openhuman-core/src/flows/ops/execution.rs
+++ b/crates/openhuman-core/src/flows/ops/execution.rs
@@@ -15,12 -20,44 +15,12 @@@ pub(crate) async fn export_run_to_langf
config: &Config,
flow_name: &str,
flow_id: &str,
- thread_id: &str,
+ run_id: &str,
status: &str,
trigger: FlowRunTrigger,
- journal: &tinyflows::engine::InMemoryGraphEventJournal,
- graph_run_id: &str,
+ observations: &[GraphObservation],
) {
- crate::agent::progress_tracing::export_graph_run_trace(
- if !config.observability.share_usage_data {
- tracing::debug!(
- target: "flows",
- flow_id = %flow_id,
- "[flows] langfuse export skipped: observability.share_usage_data is off"
- );
- return;
- }
- use tinyflows::engine::GraphEventJournal as _;
- let observations = match journal.read_from(graph_run_id, 0).await {
- Ok(observations) => observations,
- Err(e) => {
- tracing::warn!(
- target: "flows",
- flow_id = %flow_id,
- %thread_id,
- graph_run_id = %graph_run_id,
- error = %e,
- "[flows] langfuse export skipped: could not read run journal"
- );
- return;
- }
- };
- tracing::debug!(
- target: "flows",
- flow_id = %flow_id,
- %thread_id,
- graph_run_id = %graph_run_id,
- observation_count = observations.len(),
- "[flows] exporting flow run trace to Langfuse"
- );
+ crate::flows::tinyflows::langfuse_export::export_flow_run_trace(
config,
flow_name,
flow_id,
diff --cc crates/openhuman-core/src/flows/ops_agent_binding_tests.rs
index ae92ea85b5,3547fce555..900771faaa
--- a/crates/openhuman-core/src/flows/ops_agent_binding_tests.rs
+++ b/crates/openhuman-core/src/flows/ops_agent_binding_tests.rs
@@@ -386,3 -490,64 +386,64 @@@ async fn harness_readiness_checks_sessi
}
}
}
+
+ /// The agent-ref gate resolves a custom agent through the context it is handed,
+ /// not the one the calling task happens to run under: two tenants' registries
+ /// never cross.
+ #[tokio::test]
+ async fn agent_ref_gate_reads_the_registry_of_the_explicit_context() {
+ use crate::agent_registry::types::{AgentRegistryEntry, AgentRegistrySource};
+ use crate::core::runtime::{CoreContext, DispatchCtx, DomainSet};
+
+ let entry = AgentRegistryEntry {
+ id: "tenant_a_only_agent".to_string(),
+ name: "A".to_string(),
+ description: "registered for tenant A".to_string(),
+ source: AgentRegistrySource::Custom,
+ enabled: true,
+ model: None,
+ system_prompt: None,
+ tool_allowlist: Vec::new(),
+ tool_denylist: Vec::new(),
+ tool_rules: None,
+ subagents: Default::default(),
+ tags: Vec::new(),
+ metadata: Value::Null,
+ };
+ let tmp_a = TempDir::new().unwrap();
+ let tmp_b = TempDir::new().unwrap();
+ let mut config_a = test_config(&tmp_a);
+ config_a.agent_registry.entries.push(entry);
+ let config_b = test_config(&tmp_b);
+ let core_a = CoreContext::for_test_with_config(DomainSet::full(), config_a.clone());
+ let core_b = CoreContext::for_test_with_config(DomainSet::full(), config_b.clone());
+ let ctx_a = DispatchCtx::new(core_a);
+ let ctx_b = DispatchCtx::new(std::sync::Arc::clone(&core_b));
+
+ let g = graph(json!({
+ "nodes": [
+ { "id": "t", "kind": "trigger", "name": "Manual" },
+ { "id": "a", "kind": "agent", "name": "Plan",
+ "config": { "agent_ref": "tenant_a_only_agent", "prompt": "go" } }
+ ],
+ "edges": [ { "from_node": "t", "to_node": "a" } ]
+ }));
+
+ // Both calls run scoped to tenant B, so an ambient read would answer B's
+ // registry for A's call.
+ let (for_a, for_b) = CoreContext::scope(core_b, async {
+ (
- validate_agent_refs(&ctx_a, &config_a, &g).await,
- validate_agent_refs(&ctx_b, &config_b, &g).await,
++ crate::flows::host_gates::validate_agent_refs(&ctx_a, &config_a, &g).await,
++ crate::flows::host_gates::validate_agent_refs(&ctx_b, &config_b, &g).await,
+ )
+ })
+ .await;
+ assert!(
+ for_a.is_empty(),
+ "tenant A's own agent must resolve: {for_a:?}"
+ );
+ assert!(
+ for_b.iter().any(|e| e.contains("tenant_a_only_agent")),
+ "tenant B must not see tenant A's agent: {for_b:?}"
+ );
+ }
diff --cc crates/openhuman-core/src/flows/ops_run_status_and_prompt_binding_tests.rs
index fa840faf14,394e273998..a1a910132c
--- a/crates/openhuman-core/src/flows/ops_run_status_and_prompt_binding_tests.rs
+++ b/crates/openhuman-core/src/flows/ops_run_status_and_prompt_binding_tests.rs
@@@ -283,56 -261,12 +283,56 @@@ async fn flows_build_copilot_toolset_un
.expect("build workflow_builder agent");
agent.set_agent_definition_name("workflow_builder".to_string());
+ #[derive(Clone, Default)]
+ struct Capture(std::sync::Arc<std::sync::Mutex<Vec<u8>>>);
+
+ impl std::io::Write for Capture {
+ fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
+ self.0.lock().unwrap().extend_from_slice(bytes);
+ Ok(bytes.len())
+ }
+
+ fn flush(&mut self) -> std::io::Result<()> {
+ Ok(())
+ }
+ }
+
+ impl<'a> tracing_subscriber::fmt::MakeWriter<'a> for Capture {
+ type Writer = Self;
+
+ fn make_writer(&'a self) -> Self::Writer {
+ self.clone()
+ }
+ }
+
+ let capture = Capture::default();
+ let subscriber = tracing_subscriber::fmt()
+ .with_writer(capture.clone())
+ .with_ansi(false)
+ .finish();
+ let _subscriber_guard = tracing::subscriber::set_default(subscriber);
+
restrict_builder_toolset_for_copilot(&mut agent);
+ let log = String::from_utf8(capture.0.lock().unwrap().clone()).unwrap();
+ assert!(
+ log.contains("cancel_flow_run"),
+ "trace should name the hidden tool: {log}"
+ );
+ assert!(
+ log.contains("run_flow/resume_flow_run stay visible")
+ && log.contains("cancel_flow_run and the unrelated legacy run_workflow are hidden"),
+ "trace should describe the actual builder tool visibility: {log}"
+ );
+ assert!(
+ !log.contains("run_flow/resume_flow_run/cancel_flow_run stay visible"),
+ "trace contradicts the actual hidden toolset: {log}"
+ );
+
- let visible = agent.visible_tool_names_for_test();
+ let visible = agent.visible_tool_specs_arc();
for still_reachable in ["run_flow", "resume_flow_run"] {
assert!(
- visible.contains(still_reachable),
+ visible.iter().any(|spec| spec.name == still_reachable),
"`{still_reachable}` must stay reachable on the streaming copilot path — it \
is gated behind the WebChat approval surface, not hidden; visible = {visible:?}"
);
diff --cc crates/openhuman-core/src/flows/runs_adapter/projection.rs
index d84974e6dc,0000000000..8fbc632056
mode 100644,000000..100644
--- a/crates/openhuman-core/src/flows/runs_adapter/projection.rs
+++ b/crates/openhuman-core/src/flows/runs_adapter/projection.rs
@@@ -1,175 -1,0 +1,179 @@@
+//! Project module-owned PollRun events onto OpenHuman events and Langfuse.
+
+use std::collections::{HashSet, VecDeque};
+use std::sync::{LazyLock, Mutex};
+
+use serde_json::Value;
+use tinyflows_bus::runs::{self, RunEvent};
+use tinyflows_catalog::types::FlowRunTrigger;
+
+use crate::core::events::DomainEvent;
+use crate::flows::runs_adapter::session::RunSession;
+use crate::flows::runs_adapter::RunKey;
+
+const RECENT_FINISHED_KEYS: usize = 4_096;
+
+static FINISHED_KEYS: LazyLock<Mutex<(HashSet<RunKey>, VecDeque<RunKey>)>> =
+ LazyLock::new(|| Mutex::new((HashSet::new(), VecDeque::new())));
+
+pub(super) async fn project(session: &RunSession, event: &RunEvent) {
+ match event.kind.as_str() {
+ "started" => {
+ if session.mark_started() {
+ crate::core::bus::BUS.publish(DomainEvent::FlowRunStarted {
+ flow_id: session.flow_id().to_owned(),
+ run_id: session.run_id.clone(),
+ });
+ }
+ }
+ "resumed" => {
+ session.set_trigger(FlowRunTrigger::Resume);
+ session.mark_resumed();
+ }
+ "step_started" => {
+ if let Some(node_id) = event.data.get("node_id").and_then(Value::as_str) {
+ publish_step(session, node_id, "running");
+ }
+ }
+ "step" => {
+ if let (Some(node_id), Some(status)) = (
+ event.data.get("node_id").and_then(Value::as_str),
+ event.data.get("status").and_then(Value::as_str),
+ ) {
+ publish_step(session, node_id, status);
+ }
+ }
+ "graph_observation" => {
+ match serde_json::from_value::<tinyagents_graph::GraphObservation>(event.data.clone()) {
+ Ok(observation) => session.add_observation(observation),
+ Err(_) => tracing::warn!(
+ target: "flows",
+ run_id = %session.run_id,
+ "[flows] PollRun graph observation could not be decoded for Langfuse"
+ ),
+ }
+ }
+ "agent_progress" => {
+ // Detailed agent events remain on the module stream. The OpenHuman
+ // workflow overlay consumes the node-level progress events above.
+ }
+ "parked" => {
+ session.mark_parked();
+ let parked = match serde_json::from_value::<runs::RunParked>(event.data.clone()) {
+ Ok(parked) => parked,
+ Err(_) => {
+ tracing::warn!(
+ target: "flows",
+ run_id = %session.run_id,
+ "[flows] PollRun parked outcome could not be decoded"
+ );
+ return;
+ }
+ };
+ let flow = session.flow().await;
+ crate::flows::ops::notify_pending_approval(
+ &flow,
+ &session.run_id,
+ &parked.pending_approvals,
+ );
+ export_segment(session, "pending_approval").await;
+ }
+ "finished" => {
+ let finished = match serde_json::from_value::<runs::RunFinished>(event.data.clone()) {
+ Ok(finished) => finished,
+ Err(_) => {
+ tracing::warn!(
+ target: "flows",
+ run_id = %session.run_id,
+ "[flows] PollRun terminal outcome could not be decoded"
+ );
+ return;
+ }
+ };
+ if claim_finished(session.key()) {
+ crate::core::bus::BUS.publish(DomainEvent::FlowRunFinished {
+ flow_id: session.flow_id().to_owned(),
+ run_id: session.run_id.clone(),
+ status: finished.status.clone(),
+ });
+ export_segment(session, &finished.status).await;
+ }
+ session.mark_finished();
+ }
+ _ => {}
+ }
+}
+
+/// Project a recovery event when the run no longer has an in-process session.
+/// This path publishes only the newly committed terminal event; historical
+/// start/progress events are not replayed after a process restart.
+pub(crate) fn project_recovered_finished(
+ key: &RunKey,
+ flow_id: &str,
+ run_id: &str,
+ event: &RunEvent,
+) {
+ let Ok(finished) = serde_json::from_value::<runs::RunFinished>(event.data.clone()) else {
+ tracing::warn!(target: "flows", run_id, "[flows] recovery PollRun terminal outcome could not be decoded");
+ return;
+ };
+ if claim_finished(key.clone()) {
+ crate::core::bus::BUS.publish(DomainEvent::FlowRunFinished {
+ flow_id: flow_id.to_owned(),
+ run_id: run_id.to_owned(),
+ status: finished.status,
+ });
+ }
+}
+
+fn claim_finished(key: RunKey) -> bool {
+ let mut finished = FINISHED_KEYS
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
+ if !finished.0.insert(key.clone()) {
+ return false;
+ }
+ finished.1.push_back(key);
+ while finished.1.len() > RECENT_FINISHED_KEYS {
+ if let Some(expired) = finished.1.pop_front() {
+ finished.0.remove(&expired);
+ }
+ }
+ true
+}
+
+fn publish_step(session: &RunSession, node_id: &str, status: &str) {
+ crate::core::bus::BUS.publish(DomainEvent::FlowRunProgress {
+ run_id: session.run_id.clone(),
+ node_id: node_id.to_owned(),
+ status: status.to_owned(),
+ });
+}
+
+async fn export_segment(session: &RunSession, status: &str) {
+ let observations = session.take_observations();
+ let flow = session.flow().await;
+ crate::flows::ops::export_run_to_langfuse(
+ &session.config,
+ &flow.name,
+ &flow.id,
+ &session.run_id,
+ status,
+ bus_trigger(session.trigger()),
+ &observations,
+ )
+ .await;
+}
+
+fn bus_trigger(trigger: FlowRunTrigger) -> runs::FlowRunTrigger {
+ match trigger {
+ FlowRunTrigger::Rpc => runs::FlowRunTrigger::Rpc,
+ FlowRunTrigger::Schedule => runs::FlowRunTrigger::Schedule,
+ FlowRunTrigger::AppEvent => runs::FlowRunTrigger::AppEvent,
+ FlowRunTrigger::Resume => runs::FlowRunTrigger::Resume,
+ }
+}
++
++#[cfg(test)]
++#[path = "projection_tests.rs"]
++mod tests;
diff --cc crates/openhuman-core/src/flows/runs_adapter/projection_tests.rs
index 0000000000,0000000000..7ca278fe35
new file mode 100644
--- /dev/null
+++ b/crates/openhuman-core/src/flows/runs_adapter/projection_tests.rs
@@@ -1,0 -1,0 +1,14 @@@
++use super::*;
++
++#[test]
++fn catalog_flow_triggers_map_to_the_serde_bus_contract() {
++ let cases = [
++ (FlowRunTrigger::Rpc, runs::FlowRunTrigger::Rpc),
++ (FlowRunTrigger::Schedule, runs::FlowRunTrigger::Schedule),
++ (FlowRunTrigger::AppEvent, runs::FlowRunTrigger::AppEvent),
++ (FlowRunTrigger::Resume, runs::FlowRunTrigger::Resume),
++ ];
++ for (catalog, bus) in cases {
++ assert_eq!(bus_trigger(catalog), bus);
++ }
++}
diff --cc crates/openhuman-core/src/flows/tinyflows/README.md
index 09fba2b285,c5ad4acdbd..ffbf198063
--- a/crates/openhuman-core/src/flows/tinyflows/README.md
+++ b/crates/openhuman-core/src/flows/tinyflows/README.md
@@@ -1,11 -1,115 +1,16 @@@
-# tinyflows capability seam
-
-Wires the vendored `tinyflows` workflow engine (validate → compile → run over
-its own in-crate state-graph runtime, [`vendor/tinyflows/`](../../../../../vendor/tinyflows/)) to real OpenHuman
-services. `tinyflows` knows nothing about OpenHuman. Every effect a flow node
-can have (calling an LLM, running an agent, making an HTTP request, running
-code, calling a tool, reading/writing state, resolving a sub-workflow,
-recalling/writing memory) is a trait the engine declares and this module
-implements. See
-[`docs/gitbooks/en/developing/architecture/flows-on-tinyagents.md`](../../../../../docs/gitbooks/en/developing/architecture/flows-on-tinyagents.md)
-for the engine's own model (trigger model, run state shape, the two-gate
-security model); this README covers only the host seam.
-
-## Layout
-
-- [`mod.rs`](./mod.rs): export-focused. Re-exports `caps::build_capabilities` and
- `caps::open_flow_checkpointer`, the two entry points `flows::ops*.rs`
- calls to drive a run. The checkpointer is `tinyflows_drivers::DriverCheckpointer`
- on the flow catalog's storage; the `checkpoints.db` tinyflows used to write is
- imported once.
-- `caps/`: every capability adapter except `memory`, plus construction,
- curation, preflight, and invocation logic. `build_capabilities` also fills
- `tasks` with the engine's own `TokioTaskRunner` and deliberately leaves
- `shell` and `approvals` as `None` (no host shell adapter yet; approvals
- reuse the engine's pause/`flows_resume` fallback).
- - `ops.rs`: `build_capabilities` (assembles the `Capabilities` bundle for
- one run), `open_flow_checkpointer` (a `DriverCheckpointer` on the flow
- catalog's storage), Composio curation/preflight
- (`is_curated_flow_tool`, `preflight_composio_args`), and the
- `OpenHumanTools` / `PreflightToolInvoker` tool-call adapters.
- - `agent.rs`: `OpenHumanAgentRunner` (`AgentRunner`): resolves an `agent`
- node's trusted `agent_ref` and routes it to a full harness turn
- (`Agent::run_single`, a nested tinyagents graph) when a harness
- `AgentDefinition` exists, or to a persona-shaped `OpenHumanLlm::complete`
- when only a custom registry entry does. Also owns the timeout clamp and
- its scaling against the definition's iteration cap.
- - `llm.rs`: `OpenHumanLlm` (`LlmProvider`) over OpenHuman's inference
- stack; what an `agent` node falls back to without an agent runner, and
- what a raw completion node uses directly.
- - `prompt.rs`: message assembly, the `input_context` carrier and its size
- cap, and tolerant JSON extraction for structured-output nodes.
- - `http.rs`: `OpenHumanHttp` (`HttpClient`); inherits the allowlist and
- DNS-rebind protection of the underlying `HttpRequestTool` and adds
- `http_cred:<name>` credential resolution, injected after the approval
- gate computes its redacted summary so the secret never reaches the UI,
- graph, output, or logs.
- - `code.rs`: `OpenHumanCode` (`CodeRunner`); runs JS/Python through
- `sandbox::execute_in_sandbox` under `CODE_RUN_TIMEOUT_SECS`.
- - `StateStore` is `FlowState` (`state.rs`, `FlowStateDocuments`), namespaced per flow (`"flow:<id>"`) so saved flows never
- collide on a state key.
- - `resolver.rs`: `OpenHumanWorkflowResolver` (`WorkflowResolver`);
- resolves a `sub_workflow` node's id to a stored workflow.
- - `tier.rs`: `enforce_node_tier_gate` / `gate_call_for_tier`: the
- autonomy-tier and approval gate every acting node (tool call, HTTP
- request, code run, memory read/write) passes through first.
- - `tools/`: `tool_call` node dispatch, split by slug namespace:
- `native.rs` for the `oh:` prefix (native OpenHuman tools, same registry
- the assistant uses), `composio.rs` for everything else (Composio
- actions; must stay the catch-all backend since Composio slugs carry no
- prefix).
-- [`memory_adapter.rs`](./memory_adapter.rs): `OpenHumanMemory`, the `MemoryProvider` adapter for
- the `memory` node. Routes every operation through the same `tier.rs` gate
- pair as the other acting adapters (`CommandClass::Read` for
- `recall`/`search`/`flavour`/`people`, `CommandClass::Write` for
- `remember`/`forget`); `remember`/`forget` hard-refuse any scope other than
- `"flow"`. Scopes are memory v2 tag filters: `user` reads everything,
- `flow` reads the run's own `flow:<id>` items, `flows` reads every flow's
- items (tag `flows`), the same tags the `flow_memory_*` agent tools use.
- `recall` returns the engine's answer plus citations, `search` raw hits;
- `flavour` and `people` are unsupported in v2 (unknown slug / empty
- listing).
-- [`observability.rs`](./observability.rs): `tinyflows::observability::RunObserver` impls:
- `FlowRunObserver`, which persists live
- steps via `flows::upsert_flow_run_step` and publishes
- `DomainEvent::FlowRunProgress` twice per non-trigger node so the frontend
- can render a run live.
-- [`langfuse_export.rs`](./langfuse_export.rs): after a run settles, exports its durable
- `GraphObservation` slice as one Langfuse trace via `tinyagents`'
- `GraphLangfuseExporter`, tagged with the Langfuse Agent Graph view keys.
-
-## Security model
-
-The contract is spelled out in
-[flows-on-tinyagents.md § The security model: two gates](../../../../../docs/gitbooks/en/developing/architecture/flows-on-tinyagents.md#the-security-model-two-gates);
-this module holds the outer gate. `tier.rs` consults the user's autonomy
-tier for each acting node's `CommandClass` and forces an `ApprovalGate`
-round-trip on `Prompt`, even when the saved flow's own `require_approval` is
-false. Composio `tool_call` nodes additionally pass [`caps/ops.rs`](./caps/ops.rs)'s
-deny-by-default curation check (`is_curated_flow_tool`), stricter than the
-agent loop's because a flow author's slug is free-form and never round-trips
-through live tool discovery; `tools/composio.rs` documents why the tier gate
-must run before curation. The inner gate (the agent definition's `ToolScope`
-and sandbox) applies to the nested harness turn `agent.rs` starts, with no
-new origin wrapper.
-
-## Used by
-
-`crates/openhuman-core/src/flows/ops*.rs` calls `build_capabilities` and
-`open_flow_checkpointer` to run or resume a flow, and
-`langfuse_export::export_flow_run_trace` once a run settles.
-
-## Tests
-
-[`tinyflows_tests.rs`](./tinyflows_tests.rs) (capability-seam smoke tests against the real engine;
-note the real `HttpRequestTool` blocks loopback, so HTTP coverage asserts the
-SSRF/allowlist rejections rather than a mock round-trip),
-[`memory_adapter_tests.rs`](./memory_adapter_tests.rs) (the `memory` node adapter against an in-memory
-reference engine), plus a `<module>_tests.rs` file beside most modules
-above.
-
-## Further reading
-
-- [Parent module README](../README.md)
-- [Workflows](../../../../../docs/gitbooks/en/features/workflows.md)
-- [tinyflows](../../../../../vendor/tinyflows/README.md)
+# TinyFlows graph vocabulary
+
+`mod.rs` keeps a small compatibility namespace for the generic graph model and
+legacy graph migration used by OpenHuman's authoring, validation, and Catalog
+adapters.
+
+Execution is owned by the compiled TinyFlows module and accessed through its
+TinyBus contracts. OpenHuman must not call TinyFlows compiler, engine,
+capability, checkpoint, run-row, or observer implementations directly. The
+host-side code in `flows/` is limited to contract adapters and OpenHuman policy
+callbacks.
++
++The host projects `runs::PollRun` event pages in `runs_adapter/`. Flow trace
++metadata and Langfuse transport live in `langfuse_export.rs`; generic graph
++observation projection and OTLP request building live in
++`core::observability::progress_tracing`.
diff --cc crates/openhuman-core/src/flows/tinyflows/langfuse_export.rs
index 0000000000,33c3c0e9c1..88389f6e96
mode 000000,100644..100644
--- a/crates/openhuman-core/src/flows/tinyflows/langfuse_export.rs
+++ b/crates/openhuman-core/src/flows/tinyflows/langfuse_export.rs
@@@ -1,0 -1,282 +1,270 @@@
+ //! Langfuse export for `flows::` graph runs.
+ //!
+ //! After a `flows_run` / `flows_resume` settles, the `flows::` domain hands
+ //! this module the run's durable [`GraphObservation`] slice (captured by the
+ //! per-run in-memory journal that `tinyflows`' journaled entry points fill)
+ //! and it exports the run as one Langfuse trace via the backend's Langfuse
+ //! OTLP proxy route (Langfuse v4; the legacy batch ingestion path is not used
+ //! for traces).
+ //!
+ //! The trace is built by `tinyagents`' [`GraphLangfuseExporter`], which turns
+ //! each superstep and node into a timed span and stamps the Langfuse **Agent
+ //! Graph view** keys (`langgraph_node` / `langgraph_step`) on node spans, so
+ //! the Langfuse UI can render the flow run as a graph, then projects it to
+ //! v4 OTLP: trace name, session, tags, release and flow metadata ride on every
+ //! span, since v4 filters observations directly. A host span-metadata
+ //! injector additionally stamps `flow_id` on every span for filtering.
+ //!
+ //! Transport mirrors the agent-turn tracing path
+ //! (`core::observability::progress_tracing::otlp::push_spans`): the endpoint is derived
+ //! from the **current backend hostname** (`effective_backend_api_url`), auth
+ //! is the live OpenHuman session bearer (the backend injects the real
+ //! Langfuse keys server-side, stamps the authenticated user on every span and
+ //! adds `x-langfuse-ingestion-version: 4`), the send is capped at 10s, a
+ //! partial OTLP rejection counts as a failure, and every failure is logged and
+ //! swallowed — exporting is best-effort and never fails the run. Gated on
+ //! `observability.share_usage_data`.
+
+ use std::time::Duration;
+
+ use serde_json::{json, Map, Value};
+ use tinyagents_graph::{GraphLangfuseExporter, GraphObservation};
+ use tinyagents_harness::{LangfuseAuth, LangfuseClient, LangfuseTraceConfig};
-use tinyflows::engine::GraphObservation as FlowObservation;
-use tinyflows::observe::to_exporter_observations;
++use tinyflows_bus::runs::FlowRunTrigger;
+
+ use crate::config::Config;
+ use crate::security::credentials::session_support::direct_backend_credential;
-use tinyflows_catalog::FlowRunTrigger;
+
+ const LOG_TARGET: &str = "flows::langfuse";
+ /// Backend proxy route for legacy Langfuse ingestion (relative to the backend
+ /// origin). Only the client's base: [`LangfuseClient::otlp_endpoint`] derives
+ /// the OTLP route beside it, which is
+ /// where flow traces go. The backend authenticates the session JWT, injects
+ /// the Langfuse project keys, and forwards to Langfuse's
+ /// `/api/public/otel/v1/traces`.
+ /// Cap the push so a slow/hung Langfuse never stalls run teardown (same
+ /// posture as the agent-turn exporter).
+ const PUSH_TIMEOUT: Duration = Duration::from_secs(10);
+
++fn trigger_name(trigger: FlowRunTrigger) -> &'static str {
++ match trigger {
++ FlowRunTrigger::Rpc => "rpc",
++ FlowRunTrigger::Schedule => "schedule",
++ FlowRunTrigger::AppEvent => "app_event",
++ FlowRunTrigger::Resume => "resume",
++ }
++}
++
+ /// Resolve the Langfuse ingestion URL from the current backend host — the
+ /// exact base-server resolution every other backend call uses, so the host
+ /// always matches wherever the app's domain calls go (staging, prod, or a
+ /// custom `api_url` override).
+ fn ingestion_url(config: &Config) -> String {
+ // Empty without a resolved ingestion URL; callers treat a non-`http` URL
+ // as "proxy unavailable" and skip the push.
+ config
+ .resolved_endpoints
+ .tracing_ingest_url
+ .clone()
+ .unwrap_or_default()
+ }
+
+ /// The OpenHuman core crate version (e.g. `0.58.0`), stamped onto every flow
+ /// trace as the Langfuse `release` field plus an `app_version` metadata key so
+ /// traces can be correlated with the app build that produced them.
+ const APP_VERSION: &str = env!("CARGO_PKG_VERSION");
+
+ /// Builds the [`LangfuseTraceConfig`] for one flow run: the trace id is the
+ /// run's `thread_id` (`flow:{flow_id}:{uuid}`), while the session id is the
+ /// stable `flow:{flow_id}` so repeated runs group together. The trace
+ /// is named `flow.run:{flow_name}`, run-type tags (`run:flow` +
+ /// `trigger:<kind>`) mark how the run started, and flow coordinates plus the
+ /// app version ride on the trace metadata. No content — ids, name, status,
+ /// trigger, and version only.
+ fn build_flow_trace_config(
+ flow_name: &str,
+ flow_id: &str,
+ thread_id: &str,
+ status: &str,
+ trigger: FlowRunTrigger,
+ ) -> LangfuseTraceConfig {
++ let trigger = trigger_name(trigger);
+ LangfuseTraceConfig {
+ trace_id: Some(thread_id.to_string()),
+ name: Some(format!("flow.run:{flow_name}")),
+ session_id: Some(format!("flow:{flow_id}")),
+ release: Some(APP_VERSION.to_string()),
- tags: vec![
- "run:flow".to_string(),
- format!("trigger:{}", trigger.as_str()),
- ],
++ tags: vec!["run:flow".to_string(), format!("trigger:{trigger}")],
+ metadata: json!({
+ "flow_id": flow_id,
+ "status": status,
+ "source": "flows",
+ "run_type": "flow",
- "trigger": trigger.as_str(),
++ "trigger": trigger,
+ "app_version": APP_VERSION,
+ }),
+ ..Default::default()
+ }
+ }
+
+ /// Builds the graph exporter for a flow run: the batch builder plus a host
+ /// span-metadata injector that stamps `flow_id` on every span (node spans
+ /// already carry `langgraph_node`/`langgraph_step` from `tinyagents`).
+ fn build_flow_exporter(client: LangfuseClient, flow_id: &str) -> GraphLangfuseExporter {
+ let flow_id = flow_id.to_string();
+ GraphLangfuseExporter::new(client).with_span_metadata_fn(move |_obs| {
+ let mut extra = Map::new();
+ extra.insert("flow_id".to_string(), json!(flow_id));
+ Some(extra)
+ })
+ }
+
+ /// The Langfuse v4 OTLP requests for one flow run, under the product's
+ /// `service.name` (the same one agent-turn traces use).
+ fn flow_otlp_requests(
+ exporter: &GraphLangfuseExporter,
+ trace: LangfuseTraceConfig,
+ observations: &[GraphObservation],
+ ) -> tinyagents_harness::error::Result<Vec<Value>> {
- exporter.build_otlp_requests(trace, observations, flow_service_name())
-}
-
-/// The OTLP `service.name` for flow traces.
-fn flow_service_name() -> &'static str {
- crate::core::observability::progress_tracing::export_brand().product
++ crate::core::observability::progress_tracing::build_graph_otlp_requests(
++ exporter,
++ trace,
++ observations,
++ )
+ }
+
+ /// Exports one settled flow run to Langfuse as a single trace. Best-effort:
+ /// every failure path logs a `[flows]`-prefixed warning and returns — a
+ /// Langfuse outage can never fail or delay-fail the run. No-op when
+ /// `observability.share_usage_data` is off or there is nothing to send.
+ pub async fn export_flow_run_trace(
+ config: &Config,
+ flow_name: &str,
+ flow_id: &str,
+ thread_id: &str,
+ status: &str,
+ trigger: FlowRunTrigger,
- journal_observations: &[FlowObservation],
++ observations: &[GraphObservation],
+ ) {
+ if !config.observability.share_usage_data {
+ tracing::debug!(
+ target: LOG_TARGET,
+ flow_id = %flow_id,
+ "[flows] langfuse export skipped: observability.share_usage_data is off"
+ );
+ return;
+ }
- if journal_observations.is_empty() {
++ if observations.is_empty() {
+ tracing::debug!(
+ target: LOG_TARGET,
+ flow_id = %flow_id,
+ thread_id = %thread_id,
+ "[flows] langfuse export skipped: run journal is empty"
+ );
+ return;
+ }
+
+ let url = ingestion_url(config);
+ if !url.starts_with("http") {
+ tracing::warn!(
+ target: LOG_TARGET,
+ flow_id = %flow_id,
+ "[flows] langfuse export skipped: could not resolve ingestion URL from backend host (got {url:?})"
+ );
+ return;
+ }
+ // No TinyHumans connection, or no usable credential (signed out, offline
+ // local session): a configured state — `direct_backend_credential` logs
+ // the reason at debug, and the export is skipped without a request.
+ let token = match direct_backend_credential(config, "flows langfuse export") {
+ Some(crate::security::credentials::session_support::BackendCredential::Session(token)) => {
+ token
+ }
+ _ => {
+ tracing::debug!(
+ target: LOG_TARGET,
+ flow_id = %flow_id,
+ "[flows] langfuse export skipped: hosted backend not available"
+ );
+ return;
+ }
+ };
+ let client = match LangfuseClient::new(url.clone(), LangfuseAuth::Bearer { token }) {
+ Ok(client) => client,
+ Err(err) => {
+ tracing::warn!(
+ target: LOG_TARGET,
+ flow_id = %flow_id,
+ error = %err,
+ "[flows] langfuse export skipped: could not build client for {url}"
+ );
+ return;
+ }
+ };
+
- let observations = to_exporter_observations::<GraphObservation>(journal_observations);
- if observations.is_empty() {
- tracing::warn!(
- target: LOG_TARGET,
- flow_id = %flow_id,
- thread_id = %thread_id,
- "[flows] langfuse export skipped: no observation survived re-typing"
- );
- return;
- }
-
+ let exporter = build_flow_exporter(client, flow_id);
+ let trace = build_flow_trace_config(flow_name, flow_id, thread_id, status, trigger);
+ let observation_count = observations.len();
+ tracing::debug!(
+ target: LOG_TARGET,
+ flow_id = %flow_id,
+ thread_id = %thread_id,
+ status = %status,
- trigger = %trigger.as_str(),
++ trigger = %trigger_name(trigger),
+ observation_count,
+ endpoint = %exporter.client().otlp_endpoint(),
+ "[flows] pushing flow run trace to Langfuse"
+ );
+
- let requests = match flow_otlp_requests(&exporter, trace, &observations) {
++ let requests = match flow_otlp_requests(&exporter, trace, observations) {
+ Ok(requests) => requests,
+ Err(err) => {
+ tracing::warn!(
+ target: LOG_TARGET,
+ flow_id = %flow_id,
+ thread_id = %thread_id,
+ error = %err,
+ "[flows] langfuse export skipped: could not build OTLP requests"
+ );
+ return;
+ }
+ };
- let request_count = requests.len();
- // `send_otlp` fails on a partial OTLP rejection; the outer timeout caps
- // the whole export the same way the agent exporter does.
- let send = async {
- for request in requests {
- exporter.client().send_otlp(request).await?;
- }
- Ok::<(), tinyagents_harness::TinyAgentsError>(())
- };
++ // The core observability owner performs the generic graph projection and
++ // authenticated sends; this adapter supplies flow-specific trace metadata.
++ let send =
++ crate::core::observability::progress_tracing::send_graph_otlp_requests(&exporter, requests);
+ match tokio::time::timeout(PUSH_TIMEOUT, send).await {
- Ok(Ok(_)) => {
++ Ok(Ok(request_count)) => {
+ tracing::debug!(
+ target: LOG_TARGET,
+ flow_id = %flow_id,
+ thread_id = %thread_id,
+ observation_count,
+ request_count,
+ "[flows] pushed flow run trace to Langfuse"
+ );
+ }
+ Ok(Err(err)) => {
+ tracing::warn!(
+ target: LOG_TARGET,
+ flow_id = %flow_id,
+ thread_id = %thread_id,
+ error = %err,
+ "[flows] langfuse export failed (run unaffected)"
+ );
+ }
+ Err(_elapsed) => {
+ tracing::warn!(
+ target: LOG_TARGET,
+ flow_id = %flow_id,
+ thread_id = %thread_id,
+ timeout_secs = PUSH_TIMEOUT.as_secs(),
+ "[flows] langfuse export timed out (run unaffected)"
+ );
+ }
+ }
+ }
+
+ #[cfg(test)]
+ #[path = "langfuse_export_tests.rs"]
+ mod tests;
diff --cc crates/openhuman-core/src/flows/tinyflows/langfuse_export_tests.rs
index bcec48b5ac,a0d05332d7..929555d3e6
--- a/crates/openhuman-core/src/flows/tinyflows/langfuse_export_tests.rs
+++ b/crates/openhuman-core/src/flows/tinyflows/langfuse_export_tests.rs
@@@ -1,34 -1,23 +1,23 @@@
use super::*;
- use tinyagents_graph::observability::GraphObservation;
+ use serde_json::Value;
-use tinyflows::graph::ids;
-use tinyflows::graph::GraphEvent;
+use tinyagents_graph::stream::GraphEvent;
+use tinyagents_harness::ids::{EventId, GraphId, NodeId, RunId, ThreadId};
+use tinyflows_bus::runs::FlowRunTrigger;
- use wiremock::matchers::{body_json, header, method, path};
- use wiremock::{Mock, MockServer, ResponseTemplate};
-
- fn attributed_test_client() -> reqwest::Client {
- let mut headers = reqwest::header::HeaderMap::new();
- headers.insert(
- crate::backend::transport::plain::TEST_PRODUCT_HEADER,
- reqwest::header::HeaderValue::from_static(
- crate::backend::transport::plain::TEST_PRODUCT_IDENTITY,
- ),
- );
- reqwest::Client::builder()
- .default_headers(headers)
- .build()
- .expect("attributed test client")
- }
+ /// Builds a minimal observation stream for one node under run/thread ids
+ /// shaped like a real `flows_run` (`thread_id = flow:{id}:{uuid}`).
+ ///
-/// Built as the ENGINE's observation type, which is what the `flows::`
-/// domain actually hands this module — so every test below goes through
-/// the same re-typing hop production does.
-fn sample_observations(thread_id: &str) -> Vec<FlowObservation> {
- let node = ids::NodeId::new("fetch");
- let mk = |offset: u64, step: usize, ts_ms: u64, event: GraphEvent| FlowObservation {
- event_id: ids::EventId::new(format!("evt-{offset}")),
- run_id: ids::RunId::new("run-9"),
- root_run_id: ids::RunId::new("run-9"),
++/// Built from the serialized TinyAgents graph-event contract consumed by the
++/// host's PollRun adapter; no TinyFlows engine types cross this boundary.
+fn sample_observations(thread_id: &str) -> Vec<GraphObservation> {
+ let node = NodeId::new("fetch");
+ let mk = |offset: u64, step: usize, ts_ms: u64, event: GraphEvent| GraphObservation {
+ event_id: EventId::new(format!("evt-{offset}")),
+ run_id: RunId::new("run-9"),
+ root_run_id: RunId::new("run-9"),
parent_run_id: None,
- thread_id: Some(ids::ThreadId::new(thread_id)),
- graph_id: ids::GraphId::new("workflow"),
+ thread_id: Some(ThreadId::new(thread_id)),
+ graph_id: GraphId::new("workflow"),
checkpoint_id: None,
namespace: Vec::new(),
step,
@@@ -85,10 -128,13 +128,13 @@@ fn otlp_flow_trace_puts_flow_attributes
thread_id,
"completed",
FlowRunTrigger::Rpc,
+ );
+ let requests = flow_otlp_requests(
+ &build_flow_exporter(client, "flow-1"),
+ trace,
- &to_exporter_observations(&sample_observations(thread_id)),
+ &sample_observations(thread_id),
)
- .expect("OTLP requests");
-
+ .expect("otlp requests");
let resource = &requests[0]["resourceSpans"][0];
assert_eq!(
resource["resource"]["attributes"][0]["value"]["stringValue"],
@@@ -170,7 -218,7 +218,7 @@@ fn batch_carries_flow_trace_and_langgra
FlowRunTrigger::Rpc,
);
let payload = exporter
- .build_ingestion_batch(trace, &sample_observations(thread_id))
- .build_ingestion_batch(trace, &to_exporter_observations(&observations))
++ .build_ingestion_batch(trace, &observations)
.expect("batch");
let batch = payload["batch"].as_array().expect("batch array");
@@@ -283,77 -323,45 +323,34 @@@ async fn export_skips_api_key_credentia
);
}
- #[tokio::test]
- async fn shared_otlp_transport_posts_rendered_graph_json_with_attribution() {
- let thread_id = "flow:flow-1:uuid-1";
- let requests = graph_otlp_requests(
- "Daily digest",
- "flow-1",
- thread_id,
- "completed",
- FlowRunTrigger::Rpc,
- &sample_observations(thread_id),
- )
- .expect("render graph OTLP JSON");
- let server = MockServer::start().await;
- Mock::given(method("POST"))
- .and(path("/otel/v1/traces"))
- .and(header("authorization", "Bearer session-token"))
- .and(header(
- crate::backend::transport::plain::TEST_PRODUCT_HEADER,
- crate::backend::transport::plain::TEST_PRODUCT_IDENTITY,
- ))
- .and(body_json(requests[0].clone()))
- .respond_with(ResponseTemplate::new(200).set_body_json(json!({})))
- .expect(1)
- .mount(&server)
- .await;
-
- let url = format!("{}/otel/v1/traces", server.uri());
- let client = attributed_test_client();
- super::super::otlp::push_otlp_json_requests_via(&client, &url, "session-token", &requests)
- .await
- .expect("send graph request through shared authenticated transport");
- }
-
- #[tokio::test]
- async fn shared_otlp_transport_reports_http_and_partial_rejections() {
-/// The re-typing mapper itself lives (and is tested) in
-/// `tinyflows::observe`; this pins it against `tinyagents`' exporter type,
-/// which only the host sees. The hop is a serde round-trip between two independently
-/// declared types, so nothing but a test notices when one of them grows,
-/// renames, or re-tags a field: `to_exporter_observations` would start
-/// silently dropping observations and the trace would quietly lose spans.
-/// This asserts the whole sample survives AND that the fields the exporter
-/// keys spans on come through with their values intact.
++/// The bus carries serialized TinyAgents graph observations. Pin the exact
++/// round-trip the PollRun adapter uses so graph span coordinates survive.
+ #[test]
-fn re_typing_preserves_every_field() {
++fn bus_graph_observation_round_trip_preserves_export_fields() {
let thread_id = "flow:flow-1:uuid-1";
- let requests = graph_otlp_requests(
- "Daily digest",
- "flow-1",
- thread_id,
- "completed",
- FlowRunTrigger::Rpc,
- &sample_observations(thread_id),
- )
- .expect("render graph OTLP JSON");
- let engine = sample_observations(thread_id);
- let converted: Vec<GraphObservation> = to_exporter_observations(&engine);
++ let bus_events: Vec<Value> = sample_observations(thread_id)
++ .iter()
++ .map(|observation| serde_json::to_value(observation).unwrap())
++ .collect();
++ let converted: Vec<GraphObservation> = bus_events
++ .into_iter()
++ .map(|event| serde_json::from_value(event).unwrap())
++ .collect();
- let server = MockServer::start().await;
- Mock::given(method("POST"))
- .and(path("/otel/v1/traces"))
- .respond_with(ResponseTemplate::new(503))
- .mount(&server)
- .await;
- let url = format!("{}/otel/v1/traces", server.uri());
- let client = attributed_test_client();
- let error = super::super::otlp::push_otlp_json_requests_via(&client, &url, "token", &requests)
- .await
- .expect_err("HTTP failure must be reported");
- assert!(error.contains("503"), "{error}");
+ assert_eq!(
+ converted.len(),
- engine.len(),
- "an observation was dropped — the two GraphObservation types have drifted"
++ sample_observations(thread_id).len(),
++ "a serialized graph observation was dropped"
+ );
- for (before, after) in engine.iter().zip(converted.iter()) {
- assert_eq!(
- serde_json::to_value(before).unwrap(),
- serde_json::to_value(after).unwrap(),
- "re-typing changed the observation's serialized form"
- );
- }
- let server = MockServer::start().await;
- Mock::given(method("POST"))
- .and(path("/otel/v1/traces"))
- .respond_with(ResponseTemplate::new(200).set_body_json(json!({
- "partialSuccess": { "rejectedSpans": 1, "errorMessage": "invalid span" }
- })))
- .mount(&server)
- .await;
- let url = format!("{}/otel/v1/traces", server.uri());
- let client = attributed_test_client();
- let error = super::super::otlp::push_otlp_json_requests_via(&client, &url, "token", &requests)
- .await
- .expect_err("partial rejection must be reported");
- assert!(error.contains("partially rejected"), "{error}");
- // Spot-check the fields the exporter reads directly, so a drift that
- // happened to stay serde-compatible (a renamed field with a matching
- // `#[serde(rename)]`, say) still fails here rather than producing a
- // batch full of empty spans.
+ let first = &converted[0];
+ assert_eq!(
+ first.thread_id.as_ref().map(|t| t.as_str()),
+ Some(thread_id)
+ );
+ assert_eq!(first.run_id.as_str(), "run-9");
+ assert_eq!(first.graph_id.as_str(), "workflow");
+ assert_eq!(first.offset, 0);
+ assert_eq!(converted[2].step, 1);
+ assert_eq!(converted[2].ts_ms, 1_020);
}
diff --cc crates/openhuman-core/src/inference/mod.rs
index 26d935ddd1,e1abc33ec8..ad82aea14a
--- a/crates/openhuman-core/src/inference/mod.rs
+++ b/crates/openhuman-core/src/inference/mod.rs
@@@ -32,9 -32,11 +32,12 @@@ pub mod http
pub mod model_context;
pub mod ops;
pub mod provider;
+pub mod readiness;
+ pub(crate) mod reasoning;
+ pub mod registry;
mod schemas;
pub mod tokenjuice;
+ pub mod turn_models;
pub use ops as rpc;
pub use schemas::{
diff --cc crates/openhuman-core/src/integrations/composio/mod.rs
index 171030e320,19d43ab4ec..fe5225cc26
--- a/crates/openhuman-core/src/integrations/composio/mod.rs
+++ b/crates/openhuman-core/src/integrations/composio/mod.rs
@@@ -38,8 -38,7 +38,9 @@@
//! crate::core::events::DomainEvent::ComposioTriggerReceived
pub mod action_tool;
+ mod auth_probe;
+#[cfg(any(feature = "flows", test))]
+pub(crate) mod builder_tools;
pub mod bus;
pub mod catalog;
pub mod client;
diff --cc crates/openhuman-core/src/mcp/server/README.md
index b6b9351c98,f4e6c1aa36..6cf5fea783
--- a/crates/openhuman-core/src/mcp/server/README.md
+++ b/crates/openhuman-core/src/mcp/server/README.md
@@@ -37,7 -37,7 +37,7 @@@ Process shutdown closes the module sess
| `crates/openhuman-core/src/mcp/server/handler.rs` | Applies host policy and dispatches typed `ServerHostCall`s to OpenHuman tool/resource behavior. |
| [`crates/openhuman-core/src/mcp/server/tools/`](./tools/) | Tool catalog and dispatch: `mod.rs` (facade; re-exports `tinymcp_bus::ToolCallError`), `types.rs` (`McpToolSpec` and the limit/tag constants, ungated so `McpToolSpec` is one real type in both builds), `specs.rs` (catalog builders and the `ServerToolSpec` conversion), `params.rs` (OpenHuman's per-tool argument policy → RPC params), `dispatch.rs` (`call_tool`/`list_tool_specs`, policy enforcement, subagent handlers). |
| [`crates/openhuman-core/src/mcp/server/write_dispatch.rs`](./write_dispatch.rs) | Write/audit pipeline for `memory.learn`/`memory.forget`: config load, act-policy enforcement, RPC dispatch to `openhuman.memory_learn` / `openhuman.memory_forget`, audit-record write (success/rejection) via `crate::mcp::audit::record_write`, PII-redacting arg summaries. |
- | [`crates/openhuman-core/src/mcp/server/resources.rs`](./resources.rs) | Static prompt markdown catalog plus request-scoped TinyFlows `GetPrompt` reads for the flow builtins. Test cross-checks exposed agent resources against `agent::registry::agents::BUILTINS`. |
-| [`crates/openhuman-core/src/mcp/server/resources.rs`](./resources.rs) | Static `RESOURCE_CATALOG` of compile-time-embedded prompt markdown, declared and read through bus vocabulary. Test cross-checks catalog vs `agent::agents::BUILTINS`. |
++| [`crates/openhuman-core/src/mcp/server/resources.rs`](./resources.rs) | Static prompt markdown catalog plus request-scoped TinyFlows Copilot `GetPrompt` and `GetResource` bus reads for the flow builtins. Tests cross-check exposed agent resources against `agent_registry::agents::BUILTINS`. |
| [`crates/openhuman-core/src/mcp/server/http.rs`](./http.rs) | Thin Axum transport adapter; passes raw request bodies and headers to module operations and uses module-selected response metadata. Gated on `all(feature = "mcp", feature = "http-server")`. |
| [`crates/openhuman-core/src/mcp/server/local.rs`](./local.rs) | Lazily-started, process-wide in-process loopback HTTP MCP server (`ensure_local_http`, `LocalMcpEndpoint`). Lets the sandboxed `claude` subprocess (Claude Code provider) reach OpenHuman's memory/tools over loopback without the MCP server inheriting Claude Code's OS jail; a per-process random bearer token stops any other local process from talking to it. |
| [`crates/openhuman-core/src/mcp/server/subagent_depth.rs`](./subagent_depth.rs) | Per-delegation-chain depth tracking for `agent.run_subagent`, propagated across the loopback MCP HTTP hop via the `X-OpenHuman-Subagent-Depth` header (read by `handler.rs` from `tinymcp`'s `RequestContext`) so nested Claude Code subagent calls are bounded without penalizing unrelated parallel callers. |
diff --cc crates/openhuman-core/src/mcp/server/resources.rs
index 7872d90948,de0778e4bd..fb37c29a75
--- a/crates/openhuman-core/src/mcp/server/resources.rs
+++ b/crates/openhuman-core/src/mcp/server/resources.rs
@@@ -122,8 -123,22 +122,8 @@@ const RESOURCE_CATALOG: &[PromptResourc
uri: "openhuman://prompts/agents/task_manager_agent",
name: "task_manager_agent",
description: "Specialist worker for task-source feeds, workflow bundles, and artifacts.",
- content: include_str!("../../agent/registry/agents/task_manager_agent/prompt.md"),
+ content: include_str!("../../agent_registry/agents/task_manager_agent/prompt.md"),
},
- #[cfg(feature = "flows")]
- PromptResource {
- uri: "openhuman://prompts/agents/flow_discovery",
- name: "flow_discovery",
- description: "Flow Scout — read-only workflow discovery agent that suggests automations from memory, threads, and integrations.",
- content: tinyflows_copilot::prompts::FLOW_DISCOVERY,
- },
- #[cfg(feature = "flows")]
- PromptResource {
- uri: "openhuman://prompts/agents/workflow_builder",
- name: "workflow_builder",
- description: "Workflow authoring specialist that builds tinyflows automation graphs and returns proposals for review.",
- content: tinyflows_copilot::prompts::WORKFLOW_BUILDER,
- },
#[cfg(feature = "skills")]
PromptResource {
uri: "openhuman://prompts/agents/skill_setup",
diff --cc crates/openhuman-core/src/mcp/server/resources_tests.rs
index 7db25b35ec,56cbf9fcd9..54802e07e5
--- a/crates/openhuman-core/src/mcp/server/resources_tests.rs
+++ b/crates/openhuman-core/src/mcp/server/resources_tests.rs
@@@ -2,9 -2,8 +2,9 @@@ use super::*
#[test]
fn catalog_mirrors_builtins() {
- use crate::agent::registry::agents::BUILTINS;
+ use crate::agent_registry::agents::BUILTINS;
+ let resources = resource_specs();
for b in BUILTINS {
let expected_uri = format!("openhuman://prompts/agents/{}", b.id);
assert!(
@@@ -106,20 -76,12 +106,20 @@@ fn read_resource_returns_minus_32002_fo
assert!(err.message().contains("nonexistent"));
}
-#[test]
-fn read_resource_returns_content_for_each_subagent() {
+#[tokio::test]
+async fn read_resource_returns_content_for_each_subagent() {
- use crate::agent::registry::agents::BUILTINS;
+ use crate::agent_registry::agents::BUILTINS;
+ let config = crate::config::Config::default();
+ let ctx = crate::core::runtime::DispatchCtx::new(
+ crate::core::runtime::CoreContext::for_test_with_config(
+ crate::core::runtime::DomainSet::full(),
+ config,
+ ),
+ );
for b in BUILTINS {
let uri = format!("openhuman://prompts/agents/{}", b.id);
- let result = read_resource(&uri)
+ let result = read_resource(&ctx, &uri)
+ .await
.unwrap_or_else(|_| panic!("read_resource failed for agent `{}`", b.id));
let text = result["contents"][0]["text"].as_str().unwrap_or("");
assert!(
diff --cc crates/openhuman-core/src/memory/error.rs
index d6b2770f4d,c9311d9bcf..6c0d4f95b4
--- a/crates/openhuman-core/src/memory/error.rs
+++ b/crates/openhuman-core/src/memory/error.rs
@@@ -23,6 -157,9 +157,17 @@@ impl From<MemoryError> for String
}
}
++/// Direct RPC boundaries can map a TinyMemory error using the same stable
++/// memory taxonomy used by the host's fallible operations.
++impl From<tinymemory_api::Error> for StructuredRpcError {
++ fn from(error: tinymemory_api::Error) -> Self {
++ MemoryError::from(error).to_structured()
++ }
++}
++
+ /// Result alias for memory operations.
+ pub type MemoryResult<T> = Result<T, MemoryError>;
+
#[cfg(test)]
#[path = "error_tests.rs"]
mod tests;
diff --cc crates/openhuman-core/src/memory/error_tests.rs
index e52922da54,d436759d26..1868b21486
--- a/crates/openhuman-core/src/memory/error_tests.rs
+++ b/crates/openhuman-core/src/memory/error_tests.rs
@@@ -1,102 -1,89 +1,190 @@@
+use tinymemory_api::Error as MemoryApiError;
+
+ use super::*;
+
+ #[test]
+ fn every_variant_has_its_stable_code() {
+ assert_eq!(MemoryError::Off("x".into()).code(), MEMORY_OFF);
+ assert_eq!(MemoryError::Unsupported("x".into()).code(), UNSUPPORTED);
+ assert_eq!(MemoryError::invalid("x").code(), INVALID_REQUEST);
+ assert_eq!(MemoryError::Unauthorized("x".into()).code(), UNAUTHORIZED);
+ assert_eq!(MemoryError::Engine("x".into()).code(), ENGINE);
+ assert_eq!(
+ MemoryError::InsufficientCredits("x".into()).code(),
+ INSUFFICIENT_CREDITS
+ );
+ assert_eq!(MemoryError::Unavailable("x".into()).code(), UNAVAILABLE);
+ }
+
+ #[test]
+ fn structured_error_carries_the_code_and_flags_user_states() {
+ let off = MemoryError::Off("sign in".into()).to_structured();
+ assert_eq!(off.data.as_ref().unwrap()["code"], MEMORY_OFF);
+ assert_eq!(off.data.as_ref().unwrap()["kind"], MEMORY_OFF);
+ assert!(off.expected_user_state);
+ assert!(off.message.contains("sign in"));
+
+ let engine = MemoryError::Engine("boom".into()).to_structured();
+ assert!(!engine.expected_user_state);
+ }
+
+ #[test]
-fn tinymemory_errors_map_onto_the_taxonomy() {
++fn tinymemory_errors_map_onto_the_host_taxonomy() {
+ use tinymemory_api::Error as E;
+ let cases = [
+ (E::Unsupported("a".into()), UNSUPPORTED),
+ (E::InvalidRequest("a".into()), INVALID_REQUEST),
+ (E::NotFound("a".into()), INVALID_REQUEST),
+ (E::Config("a".into()), INVALID_REQUEST),
+ (E::Unauthorized("a".into()), UNAUTHORIZED),
+ (E::Conflict("a".into()), ENGINE),
+ (E::Unavailable("a".into()), UNAVAILABLE),
+ (E::Engine("a".into()), ENGINE),
+ ];
+ for (error, code) in cases {
+ assert_eq!(MemoryError::from(error).code(), code);
+ }
+ }
+
+ #[test]
-fn into_string_encodes_the_structured_error() {
++fn memory_error_string_encodes_the_structured_error() {
+ let encoded: String = MemoryError::invalid("bad").into();
+ assert!(encoded.contains(INVALID_REQUEST), "{encoded}");
+ assert!(encoded.contains("bad"), "{encoded}");
+ }
+
+ #[test]
-fn account_wide_refusals_get_their_own_codes() {
++fn typed_credit_errors_are_account_wide_but_other_engine_errors_are_not() {
+ use tinymemory_api::Error as E;
+ let credits = MemoryError::from(E::Engine(
- "[USER_INSUFFICIENT_CREDITS] memory API recall on h: the account has insufficient \
- credits (HTTP 402)"
- .into(),
++ "[USER_INSUFFICIENT_CREDITS] memory API recall on h: the account has insufficient credits (HTTP 402)".into(),
+ ));
+ assert_eq!(credits.code(), INSUFFICIENT_CREDITS);
+ assert!(credits.is_account_wide());
+ assert!(credits.to_structured().expected_user_state);
+
+ let down = MemoryError::from(E::Unavailable("timed out".into()));
+ assert_eq!(down.code(), UNAVAILABLE);
+ assert!(down.is_account_wide());
+
- // Another backend code on an engine failure stays an engine failure.
+ let other = MemoryError::from(E::Engine("[HTTP_500] boom".into()));
+ assert_eq!(other.code(), ENGINE);
+ assert!(!other.is_account_wide());
+ assert!(!MemoryError::invalid("bad").is_account_wide());
+ }
+
+ #[test]
-fn a_skip_reason_reads_back_only_account_wide_refusals() {
- let code = |reason: &str| MemoryError::refusal_from_skip_reason(reason).map(|e| e.code());
++fn recall_skip_reasons_recover_only_account_wide_refusals() {
++ let code =
++ |reason: &str| MemoryError::refusal_from_skip_reason(reason).map(|error| error.code());
+ assert_eq!(
+ code("engine error: [USER_INSUFFICIENT_CREDITS] memory API fetch (HTTP 402)"),
+ Some(INSUFFICIENT_CREDITS)
+ );
+ assert_eq!(code("unavailable: connection refused"), Some(UNAVAILABLE));
+ assert_eq!(code("unauthorized: key rejected"), Some(UNAUTHORIZED));
+ assert_eq!(code("engine error: index corrupt"), None);
+ assert_eq!(code("invalid request: bad filter"), None);
+ assert_eq!(code("empty"), None);
+ }
++
+#[test]
+fn upstream_errors_keep_the_memory_rpc_wire_codes_and_messages() {
+ let cases = [
+ (
+ MemoryApiError::Off("sign in".into()),
+ "MEMORY_OFF",
+ "memory is off: sign in",
+ true,
+ ),
+ (
+ MemoryApiError::Unsupported("fetch".into()),
+ "UNSUPPORTED",
+ "unsupported: fetch",
+ true,
+ ),
+ (
+ MemoryApiError::InvalidRequest("bad filter".into()),
+ "INVALID_REQUEST",
+ "invalid request: bad filter",
+ true,
+ ),
+ (
+ MemoryApiError::NotFound("item".into()),
+ "INVALID_REQUEST",
+ "invalid request: item",
+ true,
+ ),
+ (
+ MemoryApiError::Config("missing endpoint".into()),
+ "INVALID_REQUEST",
+ "invalid request: missing endpoint",
+ true,
+ ),
+ (
+ MemoryApiError::Unauthorized("key rejected".into()),
+ "UNAUTHORIZED",
+ "unauthorized: key rejected",
+ true,
+ ),
+ (
+ MemoryApiError::InsufficientCredits("top up".into()),
+ "INSUFFICIENT_CREDITS",
+ "insufficient credits: top up",
+ true,
+ ),
+ (
+ MemoryApiError::Unavailable("timed out".into()),
+ "UNAVAILABLE",
+ "unavailable: timed out",
+ true,
+ ),
+ (
+ MemoryApiError::Conflict("already exists".into()),
+ "ENGINE",
+ "engine error: already exists",
+ false,
+ ),
+ (
+ MemoryApiError::Engine("index corrupt".into()),
+ "ENGINE",
+ "engine error: index corrupt",
+ false,
+ ),
+ ];
+
+ for (error, code, message, expected_user_state) in cases {
+ let structured = crate::core::StructuredRpcError::from(error);
+ assert_eq!(structured.data.as_ref().unwrap()["code"], code);
+ assert_eq!(structured.data.as_ref().unwrap()["kind"], code);
+ assert_eq!(structured.message, message);
+ assert_eq!(structured.expected_user_state, expected_user_state);
+ assert_eq!(
+ crate::core::StructuredRpcError::decode(&structured.encode()),
+ Some(structured)
+ );
+ }
+}
+
+#[test]
+fn upstream_account_wide_classification_includes_credits_and_unavailable() {
+ use tinymemory_api::Error as E;
+
+ assert!(E::Off("disabled".into()).is_account_wide());
+ assert!(E::Unauthorized("bad key".into()).is_account_wide());
+ assert!(E::InsufficientCredits("top up".into()).is_account_wide());
+ assert!(E::Unavailable("timeout".into()).is_account_wide());
+ assert!(!E::InvalidRequest("bad filter".into()).is_account_wide());
+ assert!(!E::Conflict("duplicate".into()).is_account_wide());
+ assert!(!E::Engine("corrupt index".into()).is_account_wide());
+}
+
+#[test]
+fn typed_insufficient_credits_maps_without_parsing_engine_text() {
+ let error = crate::core::StructuredRpcError::from(MemoryApiError::InsufficientCredits(
+ "HTTP 402".into(),
+ ));
+ assert_eq!(error.data.as_ref().unwrap()["code"], "INSUFFICIENT_CREDITS");
+ assert_eq!(error.message, "insufficient credits: HTTP 402");
+ assert!(error.expected_user_state);
+}
diff --cc crates/openhuman-core/src/memory/lifecycle/sender.rs
index 9fdeabd286,d68dd87875..60d64bde3d
--- a/crates/openhuman-core/src/memory/lifecycle/sender.rs
+++ b/crates/openhuman-core/src/memory/lifecycle/sender.rs
@@@ -3,10 -22,15 +3,10 @@@
use tinymemory_api::ObservedActor;
- use crate::agent::turn_origin::AgentTurnOrigin;
+ use crate::security::turn_origin::AgentTurnOrigin;
-/// Channels whose senders are phone numbers (or, for iMessage, email
-/// addresses).
-const PHONE_CHANNELS: &[&str] = &["whatsapp", "signal", "imessage", "linq", "sms"];
-
-/// The actor a channel turn is observed from, or `None` for any other
-/// origin, a channel turn without a sender, or a cron run (which replays its
-/// creator's channel origin around the job's own prompt, `cron/origin.rs`).
+/// The sender observed in an external-channel user turn, or `None` for any
+/// other origin, a missing sender, or a cron replay.
#[must_use]
pub fn channel_actor(origin: &AgentTurnOrigin) -> Option<ObservedActor> {
let AgentTurnOrigin::ExternalChannel {
diff --cc crates/openhuman-core/src/memory/mod.rs
index 0b6b61bcf5,8603b6a0d9..d01bde1c1d
--- a/crates/openhuman-core/src/memory/mod.rs
+++ b/crates/openhuman-core/src/memory/mod.rs
@@@ -22,8 -23,12 +22,9 @@@ pub mod backfill
pub mod billing;
pub mod brain;
pub mod bus;
-pub mod channels;
-pub mod confine;
-pub(crate) mod convert;
pub mod deletion;
pub mod engine;
+ pub mod engine_registry;
pub mod error;
pub mod explore;
pub mod guard;
diff --cc crates/openhuman-core/src/memory/ops_tests.rs
index c49b3dc002,8e54434dfc..75b54b1dd7
--- a/crates/openhuman-core/src/memory/ops_tests.rs
+++ b/crates/openhuman-core/src/memory/ops_tests.rs
@@@ -15,84 -13,6 +15,105 @@@ fn learn_params(text: &str) -> LearnPar
}
}
++#[cfg(feature = "channels")]
++#[test]
++fn corrupt_legacy_channel_threads_are_skipped_without_modifying_the_source() {
++ let tmp = tempfile::tempdir().unwrap();
++ let workspace = tmp.path().join("workspace");
++ let memory_dir = workspace.join("memory");
++ std::fs::create_dir_all(&memory_dir).unwrap();
++ let legacy_file = memory_dir.join("channel_threads.json");
++ let corrupt = br#"{"discord":["unfinished"}"#;
++ std::fs::write(&legacy_file, corrupt).unwrap();
++
++ let threads = legacy_channel_threads(&workspace, "discord");
++
++ assert!(threads.is_empty(), "invalid legacy state is skipped");
++ assert_eq!(std::fs::read(&legacy_file).unwrap(), corrupt);
++ assert!(
++ !legacy_file.with_extension("json.corrupt").exists(),
++ "a state read must not move or quarantine the legacy file"
++ );
++}
++
+#[cfg(feature = "channels")]
+#[tokio::test]
+async fn reserved_thread_matching_uses_module_identity_boundaries() {
+ use tinychannels_bus::module_inbound::PrepareChannelIdentityRequest;
+
+ let client = crate::channels::module_fixture::client().await;
+ let base_for = |channel: &'static str| {
+ let client = client.clone();
+ async move {
+ crate::modules::channel_controller::prepare_identity(
+ &client,
+ PrepareChannelIdentityRequest {
+ channel: channel.into(),
+ sender: None,
+ reply_target: None,
+ thread_ts: None,
+ },
+ )
+ .await
+ .expect("linked TinyChannels module prepares its canonical base")
+ .thread_id
+ }
+ };
+ let base = base_for("discord").await;
+ let neighboring_channel = base_for("discordish").await;
+
+ assert!(is_channel_thread_id(&base, &base));
+ assert!(is_channel_thread_id(&format!("{base}/thread-1"), &base));
+ assert!(is_channel_thread_id(
+ &format!("{base}#thread:1700.001"),
+ &base
+ ));
+ assert!(!is_channel_thread_id(&format!("{base}suffix"), &base));
+ assert!(!is_channel_thread_id(&neighboring_channel, &base));
+ assert!(!is_channel_thread_id(&format!("prefix-{base}"), &base));
+}
+
+#[cfg(feature = "channels")]
+#[tokio::test]
+async fn unavailable_channel_module_reports_error_and_queues_known_legacy_threads() {
+ use tinychannels_bus::module_inbound::PrepareChannelIdentityRequest;
+
+ let _linked_module = crate::channels::module_fixture::client().await;
+ let tmp = tempfile::tempdir().unwrap();
+ let mut config = config_in(&tmp);
+ config.modules.enabled = false;
+ let legacy_thread = "legacy-discord-thread";
+ let legacy_file = config.workspace_dir.join("memory/channel_threads.json");
+ std::fs::create_dir_all(legacy_file.parent().unwrap()).unwrap();
+ std::fs::write(&legacy_file, br#"{"discord":["legacy-discord-thread"]}"#).unwrap();
+
+ let unavailable = crate::modules::channel_controller::prepare_identity(
+ &crate::modules::client(config.clone()),
+ PrepareChannelIdentityRequest {
+ channel: "discord".into(),
+ sender: None,
+ reply_target: None,
+ thread_ts: None,
+ },
+ )
+ .await
+ .err()
+ .expect("explicitly disabled module must stay unavailable");
+ assert_eq!(unavailable, tinybus::module::ModuleCallError::Unavailable);
+
+ let error = forget_channel(&config, "discord")
+ .await
+ .expect_err("an unavailable identity module must be visible to the caller");
+ assert_eq!(error.code(), "ENGINE");
+ assert!(error.to_string().contains("channel identity preparation"));
+ assert_eq!(
+ crate::memory::deletion::pending(&config.workspace_dir),
+ vec![crate::memory::deletion::PendingDeletion::Thread {
+ thread_id: legacy_thread.into()
+ }]
+ );
+}
+
#[tokio::test]
async fn every_engine_operation_reports_memory_off_without_an_engine() {
let tmp = tempfile::tempdir().unwrap();
diff --cc crates/openhuman-core/src/security/credentials/ops/gated_services.rs
index e3099f02a0,ff1f8155a2..377c9f761d
--- a/crates/openhuman-core/src/security/credentials/ops/gated_services.rs
+++ b/crates/openhuman-core/src/security/credentials/ops/gated_services.rs
@@@ -44,33 -44,11 +44,32 @@@ pub(super) fn spawn_integrations_cache_
/// from the initial boot path (when an existing
/// session is detected) and from `set_credential()` when a credential is installed.
pub async fn start_credential_gated_services(
- _ctx: &crate::core::runtime::DispatchCtx,
+ ctx: &crate::core::runtime::DispatchCtx,
config: &Config,
) {
+ // Optional TinyFlows resources warm in the background and must never hold
+ // credential activation or ordinary chat startup on module availability.
+ crate::skills::schedule_flow_authoring_prewarm(ctx, config, None);
+ // These login-gated services are mutually independent — the ONLY ordering
+ // constraint is voice-server → standalone-dictation-listener (they contend
+ // for the single rdev global listener on macOS). Previously each was
+ // `.await`ed in series, so their cold-start costs SUMMED: the local-AI
+ // bootstrap (Ollama/embeddings) + the Windows WASAPI microphone init
+ // (a synchronous readiness handshake in `always_on::spawn_capture_thread`)
+ // stacked into the ~10s stall users hit before hotkeys/commands were usable
+ // — worst on Windows (#3490). Worse,
+ // the hotkey/command registration (steps 2–3) sat
+ // *after* the local-AI bootstrap in the series, so commands could not
+ // register until Ollama finished warming.
+ //
+ // Run them concurrently on independent tasks instead: readiness is bounded
+ // by the slowest single service rather than their sum, and command
+ // registration no longer waits behind local-AI warm-up. Each task logs its
+ // own elapsed time so a future regression can be attributed to one stage; a
+ // panic in one service is logged on join and never aborts the others.
+
// Unit tests must not launch the real login-gated background services: they
- // include detached, long-lived continuous audio capture that outlives the
- // test that spawned it and interleaves with the
+ // include detached listeners that outlive the test that spawned them and interleave with the
// shared process state (HOME / active_user.toml) of the parallel `cargo
// test` run. Once startup became concurrent (#3490) that interleaving made
// the session-isolation tests order-dependent. `cfg!(test)` is compiled out
diff --cc crates/openhuman-core/src/skills/README.md
index a496aa39aa,4ef5eba116..50df584425
--- a/crates/openhuman-core/src/skills/README.md
+++ b/crates/openhuman-core/src/skills/README.md
@@@ -224,11 -212,10 +222,11 @@@ rather than re-implementing it
| `remove_bundle` | Root search order, error wording, the `WorkflowsChanged` publish |
| Install URL normalization, the guarded `fetch_skill_document` (HTTPS only, non-public addresses refused, pinned connections, re-validated redirects, size cap, timeout), document validation, `write_installed_document`, `redact_url` | `Retry-After` and rate-limit messages, Sentry reporting |
| `TriggerPattern` grammar and matching | `TriggeredWorkflowIndex` and the bus subscriber |
-| Bundled-skill validate, digest, install, `is_current_materialization` | The `BUNDLED` table and the builtin root |
+| Bundled-skill validate, digest, install, `is_current_materialization` | The static `BUNDLED` table and its builtin root |
+| TinyFlows Copilot `ListResources` | The scoped flow-authoring snapshot, separate materialization root, and cache/read verification |
Other owners: the orchestrator prompt renders the catalog
- (`agent/registry/agents/orchestrator/prompt.rs`), channel turns render their
+ (`agent_registry/agents/orchestrator/prompt.rs`), channel turns render their
own skills list (`agent/context/channels_prompt.rs`), fork context carries the
parent's skill list to sub-agents (`agent/harness/fork_context.rs`), and the
flows domain contributes `Flow`-scope entries (`flows/catalogue.rs`).
diff --cc crates/openhuman-core/src/skills/ops_discover.rs
index cccfb57fed,9fe272d21f..146c10a9a2
--- a/crates/openhuman-core/src/skills/ops_discover.rs
+++ b/crates/openhuman-core/src/skills/ops_discover.rs
@@@ -14,8 -14,8 +14,6 @@@ mod scan
// `Path`, `Workflow`, `WorkflowScope`, and `precedence` exactly as it did
// before this module was split into submodules.
#[cfg(test)]
--#[cfg(test)]
--#[cfg(test)]
use std::path::Path;
pub use api::{
diff --cc crates/openhuman-embed/src/lib.rs
index 25aa5cef4e,7a6f4fb7f3..f42d8958f6
--- a/crates/openhuman-embed/src/lib.rs
+++ b/crates/openhuman-embed/src/lib.rs
@@@ -215,13 -212,16 +212,16 @@@ pub use runtime::
/// so the trait unifies — re-exporting it here would break the
/// agent-runtime ownership boundary.
pub mod seams {
- pub use openhuman_core::agent::hooks::{PostTurnHook, ToolHook};
- pub use openhuman_core::agent::hooks::{ToolHookContext, ToolHookDecision, TurnContext};
- pub use openhuman_core::agent::stop_hooks::BudgetStopHook;
+ pub use openhuman_core::agent::tinyagents::host::OpenHumanRunContext;
pub use tinyagents_harness::cost::TurnCost;
+ pub use tinyagents_harness::host::{LearningSink, TurnSummary};
pub use tinyagents_harness::middleware::{PolicyDecision, ToolCallPolicy};
+ pub use tinyagents_hooks::stop::BudgetStopHook;
pub use tinyagents_hooks::stop::{StopDecision, StopHook};
+ pub use tinyagents_hooks::tool::{
+ HookIdentity, ToolHook, ToolHookContext, ToolHookDecision, ToolHookEvent,
+ };
- /// Product cost snapshot passed to harness-owned stop policies.
+ /// Product cost snapshot passed to TinyAgents stop policies.
pub type TurnState<'a> = tinyagents_hooks::stop::TurnState<'a, TurnCost>;
pub use openhuman_core::core::all::{ControllerExtension, DomainGroup};
pub use openhuman_core::core::server_launcher::{HostBoot, ServeRequest, ServerLauncher};
diff --cc scripts/ci/check-openhuman-rust-layout.mjs
index 0251ecf1fa,73f20607ac..544be8f2b0
--- a/scripts/ci/check-openhuman-rust-layout.mjs
+++ b/scripts/ci/check-openhuman-rust-layout.mjs
@@@ -25,26 -25,25 +25,23 @@@ const LEGACY_LIMIT_ENTRIES =
// `spawn_subagent_tool_impl.rs` had its entry DELETED, not lowered: the
// parameter schema moved to `spawn_subagent_parameters.rs` and the file is
// under the general 750 limit, so it needs no exception at all.
-- // The session-todo integration added transcript metadata construction to
-- // this already-exempt composition seam. Keep its allowance exact.
- ["crates/openhuman-core/src/agent/session_host/runtime_session.rs", 1012],
// Session-host factory still assembles the product's deliberately coupled
// provider, security, memory, tool and prompt policy. Generic session
// state moved to tinyagents-runtime; this remaining composition is split in
// a follow-up without reintroducing an old harness/session exception.
- ["crates/openhuman-core/src/agent/session_host/builder/factory.rs", 965],
- ["crates/openhuman-core/src/agent/subagent_host/lifecycle.rs", 1033],
- ["crates/openhuman-core/src/agent/subagent_host/ops/runner.rs", 1035],
- ["crates/openhuman-core/src/web_chat/progress_bridge.rs", 1171],
+ ["crates/openhuman-core/src/agent/session_host/builder/factory.rs", 921],
- ["crates/openhuman-core/src/agent/subagent_host/lifecycle.rs", 754],
- ["crates/openhuman-core/src/agent/subagent_host/ops/runner.rs", 922],
++ ["crates/openhuman-core/src/agent/subagent_host/lifecycle.rs", 756],
++ ["crates/openhuman-core/src/agent/subagent_host/ops/runner.rs", 927],
+ ["crates/openhuman-core/src/web_chat/progress_bridge.rs", 1089],
// These established external test modules grew with upstream coverage. Pin
// their current sizes while follow-up work separates their test concerns.
// `core/` was pruned from the line limit by name until these pins; its
// oversized files are pinned at the size they had when enforcement began.
- ["crates/openhuman-core/src/core/all.rs", 1234],
+ ["crates/openhuman-core/src/core/all.rs", 1216],
["crates/openhuman-core/src/core/all_tests.rs", 1465],
- ["crates/openhuman-core/src/core/events.rs", 1785],
- ["crates/openhuman-core/src/core/events.rs", 1781],
- ["crates/openhuman-core/src/core/events_tests.rs", 997],
++ ["crates/openhuman-core/src/core/events.rs", 1763],
+ ["crates/openhuman-core/src/core/events_tests.rs", 988],
- ["crates/openhuman-core/src/core/observability.rs", 3466],
+ ["crates/openhuman-core/src/core/observability.rs", 3429],
];
const LEGACY_LIMITS = new Map(LEGACY_LIMIT_ENTRIES);
diff --cc scripts/ci/module-pin-exemptions.json
index a9393cfac8,87ca3887fa..a08dff5d69
--- a/scripts/ci/module-pin-exemptions.json
+++ b/scripts/ci/module-pin-exemptions.json
@@@ -9,43 -9,18 +9,13 @@@
"is a deliberate edit to this file, which is a reviewable diff.",
"",
"Delete an entry the moment the pins are reconciled. An exemption that has",
-- "stopped being true fails the gate too — `expect` must still match."
++ "stopped being true fails the gate too \u2014 `expect` must still match."
],
"exemptions": [
{
"id": "tinyconnectors",
"expect": "v0.19.3-76-gcb297ef1",
"reason": "The pinned TinyConnectors workspace package is still 0.19.3, matching the registry artifact; the gitlink sits 50 commits past that tag at the additive contract 1.22 (opt-in direct-route Composio triggers, off by default). Re-pin both once a release carrying it is cut. (Gitlink now at the merged upstream cb297ef1, storage schema v2.)"
- },
- {
- "id": "tinywallet",
- "expect": "v0.23.3-30-g7695a4ac",
- "reason": "Storage schema v2 (epic #7973): the gitlink sits past the registry's released tag on the merged upstream commit carrying the uniform storage schema. Re-pin both once a release carrying it is cut; retire this entry then."
- },
- {
- "id": "tinyjuice",
- "expect": "v0.10.5-16-g7b9d1aff",
- "reason": "Storage schema v2 (epic #7973): the gitlink sits past the registry's released tag on the merged upstream commit carrying the uniform storage schema. Re-pin both once a release carrying it is cut; retire this entry then."
- },
- {
- "id": "tinymcp",
- "expect": "v0.18.7-29-gc68c1fe3",
- "reason": "Storage schema v2 (epic #7973): the gitlink sits past the registry's released tag on the merged upstream commit carrying the uniform storage schema. Re-pin both once a release carrying it is cut; retire this entry then."
- },
- {
- "id": "tinybox",
- "expect": "v0.1.36-24-g8cb2a90c",
- "reason": "Storage schema v2 (epic #7973): the gitlink sits past the registry's released tag on the merged upstream commit carrying the uniform storage schema. Re-pin both once a release carrying it is cut; retire this entry then."
- },
- {
- "id": "tinychannels",
- "expect": "v0.1.34-34-g7ce04302",
- "reason": "Storage schema v2 (epic #7973): the gitlink sits past the registry's released tag on the merged upstream commit carrying the uniform storage schema. Re-pin both once a release carrying it is cut; retire this entry then."
-- },
-- {
- "id": "tinymemes",
- "expect": "v0.4.0-9-gb3a298fc",
- "id": "tinyflows",
- "expect": "v0.8.23-92-gcad43f97",
-- "reason": "Storage schema v2 (epic #7973): the gitlink sits past the registry's released tag on the merged upstream commit carrying the uniform storage schema. Re-pin both once a release carrying it is cut; retire this entry then."
}
]
}
diff --cc scripts/ci/storage-bypass-baseline.json
index 05d7fd2cca,92207edae9..07b4b874cb
--- a/scripts/ci/storage-bypass-baseline.json
+++ b/scripts/ci/storage-bypass-baseline.json
@@@ -169,15 -134,22 +134,22 @@@
},
{
"rule": "json-write",
- "path": "crates/openhuman-core/src/flows/tinyflows/caps/code.rs",
- "line": 127,
+ "path": "crates/openhuman-core/src/core/observability/progress_tracing/export.rs",
+ "line": 33,
+ "text": "let opened = std::fs::OpenOptions::new()",
+ "occurrence": 1
+ },
+ {
+ "rule": "json-write",
- "path": "crates/openhuman-core/src/flows/tinyflows/caps/code.rs",
- "line": 127,
++ "path": "crates/openhuman-core/src/flows/caps_host/code.rs",
++ "line": 139,
"text": "tokio::fs::write(&script_path, script_body)",
"occurrence": 1
},
{
"rule": "json-write",
-- "path": "crates/openhuman-core/src/flows/tinyflows/caps/code.rs",
-- "line": 130,
++ "path": "crates/openhuman-core/src/flows/caps_host/code.rs",
++ "line": 142,
"text": "tokio::fs::write(&input_path, input_json)",
"occurrence": 1
},
diff --cc vendor/tinymemory
index 0ed2c698d8,41c34f36d9..8c7afbbd19
--- a/vendor/tinymemory
+++ b/vendor/tinymemory
@@@ -1,1 -1,1 +1,1 @@@
- Subproject commit 0ed2c698d85bd4cf9a34311664cb70200798b5e1
-Subproject commit 41c34f36d912ffecac24b229cb657f331c7fc607
++Subproject commit 8c7afbbd192586b4677c8d67c5781c6fbdd29686