The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
refactor(session): extract runtime into submodules
Steven Enamakelc5bb504f3954
diff --git a/crates/openhuman-core/src/agent/harness/session/runtime.rs b/crates/openhuman-core/src/agent/harness/session/runtime.rsindex 2507349871..61f67d28d3 100644--- a/crates/openhuman-core/src/agent/harness/session/runtime.rs+++ b/crates/openhuman-core/src/agent/harness/session/runtime.rs@@ -6,26 +6,22 @@//! them out keeps `turn.rs` focused on the interaction lifecycle and//! makes it obvious which methods are cheap getters vs which actually//! drive the model.+//!+//! Each child module contributes one `impl Agent` block:+//!+//! | File | Role |+//! |-----------------|-------------------------------------------------------|+//! | `accessors` | Getters / setters and the tool-visibility filter. |+//! | `resume` | Cold-boot resume seeding of the LLM context. |+//! | `turn_results` | Usage totals, cap flag, and citations of the last turn.|+//! | `turn_helpers` | Static per-turn parsing and telemetry helpers. |+//! | `run_loop` | `run_single` and `run_interactive`. |-use super::types::{Agent, AgentBuilder};-use crate::agent::dispatcher::ParsedToolCall;-use crate::agent::error::AgentError;-use crate::agent::messages::ConversationMessage;-use crate::core::bus::BUS;-use crate::core::events::DomainEvent;-use crate::inference::provider::{self, ToolCall};-use crate::memory::Memory;-use crate::security::prompt_injection::{- enforce_prompt_input, PromptEnforcementAction, PromptEnforcementContext,-};-use crate::tools::agent_policy::ToolPolicyEngine;-use crate::tools::{Tool, ToolSpec};-use crate::util::truncate_with_ellipsis;-use anyhow::Result;-use std::collections::HashSet;-use std::sync::Arc;-include!("runtime_impl_01_part_01.rs");-include!("runtime_impl_01_part_02.rs");+mod accessors;+mod resume;+mod run_loop;+mod turn_helpers;+mod turn_results;#[cfg(test)]#[path = "runtime_tests.rs"]diff --git a/crates/openhuman-core/src/agent/harness/session/runtime_impl_01_part_01.rs b/crates/openhuman-core/src/agent/harness/session/runtime/accessors.rssimilarity index 63%rename from crates/openhuman-core/src/agent/harness/session/runtime_impl_01_part_01.rsrename to crates/openhuman-core/src/agent/harness/session/runtime/accessors.rsindex 72e014c88e..d76b2e8ba4 100644--- a/crates/openhuman-core/src/agent/harness/session/runtime_impl_01_part_01.rs+++ b/crates/openhuman-core/src/agent/harness/session/runtime/accessors.rs@@ -1,17 +1,24 @@+//! Public getters and setters on [`Agent`]: tool registry views, config+//! snapshots, session identity, and the per-session tool-visibility filter+//! (which rebuilds the tool policy snapshot on every change).-impl Agent {-- const EVENT_ERROR_MAX_CHARS: usize = 256;+use super::super::types::{Agent, AgentBuilder};+use crate::memory::Memory;+use crate::tools::agent_policy::ToolPolicyEngine;+use crate::tools::{Tool, ToolSpec};+use std::collections::HashSet;+use std::sync::Arc;+impl Agent {// ─────────────────────────────────────────────────────────────────// Small accessors used by `run_single` + `turn` + sub-agent runner// ─────────────────────────────────────────────────────────────────- pub(super) fn event_session_id(&self) -> &str {+ pub(in crate::agent::harness::session) fn event_session_id(&self) -> &str {&self.event_session_id}- pub(super) fn event_channel(&self) -> &str {+ pub(in crate::agent::harness::session) fn event_channel(&self) -> &str {&self.event_channel}@@ -416,7 +423,7 @@ impl Agent {self.rebuild_tool_policy_session();}- pub(super) fn rebuild_tool_policy_session(&mut self) {+ pub(in crate::agent::harness::session) fn rebuild_tool_policy_session(&mut self) {// Classify the synthesised delegates too: they are advertised to the// provider and callable, so a policy snapshot built from the durable// registry alone would leave every `delegate_*` tool with no decision@@ -455,233 +462,4 @@ impl Agent {pub fn set_next_turn_overrides(&mut self, overrides: super::types::TurnOverrides) {self.pending_turn_overrides = overrides;}-- /// Seed the next turn's LLM context from an authoritative message- /// log (e.g. the web channel's per-thread conversation JSONL).- ///- /// Mirrors what [`Self::try_load_session_transcript`] does on a- /// transcript-file hit, but sources from a caller-supplied list so- /// resume works even when no transcript file exists for this- /// agent name (the typical situation right after the- /// `set_agent_definition_name` / `session_key` rename fix landed —- /// existing transcripts are written under the old name).- ///- /// `messages` is `(role, content)` pairs in chronological order.- /// Recognised roles: `"user"`, `"agent"` / `"assistant"`. Any- /// trailing user message that exactly matches `current_user_message`- /// is dropped — the caller is about to pass that text to- /// [`Self::run_single`], which will append it to history itself, so- /// keeping it here would duplicate it on the wire.- ///- /// No-ops if the agent already has a history or a cached transcript- /// (i.e. the per-process session cache is warm). Intended only for- /// cold-boot priming.- pub fn seed_resume_from_messages(- &mut self,- messages: Vec<(String, String)>,- current_user_message: &str,- ) -> Result<()> {- if !self.history.is_empty() || self.cached_transcript_messages.is_some() {- return Ok(());- }- let mut prior = messages;- if let Some(last) = prior.last() {- if last.0 == "user" && last.1.trim() == current_user_message.trim() {- prior.pop();- }- }- if prior.is_empty() {- return Ok(());- }-- // Build the system prompt fresh — there's no persisted prefix- // to preserve here, and learned-context decoration is skipped- // intentionally so this fallback path stays synchronous and- // doesn't fan out to the memory store on every cold-boot turn.- let learned = crate::agent::prompts::LearnedContextData::default();- let system_prompt = self.build_system_prompt(learned)?;-- let mut cached: Vec<crate::agent::messages::ChatMessage> =- Vec::with_capacity(prior.len() + 1);- cached.push(crate::agent::messages::ChatMessage::system(- system_prompt,- ));- for (role, content) in prior {- let chat = match role.as_str() {- "user" => crate::agent::messages::ChatMessage::user(content),- "agent" | "assistant" => {- crate::agent::messages::ChatMessage::assistant(content)- }- // Fall back to user role for unknown senders rather than- // dropping the message — losing context is worse than- // mislabelling a system/tool message.- _ => crate::agent::messages::ChatMessage::user(content),- };- cached.push(chat);- }-- let cached_len_before = cached.len();- let bounded = self.bound_cached_transcript_messages(cached);- if bounded.len() < cached_len_before {- log::warn!(- "[agent] seed_resume_from_messages — bounded cached transcript {} → {} (max_history_messages={})",- cached_len_before,- bounded.len(),- self.config.max_history_messages- );- }- log::info!(- "[agent] seed_resume_from_messages — primed cached transcript with {} prior messages",- bounded.len().saturating_sub(1)- );- self.cached_transcript_messages = Some(bounded);- Ok(())- }-- /// Cold-boot resume for the web-chat path: pre-populate this session's- /// LLM context from the **full-fidelity** `session_raw/{stem}.jsonl`- /// transcript for `thread_id`.- ///- /// This is the high-fidelity counterpart to- /// [`Self::seed_resume_from_messages`]. That fallback sources lossy- /// `(sender, content)` prose from the conversation log, so it drops every- /// tool call, tool-role result, and reasoning block — after an app restart- /// the model then "forgets" all its tool interactions. This path instead- /// routes thread → transcript via- /// [`transcript::find_root_transcript_for_thread`] and reuses the exact- /// [`transcript::read_transcript`] +- /// [`Self::bound_cached_transcript_messages`] machinery as- /// [`Self::try_load_session_transcript`], so `tool_calls`, `role:"tool"`- /// messages, and `reasoning_content` all survive the round-trip. The only- /// difference from `try_load_session_transcript` is the lookup key (thread- /// id vs. per-thread agent name), so a thread whose transcript was written- /// under a differently-scoped agent name still resumes.- ///- /// Returns `true` when a transcript was found, loaded, and seeded into- /// `cached_transcript_messages`; `false` (a no-op) when the agent is already- /// warm, no root transcript exists for the thread, the transcript is empty,- /// or it fails to parse — the caller then falls back to prose-pair seeding.- ///- /// Best-effort like `try_load_session_transcript`: read/parse failures are- /// logged and reported as `false` rather than propagated. The current turn's- /// user message is appended later by [`Self::run_single`] / `turn`, so it is- /// intentionally absent from the loaded prefix — no dedup is needed here (the- /// on-disk transcript ends at the previous completed turn).- ///- /// Goes through the S4 seam like `try_load_session_transcript` (see its doc- /// comment for why the read is `read_session` and not- /// `ChatHistory::messages()`), via the locator's `root_for_thread` — the- /// lookup that resolves by `_meta.thread_id` across *root* transcripts- /// only. That disambiguation is why it is a locator method rather than- /// anything a stem-bound handle could offer: several transcripts share one- /// thread id (every sub-agent spawned within it does).- pub fn seed_resume_from_thread_transcript(&mut self, thread_id: &str) -> bool {- if !self.history.is_empty() || self.cached_transcript_messages.is_some() {- log::debug!(- "[web-channel] seed_resume_from_thread_transcript no-op — agent already warm \- (history_len={}, cached={}) thread={thread_id}",- self.history.len(),- self.cached_transcript_messages.is_some()- );- return false;- }-- // The thread's conversation belongs to the THREAD, not the active- // profile: the locator resolves cross-dir, newest-wins across the- // shared `session_raw/` and every profile-scoped `session_raw-<id>/`- // (#5351), so switching profile mid-thread continues the same- // conversation. See `FileTranscriptLocator::root_for_thread` for why- // this must not be own-dir-first.- let Some(handle) = self.session_locator().root_for_thread(thread_id) else {- log::debug!(- "[web-channel] no root session_raw transcript for thread={thread_id} in any \- (shared or profile-scoped) session_raw dir — falling back to \- conversation-log prose seeding"- );- return false;- };- let path = handle.path().to_path_buf();-- log::info!(- "[web-channel] cold-boot resume — loading full-fidelity transcript for \- thread={thread_id} path={}",- path.display()- );-- match handle.read_session() {- // `Ok(None)` (file vanished between discovery and read) folds into- // the same empty-transcript branch, so the prose-seeding fallback- // triggers identically.- Ok(None) => {- log::debug!(- "[web-channel] root transcript for thread={thread_id} is empty — \- falling back to prose seeding"- );- false- }- Ok(Some(session)) => {- if session.messages.is_empty() {- log::debug!(- "[web-channel] root transcript for thread={thread_id} is empty — \- falling back to prose seeding"- );- return false;- }- let loaded_count = session.messages.len();- // Count the tool-role results carried into the resumed prefix —- // the fidelity the prose fallback would have silently dropped.- let tool_result_msgs = session.messages.iter().filter(|m| m.role == "tool").count();- let bounded = self.bound_cached_transcript_messages(session.messages);- if bounded.len() < loaded_count {- log::warn!(- "[web-channel] resume prefix trimmed from {} to {} messages \- (max_history_messages={}) for thread={thread_id}",- loaded_count,- bounded.len(),- self.config.max_history_messages- );- }- log::info!(- "[web-channel] cold-boot resume — primed {} transcript message(s) \- ({} tool-role result(s) preserved) for thread={thread_id}",- bounded.len(),- tool_result_msgs- );- self.cached_transcript_messages = Some(bounded);- true- }- Err(err) => {- log::warn!(- "[web-channel] failed to parse root transcript {} for thread={thread_id}: \- {err} — falling back to prose seeding",- path.display()- );- false- }- }- }-- /// Drain and return memory citations collected for the latest completed turn.- ///- /// Async because collection runs concurrently with the turn rather than- /// ahead of it (see `Agent::pending_citations`); this joins whatever is- /// still in flight. By the time a caller asks, the model round-trip has- /// already happened, so the recall has normally finished and this does not- /// wait.- pub async fn take_last_turn_citations(- &mut self,- ) -> Vec<crate::memory::agent::memory_loader::MemoryCitation> {- if let Some(handle) = self.pending_citations.take() {- match handle.await {- Ok(citations) => self.last_turn_citations = citations,- // A panicked or aborted collection must not fail the turn — the- // citations are decorative, the reply is not.- Err(err) => {- log::warn!("[agent_loop] citation task did not complete: {err}");- self.last_turn_citations.clear();- }- }- }- std::mem::take(&mut self.last_turn_citations)- }}diff --git a/crates/openhuman-core/src/agent/harness/session/runtime/resume.rs b/crates/openhuman-core/src/agent/harness/session/runtime/resume.rsnew file mode 100644index 0000000000..ce75445ca7--- /dev/null+++ b/crates/openhuman-core/src/agent/harness/session/runtime/resume.rs@@ -0,0 +1,212 @@+//! Cold-boot resume seeding: priming the next turn's LLM context from an+//! external message log or from the full-fidelity `session_raw` transcript.++use super::super::types::Agent;+use anyhow::Result;++impl Agent {+ /// Seed the next turn's LLM context from an authoritative message+ /// log (e.g. the web channel's per-thread conversation JSONL).+ ///+ /// Mirrors what [`Self::try_load_session_transcript`] does on a+ /// transcript-file hit, but sources from a caller-supplied list so+ /// resume works even when no transcript file exists for this+ /// agent name (the typical situation right after the+ /// `set_agent_definition_name` / `session_key` rename fix landed —+ /// existing transcripts are written under the old name).+ ///+ /// `messages` is `(role, content)` pairs in chronological order.+ /// Recognised roles: `"user"`, `"agent"` / `"assistant"`. Any+ /// trailing user message that exactly matches `current_user_message`+ /// is dropped — the caller is about to pass that text to+ /// [`Self::run_single`], which will append it to history itself, so+ /// keeping it here would duplicate it on the wire.+ ///+ /// No-ops if the agent already has a history or a cached transcript+ /// (i.e. the per-process session cache is warm). Intended only for+ /// cold-boot priming.+ pub fn seed_resume_from_messages(+ &mut self,+ messages: Vec<(String, String)>,+ current_user_message: &str,+ ) -> Result<()> {+ if !self.history.is_empty() || self.cached_transcript_messages.is_some() {+ return Ok(());+ }+ let mut prior = messages;+ if let Some(last) = prior.last() {+ if last.0 == "user" && last.1.trim() == current_user_message.trim() {+ prior.pop();+ }+ }+ if prior.is_empty() {+ return Ok(());+ }++ // Build the system prompt fresh — there's no persisted prefix+ // to preserve here, and learned-context decoration is skipped+ // intentionally so this fallback path stays synchronous and+ // doesn't fan out to the memory store on every cold-boot turn.+ let learned = crate::agent::prompts::LearnedContextData::default();+ let system_prompt = self.build_system_prompt(learned)?;++ let mut cached: Vec<crate::agent::messages::ChatMessage> =+ Vec::with_capacity(prior.len() + 1);+ cached.push(crate::agent::messages::ChatMessage::system(+ system_prompt,+ ));+ for (role, content) in prior {+ let chat = match role.as_str() {+ "user" => crate::agent::messages::ChatMessage::user(content),+ "agent" | "assistant" => {+ crate::agent::messages::ChatMessage::assistant(content)+ }+ // Fall back to user role for unknown senders rather than+ // dropping the message — losing context is worse than+ // mislabelling a system/tool message.+ _ => crate::agent::messages::ChatMessage::user(content),+ };+ cached.push(chat);+ }++ let cached_len_before = cached.len();+ let bounded = self.bound_cached_transcript_messages(cached);+ if bounded.len() < cached_len_before {+ log::warn!(+ "[agent] seed_resume_from_messages — bounded cached transcript {} → {} (max_history_messages={})",+ cached_len_before,+ bounded.len(),+ self.config.max_history_messages+ );+ }+ log::info!(+ "[agent] seed_resume_from_messages — primed cached transcript with {} prior messages",+ bounded.len().saturating_sub(1)+ );+ self.cached_transcript_messages = Some(bounded);+ Ok(())+ }++ /// Cold-boot resume for the web-chat path: pre-populate this session's+ /// LLM context from the **full-fidelity** `session_raw/{stem}.jsonl`+ /// transcript for `thread_id`.+ ///+ /// This is the high-fidelity counterpart to+ /// [`Self::seed_resume_from_messages`]. That fallback sources lossy+ /// `(sender, content)` prose from the conversation log, so it drops every+ /// tool call, tool-role result, and reasoning block — after an app restart+ /// the model then "forgets" all its tool interactions. This path instead+ /// routes thread → transcript via+ /// [`transcript::find_root_transcript_for_thread`] and reuses the exact+ /// [`transcript::read_transcript`] ++ /// [`Self::bound_cached_transcript_messages`] machinery as+ /// [`Self::try_load_session_transcript`], so `tool_calls`, `role:"tool"`+ /// messages, and `reasoning_content` all survive the round-trip. The only+ /// difference from `try_load_session_transcript` is the lookup key (thread+ /// id vs. per-thread agent name), so a thread whose transcript was written+ /// under a differently-scoped agent name still resumes.+ ///+ /// Returns `true` when a transcript was found, loaded, and seeded into+ /// `cached_transcript_messages`; `false` (a no-op) when the agent is already+ /// warm, no root transcript exists for the thread, the transcript is empty,+ /// or it fails to parse — the caller then falls back to prose-pair seeding.+ ///+ /// Best-effort like `try_load_session_transcript`: read/parse failures are+ /// logged and reported as `false` rather than propagated. The current turn's+ /// user message is appended later by [`Self::run_single`] / `turn`, so it is+ /// intentionally absent from the loaded prefix — no dedup is needed here (the+ /// on-disk transcript ends at the previous completed turn).+ ///+ /// Goes through the S4 seam like `try_load_session_transcript` (see its doc+ /// comment for why the read is `read_session` and not+ /// `ChatHistory::messages()`), via the locator's `root_for_thread` — the+ /// lookup that resolves by `_meta.thread_id` across *root* transcripts+ /// only. That disambiguation is why it is a locator method rather than+ /// anything a stem-bound handle could offer: several transcripts share one+ /// thread id (every sub-agent spawned within it does).+ pub fn seed_resume_from_thread_transcript(&mut self, thread_id: &str) -> bool {+ if !self.history.is_empty() || self.cached_transcript_messages.is_some() {+ log::debug!(+ "[web-channel] seed_resume_from_thread_transcript no-op — agent already warm \+ (history_len={}, cached={}) thread={thread_id}",+ self.history.len(),+ self.cached_transcript_messages.is_some()+ );+ return false;+ }++ // The thread's conversation belongs to the THREAD, not the active+ // profile: the locator resolves cross-dir, newest-wins across the+ // shared `session_raw/` and every profile-scoped `session_raw-<id>/`+ // (#5351), so switching profile mid-thread continues the same+ // conversation. See `FileTranscriptLocator::root_for_thread` for why+ // this must not be own-dir-first.+ let Some(handle) = self.session_locator().root_for_thread(thread_id) else {+ log::debug!(+ "[web-channel] no root session_raw transcript for thread={thread_id} in any \+ (shared or profile-scoped) session_raw dir — falling back to \+ conversation-log prose seeding"+ );+ return false;+ };+ let path = handle.path().to_path_buf();++ log::info!(+ "[web-channel] cold-boot resume — loading full-fidelity transcript for \+ thread={thread_id} path={}",+ path.display()+ );++ match handle.read_session() {+ // `Ok(None)` (file vanished between discovery and read) folds into+ // the same empty-transcript branch, so the prose-seeding fallback+ // triggers identically.+ Ok(None) => {+ log::debug!(+ "[web-channel] root transcript for thread={thread_id} is empty — \+ falling back to prose seeding"+ );+ false+ }+ Ok(Some(session)) => {+ if session.messages.is_empty() {+ log::debug!(+ "[web-channel] root transcript for thread={thread_id} is empty — \+ falling back to prose seeding"+ );+ return false;+ }+ let loaded_count = session.messages.len();+ // Count the tool-role results carried into the resumed prefix —+ // the fidelity the prose fallback would have silently dropped.+ let tool_result_msgs = session.messages.iter().filter(|m| m.role == "tool").count();+ let bounded = self.bound_cached_transcript_messages(session.messages);+ if bounded.len() < loaded_count {+ log::warn!(+ "[web-channel] resume prefix trimmed from {} to {} messages \+ (max_history_messages={}) for thread={thread_id}",+ loaded_count,+ bounded.len(),+ self.config.max_history_messages+ );+ }+ log::info!(+ "[web-channel] cold-boot resume — primed {} transcript message(s) \+ ({} tool-role result(s) preserved) for thread={thread_id}",+ bounded.len(),+ tool_result_msgs+ );+ self.cached_transcript_messages = Some(bounded);+ true+ }+ Err(err) => {+ log::warn!(+ "[web-channel] failed to parse root transcript {} for thread={thread_id}: \+ {err} — falling back to prose seeding",+ path.display()+ );+ false+ }+ }+ }+}diff --git a/crates/openhuman-core/src/agent/harness/session/runtime_impl_01_part_02.rs b/crates/openhuman-core/src/agent/harness/session/runtime/run_loop.rssimilarity index 51%rename from crates/openhuman-core/src/agent/harness/session/runtime_impl_01_part_02.rsrename to crates/openhuman-core/src/agent/harness/session/runtime/run_loop.rsindex 49b75d6985..6c80239575 100644--- a/crates/openhuman-core/src/agent/harness/session/runtime_impl_01_part_02.rs+++ b/crates/openhuman-core/src/agent/harness/session/runtime/run_loop.rs@@ -1,160 +1,17 @@+//! `run_single` / `run_interactive`: the single-shot and CLI entry points+//! that wrap [`Agent::turn`] with prompt-injection enforcement, telemetry+//! events, and error sanitisation.++use super::super::types::Agent;+use crate::agent::error::AgentError;+use crate::core::bus::BUS;+use crate::core::events::DomainEvent;+use crate::security::prompt_injection::{+ enforce_prompt_input, PromptEnforcementAction, PromptEnforcementContext,+};+use anyhow::Result;impl Agent {- /// Borrow the holistic token/cost/context totals for the latest completed- /// turn (parent + sub-agents) **without consuming them**. `None` until a- /// turn has run.- ///- /// This is the public, non-draining counterpart to- /// [`take_last_turn_usage_totals`](Self::take_last_turn_usage_totals): a- /// downstream crate embedding OpenHuman as a library (e.g. the OpenCompany- /// hosting platform's cost-metering hook) can read per-turn token and USD- /// totals after [`Agent::turn`](crate::agent::Agent) returns,- /// while leaving the value in place for the web-channel drain path.- pub fn last_turn_usage(- &self,- ) -> Option<&crate::agent::harness::turn_subagent_usage::LastTurnUsage> {- self.last_turn_usage_totals.as_ref()- }-- /// Drain and return the holistic token/cost/context totals for the latest- /// completed turn (parent + sub-agents). `None` until a turn has run.- /// Consumed by web-channel delivery to populate the `chat_done` usage fields.- pub(crate) fn take_last_turn_usage_totals(- &mut self,- ) -> Option<crate::agent::harness::turn_subagent_usage::LastTurnUsage> {- self.last_turn_usage_totals.take()- }-- /// Whether the most recently completed [`Self::turn`] / [`Self::run_single`]- /// paused because it hit `max_tool_iterations`, rather than finishing- /// naturally (see the field doc on `last_turn_hit_cap`). `false` before- /// any turn has run. Not draining — unlike the usage totals above, a- /// caller may reasonably check this more than once per turn.- pub fn last_turn_hit_cap(&self) -> bool {- self.last_turn_hit_cap- }-- // ─────────────────────────────────────────────────────────────────- // Static helpers for turn parsing + telemetry- // ─────────────────────────────────────────────────────────────────-- pub(super) fn count_iterations(messages: &[ConversationMessage]) -> usize {- messages- .iter()- .filter(|message| matches!(message, ConversationMessage::AssistantToolCalls { .. }))- .count()- + 1- }-- fn conversation_message_eq(left: &ConversationMessage, right: &ConversationMessage) -> bool {- serde_json::to_string(left).ok() == serde_json::to_string(right).ok()- }-- fn message_slice_eq(left: &[ConversationMessage], right: &[ConversationMessage]) -> bool {- left.len() == right.len()- && left- .iter()- .zip(right.iter())- .all(|(left, right)| Self::conversation_message_eq(left, right))- }-- pub(super) fn new_entries_for_turn<'a>(- history_snapshot: &[ConversationMessage],- current_history: &'a [ConversationMessage],- ) -> &'a [ConversationMessage] {- let common_prefix_len = history_snapshot- .iter()- .zip(current_history.iter())- .take_while(|(left, right)| Self::conversation_message_eq(left, right))- .count();-- if common_prefix_len == history_snapshot.len() {- return ¤t_history[common_prefix_len..];- }-- let max_overlap = history_snapshot.len().min(current_history.len());- for overlap in (0..=max_overlap).rev() {- let snapshot_suffix = &history_snapshot[history_snapshot.len() - overlap..];- let current_prefix = ¤t_history[..overlap];- if Self::message_slice_eq(snapshot_suffix, current_prefix) {- return ¤t_history[overlap..];- }- }-- current_history- }-- pub(super) fn sanitize_event_error_message(err: &anyhow::Error) -> String {- let kind = match err.downcast_ref::<AgentError>() {- Some(AgentError::ProviderError { .. }) => Some("provider_error"),- Some(AgentError::ContextLimitExceeded { .. }) => Some("context_limit_exceeded"),- Some(AgentError::ToolExecutionError { .. }) => Some("tool_execution_error"),- Some(AgentError::CostBudgetExceeded { .. }) => Some("cost_budget_exceeded"),- Some(AgentError::MaxIterationsExceeded { .. }) => Some("max_iterations_exceeded"),- Some(AgentError::EmptyProviderResponse { .. }) => Some("empty_provider_response"),- Some(AgentError::CompactionFailed { .. }) => Some("compaction_failed"),- Some(AgentError::PermissionDenied { .. }) => Some("permission_denied"),- Some(AgentError::RegistryValidationFailed { .. }) => Some("registry_validation_failed"),- Some(AgentError::Other(_)) | None => None,- };-- if let Some(kind) = kind {- return kind.to_string();- }-- let scrubbed = provider::sanitize_api_error(&err.to_string())- .replace(['\n', '\r', '\t'], " ")- .split_whitespace()- .collect::<Vec<_>>()- .join(" ");- truncate_with_ellipsis(&scrubbed, Self::EVENT_ERROR_MAX_CHARS)- }-- /// Injects unique IDs into tool calls that are missing them.- ///- /// This is necessary for some tool dispatchers to correctly track and- /// associate results.- pub(super) fn with_fallback_tool_call_ids(- mut parsed_calls: Vec<ParsedToolCall>,- iteration: usize,- ) -> Vec<ParsedToolCall> {- for (idx, call) in parsed_calls.iter_mut().enumerate() {- if call.tool_call_id.is_none() {- call.tool_call_id = Some(format!("parsed-{}-{}", iteration + 1, idx + 1));- }- }- parsed_calls- }-- /// Converts parsed tool calls into the provider-standard `ToolCall` format.- ///- /// If the provider response already contains native tool calls, they are- /// returned as-is.- pub(super) fn persisted_tool_calls_for_history(- response: &crate::inference::provider::ChatResponse,- parsed_calls: &[ParsedToolCall],- iteration: usize,- ) -> Vec<ToolCall> {- if !response.tool_calls.is_empty() {- return response.tool_calls.clone();- }-- parsed_calls- .iter()- .enumerate()- .map(|(idx, call)| ToolCall {- id: call- .tool_call_id- .clone()- .unwrap_or_else(|| format!("parsed-{}-{}", iteration + 1, idx + 1)),- name: call.name.clone(),- arguments: call.arguments.to_string(),- // Prompt-based tool calls carry no provider extra_content.- extra_content: None,- })- .collect()- }-// ─────────────────────────────────────────────────────────────────// Run helpers — single-shot and interactive loops// ─────────────────────────────────────────────────────────────────diff --git a/crates/openhuman-core/src/agent/harness/session/runtime/turn_helpers.rs b/crates/openhuman-core/src/agent/harness/session/runtime/turn_helpers.rsnew file mode 100644index 0000000000..961436451b--- /dev/null+++ b/crates/openhuman-core/src/agent/harness/session/runtime/turn_helpers.rs@@ -0,0 +1,134 @@+//! Static per-turn helpers: iteration counting, history diffing, event-error+//! sanitisation, and tool-call id fallback / persistence shaping.++use super::super::types::Agent;+use crate::agent::dispatcher::ParsedToolCall;+use crate::agent::error::AgentError;+use crate::agent::messages::ConversationMessage;+use crate::inference::provider::{self, ToolCall};+use crate::util::truncate_with_ellipsis;++impl Agent {+ const EVENT_ERROR_MAX_CHARS: usize = 256;++ // ─────────────────────────────────────────────────────────────────+ // Static helpers for turn parsing + telemetry+ // ─────────────────────────────────────────────────────────────────++ pub(in crate::agent::harness::session) fn count_iterations(messages: &[ConversationMessage]) -> usize {+ messages+ .iter()+ .filter(|message| matches!(message, ConversationMessage::AssistantToolCalls { .. }))+ .count()+ + 1+ }++ fn conversation_message_eq(left: &ConversationMessage, right: &ConversationMessage) -> bool {+ serde_json::to_string(left).ok() == serde_json::to_string(right).ok()+ }++ fn message_slice_eq(left: &[ConversationMessage], right: &[ConversationMessage]) -> bool {+ left.len() == right.len()+ && left+ .iter()+ .zip(right.iter())+ .all(|(left, right)| Self::conversation_message_eq(left, right))+ }++ pub(in crate::agent::harness::session) fn new_entries_for_turn<'a>(+ history_snapshot: &[ConversationMessage],+ current_history: &'a [ConversationMessage],+ ) -> &'a [ConversationMessage] {+ let common_prefix_len = history_snapshot+ .iter()+ .zip(current_history.iter())+ .take_while(|(left, right)| Self::conversation_message_eq(left, right))+ .count();++ if common_prefix_len == history_snapshot.len() {+ return ¤t_history[common_prefix_len..];+ }++ let max_overlap = history_snapshot.len().min(current_history.len());+ for overlap in (0..=max_overlap).rev() {+ let snapshot_suffix = &history_snapshot[history_snapshot.len() - overlap..];+ let current_prefix = ¤t_history[..overlap];+ if Self::message_slice_eq(snapshot_suffix, current_prefix) {+ return ¤t_history[overlap..];+ }+ }++ current_history+ }++ pub(in crate::agent::harness::session) fn sanitize_event_error_message(err: &anyhow::Error) -> String {+ let kind = match err.downcast_ref::<AgentError>() {+ Some(AgentError::ProviderError { .. }) => Some("provider_error"),+ Some(AgentError::ContextLimitExceeded { .. }) => Some("context_limit_exceeded"),+ Some(AgentError::ToolExecutionError { .. }) => Some("tool_execution_error"),+ Some(AgentError::CostBudgetExceeded { .. }) => Some("cost_budget_exceeded"),+ Some(AgentError::MaxIterationsExceeded { .. }) => Some("max_iterations_exceeded"),+ Some(AgentError::EmptyProviderResponse { .. }) => Some("empty_provider_response"),+ Some(AgentError::CompactionFailed { .. }) => Some("compaction_failed"),+ Some(AgentError::PermissionDenied { .. }) => Some("permission_denied"),+ Some(AgentError::RegistryValidationFailed { .. }) => Some("registry_validation_failed"),+ Some(AgentError::Other(_)) | None => None,+ };++ if let Some(kind) = kind {+ return kind.to_string();+ }++ let scrubbed = provider::sanitize_api_error(&err.to_string())+ .replace(['\n', '\r', '\t'], " ")+ .split_whitespace()+ .collect::<Vec<_>>()+ .join(" ");+ truncate_with_ellipsis(&scrubbed, Self::EVENT_ERROR_MAX_CHARS)+ }++ /// Injects unique IDs into tool calls that are missing them.+ ///+ /// This is necessary for some tool dispatchers to correctly track and+ /// associate results.+ pub(in crate::agent::harness::session) fn with_fallback_tool_call_ids(+ mut parsed_calls: Vec<ParsedToolCall>,+ iteration: usize,+ ) -> Vec<ParsedToolCall> {+ for (idx, call) in parsed_calls.iter_mut().enumerate() {+ if call.tool_call_id.is_none() {+ call.tool_call_id = Some(format!("parsed-{}-{}", iteration + 1, idx + 1));+ }+ }+ parsed_calls+ }++ /// Converts parsed tool calls into the provider-standard `ToolCall` format.+ ///+ /// If the provider response already contains native tool calls, they are+ /// returned as-is.+ pub(in crate::agent::harness::session) fn persisted_tool_calls_for_history(+ response: &crate::inference::provider::ChatResponse,+ parsed_calls: &[ParsedToolCall],+ iteration: usize,+ ) -> Vec<ToolCall> {+ if !response.tool_calls.is_empty() {+ return response.tool_calls.clone();+ }++ parsed_calls+ .iter()+ .enumerate()+ .map(|(idx, call)| ToolCall {+ id: call+ .tool_call_id+ .clone()+ .unwrap_or_else(|| format!("parsed-{}-{}", iteration + 1, idx + 1)),+ name: call.name.clone(),+ arguments: call.arguments.to_string(),+ // Prompt-based tool calls carry no provider extra_content.+ extra_content: None,+ })+ .collect()+ }+}diff --git a/crates/openhuman-core/src/agent/harness/session/runtime/turn_results.rs b/crates/openhuman-core/src/agent/harness/session/runtime/turn_results.rsnew file mode 100644index 0000000000..ed0ceb7d52--- /dev/null+++ b/crates/openhuman-core/src/agent/harness/session/runtime/turn_results.rs@@ -0,0 +1,64 @@+//! Read-out of the latest completed turn: usage totals, the iteration-cap+//! flag, and the memory citations collected alongside the turn.++use super::super::types::Agent;++impl Agent {+ /// Borrow the holistic token/cost/context totals for the latest completed+ /// turn (parent + sub-agents) **without consuming them**. `None` until a+ /// turn has run.+ ///+ /// This is the public, non-draining counterpart to+ /// [`take_last_turn_usage_totals`](Self::take_last_turn_usage_totals): a+ /// downstream crate embedding OpenHuman as a library (e.g. the OpenCompany+ /// hosting platform's cost-metering hook) can read per-turn token and USD+ /// totals after [`Agent::turn`](crate::agent::Agent) returns,+ /// while leaving the value in place for the web-channel drain path.+ pub fn last_turn_usage(+ &self,+ ) -> Option<&crate::agent::harness::turn_subagent_usage::LastTurnUsage> {+ self.last_turn_usage_totals.as_ref()+ }++ /// Drain and return the holistic token/cost/context totals for the latest+ /// completed turn (parent + sub-agents). `None` until a turn has run.+ /// Consumed by web-channel delivery to populate the `chat_done` usage fields.+ pub(crate) fn take_last_turn_usage_totals(+ &mut self,+ ) -> Option<crate::agent::harness::turn_subagent_usage::LastTurnUsage> {+ self.last_turn_usage_totals.take()+ }++ /// Whether the most recently completed [`Self::turn`] / [`Self::run_single`]+ /// paused because it hit `max_tool_iterations`, rather than finishing+ /// naturally (see the field doc on `last_turn_hit_cap`). `false` before+ /// any turn has run. Not draining — unlike the usage totals above, a+ /// caller may reasonably check this more than once per turn.+ pub fn last_turn_hit_cap(&self) -> bool {+ self.last_turn_hit_cap+ }++ /// Drain and return memory citations collected for the latest completed turn.+ ///+ /// Async because collection runs concurrently with the turn rather than+ /// ahead of it (see `Agent::pending_citations`); this joins whatever is+ /// still in flight. By the time a caller asks, the model round-trip has+ /// already happened, so the recall has normally finished and this does not+ /// wait.+ pub async fn take_last_turn_citations(+ &mut self,+ ) -> Vec<crate::memory::agent::memory_loader::MemoryCitation> {+ if let Some(handle) = self.pending_citations.take() {+ match handle.await {+ Ok(citations) => self.last_turn_citations = citations,+ // A panicked or aborted collection must not fail the turn — the+ // citations are decorative, the reply is not.+ Err(err) => {+ log::warn!("[agent_loop] citation task did not complete: {err}");+ self.last_turn_citations.clear();+ }+ }+ }+ std::mem::take(&mut self.last_turn_citations)+ }+}diff --git a/crates/openhuman-core/src/agent/harness/session/runtime_tests.rs b/crates/openhuman-core/src/agent/harness/session/runtime_tests.rsindex 61cbf95b0b..53503d5357 100644--- a/crates/openhuman-core/src/agent/harness/session/runtime_tests.rs+++ b/crates/openhuman-core/src/agent/harness/session/runtime_tests.rs@@ -1,4 +1,6 @@use super::*;+use super::super::types::Agent;+use crate::agent::messages::ConversationMessage;use crate::agent::dispatcher::XmlToolDispatcher;use crate::agent::error::AgentError;use crate::agent::messages::ChatMessage;diff --git a/crates/openhuman-core/src/agent/prompts/render_helpers/section_renderers.rs b/crates/openhuman-core/src/agent/prompts/render_helpers/section_renderers.rsnew file mode 100644index 0000000000..292bf92f74--- /dev/null+++ b/crates/openhuman-core/src/agent/prompts/render_helpers/section_renderers.rs@@ -0,0 +1,241 @@+//! Functional `render_*` wrappers over the section structs in+//! [`super::super::sections`], plus the per-turn datetime stamp and the+//! ambient-environment composer that `agents/<id>/prompt.rs` builders call.++use super::super::sections::*;+use super::super::types::*;+use anyhow::Result;+use chrono::{DateTime, Utc};+use std::sync::OnceLock;++// ─────────────────────────────────────────────────────────────────────────────+// Section render helpers (functional wrappers over section structs)+// ─────────────────────────────────────────────────────────────────────────────++/// Render the `## Project Context` identity block+/// (`SOUL.md` / `IDENTITY.md` / `ROLE.md` for the user-facing agent).+pub fn render_identity(ctx: &PromptContext<'_>) -> Result<String> {+ IdentitySection.build(ctx)+}++/// Render the `PROFILE.md` + `MEMORY.md` user-file injection.+/// Empty when neither `ctx.include_profile` nor `ctx.include_memory_md`+/// is set.+pub fn render_user_files(ctx: &PromptContext<'_>) -> Result<String> {+ UserFilesSection.build(ctx)+}++/// Render the tree-summariser user-memory block.+pub fn render_user_memory(ctx: &PromptContext<'_>) -> Result<String> {+ UserMemorySection.build(ctx)+}++/// Render the `## Project instructions (AGENTS.md)` block from the pre-loaded+/// global + local content on [`PromptContext`]. Empty when neither layer+/// carries content. Dynamic `agents/<id>/prompt.rs` builders call this so they+/// inherit the same AGENTS.md injection as the default section chain.+pub fn render_agents_md(ctx: &PromptContext<'_>) -> Result<String> {+ AgentsInstructionsSection.build(ctx)+}++/// Render the privileged `## User Reflections` block. Empty when the+/// learning subsystem has not captured any reflections yet.+pub fn render_user_reflections(ctx: &PromptContext<'_>) -> Result<String> {+ UserReflectionsSection.build(ctx)+}++/// Render the `## Tools` catalogue in the dispatcher's tool-call format.+pub fn render_tools(ctx: &PromptContext<'_>) -> Result<String> {+ ToolsSection.build(ctx)+}++/// Render the static `## Safety` block.+pub fn render_safety() -> String {+ SafetySection+ .build(&empty_prompt_context_for_static_sections())+ .expect("SafetySection::build is infallible")+}++/// Render the canonical grounding / anti-hallucination contract+/// ([`GROUNDING_BODY`]). Dynamic `agents/<id>/prompt.rs` builders call this+/// so they inherit the exact same anti-fabrication floor as the static+/// section chain — single source of truth, no drift.+pub fn render_grounding() -> &'static str {+ GROUNDING_BODY+}++// `render_skills` and `render_connected_integrations` helpers are+// gone — `## Available Skills` lives in `integrations_agent/prompt.rs`, and+// the connected-integrations / delegation-guide blocks each live in+// their owning agent's `prompt.rs` so no branching-on-agent-id logic+// needs to exist here.++/// Render the `## Workspace` block (working directory + file listing+/// bounds) — part of the dynamic, per-request suffix.+pub fn render_workspace(ctx: &PromptContext<'_>) -> Result<String> {+ WorkspaceSection.build(ctx)+}++/// Render the `## Runtime` block (model name, dispatcher format) —+/// dynamic.+pub fn render_runtime(ctx: &PromptContext<'_>) -> Result<String> {+ RuntimeSection.build(ctx)+}++/// Render the `## Current Date & Time` block: the static time-discipline+/// *rules* (greeting/clock grounding + the gated `resolve_time` rule). The+/// concrete "now" is **not** here — it rides the user message per turn via+/// [`current_datetime_line`] so it stays fresh and keeps this section+/// byte-stable for prefix caching (#3602).+pub fn render_datetime(ctx: &PromptContext<'_>) -> Result<String> {+ DateTimeSection.build(ctx)+}++/// Canonical one-line "now" stamp, injected per turn alongside the user+/// message by both the main session loop (`session::turn`) and the+/// sub-agent runner so every flow reports the current time identically+/// (#3602). Local time + IANA zone + `%Z`/offset + weekday, so the model+/// can localize greetings and date math without a tool call.+///+/// Deliberately lives on the *user message*, never the cached+/// system-prompt prefix: `Local::now()` is volatile, so freezing it into+/// the prefix both busts the KV cache and goes stale across a long-lived+/// session. The static grounding *rule* that tells the model to read this+/// line lives in [`DateTimeSection`] / [`render_datetime`].+pub fn current_datetime_line() -> String {+ // `library-cpu.sh` sets `OPENHUMAN_PROFILE_FORCE_UTC=1` to skip+ // `iana_time_zone`/CoreFoundation timezone resolution, which is itself a+ // measurable cost in a cold CPU profile. Gated on `rss-bench`, so it does+ // not exist in any shipped build.+ #[cfg(feature = "rss-bench")]+ if std::env::var_os("OPENHUMAN_PROFILE_FORCE_UTC").is_some() {+ let now = chrono::Utc::now();+ return format!(+ "Current Date & Time: {} UTC (UTC, UTC+00:00), {}",+ now.format("%Y-%m-%d %H:%M:%S"),+ now.format("%A"),+ );+ }++ // When the host resolves an IANA zone, stamp local time + that zone. When+ // it can't (CI, stripped containers), fall back to true UTC — formatting+ // `Utc::now()` so the time, offset, and zone label all agree rather than+ // pairing a "UTC" label with a local clock/offset.+ match iana_time_zone::get_timezone() {+ Ok(iana) => {+ let now = chrono::Local::now();+ format!(+ "Current Date & Time: {} {} ({}, UTC{}), {}",+ now.format("%Y-%m-%d %H:%M:%S"),+ iana,+ now.format("%Z"),+ now.format("%:z"),+ now.format("%A"),+ )+ }+ Err(_) => {+ let now = chrono::Utc::now();+ format!(+ "Current Date & Time: {} UTC (UTC, UTC+00:00), {}",+ now.format("%Y-%m-%d %H:%M:%S"),+ now.format("%A"),+ )+ }+ }+}++/// Render the `## User` identity block. Empty when+/// [`PromptContext::user_identity`] is unset or has no populated+/// fields. See issue #926.+pub fn render_user_identity(ctx: &PromptContext<'_>) -> Result<String> {+ UserIdentitySection.build(ctx)+}++/// Compose the full ambient-environment block — runtime + user+/// identity + current date/time, in that order.+///+/// Per-agent `prompt.rs` builders call this once near the end of their+/// assembly so every agent reports the same machine-readable view of+/// "where am I, who is the user, what time is it" (issue #926).+/// Datetime is appended last so the time-volatile section sits at the+/// tail of the prompt and the rest of the prefix stays cache-stable+/// across turns within the same minute, matching the convention used+/// by [`super::builder::SystemPromptBuilder::with_defaults`].+pub fn render_ambient_environment(ctx: &PromptContext<'_>) -> Result<String> {+ let mut out = String::with_capacity(512);+ let runtime = render_runtime(ctx)?;+ if !runtime.trim().is_empty() {+ out.push_str(runtime.trim_end());+ out.push_str("\n\n");+ }+ let user = render_user_identity(ctx)?;+ if !user.trim().is_empty() {+ out.push_str(user.trim_end());+ out.push_str("\n\n");+ }+ let datetime = render_datetime(ctx)?;+ if !datetime.trim().is_empty() {+ out.push_str(datetime.trim_end());+ out.push('\n');+ }+ Ok(out)+}++/// Format a memory item's `updated_at` as an absolute UTC date label+/// for prompt injection, e.g. `2026-05-25`.+///+/// Absolute (not relative "N days ago") on purpose: memory sections sit+/// near the front of the KV-cache-stable system prompt, so a label that+/// changes daily would bust the cached prefix for everything after it.+/// An absolute date only changes when the underlying memory does. The+/// model judges staleness by comparing this against the injected current+/// date. Shared by [`UserMemorySection`] and the working-memory block in+/// `agent_memory::memory_loader`. (#2944)+pub fn memory_date_label(updated_at: DateTime<Utc>) -> String {+ updated_at.format("%Y-%m-%d").to_string()+}++// ─────────────────────────────────────────────────────────────────────────────+// Internal helpers+// ─────────────────────────────────────────────────────────────────────────────++/// Build a throwaway `PromptContext` for sections whose `build` only+/// uses static/immutable inputs (currently just `SafetySection`). Keeps+/// the `render_safety()` free function from forcing callers to+/// manufacture a full context when they only need the static text.+fn empty_prompt_context_for_static_sections() -> PromptContext<'static> {+ static EMPTY_TOOLS: &[PromptTool<'static>] = &[];+ static EMPTY_WORKFLOWS: &[crate::skills::Workflow] = &[];+ static EMPTY_INTEGRATIONS: &[ConnectedIntegration] = &[];+ // SAFETY: the &HashSet reference must outlive the returned context;+ // a leaked OnceLock-style allocation gives us a permanent 'static+ // anchor without adding runtime cost on the hot path.+ static EMPTY_VISIBLE: OnceLock<std::collections::HashSet<String>> = OnceLock::new();+ let visible = EMPTY_VISIBLE.get_or_init(std::collections::HashSet::new);+ PromptContext {+ workspace_dir: std::path::Path::new(""),+ model_name: "",+ agent_id: "",+ tools: EMPTY_TOOLS,+ workflows: EMPTY_WORKFLOWS,+ dispatcher_instructions: "",+ learned: LearnedContextData::default(),+ visible_tool_names: visible,+ tool_call_format: ToolCallFormat::PFormat,+ connected_integrations: EMPTY_INTEGRATIONS,+ connected_identities_md: String::new(),+ include_profile: false,+ include_memory_md: false,+ curated_snapshot: None,+ user_identity: None,+ personality_soul_md: None,+ personality_memory_md: None,+ personality_roster: vec![],+ agents_md_global: None,+ agents_md_local: None,+ }+}++/// Build a P-Format signature line (`name[a|b|c]`) from a `&dyn Tool`.+/// Used by `render_subagent_system_prompt` which operates on `Box<dyn Tool>`+/// directly (no intermediate `PromptTool`). Mirrors the `PromptTool` variantdiff --git a/crates/openhuman-core/src/agent/prompts/render_helpers/subagent.rs b/crates/openhuman-core/src/agent/prompts/render_helpers/subagent.rsnew file mode 100644index 0000000000..eacc43310b--- /dev/null+++ b/crates/openhuman-core/src/agent/prompts/render_helpers/subagent.rs@@ -0,0 +1,338 @@+//! Narrow, KV-cache-stable system-prompt renderer for typed sub-agents.+//!+//! Purpose-built alternative to+//! [`SystemPromptBuilder::for_subagent`](crate::agent::prompts::builder::SystemPromptBuilder::for_subagent)+//! for callers that only hold indices into the parent's tool vec.++use super::super::builder::GLOBAL_STYLE_SUFFIX;+use super::super::sections::{GROUNDING_BODY, MEMORY_MD_FRAMING};+use super::super::types::*;+use super::workspace_files::{+ inject_workspace_file, inject_workspace_file_capped, write_agents_md_blocks,+};+use std::fmt::Write;+use std::path::Path;++// ─────────────────────────────────────────────────────────────────────────────+// Sub-agent prompt renderer+// ─────────────────────────────────────────────────────────────────────────────++/// Render a narrow, KV-cache-stable system prompt for a typed sub-agent.+///+/// This is a purpose-built alternative to+/// [`super::builder::SystemPromptBuilder::for_subagent`] for call sites+/// that only have indices into the parent's `&[Box<dyn Tool>]` vec (so they+/// can't cheaply build a filtered owning slice for `ToolsSection`). The+/// output mirrors what `for_subagent` would emit with the matching+/// `omit_*` flags, plus a sub-agent-specific calling-convention+/// preamble and a model-only runtime banner.+///+/// `archetype_body` is the already-loaded archetype markdown — for+/// `PromptSource::Inline` this is the inline string, for+/// `PromptSource::File` this is the file contents loaded by the caller.+/// Callers resolve the source exactly once and hand the body in, so+/// this renderer works uniformly for both definition shapes.+///+/// `options` carries the per-definition rendering flags (safety, etc.)+/// inverted into positive-sense `include_*` form.+/// [`SubagentRenderOptions::narrow`] preserves the historical behaviour.+///+/// # KV cache stability+///+/// The rendered bytes MUST be a pure function of:+/// - the `archetype_body` (archetype role prompt)+/// - the filtered tool set (names, descriptions, schemas)+/// - the workspace directory+/// - the resolved model name+/// - the `options` (all static per definition)+///+/// Anything that varies across invocations at the *same* call site+/// (e.g. `chrono::Local::now()`, hostnames, pids, turn counters) is+/// forbidden here. Repeat spawns of the same sub-agent within a session+/// must produce byte-identical system prompts so the inference+/// backend's automatic prefix caching can reuse the prefill from the+/// previous run. Time-of-day information, if a sub-agent needs it,+/// belongs in the user message — not the system prompt.+pub fn render_subagent_system_prompt(+ workspace_dir: &Path,+ model_name: &str,+ allowed_indices: &[usize],+ parent_tools: &[Box<dyn crate::tools::Tool>],+ extra_tools: &[Box<dyn crate::tools::Tool>],+ archetype_body: &str,+ options: SubagentRenderOptions,+ tool_call_format: ToolCallFormat,+ connected_integrations: &[ConnectedIntegration],+) -> String {+ render_subagent_system_prompt_with_format(+ workspace_dir,+ model_name,+ allowed_indices,+ parent_tools,+ extra_tools,+ archetype_body,+ options,+ tool_call_format,+ connected_integrations,+ None,+ None,+ )+}++/// Inner renderer that accepts an explicit [`ToolCallFormat`] so callers+/// that know the active dispatcher format can thread it through. The+/// public [`render_subagent_system_prompt`] defaults to PFormat for+/// backwards compatibility.+///+/// `agents_md_global` / `agents_md_local` are the pre-loaded AGENTS.md layers+/// (see [`super::agents_md::load_agents_md_layers`]); `None`/`None` (the value+/// the public wrapper passes) renders no AGENTS.md block. When present they are+/// injected as `## Project instructions (AGENTS.md)` right after the user files+/// and before the tool catalogue — matching the section order of the default /+/// sub-agent builders.+#[allow(clippy::too_many_arguments)]+pub fn render_subagent_system_prompt_with_format(+ workspace_dir: &Path,+ model_name: &str,+ allowed_indices: &[usize],+ parent_tools: &[Box<dyn crate::tools::Tool>],+ extra_tools: &[Box<dyn crate::tools::Tool>],+ archetype_body: &str,+ options: SubagentRenderOptions,+ tool_call_format: ToolCallFormat,+ _connected_integrations: &[ConnectedIntegration],+ agents_md_global: Option<&str>,+ agents_md_local: Option<&str>,+) -> String {+ let mut out = String::new();++ // 1. Archetype role prompt. Works for `PromptSource::Inline`,+ // `PromptSource::File`, and `PromptSource::Dynamic` because the+ // caller preloaded the body via `load_prompt_source`.+ let trimmed = archetype_body.trim();+ if !trimmed.is_empty() {+ out.push_str(trimmed);+ out.push_str("\n\n");+ }++ // 1b. Optional identity block. Off by default; turned on when the+ // definition sets `omit_identity = false`. Renders the same+ // OpenClaw bootstrap files the main agent loads, keeping the+ // byte layout stable across repeat spawns of the same+ // definition within a session.+ if options.include_identity {+ out.push_str("## Project Context\n\n");+ out.push_str(+ "The following workspace files define your identity, behavior, and context.\n\n",+ );+ for file in &["SOUL.md", "IDENTITY.md"] {+ inject_workspace_file(&mut out, workspace_dir, file);+ }+ }++ // 1c. PROFILE.md (onboarding enrichment output) and MEMORY.md+ // (archivist-curated long-term memory). Each is gated on its own+ // flag and capped at `USER_FILE_MAX_CHARS` (~1000 tokens) so a+ // growing on-disk file can't push the system prompt out of the+ // cache-friendly prefix range.+ //+ // KV-cache contract: once these files land in a session's+ // rendered prompt the bytes are frozen for the remainder of that+ // session. Do not re-read them mid-turn — a byte change breaks+ // the backend's automatic prefix cache. Mid-session writes to+ // either file are intentionally only visible on the NEXT session.+ if options.include_profile {+ inject_workspace_file_capped(&mut out, workspace_dir, "PROFILE.md", USER_FILE_MAX_CHARS);+ }+ if options.include_memory_md {+ // Frame MEMORY.md as durable, cross-session background memory —+ // byte-identical to `UserFilesSection::build` (GH-4745). Without the+ // frame an Inline/File sub-agent on a brand-new thread reads the bare+ // `### MEMORY.md` block as prior in-thread conversation and asserts+ // continuity that isn't there. Buffer first so the note is emitted+ // only when the file actually carries content — a dangling frame+ // pointing at nothing would itself imply phantom history.+ let mut mem = String::new();+ inject_workspace_file_capped(&mut mem, workspace_dir, "MEMORY.md", USER_FILE_MAX_CHARS);+ if !mem.trim().is_empty() {+ out.push_str(MEMORY_MD_FRAMING);+ out.push_str(&mem);+ }+ }++ // 1d. Project instructions (AGENTS.md), pre-loaded by the caller and shared+ // with the section-based builders through `write_agents_md_blocks` so+ // the byte layout can never drift between the two paths. Placed after+ // the user files and before the tool catalogue, matching the default+ // section order. Skipped entirely when both layers are `None`.+ write_agents_md_blocks(&mut out, agents_md_global, agents_md_local);++ // 2. Filtered tool catalogue. Indices are taken in ascending order+ // from `allowed_indices`, which itself preserves `parent_tools`+ // order, so the rendering is deterministic. We use `.get(i)`+ // defensively even though the current caller (subagent_runner)+ // only produces in-range indices — a future caller that derives+ // indices from a different source must not be able to panic this+ // renderer with a stale index.+ //+ // Rendering uses the caller-specified `tool_call_format` so+ // sub-agents and the main dispatcher stay in lockstep.+ // Tool catalogue rendering is dispatcher-format-aware:+ //+ // - **Native**: The provider receives full tool schemas through+ // the request body's `tools` field (via `filtered_specs` in the+ // sub-agent runner) and emits structured `tool_calls`. Listing+ // the same tools again as prose in the system prompt is pure+ // duplication — for a integrations_agent spawn with 62 dynamic gmail+ // tools, that duplication added ~54k tokens and blew past the+ // model's context window. We skip the prose `## Tools` section+ // entirely in this mode.+ //+ // - **PFormat / Json**: Both are prompt-driven formats — the+ // model discovers tools by reading the prose `## Tools` section+ // and emits text-wrapped tool calls (`<tool_call>name[a|b]</tool_call>`+ // for PFormat, `<tool_call>{"name":...}</tool_call>` for Json).+ // Neither uses the native `tools` request field, so we MUST+ // list each tool in prose — including dynamically-registered+ // `extra_tools` — or the model has no way to know they exist.+ if !matches!(tool_call_format, ToolCallFormat::Native) {+ out.push_str("## Tools\n\n");+ let render_one =+ |out: &mut String, tool: &dyn crate::tools::Tool| match tool_call_format {+ ToolCallFormat::PFormat => {+ let sig = render_pformat_signature_for_box_tool(tool);+ let _ = writeln!(+ out,+ "- **{}**: {}\n Call as: `{}`",+ tool.name(),+ tool.description(),+ sig+ );+ }+ ToolCallFormat::Json => {+ let _ = writeln!(+ out,+ "- **{}**: {}\n Parameters: `{}`",+ tool.name(),+ tool.description(),+ tool.parameters_schema()+ );+ }+ ToolCallFormat::Native => {+ // Unreachable — outer guard skips Native entirely.+ }+ };+ for &i in allowed_indices {+ let Some(tool) = parent_tools.get(i) else {+ tracing::warn!(+ index = i,+ tool_count = parent_tools.len(),+ "[context::prompt] dropping out-of-range tool index in subagent render"+ );+ continue;+ };+ render_one(&mut out, tool.as_ref());+ }+ for tool in extra_tools {+ render_one(&mut out, tool.as_ref());+ }+ }++ // 3. Sub-agent calling-convention preamble — format-aware.+ // Sub-agents need the same call format the main dispatcher expects+ // so their output parses correctly.+ out.push('\n');+ match tool_call_format {+ ToolCallFormat::PFormat => {+ out.push_str(+ "## Tool Use Protocol\n\n\+ Tool calls use **P-Format**: compact, positional, pipe-delimited syntax \+ wrapped in `<tool_call>` tags.\n\n\+ ```\n<tool_call>\ntool_name[arg1|arg2]\n</tool_call>\n```\n\n\+ Arguments are positional — match the order shown in each tool's `Call as:` \+ signature above (alphabetical by parameter name). \+ Escape `|` as `\\|`, `]` as `\\]` inside values. \+ You may emit multiple `<tool_call>` blocks per response.\n\n\+ Use the provided tools to accomplish the task. Reply with a concise, dense \+ final answer when you have one — the parent agent will weave it back into the \+ user-visible response.\n\n",+ );+ }+ ToolCallFormat::Json => {+ out.push_str(+ "## Tool Use Protocol\n\n\+ To use a tool, wrap a JSON object in `<tool_call></tool_call>` tags:\n\n\+ ```\n<tool_call>\n{\"name\": \"tool_name\", \"arguments\": {\"param\": \"value\"}}\n</tool_call>\n```\n\n\+ You may emit multiple `<tool_call>` blocks in a single response.\n\n\+ Use the provided tools to accomplish the task. Reply with a concise, dense \+ final answer when you have one — the parent agent will weave it back into the \+ user-visible response.\n\n",+ );+ }+ ToolCallFormat::Native => {+ out.push_str(+ "Use the provided tools via the model's native tool-calling output. \+ Reply with a concise, dense final answer when you have one — the parent \+ agent will weave it back into the user-visible response.\n\n",+ );+ }+ }++ // 3b. Optional safety preamble. Definitions that do work with real+ // side-effects (code_executor, tool_maker, integrations_agent) set+ // `omit_safety_preamble = false` so the narrow renderer used to+ // silently drop that instruction — we now honour the flag.+ // Byte-identical to `SafetySection::build`.+ if options.include_safety_preamble {+ out.push_str(+ "## Safety\n\n- Do not exfiltrate private data.\n- Do not run destructive commands without asking.\n- Do not bypass oversight or approval mechanisms.\n- Prefer `trash` over `rm`.\n- When in doubt, ask before acting externally.\n\n",+ );+ }++ // 3b'. Grounding / anti-hallucination contract. Always emitted (like the+ // static chain): every spawned sub-agent gets the same floor.+ // Sourced from the shared `GROUNDING_BODY` const so this narrow+ // renderer can never drift from `GroundingSection`.+ out.push_str(GROUNDING_BODY);+ out.push_str("\n\n");++ // 3c/3d. `## Available Skills` and `## Connected Integrations`+ // are no longer emitted here. Each agent that needs them+ // renders its own block in its `prompt.rs` (integrations_agent+ // owns the executor voice, orchestrator/welcome own the+ // delegator voice). Legacy Inline/File-sourced TOML agents+ // that still route through this helper simply don't get+ // either block — which matches the fact that none of them+ // currently opt in.++ // 4. Workspace so the model knows where it is. Intentionally stable:+ // no datetime, no hostname, no pid — see the KV-cache note above.+ let _ = writeln!(+ out,+ "## Workspace\n\nWorking directory: `{}`\n",+ workspace_dir.display()+ );++ // 6. Runtime banner — model name only. Stable for the lifetime of+ // this sub-agent's definition.+ let _ = writeln!(out, "## Runtime\n\nModel: {model_name}");+ out.push('\n');+ out.push_str(GLOBAL_STYLE_SUFFIX);++ out+}++/// below — both BTreeMap-iterate the schema's `properties` in the same order.+fn render_pformat_signature_for_box_tool(tool: &dyn crate::tools::Tool) -> String {+ let schema = tool.parameters_schema();+ let names: Vec<String> = schema+ .get("properties")+ .and_then(|p| p.as_object())+ .map(|m| m.keys().cloned().collect())+ .unwrap_or_default();+ if names.is_empty() {+ format!("{}[]", tool.name())+ } else {+ format!("{}[{}]", tool.name(), names.join("|"))+ }+}diff --git a/crates/openhuman-core/src/agent/prompts/render_helpers/workspace_files.rs b/crates/openhuman-core/src/agent/prompts/render_helpers/workspace_files.rsnew file mode 100644index 0000000000..fd5e223f1a--- /dev/null+++ b/crates/openhuman-core/src/agent/prompts/render_helpers/workspace_files.rs@@ -0,0 +1,296 @@+//! Workspace-file I/O helpers: seeding bundled identity files into the+//! workspace, injecting on-disk or inline content into a prompt under a+//! `###` heading with a character cap, and the shared AGENTS.md block writer.++use super::super::types::*;+use std::fmt::Write;+use std::hash::{Hash, Hasher};+use std::path::Path;++/// Ensure the workspace file is up-to-date with the compiled-in default.+///+/// On first install the file doesn't exist → write it. On subsequent runs+/// we store a hash of the compiled-in content in a sidecar file+/// (`.{filename}.builtin-hash`). If the hash changes (code was updated),+/// the disk file is overwritten so prompt improvements ship automatically.+/// User edits between code releases are preserved — we only overwrite when+/// the built-in default itself changes.+pub fn sync_workspace_file(workspace_dir: &Path, filename: &str) {+ let default_content = default_workspace_file_content(filename);+ if default_content.is_empty() {+ return;+ }++ // A real workspace is always an absolute path (`~/.openhuman/users/<id>/+ // workspace`, or a temp dir under test). A relative one means the caller+ // never had a workspace to begin with — overwhelmingly `Path::new(".")`+ // from the ~20 prompt-test fixtures — and joining onto it seeds SOUL.md,+ // IDENTITY.md and ROLE.md plus their+ // `.builtin-hash` siblings into the process's current directory. That is+ // the repo root when the suite runs, which is how they briefly ended up+ // committed (#5701).+ //+ // Refusing is safe because seeding into a relative path is never the+ // intent: a caller with a genuine workspace always has an absolute one.+ if !workspace_dir.is_absolute() {+ tracing::debug!(+ "[workspace-sync] refusing to seed {filename} into non-absolute workspace {} \+ — no workspace configured",+ workspace_dir.display()+ );+ return;+ }++ let path = workspace_dir.join(filename);+ let hash_path = workspace_dir.join(format!(".{filename}.builtin-hash"));++ // Compute a simple hash of the current compiled-in content.+ let current_hash = {+ let mut hasher = std::collections::hash_map::DefaultHasher::new();+ default_content.hash(&mut hasher);+ format!("{:016x}", hasher.finish())+ };++ // Read the last-written hash (if any).+ let stored_hash = std::fs::read_to_string(&hash_path).unwrap_or_default();+ let stored_hash = stored_hash.trim();++ if stored_hash == current_hash && path.exists() {+ // Built-in hasn't changed and file exists — nothing to do.+ return;+ }++ // Decide whether to overwrite the existing file. Two safe cases:+ // 1. File doesn't exist yet — first install, write the default.+ // 2. File exists AND its current hash matches the stored builtin+ // hash — the user hasn't edited it since we last wrote it, so+ // it's safe to ship the new default.+ // Otherwise the file has been hand-edited between releases; leave+ // the user's version in place and just update the stored hash so we+ // stop re-comparing against the old default on every boot.+ let file_exists = path.exists();+ let user_unmodified = if file_exists {+ match std::fs::read_to_string(&path) {+ Ok(disk) => {+ let mut hasher = std::collections::hash_map::DefaultHasher::new();+ disk.hash(&mut hasher);+ let disk_hash = format!("{:016x}", hasher.finish());+ disk_hash == stored_hash+ }+ Err(_) => false,+ }+ } else {+ false+ };++ if let Some(parent) = path.parent() {+ let _ = std::fs::create_dir_all(parent);+ }++ if !file_exists || user_unmodified {+ if let Err(e) = std::fs::write(&path, default_content) {+ log::warn!("[agent:prompt] failed to write workspace file {filename}: {e}");+ return;+ }+ log::info!("[agent:prompt] updated workspace file {filename} (builtin content changed)");+ } else {+ log::info!(+ "[agent:prompt] keeping user-edited workspace file {filename} (builtin changed but disk contents diverge)"+ );+ }+ let _ = std::fs::write(&hash_path, ¤t_hash);+}++/// Inject `filename` from `workspace_dir` into `prompt`, truncated to+/// [`BOOTSTRAP_MAX_CHARS`]. Thin wrapper around+/// [`inject_workspace_file_capped`] for bootstrap-class files+/// (`SOUL.md`, `IDENTITY.md`, `ROLE.md`).+pub fn inject_workspace_file(prompt: &mut String, workspace_dir: &Path, filename: &str) {+ inject_workspace_file_capped(prompt, workspace_dir, filename, BOOTSTRAP_MAX_CHARS);+}++/// Inject pre-loaded string content into `prompt` under a `### label` heading,+/// capped at `max_chars`. Mirrors the format of [`inject_snapshot_content`]+/// and [`inject_workspace_file_capped`] but takes a `&str` instead of a file+/// path. Used for personality-specific overrides (`personality_soul_md`,+/// `personality_memory_md`) on [`PromptContext`] so a swap from the file-based+/// loader to an inline override is byte-compatible with the workspace-file path.+///+/// Empty/whitespace content is silently skipped.+pub fn inject_inline_content(prompt: &mut String, label: &str, content: &str, max_chars: usize) {+ let trimmed = content.trim();+ if trimmed.is_empty() {+ return;+ }+ let _ = writeln!(prompt, "### {label}\n");+ let truncated = if trimmed.chars().count() > max_chars {+ trimmed+ .char_indices()+ .nth(max_chars)+ .map(|(idx, _)| &trimmed[..idx])+ .unwrap_or(trimmed)+ } else {+ trimmed+ };+ prompt.push_str(truncated);+ if truncated.len() < trimmed.len() {+ let _ = writeln!(+ prompt,+ "\n\n[... truncated at {max_chars} chars — use `read` for full file]\n"+ );+ } else {+ prompt.push_str("\n\n");+ }+}++/// Shared `## Project instructions (AGENTS.md)` block writer.+///+/// Used by both [`super::sections::AgentsInstructionsSection`] (the default /+/// sub-agent builder chains) and the narrow sub-agent renderer+/// ([`render_subagent_system_prompt_with_format`]) so the two paths never+/// drift. The heading is emitted only when at least one layer carries content;+/// the global layer renders first, then the local/project layer. Each layer is+/// injected via [`inject_inline_content`] under its own `###` sub-heading and+/// capped at [`BOOTSTRAP_MAX_CHARS`] with a `[... truncated]` marker.+///+/// Both inputs are already-loaded, pre-trimmed strings (see+/// [`super::agents_md::load_agents_md`]) — this writer does no file I/O, keeping+/// the rendered bytes a pure function of its inputs for KV-cache stability.+pub(crate) fn write_agents_md_blocks(out: &mut String, global: Option<&str>, local: Option<&str>) {+ let mut body = String::new();+ if let Some(g) = global {+ inject_inline_content(&mut body, "AGENTS.md (workspace)", g, BOOTSTRAP_MAX_CHARS);+ }+ if let Some(l) = local {+ inject_inline_content(&mut body, "AGENTS.md (project)", l, BOOTSTRAP_MAX_CHARS);+ }+ if body.trim().is_empty() {+ log::debug!("[agents_md] no AGENTS.md content to inject; skipping section");+ return;+ }+ log::debug!(+ "[agents_md] injecting AGENTS.md section (global={}, local={})",+ global.is_some(),+ local.is_some()+ );+ out.push_str("## Project instructions (AGENTS.md)\n\n");+ out.push_str(+ "Configurable standing instructions loaded from AGENTS.md files. Treat these as \+ durable guidance for how to operate here. The workspace layer applies globally; \+ the project layer applies to the current working directory and takes precedence \+ where the two conflict. They are background guidance, not messages in this \+ conversation.\n\n",+ );+ out.push_str(&body);+}++/// for the output header and truncation semantics.+///+/// Empty/whitespace content is silently skipped, mirroring the file+/// loader's "no noisy placeholder" behaviour.+pub fn inject_snapshot_content(prompt: &mut String, label: &str, content: &str, max_chars: usize) {+ let trimmed = content.trim();+ if trimmed.is_empty() {+ return;+ }+ let _ = writeln!(prompt, "### {label}\n");+ let truncated = if trimmed.chars().count() > max_chars {+ trimmed+ .char_indices()+ .nth(max_chars)+ .map(|(idx, _)| &trimmed[..idx])+ .unwrap_or(trimmed)+ } else {+ trimmed+ };+ prompt.push_str(truncated);+ if truncated.len() < trimmed.len() {+ let _ = writeln!(+ prompt,+ "\n\n[... truncated at {max_chars} chars — use `read` for full file]\n"+ );+ } else {+ prompt.push_str("\n\n");+ }+}++/// Inject `filename` into `prompt` with an explicit character budget.+///+/// Used directly by callers that want a tighter cap than+/// [`BOOTSTRAP_MAX_CHARS`] — notably `PROFILE.md` and `MEMORY.md` which+/// are user-specific, potentially growing, and do not warrant a full+/// 20K-char budget (see [`USER_FILE_MAX_CHARS`]).+///+/// Missing / empty files are silently skipped so callers can inject+/// optional files unconditionally without emitting a noisy placeholder.+///+/// **KV-cache contract:** the output is a pure function of `filename`,+/// file bytes at call time, and `max_chars`. Callers must invoke this+/// once per session — re-reading mid-session breaks the inference+/// backend's automatic prefix cache. See the byte-stability note on+/// [`render_subagent_system_prompt`].+pub fn inject_workspace_file_capped(+ prompt: &mut String,+ workspace_dir: &Path,+ filename: &str,+ max_chars: usize,+) {+ let path = workspace_dir.join(filename);++ match std::fs::read_to_string(&path) {+ Ok(content) => {+ let trimmed = content.trim();+ if trimmed.is_empty() {+ return;+ }+ let _ = writeln!(prompt, "### {filename}\n");+ let truncated = if trimmed.chars().count() > max_chars {+ trimmed+ .char_indices()+ .nth(max_chars)+ .map(|(idx, _)| &trimmed[..idx])+ .unwrap_or(trimmed)+ } else {+ trimmed+ };+ prompt.push_str(truncated);+ if truncated.len() < trimmed.len() {+ let _ = writeln!(+ prompt,+ "\n\n[... truncated at {max_chars} chars — use `read` for full file]\n"+ );+ } else {+ prompt.push_str("\n\n");+ }+ }+ Err(e) => match e.kind() {+ std::io::ErrorKind::NotFound => {+ // Keep prompt focused: missing optional identity/bootstrap files should not+ // add noisy placeholders that dilute tool-calling instructions.+ }+ _ => {+ log::debug!("[prompt] failed to read {}: {e}", path.display());+ }+ },+ }+}++pub fn default_workspace_file_content(filename: &str) -> &'static str {+ // The bundled identity files live at `crates/openhuman-core/src/agent/prompts/`+ // (owned by the `agent/` tree because they describe agent identity).+ // This module is under `crates/openhuman-core/src/agent/context/`, so the relative path+ // walks up one level and back into `agent/prompts/`.+ match filename {+ "SOUL.md" => include_str!("SOUL.md"),+ "IDENTITY.md" => include_str!("IDENTITY.md"),+ // The user-facing agent's role brief and writing style, moved out of+ // the compiled `orchestrator/prompt.md` so both are tunable on disk+ // without a rebuild (#5701). Same sync-and-inject contract as+ // SOUL.md / IDENTITY.md: the bundled copy seeds the workspace, and a+ // user edit wins from the next session on.+ "ROLE.md" => include_str!("ROLE.md"),+ "STYLE.md" => include_str!("STYLE.md"),++ _ => "",+ }+}