Skip to content

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

fix(agent): wire the tool-result artifact store on the session-host path

M3gA-Mindf49682546165
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 d82b7c7c1c..49f80650d3 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
@@ -300,6 +300,14 @@ impl Store for ToolResultArtifactIndexStore {
}
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,
@@ -307,6 +315,64 @@ impl ToolResultArtifactStore {
}
}
+ /// 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)
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 e606ccf66e..a49ca7f56c 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
@@ -3,6 +3,7 @@ use crate::security::{AutonomyLevel, SecurityPolicy};
use crate::tools::FileReadTool;
use serde_json::json;
use std::sync::Arc;
+use std::time::Duration;
use tinytools::Tool;
#[tokio::test]
@@ -89,6 +90,60 @@ async fn truncation_trailer_does_not_instruct_a_retry() {
);
}
+/// 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();
diff --git a/crates/openhuman-core/src/agent/session_host/artifact_wiring.rs b/crates/openhuman-core/src/agent/session_host/artifact_wiring.rs
new file mode 100644
index 0000000000..2882b09a32
--- /dev/null
+++ b/crates/openhuman-core/src/agent/session_host/artifact_wiring.rs
@@ -0,0 +1,83 @@
+//! Where the session host's tool-result artifact store comes from (#6408).
+//!
+//! Extracted from `runtime_session.rs` rather than inlined there: the choice of
+//! root is the whole correctness question for this feature, and it needs more
+//! prose than a call site should carry.
+
+use std::path::{Path, PathBuf};
+
+use crate::agent::harness::tool_result_artifacts::ToolResultArtifactStore;
+
+/// How long another session's tool-result artifacts survive before a later
+/// session sweeps them.
+///
+/// **A conservative default chosen for safety, not a retention policy.** The
+/// artifact store had no bound at all — nothing anywhere deletes these files —
+/// and shipping unbounded growth in the user's action workspace to fix a
+/// token-burn bug would trade one problem for another. This is the smallest
+/// thing that cannot grow without limit; the feature's owner should confirm or
+/// replace it.
+///
+/// Alternatives considered: a count cap (needs a policy for which artifacts are
+/// worth keeping, which this code has no basis to decide), and a sweep at
+/// session end (there is no single point where a session host ends, and a crash
+/// would skip it entirely). Age is the only one of the three that is correct
+/// without knowing the workload.
+///
+/// 24 hours because an artifact is only useful while the run that produced it
+/// can still read it back, which is bounded by a turn — a day is already far
+/// more generous than that window, and leaves a working day of artifacts
+/// available for debugging a session after the fact.
+const ARTIFACT_RETENTION: std::time::Duration = std::time::Duration::from_secs(24 * 60 * 60);
+
+/// Where artifacts are written, chosen to match where the READ path will look.
+///
+/// The store writes under `<root>/artifacts/tool-results/…` but hands the model
+/// a RELATIVE pointer, which `file_read` later resolves through
+/// `security_for_tool_context` (`tools/impl/filesystem/mod.rs`). That function
+/// overwrites `action_dir` with `ctx.workspace().root` whenever the turn carries
+/// a workspace descriptor — and `turn()` sets `context.workspace` from the
+/// host's own descriptor. So on a turn bound to a per-turn workspace, rooting
+/// the store at `action_dir` writes artifacts the model cannot dereference: a
+/// pointer to nothing, which is strictly worse than the inline truncation it
+/// replaces, since that at least returns the head.
+///
+/// The descriptor is only `Some` when the embedder set a per-turn root, and in
+/// its absence the policy's own `action_dir` survives the read path untouched.
+/// Hence the same conditional on both sides rather than either one
+/// unconditionally — pinning one would break the other case in the other
+/// direction. Credit to the #6483 investigation for identifying the read-time
+/// override; this is its session-host counterpart.
+fn artifact_root(
+ workspace_descriptor: Option<&tinytools::WorkspaceDescriptor>,
+ action_dir: &Path,
+) -> PathBuf {
+ workspace_descriptor
+ .map(|descriptor| descriptor.root.clone())
+ .unwrap_or_else(|| action_dir.to_path_buf())
+}
+
+/// Build the store the turn path hands to `TurnContextMiddleware`, sweeping
+/// other sessions' stale artifacts on the way.
+///
+/// The sweep is best-effort by design: a failed prune must never fail a turn,
+/// because the worst it costs is disk, while failing the turn costs the user
+/// their message.
+pub(super) fn build_artifact_store(
+ workspace_descriptor: Option<&tinytools::WorkspaceDescriptor>,
+ action_dir: &Path,
+ session_key: &str,
+) -> ToolResultArtifactStore {
+ let store =
+ ToolResultArtifactStore::new(artifact_root(workspace_descriptor, action_dir), session_key);
+ match store.prune_stale_sessions(ARTIFACT_RETENTION) {
+ Ok(0) => {}
+ Ok(removed) => log::debug!(
+ "[agent][tool-result-artifacts] pruned {removed} stale artifact session dir(s)"
+ ),
+ Err(error) => {
+ log::warn!("[agent][tool-result-artifacts] artifact prune failed (continuing): {error}")
+ }
+ }
+ store
+}
diff --git a/crates/openhuman-core/src/agent/session_host/mod.rs b/crates/openhuman-core/src/agent/session_host/mod.rs
index 7c7cf62e58..4334c8864c 100644
--- a/crates/openhuman-core/src/agent/session_host/mod.rs
+++ b/crates/openhuman-core/src/agent/session_host/mod.rs
@@ -64,6 +64,7 @@ pub use types::{OpenHumanSessionHost, SessionHostBuilder, TurnOverrides};
pub(crate) use builder::dedup_visible_tool_specs;
mod announcement_notes;
+mod artifact_wiring;
#[cfg(test)]
mod runtime_adapter_tests;
diff --git a/crates/openhuman-core/src/agent/session_host/runtime_adapter_tests.rs b/crates/openhuman-core/src/agent/session_host/runtime_adapter_tests.rs
index febe359560..e83a46cc88 100644
--- a/crates/openhuman-core/src/agent/session_host/runtime_adapter_tests.rs
+++ b/crates/openhuman-core/src/agent/session_host/runtime_adapter_tests.rs
@@ -479,3 +479,103 @@ fn a_subagent_thread_binding_claims_no_session_identity() {
child.set_thread_id(Some("thread-1"));
assert_eq!(child.session_id(), None);
}
+
+/// The PRODUCTION turn path must wire an artifact store, rooted where the READ
+/// path will look for it (#6408).
+///
+/// Two assertions, and both were dead code before this PR. The existing artifact
+/// tests construct `TurnContextMiddleware` with `artifact_store: Some(..)`
+/// themselves, so they prove the offload code works while saying nothing about
+/// whether production ever reaches it — and it did not: the production
+/// constructor hard-coded `None`, which is how a whole feature shipped dead.
+///
+/// The root matters as much as the wiring. The store hands the model a RELATIVE
+/// pointer, resolved later by `file_read` through `security_for_tool_context`,
+/// which overwrites `action_dir` with `ctx.workspace().root` when the turn
+/// carries a descriptor. Rooting the store at `action_dir` regardless would
+/// write artifacts the model cannot dereference — strictly worse than the
+/// truncation it replaces. So this drives a real host with a descriptor whose
+/// root is NOT `action_dir`, and pins that the store followed the descriptor.
+///
+#[tokio::test]
+async fn production_turn_path_wires_an_artifact_store_at_the_read_path_root() {
+ let action_dir = tempfile::tempdir().expect("tempdir");
+ let turn_root = tempfile::tempdir().expect("turn root");
+ assert_ne!(
+ action_dir.path(),
+ turn_root.path(),
+ "the two roots must differ or this test cannot tell them apart"
+ );
+
+ let model: Arc<dyn tinyinference_llm::model::ChatModel<()>> =
+ Arc::new(tinyagents_harness::testkit::ScriptedModel::new(Vec::new()));
+ let mut host = crate::agent::SessionHostBuilder::new()
+ .chat_model(model)
+ .tools(Vec::new())
+ .action_dir(action_dir.path().to_path_buf())
+ .memory(crate::memory::test_support::noop_memory())
+ .tool_dispatcher(Box::new(tinytools_agent::dialect::XmlDialect))
+ .workspace_descriptor(Some(
+ tinytools::WorkspaceDescriptor::new(turn_root.path().to_path_buf())
+ .with_policy_id("turn-workspace"),
+ ))
+ .build()
+ .expect("session build");
+
+ host.ensure_runtime_session()
+ .expect("ensure runtime session");
+
+ let state = host
+ .runtime_state
+ .lock()
+ .unwrap_or_else(|poisoned| poisoned.into_inner());
+ let middleware = state
+ .context_middleware
+ .as_ref()
+ .expect("the turn path must retain its context middleware");
+ let store = middleware.artifact_store.as_ref().expect(
+ "the production turn path must wire an artifact store, or oversized \
+ tool results are truncated with their tail discarded (#6408)",
+ );
+ assert_eq!(
+ store.root(),
+ turn_root.path(),
+ "the store must be rooted at the turn workspace the read path resolves \
+ against, not at action_dir — otherwise the pointer handed to the model \
+ dereferences to nothing (#6483)"
+ );
+}
+
+/// With no workspace descriptor the read path keeps the policy's own
+/// `action_dir`, so the store must too. The mirror of the test above: pinning
+/// only one branch would let the other regress silently.
+#[tokio::test]
+async fn artifact_store_falls_back_to_action_dir_without_a_descriptor() {
+ let action_dir = tempfile::tempdir().expect("tempdir");
+ let model: Arc<dyn tinyinference_llm::model::ChatModel<()>> =
+ Arc::new(tinyagents_harness::testkit::ScriptedModel::new(Vec::new()));
+ let mut host = crate::agent::SessionHostBuilder::new()
+ .chat_model(model)
+ .tools(Vec::new())
+ .action_dir(action_dir.path().to_path_buf())
+ .memory(crate::memory::test_support::noop_memory())
+ .tool_dispatcher(Box::new(tinytools_agent::dialect::XmlDialect))
+ .build()
+ .expect("session build");
+
+ host.ensure_runtime_session()
+ .expect("ensure runtime session");
+
+ let state = host
+ .runtime_state
+ .lock()
+ .unwrap_or_else(|poisoned| poisoned.into_inner());
+ let store = state
+ .context_middleware
+ .as_ref()
+ .expect("context middleware")
+ .artifact_store
+ .as_ref()
+ .expect("artifact store");
+ assert_eq!(store.root(), action_dir.path());
+}
diff --git a/crates/openhuman-core/src/agent/session_host/runtime_session.rs b/crates/openhuman-core/src/agent/session_host/runtime_session.rs
index 45b760bab6..e0391b88db 100644
--- a/crates/openhuman-core/src/agent/session_host/runtime_session.rs
+++ b/crates/openhuman-core/src/agent/session_host/runtime_session.rs
@@ -39,7 +39,7 @@ pub(super) struct OpenHumanSessionState {
terminals: Vec<SessionTerminal>,
pub(super) last_turn_hit_cap: bool,
pub(super) last_turn_usage: Option<crate::agent::tinyagents::host::LastTurnUsage>,
- context_middleware: Option<TurnContextMiddleware>,
+ pub(super) context_middleware: Option<TurnContextMiddleware>,
required_output: Option<tinyagents_harness::config::RequiredOutput>,
pub(crate) pending_turn_overrides: super::types::TurnOverrides,
pub(super) active_turn_overrides: super::types::TurnOverrides,
@@ -1435,11 +1435,19 @@ impl OpenHumanSessionHost {
context.autocompact_enabled(),
)
};
+ let artifact_store = super::artifact_wiring::build_artifact_store(
+ self.workspace_descriptor.as_ref(),
+ &self.action_dir,
+ &self.event_session_id,
+ );
+
let context_mw = TurnContextMiddleware {
tool_result_budget_bytes,
payload_summarizer: self.payload_summarizer.clone(),
task_hint: None,
- artifact_store: None,
+ // Was `None` in both production constructors; `artifact_wiring`
+ // documents why its root is the correctness question (#6408, #6483).
+ artifact_store: Some(artifact_store),
tokenjuice_compaction_enabled,
tokenjuice_compression: self.tokenjuice_compression,
runtime_config: self.runtime_config.clone(),
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 5512d8e35a..aeea16e757 100644
--- a/crates/openhuman-core/src/agent/tinyagents/middleware/turn_context.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/middleware/turn_context.rs
@@ -348,6 +348,19 @@ impl TurnContextMiddleware {
tool_result_budget_bytes: DEFAULT_TOOL_RESULT_BUDGET_BYTES,
payload_summarizer: None,
task_hint: None,
+ // Deliberately `None` on the channel / sub-agent path (#6408).
+ //
+ // This constructor has no session context, so it has no
+ // `action_dir` to root the store at. Handing it any other directory
+ // would write artifacts the model cannot read back:
+ // `artifact_read_target` only recognises a `file_read` under the
+ // action workspace's `artifacts/tool-results/…`, so an artifact
+ // written elsewhere yields a pointer that resolves to nothing —
+ // strictly worse than the inline truncation it replaced, which at
+ // least returns the head. Sub-agent turns therefore keep today's
+ // truncation until a real `action_dir` is threaded through here.
+ // Tracked as #6483 — delegated turns are where oversized results are
+ // most likely, so this gap is not cosmetic.
artifact_store: None,
tokenjuice_compaction_enabled: false,
tokenjuice_compression: AgentTokenjuiceCompression::Off,