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(memory): inline turn input structs into function parameters
Steven Enamakelea3567f560a3
diff --git a/crates/openhuman-core/src/memory/lifecycle/hooks.rs b/crates/openhuman-core/src/memory/lifecycle/hooks.rsindex 395266741f..2fab90f56f 100644--- a/crates/openhuman-core/src/memory/lifecycle/hooks.rs+++ b/crates/openhuman-core/src/memory/lifecycle/hooks.rs@@ -61,46 +61,25 @@ pub struct TurnPack {}impl TurnPack {- fn from_packs(packs: impl IntoIterator<Item = ContextPack>) -> Option<Self> {- let mut pack: Option<Self> = None;- for next in packs.into_iter().filter(|pack| !pack.is_empty()) {- let cited: Vec<crate::memory::types::TurnCitation> = next- .sections- .iter()- .flat_map(|section| section.hits.iter())- .filter(|hit| next.refs.contains(&hit.id))- .map(crate::memory::types::TurnCitation::from)- .collect();- let refs = next.refs.iter().map(ToString::to_string);- match &mut pack {- Some(pack) => {- pack.markdown.push_str("\n\n");- pack.markdown.push_str(&next.markdown);- pack.tokens += next.tokens;- for id in refs {- if !pack.refs.contains(&id) {- pack.refs.push(id);- }- }- for citation in cited {- if !pack.citations.iter().any(|known| known.id == citation.id) {- pack.citations.push(citation);- }- }- }- None => {- pack = Some(Self {- markdown: next.markdown,- tokens: next.tokens,- refs: refs.collect(),- engine: next.engine,- citations: cited,- refusal: None,- });- }- }+ fn from_pack(pack: ContextPack) -> Option<Self> {+ if pack.is_empty() {+ return None;}- pack+ let citations = pack+ .sections+ .iter()+ .flat_map(|section| section.hits.iter())+ .filter(|hit| pack.refs.contains(&hit.id))+ .map(crate::memory::types::TurnCitation::from)+ .collect();+ Some(Self {+ markdown: pack.markdown,+ tokens: pack.tokens,+ refs: pack.refs.iter().map(ToString::to_string).collect(),+ engine: pack.engine,+ citations,+ refusal: None,+ })}/// The notice a turn is given when its recall was refused outright, so@@ -179,79 +158,19 @@ impl MemoryTurn {}}-/// What the agent loop knows before the model runs.-#[derive(Debug, Clone)]-pub struct PreTurnInput {- /// The conversation thread.- pub thread_id: String,- /// The user message's index ([`user_turn_index`]).- pub turn_index: u32,- /// What the user said (without host-added context blocks).- pub user_text: String,- /// The first turn index still verbatim in the prompt; the pack leaves- /// the thread from there on out.- pub in_prompt_from: u32,- /// When the user sent it.- pub at: DateTime<Utc>,- /// The session resumes a thread whose earlier turns were compacted out- /// of the prompt: the pack opens with what the thread holds.- pub resumed_after_compaction: bool,- /// Who sent the message, when it is someone other than the memory's- /// owner: a channel's sender ([`super::sender::channel_actor`]). Logged- /// as the turn's observed actor, which the engine sends only with- /// `[memory] observed_actor` on.- pub observed_actor: Option<tinymemory_api::ObservedActor>,-}--/// Logs the user turn and recalls the pack it is given, within-/// `[memory.recall] pre_turn_timeout_ms`. `None` when memory is off, the-/// identity has neither logging nor recall, nothing relevant is stored, or-/// the engine is slow or failing — the turn runs either way. When nothing was-/// recalled because the engine refused the account (no credits, a rejected-/// credential, unreachable), the pack is a short notice saying so instead-/// ([`TurnPack::refusal`]).-///-/// The work is spawned, so a timed-out log still completes in the-/// background; only its pack is dropped.-pub async fn pre_turn(- ctx: &crate::core::runtime::DispatchCtx,- config: &Config,- identity: &ResolvedIdentity,- input: PreTurnInput,-) -> Option<TurnPack> {- let timeout = Duration::from_millis(config.memory.recall.pre_turn_timeout_ms.max(1));- let started = std::time::Instant::now();- let agent_id = identity.agent_id.clone();- let config = config.clone();- let dispatch = ctx.clone();- let identity = identity.clone();- let thread = input.thread_id.clone();- let task = ctx.spawn(async move { pre_turn_work(&dispatch, &config, &identity, input).await });- let pack = match tokio::time::timeout(timeout, task).await {- Ok(Ok(pack)) => pack,- Ok(Err(error)) => {- tracing::warn!(thread_id = %thread, %error, "[memory:hooks] pre_turn task failed");- None- }- Err(_) => {- tracing::warn!(thread_id = %thread, timeout_ms = timeout.as_millis() as u64, "[memory:hooks] pre_turn timed out; the turn runs without a pack");- None- }- };- if let Some(pack) = &pack {- crate::memory::tools::record_pack_citations(ctx, &thread, pack.citations.clone());- }- tracing::debug!(thread_id = %thread, %agent_id, injected = pack.is_some(), tokens = pack.as_ref().map_or(0, |pack| pack.tokens), refs = pack.as_ref().map_or(0, |pack| pack.refs.len()), elapsed_ms = started.elapsed().as_millis() as u64, "[memory:hooks] pre_turn");- pack-}-/// The direct lifecycle operation for bounded background workers. Unlike the/// manual timeout wrapper, its future owns all I/O and can be cancelled.pub(crate) async fn pre_turn_work(ctx: &crate::core::runtime::DispatchCtx,config: &Config,identity: &ResolvedIdentity,- input: PreTurnInput,+ thread_id: String,+ turn_index: u32,+ user_text: String,+ in_prompt_from: u32,+ at: DateTime<Utc>,+ resumed_after_compaction: bool,+ observed_actor: Option<tinymemory_api::ObservedActor>,) -> Option<TurnPack> {let logging = config.memory.conversations.enabled;if !logging && !identity.recall {@@ -286,7 +205,7 @@ pub(crate) async fn pre_turn_work(let date_hint = (recall && logging && config.memory.recall.date_hint).then(|| {let config = config.clone();let ctx = ctx.clone();- let text = input.user_text.clone();+ let text = user_text.clone();let deadline =tokio::time::Instant::now() + timeout.saturating_sub(Duration::from_millis(100));async move {@@ -303,13 +222,13 @@ pub(crate) async fn pre_turn_work(let pack = async move {// The first turn after a compaction gets one pack that leads with the// thread's earlier turns, under the turn's own budget and dedupe.- let resumed = recall && input.resumed_after_compaction;+ let resumed = recall && resumed_after_compaction;let turn = async {if logging {- let mut pre = PreTurn::new(&input.thread_id, input.turn_index, &input.user_text);- pre.in_prompt_from = input.in_prompt_from;- pre.at = Some(input.at);- pre.observed_actor = input.observed_actor.clone();+ let mut pre = PreTurn::new(&thread_id, turn_index, &user_text);+ pre.in_prompt_from = in_prompt_from;+ pre.at = Some(at);+ pre.observed_actor = observed_actor.clone();let context = match date_hint {Some(hint) => memory.pre_turn_dated(pre, resumed, hint).await,None if resumed => memory.pre_turn_resumed(pre).await,@@ -319,7 +238,7 @@ pub(crate) async fn pre_turn_work(Ok(context) => {if let Some(error) = &context.log_error {tracing::warn!(- thread_id = %input.thread_id,+ thread_id = %thread_id,error = %error,"[memory:hooks] user turn not logged");@@ -334,8 +253,8 @@ pub(crate) async fn pre_turn_work(} else if resumed {memory.start_session(SessionStart {- thread_id: Some(input.thread_id.clone()),- focus: Some(input.user_text.clone()),+ thread_id: Some(thread_id.clone()),+ focus: Some(user_text.clone()),}).await.map_err(|error| {@@ -343,7 +262,7 @@ pub(crate) async fn pre_turn_work(MemoryError::from(error)})} else {- memory.recall(&input.user_text).await.map_err(|error| {+ memory.recall(&user_text).await.map_err(|error| {tracing::warn!(%error, "[memory:hooks] recall failed");MemoryError::from(error)})@@ -355,7 +274,11 @@ pub(crate) async fn pre_turn_work(}let outcomes = [turn];let refusal = refusal_of(&outcomes);- TurnPack::from_packs(outcomes.into_iter().filter_map(Result::ok)).or_else(|| {+ outcomes+ .into_iter()+ .find_map(Result::ok)+ .and_then(TurnPack::from_pack)+ .or_else(|| {let error = refusal?;tracing::warn!(code = error.code(),@@ -363,7 +286,7 @@ pub(crate) async fn pre_turn_work("[memory:hooks] recall refused; the turn is told memory is unavailable");TurnPack::refused(&error, engine_id)- })+ })}.await;pack@@ -399,21 +322,6 @@ pub struct ToolCallSummary {pub result: Option<String>,}-/// What the agent loop knows once a turn is committed.-#[derive(Debug, Clone)]-pub struct PostTurnInput {- /// The conversation thread.- pub thread_id: String,- /// The reply's index: the user message's plus one.- pub turn_index: u32,- /// The final reply.- pub assistant_text: String,- /// Every tool call the turn made.- pub tool_calls: Vec<ToolCallSummary>,- /// When the reply was finished.- pub at: DateTime<Utc>,-}-/// The reply as logged: its text, then one `tool → result` line per call,/// so what a tool returned survives in memory even when the reply does not/// repeat it.@@ -443,11 +351,19 @@ pub fn logged_reply(text: &str, calls: &[ToolCallSummary]) -> String {/// Logs a committed reply and queues the belief builds TinyMemory hands/// back. Logs instead of failing.-pub async fn post_turn(config: &Config, identity: &ResolvedIdentity, input: PostTurnInput) {+pub async fn post_turn(+ config: &Config,+ identity: &ResolvedIdentity,+ thread_id: String,+ turn_index: u32,+ assistant_text: String,+ tool_calls: Vec<ToolCallSummary>,+ at: DateTime<Utc>,+) {if !config.memory.conversations.enabled {return;}- let text = logged_reply(&input.assistant_text, &input.tool_calls);+ let text = logged_reply(&assistant_text, &tool_calls);if text.is_empty() {return;}@@ -462,10 +378,9 @@ pub async fn post_turn(config: &Config, identity: &ResolvedIdentity, input: Postreturn;}};- let mut post = PostTurn::new(&input.thread_id, input.turn_index, text);- post.at = Some(input.at);- post.tool_calls = input- .tool_calls+ let mut post = PostTurn::new(&thread_id, turn_index, text);+ post.at = Some(at);+ post.tool_calls = tool_calls.iter().map(|call| ToolCallRef {name: call.name.clone(),@@ -478,9 +393,9 @@ pub async fn post_turn(config: &Config, identity: &ResolvedIdentity, input: Postmatch posted {Ok(report) => {tracing::debug!(- thread_id = %input.thread_id,+ thread_id = %thread_id,agent_id = %identity.agent_id,- turn = input.turn_index,+ turn = turn_index,jobs = report.jobs.len(),elapsed_ms,"[memory:hooks] reply logged"@@ -498,30 +413,6 @@ pub async fn post_turn(config: &Config, identity: &ResolvedIdentity, input: Post}}-/// Recalls what the compacted `dropped` turns carried, within-/// `[memory.recall] compaction_timeout_ms`. `None` when memory is off or-/// recall is off for the identity, or nothing comes back in time.-pub async fn compaction(- config: &Config,- identity: &ResolvedIdentity,- thread_id: &str,- dropped: Vec<Turn>,-) -> Option<TurnPack> {- let timeout = Duration::from_millis(config.memory.recall.compaction_timeout_ms.max(1));- match tokio::time::timeout(- timeout,- compaction_work(config, identity, thread_id, dropped),- )- .await- {- Ok(pack) => pack,- Err(_) => {- tracing::warn!(thread_id, "[memory:hooks] compaction recall timed out");- None- }- }-}-/// Direct compaction recall, owned and cancelled by the background worker.pub(crate) async fn compaction_work(config: &Config,@@ -541,7 +432,7 @@ pub(crate) async fn compaction_work(focus: None,};let pack = match memory.recall_for_compaction(request).await {- Ok(pack) => TurnPack::from_packs([pack]),+ Ok(pack) => TurnPack::from_pack(pack),Err(error) => {tracing::warn!(%error, "[memory:hooks] compaction recall failed");None