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
refactor(tokenjuice): execute queries and HTML extraction through released bus module
Steven Enamakel5d1e08b479e9
diff --git a/Cargo.lock b/Cargo.lockindex 10ccd480e1..f377ca7f78 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -3235,15 +3235,8 @@ version = "3.0.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "9f90e485abfd3189510c996e77be55056a51038b0fa5805e6c97b5dcf0d9ab55"dependencies = [- "aho-corasick",- "base64 0.22.1","bstr","jaq-core",- "jiff",- "libm",- "log",- "regex-bites",- "urlencoding",][[package]]@@ -3255,12 +3248,10 @@ dependencies = ["defmt","jiff-core","jiff-static",- "jiff-tzdb-platform","log","portable-atomic","portable-atomic-util","serde_core",- "windows-link",][[package]]@@ -3285,21 +3276,6 @@ dependencies = ["syn 2.0.119",]-[[package]]-name = "jiff-tzdb"-version = "0.1.8"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "142bd39932ad231f10513df9ab62661fead8719872150b7ad02a2df79f4e141e"--[[package]]-name = "jiff-tzdb-platform"-version = "0.1.3"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "875a5a69ac2bab1a891711cf5eccbec1ce0341ea805560dcd90b7a2e925132e8"-dependencies = [- "jiff-tzdb",-]-[[package]]name = "jni"version = "0.22.4"@@ -4686,7 +4662,6 @@ dependencies = ["tinyinference-local","tinyinference-providers","tinyinference-voice",- "tinyjuice","tinyjuice-bus","tinymcp","tinymcp-bus",@@ -5862,12 +5837,6 @@ dependencies = ["regex-syntax",]-[[package]]-name = "regex-bites"-version = "0.1.6"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "b6a15a2fa0bfda9361941c45550896ae87b15cc6c8c939ea350079670332e211"-[[package]]name = "regex-syntax"version = "0.8.11"@@ -7818,38 +7787,13 @@ dependencies = ["tokio",]-[[package]]-name = "tinyjuice"-version = "0.6.1"-dependencies = [- "anyhow",- "async-trait",- "dirs 7.0.0",- "hex",- "jaq-core",- "jaq-json",- "jaq-std",- "log",- "once_cell",- "regex",- "serde",- "serde_json",- "sha2 0.11.0",- "thiserror 2.0.20",- "tinyjuice-bus",- "tinytools",- "tokio",- "unicode-segmentation",- "unicode-width",- "uuid",-]-[[package]]name = "tinyjuice-bus"-version = "0.6.1"+version = "0.7.0"dependencies = ["serde","serde_json",+ "thiserror 2.0.20",][[package]]diff --git a/crates/openhuman-app/Cargo.lock b/crates/openhuman-app/Cargo.lockindex b8fc81cf18..2a038cbed1 100644--- a/crates/openhuman-app/Cargo.lock+++ b/crates/openhuman-app/Cargo.lock@@ -3188,15 +3188,8 @@ version = "3.0.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "9f90e485abfd3189510c996e77be55056a51038b0fa5805e6c97b5dcf0d9ab55"dependencies = [- "aho-corasick",- "base64 0.22.1","bstr","jaq-core",- "jiff",- "libm",- "log",- "regex-bites",- "urlencoding",][[package]]@@ -3572,12 +3565,6 @@ dependencies = ["windows-link 0.2.1",]-[[package]]-name = "libm"-version = "0.2.16"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981"-[[package]]name = "libredox"version = "0.1.24"@@ -4639,7 +4626,6 @@ dependencies = ["tinyinference-local","tinyinference-providers","tinyinference-voice",- "tinyjuice","tinyjuice-bus","tinymcp","tinymcp-bus",@@ -5687,12 +5673,6 @@ dependencies = ["regex-syntax",]-[[package]]-name = "regex-bites"-version = "0.1.6"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "b6a15a2fa0bfda9361941c45550896ae87b15cc6c8c939ea350079670332e211"-[[package]]name = "regex-syntax"version = "0.8.11"@@ -8119,38 +8099,13 @@ dependencies = ["tokio",]-[[package]]-name = "tinyjuice"-version = "0.6.1"-dependencies = [- "anyhow",- "async-trait",- "dirs 7.0.0",- "hex",- "jaq-core",- "jaq-json",- "jaq-std",- "log",- "once_cell",- "regex",- "serde",- "serde_json",- "sha2 0.11.0",- "thiserror 2.0.20",- "tinyjuice-bus",- "tinytools",- "tokio",- "unicode-segmentation",- "unicode-width",- "uuid",-]-[[package]]name = "tinyjuice-bus"-version = "0.6.1"+version = "0.7.0"dependencies = ["serde","serde_json",+ "thiserror 2.0.20",][[package]]@@ -9121,12 +9076,6 @@ version = "1.13.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8"-[[package]]-name = "unicode-width"-version = "0.2.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254"-[[package]]name = "universal-hash"version = "0.5.1"diff --git a/crates/openhuman-core/Cargo.toml b/crates/openhuman-core/Cargo.tomlindex dc6b4bedc4..5a3364b60d 100644--- a/crates/openhuman-core/Cargo.toml+++ b/crates/openhuman-core/Cargo.toml@@ -517,34 +517,6 @@ tinyvoice = { path = "../../vendor/tinyvoice/crates/tinyvoice", default-features# After cloning: `git submodule update --init vendor/tinyjuice`.tinyjuice-bus = { path = "../../vendor/tinyjuice/crates/tinyjuice-bus" }-# TinyJuice — the engine crate, for its pure content transforms only.-#-# The router, the CCR cache, the rule engine and ranged retrieval stay behind-# the loadable-module boundary: those need the module's state, its disk tier and-# its retrieval markers, and nothing here calls them. What this dependency buys-# is the stateless half — `compressors::html::html_to_markdown`, which `web_fetch`-# runs on every HTML response so the model reads a page's prose, headings and-# links instead of its minified JS.-#-# That transform has no business being reimplemented here: it is content-# handling, TinyJuice owns content handling, and a second copy would drift.-# Reaching it through TinyBus instead would make a core tool's default output-# depend on whether an optional cdylib loaded and on `compaction_enabled`-# (default `false`), which is not a defensible way to decide what a fetched page-# looks like. See `src/inference/tokenjuice/README.md`.-#-# `default-features = false` drops `tinyjuice-treesitter` and with it the three-# tree-sitter grammars — those serve the code compressor, which lives behind the-# module boundary and is not called from here.-#-# The `tinytools` feature adds `tinyjuice::repl::tools`, the `juice_find`,-# `juice_extract` and `juice_summarize` tool declarations. It names tinytools by-# URL; the root `[patch]` redirects that to the copy tinyagents vendors, so-# there is still exactly one `tinytools` package and one `Tool` trait. The CCR-# store those ops read lives in the module, so the host wraps the tools and-# feeds them each original over the bus: see `inference/tokenjuice/repl_tools.rs`.-tinyjuice = { path = "../../vendor/tinyjuice", default-features = false, features = ["tinytools", "host"] }-# TinyHosts — the unified hosting API: one `Host` trait over a hosting provider,# and the `launch` flow that puts a Next.js application, its database, its# environment and its domains on it in the one order that works.diff --git a/crates/openhuman-core/src/agent/registry/agents/summarizer/prompt.rs b/crates/openhuman-core/src/agent/registry/agents/summarizer/prompt.rsindex 3ee4484f3e..8ec36ede9f 100644--- a/crates/openhuman-core/src/agent/registry/agents/summarizer/prompt.rs+++ b/crates/openhuman-core/src/agent/registry/agents/summarizer/prompt.rs@@ -15,7 +15,7 @@ use anyhow::Result;/// second copy that could drift. It stays `pub` (issue #6014) so an embedder/// supplying its own [`PayloadSummarizer`](crate::agent::tinyagents::payload_summarizer::PayloadSummarizer)/// can read the contract its model is asked to follow.-pub const ARCHETYPE: &str = tinyjuice::summarize::SYSTEM_PROMPT;+pub const ARCHETYPE: &str = tinyjuice_bus::summary::SYSTEM_PROMPT;pub fn build(ctx: &PromptContext<'_>) -> Result<String> {let mut out = String::with_capacity(4096);diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware/tool_output.rs b/crates/openhuman-core/src/agent/tinyagents/middleware/tool_output.rsindex d8fe774e22..e1a0518ab7 100644--- a/crates/openhuman-core/src/agent/tinyagents/middleware/tool_output.rs+++ b/crates/openhuman-core/src/agent/tinyagents/middleware/tool_output.rs@@ -144,8 +144,7 @@ pub(crate) fn is_truncation_exempt(name: &str) -> bool {/// [`artifact_read_target`] does.////// Such a result is exempt from the payload summarizer (step 2). `web_fetch`-/// normally returns HTML as Markdown — `tinyjuice::compressors::html::-/// html_to_markdown`, which drops scripts and styling — and `raw: true` turns+/// normally returns HTML as Markdown — TinyJuice’s `ExtractHtml` bus operation, which drops scripts and styling — and `raw: true` turns/// that off, so the payload is unconverted markup. Paying a full-price,/// *uncached* model call to have an LLM paraphrase minified JS and CSS is the/// worst trade in the ladder: one observed `raw: true` fetch of a 183 KB pagediff --git a/crates/openhuman-core/src/inference/tokenjuice/focus.rs b/crates/openhuman-core/src/inference/tokenjuice/focus.rsnew file mode 100644index 0000000000..6517916d16--- /dev/null+++ b/crates/openhuman-core/src/inference/tokenjuice/focus.rs@@ -0,0 +1,35 @@+//! `summary_focus`: the argument a tool opts into so its caller can steer the+//! summary of a large result.+//!+//! A tool opts in by adding [`summary_focus_property`] to its schema's+//! `properties`. `ToolOutputMiddleware` takes the value out of the call in+//! `before_tool` — before schema validation and before the tool runs, so the+//! tool body never sees it — and hands it to TinyJuice with the result.++use serde_json::Value;++pub use tinyjuice_bus::tools::{summary_focus_property, SUMMARY_FOCUS_ARG};++/// Whether a tool's parameter schema declares TinyJuice's `summary_focus`,+/// as opposed to a parameter of its own that happens to share the name.+pub fn declares_summary_focus(parameters: &Value) -> bool {+ parameters+ .get("properties")+ .and_then(|properties| properties.get(SUMMARY_FOCUS_ARG))+ == Some(&summary_focus_property())+}++/// Remove `summary_focus` from a call's arguments, returning it when it holds+/// non-blank text.+pub fn take_summary_focus(arguments: &mut Value) -> Option<String> {+ let removed = arguments.as_object_mut()?.remove(SUMMARY_FOCUS_ARG)?;+ removed+ .as_str()+ .map(str::trim)+ .filter(|focus| !focus.is_empty())+ .map(str::to_string)+}++#[cfg(test)]+#[path = "focus_tests.rs"]+mod tests;diff --git a/crates/openhuman-core/src/inference/tokenjuice/focus_tests.rs b/crates/openhuman-core/src/inference/tokenjuice/focus_tests.rsnew file mode 100644index 0000000000..33180e7a1c--- /dev/null+++ b/crates/openhuman-core/src/inference/tokenjuice/focus_tests.rs@@ -0,0 +1,66 @@+use super::*;+use serde_json::json;++#[test]+fn the_focus_is_taken_out_of_the_arguments() {+ let mut args = json!({ "url": "https://example.com", "summary_focus": " the pricing " });+ assert_eq!(+ take_summary_focus(&mut args).as_deref(),+ Some("the pricing")+ );+ assert_eq!(args, json!({ "url": "https://example.com" }));+}++#[test]+fn a_blank_or_non_string_focus_is_dropped_and_still_removed() {+ for value in [json!(" "), json!(42), json!(null)] {+ let mut args = json!({ "url": "u", "summary_focus": value });+ assert_eq!(take_summary_focus(&mut args), None);+ assert_eq!(args, json!({ "url": "u" }));+ }+}++#[test]+fn arguments_without_a_focus_are_untouched() {+ let mut args = json!({ "url": "u" });+ assert_eq!(take_summary_focus(&mut args), None);+ assert_eq!(args, json!({ "url": "u" }));+ let mut not_an_object = json!("raw");+ assert_eq!(take_summary_focus(&mut not_an_object), None);+}++#[test]+fn the_property_is_an_optional_string() {+ let property = summary_focus_property();+ assert_eq!(property["type"], "string");+ assert!(property["description"]+ .as_str()+ .unwrap()+ .contains("summarized"));+}++#[test]+fn only_the_shared_property_counts_as_declaring_the_focus() {+ let declared =+ json!({ "properties": { "url": {}, "summary_focus": summary_focus_property() } });+ assert!(declares_summary_focus(&declared));++ let own_parameter = json!({ "properties": { "summary_focus": { "type": "integer" } } });+ assert!(!declares_summary_focus(&own_parameter));+ assert!(!declares_summary_focus(+ &json!({ "properties": { "url": {} } })+ ));+ assert!(!declares_summary_focus(&json!({})));+}++#[test]+fn the_property_schema_is_pinned_literally() {+ assert_eq!(+ summary_focus_property(),+ json!({+ "type": "string",+ "description": "What you need from this result. A large result is summarized around this; the full output stays retrievable."+ })+ );+ assert_eq!(SUMMARY_FOCUS_ARG, "summary_focus");+}diff --git a/crates/openhuman-core/src/inference/tokenjuice/mod.rs b/crates/openhuman-core/src/inference/tokenjuice/mod.rsindex 710d777a96..a9aa0404d8 100644--- a/crates/openhuman-core/src/inference/tokenjuice/mod.rs+++ b/crates/openhuman-core/src/inference/tokenjuice/mod.rs@@ -1,7 +1,7 @@//! OpenHuman host adapter for the separately released TinyJuice module.pub mod config_patch;-pub use tinyjuice::host::focus;+pub mod focus;pub mod generate;pub mod ml;pub mod repl_tools;@@ -142,48 +142,30 @@ pub async fn install_from_config(config: &crate::config::Config) -> Result<(), Sif installed.as_ref() == Some(&fingerprint) {return Ok(());}- proxy(config)- .await?- .call::<()>(methods::INSTALL, (request,))+ client(config)+ .call::<()>("tinyjuice", methods::INSTALL, (request,)).await.map_err(|e| e.to_string())?;*installed = Some(fingerprint);Ok(())}-#[cfg(feature = "modules")]-pub(super) async fn proxy(config: &crate::config::Config) -> Result<tinybus::Proxy, String> {- let config = {- let mut test_config = config.clone();- if let Some(path) = std::env::var_os("TINYJUICE_TEST_MODULE") {- // An explicit fixture is an opt-in to module execution even when- // the ambient test workspace has persisted modules = disabled.- test_config.modules.enabled = true;- test_config- .modules- .overrides- .push(crate::config::schema::ModuleOverride {- id: "tinyjuice".to_string(),- path: path.to_string_lossy().into_owned(),- });- }- test_config- };- let config = &config;-- crate::modules::ensure_loaded(config, "tinyjuice").await?;- let record = crate::modules::registry::find("tinyjuice")- .ok_or_else(|| "unknown module 'tinyjuice'".to_string())?;- crate::modules::host::runtime()- .await- .map_err(|e| e.to_string())?- .proxy(record.bus_name, record.object_path)- .map_err(|e| e.to_string())-}--#[cfg(not(feature = "modules"))]-pub(super) async fn proxy(_config: &crate::config::Config) -> Result<tinybus::Proxy, String> {- Err("native modules are not compiled into this build".to_string())+/// Construct explicit access over the shared process-wide loader.+fn client(config: &crate::config::Config) -> crate::modules::client::ModuleClient {+ #[allow(unused_mut)] // Fixture overrides are compiled only into tests.+ let mut config = config.clone();+ #[cfg(test)]+ if let Some(path) = std::env::var_os("TINYJUICE_TEST_MODULE") {+ config.modules.enabled = true;+ config+ .modules+ .overrides+ .push(crate::config::schema::ModuleOverride {+ id: "tinyjuice".into(),+ path: path.to_string_lossy().into_owned(),+ });+ }+ crate::modules::client::ModuleClient::new(config)}/// Everything the module considers about one tool result.@@ -236,7 +218,7 @@ impl CompactedToolOutput {/// TinyJuice's own notice for a summary that was attempted and not produced,/// so a host-side failure reads the same as a module-side one.pub fn summary_failed_notice() -> String {- tinyjuice::summarize::UnavailableReason::Failed+ tinyjuice_bus::summary::UnavailableReason::Failed.notice().to_string()}@@ -313,13 +295,6 @@ pub async fn compact_tool_output(call: ToolOutputCompaction<'_>) -> CompactedToolog::debug!("[tokenjuice] module configuration failed, passing through: {error}");return CompactedToolOutput::passthrough(content, wants_summary);}- let proxy = match proxy(&config).await {- Ok(proxy) => proxy.with_timeout(COMPACT_WITH_TIMEOUT),- Err(error) => {- log::debug!("[tokenjuice] module unavailable, passing through: {error}");- return CompactedToolOutput::passthrough(content, wants_summary);- }- };let request = types::CompactRequest {content: content.clone(),tool_name: tool_name.to_string(),@@ -330,22 +305,14 @@ pub async fn compact_tool_output(call: ToolOutputCompaction<'_>) -> CompactedToocontext_token,scope,};- let compact_with_result = proxy.call(methods::COMPACT_WITH, (request,)).await;- let response = match classify_compact_with_reply(compact_with_result, tool_name) {- CompactWithOutcome::Response(response) => response,- CompactWithOutcome::RetryAsCompact => {- let legacy_result = proxy- .call::<types::CompactResponse>(- methods::COMPACT,- (content.clone(), tool_name.to_string(), enabled, profile),- )- .await;- match finish_legacy_compact_reply(legacy_result, wants_summary) {- Some(response) => response,- None => return CompactedToolOutput::passthrough(content, wants_summary),- }- }- CompactWithOutcome::GiveUp => {+ let response = match client(&config)+ .with_timeout(COMPACT_WITH_TIMEOUT)+ .call::<types::CompactResponse>("tinyjuice", methods::COMPACT_WITH, (request,))+ .await+ {+ Ok(response) => response,+ Err(error) => {+ log::debug!("[tokenjuice] module compaction unavailable: {error}");return CompactedToolOutput::passthrough(content, wants_summary);}};@@ -353,63 +320,6 @@ pub async fn compact_tool_output(call: ToolOutputCompaction<'_>) -> CompactedToocompacted_from(response)}-/// What the module said about a `CompactWith` call, decided without touching-/// the network again — kept separate from `compact_tool_output` so the retry-/// decision is testable against synthetic wire errors.-enum CompactWithOutcome {- /// Use this response as the final result.- Response(types::CompactResponse),- /// A module released before contract 1.1 has no `CompactWith`. Retry over- /// the pre-1.1 `Compact` member.- RetryAsCompact,- /// Any other failure, a timeout above all, is not retried: the module- /// already had its chance, and a second call could double the wait on a- /// turn that is already stalled.- GiveUp,-}--fn classify_compact_with_reply(- result: Result<types::CompactResponse, tinybus::Error>,- tool_name: &str,-) -> CompactWithOutcome {- match result {- Ok(response) => CompactWithOutcome::Response(response),- Err(error) if error.wire_name() == tinybus::Error::UNKNOWN_METHOD => {- log::debug!(- "[tokenjuice] CompactWith unknown to the loaded module, retrying as Compact tool={tool_name}"- );- CompactWithOutcome::RetryAsCompact- }- Err(error) => {- log::debug!(- "[tokenjuice] CompactWith failed, passing through tool={tool_name} wire_error={}: {error}",- error.wire_name()- );- CompactWithOutcome::GiveUp- }- }-}--/// The fallback `Compact` reply, without the focus or a summary. `None` means-/// the caller should pass the original content through unchanged.-fn finish_legacy_compact_reply(- result: Result<types::CompactResponse, tinybus::Error>,- wants_summary: bool,-) -> Option<types::CompactResponse> {- match result {- Ok(mut response) => {- if wants_summary && response.notice.is_none() {- response.notice = Some(summary_failed_notice());- }- Some(response)- }- Err(error) => {- log::debug!("[tokenjuice] module compaction failed, passing through: {error}");- None- }- }-}-fn compacted_from(response: types::CompactResponse) -> CompactedToolOutput {let summarized_from_bytes = (response.compressor == CompressorKind::LlmSummary.as_str()).then_some(response.original_bytes);@@ -436,9 +346,8 @@ pub async fn detect(content: String, hint: types::ContentHint) -> Result<String,let config = crate::config::Config::load_or_init().await.map_err(|error| error.to_string())?;- proxy(&config)- .await?- .call(methods::DETECT, (content, hint))+ client(&config)+ .call("tinyjuice", methods::DETECT, (content, hint)).await.map_err(|error| error.to_string())}@@ -451,9 +360,8 @@ pub async fn compress(.await.map_err(|error| error.to_string())?;install_from_config(&config).await?;- let response: types::CompressedOutput = proxy(&config)- .await?- .call(methods::COMPRESS, (content, hint))+ let response: types::CompressedOutput = client(&config)+ .call("tinyjuice", methods::COMPRESS, (content, hint)).await.map_err(|error| error.to_string())?;savings::record(@@ -473,9 +381,8 @@ pub async fn retrieve(.await.map_err(|error| error.to_string())?;install_from_config(&config).await?;- proxy(&config)- .await?- .call(methods::RETRIEVE, (token, range))+ client(&config)+ .call("tinyjuice", methods::RETRIEVE, (token, range)).await.map_err(|error| error.to_string())}@@ -485,9 +392,8 @@ pub async fn cache_stats() -> Result<types::CacheStats, String> {.await.map_err(|error| error.to_string())?;install_from_config(&config).await?;- proxy(&config)- .await?- .call(methods::CACHE_STATS, ())+ client(&config)+ .call("tinyjuice", methods::CACHE_STATS, ()).await.map_err(|error| error.to_string())}@@ -507,3 +413,29 @@ pub(crate) mod module_stub;#[cfg(test)]#[path = "mod_repl_module_tests.rs"]mod repl_module_tests;++/// Run a typed query inside TinyJuice; cached originals stay inside the module.+pub async fn query(+ request: tinyjuice_bus::wire::QueryRequest,+) -> Result<tinyjuice_bus::wire::QueryResponse, String> {+ let config = crate::config::Config::load_or_init()+ .await+ .map_err(|e| e.to_string())?;+ install_from_config(&config).await?;+ client(&config)+ .call("tinyjuice", methods::QUERY, (request,))+ .await+ .map_err(|e| e.to_string())+}++/// Extract HTML through the compiled module independently of compression settings.+pub async fn extract_html(html: String) -> Result<String, String> {+ let config = crate::config::Config::load_or_init()+ .await+ .map_err(|e| e.to_string())?;+ let response: tinyjuice_bus::wire::HtmlResponse = client(&config)+ .call("tinyjuice", methods::EXTRACT_HTML, (html,))+ .await+ .map_err(|e| e.to_string())?;+ response.map_err(|_| "juice: HTML input exceeds module limit".into())+}diff --git a/crates/openhuman-core/src/inference/tokenjuice/mod_tests.rs b/crates/openhuman-core/src/inference/tokenjuice/mod_tests.rsindex 17009f7530..8d5abff808 100644--- a/crates/openhuman-core/src/inference/tokenjuice/mod_tests.rs+++ b/crates/openhuman-core/src/inference/tokenjuice/mod_tests.rs@@ -189,90 +189,6 @@ fn passthrough_discloses_a_notice_only_when_a_summary_was_wanted() {assert_eq!(disclosed.summarized_from_bytes, None);}-fn synthetic_compact_response(text: &str) -> types::CompactResponse {- types::CompactResponse {- text: text.to_string(),- original_bytes: text.len(),- compacted_bytes: text.len(),- rule_id: "none/plain_text".into(),- applied: false,- content_kind: "plain_text".into(),- compressor: "none".into(),- original_tokens: text.len().div_ceil(4) as u64,- compacted_tokens: text.len().div_ceil(4) as u64,- notice: None,- }-}--fn unknown_method_error() -> tinybus::Error {- tinybus::Error::UnknownMethod {- interface: tinybus::InterfaceName::new("ai.tinyhumans.tinyjuice.Compaction").unwrap(),- member: tinybus::MemberName::new("CompactWith").unwrap(),- }-}--fn method_failed_error() -> tinybus::Error {- tinybus::Error::MethodFailed {- name: "ai.tinyhumans.tinyjuice.Error.Internal".into(),- message: "boom".into(),- }-}--#[test]-fn a_successful_compact_with_reply_is_used_as_is() {- let response = synthetic_compact_response("compacted");- match classify_compact_with_reply(Ok(response.clone()), "shell") {- CompactWithOutcome::Response(got) => assert_eq!(got.text, response.text),- _ => panic!("expected Response"),- }-}--#[test]-fn an_unknown_method_error_asks_to_retry_as_compact() {- assert!(matches!(- classify_compact_with_reply(Err(unknown_method_error()), "shell"),- CompactWithOutcome::RetryAsCompact- ));-}--#[test]-fn any_other_compact_with_error_gives_up() {- assert!(matches!(- classify_compact_with_reply(Err(method_failed_error()), "shell"),- CompactWithOutcome::GiveUp- ));-}--#[test]-fn a_legacy_compact_reply_gains_the_summary_notice_when_one_was_wanted_and_missing() {- let response = synthetic_compact_response("legacy");- let finished = finish_legacy_compact_reply(Ok(response), true)- .expect("a successful reply is never dropped");- assert_eq!(finished.notice, Some(summary_failed_notice()));-}--#[test]-fn a_legacy_compact_reply_keeps_its_own_notice_when_it_already_has_one() {- let mut response = synthetic_compact_response("legacy");- response.notice = Some("module notice".to_string());- let finished =- finish_legacy_compact_reply(Ok(response), true).expect("a successful reply is kept");- assert_eq!(finished.notice, Some("module notice".to_string()));-}--#[test]-fn a_legacy_compact_reply_is_silent_when_no_summary_was_wanted() {- let response = synthetic_compact_response("legacy");- let finished = finish_legacy_compact_reply(Ok(response), false)- .expect("a successful reply is never dropped");- assert_eq!(finished.notice, None);-}--#[test]-fn a_failed_legacy_compact_reply_gives_up() {- assert!(finish_legacy_compact_reply(Err(method_failed_error()), true).is_none());-}-#[test]fn install_request_turns_on_the_handle_preview_by_default() {let config = crate::config::Config::default();@@ -330,3 +246,76 @@ fn install_request_summarizes_only_on_request_under_a_64k_cap() {);assert_eq!(request.options.llm_summary_max_input_tokens, 64_000);}++/// Run against the verified release with the host's pinned TinyBus loader.+#[tokio::test]+async fn released_queries_keep_cached_originals_in_the_module_and_accept_artifact_content() {+ if std::env::var_os("TINYJUICE_TEST_MODULE").is_none() {+ eprintln!("SKIPPED: released TinyJuice artifact not configured");+ return;+ }+ use tinyjuice_bus::{+ repl::{FindMode, ReplLimits, ReplOp, ReplOutput, ScopeUnit},+ wire::{QueryError, QueryRequest, QueryResponse, QueryTarget},+ };+ let workspace = tempfile::tempdir().unwrap();+ let config = crate::config::Config {+ workspace_dir: workspace.path().into(),+ ..Default::default()+ };+ install_from_config(&config).await.unwrap();+ let content = format!("{}\nmodule-owned-needle\n", "boring row\n".repeat(2000));+ let compressed: types::CompressedOutput = client(&config)+ .call(+ "tinyjuice",+ methods::COMPRESS,+ (content.clone(), types::ContentHint::default()),+ )+ .await+ .unwrap();+ let handle = compressed+ .ccr_token+ .expect("released module retains original");+ let make_request = |target| QueryRequest {+ target,+ op: ReplOp::Find {+ query: "module-owned-needle".into(),+ mode: FindMode::Text,+ ignore_case: false,+ context: 0,+ top_k: None,+ scope: None,+ unit: ScopeUnit::Lines,+ },+ limits: ReplLimits::default(),+ context_token: None,+ scope: None,+ };+ for target in [+ QueryTarget::Handle { token: handle },+ QueryTarget::Content { content },+ ] {+ let reply: QueryResponse = client(&config)+ .call("tinyjuice", methods::QUERY, (make_request(target),))+ .await+ .unwrap();+ assert!(+ matches!(reply, Ok(ReplOutput::Lines {hits, ..}) if hits.iter().any(|hit| hit.text.contains("module-owned-needle")))+ );+ }+ let missing: QueryResponse = client(&config)+ .call(+ "tinyjuice",+ methods::QUERY,+ (make_request(QueryTarget::Handle {+ token: "neverstored123".into(),+ }),),+ )+ .await+ .unwrap();+ assert_eq!(missing, Err(QueryError::HandleNotFound));+ let reply: tinyjuice_bus::wire::HtmlResponse = client(&config).call("tinyjuice", methods::EXTRACT_HTML, ("<html><body><h1>Fixture</h1><script>secret_script</script><p>hello</p></body></html>",)).await.unwrap();+ let markdown = reply.unwrap();+ assert!(markdown.contains("hello"));+ assert!(!markdown.contains("secret_script"));+}diff --git a/crates/openhuman-core/src/inference/tokenjuice/repl_tools.rs b/crates/openhuman-core/src/inference/tokenjuice/repl_tools.rsindex 9e54c9302e..2c77bb207f 100644--- a/crates/openhuman-core/src/inference/tokenjuice/repl_tools.rs+++ b/crates/openhuman-core/src/inference/tokenjuice/repl_tools.rs@@ -1,38 +1,13 @@-//! Agent tools `juice_find`, `juice_extract` and `juice_summarize`: inspect a-//! tool result the TinyJuice module stored behind a handle.-//!-//! With `[tokenjuice] repl_handle_enabled` on, the module replaces a large-//! result with a stats line, a short head and a handle instead of a summary-//! (see `docs/repl-tools.md` in the TinyJuice repository). These tools are how-//! the model queries what is behind that handle without reading it whole.-//!-//! TinyJuice owns the ops and the tool declarations-//! (`tinyjuice::repl::tools::repl_tools`, the `tinytools` feature). Its CCR-//! store, though, lives inside the module behind the bus, so a store handed to-//! `repl_tools` in this process would be empty. Each wrapper here therefore-//! fetches the original through the same `Retrieve` call `juice_retrieve`-//! makes, gives the stock tool a one-entry store holding it, and returns what-//! the stock tool answers. The ops, argument parsing, size caps and-//! read-only/concurrency flags are TinyJuice's, unchanged.-//!-//! Models also pass the `artifact_path` from a `[tool_result_preview]`-//! envelope (an oversized output persisted under-//! `<workspace>/artifacts/tool-results/`) where the handle goes. Such a path is-//! read from that one directory — nowhere else, no traversal, no symlink out,-//! and no larger than `file_read` would open — and queried the same way.-//! Anything else that is not a handle (a tool call id such as `call_…`) gets a-//! message saying what a handle looks like.-//!-//! Read-only, no side effects, no network access. Nothing here logs the-//! handle's content or the query.+//! Thin query adapters for the module-owned CCR store and REPL algorithms.+//! OpenHuman authorizes tool-result artifacts; only their content crosses the bus.use std::path::{Component, Path, PathBuf};use std::sync::Arc;use async_trait::async_trait;use serde_json::Value;-use tinyjuice::cache::store::{CcrPutResult, CcrStore};-use tinyjuice::repl::ReplLimits;+use tinyjuice_bus::repl::{ReplLimits, ReplOp};+use tinyjuice_bus::wire::{QueryError, QueryRequest, QueryResponse, QueryTarget};use tinytools::{PermissionLevel, Tool, ToolResult};/// The query tools TinyJuice declares. The footer suggests a subset of these.@@ -53,49 +28,28 @@ const MAX_ARTIFACT_BYTES: u64 = tinytools_std::filesystem::FileReadTool::MAX_FIL/// The relative pointer form older stores handed out (`artifacts/tool-results/…`).const RELATIVE_ARTIFACT_PREFIX: &str = "artifacts/tool-results/";-/// Token the one-entry store files an artifact's content under.-const ARTIFACT_TOKEN: &str = "artifact";--/// Where the original behind a handle comes from.+/// Contract requests are executed inside the compiled module.#[async_trait]-pub(crate) trait OriginalSource: Send + Sync {- /// `Ok(None)` is an unknown or evicted handle.- async fn original(&self, handle: &str) -> Result<Option<String>, String>;+pub(crate) trait QuerySource: Send + Sync {+ async fn query(&self, request: QueryRequest) -> Result<QueryResponse, String>;}-/// The TinyJuice module's CCR store, over the bus.struct ModuleSource;#[async_trait]-impl OriginalSource for ModuleSource {- async fn original(&self, handle: &str) -> Result<Option<String>, String> {- super::retrieve(handle.to_string(), None).await- }-}--/// A [`CcrStore`] holding the one original a call is about.-struct OneEntryStore {- token: String,- content: String,-}--impl CcrStore for OneEntryStore {- fn put(&self, _content: &str) -> CcrPutResult {- // Read-only ops never store; report "not retained" rather than lie.- CcrPutResult::new(String::new(), false)- }-- fn get(&self, token: &str) -> Option<String> {- (token == self.token).then(|| self.content.clone())+impl QuerySource for ModuleSource {+ async fn query(&self, request: QueryRequest) -> Result<QueryResponse, String> {+ super::query(request).await}}struct ModuleReplTool {name: String,+ op: String,description: String,schema: Value,cap: Option<usize>,- source: Arc<dyn OriginalSource>,+ source: Arc<dyn QuerySource>,limits: ReplLimits,/// `<workspace>/artifacts/tool-results`, when known: the one directory an/// `artifact_path` passed as the handle may be read from.@@ -130,30 +84,26 @@ pub fn repl_tools_for(config: &crate::config::Config) -> Vec<Box<dyn Tool>> {}pub(crate) fn repl_tools_with(- source: Arc<dyn OriginalSource>,+ source: Arc<dyn QuerySource>,limits: ReplLimits,) -> Vec<Box<dyn Tool>> {repl_tools_with_artifacts(source, limits, None)}pub(crate) fn repl_tools_with_artifacts(- source: Arc<dyn OriginalSource>,+ source: Arc<dyn QuerySource>,limits: ReplLimits,artifacts_dir: Option<PathBuf>,) -> Vec<Box<dyn Tool>> {- // The declarations come from TinyJuice; the probe store is never read.- let probe: Arc<dyn CcrStore> = Arc::new(OneEntryStore {- token: String::new(),- content: String::new(),- });- tinyjuice::repl::tools::repl_tools(probe, limits)+ tinyjuice_bus::tools::repl_tool_declarations().into_iter()- .map(|inner| {+ .map(|declaration| {Box::new(ModuleReplTool {- name: inner.name().to_string(),- description: inner.description().to_string(),- schema: inner.parameters_schema(),- cap: inner.max_result_size_chars(),+ name: declaration.name,+ op: declaration.op,+ description: declaration.description,+ schema: declaration.parameters,+ cap: Some(limits.max_output_chars.saturating_mul(2)),source: Arc::clone(&source),limits,artifacts_dir: artifacts_dir.clone(),@@ -283,24 +233,43 @@ fn miss_message() -> &'static str {}impl ModuleReplTool {- /// Run TinyJuice's own tool over `content`, filed under `token`.- async fn run_stock(- &self,- token: String,- content: String,- mut args: Value,- ) -> anyhow::Result<ToolResult> {+ async fn run_query(&self, target: QueryTarget, mut args: Value) -> anyhow::Result<ToolResult> {if let Some(object) = args.as_object_mut() {- object.insert("handle".into(), Value::String(token.clone()));+ object.insert("op".into(), Value::String(self.op.clone()));}- let store: Arc<dyn CcrStore> = Arc::new(OneEntryStore { token, content });- let Some(tool) = tinyjuice::repl::tools::repl_tools(store, self.limits)- .into_iter()- .find(|tool| tool.name() == self.name)- else {- return Ok(ToolResult::error("juice: unknown repl tool"));+ let op: ReplOp = match serde_json::from_value(args) {+ Ok(op) => op,+ Err(error) => {+ return Ok(ToolResult::error(format!(+ "juice: invalid arguments: {error}"+ )))+ }};- tool.execute(args).await+ let response = self+ .source+ .query(QueryRequest {+ target,+ op,+ limits: self.limits,+ context_token: None,+ scope: None,+ })+ .await;+ Ok(match response {+ Ok(Ok(output)) => ToolResult::json(serde_json::to_value(output)?),+ Ok(Err(QueryError::HandleNotFound)) => ToolResult::failed(miss_message()),+ Ok(Err(QueryError::InputTooLarge)) => {+ ToolResult::error("juice: input exceeds module limit")+ }+ Ok(Err(QueryError::InvalidPattern(pattern))) => {+ ToolResult::error(format!("juice: invalid pattern: {pattern}"))+ }+ Ok(Err(QueryError::EmptyQuery)) => ToolResult::error("juice: empty query"),+ Ok(Err(QueryError::Unsupported(operation))) => {+ ToolResult::error(format!("juice: {operation} support is not compiled in"))+ }+ Err(error) => ToolResult::error(format!("juice: {error}")),+ })}/// The handle slot held a path: query the persisted artifact it names.@@ -324,8 +293,7 @@ impl ModuleReplTool {self.name,content.len());- self.run_stock(ARTIFACT_TOKEN.to_string(), content, args)- .await+ self.run_query(QueryTarget::Content { content }, args).await}Err(message) => {log::debug!("[tokenjuice][repl] {} artifact refused", self.name);@@ -361,23 +329,8 @@ impl Tool for ModuleReplTool {return Ok(ToolResult::error(not_a_handle_message()));}};- let content = match self.source.original(&handle).await {- Ok(Some(content)) => content,- Ok(None) => {- log::debug!("[tokenjuice][repl] {} handle miss", self.name);- return Ok(ToolResult::failed(miss_message()));- }- Err(error) => {- log::debug!("[tokenjuice][repl] {} source error: {error}", self.name);- return Ok(ToolResult::error(format!("juice: {error}")));- }- };- log::debug!(- "[tokenjuice][repl] {} handle={handle} bytes={}",- self.name,- content.len()- );- self.run_stock(handle, content, args).await+ self.run_query(QueryTarget::Handle { token: handle }, args)+ .await}fn permission_level(&self) -> PermissionLevel {diff --git a/crates/openhuman-core/src/inference/tokenjuice/repl_tools_tests.rs b/crates/openhuman-core/src/inference/tokenjuice/repl_tools_tests.rsindex ef0f8ae9ca..e36b58ea84 100644--- a/crates/openhuman-core/src/inference/tokenjuice/repl_tools_tests.rs+++ b/crates/openhuman-core/src/inference/tokenjuice/repl_tools_tests.rs@@ -1,254 +1,130 @@use super::*;use serde_json::json;-use tinyjuice::cache::store::MemoryCcrStore;-use tinyjuice::types::{CompressOptions, CompressorKind};+use std::sync::Mutex;+use tinyjuice_bus::repl::ReplOutput;-/// Reads originals from an in-process store instead of the module.-struct MemorySource(Arc<MemoryCcrStore>);+#[derive(Default)]+struct RecordingSource(Mutex<Vec<QueryRequest>>);#[async_trait]-impl OriginalSource for MemorySource {- async fn original(&self, handle: &str) -> Result<Option<String>, String> {- Ok(self.0.get(handle))+impl QuerySource for RecordingSource {+ async fn query(&self, request: QueryRequest) -> Result<QueryResponse, String> {+ self.0.lock().unwrap().push(request);+ Ok(Ok(ReplOutput::Text {+ text: "needle in the middle".into(),+ }))}}struct FailingSource;-#[async_trait]-impl OriginalSource for FailingSource {- async fn original(&self, _handle: &str) -> Result<Option<String>, String> {- Err("module unavailable".to_string())+impl QuerySource for FailingSource {+ async fn query(&self, _: QueryRequest) -> Result<QueryResponse, String> {+ Err("module unavailable".into())}}fn tool(tools: &[Box<dyn Tool>], name: &str) -> usize {- tools- .iter()- .position(|t| t.name() == name)- .unwrap_or_else(|| panic!("no tool named {name}"))-}--fn log_body() -> String {- let rows: String = (0..900)- .map(|i| format!("row {i}: value {}\n", i * 7))- .collect();- let tail: String = (900..1000)- .map(|i| format!("row {i}: value {}\n", i * 7))- .collect();- format!("# Report\n{rows}ERROR: needle in the middle\n{tail}")+ tools.iter().position(|t| t.name() == name).unwrap()}--/// Compress `content` in handle mode against `store`, returning the model-facing-/// text and the handle.-async fn store_behind_handle(store: &MemoryCcrStore, content: &str) -> (String, String) {- let options = CompressOptions {- repl_handle: true,- ..CompressOptions::default()- };- let out = tinyjuice::compress_content_with_store(content, None, &options, store).await;- assert_eq!(- out.compressor,- CompressorKind::Repl,- "handle mode must apply"- );- let handle = out.ccr_token.clone().expect("a handle");- (out.text, handle)-}-fn result_text(result: &ToolResult) -> String {result.output()}+fn log_body() -> String {+ "# Report\nrow\nERROR: needle in the middle\n".repeat(100)+}#[test]-fn declares_the_three_repl_tools_read_only_capped_and_small() {+fn declarations_preserve_names_schemas_and_read_only_caps() {let tools = repl_tools();- let names: Vec<&str> = tools.iter().map(|t| t.name()).collect();assert_eq!(- names, REPL_TOOL_NAMES,- "same tools, same order as TinyJuice"+ tools.iter().map(|t| t.name()).collect::<Vec<_>>(),+ REPL_TOOL_NAMES);-- let mut schema_bytes = 0;- for t in &tools {- assert!(is_repl_tool(t.name()));- assert_eq!(t.permission_level(), PermissionLevel::ReadOnly);- assert!(t.is_concurrency_safe(&json!({})));- assert!(!t.external_effect());- assert!(- t.max_result_size_chars().is_some_and(|cap| cap > 0),- "{} must declare a result cap",- t.name()- );- let schema = t.parameters_schema();- assert!(- schema["required"]- .as_array()- .is_some_and(|r| r.contains(&json!("handle"))),- "{} must require a handle",- t.name()- );- schema_bytes += t.name().len() + t.description().len() + schema.to_string().len();+ for (tool, declaration) in tools+ .iter()+ .zip(tinyjuice_bus::tools::repl_tool_declarations())+ {+ assert_eq!(tool.parameters_schema(), declaration.parameters);+ assert_eq!(tool.description(), declaration.description);+ assert_eq!(tool.permission_level(), PermissionLevel::ReadOnly);+ assert!(tool.is_concurrency_safe(&json!({})));+ assert!(!tool.external_effect());+ assert_eq!(tool.max_result_size_chars(), Some(16_000));}- // The point of three tools is a schema that stays small on every turn.- assert!(schema_bytes < 3_000, "schemas are {schema_bytes} bytes");}#[tokio::test]-async fn handle_round_trip_find_summarize_and_extract() {- let store = Arc::new(MemoryCcrStore::default());- let content = log_body();- let (preview, handle) = store_behind_handle(&store, &content).await;-- // The model sees a small preview naming the handle and the tools.- assert!(preview.len() < content.len() / 4);- assert!(preview.contains(&handle));- // It names the slice read and the outline, then the whole-original- // retrieve last; `juice_extract` (HTML/Markdown only) is left to its- // description.- for name in ["juice_find", "juice_summarize"] {- assert!(preview.contains(name), "footer must name {name}");- }- let find = preview.find("juice_find").unwrap();- let retrieve = preview- .find(crate::inference::tokenjuice::RETRIEVE_TOOL_NAME)- .expect("footer names the whole-original retrieve");- assert!(- find < retrieve,- "slice read before whole original: {preview}"- );- assert!(- !preview.contains("needle in the middle"),- "the needle must be behind the handle, not in the preview"- );-- let tools = repl_tools_with(Arc::new(MemorySource(store)), ReplLimits::default());-- let found = tools[tool(&tools, "juice_find")]- .execute(json!({ "handle": handle, "query": "needle" }))- .await- .unwrap();- assert!(!found.is_error, "{}", result_text(&found));- assert!(result_text(&found).contains("needle in the middle"));-- let by_grep = tools[tool(&tools, "juice_find")]- .execute(json!({ "handle": handle, "query": "^row 899:", "mode": "grep" }))+async fn a_cached_handle_is_queried_without_retrieving_the_original() {+ let source = Arc::new(RecordingSource::default());+ let tools = repl_tools_with(source.clone(), ReplLimits::default());+ let result = tools[0]+ .execute(json!({"handle":"⟦tj:abc123⟧", "query":"needle"})).await.unwrap();- assert!(result_text(&by_grep).contains("row 899"));-- let summary = tools[tool(&tools, "juice_summarize")]- .execute(json!({ "handle": handle, "hint": "needle" }))- .await- .unwrap();- assert!(!summary.is_error, "{}", result_text(&summary));-- let md = "# Title\ntext\n## Section\nmore\n".repeat(200);- let md_store = Arc::new(MemoryCcrStore::default());- let (_, md_handle) = store_behind_handle(&md_store, &md).await;- let md_tools = repl_tools_with(Arc::new(MemorySource(md_store)), ReplLimits::default());- let headings = md_tools[tool(&md_tools, "juice_extract")]- .execute(json!({ "handle": md_handle, "what": "headings" }))- .await- .unwrap();- assert!(!headings.is_error, "{}", result_text(&headings));- assert!(result_text(&headings).contains("Section"));-}--#[tokio::test]-async fn answers_stay_within_the_declared_cap() {- let store = Arc::new(MemoryCcrStore::default());- let content = log_body();- let (_, handle) = store_behind_handle(&store, &content).await;- let tools = repl_tools_with(Arc::new(MemorySource(store)), ReplLimits::default());- let find = &tools[tool(&tools, "juice_find")];- // Every line matches.- let all = find- .execute(json!({ "handle": handle, "query": "row" }))- .await- .unwrap();- let cap = find.max_result_size_chars().unwrap();- assert!(- result_text(&all).chars().count() <= cap,- "{} chars exceeds the {cap} cap",- result_text(&all).chars().count()+ assert!(!result.is_error);+ let requests = source.0.lock().unwrap();+ assert_eq!(requests.len(), 1);+ assert_eq!(+ requests[0].target,+ QueryTarget::Handle {+ token: "abc123".into()+ });- assert!(result_text(&all).len() < content.len() / 4);+ assert!(matches!(&requests[0].op, ReplOp::Find {query, ..} if query == "needle"));}#[tokio::test]-async fn the_marker_form_of_a_handle_is_accepted() {- let store = Arc::new(MemoryCcrStore::default());- let (_, handle) = store_behind_handle(&store, &log_body()).await;- let tools = repl_tools_with(Arc::new(MemorySource(store)), ReplLimits::default());- let res = tools[0]- .execute(json!({ "handle": format!("⟦tj:{handle}⟧"), "query": "needle" }))+async fn authorized_artifacts_send_content_without_a_path() {+ let (_tmp, dir, file) = artifacts_fixture();+ let source = Arc::new(RecordingSource::default());+ let tools = repl_tools_with_artifacts(source.clone(), ReplLimits::default(), Some(dir));+ let result = tools[0]+ .execute(json!({"handle":file.to_string_lossy(), "query":"needle"})).await.unwrap();- assert!(!res.is_error, "{}", result_text(&res));- assert!(result_text(&res).contains("needle"));+ assert!(!result.is_error);+ assert_eq!(+ source.0.lock().unwrap()[0].target,+ QueryTarget::Content {+ content: log_body()+ }+ );}#[tokio::test]-async fn bad_or_unknown_handles_are_errors_that_do_not_invite_a_re_run() {- let store = Arc::new(MemoryCcrStore::default());- let tools = repl_tools_with(Arc::new(MemorySource(store)), ReplLimits::default());- let find = &tools[tool(&tools, "juice_find")];-- let missing = find.execute(json!({ "query": "x" })).await.unwrap();- assert!(missing.is_error);-- for bad in ["", "../etc/passwd", "a b", &"a".repeat(200)] {- let res = find- .execute(json!({ "handle": bad, "query": "x" }))- .await- .unwrap();- assert!(res.is_error, "handle {bad:?} must be rejected");+async fn rejected_paths_and_invalid_operations_never_reach_the_module() {+ let source = Arc::new(RecordingSource::default());+ let tools = repl_tools_with(source.clone(), ReplLimits::default());+ for args in [+ json!({"handle":"../secret", "query":"x"}),+ json!({"handle":"abc123"}),+ json!({}),+ ] {+ assert!(tools[0].execute(args).await.unwrap().is_error);}-- let unknown = find- .execute(json!({ "handle": "deadbeefdeadbeef", "query": "x" }))- .await- .unwrap();- assert!(unknown.is_error);- let msg = result_text(&unknown).to_lowercase();- assert!(msg.contains("do not re-run"), "{msg}");+ assert!(source.0.lock().unwrap().is_empty());}#[tokio::test]-async fn a_source_failure_is_reported_not_raised() {+async fn an_unavailable_module_is_a_tool_error() {let tools = repl_tools_with(Arc::new(FailingSource), ReplLimits::default());- let res = tools[0]- .execute(json!({ "handle": "abc123", "query": "x" }))+ let result = tools[0]+ .execute(json!({"handle":"abc123", "query":"x"})).await.unwrap();- assert!(res.is_error);- assert!(result_text(&res).contains("module unavailable"));+ assert!(result.is_error);+ assert!(result.output().contains("module unavailable"));}#[test]fn handle_normalization_only_accepts_alphanumeric_tokens() {assert_eq!(normalize_handle(" abc123 "), Some("abc123"));assert_eq!(normalize_handle("⟦tj:abc123⟧"), Some("abc123"));- assert_eq!(normalize_handle(""), None);assert_eq!(normalize_handle("../x"), None);assert_eq!(normalize_handle(&"f".repeat(MAX_HANDLE_LEN + 1)), None);}-#[test]-fn repl_tools_share_the_harness_tool_trait() {- // `tinyjuice::repl::tools` and this crate must name one `tinytools::Tool`;- // this only compiles when `repl_tools()` yields the trait objects the tool- // registry (`Vec<Box<dyn tinytools::Tool>>`) takes.- let registry: Vec<Box<dyn tinytools::Tool>> = repl_tools();- assert_eq!(registry.len(), REPL_TOOL_NAMES.len());- let raw: Vec<Box<dyn tinytools::Tool>> = tinyjuice::repl::tools::repl_tools(- Arc::new(MemoryCcrStore::default()),- ReplLimits::default(),- );- assert_eq!(raw.len(), registry.len());-}-/// A workspace whose tool-results dir holds one persisted shell output, the/// way `ToolResultArtifactStore::detached` writes it.fn artifacts_fixture() -> (tempfile::TempDir, std::path::PathBuf, std::path::PathBuf) {@@ -262,7 +138,7 @@ fn artifacts_fixture() -> (tempfile::TempDir, std::path::PathBuf, std::path::Patfn tools_with_artifacts(dir: std::path::PathBuf) -> Vec<Box<dyn Tool>> {repl_tools_with_artifacts(- Arc::new(MemorySource(Arc::new(MemoryCcrStore::default()))),+ Arc::new(RecordingSource::default()),ReplLimits::default(),Some(dir),)@@ -379,10 +255,7 @@ async fn a_call_id_or_other_non_handle_gets_an_actionable_message() {let (_tmp, dir, _file) = artifacts_fixture();for tools in [tools_with_artifacts(dir),- repl_tools_with(- Arc::new(MemorySource(Arc::new(MemoryCcrStore::default()))),- ReplLimits::default(),- ),+ repl_tools_with(Arc::new(RecordingSource::default()), ReplLimits::default()),] {let find = &tools[tool(&tools, "juice_find")];for bad in ["call_abc123", "toolu_01XyZ", "a b"] {@@ -401,10 +274,7 @@ async fn a_call_id_or_other_non_handle_gets_an_actionable_message() {#[tokio::test]async fn an_artifact_path_without_a_configured_dir_points_at_file_read() {let (_tmp, _dir, file) = artifacts_fixture();- let tools = repl_tools_with(- Arc::new(MemorySource(Arc::new(MemoryCcrStore::default()))),- ReplLimits::default(),- );+ let tools = repl_tools_with(Arc::new(RecordingSource::default()), ReplLimits::default());let res = tools[tool(&tools, "juice_find")].execute(json!({ "handle": file.to_string_lossy(), "query": "needle" })).await@@ -413,52 +283,6 @@ async fn an_artifact_path_without_a_configured_dir_points_at_file_read() {assert!(result_text(&res).contains("file_read"));}-/// Every `juice_*` / `*_retrieve` identifier a footer mentions.-fn tool_names_in(text: &str) -> Vec<String> {- text.split(|c: char| !(c.is_ascii_alphanumeric() || c == '_'))- .filter(|w| w.starts_with("juice_") || w.ends_with("_retrieve") || w.contains("juice_"))- .map(str::to_string)- .collect()-}--#[tokio::test]-async fn compressed_output_footers_only_name_tools_that_exist() {- // Regression for the "unknown tool juice_*" cluster: a footer naming a tool- // the model is not offered (or a pre-rename alias like `tinyjuice_retrieve`)- // burns the model's failure budget on a call that cannot dispatch.- use crate::inference::tokenjuice::RETRIEVE_TOOL_NAME;- let offered: Vec<&str> = REPL_TOOL_NAMES- .iter()- .copied()- .chain([RETRIEVE_TOOL_NAME])- .collect();-- let store = MemoryCcrStore::default();- let (handle_footer, _) = store_behind_handle(&store, &log_body()).await;-- let ccr = tinyjuice::compress_content_with_store(- &log_body(),- None,- &CompressOptions::default(),- &MemoryCcrStore::default(),- )- .await;-- let mut seen = 0;- for footer in [handle_footer, ccr.text] {- assert!(!footer.contains("tinyjuice_retrieve"), "{footer}");- assert!(!footer.contains("tokenjuice_retrieve"), "{footer}");- for name in tool_names_in(&footer) {- seen += 1;- assert!(- offered.contains(&name.as_str()),- "footer names `{name}`, which is not an offered tool: {footer}"- );- }- }- assert!(seen > 0, "the footers must name at least one tool");-}-/// A workspace reached through a symlinked component (macOS `/var` ->/// `/private/var`) still accepts the canonical absolute `artifact_path` the/// store hands out, while the canonical containment check keeps refusingdiff --git a/crates/openhuman-core/src/modules/registry/records_memory_juice.rs b/crates/openhuman-core/src/modules/registry/records_memory_juice.rsindex 08b190cc2b..5ce5a761ec 100644--- a/crates/openhuman-core/src/modules/registry/records_memory_juice.rs+++ b/crates/openhuman-core/src/modules/registry/records_memory_juice.rs@@ -7,63 +7,63 @@ pub(crate) const TINYJUICE: ModuleRecord = ModuleRecord {description: "Content-aware tool-output compression and recoverable caching",bus_name: "ai.tinyhumans.tinyjuice.Compression",object_path: "/ai/tinyhumans/tinyjuice/Compression",- version: "0.6.1",- release_url: "https://github.com/tinyhumansai/tinyjuice/releases/tag/v0.6.1",+ version: "0.7.0",+ release_url: "https://github.com/tinyhumansai/tinyjuice/releases/tag/v0.7.0",assets: &[PlatformAsset {host_key: "ubuntu-24.04-x86_64",- archive: "tinyjuice-module-0.6.1-ubuntu-24.04-x86_64.tar.gz",- sha256: "cdb6e564bb531b8c43a6a5250cedb34268f9623787502ad9fdcce2b331af5bb2",+ archive: "tinyjuice-module-0.7.0-ubuntu-24.04-x86_64.tar.gz",+ sha256: "368e3173b226d4ef052e18e3fc94284d9d4c4e25be4c8f55215f5baa662ef641",},PlatformAsset {host_key: "ubuntu-24.04-arm64",- archive: "tinyjuice-module-0.6.1-ubuntu-24.04-arm64.tar.gz",- sha256: "e3f55125b1367eeaba39987f6d80bdf0da2c4f18da57b6f6afc52ec21a40b18b",+ archive: "tinyjuice-module-0.7.0-ubuntu-24.04-arm64.tar.gz",+ sha256: "4a8ae99854c30c1141162f541a0ee7234ecca1fad14f80aafbb2387ab1766d3a",},PlatformAsset {host_key: "ubuntu-22.04-x86_64",- archive: "tinyjuice-module-0.6.1-ubuntu-22.04-x86_64.tar.gz",- sha256: "a85f68188c49b853184c26f81a9aa888a3367271a3e11c13e4dd2a7401abb594",+ archive: "tinyjuice-module-0.7.0-ubuntu-22.04-x86_64.tar.gz",+ sha256: "1ccebb91c91ecc6e57d0d5aaae26a0625f3262529191a19f2437cc082eac20b1",},PlatformAsset {host_key: "ubuntu-22.04-arm64",- archive: "tinyjuice-module-0.6.1-ubuntu-22.04-arm64.tar.gz",- sha256: "aaa238f0b27e2cadcf0aabbde029b9aa896a75a837d490d3c9b4400c467e183b",+ archive: "tinyjuice-module-0.7.0-ubuntu-22.04-arm64.tar.gz",+ sha256: "b5a626c55f45edc02520dfed98c70bd4d273c676ad0853a54f641dcc3d0b2aef",},PlatformAsset {host_key: "macos-26-arm64",- archive: "tinyjuice-module-0.6.1-macos-26-arm64.tar.gz",- sha256: "d4a16acb408cd9ec9d4bde065cc9a1acc67bd2177a6eb90b0f90377ac2063ccc",+ archive: "tinyjuice-module-0.7.0-macos-26-arm64.tar.gz",+ sha256: "994b02f2d04b8f3b58abd521fb4759256728f979d92487e031035d7580bd05d5",},PlatformAsset {host_key: "macos-26-x86_64",- archive: "tinyjuice-module-0.6.1-macos-26-x86_64.tar.gz",- sha256: "f5993a5cfab65beac1de8e93ecbbe17e0239d7d8255f4d0194beaa7af99630b2",+ archive: "tinyjuice-module-0.7.0-macos-26-x86_64.tar.gz",+ sha256: "3ac4b9c7813d83ad99859a3fb819644f21a4260751e394c4390542ac65bcf6d6",},PlatformAsset {host_key: "macos-15-arm64",- archive: "tinyjuice-module-0.6.1-macos-15-arm64.tar.gz",- sha256: "b04f48708fa78c196f98c2ab692343acac547aa8b361039ee88c8fc64f49d9d6",+ archive: "tinyjuice-module-0.7.0-macos-15-arm64.tar.gz",+ sha256: "f93cf8af3e04603b5392ffe9f108b86fb55f9821339dc52196a3153ae7cf9a83",},PlatformAsset {host_key: "macos-15-x86_64",- archive: "tinyjuice-module-0.6.1-macos-15-x86_64.tar.gz",- sha256: "bb4ed1fc271958fd47c8af82387307e7fefa7d7945073a54ec0c62587367b07c",+ archive: "tinyjuice-module-0.7.0-macos-15-x86_64.tar.gz",+ sha256: "cfb87a37aa0e7fa45f3b636ed20f0e58e8cd1b5da35be79b24c35b2bcb6fdf19",},PlatformAsset {host_key: "windows-2025-x86_64",- archive: "tinyjuice-module-0.6.1-windows-2025-x86_64.zip",- sha256: "4f821817706a3064c3894cfd9f677cc6841e8a3271d134d7c2894c1a4c426b90",+ archive: "tinyjuice-module-0.7.0-windows-2025-x86_64.zip",+ sha256: "60611a2f21cd4b3d6b1fb1f860b837656d1bd82ad1ed5d518467864be0056860",},PlatformAsset {host_key: "windows-2022-x86_64",- archive: "tinyjuice-module-0.6.1-windows-2022-x86_64.zip",- sha256: "a29ef60e7959a416d548bba077cbd3747dacce286e72c5ad4eda6042f7557da3",+ archive: "tinyjuice-module-0.7.0-windows-2022-x86_64.zip",+ sha256: "0f18a10f9c71a3dcec440ec610a7972074bf6270b355d83173c625d03cc8f55b",},PlatformAsset {host_key: "windows-11-arm64",- archive: "tinyjuice-module-0.6.1-windows-11-arm64.zip",- sha256: "bcdc2d8ba0770ba1c68356a825786cfc0d2ad1316c31f2a3a1edd3045190c3f7",+ archive: "tinyjuice-module-0.7.0-windows-11-arm64.zip",+ sha256: "19393938ebe4661c1e25b68fd144420a3dc65658caa1cc311973900553f6aa25",},],load: LoadPolicy::Lazy,diff --git a/crates/openhuman-core/src/tools/impl/network/host.rs b/crates/openhuman-core/src/tools/impl/network/host.rsindex 52fb495316..81e5375c5f 100644--- a/crates/openhuman-core/src/tools/impl/network/host.rs+++ b/crates/openhuman-core/src/tools/impl/network/host.rs@@ -7,7 +7,9 @@use std::sync::Arc;-use tinytools_std::network::{HtmlExtractor, HttpLimits, HttpRequestTool, NetGate, WebFetchTool};+use tinytools_std::network::{+ AsyncHtmlExtractor, HttpLimits, HttpRequestTool, NetGate, WebFetchTool,+};use crate::config::HttpRequestConfig;use crate::inference::tokenjuice::focus::{summary_focus_property, SUMMARY_FOCUS_ARG};@@ -22,22 +24,26 @@ fn http_limits() -> HttpLimits {}}-/// TinyJuice as `web_fetch`'s page engine. `tinyjuice` owns content-/// transforms; see the dependency note in `Cargo.toml` for why this is a direct-/// call and not a trip through the module bus.+/// HTML detection and extraction execute in the lazily loaded TinyJuice module.#[derive(Debug)]struct TinyJuiceHtml;-impl HtmlExtractor for TinyJuiceHtml {- fn looks_like_html(&self, body: &str) -> bool {- matches!(- tinyjuice::detect_content_kind(body, &tinyjuice::types::ContentHint::default()),- tinyjuice::types::ContentKind::Html+#[async_trait::async_trait]+impl AsyncHtmlExtractor for TinyJuiceHtml {+ async fn looks_like_html(&self, body: &str) -> anyhow::Result<bool> {+ let kind = crate::inference::tokenjuice::detect(+ body.to_string(),+ crate::inference::tokenjuice::types::ContentHint::default(),)+ .await+ .map_err(anyhow::Error::msg)?;+ Ok(kind == "html")}- fn to_markdown(&self, html: &str) -> String {- tinyjuice::compressors::html::html_to_markdown(html)+ async fn to_markdown(&self, html: &str) -> anyhow::Result<String> {+ crate::inference::tokenjuice::extract_html(html.to_string())+ .await+ .map_err(anyhow::Error::msg)}}@@ -68,7 +74,7 @@ pub fn web_fetch_tool(max_bytes: Option<usize>,timeout_secs: Option<u64>,) -> WebFetchTool {- WebFetchTool::new(+ WebFetchTool::new_async(gate,allowed_domains,max_bytes,diff --git a/crates/openhuman-core/src/tools/impl/network/host_tests.rs b/crates/openhuman-core/src/tools/impl/network/host_tests.rsindex fbf4fa80d1..80a29436dd 100644--- a/crates/openhuman-core/src/tools/impl/network/host_tests.rs+++ b/crates/openhuman-core/src/tools/impl/network/host_tests.rs@@ -85,10 +85,21 @@ fn zero_limits_fall_back_to_the_http_request_config_defaults() {assert_ne!(limits.timeout_secs, 0);}-#[test]-fn tinyjuice_detects_and_converts_html() {+#[tokio::test]+async fn tinyjuice_detects_and_converts_html() {+ if std::env::var_os("TINYJUICE_TEST_MODULE").is_none() {+ eprintln!("SKIPPED: released module fixture is not configured");+ return;+ }let page = "<!DOCTYPE html><html><body><p>hi</p></body></html>";- assert!(TinyJuiceHtml.looks_like_html(page));- assert!(!TinyJuiceHtml.looks_like_html("# Just a README\n\nSome prose.\n"));- assert!(TinyJuiceHtml.to_markdown(page).contains("hi"));+ assert!(TinyJuiceHtml.looks_like_html(page).await.unwrap());+ assert!(!TinyJuiceHtml+ .looks_like_html("# Just a README\n\nSome prose.\n")+ .await+ .unwrap());+ assert!(TinyJuiceHtml+ .to_markdown(page)+ .await+ .unwrap()+ .contains("hi"));}diff --git a/crates/openhuman-core/src/tools/impl/system/retrieve_tool_output.rs b/crates/openhuman-core/src/tools/impl/system/retrieve_tool_output.rsindex e4222f34f1..6eb63f6a1c 100644--- a/crates/openhuman-core/src/tools/impl/system/retrieve_tool_output.rs+++ b/crates/openhuman-core/src/tools/impl/system/retrieve_tool_output.rs@@ -1,14 +1,99 @@//! Tool: retrieve_tool_output — fetch the original of a compacted tool result.//!-//! The tool itself lives in `tinyjuice::host::retrieve_tool`; OpenHuman only-//! supplies the lookup, which asks the TinyJuice module for the stashed-//! original by hash.+//! Native tool-output compaction (Stage 1a) may replace a large tool result+//! with a compacted view and a `retrieve_tool_output("<hash>")` sentinel,+//! stashing the original in the TokenJuice store. This tool hands the original+//! back on demand, so even lossy compaction stays reversible.+//!+//! Read-only, no side effects, no path/network access.+use std::future::Future;+use std::pin::Pin;use std::sync::Arc;-pub use tinyjuice::host::retrieve_tool::RetrieveToolOutputTool;+use async_trait::async_trait;+use tinytools::{PermissionLevel, Tool, ToolResult};++/// Looks a stored original up by hash: `Ok(None)` is a cache miss.+pub type RetrieveFn = Arc<+ dyn Fn(String) -> Pin<Box<dyn Future<Output = Result<Option<String>, String>> + Send>>+ + Send+ + Sync,+>;++/// The `retrieve_tool_output` tool, bound to a host-supplied lookup.+pub struct RetrieveToolOutputTool {+ retrieve: RetrieveFn,+}++impl RetrieveToolOutputTool {+ /// Build the tool over `retrieve`, which resolves a hash to the original.+ pub fn new(retrieve: RetrieveFn) -> Self {+ Self { retrieve }+ }+}++#[async_trait]+impl Tool for RetrieveToolOutputTool {+ fn name(&self) -> &str {+ "retrieve_tool_output"+ }++ fn description(&self) -> &str {+ tinyjuice_bus::tools::RETRIEVE_TOOL_DESCRIPTION+ }++ fn parameters_schema(&self) -> serde_json::Value {+ tinyjuice_bus::tools::retrieve_tool_parameters()+ }++ fn permission_level(&self) -> PermissionLevel {+ PermissionLevel::ReadOnly+ }++ async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {+ let hash = args+ .get("hash")+ .and_then(|v| v.as_str())+ .map(str::trim)+ .filter(|s| !s.is_empty());+ let Some(hash) = hash else {+ return Ok(ToolResult::error(+ "retrieve_tool_output: missing required 'hash' argument".to_string(),+ ));+ };++ match (self.retrieve)(hash.to_string()).await {+ Ok(Some(original)) => {+ log::debug!(+ "[compaction][ccr] retrieved hash={} bytes={}",+ hash,+ original.len()+ );+ Ok(ToolResult::success(original))+ }+ // Deliberately does NOT say "re-run the tool". Re-running+ // regenerates the same oversized result, which is compacted and+ // offloaded again under a new hash that can be evicted just as fast+ // — so a blind re-run turns one cache miss into an unbounded+ // compact→retrieve→re-run loop (observed live: a parent agent+ // re-delegated forever on an evicted subagent result). Tell the+ // model to proceed with the compacted summary it already has.+ Ok(None) => Ok(ToolResult::error(format!(+ "retrieve_tool_output: the full original for hash '{hash}' is no longer \+ cached (evicted, or from an earlier session). Do NOT re-run the same tool \+ call to regenerate it — that produces the same oversized result and is \+ compacted again. Proceed using the compacted summary already shown above; \+ only if a specific missing detail is essential, retry with narrower \+ arguments (a tighter query, filter, or smaller limit) so the result is \+ small enough to keep in full."+ ))),+ Err(error) => Ok(ToolResult::error(error)),+ }+ }+}-/// The tool wired to the TokenJuice module's store.+/// Bind the recovery tool to the module-owned cache.pub fn retrieve_tool_output_tool() -> RetrieveToolOutputTool {RetrieveToolOutputTool::new(Arc::new(|hash| {Box::pin(async move { crate::inference::tokenjuice::retrieve(hash, None).await })diff --git a/scripts/ci/module-boundaries.json b/scripts/ci/module-boundaries.jsonindex 7d38c1b67d..ba4ed889df 100644--- a/scripts/ci/module-boundaries.json+++ b/scripts/ci/module-boundaries.json@@ -104,11 +104,6 @@}],"exceptions": [- {- "scope": "hosts",- "package": "tinyjuice",- "reason": "HTML extraction, REPL execution and schema vocabulary still call the implementation."- },{"scope": "hosts","package": "tinymcp",