Skip to content

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

refactor(agent): run sessions through TinyAgents runtime

Steven Enamakel33566d382d45
diff --git a/.sdd-progress.md b/.sdd-progress.md
index 94bb62223f..1b257cf236 100644
--- a/.sdd-progress.md
+++ b/.sdd-progress.md
@@ -1,182 +1,8 @@
-Objective: migrate host-independent agent runtime/helpers into TinyAgents family with direct imports and no compatibility shims.
-Base: migrate-inference-to-tinyinference @ 8c90600688a143e8bd377a2296db5d626bea5095; upstream/main merged at 6b88a59930257a9cc310c34e78a1cf9fbdc8d0b7.
-Plan: docs/plans/migrate-agent-runtime-to-tinyagents.md
-Spec: docs/specs/agent-runtime-upstream-boundary.md
-
-Audit: complete (OpenHuman agent tree + TinyAgents/TinyTools/TinyInference capabilities reviewed).
-Documentation: complete (boundary spec + executable plan + helper packages + ownership waves; final review PASS with no findings).
-Profiles and session/orchestration audits: complete. Executable TDD plans are
-`docs/plans/migrate-agent-sessions-to-tinyagents-session.md` and
-`docs/plans/migrate-agent-orchestration-to-tinyagents.md`; implementation is
-in progress. They require direct imports with no compatibility shims and preserve
-OpenHuman policy/security, persistence-root wiring, BUS/progress/RPC projection,
-and concrete execution adapters.
-
-Orchestration O1-O4: complete locally; independent-review remediation and
-verification are complete, pending paired commits. `tinyagents-orchestration`
-is now a correctly spelled default workspace member with a tested one-way
-dependency gate and no OpenHuman dependency. It
-owns the neutral `TeamLedger` seam, `SessionTeamLedger`,
-dependency-aware `TeamService`, claim selection, generic member completion
-graph (including optional host-provided graph-event sinks), event-log paging,
-member watermark delivery, prompt composition, and Unicode-safe evidence
-truncation. OpenHuman's agent-team controllers, runtime, and topology import
-that crate directly; the runtime injects its established
-`team:<team>:<member>` tracing sink. The prior local `types`, `ops`, `graph`,
-message-delivery, prompt, and truncation helpers and their facades are deleted.
-OpenHuman retains its root-parent context, subagent execution,
-persistence-root selection and RPC schemas. O3-O4 add direct
-`tinyagents_orchestration::workflow` definitions and
-validation, opaque host catalog metadata, phase state, a session-ledger
-`WorkflowStore`, injected async `WorkflowExecutor`, bounded `map_reduce`
-fan-out, cancellation, terminal persistence, resume skipping, upstream prompt
-context, synthesis fallback and scheduler topology. Its 19 focused tests cover
-the O3/O4 behavior matrix; fresh `cargo test -p tinyagents-orchestration` and
-root `cargo check -p openhuman` pass. Focused OpenHuman lib tests are currently
-blocked by unrelated fixture migration diagnostics outside workflow runs. O5 is
-complete locally: `tinyagents-session` gives workflow rows an atomic owner
-lease and revision/CAS transitions; `tinyagents-orchestration` registers every
-real child id before awaiting it, leases one driver across resume races, emits
-its supplied graph lifecycle sink, and preserves arbitrary JSON outputs.
-OpenHuman's production lifecycle constructs the neutral `WorkflowEngine` over
-`Config.workspace_dir`, enters it under `with_root_parent`, and uses the host
-adapter for policy-admitted `AgentOrchestrationSession` spawning, BUS/progress,
-origin and model override. The old host scheduler/state/phase graph and
-duplicate tests are deleted; topology imports the neutral graph directly. O6
-is complete locally, pending the shared build-lock test queue and final
-review/commit gates. The duplicate fixed `spawn_parallel_agents` phase
-coordinator and topology facade are deleted: the host now decodes its tool-only
-JSON contract at the tool boundary, executes host
-policy/progress/worktree stages directly, and uses the existing
-`tinyagents_graph::parallel::map_reduce` for bounded worker fanout. The typed
-request stays host-side because `toolkit`, `files:` ownership syntax and
-worktree options are product-policy inputs, not a neutral orchestration API.
-Historic OpenHuman aliases for git worktree create/list/status/diff/remove,
-base refs, errors and overlap detection are deleted; every consumer imports
-the harness surface directly. `OpenHumanWorktreeIsolation`, its BUS lifecycle
-events, descriptor gate and RPC schemas remain host-owned. Dirty-worktree
-refusal/removal and parallel policy coverage are retained. Final boundary
-remediation also removed the behavior-free OpenHuman
-`workflow_runs::scheduler_topology_preview` forwarder: topology imports
-`tinyagents_orchestration::workflow` directly. TinyAgents orchestration tests
-(31) cover direct/broadcast watermark delivery, paging beyond the ledger cap,
-prompt composition, and UTF-8 truncation.
-
-O5 final durability remediation: complete locally, pending commit/review. The
-session ledger now exposes revision-fenced host lifecycle transitions and
-lease-only renewal; stale drivers cannot write terminal/error state after a
-stop/resume hand-off. The neutral engine heartbeats throughout child execution,
-fails closed by cancelling every registered child on renewal loss, resets
-interrupted `running` phases to retryable `pending`, and flushes truthful
-terminal graph events. Phase outputs retain the established RPC projection
-`{ agentId, output: String }`; lossless JSON is stored in versioned
-`metadata.rawOutput` and consumed preferentially by downstream phases. The
-host parses and enforces `safetyTier` at admission and child dispatch, retaining
-all policy in OpenHuman. Fresh TinyAgents session (62) and orchestration (26)
-unit tests pass, including short-lease takeover, lease-loss cancellation,
-stop fencing, output-wire compatibility and terminal events. The focused
-OpenHuman lib test target still fails before workflow tests on unrelated
-pre-existing fixture/API migration diagnostics; normal `cargo check -p
-openhuman` is in progress on the shared build lock.
-
-O5 takeover-race follow-up: complete locally, pending commit/review. A new
-lease owner durably resets abandoned `running` phase state through its fenced
-CAS before scheduling, so crash recovery retries rather than declaring a
-dependency deadlock; registered child IDs remain deduplicated. Fenced engines
-now leave silently when a replacement owns the run and cannot emit/flush a
-false terminal failure. OpenHuman cancellation signals carry generations;
-start/resume loops retain their exact signal, cleanup only removes its matching
-generation, and stop only cancels the signal it observed before its successful
-lifecycle CAS. The SQLite ledger, orchestration engine, graph sink, registry
-interleaving, and scheduler-preview topology regressions are covered. Fresh
-`tinyagents-session` (63 + doctest) and `tinyagents-orchestration` (28) tests
-pass; the root check is running against the shared build lock.
-
-Session extraction S1-S4: in progress. `tinyagents-session::transcript` owns
-the neutral append-only JSONL codec, paths, display/model readers, metadata,
-history and locator interfaces. Its public history API now stays entirely on
-lossless `TranscriptMessage`; the prior `FileTranscriptHistory -> Message` /
-`ChatHistory` conversion was removed because it dropped native tool calls,
-usage, thinking and provider metadata. OpenHuman production consumers import
-`tinyagents_session::transcript` directly and the local transcript/history
-implementation plus test modules are deleted. The only retained host seam is
-an explicit field-for-field `ChatMessage <-> TranscriptMessage` conversion at
-the persistence/replay boundary. TinyAgents focused transcript tests pass
-(6 tests: raw malformed arguments/provider extensions, malformed records,
-append/compaction/request-id/partials, lossless history, discovery and legacy
-read); root `cargo check -p openhuman` passed. Remaining: compile the
-OpenHuman test targets after their test doubles are moved to the direct trait,
-clean residual stale docs and finish review/commit gates.
-
-Session final-review remediation: complete through TinyAgents `6cc9ef5` and
-OpenHuman `84acccdfe0`. `tinyagents-session` no longer carries OpenHuman
-metadata keys or a hidden side-channel protocol: neutral durable rows carry
-usage, opaque request correlation, failure display state, cache breakpoints,
-and an explicit request-preservation bit for request-less replay. The host
-adapter owns legacy `ChatMessage` markers exclusively. Fresh
-`cargo test -p tinyagents-session` passed (60 unit tests plus doctest), as did
-`cargo check -p openhuman`; the full OpenHuman lib test compile remains in
-progress on the shared build target.
-Follow-up test-fixture port: OpenHuman session, session-import, transcript
-ingest, and transcript migration tests now construct canonical durable rows
-and direct `tinyinference_llm` streams. `Cargo.lock` drops only the now-unused
-`tinyagents-session` `async-trait` and `tinyinference-llm` dependencies.
-Fresh `cargo test -p tinyagents-session` again passed (60 unit tests plus one
-doctest); full `openhuman --lib --no-run` remains blocked by unrelated
-channels, tools, orchestration, cron, and inference fixture diagnostics.
-Session documentation/boundary remediation: complete pending the paired
-TinyAgents/OpenHuman commits. TinyAgents transcript and run-ledger docs are
-host-neutral and no longer link to host-private symbols. OpenHuman READMEs,
-the layout-migration rustdoc link, and the session plan name the direct
-`tinyagents_session::transcript` dependency. The host adapter has a focused
-cache-breakpoint round-trip assertion. `cargo test -p tinyagents-session
-transcript`, `cargo doc -p tinyagents-session --no-deps`, `pnpm docs:check`,
-and formatting pass; the focused OpenHuman test command is blocked before the
-new test by unrelated pre-existing test-compilation diagnostics.
-TinyAgents PR #158 Clippy remediation: complete through TinyAgents
-`8346a77` and `6c3105e`. The transcript display projection now boxes only its
-large in-memory message variant (the JSONL wire format is unchanged), and the
-workflow persistence transition uses a typed request. Fresh
-`cargo clippy --all-targets -- -D warnings`, `cargo test -p tinyagents-session`
-(63 plus doctest), and `cargo test -p tinyagents-orchestration` (31) pass.
-Wave 2: complete (direct canonical imports, explicit recursive context, execution-scoped graph bindings including durable resume/retry, registry/definition split, integration fixtures, and full workspace gate; independent Terra reviews resolved).
-Wave 3: complete in TinyAgents (all ten host capabilities, truthful unary/stream terminal lifecycle, parent-authority-preserving recursion, budget compression/accounting, and upstream Claude provider merge; independent Terra Gate 3 and merge reviews PASS).
-Wave 4 Phase A: complete at OpenHuman commit 9baad52086 (canonical direct imports, behavior-free facade deletion, host-only conversion/tracing seams retained; independent Terra review PASS).
-Wave 4 Phase B1: complete through OpenHuman commit a3dcf3f897 (explicit OpenHumanRunContext foundation, ten-capability host bundle, canonical shared-tool adapter, call-identity-safe middleware migration, truthful routing-role projection, and boundary baseline reduced from 377 to 358; independent Terra re-review PASS). The context is intentionally not live yet; Phase B2 owns task-local and route cutover.
-Wave 4 Phase B2g: complete (root `RunContext<OpenHumanRunContext>` now carries the shared dispatch guard, attachment placeholders, and explicit child-usage ledger; synchronous descendants read and write those handles directly, `LastTurnUsage` is populated from the root ledger, and the three ambient turn-local modules are deleted). The guard keeps its host-owned pause and wall-clock policy, while deterministic tests cover pause/budget refusal and sibling-ledger isolation.
-Wave 4 Phase C1: complete (the production root `ChatTurnGraph` now fails closed without retained hosted authority and otherwise enters the one process-shared `AgentHarness` through an invocation-local `AgentInvocation`/`InvocationRuntime`. The session's frozen prompt/context ladder remains the request, while the per-turn model route set, tools, policy session, progress, workspace, cancellation, steering, journal, artifacts, budgets, and terminal mapping stay invocation-local. Channel and sub-agent routes remain on the explicitly separate legacy runner. The exact boundary baseline is now 210, down by two root-route bridge entries.)
-Task -1: complete (git_attribution removed; focused behavioral Git-hardening test passed; re-review spec PASS and quality PASS with no findings).
-Task 0: complete (temporary exact baseline reduced from 455 to 377 after Phase A; checker scans all OpenHuman crates and TinyAgents facades; vendored dependency boundary 6/6; Terra re-review PASS).
-Task 1: in progress (TinyTools final is merged `7a40010` in PR #6; the source-breaking/tool-controlled trust experiment was removed and empty PR #7 closed; TinyAgents and OpenHuman direct-import consumers complete; final runtime deletion remains).
-Task 2: in progress (TinyAgents and OpenHuman use tinytools-agent directly and deleted tool_calling/pformat/parse/dispatcher facades; final manual runtime deletion remains).
-Task 3: in progress (TinyInference final reviewed head `ecfdb76`, upstream PR #13 approved with core CI green; TinyAgents consumers complete; OpenHuman decorator/task-local deletion remains).
-Task 4: in progress (TinyAgents explicit context, child data policy, graph binding and durable continuation complete; OpenHuman task-local removal remains).
-Task 5: in progress (TinyAgents host-driven harness complete and Gate 3 PASS; OpenHuman ten-capability factory and explicit context foundation complete, with live route integration in Phase B2).
-Task 6: in progress (tinyagents-definition and direct registry consumers complete; OpenHuman cutover remains).
-Task 7: in progress (canonical graph/delegation lifecycle and tests complete; OpenHuman cutover remains).
-Task 8: pending.
-Task 9: pending.
-Task 10: pending.
-Task 11: pending.
-Task 12: pending.
-
-Upstream handoff:
-- TinyTools: merged PR #6 at `7a40010`.
-- TinyInference: ready PR #13 at reviewed head `ecfdb76`; approved, unresolved review threads 0.
-- TinyAgents: ready PR #154 at `696379d`; review threads 0; harness tests, focused integration tests, workspace check, and default/all-feature strict Clippy pass; final independent delta review and upstream CI rerun pending.
-
-Decisions:
-- Direct imports only; no forwarding modules, type aliases, or compatibility re-exports for migrated APIs.
-- OpenHuman keeps product policy, security, durable wire formats, persistence, RPC/UI projection, configuration, and concrete host adapters.
-- Do not add tinyagents-inspect in this migration; diagnostics remain a later independently justified extraction.
-- Specialized tdd-implementer/code-reviewer roles were unavailable; use scoped worker agents and read-only explorer reviewers while preserving the same implementation/review gates.
-
-Wave 1 bases:
-- TinyTools: 1eb3dade18b56c67dacbe16ae92ce42b0a097b7a
-- TinyInference: 6db1968d1463791e1823c808808da64b9579b8fc
-
-Wave 2 gate evidence:
-- `cargo fmt --all -- --check` passed in TinyAgents.
-- `cargo test --workspace` passed in TinyAgents.
-- `cargo clippy --workspace --all-targets -- -D warnings` passed in TinyAgents.
-- `pnpm rust:layout`, `pnpm docs:check`, the agent-runtime boundary checker, and the dependency-boundary suite passed.
+Phase 0: complete (commit 89490d8; tinyagents-graph binding resume/retry acceptance coverage; 452 tests + doctests and strict clippy pass; final review clean)
+Phase 1: complete (OpenHuman commit 9f051b4ea4; wrapper deleted, direct tinyagents-harness imports, host acceptance coverage; final review approved)
+Phase 2: complete (TinyAgents commit 420cab0, OpenHuman commit a83a99c505; 74 tests + doctest and OpenHuman cargo check pass; final review approved)
+Phase 3: complete (TinyAgents commits 0a44f32 + 6d611da + host-preparation/usage extensions 2d19206 + 766af06 + 6930dc5; 39 runtime tests, 17 transcript tests, workspace check and strict clippy pass; final review approved)
+Phase 4: pending (OpenHuman session_host cutover and harness/session deletion)
+Phase 5: complete (TinyAgents commits c90dca1 + 612e4e8 + 7e108c7; 23 focused / 54 orchestration tests, strict clippy and workspace check; final review approved)
+Phase 6: pending (OpenHuman subagent_host cutover and harness/subagent_runner deletion)
+Phase 7: pending (docs, boundary gates, final validation, PR updates)
diff --git a/Cargo.lock b/Cargo.lock
index 1b0c9bbd2a..3871da3414 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -4156,6 +4156,7 @@ dependencies = [
"tinyagents-language",
"tinyagents-orchestration",
"tinyagents-registry",
+ "tinyagents-runtime",
"tinyagents-session",
"tinybus",
"tinychannels",
@@ -6455,13 +6456,10 @@ version = "2.1.2"
dependencies = [
"anyhow",
"async-trait",
- "chrono",
"futures",
- "reqwest",
"rusqlite",
"serde",
"serde_json",
- "sha2 0.11.0",
"tinyagents-harness",
"tinyagents-language",
"tinyagents-tracing",
@@ -6477,9 +6475,8 @@ dependencies = [
"anyhow",
"async-trait",
"base64 0.22.1",
- "bytes",
"chrono",
- "dirs 5.0.1",
+ "dirs 6.0.0",
"flate2",
"futures",
"log",
@@ -6523,7 +6520,9 @@ dependencies = [
"serde_json",
"tinyagents-graph",
"tinyagents-harness",
+ "tinyagents-runtime",
"tinyagents-session",
+ "tinyinference-llm",
"tokio",
"uuid",
]
@@ -6536,13 +6535,26 @@ dependencies = [
"serde",
"serde_json",
"tinyagents-definition",
- "tinyagents-graph",
"tinyagents-harness",
"tinyagents-language",
"tinyinference-llm",
"tinytools",
]
+[[package]]
+name = "tinyagents-runtime"
+version = "2.1.2"
+dependencies = [
+ "async-trait",
+ "chrono",
+ "thiserror 2.0.20",
+ "tinyagents-harness",
+ "tinyagents-session",
+ "tinyinference-llm",
+ "tinytools",
+ "tokio",
+]
+
[[package]]
name = "tinyagents-session"
version = "2.1.2"
diff --git a/crates/openhuman-core/Cargo.toml b/crates/openhuman-core/Cargo.toml
index 525ae1a98f..272721f4bb 100644
--- a/crates/openhuman-core/Cargo.toml
+++ b/crates/openhuman-core/Cargo.toml
@@ -416,6 +416,7 @@ tinyagents-graph = { path = "../../vendor/tinyagents/crates/tinyagents-graph", f
tinyagents-language = { path = "../../vendor/tinyagents/crates/tinyagents-language" }
tinyagents-registry = { path = "../../vendor/tinyagents/crates/tinyagents-registry" }
tinyagents-session = { path = "../../vendor/tinyagents/crates/tinyagents-session" }
+tinyagents-runtime = { path = "../../vendor/tinyagents/crates/tinyagents-runtime" }
tinyagents-orchestration = { path = "../../vendor/tinyagents/crates/tinyagents-orchestration" }
tinyinference-core = { path = "../../vendor/tinyagents/vendor/tinyinference/crates/tinyinference-core" }
tinyinference-embeddings = { path = "../../vendor/tinyagents/vendor/tinyinference/crates/tinyinference-embeddings" }
diff --git a/crates/openhuman-core/src/agent/README.md b/crates/openhuman-core/src/agent/README.md
index 81de5c17c0..0fe6eee00d 100644
--- a/crates/openhuman-core/src/agent/README.md
+++ b/crates/openhuman-core/src/agent/README.md
@@ -4,7 +4,7 @@ Multi-agent orchestration domain. Owns the LLM tool-calling loop, sub-agent disp
## Public surface
-- `pub struct Agent` / `pub struct AgentBuilder` / `pub struct TurnOverrides` — `harness/session/types.rs`, re-exported from `harness::session` and `agent` — top-level conversation runtime; entry point for any chat turn. Constructors `Agent::from_config` and `from_config_for_agent` live in `harness/session/builder/factory.rs`; `run_single` / `run_interactive` in `harness/session/runtime/run_loop.rs`. The `builder/`, `runtime/`, and `turn/` submodules are private.
+- `pub struct OpenHumanSessionHost` / `pub struct SessionHostBuilder` / `pub struct TurnOverrides` — `session_host/types.rs`, re-exported from `agent` — top-level conversation runtime; entry point for any chat turn. Constructors live in `session_host/builder/factory.rs`; `run_single` / `run_interactive` in `session_host/runtime/run_loop.rs`. The `builder/`, `runtime/`, and `turn/` submodules are private.
- `pub fn run_subagent` / `pub struct SubagentRunOptions` / `pub enum SubagentRunError` — `harness/subagent_runner/` — execute a hierarchical sub-agent from a parent tool loop.
- `pub struct AgentDefinition` / `pub struct AgentDefinitionRegistry` / `pub enum SandboxMode` / `pub enum ToolScope` — `harness/definition/` (`agent_definition.rs`, `registry.rs`, `source.rs`, `tier.rs`, `execution_spec.rs`, `prompt_source.rs`, `subagents.rs`) — sub-agent archetypes loaded from built-ins + workspace TOML.
- `pub mod harness::fork_context` — task-local parent context for KV-cache reuse.
@@ -75,7 +75,7 @@ Flat files: `bus.rs` (`agent.run_turn` native request handler), `cost.rs` (`pub(
## Tests
-- Unit: `agent_tests.rs`, `multimodal_tests.rs`, and direct TinyTools Agent dialect coverage in `pformat_tests.rs`, plus `*_tests.rs` files colocated with `bus.rs`, `cost.rs`, `error.rs`, `hooks.rs`, `host_runtime.rs`, `message_convert.rs`, `platform_shell.rs`, `progress_sink.rs`, `schemas.rs`, `stop_hooks.rs`, `task_board.rs`, `task_session.rs`, `tool_policy.rs`, `turn_origin.rs`, `turn_workspace.rs`, and under `harness/`, `harness/session/`, `triage/`.
+- Unit: `agent_tests.rs`, `multimodal_tests.rs`, and direct TinyTools Agent dialect coverage in `pformat_tests.rs`, plus `*_tests.rs` files colocated with `bus.rs`, `cost.rs`, `error.rs`, `hooks.rs`, `host_runtime.rs`, `message_convert.rs`, `platform_shell.rs`, `progress_sink.rs`, `schemas.rs`, `stop_hooks.rs`, `task_board.rs`, `task_session.rs`, `tool_policy.rs`, `turn_origin.rs`, `turn_workspace.rs`, and under `harness/`, `session_host/`, `triage/`.
- Integration: `tests/agent_builder_public.rs`, `tests/agent_harness_public.rs`, `tests/agent_harness_e2e.rs`, `tests/agent_multimodal_public.rs`, `tests/agent_turn_overrides_e2e.rs`, `tests/agent_approval_memory_coverage_e2e.rs`.
- Schema regression: `schemas_tests.rs` (`controller_schema_inventory_is_stable`).
diff --git a/crates/openhuman-core/src/agent/agent_tests.rs b/crates/openhuman-core/src/agent/agent_tests.rs
index 8b30179d52..eb7ac73fb8 100644
--- a/crates/openhuman-core/src/agent/agent_tests.rs
+++ b/crates/openhuman-core/src/agent/agent_tests.rs
@@ -1,6 +1,6 @@
//! Comprehensive agent-loop test suite.
//!
-//! Tests exercise the full `Agent.turn()` cycle with mock providers and tools,
+//! Tests exercise the full `OpenHumanSessionHost.turn()` cycle with mock providers and tools,
//! covering every edge case an agentic tool loop must handle:
//!
//! 1. Simple text response (no tools)
@@ -24,8 +24,8 @@
//! 19. Builder validation (missing required fields)
//! 20. Idempotent system prompt insertion
-use crate::agent::harness::session::Agent;
use crate::agent::messages::{ChatMessage, ConversationMessage, ToolResultMessage};
+use crate::agent::session_host::OpenHumanSessionHost;
use crate::config::AgentConfig;
use crate::inference::provider::{ChatResponse, ToolCall};
use crate::memory::Memory;
@@ -244,14 +244,14 @@ fn make_retaining_memory() -> (Arc<dyn Memory>, tempfile::TempDir) {
}
/// Build an agent with an isolated temp workspace.
-/// Returns `(Agent, TempDir)` — hold `_tmp` in the test to keep the dir alive.
+/// Returns `(OpenHumanSessionHost, TempDir)` — hold `_tmp` in the test to keep the dir alive.
fn build_agent_with(
provider: Arc<dyn ChatModel<()>>,
tools: Vec<Box<dyn Tool>>,
dispatcher: Box<dyn ToolDialect>,
-) -> (Agent, tempfile::TempDir) {
+) -> (OpenHumanSessionHost, tempfile::TempDir) {
let (mem, tmp) = make_memory();
- let agent = Agent::builder()
+ let agent = OpenHumanSessionHost::builder()
.chat_model(provider)
.tools(tools)
.memory(mem)
@@ -267,9 +267,9 @@ fn build_agent_with_memory(
tools: Vec<Box<dyn Tool>>,
mem: Arc<dyn Memory>,
auto_save: bool,
-) -> (Agent, tempfile::TempDir) {
+) -> (OpenHumanSessionHost, tempfile::TempDir) {
let tmp = tempfile::TempDir::new().unwrap();
- let agent = Agent::builder()
+ let agent = OpenHumanSessionHost::builder()
.chat_model(provider)
.tools(tools)
.memory(mem)
@@ -285,9 +285,9 @@ fn build_agent_with_config(
provider: Arc<dyn ChatModel<()>>,
tools: Vec<Box<dyn Tool>>,
config: AgentConfig,
-) -> (Agent, tempfile::TempDir) {
+) -> (OpenHumanSessionHost, tempfile::TempDir) {
let (mem, tmp) = make_memory();
- let agent = Agent::builder()
+ let agent = OpenHumanSessionHost::builder()
.chat_model(provider)
.tools(tools)
.memory(mem)
diff --git a/crates/openhuman-core/src/agent/agent_turn_loop_packed_tool_tests.rs b/crates/openhuman-core/src/agent/agent_turn_loop_packed_tool_tests.rs
index 674d920586..8c0475d887 100644
--- a/crates/openhuman-core/src/agent/agent_turn_loop_packed_tool_tests.rs
+++ b/crates/openhuman-core/src/agent/agent_turn_loop_packed_tool_tests.rs
@@ -1,6 +1,6 @@
use super::*;
-// #6276: bare calls to withheld packed tools, driven through a whole `Agent::turn`.
+// #6276: bare calls to withheld packed tools, driven through a whole `OpenHumanSessionHost::turn`.
// Split out of `agent_turn_loop_tests.rs` to keep that file under the layout gate.
/// Stands in for a packed tool and records the arguments it ran with.
diff --git a/crates/openhuman-core/src/agent/context/manager.rs b/crates/openhuman-core/src/agent/context/manager.rs
index e19bb6dc2b..92962ebfcd 100644
--- a/crates/openhuman-core/src/agent/context/manager.rs
+++ b/crates/openhuman-core/src/agent/context/manager.rs
@@ -73,7 +73,7 @@ pub struct ContextManager {
/// context window. See [`ContextConfig::prefer_markdown_tool_output`].
prefer_markdown_tool_output: bool,
/// When `true`, native tool-output compaction (Stage 1a) runs in
- /// `Agent::execute_tool_call` before the byte cap. On by default; the
+ /// `OpenHumanSessionHost::execute_tool_call` before the byte cap. On by default; the
/// kill-switch lives here so every caller reads one source of truth.
/// See [`ContextConfig::compaction_enabled`].
compaction_enabled: bool,
diff --git a/crates/openhuman-core/src/agent/context/session_memory.rs b/crates/openhuman-core/src/agent/context/session_memory.rs
index 45bd51f560..6a091df78c 100644
--- a/crates/openhuman-core/src/agent/context/session_memory.rs
+++ b/crates/openhuman-core/src/agent/context/session_memory.rs
@@ -15,7 +15,7 @@
//!
//! This module is purely state-tracking: it owns the thresholds and a
//! `should_extract` decision, but the actual `spawn_subagent` call is
-//! issued by the caller (the `Agent::turn` epilogue) so we avoid a
+//! issued by the caller (the `OpenHumanSessionHost::turn` epilogue) so we avoid a
//! circular dependency with `harness::subagent_runner`.
/// Minimum number of *new* tokens (input + output) since the last
diff --git a/crates/openhuman-core/src/agent/debug/mod.rs b/crates/openhuman-core/src/agent/debug/mod.rs
index 18584cc0bb..185395ecee 100644
--- a/crates/openhuman-core/src/agent/debug/mod.rs
+++ b/crates/openhuman-core/src/agent/debug/mod.rs
@@ -2,9 +2,9 @@
//! would see for a given agent.
//!
//! Instead of re-implementing prompt assembly, this module routes
-//! through [`Agent::from_config_for_agent`] — the same entry point the
+//! through [`OpenHumanSessionHost::from_config_for_agent`] — the same entry point the
//! Tauri web channel and CLI use — and then calls
-//! [`Agent::build_system_prompt`] on the constructed session. The
+//! [`OpenHumanSessionHost::build_system_prompt`] on the constructed session. The
//! output is byte-identical to what the LLM would receive on turn 1 of
//! that agent.
//!
@@ -31,8 +31,8 @@ pub use dump_writer::{write_prompt_dumps, DumpWriteSummary};
pub use wire::render as render_wire_dump;
use crate::agent::harness::definition::{AgentDefinition, AgentDefinitionRegistry, PromptSource};
-use crate::agent::harness::session::Agent;
use crate::agent::prompts::{LearnedContextData, PromptContext, PromptTool, ToolCallFormat};
+use crate::agent::session_host::OpenHumanSessionHost;
use crate::config::Config;
use crate::integrations::composio::ComposioActionTool;
use tinytools::{Tool, ToolCategory};
@@ -123,7 +123,7 @@ fn tool_specs_of(tools: &[Box<dyn Tool>]) -> Vec<serde_json::Value> {
}
/// Render and return the system prompt for a single agent via the
-/// real [`Agent::from_config_for_agent`] construction path.
+/// real [`OpenHumanSessionHost::from_config_for_agent`] construction path.
pub async fn dump_agent_prompt(options: DumpPromptOptions) -> Result<DumpedPrompt> {
let config = load_dump_config(
options.workspace_dir_override.clone(),
@@ -263,7 +263,7 @@ 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 = Agent::from_config_for_agent(config, agent_id)
+ let mut agent = OpenHumanSessionHost::from_config_for_agent(config, agent_id)
.with_context(|| format!("building session agent for `{agent_id}`"))?;
// Match turn-1 behaviour: fetch the user's active Composio
@@ -283,7 +283,7 @@ async fn render_via_session(config: &Config, agent_id: &str) -> Result<DumpedPro
}
/// Package a built session agent's rendered prompt and tool surface.
-fn session_dump(agent: &Agent, agent_id: &str, text: String) -> DumpedPrompt {
+fn session_dump(agent: &OpenHumanSessionHost, agent_id: &str, text: String) -> DumpedPrompt {
// The whole callable surface, so the dump shows the `delegate_*` tools
// the refresh above just synthesised alongside the durable registry.
let tools = agent.all_tool_refs();
@@ -321,7 +321,7 @@ fn session_dump(agent: &Agent, agent_id: &str, text: String) -> DumpedPrompt {
/// slice to only the requested toolkit before calling the agent's
/// dynamic prompt builder.
async fn render_integrations_agent(config: &Config, toolkit: &str) -> Result<DumpedPrompt> {
- let mut agent = Agent::from_config_for_agent(config, INTEGRATIONS_AGENT_ID)
+ let mut agent = OpenHumanSessionHost::from_config_for_agent(config, INTEGRATIONS_AGENT_ID)
.with_context(|| format!("building integrations_agent session for `{toolkit}`"))?;
agent.fetch_connected_integrations().await;
@@ -593,7 +593,7 @@ async fn connected_toolkits_for(config: &Config) -> Result<Vec<String>> {
// reuse its `fetch_connected_integrations` cache — the call is
// deduped backend-side via `INTEGRATIONS_CACHE`, so repeated
// invocations in `dump_all_agent_prompts` only hit the wire once.
- let mut agent = Agent::from_config_for_agent(config, INTEGRATIONS_AGENT_ID)
+ let mut agent = OpenHumanSessionHost::from_config_for_agent(config, INTEGRATIONS_AGENT_ID)
.with_context(|| "building integrations_agent probe session for toolkit discovery")?;
agent.fetch_connected_integrations().await;
Ok(agent
diff --git a/crates/openhuman-core/src/agent/debug/prompt_size.rs b/crates/openhuman-core/src/agent/debug/prompt_size.rs
index 576407af08..c7e70ff8f2 100644
--- a/crates/openhuman-core/src/agent/debug/prompt_size.rs
+++ b/crates/openhuman-core/src/agent/debug/prompt_size.rs
@@ -15,7 +15,7 @@
//! # What is measured
//!
//! Everything comes from [`super::dump_agent_prompt`], which builds a real
-//! agent through `Agent::from_config_for_agent` and renders the turn-1 prompt.
+//! agent through `OpenHumanSessionHost::from_config_for_agent` and renders the turn-1 prompt.
//! No numbers are re-derived from a second code path, so the report cannot
//! drift from the dump.
//!
diff --git a/crates/openhuman-core/src/agent/debug/prompt_size_tests.rs b/crates/openhuman-core/src/agent/debug/prompt_size_tests.rs
index 24bbf91ad7..985bd19241 100644
--- a/crates/openhuman-core/src/agent/debug/prompt_size_tests.rs
+++ b/crates/openhuman-core/src/agent/debug/prompt_size_tests.rs
@@ -87,7 +87,7 @@ fn session_report_measures_the_visible_belt_not_the_registry() {
..crate::config::Config::default()
};
std::fs::create_dir_all(&config.workspace_dir).unwrap();
- let agent = crate::agent::Agent::from_config_for_agent(&config, "critic")
+ let agent = crate::agent::OpenHumanSessionHost::from_config_for_agent(&config, "critic")
.expect("critic session build");
let dumped = crate::agent::debug::session_dump(&agent, "critic", String::new());
diff --git a/crates/openhuman-core/src/agent/error.rs b/crates/openhuman-core/src/agent/error.rs
index 03a548995c..740dfc1b8d 100644
--- a/crates/openhuman-core/src/agent/error.rs
+++ b/crates/openhuman-core/src/agent/error.rs
@@ -36,7 +36,7 @@ pub enum AgentError {
/// with flaky local model fine-tunes (e.g. community quantizations of
/// Qwen/Llama via LM Studio or Ollama). Surfaced as a user-facing
/// error instead of a silent blank reply (defense-in-depth from
- /// `agent/harness/session/turn.rs`) but suppressed from Sentry — it's
+ /// `agent/session_host/turn.rs`) but suppressed from Sentry — it's
/// a provider/user-state outcome, not an OpenHuman bug, and a deeper
/// fix lives in the model / provider config the user chose. Targets
/// Sentry TAURI-RUST-4JX (~33 events, escalating on 0.56.0).
@@ -98,7 +98,7 @@ impl fmt::Display for AgentError {
}
Self::EmptyProviderResponse { .. } => {
// Verbatim user-facing string from the old
- // `agent/harness/session/turn.rs` emit site — UI / tests
+ // `agent/session_host/turn.rs` emit site — UI / tests
// grep for this exact byte sequence.
write!(f, "The model returned an empty response. Please try again.")
}
diff --git a/crates/openhuman-core/src/agent/error_tests.rs b/crates/openhuman-core/src/agent/error_tests.rs
index ad6412ff9a..d6d5663474 100644
--- a/crates/openhuman-core/src/agent/error_tests.rs
+++ b/crates/openhuman-core/src/agent/error_tests.rs
@@ -95,7 +95,7 @@ fn from_anyhow_recovers_typed_agent_error_and_other_source() {
// ── AgentError::EmptyProviderResponse (TAURI-RUST-4JX) ──────────────────
//
-// `agent::harness::session::turn` returns this variant when the provider's
+// `agent::session_host::turn` returns this variant when the provider's
// chat completion contains no text, no thinking, and no tool calls (a
// degenerate/poisoned response — typically a flaky local model). The
// variant was added so `run_single` can route it through `skips_sentry()`
@@ -107,7 +107,7 @@ fn from_anyhow_recovers_typed_agent_error_and_other_source() {
fn empty_provider_response_display_matches_user_facing_string() {
// The exact wire string is anchored: the UI surfaces it verbatim to
// the user, and the emit-site comment at
- // `agent/harness/session/turn.rs:801` (the warn breadcrumb) explicitly
+ // `agent/session_host/turn.rs:801` (the warn breadcrumb) explicitly
// calls out the "surfacing as error instead of a silent blank reply"
// contract. Any change to this byte string is a user-visible message
// change and a Sentry-fingerprint change.
diff --git a/crates/openhuman-core/src/agent/experience/README.md b/crates/openhuman-core/src/agent/experience/README.md
index 60a63ff0e7..90dfe50900 100644
--- a/crates/openhuman-core/src/agent/experience/README.md
+++ b/crates/openhuman-core/src/agent/experience/README.md
@@ -69,7 +69,7 @@ Records are stored through the `Memory` trait (no dedicated DB), served by `Driv
- `crates/openhuman-core/src/core/all.rs` — registers controllers/schemas and the namespace description.
- `crates/openhuman-core/src/agent/mod.rs` — declares `pub mod experience`.
-- `crates/openhuman-core/src/agent/harness/session/turn/core/experience_context.rs` — defines `Agent::inject_agent_experience_context`, which queries the session store plus the shared store with `retrieve_across_stores` (max 3 hits, 2048-byte block, gated on `learning_enabled`) and prepends the block to the enriched user message. Called from `turn/core_turn.rs`.
+- `crates/openhuman-core/src/agent/session_host/turn/core/experience_context.rs` — defines `Agent::inject_agent_experience_context`, which queries the session store plus the shared store with `retrieve_across_stores` (max 3 hits, 2048-byte block, gated on `learning_enabled`) and prepends the block to the enriched user message. Called from `turn/core_turn.rs`.
- `crates/openhuman-core/src/agent/tinyagents/host/experience_store.rs` — host adapter implementing `tinyagents_harness::host::ExperienceStore` over `AgentExperienceStore`.
- `crates/openhuman-core/src/config/migration_helpers/core.rs` — uses `DriverMemory::for_config` to bind the import target.
diff --git a/crates/openhuman-core/src/agent/goals/continuation.rs b/crates/openhuman-core/src/agent/goals/continuation.rs
index 0cb4d7d29f..6df1ee9077 100644
--- a/crates/openhuman-core/src/agent/goals/continuation.rs
+++ b/crates/openhuman-core/src/agent/goals/continuation.rs
@@ -30,7 +30,7 @@ use tokio::sync::Semaphore;
use super::store;
use super::{ThreadGoal, ThreadGoalStatus};
use crate::agent::turn_origin::{with_origin, AgentTurnOrigin, TrustedAutomationSource};
-use crate::agent::Agent;
+use crate::agent::OpenHumanSessionHost;
use crate::config::Config;
use crate::threads::turn_state::{TurnLifecycle, TurnStateStore};
@@ -171,7 +171,7 @@ async fn dispatch_continuation(config: &Config, goal: &ThreadGoal) -> bool {
"[thread_goals] dispatching continuation turn"
);
- let mut agent = match Agent::from_config_for_agent(config, "orchestrator") {
+ let mut agent = match OpenHumanSessionHost::from_config_for_agent(config, "orchestrator") {
Ok(a) => a,
Err(e) => {
tracing::warn!(
diff --git a/crates/openhuman-core/src/agent/harness/README.md b/crates/openhuman-core/src/agent/harness/README.md
index 9022c764f7..be9e114103 100644
--- a/crates/openhuman-core/src/agent/harness/README.md
+++ b/crates/openhuman-core/src/agent/harness/README.md
@@ -57,9 +57,9 @@ iterations.
## Public surface
-- `Agent`, `AgentBuilder`, `TurnOverrides` — re-exported from `session`; the
+- `OpenHumanSessionHost`, `SessionHostBuilder`, `TurnOverrides` — re-exported from `session_host`; the
entry point for any chat turn. External callers import these from
- `crate::agent`, which re-exports them from `harness::session`.
+ `crate::agent`, which re-exports them from `session_host`.
- `run_subagent`, `SubagentRunOptions`, `SubagentRunError` — hierarchical
sub-agent dispatch from a parent tool loop.
- `AgentDefinition`, `AgentDefinitionRegistry`, `DefinitionSource`,
diff --git a/crates/openhuman-core/src/agent/harness/archivist/hook_impl.rs b/crates/openhuman-core/src/agent/harness/archivist/hook_impl.rs
index d4baa9cba3..c65fd25bdb 100644
--- a/crates/openhuman-core/src/agent/harness/archivist/hook_impl.rs
+++ b/crates/openhuman-core/src/agent/harness/archivist/hook_impl.rs
@@ -1,7 +1,7 @@
//! `PostTurnHook` implementation for `ArchivistHook`.
use super::helpers::extract_lesson_from_tools;
-use super::store::{record_turn, ArchivedTurn};
+use super::store::{ArchivedTurn, record_turn};
use super::types::ArchivistHook;
use crate::agent::hooks::{PostTurnHook, TurnContext};
use crate::memory::api::provider::EpisodicTurn;
diff --git a/crates/openhuman-core/src/agent/harness/archivist/lifecycle.rs b/crates/openhuman-core/src/agent/harness/archivist/lifecycle.rs
index 562b65ea91..0c68ad8334 100644
--- a/crates/openhuman-core/src/agent/harness/archivist/lifecycle.rs
+++ b/crates/openhuman-core/src/agent/harness/archivist/lifecycle.rs
@@ -2,7 +2,7 @@
//! `ArchivistHook`.
use super::boundary::{BoundaryConfig, BoundaryDecision};
-use super::events_heuristic::{extract_events_heuristic, ExtractedEventKind};
+use super::events_heuristic::{ExtractedEventKind, extract_events_heuristic};
use super::helpers::{extract_profile_key, uuid_v4};
use super::types::ArchivistHook;
use crate::config::Config;
@@ -137,7 +137,7 @@ impl ArchivistHook {
/// event extraction). This guarantees the trailing segment of a session
/// is always finalized even when no boundary-triggering turn arrives.
///
- /// Called at session end (see `Agent::spawn_session_memory_extraction`
+ /// Called at session end (see `OpenHumanSessionHost::spawn_session_memory_extraction`
/// in `session/turn.rs`). Safe to call multiple times — segment_close
/// is idempotent (only transitions `open → closed`).
pub async fn flush_open_segment(&self, session_id: &str) {
diff --git a/crates/openhuman-core/src/agent/harness/archivist/resummarise.rs b/crates/openhuman-core/src/agent/harness/archivist/resummarise.rs
index 7190b6a472..8fb8c502e1 100644
--- a/crates/openhuman-core/src/agent/harness/archivist/resummarise.rs
+++ b/crates/openhuman-core/src/agent/harness/archivist/resummarise.rs
@@ -24,8 +24,8 @@
use std::collections::HashMap;
use std::sync::Mutex;
-use super::lifecycle::recap_is_usable;
use super::ArchivistHook;
+use super::lifecycle::recap_is_usable;
use crate::memory::api::provider::episodic::EpisodicTurn;
/// Segments re-summarised in one pass.
diff --git a/crates/openhuman-core/src/agent/harness/archivist/store.rs b/crates/openhuman-core/src/agent/harness/archivist/store.rs
index 34abfc2cda..7009a56948 100644
--- a/crates/openhuman-core/src/agent/harness/archivist/store.rs
+++ b/crates/openhuman-core/src/agent/harness/archivist/store.rs
@@ -238,7 +238,7 @@ pub(super) fn record_turn(workspace: &Path, mut turn: ArchivedTurn) -> Result<Ar
Err(_) if path.exists() => continue,
Err(err) => {
return Err(err)
- .with_context(|| format!("failed to write episodic turn {}", path.display()))
+ .with_context(|| format!("failed to write episodic turn {}", path.display()));
}
}
}
diff --git a/crates/openhuman-core/src/agent/harness/artifact_offload/mod.rs b/crates/openhuman-core/src/agent/harness/artifact_offload/mod.rs
index 4ac02620a2..6ab1c771ed 100644
--- a/crates/openhuman-core/src/agent/harness/artifact_offload/mod.rs
+++ b/crates/openhuman-core/src/agent/harness/artifact_offload/mod.rs
@@ -56,17 +56,16 @@ use tinyagents_harness::artifacts::ArtifactOffload;
use crate::security::SecurityPolicy;
pub use contract::{
- render_artifact_offload_contract, should_render_offload_contract, ARTIFACT_OFFLOAD_HEADING,
- OFFLOAD_WRITE_TOOL,
+ ARTIFACT_OFFLOAD_HEADING, OFFLOAD_WRITE_TOOL, render_artifact_offload_contract,
+ should_render_offload_contract,
};
pub use policy::{SanitizingRedactor, WorkspaceGuard};
pub use tinyagents_harness::artifacts::{
- build_abstract, effective_offload_threshold, extract_artifact_paths, note_artifact_handoff,
- relative_to_root as relative_to_action_dir, render_artifact_pointer, resolve_artifact_path,
- sanitize_component, should_offload, ArtifactKind, ArtifactOffload as Offload, OffloadError,
- OffloadedArtifact, ABSTRACT_BUDGET_CHARS, ARTIFACT_POINTER_PREFIX,
+ ABSTRACT_BUDGET_CHARS, ARTIFACT_POINTER_PREFIX, ArtifactKind, ArtifactOffload as Offload,
DEFAULT_OFFLOAD_THRESHOLD_BYTES, HANDOFF_STAGE_CONSUMED, HANDOFF_STAGE_RECORDED, OUTPUTS_DIR,
- SCRATCH_DIR,
+ OffloadError, OffloadedArtifact, SCRATCH_DIR, build_abstract, effective_offload_threshold,
+ extract_artifact_paths, note_artifact_handoff, relative_to_root as relative_to_action_dir,
+ render_artifact_pointer, resolve_artifact_path, sanitize_component, should_offload,
};
/// Tool OpenHuman tells a parent to open an offloaded artifact with.
diff --git a/crates/openhuman-core/src/agent/harness/definition.rs b/crates/openhuman-core/src/agent/harness/definition.rs
index ad4e352c27..bdaaf7c8d9 100644
--- a/crates/openhuman-core/src/agent/harness/definition.rs
+++ b/crates/openhuman-core/src/agent/harness/definition.rs
@@ -34,14 +34,14 @@ mod subagents;
mod tier;
pub use agent_definition::{
- AgentDefinition, IterationPolicy, TriggerMemoryAgent, EXTENDED_MAX_TOOL_ITERATIONS,
+ AgentDefinition, EXTENDED_MAX_TOOL_ITERATIONS, IterationPolicy, TriggerMemoryAgent,
};
pub use execution_spec::{ModelSpec, SandboxMode, ToolScope};
pub use prompt_source::{PromptBuilder, PromptSource};
pub use registry::AgentDefinitionRegistry;
pub use source::DefinitionSource;
pub use subagents::{SkillsWildcard, SubagentEntry};
-pub use tier::{validate_tier_transition, AgentTier};
+pub use tier::{AgentTier, validate_tier_transition};
/// Sentinel used to represent an explicit zero-tool scope.
pub const NO_TOOLS_SENTINEL: &str = "__no_tools__";
diff --git a/crates/openhuman-core/src/agent/harness/definition/agent_definition.rs b/crates/openhuman-core/src/agent/harness/definition/agent_definition.rs
index 21275ba78c..dc674de8da 100644
--- a/crates/openhuman-core/src/agent/harness/definition/agent_definition.rs
+++ b/crates/openhuman-core/src/agent/harness/definition/agent_definition.rs
@@ -7,7 +7,7 @@ use serde::{Deserialize, Serialize};
use super::execution_spec::{ModelSpec, SandboxMode, ToolScope};
use super::prompt_source::PromptSource;
use super::source::DefinitionSource;
-use super::subagents::{deserialize_subagent_entries, SubagentEntry};
+use super::subagents::{SubagentEntry, deserialize_subagent_entries};
use super::tier::AgentTier;
use crate::inference::tokenjuice::AgentTokenjuiceCompression;
diff --git a/crates/openhuman-core/src/agent/harness/definition_loader.rs b/crates/openhuman-core/src/agent/harness/definition_loader.rs
index abb42f335a..e1468c5e4d 100644
--- a/crates/openhuman-core/src/agent/harness/definition_loader.rs
+++ b/crates/openhuman-core/src/agent/harness/definition_loader.rs
@@ -13,7 +13,7 @@
//! never breaks the rest of the system.
use super::definition::{AgentDefinition, DefinitionSource, PromptSource};
-use anyhow::{bail, Context, Result};
+use anyhow::{Context, Result, bail};
use std::fs;
use std::path::{Path, PathBuf};
diff --git a/crates/openhuman-core/src/agent/harness/fork_context.rs b/crates/openhuman-core/src/agent/harness/fork_context.rs
index 43696909d4..7ff9125ed9 100644
--- a/crates/openhuman-core/src/agent/harness/fork_context.rs
+++ b/crates/openhuman-core/src/agent/harness/fork_context.rs
@@ -3,7 +3,7 @@
//! the [`tinytools::Tool`] trait.
//!
//! [`PARENT_CONTEXT`] is set by the parent
-//! [`crate::agent::Agent`] around its `turn` so that any tool
+//! [`crate::agent::OpenHumanSessionHost`] around its `turn` so that any tool
//! executing inside that turn (in particular `spawn_subagent`) can read
//! the parent's provider, tool list, and model information.
//!
@@ -26,7 +26,7 @@ use tinytools::{Tool, ToolSpec};
// ─────────────────────────────────────────────────────────────────────────────
/// Snapshot of the parent agent's runtime, made available to any tool
-/// running inside [`crate::agent::Agent::turn`] via the
+/// running inside [`crate::agent::OpenHumanSessionHost::turn`] via the
/// [`PARENT_CONTEXT`] task-local.
///
/// All heavy fields are `Arc`-shared so cloning the context for sub-agents
@@ -183,7 +183,7 @@ tokio::task_local! {
/// Returns a clone of the current parent execution context, if one is set.
///
-/// Returns `None` when called from outside [`crate::agent::Agent::turn`]
+/// Returns `None` when called from outside [`crate::agent::OpenHumanSessionHost::turn`]
/// (e.g. CLI tool invocation).
pub fn current_parent() -> Option<ParentExecutionContext> {
PARENT_CONTEXT.try_with(|ctx| ctx.clone()).ok()
diff --git a/crates/openhuman-core/src/agent/harness/graph.rs b/crates/openhuman-core/src/agent/harness/graph.rs
index cb3eb3fe2c..2b6a6f6c19 100644
--- a/crates/openhuman-core/src/agent/harness/graph.rs
+++ b/crates/openhuman-core/src/agent/harness/graph.rs
@@ -34,8 +34,8 @@ use tokio::sync::mpsc::Sender;
use crate::agent::messages::ChatMessage;
use crate::agent::progress::AgentProgress;
-use crate::agent::tinyagents::run_turn_via_tinyagents_shared;
use crate::agent::tinyagents::TurnModelSource;
+use crate::agent::tinyagents::run_turn_via_tinyagents_shared;
use crate::config::{MultimodalConfig, MultimodalFileConfig};
use tinytools::Tool;
diff --git a/crates/openhuman-core/src/agent/harness/harness_tool_call_parsing_tests.rs b/crates/openhuman-core/src/agent/harness/harness_tool_call_parsing_tests.rs
index 6fe4744fb6..ed687cedec 100644
--- a/crates/openhuman-core/src/agent/harness/harness_tool_call_parsing_tests.rs
+++ b/crates/openhuman-core/src/agent/harness/harness_tool_call_parsing_tests.rs
@@ -535,10 +535,12 @@ fn parse_glm_style_browser_open_url() {
assert_eq!(calls.len(), 1);
assert_eq!(calls[0].0, "shell");
assert!(calls[0].1["command"].as_str().unwrap().contains("curl"));
- assert!(calls[0].1["command"]
- .as_str()
- .unwrap()
- .contains("example.com"));
+ assert!(
+ calls[0].1["command"]
+ .as_str()
+ .unwrap()
+ .contains("example.com")
+ );
}
#[test]
diff --git a/crates/openhuman-core/src/agent/harness/memory_protocol_tests.rs b/crates/openhuman-core/src/agent/harness/memory_protocol_tests.rs
index 78f53a4d60..1933209396 100644
--- a/crates/openhuman-core/src/agent/harness/memory_protocol_tests.rs
+++ b/crates/openhuman-core/src/agent/harness/memory_protocol_tests.rs
@@ -155,8 +155,9 @@ fn reads_and_other_ops_need_no_guidance() {
let mut t = MemoryProtocolTracker::new();
assert!(!t.observe_tool("memory_recall", &no_args()).needs_guidance());
assert!(!t.observe_tool("send_message", &no_args()).needs_guidance());
- assert!(t
- .observe_tool("memory_recall", &no_args())
- .guidance("memory_recall")
- .is_none());
+ assert!(
+ t.observe_tool("memory_recall", &no_args())
+ .guidance("memory_recall")
+ .is_none()
+ );
}
diff --git a/crates/openhuman-core/src/agent/harness/mod.rs b/crates/openhuman-core/src/agent/harness/mod.rs
index 3cb6bad22e..520ac62eb1 100644
--- a/crates/openhuman-core/src/agent/harness/mod.rs
+++ b/crates/openhuman-core/src/agent/harness/mod.rs
@@ -35,7 +35,6 @@ pub(crate) mod memory_context_safety;
pub(crate) mod memory_protocol;
pub(crate) mod required_output;
pub mod sandbox_context;
-pub mod session;
pub(crate) mod spawn_depth_context;
pub mod subagent_runner;
pub mod task_recency_context;
@@ -50,12 +49,12 @@ pub use definition::{
SandboxMode, ToolScope, TriggerMemoryAgent,
};
pub use fork_context::{
- current_agent_context_prepared_sources, current_parent, with_agent_context_prepared_sources,
- with_parent_context, AgentContextPreparedSource, ParentExecutionContext,
+ AgentContextPreparedSource, ParentExecutionContext, current_agent_context_prepared_sources,
+ current_parent, with_agent_context_prepared_sources, with_parent_context,
};
pub use sandbox_context::{current_sandbox_mode, with_current_sandbox_mode};
-pub(crate) use spawn_depth_context::{with_spawn_depth, MAX_SPAWN_DEPTH};
-pub use subagent_runner::{run_subagent, SubagentRunError, SubagentRunOptions};
+pub(crate) use spawn_depth_context::{MAX_SPAWN_DEPTH, with_spawn_depth};
+pub use subagent_runner::{SubagentRunError, SubagentRunOptions, run_subagent};
pub use task_recency_context::{current_task_recency_window, with_task_recency_window};
pub(crate) use graph::run_channel_turn_via_graph;
diff --git a/crates/openhuman-core/src/agent/harness/required_output.rs b/crates/openhuman-core/src/agent/harness/required_output.rs
index 02d0785e6e..dd0b8e33c1 100644
--- a/crates/openhuman-core/src/agent/harness/required_output.rs
+++ b/crates/openhuman-core/src/agent/harness/required_output.rs
@@ -57,11 +57,7 @@ pub(crate) fn find_required_block(
let has_all = keys
.iter()
.all(|key| obj.get(key).is_some_and(|v| !v.is_null()));
- if has_all {
- Some(first)
- } else {
- None
- }
+ if has_all { Some(first) } else { None }
}
/// A minimal, schema-valid block synthesised when the model omits the block and
@@ -85,7 +81,7 @@ pub(crate) fn synthesize_block(contract: &RequiredOutput) -> String {
/// satisfies the leading-position rule directly, whether the caller keeps the
/// re-prompt as the whole reply (the non-streamed *replace* path) or appends it
/// after prose that was already streamed (the *append* path); see
-/// `Agent::enforce_required_output`.
+/// `OpenHumanSessionHost::enforce_required_output`.
pub(crate) fn repair_instruction(contract: &RequiredOutput) -> String {
let keys = contract.all_keys().join("\", \"");
format!(
diff --git a/crates/openhuman-core/src/agent/harness/session/mod.rs b/crates/openhuman-core/src/agent/harness/session/mod.rs
deleted file mode 100644
index a04d1228e4..0000000000
--- a/crates/openhuman-core/src/agent/harness/session/mod.rs
+++ /dev/null
@@ -1,60 +0,0 @@
-//! Stateful agent session — the single execution tier.
-//!
-//! This module owns the [`Agent`] struct, which drives per-turn
-//! interaction with the provider, tool registry, memory system, and
-//! hook pipeline. It is the runtime the `channels`, `local_ai`, and
-//! `cron` layers invoke when they need a conversation to make
-//! progress.
-//!
-//! # Product shell over TinyAgents
-//!
-//! The model/tool iteration loop itself is **not** here: `turn` routes every
-//! chat turn through `turn::graph` into
-//! [`crate::agent::tinyagents::run_turn_via_tinyagents_shared`], the
-//! shared TinyAgents harness assembly. What this module keeps is the
-//! OpenHuman product shell around that loop — transcript persistence and
-//! legacy-format compatibility from `tinyagents_session::transcript`, prompt
-//! section assembly and KV-cache prefix stability, memory/context injection
-//! policy, post-turn hooks, and the persisted history shape. The migration
-//! plan for moving the durable parts onto TinyAgents store/cache primitives
-//! is `docs/tinyagents-harness-migration-audit.md`.
-//!
-//! # File layout
-//!
-//! | File | Role |
-//! |---------------|------------------------------------------------------------------|
-//! | [`types`] | `Agent` and `AgentBuilder` struct definitions (no logic). |
-//! | [`builder`] | `AgentBuilder` fluent API + `Agent::from_config` factory. |
-//! | [`turn`] | The `turn()` lifecycle, tool dispatch, context-pipeline wiring. |
-//! | [`runtime`] | Public accessors, `run_single` / `run_interactive`, helpers. |
-//! | `tests` | Integration tests (private). |
-//!
-//! External callers should import [`Agent`] and [`AgentBuilder`] from
-//! `crate::agent`, which re-exports them from this module.
-//! The child files are an implementation detail.
-
-pub(crate) use builder::provider_role_for_definition;
-
-mod builder;
-mod runtime;
-#[cfg(test)]
-mod tool_progress;
-mod turn;
-// `pub(crate)` since issue #6014: the tool-call-cap instruction is now appended
-// inside the loop by `tinyagents::middleware::FinalCallWrapUpMiddleware`, so the
-// harness-assembly site has to name it. It stays the one definition — the whole
-// point is that the in-loop conclusion and the out-of-band fallback ask for the
-// same thing.
-pub(crate) mod turn_checkpoint;
-mod types;
-
-#[cfg(test)]
-#[path = "session_tests.rs"]
-mod tests;
-
-pub use types::{Agent, AgentBuilder, TurnOverrides};
-
-// Re-export the duplicate-tool-spec guard for sibling harness modules
-// (`session::runtime`, `subagent_runner`) so all provider call sites
-// share one tested implementation.
-pub(crate) use builder::dedup_visible_tool_specs;
diff --git a/crates/openhuman-core/src/agent/harness/session/runtime/resume.rs b/crates/openhuman-core/src/agent/harness/session/runtime/resume.rs
deleted file mode 100644
index 7b5df7131b..0000000000
--- a/crates/openhuman-core/src/agent/harness/session/runtime/resume.rs
+++ /dev/null
@@ -1,235 +0,0 @@
-//! Cold-boot resume seeding: priming the next turn's LLM context from an
-//! external message log or from the full-fidelity `session_raw` transcript.
-
-use super::super::types::Agent;
-use anyhow::Result;
-
-impl Agent {
- /// Seed the next turn's LLM context from an authoritative message
- /// log (e.g. the web channel's per-thread conversation JSONL).
- ///
- /// Mirrors what [`Self::try_load_session_transcript`] does on a
- /// transcript-file hit, but sources from a caller-supplied list so
- /// resume works even when no transcript file exists for this
- /// agent name (the typical situation right after the
- /// `set_agent_definition_name` / `session_key` rename fix landed —
- /// existing transcripts are written under the old name).
- ///
- /// `messages` is `(role, content)` pairs in chronological order.
- /// Recognised roles: `"user"`, `"agent"` / `"assistant"`. Any
- /// trailing user message that exactly matches `current_user_message`
- /// is dropped — the caller is about to pass that text to
- /// [`Self::run_single`], which will append it to history itself, so
- /// keeping it here would duplicate it on the wire.
- ///
- /// No-ops if the agent already has a history or a cached transcript
- /// (i.e. the per-process session cache is warm). Intended only for
- /// cold-boot priming.
- pub fn seed_resume_from_messages(
- &mut self,
- messages: Vec<(String, String)>,
- current_user_message: &str,
- ) -> Result<()> {
- if !self.history.is_empty() || self.cached_transcript_messages.is_some() {
- return Ok(());
- }
- let mut prior = messages;
- if let Some(last) = prior.last() {
- if last.0 == "user" && last.1.trim() == current_user_message.trim() {
- prior.pop();
- }
- }
- if prior.is_empty() {
- return Ok(());
- }
-
- // Build the system prompt fresh — there's no persisted prefix
- // to preserve here, and learned-context decoration is skipped
- // intentionally so this fallback path stays synchronous and
- // doesn't fan out to the memory store on every cold-boot turn.
- let learned = crate::agent::prompts::LearnedContextData::default();
- let system_prompt = self.build_system_prompt(learned)?;
-
- let mut cached: Vec<crate::agent::messages::ChatMessage> =
- Vec::with_capacity(prior.len() + 1);
- cached.push(crate::agent::messages::ChatMessage::system(system_prompt));
- for (role, content) in prior {
- let chat = match role.as_str() {
- "user" => crate::agent::messages::ChatMessage::user(content),
- "agent" | "assistant" => crate::agent::messages::ChatMessage::assistant(content),
- // Fall back to user role for unknown senders rather than
- // dropping the message — losing context is worse than
- // mislabelling a system/tool message.
- _ => crate::agent::messages::ChatMessage::user(content),
- };
- cached.push(chat);
- }
-
- let cached_len_before = cached.len();
- let bounded = self.bound_cached_transcript_messages(cached);
- if bounded.len() < cached_len_before {
- log::warn!(
- "[agent] seed_resume_from_messages — bounded cached transcript {} → {} (max_history_messages={})",
- cached_len_before,
- bounded.len(),
- self.config.max_history_messages
- );
- }
- log::info!(
- "[agent] seed_resume_from_messages — primed cached transcript with {} prior messages",
- bounded.len().saturating_sub(1)
- );
- self.cached_transcript_messages = Some(bounded);
- Ok(())
- }
-
- /// Cold-boot resume for the web-chat path: pre-populate this session's
- /// LLM context from the **full-fidelity** `session_raw/{stem}.jsonl`
- /// transcript for `thread_id`.
- ///
- /// This is the high-fidelity counterpart to
- /// [`Self::seed_resume_from_messages`]. That fallback sources lossy
- /// `(sender, content)` prose from the conversation log, so it drops every
- /// tool call, tool-role result, and reasoning block — after an app restart
- /// the model then "forgets" all its tool interactions. This path instead
- /// routes thread → transcript via
- /// [`transcript::find_root_transcript_for_thread`] and reuses the exact
- /// [`transcript::read_transcript`] +
- /// [`Self::bound_cached_transcript_messages`] machinery as
- /// [`Self::try_load_session_transcript`], so `tool_calls`, `role:"tool"`
- /// messages, and `reasoning_content` all survive the round-trip. The only
- /// difference from `try_load_session_transcript` is the lookup key (thread
- /// id vs. per-thread agent name), so a thread whose transcript was written
- /// under a differently-scoped agent name still resumes.
- ///
- /// Returns `true` when a transcript was found, loaded, and seeded into
- /// `cached_transcript_messages`; `false` (a no-op) when the agent is already
- /// warm, no root transcript exists for the thread, the transcript is empty,
- /// or it fails to parse — the caller then falls back to prose-pair seeding.
- ///
- /// Best-effort like `try_load_session_transcript`: read/parse failures are
- /// logged and reported as `false` rather than propagated. The current turn's
- /// user message is appended later by [`Self::run_single`] / `turn`, so it is
- /// intentionally absent from the loaded prefix — no dedup is needed here (the
- /// on-disk transcript ends at the previous completed turn).
- ///
- /// Goes through the S4 seam like `try_load_session_transcript` (see its doc
- /// comment for why the read is `read_session` and not
- /// `ChatHistory::messages()`), via the locator's `root_for_thread` — the
- /// lookup that resolves by `_meta.thread_id` across *root* transcripts
- /// only. That disambiguation is why it is a locator method rather than
- /// anything a stem-bound handle could offer: several transcripts share one
- /// thread id (every sub-agent spawned within it does).
- pub fn seed_resume_from_thread_transcript(&mut self, thread_id: &str) -> bool {
- self.seed_resume_from_thread_transcript_scoped(thread_id, None)
- }
-
- /// [`Self::seed_resume_from_thread_transcript`], additionally scoped to
- /// `agent_id` (the calling agent's definition id) when given.
- ///
- /// A library host running several independently configured
- /// [`Runtime`](openhuman_embed) agents can hand two of them the same
- /// caller-supplied `thread_id` — nothing about the id namespace prevents
- /// it. Plain `thread_id` matching would then resume whichever agent's
- /// transcript is newest into the *other* agent's turn, splicing one
- /// agent's history (and its caller's data) into another's context.
- /// `agent_id` closes that by also requiring `_meta.agent_id` to match.
- ///
- /// `agent_id: None` keeps the original unscoped behaviour, used by the
- /// desktop orchestrator's web-channel resume, where a `thread_id` is
- /// driven by one logical agent (#5351).
- pub fn seed_resume_from_thread_transcript_scoped(
- &mut self,
- thread_id: &str,
- agent_id: Option<&str>,
- ) -> bool {
- if !self.history.is_empty() || self.cached_transcript_messages.is_some() {
- log::debug!(
- "[web-channel] seed_resume_from_thread_transcript no-op — agent already warm \
- (history_len={}, cached={}) thread={thread_id}",
- self.history.len(),
- self.cached_transcript_messages.is_some()
- );
- return false;
- }
-
- // The thread's conversation belongs to the thread. The locator reads
- // the canonical `session_raw/` store, and `agent_id` additionally
- // narrows to one agent's own transcripts — see
- // `FileTranscriptLocator::root_for_thread_scoped`.
- let Some(handle) = self
- .session_locator()
- .root_for_thread_scoped(thread_id, agent_id)
- else {
- log::debug!(
- "[web-channel] no root session_raw transcript for thread={thread_id} — falling back to \
- conversation-log prose seeding"
- );
- return false;
- };
- let path = handle.path().to_path_buf();
-
- log::info!(
- "[web-channel] cold-boot resume — loading full-fidelity transcript for \
- thread={thread_id} path={}",
- path.display()
- );
-
- match handle.read_session() {
- // `Ok(None)` (file vanished between discovery and read) folds into
- // the same empty-transcript branch, so the prose-seeding fallback
- // triggers identically.
- Ok(None) => {
- log::debug!(
- "[web-channel] root transcript for thread={thread_id} is empty — \
- falling back to prose seeding"
- );
- false
- }
- Ok(Some(session)) => {
- if session.messages.is_empty() {
- log::debug!(
- "[web-channel] root transcript for thread={thread_id} is empty — \
- falling back to prose seeding"
- );
- return false;
- }
- let loaded_count = session.messages.len();
- // Count the tool-role results carried into the resumed prefix —
- // the fidelity the prose fallback would have silently dropped.
- let tool_result_msgs = session.messages.iter().filter(|m| m.role == "tool").count();
- let replay = session
- .messages
- .into_iter()
- .map(crate::agent::messages::chat_message_from_transcript)
- .collect();
- let bounded = self.bound_cached_transcript_messages(replay);
- if bounded.len() < loaded_count {
- log::warn!(
- "[web-channel] resume prefix trimmed from {} to {} messages \
- (max_history_messages={}) for thread={thread_id}",
- loaded_count,
- bounded.len(),
- self.config.max_history_messages
- );
- }
- log::info!(
- "[web-channel] cold-boot resume — primed {} transcript message(s) \
- ({} tool-role result(s) preserved) for thread={thread_id}",
- bounded.len(),
- tool_result_msgs
- );
- self.cached_transcript_messages = Some(bounded);
- true
- }
- Err(err) => {
- log::warn!(
- "[web-channel] failed to parse root transcript {} for thread={thread_id}: \
- {err} — falling back to prose seeding",
- path.display()
- );
- false
- }
- }
- }
-}
diff --git a/crates/openhuman-core/src/agent/harness/session/runtime_tests.rs b/crates/openhuman-core/src/agent/harness/session/runtime_tests.rs
deleted file mode 100644
index 0e28558c9d..0000000000
--- a/crates/openhuman-core/src/agent/harness/session/runtime_tests.rs
+++ /dev/null
@@ -1,462 +0,0 @@
-use super::super::types::Agent;
-use crate::agent::error::AgentError;
-use crate::agent::messages::ChatMessage;
-use crate::agent::messages::ConversationMessage;
-use crate::core::events::DomainEvent;
-use crate::inference::provider::{ChatResponse, UsageInfo};
-use crate::memory::Memory;
-use anyhow::anyhow;
-use async_trait::async_trait;
-use parking_lot::Mutex;
-use std::sync::Arc;
-use tinyinference_llm::model::{
- ChatModel, ModelRequest, ModelResponse, ModelStream, ModelStreamItem,
-};
-use tinytools_agent::dialect::XmlDialect;
-use tokio::sync::Mutex as AsyncMutex;
-use tokio::time::{sleep, Duration};
-
-struct StaticModel {
- response: Mutex<Option<anyhow::Result<ChatResponse>>>,
-}
-
-#[async_trait]
-impl ChatModel<()> for StaticModel {
- async fn invoke(
- &self,
- _state: &(),
- request: ModelRequest,
- ) -> tinyinference_llm::Result<ModelResponse> {
- let response = self.response.lock().take().unwrap_or_else(|| {
- Ok(ChatResponse {
- text: Some("done".into()),
- tool_calls: vec![],
- usage: None,
- reasoning_content: None,
- })
- });
- match response {
- Ok(response) => Ok(
- crate::agent::tinyagents::model::native_model_response_for_request(
- &response, &request,
- ),
- ),
- Err(error) => Err(tinyinference_llm::Error::Model(error.to_string())),
- }
- }
-
- async fn stream(
- &self,
- state: &(),
- request: ModelRequest,
- ) -> tinyinference_llm::Result<ModelStream> {
- let response = self.invoke(state, request).await?;
- Ok(ModelStream::new(Box::pin(futures::stream::iter(vec![
- ModelStreamItem::Started,
- ModelStreamItem::Completed(response),
- ]))))
- }
-}
-
-/// Model that fails every call with the rendered form of a host [`AgentError`].
-///
-/// The default turn model (`chat-v1`) now carries a same-family cross-route
-/// fallback chain (`chat-v1 → burst-v1`, issue #4249 Workstream 02.2). A mock
-/// that errors only once (via `StaticModel`'s `take()`) would fail the primary
-/// route and then succeed on the fallback route, masking the terminal error. To
-/// exercise `run_single`'s error-surfacing path we need a model that fails on
-/// every route so the harness exhausts the chain and surfaces the message.
-struct PersistentErrModel {
- kind: PersistentErrKind,
-}
-
-#[derive(Clone, Copy)]
-enum PersistentErrKind {
- MaxIterations { max: usize },
- PermissionDenied,
-}
-
-impl PersistentErrModel {
- fn build_error(&self) -> anyhow::Error {
- match self.kind {
- PersistentErrKind::MaxIterations { max } => {
- anyhow!(AgentError::MaxIterationsExceeded { max })
- }
- PersistentErrKind::PermissionDenied => anyhow!(AgentError::PermissionDenied {
- tool_name: "shell".into(),
- required_level: "Execute".into(),
- channel_max_level: "ReadOnly".into(),
- }),
- }
- }
-}
-
-#[async_trait]
-impl ChatModel<()> for PersistentErrModel {
- async fn invoke(
- &self,
- _state: &(),
- _request: ModelRequest,
- ) -> tinyinference_llm::Result<ModelResponse> {
- Err(tinyinference_llm::Error::Model(
- self.build_error().to_string(),
- ))
- }
-}
-
-fn make_agent(model: Arc<dyn ChatModel<()>>) -> Agent {
- // The embedding seam fails loudly when unwired; before the memory
- // extraction this was a direct call and needed no setup.
- let workspace = tempfile::TempDir::new().expect("temp workspace");
- let workspace_path = workspace.path().to_path_buf();
- std::mem::forget(workspace);
- let _memory_cfg = crate::config::MemoryConfig {
- backend: "none".into(),
- ..crate::config::MemoryConfig::default()
- };
- let mem: Arc<dyn Memory> = crate::memory::test_support::noop_memory();
-
- Agent::builder()
- .chat_model(model)
- .tools(vec![])
- .memory(mem)
- .tool_dispatcher(Box::new(XmlDialect))
- .workspace_dir(workspace_path)
- .event_context("runtime-test-session", "runtime-test-channel")
- .build()
- .unwrap()
-}
-
-#[test]
-fn new_entries_for_turn_detects_prefix_overlap_and_fallbacks() {
- let history_snapshot = vec![
- ConversationMessage::Chat(ChatMessage::user("a")),
- ConversationMessage::Chat(ChatMessage::assistant("b")),
- ];
- let current_history = vec![
- ConversationMessage::Chat(ChatMessage::user("a")),
- ConversationMessage::Chat(ChatMessage::assistant("b")),
- ConversationMessage::Chat(ChatMessage::assistant("c")),
- ];
- let appended = Agent::new_entries_for_turn(&history_snapshot, &current_history);
- assert_eq!(appended.len(), 1);
-
- let shifted_history = vec![
- ConversationMessage::Chat(ChatMessage::assistant("b")),
- ConversationMessage::Chat(ChatMessage::assistant("c")),
- ];
- let overlap = Agent::new_entries_for_turn(&history_snapshot, &shifted_history);
- assert_eq!(overlap.len(), 1);
- assert!(matches!(&overlap[0], ConversationMessage::Chat(msg) if msg.content == "c"));
-}
-
-#[test]
-fn sanitizers_and_tool_call_helpers_cover_fallback_paths() {
- let err = anyhow!(AgentError::PermissionDenied {
- tool_name: "shell".into(),
- required_level: "Execute".into(),
- channel_max_level: "ReadOnly".into(),
- });
- assert_eq!(
- Agent::sanitize_event_error_message(&err),
- "permission_denied"
- );
-
- let generic = anyhow!("bad key sk-123456789012345678901234567890\nwith\twhitespace");
- let sanitized = Agent::sanitize_event_error_message(&generic);
- assert!(!sanitized.contains('\n'));
- assert!(!sanitized.contains('\t'));
-
- let calls = vec![
- tinytools_agent::ParsedToolCall {
- name: "a".into(),
- arguments: serde_json::json!({}),
- id: None,
- },
- tinytools_agent::ParsedToolCall {
- name: "b".into(),
- arguments: serde_json::json!({"x":1}),
- id: Some("keep".into()),
- },
- ];
- let calls = Agent::with_fallback_tool_call_ids(calls, 2);
- assert_eq!(calls[0].id.as_deref(), Some("parsed-3-1"));
- assert_eq!(calls[1].id.as_deref(), Some("keep"));
-
- let response = crate::inference::provider::ChatResponse {
- text: Some(String::new()),
- tool_calls: vec![],
- usage: None,
- reasoning_content: None,
- };
- let persisted = Agent::persisted_tool_calls_for_history(&response, &calls, 2);
- assert_eq!(persisted[0].id, "parsed-3-1");
- assert_eq!(persisted[1].id, "keep");
-
- let history = vec![
- ConversationMessage::AssistantToolCalls {
- text: None,
- tool_calls: vec![],
- reasoning_content: None,
- extra_metadata: None,
- },
- ConversationMessage::AssistantToolCalls {
- text: None,
- tool_calls: vec![],
- reasoning_content: None,
- extra_metadata: None,
- },
- ];
- assert_eq!(Agent::count_iterations(&history), 3);
-}
-
-#[test]
-fn run_single_preserves_native_model_error_text() {
- std::thread::Builder::new()
- .name("agent-runtime-error-test".into())
- .stack_size(32 * 1024 * 1024)
- .spawn(|| {
- tokio::runtime::Builder::new_current_thread()
- .enable_all()
- .build()
- .expect("test runtime")
- .block_on(async {
- // Host-generated user-state errors remain typed and therefore retain the
- // Sentry-suppression contract at their source.
- let typed = anyhow!(AgentError::MaxIterationsExceeded { max: 8 });
- assert!(matches!(
- typed.downcast_ref::<AgentError>(),
- Some(AgentError::MaxIterationsExceeded { max: 8 })
- ));
- assert_eq!(
- Agent::sanitize_event_error_message(&typed),
- "max_iterations_exceeded"
- );
-
- // A crate-native model error crosses the TinyAgents boundary as its
- // provider-neutral error type rather than a downcastable host error. Its
- // user-visible text must still remain intact.
- crate::core::bus::init().await.expect("bus init");
-
- let err_provider: Arc<dyn ChatModel<()>> = Arc::new(PersistentErrModel {
- kind: PersistentErrKind::MaxIterations { max: 8 },
- });
- let mut agent = make_agent(err_provider);
- let err = agent
- .run_single("hello")
- .await
- .expect_err("run_single should surface max-iter cap");
-
- // The user-visible chat string MUST stay byte-identical — the UI
- // (and `runtime_tool_calls.rs` channel test) reads this verbatim.
- assert!(
- err.to_string()
- .contains("Agent exceeded maximum tool iterations"),
- "canonical phrase missing: {err}"
- );
-
- assert!(
- err.downcast_ref::<AgentError>().is_none(),
- "model-boundary errors must not pretend to retain host types"
- );
- assert!(
- Agent::sanitize_event_error_message(&err)
- .contains("Agent exceeded maximum tool iterations"),
- "native error text should survive sanitization: {err}"
- );
- });
- })
- .expect("agent runtime test thread")
- .join()
- .expect("agent runtime test should not panic");
-}
-
-#[tokio::test]
-async fn run_single_publishes_completed_and_error_events() {
- crate::core::bus::init().await.expect("bus init");
- let events = Arc::new(AsyncMutex::new(Vec::<DomainEvent>::new()));
- let events_handler = Arc::clone(&events);
- let _handle = crate::core::bus::BUS
- .get()
- .unwrap()
- .on("runtime-events-test", move |event| {
- let events = Arc::clone(&events_handler);
- let cloned = event.clone();
- Box::pin(async move {
- events.lock().await.push(cloned);
- })
- });
-
- let ok_provider: Arc<dyn ChatModel<()>> = Arc::new(StaticModel {
- response: Mutex::new(Some(Ok(ChatResponse {
- text: Some("ok".into()),
- tool_calls: vec![],
- usage: Some(UsageInfo::default()),
- reasoning_content: None,
- }))),
- });
- let mut ok_agent = make_agent(ok_provider);
- let response = ok_agent.run_single("hello").await.expect("run_single ok");
- assert_eq!(response, "ok");
-
- let err_provider: Arc<dyn ChatModel<()>> = Arc::new(PersistentErrModel {
- kind: PersistentErrKind::PermissionDenied,
- });
- let mut err_agent = make_agent(err_provider);
- let err = err_agent
- .run_single("hello")
- .await
- .expect_err("run_single should publish error");
- assert!(err.to_string().contains("Permission denied"));
-
- sleep(Duration::from_millis(20)).await;
- let captured = events.lock().await;
- assert!(captured.iter().any(|event| matches!(
- event,
- DomainEvent::AgentTurnStarted { session_id, channel }
- if session_id == "runtime-test-session" && channel == "runtime-test-channel"
- )));
- assert!(captured.iter().any(|event| matches!(
- event,
- DomainEvent::AgentTurnCompleted {
- session_id,
- text_chars,
- iterations,
- } if session_id == "runtime-test-session" && *text_chars == 2 && *iterations >= 1
- )));
- assert!(captured.iter().any(|event| matches!(
- event,
- DomainEvent::AgentError {
- session_id,
- message,
- recoverable,
- } if session_id == "runtime-test-session"
- && message.contains("Permission denied")
- && !recoverable
- )));
-}
-
-#[test]
-fn accessors_and_history_reset_expose_agent_runtime_state() {
- let provider: Arc<dyn ChatModel<()>> = Arc::new(StaticModel {
- response: Mutex::new(None),
- });
- let mut agent = make_agent(provider);
- agent.history = vec![ConversationMessage::Chat(ChatMessage::system("sys"))];
- agent.workflows = vec![crate::skills::Workflow {
- name: "demo".into(),
- ..Default::default()
- }];
-
- assert_eq!(agent.event_session_id(), "runtime-test-session");
- assert_eq!(agent.event_channel(), "runtime-test-channel");
- assert_eq!(agent.tools().len(), 0);
- assert_eq!(agent.tool_specs().len(), 0);
- assert_eq!(agent.workspace_dir(), agent.workspace_dir.as_path());
- assert_eq!(agent.model_name(), agent.model_name);
- assert_eq!(agent.temperature(), agent.temperature);
- assert_eq!(agent.workflows().len(), 1);
- assert_eq!(
- agent.agent_config().max_tool_iterations,
- agent.config.max_tool_iterations
- );
- assert_eq!(agent.history().len(), 1);
- assert!(!agent.memory_arc().name().is_empty());
-
- agent.set_event_context("updated-session", "updated-channel");
- assert_eq!(agent.event_session_id(), "updated-session");
- assert_eq!(agent.event_channel(), "updated-channel");
-
- agent.clear_history();
- assert!(agent.history().is_empty());
- assert_eq!(Agent::count_iterations(agent.history()), 1);
-}
-
-#[test]
-fn helper_paths_cover_no_overlap_native_calls_and_truncation() {
- let history_snapshot = vec![ConversationMessage::Chat(ChatMessage::user("a"))];
- let current_history = vec![ConversationMessage::Chat(ChatMessage::assistant("b"))];
- let appended = Agent::new_entries_for_turn(&history_snapshot, &current_history);
- assert_eq!(appended.len(), 1);
- assert!(matches!(&appended[0], ConversationMessage::Chat(msg) if msg.content == "b"));
-
- let native_calls = vec![crate::inference::provider::ToolCall {
- id: "native-1".into(),
- name: "echo".into(),
- arguments: "{}".into(),
- extra_content: None,
- }];
- let response = crate::inference::provider::ChatResponse {
- text: Some(String::new()),
- tool_calls: native_calls.clone(),
- usage: None,
- reasoning_content: None,
- };
- let persisted = Agent::persisted_tool_calls_for_history(&response, &[], 0);
- assert_eq!(persisted.len(), 1);
- assert_eq!(persisted[0].id, native_calls[0].id);
- assert_eq!(persisted[0].name, native_calls[0].name);
-
- let long = anyhow!("{}", "x".repeat(400));
- let sanitized = Agent::sanitize_event_error_message(&long);
- assert!(sanitized.len() <= 256);
-}
-
-// ── Host capability accessors (plan-agents Phase 4) ──────────────────────────
-
-/// The memory-backed capabilities build from a bare-builder session.
-///
-/// These two are the adapters that need only `Arc<dyn Memory>`, which every
-/// session has however it was assembled — so they must work on the builder path
-/// too, not just behind the factory.
-#[tokio::test]
-async fn memory_backed_host_capabilities_build_from_session_state() {
- use tinyagents_harness::host::{AgentMemory, ExperienceStore};
-
- let model: Arc<dyn ChatModel<()>> = Arc::new(StaticModel {
- response: Mutex::new(None),
- });
- let agent = make_agent(model);
-
- // Exercised through the trait objects, not the concrete types: the point of
- // the accessor is that the runtime can hold `dyn AgentMemory`.
- let memory: &dyn AgentMemory = &agent.host_agent_memory();
- let recalled = memory
- .recall(tinyagents_harness::host::RecallRequest::new("anything"))
- .await
- .expect("recall must succeed against an empty backend");
- assert!(
- recalled.is_empty(),
- "a `backend = none` memory has nothing to recall"
- );
-
- let experience: &dyn ExperienceStore = &agent.host_experience_store();
- let prior = experience
- .recall_for("orchestrator", "some task")
- .await
- .expect("recall_for must succeed against an empty store");
- assert!(prior.is_empty(), "no experience has been recorded yet");
-}
-
-/// A bare-builder session reports its config-dependent capabilities as
-/// unavailable rather than pretending otherwise.
-///
-/// `host_capabilities_available()` is what keeps "this session cannot answer
-/// that" distinguishable from "the capability failed" — the same
-/// absence-versus-failure rule the traits are built on. The factory path sets
-/// the config (`factory.rs`); the builder path deliberately does not.
-#[tokio::test]
-async fn a_bare_builder_session_reports_config_capabilities_unavailable() {
- let model: Arc<dyn ChatModel<()>> = Arc::new(StaticModel {
- response: Mutex::new(None),
- });
- let agent = make_agent(model);
- assert!(
- agent.runtime_config().is_none(),
- "the bare builder path supplies no host Config"
- );
- assert!(
- !agent.host_capabilities_available(),
- "config-dependent capabilities must report unavailable, not be fabricated"
- );
-}
diff --git a/crates/openhuman-core/src/agent/harness/session/session_builder_and_listener_tests.rs b/crates/openhuman-core/src/agent/harness/session/session_builder_and_listener_tests.rs
deleted file mode 100644
index 8599d5b08e..0000000000
--- a/crates/openhuman-core/src/agent/harness/session/session_builder_and_listener_tests.rs
+++ /dev/null
@@ -1,661 +0,0 @@
-use super::*;
-
-/// Regression test for the `build_session_agent_inner` agent-id
-/// threading bug.
-///
-/// Prior to the fix, `build_session_agent_inner` took an `agent_id:
-/// &str` parameter but never threaded it into the `Agent::builder()`
-/// chain. The builder's `.build()` then fell back to the legacy
-/// `"main"` default, and every session built via
-/// `Agent::from_config_for_agent` carried `agent_definition_name =
-/// "main"` at runtime regardless of which id the caller asked for.
-///
-/// In the current codebase the user-facing path is `"orchestrator"`,
-/// and the same builder is also used by several direct session agents.
-/// A fallback to `"main"` silently misfiles transcripts on disk and
-/// stamps the wrong agent metadata into them. Typed sub-agents are
-/// unaffected because they're spawned through `subagent_runner` and
-/// never touch the `from_config_for_agent` / builder fallback path.
-///
-/// This test pins the builder contract the fix relies on: calling
-/// `.agent_definition_name(id)` on the builder chain produces an
-/// `Agent` whose [`Agent::agent_definition_name`] accessor returns
-/// that id verbatim. `"orchestrator"` covers the user-facing chat path;
-/// the others are defensive coverage so a future top-level caller still
-/// inherits the contract.
-#[test]
-fn agent_builder_threads_agent_definition_name_when_set() {
- for expected in ["integrations_agent", "orchestrator", "trigger_triage"] {
- let agent = build_minimal_agent_with_definition_name(Some(expected));
- assert_eq!(
- agent.agent_definition_name(),
- expected,
- "agent.agent_definition_name() should return the value passed to the builder"
- );
- }
-}
-
-/// Complementary to [`agent_builder_threads_agent_definition_name_when_set`]:
-/// when a caller builds an `Agent` without ever calling
-/// [`AgentBuilder::agent_definition_name`], the legacy `"main"`
-/// fallback still applies. This pins the fallback contract that
-/// direct builder users (tests, CLI harnesses) rely on, and
-/// documents the exact misbehaviour the threading fix prevents —
-/// `build_session_agent_inner` used to hit this fallback even when
-/// a caller asked for a concrete agent id, because the
-/// `.agent_definition_name` setter was missing from the builder chain.
-#[test]
-fn agent_builder_falls_back_to_main_when_definition_name_unset() {
- let agent = build_minimal_agent_with_definition_name(None);
- assert_eq!(
- agent.agent_definition_name(),
- "main",
- "AgentBuilder::build should default agent_definition_name to \"main\" when unset"
- );
-}
-
-#[test]
-fn set_connected_integrations_marks_session_initialized_and_updates_hash() {
- let mut agent = build_minimal_agent_with_definition_name(Some("orchestrator"));
- assert!(
- !agent.connected_integrations_initialized,
- "fresh builder-built agents should start with placeholder integration state"
- );
-
- agent.set_connected_integrations(vec![crate::agent::prompts::ConnectedIntegration {
- toolkit: "gmail".into(),
- description: "Email".into(),
- tools: vec![],
- gated_tools: vec![],
- connected: true,
- connections: Vec::new(),
- non_active_status: None,
- }]);
-
- assert!(agent.connected_integrations_initialized);
- assert_eq!(agent.connected_integrations().len(), 1);
- assert_eq!(agent.connected_integrations()[0].toolkit, "gmail");
- assert_eq!(
- agent.last_seen_integrations_hash,
- crate::integrations::composio::connected_set_hash(agent.connected_integrations())
- );
-}
-
-#[test]
-fn refresh_delegation_tools_updates_schema_even_when_tool_arc_is_shared() {
- use crate::agent::harness::AgentDefinitionRegistry;
-
- AgentDefinitionRegistry::init_global_builtins().unwrap();
- let mut agent = build_minimal_agent_with_definition_name(Some("orchestrator"));
- agent.set_connected_integrations(vec![crate::agent::prompts::ConnectedIntegration {
- toolkit: "gmail".into(),
- description: "Email".into(),
- tools: vec![],
- gated_tools: vec![],
- connected: true,
- connections: Vec::new(),
- non_active_status: None,
- }]);
-
- agent.refresh_delegation_tools();
- assert_eq!(
- integration_delegate_toolkit_enum(&agent),
- vec!["gmail".to_string()]
- );
-
- // Simulate an in-flight turn holding a shared Arc clone.
- let _shared_tools = agent.tools_arc();
- agent.set_connected_integrations(vec![
- crate::agent::prompts::ConnectedIntegration {
- toolkit: "gmail".into(),
- description: "Email".into(),
- tools: vec![],
- gated_tools: vec![],
- connected: true,
- connections: Vec::new(),
- non_active_status: None,
- },
- crate::agent::prompts::ConnectedIntegration {
- toolkit: "notion".into(),
- description: "Docs".into(),
- tools: vec![],
- gated_tools: vec![],
- connected: true,
- connections: Vec::new(),
- non_active_status: None,
- },
- ]);
-
- agent.refresh_delegation_tools();
- assert_eq!(
- integration_delegate_toolkit_enum(&agent),
- vec!["gmail".to_string(), "notion".to_string()]
- );
- // The schema moved; the executable instances must have moved with it.
- // Before #6145 the shared clone above blocked the instance reconcile and
- // only this assertion would have failed.
- super::assert_synthesized_delegates_are_executable(&agent);
-}
-
-/// Regression for #3044: repeated mid-session connects while the `tools`
-/// Arc stays shared (a detached sub-agent's cloned `ParentExecutionContext`
-/// outliving its turn) must not accumulate duplicate synthesised `ToolSpec`s.
-///
-/// Before the fix, a failed `tools` reconcile rolled `synthesized_tool_names`
-/// back to the *old* mask. On the next refresh the spec `retain` used that
-/// stale mask and failed to drop the intervening refresh's specs, so the
-/// synthesised delegate spec piled up once per connect.
-#[test]
-fn refresh_delegation_tools_no_duplicate_specs_across_shared_arc_connects() {
- use crate::agent::harness::AgentDefinitionRegistry;
-
- AgentDefinitionRegistry::init_global_builtins().unwrap();
- let mut agent = build_minimal_agent_with_definition_name(Some("orchestrator"));
-
- let conn = |slug: &str, desc: &str| crate::agent::prompts::ConnectedIntegration {
- toolkit: slug.into(),
- description: desc.into(),
- tools: vec![],
- gated_tools: vec![],
- connected: true,
- connections: Vec::new(),
- non_active_status: None,
- };
-
- let delegate_spec_count = |agent: &Agent| -> usize {
- agent
- .tool_specs()
- .iter()
- .filter(|s| s.name == "delegate_to_integrations_agent")
- .count()
- };
-
- // Turn 1: gmail connects.
- agent.set_connected_integrations(vec![conn("gmail", "Email")]);
- agent.refresh_delegation_tools();
-
- // Hold a shared clone across every subsequent refresh so `Arc::get_mut`
- // always fails — exactly what happens during an in-flight turn.
- let _shared_tools = agent.tools_arc();
-
- // Turn 2: notion connects mid-session.
- agent.set_connected_integrations(vec![conn("gmail", "Email"), conn("notion", "Docs")]);
- agent.refresh_delegation_tools();
-
- // Turn 3: slack connects mid-session — this is where the old code
- // produced a duplicate `delegate_to_integrations_agent` spec.
- agent.set_connected_integrations(vec![
- conn("gmail", "Email"),
- conn("notion", "Docs"),
- conn("slack", "Chat"),
- ]);
- agent.refresh_delegation_tools();
-
- assert_eq!(
- delegate_spec_count(&agent),
- 1,
- "exactly one synthesised delegate spec must remain after repeated shared-Arc connects"
- );
- assert_eq!(
- integration_delegate_toolkit_enum(&agent),
- vec![
- "gmail".to_string(),
- "notion".to_string(),
- "slack".to_string()
- ]
- );
- super::assert_synthesized_delegates_are_executable(&agent);
-}
-
-#[tokio::test]
-async fn composio_listener_drains_integrations_changed_events() {
- let mut agent = build_minimal_agent_with_definition_name(Some("orchestrator"));
- // Use an isolated bus, NOT the global singleton: other tests (e.g.
- // `events_tests` and any composio-listener publisher) emit
- // `ComposioIntegrationsChanged` on the global bus in parallel, which would
- // leak into this receiver and make the second drain observe a foreign
- // event — racing the "drained after one pass" assertion. Injecting a
- // locally-owned channel keeps this test deterministic.
- let isolated = crate::core::bus_testing::isolated_bus().await;
- agent.set_composio_integrations_rx_for_test(isolated.receiver());
- isolated.publish(DomainEvent::ComposioIntegrationsChanged {
- toolkits: vec!["gmail".into()],
- });
- assert!(agent.drain_composio_integrations_changed_events());
- assert!(
- !agent.drain_composio_integrations_changed_events(),
- "event queue should be drained after one pass"
- );
-}
-
-#[tokio::test]
-async fn skill_listener_drains_workflows_changed_events() {
- let mut agent = build_minimal_agent_with_definition_name(Some("orchestrator"));
- // Use an isolated bus, NOT the global singleton: other tests publish
- // `WorkflowsChanged` on the global bus in parallel — `skill_listener_
- // treats_lag_as_signal` floods 256 of them and
- // `create_workflow_inner_emits_workflows_changed` emits one — so a foreign
- // event could land between the two drains below and flip the second drain
- // to `true`, failing the "drained after one pass" assertion. Injecting a
- // locally-owned channel isolates this test from those publishers.
- let isolated = crate::core::bus_testing::isolated_bus().await;
- agent.set_skill_events_rx_for_test(isolated.receiver());
- isolated.publish(DomainEvent::WorkflowsChanged {
- reason: "install".into(),
- });
- assert!(
- agent.drain_skill_events(),
- "a WorkflowsChanged event should be observed"
- );
- assert!(
- !agent.drain_skill_events(),
- "event queue should be drained after one pass"
- );
-}
-
-#[tokio::test]
-async fn skill_listener_treats_lag_as_signal() {
- let mut agent = build_minimal_agent_with_definition_name(Some("orchestrator"));
- // Isolated bus (see `skill_listener_drains_workflows_changed_events` for
- // why the global singleton races). Flood well past the 64-slot bounded
- // channel so the receiver lags. The `Lagged` arm must still report a
- // signal (returns true) so a refresh isn't silently dropped under load.
- let isolated = crate::core::bus_testing::isolated_bus().await;
- agent.set_skill_events_rx_for_test(isolated.receiver());
- for _ in 0..256 {
- // Overruns the receiver's buffer on purpose: `try_recv` must then
- // report `Lagged`, which the drain treats as "something changed".
- isolated.publish(DomainEvent::WorkflowsChanged {
- reason: "install".into(),
- });
- }
- assert!(
- agent.drain_skill_events(),
- "a lagged listener must be treated as a signal"
- );
-}
-
-#[tokio::test]
-async fn skill_listener_closed_channel_nulls_rx_and_is_not_a_signal() {
- let mut agent = build_minimal_agent_with_definition_name(Some("orchestrator"));
- // A receiver whose sender has been dropped → `try_recv` yields `Closed`.
- let isolated = crate::core::bus_testing::isolated_bus().await;
- agent.set_skill_events_rx_for_test(isolated.receiver());
- // Dropping the bus drops its connection, which eventually closes the signal
- // stream. "Eventually" is the difference from a raw channel: the dispatch
- // task has to notice the transport is gone and exit before the broadcast
- // sender is released, so this polls rather than asserting immediately.
- drop(isolated);
- let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(5);
- while agent.has_skill_events_rx() {
- assert!(
- !agent.drain_skill_events(),
- "a closed channel is never a signal"
- );
- assert!(
- tokio::time::Instant::now() < deadline,
- "a closed receiver should be dropped so the next drain re-arms"
- );
- tokio::task::yield_now().await;
- }
-}
-
-/// Exercises real SKILL.md discovery from disk, so it is meaningful only with
-/// the `skills` domain compiled in — the disabled facade's
-/// `load_workflow_metadata` always returns an empty catalog by design.
-#[test]
-#[cfg(feature = "skills")]
-fn refresh_workflows_picks_up_skill_installed_on_disk() {
- // The embedding seam fails loudly when unwired; before the memory
- // extraction this was a direct call and needed no setup.
- use crate::skills::ops_types::{SKILL_MD, TRUST_MARKER};
-
- // Isolated, trusted workspace with one project-scope skill on disk.
- let ws = tempfile::TempDir::new().expect("temp workspace");
- let wsp = ws.path().to_path_buf();
- std::fs::create_dir_all(wsp.join(".openhuman")).unwrap();
- std::fs::write(wsp.join(".openhuman").join(TRUST_MARKER), "").unwrap();
- let skill_dir = wsp
- .join(".openhuman")
- .join("skills")
- .join("zz-refresh-test");
- std::fs::create_dir_all(&skill_dir).unwrap();
- std::fs::write(
- skill_dir.join(SKILL_MD),
- "---\nname: zz-refresh-test\ndescription: a refresh test skill\n---\n# body\n",
- )
- .unwrap();
-
- let _memory_cfg = crate::config::MemoryConfig {
- backend: "none".into(),
- ..crate::config::MemoryConfig::default()
- };
- let mem: Arc<dyn Memory> = crate::memory::test_support::noop_memory();
- let provider = Arc::new(MockProvider {
- responses: Mutex::new(vec![]),
- });
- let mut agent = Agent::builder()
- .chat_model(provider)
- .tools(vec![Box::new(MockTool)])
- .memory(mem)
- .tool_dispatcher(Box::new(NativeDialect))
- .workspace_dir(wsp.clone())
- .build()
- .expect("agent build should succeed");
-
- // Starts with no skills; refresh discovers the on-disk one and parks it
- // for announcement.
- assert!(agent.test_workflow_ids().is_empty());
- assert!(
- agent.refresh_workflows("test"),
- "installing a skill on disk should change the set"
- );
- assert!(
- agent
- .test_workflow_ids()
- .iter()
- .any(|id| id == "zz-refresh-test"),
- "the new skill should be discoverable"
- );
- assert!(
- agent
- .test_pending_skill_announcement()
- .iter()
- .any(|id| id == "zz-refresh-test"),
- "the new skill should be parked for announcement"
- );
- // Idempotent: no new install -> no change.
- assert!(
- !agent.refresh_workflows("test"),
- "no install since last refresh -> no change"
- );
-}
-
-/// See [`refresh_workflows_picks_up_skill_installed_on_disk`] — same
-/// disk-discovery dependency, so same `skills` gate.
-#[test]
-#[cfg(feature = "skills")]
-fn refresh_workflows_retracts_skill_removed_from_disk() {
- // The embedding seam fails loudly when unwired; before the memory
- // extraction this was a direct call and needed no setup.
- use crate::skills::ops_types::{SKILL_MD, TRUST_MARKER};
-
- let ws = tempfile::TempDir::new().expect("temp workspace");
- let wsp = ws.path().to_path_buf();
- std::fs::create_dir_all(wsp.join(".openhuman")).unwrap();
- std::fs::write(wsp.join(".openhuman").join(TRUST_MARKER), "").unwrap();
-
- // Write a skill to disk.
- let skill_dir = wsp
- .join(".openhuman")
- .join("skills")
- .join("zz-retract-test");
- std::fs::create_dir_all(&skill_dir).unwrap();
- std::fs::write(
- skill_dir.join(SKILL_MD),
- "---\nname: zz-retract-test\ndescription: a retraction test skill\n---\n# body\n",
- )
- .unwrap();
-
- let _memory_cfg = crate::config::MemoryConfig {
- backend: "none".into(),
- ..crate::config::MemoryConfig::default()
- };
- let mem: Arc<dyn Memory> = crate::memory::test_support::noop_memory();
- let provider = Arc::new(MockProvider {
- responses: Mutex::new(vec![]),
- });
- let mut agent = Agent::builder()
- .chat_model(provider)
- .tools(vec![Box::new(MockTool)])
- .memory(mem)
- .tool_dispatcher(Box::new(NativeDialect))
- .workspace_dir(wsp.clone())
- .build()
- .expect("agent build should succeed");
-
- // First refresh: picks up the installed skill.
- assert!(agent.refresh_workflows("test-install"));
- assert!(
- agent
- .test_workflow_ids()
- .iter()
- .any(|id| id == "zz-retract-test"),
- "skill should be in catalogue after first refresh"
- );
- assert!(
- agent
- .test_pending_skill_announcement()
- .iter()
- .any(|id| id == "zz-retract-test"),
- "skill should be parked for announcement"
- );
- // Now remove the skill from disk.
- std::fs::remove_dir_all(&skill_dir).unwrap();
-
- // Second refresh: detects the removal, parks the retraction.
- assert!(
- agent.refresh_workflows("test-remove"),
- "removing a skill should change the set"
- );
- assert!(
- !agent
- .test_workflow_ids()
- .iter()
- .any(|id| id == "zz-retract-test"),
- "skill should be gone from catalogue after removal"
- );
- assert!(
- agent
- .test_pending_skill_retraction()
- .iter()
- .any(|id| id == "zz-retract-test"),
- "removed skill should be parked for retraction"
- );
- // Retraction should have cleared it from announced_skills; re-install will
- // be announced fresh (not silently re-added). Verify by re-adding the skill
- // and confirming it gets announced again.
- std::fs::create_dir_all(&skill_dir).unwrap();
- std::fs::write(
- skill_dir.join(SKILL_MD),
- "---\nname: zz-retract-test\ndescription: a retraction test skill\n---\n# body\n",
- )
- .unwrap();
- assert!(agent.refresh_workflows("test-reinstall"));
- assert!(
- agent
- .test_pending_skill_announcement()
- .iter()
- .any(|id| id == "zz-retract-test"),
- "re-installed skill should be announced again after retraction cleared it from announced set"
- );
- // Re-install must also cancel the still-pending retraction so the user turn
- // never carries a contradictory "installed" + "retracted" pair for the same
- // skill.
- assert!(
- !agent
- .test_pending_skill_retraction()
- .iter()
- .any(|id| id == "zz-retract-test"),
- "re-install should cancel the pending retraction for the same skill"
- );
-}
-
-#[tokio::test]
-async fn turn_without_tools_returns_text() {
- // The embedding seam fails loudly when unwired; before the memory
- // extraction this was a direct call and needed no setup.
- let workspace = tempfile::TempDir::new().expect("temp workspace");
- let workspace_path = workspace.path().to_path_buf();
-
- let provider = Arc::new(MockProvider {
- responses: Mutex::new(vec![crate::inference::provider::ChatResponse {
- text: Some("hello".into()),
- tool_calls: vec![],
- usage: None,
- reasoning_content: None,
- }]),
- });
-
- let _memory_cfg = crate::config::MemoryConfig {
- backend: "none".into(),
- ..crate::config::MemoryConfig::default()
- };
- let mem: Arc<dyn Memory> = crate::memory::test_support::noop_memory();
-
- let mut agent = Agent::builder()
- .chat_model(provider)
- .tools(vec![Box::new(MockTool)])
- .memory(mem)
- .tool_dispatcher(Box::new(XmlDialect))
- .workspace_dir(workspace_path)
- .build()
- .unwrap();
-
- let response = agent.turn("hi").await.unwrap();
- assert_eq!(response, "hello");
-}
-
-/// The public [`Agent::last_turn_usage`] accessor peeks the per-turn
-/// token/cost totals **without draining** them, so a downstream crate
-/// embedding OpenHuman as a library (e.g. the OpenCompany hosting platform's
-/// cost-metering hook) can read usage after a turn while the existing
-/// web-channel `take_last_turn_usage_totals` drain path still works.
-#[tokio::test]
-async fn last_turn_usage_is_public_and_non_draining() {
- // The embedding seam fails loudly when unwired; before the memory
- // extraction this was a direct call and needed no setup.
- let workspace = tempfile::TempDir::new().expect("temp workspace");
- let workspace_path = workspace.path().to_path_buf();
-
- let provider = Arc::new(MockProvider {
- responses: Mutex::new(vec![crate::inference::provider::ChatResponse {
- text: Some("hello".into()),
- tool_calls: vec![],
- usage: Some(crate::inference::provider::UsageInfo {
- input_tokens: 123,
- output_tokens: 45,
- context_window: 8000,
- charged_amount_usd: 0.01,
- ..Default::default()
- }),
- reasoning_content: None,
- }]),
- });
-
- let _memory_cfg = crate::config::MemoryConfig {
- backend: "none".into(),
- ..crate::config::MemoryConfig::default()
- };
- let mem: Arc<dyn Memory> = crate::memory::test_support::noop_memory();
-
- let mut agent = Agent::builder()
- .chat_model(provider)
- .tools(vec![Box::new(MockTool)])
- .memory(mem)
- .tool_dispatcher(Box::new(XmlDialect))
- .workspace_dir(workspace_path)
- .build()
- .unwrap();
-
- // No turn has run yet — nothing to report.
- assert!(agent.last_turn_usage().is_none());
-
- let response = agent.turn("hi").await.unwrap();
- assert_eq!(response, "hello");
-
- // The accessor now yields totals, and the return type's fields are all
- // publicly readable (this closure would not compile if they were not).
- let peeked: crate::agent::tinyagents::host::LastTurnUsage = {
- let usage = agent
- .last_turn_usage()
- .expect("usage should be populated after a turn");
- crate::agent::tinyagents::host::LastTurnUsage {
- input_tokens: usage.input_tokens,
- output_tokens: usage.output_tokens,
- cached_input_tokens: usage.cached_input_tokens,
- cost_usd: usage.cost_usd,
- context_window: usage.context_window,
- subagents: usage.subagents.clone(),
- }
- };
-
- // Peeking must not consume: a second read returns the same snapshot.
- assert_eq!(agent.last_turn_usage(), Some(&peeked));
-
- // The internal web-channel drain still sees the very same value, proving
- // the borrow accessor left it untouched.
- let drained = agent
- .take_last_turn_usage_totals()
- .expect("drain should still yield the totals the borrow peeked");
- assert_eq!(drained, peeked);
-
- // After the drain the peek accessor reports nothing, as expected.
- assert!(agent.last_turn_usage().is_none());
-}
-
-/// Regression for #6145: a delegate tool that appears for the **first time**
-/// while the `tools` Arc is shared must be dispatchable, not just advertised.
-///
-/// This is the exact field scenario from the issue — an agent whose surface
-/// carried no `delegate_to_integrations_agent` at all, a mid-session Composio
-/// connect while a clone was held, and a refresh that logged
-/// `added=["delegate_to_integrations_agent"] tools_reconciled=false`. The spec
-/// was reconciled, the instance was not, and the policy snapshot — built from
-/// the instances — had no entry for it, so the fail-closed visibility filter
-/// hid the delegate: silently missing until a unique-owner refresh happened.
-#[test]
-fn newly_synthesized_delegate_is_executable_while_tool_arc_is_shared() {
- use crate::agent::harness::AgentDefinitionRegistry;
-
- AgentDefinitionRegistry::init_global_builtins().unwrap();
- let mut agent = build_minimal_agent_with_definition_name(Some("orchestrator"));
-
- // Turn 1 with nothing connected: no integration delegate exists yet.
- agent.refresh_delegation_tools();
- let advertised_before = agent
- .tool_specs()
- .iter()
- .any(|spec| spec.name == "delegate_to_integrations_agent");
- let executable_before = agent
- .synthesized_tools_arc()
- .iter()
- .any(|t| t.name() == "delegate_to_integrations_agent");
- assert_eq!(
- advertised_before, executable_before,
- "schema and instances must agree even before anything is connected"
- );
-
- // A detached sub-agent's cloned ParentExecutionContext holds a clone for
- // as long as it runs. `Arc::get_mut` would fail from here on — which is
- // what used to break the instance reconcile.
- let _shared_tools = agent.tools_arc();
-
- agent.set_connected_integrations(vec![crate::agent::prompts::ConnectedIntegration {
- toolkit: "gmail".into(),
- description: "Email".into(),
- tools: vec![],
- gated_tools: vec![],
- connected: true,
- connections: Vec::new(),
- non_active_status: None,
- }]);
- agent.refresh_delegation_tools();
-
- assert!(
- agent
- .tool_specs()
- .iter()
- .any(|spec| spec.name == "delegate_to_integrations_agent"),
- "the mid-session connect must publish the delegate spec"
- );
- assert!(
- agent
- .synthesized_tools_arc()
- .iter()
- .any(|t| t.name() == "delegate_to_integrations_agent"),
- "the delegate must also exist as an executable instance — a spec with \
- nothing registered to run it is #6145"
- );
- super::assert_synthesized_delegates_are_executable(&agent);
-}
diff --git a/crates/openhuman-core/src/agent/harness/session/session_builder_autoload_tests.rs b/crates/openhuman-core/src/agent/harness/session/session_builder_autoload_tests.rs
deleted file mode 100644
index e2018cbf76..0000000000
--- a/crates/openhuman-core/src/agent/harness/session/session_builder_autoload_tests.rs
+++ /dev/null
@@ -1,127 +0,0 @@
-//! `flows_build` must not open a new flow with another flow's builder session.
-//!
-//! Found by a real-token baseline run: a `flows_build` resumed the previous
-//! day's builder session, because the empty-history fallback
-//! (`try_load_session_transcript`) loads the newest transcript for the agent
-//! *name*, and every flow's builder is named `workflow_builder`.
-
-use super::*;
-use tinyagents_session::transcript::{
- SessionTranscript, TranscriptHistory, TranscriptLocator, TranscriptMeta, TranscriptRead,
-};
-
-const FLOW_A: &str = "flow A: forward my invoices to accounting";
-
-/// What a brand-new flow B sees on disk: flow A's builder transcript is the
-/// newest for the agent name, and nothing exists for B's thread.
-struct OtherFlowOnly {
- handle: Arc<FakeSessionHistory>,
-}
-
-impl TranscriptLocator for OtherFlowOnly {
- fn latest_for_agent(&self, _agent_name: &str) -> Option<Arc<dyn TranscriptRead>> {
- Some(self.handle.clone())
- }
-
- fn root_for_thread(&self, _thread_id: &str) -> Option<Arc<dyn TranscriptRead>> {
- None
- }
-
- fn open_stem(&self, _stem: &str, _seed: TranscriptMeta) -> Result<Arc<dyn TranscriptHistory>> {
- Ok(self.handle.clone())
- }
-}
-
-/// Records the text of every message sent to the model.
-#[derive(Default)]
-struct SeenText(Mutex<String>);
-
-#[async_trait]
-impl ChatModel<()> for SeenText {
- fn profile(&self) -> Option<&ModelProfile> {
- static PROFILE: std::sync::LazyLock<ModelProfile> =
- std::sync::LazyLock::new(ModelProfile::default);
- Some(&PROFILE)
- }
-
- async fn invoke(
- &self,
- _state: &(),
- request: ModelRequest,
- ) -> tinyinference_llm::Result<ModelResponse> {
- for message in &request.messages {
- self.0.lock().push_str(&message.text());
- }
- let response = ChatResponse {
- text: Some("ok".into()),
- tool_calls: vec![],
- usage: None,
- reasoning_content: None,
- };
- Ok(crate::agent::tinyagents::model::native_model_response_for_request(&response, &request))
- }
-
- async fn stream(
- &self,
- state: &(),
- request: ModelRequest,
- ) -> tinyinference_llm::Result<ModelStream> {
- let response = self.invoke(state, request).await?;
- Ok(ModelStream::new(Box::pin(futures::stream::iter(vec![
- ModelStreamItem::Started,
- ModelStreamItem::Completed(response),
- ]))))
- }
-}
-
-fn builder_agent(workspace: &std::path::Path) -> (Agent, Arc<SeenText>) {
- let handle = Arc::new(FakeSessionHistory {
- path: workspace.join("session_raw").join("flow_a.jsonl"),
- canned: Some(SessionTranscript {
- meta: fake_transcript_meta("thr_flow_a"),
- messages: durable_messages(vec![
- crate::agent::messages::ChatMessage::system("builder system prompt"),
- crate::agent::messages::ChatMessage::user(FLOW_A),
- crate::agent::messages::ChatMessage::assistant("proposed flow A"),
- ]),
- }),
- appended: Mutex::new(Vec::new()),
- });
- let model = Arc::new(SeenText::default());
- let agent = Agent::builder()
- .chat_model(model.clone())
- .tools(vec![Box::new(MockTool)])
- .memory(crate::memory::test_support::noop_memory())
- .tool_dispatcher(Box::new(NativeDialect))
- .agent_definition_name("workflow_builder")
- .workspace_dir(workspace.to_path_buf())
- .with_session_history_locator(Arc::new(OtherFlowOnly { handle }))
- .build()
- .expect("agent build should succeed");
- (agent, model)
-}
-
-#[tokio::test]
-async fn a_new_flow_builder_turn_does_not_resume_another_flows_session() {
- // Control: left alone, the by-name fallback splices flow A into the turn.
- // Without this the assertion below could pass on a fixture that never
- // reaches the request at all.
- let workspace = tempfile::TempDir::new().expect("temp workspace");
- let (mut agent, model) = builder_agent(workspace.path());
- agent.turn("build flow B").await.unwrap();
- assert!(
- model.0.lock().contains(FLOW_A),
- "fixture must reach the request through the by-name fallback"
- );
-
- let workspace = tempfile::TempDir::new().expect("temp workspace");
- let (mut agent, model) = builder_agent(workspace.path());
- crate::flows::ops::start_builder_turn_clean(&mut agent);
- agent.turn("build flow B").await.unwrap();
- let seen = model.0.lock().clone();
- assert!(seen.contains("build flow B"), "{seen}");
- assert!(
- !seen.contains(FLOW_A),
- "a new flow's builder turn carried another flow's session:\n{seen}"
- );
-}
diff --git a/crates/openhuman-core/src/agent/harness/session/session_dispatch_and_resume_tests.rs b/crates/openhuman-core/src/agent/harness/session/session_dispatch_and_resume_tests.rs
deleted file mode 100644
index f33312ce2b..0000000000
--- a/crates/openhuman-core/src/agent/harness/session/session_dispatch_and_resume_tests.rs
+++ /dev/null
@@ -1,713 +0,0 @@
-use super::*;
-
-#[tokio::test]
-async fn turn_with_native_dispatcher_handles_tool_results_variant() {
- // The embedding seam fails loudly when unwired; before the memory
- // extraction this was a direct call and needed no setup.
- let workspace = tempfile::TempDir::new().expect("temp workspace");
- let workspace_path = workspace.path().to_path_buf();
-
- let provider = Arc::new(MockProvider {
- responses: Mutex::new(vec![
- crate::inference::provider::ChatResponse {
- text: Some(String::new()),
- tool_calls: vec![crate::inference::provider::ToolCall {
- id: "tc1".into(),
- name: "echo".into(),
- arguments: "{}".into(),
- extra_content: None,
- }],
- usage: None,
- reasoning_content: None,
- },
- crate::inference::provider::ChatResponse {
- text: Some("done".into()),
- tool_calls: vec![],
- usage: None,
- reasoning_content: None,
- },
- ]),
- });
-
- let _memory_cfg = crate::config::MemoryConfig {
- backend: "none".into(),
- ..crate::config::MemoryConfig::default()
- };
- let mem: Arc<dyn Memory> = crate::memory::test_support::noop_memory();
-
- let mut agent = Agent::builder()
- .chat_model(provider)
- .tools(vec![Box::new(MockTool)])
- .memory(mem)
- .tool_dispatcher(Box::new(NativeDialect))
- .workspace_dir(workspace_path)
- .build()
- .unwrap();
-
- let response = agent.turn("hi").await.unwrap();
- assert_eq!(response, "done");
- assert!(agent
- .history()
- .iter()
- .any(|msg| matches!(msg, ConversationMessage::ToolResults(_))));
-}
-
-#[tokio::test]
-async fn turn_with_native_dispatcher_persists_fallback_tool_calls() {
- // The embedding seam fails loudly when unwired; before the memory
- // extraction this was a direct call and needed no setup.
- let workspace = tempfile::TempDir::new().expect("temp workspace");
- let workspace_path = workspace.path().to_path_buf();
-
- let provider = Arc::new(MockProvider {
- responses: Mutex::new(vec![
- crate::inference::provider::ChatResponse {
- text: Some(
- "Checking...\n<tool_call>{\"name\":\"echo\",\"arguments\":{}}</tool_call>"
- .into(),
- ),
- tool_calls: vec![],
- usage: None,
- reasoning_content: None,
- },
- crate::inference::provider::ChatResponse {
- text: Some("done".into()),
- tool_calls: vec![],
- usage: None,
- reasoning_content: None,
- },
- ]),
- });
-
- let _memory_cfg = crate::config::MemoryConfig {
- backend: "none".into(),
- ..crate::config::MemoryConfig::default()
- };
- let mem: Arc<dyn Memory> = crate::memory::test_support::noop_memory();
-
- let mut agent = Agent::builder()
- .chat_model(provider)
- .tools(vec![Box::new(MockTool)])
- .memory(mem)
- .tool_dispatcher(Box::new(NativeDialect))
- .workspace_dir(workspace_path)
- .build()
- .unwrap();
-
- let response = agent.turn("hi").await.unwrap();
- assert_eq!(response, "done");
-
- let persisted_calls = agent
- .history()
- .iter()
- .find_map(|msg| match msg {
- ConversationMessage::AssistantToolCalls { tool_calls, .. } => Some(tool_calls),
- _ => None,
- })
- .expect("assistant tool calls should be persisted");
- assert_eq!(persisted_calls.len(), 1);
- assert_eq!(persisted_calls[0].name, "echo");
-}
-
-/// End-to-end: parent Agent issues a `spawn_subagent` tool call, the
-/// runner dispatches a built-in sub-agent (`researcher`) using the
-/// same MockProvider, and the parent's next turn folds the sub-agent's
-/// text output into the final response.
-///
-/// This is the highest-level test that exercises:
-/// - Agent::turn → execute_tool_call → SpawnSubagentTool::execute
-/// - PARENT_CONTEXT task-local visibility
-/// - AgentDefinitionRegistry::global lookup
-/// - run_subagent → run_inner_loop with the parent's provider
-/// - Result returned as a ToolResult and threaded back into history
-///
-/// Uses the `#[cfg(test)]`-only `__test_inherit_echo` sub-agent
-/// (`ModelSpec::Inherit`) rather than `researcher`. After #1710,
-/// sub-agents with a `Hint(workload)` spec build a fresh provider via
-/// `create_chat_provider(...)` and therefore can't share this test's
-/// `MockProvider` — so a Hint sub-agent here would leak the scripted
-/// chain. `Inherit` keeps `parent.provider`, which is exactly the
-/// plumbing this test asserts. Provider *routing* for Hint sub-agents
-/// is covered independently by
-/// `subagent_runner::ops::tests::resolve_subagent_source_*`.
-// The full spawn_subagent path (parent turn → run_subagent → nested agent
-// turn) is a deep async state machine. In debug/coverage builds each future
-// frame is large, and the two stacked turns exceed the default ~2 MiB libtest
-// per-test thread stack — the thread overflows and SIGABRTs the *entire* test
-// process. Because libtest runs tests concurrently, the abort then tags
-// whichever unrelated test happened to be in flight as FAILED, producing the
-// run-to-run flake reported in issue #5209 (the experience-recall test was the
-// most frequent victim). CI only avoided this by exporting a 64 MiB
-// `RUST_MIN_STACK`; a raw `cargo test` (e.g. the diff-scoped coverage command)
-// has no such env and reliably overflows. Production already drives agent
-// turns on an explicit large stack for this exact reason
-// (`agent::bus::handle_agent_run_turn_on_large_stack`). Mirror that here so the
-// test is self-contained and never aborts the process, regardless of
-// `RUST_MIN_STACK`.
-#[test]
-fn turn_dispatches_spawn_subagent_through_full_path() {
- std::thread::Builder::new()
- .name("spawn-subagent-full-path-test".to_string())
- .stack_size(64 * 1024 * 1024)
- .spawn(|| {
- tokio::runtime::Builder::new_current_thread()
- .enable_all()
- .build()
- .expect("build large-stack test runtime")
- .block_on(turn_dispatches_spawn_subagent_through_full_path_inner());
- })
- .expect("spawn large-stack test thread")
- .join()
- .expect("large-stack spawn_subagent test thread panicked");
-}
-
-/// KV-cache invariant: across multiple turns in the same session, the
-/// system-prompt bytes submitted to the provider must be byte-identical,
-/// and the model name must not flip. Both are required for the backend's
-/// automatic prefix cache to hit — if either changes, the backend must
-/// re-prefill the entire prompt every turn.
-///
-/// This test guards against two regressions:
-/// 1. A future edit that reintroduces the subsequent-turn system
-/// prompt rebuild (see the `learning_enabled` branch we
-/// deliberately removed in `turn()`).
-/// 2. A future edit that reintroduces per-message model
-/// classification on the main agent (which would flip the
-/// effective model between turns).
-#[tokio::test]
-async fn system_prompt_and_model_are_byte_stable_across_turns() {
- // The embedding seam fails loudly when unwired; before the memory
- // extraction this was a direct call and needed no setup.
- let workspace = tempfile::TempDir::new().expect("temp workspace");
- let workspace_path = workspace.path().to_path_buf();
-
- let provider = Arc::new(RecordingProvider {
- responses: Mutex::new(vec![
- crate::inference::provider::ChatResponse {
- text: Some("first".into()),
- tool_calls: vec![],
- usage: None,
- reasoning_content: None,
- },
- crate::inference::provider::ChatResponse {
- text: Some("second".into()),
- tool_calls: vec![],
- usage: None,
- reasoning_content: None,
- },
- crate::inference::provider::ChatResponse {
- text: Some("third".into()),
- tool_calls: vec![],
- usage: None,
- reasoning_content: None,
- },
- ]),
- captures: Mutex::new(Vec::new()),
- });
-
- let _memory_cfg = crate::config::MemoryConfig {
- backend: "none".into(),
- ..crate::config::MemoryConfig::default()
- };
- let mem: Arc<dyn Memory> = crate::memory::test_support::noop_memory();
-
- let mut agent = Agent::builder()
- .chat_model(provider.clone() as Arc<dyn ChatModel<()>>)
- .tools(vec![])
- .memory(mem)
- .tool_dispatcher(Box::new(NativeDialect))
- .workspace_dir(workspace_path)
- // Learning flag is explicitly enabled to prove that the
- // former "rebuild system prompt on subsequent turns" branch
- // is gone — we should still see byte-stable prompts.
- .learning_enabled(true)
- .build()
- .unwrap();
-
- for prompt in ["first question", "second question", "third question"] {
- agent.turn(prompt).await.unwrap();
- }
-
- let captures = provider.captures.lock().clone();
- assert_eq!(
- captures.len(),
- 3,
- "expected one provider call per turn, got {}",
- captures.len()
- );
-
- let first_system = captures[0]
- .system_prompt
- .as_ref()
- .expect("first turn should have a system prompt");
- for (idx, cap) in captures.iter().enumerate() {
- let sys = cap
- .system_prompt
- .as_ref()
- .expect("every turn should carry the system prompt");
- assert_eq!(
- sys, first_system,
- "system prompt drifted on turn {} — KV cache prefix broken",
- idx
- );
- assert_eq!(
- cap.model, captures[0].model,
- "model name flipped on turn {} — KV cache namespace broken",
- idx
- );
- assert!(
- !sys.contains("<!-- CACHE_BOUNDARY -->"),
- "system prompt should not leak any cache-boundary marker"
- );
- }
-}
-
-/// Regression test for the per-thread transcript resume bug.
-///
-/// `set_agent_definition_name` is called by the web channel after
-/// `Agent::from_config_for_agent("orchestrator")` returns, to scope
-/// transcripts per thread (e.g. `"orchestrator_thread-6ad6d"`). Prior
-/// to the fix this only updated `agent_definition_name` and left
-/// `session_key` pointing at the builder-time name. Persist would
-/// then write `session_raw/<ts>_orchestrator.jsonl` while resume
-/// searched for `session_raw/<ts>_orchestrator_thread-6ad6d.jsonl`,
-/// so every cold-boot turn ran against an empty transcript and the
-/// LLM had no conversation history.
-///
-/// This test pins the contract: after `set_agent_definition_name`,
-/// `session_key`'s suffix matches the new (sanitised) name so the
-/// next persist+resume pair land on the same file.
-#[test]
-fn set_agent_definition_name_rewrites_session_key_suffix() {
- let agent_first = build_minimal_agent_with_definition_name(Some("orchestrator"));
- let original_key = agent_first.session_key().to_string();
- assert!(
- original_key.ends_with("_orchestrator"),
- "builder should seed session_key suffix from agent_definition_name; got {original_key}"
- );
-
- let mut agent = build_minimal_agent_with_definition_name(Some("orchestrator"));
- let prefix = agent
- .session_key()
- .split_once('_')
- .map(|(p, _)| p.to_string())
- .expect("session_key must have a `<ts>_<suffix>` shape");
-
- agent.set_agent_definition_name("orchestrator_thread-6ad6d");
-
- assert_eq!(agent.agent_definition_name(), "orchestrator_thread-6ad6d");
- assert_eq!(
- agent.session_key(),
- format!("{prefix}_orchestrator_thread-6ad6d"),
- "session_key suffix must track agent_definition_name so transcript persist + \
- resume agree on the file path"
- );
-}
-
-/// `set_agent_definition_name` must sanitise non-allowed characters in
-/// the new name (matching the builder's policy) so `session_key`
-/// never contains anything that would escape the `session_raw/`
-/// directory or break filename parsing on disk.
-#[test]
-fn set_agent_definition_name_sanitises_unsafe_characters() {
- let mut agent = build_minimal_agent_with_definition_name(Some("orchestrator"));
- agent.set_agent_definition_name("orch/../../etc/passwd thread-6ad6d");
- assert!(
- !agent.session_key().contains('/'),
- "session_key must never contain path separators; got {}",
- agent.session_key()
- );
- assert!(
- !agent.session_key().contains(' '),
- "session_key must never contain whitespace; got {}",
- agent.session_key()
- );
-}
-
-/// Cold-boot resume from the conversation JSONL works even when no
-/// matching transcript file exists. The web channel calls
-/// `seed_resume_from_messages` on the cache-miss path so the agent
-/// sees prior conversation context immediately, instead of having to
-/// wait for a transcript to be persisted under the new
-/// thread-scoped name.
-#[test]
-fn seed_resume_from_messages_primes_cached_transcript() {
- let mut agent = build_minimal_agent_with_definition_name(Some("orchestrator"));
- let prior = vec![
- ("user".to_string(), "what is btc price".to_string()),
- ("agent".to_string(), "$80,000".to_string()),
- // Trailing user message that the caller is about to pass to
- // run_single — must be deduped from the cached prefix.
- ("user".to_string(), "what did i just ask".to_string()),
- ];
- agent
- .seed_resume_from_messages(prior, "what did i just ask")
- .expect("seed");
-
- let cached = agent
- .cached_transcript_messages
- .as_ref()
- .expect("cache populated");
- // [system, user(btc), agent(80k)] — trailing user was deduped.
- assert_eq!(cached.len(), 3);
- assert_eq!(cached[0].role, "system");
- assert_eq!(cached[1].role, "user");
- assert_eq!(cached[1].content, "what is btc price");
- assert_eq!(cached[2].role, "assistant");
- assert_eq!(cached[2].content, "$80,000");
-}
-
-/// `seed_resume_from_messages` must not stomp the existing context if
-/// the agent has already been warmed (in-process session cache hit).
-/// Otherwise the cache-miss branch in the web channel would erase
-/// real progress whenever the caller defensively invoked seeding.
-#[test]
-fn seed_resume_from_messages_is_noop_on_warm_agent() {
- let mut agent = build_minimal_agent_with_definition_name(Some("orchestrator"));
- agent.cached_transcript_messages = Some(vec![
- crate::agent::messages::ChatMessage::system("warm prefix"),
- crate::agent::messages::ChatMessage::user("hi"),
- ]);
- agent
- .seed_resume_from_messages(vec![("user".into(), "different".into())], "different")
- .expect("seed");
- let cached = agent
- .cached_transcript_messages
- .as_ref()
- .expect("still populated");
- assert_eq!(cached.len(), 2);
- assert_eq!(cached[0].content, "warm prefix");
-}
-
-/// Trailing user message that does NOT match the current incoming
-/// message must be preserved — the dedup heuristic only fires on
-/// exact match because the conversation JSONL is the source of truth
-/// and may legitimately contain back-to-back user messages (e.g. the
-/// thread-7242c case where an interrupted turn left the prior user
-/// message un-replied).
-#[test]
-fn seed_resume_from_messages_preserves_unmatched_trailing_user() {
- let mut agent = build_minimal_agent_with_definition_name(Some("orchestrator"));
- let prior = vec![
- ("user".to_string(), "earlier question".to_string()),
- ("agent".to_string(), "earlier answer".to_string()),
- ("user".to_string(), "stranded follow-up".to_string()),
- ];
- agent
- .seed_resume_from_messages(prior, "completely different new turn")
- .expect("seed");
- let cached = agent
- .cached_transcript_messages
- .as_ref()
- .expect("cache populated");
- // [system, user, agent, user] — trailing kept because it doesn't
- // match the current turn's user input.
- assert_eq!(cached.len(), 4);
- assert_eq!(cached[3].role, "user");
- assert_eq!(cached[3].content, "stranded follow-up");
-}
-
-#[test]
-fn seed_resume_from_messages_respects_history_window_bound() {
- let mut agent = build_minimal_agent_with_definition_name(Some("orchestrator"));
- agent.config.max_history_messages = 4;
- let prior = vec![
- ("user".to_string(), "u1".to_string()),
- ("agent".to_string(), "a1".to_string()),
- ("user".to_string(), "u2".to_string()),
- ("agent".to_string(), "a2".to_string()),
- ("user".to_string(), "u3".to_string()),
- ("agent".to_string(), "a3".to_string()),
- ];
- agent
- .seed_resume_from_messages(prior, "new turn")
- .expect("seed");
-
- let cached = agent
- .cached_transcript_messages
- .as_ref()
- .expect("cache populated");
- // max_history_messages=4 keeps [system + last 3 messages].
- assert_eq!(cached.len(), 4);
- assert_eq!(cached[0].role, "system");
- assert_eq!(cached[1].content, "a2");
- assert_eq!(cached[2].content, "u3");
- assert_eq!(cached[3].content, "a3");
-}
-
-#[test]
-fn bound_cached_transcript_messages_without_system_prefix_keeps_tail() {
- let mut agent = build_minimal_agent_with_definition_name(Some("orchestrator"));
- agent.config.max_history_messages = 3;
-
- let messages = vec![
- crate::agent::messages::ChatMessage::user("u1"),
- crate::agent::messages::ChatMessage::assistant("a1"),
- crate::agent::messages::ChatMessage::user("u2"),
- crate::agent::messages::ChatMessage::assistant("a2"),
- crate::agent::messages::ChatMessage::user("u3"),
- ];
- let bounded = agent.bound_cached_transcript_messages(messages);
- assert_eq!(bounded.len(), 3);
- assert_eq!(bounded[0].content, "u2");
- assert_eq!(bounded[1].content, "a2");
- assert_eq!(bounded[2].content, "u3");
-}
-
-/// The cached-transcript resume path operates on wire-form `ChatMessage`s. When
-/// the window cut lands so the tail opens on a `tool` result whose `tool_calls`
-/// opener fell outside the window, `bound_cached_transcript_messages` must snap
-/// past it — a leading `tool` message has no preceding `tool_calls` and the
-/// provider 400s (surfacing as "Something went wrong").
-#[test]
-fn bound_cached_transcript_messages_snaps_past_leading_orphan_tool() {
- use crate::agent::messages::ChatMessage;
-
- let mut agent = build_minimal_agent_with_definition_name(Some("orchestrator"));
- agent.config.max_history_messages = 3;
-
- // 5 messages, cap 3: the tail slice is [tool(a), user(u2), assistant(a2)];
- // the assistant `tool_calls` opener fell outside the window.
- let messages = vec![
- ChatMessage::assistant(
- r#"{"content":"calling","tool_calls":[{"id":"call_a","name":"shell","arguments":"{}"}]}"#,
- ),
- ChatMessage::tool(r#"{"tool_call_id":"call_a","content":"orphaned"}"#),
- ChatMessage::user("u2"),
- ChatMessage::assistant("a2"),
- ChatMessage::user("u3"),
- ];
-
- let bounded = agent.bound_cached_transcript_messages(messages);
-
- assert!(
- bounded.first().map(|m| m.role.as_str()) != Some("tool"),
- "window must not open on an orphaned tool result"
- );
- assert!(
- !bounded.iter().any(|m| m.role == "tool"),
- "the orphaned tool result must be dropped"
- );
- // tail [tool, u2, a2, u3] -> drop leading tool -> [u2, a2, u3].
- assert_eq!(
- bounded
- .iter()
- .map(|m| m.content.as_str())
- .collect::<Vec<_>>(),
- vec!["u2", "a2", "u3"]
- );
-}
-
-/// A durable tool with a caller-chosen name, for the tests that pin how the
-/// durable registry and the synthesised delegation set relate.
-struct NamedTool(&'static str);
-
-#[async_trait]
-impl Tool for NamedTool {
- /// The caller-chosen name.
- fn name(&self) -> &str {
- self.0
- }
-
- /// Fixed marker text, so a test can tell it from a synthesised delegate.
- fn description(&self) -> &str {
- "durable"
- }
-
- /// A schema no synthesised delegate produces, so a spec can be attributed.
- fn parameters_schema(&self) -> serde_json::Value {
- serde_json::json!({"type": "object", "properties": {"durable": {"type": "boolean"}}})
- }
-
- /// Returns a fixed success; dispatch itself is not under test here.
- async fn execute(&self, _args: serde_json::Value) -> Result<tinytools::ToolResult> {
- Ok(tinytools::ToolResult::success("durable"))
- }
-}
-
-/// A connected Composio toolkit with the given slug, for driving refreshes.
-fn connected(slug: &str) -> crate::agent::prompts::ConnectedIntegration {
- crate::agent::prompts::ConnectedIntegration {
- toolkit: slug.into(),
- description: slug.into(),
- tools: vec![],
- gated_tools: vec![],
- connected: true,
- connections: Vec::new(),
- non_active_status: None,
- }
-}
-
-/// Regression for #6145, revoke direction: a delegate whose toolkit was
-/// disconnected must leave the executable set and the policy snapshot in the
-/// same pass its spec is withdrawn, even while an in-flight turn holds clones.
-///
-/// This was the damaging half of the drift: the spec went, but the instance
-/// stayed in the shared `tools` Arc, the policy session built from that Arc
-/// kept allowing it, and the adapter registered from it kept advertising it —
-/// so a disconnected integration's delegate remained callable.
-#[test]
-fn revoked_delegate_leaves_instances_and_policy_with_its_spec_while_tool_arc_is_shared() {
- use crate::agent::harness::AgentDefinitionRegistry;
- const DELEGATE: &str = "delegate_to_integrations_agent";
-
- AgentDefinitionRegistry::init_global_builtins().unwrap();
- let mut agent = build_minimal_agent_with_definition_name(Some("orchestrator"));
-
- agent.set_connected_integrations(vec![connected("gmail"), connected("notion")]);
- agent.refresh_delegation_tools();
- assert_eq!(
- integration_delegate_toolkit_enum(&agent),
- vec!["gmail".to_string(), "notion".to_string()]
- );
-
- // An in-flight turn holds both sets for its whole duration.
- let _durable_in_flight = agent.tools_arc();
- let synthesized_in_flight = agent.synthesized_tools_arc();
-
- // notion is disconnected: the enum shrinks and the instance follows it.
- agent.set_connected_integrations(vec![connected("gmail")]);
- agent.refresh_delegation_tools();
- assert_eq!(
- integration_delegate_toolkit_enum(&agent),
- vec!["gmail".to_string()]
- );
- super::assert_synthesized_delegates_are_executable(&agent);
-
- // Everything is disconnected: the delegate leaves every surface at once.
- agent.set_connected_integrations(Vec::new());
- agent.refresh_delegation_tools();
- assert!(
- !agent.tool_specs().iter().any(|spec| spec.name == DELEGATE),
- "the withdrawn delegate must not keep a spec"
- );
- assert!(
- !agent
- .synthesized_tools_arc()
- .iter()
- .any(|tool| tool.name() == DELEGATE),
- "the executable instance must go with the spec — this is what stayed \
- behind before #6145"
- );
- assert!(!agent
- .all_tool_refs()
- .iter()
- .any(|tool| tool.name() == DELEGATE));
- assert!(
- !agent.tool_policy_session.is_allowed(DELEGATE)
- && !agent.tool_policy_session.decisions.contains_key(DELEGATE),
- "a withdrawn delegate must not keep a policy allowance"
- );
- super::assert_synthesized_delegates_are_executable(&agent);
-
- // The turn that started before the revoke still sees its own coherent set.
- assert!(
- synthesized_in_flight
- .iter()
- .any(|tool| tool.name() == DELEGATE),
- "an in-flight turn keeps the snapshot it started with"
- );
-}
-
-/// A durable tool that owns a delegate's name wins on every surface, at build
-/// time and on every refresh — and a refresh must never withdraw the durable
-/// tool's spec when it re-synthesises the colliding delegate.
-///
-/// The old refresh put the unfiltered synthesised names into its mask, so the
-/// next refresh's spec `retain` dropped the durable tool's spec and appended
-/// the delegate's: the model then read the delegate's schema for a name whose
-/// first-wins dispatch ran the durable tool.
-#[test]
-fn a_durable_tool_owning_a_delegate_name_wins_everywhere_across_refreshes() {
- use crate::agent::harness::AgentDefinitionRegistry;
- const DELEGATE: &str = "delegate_to_integrations_agent";
-
- AgentDefinitionRegistry::init_global_builtins().unwrap();
- let mut agent = build_minimal_agent_with_tool_sets(
- vec![Box::new(MockTool), Box::new(NamedTool(DELEGATE))],
- Vec::new(),
- Some("orchestrator"),
- );
- let durable_schema = NamedTool(DELEGATE).parameters_schema();
-
- for toolkits in [vec!["gmail"], vec!["gmail", "notion"], vec!["notion"]] {
- agent.set_connected_integrations(toolkits.iter().map(|slug| connected(slug)).collect());
- agent.refresh_delegation_tools();
-
- assert!(
- !agent
- .synthesized_tools_arc()
- .iter()
- .any(|tool| tool.name() == DELEGATE),
- "the colliding delegate must not be synthesised beside the durable tool"
- );
- let specs: Vec<&std::sync::Arc<tinytools::ToolSpec>> = agent
- .tool_specs()
- .iter()
- .filter(|spec| spec.name == DELEGATE)
- .collect();
- assert_eq!(specs.len(), 1, "exactly one spec may carry the name");
- assert_eq!(
- specs[0].parameters, durable_schema,
- "and it must be the durable tool's schema — a refresh must not swap it \
- for the delegate's"
- );
- assert_eq!(
- agent
- .all_tool_refs()
- .iter()
- .filter(|tool| tool.name() == DELEGATE)
- .count(),
- 1
- );
- assert!(agent.tool_policy_session.is_allowed(DELEGATE));
- super::assert_synthesized_delegates_are_executable(&agent);
- }
-}
-
-/// The builder keeps the synthesised set beside the durable registry, never
-/// inside it, and drops a synthesised name a durable tool already owns.
-#[test]
-fn builder_holds_synthesized_tools_apart_from_the_durable_registry() {
- let agent = build_minimal_agent_with_tool_sets(
- vec![Box::new(MockTool)],
- vec![
- Box::new(NamedTool("delegate_probe")),
- Box::new(NamedTool("echo")),
- ],
- None,
- );
-
- assert!(
- agent.tools().iter().all(|tool| tool.name() == "echo"),
- "the durable registry must hold only what was handed to `tools`"
- );
- let synthesized: Vec<String> = agent
- .synthesized_tools_arc()
- .iter()
- .map(|tool| tool.name().to_string())
- .collect();
- assert_eq!(
- synthesized,
- vec!["delegate_probe".to_string()],
- "the synthesised `echo` collides with the durable tool and must be dropped"
- );
- assert_eq!(
- agent
- .tool_specs()
- .iter()
- .filter(|spec| spec.name == "echo")
- .count(),
- 1,
- "the durable tool keeps the only `echo` spec"
- );
- assert!(agent
- .tool_specs()
- .iter()
- .any(|spec| spec.name == "delegate_probe"));
- assert!(agent.tool_policy_session.is_allowed("delegate_probe"));
- let expected_mask: std::collections::HashSet<String> =
- std::iter::once("delegate_probe".to_string()).collect();
- assert_eq!(agent.synthesized_tool_names, expected_mask);
- super::assert_synthesized_delegates_are_executable(&agent);
-}
diff --git a/crates/openhuman-core/src/agent/harness/session/session_prefix_stability_tests.rs b/crates/openhuman-core/src/agent/harness/session/session_prefix_stability_tests.rs
deleted file mode 100644
index 6c2cee6177..0000000000
--- a/crates/openhuman-core/src/agent/harness/session/session_prefix_stability_tests.rs
+++ /dev/null
@@ -1,210 +0,0 @@
-use super::*;
-
-/// The superseded synthesised instances are released once the readers holding
-/// them go away — the issue's "clean up the old one once its refcount drops".
-#[test]
-fn superseded_synthesized_instances_are_released_when_readers_drop() {
- use crate::agent::harness::AgentDefinitionRegistry;
-
- AgentDefinitionRegistry::init_global_builtins().unwrap();
- let mut agent = build_minimal_agent_with_definition_name(Some("orchestrator"));
-
- let conn = |slug: &str, desc: &str| crate::agent::prompts::ConnectedIntegration {
- toolkit: slug.into(),
- description: desc.into(),
- tools: vec![],
- gated_tools: vec![],
- connected: true,
- connections: Vec::new(),
- non_active_status: None,
- };
-
- agent.set_connected_integrations(vec![conn("gmail", "Email")]);
- agent.refresh_delegation_tools();
-
- // A turn takes its snapshot of the synthesised set and keeps it.
- let in_flight = agent.synthesized_tools_arc();
- assert_eq!(Arc::strong_count(&in_flight), 2, "agent + in-flight turn");
-
- // The connection set changes underneath it.
- agent.set_connected_integrations(vec![conn("gmail", "Email"), conn("notion", "Docs")]);
- agent.refresh_delegation_tools();
-
- // The reader still sees a coherent set, and it is the *previous* one.
- assert_eq!(
- Arc::strong_count(&in_flight),
- 1,
- "the agent has moved on to a fresh Arc; only the in-flight turn holds the old one"
- );
- assert!(
- !Arc::ptr_eq(&in_flight, &agent.synthesized_tools_arc()),
- "a refresh must publish a new Arc rather than mutating the shared one"
- );
-
- // When the turn ends, the superseded instances are freed.
- drop(in_flight);
- assert_eq!(
- Arc::strong_count(&agent.synthesized_tools_arc()),
- 2,
- "only the agent's own Arc and this test's clone remain"
- );
-}
-
-/// The tool block is part of the KV-cache prefix, so a refresh that changes
-/// nothing must change no bytes.
-///
-/// Every prefix cache renders the tool catalogue ahead of the conversation, so
-/// the `tools` array sits *in front of* the frozen system prompt rather than
-/// after it. A rebuild that reorders an unchanged set — or that rebuilds at all
-/// when the connection set is the same — therefore costs the entire cached
-/// prefix on that turn, system prompt included, while every functional test
-/// still passes because the same capabilities are advertised.
-///
-/// Two properties keep that from happening and both are easy to lose:
-/// `refresh_delegation_tools` appends the synthesised specs in a deterministic
-/// sequence (derived from `definition.subagents`, a `Vec`) rather than from the
-/// `HashSet` it also maintains, and `connected_set_hash` sorts before hashing so
-/// a backend that returns the same toolkits in a new order never reaches here at
-/// all. This asserts the observable consequence rather than either mechanism, so
-/// it survives a refactor of either.
-#[test]
-fn an_unchanged_integration_set_leaves_the_tool_block_byte_stable() {
- use crate::agent::harness::AgentDefinitionRegistry;
-
- AgentDefinitionRegistry::init_global_builtins().unwrap();
- let mut agent = build_minimal_agent_with_definition_name(Some("orchestrator"));
-
- let integrations = || {
- vec![
- crate::agent::prompts::ConnectedIntegration {
- toolkit: "gmail".into(),
- description: "Email".into(),
- tools: vec![],
- gated_tools: vec![],
- connected: true,
- connections: Vec::new(),
- non_active_status: None,
- },
- crate::agent::prompts::ConnectedIntegration {
- toolkit: "notion".into(),
- description: "Docs".into(),
- tools: vec![],
- gated_tools: vec![],
- connected: true,
- connections: Vec::new(),
- non_active_status: None,
- },
- ]
- };
-
- // Exactly what a provider request carries: name, description and schema,
- // in order. Description is part of the wire bytes too — a stale delegate
- // description surviving a reconcile is the same class of bug as a stale
- // schema and this fixture should catch either.
- let wire_block = |agent: &Agent| -> Vec<(String, String, String)> {
- agent
- .tool_specs()
- .iter()
- .map(|spec| {
- (
- spec.name.clone(),
- spec.description.clone(),
- spec.parameters.to_string(),
- )
- })
- .collect()
- };
-
- agent.set_connected_integrations(integrations());
- agent.refresh_delegation_tools();
- let first = wire_block(&agent);
- assert!(
- first
- .iter()
- .any(|(name, _, _)| name.starts_with("delegate_")),
- "the fixture must actually synthesise delegates, or this pins nothing"
- );
-
- // A second reconcile over the same connection set — the turn-boundary path
- // when the Composio cache answers with what it answered last turn.
- agent.refresh_delegation_tools();
- assert_eq!(
- wire_block(&agent),
- first,
- "re-synthesising an unchanged integration set rewrote the tool block; \
- the tool catalogue precedes the conversation in every provider's cached \
- prefix, so this costs the frozen system prompt too"
- );
-
- // The same set in the opposite order is the same capability surface. The
- // hash is order-insensitive, so a reordered backend response must not even
- // reach a rebuild — and if it does, it must still land on the same bytes.
- let mut reordered = integrations();
- reordered.reverse();
- assert_eq!(
- crate::integrations::composio::connected_set_hash(&reordered),
- crate::integrations::composio::connected_set_hash(&integrations()),
- "connected_set_hash must not see a reordering as a change"
- );
- agent.set_connected_integrations(reordered);
- agent.refresh_delegation_tools();
- assert_eq!(
- wire_block(&agent),
- first,
- "the same toolkits in a different order produced a different tool block"
- );
-}
-
-/// A resumed prefix with no leading system message must not erase this
-/// turn's freshly rendered one.
-///
-/// `bound_cached_transcript_messages` keeps a leading system message only
-/// "when present" — a transcript that was never seeded with one (or was
-/// truncated ahead of it) hands `absorb_resumed_transcript_prefix` a `cached`
-/// prefix with no system entry at all. Unconditionally dropping the current
-/// system message(s) in that case would leave `history` with none, which is
-/// strictly worse than the stale-but-present one this turn already built.
-#[tokio::test]
-async fn a_resumed_prefix_without_a_system_message_keeps_the_current_one() {
- use crate::agent::messages::{ChatMessage, ConversationMessage};
-
- let workspace = tempfile::TempDir::new().expect("temp workspace");
- let canned = tinyagents_session::transcript::SessionTranscript {
- meta: fake_transcript_meta("thr_resume_no_system"),
- messages: durable_messages(vec![
- ChatMessage::user("first question"),
- ChatMessage::assistant("first answer"),
- ]),
- };
- let (mut agent, _handle) = agent_with_fake_locator(workspace.path(), Some(canned));
- agent.try_load_session_transcript();
-
- agent.history = vec![
- ConversationMessage::Chat(ChatMessage::system("freshly rendered prompt")),
- ConversationMessage::Chat(ChatMessage::user("second question")),
- ];
-
- agent.absorb_resumed_transcript_prefix();
-
- let rendered: Vec<(&str, &str)> = agent
- .history
- .iter()
- .map(|entry| match entry {
- ConversationMessage::Chat(chat) => (chat.role.as_str(), chat.content.as_str()),
- other => panic!("expected only Chat entries, got {other:?}"),
- })
- .collect();
- assert_eq!(
- rendered,
- vec![
- ("user", "first question"),
- ("assistant", "first answer"),
- // The cached prefix supplied no system message, so this turn's
- // freshly rendered one must survive rather than being dropped
- // unconditionally.
- ("system", "freshly rendered prompt"),
- ("user", "second question"),
- ],
- "the current system prompt must be kept when the cached prefix has none"
- );
-}
diff --git a/crates/openhuman-core/src/agent/harness/session/session_resume_request_id_tests.rs b/crates/openhuman-core/src/agent/harness/session/session_resume_request_id_tests.rs
deleted file mode 100644
index 53d7083fdd..0000000000
--- a/crates/openhuman-core/src/agent/harness/session/session_resume_request_id_tests.rs
+++ /dev/null
@@ -1,310 +0,0 @@
-use super::*;
-
-/// #6282 review: a resume leaves every row's own `extra_metadata` exactly as it
-/// was — a scalar, a caller object that happens to use the wrapper key, and a
-/// scalar under *two* host markers (a failed tool row that is also replayed,
-/// where removing the first marker must not drop the second) — while each row
-/// keeps the request it was first written under.
-#[test]
-fn resumed_rows_keep_their_own_extra_metadata() {
- use crate::agent::messages::{attach_chat_tool_failure_metadata, ChatMessage};
- use tinyagents_session::transcript::{
- append_transcript_turn, read_transcript, read_transcript_display, DisplayRecord,
- };
-
- let dir = tempfile::TempDir::new().expect("temp dir");
- let meta = fake_transcript_meta("thr_metadata");
-
- let mut noted = ChatMessage::user("noted question");
- noted.extra_metadata = Some(serde_json::json!("pinned"));
- let mut collides = ChatMessage::user("caller uses the wrapper key");
- collides.extra_metadata = Some(serde_json::json!({ "openhuman_wrapped_value": "pinned" }));
- let mut failed_tool = ChatMessage::tool(r#"{"tool_call_id":"call-1","content":"boom"}"#);
- failed_tool.extra_metadata = Some(serde_json::json!("tool-note"));
- attach_chat_tool_failure_metadata(&mut failed_tool, Some("boom"));
-
- let first = dir.path().join("first.jsonl");
- append_transcript_turn(
- &first,
- &[],
- &durable_messages([ChatMessage::system("sys"), noted, collides, failed_tool]),
- &meta,
- None,
- Some("req-1"),
- )
- .expect("turn 1");
-
- // Resume into a fresh file: the reader re-attaches each row's provenance,
- // the writer strips the markers again.
- let resumed = read_transcript(&first).expect("read").messages;
- let second = dir.path().join("second.jsonl");
- append_transcript_turn(&second, &[], &resumed, &meta, None, Some("req-2")).expect("turn 2");
-
- let rows: Vec<_> = read_transcript_display(&second)
- .expect("display read")
- .records
- .into_iter()
- .filter_map(|record| match record {
- DisplayRecord::Message(m) => Some(m),
- _ => None,
- })
- .collect();
- assert_eq!(
- rows.iter()
- .map(|row| row.request_id.as_deref())
- .collect::<Vec<_>>(),
- vec![Some("req-1"); 4],
- "every replayed row keeps the request that wrote it"
- );
- assert_eq!(
- rows[0].message.extra_metadata, None,
- "a row that had no metadata keeps none"
- );
- assert_eq!(
- rows[1].message.extra_metadata,
- Some(serde_json::json!("pinned")),
- "a scalar survives the resume unwrapped"
- );
- assert_eq!(
- rows[2].message.extra_metadata,
- Some(serde_json::json!({ "openhuman_wrapped_value": "pinned" })),
- "a caller object using the wrapper key stays an object"
- );
- assert_eq!(
- rows[3].message.extra_metadata,
- Some(serde_json::json!("tool-note")),
- "a scalar under both the failure and replay markers survives intact"
- );
- assert!(
- rows[3].failure && rows[3].failure_detail.as_deref() == Some("boom"),
- "the replayed tool row keeps its failure flag and detail"
- );
-
- // The display reader reconstructs from the line fields, so assert the file
- // itself too: the markers are an in-memory side-channel and must never be
- // persisted, and each row's caller metadata must be on disk in its original
- // shape.
- let raw = std::fs::read_to_string(&second).expect("read persisted transcript");
- for marker in [
- "openhuman_replayed",
- "openhuman_tool_failure",
- "openhuman_wrapped_value\":{",
- ] {
- assert!(
- !raw.contains(marker),
- "the persisted transcript must not carry {marker}: {raw}"
- );
- }
- assert!(
- raw.contains(r#""extra_metadata":"pinned""#)
- && raw.contains(r#""extra_metadata":{"openhuman_wrapped_value":"pinned"}"#)
- && raw.contains(r#""extra_metadata":"tool-note""#),
- "each row's caller metadata must be persisted in its original shape: {raw}"
- );
-}
-
-/// #6282 review: when a resumed transcript is later reduced, the writer's
-/// compaction record carries the full reduced set. Replayed rows inside it must
-/// keep the request they were first written under, the same as on a plain
-/// append.
-#[test]
-fn replayed_rows_keep_their_request_id_inside_a_compaction_record() {
- use crate::agent::messages::ChatMessage;
- use tinyagents_session::transcript::{
- append_transcript_turn, read_transcript, read_transcript_display, DisplayRecord,
- };
-
- let dir = tempfile::TempDir::new().expect("temp dir");
- let meta = fake_transcript_meta("thr_compaction");
-
- let first = dir.path().join("first.jsonl");
- let turn1 = durable_messages(vec![
- ChatMessage::system("sys"),
- ChatMessage::user("old question"),
- ChatMessage::assistant("old answer"),
- ]);
- append_transcript_turn(&first, &[], &turn1, &meta, None, Some("req-1")).expect("turn 1");
-
- // Resume into a fresh file, then append the resuming turn.
- let mut resumed = read_transcript(&first).expect("read").messages;
- resumed.push(crate::agent::messages::transcript_message_from_chat(
- &ChatMessage::user("new question"),
- ));
- let second = dir.path().join("second.jsonl");
- append_transcript_turn(&second, &[], &resumed, &meta, None, Some("req-2")).expect("turn 2");
-
- // A context reduction drops the old question: the persisted set is no
- // longer a prefix, so the writer appends a compaction record.
- let reduced = vec![resumed[0].clone(), resumed[2].clone(), resumed[3].clone()];
- append_transcript_turn(&second, &resumed, &reduced, &meta, None, Some("req-3"))
- .expect("reduced turn");
-
- let compaction = read_transcript_display(&second)
- .expect("display read")
- .records
- .into_iter()
- .find_map(|record| match record {
- DisplayRecord::Compaction(marker) => Some(marker),
- _ => None,
- })
- .expect("the reduction must be recorded as a compaction");
- let ids: Vec<Option<&str>> = compaction
- .replacement
- .iter()
- .map(|m| m.request_id.as_deref())
- .collect();
- assert_eq!(
- ids,
- vec![Some("req-1"), Some("req-1"), Some("req-3")],
- "replayed rows keep req-1 inside the compaction; only the non-replayed row takes \
- the compacting request, as compaction already does for live rows"
- );
-}
-
-/// #6282: rows seeded from the conversation log belong to earlier turns and
-/// carry no request id, so persisting them together with the next turn must
-/// not stamp them with that turn's request.
-#[test]
-fn prose_seeded_rows_are_not_restamped_with_the_resuming_request() {
- use crate::agent::messages::{ChatMessage, ConversationMessage};
- use tinyagents_session::transcript::{
- append_transcript_turn, read_transcript_display, DisplayRecord,
- };
-
- let mut agent = build_minimal_agent_with_definition_name(Some("orchestrator"));
- agent
- .seed_resume_from_messages(
- vec![
- ("user".to_string(), "install it".to_string()),
- ("agent".to_string(), "Something went wrong.".to_string()),
- ],
- "what happened?",
- )
- .expect("seed");
- // The resuming turn: its own message, then the seeded prefix absorbed ahead
- // of it and rendered for persistence, exactly as the turn driver does.
- agent.history = vec![ConversationMessage::Chat(ChatMessage::user(
- "what happened?",
- ))];
- agent.absorb_resumed_transcript_prefix();
- let messages: Vec<_> = agent
- .history
- .iter()
- .filter_map(|message| match message {
- ConversationMessage::Chat(message) => Some(message.clone()),
- ConversationMessage::AssistantToolCalls { .. }
- | ConversationMessage::ToolResults(_) => None,
- })
- .collect();
-
- let dir = tempfile::TempDir::new().expect("temp dir");
- let path = dir.path().join("seeded.jsonl");
- append_transcript_turn(
- &path,
- &[],
- &durable_messages(messages),
- &fake_transcript_meta("thr_seeded"),
- None,
- Some("req-now"),
- )
- .expect("persist seeded turn");
-
- let rows: Vec<(String, Option<String>)> = read_transcript_display(&path)
- .expect("display read")
- .records
- .into_iter()
- .filter_map(|record| match record {
- DisplayRecord::Message(m) => Some((m.message.content, m.request_id)),
- _ => None,
- })
- .collect();
- let ids: Vec<Option<&str>> = rows.iter().map(|(_, id)| id.as_deref()).collect();
- assert_eq!(
- ids,
- vec![None, None, None, Some("req-now")],
- "the seeded prefix (its system prompt included) keeps no request id; only \
- this turn's new message takes it: {rows:?}"
- );
-}
-
-/// #6282: a thread transcript written without request ids (a CLI or full-rewrite
-/// transcript) resumed into a request-scoped turn must not have its replayed
-/// rows restamped with the resuming request, which would group every earlier
-/// message into the current turn.
-#[test]
-fn a_resumed_request_less_transcript_is_not_restamped_with_the_resuming_request() {
- use crate::agent::messages::{ChatMessage, ConversationMessage};
- use tinyagents_session::transcript::{self, read_transcript_display, DisplayRecord};
-
- let ws = tempfile::TempDir::new().expect("temp workspace");
- let wsp = ws.path().to_path_buf();
- let thread_id = "thr_request_less";
- let path = transcript::resolve_keyed_transcript_path(&wsp, "1700000000_orchestrator")
- .expect("resolve transcript path");
- transcript::write_transcript(
- &path,
- &durable_messages([
- ChatMessage::system("stored prompt"),
- ChatMessage::user("first question"),
- ChatMessage::assistant("first answer"),
- ]),
- &fake_transcript_meta(thread_id),
- None,
- )
- .expect("write transcript");
-
- let mem: Arc<dyn Memory> = crate::memory::test_support::noop_memory();
- let mut agent = Agent::builder()
- .chat_model(Arc::new(MockProvider {
- responses: Mutex::new(vec![]),
- }))
- .tools(vec![Box::new(MockTool)])
- .memory(mem)
- .tool_dispatcher(Box::new(NativeDialect))
- .workspace_dir(wsp.clone())
- .build()
- .expect("agent build should succeed");
- assert!(agent.seed_resume_from_thread_transcript(thread_id));
-
- // The resuming turn: its own message, then the replayed prefix absorbed
- // ahead of it, exactly as the turn driver does.
- agent.history = vec![ConversationMessage::Chat(ChatMessage::user(
- "second question",
- ))];
- agent.absorb_resumed_transcript_prefix();
- let messages: Vec<_> = agent
- .history
- .iter()
- .filter_map(|message| match message {
- ConversationMessage::Chat(message) => Some(message.clone()),
- ConversationMessage::AssistantToolCalls { .. }
- | ConversationMessage::ToolResults(_) => None,
- })
- .collect();
-
- let out = wsp.join("resumed.jsonl");
- transcript::append_transcript_turn(
- &out,
- &[],
- &durable_messages(messages),
- &fake_transcript_meta(thread_id),
- None,
- Some("req-2"),
- )
- .expect("persist resumed turn");
- let rows: Vec<(String, Option<String>)> = read_transcript_display(&out)
- .expect("display read")
- .records
- .into_iter()
- .filter_map(|record| match record {
- DisplayRecord::Message(m) => Some((m.message.content, m.request_id)),
- _ => None,
- })
- .collect();
- let ids: Vec<Option<&str>> = rows.iter().map(|(_, id)| id.as_deref()).collect();
- assert_eq!(
- ids,
- vec![None, None, None, Some("req-2")],
- "replayed request-less rows keep no request id; only the resuming turn's row takes it: {rows:?}"
- );
-}
diff --git a/crates/openhuman-core/src/agent/harness/session/session_tests.rs b/crates/openhuman-core/src/agent/harness/session/session_tests.rs
deleted file mode 100644
index 98c0d7428d..0000000000
--- a/crates/openhuman-core/src/agent/harness/session/session_tests.rs
+++ /dev/null
@@ -1,561 +0,0 @@
-//! `Agent` unit + integration tests.
-//!
-//! All tests exercise the agent through its public surface only (no
-//! private-field access), which is why they live in a sibling file
-//! rather than inline with one of the impl blocks. Shared fakes
-//! (`MockProvider`, `RecordingProvider`, `MockTool`) are defined here.
-
-use super::types::{Agent, AgentBuilder};
-use crate::agent::messages::{ChatMessage, ConversationMessage};
-use crate::core::events::DomainEvent;
-use crate::inference::provider::ChatResponse;
-use crate::memory::Memory;
-use anyhow::Result;
-use async_trait::async_trait;
-use parking_lot::Mutex;
-use std::sync::Arc;
-use tinyagents_session::transcript::{
- SessionTranscript, TranscriptHistory, TranscriptLocator, TranscriptMeta, TranscriptRead,
- TranscriptTurn,
-};
-use tinyinference_llm::message::Message;
-use tinyinference_llm::model::{
- ChatModel, ModelProfile, ModelRequest, ModelResponse, ModelStream, ModelStreamItem,
-};
-use tinytools::Tool;
-use tinytools_agent::dialect::{NativeDialect, XmlDialect};
-
-fn durable_messages(
- messages: impl IntoIterator<Item = ChatMessage>,
-) -> Vec<tinyagents_session::transcript::TranscriptMessage> {
- messages
- .into_iter()
- .map(|message| crate::agent::messages::transcript_message_from_chat(&message))
- .collect()
-}
-
-struct MockProvider {
- responses: Mutex<Vec<ChatResponse>>,
-}
-
-#[async_trait]
-impl ChatModel<()> for MockProvider {
- fn profile(&self) -> Option<&ModelProfile> {
- static PROFILE: std::sync::LazyLock<ModelProfile> =
- std::sync::LazyLock::new(ModelProfile::default);
- Some(&PROFILE)
- }
-
- async fn invoke(
- &self,
- _state: &(),
- request: ModelRequest,
- ) -> tinyinference_llm::Result<ModelResponse> {
- let mut guard = self.responses.lock();
- let response = if guard.is_empty() {
- ChatResponse {
- text: Some("done".into()),
- tool_calls: vec![],
- usage: None,
- reasoning_content: None,
- }
- } else {
- guard.remove(0)
- };
- Ok(crate::agent::tinyagents::model::native_model_response_for_request(&response, &request))
- }
-
- async fn stream(
- &self,
- state: &(),
- request: ModelRequest,
- ) -> tinyinference_llm::Result<ModelStream> {
- let response = self.invoke(state, request).await?;
- Ok(ModelStream::new(Box::pin(futures::stream::iter(vec![
- ModelStreamItem::Started,
- ModelStreamItem::Completed(response),
- ]))))
- }
-}
-
-/// Provider that records the system prompt bytes and model name of
-/// every `chat()` call. Used by KV-cache stability tests — anything
-/// that varies between turns (timestamps, re-rendered memory context,
-/// flipped model hints) will show up as a diff between captures.
-#[derive(Default)]
-struct RecordingProvider {
- captures: Mutex<Vec<CapturedCall>>,
- responses: Mutex<Vec<ChatResponse>>,
-}
-
-#[derive(Clone)]
-struct CapturedCall {
- system_prompt: Option<String>,
- model: String,
-}
-
-#[async_trait]
-impl ChatModel<()> for RecordingProvider {
- fn profile(&self) -> Option<&ModelProfile> {
- static PROFILE: std::sync::LazyLock<ModelProfile> =
- std::sync::LazyLock::new(ModelProfile::default);
- Some(&PROFILE)
- }
-
- async fn invoke(
- &self,
- _state: &(),
- request: ModelRequest,
- ) -> tinyinference_llm::Result<ModelResponse> {
- let system_prompt = request.messages.iter().find_map(|message| match message {
- Message::System(_) => Some(message.text()),
- _ => None,
- });
- self.captures.lock().push(CapturedCall {
- system_prompt,
- model: request.model.clone().unwrap_or_default(),
- });
-
- let mut guard = self.responses.lock();
- let response = if guard.is_empty() {
- ChatResponse {
- text: Some("done".into()),
- tool_calls: vec![],
- usage: None,
- reasoning_content: None,
- }
- } else {
- guard.remove(0)
- };
- Ok(crate::agent::tinyagents::model::native_model_response_for_request(&response, &request))
- }
-
- async fn stream(
- &self,
- state: &(),
- request: ModelRequest,
- ) -> tinyinference_llm::Result<ModelStream> {
- let response = self.invoke(state, request).await?;
- Ok(ModelStream::new(Box::pin(futures::stream::iter(vec![
- ModelStreamItem::Started,
- ModelStreamItem::Completed(response),
- ]))))
- }
-}
-
-struct MockTool;
-
-#[async_trait]
-impl Tool for MockTool {
- fn name(&self) -> &str {
- "echo"
- }
-
- fn description(&self) -> &str {
- "echo"
- }
-
- fn parameters_schema(&self) -> serde_json::Value {
- serde_json::json!({"type": "object"})
- }
-
- async fn execute(&self, _args: serde_json::Value) -> Result<tinytools::ToolResult> {
- Ok(tinytools::ToolResult::success("tool-out"))
- }
-}
-
-// silence clippy — `AgentBuilder` is imported so tests can reference
-// it in doc examples / type assertions if needed.
-#[allow(dead_code)]
-fn _assert_builder_is_exported() -> AgentBuilder {
- Agent::builder()
-}
-
-/// Minimal in-memory `Agent` build that every agent_definition_name
-/// regression test reuses. Spins up a scratch workspace, a `none`
-/// memory backend, a one-response `MockProvider`, and a single
-/// `MockTool`, then feeds those into [`Agent::builder`]. Returns the
-/// built `Agent` so individual tests can assert against the
-/// [`Agent::agent_definition_name`] accessor.
-fn build_minimal_agent_with_definition_name(definition_name: Option<&str>) -> Agent {
- build_minimal_agent_with_tool_sets(vec![Box::new(MockTool)], Vec::new(), definition_name)
-}
-
-/// [`build_minimal_agent_with_definition_name`] with caller-chosen durable and
-/// synthesised tool sets, for the tests that pin how the two sets relate.
-fn build_minimal_agent_with_tool_sets(
- tools: Vec<Box<dyn Tool>>,
- synthesized_tools: Vec<Box<dyn Tool>>,
- definition_name: Option<&str>,
-) -> Agent {
- // The embedding seam fails loudly when unwired; before the memory
- // extraction this was a direct call and needed no setup.
- let workspace = tempfile::TempDir::new().expect("temp workspace");
- let workspace_path = workspace.path().to_path_buf();
-
- let provider = Arc::new(MockProvider {
- responses: Mutex::new(vec![]),
- });
-
- let _memory_cfg = crate::config::MemoryConfig {
- backend: "none".into(),
- ..crate::config::MemoryConfig::default()
- };
- let mem: Arc<dyn Memory> = crate::memory::test_support::noop_memory();
-
- let mut builder = Agent::builder()
- .chat_model(provider)
- .tools(tools)
- .synthesized_tools(synthesized_tools)
- .memory(mem)
- .tool_dispatcher(Box::new(NativeDialect))
- .workspace_dir(workspace_path);
-
- if let Some(name) = definition_name {
- builder = builder.agent_definition_name(name);
- }
-
- builder.build().expect("minimal agent build should succeed")
-}
-
-fn integration_delegate_toolkit_enum(agent: &Agent) -> Vec<String> {
- let spec = agent
- .tool_specs()
- .iter()
- .find(|spec| spec.name == "delegate_to_integrations_agent")
- .expect("delegate_to_integrations_agent tool spec should be present");
- let mut out: Vec<String> = spec.parameters["properties"]["toolkit"]["enum"]
- .as_array()
- .expect("toolkit enum should be an array")
- .iter()
- .filter_map(|v| v.as_str().map(ToString::to_string))
- .collect();
- out.sort();
- out
-}
-
-/// Every synthesised delegate the agent advertises must have an executable
-/// instance behind it, and vice versa.
-///
-/// This is the invariant #6145 broke: `tool_specs` reconciled unconditionally
-/// while the instances only reconciled when the `tools` `Arc` happened to be
-/// uniquely owned. A mid-session connect published a `delegate_*` spec with no
-/// instance behind it — and, the policy snapshot being built from the
-/// instances, no decision either, so the fail-closed visibility filter hid it
-/// — while a revoke withdrew the spec and left the instance registered and
-/// callable. Asserted through the public surface only, like every other test
-/// in this file.
-fn assert_synthesized_delegates_are_executable(agent: &Agent) {
- let instances = agent.synthesized_tools_arc();
- let executable: std::collections::HashSet<String> =
- instances.iter().map(|t| t.name().to_string()).collect();
- assert_eq!(
- executable.len(),
- instances.len(),
- "the synthesised set must not contain duplicate tool names"
- );
-
- let spec_names: std::collections::HashSet<String> = agent
- .tool_specs()
- .iter()
- .map(|spec| spec.name.clone())
- .collect();
- for name in &executable {
- assert!(
- spec_names.contains(name),
- "executable synthesised tool `{name}` is not advertised in tool_specs"
- );
- }
-
- // The other direction is the connect case: a `delegate_*` spec with
- // nothing registered to run it. Checked against the whole callable
- // surface, since a durable tool may legitimately own a `delegate_*` name
- // (in which case the synthesised one is dropped, not the durable one).
- let all_names: Vec<&str> = agent.all_tool_refs().iter().map(|t| t.name()).collect();
- let callable: std::collections::HashSet<&str> = all_names.iter().copied().collect();
- let advertised_delegates: Vec<&String> = spec_names
- .iter()
- .filter(|name| name.starts_with("delegate_"))
- .collect();
- for name in advertised_delegates {
- assert!(
- callable.contains(name.as_str()),
- "advertised delegate `{name}` has no executable instance in either set; \
- callable={callable:?}"
- );
- }
-
- // Presence is not enough. A stale instance under a fresh spec is the same
- // class of bug one step quieter: the model reads the new `toolkit` enum
- // and routes to an instance built from the previous connection set. Pin
- // that each instance's own schema is byte-identical to what is advertised.
- for tool in instances.iter() {
- let advertised = agent
- .tool_specs()
- .iter()
- .find(|spec| spec.name == tool.name())
- .unwrap_or_else(|| panic!("no spec advertised for synthesised tool `{}`", tool.name()));
- assert_eq!(
- tool.spec().parameters,
- advertised.parameters,
- "synthesised instance `{}` carries a stale schema — advertised and executable \
- must be rebuilt in the same pass",
- tool.name()
- );
- }
-
- // The two sets are disjoint by construction, so a name never resolves to
- // two instances however the readers order them.
- assert_eq!(
- callable.len(),
- all_names.len(),
- "the durable and synthesised sets must not share a name: {all_names:?}"
- );
-
- // And every synthesised tool carries a policy decision — without one the
- // fail-closed visibility filter would hide it, which is how the connect
- // direction of #6145 stayed invisible.
- for name in &executable {
- assert!(
- agent.tool_policy_session.decisions.contains_key(name),
- "synthesised tool `{name}` has no policy decision"
- );
- }
-}
-
-async fn turn_dispatches_spawn_subagent_through_full_path_inner() {
- // The embedding seam fails loudly when unwired; before the memory
- // extraction this was a direct call and needed no setup.
- use crate::agent::harness::AgentDefinitionRegistry;
- use crate::tools::SpawnSubagentTool;
-
- // Idempotent — other tests may have already initialised it.
- AgentDefinitionRegistry::init_global_builtins().unwrap();
-
- let workspace = tempfile::TempDir::new().expect("temp workspace");
- let workspace_path = workspace.path().to_path_buf();
-
- // Scripted responses, in the exact order MockProvider will see them:
- // 1. Parent turn iter 0 — emit a spawn_subagent tool call.
- // 2. Sub-agent (researcher) iter 0 — return final text "X is Y".
- // 3. Parent turn iter 1 — fold sub-agent result into "Based on the research, X is Y."
- let provider = Arc::new(MockProvider {
- responses: Mutex::new(vec![
- crate::inference::provider::ChatResponse {
- text: Some(String::new()),
- tool_calls: vec![crate::inference::provider::ToolCall {
- id: "call-spawn".into(),
- name: "spawn_subagent".into(),
- arguments: serde_json::json!({
- "agent_id": "__test_inherit_echo",
- "prompt": "find out about X",
- "blocking": true
- })
- .to_string(),
- extra_content: None,
- }],
- usage: None,
- reasoning_content: None,
- },
- crate::inference::provider::ChatResponse {
- text: Some("X is Y".into()),
- tool_calls: vec![],
- usage: None,
- reasoning_content: None,
- },
- crate::inference::provider::ChatResponse {
- text: Some("Based on the research, X is Y.".into()),
- tool_calls: vec![],
- usage: None,
- reasoning_content: None,
- },
- ]),
- });
-
- let _memory_cfg = crate::config::MemoryConfig {
- backend: "none".into(),
- ..crate::config::MemoryConfig::default()
- };
- let mem: Arc<dyn Memory> = crate::memory::test_support::noop_memory();
-
- // Tools include SpawnSubagentTool so the parent can call it.
- let tools: Vec<Box<dyn Tool>> = vec![Box::new(SpawnSubagentTool::new())];
-
- let mut agent = Agent::builder()
- .chat_model(provider)
- .tools(tools)
- .memory(mem)
- .tool_dispatcher(Box::new(NativeDialect))
- .workspace_dir(workspace_path)
- .build()
- .unwrap();
-
- let response = agent.turn("tell me about X").await.unwrap();
- assert_eq!(response, "Based on the research, X is Y.");
-
- // The parent's history should contain the spawn_subagent
- // assistant tool call AND a tool-result message carrying the
- // sub-agent's compact output.
- let has_spawn_call = agent.history().iter().any(|msg| match msg {
- ConversationMessage::AssistantToolCalls { tool_calls, .. } => {
- tool_calls.iter().any(|c| c.name == "spawn_subagent")
- }
- _ => false,
- });
- assert!(
- has_spawn_call,
- "parent history should contain the spawn_subagent assistant tool call"
- );
-
- let tool_result_contains_subagent_output = agent.history().iter().any(|msg| match msg {
- ConversationMessage::ToolResults(results) => {
- results.iter().any(|r| r.content.contains("X is Y"))
- }
- ConversationMessage::Chat(chat) if chat.role == "tool" => chat.content.contains("X is Y"),
- _ => false,
- });
- assert!(
- tool_result_contains_subagent_output,
- "parent history should contain a tool-result entry with the sub-agent's output"
- );
-}
-
-// ─────────────────────────────────────────────────────────────────────
-// S4: the transcript seam is genuinely substitutable
-// ─────────────────────────────────────────────────────────────────────
-
-/// A `SessionHistory` that keeps everything in memory and touches no file.
-///
-/// The point of the fake is not that it is convenient — it is that it is
-/// *possible*. Before the locator existed, `session_history` was an
-/// `Arc<dyn …>` the turn path constructed inline, so nothing could ever be put
-/// behind it; this fake failing to compile or failing to receive the turn is
-/// the regression signal for that.
-struct FakeSessionHistory {
- path: std::path::PathBuf,
- canned: Option<SessionTranscript>,
- appended: Mutex<Vec<Vec<tinyagents_session::transcript::TranscriptMessage>>>,
-}
-
-impl TranscriptRead for FakeSessionHistory {
- fn path(&self) -> &std::path::Path {
- &self.path
- }
-
- fn read_session(&self) -> Result<Option<SessionTranscript>> {
- Ok(self.canned.clone())
- }
-}
-
-impl TranscriptHistory for FakeSessionHistory {
- fn append_turn(&self, turn: TranscriptTurn<'_>) -> Result<()> {
- self.appended.lock().push(turn.next.to_vec());
- Ok(())
- }
- fn messages(&self) -> Result<Vec<tinyagents_session::transcript::TranscriptMessage>> {
- Ok(self
- .canned
- .as_ref()
- .map(|transcript| transcript.messages.clone())
- .unwrap_or_default())
- }
- fn append(&self, _message: tinyagents_session::transcript::TranscriptMessage) -> Result<()> {
- Ok(())
- }
- fn replace(
- &self,
- _messages: &[tinyagents_session::transcript::TranscriptMessage],
- ) -> Result<()> {
- Ok(())
- }
- fn clear(&self) -> Result<()> {
- Ok(())
- }
-}
-
-/// Serves one canned transcript for every lookup and one recording write
-/// handle, so a whole session's transcript I/O can be observed off-disk.
-struct FakeLocator {
- handle: Arc<FakeSessionHistory>,
-}
-
-impl TranscriptLocator for FakeLocator {
- fn latest_for_agent(&self, _agent_name: &str) -> Option<Arc<dyn TranscriptRead>> {
- Some(self.handle.clone())
- }
-
- fn root_for_thread(&self, _thread_id: &str) -> Option<Arc<dyn TranscriptRead>> {
- Some(self.handle.clone())
- }
-
- fn open_stem(&self, _stem: &str, _seed: TranscriptMeta) -> Result<Arc<dyn TranscriptHistory>> {
- Ok(self.handle.clone())
- }
-}
-
-fn fake_transcript_meta(thread_id: &str) -> TranscriptMeta {
- TranscriptMeta {
- agent_name: "faker".into(),
- agent_id: None,
- agent_type: Some("root".into()),
- dispatcher: "native".into(),
- provider: None,
- model: None,
- created: "2026-08-08T00:00:00Z".into(),
- updated: "2026-08-08T00:00:00Z".into(),
- turn_count: 1,
- input_tokens: 0,
- output_tokens: 0,
- cached_input_tokens: 0,
- charged_amount_usd: 0.0,
- thread_id: Some(thread_id.into()),
- task_id: None,
- }
-}
-
-fn agent_with_fake_locator(
- workspace: &std::path::Path,
- canned: Option<SessionTranscript>,
-) -> (Agent, Arc<FakeSessionHistory>) {
- let handle = Arc::new(FakeSessionHistory {
- path: workspace.join("session_raw").join("fake.jsonl"),
- canned,
- appended: Mutex::new(Vec::new()),
- });
- let _memory_cfg = crate::config::MemoryConfig {
- backend: "none".into(),
- ..crate::config::MemoryConfig::default()
- };
- let mem: Arc<dyn Memory> = crate::memory::test_support::noop_memory();
- let agent = Agent::builder()
- .chat_model(Arc::new(MockProvider {
- responses: Mutex::new(vec![]),
- }))
- .tools(vec![Box::new(MockTool)])
- .memory(mem)
- .tool_dispatcher(Box::new(NativeDialect))
- .agent_definition_name("faker")
- .workspace_dir(workspace.to_path_buf())
- .with_session_history_locator(Arc::new(FakeLocator {
- handle: handle.clone(),
- }))
- .build()
- .expect("agent build should succeed");
- (agent, handle)
-}
-
-#[path = "session_builder_and_listener_tests.rs"]
-mod session_builder_and_listener_tests;
-#[cfg(feature = "flows")]
-#[path = "session_builder_autoload_tests.rs"]
-mod session_builder_autoload_tests;
-#[path = "session_dispatch_and_resume_tests.rs"]
-mod session_dispatch_and_resume_tests;
-#[path = "session_prefix_stability_tests.rs"]
-mod session_prefix_stability_tests;
-#[path = "session_resume_request_id_tests.rs"]
-mod session_resume_request_id_tests;
-#[path = "session_thread_resume_scoped_tests.rs"]
-mod session_thread_resume_scoped_tests;
-#[path = "session_thread_resume_tests.rs"]
-mod session_thread_resume_tests;
diff --git a/crates/openhuman-core/src/agent/harness/session/session_thread_resume_scoped_tests.rs b/crates/openhuman-core/src/agent/harness/session/session_thread_resume_scoped_tests.rs
deleted file mode 100644
index 41e737769d..0000000000
--- a/crates/openhuman-core/src/agent/harness/session/session_thread_resume_scoped_tests.rs
+++ /dev/null
@@ -1,100 +0,0 @@
-//! Regression coverage for `agent_id`-scoped transcript resume.
-//!
-//! Split from `session_thread_resume_tests.rs` to keep that file under the
-//! repo's 750-line layout cap (rust:layout / check-openhuman-rust-layout.mjs).
-//! Shares its parent's `use super::*` fixtures via the same `#[path]` mount.
-
-use super::*;
-
-/// Regression: a library host can give two distinct runtime agents the same
-/// caller-supplied `thread_id` — nothing in the id namespace prevents it.
-/// Without `agent_id` scoping, resume would resolve to whichever agent's
-/// transcript for that thread is newest, splicing agent A's history into
-/// agent B's turn. `seed_resume_from_thread_transcript_scoped` must instead
-/// resume only the transcript whose `_meta.agent_id` matches the caller.
-#[test]
-fn seed_resume_from_thread_transcript_scoped_does_not_leak_across_agents() {
- use crate::agent::messages::ChatMessage;
- use tinyagents_session::transcript::{self, TranscriptMeta};
-
- let ws = tempfile::TempDir::new().expect("temp workspace");
- let wsp = ws.path().to_path_buf();
- // Two independently configured runtime agents reuse the same thread id —
- // e.g. a host that mints thread ids per conversation turn rather than per
- // agent.
- let thread_id = "thr_shared_across_agents";
-
- let meta = |agent_id: &str, stamp: &str| TranscriptMeta {
- agent_name: format!("{agent_id}_thr_shared"),
- agent_id: Some(agent_id.to_string()),
- agent_type: Some("root".to_string()),
- dispatcher: "native".to_string(),
- provider: None,
- model: None,
- created: stamp.to_string(),
- updated: stamp.to_string(),
- turn_count: 1,
- input_tokens: 0,
- output_tokens: 0,
- cached_input_tokens: 0,
- charged_amount_usd: 0.0,
- thread_id: Some(thread_id.to_string()),
- task_id: None,
- };
-
- // Agent A's transcript — written LATER (newer `created`), so an unscoped
- // newest-wins lookup would pick this one for agent B too.
- let a_messages = vec![
- ChatMessage::system("system prompt"),
- ChatMessage::user("agent A's private question"),
- ChatMessage::assistant("agent A's private answer"),
- ];
- let a_path = wsp.join("session_raw").join("1700009999_agent_a.jsonl");
- std::fs::create_dir_all(a_path.parent().unwrap()).unwrap();
- transcript::write_transcript(
- &a_path,
- &durable_messages(a_messages),
- &meta("agent_a", "2026-02-02T00:00:00Z"),
- None,
- )
- .expect("write agent A transcript");
-
- // Agent B's own transcript — older, but the one agent B must resume.
- let b_messages = vec![
- ChatMessage::system("system prompt"),
- ChatMessage::user("agent B's own question"),
- ChatMessage::assistant("agent B's own answer"),
- ];
- let b_path = wsp.join("session_raw").join("1700000000_agent_b.jsonl");
- std::fs::create_dir_all(b_path.parent().unwrap()).unwrap();
- transcript::write_transcript(
- &b_path,
- &durable_messages(b_messages),
- &meta("agent_b", "2026-01-01T00:00:00Z"),
- None,
- )
- .expect("write agent B transcript");
-
- let mut agent_b = build_minimal_agent_with_definition_name(Some("agent_b"));
- agent_b.workspace_dir = wsp.clone();
-
- assert!(
- agent_b.seed_resume_from_thread_transcript_scoped(thread_id, Some("agent_b")),
- "agent B must resume its own transcript for the shared thread id"
- );
- let cached = agent_b
- .cached_transcript_messages
- .as_ref()
- .expect("cached transcript populated");
- assert!(
- cached.iter().any(|m| m.content.contains("agent B's own")),
- "agent B's resume must load its own transcript"
- );
- assert!(
- !cached
- .iter()
- .any(|m| m.content.contains("agent A's private")),
- "agent B's resume must never load agent A's transcript for the same thread id, \
- got {cached:?}"
- );
-}
diff --git a/crates/openhuman-core/src/agent/harness/session/session_thread_resume_tests.rs b/crates/openhuman-core/src/agent/harness/session/session_thread_resume_tests.rs
deleted file mode 100644
index 808118e036..0000000000
--- a/crates/openhuman-core/src/agent/harness/session/session_thread_resume_tests.rs
+++ /dev/null
@@ -1,661 +0,0 @@
-use super::*;
-
-/// Cold-boot web-chat resume must prefer the full-fidelity `session_raw`
-/// transcript over lossy conversation-log prose. This is the regression for the
-/// "model forgets its tool interactions after an app restart" bug: once the
-/// in-memory agent is dropped and a fresh agent cold-boots for the same thread,
-/// the resumed context must still carry the tool call, the tool-role result, and
-/// the reasoning that prose seeding (`seed_resume_from_messages`) discards.
-#[test]
-fn seed_resume_from_thread_transcript_preserves_tool_calls_and_reasoning() {
- // The embedding seam fails loudly when unwired; before the memory
- // extraction this was a direct call and needed no setup.
- use crate::agent::messages::{attach_chat_turn_usage_metadata, ChatMessage};
- use tinyagents_session::transcript::{
- self, MessageUsage, TranscriptMeta, TranscriptToolCall, TurnUsage,
- };
-
- let ws = tempfile::TempDir::new().expect("temp workspace");
- let wsp = ws.path().to_path_buf();
- let thread_id = "thr_resume_fidelity";
-
- // ── Simulate a prior session persisted to session_raw carrying a tool
- // call + reasoning on the tool-calling assistant turn and a tool-role
- // result — exactly the fidelity the prose fallback drops. ──
- let mut assistant_toolcall = ChatMessage::assistant("Let me look that up.");
- attach_chat_turn_usage_metadata(
- &mut assistant_toolcall,
- &TurnUsage {
- provider: "openai".to_string(),
- model: "gpt-x".to_string(),
- usage: MessageUsage {
- input: 10,
- output: 5,
- cached_input: 0,
- context_window: 0,
- cost_usd: 0.0,
- },
- ts: "2026-01-01T00:00:00Z".to_string(),
- reasoning_content: Some("I should search the web for the price.".to_string()),
- tool_calls: vec![TranscriptToolCall {
- id: "call_1".to_string(),
- name: "web_search".to_string(),
- arguments: r#"{"query":"btc price"}"#.to_string(),
- extra_content: None,
- }],
- iteration: 1,
- },
- );
-
- let messages = vec![
- ChatMessage::system("system prompt"),
- ChatMessage::user("what is btc price"),
- assistant_toolcall,
- ChatMessage::tool(r#"{"tool_call_id":"call_1","content":"$80,000"}"#),
- ChatMessage::assistant("BTC is around $80,000."),
- ];
- let meta = TranscriptMeta {
- agent_name: "orchestrator_thread-resume".to_string(),
- agent_id: Some("orchestrator".to_string()),
- agent_type: Some("root".to_string()),
- dispatcher: "native".to_string(),
- provider: None,
- model: None,
- created: "2026-01-01T00:00:00Z".to_string(),
- updated: "2026-01-01T00:00:00Z".to_string(),
- turn_count: 1,
- input_tokens: 10,
- output_tokens: 5,
- cached_input_tokens: 0,
- charged_amount_usd: 0.0,
- thread_id: Some(thread_id.to_string()),
- task_id: None,
- };
- // Root stem: no `__`, so `find_root_transcript_for_thread` accepts it.
- let path = transcript::resolve_keyed_transcript_path(&wsp, "1700000000_orchestrator")
- .expect("resolve transcript path");
- transcript::write_transcript(&path, &durable_messages(messages), &meta, None)
- .expect("write transcript");
-
- // ── Cold boot: a brand-new agent for the same thread whose agent
- // definition name deliberately does NOT match the transcript stem — the
- // resume must route purely by thread id, not by agent name. ──
- let _memory_cfg = crate::config::MemoryConfig {
- backend: "none".into(),
- ..crate::config::MemoryConfig::default()
- };
- let mem: Arc<dyn Memory> = crate::memory::test_support::noop_memory();
- let mut agent = Agent::builder()
- .chat_model(Arc::new(MockProvider {
- responses: Mutex::new(vec![]),
- }))
- .tools(vec![Box::new(MockTool)])
- .memory(mem)
- .tool_dispatcher(Box::new(NativeDialect))
- .agent_definition_name("some_other_agent_name")
- .workspace_dir(wsp.clone())
- .build()
- .expect("agent build should succeed");
-
- let loaded = agent.seed_resume_from_thread_transcript(thread_id);
- assert!(
- loaded,
- "cold-boot resume must load the thread's root transcript"
- );
-
- let cached = agent
- .cached_transcript_messages
- .as_ref()
- .expect("cached transcript populated");
-
- // The tool-role result must survive — prose seeding would have dropped it.
- assert!(
- cached.iter().any(|m| m.role == "tool"),
- "resumed context must include the tool-role result message"
- );
-
- // The assistant tool call + reasoning survive, carried in metadata.
- let tool_call_carrier = cached
- .iter()
- .find(|m| {
- m.role == "assistant"
- && m.extra_metadata
- .as_ref()
- .and_then(|v| v.get("openhuman_turn_usage"))
- .is_some()
- })
- .expect("resumed context must include the assistant tool-call turn");
- let usage_value = tool_call_carrier
- .extra_metadata
- .as_ref()
- .and_then(|v| v.get("openhuman_turn_usage"))
- .cloned()
- .expect("turn usage metadata present");
- let parsed: TurnUsage = serde_json::from_value(usage_value).expect("turn usage deserializes");
- assert!(
- parsed.tool_calls.iter().any(|c| c.name == "web_search"),
- "the persisted tool call must round-trip into the resumed context"
- );
- assert_eq!(
- parsed.reasoning_content.as_deref(),
- Some("I should search the web for the price."),
- "reasoning content must be preserved on resume"
- );
-}
-
-/// Cold-boot resume over an **append-only** transcript that carries a
-/// compaction record: the resumed model context must equal the REDUCED set the
-/// compaction installed (byte-identical to what the old full-rewrite produced),
-/// not the full pre-compaction history.
-#[test]
-fn seed_resume_replays_compaction_to_reduced_context() {
- use crate::agent::messages::ChatMessage;
- use tinyagents_session::transcript::{self, TranscriptMeta};
-
- let ws = tempfile::TempDir::new().expect("temp workspace");
- let wsp = ws.path().to_path_buf();
- let thread_id = "thr_compaction_resume";
-
- let meta = TranscriptMeta {
- agent_name: "orchestrator_thread-compact".to_string(),
- agent_id: Some("orchestrator".to_string()),
- agent_type: Some("root".to_string()),
- dispatcher: "native".to_string(),
- provider: None,
- model: None,
- created: "2026-01-01T00:00:00Z".to_string(),
- updated: "2026-01-01T00:00:00Z".to_string(),
- turn_count: 2,
- input_tokens: 0,
- output_tokens: 0,
- cached_input_tokens: 0,
- charged_amount_usd: 0.0,
- thread_id: Some(thread_id.to_string()),
- task_id: None,
- };
- let path = transcript::resolve_keyed_transcript_path(&wsp, "1700000000_orchestrator")
- .expect("resolve transcript path");
-
- // Turn 1: a full exchange. Turn 2: a context reduction (not a prefix) that
- // must land as a compaction record.
- let full = durable_messages(vec![
- ChatMessage::system("system prompt"),
- ChatMessage::user("q1"),
- ChatMessage::assistant("a1"),
- ChatMessage::user("q2"),
- ChatMessage::assistant("a2"),
- ]);
- transcript::append_transcript_turn(&path, &[], &full, &meta, None, None)
- .expect("append turn 1");
- let reduced = durable_messages(vec![
- ChatMessage::system("system prompt"),
- ChatMessage::assistant("[summary] q1/q2"),
- ChatMessage::user("q3"),
- ChatMessage::assistant("a3"),
- ]);
- transcript::append_transcript_turn(&path, &full, &reduced, &meta, None, None)
- .expect("append turn 2 (compaction)");
-
- let mut agent = build_minimal_agent_with_definition_name(Some("some_other_agent_name"));
- agent.workspace_dir = wsp.clone();
-
- let loaded = agent.seed_resume_from_thread_transcript(thread_id);
- assert!(
- loaded,
- "cold-boot resume must load the compacted transcript"
- );
- let cached = agent
- .cached_transcript_messages
- .as_ref()
- .expect("cached transcript populated");
- assert_eq!(
- cached
- .iter()
- .map(|m| m.content.as_str())
- .collect::<Vec<_>>(),
- vec!["system prompt", "[summary] q1/q2", "q3", "a3"],
- "resumed context must be the reduced set the compaction installed"
- );
-}
-
-/// Resume must pick the newest matching canonical transcript for a thread.
-#[test]
-fn seed_resume_from_thread_transcript_picks_newest_canonical_transcript() {
- use crate::agent::messages::ChatMessage;
- use tinyagents_session::transcript::{self, TranscriptMeta};
-
- let ws = tempfile::TempDir::new().expect("temp workspace");
- let wsp = ws.path().to_path_buf();
- let thread_id = "thr_newest_wins";
-
- let meta = |stamp: &str| TranscriptMeta {
- agent_name: "orchestrator_thr_newest".to_string(),
- agent_id: Some("orchestrator".to_string()),
- agent_type: Some("root".to_string()),
- dispatcher: "native".to_string(),
- provider: None,
- model: None,
- created: stamp.to_string(),
- updated: stamp.to_string(),
- turn_count: 1,
- input_tokens: 0,
- output_tokens: 0,
- cached_input_tokens: 0,
- charged_amount_usd: 0.0,
- thread_id: Some(thread_id.to_string()),
- task_id: None,
- };
-
- // OLDER transcript in the agent's OWN (shared) dir.
- let older = durable_messages(vec![
- ChatMessage::system("system prompt"),
- ChatMessage::user("draft plan"),
- ChatMessage::assistant("early draft, details TBD"),
- ]);
- let old_path = wsp
- .join("session_raw")
- .join("1700000000_orchestrator.jsonl");
- std::fs::create_dir_all(old_path.parent().unwrap()).unwrap();
- transcript::write_transcript(&old_path, &older, &meta("2026-01-01T00:00:00Z"), None)
- .expect("write older");
-
- // NEWER transcript in the same canonical store.
- let newer = durable_messages(vec![
- ChatMessage::system("system prompt"),
- ChatMessage::user("finalize plan"),
- ChatMessage::assistant("FINAL: Minimax is the image generator"),
- ]);
- let new_path = wsp
- .join("session_raw")
- .join("1700009999_orchestrator.jsonl");
- std::fs::create_dir_all(new_path.parent().unwrap()).unwrap();
- transcript::write_transcript(&new_path, &newer, &meta("2026-02-02T00:00:00Z"), None)
- .expect("write newer");
-
- // The newest transcript must win over an older matching root transcript.
- let mut agent = build_minimal_agent_with_definition_name(Some("orchestrator"));
- agent.workspace_dir = wsp.clone();
-
- assert!(agent.seed_resume_from_thread_transcript(thread_id));
- let cached = agent
- .cached_transcript_messages
- .as_ref()
- .expect("cached transcript populated");
- assert!(
- cached.iter().any(|m| m.content.contains("FINAL")),
- "resume must load the newest canonical transcript, not the older copy"
- );
- assert!(
- !cached.iter().any(|m| m.content.contains("early draft")),
- "the older transcript must not shadow the newer canonical transcript"
- );
-}
-
-/// When no root transcript exists for the thread, the transcript resume is a
-/// no-op returning `false` so the caller falls back to prose-pair seeding.
-#[test]
-fn seed_resume_from_thread_transcript_returns_false_without_transcript() {
- let mut agent = build_minimal_agent_with_definition_name(Some("orchestrator"));
- assert!(!agent.seed_resume_from_thread_transcript("thr_missing"));
- assert!(agent.cached_transcript_messages.is_none());
-}
-
-/// Transcript resume must not stomp an already-warm agent (in-process session
-/// cache hit) — mirrors the `seed_resume_from_messages` warm-agent guard.
-#[test]
-fn seed_resume_from_thread_transcript_is_noop_on_warm_agent() {
- let mut agent = build_minimal_agent_with_definition_name(Some("orchestrator"));
- agent.cached_transcript_messages = Some(vec![crate::agent::messages::ChatMessage::system(
- "warm prefix",
- )]);
- assert!(!agent.seed_resume_from_thread_transcript("thr_x"));
- let cached = agent
- .cached_transcript_messages
- .as_ref()
- .expect("still populated");
- assert_eq!(cached.len(), 1);
- assert_eq!(cached[0].content, "warm prefix");
-}
-
-/// `hide_tools` on an agent that already has a visible-tool filter must drop
-/// only the named tools and leave the rest of the belt intact.
-#[test]
-fn hide_tools_drops_named_from_existing_filter() {
- let mut agent = build_minimal_agent_with_definition_name(None);
- agent.set_visible_tool_names(
- ["alpha".to_string(), "beta".to_string(), "echo".to_string()]
- .into_iter()
- .collect(),
- );
-
- agent.hide_tools(&["echo"]);
-
- let visible = agent.visible_tool_names_for_test();
- assert!(visible.contains("alpha") && visible.contains("beta"));
- assert!(
- !visible.contains("echo"),
- "hidden tool must be removed from the existing filter; visible = {visible:?}"
- );
-}
-
-/// `hide_tools` must materialize the wildcard sentinel before removing a real
-/// tool, leaving the rest of the belt visible and executable.
-#[test]
-fn hide_tools_seeds_allowlist_when_no_filter_present() {
- struct KeepTool;
-
- #[async_trait::async_trait]
- impl Tool for KeepTool {
- fn name(&self) -> &str {
- "keep"
- }
-
- fn description(&self) -> &str {
- "remain visible while another tool is hidden"
- }
-
- fn parameters_schema(&self) -> serde_json::Value {
- serde_json::json!({"type": "object"})
- }
-
- async fn execute(&self, _args: serde_json::Value) -> Result<tinytools::ToolResult> {
- Ok(tinytools::ToolResult::success("kept"))
- }
- }
-
- let mut agent = build_minimal_agent_with_tool_sets(
- vec![Box::new(MockTool), Box::new(KeepTool)],
- Vec::new(),
- None,
- );
- assert!(
- !agent.visible_tool_names_for_test().is_empty(),
- "precondition: the tool-pack builder seeds a concrete visible allowlist at build time"
- );
- assert!(
- agent.tool_specs().iter().any(|spec| spec.name == "echo"),
- "precondition: the mock belt includes `echo`"
- );
-
- // Recreate the wildcard sentinel directly so this test exercises
- // `hide_tools`'s own sentinel-to-allowlist transition. The public reset
- // setter deliberately materializes the sentinel before returning.
- agent.visible_tool_names.clear();
- agent.hide_tools(&["echo"]);
-
- let visible = agent.visible_tool_names_for_test();
- assert!(
- visible.contains("keep"),
- "seeding must preserve the rest of the concrete allowlist; visible = {visible:?}"
- );
- assert!(
- !visible.contains("echo"),
- "the real hidden tool must be removed from the materialized belt; visible = {visible:?}"
- );
- assert!(
- !agent
- .visible_tool_specs_arc()
- .iter()
- .any(|spec| spec.name == "echo"),
- "the hidden tool must leave the provider-facing surface"
- );
- assert!(
- !agent.tool_policy_session.is_allowed("echo"),
- "the hidden tool must also be denied at execution policy"
- );
-}
-
-// ── Issue #4868 — `set_max_tool_iterations` post-construction override ─────
-
-/// `set_max_tool_iterations` directly overrides the runtime cap, independent
-/// of whatever the builder resolved it to.
-#[test]
-fn set_max_tool_iterations_overrides_the_builder_resolved_cap() {
- let mut agent = build_minimal_agent_with_definition_name(Some("orchestrator"));
- let before = agent.agent_config().max_tool_iterations;
-
- agent.set_max_tool_iterations(200);
-
- assert_eq!(agent.agent_config().max_tool_iterations, 200);
- assert_ne!(
- 200, before,
- "sanity: the override must actually change the cap for this assertion to mean anything"
- );
-}
-
-/// Regression for issue #4868's `skill_runtime`/`task_dispatcher` callers:
-/// both build the agent via `Agent::from_config_for_agent` (which now stamps
-/// the resolved agent definition's own `effective_max_iterations()` — 15 for
-/// `orchestrator`), then need a much larger budget (200) for a full
-/// workflow/autonomous-task run. `set_max_tool_iterations` must win over
-/// whatever the session builder resolved, so the post-construction override
-/// actually sticks instead of being silently re-clobbered.
-#[test]
-fn set_max_tool_iterations_survives_after_definition_backed_construction() {
- use crate::agent::harness::AgentDefinitionRegistry;
-
- AgentDefinitionRegistry::init_global_builtins().unwrap();
-
- let workspace = tempfile::TempDir::new().expect("temp workspace");
- let mut config = crate::config::Config {
- workspace_dir: workspace.path().to_path_buf(),
- action_dir: workspace.path().to_path_buf(),
- ..crate::config::Config::default()
- };
- config.http_request.allowed_domains = vec!["*".to_string()];
-
- let mut agent =
- Agent::from_config_for_agent(&config, "orchestrator").expect("build orchestrator agent");
- assert_eq!(
- agent.agent_config().max_tool_iterations,
- 15,
- "precondition: the orchestrator definition's own cap (15) is applied by the builder"
- );
-
- // Mirrors `skill_runtime::run_machinery`/`task_dispatcher::executor`:
- // apply the much larger workflow/task-run budget AFTER construction.
- const WORKFLOW_RUN_MAX_ITERATIONS: usize = 200;
- agent.set_max_tool_iterations(WORKFLOW_RUN_MAX_ITERATIONS);
-
- assert_eq!(
- agent.agent_config().max_tool_iterations,
- WORKFLOW_RUN_MAX_ITERATIONS,
- "post-construction override must win over the definition-resolved cap"
- );
-}
-
-/// Both resume reads and the turn write are served by the injected locator,
-/// with **nothing written under the workspace**. That last assertion is the
-/// whole point: it is the proof the `Arc<dyn …>` is a real seam rather than
-/// decoration around a hardcoded filesystem call.
-#[tokio::test]
-async fn fake_locator_substitutes_the_whole_turn_path() {
- let workspace = tempfile::TempDir::new().expect("temp workspace");
- let canned = tinyagents_session::transcript::SessionTranscript {
- meta: fake_transcript_meta("thr_fake"),
- messages: durable_messages(vec![
- crate::agent::messages::ChatMessage::system("canned system"),
- crate::agent::messages::ChatMessage::user("canned question"),
- crate::agent::messages::ChatMessage::assistant("canned answer"),
- ]),
- };
- let (mut agent, handle) = agent_with_fake_locator(workspace.path(), Some(canned));
-
- // (1) The stem-keyed resume read.
- agent.try_load_session_transcript();
- let cached = agent
- .cached_transcript_messages
- .as_ref()
- .expect("resume prefix came from the fake locator");
- assert_eq!(
- cached
- .iter()
- .map(|m| m.content.as_str())
- .collect::<Vec<_>>(),
- vec!["canned system", "canned question", "canned answer"]
- );
-
- // (2) The thread-keyed cold-boot read (cleared first — it no-ops on a warm
- // agent by design).
- agent.cached_transcript_messages = None;
- assert!(agent.seed_resume_from_thread_transcript("thr_fake"));
- assert_eq!(
- agent
- .cached_transcript_messages
- .as_ref()
- .expect("cold-boot prefix")
- .len(),
- 3
- );
-
- // (3) The write.
- let turn = vec![
- crate::agent::messages::ChatMessage::user("live question"),
- crate::agent::messages::ChatMessage::assistant("live answer"),
- ];
- agent.persist_session_transcript(&turn, 1, 2, 0, 0.0, None);
- let appended = handle.appended.lock();
- assert_eq!(appended.len(), 1, "the turn reached the injected handle");
- assert_eq!(
- appended[0]
- .iter()
- .map(|m| m.content.as_str())
- .collect::<Vec<_>>(),
- vec!["live question", "live answer"]
- );
- assert_eq!(
- agent.session_transcript_path.as_deref(),
- Some(handle.path.as_path()),
- "session_transcript_path is the bound handle's own path — they cannot drift"
- );
-
- drop(appended);
-
- // (4) Nothing touched the transcript filesystem. (The #4249 store mirror
- // still runs — it is a separate, gated path this seam does not own — but it
- // never writes `session_raw/`.)
- assert!(
- !workspace.path().join("session_raw").exists(),
- "an injected locator must take the turn path entirely off disk"
- );
-}
-
-/// A locator that finds nothing must leave the agent cold, so the caller's
-/// prose-seeding fallback still fires.
-#[test]
-fn fake_locator_with_no_transcript_leaves_the_agent_cold() {
- let workspace = tempfile::TempDir::new().expect("temp workspace");
- let (mut agent, _handle) = agent_with_fake_locator(workspace.path(), None);
-
- agent.try_load_session_transcript();
- assert!(agent.cached_transcript_messages.is_none());
- assert!(
- !agent.seed_resume_from_thread_transcript("thr_fake"),
- "an Ok(None) read must report false like a missing file did"
- );
-}
-
-/// A resumed transcript must survive into `history`, not just into one request.
-///
-/// The prefix used to be spliced into the outgoing message list and dropped.
-/// Everything downstream reads `history`, so that cost the conversation twice,
-/// and both were observed against a live core before this test existed:
-///
-/// 1. The **next** turn went out without it — a ten-message thread answered its
-/// following question from four messages. Amnesia first, cache miss second.
-/// 2. The transcript persisted afterwards is serialized from `history`, so the
-/// file written after a resume held only the new turn. `latest_for_agent`
-/// hands that file to the next resume, so each restart truncated the thread
-/// further.
-///
-/// Asserting on `history` rather than on a rendered request is deliberate: the
-/// request was never the thing that was broken.
-#[tokio::test]
-async fn a_resumed_transcript_prefix_is_absorbed_into_history() {
- use crate::agent::messages::{ChatMessage, ConversationMessage};
-
- let workspace = tempfile::TempDir::new().expect("temp workspace");
- let canned = tinyagents_session::transcript::SessionTranscript {
- meta: fake_transcript_meta("thr_resume"),
- messages: durable_messages(vec![
- ChatMessage::system("stored system prompt"),
- ChatMessage::user("first question"),
- ChatMessage::assistant("first answer"),
- ]),
- };
- let (mut agent, _handle) = agent_with_fake_locator(workspace.path(), Some(canned));
- agent.try_load_session_transcript();
-
- // What `turn()` leaves behind on a resumed turn: a freshly rendered system
- // prompt it had to build because `history` was empty, then this turn's user
- // message.
- agent.history = vec![
- ConversationMessage::Chat(ChatMessage::system("freshly rendered prompt")),
- ConversationMessage::Chat(ChatMessage::user("second question")),
- ];
-
- agent.absorb_resumed_transcript_prefix();
-
- let rendered: Vec<(&str, &str)> = agent
- .history
- .iter()
- .map(|entry| match entry {
- ConversationMessage::Chat(chat) => (chat.role.as_str(), chat.content.as_str()),
- other => panic!("expected only Chat entries, got {other:?}"),
- })
- .collect();
- assert_eq!(
- rendered,
- vec![
- // The stored prompt wins: it is the prefix the backend has already
- // tokenised, and re-rendering it is what resuming exists to avoid.
- ("system", "stored system prompt"),
- ("user", "first question"),
- ("assistant", "first answer"),
- ("user", "second question"),
- ],
- "the replayed prefix must land in history ahead of this turn, with the \
- freshly rendered system prompt dropped in favour of the stored one"
- );
- assert!(
- agent.cached_transcript_messages.is_none(),
- "the prefix is consumed once — history owns it from here"
- );
-
- // Defect (1): a second turn appends to a history that still carries the
- // replayed conversation, rather than starting from just its own message.
- agent
- .history
- .push(ConversationMessage::Chat(ChatMessage::user(
- "third question",
- )));
- agent.absorb_resumed_transcript_prefix();
- assert_eq!(
- agent.history.len(),
- 5,
- "a later turn must neither lose the replayed prefix nor duplicate it"
- );
-
- // Defect (2): what persistence serializes is that same full sequence, so
- // the transcript written after a resume is complete and the *next* resume
- // reads a whole thread rather than a truncated one.
- let persisted: Vec<_> = agent
- .history
- .iter()
- .filter_map(|message| match message {
- ConversationMessage::Chat(message) => Some(message.content.as_str()),
- ConversationMessage::AssistantToolCalls { .. }
- | ConversationMessage::ToolResults(_) => None,
- })
- .collect();
- assert_eq!(
- persisted,
- vec![
- "stored system prompt",
- "first question",
- "first answer",
- "second question",
- "third question",
- ],
- );
-}
diff --git a/crates/openhuman-core/src/agent/harness/session/turn/context_tests.rs b/crates/openhuman-core/src/agent/harness/session/turn/context_tests.rs
deleted file mode 100644
index e75aa165cf..0000000000
--- a/crates/openhuman-core/src/agent/harness/session/turn/context_tests.rs
+++ /dev/null
@@ -1,63 +0,0 @@
-//! Where the tool-policy boundary lands relative to the persona (#5704).
-//!
-//! Extracted from `context.rs` — the Rust layout gate requires test modules to
-//! live in a sibling `*_tests.rs` file rather than inline.
-
-use super::append_tool_policy_boundary;
-
-const PERSONA: &str = "You are the archetype.\nMore persona.";
-const BOUNDARY: &str = "## Tool Policy Boundary\n- Agent: alpha";
-
-#[test]
-fn the_boundary_goes_after_the_prompt_body() {
- let out = append_tool_policy_boundary(PERSONA.into(), Some(BOUNDARY.into()));
- let body_at = out.find("You are the archetype.").expect("body present");
- let boundary_at = out
- .find("## Tool Policy Boundary")
- .expect("boundary present");
- assert!(
- body_at < boundary_at,
- "the session-scoped block must not precede the stable prompt (#5704):\n{out}"
- );
-}
-
-#[test]
-fn the_persona_stays_the_opening_line() {
- let out = append_tool_policy_boundary(PERSONA.into(), Some(BOUNDARY.into()));
- assert_eq!(
- out.lines().next(),
- Some("You are the archetype."),
- "prepending replaced every agent's first line with a constant heading"
- );
-}
-
-#[test]
-fn two_agents_share_the_whole_prompt_body_as_a_common_prefix() {
- // The point of appending: the varying part is last, so everything the
- // two turns have in common is a shared leading prefix the backend can
- // reuse. Prepending moved the first diverging byte to offset 0.
- let alpha = append_tool_policy_boundary(
- PERSONA.into(),
- Some("## Tool Policy Boundary\n- Agent: alpha".into()),
- );
- let beta = append_tool_policy_boundary(
- PERSONA.into(),
- Some("## Tool Policy Boundary\n- Agent: beta".into()),
- );
- let shared = alpha
- .bytes()
- .zip(beta.bytes())
- .take_while(|(a, b)| a == b)
- .count();
- assert!(
- shared >= PERSONA.len(),
- "the shared prefix ({shared} bytes) must cover the whole stable body ({} bytes)",
- PERSONA.len()
- );
-}
-
-#[test]
-fn no_boundary_leaves_the_prompt_untouched() {
- let out = append_tool_policy_boundary(PERSONA.into(), None);
- assert_eq!(out, PERSONA);
-}
diff --git a/crates/openhuman-core/src/agent/harness/session/turn/core.rs b/crates/openhuman-core/src/agent/harness/session/turn/core.rs
deleted file mode 100644
index 881fc35074..0000000000
--- a/crates/openhuman-core/src/agent/harness/session/turn/core.rs
+++ /dev/null
@@ -1,250 +0,0 @@
-//! Core turn execution: the main `turn()` method and `inject_agent_experience_context()`.
-
-use super::super::types::Agent;
-use super::{
- integration_announcement_note, mcp_announcement_note, newly_connected_slugs,
- skill_announcement_note, skill_retraction_note,
-};
-use crate::agent::harness;
-use crate::agent::hooks::{self};
-use crate::agent::messages::{ChatMessage, ConversationMessage};
-use crate::agent::progress::AgentProgress;
-use crate::memory::agent::memory_loader::collect_recall_citations;
-use crate::memory::MemoryCategory;
-
-use anyhow::Result;
-use std::hash::{Hash, Hasher};
-
-/// The outcome captured for one assistant tool call, matched by call id, tool
-/// name **and occurrence**.
-///
-/// Prompt-guided (XML / P-Format) calls carry no provider id, so every model
-/// response synthesizes `call_0`, `call_1`, … afresh (`tinyagents::model`), and a
-/// turn with several tool rounds repeats the same ids. A first-match lookup gave
-/// every later round the first round's result, so a turn's records could hide its
-/// latest failure (Codex review on #6289). The n-th call under an `(id, name)`
-/// takes the n-th outcome recorded under it: rounds run in order and ids are
-/// unique within a round, so parallel execution inside a round cannot reorder
-/// them. Keying on the name as well stops an unknown-tool call, which never
-/// reaches the capture sink, from consuming a later round's real outcome.
-fn nth_call_outcome<'a>(
- tool_outcomes: &'a [crate::agent::tinyagents::ToolCallOutcome],
- seen: &mut std::collections::HashMap<(String, String), usize>,
- call_id: &str,
- name: &str,
-) -> Option<&'a crate::agent::tinyagents::ToolCallOutcome> {
- let occurrence = seen
- .entry((call_id.to_string(), name.to_string()))
- .or_insert(0);
- let outcome = tool_outcomes
- .iter()
- .filter(|o| o.call_id == call_id && o.name == name)
- .nth(*occurrence);
- *occurrence += 1;
- outcome
-}
-
-/// Flatten the assistant tool calls a turn produced into [`ToolCallRecord`]s for
-/// post-turn hooks + the deterministic cap checkpoint. Per-call success +
-/// sanitized output summary are recovered from the turn's captured
-/// [`ToolCallOutcome`]s (correlated by provider call id), since the harness folds
-/// a tool result into a `Message::tool` that drops its failure flag — matching the
-/// engine's honest per-call accounting instead of recording every call as ok.
-fn tool_records_from_conversation(
- conversation: &[ConversationMessage],
- tool_outcomes: &[crate::agent::tinyagents::ToolCallOutcome],
-) -> Vec<hooks::ToolCallRecord> {
- let mut records = Vec::new();
- let mut seen = std::collections::HashMap::new();
- for msg in conversation {
- if let ConversationMessage::AssistantToolCalls { tool_calls, .. } = msg {
- for call in tool_calls {
- let outcome = nth_call_outcome(tool_outcomes, &mut seen, &call.id, &call.name);
- // Default a MISSING outcome to `false` (#4467, item 7): a call
- // with no captured outcome is a hallucinated/unknown tool the
- // crate recovered via `ReturnToolError` without running
- // `after_tool` (so the capture sink never saw it). Recording it as
- // succeeded misreports the timeline; real executed tools always
- // have an outcome, so this only flips the genuinely-unknown case.
- let success = outcome.map(|o| o.success).unwrap_or(false);
- let output_summary = outcome
- .map(|o| hooks::sanitize_tool_output(&o.content, &call.name, success))
- .unwrap_or_default();
- records.push(hooks::ToolCallRecord {
- name: call.name.clone(),
- arguments: serde_json::from_str(&call.arguments)
- .unwrap_or(serde_json::Value::Null),
- success,
- output_summary,
- duration_ms: 0,
- });
- }
- }
- }
- records
-}
-
-/// The cap checkpoint's view of this turn's tool calls: name, status, and a
-/// truncated slice of the **actual output** (issue #6014).
-///
-/// The sibling of [`tool_records_from_conversation`] above, and separate from
-/// it on purpose. That one builds `hooks::ToolCallRecord`s, whose
-/// `output_summary` is deliberately sanitized to carry no raw output — right
-/// for the learning pipeline it feeds, useless for a checkpoint the user reads
-/// in place of the answer the turn ran out of room to write. Reading
-/// `ToolCallOutcome::content` directly here keeps the raw payload on the one
-/// path that needs it instead of widening the sanitized type for everyone.
-fn checkpoint_results_from_conversation(
- conversation: &[ConversationMessage],
- tool_outcomes: &[crate::agent::tinyagents::ToolCallOutcome],
-) -> Vec<super::super::turn_checkpoint::CheckpointToolResult> {
- let mut results = Vec::new();
- let mut seen = std::collections::HashMap::new();
- for msg in conversation {
- if let ConversationMessage::AssistantToolCalls { tool_calls, .. } = msg {
- for call in tool_calls {
- let outcome = nth_call_outcome(tool_outcomes, &mut seen, &call.id, &call.name);
- // Same missing-outcome rule as `tool_records_from_conversation`:
- // a call the crate recovered without running `after_tool` never
- // reached the capture sink, so it is reported as failed rather
- // than silently as a success.
- let success = outcome.map(|o| o.success).unwrap_or(false);
- let content = outcome
- .map(|o| {
- super::super::turn_checkpoint::truncate_chars(
- &o.content,
- super::super::turn_checkpoint::CHECKPOINT_RESULT_CHARS,
- )
- })
- .unwrap_or_default();
- results.push(super::super::turn_checkpoint::CheckpointToolResult {
- name: call.name.clone(),
- success,
- content,
- });
- }
- }
- }
- results
-}
-
-/// Stamp each **failed** tool-result [`ChatMessage`] with its failure outcome
-/// before persistence, so the derived transcript view can render an error tool
-/// row instead of a false success.
-///
-/// The harness folds a tool result into a `role:"tool"` message whose native
-/// content envelope (`{"tool_call_id":…,"content":…}`) has already dropped
-/// `ToolResult::is_error`. The only structured per-call success signal is the
-/// captured [`ToolCallOutcome`] side-channel; correlate by provider call id and
-/// re-attach an additive failure marker (see
-/// `transcript::attach_tool_failure_metadata`). Non-tool messages, tool messages
-/// with no matching outcome, and successful calls are left untouched.
-fn stamp_tool_failures(
- messages: &mut [ChatMessage],
- tool_outcomes: &[crate::agent::tinyagents::ToolCallOutcome],
-) {
- if tool_outcomes.is_empty() {
- return;
- }
- for msg in messages.iter_mut() {
- if msg.role != "tool" {
- continue;
- }
- let Some(call_id) = parse_tool_call_id(&msg.content) else {
- continue;
- };
- let Some(outcome) = tool_outcomes.iter().find(|o| o.call_id == call_id) else {
- continue;
- };
- if outcome.success {
- continue;
- }
- let detail = short_failure_detail(&outcome.content);
- log::debug!(
- "[transcript] stamping tool failure call_id={call_id} name={}",
- outcome.name
- );
- crate::agent::messages::attach_chat_tool_failure_metadata(msg, detail.as_deref());
- }
-}
-
-/// Extract the `tool_call_id` from a native tool-result content envelope
-/// (`{"tool_call_id":…,"content":…}`). `None` for non-envelope content (XML /
-/// P-Format dispatchers, which don't emit `role:"tool"` messages anyway).
-fn parse_tool_call_id(content: &str) -> Option<String> {
- let value: serde_json::Value = serde_json::from_str(content).ok()?;
- value.get("tool_call_id")?.as_str().map(str::to_string)
-}
-
-/// Reduce a tool's error output to a short, single-line reason for display.
-fn short_failure_detail(content: &str) -> Option<String> {
- const MAX: usize = 160;
- let line = content.lines().map(str::trim).find(|l| !l.is_empty())?;
- let short: String = line.chars().take(MAX).collect();
- if short.is_empty() {
- None
- } else {
- Some(short)
- }
-}
-
-/// Rewrite the **trailing** assistant `Chat` message in `history` to `text`,
-/// keeping the persisted transcript and the next turn's KV-cache prefix
-/// consistent with a repaired required-output reply (issue #4117). Only the last
-/// row is touched — when the tail is not an assistant `Chat` (defensive; a clean
-/// finish, a cap checkpoint, and the #4093 close all end on one) a fresh
-/// assistant message is appended rather than mutating an older entry.
-#[cfg(test)]
-#[path = "core_tests.rs"]
-mod tests;
-
-/// Whether a history row is an assistant `Chat` with nothing in it.
-///
-/// The cap path's concluding call can answer with empty text, and that message
-/// is folded into the history before the out-of-band wrap-up builds its request
-/// from it. Anthropic rejects a message with empty content, so it has to go
-/// (CodeRabbit on #6068).
-pub(super) fn is_empty_assistant_chat(message: &ConversationMessage) -> bool {
- matches!(message, ConversationMessage::Chat(chat)
- if chat.role == "assistant" && chat.content.trim().is_empty())
-}
-
-fn replace_last_assistant_reply(history: &mut Vec<ConversationMessage>, text: &str) {
- match history.last_mut() {
- Some(ConversationMessage::Chat(chat)) if chat.role == "assistant" => {
- chat.content = text.to_string();
- }
- _ => history.push(ConversationMessage::Chat(ChatMessage::assistant(
- text.to_string(),
- ))),
- }
-}
-
-fn render_agent_context_status_note(sources: &[harness::AgentContextPreparedSource]) -> String {
- let sources = if sources.is_empty() {
- "the OpenHuman harness".to_string()
- } else {
- sources
- .iter()
- .map(|source| source.source.as_str())
- .collect::<Vec<_>>()
- .join(", ")
- };
- format!(
- "## Agent context status\n\nAgent context retrieval/preparation has already run once \
- for this turn in code via {sources}. Do not call `agent_prepare_context` again for \
- general context preparation. Use the prepared context below, and call only specific \
- follow-up tools if a concrete missing detail is required."
- )
-}
-
-include!("core_turn.rs");
-
-// `Agent`'s tinyagents-backed chat turn and the pre-turn context injection it
-// calls, split by responsibility into real submodules. Their `impl Agent`
-// blocks complement `turn()` above.
-mod experience_context;
-mod failed_turn;
-mod grounded_close;
-mod harness_turn;
-mod resumed_prefix;
diff --git a/crates/openhuman-core/src/agent/harness/session/turn/core/experience_context.rs b/crates/openhuman-core/src/agent/harness/session/turn/core/experience_context.rs
deleted file mode 100644
index 6eccf73142..0000000000
--- a/crates/openhuman-core/src/agent/harness/session/turn/core/experience_context.rs
+++ /dev/null
@@ -1,184 +0,0 @@
-//! Pre-turn context injection: agent-experience retrieval and the triggered
-//! memory-agent block prepended to the enriched user message.
-
-use crate::agent::experience::{
- prepend_experience_block, render_experience_hits, retrieve_across_stores, AgentExperienceStore,
- ExperienceQuery,
-};
-use crate::agent::harness;
-use crate::agent::harness::definition::TriggerMemoryAgent;
-use crate::agent::harness::fork_context::ParentExecutionContext;
-use crate::agent::harness::session::types::Agent;
-use crate::util::truncate_with_ellipsis;
-
-impl Agent {
- pub(in crate::agent::harness::session::turn) async fn inject_agent_experience_context(
- &self,
- user_message: &str,
- enriched: String,
- ) -> String {
- const MAX_EXPERIENCE_HITS: usize = 3;
- const MAX_EXPERIENCE_BLOCK_BYTES: usize = 2048;
-
- if !self.learning_enabled {
- return enriched;
- }
-
- let tools = self
- .visible_tool_specs
- .iter()
- .map(|spec| spec.name.clone())
- .collect();
- let stores = vec![AgentExperienceStore::new(self.memory.clone())];
- let query = ExperienceQuery {
- query: user_message.to_string(),
- tools,
- tags: Vec::new(),
- agent_id: Some(self.agent_definition_id.clone()).filter(|id| !id.trim().is_empty()),
- entrypoint: Some(self.event_channel.clone())
- .filter(|entrypoint| !entrypoint.trim().is_empty()),
- max_hits: MAX_EXPERIENCE_HITS,
- };
-
- match retrieve_across_stores(&stores, query).await {
- Ok(hits) => {
- let matched_hits: Vec<_> = hits
- .into_iter()
- .filter(|hit| !hit.match_reasons.is_empty())
- .collect();
- let block = render_experience_hits(&matched_hits, MAX_EXPERIENCE_BLOCK_BYTES);
- if block.is_empty() {
- return enriched;
- }
- log::debug!(
- "[agent-experience] injected {} experience hit(s) bytes={}",
- matched_hits.len(),
- block.len()
- );
- prepend_experience_block(&enriched, &block)
- }
- Err(err) => {
- log::warn!("[agent-experience] retrieval failed (non-fatal): {err}");
- enriched
- }
- }
- }
-
- pub(super) async fn inject_triggered_memory_agent_context(
- &self,
- user_message: &str,
- enriched: String,
- parent_context: &ParentExecutionContext,
- force_skip: bool,
- ) -> (String, bool) {
- const MEMORY_AGENT_ID: &str = "agent_memory";
- const MAX_MEMORY_AGENT_BLOCK_CHARS: usize = 8000;
-
- if force_skip {
- // Per-turn override (#1725): a chat / small-talk turn skips the
- // pre-turn memory-agent retrieval even when this agent's policy is
- // `Always`, so a greeting never pulls a prior task's remembered
- // context into an unrelated reply.
- log::debug!(
- "[agent_memory:trigger] skipped agent_id={} (per-turn suppress_memory_agent override)",
- self.agent_definition_id
- );
- return (enriched, false);
- }
-
- if self.trigger_memory_agent != TriggerMemoryAgent::Always {
- log::debug!(
- "[agent_memory:trigger] skipped agent_id={} policy={:?}",
- self.agent_definition_id,
- self.trigger_memory_agent
- );
- return (enriched, false);
- }
-
- if self.agent_definition_id == MEMORY_AGENT_ID {
- log::debug!("[agent_memory:trigger] skipped recursive memory agent invocation");
- return (enriched, false);
- }
-
- let Some(registry) = harness::AgentDefinitionRegistry::global() else {
- log::warn!(
- "[agent_memory:trigger] AgentDefinitionRegistry unavailable; continuing without memory agent context"
- );
- return (enriched, false);
- };
- let Some(definition) = registry.get(MEMORY_AGENT_ID).cloned() else {
- log::warn!(
- "[agent_memory:trigger] `{MEMORY_AGENT_ID}` definition unavailable; continuing without memory agent context"
- );
- return (enriched, false);
- };
-
- let task_id = format!("mem-trigger-{}", uuid::Uuid::new_v4());
- let prompt = format!(
- "Search the user's memory tree and return only context relevant to the next agent turn.\n\nUser prompt:\n{user_message}"
- );
- let options = harness::SubagentRunOptions {
- task_id: Some(task_id.clone()),
- model_override: Some(parent_context.model_name.clone()),
- run_context: crate::agent::tinyagents::host::OpenHumanRunContext::new()
- .with_parent(parent_context.clone()),
- ..Default::default()
- };
-
- log::debug!(
- "[agent_memory:trigger] starting agent_id={} task_id={} user_message_chars={}",
- self.agent_definition_id,
- task_id,
- user_message.chars().count()
- );
-
- let started = std::time::Instant::now();
- let result = harness::run_subagent(&definition, &prompt, options).await;
-
- match result {
- Ok(outcome) => {
- log::info!(
- "[agent_memory:trigger] completed agent_id={} task_id={} iterations={} elapsed={:?} status={:?} output_chars={}",
- self.agent_definition_id,
- task_id,
- outcome.iterations,
- started.elapsed(),
- outcome.status,
- outcome.output.chars().count()
- );
- let mut output =
- truncate_with_ellipsis(&outcome.output, MAX_MEMORY_AGENT_BLOCK_CHARS);
- if let harness::subagent_runner::SubagentRunStatus::AwaitingUser {
- question, ..
- } = &outcome.status
- {
- let question = question.trim();
- if !question.is_empty() {
- output.push_str("\n\nMemory agent needs clarification: ");
- output.push_str(question);
- }
- }
- output = truncate_with_ellipsis(&output, MAX_MEMORY_AGENT_BLOCK_CHARS);
- if output.trim().is_empty() {
- return (enriched, false);
- }
- (
- format!(
- "## Memory agent context\n\n{}\n\n---\n\n{}",
- output.trim(),
- enriched
- ),
- true,
- )
- }
- Err(err) => {
- log::warn!(
- "[agent_memory:trigger] failed agent_id={} task_id={}: {err:#}",
- self.agent_definition_id,
- task_id
- );
- (enriched, false)
- }
- }
- }
-}
diff --git a/crates/openhuman-core/src/agent/harness/session/turn/core/failed_turn.rs b/crates/openhuman-core/src/agent/harness/session/turn/core/failed_turn.rs
deleted file mode 100644
index 5b516f7d50..0000000000
--- a/crates/openhuman-core/src/agent/harness/session/turn/core/failed_turn.rs
+++ /dev/null
@@ -1,156 +0,0 @@
-//! Keeping what a failed chat turn did (#6281).
-
-use crate::agent::harness::session::turn_checkpoint::{truncate_chars, CHECKPOINT_RESULT_CHARS};
-use crate::agent::harness::session::types::Agent;
-use crate::agent::harness::tool_result_artifacts::ToolResultArtifactStore;
-use crate::agent::messages::{ChatMessage, ConversationMessage};
-use crate::agent::tinyagents::{
- render_unanswered_steps, TranscriptSnapshot, TranscriptSnapshotSink,
-};
-use anyhow::Result;
-use tinyagents_session::transcript::{MessageUsage, TurnUsage};
-use tinyinference_llm::message::Message;
-
-/// Leads the note a failed turn leaves in history, so the model (and a reader
-/// of the transcript) can tell it from a reply.
-const FAILED_TURN_NOTE_PREFIX: &str = "[turn failed before completion:";
-
-impl Agent {
- /// Drive the chat turn and, if it fails, keep what it did.
- ///
- /// `turn()` has already pushed this turn's user message, but on `Err` the
- /// turn body returned before anything else it produced reached `history` or
- /// the transcript. Every follow-up ("what happened?", "try again") then ran
- /// without the tool calls, their results, or the reason the turn failed.
- ///
- /// On any error from the turn body (provider, harness, tool loop, or a typed
- /// error raised after the loop) this appends the rounds the provider had
- /// already accepted, then a failure note, and persists the transcript, so a
- /// warm follow-up and a cold-boot resume both see them. A turn future that is
- /// dropped (cancelled) is not an error and records nothing here.
- pub(super) async fn run_turn_via_tinyagents_session(
- &mut self,
- user_message: &str,
- effective_model: &str,
- temperature: f64,
- max_iterations: usize,
- artifact_store: Option<ToolResultArtifactStore>,
- suppress_tools: bool,
- run_context: crate::agent::tinyagents::host::OpenHumanRunContext,
- ) -> Result<String> {
- let snapshot = TranscriptSnapshotSink::default();
- let result = Box::pin(self.run_turn_via_tinyagents_session_inner(
- user_message,
- effective_model,
- temperature,
- max_iterations,
- artifact_store,
- suppress_tools,
- run_context,
- snapshot.clone(),
- ))
- .await;
- if let Err(err) = &result {
- let snapshot = std::mem::take(
- &mut *snapshot
- .lock()
- .unwrap_or_else(std::sync::PoisonError::into_inner),
- );
- self.record_failed_turn(&snapshot, effective_model, err);
- }
- result
- }
-
- fn record_failed_turn(
- &mut self,
- snapshot: &TranscriptSnapshot,
- effective_model: &str,
- err: &anyhow::Error,
- ) {
- let base = snapshot.request_base_len.min(snapshot.messages.len());
- let accepted_end = snapshot.accepted_end();
- let accepted = &snapshot.messages[base..accepted_end];
- let unanswered = &snapshot.messages[accepted_end..];
- log::warn!(
- "[agent_loop] turn failed; recording {} accepted round message(s), {} unanswered \
- message(s) as text, and the failure cause into history session_id={} \
- request_id={} model={} — #6281",
- accepted.len(),
- unanswered.len(),
- self.event_session_id,
- crate::agent::turn_origin::current_request_id()
- .as_deref()
- .unwrap_or("-"),
- effective_model
- );
- // Only rounds the provider already answered are replayed as structured
- // messages. The newest round was carried only by the failing request, and
- // a request rejected for malformed tool history must not be replayed, or
- // the de-poison eviction in `web_chat::run_task` would reseed the same
- // rejection from this transcript. That round goes into the note as text.
- self.history
- .extend(crate::agent::message_convert::messages_to_conversation(
- accepted,
- ));
- self.history
- .push(ConversationMessage::Chat(ChatMessage::assistant(
- failed_turn_note(err, unanswered),
- )));
- self.trim_history();
-
- // The calls the provider answered were billed even though the turn
- // failed. Their spend already reached the cost tracker live (the event
- // bridge records usage per call); the transcript records the same totals
- // instead of zeros.
- let (input, output, cached) = (
- snapshot.input_tokens,
- snapshot.output_tokens,
- snapshot.cached_input_tokens,
- );
- let cost_usd = crate::platform::cost::catalog::estimate_cost_usd(
- effective_model,
- input,
- output,
- cached,
- );
- let persisted = crate::agent::message_convert::provider_messages_from_conversation(
- self.tool_dispatcher.as_ref(),
- &self.history,
- );
- let turn_usage = TurnUsage {
- provider: self.event_channel().to_string(),
- model: effective_model.to_string(),
- usage: MessageUsage {
- input,
- output,
- cached_input: cached,
- context_window: 0,
- cost_usd,
- },
- ts: chrono::Utc::now().to_rfc3339(),
- reasoning_content: None,
- tool_calls: Vec::new(),
- iteration: snapshot.model_calls,
- };
- self.persist_session_transcript(
- &persisted,
- input,
- output,
- cached,
- cost_usd,
- Some(&turn_usage),
- );
- }
-}
-
-/// The failure cause, plus the unanswered steps rendered as text.
-fn failed_turn_note(err: &anyhow::Error, unanswered: &[Message]) -> String {
- let cause = format!(
- "{FAILED_TURN_NOTE_PREFIX} {}]",
- truncate_chars(&err.to_string(), CHECKPOINT_RESULT_CHARS)
- );
- match render_unanswered_steps(unanswered) {
- Some(steps) => format!("{cause}\n\n{steps}"),
- None => cause,
- }
-}
diff --git a/crates/openhuman-core/src/agent/harness/session/turn/core/grounded_close.rs b/crates/openhuman-core/src/agent/harness/session/turn/core/grounded_close.rs
deleted file mode 100644
index d9af71fc3d..0000000000
--- a/crates/openhuman-core/src/agent/harness/session/turn/core/grounded_close.rs
+++ /dev/null
@@ -1,126 +0,0 @@
-//! Close a turn that has no usable reply of its own from its tool records: a
-//! tool turn that ended without final text (#4093, #6278) or a run the
-//! no-progress breaker halted (#6279).
-
-use crate::agent::harness::session::turn_checkpoint::{self, CloseVerdict};
-use crate::agent::harness::session::types::Agent;
-use crate::agent::messages::{ChatMessage, ConversationMessage};
-use crate::agent::tinyagents::TinyagentsTurnOutcome;
-use crate::inference::provider::UsageInfo;
-
-impl Agent {
- /// Write the closing message for a turn whose run produced no usable reply:
- /// the loop ended on empty text after tool work (#4093), or the breaker
- /// halted it (`outcome.breaker_halt`, #6279).
- ///
- /// Three steps, each closing a way the old path shipped a non-answer:
- ///
- /// 1. **Grounded wrap-up.** One tools-disabled call whose instruction
- /// restates this turn's tool records, failures and their messages
- /// included, plus the breaker's stop note as input. Context middleware
- /// may have cleared or summarised those bodies earlier in the turn, and a
- /// model that cannot see a success will say it never happened (#6278).
- /// 2. **Check.** A separate call that sees only the request, the records and
- /// the candidate rejects a reply that narrates intent, contradicts a
- /// record, or drops the failure that explains an unfinished request.
- /// 3. **Fallback.** An empty, tool-calling, rejected or unverified close
- /// (the check failed or gave no verdict) is replaced by
- /// [`turn_checkpoint::build_deterministic_final_summary`], which quotes
- /// each result and the stop note.
- ///
- /// Accepted model text is streamed only after the check, so a rejected
- /// reply never renders and the streamed text matches the persisted one. The
- /// reply is pushed onto `history`, and the usage of every extra call is
- /// returned for the caller's turn accounting.
- pub(super) async fn close_turn_from_records(
- &mut self,
- outcome: &TinyagentsTurnOutcome,
- user_message: &str,
- effective_model: &str,
- ) -> (String, Vec<UsageInfo>) {
- let stop_reason = outcome.breaker_halt.as_deref();
- let mut usage = Vec::new();
-
- // The run folded its blank terminal assistant response into history (an
- // empty `Chat(assistant(""))`). Drop it before the wrap-up request and
- // before the reply is appended: strict providers reject empty content,
- // and the transcript must not carry a dangling blank turn.
- if self
- .history
- .last()
- .is_some_and(super::is_empty_assistant_chat)
- {
- self.history.pop();
- }
-
- let results = super::checkpoint_results_from_conversation(
- &outcome.conversation,
- &outcome.tool_outcomes,
- );
- let records =
- turn_checkpoint::render_tool_results(&results, turn_checkpoint::GROUNDING_TOTAL_CHARS);
- let iteration = outcome.model_calls as u32 + 1;
-
- let base = crate::agent::message_convert::provider_messages_from_conversation(
- self.tool_dispatcher.as_ref(),
- &self.history,
- );
- let (candidate, candidate_usage) = self
- .summarize_turn_wrapup(
- &base,
- effective_model,
- iteration,
- &turn_checkpoint::final_answer_instruction(stop_reason, &records),
- false,
- )
- .await;
- usage.extend(candidate_usage);
-
- let verdict = if candidate.trim().is_empty() {
- None
- } else {
- let prompt =
- turn_checkpoint::close_verification_prompt(user_message, &records, &candidate);
- let (verdict_text, verdict_usage) = self
- .silent_completion(
- &[ChatMessage::user(prompt)],
- effective_model,
- "closing-message check",
- )
- .await;
- usage.extend(verdict_usage);
- Some(turn_checkpoint::parse_close_verdict(&verdict_text))
- };
- if verdict == Some(CloseVerdict::Unclear) {
- log::warn!(
- "[agent_loop] closing-message check returned no ACCEPT/REJECT verdict; using the deterministic fallback"
- );
- }
-
- // Only an explicit ACCEPT ships the model's text. A failed or malformed
- // check leaves the reply unverified, and shipping unverified closing text
- // is the defect this path exists to stop (CodeRabbit on #6289).
- let accepted = verdict == Some(CloseVerdict::Accept);
- let reply = if accepted {
- self.stream_text_continuation(&candidate, iteration).await;
- candidate
- } else {
- turn_checkpoint::build_deterministic_final_summary(&results, stop_reason)
- };
-
- log::info!(
- "[agent_loop] closed turn from tool records after {} tool call(s): halted={} verdict={:?} fallback={} ({} chars) — #4093 #6278 #6279",
- outcome.tool_calls,
- stop_reason.is_some(),
- verdict,
- !accepted,
- reply.chars().count()
- );
-
- self.history
- .push(ConversationMessage::Chat(ChatMessage::assistant(
- reply.clone(),
- )));
- (reply, usage)
- }
-}
diff --git a/crates/openhuman-core/src/agent/harness/session/turn/core/harness_turn.rs b/crates/openhuman-core/src/agent/harness/session/turn/core/harness_turn.rs
deleted file mode 100644
index 507edc2600..0000000000
--- a/crates/openhuman-core/src/agent/harness/session/turn/core/harness_turn.rs
+++ /dev/null
@@ -1,588 +0,0 @@
-//! The tinyagents-backed chat turn driver (`run_turn_via_tinyagents_session`).
-//!
-//! Converts the frozen history to provider messages, runs the harness loop over
-//! the agent's tools, applies the deterministic cap / final-answer fallbacks,
-//! persists the transcript, and fires post-turn hooks.
-
-use super::{
- checkpoint_results_from_conversation, is_empty_assistant_chat, replace_last_assistant_reply,
- stamp_tool_failures, tool_records_from_conversation,
-};
-use crate::agent::harness::session::turn::graph;
-use crate::agent::harness::session::turn_checkpoint;
-use crate::agent::harness::session::types::Agent;
-use crate::agent::hooks::{self, TurnContext};
-use crate::agent::messages::{ChatMessage, ConversationMessage};
-use crate::agent::progress::AgentProgress;
-use crate::memory::MemoryCategory;
-use crate::util::truncate_with_ellipsis;
-use anyhow::Result;
-
-impl Agent {
- /// Drive a full chat turn through the `tinyagents` harness (issue #4249).
- ///
- /// The frozen system+prior history is converted to provider messages, the
- /// user turn appended, and the loop run over the agent's resolved tools. The
- /// final reply + the user turn are recorded into `history`, the transcript
- /// is persisted, and `TurnCompleted` is emitted so the UI stops spinning.
- ///
- /// Full-fidelity with the legacy `run_turn_engine`: live tool-timeline /
- /// text-delta progress and the cost/token footer are mirrored from the
- /// harness event stream via `OpenhumanEventBridge` (tinyagents harness),
- /// `[IMAGE:…]`/`[FILE:…]` markers are expanded for the provider, and history
- /// is trimmed to the provider's context window.
- ///
- /// Called through [`Agent::run_turn_via_tinyagents_session`], which records
- /// a failed turn from `transcript_snapshot` (#6281).
- #[allow(clippy::too_many_arguments)]
- pub(super) async fn run_turn_via_tinyagents_session_inner(
- &mut self,
- user_message: &str,
- effective_model: &str,
- temperature: f64,
- max_iterations: usize,
- artifact_store: Option<
- crate::agent::harness::tool_result_artifacts::ToolResultArtifactStore,
- >,
- suppress_tools: bool,
- run_context: crate::agent::tinyagents::host::OpenHumanRunContext,
- transcript_snapshot: crate::agent::tinyagents::TranscriptSnapshotSink,
- ) -> Result<String> {
- let turn_started = std::time::Instant::now();
- // This turn's stamped user message is already the last entry in
- // `self.history` (pushed by `turn()` before the engine branch), so build
- // the provider messages straight from history — do NOT push the user
- // again. A resumed session's replayed prefix is folded into that same
- // history first (see below), so there is exactly one sequence to read.
- self.absorb_resumed_transcript_prefix();
- let mut messages = crate::agent::message_convert::provider_messages_from_conversation(
- self.tool_dispatcher.as_ref(),
- &self.history,
- );
-
- // Multimodal prep (parity with the legacy engine): rehydrate image
- // placeholders for vision-capable providers, then expand `[IMAGE:…]` /
- // `[FILE:…]` markers into provider-ready content before dispatch. The
- // expanded copy is provider-only and never persisted to `history`.
- let multimodal = self
- .runtime_config
- .as_ref()
- .map(|c| c.multimodal.clone())
- .unwrap_or_default();
- let multimodal_files = self
- .runtime_config
- .as_ref()
- .map(|c| c.multimodal_files.clone())
- .unwrap_or_default();
- // Resolve the effective context window and build the turn's tiered crate
- // `ChatModel` set from the session source up front (issue #4249, Phase 3 /
- // Motion A) — the harness holds crate model types, and the vision read
- // below comes off the built models, not a raw provider.
- let context_window = self
- .turn_model_source
- .effective_context_window(effective_model)
- .await;
- let turn_models = self.turn_model_source.build(
- effective_model,
- temperature,
- context_window,
- self.thread_id(),
- )?;
-
- // Honor custom/BYOK vision models too: they can set `model_vision` even
- // when the provider capability bit is false, and must still rehydrate
- // `[IMAGE:…]` placeholders (else image chat silently degrades to text).
- if (turn_models.supports_vision() || self.model_vision)
- && crate::agent::multimodal::has_image_placeholders(&messages)
- {
- messages = crate::agent::multimodal::rehydrate_image_placeholders(&messages);
- }
- let messages = crate::agent::multimodal::prepare_messages_for_provider(
- &messages,
- &multimodal,
- &multimodal_files,
- )
- .await
- .map(|prepared| prepared.messages)
- .unwrap_or(messages);
- // The rounds this run produces start after the transcript it is seeded
- // with; a failed turn records only those (#6281).
- transcript_snapshot
- .lock()
- .unwrap_or_else(std::sync::PoisonError::into_inner)
- .request_base_len = messages.len();
-
- // Per-turn tool scope (#1725). A chat / small-talk turn runs with an
- // EMPTY tool set: the provider request carries no tool schema, so the
- // model cannot enter the tool loop and answers in a single call. The
- // agent's durable `self.tools` / `self.visible_tool_names` are left
- // untouched — the next un-overridden turn gets the full toolbelt back.
- let (turn_tools, turn_synthesized_tools, turn_visible_tool_names) =
- self.turn_tool_sets(suppress_tools);
-
- tracing::info!(
- model = %effective_model,
- max_iterations,
- tools = turn_tools.len() + turn_synthesized_tools.len(),
- suppress_tools,
- "[agent_loop] routing chat turn through the tinyagents harness"
- );
-
- // Dispatch through the chat turn graph (this folder's `graph.rs`): a thin
- // wrapper over the shared tinyagents seam that pins the chat path's fixed
- // arguments (no child scope, no early-exit tools, graceful cap pause,
- // per-turn output cap) and runs the context-window summarization step.
- // Context middlewares sourced from this session's ContextManager: the
- // per-tool-result byte cap + payload summarizer (after_tool) and
- // microcompact tool-body clearing (before_model). KV-cache-prefix drift
- // detection is owned by the crate `PromptCacheGuardMiddleware` (fed by
- // `PromptCacheSegmentMiddleware`); the warn-only `CacheAlignMiddleware`
- // was deleted in C3.
- let context_mw = crate::agent::tinyagents::TurnContextMiddleware {
- tool_result_budget_bytes: self.context.tool_result_budget_bytes(),
- payload_summarizer: self.payload_summarizer.clone(),
- // The raw user message (the date-stamped copy lives in history):
- // what the summarizer should keep facts for (#6283).
- task_hint: Some(user_message.to_string()),
- artifact_store,
- tokenjuice_compaction_enabled: self.context.compaction_enabled(),
- tokenjuice_compression: self.tokenjuice_compression,
- runtime_config: self.runtime_config.clone(),
- microcompact_keep_recent: self.context.microcompact_keep_recent(),
- // Honor the [context].enabled / autocompact_enabled opt-outs: when off,
- // the summarization middleware is not installed (no summarizer tokens,
- // no history rewrite).
- autocompact_enabled: self.context.autocompact_enabled(),
- // Progressive-disclosure handoff is a sub-agent (integrations_agent)
- // concern; the top-level chat turn never sets it.
- handoff: None,
- // The harness drops its working transcript on `Err`; the snapshot
- // is how a failed turn still keeps the rounds it completed (#6281).
- transcript_snapshot: Some(transcript_snapshot.clone()),
- };
-
- let outcome = graph::run_chat_turn_graph(graph::ChatTurnGraph {
- turn_models,
- model: effective_model.to_string(),
- messages,
- tools: turn_tools,
- synthesized_tools: turn_synthesized_tools,
- visible_tool_names: turn_visible_tool_names,
- max_iterations,
- on_progress: self.on_progress.clone(),
- context_window,
- run_queue: self.run_queue.clone(),
- context_mw,
- // Enforce the builder-configured tool policy at the tool
- // boundary (the tinyagents path otherwise bypasses it).
- tool_policy: Some(crate::agent::tinyagents::ToolPolicyEnforcement {
- policy: self.tool_policy.clone(),
- session: self.tool_policy_session.clone(),
- session_id: self.event_session_id.clone(),
- channel: self.event_channel().to_string(),
- agent_definition_id: self.agent_definition_id.clone(),
- }),
- // Section D: forward the session's turn workspace descriptor (if
- // any) so the top-level chat turn's acting tools use its root as
- // their default cwd.
- workspace_descriptor: self.workspace_descriptor.clone(),
- // Scope direct Master-Agent calls under its declared
- // sandbox. `agent_definition_name` can carry a thread
- // suffix, so resolve with the stable definition id.
- sandbox_mode: self
- .resolved_definition()
- .map(|definition| definition.sandbox_mode)
- .unwrap_or(crate::agent::harness::definition::SandboxMode::None),
- thread_id: self.thread_id.clone(),
- run_context: run_context.clone(),
- hosted_base: self.hosted_base.clone(),
- agent_id: self.agent_definition_id.clone(),
- })
- .await?;
- let subagent_usage_entries = run_context.subagent_usage_entries();
- // The run handed back its own transcript, folded into history below, so
- // an error after this point must not replay the snapshot's rounds again.
- transcript_snapshot
- .lock()
- .unwrap_or_else(std::sync::PoisonError::into_inner)
- .messages
- .clear();
-
- // Record whether this turn paused at the tool-call cap (vs. finishing
- // naturally) BEFORE anything below can early-return, so a caller
- // inspecting `last_turn_hit_cap()` after `run_single` always reflects
- // this turn, never a stale value from a prior one.
- self.last_turn_hit_cap = outcome.hit_cap;
-
- // The stamped user turn is already in `self.history` (pushed by `turn()`),
- // so append only the structured messages this turn produced — assistant
- // tool calls + tool results + (for a clean finish) the final assistant —
- // preserving tool-call history fidelity for the UI, persisted transcript,
- // and the next turn's KV-cache prefix.
- self.history.extend(outcome.conversation.iter().cloned());
-
- // Token accounting for the turn (the cap checkpoint call below folds in
- // its own usage).
- // Seed from the turn outcome (the harness observed real usage incl. cached
- // tokens and an estimated cost) rather than zero, so a normal non-cap turn
- // persists real cost instead of $0. The cap-checkpoint branch below folds
- // in its extra call's usage on top.
- let mut input_tokens = outcome.input_tokens;
- let mut output_tokens = outcome.output_tokens;
- let mut cached_input_tokens = outcome.cached_input_tokens;
- let mut charged_amount_usd = outcome.charged_amount_usd;
-
- let reply = if outcome.hit_cap
- && outcome.wrap_up_injected
- && !outcome.text.trim().is_empty()
- {
- // The conclusion was produced INSIDE the loop (issue #6014):
- // `FinalCallWrapUpMiddleware` withdrew the tools on the last
- // permitted model call and appended the wrap-up instruction, so this
- // turn's own final response already is the capped turn's answer.
- // There is nothing left to ask for, and asking anyway would spend a
- // second call to re-summarise text the model has just written.
- //
- // No `history.push` either: unlike the out-of-band path below, this
- // response came from the loop, so it was already folded into
- // `self.history` by the `extend(outcome.conversation)` above. Pushing
- // it again would duplicate the assistant turn in the transcript and
- // in the next request's prefix.
- log::info!(
- "[agent_loop] turn capped at {} model call(s); the loop's final call produced the \
- conclusion ({} chars) — no out-of-band wrap-up needed",
- outcome.model_calls,
- outcome.text.chars().count()
- );
- outcome.text.clone()
- } else if outcome.hit_cap {
- // The loop paused at the tool-call cap. Ask the model for a resumable
- // checkpoint (tools disabled), falling back to a deterministic
- // done/next summary so the thread never ends on a dangling tool
- // cycle. Fold the extra call's usage into the turn accounting.
- //
- // Reached when the in-loop conclusion above did not happen or came
- // back empty: a run with the middleware uninstalled, a budget of one
- // model call, or a concluding call that answered with nothing. Kept
- // intact so no path loses the behaviour it had before #6014.
- // The concluding call answered with nothing, and the `extend` above
- // folded that empty assistant message into `self.history`. Anthropic
- // rejects empty content, so sending it would turn "the model said
- // nothing" into a failed turn (CodeRabbit on #6068).
- if self.history.last().is_some_and(is_empty_assistant_chat) {
- self.history.pop();
- }
- let base = crate::agent::message_convert::provider_messages_from_conversation(
- self.tool_dispatcher.as_ref(),
- &self.history,
- );
- let (summary, summary_usage) = self
- .summarize_turn_wrapup(
- &base,
- effective_model,
- outcome.model_calls as u32 + 1,
- turn_checkpoint::MAX_ITER_CHECKPOINT_INSTRUCTION,
- true,
- )
- .await;
- if let Some(u) = summary_usage {
- input_tokens += u.input_tokens;
- output_tokens += u.output_tokens;
- cached_input_tokens += u.cached_input_tokens;
- charged_amount_usd += u.charged_amount_usd;
- }
- let checkpoint = if summary.trim().is_empty() {
- turn_checkpoint::build_deterministic_checkpoint(
- &checkpoint_results_from_conversation(
- &outcome.conversation,
- &outcome.tool_outcomes,
- ),
- max_iterations,
- )
- } else {
- summary
- };
- self.history
- .push(ConversationMessage::Chat(ChatMessage::assistant(
- checkpoint.clone(),
- )));
- checkpoint
- } else if outcome.text.trim().is_empty() && outcome.tool_calls == 0 {
- // A completion with no text and no tool calls is never a valid final
- // answer — surface it as an error instead of wedging the thread on a
- // blank reply (bug-report-2026-05-26 A1, defect B).
- //
- // #4457 (defect A): the empty terminal assistant response was already
- // folded into `self.history` via `outcome.conversation` at the
- // `history.extend` above (an empty `Chat(assistant(""))`). The #4093
- // branch below pops that dangling blank row before re-prompting, but
- // this `tool_calls == 0` path returned the error with the empty row
- // still in history — so the *next* request carried an empty-content
- // assistant message and strict providers (Anthropic: "text content
- // blocks must be non-empty") 400 the whole thread, not just this turn.
- // Pop the trailing empty assistant row before returning so a retry
- // sends a clean transcript.
- if matches!(
- self.history.last(),
- Some(ConversationMessage::Chat(msg))
- if msg.role == "assistant" && msg.content.trim().is_empty()
- ) {
- log::debug!(
- "[agent_loop] EmptyProviderResponse at iteration {}: popping dangling empty assistant row before returning — #4457 defect A",
- outcome.model_calls
- );
- self.history.pop();
- }
- return Err(anyhow::Error::new(
- crate::agent::error::AgentError::EmptyProviderResponse {
- iteration: outcome.model_calls,
- },
- ));
- } else if outcome.breaker_halt.is_some() || outcome.text.trim().is_empty() {
- // Two ways a turn reaches here without a reply it can ship:
- //
- // * #4093: the loop ran tool calls (tool_calls > 0, so the branch
- // above did not fire) and then ended with no final text — the
- // turn did work but would otherwise end silently.
- // * #6279: the no-progress breaker halted the run. `outcome.text`
- // then holds the breaker's stop note, which is worded for a model
- // ("Report this back instead of retrying") and must not be the
- // user's reply.
- //
- // Both close from the turn's tool records: a grounded wrap-up, a
- // check that rejects intent narration or claims the records
- // contradict (#6278), and a deterministic fallback that quotes the
- // failures. Fold the extra calls' usage into the turn accounting,
- // exactly like the cap path above.
- let (final_answer, close_usage) = self
- .close_turn_from_records(&outcome, user_message, effective_model)
- .await;
- for u in close_usage {
- input_tokens += u.input_tokens;
- output_tokens += u.output_tokens;
- cached_input_tokens += u.cached_input_tokens;
- charged_amount_usd += u.charged_amount_usd;
- }
- final_answer
- } else if outcome.early_exit_tool.is_some() {
- // Paused on `ask_user_clarification`. The run stopped right after the
- // tool round, so `outcome.conversation` ends on a tool result and
- // carries no final assistant turn — `outcome.text` (the question) is
- // standing in for one. Push it, or the reply the user is looking at
- // would be missing from the next request's prefix and the model would
- // have to infer that it asked anything from its own tool result.
- // The sub-agent path makes the same substitution when it persists a
- // paused child's transcript (`subagent_runner/ops/graph/dispatch.rs`).
- self.history
- .push(ConversationMessage::Chat(ChatMessage::assistant(
- outcome.text.clone(),
- )));
- outcome.text.clone()
- } else {
- outcome.text.clone()
- };
-
- // Enforce the required structured-output contract (issue #4117) on the
- // accepted reply — for the branches above that actually deliver one
- // (normal finish, cap checkpoint, #4093 synthesized close), since each
- // is a reply downstream parsing depends on. When this agent must emit a JSON block
- // every turn and the reply omitted it, validate-and-repair before the
- // turn is accepted, reconciling with streaming (append-only when a live
- // stream is attached, replace otherwise — see `enforce_required_output`).
- // The trailing assistant message is rewritten to match, and the repair
- // call's usage is folded into the turn accounting. `required_output`
- // defaults to `None`, so existing agents are entirely unaffected.
- // Converted to the crate contract at the read site: the enforcement
- // helpers below are part of the runtime slated to move into TinyAgents
- // and so speak the crate type, while the session still holds the host's
- // `AgentConfig`. See `tinyagents::config::required_output_from`.
- //
- // NOT for a turn paused on `ask_user_clarification`. The reply there is
- // the question itself, which will not carry the required block, so
- // enforcement would spend a repair model call rewriting the very text
- // the user is being asked to answer — and `replace_last_assistant_reply`
- // would persist the rewrite, so the question in the transcript would
- // stop matching the one on screen. A paused turn delivers no reply for
- // downstream parsing to depend on; the contract applies to the answer
- // this agent gives after the user replies, not to the asking (#6213
- // review).
- let required_output = if outcome.early_exit_tool.is_some() {
- None
- } else {
- self.config
- .required_output
- .as_ref()
- .map(crate::agent::tinyagents::config::required_output_from)
- };
- let reply = if let Some(contract) = required_output {
- match self
- .enforce_required_output(
- &reply,
- &contract,
- effective_model,
- outcome.model_calls as u32 + 1,
- )
- .await
- {
- Some((repaired, repair_usage)) => {
- if let Some(u) = repair_usage {
- input_tokens += u.input_tokens;
- output_tokens += u.output_tokens;
- cached_input_tokens += u.cached_input_tokens;
- charged_amount_usd += u.charged_amount_usd;
- }
- replace_last_assistant_reply(&mut self.history, &repaired);
- repaired
- }
- None => reply,
- }
- } else {
- reply
- };
- self.trim_history();
-
- // Fold this turn's sub-agent spend into the cumulative meters and capture
- // the holistic per-turn usage the web channel surfaces on `chat_done` (it
- // calls `take_last_turn_usage_totals()` right after the turn). Without this
- // the event reported `usage: None` despite the transcript being persisted
- // with real numbers.
- for entry in &subagent_usage_entries {
- input_tokens = input_tokens.saturating_add(entry.usage.input_tokens);
- output_tokens = output_tokens.saturating_add(entry.usage.output_tokens);
- cached_input_tokens =
- cached_input_tokens.saturating_add(entry.usage.cached_input_tokens);
- charged_amount_usd += entry.usage.charged_amount_usd;
- }
- self.last_turn_usage_totals = Some(crate::agent::tinyagents::host::LastTurnUsage {
- input_tokens,
- output_tokens,
- cached_input_tokens,
- cost_usd: charged_amount_usd,
- context_window: context_window.unwrap_or(0),
- subagents: subagent_usage_entries,
- });
-
- let mut persisted = crate::agent::message_convert::provider_messages_from_conversation(
- self.tool_dispatcher.as_ref(),
- &self.history,
- );
- // Re-attach per-call failure outcomes (dropped when the engine folded
- // each tool result into a `role:"tool"` message) so the derived
- // transcript view renders failed tools as errors, not successes.
- stamp_tool_failures(&mut persisted, &outcome.tool_outcomes);
- // Carry the turn's provider (event channel) + effective model and usage
- // into the persisted transcript meta. Passing `None` here dropped
- // `provider`/`model` from every transcript (they are `TranscriptMeta`
- // fields sourced from the turn usage) — parity with the legacy engine,
- // which handed `self.last_turn_usage.as_ref()` to this call.
- let turn_usage = tinyagents_session::transcript::TurnUsage {
- provider: self.event_channel().to_string(),
- // The model that actually ran this turn (a per-turn override can
- // diverge from `self.model_name`); attribute usage to it.
- model: effective_model.to_string(),
- usage: tinyagents_session::transcript::MessageUsage {
- input: input_tokens,
- output: output_tokens,
- cached_input: cached_input_tokens,
- context_window: context_window.unwrap_or(0),
- cost_usd: charged_amount_usd,
- },
- ts: chrono::Utc::now().to_rfc3339(),
- reasoning_content: None,
- tool_calls: Vec::new(),
- iteration: outcome.model_calls as u32,
- };
- self.persist_session_transcript(
- &persisted,
- input_tokens,
- output_tokens,
- cached_input_tokens,
- charged_amount_usd,
- Some(&turn_usage),
- );
-
- // Charge this turn's usage against the thread's active goal (parity with
- // the legacy engine) so budgeted goals progress to `budget_limited` and
- // continuation scheduling reads a live budget. Self-guarding + best-effort
- // — a no-op when this run has no active explicit thread goal.
- crate::agent::goals::runtime::account_turn_against_goal(
- &self.workspace_dir,
- self.thread_id(),
- input_tokens,
- output_tokens,
- turn_started.elapsed().as_secs(),
- )
- .await;
-
- // Content (prompt + reply) rides its own event so a tracing consumer can
- // attach it to the turn span. Gated on the opt-in
- // `observability.agent_tracing.capture_content` flag (#4454): with the
- // default off, we don't even emit the content event, so prompt/reply text
- // never reaches the span store or any exporter. The collector applies the
- // same storage-level gate as defense in depth.
- let capture_content = self
- .runtime_config
- .as_ref()
- .map(|c| c.observability.agent_tracing.capture_content)
- .unwrap_or(false);
- if capture_content {
- log::debug!(
- target: "agent-tracing",
- "[agent-tracing] emitting TurnContent (capture_content=true)"
- );
- self.emit_progress(AgentProgress::TurnContent {
- input: Some(user_message.to_string()),
- output: Some(reply.clone()),
- })
- .await;
- } else {
- log::debug!(
- target: "agent-tracing",
- "[agent-tracing] skipping TurnContent emit (capture_content=false)"
- );
- }
-
- self.emit_progress(AgentProgress::TurnCompleted {
- iterations: outcome.model_calls as u32,
- })
- .await;
-
- if self.auto_save {
- let summary = truncate_with_ellipsis(&reply, 100);
- let autosave_key = format!("assistant_resp:{}", uuid::Uuid::new_v4());
- let _ = self
- .memory
- .store(
- crate::agent::learning::transcript_ingest::CONVERSATION_RAW_NAMESPACE,
- &autosave_key,
- &summary,
- MemoryCategory::Daily,
- None,
- )
- .await;
- }
-
- // Fire post-turn hooks (non-blocking), matching the legacy engine.
- if !self.post_turn_hooks.is_empty() {
- let ctx = TurnContext {
- user_message: user_message.to_string(),
- assistant_response: reply.clone(),
- tool_calls: tool_records_from_conversation(
- &outcome.conversation,
- &outcome.tool_outcomes,
- ),
- turn_duration_ms: turn_started.elapsed().as_millis() as u64,
- session_id: Some(self.event_session_id.clone())
- .filter(|session_id| !session_id.trim().is_empty()),
- agent_id: Some(self.agent_definition_id.clone())
- .filter(|agent_id| !agent_id.trim().is_empty()),
- entrypoint: Some(self.event_channel.clone())
- .filter(|entrypoint| !entrypoint.trim().is_empty()),
- iteration_count: outcome.model_calls,
- };
- hooks::fire_hooks(&self.post_turn_hooks, ctx);
- }
-
- Ok(reply)
- }
-}
diff --git a/crates/openhuman-core/src/agent/harness/session/turn/core/resumed_prefix.rs b/crates/openhuman-core/src/agent/harness/session/turn/core/resumed_prefix.rs
deleted file mode 100644
index 581300ce4c..0000000000
--- a/crates/openhuman-core/src/agent/harness/session/turn/core/resumed_prefix.rs
+++ /dev/null
@@ -1,89 +0,0 @@
-//! Folding a resumed session's replayed transcript prefix into the live history.
-
-use crate::agent::harness::session::types::Agent;
-use crate::agent::messages::ConversationMessage;
-
-impl Agent {
- /// Fold a resumed session's replayed transcript prefix into [`Agent::history`].
- ///
- /// A no-op unless `cached_transcript_messages` is set, which happens only on
- /// the first turn after a resume.
- pub(in crate::agent::harness::session) fn absorb_resumed_transcript_prefix(&mut self) {
- let Some(cached) = self.cached_transcript_messages.take() else {
- return;
- };
- // A resumed session's replayed prefix is **absorbed into
- // `self.history`**, not merely prepended to this one request.
- //
- // It used to be prepended: the request was built from `history`,
- // the cached prefix was `take()`n and spliced in front, and
- // `history` was left holding only the new turn. That made the
- // replayed conversation visible to exactly one request, and it cost
- // the conversation twice over — both observed on the wire, not
- // reasoned about:
- //
- // 1. **The next turn lost it.** `take()` empties the field, and
- // nothing else ever re-read the transcript, so turn 2 after a
- // restart went out with only its own messages. A ten-message
- // thread answered its next question from four. That is
- // conversational amnesia first and a cache miss second.
- // 2. **The transcript written afterwards lost it.** Persistence
- // serializes `history` (see `run_turn_impl`'s
- // `persist_session_transcript` call), so the file produced after
- // a resume held only the new turn — and `latest_for_agent` hands
- // that file to the *next* resume. Each restart truncated the
- // thread a little further.
- //
- // Absorbing it makes `history` the single source of truth again, so
- // the request, the following turn and the durable record cannot
- // disagree. The bytes on the wire for *this* request are unchanged:
- // the prefix's entries are already provider-shaped `ChatMessage`s
- // and `Chat` is rendered verbatim, exactly as the splice did.
- //
- // The leading system message(s) built for this turn are dropped in
- // favour of the prefix's own, which is the whole point of resuming —
- // the stored prompt is the KV-cache prefix the backend has already
- // tokenised, and re-rendering it is what this path exists to avoid.
- //
- // `Chat` rather than the structured `AssistantToolCalls` /
- // `ToolResults` variants is deliberate: these entries have already
- // been through `bound_cached_transcript_messages`, which snaps the
- // window past an orphaned lead and strips a trailing unpaired
- // opener, so the cycle-pairing guard has nothing left to do. Lifting
- // them into the structured variants would mean re-deriving a pairing
- // that was already decided, with a second chance to get it wrong;
- // the native envelope they carry is parsed back into real tool calls
- // at the provider seam either way (see
- // `message_convert::parse_native_assistant_envelope`, which exists
- // for precisely this seeded-transcript case).
- // `bound_cached_transcript_messages` preserves a leading system
- // message only "when present" — a resumed transcript that was never
- // seeded with one (or was truncated ahead of it) hands back a
- // `cached` prefix with no system entry at all. Dropping this turn's
- // freshly-built system message(s) unconditionally would then leave
- // the absorbed history with none, not the cached one's — so only
- // drop them when the cached prefix actually supplies a replacement.
- let cached_has_system = matches!(cached.first(), Some(msg) if msg.role == "system");
- let tail: Vec<ConversationMessage> = self
- .history
- .drain(..)
- .skip_while(|entry| {
- cached_has_system
- && matches!(entry, ConversationMessage::Chat(chat) if chat.role == "system")
- })
- .collect();
- // Every absorbed row belongs to an earlier turn. Mark it as replayed so
- // persisting it with this turn keeps the request it was written under
- // (or none) instead of taking this turn's request id (#6282). This is
- // the one place every resume path (thread transcript, agent
- // transcript, conversation-log seed) enters `history`.
- self.history = cached
- .into_iter()
- .map(|mut message| {
- crate::agent::messages::mark_chat_replayed_if_unmarked(&mut message);
- ConversationMessage::Chat(message)
- })
- .chain(tail)
- .collect();
- }
-}
diff --git a/crates/openhuman-core/src/agent/harness/session/turn/core_tests.rs b/crates/openhuman-core/src/agent/harness/session/turn/core_tests.rs
deleted file mode 100644
index d63c2e7c54..0000000000
--- a/crates/openhuman-core/src/agent/harness/session/turn/core_tests.rs
+++ /dev/null
@@ -1,33 +0,0 @@
-//! What the cap path must not send to a provider (#6068).
-//!
-//! Sibling `*_tests.rs` file rather than an inline module, per the Rust layout
-//! gate. `is_empty_assistant_chat` is `pub(super)` inside a private `core`
-//! module, so this is the one place it is reachable from.
-
-use super::*;
-
-#[test]
-fn an_empty_assistant_reply_is_recognised_for_removal() {
- let empty = ConversationMessage::Chat(ChatMessage::assistant(String::new()));
- let blank = ConversationMessage::Chat(ChatMessage::assistant(" \n".to_string()));
- let real =
- ConversationMessage::Chat(ChatMessage::assistant("here is what I found".to_string()));
- let user = ConversationMessage::Chat(ChatMessage::user("do the thing".to_string()));
-
- assert!(
- is_empty_assistant_chat(&empty),
- "empty content must be dropped"
- );
- assert!(
- is_empty_assistant_chat(&blank),
- "whitespace-only content is empty to a provider too"
- );
- assert!(
- !is_empty_assistant_chat(&real),
- "a real conclusion must never be dropped"
- );
- assert!(
- !is_empty_assistant_chat(&user),
- "only the assistant's own empty turn is at issue"
- );
-}
diff --git a/crates/openhuman-core/src/agent/harness/session/turn/core_turn.rs b/crates/openhuman-core/src/agent/harness/session/turn/core_turn.rs
deleted file mode 100644
index ddd25d9089..0000000000
--- a/crates/openhuman-core/src/agent/harness/session/turn/core_turn.rs
+++ /dev/null
@@ -1,712 +0,0 @@
-impl Agent {
- /// Executes a single interaction "turn" with the agent.
- ///
- /// This function is the primary driver of the agent's behavior. It manages the
- /// end-to-end lifecycle of a user request:
- ///
- /// 1. **Initialization**: Resumes from a session transcript if this is a new turn
- /// to preserve KV-cache stability.
- /// 2. **Prompt Construction**: Builds the system prompt (only on the first turn)
- /// incorporating learned context and tool instructions.
- /// 3. **Context Injection**: Enriches the user message with per-turn context
- /// such as situational preferences, the thread goal, and active sub-agents.
- /// Broad memory recall is available to the model on demand instead.
- /// 4. **Execution Loop**: Enters a loop (up to `max_tool_iterations`) where it:
- /// - Manages the context window (reduction/summarization).
- /// - Calls the LLM provider.
- /// - Parses and executes tool calls.
- /// - Accumulates results into history.
- /// 5. **Synthesis**: Returns the final assistant response after all tools have
- /// finished or the iteration budget is exhausted.
- /// 6. **Background Tasks**: Triggers episodic memory indexing and facts
- /// extraction asynchronously.
- pub async fn turn(&mut self, user_message: &str) -> Result<String> {
- // Consume any per-turn overrides the caller set for THIS turn (#1725).
- // Taking them resets the field to the default, so they apply to exactly
- // one turn — a chat/small-talk turn runs tool-less, memory-less and
- // goal-less without permanently altering the agent, and the following
- // turn is back to full-agentic behaviour. Callers that never opt in get
- // `TurnOverrides::default()` (all-false) and the unchanged path.
- let turn_overrides = std::mem::take(&mut self.pending_turn_overrides);
- if turn_overrides != super::super::types::TurnOverrides::default() {
- log::info!(
- "[agent_loop] per-turn overrides active: suppress_active_goal={} suppress_tools={} suppress_memory_agent={}",
- turn_overrides.suppress_active_goal,
- turn_overrides.suppress_tools,
- turn_overrides.suppress_memory_agent
- );
- }
- self.emit_progress(AgentProgress::TurnStarted).await;
- log::info!("[agent] turn started — awaiting user message processing");
- log::info!(
- "[agent_loop] turn start message_chars={} history_len={} max_tool_iterations={}",
- user_message.chars().count(),
- self.history.len(),
- self.config.max_tool_iterations
- );
- self.ensure_composio_integrations_listener();
- // Arm the installed-skills listener at turn start (not lazily inside
- // `drain_skill_events`, which is only reached after the first turn) —
- // broadcast subscriptions are not retroactive, so a skill installed
- // during turn 1 would otherwise be missed until a later subscribe.
- self.ensure_skill_events_listener();
- // ── Session transcript resume ─────────────────────────────────
- // On a fresh session (empty history), look for a previous
- // transcript to pre-populate the exact provider messages for
- // KV cache prefix reuse.
- if self.history.is_empty()
- && self.cached_transcript_messages.is_none()
- && !turn_overrides.suppress_transcript_autoload
- {
- self.try_load_session_transcript();
- }
-
- if self.history.is_empty() {
- // Learned context is only baked into the system prompt on the
- // very first turn — once the history is non-empty we reuse the
- // stored prompt verbatim to preserve the KV-cache prefix the
- // inference backend has already tokenised. Fetching it later
- // would just burn memory-store reads on data we throw away.
- if !self.connected_integrations_initialized {
- self.fetch_connected_integrations().await;
- // Sessions born without a cached Composio view still need
- // a one-shot delegation-surface reconcile before the system
- // prompt is frozen. It runs before `build_system_prompt`
- // below so the rendered tool catalogue carries the delegates.
- self.refresh_delegation_tools();
- }
- let learned = self.fetch_learned_context().await;
- let rendered_prompt = self.build_system_prompt(learned)?;
- log::info!("[agent] system prompt built — initialising conversation history");
- log::info!(
- "[agent_loop] system prompt built chars={}",
- rendered_prompt.chars().count()
- );
- // User-file injection (PROFILE.md, MEMORY.md) puts
- // potentially-sensitive content (LinkedIn scrape output,
- // archivist-curated memories) into the system prompt. Avoid
- // leaking that to debug logs — log a length + content hash
- // instead. Narrow specialists (both flags off) keep the
- // full-body log so prompt-engineering iteration on
- // tools/safety sections stays easy.
- //
- // AGENTS.md instruction layers are also user/project-controlled and
- // can land in the prompt even when PROFILE/MEMORY are both omitted
- // (common for narrow specialists), so treat their presence as a
- // redaction trigger too — otherwise the full-body path would print
- // raw AGENTS.md contents verbatim.
- let contains_agents_md =
- rendered_prompt.contains("## Project instructions (AGENTS.md)");
- if self.omit_profile && self.omit_memory_md && !contains_agents_md {
- log::debug!("[agent_loop] system prompt body:\n{}", rendered_prompt);
- } else {
- let mut hasher = std::collections::hash_map::DefaultHasher::new();
- rendered_prompt.hash(&mut hasher);
- log::debug!(
- "[agent_loop] system prompt body redacted (contains PROFILE/MEMORY/AGENTS.md): chars={} hash={:016x}",
- rendered_prompt.chars().count(),
- hasher.finish()
- );
- }
- self.history
- .push(ConversationMessage::Chat(ChatMessage::system(
- rendered_prompt,
- )));
- // Seed the per-turn mid-session refresh baseline with the
- // hash of whatever Composio actually returned just now.
- // Subsequent turns short-circuit unless this hash changes.
- self.last_seen_integrations_hash =
- crate::integrations::composio::connected_set_hash(
- &self.connected_integrations,
- );
- // Seed the announced set with the startup connected toolkits so
- // only genuinely-new mid-session connects get announced later.
- self.announced_integrations = self
- .connected_integrations
- .iter()
- .map(|i| i.toolkit.clone())
- .collect();
- // MCP analogue: seed the announced MCP set with the servers already
- // connected at startup. Those are already in the (turn-1) system
- // prompt's `## Connected MCP Servers` block, so only servers that
- // connect *mid-session* should later be announced on the user turn.
- self.announced_mcp_servers =
- crate::mcp::registry::connections::connected_overview()
- .await
- .into_iter()
- .map(|s| s.qualified_name)
- .collect();
- } else {
- // Deliberately do NOT rebuild the system prompt on subsequent
- // turns. The rendered prompt is the KV-cache prefix the inference
- // backend has already tokenised; replacing its bytes (even
- // cosmetically) forces the backend to re-prefill from scratch.
- //
- // Dynamic turn-to-turn context rides on the user message assembled
- // below (`context`) — that is where anything varying between turns
- // belongs. Broad memory recall is not injected; the model calls the
- // memory tools when it needs stored context.
- //
- // *** Mid-session schema-only refresh ***
- //
- // The system prompt stays frozen, but the function-calling schema
- // (the `tools` field in the provider request) is sent fresh on
- // every API call. So we *can* react to Composio connect/disconnect
- // events mid-session by re-synthesising the `delegate_<toolkit>`
- // surface on `self.tools` / `self.tool_specs` and letting the next
- // provider call carry the new schema. The system prompt's
- // `## Connected Integrations` block goes mildly stale until the
- // next session, but the schema is the source of truth the model
- // actually routes against.
- //
- // **This is not free, and an earlier version of this comment said
- // it was** — it claimed the tools field "is not part of the
- // KV-cache prefix". It is. Every prefix cache in production renders
- // the tool catalogue *before* the conversation, because a chat
- // template has to put it somewhere the model reads it ahead of the
- // first user turn: OpenAI's automatic cache, Anthropic's
- // `cache_control` (tools → system → messages), DeepSeek's context
- // cache, any vLLM/SGLang radix cache. A changed tool block
- // therefore invalidates the *whole* prefix — including the system
- // prompt this branch goes to such lengths to freeze.
- //
- // The refresh is still right, because a tool surface that lies
- // about what the model can call is worse than a cold prefill. What
- // follows from the correction is narrower and load-bearing: the
- // rebuild must fire only on a *real* capability change, and must be
- // byte-stable when nothing changed. Both properties are already
- // paid for and must stay that way —
- // `connected_set_hash` is order-insensitive (sorted), so a backend
- // that returns the same toolkits in a different order does not
- // trigger a reconcile, and `refresh_delegation_tools` rebuilds
- // `tool_specs` in a deterministic order rather than from a set.
- // `an_unchanged_integration_set_leaves_the_tool_block_byte_stable`
- // pins it.
- //
- // The signal we react to is the process-wide
- // [`crate::integrations::composio::INTEGRATIONS_CACHE`], kept
- // current by (a) the desktop UI's 5 s
- // `composio_list_connections` poll, (b) the post-OAuth
- // `ComposioConnectionCreatedSubscriber` invalidation, and
- // (c) the 60 s TTL fallback. We read it via the read-only
- // [`crate::integrations::composio::cached_active_integrations`]
- // helper — never trigger a backend fetch ourselves, never
- // block on a writer.
- // Session agents built through `from_config_*` carry their
- // runtime `Config` snapshot directly, so this read avoids the
- // old `Config::load_or_init()` round-trip on every turn.
- //
- let _ = self.refresh_delegation_tools_from_cached_integrations("turn-boundary");
- // Same idea for installed skills. The system-prompt
- // `## Installed Skills` block is frozen at turn 1 for KV-cache
- // stability (history is non-empty here, so it is never rebuilt
- // mid-session), so — exactly like the MCP mechanism — the
- // user-turn announcement below is what surfaces a mid-session
- // install to the model. `refresh_workflows` updates the tracked
- // set (so the next refresh diffs correctly and a future fresh
- // session renders the new catalogue) and parks the announcement.
- // Event-driven (mirror of the composio path): only re-scan disk
- // when a `WorkflowsChanged` event was published since the last
- // turn — no per-turn filesystem walk on the steady-state hot path.
- if self.drain_skill_events() {
- let _ = self.refresh_workflows("event");
- }
- // Cache empty/expired or config unavailable => no signal.
- // We leave the current tool surface alone and pick up any
- // real change on the next turn after the UI's 5 s poll has
- // repopulated [`INTEGRATIONS_CACHE`].
-
- // MCP mid-session connect surfacing — the analogue of the Composio
- // path above. `use_mcp_server` is a single static delegate (no
- // per-server schema to refresh), so the whole mechanism is: diff
- // the live in-process connection map against what we've already
- // announced and queue a one-shot note for any newly-connected
- // server onto the next user message. The map is in-process (no
- // network, unlike Composio's cache), so reading it every turn is
- // cheap. Like the Composio block, the frozen `## Connected MCP
- // Servers` system-prompt section stays as the turn-1 snapshot.
- let connected_mcp: Vec<String> =
- crate::mcp::registry::connections::connected_overview()
- .await
- .into_iter()
- .map(|s| s.qualified_name)
- .collect();
- for qn in newly_connected_slugs(&connected_mcp, &mut self.announced_mcp_servers) {
- if !self.pending_mcp_announcement.contains(&qn) {
- self.pending_mcp_announcement.push(qn);
- }
- }
-
- log::trace!(
- "[agent_loop] system prompt reused (history_len={}) — KV cache prefix preserved",
- self.history.len()
- );
- }
-
- // `auto_save` says the workspace keeps its chat in memory; the origin says
- // whether this turn is chat at all. An internal agent is built from the
- // same config (`Agent::from_config_for_agent`), so it inherits the flag —
- // and its "user message" is the prompt the host wrote for it, not
- // anything the user said. Live, that stored `memory_goals::enrich`'s
- // prompt as a `Conversation` document keyed `user_msg:…`, where it then
- // competed for slots in every later recall (#5312). Gating here rather
- // than at each caller keeps a new internal agent from having to remember
- // to opt out, which is a thing nobody notices forgetting.
- //
- // Upstream of the same-session exclusion filter `main` added alongside
- // `CONVERSATION_RAW_NAMESPACE`: that filter stops this document echoing
- // back inside the turn that wrote it, but a host-written prompt stored
- // here still surfaces in a *later* session's recall. This gate is what
- // keeps it from being written at all.
- if self.auto_save && crate::agent::turn_origin::current_is_user_authored() {
- // Fire-and-forget: persisting the user message to the memory store
- // does an embedding round-trip (Voyage) + memory-tree write that the
- // in-flight turn never reads back. Awaiting it delayed the start of
- // *every* turn before recall/LLM began, so spawn it and let the chat
- // continue immediately.
- //
- // Use a UNIQUE per-message key: the old fixed `"user_msg"` key
- // upserts a single document (`upsert_document` keys by namespace+key),
- // so concurrent turns would race on — and overwrite — one shared slot.
- // A unique key makes each user message its own conversation document,
- // which both removes the race and stops the autosave from only ever
- // retaining the latest message.
- let memory = self.memory.clone();
- let user_msg = user_message.to_string();
- let autosave_key = format!("user_msg:{}", uuid::Uuid::new_v4());
- let chars = user_msg.chars().count();
- // Captured before `tokio::spawn` from this owned session carrier.
- // Tagging
- // this document with the live chat thread id is what lets the
- // same-session exclusion filter (`UnifiedMemory::recall` /
- // `memory_hybrid_search`) recognize and drop it later this same
- // turn, so the agent's own on-demand memory search doesn't echo
- // its own triggering request back as a "relevant" result.
- let session_id_for_autosave = self.thread_id.clone();
- log::debug!(
- "[agent_autosave] enqueue user-message store key={autosave_key} chars={chars} \
- session_id={}",
- session_id_for_autosave.as_deref().unwrap_or("<none>")
- );
- tokio::spawn(async move {
- match memory
- .store(
- crate::agent::learning::transcript_ingest::CONVERSATION_RAW_NAMESPACE,
- &autosave_key,
- &user_msg,
- MemoryCategory::Conversation,
- session_id_for_autosave.as_deref(),
- )
- .await
- {
- Ok(()) => log::debug!(
- "[agent_autosave] stored user-message key={autosave_key} chars={chars}"
- ),
- Err(err) => log::warn!(
- "[agent_autosave] user-message memory autosave failed key={autosave_key} err={err}"
- ),
- }
- });
- }
-
- log::info!("[agent] spawning UI-only citation collection for user message");
- const MEMORY_CITATION_LIMIT: usize = 5;
- const MEMORY_CITATION_MIN_RELEVANCE: f64 = 0.4;
- // Spawned, not awaited: see `Agent::pending_citations`. The result is
- // UI-only, so the turn must not wait for it before calling the model.
- self.last_turn_citations.clear();
- if let Some(previous) = self.pending_citations.take() {
- // A turn that never had its citations collected leaves a task
- // behind; abort it rather than letting a stale recall outlive the
- // turn it belonged to.
- previous.abort();
- }
- let citation_memory = self.memory.clone();
- let citation_query = user_message.to_string();
- self.pending_citations = Some(tokio::spawn(async move {
- match collect_recall_citations(
- citation_memory.as_ref(),
- &citation_query,
- MEMORY_CITATION_LIMIT,
- MEMORY_CITATION_MIN_RELEVANCE,
- )
- .await
- {
- Ok(citations) => {
- log::debug!(
- "[agent_loop] memory citations collected count={}",
- citations.len()
- );
- citations
- }
- Err(_err) => {
- // Recall errors may include the user-authored query. Keep
- // warning logs free of raw external content.
- log::warn!("[agent_loop] memory citation collection failed");
- Vec::new()
- }
- }
- }));
- // No per-turn memory-context block is assembled here any more.
- //
- // `memory_loader.load_context()` used to prepend `[User working
- // memory]`, `[Prior conversations]` and `[Cross-chat context]` to every
- // user message. It cost two full scans of the `global` namespace per
- // turn — every document and every vector chunk, decoded and scored — to
- // contribute at most nine lines, and the cost grew with everything the
- // user had ever said. Benchmarked at ~10k memories it was the dominant
- // per-turn cost by a wide margin, and the `[User working memory]` arm
- // in particular scanned the whole namespace only to filter the results
- // down to a `working.user.` key prefix, so it returned nothing at all
- // once ordinary chat crowded the ranking.
- //
- // Memory is still available to the agent — `memory_recall` and the rest
- // of the memory tools are unchanged, so the model fetches what it needs
- // when it needs it, rather than every turn paying for a broad guess.
- let mut context = String::new();
-
- // ── Lanes B and C: per-message memory (every turn) ───────────────────
- // Situational preferences, and the gated auto-recall of facts about the
- // user (#6040). Both are bounded — the only memory awaits left on the
- // turn's critical path; citations and autosave above are spawned off
- // it — and both ride this per-turn context rather than the cached
- // system-prompt prefix. See `turn/recall_lanes.rs`.
- super::recall_lanes::append_recall_lanes(self, user_message, &mut context).await;
-
- // ── Thread goal (Codex-style per-thread completion contract) ─────────
- // Load this thread's durable goal once per turn and prepend a compact
- // [active_goal] block so the objective + live status/budget steer the
- // turn. Rides the per-turn context (NOT the cached system-prompt prefix)
- // so edits take effect immediately. `active_goal` is reused below to arm
- // the budget stop hook around the engine call.
- // Capture the workspace path for the budget stop hook built after the
- // `turn_body` coroutine (which borrows `&mut self`) is constructed.
- let goal_workspace_dir = self.workspace_dir.clone();
- let active_goal = if turn_overrides.suppress_active_goal {
- // Chat / small-talk turn: do NOT load, auto-resume, inject, or
- // budget-arm this thread's goal. A goal an earlier task left
- // uncompleted must not steer an unrelated greeting (#1725, the
- // "stale goal replays every turn" half of the context leak).
- log::debug!(
- "[thread_goals] active_goal suppressed for this turn (chat/small-talk override)"
- );
- None
- } else {
- let loaded = crate::agent::goals::runtime::load_for_thread(
- &self.workspace_dir, self.thread_id(),
- )
- .await;
- // Thread-resume semantics: the user re-engaging a thread reactivates a
- // paused goal (Codex's ThreadResumed). Best-effort; on failure keep
- // the loaded (paused) goal so we still surface it.
- match loaded {
- Some(goal)
- if matches!(
- goal.status,
- crate::agent::goals::ThreadGoalStatus::Paused
- ) =>
- {
- crate::agent::goals::runtime::resume_for_thread(
- &self.workspace_dir, self.thread_id(),
- )
- .await
- .unwrap_or(Some(goal))
- }
- other => other,
- }
- };
- if let Some(ref goal) = active_goal {
- if let Some(block) = tinyagents_graph::goals::active_goal_context_block(goal) {
- log::info!(
- "[thread_goals] injecting active_goal block status={} budget={:?} ({} chars)",
- goal.status.as_str(),
- goal.token_budget,
- block.chars().count()
- );
- context.push_str(&block);
- }
- }
-
- // ── Active sub-agents (ambient fleet awareness) ──────────────────────
- // When this agent has async/parallel workers registered under its own
- // session, prepend a compact `[active_subagents]` roster (agent type,
- // subagent_session_id, live status) so it tracks the fleet from the turn
- // context instead of relying on remembered `[async_subagent_ref]` blocks
- // that may have scrolled away. Children register under the parent's
- // `session_id`, which is this agent's `event_session_id` (see
- // `build_parent_execution_context`). Gated on presence: agents that never
- // spawn get an empty block and no injection. Rides per-turn context (like
- // the goal block) so status is always live.
- if let Some(block) =
- crate::agent::orchestration::running_subagents::active_subagents_context_block(
- &self.event_session_id,
- &self.workspace_dir,
- )
- {
- log::info!(
- "[running_subagents] injecting active_subagents block session={} ({} chars)",
- self.event_session_id,
- block.chars().count()
- );
- context.push_str(&block);
- }
-
- let enriched = if context.is_empty() {
- log::info!("[agent] no memory context found — using raw user message");
- self.last_memory_context = None;
- user_message.to_string()
- } else {
- log::info!(
- "[agent] memory context loaded — enriching user message context_chars={}",
- context.chars().count()
- );
- self.last_memory_context = Some(context.clone());
- format!("{context}{user_message}")
- };
-
- let enriched = self
- .inject_agent_experience_context(user_message, enriched)
- .await;
-
- // ── SKILL.md body injection: REMOVED (was #781) ──────────────
- // We used to keyword-match installed skills against the user message
- // and prepend their full SKILL.md bodies onto the user turn. That
- // brittle name/description/tag match fired unintentionally and — by
- // baking the body into the stored user message — left full skill text
- // permanently in chat history (microcompact only clears tool results,
- // not user messages).
- //
- // Skills are now surfaced via the compact `## Installed Skills`
- // catalog in the orchestrator prompt and executed via `run_skill`,
- // which loads and follows the SKILL.md inside an isolated worker, so
- // the full body never enters this conversation. `self.workflows` still
- // feeds the catalog through `PromptContext`.
-
- // Consume any one-shot mid-session connect announcement parked by
- // `refresh_delegation_tools_from_cached_integrations`. It rides on the
- // user turn (NOT a system message — `trim_history` hoists system
- // messages to the front and would bust the KV-cache prefix) and
- // `.take()` clears it so it fires exactly once.
- let pending_slugs = std::mem::take(&mut self.pending_integration_announcement);
- let enriched = match integration_announcement_note(&pending_slugs) {
- Some(note) => format!("{note}\n\n{enriched}"),
- None => enriched,
- };
-
- // Same one-shot treatment for MCP servers connected mid-session
- // (queued above). `.take()` clears it so it fires exactly once.
- let pending_mcp = std::mem::take(&mut self.pending_mcp_announcement);
- let enriched = match mcp_announcement_note(&pending_mcp) {
- Some(note) => format!("{note}\n\n{enriched}"),
- None => enriched,
- };
-
- // Same one-shot pattern for skills installed mid-session (parked by
- // `refresh_workflows` above). Rides the user turn so the KV-cache
- // prefix stays stable; `.take()` fires it exactly once.
- let pending_skills = std::mem::take(&mut self.pending_skill_announcement);
- let enriched = match skill_announcement_note(&pending_skills) {
- Some(note) => format!("{note}\n\n{enriched}"),
- None => enriched,
- };
-
- // Same one-shot treatment for skills uninstalled mid-session (parked by
- // `refresh_workflows`). The model must know the skill is gone so it does
- // not attempt `run_skill` on a removed entry. Rides the user turn for
- // the same KV-cache reason as the install note above.
- let pending_retracted = std::mem::take(&mut self.pending_skill_retraction);
- let enriched = match skill_retraction_note(&pending_retracted) {
- Some(note) => format!("{note}\n\n{enriched}"),
- None => enriched,
- };
-
- // Pin the main agent to its configured model for the lifetime of
- // the session. Per-turn classification used to run here, but it
- // would flip `effective_model` mid-conversation (e.g. reasoning →
- // coding based on a single keyword). Every flip invalidates the
- // backend's KV cache namespace for this session, costing full
- // re-prefill on the very next turn. The main agent's job is to
- // decide *which sub-agent* to spawn — that routing lives in the
- // model prompt, not in the Rust-side classifier. Sub-agents pick
- // their own tier via `ModelSpec::Hint(...)` in their definition.
- let effective_model = self.model_name.clone();
- log::info!(
- "[agent_loop] model pinned model={} (per-turn classification disabled for KV cache stability)",
- effective_model
- );
-
- // Snapshot the parent's runtime once per turn so any
- // `spawn_subagent` invocation that fires inside this turn can
- // read it via the PARENT_CONTEXT task-local. We override the
- // model field with the post-classification effective model.
- let mut parent_context = self.build_parent_execution_context();
- parent_context.model_name = effective_model.clone();
- let session_memory_parent_context = parent_context.clone();
-
- let mut agent_context_prepared_sources: Vec<harness::AgentContextPreparedSource> =
- Vec::new();
- // Triggered memory-agent recall runs on EVERY channel, voice included:
- // dropping it on voice would strip the user's remembered context
- // (preferences, people, prior facts) from spoken answers — a real quality
- // loss the transcript alone can't replace. Recall adds a few seconds of
- // embedding + retrieval before the first model token, but on realtime
- // voice that latency is already covered end-to-end: the backend relay
- // streams an audible keepalive filler from t=0 so the cloud session never
- // sees a silent stall, and the desktop's ~8s ack-defer closes the spoken
- // turn and finishes in the background if the work runs long. So the recall
- // path is byte-for-byte identical across voice and chat.
- let (enriched, memory_agent_context_injected) = self
- .inject_triggered_memory_agent_context(
- user_message,
- enriched,
- &parent_context,
- turn_overrides.suppress_memory_agent,
- )
- .await;
- if memory_agent_context_injected {
- agent_context_prepared_sources.push(harness::AgentContextPreparedSource {
- source: "memory agent context retrieval".to_string(),
- has_enough_context: None,
- });
- }
-
- let enriched = if agent_context_prepared_sources.is_empty() {
- enriched
- } else {
- log::debug!(
- "[agent_loop] agent context already prepared sources={:?}",
- agent_context_prepared_sources
- );
- format!(
- "{}\n\n{enriched}",
- render_agent_context_status_note(&agent_context_prepared_sources)
- )
- };
-
- // #3602: stamp every turn's user message with the live local time
- // so time-relative phrasing (greetings, "today"/"tonight") is
- // grounded on the real clock. Rides the user message — not the
- // frozen system-prompt prefix (see core.rs KV-cache note above) — so
- // it stays fresh across a long-lived session without busting the
- // cached prefix. This path runs for every `turn()` caller, including
- // one-shot `run_single` flows (cron/morning-briefing/meet), so those
- // get a fresh stamp too. The grounding *rule* lives in the system
- // prompt's `## Current Date & Time` section.
- let enriched = format!(
- "{}\n\n{enriched}",
- crate::agent::prompts::current_datetime_line()
- );
-
- self.history
- .push(ConversationMessage::Chat(ChatMessage::user(enriched)));
-
- // Bump the session-memory turn counter. Used later by
- // `should_extract_session_memory` to decide whether to spawn a
- // background archivist fork at end-of-turn.
- self.context.tick_turn();
-
- // The root host carrier is constructed before the turn starts and is
- // passed through TinyAgents' `RunContext` to every synchronous child.
- // These values used to be recovered through nested Tokio scopes.
- let mut turn_run_context = crate::agent::tinyagents::host::OpenHumanRunContext::new();
- turn_run_context.parent = Some(parent_context.clone());
- turn_run_context.prepared_context_sources = std::sync::Arc::new(agent_context_prepared_sources.clone());
- turn_run_context.attachment_placeholders = std::sync::Arc::new(
- crate::agent::multimodal::extract_image_placeholders_in_text(user_message),
- );
- turn_run_context.dispatch = Some(std::sync::Arc::new(
- crate::agent::tinyagents::host::TurnDispatchState::new(
- crate::agent::tinyagents::agent_turn_wall_clock_ms()
- .map(std::time::Duration::from_millis),
- ),
- ));
- let mut turn_stop_hooks = crate::agent::stop_hooks::current_stop_hooks();
- if let Some(ref goal) = active_goal {
- if let Some(hook) =
- crate::agent::goals::runtime::GoalBudgetStopHook::for_goal(&goal_workspace_dir, goal)
- {
- turn_stop_hooks.push(std::sync::Arc::new(hook));
- }
- }
- turn_run_context.stop_hooks = turn_stop_hooks;
-
- let turn_body = async {
- // Keep the scalar turn settings outside the pinned future arguments;
- // the TinyAgents session path reads provider/tool/multimodal state
- // directly from `self` when preparing the request.
- let temperature = self.temperature;
- let max_iterations = self.config.max_tool_iterations;
- let artifact_store = Some(
- crate::agent::harness::tool_result_artifacts::ToolResultArtifactStore::new(
- self.action_dir.clone(),
- self.session_key.clone(),
- ),
- );
- // The whole turn runs through the tinyagents harness (issue #4249);
- // the legacy `run_turn_engine` has been removed. Heap-allocate the
- // (large) session-turn future so it isn't held inline on `turn()`'s
- // already-large frame — `run_single` and the cron wrappers nest more
- // layers on top, which would otherwise overflow the stack.
- Box::pin(self.run_turn_via_tinyagents_session(
- user_message,
- &effective_model,
- temperature,
- max_iterations,
- artifact_store,
- turn_overrides.suppress_tools,
- turn_run_context.clone(),
- ))
- .await
- }; // end of `turn_body` async block
-
- let result = turn_body.await;
-
- // Session transcript persistence lives INSIDE the turn body —
- // one write per provider response, fired right after the
- // response lands (see the tool-call and terminal branches in
- // `turn_body`). A crash during tool execution no longer drops
- // the assistant's reply because it was already flushed to
- // disk before tool dispatch started. No outer-loop save is
- // needed here.
-
- // ── Session-memory extraction (stage 5) ───────────────────────
- //
- // If the pipeline's deltas have crossed all three thresholds
- // (token growth, tool calls, turn count), spawn a *background*
- // archivist sub-agent that will distil durable facts into the
- // workspace MEMORY.md file via the `update_memory_md` tool.
- //
- // The archivist sub-agent itself is spawned and runs asynchronously
- // on the `agentic` tier. We optimistically mark the extraction
- // complete right away — if it actually fails, we'll just retry on the
- // next threshold window (a few turns later), which is the right amount
- // of retry behaviour for a librarian task that's idempotent across
- // reruns.
- //
- // This call is NOT fire-and-forget, despite spawning one (#6200). It
- // is awaited, and before it spawns anything it awaits
- // `flush_open_segment`, so the trailing segment's recap runs on this
- // path — `result` below is returned only afterwards. The comment here
- // used to claim the turn returned immediately; it did not, and with
- // `tinyinference`'s 600 s request default underneath that was up to ten
- // minutes of a held-open turn. `RECAP_DEADLINE` in `archivist::recap`
- // is what bounds it now.
- //
- // Detaching the flush instead would match the old comment, but it would
- // drop the `GUARANTEE:` documented at the flush site — that the
- // trailing segment always receives its recap before wind-down. Bounding
- // the wait keeps that promise and removes the hazard.
- if result.is_ok() && self.context.should_extract_session_memory() {
- self.spawn_session_memory_extraction(session_memory_parent_context)
- .await;
- // Sibling pipeline (#1399): heuristic transcript ingestion
- // turns the just-written transcript into durable
- // conversational memory + reflections so a brand-new chat
- // can recover continuity. Background-only, never blocks the
- // user-facing turn return.
- self.spawn_transcript_ingestion();
- }
-
- result
- }
-}
diff --git a/crates/openhuman-core/src/agent/harness/session/turn/mod.rs b/crates/openhuman-core/src/agent/harness/session/turn/mod.rs
deleted file mode 100644
index 8d108d9967..0000000000
--- a/crates/openhuman-core/src/agent/harness/session/turn/mod.rs
+++ /dev/null
@@ -1,260 +0,0 @@
-//! Turn lifecycle: running a single interaction, executing tools, and
-//! wiring context stats + the sub-agent harness around them.
-
-mod context;
-mod core;
-mod graph;
-mod recall_lanes;
-mod session_io;
-mod tools;
-
-use tinytools_agent::ParsedToolCall;
-
-use std::borrow::Cow;
-
-/// Built-in direct tools that the orchestrator should call by name, not
-/// wrapped in `run_workflow`.
-const DIRECT_TOOL_NAMES: &[&str] = &[
- "cron_add",
- "cron_list",
- "cron_remove",
- "cron_update",
- "cron_run",
- "cron_runs",
- "current_time",
-];
-
-/// Recovery shim for legacy/wrong-model calls of the form:
-/// `run_workflow({workflow_id: "<built-in tool>", inputs: {...}})` (or the
-/// pre-rename `run_skill({skill_id: ...})`).
-///
-/// When this pattern appears, rewrite it into a direct tool call so the turn
-/// can proceed without a manual retry.
-pub(super) fn normalize_tool_call<'a>(call: &'a ParsedToolCall) -> Cow<'a, ParsedToolCall> {
- if call.name != "run_workflow" && call.name != "run_skill" {
- return Cow::Borrowed(call);
- }
- // Accept either the current `workflow_id` arg or the legacy `skill_id`.
- let Some(target) = call
- .arguments
- .get("workflow_id")
- .or_else(|| call.arguments.get("skill_id"))
- .and_then(|v| v.as_str())
- else {
- return Cow::Borrowed(call);
- };
- if !DIRECT_TOOL_NAMES.contains(&target) {
- return Cow::Borrowed(call);
- }
- let Some(inputs) = call.arguments.get("inputs").and_then(|v| v.as_object()) else {
- return Cow::Borrowed(call);
- };
-
- log::warn!(
- "[agent_loop] rewrote legacy {}->{} call into direct tool invocation",
- call.name,
- target
- );
- let skill_id = target;
- Cow::Owned(ParsedToolCall {
- name: skill_id.to_string(),
- arguments: serde_json::Value::Object(inputs.clone()),
- id: call.id.clone(),
- })
-}
-
-/// Compute the one-shot mid-session connect announcement.
-///
-/// Given the toolkit slugs currently connected and the set of slugs already
-/// announced to the model this session, returns a natural-language note for
-/// any genuinely-new slugs (and records them in `announced` so they are never
-/// re-announced). Returns `None` when nothing new connected.
-///
-/// Kept as a free function (no `&self`) so the delta logic is unit-testable
-/// without standing up a full `Agent` — see `turn_tests.rs`.
-/// Returns the toolkit slugs in `connected` that have not yet been announced
-/// this session, marking them announced. Empty when nothing is new.
-pub(super) fn newly_connected_slugs(
- connected: &[String],
- announced: &mut std::collections::HashSet<String>,
-) -> Vec<String> {
- let newly: Vec<String> = connected
- .iter()
- .filter(|slug| !announced.contains(*slug))
- .cloned()
- .collect();
- for slug in &newly {
- announced.insert(slug.clone());
- }
- newly
-}
-
-/// Render the one-shot user-turn note for a set of freshly-connected slugs.
-/// Empty input yields `None`.
-pub(super) fn integration_announcement_note(slugs: &[String]) -> Option<String> {
- if slugs.is_empty() {
- return None;
- }
- Some(format!(
- "[integration update] These integration(s) connected during this conversation and are available right now: {}. \
-Use delegate_to_integrations_agent with the matching toolkit slug to act on them immediately — do not tell the user to reconnect or restart.",
- slugs.join(", ")
- ))
-}
-
-/// Render the one-shot user-turn note for MCP server(s) that connected
-/// mid-session. The MCP analogue of [`integration_announcement_note`]: the
-/// system-prompt `## Connected MCP Servers` block is frozen at turn 1 (KV-cache
-/// prefix), so a server connected mid-conversation is surfaced here instead, on
-/// the user turn. Empty input yields `None`.
-pub(super) fn mcp_announcement_note(servers: &[String]) -> Option<String> {
- if servers.is_empty() {
- return None;
- }
- Some(format!(
- "[MCP update] These MCP server(s) connected during this conversation and are available right now: {}. \
-Use the use_mcp_server delegate to act on them immediately — do not tell the user to reconnect or restart.",
- servers.join(", ")
- ))
-}
-
-/// One-shot note prepended to the next user turn when skills are installed
-/// mid-session. Mirrors [`integration_announcement_note`] for the
-/// `## Installed Skills` catalogue: tells the model the freshly-installed
-/// skills are usable now (via `run_skill`) so it acts instead of claiming
-/// they aren't installed from stale context. Returns `None` when nothing is
-/// pending. Rides the user turn (not the system prompt) to keep the KV-cache
-/// prefix stable.
-pub(super) fn skill_announcement_note(skill_ids: &[String]) -> Option<String> {
- if skill_ids.is_empty() {
- return None;
- }
- Some(format!(
- "[skills update] These skill(s) were installed during this conversation and are available right now: {}. \
-They are in your `## Installed Skills` list — run one with `run_skill` immediately; do not tell the user to reinstall or restart.",
- skill_ids.join(", ")
- ))
-}
-
-/// One-shot note prepended to the next user turn when skills are uninstalled
-/// mid-session. Symmetric to [`skill_announcement_note`]: tells the model the
-/// listed skills are no longer present and `run_skill` will fail for them, so
-/// it does not attempt to invoke them. Rides the user turn (not the system
-/// prompt) to keep the KV-cache prefix stable.
-pub(super) fn skill_retraction_note(skill_ids: &[String]) -> Option<String> {
- if skill_ids.is_empty() {
- return None;
- }
- Some(format!(
- "[skills retracted] These skill(s) were uninstalled during this conversation and are no longer available: {}. \
-Do not attempt to run them with `run_skill` — they have been removed. Tell the user to reinstall if they want to use them again.",
- skill_ids.join(", ")
- ))
-}
-
-/// Every namespace's root summary, under user-resolved per-namespace and total
-/// caps. The limits are derived from the active
-/// [`crate::config::schema::agent::MemoryContextWindow`]
-/// preset by [`crate::config::schema::agent::AgentConfig::resolved_memory_limits`].
-///
-/// # Why `async` is the whole bridge
-///
-/// The only caller, `turn::context::fetch_learned_context`, is already an
-/// `async fn` and awaits four memory reads immediately above this one, so the
-/// driver call is awaited rather than bridged. `block_in_place` — the pattern
-/// `session::builder::helpers` uses for a genuinely synchronous caller —
-/// panics on a current-thread runtime and would buy nothing here.
-///
-/// An unresolvable binding, a driver with no tree family, or a failed read all
-/// yield no summaries. That is what this returned before as well: the engine's
-/// scan swallowed its own failures into an empty vector, and the prompt simply
-/// carries no memory block.
-pub(super) async fn collect_tree_root_summaries(
- per_namespace_cap: usize,
- total_cap: usize,
-) -> Vec<crate::agent::prompts::NamespaceSummary> {
- driver_tree_root_summaries(per_namespace_cap, total_cap)
- .await
- .into_iter()
- .map(
- |(namespace, body, updated_at)| crate::agent::prompts::NamespaceSummary {
- namespace,
- body,
- updated_at,
- },
- )
- .collect()
-}
-
-/// The shared subtree's root summaries, read from the guarded driver.
-///
-/// Returns the same positional `(namespace, body, updated_at)` triple the
-/// engine scan did.
-async fn driver_tree_root_summaries(
- per_namespace_cap: usize,
- total_cap: usize,
-) -> Vec<(String, String, chrono::DateTime<chrono::Utc>)> {
- use crate::memory::api::provider::MemoryProvider;
-
- let guard = match crate::memory::ops::guard::active_memory_guard().await {
- Ok(guard) => guard,
- Err(error) => {
- log::debug!("[session::turn] tree root summaries: no bound driver ({error})");
- return Vec::new();
- }
- };
- let Some(tree) = guard.as_tree() else {
- log::debug!(
- "[session::turn] tree root summaries: driver '{}' does not serve Tree",
- guard.driver_id()
- );
- return Vec::new();
- };
- match tree
- .root_summaries_with_caps(per_namespace_cap, total_cap)
- .await
- {
- Ok(rows) => rows
- .into_iter()
- .map(|row| (row.namespace, row.body, row.updated_at))
- .collect(),
- Err(error) => {
- log::warn!("[session::turn] tree root summaries: {error}");
- Vec::new()
- }
- }
-}
-
-/// Sanitize a learned memory entry before injecting into the system prompt.
-/// Strips raw data, limits length, and removes potential secrets.
-pub(super) fn sanitize_learned_entry(content: &str) -> String {
- let trimmed = content.trim();
- if trimmed.is_empty() {
- return String::new();
- }
- // Truncate to a safe length
- let max_len = 200;
- let sanitized: String = trimmed.chars().take(max_len).collect();
- // Strip anything that looks like a secret/token
- if sanitized.contains("Bearer ")
- || sanitized.contains("sk-")
- || sanitized.contains("ghp_")
- || sanitized.contains("-----BEGIN")
- {
- return "[redacted: potential secret]".to_string();
- }
- sanitized
-}
-
-#[cfg(test)]
-pub(crate) use super::turn_checkpoint::assistant_message_has_tool_calls;
-#[cfg(test)]
-pub(crate) use super::types::Agent;
-#[cfg(test)]
-pub(crate) use crate::agent::prompts::LearnedContextData;
-#[cfg(test)]
-pub(crate) use anyhow::Result;
-
-#[cfg(test)]
-#[path = "../turn_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/agent/harness/session/turn/session_io.rs b/crates/openhuman-core/src/agent/harness/session/turn/session_io.rs
deleted file mode 100644
index 291d69900f..0000000000
--- a/crates/openhuman-core/src/agent/harness/session/turn/session_io.rs
+++ /dev/null
@@ -1,13 +0,0 @@
-//! Session persistence: transcript loading, checkpointing, and background tasks.
-//!
-//! Each submodule contributes an `impl Agent` block:
-//!
-//! - [`transcript_load`] — resume-time transcript lookup and read.
-//! - [`transcript_persist`] — post-turn transcript write and store mirrors.
-//! - [`wrapup`] — out-of-band wrap-up summary and required-output repair.
-//! - [`background_tasks`] — fire-and-forget memory extraction and ingestion.
-
-mod background_tasks;
-mod transcript_load;
-mod transcript_persist;
-mod wrapup;
diff --git a/crates/openhuman-core/src/agent/harness/session/turn/session_io/background_tasks.rs b/crates/openhuman-core/src/agent/harness/session/turn/session_io/background_tasks.rs
deleted file mode 100644
index 7922cf2aa2..0000000000
--- a/crates/openhuman-core/src/agent/harness/session/turn/session_io/background_tasks.rs
+++ /dev/null
@@ -1,154 +0,0 @@
-//! Fire-and-forget background tasks kicked off after a turn settles:
-//! archivist session-memory extraction and transcript ingestion.
-
-use crate::agent::context::ARCHIVIST_EXTRACTION_PROMPT;
-use crate::agent::harness;
-use crate::agent::harness::session::types::Agent;
-
-impl Agent {
- // ─────────────────────────────────────────────────────────────────
- // Session-memory extraction.
- // ─────────────────────────────────────────────────────────────────
-
- /// Spawn a background archivist sub-agent to extract durable facts
- /// from the recent conversation into `MEMORY.md`. Fire-and-forget.
- ///
- /// Gated by [`context_pipeline::SessionMemoryState::should_extract`]
- /// — see its docs for the threshold invariants. Safe to call from
- /// inside `turn()` after the turn body has settled.
- pub(in super::super) async fn spawn_session_memory_extraction(
- &mut self,
- parent_ctx: harness::ParentExecutionContext,
- ) {
- // ── Flush the trailing open segment before the session winds down ──
- //
- // The ArchivistHook manages per-turn segment lifecycle but cannot
- // force-close the *last* open segment because there is no explicit
- // "session end" event in the turn loop. `spawn_session_memory_extraction`
- // is the closest available signal: it fires when the context manager
- // decides the session has accumulated enough material to archive.
- //
- // GUARANTEE: the flush is *awaited* here (not fire-and-forget) so
- // the trailing segment always receives its recap + embedding + tree
- // ingest before the function returns, even during runtime wind-down.
- // This honours the doc-comment guarantee on `flush_open_segment` in
- // `archivist.rs`. No deadlock risk: no mutex guard is held across
- // this await point.
- if let Some(ref archivist) = self.archivist_hook {
- let session_id = self.event_session_id.clone();
- log::debug!(
- "[archivist] awaiting flush_open_segment for session={session_id} at session wind-down"
- );
- archivist.flush_open_segment(&session_id).await;
- }
-
- let Some(registry) = harness::AgentDefinitionRegistry::global() else {
- log::debug!("[session_memory] registry not initialised — skipping extraction spawn");
- return;
- };
- let Some(definition) = registry.get("archivist").cloned() else {
- log::debug!(
- "[session_memory] archivist definition not found — skipping extraction spawn"
- );
- return;
- };
-
- let extraction_prompt = ARCHIVIST_EXTRACTION_PROMPT.to_string();
-
- // Flip the extraction state to "in-progress" so future
- // should_extract checks return false until the archivist
- // finishes. We then hand a shared handle to the spawned task
- // so it can mark the extraction complete (resets deltas) on
- // success, or failed (keeps deltas intact for retry) on error.
- // This replaces the old optimistic `mark_complete` that
- // silently dropped the retry window when extractions failed.
- let stats_snapshot = self.context.stats();
- self.context.mark_session_memory_started();
- let sm_handle = self.context.session_memory_handle();
-
- log::info!(
- "[session_memory] spawning background archivist extraction (turn={}, tokens={})",
- stats_snapshot.session_memory_current_turn,
- stats_snapshot.session_memory_total_tokens
- );
-
- tokio::spawn(async move {
- let options = harness::SubagentRunOptions {
- run_context: crate::agent::tinyagents::host::OpenHumanRunContext::new()
- .with_parent(parent_ctx),
- ..Default::default()
- };
- let result = harness::run_subagent(&definition, &extraction_prompt, options).await;
- match result {
- Ok(outcome) => {
- tracing::info!(
- agent_id = %outcome.agent_id,
- task_id = %outcome.task_id,
- iterations = outcome.iterations,
- output_chars = outcome.output.chars().count(),
- "[session_memory] archivist extraction completed"
- );
- if let Ok(mut sm) = sm_handle.lock() {
- sm.mark_extraction_complete();
- }
- }
- Err(err) => {
- tracing::warn!(
- error = %err,
- "[session_memory] archivist extraction failed — will retry after next threshold crossing"
- );
- // Leave the deltas intact so the next threshold
- // crossing schedules another attempt. Clearing
- // `extraction_in_progress` lets the retry
- // actually fire.
- if let Ok(mut sm) = sm_handle.lock() {
- sm.mark_extraction_failed();
- }
- }
- }
- });
- }
-
- /// Spawn a background task that ingests the current session
- /// transcript into the conversational-memory store.
- ///
- /// Issue #1399: complements `spawn_session_memory_extraction`. The
- /// archivist path writes dense bullets into `MEMORY.md`; this path
- /// extracts importance-tagged, provenance-bearing memories via the
- /// heuristic [`crate::agent::learning::transcript_ingest`]
- /// pipeline. The two are deliberately independent so the prompt
- /// retrieval layer can pull from `conversation_memory` without
- /// needing the archivist's extraction to have fired this session.
- ///
- /// Fire-and-forget: failures are logged, never propagated.
- pub(in super::super) fn spawn_transcript_ingestion(&self) {
- let Some(path) = self.session_transcript_path.clone() else {
- log::debug!("[transcript_ingest] no session transcript path yet — skipping spawn");
- return;
- };
- let memory = std::sync::Arc::clone(&self.memory);
-
- tokio::spawn(async move {
- match crate::agent::learning::transcript_ingest::ingest_transcript_path(
- memory.as_ref(),
- &path,
- )
- .await
- {
- Ok(report) => tracing::info!(
- transcript = %path.display(),
- extracted = report.extracted,
- stored = report.stored,
- deduped = report.deduped,
- reflections_stored = report.reflections_stored,
- "[transcript_ingest] background ingest complete"
- ),
- Err(err) => tracing::warn!(
- transcript = %path.display(),
- error = %err,
- "[transcript_ingest] background ingest failed — will retry next threshold window"
- ),
- }
- });
- }
-}
diff --git a/crates/openhuman-core/src/agent/harness/session/turn/session_io/transcript_load.rs b/crates/openhuman-core/src/agent/harness/session/turn/session_io/transcript_load.rs
deleted file mode 100644
index 8b2b70e76b..0000000000
--- a/crates/openhuman-core/src/agent/harness/session/turn/session_io/transcript_load.rs
+++ /dev/null
@@ -1,120 +0,0 @@
-//! Loading a prior session transcript for KV-cache resume, and the locator
-//! that finds it.
-
-use crate::agent::harness::session::types::Agent;
-use crate::agent::messages::chat_message_from_transcript;
-use tinyagents_session::transcript::{FileTranscriptLocator, TranscriptLocator};
-
-impl Agent {
- // ─────────────────────────────────────────────────────────────────
- // Session transcript helpers
- // ─────────────────────────────────────────────────────────────────
-
- /// Try to load a previous session transcript for KV cache resume.
- ///
- /// Best-effort: failures are logged and silently ignored.
- ///
- /// # How this reaches the transcript (S4)
- ///
- /// Both halves of the turn path now go through the seam: writes through
- /// [`TranscriptHistory::append_turn`][tinyagents_session::transcript::TranscriptHistory::append_turn],
- /// reads through
- /// [`TranscriptLocator`][tinyagents_session::transcript::TranscriptLocator]
- /// + [`TranscriptRead::read_session`][tinyagents_session::transcript::TranscriptRead::read_session].
- ///
- /// The read is **not** `ChatHistory::messages()`, and that is settled, not
- /// pending: `messages()` returns `Vec<Message>`, and converting back with
- /// `message_to_chat_message` flattens `Assistant.tool_calls` into plain
- /// text. That is precisely what
- /// [`bound_cached_transcript_messages`][Agent::bound_cached_transcript_messages]'
- /// TAURI-RUST-7 trailing strip inspects, and re-sending a flattened prefix
- /// to a native provider is the `400 assistant message with 'tool_calls'
- /// must be followed by tool messages` failure that strip exists to prevent.
- /// `read_session` returns the whole [`SessionTranscript`][tinyagents_session::transcript::SessionTranscript]
- /// instead — the same struct the free function returns, from the same
- /// `read_transcript` call — so compaction replay, `interrupted: true`
- /// partial skipping and the `_meta` header
- /// [`maybe_shadow_read_session_store`][Agent::maybe_shadow_read_session_store]
- /// needs all survive by construction.
- ///
- /// Discovery lives on the locator because it is a *lookup*, not a read:
- /// this function's key is `(workspace, agent name)`
- /// (newest match, with a legacy `session_raw/DDMMYYYY/` fallback) and the
- /// cold-boot sibling
- /// [`seed_resume_from_thread_transcript`][Agent::seed_resume_from_thread_transcript]
- /// keys off `_meta.thread_id`. Neither is a stem, and `ChatHistory` has no
- /// discovery concept at all.
- pub(crate) fn try_load_session_transcript(&mut self) {
- let Some(handle) = self
- .session_locator()
- .latest_for_agent(&self.agent_definition_name)
- else {
- log::debug!(
- "[transcript] no previous transcript found for agent={}",
- self.agent_definition_name
- );
- return;
- };
- let path = handle.path().to_path_buf();
- log::info!(
- "[transcript] found previous transcript path={}",
- path.display()
- );
- match handle.read_session() {
- // `Ok(None)` (file vanished between discovery and read) folds into
- // the same "nothing to resume from" branch as an empty transcript,
- // so the caller's behaviour is unchanged either way.
- Ok(None) => {
- log::debug!("[transcript] previous transcript is empty — skipping resume");
- }
- Ok(Some(session)) => {
- if session.messages.is_empty() {
- log::debug!("[transcript] previous transcript is empty — skipping resume");
- return;
- }
- let loaded_count = session.messages.len();
- log::info!("[transcript] loaded {} messages for resume", loaded_count);
- // Best-effort store-backed shadow read (issue #4249,
- // 04.2 phase 2). Observes + logs divergence only; the
- // legacy transcript just loaded stays authoritative and
- // is what feeds the resume below. Gated OFF by default.
- self.maybe_shadow_read_session_store(&path, &session);
- let replay = session
- .messages
- .into_iter()
- .map(chat_message_from_transcript)
- .collect();
- let bounded = self.bound_cached_transcript_messages(replay);
- if bounded.len() < loaded_count {
- log::warn!(
- "[transcript] resume prefix trimmed from {} to {} messages (max_history_messages={})",
- loaded_count,
- bounded.len(),
- self.config.max_history_messages
- );
- }
- self.cached_transcript_messages = Some(bounded);
- }
- Err(err) => {
- log::warn!(
- "[transcript] failed to parse previous transcript {}: {err}",
- path.display()
- );
- }
- }
- }
-
- /// The transcript locator for this session — the injected one, or a
- /// [`FileTranscriptLocator`] built from the agent's **current** workspace.
- ///
- /// Built per call rather than cached: `workspace_dir` is reassignable after
- /// `build()` (tests do exactly that), and a locator frozen at build time
- /// would silently keep resolving against the directory the agent no longer
- /// uses.
- pub(crate) fn session_locator(&self) -> std::sync::Arc<dyn TranscriptLocator> {
- match &self.session_history_locator {
- Some(locator) => locator.clone(),
- None => std::sync::Arc::new(FileTranscriptLocator::new(self.workspace_dir.clone())),
- }
- }
-}
diff --git a/crates/openhuman-core/src/agent/harness/session/turn/session_io/transcript_persist.rs b/crates/openhuman-core/src/agent/harness/session/turn/session_io/transcript_persist.rs
deleted file mode 100644
index 947d6069b5..0000000000
--- a/crates/openhuman-core/src/agent/harness/session/turn/session_io/transcript_persist.rs
+++ /dev/null
@@ -1,284 +0,0 @@
-//! Persisting the turn's provider messages as the session transcript, plus the
-//! session-store dual-write / shadow-read mirrors.
-
-use crate::agent::harness::session::types::Agent;
-use crate::agent::messages::{transcript_message_from_chat, ChatMessage};
-use tinyagents_session::transcript::{self, TranscriptTurn};
-
-impl Agent {
- /// Persist the exact provider messages as a session transcript.
- ///
- /// Writes JSONL as source of truth and re-renders the companion `.md`
- /// for human readability. Best-effort: failures are logged and silently
- /// ignored. The JSONL conversation store remains the authoritative
- /// persistence layer; session transcripts are an optimization for KV
- /// cache stability.
- ///
- /// `turn_usage` — when `Some`, attributes per-message token/cost figures
- /// to the last assistant message in the written transcript.
- pub(crate) fn persist_session_transcript(
- &mut self,
- messages: &[ChatMessage],
- input_tokens: u64,
- output_tokens: u64,
- cached_input_tokens: u64,
- charged_amount_usd: f64,
- turn_usage: Option<&transcript::TurnUsage>,
- ) {
- let now = chrono::Utc::now().to_rfc3339();
-
- // This turn's `_meta`. Built before the path/handle binding below so it
- // can double as the handle's `seed_meta`; it depends only on agent
- // state and this turn's figures, never on the resolved path.
- let meta = transcript::TranscriptMeta {
- agent_name: self.agent_definition_name.clone(),
- agent_id: Some(self.agent_definition_id.clone()),
- agent_type: Some(if self.session_parent_prefix.is_some() {
- "subagent".to_string()
- } else {
- "root".to_string()
- }),
- dispatcher: if self.tool_dispatcher.should_send_tool_specs() {
- "native".into()
- } else {
- "xml".into()
- },
- provider: turn_usage.map(|usage| usage.provider.clone()),
- model: turn_usage.map(|usage| usage.model.clone()),
- created: now.clone(),
- updated: now,
- turn_count: self.context.stats().session_memory_current_turn as usize,
- input_tokens,
- output_tokens,
- cached_input_tokens,
- charged_amount_usd,
- thread_id: self.thread_id.clone(),
- task_id: None,
- };
-
- // Bind the write seam on first write. The stem is
- // `{parent_prefix}__{session_key}` for sub-agents (producing a
- // flat hierarchical filename) or just `{session_key}` for a
- // root session. Prefix chaining is already done by the
- // sub-agent runner when it populates `session_parent_prefix`.
- //
- // Path resolution is the locator's job, not this function's: it used to
- // be duplicated here (a `resolve_keyed_transcript_path_in_dir` call
- // that had to stay in lockstep with the identical one inside the
- // handle's constructor). One call now yields both, and
- // `session_transcript_path` is simply the bound handle's own path — so
- // they cannot drift. The seed meta only matters when the file is absent
- // and the caller supplies none; the turn path always passes its own
- // freshly-computed meta below, so it never takes effect.
- if self.session_transcript_path.is_none() {
- let stem = match &self.session_parent_prefix {
- Some(prefix) => format!("{}__{}", prefix, self.session_key),
- None => self.session_key.clone(),
- };
- match self.session_locator().open_stem(&stem, meta.clone()) {
- Ok(history) => {
- log::info!(
- "[transcript] new session transcript path={}",
- history.path().display()
- );
- self.session_transcript_path = Some(history.path().to_path_buf());
- self.session_history = Some(history);
- }
- Err(err) => {
- log::warn!("[transcript] failed to bind session history: {err:#}");
- self.session_transcript_path = None;
- return;
- }
- }
- }
-
- let path = self.session_transcript_path.clone().unwrap();
- // Cloned out of `self` before the write so the later `&mut self`
- // dual-write does not conflict with a live borrow of the handle.
- let Some(history) = self.session_history.clone() else {
- log::warn!("[transcript] no session history bound; skipping append");
- return;
- };
-
- // Append-only write (Phase A, transcript-derived view): diff this turn's
- // logical messages against the previously-persisted set tracked in
- // memory. A pure extension appends only the new tail; a context
- // reduction appends a `compaction` record. The file is never rewritten,
- // so pre-compaction history survives on disk for the display projection.
- // `request_id` (web-chat only) stamps a turn boundary on each line.
- //
- // This goes through `TranscriptHistory::append_turn` rather than
- // `transcript::append_transcript_turn` directly (S4). The handle is a
- // pure forwarder of exactly these six values — it must be, because the
- // crate's `ChatHistory` methods carry no channel for `request_id`,
- // `turn_usage` or a caller-computed `TranscriptMeta`, and dropping any
- // of them silently guts the transcript-view projection. See the header
- // of `tinyagents_session::transcript::TranscriptHistory` for the full argument.
- let prev = std::mem::take(&mut self.persisted_transcript_messages);
- let next: Vec<_> = messages.iter().map(transcript_message_from_chat).collect();
- let request_id = crate::agent::turn_origin::current_request_id();
- match history.append_turn(TranscriptTurn {
- prev: &prev,
- next: &next,
- meta: &meta,
- turn_usage,
- request_id: request_id.as_deref(),
- }) {
- Ok(()) => {
- // Track the new persisted logical set for the next turn's diff.
- self.persisted_transcript_messages = next;
- // Best-effort, non-fatal dual-write into the TinyAgents store.
- // Gated by the default-ON session dual-write flag
- // (`OPENHUMAN_SESSION_DUAL_WRITE` is a kill switch). Only runs
- // after the legacy JSONL append above succeeds; the legacy path
- // is primary and untouched (issue #4249, 04.1).
- self.maybe_dual_write_session_store(&path);
- }
- Err(err) => {
- // Restore the tracked state so a transient failure doesn't make
- // the next turn mis-diff (and spuriously emit a compaction).
- self.persisted_transcript_messages = prev;
- log::warn!(
- "[transcript] failed to append transcript {}: {err}",
- path.display()
- );
- }
- }
- }
-
- /// Mirror the just-persisted turn into the TinyAgents session store.
- ///
- /// Additive and gated on the default-ON session dual-write flag
- /// (`OPENHUMAN_SESSION_DUAL_WRITE` is a kill switch): when killed this is a
- /// cheap early return — no store handle is constructed and behavior is
- /// byte-identical to the legacy-only path. When on (the default), the
- /// store write is fired best-effort on a background task and any error is
- /// logged (`[session-store]`) and swallowed, so it can never fail or alter a
- /// chat turn. Records reuse the importer's normalization
- /// ([`crate::agent::session_import`]) so live and imported records are
- /// shape-identical. Reads stay 100% legacy until 04.2.
- fn maybe_dual_write_session_store(&self, path: &std::path::Path) {
- use crate::agent::session_import::live;
-
- // Config flag (default ON) gates the mirror; the env kill switch can
- // still force it off. `self.config` is the effective per-agent config.
- if !live::dual_write_enabled(self.config.session_dual_write) {
- return;
- }
-
- // The session key is the transcript stem — the same value the importer
- // reads off the on-disk filename, so `stream_name`/descriptor keys match.
- let Some(stem) = path
- .file_stem()
- .and_then(|s| s.to_str())
- .map(str::to_string)
- else {
- log::warn!(
- "[session-store] dual-write skipped: no file stem for {}",
- path.display()
- );
- return;
- };
-
- let workspace = self.workspace_dir.clone();
- let path = path.to_path_buf();
-
- log::debug!(
- "[session-store] dual-write scheduled stem={stem} workspace={}",
- workspace.display()
- );
- tokio::spawn(async move {
- // Mirror the exact transcript the shadow reader compares against.
- // `shadow_read_compare` normalizes `read_transcript(path)` — the
- // legacy JSONL after its write→read round-trip — so build the store
- // record from that same read rather than from the in-memory turn.
- // Reconstructing it by hand let sidecar `extra_metadata` (turn-usage,
- // tool-failure marker, reasoning) diverge on resumed sessions even
- // though every message body, id and role matched, which is what the
- // parity soak flagged as `[session_shadow_read] DIVERGENCE` (#6149).
- // Read-and-mirror runs here on the same best-effort background task
- // that already fully rewrites the journal stream. The read itself is
- // synchronous — `fs::read_to_string` plus a JSON parse over the whole
- // append-only JSONL, which grows for the life of the session — so it
- // goes to the blocking pool instead of stalling a Tokio worker for
- // the length of the file. On a read error, skip the mirror for this
- // turn (legacy stays authoritative).
- let read_path = path.clone();
- let read_back =
- tokio::task::spawn_blocking(move || transcript::read_transcript(&read_path)).await;
- let session_transcript = match read_back {
- Ok(Ok(t)) => t,
- Ok(Err(err)) => {
- log::debug!(
- "[session-store] dual-write skipped: transcript read-back failed for {}: {err:#}",
- path.display()
- );
- return;
- }
- Err(err) => {
- log::debug!(
- "[session-store] dual-write skipped: transcript read-back task failed for {}: {err}",
- path.display()
- );
- return;
- }
- };
- if let Err(err) = live::write_live_turn(&workspace, &stem, &session_transcript).await {
- log::warn!("[session-store] dual-write failed stem={stem}: {err:#}");
- }
- });
- }
-
- /// Store-backed **shadow read** of a just-loaded session transcript.
- ///
- /// Beside the legacy authoritative reader (`try_load_session_transcript`),
- /// read the same session back from the TinyAgents journal store, normalize
- /// both sides through the importer's `session_import::convert` machinery,
- /// compare, and log any divergence (`[session_shadow_read]`, issue #4249,
- /// 04.2 phase 2). Additive and gated on the default-**OFF**
- /// `AgentConfig::session_shadow_reads` flag
- /// (`OPENHUMAN_SESSION_SHADOW_READS` is a kill switch): when disabled this
- /// is a cheap early return.
- ///
- /// The legacy transcript stays authoritative — this only observes. The
- /// comparison runs on a spawned background task so it never slows the
- /// authoritative read, and every store-read error is treated as "no shadow
- /// available" (logged at debug), never propagated.
- pub(super) fn maybe_shadow_read_session_store(
- &self,
- path: &std::path::Path,
- session: &transcript::SessionTranscript,
- ) {
- use crate::agent::session_import::live;
-
- // Config flag (default OFF) gates the shadow read; the env kill switch
- // can still force it off. `self.config` is the effective per-agent config.
- if !live::shadow_reads_enabled(self.config.session_shadow_reads) {
- return;
- }
-
- // Same session key the write side / importer use: the transcript stem.
- let Some(stem) = path
- .file_stem()
- .and_then(|s| s.to_str())
- .map(str::to_string)
- else {
- log::debug!(
- "[session_shadow_read] skipped: no file stem for {}",
- path.display()
- );
- return;
- };
-
- let workspace = self.workspace_dir.clone();
- let transcript = session.clone();
- log::debug!(
- "[session_shadow_read] scheduled stem={stem} workspace={} legacy_messages={}",
- workspace.display(),
- transcript.messages.len()
- );
- tokio::spawn(async move {
- let _ = live::shadow_read_compare(&workspace, &stem, &transcript).await;
- });
- }
-}
diff --git a/crates/openhuman-core/src/agent/harness/session/turn/session_io/wrapup.rs b/crates/openhuman-core/src/agent/harness/session/turn/session_io/wrapup.rs
deleted file mode 100644
index d7e2da871d..0000000000
--- a/crates/openhuman-core/src/agent/harness/session/turn/session_io/wrapup.rs
+++ /dev/null
@@ -1,438 +0,0 @@
-//! Out-of-band provider calls that finish a turn: the tools-disabled wrap-up
-//! summary and required-output enforcement / repair.
-
-use crate::agent::harness;
-use crate::agent::harness::session::types::Agent;
-use crate::agent::messages::ChatMessage;
-use crate::agent::progress::AgentProgress;
-use crate::inference::provider::{ChatResponse, UsageInfo, AGENT_TURN_MAX_OUTPUT_TOKENS};
-use futures::StreamExt;
-use tinyinference_llm::model::{ModelRequest, ModelStreamItem};
-
-impl Agent {
- /// **disabled** so the model returns prose rather than another tool call.
- /// Buffers text deltas and forwards them to the progress sink (when
- /// attached) only after the completed response is validated as prose, so
- /// prompt-formatted tool calls cannot flash in the UI before fallback.
- ///
- /// `instruction` is the synthetic user turn that steers the wrap-up — the
- /// tool-call-cap checkpoint (`MAX_ITER_CHECKPOINT_INSTRUCTION`) or the
- /// no-final-answer close (`FINAL_ANSWER_INSTRUCTION`, issue #4093).
- ///
- /// `stream_text` forwards the validated text to the progress sink. The
- /// no-final-answer close passes `false` and streams only after its own
- /// check accepts the text (issue #6278), so a rejected close never renders.
- ///
- /// Returns the summary text (empty when the provider call fails or
- /// yields nothing — the caller then falls back to a deterministic builder
- /// so the turn is never left without a well-formed assistant message,
- /// bug-report-2026-05-26 A1 / issue #4093) **paired with the provider
- /// usage** for this extra call, so the caller can fold it into the turn's
- /// cumulative token/cost accounting instead of silently dropping it.
- pub(in crate::agent::harness::session::turn) async fn summarize_turn_wrapup(
- &self,
- base_messages: &[ChatMessage],
- effective_model: &str,
- iteration_for_stream: u32,
- instruction: &str,
- stream_text: bool,
- ) -> (String, Option<UsageInfo>) {
- let mut messages = base_messages.to_vec();
- messages.push(ChatMessage::user(instruction));
-
- let chat_model = match self.turn_model_source.build_summarizer(
- effective_model,
- self.temperature,
- self.thread_id(),
- ) {
- Ok(model) => model,
- Err(error) => {
- tracing::error!(
- error = %error,
- model = effective_model,
- "[agent::session] failed to build wrap-up model"
- );
- return (String::new(), None);
- }
- };
- let request = ModelRequest::new(
- messages
- .iter()
- .map(crate::agent::tinyagents::chat_message_to_message)
- .collect(),
- )
- .with_model(effective_model)
- .with_temperature(self.temperature)
- .with_max_tokens(AGENT_TURN_MAX_OUTPUT_TOKENS);
- let mut stream = match chat_model.stream(&(), request).await {
- Ok(stream) => stream,
- Err(error) => {
- tracing::warn!(
- error = %error,
- model = effective_model,
- "[agent::session] wrap-up stream failed to start"
- );
- return (String::new(), None);
- }
- };
-
- let mut streamed_text = String::new();
- let mut completed = None;
- while let Some(item) = stream.next().await {
- match item {
- ModelStreamItem::MessageDelta(delta) if !delta.text.is_empty() => {
- streamed_text.push_str(&delta.text);
- }
- ModelStreamItem::Completed(response) => completed = Some(response),
- ModelStreamItem::Failed(error) => {
- tracing::warn!(%error, "[agent::session] wrap-up stream failed");
- return (String::new(), None);
- }
- ModelStreamItem::ProviderFailed(error) => {
- tracing::warn!(error = %error.message, "[agent::session] wrap-up provider failed");
- return (String::new(), None);
- }
- _ => {}
- }
- }
- let Some(response) = completed else {
- tracing::warn!("[agent::session] wrap-up stream ended without completion");
- return (String::new(), None);
- };
- let usage = crate::agent::tinyagents::model::usage_info_from_response(&response);
- let text = response.text();
- // Tools are disabled for wrap-up calls, but text-protocol models can
- // still ignore that instruction. Parse through the active dispatcher
- // so XML/JSON and registry-backed P-Format calls are all rejected. The
- // completed response and buffered deltas are checked independently:
- // some providers only preserve one of those representations.
- let parsed_call_count = |candidate: &str| {
- self.tool_dispatcher
- .parse_response(
- &crate::agent::message_convert::dialect_response_from_provider(&ChatResponse {
- text: Some(candidate.to_string()),
- ..ChatResponse::default()
- }),
- )
- .1
- .len()
- };
- let parsed_response_calls = parsed_call_count(&text);
- let parsed_stream_calls = if streamed_text == text {
- parsed_response_calls
- } else {
- parsed_call_count(&streamed_text)
- };
- let native_tool_calls = response.tool_calls().len();
- let attempted_tool_call =
- native_tool_calls > 0 || parsed_response_calls > 0 || parsed_stream_calls > 0;
- let checkpoint = if attempted_tool_call {
- tracing::warn!(
- model = effective_model,
- iteration = iteration_for_stream,
- native_tool_calls,
- parsed_response_calls,
- parsed_stream_calls,
- "[agent::session] wrap-up attempted a tool call; using deterministic fallback"
- );
- String::new()
- } else if !text.trim().is_empty() {
- tracing::debug!(
- model = effective_model,
- iteration = iteration_for_stream,
- text_len = text.len(),
- "[agent::session] wrap-up selected completed response text"
- );
- text
- } else {
- tracing::debug!(
- model = effective_model,
- iteration = iteration_for_stream,
- text_len = streamed_text.len(),
- "[agent::session] wrap-up selected buffered stream text"
- );
- streamed_text
- };
- // Hold wrap-up deltas until protocol validation completes. Otherwise a
- // rejected XML/P-Format tool call briefly renders in chat even though
- // the caller subsequently replaces it with a deterministic fallback.
- if stream_text && !checkpoint.is_empty() {
- if let Some(sink) = &self.on_progress {
- if let Err(error) = sink
- .send(AgentProgress::TextDelta {
- delta: checkpoint.clone(),
- iteration: iteration_for_stream,
- })
- .await
- {
- tracing::debug!(
- model = effective_model,
- iteration = iteration_for_stream,
- error = %error,
- "[agent::session] wrap-up progress sink closed"
- );
- }
- }
- }
- tracing::debug!(
- model = effective_model,
- iteration = iteration_for_stream,
- checkpoint_len = checkpoint.len(),
- used_deterministic_fallback = attempted_tool_call,
- "[agent::session] wrap-up checkpoint selection complete"
- );
- (checkpoint, usage)
- }
-
- /// Enforce this agent's required structured-output contract on the turn's
- /// final `reply` (issue #4117), reconciling with streaming.
- ///
- /// When the contract is active and `reply` already carries a well-formed
- /// leading block, returns `None` (the caller keeps `reply` unchanged). When
- /// the block is omitted/invalid, the turn is **repaired** so downstream
- /// parsing/routing always receives one, and the repaired text is returned as
- /// `Some((repaired_text, usage))` so the caller can fold the extra call's
- /// usage into the turn accounting and rewrite the trailing assistant message.
- ///
- /// ## Streaming reconciliation (the #4387 / sanil-23 blocker)
- ///
- /// The original reply is streamed to the client as `TextDelta`s *before* this
- /// runs (via the harness event bridge, keyed on `on_progress`). #4387
- /// repaired with a `stream: None` re-prompt whose result then *replaced* the
- /// already-streamed reply — so the client watched one answer stream in and
- /// silently got a different one back. This implementation makes the repair
- /// **append-only**, so the returned/persisted reply is always exactly the
- /// concatenation of deltas the client saw — the live preview is a *prefix* of
- /// the final message, never contradicted:
- ///
- /// * **Streamed case** (`on_progress` attached — interactive/user-visible):
- /// the corrective re-prompt runs *silently* (its raw output is never
- /// streamed, so a malformed attempt is never shown), then the chosen
- /// correction — the model's block if the concatenation validates, else a
- /// deterministic [`synthesize_block`] — is streamed as a continuation and
- /// appended after the original prose. Visible text == returned text, and
- /// the appended block is the first JSON value (prose isn't JSON), so the
- /// leading-position rule holds for the dominant omitted-block case.
- /// * **Non-streamed case** (`on_progress` absent — background/cron/routing,
- /// the "non-user-visible" scope sanil-23 offered as the alternative): no
- /// client saw anything, so there is nothing to stay consistent with. The
- /// strict #4387 **replace** design applies — recover via re-prompt, else
- /// prepend a synthesized block to the prose — guaranteeing strict leading
- /// position.
- ///
- /// `iteration_for_stream` labels the streamed continuation so the UI groups
- /// it with the turn's other deltas.
- ///
- /// [`synthesize_block`]: harness::required_output::synthesize_block
- pub(in super::super) async fn enforce_required_output(
- &self,
- reply: &str,
- contract: &tinyagents_harness::config::RequiredOutput,
- effective_model: &str,
- iteration_for_stream: u32,
- ) -> Option<(String, Option<UsageInfo>)> {
- use harness::required_output as ro;
-
- if ro::output_satisfies_contract(reply, contract) {
- return None;
- }
- log::warn!(
- "[agent_loop] required output block `{}` omitted from turn reply — repairing (streamed={})",
- contract.block_key,
- self.on_progress.is_some(),
- );
-
- // Corrective re-prompt (native tools disabled), seeded with the current
- // history — which already carries the omitting assistant reply, so the
- // model sees exactly what it left out. Run silently: we validate the
- // result before deciding whether/what to show, so a malformed attempt is
- // never streamed to the client.
- let mut base = crate::agent::message_convert::provider_messages_from_conversation(
- self.tool_dispatcher.as_ref(),
- &self.history,
- );
- base.push(ChatMessage::user(ro::repair_instruction(contract)));
- let (repair_text, usage) = self
- .silent_completion(&base, effective_model, "required-output re-prompt")
- .await;
- let repair_text = repair_text.trim().to_string();
-
- // Non-streamed (replace) path: nothing was shown, so the repaired reply
- // can stand alone with a strictly-leading block.
- if self.on_progress.is_none() {
- if !repair_text.is_empty() && ro::output_satisfies_contract(&repair_text, contract) {
- log::info!(
- "[agent_loop] required output block `{}` recovered via re-prompt (replace)",
- contract.block_key
- );
- return Some((repair_text, usage));
- }
- log::warn!(
- "[agent_loop] required output block `{}` still missing after re-prompt — prepending a synthesized block",
- contract.block_key
- );
- let synthesized = format!("{}\n\n{}", ro::synthesize_block(contract), reply);
- return Some((synthesized, usage));
- }
-
- // Streamed (append) path: the original prose is already on the client, so
- // never replace it — append a streamed correction and return the exact
- // concatenation the client sees. Append ONLY the required block, not the
- // whole re-prompt reply: `repair_instruction` asks the model to re-emit the
- // block *and continue with its answer*, so appending the full reply would
- // duplicate the already-streamed answer after the block (#4900). Prefer the
- // model's own recovered block; fall back to a synthesized one otherwise.
- let correction = match ro::find_required_block(&repair_text, contract) {
- Some(block) => {
- log::info!(
- "[agent_loop] required output block `{}` recovered via re-prompt (append)",
- contract.block_key
- );
- serde_json::to_string(&block).unwrap_or_else(|_| ro::synthesize_block(contract))
- }
- None => {
- log::warn!(
- "[agent_loop] required output block `{}` still missing after re-prompt — appending a synthesized block",
- contract.block_key
- );
- ro::synthesize_block(contract)
- }
- };
- // Stream only the correction as a continuation so the live preview stays
- // a prefix of the final message (visible == returned).
- let continuation = format!("\n\n{correction}");
- self.stream_text_continuation(&continuation, iteration_for_stream)
- .await;
- let repaired = format!("{reply}{continuation}");
- if !ro::output_satisfies_contract(&repaired, contract) {
- // The only way to reach here is a reply that streamed a *non-conforming
- // JSON object first*: append-only can't restore strict leading
- // position without contradicting what the user already saw, so we
- // accept the trailing valid block and keep stream consistency (the
- // higher-priority invariant). Downstream still finds a conforming
- // block via `extract_json_values`; only strict ordering is relaxed,
- // and only for this pathological already-streamed case.
- log::warn!(
- "[agent_loop] required output block `{}` appended but not in leading position (streamed reply led with JSON) — accepting for stream consistency",
- contract.block_key
- );
- }
- Some((repaired, usage))
- }
-
- /// Ask the provider once, with native tools **disabled** and **without**
- /// forwarding any delta to the progress sink: the required-output repair
- /// (issue #4117) and the closing-message check (issue #6278). `purpose`
- /// labels the logs. Returns the parsed prose paired
- /// with the call's usage (empty text + `None` usage when the call fails or
- /// yields only tool-call markup).
- ///
- /// Unlike [`summarize_turn_wrapup`](Self::summarize_turn_wrapup) this is
- /// deliberately silent: `enforce_required_output` validates the result before
- /// deciding what (if anything) to stream, so a malformed repair attempt is
- /// never shown to the client.
- pub(in crate::agent::harness::session::turn) async fn silent_completion(
- &self,
- base_messages: &[ChatMessage],
- effective_model: &str,
- purpose: &str,
- ) -> (String, Option<UsageInfo>) {
- let chat_model = match self.turn_model_source.build_summarizer(
- effective_model,
- self.temperature,
- self.thread_id(),
- ) {
- Ok(model) => model,
- Err(error) => {
- tracing::error!(
- error = %error,
- model = effective_model,
- purpose,
- "[agent::session] failed to build silent-completion model"
- );
- return (String::new(), None);
- }
- };
- let request = ModelRequest::new(
- base_messages
- .iter()
- .map(crate::agent::tinyagents::chat_message_to_message)
- .collect(),
- )
- .with_model(effective_model)
- .with_temperature(self.temperature)
- .with_max_tokens(AGENT_TURN_MAX_OUTPUT_TOKENS);
- let mut stream = match chat_model.stream(&(), request).await {
- Ok(stream) => stream,
- Err(error) => {
- tracing::warn!(
- error = %error,
- model = effective_model,
- purpose,
- "[agent::session] silent-completion stream failed to start"
- );
- return (String::new(), None);
- }
- };
-
- let mut streamed_text = String::new();
- let mut completed = None;
- while let Some(item) = stream.next().await {
- match item {
- // Buffer only — deliberately NOT forwarded to `on_progress`.
- ModelStreamItem::MessageDelta(delta) if !delta.text.is_empty() => {
- streamed_text.push_str(&delta.text);
- }
- ModelStreamItem::Completed(response) => completed = Some(response),
- ModelStreamItem::Failed(error) => {
- tracing::warn!(%error, purpose, "[agent::session] silent-completion stream failed");
- return (String::new(), None);
- }
- ModelStreamItem::ProviderFailed(error) => {
- tracing::warn!(error = %error.message, purpose, "[agent::session] silent-completion provider failed");
- return (String::new(), None);
- }
- _ => {}
- }
- }
- let Some(response) = completed else {
- tracing::warn!(
- purpose,
- "[agent::session] silent-completion ended without completion"
- );
- return (String::new(), None);
- };
- let usage = crate::agent::tinyagents::model::usage_info_from_response(&response);
- let text = response.text();
- let out = if !text.trim().is_empty() {
- text
- } else if response.tool_calls().is_empty() {
- streamed_text
- } else {
- // Only tool-call markup was present — no usable prose.
- String::new()
- };
- (out, usage)
- }
-
- /// Emit `text` to the progress sink as a `TextDelta` continuation so a
- /// repaired required-output block appears in the UI appended after the
- /// already-streamed reply (issue #4117). No-op when no sink is attached.
- pub(in crate::agent::harness::session::turn) async fn stream_text_continuation(
- &self,
- text: &str,
- iteration: u32,
- ) {
- if text.is_empty() {
- return;
- }
- if let Some(sink) = &self.on_progress {
- let _ = sink
- .send(AgentProgress::TextDelta {
- delta: text.to_string(),
- iteration,
- })
- .await;
- }
- }
-}
diff --git a/crates/openhuman-core/src/agent/harness/session/turn_auto_recall_tests.rs b/crates/openhuman-core/src/agent/harness/session/turn_auto_recall_tests.rs
deleted file mode 100644
index e1ddce4a7b..0000000000
--- a/crates/openhuman-core/src/agent/harness/session/turn_auto_recall_tests.rs
+++ /dev/null
@@ -1,300 +0,0 @@
-use super::turn_learned_context_and_announcements_tests::scripted_reply;
-use super::*;
-
-// ── Lane C: auto-recall of facts about the user (#6040) ──────────────────────
-//
-// The lane is exercised through a real `turn()`: a scripted source stands in
-// for the memory driver, the scripted chat model records every request, and
-// the assertions read the user message the model was actually sent.
-
-use crate::memory::api::error::MemoryError;
-use crate::memory::api::provider::retrieval::{
- FastRetrieveQuery, RetrievalHit, RetrievalNodeKind, RetrievalResponse,
-};
-use crate::memory::api::types::NamespaceMemoryHit;
-use crate::memory::auto_recall::{
- AutoRecall, AutoRecallSource, AUTO_RECALL_BANNER, AUTO_RECALL_HINT,
-};
-use crate::memory::guard::test_support::{
- embedded_policy, guarded_with, namespace_hit, RecordingProvider,
-};
-
-const IDOL_QUESTION: &str = "who is my idol and why?";
-const IDOL_FACT: &str = "Idol: Virat Kohli, because of his dedication and consistency";
-
-struct ScriptedAutoRecallSource {
- hits: Vec<RetrievalHit>,
- delay: Duration,
- calls: AtomicUsize,
- notes_calls: AtomicUsize,
-}
-
-impl ScriptedAutoRecallSource {
- fn with_fact(content: &str) -> Arc<Self> {
- Arc::new(Self {
- hits: vec![RetrievalHit {
- node_id: "leaf-1".into(),
- node_kind: RetrievalNodeKind::Leaf,
- tree_id: String::new(),
- tree_kind: None,
- tree_scope: "folder:profile".into(),
- level: 0,
- content: content.to_string(),
- entities: Vec::new(),
- topics: Vec::new(),
- time_range_start: chrono::DateTime::<chrono::Utc>::default(),
- time_range_end: chrono::DateTime::<chrono::Utc>::default(),
- score: 0.9,
- child_ids: Vec::new(),
- source_ref: None,
- }],
- delay: Duration::ZERO,
- calls: AtomicUsize::new(0),
- notes_calls: AtomicUsize::new(0),
- })
- }
-
- fn slow(content: &str, delay: Duration) -> Arc<Self> {
- let mut source = Arc::try_unwrap(Self::with_fact(content))
- .ok()
- .expect("fresh arc");
- source.delay = delay;
- Arc::new(source)
- }
-
- fn calls(&self) -> usize {
- self.calls.load(Ordering::SeqCst)
- }
-
- fn notes_calls(&self) -> usize {
- self.notes_calls.load(Ordering::SeqCst)
- }
-}
-
-#[async_trait]
-impl AutoRecallSource for ScriptedAutoRecallSource {
- async fn fast_retrieve(
- &self,
- _query: &str,
- _options: FastRetrieveQuery,
- ) -> Result<RetrievalResponse, MemoryError> {
- self.calls.fetch_add(1, Ordering::SeqCst);
- if !self.delay.is_zero() {
- tokio::time::sleep(self.delay).await;
- }
- Ok(RetrievalResponse {
- total: self.hits.len(),
- hits: self.hits.clone(),
- truncated: false,
- })
- }
-
- async fn recall_namespace_scored(
- &self,
- _namespace: &str,
- _query: &str,
- _limit: usize,
- ) -> Result<Vec<NamespaceMemoryHit>, MemoryError> {
- // This fake scripts the tree; the notes leg is exercised through the
- // production wiring below, over a `RecordingProvider`.
- self.notes_calls.fetch_add(1, Ordering::SeqCst);
- Ok(Vec::new())
- }
-}
-
-/// A turn-capable agent with Lane C bound (or deliberately absent), over the
-/// same real embedded store the other turn tests use.
-fn make_agent_with_auto_recall(
- provider: Arc<dyn ChatModel<()>>,
- auto_recall: Option<Arc<AutoRecall>>,
-) -> Agent {
- let workspace = tempfile::TempDir::new().expect("temp workspace");
- let workspace_path = workspace.path().to_path_buf();
- std::mem::forget(workspace);
- let _memory_cfg = crate::config::MemoryConfig {
- backend: "none".into(),
- ..crate::config::MemoryConfig::default()
- };
- let mem: Arc<dyn Memory> = crate::memory::test_support::noop_memory();
-
- Agent::builder()
- .chat_model(provider)
- .tools(vec![])
- .memory(mem)
- .auto_recall(auto_recall)
- .tool_dispatcher(Box::new(XmlDialect))
- .config(crate::config::AgentConfig::default())
- .context_config(crate::config::ContextConfig::default())
- .workspace_dir(workspace_path)
- .event_context("turn-test-session", "turn-test-channel")
- .build()
- .unwrap()
-}
-
-/// The messages the model was sent on the first (only) request, split by role.
-async fn first_request(provider: &SequenceProvider) -> (Vec<String>, Vec<String>) {
- let requests = provider.requests.lock().await;
- let request = requests.first().expect("the model was called once");
- let system = request
- .iter()
- .filter(|m| m.role == "system")
- .map(|m| m.content.clone())
- .collect();
- let user = request
- .iter()
- .filter(|m| m.role == "user")
- .map(|m| m.content.clone())
- .collect();
- (system, user)
-}
-
-#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
-async fn auto_recall_block_rides_the_user_message_for_a_personal_question() {
- let source = ScriptedAutoRecallSource::with_fact(IDOL_FACT);
- let lane = Arc::new(AutoRecall::new(source.clone(), true, None));
- let provider_impl = scripted_reply("Virat Kohli, for his dedication and consistency.");
- let provider: Arc<dyn ChatModel<()>> = provider_impl.clone();
- let mut agent = make_agent_with_auto_recall(provider, Some(lane));
-
- let reply = agent.turn(IDOL_QUESTION).await.expect("turn succeeds");
- assert!(reply.contains("Virat"));
- assert_eq!(source.calls(), 1, "one bounded lookup for one gated turn");
- assert_eq!(source.notes_calls(), 1, "and one notes lookup beside it");
-
- let (system, user) = first_request(&provider_impl).await;
- let last_user = user.last().expect("a user message");
- assert!(
- last_user.contains(AUTO_RECALL_BANNER) && last_user.contains("Virat Kohli"),
- "the block must ride the user message: {last_user}"
- );
- assert!(
- last_user.contains(IDOL_QUESTION),
- "the user's own words must follow the block: {last_user}"
- );
- assert!(
- system.iter().all(|s| !s.contains(AUTO_RECALL_BANNER)),
- "the block must never land in the system prompt"
- );
-}
-
-#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
-async fn auto_recall_stays_silent_and_costs_nothing_on_small_talk() {
- let source = ScriptedAutoRecallSource::with_fact(IDOL_FACT);
- let lane = Arc::new(AutoRecall::new(source.clone(), true, None));
- let provider_impl = scripted_reply("Sunny, probably.");
- let provider: Arc<dyn ChatModel<()>> = provider_impl.clone();
- let mut agent = make_agent_with_auto_recall(provider, Some(lane));
-
- agent
- .turn("what's the weather today")
- .await
- .expect("turn succeeds");
- assert_eq!(source.calls(), 0, "a closed gate never reaches the store");
- let (_, user) = first_request(&provider_impl).await;
- assert!(user.iter().all(|u| !u.contains(AUTO_RECALL_BANNER)));
-}
-
-#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
-async fn auto_recall_disabled_by_the_hooks_switch_injects_nothing() {
- let source = ScriptedAutoRecallSource::with_fact(IDOL_FACT);
- let lane = Arc::new(AutoRecall::new(source.clone(), false, None));
- let provider_impl = scripted_reply("I don't have that stored.");
- let provider: Arc<dyn ChatModel<()>> = provider_impl.clone();
- let mut agent = make_agent_with_auto_recall(provider, Some(lane));
-
- agent.turn(IDOL_QUESTION).await.expect("turn succeeds");
- assert_eq!(source.calls(), 0);
- let (_, user) = first_request(&provider_impl).await;
- assert!(user.iter().all(|u| !u.contains(AUTO_RECALL_BANNER)));
-}
-
-#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
-async fn auto_recall_timeout_yields_an_ordinary_turn() {
- let source = ScriptedAutoRecallSource::slow(IDOL_FACT, Duration::from_millis(300));
- let lane = Arc::new(
- AutoRecall::new(source.clone(), true, None).with_budget(Duration::from_millis(20)),
- );
- let provider_impl = scripted_reply("Still here.");
- let provider: Arc<dyn ChatModel<()>> = provider_impl.clone();
- let mut agent = make_agent_with_auto_recall(provider, Some(lane));
-
- let reply = agent.turn(IDOL_QUESTION).await.expect("turn succeeds");
- assert_eq!(reply, "Still here.");
- assert_eq!(source.calls(), 1);
- let (_, user) = first_request(&provider_impl).await;
- assert!(user.iter().all(|u| !u.contains(AUTO_RECALL_BANNER)));
-}
-
-#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
-async fn a_session_without_the_lane_turns_as_before() {
- let provider_impl = scripted_reply("Hello.");
- let provider: Arc<dyn ChatModel<()>> = provider_impl.clone();
- let mut agent = make_agent_with_auto_recall(provider, None);
-
- let reply = agent.turn(IDOL_QUESTION).await.expect("turn succeeds");
- assert_eq!(reply, "Hello.");
- let (_, user) = first_request(&provider_impl).await;
- assert!(user.iter().all(|u| !u.contains(AUTO_RECALL_BANNER)));
-}
-
-// ── Lane C: the notes leg (#6063) ────────────────────────────────────────────
-
-#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
-async fn auto_recall_injects_a_note_written_by_memory_store_when_the_tree_is_empty() {
- // The #6063 repro through the production wiring: `memory_store` filed the
- // fact in `global`, the tree never saw it, and the lane is bound from the
- // guard exactly as `bind_session_memory` binds it.
- let provider = RecordingProvider::new().with_namespace_hits(vec![namespace_hit(
- "global",
- "favourite_tea_oolong",
- "User's favourite tea is oolong.",
- 0.72,
- )]);
- let (provider, guard) = guarded_with(provider, embedded_policy());
- let lane = Arc::new(AutoRecall::from_guard(Arc::new(guard)));
- let model_impl = scripted_reply("Oolong.");
- let model: Arc<dyn ChatModel<()>> = model_impl.clone();
- let mut agent = make_agent_with_auto_recall(model, Some(lane));
-
- let reply = agent
- .turn("What's my favourite tea?")
- .await
- .expect("turn succeeds");
- assert_eq!(reply, "Oolong.");
-
- let (system, user) = first_request(&model_impl).await;
- let last_user = user.last().expect("a user message");
- assert!(last_user.contains(AUTO_RECALL_BANNER), "{last_user}");
- assert!(
- last_user.contains(AUTO_RECALL_HINT),
- "the block says what it is: {last_user}"
- );
- assert!(
- last_user.contains("- User's favourite tea is oolong. (note: favourite_tea_oolong)"),
- "the note rides the user message: {last_user}"
- );
- assert!(
- system.iter().all(|s| !s.contains(AUTO_RECALL_BANNER)),
- "the block must never land in the system prompt"
- );
-
- let mut methods: Vec<String> = provider.calls().into_iter().map(|c| c.method).collect();
- methods.sort();
- assert_eq!(
- methods,
- vec![
- "retrieval.fast_retrieve".to_string(),
- "retrieval.recall_namespace_scored".to_string()
- ],
- "both legs, once each, through the guard"
- );
- let notes_call = provider
- .calls()
- .into_iter()
- .find(|c| c.method == "retrieval.recall_namespace_scored")
- .expect("the notes leg");
- assert_eq!(
- notes_call.content.as_deref(),
- Some("namespace=global limit=3")
- );
-}
diff --git a/crates/openhuman-core/src/agent/harness/session/turn_checkpoint_and_wrapup_tests.rs b/crates/openhuman-core/src/agent/harness/session/turn_checkpoint_and_wrapup_tests.rs
deleted file mode 100644
index 8c4f18be8a..0000000000
--- a/crates/openhuman-core/src/agent/harness/session/turn_checkpoint_and_wrapup_tests.rs
+++ /dev/null
@@ -1,667 +0,0 @@
-use super::*;
-use tinyagents_session::transcript;
-
-/// Issue #4117 — when the corrective re-prompt call itself fails, enforcement
-/// still guarantees a well-formed block: the deterministic synthesized fallback
-/// is used so the turn is never left without one (no live sink → replace path).
-#[tokio::test]
-async fn turn_synthesizes_required_output_when_reprompt_call_fails() {
- let provider_impl = Arc::new(SequenceProvider {
- responses: AsyncMutex::new(vec![
- Ok(ChatResponse {
- text: Some("Working on it.".into()),
- tool_calls: vec![],
- usage: None,
- reasoning_content: None,
- }),
- // Re-prompt call errors out.
- Err(anyhow::anyhow!("provider boom")),
- ]),
- requests: AsyncMutex::new(Vec::new()),
- tool_counts: AsyncMutex::new(Vec::new()),
- });
- let provider: Arc<dyn ChatModel<()>> = provider_impl.clone();
-
- let config = crate::config::AgentConfig {
- max_tool_iterations: 3,
- max_history_messages: 10,
- required_output: Some(crate::config::RequiredOutputContract::new("thoughts")),
- ..crate::config::AgentConfig::default()
- };
-
- let mut agent = make_agent_with_builder(
- provider,
- vec![],
- vec![],
- config,
- crate::config::ContextConfig::default(),
- );
-
- let response = agent.turn("hello").await.expect("turn should succeed");
-
- // Deterministic fallback: a synthesized block leads, original prose kept.
- let first_block = tinytools_agent::extract_json_values(&response)
- .into_iter()
- .next();
- assert!(
- first_block
- .as_ref()
- .is_some_and(|v| v.get("thoughts").is_some()),
- "failed re-prompt must still yield a synthesized leading block, got: {response}"
- );
- assert!(response.contains("Working on it."));
-}
-
-#[tokio::test]
-async fn turn_emits_checkpoint_when_max_tool_iterations_are_exceeded() {
- // First response forces a tool call (consuming the single allowed
- // iteration); the second is the model-written checkpoint the harness
- // requests (tools disabled) once the cap is hit. The turn must NOT
- // error anymore — it returns a resumable checkpoint so the thread stays
- // well-formed and the user can continue on their next message
- // (bug-report-2026-05-26 A1).
- let provider: Arc<dyn ChatModel<()>> = Arc::new(SequenceProvider {
- responses: AsyncMutex::new(vec![
- Ok(ChatResponse {
- text: Some("<tool_call>{\"name\":\"echo\",\"arguments\":{}}</tool_call>".into()),
- tool_calls: vec![],
- usage: None,
- reasoning_content: None,
- }),
- Ok(ChatResponse {
- text: Some(
- "**Done so far:** ran echo.\n**Next steps:** I'll continue from here.".into(),
- ),
- tool_calls: vec![],
- usage: None,
- reasoning_content: None,
- }),
- ]),
- requests: AsyncMutex::new(Vec::new()),
- tool_counts: AsyncMutex::new(Vec::new()),
- });
- let mut agent = make_agent_with_builder(
- provider,
- vec![Box::new(EchoTool)],
- vec![],
- crate::config::AgentConfig {
- max_tool_iterations: 1,
- ..crate::config::AgentConfig::default()
- },
- crate::config::ContextConfig::default(),
- );
-
- let reply = agent
- .turn("hello")
- .await
- .expect("turn should emit a checkpoint at the iteration cap, not error");
- assert!(
- reply.contains("Next steps"),
- "checkpoint should summarize next steps, got: {reply}"
- );
- // The tool-call history from the capped iteration is preserved...
- assert!(agent.history.iter().any(|message| matches!(
- message,
- ConversationMessage::AssistantToolCalls { tool_calls, .. } if tool_calls.len() == 1
- )));
- // ...and the transcript ends on a well-formed assistant message (the
- // checkpoint), never a dangling tool cycle — this is what stops the
- // next message from silently wedging the thread.
- assert!(
- matches!(
- agent.history.last(),
- Some(ConversationMessage::Chat(msg))
- if msg.role == "assistant" && msg.content.contains("Next steps")
- ),
- "history should end on the assistant checkpoint, got: {:?}",
- agent.history.last()
- );
-}
-
-#[tokio::test]
-async fn turn_errors_on_empty_provider_response() {
- // A completion with no text and no tool calls is never a valid final
- // answer — surface it as an error instead of accepting a blank reply,
- // which previously rendered as silence and wedged the thread
- // (bug-report-2026-05-26 A1, defect B).
- let provider: Arc<dyn ChatModel<()>> = Arc::new(SequenceProvider {
- responses: AsyncMutex::new(vec![Ok(ChatResponse {
- text: Some(String::new()),
- tool_calls: vec![],
- usage: None,
- reasoning_content: None,
- })]),
- requests: AsyncMutex::new(Vec::new()),
- tool_counts: AsyncMutex::new(Vec::new()),
- });
- let mut agent = make_agent_with_builder(
- provider,
- vec![],
- vec![],
- crate::config::AgentConfig::default(),
- crate::config::ContextConfig::default(),
- );
-
- let err = agent
- .turn("hello")
- .await
- .expect_err("an empty provider response should surface as an error");
- assert!(
- err.to_string().contains("empty response"),
- "expected an empty-response error, got: {err}"
- );
-}
-
-#[tokio::test]
-async fn turn_checkpoint_falls_back_to_deterministic_summary_when_model_summary_empty() {
- // Tool call consumes the single iteration; the checkpoint request then
- // comes back empty. The harness must fall back to a deterministic
- // done/next summary so the turn never returns blank — the safety net
- // that guarantees the thread can't re-wedge (bug-report-2026-05-26 A1).
- let provider: Arc<dyn ChatModel<()>> = Arc::new(SequenceProvider {
- responses: AsyncMutex::new(vec![
- Ok(ChatResponse {
- text: Some("<tool_call>{\"name\":\"echo\",\"arguments\":{}}</tool_call>".into()),
- tool_calls: vec![],
- usage: None,
- reasoning_content: None,
- }),
- Ok(ChatResponse {
- text: Some(String::new()),
- tool_calls: vec![],
- usage: None,
- reasoning_content: None,
- }),
- ]),
- requests: AsyncMutex::new(Vec::new()),
- tool_counts: AsyncMutex::new(Vec::new()),
- });
- let mut agent = make_agent_with_builder(
- provider,
- vec![Box::new(EchoTool)],
- vec![],
- crate::config::AgentConfig {
- max_tool_iterations: 1,
- ..crate::config::AgentConfig::default()
- },
- crate::config::ContextConfig::default(),
- );
-
- let reply = agent
- .turn("hello")
- .await
- .expect("empty model checkpoint should fall back, not error");
- assert!(
- reply.contains("tool-call limit"),
- "deterministic fallback summary expected, got: {reply}"
- );
- assert!(
- reply.contains("echo"),
- "fallback should list the tool that ran, got: {reply}"
- );
-}
-
-#[tokio::test]
-async fn turn_checkpoint_rejects_pformat_wrapup_without_streaming_it() {
- let provider: Arc<dyn ChatModel<()>> = Arc::new(SequenceProvider {
- responses: AsyncMutex::new(vec![
- Ok(ChatResponse {
- text: Some("<tool_call>{\"name\":\"echo\",\"arguments\":{}}</tool_call>".into()),
- ..ChatResponse::default()
- }),
- Ok(ChatResponse {
- text: Some("<tool_call>echo[]</tool_call>".into()),
- ..ChatResponse::default()
- }),
- ]),
- requests: AsyncMutex::new(Vec::new()),
- tool_counts: AsyncMutex::new(Vec::new()),
- });
- let tools: Vec<Box<dyn Tool>> = vec![Box::new(EchoTool)];
- let registry = tinytools_agent::build_registry(
- tools
- .iter()
- .map(|tool| (tool.name(), tool.parameters_schema())),
- );
- let mut agent = make_agent_with_builder_and_dispatcher(
- provider,
- tools,
- vec![],
- crate::config::AgentConfig {
- max_tool_iterations: 1,
- ..crate::config::AgentConfig::default()
- },
- crate::config::ContextConfig::default(),
- Box::new(PFormatDialect::new(registry)),
- );
- let (progress_tx, mut progress_rx) = tokio::sync::mpsc::channel(16);
- agent.set_on_progress(Some(progress_tx));
-
- let reply = agent
- .turn("hello")
- .await
- .expect("P-Format wrap-up call should use the deterministic checkpoint");
- assert!(
- reply.contains("tool-call limit"),
- "P-Format wrap-up must be rejected, got: {reply}"
- );
-
- agent.set_on_progress(None);
- let mut rendered_invalid_wrapup = false;
- while let Ok(progress) = progress_rx.try_recv() {
- if let crate::agent::progress::AgentProgress::TextDelta { delta, .. } = progress {
- rendered_invalid_wrapup |= delta.contains("echo[]");
- }
- }
- assert!(
- !rendered_invalid_wrapup,
- "rejected P-Format wrap-up must not be emitted to the progress sink"
- );
-}
-
-#[tokio::test]
-async fn turn_synthesizes_final_answer_when_tool_turn_yields_no_text() {
- // #4093: the model runs a tool and then yields a terminating response with
- // NO text and NO further tool calls — the turn did work but would end
- // silently. Because the cap was not hit, this is not a checkpoint case; the
- // harness must enforce the "must produce a final response" terminal step by
- // re-prompting the model (tools disabled) for a closing summary and
- // returning that instead of a blank reply.
- let provider: Arc<dyn ChatModel<()>> = Arc::new(SequenceProvider {
- responses: AsyncMutex::new(vec![
- // Tool iteration (well under the cap).
- Ok(ChatResponse {
- text: Some("<tool_call>{\"name\":\"echo\",\"arguments\":{}}</tool_call>".into()),
- tool_calls: vec![],
- usage: None,
- reasoning_content: None,
- }),
- // Terminal response with no text and no tool calls — the silent end.
- Ok(ChatResponse {
- text: Some(String::new()),
- tool_calls: vec![],
- usage: None,
- reasoning_content: None,
- }),
- // The harness's forced final-answer re-prompt (tools disabled).
- Ok(ChatResponse {
- text: Some("All done — I ran echo and it succeeded.".into()),
- tool_calls: vec![],
- usage: None,
- reasoning_content: None,
- }),
- // The check on that closing message accepts it (#6278).
- Ok(ChatResponse {
- text: Some("ACCEPT".into()),
- ..ChatResponse::default()
- }),
- ]),
- requests: AsyncMutex::new(Vec::new()),
- tool_counts: AsyncMutex::new(Vec::new()),
- });
- let mut agent = make_agent_with_builder(
- provider,
- vec![Box::new(EchoTool)],
- vec![],
- crate::config::AgentConfig {
- max_tool_iterations: 5,
- ..crate::config::AgentConfig::default()
- },
- crate::config::ContextConfig::default(),
- );
-
- let reply = agent
- .turn("hello")
- .await
- .expect("a tool-only turn with no final text should synthesize one, not error");
- assert!(
- !reply.trim().is_empty(),
- "turn must never end with an empty final message (#4093), got: {reply:?}"
- );
- assert!(
- reply.contains("I ran echo"),
- "the synthesized final message should be the model's wrap-up, got: {reply}"
- );
- // The transcript must end on the assistant's final message, not a dangling
- // tool cycle.
- assert!(
- matches!(
- agent.history.last(),
- Some(ConversationMessage::Chat(msg))
- if msg.role == "assistant" && !msg.content.trim().is_empty()
- ),
- "history should end on a non-empty assistant message, got: {:?}",
- agent.history.last()
- );
- // ...and the blank terminal assistant response (folded in from the turn
- // outcome) must have been dropped, not left dangling before the synthesized
- // answer (Codex review).
- assert!(
- !agent.history.iter().any(|m| matches!(
- m,
- ConversationMessage::Chat(msg)
- if msg.role == "assistant" && msg.content.trim().is_empty()
- )),
- "no blank assistant turn should remain in history, got: {:?}",
- agent.history
- );
-}
-
-#[tokio::test]
-async fn turn_final_answer_falls_back_to_deterministic_summary_when_reprompt_empty() {
- // #4093 safety net: the tool ran, the model yielded no final text, and the
- // forced final-answer re-prompt ALSO came back empty. The harness must fall
- // back to a deterministic summary of the tool calls so the turn is never
- // blank — and, unlike the cap path, it must read as a completed summary
- // rather than a paused "tool-call limit" checkpoint.
- let provider: Arc<dyn ChatModel<()>> = Arc::new(SequenceProvider {
- responses: AsyncMutex::new(vec![
- Ok(ChatResponse {
- text: Some("<tool_call>{\"name\":\"echo\",\"arguments\":{}}</tool_call>".into()),
- tool_calls: vec![],
- usage: None,
- reasoning_content: None,
- }),
- Ok(ChatResponse {
- text: Some(String::new()),
- tool_calls: vec![],
- usage: None,
- reasoning_content: None,
- }),
- // Re-prompt for a final answer also returns empty.
- Ok(ChatResponse {
- text: Some(String::new()),
- tool_calls: vec![],
- usage: None,
- reasoning_content: None,
- }),
- ]),
- requests: AsyncMutex::new(Vec::new()),
- tool_counts: AsyncMutex::new(Vec::new()),
- });
- let mut agent = make_agent_with_builder(
- provider,
- vec![Box::new(EchoTool)],
- vec![],
- crate::config::AgentConfig {
- max_tool_iterations: 5,
- ..crate::config::AgentConfig::default()
- },
- crate::config::ContextConfig::default(),
- );
-
- let reply = agent
- .turn("hello")
- .await
- .expect("empty final re-prompt should fall back deterministically, not error");
- assert!(
- !reply.trim().is_empty(),
- "deterministic fallback must be non-empty (#4093), got: {reply:?}"
- );
- assert!(
- reply.contains("echo"),
- "fallback should list the tool that ran, got: {reply}"
- );
- assert!(
- !reply.contains("tool-call limit"),
- "a non-capped turn must not claim it hit the tool-call limit, got: {reply}"
- );
- // The blank terminal assistant response must not linger before the
- // deterministic summary (Codex review).
- assert!(
- !agent.history.iter().any(|m| matches!(
- m,
- ConversationMessage::Chat(msg)
- if msg.role == "assistant" && msg.content.trim().is_empty()
- )),
- "no blank assistant turn should remain in history, got: {:?}",
- agent.history
- );
-}
-
-#[tokio::test]
-async fn summarize_turn_wrapup_rejects_prompt_tool_call_and_preserves_usage() {
- let provider: Arc<dyn ChatModel<()>> = Arc::new(SequenceProvider {
- responses: AsyncMutex::new(vec![Ok(ChatResponse {
- text: Some("<tool_call>{\"name\":\"echo\",\"arguments\":{}}</tool_call>".into()),
- tool_calls: vec![],
- usage: Some(UsageInfo {
- input_tokens: 13,
- output_tokens: 5,
- cached_input_tokens: 3,
- charged_amount_usd: 0.07,
- ..UsageInfo::default()
- }),
- reasoning_content: None,
- })]),
- requests: AsyncMutex::new(Vec::new()),
- tool_counts: AsyncMutex::new(Vec::new()),
- });
- let agent = make_agent_with_builder(
- provider,
- vec![],
- vec![],
- crate::config::AgentConfig::default(),
- crate::config::ContextConfig::default(),
- );
-
- let (summary, usage) = agent
- .summarize_turn_wrapup(&[], "test-model", 1, "write a wrap-up", true)
- .await;
-
- assert!(
- summary.is_empty(),
- "prompt-formatted tool calls must trigger the deterministic fallback"
- );
- let usage = usage.expect("rejected wrap-up must preserve provider usage");
- assert_eq!(usage.input_tokens, 13);
- assert_eq!(usage.output_tokens, 5);
- assert_eq!(usage.cached_input_tokens, 3);
- assert_eq!(usage.charged_amount_usd, 0.07);
-}
-
-#[tokio::test]
-async fn turn_checkpoint_usage_is_folded_into_transcript_accounting() {
- // The extra checkpoint provider call costs tokens; those must land in
- // the persisted transcript's cumulative accounting rather than being
- // silently dropped (CodeRabbit review on bug-report-2026-05-26 A1).
- let provider: Arc<dyn ChatModel<()>> = Arc::new(SequenceProvider {
- responses: AsyncMutex::new(vec![
- // Tool iteration — provider reports no usage.
- Ok(ChatResponse {
- text: Some("<tool_call>{\"name\":\"echo\",\"arguments\":{}}</tool_call>".into()),
- tool_calls: vec![],
- usage: None,
- reasoning_content: None,
- }),
- // Checkpoint call — reports usage that must be accounted for.
- Ok(ChatResponse {
- text: Some("**Done so far:** ran echo.\n**Next steps:** continue.".into()),
- tool_calls: vec![],
- usage: Some(UsageInfo {
- input_tokens: 11,
- output_tokens: 4,
- cached_input_tokens: 2,
- charged_amount_usd: 0.05,
- ..UsageInfo::default()
- }),
- reasoning_content: None,
- }),
- ]),
- requests: AsyncMutex::new(Vec::new()),
- tool_counts: AsyncMutex::new(Vec::new()),
- });
- let mut agent = make_agent_with_builder(
- provider,
- vec![Box::new(EchoTool)],
- vec![],
- crate::config::AgentConfig {
- max_tool_iterations: 1,
- ..crate::config::AgentConfig::default()
- },
- crate::config::ContextConfig::default(),
- );
-
- agent
- .turn("hello")
- .await
- .expect("turn should emit a checkpoint at the iteration cap");
-
- let transcript = transcript::read_transcript(
- agent
- .session_transcript_path
- .as_ref()
- .expect("checkpoint turn should persist a transcript"),
- )
- .expect("transcript should be readable");
- // Only the checkpoint call reported usage, so the turn totals must equal
- // exactly its numbers — proof the extra call is accounted for, not lost.
- assert_eq!(
- transcript.meta.input_tokens, 11,
- "checkpoint input tokens should be folded into the turn total"
- );
- assert_eq!(transcript.meta.output_tokens, 4);
- assert_eq!(transcript.meta.cached_input_tokens, 2);
-}
-
-#[tokio::test]
-async fn fetch_learned_context_returns_empty_when_both_flags_off() {
- let tmp = tempfile::TempDir::new().unwrap();
- let mem = make_real_memory(tmp.path());
-
- // Store a pinned preference so we can verify it is NOT returned.
- mem.store(
- "user_profile",
- "pinned/tooling/package_manager",
- "[pinned] (class=tooling) package_manager: pnpm",
- crate::memory::MemoryCategory::Core,
- None,
- )
- .await
- .unwrap();
-
- let agent = make_agent_with_memory(
- mem,
- tmp.path().to_path_buf(),
- false, // learning_enabled
- false, // explicit_preferences_enabled
- );
-
- let learned = agent.fetch_learned_context().await;
-
- assert!(
- learned.user_profile.is_empty(),
- "both flags off: user_profile must be empty, got {:?}",
- learned.user_profile
- );
- assert!(learned.observations.is_empty());
- assert!(learned.patterns.is_empty());
- assert!(learned.reflections.is_empty());
-}
-
-/// Issue #6014: a capped turn concludes from **inside** the loop.
-///
-/// The turn used to exit on the cap and then make a second, out-of-band call
-/// asking for a checkpoint. That call ran with none of the loop's context
-/// management and failed silently into a digest of tool names — on the very
-/// turns that had gathered the most. The last permitted model call now does the
-/// concluding itself: tools withdrawn, wrap-up instruction appended, answer
-/// produced by an ordinary loop iteration.
-///
-/// Pinned here: the tool schemas really are withdrawn on that call (not merely
-/// discouraged in prose), the loop's own text becomes the reply, the turn still
-/// reports as capped, and — the whole point — no extra provider call is made.
-#[tokio::test]
-async fn a_capped_turn_concludes_inside_the_loop_without_a_second_call() {
- let recorded = Arc::new(SequenceProvider {
- responses: AsyncMutex::new(vec![
- // Call 1 spends the turn's only tool round.
- Ok(ChatResponse {
- text: Some("<tool_call>{\"name\":\"echo\",\"arguments\":{}}</tool_call>".into()),
- tool_calls: vec![],
- usage: None,
- reasoning_content: None,
- }),
- // Call 2 is the last permitted one, so the middleware turns it into
- // the conclusion. A third response is deliberately NOT scripted: if
- // anything still made an out-of-band wrap-up call, the provider
- // would run dry and the turn would fail.
- Ok(ChatResponse {
- text: Some("The echo tool returned `hello`, which answers the question.".into()),
- tool_calls: vec![],
- usage: None,
- reasoning_content: None,
- }),
- ]),
- requests: AsyncMutex::new(Vec::new()),
- tool_counts: AsyncMutex::new(Vec::new()),
- });
- let provider: Arc<dyn ChatModel<()>> = recorded.clone();
-
- let mut agent = make_agent_with_builder(
- provider,
- vec![Box::new(EchoTool)],
- vec![],
- crate::config::AgentConfig {
- // Two, not one: a single-call budget would make the FIRST call the
- // concluding one, so the turn could never run a tool at all — which
- // the middleware treats as a misconfiguration and declines to touch.
- max_tool_iterations: 2,
- ..crate::config::AgentConfig::default()
- },
- crate::config::ContextConfig::default(),
- );
-
- let reply = agent
- .turn("what does echo say?")
- .await
- .expect("a capped turn should conclude, not error");
-
- // The loop's own final text is the reply — it reports the RESULT, which is
- // what the old process-shaped checkpoint could not do.
- assert!(
- reply.contains("returned `hello`"),
- "the in-loop conclusion should be the reply, got: {reply}"
- );
-
- let tool_counts = recorded.tool_counts.lock().await.clone();
- assert_eq!(
- tool_counts.len(),
- 2,
- "exactly two provider calls: the tool round and the conclusion — an out-of-band wrap-up \
- would make a third, {tool_counts:?}"
- );
- assert!(
- tool_counts[0] > 0,
- "the first call must be offered the tool belt, got {tool_counts:?}"
- );
- assert_eq!(
- tool_counts[1], 0,
- "the concluding call must be offered NO tools — the instruction alone is a request the \
- model may ignore, {tool_counts:?}"
- );
-
- // Still reported as a pause, so callers that render a "continue" affordance
- // (and the workflow runner, which must not settle a capped node as
- // finished) keep the signal they read today.
- assert!(
- agent.last_turn_hit_cap(),
- "a turn that concluded at its cap is still a capped turn"
- );
-
- // The transcript ends on that conclusion exactly once: it came from the
- // loop, so it is already folded in via the run's conversation, and the cap
- // branch must not append a second copy.
- let conclusions = agent
- .history
- .iter()
- .filter(|message| {
- matches!(message, ConversationMessage::Chat(msg)
- if msg.role == "assistant" && msg.content.contains("returned `hello`"))
- })
- .count();
- assert_eq!(
- conclusions, 1,
- "the conclusion should appear once in history, not be re-pushed by the cap branch"
- );
-}
diff --git a/crates/openhuman-core/src/agent/harness/session/turn_failed_turn_history_tests.rs b/crates/openhuman-core/src/agent/harness/session/turn_failed_turn_history_tests.rs
deleted file mode 100644
index ce8616a477..0000000000
--- a/crates/openhuman-core/src/agent/harness/session/turn_failed_turn_history_tests.rs
+++ /dev/null
@@ -1,220 +0,0 @@
-use super::*;
-use tinyagents_session::transcript;
-
-fn echo_tool_call() -> anyhow::Result<ChatResponse> {
- Ok(ChatResponse {
- text: Some("<tool_call>{\"name\":\"echo\",\"arguments\":{}}</tool_call>".into()),
- tool_calls: vec![],
- usage: Some(UsageInfo {
- input_tokens: 100,
- output_tokens: 7,
- ..UsageInfo::default()
- }),
- reasoning_content: None,
- })
-}
-
-fn failed_turn_agent(provider: Arc<dyn ChatModel<()>>) -> Agent {
- make_agent_with_builder(
- provider,
- vec![Box::new(EchoTool)],
- vec![],
- crate::config::AgentConfig {
- max_tool_iterations: 5,
- ..crate::config::AgentConfig::default()
- },
- crate::config::ContextConfig::default(),
- )
-}
-
-fn tool_call_rounds(agent: &Agent) -> usize {
- agent
- .history
- .iter()
- .filter(|message| matches!(message, ConversationMessage::AssistantToolCalls { .. }))
- .count()
-}
-
-/// #6281: a turn that fails after doing work keeps the rounds the provider
-/// accepted plus the failure cause, persists them, and the next turn sees them.
-#[tokio::test]
-async fn failed_turn_keeps_its_work_and_cause_for_the_next_turn() {
- let provider_impl = Arc::new(SequenceProvider {
- responses: AsyncMutex::new(vec![
- // Call 1 answered: round 1 runs.
- echo_tool_call(),
- // Call 2 answered (its request carried round 1): round 2 runs.
- echo_tool_call(),
- // Call 3 fails; only its request carried round 2. A 400 is not
- // retried by the harness, so the turn fails on this one response.
- Err(anyhow::anyhow!("400 Bad Request: provider boom")),
- // The follow-up turn.
- Ok(ChatResponse {
- text: Some("The last turn hit a provider error.".into()),
- tool_calls: vec![],
- usage: None,
- reasoning_content: None,
- }),
- ]),
- requests: AsyncMutex::new(Vec::new()),
- tool_counts: AsyncMutex::new(Vec::new()),
- });
- let mut agent = failed_turn_agent(provider_impl.clone());
-
- let err = agent
- .turn("run the task")
- .await
- .expect_err("the third model call fails the turn");
- assert!(err.to_string().contains("provider boom"), "got: {err}");
-
- // Round 1 was in a request the provider answered, so it is replayed as
- // structured messages. Round 2 was only in the failing request, so it must
- // not be (a rejected request must never be replayed), and lives in the note.
- assert_eq!(
- tool_call_rounds(&agent),
- 1,
- "only the accepted round is kept as structured tool calls: {:?}",
- agent.history
- );
- assert!(agent
- .history
- .iter()
- .any(|message| matches!(message, ConversationMessage::ToolResults(results) if !results.is_empty())));
- let note = match agent.history.last() {
- Some(ConversationMessage::Chat(chat)) if chat.role == "assistant" => chat.content.clone(),
- other => panic!("a failed turn must end history on its failure note, got: {other:?}"),
- };
- assert!(
- note.starts_with("[turn failed before completion:") && note.contains("provider boom"),
- "the note must carry the failure cause, got: {note}"
- );
- assert!(
- note.contains("called `echo`"),
- "the unanswered round must be kept as text, got: {note}"
- );
-
- let path = agent
- .session_transcript_path
- .clone()
- .expect("a failed turn must persist its transcript");
- let persisted = transcript::read_transcript(&path).expect("read transcript");
- assert!(
- persisted
- .messages
- .iter()
- .any(|message| message.role == "assistant" && message.content.contains("provider boom")),
- "the persisted transcript must carry the failure note"
- );
- // Both answered calls reported usage before the failure; the failed turn
- // records it rather than zeros.
- assert_eq!(
- (persisted.meta.input_tokens, persisted.meta.output_tokens),
- (200, 14),
- "the failed turn must record the usage of its answered calls"
- );
-
- agent
- .turn("what happened?")
- .await
- .expect("the follow-up turn succeeds");
- let requests = provider_impl.requests.lock().await;
- let follow_up = requests.last().expect("follow-up request");
- assert!(
- follow_up
- .iter()
- .any(|message| message.content.starts_with("[Tool results]")),
- "the follow-up request must carry the failed turn's tool result: {follow_up:?}"
- );
- assert!(
- follow_up
- .iter()
- .any(|message| message.role == "assistant" && message.content.contains("provider boom")),
- "the follow-up request must carry the failure cause: {follow_up:?}"
- );
-}
-
-/// #6281: a turn that fails on its first model call still records why, so the
-/// history never holds two user messages in a row with no explanation between.
-#[tokio::test]
-async fn turn_failing_on_first_call_records_the_cause() {
- let provider: Arc<dyn ChatModel<()>> = Arc::new(SequenceProvider {
- responses: AsyncMutex::new(vec![Err(anyhow::anyhow!("400 Bad Request: provider boom"))]),
- requests: AsyncMutex::new(Vec::new()),
- tool_counts: AsyncMutex::new(Vec::new()),
- });
- let mut agent = failed_turn_agent(provider);
-
- agent
- .turn("run the task")
- .await
- .expect_err("the first model call fails the turn");
-
- assert_eq!(tool_call_rounds(&agent), 0);
- let tail: Vec<(String, String)> = agent
- .history
- .iter()
- .rev()
- .take(2)
- .map(|message| match message {
- ConversationMessage::Chat(chat) => (chat.role.clone(), chat.content.clone()),
- other => panic!("unexpected history entry: {other:?}"),
- })
- .collect();
- assert_eq!(tail[1].0, "user");
- assert_eq!(tail[0].0, "assistant");
- assert!(tail[0].1.contains("provider boom"), "got: {}", tail[0].1);
- assert!(agent.session_transcript_path.is_some());
-}
-
-/// #6281 review: an error in the tool stage, after a model response and before
-/// the next model request, still records that response's tool calls.
-#[tokio::test]
-async fn tool_stage_failure_keeps_the_latest_response() {
- // One response asking for more tool calls than the turn's tool-call cap
- // (eight per allowed model call): admission of the call past the cap fails
- // the run in the tool stage, before any further model request.
- let calls: String = (0..9)
- .map(|n| {
- format!("<tool_call>{{\"name\":\"echo\",\"arguments\":{{\"n\":{n}}}}}</tool_call>")
- })
- .collect();
- let provider: Arc<dyn ChatModel<()>> = Arc::new(SequenceProvider {
- responses: AsyncMutex::new(vec![Ok(ChatResponse {
- text: Some(calls),
- tool_calls: vec![],
- usage: None,
- reasoning_content: None,
- })]),
- requests: AsyncMutex::new(Vec::new()),
- tool_counts: AsyncMutex::new(Vec::new()),
- });
- let mut agent = make_agent_with_builder(
- provider,
- vec![Box::new(EchoTool)],
- vec![],
- crate::config::AgentConfig {
- max_tool_iterations: 1,
- ..crate::config::AgentConfig::default()
- },
- crate::config::ContextConfig::default(),
- );
-
- let err = agent
- .turn("run the task")
- .await
- .expect_err("the call past the tool-call cap fails the turn");
-
- let note = match agent.history.last() {
- Some(ConversationMessage::Chat(chat)) if chat.role == "assistant" => chat.content.clone(),
- other => panic!("a failed turn must end history on its failure note, got: {other:?}"),
- };
- assert!(
- note.contains("called `echo`"),
- "the response the tool stage failed on must be kept as text ({err}), got: {note}"
- );
- assert_eq!(
- tool_call_rounds(&agent),
- 0,
- "a response no provider has seen again is never replayed as structured tool calls"
- );
-}
diff --git a/crates/openhuman-core/src/agent/harness/session/turn_final_reply_grounding_tests.rs b/crates/openhuman-core/src/agent/harness/session/turn_final_reply_grounding_tests.rs
deleted file mode 100644
index 10f5ca5527..0000000000
--- a/crates/openhuman-core/src/agent/harness/session/turn_final_reply_grounding_tests.rs
+++ /dev/null
@@ -1,300 +0,0 @@
-//! Issues #6278 and #6279: a turn with no usable reply of its own is closed from
-//! its tool records, and the closing message is checked before it is shown.
-
-use super::*;
-use crate::agent::progress::AgentProgress;
-
-/// What the failing tool returns. It carries a link on purpose: these defects
-/// dropped exactly this kind of user-actionable detail.
-const INSTALL_FAILURE: &str = "item 'demo' has no direct download, so it can't be installed \
- automatically. View it at https://example.test/demo";
-
-const INSTALL_CALL: &str = "<tool_call>{\"name\":\"install_item\",\"arguments\":{}}</tool_call>";
-
-struct FailingInstallTool;
-
-#[async_trait]
-impl Tool for FailingInstallTool {
- fn name(&self) -> &str {
- "install_item"
- }
-
- fn description(&self) -> &str {
- "install an item"
- }
-
- fn parameters_schema(&self) -> serde_json::Value {
- serde_json::json!({"type":"object"})
- }
-
- async fn execute(&self, _args: serde_json::Value) -> Result<ToolResult> {
- Ok(ToolResult::error(INSTALL_FAILURE))
- }
-}
-
-/// Succeeds on its first call and fails on every later one, so each tool round's
-/// record is distinguishable from the others.
-struct TwoRoundInstallTool {
- calls: AtomicUsize,
-}
-
-#[async_trait]
-impl Tool for TwoRoundInstallTool {
- fn name(&self) -> &str {
- "install_item"
- }
-
- fn description(&self) -> &str {
- "install an item"
- }
-
- fn parameters_schema(&self) -> serde_json::Value {
- serde_json::json!({"type":"object"})
- }
-
- async fn execute(&self, _args: serde_json::Value) -> Result<ToolResult> {
- if self.calls.fetch_add(1, Ordering::SeqCst) == 0 {
- Ok(ToolResult::success(
- "round one: found the demo item in the catalog",
- ))
- } else {
- Ok(ToolResult::error(INSTALL_FAILURE))
- }
- }
-}
-
-fn respond(text: &str) -> anyhow::Result<ChatResponse> {
- Ok(ChatResponse {
- text: Some(text.into()),
- ..ChatResponse::default()
- })
-}
-
-fn scripted(responses: Vec<anyhow::Result<ChatResponse>>) -> Arc<SequenceProvider> {
- Arc::new(SequenceProvider {
- responses: AsyncMutex::new(responses),
- requests: AsyncMutex::new(Vec::new()),
- tool_counts: AsyncMutex::new(Vec::new()),
- })
-}
-
-/// Run one turn against `provider`, returning the reply and everything streamed.
-async fn run_turn(
- provider: Arc<SequenceProvider>,
- tools: Vec<Box<dyn Tool>>,
-) -> (Agent, String, String) {
- let mut agent = make_agent_with_builder(
- provider,
- tools,
- vec![],
- crate::config::AgentConfig {
- max_tool_iterations: 8,
- ..crate::config::AgentConfig::default()
- },
- crate::config::ContextConfig::default(),
- );
- let (progress_tx, mut progress_rx) = tokio::sync::mpsc::channel(256);
- agent.set_on_progress(Some(progress_tx));
- let reply = agent
- .turn("install the demo item")
- .await
- .expect("the turn should close with a reply, not error");
- agent.set_on_progress(None);
- let mut streamed = String::new();
- while let Ok(progress) = progress_rx.try_recv() {
- if let AgentProgress::TextDelta { delta, .. } = progress {
- streamed.push_str(&delta);
- }
- }
- (agent, reply, streamed)
-}
-
-fn history_ends_on(agent: &Agent, reply: &str) -> bool {
- matches!(
- agent.history.last(),
- Some(ConversationMessage::Chat(msg)) if msg.role == "assistant" && msg.content == reply
- )
-}
-
-#[tokio::test]
-async fn an_intent_only_close_is_rejected_and_replaced_by_the_tool_records() {
- const NARRATION: &str = "I'll search the registry for the demo item.";
- let recorded = scripted(vec![
- respond(INSTALL_CALL),
- // The silent end: tool work done, no final text (#4093).
- respond(""),
- // The wrap-up narrates intent instead of reporting the outcome.
- respond(NARRATION),
- // The check rejects it.
- respond("REJECT"),
- ]);
-
- let (agent, reply, streamed) =
- run_turn(recorded.clone(), vec![Box::new(FailingInstallTool)]).await;
-
- assert!(
- !reply.contains(NARRATION),
- "a close the check rejected must not be the reply, got: {reply}"
- );
- assert!(
- reply.contains("View it at https://example.test/demo"),
- "the fallback must carry the failing tool's own message, got: {reply}"
- );
- assert!(
- !streamed.contains(NARRATION),
- "a rejected close must never be streamed, got: {streamed}"
- );
- assert!(
- history_ends_on(&agent, &reply),
- "history must end on the reply the user saw, got: {:?}",
- agent.history.last()
- );
-
- let requests = recorded.requests.lock().await;
- assert_eq!(requests.len(), 4, "tool round, silent end, wrap-up, check");
- let wrap_up = &requests[2].last().expect("wrap-up instruction").content;
- assert!(
- wrap_up.contains("<tool_records>") && wrap_up.contains(INSTALL_FAILURE),
- "the wrap-up must be grounded in this turn's tool records, got: {wrap_up}"
- );
- assert_eq!(
- requests[3].len(),
- 1,
- "the check must see only its own prompt, not the conversation"
- );
- assert!(
- requests[3][0].content.contains(NARRATION)
- && requests[3][0].content.contains(INSTALL_FAILURE),
- "the check must be given the candidate and the records, got: {}",
- requests[3][0].content
- );
-}
-
-/// A check that fails or answers without a verdict leaves the close unverified,
-/// and unverified closing text must not ship (CodeRabbit on #6289).
-#[tokio::test]
-async fn an_unverified_close_is_replaced_by_the_tool_records() {
- const CANDIDATE: &str = "The demo item is installed.";
- let recorded = scripted(vec![
- respond(INSTALL_CALL),
- respond(""),
- respond(CANDIDATE),
- // No ACCEPT/REJECT verdict.
- respond("I am not sure."),
- ]);
-
- let (agent, reply, streamed) = run_turn(recorded, vec![Box::new(FailingInstallTool)]).await;
-
- assert!(
- !reply.contains(CANDIDATE),
- "a close the check could not verify must not be the reply, got: {reply}"
- );
- assert!(
- reply.contains("View it at https://example.test/demo"),
- "the fallback must carry the failing tool's own message, got: {reply}"
- );
- assert!(
- !streamed.contains(CANDIDATE),
- "an unverified close must never be streamed, got: {streamed}"
- );
- assert!(history_ends_on(&agent, &reply));
-}
-
-#[tokio::test]
-async fn an_accepted_close_is_streamed_and_kept() {
- const CLOSE: &str = "I could not install the demo item: it has no direct download. \
- You can view it at https://example.test/demo.";
- let recorded = scripted(vec![
- respond(INSTALL_CALL),
- respond(""),
- respond(CLOSE),
- respond("ACCEPT"),
- ]);
-
- let (agent, reply, streamed) = run_turn(recorded, vec![Box::new(FailingInstallTool)]).await;
-
- assert_eq!(reply, CLOSE, "an accepted close is the reply");
- assert!(
- streamed.contains(CLOSE),
- "an accepted close must be streamed once the check passes, got: {streamed}"
- );
- assert!(history_ends_on(&agent, &reply));
-}
-
-#[tokio::test]
-async fn a_breaker_halt_is_closed_for_the_user_instead_of_showing_the_stop_note() {
- const CLOSE: &str = "I could not install the demo item: it has no direct download. \
- You can view it at https://example.test/demo.";
- let recorded = scripted(vec![
- // The same failing call three times trips the identical-retry breaker.
- respond(INSTALL_CALL),
- respond(INSTALL_CALL),
- respond(INSTALL_CALL),
- // Wrap-up, then its check.
- respond(CLOSE),
- respond("ACCEPT"),
- ]);
-
- let (agent, reply, _) = run_turn(recorded.clone(), vec![Box::new(FailingInstallTool)]).await;
-
- assert!(
- !reply.contains("instead of retrying") && !reply.starts_with("Stopping:"),
- "the breaker's model-directed stop note must not be the user's reply, got: {reply}"
- );
- assert_eq!(reply, CLOSE, "the checked close is the reply");
- assert!(
- history_ends_on(&agent, &reply),
- "a halted turn's reply must be recorded in history, got: {:?}",
- agent.history.last()
- );
-
- let requests = recorded.requests.lock().await;
- assert_eq!(
- requests.len(),
- 5,
- "three tool rounds, the wrap-up and the check; the halted loop makes no further call"
- );
- let wrap_up = &requests[3].last().expect("wrap-up instruction").content;
- assert!(
- wrap_up.contains("<stop_note>") && wrap_up.contains(INSTALL_FAILURE),
- "the wrap-up must receive the stop note and the records as input, got: {wrap_up}"
- );
-}
-
-/// XML-dialect calls carry no provider id, so both rounds' calls are `call_0`.
-/// Each round must still be recorded with its own result: the second round's
-/// failure is why the request was not done, and a first-match lookup replaced it
-/// with the first round's success (Codex review on #6289).
-#[tokio::test]
-async fn each_tool_round_is_recorded_with_its_own_result() {
- let recorded = scripted(vec![
- respond(INSTALL_CALL),
- respond(INSTALL_CALL),
- respond(""),
- respond("I'll look into the demo item."),
- respond("REJECT"),
- ]);
-
- let (_, reply, _) = run_turn(
- recorded.clone(),
- vec![Box::new(TwoRoundInstallTool {
- calls: AtomicUsize::new(0),
- })],
- )
- .await;
-
- assert!(
- reply.contains("round one: found the demo item in the catalog"),
- "the first round keeps its own result, got: {reply}"
- );
- assert!(
- reply.contains("View it at https://example.test/demo"),
- "the second round must be recorded with its own failure, not the first round's result, got: {reply}"
- );
- let requests = recorded.requests.lock().await;
- let wrap_up = &requests[3].last().expect("wrap-up instruction").content;
- assert!(
- wrap_up.contains(INSTALL_FAILURE),
- "the wrap-up records must carry the second round's failure, got: {wrap_up}"
- );
-}
diff --git a/crates/openhuman-core/src/agent/harness/session/turn_history_and_context_tests.rs b/crates/openhuman-core/src/agent/harness/session/turn_history_and_context_tests.rs
deleted file mode 100644
index 1e9337105f..0000000000
--- a/crates/openhuman-core/src/agent/harness/session/turn_history_and_context_tests.rs
+++ /dev/null
@@ -1,522 +0,0 @@
-use super::*;
-use tinyagents_session::transcript;
-
-#[test]
-fn trim_history_preserves_system_and_keeps_latest_non_system_entries() {
- let mut agent = make_agent(None);
- agent.history = vec![
- ConversationMessage::Chat(ChatMessage::system("sys")),
- ConversationMessage::Chat(ChatMessage::user("u1")),
- ConversationMessage::Chat(ChatMessage::assistant("a1")),
- ConversationMessage::Chat(ChatMessage::user("u2")),
- ConversationMessage::Chat(ChatMessage::assistant("a2")),
- ];
-
- agent.trim_history();
-
- assert_eq!(agent.history.len(), 4);
- assert!(matches!(&agent.history[0], ConversationMessage::Chat(msg) if msg.role == "system"));
- assert!(agent
- .history
- .iter()
- .all(|msg| !matches!(msg, ConversationMessage::Chat(chat) if chat.content == "u1")));
- assert!(agent
- .history
- .iter()
- .any(|msg| matches!(msg, ConversationMessage::Chat(chat) if chat.content == "a2")));
-}
-
-/// When the `max_history_messages` cap drops an `AssistantToolCalls` opener but
-/// keeps its `ToolResults`, the window would otherwise open on an orphaned tool
-/// result — serialized, a `tool` message with no preceding `tool_calls`, which
-/// the provider rejects (the 400 that surfaces as "Something went wrong").
-/// `trim_history` must snap past the orphan so the window starts on a clean turn.
-#[test]
-fn trim_history_snaps_past_orphaned_tool_results() {
- use crate::agent::messages::ToolResultMessage;
- use crate::inference::provider::ToolCall;
-
- let mut agent = make_agent(None); // max_history_messages = 3
- agent.history = vec![
- ConversationMessage::Chat(ChatMessage::system("sys")),
- // This opener is the oldest non-system entry, so the cap drops it...
- ConversationMessage::AssistantToolCalls {
- text: Some("calling".into()),
- tool_calls: vec![ToolCall {
- id: "call_x".into(),
- name: "shell".into(),
- arguments: "{}".into(),
- extra_content: None,
- }],
- reasoning_content: None,
- extra_metadata: None,
- },
- // ...orphaning this result at the head of the kept window.
- ConversationMessage::ToolResults(vec![ToolResultMessage {
- tool_call_id: "call_x".into(),
- content: "result".into(),
- }]),
- ConversationMessage::Chat(ChatMessage::user("u2")),
- ConversationMessage::Chat(ChatMessage::assistant("a2")),
- ];
-
- agent.trim_history();
-
- assert!(
- !agent
- .history
- .iter()
- .any(|m| matches!(m, ConversationMessage::ToolResults(_))),
- "orphaned ToolResults must be dropped, not left at the window head"
- );
- assert!(
- matches!(agent.history.first(), Some(ConversationMessage::Chat(c)) if c.role == "system"),
- "system message is preserved"
- );
- // system + u2 + a2 (the bisected cycle is gone entirely).
- assert_eq!(agent.history.len(), 3);
-}
-
-#[tokio::test]
-async fn build_parent_context_and_sanitize_helpers_cover_snapshot_paths() {
- let mut agent = make_agent(None);
- agent.last_memory_context = Some("remember this".into());
- agent.workflows = vec![crate::skills::Workflow {
- name: "demo".into(),
- ..Default::default()
- }];
-
- let parent = agent.build_parent_execution_context();
- assert_eq!(parent.model_name, agent.model_name);
- assert_eq!(parent.temperature, agent.temperature);
- assert_eq!(parent.memory_context.as_deref(), Some("remember this"));
- assert_eq!(parent.session_id, "turn-test-session");
- assert_eq!(parent.channel, "turn-test-channel");
- assert_eq!(parent.workflows.len(), 1);
-
- assert_eq!(sanitize_learned_entry(" "), "");
- assert_eq!(
- sanitize_learned_entry("Bearer abcdef"),
- "[redacted: potential secret]"
- );
- let long = "x".repeat(500);
- assert_eq!(sanitize_learned_entry(&long).chars().count(), 200);
- // A profile subtree that was never written. Named rather than `"memory"`
- // because the shared subtree is the driver's now (#5560), and what this
- // line is here to cover is the host-local scan's empty answer.
- assert!(collect_tree_root_summaries(8_000, 32_000).await.is_empty());
-}
-
-#[test]
-fn build_parent_context_propagates_own_descriptor_on_root_turn() {
- // Regression (PR #5118 review, Codex): on a ROOT chat turn `current_parent()`
- // is `None`, so the parent snapshot must fall back to the agent's OWN
- // descriptor. Without it, a dedicated-workspace profile's descriptor never
- // reaches subagents spawned via spawn_subagent/spawn_async_subagent, and they
- // silently fall back to the shared action_dir instead of
- // `<action_dir>/profiles/<id>`.
- let descriptor =
- tinytools::WorkspaceDescriptor::new(std::path::PathBuf::from("/tmp/act/profiles/alice"))
- .with_policy_id("openhuman.profile:alice");
-
- let mut agent = make_agent(None);
- // No ambient parent context is installed in this test, so current_parent()
- // is None — exactly the root-turn scenario.
- agent.workspace_descriptor = Some(descriptor);
-
- let parent = agent.build_parent_execution_context();
- assert_eq!(
- parent.workspace_descriptor.as_ref().map(|d| d.root.clone()),
- Some(std::path::PathBuf::from("/tmp/act/profiles/alice")),
- "root turn must propagate the agent's own profile descriptor to spawned subagents"
- );
- assert_eq!(
- parent
- .workspace_descriptor
- .as_ref()
- .map(|d| d.policy_id.clone()),
- Some("openhuman.profile:alice".to_string()),
- );
-}
-
-#[test]
-fn build_parent_context_has_no_descriptor_without_profile_or_parent() {
- // A profile-less root turn (no ambient parent, no own descriptor) keeps the
- // snapshot's descriptor `None` so shared-action_dir behaviour is unchanged.
- let agent = make_agent(None);
- let parent = agent.build_parent_execution_context();
- assert!(parent.workspace_descriptor.is_none());
-}
-
-/// Stands in for a synthesised `delegate_*` tool in the parent's own surface.
-struct ProbeDelegateTool;
-
-#[async_trait]
-impl Tool for ProbeDelegateTool {
- /// A `delegate_*` name, like every synthesised delegation tool.
- fn name(&self) -> &str {
- "delegate_probe"
- }
-
- /// Marker text only; the description is never asserted on.
- fn description(&self) -> &str {
- "probe delegate"
- }
-
- /// An empty object schema, like a parameterless delegate.
- fn parameters_schema(&self) -> serde_json::Value {
- serde_json::json!({"type": "object"})
- }
-
- /// Never dispatched by these tests.
- async fn execute(&self, _args: serde_json::Value) -> Result<ToolResult> {
- Ok(ToolResult::success("probe"))
- }
-}
-
-/// What a child is handed: the durable registry and its specs, index for
-/// index — never the parent's synthesised delegation specs, which have no
-/// instance in `all_tools` and which a sub-agent must not see (#4452).
-#[test]
-fn build_parent_context_passes_durable_specs_matching_all_tools() {
- let agent = make_agent_with_tool_sets(
- vec![Box::new(EchoTool), Box::new(CronAddProbeTool)],
- vec![Box::new(ProbeDelegateTool)],
- None,
- );
- assert!(
- agent
- .tool_specs()
- .iter()
- .any(|spec| spec.name == "delegate_probe"),
- "sanity: the parent itself advertises the synthesised delegate"
- );
-
- let parent = agent.build_parent_execution_context();
- assert_eq!(parent.all_tool_specs.len(), parent.all_tools.len());
- for (tool, spec) in parent.all_tools.iter().zip(parent.all_tool_specs.iter()) {
- assert_eq!(
- tool.name(),
- spec.name,
- "a child's specs must track its tools index for index"
- );
- }
- assert!(
- !parent
- .all_tool_specs
- .iter()
- .any(|spec| spec.name == "delegate_probe"),
- "a synthesised delegate spec must never reach a child"
- );
-}
-
-#[tokio::test]
-async fn transcript_roundtrip_work() {
- let mut agent = make_agent(None);
-
- let messages = vec![
- ChatMessage::system("sys"),
- ChatMessage::user("hello"),
- ChatMessage::assistant("done"),
- ];
- agent.persist_session_transcript(&messages, 10, 5, 3, 0.25, None);
- assert!(agent.session_transcript_path.is_some());
-
- let loaded = transcript::read_transcript(agent.session_transcript_path.as_ref().unwrap())
- .expect("transcript should be readable");
- assert_eq!(loaded.messages.len(), 3);
- assert_eq!(loaded.meta.input_tokens, 10);
-
- let mut resumed = make_agent(None);
- resumed.workspace_dir = agent.workspace_dir.clone();
- resumed.agent_definition_name = agent.agent_definition_name.clone();
- resumed.try_load_session_transcript();
- assert_eq!(
- resumed.cached_transcript_messages.as_ref().map(|m| m.len()),
- Some(3)
- );
-}
-
-#[tokio::test]
-async fn transcript_resume_is_bounded_by_max_history_messages() {
- let mut writer = make_agent(None);
- let mut messages = vec![ChatMessage::system("sys")];
- for idx in 0..8 {
- messages.push(ChatMessage::user(format!("u{idx}")));
- messages.push(ChatMessage::assistant(format!("a{idx}")));
- }
- writer.persist_session_transcript(&messages, 0, 0, 0, 0.0, None);
-
- let mut resumed = make_agent(None);
- resumed.workspace_dir = writer.workspace_dir.clone();
- resumed.agent_definition_name = writer.agent_definition_name.clone();
- resumed.config.max_history_messages = 5;
- resumed.try_load_session_transcript();
-
- let cached = resumed
- .cached_transcript_messages
- .as_ref()
- .expect("resume cache should be populated");
- assert_eq!(cached.len(), 5);
- assert_eq!(cached[0].role, "system");
- assert_eq!(cached[1].content, "u6");
- assert_eq!(cached[2].content, "a6");
- assert_eq!(cached[3].content, "u7");
- assert_eq!(cached[4].content, "a7");
-}
-
-#[test]
-fn set_agent_definition_name_refreshes_tool_policy_identity() {
- let provider: Arc<dyn ChatModel<()>> = Arc::new(DummyProvider);
- let mut config = crate::config::AgentConfig::default();
- config
- .channel_permissions
- .insert("turn-test-channel".into(), "read_only".into());
- let mut agent = make_agent_with_builder(
- provider,
- vec![
- Box::new(EchoTool),
- Box::new(CountingWriteTool {
- calls: Arc::new(AtomicUsize::new(0)),
- }),
- ],
- vec![],
- config,
- crate::config::ContextConfig::default(),
- );
-
- agent.set_agent_definition_name("renamed_agent");
-
- assert_eq!(agent.tool_policy_session.profile.agent_id, "renamed_agent");
- let prompt = agent
- .build_system_prompt(LearnedContextData::default())
- .expect("prompt");
- assert!(prompt.contains("Agent: renamed_agent"));
-}
-
-// Removed: execute_tool_call_denies_by_policy_before_tool_runs and
-// execute_tool_call_threads_generated_tool_context_into_policy — see the note
-// above; they exercised the deleted direct tool executor.
-
-#[tokio::test]
-async fn turn_runs_full_tool_cycle_with_context_and_hooks() {
- let provider_impl = Arc::new(SequenceProvider {
- responses: AsyncMutex::new(vec![
- Ok(ChatResponse {
- text: Some(
- "preface <tool_call>{\"name\":\"echo\",\"arguments\":{\"value\":1}}</tool_call>"
- .into(),
- ),
- tool_calls: vec![],
- usage: None,
- reasoning_content: None,
- }),
- Ok(ChatResponse {
- text: Some("final answer".into()),
- tool_calls: vec![],
- usage: None,
- reasoning_content: None,
- }),
- ]),
- requests: AsyncMutex::new(Vec::new()),
- tool_counts: AsyncMutex::new(Vec::new()),
- });
- let provider: Arc<dyn ChatModel<()>> = provider_impl.clone();
- let hook_calls = Arc::new(AsyncMutex::new(Vec::<TurnContext>::new()));
- let hook_notify = Arc::new(Notify::new());
- let hooks: Vec<Arc<dyn PostTurnHook>> = vec![Arc::new(RecordingHook {
- calls: Arc::clone(&hook_calls),
- notify: Arc::clone(&hook_notify),
- })];
-
- let mut agent = make_agent_with_builder(
- provider,
- vec![Box::new(EchoTool)],
- hooks,
- crate::config::AgentConfig {
- max_tool_iterations: 3,
- max_history_messages: 10,
- ..crate::config::AgentConfig::default()
- },
- crate::config::ContextConfig::default(),
- );
-
- let response = agent
- .turn("hello world")
- .await
- .expect("turn should succeed");
- assert_eq!(response, "final answer");
- assert!(agent.history.iter().any(|message| matches!(
- message,
- ConversationMessage::AssistantToolCalls {
- text, tool_calls, ..
- }
- if text.as_deref().is_some_and(|value| value.contains("preface")) && tool_calls.len() == 1
- )));
- assert!(agent.history.iter().any(|message| matches!(
- message,
- ConversationMessage::Chat(chat) if chat.role == "assistant" && chat.content == "final answer"
- )));
-
- timeout(Duration::from_secs(1), async {
- loop {
- if !hook_calls.lock().await.is_empty() {
- break;
- }
- hook_notify.notified().await;
- }
- })
- .await
- .expect("hook should fire");
-
- let recorded_hooks = hook_calls.lock().await;
- assert_eq!(recorded_hooks.len(), 1);
- assert_eq!(recorded_hooks[0].assistant_response, "final answer");
- assert_eq!(recorded_hooks[0].iteration_count, 2);
- assert_eq!(recorded_hooks[0].tool_calls.len(), 1);
- assert_eq!(recorded_hooks[0].tool_calls[0].name, "echo");
- drop(recorded_hooks);
-
- let requests = provider_impl.requests.lock().await;
- assert_eq!(requests.len(), 2);
- assert_eq!(requests[0][0].role, "system");
- assert!(requests[0][1].content.contains("hello world"));
- assert!(requests[1]
- .iter()
- .any(|msg| msg.role == "assistant" && msg.content.contains("preface")));
- assert!(requests[1]
- .iter()
- .any(|msg| msg.role == "user" && msg.content.contains("[Tool results]")));
-}
-
-#[tokio::test]
-async fn turn_triggers_configured_memory_agent_before_parent_prompt() {
- // The embedding seam fails loudly when unwired; before the memory
- // extraction this was a direct call and needed no setup.
- crate::agent::harness::definition::AgentDefinitionRegistry::init_global_builtins()
- .expect("built-in agent definitions should load");
- assert!(
- crate::agent::harness::definition::AgentDefinitionRegistry::global()
- .and_then(|registry| registry.get("agent_memory"))
- .is_some()
- );
-
- let provider_impl = Arc::new(SequenceProvider {
- responses: AsyncMutex::new(vec![
- Ok(ChatResponse {
- text: Some("memory context: user prefers concise Rust changes".into()),
- tool_calls: vec![],
- usage: None,
- reasoning_content: None,
- }),
- Ok(ChatResponse {
- text: Some("parent final".into()),
- tool_calls: vec![],
- usage: None,
- reasoning_content: None,
- }),
- ]),
- requests: AsyncMutex::new(Vec::new()),
- tool_counts: AsyncMutex::new(Vec::new()),
- });
- let provider: Arc<dyn ChatModel<()>> = provider_impl.clone();
- let workspace = tempfile::TempDir::new().expect("temp workspace");
- let workspace_path = workspace.path().to_path_buf();
- // The triggered memory agent runs through `run_subagent`, whose
- // deterministic fast path loads the host config and queries whatever memory
- // tree it points at. Keep that inside this test's scratch workspace so the
- // fast path finds nothing and the model-driven walk (the two-call sequence
- // asserted below) is what actually runs.
- let _workspace_env = WorkspaceEnvGuard::set(&workspace_path);
- let _memory_cfg = crate::config::MemoryConfig {
- backend: "none".into(),
- ..crate::config::MemoryConfig::default()
- };
- // The embedding seam, as above.
- let mem: Arc<dyn Memory> = crate::memory::test_support::noop_memory();
-
- let mut agent = Agent::builder()
- .chat_model(provider)
- .tools(vec![Box::new(EchoTool)])
- .memory(mem)
- .tool_dispatcher(Box::new(XmlDialect))
- .config(crate::config::AgentConfig {
- max_tool_iterations: 3,
- max_history_messages: 10,
- ..crate::config::AgentConfig::default()
- })
- .workspace_dir(workspace_path)
- .auto_save(false)
- .event_context("turn-test-session", "turn-test-channel")
- .trigger_memory_agent(crate::agent::harness::definition::TriggerMemoryAgent::Always)
- .build()
- .unwrap();
- assert_eq!(
- agent.trigger_memory_agent,
- crate::agent::harness::definition::TriggerMemoryAgent::Always
- );
-
- let response = agent
- .turn("Implement the memory trigger.")
- .await
- .expect("turn should succeed");
- assert_eq!(response, "parent final");
-
- let requests = provider_impl.requests.lock().await;
- assert_eq!(requests.len(), 2);
- assert!(requests[0].iter().any(|msg| {
- msg.role == "user" && msg.content.contains("Implement the memory trigger.")
- }));
- assert!(requests[1].iter().any(|msg| {
- msg.role == "user"
- && msg.content.contains("## Memory agent context")
- && msg
- .content
- .contains("memory context: user prefers concise Rust changes")
- && msg.content.contains("Implement the memory trigger.")
- }));
-}
-
-/// #1725: a per-turn `suppress_tools` override sends an EMPTY tool schema to the
-/// provider, so a chat / small-talk turn cannot enter the tool loop — even
-/// though the agent was built WITH a tool. The default (no override) path still
-/// offers the tool, proving the suppression is per-turn and not a rebuild.
-#[tokio::test]
-async fn turn_override_suppress_tools_sends_empty_tool_schema() {
- let provider_impl = Arc::new(SequenceProvider {
- responses: AsyncMutex::new(vec![Ok(ChatResponse {
- text: Some("hi there".into()),
- tool_calls: vec![],
- usage: None,
- reasoning_content: None,
- })]),
- requests: AsyncMutex::new(Vec::new()),
- tool_counts: AsyncMutex::new(Vec::new()),
- });
- let provider: Arc<dyn ChatModel<()>> = provider_impl.clone();
- let mut agent = make_agent_with_builder(
- provider,
- vec![Box::new(EchoTool)],
- Vec::new(),
- crate::config::AgentConfig {
- max_tool_iterations: 3,
- max_history_messages: 10,
- ..crate::config::AgentConfig::default()
- },
- crate::config::ContextConfig::default(),
- );
-
- agent.set_next_turn_overrides(crate::agent::harness::session::TurnOverrides {
- suppress_tools: true,
- ..Default::default()
- });
- let response = agent.turn("hey").await.expect("turn should succeed");
- assert_eq!(response, "hi there");
-
- let counts = provider_impl.tool_counts.lock().await;
- assert_eq!(counts.len(), 1, "small-talk turn is a single provider call");
- assert_eq!(
- counts[0], 0,
- "suppress_tools must send an empty tool schema (no tool loop possible)"
- );
-}
diff --git a/crates/openhuman-core/src/agent/harness/session/turn_learned_context_and_announcements_tests.rs b/crates/openhuman-core/src/agent/harness/session/turn_learned_context_and_announcements_tests.rs
deleted file mode 100644
index a9ad695209..0000000000
--- a/crates/openhuman-core/src/agent/harness/session/turn_learned_context_and_announcements_tests.rs
+++ /dev/null
@@ -1,609 +0,0 @@
-use super::*;
-
-#[tokio::test]
-async fn fetch_learned_context_returns_general_prefs_when_explicit_flag_on_learning_off() {
- let tmp = tempfile::TempDir::new().unwrap();
- let mem = make_real_memory(tmp.path());
-
- // Store two general preferences in the two-lane store (where save_preference
- // writes them). The explicit path now reads `user_pref_general`, not the
- // legacy `user_profile` pinned namespace.
- mem.store(
- crate::memory::preferences::USER_PREF_GENERAL_NAMESPACE,
- "package_manager",
- "Use pnpm for package management.",
- crate::memory::MemoryCategory::Core,
- None,
- )
- .await
- .unwrap();
- mem.store(
- crate::memory::preferences::USER_PREF_GENERAL_NAMESPACE,
- "verbosity",
- "Keep replies terse.",
- crate::memory::MemoryCategory::Core,
- None,
- )
- .await
- .unwrap();
-
- let agent = make_agent_with_memory(
- mem,
- tmp.path().to_path_buf(),
- false, // learning_enabled — full inference stack OFF
- true, // explicit_preferences_enabled — narrow path ON
- );
-
- let learned = agent.fetch_learned_context().await;
-
- assert_eq!(
- learned.user_profile.len(),
- 2,
- "explicit flag on, learning off: expected 2 general preferences, got: {:?}",
- learned.user_profile
- );
- assert!(
- learned.user_profile.iter().any(|s| s.contains("pnpm")),
- "package_manager preference value must appear in user_profile: {:?}",
- learned.user_profile
- );
- assert!(
- learned.user_profile.iter().any(|s| s.contains("terse")),
- "verbosity preference value must appear in user_profile: {:?}",
- learned.user_profile
- );
- // Inference-derived data must remain empty — the stack was NOT engaged.
- assert!(
- learned.observations.is_empty(),
- "observations must be empty when learning_enabled=false"
- );
- assert!(
- learned.patterns.is_empty(),
- "patterns must be empty when learning_enabled=false"
- );
- assert!(
- learned.reflections.is_empty(),
- "reflections must be empty when learning_enabled=false"
- );
-}
-
-#[tokio::test]
-async fn fetch_learned_context_explicit_flag_off_learning_off_returns_empty_even_with_stored_prefs()
-{
- let tmp = tempfile::TempDir::new().unwrap();
- let mem = make_real_memory(tmp.path());
-
- mem.store(
- "user_profile",
- "pinned/style/tone",
- "[pinned] (class=style) tone: formal",
- crate::memory::MemoryCategory::Core,
- None,
- )
- .await
- .unwrap();
-
- let agent = make_agent_with_memory(
- mem,
- tmp.path().to_path_buf(),
- false, // learning_enabled
- false, // explicit_preferences_enabled — both off
- );
-
- let learned = agent.fetch_learned_context().await;
- assert!(
- learned.user_profile.is_empty(),
- "both flags off: user_profile must be empty even when prefs exist, got: {:?}",
- learned.user_profile
- );
-}
-
-#[tokio::test]
-async fn fetch_learned_context_loads_general_prefs_when_learning_enabled() {
- let tmp = tempfile::TempDir::new().unwrap();
- let mem = make_real_memory(tmp.path());
- mem.store(
- crate::memory::preferences::USER_PREF_GENERAL_NAMESPACE,
- "tone",
- "Be concise and direct.",
- crate::memory::MemoryCategory::Core,
- None,
- )
- .await
- .unwrap();
-
- // learning_enabled=true → full path, which now also sources standing prefs
- // from the explicit user_pref_general store (inferred facets are demoted, so
- // they are no longer injected as ground truth).
- let agent = make_agent_with_memory(mem, tmp.path().to_path_buf(), true, true);
- let learned = agent.fetch_learned_context().await;
- assert!(
- learned.user_profile.iter().any(|s| s.contains("concise")),
- "learning path must inject explicit general prefs into user_profile: {:?}",
- learned.user_profile
- );
-}
-
-// ── assistant_message_has_tool_calls — TAURI-RUST-7 envelope check ─────
-
-#[test]
-fn assistant_message_has_tool_calls_detects_native_envelope() {
- let body = serde_json::json!({
- "content": "calling tool",
- "tool_calls": [{
- "id": "tc-1",
- "name": "shell",
- "arguments": "{}"
- }]
- })
- .to_string();
- let msg = ChatMessage::assistant(body);
- assert!(super::super::assistant_message_has_tool_calls(&msg));
-}
-
-#[test]
-fn assistant_message_has_tool_calls_rejects_non_assistant_role() {
- let body = serde_json::json!({
- "content": "x",
- "tool_calls": [{ "id": "tc-1", "name": "shell", "arguments": "{}" }]
- })
- .to_string();
- let msg = ChatMessage::user(body);
- assert!(!super::super::assistant_message_has_tool_calls(&msg));
-}
-
-#[test]
-fn assistant_message_has_tool_calls_rejects_plain_text_reply() {
- // Most common positive case for the previous over-broad check: a plain
- // assistant reply whose text happens to mention `tool_calls`.
- let msg = ChatMessage::assistant("I considered using tool_calls but chose not to.");
- assert!(!super::super::assistant_message_has_tool_calls(&msg));
-}
-
-#[test]
-fn assistant_message_has_tool_calls_rejects_envelope_without_content_field() {
- // A bare `{"tool_calls": [...]}` JSON in the content (no `content` field)
- // is not the envelope the canonical native dialect emits.
- let body = serde_json::json!({
- "tool_calls": [{ "id": "tc-1", "name": "shell", "arguments": "{}" }]
- })
- .to_string();
- let msg = ChatMessage::assistant(body);
- assert!(!super::super::assistant_message_has_tool_calls(&msg));
-}
-
-#[test]
-fn assistant_message_has_tool_calls_rejects_empty_tool_calls_array() {
- let body = serde_json::json!({
- "content": "no tools",
- "tool_calls": []
- })
- .to_string();
- let msg = ChatMessage::assistant(body);
- assert!(!super::super::assistant_message_has_tool_calls(&msg));
-}
-
-#[test]
-fn assistant_message_has_tool_calls_rejects_malformed_tool_call_items() {
- // tool_call object missing `id` — not the native envelope shape.
- let body_no_id = serde_json::json!({
- "content": "x",
- "tool_calls": [{ "name": "shell", "arguments": "{}" }]
- })
- .to_string();
- assert!(!super::super::assistant_message_has_tool_calls(
- &ChatMessage::assistant(body_no_id)
- ));
-
- // tool_call object missing `arguments` — also rejected.
- let body_no_args = serde_json::json!({
- "content": "x",
- "tool_calls": [{ "id": "tc-1", "name": "shell" }]
- })
- .to_string();
- assert!(!super::super::assistant_message_has_tool_calls(
- &ChatMessage::assistant(body_no_args)
- ));
-}
-
-#[test]
-fn assistant_message_has_tool_calls_rejects_non_object_root() {
- // Content is a JSON array, not an object.
- let msg = ChatMessage::assistant(r#"["just", "an", "array"]"#.to_string());
- assert!(!super::super::assistant_message_has_tool_calls(&msg));
-}
-
-#[test]
-fn assistant_message_has_tool_calls_rejects_non_json_content() {
- // Plain prose that doesn't parse as JSON at all — early-returns false via
- // the `let Ok(value) = serde_json::from_str(...)` arm. Keeps the message
- // when the trailing-strip uses this helper.
- let msg = ChatMessage::assistant("Just a normal text reply, no JSON here.");
- assert!(!super::super::assistant_message_has_tool_calls(&msg));
-}
-
-#[test]
-fn bound_cached_transcript_messages_pops_trailing_tool_calls_envelope() {
- let agent = make_agent(None); // max_history_messages = 3
- // Need > max so the bound runs (early-returns when len <= max).
- let messages = vec![
- ChatMessage::system("sys"),
- ChatMessage::user("u1"),
- ChatMessage::assistant("a1"),
- ChatMessage::user("u2"),
- ChatMessage::assistant(tool_calls_envelope("tc-trailing")),
- ];
-
- // With `max_history_messages = 3` and the leading `system` message,
- // `bound_cached_transcript_messages` keeps the last 2 non-system entries
- // — i.e. `[system, u2, trailing-envelope]`. After the envelope pop the
- // tail is `user("u2")`, not the dropped assistant message.
- let bounded = agent.bound_cached_transcript_messages(messages);
- assert!(
- bounded
- .last()
- .is_some_and(|m| m.role == "user" && m.content == "u2"),
- "trailing tool_calls envelope must be popped; expected user tail 'u2' — got tail role={:?} content={:?}",
- bounded.last().map(|m| m.role.as_str()),
- bounded.last().map(|m| m.content.as_str())
- );
- assert!(
- !bounded
- .iter()
- .any(super::super::assistant_message_has_tool_calls),
- "no tool_calls envelope should survive the strip"
- );
-}
-
-#[test]
-fn bound_cached_transcript_messages_leaves_plain_assistant_tail_intact() {
- let agent = make_agent(None); // max_history_messages = 3
- let messages = vec![
- ChatMessage::system("sys"),
- ChatMessage::user("u1"),
- ChatMessage::assistant("a1"),
- ChatMessage::user("u2"),
- ChatMessage::assistant("plain text reply, no tool_calls"),
- ];
-
- let bounded = agent.bound_cached_transcript_messages(messages);
- let tail = bounded.last().expect("bounded transcript is non-empty");
- assert_eq!(tail.role, "assistant");
- assert_eq!(tail.content, "plain text reply, no tool_calls");
-}
-
-#[test]
-fn bound_cached_transcript_messages_strips_multiple_trailing_envelopes() {
- // Defence-in-depth: if the cached transcript ends on multiple consecutive
- // unpaired tool_calls envelopes (e.g. two abortive turns), pop them all.
- let agent = make_agent(None);
- let messages = vec![
- ChatMessage::system("sys"),
- ChatMessage::user("u1"),
- ChatMessage::assistant("a1"),
- ChatMessage::assistant(tool_calls_envelope("tc-1")),
- ChatMessage::assistant(tool_calls_envelope("tc-2")),
- ];
-
- let bounded = agent.bound_cached_transcript_messages(messages);
- let any_envelope = bounded
- .iter()
- .any(super::super::assistant_message_has_tool_calls);
- assert!(
- !any_envelope,
- "all trailing tool_calls envelopes must be stripped"
- );
-}
-
-#[test]
-fn integration_announcement_fires_once_for_new_toolkit() {
- // Seed the announced set with the startup-connected toolkit, mirroring the
- // turn-1 seed in `run_turn`.
- let mut announced: HashSet<String> = HashSet::new();
- announced.insert("gmail".to_string());
-
- // A mid-session connect adds `slack`: it should be announced, and recorded
- // so it never re-announces.
- let connected = vec!["gmail".to_string(), "slack".to_string()];
- let newly = newly_connected_slugs(&connected, &mut announced);
- assert_eq!(newly, vec!["slack".to_string()]);
- let note = integration_announcement_note(&newly)
- .expect("a newly-connected toolkit must produce an announcement");
- assert!(
- note.contains("slack"),
- "announcement must name the new toolkit slug, got: {note}"
- );
- assert!(
- !note.contains("gmail"),
- "already-announced toolkit must not be re-announced, got: {note}"
- );
- assert!(
- announced.contains("slack"),
- "the new slug must be recorded as announced"
- );
-
- // A second refresh with the identical connected set parks nothing — every
- // slug is now in `announced`.
- let second = newly_connected_slugs(&connected, &mut announced);
- assert!(
- second.is_empty(),
- "an unchanged connected set must not re-surface a slug, got: {second:?}"
- );
- assert!(integration_announcement_note(&second).is_none());
-}
-
-#[test]
-fn mcp_announcement_fires_once_for_new_server() {
- // Seed the announced set with the startup-connected MCP server, mirroring
- // the turn-1 seed in `run_turn` (those are already in the system prompt's
- // `## Connected MCP Servers` block, so only mid-session connects announce).
- let mut announced: HashSet<String> = HashSet::new();
- announced.insert("ac.tandem/docs-mcp".to_string());
-
- // A mid-session connect adds a weather server: it should be announced once,
- // and recorded so it never re-announces.
- let connected = vec![
- "ac.tandem/docs-mcp".to_string(),
- "io.weather/mcp".to_string(),
- ];
- let newly = newly_connected_slugs(&connected, &mut announced);
- assert_eq!(newly, vec!["io.weather/mcp".to_string()]);
- let note = mcp_announcement_note(&newly)
- .expect("a newly-connected MCP server must produce an announcement");
- assert!(
- note.contains("io.weather/mcp"),
- "announcement must name the new server, got: {note}"
- );
- assert!(
- note.contains("use_mcp_server"),
- "announcement must point the model at the use_mcp_server delegate, got: {note}"
- );
- assert!(
- !note.contains("ac.tandem/docs-mcp"),
- "an already-announced server must not be re-announced, got: {note}"
- );
-
- // A second pass with the identical connected set parks nothing.
- let second = newly_connected_slugs(&connected, &mut announced);
- assert!(
- second.is_empty(),
- "an unchanged connected set must not re-surface a server, got: {second:?}"
- );
- assert!(mcp_announcement_note(&second).is_none());
-}
-
-#[test]
-fn integration_announcement_accumulates_two_connects_in_one_note() {
- // Two mid-session connects between consecutive user turns must BOTH be
- // announced — the second must not overwrite the first (#3044 regression:
- // the old `Option<String>` field dropped the earlier note).
- let mut announced: HashSet<String> = HashSet::new();
- announced.insert("gmail".to_string());
- let mut pending: Vec<String> = Vec::new();
-
- // First connect: notion.
- for slug in newly_connected_slugs(&["gmail".to_string(), "notion".to_string()], &mut announced)
- {
- if !pending.contains(&slug) {
- pending.push(slug);
- }
- }
- // Second connect before the user turn: slack.
- for slug in newly_connected_slugs(
- &[
- "gmail".to_string(),
- "notion".to_string(),
- "slack".to_string(),
- ],
- &mut announced,
- ) {
- if !pending.contains(&slug) {
- pending.push(slug);
- }
- }
-
- let note = integration_announcement_note(&pending).expect("two connects must produce a note");
- assert!(
- note.contains("notion"),
- "first connect must survive: {note}"
- );
- assert!(
- note.contains("slack"),
- "second connect must be present: {note}"
- );
- assert!(
- !note.contains("gmail"),
- "startup slug must not re-announce: {note}"
- );
-}
-
-#[test]
-fn skill_announcement_note_empty_yields_none() {
- assert!(super::super::skill_announcement_note(&[]).is_none());
-}
-
-#[test]
-fn skill_announcement_note_mentions_ids_and_run_skill() {
- let note = super::super::skill_announcement_note(&[
- "ascii-art".to_string(),
- "github-issues".to_string(),
- ])
- .expect("non-empty input should yield a note");
- assert!(note.contains("[skills update]"));
- assert!(note.contains("ascii-art"));
- assert!(note.contains("github-issues"));
- assert!(
- note.contains("run_skill"),
- "note must steer the model to run_skill: {note}"
- );
-}
-
-#[test]
-fn skill_retraction_note_empty_yields_none() {
- assert!(super::super::skill_retraction_note(&[]).is_none());
-}
-
-#[test]
-fn skill_retraction_note_names_removed_skills_and_warns_against_run_skill() {
- let note = super::super::skill_retraction_note(&[
- "ascii-art".to_string(),
- "github-issues".to_string(),
- ])
- .expect("non-empty input should yield a note");
- assert!(note.contains("[skills retracted]"));
- assert!(note.contains("ascii-art"));
- assert!(note.contains("github-issues"));
- assert!(
- note.contains("run_skill"),
- "note must mention run_skill so the model knows not to invoke it: {note}"
- );
- assert!(
- !note.contains("[skills update]"),
- "retraction note must not look like an install announcement: {note}"
- );
-}
-
-// ── Lane B through the production memory handle (#6041) ─────────────────────
-//
-// Every other turn test binds the embedded store, whose `Memory` impl answers
-// `recall_relevant_by_vector` itself. Production binds `DriverMemory`, which
-// sat on the trait's empty default — so Lane B never injected anything on a
-// module-backed install and no test noticed. These run the real `turn()` over
-// `DriverMemory` on a scripted driver.
-
-use crate::agent::experience::ops::DriverMemory;
-use crate::memory::api::provider::MemoryProvider;
-use crate::memory::guard::test_support::{namespace_hit, namespace_summary, RecordingProvider};
-use crate::memory::preferences::USER_PREF_SITUATIONAL_NAMESPACE;
-
-const PREFERENCES_BANNER: &str = "## Relevant preferences for this message";
-
-pub(super) fn scripted_reply(text: &str) -> Arc<SequenceProvider> {
- Arc::new(SequenceProvider {
- responses: AsyncMutex::new(vec![Ok(ChatResponse {
- text: Some(text.into()),
- tool_calls: vec![],
- usage: None,
- reasoning_content: None,
- })]),
- requests: AsyncMutex::new(Vec::new()),
- tool_counts: AsyncMutex::new(Vec::new()),
- })
-}
-
-/// A turn-capable agent whose memory is the production adapter over `driver`.
-fn make_agent_over_driver(
- provider: Arc<dyn ChatModel<()>>,
- driver: Arc<RecordingProvider>,
-) -> Agent {
- let workspace = tempfile::TempDir::new().expect("temp workspace");
- let workspace_path = workspace.path().to_path_buf();
- std::mem::forget(workspace);
- let mem: Arc<dyn Memory> = Arc::new(DriverMemory::new(driver as Arc<dyn MemoryProvider>));
-
- Agent::builder()
- .chat_model(provider)
- .tools(vec![])
- .memory(mem)
- .tool_dispatcher(Box::new(XmlDialect))
- .config(crate::config::AgentConfig::default())
- .context_config(crate::config::ContextConfig::default())
- .workspace_dir(workspace_path)
- .event_context("turn-test-session", "turn-test-channel")
- .build()
- .unwrap()
-}
-
-/// The user messages the model was sent on the first (only) request.
-async fn first_request_user_messages(provider: &SequenceProvider) -> Vec<String> {
- let requests = provider.requests.lock().await;
- let request = requests.first().expect("the model was called once");
- request
- .iter()
- .filter(|m| m.role == "user")
- .map(|m| m.content.clone())
- .collect()
-}
-
-#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
-async fn situational_preference_reaches_the_model_through_driver_memory() {
- // The namespace must look populated (a non-zero count) before Lane B pays
- // for the vector recall; then the scored hits decide what is injected.
- let driver = Arc::new(
- RecordingProvider::new()
- .with_namespace_summaries(vec![namespace_summary(USER_PREF_SITUATIONAL_NAMESPACE, 2)])
- .with_namespace_hits(vec![
- namespace_hit(
- USER_PREF_SITUATIONAL_NAMESPACE,
- "editor",
- "Prefers vim for editing code.",
- 0.9,
- ),
- namespace_hit(
- USER_PREF_SITUATIONAL_NAMESPACE,
- "lexical_only",
- "Shares words, means nothing.",
- 0.1,
- ),
- ]),
- );
- let provider_impl = scripted_reply("vim it is.");
- let provider: Arc<dyn ChatModel<()>> = provider_impl.clone();
- let mut agent = make_agent_over_driver(provider, driver.clone());
-
- agent
- .turn("which editor should I use for this rust project?")
- .await
- .expect("turn succeeds");
-
- assert!(
- driver
- .calls()
- .iter()
- .any(|c| c.method == "retrieval.recall_namespace_scored"),
- "Lane B must ask the driver, not the trait default: {:?}",
- driver.calls()
- );
- let user = first_request_user_messages(&provider_impl).await;
- let last = user.last().expect("a user message");
- assert!(
- last.contains(PREFERENCES_BANNER) && last.contains("Prefers vim for editing code."),
- "the situational preference must ride the user message: {last}"
- );
- assert!(
- !last.contains("Shares words, means nothing."),
- "a hit below the vector floor must not be injected: {last}"
- );
-}
-
-#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
-async fn no_situational_preference_means_no_block_and_no_embed_through_driver_memory() {
- // Nothing stored under the situational namespace: the lane must find that
- // out from the namespace counts and never reach the vector recall, which
- // is the call that embeds the message.
- let driver = Arc::new(RecordingProvider::new());
- let provider_impl = scripted_reply("Sunny.");
- let provider: Arc<dyn ChatModel<()>> = provider_impl.clone();
- let mut agent = make_agent_over_driver(provider, driver.clone());
-
- agent
- .turn("what's the weather today")
- .await
- .expect("turn succeeds");
- let user = first_request_user_messages(&provider_impl).await;
- assert!(
- user.iter().all(|u| !u.contains(PREFERENCES_BANNER)),
- "an empty answer must inject nothing: {user:?}"
- );
- let methods: Vec<String> = driver.calls().into_iter().map(|c| c.method).collect();
- assert!(
- methods.iter().any(|m| m == "core.namespaces"),
- "the lane must ask for the namespace counts: {methods:?}"
- );
- assert!(
- !methods
- .iter()
- .any(|m| m == "retrieval.recall_namespace_scored"),
- "an empty namespace must not cost an embed round trip: {methods:?}"
- );
-}
diff --git a/crates/openhuman-core/src/agent/harness/session/turn_required_output_tests.rs b/crates/openhuman-core/src/agent/harness/session/turn_required_output_tests.rs
deleted file mode 100644
index 6f3b951199..0000000000
--- a/crates/openhuman-core/src/agent/harness/session/turn_required_output_tests.rs
+++ /dev/null
@@ -1,622 +0,0 @@
-use super::*;
-
-/// The control case for the test above: with NO override the same agent offers
-/// its tool, and the override state has reset after the previous turn — so the
-/// suppression is genuinely one-shot.
-#[tokio::test]
-async fn turn_without_override_offers_tools_and_resets_after_a_suppressed_turn() {
- let provider_impl = Arc::new(SequenceProvider {
- responses: AsyncMutex::new(vec![
- Ok(ChatResponse {
- text: Some("first".into()),
- tool_calls: vec![],
- usage: None,
- reasoning_content: None,
- }),
- Ok(ChatResponse {
- text: Some("second".into()),
- tool_calls: vec![],
- usage: None,
- reasoning_content: None,
- }),
- ]),
- requests: AsyncMutex::new(Vec::new()),
- tool_counts: AsyncMutex::new(Vec::new()),
- });
- let provider: Arc<dyn ChatModel<()>> = provider_impl.clone();
- let mut agent = make_agent_with_builder(
- provider,
- vec![Box::new(EchoTool)],
- Vec::new(),
- crate::config::AgentConfig {
- max_tool_iterations: 3,
- max_history_messages: 10,
- ..crate::config::AgentConfig::default()
- },
- crate::config::ContextConfig::default(),
- );
-
- // Turn 1: suppressed.
- agent.set_next_turn_overrides(crate::agent::harness::session::TurnOverrides {
- suppress_tools: true,
- ..Default::default()
- });
- agent.turn("hi").await.expect("turn 1 succeeds");
- // Turn 2: no override set — the field must have reset to default.
- agent
- .turn("now do the work")
- .await
- .expect("turn 2 succeeds");
-
- let counts = provider_impl.tool_counts.lock().await;
- assert_eq!(counts.len(), 2);
- assert_eq!(counts[0], 0, "turn 1 suppressed its tools");
- assert!(
- counts[1] >= 1,
- "turn 2 must have the full toolbelt back (one-shot suppression, not a rebuild)"
- );
-}
-
-/// #1725: a per-turn `suppress_memory_agent` override skips the pre-turn
-/// `agent_memory` retrieval even when the agent's policy is `Always`, so a
-/// greeting is a SINGLE provider call with no "## Memory agent context" block.
-#[tokio::test]
-async fn turn_override_suppress_memory_agent_skips_memory_trigger() {
- crate::agent::harness::definition::AgentDefinitionRegistry::init_global_builtins()
- .expect("built-in agent definitions should load");
-
- let provider_impl = Arc::new(SequenceProvider {
- responses: AsyncMutex::new(vec![Ok(ChatResponse {
- text: Some("parent final".into()),
- tool_calls: vec![],
- usage: None,
- reasoning_content: None,
- })]),
- requests: AsyncMutex::new(Vec::new()),
- tool_counts: AsyncMutex::new(Vec::new()),
- });
- let provider: Arc<dyn ChatModel<()>> = provider_impl.clone();
- let workspace = tempfile::TempDir::new().expect("temp workspace");
- let workspace_path = workspace.path().to_path_buf();
- let _workspace_env = WorkspaceEnvGuard::set(&workspace_path);
- let _memory_cfg = crate::config::MemoryConfig {
- backend: "none".into(),
- ..crate::config::MemoryConfig::default()
- };
- // The embedding seam, as above.
- let mem: Arc<dyn Memory> = crate::memory::test_support::noop_memory();
-
- let mut agent = Agent::builder()
- .chat_model(provider)
- .tools(vec![Box::new(EchoTool)])
- .memory(mem)
- .tool_dispatcher(Box::new(XmlDialect))
- .config(crate::config::AgentConfig {
- max_tool_iterations: 3,
- max_history_messages: 10,
- ..crate::config::AgentConfig::default()
- })
- .workspace_dir(workspace_path)
- .auto_save(false)
- .event_context("turn-test-session", "turn-test-channel")
- .trigger_memory_agent(crate::agent::harness::definition::TriggerMemoryAgent::Always)
- .build()
- .unwrap();
-
- agent.set_next_turn_overrides(crate::agent::harness::session::TurnOverrides {
- suppress_memory_agent: true,
- suppress_tools: true,
- suppress_active_goal: true,
- suppress_transcript_autoload: false,
- });
- let response = agent.turn("hi there").await.expect("turn should succeed");
- assert_eq!(response, "parent final");
-
- let requests = provider_impl.requests.lock().await;
- assert_eq!(
- requests.len(),
- 1,
- "suppress_memory_agent must skip the memory-agent subagent call (only the parent turn runs)"
- );
- assert!(
- !requests[0]
- .iter()
- .any(|msg| msg.content.contains("## Memory agent context")),
- "no memory-agent context block may be injected on a suppressed turn"
- );
-}
-
-#[tokio::test]
-async fn turn_uses_cached_transcript_prefix_on_first_iteration() {
- let provider_impl = Arc::new(SequenceProvider {
- responses: AsyncMutex::new(vec![Ok(ChatResponse {
- text: Some("cached-final".into()),
- tool_calls: vec![],
- usage: None,
- reasoning_content: None,
- })]),
- requests: AsyncMutex::new(Vec::new()),
- tool_counts: AsyncMutex::new(Vec::new()),
- });
- let provider: Arc<dyn ChatModel<()>> = provider_impl.clone();
- let mut agent = make_agent_with_builder(
- provider,
- vec![Box::new(EchoTool)],
- vec![],
- crate::config::AgentConfig::default(),
- crate::config::ContextConfig::default(),
- );
- agent.cached_transcript_messages = Some(vec![
- ChatMessage::system("cached-system"),
- ChatMessage::assistant("cached-assistant"),
- ]);
-
- let response = agent.turn("fresh").await.expect("turn should succeed");
- assert_eq!(response, "cached-final");
- assert!(agent.cached_transcript_messages.is_none());
-
- let requests = provider_impl.requests.lock().await;
- assert_eq!(requests.len(), 1);
- assert_eq!(requests[0].len(), 3);
- assert_eq!(requests[0][0].content, "cached-system");
- assert_eq!(requests[0][1].content, "cached-assistant");
- assert_eq!(requests[0][2].role, "user");
- // #3602: every turn's user message is prefixed with the live
- // `Current Date & Time:` stamp, then the raw prompt. Assert the stamp
- // leads and the original prompt is preserved at the tail.
- assert!(
- requests[0][2].content.starts_with("Current Date & Time:"),
- "user message must lead with the per-turn time stamp: {}",
- requests[0][2].content
- );
- assert!(
- requests[0][2].content.ends_with("fresh"),
- "user message must preserve the original prompt: {}",
- requests[0][2].content
- );
-}
-
-/// Issue #4117 — a reply that already carries a well-formed leading block is
-/// accepted verbatim: no corrective re-prompt, so exactly one provider call.
-#[tokio::test]
-async fn turn_accepts_valid_required_output_without_repair() {
- let provider_impl = Arc::new(SequenceProvider {
- responses: AsyncMutex::new(vec![Ok(ChatResponse {
- text: Some("{\"thoughts\": \"planning\", \"next_action\": \"answer\"}".into()),
- tool_calls: vec![],
- usage: None,
- reasoning_content: None,
- })]),
- requests: AsyncMutex::new(Vec::new()),
- tool_counts: AsyncMutex::new(Vec::new()),
- });
- let provider: Arc<dyn ChatModel<()>> = provider_impl.clone();
-
- let config = crate::config::AgentConfig {
- max_tool_iterations: 3,
- max_history_messages: 10,
- required_output: Some(crate::config::RequiredOutputContract {
- block_key: "thoughts".into(),
- required_keys: vec!["next_action".into()],
- }),
- ..crate::config::AgentConfig::default()
- };
-
- let mut agent = make_agent_with_builder(
- provider,
- vec![],
- vec![],
- config,
- crate::config::ContextConfig::default(),
- );
-
- let response = agent.turn("hello").await.expect("turn should succeed");
-
- assert!(
- response.contains("thoughts") && response.contains("next_action"),
- "a valid reply must be accepted verbatim, got: {response}"
- );
- // No corrective re-prompt fired — a single provider call.
- assert_eq!(provider_impl.requests.lock().await.len(), 1);
-}
-
-/// Issue #4117 — with no live progress sink (background/routing agent), when the
-/// model emits prose without the mandated JSON block the turn engine re-prompts
-/// and the recovered block-bearing reply *replaces* the omitting one.
-#[tokio::test]
-async fn turn_repairs_missing_required_output_via_reprompt() {
- let provider_impl = Arc::new(SequenceProvider {
- responses: AsyncMutex::new(vec![
- // Turn 1 final reply: prose only, no `thoughts` block.
- Ok(ChatResponse {
- text: Some("Sure, I'll handle that.".into()),
- tool_calls: vec![],
- usage: None,
- reasoning_content: None,
- }),
- // Corrective re-prompt: the model now emits a valid block.
- Ok(ChatResponse {
- text: Some(
- "{\"thoughts\": \"planning the work\", \"next_action\": \"answer\"}".into(),
- ),
- tool_calls: vec![],
- usage: None,
- reasoning_content: None,
- }),
- ]),
- requests: AsyncMutex::new(Vec::new()),
- tool_counts: AsyncMutex::new(Vec::new()),
- });
- let provider: Arc<dyn ChatModel<()>> = provider_impl.clone();
-
- let config = crate::config::AgentConfig {
- max_tool_iterations: 3,
- max_history_messages: 10,
- required_output: Some(crate::config::RequiredOutputContract {
- block_key: "thoughts".into(),
- required_keys: vec!["next_action".into()],
- }),
- ..crate::config::AgentConfig::default()
- };
-
- let mut agent = make_agent_with_builder(
- provider,
- vec![],
- vec![],
- config,
- crate::config::ContextConfig::default(),
- );
-
- let response = agent.turn("hello").await.expect("turn should succeed");
-
- // The returned reply carries the recovered block.
- assert!(
- response.contains("thoughts") && response.contains("next_action"),
- "repaired reply must contain the required block, got: {response}"
- );
- // The omitting prose reply was re-prompted (2 provider calls total).
- assert_eq!(provider_impl.requests.lock().await.len(), 2);
- // History's trailing assistant message was rewritten to match.
- assert!(agent.history.iter().rev().any(|message| matches!(
- message,
- ConversationMessage::Chat(chat)
- if chat.role == "assistant" && chat.content.contains("next_action")
- )));
-}
-
-/// Issue #4117 — when the corrective re-prompt *also* omits the block (and no
-/// live sink is attached), the turn engine synthesizes a minimal valid block and
-/// prepends it to the original prose so the accepted turn leads with a
-/// well-formed block and never loses the model's answer.
-#[tokio::test]
-async fn turn_synthesizes_required_output_when_reprompt_also_omits() {
- let provider_impl = Arc::new(SequenceProvider {
- responses: AsyncMutex::new(vec![
- // Turn 1 final reply: prose only.
- Ok(ChatResponse {
- text: Some("Working on it.".into()),
- tool_calls: vec![],
- usage: None,
- reasoning_content: None,
- }),
- // Re-prompt: still no block.
- Ok(ChatResponse {
- text: Some("Still just prose, sorry.".into()),
- tool_calls: vec![],
- usage: None,
- reasoning_content: None,
- }),
- ]),
- requests: AsyncMutex::new(Vec::new()),
- tool_counts: AsyncMutex::new(Vec::new()),
- });
- let provider: Arc<dyn ChatModel<()>> = provider_impl.clone();
-
- let config = crate::config::AgentConfig {
- max_tool_iterations: 3,
- max_history_messages: 10,
- required_output: Some(crate::config::RequiredOutputContract::new("thoughts")),
- ..crate::config::AgentConfig::default()
- };
-
- let mut agent = make_agent_with_builder(
- provider,
- vec![],
- vec![],
- config,
- crate::config::ContextConfig::default(),
- );
-
- let response = agent.turn("hello").await.expect("turn should succeed");
-
- // The synthesized block is prepended to the ORIGINAL turn reply
- // ("Working on it."), not the failed corrective re-prompt — so the leading
- // JSON object carries the block and the original prose is preserved.
- let first_block = tinytools_agent::extract_json_values(&response)
- .into_iter()
- .next();
- assert!(
- first_block
- .as_ref()
- .is_some_and(|v| v.get("thoughts").is_some()),
- "synthesized reply must lead with a `thoughts` block, got: {response}"
- );
- assert!(response.contains("Working on it."));
- assert_eq!(provider_impl.requests.lock().await.len(), 2);
-}
-
-/// Issue #4117 (the #4387 / sanil-23 streaming blocker) — when a live progress
-/// sink is attached (the reply was streamed to the client) and the block is
-/// omitted, the repair is **append-only**: the original prose is preserved, the
-/// recovered block is *appended* after it (never replacing what the user saw),
-/// and the appended block is streamed as a `TextDelta` continuation so the
-/// returned reply is exactly the concatenation the client watched.
-#[tokio::test]
-async fn turn_appends_required_output_block_when_streamed_to_preserve_consistency() {
- let provider_impl = Arc::new(SequenceProvider {
- responses: AsyncMutex::new(vec![
- // Turn 1 final reply: prose only, streamed to the client.
- Ok(ChatResponse {
- text: Some("Sure, I'll handle that.".into()),
- tool_calls: vec![],
- usage: None,
- reasoning_content: None,
- }),
- // Corrective re-prompt: the model now emits a valid block.
- Ok(ChatResponse {
- text: Some(
- "{\"thoughts\": \"planning the work\", \"next_action\": \"answer\"}".into(),
- ),
- tool_calls: vec![],
- usage: None,
- reasoning_content: None,
- }),
- ]),
- requests: AsyncMutex::new(Vec::new()),
- tool_counts: AsyncMutex::new(Vec::new()),
- });
- let provider: Arc<dyn ChatModel<()>> = provider_impl.clone();
-
- let config = crate::config::AgentConfig {
- max_tool_iterations: 3,
- max_history_messages: 10,
- required_output: Some(crate::config::RequiredOutputContract {
- block_key: "thoughts".into(),
- required_keys: vec!["next_action".into()],
- }),
- ..crate::config::AgentConfig::default()
- };
-
- let mut agent = make_agent_with_builder(
- provider,
- vec![],
- vec![],
- config,
- crate::config::ContextConfig::default(),
- );
-
- // Attach a live progress sink and drain it concurrently so the streamed
- // deltas are captured without the bounded channel ever back-pressuring the
- // turn.
- let (tx, mut rx) = tokio::sync::mpsc::channel(64);
- let text_deltas = Arc::new(AsyncMutex::new(Vec::<String>::new()));
- let text_deltas_drain = text_deltas.clone();
- let drain = tokio::spawn(async move {
- while let Some(progress) = rx.recv().await {
- if let crate::agent::progress::AgentProgress::TextDelta { delta, .. } = progress {
- text_deltas_drain.lock().await.push(delta);
- }
- }
- });
- agent.set_on_progress(Some(tx));
-
- let response = agent.turn("hello").await.expect("turn should succeed");
-
- // Drop the sink so the drain task observes channel close and finishes.
- agent.set_on_progress(None);
- // The continuation delta is sent (awaited) during the turn, so it is already
- // drained; guard the join with a timeout so a leaked sender clone can never
- // hang the test.
- let _ = timeout(Duration::from_secs(5), drain).await;
-
- // Append-only: the original prose is preserved AND precedes the block — the
- // streamed preview is a prefix of the final reply, never contradicted.
- assert!(
- response.contains("Sure, I'll handle that."),
- "original streamed prose must be preserved, not replaced: {response}"
- );
- assert!(
- response.contains("next_action"),
- "repaired reply must contain the required block: {response}"
- );
- let prose_at = response
- .find("Sure, I'll handle that.")
- .expect("prose present");
- let block_at = response.find("next_action").expect("block present");
- assert!(
- prose_at < block_at,
- "the block must be appended AFTER the already-streamed prose: {response}"
- );
-
- // The appended correction was streamed as a `TextDelta` continuation.
- let deltas = text_deltas.lock().await;
- assert!(
- deltas.iter().any(|d| d.contains("next_action")),
- "the appended block must be streamed as a TextDelta continuation, got: {deltas:?}"
- );
- assert_eq!(provider_impl.requests.lock().await.len(), 2);
-}
-
-/// Issue #4117 / #4900 — streamed path where the corrective re-prompt obeys
-/// `repair_instruction` literally: it leads with the block **and continues with
-/// the answer** (as the prompt asks). Because the original prose is already on
-/// the client, only the block may be appended — appending the whole re-prompt
-/// reply would duplicate the answer. Guards against that regression.
-#[tokio::test]
-async fn turn_appends_only_block_not_restated_answer_when_streamed() {
- let provider_impl = Arc::new(SequenceProvider {
- responses: AsyncMutex::new(vec![
- // Turn 1 final reply: prose only, streamed to the client.
- Ok(ChatResponse {
- text: Some("Paris is the capital of France.".into()),
- tool_calls: vec![],
- usage: None,
- reasoning_content: None,
- }),
- // Corrective re-prompt: block first, THEN the restated answer — exactly
- // what `repair_instruction` ("…then continue with your answer") elicits.
- Ok(ChatResponse {
- text: Some(
- "{\"thoughts\": \"restating\", \"next_action\": \"answer\"}\n\n\
- Paris is the capital of France."
- .into(),
- ),
- tool_calls: vec![],
- usage: None,
- reasoning_content: None,
- }),
- ]),
- requests: AsyncMutex::new(Vec::new()),
- tool_counts: AsyncMutex::new(Vec::new()),
- });
- let provider: Arc<dyn ChatModel<()>> = provider_impl.clone();
-
- let config = crate::config::AgentConfig {
- max_tool_iterations: 3,
- max_history_messages: 10,
- required_output: Some(crate::config::RequiredOutputContract {
- block_key: "thoughts".into(),
- required_keys: vec!["next_action".into()],
- }),
- ..crate::config::AgentConfig::default()
- };
-
- let mut agent = make_agent_with_builder(
- provider,
- vec![],
- vec![],
- config,
- crate::config::ContextConfig::default(),
- );
-
- let (tx, mut rx) = tokio::sync::mpsc::channel(64);
- let text_deltas = Arc::new(AsyncMutex::new(Vec::<String>::new()));
- let text_deltas_drain = text_deltas.clone();
- let drain = tokio::spawn(async move {
- while let Some(progress) = rx.recv().await {
- if let crate::agent::progress::AgentProgress::TextDelta { delta, .. } = progress {
- text_deltas_drain.lock().await.push(delta);
- }
- }
- });
- agent.set_on_progress(Some(tx));
-
- let response = agent
- .turn("what is the capital of France?")
- .await
- .expect("turn should succeed");
-
- agent.set_on_progress(None);
- let _ = timeout(Duration::from_secs(5), drain).await;
-
- // The block is appended and the original prose preserved …
- assert!(
- response.contains("next_action"),
- "repaired reply must contain the required block: {response}"
- );
- // … but the answer must appear exactly ONCE — the restated answer from the
- // re-prompt reply must not be appended after the block.
- assert_eq!(
- response.matches("Paris is the capital of France.").count(),
- 1,
- "the answer must not be duplicated by appending the re-prompt's restated prose: {response}"
- );
- // Streamed continuation carried the block, not a second copy of the answer.
- let deltas = text_deltas.lock().await;
- let streamed_continuation: String = deltas.concat();
- assert!(
- streamed_continuation.contains("next_action"),
- "the appended block must be streamed as a continuation, got: {deltas:?}"
- );
- assert!(
- !streamed_continuation.contains("Paris is the capital of France."),
- "the streamed continuation must not restream the answer, got: {deltas:?}"
- );
-}
-
-/// Issue #4117 — streamed path, but the corrective re-prompt *also* omits the
-/// block. A synthesized block is appended (never replacing the streamed prose)
-/// and streamed as a continuation, so the accepted turn still leads with the
-/// original prose and carries a well-formed block.
-#[tokio::test]
-async fn turn_appends_synthesized_block_when_streamed_reprompt_also_omits() {
- let provider_impl = Arc::new(SequenceProvider {
- responses: AsyncMutex::new(vec![
- Ok(ChatResponse {
- text: Some("Working on it.".into()),
- tool_calls: vec![],
- usage: None,
- reasoning_content: None,
- }),
- // Re-prompt: still no block.
- Ok(ChatResponse {
- text: Some("Still just prose, sorry.".into()),
- tool_calls: vec![],
- usage: None,
- reasoning_content: None,
- }),
- ]),
- requests: AsyncMutex::new(Vec::new()),
- tool_counts: AsyncMutex::new(Vec::new()),
- });
- let provider: Arc<dyn ChatModel<()>> = provider_impl.clone();
-
- let config = crate::config::AgentConfig {
- max_tool_iterations: 3,
- max_history_messages: 10,
- required_output: Some(crate::config::RequiredOutputContract::new("thoughts")),
- ..crate::config::AgentConfig::default()
- };
-
- let mut agent = make_agent_with_builder(
- provider,
- vec![],
- vec![],
- config,
- crate::config::ContextConfig::default(),
- );
-
- let (tx, mut rx) = tokio::sync::mpsc::channel(64);
- let text_deltas = Arc::new(AsyncMutex::new(Vec::<String>::new()));
- let text_deltas_drain = text_deltas.clone();
- let drain = tokio::spawn(async move {
- while let Some(progress) = rx.recv().await {
- if let crate::agent::progress::AgentProgress::TextDelta { delta, .. } = progress {
- text_deltas_drain.lock().await.push(delta);
- }
- }
- });
- agent.set_on_progress(Some(tx));
-
- let response = agent.turn("hello").await.expect("turn should succeed");
- agent.set_on_progress(None);
- // The continuation delta is sent (awaited) during the turn, so it is already
- // drained; guard the join with a timeout so a leaked sender clone can never
- // hang the test.
- let _ = timeout(Duration::from_secs(5), drain).await;
-
- // Original prose preserved and leads; a synthesized `thoughts` block follows.
- assert!(response.contains("Working on it."));
- let prose_at = response.find("Working on it.").expect("prose present");
- let block_at = response.find("thoughts").expect("synth block present");
- assert!(
- prose_at < block_at,
- "synthesized block must be appended after the streamed prose: {response}"
- );
- let deltas = text_deltas.lock().await;
- assert!(
- deltas.iter().any(|d| d.contains("thoughts")),
- "the synthesized block must be streamed as a continuation, got: {deltas:?}"
- );
- assert_eq!(provider_impl.requests.lock().await.len(), 2);
-}
diff --git a/crates/openhuman-core/src/agent/harness/session/turn_tests.rs b/crates/openhuman-core/src/agent/harness/session/turn_tests.rs
deleted file mode 100644
index 5fbc7d0bb3..0000000000
--- a/crates/openhuman-core/src/agent/harness/session/turn_tests.rs
+++ /dev/null
@@ -1,550 +0,0 @@
-use super::*;
-use crate::agent::experience::{
- AgentExperience, AgentExperienceStore, ExperienceOutcome, ExperienceSource,
-};
-use crate::agent::hooks::{PostTurnHook, TurnContext};
-use crate::agent::messages::{ChatMessage, ConversationMessage};
-use crate::agent::tool_policy::{
- GeneratedToolRuntimeContext, GeneratedToolRuntimeRisk, ToolPolicy, ToolPolicyDecision,
- ToolPolicyRequest,
-};
-use crate::inference::provider::{ChatResponse, UsageInfo};
-use crate::memory::Memory;
-use async_trait::async_trait;
-use std::collections::HashSet;
-use std::sync::atomic::{AtomicUsize, Ordering};
-use std::sync::Arc;
-use tinyinference_llm::message::Message;
-use tinyinference_llm::model::{
- ChatModel, ModelProfile, ModelRequest, ModelResponse, ModelStream, ModelStreamItem,
-};
-use tinytools::ToolResult;
-use tinytools::{PermissionLevel, Tool};
-use tinytools_agent::dialect::{PFormatDialect, ToolDialect, XmlDialect};
-use tokio::sync::Mutex as AsyncMutex;
-use tokio::sync::Notify;
-use tokio::time::{timeout, Duration};
-
-struct DummyProvider;
-
-#[async_trait]
-impl ChatModel<()> for DummyProvider {
- fn profile(&self) -> Option<&ModelProfile> {
- static PROFILE: std::sync::LazyLock<ModelProfile> =
- std::sync::LazyLock::new(ModelProfile::default);
- Some(&PROFILE)
- }
-
- async fn invoke(
- &self,
- _state: &(),
- _request: ModelRequest,
- ) -> tinyinference_llm::Result<ModelResponse> {
- Ok(ModelResponse::assistant("unused"))
- }
-}
-
-struct SequenceProvider {
- responses: AsyncMutex<Vec<anyhow::Result<ChatResponse>>>,
- requests: AsyncMutex<Vec<Vec<ChatMessage>>>,
- /// Number of tool declarations the provider was offered on each call, in
- /// call order. Lets a test assert per-turn tool suppression (#1725): a
- /// chat/small-talk turn must send an empty tool schema.
- tool_counts: AsyncMutex<Vec<usize>>,
-}
-
-#[async_trait]
-impl ChatModel<()> for SequenceProvider {
- fn profile(&self) -> Option<&ModelProfile> {
- static PROFILE: std::sync::LazyLock<ModelProfile> =
- std::sync::LazyLock::new(ModelProfile::default);
- Some(&PROFILE)
- }
-
- async fn invoke(
- &self,
- _state: &(),
- request: ModelRequest,
- ) -> tinyinference_llm::Result<ModelResponse> {
- self.tool_counts.lock().await.push(request.tools.len());
- self.requests.lock().await.push(
- request
- .messages
- .iter()
- .map(|message| ChatMessage {
- id: None,
- role: match message {
- Message::System(_) => "system",
- Message::User(_) => "user",
- Message::Assistant(_) => "assistant",
- // SequenceProvider replaces the old prompt-guided
- // Provider fixture. Its wire adapter flattened tool
- // results into a user turn rather than sending the
- // native `tool` role.
- Message::Tool(_) => "user",
- }
- .to_string(),
- content: match message {
- Message::Tool(_) => format!("[Tool results]\n{}", message.text()),
- _ => message.text(),
- },
- extra_metadata: None,
- cache_breakpoints: Vec::new(),
- })
- .collect(),
- );
- match self.responses.lock().await.remove(0) {
- Ok(response) => Ok(
- crate::agent::tinyagents::model::native_model_response_for_request(
- &response, &request,
- ),
- ),
- Err(error) => Err(tinyinference_llm::Error::Model(error.to_string())),
- }
- }
-
- async fn stream(
- &self,
- state: &(),
- request: ModelRequest,
- ) -> tinyinference_llm::Result<ModelStream> {
- // The legacy fixture implemented `chat` but did not write provider
- // deltas. Preserve that non-streaming wire behavior: the harness still
- // receives the authoritative completed response, while turn-owned
- // continuation deltas remain independently observable.
- let response = self.invoke(state, request).await?;
- Ok(ModelStream::new(Box::pin(futures::stream::iter(vec![
- ModelStreamItem::Started,
- ModelStreamItem::Completed(response),
- ]))))
- }
-}
-
-struct EchoTool;
-
-#[async_trait]
-impl Tool for EchoTool {
- fn name(&self) -> &str {
- "echo"
- }
-
- fn description(&self) -> &str {
- "echo"
- }
-
- fn parameters_schema(&self) -> serde_json::Value {
- serde_json::json!({"type":"object"})
- }
-
- async fn execute(&self, _args: serde_json::Value) -> Result<ToolResult> {
- Ok(ToolResult::success("echo-output"))
- }
-}
-
-struct CronAddProbeTool;
-
-#[async_trait]
-impl Tool for CronAddProbeTool {
- fn name(&self) -> &str {
- "cron_add"
- }
-
- fn description(&self) -> &str {
- "cron add probe"
- }
-
- fn parameters_schema(&self) -> serde_json::Value {
- serde_json::json!({"type":"object"})
- }
-
- async fn execute(&self, args: serde_json::Value) -> Result<ToolResult> {
- Ok(ToolResult::success(format!("cron_add_args={args}")))
- }
-}
-
-struct CountingTool {
- calls: Arc<AtomicUsize>,
-}
-
-#[async_trait]
-impl Tool for CountingTool {
- fn name(&self) -> &str {
- "counting"
- }
-
- fn description(&self) -> &str {
- "counting"
- }
-
- fn parameters_schema(&self) -> serde_json::Value {
- serde_json::json!({"type":"object"})
- }
-
- async fn execute(&self, _args: serde_json::Value) -> Result<ToolResult> {
- self.calls.fetch_add(1, Ordering::SeqCst);
- Ok(ToolResult::success("counting-output"))
- }
-}
-
-struct DenyCountingPolicy;
-
-#[async_trait]
-impl ToolPolicy for DenyCountingPolicy {
- fn name(&self) -> &str {
- "deny_counting"
- }
-
- async fn check(&self, request: &ToolPolicyRequest) -> ToolPolicyDecision {
- assert_eq!(request.tool_name, "counting");
- assert_eq!(request.context.session_id, "turn-test-session");
- assert_eq!(request.context.channel, "turn-test-channel");
- assert_eq!(request.context.agent_definition_id, "main");
- assert_eq!(request.context.call_id, "policy-1");
- assert_eq!(request.context.iteration, 1);
- ToolPolicyDecision::deny("locked by test policy")
- }
-}
-
-struct LongTool;
-
-#[async_trait]
-impl Tool for LongTool {
- fn name(&self) -> &str {
- "long"
- }
-
- fn description(&self) -> &str {
- "long"
- }
-
- fn parameters_schema(&self) -> serde_json::Value {
- serde_json::json!({"type":"object"})
- }
-
- async fn execute(&self, _args: serde_json::Value) -> Result<ToolResult> {
- Ok(ToolResult::success("x".repeat(800)))
- }
-}
-
-struct CountingWriteTool {
- calls: Arc<AtomicUsize>,
-}
-
-#[async_trait]
-impl Tool for CountingWriteTool {
- fn name(&self) -> &str {
- "write_notes"
- }
-
- fn description(&self) -> &str {
- "write notes"
- }
-
- fn parameters_schema(&self) -> serde_json::Value {
- serde_json::json!({"type":"object"})
- }
-
- async fn execute(&self, _args: serde_json::Value) -> Result<ToolResult> {
- self.calls.fetch_add(1, Ordering::SeqCst);
- Ok(ToolResult::success("write-output"))
- }
-
- fn permission_level(&self) -> PermissionLevel {
- PermissionLevel::Write
- }
-}
-
-struct GeneratedContextTool {
- calls: Arc<AtomicUsize>,
-}
-
-#[async_trait]
-impl Tool for GeneratedContextTool {
- fn name(&self) -> &str {
- "generated_send"
- }
-
- fn description(&self) -> &str {
- "generated send"
- }
-
- fn parameters_schema(&self) -> serde_json::Value {
- serde_json::json!({"type":"object"})
- }
-
- async fn execute(&self, _args: serde_json::Value) -> Result<ToolResult> {
- self.calls.fetch_add(1, Ordering::SeqCst);
- Ok(ToolResult::success("generated-output"))
- }
-
- fn host_call_extension(
- &self,
- _args: &serde_json::Value,
- ) -> Option<Box<dyn std::any::Any + Send + Sync>> {
- Some(Box::new(GeneratedToolRuntimeContext {
- provider_id: "mail.runtime".to_string(),
- capability_id: "email.send".to_string(),
- risk: GeneratedToolRuntimeRisk::ExternalWrite,
- source_digest: Some("sha256:abc".to_string()),
- approval_id: Some("approval-1".to_string()),
- }))
- }
-}
-
-struct RequireGeneratedContextPolicy;
-
-#[async_trait]
-impl ToolPolicy for RequireGeneratedContextPolicy {
- fn name(&self) -> &str {
- "require_generated_context"
- }
-
- async fn check(&self, request: &ToolPolicyRequest) -> ToolPolicyDecision {
- let context = request
- .generated_tool
- .as_ref()
- .expect("generated tool context should be threaded");
- assert_eq!(context.provider_id, "mail.runtime");
- assert_eq!(context.capability_id, "email.send");
- assert_eq!(context.risk, GeneratedToolRuntimeRisk::ExternalWrite);
- assert_eq!(context.approval_id.as_deref(), Some("approval-1"));
- ToolPolicyDecision::require_approval("generated context requires approval")
- }
-}
-
-struct RecordingHook {
- calls: Arc<AsyncMutex<Vec<TurnContext>>>,
- notify: Arc<Notify>,
-}
-
-#[async_trait]
-impl PostTurnHook for RecordingHook {
- fn name(&self) -> &str {
- "recording"
- }
-
- async fn on_turn_complete(&self, ctx: &TurnContext) -> anyhow::Result<()> {
- self.calls.lock().await.push(ctx.clone());
- self.notify.notify_waiters();
- Ok(())
- }
-}
-
-/// Point `OPENHUMAN_WORKSPACE` at a scratch directory for the lifetime of a
-/// test, restoring the previous value on drop.
-///
-/// Needed by any test that lets the harness reach `Config::load_or_init()` —
-/// notably the triggered `agent_memory` path, whose deterministic fast path
-/// (`subagent_runner::ops::runner::try_deterministic_memory_retrieval`, #4677)
-/// loads the **host** config and queries the real memory tree behind it, not
-/// the `Memory` handed to the `Agent` under test. Without this the test reads
-/// the developer's own `~/.openhuman`: on a populated machine `fast_retrieve`
-/// returns hits, the fast path short-circuits with zero provider calls, and the
-/// mock provider's queued responses land on the wrong turns. CI has an empty
-/// home, so the failure only ever reproduces locally.
-///
-/// Same shape as the guards in `memory::ops::files` / `memory::query::
-/// test_workspace`; `TEST_ENV_LOCK` serializes it against them.
-struct WorkspaceEnvGuard {
- _lock: std::sync::MutexGuard<'static, ()>,
- previous: Option<std::ffi::OsString>,
-}
-
-impl WorkspaceEnvGuard {
- fn set(path: &std::path::Path) -> Self {
- let lock = crate::config::TEST_ENV_LOCK
- .lock()
- .unwrap_or_else(|poisoned| poisoned.into_inner());
- let previous = std::env::var_os("OPENHUMAN_WORKSPACE");
- unsafe {
- std::env::set_var("OPENHUMAN_WORKSPACE", path);
- }
- Self {
- _lock: lock,
- previous,
- }
- }
-}
-
-impl Drop for WorkspaceEnvGuard {
- fn drop(&mut self) {
- unsafe {
- if let Some(previous) = self.previous.take() {
- std::env::set_var("OPENHUMAN_WORKSPACE", previous);
- } else {
- std::env::remove_var("OPENHUMAN_WORKSPACE");
- }
- }
- }
-}
-
-fn make_agent(visible_tool_names: Option<HashSet<String>>) -> Agent {
- make_agent_with_tool_sets(vec![Box::new(EchoTool)], Vec::new(), visible_tool_names)
-}
-
-/// [`make_agent`] with caller-chosen durable and synthesised tool sets.
-fn make_agent_with_tool_sets(
- tools: Vec<Box<dyn Tool>>,
- synthesized_tools: Vec<Box<dyn Tool>>,
- visible_tool_names: Option<HashSet<String>>,
-) -> Agent {
- // The embedding seam fails loudly when unwired; before the memory
- // extraction this was a direct call and needed no setup.
- let workspace = tempfile::TempDir::new().expect("temp workspace");
- let workspace_path = workspace.path().to_path_buf();
- std::mem::forget(workspace);
- let _memory_cfg = crate::config::MemoryConfig {
- backend: "none".into(),
- ..crate::config::MemoryConfig::default()
- };
- // `create_memory` reaches the engine's embedding seam, which fails loudly
- // when unwired rather than degrading — a deliberate choice, so an unwired
- // host cannot corrupt an embedding space quietly. Nothing in a unit test
- // runs the startup wiring that installs it, so the helper installs it
- // itself. `install_for_tests` is idempotent (a `Once`), so every helper in
- // this file calling it costs one install for the whole binary.
- let mem: Arc<dyn Memory> = crate::memory::test_support::noop_memory();
-
- let mut builder = Agent::builder()
- .chat_model(Arc::new(DummyProvider))
- .tools(tools)
- .synthesized_tools(synthesized_tools)
- .memory(mem)
- .tool_dispatcher(Box::new(XmlDialect))
- .workspace_dir(workspace_path)
- .event_context("turn-test-session", "turn-test-channel")
- .config(crate::config::AgentConfig {
- max_history_messages: 3,
- ..crate::config::AgentConfig::default()
- });
-
- if let Some(names) = visible_tool_names {
- builder = builder.visible_tool_names(names);
- }
-
- builder.build().unwrap()
-}
-
-fn make_agent_with_builder(
- provider: Arc<dyn ChatModel<()>>,
- tools: Vec<Box<dyn Tool>>,
- post_turn_hooks: Vec<Arc<dyn PostTurnHook>>,
- config: crate::config::AgentConfig,
- context_config: crate::config::ContextConfig,
-) -> Agent {
- make_agent_with_builder_and_dispatcher(
- provider,
- tools,
- post_turn_hooks,
- config,
- context_config,
- Box::new(XmlDialect),
- )
-}
-
-fn make_agent_with_builder_and_dispatcher(
- provider: Arc<dyn ChatModel<()>>,
- tools: Vec<Box<dyn Tool>>,
- post_turn_hooks: Vec<Arc<dyn PostTurnHook>>,
- config: crate::config::AgentConfig,
- context_config: crate::config::ContextConfig,
- tool_dispatcher: Box<dyn ToolDialect>,
-) -> Agent {
- let workspace = tempfile::TempDir::new().expect("temp workspace");
- let workspace_path = workspace.path().to_path_buf();
- std::mem::forget(workspace);
- let _memory_cfg = crate::config::MemoryConfig {
- backend: "none".into(),
- ..crate::config::MemoryConfig::default()
- };
- // The embedding seam, as above.
- let mem: Arc<dyn Memory> = crate::memory::test_support::noop_memory();
-
- Agent::builder()
- .chat_model(provider)
- .tools(tools)
- .memory(mem)
- .tool_dispatcher(tool_dispatcher)
- .post_turn_hooks(post_turn_hooks)
- .config(config)
- .context_config(context_config)
- .workspace_dir(workspace_path)
- .auto_save(true)
- .event_context("turn-test-session", "turn-test-channel")
- .build()
- .unwrap()
-}
-
-// Removed: execute_tool_call_applies_inline_result_budget — see the note above;
-// it exercised the deleted direct tool executor.
-
-// ── Explicit-preferences narrow path ──────────────────────────────────────────
-//
-// These tests verify that `fetch_learned_context` correctly handles the three
-// flag combinations:
-// 1. both flags off → empty context
-// 2. explicit_preferences_enabled=true, learning_enabled=false
-// → only general user_pref entries returned, no inference data
-// 3. learning_enabled=true → full path (existing tests cover this; we only
-// verify that explicit entries are included as well)
-//
-// We use the real `UnifiedMemory` backend (sqlite) so the list/store round-trip
-// is exercised end-to-end without mocking the memory layer.
-
-fn make_agent_with_memory(
- memory: Arc<dyn Memory>,
- workspace_dir: std::path::PathBuf,
- learning_enabled: bool,
- explicit_preferences_enabled: bool,
-) -> Agent {
- Agent::builder()
- .chat_model(Arc::new(DummyProvider))
- .tools(vec![])
- .memory(memory)
- .tool_dispatcher(Box::new(XmlDialect))
- .workspace_dir(workspace_dir)
- .event_context("pref-test-session", "pref-test-channel")
- .learning_enabled(learning_enabled)
- .explicit_preferences_enabled(explicit_preferences_enabled)
- .build()
- .unwrap()
-}
-
-fn make_real_memory(_workspace: &std::path::Path) -> Arc<dyn Memory> {
- Arc::new(crate::memory::tool_memory::test_helpers::MockMemory::default())
-}
-
-// ── bound_cached_transcript_messages — TAURI-RUST-7 trailing-strip ─────
-//
-// `bound_cached_transcript_messages` operates on a `Vec<ChatMessage>` (the
-// dispatcher-serialised wire format), so its detection runs through
-// `assistant_message_has_tool_calls`. Verify the symmetric trailing-strip
-// pops unpaired tool_calls envelopes while leaving plain assistant replies
-// untouched.
-
-fn tool_calls_envelope(id: &str) -> String {
- serde_json::json!({
- "content": "calling tool",
- "tool_calls": [{
- "id": id,
- "name": "shell",
- "arguments": "{}"
- }]
- })
- .to_string()
-}
-
-#[path = "turn_auto_recall_tests.rs"]
-mod turn_auto_recall_tests;
-#[path = "turn_checkpoint_and_wrapup_tests.rs"]
-mod turn_checkpoint_and_wrapup_tests;
-#[path = "turn_failed_turn_history_tests.rs"]
-mod turn_failed_turn_history_tests;
-#[path = "turn_final_reply_grounding_tests.rs"]
-mod turn_final_reply_grounding_tests;
-#[path = "turn_history_and_context_tests.rs"]
-mod turn_history_and_context_tests;
-#[path = "turn_learned_context_and_announcements_tests.rs"]
-mod turn_learned_context_and_announcements_tests;
-#[path = "turn_required_output_tests.rs"]
-mod turn_required_output_tests;
diff --git a/crates/openhuman-core/src/agent/harness/session/types_tests.rs b/crates/openhuman-core/src/agent/harness/session/types_tests.rs
deleted file mode 100644
index 77012c3a19..0000000000
--- a/crates/openhuman-core/src/agent/harness/session/types_tests.rs
+++ /dev/null
@@ -1,17 +0,0 @@
-use super::*;
-
-#[test]
-fn agent_builder_default_matches_new() {
- let builder = AgentBuilder::new();
- let default_builder = AgentBuilder::default();
-
- assert_eq!(builder.learning_enabled, default_builder.learning_enabled);
- assert_eq!(builder.auto_save, default_builder.auto_save);
- assert!(builder.turn_model_source.is_none());
- assert!(builder.tools.is_none());
- assert!(builder.memory.is_none());
- assert!(builder.event_session_id.is_none());
- assert!(builder.event_channel.is_none());
- assert!(builder.agent_definition_name.is_none());
- assert!(builder.post_turn_hooks.is_empty());
-}
diff --git a/crates/openhuman-core/src/agent/harness/subagent_runner/extract_tool.rs b/crates/openhuman-core/src/agent/harness/subagent_runner/extract_tool.rs
index 37e36e4476..04ab0a0e4b 100644
--- a/crates/openhuman-core/src/agent/harness/subagent_runner/extract_tool.rs
+++ b/crates/openhuman-core/src/agent/harness/subagent_runner/extract_tool.rs
@@ -25,14 +25,14 @@ use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex as StdMutex};
use async_trait::async_trait;
-use serde_json::{json, Value};
-use tinyagents_graph::parallel::{map_reduce, FailurePolicy, ParallelOptions};
+use serde_json::{Value, json};
+use tinyagents_graph::parallel::{FailurePolicy, ParallelOptions, map_reduce};
-use super::handoff::{chunk_content, ResultHandoffCache, HANDOFF_MAX_ENTRIES};
-use crate::agent::messages::{transcript_message_from_chat, ChatMessage};
+use super::handoff::{HANDOFF_MAX_ENTRIES, ResultHandoffCache, chunk_content};
+use crate::agent::messages::{ChatMessage, transcript_message_from_chat};
use crate::agent::tinyagents::TurnModelSource;
use tinyagents_session::transcript::{
- resolve_keyed_transcript_path, write_transcript, MessageUsage, TranscriptMeta, TurnUsage,
+ MessageUsage, TranscriptMeta, TurnUsage, resolve_keyed_transcript_path, write_transcript,
};
use tinyinference_llm::message::Message;
use tinyinference_llm::model::ModelRequest;
diff --git a/crates/openhuman-core/src/agent/harness/subagent_runner/handoff.rs b/crates/openhuman-core/src/agent/harness/subagent_runner/handoff.rs
index 5c29321e44..e04b01b2b8 100644
--- a/crates/openhuman-core/src/agent/harness/subagent_runner/handoff.rs
+++ b/crates/openhuman-core/src/agent/harness/subagent_runner/handoff.rs
@@ -35,8 +35,8 @@
// pre-migration module and in case a future caller needs them directly.
#[allow(unused_imports)]
pub(crate) use tinyagents_harness::handoff::{
- build_handoff_placeholder, chunk_content, clean_tool_output, CachedResult, ResultHandoffCache,
- HANDOFF_MAX_ENTRIES, HANDOFF_OVERSIZE_THRESHOLD_TOKENS, HANDOFF_PREVIEW_CHARS,
+ CachedResult, HANDOFF_MAX_ENTRIES, HANDOFF_OVERSIZE_THRESHOLD_TOKENS, HANDOFF_PREVIEW_CHARS,
+ ResultHandoffCache, build_handoff_placeholder, chunk_content, clean_tool_output,
};
/// Apply the progressive-disclosure handoff to a tool result. Resolves the
diff --git a/crates/openhuman-core/src/agent/harness/subagent_runner/mod.rs b/crates/openhuman-core/src/agent/harness/subagent_runner/mod.rs
index c50a7a09ec..26272cdca2 100644
--- a/crates/openhuman-core/src/agent/harness/subagent_runner/mod.rs
+++ b/crates/openhuman-core/src/agent/harness/subagent_runner/mod.rs
@@ -4,7 +4,7 @@
//! runner:
//!
//! 1. Reads the [`super::fork_context::ParentExecutionContext`] task-local
-//! set by the parent [`crate::agent::Agent::turn`].
+//! set by the parent [`crate::agent::OpenHumanSessionHost::turn`].
//! 2. Resolves the sub-agent's model name (inherit / hint / exact).
//! 3. Filters the parent's tool registry per `definition.tools`,
//! `disallowed_tools`, and `skill_filter` (or, in `fork` mode,
@@ -73,7 +73,7 @@ pub(crate) use tool_prep::build_text_mode_tool_instructions;
// Progressive-disclosure handoff: the tinyagents `HandoffMiddleware` intercepts
// oversized sub-agent tool results via `apply_handoff`, sharing the per-spawn
// `ResultHandoffCache` with the `extract_from_result` tool.
-pub(crate) use handoff::{apply_handoff, ResultHandoffCache};
+pub(crate) use handoff::{ResultHandoffCache, apply_handoff};
pub(crate) use ops::run_agent_turn_request_via_default_graph;
pub(crate) use ops::{append_subagent_role_contract, resolve_subagent_source};
diff --git a/crates/openhuman-core/src/agent/harness/subagent_runner/ops/graph.rs b/crates/openhuman-core/src/agent/harness/subagent_runner/ops/graph.rs
index 7fe34dd1f5..6187eeeeaf 100644
--- a/crates/openhuman-core/src/agent/harness/subagent_runner/ops/graph.rs
+++ b/crates/openhuman-core/src/agent/harness/subagent_runner/ops/graph.rs
@@ -46,7 +46,7 @@ mod worker_mirror;
#[cfg(test)]
pub(super) use dispatch::inherited_thread_id;
pub(crate) use dispatch::run_agent_turn_request_via_default_graph;
-pub(super) use dispatch::{run_subagent_via_graph, AggregatedUsage};
+pub(super) use dispatch::{AggregatedUsage, run_subagent_via_graph};
// Only what `graph_tests.rs`'s `use super::*` still needs directly (the rest
// of the original flat imports now live with the code that uses them, in
diff --git a/crates/openhuman-core/src/agent/harness/subagent_runner/ops/graph/dispatch.rs b/crates/openhuman-core/src/agent/harness/subagent_runner/ops/graph/dispatch.rs
index 87cf96bde7..0a55e46144 100644
--- a/crates/openhuman-core/src/agent/harness/subagent_runner/ops/graph/dispatch.rs
+++ b/crates/openhuman-core/src/agent/harness/subagent_runner/ops/graph/dispatch.rs
@@ -10,7 +10,7 @@ use crate::agent::harness::agent_graph::{AgentTurnRequest, AgentTurnResult, Agen
use crate::agent::harness::subagent_runner::types::SubagentRunError;
use crate::agent::messages::{ChatMessage, ConversationMessage};
use crate::agent::progress::AgentProgress;
-use crate::agent::tinyagents::{run_turn_via_tinyagents_shared, SubagentScope};
+use crate::agent::tinyagents::{SubagentScope, run_turn_via_tinyagents_shared};
use crate::inference::tokenjuice::AgentTokenjuiceCompression;
use tinyagents_harness::run_queue::RunQueue;
use tinytools::WorkspaceDescriptor;
diff --git a/crates/openhuman-core/src/agent/harness/subagent_runner/ops/graph/worker_mirror.rs b/crates/openhuman-core/src/agent/harness/subagent_runner/ops/graph/worker_mirror.rs
index 7453692ad9..49fed9d05c 100644
--- a/crates/openhuman-core/src/agent/harness/subagent_runner/ops/graph/worker_mirror.rs
+++ b/crates/openhuman-core/src/agent/harness/subagent_runner/ops/graph/worker_mirror.rs
@@ -19,7 +19,7 @@ fn append_worker_message(
sender: &str,
metadata: serde_json::Value,
) {
- use crate::memory::conversations::{append_message, ConversationMessage as StoredMessage};
+ use crate::memory::conversations::{ConversationMessage as StoredMessage, append_message};
let mut extra = serde_json::json!({
"scope": "worker_thread",
"agent_id": agent_id,
diff --git a/crates/openhuman-core/src/agent/harness/subagent_runner/ops/graph_tests.rs b/crates/openhuman-core/src/agent/harness/subagent_runner/ops/graph_tests.rs
index 352ce51ad0..d9bb75aae3 100644
--- a/crates/openhuman-core/src/agent/harness/subagent_runner/ops/graph_tests.rs
+++ b/crates/openhuman-core/src/agent/harness/subagent_runner/ops/graph_tests.rs
@@ -562,7 +562,7 @@ impl<S: tracing::Subscriber> tracing_subscriber::Layer<S> for WarnLayer {
let mut message = Message(None);
event.record(&mut message);
if let Some(text) = message.0 {
- self.0 .0.lock().unwrap().push(text);
+ self.0.0.lock().unwrap().push(text);
}
}
}
diff --git a/crates/openhuman-core/src/agent/harness/subagent_runner/ops/mod.rs b/crates/openhuman-core/src/agent/harness/subagent_runner/ops/mod.rs
index c7b94c9442..99cacb3c1e 100644
--- a/crates/openhuman-core/src/agent/harness/subagent_runner/ops/mod.rs
+++ b/crates/openhuman-core/src/agent/harness/subagent_runner/ops/mod.rs
@@ -54,9 +54,9 @@ pub(crate) use provider::resolve_subagent_source;
#[cfg(test)]
use prompt::dedup_tool_specs_by_name;
#[cfg(test)]
-use provider::normalize_slug;
-#[cfg(test)]
pub(super) use provider::LazyToolkitResolver;
+#[cfg(test)]
+use provider::normalize_slug;
// filter_tool_indices lives in tool_prep (sibling of ops).
#[cfg(test)]
pub(super) use super::tool_prep::filter_tool_indices;
@@ -68,7 +68,7 @@ pub(super) use crate::agent::harness::definition::{AgentDefinition, PromptSource
#[cfg(test)]
pub(super) use crate::agent::harness::fork_context::ParentExecutionContext;
#[cfg(test)]
-pub(super) use crate::agent::harness::{with_spawn_depth, MAX_SPAWN_DEPTH};
+pub(super) use crate::agent::harness::{MAX_SPAWN_DEPTH, with_spawn_depth};
#[cfg(test)]
use tinytools::ToolSpec;
diff --git a/crates/openhuman-core/src/agent/harness/subagent_runner/ops/prompt.rs b/crates/openhuman-core/src/agent/harness/subagent_runner/ops/prompt.rs
index 306831d9f7..bc45cf658d 100644
--- a/crates/openhuman-core/src/agent/harness/subagent_runner/ops/prompt.rs
+++ b/crates/openhuman-core/src/agent/harness/subagent_runner/ops/prompt.rs
@@ -4,7 +4,7 @@
//! deduplication helper used before sending specs to the provider.
use crate::agent::harness::artifact_offload::{
- render_artifact_offload_contract, should_render_offload_contract, ARTIFACT_OFFLOAD_HEADING,
+ ARTIFACT_OFFLOAD_HEADING, render_artifact_offload_contract, should_render_offload_contract,
};
use std::collections::HashSet;
use tinytools::ToolSpec;
diff --git a/crates/openhuman-core/src/agent/harness/subagent_runner/ops/runner.rs b/crates/openhuman-core/src/agent/harness/subagent_runner/ops/runner.rs
index cf80225a70..c78db12ce8 100644
--- a/crates/openhuman-core/src/agent/harness/subagent_runner/ops/runner.rs
+++ b/crates/openhuman-core/src/agent/harness/subagent_runner/ops/runner.rs
@@ -13,13 +13,12 @@ use std::time::Instant;
use crate::agent::file_state::with_file_state_agent_id;
use crate::agent::harness::agent_graph::{AgentTurnRequest, AgentTurnUsage};
use crate::agent::harness::artifact_offload::{
- effective_offload_threshold, extract_artifact_paths, new_artifact_offload,
- note_artifact_handoff, offload_oversized_result, DEFAULT_OFFLOAD_THRESHOLD_BYTES,
- HANDOFF_STAGE_RECORDED,
+ DEFAULT_OFFLOAD_THRESHOLD_BYTES, HANDOFF_STAGE_RECORDED, effective_offload_threshold,
+ extract_artifact_paths, new_artifact_offload, note_artifact_handoff, offload_oversized_result,
};
use crate::agent::harness::definition::{
- validate_tier_transition, AgentDefinition, AgentDefinitionRegistry, AgentTier, IterationPolicy,
- PromptSource, SandboxMode as AgentSandboxMode,
+ AgentDefinition, AgentDefinitionRegistry, AgentTier, IterationPolicy, PromptSource,
+ SandboxMode as AgentSandboxMode, validate_tier_transition,
};
use crate::agent::harness::fork_context::ParentExecutionContext;
use crate::agent::harness::subagent_runner::extract_tool::ExtractFromResultTool;
@@ -34,14 +33,14 @@ use crate::agent::harness::subagent_runner::types::{
SubagentMode, SubagentRunError, SubagentRunOptions, SubagentRunOutcome, SubagentRunStatus,
SubagentUsage,
};
-use crate::agent::harness::{with_current_sandbox_mode, with_spawn_depth, MAX_SPAWN_DEPTH};
+use crate::agent::harness::{MAX_SPAWN_DEPTH, with_current_sandbox_mode, with_spawn_depth};
use crate::agent::prompts::{
- render_subagent_system_prompt_with_format, PromptContext, PromptTool, SubagentRenderOptions,
+ PromptContext, PromptTool, SubagentRenderOptions, render_subagent_system_prompt_with_format,
};
use crate::inference::provider::AGENT_TURN_MAX_OUTPUT_TOKENS;
use crate::memory::api::provider::retrieval::{FastRetrieveQuery, RetrievalResponse};
use crate::memory::source_scope::as_bus_scope;
-use tinyagents_harness::tool::{rank_tools_by_prompt, SelectableTool, MIN_CONFIDENT_HITS};
+use tinyagents_harness::tool::{MIN_CONFIDENT_HITS, SelectableTool, rank_tools_by_prompt};
use tinytools::{
SandboxMode as TinyagentsSandboxMode, Tool, ToolCategory, ToolSpec, WorkspaceDescriptor,
};
@@ -50,7 +49,7 @@ 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, LazyToolkitResolver,
+ LazyToolkitResolver, resolve_subagent_source, user_is_signed_in_to_composio,
};
/// Runtime spawn-hierarchy gate decision for one delegation hop.
@@ -1032,7 +1031,7 @@ async fn run_typed_mode(
};
use crate::integrations::composio::client::{
- create_composio_client, ComposioClientKind,
+ ComposioClientKind, create_composio_client,
};
let client_kind = match create_composio_client(arc_config.as_ref()) {
Ok(k) => Some(k),
@@ -1321,7 +1320,7 @@ async fn run_typed_mode(
for tool in &dynamic_tools {
allowed_names.insert(tool.name().to_string());
}
- let filtered_specs = crate::agent::harness::session::dedup_visible_tool_specs(filtered_specs);
+ let filtered_specs = crate::agent::session_host::dedup_visible_tool_specs(filtered_specs);
let filtered_specs = dedup_tool_specs_by_name(&definition.id, filtered_specs);
tracing::debug!(
diff --git a/crates/openhuman-core/src/agent/harness/subagent_runner/ops/runner_fast_path_tests_tests.rs b/crates/openhuman-core/src/agent/harness/subagent_runner/ops/runner_fast_path_tests_tests.rs
index 4169fa8753..42812f1fcc 100644
--- a/crates/openhuman-core/src/agent/harness/subagent_runner/ops/runner_fast_path_tests_tests.rs
+++ b/crates/openhuman-core/src/agent/harness/subagent_runner/ops/runner_fast_path_tests_tests.rs
@@ -1,6 +1,6 @@
use super::{
- apply_max_result_chars, format_deterministic_memory_hits, parse_memory_fast_path_enabled,
- MEMORY_FAST_PATH_LIMIT,
+ MEMORY_FAST_PATH_LIMIT, apply_max_result_chars, format_deterministic_memory_hits,
+ parse_memory_fast_path_enabled,
};
use crate::memory::api::provider::retrieval::{RetrievalHit, RetrievalNodeKind, RetrievalResponse};
use chrono::Utc;
diff --git a/crates/openhuman-core/src/agent/harness/subagent_runner/ops_tests_slug_filter_typed_mode_tests.rs b/crates/openhuman-core/src/agent/harness/subagent_runner/ops_tests_slug_filter_typed_mode_tests.rs
index 009a9d7b41..7598025aa7 100644
--- a/crates/openhuman-core/src/agent/harness/subagent_runner/ops_tests_slug_filter_typed_mode_tests.rs
+++ b/crates/openhuman-core/src/agent/harness/subagent_runner/ops_tests_slug_filter_typed_mode_tests.rs
@@ -184,12 +184,16 @@ async fn typed_mode_system_prompt_includes_subagent_role_contract() {
.find(|m| m.role == "system")
.expect("system message should be present");
assert!(system_msg.content.contains("## Sub-agent Role Contract"));
- assert!(system_msg
- .content
- .contains("You are a sub-agent working for a parent OpenHuman agent"));
- assert!(system_msg
- .content
- .contains("Keep your final response concise and synthesis-ready"));
+ assert!(
+ system_msg
+ .content
+ .contains("You are a sub-agent working for a parent OpenHuman agent")
+ );
+ assert!(
+ system_msg
+ .content
+ .contains("Keep your final response concise and synthesis-ready")
+ );
}
#[tokio::test]
diff --git a/crates/openhuman-core/src/agent/harness/subagent_runner/tool_prep.rs b/crates/openhuman-core/src/agent/harness/subagent_runner/tool_prep.rs
index 64c71e941c..1a5f00e357 100644
--- a/crates/openhuman-core/src/agent/harness/subagent_runner/tool_prep.rs
+++ b/crates/openhuman-core/src/agent/harness/subagent_runner/tool_prep.rs
@@ -233,8 +233,8 @@ pub(crate) fn subagent_prompt_protocol(
text_mode: bool,
) -> (crate::agent::prompts::ToolCallFormat, String) {
use crate::agent::prompts::ToolCallFormat;
- use tinytools_agent::dialect::{NativeDialect, PFormatDialect, ToolDialect, XmlDialect};
use tinytools_agent::PFormatRegistry;
+ use tinytools_agent::dialect::{NativeDialect, PFormatDialect, ToolDialect, XmlDialect};
if text_mode {
return (ToolCallFormat::PFormat, String::new());
}
diff --git a/crates/openhuman-core/src/agent/harness/subagent_runner/tool_prep_tests.rs b/crates/openhuman-core/src/agent/harness/subagent_runner/tool_prep_tests.rs
index 3fc75ad852..1e7dae5286 100644
--- a/crates/openhuman-core/src/agent/harness/subagent_runner/tool_prep_tests.rs
+++ b/crates/openhuman-core/src/agent/harness/subagent_runner/tool_prep_tests.rs
@@ -58,7 +58,7 @@ fn unprefixed_delegate_name_overrides_are_treated_as_spawn_tools() {
// ── Essential-action reservation (#6033) ────────────────────────────────
use crate::agent::prompts::ConnectedIntegrationTool;
-use tinyagents_harness::tool::{rank_tools_by_prompt, SelectableTool};
+use tinyagents_harness::tool::{SelectableTool, rank_tools_by_prompt};
fn action(name: &str) -> ConnectedIntegrationTool {
ConnectedIntegrationTool {
@@ -275,7 +275,10 @@ fn gmail_read_prompt_keeps_a_content_returning_action() {
names.contains(&"GMAIL_FETCH_EMAILS"),
"prompt {prompt:?} must keep a content-returning action; got {names:?}"
);
- assert!(selected.len() <= 12, "prompt {prompt:?} exceeded the budget");
+ assert!(
+ selected.len() <= 12,
+ "prompt {prompt:?} exceeded the budget"
+ );
assert_eq!(
selected.len(),
selected
diff --git a/crates/openhuman-core/src/agent/harness/subagent_runner/tool_ranking_tests.rs b/crates/openhuman-core/src/agent/harness/subagent_runner/tool_ranking_tests.rs
index 9b2a13f4a9..c54e8c7ac6 100644
--- a/crates/openhuman-core/src/agent/harness/subagent_runner/tool_ranking_tests.rs
+++ b/crates/openhuman-core/src/agent/harness/subagent_runner/tool_ranking_tests.rs
@@ -10,7 +10,7 @@
//! moving up with the algorithm.
use crate::agent::prompts::ConnectedIntegrationTool;
-use tinyagents_harness::tool::{rank_tools_by_prompt, SelectableTool, MIN_CONFIDENT_HITS};
+use tinyagents_harness::tool::{MIN_CONFIDENT_HITS, SelectableTool, rank_tools_by_prompt};
fn rank_actions_by_prompt(
prompt: &str,
diff --git a/crates/openhuman-core/src/agent/harness/tool_result_artifacts/mod.rs b/crates/openhuman-core/src/agent/harness/tool_result_artifacts/mod.rs
index 3d4a385036..aa54b2c30b 100644
--- a/crates/openhuman-core/src/agent/harness/tool_result_artifacts/mod.rs
+++ b/crates/openhuman-core/src/agent/harness/tool_result_artifacts/mod.rs
@@ -9,7 +9,7 @@
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
-use crate::memory::safety::{sanitize_text, SanitizationReport, Sanitized};
+use crate::memory::safety::{SanitizationReport, Sanitized, sanitize_text};
use async_trait::async_trait;
use serde_json::Value;
use tinyagents_harness::store::Store;
diff --git a/crates/openhuman-core/src/agent/harness/tool_result_artifacts/mod_tests.rs b/crates/openhuman-core/src/agent/harness/tool_result_artifacts/mod_tests.rs
index afa8a4a78d..37ef4b1e77 100644
--- a/crates/openhuman-core/src/agent/harness/tool_result_artifacts/mod_tests.rs
+++ b/crates/openhuman-core/src/agent/harness/tool_result_artifacts/mod_tests.rs
@@ -44,9 +44,11 @@ async fn threshold_persists_preview_and_readable_file() {
.unwrap();
assert!(!read.is_error, "{}", read.output());
assert!(read.output().contains("xxxx"));
- assert!(!read
- .output()
- .contains("ghp_abcdefghijklmnopqrstuvwxyz123456"));
+ assert!(
+ !read
+ .output()
+ .contains("ghp_abcdefghijklmnopqrstuvwxyz123456")
+ );
}
#[tokio::test]
@@ -72,10 +74,11 @@ async fn persisted_preview_is_bounded_for_small_budget() {
assert!(outcome.final_bytes <= 320, "final={}", outcome.final_bytes);
assert_eq!(out.len(), outcome.final_bytes);
assert!(out.contains("[tool_result_preview]"));
- assert!(tmp
- .path()
- .join("artifacts/tool-results/session/shell/call.txt")
- .exists());
+ assert!(
+ tmp.path()
+ .join("artifacts/tool-results/session/shell/call.txt")
+ .exists()
+ );
}
#[tokio::test]
@@ -109,10 +112,11 @@ async fn aggregate_spills_largest_until_under_budget() {
let total: usize = results.iter().map(|result| result.output.len()).sum();
assert!(total <= 1800, "total={total}");
assert!(!results[0].output.starts_with("[tool_result_preview]\n"));
- assert!(tmp
- .path()
- .join("artifacts/tool-results/session/largest/largest.txt")
- .exists());
+ assert!(
+ tmp.path()
+ .join("artifacts/tool-results/session/largest/largest.txt")
+ .exists()
+ );
}
#[tokio::test]
@@ -158,10 +162,11 @@ async fn aggregate_forces_budget_when_envelope_has_no_savings() {
total <= results.len() * MIN_ENVELOPE_ALLOWANCE_BYTES,
"total={total} exceeds the per-result envelope floor bound"
);
- assert!(tmp
- .path()
- .join("artifacts/tool-results/session/one/one.txt")
- .exists());
+ assert!(
+ tmp.path()
+ .join("artifacts/tool-results/session/one/one.txt")
+ .exists()
+ );
}
#[test]
@@ -230,11 +235,13 @@ fn artifact_read_target_matches_only_file_read_under_the_artifact_directory() {
#[test]
fn artifact_read_target_matches_the_artifact_directory_as_a_path_component() {
- assert!(artifact_read_target(
- "file_read",
- &json!({"path": "./artifacts/tool-results/s/c.txt"})
- )
- .is_some());
+ assert!(
+ artifact_read_target(
+ "file_read",
+ &json!({"path": "./artifacts/tool-results/s/c.txt"})
+ )
+ .is_some()
+ );
assert_eq!(
artifact_read_target(
"file_read",
diff --git a/crates/openhuman-core/src/agent/learning/README.md b/crates/openhuman-core/src/agent/learning/README.md
index bc20a45c2d..689bc0efb0 100644
--- a/crates/openhuman-core/src/agent/learning/README.md
+++ b/crates/openhuman-core/src/agent/learning/README.md
@@ -112,7 +112,7 @@ These are subscriber registrations rather than a single `bus.rs`; subscriptions
## Used by
- `crates/openhuman-core/src/core/all.rs` — registers the `learning.*` controllers + schemas.
-- `crates/openhuman-core/src/agent/harness/session/builder/factory.rs` (registers `LearnedContextSection` / `UserProfileSection` and the `ReflectionHook` when `config.learning.enabled`), `builder/helpers.rs` (`MemoryAccessSection` / `MemoryWriteSection` gated by `any_tool_offered`), `turn/context.rs` (reads the `learning_observations` / `learning_patterns` / reflections namespaces into `PromptContext.learned`), `turn/session_io/background_tasks.rs` (`transcript_ingest::ingest_transcript_path`), and `agent/tinyagents/host/learning_sink.rs` (`ToolTrackerHook` + `UserProfileHook` post-turn fan-out).
+- `crates/openhuman-core/src/agent/session_host/builder/factory.rs` (registers `LearnedContextSection` / `UserProfileSection` and the `ReflectionHook` when `config.learning.enabled`), `builder/helpers.rs` (`MemoryAccessSection` / `MemoryWriteSection` gated by `any_tool_offered`), `turn/context.rs` (reads the `learning_observations` / `learning_patterns` / reflections namespaces into `PromptContext.learned`), `turn/session_io/background_tasks.rs` (`transcript_ingest::ingest_transcript_path`), and `agent/tinyagents/host/learning_sink.rs` (`ToolTrackerHook` + `UserProfileHook` post-turn fan-out).
- `learning::startup::register_learning_subscribers` is the entry point that wires the Phase 2/3/4 subscribers; it is invoked from `crates/openhuman-core/src/core/jsonrpc.rs` (`register_domain_subscribers`, inside the `plan.agent` block — i.e. whenever the `DomainSet` allows `DomainGroup::Agent` — guarded by `learning_first_time()`), not from the skippable `channels::runtime::startup` path — see the "why" note in `startup.rs` (#5003).
- `crates/openhuman-core/src/modules/memory/people_chunks_retrieval.rs` (`impl MemoryProfile for ModuleMemoryProvider`, the driver `FacetCache` reaches through the guard), `integrations/composio/profile_md.rs` (`replace_managed_block`, used by `profile_md_renderer.rs`), `tools/impl/system/tool_stats.rs`, `tools/schemas.rs` — consume facet/learning types.
diff --git a/crates/openhuman-core/src/agent/learning/transcript_ingest/mod.rs b/crates/openhuman-core/src/agent/learning/transcript_ingest/mod.rs
index a24b6b01b0..eb4145d12e 100644
--- a/crates/openhuman-core/src/agent/learning/transcript_ingest/mod.rs
+++ b/crates/openhuman-core/src/agent/learning/transcript_ingest/mod.rs
@@ -59,7 +59,7 @@ const PERSIST_CONCURRENCY: usize = 8;
///
/// Background-first: callers should invoke this from a `tokio::spawn` so
/// chat latency is unaffected (see
-/// `Agent::spawn_transcript_ingestion`). Failures are returned but the
+/// `OpenHumanSessionHost::spawn_transcript_ingestion`). Failures are returned but the
/// caller should generally just log them — ingestion is best-effort and
/// retried on the next transcript write.
pub async fn ingest_transcript_path(
diff --git a/crates/openhuman-core/src/agent/mod.rs b/crates/openhuman-core/src/agent/mod.rs
index 0cc3748645..5b6531ab9e 100644
--- a/crates/openhuman-core/src/agent/mod.rs
+++ b/crates/openhuman-core/src/agent/mod.rs
@@ -6,7 +6,7 @@
//!
//! ## Key Components
//!
-//! - **[`harness::session::Agent`]**: The primary entry point for running a
+//! - **[`session_host::OpenHumanSessionHost`]**: The primary entry point for running a
//! conversation. It manages the loop of sending prompts to a provider and
//! executing the resulting tool calls.
//! - **[`crate::agent::registry::agents`]**: Definitions for built-in
@@ -61,6 +61,10 @@ pub mod queued_turn;
pub mod registry;
mod schemas;
pub mod session_db;
+/// OpenHuman's composition and policy layer around the neutral TinyAgents
+/// session runtime. Generic history, transcript delta, prefix and tool
+/// snapshots are owned by `tinyagents-runtime`.
+pub mod session_host;
pub mod session_import;
pub mod stop_hooks;
pub mod task_dispatcher;
@@ -92,4 +96,4 @@ pub use schemas::{
mod tests;
#[allow(unused_imports)]
-pub use harness::session::{Agent, AgentBuilder};
+pub use session_host::{OpenHumanSessionHost, SessionHostBuilder, TurnOverrides};
diff --git a/crates/openhuman-core/src/agent/orchestration/parent_context/builder.rs b/crates/openhuman-core/src/agent/orchestration/parent_context/builder.rs
index 9b00019099..5fe32d9e38 100644
--- a/crates/openhuman-core/src/agent/orchestration/parent_context/builder.rs
+++ b/crates/openhuman-core/src/agent/orchestration/parent_context/builder.rs
@@ -31,7 +31,7 @@ use anyhow::{Context, Result};
use crate::agent::harness::fork_context::{
current_parent, with_parent_context, ParentExecutionContext,
};
-use crate::agent::Agent;
+use crate::agent::OpenHumanSessionHost;
use crate::config::Config;
const LOG_TARGET: &str = "agent_orchestration::parent_context";
@@ -83,7 +83,7 @@ pub(crate) async fn build_root_parent(
}
}
- let mut agent = Agent::from_config(config)
+ let mut agent = OpenHumanSessionHost::from_config(config)
.context("build Agent from config for orchestration root parent")?;
let integrations = crate::integrations::composio::fetch_connected_integrations(config).await;
diff --git a/crates/openhuman-core/src/agent/orchestration/tools/spawn_parallel_agents_tests.rs b/crates/openhuman-core/src/agent/orchestration/tools/spawn_parallel_agents_tests.rs
index 9f8f846e35..e7554ee579 100644
--- a/crates/openhuman-core/src/agent/orchestration/tools/spawn_parallel_agents_tests.rs
+++ b/crates/openhuman-core/src/agent/orchestration/tools/spawn_parallel_agents_tests.rs
@@ -11,7 +11,7 @@ use crate::agent::orchestration::spawn_parallel_graph::{
};
use crate::agent::prompts::ToolCallFormat;
use crate::agent::tinyagents::host::OpenHumanRunContext;
-use crate::agent::Agent;
+use crate::agent::OpenHumanSessionHost;
use crate::config::AgentConfig;
use crate::memory::{Memory, MemoryCategory, MemoryEntry, NamespaceSummary, RecallOpts};
use async_trait::async_trait;
@@ -600,7 +600,7 @@ async fn agent_turn_runs_long_parallel_subagent_flow_with_many_nested_tool_calls
}),
];
- let mut agent = Agent::builder()
+ let mut agent = OpenHumanSessionHost::builder()
.chat_model(Arc::new(provider.clone()))
.tools(tools)
.memory(mem)
diff --git a/crates/openhuman-core/src/agent/orchestration/tools/spawn_subagent_tests.rs b/crates/openhuman-core/src/agent/orchestration/tools/spawn_subagent_tests.rs
index 8fdcb23bc3..7fc4ac2840 100644
--- a/crates/openhuman-core/src/agent/orchestration/tools/spawn_subagent_tests.rs
+++ b/crates/openhuman-core/src/agent/orchestration/tools/spawn_subagent_tests.rs
@@ -156,7 +156,7 @@ async fn no_registry_returns_clear_error() {
.unwrap();
// Either: registry uninitialised → clear init error, OR
// registry was initialised by a previous test → "no parent context"
- // because we're not running inside an Agent::turn. Both are
+ // because we're not running inside an OpenHumanSessionHost::turn. Both are
// acceptable: the tool gracefully refuses.
assert!(result.is_error);
}
diff --git a/crates/openhuman-core/src/agent/orchestration/workflow_runs/engine.rs b/crates/openhuman-core/src/agent/orchestration/workflow_runs/engine.rs
index 071d321583..c32b7280a8 100644
--- a/crates/openhuman-core/src/agent/orchestration/workflow_runs/engine.rs
+++ b/crates/openhuman-core/src/agent/orchestration/workflow_runs/engine.rs
@@ -21,7 +21,7 @@
//!
//! The fix mirrors the production blueprint in
//! [`crate::agent::triage::escalation`]: build a *root*
-//! [`ParentExecutionContext`] from a real [`Agent`] (`Agent::from_config`) and
+//! [`ParentExecutionContext`] from a real [`Agent`] (`OpenHumanSessionHost::from_config`) and
//! run the whole phase loop inside [`with_parent_context`]. Every
//! `spawn_agent` call nested in that scope then resolves `current_parent()` to
//! the root, inheriting a real provider, tool registry, memory, and model — the
diff --git a/crates/openhuman-core/src/agent/progress.rs b/crates/openhuman-core/src/agent/progress.rs
index 9c80c85482..0e16f888a0 100644
--- a/crates/openhuman-core/src/agent/progress.rs
+++ b/crates/openhuman-core/src/agent/progress.rs
@@ -2,7 +2,7 @@
//!
//! Consumers (e.g. the web channel provider) create an
//! `mpsc::Sender<AgentProgress>` and attach it to the [`Agent`] via
-//! [`Agent::set_on_progress`] before calling [`Agent::run_single`].
+//! [`OpenHumanSessionHost::set_on_progress`] before calling [`OpenHumanSessionHost::run_single`].
//! The agent's turn loop sends events through this channel as it
//! progresses — tool calls starting/completing, iteration boundaries,
//! sub-agent lifecycle, etc.
diff --git a/crates/openhuman-core/src/agent/progress_sink.rs b/crates/openhuman-core/src/agent/progress_sink.rs
index 48570c5686..d53bc04484 100644
--- a/crates/openhuman-core/src/agent/progress_sink.rs
+++ b/crates/openhuman-core/src/agent/progress_sink.rs
@@ -3,10 +3,10 @@
//!
//! The agent harness already emits everything an embedder needs
//! ([`AgentProgress`], attached with
-//! [`Agent::set_on_progress`](crate::agent::Agent::set_on_progress)),
+//! [`OpenHumanSessionHost::set_on_progress`](crate::agent::OpenHumanSessionHost::set_on_progress)),
//! but RPC entry points such as
//! [`agent_chat`](crate::inference::host_runtime::ops::agent_chat) build the
-//! [`Agent`](crate::agent::Agent) internally and drop it, so there is
+//! [`Agent`](crate::agent::OpenHumanSessionHost) internally and drop it, so there is
//! no handle to attach a sink to. A host embedding the core in-process therefore
//! sees nothing at all for the whole turn — no tool calls, no deltas — and can
//! only guess whether a long turn is alive.
@@ -37,7 +37,7 @@
use crate::agent::progress::AgentProgress;
/// The channel an embedder hands to [`with_progress_sink`], and the same type
-/// [`Agent::set_on_progress`](crate::agent::Agent::set_on_progress)
+/// [`OpenHumanSessionHost::set_on_progress`](crate::agent::OpenHumanSessionHost::set_on_progress)
/// takes — so a sink read back out of the task-local can be attached directly.
///
/// Use a bounded channel with headroom: the turn loop sends from inside the
@@ -47,7 +47,7 @@ pub type ProgressSink = tokio::sync::mpsc::Sender<AgentProgress>;
tokio::task_local! {
/// Per-turn progress sink scoped by an in-process embedder around the
/// future it awaits. Read by entry points that build an
- /// [`Agent`](crate::agent::Agent) internally.
+ /// [`Agent`](crate::agent::OpenHumanSessionHost) internally.
pub static AGENT_PROGRESS_SINK: ProgressSink;
}
diff --git a/crates/openhuman-core/src/agent/progress_tracing/journal_projection.rs b/crates/openhuman-core/src/agent/progress_tracing/journal_projection.rs
index c375c447dd..07fd045252 100644
--- a/crates/openhuman-core/src/agent/progress_tracing/journal_projection.rs
+++ b/crates/openhuman-core/src/agent/progress_tracing/journal_projection.rs
@@ -485,6 +485,9 @@ fn observation_to_progress(obs: &AgentObservation, state: &mut ReplayState) -> V
// what the trace records. The live bridge logs them and emits no
// `AgentProgress` for any of them either.
| AgentEvent::ToolsFiltered { .. }
+ | AgentEvent::ToolsAdvertised { .. }
+ | AgentEvent::ToolSearched { .. }
+ | AgentEvent::DeferredToolCall { .. }
| AgentEvent::WorkspacePrepared { .. }
| AgentEvent::WorkspaceViolation { .. }
| AgentEvent::WorkspaceCleanup { .. }
diff --git a/crates/openhuman-core/src/agent/prompts/README.md b/crates/openhuman-core/src/agent/prompts/README.md
index 5ef1f95ddd..0f4fe6e4bb 100644
--- a/crates/openhuman-core/src/agent/prompts/README.md
+++ b/crates/openhuman-core/src/agent/prompts/README.md
@@ -85,11 +85,11 @@ Other domains contribute prompt content without living in this directory:
- `agent/learning/prompt_sections.rs` — `LearnedContextSection`,
`UserProfileSection`, `MemoryAccessSection`, `MemoryWriteSection`
- (`PromptSection` impls, config-gated; `agent/harness/session/builder/factory.rs`
+ (`PromptSection` impls, config-gated; `agent/session_host/builder/factory.rs`
and `.../builder/helpers.rs` append them with `add_section` /
`insert_section_before` when learning or explicit preferences are enabled).
- `tools/agent_policy/prompt.rs` — `render_tool_policy_boundary` is not a
- section: `agent/harness/session/turn/context.rs` string-appends its
+ section: `agent/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.
@@ -97,7 +97,7 @@ Built-in archetype system prompts (orchestrator, welcome, integrations_agent,
…) live in `agent/registry/agents/<name>/prompt.rs` and
`flows/agents/{flow_discovery,workflow_builder}/prompt.rs`, not here. Each is a
`PromptSource::Dynamic` function that hand-assembles its body via the
-`render_*` helpers; `agent/harness/session/builder/factory.rs` wraps it with
+`render_*` helpers; `agent/session_host/builder/factory.rs` wraps it with
`SystemPromptBuilder::from_dynamic`.
## Builder entry points
@@ -122,7 +122,7 @@ three chains share the same anti-fabrication floor and style rules.
## KV-cache / prefix stability
The rendered prompt is built once per session and reused on every turn
-(`agent/harness/session/turn/context.rs`) so the inference backend's prefix
+(`agent/session_host/turn/context.rs`) so the inference backend's prefix
cache hits. `PromptSection::tier()` (`PromptTier::Stable` / `Context` /
`Volatile`, default `Stable`) controls emission order in
`SystemPromptBuilder::build_tiered`: stable bytes (identity, tools, safety,
@@ -139,10 +139,10 @@ rather than "N days ago".
## Used by
-- `agent/harness/session/turn/context.rs` — loads `AGENTS.md` layers and
+- `agent/session_host/turn/context.rs` — loads `AGENTS.md` layers and
connected identities into `PromptContext`, calls the builder, appends the
tool-policy boundary.
-- `agent/harness/session/builder/factory.rs` — picks the entry point per
+- `agent/session_host/builder/factory.rs` — picks the entry point per
`PromptSource` and registers the learning/profile sections.
- `agent/debug/` — `dump_agent_prompt` / `dump_all_agent_prompts` (`mod.rs`)
build the same `PromptContext` to render each agent's prompt,
diff --git a/crates/openhuman-core/src/agent/prompts/mod_tests_user_files_reflections_tests.rs b/crates/openhuman-core/src/agent/prompts/mod_tests_user_files_reflections_tests.rs
index 41ea8fa77f..29fbe79f68 100644
--- a/crates/openhuman-core/src/agent/prompts/mod_tests_user_files_reflections_tests.rs
+++ b/crates/openhuman-core/src/agent/prompts/mod_tests_user_files_reflections_tests.rs
@@ -107,7 +107,7 @@ fn rendered_subagent_system_prompt_is_byte_stable_across_repeat_calls() {
#[test]
fn for_subagent_builder_injects_user_files_even_when_identity_omitted() {
// Regression pin for the review finding: the runtime Tauri chat
- // path spins welcome/trigger_* via `Agent::from_config_for_agent`
+ // path spins welcome/trigger_* via `OpenHumanSessionHost::from_config_for_agent`
// → `SystemPromptBuilder::for_subagent(body, omit_identity=true, …)`,
// which deliberately drops `IdentitySection`. Before
// `UserFilesSection` existed, our PROFILE/MEMORY injection lived
diff --git a/crates/openhuman-core/src/agent/prompts/types.rs b/crates/openhuman-core/src/agent/prompts/types.rs
index 4f61ad3255..353465c7cf 100644
--- a/crates/openhuman-core/src/agent/prompts/types.rs
+++ b/crates/openhuman-core/src/agent/prompts/types.rs
@@ -264,7 +264,7 @@ impl<'a> PromptTool<'a> {
///
/// An agent's callable surface is not one contiguous slice: the durable
/// registry and the freshly-synthesised delegation set live in separate
- /// `Arc`s (see `Agent::synthesized_tools`), and the prompt catalogue must
+ /// `Arc`s (see `OpenHumanSessionHost::synthesized_tools`), and the prompt catalogue must
/// render both. Taking an iterator lets the caller chain them without
/// materialising a combined `Vec<Box<dyn Tool>>` — which is impossible
/// anyway, since `Box<dyn Tool>` is not cloneable.
diff --git a/crates/openhuman-core/src/agent/registry/README.md b/crates/openhuman-core/src/agent/registry/README.md
index 29b9fc1a49..fa5513c38e 100644
--- a/crates/openhuman-core/src/agent/registry/README.md
+++ b/crates/openhuman-core/src/agent/registry/README.md
@@ -136,7 +136,7 @@ orchestrator tool synthesis in `tools/orchestrator_tools.rs` and
- `agent/harness/builtin_definitions.rs` — `load_builtins()` seeds the
process-global `AgentDefinitionRegistry`; `agent/harness/definition/registry.rs`
calls `validate_tier_hierarchy` again after workspace overrides merge.
-- `agent/harness/session/builder/factory.rs` —
+- `agent/session_host/builder/factory.rs` —
`Agent::from_config_for_agent` falls back to `find_custom_in_config` +
`definition_from_registry_entry` when an id is not in the harness registry.
- `agent/schemas.rs` — `agent.graph_topologies` and `agent.registry_snapshot`
diff --git a/crates/openhuman-core/src/agent/registry/agents/fleet_prompt_tests.rs b/crates/openhuman-core/src/agent/registry/agents/fleet_prompt_tests.rs
index 907dbdc78e..52cee63613 100644
--- a/crates/openhuman-core/src/agent/registry/agents/fleet_prompt_tests.rs
+++ b/crates/openhuman-core/src/agent/registry/agents/fleet_prompt_tests.rs
@@ -376,8 +376,7 @@ fn every_prompt_names_at_least_one_tool_it_can_call() {
/// are reworded, that judge silently grades against a different standard.
#[test]
fn close_verification_rubric_keeps_its_three_rules() {
- let rubric =
- crate::agent::harness::session::turn_checkpoint::close_verification_prompt("", "", "");
+ let rubric = crate::agent::session_host::turn_checkpoint::close_verification_prompt("", "", "");
for stem in [
"1. The reply only says what the assistant will do",
"2. The reply states something the tool records contradict",
diff --git a/crates/openhuman-core/src/agent/registry/agents/orchestrator/prompt.rs b/crates/openhuman-core/src/agent/registry/agents/orchestrator/prompt.rs
index cb9a585722..5d80ac6c86 100644
--- a/crates/openhuman-core/src/agent/registry/agents/orchestrator/prompt.rs
+++ b/crates/openhuman-core/src/agent/registry/agents/orchestrator/prompt.rs
@@ -291,7 +291,7 @@ fn strip_route_lines(archetype: &str, skills: bool, mcp: bool) -> String {
/// The registry entry behind `agent_id`, tolerating the web channel's rename.
///
-/// `PromptContext::agent_id` carries `Agent::agent_definition_name`, which the
+/// `PromptContext::agent_id` carries `OpenHumanSessionHost::agent_definition_name`, which the
/// web channel rewrites to `"orchestrator_<short_thread>"` so each thread gets
/// its own transcript namespace. The canonical id lives in a different field
/// (`agent_definition_id`, whose docs say to use it for exactly this), but that
diff --git a/crates/openhuman-core/src/agent/registry/defaults.rs b/crates/openhuman-core/src/agent/registry/defaults.rs
index bbede9785c..5ee1226694 100644
--- a/crates/openhuman-core/src/agent/registry/defaults.rs
+++ b/crates/openhuman-core/src/agent/registry/defaults.rs
@@ -53,7 +53,7 @@ fn default_entry_from_definition(def: AgentDefinition) -> AgentRegistryEntry {
/// Inverse of [`default_entry_from_definition`] — synthesizes a harness
/// [`AgentDefinition`] from a user-authored [`AgentRegistryEntry`] so a
/// custom agent (one with no shipped harness definition) can be built through
-/// the same [`crate::agent::Agent::from_config_for_agent`] factory
+/// the same [`crate::agent::OpenHumanSessionHost::from_config_for_agent`] factory
/// path as a built-in, and therefore run with its real tool belt rather than
/// degrade to a persona-only completion.
///
diff --git a/crates/openhuman-core/src/agent/registry/ops.rs b/crates/openhuman-core/src/agent/registry/ops.rs
index dd3636ffae..0f08a360ef 100644
--- a/crates/openhuman-core/src/agent/registry/ops.rs
+++ b/crates/openhuman-core/src/agent/registry/ops.rs
@@ -3,7 +3,7 @@
use std::collections::HashMap;
use crate::agent::harness::AgentDefinitionRegistry;
-use crate::agent::Agent;
+use crate::agent::OpenHumanSessionHost;
use crate::config::rpc as config_rpc;
use crate::config::Config;
@@ -152,7 +152,7 @@ pub async fn available_tools() -> Result<Vec<AgentToolInfo>, String> {
let config = config_rpc::load_config_with_timeout().await?;
AgentDefinitionRegistry::init_global(&config.workspace_dir)
.map_err(|e| format!("failed to initialise AgentDefinitionRegistry: {e}"))?;
- let agent = Agent::from_config_for_agent(&config, TOOLS_CATALOG_AGENT_ID)
+ let agent = OpenHumanSessionHost::from_config_for_agent(&config, TOOLS_CATALOG_AGENT_ID)
.map_err(|e| format!("failed to build tools-catalog agent: {e}"))?;
let mut tools: Vec<AgentToolInfo> = agent
@@ -201,8 +201,8 @@ pub fn merge_entries(
/// Synchronous, config-only lookup for a user-authored (`Custom`-source),
/// **enabled** agent registry entry by id.
///
-/// Used by the agent factory (`Agent::from_config_for_agent` family, see
-/// `agent::harness::session::builder::factory`) on a harness-registry lookup
+/// Used by the agent factory (`OpenHumanSessionHost::from_config_for_agent` family, see
+/// `agent::session_host::builder::factory`) on a harness-registry lookup
/// miss so a custom agent can be synthesized into a real
/// `AgentDefinition` (via `definition_from_registry_entry`) and run with its
/// real tool belt, instead of erroring (chat/task-dispatcher) or degrading to
diff --git a/crates/openhuman-core/src/agent/harness/session/builder/builder_build.rs b/crates/openhuman-core/src/agent/session_host/builder/builder_build.rs
similarity index 93%
rename from crates/openhuman-core/src/agent/harness/session/builder/builder_build.rs
rename to crates/openhuman-core/src/agent/session_host/builder/builder_build.rs
index 037c7d291f..4ddddb9ead 100644
--- a/crates/openhuman-core/src/agent/harness/session/builder/builder_build.rs
+++ b/crates/openhuman-core/src/agent/session_host/builder/builder_build.rs
@@ -1,25 +1,25 @@
-//! `AgentBuilder::build` — validates and assembles the final [`Agent`].
+//! `SessionHostBuilder::build` — validates and assembles the final [`OpenHumanSessionHost`].
use super::{dedup_visible_tool_specs, visible_tool_specs_for_policy};
use crate::agent::context::ContextManager;
-use crate::agent::harness::session::types::{Agent, AgentBuilder};
+use crate::agent::session_host::types::{OpenHumanSessionHost, SessionHostBuilder};
use crate::tools::agent_policy::ToolPolicyEngine;
use anyhow::Result;
use std::sync::Arc;
use tinytools::{Tool, ToolSpec};
-impl AgentBuilder {
- /// Validates the configuration and constructs a new `Agent` instance.
+impl SessionHostBuilder {
+ /// Validates the configuration and constructs a new `OpenHumanSessionHost` instance.
///
/// This method is responsible for wiring together the provided components,
/// setting up the context manager, and initializing the conversation history.
/// It ensures that all required fields (provider, tools, memory, etc.) are present.
- pub fn build(self) -> Result<Agent> {
+ pub fn build(self) -> Result<OpenHumanSessionHost> {
let tools = self
.tools
.ok_or_else(|| anyhow::anyhow!("tools are required"))?;
// The synthesised set lives beside the durable registry, never inside
- // it (`Agent::synthesized_tools`); a durable name wins a collision.
+ // it (`OpenHumanSessionHost::synthesized_tools`); a durable name wins a collision.
let synthesized_tools = super::drop_synthesized_name_collisions(
&tools,
self.synthesized_tools.unwrap_or_default(),
@@ -87,7 +87,7 @@ impl AgentBuilder {
// This is the one site that turns the "all visible" sentinel into a
// concrete set for a session, so the refresh paths never re-admit a
// durable Hidden tool: `refresh_delegation_tools` (turn/tools.rs) only
- // swaps synthesised names, and `Agent::hide_tools` only seeds a set
+ // swaps synthesised names, and `OpenHumanSessionHost::hide_tools` only seeds a set
// that is still empty — see the matching strip there.
let deferred = if belt_is_wildcard {
crate::tools::implementations::meta::strip_deferred_from_visible(
@@ -139,7 +139,7 @@ impl AgentBuilder {
);
// A child agent inherits explicit profile and channel restrictions, but
- // not the primary agent's own role-specific tool scope. The Master Agent
+ // not the primary agent's own role-specific tool scope. The Master OpenHumanSessionHost
// can write directly, while specialists may still need tools outside its
// intentionally compact default surface. Conflating those two surfaces
// silently strips specialist capabilities (#5118 merge).
@@ -199,7 +199,7 @@ impl AgentBuilder {
visible_names_list.join(", ")
);
- // Pull the model source out of the builder once; the Agent holds it and
+ // Pull the model source out of the builder once; the OpenHumanSessionHost holds it and
// builds a fresh tiered crate `ChatModel` set from it per turn.
let turn_model_source = self
.turn_model_source
@@ -241,7 +241,11 @@ impl AgentBuilder {
// is unreachable through `use_skill` until this second binding runs.
crate::tools::toolpacks::bind_synthesized_pack_registry(&tools, &synthesized_tools);
- Ok(Agent {
+ Ok(OpenHumanSessionHost {
+ runtime_session: None,
+ runtime_state: Arc::new(std::sync::Mutex::new(
+ super::super::runtime_session::OpenHumanSessionState::default(),
+ )),
turn_model_source,
tools,
synthesized_tools,
@@ -269,11 +273,6 @@ impl AgentBuilder {
workflows: self.workflows.unwrap_or_default(),
auto_save: self.auto_save.unwrap_or(false),
last_memory_context: None,
- last_turn_citations: Vec::new(),
- pending_citations: None,
- last_turn_usage_totals: None,
- last_turn_hit_cap: false,
- history: Vec::new(),
post_turn_hooks: self.post_turn_hooks,
learning_enabled: self.learning_enabled,
explicit_preferences_enabled: self.explicit_preferences_enabled,
@@ -287,10 +286,7 @@ impl AgentBuilder {
// `refresh_delegation_tools` to re-resolve the agent's
// `subagents` declaration against the global registry.
agent_definition_id: agent_definition_name.clone(),
- session_transcript_path: None,
- session_history: None,
session_history_locator: self.session_history_locator,
- persisted_transcript_messages: Vec::new(),
session_key: {
let unix_ts = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
@@ -309,8 +305,7 @@ impl AgentBuilder {
format!("{unix_ts}_{sanitized}")
},
session_parent_prefix: self.session_parent_prefix,
- cached_transcript_messages: None,
- context,
+ context: std::sync::Arc::new(std::sync::Mutex::new(context)),
on_progress: None,
run_queue: None,
connected_integrations: Vec::new(),
@@ -341,7 +336,6 @@ impl AgentBuilder {
pending_skill_retraction: Vec::new(),
archivist_hook: self.archivist_hook,
synthesized_tool_names,
- pending_turn_overrides: super::super::types::TurnOverrides::default(),
})
}
}
diff --git a/crates/openhuman-core/src/agent/harness/session/builder/builder_tests.rs b/crates/openhuman-core/src/agent/session_host/builder/builder_tests.rs
similarity index 97%
rename from crates/openhuman-core/src/agent/harness/session/builder/builder_tests.rs
rename to crates/openhuman-core/src/agent/session_host/builder/builder_tests.rs
index ed09915864..6110559982 100644
--- a/crates/openhuman-core/src/agent/harness/session/builder/builder_tests.rs
+++ b/crates/openhuman-core/src/agent/session_host/builder/builder_tests.rs
@@ -309,7 +309,7 @@ fn use_skill_survives_a_ceiling_that_excludes_it_when_a_pack_is_still_reachable(
#[tokio::test]
async fn an_empty_named_scope_advertises_no_tools_at_all() {
- use crate::agent::harness::session::types::Agent;
+ use crate::agent::session_host::types::OpenHumanSessionHost;
// `summarizer` is a shipped definition with `named = []`. Using the real
// one rather than a fixture is deliberate: the bug was in how a real
@@ -321,7 +321,7 @@ async fn an_empty_named_scope_advertises_no_tools_at_all() {
let tmp = tempfile::TempDir::new().unwrap();
let config = test_config(&tmp);
- let agent = Agent::from_config_for_agent(&config, "summarizer")
+ let agent = OpenHumanSessionHost::from_config_for_agent(&config, "summarizer")
.expect("summarizer is a shipped agent definition");
let visible = agent.visible_tool_names_for_test();
@@ -342,7 +342,7 @@ async fn a_zero_tool_agent_does_not_gain_the_compaction_recovery_tool() {
// first time. Without `is_empty_tool_scope` there, "no tools" would have
// quietly become "one tool" — and there is nothing for it to recover,
// because an agent with no tools produces no tool output to truncate.
- use crate::agent::harness::session::types::Agent;
+ use crate::agent::session_host::types::OpenHumanSessionHost;
use crate::inference::tokenjuice::RETRIEVE_TOOL_NAME;
// Tolerant of an already-initialised singleton: this binary shares one
@@ -352,7 +352,7 @@ async fn a_zero_tool_agent_does_not_gain_the_compaction_recovery_tool() {
let tmp = tempfile::TempDir::new().unwrap();
let config = test_config(&tmp);
- let agent = Agent::from_config_for_agent(&config, "trigger_triage")
+ let agent = OpenHumanSessionHost::from_config_for_agent(&config, "trigger_triage")
.expect("trigger_triage is a shipped agent definition");
assert!(
@@ -375,7 +375,7 @@ fn the_no_tools_sentinel_can_never_name_a_real_tool() {
#[test]
fn is_empty_tool_scope_distinguishes_the_three_states() {
- use crate::agent::harness::definition::{is_empty_tool_scope, NO_TOOLS_SENTINEL};
+ use crate::agent::harness::definition::{NO_TOOLS_SENTINEL, is_empty_tool_scope};
use std::collections::HashSet;
// Unset — the historical "everything" sentinel.
diff --git a/crates/openhuman-core/src/agent/harness/session/builder/builder_tests_explicit_definition_tests.rs b/crates/openhuman-core/src/agent/session_host/builder/builder_tests_explicit_definition_tests.rs
similarity index 91%
rename from crates/openhuman-core/src/agent/harness/session/builder/builder_tests_explicit_definition_tests.rs
rename to crates/openhuman-core/src/agent/session_host/builder/builder_tests_explicit_definition_tests.rs
index e01a7d0270..4572c88149 100644
--- a/crates/openhuman-core/src/agent/harness/session/builder/builder_tests_explicit_definition_tests.rs
+++ b/crates/openhuman-core/src/agent/session_host/builder/builder_tests_explicit_definition_tests.rs
@@ -7,7 +7,7 @@ use super::*;
use crate::agent::harness::definition::{
AgentDefinitionRegistry, PromptSource, SandboxMode, ToolScope,
};
-use crate::agent::harness::session::types::Agent;
+use crate::agent::session_host::types::OpenHumanSessionHost;
fn explicit_definition(id: &str) -> crate::agent::harness::definition::AgentDefinition {
let mut def = AgentDefinitionRegistry::builtins_only()
@@ -30,7 +30,7 @@ async fn from_config_with_definition_stamps_the_definition_on_the_session() {
let config = test_config(&tmp);
let def = explicit_definition("embedded-alpha");
- let agent = Agent::from_config_with_definition(&config, &def)
+ let agent = OpenHumanSessionHost::from_config_with_definition(&config, &def)
.expect("build from an explicit definition");
assert_eq!(agent.agent_definition_id, "embedded-alpha");
@@ -61,7 +61,7 @@ async fn resolved_definition_prefers_the_sessions_own_over_a_same_id_registry_en
"the registry's orchestrator is not read-only, so a leak is observable"
);
- let agent = Agent::from_config_with_definition(&config, &def)
+ let agent = OpenHumanSessionHost::from_config_with_definition(&config, &def)
.expect("build from an explicit definition");
assert_eq!(
@@ -78,7 +78,7 @@ async fn registry_built_sessions_resolve_the_registry_definition() {
let tmp = tempfile::TempDir::new().unwrap();
let config = test_config(&tmp);
- let agent = Agent::from_config(&config).expect("orchestrator session");
+ let agent = OpenHumanSessionHost::from_config(&config).expect("orchestrator session");
let resolved = agent.resolved_definition().expect("registry definition");
assert_eq!(resolved.id, "orchestrator");
let registry_mode = AgentDefinitionRegistry::global()
diff --git a/crates/openhuman-core/src/agent/harness/session/builder/builder_tests_memory_write_instruction_tests.rs b/crates/openhuman-core/src/agent/session_host/builder/builder_tests_memory_write_instruction_tests.rs
similarity index 80%
rename from crates/openhuman-core/src/agent/harness/session/builder/builder_tests_memory_write_instruction_tests.rs
rename to crates/openhuman-core/src/agent/session_host/builder/builder_tests_memory_write_instruction_tests.rs
index 4846044e48..aa245f3dbf 100644
--- a/crates/openhuman-core/src/agent/harness/session/builder/builder_tests_memory_write_instruction_tests.rs
+++ b/crates/openhuman-core/src/agent/session_host/builder/builder_tests_memory_write_instruction_tests.rs
@@ -9,8 +9,8 @@ use super::*;
#[tokio::test]
async fn memory_write_instruction_is_present_with_learning_disabled() {
- use crate::agent::harness::session::types::Agent;
use crate::agent::prompts::LearnedContextData;
+ use crate::agent::session_host::types::OpenHumanSessionHost;
let tmp = tempfile::TempDir::new().unwrap();
let config = test_config(&tmp);
@@ -19,9 +19,13 @@ async fn memory_write_instruction_is_present_with_learning_disabled() {
"the default install has learning off; the write rule must not depend on it"
);
let orchestrator = builtin_def("orchestrator");
- let agent =
- Agent::build_session_agent_inner(&config, "orchestrator", Some(&orchestrator), false)
- .expect("build session");
+ let agent = OpenHumanSessionHost::build_session_agent_inner(
+ &config,
+ "orchestrator",
+ Some(&orchestrator),
+ false,
+ )
+ .expect("build session");
let prompt = agent
.build_system_prompt(LearnedContextData::default())
@@ -34,14 +38,19 @@ async fn memory_write_instruction_is_present_with_learning_disabled() {
#[tokio::test]
async fn memory_write_instruction_names_only_the_write_tool_a_scoped_agent_holds() {
- use crate::agent::harness::session::types::Agent;
use crate::agent::prompts::LearnedContextData;
+ use crate::agent::session_host::types::OpenHumanSessionHost;
let tmp = tempfile::TempDir::new().unwrap();
let config = test_config(&tmp);
let archivist = builtin_def("archivist");
- let agent = Agent::build_session_agent_inner(&config, "archivist", Some(&archivist), false)
- .expect("build archivist session");
+ let agent = OpenHumanSessionHost::build_session_agent_inner(
+ &config,
+ "archivist",
+ Some(&archivist),
+ false,
+ )
+ .expect("build archivist session");
let prompt = agent
.build_system_prompt(LearnedContextData::default())
diff --git a/crates/openhuman-core/src/agent/harness/session/builder/builder_tests_tool_exposure_tests.rs b/crates/openhuman-core/src/agent/session_host/builder/builder_tests_tool_exposure_tests.rs
similarity index 80%
rename from crates/openhuman-core/src/agent/harness/session/builder/builder_tests_tool_exposure_tests.rs
rename to crates/openhuman-core/src/agent/session_host/builder/builder_tests_tool_exposure_tests.rs
index 0269a34520..8964793d65 100644
--- a/crates/openhuman-core/src/agent/harness/session/builder/builder_tests_tool_exposure_tests.rs
+++ b/crates/openhuman-core/src/agent/session_host/builder/builder_tests_tool_exposure_tests.rs
@@ -7,8 +7,13 @@ fn visible_names(agent_id: &str) -> std::collections::HashSet<String> {
.get(agent_id)
.cloned()
.unwrap_or_else(|| panic!("built-in agent definition not found: {agent_id}"));
- let agent = crate::agent::Agent::from_config_with_definition(&config, &definition, None, None)
- .unwrap_or_else(|e| panic!("{agent_id} session build: {e}"));
+ let agent = crate::agent::OpenHumanSessionHost::from_config_with_definition(
+ &config,
+ &definition,
+ None,
+ None,
+ )
+ .unwrap_or_else(|e| panic!("{agent_id} session build: {e}"));
agent
.visible_tool_specs_arc()
.iter()
@@ -24,16 +29,22 @@ fn resetting_wildcard_visibility_keeps_collapsed_exposure() {
.get("tools_agent")
.cloned()
.expect("tools_agent built-in definition");
- let mut agent =
- crate::agent::Agent::from_config_with_definition(&config, &definition, None, None)
- .expect("build tools agent");
+ let mut agent = crate::agent::OpenHumanSessionHost::from_config_with_definition(
+ &config,
+ &definition,
+ None,
+ None,
+ )
+ .expect("build tools agent");
agent.set_visible_tool_names(std::collections::HashSet::new());
let visible = agent.visible_tool_specs_arc();
- assert!(visible
- .iter()
- .any(|spec| spec.name == crate::memory::tools::MEMORY_TOOL_NAME));
+ assert!(
+ visible
+ .iter()
+ .any(|spec| spec.name == crate::memory::tools::MEMORY_TOOL_NAME)
+ );
assert!(!visible.iter().any(|spec| spec.name == "memory_store"));
}
@@ -45,17 +56,23 @@ fn hiding_and_reseeding_wildcard_visibility_keeps_collapsed_exposure() {
.get("tools_agent")
.cloned()
.expect("tools_agent built-in definition");
- let mut agent =
- crate::agent::Agent::from_config_with_definition(&config, &definition, None, None)
- .expect("build tools agent");
+ let mut agent = crate::agent::OpenHumanSessionHost::from_config_with_definition(
+ &config,
+ &definition,
+ None,
+ None,
+ )
+ .expect("build tools agent");
agent.set_visible_tool_names(std::collections::HashSet::new());
agent.hide_tools(&[crate::memory::tools::MEMORY_TOOL_NAME]);
let visible = agent.visible_tool_specs_arc();
- assert!(!visible
- .iter()
- .any(|spec| spec.name == crate::memory::tools::MEMORY_TOOL_NAME));
+ assert!(
+ !visible
+ .iter()
+ .any(|spec| spec.name == crate::memory::tools::MEMORY_TOOL_NAME)
+ );
assert!(!visible.iter().any(|spec| spec.name == "memory_store"));
}
diff --git a/crates/openhuman-core/src/agent/harness/session/builder/builder_tests_tool_spec_views_tests.rs b/crates/openhuman-core/src/agent/session_host/builder/builder_tests_tool_spec_views_tests.rs
similarity index 97%
rename from crates/openhuman-core/src/agent/harness/session/builder/builder_tests_tool_spec_views_tests.rs
rename to crates/openhuman-core/src/agent/session_host/builder/builder_tests_tool_spec_views_tests.rs
index 3686d7cb85..1130c77396 100644
--- a/crates/openhuman-core/src/agent/harness/session/builder/builder_tests_tool_spec_views_tests.rs
+++ b/crates/openhuman-core/src/agent/session_host/builder/builder_tests_tool_spec_views_tests.rs
@@ -16,7 +16,7 @@ fn the_three_spec_views_share_their_leaf_schemas() {
let tmp = tempfile::TempDir::new().unwrap();
let config = test_config(&tmp);
- let agent = crate::agent::Agent::from_config_for_agent(&config, "orchestrator")
+ let agent = crate::agent::OpenHumanSessionHost::from_config_for_agent(&config, "orchestrator")
.expect("orchestrator session build");
let durable = agent.durable_tool_specs_arc();
@@ -126,7 +126,7 @@ fn dedup_keeps_the_original_allocation_of_the_winning_spec() {
fn spec_views_stay_consistent_for_a_tool_less_agent() {
let model: std::sync::Arc<dyn tinyinference_llm::model::ChatModel<()>> =
std::sync::Arc::new(tinyagents_harness::testkit::ScriptedModel::new(Vec::new()));
- let agent = crate::agent::AgentBuilder::new()
+ let agent = crate::agent::SessionHostBuilder::new()
.chat_model(model)
.tools(Vec::new())
.memory(crate::memory::test_support::noop_memory())
diff --git a/crates/openhuman-core/src/agent/harness/session/builder/factory.rs b/crates/openhuman-core/src/agent/session_host/builder/factory.rs
similarity index 97%
rename from crates/openhuman-core/src/agent/harness/session/builder/factory.rs
rename to crates/openhuman-core/src/agent/session_host/builder/factory.rs
index 512f606049..ce45e7b1fb 100644
--- a/crates/openhuman-core/src/agent/harness/session/builder/factory.rs
+++ b/crates/openhuman-core/src/agent/session_host/builder/factory.rs
@@ -1,17 +1,17 @@
-//! `Agent::from_config` factory methods and the internal
+//! `OpenHumanSessionHost::from_config` factory methods and the internal
//! `build_session_agent_inner` constructor.
use super::helpers::prefetch_tool_memory_rules_blocking;
use super::should_synthesize_delegation_tools;
use crate::agent::harness::definition::NO_TOOLS_SENTINEL;
use crate::agent::harness::definition::{AgentDefinitionRegistry, PromptSource, ToolScope};
-use crate::agent::harness::session::types::Agent;
use crate::agent::host_runtime;
use crate::agent::prompts::SystemPromptBuilder;
+use crate::agent::session_host::types::OpenHumanSessionHost;
use crate::config::Config;
use crate::inference::provider;
-use crate::memory::tool_memory::capture::ToolMemoryCaptureHook;
use crate::memory::Memory;
+use crate::memory::tool_memory::capture::ToolMemoryCaptureHook;
use crate::security::SecurityPolicy;
use crate::tools;
use anyhow::Result;
@@ -19,10 +19,10 @@ use std::sync::Arc;
use tinytools::{PermissionLevel, Tool};
use tinytools_agent::dialect::{NativeDialect, PFormatDialect, ToolDialect, XmlDialect};
-impl Agent {
- /// Constructs an `Agent` instance from a global system configuration.
+impl OpenHumanSessionHost {
+ /// Constructs an `OpenHumanSessionHost` instance from a global system configuration.
///
- /// Thin wrapper around [`Agent::from_config_for_agent`] that always
+ /// Thin wrapper around [`OpenHumanSessionHost::from_config_for_agent`] that always
/// targets the orchestrator definition. This preserves the legacy
/// "main agent = orchestrator" behaviour for CLI / REPL / any caller
/// that does not participate in the #525 onboarding-routing flow.
@@ -30,12 +30,12 @@ impl Agent {
/// Callers that need to select a different agent at session-build
/// time (for example the Tauri web chat path, which routes to the
/// welcome agent pre-onboarding) should call
- /// [`Agent::from_config_for_agent`] directly.
+ /// [`OpenHumanSessionHost::from_config_for_agent`] directly.
pub fn from_config(config: &Config) -> Result<Self> {
Self::from_config_for_agent(config, "orchestrator")
}
- /// Constructs an `Agent` instance scoped to a specific agent
+ /// Constructs an `OpenHumanSessionHost` instance scoped to a specific agent
/// definition loaded from the global [`AgentDefinitionRegistry`].
///
/// `agent_id` is looked up in the registry; the returned agent
@@ -111,7 +111,7 @@ impl Agent {
///
/// The definition is authoritative for this agent's prompt, tool scope,
/// sandbox mode and delegation allowlist; it is stamped on the session so
- /// in-turn readers ([`Agent::resolved_definition`]) never fall back to a
+ /// in-turn readers ([`OpenHumanSessionHost::resolved_definition`]) never fall back to a
/// registry entry that happens to share its id. This is the constructor a
/// library host uses to run many independently specified agents on one
/// booted core.
@@ -128,7 +128,7 @@ impl Agent {
}
/// Internal constructor that consumes the optionally-resolved agent
- /// definition. Split out from [`Agent::from_config_for_agent`] so
+ /// definition. Split out from [`OpenHumanSessionHost::from_config_for_agent`] so
/// the lookup + logging live in one place and the heavy-lifting
/// body stays readable.
// `pub(crate)` (rather than private) so `builder_tests` can drive the
@@ -268,7 +268,7 @@ impl Agent {
// #4249, 1c). `model_routes` translation and intelligent local/cloud
// task hinting now live in the unified routing layer (router.rs) rather
// than a per-session wrapper, so they are not re-wrapped here.
- // The Master Agent's definition selects the coding workload so the
+ // The Master OpenHumanSessionHost's definition selects the coding workload so the
// default user-facing turn has a model suitable for the direct
// inspect → edit → verify loop. Legacy/no-definition callers retain
// the configured chat default. Other specialised roles still select
@@ -277,7 +277,7 @@ impl Agent {
// workload — legacy tier literals like `reasoning-v1` (which the
// bootstrap historically pinned as `default_model` for everyone)
// fall through to `chat`. This preserves `config.chat_provider` for
- // legacy callers. A built-in Master Agent has an explicit
+ // legacy callers. A built-in Master OpenHumanSessionHost has an explicit
// `hint:coding`, while existing pre-registry callers continue using
// `config.default_model` unchanged.
let provider_role =
@@ -463,7 +463,7 @@ impl Agent {
// and the full learning subsystem is NOT already wiring UserProfileSection,
// we add it here so pinned preferences written by `remember_preference`
// reach every session prompt. The `fetch_learned_context` gate is
- // widened by `explicit_preferences_enabled` on the Agent (see
+ // widened by `explicit_preferences_enabled` on the OpenHumanSessionHost (see
// `session/turn.rs`) so the data is actually fetched and populated.
if config.learning.explicit_preferences_enabled && !config.learning.enabled {
prompt_builder = prompt_builder.add_section(Box::new(
@@ -490,8 +490,8 @@ impl Agent {
let (model, resolved_model) =
provider::create_chat_model_with_model_id("reasoning", config, 0.3)?;
log::debug!(
- "[learning] built crate-native reflection model resolved_model={resolved_model}"
- );
+ "[learning] built crate-native reflection model resolved_model={resolved_model}"
+ );
Some(model)
} else {
None
@@ -731,7 +731,7 @@ impl Agent {
// we just synthesised as a delegation wrapper. When the
// definition is `ToolScope::Wildcard` (legacy default, no
// filter), we still populate `visible` from the delegation
- // tools alone so the existing `Agent::visible_tool_names`
+ // tools alone so the existing `OpenHumanSessionHost::visible_tool_names`
// contract (empty == no filter) stays intact: an empty set
// means "no filter" for both legacy callers and the new
// agent-scoped path.
@@ -793,7 +793,7 @@ impl Agent {
);
// The delegation tools stay beside the durable registry rather than
- // inside it: the builder holds them in `Agent::synthesized_tools`,
+ // inside it: the builder holds them in `OpenHumanSessionHost::synthesized_tools`,
// drops any name a durable tool already owns, and
// `refresh_delegation_tools` replaces the whole set later (#6145).
@@ -864,9 +864,9 @@ impl Agent {
.map(|def| def.effective_tokenjuice_compression())
.unwrap_or(crate::inference::tokenjuice::AgentTokenjuiceCompression::Full);
- // Stamp the resolved agent definition id onto the Agent via the
+ // Stamp the resolved agent definition id onto the OpenHumanSessionHost via the
// builder. Without this call, `agent_definition_name` falls
- // back to the legacy `"main"` default (see `AgentBuilder::build`)
+ // back to the legacy `"main"` default (see `SessionHostBuilder::build`)
// for every non-orchestrator caller. In the current codebase
// that is benign for the orchestrator (which is already aliased
// as `"main"` everywhere downstream) but causes two concrete
@@ -883,7 +883,7 @@ impl Agent {
// are spawned through `subagent_runner` which constructs its
// prompt and history directly.
//
- // See the docstring on `AgentBuilder::agent_definition_name`
+ // See the docstring on `SessionHostBuilder::agent_definition_name`
// for the full list of surfaces and the latent prompt-section
// foot-gun this call also closes.
log::debug!(
@@ -973,7 +973,7 @@ impl Agent {
);
effective_agent_config.max_tool_iterations = def_cap;
}
- let mut builder = Agent::builder()
+ let mut builder = OpenHumanSessionHost::builder()
.crate_native_provider(provider_role, Arc::clone(&base_config))
.tools(tools)
.synthesized_tools(delegation_tools)
@@ -1171,10 +1171,10 @@ fn resolve_dispatcher_kind(
/// Resolve the provider/workload role for a session build.
///
/// The `subconscious` workload has two entry points and both must route here:
-/// - the cloud tick builds via `Agent::from_config` (agent_id `"orchestrator"`)
+/// - the cloud tick builds via `OpenHumanSessionHost::from_config` (agent_id `"orchestrator"`)
/// with `default_model = "hint:subconscious"`;
/// - the event-driven long-lived session builds via
-/// `Agent::from_config_for_agent(_, "subconscious")` and does NOT set the hint.
+/// `OpenHumanSessionHost::from_config_for_agent(_, "subconscious")` and does NOT set the hint.
///
/// Routing on `agent_id == "subconscious"` covers the second case (Codex P2:
/// otherwise promoted background turns fall through to `chat_provider` and ignore
diff --git a/crates/openhuman-core/src/agent/harness/session/builder/factory_provider_role_tests_tests.rs b/crates/openhuman-core/src/agent/session_host/builder/factory_provider_role_tests_tests.rs
similarity index 98%
rename from crates/openhuman-core/src/agent/harness/session/builder/factory_provider_role_tests_tests.rs
rename to crates/openhuman-core/src/agent/session_host/builder/factory_provider_role_tests_tests.rs
index 1581cc862e..1b730a0ebf 100644
--- a/crates/openhuman-core/src/agent/harness/session/builder/factory_provider_role_tests_tests.rs
+++ b/crates/openhuman-core/src/agent/session_host/builder/factory_provider_role_tests_tests.rs
@@ -1,5 +1,5 @@
use super::provider_role_for;
-use super::{resolve_dispatcher_kind, DispatcherKind};
+use super::{DispatcherKind, resolve_dispatcher_kind};
#[test]
fn legacy_orchestrator_fallback_defaults_to_chat() {
diff --git a/crates/openhuman-core/src/agent/harness/session/builder/helpers.rs b/crates/openhuman-core/src/agent/session_host/builder/helpers.rs
similarity index 96%
rename from crates/openhuman-core/src/agent/harness/session/builder/helpers.rs
rename to crates/openhuman-core/src/agent/session_host/builder/helpers.rs
index 06096c7129..aa512067d5 100644
--- a/crates/openhuman-core/src/agent/harness/session/builder/helpers.rs
+++ b/crates/openhuman-core/src/agent/session_host/builder/helpers.rs
@@ -13,10 +13,10 @@
//! shared with the session's `DriverMemory`, so recall and tool-memory rules
//! always address the same durable data.
+use crate::memory::Memory;
use crate::memory::api::provider::MemoryProvider;
use crate::memory::auto_recall::AutoRecall;
-use crate::memory::tool_memory::{tool_memory_store, ToolMemoryRule};
-use crate::memory::Memory;
+use crate::memory::tool_memory::{ToolMemoryRule, tool_memory_store};
use std::sync::Arc;
use crate::agent::prompts::SystemPromptBuilder;
@@ -111,8 +111,8 @@ pub(super) fn add_memory_prompt_sections(
agent_id: &str,
) -> SystemPromptBuilder {
use crate::agent::learning::{
- any_tool_offered, MemoryAccessSection, MemoryWriteSection, MEMORY_READ_TOOLS,
- MEMORY_STORE_TOOL, MEMORY_WRITE_DELEGATE_TOOL, SAVE_PREFERENCE_TOOL,
+ MEMORY_READ_TOOLS, MEMORY_STORE_TOOL, MEMORY_WRITE_DELEGATE_TOOL, MemoryAccessSection,
+ MemoryWriteSection, SAVE_PREFERENCE_TOOL, any_tool_offered,
};
let mut prompt_builder = prompt_builder;
if any_tool_offered(&MEMORY_READ_TOOLS, tools, delegation_tools, visible) {
diff --git a/crates/openhuman-core/src/agent/harness/session/builder/mod.rs b/crates/openhuman-core/src/agent/session_host/builder/mod.rs
similarity index 98%
rename from crates/openhuman-core/src/agent/harness/session/builder/mod.rs
rename to crates/openhuman-core/src/agent/session_host/builder/mod.rs
index 0e8d05527e..375934dce6 100644
--- a/crates/openhuman-core/src/agent/harness/session/builder/mod.rs
+++ b/crates/openhuman-core/src/agent/session_host/builder/mod.rs
@@ -1,6 +1,6 @@
-//! `AgentBuilder` fluent API and the `Agent::from_config` factory.
+//! `SessionHostBuilder` fluent API and the `OpenHumanSessionHost::from_config` factory.
//!
-//! Everything in this module is about *constructing* an `Agent` — the
+//! Everything in this module is about *constructing* an `OpenHumanSessionHost` — the
//! builder setters, the `build()` validator, and the `from_config()`
//! factory that wires together the real provider / memory / tool
//! registry from a loaded [`Config`]. Per-turn behaviour lives in
diff --git a/crates/openhuman-core/src/agent/harness/session/builder/setters.rs b/crates/openhuman-core/src/agent/session_host/builder/setters.rs
similarity index 94%
rename from crates/openhuman-core/src/agent/harness/session/builder/setters.rs
rename to crates/openhuman-core/src/agent/session_host/builder/setters.rs
index 10557af5c1..4d208194ec 100644
--- a/crates/openhuman-core/src/agent/harness/session/builder/setters.rs
+++ b/crates/openhuman-core/src/agent/session_host/builder/setters.rs
@@ -1,15 +1,15 @@
-//! `AgentBuilder` fluent setters. See `builder_build.rs` for the `build()`
-//! validator that assembles the final `Agent`.
+//! `SessionHostBuilder` fluent setters. See `builder_build.rs` for the `build()`
+//! validator that assembles the final `OpenHumanSessionHost`.
-use crate::agent::harness::session::types::AgentBuilder;
use crate::agent::harness::TriggerMemoryAgent;
+use crate::agent::session_host::types::SessionHostBuilder;
use crate::config::ContextConfig;
use crate::memory::Memory;
use std::sync::Arc;
use tinytools::Tool;
-impl AgentBuilder {
- /// Creates a new `AgentBuilder` with default values.
+impl SessionHostBuilder {
+ /// Creates a new `SessionHostBuilder` with default values.
pub fn new() -> Self {
Self {
turn_model_source: None,
@@ -82,7 +82,7 @@ impl AgentBuilder {
}
/// Sets the delegation tools synthesised for the session's initial
- /// connection set — see [`Agent::synthesized_tools`]. A name a durable
+ /// connection set — see [`OpenHumanSessionHost::synthesized_tools`]. A name a durable
/// tool already owns is dropped in [`Self::build`]. Defaults to none.
pub fn synthesized_tools(mut self, tools: Vec<Box<dyn Tool>>) -> Self {
self.synthesized_tools = Some(tools);
@@ -255,7 +255,7 @@ impl AgentBuilder {
/// Sets the agent definition id this session is running
/// (`welcome`, `orchestrator`, `integrations_agent`, …).
///
- /// This value is stamped onto the built [`Agent`] and surfaces in
+ /// This value is stamped onto the built [`OpenHumanSessionHost`] and surfaces in
/// the following places:
///
/// * **Transcript filename on disk** — `transcript::write_transcript`
@@ -277,7 +277,7 @@ impl AgentBuilder {
/// that special-cases `integrations_agent` vs every other agent — so
/// the current user-visible impact of a wrong id is limited to
/// the two bullets above. The stamped `prompt_builder` injected
- /// by [`Agent::from_config_for_agent`] is what actually drives
+ /// by [`OpenHumanSessionHost::from_config_for_agent`] is what actually drives
/// prompt flavour per archetype, independent of this field. That
/// said, any future prompt section that branches on a
/// non-`integrations_agent` id (e.g. welcome-specific banner, planner-
@@ -285,7 +285,7 @@ impl AgentBuilder {
/// left at `"main"`, so keeping it correctly stamped closes a
/// latent foot-gun for code that hasn't been written yet.
///
- /// Callers building via [`Agent::from_config_for_agent`] get this
+ /// Callers building via [`OpenHumanSessionHost::from_config_for_agent`] get this
/// wired automatically inside `build_session_agent_inner`; direct
/// builder users (tests, CLI) must set it explicitly if they care
/// about any of the surfaces above.
@@ -325,7 +325,7 @@ impl AgentBuilder {
}
/// Forward the target agent definition's `omit_profile` flag so
- /// [`Agent::build_system_prompt`] can decide whether to inject
+ /// [`OpenHumanSessionHost::build_system_prompt`] can decide whether to inject
/// `PROFILE.md`. Only opt-in agents (welcome, orchestrator, the
/// trigger pair) should set this to `false`.
pub fn omit_profile(mut self, omit: bool) -> Self {
@@ -334,7 +334,7 @@ impl AgentBuilder {
}
/// Forward the target agent definition's `omit_memory_md` flag so
- /// [`Agent::build_system_prompt`] can decide whether to inject
+ /// [`OpenHumanSessionHost::build_system_prompt`] can decide whether to inject
/// `MEMORY.md`. Same opt-in set as `omit_profile`.
pub fn omit_memory_md(mut self, omit: bool) -> Self {
self.omit_memory_md = Some(omit);
@@ -346,7 +346,7 @@ impl AgentBuilder {
/// [`crate::agent::tinyagents::payload_summarizer::PayloadSummarizer::maybe_summarize_in_parent`]
/// on successful tool output and replaces the raw payload with the
/// compressed summary on success. Currently set only for the orchestrator
- /// session by [`Agent::build_session_agent_inner`].
+ /// session by [`OpenHumanSessionHost::build_session_agent_inner`].
pub fn payload_summarizer(
mut self,
summarizer: Arc<dyn crate::agent::tinyagents::payload_summarizer::PayloadSummarizer>,
@@ -377,7 +377,7 @@ impl AgentBuilder {
///
/// Set from `build_session_agent_inner` when
/// `config.learning.episodic_capture_enabled` is `true` and a
- /// SQLite connection is available. Callers that construct an `Agent`
+ /// SQLite connection is available. Callers that construct an `OpenHumanSessionHost`
/// directly (tests, CLI) can leave this `None` — flush is a no-op
/// when the hook is absent.
pub fn archivist_hook(
diff --git a/crates/openhuman-core/src/agent/session_host/codec.rs b/crates/openhuman-core/src/agent/session_host/codec.rs
new file mode 100644
index 0000000000..e5726731d0
--- /dev/null
+++ b/crates/openhuman-core/src/agent/session_host/codec.rs
@@ -0,0 +1,183 @@
+//! OpenHuman's lossless transcript dialect adapter.
+//!
+//! TinyAgents owns transcript deltas and persistence. This module owns only
+//! the conversion to OpenHuman's established wire rows; keeping it here makes
+//! the runtime usable by non-OpenHuman hosts without inheriting our metadata.
+
+use crate::agent::{
+ message_convert,
+ messages::{chat_message_from_transcript, transcript_message_from_chat},
+ tinyagents::host::OpenHumanRunContext,
+};
+use tinyagents_runtime::{RuntimeError, TranscriptCodec, TranscriptTurnOptions};
+use tinyagents_session::transcript::{
+ MessageUsage, SessionTranscript, ToolFailure, TranscriptMessage, TranscriptToolCall, TurnUsage,
+};
+use tinyinference_llm::message::Message;
+
+/// Converts OpenHuman's durable transcript rows at the TinyAgents boundary.
+#[derive(Default)]
+pub struct OpenHumanTranscriptCodec;
+
+impl TranscriptCodec<OpenHumanRunContext> for OpenHumanTranscriptCodec {
+ fn decode_history(&self, transcript: &SessionTranscript) -> Result<Vec<Message>, RuntimeError> {
+ let rows = transcript
+ .messages
+ .iter()
+ .cloned()
+ .map(chat_message_from_transcript)
+ .collect::<Vec<_>>();
+ Ok(message_convert::history_to_messages(&rows))
+ }
+
+ fn reconcile(
+ &self,
+ prior: &[TranscriptMessage],
+ previous: &[Message],
+ next: &[Message],
+ options: &TranscriptTurnOptions<OpenHumanRunContext>,
+ ) -> Result<Vec<TranscriptMessage>, RuntimeError> {
+ let mut rows = next
+ .iter()
+ .map(message_convert::message_to_native_chat_message)
+ .map(|message| transcript_message_from_chat(&message))
+ .collect::<Vec<_>>();
+
+ // `Message` intentionally cannot represent all durable transcript
+ // data. Match each next message to one *unused* previous position and
+ // retain the authoritative raw row there. Matching by the model
+ // message, rather than by role/content alone, keeps native tool-call
+ // envelopes distinct and also survives a compaction replacement that
+ // keeps non-prefix messages. New messages alone receive this turn's
+ // request correlation id.
+ let mut consumed = vec![false; previous.len().min(prior.len())];
+ for (next_index, next_message) in next.iter().enumerate() {
+ let matched = previous.iter().enumerate().take(consumed.len()).find_map(
+ |(previous_index, previous_message)| {
+ (!consumed[previous_index] && previous_message == next_message)
+ .then_some(previous_index)
+ },
+ );
+ if let Some(previous_index) = matched {
+ rows[next_index] = prior[previous_index].clone();
+ consumed[previous_index] = true;
+ } else {
+ rows[next_index].request_id = options.request_id.clone();
+ }
+ }
+ // The generic inference `Message::Tool` intentionally carries only a
+ // result body and correlation id. OpenHuman's explicit per-turn
+ // sidecar preserves the execution failure bit until this persistence
+ // boundary, so resumed transcript rows retain the same failure status
+ // the live tool timeline observed.
+ let failures = options
+ .context
+ .session_sidecar
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .tool_outcomes
+ .iter()
+ .filter(|outcome| !outcome.success)
+ .map(|outcome| outcome.call_id.clone())
+ .collect::<std::collections::HashSet<_>>();
+ for row in &mut rows {
+ if row.role == "tool" && row.id.as_ref().is_some_and(|id| failures.contains(id)) {
+ row.tool_failure = Some(ToolFailure {
+ failed: true,
+ detail: None,
+ });
+ }
+ }
+ Ok(rows)
+ }
+
+ fn turn_usage(
+ &self,
+ options: &TranscriptTurnOptions<OpenHumanRunContext>,
+ ) -> Result<Option<TurnUsage>, RuntimeError> {
+ let subagents = options.context.subagent_usage_entries();
+ let mut sidecar = options
+ .context
+ .session_sidecar
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .clone();
+ // The root driver returns only after synchronous delegates have
+ // completed. Snapshot their explicit ledger here, immediately before
+ // the runtime's atomic append, so durable billing cannot lag the UI.
+ sidecar.subagents = subagents;
+ let child_input = sidecar
+ .subagents
+ .iter()
+ .map(|entry| entry.usage.input_tokens)
+ .sum::<u64>();
+ let child_output = sidecar
+ .subagents
+ .iter()
+ .map(|entry| entry.usage.output_tokens)
+ .sum::<u64>();
+ let child_cached_input = sidecar
+ .subagents
+ .iter()
+ .map(|entry| entry.usage.cached_input_tokens)
+ .sum::<u64>();
+ let child_cost = sidecar
+ .subagents
+ .iter()
+ .map(|entry| entry.usage.charged_amount_usd)
+ .sum::<f64>();
+ // Keep the sidecar authoritative for the post-commit UI too.
+ *options
+ .context
+ .session_sidecar
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner) = sidecar.clone();
+ let route = sidecar.resolved_route;
+ // Preserve the old contract of omitting a synthetic all-zero usage
+ // record, while ensuring every observed driver sidecar travels in the
+ // same atomic runtime append as its transcript rows.
+ if sidecar.input_tokens.saturating_add(child_input) == 0
+ && sidecar.output_tokens.saturating_add(child_output) == 0
+ && sidecar
+ .cached_input_tokens
+ .saturating_add(child_cached_input)
+ == 0
+ && sidecar.cost_usd + child_cost == 0.0
+ && route.is_none()
+ {
+ return Ok(None);
+ }
+ Ok(Some(TurnUsage {
+ provider: route
+ .as_ref()
+ .map(|route| route.provider.clone())
+ .unwrap_or_default(),
+ model: route
+ .as_ref()
+ .map(|route| route.model.clone())
+ .unwrap_or_default(),
+ usage: MessageUsage {
+ input: sidecar.input_tokens.saturating_add(child_input),
+ output: sidecar.output_tokens.saturating_add(child_output),
+ cached_input: sidecar
+ .cached_input_tokens
+ .saturating_add(child_cached_input),
+ context_window: sidecar.context_window,
+ cost_usd: sidecar.cost_usd + child_cost,
+ },
+ ts: chrono::Utc::now().to_rfc3339(),
+ reasoning_content: None,
+ tool_calls: sidecar
+ .tool_outcomes
+ .iter()
+ .map(|outcome| TranscriptToolCall {
+ id: outcome.call_id.clone(),
+ name: outcome.name.clone(),
+ arguments: outcome.arguments.to_string(),
+ extra_content: None,
+ })
+ .collect(),
+ iteration: sidecar.model_calls.min(u32::MAX as usize) as u32,
+ }))
+ }
+}
diff --git a/crates/openhuman-core/src/agent/session_host/driver.rs b/crates/openhuman-core/src/agent/session_host/driver.rs
new file mode 100644
index 0000000000..52b85493d1
--- /dev/null
+++ b/crates/openhuman-core/src/agent/session_host/driver.rs
@@ -0,0 +1,590 @@
+//! OpenHuman's model-and-harness implementation of the neutral session driver.
+//!
+//! This adapter deliberately has no transcript, prefix, or generic history
+//! state. `tinyagents_runtime::Session` owns those concerns and gives this
+//! type the complete immutable model history and tool declaration snapshot for
+//! one invocation.
+
+mod grounded_close;
+
+use std::{collections::HashSet, sync::Arc, time::Instant};
+
+use async_trait::async_trait;
+use tinyagents_runtime::{
+ DriverFailure, DriverOutcome, DriverRequest, RuntimeError, SessionDriver, TranscriptPartial,
+};
+use tinyinference_llm::message::Message;
+use tinytools_agent::dialect::ToolDialect;
+
+use crate::agent::{
+ messages::ChatMessage,
+ session_host::turn::graph::{self, ChatTurnGraph},
+ tinyagents::{TurnModelSource, host::OpenHumanHostBase, host::OpenHumanRunContext},
+};
+
+/// Immutable host composition consumed by [`OpenHumanSessionDriver`].
+///
+/// Mutable per-turn policy belongs in `OpenHumanSessionHooks`; the driver only
+/// receives its final context, history, and immutable tool declaration view.
+pub struct OpenHumanSessionDriver {
+ turn_model_source: TurnModelSource,
+ dispatcher: Arc<dyn ToolDialect>,
+ model_name: String,
+ temperature: f64,
+ max_iterations: usize,
+ model_vision: bool,
+ run_queue:
+ Option<Arc<tinyagents_harness::run_queue::RunQueue<crate::agent::queued_turn::QueuedTurn>>>,
+ workspace: Option<tinytools::WorkspaceDescriptor>,
+ sandbox_mode: crate::agent::harness::definition::SandboxMode,
+ hosted_base: Option<Arc<OpenHumanHostBase>>,
+ agent_id: String,
+}
+
+impl OpenHumanSessionDriver {
+ #[allow(clippy::too_many_arguments)]
+ pub(crate) fn new(
+ turn_model_source: TurnModelSource,
+ dispatcher: Arc<dyn ToolDialect>,
+ model_name: String,
+ temperature: f64,
+ max_iterations: usize,
+ model_vision: bool,
+ run_queue: Option<
+ Arc<tinyagents_harness::run_queue::RunQueue<crate::agent::queued_turn::QueuedTurn>>,
+ >,
+ workspace: Option<tinytools::WorkspaceDescriptor>,
+ sandbox_mode: crate::agent::harness::definition::SandboxMode,
+ hosted_base: Option<Arc<OpenHumanHostBase>>,
+ agent_id: String,
+ ) -> Self {
+ Self {
+ turn_model_source,
+ dispatcher,
+ model_name,
+ temperature,
+ max_iterations,
+ model_vision,
+ run_queue,
+ workspace,
+ sandbox_mode,
+ hosted_base,
+ agent_id,
+ }
+ }
+}
+
+#[async_trait]
+impl SessionDriver<OpenHumanRunContext> for OpenHumanSessionDriver {
+ async fn execute(
+ &self,
+ request: DriverRequest<OpenHumanRunContext>,
+ ) -> Result<DriverOutcome, DriverFailure> {
+ // These two inputs are prepared by the OpenHuman lifecycle hook for
+ // this exact request. Falling back to the snapshots captured when the
+ // long-lived driver was constructed would let a later channel/tool
+ // policy or context change execute under stale authority.
+ let tool_policy = request
+ .run_context
+ .data
+ .tool_policy
+ .clone()
+ .ok_or_else(|| {
+ driver_failure("session turn is missing its request-scoped tool policy")
+ })?;
+ let mut context_mw = request
+ .run_context
+ .data
+ .context_middleware
+ .clone()
+ .ok_or_else(|| driver_failure("session turn is missing its request-scoped context"))?;
+ // The harness drops its `AgentRun` on an error. Snapshot the exact
+ // request boundary before assembling the graph so the error path can
+ // persist only provider-accepted rounds, plus a display-only failure
+ // record, without manufacturing a second host history.
+ let snapshot = context_mw
+ .transcript_snapshot
+ .get_or_insert_with(|| {
+ Arc::new(std::sync::Mutex::new(
+ crate::agent::tinyagents::TranscriptSnapshot {
+ request_base_len: request.history.len(),
+ ..Default::default()
+ },
+ ))
+ })
+ .clone();
+ if let Ok(mut snapshot_state) = snapshot.lock() {
+ snapshot_state
+ .pricing_model
+ .get_or_insert_with(|| self.model_name.clone());
+ }
+ let sidecar = request.run_context.data.session_sidecar.clone();
+ let started = Instant::now();
+ let user_message = request
+ .history
+ .iter()
+ .rev()
+ .find(|message| matches!(message, Message::User(_)))
+ .map(Message::text)
+ .unwrap_or_default();
+ let context_window = self
+ .turn_model_source
+ .effective_context_window(&self.model_name)
+ .await;
+ let turn_models = self
+ .turn_model_source
+ .build(
+ &self.model_name,
+ self.temperature,
+ context_window,
+ request.run_context.data.thread_id.as_deref(),
+ )
+ .map_err(driver_error)?;
+
+ let mut messages: Vec<ChatMessage> = request
+ .history
+ .iter()
+ .map(crate::agent::message_convert::message_to_native_chat_message)
+ .collect();
+ if (turn_models.supports_vision() || self.model_vision)
+ && crate::agent::multimodal::has_image_placeholders(&messages)
+ {
+ messages = crate::agent::multimodal::rehydrate_image_placeholders(&messages);
+ }
+
+ // Runtime's `ToolSnapshot` remains the model declaration and final
+ // allowlist. The actual executable instances must be supplied by the
+ // request hook as well: falling back to a long-lived driver's tool
+ // registry would let revoked or hidden tools execute under stale
+ // authority.
+ let tools = request
+ .run_context
+ .data
+ .current_tools
+ .clone()
+ .ok_or_else(|| driver_failure("session turn is missing request-scoped tools"))?;
+ let synthesized_tools = request
+ .run_context
+ .data
+ .current_synthesized_tools
+ .clone()
+ .ok_or_else(|| {
+ driver_failure("session turn is missing request-scoped synthesized tools")
+ })?;
+ let visible_tool_names: HashSet<String> = request
+ .tools
+ .specs()
+ .iter()
+ .map(|spec| spec.name.clone())
+ .collect();
+ ensure_snapshot_tools_are_executable(&visible_tool_names, &tools, &synthesized_tools)?;
+ let run_context = request.run_context.data.clone();
+ let outcome = match graph::run_chat_turn_graph(ChatTurnGraph {
+ turn_models,
+ model: self.model_name.clone(),
+ messages,
+ tools,
+ synthesized_tools,
+ visible_tool_names,
+ max_iterations: self.max_iterations,
+ on_progress: run_context.progress.clone(),
+ context_window,
+ run_queue: self.run_queue.clone(),
+ context_mw,
+ tool_policy: Some(tool_policy),
+ workspace_descriptor: self.workspace.clone(),
+ sandbox_mode: self.sandbox_mode,
+ thread_id: run_context.thread_id.clone(),
+ run_context,
+ hosted_base: self.hosted_base.clone(),
+ agent_id: self.agent_id.clone(),
+ })
+ .await
+ {
+ Ok(outcome) => outcome,
+ Err(error) => {
+ return Err(driver_error_with_snapshot(
+ error,
+ &snapshot,
+ &sidecar,
+ started.elapsed(),
+ &self.model_name,
+ ));
+ }
+ };
+
+ let close = grounded_close::close_if_needed(
+ &self.turn_model_source,
+ &self.model_name,
+ self.temperature,
+ request.run_context.data.thread_id.as_deref(),
+ self.dispatcher.as_ref(),
+ &request.history,
+ &user_message,
+ &outcome,
+ )
+ .await;
+ let mut output = close
+ .as_ref()
+ .map(|close| close.output.clone())
+ .unwrap_or_else(|| outcome.text.clone());
+ let mut history = request.history;
+ let conversation = crate::agent::message_convert::provider_messages_from_conversation(
+ self.dispatcher.as_ref(),
+ &outcome.conversation,
+ );
+ let mut appended = crate::agent::message_convert::history_to_messages(&conversation);
+ if close.is_some() {
+ // A blank or breaker-halt terminal row is not the durable answer.
+ // Retain every completed tool round and replace only that final
+ // assistant row with the verified/deterministic grounded close.
+ if appended
+ .last()
+ .is_some_and(|message| matches!(message, Message::Assistant(_)))
+ {
+ appended.pop();
+ }
+ appended.push(Message::assistant(output.clone()));
+ }
+ history.extend(appended);
+
+ let required_output = request.run_context.data.required_output.clone();
+ let required_repair = match required_output.as_ref() {
+ Some(contract) => {
+ grounded_close::repair_required_output(
+ &self.turn_model_source,
+ &self.model_name,
+ self.temperature,
+ request.run_context.data.thread_id.as_deref(),
+ self.dispatcher.as_ref(),
+ contract,
+ &history,
+ &output,
+ close.is_none() && request.run_context.data.progress.is_some(),
+ request.run_context.data.progress.as_ref(),
+ outcome.model_calls.saturating_add(1) as u32,
+ )
+ .await
+ }
+ None => None,
+ };
+ if let Some(repair) = &required_repair {
+ output = repair.output.clone();
+ if history
+ .last()
+ .is_some_and(|message| matches!(message, Message::Assistant(_)))
+ {
+ history.pop();
+ }
+ history.push(Message::assistant(output.clone()));
+ }
+
+ // This is deliberately an out-of-band observation rather than a
+ // second history or transcript. The runtime only reads it from
+ // `after_commit`, so a failed/cancelled turn cannot publish its usage
+ // or tool outcomes as if they had become durable.
+ {
+ let repair_usage = required_repair.as_ref().map(|repair| &repair.usage);
+ let mut observed = sidecar
+ .lock()
+ .unwrap_or_else(|poisoned| poisoned.into_inner());
+ observed.model_calls = outcome.model_calls
+ + close
+ .as_ref()
+ .map(|close| close.usage.model_calls)
+ .unwrap_or_default()
+ + repair_usage
+ .map(|usage| usage.model_calls)
+ .unwrap_or_default();
+ observed.tool_calls = outcome.tool_calls;
+ observed.input_tokens = outcome.input_tokens
+ + close
+ .as_ref()
+ .map(|close| close.usage.input_tokens)
+ .unwrap_or_default()
+ + repair_usage
+ .map(|usage| usage.input_tokens)
+ .unwrap_or_default();
+ observed.output_tokens = outcome.output_tokens
+ + close
+ .as_ref()
+ .map(|close| close.usage.output_tokens)
+ .unwrap_or_default()
+ + repair_usage
+ .map(|usage| usage.output_tokens)
+ .unwrap_or_default();
+ observed.cached_input_tokens = outcome.cached_input_tokens
+ + close
+ .as_ref()
+ .map(|close| close.usage.cached_input_tokens)
+ .unwrap_or_default()
+ + repair_usage
+ .map(|usage| usage.cached_input_tokens)
+ .unwrap_or_default();
+ observed.cost_usd = outcome.charged_amount_usd
+ + close
+ .as_ref()
+ .map(|close| close.usage.charged_amount_usd)
+ .unwrap_or_default()
+ + repair_usage
+ .map(|usage| usage.charged_amount_usd)
+ .unwrap_or_default();
+ observed.duration = Some(started.elapsed());
+ observed.tool_outcomes = outcome.tool_outcomes.clone();
+ observed.hit_cap = outcome.hit_cap;
+ observed.wrap_up_injected = outcome.wrap_up_injected;
+ observed.resolved_route = outcome.resolved_route.clone();
+ }
+ Ok(DriverOutcome {
+ history,
+ output: Some(output),
+ partial: None,
+ interrupted: outcome.early_exit_tool.is_some() || outcome.hit_cap,
+ })
+ }
+}
+
+fn driver_error(error: impl std::fmt::Display) -> DriverFailure {
+ driver_failure(error)
+}
+
+fn driver_failure(error: impl std::fmt::Display) -> DriverFailure {
+ DriverFailure {
+ error: RuntimeError::Driver(error.to_string()),
+ partial: None,
+ }
+}
+
+/// Refuse a provider declaration that has no executable request-scoped source.
+/// Sources may contain additional durable tools because the runtime snapshot is
+/// the final provider-visible allowlist, but every declared name must resolve
+/// here before the graph begins.
+fn ensure_snapshot_tools_are_executable(
+ visible_tool_names: &HashSet<String>,
+ tools: &Arc<Vec<Box<dyn tinytools::Tool>>>,
+ synthesized_tools: &Arc<Vec<Box<dyn tinytools::Tool>>>,
+) -> Result<(), DriverFailure> {
+ let executable_tool_names = tools
+ .iter()
+ .chain(synthesized_tools.iter())
+ .map(|tool| tool.name().to_string())
+ .collect::<HashSet<_>>();
+ let missing = visible_tool_names
+ .difference(&executable_tool_names)
+ .cloned()
+ .collect::<Vec<_>>();
+ if missing.is_empty() {
+ Ok(())
+ } else {
+ Err(driver_failure(format!(
+ "session tool snapshot declares non-executable tools: {}",
+ missing.join(", ")
+ )))
+ }
+}
+
+fn driver_error_with_snapshot(
+ error: impl std::fmt::Display,
+ snapshot: &crate::agent::tinyagents::TranscriptSnapshotSink,
+ sidecar: &std::sync::Arc<
+ std::sync::Mutex<crate::agent::tinyagents::host::run_context::SessionTurnSidecar>,
+ >,
+ elapsed: std::time::Duration,
+ fallback_model: &str,
+) -> DriverFailure {
+ let error = error.to_string();
+ let guard = snapshot
+ .lock()
+ .unwrap_or_else(|poisoned| poisoned.into_inner());
+ // A graph error drops the harness's `AgentRun`, but its snapshot has
+ // already observed provider-accepted usage and completed tool outcomes.
+ // Copy those into the per-turn sidecar *before* producing the partial so
+ // runtime's single atomic append carries the same usage/failure truth as a
+ // successful turn. The partial history below remains accepted-only.
+ {
+ let mut observed = sidecar
+ .lock()
+ .unwrap_or_else(|poisoned| poisoned.into_inner());
+ observed.model_calls = guard.model_calls as usize;
+ observed.tool_calls = guard.tool_outcomes.len();
+ observed.input_tokens = guard.input_tokens;
+ observed.output_tokens = guard.output_tokens;
+ observed.cached_input_tokens = guard.cached_input_tokens;
+ observed.cost_usd = if guard.charged_amount_usd > 0.0 {
+ guard.charged_amount_usd
+ } else {
+ let pricing_model = guard
+ .resolved_route
+ .as_ref()
+ .map(|route| route.route.as_str())
+ .filter(|route| !route.trim().is_empty())
+ .unwrap_or(fallback_model);
+ crate::agent::cost::estimate_call_cost_usd(
+ pricing_model,
+ &crate::inference::provider::UsageInfo {
+ input_tokens: guard.input_tokens,
+ output_tokens: guard.output_tokens,
+ context_window: 0,
+ cached_input_tokens: guard.cached_input_tokens,
+ cache_creation_tokens: 0,
+ reasoning_tokens: 0,
+ charged_amount_usd: 0.0,
+ },
+ )
+ };
+ observed.duration = Some(elapsed);
+ observed.tool_outcomes = guard.tool_outcomes.clone();
+ observed.resolved_route = guard.resolved_route.clone();
+ }
+ if guard.messages.is_empty() {
+ return driver_failure(error);
+ }
+ let accepted_end = guard.accepted_end();
+ let history = guard.messages[..accepted_end].to_vec();
+ let unanswered =
+ crate::agent::tinyagents::render_unanswered_steps(&guard.messages[accepted_end..]);
+ let display = match unanswered {
+ Some(steps) => format!("The turn stopped before completion: {error}.\n\n{steps}"),
+ None => format!("The turn stopped before completion: {error}."),
+ };
+ DriverFailure {
+ error: RuntimeError::Driver(error),
+ partial: Some(DriverOutcome {
+ history,
+ output: None,
+ partial: Some(TranscriptPartial::new(display)),
+ interrupted: true,
+ }),
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn sidecar() -> std::sync::Arc<
+ std::sync::Mutex<crate::agent::tinyagents::host::run_context::SessionTurnSidecar>,
+ > {
+ crate::agent::tinyagents::host::OpenHumanRunContext::new()
+ .session_sidecar
+ .clone()
+ }
+
+ #[test]
+ fn graph_failure_persists_only_accepted_snapshot_history() {
+ let snapshot = Arc::new(std::sync::Mutex::new(
+ crate::agent::tinyagents::TranscriptSnapshot {
+ messages: vec![
+ Message::system("stable prefix"),
+ Message::user("request"),
+ Message::assistant("provider reply not yet accepted by a later request"),
+ ],
+ accepted_len: 2,
+ request_base_len: 2,
+ ..Default::default()
+ },
+ ));
+
+ let failure = driver_error_with_snapshot(
+ "provider rejected follow-up",
+ &snapshot,
+ &sidecar(),
+ std::time::Duration::from_millis(1),
+ "chat-v1",
+ );
+ let partial = failure.partial.expect("snapshot should produce a partial");
+ assert_eq!(partial.history.len(), 2);
+ assert_eq!(partial.history[0].text(), "stable prefix");
+ assert_eq!(partial.history[1].text(), "request");
+ assert!(
+ partial
+ .partial
+ .expect("display partial")
+ .content
+ .contains("provider rejected follow-up")
+ );
+ }
+
+ #[test]
+ fn graph_failure_copies_snapshot_usage_and_failed_tool_outcome_to_sidecar() {
+ let snapshot = Arc::new(std::sync::Mutex::new(
+ crate::agent::tinyagents::TranscriptSnapshot {
+ messages: vec![Message::user("request"), Message::tool("call-1", "denied")],
+ accepted_len: 1,
+ request_base_len: 1,
+ input_tokens: 21,
+ output_tokens: 8,
+ cached_input_tokens: 3,
+ charged_amount_usd: 0.004,
+ resolved_route: Some(tinyinference_llm::model::ResolvedModelRoute::new(
+ "openhuman",
+ "chat-concrete",
+ "chat-v1",
+ )),
+ model_calls: 2,
+ tool_outcomes: vec![crate::agent::tinyagents::ToolCallOutcome {
+ call_id: "call-1".into(),
+ name: "write_file".into(),
+ arguments: serde_json::json!({"path": "blocked.txt"}),
+ success: false,
+ content: "denied".into(),
+ duration_ms: 17,
+ }],
+ },
+ ));
+ let sidecar = sidecar();
+
+ let failure = driver_error_with_snapshot(
+ "tool follow-up was rejected",
+ &snapshot,
+ &sidecar,
+ std::time::Duration::from_millis(25),
+ "chat-v1",
+ );
+
+ let partial = failure.partial.expect("recoverable snapshot partial");
+ assert_eq!(partial.history, vec![Message::user("request")]);
+ let observed = sidecar.lock().expect("sidecar");
+ assert_eq!(observed.model_calls, 2);
+ assert_eq!(observed.input_tokens, 21);
+ assert_eq!(observed.output_tokens, 8);
+ assert_eq!(observed.cached_input_tokens, 3);
+ assert!((observed.cost_usd - 0.004).abs() < f64::EPSILON);
+ let route = observed
+ .resolved_route
+ .as_ref()
+ .expect("accepted route reaches sidecar");
+ assert_eq!(route.provider, "openhuman");
+ assert_eq!(route.model, "chat-concrete");
+ assert_eq!(route.route, "chat-v1");
+ assert_eq!(observed.tool_calls, 1);
+ assert_eq!(
+ observed.duration,
+ Some(std::time::Duration::from_millis(25))
+ );
+ assert_eq!(observed.tool_outcomes.len(), 1);
+ let failure = &observed.tool_outcomes[0];
+ assert!(
+ !failure.success,
+ "completed failure state survives graph error"
+ );
+ assert_eq!(failure.content, "denied");
+ assert_eq!(
+ failure.arguments,
+ serde_json::json!({"path": "blocked.txt"})
+ );
+ assert_eq!(failure.duration_ms, 17);
+ }
+
+ #[test]
+ fn tool_snapshot_with_no_executable_source_fails_closed_before_graph() {
+ let visible = HashSet::from(["revoked_tool".to_string()]);
+ let error = ensure_snapshot_tools_are_executable(
+ &visible,
+ &Arc::new(Vec::new()),
+ &Arc::new(Vec::new()),
+ )
+ .expect_err("a declared tool must have a request-scoped executable source");
+ assert!(error.error.to_string().contains("revoked_tool"));
+ }
+}
diff --git a/crates/openhuman-core/src/agent/session_host/driver/grounded_close.rs b/crates/openhuman-core/src/agent/session_host/driver/grounded_close.rs
new file mode 100644
index 0000000000..83708ec93d
--- /dev/null
+++ b/crates/openhuman-core/src/agent/session_host/driver/grounded_close.rs
@@ -0,0 +1,252 @@
+//! Tools-disabled, evidence-grounded repairs for terminal session replies.
+//!
+//! The normal loop owns the ordinary final model response. This module only
+//! runs when that response is absent, a no-progress breaker stopped the loop,
+//! or an older harness configuration reached a cap without its in-loop close.
+//! It deliberately uses the same explicit model source as the turn and keeps
+//! its usage in a sidecar; it never owns transcript history or persistence.
+
+use futures::StreamExt;
+use tinyinference_llm::model::{ModelRequest, ModelStreamItem};
+use tinytools_agent::dialect::ToolDialect;
+
+use crate::agent::{
+ message_convert::{dialect_response_from_provider, message_to_native_chat_message},
+ messages::ChatMessage,
+ session_host::turn_checkpoint::{
+ self, CloseVerdict, build_deterministic_checkpoint, build_deterministic_final_summary,
+ close_verification_prompt, final_answer_instruction, parse_close_verdict,
+ render_tool_results, results_from_tool_outcomes,
+ },
+ tinyagents::{TinyagentsTurnOutcome, TurnModelSource},
+};
+use crate::inference::provider::{AGENT_TURN_MAX_OUTPUT_TOKENS, ChatResponse, UsageInfo};
+
+/// Accounting from model calls performed after the harness loop has ended.
+#[derive(Default)]
+pub(super) struct RepairUsage {
+ pub(super) model_calls: usize,
+ pub(super) input_tokens: u64,
+ pub(super) output_tokens: u64,
+ pub(super) cached_input_tokens: u64,
+ pub(super) charged_amount_usd: f64,
+}
+
+impl RepairUsage {
+ fn record(&mut self, usage: Option<UsageInfo>) {
+ self.model_calls += 1;
+ if let Some(usage) = usage {
+ self.input_tokens += usage.input_tokens;
+ self.output_tokens += usage.output_tokens;
+ self.cached_input_tokens += usage.cached_input_tokens;
+ self.charged_amount_usd += usage.charged_amount_usd;
+ }
+ }
+}
+
+/// A repaired terminal reply and the extra provider usage it incurred.
+pub(super) struct GroundedClose {
+ pub(super) output: String,
+ pub(super) usage: RepairUsage,
+}
+
+/// Repair an otherwise valid terminal reply which omits the host's required
+/// structured-output block. This mirrors the legacy session contract while
+/// keeping the repair call and its usage inside the explicit driver sidecar.
+#[allow(clippy::too_many_arguments)]
+pub(super) async fn repair_required_output(
+ source: &TurnModelSource,
+ model: &str,
+ temperature: f64,
+ thread_id: Option<&str>,
+ dispatcher: &dyn ToolDialect,
+ contract: &tinyagents_harness::config::RequiredOutput,
+ history: &[tinyinference_llm::message::Message],
+ reply: &str,
+ reply_already_streamed: bool,
+ progress: Option<&tokio::sync::mpsc::Sender<crate::agent::progress::AgentProgress>>,
+ iteration: u32,
+) -> Option<GroundedClose> {
+ use crate::agent::harness::required_output as required;
+
+ if required::output_satisfies_contract(reply, contract) {
+ return None;
+ }
+
+ let mut prompt_history: Vec<ChatMessage> =
+ history.iter().map(message_to_native_chat_message).collect();
+ prompt_history.push(ChatMessage::user(required::repair_instruction(contract)));
+ let (candidate, candidate_usage) =
+ completion(source, model, temperature, thread_id, prompt_history).await;
+ let mut usage = RepairUsage::default();
+ usage.record(candidate_usage);
+ let candidate = candidate.trim().to_owned();
+ let candidate_is_usable = !candidate.is_empty()
+ && !contains_tool_call(dispatcher, &candidate)
+ && required::output_satisfies_contract(&candidate, contract);
+
+ if !reply_already_streamed {
+ let output = if candidate_is_usable {
+ candidate
+ } else {
+ format!("{}\n\n{reply}", required::synthesize_block(contract))
+ };
+ return Some(GroundedClose { output, usage });
+ }
+
+ // The main loop may have already emitted the original reply. Never
+ // replace what the user saw: append the recovered block (or a deterministic
+ // one) and stream that exact continuation before returning it for commit.
+ let correction = if candidate_is_usable {
+ required::find_required_block(&candidate, contract)
+ .and_then(|block| serde_json::to_string(&block).ok())
+ .unwrap_or_else(|| required::synthesize_block(contract))
+ } else {
+ required::synthesize_block(contract)
+ };
+ let continuation = format!("\n\n{correction}");
+ if let Some(progress) = progress {
+ if let Err(error) = progress
+ .send(crate::agent::progress::AgentProgress::TextDelta {
+ delta: continuation.clone(),
+ iteration,
+ })
+ .await
+ {
+ tracing::debug!(%error, "[session-runtime] required-output repair progress receiver closed");
+ }
+ }
+ Some(GroundedClose {
+ output: format!("{reply}{continuation}"),
+ usage,
+ })
+}
+
+/// Return `None` when the loop's terminal text is already usable.
+#[allow(clippy::too_many_arguments)]
+pub(super) async fn close_if_needed(
+ source: &TurnModelSource,
+ model: &str,
+ temperature: f64,
+ thread_id: Option<&str>,
+ dispatcher: &dyn ToolDialect,
+ base_history: &[tinyinference_llm::message::Message],
+ user_message: &str,
+ outcome: &TinyagentsTurnOutcome,
+) -> Option<GroundedClose> {
+ let needs_cap_close = outcome.hit_cap && !outcome.wrap_up_injected;
+ let needs_final_close = outcome.text.trim().is_empty() || outcome.breaker_halt.is_some();
+ if !needs_cap_close && !needs_final_close {
+ return None;
+ }
+
+ let records = results_from_tool_outcomes(&outcome.tool_outcomes);
+ let rendered = render_tool_results(&records, turn_checkpoint::GROUNDING_TOTAL_CHARS);
+ let instruction = if needs_cap_close {
+ format!(
+ "{}\n\n<tool_records>\n{}\n</tool_records>",
+ turn_checkpoint::MAX_ITER_CHECKPOINT_INSTRUCTION,
+ if rendered.is_empty() {
+ "(no tool calls completed)"
+ } else {
+ &rendered
+ }
+ )
+ } else {
+ final_answer_instruction(outcome.breaker_halt.as_deref(), &rendered)
+ };
+ let mut base: Vec<ChatMessage> = base_history
+ .iter()
+ .map(message_to_native_chat_message)
+ .collect();
+ base.push(ChatMessage::user(instruction));
+
+ let mut usage = RepairUsage::default();
+ let (candidate, candidate_usage) =
+ completion(source, model, temperature, thread_id, base).await;
+ usage.record(candidate_usage);
+ let candidate = candidate.trim().to_owned();
+
+ // A closing response is only user-visible after a separate, tool-less
+ // verifier accepts it. This prevents a fluent repair from contradicting a
+ // captured failure result or merely narrating intended work.
+ let accepted = if candidate.is_empty() || contains_tool_call(dispatcher, &candidate) {
+ false
+ } else {
+ let prompt = close_verification_prompt(user_message, &rendered, &candidate);
+ let (verdict, verdict_usage) = completion(
+ source,
+ model,
+ temperature,
+ thread_id,
+ vec![ChatMessage::user(prompt)],
+ )
+ .await;
+ usage.record(verdict_usage);
+ parse_close_verdict(&verdict) == CloseVerdict::Accept
+ };
+
+ let output = if accepted {
+ candidate
+ } else if needs_cap_close {
+ build_deterministic_checkpoint(&records, outcome.model_calls)
+ } else {
+ build_deterministic_final_summary(&records, outcome.breaker_halt.as_deref())
+ };
+ Some(GroundedClose { output, usage })
+}
+
+async fn completion(
+ source: &TurnModelSource,
+ model: &str,
+ temperature: f64,
+ thread_id: Option<&str>,
+ messages: Vec<ChatMessage>,
+) -> (String, Option<UsageInfo>) {
+ let Ok(model_client) = source.build_summarizer(model, temperature, thread_id) else {
+ return (String::new(), None);
+ };
+ let request = ModelRequest::new(
+ messages
+ .iter()
+ .map(crate::agent::tinyagents::chat_message_to_message)
+ .collect(),
+ )
+ .with_model(model)
+ .with_temperature(temperature)
+ .with_max_tokens(AGENT_TURN_MAX_OUTPUT_TOKENS);
+ let Ok(mut stream) = model_client.stream(&(), request).await else {
+ return (String::new(), None);
+ };
+ let mut buffered = String::new();
+ while let Some(item) = stream.next().await {
+ match item {
+ ModelStreamItem::MessageDelta(delta) => buffered.push_str(&delta.text),
+ ModelStreamItem::Completed(response) => {
+ let text = response.text();
+ let selected = (!text.trim().is_empty())
+ .then_some(text)
+ .unwrap_or(buffered);
+ return (
+ selected,
+ crate::agent::tinyagents::model::usage_info_from_response(&response),
+ );
+ }
+ ModelStreamItem::Failed(_) | ModelStreamItem::ProviderFailed(_) => {
+ return (String::new(), None);
+ }
+ _ => {}
+ }
+ }
+ (String::new(), None)
+}
+
+fn contains_tool_call(dispatcher: &dyn ToolDialect, text: &str) -> bool {
+ !dispatcher
+ .parse_response(&dialect_response_from_provider(&ChatResponse {
+ text: Some(text.to_owned()),
+ ..ChatResponse::default()
+ }))
+ .1
+ .is_empty()
+}
diff --git a/crates/openhuman-core/src/agent/session_host/factory.rs b/crates/openhuman-core/src/agent/session_host/factory.rs
new file mode 100644
index 0000000000..c42736a7d3
--- /dev/null
+++ b/crates/openhuman-core/src/agent/session_host/factory.rs
@@ -0,0 +1,37 @@
+//! Composition factory for OpenHuman-owned TinyAgents sessions.
+
+use std::sync::Arc;
+use tinyagents_runtime::{
+ PrefixSnapshot, RuntimeError, Session, SessionBuilder, SessionDriver, ToolSnapshot,
+};
+use tinyagents_session::transcript::{TranscriptLocator, TranscriptMeta};
+
+use crate::agent::tinyagents::host::OpenHumanRunContext;
+
+use super::{OpenHumanSessionHooks, OpenHumanTranscriptCodec};
+
+/// Builds the neutral runtime from OpenHuman's resolved policy and adapters.
+///
+/// No stateful history, transcript delta or prefix implementation belongs in
+/// this type; those remain directly owned by `tinyagents_runtime::Session`.
+pub struct OpenHumanSessionFactory;
+
+impl OpenHumanSessionFactory {
+ pub fn build(
+ driver: Arc<dyn SessionDriver<OpenHumanRunContext>>,
+ hooks: Arc<OpenHumanSessionHooks>,
+ prefix: PrefixSnapshot,
+ tools: ToolSnapshot,
+ locator: Arc<dyn TranscriptLocator>,
+ stem: impl Into<String>,
+ meta: TranscriptMeta,
+ ) -> Result<Session<OpenHumanRunContext>, RuntimeError> {
+ SessionBuilder::new(driver)
+ .codec(Arc::new(OpenHumanTranscriptCodec))
+ .hooks(hooks)
+ .prefix(prefix)
+ .tool_snapshot(tools)
+ .transcript(locator, stem, meta)
+ .build()
+ }
+}
diff --git a/crates/openhuman-core/src/agent/session_host/hooks.rs b/crates/openhuman-core/src/agent/session_host/hooks.rs
new file mode 100644
index 0000000000..cc00a61613
--- /dev/null
+++ b/crates/openhuman-core/src/agent/session_host/hooks.rs
@@ -0,0 +1,130 @@
+//! OpenHuman lifecycle observations for a neutral TinyAgents session.
+
+use async_trait::async_trait;
+use std::{future::Future, pin::Pin, sync::Arc};
+use tinyagents_runtime::{
+ CommitReceipt, ResumePreparation, RuntimeError, SessionHooks, SessionStateView,
+ SessionTerminal, SessionTurnOutcome, SessionTurnRequest, TranscriptTurnOptions, TurnOptions,
+ TurnPreparation,
+};
+
+use crate::agent::tinyagents::host::OpenHumanRunContext;
+
+/// Product callbacks attached to one runtime session.
+///
+/// The runtime makes the durable commit before `after_commit` and guarantees a
+/// single terminal callback. OpenHuman adapters use these points for progress,
+/// BUS projection, memory/experience work and usage finalization.
+pub struct OpenHumanSessionHooks {
+ before_resume: Arc<
+ dyn for<'a> Fn(
+ &'a mut SessionTurnRequest,
+ &'a mut TurnOptions<OpenHumanRunContext>,
+ SessionStateView<'a>,
+ ) -> HookFuture<'a, ResumePreparation>
+ + Send
+ + Sync,
+ >,
+ before: Arc<
+ dyn for<'a> Fn(
+ &'a mut SessionTurnRequest,
+ &'a mut TurnOptions<OpenHumanRunContext>,
+ SessionStateView<'a>,
+ ) -> HookFuture<'a, TurnPreparation>
+ + Send
+ + Sync,
+ >,
+ before_commit: Arc<
+ dyn for<'a> Fn(
+ &'a SessionTurnOutcome,
+ &'a TranscriptTurnOptions<OpenHumanRunContext>,
+ ) -> HookFuture<'a, ()>
+ + Send
+ + Sync,
+ >,
+ committed:
+ Arc<dyn Fn(CommitReceipt<OpenHumanRunContext>) -> HookFuture<'static, ()> + Send + Sync>,
+ terminal: Arc<dyn Fn(SessionTerminal) -> HookFuture<'static, ()> + Send + Sync>,
+}
+
+type HookFuture<'a, T> = Pin<Box<dyn Future<Output = Result<T, RuntimeError>> + Send + 'a>>;
+
+impl OpenHumanSessionHooks {
+ /// Installs product callbacks. Callbacks are intentionally synchronous;
+ /// expensive memory and learning work should be spawned by `committed` so
+ /// it cannot relabel an already durable turn.
+ pub fn new(
+ before_resume: impl for<'a> Fn(
+ &'a mut SessionTurnRequest,
+ &'a mut TurnOptions<OpenHumanRunContext>,
+ SessionStateView<'a>,
+ ) -> HookFuture<'a, ResumePreparation>
+ + Send
+ + Sync
+ + 'static,
+ before: impl for<'a> Fn(
+ &'a mut SessionTurnRequest,
+ &'a mut TurnOptions<OpenHumanRunContext>,
+ SessionStateView<'a>,
+ ) -> HookFuture<'a, TurnPreparation>
+ + Send
+ + Sync
+ + 'static,
+ before_commit: impl for<'a> Fn(
+ &'a SessionTurnOutcome,
+ &'a TranscriptTurnOptions<OpenHumanRunContext>,
+ ) -> HookFuture<'a, ()>
+ + Send
+ + Sync
+ + 'static,
+ committed: impl Fn(CommitReceipt<OpenHumanRunContext>) -> HookFuture<'static, ()>
+ + Send
+ + Sync
+ + 'static,
+ terminal: impl Fn(SessionTerminal) -> HookFuture<'static, ()> + Send + Sync + 'static,
+ ) -> Self {
+ Self {
+ before_resume: Arc::new(before_resume),
+ before: Arc::new(before),
+ before_commit: Arc::new(before_commit),
+ committed: Arc::new(committed),
+ terminal: Arc::new(terminal),
+ }
+ }
+}
+
+#[async_trait]
+impl SessionHooks<OpenHumanRunContext> for OpenHumanSessionHooks {
+ async fn before_resume(
+ &self,
+ request: &mut SessionTurnRequest,
+ options: &mut TurnOptions<OpenHumanRunContext>,
+ state: SessionStateView<'_>,
+ ) -> Result<ResumePreparation, RuntimeError> {
+ (self.before_resume)(request, options, state).await
+ }
+ async fn before_turn(
+ &self,
+ request: &mut SessionTurnRequest,
+ options: &mut TurnOptions<OpenHumanRunContext>,
+ state: SessionStateView<'_>,
+ ) -> Result<TurnPreparation, RuntimeError> {
+ (self.before)(request, options, state).await
+ }
+ async fn before_commit(
+ &self,
+ outcome: &SessionTurnOutcome,
+ options: &TranscriptTurnOptions<OpenHumanRunContext>,
+ ) -> Result<(), RuntimeError> {
+ (self.before_commit)(outcome, options).await
+ }
+ async fn after_commit(
+ &self,
+ receipt: CommitReceipt<OpenHumanRunContext>,
+ ) -> Result<(), RuntimeError> {
+ (self.committed)(receipt).await
+ }
+ async fn on_terminal(&self, terminal: SessionTerminal) -> Result<(), RuntimeError> {
+ (self.terminal)(terminal).await
+ }
+}
diff --git a/crates/openhuman-core/src/agent/session_host/mod.rs b/crates/openhuman-core/src/agent/session_host/mod.rs
new file mode 100644
index 0000000000..a51176ae8d
--- /dev/null
+++ b/crates/openhuman-core/src/agent/session_host/mod.rs
@@ -0,0 +1,64 @@
+//! Stateful agent session — the single execution tier.
+//!
+//! This module owns the [`OpenHumanSessionHost`] struct, which drives per-turn
+//! interaction with the provider, tool registry, memory system, and
+//! hook pipeline. It is the runtime the `channels`, `local_ai`, and
+//! `cron` layers invoke when they need a conversation to make
+//! progress.
+//!
+//! # Product shell over TinyAgents
+//!
+//! Every production turn is a `tinyagents_runtime::Session` transition. The
+//! OpenHuman driver supplies model/tool execution; codec and hooks supply the
+//! product transcript dialect, prompt policy, and post-durability effects.
+//! The runtime, rather than this host, owns generic history, raw transcript
+//! reconciliation, prefix stability, tool snapshots, resume, and persistence.
+//!
+//! # File layout
+//!
+//! | File | Role |
+//! |---------------|------------------------------------------------------------------|
+//! | [`types`] | `OpenHumanSessionHost` and `SessionHostBuilder` struct definitions (no logic). |
+//! | [`builder`] | `SessionHostBuilder` fluent API + `OpenHumanSessionHost::from_config` factory. |
+//! | [`runtime_session`] | Runtime session composition and public `turn()`. |
+//! | [`driver`] | OpenHuman model/harness `SessionDriver`. |
+//! | [`hooks`] | Product preparation/commit/terminal hooks. |
+//! | [`runtime`] | Public accessors and `run_single` / `run_interactive`. |
+//!
+//! External callers should import [`OpenHumanSessionHost`] and [`SessionHostBuilder`] from
+//! `crate::agent`, which re-exports them from this module.
+//! The child files are an implementation detail.
+
+pub(crate) use builder::provider_role_for_definition;
+
+mod builder;
+mod codec;
+mod driver;
+mod factory;
+mod hooks;
+mod policy;
+mod runtime;
+mod runtime_session;
+#[cfg(test)]
+mod tool_progress;
+mod turn;
+// `pub(crate)` since issue #6014: the tool-call-cap instruction is now appended
+// inside the loop by `tinyagents::middleware::FinalCallWrapUpMiddleware`, so the
+// harness-assembly site has to name it. It stays the one definition — the whole
+// point is that the in-loop conclusion and the out-of-band fallback ask for the
+// same thing.
+pub(crate) mod turn_checkpoint;
+mod types;
+
+pub use codec::OpenHumanTranscriptCodec;
+pub use factory::OpenHumanSessionFactory;
+pub use hooks::OpenHumanSessionHooks;
+pub use types::{OpenHumanSessionHost, SessionHostBuilder, TurnOverrides};
+
+// Re-export the duplicate-tool-spec guard for sibling harness modules
+// (`session::runtime`, `subagent_runner`) so all provider call sites
+// share one tested implementation.
+pub(crate) use builder::dedup_visible_tool_specs;
+
+#[cfg(test)]
+mod runtime_adapter_tests;
diff --git a/crates/openhuman-core/src/agent/session_host/policy.rs b/crates/openhuman-core/src/agent/session_host/policy.rs
new file mode 100644
index 0000000000..a6f418b213
--- /dev/null
+++ b/crates/openhuman-core/src/agent/session_host/policy.rs
@@ -0,0 +1,5 @@
+//! OpenHuman-only session policy seams.
+//!
+//! Tool authorization, required-output and checkpoint prompts stay in this
+//! host package. Generic snapshot storage and execution stay in
+//! `tinyagents-runtime`.
diff --git a/crates/openhuman-core/src/agent/harness/session/runtime.rs b/crates/openhuman-core/src/agent/session_host/runtime.rs
similarity index 89%
rename from crates/openhuman-core/src/agent/harness/session/runtime.rs
rename to crates/openhuman-core/src/agent/session_host/runtime.rs
index 61f67d28d3..22488dfddf 100644
--- a/crates/openhuman-core/src/agent/harness/session/runtime.rs
+++ b/crates/openhuman-core/src/agent/session_host/runtime.rs
@@ -7,7 +7,7 @@
//! makes it obvious which methods are cheap getters vs which actually
//! drive the model.
//!
-//! Each child module contributes one `impl Agent` block:
+//! Each child module contributes one `impl OpenHumanSessionHost` block:
//!
//! | File | Role |
//! |-----------------|-------------------------------------------------------|
@@ -18,11 +18,6 @@
//! | `run_loop` | `run_single` and `run_interactive`. |
mod accessors;
-mod resume;
mod run_loop;
mod turn_helpers;
mod turn_results;
-
-#[cfg(test)]
-#[path = "runtime_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/agent/harness/session/runtime/accessors.rs b/crates/openhuman-core/src/agent/session_host/runtime/accessors.rs
similarity index 88%
rename from crates/openhuman-core/src/agent/harness/session/runtime/accessors.rs
rename to crates/openhuman-core/src/agent/session_host/runtime/accessors.rs
index 94f802f9fc..f033c5aca6 100644
--- a/crates/openhuman-core/src/agent/harness/session/runtime/accessors.rs
+++ b/crates/openhuman-core/src/agent/session_host/runtime/accessors.rs
@@ -1,8 +1,8 @@
-//! Public getters and setters on [`Agent`]: tool registry views, config
+//! Public getters and setters on [`OpenHumanSessionHost`]: tool registry views, config
//! snapshots, session identity, and the per-session tool-visibility filter
//! (which rebuilds the tool policy snapshot on every change).
-use super::super::types::{Agent, AgentBuilder};
+use super::super::types::{OpenHumanSessionHost, SessionHostBuilder};
use crate::agent::messages::ConversationMessage;
use crate::memory::Memory;
use crate::tools::agent_policy::ToolPolicyEngine;
@@ -10,16 +10,16 @@ use std::collections::HashSet;
use std::sync::Arc;
use tinytools::{Tool, ToolSpec};
-impl Agent {
+impl OpenHumanSessionHost {
// ─────────────────────────────────────────────────────────────────
// Small accessors used by `run_single` + `turn` + sub-agent runner
// ─────────────────────────────────────────────────────────────────
- pub(in crate::agent::harness::session) fn event_session_id(&self) -> &str {
+ pub(in crate::agent::session_host) fn event_session_id(&self) -> &str {
&self.event_session_id
}
- pub(in crate::agent::harness::session) fn event_channel(&self) -> &str {
+ pub(in crate::agent::session_host) fn event_channel(&self) -> &str {
&self.event_channel
}
@@ -27,9 +27,9 @@ impl Agent {
/// (`"welcome"`, `"orchestrator"`, `"integrations_agent"`, …).
///
/// Exposed so callers that build sessions via
- /// [`Agent::from_config_for_agent`] can stamp the resolved id onto
+ /// [`OpenHumanSessionHost::from_config_for_agent`] can stamp the resolved id onto
/// correlation logs and progress events without reaching for the
- /// source `Config`. See [`AgentBuilder::agent_definition_name`]
+ /// source `Config`. See [`SessionHostBuilder::agent_definition_name`]
/// for the full list of downstream surfaces (transcript filename,
/// transcript metadata header, and `PromptContext::agent_id`) that
/// read this field.
@@ -37,9 +37,9 @@ impl Agent {
&self.agent_definition_name
}
- /// Returns a new `AgentBuilder`.
- pub fn builder() -> AgentBuilder {
- AgentBuilder::new()
+ /// Returns a new `SessionHostBuilder`.
+ pub fn builder() -> SessionHostBuilder {
+ SessionHostBuilder::new()
}
/// Clone the agent's model source. Used by the sub-agent runner /
@@ -71,7 +71,7 @@ impl Agent {
/// Clone the agent's synthesised delegation tools `Arc`.
///
- /// Replaced wholesale on every [`Agent::refresh_delegation_tools`], so a
+ /// Replaced wholesale on every [`OpenHumanSessionHost::refresh_delegation_tools`], so a
/// clone taken here is a stable snapshot for the rest of the caller's turn
/// even if the connection set changes underneath it.
pub fn synthesized_tools_arc(&self) -> Arc<Vec<Box<dyn Tool>>> {
@@ -138,7 +138,7 @@ impl Agent {
/// The full host [`Config`](crate::config::Config) this session
/// was built with, when it was built through the factory.
///
- /// `None` on the bare-builder path (`AgentBuilder` without
+ /// `None` on the bare-builder path (`SessionHostBuilder` without
/// `AgentFactory`), which is used by tests and by callers assembling a
/// session by hand. Every capability adapter that needs host config treats
/// `None` as "not available" rather than loading one itself — see
@@ -281,15 +281,30 @@ impl Agent {
self.config.max_tool_iterations = cap;
}
- /// Returns the current conversation history.
- pub fn history(&self) -> &[ConversationMessage] {
- &self.history
+ /// Returns a presentation projection of the runtime-owned history.
+ ///
+ /// This intentionally returns an owned value: retaining a second borrowed
+ /// or mutable `ConversationMessage` accumulator in the host would recreate
+ /// the session state now owned by `tinyagents_runtime::Session`.
+ pub fn history(&self) -> Vec<ConversationMessage> {
+ self.runtime_session
+ .as_ref()
+ .map(|session| {
+ session
+ .history()
+ .iter()
+ .map(crate::agent::message_convert::message_to_native_chat_message)
+ .map(ConversationMessage::Chat)
+ .collect()
+ })
+ .unwrap_or_default()
}
pub fn set_event_context(&mut self, session_id: impl Into<String>, channel: impl Into<String>) {
self.event_session_id = session_id.into();
self.event_channel = channel.into();
self.rebuild_tool_policy_session();
+ self.sync_runtime_tool_surface();
}
/// Bind the OpenHuman conversation thread for the next and subsequent
@@ -342,6 +357,7 @@ impl Agent {
self.session_key = format!("{prefix}_{sanitized}");
self.agent_definition_name = name;
self.rebuild_tool_policy_session();
+ self.sync_runtime_tool_surface();
}
/// Attach a progress event sender for real-time turn updates.
@@ -360,9 +376,9 @@ impl Agent {
/// root as their default working directory.
///
/// The post-build counterpart of
- /// [`AgentBuilder::workspace_descriptor`](crate::agent::AgentBuilder::workspace_descriptor),
+ /// [`SessionHostBuilder::workspace_descriptor`](crate::agent::SessionHostBuilder::workspace_descriptor),
/// for callers that construct the agent through
- /// [`Agent::from_config`](crate::agent::Agent::from_config) and
+ /// [`OpenHumanSessionHost::from_config`](crate::agent::OpenHumanSessionHost::from_config) and
/// therefore never see the builder — notably the per-turn `cwd` of
/// [`agent_chat`](crate::inference::host_runtime::ops::agent_chat).
///
@@ -394,11 +410,13 @@ impl Agent {
/// session. An empty set restores the default "all visible" behavior,
/// still subject to the configured channel permission policy.
pub fn set_visible_tool_names(&mut self, names: HashSet<String>) {
+ let auto_include_new_synthesized_tools = names.is_empty();
self.visible_tool_names = names;
if self.visible_tool_names.is_empty() {
self.seed_wildcard_visible_tools();
}
self.rebuild_tool_policy_session();
+ self.sync_runtime_tool_surface_with_auto_include(Some(auto_include_new_synthesized_tools));
}
/// Materialise the wildcard visibility sentinel while preserving the
@@ -450,9 +468,10 @@ impl Agent {
self.visible_tool_names.remove(*name);
}
self.rebuild_tool_policy_session();
+ self.sync_runtime_tool_surface_with_auto_include(Some(false));
}
- pub(in crate::agent::harness::session) fn rebuild_tool_policy_session(&mut self) {
+ pub(in crate::agent::session_host) fn rebuild_tool_policy_session(&mut self) {
// Classify the synthesised delegates too: they are advertised to the
// provider and callable, so a policy snapshot built from the durable
// registry alone would leave every `delegate_*` tool with no decision
@@ -486,7 +505,13 @@ impl Agent {
/// Clears the agent's conversation history.
pub fn clear_history(&mut self) {
- self.history.clear();
+ // Runtime `Session` owns the only generic history and has no mutable
+ // clear operation by design. Dropping this uncommitted/committed
+ // composition starts a fresh runtime session on the next public turn.
+ self.runtime_session = None;
+ self.runtime_state = Arc::new(std::sync::Mutex::new(
+ super::super::runtime_session::OpenHumanSessionState::default(),
+ ));
}
/// Set the overrides applied to the **next** [`Self::turn`] call.
@@ -499,6 +524,9 @@ impl Agent {
/// motivating case (#1725: a bare greeting must not run the task loop nor
/// inherit a prior task's goal / tools / memory).
pub fn set_next_turn_overrides(&mut self, overrides: super::super::types::TurnOverrides) {
- self.pending_turn_overrides = overrides;
+ self.runtime_state
+ .lock()
+ .unwrap_or_else(|poisoned| poisoned.into_inner())
+ .pending_turn_overrides = overrides;
}
}
diff --git a/crates/openhuman-core/src/agent/harness/session/runtime/run_loop.rs b/crates/openhuman-core/src/agent/session_host/runtime/run_loop.rs
similarity index 94%
rename from crates/openhuman-core/src/agent/harness/session/runtime/run_loop.rs
rename to crates/openhuman-core/src/agent/session_host/runtime/run_loop.rs
index 6c80239575..c600343779 100644
--- a/crates/openhuman-core/src/agent/harness/session/runtime/run_loop.rs
+++ b/crates/openhuman-core/src/agent/session_host/runtime/run_loop.rs
@@ -1,17 +1,17 @@
//! `run_single` / `run_interactive`: the single-shot and CLI entry points
-//! that wrap [`Agent::turn`] with prompt-injection enforcement, telemetry
+//! that wrap [`OpenHumanSessionHost::turn`] with prompt-injection enforcement, telemetry
//! events, and error sanitisation.
-use super::super::types::Agent;
+use super::super::types::OpenHumanSessionHost;
use crate::agent::error::AgentError;
use crate::core::bus::BUS;
use crate::core::events::DomainEvent;
use crate::security::prompt_injection::{
- enforce_prompt_input, PromptEnforcementAction, PromptEnforcementContext,
+ PromptEnforcementAction, PromptEnforcementContext, enforce_prompt_input,
};
use anyhow::Result;
-impl Agent {
+impl OpenHumanSessionHost {
// ─────────────────────────────────────────────────────────────────
// Run helpers — single-shot and interactive loops
// ─────────────────────────────────────────────────────────────────
@@ -62,7 +62,7 @@ impl Agent {
return Err(anyhow::anyhow!(user_message));
}
- let history_snapshot = self.history.clone();
+ let history_snapshot = self.history();
BUS.publish(DomainEvent::AgentTurnStarted {
session_id: self.event_session_id().to_string(),
channel: self.event_channel().to_string(),
@@ -70,7 +70,8 @@ impl Agent {
match self.turn(message).await {
Ok(response) => {
- let new_entries = Self::new_entries_for_turn(&history_snapshot, &self.history);
+ let history = self.history();
+ let new_entries = Self::new_entries_for_turn(&history_snapshot, &history);
BUS.publish(DomainEvent::AgentTurnCompleted {
session_id: self.event_session_id().to_string(),
text_chars: response.chars().count(),
@@ -83,7 +84,7 @@ impl Agent {
// Some typed `AgentError` variants represent agent / user /
// provider state that the UI already surfaces — the
// max-tool-iterations cap (OPENHUMAN-TAURI-99 / -98,
- // chat-rendered "Error: Agent exceeded maximum tool
+ // chat-rendered "Error: OpenHumanSessionHost exceeded maximum tool
// iterations") and the empty-provider-response degeneracy
// (TAURI-RUST-4JX, "The model returned an empty response.
// Please try again."). Skip the Sentry funnel for both
diff --git a/crates/openhuman-core/src/agent/harness/session/runtime/turn_helpers.rs b/crates/openhuman-core/src/agent/session_host/runtime/turn_helpers.rs
similarity index 92%
rename from crates/openhuman-core/src/agent/harness/session/runtime/turn_helpers.rs
rename to crates/openhuman-core/src/agent/session_host/runtime/turn_helpers.rs
index 70662469ee..e502f4ad8e 100644
--- a/crates/openhuman-core/src/agent/harness/session/runtime/turn_helpers.rs
+++ b/crates/openhuman-core/src/agent/session_host/runtime/turn_helpers.rs
@@ -1,21 +1,21 @@
//! Static per-turn helpers: iteration counting, history diffing, event-error
//! sanitisation, and tool-call id fallback / persistence shaping.
-use super::super::types::Agent;
+use super::super::types::OpenHumanSessionHost;
use crate::agent::error::AgentError;
use crate::agent::messages::ConversationMessage;
use crate::inference::provider::ToolCall;
use crate::util::truncate_with_ellipsis;
use tinytools_agent::ParsedToolCall;
-impl Agent {
+impl OpenHumanSessionHost {
const EVENT_ERROR_MAX_CHARS: usize = 256;
// ─────────────────────────────────────────────────────────────────
// Static helpers for turn parsing + telemetry
// ─────────────────────────────────────────────────────────────────
- pub(in crate::agent::harness::session) fn count_iterations(
+ pub(in crate::agent::session_host) fn count_iterations(
messages: &[ConversationMessage],
) -> usize {
messages
@@ -37,7 +37,7 @@ impl Agent {
.all(|(left, right)| Self::conversation_message_eq(left, right))
}
- pub(in crate::agent::harness::session) fn new_entries_for_turn<'a>(
+ pub(in crate::agent::session_host) fn new_entries_for_turn<'a>(
history_snapshot: &[ConversationMessage],
current_history: &'a [ConversationMessage],
) -> &'a [ConversationMessage] {
@@ -63,7 +63,7 @@ impl Agent {
current_history
}
- pub(in crate::agent::harness::session) fn sanitize_event_error_message(
+ pub(in crate::agent::session_host) fn sanitize_event_error_message(
err: &anyhow::Error,
) -> String {
let kind = match err.downcast_ref::<AgentError>() {
@@ -95,7 +95,7 @@ impl Agent {
///
/// This is necessary for some tool dispatchers to correctly track and
/// associate results.
- pub(in crate::agent::harness::session) fn with_fallback_tool_call_ids(
+ pub(in crate::agent::session_host) fn with_fallback_tool_call_ids(
mut parsed_calls: Vec<ParsedToolCall>,
iteration: usize,
) -> Vec<ParsedToolCall> {
@@ -111,7 +111,7 @@ impl Agent {
///
/// If the provider response already contains native tool calls, they are
/// returned as-is.
- pub(in crate::agent::harness::session) fn persisted_tool_calls_for_history(
+ pub(in crate::agent::session_host) fn persisted_tool_calls_for_history(
response: &crate::inference::provider::ChatResponse,
parsed_calls: &[ParsedToolCall],
iteration: usize,
diff --git a/crates/openhuman-core/src/agent/harness/session/runtime/turn_results.rs b/crates/openhuman-core/src/agent/session_host/runtime/turn_results.rs
similarity index 57%
rename from crates/openhuman-core/src/agent/harness/session/runtime/turn_results.rs
rename to crates/openhuman-core/src/agent/session_host/runtime/turn_results.rs
index 288d209033..08e53b107d 100644
--- a/crates/openhuman-core/src/agent/harness/session/runtime/turn_results.rs
+++ b/crates/openhuman-core/src/agent/session_host/runtime/turn_results.rs
@@ -1,9 +1,9 @@
//! Read-out of the latest completed turn: usage totals, the iteration-cap
//! flag, and the memory citations collected alongside the turn.
-use super::super::types::Agent;
+use super::super::types::OpenHumanSessionHost;
-impl Agent {
+impl OpenHumanSessionHost {
/// Borrow the holistic token/cost/context totals for the latest completed
/// turn (parent + sub-agents) **without consuming them**. `None` until a
/// turn has run.
@@ -12,10 +12,14 @@ impl Agent {
/// [`take_last_turn_usage_totals`](Self::take_last_turn_usage_totals): a
/// downstream crate embedding OpenHuman as a library (e.g. the OpenCompany
/// hosting platform's cost-metering hook) can read per-turn token and USD
- /// totals after [`Agent::turn`](crate::agent::Agent) returns,
+ /// totals after [`OpenHumanSessionHost::turn`](crate::agent::OpenHumanSessionHost) returns,
/// while leaving the value in place for the web-channel drain path.
- pub fn last_turn_usage(&self) -> Option<&crate::agent::tinyagents::host::LastTurnUsage> {
- self.last_turn_usage_totals.as_ref()
+ pub fn last_turn_usage(&self) -> Option<crate::agent::tinyagents::host::LastTurnUsage> {
+ self.runtime_state
+ .lock()
+ .unwrap_or_else(|poisoned| poisoned.into_inner())
+ .last_turn_usage
+ .clone()
}
/// Drain and return the holistic token/cost/context totals for the latest
@@ -24,7 +28,11 @@ impl Agent {
pub(crate) fn take_last_turn_usage_totals(
&mut self,
) -> Option<crate::agent::tinyagents::host::LastTurnUsage> {
- self.last_turn_usage_totals.take()
+ self.runtime_state
+ .lock()
+ .unwrap_or_else(|poisoned| poisoned.into_inner())
+ .last_turn_usage
+ .take()
}
/// Whether the most recently completed [`Self::turn`] / [`Self::run_single`]
@@ -33,30 +41,53 @@ impl Agent {
/// any turn has run. Not draining — unlike the usage totals above, a
/// caller may reasonably check this more than once per turn.
pub fn last_turn_hit_cap(&self) -> bool {
- self.last_turn_hit_cap
+ self.runtime_state
+ .lock()
+ .unwrap_or_else(|poisoned| poisoned.into_inner())
+ .last_turn_hit_cap
}
/// Drain and return memory citations collected for the latest completed turn.
///
/// Async because collection runs concurrently with the turn rather than
- /// ahead of it (see `Agent::pending_citations`); this joins whatever is
+ /// ahead of it (see `OpenHumanSessionHost::pending_citations`); this joins whatever is
/// still in flight. By the time a caller asks, the model round-trip has
/// already happened, so the recall has normally finished and this does not
/// wait.
pub async fn take_last_turn_citations(
&mut self,
) -> Vec<crate::memory::agent::memory_loader::MemoryCitation> {
- if let Some(handle) = self.pending_citations.take() {
+ let pending = self
+ .runtime_state
+ .lock()
+ .unwrap_or_else(|poisoned| poisoned.into_inner())
+ .pending_citations
+ .take();
+ if let Some(handle) = pending {
match handle.await {
- Ok(citations) => self.last_turn_citations = citations,
+ Ok(citations) => self
+ .runtime_state
+ .lock()
+ .unwrap_or_else(|poisoned| poisoned.into_inner())
+ .last_turn_citations = citations,
// A panicked or aborted collection must not fail the turn — the
// citations are decorative, the reply is not.
Err(err) => {
log::warn!("[agent_loop] citation task did not complete: {err}");
- self.last_turn_citations.clear();
+ self.runtime_state
+ .lock()
+ .unwrap_or_else(|poisoned| poisoned.into_inner())
+ .last_turn_citations
+ .clear();
}
}
}
- std::mem::take(&mut self.last_turn_citations)
+ std::mem::take(
+ &mut self
+ .runtime_state
+ .lock()
+ .unwrap_or_else(|poisoned| poisoned.into_inner())
+ .last_turn_citations,
+ )
}
}
diff --git a/crates/openhuman-core/src/agent/session_host/runtime_adapter_tests.rs b/crates/openhuman-core/src/agent/session_host/runtime_adapter_tests.rs
new file mode 100644
index 0000000000..f6618b6551
--- /dev/null
+++ b/crates/openhuman-core/src/agent/session_host/runtime_adapter_tests.rs
@@ -0,0 +1,358 @@
+use std::sync::{Arc, Mutex};
+
+use async_trait::async_trait;
+use tinyagents_runtime::{
+ DriverFailure, DriverOutcome, DriverRequest, PrefixSnapshot, ResumeMode, SessionDriver,
+ SessionTerminal, SessionTurnRequest, ToolSnapshot, TranscriptCodec, TranscriptTurnOptions,
+ TurnOptions,
+};
+use tinyagents_session::transcript::{FileTranscriptLocator, TranscriptMeta};
+use tinyinference_llm::message::Message;
+
+use super::runtime_session::{
+ account_committed_turn_against_goal, holistic_last_turn_usage, reconcile_synthesized_visibility,
+};
+use super::{OpenHumanSessionFactory, OpenHumanSessionHooks, OpenHumanTranscriptCodec};
+use crate::agent::tinyagents::host::OpenHumanRunContext;
+
+struct RecordingDriver(Arc<Mutex<Vec<OpenHumanRunContext>>>);
+
+#[async_trait]
+impl SessionDriver<OpenHumanRunContext> for RecordingDriver {
+ async fn execute(
+ &self,
+ request: DriverRequest<OpenHumanRunContext>,
+ ) -> Result<DriverOutcome, DriverFailure> {
+ self.0
+ .lock()
+ .unwrap()
+ .push(request.run_context.data.clone());
+ let mut history = request.history;
+ history.push(Message::assistant("done"));
+ Ok(DriverOutcome {
+ history,
+ output: Some("done".into()),
+ partial: None,
+ interrupted: false,
+ })
+ }
+}
+
+#[test]
+fn codec_marks_failed_tool_rows_from_the_explicit_turn_sidecar() {
+ let context = OpenHumanRunContext::new();
+ context.session_sidecar.lock().unwrap().tool_outcomes.push(
+ crate::agent::tinyagents::ToolCallOutcome {
+ call_id: "call-1".into(),
+ name: "dangerous_tool".into(),
+ arguments: serde_json::json!({"path": "secret"}),
+ success: false,
+ content: "denied".into(),
+ duration_ms: 0,
+ },
+ );
+ let rows = OpenHumanTranscriptCodec
+ .reconcile(
+ &[],
+ &[],
+ &[Message::tool("call-1", "denied")],
+ &TranscriptTurnOptions {
+ request_id: Some("request-1".into()),
+ thread_id: None,
+ stream: false,
+ resume: ResumeMode::Never,
+ context,
+ },
+ )
+ .unwrap();
+ assert!(
+ rows[0]
+ .tool_failure
+ .as_ref()
+ .is_some_and(|failure| failure.failed)
+ );
+}
+
+#[test]
+fn codec_attaches_sidecar_usage_and_exact_tool_arguments_to_atomic_append() {
+ let context = OpenHumanRunContext::new();
+ {
+ let mut sidecar = context.session_sidecar.lock().unwrap();
+ sidecar.model_calls = 2;
+ sidecar.input_tokens = 13;
+ sidecar.output_tokens = 8;
+ sidecar.cached_input_tokens = 3;
+ sidecar.cost_usd = 0.004;
+ sidecar.context_window = 128_000;
+ sidecar
+ .tool_outcomes
+ .push(crate::agent::tinyagents::ToolCallOutcome {
+ call_id: "call-usage".into(),
+ name: "read_file".into(),
+ arguments: serde_json::json!({"path": "Cargo.toml"}),
+ success: true,
+ content: "[package]".into(),
+ duration_ms: 7,
+ });
+ }
+ context.append_subagent_usage(crate::agent::tinyagents::host::SubagentUsageEntry {
+ task_id: "child-usage".into(),
+ agent_id: "researcher".into(),
+ usage: crate::agent::harness::subagent_runner::SubagentUsage {
+ input_tokens: 5,
+ output_tokens: 2,
+ cached_input_tokens: 1,
+ charged_amount_usd: 0.001,
+ },
+ });
+ let usage = OpenHumanTranscriptCodec
+ .turn_usage(&TranscriptTurnOptions {
+ request_id: Some("request-usage".into()),
+ thread_id: None,
+ stream: false,
+ resume: ResumeMode::Never,
+ context,
+ })
+ .unwrap()
+ .expect("observed sidecar produces transcript usage");
+
+ assert_eq!(usage.usage.input, 18, "direct + completed child input");
+ assert_eq!(usage.usage.output, 10, "direct + completed child output");
+ assert_eq!(usage.usage.cached_input, 4);
+ assert_eq!(usage.usage.context_window, 128_000);
+ assert!((usage.usage.cost_usd - 0.005).abs() < f64::EPSILON);
+ assert_eq!(usage.iteration, 2);
+ assert_eq!(usage.tool_calls.len(), 1);
+ assert_eq!(usage.tool_calls[0].id, "call-usage");
+ assert_eq!(usage.tool_calls[0].arguments, r#"{"path":"Cargo.toml"}"#);
+}
+
+#[test]
+fn last_turn_usage_reports_the_same_holistic_totals_as_transcript_billing() {
+ let mut sidecar = crate::agent::tinyagents::host::run_context::SessionTurnSidecar {
+ input_tokens: 13,
+ output_tokens: 8,
+ cached_input_tokens: 3,
+ cost_usd: 0.004,
+ context_window: 128_000,
+ ..Default::default()
+ };
+ sidecar
+ .subagents
+ .push(crate::agent::tinyagents::host::SubagentUsageEntry {
+ task_id: "child-ui".into(),
+ agent_id: "researcher".into(),
+ usage: crate::agent::harness::subagent_runner::SubagentUsage {
+ input_tokens: 5,
+ output_tokens: 2,
+ cached_input_tokens: 1,
+ charged_amount_usd: 0.001,
+ },
+ });
+
+ let usage = holistic_last_turn_usage(&sidecar);
+ assert_eq!(usage.input_tokens, 18);
+ assert_eq!(usage.output_tokens, 10);
+ assert_eq!(usage.cached_input_tokens, 4);
+ assert!((usage.cost_usd - 0.005).abs() < f64::EPSILON);
+ assert_eq!(usage.context_window, 128_000);
+ assert_eq!(usage.subagents.len(), 1, "detail breakdown is retained");
+}
+
+#[test]
+fn explicit_hidden_delegate_stays_hidden_across_dynamic_refreshes() {
+ let mut visible = ["read_file".to_string()]
+ .into_iter()
+ .collect::<std::collections::HashSet<_>>();
+ let prior = [
+ "delegate_research".to_string(),
+ "delegate_calendar".to_string(),
+ ]
+ .into_iter()
+ .collect::<std::collections::HashSet<_>>();
+ let refreshed = [
+ "delegate_research".to_string(),
+ "delegate_drive".to_string(),
+ ]
+ .into_iter()
+ .collect::<std::collections::HashSet<_>>();
+
+ reconcile_synthesized_visibility(&mut visible, &prior, &refreshed, false);
+
+ assert!(
+ !visible.contains("delegate_research"),
+ "an explicitly hidden existing delegate remains hidden after refresh"
+ );
+ assert!(
+ !visible.contains("delegate_drive"),
+ "a new connection cannot bypass an explicit visibility restriction"
+ );
+ assert!(
+ !visible.contains("delegate_calendar"),
+ "a revoked connection leaves the surface"
+ );
+}
+
+#[test]
+fn wildcard_delegate_visibility_admits_new_connections_and_removes_revoked_ones() {
+ let mut visible = ["read_file".to_string(), "delegate_calendar".to_string()]
+ .into_iter()
+ .collect::<std::collections::HashSet<_>>();
+ let prior = ["delegate_calendar".to_string()]
+ .into_iter()
+ .collect::<std::collections::HashSet<_>>();
+ let refreshed = ["delegate_drive".to_string()]
+ .into_iter()
+ .collect::<std::collections::HashSet<_>>();
+
+ reconcile_synthesized_visibility(&mut visible, &prior, &refreshed, true);
+
+ assert!(visible.contains("delegate_drive"));
+ assert!(!visible.contains("delegate_calendar"));
+ assert!(visible.contains("read_file"));
+}
+
+#[tokio::test]
+async fn committed_goal_accounting_uses_direct_and_completed_child_usage() {
+ let workspace = tempfile::tempdir().unwrap();
+ crate::agent::goals::store::set(
+ workspace.path(),
+ "receipt-goal",
+ "finish migration",
+ Some(20),
+ )
+ .await
+ .unwrap();
+ let mut sidecar = crate::agent::tinyagents::host::run_context::SessionTurnSidecar {
+ input_tokens: 9,
+ output_tokens: 4,
+ duration: Some(std::time::Duration::from_secs(2)),
+ ..Default::default()
+ };
+ sidecar
+ .subagents
+ .push(crate::agent::tinyagents::host::SubagentUsageEntry {
+ task_id: "child-goal".into(),
+ agent_id: "researcher".into(),
+ usage: crate::agent::harness::subagent_runner::SubagentUsage {
+ input_tokens: 5,
+ output_tokens: 3,
+ ..Default::default()
+ },
+ });
+
+ account_committed_turn_against_goal(workspace.path(), Some("receipt-goal"), &sidecar).await;
+
+ let goal = crate::agent::goals::store::get(workspace.path(), "receipt-goal")
+ .await
+ .unwrap()
+ .unwrap();
+ assert_eq!(
+ goal.tokens_used, 21,
+ "receipt accounts direct + child usage"
+ );
+ assert_eq!(
+ goal.status,
+ crate::agent::goals::ThreadGoalStatus::BudgetLimited,
+ "receipt-backed accounting advances continuation/budget state"
+ );
+}
+
+fn meta() -> TranscriptMeta {
+ TranscriptMeta {
+ agent_name: "adapter-test".into(),
+ agent_id: Some("adapter-test".into()),
+ agent_type: Some("root".into()),
+ dispatcher: "test".into(),
+ provider: None,
+ model: None,
+ created: chrono::Utc::now().to_rfc3339(),
+ updated: chrono::Utc::now().to_rfc3339(),
+ turn_count: 0,
+ input_tokens: 0,
+ output_tokens: 0,
+ cached_input_tokens: 0,
+ charged_amount_usd: 0.0,
+ thread_id: None,
+ task_id: None,
+ }
+}
+
+#[tokio::test]
+async fn runtime_adapter_passes_host_context_commits_before_finalize_and_emits_one_terminal() {
+ let seen_context = Arc::new(Mutex::new(Vec::new()));
+ let order = Arc::new(Mutex::new(Vec::new()));
+ let terminals = Arc::new(Mutex::new(Vec::new()));
+ let hooks = Arc::new(OpenHumanSessionHooks::new(
+ |_, _, _| Box::pin(async { Ok(Default::default()) }),
+ |_, _, _| Box::pin(async { Ok(Default::default()) }),
+ |_, _| Box::pin(async { Ok(()) }),
+ {
+ let order = Arc::clone(&order);
+ move |_| {
+ let order = Arc::clone(&order);
+ Box::pin(async move {
+ order.lock().unwrap().push("commit");
+ Ok(())
+ })
+ }
+ },
+ {
+ let order = Arc::clone(&order);
+ let terminals = Arc::clone(&terminals);
+ move |terminal| {
+ let order = Arc::clone(&order);
+ let terminals = Arc::clone(&terminals);
+ Box::pin(async move {
+ order.lock().unwrap().push("terminal");
+ terminals.lock().unwrap().push(terminal);
+ Ok(())
+ })
+ }
+ },
+ ));
+ let root = std::env::temp_dir().join(format!(
+ "openhuman-session-adapter-{}",
+ uuid::Uuid::new_v4()
+ ));
+ let context = OpenHumanRunContext::new();
+ let cancellation = context.cancellation.clone();
+ let mut session = OpenHumanSessionFactory::build(
+ Arc::new(RecordingDriver(Arc::clone(&seen_context))),
+ hooks,
+ PrefixSnapshot::default(),
+ ToolSnapshot::default(),
+ Arc::new(FileTranscriptLocator::new(&root)),
+ "adapter-test",
+ meta(),
+ )
+ .unwrap();
+
+ session
+ .turn(
+ SessionTurnRequest::new(Message::user("hello")),
+ TurnOptions {
+ request_id: Some("request-1".into()),
+ thread_id: Some("thread-1".into()),
+ stream: false,
+ resume: Default::default(),
+ cancellation: cancellation.clone(),
+ run_context: context
+ .into_tinyagents(tinyagents_harness::context::RunConfig::new("adapter-turn")),
+ },
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(seen_context.lock().unwrap().len(), 1);
+ assert_eq!(*order.lock().unwrap(), ["commit", "terminal"]);
+ assert!(matches!(
+ terminals.lock().unwrap().as_slice(),
+ [SessionTerminal::Completed(_)]
+ ));
+ assert!(
+ root.join("session_raw").exists(),
+ "commit precedes finalization"
+ );
+ let _ = std::fs::remove_dir_all(root);
+}
diff --git a/crates/openhuman-core/src/agent/session_host/runtime_session.rs b/crates/openhuman-core/src/agent/session_host/runtime_session.rs
new file mode 100644
index 0000000000..d8c0bf1643
--- /dev/null
+++ b/crates/openhuman-core/src/agent/session_host/runtime_session.rs
@@ -0,0 +1,1943 @@
+//! 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.
+
+use std::sync::Arc;
+
+use anyhow::Result;
+use tinyagents_runtime::{
+ CommitReceipt, PrefixSnapshot, ResumeMode, ResumePreparation, SessionBuilder, SessionTerminal,
+ SessionTurnRequest, ToolSnapshot, TranscriptCodec, TranscriptTarget, TurnOptions,
+ TurnPreparation,
+};
+use tinyagents_session::transcript::TranscriptMeta;
+use tinyinference_llm::message::Message;
+
+use crate::agent::{
+ session_host::{
+ OpenHumanSessionHooks, OpenHumanTranscriptCodec, driver::OpenHumanSessionDriver,
+ },
+ tinyagents::{TurnContextMiddleware, host::OpenHumanRunContext},
+};
+
+use super::types::OpenHumanSessionHost;
+
+/// Mutable product state observed by the runtime hooks.
+///
+/// This type has no message accumulator, raw transcript rows, prefix matching,
+/// resume cache, or persistence handle. Those are exclusively `Session` state.
+#[derive(Default)]
+pub(super) struct OpenHumanSessionState {
+ /// Host-selected transcript destination. The runtime binds and owns the
+ /// resulting history handle, raw rows and append/reconcile state.
+ resume_target: Option<TranscriptTarget>,
+ last_commit: Option<CommitReceipt<OpenHumanRunContext>>,
+ terminals: Vec<SessionTerminal>,
+ pub(super) last_turn_hit_cap: bool,
+ pub(super) last_turn_usage: Option<crate::agent::tinyagents::host::LastTurnUsage>,
+ context_middleware: Option<TurnContextMiddleware>,
+ required_output: Option<tinyagents_harness::config::RequiredOutput>,
+ pub(crate) pending_turn_overrides: super::types::TurnOverrides,
+ prelude: Option<OpenHumanTurnPrelude>,
+ pub(crate) pending_citations:
+ Option<tokio::task::JoinHandle<Vec<crate::memory::agent::memory_loader::MemoryCitation>>>,
+ pub(crate) last_turn_citations: Vec<crate::memory::agent::memory_loader::MemoryCitation>,
+}
+
+/// Owned host-only inputs used by the async runtime preparation hook.
+/// It deliberately excludes transcript/history/tool snapshots, which belong to
+/// `tinyagents_runtime::Session`.
+#[derive(Clone)]
+struct OpenHumanTurnPrelude {
+ memory: Arc<dyn crate::memory::Memory>,
+ learning_enabled: bool,
+ explicit_preferences_enabled: bool,
+ config: crate::config::AgentConfig,
+ /// Host session-memory state, shared by the runtime hooks. It is not
+ /// generic conversation state and the runtime never persists it.
+ context: Arc<std::sync::Mutex<crate::agent::context::ContextManager>>,
+ tool_policy: Arc<dyn crate::agent::tool_policy::ToolPolicy>,
+ tool_dispatcher: Arc<dyn tinytools_agent::dialect::ToolDialect>,
+ workspace_dir: std::path::PathBuf,
+ action_dir: std::path::PathBuf,
+ model_name: String,
+ agent_definition_name: String,
+ omit_profile: bool,
+ omit_memory_md: bool,
+ auto_save: bool,
+ thread_id: Option<String>,
+ auto_recall: Option<Arc<crate::memory::auto_recall::AutoRecall>>,
+ agent_definition_id: String,
+ event_session_id: String,
+ event_channel: String,
+ trigger_memory_agent: crate::agent::harness::definition::TriggerMemoryAgent,
+ subagent_tool_ceiling_names: std::collections::HashSet<String>,
+ turn_model_source: crate::agent::tinyagents::TurnModelSource,
+ temperature: f64,
+ workspace_descriptor: Option<tinytools::WorkspaceDescriptor>,
+ session_key: String,
+ session_parent_prefix: Option<String>,
+ on_progress: Option<tokio::sync::mpsc::Sender<crate::agent::progress::AgentProgress>>,
+ run_queue:
+ Option<Arc<tinyagents_harness::run_queue::RunQueue<crate::agent::queued_turn::QueuedTurn>>>,
+ allowed_subagent_ids: std::collections::HashSet<String>,
+ sandbox_mode: crate::agent::harness::definition::SandboxMode,
+ runtime_config: Option<Arc<crate::config::Config>>,
+ archivist_hook: Option<Arc<crate::agent::harness::archivist::ArchivistHook>>,
+ /// The one authoritative, request-refreshable composition of executable
+ /// tools, policy, and provider schema. Generic runtime owns the immutable
+ /// `ToolSnapshot`; this host surface is the source used to create it.
+ tool_surface: Arc<std::sync::Mutex<OpenHumanTurnToolSurface>>,
+ mutable: Arc<std::sync::Mutex<OpenHumanTurnPreludeMutable>>,
+}
+
+/// Host-owned tool composition from which one runtime request is prepared.
+/// All three views are rebuilt together so a prompt schema, execution source,
+/// and fail-closed policy cannot describe different authority.
+struct OpenHumanTurnToolSurface {
+ tools: Arc<Vec<Box<dyn tinytools::Tool>>>,
+ synthesized_tools: Arc<Vec<Box<dyn tinytools::Tool>>>,
+ tool_specs: Arc<Vec<Arc<tinytools::ToolSpec>>>,
+ durable_tool_specs: Arc<Vec<Arc<tinytools::ToolSpec>>>,
+ visible_tool_specs: Arc<Vec<Arc<tinytools::ToolSpec>>>,
+ visible_tool_names: std::collections::HashSet<String>,
+ /// Whether newly connected delegates may enter the visible belt without a
+ /// caller explicitly allowing them. A hide/named restriction turns this
+ /// off so refresh cannot reopen withdrawn authority.
+ auto_include_new_synthesized_tools: bool,
+ synthesized_tool_names: std::collections::HashSet<String>,
+ tool_policy_session: crate::tools::agent_policy::ToolPolicySession,
+ event_session_id: String,
+ event_channel: String,
+ agent_definition_name: String,
+}
+
+/// Per-session product observations that were formerly scattered across the
+/// legacy `core_turn` loop. Generic history, raw transcript data and prefix
+/// state intentionally do not appear here.
+#[derive(Default)]
+struct OpenHumanTurnPreludeMutable {
+ last_memory_context: Option<String>,
+ announced_integrations: std::collections::HashSet<String>,
+ pending_integration_announcement: Vec<String>,
+ announced_mcp_servers: std::collections::HashSet<String>,
+ pending_mcp_announcement: Vec<String>,
+ announced_skills: std::collections::HashSet<String>,
+ pending_skill_announcement: Vec<String>,
+ pending_skill_retraction: Vec<String>,
+ connected_integrations: Vec<crate::agent::prompts::ConnectedIntegration>,
+ connected_integrations_initialized: bool,
+ workflows: Vec<crate::skills::Workflow>,
+ composio_events: Option<tinybus::events::EventReceiver<crate::core::events::DomainEvent>>,
+ skill_events: Option<tinybus::events::EventReceiver<crate::core::events::DomainEvent>>,
+ pending_user_autosave: Option<String>,
+}
+
+impl OpenHumanTurnPrelude {
+ fn current_tool_source(
+ &self,
+ ) -> (
+ Arc<Vec<Box<dyn tinytools::Tool>>>,
+ Arc<Vec<Box<dyn tinytools::Tool>>>,
+ crate::tools::agent_policy::ToolPolicySession,
+ String,
+ 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_session_id.clone(),
+ surface.event_channel.clone(),
+ )
+ }
+
+ fn replace_tool_surface(&self, surface: OpenHumanTurnToolSurface) {
+ *self
+ .tool_surface
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner) = surface;
+ }
+
+ async fn prepare(&self, cold: bool) -> Result<TurnPreparation> {
+ let tools = {
+ let surface = self
+ .tool_surface
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
+ ToolSnapshot::new(
+ surface
+ .visible_tool_specs
+ .iter()
+ .map(|spec| spec.as_ref().clone())
+ .collect(),
+ )
+ .map_err(|error| anyhow::anyhow!(error.to_string()))?
+ };
+ let prefix = if cold {
+ let learned = self.fetch_learned_context().await;
+ Some(PrefixSnapshot::new(vec![Message::system(
+ self.build_system_prompt(learned)?,
+ )]))
+ } else {
+ None
+ };
+ Ok(TurnPreparation {
+ prefix,
+ tools: Some(tools),
+ })
+ }
+
+ async fn refresh_turn_boundary(&self, cold: bool) {
+ if cold {
+ self.refresh_cold_integrations().await;
+ } else {
+ self.refresh_dynamic_announcements().await;
+ }
+ // Integration changes are authority changes, not only display
+ // announcements. Refresh the delegation executable set and rebuild
+ // its schema/policy in the same hook pass before the driver sees it.
+ self.refresh_delegation_tool_surface();
+ }
+
+ fn begin_user_effects(&self, state: &mut OpenHumanSessionState, request: &SessionTurnRequest) {
+ let user_text = request.input.text();
+ if self.auto_save && crate::agent::turn_origin::current_is_user_authored() {
+ self.mutable
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .pending_user_autosave = Some(user_text.clone());
+ }
+ state.last_turn_citations.clear();
+ if let Some(previous) = state.pending_citations.take() {
+ previous.abort();
+ }
+ let memory = self.memory.clone();
+ state.pending_citations = Some(tokio::spawn(async move {
+ crate::memory::agent::memory_loader::collect_recall_citations(
+ memory.as_ref(),
+ &user_text,
+ 5,
+ 0.4,
+ )
+ .await
+ .unwrap_or_default()
+ }));
+ }
+
+ async fn fetch_learned_context(&self) -> crate::agent::prompts::LearnedContextData {
+ if !self.learning_enabled && !self.explicit_preferences_enabled {
+ return Default::default();
+ }
+ if !self.learning_enabled && self.explicit_preferences_enabled {
+ return crate::agent::prompts::LearnedContextData {
+ user_profile: crate::memory::preferences::load_general_preferences_on(
+ &self.memory,
+ crate::memory::preferences::STANDING_PREFS_LIMIT,
+ )
+ .await,
+ ..Default::default()
+ };
+ }
+ use crate::memory::MemoryCategory;
+ let observations = self
+ .memory
+ .list(
+ Some("learning_observations"),
+ Some(&MemoryCategory::Custom("learning_observations".into())),
+ None,
+ )
+ .await
+ .unwrap_or_default();
+ let patterns = self
+ .memory
+ .list(
+ Some("learning_patterns"),
+ Some(&MemoryCategory::Custom("learning_patterns".into())),
+ None,
+ )
+ .await
+ .unwrap_or_default();
+ let reflections = self
+ .memory
+ .list(
+ Some(crate::agent::learning::reflection::REFLECTIONS_NAMESPACE),
+ Some(&MemoryCategory::Custom(
+ crate::agent::learning::reflection::REFLECTIONS_NAMESPACE.into(),
+ )),
+ None,
+ )
+ .await
+ .unwrap_or_default();
+ let limits = self.config.resolved_memory_limits();
+ crate::agent::prompts::LearnedContextData {
+ observations: observations
+ .iter()
+ .rev()
+ .take(5)
+ .map(|entry| sanitize_prelude_entry(&entry.content))
+ .collect(),
+ patterns: patterns
+ .iter()
+ .take(3)
+ .map(|entry| sanitize_prelude_entry(&entry.content))
+ .collect(),
+ user_profile: crate::memory::preferences::load_general_preferences_on(
+ &self.memory,
+ crate::memory::preferences::STANDING_PREFS_LIMIT,
+ )
+ .await,
+ reflections: reflections
+ .iter()
+ .rev()
+ .take(10)
+ .map(|entry| sanitize_prelude_entry(&entry.content))
+ .collect(),
+ tree_root_summaries: collect_prelude_tree_roots(
+ limits.per_namespace_max_chars,
+ limits.total_tree_max_chars,
+ )
+ .await,
+ }
+ }
+
+ fn build_system_prompt(
+ &self,
+ learned: crate::agent::prompts::LearnedContextData,
+ ) -> Result<String> {
+ use crate::agent::prompts::{PromptContext, PromptTool, tool_call_format_from_dialect};
+ let surface = self
+ .tool_surface
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
+ let specs = surface
+ .visible_tool_specs
+ .iter()
+ .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())
+ .map(|tool| tool.as_ref())
+ .collect::<Vec<_>>();
+ let prompt_tools = PromptTool::from_tool_refs(tool_refs.iter().copied());
+ let visible_tool_names = surface.tool_policy_session.visible_tool_names_for_prompt();
+ 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,
+ tools: &prompt_tools,
+ workflows: &mutable.workflows,
+ dispatcher_instructions: &instructions,
+ learned,
+ visible_tool_names: &visible_tool_names,
+ tool_call_format: tool_call_format_from_dialect(
+ self.tool_dispatcher.tool_call_format(),
+ ),
+ connected_integrations: &mutable.connected_integrations,
+ connected_identities_md: crate::agent::prompts::render_connected_identities(),
+ include_profile: !self.omit_profile,
+ include_memory_md: !self.omit_memory_md,
+ curated_snapshot: None,
+ 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(&context)
+ .map_err(Into::into)
+ }
+
+ async fn refresh_cold_integrations(&self) {
+ let should_fetch = !self
+ .mutable
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .connected_integrations_initialized;
+ if !should_fetch {
+ return;
+ }
+ let config = match self.runtime_config.clone() {
+ Some(config) => Some(config),
+ None => crate::config::Config::load_or_init()
+ .await
+ .ok()
+ .map(Arc::new),
+ };
+ let Some(config) = config else {
+ return;
+ };
+ let connected = crate::integrations::composio::fetch_connected_integrations(&config).await;
+ let mcp_servers = crate::mcp::registry::connections::connected_overview()
+ .await
+ .into_iter()
+ .map(|server| server.qualified_name)
+ .collect::<std::collections::HashSet<_>>();
+ let mut mutable = self
+ .mutable
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
+ mutable.connected_integrations = connected;
+ mutable.connected_integrations_initialized = true;
+ mutable.announced_integrations = mutable
+ .connected_integrations
+ .iter()
+ .map(|item| item.toolkit.clone())
+ .collect();
+ mutable.announced_mcp_servers = mcp_servers;
+ }
+
+ async fn refresh_dynamic_announcements(&self) {
+ let skills_changed = self.drain_host_events();
+ if let Some(config) = self.runtime_config.as_deref() {
+ if let Some(current) = crate::integrations::composio::cached_active_integrations(config)
+ {
+ let mut mutable = self
+ .mutable
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
+ let current_slugs: std::collections::HashSet<_> =
+ current.iter().map(|item| item.toolkit.clone()).collect();
+ for slug in &current_slugs {
+ if mutable.announced_integrations.insert(slug.clone())
+ && !mutable.pending_integration_announcement.contains(slug)
+ {
+ mutable.pending_integration_announcement.push(slug.clone());
+ }
+ }
+ mutable.connected_integrations = current;
+ }
+ }
+ let connected_mcp = crate::mcp::registry::connections::connected_overview()
+ .await
+ .into_iter()
+ .map(|server| server.qualified_name)
+ .collect::<Vec<_>>();
+ let mut mutable = self
+ .mutable
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
+ for server in connected_mcp {
+ if mutable.announced_mcp_servers.insert(server.clone())
+ && !mutable.pending_mcp_announcement.contains(&server)
+ {
+ mutable.pending_mcp_announcement.push(server);
+ }
+ }
+ if !skills_changed {
+ return;
+ }
+ // Event-driven metadata refresh keeps the steady-state hot path free
+ // of the old per-turn filesystem scan.
+ let latest = crate::skills::load_workflow_metadata(&self.workspace_dir);
+ let id = |workflow: &crate::skills::Workflow| {
+ if workflow.dir_name.is_empty() {
+ workflow.name.clone()
+ } else {
+ workflow.dir_name.clone()
+ }
+ };
+ let previous: std::collections::HashSet<_> = mutable.workflows.iter().map(&id).collect();
+ let current: std::collections::HashSet<_> = latest.iter().map(&id).collect();
+ for id in current.difference(&previous) {
+ if mutable.announced_skills.insert((*id).clone())
+ && !mutable.pending_skill_announcement.contains(id)
+ {
+ mutable.pending_skill_announcement.push((*id).clone());
+ }
+ }
+ for id in previous.difference(&current) {
+ mutable.announced_skills.remove(id);
+ mutable
+ .pending_skill_announcement
+ .retain(|pending| pending != id);
+ if !mutable.pending_skill_retraction.contains(id) {
+ mutable.pending_skill_retraction.push((*id).clone());
+ }
+ }
+ mutable.workflows = latest;
+ }
+
+ /// Rebuild every delegation-dependent tool view from the current cached
+ /// integration set. This mirrors the legacy refresh's replace-not-append
+ /// semantics, but keeps the mutable authority in hook state rather than a
+ /// second turn loop. A revoked delegate is removed from the executable
+ /// source, schema, and policy together before this request is prepared.
+ fn refresh_delegation_tool_surface(&self) {
+ use crate::agent::harness::definition::AgentDefinitionRegistry;
+ use crate::tools::agent_policy::ToolPolicyEngine;
+ use crate::tools::orchestrator_tools::collect_orchestrator_tools;
+
+ let Some(registry) = AgentDefinitionRegistry::global() else {
+ return;
+ };
+ let Some(definition) = registry.get(&self.agent_definition_id).cloned() else {
+ return;
+ };
+ if definition.subagents.is_empty() {
+ return;
+ }
+ let integrations = self
+ .mutable
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .connected_integrations
+ .clone();
+ let mut surface = self
+ .tool_surface
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
+ let synthesized = super::builder::drop_synthesized_name_collisions(
+ &surface.tools,
+ collect_orchestrator_tools(&definition, registry, &integrations),
+ );
+ let synthesized_names = synthesized
+ .iter()
+ .map(|tool| tool.name().to_string())
+ .collect::<std::collections::HashSet<_>>();
+ let previous_synthesized = std::mem::replace(
+ &mut surface.synthesized_tool_names,
+ synthesized_names.clone(),
+ );
+ let auto_include_new_synthesized_tools = surface.auto_include_new_synthesized_tools;
+ let agent_definition_name = surface.agent_definition_name.clone();
+ reconcile_synthesized_visibility(
+ &mut surface.visible_tool_names,
+ &previous_synthesized,
+ &synthesized_names,
+ auto_include_new_synthesized_tools,
+ );
+ crate::tools::toolpacks::strip_packed_from_visible(
+ &mut surface.visible_tool_names,
+ &agent_definition_name,
+ );
+
+ let specs = surface
+ .durable_tool_specs
+ .iter()
+ .cloned()
+ .chain(synthesized.iter().map(|tool| Arc::new(tool.spec())))
+ .collect::<Vec<_>>();
+ let synthesized_tools = Arc::new(synthesized);
+ crate::tools::toolpacks::bind_synthesized_pack_registry(&surface.tools, &synthesized_tools);
+ let all_tools = surface
+ .tools
+ .iter()
+ .chain(synthesized_tools.iter())
+ .map(|tool| tool.as_ref())
+ .collect::<Vec<_>>();
+ let mut policy = ToolPolicyEngine::build_session_from_refs(
+ &surface.agent_definition_name,
+ &surface.event_channel,
+ "session",
+ &self.config.channel_permissions,
+ &all_tools,
+ &surface.visible_tool_names,
+ );
+ crate::tools::toolpacks::close_handed_off_packs(
+ &mut policy,
+ &surface.agent_definition_name,
+ &all_tools,
+ );
+ let visible = super::builder::dedup_visible_tool_specs(
+ super::builder::visible_tool_specs_for_policy(
+ &specs,
+ &surface.visible_tool_names,
+ &policy,
+ ),
+ );
+ surface.tool_specs = Arc::new(specs);
+ surface.synthesized_tools = synthesized_tools;
+ surface.visible_tool_specs = Arc::new(visible);
+ surface.tool_policy_session = policy;
+ }
+
+ 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.
+ async fn enrich_request(
+ &self,
+ original_user_message: &str,
+ overrides: &super::types::TurnOverrides,
+ run_context: &mut OpenHumanRunContext,
+ ) -> String {
+ let mut context = String::new();
+ self.append_recall_lanes(original_user_message, &mut context)
+ .await;
+
+ let active_goal = if 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, crate::agent::goals::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) = crate::agent::goals::runtime::GoalBudgetStopHook::for_goal(
+ &self.workspace_dir,
+ goal,
+ ) {
+ run_context.stop_hooks.push(Arc::new(hook));
+ }
+ }
+ if let Some(block) =
+ crate::agent::orchestration::running_subagents::active_subagents_context_block(
+ &self.event_session_id,
+ &self.workspace_dir,
+ )
+ {
+ 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);
+ }
+ enriched = self
+ .inject_agent_experience_context(original_user_message, enriched)
+ .await;
+
+ let parent = self.parent_context();
+ let (enriched_with_memory_agent, memory_agent_context_injected) = self
+ .inject_triggered_memory_agent_context(
+ original_user_message,
+ enriched,
+ &parent,
+ overrides.suppress_memory_agent,
+ )
+ .await;
+ enriched = enriched_with_memory_agent;
+ let mut prepared_sources = Vec::new();
+ if memory_agent_context_injected {
+ prepared_sources.push(crate::agent::harness::AgentContextPreparedSource {
+ source: "memory agent context retrieval".to_string(),
+ has_enough_context: None,
+ });
+ }
+ if !prepared_sources.is_empty() {
+ enriched = format!(
+ "{}\n\n{enriched}",
+ render_agent_context_status_note(&prepared_sources)
+ );
+ }
+ self.apply_pending_announcements(&mut enriched);
+
+ run_context.parent = Some(parent);
+ run_context.prepared_context_sources = Arc::new(prepared_sources);
+ run_context.attachment_placeholders = Arc::new(
+ crate::agent::multimodal::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()
+ .map(std::time::Duration::from_millis),
+ ),
+ ));
+ run_context.sandbox_mode = Some(self.sandbox_mode);
+ run_context
+ .stop_hooks
+ .extend(crate::agent::stop_hooks::current_stop_hooks());
+ self.context
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .tick_turn();
+ format!(
+ "{}\n\n{enriched}",
+ crate::agent::prompts::current_datetime_line()
+ )
+ }
+
+ async fn append_recall_lanes(&self, user_message: &str, context: &mut String) {
+ const BUDGET: std::time::Duration = std::time::Duration::from_secs(5);
+ let preferences = tokio::time::timeout(
+ BUDGET,
+ crate::memory::preferences::recall_situational_preferences_on(
+ &self.memory,
+ user_message,
+ ),
+ )
+ .await
+ .unwrap_or_default();
+ if !preferences.is_empty() {
+ context.push_str("## Relevant preferences\n\n");
+ for preference in preferences {
+ context.push_str(preference.trim());
+ context.push('\n');
+ }
+ context.push('\n');
+ }
+ if let Some(auto_recall) = &self.auto_recall {
+ if let Some(block) = auto_recall.block_for(user_message).await {
+ context.push_str(&block);
+ }
+ }
+ }
+
+ async fn inject_agent_experience_context(
+ &self,
+ user_message: &str,
+ enriched: String,
+ ) -> String {
+ if !self.learning_enabled {
+ return enriched;
+ }
+ let visible_tools = self
+ .tool_surface
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .visible_tool_specs
+ .iter()
+ .map(|spec| spec.name.clone())
+ .collect();
+ let query = crate::agent::experience::ExperienceQuery {
+ query: user_message.to_string(),
+ tools: visible_tools,
+ tags: Vec::new(),
+ agent_id: Some(self.agent_definition_id.clone()).filter(|id| !id.trim().is_empty()),
+ entrypoint: Some(self.event_channel.clone())
+ .filter(|channel| !channel.trim().is_empty()),
+ max_hits: 3,
+ };
+ let stores = vec![crate::agent::experience::AgentExperienceStore::new(
+ self.memory.clone(),
+ )];
+ match crate::agent::experience::retrieve_across_stores(&stores, query).await {
+ Ok(hits) => {
+ let matched: Vec<_> = hits
+ .into_iter()
+ .filter(|hit| !hit.match_reasons.is_empty())
+ .collect();
+ let block = crate::agent::experience::render_experience_hits(&matched, 2048);
+ if block.is_empty() {
+ enriched
+ } else {
+ crate::agent::experience::prepend_experience_block(&enriched, &block)
+ }
+ }
+ Err(error) => {
+ log::warn!("[agent-experience] retrieval failed (non-fatal): {error}");
+ enriched
+ }
+ }
+ }
+
+ fn parent_context(&self) -> crate::agent::harness::ParentExecutionContext {
+ let surface = self
+ .tool_surface
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
+ crate::agent::harness::ParentExecutionContext {
+ agent_definition_id: self.agent_definition_id.clone(),
+ allowed_subagent_ids: self.allowed_subagent_ids.clone(),
+ turn_model_source: self.turn_model_source.clone(),
+ all_tools: surface.tools.clone(),
+ all_tool_specs: surface.durable_tool_specs.clone(),
+ visible_tool_names: surface.visible_tool_names.clone(),
+ visible_tool_specs: surface.visible_tool_specs.clone(),
+ subagent_tool_ceiling_names: self.subagent_tool_ceiling_names.clone(),
+ model_name: self.model_name.clone(),
+ temperature: self.temperature,
+ workspace_dir: self.workspace_dir.clone(),
+ workspace_descriptor: crate::agent::harness::current_parent()
+ .and_then(|parent| parent.workspace_descriptor)
+ .or_else(|| self.workspace_descriptor.clone()),
+ memory: self.memory.clone(),
+ agent_config: self.config.clone(),
+ workflows: Arc::new(
+ self.mutable
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .workflows
+ .clone(),
+ ),
+ memory_context: Arc::new(
+ self.mutable
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .last_memory_context
+ .clone(),
+ ),
+ session_id: self.event_session_id.clone(),
+ channel: self.event_channel.clone(),
+ connected_integrations: self
+ .mutable
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .connected_integrations
+ .clone(),
+ tool_call_format: crate::agent::prompts::tool_call_format_from_dialect(
+ self.tool_dispatcher.tool_call_format(),
+ ),
+ session_key: self.session_key.clone(),
+ session_parent_prefix: self.session_parent_prefix.clone(),
+ on_progress: self.on_progress.clone(),
+ run_queue: self.run_queue.clone(),
+ }
+ }
+
+ async fn inject_triggered_memory_agent_context(
+ &self,
+ user_message: &str,
+ enriched: String,
+ parent_context: &crate::agent::harness::ParentExecutionContext,
+ force_skip: bool,
+ ) -> (String, bool) {
+ use crate::agent::harness::definition::TriggerMemoryAgent;
+ if force_skip
+ || self.trigger_memory_agent != TriggerMemoryAgent::Always
+ || self.agent_definition_id == "agent_memory"
+ {
+ return (enriched, false);
+ }
+ let Some(registry) = crate::agent::harness::AgentDefinitionRegistry::global() else {
+ return (enriched, false);
+ };
+ let Some(definition) = registry.get("agent_memory").cloned() else {
+ return (enriched, false);
+ };
+ let prompt = format!(
+ "Search the user's memory tree and return only context relevant to the next agent turn.\n\nUser prompt:\n{user_message}"
+ );
+ let options = crate::agent::harness::SubagentRunOptions {
+ task_id: Some(format!("mem-trigger-{}", uuid::Uuid::new_v4())),
+ model_override: Some(parent_context.model_name.clone()),
+ run_context: OpenHumanRunContext::new().with_parent(parent_context.clone()),
+ ..Default::default()
+ };
+ match crate::agent::harness::run_subagent(&definition, &prompt, options).await {
+ Ok(outcome) if !outcome.output.trim().is_empty() => (
+ format!(
+ "## Memory agent context\n\n{}\n\n---\n\n{enriched}",
+ crate::util::truncate_with_ellipsis(&outcome.output, 8000)
+ ),
+ true,
+ ),
+ Ok(_) => (enriched, false),
+ Err(error) => {
+ log::warn!("[agent_memory:trigger] failed: {error:#}");
+ (enriched, false)
+ }
+ }
+ }
+
+ 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}");
+ }
+ }
+
+ async fn finalize_after_durable_commit(&self, receipt: &CommitReceipt<OpenHumanRunContext>) {
+ self.flush_user_autosave().await;
+ self.mirror_transcript_after_commit(receipt);
+ self.spawn_transcript_ingestion_after_commit(receipt);
+ self.spawn_session_memory_extraction_after_commit(receipt)
+ .await;
+ }
+
+ async fn flush_user_autosave(&self) {
+ let message = self
+ .mutable
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .pending_user_autosave
+ .take();
+ let Some(message) = message else {
+ return;
+ };
+ let key = format!("user_msg:{}", uuid::Uuid::new_v4());
+ if let Err(error) = self
+ .memory
+ .store(
+ crate::agent::learning::transcript_ingest::CONVERSATION_RAW_NAMESPACE,
+ &key,
+ &message,
+ crate::memory::MemoryCategory::Conversation,
+ self.thread_id.as_deref(),
+ )
+ .await
+ {
+ log::warn!(
+ "[agent_autosave] durable user-message autosave failed key={key} err={error}"
+ );
+ }
+ }
+
+ fn mirror_transcript_after_commit(&self, receipt: &CommitReceipt<OpenHumanRunContext>) {
+ let Some(path) = receipt
+ .transcript
+ .as_ref()
+ .map(|commit| commit.path.clone())
+ else {
+ return;
+ };
+ if !crate::agent::session_import::live::dual_write_enabled(self.config.session_dual_write) {
+ return;
+ }
+ let Some(stem) = path
+ .file_stem()
+ .and_then(|stem| stem.to_str())
+ .map(str::to_owned)
+ else {
+ return;
+ };
+ let workspace = self.workspace_dir.clone();
+ tokio::spawn(async move {
+ let read_path = path.clone();
+ let transcript = tokio::task::spawn_blocking(move || {
+ tinyagents_session::transcript::read_transcript(&read_path)
+ })
+ .await;
+ let Ok(Ok(transcript)) = transcript else {
+ log::warn!("[session-store] dual-write transcript read-back failed");
+ return;
+ };
+ if let Err(error) =
+ crate::agent::session_import::live::write_live_turn(&workspace, &stem, &transcript)
+ .await
+ {
+ log::warn!("[session-store] dual-write failed stem={stem}: {error:#}");
+ }
+ });
+ }
+
+ fn spawn_transcript_ingestion_after_commit(
+ &self,
+ receipt: &CommitReceipt<OpenHumanRunContext>,
+ ) {
+ let Some(path) = receipt
+ .transcript
+ .as_ref()
+ .map(|commit| commit.path.clone())
+ else {
+ return;
+ };
+ let memory = self.memory.clone();
+ tokio::spawn(async move {
+ if let Err(error) = crate::agent::learning::transcript_ingest::ingest_transcript_path(
+ memory.as_ref(),
+ &path,
+ )
+ .await
+ {
+ log::warn!("[transcript_ingest] background ingest failed: {error}");
+ }
+ });
+ }
+
+ async fn spawn_session_memory_extraction_after_commit(
+ &self,
+ receipt: &CommitReceipt<OpenHumanRunContext>,
+ ) {
+ let should_extract = self
+ .context
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .should_extract_session_memory();
+ if !should_extract {
+ return;
+ }
+ if let Some(archivist) = &self.archivist_hook {
+ archivist.flush_open_segment(&self.event_session_id).await;
+ }
+ // Resolve all fallible launch inputs before mutating the extraction
+ // state. A missing registry/definition/parent is a no-op, not a
+ // permanently "in progress" session-memory extraction.
+ let Some(registry) = crate::agent::harness::AgentDefinitionRegistry::global() else {
+ return;
+ };
+ let Some(definition) = registry.get("archivist").cloned() else {
+ return;
+ };
+ let Some(parent) = receipt.options.context.parent.clone() else {
+ return;
+ };
+ let (handle, stats) = {
+ let mut context = self
+ .context
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
+ let stats = context.stats();
+ context.mark_session_memory_started();
+ (context.session_memory_handle(), stats)
+ };
+ log::info!(
+ "[session_memory] scheduling durable archivist extraction turn={}",
+ stats.session_memory_current_turn
+ );
+ tokio::spawn(async move {
+ let result = crate::agent::harness::run_subagent(
+ &definition,
+ crate::agent::context::ARCHIVIST_EXTRACTION_PROMPT,
+ crate::agent::harness::SubagentRunOptions {
+ run_context: OpenHumanRunContext::new().with_parent(parent),
+ ..Default::default()
+ },
+ )
+ .await;
+ if let Ok(mut state) = handle.lock() {
+ if result.is_ok() {
+ state.mark_extraction_complete();
+ } else {
+ state.mark_extraction_failed();
+ }
+ }
+ });
+ }
+}
+
+/// Reconcile visible delegate names without reopening a caller's explicit
+/// restriction. Revoked names disappear; a newly connected name is admitted
+/// only for the wildcard belt.
+pub(super) fn reconcile_synthesized_visibility(
+ visible: &mut std::collections::HashSet<String>,
+ previous: &std::collections::HashSet<String>,
+ next: &std::collections::HashSet<String>,
+ auto_include_new: bool,
+) {
+ for name in previous.difference(next) {
+ visible.remove(name);
+ }
+ if auto_include_new {
+ visible.extend(next.iter().cloned());
+ }
+}
+
+/// Account only a receipt-backed turn, using the same direct-plus-completed
+/// child total the codec attached to the atomic transcript append.
+pub(super) async fn account_committed_turn_against_goal(
+ workspace_dir: &std::path::Path,
+ thread_id: Option<&str>,
+ sidecar: &crate::agent::tinyagents::host::run_context::SessionTurnSidecar,
+) {
+ let child_input = sidecar
+ .subagents
+ .iter()
+ .map(|entry| entry.usage.input_tokens)
+ .sum::<u64>();
+ let child_output = sidecar
+ .subagents
+ .iter()
+ .map(|entry| entry.usage.output_tokens)
+ .sum::<u64>();
+ crate::agent::goals::runtime::account_turn_against_goal(
+ workspace_dir,
+ thread_id,
+ sidecar.input_tokens.saturating_add(child_input),
+ sidecar.output_tokens.saturating_add(child_output),
+ sidecar
+ .duration
+ .map(|duration| duration.as_secs())
+ .unwrap_or_default(),
+ )
+ .await;
+}
+
+/// UI billing projection for a committed turn. It keeps child records for a
+/// detailed display while reporting the same all-in totals the codec persists.
+pub(super) fn holistic_last_turn_usage(
+ sidecar: &crate::agent::tinyagents::host::run_context::SessionTurnSidecar,
+) -> crate::agent::tinyagents::host::LastTurnUsage {
+ let input_tokens = sidecar
+ .subagents
+ .iter()
+ .fold(sidecar.input_tokens, |total, entry| {
+ total.saturating_add(entry.usage.input_tokens)
+ });
+ let output_tokens = sidecar
+ .subagents
+ .iter()
+ .fold(sidecar.output_tokens, |total, entry| {
+ total.saturating_add(entry.usage.output_tokens)
+ });
+ let cached_input_tokens = sidecar
+ .subagents
+ .iter()
+ .fold(sidecar.cached_input_tokens, |total, entry| {
+ total.saturating_add(entry.usage.cached_input_tokens)
+ });
+ let cost_usd = sidecar
+ .subagents
+ .iter()
+ .fold(sidecar.cost_usd, |total, entry| {
+ total + entry.usage.charged_amount_usd
+ });
+ crate::agent::tinyagents::host::LastTurnUsage {
+ input_tokens,
+ output_tokens,
+ cached_input_tokens,
+ cost_usd,
+ context_window: sidecar.context_window,
+ subagents: sidecar.subagents.clone(),
+ }
+}
+
+fn sanitize_prelude_entry(content: &str) -> String {
+ let value: String = content.trim().chars().take(200).collect();
+ if value.contains("Bearer ")
+ || value.contains("sk-")
+ || value.contains("ghp_")
+ || value.contains("-----BEGIN")
+ {
+ "[redacted: potential secret]".into()
+ } else {
+ value
+ }
+}
+
+fn render_agent_context_status_note(
+ sources: &[crate::agent::harness::AgentContextPreparedSource],
+) -> String {
+ let sources = if sources.is_empty() {
+ "the OpenHuman harness".to_string()
+ } else {
+ sources
+ .iter()
+ .map(|source| source.source.as_str())
+ .collect::<Vec<_>>()
+ .join(", ")
+ };
+ format!(
+ "## Agent context status\n\nAgent context retrieval/preparation has already run once \
+ for this turn in code via {sources}. Do not call `agent_prepare_context` again for \
+ general context preparation. Use the prepared context below, and call only specific \
+ follow-up tools if a concrete missing detail is required."
+ )
+}
+
+fn integration_announcement_note(slugs: &[String]) -> Option<String> {
+ (!slugs.is_empty()).then(|| format!(
+ "[integration update] These integration(s) connected during this conversation and are available right now: {}. \
+Use delegate_to_integrations_agent with the matching toolkit slug to act on them immediately — do not tell the user to reconnect or restart.",
+ slugs.join(", ")
+ ))
+}
+
+fn mcp_announcement_note(servers: &[String]) -> Option<String> {
+ (!servers.is_empty()).then(|| format!(
+ "[MCP update] These MCP server(s) connected during this conversation and are available right now: {}. \
+Use the use_mcp_server delegate to act on them immediately — do not tell the user to reconnect or restart.",
+ servers.join(", ")
+ ))
+}
+
+fn skill_announcement_note(skill_ids: &[String]) -> Option<String> {
+ (!skill_ids.is_empty()).then(|| format!(
+ "[skills update] These skill(s) were installed during this conversation and are available right now: {}. \
+They are in your `## Installed Skills` list — run one with `run_skill` immediately; do not tell the user to reinstall or restart.",
+ skill_ids.join(", ")
+ ))
+}
+
+fn skill_retraction_note(skill_ids: &[String]) -> Option<String> {
+ (!skill_ids.is_empty()).then(|| format!(
+ "[skills retracted] These skill(s) were uninstalled during this conversation and are no longer available: {}. \
+Do not attempt to run them with `run_skill` — they have been removed. Tell the user to reinstall if they want to use them again.",
+ skill_ids.join(", ")
+ ))
+}
+
+async fn collect_prelude_tree_roots(
+ per_namespace_cap: usize,
+ total_cap: usize,
+) -> Vec<crate::agent::prompts::NamespaceSummary> {
+ use crate::memory::api::provider::MemoryProvider;
+ let Ok(guard) = crate::memory::ops::guard::active_memory_guard().await else {
+ return Vec::new();
+ };
+ let Some(tree) = guard.as_tree() else {
+ return Vec::new();
+ };
+ tree.root_summaries_with_caps(per_namespace_cap, total_cap)
+ .await
+ .unwrap_or_default()
+ .into_iter()
+ .map(|row| crate::agent::prompts::NamespaceSummary {
+ namespace: row.namespace,
+ body: row.body,
+ updated_at: row.updated_at,
+ })
+ .collect()
+}
+
+impl OpenHumanSessionHost {
+ /// Seed a cold runtime session from a host-provided message log.
+ ///
+ /// The runtime receives both the seed and any subsequent append; the host
+ /// does not retain a parallel history cache. This lower-fidelity fallback
+ /// intentionally has no raw transcript rows because its source is a
+ /// role/content log rather than an authoritative transcript.
+ pub fn seed_resume_from_messages(
+ &mut self,
+ mut messages: Vec<(String, String)>,
+ current_user_message: &str,
+ ) -> Result<()> {
+ if self.runtime_session.is_some() {
+ return Ok(());
+ }
+ if messages.last().is_some_and(|(role, text)| {
+ role == "user" && text.trim() == current_user_message.trim()
+ }) {
+ messages.pop();
+ }
+ if messages.is_empty() {
+ return Ok(());
+ }
+ self.ensure_runtime_session()?;
+ let history = messages
+ .into_iter()
+ .map(|(role, text)| match role.as_str() {
+ "system" => Message::system(text),
+ "assistant" | "agent" => Message::assistant(text),
+ _ => Message::user(text),
+ })
+ .collect();
+ self.runtime_session
+ .as_mut()
+ .expect("runtime session initialized")
+ .seed_history(history, Vec::new())
+ .map_err(|error| anyhow::anyhow!(error.to_string()))
+ }
+
+ /// Seed a cold runtime session from the lossless transcript selected for a
+ /// conversation thread. The original raw rows travel with the seed so the
+ /// next runtime append can reconcile rather than reserialize them.
+ pub fn seed_resume_from_thread_transcript(&mut self, thread_id: &str) -> bool {
+ self.seed_resume_from_thread_transcript_scoped(thread_id, None)
+ }
+
+ pub fn seed_resume_from_thread_transcript_scoped(
+ &mut self,
+ thread_id: &str,
+ agent_id: Option<&str>,
+ ) -> bool {
+ if self.runtime_session.is_some() {
+ return false;
+ }
+ let Some(handle) = self
+ .session_locator()
+ .root_for_thread_scoped(thread_id, agent_id)
+ else {
+ return false;
+ };
+ let Ok(Some(transcript)) = handle.read_session() else {
+ return false;
+ };
+ let Ok(history) = OpenHumanTranscriptCodec.decode_history(&transcript) else {
+ return false;
+ };
+ if history.is_empty() || self.ensure_runtime_session().is_err() {
+ return false;
+ }
+ self.runtime_session
+ .as_mut()
+ .expect("runtime session initialized")
+ .seed_history(history, transcript.messages)
+ .is_ok()
+ }
+
+ /// Dispatch one public OpenHuman turn through the neutral runtime.
+ pub async fn turn(&mut self, user_message: &str) -> Result<String> {
+ self.ensure_runtime_session()?;
+
+ let mut context = OpenHumanRunContext::new();
+ context.progress = self.on_progress.clone();
+ context.thread_id = self.thread_id.clone();
+ context.workspace = self.workspace_descriptor.clone();
+ let cancellation = context.cancellation.clone();
+ let options = TurnOptions {
+ request_id: crate::agent::turn_origin::current_request_id(),
+ thread_id: self.thread_id.clone(),
+ stream: self.on_progress.is_some(),
+ resume: if self
+ .runtime_session
+ .as_ref()
+ .is_some_and(|session| session.history().is_empty())
+ {
+ ResumeMode::LatestForAgent
+ } else {
+ ResumeMode::Never
+ },
+ cancellation,
+ run_context: context.into_tinyagents(tinyagents_harness::context::RunConfig::new(
+ "openhuman-session",
+ )),
+ };
+ let outcome = self
+ .runtime_session
+ .as_mut()
+ .expect("runtime session initialized")
+ .turn(
+ SessionTurnRequest::new(Message::user(user_message)),
+ options,
+ )
+ .await
+ .map_err(|error| anyhow::anyhow!(error.to_string()))?;
+ Ok(outcome.output.unwrap_or_default())
+ }
+
+ fn ensure_runtime_session(&mut self) -> Result<()> {
+ if self.runtime_session.is_some() {
+ return Ok(());
+ }
+ let context_mw = TurnContextMiddleware {
+ tool_result_budget_bytes: self
+ .context
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .tool_result_budget_bytes(),
+ payload_summarizer: self.payload_summarizer.clone(),
+ task_hint: None,
+ artifact_store: None,
+ tokenjuice_compaction_enabled: self
+ .context
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .compaction_enabled(),
+ tokenjuice_compression: self.tokenjuice_compression,
+ runtime_config: self.runtime_config.clone(),
+ microcompact_keep_recent: self
+ .context
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .microcompact_keep_recent(),
+ autocompact_enabled: self
+ .context
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .autocompact_enabled(),
+ handoff: None,
+ transcript_snapshot: None,
+ };
+ let driver = Arc::new(OpenHumanSessionDriver::new(
+ self.turn_model_source.clone(),
+ self.tool_dispatcher.clone(),
+ self.model_name.clone(),
+ self.temperature,
+ self.config.max_tool_iterations,
+ self.model_vision,
+ self.run_queue.clone(),
+ self.workspace_descriptor.clone(),
+ self.resolved_definition()
+ .map(|definition| definition.sandbox_mode)
+ .unwrap_or(crate::agent::harness::definition::SandboxMode::None),
+ self.hosted_base.clone(),
+ self.agent_definition_id.clone(),
+ ));
+ let shared = self.runtime_state.clone();
+ let resume_target = TranscriptTarget::new(
+ self.session_locator(),
+ self.runtime_transcript_stem(),
+ self.runtime_transcript_meta(),
+ )
+ .with_resume_agent(self.agent_definition_name.clone());
+ {
+ let mut state = self
+ .runtime_state
+ .lock()
+ .unwrap_or_else(|poisoned| poisoned.into_inner());
+ state.resume_target = Some(resume_target);
+ state.context_middleware = Some(context_mw.clone());
+ state.required_output = self
+ .config
+ .required_output
+ .as_ref()
+ .map(crate::agent::tinyagents::config::required_output_from);
+ state.prelude = Some(OpenHumanTurnPrelude {
+ memory: self.memory.clone(),
+ learning_enabled: self.learning_enabled,
+ explicit_preferences_enabled: self.explicit_preferences_enabled,
+ config: self.config.clone(),
+ context: self.context.clone(),
+ tool_policy: self.tool_policy.clone(),
+ tool_dispatcher: self.tool_dispatcher.clone(),
+ workspace_dir: self.workspace_dir.clone(),
+ action_dir: self.action_dir.clone(),
+ model_name: self.model_name.clone(),
+ agent_definition_name: self.agent_definition_name.clone(),
+ omit_profile: self.omit_profile,
+ omit_memory_md: self.omit_memory_md,
+ auto_save: self.auto_save,
+ thread_id: self.thread_id.clone(),
+ auto_recall: self.auto_recall.clone(),
+ agent_definition_id: self.agent_definition_id.clone(),
+ event_session_id: self.event_session_id.clone(),
+ event_channel: self.event_channel.clone(),
+ trigger_memory_agent: self.trigger_memory_agent,
+ subagent_tool_ceiling_names: self.subagent_tool_ceiling_names.clone(),
+ turn_model_source: self.turn_model_source.clone(),
+ temperature: self.temperature,
+ workspace_descriptor: self.workspace_descriptor.clone(),
+ session_key: self.session_key.clone(),
+ session_parent_prefix: self.session_parent_prefix.clone(),
+ on_progress: self.on_progress.clone(),
+ run_queue: self.run_queue.clone(),
+ allowed_subagent_ids: self
+ .resolved_definition()
+ .map(|definition| {
+ definition
+ .subagents
+ .iter()
+ .filter_map(|entry| match entry {
+ crate::agent::harness::definition::SubagentEntry::AgentId(id) => {
+ Some(id.clone())
+ }
+ crate::agent::harness::definition::SubagentEntry::Skills(
+ wildcard,
+ ) if wildcard.matches_all() => {
+ Some("integrations_agent".to_string())
+ }
+ crate::agent::harness::definition::SubagentEntry::Skills(_) => None,
+ })
+ .collect()
+ })
+ .unwrap_or_default(),
+ sandbox_mode: self
+ .resolved_definition()
+ .map(|definition| definition.sandbox_mode)
+ .unwrap_or(crate::agent::harness::definition::SandboxMode::None),
+ runtime_config: self.runtime_config.clone(),
+ archivist_hook: self.archivist_hook.clone(),
+ tool_surface: Arc::new(std::sync::Mutex::new(OpenHumanTurnToolSurface {
+ tools: self.tools.clone(),
+ synthesized_tools: self.synthesized_tools.clone(),
+ tool_specs: self.tool_specs.clone(),
+ durable_tool_specs: self.durable_tool_specs.clone(),
+ visible_tool_specs: self.visible_tool_specs.clone(),
+ visible_tool_names: self.visible_tool_names.clone(),
+ auto_include_new_synthesized_tools: true,
+ synthesized_tool_names: self.synthesized_tool_names.clone(),
+ tool_policy_session: self.tool_policy_session.clone(),
+ event_session_id: self.event_session_id.clone(),
+ event_channel: self.event_channel.clone(),
+ agent_definition_name: self.agent_definition_name.clone(),
+ })),
+ mutable: Arc::new(std::sync::Mutex::new(OpenHumanTurnPreludeMutable {
+ last_memory_context: self.last_memory_context.clone(),
+ announced_integrations: self.announced_integrations.clone(),
+ pending_integration_announcement: self.pending_integration_announcement.clone(),
+ announced_mcp_servers: self.announced_mcp_servers.clone(),
+ pending_mcp_announcement: self.pending_mcp_announcement.clone(),
+ announced_skills: self.announced_skills.clone(),
+ pending_skill_announcement: self.pending_skill_announcement.clone(),
+ pending_skill_retraction: self.pending_skill_retraction.clone(),
+ connected_integrations: self.connected_integrations.clone(),
+ connected_integrations_initialized: self.connected_integrations_initialized,
+ workflows: self.workflows.clone(),
+ composio_events: None,
+ skill_events: None,
+ pending_user_autosave: None,
+ })),
+ });
+ }
+ let hooks = Arc::new(OpenHumanSessionHooks::new(
+ move |_, _, _| {
+ let shared = shared.clone();
+ Box::pin(async move {
+ Ok(ResumePreparation {
+ transcript: shared
+ .lock()
+ .unwrap_or_else(|poisoned| poisoned.into_inner())
+ .resume_target
+ .clone(),
+ })
+ })
+ },
+ {
+ let state = self.runtime_state.clone();
+ move |request, options, view| {
+ let state = state.clone();
+ let request_base_len = view.history.len()
+ + usize::from(view.history.last() != Some(&request.input));
+ let resumed_prefix = view.resumed.then(|| {
+ view.history
+ .first()
+ .filter(|message| matches!(message, Message::System(_)))
+ .cloned()
+ .map(|message| PrefixSnapshot::new(vec![message]))
+ });
+ Box::pin(async move {
+ let transcript_snapshot =
+ crate::agent::tinyagents::TranscriptSnapshotSink::default();
+ transcript_snapshot
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .request_base_len = request_base_len;
+ let prelude = state
+ .lock()
+ .unwrap_or_else(|poisoned| poisoned.into_inner())
+ .prelude
+ .clone();
+ let prelude = prelude.ok_or_else(|| {
+ tinyagents_runtime::RuntimeError::MissingDependency(
+ "OpenHumanTurnPrelude",
+ )
+ })?;
+ prelude
+ .refresh_turn_boundary(!view.resumed && view.history.is_empty())
+ .await;
+ // The driver resolves the same model source, but the
+ // host sidecar needs this metadata before either the
+ // successful or partial runtime append asks the codec
+ // for atomic billing data.
+ let context_window = prelude
+ .turn_model_source
+ .effective_context_window(&prelude.model_name)
+ .await
+ .unwrap_or_default();
+ options
+ .run_context
+ .data
+ .session_sidecar
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .context_window = context_window;
+ let original_user_message = request.input.text();
+ prelude.begin_user_effects(
+ &mut state
+ .lock()
+ .unwrap_or_else(|poisoned| poisoned.into_inner()),
+ request,
+ );
+ let overrides = std::mem::take(
+ &mut state
+ .lock()
+ .unwrap_or_else(|poisoned| poisoned.into_inner())
+ .pending_turn_overrides,
+ );
+ let enriched = prelude
+ .enrich_request(
+ &original_user_message,
+ &overrides,
+ &mut options.run_context.data,
+ )
+ .await;
+ request.input = Message::user(enriched);
+ let mut preparation = prelude
+ .prepare(!view.resumed && view.history.is_empty())
+ .await
+ .map_err(|error| {
+ tinyagents_runtime::RuntimeError::Driver(error.to_string())
+ })?;
+ if overrides.suppress_tools {
+ preparation.tools = Some(ToolSnapshot::default());
+ }
+ let (
+ mut current_tools,
+ mut current_synthesized_tools,
+ policy_session,
+ policy_session_id,
+ policy_channel,
+ ) = prelude.current_tool_source();
+ if overrides.suppress_tools {
+ // The execution source must narrow with the wire
+ // snapshot. Leaving instances here would make a
+ // tool-less override advisory instead of a hard
+ // authority boundary.
+ current_tools = Arc::new(Vec::new());
+ current_synthesized_tools = Arc::new(Vec::new());
+ }
+ let mut middleware = state
+ .lock()
+ .unwrap_or_else(|poisoned| poisoned.into_inner())
+ .context_middleware
+ .clone()
+ .ok_or_else(|| {
+ tinyagents_runtime::RuntimeError::MissingDependency(
+ "TurnContextMiddleware",
+ )
+ })?;
+ middleware.transcript_snapshot = Some(transcript_snapshot);
+ options.run_context.data.context_middleware = Some(middleware);
+ options.run_context.data.current_tools = Some(current_tools);
+ options.run_context.data.current_synthesized_tools =
+ Some(current_synthesized_tools);
+ options.run_context.data.tool_policy =
+ Some(crate::agent::tinyagents::ToolPolicyEnforcement {
+ policy: prelude.tool_policy.clone(),
+ session: policy_session,
+ session_id: policy_session_id,
+ channel: policy_channel,
+ // This is the stable agent definition key
+ // used for driver diagnostics and policy
+ // enforcement. The mutable surface carries
+ // its current display name separately when it
+ // rebuilds the policy session.
+ agent_definition_id: prelude.agent_definition_id.clone(),
+ });
+ options.run_context.data.required_output = state
+ .lock()
+ .unwrap_or_else(|poisoned| poisoned.into_inner())
+ .required_output
+ .clone();
+ if let Some(prefix) = resumed_prefix {
+ preparation.prefix = prefix;
+ }
+ Ok(preparation)
+ })
+ }
+ },
+ |outcome, _| {
+ Box::pin(async move {
+ if outcome
+ .output
+ .as_deref()
+ .is_none_or(|output| output.trim().is_empty())
+ {
+ return Err(tinyagents_runtime::RuntimeError::Driver(
+ "driver returned an empty final response after repair".into(),
+ ));
+ }
+ Ok(())
+ })
+ },
+ {
+ let state = self.runtime_state.clone();
+ let progress = self.on_progress.clone();
+ let post_turn_hooks = self.post_turn_hooks.clone();
+ let session_id = self.event_session_id.clone();
+ let agent_id = self.agent_definition_id.clone();
+ let channel = self.event_channel.clone();
+ move |receipt| {
+ let state = state.clone();
+ let progress = progress.clone();
+ let post_turn_hooks = post_turn_hooks.clone();
+ let session_id = session_id.clone();
+ let agent_id = agent_id.clone();
+ let channel = channel.clone();
+ Box::pin(async move {
+ let iterations = receipt
+ .outcome
+ .history
+ .iter()
+ .filter(|message| matches!(message, Message::Assistant(_)))
+ .count()
+ .max(1) as u32;
+ let output = receipt.outcome.output.clone().unwrap_or_default();
+ let input = receipt
+ .outcome
+ .history
+ .iter()
+ .rev()
+ .find_map(|message| match message {
+ Message::User(_) => Some(message.text()),
+ _ => None,
+ })
+ .unwrap_or_default();
+ let sidecar = receipt
+ .options
+ .context
+ .session_sidecar
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .clone();
+ let usage = holistic_last_turn_usage(&sidecar);
+ let interrupted = sidecar.hit_cap || receipt.outcome.interrupted;
+ let tool_calls = sidecar
+ .tool_outcomes
+ .iter()
+ .map(|outcome| crate::agent::hooks::ToolCallRecord {
+ name: outcome.name.clone(),
+ arguments: outcome.arguments.clone(),
+ success: outcome.success,
+ output_summary: crate::agent::hooks::sanitize_tool_output(
+ &outcome.content,
+ &outcome.name,
+ outcome.success,
+ ),
+ duration_ms: outcome.duration_ms,
+ })
+ .collect::<Vec<_>>();
+ let turn_duration_ms = sidecar
+ .duration
+ .map(|duration| duration.as_millis().min(u128::from(u64::MAX)) as u64)
+ .unwrap_or_default();
+ let prelude = state
+ .lock()
+ .unwrap_or_else(|poisoned| poisoned.into_inner())
+ .prelude
+ .clone();
+ let citations = state
+ .lock()
+ .unwrap_or_else(|poisoned| poisoned.into_inner())
+ .pending_citations
+ .take();
+ if let Some(prelude) = prelude {
+ // `after_commit` is only reached after runtime
+ // transcript durability. Every host write below is
+ // therefore receipt-gated.
+ prelude.finalize_after_durable_commit(&receipt).await;
+ // Account the same committed direct + child totals
+ // that the codec atomically attached to the
+ // transcript. A continuation's suppression state
+ // is intentionally cleared by the goals runtime
+ // only after this receipt exists.
+ account_committed_turn_against_goal(
+ &prelude.workspace_dir,
+ receipt.options.context.thread_id.as_deref(),
+ &sidecar,
+ )
+ .await;
+ }
+ // Citations are display-only, but their result belongs
+ // to this committed turn. Join only after durability so
+ // a failed/cancelled candidate never becomes the UI's
+ // "last turn" citation set.
+ let citations = match citations {
+ Some(task) => task.await.unwrap_or_default(),
+ None => Vec::new(),
+ };
+ state
+ .lock()
+ .unwrap_or_else(|poisoned| poisoned.into_inner())
+ .last_commit = Some(receipt);
+ let mut state = state
+ .lock()
+ .unwrap_or_else(|poisoned| poisoned.into_inner());
+ state.last_turn_hit_cap = interrupted;
+ state.last_turn_usage = Some(usage);
+ state.last_turn_citations = citations;
+ if let Some(progress) = &progress {
+ let _ = progress.try_send(
+ crate::agent::progress::AgentProgress::TurnContent {
+ input: Some(input.clone()),
+ output: Some(output.clone()),
+ },
+ );
+ let _ = progress.try_send(
+ crate::agent::progress::AgentProgress::TurnCompleted { iterations },
+ );
+ }
+ crate::agent::hooks::fire_hooks(
+ &post_turn_hooks,
+ crate::agent::hooks::TurnContext {
+ user_message: input,
+ assistant_response: output,
+ tool_calls,
+ turn_duration_ms,
+ session_id: Some(session_id.clone()),
+ agent_id: Some(agent_id.clone()),
+ entrypoint: Some(channel.clone()),
+ iteration_count: iterations as usize,
+ },
+ );
+ Ok(())
+ })
+ }
+ },
+ {
+ let state = self.runtime_state.clone();
+ move |terminal| {
+ let state = state.clone();
+ Box::pin(async move {
+ state
+ .lock()
+ .unwrap_or_else(|poisoned| poisoned.into_inner())
+ .terminals
+ .push(terminal);
+ Ok(())
+ })
+ }
+ },
+ ));
+ self.runtime_session = Some(
+ SessionBuilder::new(driver)
+ .codec(Arc::new(OpenHumanTranscriptCodec))
+ .hooks(hooks)
+ .build()
+ .map_err(|error| anyhow::anyhow!(error.to_string()))?,
+ );
+ Ok(())
+ }
+
+ /// Publish a caller-driven visibility/policy mutation into the live hook
+ /// state. The runtime keeps generic snapshots immutable per request; this
+ /// simply replaces the host composition from which the *next* snapshot,
+ /// execution source, and enforcement object are built.
+ pub(in crate::agent::session_host) fn sync_runtime_tool_surface(&self) {
+ self.sync_runtime_tool_surface_with_auto_include(None);
+ }
+
+ /// Publish a visibility mutation and record whether future dynamically
+ /// connected delegates may enter the surface without an explicit allow.
+ pub(in crate::agent::session_host) fn sync_runtime_tool_surface_with_auto_include(
+ &self,
+ auto_include_new_synthesized_tools: Option<bool>,
+ ) {
+ let prelude = self
+ .runtime_state
+ .lock()
+ .unwrap_or_else(|poisoned| poisoned.into_inner())
+ .prelude
+ .clone();
+ let Some(prelude) = prelude else {
+ return;
+ };
+ let prior_auto_include = prelude
+ .tool_surface
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .auto_include_new_synthesized_tools;
+ prelude.replace_tool_surface(OpenHumanTurnToolSurface {
+ tools: self.tools.clone(),
+ synthesized_tools: self.synthesized_tools.clone(),
+ tool_specs: self.tool_specs.clone(),
+ durable_tool_specs: self.durable_tool_specs.clone(),
+ visible_tool_specs: self.visible_tool_specs.clone(),
+ visible_tool_names: self.visible_tool_names.clone(),
+ auto_include_new_synthesized_tools: auto_include_new_synthesized_tools
+ .unwrap_or(prior_auto_include),
+ synthesized_tool_names: self.synthesized_tool_names.clone(),
+ tool_policy_session: self.tool_policy_session.clone(),
+ event_session_id: self.event_session_id.clone(),
+ event_channel: self.event_channel.clone(),
+ agent_definition_name: self.agent_definition_name.clone(),
+ });
+ }
+
+ fn runtime_transcript_stem(&self) -> String {
+ match &self.session_parent_prefix {
+ Some(prefix) => format!("{prefix}__{}", self.session_key),
+ None => self.session_key.clone(),
+ }
+ }
+
+ fn session_locator(&self) -> Arc<dyn tinyagents_session::transcript::TranscriptLocator> {
+ self.session_history_locator.clone().unwrap_or_else(|| {
+ Arc::new(tinyagents_session::transcript::FileTranscriptLocator::new(
+ self.workspace_dir.clone(),
+ ))
+ })
+ }
+
+ fn runtime_transcript_meta(&self) -> TranscriptMeta {
+ let now = chrono::Utc::now().to_rfc3339();
+ TranscriptMeta {
+ agent_name: self.agent_definition_name.clone(),
+ agent_id: Some(self.agent_definition_id.clone()),
+ agent_type: Some(if self.session_parent_prefix.is_some() {
+ "subagent".into()
+ } else {
+ "root".into()
+ }),
+ dispatcher: if self.tool_dispatcher.should_send_tool_specs() {
+ "native".into()
+ } else {
+ "xml".into()
+ },
+ provider: None,
+ model: Some(self.model_name.clone()),
+ created: now.clone(),
+ updated: now,
+ turn_count: 0,
+ input_tokens: 0,
+ output_tokens: 0,
+ cached_input_tokens: 0,
+ charged_amount_usd: 0.0,
+ thread_id: self.thread_id.clone(),
+ task_id: None,
+ }
+ }
+}
diff --git a/crates/openhuman-core/src/agent/harness/session/tool_progress.rs b/crates/openhuman-core/src/agent/session_host/tool_progress.rs
similarity index 98%
rename from crates/openhuman-core/src/agent/harness/session/tool_progress.rs
rename to crates/openhuman-core/src/agent/session_host/tool_progress.rs
index b455619b39..c64a402b42 100644
--- a/crates/openhuman-core/src/agent/harness/session/tool_progress.rs
+++ b/crates/openhuman-core/src/agent/session_host/tool_progress.rs
@@ -3,7 +3,7 @@
//! The legacy direct tool-execution path never names a concrete [`AgentProgress`]
//! variant. It talks to a [`ProgressReporter`], whose impls pick the event flavor:
//!
-//! * [`TurnProgress`] — top-level chat (channel loop, `Agent::turn`): emits the
+//! * [`TurnProgress`] — top-level chat (channel loop, `OpenHumanSessionHost::turn`): emits the
//! `Turn*` / `ToolCall*` / `TurnCostUpdated` events and streams provider
//! deltas as `TextDelta` / `ThinkingDelta` / `ToolCallArgsDelta`.
diff --git a/crates/openhuman-core/src/agent/harness/session/turn/context.rs b/crates/openhuman-core/src/agent/session_host/turn/context.rs
similarity index 64%
rename from crates/openhuman-core/src/agent/harness/session/turn/context.rs
rename to crates/openhuman-core/src/agent/session_host/turn/context.rs
index 8953c5d785..25d88c67cc 100644
--- a/crates/openhuman-core/src/agent/harness/session/turn/context.rs
+++ b/crates/openhuman-core/src/agent/session_host/turn/context.rs
@@ -1,142 +1,62 @@
//! History, context, and system prompt management.
-use super::super::turn_checkpoint::assistant_message_has_tool_calls;
-use super::super::types::Agent;
-use super::{collect_tree_root_summaries, sanitize_learned_entry};
-use crate::agent::messages::{ChatMessage, ConversationMessage};
+use super::super::types::OpenHumanSessionHost;
use crate::agent::prompts::{
- tool_call_format_from_dialect, LearnedContextData, PromptContext, PromptTool,
+ LearnedContextData, PromptContext, PromptTool, tool_call_format_from_dialect,
};
use crate::memory::MemoryCategory;
use crate::tools::agent_policy::render_tool_policy_boundary;
use anyhow::Result;
-impl Agent {
- // ─────────────────────────────────────────────────────────────────
- // History & prompt helpers
- // ─────────────────────────────────────────────────────────────────
+async fn collect_tree_root_summaries(
+ per_namespace_cap: usize,
+ total_cap: usize,
+) -> Vec<crate::agent::prompts::NamespaceSummary> {
+ use crate::memory::api::provider::MemoryProvider;
- /// Truncates the conversation history to the configured maximum message count.
- ///
- /// System messages are always preserved. Older non-system messages are
- /// dropped first.
- pub(in super::super) fn trim_history(&mut self) {
- let max = self.config.max_history_messages;
- if self.history.len() <= max {
- return;
- }
-
- let mut system_messages = Vec::new();
- let mut other_messages = Vec::new();
-
- for msg in self.history.drain(..) {
- match &msg {
- ConversationMessage::Chat(chat) if chat.role == "system" => {
- system_messages.push(msg);
- }
- _ => other_messages.push(msg),
- }
+ let Ok(guard) = crate::memory::ops::guard::active_memory_guard().await else {
+ return Vec::new();
+ };
+ let Some(tree) = guard.as_tree() else {
+ return Vec::new();
+ };
+ match tree
+ .root_summaries_with_caps(per_namespace_cap, total_cap)
+ .await
+ {
+ Ok(rows) => rows
+ .into_iter()
+ .map(|row| crate::agent::prompts::NamespaceSummary {
+ namespace: row.namespace,
+ body: row.body,
+ updated_at: row.updated_at,
+ })
+ .collect(),
+ Err(error) => {
+ log::warn!("[session-runtime] tree root summaries unavailable: {error}");
+ Vec::new()
}
-
- if other_messages.len() > max {
- let drop_count = other_messages.len() - max;
- other_messages.drain(0..drop_count);
- }
-
- // A cut that lands *between* an `AssistantToolCalls` and its
- // `ToolResults` leaves the window opening on an orphaned `ToolResults`.
- // Serialized, that is a `tool` message with no preceding `tool_calls`,
- // which the provider rejects with a 400 (the response streams back
- // empty and surfaces to the user as "Something went wrong"). Snap the
- // boundary forward past any leading orphaned results so the window
- // always starts on a clean turn (a `Chat` or an `AssistantToolCalls`).
- let orphan_lead = other_messages
- .iter()
- .take_while(|m| matches!(m, ConversationMessage::ToolResults(_)))
- .count();
- if orphan_lead > 0 {
- log::debug!(
- "[agent] trim_history snapped window past {orphan_lead} orphaned ToolResults \
- (tool-cycle bisected by the {max}-message cap)"
- );
- other_messages.drain(0..orphan_lead);
- }
-
- self.history = system_messages;
- self.history.extend(other_messages);
}
+}
- /// Bound a resumed transcript prefix to the agent history window.
- ///
- /// Resume paths may load a long prior transcript directly into
- /// `cached_transcript_messages` (provider-ready `ChatMessage`s), which
- /// bypasses `self.history`-based trimming/reduction. Keep at most
- /// `max_history_messages` entries while preserving the leading system
- /// message when present.
- pub(in super::super) fn bound_cached_transcript_messages(
- &self,
- messages: Vec<ChatMessage>,
- ) -> Vec<ChatMessage> {
- let max = self.config.max_history_messages.max(1);
- if messages.len() <= max {
- return messages;
- }
-
- let has_system = matches!(messages.first(), Some(msg) if msg.role == "system");
- let keep_tail = if has_system {
- max.saturating_sub(1)
- } else {
- max
- };
- let start = messages.len().saturating_sub(keep_tail);
-
- // Same hazard as `trim_history`: the tail slice can open on a `tool`
- // message whose `tool_calls` opener fell outside the window, which the
- // provider rejects. Advance past any leading orphaned `tool` results so
- // the window starts on a clean turn.
- let tail = &messages[start..];
- let orphan_lead = tail.iter().take_while(|m| m.role == "tool").count();
- if orphan_lead > 0 {
- log::debug!(
- "[agent] bound_cached_transcript_messages snapped window past {orphan_lead} \
- orphaned tool result(s) (tool-cycle bisected by the {max}-message cap)"
- );
- }
- let tail = &tail[orphan_lead..];
-
- let mut bounded = Vec::with_capacity(tail.len() + usize::from(has_system));
- if has_system {
- bounded.push(messages[0].clone());
- }
- bounded.extend(tail.iter().cloned());
-
- // TAURI-RUST-7: symmetric guard to the leading-orphan strip above. A
- // resumed transcript that ends on an `assistant` message containing
- // `tool_calls` (because the cached transcript was captured mid-cycle,
- // before the tool responses were persisted) is rejected by the
- // provider with `400 An assistant message with 'tool_calls' must be
- // followed by tool messages`. Pop any such trailing assistant
- // tool_calls so the bounded transcript ends on a clean turn boundary.
- let mut dropped_tail = 0usize;
- while bounded
- .last()
- .map(assistant_message_has_tool_calls)
- .unwrap_or(false)
- {
- bounded.pop();
- dropped_tail += 1;
- }
- if dropped_tail > 0 {
- log::debug!(
- "[agent] bound_cached_transcript_messages stripped {dropped_tail} trailing \
- assistant tool_calls message(s) without paired tool responses"
- );
- }
-
- bounded
+fn sanitize_learned_entry(content: &str) -> String {
+ let trimmed = content.trim();
+ if trimmed.is_empty() {
+ return String::new();
}
+ let sanitized: String = trimmed.chars().take(200).collect();
+ if sanitized.contains("Bearer ")
+ || sanitized.contains("sk-")
+ || sanitized.contains("ghp_")
+ || sanitized.contains("-----BEGIN")
+ {
+ return "[redacted: potential secret]".to_string();
+ }
+ sanitized
+}
+impl OpenHumanSessionHost {
/// Pre-fetches learned context data from memory (observations, patterns, user profile).
///
/// This is an async, non-blocking operation that populates the context
@@ -335,7 +255,11 @@ impl Agent {
// Route through the global context manager so every
// prompt-building call-site — main agent, sub-agent runner,
// channel runtimes — shares one builder configuration.
- let prompt = self.context.build_system_prompt(&ctx)?;
+ let prompt = self
+ .context
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .build_system_prompt(&ctx)?;
// Appended, not prepended (#5704). Every line of this block is
// session-scoped — agent id, channel, entry point, risk level, the
// allowed-tool list — so putting it first moves the prompt's first
@@ -355,7 +279,7 @@ impl Agent {
/// Place the tool-policy boundary block relative to the assembled prompt.
///
-/// Separated from [`Agent`] so the ordering can be tested without standing up a
+/// Separated from [`OpenHumanSessionHost`] so the ordering can be tested without standing up a
/// session: everything that decides the placement is in these two arguments.
fn append_tool_policy_boundary(prompt: String, boundary: Option<String>) -> String {
match boundary {
@@ -363,7 +287,3 @@ fn append_tool_policy_boundary(prompt: String, boundary: Option<String>) -> Stri
None => prompt,
}
}
-
-#[cfg(test)]
-#[path = "context_tests.rs"]
-mod tool_policy_boundary_placement_tests;
diff --git a/crates/openhuman-core/src/agent/harness/session/turn/graph.rs b/crates/openhuman-core/src/agent/session_host/turn/graph.rs
similarity index 86%
rename from crates/openhuman-core/src/agent/harness/session/turn/graph.rs
rename to crates/openhuman-core/src/agent/session_host/turn/graph.rs
index 2a5f1cea4b..eb4f95628b 100644
--- a/crates/openhuman-core/src/agent/harness/session/turn/graph.rs
+++ b/crates/openhuman-core/src/agent/session_host/turn/graph.rs
@@ -8,8 +8,8 @@
//! driven by the tinyagents harness, observed via the session's `on_progress`
//! sink (live tool timeline, streaming text deltas, cost/token footer) and
//! steerable mid-flight through the session run queue. The loop pauses gracefully
-//! at the model-call cap so [`core`](super::core) can emit a resumable checkpoint
-//! instead of erroring.
+//! at the model-call cap; the session driver then runs its tools-disabled,
+//! grounded close when the in-loop conclusion was unavailable.
//!
//! **Available tools.** The agent's resolved harness tool set (`tools`),
//! advertised via the canonical shared-tool adapter
@@ -62,7 +62,9 @@ pub(crate) struct ChatTurnGraph {
/// mid-session Composio connect reach the model as a *callable* tool and a
/// revoke withdraw one, without owning `tools`.
pub synthesized_tools: Arc<Vec<Box<dyn Tool>>>,
- /// Callable-tool whitelist (empty = every visible tool).
+ /// Callable-tool whitelist captured from the runtime request snapshot.
+ /// An empty set is deny-all, never an implicit expansion to the driver's
+ /// construction-time registry.
pub visible_tool_names: HashSet<String>,
/// Model-call cap for the loop.
pub max_iterations: usize,
@@ -99,25 +101,20 @@ pub(crate) struct ChatTurnGraph {
}
/// Drive the chat turn graph: a thin wrapper over the shared tinyagents seam
-/// that pins the chat path's fixed arguments. Returns the turn outcome
-/// ([`core`](super::core) folds usage, persists the conversation, and handles a
-/// cap-hit checkpoint).
+/// that pins the chat path's fixed arguments. Returns the loop outcome; the
+/// session driver owns post-loop grounded close and records all final usage in
+/// its post-commit sidecar.
pub(crate) async fn run_chat_turn_graph(graph: ChatTurnGraph) -> Result<TinyagentsTurnOutcome> {
let hosted_base = graph.hosted_base.clone().ok_or_else(|| {
anyhow::anyhow!(
"hosted root invocation is unavailable because the session has no hosted authority"
)
})?;
- // Fail-closed allowlist plumbing (issue #4452): the shared seam now takes an
- // `Option<HashSet<String>>` where `None` = no filter (all visible tools) and
- // `Some(set)` = exactly those tools. The chat path's historical convention is
- // "empty `visible_tool_names` = every visible tool", so map an empty set to
- // `None` to preserve that behavior; a populated set stays an explicit filter.
- let visible_tool_names = if graph.visible_tool_names.is_empty() {
- None
- } else {
- Some(graph.visible_tool_names)
- };
+ // `DriverRequest.tools` is the model-visible authority for this invocation.
+ // The shared seam's `Some(empty)` spelling is intentionally a deny-all;
+ // translating it to `None` would re-expose every construction-time tool
+ // when a host deliberately supplied an empty snapshot.
+ let visible_tool_names = Some(graph.visible_tool_names);
// The turn's crate `ChatModel` set was built by the caller from the session's
// `TurnModelSource` (issue #4249, Phase 3 / Motion A); the telemetry id rides
// on the bundle.
@@ -137,7 +134,7 @@ pub(crate) async fn run_chat_turn_graph(graph: ChatTurnGraph) -> Result<Tinyagen
&graph.model,
graph.messages,
// Durable set first, synthesised second — the order `tool_specs` and
- // `Agent::all_tool_refs` use, so the name a spec was advertised
+ // `OpenHumanSessionHost::all_tool_refs` use, so the name a spec was advertised
// under resolves to the same instance here. The two sets are
// disjoint by construction (`builder::drop_synthesized_name_collisions`),
// so the order never decides a collision; it only keeps every
@@ -171,11 +168,10 @@ pub(crate) async fn run_chat_turn_graph(graph: ChatTurnGraph) -> Result<Tinyagen
graph.context_mw,
// Builder-configured tool policy enforcement (session chat path).
graph.tool_policy,
- // #4457 (defect C): defer the terminal `TurnCompleted` to the caller.
- // The session path (`run_turn_impl` in `turn/core.rs`) runs its cap/#4093
- // wrap-up (`summarize_turn_wrapup`) *after* this seam returns and then
- // emits the single `TurnCompleted` itself — a seam-level emit here would
- // fire before that checkpoint streams and duplicate the event.
+ // The runtime's durable `after_commit` callback emits the terminal
+ // event after any driver-grounded close has become part of the
+ // candidate history. A seam-level event would arrive before that
+ // close and duplicate the lifecycle projection.
true,
)
.await
diff --git a/crates/openhuman-core/src/agent/session_host/turn/mod.rs b/crates/openhuman-core/src/agent/session_host/turn/mod.rs
new file mode 100644
index 0000000000..07f011a8bf
--- /dev/null
+++ b/crates/openhuman-core/src/agent/session_host/turn/mod.rs
@@ -0,0 +1,22 @@
+//! Host-specific prompt construction, tool policy refresh, and the model graph.
+//!
+//! Generic turn lifecycle is intentionally absent: it is owned by
+//! `tinyagents_runtime::Session` in `runtime_session`.
+
+mod context;
+pub(crate) mod graph;
+mod tools;
+
+/// Returns newly connected capability names and records the observation once.
+pub(super) fn newly_connected_slugs(
+ connected: &[String],
+ announced: &mut std::collections::HashSet<String>,
+) -> Vec<String> {
+ let newly: Vec<String> = connected
+ .iter()
+ .filter(|slug| !announced.contains(*slug))
+ .cloned()
+ .collect();
+ announced.extend(newly.iter().cloned());
+ newly
+}
diff --git a/crates/openhuman-core/src/agent/harness/session/turn/recall_lanes.rs b/crates/openhuman-core/src/agent/session_host/turn/recall_lanes.rs
similarity index 90%
rename from crates/openhuman-core/src/agent/harness/session/turn/recall_lanes.rs
rename to crates/openhuman-core/src/agent/session_host/turn/recall_lanes.rs
index ab611056fd..c4d04f0a80 100644
--- a/crates/openhuman-core/src/agent/harness/session/turn/recall_lanes.rs
+++ b/crates/openhuman-core/src/agent/session_host/turn/recall_lanes.rs
@@ -24,11 +24,15 @@
//! `core_turn.rs` documents the broad per-turn recall that used to live here
//! and why it was removed; neither lane is that.
-use super::super::types::Agent;
+use super::super::types::OpenHumanSessionHost;
use std::time::Instant;
/// Append the Lane B and Lane C blocks for `user_message` to `context`.
-pub(super) async fn append_recall_lanes(agent: &Agent, user_message: &str, context: &mut String) {
+pub(super) async fn append_recall_lanes(
+ agent: &OpenHumanSessionHost,
+ user_message: &str,
+ context: &mut String,
+) {
let (situational, auto_recall) = tokio::join!(
situational_preferences(agent, user_message),
auto_recall_block(agent, user_message),
@@ -48,7 +52,7 @@ pub(super) async fn append_recall_lanes(agent: &Agent, user_message: &str, conte
}
/// Lane B: preferences semantically relevant to this message.
-async fn situational_preferences(agent: &Agent, user_message: &str) -> Vec<String> {
+async fn situational_preferences(agent: &OpenHumanSessionHost, user_message: &str) -> Vec<String> {
// 5 s, not 3: the module's lookup (a query embed round trip, queued behind
// the citation and autosave calls spawned off the turn) measured over 3 s
// on a live desktop and lost the block on both on-topic turns of the
@@ -86,7 +90,7 @@ async fn situational_preferences(agent: &Agent, user_message: &str) -> Vec<Strin
}
/// Lane C: the gated auto-recall block, when the session has the lane bound.
-async fn auto_recall_block(agent: &Agent, user_message: &str) -> Option<String> {
+async fn auto_recall_block(agent: &OpenHumanSessionHost, user_message: &str) -> Option<String> {
let Some(auto_recall) = agent.auto_recall.as_ref() else {
log::debug!("[auto_recall] no lane bound to this session; skipping");
return None;
diff --git a/crates/openhuman-core/src/agent/harness/session/turn/tools.rs b/crates/openhuman-core/src/agent/session_host/turn/tools.rs
similarity index 98%
rename from crates/openhuman-core/src/agent/harness/session/turn/tools.rs
rename to crates/openhuman-core/src/agent/session_host/turn/tools.rs
index 8a11416946..b0380c7e1e 100644
--- a/crates/openhuman-core/src/agent/harness/session/turn/tools.rs
+++ b/crates/openhuman-core/src/agent/session_host/turn/tools.rs
@@ -1,6 +1,6 @@
//! Tool execution and Composio delegation refresh.
-use super::super::types::Agent;
+use super::super::types::OpenHumanSessionHost;
use super::newly_connected_slugs;
use crate::agent::harness;
use crate::agent::progress::AgentProgress;
@@ -8,14 +8,14 @@ use crate::agent::progress::AgentProgress;
use std::sync::Arc;
/// One turn's tool inputs: the durable registry, the synthesised delegation
-/// set, and the callable-name allowlist. See [`Agent::turn_tool_sets`].
+/// set, and the callable-name allowlist. See [`OpenHumanSessionHost::turn_tool_sets`].
type TurnToolSets = (
Arc<Vec<Box<dyn tinytools::Tool>>>,
Arc<Vec<Box<dyn tinytools::Tool>>>,
std::collections::HashSet<String>,
);
-impl Agent {
+impl OpenHumanSessionHost {
// ─────────────────────────────────────────────────────────────────
// Sub-agent context snapshots
// ─────────────────────────────────────────────────────────────────
@@ -98,7 +98,7 @@ impl Agent {
///
/// Returns `(durable tools, synthesised delegation tools, visible names)`.
/// The two tool sets stay separate all the way to dispatch — see
- /// [`Agent::synthesized_tools`] for why they are not one `Arc`.
+ /// [`OpenHumanSessionHost::synthesized_tools`] for why they are not one `Arc`.
///
/// `suppress_tools` is the per-turn scope override (#1725): a chat /
/// small-talk turn runs with an EMPTY tool set, so the provider request
@@ -526,7 +526,7 @@ impl Agent {
/// [`crate::integrations::composio::cached_active_integrations`]).
///
/// **Concurrency**: this cannot fail on a shared session. The synthesised
- /// instances live in their own [`Agent::synthesized_tools`] `Arc`, which is
+ /// instances live in their own [`OpenHumanSessionHost::synthesized_tools`] `Arc`, which is
/// *replaced* rather than mutated in place — so an in-flight turn or a
/// spawned sub-agent holding a clone never blocks reconciliation. Those
/// readers keep the previous, self-consistent set for the rest of their
@@ -652,6 +652,7 @@ impl Agent {
// same-named skill tool on the wire — Anthropic 400s on dup
// tool names where OpenHuman's backend silently accepts.
self.rebuild_tool_policy_session();
+ self.sync_runtime_tool_surface();
// Compute add/remove deltas for the log line — useful when
// diagnosing a Composio connect/revoke that should have rebuilt
diff --git a/crates/openhuman-core/src/agent/harness/session/turn_checkpoint.rs b/crates/openhuman-core/src/agent/session_host/turn_checkpoint.rs
similarity index 92%
rename from crates/openhuman-core/src/agent/harness/session/turn_checkpoint.rs
rename to crates/openhuman-core/src/agent/session_host/turn_checkpoint.rs
index dab056dc42..ff7af14853 100644
--- a/crates/openhuman-core/src/agent/harness/session/turn_checkpoint.rs
+++ b/crates/openhuman-core/src/agent/session_host/turn_checkpoint.rs
@@ -109,13 +109,30 @@ conclusion yet, say that plainly and name what is missing.";
/// of room to give — so it needs the content that type exists to remove.
/// Widening `ToolCallRecord` would have carried raw payloads into every
/// learning record as a side effect.
-pub(super) struct CheckpointToolResult {
+pub(crate) struct CheckpointToolResult {
/// The tool that ran.
- pub name: String,
+ pub(crate) name: String,
/// Whether it reported success.
- pub success: bool,
+ pub(crate) success: bool,
/// Its raw output, truncated at the call site to [`CHECKPOINT_RESULT_CHARS`].
- pub content: String,
+ pub(crate) content: String,
+}
+
+/// Convert the typed boundary capture into the narrow record shape used by
+/// both the model-grounded close and deterministic fallbacks. The harness's
+/// transcript messages do not preserve a tool-result error flag, so this must
+/// use [`ToolCallOutcome`] rather than trying to infer success from prose.
+pub(crate) fn results_from_tool_outcomes(
+ outcomes: &[crate::agent::tinyagents::ToolCallOutcome],
+) -> Vec<CheckpointToolResult> {
+ outcomes
+ .iter()
+ .map(|outcome| CheckpointToolResult {
+ name: outcome.name.clone(),
+ success: outcome.success,
+ content: truncate_chars(&outcome.content, CHECKPOINT_RESULT_CHARS),
+ })
+ .collect()
}
/// How much of one tool result the deterministic checkpoint reproduces.
@@ -125,7 +142,7 @@ pub(super) struct CheckpointToolResult {
/// The model-written checkpoint is what should normally answer — this is the
/// safety net for when that call fails, and a truncated payload the user can
/// read beats a tool name they cannot act on.
-pub(super) const CHECKPOINT_RESULT_CHARS: usize = 800;
+pub(crate) const CHECKPOINT_RESULT_CHARS: usize = 800;
/// Ceiling on the reproduced output across **all** results in one checkpoint.
///
@@ -138,13 +155,13 @@ pub(super) const CHECKPOINT_RESULT_CHARS: usize = 800;
/// ones the loop exited before the model could read (the cap is checked before
/// the request is built), so they are both the freshest and the only ones
/// guaranteed to have reached no other reader.
-pub(super) const CHECKPOINT_TOTAL_CHARS: usize = 4_000;
+pub(crate) const CHECKPOINT_TOTAL_CHARS: usize = 4_000;
/// Truncate `text` to `max` **characters**, on a char boundary, appending an
/// ellipsis marker when anything was cut. Chars rather than bytes so a
/// multi-byte payload cannot panic the fallback that exists to stop a turn
/// wedging.
-pub(super) fn truncate_chars(text: &str, max: usize) -> String {
+pub(crate) fn truncate_chars(text: &str, max: usize) -> String {
let trimmed = text.trim();
if trimmed.chars().count() <= max {
return trimmed.to_string();
@@ -171,7 +188,7 @@ mod tests;
/// between the turn's work and the user. The output is quoted as data, under a
/// heading that says so, because none of it has been through a model on this
/// path: it is raw tool output being surfaced verbatim, not an answer.
-pub(super) fn build_deterministic_checkpoint(
+pub(crate) fn build_deterministic_checkpoint(
results: &[CheckpointToolResult],
max_iterations: usize,
) -> String {
@@ -194,7 +211,7 @@ pub(super) fn build_deterministic_checkpoint(
/// result's own output, spending `total_budget` characters from the **newest**
/// result backwards (see [`CHECKPOINT_TOTAL_CHARS`] for why newest first) and
/// disclosing how many earlier results were left out.
-pub(super) fn render_tool_results(results: &[CheckpointToolResult], total_budget: usize) -> String {
+pub(crate) fn render_tool_results(results: &[CheckpointToolResult], total_budget: usize) -> String {
// Render each block before choosing, so the budget is charged what
// the checkpoint will actually contain (CodeRabbit on #6068). Walking
// `r.content` alone undercounts by the per-result header and the `" > "`
@@ -250,7 +267,7 @@ pub(super) fn render_tool_results(results: &[CheckpointToolResult], total_budget
/// does not exist" contradicts. Still bounded, so a turn with a very long tool
/// history cannot push the wrap-up past a small context window. Past the bound
/// the oldest results drop first, disclosed as omitted.
-pub(super) const GROUNDING_TOTAL_CHARS: usize = 16_000;
+pub(crate) const GROUNDING_TOTAL_CHARS: usize = 16_000;
/// Instruction appended (as a synthetic user turn) when a turn finished its
/// tool work but the model produced **no final answer** — it yielded a
@@ -264,7 +281,7 @@ pub(super) const GROUNDING_TOTAL_CHARS: usize = 16_000;
/// ("I'll search the registry") after the work was over, and replies that
/// contradicted results the context middleware had already cleared from view.
/// So this names both failure shapes, and the records are restated below it.
-pub(super) const FINAL_ANSWER_INSTRUCTION: &str = "\
+pub(crate) const FINAL_ANSWER_INSTRUCTION: &str = "\
You have finished using tools for this turn but have not yet written a reply to the user. \
Tools are no longer available and nothing more will run this turn, so do not call any tools and do not \
describe steps you are about to take. Write a self-contained final message that reports what actually happened: \
@@ -280,7 +297,7 @@ If nothing conclusive resulted, say so plainly.";
/// The stop note is passed as input, not as text to repeat. The breaker words it
/// for a model ("Report this back instead of retrying"), which is right for a
/// sub-agent's parent and wrong on a user's screen.
-pub(super) fn final_answer_instruction(stop_reason: Option<&str>, records: &str) -> String {
+pub(crate) fn final_answer_instruction(stop_reason: Option<&str>, records: &str) -> String {
let mut out = String::new();
if let Some(reason) = stop_reason {
out.push_str(
@@ -337,7 +354,7 @@ pub(crate) fn close_verification_prompt(user_request: &str, records: &str, reply
/// The check call's verdict on a closing message.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-pub(super) enum CloseVerdict {
+pub(crate) enum CloseVerdict {
Accept,
Reject,
/// Neither word found (or the call failed). The reply is unverified, so the
@@ -348,7 +365,7 @@ pub(super) enum CloseVerdict {
/// Read the verdict from the check call's text: the **last** standalone
/// `ACCEPT`/`REJECT` token wins, so a model that reasons aloud before its
/// answer is read by its conclusion, and `UNACCEPTABLE` is not an `ACCEPT`.
-pub(super) fn parse_close_verdict(text: &str) -> CloseVerdict {
+pub(crate) fn parse_close_verdict(text: &str) -> CloseVerdict {
text.split(|c: char| !c.is_ascii_alphabetic())
.filter_map(|token| match token.to_ascii_uppercase().as_str() {
"ACCEPT" => Some(CloseVerdict::Accept),
@@ -374,7 +391,7 @@ pub(super) fn parse_close_verdict(text: &str) -> CloseVerdict {
/// The lead does not say the calls failed: `RepeatProgressMiddleware` halts
/// through the same slot when identical calls keep *succeeding*, and the
/// records below carry each call's real status.
-pub(super) fn build_deterministic_final_summary(
+pub(crate) fn build_deterministic_final_summary(
results: &[CheckpointToolResult],
stop_reason: Option<&str>,
) -> String {
@@ -395,7 +412,9 @@ pub(super) fn build_deterministic_final_summary(
lead.push_str("\n**What each tool call returned**\n");
lead
}
- None => String::from("I finished this turn without writing up a result. Here is what each tool call returned:\n"),
+ None => String::from(
+ "I finished this turn without writing up a result. Here is what each tool call returned:\n",
+ ),
};
if results.is_empty() {
out.push_str("\n- (no tool calls completed)\n");
diff --git a/crates/openhuman-core/src/agent/harness/session/turn_checkpoint_tests.rs b/crates/openhuman-core/src/agent/session_host/turn_checkpoint_tests.rs
similarity index 91%
rename from crates/openhuman-core/src/agent/harness/session/turn_checkpoint_tests.rs
rename to crates/openhuman-core/src/agent/session_host/turn_checkpoint_tests.rs
index 9d846a6de6..a3e7bbad24 100644
--- a/crates/openhuman-core/src/agent/harness/session/turn_checkpoint_tests.rs
+++ b/crates/openhuman-core/src/agent/session_host/turn_checkpoint_tests.rs
@@ -34,6 +34,33 @@ fn the_deterministic_checkpoint_reproduces_each_result_body() {
assert!(!out.contains("omitted for length"));
}
+#[test]
+fn checkpoint_records_keep_the_captured_tool_failure_status_and_body() {
+ let records = results_from_tool_outcomes(&[
+ crate::agent::tinyagents::ToolCallOutcome {
+ call_id: "call-ok".into(),
+ name: "read_file".into(),
+ arguments: serde_json::Value::Null,
+ success: true,
+ content: "configuration found".into(),
+ duration_ms: 0,
+ },
+ crate::agent::tinyagents::ToolCallOutcome {
+ call_id: "call-failed".into(),
+ name: "apply_patch".into(),
+ arguments: serde_json::Value::Null,
+ success: false,
+ content: "permission denied".into(),
+ duration_ms: 0,
+ },
+ ]);
+
+ let rendered = render_tool_results(&records, CHECKPOINT_TOTAL_CHARS);
+ assert!(rendered.contains("`read_file` — ok"));
+ assert!(rendered.contains("`apply_patch` — failed"));
+ assert!(rendered.contains("permission denied"));
+}
+
/// Over the budget the checkpoint starts later rather than truncating every
/// body, and says how many it skipped — a silent drop reads as "that is all
/// there was".
diff --git a/crates/openhuman-core/src/agent/harness/session/types.rs b/crates/openhuman-core/src/agent/session_host/types.rs
similarity index 83%
rename from crates/openhuman-core/src/agent/harness/session/types.rs
rename to crates/openhuman-core/src/agent/session_host/types.rs
index 9510cf4b47..48eedaaef0 100644
--- a/crates/openhuman-core/src/agent/harness/session/types.rs
+++ b/crates/openhuman-core/src/agent/session_host/types.rs
@@ -1,32 +1,30 @@
-//! `Agent` and `AgentBuilder` struct definitions.
+//! `OpenHumanSessionHost` and `SessionHostBuilder` struct definitions.
//!
//! The data shapes live here, separate from their behaviour, so the
//! rest of the sub-module (`builder.rs`, `turn.rs`, `runtime.rs`) can
//! focus on logic. Fields are `pub(super)` so sibling files that
-//! `impl Agent`/`impl AgentBuilder` can see them without the whole
+//! `impl OpenHumanSessionHost`/`impl SessionHostBuilder` can see them without the whole
//! crate gaining field access.
use crate::agent::context::ContextManager;
use crate::agent::harness::archivist::ArchivistHook;
use crate::agent::harness::definition::TriggerMemoryAgent;
use crate::agent::hooks::PostTurnHook;
-use crate::agent::messages::{ChatMessage, ConversationMessage};
use crate::agent::progress::AgentProgress;
use crate::agent::prompts::SystemPromptBuilder;
use crate::agent::tinyagents::TurnModelSource;
use crate::agent::tool_policy::ToolPolicy;
use crate::memory::Memory;
use crate::tools::agent_policy::ToolPolicySession;
-use std::path::PathBuf;
use std::sync::Arc;
use tinytools::{Tool, ToolSpec};
use tinytools_agent::dialect::ToolDialect;
-/// Per-turn behaviour overrides applied to a **single** [`Agent::turn`] call.
+/// Per-turn behaviour overrides applied to a **single** [`OpenHumanSessionHost::turn`] call.
///
/// Defaults to all-`false`, so an agent built and driven exactly as before
/// behaves identically — the overrides only take effect when a caller opts in
-/// via [`Agent::set_next_turn_overrides`] before dispatching a turn. The turn
+/// via [`OpenHumanSessionHost::set_next_turn_overrides`] before dispatching a turn. The turn
/// consumes (takes) them at its start, so they apply to exactly one turn and
/// then reset to the default; a caller that wants a run of chat turns re-sets
/// them each time.
@@ -60,17 +58,26 @@ pub struct TurnOverrides {
/// re-bound the in-memory history to a different chat sets this so a cleared
/// history is not silently repopulated from an unrelated thread's transcript
/// (opencompany #1725). Thread-correct resume via
- /// `Agent::seed_resume_from_thread_transcript` still works -- it seeds
- /// `cached_transcript_messages`, which this path never touches.
+ /// `OpenHumanSessionHost::seed_resume_from_thread_transcript` still works:
+ /// it seeds the runtime directly, rather than retaining a host cache.
pub suppress_transcript_autoload: bool,
}
/// An autonomous or semi-autonomous AI agent.
///
-/// The `Agent` is the central component that manages conversation state,
+/// The `OpenHumanSessionHost` is the central component that manages conversation state,
/// executes tools based on model requests, and interacts with the memory
/// system to maintain context across turns.
-pub struct Agent {
+pub struct OpenHumanSessionHost {
+ /// The sole live owner of model history, lossless transcript rows, prefix
+ /// stability and per-turn immutable tool snapshots. Constructed lazily
+ /// after the factory has installed hosted authority.
+ pub(super) runtime_session:
+ Option<tinyagents_runtime::Session<crate::agent::tinyagents::host::OpenHumanRunContext>>,
+ /// Host-only mutable preparation/finalization state shared with the
+ /// runtime hooks. It deliberately contains no generic session mechanics.
+ pub(super) runtime_state:
+ std::sync::Arc<std::sync::Mutex<super::runtime_session::OpenHumanSessionState>>,
/// The turn's model source — builds this agent's tiered crate `ChatModel`
/// set per turn (issue #4249, Phase 3 / Motion A). Replaces the raw
/// `Arc<dyn Provider>`; the harness names crate model types only.
@@ -114,7 +121,7 @@ pub struct Agent {
/// do not delegate.
pub(super) synthesized_tools: Arc<Vec<Box<dyn Tool>>>,
/// Full tool specs: [`Self::tools`]' specs first, then the synthesised
- /// half, which [`Agent::refresh_delegation_tools`] swaps in place.
+ /// half, which [`OpenHumanSessionHost::refresh_delegation_tools`] swaps in place.
///
/// The leaves are `Arc<ToolSpec>` and are **shared** with
/// [`Self::durable_tool_specs`] and [`Self::visible_tool_specs`]: all three
@@ -156,7 +163,7 @@ pub struct Agent {
/// embedders that bring their own `Memory`); the lane then stays silent.
pub(super) auto_recall: Option<Arc<crate::memory::auto_recall::AutoRecall>>,
// `Arc` (not `Box`) so the tinyagents turn path can hold a cheap clone of
- // the dispatcher without borrowing the `Agent` while session state mutates.
+ // the dispatcher without borrowing the `OpenHumanSessionHost` while session state mutates.
pub(super) tool_dispatcher: Arc<dyn ToolDialect>,
pub(super) config: crate::config::AgentConfig,
pub(super) model_name: String,
@@ -174,14 +181,13 @@ pub struct Agent {
/// `action_dir` cwd behaviour.
pub(super) workspace_descriptor: Option<tinytools::WorkspaceDescriptor>,
pub(super) workflows: Vec<crate::skills::Workflow>,
- /// Agent workflows discovered at session start.
+ /// OpenHumanSessionHost workflows discovered at session start.
pub(super) auto_save: bool,
/// Last memory context loaded for the current turn. Stored so it can
/// be forwarded to subagents via `ParentExecutionContext`.
pub(super) last_memory_context: Option<String>,
/// Citation metadata collected from memory recall for the most recent turn.
/// Consumed by web-channel delivery to render source chips in the UI.
- pub(super) last_turn_citations: Vec<crate::memory::agent::memory_loader::MemoryCitation>,
/// In-flight citation recall for the current turn.
///
/// Citations are UI-only — they render source chips and never enter the
@@ -194,13 +200,10 @@ pub struct Agent {
/// joined only when a consumer actually asks for the citations — which
/// happens after the turn returns. The contract is unchanged: callers still
/// get the citations for the turn they just ran.
- pub(super) pending_citations:
- Option<tokio::task::JoinHandle<Vec<crate::memory::agent::memory_loader::MemoryCitation>>>,
/// Holistic token/cost/context accounting for the most recent turn (parent +
/// any sub-agents spawned during it). Consumed by web-channel delivery to
/// surface session token/cost/context meters in the UI footer. `None` until
/// the first turn completes.
- pub(super) last_turn_usage_totals: Option<crate::agent::tinyagents::host::LastTurnUsage>,
/// Whether the most recent turn's tinyagents loop paused because it hit
/// `max_tool_iterations` (`TinyagentsTurnOutcome::hit_cap`), rather than
/// finishing naturally. `false` until the first turn completes, and reset
@@ -210,8 +213,6 @@ pub struct Agent {
/// distinguish "the agent paused mid-work" from "the agent asked a
/// question" or "the agent finished" — `run_single` only returns the
/// checkpoint/final text, with no other signal for which case occurred.
- pub(super) last_turn_hit_cap: bool,
- pub(super) history: Vec<ConversationMessage>,
pub(super) post_turn_hooks: Vec<Arc<dyn PostTurnHook>>,
pub(super) learning_enabled: bool,
/// When `true`, pinned preferences stored via `remember_preference` are
@@ -229,7 +230,7 @@ pub struct Agent {
/// transcript paths: `sessions/DDMMYYYY/{agent}_{index}.md`.
///
/// May be rewritten mid-session by
- /// [`Agent::set_agent_definition_name`] (e.g. the web channel
+ /// [`OpenHumanSessionHost::set_agent_definition_name`] (e.g. the web channel
/// stamps `"orchestrator_<short_thread>"` so each thread gets its
/// own transcript namespace). Anything that needs to resolve the
/// session back to its registry entry must use
@@ -246,36 +247,13 @@ pub struct Agent {
///
/// [`AgentDefinitionRegistry`]: crate::agent::harness::definition::AgentDefinitionRegistry
pub(super) agent_definition_id: String,
- /// Resolved filesystem path for this session's transcript file.
- /// Set on first write, reused for subsequent **appends** within the
- /// same session.
- pub(super) session_transcript_path: Option<PathBuf>,
- /// The transcript-write seam for this session, bound to the same file as
- /// `session_transcript_path` on first write.
- ///
- /// This is the S4 indirection: the turn path appends through
- /// [`TranscriptHistory::append_turn`][tinyagents_session::transcript::TranscriptHistory::append_turn]
- /// rather than calling the format's free function directly.
- ///
- /// It is `Arc<dyn …>` rather than the concrete handle so the turn loop is
- /// written against the seam instead of the implementation. It is now
- /// genuinely substitutable: the handle is produced by
- /// [`TranscriptLocator::open_stem`][tinyagents_session::transcript::TranscriptLocator::open_stem]
- /// on the locator in `session_history_locator`, so injecting a locator
- /// replaces this session's writes as well as both of its resume reads.
- ///
- /// `session_transcript_path` stays alongside it rather than being folded
- /// into the handle: the dual-write mirror needs the concrete `&Path` for
- /// `file_stem()`, and several tests assert on it directly.
- pub(super) session_history:
- Option<std::sync::Arc<dyn tinyagents_session::transcript::TranscriptHistory>>,
/// Injected transcript locator, or `None` to use real files.
///
/// The single injection point for the whole transcript seam: it resolves
/// both resume reads (`latest_for_agent`, `root_for_thread`) and binds this
/// session's write handle (`open_stem`). `None` is the production default
/// and is resolved *lazily* by
- /// [`Agent::session_locator`][Self::session_locator] into a
+ /// [`OpenHumanSessionHost::session_locator`][Self::session_locator] into a
/// [`FileTranscriptLocator`][tinyagents_session::transcript::FileTranscriptLocator]
/// over the **current** `workspace_dir` — never
/// captured at build time, because callers (tests especially) reassign
@@ -283,14 +261,6 @@ pub struct Agent {
/// reading the old directory.
pub(super) session_history_locator:
Option<std::sync::Arc<dyn tinyagents_session::transcript::TranscriptLocator>>,
- /// The logical message set most recently persisted to
- /// `session_transcript_path`, tracked in memory so the append-only writer
- /// can diff each turn's messages against it (pure extension → append tail;
- /// reduction → compaction record) without re-reading the growing file.
- /// Empty until the first persist. Each process writes its own transcript
- /// file, so this in-memory state is always aligned with the file it owns.
- pub(super) persisted_transcript_messages:
- Vec<tinyagents_session::transcript::TranscriptMessage>,
/// Unique transcript key for this session, formatted as
/// `"{unix_ts}_{agent_id}"`. Generated once at agent-build time so
/// every transcript write in this session uses the same filename
@@ -305,10 +275,6 @@ pub struct Agent {
/// `Some("1713000000_orchestrator/1713000123_planner")` so nested
/// delegations produce a tree on disk.
pub(super) session_parent_prefix: Option<String>,
- /// Messages loaded from a previous session transcript on resume.
- /// Consumed once (via `.take()`) on the first turn to provide a
- /// byte-identical prefix for KV cache reuse.
- pub(super) cached_transcript_messages: Option<Vec<ChatMessage>>,
/// Per-session [`ContextManager`] — owns the system-prompt
/// builder, the layered reduction pipeline (tool-result budget →
/// microcompact → autocompact signal → session-memory extraction
@@ -317,7 +283,9 @@ pub struct Agent {
/// Constructed once at session start so its budget counters and
/// session-memory deltas persist across turns. See
/// [`crate::agent::context`] for the full surface.
- pub(super) context: ContextManager,
+ /// Host-only context/prompt and session-memory bookkeeping shared by the
+ /// runtime hooks; it is never a duplicate conversation history.
+ pub(super) context: Arc<std::sync::Mutex<ContextManager>>,
/// Optional progress event sender for real-time turn progress.
/// When set, the turn loop emits [`AgentProgress`] events through
/// this channel so callers (e.g. web channel) can surface live
@@ -335,7 +303,7 @@ pub struct Agent {
/// Whether `connected_integrations` is an authoritative session-start
/// snapshot (prewarmed from the shared Composio cache or fetched
/// explicitly) versus the default empty placeholder installed by
- /// `AgentBuilder::build`. Turn 1 uses this to decide whether it must
+ /// `SessionHostBuilder::build`. Turn 1 uses this to decide whether it must
/// still pay the cold-start fetch cost before freezing the system prompt.
pub(super) connected_integrations_initialized: bool,
/// Full runtime config snapshot for integration-cache reads and the
@@ -349,7 +317,7 @@ pub struct Agent {
pub(super) hosted_base: Option<Arc<crate::agent::tinyagents::host::OpenHumanHostBase>>,
/// The definition this session was built from, when the factory had one.
///
- /// Read back through [`Agent::resolved_definition`] by the in-turn sites
+ /// Read back through [`OpenHumanSessionHost::resolved_definition`] by the in-turn sites
/// that need the definition's `sandbox_mode` or `subagents` — so an agent
/// built from an explicit definition (a library host's per-agent spec)
/// keeps those settings instead of having them silently replaced by
@@ -383,16 +351,16 @@ pub struct Agent {
/// default policy allows all calls so existing agents keep their
/// behaviour unless a caller opts into stricter policy.
pub(super) tool_policy: Arc<dyn ToolPolicy>,
- /// Hash of the Composio connection set this Agent last reconciled
+ /// Hash of the Composio connection set this OpenHumanSessionHost last reconciled
/// against. Compared at top-of-turn to a fresh hash computed from
/// [`crate::integrations::composio::cached_active_integrations`]; on
- /// diff, [`Agent::refresh_delegation_tools`] re-synthesises the
+ /// diff, [`OpenHumanSessionHost::refresh_delegation_tools`] re-synthesises the
/// `delegate_<toolkit>` surface to match the live connected set.
///
/// Initialised to `0` at construction. Turn 1's existing refresh
/// path (gated by `history.is_empty()`) writes the first real hash
- /// after [`Agent::fetch_connected_integrations`] populates
- /// [`Agent::connected_integrations`], so the per-turn check is
+ /// after [`OpenHumanSessionHost::fetch_connected_integrations`] populates
+ /// [`OpenHumanSessionHost::connected_integrations`], so the per-turn check is
/// dormant on session startup and only fires when integrations
/// actually change mid-conversation.
pub(super) last_seen_integrations_hash: u64,
@@ -463,19 +431,19 @@ pub struct Agent {
/// closest available signal to "session is ending") to finalize the
/// trailing open segment with an LLM recap + embedding.
pub(super) archivist_hook: Option<Arc<ArchivistHook>>,
- /// Names of every tool currently in [`Agent::synthesized_tools`] — those
+ /// Names of every tool currently in [`OpenHumanSessionHost::synthesized_tools`] — those
/// produced by [`crate::tools::orchestrator_tools::collect_orchestrator_tools`]
/// (i.e. `delegate_<toolkit>` skill tools and archetype-delegation
/// tools like `delegate_archivist`). Tracked so
- /// [`Agent::refresh_delegation_tools`] can drop the entire
- /// previously-synthesised subset of [`Agent::tool_specs`] on each refresh
+ /// [`OpenHumanSessionHost::refresh_delegation_tools`] can drop the entire
+ /// previously-synthesised subset of [`OpenHumanSessionHost::tool_specs`] on each refresh
/// and append the fresh set — without that mask we'd risk either leaking
/// stale `delegate_<toolkit>` specs on revoke or accidentally removing
/// direct tools (`query_memory`, `cron_add`, …) that share a name
/// prefix.
///
- /// Seeded by [`AgentBuilder::build`] from the set handed to
- /// [`AgentBuilder::synthesized_tools`], then replaced by
+ /// Seeded by [`SessionHostBuilder::build`] from the set handed to
+ /// [`SessionHostBuilder::synthesized_tools`], then replaced by
/// `refresh_delegation_tools` on every refresh.
///
/// Invariant: this set is the name mask for **both** [`Self::tool_specs`]'
@@ -484,22 +452,14 @@ pub struct Agent {
/// without the other — the schema and the executable instances cannot
/// drift (#6145).
pub(super) synthesized_tool_names: std::collections::HashSet<String>,
- /// Overrides applied to the **next** [`Agent::turn`] call, then reset.
- ///
- /// Defaults to [`TurnOverrides::default`] (no suppression), so an agent
- /// driven exactly as before is byte-for-byte unchanged. A caller sets this
- /// via [`Agent::set_next_turn_overrides`] immediately before dispatching a
- /// chat / small-talk turn; `turn()` takes it at the top so it applies to
- /// one turn only. See [`TurnOverrides`] for the motivating case (#1725).
- pub(super) pending_turn_overrides: TurnOverrides,
}
-/// A builder for creating `Agent` instances with custom configuration.
-pub struct AgentBuilder {
+/// A builder for creating `OpenHumanSessionHost` instances with custom configuration.
+pub struct SessionHostBuilder {
pub(super) turn_model_source: Option<TurnModelSource>,
pub(super) tools: Option<Vec<Box<dyn Tool>>>,
/// Delegation tools synthesised for the session's initial connection set.
- /// Held in [`Agent::synthesized_tools`], never inside [`Agent::tools`].
+ /// Held in [`OpenHumanSessionHost::synthesized_tools`], never inside [`OpenHumanSessionHost::tools`].
pub(super) synthesized_tools: Option<Vec<Box<dyn Tool>>>,
/// When set, restricts which tools the main agent sees/calls.
pub(super) visible_tool_names: Option<std::collections::HashSet<String>>,
@@ -507,13 +467,13 @@ pub struct AgentBuilder {
/// Channel-policy restrictions are intersected during [`Self::build`].
pub(super) subagent_tool_ceiling_names: Option<std::collections::HashSet<String>>,
pub(super) memory: Option<Arc<dyn Memory>>,
- /// Forwarded to [`Agent::auto_recall`] at build time. Defaults to `None`.
+ /// Forwarded to [`OpenHumanSessionHost::auto_recall`] at build time. Defaults to `None`.
pub(super) auto_recall: Option<Arc<crate::memory::auto_recall::AutoRecall>>,
pub(super) prompt_builder: Option<SystemPromptBuilder>,
pub(super) tool_dispatcher: Option<Box<dyn ToolDialect>>,
pub(super) config: Option<crate::config::AgentConfig>,
/// Optional [`ContextConfig`] override threaded through from
- /// `Agent::from_config`. When unset the builder falls back to
+ /// `OpenHumanSessionHost::from_config`. When unset the builder falls back to
/// [`crate::config::ContextConfig::default`].
pub(super) context_config: Option<crate::config::ContextConfig>,
pub(super) model_name: Option<String>,
@@ -522,11 +482,11 @@ pub struct AgentBuilder {
pub(super) temperature: Option<f64>,
pub(super) workspace_dir: Option<std::path::PathBuf>,
pub(super) action_dir: Option<std::path::PathBuf>,
- /// Optional turn workspace descriptor forwarded to [`Agent`] at build time.
+ /// Optional turn workspace descriptor forwarded to [`OpenHumanSessionHost`] at build time.
/// Defaults to `None` (shared `action_dir` cwd).
pub(super) workspace_descriptor: Option<tinytools::WorkspaceDescriptor>,
pub(super) workflows: Option<Vec<crate::skills::Workflow>>,
- /// Agent workflows to surface in the prompt. Populated from `load_workflows`
+ /// OpenHumanSessionHost workflows to surface in the prompt. Populated from `load_workflows`
/// at session start; defaults to empty when not explicitly set.
pub(super) auto_save: Option<bool>,
pub(super) post_turn_hooks: Vec<Arc<dyn PostTurnHook>>,
@@ -540,26 +500,26 @@ pub struct AgentBuilder {
/// flat in `session_raw/DDMMYYYY/{session_key}.jsonl`. Populated
/// by the sub-agent runner so nested delegations produce a tree.
pub(super) session_parent_prefix: Option<String>,
- /// Forwarded to [`Agent::session_history_locator`]. `None` (default) means
+ /// Forwarded to [`OpenHumanSessionHost::session_history_locator`]. `None` (default) means
/// real files; set it with
- /// [`with_session_history_locator`][super::builder::AgentBuilder::with_session_history_locator]
+ /// [`with_session_history_locator`][super::builder::SessionHostBuilder::with_session_history_locator]
/// to substitute the transcript backing store for the whole turn path.
pub(super) session_history_locator:
Option<std::sync::Arc<dyn tinyagents_session::transcript::TranscriptLocator>>,
- /// Forwarded to [`Agent::omit_profile`] at `build()` time. Mirrors the
+ /// Forwarded to [`OpenHumanSessionHost::omit_profile`] at `build()` time. Mirrors the
/// target definition's `omit_profile` flag; `None` means "fall back
/// to the safe default" (omit).
pub(super) omit_profile: Option<bool>,
- /// Forwarded to [`Agent::omit_memory_md`]. Same shape as
+ /// Forwarded to [`OpenHumanSessionHost::omit_memory_md`]. Same shape as
/// `omit_profile` — `None` falls back to the "omit" default.
pub(super) omit_memory_md: Option<bool>,
- /// Optional payload-summarizer threaded through to [`Agent`] at
+ /// Optional payload-summarizer threaded through to [`OpenHumanSessionHost`] at
/// build time. Defaults to `None`; the orchestrator branch in
- /// [`super::builder::Agent::build_session_agent_inner`] sets this
+ /// [`super::builder::OpenHumanSessionHost::build_session_agent_inner`] sets this
/// to a `SubagentPayloadSummarizer` instance.
pub(super) payload_summarizer:
Option<Arc<dyn crate::agent::tinyagents::payload_summarizer::PayloadSummarizer>>,
- /// Forwarded to [`Agent::trigger_memory_agent`] at build time.
+ /// Forwarded to [`OpenHumanSessionHost::trigger_memory_agent`] at build time.
pub(super) trigger_memory_agent: Option<TriggerMemoryAgent>,
/// Per-agent TokenJuice tool-output compression profile.
pub(super) tokenjuice_compression: crate::inference::tokenjuice::AgentTokenjuiceCompression,
@@ -571,12 +531,8 @@ pub struct AgentBuilder {
pub(super) archivist_hook: Option<Arc<ArchivistHook>>,
}
-impl Default for AgentBuilder {
+impl Default for SessionHostBuilder {
fn default() -> Self {
Self::new()
}
}
-
-#[cfg(test)]
-#[path = "types_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/agent/session_import/README.md b/crates/openhuman-core/src/agent/session_import/README.md
index 7e3d881ed4..318e45f149 100644
--- a/crates/openhuman-core/src/agent/session_import/README.md
+++ b/crates/openhuman-core/src/agent/session_import/README.md
@@ -79,7 +79,7 @@ in `crates/openhuman-core/src/core/all.rs`.
- `crates/openhuman-core/src/core/all.rs` — registers the controller.
- `tinyagents_session::transcript` — the legacy transcript readers
(`read_transcript`, `read_transcript_legacy_md`) the importer converts from.
-- `crates/openhuman-core/src/agent/harness/session/turn/session_io/transcript_persist.rs`
+- `crates/openhuman-core/src/agent/session_host/turn/session_io/transcript_persist.rs`
— calls `live::write_live_turn` after each transcript write and
`live::shadow_read_compare` after each transcript load, both on background tasks.
- `crates/openhuman-core/src/agent/tinyagents/turn_runner.rs` — registers
diff --git a/crates/openhuman-core/src/agent/task_dispatcher/executor.rs b/crates/openhuman-core/src/agent/task_dispatcher/executor.rs
index a1aafe7a9e..bbeafff879 100644
--- a/crates/openhuman-core/src/agent/task_dispatcher/executor.rs
+++ b/crates/openhuman-core/src/agent/task_dispatcher/executor.rs
@@ -10,8 +10,8 @@ use crate::agent::harness::definition::AgentDefinitionRegistry;
// Only read by the `skills`-gated workflow-resolution branch below.
#[cfg(feature = "skills")]
use crate::agent::harness::definition::PromptSource;
-use crate::agent::harness::session::Agent;
use crate::agent::harness::subagent_runner::with_autonomous_iter_cap;
+use crate::agent::session_host::OpenHumanSessionHost;
use crate::agent::task_session;
use crate::agent::todos::ops::{self, BoardLocation, CardPatch};
use crate::agent::todos::runs::{self, RunOutcome};
@@ -124,7 +124,7 @@ pub(super) async fn run_autonomous(
config.http_request.allowed_domains = vec!["*".to_string()];
}
- let mut agent = Agent::from_config_for_agent(&config, &executor.agent_id)
+ let mut agent = OpenHumanSessionHost::from_config_for_agent(&config, &executor.agent_id)
.map_err(|e| format!("build agent: {e:#}"))?;
// Issue #4868 — apply the autonomous task-run iteration budget AFTER
// construction. The session builder now stamps the resolved agent
diff --git a/crates/openhuman-core/src/agent/tinyagents/README.md b/crates/openhuman-core/src/agent/tinyagents/README.md
index 9220f55d53..3848a22876 100644
--- a/crates/openhuman-core/src/agent/tinyagents/README.md
+++ b/crates/openhuman-core/src/agent/tinyagents/README.md
@@ -85,10 +85,10 @@ Responses project the crate's own `AgentObservation` and `HarnessRunStatus` serd
## Used by
-- `agent/harness/session/turn/graph.rs`: the chat-turn route into `run_turn_via_tinyagents_shared`.
+- `agent/session_host/turn/graph.rs`: the chat-turn route into `run_turn_via_tinyagents_shared`.
- `agent/harness/graph.rs`: the channel/CLI bus turn route.
- `agent/harness/subagent_runner/ops/graph.rs`: the sub-agent spawn route. It and the session route both build their context-window summarizer through `TurnModelSource::build_summarizer`.
-- `agent/harness/session/builder/setters.rs`, `agent/harness/subagent_runner/ops/{provider,runner}.rs`, `channels/`: construct `TurnModelSource`.
+- `agent/session_host/builder/setters.rs`, `agent/harness/subagent_runner/ops/{provider,runner}.rs`, `channels/`: construct `TurnModelSource`.
- `agent/bus.rs`: reads `TinyagentsTurnOutcome::resolved_route` after a turn.
- `core/all.rs` (replay controllers) and `core/runtime/builder.rs` (`reaper::reap_orphaned_runs`).
- `agent/todos/`: `todos::*` stores.
diff --git a/crates/openhuman-core/src/agent/tinyagents/harness_context_ladder.rs b/crates/openhuman-core/src/agent/tinyagents/harness_context_ladder.rs
index 1612ad1336..f8abac4b39 100644
--- a/crates/openhuman-core/src/agent/tinyagents/harness_context_ladder.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/harness_context_ladder.rs
@@ -164,7 +164,7 @@ pub(super) fn install_context_ladder(
let wrap_up_mw = wrap_up_at_cap.then(|| {
Arc::new(middleware::FinalCallWrapUpMiddleware::new(
- crate::agent::harness::session::turn_checkpoint::MAX_ITER_CHECKPOINT_INSTRUCTION,
+ crate::agent::session_host::turn_checkpoint::MAX_ITER_CHECKPOINT_INSTRUCTION,
tool_outcome_sink.clone(),
// What is left after the contents list's share, so restoration
// stops short of provoking an eviction (see the middleware).
diff --git a/crates/openhuman-core/src/agent/tinyagents/host/context_composer.rs b/crates/openhuman-core/src/agent/tinyagents/host/context_composer.rs
index 568b982a58..52548b824c 100644
--- a/crates/openhuman-core/src/agent/tinyagents/host/context_composer.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/host/context_composer.rs
@@ -21,7 +21,7 @@
//! Prompt assembly is **not** reimplemented here. Everything this file does is
//! translate a [`TurnContextRequest`] into a `PromptContext` and hand it to the
//! existing `SystemPromptBuilder::with_defaults()` chain — the same chain
-//! `agent::harness::session::turn::context::build_system_prompt` uses. That
+//! `agent::session_host::turn::context::build_system_prompt` uses. That
//! keeps one source of truth for section ordering, the grounding contract, and
//! the global style suffix.
//!
@@ -114,7 +114,7 @@ pub struct OpenHumanContextComposer {
///
// TODO(phase4): this should be resolved per `req.thread_id` rather than
// snapshotted at construction. The real fetch lives in
- // `crate::agent::harness::session::turn::context` (see the
+ // `crate::agent::session_host::turn::context` (see the
// `LearnedContextData { … }` assembly around `sanitize_learned_entry` /
// `tree_root_summaries`), which reads the learning store and the memory
// tree summarizer. It is not a free function and is not thread-keyed
@@ -294,7 +294,7 @@ impl ContextComposer for OpenHumanContextComposer {
// from the profiles domain (`crate::profiles`); the
// existing main-agent path leaves this empty too (see the
// `personality_roster: vec![]` TODO in
- // `agent/harness/session/turn/context.rs`), so this matches
+ // `agent/session_host/turn/context.rs`), so this matches
// current behaviour rather than regressing it.
personality_roster: Vec::new(),
agents_md_global: agents_md.global,
diff --git a/crates/openhuman-core/src/agent/tinyagents/host/definition_registry.rs b/crates/openhuman-core/src/agent/tinyagents/host/definition_registry.rs
index b791d2b608..960408e12d 100644
--- a/crates/openhuman-core/src/agent/tinyagents/host/definition_registry.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/host/definition_registry.rs
@@ -41,7 +41,7 @@
//! **3. `ToolScope::Wildcard` has no crate representation.** The crate models
//! tools as an explicit `Vec<String>` in which **empty means unrestricted**,
//! matching the session builder ("an empty `visible` set means no filter" —
-//! `agent/harness/session/builder/factory.rs`). So an unrestricted wildcard
+//! `agent/session_host/builder/factory.rs`). So an unrestricted wildcard
//! agent maps to an empty `tools` vec.
//!
//! That one value must not be made to carry three meanings. Three distinct
@@ -205,7 +205,7 @@ impl OpenHumanDefinitionRegistry {
/// enabled custom-agent config fallback.
///
/// Mirrors the lookup order the agent factory uses
- /// (`agent/harness/session/builder/factory.rs` falls back to
+ /// (`agent/session_host/builder/factory.rs` falls back to
/// [`find_custom_in_config`] on a harness-registry miss). The disabled and
/// `Default`-source filters live inside [`find_custom_in_config`] and are
/// deliberately not re-implemented here.
@@ -416,12 +416,12 @@ fn model_for(spec: &ModelSpec) -> Option<String> {
/// Whether `name` is blocked by a definition's `disallowed_tools`.
///
/// Mirrors the private `definition_disallows_tool` in
-/// `agent/harness/session/builder/factory.rs`, including its trailing-`*`
+/// `agent/session_host/builder/factory.rs`, including its trailing-`*`
/// prefix-match form. Duplicated rather than imported because that helper is
/// module-private and Phase 4 must not edit existing files.
///
/// TODO(phase4): make `definition_disallows_tool` `pub(crate)` in
-/// `agent/harness/session/builder/factory.rs` and delete this copy, so the
+/// `agent/session_host/builder/factory.rs` and delete this copy, so the
/// denylist grammar has one implementation.
fn disallows_tool(disallowed: &[String], name: &str) -> bool {
disallowed.iter().any(|entry| {
diff --git a/crates/openhuman-core/src/agent/tinyagents/host/learning_sink.rs b/crates/openhuman-core/src/agent/tinyagents/host/learning_sink.rs
index a4d594bca5..21dfc76c52 100644
--- a/crates/openhuman-core/src/agent/tinyagents/host/learning_sink.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/host/learning_sink.rs
@@ -85,7 +85,7 @@ use crate::memory::Memory;
///
/// Holds the hook list rather than building it, because *which* hooks are
/// installed is a composition decision the session builder already makes (see
-/// `agent/harness/session/builder/factory.rs`); duplicating that policy here
+/// `agent/session_host/builder/factory.rs`); duplicating that policy here
/// would give the generic runtime a second, silently divergent hook set.
/// [`OpenHumanLearningSink::from_learning_config`] is a convenience for the
/// hooks that need nothing but config and memory.
diff --git a/crates/openhuman-core/src/agent/tinyagents/host/progress_sink.rs b/crates/openhuman-core/src/agent/tinyagents/host/progress_sink.rs
index c1e0de5607..c1cf3a6a81 100644
--- a/crates/openhuman-core/src/agent/tinyagents/host/progress_sink.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/host/progress_sink.rs
@@ -30,7 +30,7 @@
//!
//! So this sink writes `AgentProgress` into the same
//! `mpsc::Sender<AgentProgress>` the existing agent turn loop uses
-//! (`Agent::set_on_progress`), and the established bridge does the publishing.
+//! (`OpenHumanSessionHost::set_on_progress`), and the established bridge does the publishing.
//! `publish_web_channel_event` is still the terminal step — one hop further
//! down, where it already lives.
//!
@@ -156,7 +156,7 @@ struct OpenToolCall {
/// Forwards crate progress into an OpenHuman [`AgentProgress`] channel.
///
/// Construct one per turn with the same sender that would otherwise be handed
-/// to `Agent::set_on_progress`, so the existing
+/// to `OpenHumanSessionHost::set_on_progress`, so the existing
/// `web_chat::progress_bridge` consumer sees an identical event stream
/// regardless of which runtime produced it.
///
diff --git a/crates/openhuman-core/src/agent/tinyagents/host/run_context.rs b/crates/openhuman-core/src/agent/tinyagents/host/run_context.rs
index 296312762b..06b0c88c64 100644
--- a/crates/openhuman-core/src/agent/tinyagents/host/run_context.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/host/run_context.rs
@@ -23,6 +23,9 @@ use crate::agent::harness::tool_result_artifacts::ToolResultArtifactIndexStore;
use crate::agent::progress::AgentProgress;
use crate::agent::stop_hooks::StopHook;
use crate::agent::tinyagents::turn_outcome::ToolOutcomeSink;
+use crate::agent::tinyagents::{
+ TurnContextMiddleware, turn_outcome::ToolCallOutcome, turn_policy::ToolPolicyEnforcement,
+};
use crate::agent::turn_origin::AgentTurnOrigin;
use tinyinference_llm::model::ResolvedModelRoute;
@@ -46,6 +49,33 @@ pub struct LastTurnUsage {
pub subagents: Vec<SubagentUsageEntry>,
}
+/// Runtime-written sidecars for one OpenHuman session transition.
+///
+/// The host supplies this explicit sink in `before_turn`; the driver and its
+/// middleware fill it without mutating a second host history or transcript.
+/// `after_commit` reads it only after the runtime durable append succeeds.
+#[derive(Debug, Clone, Default)]
+pub(crate) struct SessionTurnSidecar {
+ pub model_calls: usize,
+ pub tool_calls: usize,
+ pub input_tokens: u64,
+ pub output_tokens: u64,
+ pub cached_input_tokens: u64,
+ pub cost_usd: f64,
+ /// The selected model's context window for this exact request. The
+ /// provider response's generic usage cannot represent this host datum.
+ pub context_window: u64,
+ /// Completed child runs observed before the root driver returned. This is
+ /// copied into the sidecar before transcript append so transcript billing
+ /// and the post-commit UI use the same complete ledger.
+ pub subagents: Vec<SubagentUsageEntry>,
+ pub duration: Option<Duration>,
+ pub tool_outcomes: Vec<ToolCallOutcome>,
+ pub hit_cap: bool,
+ pub wrap_up_injected: bool,
+ pub resolved_route: Option<ResolvedModelRoute>,
+}
+
/// Immutable inputs to the host's pre-dispatch policy.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct DispatchInputs {
@@ -206,6 +236,23 @@ pub struct OpenHumanRunContext {
pub workspace: Option<tinytools::WorkspaceDescriptor>,
/// Per-turn tool result capture shared with the event bridge.
pub(crate) tool_outcomes: Option<ToolOutcomeSink>,
+ /// Fail-closed OpenHuman tool-policy snapshot for this exact turn.
+ pub(crate) tool_policy: Option<ToolPolicyEnforcement>,
+ /// Exact executable durable tools selected by the host hook for this turn.
+ /// The driver must consume this request-scoped source rather than its
+ /// construction-time registry, so later visibility/revocation changes are
+ /// authoritative at execution as well as prompt rendering.
+ pub(crate) current_tools: Option<Arc<Vec<Box<dyn tinytools::Tool>>>>,
+ /// Exact executable dynamic/delegation tools selected with
+ /// [`Self::current_tools`] for this turn.
+ pub(crate) current_synthesized_tools: Option<Arc<Vec<Box<dyn tinytools::Tool>>>>,
+ /// Context middleware snapshot prepared for this exact turn.
+ pub(crate) context_middleware: Option<TurnContextMiddleware>,
+ /// Model/harness sidecars consumed only after a durable commit.
+ pub(crate) session_sidecar: Arc<Mutex<SessionTurnSidecar>>,
+ /// Required structured-output contract for this exact host turn. The
+ /// driver repairs it before returning a candidate to runtime validation.
+ pub(crate) required_output: Option<tinyagents_harness::config::RequiredOutput>,
}
impl Default for OpenHumanRunContext {
@@ -238,6 +285,12 @@ impl OpenHumanRunContext {
thread_id: None,
workspace: None,
tool_outcomes: None,
+ tool_policy: None,
+ current_tools: None,
+ current_synthesized_tools: None,
+ context_middleware: None,
+ session_sidecar: Arc::new(Mutex::new(SessionTurnSidecar::default())),
+ required_output: None,
}
}
diff --git a/crates/openhuman-core/src/agent/tinyagents/host/run_context_tests.rs b/crates/openhuman-core/src/agent/tinyagents/host/run_context_tests.rs
index f3ad02744d..abf28fbfb9 100644
--- a/crates/openhuman-core/src/agent/tinyagents/host/run_context_tests.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/host/run_context_tests.rs
@@ -34,16 +34,20 @@ fn child_inherits_tree_handles_but_isolates_observations_and_usage() {
assert_eq!(child.spawn_depth, 1);
assert_eq!(child.thread_id.as_deref(), Some("thread-a"));
assert!(child.file_state_agent_id().is_none());
- assert!(child
- .resolved_route
- .lock()
- .expect("child route lock")
- .is_none());
- assert!(child
- .subagent_usage
- .lock()
- .expect("child usage lock")
- .is_empty());
+ assert!(
+ child
+ .resolved_route
+ .lock()
+ .expect("child route lock")
+ .is_none()
+ );
+ assert!(
+ child
+ .subagent_usage
+ .lock()
+ .expect("child usage lock")
+ .is_empty()
+ );
parent.cancellation.cancel();
assert!(child.cancellation.is_cancelled());
diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware/final_call_wrap_up.rs b/crates/openhuman-core/src/agent/tinyagents/middleware/final_call_wrap_up.rs
index fd2d46cfec..c9cb2d8282 100644
--- a/crates/openhuman-core/src/agent/tinyagents/middleware/final_call_wrap_up.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/middleware/final_call_wrap_up.rs
@@ -22,7 +22,7 @@ use super::message_trim::{estimate_message_tokens, estimate_text_tokens};
/// # Why the loop and not afterwards
///
/// A capped turn used to end like this: the loop exits on the model-call cap,
-/// and `Agent::summarize_turn_wrapup` then dispatches a second, out-of-band
+/// and `OpenHumanSessionHost::summarize_turn_wrapup` then dispatches a second, out-of-band
/// request straight at the `ChatModel` asking for a checkpoint. Being outside
/// the harness, that request ran with **none** of the loop's context
/// management — no microcompact, no compression, no trim — while being built
diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware/tool_outcome_capture.rs b/crates/openhuman-core/src/agent/tinyagents/middleware/tool_outcome_capture.rs
index 7cdae1eb0a..4e5b88d17a 100644
--- a/crates/openhuman-core/src/agent/tinyagents/middleware/tool_outcome_capture.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/middleware/tool_outcome_capture.rs
@@ -26,6 +26,14 @@ pub(crate) struct ToolOutcomeCaptureMiddleware {
/// 1.6 owns the raw outcome fields; the host still adds classified failure
/// metadata for the UI.
failure_map: crate::agent::tinyagents::observability::ToolFailureMap,
+ /// Invocation start + the original structured arguments. `after_tool`
+ /// receives only an identity/result pair, so preserve both facts at the
+ /// boundary where TinyTools still exposes the full call.
+ started: std::sync::Arc<
+ std::sync::Mutex<
+ std::collections::HashMap<String, (std::time::Instant, serde_json::Value)>,
+ >,
+ >,
}
impl ToolOutcomeCaptureMiddleware {
@@ -33,7 +41,11 @@ impl ToolOutcomeCaptureMiddleware {
sink: crate::agent::tinyagents::ToolOutcomeSink,
failure_map: crate::agent::tinyagents::observability::ToolFailureMap,
) -> Self {
- Self { sink, failure_map }
+ Self {
+ sink,
+ failure_map,
+ started: Default::default(),
+ }
}
}
@@ -45,6 +57,21 @@ impl Middleware<(), crate::agent::tinyagents::host::OpenHumanRunContext>
"tool_outcome_capture"
}
+ async fn before_tool(
+ &self,
+ _ctx: &mut RunContext<crate::agent::tinyagents::host::OpenHumanRunContext>,
+ _state: &(),
+ call: &mut tinyinference_llm::tool::ToolCall,
+ ) -> TaResult<()> {
+ if let Ok(mut started) = self.started.lock() {
+ started.insert(
+ call.id.to_string(),
+ (std::time::Instant::now(), call.arguments.clone()),
+ );
+ }
+ Ok(())
+ }
+
async fn after_tool(
&self,
_ctx: &mut RunContext<crate::agent::tinyagents::host::OpenHumanRunContext>,
@@ -54,6 +81,18 @@ impl Middleware<(), crate::agent::tinyagents::host::OpenHumanRunContext>
) -> TaResult<()> {
let tool_name = invocation.tool_name();
let call_id = invocation.call_id().to_string();
+ let (duration_ms, arguments) = self
+ .started
+ .lock()
+ .ok()
+ .and_then(|mut started| started.remove(&call_id))
+ .map(|(started, arguments)| {
+ (
+ started.elapsed().as_millis().min(u128::from(u64::MAX)) as u64,
+ arguments,
+ )
+ })
+ .unwrap_or_default();
// Enrich a raw security-policy / autonomy block (issue #4094): the ~20
// `[policy-blocked]` denials emitted deep in `SecurityPolicy` / the tools
// return a bare marker line with no workaround and no relay directive, so
@@ -101,7 +140,7 @@ impl Middleware<(), crate::agent::tinyagents::host::OpenHumanRunContext>
(
success,
failure,
- 0,
+ duration_ms,
crate::agent::tinyagents::middleware::tool_result_text(result)
.chars()
.count(),
@@ -112,8 +151,10 @@ impl Middleware<(), crate::agent::tinyagents::host::OpenHumanRunContext>
sink.push(crate::agent::tinyagents::ToolCallOutcome {
call_id,
name: tool_name.to_string(),
+ arguments,
success,
content: crate::agent::tinyagents::middleware::tool_result_text(result),
+ duration_ms,
});
}
Ok(())
@@ -139,6 +180,16 @@ mod tests {
let middleware = ToolOutcomeCaptureMiddleware::new(sink.clone(), failure_map.clone());
let mut ctx = context();
+ let mut success_call = tinyinference_llm::tool::ToolCall {
+ id: "echo-success".into(),
+ name: "echo".into(),
+ arguments: serde_json::json!({"message": "hello"}),
+ invalid: None,
+ };
+ middleware
+ .before_tool(&mut ctx, &(), &mut success_call)
+ .await
+ .expect("start metadata is captured");
let success = ToolInvocationIdentity::new("echo-success", "echo");
let mut success_result = TaToolResult::success("done");
middleware
@@ -146,6 +197,16 @@ mod tests {
.await
.expect("successful result is captured");
+ let mut failure_call = tinyinference_llm::tool::ToolCall {
+ id: "echo-failure".into(),
+ name: "echo".into(),
+ arguments: serde_json::json!({"message": "retry"}),
+ invalid: None,
+ };
+ middleware
+ .before_tool(&mut ctx, &(), &mut failure_call)
+ .await
+ .expect("start metadata is captured");
let failure = ToolInvocationIdentity::new("echo-failure", "echo");
let mut failure_result = TaToolResult::error("request timed out");
middleware
@@ -157,8 +218,16 @@ mod tests {
assert_eq!(outcomes.len(), 2);
assert_eq!(outcomes[0].call_id, "echo-success");
assert!(outcomes[0].success);
+ assert_eq!(
+ outcomes[0].arguments,
+ serde_json::json!({"message": "hello"})
+ );
assert_eq!(outcomes[1].call_id, "echo-failure");
assert!(!outcomes[1].success);
+ assert_eq!(
+ outcomes[1].arguments,
+ serde_json::json!({"message": "retry"})
+ );
drop(outcomes);
let recorded = failure_map.lock().expect("failure lookup");
diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware/turn_context.rs b/crates/openhuman-core/src/agent/tinyagents/middleware/turn_context.rs
index 4773180bc8..06dded60ce 100644
--- a/crates/openhuman-core/src/agent/tinyagents/middleware/turn_context.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/middleware/turn_context.rs
@@ -4,6 +4,7 @@
use std::collections::HashMap;
use std::sync::Arc;
+use std::time::Instant;
use async_trait::async_trait;
@@ -12,11 +13,12 @@ use tinyagents_harness::error::Result as TaResult;
use tinyagents_harness::middleware::{Middleware, ToolInvocationIdentity};
use tinyagents_harness::runtime::AgentHarness;
use tinyinference_llm::message::Message;
-use tinyinference_llm::model::{ModelRequest, ModelResponse};
+use tinyinference_llm::model::{ModelRequest, ModelResponse, ResolvedModelRoute};
use tinytools::{ToolPolicy as TaToolPolicy, ToolResult as TaToolResult};
use crate::agent::harness::tool_result_artifacts::ToolResultArtifactStore;
use crate::agent::tinyagents::payload_summarizer::PayloadSummarizer;
+use crate::agent::tinyagents::turn_outcome::ToolCallOutcome;
use crate::inference::tokenjuice::AgentTokenjuiceCompression;
use super::tool_output::ToolOutputMiddleware;
@@ -92,9 +94,22 @@ pub(crate) struct TranscriptSnapshot {
pub(crate) input_tokens: u64,
pub(crate) output_tokens: u64,
pub(crate) cached_input_tokens: u64,
+ /// Provider-reported cost where available, otherwise the host's per-call
+ /// estimate. This covers only model calls the provider answered.
+ pub(crate) charged_amount_usd: f64,
+ /// The last accepted model route. A failed follow-up has no response of
+ /// its own, so this remains the route that incurred the snapshot usage.
+ pub(crate) resolved_route: Option<ResolvedModelRoute>,
+ /// Driver-selected model used only when a provider response has no route
+ /// metadata. The driver fills this even when the hook seeded the snapshot.
+ pub(crate) pricing_model: Option<String>,
/// Model calls the provider answered, so a failed run reports its real
/// iteration count rather than one derived from message counts.
pub(crate) model_calls: u32,
+ /// Completed tool calls observed before the failure. Unlike the transcript
+ /// `Message::Tool` row, these retain the result error flag, structured
+ /// arguments, and elapsed time required by the post-commit sidecar.
+ pub(crate) tool_outcomes: Vec<ToolCallOutcome>,
}
/// Display cap for one unanswered step in a failure note, matching the cap
@@ -160,6 +175,11 @@ pub(crate) type TranscriptSnapshotSink = Arc<std::sync::Mutex<TranscriptSnapshot
/// failure.
pub(crate) struct TranscriptSnapshotMiddleware {
sink: TranscriptSnapshotSink,
+ /// `after_tool` receives no structured arguments or start time. Keep both
+ /// while the harness still exposes the concrete call so an erroring run can
+ /// hand the same honest tool result to the durable partial append as a
+ /// completed run does.
+ started: Arc<std::sync::Mutex<HashMap<String, (Instant, serde_json::Value)>>>,
}
#[async_trait]
@@ -170,6 +190,21 @@ impl Middleware<(), crate::agent::tinyagents::host::OpenHumanRunContext>
"openhuman.transcript_snapshot"
}
+ async fn before_tool(
+ &self,
+ _ctx: &mut RunContext<crate::agent::tinyagents::host::OpenHumanRunContext>,
+ _state: &(),
+ call: &mut tinyinference_llm::tool::ToolCall,
+ ) -> TaResult<()> {
+ if let Ok(mut started) = self.started.lock() {
+ started.insert(
+ call.id.to_string(),
+ (Instant::now(), call.arguments.clone()),
+ );
+ }
+ Ok(())
+ }
+
async fn after_tool(
&self,
_ctx: &mut RunContext<crate::agent::tinyagents::host::OpenHumanRunContext>,
@@ -179,11 +214,32 @@ impl Middleware<(), crate::agent::tinyagents::host::OpenHumanRunContext>
) -> TaResult<()> {
// A tool result reaches a provider only with the next request, so it
// also sits past `accepted_len` until that request is answered.
+ let call_id = invocation.call_id().to_string();
+ let (duration_ms, arguments) = self
+ .started
+ .lock()
+ .ok()
+ .and_then(|mut started| started.remove(&call_id))
+ .map(|(started, arguments)| {
+ (
+ started.elapsed().as_millis().min(u128::from(u64::MAX)) as u64,
+ arguments,
+ )
+ })
+ .unwrap_or_default();
+ let content = crate::agent::tinyagents::middleware::tool_result_text(result);
if let Ok(mut guard) = self.sink.lock() {
- guard.messages.push(Message::tool(
- invocation.call_id().to_string(),
- crate::agent::tinyagents::middleware::tool_result_text(result),
- ));
+ guard
+ .messages
+ .push(Message::tool(call_id.clone(), content.clone()));
+ guard.tool_outcomes.push(ToolCallOutcome {
+ call_id,
+ name: invocation.tool_name().to_string(),
+ arguments,
+ success: !result.is_error,
+ content,
+ duration_ms,
+ });
}
Ok(())
}
@@ -202,10 +258,21 @@ impl Middleware<(), crate::agent::tinyagents::host::OpenHumanRunContext>
async fn after_model(
&self,
- _ctx: &mut RunContext<crate::agent::tinyagents::host::OpenHumanRunContext>,
+ ctx: &mut RunContext<crate::agent::tinyagents::host::OpenHumanRunContext>,
_state: &(),
response: &mut ModelResponse,
) -> TaResult<()> {
+ // The model middleware records this same route in the host context.
+ // Prefer response metadata because it is the exact accepted call; the
+ // context slot is the compatibility seam for a model wrapper that only
+ // exposes its route there.
+ let route = response.resolved_route.clone().or_else(|| {
+ ctx.data
+ .resolved_route
+ .lock()
+ .unwrap_or_else(|poisoned| poisoned.into_inner())
+ .clone()
+ });
if let Ok(mut guard) = self.sink.lock() {
guard.accepted_len = guard.messages.len();
guard.model_calls += 1;
@@ -224,6 +291,36 @@ impl Middleware<(), crate::agent::tinyagents::host::OpenHumanRunContext>
guard.input_tokens += usage.input_tokens;
guard.output_tokens += usage.output_tokens;
guard.cached_input_tokens += usage.cache_read_tokens;
+ let host_usage =
+ crate::agent::tinyagents::model::usage_info_from_response(response)
+ .unwrap_or_else(|| crate::inference::provider::UsageInfo {
+ input_tokens: usage.input_tokens,
+ output_tokens: usage.output_tokens,
+ context_window: 0,
+ cached_input_tokens: usage.cache_read_tokens,
+ cache_creation_tokens: usage.cache_creation_tokens,
+ reasoning_tokens: usage.reasoning_tokens,
+ charged_amount_usd: 0.0,
+ });
+ // Use the host's per-call pricing helper whenever the provider
+ // omitted an authoritative amount. `route` is preferred over a
+ // construction-time model because it preserves fallback pricing.
+ let cost_model = route
+ .as_ref()
+ .map(|route| {
+ if route.route.trim().is_empty() {
+ route.model.as_str()
+ } else {
+ route.route.as_str()
+ }
+ })
+ .or(guard.pricing_model.as_deref())
+ .unwrap_or_default();
+ guard.charged_amount_usd +=
+ crate::agent::cost::call_cost_usd(cost_model, &host_usage);
+ }
+ if route.is_some() {
+ guard.resolved_route = route;
}
}
Ok(())
@@ -285,7 +382,10 @@ impl TurnContextMiddleware {
// before microcompact/summarization rewrite it — the caller's error path
// persists exactly what the model was about to see.
if let Some(sink) = self.transcript_snapshot {
- harness.push_middleware(Arc::new(TranscriptSnapshotMiddleware { sink }));
+ harness.push_middleware(Arc::new(TranscriptSnapshotMiddleware {
+ sink,
+ started: Default::default(),
+ }));
}
// Microcompact is NOT registered here any more (issue #6014). It used to
// be, which put its `before_model` ahead of the summarization step the
@@ -422,3 +522,54 @@ impl Middleware<(), crate::agent::tinyagents::host::OpenHumanRunContext> for Han
Ok(())
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use tinyagents_harness::context::RunConfig;
+
+ #[tokio::test]
+ async fn transcript_snapshot_keeps_a_completed_failed_tool_row() {
+ let sink = Arc::new(std::sync::Mutex::new(TranscriptSnapshot::default()));
+ let middleware = TranscriptSnapshotMiddleware {
+ sink: sink.clone(),
+ started: Default::default(),
+ };
+ let mut context = RunContext::new(
+ RunConfig::new("snapshot-tool-outcome"),
+ crate::agent::tinyagents::host::OpenHumanRunContext::new(),
+ );
+ let mut call = tinyinference_llm::tool::ToolCall {
+ id: "failed-call".into(),
+ name: "write_file".into(),
+ arguments: serde_json::json!({"path": "blocked.txt"}),
+ invalid: None,
+ };
+ middleware
+ .before_tool(&mut context, &(), &mut call)
+ .await
+ .expect("snapshot accepts tool start");
+ let invocation = ToolInvocationIdentity::new("failed-call", "write_file");
+ let mut result = TaToolResult::error("permission denied");
+ middleware
+ .after_tool(&mut context, &(), &invocation, &mut result)
+ .await
+ .expect("snapshot accepts tool completion");
+
+ let snapshot = sink.lock().expect("snapshot");
+ assert_eq!(
+ snapshot.messages,
+ vec![Message::tool("failed-call", "permission denied")]
+ );
+ assert_eq!(snapshot.tool_outcomes.len(), 1);
+ let outcome = &snapshot.tool_outcomes[0];
+ assert_eq!(outcome.call_id, "failed-call");
+ assert_eq!(outcome.name, "write_file");
+ assert_eq!(
+ outcome.arguments,
+ serde_json::json!({"path": "blocked.txt"})
+ );
+ assert!(!outcome.success);
+ assert_eq!(outcome.content, "permission denied");
+ }
+}
diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware_wrap_up_toc_tests.rs b/crates/openhuman-core/src/agent/tinyagents/middleware_wrap_up_toc_tests.rs
index 7bef51b4a9..daff548b96 100644
--- a/crates/openhuman-core/src/agent/tinyagents/middleware_wrap_up_toc_tests.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/middleware_wrap_up_toc_tests.rs
@@ -140,8 +140,10 @@ fn sink_with(entries: &[(&str, &str)]) -> crate::agent::tinyagents::ToolOutcomeS
.map(|(id, content)| crate::agent::tinyagents::ToolCallOutcome {
call_id: (*id).to_string(),
name: "fetch".to_string(),
+ arguments: serde_json::Value::Null,
success: true,
content: (*content).to_string(),
+ duration_ms: 0,
})
.collect(),
))
diff --git a/crates/openhuman-core/src/agent/tinyagents/observability/event_projection.rs b/crates/openhuman-core/src/agent/tinyagents/observability/event_projection.rs
index 73d0c1ac92..fd30c78695 100644
--- a/crates/openhuman-core/src/agent/tinyagents/observability/event_projection.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/observability/event_projection.rs
@@ -245,8 +245,8 @@ impl EventListener for OpenhumanEventBridge {
// command (issue #4249, 07.3). A rejected command means the run's
// `SteeringPolicy` refused the kind and the crate is aborting the
// run with `TinyAgentsError::Steering`, so surface it louder. The
- // bespoke ack plumbing in `harness/run_queue/` stays live (gated:
- // web-channel followup/parallel still need a local owner); UI
+ // web-channel queue routing stays host-owned (gated: followup /
+ // parallel still need a local owner); UI
// projection of this event remains pending.
if *accepted {
tracing::debug!(
diff --git a/crates/openhuman-core/src/agent/tinyagents/payload_summarizer.rs b/crates/openhuman-core/src/agent/tinyagents/payload_summarizer.rs
index d5d435bcdc..c013e440c8 100644
--- a/crates/openhuman-core/src/agent/tinyagents/payload_summarizer.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/payload_summarizer.rs
@@ -46,7 +46,7 @@
//! ## Scope
//!
//! Only the orchestrator session gets a `PayloadSummarizer` wired in
-//! ([`crate::agent::harness::session::builder::AgentBuilder`]
+//! ([`crate::agent::session_host::builder::AgentBuilder`]
//! checks `agent_id == "orchestrator"`). Welcome, integrations_agent,
//! researcher, planner, archivist, and every other typed sub-agent get
//! `None` and their tool results are untouched. The summarizer itself
diff --git a/crates/openhuman-core/src/agent/tinyagents/steering_forwarder.rs b/crates/openhuman-core/src/agent/tinyagents/steering_forwarder.rs
index 0ac3175938..0825d84395 100644
--- a/crates/openhuman-core/src/agent/tinyagents/steering_forwarder.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/steering_forwarder.rs
@@ -24,8 +24,8 @@
//! is held across the drive future, cleanup happens identically on normal
//! return, error, and drop-cancellation.
-use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
+use std::sync::Arc;
use std::time::Duration;
use tinyagents_harness::ids::TaskId;
diff --git a/crates/openhuman-core/src/agent/tinyagents/turn_models.rs b/crates/openhuman-core/src/agent/tinyagents/turn_models.rs
index bfb820b11f..1273cc706b 100644
--- a/crates/openhuman-core/src/agent/tinyagents/turn_models.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/turn_models.rs
@@ -272,7 +272,7 @@ fn build_turn_models_crate(
/// agent harness holds instead of a provider-specific client (issue #4249, Phase 3
/// / Motion A).
///
-/// An [`Agent`](crate::agent::Agent) (and each channel/subagent turn
+/// An [`Agent`](crate::agent::OpenHumanSessionHost) (and each channel/subagent turn
/// request) is model-agnostic: it holds this source and builds a *tiered* crate
/// [`ChatModel`] set (primary + workload-tier fallback routes + summarizer) per
/// turn. Production sources retain only crate-native role/config metadata;
diff --git a/crates/openhuman-core/src/agent/tinyagents/turn_outcome.rs b/crates/openhuman-core/src/agent/tinyagents/turn_outcome.rs
index 31ed67f85c..da12297003 100644
--- a/crates/openhuman-core/src/agent/tinyagents/turn_outcome.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/turn_outcome.rs
@@ -80,8 +80,15 @@ pub(crate) struct TinyagentsTurnOutcome {
pub(crate) struct ToolCallOutcome {
pub call_id: String,
pub name: String,
+ /// The exact structured arguments supplied for this invocation. They are
+ /// captured at `before_tool`, while the native `ToolCall` is still
+ /// available, so post-commit hooks and transcript usage never have to
+ /// reconstruct arguments from provider prose.
+ pub arguments: serde_json::Value,
pub success: bool,
pub content: String,
+ /// Measured wall-clock runtime for this concrete tool invocation.
+ pub duration_ms: u64,
}
/// Shared sink the [`ToolOutcomeCaptureMiddleware`](super::middleware::ToolOutcomeCaptureMiddleware)
diff --git a/crates/openhuman-core/src/agent/triage/evaluator/arm.rs b/crates/openhuman-core/src/agent/triage/evaluator/arm.rs
index 5356c7c791..e230c090ac 100644
--- a/crates/openhuman-core/src/agent/triage/evaluator/arm.rs
+++ b/crates/openhuman-core/src/agent/triage/evaluator/arm.rs
@@ -47,7 +47,7 @@ pub(crate) enum ArmError {
/// action (top up) to fix it, so it must not page Sentry.
BudgetExhausted(anyhow::Error),
/// Our prompt-injection guard (`agent::bus`'s `enforce_prompt_input`,
- /// also used by `agent::harness::session::runtime`) flagged the
+ /// also used by `agent::session_host::runtime`) flagged the
/// incoming content as adversarial / unsafe and refused to dispatch
/// the turn. The guard runs *before* either model is contacted, so
/// trying the same prompt again — on cloud or local — produces the
@@ -263,7 +263,7 @@ pub(crate) fn classify_error(message: String) -> ArmError {
/// - `crates/openhuman-core/src/agent/bus.rs` — `Blocked` / `ReviewBlocked` arms of the
/// `enforce_prompt_input` decision (the path the triage evaluator hits via
/// `agent.run_turn`).
-/// - `crates/openhuman-core/src/agent/harness/session/runtime.rs` — same strings in the
+/// - `crates/openhuman-core/src/agent/session_host/runtime.rs` — same strings in the
/// tool-call loop, kept identical so this classifier covers both.
/// - `crates/openhuman-core/src/inference/local/ops.rs` — user-facing variants with the
/// `"Please rephrase clearly."` suffix; we match the leading phrase so
diff --git a/crates/openhuman-core/src/agent/triage/evaluator_fallback_chain_tests.rs b/crates/openhuman-core/src/agent/triage/evaluator_fallback_chain_tests.rs
index 114b502a7d..772ea075b3 100644
--- a/crates/openhuman-core/src/agent/triage/evaluator_fallback_chain_tests.rs
+++ b/crates/openhuman-core/src/agent/triage/evaluator_fallback_chain_tests.rs
@@ -168,7 +168,7 @@ fn classify_string_recognises_top_up_and_out_of_credits_as_budget_exhausted() {
fn classify_string_recognises_prompt_guard_rejection_as_safety_flagged() {
// OPENHUMAN-TAURI-X regression: the exact phrase our prompt-injection
// guard emits from `agent::bus::enforce_prompt_input` /
- // `agent::harness::session::runtime` when it refuses to dispatch a
+ // `agent::session_host::runtime` when it refuses to dispatch a
// turn. Was previously classified as Fatal, which paged Sentry for
// every adversarial Gmail message the triage agent saw.
for raw in [
diff --git a/crates/openhuman-core/src/agent/turn_workspace.rs b/crates/openhuman-core/src/agent/turn_workspace.rs
index c82a42f694..f87b2e5a95 100644
--- a/crates/openhuman-core/src/agent/turn_workspace.rs
+++ b/crates/openhuman-core/src/agent/turn_workspace.rs
@@ -16,7 +16,7 @@
//! a turn may work:
//!
//! * the session builder
-//! ([`Agent::from_config`](crate::agent::Agent::from_config)),
+//! ([`OpenHumanSessionHost::from_config`](crate::agent::OpenHumanSessionHost::from_config)),
//! which turns it into the turn's
//! [`WorkspaceDescriptor`](tinyagents_harness::workspace::WorkspaceDescriptor)
//! so acting tools (shell, file, git) resolve their default cwd there; and
diff --git a/crates/openhuman-core/src/bin/library_profile/scenarios/agent_turn.rs b/crates/openhuman-core/src/bin/library_profile/scenarios/agent_turn.rs
index be1cce5a70..27cd07fcb5 100644
--- a/crates/openhuman-core/src/bin/library_profile/scenarios/agent_turn.rs
+++ b/crates/openhuman-core/src/bin/library_profile/scenarios/agent_turn.rs
@@ -4,7 +4,7 @@
use anyhow::Result;
use openhuman_core::agent::harness::AgentDefinitionRegistry;
-use openhuman_core::agent::Agent;
+use openhuman_core::agent::OpenHumanSessionHost;
use openhuman_core::inference::provider::factory::test_provider_override;
use crate::harness::{fixture, measure, ProfileResult};
@@ -20,7 +20,8 @@ pub async fn run() -> Result<ProfileResult> {
eprintln!("[library-profile] agent-turn: registries ready, mock installed");
measure("agent-turn", 1, None, |_rec| async {
- let mut agent = Agent::from_config_for_agent(&fixture.config, "subconscious")?;
+ let mut agent =
+ OpenHumanSessionHost::from_config_for_agent(&fixture.config, "subconscious")?;
let reply = agent
.run_single("Give me a one-line status on the Phoenix migration.")
.await?;
diff --git a/crates/openhuman-core/src/bin/library_profile/scenarios/fleet.rs b/crates/openhuman-core/src/bin/library_profile/scenarios/fleet.rs
index e3484fce48..e8508acf27 100644
--- a/crates/openhuman-core/src/bin/library_profile/scenarios/fleet.rs
+++ b/crates/openhuman-core/src/bin/library_profile/scenarios/fleet.rs
@@ -20,7 +20,7 @@ use std::time::{Duration, Instant};
use anyhow::Result;
use openhuman_core::agent::harness::AgentDefinitionRegistry;
-use openhuman_core::agent::Agent;
+use openhuman_core::agent::OpenHumanSessionHost;
use openhuman_core::inference::provider::factory::test_provider_override;
use openhuman_core::platform::proc_metrics;
@@ -112,11 +112,11 @@ fn build_agents(
config: &openhuman_core::config::Config,
n: usize,
rec: &Recorder,
-) -> Result<Vec<Agent>> {
+) -> Result<Vec<OpenHumanSessionHost>> {
let stride = (n / 10).max(1);
let mut agents = Vec::with_capacity(n);
for i in 0..n {
- match Agent::from_config_for_agent(config, FLEET_AGENT_ID) {
+ match OpenHumanSessionHost::from_config_for_agent(config, FLEET_AGENT_ID) {
Ok(agent) => agents.push(agent),
Err(err) => {
eprintln!(
diff --git a/crates/openhuman-core/src/bin/library_profile/scenarios/long_agent.rs b/crates/openhuman-core/src/bin/library_profile/scenarios/long_agent.rs
index 520ecaac01..30614f10a1 100644
--- a/crates/openhuman-core/src/bin/library_profile/scenarios/long_agent.rs
+++ b/crates/openhuman-core/src/bin/library_profile/scenarios/long_agent.rs
@@ -5,7 +5,7 @@
use anyhow::Result;
use openhuman_core::agent::harness::AgentDefinitionRegistry;
-use openhuman_core::agent::Agent;
+use openhuman_core::agent::OpenHumanSessionHost;
use openhuman_core::inference::provider::factory::test_provider_override;
use crate::harness::{fixture, measure, ProfileResult};
@@ -35,7 +35,7 @@ pub async fn run() -> Result<ProfileResult> {
let mock = PlainTextMock::new("Phoenix migration is healthy; no action needed.");
let _provider = test_provider_override::install_model(mock.clone());
- let mut agent = Agent::from_config_for_agent(&fixture.config, "subconscious")?;
+ let mut agent = OpenHumanSessionHost::from_config_for_agent(&fixture.config, "subconscious")?;
eprintln!("[library-profile] long-agent: warming agent with one pre-measure turn");
let warm = agent.run_single("Warm-up: confirm you are ready.").await?;
anyhow::ensure!(!warm.trim().is_empty(), "empty warm-up reply");
diff --git a/crates/openhuman-core/src/bin/library_profile/scenarios/skill_run.rs b/crates/openhuman-core/src/bin/library_profile/scenarios/skill_run.rs
index 5130e9e6b3..6d64232d3d 100644
--- a/crates/openhuman-core/src/bin/library_profile/scenarios/skill_run.rs
+++ b/crates/openhuman-core/src/bin/library_profile/scenarios/skill_run.rs
@@ -42,7 +42,7 @@
use anyhow::{Context, Result};
use openhuman_core::agent::harness::AgentDefinitionRegistry;
-use openhuman_core::agent::Agent;
+use openhuman_core::agent::OpenHumanSessionHost;
use openhuman_core::config::Config;
use openhuman_core::inference::provider::factory::test_provider_override;
use openhuman_core::security::AutonomyLevel;
@@ -148,7 +148,7 @@ pub async fn run() -> Result<ProfileResult> {
let futures = (0..concurrency).map(|idx| {
let config = config.clone();
async move {
- let mut agent = Agent::from_config_for_agent(&config, CODE_AGENT)
+ let mut agent = OpenHumanSessionHost::from_config_for_agent(&config, CODE_AGENT)
.with_context(|| format!("building code_executor agent #{idx}"))?;
let reply = agent
.run_single(
diff --git a/crates/openhuman-core/src/bin/library_profile/scenarios/subagent_storm.rs b/crates/openhuman-core/src/bin/library_profile/scenarios/subagent_storm.rs
index caccb32978..34afb9b425 100644
--- a/crates/openhuman-core/src/bin/library_profile/scenarios/subagent_storm.rs
+++ b/crates/openhuman-core/src/bin/library_profile/scenarios/subagent_storm.rs
@@ -35,7 +35,7 @@
use anyhow::Result;
use openhuman_core::agent::harness::AgentDefinitionRegistry;
-use openhuman_core::agent::Agent;
+use openhuman_core::agent::OpenHumanSessionHost;
use openhuman_core::inference::provider::factory::test_provider_override;
use crate::harness::{fixture, measure, ProfileResult, TurnLatency};
@@ -109,7 +109,7 @@ pub async fn run() -> Result<ProfileResult> {
let mock_for_workload = mock.clone();
let mut result = measure("subagent-storm", width, None, move |rec| async move {
rec.checkpoint("baseline")?;
- let mut agent = Agent::from_config_for_agent(&config, "orchestrator")?;
+ let mut agent = OpenHumanSessionHost::from_config_for_agent(&config, "orchestrator")?;
let reply = agent.run_single(STORM_PROMPT).await?;
rec.checkpoint("storm-turn-done")?;
anyhow::ensure!(!reply.trim().is_empty(), "empty storm-turn response");
diff --git a/crates/openhuman-core/src/bin/rss_bench.rs b/crates/openhuman-core/src/bin/rss_bench.rs
index c2f8c82aea..661da4c994 100644
--- a/crates/openhuman-core/src/bin/rss_bench.rs
+++ b/crates/openhuman-core/src/bin/rss_bench.rs
@@ -1,8 +1,8 @@
//! `rss-bench` — steady-state RSS benchmark for an embedded `openhuman_core`
//! agent roster (#5046).
//!
-//! Mirrors the OpenCompany embedding contract: a bare [`Agent`] built directly
-//! via [`Agent::builder`] (no `CoreBuilder`, no RPC, no background services)
+//! Mirrors the OpenCompany embedding contract: a bare [`OpenHumanSessionHost`] built directly
+//! via [`OpenHumanSessionHost::builder`] (no `CoreBuilder`, no RPC, no background services)
//! with an injected mock model, an in-process `"none"` memory backend, and a
//! per-agent temp workspace. Builds a 1-agent and an 8-agent roster, runs one
//! deterministic warm-up turn per agent to fault in lazy allocations, settles,
@@ -26,7 +26,7 @@
use anyhow::{Context, Result};
use async_trait::async_trait;
-use openhuman_core::agent::Agent;
+use openhuman_core::agent::OpenHumanSessionHost;
use openhuman_core::memory::{Memory, MemoryCategory, MemoryEntry, NamespaceSummary, RecallOpts};
use openhuman_core::platform::proc_metrics::{
self, BenchReport, ProcSample, RosterResult, REPORT_SCHEMA_VERSION, RSS_BUDGET_KIB,
@@ -153,7 +153,7 @@ impl Memory for NoopMemory {
/// A built roster plus the temp workspaces that must outlive it — dropping the
/// `TempDir`s would delete the agents' workspaces mid-measurement.
struct Roster {
- agents: Vec<Agent>,
+ agents: Vec<OpenHumanSessionHost>,
_workspaces: Vec<TempDir>,
}
@@ -168,7 +168,7 @@ fn build_roster(n: usize) -> Result<Roster> {
let memory: Arc<dyn Memory> = Arc::new(NoopMemory);
- let agent = Agent::builder()
+ let agent = OpenHumanSessionHost::builder()
.chat_model(Arc::new(MockModel))
.tools(vec![Box::new(EchoTool)])
.memory(memory)
diff --git a/crates/openhuman-core/src/channels/README.md b/crates/openhuman-core/src/channels/README.md
index cfee47c7e0..629897daec 100644
--- a/crates/openhuman-core/src/channels/README.md
+++ b/crates/openhuman-core/src/channels/README.md
@@ -4,7 +4,7 @@ Multi-platform messaging integration. Re-exports the `Channel` trait vocabulary,
## Feature gate
-The domain lives behind the `channels` feature (default-ON, #4801), except two dependency-free carve-outs that always-on code reaches directly: `traits` (the `Channel`/`SendMessage` re-export, named by the always-on agent-harness interactive loop in `agent/harness/session/`) and `cli` (`CliChannel`, the stdin/stdout REPL that loop drives in every build). Everything else — `providers`, `host`, `controllers`, `runtime`, `bus`, `proactive`, `commands`, `context`, `routes`, `relay_runtime`, `system_prompt`, the provider re-exports, `doctor_channels`, `start_channels`, `build_system_prompt` and the `test_support` re-export — is `#[cfg(feature = "channels")]`. The feature owns the optional `tinychannels` crate (`channels = ["dep:tinychannels", "tinychannels/email", "tinychannels/lark"]`); the always-on pins (config schema, the `DomainEvent` inbound envelope, security pairing) resolve through the unconditional `tinychannels-bus` contract crate instead. Measured, the gate sheds no transitive packages — its value is compile surface and binary size — and `voice` re-enables `dep:tinychannels` for `EmailChannel` alone. The full rationale is the comment above the `channels` feature in `crates/openhuman-core/Cargo.toml`.
+The domain lives behind the `channels` feature (default-ON, #4801), except two dependency-free carve-outs that always-on code reaches directly: `traits` (the `Channel`/`SendMessage` re-export, named by the always-on agent-harness interactive loop in `agent/session_host/`) and `cli` (`CliChannel`, the stdin/stdout REPL that loop drives in every build). Everything else — `providers`, `host`, `controllers`, `runtime`, `bus`, `proactive`, `commands`, `context`, `routes`, `relay_runtime`, `system_prompt`, the provider re-exports, `doctor_channels`, `start_channels`, `build_system_prompt` and the `test_support` re-export — is `#[cfg(feature = "channels")]`. The feature owns the optional `tinychannels` crate (`channels = ["dep:tinychannels", "tinychannels/email", "tinychannels/lark"]`); the always-on pins (config schema, the `DomainEvent` inbound envelope, security pairing) resolve through the unconditional `tinychannels-bus` contract crate instead. Measured, the gate sheds no transitive packages — its value is compile surface and binary size — and `voice` re-enables `dep:tinychannels` for `EmailChannel` alone. The full rationale is the comment above the `channels` feature in `crates/openhuman-core/Cargo.toml`.
## Public surface
@@ -49,7 +49,7 @@ Flat files: `bus.rs` (`ChannelInboundSubscriber`, handles `DomainEvent::ChannelI
- `crates/openhuman-core/src/core/all.rs` — registers `controllers::all_channels_registered_controllers()` under the `channels` feature gate.
- `crates/openhuman-core/src/core/runtime/services.rs` — `spawn_channels_service` calls `channels::start_channels(config)` unless `OPENHUMAN_DISABLE_CHANNEL_LISTENERS` is set or `has_listening_integrations()` is false.
- `crates/openhuman-core/src/core/jsonrpc.rs` — `bootstrap_core_runtime` subscribes `bus::ChannelInboundSubscriber` and calls `proactive::register_web_only_proactive_subscriber()`.
-- `crates/openhuman-core/src/agent/harness/session/` — the interactive loop drives the ungated `CliChannel`.
+- `crates/openhuman-core/src/agent/session_host/` — the interactive loop drives the ungated `CliChannel`.
- `crates/openhuman-core/src/cron/bus.rs` — `CronDeliverySubscriber` is handed the started channel map by `runtime/startup.rs`; it names channels only through `tinychannels_bus`.
## Tests
diff --git a/crates/openhuman-core/src/channels/mod.rs b/crates/openhuman-core/src/channels/mod.rs
index 3fa24c177d..21c68dfdea 100644
--- a/crates/openhuman-core/src/channels/mod.rs
+++ b/crates/openhuman-core/src/channels/mod.rs
@@ -6,7 +6,7 @@
//!
//! * `traits` — a one-line re-export of the `tinychannels` `Channel` /
//! `SendMessage` traits, named by the always-on agent-harness interactive
-//! loop (`agent::harness::session::runtime::run_interactive`).
+//! loop (`agent::session_host::runtime::run_interactive`).
//! * `cli` — `CliChannel`, the dependency-free local stdin/stdout REPL the same
//! interactive loop drives in every build.
//!
diff --git a/crates/openhuman-core/src/channels/runtime/dispatch/processor/turn.rs b/crates/openhuman-core/src/channels/runtime/dispatch/processor/turn.rs
index 127025c264..8692b13a2b 100644
--- a/crates/openhuman-core/src/channels/runtime/dispatch/processor/turn.rs
+++ b/crates/openhuman-core/src/channels/runtime/dispatch/processor/turn.rs
@@ -587,7 +587,7 @@ pub(crate) async fn process_channel_runtime_message(
);
// The typed `AgentError` is flattened to a `String` at the
// native-bus boundary (`agent::bus` map_err → `e.to_string()`),
- // so the downcast that works in `Agent::run_single` is not an
+ // so the downcast that works in `OpenHumanSessionHost::run_single` is not an
// option here — fall back to canonical-phrase substring match.
// The max-tool-iterations cap is a deterministic agent-state
// outcome and is already surfaced to the user as the
diff --git a/crates/openhuman-core/src/config/migrations/README.md b/crates/openhuman-core/src/config/migrations/README.md
index 215a5ce8cf..6b57184fe3 100644
--- a/crates/openhuman-core/src/config/migrations/README.md
+++ b/crates/openhuman-core/src/config/migrations/README.md
@@ -64,7 +64,7 @@ Does not own a `store.rs`. Its effects are written through other layers:
## Dependencies
- `crate::config` (`Config`, `HttpRequestConfig`, `schema::cloud_providers::{CloudProviderCreds, AuthStyle, CloudProviderType, generate_provider_id}`, `schema::LlmBackend`, `MODEL_CHAT_V1`, `MODEL_REASONING_V1`, `MODEL_REASONING_QUICK_V1`) — the migrations read and mutate the config struct; `schema_version` is the gating field.
-- `crate::agent::harness::session::transcript` (`transcript`, `SessionTranscript`, `write_transcript`) — `phase_out_profile_md` parses and rewrites persisted session transcripts byte-compatibly.
+- `tinyagents_session::transcript` (`transcript`, `SessionTranscript`, `write_transcript`) — `phase_out_profile_md` parses and rewrites persisted session transcripts byte-compatibly.
- `crate::inference::provider::factory` — `reconcile_orphaned_providers` mirrors the factory's exact, case-sensitive provider-string grammar so "resolvable here" matches "resolvable at inference time"; `unify_ai_provider_settings` references the factory's provider-string format.
- `crate::inference::host_runtime::ollama_base_url_from_config` — the runner's Ollama reachability probe for the 6→7 step. That step and the 9→10 step mirror, by hand, the provider-string grammar of `embeddings::factory::create_embedding_provider` and `voice::factory::create_stt_provider` respectively (doc-linked, not imported), so keep them in sync when those factories change.
- `crate::agent::messages::ChatMessage`, `schema::{LocalAiConfig, LocalAiUsage, ModelRouteConfig, SttEngine}` and `voice::factory::effective_stt_provider` are imported only by tests.
diff --git a/crates/openhuman-core/src/config/schema/context.rs b/crates/openhuman-core/src/config/schema/context.rs
index aa8d35df96..d66a94b855 100644
--- a/crates/openhuman-core/src/config/schema/context.rs
+++ b/crates/openhuman-core/src/config/schema/context.rs
@@ -105,7 +105,7 @@ pub struct ContextConfig {
/// Master switch for native tool-output compaction (Stage 1a). When
/// `true` (the default), large structured tool outputs (build/test logs,
/// diffs, JSON arrays) are content-aware compressed in
- /// `Agent::execute_tool_call` *before* the [`Self::tool_result_budget_bytes`]
+ /// `OpenHumanSessionHost::execute_tool_call` *before* the [`Self::tool_result_budget_bytes`]
/// byte cap and before they enter history. The compression never drops the
/// first/last/high-signal lines and only ever shrinks output, so it is on
/// by default.
diff --git a/crates/openhuman-core/src/core/agent_cli.rs b/crates/openhuman-core/src/core/agent_cli.rs
index fed2ab8f7e..2664214fbf 100644
--- a/crates/openhuman-core/src/core/agent_cli.rs
+++ b/crates/openhuman-core/src/core/agent_cli.rs
@@ -14,8 +14,8 @@
//!
//! `dump-prompt` is the main tool: it renders the exact system prompt the
//! context engine would hand to the LLM when that agent is spawned. The
-//! dump routes through [`Agent::from_config_for_agent`] and calls
-//! [`Agent::build_system_prompt`] on the live session, so the output is
+//! dump routes through [`OpenHumanSessionHost::from_config_for_agent`] and calls
+//! [`OpenHumanSessionHost::build_system_prompt`] on the live session, so the output is
//! byte-identical to what the LLM sees on turn 1. Pass
//! `--agent orchestrator` for the orchestrator prompt; otherwise pass
//! any built-in or workspace-custom agent id (e.g. `integrations_agent`,
diff --git a/crates/openhuman-core/src/core/observability.rs b/crates/openhuman-core/src/core/observability.rs
index 824a6b21fe..f70eddd5f3 100644
--- a/crates/openhuman-core/src/core/observability.rs
+++ b/crates/openhuman-core/src/core/observability.rs
@@ -178,7 +178,7 @@ pub enum ExpectedErrorKind {
/// (`text_chars=0 thinking_chars=0 tool_calls=0`), so the agent harness
/// bailed with the user-facing `"The model returned an empty response.
/// Please try again."` string
- /// (`agent::harness::session::turn`). This is a model/user-config
+ /// (`agent::session_host::turn`). This is a model/user-config
/// condition — a quirky or broken local fine-tune that returns nothing,
/// a provider that dropped the stream — not a code bug. The UI already
/// surfaces the typed error and the user can retry; Sentry has no
@@ -1949,7 +1949,7 @@ fn is_filesystem_user_path_invalid_message(lower: &str) -> bool {
/// Detect the agent harness's empty-provider-response bail.
///
/// Anchored on the literal user-facing string emitted at
-/// `agent::harness::session::turn` —
+/// `agent::session_host::turn` —
/// `"The model returned an empty response. Please try again."` — which is
/// preserved verbatim as the provider/model returns a body with
/// `text_chars=0 thinking_chars=0 tool_calls=0`.
@@ -2834,7 +2834,7 @@ fn all_provider_attempts_are_transient(message: &str) -> bool {
/// `crate::agent::error::MAX_ITERATIONS_ERROR_PREFIX`).
///
/// Defense-in-depth filter for the Sentry `before_send` hook: the primary
-/// suppression lives at the call sites in `agent::harness::session::
+/// suppression lives at the call sites in `agent::session_host::
/// runtime::run_single`, `channels::runtime::dispatch`, and
/// `web_chat::run_chat_task`, all of which now skip
/// `report_error` when this variant is detected. This filter catches any
diff --git a/crates/openhuman-core/src/core/observability_error_classification_provider_tests.rs b/crates/openhuman-core/src/core/observability_error_classification_provider_tests.rs
index 62c7596b4e..f7c567f48e 100644
--- a/crates/openhuman-core/src/core/observability_error_classification_provider_tests.rs
+++ b/crates/openhuman-core/src/core/observability_error_classification_provider_tests.rs
@@ -371,7 +371,7 @@ fn does_not_classify_unrelated_empty_response_phrases() {
"[memory_tree_walk] turn=3 LLM gave up (empty response)",
// learning/reflection.rs:576 — reflection skip, not a failure.
"[learning] reflection skipped (empty response — gate off or local AI unavailable)",
- // agent/harness/session/turn.rs:811 — "provider returned an empty
+ // agent/session_host/turn.rs:811 — "provider returned an empty
// final response" uses subject "provider", not "model"; must not match.
"[agent_loop] provider returned an empty final response (i=2, no text, no tool calls)",
] {
diff --git a/crates/openhuman-core/src/cron/scheduler/agent_run.rs b/crates/openhuman-core/src/cron/scheduler/agent_run.rs
index e560188289..7487efa2a5 100644
--- a/crates/openhuman-core/src/cron/scheduler/agent_run.rs
+++ b/crates/openhuman-core/src/cron/scheduler/agent_run.rs
@@ -3,7 +3,7 @@
use super::delivery::is_morning_briefing_job;
use super::failure_classification::classify_agent_anyhow_for_user;
-use crate::agent::Agent;
+use crate::agent::OpenHumanSessionHost;
use crate::config::Config;
use crate::core::bus::BUS;
use crate::core::events::DomainEvent;
@@ -33,7 +33,7 @@ pub(super) async fn run_agent_job(
// When an agent_id is set, resolve the built-in definition and apply
// its model hint, iteration cap, and prompt body so the cron job
// runs with the definition's constraints instead of the generic
- // Agent::from_config defaults.
+ // OpenHumanSessionHost::from_config defaults.
let selected_agent_id = job.agent_id.as_deref().unwrap_or("orchestrator");
{
let agent_id = selected_agent_id;
@@ -232,7 +232,7 @@ pub(super) fn run_flow_schedule_job(job: &CronJob) -> (bool, String) {
pub(super) const EMPTY_AGENT_OUTPUT: &str = "agent job executed";
pub(super) struct BuiltCronAgent {
- pub(crate) agent: Agent,
+ pub(crate) agent: OpenHumanSessionHost,
}
pub(super) fn build_agent_for_cron_job(
@@ -240,7 +240,7 @@ pub(super) fn build_agent_for_cron_job(
job: &CronJob,
) -> anyhow::Result<BuiltCronAgent> {
let agent_id = job.agent_id.as_deref().unwrap_or("orchestrator");
- match Agent::from_config_for_agent(config, agent_id) {
+ match OpenHumanSessionHost::from_config_for_agent(config, agent_id) {
Ok(agent) => {
tracing::debug!(
job_id = %job.id,
@@ -256,7 +256,7 @@ pub(super) fn build_agent_for_cron_job(
error = %e,
"[cron] failed to build agent from definition; falling back to canonical orchestrator"
);
- Agent::from_config_for_agent(config, "orchestrator")
+ OpenHumanSessionHost::from_config_for_agent(config, "orchestrator")
.map(|agent| BuiltCronAgent { agent })
}
}
diff --git a/crates/openhuman-core/src/cron/types.rs b/crates/openhuman-core/src/cron/types.rs
index 2f1c0ae0ff..3470eccd7f 100644
--- a/crates/openhuman-core/src/cron/types.rs
+++ b/crates/openhuman-core/src/cron/types.rs
@@ -230,7 +230,7 @@ pub struct CronJob {
/// `"morning_briefing"`). When set, [`crate::cron::scheduler`]
/// resolves the agent definition from the registry and runs with the
/// definition's prompt, tool allowlist, iteration cap, and model hint
- /// instead of the generic `Agent::from_config` path.
+ /// instead of the generic `OpenHumanSessionHost::from_config` path.
pub agent_id: Option<String>,
pub enabled: bool,
pub delivery: DeliveryConfig,
diff --git a/crates/openhuman-core/src/desktop/app_state/README.md b/crates/openhuman-core/src/desktop/app_state/README.md
index 55468851bb..87e48586b2 100644
--- a/crates/openhuman-core/src/desktop/app_state/README.md
+++ b/crates/openhuman-core/src/desktop/app_state/README.md
@@ -42,7 +42,7 @@ The signed-in identity for prompts and Sentry is `security::credentials::identit
- `crates/openhuman-core/src/core/all.rs` — registers `all_app_state_registered_controllers()`; the shell reaches them through `coreRpcClient` → `relay_http_rpc`.
- `crates/openhuman-core/src/core/jsonrpc.rs` — `latch_from_config` at runtime bootstrap.
-- `crates/openhuman-core/src/agent/harness/session/builder/factory.rs` — `load_stored_app_state` to read `onboarding_tasks.enabled_tools` for tool filtering.
+- `crates/openhuman-core/src/agent/session_host/builder/factory.rs` — `load_stored_app_state` to read `onboarding_tasks.enabled_tools` for tool filtering.
- `crates/openhuman-core/src/security/keyring_consent/ops.rs` — persists the consent choice through `update_local_state`.
## Tests
diff --git a/crates/openhuman-core/src/flows/README.md b/crates/openhuman-core/src/flows/README.md
index bd700f05ca..4af696e12b 100644
--- a/crates/openhuman-core/src/flows/README.md
+++ b/crates/openhuman-core/src/flows/README.md
@@ -67,7 +67,7 @@ from always-compiled code.
- `crates/openhuman-core/src/core/runtime/services.rs` — runs `sweep_orphaned_running_runs_on_boot` and `reconcile_schedule_triggers_on_boot` during core boot and calls `medulla_bridge::install`; `platform/socket/ops.rs` installs the bridge on the socket path as well.
- `crates/openhuman-core/src/tools/ops.rs` — pushes all 27 flows tools onto the agent tool list (`tools/mod.rs` re-exports the four tool modules).
- `crates/openhuman-core/src/agent/registry/agents/loader.rs` — registers `workflow_builder` and `flow_discovery` as built-in archetypes.
-- `crates/openhuman-core/src/agent/harness/session/` (`builder/factory.rs`, `turn/tools.rs`) — extends the skill catalogue with `catalogue::flow_entries`.
+- `crates/openhuman-core/src/agent/session_host/` (`builder/factory.rs`, `turn/tools.rs`) — extends the skill catalogue with `catalogue::flow_entries`.
## Tests
diff --git a/crates/openhuman-core/src/flows/ops/builder.rs b/crates/openhuman-core/src/flows/ops/builder.rs
index 4da65e89bc..867e156bbd 100644
--- a/crates/openhuman-core/src/flows/ops/builder.rs
+++ b/crates/openhuman-core/src/flows/ops/builder.rs
@@ -35,7 +35,7 @@ pub(crate) async fn flows_build_with_extra_hidden_tools(
stream: Option<FlowStreamTarget>,
extra_hidden_tools: &[&str],
) -> Result<RpcOutcome<Value>, String> {
- use crate::agent::Agent;
+ use crate::agent::OpenHumanSessionHost;
use crate::flows::agents::workflow_builder::builder_prompt::render_prompt;
// Reject invalid turns (e.g. a `build` with no `flow_id`) before we render a
@@ -61,7 +61,7 @@ pub(crate) async fn flows_build_with_extra_hidden_tools(
// resolves the per-agent iteration cap from the `workflow_builder`
// `AgentDefinition` itself (`iteration_policy = "extended"` ->
// `effective_max_iterations()` = 50), so no override is needed here.
- let mut agent = Agent::from_config_for_agent(config, "workflow_builder")
+ let mut agent = OpenHumanSessionHost::from_config_for_agent(config, "workflow_builder")
.map_err(|e| format!("failed to build workflow_builder agent: {e:#}"))?;
agent.set_agent_definition_name("workflow_builder".to_string());
start_builder_turn_clean(&mut agent);
@@ -276,7 +276,8 @@ pub(crate) async fn flows_build_with_extra_hidden_tools(
// response — the frontend renders from the stream, not the return value,
// so patching only the latter would still leave an interactive user
// staring at the original silent/status-only text.
- let proposal = extract_workflow_proposal(agent.history());
+ let runtime_history = agent.history();
+ let proposal = extract_workflow_proposal(&runtime_history);
// A user-cancelled turn settles here, clean and separate from the
// error/trail-off paths below: `finalize_flow_stream` gets an `Ok(...)` (a
@@ -346,7 +347,8 @@ pub(crate) async fn flows_build_with_extra_hidden_tools(
// is NEVER left with silence or an unanswerable status note.
let trail_off = !capped && proposal.is_none() && run_error.is_none();
let assistant_text = if trail_off && !text_looks_like_question(&assistant_text) {
- let fallback = build_trail_off_fallback(agent.history());
+ let runtime_history = agent.history();
+ let fallback = build_trail_off_fallback(&runtime_history);
let combined = combine_trail_off_fallback(&fallback, &assistant_text);
tracing::warn!(
target: "flows",
@@ -458,15 +460,15 @@ pub(super) fn extract_workflow_proposal(
/// Keep the builder's first turn from auto-resuming another flow's session.
///
-/// On an empty history `Agent::turn` falls back to `try_load_session_transcript`,
+/// On an empty history `OpenHumanSessionHost::turn` falls back to `try_load_session_transcript`,
/// which loads the newest transcript for the agent *name*. Every flow's builder
/// shares the name `workflow_builder` and the profile's `session_raw/` dir, so
/// that fallback hands a brand-new flow the most recent builder conversation from
/// whichever flow ran last. Thread-scoped resume, where a host does it, seeds
/// `cached_transcript_messages` and is unaffected. `agent_chat` suppresses the
/// same fallback for the same reason.
-pub(crate) fn start_builder_turn_clean(agent: &mut crate::agent::Agent) {
- agent.set_next_turn_overrides(crate::agent::harness::session::TurnOverrides {
+pub(crate) fn start_builder_turn_clean(agent: &mut crate::agent::OpenHumanSessionHost) {
+ agent.set_next_turn_overrides(crate::agent::session_host::TurnOverrides {
suppress_transcript_autoload: true,
..Default::default()
});
diff --git a/crates/openhuman-core/src/flows/ops/builder_toolset.rs b/crates/openhuman-core/src/flows/ops/builder_toolset.rs
index 10ee2e737f..deb99c5bdd 100644
--- a/crates/openhuman-core/src/flows/ops/builder_toolset.rs
+++ b/crates/openhuman-core/src/flows/ops/builder_toolset.rs
@@ -66,13 +66,13 @@ pub(super) const FLOWS_BUILD_HIDDEN_TOOLS: &[&str] = &[
/// Strip the live-run / resume / cancel tool(s) in [`FLOWS_BUILD_HIDDEN_TOOLS`]
/// from `agent`'s callable set for the direct `flows_build` RPC path.
///
-/// Delegates to [`crate::agent::Agent::hide_tools`], which removes
+/// Delegates to [`crate::agent::OpenHumanSessionHost::hide_tools`], which removes
/// the names from the builder's (already narrow) visible belt and rebuilds the
/// session's `ToolPolicySession` so they resolve to `Deny` at the tool-call
/// boundary — a hard execution guarantee even if the model requests the tool.
/// The authoring tools (`propose`/`revise`/`save`/`dry_run`/reads/`create_workflow`/
/// `duplicate_flow`) stay visible and untouched, so the turn never fail-closes.
-pub(super) fn restrict_builder_toolset(agent: &mut crate::agent::Agent) {
+pub(super) fn restrict_builder_toolset(agent: &mut crate::agent::OpenHumanSessionHost) {
tracing::debug!(
target: "flows",
hidden = ?FLOWS_BUILD_HIDDEN_TOOLS,
@@ -129,7 +129,7 @@ pub(super) const FLOWS_BUILD_COPILOT_HIDDEN_TOOLS: &[&str] = &["run_workflow", "
/// Strip only [`FLOWS_BUILD_COPILOT_HIDDEN_TOOLS`] from `agent`'s callable set
/// on the streaming `flows_build` path (copilot pane with a real approval
/// surface) — see that constant's doc for the full safety rationale.
-pub(super) fn restrict_builder_toolset_for_copilot(agent: &mut crate::agent::Agent) {
+pub(super) fn restrict_builder_toolset_for_copilot(agent: &mut crate::agent::OpenHumanSessionHost) {
tracing::info!(
target: "flows",
hidden = ?FLOWS_BUILD_COPILOT_HIDDEN_TOOLS,
diff --git a/crates/openhuman-core/src/flows/ops/discovery.rs b/crates/openhuman-core/src/flows/ops/discovery.rs
index 083bd1dfd7..3a01072a0d 100644
--- a/crates/openhuman-core/src/flows/ops/discovery.rs
+++ b/crates/openhuman-core/src/flows/ops/discovery.rs
@@ -40,7 +40,7 @@ pub async fn flows_discover(
stream: Option<FlowStreamTarget>,
) -> Result<RpcOutcome<Vec<FlowSuggestion>>, String> {
use crate::agent::turn_origin::{with_origin, AgentTurnOrigin};
- use crate::agent::Agent;
+ use crate::agent::OpenHumanSessionHost;
tracing::info!(
target: "flows",
@@ -54,7 +54,7 @@ pub async fn flows_discover(
crate::agent::harness::AgentDefinitionRegistry::init_global(&config.workspace_dir)
.map_err(|e| format!("failed to initialise agent registry: {e}"))?;
- let mut agent = Agent::from_config_for_agent(config, "flow_discovery")
+ let mut agent = OpenHumanSessionHost::from_config_for_agent(config, "flow_discovery")
.map_err(|e| format!("failed to build flow_discovery agent: {e:#}"))?;
agent.set_agent_definition_name("flow_discovery".to_string());
diff --git a/crates/openhuman-core/src/flows/ops/inference_readiness.rs b/crates/openhuman-core/src/flows/ops/inference_readiness.rs
index a1af48de4c..c6161d3e35 100644
--- a/crates/openhuman-core/src/flows/ops/inference_readiness.rs
+++ b/crates/openhuman-core/src/flows/ops/inference_readiness.rs
@@ -189,7 +189,7 @@ pub(super) fn agent_node_role(config: &Config, node: &tinyflows::model::Node) ->
crate::flows::tinyflows::caps::resolve_node_model(&node.config, entry_model).map(
|model| crate::flows::tinyflows::caps::harness_model_default_override(&model),
);
- return crate::agent::harness::session::provider_role_for_definition(
+ return crate::agent::session_host::provider_role_for_definition(
agent_ref,
override_model
.as_deref()
diff --git a/crates/openhuman-core/src/flows/ops/streaming.rs b/crates/openhuman-core/src/flows/ops/streaming.rs
index d8d93b01ec..68b35654ac 100644
--- a/crates/openhuman-core/src/flows/ops/streaming.rs
+++ b/crates/openhuman-core/src/flows/ops/streaming.rs
@@ -55,7 +55,7 @@ impl FlowStreamTarget {
/// (turn end). `source` is a short trace-attribution label (e.g.
/// `"flows_build"`).
pub(super) fn attach_flow_progress_bridge(
- agent: &mut crate::agent::Agent,
+ agent: &mut crate::agent::OpenHumanSessionHost,
target: &FlowStreamTarget,
source: &str,
config: &Config,
diff --git a/crates/openhuman-core/src/flows/ops_migration_and_side_effect_tests.rs b/crates/openhuman-core/src/flows/ops_migration_and_side_effect_tests.rs
index 4c6989f211..8fe4840cec 100644
--- a/crates/openhuman-core/src/flows/ops_migration_and_side_effect_tests.rs
+++ b/crates/openhuman-core/src/flows/ops_migration_and_side_effect_tests.rs
@@ -24,8 +24,9 @@ async fn flows_discover_applies_the_flow_discovery_definitions_effective_iterati
let expected = def.effective_max_iterations();
assert_eq!(expected, 50);
- let agent = crate::agent::Agent::from_config_for_agent(&config, "flow_discovery")
- .expect("build flow_discovery agent");
+ let agent =
+ crate::agent::OpenHumanSessionHost::from_config_for_agent(&config, "flow_discovery")
+ .expect("build flow_discovery agent");
assert_eq!(agent.agent_config().max_tool_iterations, expected);
}
diff --git 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
index c4c2ffbb7c..746b37adda 100644
--- 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
@@ -440,8 +440,9 @@ async fn flows_build_hides_the_live_run_tool_from_the_builder_belt() {
// wired. `Once`-guarded, so this is free when another test got there first.
crate::agent::harness::AgentDefinitionRegistry::init_global(&config.workspace_dir)
.expect("agent registry init");
- let mut agent = crate::agent::Agent::from_config_for_agent(&config, "workflow_builder")
- .expect("build workflow_builder agent");
+ let mut agent =
+ crate::agent::OpenHumanSessionHost::from_config_for_agent(&config, "workflow_builder")
+ .expect("build workflow_builder agent");
agent.set_agent_definition_name("workflow_builder".to_string());
// Precondition: the builder advertises all four run-advancing tools on its
@@ -537,8 +538,9 @@ async fn flows_build_copilot_toolset_unhides_the_live_run_tools() {
// wired. `Once`-guarded, so this is free when another test got there first.
crate::agent::harness::AgentDefinitionRegistry::init_global(&config.workspace_dir)
.expect("agent registry init");
- let mut agent = crate::agent::Agent::from_config_for_agent(&config, "workflow_builder")
- .expect("build workflow_builder agent");
+ let mut agent =
+ crate::agent::OpenHumanSessionHost::from_config_for_agent(&config, "workflow_builder")
+ .expect("build workflow_builder agent");
agent.set_agent_definition_name("workflow_builder".to_string());
restrict_builder_toolset_for_copilot(&mut agent);
@@ -612,8 +614,9 @@ async fn flows_build_applies_the_builder_definitions_effective_iteration_cap() {
// End-to-end: the agent actually built for this path carries the
// definition's cap straight off the unmodified `config` — the session
// builder resolves it internally now, no `flows_build`-side override.
- let agent = crate::agent::Agent::from_config_for_agent(&config, "workflow_builder")
- .expect("build workflow_builder agent");
+ let agent =
+ crate::agent::OpenHumanSessionHost::from_config_for_agent(&config, "workflow_builder")
+ .expect("build workflow_builder agent");
assert_eq!(agent.agent_config().max_tool_iterations, expected);
assert_ne!(
agent.agent_config().max_tool_iterations,
diff --git a/crates/openhuman-core/src/flows/tinyflows/caps/agent.rs b/crates/openhuman-core/src/flows/tinyflows/caps/agent.rs
index 5766e0f9d5..b81ada4117 100644
--- a/crates/openhuman-core/src/flows/tinyflows/caps/agent.rs
+++ b/crates/openhuman-core/src/flows/tinyflows/caps/agent.rs
@@ -26,10 +26,10 @@ use crate::inference::provider::{is_raw_passthrough_model, role_for_model_tier};
/// 1. **Full harness turn** (the common case, Phase A). When `agent_ref` names a
/// harness [`AgentDefinition`](crate::agent::harness::definition::AgentDefinition),
/// the node builds a real session agent
-/// ([`Agent::from_config_for_agent`](crate::agent::Agent::from_config_for_agent)
+/// ([`OpenHumanSessionHost::from_config_for_agent`](crate::agent::OpenHumanSessionHost::from_config_for_agent)
/// + `set_agent_definition_name`) and drives one full turn via
///
-/// [`Agent::run_single`](crate::agent::Agent::run_single) — the
+/// [`OpenHumanSessionHost::run_single`](crate::agent::OpenHumanSessionHost::run_single) — the
/// complete tool loop. The definition's `ToolScope` / `sandbox_mode` /
/// `max_iterations` govern the turn, so an agent node gains its curated
/// toolset with no graph change. This is the same harness pattern
@@ -61,7 +61,7 @@ use crate::inference::provider::{is_raw_passthrough_model, role_for_model_tier};
/// first cut (skip-memory is a follow-up).
///
/// **Concurrency safety.** `run_agent` is re-entrant by construction: it builds
-/// a fresh [`Agent`](crate::agent::Agent) per call and stamps any
+/// a fresh [`Agent`](crate::agent::OpenHumanSessionHost) per call and stamps any
/// model override onto a *cloned* `Config`, so concurrent calls never mutate
/// shared state. The origin escalation and approval-run context are task-locals
/// propagated by the engine's `buffer_unordered` (which polls every item on the
@@ -198,7 +198,7 @@ pub(crate) fn resolve_run_timeout_secs(
}
/// Renders an agent-node completion `request` into the single user message
-/// [`Agent::run_single`](crate::agent::Agent::run_single) takes: the
+/// [`OpenHumanSessionHost::run_single`](crate::agent::OpenHumanSessionHost::run_single) takes: the
/// `prompt` string when present and non-empty, else the `messages` array
/// flattened to `"<role>: <content>"` lines (blank entries skipped). Empty
/// string when neither yields content. Mirrors how [`OpenHumanLlm::complete`]
@@ -256,7 +256,7 @@ pub(crate) fn resolve_node_model(request: &Value, entry_model: Option<&str>) ->
}
/// Translates a managed tier / `hint:*` / model string into the `default_model`
-/// value that routes a freshly-built harness [`Agent`](crate::agent::Agent)
+/// value that routes a freshly-built harness [`Agent`](crate::agent::OpenHumanSessionHost)
/// to the workload serving that tier. The session builder's `provider_role_for`
/// only routes the `hint:<role>` form to a specialised workload, so a bare tier
/// name (`reasoning-v1`) must be normalised to `hint:reasoning` here — otherwise
@@ -309,7 +309,7 @@ pub(crate) fn structured_output_instruction(request: &Value) -> Option<String> {
/// line; an absent part contributes nothing (no stray blank lines). Pulled
/// out as its own pure function — rather than inlined in `run_via_harness` —
/// so the prepend order is unit-testable without building a real harness
-/// [`Agent`](crate::agent::Agent).
+/// [`Agent`](crate::agent::OpenHumanSessionHost).
pub(crate) fn build_harness_run_prompt(request: &Value) -> String {
let parts = [
input_context_block(request),
@@ -390,7 +390,7 @@ impl AgentRunner for OpenHumanAgentRunner {
// — even for a user-created custom agent, which has real
// `tool_allowlist`/`model` settings that fallback ignores.
//
- // The agent factory (`Agent::from_config_for_agent`) now
+ // The agent factory (`OpenHumanSessionHost::from_config_for_agent`) now
// also consults `config.agent_registry.entries` on a
// harness-registry miss and synthesizes a real
// `AgentDefinition` for any `AgentRegistrySource::Custom`
@@ -492,7 +492,7 @@ impl OpenHumanAgentRunner {
conn: Option<&str>,
entry_model: Option<&str>,
) -> Result<Value> {
- use crate::agent::Agent;
+ use crate::agent::OpenHumanSessionHost;
// Hold a slot for the whole turn: a fanned-out node can call this
// hundreds of times at once, and each call below builds a full agent
@@ -532,8 +532,8 @@ impl OpenHumanAgentRunner {
None => Cow::Borrowed(self.config.as_ref()),
};
- let mut agent =
- Agent::from_config_for_agent(effective.as_ref(), agent_ref).map_err(|e| {
+ let mut agent = OpenHumanSessionHost::from_config_for_agent(effective.as_ref(), agent_ref)
+ .map_err(|e| {
EngineError::Capability(format!(
"agent node: failed to build harness agent '{agent_ref}': {e:#}"
))
diff --git a/crates/openhuman-core/src/flows/tinyflows/caps/ops_tier_gate_and_timeouts_tests.rs b/crates/openhuman-core/src/flows/tinyflows/caps/ops_tier_gate_and_timeouts_tests.rs
index c373d4fde7..d41494148d 100644
--- a/crates/openhuman-core/src/flows/tinyflows/caps/ops_tier_gate_and_timeouts_tests.rs
+++ b/crates/openhuman-core/src/flows/tinyflows/caps/ops_tier_gate_and_timeouts_tests.rs
@@ -451,7 +451,7 @@ fn agent_node_runtime_resolves_to_the_definitions_effective_iteration_cap() {
let expected = def.effective_max_iterations();
assert_eq!(expected, 50);
- let agent = crate::agent::Agent::from_config_for_agent(&config, "code_executor")
+ let agent = crate::agent::OpenHumanSessionHost::from_config_for_agent(&config, "code_executor")
.expect("build code_executor agent");
assert_eq!(agent.agent_config().max_tool_iterations, expected);
diff --git a/crates/openhuman-core/src/flows/tinyflows/caps/tier.rs b/crates/openhuman-core/src/flows/tinyflows/caps/tier.rs
index 0a28b8a712..cf911a0f6b 100644
--- a/crates/openhuman-core/src/flows/tinyflows/caps/tier.rs
+++ b/crates/openhuman-core/src/flows/tinyflows/caps/tier.rs
@@ -176,7 +176,7 @@ fn force_workflow_approval(
/// referenced agent's LLM will pick — the graph only names the `agent_ref`, and
/// the definition's `ToolScope` is the runtime pool. So the "trust root =
/// static action" invariant that justifies the `intercept_audited` shortcut
-/// simply doesn't hold across the `Agent::run_single` boundary.
+/// simply doesn't hold across the `OpenHumanSessionHost::run_single` boundary.
///
/// `Workflow { require_approval: true }` passes through unchanged (already
/// user-forced HITL); other origins pass through unchanged (Cron / Web chat
diff --git a/crates/openhuman-core/src/inference/host_runtime/ops/agent_chat.rs b/crates/openhuman-core/src/inference/host_runtime/ops/agent_chat.rs
index 7b6ec2291e..9ff246663d 100644
--- a/crates/openhuman-core/src/inference/host_runtime/ops/agent_chat.rs
+++ b/crates/openhuman-core/src/inference/host_runtime/ops/agent_chat.rs
@@ -1,6 +1,6 @@
//! Agent chat turns: the full tool-using turn and the simple no-tools variant.
-use crate::agent::Agent;
+use crate::agent::OpenHumanSessionHost;
use crate::config::Config;
use crate::inference::provider as providers;
use crate::rpc::RpcOutcome;
@@ -74,28 +74,31 @@ pub async fn agent_chat(
/// Which session [`agent_chat_for`] builds the turn on.
#[derive(Debug, Clone, Copy)]
pub enum AgentChatTarget<'a> {
- /// The orchestrator — [`Agent::from_config`], today's `agent_chat`.
+ /// The orchestrator — [`OpenHumanSessionHost::from_config`], today's `agent_chat`.
Orchestrator,
/// Resolve `id` the way every other id-keyed entry point does: the
/// process registry first, then `config.agent_registry.entries`.
AgentId(&'a str),
/// A definition the caller already holds; nothing is resolved by id. The
/// entry point for a library host running its own per-agent specs — see
- /// [`Agent::from_config_with_definition`].
+ /// [`OpenHumanSessionHost::from_config_with_definition`].
Definition {
definition: &'a crate::agent::harness::definition::AgentDefinition,
},
}
-fn build_turn_agent(config: &Config, target: &AgentChatTarget<'_>) -> Result<Agent, String> {
+fn build_turn_agent(
+ config: &Config,
+ target: &AgentChatTarget<'_>,
+) -> Result<OpenHumanSessionHost, String> {
match target {
- AgentChatTarget::Orchestrator => Agent::from_config(config),
+ AgentChatTarget::Orchestrator => OpenHumanSessionHost::from_config(config),
AgentChatTarget::AgentId(id) => {
log::debug!("[inference] agent_chat building agent_id={id}");
- Agent::from_config_for_agent(config, id)
+ OpenHumanSessionHost::from_config_for_agent(config, id)
}
AgentChatTarget::Definition { definition } => {
- Agent::from_config_with_definition(config, definition)
+ OpenHumanSessionHost::from_config_with_definition(config, definition)
}
}
.map_err(|e| e.to_string())
@@ -106,10 +109,10 @@ fn build_turn_agent(config: &Config, target: &AgentChatTarget<'_>) -> Result<Age
/// Two differences from the historical `agent_chat` beyond the target:
///
/// * A non-empty `thread_id` resumes **that thread's** transcript
-/// (`Agent::seed_resume_from_thread_transcript`). When the thread has no
+/// (`OpenHumanSessionHost::seed_resume_from_thread_transcript`). When the thread has no
/// transcript yet, auto-resume is suppressed for the turn so a fresh thread
/// never splices in the agent's newest transcript from some other thread —
-/// `Agent::turn` resolves the latest transcript per agent *name*, not per
+/// `OpenHumanSessionHost::turn` resolves the latest transcript per agent *name*, not per
/// thread.
/// * The agent is built by `target`, so a library host can run one booted
/// core with many independently defined agents.
@@ -168,7 +171,7 @@ pub async fn agent_chat_for(
}
None => build_turn_agent(config, &target)?,
};
- // Thread-correct resume. `Agent::turn` would otherwise auto-load the
+ // Thread-correct resume. `OpenHumanSessionHost::turn` would otherwise auto-load the
// newest transcript for the agent *name*, which is another thread's
// history whenever the same agent serves several threads (every library
// host does exactly that). Seed from this thread's transcript when it has
@@ -195,13 +198,13 @@ pub async fn agent_chat_for(
log::debug!("[inference] agent_chat resumed thread transcript thread_id={id}");
} else {
log::debug!("[inference] agent_chat fresh thread thread_id={id}; autoload suppressed");
- agent.set_next_turn_overrides(crate::agent::harness::session::TurnOverrides {
+ agent.set_next_turn_overrides(crate::agent::session_host::TurnOverrides {
suppress_transcript_autoload: true,
..Default::default()
});
}
}
- // Live progress for in-process embedders. `Agent::from_config` never
+ // Live progress for in-process embedders. `OpenHumanSessionHost::from_config` never
// attaches a sink itself, so there is nothing to clobber here; callers that
// set one explicitly (web chat, platform socket, flows, skills) hold their
// own `Agent` and never reach this path — where both could apply, the
diff --git a/crates/openhuman-core/src/inference/provider/README.md b/crates/openhuman-core/src/inference/provider/README.md
index ee8d6c4c34..37ad1a72ba 100644
--- a/crates/openhuman-core/src/inference/provider/README.md
+++ b/crates/openhuman-core/src/inference/provider/README.md
@@ -68,8 +68,8 @@ domain.
## Called by
`grep -rn 'inference::provider::' crates/openhuman-core/src` shows the main
-consumers: the agent harness (`agent/harness/session/builder/factory.rs`,
-`agent/harness/session/runtime*.rs`, `agent/harness/subagent_runner/ops/*`,
+consumers: the agent harness (`agent/session_host/builder/factory.rs`,
+`agent/session_host/runtime*.rs`, `agent/harness/subagent_runner/ops/*`,
`agent/tinyagents/host/model_resolver.rs`), `web_chat/session.rs` and
`web_chat/web_errors/` (`classify.rs`, `budget.rs`, `retry.rs`, `timeout.rs`,
`backend_error_code.rs`, `provider_detail.rs`, `response_predicates.rs`), `voice/factory/{helpers,mod}.rs`,
diff --git a/crates/openhuman-core/src/integrations/composio/README.md b/crates/openhuman-core/src/integrations/composio/README.md
index 6743d8c8cc..bf2065c6c3 100644
--- a/crates/openhuman-core/src/integrations/composio/README.md
+++ b/crates/openhuman-core/src/integrations/composio/README.md
@@ -187,7 +187,7 @@ Published from `ops/` via `crate::core::bus::BUS.publish` (`crate::core::events:
- `crates/openhuman-core/src/tools/{mod,ops}.rs`, `tools/schemas/composio.rs` — wires agent tools into the tool registry.
- `crates/openhuman-core/src/core/jsonrpc.rs` — at startup initializes trigger history and registers the three bus subscribers.
- `crates/openhuman-core/src/channels/runtime/startup/start_channels.rs` (`start_channels`) — the one caller of `start_periodic_sync()`. `core/runtime/services.rs`'s `composio_integration_sync` job only runs `memory::sources::reconcile::ensure_composio_sources`; its comment explains why the periodic loop is not started there.
-- `crates/openhuman-core/src/agent/**` — harness/session/subagent spawning (`integrations_agent`), triage escalation, debug (e.g. `agent/harness/subagent_runner/`, `agent/orchestration/tools/`, `agent/debug/mod.rs`).
+- `crates/openhuman-core/src/agent/**` — session_host/subagent spawning (`integrations_agent`), triage escalation, debug (e.g. `agent/harness/subagent_runner/`, `agent/orchestration/tools/`, `agent/debug/mod.rs`).
- `crates/openhuman-core/src/platform/socket/event_handlers.rs` — parses `composio:trigger` and publishes `ComposioTriggerReceived`.
- `crates/openhuman-core/src/agent/learning/linkedin_enrichment*.rs`, `agent/learning/profile_md_renderer.rs` — connected-identity enrichment consumers.
- `crates/openhuman-core/src/agent/prompts/connected_identities.rs` — renders connected identities into the agent prompt.
diff --git a/crates/openhuman-core/src/main.rs b/crates/openhuman-core/src/main.rs
index d0b1846d53..fcde7b88f1 100644
--- a/crates/openhuman-core/src/main.rs
+++ b/crates/openhuman-core/src/main.rs
@@ -133,7 +133,7 @@ fn main() {
}
// Defense-in-depth: drop max-tool-iterations cap events that
// slipped past the call-site filters in
- // `agent::harness::session::runtime::run_single`,
+ // `agent::session_host::runtime::run_single`,
// `channels::runtime::dispatch`, and
// `web_chat::run_chat_task`. The cap is a
// deterministic agent-state outcome surfaced to the user via
diff --git a/crates/openhuman-core/src/mcp/registry/README.md b/crates/openhuman-core/src/mcp/registry/README.md
index 397008e955..f1deebe4a2 100644
--- a/crates/openhuman-core/src/mcp/registry/README.md
+++ b/crates/openhuman-core/src/mcp/registry/README.md
@@ -142,7 +142,7 @@ same real type in both builds.
`crates/openhuman-core/src/agent/registry/agents/orchestrator/prompt.rs` —
read `mcp::registry::connections` to list connected servers/tools for the
tool catalog and the orchestrator prompt.
-- `crates/openhuman-core/src/agent/harness/session/turn/core_turn.rs` — reads
+- `crates/openhuman-core/src/agent/session_host/turn/core_turn.rs` — reads
`connections::connected_overview()` when assembling a turn.
- `crates/openhuman-core/src/platform/about_app/catalog_auth_channels_team.rs` — the
`channels.mcp_registry_browse` / `mcp_server_install` /
diff --git a/crates/openhuman-core/src/mcp/registry/ops.rs b/crates/openhuman-core/src/mcp/registry/ops.rs
index 6ff58ec553..5414c6f3f9 100644
--- a/crates/openhuman-core/src/mcp/registry/ops.rs
+++ b/crates/openhuman-core/src/mcp/registry/ops.rs
@@ -638,7 +638,7 @@ async fn invoke_config_assist_agent(
message.len()
);
- let mut agent = match crate::agent::Agent::from_config(config) {
+ let mut agent = match crate::agent::OpenHumanSessionHost::from_config(config) {
Ok(a) => a,
Err(e) => {
return Ok(json!({
diff --git a/crates/openhuman-core/src/mcp/server/tools/dispatch.rs b/crates/openhuman-core/src/mcp/server/tools/dispatch.rs
index 73bf6ee784..541b012e27 100644
--- a/crates/openhuman-core/src/mcp/server/tools/dispatch.rs
+++ b/crates/openhuman-core/src/mcp/server/tools/dispatch.rs
@@ -2,7 +2,7 @@ use serde_json::{json, Map, Value};
use tinyinference_llm::tool::ToolSchema;
use crate::agent::harness::AgentDefinitionRegistry;
-use crate::agent::Agent;
+use crate::agent::OpenHumanSessionHost;
use crate::config::rpc as config_rpc;
use crate::core::all;
use crate::security::{SecurityPolicy, ToolOperation};
@@ -208,11 +208,12 @@ async fn load_config_and_init_registry() -> Result<crate::config::Config, ToolCa
Ok(config)
}
-async fn build_orchestrator_agent() -> Result<Agent, ToolCallError> {
+async fn build_orchestrator_agent() -> Result<OpenHumanSessionHost, ToolCallError> {
let config = load_config_and_init_registry().await?;
- let mut agent = Agent::from_config_for_agent(&config, "orchestrator").map_err(|err| {
- ToolCallError::Internal(format!("failed to build orchestrator agent: {err}"))
- })?;
+ let mut agent =
+ OpenHumanSessionHost::from_config_for_agent(&config, "orchestrator").map_err(|err| {
+ ToolCallError::Internal(format!("failed to build orchestrator agent: {err}"))
+ })?;
agent.fetch_connected_integrations().await;
agent.refresh_delegation_tools();
Ok(agent)
@@ -358,9 +359,10 @@ async fn run_subagent_tool(params: &Map<String, Value>) -> Result<Value, ToolCal
let child_depth = chain_depth + 1;
let config = load_config_and_init_registry().await?;
- let mut agent = Agent::from_config_for_agent(&config, &agent_id).map_err(|err| {
- ToolCallError::InvalidParams(format!("failed to build agent `{agent_id}`: {err}"))
- })?;
+ let mut agent =
+ OpenHumanSessionHost::from_config_for_agent(&config, &agent_id).map_err(|err| {
+ ToolCallError::InvalidParams(format!("failed to build agent `{agent_id}`: {err}"))
+ })?;
agent.set_event_context(
format!("mcp:{}:{}", agent_id, uuid::Uuid::new_v4()),
"mcp_server",
diff --git a/crates/openhuman-core/src/memory/agent/README.md b/crates/openhuman-core/src/memory/agent/README.md
index 96e880e011..1413172438 100644
--- a/crates/openhuman-core/src/memory/agent/README.md
+++ b/crates/openhuman-core/src/memory/agent/README.md
@@ -21,7 +21,7 @@ The memory agent is a specialist sub-agent that navigates the user's memory tree
| `types.rs` | Benchmark and performance tracking types |
| `ops.rs` | Benchmarking harness for memory walk performance |
| `tools.rs` | `call_memory_agent` tool implementation, re-exported from [`tools/mod.rs`](../../tools/mod.rs) (`pub use crate::memory::agent::tools::*;`) |
-| `memory_loader.rs` | What is left of the old per-turn memory loader: `CROSS_CHAT_HEADER` (the `[Cross-chat context]` block header, bound by `agent/harness/memory_context.rs` and the orchestrator prompt so the wording cannot drift), `MemoryCitation`, and `collect_recall_citations` (called from `agent/harness/session/turn/core_turn.rs`; the citations reach `web_chat`'s reply presentation). The per-turn `load_context()` block — two full scans of the `global` namespace every turn — was removed from `core_turn.rs`; see [`memory/auto_recall/mod.rs`](../auto_recall/mod.rs) for what replaced it. The `PRIOR_CONVERSATION_*` constants are leftovers of that block and have no caller. |
+| `memory_loader.rs` | What is left of the old per-turn memory loader: `CROSS_CHAT_HEADER` (the `[Cross-chat context]` block header, bound by `agent/harness/memory_context.rs` and the orchestrator prompt so the wording cannot drift), `MemoryCitation`, and `collect_recall_citations` (called from `agent/session_host/turn/core_turn.rs`; the citations reach `web_chat`'s reply presentation). The per-turn `load_context()` block — two full scans of the `global` namespace every turn — was removed from `core_turn.rs`; see [`memory/auto_recall/mod.rs`](../auto_recall/mod.rs) for what replaced it. The `PRIOR_CONVERSATION_*` constants are leftovers of that block and have no caller. |
## Memory tree structure
diff --git a/crates/openhuman-core/src/memory/goals/enrich.rs b/crates/openhuman-core/src/memory/goals/enrich.rs
index 36971ee0ba..57d2fd5b19 100644
--- a/crates/openhuman-core/src/memory/goals/enrich.rs
+++ b/crates/openhuman-core/src/memory/goals/enrich.rs
@@ -17,7 +17,7 @@ use std::time::{SystemTime, UNIX_EPOCH};
use crate::agent::harness::definition::AgentDefinitionRegistry;
use crate::agent::turn_origin::{with_origin, AgentTurnOrigin, TrustedAutomationSource};
-use crate::agent::Agent;
+use crate::agent::OpenHumanSessionHost;
use crate::config::Config;
use crate::memory::api::goals::GoalsDoc;
use crate::memory::api::provider::MemoryProvider;
@@ -120,7 +120,7 @@ pub async fn enrich_goals(
}
}
- let mut agent = Agent::from_config_for_agent(config, GOALS_AGENT_ID)
+ let mut agent = OpenHumanSessionHost::from_config_for_agent(config, GOALS_AGENT_ID)
.map_err(|e| format!("goals agent init failed: {e}"))?;
let job_id = format!("memory_goals:enrich:{}", now_secs());
diff --git a/crates/openhuman-core/src/platform/socket/medulla/mod.rs b/crates/openhuman-core/src/platform/socket/medulla/mod.rs
index f46a2ff767..6181f1b542 100644
--- a/crates/openhuman-core/src/platform/socket/medulla/mod.rs
+++ b/crates/openhuman-core/src/platform/socket/medulla/mod.rs
@@ -46,7 +46,7 @@ use tokio_util::sync::CancellationToken;
use crate::agent::progress::AgentProgress;
use crate::agent::turn_origin::{with_origin, AgentTurnOrigin};
-use crate::agent::Agent;
+use crate::agent::OpenHumanSessionHost;
use payloads::{
AgentDescriptor, CapabilitiesRequest, CapabilitiesResult, RegisterAgents, TaskResult,
@@ -398,11 +398,15 @@ async fn drain_steer(steer_rx: &mut mpsc::UnboundedReceiver<String>) -> Option<S
/// not the bare `agent_definition_name`. Without this, two `medulla:task_run`s
/// on the same `agentId` would collide onto one shared transcript and the
/// second would resume the first's history.
-async fn build_agent(agent_id: &str, task_id: &str, session_id: &str) -> Result<Agent, String> {
+async fn build_agent(
+ agent_id: &str,
+ task_id: &str,
+ session_id: &str,
+) -> Result<OpenHumanSessionHost, String> {
let config = crate::config::rpc::load_config_with_timeout().await?;
crate::agent::harness::AgentDefinitionRegistry::init_global(&config.workspace_dir)
.map_err(|err| format!("failed to init agent definition registry: {err}"))?;
- let mut agent = Agent::from_config_for_agent(&config, agent_id)
+ let mut agent = OpenHumanSessionHost::from_config_for_agent(&config, agent_id)
.map_err(|err| format!("failed to build agent `{agent_id}`: {err}"))?;
agent.set_event_context(format!("medulla:{task_id}"), "medulla_harness");
// Scope the transcript/session key per medulla session so distinct sessions
@@ -417,7 +421,7 @@ async fn build_agent(agent_id: &str, task_id: &str, session_id: &str) -> Result<
/// Derive a per-session agent-definition (transcript) key from the medulla
/// `session_id`, namespaced by `agent_id`. The session id is truncated on a
/// char boundary to keep transcript filenames bounded; the underlying
-/// [`Agent::set_agent_definition_name`] sanitizes any remaining non-filename
+/// [`OpenHumanSessionHost::set_agent_definition_name`] sanitizes any remaining non-filename
/// characters.
fn medulla_session_key(agent_id: &str, session_id: &str) -> String {
let short: String = session_id.chars().take(32).collect();
diff --git a/crates/openhuman-core/src/platform/startup/README.md b/crates/openhuman-core/src/platform/startup/README.md
index 1fea3db158..18f329a448 100644
--- a/crates/openhuman-core/src/platform/startup/README.md
+++ b/crates/openhuman-core/src/platform/startup/README.md
@@ -5,7 +5,7 @@ Generic OpenHuman process-startup helpers. Currently a thin, stateless module wh
## Responsibilities
- Run workspace migrations at process startup via `run_workspace_migrations(workspace_dir)`.
-- Drive the **session-layout** migration (`agent::harness::session::migrate_session_layout_if_needed`) and log its outcome (jsonl/md moved, pruned legacy dirs, warnings).
+- Drive the **session-layout** migration and log its outcome (jsonl/md moved, pruned legacy dirs, warnings).
- Drive the **welcome-to-orchestrator** thread/artifact migration (`threads::migrate_welcome_agent_artifacts`) and log its outcome (threads/transcripts updated, files renamed).
- Swallow migration errors (log `warn`) and fall back to in-place legacy reads so boot always proceeds.
@@ -34,11 +34,11 @@ None (no `bus.rs`); does not publish or subscribe to `DomainEvent`s.
## Persistence
-No own state/store. It triggers migrations that mutate on-disk workspace artifacts (session layout files, thread/transcript artifacts) under `workspace_dir`, but the actual persistence and idempotency markers live in the called migration helpers (`agent::harness::session`, `threads`).
+No own state/store. It triggers migrations that mutate on-disk workspace artifacts (session layout files, thread/transcript artifacts) under `workspace_dir`, but the actual persistence and idempotency markers live in the called migration helpers (`tinyagents_session::transcript`, `threads`).
## Dependencies
-- `crate::agent::harness::session::migrate_session_layout_if_needed` — performs the session-layout migration (moves jsonl/md, prunes legacy dirs).
+- `tinyagents_session::transcript` — owns the durable session layout and transcript transitions.
- `crate::threads::migrate_welcome_agent_artifacts` — performs the welcome-agent → orchestrator artifact migration.
## Used by
diff --git a/crates/openhuman-core/src/security/credentials/README.md b/crates/openhuman-core/src/security/credentials/README.md
index c3f08eeaa0..4ba5689c1f 100644
--- a/crates/openhuman-core/src/security/credentials/README.md
+++ b/crates/openhuman-core/src/security/credentials/README.md
@@ -99,7 +99,7 @@ Note: `list_provider_credentials_by_prefix` and the Composio-direct/secret helpe
## Used by
-Many domains consume `AuthService` / session helpers / Composio-direct key, including (paths under `crates/openhuman-core/src/`): `core/{all,auth,jsonrpc}.rs` and `core/runtime/{context,services}.rs` (controller wiring, auth gate, gated services, boot seeding, identity seeding), `api/jwt.rs`, `desktop/app_state/ops/` (snapshot), `channels/controllers/ops/*` and `channels/runtime/startup/credentials.rs` (managed credentials), `integrations/composio/{client/direct,ops/direct_mode}.rs` (BYO key), `config/ops/model.rs`, `config/migrations/unify_ai_provider_settings.rs`, `embeddings/{cloud_adapter,factory,rpc/api_keys}.rs`, `security/encryption/ops.rs`, `http_host/auth.rs`, `inference/{openai_oauth,provider}/*` (provider auth, OpenAI OAuth), `hosted/{announcements,billing,team}/ops.rs`, `flows/*`, `modules/{connectors,memory_host}.rs`, `web3/wallet/ops.rs`, and the prompt-layer identity readers (`agent/tinyagents/host/context_composer.rs`, `agent/harness/session/turn/context.rs`, …).
+Many domains consume `AuthService` / session helpers / Composio-direct key, including (paths under `crates/openhuman-core/src/`): `core/{all,auth,jsonrpc}.rs` and `core/runtime/{context,services}.rs` (controller wiring, auth gate, gated services, boot seeding, identity seeding), `api/jwt.rs`, `desktop/app_state/ops/` (snapshot), `channels/controllers/ops/*` and `channels/runtime/startup/credentials.rs` (managed credentials), `integrations/composio/{client/direct,ops/direct_mode}.rs` (BYO key), `config/ops/model.rs`, `config/migrations/unify_ai_provider_settings.rs`, `embeddings/{cloud_adapter,factory,rpc/api_keys}.rs`, `security/encryption/ops.rs`, `http_host/auth.rs`, `inference/{openai_oauth,provider}/*` (provider auth, OpenAI OAuth), `hosted/{announcements,billing,team}/ops.rs`, `flows/*`, `modules/{connectors,memory_host}.rs`, `web3/wallet/ops.rs`, and the prompt-layer identity readers (`agent/tinyagents/host/context_composer.rs`, `agent/session_host/turn/context.rs`, …).
## Notes / gotchas
diff --git a/crates/openhuman-core/src/security/prompt_injection/README.md b/crates/openhuman-core/src/security/prompt_injection/README.md
index 783d0fb1b2..7f56bcde89 100644
--- a/crates/openhuman-core/src/security/prompt_injection/README.md
+++ b/crates/openhuman-core/src/security/prompt_injection/README.md
@@ -55,7 +55,7 @@ No `crate::*` or `crate::core::*` dependencies — the module is self-contained.
Consumers call `enforce_prompt_input` and treat any non-`Allow` action as a rejection (returning a user-facing guard message):
-- `crates/openhuman-core/src/agent/harness/session/runtime.rs` — gates agent session turns; emits `prompt_injection_blocked`.
+- `crates/openhuman-core/src/agent/session_host/runtime.rs` — gates agent session turns; emits `prompt_injection_blocked`.
- `crates/openhuman-core/src/agent/bus.rs` — screens inbound prompts on the agent event path.
- `crates/openhuman-core/src/agent/tinyagents/host/security_gate.rs` — `screen_input` stage of the tinyagents security gate.
- `crates/openhuman-core/src/mcp/registry/mod.rs` — `scan_tool_definition` on remote tool metadata at registration.
diff --git a/crates/openhuman-core/src/skills/README.md b/crates/openhuman-core/src/skills/README.md
index 2454a8e71d..388ab5e71a 100644
--- a/crates/openhuman-core/src/skills/README.md
+++ b/crates/openhuman-core/src/skills/README.md
@@ -46,7 +46,7 @@ Plus the sub-domain namespaces: `skill_registry.*` (`browse`, `search`, `sources
- `crates/openhuman-core/src/config/` — `Config::load_or_init()` for workspace resolution in the RPC handlers; the trust marker is `<workspace>/.openhuman/trust` (`ops_types::TRUST_MARKER`).
- `crates/openhuman-core/src/config/workspace/ops.rs` — calls `skills::init_workflows_dir` during workspace bootstrap.
-- `crates/openhuman-core/src/agent/registry/agents/orchestrator/prompt.rs` — renders the `## Installed Skills` catalog, fed by the skill list on `PromptContext` (`agent/harness/session/turn/context.rs`).
+- `crates/openhuman-core/src/agent/registry/agents/orchestrator/prompt.rs` — renders the `## Installed Skills` catalog, fed by the skill list on `PromptContext` (`agent/session_host/turn/context.rs`).
- `crates/openhuman-core/src/agent/context/channels_prompt.rs` — renders the `## Available Skills` list for channel-driven turns (`agent/prompts/` no longer emits a skills section).
- `crates/openhuman-core/src/core/bus.rs` / `crates/openhuman-core/src/core/events.rs` — `bus.rs` subscribes to `DomainEvent` for triggered skills; `ops_create.rs` and `ops_install/fetch.rs` publish `DomainEvent::WorkflowsChanged` after create/install/uninstall so open sessions refresh their catalog. (`WorkflowLoaded`/`WorkflowStopped`/`WorkflowStartFailed`/`WorkflowExecuted` are declared in `events.rs` but nothing in this module publishes them.)
- `crates/openhuman-core/src/agent/harness/definition.rs` — `registry.rs` flattens `AgentDefinition` fields from `skill.toml`.
@@ -55,7 +55,7 @@ Plus the sub-domain namespaces: `skill_registry.*` (`browse`, `search`, `sources
- `tinytools` — supplies the shared `ToolResult`/`ToolContent` shape directly.
- `crates/openhuman-core/src/agent/harness/fork_context.rs` — fork context propagates injected skills.
-- `crates/openhuman-core/src/agent/harness/session/turn/context.rs` and `.../turn/tools.rs` — the per-turn `workflows` list handed to `PromptContext`; `refresh_workflows` reloads it from the workspace when a `WorkflowsChanged` event is drained.
+- `crates/openhuman-core/src/agent/session_host/turn/context.rs` and `.../turn/tools.rs` — the per-turn `workflows` list handed to `PromptContext`; `refresh_workflows` reloads it from the workspace when a `WorkflowsChanged` event is drained.
- `crates/openhuman-core/src/agent/tools/run_workflow.rs` — the separate `run_workflow`/`AwaitWorkflowTool` launch path.
- `crates/openhuman-core/src/core/all.rs` — controller registry wiring for `skills`, `skill_registry`, and `skill_runtime`.
@@ -65,7 +65,7 @@ Behavior tests live beside their modules as `*_tests.rs` (e.g. `ops_tests.rs` an
`e2e_plumbing_tests.rs` and `e2e_run_tests.rs` are mock-LLM end-to-end tests: plumbing (create → registry round-trip, orchestrator turn calling `list_workflows`/`run_workflow`, `await_run_outcome` polling) and run execution (`spawn_workflow_run_background` → terminal `DONE` → `await_run_outcome`, `#[ignore]`d and serial because they set the process-global `OPENHUMAN_WORKSPACE`).
-Catalog refresh in a live session (`refresh_workflows`) is covered by `crates/openhuman-core/src/agent/harness/session/session_builder_and_listener_tests.rs`.
+Catalog refresh in a live session (`refresh_workflows`) is covered by `crates/openhuman-core/src/agent/session_host/session_builder_and_listener_tests.rs`.
## Notes
diff --git a/crates/openhuman-core/src/skills/ops_create.rs b/crates/openhuman-core/src/skills/ops_create.rs
index 8b181194e5..9f405a13ac 100644
--- a/crates/openhuman-core/src/skills/ops_create.rs
+++ b/crates/openhuman-core/src/skills/ops_create.rs
@@ -406,7 +406,7 @@ pub(crate) fn create_workflow_inner(
.ok_or_else(|| format!("created skill '{slug}' but failed to re-discover"))?;
// Notify live agent sessions so they pick up the new skill in their
- // `## Installed Skills` catalogue (see `Agent::refresh_workflows`).
+ // `## Installed Skills` catalogue (see `OpenHumanSessionHost::refresh_workflows`).
crate::core::bus::BUS.publish(crate::core::events::DomainEvent::WorkflowsChanged {
reason: "create".to_string(),
});
diff --git a/crates/openhuman-core/src/skills/ops_discover/api.rs b/crates/openhuman-core/src/skills/ops_discover/api.rs
index a500fb7f4c..c45ec45bdd 100644
--- a/crates/openhuman-core/src/skills/ops_discover/api.rs
+++ b/crates/openhuman-core/src/skills/ops_discover/api.rs
@@ -55,7 +55,7 @@ pub fn discovery_home_dir() -> Option<PathBuf> {
///
/// Delegates to [`discover_workflows`] with the current user's home directory
/// so user-scope skills (`~/.openhuman/skills/`, `~/.agents/skills/`) are
-/// surfaced for existing production callers (`agent::harness::session::builder`,
+/// surfaced for existing production callers (`agent::session_host::builder`,
/// `channels::runtime::startup`). Previously this shim passed `None` for the
/// home directory, which silently dropped user-installed skills from the
/// main runtime path.
diff --git a/crates/openhuman-core/src/skills/ops_install/fetch.rs b/crates/openhuman-core/src/skills/ops_install/fetch.rs
index 03121c60c1..1c86e0a7d5 100644
--- a/crates/openhuman-core/src/skills/ops_install/fetch.rs
+++ b/crates/openhuman-core/src/skills/ops_install/fetch.rs
@@ -396,7 +396,7 @@ pub(crate) async fn install_workflow_from_url_with_home(
let stderr = parse_warnings.join("\n");
// Notify live agent sessions so they refresh their `## Installed Skills`
- // catalogue mid-conversation (see `Agent::refresh_workflows`).
+ // catalogue mid-conversation (see `OpenHumanSessionHost::refresh_workflows`).
crate::core::bus::BUS.publish(crate::core::events::DomainEvent::WorkflowsChanged {
reason: "install".to_string(),
});
diff --git a/crates/openhuman-core/src/skills/ops_install/uninstall.rs b/crates/openhuman-core/src/skills/ops_install/uninstall.rs
index e49644359c..a43cd8c06d 100644
--- a/crates/openhuman-core/src/skills/ops_install/uninstall.rs
+++ b/crates/openhuman-core/src/skills/ops_install/uninstall.rs
@@ -165,7 +165,7 @@ pub fn uninstall_workflow(
.map_err(|e| format!("remove {} failed: {e}", canonical_candidate.display()))?;
// Notify live agent sessions to drop the removed skill from their
- // `## Installed Skills` catalogue (see `Agent::refresh_workflows`).
+ // `## Installed Skills` catalogue (see `OpenHumanSessionHost::refresh_workflows`).
crate::core::bus::BUS.publish(crate::core::events::DomainEvent::WorkflowsChanged {
reason: "uninstall".to_string(),
});
diff --git a/crates/openhuman-core/src/skills/runtime/run_machinery.rs b/crates/openhuman-core/src/skills/runtime/run_machinery.rs
index b8aae4e632..78b3083a17 100644
--- a/crates/openhuman-core/src/skills/runtime/run_machinery.rs
+++ b/crates/openhuman-core/src/skills/runtime/run_machinery.rs
@@ -7,8 +7,8 @@
use serde_json::Value;
-use crate::agent::harness::session::Agent;
use crate::agent::harness::subagent_runner::with_autonomous_iter_cap;
+use crate::agent::session_host::OpenHumanSessionHost;
use crate::config::Config;
use crate::skills::{preflight, registry, run_log};
@@ -182,19 +182,20 @@ pub async fn spawn_workflow_run_background(
if config.http_request.allowed_domains.is_empty() {
config.http_request.allowed_domains = vec!["*".to_string()];
}
- let mut agent = match Agent::from_config_for_agent(&config, "orchestrator") {
- Ok(a) => a,
- Err(e) => {
- let _ = run_log::write_footer(
- &log_path,
- "FAILED",
- 0,
- &format!("build agent: {e:#}"),
- )
- .await;
- return;
- }
- };
+ let mut agent =
+ match OpenHumanSessionHost::from_config_for_agent(&config, "orchestrator") {
+ Ok(a) => a,
+ Err(e) => {
+ let _ = run_log::write_footer(
+ &log_path,
+ "FAILED",
+ 0,
+ &format!("build agent: {e:#}"),
+ )
+ .await;
+ return;
+ }
+ };
// Issue #4868 — apply the workflow-run iteration budget AFTER
// construction. The session builder now stamps `orchestrator`'s
// definition cap (15) onto the agent; a full workflow run
diff --git a/crates/openhuman-core/src/tools/README.md b/crates/openhuman-core/src/tools/README.md
index 0d1f274fa6..aea6165e6d 100644
--- a/crates/openhuman-core/src/tools/README.md
+++ b/crates/openhuman-core/src/tools/README.md
@@ -115,7 +115,7 @@ None. No `store.rs`; the module holds no persisted state. Tools that persist (me
## Used by
- `crates/openhuman-core/src/core/all.rs` — registers the `tools` RPC controllers + schemas.
-- `crate::agent` harness (`agent/harness/session/builder/`, `subagent_runner`, `agent/tools/*`) and the `crate::agent::tinyagents` seam (`CanonicalSharedToolAdapter`, `ToolPolicyMiddleware`) — primary consumers; build the registry and execute/police tools on the tinyagents harness path.
+- `crate::agent` harness (`agent/session_host/builder/`, `subagent_runner`, `agent/tools/*`) and the `crate::agent::tinyagents` seam (`CanonicalSharedToolAdapter`, `ToolPolicyMiddleware`) — primary consumers; build the registry and execute/police tools on the tinyagents harness path.
- `crate::channels::runtime::dispatch::routing` — calls `orchestrator_tools::collect_orchestrator_tools` to build per-subagent orchestrator tool sets.
- `crate::tools::agent_policy`, `crate::security::approval` — read tool metadata (category, external-effect) for policy/approval decisions.
- `crate::tools::registry` (reads `all_tools_controller_schemas`) and `crate::mcp::server` (reuses `SEARXNG_MAX_RESULTS` / `normalize_categories` for its stdio tool specs).
diff --git a/crates/openhuman-core/src/tools/agent_policy/README.md b/crates/openhuman-core/src/tools/agent_policy/README.md
index 54923c7a73..09e2608b2a 100644
--- a/crates/openhuman-core/src/tools/agent_policy/README.md
+++ b/crates/openhuman-core/src/tools/agent_policy/README.md
@@ -47,11 +47,11 @@ Re-exported from `mod.rs`:
## Used by
-- `crates/openhuman-core/src/agent/harness/session/builder/builder_build.rs` — builds two snapshots with `build_session_from_refs`: the session's `tool_policy_session` (with the role visibility filter) and a `channel_policy_session` without it, used to derive the sub-agent tool ceiling.
-- `crates/openhuman-core/src/agent/harness/session/builder/mod.rs` — `visible_tool_specs_for_policy` filters prompt-visible specs with `decision_for(name).blocks_execution()`.
-- `crates/openhuman-core/src/agent/harness/session/runtime/accessors.rs` — `rebuild_tool_policy_session` re-runs `build_session_from_refs` after `hide_tools`.
-- `crates/openhuman-core/src/agent/harness/session/turn/context.rs` — calls `render_tool_policy_boundary(&session, 2048)` and appends the block to the end of the system prompt.
-- `crates/openhuman-core/src/agent/harness/session/types.rs` — carries `tool_policy_session` on the session.
+- `crates/openhuman-core/src/agent/session_host/builder/builder_build.rs` — builds two snapshots with `build_session_from_refs`: the session's `tool_policy_session` (with the role visibility filter) and a `channel_policy_session` without it, used to derive the sub-agent tool ceiling.
+- `crates/openhuman-core/src/agent/session_host/builder/mod.rs` — `visible_tool_specs_for_policy` filters prompt-visible specs with `decision_for(name).blocks_execution()`.
+- `crates/openhuman-core/src/agent/session_host/runtime/accessors.rs` — `rebuild_tool_policy_session` re-runs `build_session_from_refs` after `hide_tools`.
+- `crates/openhuman-core/src/agent/session_host/turn/context.rs` — calls `render_tool_policy_boundary(&session, 2048)` and appends the block to the end of the system prompt.
+- `crates/openhuman-core/src/agent/session_host/types.rs` — carries `tool_policy_session` on the session.
- `crates/openhuman-core/src/agent/tinyagents/middleware/tool_policy.rs` — `ToolPolicyMiddleware` is the runtime enforcement point: `is_denied()` for direct calls, `blocks_execution()` for the `use_skill` route. The snapshot reaches it through `ToolPolicyEnforcement` in `agent/tinyagents/turn_policy.rs`.
- `crates/openhuman-core/src/agent/tinyagents/host/security_gate.rs` — `SecurityGate::with_tool_policy` accepts an `Arc<ToolPolicySession>` and maps its actions to gate verdicts.
- `crates/openhuman-core/src/config/schema/agent.rs` — the `channel_permissions` field docs describe the engine's fallback semantics.
diff --git a/crates/openhuman-core/src/tools/agent_policy/engine.rs b/crates/openhuman-core/src/tools/agent_policy/engine.rs
index 0607824529..665178bff3 100644
--- a/crates/openhuman-core/src/tools/agent_policy/engine.rs
+++ b/crates/openhuman-core/src/tools/agent_policy/engine.rs
@@ -36,7 +36,7 @@ impl ToolPolicyEngine {
///
/// A session agent's callable surface is split across two `Arc`s — the
/// durable registry and the freshly-synthesised delegation set (see
- /// `Agent::synthesized_tools`). Both must be classified, or a delegate tool
+ /// `OpenHumanSessionHost::synthesized_tools`). Both must be classified, or a delegate tool
/// the model can see and call would carry no policy decision at all and
/// fall through the per-channel permission gate.
pub fn build_session_from_refs(
diff --git a/crates/openhuman-core/src/tools/impl/README.md b/crates/openhuman-core/src/tools/impl/README.md
index 455432cb5a..49ad2ef52a 100644
--- a/crates/openhuman-core/src/tools/impl/README.md
+++ b/crates/openhuman-core/src/tools/impl/README.md
@@ -35,7 +35,7 @@ tested but no production assembly site constructs it today.
| `network/` | `HttpRequestTool`, `WebFetchTool`, `CurlTool`, `GitbooksSearchTool`, `GitbooksGetPageTool`, `GmailUnsubscribeTool`, and under the `mcp` Cargo feature `McpListServersTool`, `McpListToolsTool`, `McpCallTool`, `McpSetupSearchTool`, `McpSetupGetTool`, `McpSetupInstallAndConnectTool`, `McpSetupRequestSecretTool`, `McpSetupTestConnectionTool`; `url_guard.rs` is the shared SSRF/allowlist validator, not a tool | `http_request`, `web_fetch`, `curl`, `gmail_unsubscribe` always registered; `gitbooks_*` need `gitbooks.enabled` and, when the active profile sets an `mcp_allowlist`, an entry named `gitbooks`; the `mcp_setup_*` tools register whenever the `mcp` feature is on; `mcp_list_servers`/`mcp_list_tools`/`mcp_call_tool` register only when the static `[[mcp_client.servers]]` registry (after the profile allowlist) is non-empty |
| `document/` (feature `documents`) | `DocumentTool` (`generate_document`) | always registered when compiled. Builds `.docx` bytes via the pure-Rust `engine` module (`docx-rs`, no subprocess) inside `spawn_blocking` + `tokio::time::timeout`; allocates the artifact with `agent::artifacts::create_artifact` (kind `Document`), persists `args.json` next to it for the failed-card Retry path, then `finalize_artifact` or `fail_artifact` |
| `presentation/` (feature `documents`) | `PresentationTool` (`generate_presentation`) | always registered when compiled. Same shape as `document/` with `ppt-rs` producing `.pptx` and kind `Presentation` |
-| `meta/` | `ToolSearchTool` (`tool_search`, name constant `TOOL_SEARCH_NAME`), `ToolSearchIndex`, `ToolSearchHandle`, `strip_deferred_from_visible`, `bind_tool_search_index`; `collapse` helpers (`resolve`, `merge_action_schemas`, `args_without_action`, `strictest_permission`, `any_external_effect`, `unknown_action_message`, `CollapsedAction`) | not registered: nothing in `tools/ops.rs` or the session builder constructs `ToolSearchTool`, and `strip_deferred_from_visible`/`bind_tool_search_index` have no production caller, so `ToolExposure::Deferred` (declared by e.g. `integrations/tools/stock_prices.rs`) is not enforced today; only `Hidden` is filtered in `agent/harness/session/builder/factory.rs`. The `collapse` helpers are used by `cron/tools/collapsed.rs` and `memory/tools/collapsed.rs` to merge a multi-action tool's per-action schemas and permissions into one entry |
+| `meta/` | `ToolSearchTool` (`tool_search`, name constant `TOOL_SEARCH_NAME`), `ToolSearchIndex`, `ToolSearchHandle`, `strip_deferred_from_visible`, `bind_tool_search_index`; `collapse` helpers (`resolve`, `merge_action_schemas`, `args_without_action`, `strictest_permission`, `any_external_effect`, `unknown_action_message`, `CollapsedAction`) | not registered: nothing in `tools/ops.rs` or the session builder constructs `ToolSearchTool`, and `strip_deferred_from_visible`/`bind_tool_search_index` have no production caller, so `ToolExposure::Deferred` (declared by e.g. `integrations/tools/stock_prices.rs`) is not enforced today; only `Hidden` is filtered in `agent/session_host/builder/factory.rs`. The `collapse` helpers are used by `cron/tools/collapsed.rs` and `memory/tools/collapsed.rs` to merge a multi-action tool's per-action schemas and permissions into one entry |
## Notes
diff --git a/crates/openhuman-core/src/tools/orchestrator_tools.rs b/crates/openhuman-core/src/tools/orchestrator_tools.rs
index bd8927dd63..2c5ddae29b 100644
--- a/crates/openhuman-core/src/tools/orchestrator_tools.rs
+++ b/crates/openhuman-core/src/tools/orchestrator_tools.rs
@@ -21,7 +21,7 @@
//! descriptions automatically stay in sync with the definitions and
//! never drift from a hardcoded table.
//!
-//! Called from [`crate::agent::harness::session::builder`] at
+//! Called from [`crate::agent::session_host::builder`] at
//! agent-build time, with the orchestrator's own definition, the global
//! registry (for delegation target lookups), and the current list of
//! connected Composio integrations.
diff --git a/crates/openhuman-core/src/tools/toolpacks/README.md b/crates/openhuman-core/src/tools/toolpacks/README.md
index db69c4546f..ee4ac20bff 100644
--- a/crates/openhuman-core/src/tools/toolpacks/README.md
+++ b/crates/openhuman-core/src/tools/toolpacks/README.md
@@ -97,14 +97,14 @@ to that delegate, not a second skill runtime.
tool's `host_extension`.
- `core/runtime/builder.rs` and `core/runtime/context.rs` —
`CoreBuilder::tool_groups` and the ambient `ToolGroups` on `CoreContext`.
-- `agent/harness/session/builder/` — `builder_build.rs` strips packed names
+- `agent/session_host/builder/` — `builder_build.rs` strips packed names
from the agent's visible set and binds both registries once the tool `Arc`s
exist; `mod.rs` calls `scope_use_skill_spec` so the advertised `use_skill`
spec lists only packs this session can call something in, and drops the
spec entirely when that is none.
-- `agent/harness/session/turn/tools.rs` — rebinds the synthesized registry
+- `agent/session_host/turn/tools.rs` — rebinds the synthesized registry
after every delegation refresh and re-strips packed names;
- `agent/harness/session/runtime/accessors.rs` re-strips after
+ `agent/session_host/runtime/accessors.rs` re-strips after
materializing the visible set.
- `agent/tinyagents/middleware/tool_policy.rs` — after
the permission gates, intercepts the disclosure half of a `use_skill` call
diff --git a/crates/openhuman-core/src/tools/toolpacks/toolpacks_tests.rs b/crates/openhuman-core/src/tools/toolpacks/toolpacks_tests.rs
index db7315a72f..faaded2ef8 100644
--- a/crates/openhuman-core/src/tools/toolpacks/toolpacks_tests.rs
+++ b/crates/openhuman-core/src/tools/toolpacks/toolpacks_tests.rs
@@ -104,7 +104,7 @@ fn find<'a>(tools: &'a [Box<dyn Tool>], name: &str) -> &'a dyn Tool {
/// vector, the packed tool in the separate synthesised one.
///
/// This is not a contrived shape. Every `delegate_*` tool is synthesised into
-/// `Agent::synthesized_tools`, a different `Arc` from the durable registry
+/// `OpenHumanSessionHost::synthesized_tools`, a different `Arc` from the durable registry
/// (#6145), and seven delegates were already packed.
fn split_registries(
name: &'static str,
diff --git a/crates/openhuman-core/src/voice/realtime_harness/agent.rs b/crates/openhuman-core/src/voice/realtime_harness/agent.rs
index 276cc4a3e1..d6e899a97f 100644
--- a/crates/openhuman-core/src/voice/realtime_harness/agent.rs
+++ b/crates/openhuman-core/src/voice/realtime_harness/agent.rs
@@ -1,5 +1,5 @@
//! Building and running the per-turn voice orchestrator: a fresh, isolated
-//! `Agent` pinned to a fast non-thinking model, seeded from the relayed
+//! `OpenHumanSessionHost` pinned to a fast non-thinking model, seeded from the relayed
//! history, run under the hard per-turn ceiling with the same chat-scoped
//! approval surface web chat installs.
@@ -8,8 +8,8 @@ use std::time::Duration;
use log::{info, warn};
use serde_json::Value;
-use crate::agent::harness::session::Agent;
use crate::agent::progress::AgentProgress;
+use crate::agent::session_host::OpenHumanSessionHost;
use crate::agent::turn_origin::{with_origin, AgentTurnOrigin};
use super::chat_delivery::{VOICE_CHAT_CLIENT_ID, VOICE_CHAT_THREAD_ID};
@@ -44,7 +44,7 @@ const VOICE_AGENT_NAME: &str = "voice";
/// whole budget *thinking* before its first word. `chat-v1` (DeepSeek-V4-Flash,
/// thinking off) is a short-turn, tool-capable SKU: the master still routes
/// delegation through the prompt (per-turn classification is disabled — see the
-/// model pin in `agent/harness/session/turn/core.rs`), so tool turns keep working
+/// model pin in `agent/session_host/turn/core.rs`), so tool turns keep working
/// while spoken replies start in ~1s instead of ~6s. Reasoning models are the
/// wrong tool for a latency-capped realtime channel.
const VOICE_MODEL: &str = "chat-v1";
@@ -96,9 +96,9 @@ async fn build_voice_agent(
correlation_id: &str,
messages: &[Value],
prompt: &str,
-) -> Result<Agent, String> {
+) -> Result<OpenHumanSessionHost, String> {
let config = crate::config::ops::load_config_with_timeout().await?;
- let mut agent = Agent::from_config_for_agent(&config, "orchestrator")
+ let mut agent = OpenHumanSessionHost::from_config_for_agent(&config, "orchestrator")
.map_err(|e| format!("orchestrator build failed: {e}"))?;
agent.set_event_context(format!("voice_{correlation_id}"), "voice_agent");
// Isolate the voice transcript namespace from the chat orchestrator so a
@@ -127,7 +127,7 @@ async fn build_voice_agent(
/// Run the orchestrator turn under the hard per-turn ceiling. The streaming sink
/// must already be attached; deltas flow out while this runs.
async fn run_single_with_timeout(
- agent: &mut Agent,
+ agent: &mut OpenHumanSessionHost,
correlation_id: &str,
prompt: &str,
) -> Result<String, String> {
diff --git a/crates/openhuman-core/src/voice/realtime_harness/prompt.rs b/crates/openhuman-core/src/voice/realtime_harness/prompt.rs
index d2838fad29..ee6fec751f 100644
--- a/crates/openhuman-core/src/voice/realtime_harness/prompt.rs
+++ b/crates/openhuman-core/src/voice/realtime_harness/prompt.rs
@@ -15,7 +15,7 @@ pub(super) const VOICE_READBACK_PREFIX: &str =
"Please read the following to me, word for word, and say nothing else:";
/// Convert an OpenAI-style `messages` array into `(role, content)` history pairs
-/// for [`Agent::seed_resume_from_messages`]. Drops `system` turns — the relayed
+/// for [`OpenHumanSessionHost::seed_resume_from_messages`]. Drops `system` turns — the relayed
/// system prompt is the ElevenLabs agent's, not ours — and flattens multimodal
/// content the same way [`extract_prompt`] does. Pure + unit-tested.
pub(super) fn messages_to_history_pairs(messages: &[Value]) -> Vec<(String, String)> {
diff --git a/crates/openhuman-core/src/web_chat/event_bus_tests.rs b/crates/openhuman-core/src/web_chat/event_bus_tests.rs
index 74815df45d..ec41760f3d 100644
--- a/crates/openhuman-core/src/web_chat/event_bus_tests.rs
+++ b/crates/openhuman-core/src/web_chat/event_bus_tests.rs
@@ -48,7 +48,7 @@ async fn find_egress_web_event(
.and_then(|s| s.as_str())
== Some(marker) =>
{
- return ev
+ return ev;
}
Ok(_) => continue,
Err(broadcast::error::RecvError::Lagged(_)) => continue,
diff --git a/crates/openhuman-core/src/web_chat/mod.rs b/crates/openhuman-core/src/web_chat/mod.rs
index 882eb52ccf..838c5fe802 100644
--- a/crates/openhuman-core/src/web_chat/mod.rs
+++ b/crates/openhuman-core/src/web_chat/mod.rs
@@ -42,10 +42,9 @@ pub(crate) use web_errors::classify_inference_error;
#[cfg(any(test, debug_assertions))]
#[allow(unused_imports)]
pub(crate) use web_errors::{
- ClassifiedError, extract_provider_error_detail, extract_provider_name,
- generic_inference_error_user_message, is_action_budget_exhausted, is_fallback_chain_exhausted,
- is_non_retryable_rate_limit_text, parse_retry_after_secs_from_str, retry_after_hint,
- with_provider_detail,
+ extract_provider_error_detail, extract_provider_name, generic_inference_error_user_message,
+ is_action_budget_exhausted, is_fallback_chain_exhausted, is_non_retryable_rate_limit_text,
+ parse_retry_after_secs_from_str, retry_after_hint, with_provider_detail, ClassifiedError,
};
// Public API — event bus
@@ -108,11 +107,11 @@ pub(crate) use web_errors::{
// Test helpers (debug/test builds only)
#[cfg(any(test, debug_assertions))]
-pub use ops::RUN_CHAT_TASK_TEST_LOCK;
-#[cfg(any(test, debug_assertions))]
pub use ops::set_test_forced_run_chat_task_error;
#[cfg(any(test, debug_assertions))]
-pub use ops::{TestRunChatTaskBlock, set_test_run_chat_task_block};
+pub use ops::RUN_CHAT_TASK_TEST_LOCK;
+#[cfg(any(test, debug_assertions))]
+pub use ops::{set_test_run_chat_task_block, TestRunChatTaskBlock};
#[cfg(any(test, debug_assertions))]
#[path = "mod_test_support_tests.rs"]
diff --git a/crates/openhuman-core/src/web_chat/ops.rs b/crates/openhuman-core/src/web_chat/ops.rs
index 7bad3de183..9ba894ce0e 100644
--- a/crates/openhuman-core/src/web_chat/ops.rs
+++ b/crates/openhuman-core/src/web_chat/ops.rs
@@ -13,8 +13,8 @@ mod test_hooks;
mod turn_guards;
pub(super) use budget_correlation::{
- BudgetCorrelation, classify_budget_correlation, clear_budget_signal, has_fresh_budget_signal,
- record_budget_signal,
+ classify_budget_correlation, clear_budget_signal, has_fresh_budget_signal,
+ record_budget_signal, BudgetCorrelation,
};
pub use channel_ops::{
@@ -24,22 +24,22 @@ pub use channel_ops::{
pub use start_chat::start_chat;
-pub(super) use state::THREAD_SESSIONS;
#[cfg(test)]
pub use state::drain_queued_turns_for_test;
#[cfg(any(test, debug_assertions))]
pub use state::parallel_in_flight_entries_for_test;
+pub(super) use state::THREAD_SESSIONS;
pub use state::{cancel_should_target, in_flight_entries_for_test, invalidate_thread_sessions};
pub(crate) use state::{event_session_id_for, key_for};
+#[cfg(any(test, debug_assertions))]
+pub use test_hooks::set_test_forced_run_chat_task_error;
#[cfg(any(test, debug_assertions))]
pub use test_hooks::RUN_CHAT_TASK_TEST_LOCK;
#[cfg(any(test, debug_assertions))]
-pub use test_hooks::set_test_forced_run_chat_task_error;
+pub use test_hooks::{set_test_run_chat_task_block, TestRunChatTaskBlock};
#[cfg(any(test, debug_assertions))]
pub(super) use test_hooks::{TEST_FORCED_RUN_CHAT_TASK_ERROR, TEST_RUN_CHAT_TASK_BLOCK};
-#[cfg(any(test, debug_assertions))]
-pub use test_hooks::{TestRunChatTaskBlock, set_test_run_chat_task_block};
pub(crate) use turn_guards::sentry_suppression_reason;
#[cfg(test)]
diff --git a/crates/openhuman-core/src/web_chat/ops/start_chat.rs b/crates/openhuman-core/src/web_chat/ops/start_chat.rs
index 5ce8f62437..4fb36b2d7a 100644
--- a/crates/openhuman-core/src/web_chat/ops/start_chat.rs
+++ b/crates/openhuman-core/src/web_chat/ops/start_chat.rs
@@ -12,7 +12,7 @@ use uuid::Uuid;
use crate::core::events::DomainEvent;
use crate::core::socketio::WebChannelEvent;
use crate::security::prompt_injection::{
- PromptEnforcementAction, PromptEnforcementContext, enforce_prompt_input,
+ enforce_prompt_input, PromptEnforcementAction, PromptEnforcementContext,
};
use super::super::event_bus::publish_web_channel_event;
@@ -20,7 +20,7 @@ use super::super::run_task::run_chat_task;
use super::super::types::{ChatRequestMetadata, InFlightEntry, QueueMode};
use super::super::web_errors::classify_inference_error;
use super::parallel_turn::spawn_parallel_turn;
-use super::state::{IN_FLIGHT, cancel_in_flight_gracefully, key_for};
+use super::state::{cancel_in_flight_gracefully, key_for, IN_FLIGHT};
use super::turn_guards::{
run_turn_under_cancel_and_deadline, sentry_suppression_reason, timeout_bound_tag,
};
diff --git a/crates/openhuman-core/src/web_chat/progress_bridge.rs b/crates/openhuman-core/src/web_chat/progress_bridge.rs
index 16800b7b4a..380e24dc8c 100644
--- a/crates/openhuman-core/src/web_chat/progress_bridge.rs
+++ b/crates/openhuman-core/src/web_chat/progress_bridge.rs
@@ -274,10 +274,10 @@ async fn shadow_compare_journal_projection(
Ok(observations) => observations,
Err(err) => {
log::warn!(
- "[agent-tracing][journal-shadow] read failed request_id={} journal_run_id={} err={err}",
- request_id,
- journal_run_id
- );
+ "[agent-tracing][journal-shadow] read failed request_id={} journal_run_id={} err={err}",
+ request_id,
+ journal_run_id
+ );
return None;
}
};
diff --git a/crates/openhuman-core/src/web_chat/run_task.rs b/crates/openhuman-core/src/web_chat/run_task.rs
index 9af1b360a2..27b001b216 100644
--- a/crates/openhuman-core/src/web_chat/run_task.rs
+++ b/crates/openhuman-core/src/web_chat/run_task.rs
@@ -10,7 +10,7 @@ use tinyagents_harness::run_queue::RunQueue;
use crate::config::rpc as config_rpc;
use crate::threads::turn_state::TurnStateStore;
-use super::ops::{BudgetCorrelation, THREAD_SESSIONS, key_for};
+use super::ops::{key_for, BudgetCorrelation, THREAD_SESSIONS};
use super::progress_bridge::spawn_progress_bridge;
use super::session::{
build_session_agent, build_session_fingerprint, normalize_model_override, pick_target_agent_id,
diff --git a/crates/openhuman-core/src/web_chat/schemas.rs b/crates/openhuman-core/src/web_chat/schemas.rs
index aace6fd1c5..543de7302b 100644
--- a/crates/openhuman-core/src/web_chat/schemas.rs
+++ b/crates/openhuman-core/src/web_chat/schemas.rs
@@ -59,9 +59,18 @@ pub fn schemas(function: &str) -> ControllerSchema {
"locale",
"Optional BCP-47 UI locale (e.g. 'ar', 'zh-CN'). Drives the \"reply in this language\" system-prompt directive.",
),
- optional_bool("speak_reply", "When true, the agent's final reply is spoken via TTS (for PTT and similar background voice flows)."),
- optional_string("source", "Origin of the message: \"ptt\" | \"dictation\" | \"type\" | other. Used for analytics + downstream metadata."),
- optional_u64("session_id", "Optional caller-provided correlation id (PTT session id)."),
+ optional_bool(
+ "speak_reply",
+ "When true, the agent's final reply is spoken via TTS (for PTT and similar background voice flows).",
+ ),
+ optional_string(
+ "source",
+ "Origin of the message: \"ptt\" | \"dictation\" | \"type\" | other. Used for analytics + downstream metadata.",
+ ),
+ optional_u64(
+ "session_id",
+ "Optional caller-provided correlation id (PTT session id).",
+ ),
optional_string(
"queue_mode",
"Queue mode: 'interrupt' (default), 'steer', 'followup', 'collect', or 'parallel'.",
diff --git a/crates/openhuman-core/src/web_chat/session.rs b/crates/openhuman-core/src/web_chat/session.rs
index 4aa5950c8a..6a4b731428 100644
--- a/crates/openhuman-core/src/web_chat/session.rs
+++ b/crates/openhuman-core/src/web_chat/session.rs
@@ -3,7 +3,7 @@
//! `SessionCacheFingerprint` that decides whether a cached agent can be
//! reused for the next turn on a thread.
-use crate::agent::Agent;
+use crate::agent::OpenHumanSessionHost;
use crate::config::Config;
use serde_json::json;
@@ -49,7 +49,7 @@ pub(super) fn build_session_agent(
model_override: Option<String>,
temperature: Option<f64>,
locale: Option<&str>,
-) -> Result<Agent, String> {
+) -> Result<OpenHumanSessionHost, String> {
let mut effective = config.clone();
if let Some(model) = model_override {
effective.default_model = Some(model);
@@ -78,7 +78,7 @@ pub(super) fn build_session_agent(
);
}
- let agent_result = Agent::from_config_for_agent(&effective, target_agent_id);
+ let agent_result = OpenHumanSessionHost::from_config_for_agent(&effective, target_agent_id);
agent_result
.map(|mut agent| {
diff --git a/crates/openhuman-core/src/web_chat/types.rs b/crates/openhuman-core/src/web_chat/types.rs
index fc9b4a5201..6b1fa72c0a 100644
--- a/crates/openhuman-core/src/web_chat/types.rs
+++ b/crates/openhuman-core/src/web_chat/types.rs
@@ -6,7 +6,7 @@
use serde::Deserialize;
use tinyagents_harness::run_queue::QueueLane;
-use crate::agent::Agent;
+use crate::agent::OpenHumanSessionHost;
/// How a web request arriving during an active turn is handled.
///
@@ -72,7 +72,7 @@ pub(crate) struct SessionCacheFingerprint {
}
pub(super) struct SessionEntry {
- pub(super) agent: Agent,
+ pub(super) agent: OpenHumanSessionHost,
pub(super) fingerprint: SessionCacheFingerprint,
}
diff --git a/crates/openhuman-core/src/web_chat/web_tests.rs b/crates/openhuman-core/src/web_chat/web_tests.rs
index 7264560b95..bfaa7cacc8 100644
--- a/crates/openhuman-core/src/web_chat/web_tests.rs
+++ b/crates/openhuman-core/src/web_chat/web_tests.rs
@@ -1,5 +1,4 @@
use super::{
- ChatRequestMetadata, ClassifiedError, TestRunChatTaskBlock, WebChatParams,
all_web_channel_controller_schemas, all_web_channel_registered_controllers, cancel_chat,
channel_web_cancel, channel_web_queue_clear, channel_web_queue_status,
classify_inference_error, compose_system_prompt_suffix, drain_queued_turns_for_test,
@@ -9,13 +8,14 @@ use super::{
normalize_model_override, optional_f64, optional_string, parallel_in_flight_entries_for_test,
provider_role_for_model_override, required_string, schemas, sentry_suppression_reason,
set_test_forced_run_chat_task_error, set_test_run_chat_task_block, start_chat,
- subscribe_web_channel_events,
+ subscribe_web_channel_events, ChatRequestMetadata, ClassifiedError, TestRunChatTaskBlock,
+ WebChatParams,
};
use crate::core::TypeSchema;
-use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::Arc;
use tinyagents_harness::run_queue::QueueLane;
-use tokio::time::{Duration, timeout};
+use tokio::time::{timeout, Duration};
// Serializes every test that drives `start_chat` with the process-global
// `run_chat_task` test hooks (forced error / forced block) or the
diff --git a/crates/openhuman-core/src/web_chat/web_tests_queue_acceptance_tests.rs b/crates/openhuman-core/src/web_chat/web_tests_queue_acceptance_tests.rs
index 7255aa4224..ec0320110f 100644
--- a/crates/openhuman-core/src/web_chat/web_tests_queue_acceptance_tests.rs
+++ b/crates/openhuman-core/src/web_chat/web_tests_queue_acceptance_tests.rs
@@ -148,11 +148,9 @@ async fn terminal_turn_dispatches_followup_as_a_fresh_host_turn() {
.any(|(key, request_id)| key == thread_id && request_id != &primary_request_id)
})
.await;
- assert!(
- entries
- .iter()
- .any(|(key, request_id)| key == thread_id && request_id != &primary_request_id)
- );
+ assert!(entries
+ .iter()
+ .any(|(key, request_id)| key == thread_id && request_id != &primary_request_id));
cancel_parked_turn(thread_id, &block).await;
}
@@ -209,21 +207,15 @@ async fn cancellation_discards_pending_lanes_before_a_replacement_turn() {
.await
.expect("replacement queue status should be available");
assert_eq!(replacement.value["total"], 0);
- assert!(
- drain_queued_turns_for_test(thread_id, QueueLane::Followup)
- .await
- .is_empty()
- );
- assert!(
- drain_queued_turns_for_test(thread_id, QueueLane::Steer)
- .await
- .is_empty()
- );
- assert!(
- drain_queued_turns_for_test(thread_id, QueueLane::Collect)
- .await
- .is_empty()
- );
+ assert!(drain_queued_turns_for_test(thread_id, QueueLane::Followup)
+ .await
+ .is_empty());
+ assert!(drain_queued_turns_for_test(thread_id, QueueLane::Steer)
+ .await
+ .is_empty());
+ assert!(drain_queued_turns_for_test(thread_id, QueueLane::Collect)
+ .await
+ .is_empty());
cancel_parked_turn(thread_id, &replacement_block).await;
}
diff --git a/crates/openhuman-core/src/web_chat/web_tests_rate_limit_classification_tests.rs b/crates/openhuman-core/src/web_chat/web_tests_rate_limit_classification_tests.rs
index 4d8b0fed0a..2861fcfb10 100644
--- a/crates/openhuman-core/src/web_chat/web_tests_rate_limit_classification_tests.rs
+++ b/crates/openhuman-core/src/web_chat/web_tests_rate_limit_classification_tests.rs
@@ -5,8 +5,7 @@ fn both_timeout_shapes_still_render_the_same_user_facing_copy() {
// The telemetry split must not change what the user sees: either way the
// turn ran out of time and the graceful `turn_timeout` copy is correct.
let marker = super::super::web_errors::turn_timeout_error_message(600);
- let harness =
- "run timed out: tool call for run `agent_turn` exceeded its remaining wall-clock budget (26375 ms)";
+ let harness = "run timed out: tool call for run `agent_turn` exceeded its remaining wall-clock budget (26375 ms)";
assert_eq!(classify_inference_error(&marker).error_type, "turn_timeout");
assert_eq!(classify_inference_error(harness).error_type, "turn_timeout");
}
diff --git a/crates/openhuman-core/src/web_chat/web_tests_start_chat_ingress_tests.rs b/crates/openhuman-core/src/web_chat/web_tests_start_chat_ingress_tests.rs
index e45492aaee..39d68eeb53 100644
--- a/crates/openhuman-core/src/web_chat/web_tests_start_chat_ingress_tests.rs
+++ b/crates/openhuman-core/src/web_chat/web_tests_start_chat_ingress_tests.rs
@@ -604,7 +604,10 @@ fn classify_inference_error_harness_wall_clock_timeout_is_turn_timeout() {
retryable,
..
} = classify_inference_error(raw);
- assert_eq!(category, "turn_timeout", "must classify as turn_timeout: {raw}");
+ assert_eq!(
+ category, "turn_timeout",
+ "must classify as turn_timeout: {raw}"
+ );
assert!(retryable, "a wall-clock timeout is retryable: {raw}");
}
}
diff --git a/docs/TEST-COVERAGE-MATRIX.md b/docs/TEST-COVERAGE-MATRIX.md
index edb8ec451f..bd27cd0916 100644
--- a/docs/TEST-COVERAGE-MATRIX.md
+++ b/docs/TEST-COVERAGE-MATRIX.md
@@ -223,7 +223,7 @@ End-to-end coverage of the agent harness via the web-chat RPC surface against an
| 4.4.10 | Provider Error Retry | RI | `tests/agent_harness_e2e.rs` | ✅ | First upstream 500 retried by ReliableProvider; second succeeds |
| 4.4.11 | Inference Phase Transitions | WD | `app/test/e2e/specs/agent-harness-behaviors.spec.ts` | ✅ | Redux `inferenceStatusByThread` observes `subagent` phase then clears to idle |
| 4.4.12 | Tool Timeline Completeness | WD | `app/test/e2e/specs/agent-harness-behaviors.spec.ts` | ✅ | Timeline entries carry id/name/status/round; subagent row reaches `success`; rounds non-decreasing |
-| 4.4.13 | Grounded Close (no final text / breaker halt) | RU | `crates/openhuman-core/src/agent/harness/session/turn_final_reply_grounding_tests.rs`, `crates/openhuman-core/src/agent/harness/session/turn_checkpoint_tests.rs` | ✅ | Tool-records wrap-up, check rejects intent narration / contradicted claims, fallback quotes failure messages; breaker stop note never shown verbatim (#6278, #6279) |
+| 4.4.13 | Grounded Close (no final text / breaker halt) | RU | `crates/openhuman-core/src/agent/session_host/turn_final_reply_grounding_tests.rs`, `crates/openhuman-core/src/agent/session_host/turn_checkpoint_tests.rs` | ✅ | Tool-records wrap-up, check rejects intent narration / contradicted claims, fallback quotes failure messages; breaker stop note never shown verbatim (#6278, #6279) |
---
@@ -353,16 +353,16 @@ End-to-end coverage of the agent harness via the web-chat RPC surface against an
| ID | Feature | Layer | Test path(s) | Status | Notes |
| ----- | ------------------------------------------ | ----- | -------------------------------------------------------------------------------------------------------------- | ------ | ----------------------------------------------------------------------- |
| 8.4.1 | Save Preference (general / situational) | RU | `crates/openhuman-core/src/agent/tools/save_preference_tests.rs` | ✅ | `save_preference` tool → `user_pref_{general,situational}`, topic-keyed |
-| 8.4.2 | Lane A — Standing Prefs in System Prompt | RU | `crates/openhuman-core/src/agent/learning/prompt_sections.rs`, `crates/openhuman-core/src/agent/harness/session/turn_tests.rs` | ✅ | General prefs rendered into the system prompt at thread start |
-| 8.4.3 | Lane B — Situational Recall (vector-gated) | RU | `crates/openhuman-core/src/agent/harness/session/turn_learned_context_and_announcements_tests.rs::situational_preference_reaches_the_model_through_driver_memory`, `crates/openhuman-core/src/agent/experience/ops_tests.rs::recall_relevant_by_vector_*`, `crates/openhuman-core/src/memory/preferences/preferences_tests.rs` | ✅ | Per-turn through the production `DriverMemory` handle (#6041); relevant query injects, below-floor suppresses |
+| 8.4.2 | Lane A — Standing Prefs in System Prompt | RU | `crates/openhuman-core/src/agent/learning/prompt_sections.rs`, `crates/openhuman-core/src/agent/session_host/turn_tests.rs` | ✅ | General prefs rendered into the system prompt at thread start |
+| 8.4.3 | Lane B — Situational Recall (vector-gated) | RU | `crates/openhuman-core/src/agent/session_host/turn_learned_context_and_announcements_tests.rs::situational_preference_reaches_the_model_through_driver_memory`, `crates/openhuman-core/src/agent/experience/ops_tests.rs::recall_relevant_by_vector_*`, `crates/openhuman-core/src/memory/preferences/preferences_tests.rs` | ✅ | Per-turn through the production `DriverMemory` handle (#6041); relevant query injects, below-floor suppresses |
| 8.4.4 | Same-Topic Contradiction (replace) | RU | `crates/openhuman-core/src/agent/tools/save_preference_tests.rs::recategorising_moves_pref_between_namespaces` | ✅ | `ON CONFLICT REPLACE`; a topic lives in exactly one scope |
| 8.4.5 | Cross-Topic Contradiction Surfacing | RU | `crates/openhuman-core/src/agent/tools/save_preference_tests.rs::save_surfaces_related_preference_for_contradiction_check` | ✅ | Related prefs surfaced in the tool result for the chat agent to resolve |
| 8.4.6 | vector_chunks Model-Signature Recall Guard | RU | `vendor/tinymemory/crates/tinymemory-core/src/store/namespace_store/query_tests.rs::vector_recall_excludes_other_model_signature` (vendored `tinymemory`) | ✅ | Excludes cross-model vectors; dim-guards legacy rows |
-| 8.4.7 | Lane C — Auto-recall of User Facts (gated) | RU | `crates/openhuman-core/src/memory/auto_recall/{gate_tests,auto_recall_tests}.rs`, `crates/openhuman-core/src/agent/harness/session/turn_auto_recall_tests.rs::auto_recall_*` | ✅ | #6040: lexical gate, bounded `fast_retrieve` via the guard, block rides the user message; `hooks.auto_recall` switch |
+| 8.4.7 | Lane C — Auto-recall of User Facts (gated) | RU | `crates/openhuman-core/src/memory/auto_recall/{gate_tests,auto_recall_tests}.rs`, `crates/openhuman-core/src/agent/session_host/turn_auto_recall_tests.rs::auto_recall_*` | ✅ | #6040: lexical gate, bounded `fast_retrieve` via the guard, block rides the user message; `hooks.auto_recall` switch |
| 8.4.8 | Lane C Boot Warm-up | RU | `crates/openhuman-core/src/memory/auto_recall/warm_tests.rs` | ✅ | One bounded retrieval after the memory module loads; failure/timeout are log-only |
| 8.4.9 | Memory-Access Instruction (ungated) | RU | `crates/openhuman-core/src/agent/learning/prompt_sections_tests_2_tests.rs` | ✅ | Added whenever a retrieval tool is visible, independent of `learning.enabled`; forbids claiming absence unsearched |
-| 8.4.10 | Memory-Write Instruction + `memory_store` defaults | RU | `crates/openhuman-core/src/agent/learning/prompt_sections_tests_2_tests.rs::memory_write_*`, `crates/openhuman-core/src/agent/learning/prompt_sections_tests_2_tests.rs::write_tool_gate_*`, `crates/openhuman-core/src/agent/harness/session/builder/builder_tests_memory_write_instruction_tests.rs::memory_write_instruction_*`, `crates/openhuman-core/src/memory/tools/store_tests.rs::resolve_*` | ✅ | #6048: "remember X" must be a write before the reply; section keyed on write-tool visibility, not `learning.enabled`; `memory_store` namespace/key optional |
-| 8.4.11 | Lane C — Notes leg (`global` namespace) + hint | RU | `crates/openhuman-core/src/memory/auto_recall/notes_lane_tests.rs` (all), `crates/openhuman-core/src/memory/auto_recall/auto_recall_tests.rs::from_guard_reads_through_the_guarded_retrieval_family`, `crates/openhuman-core/src/agent/harness/session/turn_auto_recall_tests.rs::auto_recall_injects_a_note_written_by_memory_store_when_the_tree_is_empty` | ✅ | #6063: a fact `memory_store` filed in `global` is recalled through `recall_namespace_scored` beside the tree walk (per-leg budget, absolute 0.35 floor, notes render first, `ExternalSync`/connector-keyed notes wrapped); block opens with the "pre-fetched, not a search" hint |
+| 8.4.10 | Memory-Write Instruction + `memory_store` defaults | RU | `crates/openhuman-core/src/agent/learning/prompt_sections_tests_2_tests.rs::memory_write_*`, `crates/openhuman-core/src/agent/learning/prompt_sections_tests_2_tests.rs::write_tool_gate_*`, `crates/openhuman-core/src/agent/session_host/builder/builder_tests_memory_write_instruction_tests.rs::memory_write_instruction_*`, `crates/openhuman-core/src/memory/tools/store_tests.rs::resolve_*` | ✅ | #6048: "remember X" must be a write before the reply; section keyed on write-tool visibility, not `learning.enabled`; `memory_store` namespace/key optional |
+| 8.4.11 | Lane C — Notes leg (`global` namespace) + hint | RU | `crates/openhuman-core/src/memory/auto_recall/notes_lane_tests.rs` (all), `crates/openhuman-core/src/memory/auto_recall/auto_recall_tests.rs::from_guard_reads_through_the_guarded_retrieval_family`, `crates/openhuman-core/src/agent/session_host/turn_auto_recall_tests.rs::auto_recall_injects_a_note_written_by_memory_store_when_the_tree_is_empty` | ✅ | #6063: a fact `memory_store` filed in `global` is recalled through `recall_namespace_scored` beside the tree walk (per-leg budget, absolute 0.35 floor, notes render first, `ExternalSync`/connector-keyed notes wrapped); block opens with the "pre-fetched, not a search" hint |
### 8.5 Long-term Goals
@@ -499,7 +499,7 @@ End-to-end coverage of the agent harness via the web-chat RPC surface against an
| 11.1.12 | MCP UI surface + setup-agent client | VU/RU | `app/src/components/channels/mcp/InstallDialog.test.tsx`, `app/src/components/channels/mcp/McpServersTab.test.tsx`, `app/src/services/api/mcpClientsApi.test.ts`, `crates/openhuman-core/src/mcp/registry/ops.rs`, `crates/openhuman-core/src/mcp/registry/setup_ops_tests.rs`, `vendor/tinymcp/crates/tinymcp/src/registry/{curation,sources}/` (vendored `tinymcp`) (#3039, #4272; `mcpSetupApi.test.ts` was removed in #5095) | ✅ | Skills `?tab=mcp` renders `McpServersTab` (not Coming Soon); auto-connect on install (best-effort); typed `mcpSetupApi` wrapper; curated "perfect server" catalog (declared website + named credential) with official-vendor badge + official-first order; namespace-stripped relevance search + server-side Stdio/Hosted transport filter; clickable Website/Repo links; wired connection health toolbar (Retry all / Disconnect all) (#4272) |
| 11.1.13 | MCP HTTP-remote auth (token / Bearer / OAuth) + redirect resolution | RU/VU | `vendor/tinymcp/crates/tinymcp/src/registry/connections/` (`build_http_auth*`, `resolve_final_url`), `vendor/tinymcp/crates/tinymcp/src/registry/oauth/` (PKCE/token/bundle/callback port) (vendored `tinymcp`), `app/src/components/channels/mcp/ConnectAuthModal.test.tsx` (#3495) | ✅ | Bearer/raw scheme + custom headers; redirect-final-URL resolved before auth; OAuth dynamic client registration + PKCE + refresh; tokens MERGED into stored env; credentials stored encrypted locally, never sent to backend |
| 11.1.14 | MCP "Help & configure" assistant | VU/RU | `app/src/components/channels/mcp/ConfigAssistantPanel.test.tsx`, `app/src/components/channels/mcp/ConfigHelpModal.test.tsx`, `crates/openhuman-core/src/mcp/registry/ops.rs` (`invoke_config_assist_agent`) (#3495) | ✅ | Server-specific prompt offered as a one-click "Get step-by-step setup help" action (on-demand, no longer auto-run on open — #4272), running an agentic turn scoped to web_search_tool/web_fetch/curl only; markdown-rendered reply; per-MCP chat persisted while on the detail page |
-| 11.1.15 | Agent uses connected MCP servers in chat | RU | `crates/openhuman-core/src/agent/registry/agents/loader.rs` (`orchestrator_subagents_include_mcp_agent`, `mcp_agent_drives_connected_servers_without_install_or_shell`, `planner_has_readonly_mcp_discovery_not_execute`), `crates/openhuman-core/src/agent/registry/agents/orchestrator/prompt.rs` (`connected_mcp_block_*`), `crates/openhuman-core/src/agent/harness/session/turn_tests.rs` (`mcp_announcement_fires_once_for_new_server`), `tests/agent_harness_e2e.rs` (`agent_calls_a_tool_on_an_mcp_server_installed_from_the_registry`: orchestrator → `use_skill` → `use_mcp_server` → `mcp_registry_tool_call`), `crates/openhuman-core/src/mcp/registry/tools_tests.rs`, `vendor/tinymcp/crates/tinymcp/src/registry/connections/` (vendored `tinymcp`) (#3495) | ✅ | `use_mcp_server` delegate → `mcp_agent` worker (discover→list→call); `mcp_registry_list_tools` read-only discovery; orchestrator `## Connected MCP Servers` prompt block + mid-session connect announcement on the user turn; planner read-only MCP discovery (no `tool_call`) |
+| 11.1.15 | Agent uses connected MCP servers in chat | RU | `crates/openhuman-core/src/agent/registry/agents/loader.rs` (`orchestrator_subagents_include_mcp_agent`, `mcp_agent_drives_connected_servers_without_install_or_shell`, `planner_has_readonly_mcp_discovery_not_execute`), `crates/openhuman-core/src/agent/registry/agents/orchestrator/prompt.rs` (`connected_mcp_block_*`), `crates/openhuman-core/src/agent/session_host/turn_tests.rs` (`mcp_announcement_fires_once_for_new_server`), `tests/agent_harness_e2e.rs` (`agent_calls_a_tool_on_an_mcp_server_installed_from_the_registry`: orchestrator → `use_skill` → `use_mcp_server` → `mcp_registry_tool_call`), `crates/openhuman-core/src/mcp/registry/tools_tests.rs`, `vendor/tinymcp/crates/tinymcp/src/registry/connections/` (vendored `tinymcp`) (#3495) | ✅ | `use_mcp_server` delegate → `mcp_agent` worker (discover→list→call); `mcp_registry_list_tools` read-only discovery; orchestrator `## Connected MCP Servers` prompt block + mid-session connect announcement on the user turn; planner read-only MCP discovery (no `tool_call`) |
| 11.1.16 | MCP supervisor observability (Event Log + notifications) | RU | `crates/openhuman-core/src/mcp/registry/supervisor_events_tests.rs`, `crates/openhuman-core/src/core/events_tests.rs` (`mcp_supervisor_events_*`, `mcp_lifecycle_events_*`), `crates/openhuman-core/src/desktop/notifications/bus_tests_2_tests.rs` (`mcp_*`, `*_workspace*`, `an_outage_is_filed_under_its_own_workspace_not_the_bridge_s`, `*_announced`), `app/src/components/settings/panels/__tests__/EventLogPanel.test.tsx` (detail line + filter), `vendor/tinymcp/crates/tinymcp/src/registry/supervisor/test.rs` ("The report" section) (#5931) | ✅ | `tinymcp::Supervisor::tick` returns a `TickReport`; the host maps it to `McpServer{ProbeTimedOut,TransportDropped,Reconnected,ReconnectFailed,Parked}` domain events (Event Log, `mcp_client` domain, server name in the agent column, failure reason via `DomainEvent::log_detail`) and the notification bridge notifies only on the first failed reconnect of an episode, on recovery after failures, and on a parked server — filing each under the workspace the event names and announcing it only when that workspace is live, since one process supervises every workspace it has opened and the bridge's own binding may be the stale half after a switch |
<!-- 11.1.9 Vault Markdown Writes — removed: Knowledge Vaults dropped (vault domain + VaultPanel deleted). -->
diff --git a/docs/plans/extract-remaining-harness-session-and-subagent-runner.md b/docs/plans/extract-remaining-harness-session-and-subagent-runner.md
index f3e0136ec2..aefdbb6305 100644
--- a/docs/plans/extract-remaining-harness-session-and-subagent-runner.md
+++ b/docs/plans/extract-remaining-harness-session-and-subagent-runner.md
@@ -337,7 +337,7 @@ deleted module declarations and forwarding surfaces. These final production
grep gates must be empty (negative checker fixtures are the sole exception):
```bash
-rg -n 'agent::harness::session|harness::session|mod session;' crates tests
+rg -n 'agent::session_host|tinyagents_runtime::Session' crates tests
rg -n 'agent::harness::subagent_runner|harness::subagent_runner|mod subagent_runner;' crates tests
rg -n 'pub use .*tinyagents_(runtime|session|orchestration)|type .*=(.*tinyagents)' crates/openhuman-core/src
rg -n 'struct RunQueue|impl RunQueue|harness/run_queue' crates/openhuman-core/src/agent
diff --git a/docs/plans/migrate-agent-sessions-to-tinyagents-session.md b/docs/plans/migrate-agent-sessions-to-tinyagents-session.md
index 1c2800d336..ec0ff8822f 100644
--- a/docs/plans/migrate-agent-sessions-to-tinyagents-session.md
+++ b/docs/plans/migrate-agent-sessions-to-tinyagents-session.md
@@ -53,7 +53,7 @@ the new orchestration crate, or a provider dialect for transcript persistence.
OpenHuman replaces its local types and helpers with direct imports, then
implements only an adapter at the existing host boundary where conversion from
`ChatMessage` to crate-native messages is unavoidable. Do not retain
-`agent::harness::session::transcript::*` as a public facade.
+`agent::session_host::codec::*` as the OpenHuman transcript adapter.
## File map
diff --git a/docs/prompt-evals.md b/docs/prompt-evals.md
index fa08812cf9..d0b8625bad 100644
--- a/docs/prompt-evals.md
+++ b/docs/prompt-evals.md
@@ -94,7 +94,7 @@ Scoring reads only artifacts the run already writes, in this order:
`max_input_tokens` ceiling per case. The judge call is not included.
4. **Judge** (cases with `"judge": true`). The production close-verification
rubric from `close_verification_prompt` in
- `agent/harness/session/turn_checkpoint.rs`, copied into `cases.json` rather
+ `agent/session_host/turn_checkpoint.rs`, copied into `cases.json` rather
than widening that `pub(super)` function for an on-demand script. The
verdict is read as `parse_close_verdict` reads it: the last standalone
`ACCEPT`/`REJECT` token wins, so `UNACCEPTABLE` is not `ACCEPT`.
diff --git a/gitbooks/developing/architecture/agent-harness.md b/gitbooks/developing/architecture/agent-harness.md
index 01723d954e..8fadcb81a1 100644
--- a/gitbooks/developing/architecture/agent-harness.md
+++ b/gitbooks/developing/architecture/agent-harness.md
@@ -66,7 +66,7 @@ runtime-wide".
> (`run_turn_via_tinyagents_shared`). The legacy `run_turn_engine`, the three
> hand-rolled loops, `turn_engine_adapter`, and the custom `agent_graph/` engine
> described later in this page have been **removed**; the surviving shared seam,
-> `TurnProgress`, lives in `agent/harness/session/tool_progress.rs`. The dead
+> `TurnProgress`, lives in `agent/session_host/tool_progress.rs`. The dead
> `token_budget.rs` (context trimming is now `MessageTrimMiddleware`) and the
> vestigial `interrupt.rs` fence (cancellation is the tinyagents steering channel)
> are gone; policy **stop hooks** (budget / thread-goal / iteration caps) now fire
@@ -223,7 +223,7 @@ loop {
Every iteration emits a real-time `AgentProgress` event so the UI can render token-by-token streaming, "calling tool X" status, and per-iteration cost updates.
-**One engine, three entry points.** The loop lives in one place (the tinyagents `AgentHarness`, entered via `run_turn_via_tinyagents_shared` in `crates/openhuman-core/src/agent/tinyagents/mod.rs`) and every caller drives it: the chat turn (`harness/session/turn/core.rs` → `session/turn/graph.rs`), the channel/CLI bus turn (`harness/graph.rs`), and spawned sub-agents (`harness/subagent_runner/ops/graph.rs`). What varies per caller is supplied through the adapter seam: OpenHuman's provider wrapped as a `ChatModel` (`tinyagents/model.rs`), tools wrapped as tinyagents `Tool`s (`tinyagents/tools.rs`), an event bridge that projects harness `AgentEvent`s into `AgentProgress` + cost telemetry (`tinyagents/observability.rs`), `RunPolicy::unknown_tool` for hallucinated tool recovery, and a named middleware stack (`tinyagents/middleware.rs`) carrying the OpenHuman cross-cuts: approval/security gating (`ApprovalSecurityMiddleware`), tool policy and CLI/RPC-only denial (`ToolPolicyMiddleware`, `CliRpcOnlyMiddleware`), malformed-argument recovery (`ArgRecoveryMiddleware`), cost budget pre-checks (`CostBudgetMiddleware`), the repeated-tool-failure circuit breaker (`RepeatedToolFailureMiddleware`), and context trimming/compression. Policy stop hooks fire through `StopHookMiddleware` (`tinyagents/stop_hooks.rs`). The surviving OpenHuman-owned seam, `TurnProgress`, lives in `harness/session/tool_progress.rs`. Because all three entry points assemble the same harness, they can't drift.
+**One engine, three entry points.** The loop lives in one place (the tinyagents `AgentHarness`, entered via `run_turn_via_tinyagents_shared` in `crates/openhuman-core/src/agent/tinyagents/mod.rs`) and every caller drives it: the chat turn (`session_host/turn/core.rs` → `session/turn/graph.rs`), the channel/CLI bus turn (`harness/graph.rs`), and spawned sub-agents (`harness/subagent_runner/ops/graph.rs`). What varies per caller is supplied through the adapter seam: OpenHuman's provider wrapped as a `ChatModel` (`tinyagents/model.rs`), tools wrapped as tinyagents `Tool`s (`tinyagents/tools.rs`), an event bridge that projects harness `AgentEvent`s into `AgentProgress` + cost telemetry (`tinyagents/observability.rs`), `RunPolicy::unknown_tool` for hallucinated tool recovery, and a named middleware stack (`tinyagents/middleware.rs`) carrying the OpenHuman cross-cuts: approval/security gating (`ApprovalSecurityMiddleware`), tool policy and CLI/RPC-only denial (`ToolPolicyMiddleware`, `CliRpcOnlyMiddleware`), malformed-argument recovery (`ArgRecoveryMiddleware`), cost budget pre-checks (`CostBudgetMiddleware`), the repeated-tool-failure circuit breaker (`RepeatedToolFailureMiddleware`), and context trimming/compression. Policy stop hooks fire through `StopHookMiddleware` (`tinyagents/stop_hooks.rs`). The surviving OpenHuman-owned seam, `TurnProgress`, lives in `session_host/tool_progress.rs`. Because all three entry points assemble the same harness, they can't drift.
### Tool dispatch and tool-call dialects
@@ -525,7 +525,7 @@ The harness shell lives under `crates/openhuman-core/src/agent/`, with the tinya
| File / dir | What lives there |
| ---------------------------------------- | ------------------------------------------------------------------------------------------------------------- |
-| `harness/session/turn/core.rs` | `Agent::turn` - the lifecycle described above; routes into the tinyagents runner via `session/turn/graph.rs`. |
+| `session_host/turn/core.rs` | `Agent::turn` - the lifecycle described above; routes into the tinyagents runner via `session/turn/graph.rs`. |
| `../tinyagents/mod.rs` | `run_turn_via_tinyagents_shared` - the shared tinyagents harness assembly (the live loop). |
| `../tinyagents/middleware.rs` | The named OpenHuman middleware stack (approval/security, tool policy, recovery, budgets, circuit breaker). |
| `harness/graph.rs` | The channel/CLI bus turn route into the tinyagents runner. |
@@ -534,7 +534,7 @@ The harness shell lives under `crates/openhuman-core/src/agent/`, with the tinya
| `harness/definition.rs` | `AgentDefinition` - what an archetype declares. |
| `harness/subagent_runner/ops/runner.rs` | Integration-tool ranking uses canonical `tinyagents_harness::tool` APIs. |
| `../tinyagents/payload_summarizer.rs` | Oversized-tool-result detour. |
-| `harness/session/tool_progress.rs` | Surviving OpenHuman seam: `TurnProgress`. |
+| `session_host/tool_progress.rs` | Surviving OpenHuman seam: `TurnProgress`. |
| `message_convert.rs` | Concrete durable/provider conversion around canonical tool-call dialect APIs. |
| `triage/` | External-trigger classification + escalation. |
| `registry/agents/` | Built-in archetypes - one subdirectory per agent. |
@@ -596,7 +596,7 @@ Most agents reuse `blueprint::canonical_turn(id)` (the standard tool-calling loo
## Agent engine + orchestration on tinyagents (live)
-Every agent turn (chat via `harness/session/turn/core.rs`, channel/CLI via `harness/graph.rs`, and sub-agent via `harness/subagent_runner/ops/graph.rs`) drives through `crate::agent::tinyagents::run_turn_via_tinyagents_shared`, which runs the crate's `AgentHarness`. There is no in-house turn engine, tool loop, or routing gate left; dispatch is unconditional. The seam:
+Every agent turn (chat via `session_host/turn/core.rs`, channel/CLI via `harness/graph.rs`, and sub-agent via `harness/subagent_runner/ops/graph.rs`) drives through `crate::agent::tinyagents::run_turn_via_tinyagents_shared`, which runs the crate's `AgentHarness`. There is no in-house turn engine, tool loop, or routing gate left; dispatch is unconditional. The seam:
| File (`crates/openhuman-core/src/agent/tinyagents/`) | Role |
| ------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
diff --git a/scripts/ci/check-openhuman-rust-layout.mjs b/scripts/ci/check-openhuman-rust-layout.mjs
index 17c8aa52cc..bd2257387e 100644
--- a/scripts/ci/check-openhuman-rust-layout.mjs
+++ b/scripts/ci/check-openhuman-rust-layout.mjs
@@ -12,7 +12,11 @@ const LINE_LIMIT = 750;
// their current size makes the gate monotonic: they cannot grow, no new
// exception can appear, and deleting an entry is the only way to relax it.
const LEGACY_LIMITS = new Map([
- ["crates/openhuman-core/src/agent/harness/session/builder/factory.rs", 1552],
+ // 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", 1245],
["crates/openhuman-core/src/agent/harness/subagent_runner/ops/runner.rs", 1769],
["crates/openhuman-core/src/tools/ops.rs", 1502],
["crates/openhuman-core/src/web_chat/progress_bridge.rs", 1547],
diff --git a/scripts/prompt-eval/cases.json b/scripts/prompt-eval/cases.json
index 04adc6a42c..6350cb6000 100644
--- a/scripts/prompt-eval/cases.json
+++ b/scripts/prompt-eval/cases.json
@@ -1,7 +1,7 @@
{
"_comment": "Tier-2 prompt evals: real model, scored, on demand only. Never wired into CI. See docs/prompt-evals.md.",
"judge": {
- "_source": "Copied from close_verification_prompt in crates/openhuman-core/src/agent/harness/session/turn_checkpoint.rs (pub(super), deliberately not widened for this script). The Rust copy has a drift guard; if you edit the rules there, mirror them here.",
+ "_source": "Copied from close_verification_prompt in crates/openhuman-core/src/agent/session_host/turn_checkpoint.rs (pub(super), deliberately not widened for this script). The Rust copy has a drift guard; if you edit the rules there, mirror them here.",
"preamble": "You are checking a reply before it is shown to a user. Below are the user's request, the records of the tool calls made while handling it, and the reply.",
"rules": [
"The reply only says what the assistant will do or is about to do, instead of reporting what happened.",
diff --git a/tests/agent_builder_public.rs b/tests/agent_builder_public.rs
index 7268363c20..3fc90973c0 100644
--- a/tests/agent_builder_public.rs
+++ b/tests/agent_builder_public.rs
@@ -1,7 +1,7 @@
use anyhow::Result;
use async_trait::async_trait;
use openhuman_core::agent::prompts::SystemPromptBuilder;
-use openhuman_core::agent::Agent;
+use openhuman_core::agent::OpenHumanSessionHost;
use openhuman_core::memory::{Memory, MemoryCategory, MemoryEntry};
use openhuman_core::tinytools_agent::dialect::XmlDialect;
use tinytools::{Tool, ToolResult};
@@ -107,8 +107,8 @@ impl Memory for StubMemory {
}
}
-fn base_builder() -> openhuman_core::agent::AgentBuilder {
- Agent::builder()
+fn base_builder() -> openhuman_core::agent::SessionHostBuilder {
+ OpenHumanSessionHost::builder()
.chat_model(Arc::new(StubModel))
.tools(vec![
Box::new(StubTool("alpha")),
@@ -120,20 +120,20 @@ fn base_builder() -> openhuman_core::agent::AgentBuilder {
#[test]
fn builder_validates_required_fields() {
- let err = Agent::builder()
+ let err = OpenHumanSessionHost::builder()
.build()
.err()
.expect("missing tools should error");
assert!(err.to_string().contains("tools are required"));
- let err = Agent::builder()
+ let err = OpenHumanSessionHost::builder()
.tools(vec![Box::new(StubTool("alpha"))])
.build()
.err()
.expect("missing provider should error");
assert!(err.to_string().contains("provider is required"));
- let err = Agent::builder()
+ let err = OpenHumanSessionHost::builder()
.chat_model(Arc::new(StubModel))
.tools(vec![Box::new(StubTool("alpha"))])
.build()
@@ -141,7 +141,7 @@ fn builder_validates_required_fields() {
.expect("missing memory should error");
assert!(err.to_string().contains("memory is required"));
- let err = Agent::builder()
+ let err = OpenHumanSessionHost::builder()
.chat_model(Arc::new(StubModel))
.tools(vec![Box::new(StubTool("alpha"))])
.memory(Arc::new(StubMemory))
diff --git a/tests/agent_harness_e2e.rs b/tests/agent_harness_e2e.rs
index 4e638b4ec2..4a16d49411 100644
--- a/tests/agent_harness_e2e.rs
+++ b/tests/agent_harness_e2e.rs
@@ -1173,7 +1173,7 @@ async fn scheduling_clarification_flow_inner() {
// to "orchestrator asks the user itself", which never exercises the pause.
let scheduler_request = requests.get(1).map(Value::to_string).unwrap_or_default();
assert!(
- scheduler_request.contains("Scheduler Agent"),
+ scheduler_request.contains("Scheduler OpenHumanSessionHost"),
"request[1] did not carry the scheduler_agent prompt — schedule_task did not \
delegate; request: {scheduler_request}"
);
@@ -1841,7 +1841,7 @@ async fn approval_gate_timeout_inner() {
// `expression` arg (format!("{i}m ago")) gives a different hash each iteration,
// preventing REPEAT_OUTPUT_THRESHOLD from firing. Queuing beyond the
// definition-derived cap trips max_tool_iterations. AgentError::MaxIterationsExceeded →
-// "Agent exceeded maximum tool iterations (N)"
+// "OpenHumanSessionHost exceeded maximum tool iterations (N)"
// (error.rs:89-90; MAX_ITERATIONS_ERROR_PREFIX at error.rs:176).
//
// empty_provider_response:
@@ -1851,7 +1851,7 @@ async fn approval_gate_timeout_inner() {
// again." Lowercased → contains "empty". skips_sentry() = true for both
// variants (error.rs:148-153).
-/// Agent loops past max_tool_iterations (10) → user-facing max-iterations error,
+/// OpenHumanSessionHost loops past max_tool_iterations (10) → user-facing max-iterations error,
/// surfaced as a terminal event (not a hang, not a crash).
///
/// resolve_time (ops.rs:192, orchestrator/agent.toml:173) always returns
@@ -1907,14 +1907,14 @@ async fn max_iterations_exceeded_inner() {
// turn_checkpoint.rs:62 intercepts it and renders a user-friendly `chat_done`
// message: "I reached the tool-call limit for this turn ({max_iterations} steps),
// so I paused here." This is the reachable surface from the web-chat channel.
- // The lower-level display "Agent exceeded maximum tool iterations (N)" (error.rs:89-90,
+ // The lower-level display "OpenHumanSessionHost exceeded maximum tool iterations (N)" (error.rs:89-90,
// prefix const error.rs:176) is only visible in sub-agent checkpoints
// (checkpoint.rs:31-40), not in the top-level orchestrator turn.
assert!(
serialized.contains("tool-call limit")
|| serialized.contains("tool_call_limit")
|| serialized.contains("maximum tool iterations")
- || serialized.contains("Agent exceeded"),
+ || serialized.contains("OpenHumanSessionHost exceeded"),
"expected max-iterations surface (tool-call limit or similar); got: {serialized}"
);
@@ -2317,7 +2317,7 @@ async fn multi_hop_delegation_chain_inner() {
// ─── Task 10: Streaming tool-call accumulation (issue test 13) ───────────────
//
-// This module runs at the Agent level using a ScriptedProvider (same pattern as
+// This module runs at the OpenHumanSessionHost level using a ScriptedProvider (same pattern as
// tests/agent_session_turn_raw_coverage_e2e.rs). It does NOT use the HTTP
// scripted-upstream + SSE stack above: the RPC/SSE stack doesn't expose
// per-delta streaming observability that would let us assert the exact fragment
@@ -2359,7 +2359,7 @@ async fn multi_hop_delegation_chain_inner() {
mod streaming_support {
use async_trait::async_trait;
- use openhuman_core::agent::Agent;
+ use openhuman_core::agent::OpenHumanSessionHost;
use openhuman_core::config::{AgentConfig, ContextConfig};
use openhuman_core::memory::Memory;
use openhuman_core::tinytools_agent::dialect::NativeDialect;
@@ -2547,8 +2547,8 @@ mod streaming_support {
tools: Vec<Box<dyn Tool>>,
workspace_path: PathBuf,
config: AgentConfig,
- ) -> Agent {
- Agent::builder()
+ ) -> OpenHumanSessionHost {
+ OpenHumanSessionHost::builder()
.chat_model(provider)
.tools(tools)
.memory(memory_for_workspace_s(&workspace_path))
@@ -4149,7 +4149,7 @@ mod tool_policy_boundary_placement {
use anyhow::Result;
use async_trait::async_trait;
use openhuman_core::agent::prompts::LearnedContextData;
- use openhuman_core::agent::Agent;
+ use openhuman_core::agent::OpenHumanSessionHost;
use openhuman_core::config::AgentConfig;
use openhuman_core::memory::{
Memory, MemoryCategory, MemoryEntry, NamespaceSummary as MemoryNamespaceSummary, RecallOpts,
@@ -4253,7 +4253,7 @@ mod tool_policy_boundary_placement {
.channel_permissions
.insert("boundary-channel".to_string(), "read_only".to_string());
- let agent = Agent::builder()
+ let agent = OpenHumanSessionHost::builder()
.chat_model(provider)
.tools(vec![
Box::new(ScopedTool {
@@ -4284,7 +4284,7 @@ mod tool_policy_boundary_placement {
/// the inference backend's automatic prefix cache everything behind it. It
/// also replaced each agent's opening persona line with a constant heading.
///
- /// This drives the real `Agent::build_system_prompt`. The four tests #5821
+ /// This drives the real `OpenHumanSessionHost::build_system_prompt`. The four tests #5821
/// shipped exercise the extracted pure helper `append_tool_policy_boundary`
/// and would all still pass if `build_system_prompt` stopped calling it; the
/// one existing test that goes through the builder,
diff --git a/tests/agent_turn_overrides_e2e.rs b/tests/agent_turn_overrides_e2e.rs
index a06a6694de..8229ecf42d 100644
--- a/tests/agent_turn_overrides_e2e.rs
+++ b/tests/agent_turn_overrides_e2e.rs
@@ -8,7 +8,7 @@
//! block is absent, and `suppress_transcript_autoload` appears once, as `false`
//! (`:115`) — it is never exercised at all.
//!
-//! These drive a real `Agent::turn` against a scripted model and assert on what
+//! These drive a real `OpenHumanSessionHost::turn` against a scripted model and assert on what
//! actually reaches the provider.
//!
//! # Every test carries its own control
@@ -35,8 +35,8 @@ use std::sync::{Arc, Mutex, OnceLock};
use tempfile::TempDir;
use openhuman_core::agent::goals::{runtime as goal_runtime, store as goal_store};
-use openhuman_core::agent::harness::session::TurnOverrides;
-use openhuman_core::agent::Agent;
+use openhuman_core::agent::session_host::TurnOverrides;
+use openhuman_core::agent::OpenHumanSessionHost;
use openhuman_core::config::{AgentConfig, ContextConfig};
use tinyinference_llm::message::Message;
use tinyinference_llm::model::{
@@ -232,8 +232,8 @@ fn agent_with(
tools: Vec<Box<dyn Tool>>,
workspace_path: PathBuf,
dispatcher: Box<dyn openhuman_core::tinytools_agent::dialect::ToolDialect>,
-) -> Agent {
- Agent::builder()
+) -> OpenHumanSessionHost {
+ OpenHumanSessionHost::builder()
.chat_model(model)
.tools(tools)
.memory(noop_memory::noop_memory())
diff --git a/tests/calendar_grounding_e2e.rs b/tests/calendar_grounding_e2e.rs
index 298c03298e..12a8f99809 100644
--- a/tests/calendar_grounding_e2e.rs
+++ b/tests/calendar_grounding_e2e.rs
@@ -1,6 +1,6 @@
use anyhow::Result;
use async_trait::async_trait;
-use openhuman_core::agent::Agent;
+use openhuman_core::agent::OpenHumanSessionHost;
use openhuman_core::tinytools_agent::dialect::NativeDialect;
use tinytools::{PermissionLevel, Tool, ToolResult};
@@ -108,7 +108,7 @@ async fn test_orchestrator_has_current_date_context() -> Result<()> {
let captured_messages = Arc::new(Mutex::new(Vec::new()));
let model = calendar_model(captured_messages.clone());
- let mut agent = Agent::builder()
+ let mut agent = OpenHumanSessionHost::builder()
.chat_model(model)
.tools(vec![Box::new(MockCalendarTool)])
.tool_dispatcher(Box::new(NativeDialect))
diff --git a/tests/raw_coverage/agent_harness_leftovers_raw_coverage_e2e.rs b/tests/raw_coverage/agent_harness_leftovers_raw_coverage_e2e.rs
index e3d0e085fa..29a286e210 100644
--- a/tests/raw_coverage/agent_harness_leftovers_raw_coverage_e2e.rs
+++ b/tests/raw_coverage/agent_harness_leftovers_raw_coverage_e2e.rs
@@ -8,7 +8,7 @@ use openhuman_core::agent::prompts::{
};
use openhuman_core::tinytools_agent::dialect::NativeDialect;
use openhuman_core::agent::harness::definition::AgentTier;
-use openhuman_core::agent::harness::session::Agent;
+use openhuman_core::agent::session_host::OpenHumanSessionHost;
use openhuman_core::agent::harness::{
run_subagent, with_parent_context, AgentDefinition, DefinitionSource, ModelSpec,
ParentExecutionContext, PromptSource, SandboxMode, SubagentRunOptions, ToolScope,
@@ -265,8 +265,8 @@ fn build_agent(
workspace: &Path,
provider: Arc<ScriptedModel>,
tools: Vec<Box<dyn Tool>>,
-) -> Result<Agent> {
- let mut agent = Agent::builder()
+) -> Result<OpenHumanSessionHost> {
+ let mut agent = OpenHumanSessionHost::builder()
.chat_model(provider)
.tools(tools)
.memory(Arc::new(StubMemory::default()))
@@ -478,19 +478,19 @@ async fn builder_reports_missing_required_fields_in_validation_order() -> Result
let tmp = TempDir::new()?;
let provider = ScriptedModel::new(vec![text_response("unused")]);
- let err = match Agent::builder().build() {
+ let err = match OpenHumanSessionHost::builder().build() {
Ok(_) => panic!("builder without tools should fail"),
Err(err) => err,
};
assert!(err.to_string().contains("tools are required"));
- let err = match Agent::builder().tools(Vec::new()).build() {
+ let err = match OpenHumanSessionHost::builder().tools(Vec::new()).build() {
Ok(_) => panic!("builder without provider should fail"),
Err(err) => err,
};
assert!(err.to_string().contains("provider is required"));
- let err = match Agent::builder()
+ let err = match OpenHumanSessionHost::builder()
.tools(Vec::new())
.chat_model(provider)
.workspace_dir(tmp.path().to_path_buf())
diff --git a/tests/raw_coverage/agent_harness_raw_coverage_e2e.rs b/tests/raw_coverage/agent_harness_raw_coverage_e2e.rs
index 183ab34376..798f1d5b68 100644
--- a/tests/raw_coverage/agent_harness_raw_coverage_e2e.rs
+++ b/tests/raw_coverage/agent_harness_raw_coverage_e2e.rs
@@ -2,7 +2,7 @@ use anyhow::Result;
use async_trait::async_trait;
use openhuman_core::tinytools_agent::dialect::NativeDialect;
use openhuman_core::agent::harness::definition::AgentDefinitionRegistry;
-use openhuman_core::agent::harness::session::Agent;
+use openhuman_core::agent::session_host::OpenHumanSessionHost;
use openhuman_core::agent::harness::{
run_subagent, with_parent_context, AgentDefinition, ParentExecutionContext, PromptSource,
SandboxMode, SubagentRunOptions, ToolScope,
@@ -230,7 +230,7 @@ fn agent_config() -> AgentConfig {
}
}
-fn build_agent(workspace: &Path, provider: Arc<ScriptedModel>, agent_name: &str) -> Result<Agent> {
+fn build_agent(workspace: &Path, provider: Arc<ScriptedModel>, agent_name: &str) -> Result<OpenHumanSessionHost> {
build_agent_with_tools(workspace, provider, agent_name, vec![Box::new(EchoTool)])
}
@@ -239,8 +239,8 @@ fn build_agent_with_tools(
provider: Arc<ScriptedModel>,
agent_name: &str,
tools: Vec<Box<dyn Tool>>,
-) -> Result<Agent> {
- let mut agent = Agent::builder()
+) -> Result<OpenHumanSessionHost> {
+ let mut agent = OpenHumanSessionHost::builder()
.chat_model(provider)
.tools(tools)
.memory(Arc::new(StubMemory))
diff --git a/tests/raw_coverage/agent_prompts_subagent_raw_coverage_e2e.rs b/tests/raw_coverage/agent_prompts_subagent_raw_coverage_e2e.rs
index 4000ac1865..d84d02e4be 100644
--- a/tests/raw_coverage/agent_prompts_subagent_raw_coverage_e2e.rs
+++ b/tests/raw_coverage/agent_prompts_subagent_raw_coverage_e2e.rs
@@ -1,7 +1,7 @@
use anyhow::Result;
use async_trait::async_trait;
use openhuman_core::tinytools_agent::dialect::NativeDialect;
-use openhuman_core::agent::harness::session::Agent;
+use openhuman_core::agent::session_host::OpenHumanSessionHost;
use openhuman_core::agent::harness::{
run_subagent, with_parent_context, AgentDefinition, DefinitionSource, ModelSpec,
ParentExecutionContext, PromptSource, SandboxMode, SubagentRunError, SubagentRunOptions,
@@ -477,19 +477,19 @@ fn subagent_prompt_renderer_covers_format_branches_and_missing_indices() {
fn agent_builder_validation_reports_each_required_component() {
let provider = ScriptedModel::new(vec![]);
- let err = match Agent::builder().build() {
+ let err = match OpenHumanSessionHost::builder().build() {
Ok(_) => panic!("builder without tools should fail"),
Err(err) => err.to_string(),
};
assert!(err.contains("tools are required"));
- let err = match Agent::builder().tools(Vec::new()).build() {
+ let err = match OpenHumanSessionHost::builder().tools(Vec::new()).build() {
Ok(_) => panic!("builder without provider should fail"),
Err(err) => err.to_string(),
};
assert!(err.contains("provider is required"));
- let err = match Agent::builder()
+ let err = match OpenHumanSessionHost::builder()
.tools(Vec::new())
.chat_model(provider.clone())
.build()
@@ -499,7 +499,7 @@ fn agent_builder_validation_reports_each_required_component() {
};
assert!(err.contains("memory is required"));
- let err = match Agent::builder()
+ let err = match OpenHumanSessionHost::builder()
.tools(Vec::new())
.chat_model(provider)
.memory(Arc::new(StubMemory))
@@ -510,7 +510,7 @@ fn agent_builder_validation_reports_each_required_component() {
};
assert!(err.contains("tool_dispatcher is required"));
- let agent = Agent::builder()
+ let agent = OpenHumanSessionHost::builder()
.tools(vec![tool("echo"), tool("echo")])
.chat_model(ScriptedModel::new(vec![]))
.memory(Arc::new(StubMemory))
diff --git a/tests/raw_coverage/agent_round26_raw_coverage_e2e.rs b/tests/raw_coverage/agent_round26_raw_coverage_e2e.rs
index 8ef2896894..26e4fd862a 100644
--- a/tests/raw_coverage/agent_round26_raw_coverage_e2e.rs
+++ b/tests/raw_coverage/agent_round26_raw_coverage_e2e.rs
@@ -10,7 +10,7 @@ use openhuman_core::agent::prompts::{
};
use openhuman_core::agent::debug::{dump_agent_prompt, DumpPromptOptions};
use openhuman_core::tinytools_agent::dialect::NativeDialect;
-use openhuman_core::agent::Agent;
+use openhuman_core::agent::OpenHumanSessionHost;
use openhuman_core::config::AgentConfig;
use openhuman_core::memory::{
Memory, MemoryCategory, MemoryEntry, NamespaceSummary, RecallOpts,
@@ -382,7 +382,7 @@ async fn builder_dedupes_visible_native_tools_and_seed_resume_bounds_history() -
let mut visible = HashSet::new();
visible.insert("round26_duplicate".to_string());
- let mut agent = Agent::builder()
+ let mut agent = OpenHumanSessionHost::builder()
.chat_model(provider.clone())
.tools(tools)
.visible_tool_names(visible)
diff --git a/tests/raw_coverage/agent_session_round24_raw_coverage_e2e.rs b/tests/raw_coverage/agent_session_round24_raw_coverage_e2e.rs
index 442e730b6a..9c37a2e374 100644
--- a/tests/raw_coverage/agent_session_round24_raw_coverage_e2e.rs
+++ b/tests/raw_coverage/agent_session_round24_raw_coverage_e2e.rs
@@ -2,7 +2,7 @@ use anyhow::Result;
use async_trait::async_trait;
use openhuman_core::tinytools_agent::dialect::XmlDialect;
use openhuman_core::agent::hooks::{PostTurnHook, TurnContext};
-use openhuman_core::agent::Agent;
+use openhuman_core::agent::OpenHumanSessionHost;
use openhuman_core::config::{AgentConfig, ContextConfig};
use openhuman_core::agent::prompts::{
ConnectedIntegration, LearnedContextData, PersonalityRosterEntry, PersonalityRosterSection,
@@ -421,7 +421,7 @@ async fn max_iteration_checkpoint_uses_deterministic_fallback_and_hooks() {
))],
);
- let mut agent = Agent::builder()
+ let mut agent = OpenHumanSessionHost::builder()
.chat_model(provider.clone())
.tools(vec![Box::new(Round24Tool {
calls: calls.clone(),
@@ -494,7 +494,7 @@ async fn max_iteration_checkpoint_uses_deterministic_fallback_and_hooks() {
#[tokio::test]
async fn builder_validation_and_system_prompt_cover_defaults_and_learning() {
let _env = env_lock();
- let missing_tools = match Agent::builder().build() {
+ let missing_tools = match OpenHumanSessionHost::builder().build() {
Ok(_) => panic!("builder without tools should fail"),
Err(err) => err,
};
@@ -508,7 +508,7 @@ async fn builder_validation_and_system_prompt_cover_defaults_and_learning() {
let calls = Arc::new(AtomicUsize::new(0));
let memory = RecordingMemory::new();
let provider = ScriptedModel::new(vec![text_response("learned final", None)]);
- let mut agent = Agent::builder()
+ let mut agent = OpenHumanSessionHost::builder()
.chat_model(provider.clone())
.tools(vec![Box::new(Round24Tool { calls })])
.memory(memory)
diff --git a/tests/raw_coverage/agent_session_turn_raw_coverage_e2e.rs b/tests/raw_coverage/agent_session_turn_raw_coverage_e2e.rs
index d9cf79ba9b..e0fbe3b734 100644
--- a/tests/raw_coverage/agent_session_turn_raw_coverage_e2e.rs
+++ b/tests/raw_coverage/agent_session_turn_raw_coverage_e2e.rs
@@ -14,7 +14,7 @@ use openhuman_core::agent::progress::AgentProgress;
use openhuman_core::agent::tool_policy::{
ToolPolicy, ToolPolicyDecision, ToolPolicyRequest,
};
-use openhuman_core::agent::Agent;
+use openhuman_core::agent::OpenHumanSessionHost;
use openhuman_core::config::{AgentConfig, Config, ContextConfig, MemoryConfig};
use openhuman_core::agent::messages::ConversationMessage;
use openhuman_core::memory::{
@@ -620,8 +620,8 @@ fn agent_with(
dispatcher: Box<dyn openhuman_core::tinytools_agent::dialect::ToolDialect>,
config: AgentConfig,
context_config: ContextConfig,
-) -> Agent {
- Agent::builder()
+) -> OpenHumanSessionHost {
+ OpenHumanSessionHost::builder()
.chat_model(model)
.tools(tools)
.memory(noop_memory::noop_memory())
@@ -832,7 +832,7 @@ async fn turn_citation_task_replaces_previous_handle_and_joins_successfully_inne
release_recall: Some(never_release_first),
recall_cancelled: Some(first_cancelled.clone()),
});
- let mut agent = Agent::builder()
+ let mut agent = OpenHumanSessionHost::builder()
.chat_model(ScriptedModel::new(vec![
text_response("first answer"),
text_response("second answer"),
@@ -922,7 +922,7 @@ async fn turn_xml_failures_checkpoint_policy_visibility_and_hooks_are_publicly_e
let hook_notify = Arc::new(Notify::new());
let mut channel_permissions = std::collections::HashMap::new();
channel_permissions.insert("round17-channel".to_string(), "read_only".to_string());
- let mut agent = Agent::builder()
+ let mut agent = OpenHumanSessionHost::builder()
.chat_model(provider.clone())
.tools(vec![
Round17Tool::boxed("round17_ok", "ok-output", ok_calls.clone()),
diff --git a/tests/raw_coverage/agent_tool_loop_raw_coverage_e2e.rs b/tests/raw_coverage/agent_tool_loop_raw_coverage_e2e.rs
index b9c32fec79..77ab7e9067 100644
--- a/tests/raw_coverage/agent_tool_loop_raw_coverage_e2e.rs
+++ b/tests/raw_coverage/agent_tool_loop_raw_coverage_e2e.rs
@@ -5,7 +5,7 @@ use openhuman_core::agent::bus::{
};
use openhuman_core::agent::debug::{dump_agent_prompt, DumpPromptOptions};
use openhuman_core::tinytools_agent::dialect::XmlDialect;
-use openhuman_core::agent::{Agent, AgentBuilder};
+use openhuman_core::agent::{OpenHumanSessionHost, SessionHostBuilder};
use openhuman_core::config::{AgentConfig, MultimodalConfig, MultimodalFileConfig};
use openhuman_core::agent::prompts::LearnedContextData;
use openhuman_core::agent::messages::ChatMessage;
@@ -582,7 +582,7 @@ async fn agent_builder_prompt_and_debug_dump_cover_public_session_paths() {
config.max_tool_iterations = 2;
config.max_history_messages = 4;
- let agent = AgentBuilder::new()
+ let agent = SessionHostBuilder::new()
.chat_model(provider)
.tools(vec![StaticTool::ok("echo", "ok")])
.memory(Arc::new(NoopMemory::default()))
@@ -623,7 +623,7 @@ async fn agent_turn_blank_final_response_is_typed_error() {
let workspace = round15_workspace("blank-final");
std::fs::create_dir_all(&workspace).unwrap();
let provider = ScriptedModel::new(vec![ModelResponse::assistant("")]);
- let mut agent = Agent::builder()
+ let mut agent = OpenHumanSessionHost::builder()
.chat_model(provider)
.tools(vec![])
.memory(Arc::new(NoopMemory::default()))
diff --git a/tests/raw_coverage/agent_turn_builder_leftovers_raw_coverage_e2e.rs b/tests/raw_coverage/agent_turn_builder_leftovers_raw_coverage_e2e.rs
index 024663e263..bd46819b72 100644
--- a/tests/raw_coverage/agent_turn_builder_leftovers_raw_coverage_e2e.rs
+++ b/tests/raw_coverage/agent_turn_builder_leftovers_raw_coverage_e2e.rs
@@ -2,7 +2,7 @@ use anyhow::Result;
use async_trait::async_trait;
use tinytools_agent::dialect::{NativeDialect, XmlDialect};
use openhuman_core::agent::hooks::{PostTurnHook, TurnContext};
-use openhuman_core::agent::Agent;
+use openhuman_core::agent::OpenHumanSessionHost;
use openhuman_core::config::{AgentConfig, ContextConfig};
use openhuman_core::agent::context::session_memory::SessionMemoryConfig;
use openhuman_core::memory::{
@@ -345,7 +345,7 @@ async fn native_turn_dedups_duplicate_tool_specs_and_executes_empty_arguments()
true,
);
- let mut agent = Agent::builder()
+ let mut agent = OpenHumanSessionHost::builder()
.chat_model(provider.clone())
.tools(vec![
tool(
@@ -411,7 +411,7 @@ async fn xml_turn_persists_tool_cycle_and_fires_failure_hook_context() {
false,
);
- let mut agent = Agent::builder()
+ let mut agent = OpenHumanSessionHost::builder()
.chat_model(provider)
.tools(vec![tool(
"round20_fail",
@@ -484,7 +484,7 @@ async fn session_memory_threshold_path_runs_only_after_successful_turn() {
false,
);
- let mut agent = Agent::builder()
+ let mut agent = OpenHumanSessionHost::builder()
.chat_model(provider)
.tools(vec![tool(
"round20_ok",
@@ -531,7 +531,7 @@ async fn session_memory_threshold_path_runs_only_after_successful_turn() {
let (_empty_tmp, empty_workspace) = workspace("empty-failed-turn");
let empty_provider = ScriptedModel::new(vec![text_response(" ", None)], false);
- let mut failed_agent = Agent::builder()
+ let mut failed_agent = OpenHumanSessionHost::builder()
.chat_model(empty_provider)
.tools(Vec::new())
.memory(RecordingMemory::new())
diff --git a/tests/raw_coverage/inference_agent_raw_coverage_e2e.rs b/tests/raw_coverage/inference_agent_raw_coverage_e2e.rs
index 24d058b1b0..60b73bbb88 100644
--- a/tests/raw_coverage/inference_agent_raw_coverage_e2e.rs
+++ b/tests/raw_coverage/inference_agent_raw_coverage_e2e.rs
@@ -92,7 +92,7 @@ use openhuman_core::agent::triage::routing::{
build_local_provider_with_config, ResolvedProvider,
};
use openhuman_core::agent::triage::{parse_triage_decision, ParseError, TriageAction};
-use openhuman_core::agent::Agent;
+use openhuman_core::agent::OpenHumanSessionHost;
use openhuman_core::agent::{
all_agent_controller_schemas, all_agent_registered_controllers,
};
@@ -781,8 +781,8 @@ async fn call(controller: &RegisteredController, params: Value) -> Result<Value,
(controller.handler)(params).await
}
-fn base_agent_builder() -> openhuman_core::agent::AgentBuilder {
- Agent::builder()
+fn base_agent_builder() -> openhuman_core::agent::SessionHostBuilder {
+ OpenHumanSessionHost::builder()
.chat_model(Arc::new(EchoModel))
.tools(vec![
Box::new(StubTool("alpha")),
@@ -1079,20 +1079,20 @@ async fn agent_registry_and_profile_controllers_cover_success_and_errors() {
#[test]
fn agent_builder_public_paths_cover_required_fields_defaults_and_filters() {
- let err = Agent::builder()
+ let err = OpenHumanSessionHost::builder()
.build()
.err()
.expect("missing tools should error");
assert!(err.to_string().contains("tools are required"));
- let err = Agent::builder()
+ let err = OpenHumanSessionHost::builder()
.tools(vec![Box::new(StubTool("alpha"))])
.build()
.err()
.expect("missing provider should error");
assert!(err.to_string().contains("provider is required"));
- let err = Agent::builder()
+ let err = OpenHumanSessionHost::builder()
.chat_model(Arc::new(EchoModel))
.tools(vec![Box::new(StubTool("alpha"))])
.build()
@@ -1100,7 +1100,7 @@ fn agent_builder_public_paths_cover_required_fields_defaults_and_filters() {
.expect("missing memory should error");
assert!(err.to_string().contains("memory is required"));
- let err = Agent::builder()
+ let err = OpenHumanSessionHost::builder()
.chat_model(Arc::new(EchoModel))
.tools(vec![Box::new(StubTool("alpha"))])
.memory(Arc::new(RecordingMemory::default()))
@@ -1168,7 +1168,7 @@ fn agent_definition_public_shapes_cover_serde_defaults_and_registry_replacement(
r#"
id = "coverage_agent"
when_to_use = "Exercise public definition shapes."
-display_name = "Coverage Agent"
+display_name = "Coverage OpenHumanSessionHost"
temperature = 0.33
disallowed_tools = ["dangerous"]
extra_tools = ["safe_extra"]
@@ -1192,7 +1192,7 @@ named = ["todo", "plan_exit"]
)
.expect("definition TOML");
- assert_eq!(parsed.display_name(), "Coverage Agent");
+ assert_eq!(parsed.display_name(), "Coverage OpenHumanSessionHost");
assert_eq!(parsed.model.resolve("parent-model"), "reasoning-v1");
assert_eq!(parsed.sandbox_mode, SandboxMode::ReadOnly);
assert_eq!(parsed.agent_tier, AgentTier::Reasoning);
diff --git a/tests/raw_coverage/tools_agent_credentials_state_raw_coverage_e2e.rs b/tests/raw_coverage/tools_agent_credentials_state_raw_coverage_e2e.rs
index 0f71a73262..5ebfae5d51 100644
--- a/tests/raw_coverage/tools_agent_credentials_state_raw_coverage_e2e.rs
+++ b/tests/raw_coverage/tools_agent_credentials_state_raw_coverage_e2e.rs
@@ -17,7 +17,7 @@ use axum::routing::post;
use axum::{Json, Router};
use chrono::{Duration as ChronoDuration, Utc};
use openhuman_core::tinytools_agent::dialect::NativeDialect;
-use openhuman_core::agent::harness::session::Agent;
+use openhuman_core::agent::session_host::OpenHumanSessionHost;
use openhuman_core::agent::harness::{
run_subagent, with_parent_context, AgentDefinition, ParentExecutionContext, PromptSource,
SandboxMode, SubagentRunOptions, ToolScope,
@@ -395,7 +395,7 @@ fn agent_definition(id: &str, max_result_chars: Option<usize>) -> AgentDefinitio
AgentDefinition {
id: id.to_string(),
when_to_use: "Raw coverage test agent".to_string(),
- display_name: Some("Round16 Agent".to_string()),
+ display_name: Some("Round16 OpenHumanSessionHost".to_string()),
system_prompt: PromptSource::Inline("Use the visible tools and answer tersely.".into()),
omit_identity: true,
omit_memory_context: false,
@@ -738,7 +738,7 @@ async fn round16_agent_builder_turn_uses_public_harness_paths() {
),
response(Some("builder final"), Vec::new()),
]));
- let mut agent = Agent::builder()
+ let mut agent = OpenHumanSessionHost::builder()
.chat_model(provider)
.tools(vec![Box::new(EchoTool)])
.memory(Arc::new(StubMemory))
diff --git a/vendor/tinyagents b/vendor/tinyagents
index 420cab0fc9..2a8e69b65b 160000
--- a/vendor/tinyagents
+++ b/vendor/tinyagents
@@ -1 +1 @@
-Subproject commit 420cab0fc99ce91222aec1ab8b7b99abfbba0325
+Subproject commit 2a8e69b65b0f67d059e5a8b512d1f16ecd5e03e8