Skip to content

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

refactor(prompts): delegate AGENTS.md loading and prompt sections to tinyagents-harness

Steven Enamakela463c7d49d95
diff --git a/crates/openhuman-core/src/agent/prompts/agents_md.rs b/crates/openhuman-core/src/agent/prompts/agents_md.rs
index 76934eba6d..556162016b 100644
--- a/crates/openhuman-core/src/agent/prompts/agents_md.rs
+++ b/crates/openhuman-core/src/agent/prompts/agents_md.rs
@@ -1,235 +1,24 @@
-//! AGENTS.md instruction loading — OpenHuman's analog of Claude Code's
-//! `CLAUDE.md` / Codex's `AGENTS.md`.
-//!
-//! Loads configurable instruction text from `AGENTS.md` files at two layers:
-//!
-//! 1. **Global** — `<workspace_dir>/AGENTS.md`: the user's OpenHuman workspace
-//! (where `SOUL.md` / `USER.md` already live). Applies to every run.
-//! 2. **Local / project** — `<effective action_dir>/AGENTS.md`: the folder the
-//! agent is actually operating in. For sub-agent runs with a
-//! `worktree_action_dir` override, that override dir is the local layer.
-//!
-//! The loaded strings are threaded into
-//! [`crate::agent::prompts::PromptContext`] and rendered by
-//! `AgentsInstructionsSection` **once at system-prompt build time** — never
-//! re-read per turn — so the frozen system-prompt prefix / KV-cache contract is
-//! preserved. Missing, unreadable, or empty files are silently skipped. The
-//! renderer caps each layer at
-//! [`crate::agent::prompts::BOOTSTRAP_MAX_CHARS`] with a
-//! `[... truncated]` marker.
+//! OpenHuman's path-policy adapter for the TinyAgents `AGENTS.md` loader.
-use super::types::BOOTSTRAP_MAX_CHARS;
-use std::io::Read;
use std::path::Path;
-/// The instruction file name loaded at each layer.
-pub const AGENTS_MD_FILENAME: &str = "AGENTS.md";
+pub use tinyagents_harness::context::{
+ AGENTS_MD_FILENAME, AgentsMdContent, MAX_AGENTS_MD_READ_BYTES,
+};
-/// Hard cap on the number of bytes read from an `AGENTS.md` before the
-/// renderer's per-layer character cap ([`BOOTSTRAP_MAX_CHARS`]) applies.
-///
-/// `AGENTS.md` is an untrusted, user/project-controlled file. Reading it whole
-/// via `read_to_string` would allocate an arbitrarily large buffer — a
-/// multi-megabyte file could stall prompt construction or exhaust memory
-/// **before** the renderer ever gets a chance to truncate. Bounding the read
-/// here fixes that at the root. At UTF-8's worst case of 4 bytes per character
-/// this budget still yields at least `BOOTSTRAP_MAX_CHARS` characters (plus
-/// slack), so the renderer's cap + `[... truncated]` marker still fire exactly
-/// as before for any file large enough to matter — the read bound is invisible
-/// to well-formed files and only clamps pathological ones.
-const MAX_AGENTS_MD_READ_BYTES: u64 = (BOOTSTRAP_MAX_CHARS as u64) * 4 + 1024;
-
-/// Pre-loaded `AGENTS.md` contents for the global + local layers.
-///
-/// Both fields are `None` when the corresponding file is absent / empty /
-/// unreadable, or (for `local`) when it deduplicates against the global layer.
-#[derive(Debug, Clone, Default, PartialEq, Eq)]
-pub struct AgentsMdContent {
- /// `<workspace_dir>/AGENTS.md` — the workspace-global layer.
- pub global: Option<String>,
- /// `<effective action_dir>/AGENTS.md` — the project layer. `None` when the
- /// local dir resolves to the same path as the workspace dir (the file is
- /// then loaded once, into [`Self::global`]).
- pub local: Option<String>,
-}
-
-impl AgentsMdContent {
- /// Whether either layer carries content.
- pub fn is_empty(&self) -> bool {
- self.global.is_none() && self.local.is_none()
- }
-}
-
-/// Load a single `AGENTS.md` from `dir`.
-///
-/// Returns `Some(trimmed_content)` when the file exists, is readable, and is
-/// non-empty after trimming. Missing / unreadable / empty files yield `None`
-/// (silently skipped) — callers inject the result unconditionally without a
-/// noisy placeholder. Never logs the file contents, only paths and sizes.
+/// Load one instruction file after applying OpenHuman's path-root policy.
pub fn load_agents_md(dir: &Path) -> Option<String> {
- let path = dir.join(AGENTS_MD_FILENAME);
- // Path hardening (race-free): the project-layer AGENTS.md lives in the
- // agent's user/project-controlled action dir, so a checkout could make it a
- // symlink pointing outside the root (a home-directory secret, a device node)
- // and have its bytes read into the system prompt and shipped to the
- // configured inference provider. We open with `O_NOFOLLOW` (Unix), so the
- // kernel atomically refuses to follow a final-component symlink at open
- // time — there is no stat-then-open window a racing writer could exploit by
- // swapping a checked regular file for a symlink. We then fstat the *opened*
- // handle and require a regular file (rejecting a directory / FIFO / socket /
- // device substituted in the same race), and — defence in depth against a
- // symlinked *parent* component — require the canonical path to stay under
- // `dir` (mirroring `validate_path_within_root`, used for agent-definition
- // TOML). All rejections skip silently, exactly like a missing file.
- let file = match open_no_follow(&path) {
- Ok(f) => f,
- Err(e) => {
- if is_symlink_refusal(&e) {
- log::warn!(
- "[agents_md] refusing to read symlinked {} (path hardening)",
- path.display()
- );
- } else if e.kind() == std::io::ErrorKind::NotFound {
- log::debug!("[agents_md] no AGENTS.md at {}", path.display());
- } else {
- log::debug!("[agents_md] failed to open {}: {e}", path.display());
- }
- return None;
- }
- };
- // fstat on the opened fd (race-free): reject anything that is not a regular
- // file — a directory, FIFO, socket, or device that slipped through.
- match file.metadata() {
- Ok(m) if m.is_file() => {}
- Ok(_) => {
- log::debug!(
- "[agents_md] {} is not a regular file; skipping",
- path.display()
- );
- return None;
- }
- Err(e) => {
- log::debug!("[agents_md] failed to stat opened {}: {e}", path.display());
- return None;
- }
- }
- if let Err(e) = crate::security::validate_path_within_root(&path, dir) {
- log::warn!(
- "[agents_md] refusing to read {} outside its root: {e}",
- path.display()
- );
- return None;
- }
- // Bounded read: never slurp an arbitrarily large untrusted file whole into
- // memory. We `take(MAX_AGENTS_MD_READ_BYTES)` rather than `read_to_string`,
- // so a pathological multi-MB AGENTS.md can't stall prompt construction or
- // exhaust memory before the renderer's char cap applies.
- let mut buf = Vec::new();
- if let Err(e) = file.take(MAX_AGENTS_MD_READ_BYTES).read_to_end(&mut buf) {
- log::debug!("[agents_md] failed to read {}: {e}", path.display());
- return None;
- }
- let hit_read_bound = buf.len() as u64 >= MAX_AGENTS_MD_READ_BYTES;
- // `from_utf8_lossy` tolerates a multi-byte char clipped at the read bound by
- // substituting the replacement character for the trailing partial bytes.
- let content = String::from_utf8_lossy(&buf);
- let trimmed = content.trim();
- if trimmed.is_empty() {
- log::debug!("[agents_md] skipped empty {}", path.display());
- return None;
- }
- if hit_read_bound {
- log::debug!(
- "[agents_md] {} exceeds {} bytes; read bounded before render-time cap",
- path.display(),
- MAX_AGENTS_MD_READ_BYTES
- );
- }
- log::debug!(
- "[agents_md] loaded {} ({} chars)",
- path.display(),
- trimmed.chars().count()
- );
- Some(trimmed.to_string())
-}
-
-/// Load the global + local `AGENTS.md` layers given the workspace dir and the
-/// effective local (action) dir.
-///
-/// Global renders first, local second (project instructions layered after).
-/// **Dedupe:** when the two dirs resolve to the same path the file is loaded
-/// once, into [`AgentsMdContent::global`], and `local` stays `None` so the same
-/// instructions are never injected twice.
-pub fn load_agents_md_layers(workspace_dir: &Path, local_dir: &Path) -> AgentsMdContent {
- let global = load_agents_md(workspace_dir);
- let same_dir = paths_equal(workspace_dir, local_dir);
- let local = if same_dir {
- log::debug!(
- "[agents_md] local dir {} == workspace dir; loaded once (deduped)",
- local_dir.display()
- );
- None
- } else {
- load_agents_md(local_dir)
- };
- AgentsMdContent { global, local }
-}
-
-/// Compare two directory paths for identity, canonicalizing when possible so
-/// `./foo` and `foo` (or symlinked equivalents) dedupe. Falls back to literal
-/// equality when canonicalization fails (e.g. a dir that does not exist yet).
-fn paths_equal(a: &Path, b: &Path) -> bool {
- match (std::fs::canonicalize(a), std::fs::canonicalize(b)) {
- (Ok(ca), Ok(cb)) => ca == cb,
- _ => a == b,
- }
-}
-
-/// Open `path` read-only while refusing to follow a final-component symlink.
-///
-/// On Unix this passes `O_NOFOLLOW` (the kernel returns `ELOOP`/`EMLINK` instead
-/// of opening the symlink target) plus `O_NONBLOCK` (never block on a FIFO /
-/// device a racing writer may substitute — it is rejected by the `is_file`
-/// fstat check afterwards). This closes the check-to-open race that a
-/// stat-then-`File::open` sequence would leave open. See [`load_agents_md`].
-#[cfg(unix)]
-fn open_no_follow(path: &Path) -> std::io::Result<std::fs::File> {
- use std::os::unix::fs::OpenOptionsExt;
- std::fs::OpenOptions::new()
- .read(true)
- .custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK)
- .open(path)
-}
-
-/// Non-Unix fallback: best-effort pre-open symlink check. Windows symlink
-/// creation requires elevation / developer mode, so the residual
-/// check-to-open race is low risk on these platforms.
-#[cfg(not(unix))]
-fn open_no_follow(path: &Path) -> std::io::Result<std::fs::File> {
- let meta = std::fs::symlink_metadata(path)?;
- if meta.file_type().is_symlink() {
- return Err(std::io::Error::new(
- std::io::ErrorKind::InvalidInput,
- "refusing to follow symlink",
- ));
- }
- std::fs::File::open(path)
-}
-
-/// Whether an [`open_no_follow`] error is the "refused a symlink" signal (as
-/// opposed to a genuine I/O failure), so the caller can log it distinctly.
-#[cfg(unix)]
-fn is_symlink_refusal(e: &std::io::Error) -> bool {
- // `O_NOFOLLOW` on a symlink yields `ELOOP` on Linux/macOS and `EMLINK` on
- // some BSDs — either way the open was refused *because* it was a symlink.
- matches!(e.raw_os_error(), Some(v) if v == libc::ELOOP || v == libc::EMLINK)
+ tinyagents_harness::context::load_agents_md(dir, |path, root| {
+ crate::security::validate_path_within_root(path, root).is_ok()
+ })
}
-#[cfg(not(unix))]
-fn is_symlink_refusal(e: &std::io::Error) -> bool {
- e.kind() == std::io::ErrorKind::InvalidInput
+/// Load the workspace and effective action-directory layers once each.
+pub fn load_agents_md_layers(workspace_dir: &Path, action_dir: &Path) -> AgentsMdContent {
+ tinyagents_harness::context::load_agents_md_layers(
+ workspace_dir,
+ action_dir,
+ true,
+ |path, root| crate::security::validate_path_within_root(path, root).is_ok(),
+ )
}
-
-#[cfg(test)]
-#[path = "agents_md_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/prompts/sections.rs b/crates/openhuman-core/src/prompts/sections.rs
index 8c3bdf8c97..4f7d1d8246 100644
--- a/crates/openhuman-core/src/prompts/sections.rs
+++ b/crates/openhuman-core/src/prompts/sections.rs
@@ -1,6 +1,6 @@
-//! Concrete [`PromptSection`] implementations.
+//! OpenHuman-owned prompt content sections.
//!
-//! Each unit struct renders one logical block of the system prompt.
+//! Each unit struct renders one logical block of OpenHuman's system prompt.
//! The rendering logic delegates to the free helpers in
//! workspace-file helpers re-exported by [`super`] for workspace-file injection and
//! sub-agent plumbing.
@@ -30,7 +30,7 @@ impl ArchetypePromptSection {
}
}
-impl PromptSection for ArchetypePromptSection {
+impl ArchetypePromptSection {
fn name(&self) -> &str {
"archetype_prompt"
}
@@ -59,23 +59,14 @@ impl DynamicPromptSection {
}
}
-impl PromptSection for DynamicPromptSection {
+impl tinyagents_harness::prompt::DynamicPromptSection<PromptContext<'_>> for DynamicPromptSection {
fn name(&self) -> &str {
"dynamic_prompt"
}
- fn tier(&self) -> PromptTier {
- // A builder that declares no tiers is treated as all-volatile, the
- // conservative reading: nothing stable is placed behind it by mistake.
- PromptTier::Volatile
- }
-
- fn build(&self, ctx: &PromptContext<'_>) -> Result<String> {
- (self.builder)(ctx)
- }
-
- fn build_parts(&self, ctx: &PromptContext<'_>) -> Result<Vec<(PromptTier, String)>> {
- let body = (self.builder)(ctx)?;
+ fn render(&self, ctx: &PromptContext<'_>) -> tinyagents_harness::Result<Vec<TieredPromptPart>> {
+ let body = (self.builder)(ctx)
+ .map_err(|error| tinyagents_harness::TinyAgentsError::Model(error.to_string()))?;
let has_marker =
body.contains(PROMPT_TIER_CONTEXT_MARKER) || body.contains(PROMPT_TIER_VOLATILE_MARKER);
// A builder that marks its tiers starts in `Stable`; one that does not
@@ -139,7 +130,7 @@ pub struct PersonalityRosterSection;
// PromptSection implementations
// ─────────────────────────────────────────────────────────────────────────────
-impl PromptSection for PersonalityRosterSection {
+impl PersonalityRosterSection {
fn tier(&self) -> PromptTier {
// Carries each personality's recent context, which the session rewrites.
PromptTier::Volatile
@@ -179,7 +170,7 @@ impl PromptSection for PersonalityRosterSection {
}
}
-impl PromptSection for IdentitySection {
+impl IdentitySection {
fn name(&self) -> &str {
"identity"
}
@@ -215,7 +206,7 @@ impl PromptSection for IdentitySection {
}
}
-impl PromptSection for AgentsInstructionsSection {
+impl AgentsInstructionsSection {
fn tier(&self) -> PromptTier {
// AGENTS.md layers: per project and per install, stable within a session.
PromptTier::Context
@@ -236,7 +227,7 @@ impl PromptSection for AgentsInstructionsSection {
}
}
-impl PromptSection for ToolsSection {
+impl ToolsSection {
fn name(&self) -> &str {
"tools"
}
@@ -314,7 +305,7 @@ impl PromptSection for ToolsSection {
}
}
-impl PromptSection for SafetySection {
+impl SafetySection {
fn name(&self) -> &str {
"safety"
}
@@ -364,7 +355,7 @@ pub const GROUNDING_BODY: &str = "## Grounding and tool use\n\n\
- Never delete state, data or services the solution needs at runtime, including during cleanup. Before finishing, verify the final state the way a fresh consumer would see it.\n\
- Skills run only via `run_workflow`, and only the skills listed as installed exist. Do not invent skill ids.";
-impl PromptSection for GroundingSection {
+impl GroundingSection {
fn name(&self) -> &str {
"grounding"
}
@@ -374,7 +365,7 @@ impl PromptSection for GroundingSection {
}
}
-impl PromptSection for WorkspaceSection {
+impl WorkspaceSection {
fn tier(&self) -> PromptTier {
// Names the resolved workspace; per install, not per build.
PromptTier::Context
@@ -420,7 +411,7 @@ impl PromptSection for WorkspaceSection {
}
}
-impl PromptSection for RuntimeSection {
+impl RuntimeSection {
fn tier(&self) -> PromptTier {
// Host runtime facts; per install, not per build.
PromptTier::Context
@@ -446,7 +437,7 @@ impl PromptSection for RuntimeSection {
}
}
-impl PromptSection for DateTimeSection {
+impl DateTimeSection {
fn tier(&self) -> PromptTier {
// The live clock is carried in the user message. This section is static.
PromptTier::Stable
@@ -488,7 +479,7 @@ impl PromptSection for DateTimeSection {
}
}
-impl PromptSection for UserIdentitySection {
+impl UserIdentitySection {
fn tier(&self) -> PromptTier {
// The signed-in user, which changes on login and on logout.
PromptTier::Volatile