The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
Merge remote-tracking branch 'origin/main' into epic-8088-final-rollup
Steven Enamakel6ff307fd3645
diff --cc Cargo.lockindex 172293ac29,39d22b7339..b9ff277857--- a/Cargo.lock+++ b/Cargo.lock@@@ -5425,9 -5724,10 +5724,9 @@@ dependencies ="sysinfo","tar","tempfile",- "thiserror 2.0.20",+ "thiserror 2.0.21","tiny-artifacts","tinyagents-definition",- "tinyagents-graph","tinyagents-harness","tinyagents-harness-tools","tinyagents-hooks",@@@ -5474,11 -5775,16 +5774,15 @@@"tinyskills","tinyskills-drivers","tinystoragedrivers",+ "tinystoragedrivers-api","tinystoragedrivers-bus","tinystoragedrivers-busproxy",- "tinystoragedrivers-client",+ "tinystoragedrivers-connect",+ "tinystoragedrivers-secrets",+ "tinystoragedrivers-testkit",+ "tinystoragedrivers-types","tinytools 0.6.0","tinytools-agent 0.6.0",- "tinytools-std","tinyvoice-bus","tinywallet","tinywallet-bus",@@@ -5552,9 -5859,10 +5856,9 @@@ dependencies ="tinymemory-tools","tinysearch-bus","tinystoragedrivers",- "tinystoragedrivers-core",+ "tinystoragedrivers-api","tinytools 0.6.0","tinytools-agent 0.6.0",- "tinytools-std","tokio","tokio-stream","tokio-tungstenite 0.29.0",@@@ -5587,8 -5896,9 +5892,8 @@@ dependencies ="serde","serde_json","tempfile",- "thiserror 2.0.20",+ "thiserror 2.0.21","tinyagents-definition",- "tinyagents-graph","tinyagents-harness","tinyagents-harness-tools","tinyagents-hooks",@@@ -8417,8 -8806,9 +8800,8 @@@ dependencies ="async-trait","serde","serde_json",- "thiserror 2.0.20",+ "thiserror 2.0.21",- "tinystoragedrivers-api",- "tinystoragedrivers-types",+ "tinystoragedrivers-core","tinytools 0.6.0","tokio","tracing",@@@ -9811,43 -10291,38 +10284,54 @@@ dependencies =][[package]]- name = "tinystoragedrivers-client"- version = "1.0.0"+ name = "tinystoragedrivers-connect"+ version = "2.1.0"dependencies = [- "async-trait",- "serde",+ "lapin",+ "mongodb",+ "object_store",+ "rusqlite","serde_json",- "tinystoragedrivers-bus",- "tinystoragedrivers-core",- "tinystoragedrivers-secrets",+ "tinystoragedrivers-types","tokio",+ "url",+ "zstd",]+[[package]]+name = "tinystoragedrivers-core"+version = "1.0.0"++source = "git+https://github.com/tinyhumansai/tinystoragedrivers.git?rev=be94f7568fe7650b0729be55128f48270414b9a7#be94f7568fe7650b0729be55128f48270414b9a7"+dependencies = [+ "async-trait",+ "data-encoding",+ "serde",+ "serde_json",+ "sha2 0.10.9",- "tinystoragedrivers-schema",++ "thiserror 2.0.21",+ "tokio",+ "ulid",- "zstd 0.13.3",++ "zstd",+]+[[package]]- name = "tinystoragedrivers-file"- version = "1.0.0"+ name = "tinystoragedrivers-document"+ version = "2.1.0"dependencies = ["async-trait",+ "data-encoding",+ "futures-util","libc",+ "mongodb",+ "rusqlite","serde","serde_json",- "tinystoragedrivers-core",+ "sha2 0.11.1",+ "tinystoragedrivers-api",+ "tinystoragedrivers-connect",+ "tinystoragedrivers-types","tokio",+ "zstd",][[package]]diff --cc crates/openhuman-app/Cargo.lockindex 4f73f852b7,ae17ce414b..3941829d0d--- a/crates/openhuman-app/Cargo.lock+++ b/crates/openhuman-app/Cargo.lock@@@ -3785,9 -4550,10 +4603,9 @@@ dependencies ="sysinfo","tar","tempfile",- "thiserror 2.0.20",+ "thiserror 2.0.21","tiny-artifacts","tinyagents-definition",- "tinyagents-graph","tinyagents-harness","tinyagents-harness-tools","tinyagents-hooks",@@@ -3805,9 -4572,7 +4624,8 @@@"tinyconnectors-bus","tinydocs-bus","tinyeventqueues-bus",+ "tinyflows","tinyflows-bus",- "tinyflows-import","tinyhosts-bus","tinyinference-core","tinyinference-decisions",@@@ -3827,11 -4593,15 +4646,14 @@@"tinyskills","tinyskills-drivers","tinystoragedrivers",+ "tinystoragedrivers-api","tinystoragedrivers-bus","tinystoragedrivers-busproxy",- "tinystoragedrivers-client",+ "tinystoragedrivers-connect",+ "tinystoragedrivers-secrets",+ "tinystoragedrivers-types","tinytools","tinytools-agent",- "tinytools-std","tinyvoice-bus","tinywallet-bus","tokio",@@@ -3911,8 -4681,9 +4733,8 @@@ dependencies ="serde","serde_json","tempfile",- "thiserror 2.0.20",+ "thiserror 2.0.21","tinyagents-definition",- "tinyagents-graph","tinyagents-harness","tinyagents-harness-tools","tinyagents-hooks",@@@ -6515,22 -7583,25 +7639,25 @@@ dependencies ="regex","reqwest 0.12.28","rustix 1.1.5",+ "schemars 1.2.2","serde","serde_json",- "sha2 0.11.0",+ "sha2 0.11.1","tar","tempfile",- "thiserror 2.0.20",+ "thiserror 2.0.21","tinyagents-definition",+ "tinyagents-storage-kit","tinyinference-core","tinyinference-embeddings","tinyinference-image","tinyinference-llm",+ "tinyinference-providers","tinyinference-video",- "tinystoragedrivers-core",+ "tinystoragedrivers-api",+ "tinystoragedrivers-types","tinytools","tinytools-agent",- "tinytools-std","tokio","tracing","uuid",@@@ -6608,15 -7667,15 +7736,14 @@@ dependencies ="parking_lot","serde","serde_json",- "sha2 0.11.0",- "thiserror 2.0.20",+ "sha2 0.11.1",+ "thiserror 2.0.21","tinyagents-definition",- "tinyagents-graph","tinyagents-harness","tinyagents-session",+ "tinyagents-storage-kit","tinyagents-tasks","tinyinference-llm",- "tinystoragedrivers-core","tinytools","tokio","tracing",@@@ -6688,11 -7761,10 +7829,11 @@@ dependencies ="serde","serde_json","tinyagents-harness",+ "tinyagents-storage-kit","tinyinference-llm",- "tinystoragedrivers-core","tokio","tracing",+ "uuid",][[package]]@@@ -6793,29 -7864,9 +7933,29 @@@ version = "0.1.3dependencies = ["serde","serde_json",- "tinystoragedrivers-core",+ "tinystoragedrivers-types",]+[[package]]+name = "tinyflows"+version = "0.8.29"+dependencies = [+ "async-trait",+ "base64 0.23.1",+ "futures-timer",+ "futures-util",+ "getrandom 0.4.3",+ "hex",+ "jaq-core",+ "jaq-json",+ "jaq-std",+ "serde",+ "serde_json",+ "thiserror 2.0.20",+ "tokio",+ "tracing",+]+[[package]]name = "tinyflows-bus"version = "0.1.0"@@@ -7766,16 -8903,30 +8992,36 @@@ dependencies ="rand 0.9.5","rustls","rustls-pki-types",- "sha1",- "thiserror 2.0.20",+ "sha1 0.10.7",+ "thiserror 2.0.21",+ ]++ [[package]]+ name = "typed-builder"+ version = "0.22.0"+ source = "registry+https://github.com/rust-lang/crates.io-index"+ checksum = "398a3a3c918c96de527dc11e6e846cd549d4508030b8a33e1da12789c856b81a"+ dependencies = [+ "typed-builder-macro",+ ]++ [[package]]+ name = "typed-builder-macro"+ version = "0.22.0"+ source = "registry+https://github.com/rust-lang/crates.io-index"+ checksum = "0e48cea23f68d1f78eb7bc092881b6bb88d3d6b5b7e6234f6f9c911da1ffb221"+ dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",]+[[package]]+name = "typed-arena"+version = "2.0.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6af6ae20167a9ece4bcb41af5b80f8a1f1df981f6391189ce00fd257af04126a"+[[package]]name = "typed-path"version = "0.12.4"diff --cc crates/openhuman-cli/Cargo.tomlindex 90ad51657f,0dc9a0c367..29d7391331--- a/crates/openhuman-cli/Cargo.toml+++ b/crates/openhuman-cli/Cargo.toml@@@ -386,12 -445,13 +444,13 @@@ serde = { version = "1", features = ["dtempfile = "3"tinyinference-llm = { path = "../../vendor/tinyagents/vendor/tinyinference/crates/tinyinference-llm" }# The document-port contract for failure injection in cron storage regressions.- tinystoragedrivers-core = { git = "https://github.com/tinyhumansai/tinystoragedrivers", tag = "v1.0.0" }- tinystoragedrivers = { git = "https://github.com/tinyhumansai/tinystoragedrivers", tag = "v1.0.0", default-features = false, features = ["sqlite"] }+ tinystoragedrivers-api = { git = "https://github.com/tinyhumansai/tinystoragedrivers", rev = "05eaada962decbab33bafa4763d2bd1a67f6b456" }+ tinystoragedrivers = { git = "https://github.com/tinyhumansai/tinystoragedrivers", rev = "05eaada962decbab33bafa4763d2bd1a67f6b456", default-features = false, features = ["sqlite"] }+ zeroize = "1"tinytools = { path = "../../vendor/tinyagents/vendor/tinytools/crates/tinytools" }-tinytools-std = { path = "../../vendor/tinyagents/vendor/tinytools/crates/tinytools-std" }# The completion log a detached sub-agent leaves, for the SaaS delivery-recovery e2e.tinyagents-tasks = { path = "../../vendor/tinyagents/crates/tinyagents-tasks" }- tinyagents-harness-tools = { workspace = true, features = ["goals", "skills", "fs", "net", "exec"] }++tinyagents-harness-tools = { path = "../../vendor/tinyagents/crates/tinyagents-harness-tools", default-features = false, features = ["goals"] }toml = "1.0"tracing = "0.1"# The TinyComputer contract, for the live computer-use e2e (`computer_bali_live_e2e`).diff --cc crates/openhuman-core/Cargo.tomlindex 4679643452,a26e88e319..724f36ebb4--- a/crates/openhuman-core/Cargo.toml+++ b/crates/openhuman-core/Cargo.toml@@@ -53,15 -53,7 +53,8 @@@ crate-type = ["rlib"# contracts. Unconditional because cron and module callbacks remain available# without the OpenHuman `flows` surface; engine and catalog implementations are# reached only through the loaded module's bus endpoints.+tinyflows = { path = "../../vendor/tinyflows/crates/tinyflows" }tinyflows-bus = { path = "../../vendor/tinyflows/crates/tinyflows-bus" }- # Reads the stores tinyflows hosts used before storage moved onto the ports- # (`flows.db`, `jobs.db`, `checkpoints.db`, drafts). Only its pure SQLite readers- # are enabled here: flows and checkpoints use bus records owned by the module;- # the `schedule-read` reader remains active without the `flows` feature, where- # the host replays cron records through the module's ImportJob/ImportRun bus- # members.- tinyflows-import = { path = "../../vendor/tinyflows/crates/tinyflows-import", default-features = false, features = ["schedule-read"] }# TinyAgents — Rust LLM orchestration framework (LangGraph/LangChain-style):# durable state graphs, agent-loop harness, model/tool registries, REPL +# `.rag` workflow language. openhuman's agent engine + orchestration run on this@@@ -116,15 -113,28 +114,24 @@@ tinyagents-definition = { path = "../..# Agents, the Sarvam cascade) and executes its tool calls through the turn# harness pipeline. Only the `voice` feature's `voice::live` uses it.tinyagents-live = { path = "../../vendor/tinyagents/crates/tinyagents-live", optional = true }-tinyagents-graph = { path = "../../vendor/tinyagents/crates/tinyagents-graph", features = [- "sqlite",- "storage-drivers",-] }tinyagents-registry = { path = "../../vendor/tinyagents/crates/tinyagents-registry" }tinyagents-session = { path = "../../vendor/tinyagents/crates/tinyagents-session", features = ["storage-drivers"] }+ tinyagents-storage-kit = { path = "../../vendor/tinyagents/crates/tinyagents-storage-kit" }# The storage ports and the URL-to-backend facade (`storage` domain). No driver# by default: the `storage-*` features below add them.- tinystoragedrivers = { git = "https://github.com/tinyhumansai/tinystoragedrivers", tag = "v1.0.0", default-features = false, features = ["blocking", "secrets", "file", "sqlite"] }+ tinystoragedrivers = { git = "https://github.com/tinyhumansai/tinystoragedrivers", rev = "05eaada962decbab33bafa4763d2bd1a67f6b456", default-features = false }+ tinystoragedrivers-api = { git = "https://github.com/tinyhumansai/tinystoragedrivers", rev = "05eaada962decbab33bafa4763d2bd1a67f6b456" }+ # Legacy source readers use the shared SQLite binding only while the host+ # migration feature is enabled; production storage opens through the facade.+ tinystoragedrivers-connect = { git = "https://github.com/tinyhumansai/tinystoragedrivers", rev = "05eaada962decbab33bafa4763d2bd1a67f6b456", features = ["sqlite"], optional = true }+ tinystoragedrivers-types = { git = "https://github.com/tinyhumansai/tinystoragedrivers", rev = "05eaada962decbab33bafa4763d2bd1a67f6b456" }+ # The host config and secret adapters use the driver's established `enc2`+ # codec and per-scope key provider while storing through the v2 SecretStore+ # port. The backend itself still supplies the port implementation.+ tinystoragedrivers-secrets = { git = "https://github.com/tinyhumansai/tinystoragedrivers", rev = "05eaada962decbab33bafa4763d2bd1a67f6b456", default-features = false, features = ["document"] }# The storage bus: the wire contract and the reference host server that the# `modules::storage_host` interface answers loaded modules with. Modules only.- tinystoragedrivers-bus = { git = "https://github.com/tinyhumansai/tinystoragedrivers", tag = "v1.0.0", optional = true }- tinystoragedrivers-client = { git = "https://github.com/tinyhumansai/tinystoragedrivers", tag = "v1.0.0", optional = true }+ tinystoragedrivers-bus = { git = "https://github.com/tinyhumansai/tinystoragedrivers", rev = "05eaada962decbab33bafa4763d2bd1a67f6b456", optional = true }# The host half of the storage bus transport: registers the four `Storage`# objects and binds blob streams and watch signals to the calling peer# (`Connection::accept_stream_from` / `emit_to`).diff --cc crates/openhuman-core/src/agent/harness/tool_result_artifacts/mod.rsindex ec422899b3,7ac4f1c334..cc8e4b3230--- a/crates/openhuman-core/src/agent/harness/tool_result_artifacts/mod.rs+++ b/crates/openhuman-core/src/agent/harness/tool_result_artifacts/mod.rs@@@ -30,14 -30,10 +30,14 @@@ use std::sync::Arcuse serde_json::Value;use tinyagents_harness::artifacts::tool_results::{self, ArtifactRead, ToolResultArtifactStore};- use tinystoragedrivers::BlobStore;+ use tinystoragedrivers_api::BlobStore;use crate::agent::harness::artifact_offload::{SanitizingRedactor, READ_TOOL};-use tinytools_std::filesystem::FileReadTool;+use tinyagents_harness_tools::fs::filesystem::FileReadTool;++mod wiring;++pub(crate) use wiring::build_artifact_store;/// Namespace of the artifact index in the run's store registry.pub(crate) const TINYAGENTS_TOOL_RESULT_ARTIFACT_STORE: &str = "openhuman_tool_result_artifacts";diff --cc crates/openhuman-core/src/agent/orchestration/subagent_sessions/mod.rsindex ff4a694aa8,877d128f67..c704f3e1d0--- a/crates/openhuman-core/src/agent/orchestration/subagent_sessions/mod.rs+++ b/crates/openhuman-core/src/agent/orchestration/subagent_sessions/mod.rs@@@ -1,27 -1,27 +1,29 @@@mod ops;mod storage_schema;mod store;- pub use storage_schema::storage_schema;+ pub(crate) use storage_schema::collection_specs;+ #[cfg(feature = "legacy-import")]+ pub(crate) use storage_schema::upgrade_records;mod store_documents;mod tiny_port;+mod tiny_port_epoch;mod types;+#[cfg(test)]+pub(crate) use ops::cancel_driver_job_by_task;pub use ops::{- action_root_key, cancel_driver_job_by_task, cancel_driver_job_for_observed_session,- cancel_driver_jobs_for_thread, close_if_current, find_reusable, list_for_parent,- mark_driver_pause_cancelled, mark_failed, mark_finished, normalize_task_key,- resolve_lifecycle_key, reuse_decision, task_title_from_prompt, upsert_running,- DriverTaskCancellation,+ action_root_key, cancel_driver_job_for_observed_session, cancel_driver_jobs_for_thread,+ close_if_current, find_reusable, list_for_parent, mark_failed, mark_finished,+ normalize_task_key, resolve_driver_lifecycle_key, resolve_lifecycle_key, reuse_decision,+ upsert_running, DriverTaskCancellation,};+#[cfg(test)]pub(crate) use tiny_port::OpenHumanTinySubagentSessionStore;+pub(crate) use tiny_port::{host_projection, import_terminal_task_for_context, open_for_context};+pub(crate) use tiny_port_epoch::{parent_epoch_for_context, set_parent_epoch_for_context};pub use types::{- DurableSubagentSessionSummary, DurableSubagentStatus, SubagentSessionSelector,- SubagentSessionStore, SubagentSessionUpsert,+ DurableSubagentStatus, SubagentSessionSelector, SubagentSessionStore, SubagentSessionUpsert,};-// Test-only since the `harness-subagent-audit` debug binary (and the-// `orchestration::harness_audit` facade it needed) were removed: production-// callers reach the session records through `DurableSubagentSessionSummary`.-#[cfg(test)]-pub use types::DurableSubagentSession;+// The spawn compatibility adapter retains this host projection while the+// remaining lifecycle writers migrate to TinyAgents' durable store.+pub(crate) use types::DurableSubagentSession;diff --cc crates/openhuman-core/src/agent/orchestration/subagent_sessions/storage_schema.rsindex 9c24471686,8923fbcf72..93f683b4b5--- a/crates/openhuman-core/src/agent/orchestration/subagent_sessions/storage_schema.rs+++ b/crates/openhuman-core/src/agent/orchestration/subagent_sessions/storage_schema.rs@@@ -11,30 -11,33 +11,34 @@@//! saved since. The driver's `updated_ms` is the time of the write, not of the//! session's last use.+ use anyhow::Result;use serde_json::{Map, Value};- use tinystoragedrivers::schema::{Schema, ScopeClass, SourceRecord, Step, TargetRecord};- use tinystoragedrivers::{CollectionSpec, Result};+ use tinystoragedrivers::CollectionSpec;- use crate::storage::schema_support::{key_of, owner, time_ms};+ use crate::storage::schema_support::{+ key_of, map_legacy_collection, time_ms, LegacySourceRecord as SourceRecord,+ LegacyTargetRecord as TargetRecord,+ };pub(super) const SESSIONS: &str = "subagents.sessions";+pub(super) const EPOCHS: &str = "subagents.session_epochs";pub(super) const LEGACY_SESSIONS: &str = "subagent_sessions";- const SCHEMA: u32 = 2;-- /// What the session store keeps and the step from the v1 collection.- #[must_use]- pub fn storage_schema() -> Schema {- Schema::new(owner("subagents"))- .collection_with(SCHEMA, spec(), ScopeClass::Agent)- .collection_with(1, CollectionSpec::new(EPOCHS), ScopeClass::Agent)- .step(Step::new("sessions_v2", SESSIONS, 1, SCHEMA, sessions_v2).source(LEGACY_SESSIONS))+ /// Converts legacy sub-agent session rows into the current owner shape.+ pub(crate) fn upgrade_records(+ records: Vec<crate::storage::import::Record>,+ ) -> Result<Vec<crate::storage::import::Record>> {+ map_legacy_collection(records, LEGACY_SESSIONS, sessions_v2)}pub(super) fn spec() -> CollectionSpec {CollectionSpec::new(SESSIONS)}+ /// Collections owned by the sub-agent session host.+ pub(crate) fn collection_specs() -> Vec<CollectionSpec> {- vec![spec()]++ vec![spec(), CollectionSpec::new(EPOCHS)]+ }+pub(super) fn legacy_collections() -> Vec<CollectionSpec> {vec![CollectionSpec::new(LEGACY_SESSIONS)]}@@@ -54,7 -57,6 +58,8 @@@ const COPIES: [(&str, &str); 18] =("taskTitle", "task_title"),("currentTaskId", "current_task_id"),("lifecycleKey", "lifecycle_key"),+ ("parentEpoch", "parent_epoch"),++ ("parentEpoch", "parent_epoch"),("status", "status"),("reusable", "reusable"),("latestHistory", "latest_history"),diff --cc crates/openhuman-core/src/agent/orchestration/subagent_sessions/store_documents_tests.rsindex d928003878,be659a39a7..caa29e8bb3--- a/crates/openhuman-core/src/agent/orchestration/subagent_sessions/store_documents_tests.rs+++ b/crates/openhuman-core/src/agent/orchestration/subagent_sessions/store_documents_tests.rs@@@ -223,9 -224,7 +225,8 @@@ fn a_durable_session_keeps_its_scoped_ltask_id: "task".into(),};saved.lifecycle_key = Some(key.clone());- saved.parent_epoch = Some(7);- docs_in(&storage, "local").save(&[saved]).unwrap();- let loaded = docs_in(&storage, "local").load().unwrap();+ docs_in(storage.as_ref(), "local").save(&[saved]).unwrap();+ let loaded = docs_in(storage.as_ref(), "local").load().unwrap();assert_eq!(loaded[0].lifecycle_key, Some(key));+ assert_eq!(loaded[0].parent_epoch, Some(7));}diff --cc crates/openhuman-core/src/agent/session_host/driver/grounded_close.rsindex c7d0f45c20,e60c0a2875..d49a8ba542--- a/crates/openhuman-core/src/agent/session_host/driver/grounded_close.rs+++ b/crates/openhuman-core/src/agent/session_host/driver/grounded_close.rs@@@ -235,13 -240,17 +240,17 @@@ pub(super) struct GroundedClose/// Keeping this separate from the model-driven repair path guarantees zero/// additional provider calls once its recovery budget is exhausted.fn classified_halt_close(outcome: &TinyagentsTurnOutcome) -> Option<GroundedClose> {- let reason = outcome.breaker_halt.as_deref()?;- if !reason.starts_with("Stopping after ") {+ let reason = outcome.breaker_halt.as_deref().unwrap_or_default();+ if outcome.failure_cause.is_none() && !reason.starts_with("Stopping after ") {return None;}- let records = results_from_tool_outcomes(&outcome.tool_outcomes);+ let records = product_copy::close_results(&outcome.tool_outcomes);Some(GroundedClose {- output: stop_policy::deterministic_final_summary(&records, Some(reason)),+ output: build_deterministic_final_summary_with_cause(+ &records,+ Some(reason),+ outcome.failure_cause.as_ref(),+ ),usage: RepairUsage::default(),})}@@@ -406,15 -409,13 +417,19 @@@ pub(super) async fn close_if_neededlet harness_phrases: Vec<&str> = harness_needles.iter().map(String::as_str).collect();let fallback = || {if needs_cap_close {- build_deterministic_checkpoint(&records, outcome.model_calls)+ let checkpoint_results = product_copy::render_close_results(&records, 4_000);+ tinyagents_harness::close::checkpoint_with_copy(+ &product_copy::OPENHUMAN_CLOSE_COPY,+ outcome.model_calls,+ &checkpoint_results,+ !records.is_empty(),+ )} else {- stop_policy::deterministic_final_summary(&records, stop_reason)+ build_deterministic_final_summary_with_cause(+ &records,+ stop_reason,+ outcome.failure_cause.as_ref(),+ )}};diff --cc crates/openhuman-core/src/agent/session_host/mod.rsindex 689e4a5230,bb41dd1745..1f0a0cf701--- a/crates/openhuman-core/src/agent/session_host/mod.rs+++ b/crates/openhuman-core/src/agent/session_host/mod.rs@@@ -46,9 -45,20 +46,13 @@@ mod live_toolsmod resume_bound_session_tests;mod runtime;mod runtime_session;-pub(crate) mod stop_summary;-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;+pub(crate) mod stop_policy;mod types;+ #[cfg(test)]+ #[path = "test_support.rs"]+ pub(crate) mod test_support;+pub use codec::OpenHumanTranscriptCodec;pub type OpenHumanSessionHooks =tinyagents_runtime::FnSessionHooks<crate::agent::tinyagents::host::OpenHumanRunContext>;diff --cc crates/openhuman-core/src/agent/session_host/runtime_adapter_trace_tests.rsindex eeecee2bbb,e6b9b5da84..0d5e8f29ca--- a/crates/openhuman-core/src/agent/session_host/runtime_adapter_trace_tests.rs+++ b/crates/openhuman-core/src/agent/session_host/runtime_adapter_trace_tests.rs@@@ -78,12 -69,11 +78,13 @@@ async fn cancellation_during_required_ocalls: std::sync::atomic::AtomicUsize::new(0),repair_started: tokio::sync::Notify::new(),repair_call_id: std::sync::Mutex::new(None),+ user_messages: std::sync::Mutex::new(Vec::new()),});let chat_model: Arc<dyn ChatModel<()>> = model.clone();+ let locator = memory_locator();let mut host = crate::agent::SessionHostBuilder::new().chat_model_with_config(chat_model, Arc::new(config.clone()))+ .model_name("test/session-fixture".to_string()).config(config.agent.clone()).tools(Vec::new()).workspace_dir(workspace.clone())diff --cc crates/openhuman-core/src/agent/session_host/runtime_session/prelude.rsindex c31ca2a8db,0330c99193..65c6c3d37d--- a/crates/openhuman-core/src/agent/session_host/runtime_session/prelude.rs+++ b/crates/openhuman-core/src/agent/session_host/runtime_session/prelude.rs@@@ -253,29 -224,32 +240,33 @@@ impl OpenHumanTurnPrelude) -> String {let mut context = String::new();+ // A paused goal stays paused: the model reads the message and resumes,+ // replaces or leaves it with the goal tools. Turns with the run-state+ // block see the goal there, current on every call, so it is not also+ // prepended to the user's message.+ run_context.goal_suppressed = turn.overrides.suppress_active_goal;let active_goal = if turn.overrides.suppress_active_goal {None- } else if let Some(thread_id) = self.thread_id.as_deref() {- let store = crate::agent::goals::goal_store(&self.workspace_dir, &self.dispatch_ctx());- match store.prepare_turn(thread_id).await {- Ok(preparation) => {- if let Some(block) = preparation.context_block {- context.push_str(&block);- }- preparation.goal- }- Err(error) => {- tracing::debug!(thread_id, %error, "[thread_goals] prepare_turn failed");- None- }- }} else {- None+ crate::agent::goals::runtime::load_for_thread(+ &self.workspace_dir,+ self.thread_id.as_deref(),+ )+ .await};+ let state_block_shows_goal =+ crate::agent::tinyagents::state_block::applies(false, Some(&self.agent_definition_id));if let Some(goal) = &active_goal {+ if !state_block_shows_goal {+ if let Some(block) =+ tinyagents_harness_tools::goals::active_goal_context_block(goal)+ {+ context.push_str(&block);+ }+ }if let Some(hook) = tinyagents_hooks::stop::GoalBudgetStopHook::for_goal(- crate::storage::sessions::stores_or_ephemeral(&self.workspace_dir).kv,+ crate::agent::goals::goal_store(&self.workspace_dir, &self.dispatch_ctx())+ .backing_store(),goal,) {run_context.stop_hooks.push(Arc::new(hook));diff --cc crates/openhuman-core/src/agent/session_host/stop_policy.rsindex a9d8fbde4b,fcce47a012..991fa7b207--- a/crates/openhuman-core/src/agent/session_host/stop_policy.rs+++ b/crates/openhuman-core/src/agent/session_host/stop_policy.rs@@@ -239,9 -279,37 +276,21 @@@ pub(crate) fn short_error_line(contentformat!("{}…", cut.trim_end())}-/// One collapsed line: a tool, whether it succeeded, the error line for a-/// failure, and how many results it stands for.-struct Group {- name: String,- success: bool,- error: String,- count: usize,-}--fn times(count: usize) -> String {- match count {- 1 => String::new(),- n => format!(" {n} times"),- }-}-/// The user-facing reply for a turn the breaker stopped with `stop_note`.pub(crate) fn render_stop_summary(results: &[CheckpointToolResult], stop_note: &str) -> String {- let kind = StopReasonKind::from_stop_note(stop_note);+ render_stop_summary_with_cause(results, stop_note, None)+ }++ /// Render a stopped-turn summary from its typed cause when the harness has+ /// one. The note is only a compatibility source for old, untyped stops.+ pub(crate) fn render_stop_summary_with_cause(+ results: &[CheckpointToolResult],+ stop_note: &str,+ failure_cause: Option<&tinyagents_harness::no_progress::ClassifiedStopCause>,+ ) -> String {+ let kind = failure_cause+ .map(|cause| StopReasonKind::from_failure_class(&cause.class))+ .unwrap_or_else(|| StopReasonKind::from_stop_note(stop_note));tracing::debug!(reason = kind.key(),results = results.len(),diff --cc crates/openhuman-core/src/agent/subagent_host/ops/runner.rsindex 443016481a,1aae38e194..ad224eddfa--- a/crates/openhuman-core/src/agent/subagent_host/ops/runner.rs+++ b/crates/openhuman-core/src/agent/subagent_host/ops/runner.rs@@@ -18,14 -20,16 +18,17 @@@ use crate::agent::subagent_host::tool_puse crate::agent::subagent_host::types::{SubagentMode, SubagentRunError, SubagentRunOptions, SubagentRunOutcome,};+use crate::agent::subagent_host::ParentExecutionContext;use crate::agent::tinyagents::budget::MAX_SPAWN_DEPTH;use crate::agent_registry::host_definition::{AgentDefinition, AgentDefinitionRegistry};- use crate::inference::provider::AGENT_TURN_MAX_OUTPUT_TOKENS;- use tinyagents_definition::{validate_tier_transition, AgentTier, IterationPolicy, PromptSource};+ use tinyagents_definition::{+ validate_tier_transition, AgentTier, IterationPolicy, PromptSource,+ SandboxMode as AgentSandboxMode,+ };use tinyagents_harness::context::{current_run_depth, with_run_depth, RunConfig, RunDepth};+ use tinyagents_harness::turn_policy::AGENT_TURN_MAX_OUTPUT_TOKENS;+ use tinytools::{SandboxMode as TinyagentsSandboxMode, ToolSpec, WorkspaceDescriptor};-use tinytools_std::file_state::with_file_state_agent_id;+use tinyagents_harness_tools::fs::file_state::with_file_state_agent_id;- use tinytools::{Tool, ToolSpec};use super::prompt::compose_subagent_system_prompt;use super::provider::resolve_subagent_source;diff --cc crates/openhuman-core/src/agent/tinyagents/README.mdindex ee7649f41f,ecfd0153b0..975a676b72--- a/crates/openhuman-core/src/agent/tinyagents/README.md+++ b/crates/openhuman-core/src/agent/tinyagents/README.md@@@ -36,9 -36,9 +36,8 @@@ The adapter seam between OpenHuman and| [`middleware/research_budget.rs`](./middleware/research_budget.rs) | Withdraws the web tools from a top-level turn after eight successful search or fetch calls (forcing an answer only when no other tool remains), and notes once when consecutive web calls fail. || `model.rs` | Helpers and wrappers over native crate `ChatModel` values: message/response translation, usage merging, stream-delta forwarding, `MaxTokensModel`, `ProfileOverrideModel`. || [`tools.rs`](./tools.rs) | `CanonicalSharedToolAdapter`: resolves an OpenHuman shared tool registry and forwards the canonical `tinytools::Tool` contract; `EarlyExitHook` pauses successful `ask_user_clarification`-style calls. |- | `routes.rs` | the workload router projected from the upstream `WORKLOAD_ROUTES` table, `RequiredCapabilitiesMiddleware`, `FallbackObserverMiddleware`, `UsageCarryMiddleware`, and the per-model fallback policy. || [`observability.rs`](./observability.rs) + `observability/` | `event_bridge.rs`: `OpenhumanEventBridge`, translating crate `AgentEvent`s into `AgentProgress` and feeding per-call usage into `crate::platform::cost`. `event_projection.rs`: its `EventListener` impl. `bridge_types.rs`: `SubagentScope` and the shared bridge carries (the cap pauser itself is `tinyagents_harness::events::CapPauser`). |-| [`host/steering.rs`](./host/steering.rs) | OpenHuman's steering allowlist and the shared `SteeringRegistry` for detached sub-agents. Task primitives are imported directly from `tinyagents_graph::orchestration`. |-| [`host/delegation.rs`](./host/delegation.rs) | Explicit tracing-bound execution helpers over `tinyagents_graph::delegation`'s plan, execute, review, finalize graph. |+| [`host/steering.rs`](./host/steering.rs) | OpenHuman's steering allowlist and the shared `SteeringRegistry` for detached sub-agents. Task primitives come from `tinyagents_orchestration`. || [`payload_summarizer.rs`](./payload_summarizer.rs) | `PayloadSummarizer` trait, `SummarizeOutcome`/`UnavailableReason`, and the default `SubagentPayloadSummarizer` that compresses oversized tool results through the `summarizer` sub-agent instead of hard-truncating them. || [`policy_denial.rs`](./policy_denial.rs) | `maybe_enrich_policy_block`: rewrites `[policy-blocked]` tool results into structured what/why/workaround messages that tell the model to relay the denial rather than fabricate output. Called from `ToolOutcomeCaptureMiddleware`. || [`host/run_context.rs`](./host/run_context.rs) + typed tool dispatch | `OpenHumanRunContext` owns one root `CancellationToken`; child contexts share it and recursive tools receive it from their typed parent `RunContext`. |diff --cc crates/openhuman-core/src/agent/tinyagents/budget.rsindex 7368d78a22,07b95ef2a7..991690306e--- a/crates/openhuman-core/src/agent/tinyagents/budget.rs+++ b/crates/openhuman-core/src/agent/tinyagents/budget.rs@@@ -41,10 -93,24 +41,24 @@@ impl crate::inference::turn_models::Turif budget.is_none() && admission.is_none() {return self;}- self.primary = control_model(self.primary, budget, admission.clone());- self.summarizer = control_model(self.summarizer, budget, admission.clone());+ if let Some(models) = self.native_model_set.take() {+ let models = models+ .map_models(|_, model| ModelBudget::control(model, budget, admission.clone()));+ let mut registrations = models.registrations("primary").into_iter();+ self.primary = registrations+ .next()+ .expect("native turn set contains its primary")+ .1;+ self.routes = registrations.collect();+ self.summarizer = models.summarizer();+ self.error_slot = models.primary_error_slot();+ self.native_model_set = Some(models);+ return self;+ }+ self.primary = ModelBudget::control(self.primary, budget, admission.clone());+ self.summarizer = ModelBudget::control(self.summarizer, budget, admission.clone());for (_, route) in &mut self.routes {- *route = ModelBudget::control(route.clone(), budget, admission.clone());+ *route = control_model(route.clone(), budget, admission.clone());}self}diff --cc crates/openhuman-core/src/agent/tinyagents/turn_middleware.rsindex 43687c9457,64ce426c8a..5d8007bf29--- a/crates/openhuman-core/src/agent/tinyagents/turn_middleware.rs+++ b/crates/openhuman-core/src/agent/tinyagents/turn_middleware.rs@@@ -39,15 -35,18 +39,21 @@@ use crate::agent::tinyagents::host::Opeuse crate::agent::tinyagents::middleware;use crate::agent::tinyagents::middleware::turn_context::TurnContextMiddleware;use crate::agent::tinyagents::observability::{ProviderUsageCarry, SubagentScope, ToolFailureMap};- use crate::agent::tinyagents::routes;use crate::agent::tinyagents::verify_before_finish;- use crate::inference::provider::model::TurnChatModel;use super::ToolPolicyEnforcement;+#[path = "turn_native_security.rs"]+mod native_security;+use native_security::NativeSubagentSecurityMiddleware;+ struct OpenHumanCostEstimator;++ impl tinyagents_harness::middleware::library::CostEstimator for OpenHumanCostEstimator {+ fn estimate(&self, model: &str, usage: &tinyinference_llm::usage::BilledUsage) -> Option<f64> {+ crate::agent::cost::estimate_call_cost_usd(model, usage)+ }+ }+/// What the middleware stack needs to know about the turn.pub(super) struct TurnMiddlewareInputs {/// Configured provider id used only when the response has no resolved route.diff --cc crates/openhuman-core/src/agent/tools.rsindex b251ffe507,b1b96cd05f..4d3bd5c8f6--- a/crates/openhuman-core/src/agent/tools.rs+++ b/crates/openhuman-core/src/agent/tools.rs@@@ -18,10 -21,13 +18,9 @@@//! `agent::registration` assembles the dialogue tools; `tools::ops` composes//! domain registrations and applies the runtime capability filters.pub(crate) mod plan_exit;-// Pure `skill_runtime` client (spawn + await a workflow run) — compiled out-// with the `skills` gate so the tool list OMITS these rather than degrading-// them to a disabled-error.mod todo;- mod wait;-pub use plan_exit::PlanExitTool;pub const PLAN_EXIT_MARKER: &str = tinyagents_harness_tools::PLAN_EXIT_MARKER;+ pub use tinyagents_harness_tools::{WaitLoopTool, WaitTool};pub use todo::TodoTool;pub(crate) use todo::TodoToolDispatch;- pub use wait::{WaitLoopTool, WaitTool};diff --cc crates/openhuman-core/src/agent_runs/mod.rsindex ad4cd7d595,a804cd35a2..85eadd3ca6--- a/crates/openhuman-core/src/agent_runs/mod.rs+++ b/crates/openhuman-core/src/agent_runs/mod.rs@@@ -1,11 -1,31 +1,29 @@@-//! Product-facing RPC surfaces for agent runs, teams, workflows, replay, and tools.+//! Product-facing RPC surfaces for agent runs, workflows, replay, and tools.+ pub mod agent_chat;+ pub(crate) mod agent_teams;+ pub(crate) mod command_center;pub(crate) mod context_breakdown;pub(crate) mod replay;mod schemas;pub(crate) mod subagent_control;mod subagent_finalize;-pub(crate) mod workflow_runs;-pub(crate) mod worktree_schemas;+ pub(crate) use agent_chat::all_inference_agent_chat_registered_controllers;+ pub(crate) use agent_teams::{+ all_agent_team_controller_schemas, all_agent_team_registered_controllers,+ };+ /// The canonical RPC method name for `inference.agent_chat`.+ ///+ /// The controller's `namespace` + `function` combine into the wire method+ /// `openhuman.inference_agent_chat` ([`rpc_method_name`](crate::core::ControllerSchema)).+ /// Host facades (the embed library) reference this constant rather than+ /// spelling the string out, so a rename upstream cannot silently drift an+ /// embedder's dispatch string away from the registered controller.+ pub const INFERENCE_AGENT_CHAT: &str = "openhuman.inference_agent_chat";+ pub(crate) use command_center::{+ all_command_center_controller_schemas, all_command_center_registered_controllers,+ };pub(crate) use schemas::all_registered_controllers as all_agent_registered_controllers;pub(crate) use subagent_control::{all_controller_schemas as all_subagent_control_controller_schemas,diff --cc crates/openhuman-core/src/artifacts/tiny_store.rsindex 60c95e8d32,a74720d8d8..952dd67b0b--- a/crates/openhuman-core/src/artifacts/tiny_store.rs+++ b/crates/openhuman-core/src/artifacts/tiny_store.rs@@@ -447,107 -300,22 +447,75 @@@ pub fn artifacts_servicefiles: FileRoots,action_dir: Option<&Path>,chat: Option<&ApprovalChatContext>,+ ctx: &crate::core::runtime::DispatchCtx,) -> Artifacts {+ let scoped = crate::storage::sessions::artifact_scoped_for_in(workspace_dir, ctx);+ build_artifacts_service_with_scope(workspace_dir, files, action_dir, chat, ctx, scoped, None).0+}++/// Build the artifact service in the current dispatch context.+pub fn artifacts_service_current(+ workspace_dir: &Path,+ files: FileRoots,+ action_dir: Option<&Path>,+ chat: Option<&ApprovalChatContext>,+) -> Artifacts {+ artifacts_service(+ workspace_dir,+ files,+ action_dir,+ chat,+ &crate::core::runtime::DispatchCtx::ambient(),+ )+}++/// Build a service and bind its publisher to the same tenant file store used+/// by the artifact versions.+pub fn artifacts_service_with_publisher(+ workspace_dir: &Path,+ files: FileRoots,+ action_dir: Option<&Path>,+ chat: Option<&ApprovalChatContext>,+ publisher: Option<&super::ArtifactPublisherBinder>,+) -> Artifacts {+ let ctx = crate::core::runtime::DispatchCtx::ambient();+ let scoped = crate::storage::sessions::artifact_scoped_for_in(workspace_dir, &ctx);+ build_artifacts_service_with_scope(+ workspace_dir,+ files,+ action_dir,+ chat,+ &ctx,+ scoped,+ publisher,+ )+ .0+}++pub(super) fn build_artifacts_service_with_scope(+ workspace_dir: &Path,+ files: FileRoots,+ action_dir: Option<&Path>,+ chat: Option<&ApprovalChatContext>,+ ctx: &crate::core::runtime::DispatchCtx,+ scoped: Option<crate::storage::ScopedStorage>,+ publisher: Option<&super::ArtifactPublisherBinder>,+) -> (Artifacts, Option<Arc<dyn FileStore>>) {let roots = file_roots(workspace_dir, &files, action_dir);- let file_store = scoped- .as_ref()- .map(|scoped| Arc::new(tiny_artifacts::BlobFileStore::new(scoped)) as Arc<dyn FileStore>);- let mut records: Arc<dyn ArtifactStore> = match scoped.as_ref() {- Some(scoped) => Arc::new(super::version_documents::DocumentArtifactStore::over(- workspace_dir,- scoped,- )),- None => Arc::new(UnavailableArtifactStore),- };- if let Some(store) = file_store.as_ref() {- records = Arc::new(LegacyFileImportStore {- records,- files: store.clone(),- roots: guarded_roots(roots.clone()),- });- }- let mut artifacts = Artifacts::new(records)- .with_observer(Arc::new(LegacyUiBridge::new(- workspace_dir,- files,- guarded_roots(roots.clone()),- file_store.clone(),- chat,- ctx,- )))- .with_file_roots(guarded_roots(roots))- .with_version_files(version_files_dir(workspace_dir));- if let Some(file_store) = file_store.as_ref() {- if let Some(publisher) = publisher {- artifacts = artifacts.with_publisher(publisher(file_store.clone()));+ let service = Artifacts::new(Arc::new(versioned_store(workspace_dir)))+ .with_observer(Arc::new(LegacyUiBridge::new(workspace_dir, files, chat)))+ .with_file_roots(guarded_roots(roots));+ match crate::storage::local::open("artifacts::files", workspace_dir)+ .and_then(|opened| opened.scoped())+ {+ Ok(scoped) => {+ service.with_file_store(Arc::new(tiny_artifacts::BlobFileStore::new(&scoped)))+ }+ Err(error) => {+ log::warn!("[artifacts] file storage unavailable: {error:#}");+ service}- artifacts = artifacts.with_file_store(file_store.clone());}- (artifacts, file_store)- }-- pub(crate) fn artifacts_service_with_file_store(- workspace_dir: &Path,- files: FileRoots,- action_dir: Option<&Path>,- chat: Option<&ApprovalChatContext>,- ctx: &crate::core::runtime::DispatchCtx,- ) -> (Artifacts, Option<Arc<dyn FileStore>>) {- let scoped = crate::storage::sessions::artifact_scoped_for_in(workspace_dir, ctx);- build_artifacts_service_with_scope(workspace_dir, files, action_dir, chat, ctx, scoped, None)}/// Where each file version keeps its own copy:diff --cc crates/openhuman-core/src/config/migrations/mod.rsindex 6e86ad4f8c,6f7018f51a..07b70854de--- a/crates/openhuman-core/src/config/migrations/mod.rs+++ b/crates/openhuman-core/src/config/migrations/mod.rs@@@ -33,9 -32,7 +32,8 @@@ mod remove_write_auto_approvemod repair_http_request_limits;mod retire_chat_v1_model;pub(crate) mod retire_cloud_provider_type;+pub(crate) mod retire_configured_agents;mod retire_local_whisper_stt;- mod retire_managed_tier_slugs;mod unify_ai_provider_settings;/// Current target schema version. Bumped alongside every new migration.diff --cc crates/openhuman-core/src/flows/catalog_storage_resource_tests.rsindex be992331c3,faf14e6116..901053b8db--- a/crates/openhuman-core/src/flows/catalog_storage_resource_tests.rs+++ b/crates/openhuman-core/src/flows/catalog_storage_resource_tests.rs@@@ -23,14 -23,8 +23,15 @@@ fn open_fd_count() -> usize}#[tokio::test]+ #[cfg(feature = "storage-sqlite")]async fn workspace_fd_lifetime_is_separate_from_catalog_callback_lifetime() {+ if crate::util::module_test_process::run(+ module_path!(),+ "workspace_fd_lifetime_is_separate_from_catalog_callback_lifetime",+ ) {+ return;+ }+// Warm the process-wide bus before measuring. Serving additional callback// objects should only add entries to that shared bus, not open a backend.crate::modules::runtime::runtime()diff --cc crates/openhuman-core/src/inference/tokenjuice/mod.rsindex 8496a94ed0,c16b5e73fa..cc38dc03c9--- a/crates/openhuman-core/src/inference/tokenjuice/mod.rs+++ b/crates/openhuman-core/src/inference/tokenjuice/mod.rs@@@ -1,43 -1,122 +1,122 @@@//! OpenHuman host adapter for the separately released TinyJuice module.pub mod config_patch;- pub mod focus;- pub mod generate;- pub mod repl_tools;+ pub use tinyjuice_host::{focus, generate};pub mod savings;pub mod schemas;- pub mod tools;use crate::core::runtime::DispatchCtx;+ use async_trait::async_trait;+ use std::path::{Path, PathBuf};+ use std::sync::Arc;use tinyjuice_bus::names::methods;+ use tinyjuice_bus::repl::ReplLimits;use tinyjuice_bus::types::{AgentTokenjuiceCompression, CompressorKind};+ use tinyjuice_bus::wire::{QueryRequest, QueryResponse};+ use tinytools::{Tool, ToolRunContext, ToolSpec};++ struct ModuleSource(Option<Arc<crate::config::Config>>);++ #[async_trait]+ impl tinyjuice_host::repl_tools::QuerySource for ModuleSource {+ async fn query(+ &self,+ context: Option<&dyn ToolRunContext>,+ request: QueryRequest,+ ) -> Result<QueryResponse, String> {+ let ctx = crate::agent::tinyagents::host::run_context::dispatch_ctx_for_tool(context);+ match &self.0 {+ Some(config) => query_for_config(config, request).await,+ None => query(&ctx, request).await,+ }+ }+ }- pub use repl_tools::{is_repl_tool, repl_tools, repl_tools_for};- pub use tools::TokenjuiceRetrieveTool;+ fn host_repl_tools(+ source: Arc<dyn tinyjuice_host::repl_tools::QuerySource>,+ limits: ReplLimits,+ artifacts_dir: Option<PathBuf>,+ ) -> Vec<Box<dyn Tool>> {+ tinyjuice_host::repl_tools::repl_tools(+ source,+ limits,+ artifacts_dir,- tinytools_std::filesystem::FileReadTool::MAX_FILE_SIZE_BYTES,++ tinyagents_harness_tools::fs::filesystem::FileReadTool::MAX_FILE_SIZE_BYTES,+ None,+ )+ }- use tinyjuice_bus::wire::InstallRequest;+ #[cfg(test)]+ fn repl_tools_with(+ source: Arc<dyn tinyjuice_host::repl_tools::QuerySource>,+ limits: ReplLimits,+ ) -> Vec<Box<dyn Tool>> {+ host_repl_tools(source, limits, None)+ }- use tinyjuice_bus::tools::{LEGACY_RETRIEVE, REPL_TOOLS, RETRIEVE};- pub const LEGACY_RETRIEVE_TOOL_NAME: &str = "retrieve_tool_output";- /// Every name the recovery surface answers to: the live tool plus the two- /// migration aliases a replayed transcript may still call.- pub const RECOVERY_TOOL_NAMES: &[&str] = &[- RETRIEVE,- LEGACY_RETRIEVE,- "tokenjuice_retrieve",- LEGACY_RETRIEVE_TOOL_NAME,- ];-- /// The recovery tool a curated (`ToolScope::Named`) belt is guaranteed to- /// advertise. Only the live tool: the aliases stay registered so an old- /// transcript replays, but putting all three on the wire charged every- /// Named agent for three copies of one schema.- pub const RECOVERY_TOOL_VISIBLE: &[&str] = &[RETRIEVE];-- pub fn is_recovery_tool(name: &str) -> bool {- RECOVERY_TOOL_NAMES.contains(&name)+ /// Whether a name is one of TinyJuice's query tools.+ pub fn is_repl_tool(name: &str) -> bool {+ tinyjuice_bus::tools::REPL_TOOLS.contains(&name)}+ /// Build TinyJuice's query tools against the ambient runtime context.+ pub fn repl_tools() -> Vec<Box<dyn Tool>> {+ host_repl_tools(Arc::new(ModuleSource(None)), ReplLimits::default(), None)+ }++ /// Offer query tools only when enabled handle storage can produce handles.+ pub fn repl_tools_for(config: &crate::config::Config) -> Vec<Box<dyn Tool>> {+ if !repl_handle_active(config) {+ return Vec::new();+ }+ host_repl_tools(+ Arc::new(ModuleSource(Some(Arc::new(config.clone())))),+ ReplLimits::default(),+ Some(crate::security::policy::tool_result_artifacts_dir(+ &config.workspace_dir,+ )),+ )+ }++ pub(crate) fn repl_tools_for_recorded(+ config: Option<&crate::config::Config>,+ workspace_dir: &Path,+ recorded: &[ToolSpec],+ ) -> Vec<Box<dyn Tool>> {+ let current = tinyjuice_bus::tools::repl_tool_declarations();+ let declarations = recorded+ .iter()+ .filter(|spec| is_repl_tool(&spec.name))+ .filter_map(|spec| {+ let current = current.iter().find(|item| item.name == spec.name)?;+ Some(tinyjuice_bus::tools::ReplToolDeclaration {+ name: spec.name.clone(),+ op: current.op.clone(),+ description: spec.description.clone(),+ parameters: spec.parameters.clone(),+ })+ })+ .collect();+ tinyjuice_host::repl_tools::repl_tools_with_declarations(+ declarations,+ Arc::new(ModuleSource(config.cloned().map(Arc::new))),+ ReplLimits::default(),+ Some(crate::security::policy::tool_result_artifacts_dir(+ workspace_dir,+ )),- tinytools_std::filesystem::FileReadTool::MAX_FILE_SIZE_BYTES,++ tinyagents_harness_tools::fs::filesystem::FileReadTool::MAX_FILE_SIZE_BYTES,+ None,+ )+ }++ use tinyjuice_bus::wire::InstallRequest;++ use tinyjuice_bus::tools::REPL_TOOLS;+ pub use tinyjuice_host::recovery::{+ is_recovery_tool, summary_failed_notice, CompactedToolOutput, RECOVERY_TOOL_NAMES,+ RECOVERY_TOOL_VISIBLE,+ };+/// Whether the `[components] juice` switch is on. Off means turns truncate/// tool output only: no compaction, no summary, no `juice_*` / recovery tools,/// and the module is never loaded for it.diff --cc crates/openhuman-core/src/media/generation/artifact_tool.rsindex 92ab8b1943,e39cf65e22..2b1ba5c3f7--- a/crates/openhuman-core/src/media/generation/artifact_tool.rs+++ b/crates/openhuman-core/src/media/generation/artifact_tool.rs@@@ -1,48 -1,114 +1,49 @@@-//! [`MediaArtifactTool`] — wraps a media-generation [`Tool`] (TinyAgents'-//! `GenerateImageTool` / `GenerateVideoTool`, boxed in `super::tools`) so-//! every file the inner tool saves is also filed as a versioned OpenHuman-//! artifact, through the same [`Production`] flow the document and-//! presentation producers use.+//! OpenHuman's media-generation adapters around TinyAgents' generic artifact tool.//!-//! The inner tool writes bytes to its `MediaOutput` blob store and reports-//! each blob key in its JSON result's `artifacts` array-//! (`{"type": "image"|"video", "path", "media_type"|"format", "bytes"}`, see-//! `tinyagents_harness::media::{GenerateImageTool, GenerateVideoTool}`). Host-//! adapters may also report absolute file paths. This wrapper runs the inner-//! tool unchanged, then for every reported output: starts a [`Production`]-//! (recording the provider-assigned tool-call id so the card correlates with-//! the tool-call bubble, #C5), stores the blob or file into the artifact's-//! reserved path, and completes it — or fails just that one-//! artifact and annotates its entry with `artifact_error`, without-//! disturbing the others (`n > 1` generations are common for images). On-//! success each entry gains an `artifact_id` field so the model (and the-//! bridged `chat.tool_result`) can reference the card; the rest of the-//! tool's JSON/markdown result shape is preserved byte-for-byte.-//!-//! A run with no context (`execute`/`execute_with_options`, e.g. CLI/tests)-//! still creates artifacts — the production simply records no-//! `tool_call_id` and the chat-context bridge in `artifacts/store.rs`-//! degrades to `thread_id = None` as it already does for every other-//! producer.+//! TinyAgents owns the result traversal, per-call tool construction, and progress+//! heartbeat. OpenHuman supplies the artifact store, file placement, blob access,+//! and the policy for reusing previously generated files as references.use std::path::{Path, PathBuf};-use std::sync::Arc;+use std::sync::{Arc, RwLock};use async_trait::async_trait;- use serde_json::Value;- use tinyagents_harness_tools::media::{- ArtifactFiling, FiledArtifact, GeneratedArtifact, MediaArtifactKind, MediaInnerFactory,- MediaProgressFn,- };+ use futures_util::StreamExt;+ use serde_json::{json, Value};use tinytools::{- PermissionLevel, Tool, ToolCallOptions, ToolCategory, ToolContent, ToolPolicy, ToolResult,- ToolRunContext, ToolScope, ToolTimeout,+ PermissionLevel, Tool, ToolCallOptions, ToolCategory, ToolPolicy, ToolResult, ToolRunContext,+ ToolScope, ToolTimeout,};use tokio::io::AsyncWriteExt;use crate::artifacts::production::Production;use crate::artifacts::ArtifactKind;+ use crate::security::approval::ApprovalChatContext;+ use crate::tools::host_extensions::tool_call_id;+ use tinyagents_harness::tinyinference_video::ProgressFn;+ use tinystoragedrivers_api::BlobStore;-use super::progress::{video_status_observer, JobStateSlot};--const FILE_REFERENCE_FIELDS: [&str; 8] = [- "references",- "reference_images",- "input_images",- "inputImages",- "first_frame",- "inputImage",- "input_image",- "last_frame",-];--/// Whether a media call references an absolute path under a trusted Files root.-/// Only these requests need a durable-artifact refresh before tool execution.-fn has_reusable_files_reference(args: &Value, files: &crate::artifacts::FileRoots) -> bool {- for field in FILE_REFERENCE_FIELDS {- let Some(value) = args.get(field) else {- continue;- };- let candidates = value.as_str().into_iter().chain(- value- .as_array()- .into_iter()- .flatten()- .filter_map(Value::as_str),- );- if candidates.into_iter().any(|candidate| {- let path = Path::new(candidate);- path.is_absolute() && files.contains_path(path)- }) {- return true;- }- }- false+/// A host adapter that retains OpenHuman artifact behavior while delegating+/// generic media result handling to TinyAgents' harness-tools crate.+pub struct MediaArtifactTool<T: Tool> {+ inner: tinyagents_harness_tools::media::MediaArtifactTool<ReferenceRefreshTool<T>>,+ policy: Arc<RwLock<MediaArtifactPolicy>>,+ workspace_dir: PathBuf,+ files_dir: crate::artifacts::FileRoots,+ allowed_references: Option<super::tools::MediaReferenceAllowlist>,}-/// Maximum characters of the prompt kept in a generated artifact's title.-const TITLE_PROMPT_CHARS: usize = 60;--/// Wraps a media-generation tool so every file it saves is also tracked as-/// an OpenHuman artifact. See module docs for the flow.-pub struct MediaArtifactTool<T: Tool> {- inner: T,+#[derive(Clone)]+struct MediaArtifactPolicy {kind: ArtifactKind,workspace_dir: PathBuf,- /// Visible folder each generated file is moved into (#5505).files_dir: crate::artifacts::FileRoots,- blobs: Option<Arc<dyn tinystoragedrivers::BlobStore>>,+ blobs: Option<Arc<dyn BlobStore>>,allowed_references: Option<super::tools::MediaReferenceAllowlist>,- /// Builds the inner tool for one call around that call's poll observer.- /// Set for the video tool, whose `WaitPolicy::progress` hook is fixed at- /// construction: a tool per call lets the observer record into the call's- /// own [`JobStateSlot`]. `inner` still answers the static `Tool` metadata.- per_call: Option<PerCallInner<T>>,}-type PerCallInner<T> =- std::sync::Arc<dyn Fn(ProgressFn, Option<&ApprovalChatContext>) -> T + Send + Sync>;--impl<T: Tool> MediaArtifactTool<T> {- /// `kind` is the artifact category to file every generated output- /// under (`ArtifactKind::Image` / `ArtifactKind::Video`); `workspace_dir`- /// holds the artifact metadata; `files_dir` is the visible folder the- /// generated file is moved into (#5505).+impl<T: Tool + 'static> MediaArtifactTool<T> {+ /// Creates the host adapter for a media generation tool.pub fn new(inner: T,kind: ArtifactKind,@@@ -80,13 -127,11 +81,10 @@@}/// Reads generated outputs addressed by blob key from the media tool's- /// backing store. This keeps TinyAgents' blob-backed output contract- /// separate from the host's visible Files-folder artifact store.+ /// backing store.#[must_use]- pub fn with_blobs(self, blobs: Arc<dyn tinystoragedrivers::BlobStore>) -> Self {- self.policy- .write()- .unwrap_or_else(std::sync::PoisonError::into_inner)- .blobs = Some(blobs);+ pub fn with_blobs(mut self, blobs: Arc<dyn BlobStore>) -> Self {+ self.blobs = Some(blobs);self}@@@ -116,43 -338,162 +114,132 @@@async fn complete_and_discard_blob(&self,production: &Production,- src: &Path,+ source: &Path,) -> Result<u64, String> {- let size = production.complete().await?;- self.delete_blob_after_finalize(src).await;- Ok(size)+ OpenHumanArtifactFiling(Arc::clone(&self.policy))+ .complete_and_discard_blob(production, source)+ .await}- /// Rehydrates finalized media paths after a session rebuild. Only Ready- /// image/video artifacts whose files still resolve through the configured- /// trusted roots enter the exact-path allowlist.- async fn refresh_allowed_references(&self) -> Result<(), String> {- let Some(allowed) = &self.allowed_references else {- return Ok(());- };-- let mut recovered = std::collections::HashSet::new();- let previously_allowed = allowed- .lock()- .unwrap_or_else(std::sync::PoisonError::into_inner)- .clone();- let artifacts =- match crate::artifacts::store::list_artifacts(&self.workspace_dir, 0, usize::MAX, None)- .await- {- Ok((artifacts, _)) => artifacts,- Err(error) => {- tracing::warn!(- target: "media_generation",- %error,- "[media_generation] could not refresh reusable artifact paths"- );- return Err(- "could not validate previously generated media references; retry the media call"- .to_string(),- );- }- };-- for meta in artifacts.iter().filter(|meta| {- matches!(&meta.kind, ArtifactKind::Image | ArtifactKind::Video)- && matches!(&meta.status, crate::artifacts::ArtifactStatus::Ready)- }) {- let Ok(path) = crate::artifacts::resolve_ready_file_meta(- &self.workspace_dir,- &self.files_dir,- meta,- )- .await- else {- continue;- };- if let Ok(path) = tokio::fs::canonicalize(path).await {- recovered.insert(path);- }+ /// Builds the inner generator for one call around its provider progress+ /// observer and the call's own host context.+ #[must_use]+ pub fn with_per_call_inner(+ self,+ build: impl for<'a> Fn(MediaProgressFn, Option<&'a dyn ToolRunContext>) -> T+ + Send+ + Sync+ + 'static,+ ) -> Self {+ let Self {+ inner,+ policy,+ workspace_dir,+ files_dir,+ allowed_references,+ } = self;+ let build: MediaInnerFactory<T> = Arc::new(build);+ let per_call_policy = Arc::clone(&policy);+ let inner = inner.with_per_call_inner(Arc::new(move |progress, context| {+ ReferenceRefreshTool::new(build(progress, context), Arc::clone(&per_call_policy))+ }));+ Self {+ inner,+ policy,+ workspace_dir,+ files_dir,+ allowed_references,}-- // Prune paths that were allowed before this scan but are no longer- // Ready. Paths added concurrently after the snapshot are preserved.- let mut allowed = allowed- .lock()- .unwrap_or_else(std::sync::PoisonError::into_inner);- allowed.retain(|path| !previously_allowed.contains(path) || recovered.contains(path));- allowed.extend(recovered);- Ok(())}++ async fn file_blob(&self, key: &Path, dest: &Path) -> Result<u64, String> {+ let key = key+ .to_str()+ .ok_or_else(|| "generated media blob key is not valid UTF-8".to_string())?;+ let blobs = self.blobs.as_ref().ok_or_else(|| {+ format!("generated media returned blob key {key:?} without a blob store")+ })?;+ let mut blob = blobs+ .get_stream(key)+ .await+ .map_err(|error| format!("failed to read generated media blob {key:?}: {error}"))?+ .ok_or_else(|| format!("generated media blob {key:?} was not found"))?;+ copy_blob_to_file(&mut blob.reader, dest, key).await+ }+ }++ async fn copy_blob_to_file(+ reader: &mut tinyagents_storage_kit::blob::BlobReader,+ dest: &Path,+ key: &str,+ ) -> Result<u64, String> {+ let mut file = tokio::fs::OpenOptions::new()+ .write(true)+ .truncate(true)+ .open(dest)+ .await+ .map_err(|error| {+ format!(+ "failed to open artifact destination {}: {error}",+ dest.display()+ )+ })?;+ let mut size = 0_u64;+ while let Some(chunk) = reader.next().await {+ let chunk = match chunk {+ Ok(chunk) => chunk,+ Err(error) => {+ drop(file);+ let _ = tokio::fs::remove_file(dest).await;+ return Err(format!(+ "failed to copy generated media blob {key:?}: {error}"+ ));+ }+ };+ if let Err(error) = file.write_all(&chunk).await {+ drop(file);+ let _ = tokio::fs::remove_file(dest).await;+ return Err(format!(+ "failed to write generated media blob {key:?}: {error}"+ ));+ }+ size = size.saturating_add(chunk.len() as u64);+ }+ if let Err(error) = file.flush().await {+ drop(file);+ let _ = tokio::fs::remove_file(dest).await;+ return Err(format!(+ "failed to flush artifact destination {}: {error}",+ dest.display()+ ));+ }+ Ok(size)+ }++ fn set_artifact_error(entry: &mut Value, message: &str) {+ if let Some(obj) = entry.as_object_mut() {+ obj.insert("artifact_error".into(), json!(message));+ }+ }++ /// Moves `src` to `dest`, falling back to copy + remove across filesystem+ /// boundaries (`rename` fails with `EXDEV` when the files folder and the+ /// media output dir are on different mounts). Returns the final file size.+ async fn move_or_copy(src: &Path, dest: &Path) -> Result<u64, String> {+ if tokio::fs::rename(src, dest).await.is_err() {+ tokio::fs::copy(src, dest).await.map_err(|e| {+ format!(+ "failed to copy {} -> {}: {e}",+ src.display(),+ dest.display()+ )+ })?;+ let _ = tokio::fs::remove_file(src).await;+ }+ let stat = tokio::fs::metadata(dest)+ .await+ .map_err(|e| format!("failed to stat {}: {e}", dest.display()))?;+ Ok(stat.len())}#[async_trait]diff --cc crates/openhuman-core/src/sandbox/shell_exec_fixture.rsindex 64b7aa36d9,6c498619fc..aa324f3533--- a/crates/openhuman-core/src/sandbox/shell_exec_fixture.rs+++ b/crates/openhuman-core/src/sandbox/shell_exec_fixture.rs@@@ -59,28 -64,69 +64,69 @@@ pub(crate) async fn run(run: NativeShel.stdout(Stdio::piped()).stderr(Stdio::piped()).kill_on_drop(true);- tinytools_std::timeout::own_process_group(command.as_std_mut());+ tinyagents_harness_tools::exec::timeout::own_process_group(command.as_std_mut());- match tinyagents_harness_tools::exec::timeout::output_or_kill(&mut command, run.timeout).await {- Ok(Ok(output)) => {- // The module streams output into the caller's meter as it reads it;- // the fixture folds the finished output in the same way.- if let Some(meter) = &run.meter {- meter.record(&output.stdout);- meter.record(&output.stderr);+ let mut child = command+ .spawn()+ .map_err(|error| anyhow::anyhow!("Failed to execute command: {error}"))?;+ let pid = child.id();+ // Read both streams as the command runs, like the module does, so a+ // command stopped at its deadline keeps what it printed before.+ let (mut stdout_pipe, mut stderr_pipe) = (child.stdout.take(), child.stderr.take());+ let (mut stdout, mut stderr) = (Vec::new(), Vec::new());+ let finished = tokio::time::timeout(run.timeout, async {+ let (status, (), ()) = tokio::join!(+ child.wait(),+ drain(&mut stdout_pipe, &mut stdout),+ drain(&mut stderr_pipe, &mut stderr),+ );+ status+ })+ .await;+ let (exit_code, timed_out) = match finished {+ Ok(status) => (status?.code().unwrap_or(-1), false),+ Err(_) => {+ // Stop the command and everything it started, then give the+ // readers a moment to drain what is left in the pipes.+ if let Some(pid) = pid {- tinytools_std::timeout::kill_process_group(pid);++ tinyagents_harness_tools::exec::timeout::kill_process_group(pid);}- Ok(SandboxExecResult {- exit_code: output.status.code().unwrap_or(-1),- stdout: String::from_utf8_lossy(&output.stdout).into_owned(),- stderr: String::from_utf8_lossy(&output.stderr).into_owned(),- timed_out: false,+ let _ = child.start_kill();+ let _ = tokio::time::timeout(Duration::from_secs(2), async {+ tokio::join!(+ drain(&mut stdout_pipe, &mut stdout),+ drain(&mut stderr_pipe, &mut stderr),+ )})+ .await;+ (-1, true)+ }+ };+ // The module streams output into the caller's meter as it reads it; the+ // fixture folds the collected output in the same way.+ if let Some(meter) = &run.meter {+ meter.record(&stdout);+ meter.record(&stderr);+ }+ Ok(SandboxExecResult {+ exit_code,+ stdout: String::from_utf8_lossy(&stdout).into_owned(),+ stderr: String::from_utf8_lossy(&stderr).into_owned(),+ timed_out,+ })+ }++ /// Appends what `pipe` delivers to `into` until it closes. Reads are+ /// cancel-safe, so a drain cut short by the deadline keeps every chunk it read,+ /// and a later call picks up where it stopped.+ async fn drain(pipe: &mut Option<impl AsyncRead + Unpin>, into: &mut Vec<u8>) {+ let Some(pipe) = pipe else {+ return;+ };+ let mut chunk = [0u8; 8192];+ while let Ok(read) = pipe.read(&mut chunk).await {+ if read == 0 {+ break;}- Ok(Err(error)) => anyhow::bail!("Failed to execute command: {error}"),- Err(_) => Ok(SandboxExecResult {- exit_code: -1,- stdout: String::new(),- stderr: format!("Command timed out after {}s", run.timeout.as_secs()),- timed_out: true,- }),+ into.extend_from_slice(&chunk[..read]);}}diff --cc crates/openhuman-core/src/storage/schema_tests.rsindex 8765691573,5e82c540c5..08ab80c814--- a/crates/openhuman-core/src/storage/schema_tests.rs+++ b/crates/openhuman-core/src/storage/schema_tests.rs@@@ -25,44 -40,19 +40,51 @@@ fn every_linked_crate_exposes_its_valid}#[test]- fn module_items_are_the_owners_module_scoped_declarations() {- let mcp = module_items("mcp");- assert!(mcp- .collections- .iter()- .any(|spec| spec.name == "mcp.servers"));- assert!(mcp.streams.iter().any(|name| name == "mcp.audit"));- assert!(module_items("no-such-owner").collections.is_empty());+ fn module_collections_are_limited_to_the_named_owner() {+ let mcp = module_collections("mcp");+ assert!(mcp.iter().any(|spec| spec.name == "mcp.servers"));+ assert!(module_collections("no-such-owner").is_empty());+ }++ #[test]+ fn tinyjuice_ccr_blobs_stay_inside_the_juice_owner_namespace() {+ assert_eq!(+ module_collections("juice")+ .iter()+ .map(|collection| collection.name.as_str())+ .collect::<Vec<_>>(),+ [tinyjuice_bus::storage::SAVINGS_COLLECTION]+ );}++#[test]+fn tiny_artifacts_blob_namespace_composes_with_host_artifact_collections() {+ let registry = registry().expect("the owners compose");+ assert_eq!(+ registry+ .owners()+ .filter(|owner| *owner == "artifacts")+ .count(),+ 1+ );++ let artifacts = owner_schemas()+ .into_iter()+ .find(|schema| schema.owner.as_str() == "artifacts")+ .expect("the artifact owners are composed");+ assert!(artifacts.items.iter().any(|item| matches!(+ item,+ Item::Collection { name, .. } if name == "artifacts.records"+ )));+ assert!(artifacts.items.iter().any(|item| matches!(+ item,+ Item::Blobs {+ prefix,+ scope: ScopeClass::Tenant,+ } if prefix == "artifacts/files/"+ )));+ assert!(!module_items("artifacts")+ .blobs+ .iter()+ .any(|prefix| prefix == "artifacts/files/"));+}diff --cc crates/openhuman-core/src/storage/sessions/host_stores.rsindex 0790527180,81e14bb3a5..24590cc4ca--- a/crates/openhuman-core/src/storage/sessions/host_stores.rs+++ b/crates/openhuman-core/src/storage/sessions/host_stores.rs@@@ -69,21 -69,13 +69,26 @@@ pub fn provider_for_workspace(workspace}}+/// The provider selected by `context` for `workspace_dir`, else the workspace+/// fallback. This preserves agent-local host overrides when work carries an+/// explicit dispatch context rather than the ambient task context.+pub fn provider_for_workspace_in(+ workspace_dir: &Path,+ context: &crate::core::runtime::DispatchCtx,+) -> Arc<dyn SessionStoreProvider> {+ match super::installed_in(context) {+ Some(installed) => installed,+ None => fallback_provider(workspace_dir),+ }+}+/// The provider over `workspace_dir`'s default backend, installed or not.pub(super) fn fallback_provider(workspace_dir: &Path) -> Arc<dyn SessionStoreProvider> {+ if crate::core::runtime::is_saas() && crate::storage::installed().is_none() {+ return refusing_provider(+ "no host storage backend is installed for this SaaS session".to_owned(),+ );+ }let backend = match crate::storage::local::backend_for(workspace_dir) {Ok(backend) => backend,Err(error) => {@@@ -213,70 -207,14 +220,71 @@@ pub fn artifact_blobs_for(workspace_dirSome(Arc::clone(scoped.blobs()))}+/// The artifact ports for the tenant carried by `context` on the workspace's+/// storage backend. Unlike [`artifact_blobs_for`], this does not consult the+/// ambient dispatch context, so a tool that was moved to a detached task keeps+/// using the profile that authorized the call.+#[must_use]+pub fn artifact_scoped_for_in(+ workspace_dir: &Path,+ context: &crate::core::runtime::DispatchCtx,+) -> Option<ScopedStorage> {+ let tenant = match context.tenant() {+ Ok(tenant) => tenant,+ Err(no_tenant) => {+ log::warn!("[session_store] no tenant for artifact scope: {no_tenant}");+ return None;+ }+ };+ // Match the storage domain's established scope for this tenant. Session+ // keys encode a default agent even when the storage scope is local, so do+ // not derive artifact scope from the session key.+ let scope = match crate::storage::scope_from(+ tenant.profile.as_deref(),+ tenant.agent.as_deref(),+ crate::core::runtime::mode::is_saas(),+ ) {+ Ok(scope) => scope,+ Err(error) => {+ log::warn!("[session_store] no artifact storage scope: {error}");+ return None;+ }+ };+ let backend = match context.resolved() {+ Some(core) => crate::core::runtime::CoreContext::sync_scope(core, || {+ crate::storage::local::backend_for(workspace_dir)+ }),+ // Outside SaaS, an unresolved context represents the single-user+ // default tenant validated above. The backend slot is process-global.+ None => crate::storage::local::backend_for(workspace_dir),+ };+ let backend = match backend {+ Ok(backend) => backend,+ Err(error) => {+ log::warn!("[session_store] no storage backend for artifacts: {error:#}");+ return None;+ }+ };+ match backend.for_scope(&scope) {+ Ok(scoped) => Some(scoped),+ Err(error) => {+ log::warn!(+ "[session_store] artifact scope refused scope={}: {error}",+ scope.as_str()+ );+ None+ }+ }+}+/// The calling tenant's scoped storage on `workspace_dir`'s backend. `what`/// only labels the log line when the backend or scope is refused.- fn tenant_scope_for(- workspace_dir: &Path,- what: &str,- ) -> Option<(String, tinystoragedrivers::ScopedStorage)> {- let key = tenant_agent_key()?;+ fn tenant_scope_for(workspace_dir: &Path, what: &str) -> Option<(String, ScopedStorage)> {+ let key = match tenant_agent_key() {+ Some(key) => key,+ None if !crate::core::runtime::is_saas() => super::DEFAULT_AGENT.to_owned(),+ None => return None,+ };let backend = match crate::storage::local::backend_for(workspace_dir) {Ok(backend) => backend,Err(error) => {diff --cc crates/openhuman-core/src/storage/sessions/tenant_router.rsindex 20155111a2,da26d0b1ca..1f689fd9c1--- a/crates/openhuman-core/src/storage/sessions/tenant_router.rs+++ b/crates/openhuman-core/src/storage/sessions/tenant_router.rs@@@ -10,127 -10,15 +10,15 @@@//! `u:<profile>/agent:<id>`, inside the tenant fence.use std::collections::HashMap;-use std::sync::{Arc, Mutex, PoisonError};+use std::sync::{Arc, LazyLock, Mutex, PoisonError, RwLock, Weak};use tinyagents_harness::store::SchemaAdmission;- use tinyagents_session::port::{- AgentStores, SessionStoreLease, SessionStoreLeaseError, SessionStoreProvider,- };- use tinyagents_session::{RebindableSessionStores, SessionStoreRegistry};- use tinystoragedrivers::{Scope, StorageBackend, StorageError};+ use tinyagents_session::port::{AgentStorageFactory, AgentStores, SessionStoreProvider};+ use tinyagents_session::DriverSessionStores;+ use tinyagents_storage_kit::{Blocking, Scope as PortScope, ScopedStorage};+ use tinystoragedrivers::{StorageBackend, StorageError};- type TenantProviders = Mutex<HashMap<Scope, Arc<RebindableSessionStores>>>;-- #[derive(Default)]- struct TenantStoreRegistry {- providers: Arc<SessionStoreRegistry>,- state: Mutex<TenantStoreRegistryState>,- }-- #[derive(Default)]- struct TenantStoreRegistryState {- backends: Vec<Weak<RwLock<Arc<dyn StorageBackend>>>>,- tenants: Vec<Weak<TenantProviders>>,- current_backend: Option<Arc<dyn StorageBackend>>,- }-- impl TenantStoreRegistry {- fn rebind(&self, backend: &Arc<dyn StorageBackend>) -> Result<usize, StorageError> {- let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner);- let backends = state- .backends- .iter()- .filter_map(Weak::upgrade)- .collect::<Vec<_>>();- let tenant_maps = state- .tenants- .iter()- .filter_map(Weak::upgrade)- .collect::<Vec<_>>();- // `route` locks tenants before reading the backend. Keep that lock- // order while preventing new providers from appearing during rebind.- let tenant_maps = tenant_maps- .iter()- .map(|tenants| tenants.lock().unwrap_or_else(PoisonError::into_inner))- .collect::<Vec<_>>();- let mut bindings = backends- .iter()- .map(|backend| backend.write().unwrap_or_else(PoisonError::into_inner))- .collect::<Vec<_>>();-- let mut providers = tenant_maps- .iter()- .zip(&bindings)- .flat_map(|(tenants, current_backend)| {- tenants.iter().map(move |(tenant, provider)| {- (- tenant.as_str().to_owned(),- Arc::clone(provider),- Arc::clone(current_backend),- )- })- })- .collect::<Vec<_>>();- // A stable order makes a later-provider failure deterministic and- // keeps rollback behavior predictable across runs.- providers.sort_by(|left, right| left.0.cmp(&right.0));-- let mut moved: Vec<(Arc<RebindableSessionStores>, Arc<dyn StorageBackend>)> =- Vec::with_capacity(providers.len());- for (_, provider, old_backend) in &providers {- if let Err(error) = provider.rebind(Arc::clone(backend)) {- let mut rollback_failures = Vec::new();- for (moved_provider, moved_backend) in moved.iter().rev() {- if let Err(rollback_error) = moved_provider.rebind(Arc::clone(moved_backend)) {- rollback_failures.push(rollback_error.to_string());- }- }- if rollback_failures.is_empty() {- tracing::error!(target: "openhuman::storage", %error, "[session_store] tenant provider rebind failed; prior providers were restored");- return Err(error);- }- tracing::error!(target: "openhuman::storage", %error, rollback_errors = ?rollback_failures, restored = moved.len() - rollback_failures.len(), "[session_store] tenant provider rebind and rollback failed; providers may remain split across backends");- return Err(StorageError::invalid_input(format!(- "tenant session-store rebind failed ({error}); rollback failed for {} provider(s): {}",- rollback_failures.len(),- rollback_failures.join("; ")- )));- }- moved.push((Arc::clone(provider), Arc::clone(old_backend)));- }-- for current in &mut bindings {- **current = Arc::clone(backend);- }- state.backends.retain(|weak| weak.strong_count() > 0);- state.tenants.retain(|weak| weak.strong_count() > 0);- state.current_backend = Some(Arc::clone(backend));- Ok(moved.len())- }-- fn register_backend(- &self,- backend: &Arc<RwLock<Arc<dyn StorageBackend>>>,- tenants: &Arc<TenantProviders>,- ) {- let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner);- if let Some(current) = &state.current_backend {- *backend.write().unwrap_or_else(PoisonError::into_inner) = Arc::clone(current);- }- state.backends.retain(|weak| weak.strong_count() > 0);- state.backends.push(Arc::downgrade(backend));- state.tenants.retain(|weak| weak.strong_count() > 0);- state.tenants.push(Arc::downgrade(tenants));- }- }-- static PROCESS_SESSION_STORES: LazyLock<Arc<TenantStoreRegistry>> =- LazyLock::new(|| Arc::new(TenantStoreRegistry::default()));-- /// Rebinds the host's live tenant routers to `backend`.- pub fn rebind_all(backend: &Arc<dyn StorageBackend>) -> Result<usize, StorageError> {- PROCESS_SESSION_STORES.rebind(backend)- }+ use crate::storage::Scope;/// Session stores over one backend, routed to a per-tenant provider.pub struct TenantSessionStores {@@@ -146,9 -34,7 +34,8 @@@impl std::fmt::Debug for TenantSessionStores {fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {let tenants = self.tenants.lock().unwrap_or_else(PoisonError::into_inner);+ let backend = self.backend.read().unwrap_or_else(PoisonError::into_inner);f.debug_struct("TenantSessionStores")- .field("driver", &backend.driver()).field("tenants", &tenants.len()).finish_non_exhaustive()}@@@ -271,16 -144,11 +155,16 @@@ impl SessionStoreProvider for TenantSesprovider.try_for_agent(&agent)}+ fn lease_for_agent(&self, agent_id: &str) -> Result<SessionStoreLease, SessionStoreLeaseError> {+ let (provider, agent) = self.route(agent_id);+ provider.lease_for_agent(&agent)+ }+fn bind_actor(&self,- backend: Arc<dyn StorageBackend>,+ factory: AgentStorageFactory,) -> Result<Option<Arc<dyn SessionStoreProvider>>, StorageError> {- self.bind_actor_with_schema_admission(backend, self.admission)+ self.bind_actor_with_schema_admission(factory, self.admission)}fn bind_actor_with_schema_admission(diff --cc crates/openhuman-core/src/threads/ops.rsindex 9ee2c9a38e,c0a42b1f72..675408974d--- a/crates/openhuman-core/src/threads/ops.rs+++ b/crates/openhuman-core/src/threads/ops.rs@@@ -24,11 -24,10 +24,12 @@@ pub use edit::edit_message, regenerate, EditMessageRequest, EditOrRegenerateResponse, RegenerateRequest,};pub use live_state::{- goal_get, todos_get, ThreadGoalGetResponse, ThreadLiveStateRequest, ThreadTodosGetResponse,+ goal_get, state_get, todos_get, ThreadGoalGetResponse, ThreadLiveStateRequest,+ ThreadStateGetResponse, ThreadTodosGetResponse,};pub use purge::threads_purge;+#[cfg(test)]+pub(crate) use purge::threads_purge_inner_with_snapshot_hook;pub use search::{thread_search, ThreadSearchHit, ThreadSearchRequest, ThreadSearchResponse};pub use title_generation::thread_generate_title;pub use transcript::{transcript_get, TranscriptGetRequest};diff --cc crates/openhuman-core/src/threads/ops/live_state.rsindex d456ce4c2b,c49eaf2fa3..629c843abb--- a/crates/openhuman-core/src/threads/ops/live_state.rs+++ b/crates/openhuman-core/src/threads/ops/live_state.rs@@@ -4,10 -4,11 +4,11 @@@//! separately over the web channel (`thread_goal_updated`/`thread_goal_cleared`,//! `thread_todos_changed` — see `web_chat::event_bus`); these RPCs are the//! one-shot "what is it right now" read a client makes when it opens a thread- //! that already had one in flight.+ //! that already had one in flight. `state_get` reads both plus the agent's+ //! notes in one call, with the run-state block they render to.use super::support::{envelope, workspace_dir};-use crate::agent::goals::goal_to_value;+use crate::agent::goals::{goal_store, goal_to_value};use crate::core::Outcome;use crate::threads::ApiEnvelope;diff --cc crates/openhuman-core/src/tools/impl/filesystem/gate.rsindex f83f3d1cd3,d2c9fdfc4e..0c9a42fb57--- a/crates/openhuman-core/src/tools/impl/filesystem/gate.rs+++ b/crates/openhuman-core/src/tools/impl/filesystem/gate.rs@@@ -8,11 -8,11 +8,11 @@@ use std::path::{Path, PathBuf}use std::sync::Arc;use async_trait::async_trait;-use tinytools_std::filesystem::FsGate;+use tinyagents_harness_tools::fs::filesystem::FsGate;+ use crate::security::policy::CommandClass;use crate::security::policy::{TrustedAccess, TrustedRoot};use crate::security::{AutonomyLevel, GateDecision, SecurityPolicy};- use tinybox_bus::CommandClass;/// Clone `security` and scope it to `root`, a run's workspace descriptor root.///diff --cc crates/openhuman-core/src/tools/impl/system/shell.rsindex 4d01749b8a,1b55fd9c7f..edef605ef7--- a/crates/openhuman-core/src/tools/impl/system/shell.rs+++ b/crates/openhuman-core/src/tools/impl/system/shell.rs@@@ -1,7 -1,10 +1,9 @@@-use super::shell_description::{command_param_description, shell_description};#[cfg(feature = "modules")]use super::shell_support::container_environment;- use super::shell_support::{command_failure, exec_result, python_utf8_env, tool_timeout_message};- use crate::agent::tinyagents::host::run_context::command_environment_for_tool;+ use super::shell_support::{command_failure, exec_result, tool_timeout_message};+ use crate::agent::tinyagents::host::run_context::{+ command_environment_for_tool, dispatch_ctx_for_tool,+ };use crate::config::Config;use crate::core::runtime::DispatchCtx;use crate::modules::tinybox::host_runtime::RuntimeAdapter;@@@ -556,9 -707,9 +558,9 @@@ impl ShellHostcommand_environment.as_deref(),);// Apply the same Git config hardening to local and sandboxed shells.- extra_env.extend(tinytools_std::filesystem::shell_git_env());+ extra_env.extend(tinyagents_harness_tools::fs::filesystem::shell_git_env());- // And the same Python UTF-8 defaults the native path sets.- for (var, val) in python_utf8_env(|name| {+ // And the same Python defaults the native path sets.+ for (var, val) in super::shell_support::python_env_defaults(|name| {command_environment.as_ref().and_then(|overrides| overrides.get(name).map(std::ffi::OsString::from))diff --cc crates/openhuman-core/src/web_chat/progress_bridge.rsindex 103c275aa1,051d3e6a2d..c6cee03cab--- a/crates/openhuman-core/src/web_chat/progress_bridge.rs+++ b/crates/openhuman-core/src/web_chat/progress_bridge.rs@@@ -6,13 -6,16 +6,16 @@@use serde_json::json;use crate::threads::turn_state::mirror::ObserveProgress;-use crate::web_chat::{SubagentProgressDetail, WebChannelEvent};+use crate::web_chat::WebChannelEvent;use tinyagents_session::{port::TurnStates, turn_state::TurnStateMirror};- use super::event_bus::publish_web_channel_event_in;use super::types::ChatRequestMetadata;- use crate::core::runtime::DispatchCtx;+ #[path = "progress_bridge_narration.rs"]+ mod narration;+ #[cfg(test)]+ use narration::interim_narration_text;+ use narration::{flush_interim_narration, publish_seq_stamped, MIN_INTERIM_NARRATION_CHARS};#[path = "progress_bridge_subagent_events.rs"]mod subagent_events;#[path = "progress_bridge_text_events.rs"]diff --cc crates/openhuman-embed/Cargo.tomlindex 90a3a3e0f2,a8e5859fe8..367012b589--- a/crates/openhuman-embed/Cargo.toml+++ b/crates/openhuman-embed/Cargo.toml@@@ -78,8 -82,8 +82,8 @@@ tinymcp-bus = { path = "../../vendor/ti# conversations in its own database, and the in-memory provider; same path as# the core's so one copy resolves.tinyagents-hooks = { workspace = true }- tinyagents-harness-tools = { workspace = true, default-features = false, features = ["todos", "exec"] }++tinyagents-harness-tools = { workspace = true, default-features = false, features = ["todos"] }tinyagents-harness = { path = "../../vendor/tinyagents/crates/tinyagents-harness", default-features = false }-tinyagents-harness-tools = { path = "../../vendor/tinyagents/crates/tinyagents-harness-tools", default-features = false, features = ["todos"] }tinyagents-definition = { path = "../../vendor/tinyagents/crates/tinyagents-definition" }tinyagents-session = { path = "../../vendor/tinyagents/crates/tinyagents-session" }# Native persisted todo codec exposed by the existing session-store contract.diff --cc scripts/__tests__/embed-contract-boundary.test.mjsindex 5cb80fa6a7,d9292e3598..12a1ce31e4--- a/scripts/__tests__/embed-contract-boundary.test.mjs+++ b/scripts/__tests__/embed-contract-boundary.test.mjs@@@ -76,10 -132,9 +132,9 @@@ test("native injection allowances rejec}});-test("Embed preserves native persisted codecs without admitting core facades", () => {const codecs = [- "pub use tinyagents_graph::todos::TodoList;",+ "pub use tinyagents_harness_tools::todos::TodoList;","pub use tinyagents_harness::events::{AgentEvent, HarnessRunStatus};","pub use tinyagents_harness::ids::ExecutionStatus;","pub use tinyagents_harness::observability::AgentObservation;",diff --cc tests/json_rpc_config_e2e.rsindex 0000000000,048c2ca4c7..25c51b6264mode 000000,100644..100644--- a/tests/json_rpc_config_e2e.rs+++ b/tests/json_rpc_config_e2e.rs@@@ -1,0 -1,632 +1,632 @@@+ //! JSON-RPC E2E cases for the config namespace.++ #[path = "support/rpc_e2e_harness.rs"]+ mod harness;+ use harness::*;++ #[tokio::test]+ async fn json_rpc_legacy_provider_type_preserves_default_endpoint() {+ let _env_lock = json_rpc_e2e_env_lock_async().await;+ let tmp = tempdir().expect("tempdir");+ let home = tmp.path();+ let _home_guard = EnvVarGuard::set_to_path("HOME", home);+ let _workspace_guard = EnvVarGuard::unset("OPENHUMAN_WORKSPACE");+ let _backend_url_guard = EnvVarGuard::unset("BACKEND_URL");+ let _vite_backend_guard = EnvVarGuard::unset("VITE_BACKEND_URL");+ write_min_config(&home.join(".openhuman"), "http://127.0.0.1:9");+ let (rpc_addr, rpc_join) = serve_on_ephemeral(build_core_http_router(false)).await;+ let rpc_base = format!("http://{rpc_addr}");+ for (index, method) in [+ "openhuman.config_update_model_settings",+ "openhuman.inference_update_model_settings",+ ]+ .into_iter()+ .enumerate()+ {+ let updated = post_json_rpc(+ &rpc_base,+ 41_250 + index as i64,+ method,+ json!({+ "cloud_providers": [{"slug": "legacy", "endpoint": "", "type": " anthropic ",+ "default_model": "claude-sonnet-4"}]+ }),+ )+ .await;+ let snapshot = peel_logs_envelope(assert_no_jsonrpc_error(+ &updated,+ "legacy provider endpoint update",+ ));+ let path = snapshot["config_path"].as_str().expect("saved config path");+ let persisted: openhuman_core::config::Config =+ toml::from_str(&std::fs::read_to_string(path).unwrap()).unwrap();+ let provider = persisted+ .cloud_providers+ .iter()+ .find(|p| p.slug == "legacy")+ .unwrap();+ assert_eq!(+ provider.endpoint, "https://api.anthropic.com/v1",+ "{method}"+ );+ assert_eq!(+ provider.auth_style,+ openhuman_core::config::schema::AuthStyle::Anthropic+ );+ assert_eq!(provider.default_model.as_deref(), Some("claude-sonnet-4"));+ let updated = post_json_rpc(+ &rpc_base,+ 41_260 + index as i64,+ method,+ json!({"cloud_providers": [{"slug": "legacy", "endpoint": "http://127.0.0.1:9/v1",+ "type": "anthropic", "auth_style": "bearer"}]}),+ )+ .await;+ let snapshot = peel_logs_envelope(assert_no_jsonrpc_error(+ &updated,+ "explicit provider values",+ ));+ let providers = snapshot["config"]["cloud_providers"].as_array().unwrap();+ let provider = providers.iter().find(|p| p["slug"] == "legacy").unwrap();+ assert_eq!(provider["endpoint"], "http://127.0.0.1:9/v1");+ assert_eq!(provider["auth_style"], "bearer");+ }+ rpc_join.abort();+ }++ #[tokio::test]+ async fn json_rpc_config_update_browser_settings_persists_backend() {+ let _env_lock = json_rpc_e2e_env_lock_async().await;+ let tmp = tempdir().expect("tempdir");+ let home = tmp.path();+ let openhuman_home = home.join(".openhuman");++ let _home_guard = EnvVarGuard::set_to_path("HOME", home);+ let _workspace_guard = EnvVarGuard::unset("OPENHUMAN_WORKSPACE");+ let _backend_url_guard = EnvVarGuard::unset("BACKEND_URL");+ let _vite_backend_guard = EnvVarGuard::unset("VITE_BACKEND_URL");++ write_min_config(&openhuman_home, "http://127.0.0.1:9");++ let (rpc_addr, rpc_join) = serve_on_ephemeral(build_core_http_router(false)).await;+ let rpc_base = format!("http://{rpc_addr}");++ let updated = post_json_rpc(+ &rpc_base,+ 41_241,+ "openhuman.config_update_browser_settings",+ json!({+ "enabled": true,+ "backend": "playwright",+ "learn_from_tasks": false+ }),+ )+ .await;+ let updated_result =+ assert_no_jsonrpc_error(&updated, "config_update_browser_settings backend");+ let updated_snapshot = peel_logs_envelope(updated_result);+ assert_eq!(+ updated_snapshot+ .pointer("/config/browser/enabled")+ .and_then(Value::as_bool),+ Some(true),+ "browser enabled flag should persist in update response: {updated_snapshot}"+ );+ assert_eq!(+ updated_snapshot+ .pointer("/config/browser/backend")+ .and_then(Value::as_str),+ Some("playwright"),+ "browser backend should persist in update response: {updated_snapshot}"+ );++ let get = post_json_rpc(&rpc_base, 41_242, "openhuman.config_get", json!({})).await;+ let get_result = assert_no_jsonrpc_error(&get, "config_get");+ let snapshot = peel_logs_envelope(get_result);+ assert_eq!(+ snapshot+ .pointer("/config/browser/backend")+ .and_then(Value::as_str),+ Some("playwright"),+ "browser backend should persist in config_get response: {snapshot}"+ );+ assert_eq!(+ snapshot+ .pointer("/config/browser/learn_from_tasks")+ .and_then(Value::as_bool),+ Some(false),+ "switching learning off should persist in config_get response: {snapshot}"+ );++ let invalid = post_json_rpc(+ &rpc_base,+ 41_243,+ "openhuman.config_update_browser_settings",+ json!({+ "backend": "netscape"+ }),+ )+ .await;+ assert_jsonrpc_error(&invalid, "invalid browser backend");++ rpc_join.abort();+ }++ #[tokio::test]+ async fn json_rpc_reasoning_effort_persists_and_rejects_unknown_levels() {+ let _env_lock = json_rpc_e2e_env_lock_async().await;+ let tmp = tempdir().expect("tempdir");+ let home = tmp.path();+ let openhuman_home = home.join(".openhuman");++ let _home_guard = EnvVarGuard::set_to_path("HOME", home);+ let _workspace_guard = EnvVarGuard::unset("OPENHUMAN_WORKSPACE");+ let _backend_url_guard = EnvVarGuard::unset("BACKEND_URL");+ let _vite_backend_guard = EnvVarGuard::unset("VITE_BACKEND_URL");++ write_min_config(&openhuman_home, "http://127.0.0.1:9");++ let (rpc_addr, rpc_join) = serve_on_ephemeral(build_core_http_router(false)).await;+ let rpc_base = format!("http://{rpc_addr}");++ // The composer's default: an alias is stored as the canonical wire token+ // and surfaces in the client config the UI loads.+ let updated = post_json_rpc(+ &rpc_base,+ 41_251,+ "openhuman.config_update_runtime_settings",+ json!({ "reasoning_effort": "max" }),+ )+ .await;+ assert_no_jsonrpc_error(&updated, "config_update_runtime_settings reasoning_effort");+ let client = post_json_rpc(+ &rpc_base,+ 41_252,+ "openhuman.inference_get_client_config",+ json!({}),+ )+ .await;+ let client_config = peel_logs_envelope(assert_no_jsonrpc_error(+ &client,+ "inference_get_client_config",+ ));+ assert_eq!(+ client_config+ .get("reasoning_effort")+ .and_then(Value::as_str),+ Some("xhigh"),+ "client config should report the saved thinking level: {client_config}"+ );++ let invalid_default = post_json_rpc(+ &rpc_base,+ 41_253,+ "openhuman.config_update_runtime_settings",+ json!({ "reasoning_effort": "turbo" }),+ )+ .await;+ assert_jsonrpc_error(&invalid_default, "unknown default reasoning_effort");++ // A per-thread level that does not parse is rejected before any turn starts.+ let invalid_turn = post_json_rpc(+ &rpc_base,+ 41_254,+ "openhuman.channel_web_chat",+ json!({+ "client_id": "reasoning-client",+ "thread_id": "reasoning-thread",+ "message": "hello",+ "reasoning_effort": "turbo",+ }),+ )+ .await;+ let err = assert_jsonrpc_error(&invalid_turn, "unknown turn reasoning_effort");+ assert!(+ err.to_string().contains("reasoning_effort"),+ "the rejection should name the bad param: {err}"+ );++ rpc_join.abort();+ }++ #[tokio::test]+ async fn json_rpc_config_autonomy_settings_roundtrip() {+ let _env_lock = json_rpc_e2e_env_lock_async().await;+ let tmp = tempdir().expect("tempdir");+ let home = tmp.path();+ let openhuman_home = home.join(".openhuman");++ let _home_guard = EnvVarGuard::set_to_path("HOME", home);+ let _workspace_guard = EnvVarGuard::unset("OPENHUMAN_WORKSPACE");+ let _backend_url_guard = EnvVarGuard::unset("BACKEND_URL");+ let _vite_backend_guard = EnvVarGuard::unset("VITE_BACKEND_URL");++ let (mock_addr, mock_join) = serve_on_ephemeral(mock_upstream_router()).await;+ let mock_origin = format!("http://{}", mock_addr);+ write_min_config_with_local_ai_disabled(&openhuman_home, &mock_origin);++ let (rpc_addr, rpc_join) = serve_on_ephemeral(build_core_http_router(false)).await;+ let rpc_base = format!("http://{}", rpc_addr);+ tokio::time::sleep(Duration::from_millis(100)).await;++ // GET → expect the default (20).+ let initial = post_json_rpc(+ &rpc_base,+ 7001,+ "openhuman.config_get_autonomy_settings",+ json!({}),+ )+ .await;+ let initial_outer = assert_no_jsonrpc_error(&initial, "get_autonomy_settings initial");+ // assert_no_jsonrpc_error already strips the JSON-RPC envelope; one more hop+ // strips the into_cli_compatible_json wrapper to reach the payload fields.+ let initial_value = initial_outer+ .get("result")+ .and_then(|r| r.get("max_actions_per_hour"))+ .and_then(Value::as_u64);+ // Default is `u32::MAX` (functionally unlimited) — fresh installs should+ // not be rate-limited until the user opts into a ceiling. See the+ // autonomy schema for the rationale.+ assert_eq!(+ initial_value,+ Some(u32::MAX as u64),+ "expected default u32::MAX (unlimited), got envelope: {initial_outer}"+ );++ // UPDATE → 250.+ let update = post_json_rpc(+ &rpc_base,+ 7002,+ "openhuman.config_update_autonomy_settings",+ json!({ "max_actions_per_hour": 250 }),+ )+ .await;+ assert_no_jsonrpc_error(&update, "update_autonomy_settings");++ // GET again → expect 250.+ let after = post_json_rpc(+ &rpc_base,+ 7003,+ "openhuman.config_get_autonomy_settings",+ json!({}),+ )+ .await;+ let after_outer = assert_no_jsonrpc_error(&after, "get_autonomy_settings after");+ let after_value = after_outer+ .get("result")+ .and_then(|r| r.get("max_actions_per_hour"))+ .and_then(Value::as_u64);+ assert_eq!(+ after_value,+ Some(250),+ "expected 250 after update, got envelope: {after_outer}"+ );++ // Invalid value rejected — server returns JSON-RPC error envelope, not a result.+ // Upper bound was lifted to u32::MAX (the new "unlimited" sentinel that the+ // UI exposes as a preset), so the only rejected value is now zero.+ let bad = post_json_rpc(+ &rpc_base,+ 7004,+ "openhuman.config_update_autonomy_settings",+ json!({ "max_actions_per_hour": 0 }),+ )+ .await;+ let bad_err = assert_jsonrpc_error(&bad, "update_autonomy_settings bad value");+ let err_message = bad_err+ .get("message")+ .and_then(Value::as_str)+ .unwrap_or_else(|| panic!("error object missing message: {bad_err}"));+ assert!(+ err_message.contains("unsigned integer >= 1"),+ "expected validation error in: {err_message}"+ );++ // auto_approve ("Always allow" allowlist) round-trips through the same+ // update/get path the Agent Access settings panel uses.+ let update_allow = post_json_rpc(+ &rpc_base,+ 7005,+ "openhuman.config_update_autonomy_settings",+ json!({ "auto_approve": ["shell", "curl"] }),+ )+ .await;+ assert_no_jsonrpc_error(&update_allow, "update_autonomy_settings auto_approve");++ let after_allow = post_json_rpc(+ &rpc_base,+ 7006,+ "openhuman.config_get_autonomy_settings",+ json!({}),+ )+ .await;+ let after_allow_outer =+ assert_no_jsonrpc_error(&after_allow, "get_autonomy_settings auto_approve");+ let allow_list: Vec<String> = after_allow_outer+ .get("result")+ .and_then(|r| r.get("auto_approve"))+ .and_then(Value::as_array)+ .map(|arr| {+ arr.iter()+ .filter_map(|v| v.as_str().map(str::to_string))+ .collect()+ })+ .unwrap_or_default();+ assert_eq!(+ allow_list,+ vec!["shell".to_string(), "curl".to_string()],+ "auto_approve allowlist should round-trip, got envelope: {after_allow_outer}"+ );++ // `auto_approve_all` (the blanket bypass) round-trips through the same+ // update/get path, and defaults to `false`.+ let initial_auto_all = initial_outer+ .get("result")+ .and_then(|r| r.get("auto_approve_all"))+ .and_then(Value::as_bool);+ assert_eq!(+ initial_auto_all,+ Some(false),+ "auto_approve_all should default to false, got envelope: {initial_outer}"+ );++ let update_auto_all = post_json_rpc(+ &rpc_base,+ 7007,+ "openhuman.config_update_autonomy_settings",+ json!({ "auto_approve_all": true }),+ )+ .await;+ assert_no_jsonrpc_error(+ &update_auto_all,+ "update_autonomy_settings auto_approve_all",+ );++ let after_auto_all = post_json_rpc(+ &rpc_base,+ 7008,+ "openhuman.config_get_autonomy_settings",+ json!({}),+ )+ .await;+ let after_auto_all_outer =+ assert_no_jsonrpc_error(&after_auto_all, "get_autonomy_settings auto_approve_all");+ let auto_all_value = after_auto_all_outer+ .get("result")+ .and_then(|r| r.get("auto_approve_all"))+ .and_then(Value::as_bool);+ assert_eq!(+ auto_all_value,+ Some(true),+ "auto_approve_all should round-trip to true, got envelope: {after_auto_all_outer}"+ );++ mock_join.abort();+ rpc_join.abort();+ }++ /// Issue #3100 — the agent/action timeout must be readable and writable over+ /// RPC (the surface the Settings → Agent OS access "Action timeout" control+ /// uses), with the same bounds the UI shows and a validation error on garbage.++ #[tokio::test]+ async fn json_rpc_config_agent_timeout_settings_roundtrip() {+ let _env_lock = json_rpc_e2e_env_lock_async().await;+ let tmp = tempdir().expect("tempdir");+ let home = tmp.path();+ let openhuman_home = home.join(".openhuman");++ let _home_guard = EnvVarGuard::set_to_path("HOME", home);+ let _workspace_guard = EnvVarGuard::unset("OPENHUMAN_WORKSPACE");+ let _backend_url_guard = EnvVarGuard::unset("BACKEND_URL");+ let _vite_backend_guard = EnvVarGuard::unset("VITE_BACKEND_URL");+ // No operator override so the config value drives the effective timeout.+ let _timeout_env_guard = EnvVarGuard::unset("OPENHUMAN_TOOL_TIMEOUT_SECS");++ let (mock_addr, mock_join) = serve_on_ephemeral(mock_upstream_router()).await;+ let mock_origin = format!("http://{}", mock_addr);+ write_min_config_with_local_ai_disabled(&openhuman_home, &mock_origin);++ let (rpc_addr, rpc_join) = serve_on_ephemeral(build_core_http_router(false)).await;+ let rpc_base = format!("http://{}", rpc_addr);+ tokio::time::sleep(Duration::from_millis(100)).await;++ // GET → defaults: 120s, bounds 1..=3600, no env override.+ let initial = post_json_rpc(+ &rpc_base,+ 7101,+ "openhuman.config_get_agent_settings",+ json!({}),+ )+ .await;+ let initial_outer = assert_no_jsonrpc_error(&initial, "get_agent_settings initial");+ let initial_result = initial_outer+ .get("result")+ .unwrap_or_else(|| panic!("missing result: {initial_outer}"));+ assert_eq!(+ initial_result+ .get("agent_timeout_secs")+ .and_then(Value::as_u64),+ Some(120),+ "default timeout should be 120, got: {initial_outer}"+ );+ assert_eq!(+ initial_result+ .get("min_timeout_secs")+ .and_then(Value::as_u64),+ Some(1)+ );+ assert_eq!(+ initial_result+ .get("max_timeout_secs")+ .and_then(Value::as_u64),+ Some(3600)+ );+ assert_eq!(+ initial_result.get("env_override").and_then(Value::as_bool),+ Some(false)+ );++ // UPDATE → 300s.+ let update = post_json_rpc(+ &rpc_base,+ 7102,+ "openhuman.config_update_agent_settings",+ json!({ "agent_timeout_secs": 300 }),+ )+ .await;+ assert_no_jsonrpc_error(&update, "update_agent_settings");++ // GET again → 300, and the runtime-effective value tracks it.+ let after = post_json_rpc(+ &rpc_base,+ 7103,+ "openhuman.config_get_agent_settings",+ json!({}),+ )+ .await;+ let after_outer = assert_no_jsonrpc_error(&after, "get_agent_settings after");+ let after_result = after_outer+ .get("result")+ .unwrap_or_else(|| panic!("missing result: {after_outer}"));+ assert_eq!(+ after_result+ .get("agent_timeout_secs")+ .and_then(Value::as_u64),+ Some(300),+ "expected 300 after update, got: {after_outer}"+ );+ assert_eq!(+ after_result+ .get("effective_timeout_secs")+ .and_then(Value::as_u64),+ Some(300),+ "effective timeout should track the saved value, got: {after_outer}"+ );++ // Invalid value (0 disables the timeout) → JSON-RPC error envelope.+ let bad = post_json_rpc(+ &rpc_base,+ 7104,+ "openhuman.config_update_agent_settings",+ json!({ "agent_timeout_secs": 0 }),+ )+ .await;+ let bad_err = assert_jsonrpc_error(&bad, "update_agent_settings bad value");+ let err_message = bad_err+ .get("message")+ .and_then(Value::as_str)+ .unwrap_or_else(|| panic!("error object missing message: {bad_err}"));+ assert!(+ err_message.contains("between"),+ "expected range validation error in: {err_message}"+ );++ // Restore the process-global timeout so later tests in this binary don't+ // inherit the 300s value set above (the AtomicU64 is per-process, not per-test).+ openhuman_core::tools::timeout::set_tool_timeout_secs(- tinytools_std::timeout::DEFAULT_TIMEOUT_SECS,++ tinyagents_harness_tools::exec::timeout::DEFAULT_TIMEOUT_SECS,+ );++ mock_join.abort();+ rpc_join.abort();+ }++ // ---------------------------------------------------------------------------+ // Port-conflict recovery E2E+ // ---------------------------------------------------------------------------+ //+ // Verifies that when the preferred core port (7788) is already occupied, the+ // RPC stack starts successfully on a fallback port and remains fully+ // reachable. A second pass confirms that once the blocker is dropped, port+ // 7788 becomes available again — matching the "repro gone" acceptance+ // criterion from issue #2617.++ #[tokio::test]+ async fn port_conflict_recovery_core_starts_on_fallback_port_e2e() {+ let _env_lock = json_rpc_e2e_env_lock_async().await;++ // ── 1. occupy port 7788 with a dummy listener ─────────────────────────+ // Use std::net so the binding is synchronous and stable before we call+ // pick_listen_port.+ let blocker =+ std::net::TcpListener::bind("127.0.0.1:7788").expect("bind blocker on 7788 for e2e test");+ blocker+ .set_nonblocking(true)+ .expect("set blocker non-blocking");++ // ── 2. pick_listen_port should fall back to 7789–7798 ────────────────+ let pick_result = pick_listen_port(7788)+ .await+ .expect("pick_listen_port must succeed when port is occupied by non-OpenHuman process");+ assert!(+ pick_result.fallback_from.is_some(),+ "expected fallback_from to be Some(7788) when preferred port is occupied, got None"+ );+ assert_eq!(+ pick_result.fallback_from,+ Some(7788),+ "fallback_from should record the originally preferred port"+ );+ let fallback_port = pick_result.port;+ assert!(+ (7789..=7798).contains(&fallback_port),+ "fallback port {fallback_port} should be in the 7789–7798 range"+ );++ // ── 3. serve the core router on the fallback listener ────────────────+ ensure_test_rpc_auth();+ let router = build_core_http_router(false);+ let listener =+ tokio::net::TcpListener::from_std(pick_result.listener.into_std().expect("into_std"))+ .expect("from_std");+ let addr: SocketAddr = listener.local_addr().expect("local_addr");+ let rpc_join = tokio::spawn(async move { axum::serve(listener, router).await });+ let rpc_base = format!("http://{addr}");+ assert_eq!(+ addr.port(),+ fallback_port,+ "server should be on the fallback port"+ );++ // ── 4. RPC health-check on the fallback port ─────────────────────────+ let diag = post_json_rpc(&rpc_base, 26170, "openhuman.connectivity_diag", json!({})).await;+ // JSON-RPC result envelope → inner cli-compatible wrapper → diag payload.+ // post_json_rpc returns the raw JSON-RPC response; assert_no_jsonrpc_error+ // unwraps the outer "result". The inner value is {"logs":[...],"result":{"diag":{...}}},+ // so we need one more "result" hop before accessing "diag".+ let outer = assert_no_jsonrpc_error(&diag, "connectivity_diag on fallback port");+ let inner = outer.get("result").unwrap_or_else(|| {+ panic!("connectivity_diag outer result missing 'result' key; got: {outer}")+ });+ let diag_payload = inner.get("diag").unwrap_or_else(|| {+ panic!("connectivity_diag inner result missing 'diag' key; got: {inner}")+ });+ assert!(+ diag_payload.get("sidecar_pid").is_some(),+ "connectivity_diag should return sidecar_pid field; got: {diag_payload}"+ );+ assert!(+ diag_payload.get("listen_port").is_some(),+ "connectivity_diag should return listen_port field; got: {diag_payload}"+ );++ rpc_join.abort();++ // ── 5. drop blocker — verify 7788 is now free ────────────────────────+ drop(blocker);++ let after_drop = pick_listen_port(7788)+ .await+ .expect("pick_listen_port should succeed with 7788 free");+ assert_eq!(+ after_drop.port, 7788,+ "after releasing the blocker, pick_listen_port should bind directly on 7788"+ );+ assert!(+ after_drop.fallback_from.is_none(),+ "fallback_from should be None when 7788 is free"+ );+ // Release the listener so the port is not held across tests.+ drop(after_drop.listener);+ }diff --cc vendor/tinyagentsindex 9d9cf25d5a,e193117584..66698ac91f--- a/vendor/tinyagents+++ b/vendor/tinyagents@@@ -1,1 -1,1 +1,1 @@@- Subproject commit 9d9cf25d5af5c81fd991173494f9866077d806a9-Subproject commit e193117584811063bbd29442e3edf5aba3506010++Subproject commit 66698ac91fb67a03b1d2254306f9547c9e663243