Skip to content

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

fix(agent): handle tool result artifacts for missing files

Steven Enamakel527c344183df
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 62bfbcffef..f4a4505acf 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
@@ -1,724 +1,60 @@
-//! Persist oversized tool outputs as action-workspace artifacts.
+//! OpenHuman's wiring of per-tool-result artifact persistence.
//!
-//! Tool results enter the model context before the provider has seen them, so
-//! this is the last cheap point to replace large raw output with a bounded
-//! preview. The full, scrubbed body is written under `action_dir` so normal
-//! file-reading tools can inspect it later without exposing internal workspace
-//! state.
-
-use std::path::{Path, PathBuf};
-use std::sync::{Arc, Mutex};
+//! The mechanics — the store, the `[tool_result_preview]` envelope, the
+//! per-result and aggregate budgets, paged artifact reads — live in
+//! [`tinyagents_harness::artifacts::tool_results`]. What stays here is what only
+//! the host can decide:
+//!
+//! * **the redactor**: the same `sanitize_text` pass that scrubs a worker
+//! artifact ([`SanitizingRedactor`]), because an artifact on disk is exactly as
+//! readable as the tool result it replaces;
+//! * **the tool vocabulary**: `file_read` opens an artifact and `use_skill` is the
+//! one wrapper whose result *is* the wrapped tool's result;
+//! * **the read limit**: the largest body `file_read` will open
+//! ([`FileReadTool::MAX_FILE_SIZE_BYTES`]).
-use crate::memory::safety::{sanitize_text, SanitizationReport, Sanitized};
-use async_trait::async_trait;
use serde_json::Value;
-use tinyagents_harness::store::Store;
-use tinytools_agent::dialect::ToolOutcome;
-
-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,
-}
+use tinyagents_harness::artifacts::tool_results::{self, ArtifactRead, ToolResultArtifactStore};
-/// The only tool whose result is a read of an artifact's content.
-const FILE_READ_TOOL: &str = "file_read";
+use crate::agent::harness::artifact_offload::{SanitizingRedactor, READ_TOOL};
+use crate::tools::FileReadTool;
-/// 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 == tinyagents_harness::tool::packs::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('/'));
- // An absent or null offset starts at 0. A present one that is not a
- // non-negative integer that fits `usize` is not a read `file_read` serves
- // (it rejects it), so it is not an artifact read either; never reinterpret
- // it as 0.
- let offset = match args.get("offset") {
- None | Some(Value::Null) => 0,
- Some(value) => usize::try_from(value.as_u64()?).ok()?,
- };
- under_root.then(|| ArtifactRead {
- path: path.to_string(),
- offset,
- })
-}
-
-/// 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 Some(total) = start.checked_add(content.len()) else {
- // Only reachable with an offset no real read carries (`file_read`
- // rejects offsets past its at-most-10-MiB file). Bound the result but
- // advertise no continuation, since none could advance.
- let cut = crate::util::floor_char_boundary(&content, budget_bytes);
- return content[..cut].to_string();
- };
- 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
-/// `0` (or a handful of bytes) once earlier-spilled results have already consumed
-/// the aggregate budget; bounding the envelope to that would return `""` — or a
-/// header cut mid-line — discarding the `artifact_path` pointer the model needs
-/// to `file_read` the full output. This floor keeps the envelope header (through
-/// the `artifact_path` / `read_with` lines) intact even when the raw budget math
-/// says zero; `apply_tool_result_budget` retains the head, so the pointer always
-/// survives. Slightly overshooting the aggregate budget here is the correct
-/// trade — a valid pointer is worth a few hundred bytes.
-const MIN_ENVELOPE_ALLOWANCE_BYTES: usize = 512;
+/// Namespace of the artifact index in the run's store registry.
pub(crate) const TINYAGENTS_TOOL_RESULT_ARTIFACT_STORE: &str = "openhuman_tool_result_artifacts";
-const TRAILER_RESERVED: usize = 256;
-
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-struct BudgetOutcome {
- original_bytes: usize,
- final_bytes: usize,
- truncated: bool,
-}
-
-impl BudgetOutcome {
- fn unchanged(len: usize) -> Self {
- Self {
- original_bytes: len,
- final_bytes: len,
- truncated: false,
- }
- }
-}
-fn apply_tool_result_budget(content: String, budget_bytes: usize) -> (String, BudgetOutcome) {
- let original_bytes = content.len();
- if budget_bytes == 0 || original_bytes <= budget_bytes {
- return (content, BudgetOutcome::unchanged(original_bytes));
- }
-
- let head_capacity = budget_bytes.saturating_sub(TRAILER_RESERVED).max(1);
- let mut cut = crate::util::floor_char_boundary(&content, head_capacity);
- if cut == 0 {
- cut = content
- .char_indices()
- .next()
- .map(|(_, c)| c.len_utf8())
- .unwrap_or(0);
- }
-
- let dropped_bytes = original_bytes.saturating_sub(cut);
- let mut out = String::with_capacity(cut + TRAILER_RESERVED);
- out.push_str(&content[..cut]);
- // Say what was lost, and say what NOT to do about it (#6408).
- //
- // The previous wording ended "re-run with a narrower query to see the
- // rest", which is an instruction to repeat the call. For a listing tool
- // with no narrowing argument in reach — `GITHUB_LIST_PULL_REQUESTS` is the
- // reported case — the model has nothing to narrow, so it re-issues the
- // identical call, gets the identical truncation, and repeats until the
- // successful-repeat tracker halts the run: 8-14 calls per question, the
- // token and quota burn, and an "Incomplete" the user cannot explain.
- //
- // Truncation here is deterministic: the same call returns the same bytes
- // and the same cut. Saying so is what makes the retry stop, and giving the
- // totals lets the model judge whether the head it kept is enough to answer
- // from. Keep the `truncated by tool_result_budget` phrase — it is the
- // grep handle several suites and the runbooks match on.
- out.push_str(&format!(
- "\n\n[… {dropped_bytes} of {original_bytes} bytes truncated by tool_result_budget. \
- Repeating this call returns the same truncation — narrow the request \
- (filter, paginate, or request a smaller range) or answer from the {cut} bytes above …]"
- ));
-
- let final_bytes = out.len();
- (
- out,
- BudgetOutcome {
- original_bytes,
- final_bytes,
- truncated: true,
- },
+/// A store rooted at `action_dir` for one session, wired to OpenHuman's
+/// redactor, read tool and read limit.
+pub(crate) fn new_tool_result_store(
+ action_dir: std::path::PathBuf,
+ session_key: impl Into<String>,
+) -> ToolResultArtifactStore {
+ ToolResultArtifactStore::new(
+ action_dir,
+ session_key,
+ std::sync::Arc::new(SanitizingRedactor),
+ READ_TOOL,
+ FileReadTool::MAX_FILE_SIZE_BYTES,
)
}
-#[derive(Debug, Clone)]
-pub(crate) struct ToolResultArtifactStore {
- action_dir: PathBuf,
- session_key: String,
-}
-
-#[derive(Debug, Clone, PartialEq, Eq)]
-pub(crate) struct PersistedToolResult {
- pub output: String,
- pub path: String,
- pub original_bytes: usize,
- pub stored_bytes: usize,
- pub redactions: SanitizationReport,
-}
-
-#[derive(Debug, Clone, PartialEq, Eq)]
-pub(crate) struct ToolResultArtifactOutcome {
- pub original_bytes: usize,
- pub final_bytes: usize,
- pub persisted: bool,
- pub artifact_path: Option<String>,
-}
-
-impl ToolResultArtifactOutcome {
- pub fn unchanged(len: usize) -> Self {
- Self {
- original_bytes: len,
- final_bytes: len,
- persisted: false,
- artifact_path: None,
- }
- }
-}
-
-#[derive(Clone, Debug, Default)]
-pub(crate) struct ToolResultArtifactIndexStore {
- data: Arc<Mutex<std::collections::HashMap<String, std::collections::HashMap<String, Value>>>>,
-}
-
-impl ToolResultArtifactIndexStore {
- pub(crate) fn new() -> Self {
- Self::default()
- }
-}
-
-#[async_trait]
-impl Store for ToolResultArtifactIndexStore {
- async fn get(&self, namespace: &str, key: &str) -> tinyagents_harness::Result<Option<Value>> {
- let guard = self.data.lock().map_err(|_| {
- tinyagents_harness::TinyAgentsError::Memory("tool artifact index poisoned".into())
- })?;
- Ok(guard.get(namespace).and_then(|ns| ns.get(key).cloned()))
- }
-
- async fn put(
- &self,
- namespace: &str,
- key: &str,
- value: Value,
- ) -> tinyagents_harness::Result<()> {
- let mut guard = self.data.lock().map_err(|_| {
- tinyagents_harness::TinyAgentsError::Memory("tool artifact index poisoned".into())
- })?;
- guard
- .entry(namespace.to_string())
- .or_default()
- .insert(key.to_string(), value);
- Ok(())
- }
-
- async fn delete(&self, namespace: &str, key: &str) -> tinyagents_harness::Result<()> {
- let mut guard = self.data.lock().map_err(|_| {
- tinyagents_harness::TinyAgentsError::Memory("tool artifact index poisoned".into())
- })?;
- if let Some(ns) = guard.get_mut(namespace) {
- ns.remove(key);
- }
- Ok(())
- }
-
- async fn list(&self, namespace: &str) -> tinyagents_harness::Result<Vec<String>> {
- let guard = self.data.lock().map_err(|_| {
- tinyagents_harness::TinyAgentsError::Memory("tool artifact index poisoned".into())
- })?;
- Ok(guard
- .get(namespace)
- .map(|ns| ns.keys().cloned().collect())
- .unwrap_or_default())
- }
-}
-
-impl ToolResultArtifactStore {
- /// The root artifacts are written under. Test-only: production never needs
- /// to ask, but a caller choosing the wrong root produces a pointer the model
- /// cannot dereference, and that is only assertable from outside (#6483).
- #[cfg(test)]
- pub(crate) fn root(&self) -> &std::path::Path {
- &self.action_dir
- }
-
- pub(crate) fn new(action_dir: PathBuf, session_key: impl Into<String>) -> Self {
- Self {
- action_dir,
- session_key: sanitize_component(&session_key.into()),
- }
- }
-
- /// Delete artifact directories for sessions other than this one that have
- /// not been touched within `max_age`.
- ///
- /// Artifacts are written under the user's action workspace and nothing else
- /// removes them, so without a bound the directory grows for the life of the
- /// install — a connector returning 17-65 KB across 8-14 calls per question
- /// (#6408) writes a file per call. Trading a token-burn bug for a
- /// disk-growth bug is not a fix.
- ///
- /// Pruning on session START rather than on session end is deliberate. There
- /// is no single point where a session host ends — cached agents are evicted
- /// on fingerprint mismatch or poisoning, and a crash ends a session with no
- /// hook at all — so an end-of-session sweep would miss exactly the runs most
- /// likely to have left artifacts behind. An age sweep at start is
- /// self-healing instead: whatever the last run did, the next one tidies it.
- ///
- /// The current session is never pruned, no matter its age, so a long-lived
- /// session cannot delete artifacts the model may still be reading back.
- ///
- /// Best-effort by design: a failure here must not fail a turn. The caller
- /// logs and carries on, because the worst case is disk left uncollected,
- /// which the next session retries.
- pub(crate) fn prune_stale_sessions(
- &self,
- max_age: std::time::Duration,
- ) -> std::io::Result<u32> {
- let root = self.action_dir.join(ARTIFACT_ROOT);
- let entries = match std::fs::read_dir(&root) {
- Ok(entries) => entries,
- // No artifact root yet is the common case on a first run.
- Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(0),
- Err(error) => return Err(error),
- };
-
- let now = std::time::SystemTime::now();
- let mut removed = 0;
- for entry in entries.flatten() {
- let name = entry.file_name();
- // Never prune the directory this store is actively writing into.
- if name.to_str() == Some(self.session_key.as_str()) {
- continue;
- }
- if !entry.file_type().is_ok_and(|kind| kind.is_dir()) {
- continue;
- }
- let stale = entry
- .metadata()
- .and_then(|meta| meta.modified())
- .ok()
- .and_then(|modified| now.duration_since(modified).ok())
- .is_some_and(|age| age > max_age);
- if stale && std::fs::remove_dir_all(entry.path()).is_ok() {
- removed += 1;
- }
- }
- Ok(removed)
- }
-
- pub(crate) fn path_for_read_tool(&self, tool_name: &str, call_id: Option<&str>) -> String {
- let call = call_id
- .map(sanitize_component)
- .filter(|value| !value.is_empty())
- .unwrap_or_else(|| uuid::Uuid::new_v4().simple().to_string());
- format!(
- "{ARTIFACT_ROOT}/{}/{}/{}.txt",
- self.session_key,
- sanitize_component(tool_name),
- call
- )
- }
-
- /// 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 (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)?;
- if let Some(parent) = absolute_path.parent() {
- tokio::fs::create_dir_all(parent).await?;
- }
- tokio::fs::write(&absolute_path, sanitized.value.as_bytes()).await?;
-
- let (preview, preview_outcome) =
- apply_tool_result_budget(sanitized.value.clone(), preview_budget_bytes);
- let redaction_note = if sanitized.report.changed() {
- " Credential/PII redaction was applied before storage and preview exposure."
- } else {
- ""
- };
- let truncation_note = if preview_outcome.truncated {
- format!(
- " Preview is bounded; {} stored bytes are available via file_read.",
- sanitized.value.len()
- )
- } else {
- String::new()
- };
-
- let envelope = format!(
- "[tool_result_preview]\n\
- tool: {tool_name}\n\
- reason: {reason}\n\
- original_bytes: {}\n\
- stored_bytes: {}\n\
- artifact_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(),
- sanitized.value.len(),
- );
-
- Ok(PersistedToolResult {
- output: envelope,
- path: relative_path,
- original_bytes: content.len(),
- stored_bytes: sanitized.value.len(),
- redactions: sanitized.report,
- })
- }
-}
-
-/// 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()
+/// The artifact a tool call reads, if any — `file_read`, possibly wrapped in
+/// `use_skill` (#6284).
+pub(crate) fn artifact_read_target(tool_name: &str, args: &Value) -> Option<ArtifactRead> {
+ tool_results::artifact_read_target(
+ tool_name,
+ args,
+ READ_TOOL,
+ tinyagents_harness::tool::packs::USE_SKILL,
)
}
-/// 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(
+/// Bound one page of an artifact read to `budget_bytes`.
+pub(crate) fn page_artifact_read(
content: String,
- full_output: Option<String>,
- store: Option<&ToolResultArtifactStore>,
- tool_name: &str,
- call_id: Option<&str>,
- budget_bytes: usize,
-) -> (String, ToolResultArtifactOutcome) {
- let original_bytes = content.len();
- if budget_bytes == 0 || original_bytes <= budget_bytes {
- return (
- content,
- ToolResultArtifactOutcome::unchanged(original_bytes),
- );
- }
-
- if let Some(store) = store {
- match store
- .persist(
- tool_name,
- call_id,
- full_output.as_deref().unwrap_or(&content),
- full_output.as_ref().map(|_| content.as_str()),
- budget_bytes,
- "per-result budget exceeded",
- )
- .await
- {
- Ok(persisted) => {
- let (output, final_bytes) = bound_text_to_budget(persisted.output, budget_bytes);
- if final_bytes >= original_bytes {
- // #4469 item 9: this branch does NOT fall back to inline
- // truncation — the envelope is returned regardless, because it
- // carries the `artifact_path` pointer to the full stored output
- // (worth keeping even when the preview text nets no byte saving
- // vs. the raw result). Log it as an observation only.
- log::debug!(
- "[agent][tool-result-artifacts] persisted envelope not smaller than raw result tool={} original_bytes={} final_bytes={} budget_bytes={} -- keeping envelope for its artifact_path pointer",
- tool_name,
- original_bytes,
- final_bytes,
- budget_bytes
- );
- }
- log::info!(
- "[agent][tool-result-artifacts] persisted oversized tool result tool={} original_bytes={} stored_bytes={} path={} redacted={}",
- tool_name,
- persisted.original_bytes,
- persisted.stored_bytes,
- persisted.path,
- persisted.redactions.changed()
- );
- return (
- output,
- ToolResultArtifactOutcome {
- // 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),
- },
- );
- }
- Err(err) => {
- log::warn!(
- "[agent][tool-result-artifacts] persist failed tool={} original_bytes={} err={} — falling back to inline truncation",
- tool_name,
- original_bytes,
- err
- );
- }
- }
- }
-
- // Reached two ways, and only one of them was audible: a persist that FAILED
- // warns just above, but a run with no artifact store configured falls
- // through to here silently — the oversized tail is discarded with nothing
- // recording that it happened. Say so, so "where did the rest of my search
- // result go" is answerable from the logs rather than by reading this
- // function.
- if store.is_none() {
- log::info!(
- "[agent][tool-result-artifacts] no artifact store configured; truncating oversized tool result inline tool={} original_bytes={} budget_bytes={} — the tail is discarded, not recoverable",
- tool_name,
- original_bytes,
- budget_bytes
- );
- }
- let (output, BudgetOutcome { final_bytes, .. }) =
- apply_tool_result_budget(content, budget_bytes);
- (
- output,
- ToolResultArtifactOutcome {
- original_bytes,
- final_bytes,
- persisted: false,
- artifact_path: None,
- },
- )
-}
-
-pub(crate) async fn spill_aggregate_tool_results(
- results: &mut [ToolOutcome],
- store: Option<&ToolResultArtifactStore>,
+ read: &ArtifactRead,
budget_bytes: usize,
-) {
- if budget_bytes == 0 {
- return;
- }
- let Some(store) = store else {
- return;
- };
-
- let mut total: usize = results.iter().map(|result| result.output.len()).sum();
- if total <= budget_bytes {
- return;
- }
-
- let mut indexes: Vec<usize> = (0..results.len()).collect();
- indexes.sort_by_key(|idx| std::cmp::Reverse(results[*idx].output.len()));
-
- for idx in indexes {
- if total <= budget_bytes {
- break;
- }
- let original = results[idx].output.clone();
- let original_len = original.len();
- let allowed_len = budget_bytes.saturating_sub(total.saturating_sub(original_len));
- let persisted_output = if looks_like_preview_envelope(&original) {
- Ok(PersistedToolResult {
- output: original.clone(),
- path: "<existing-preview>".to_string(),
- original_bytes: original_len,
- stored_bytes: original_len,
- redactions: SanitizationReport::default(),
- })
- } else {
- store
- .persist(
- &results[idx].name,
- results[idx].tool_call_id.as_deref(),
- &original,
- None,
- allowed_len.min(AGGREGATE_PREVIEW_BUDGET_BYTES),
- "aggregate tool-result budget exceeded",
- )
- .await
- };
- match persisted_output {
- Ok(persisted) => {
- // #4469 item 6: never bound the preview envelope below the minimum
- // that preserves its `[tool_result_preview]` header + artifact
- // pointer — `allowed_len` can be 0 here, which would blank the
- // result and strip the `artifact_path` the model reads to recover
- // the full output.
- let envelope_allowance = allowed_len.max(MIN_ENVELOPE_ALLOWANCE_BYTES);
- let (output, final_bytes) =
- bound_text_to_budget(persisted.output, envelope_allowance);
- total = total
- .saturating_sub(original_len)
- .saturating_add(final_bytes);
- log::info!(
- "[agent][tool-result-artifacts] aggregate spill tool={} original_bytes={} final_bytes={} total_bytes={} path={}",
- results[idx].name,
- original_len,
- final_bytes,
- total,
- persisted.path
- );
- results[idx].output = output;
- }
- Err(err) => {
- log::warn!(
- "[agent][tool-result-artifacts] aggregate spill failed tool={} bytes={} err={} -- falling back to inline budget trim",
- results[idx].name,
- original_len,
- err
- );
- let (output, final_bytes) = bound_text_to_budget(original, allowed_len);
- total = total
- .saturating_sub(original_len)
- .saturating_add(final_bytes);
- results[idx].output = output;
- }
- }
- }
-}
-
-fn looks_like_preview_envelope(value: &str) -> bool {
- value.starts_with("[tool_result_preview]\n")
-}
-
-fn bound_text_to_budget(content: String, budget_bytes: usize) -> (String, usize) {
- if budget_bytes == 0 {
- return (String::new(), 0);
- }
- let (mut output, BudgetOutcome { final_bytes, .. }) =
- apply_tool_result_budget(content, budget_bytes);
- if final_bytes <= budget_bytes {
- return (output, final_bytes);
- }
- let cut = crate::util::floor_char_boundary(&output, budget_bytes);
- output.truncate(cut);
- let final_bytes = output.len();
- (output, final_bytes)
-}
-
-fn sanitize_component(value: &str) -> String {
- let mut out = String::with_capacity(value.len().min(80));
- for ch in value.chars().take(80) {
- if ch.is_ascii_alphanumeric() || ch == '-' || ch == '_' {
- out.push(ch);
- } else {
- out.push('_');
- }
- }
- if out.is_empty() {
- "unknown".to_string()
- } else {
- out
- }
-}
-
-fn assert_within_action_dir(action_dir: &Path, path: &Path) -> anyhow::Result<()> {
- if path.starts_with(action_dir) {
- return Ok(());
- }
- anyhow::bail!(
- "tool-result artifact path escaped action_dir: {}",
- path.display()
- );
+) -> String {
+ tool_results::page_artifact_read(content, read, budget_bytes, READ_TOOL)
}
#[cfg(test)]
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 4251191674..3cd17ca532 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
@@ -1,15 +1,17 @@
use super::*;
use crate::security::{AutonomyLevel, SecurityPolicy};
-use crate::tools::FileReadTool;
use serde_json::json;
use std::sync::Arc;
-use std::time::Duration;
+use tinyagents_harness::artifacts::tool_results::apply_per_result_persistence;
use tinytools::Tool;
+/// End to end through OpenHuman's wiring: the real `sanitize_text` redacts the
+/// stored body and the preview, and the real `file_read` opens the artifact at
+/// the path the envelope names.
#[tokio::test]
async fn threshold_persists_preview_and_readable_file() {
let tmp = tempfile::tempdir().unwrap();
- let store = ToolResultArtifactStore::new(tmp.path().to_path_buf(), "session/one");
+ let store = new_tool_result_store(tmp.path().to_path_buf(), "session/one");
let raw = format!(
"{} {}",
"x".repeat(4096),
@@ -50,441 +52,45 @@ async fn threshold_persists_preview_and_readable_file() {
.contains("ghp_abcdefghijklmnopqrstuvwxyz123456"));
}
-#[tokio::test]
-async fn fallback_truncates_when_store_missing() {
- let raw = "z".repeat(4096);
- 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);
-}
-
-/// The truncation trailer must not tell the model to re-run the call (#6408).
-///
-/// The old wording ended "re-run with a narrower query to see the rest". A
-/// listing tool with no narrowing argument in reach leaves the model only the
-/// identical call, which returns the identical truncation, until the
-/// successful-repeat tracker halts the run. Assert the retry instruction is
-/// gone and the deterministic-truncation statement that replaces it is
-/// present, so a revert to the old trailer fails here.
-#[tokio::test]
-async fn truncation_trailer_does_not_instruct_a_retry() {
- let raw = "z".repeat(4096);
- let (out, outcome) =
- apply_per_result_persistence(raw, None, None, "GITHUB_LIST_PULL_REQUESTS", None, 512).await;
-
- assert!(
- !outcome.persisted,
- "fixture must truncate inline, not persist"
- );
- assert!(
- !out.contains("re-run"),
- "trailer must not instruct a re-run; got: {out}"
- );
- assert!(
- out.contains("Repeating this call returns the same truncation"),
- "trailer must say the truncation is deterministic; got: {out}"
- );
- // Both totals, so the model can judge whether the retained head suffices.
- assert!(
- out.contains("of 4096 bytes truncated by tool_result_budget"),
- "trailer must report dropped-of-original bytes; got: {out}"
- );
-}
-
-/// The sweep bounds growth without touching the live session (#6408).
-///
-/// Nothing else deletes these files, so an unbounded artifact directory would
-/// trade a token-burn bug for a disk-growth one. Asserts both halves: a stale
-/// OTHER session is removed, and the CURRENT session survives regardless of
-/// age — a sweep that collected the running session's own artifacts would
-/// delete the bodies the model is about to read back.
-#[tokio::test]
-async fn prune_removes_stale_sessions_but_never_the_current_one() {
- let tmp = tempfile::tempdir().unwrap();
- let root = tmp.path().join("artifacts/tool-results");
- let current = root.join("live-session");
- let stale = root.join("old-session");
- std::fs::create_dir_all(&current).unwrap();
- std::fs::create_dir_all(&stale).unwrap();
- std::fs::write(current.join("a.txt"), "current").unwrap();
- std::fs::write(stale.join("b.txt"), "stale").unwrap();
-
- let store = ToolResultArtifactStore::new(tmp.path().to_path_buf(), "live-session");
-
- // Nothing is old enough yet: a generous window must collect nothing.
- assert_eq!(
- store
- .prune_stale_sessions(Duration::from_secs(3600))
- .unwrap(),
- 0
- );
- assert!(stale.exists(), "nothing is stale within the window");
-
- // A zero window makes every directory stale, so only the current-session
- // exemption can save `live-session`.
- let removed = store.prune_stale_sessions(Duration::from_secs(0)).unwrap();
- assert_eq!(
- removed, 1,
- "exactly the one other session should be collected"
- );
- assert!(!stale.exists(), "stale session dir must be removed");
- assert!(
- current.join("a.txt").exists(),
- "the current session's artifacts must survive its own sweep"
- );
-}
-
-/// A missing artifact root is the normal first-run case, not an error.
-#[tokio::test]
-async fn prune_is_a_noop_when_no_artifacts_exist() {
- let tmp = tempfile::tempdir().unwrap();
- let store = ToolResultArtifactStore::new(tmp.path().to_path_buf(), "session");
- assert_eq!(
- store.prune_stale_sessions(Duration::from_secs(0)).unwrap(),
- 0
- );
-}
-
-#[tokio::test]
-async fn persisted_preview_is_bounded_for_small_budget() {
- let tmp = tempfile::tempdir().unwrap();
- let store = ToolResultArtifactStore::new(tmp.path().to_path_buf(), "session");
- let raw = "x".repeat(800);
-
- let (out, outcome) =
- 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);
- assert_eq!(out.len(), outcome.final_bytes);
- assert!(out.contains("[tool_result_preview]"));
- assert!(tmp
- .path()
- .join("artifacts/tool-results/session/shell/call.txt")
- .exists());
-}
-
-#[tokio::test]
-async fn aggregate_spills_largest_until_under_budget() {
- let tmp = tempfile::tempdir().unwrap();
- let store = ToolResultArtifactStore::new(tmp.path().to_path_buf(), "session");
- let mut results = vec![
- ToolOutcome {
- name: "small".into(),
- output: "a".repeat(100),
- success: true,
- tool_call_id: Some("small".into()),
- trusted_verbatim: false,
- },
- ToolOutcome {
- name: "largest".into(),
- output: "b".repeat(2000),
- success: true,
- tool_call_id: Some("largest".into()),
- trusted_verbatim: false,
- },
- ToolOutcome {
- name: "medium".into(),
- output: "c".repeat(900),
- success: true,
- tool_call_id: Some("medium".into()),
- trusted_verbatim: false,
- },
- ];
-
- spill_aggregate_tool_results(&mut results, Some(&store), 1800).await;
-
- assert!(results[1].output.starts_with("[tool_result_preview]\n"));
- let total: usize = results.iter().map(|result| result.output.len()).sum();
- assert!(total <= 1800, "total={total}");
- assert!(!results[0].output.starts_with("[tool_result_preview]\n"));
- assert!(tmp
- .path()
- .join("artifacts/tool-results/session/largest/largest.txt")
- .exists());
-}
-
-#[tokio::test]
-async fn aggregate_forces_budget_when_envelope_has_no_savings() {
- let tmp = tempfile::tempdir().unwrap();
- let store = ToolResultArtifactStore::new(tmp.path().to_path_buf(), "session");
- let mut results = vec![
- ToolOutcome {
- name: "one".into(),
- output: "a".repeat(350),
- success: true,
- tool_call_id: Some("one".into()),
- trusted_verbatim: false,
- },
- ToolOutcome {
- name: "two".into(),
- output: "b".repeat(350),
- success: true,
- tool_call_id: Some("two".into()),
- trusted_verbatim: false,
- },
- ToolOutcome {
- name: "three".into(),
- output: "c".repeat(350),
- success: true,
- tool_call_id: Some("three".into()),
- trusted_verbatim: false,
- },
- ];
-
- spill_aggregate_tool_results(&mut results, Some(&store), 500).await;
-
- let total: usize = results.iter().map(|result| result.output.len()).sum();
- // #4469 item 6: the aggregate spill now floors each persisted envelope at
- // MIN_ENVELOPE_ALLOWANCE_BYTES so the `[tool_result_preview]` header +
- // `artifact_path` pointer always survives (previously an exhausted budget
- // could blank a result to ""). That is a documented trade — the total may
- // slightly overshoot the raw aggregate budget — so the invariant is now:
- // (a) no envelope is blanked, and (b) the total stays bounded by the
- // per-result floor rather than the raw budget.
- assert!(
- results.iter().all(|result| !result.output.is_empty()),
- "no persisted envelope may be blanked — the artifact pointer must survive"
- );
- assert!(
- total <= results.len() * MIN_ENVELOPE_ALLOWANCE_BYTES,
- "total={total} exceeds the per-result envelope floor bound"
- );
- assert!(tmp
- .path()
- .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}");
-}
-
+/// The vocabulary passed to the crate is OpenHuman's: `file_read` reads,
+/// `use_skill` is the only wrapper followed.
#[test]
-fn artifact_read_target_matches_only_file_read_under_the_artifact_directory() {
+fn read_targets_use_openhumans_tool_names() {
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"})
+ "use_skill",
+ &json!({"skill": "files", "tool": "file_read", "args": {"path": path, "offset": 3}})
)
- .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"
- );
+ .is_some_and(|read| read.offset == 3));
+ assert!(artifact_read_target("glob", &json!({"path": path})).is_none());
}
+/// A continuation names `file_read` and the offset, in the wire format the
+/// model has always seen.
#[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"
- );
- }
-}
-
-#[test]
-fn a_page_near_the_maximum_offset_neither_overflows_nor_advertises_a_stuck_continuation() {
+fn a_page_names_file_read_as_the_continuation() {
let read = ArtifactRead {
path: "artifacts/tool-results/s/shell/c.txt".to_string(),
- offset: usize::MAX - 10,
+ offset: 0,
};
- // The offset comes straight from the model's arguments, so the page
- // arithmetic must not overflow on an absurd one.
- let page = std::panic::catch_unwind(|| page_artifact_read("q".repeat(5_000), &read, 1_000));
- assert!(
- page.is_ok(),
- "an offset near usize::MAX must not overflow the page arithmetic"
- );
- let page = page.unwrap();
- assert!(
- page.len() <= 1_000,
- "the result is still bounded, got {} bytes",
- page.len()
- );
+ let page = page_artifact_read("y".repeat(5_000), &read, 1_000);
assert!(
- !page.contains("Continue with"),
- "no continuation may be advertised when the next offset cannot advance"
+ page.contains("Continue with file_read {\"path\":\"artifacts/tool-results/s/shell/c.txt\",\"offset\":"),
+ "{page}"
);
}
-#[test]
-fn artifact_read_target_rejects_an_explicit_invalid_offset() {
- let path = "artifacts/tool-results/s/shell/c.txt";
- for bad in [json!(-1), json!(1.5), json!("12")] {
- assert_eq!(
- artifact_read_target("file_read", &json!({"path": path, "offset": bad.clone()})),
- None,
- "offset {bad} is not a read file_read serves, so it must not become an artifact read at 0"
- );
- }
- for absent in [json!({"path": path}), json!({"path": path, "offset": null})] {
- assert_eq!(
- artifact_read_target("file_read", &absent).map(|read| read.offset),
- Some(0),
- "an absent or null offset reads from the start"
- );
- }
+/// The read limit is `file_read`'s own: a body whose redacted form it would
+/// refuse is never stored, so the preview never points at an unreadable file.
+#[tokio::test]
+async fn the_store_is_bounded_by_file_reads_limit() {
+ let tmp = tempfile::tempdir().unwrap();
+ let store = new_tool_result_store(tmp.path().to_path_buf(), "s");
+ let too_big = "z".repeat(FileReadTool::MAX_FILE_SIZE_BYTES as usize + 1);
+ let (out, outcome) =
+ apply_per_result_persistence(too_big, None, Some(&store), "shell", Some("c"), 1024).await;
+ assert!(!outcome.persisted, "an unreadable body must truncate inline");
+ assert!(out.contains("truncated by tool_result_budget"));
+ assert!(!tmp.path().join("artifacts").exists());
}
diff --git a/crates/openhuman-core/src/agent/session_host/builder/mod.rs b/crates/openhuman-core/src/agent/session_host/builder/mod.rs
index ec0b570adc..ab6baa9276 100644
--- a/crates/openhuman-core/src/agent/session_host/builder/mod.rs
+++ b/crates/openhuman-core/src/agent/session_host/builder/mod.rs
@@ -164,7 +164,8 @@ pub(super) fn visible_tool_specs_for_policy(
// `durable_tool_specs` is meant to stay the unscoped truth.
// This copies exactly the one spec being rewritten and leaves
// the other ~48 visible schemas shared.
- return crate::tools::toolpacks::scope_use_skill_spec(
+ return tinyagents_harness::tool::packs::scope_use_skill_spec(
+ &crate::tools::toolpacks::CATALOG,
Arc::make_mut(&mut spec),
&is_callable,
)
diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware/tool_policy.rs b/crates/openhuman-core/src/agent/tinyagents/middleware/tool_policy.rs
index 8a6e11d7ae..562fea6283 100644
--- a/crates/openhuman-core/src/agent/tinyagents/middleware/tool_policy.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/middleware/tool_policy.rs
@@ -131,6 +131,7 @@ impl ToolPolicyMiddleware {
})
.collect();
tinyagents_harness::tool::packs::NoSuchPackTool {
+ not_found_marker: crate::tools::status::NOT_FOUND_MARKER,
skill: pack.id,
tool,
callable,
@@ -170,7 +171,8 @@ impl ToolPolicyMiddleware {
let route = crate::tools::toolpacks::pack(skill)
.map(|pack| self.route_for_pack(pack))
.unwrap_or_default();
- let rendered = crate::tools::toolpacks::render_pack_filtered(
+ let rendered = tinyagents_harness::tool::packs::render_pack_filtered(
+ &crate::tools::toolpacks::CATALOG,
skill,
handle,
// The same predicate the gate applies to `use_skill`'s inner tool.