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
fix(middleware): use harness-layout segment ids for stable prompt cache
Steven Enamakel3ff1f5e19d60
diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware/prompt_cache.rs b/crates/openhuman-core/src/agent/tinyagents/middleware/prompt_cache.rsindex 3f11a27d4f..6ec41c14df 100644--- a/crates/openhuman-core/src/agent/tinyagents/middleware/prompt_cache.rs+++ b/crates/openhuman-core/src/agent/tinyagents/middleware/prompt_cache.rs@@ -1,6 +1,8 @@//! [`PromptCacheSegmentMiddleware`]: declare the turn's stable prompt prefix-//! (system prompt + tool schemas) as cache segments with content-fingerprint-//! ids, so the crate `PromptCacheGuardMiddleware` has a prefix to protect.+//! (system prompt + tool schemas) as the harness-layout cache segments+//! (`system` / `tools`) with a content-derived request fingerprint, so the+//! crate `PromptCacheGuardMiddleware` has a prefix to protect and the provider+//! prompt-cache routing key stays stable across a thread's turns.use async_trait::async_trait;use sha2::{Digest, Sha256};@@ -33,11 +35,20 @@ fn stable_prefix_fingerprint(value: &serde_json::Value) -> String {/// OpenHuman assembles the request's messages/tools directly rather than through/// the crate prompt builder, so `cache_segments` would otherwise stay empty and/// the crate `PromptCacheGuardMiddleware` (installed immediately after this)-/// would have no prefix to protect. This stamps the segments with-/// **content-fingerprint ids**: an unchanged system prompt + full tool-schema set-/// yields a stable prefix, while an injected timestamp/uuid/etc. or changed tool-/// schema flips it and the guard records a-/// [`CacheLayoutEvent`](tinyagents_harness::cache::CacheLayoutEvent). This is+/// would have no prefix to protect. The segments use the harness-layout ids+/// `system` and `tools` — exactly those, and only those. The crate's+/// `refresh_prompt_cache_fingerprint` (agent_loop/run_loop.rs) recognises that+/// layout at dispatch and rebuilds `prompt_fingerprint` from the bytes actually+/// sent (system messages + tool schemas), so an unchanged system prompt ++/// tool-schema set yields the same fingerprint on every call of a thread, while+/// an injected timestamp/uuid/etc. or a changed tool schema flips it and the+/// guard records a+/// [`CacheLayoutEvent`](tinyagents_harness::cache::CacheLayoutEvent). Any+/// *other* id shape (an earlier version stamped `system:<sha>` / `tools:<sha>`)+/// is treated by the crate as a custom annotation and fingerprinted over the+/// **whole request**, which changed the provider `prompt_cache_key` on every+/// call — OpenRouter uses that key for sticky endpoint routing, so each call+/// re-rolled the endpoint and the per-endpoint prefix cache missed. This is/// the structured, crate-native replacement for the deleted warn-only/// `CacheAlignMiddleware` volatile-token scan (C3): the crate/// `PromptCacheGuardMiddleware` now owns KV-cache-prefix drift detection via@@ -45,6 +56,12 @@ fn stable_prefix_fingerprint(value: &serde_json::Value) -> String {/// `cache_segments` / `prompt_fingerprint`.pub(crate) struct PromptCacheSegmentMiddleware;+/// Segment ids the crate's `refresh_prompt_cache_fingerprint` recognises as its+/// own stable-prefix layout. Any other id opts the request into whole-request+/// fingerprinting (see the middleware docs).+const HARNESS_SYSTEM_SEGMENT_ID: &str = "system";+const HARNESS_TOOLS_SEGMENT_ID: &str = "tools";+#[async_trait]impl Middleware<(), crate::agent::tinyagents::host::OpenHumanRunContext>for PromptCacheSegmentMiddleware@@ -61,17 +78,13 @@ impl Middleware<(), crate::agent::tinyagents::host::OpenHumanRunContext>) -> TaResult<()> {let mut segments: Vec<PromptSegment> = Vec::new();// 1. System prompt — the cache-hottest stable prefix segment.- if let Some(sys) = request+ if request.messages.iter()- .find(|m| matches!(m, TaMessage::System(_)))+ .any(|m| matches!(m, TaMessage::System(_))){- let fp = stable_prefix_fingerprint(&serde_json::json!({- "role": "system",- "messages": [sys],- }));segments.push(PromptSegment {- id: format!("system:{fp}"),+ id: HARNESS_SYSTEM_SEGMENT_ID.to_string(),role: SegmentRole::System,cacheable: true,});@@ -81,19 +94,23 @@ impl Middleware<(), crate::agent::tinyagents::host::OpenHumanRunContext>// tool surface legitimately busts the prefix; an unchanged one keeps// it stable.if !request.tools.is_empty() {- let fp = stable_prefix_fingerprint(&serde_json::json!({- "role": "tools",- "tools": &request.tools,- }));segments.push(PromptSegment {- id: format!("tools:{fp}"),+ id: HARNESS_TOOLS_SEGMENT_ID.to_string(),role: SegmentRole::Tools,cacheable: true,});}if !segments.is_empty() {+ // Content-derived, so a guard reading it before dispatch sees a+ // system-prompt or tool-schema edit; the crate recomputes it from+ // the final bytes at dispatch.+ let system_messages: Vec<&TaMessage> = request+ .messages+ .iter()+ .filter(|m| matches!(m, TaMessage::System(_)))+ .collect();request.prompt_fingerprint = Some(stable_prefix_fingerprint(&serde_json::json!({- "segments": &segments,+ "system": system_messages,"tools": &request.tools,})));tracing::debug!(diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware_tool_output_tests.rs b/crates/openhuman-core/src/agent/tinyagents/middleware_tool_output_tests.rsindex 8a674ec27b..58bde1d904 100644--- a/crates/openhuman-core/src/agent/tinyagents/middleware_tool_output_tests.rs+++ b/crates/openhuman-core/src/agent/tinyagents/middleware_tool_output_tests.rs@@ -179,11 +179,28 @@ async fn prompt_cache_segments_fingerprint_full_tool_schema() {.find(|segment| segment.role == SegmentRole::Tools).expect("tool segment");+ // Segment ids are the harness-layout constants, never content-suffixed:+ // `refresh_prompt_cache_fingerprint` only recognises exactly `system` /+ // `tools`, and any other id is fingerprinted over the whole request, which+ // re-rolls the provider `prompt_cache_key` (OpenRouter's sticky-routing+ // key) on every call.+ assert_eq!(first_tool_segment.id, "tools");+ assert_eq!(second_tool_segment.id, "tools");+ assert!(first.cache_segments.iter().all(|s| s.cacheable));+ assert_eq!(+ first+ .cache_segments+ .iter()+ .find(|s| s.role == SegmentRole::System)+ .expect("system segment")+ .id,+ "system"+ );+ // The content difference is carried by the request fingerprint instead.assert_ne!(- first_tool_segment.id, second_tool_segment.id,+ first.prompt_fingerprint, second.prompt_fingerprint,"same-name tools with different schemas must bust the stable prefix");- assert_ne!(first.prompt_fingerprint, second.prompt_fingerprint);assert_eq!(first.prompt_fingerprint.as_deref().unwrap().len(),64,@@ -191,6 +208,48 @@ async fn prompt_cache_segments_fingerprint_full_tool_schema() {);}+#[tokio::test]+async fn prompt_cache_segments_are_stable_across_a_threads_turns() {+ // The whole point: two calls of one thread — same system prompt, same+ // tools, longer conversation — must declare identical segments and an+ // identical request fingerprint, so the provider routing key derived from+ // them (`tap-<fingerprint>`) does not change turn to turn.+ let mw = PromptCacheSegmentMiddleware;+ let tools = vec![ToolSchema::new(+ "lookup",+ "lookup a user",+ json!({ "type": "object", "properties": { "id": { "type": "string" } } }),+ )];+ let mut turn_one = ModelRequest::new(vec![TaMessage::system("sys"), TaMessage::user("hi")])+ .with_tools(tools.clone());+ let mut turn_two = ModelRequest::new(vec![+ TaMessage::system("sys"),+ TaMessage::user("hi"),+ TaMessage::assistant("hello"),+ TaMessage::user("and again, later"),+ ])+ .with_tools(tools);+ mw.before_model(&mut ctx(), &(), &mut turn_one).await.unwrap();+ mw.before_model(&mut ctx(), &(), &mut turn_two).await.unwrap();++ let ids = |r: &ModelRequest| {+ r.cache_segments+ .iter()+ .map(|s| (s.id.clone(), s.role, s.cacheable))+ .collect::<Vec<_>>()+ };+ assert_eq!(ids(&turn_one), ids(&turn_two));+ assert_eq!(+ ids(&turn_one),+ vec![+ ("system".to_string(), SegmentRole::System, true),+ ("tools".to_string(), SegmentRole::Tools, true),+ ]+ );+ assert_eq!(turn_one.prompt_fingerprint, turn_two.prompt_fingerprint);+ assert!(turn_one.prompt_fingerprint.is_some());+}+#[tokio::test]async fn raw_security_policy_block_is_enriched_with_workaround_and_relay() {let mw = outcome_capture_mw();