Skip to content

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

fix(agent): serve reads of persisted tool-result artifacts verbatim, store the tool's real output (#6284)

M3gA-Mindb56a47584617
diff --git a/crates/openhuman-core/src/agent/harness/tool_result_artifacts/mod.rs b/crates/openhuman-core/src/agent/harness/tool_result_artifacts/mod.rs
index 1096559d86..f5e5d44621 100644
--- a/crates/openhuman-core/src/agent/harness/tool_result_artifacts/mod.rs
+++ b/crates/openhuman-core/src/agent/harness/tool_result_artifacts/mod.rs
@@ -10,12 +10,111 @@ use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use crate::agent::dispatcher::ToolExecutionResult;
-use crate::memory::safety::{sanitize_text, SanitizationReport};
+use crate::memory::safety::{sanitize_text, SanitizationReport, Sanitized};
use async_trait::async_trait;
use serde_json::Value;
use tinyagents_harness::store::Store;
const ARTIFACT_ROOT: &str = "artifacts/tool-results";
+
+/// A read of a persisted artifact, recognised from a tool call's arguments.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub(crate) struct ArtifactRead {
+ pub path: String,
+ pub offset: usize,
+}
+
+/// The only tool whose result is a read of an artifact's content.
+const FILE_READ_TOOL: &str = "file_read";
+
+/// The artifact a tool call reads, if any.
+///
+/// Only a `file_read` counts, because only its result *is* the stored body:
+/// `file_write`, `glob`, `list` or `apply_patch` can name an artifact path too,
+/// and their output must still take the normal ladder. The read may arrive
+/// wrapped in `use_skill`, reported under that name
+/// (`use_skill {"skill":"files","tool":"file_read","args":{"path":…}}`), so
+/// `use_skill` — and only `use_skill`, the one tool whose result *is* the
+/// wrapped tool's result — is followed into the tool it runs (#6284). Any
+/// other tool that happens to carry `tool`/`args` fields is not a wrapper.
+pub(crate) fn artifact_read_target(tool_name: &str, args: &Value) -> Option<ArtifactRead> {
+ if tool_name == crate::tools::toolpacks::USE_SKILL {
+ let inner_tool = args.get("tool").and_then(Value::as_str)?;
+ return artifact_read_target(inner_tool, args.get("args")?);
+ }
+ if tool_name != FILE_READ_TOOL {
+ return None;
+ }
+ let path = args.get("path").and_then(Value::as_str)?;
+ // A path component match: `artifacts/tool-results-backup/…` shares the
+ // prefix but is not the artifact directory.
+ let under_root = path
+ .trim_start_matches("./")
+ .strip_prefix(ARTIFACT_ROOT)
+ .is_some_and(|rest| rest.starts_with('/'));
+ under_root.then(|| ArtifactRead {
+ path: path.to_string(),
+ offset: args
+ .get("offset")
+ .and_then(Value::as_u64)
+ .and_then(|o| usize::try_from(o).ok())
+ .unwrap_or(0),
+ })
+}
+
+/// Bound one page of an artifact read to `budget_bytes`, naming the exact
+/// `offset` the next read continues from. Never persists: re-persisting a read
+/// of an artifact creates a new artifact whose preview is the same bounded
+/// head, and the model can loop between previews without ever reaching the
+/// body.
+pub(crate) fn page_artifact_read(
+ content: String,
+ read: &ArtifactRead,
+ budget_bytes: usize,
+) -> String {
+ if budget_bytes == 0 {
+ return content;
+ }
+ // A page is useless without its continuation, so a budget too small to
+ // carry one is raised to the floor a persisted envelope already takes for
+ // the same reason (`MIN_ENVELOPE_ALLOWANCE_BYTES`). Every page therefore
+ // fits `max(budget_bytes, MIN_ENVELOPE_ALLOWANCE_BYTES)` and advances.
+ let budget_bytes = budget_bytes.max(MIN_ENVELOPE_ALLOWANCE_BYTES);
+ if content.len() <= budget_bytes {
+ return content;
+ }
+ let start = read.offset;
+ let total = start + content.len();
+ let with_path = |next: usize| {
+ format!(
+ "\n\n[artifact page: bytes {start}..{next} of {total}. Continue with file_read {{\"path\":\"{}\",\"offset\":{next}}}]",
+ read.path
+ )
+ };
+ // Without the path (the caller already has it). At most ~100 bytes, so it
+ // always leaves body room under the floor.
+ let without_path = |next: usize| {
+ format!(
+ "\n\n[artifact page: bytes {start}..{next} of {total}. Continue with file_read at \"offset\":{next}]"
+ )
+ };
+ // Sized from the trailer this page will actually carry, not a fixed
+ // reservation. `next` never has more digits than `total`, so a trailer
+ // rendered with `total` is its longest form.
+ let use_path = with_path(total).len() + 4 <= budget_bytes;
+ let longest = if use_path {
+ with_path(total).len()
+ } else {
+ without_path(total).len()
+ };
+ let cut = crate::util::floor_char_boundary(&content, budget_bytes - longest);
+ let trailer = if use_path {
+ with_path(start + cut)
+ } else {
+ without_path(start + cut)
+ };
+ format!("{}{trailer}", &content[..cut])
+}
const AGGREGATE_PREVIEW_BUDGET_BYTES: usize = 512;
/// #4469 item 6: floor for how tightly a persisted `[tool_result_preview]`
/// envelope may be bounded during aggregate spill. `allowed_len` can saturate to
@@ -194,15 +293,25 @@ impl ToolResultArtifactStore {
)
}
+ /// Store `content` and return an envelope previewing it. When `content`
+ /// would be unreadable once sanitized (see [`readable_body`]) and a
+ /// `fallback` is given, the fallback is stored instead; when neither fits,
+ /// this errors and the caller truncates inline rather than writing an
+ /// artifact nobody can read.
async fn persist(
&self,
tool_name: &str,
call_id: Option<&str>,
content: &str,
+ fallback: Option<&str>,
preview_budget_bytes: usize,
reason: &str,
) -> anyhow::Result<PersistedToolResult> {
- let sanitized = sanitize_text(content);
+ let (content, sanitized) = readable_body(
+ content,
+ fallback,
+ crate::tools::FileReadTool::MAX_FILE_SIZE_BYTES,
+ )?;
let relative_path = self.path_for_read_tool(tool_name, call_id);
let absolute_path = self.action_dir.join(&relative_path);
assert_within_action_dir(&self.action_dir, &absolute_path)?;
@@ -234,7 +343,7 @@ impl ToolResultArtifactStore {
original_bytes: {}\n\
stored_bytes: {}\n\
artifact_path: {relative_path}\n\
- read_with: file_read {{\"path\":\"{relative_path}\"}}\n\
+ read_with: file_read {{\"path\":\"{relative_path}\"}} (a long read returns one page and names the \"offset\" to continue from)\n\
notes: Full scrubbed output was persisted under the action workspace.{redaction_note}{truncation_note}\n\n\
[preview]\n{preview}",
content.len(),
@@ -251,8 +360,42 @@ impl ToolResultArtifactStore {
}
}
+/// The body to store: `primary` if its sanitized form fits `limit`, else
+/// `fallback` if *its* sanitized form does, else an error. Both checks are on
+/// the sanitized size, the bytes actually written, because redaction can grow a
+/// body (`+15551234567` becomes `[REDACTED_PII_PHONE]`): a raw body under the
+/// limit can still produce an artifact `file_read` refuses to open.
+fn readable_body<'a>(
+ primary: &'a str,
+ fallback: Option<&'a str>,
+ limit: u64,
+) -> anyhow::Result<(&'a str, Sanitized<String>)> {
+ let sanitized = sanitize_text(primary);
+ if sanitized.value.len() as u64 <= limit {
+ return Ok((primary, sanitized));
+ }
+ if let Some(fallback) = fallback {
+ let sanitized_fallback = sanitize_text(fallback);
+ if sanitized_fallback.value.len() as u64 <= limit {
+ return Ok((fallback, sanitized_fallback));
+ }
+ }
+ anyhow::bail!(
+ "tool result would not be readable once stored: {} sanitized bytes exceed the {limit}-byte file_read limit",
+ sanitized.value.len()
+ )
+}
+
+/// Persist an over-budget result and return its envelope.
+///
+/// `full_output` is the tool's output before any earlier stage rewrote it
+/// (summarizer, TokenJuice). When given, *that* is what gets stored, so the
+/// artifact holds what the tool returned rather than a compacted copy of it;
+/// `content` still decides whether the budget was exceeded and is what the
+/// model would otherwise have seen.
pub(crate) async fn apply_per_result_persistence(
content: String,
+ full_output: Option<String>,
store: Option<&ToolResultArtifactStore>,
tool_name: &str,
call_id: Option<&str>,
@@ -271,7 +414,8 @@ pub(crate) async fn apply_per_result_persistence(
.persist(
tool_name,
call_id,
- &content,
+ full_output.as_deref().unwrap_or(&content),
+ full_output.as_ref().map(|_| content.as_str()),
budget_bytes,
"per-result budget exceeded",
)
@@ -304,7 +448,10 @@ pub(crate) async fn apply_per_result_persistence(
return (
output,
ToolResultArtifactOutcome {
- original_bytes,
+ // The size of what was stored, which `full_output` can
+ // make larger than `content`; the artifact index and its
+ // contents list read this number.
+ original_bytes: persisted.original_bytes,
final_bytes,
persisted: true,
artifact_path: Some(persisted.path),
@@ -390,6 +537,7 @@ pub(crate) async fn spill_aggregate_tool_results(
&results[idx].name,
results[idx].tool_call_id.as_deref(),
&original,
+ None,
allowed_len.min(AGGREGATE_PREVIEW_BUDGET_BYTES),
"aggregate tool-result budget exceeded",
)
diff --git a/crates/openhuman-core/src/agent/harness/tool_result_artifacts/mod_tests.rs b/crates/openhuman-core/src/agent/harness/tool_result_artifacts/mod_tests.rs
index 1060ff0309..1e8c7e55b8 100644
--- a/crates/openhuman-core/src/agent/harness/tool_result_artifacts/mod_tests.rs
+++ b/crates/openhuman-core/src/agent/harness/tool_result_artifacts/mod_tests.rs
@@ -15,9 +15,15 @@ async fn threshold_persists_preview_and_readable_file() {
"ghp_abcdefghijklmnopqrstuvwxyz123456"
);
- let (out, outcome) =
- apply_per_result_persistence(raw.clone(), Some(&store), "shell", Some("call-1"), 1024)
- .await;
+ let (out, outcome) = apply_per_result_persistence(
+ raw.clone(),
+ None,
+ Some(&store),
+ "shell",
+ Some("call-1"),
+ 1024,
+ )
+ .await;
assert!(outcome.persisted);
assert!(out.contains("artifact_path: artifacts/tool-results/session_one/shell/call-1.txt"));
@@ -46,7 +52,8 @@ async fn threshold_persists_preview_and_readable_file() {
#[tokio::test]
async fn fallback_truncates_when_store_missing() {
let raw = "z".repeat(4096);
- let (out, outcome) = apply_per_result_persistence(raw, None, "shell", Some("call"), 512).await;
+ let (out, outcome) =
+ apply_per_result_persistence(raw, None, None, "shell", Some("call"), 512).await;
assert!(!outcome.persisted);
assert!(out.contains("truncated by tool_result_budget"));
assert!(out.len() < 4096);
@@ -59,7 +66,7 @@ async fn persisted_preview_is_bounded_for_small_budget() {
let raw = "x".repeat(800);
let (out, outcome) =
- apply_per_result_persistence(raw, Some(&store), "shell", Some("call"), 320).await;
+ apply_per_result_persistence(raw, None, Some(&store), "shell", Some("call"), 320).await;
assert!(outcome.persisted);
assert!(outcome.final_bytes <= 320, "final={}", outcome.final_bytes);
@@ -156,3 +163,190 @@ async fn aggregate_forces_budget_when_envelope_has_no_savings() {
.join("artifacts/tool-results/session/one/one.txt")
.exists());
}
+
+#[test]
+fn artifact_read_target_finds_a_path_nested_in_a_wrapper_call() {
+ let args = json!({
+ "skill": "files",
+ "tool": "file_read",
+ "args": {"path": "artifacts/tool-results/s/use_skill/c.txt", "offset": 42}
+ });
+ assert_eq!(
+ artifact_read_target("use_skill", &args),
+ Some(ArtifactRead {
+ path: "artifacts/tool-results/s/use_skill/c.txt".to_string(),
+ offset: 42,
+ })
+ );
+ assert_eq!(
+ artifact_read_target("file_read", &json!({"path": "src/main.rs"})),
+ None
+ );
+}
+
+#[tokio::test]
+async fn persisted_outcome_reports_the_size_of_the_stored_body() {
+ let tmp = tempfile::tempdir().unwrap();
+ let store = ToolResultArtifactStore::new(tmp.path().to_path_buf(), "session");
+ let rewritten = "s".repeat(3_000);
+ let full = "r".repeat(8_000);
+
+ let (out, outcome) = apply_per_result_persistence(
+ rewritten,
+ Some(full),
+ Some(&store),
+ "shell",
+ Some("call"),
+ 1_000,
+ )
+ .await;
+
+ assert!(outcome.persisted);
+ assert_eq!(
+ outcome.original_bytes, 8_000,
+ "the outcome feeds the artifact index, so it must report the stored body's size"
+ );
+ assert!(out.contains("original_bytes: 8000"), "{out}");
+}
+
+#[test]
+fn artifact_read_target_matches_only_file_read_under_the_artifact_directory() {
+ let path = "artifacts/tool-results/s/shell/c.txt";
+ assert!(artifact_read_target("file_read", &json!({"path": path})).is_some());
+ assert_eq!(
+ artifact_read_target("file_write", &json!({"path": path, "content": "x"})),
+ None,
+ "a write to an artifact path is not a read of its content"
+ );
+ assert_eq!(
+ artifact_read_target(
+ "use_skill",
+ &json!({"skill": "files", "tool": "glob", "args": {"path": path}})
+ ),
+ None,
+ "a wrapped non-read tool is not a read of its content"
+ );
+}
+
+#[test]
+fn artifact_read_target_matches_the_artifact_directory_as_a_path_component() {
+ assert!(artifact_read_target(
+ "file_read",
+ &json!({"path": "./artifacts/tool-results/s/c.txt"})
+ )
+ .is_some());
+ assert_eq!(
+ artifact_read_target(
+ "file_read",
+ &json!({"path": "artifacts/tool-results-backup/report.txt"})
+ ),
+ None,
+ "a sibling directory sharing the prefix is not the artifact directory"
+ );
+}
+
+#[test]
+fn an_artifact_page_stays_within_the_budget_with_a_long_path() {
+ let read = ArtifactRead {
+ path: format!(
+ "artifacts/tool-results/{}/use_skill/call.txt",
+ "s".repeat(240)
+ ),
+ offset: 1_234_567,
+ };
+
+ let page = page_artifact_read("y".repeat(5_000), &read, 1_000);
+ assert!(
+ page.len() <= 1_000,
+ "a page must fit the result budget, got {} bytes",
+ page.len()
+ );
+ let body = page
+ .find("\n\n[artifact page")
+ .expect("continuation marker");
+ assert!(
+ page.contains(&format!("\"offset\":{}", 1_234_567 + body)),
+ "the marker must name the offset right after this page: {page}"
+ );
+}
+
+#[test]
+fn a_page_never_exceeds_the_floored_budget_and_always_advances() {
+ // A path too long for its full trailer to leave body room under the floor.
+ let read = ArtifactRead {
+ path: format!("artifacts/tool-results/{}/c.txt", "p".repeat(600)),
+ offset: 7,
+ };
+ let content = "z".repeat(5_000);
+
+ for budget in [2, 100, MIN_ENVELOPE_ALLOWANCE_BYTES, 700] {
+ let page = page_artifact_read(content.clone(), &read, budget);
+ let limit = budget.max(MIN_ENVELOPE_ALLOWANCE_BYTES);
+ assert!(
+ page.len() <= limit,
+ "budget {budget}: a page must fit max(budget, floor) = {limit}, got {} bytes",
+ page.len()
+ );
+ let body = page
+ .find("\n\n[artifact page")
+ .expect("continuation marker");
+ assert!(
+ body > 0,
+ "budget {budget}: every page must advance past its offset"
+ );
+ assert!(
+ page.contains(&format!("\"offset\":{}", 7 + body)),
+ "budget {budget}: the marker must name the offset right after this page: {page}"
+ );
+ }
+}
+
+#[test]
+fn a_body_redaction_grows_past_the_read_limit_falls_back_to_the_processed_copy() {
+ let raw = "call +15551234567 or +15557654321";
+ // The limit is the raw size: the raw body fits, its redacted form does not.
+ let (chosen, stored) = readable_body(raw, Some("processed copy"), raw.len() as u64)
+ .expect("the processed copy fits");
+ assert_eq!(
+ chosen, "processed copy",
+ "a body whose sanitized form exceeds the read limit must not be stored, got {:?}",
+ stored.value
+ );
+
+ let (kept, _) = readable_body(raw, Some("processed copy"), 10_000).expect("fits");
+ assert_eq!(
+ kept, raw,
+ "a body that stays within the limit is stored as returned"
+ );
+}
+
+#[test]
+fn a_body_is_refused_when_neither_candidate_fits_the_read_limit() {
+ let raw = "call +15551234567 or +15557654321";
+ let fallback = "fallback +15550001111 +15550002222";
+ let limit = raw.len().min(fallback.len()) as u64;
+ assert!(
+ readable_body(raw, Some(fallback), limit).is_err(),
+ "when neither the raw body nor the fallback fits once sanitized, nothing may be stored"
+ );
+ assert!(
+ readable_body(raw, None, limit).is_err(),
+ "a body with no fallback that does not fit must not be stored either"
+ );
+}
+
+#[test]
+fn artifact_read_target_follows_only_use_skill_into_a_wrapped_tool() {
+ let nested = json!({"tool": "file_read", "args": {"path": "artifacts/tool-results/s/c.txt"}});
+ assert!(
+ artifact_read_target("use_skill", &nested).is_some(),
+ "use_skill forwards file_read's result, so its wrapped read counts"
+ );
+ for outer in ["glob", "file_write", "shell"] {
+ assert_eq!(
+ artifact_read_target(outer, &nested),
+ None,
+ "{outer} carrying tool/args fields is not a wrapper; its result is its own"
+ );
+ }
+}
diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware/tool_output.rs b/crates/openhuman-core/src/agent/tinyagents/middleware/tool_output.rs
index 93bcfe3939..c46103d018 100644
--- a/crates/openhuman-core/src/agent/tinyagents/middleware/tool_output.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/middleware/tool_output.rs
@@ -3,7 +3,7 @@
//! compaction, per-tool char cap, shared byte-budget backstop, disclosure.
use std::collections::HashMap;
-use std::sync::Arc;
+use std::sync::{Arc, Mutex};
use async_trait::async_trait;
@@ -12,9 +12,11 @@ use tinyagents_harness::error::Result as TaResult;
use tinyagents_harness::events::AgentEvent;
use tinyagents_harness::middleware::Middleware;
use tinyagents_harness::tool::{ToolPolicy as TaToolPolicy, ToolResult as TaToolResult};
+use tinyinference::tool::ToolCall as TaToolCall;
use crate::agent::harness::tool_result_artifacts::{
- apply_per_result_persistence, ToolResultArtifactStore, TINYAGENTS_TOOL_RESULT_ARTIFACT_STORE,
+ apply_per_result_persistence, artifact_read_target, page_artifact_read, ArtifactRead,
+ ToolResultArtifactStore, TINYAGENTS_TOOL_RESULT_ARTIFACT_STORE,
};
use crate::agent::tinyagents::payload_summarizer::{
PayloadSummarizer, SummarizeOutcome, UnavailableReason,
@@ -105,6 +107,10 @@ pub(crate) struct ToolOutputMiddleware {
/// `max_result_size_chars()` cap without re-querying the OpenHuman tool
/// trait from `after_tool`.
pub(crate) tool_policies: HashMap<String, TaToolPolicy>,
+ /// Calls that read a persisted artifact, keyed by call id. Filled in
+ /// `before_tool`, where the arguments are visible, and consumed in
+ /// `after_tool`, where they are not.
+ pub(crate) artifact_reads: Mutex<HashMap<String, ArtifactRead>>,
}
impl ToolOutputMiddleware {
@@ -124,12 +130,61 @@ impl Middleware<()> for ToolOutputMiddleware {
"tool_output_budget"
}
+ async fn before_tool(
+ &self,
+ _ctx: &mut RunContext<()>,
+ _state: &(),
+ call: &mut TaToolCall,
+ ) -> TaResult<()> {
+ if let Some(read) = artifact_read_target(&call.name, &call.arguments) {
+ tracing::debug!(
+ tool = %call.name,
+ call_id = %call.id,
+ path = %read.path,
+ offset = read.offset,
+ "[tinyagents::mw] call reads a persisted tool-result artifact"
+ );
+ if let Ok(mut reads) = self.artifact_reads.lock() {
+ reads.insert(call.id.clone(), read);
+ }
+ }
+ Ok(())
+ }
+
async fn after_tool(
&self,
ctx: &mut RunContext<()>,
_state: &(),
result: &mut TaToolResult,
) -> TaResult<()> {
+ // A read of a persisted artifact is the model following the envelope's
+ // `read_with` instruction. Every stage below would defeat it: the
+ // summarizer re-summarizes the body the model asked to see, TokenJuice
+ // compacts it, and the byte budget persists it as a *new* artifact with
+ // the same bounded preview — a loop that never reaches the data (#6284).
+ // Serve it verbatim, one bounded page at a time.
+ let artifact_read = self
+ .artifact_reads
+ .lock()
+ .ok()
+ .and_then(|mut reads| reads.remove(&result.call_id));
+ if let Some(read) = artifact_read {
+ tracing::info!(
+ tool = %result.name,
+ call_id = %result.call_id,
+ path = %read.path,
+ offset = read.offset,
+ bytes = result.content.len(),
+ "[tinyagents::mw] artifact read: skipping summarizer, compaction and re-persistence"
+ );
+ result.content = page_artifact_read(
+ std::mem::take(&mut result.content),
+ &read,
+ self.budget_bytes,
+ );
+ return Ok(());
+ }
+
// Proposal-/persistence-emitting workflow tools return a self-describing
// `{ "type": "workflow_proposal", … }` JSON payload that `flows::ops`'
// `extract_workflow_proposal` (and the frontend's content-based
@@ -184,6 +239,21 @@ impl Middleware<()> for ToolOutputMiddleware {
// the authoritative size with it (#6283).
let mut summarized_from_bytes: Option<usize> = None;
+ // The tool's own output, kept only when it could end up persisted (step
+ // 4 with a store), so the artifact stores what the tool returned rather
+ // than the summarized or compacted copy the stages below produce. The
+ // live artifact otherwise held 71,650 compacted bytes of a 119,796-byte
+ // result and reported the smaller number as `original_bytes`. Skipped
+ // when the raw body is larger than `file_read` will open: an artifact
+ // nobody can read back is worse than the processed copy.
+ let full_output = (!truncation_exempt
+ && self.tool_char_cap(&result.name).is_none()
+ && self.budget_bytes > 0
+ && self.artifact_store.is_some()
+ && result.content.len() > self.budget_bytes
+ && result.content.len() as u64 <= crate::tools::FileReadTool::MAX_FILE_SIZE_BYTES)
+ .then(|| result.content.clone());
+
if !compaction_exempt {
if let Some(ps) = &self.payload_summarizer {
match ps
@@ -299,6 +369,7 @@ impl Middleware<()> for ToolOutputMiddleware {
if !truncation_exempt && tool_cap.is_none() && self.budget_bytes > 0 {
let (capped, outcome) = apply_per_result_persistence(
std::mem::take(&mut result.content),
+ full_output,
self.artifact_store.as_ref(),
&result.name,
Some(&result.call_id),
diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware/turn_context.rs b/crates/openhuman-core/src/agent/tinyagents/middleware/turn_context.rs
index 6f1c816eef..4a1d38068f 100644
--- a/crates/openhuman-core/src/agent/tinyagents/middleware/turn_context.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/middleware/turn_context.rs
@@ -314,6 +314,7 @@ impl TurnContextMiddleware {
tokenjuice_compression: self.tokenjuice_compression,
runtime_config: self.runtime_config,
tool_policies,
+ artifact_reads: Default::default(),
}));
}
// Push the handoff LAST (so its `after_tool` runs FIRST): it observes the
diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware_tests.rs b/crates/openhuman-core/src/agent/tinyagents/middleware_tests.rs
index 58857f476f..5a56346612 100644
--- a/crates/openhuman-core/src/agent/tinyagents/middleware_tests.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/middleware_tests.rs
@@ -82,6 +82,7 @@ fn summarizer_mw(ps: Arc<dyn PayloadSummarizer>) -> ToolOutputMiddleware {
tokenjuice_compression: crate::inference::tokenjuice::AgentTokenjuiceCompression::Off,
runtime_config: None,
tool_policies: HashMap::new(),
+ artifact_reads: Default::default(),
}
}
@@ -175,6 +176,7 @@ fn compaction_enabled_mw() -> ToolOutputMiddleware {
tokenjuice_compression: AgentTokenjuiceCompression::Full,
runtime_config: None,
tool_policies: HashMap::new(),
+ artifact_reads: Default::default(),
}
}
@@ -223,6 +225,7 @@ fn truncation_probe_mw() -> ToolOutputMiddleware {
tokenjuice_compression: AgentTokenjuiceCompression::Off,
runtime_config: None,
tool_policies: HashMap::new(),
+ artifact_reads: Default::default(),
}
}
@@ -422,6 +425,8 @@ fn embedder_hook_mw(
mod loop_guard_tests;
#[path = "middleware_repeat_progress_tests.rs"]
mod repeat_progress_tests;
+#[path = "middleware_tool_output_artifact_tests.rs"]
+mod tool_output_artifact_tests;
#[path = "middleware_tool_output_tests.rs"]
mod tool_output_tests;
#[path = "middleware_tool_policy_tests.rs"]
diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware_tool_output_artifact_tests.rs b/crates/openhuman-core/src/agent/tinyagents/middleware_tool_output_artifact_tests.rs
new file mode 100644
index 0000000000..d906ce9765
--- /dev/null
+++ b/crates/openhuman-core/src/agent/tinyagents/middleware_tool_output_artifact_tests.rs
@@ -0,0 +1,130 @@
+//! `ToolOutputMiddleware` and persisted tool-result artifacts (#6284): reads
+//! of an artifact and what gets stored. Split from
+//! `middleware_tool_output_tests.rs` to keep each file under the layout limit.
+
+use super::*;
+
+fn artifact_mw(
+ summarizer: Option<Arc<dyn PayloadSummarizer>>,
+ action_dir: &std::path::Path,
+) -> ToolOutputMiddleware {
+ ToolOutputMiddleware {
+ budget_bytes: 1_000,
+ payload_summarizer: summarizer,
+ task_hint: None,
+ artifact_store: Some(
+ crate::agent::harness::tool_result_artifacts::ToolResultArtifactStore::new(
+ action_dir.to_path_buf(),
+ "session",
+ ),
+ ),
+ tokenjuice_compaction_enabled: false,
+ tokenjuice_compression: AgentTokenjuiceCompression::Off,
+ runtime_config: None,
+ tool_policies: HashMap::new(),
+ artifact_reads: Default::default(),
+ }
+}
+
+fn summarized(summary: &str, original_bytes: usize) -> Arc<dyn PayloadSummarizer> {
+ StubSummarizer::ok(SummarizeOutcome::Summarized(
+ crate::agent::tinyagents::payload_summarizer::SummarizedPayload {
+ summary: summary.to_string(),
+ original_bytes,
+ summary_bytes: summary.len(),
+ },
+ ))
+}
+
+#[tokio::test]
+async fn a_wrapped_read_of_a_persisted_artifact_is_paged_not_resummarized_or_repersisted() {
+ let tmp = tempfile::tempdir().unwrap();
+ let mw = artifact_mw(Some(summarized("SUMMARY", 5_000)), tmp.path());
+ let path = "artifacts/tool-results/session/use_skill/earlier.txt";
+ // The read arrives wrapped, reported under the wrapper's name, exactly as
+ // `use_skill` delivers `file_read`.
+ let mut call = TaToolCall::new(
+ "c1",
+ "use_skill",
+ json!({"skill": "files", "tool": "file_read", "args": {"path": path, "offset": 2_000}}),
+ );
+ let mut ctx = ctx();
+ mw.before_tool(&mut ctx, &(), &mut call).await.unwrap();
+ let mut result = tool_result("use_skill", &"y".repeat(5_000));
+
+ mw.after_tool(&mut ctx, &(), &mut result).await.unwrap();
+
+ assert!(
+ result.content.starts_with("yyyy"),
+ "an artifact read must return the stored body, not a summary of it: {:?}",
+ &result.content[..result.content.len().min(120)]
+ );
+ let page_end = result
+ .content
+ .find("\n\n[artifact page")
+ .expect("an over-budget read must be paged with a continuation marker");
+ assert!(
+ result
+ .content
+ .contains(&format!("\"offset\":{}", 2_000 + page_end)),
+ "the page must name the exact offset the next read starts at: {}",
+ &result.content[page_end..]
+ );
+ assert!(
+ !tmp.path().join("artifacts").exists(),
+ "reading an artifact must not persist it again as a new artifact"
+ );
+}
+
+#[tokio::test]
+async fn an_oversized_result_is_stored_as_the_tool_returned_it_not_as_rewritten() {
+ let tmp = tempfile::tempdir().unwrap();
+ // A summary still over the 1,000-byte budget, so the result is persisted
+ // after an earlier stage has already rewritten it.
+ let mw = artifact_mw(Some(summarized(&"s".repeat(3_000), 8_000)), tmp.path());
+ let raw = "r".repeat(8_000);
+ let mut result = tool_result("echo", &raw);
+
+ mw.after_tool(&mut ctx(), &(), &mut result).await.unwrap();
+
+ assert!(
+ result.content.contains("[tool_result_preview]"),
+ "an over-budget result is persisted: {}",
+ result.content
+ );
+ let stored = std::fs::read_to_string(
+ tmp.path()
+ .join("artifacts/tool-results/session/echo/c1.txt"),
+ )
+ .expect("artifact written");
+ assert_eq!(
+ stored, raw,
+ "the artifact must hold the tool's own output, not the rewritten copy"
+ );
+ assert!(
+ result.content.contains("original_bytes: 8000"),
+ "the envelope must report the size of what was stored: {}",
+ result.content
+ );
+}
+
+#[tokio::test]
+async fn a_raw_result_file_read_cannot_open_is_stored_as_the_processed_copy() {
+ let tmp = tempfile::tempdir().unwrap();
+ let summary = "s".repeat(3_000);
+ let raw_len = crate::tools::FileReadTool::MAX_FILE_SIZE_BYTES as usize + 1;
+ let mw = artifact_mw(Some(summarized(&summary, raw_len)), tmp.path());
+ let mut result = tool_result("echo", &"r".repeat(raw_len));
+
+ mw.after_tool(&mut ctx(), &(), &mut result).await.unwrap();
+
+ let stored = std::fs::read_to_string(
+ tmp.path()
+ .join("artifacts/tool-results/session/echo/c1.txt"),
+ )
+ .expect("artifact written");
+ assert_eq!(
+ stored, summary,
+ "a raw body over file_read's limit would be unreadable, so the processed copy is stored"
+ );
+}
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.rs
index 8502a0b59c..cef369e2a0 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
@@ -317,6 +317,7 @@ async fn tool_output_truncates_over_the_flat_budget() {
tokenjuice_compression: AgentTokenjuiceCompression::Off,
runtime_config: None,
tool_policies: HashMap::new(),
+ artifact_reads: Default::default(),
};
let mut result = tool_result("echo", &"x".repeat(5_000));
mw.after_tool(&mut ctx(), &(), &mut result).await.unwrap();
@@ -339,6 +340,7 @@ async fn tool_output_leaves_small_results_untouched() {
tokenjuice_compression: AgentTokenjuiceCompression::Off,
runtime_config: None,
tool_policies: HashMap::new(),
+ artifact_reads: Default::default(),
};
let mut result = tool_result("echo", "tiny");
mw.after_tool(&mut ctx(), &(), &mut result).await.unwrap();
@@ -370,6 +372,7 @@ fn tool_char_cap_reads_the_tools_own_declared_cap() {
tokenjuice_compression: AgentTokenjuiceCompression::Off,
runtime_config: None,
tool_policies,
+ artifact_reads: Default::default(),
};
// Tool declares its own char cap → surfaced for the per-tool truncation.
assert_eq!(mw.tool_char_cap("big"), Some(10));
@@ -413,6 +416,7 @@ async fn an_unavailable_notice_survives_a_tool_cap_shorter_than_itself() {
tokenjuice_compression: crate::inference::tokenjuice::AgentTokenjuiceCompression::Off,
runtime_config: None,
tool_policies,
+ artifact_reads: Default::default(),
};
let mut result = tool_result("terse", &"payload ".repeat(200));
@@ -468,6 +472,7 @@ async fn tool_output_honors_a_tools_own_cap() {
tokenjuice_compression: AgentTokenjuiceCompression::Off,
runtime_config: None,
tool_policies,
+ artifact_reads: Default::default(),
};
let mut result = tool_result("capped", &"y".repeat(500));
mw.after_tool(&mut ctx(), &(), &mut result).await.unwrap();
diff --git a/crates/openhuman-core/src/tools/impl/filesystem/file_read.rs b/crates/openhuman-core/src/tools/impl/filesystem/file_read.rs
index 21b3c108af..7647f1a153 100644
--- a/crates/openhuman-core/src/tools/impl/filesystem/file_read.rs
+++ b/crates/openhuman-core/src/tools/impl/filesystem/file_read.rs
@@ -14,6 +14,10 @@ pub struct FileReadTool {
}
impl FileReadTool {
+ /// Largest file this tool will open. Anything that must stay readable
+ /// through it (a persisted tool-result artifact) has to fit.
+ pub const MAX_FILE_SIZE_BYTES: u64 = MAX_FILE_SIZE_BYTES;
+
pub fn new(security: Arc<SecurityPolicy>) -> Self {
Self { security }
}
@@ -39,6 +43,11 @@ impl Tool for FileReadTool {
"path": {
"type": "string",
"description": "Relative path to the file within the workspace"
+ },
+ "offset": {
+ "type": "integer",
+ "minimum": 0,
+ "description": "Byte offset to start reading from. Use the offset a paged read reports to continue it."
}
},
"required": ["path"]
@@ -124,7 +133,29 @@ impl FileReadTool {
.unwrap_or(std::time::SystemTime::UNIX_EPOCH);
file_state::record_read(&agent_id, resolved_path, mtime, false);
}
- Ok(ToolResult::success(contents))
+ let offset = args
+ .get("offset")
+ .and_then(serde_json::Value::as_u64)
+ .and_then(|o| usize::try_from(o).ok())
+ .unwrap_or(0);
+ if offset == 0 {
+ return Ok(ToolResult::success(contents));
+ }
+ if offset > contents.len() {
+ return Ok(ToolResult::error(format!(
+ "offset {offset} is past the end of the file ({} bytes)",
+ contents.len()
+ )));
+ }
+ // Rejected rather than snapped to a boundary: a caller paging
+ // from `offset` computes the next offset from where it asked to
+ // start, so a silent move backwards would skip or repeat bytes.
+ if !contents.is_char_boundary(offset) {
+ return Ok(ToolResult::error(format!(
+ "offset {offset} falls inside a multi-byte character; continue from the offset a paged read reports"
+ )));
+ }
+ Ok(ToolResult::success(contents[offset..].to_string()))
}
Err(e) => Ok(ToolResult::error(format!("Failed to read file: {e}"))),
}
diff --git a/crates/openhuman-core/src/tools/impl/filesystem/file_read_tests.rs b/crates/openhuman-core/src/tools/impl/filesystem/file_read_tests.rs
index 0c7f25314c..7b72f66961 100644
--- a/crates/openhuman-core/src/tools/impl/filesystem/file_read_tests.rs
+++ b/crates/openhuman-core/src/tools/impl/filesystem/file_read_tests.rs
@@ -294,3 +294,58 @@ async fn file_read_reports_invalid_utf8_as_an_error_not_a_panic() {
let _ = tokio::fs::remove_dir_all(&dir).await;
}
+
+#[tokio::test]
+async fn file_read_offset_continues_from_the_given_byte() {
+ let dir = tempfile::tempdir().unwrap();
+ tokio::fs::write(dir.path().join("paged.txt"), "hello world")
+ .await
+ .unwrap();
+ let tool = FileReadTool::new(test_security(dir.path().to_path_buf()));
+
+ let page = tool
+ .execute(json!({"path": "paged.txt", "offset": 6}))
+ .await
+ .unwrap();
+ assert!(!page.is_error, "{}", page.output());
+ assert_eq!(
+ page.output(),
+ "world",
+ "a read with an offset must start at that byte"
+ );
+
+ let past_end = tool
+ .execute(json!({"path": "paged.txt", "offset": 99}))
+ .await
+ .unwrap();
+ assert!(
+ past_end.is_error,
+ "an offset past the end must be reported, not returned as an empty read"
+ );
+}
+
+#[tokio::test]
+async fn file_read_rejects_an_offset_inside_a_multibyte_character() {
+ let dir = tempfile::tempdir().unwrap();
+ // "é" is two bytes, so byte 1 is inside it.
+ tokio::fs::write(dir.path().join("utf8.txt"), "é world")
+ .await
+ .unwrap();
+ let tool = FileReadTool::new(test_security(dir.path().to_path_buf()));
+
+ let inside = tool
+ .execute(json!({"path": "utf8.txt", "offset": 1}))
+ .await
+ .unwrap();
+ assert!(
+ inside.is_error,
+ "an offset inside a character must be rejected, not moved, or paging skips bytes: {}",
+ inside.output()
+ );
+
+ let boundary = tool
+ .execute(json!({"path": "utf8.txt", "offset": 2}))
+ .await
+ .unwrap();
+ assert_eq!(boundary.output(), " world");
+}
diff --git a/docs/TEST-COVERAGE-MATRIX.md b/docs/TEST-COVERAGE-MATRIX.md
index 345cb9ae19..1948c0bfac 100644
--- a/docs/TEST-COVERAGE-MATRIX.md
+++ b/docs/TEST-COVERAGE-MATRIX.md
@@ -254,7 +254,7 @@ End-to-end coverage of the agent harness via the web-chat RPC surface against an
| ID | Feature | Layer | Test path(s) | Status | Notes |
| ----- | ---------------------------- | ----- | ------------------------------------------------------------------------------------------------------ | ------ | -------------------------------------------------------------------- |
-| 6.1.1 | File Read Access | RU+WD | `crates/openhuman-core/src/tools/impl/filesystem/file_read.rs`, `app/test/e2e/specs/tool-filesystem-flow.spec.ts` | ✅ | Was 🟡 — WDIO drives memory_read_file + asserts via Node fs |
+| 6.1.1 | File Read Access | RU+WD | `crates/openhuman-core/src/tools/impl/filesystem/file_read.rs`, `app/test/e2e/specs/tool-filesystem-flow.spec.ts` | ✅ | Was 🟡 — WDIO drives memory_read_file + asserts via Node fs. Byte `offset` paging (continues a paged artifact read, #6284): `file_read_tests.rs::file_read_offset_continues_from_the_given_byte` |
| 6.1.2 | File Write Access | RU+WD | `crates/openhuman-core/src/tools/impl/filesystem/file_write.rs`, `app/test/e2e/specs/tool-filesystem-flow.spec.ts` | ✅ | Was 🟡 — WDIO drives memory_write_file + asserts bytes match on disk |
| 6.1.3 | Path Restriction Enforcement | RU+WD | `crates/openhuman-core/src/tools/impl/filesystem/file_read.rs`, `app/test/e2e/specs/tool-filesystem-flow.spec.ts` | ✅ | Was 🟡 — WDIO asserts traversal + absolute-path denial envelope |