Skip to content

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

feat(context): render the persisted-artifact index into the request

sanil-23f46dda5c490c
diff --git a/src/openhuman/agent/tinyagents/middleware_part_05.rs b/src/openhuman/agent/tinyagents/middleware_part_05.rs
index 49f1f3fe23..e38dcc60f5 100644
--- a/src/openhuman/agent/tinyagents/middleware_part_05.rs
+++ b/src/openhuman/agent/tinyagents/middleware_part_05.rs
@@ -706,3 +706,119 @@ fn self_outcome_for(
.find(|outcome| outcome.call_id == call_id)
.map(|outcome| outcome.content.clone())
}
+
+// ── ArtifactIndexTocMiddleware (issue #6014) ─────────────────────────────────
+
+/// Namespace `ToolOutputMiddleware` writes each persisted artifact under.
+const ARTIFACT_INDEX_NAMESPACE: &str = "tool_results";
+
+/// Renders the run's persisted-artifact index into the request as a short
+/// contents list, so the model can always see what this turn has gathered and
+/// where the full copy lives.
+///
+/// # The reference used to live somewhere it could be destroyed
+///
+/// A tool result over the per-result budget is written to disk and replaced by
+/// a preview plus an `artifact_path` pointer (`apply_per_result_persistence`).
+/// That pointer's only home was the tool-result message itself — and tool-result
+/// messages are exactly what the two reduction steps act on. Microcompact
+/// replaces a body with `CLEARED_PLACEHOLDER`; compression folds the older slice
+/// into a summary that *should* carry paths forward ("prefer concrete facts —
+/// paths, names, values") but is a model call, not a guarantee.
+///
+/// Either way the outcome is the same and it is silent: the data sits intact on
+/// disk with nothing in context saying it exists. Every component did its job —
+/// the result was persisted, the transcript was reduced — and the turn quietly
+/// lost the ability to reach its own findings. No log fires, because nothing
+/// failed.
+///
+/// The index has been maintained all along (`ToolResultArtifactIndexStore`,
+/// registered on `RunContext.stores`, written on every persist). Nothing read
+/// it. This reads it.
+///
+/// # Why re-rendered rather than injected once
+///
+/// The contents list is built fresh into each request and never enters the
+/// loop's own transcript, which is what makes it un-destroyable rather than
+/// merely durable: there is no stored copy for a later pass to blank, fold or
+/// evict, and it cannot accumulate into a stack of stale lists. It is also
+/// always current — an artifact persisted on the previous round appears on the
+/// next call with no bookkeeping.
+///
+/// Emitted as a **system** message for the same reason: compression keeps every
+/// system message verbatim and the trim never drops one, so the one thing that
+/// says where the data went is the one thing the ladder may not take. It is
+/// appended at the tail rather than the head so the cacheable prompt prefix is
+/// untouched.
+pub(crate) struct ArtifactIndexTocMiddleware;
+
+#[async_trait]
+impl Middleware<()> for ArtifactIndexTocMiddleware {
+ fn name(&self) -> &str {
+ "artifact_index_toc"
+ }
+
+ async fn before_model(
+ &self,
+ ctx: &mut RunContext<()>,
+ _state: &(),
+ request: &mut ModelRequest,
+ ) -> TaResult<()> {
+ let Some(store) = ctx
+ .stores
+ .get(crate::openhuman::agent::harness::tool_result_artifacts::TINYAGENTS_TOOL_RESULT_ARTIFACT_STORE)
+ else {
+ return Ok(());
+ };
+ let keys = store
+ .list(ARTIFACT_INDEX_NAMESPACE)
+ .await
+ .unwrap_or_default();
+ if keys.is_empty() {
+ // No result has been offloaded, so there is nothing to point at and
+ // no reason to spend context saying so.
+ return Ok(());
+ }
+
+ let mut rows: Vec<String> = Vec::new();
+ for key in &keys {
+ let Ok(Some(entry)) = store.get(ARTIFACT_INDEX_NAMESPACE, key).await else {
+ continue;
+ };
+ let tool = entry
+ .get("tool")
+ .and_then(|v| v.as_str())
+ .unwrap_or("tool");
+ let Some(path) = entry.get("artifact_path").and_then(|v| v.as_str()) else {
+ continue;
+ };
+ let bytes = entry
+ .get("original_bytes")
+ .and_then(serde_json::Value::as_u64)
+ .unwrap_or(0);
+ rows.push(format!("- `{tool}` → `{path}` ({bytes} bytes)"));
+ }
+ if rows.is_empty() {
+ return Ok(());
+ }
+ // Sorted so the list is stable between calls when nothing was added —
+ // the index is a `HashMap`, whose iteration order is not. An unstable
+ // ordering would rewrite this message on every call for no reason,
+ // costing cache and making the diff unreadable in a trace.
+ rows.sort();
+ let count = rows.len();
+ tracing::debug!(
+ artifacts = count,
+ "[tinyagents::mw] rendering the persisted-artifact contents list"
+ );
+ request.messages.push(TaMessage::system(format!(
+ "## Stored results from this turn\n\n\
+ {count} tool result(s) were too large to keep inline and were written to disk. The \
+ text you saw for them is a preview; the full content is at the path below and can be \
+ read with the file-reading tool when you need detail the preview does not carry.\n\n\
+ {}",
+ rows.join("\n")
+ )));
+ Ok(())
+ }
+}
diff --git a/src/openhuman/agent/tinyagents/middleware_tests_part_03_tests.rs b/src/openhuman/agent/tinyagents/middleware_tests_part_03_tests.rs
index 21265eba78..515b9c2b99 100644
--- a/src/openhuman/agent/tinyagents/middleware_tests_part_03_tests.rs
+++ b/src/openhuman/agent/tinyagents/middleware_tests_part_03_tests.rs
@@ -260,3 +260,122 @@ async fn wrap_up_does_not_rewrite_a_result_that_was_never_cleared() {
"only a placeholder body may be replaced"
);
}
+
+// ── ArtifactIndexTocMiddleware (issue #6014) ─────────────────────────────────
+
+async fn ctx_with_artifacts(entries: &[(&str, &str, &str, u64)]) -> RunContext<()> {
+ use tinyagents_harness::store::StoreRegistry;
+ let index = std::sync::Arc::new(
+ crate::openhuman::agent::harness::tool_result_artifacts::ToolResultArtifactIndexStore::new(
+ ),
+ );
+ for (call_id, tool, path, bytes) in entries {
+ let mut fields = serde_json::Map::new();
+ fields.insert("tool".to_string(), (*tool).into());
+ fields.insert("call_id".to_string(), (*call_id).into());
+ fields.insert("artifact_path".to_string(), (*path).into());
+ fields.insert(
+ "original_bytes".to_string(),
+ serde_json::Value::from(*bytes),
+ );
+ tinyagents_harness::store::Store::put(
+ index.as_ref(),
+ "tool_results",
+ call_id,
+ fields.into(),
+ )
+ .await
+ .unwrap();
+ }
+ let mut registry = StoreRegistry::new();
+ registry.register(
+ crate::openhuman::agent::harness::tool_result_artifacts::TINYAGENTS_TOOL_RESULT_ARTIFACT_STORE,
+ index,
+ );
+ RunContext::new(RunConfig::new("mw-test"), ()).with_stores(registry)
+}
+
+/// Nothing offloaded → no message. The contents list must not spend context
+/// saying that there is nothing to point at.
+#[tokio::test]
+async fn toc_is_absent_when_no_result_was_offloaded() {
+ let mw = ArtifactIndexTocMiddleware;
+ let mut ctx = ctx_with_artifacts(&[]).await;
+ let mut request = ModelRequest {
+ messages: vec![TaMessage::user("hi")],
+ ..Default::default()
+ };
+
+ mw.before_model(&mut ctx, &(), &mut request).await.unwrap();
+
+ assert_eq!(request.messages.len(), 1, "no artifacts, no contents list");
+}
+
+/// The paths reach the model even though nothing in the transcript carries
+/// them — which is the whole point: the pointer's old home (the tool body) is
+/// what the reduction steps act on.
+#[tokio::test]
+async fn toc_lists_every_persisted_artifact_as_a_system_message() {
+ let mw = ArtifactIndexTocMiddleware;
+ let mut ctx = ctx_with_artifacts(&[
+ ("call-1", "fetch_issues", "outputs/issues-p1.json", 240_000),
+ ("call-2", "web_search", "outputs/search-2.json", 91_000),
+ ])
+ .await;
+ // A transcript that has already lost both pointers: one body blanked by
+ // microcompact, the other never present.
+ let mut request = ModelRequest {
+ messages: vec![
+ TaMessage::user("what did you find?"),
+ TaMessage::tool("call-1", CLEARED_PLACEHOLDER),
+ ],
+ ..Default::default()
+ };
+
+ mw.before_model(&mut ctx, &(), &mut request).await.unwrap();
+
+ let last = request.messages.last().expect("a contents list");
+ assert!(
+ matches!(last, TaMessage::System(_)),
+ "must be a system message — compression keeps those verbatim and the trim never drops \
+ one, so the pointer cannot be reduced away: {last:?}"
+ );
+ let text = last.text();
+ assert!(
+ text.contains("outputs/issues-p1.json"),
+ "missing path: {text}"
+ );
+ assert!(
+ text.contains("outputs/search-2.json"),
+ "missing path: {text}"
+ );
+ assert!(text.contains("fetch_issues"), "missing tool name: {text}");
+}
+
+/// Rendered fresh per request, so repeated passes cannot stack stale lists.
+#[tokio::test]
+async fn toc_does_not_accumulate_across_calls() {
+ let mw = ArtifactIndexTocMiddleware;
+ let mut ctx = ctx_with_artifacts(&[("call-1", "fetch", "outputs/a.json", 100)]).await;
+
+ let mut first = ModelRequest {
+ messages: vec![TaMessage::user("hi")],
+ ..Default::default()
+ };
+ mw.before_model(&mut ctx, &(), &mut first).await.unwrap();
+
+ // The loop rebuilds the request from its own transcript each iteration, so
+ // the second call starts from the same base — not from the mutated first.
+ let mut second = ModelRequest {
+ messages: vec![TaMessage::user("hi")],
+ ..Default::default()
+ };
+ mw.before_model(&mut ctx, &(), &mut second).await.unwrap();
+
+ assert_eq!(first.messages.len(), 2);
+ assert_eq!(
+ second.messages.len(),
+ 2,
+ "exactly one contents list per request"
+ );
+}
diff --git a/src/openhuman/agent/tinyagents/mod_part_04.rs b/src/openhuman/agent/tinyagents/mod_part_04.rs
index 37ff75bf54..061e00defa 100644
--- a/src/openhuman/agent/tinyagents/mod_part_04.rs
+++ b/src/openhuman/agent/tinyagents/mod_part_04.rs
@@ -626,6 +626,13 @@ fn assemble_turn_harness(
harness.push_middleware(mw);
}
+ // Issue #6014: say where the offloaded results went, from the index rather
+ // than from the transcript. Registered after the reduction steps above so it
+ // renders whatever survived them, and before the trim so its message is
+ // counted in that budget — the trim never drops a system message, so being
+ // counted costs nothing and being uncounted could push the request over.
+ harness.push_middleware(Arc::new(middleware::ArtifactIndexTocMiddleware));
+
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