Skip to content

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

chore: files changed crates/openhuman-core/src/agent/tinyagents/README.md,crates/openhuman-core/src/

Steven Enamakelf2a0d6498abf
diff --git a/crates/openhuman-core/src/agent/tinyagents/README.md b/crates/openhuman-core/src/agent/tinyagents/README.md
index dc6319f749..291243da74 100644
--- a/crates/openhuman-core/src/agent/tinyagents/README.md
+++ b/crates/openhuman-core/src/agent/tinyagents/README.md
@@ -32,7 +32,7 @@ The adapter seam between OpenHuman and the vendored [`tinyagents`](../../../../.
| `replay/` | Read-only agent-run replay/status RPC (`mod.rs`, `ops.rs`, `schemas.rs`): three `agent`-namespace controllers; `ops.rs` is a workspace adapter over `tinyagents_harness::observability::replay`. |
| `journal.rs` | `TurnJournal` and `attach_turn_journal`: a crate `StoreEventJournal` over a JSONL append store plus a `HarnessStatusStore` writer (`FileStatusStore`, `mint_run_id` and the env-secret redaction seed are upstream in `tinyagents_harness::observability`) under `{workspace}/tinyagents_store`. Attached alongside the live `observability` bridge as an independent `EventSink` subscriber, wrapped in `RedactingSink`; best-effort and non-fatal. |
| `reaper.rs` | `reap_orphaned_runs`: workspace adapter over the upstream sweep (`tinyagents_harness::observability::reap_orphaned_runs`) that marks non-terminal runs `Cancelled` in the durable status store. The only writer over the status seam that `replay/` reads. |
-| [`middleware.rs`](./middleware.rs) + `middleware/` | The named OpenHuman middleware stack. `turn_context.rs`: `TurnContextMiddleware` (bundles config and installs the enabled hooks), `TranscriptSnapshotMiddleware`/`TranscriptSnapshotSink`. `tool_output.rs`: `ToolOutputMiddleware` (per-result byte cap and optional payload summarizer). `approval.rs`: `ApprovalSecurityMiddleware`. `cli_rpc_only.rs`: `CliRpcOnlyMiddleware`. `tool_policy.rs`: the `ToolPolicyMiddleware` struct and impl (records blocks into `crate::tools::registry::denials`). `tool_outcome_capture.rs`: `ToolOutcomeCaptureMiddleware`. `embedder_hooks.rs`: `EmbedderToolHooksMiddleware`. `memory_protocol.rs`: the OpenHuman tool vocabulary (`memory_protocol_spec()`) for the upstream `MemoryProtocolMiddleware`. `cost_budget.rs`: `CostBudgetMiddleware`. `repeated_failure.rs`: `RepeatedToolFailureMiddleware` (class-specific recovery budgets before the next model call; equivalent failures share a stable resource scope even when arguments differ). `loop_guards.rs`: `TerminalInferenceFailure`. `credential_scrub.rs`: the browser confirmation-token exemption and `credential_scrub_middleware()`, which wires the harness `CredentialScrubMiddleware`. The generic context-ladder and loop-guard middleware live in `tinyagents-harness` (`middleware::library`) and are installed by [`harness_context_ladder.rs`](./harness_context_ladder.rs) / `harness_assembly.rs`: `ImageAwareMessageTrimMiddleware`, `FinalCallWrapUpMiddleware` (host passes the `file_write`/`apply_patch` deliverable tools and `CLEARED_PLACEHOLDER`), `ArtifactIndexTocMiddleware` (issue #6014), `RepeatProgressMiddleware`/`RepeatEvictionObserver` (host passes the `wait_subagent` exemption), and `ArgRecoveryMiddleware`. |
+| [`middleware.rs`](./middleware.rs) + `middleware/` | The named OpenHuman middleware stack. `turn_context.rs`: `TurnContextMiddleware` (bundles config and installs the enabled hooks), `TranscriptSnapshotMiddleware`/`TranscriptSnapshotSink`. `tool_output.rs`: `ToolOutputMiddleware` (per-result byte cap and optional payload summarizer). `approval.rs`: `ApprovalSecurityMiddleware`. `cli_rpc_only.rs`: `CliRpcOnlyMiddleware`. `tool_policy.rs`: the `ToolPolicyMiddleware` struct and impl (records blocks into `crate::tools::registry::denials`). `tool_outcome_capture.rs`: `ToolOutcomeCaptureMiddleware`. `embedder_hooks.rs`: `EmbedderToolHooksMiddleware`. `memory_protocol.rs`: the OpenHuman tool vocabulary (`memory_protocol_spec()`) for the upstream `MemoryProtocolMiddleware`. `cost_budget.rs`: `CostBudgetMiddleware`. `repeated_failure.rs`: `RepeatedToolFailureMiddleware` (class-specific recovery budgets before the next model call; equivalent failures share a stable resource scope even when arguments differ). `loop_guards.rs`: `TerminalInferenceFailure`. `credential_scrub.rs`: the browser confirmation-token exemption and `credential_scrub_middleware()`, which wires the harness `CredentialScrubMiddleware`. The generic context-ladder and loop-guard middleware live in `tinyagents-harness` (`middleware::library`) and are installed by [`context_wiring.rs`](./context_wiring.rs) / `harness_assembly.rs`: `ImageAwareMessageTrimMiddleware`, `FinalCallWrapUpMiddleware` (host passes the `file_write`/`apply_patch` deliverable tools and `CLEARED_PLACEHOLDER`), `ArtifactIndexTocMiddleware` (issue #6014), `RepeatProgressMiddleware`/`RepeatEvictionObserver` (host passes the `wait_subagent` exemption), and `ArgRecoveryMiddleware`. |
| [`middleware/research_budget.rs`](./middleware/research_budget.rs) | Withdraws the web tools from a top-level turn after eight successful search or fetch calls (forcing an answer only when no other tool remains), and notes once when consecutive web calls fail. |
| `model.rs` | Helpers and wrappers over native crate `ChatModel` values: message/response translation, usage merging, stream-delta forwarding, `MaxTokensModel`, `ProfileOverrideModel`. |
| [`tools.rs`](./tools.rs) | `CanonicalSharedToolAdapter`: resolves an OpenHuman shared tool registry and forwards the canonical `tinytools::Tool` contract; `EarlyExitHook` pauses successful `ask_user_clarification`-style calls. |
diff --git a/crates/openhuman-core/src/agent/tinyagents/context_wiring.rs b/crates/openhuman-core/src/agent/tinyagents/context_wiring.rs
new file mode 100644
index 0000000000..39a6d37104
--- /dev/null
+++ b/crates/openhuman-core/src/agent/tinyagents/context_wiring.rs
@@ -0,0 +1,166 @@
+//! Host wiring for the context ladder. The ladder's order and sizing rules live
+//! in `tinyagents_harness::middleware::ContextLadder`; this file supplies only
+//! what the host owns: the summarizer behind compression (task-state or free
+//! form, with memory recall), the wrap-up prompts and deliverable tools, and
+//! the outcome sink the wrap-up restores from.
+
+use std::sync::Arc;
+
+use tinyagents_harness::middleware::{
+ compression_policy, legacy_max_input_tokens, microcompact_for_window, split_input_allowance,
+ ArtifactIndexTocMiddleware, CapturedOutcomes, ContextCompressionMiddleware, ContextLadder,
+ FinalCallWrapUpMiddleware, ImageAwareMessageTrimMiddleware, OutcomesUnavailable,
+};
+use tinyagents_harness::runtime::AgentHarness;
+use tinyagents_harness::summarization::{
+ FaultTolerantCachingSummarizer, ModelSummarizer, SummarizationPolicy, TaskStateSummarizer,
+ DEFAULT_TASK_STATE_CHUNK_TOKENS,
+};
+
+use crate::agent::tinyagents::host::OpenHumanRunContext;
+use crate::agent::tinyagents::memory_summarizer::MemoryRecallSummarizer;
+use crate::agent::tinyagents::model::TurnChatModel;
+use crate::agent::tinyagents::turn_outcome::ToolOutcomeSink;
+
+/// Fractions of a capped turn's model-call budget at which the model is told
+/// how many calls are left.
+const BUDGET_NOTICE_THRESHOLDS: [f64; 2] = [0.5, 0.8];
+/// Longest verbatim tail of a task-state compaction (tokens).
+const TASK_STATE_KEEP_RECENT_TOKENS: u64 = 20_000;
+/// Store the artifact index is registered under on the run context.
+const ARTIFACT_INDEX_STORE: &str =
+ crate::agent::harness::tool_result_artifacts::TINYAGENTS_TOOL_RESULT_ARTIFACT_STORE;
+
+/// Read side of the tool-outcome capture sink, for the wrap-up's restoration.
+pub(super) struct OutcomeSinkSource(pub(super) ToolOutcomeSink);
+
+impl CapturedOutcomes for OutcomeSinkSource {
+ fn content_for(&self, call_id: &str) -> Result<Option<String>, OutcomesUnavailable> {
+ let outcomes = self.0.lock().map_err(|_| OutcomesUnavailable)?;
+ Ok(outcomes
+ .iter()
+ .find(|o| o.call_id == call_id)
+ .map(|o| o.content.clone()))
+ }
+}
+
+/// Install the ladder; returns the compression and wrap-up handles the run loop
+/// reads after the drive future returns. `wrap_up_at_cap` is true only for a
+/// top-level turn that pauses at its model-call cap.
+#[allow(clippy::too_many_arguments)]
+pub(super) fn install_context_ladder(
+ harness: &mut AgentHarness<(), OpenHumanRunContext>,
+ model: &str,
+ context_window: Option<u64>,
+ autocompact_enabled: bool,
+ compaction_trigger_tokens: Option<u64>,
+ compaction_strategy: crate::config::CompactionStrategy,
+ microcompact_keep_recent: usize,
+ summarizer_model: TurnChatModel,
+ wrap_up_at_cap: bool,
+ tool_outcome_sink: &ToolOutcomeSink,
+ memory_turn: Option<Arc<crate::memory::lifecycle::hooks::MemoryTurn>>,
+) -> (
+ Option<Arc<ContextCompressionMiddleware>>,
+ Option<Arc<FinalCallWrapUpMiddleware>>,
+) {
+ let window = context_window.filter(|w| *w > 0);
+ let compression = autocompact_enabled
+ .then(|| compression_policy(context_window, compaction_trigger_tokens))
+ .flatten()
+ .map(|policy| {
+ Arc::new(compression_middleware(
+ policy,
+ compaction_strategy,
+ context_window,
+ summarizer_model,
+ model,
+ memory_turn,
+ ))
+ });
+ // One allowance split between the contents list and wrap-up restoration.
+ let trim_allowance = window
+ .map(|w| legacy_max_input_tokens(w).max(1))
+ .unwrap_or(0);
+ let (toc_allowance, restore_allowance) = split_input_allowance(trim_allowance);
+ let wrap_up = wrap_up_at_cap.then(|| {
+ Arc::new(
+ FinalCallWrapUpMiddleware::new(
+ crate::agent::session_host::turn_checkpoint::MAX_ITER_CHECKPOINT_INSTRUCTION,
+ crate::agent::session_host::turn_checkpoint::FINAL_WRITE_INSTRUCTION,
+ Arc::new(OutcomeSinkSource(tool_outcome_sink.clone())),
+ restore_allowance,
+ )
+ .with_deliverable_tools(["file_write", "apply_patch"])
+ .with_cleared_placeholder(crate::agent::context::CLEARED_PLACEHOLDER)
+ .with_budget_notice(BUDGET_NOTICE_THRESHOLDS),
+ )
+ });
+ ContextLadder {
+ compression,
+ microcompact: (microcompact_keep_recent > 0).then(|| {
+ microcompact_for_window(
+ microcompact_keep_recent,
+ crate::agent::context::CLEARED_PLACEHOLDER,
+ context_window,
+ )
+ }),
+ wrap_up,
+ artifact_toc: Some(ArtifactIndexTocMiddleware::new(
+ toc_allowance,
+ ARTIFACT_INDEX_STORE,
+ )),
+ trim: window.map(ImageAwareMessageTrimMiddleware::for_context_window),
+ }
+ .install(harness)
+}
+
+/// The compression middleware for `strategy`: `TaskState` writes a typed
+/// checkpoint over a token-budgeted tail, `Summary` is the free-form summarizer.
+fn compression_middleware(
+ policy: SummarizationPolicy,
+ strategy: crate::config::CompactionStrategy,
+ context_window: Option<u64>,
+ summarizer_model: TurnChatModel,
+ model: &str,
+ memory_turn: Option<Arc<crate::memory::lifecycle::hooks::MemoryTurn>>,
+) -> ContextCompressionMiddleware {
+ let window = context_window.filter(|w| *w > 0);
+ match strategy {
+ crate::config::CompactionStrategy::TaskState => {
+ let keep_recent = window.map_or(TASK_STATE_KEEP_RECENT_TOKENS, |w| {
+ (w / 5).min(TASK_STATE_KEEP_RECENT_TOKENS)
+ });
+ let chunk = window.map_or(DEFAULT_TASK_STATE_CHUNK_TOKENS, |w| {
+ (w * 2 / 5).clamp(4_000, DEFAULT_TASK_STATE_CHUNK_TOKENS)
+ });
+ tracing::info!(model, keep_recent_tokens = keep_recent, max_chunk_tokens = chunk, context_window = ?window, "[context_compression] strategy=task_state");
+ let summarizer = FaultTolerantCachingSummarizer::new(
+ Box::new(
+ TaskStateSummarizer::new(summarizer_model, model).with_max_chunk_tokens(chunk),
+ ),
+ &policy,
+ );
+ ContextCompressionMiddleware::with_summarizer(
+ policy,
+ MemoryRecallSummarizer::wrap(Box::new(summarizer), memory_turn),
+ )
+ .with_keep_recent_tokens(keep_recent)
+ }
+ crate::config::CompactionStrategy::Summary => {
+ tracing::info!(model, "[context_compression] strategy=summary");
+ let summarizer = FaultTolerantCachingSummarizer::new(
+ Box::new(ModelSummarizer::new(summarizer_model, model)),
+ &policy,
+ );
+ ContextCompressionMiddleware::with_summarizer(
+ policy,
+ MemoryRecallSummarizer::wrap(Box::new(summarizer), memory_turn),
+ )
+ }
+ }
+}
+
+#[cfg(test)]
+#[path = "context_wiring_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-core/src/agent/tinyagents/context_wiring_tests.rs b/crates/openhuman-core/src/agent/tinyagents/context_wiring_tests.rs
new file mode 100644
index 0000000000..4212d515e1
--- /dev/null
+++ b/crates/openhuman-core/src/agent/tinyagents/context_wiring_tests.rs
@@ -0,0 +1,20 @@
+use super::*;
+use crate::agent::tinyagents::turn_outcome::ToolCallOutcome;
+
+#[test]
+fn outcome_source_returns_captured_content_by_call_id() {
+ let sink: ToolOutcomeSink = Default::default();
+ let source = OutcomeSinkSource(sink.clone());
+ assert!(source.content_for("missing").unwrap().is_none());
+ sink.lock().unwrap().push(ToolCallOutcome {
+ call_id: "c1".into(),
+ content: "body".into(),
+ ..Default::default()
+ });
+ assert_eq!(source.content_for("c1").unwrap().as_deref(), Some("body"));
+}
+
+#[test]
+fn budget_notice_thresholds_stay_at_half_and_eighty_percent() {
+ assert_eq!(BUDGET_NOTICE_THRESHOLDS, [0.5, 0.8]);
+}
diff --git a/crates/openhuman-core/src/agent/tinyagents/harness_assembly.rs b/crates/openhuman-core/src/agent/tinyagents/harness_assembly.rs
index 40b45d6019..6157478ec4 100644
--- a/crates/openhuman-core/src/agent/tinyagents/harness_assembly.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/harness_assembly.rs
@@ -17,7 +17,7 @@ use tinyinference_llm::model::CapabilitySet;
use tokio::sync::mpsc::Sender;
use crate::agent::progress::AgentProgress;
-use crate::agent::tinyagents::harness_context_ladder::install_context_ladder;
+use crate::agent::tinyagents::context_wiring::install_context_ladder;
use crate::agent::tinyagents::harness_tool_registration::register_turn_tools_and_agents;
use crate::agent::tinyagents::host::steering;
use crate::agent::tinyagents::host::OpenHumanRunContext;
@@ -508,7 +508,7 @@ pub(super) fn assemble_turn_harness(
)));
// The context ladder (compression, microcompact, final-call wrap-up,
// artifact contents list, trim), registered here so each step keeps its
- // place in the middleware order. See `harness_context_ladder.rs`.
+ // place in the middleware order. See `context_wiring.rs`.
let (compression_mw, wrap_up_fired) = install_context_ladder(
&mut harness,
model,
diff --git a/crates/openhuman-core/src/agent/tinyagents/harness_context_ladder.rs b/crates/openhuman-core/src/agent/tinyagents/harness_context_ladder.rs
deleted file mode 100644
index 22788af04d..0000000000
--- a/crates/openhuman-core/src/agent/tinyagents/harness_context_ladder.rs
+++ /dev/null
@@ -1,419 +0,0 @@
-//! The context ladder for
-//! [`assemble_turn_harness`](super::harness_assembly::assemble_turn_harness):
-//! register the reduction steps that keep a turn's request inside the model's
-//! context window (compression, microcompact, the final-call wrap-up, the
-//! offloaded-artifact contents list and the trim) in the order they must fire.
-//!
-//! Split out of `harness_assembly.rs` unchanged, so the assembly stays under the
-//! 750-line Rust layout limit. The call site sits at the same point in the
-//! registration sequence, so every middleware keeps its position.
-
-use std::sync::Arc;
-
-use tinyagents_harness::middleware::{
- legacy_max_input_tokens, split_input_allowance, ArtifactIndexTocMiddleware, CapturedOutcomes,
- ContextCompressionMiddleware, FinalCallWrapUpMiddleware, ImageAwareMessageTrimMiddleware,
- OutcomesUnavailable,
-};
-use tinyagents_harness::runtime::AgentHarness;
-
-use crate::agent::tinyagents::host::OpenHumanRunContext;
-use crate::agent::tinyagents::model::TurnChatModel;
-use crate::agent::tinyagents::turn_outcome::ToolOutcomeSink;
-
-/// Window assumed for sizing microcompact when the model's context window is
-/// unknown (not in any static table, no `context_length` from `/v1/models`).
-/// Deliberately conservative: small enough that a runaway transcript is still
-/// blanked well before any real model overflows, large enough that a short run
-/// stays append-only and prompt-cache eligible. Used only for microcompact;
-/// compression and trim still treat an unknown window as "nothing to size
-/// against", and known-window behaviour is unchanged.
-pub(super) const UNKNOWN_WINDOW_FALLBACK_TOKENS: u64 = 64_000;
-
-/// Fractions of a capped turn's model-call budget at which the model is told
-/// how many calls are left (#6958; `FinalCallWrapUpMiddleware::with_budget_notice`).
-const BUDGET_NOTICE_THRESHOLDS: [f64; 2] = [0.5, 0.8];
-
-/// Store `ToolResultArtifactIndexStore` is registered under on the run context.
-const ARTIFACT_INDEX_STORE: &str =
- crate::agent::harness::tool_result_artifacts::TINYAGENTS_TOOL_RESULT_ARTIFACT_STORE;
-
-/// Read side of the tool-outcome capture sink, for the wrap-up's restoration.
-struct OutcomeSinkSource(ToolOutcomeSink);
-
-impl CapturedOutcomes for OutcomeSinkSource {
- fn content_for(&self, call_id: &str) -> Result<Option<String>, OutcomesUnavailable> {
- let outcomes = self.0.lock().map_err(|_| OutcomesUnavailable)?;
- Ok(outcomes
- .iter()
- .find(|outcome| outcome.call_id == call_id)
- .map(|outcome| outcome.content.clone()))
- }
-}
-
-/// Push the context ladder onto `harness` and return the two handles the run
-/// loop reads after the drive future returns: the installed compression
-/// middleware (to drain its provenance records), and the wrap-up middleware's
-/// fired flag. Each is `None` when that step is not installed.
-///
-/// `wrap_up_at_cap` is true only for a top-level turn that pauses at its
-/// model-call cap; see the wrap-up comment below for why sub-agents and
-/// erroring runs are excluded.
-#[allow(clippy::too_many_arguments)]
-pub(super) fn install_context_ladder(
- harness: &mut AgentHarness<(), OpenHumanRunContext>,
- model: &str,
- context_window: Option<u64>,
- autocompact_enabled: bool,
- compaction_trigger_tokens: Option<u64>,
- compaction_strategy: crate::config::CompactionStrategy,
- microcompact_keep_recent: usize,
- summarizer_model: TurnChatModel,
- wrap_up_at_cap: bool,
- tool_outcome_sink: &ToolOutcomeSink,
- memory_turn: Option<Arc<crate::memory::lifecycle::hooks::MemoryTurn>>,
-) -> (
- Option<Arc<ContextCompressionMiddleware>>,
- Option<Arc<FinalCallWrapUpMiddleware>>,
-) {
- // Autocompaction parity: when the provider's context window is known, install
- // the two-stage context-management step (issue #4249).
- //
- // 1. `ContextCompressionMiddleware` — the **summarization** step. Once the
- // running token estimate crosses `window * SUMMARIZE_THRESHOLD_FRACTION`
- // (min(80% of *this model's* context window, 350k tokens), or the absolute
- // `compaction_trigger_tokens` override), it folds the older slice of the
- // transcript into a single LLM-generated, user-role checkpoint (keeping
- // system messages + the recent window verbatim). This is keyed to whatever model
- // the turn is running on, preserving the legacy context threshold.
- // 2. `ImageAwareMessageTrimMiddleware` — a deterministic, no-extra-LLM-call
- // hard cap (issue #4462; replaces the crate `MessageTrimMiddleware`).
- // Pushed **after** compression (so `before_model` runs compression first),
- // it front-trims to the legacy proportional budget only as a last resort
- // when even the summary + recent window still overflow — image markers
- // priced flat, system messages never dropped, evictions logged.
- //
- // The LLM summarization step honors the `[context].enabled` /
- // `autocompact_enabled` opt-outs (a disabled config must not spend summarizer
- // tokens or rewrite history); the deterministic trim backstop always installs
- // when a window is known, matching the legacy always-on `trim_history` cap.
- // Concrete handle to the compression middleware (when installed), retained so
- // the run loop can drain its `records()` after the drive future returns and
- // surface each compaction's provenance (source ids + before/after token
- // estimates) — the `AgentEvent::Compressed` projection only carries the token
- // deltas, so provenance would otherwise be dropped (issue #4249, 03.1 item 6).
- let mut compression_mw: Option<Arc<ContextCompressionMiddleware>> = None;
- let compression_policy = compression_policy(context_window, compaction_trigger_tokens);
- if autocompact_enabled {
- if let Some(policy) = compression_policy {
- // Wrap the LLM-backed summarizer in a fault-tolerant, per-turn-caching
- // adapter (issue #4461): a summarizer failure must no longer abort the
- // turn (warn + circuit-breaker + deterministic trim instead), and an
- // identical re-issued input slice must not re-run the summarizer LLM.
- // The summary is a user-role, reference-only checkpoint
- // (`SummaryPlacement::User`, the crate default): the system prompt
- // and tool declarations stay byte-stable across a compaction.
- let mw = Arc::new(compression_middleware(
- policy,
- compaction_strategy,
- context_window,
- summarizer_model,
- model,
- memory_turn,
- ));
- // Lifecycle `before_model` runs the threshold compaction; the
- // model wrap runs the provider-overflow → compact → retry-once
- // recovery. One instance in both places shares one per-run fold,
- // so the overflow path extends the threshold path's compaction
- // instead of compacting from scratch, and a request the threshold
- // path already compacted is not compacted again on the way in.
- harness.push_middleware(mw.clone());
- harness.push_model_middleware(mw.clone());
- compression_mw = Some(mw);
- }
- }
- // Deterministic hard-cap trim (issue #4462). The crate
- // `MessageTrimMiddleware` regressed three legacy `token_budget.rs`
- // guards: it priced a base64 image at ~2M tokens (chars/4) and could
- // evict system messages, it reordered system messages to the front, and
- // its budget was the fixed `window − AGENT_TURN_MAX_OUTPUT_TOKENS`
- // (floored 1024) that collapses an 8k local model's input budget from
- // ~7373 to 1024. Our seam-owned `ImageAwareMessageTrimMiddleware`
- // restores all three: image markers priced at a flat cost, the
- // proportional reply reserve, system messages always kept in place, and a
- // grep-able warn with drop/token counts on any eviction.
-
- // ── The context ladder, cheapest sufficient step first (issue #6014) ──────
- //
- // `before_model` runs in registration order, so what follows IS the firing
- // order, and each step only matters when the one above was not enough:
- // 1. compression (above) folds the older slice into a task-aware summary;
- // 2. microcompact blanks older tool bodies if still over;
- // 3. the wrap-up undoes (2) for a capped turn's concluding call;
- // 4. trim evicts oldest whole messages if still over.
- //
- // The order used to be 2 -> 1 -> 4, because `context_mw.install` registered
- // microcompact: the summarizer was handed a transcript whose tool bodies
- // were already `CLEARED_PLACEHOLDER` and asked, by its own prompt, for "key
- // results/outputs" it could no longer see. Nothing recovered them.
- if microcompact_keep_recent > 0 {
- // The token-budget gate the crate added for this (#4755) and this call
- // site never used. Constructed bare, microcompact blanks on EVERY call
- // past `keep_recent` — not only under pressure — so a ten-call turn
- // answered from the last five results while well inside a window with
- // room for all ten. Not a capped-turn problem: every turn. The budget
- // matches the trim's allowance, putting microcompact strictly behind
- // compression. See `microcompact_middleware` for the unknown-window case.
- let microcompact = microcompact_middleware(microcompact_keep_recent, context_window);
- // Emit `AgentEvent::Compressed` when a body is cleared. Off by default —
- // the middleware was built as "a silent transcript rewrite" — which is
- // why blanking was, until now, the one reduction step nobody could see
- // happening: compression logs its provenance, the trim warns on every
- // eviction, and the per-result artifact store logs each persist. Only
- // this one destroyed content without saying so, which is how it went
- // unnoticed that it was doing it on every call.
- harness.push_middleware(Arc::new(microcompact.with_events(true)));
- }
-
- // Issue #6014: make the last permitted model call the turn's conclusion,
- // rather than leaving the answer to an extra out-of-band call after the loop
- // has exited.
- //
- // **Top-level turns only**, the same cut `CapPauser`'s dispatch guard takes.
- // A sub-agent reaching its own cap is a routine outcome, not a user-visible
- // dead end: it summarises, hands the result back to its parent, and
- // `subagent_host` already owns that checkpoint. The harm this fixes — a
- // person left with a status line where an answer should be — belongs to the
- // turn that answers a human. It also leaves a child's budget alone: the
- // conclusion costs a call, and turning every delegated run's N tool rounds
- // into N-1 is not a trade to impose as a side effect.
- // One allowance, split between the two things that add to the request
- // (CodeRabbit on #6068). Computed independently they were each bounded and
- // the pair was not: restoration could fill the whole allowance and the
- // contents list add its tenth on top. `0` when no window is advertised.
- let trim_allowance = context_window
- .filter(|w| *w > 0)
- .map(|w| legacy_max_input_tokens(w).max(1))
- .unwrap_or(0);
- let (toc_allowance, restore_allowance) = split_input_allowance(trim_allowance);
-
- let wrap_up_mw = wrap_up_at_cap.then(|| {
- Arc::new(
- FinalCallWrapUpMiddleware::new(
- crate::agent::session_host::turn_checkpoint::MAX_ITER_CHECKPOINT_INSTRUCTION,
- crate::agent::session_host::turn_checkpoint::FINAL_WRITE_INSTRUCTION,
- Arc::new(OutcomeSinkSource(tool_outcome_sink.clone())),
- // What is left after the contents list's share, so restoration
- // stops short of provoking an eviction (see the middleware).
- restore_allowance,
- )
- // The call before the conclusion keeps only the tools that can
- // persist a deliverable (`file_write` is the only create-capable
- // file tool; `apply_patch` has a create mode). `shell` is left out
- // on purpose: it can equally run a crawler.
- .with_deliverable_tools(["file_write", "apply_patch"])
- .with_cleared_placeholder(crate::agent::context::CLEARED_PLACEHOLDER)
- // #6958: the model first heard about its budget on the
- // penultimate call, too late for a multi-file change. Say how many
- // calls are left at half and at 80% of the budget.
- .with_budget_notice(BUDGET_NOTICE_THRESHOLDS),
- )
- });
- let wrap_up_fired = wrap_up_mw.clone();
- if let Some(mw) = wrap_up_mw {
- harness.push_middleware(mw);
- }
-
- // Issue #6014: say where the offloaded results went, from the index rather
- // than the transcript. After the reduction steps so it renders what
- // survived them, before the trim so its message is counted in that budget.
- // Its share of the allowance split above: the list is a system message, so
- // nothing downstream can shrink it (see the middleware).
- harness.push_middleware(Arc::new(ArtifactIndexTocMiddleware::new(
- toc_allowance,
- ARTIFACT_INDEX_STORE,
- )));
-
- if let Some(window) = context_window.filter(|w| *w > 0) {
- // Deterministic hard-cap trim (issue #4462), last in the ladder: it drops
- // whole messages, so it runs only once summarizing and blanking have both
- // failed to fit the window. See `ImageAwareMessageTrimMiddleware` for the
- // three legacy guards it restores over the crate trim.
- harness.push_middleware(Arc::new(
- ImageAwareMessageTrimMiddleware::for_context_window(window),
- ));
- }
-
- (compression_mw, wrap_up_fired)
-}
-
-/// Longest verbatim tail kept by a task-state compaction (tokens). Measured
-/// default for large-window coding agents; small windows keep a fifth of
-/// the window instead.
-const TASK_STATE_KEEP_RECENT_TOKENS: u64 = 20_000;
-
-/// The compression middleware for `strategy`.
-///
-/// `TaskState` (the default) writes a typed task-state checkpoint
-/// (`TaskStateSummarizer`) over a token-budgeted tail: `min(20k, window/5)`
-/// recent tokens verbatim, and history folded in chunks of at most 40% of the
-/// window so a small model never sees more than it can read. `Summary` is the
-/// free-form `ModelSummarizer` over the policy's last `keep_last` messages.
-pub(super) fn compression_middleware(
- policy: tinyagents_harness::summarization::SummarizationPolicy,
- strategy: crate::config::CompactionStrategy,
- context_window: Option<u64>,
- summarizer_model: TurnChatModel,
- model: &str,
- memory_turn: Option<Arc<crate::memory::lifecycle::hooks::MemoryTurn>>,
-) -> ContextCompressionMiddleware {
- use tinyagents_harness::summarization::{
- FaultTolerantCachingSummarizer, ModelSummarizer, TaskStateSummarizer,
- DEFAULT_TASK_STATE_CHUNK_TOKENS,
- };
- let window = context_window.filter(|w| *w > 0);
- match strategy {
- crate::config::CompactionStrategy::TaskState => {
- let keep_recent = window.map_or(TASK_STATE_KEEP_RECENT_TOKENS, |w| {
- (w / 5).min(TASK_STATE_KEEP_RECENT_TOKENS)
- });
- let chunk = window.map_or(DEFAULT_TASK_STATE_CHUNK_TOKENS, |w| {
- (w * 2 / 5).clamp(4_000, DEFAULT_TASK_STATE_CHUNK_TOKENS)
- });
- tracing::info!(
- model,
- keep_recent_tokens = keep_recent,
- max_chunk_tokens = chunk,
- context_window = ?window,
- "[context_compression] strategy=task_state"
- );
- let summarizer = FaultTolerantCachingSummarizer::new(
- Box::new(
- TaskStateSummarizer::new(summarizer_model, model).with_max_chunk_tokens(chunk),
- ),
- &policy,
- );
- ContextCompressionMiddleware::with_summarizer(
- policy,
- super::memory_summarizer::MemoryRecallSummarizer::wrap(
- Box::new(summarizer),
- memory_turn,
- ),
- )
- .with_keep_recent_tokens(keep_recent)
- }
- crate::config::CompactionStrategy::Summary => {
- tracing::info!(model, "[context_compression] strategy=summary");
- let summarizer = FaultTolerantCachingSummarizer::new(
- Box::new(ModelSummarizer::new(summarizer_model, model)),
- &policy,
- );
- ContextCompressionMiddleware::with_summarizer(
- policy,
- super::memory_summarizer::MemoryRecallSummarizer::wrap(
- Box::new(summarizer),
- memory_turn,
- ),
- )
- }
- }
-}
-
-/// The summarization policy for this turn, or `None` when compaction has
-/// nothing to size against.
-///
-/// Normally `min(80% of the model's context window, 350k tokens)` (TinyAgents
-/// `summarization_policy`). `trigger_override` (the
-/// `[context].compaction_trigger_tokens` / `OPENHUMAN_COMPACTION_TRIGGER_TOKENS`
-/// bench knob) pins the trigger to that absolute token count instead, and
-/// enables compaction even when the window is unknown.
-pub(super) fn compression_policy(
- context_window: Option<u64>,
- trigger_override: Option<u64>,
-) -> Option<tinyagents_harness::summarization::SummarizationPolicy> {
- use tinyagents_harness::summarization::{
- summarization_policy, SummarizationPolicy, DEFAULT_SUMMARIZE_KEEP_LAST,
- };
- let window = context_window.filter(|w| *w > 0);
- match trigger_override.filter(|t| *t > 0) {
- Some(tokens) => {
- tracing::info!(
- trigger_tokens = tokens,
- context_window = ?window,
- "[context_compression] compaction trigger override active"
- );
- let base = window
- .map(summarization_policy)
- .unwrap_or(SummarizationPolicy {
- keep_last: DEFAULT_SUMMARIZE_KEEP_LAST,
- ..SummarizationPolicy::default()
- });
- Some(base.with_trigger_override(tokens))
- }
- None => window.map(summarization_policy),
- }
- .map(|policy| with_turn_aware_tail(policy, window))
-}
-
-/// Build the microcompact step of the context ladder.
-///
-/// With a known window the token budget is the trim's allowance
-/// (`legacy_max_input_tokens(window)`). Without one, the budget is sized
-/// against [`UNKNOWN_WINDOW_FALLBACK_TOKENS`] instead of being left unset:
-/// a bare microcompact blanks every tool result older than `keep_recent` on
-/// every turn, and each blanking rewrites an already-sent prefix position, so
-/// the provider's prompt (KV) cache misses from that point on. Observed on a
-/// router whose model id had no static window: 77 of 80 turns emitted
-/// `compressed` events, only 48-67% of input tokens were cached (99% when the
-/// same prompts were sent append-only) and cold calls took ~6-7 s vs ~3 s
-/// warm. The finite fallback keeps a short run append-only while still
-/// blanking once the transcript outgrows it, so growth stays bounded.
-pub(super) fn microcompact_middleware(
- keep_recent: usize,
- context_window: Option<u64>,
-) -> tinyagents_harness::middleware::MicrocompactMiddleware {
- let window = context_window
- .filter(|w| *w > 0)
- .unwrap_or(UNKNOWN_WINDOW_FALLBACK_TOKENS);
- tinyagents_harness::middleware::MicrocompactMiddleware::new(
- keep_recent,
- crate::agent::context::CLEARED_PLACEHOLDER,
- )
- .with_token_budget(legacy_max_input_tokens(window).max(1))
-}
-
-/// Share of the context window a compaction keeps verbatim as its tail.
-const COMPACTION_TAIL_WINDOW_FRACTION: f64 = 0.30;
-
-/// Size the kept tail in tokens and pin the turn's user message (#6960).
-///
-/// Split by count (the last eight messages), a long tool-driven turn that
-/// crosses the trigger mid-turn folds its only user message — the assignment
-/// being worked on — into the summary, and the agent loses the task. This
-/// keeps ~30% of the window verbatim instead, capped at half the trigger so a
-/// capped trigger (350k on a 1M window) still has room to fold, and pins the
-/// turn's user message to the front of that tail. With no known window the
-/// tail is 30% of the trigger.
-fn with_turn_aware_tail(
- mut policy: tinyagents_harness::summarization::SummarizationPolicy,
- window: Option<u64>,
-) -> tinyagents_harness::summarization::SummarizationPolicy {
- let trigger = policy.trigger_budget();
- let keep_tokens = match window {
- Some(window) => ((window as f64 * COMPACTION_TAIL_WINDOW_FRACTION) as u64).min(trigger / 2),
- None => (trigger as f64 * COMPACTION_TAIL_WINDOW_FRACTION) as u64,
- };
- tracing::debug!(
- context_window = ?window,
- trigger,
- keep_tokens,
- "[context_compression] token tail with the turn's user message pinned"
- );
- policy.keep_recent_tokens = Some(keep_tokens);
- policy.pin_turn_user_message = true;
- policy
-}
-
-#[cfg(test)]
-#[path = "harness_context_ladder_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/agent/tinyagents/harness_context_ladder_tests.rs b/crates/openhuman-core/src/agent/tinyagents/harness_context_ladder_tests.rs
deleted file mode 100644
index ffd5ed57bc..0000000000
--- a/crates/openhuman-core/src/agent/tinyagents/harness_context_ladder_tests.rs
+++ /dev/null
@@ -1,92 +0,0 @@
-use super::*;
-use tinyagents_harness::summarization::DEFAULT_SUMMARIZE_KEEP_LAST;
-
-#[test]
-fn no_window_and_no_override_installs_no_compression() {
- assert!(compression_policy(None, None).is_none());
- assert!(compression_policy(Some(0), None).is_none());
- assert!(compression_policy(None, Some(0)).is_none());
-}
-
-#[test]
-fn a_known_window_triggers_at_eighty_percent_capped_at_350k() {
- let policy = compression_policy(Some(200_000), None).expect("policy");
- assert_eq!(policy.trigger_budget(), 160_000);
- assert_eq!(policy.keep_last, DEFAULT_SUMMARIZE_KEEP_LAST);
- // DeepSeek V4 Flash's discovered 1M window compacts at 350k, not ~840k.
- let policy = compression_policy(Some(1_048_576), None).expect("policy");
- assert!(policy.trigger_budget().abs_diff(350_000) <= 1);
-}
-
-#[test]
-fn the_override_replaces_the_window_fraction() {
- let policy = compression_policy(Some(1_000_000), Some(64_000)).expect("policy");
- assert_eq!(policy.trigger_budget(), 64_000);
- assert!(policy.exceeds_trigger(64_001));
- assert!(!policy.exceeds_trigger(63_000));
- assert_eq!(policy.keep_last, DEFAULT_SUMMARIZE_KEEP_LAST);
-}
-
-#[test]
-fn the_override_works_without_a_known_window() {
- let policy = compression_policy(None, Some(64_000)).expect("policy");
- assert_eq!(policy.trigger_budget(), 64_000);
- assert_eq!(policy.keep_last, DEFAULT_SUMMARIZE_KEEP_LAST);
-}
-
-/// Issue #6960: a compaction that fires mid-turn must keep the turn's
-/// assignment verbatim and size its tail in tokens, not by message count.
-#[test]
-fn the_policy_keeps_a_token_tail_and_pins_the_turn_user_message() {
- let policy = compression_policy(Some(200_000), None).expect("policy");
- assert!(policy.pin_turn_user_message);
- // 30% of the window.
- assert_eq!(policy.keep_recent_tokens, Some(60_000));
-}
-
-#[test]
-fn the_token_tail_never_exceeds_half_the_trigger() {
- // A 1M window compacts at 350k; 30% of the window (300k) would leave the
- // compaction almost nothing to fold.
- let policy = compression_policy(Some(1_048_576), None).expect("policy");
- assert_eq!(policy.keep_recent_tokens, Some(policy.trigger_budget() / 2));
- let policy = compression_policy(Some(1_000_000), Some(64_000)).expect("policy");
- assert_eq!(policy.keep_recent_tokens, Some(32_000));
-}
-
-#[test]
-fn an_override_without_a_window_still_pins_with_a_token_tail() {
- let policy = compression_policy(None, Some(64_000)).expect("policy");
- assert!(policy.pin_turn_user_message);
- assert_eq!(policy.keep_recent_tokens, Some(19_200));
-}
-
-// ── microcompact budget (prompt-cache churn when the window is unknown) ──────
-
-#[test]
-fn an_unknown_window_still_gives_microcompact_a_budget_so_short_runs_stay_append_only() {
- // Unbudgeted microcompact blanks every old tool body on every turn, which
- // rewrites the sent prefix and misses the provider's prompt cache.
- for window in [None, Some(0)] {
- let mw = microcompact_middleware(5, window);
- assert_eq!(
- mw.token_budget(),
- Some(legacy_max_input_tokens(UNKNOWN_WINDOW_FALLBACK_TOKENS)),
- "window {window:?}"
- );
- }
-}
-
-#[test]
-fn the_unknown_window_budget_is_finite_so_blanking_still_backstops_growth() {
- let budget = microcompact_middleware(5, None).token_budget().unwrap();
- assert!(budget < UNKNOWN_WINDOW_FALLBACK_TOKENS);
- assert!(budget > 0);
-}
-
-#[test]
-fn a_known_window_keeps_the_trim_allowance_as_the_microcompact_budget() {
- let mw = microcompact_middleware(5, Some(200_000));
- assert_eq!(mw.token_budget(), Some(legacy_max_input_tokens(200_000)));
- assert_eq!(mw.keep_recent(), 5);
-}
diff --git a/crates/openhuman-core/src/agent/tinyagents/mod.rs b/crates/openhuman-core/src/agent/tinyagents/mod.rs
index 78edfd30f8..7492b6678f 100644
--- a/crates/openhuman-core/src/agent/tinyagents/mod.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/mod.rs
@@ -25,7 +25,7 @@ mod deadline_wind_down;
pub mod discovery;
mod embeddings;
mod harness_assembly;
-mod harness_context_ladder;
+mod context_wiring;
pub(crate) mod harness_tool_registration;
pub mod host;
pub(crate) mod hosted_error;