Skip to content

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

feat(tokenjuice): add focus and generate modules with tool output retrieval

Steven Enamakel43509e52f7ea
diff --git a/crates/openhuman-core/Cargo.toml b/crates/openhuman-core/Cargo.toml
index 6d0480b241..c8a13a36e6 100644
--- a/crates/openhuman-core/Cargo.toml
+++ b/crates/openhuman-core/Cargo.toml
@@ -601,7 +601,7 @@ tinyjuice-bus = { path = "../../vendor/tinyjuice/crates/tinyjuice-bus" }
# 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"] }
+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
diff --git a/crates/openhuman-core/src/inference/tokenjuice/focus.rs b/crates/openhuman-core/src/inference/tokenjuice/focus.rs
deleted file mode 100644
index 864200f648..0000000000
--- a/crates/openhuman-core/src/inference/tokenjuice/focus.rs
+++ /dev/null
@@ -1,45 +0,0 @@
-//! `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::{json, Value};
-
-/// The argument's name on the wire.
-pub const SUMMARY_FOCUS_ARG: &str = "summary_focus";
-
-/// The schema for the optional `summary_focus` argument.
-pub fn summary_focus_property() -> Value {
- json!({
- "type": "string",
- "description": "What you need from this result. A large result is summarized around \
- this; the full output stays retrievable."
- })
-}
-
-/// 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.rs
deleted file mode 100644
index 497a6ad9bd..0000000000
--- a/crates/openhuman-core/src/inference/tokenjuice/focus_tests.rs
+++ /dev/null
@@ -1,53 +0,0 @@
-use super::*;
-
-#[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!({})));
-}
diff --git a/crates/openhuman-core/src/inference/tokenjuice/generate.rs b/crates/openhuman-core/src/inference/tokenjuice/generate.rs
deleted file mode 100644
index 0356fff289..0000000000
--- a/crates/openhuman-core/src/inference/tokenjuice/generate.rs
+++ /dev/null
@@ -1,97 +0,0 @@
-//! The host half of TinyJuice's summary stage: serving `MlHost.Generate`.
-//!
-//! TinyJuice writes the summary prompt and decides when one is worth writing;
-//! the model call is ours, because only the host knows which model the turn
-//! runs on, and the call must inherit that turn's cancellation, thread and
-//! lineage. None of that crosses the bus, and task-local state does not cross
-//! a module boundary either, so the turn is passed by reference instead:
-//!
-//! 1. before `CompactWith`, the caller [`register`]s a [`PreparedGenerate`] —
-//! a closure already bound to its turn — and sends the returned ticket's
-//! token as `context_token`;
-//! 2. if the module asks for a summary, `MlHost.Generate` arrives with that
-//! token and [`serve`] runs the closure;
-//! 3. the ticket removes the entry when dropped, whether or not it was used.
-//!
-//! An unknown token (expired, never registered, or already used) is a decline,
-//! not an error: the module then falls back to its deterministic compressors.
-
-use std::collections::HashMap;
-use std::sync::{LazyLock, Mutex};
-
-use futures::future::BoxFuture;
-
-pub use tinyjuice_bus::wire::GenerateRequest;
-
-/// One model call, bound to the turn that will pay for it.
-pub type PreparedGenerate =
- Box<dyn FnOnce(GenerateRequest) -> BoxFuture<'static, anyhow::Result<String>> + Send>;
-
-static PENDING: LazyLock<Mutex<HashMap<String, PreparedGenerate>>> =
- LazyLock::new(Default::default);
-
-/// Holds one registered call. Dropping it withdraws the call.
-#[must_use = "dropping the ticket withdraws the registered call"]
-pub struct GenerateTicket {
- token: String,
-}
-
-impl GenerateTicket {
- /// The value to send as `CompactRequest::context_token`.
- pub fn token(&self) -> &str {
- &self.token
- }
-}
-
-impl Drop for GenerateTicket {
- fn drop(&mut self) {
- if let Ok(mut pending) = PENDING.lock() {
- pending.remove(&self.token);
- }
- }
-}
-
-/// Register a call and get the ticket that names it.
-pub fn register(prepared: PreparedGenerate) -> GenerateTicket {
- let token = uuid::Uuid::new_v4().to_string();
- if let Ok(mut pending) = PENDING.lock() {
- pending.insert(token.clone(), prepared);
- }
- log::debug!("[tokenjuice::generate] registered context_token={token}");
- GenerateTicket { token }
-}
-
-/// Answer one `MlHost.Generate` call. `Ok(None)` declines.
-pub async fn serve(request: GenerateRequest) -> Result<Option<String>, String> {
- let token = request.context_token.clone();
- let prepared = PENDING.lock().ok().and_then(|mut p| p.remove(&token));
- let Some(prepared) = prepared else {
- log::debug!("[tokenjuice::generate] no registered call, declining context_token={token}");
- return Ok(None);
- };
- let prompt_bytes = request.prompt.len();
- let purpose = request.purpose.clone();
- let started = std::time::Instant::now();
- match prepared(request).await {
- Ok(text) => {
- log::info!(
- "[tokenjuice::generate] served context_token={token} purpose={purpose} \
- prompt_bytes={prompt_bytes} reply_bytes={} elapsed_ms={}",
- text.len(),
- started.elapsed().as_millis()
- );
- Ok(Some(text))
- }
- Err(error) => {
- log::warn!(
- "[tokenjuice::generate] model call failed context_token={token} purpose={purpose} \
- error={error}"
- );
- Err(error.to_string())
- }
- }
-}
-
-#[cfg(test)]
-#[path = "generate_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/inference/tokenjuice/generate_tests.rs b/crates/openhuman-core/src/inference/tokenjuice/generate_tests.rs
deleted file mode 100644
index c6e30ba570..0000000000
--- a/crates/openhuman-core/src/inference/tokenjuice/generate_tests.rs
+++ /dev/null
@@ -1,52 +0,0 @@
-use super::*;
-
-fn request(token: &str) -> GenerateRequest {
- GenerateRequest {
- context_token: token.to_string(),
- purpose: "tool_output_summary".into(),
- system: "system".into(),
- prompt: "prompt".into(),
- max_output_tokens: 16,
- }
-}
-
-#[tokio::test]
-async fn an_unknown_token_declines() {
- assert_eq!(serve(request("never-registered")).await, Ok(None));
-}
-
-#[tokio::test]
-async fn a_registered_call_runs_once_with_the_request() {
- let ticket = register(Box::new(|request: GenerateRequest| {
- Box::pin(async move { Ok(format!("{} / {}", request.system, request.prompt)) })
- }));
- let token = ticket.token().to_string();
- assert_eq!(
- serve(request(&token)).await,
- Ok(Some("system / prompt".to_string()))
- );
- // Used up: a second call for the same token declines.
- assert_eq!(serve(request(&token)).await, Ok(None));
-}
-
-#[tokio::test]
-async fn a_dropped_ticket_withdraws_its_call() {
- let ticket = register(Box::new(|_| {
- Box::pin(async { panic!("a withdrawn call must not run") })
- }));
- let token = ticket.token().to_string();
- drop(ticket);
- assert_eq!(serve(request(&token)).await, Ok(None));
-}
-
-#[tokio::test]
-async fn a_failed_model_call_is_an_error() {
- let ticket = register(Box::new(|_| {
- Box::pin(async { Err(anyhow::anyhow!("provider offline")) })
- }));
- let token = ticket.token().to_string();
- assert_eq!(
- serve(request(&token)).await,
- Err("provider offline".to_string())
- );
-}
diff --git a/crates/openhuman-core/src/inference/tokenjuice/mod.rs b/crates/openhuman-core/src/inference/tokenjuice/mod.rs
index 9860a557e7..fbc8eb8fcf 100644
--- a/crates/openhuman-core/src/inference/tokenjuice/mod.rs
+++ b/crates/openhuman-core/src/inference/tokenjuice/mod.rs
@@ -1,8 +1,7 @@
//! OpenHuman host adapter for the separately released TinyJuice module.
pub mod config_patch;
-pub mod focus;
-pub mod generate;
+pub use tinyjuice::host::{focus, generate};
pub mod ml;
pub mod repl_tools;
pub mod savings;
diff --git a/crates/openhuman-core/src/tools/impl/system/mod.rs b/crates/openhuman-core/src/tools/impl/system/mod.rs
index e0b110ec0d..5c1e79430e 100644
--- a/crates/openhuman-core/src/tools/impl/system/mod.rs
+++ b/crates/openhuman-core/src/tools/impl/system/mod.rs
@@ -32,7 +32,7 @@ pub use npm_exec::NpmExecTool;
pub use proxy_config::ProxyConfigTool;
pub use pushover::PushoverTool;
pub use python_exec::PythonExecTool;
-pub use retrieve_tool_output::RetrieveToolOutputTool;
+pub use retrieve_tool_output::{retrieve_tool_output_tool, RetrieveToolOutputTool};
pub use schedule::ScheduleTool;
pub use shell::ShellTool;
pub use tool_stats::ToolStatsTool;
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.rs
index abc2ded99f..e4222f34f1 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,101 +1,18 @@
//! Tool: retrieve_tool_output — fetch the original of a compacted tool result.
//!
-//! 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 async_trait::async_trait;
-use serde_json::json;
-use tinytools::{PermissionLevel, Tool, ToolResult};
-
-pub struct RetrieveToolOutputTool;
-
-impl RetrieveToolOutputTool {
- pub fn new() -> Self {
- Self
- }
-}
-
-impl Default for RetrieveToolOutputTool {
- fn default() -> Self {
- Self::new()
- }
-}
-
-#[async_trait]
-impl Tool for RetrieveToolOutputTool {
- fn name(&self) -> &str {
- "retrieve_tool_output"
- }
-
- fn description(&self) -> &str {
- "Retrieve the full, original text of a tool result that was compacted to \
- save context. When a tool output shows a marker like \
- `retrieve_tool_output(\"a1b2c3d4e5f6\")`, call this with that hash to get \
- the complete original back. Use it only when you actually need the dropped \
- detail — the compacted view is usually enough."
- }
-
- fn parameters_schema(&self) -> serde_json::Value {
- json!({
- "type": "object",
- "properties": {
- "hash": {
- "type": "string",
- "description": "The hash from a retrieve_tool_output(\"…\") marker."
- }
- },
- "required": ["hash"]
- })
- }
+//! 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.
- fn permission_level(&self) -> PermissionLevel {
- PermissionLevel::ReadOnly
- }
+use std::sync::Arc;
- 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(),
- ));
- };
+pub use tinyjuice::host::retrieve_tool::RetrieveToolOutputTool;
- match crate::inference::tokenjuice::retrieve(hash.to_string(), None).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.
+pub fn retrieve_tool_output_tool() -> RetrieveToolOutputTool {
+ RetrieveToolOutputTool::new(Arc::new(|hash| {
+ Box::pin(async move { crate::inference::tokenjuice::retrieve(hash, None).await })
+ }))
}
#[cfg(test)]
diff --git a/crates/openhuman-core/src/tools/impl/system/retrieve_tool_output_tests.rs b/crates/openhuman-core/src/tools/impl/system/retrieve_tool_output_tests.rs
index cf66a7036f..720f2a3d4c 100644
--- a/crates/openhuman-core/src/tools/impl/system/retrieve_tool_output_tests.rs
+++ b/crates/openhuman-core/src/tools/impl/system/retrieve_tool_output_tests.rs
@@ -1,60 +1,20 @@
use super::*;
-#[tokio::test]
-#[ignore = "requires a built TinyJuice module"]
-async fn retrieves_offloaded_original() {
- let original = "ORIGINAL PAYLOAD ".repeat(20);
- let hash = "module-fixture";
- let tool = RetrieveToolOutputTool::new();
- let res = tool.execute(json!({ "hash": hash })).await.unwrap();
- assert!(!res.is_error);
- assert_eq!(res.output(), original);
-}
+use serde_json::json;
+use tinytools::Tool;
#[tokio::test]
async fn missing_hash_is_error() {
- let tool = RetrieveToolOutputTool::new();
- let res = tool
- .execute(json!({ "hash": "deadbeefcafe" }))
- .await
- .unwrap();
- assert!(res.is_error);
+ let tool = retrieve_tool_output_tool();
let res2 = tool.execute(json!({})).await.unwrap();
assert!(res2.is_error);
}
#[tokio::test]
-async fn a_cache_miss_does_not_tell_the_model_to_re_run() {
- // The loop this guards against: a miss that says "re-run the tool" makes
- // the agent regenerate the same oversized result, which is compacted and
- // evicted again — an unbounded compact→retrieve→re-run loop.
- let tool = RetrieveToolOutputTool::new();
- let msg = tool
+async fn an_unreachable_store_is_reported_as_a_tool_error() {
+ let tool = retrieve_tool_output_tool();
+ let res = tool
.execute(json!({ "hash": "deadbeefcafe" }))
.await
- .unwrap()
- .output();
- let lowered = msg.to_lowercase();
- assert!(
- lowered.contains("do not re-run"),
- "a miss must explicitly discourage re-running: {msg}"
- );
- // Scan rather than match one phrase. `!contains("re-run the tool")` both
- // accepts a bare "re-run the same call" elsewhere in the string — which
- // reads to the model as permission, and is the loop this fixes — and
- // rejects the perfectly good "Do not re-run the tool". Every mention of
- // re-running has to be the negated one. Mirrors the assertion in
- // `inference/tokenjuice/tools_tests.rs`.
- let mut cursor = 0;
- while let Some(found) = lowered[cursor..].find("re-run") {
- let at = cursor + found;
- assert!(
- lowered[..at].trim_end().ends_with("do not"),
- "every mention of re-running must be negated, found a bare one at {at}: {msg}"
- );
- cursor = at + "re-run".len();
- }
- assert!(
- msg.contains("compacted summary"),
- "a miss must point the model at the summary it already has: {msg}"
- );
+ .unwrap();
+ assert!(res.is_error);
}
diff --git a/crates/openhuman-core/src/tools/ops.rs b/crates/openhuman-core/src/tools/ops.rs
index 85be1dba19..9953673d8a 100644
--- a/crates/openhuman-core/src/tools/ops.rs
+++ b/crates/openhuman-core/src/tools/ops.rs
@@ -234,7 +234,7 @@ pub fn all_tools_with_runtime(
// Reversibility for native tool-output compaction (Stage 1a): when a
// large result is compacted with a `retrieve_tool_output("<hash>")`
// marker, this hands the original back from the CCR store on demand.
- Box::new(RetrieveToolOutputTool::new()),
+ Box::new(retrieve_tool_output_tool()),
// TokenJuice 2.0 content-router retrieval: fetches the original (full or
// by byte/line range) for a `⟦tj:<hash>⟧` marker from the CCR cache.
// Supersedes `retrieve_tool_output`; both are kept live during migration.