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): own turn-bound summary callbacks in host
Steven Enamakelb2e5d0de0d72
diff --git a/crates/openhuman-core/src/inference/tokenjuice/README.md b/crates/openhuman-core/src/inference/tokenjuice/README.mdindex b0ec0ab209..0eb896c388 100644--- a/crates/openhuman-core/src/inference/tokenjuice/README.md+++ b/crates/openhuman-core/src/inference/tokenjuice/README.md@@ -21,6 +21,7 @@ OpenHuman-owned files:| [`types.rs`](./types.rs) | Re-export of the `tinyjuice-bus` contract (`tinyjuice_bus::types::{AgentTokenjuiceCompression, CompressOptions, CompressedOutput, CompressorKind, ContentHint, ContentKind}` and `tinyjuice_bus::wire::{CacheStats, CompactResponse, InstallRequest, RangeUnit, RetrieveRange}`) under the paths ~40 call sites in this crate already use. || [`schemas.rs`](./schemas.rs) | JSON-RPC controller schemas and handlers. || [`config_patch.rs`](./config_patch.rs) | Partial update shape for the `[tokenjuice]` config block. |+| [`generate.rs`](./generate.rs) | Turn-bound, single-use summary callbacks. The host registers the model call, sends its opaque ticket through the existing contract, and withdraws the callback when the ticket drops. || [`repl_tools.rs`](./repl_tools.rs) | The three REPL tools (`juice_find`, `juice_extract`, `juice_summarize`) over a stored result. TinyJuice owns the ops and declarations (`tinyjuice::repl::tools`, cargo feature `tinytools`); the CCR store lives in the module, so each call fetches the original with `Retrieve` and hands the stock tool a one-entry store. Registered by [`tools/ops.rs`](../../tools/ops.rs) only while `repl_handle_active(config)`. || [`tools.rs`](./tools.rs) | OpenHuman agent tool implementation for the retrieve tool (`RETRIEVE_TOOL_NAME = "juice_retrieve"`; `"tokenjuice_retrieve"` is a recognized recovery-tool alias, not the tool's registered name, see `RECOVERY_TOOL_NAMES`). || `ml/` | Bridge from TinyJuice's optional ML callback into the shared `runtime::python_server` Kompress backend (ModernBERT token/sentence salience); opt-in via `config.tokenjuice.ml_compression_enabled` (default off), degrades gracefully when the flag is off or the runtime server is unavailable. |diff --git a/crates/openhuman-core/src/inference/tokenjuice/generate.rs b/crates/openhuman-core/src/inference/tokenjuice/generate.rsnew file mode 100644index 0000000000..d08f64b0e9--- /dev/null+++ b/crates/openhuman-core/src/inference/tokenjuice/generate.rs@@ -0,0 +1,99 @@+//! OpenHuman's turn-bound callbacks for the TinyJuice module's `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::future::Future;+use std::pin::Pin;+use std::sync::{LazyLock, Mutex};++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) -> Pin<Box<dyn Future<Output = anyhow::Result<String>> + Send>>+ + 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.rsnew file mode 100644index 0000000000..c6e30ba570--- /dev/null+++ b/crates/openhuman-core/src/inference/tokenjuice/generate_tests.rs@@ -0,0 +1,52 @@+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.rsindex a006b91137..710d777a96 100644--- a/crates/openhuman-core/src/inference/tokenjuice/mod.rs+++ b/crates/openhuman-core/src/inference/tokenjuice/mod.rs@@ -1,7 +1,8 @@//! OpenHuman host adapter for the separately released TinyJuice module.pub mod config_patch;-pub use tinyjuice::host::{focus, generate};+pub use tinyjuice::host::focus;+pub mod generate;pub mod ml;pub mod repl_tools;pub mod savings;