Skip to content

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

chore: files changed crates/openhuman-core/src/memory/lifecycle/date_hint.rs,crates/openhuman-core/s

Steven Enamakel295b8e9ee7c4
diff --git a/crates/openhuman-core/src/memory/lifecycle/date_hint.rs b/crates/openhuman-core/src/memory/lifecycle/date_hint.rs
index 8d252ccbd2..3af9057dbf 100644
--- a/crates/openhuman-core/src/memory/lifecycle/date_hint.rs
+++ b/crates/openhuman-core/src/memory/lifecycle/date_hint.rs
@@ -1,79 +1,74 @@
-//! Which days a user turn is about, worked out by one small model call that
-//! runs beside the pre-turn recall (`[memory.recall] date_hint`, off by
-//! default). Any language: the model reads "kal", "el viernes", "letzte
-//! Woche" against the date line, which no keyword list can.
-//!
-//! The hint only reorders the pack's fetch sections (memories from those
-//! days first); a late, failed or unparseable answer leaves the pack as it
-//! would have been. Measured through the managed route (2026-10-08): p50
-//! ≈ 3 s, so with the 1.5 s default budget most turns finish without it.
+//! OpenHuman's model callback for TinyMemory's runtime-neutral date hint.
-use chrono::NaiveDate;
-use tinyinference_llm::message::Message;
-use tinyinference_llm::model::ModelRequest;
-use tinymemory_api::TimeHint;
+use std::sync::Arc;
+
+use futures::future::BoxFuture;
+use tinymemory_tools::lifecycle::date_hint::DateHintModel;
use crate::config::Config;
+use crate::core::runtime::DispatchCtx;
-const INSTRUCTION: &str = "Return the calendar date range (local dates) that the user's message refers to, as JSON only: {\"from\":\"YYYY-MM-DD\",\"to\":\"YYYY-MM-DD\"}, or {\"from\":null,\"to\":null} when it refers to no date. Resolve relative words (yesterday, last week, a weekday, a month) against the current date. A single day has from == to. If a word can mean either the past or the future (e.g. Hindi/Hinglish 'kal', 'parso'), return a window covering both readings.";
+pub(super) fn model(ctx: DispatchCtx, config: Arc<Config>) -> Arc<dyn DateHintModel> {
+ Arc::new(HostDateHintModel { ctx, config })
+}
-/// The days `user_text` is about, in `zone`, from the user's chat model.
-/// `None` when it names no time, or the call fails or answers nonsense.
-///
-/// Not bounded here: the caller owns the deadline in the pre-turn work, as
-/// tinymemory's `pre_turn_dated` requires of its hint.
-pub async fn extract(
- ctx: &crate::core::runtime::DispatchCtx,
- config: &Config,
- user_text: &str,
- zone: &str,
-) -> Option<TimeHint> {
- let (model, model_id) = match crate::inference::provider::create_chat_model_with_model_id_in(
- ctx, "chat", config, 0.0,
- ) {
- Ok(model) => model,
- Err(error) => {
- tracing::debug!(%error, "[memory:date_hint] no chat model");
- return None;
- }
- };
- let system = format!(
- "{}\n\n{INSTRUCTION}",
- crate::agent::prompts::current_datetime_line(Some(zone))
- );
- let mut request = ModelRequest::new(vec![Message::system(system), Message::user(user_text)]);
- request.max_tokens = Some(400);
- request.temperature = Some(0.0);
- let started = std::time::Instant::now();
- let answer = model.invoke(&(), request).await;
- let elapsed_ms = started.elapsed().as_millis() as u64;
- match answer {
- Ok(response) => {
- let hint = parse(&response.text(), zone);
- tracing::debug!(model = %model_id, elapsed_ms, dated = hint.is_some(), "[memory:date_hint] extracted");
- hint
- }
- Err(error) => {
- tracing::debug!(model = %model_id, elapsed_ms, %error, "[memory:date_hint] call failed");
- None
- }
- }
+struct HostDateHintModel {
+ ctx: DispatchCtx,
+ config: Arc<Config>,
}
-/// The `{"from","to"}` object in a model's answer (code fences and prose
-/// around it are tolerated) as a hint in `zone`.
-fn parse(answer: &str, zone: &str) -> Option<TimeHint> {
- #[derive(serde::Deserialize)]
- struct Range {
- from: Option<NaiveDate>,
- to: Option<NaiveDate>,
+impl DateHintModel for HostDateHintModel {
+ fn complete(
+ &self,
+ instruction: String,
+ user_text: String,
+ zone: String,
+ ) -> BoxFuture<'static, Option<String>> {
+ let ctx = self.ctx.clone();
+ let config = self.config.clone();
+ Box::pin(async move {
+ let (model, model_id) =
+ match crate::inference::provider::create_chat_model_with_model_id_in(
+ &ctx, "chat", &config, 0.0,
+ ) {
+ Ok(model) => model,
+ Err(error) => {
+ tracing::debug!(%error, "[memory:date_hint] no chat model");
+ return None;
+ }
+ };
+ let system = format!(
+ "{}\n\n{instruction}",
+ crate::agent::prompts::current_datetime_line(Some(&zone))
+ );
+ let mut request = tinyinference_llm::model::ModelRequest::new(vec![
+ tinyinference_llm::message::Message::system(system),
+ tinyinference_llm::message::Message::user(user_text),
+ ]);
+ request.max_tokens = Some(400);
+ request.temperature = Some(0.0);
+ let started = std::time::Instant::now();
+ match model.invoke(&(), request).await {
+ Ok(response) => {
+ let elapsed_ms = started.elapsed().as_millis() as u64;
+ tracing::debug!(
+ model = %model_id,
+ elapsed_ms,
+ "[memory:date_hint] model answered"
+ );
+ Some(response.text())
+ }
+ Err(error) => {
+ let elapsed_ms = started.elapsed().as_millis() as u64;
+ tracing::debug!(
+ model = %model_id,
+ elapsed_ms,
+ %error,
+ "[memory:date_hint] call failed"
+ );
+ None
+ }
+ }
+ })
}
- let json = answer.get(answer.find('{')?..=answer.rfind('}')?)?;
- let range: Range = serde_json::from_str(json).ok()?;
- let from = range.from?;
- TimeHint::new(from, range.to.unwrap_or(from), Some(zone.to_string())).ok()
}
-
-#[cfg(test)]
-#[path = "date_hint_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/memory/lifecycle/hooks.rs b/crates/openhuman-core/src/memory/lifecycle/hooks.rs
index db79ca5e91..3a56977c84 100644
--- a/crates/openhuman-core/src/memory/lifecycle/hooks.rs
+++ b/crates/openhuman-core/src/memory/lifecycle/hooks.rs
@@ -1,167 +1,218 @@
-//! The turn-side hooks: pre-turn, post-turn and compaction.
-//!
-//! The agent loop calls these; each is bounded, logs instead of failing, and
-//! returns nothing the turn depends on. See `crates/openhuman-core/src/agent/
-//! session_host/runtime_session.rs` (pre-turn), `memory::bus` (post-turn,
-//! through `ConversationTurnCommitted`) and `agent/tinyagents/
-//! memory_summarizer.rs` (compaction).
-//!
-//! Turn indices follow the committed transcript: the user message of the
-//! turn that follows `n` committed turns is `2n`, its reply `2n + 1`. They
-//! are stable across retries and restarts, which is what lets TinyMemory
-//! recognise a retried turn as a duplicate.
+//! OpenHuman adapters for TinyMemory's runtime-neutral turn hooks.
+use std::sync::{Arc, Weak};
use std::time::Duration;
+use async_trait::async_trait;
use chrono::{DateTime, Utc};
use serde::Serialize;
-use tinymemory_api::{Error, ToolCallRef, Turn};
-use tinymemory_tools::recall::SkipReason;
-use tinymemory_tools::{Compaction, ContextPack, PostTurn, PreTurn, SessionStart};
+use tinymemory_api::{Hit, ObservedActor, ThreadWindow, ToolCallRef, Turn};
+use tinymemory_tools::layout::identity::ResolvedIdentity;
+use tinymemory_tools::lifecycle::turn::{
+ self as native_turn, CitationSink, Clock, CompactionOptions, DateHintModel, EngineResolver,
+ JobsSink, LoggedToolCall, PostTurn, PreTurn, PreTurnOptions, TurnHooks as NativeTurnHooks,
+ TurnPack as NativeTurnPack,
+};
+use tinymemory_tools::{AgentMemory, BackgroundJob};
use crate::config::Config;
+use crate::core::runtime::{CoreContext, DispatchCtx};
use crate::memory::engine;
-use tinymemory_tools::layout::identity::ResolvedIdentity;
-
-use super::{agent_memory_on, jobs, log_only};
-
-/// Opening tag of an injected pack.
-pub const OPEN_TAG: &str = "<memory-context>";
-/// Closing tag of an injected pack.
-pub const CLOSE_TAG: &str = "</memory-context>";
-/// Longest tool result line appended to a logged reply, in characters.
-const MAX_TOOL_LINE_CHARS: usize = 240;
+pub use native_turn::{CLOSE_TAG, MAX_TOOL_LINE_CHARS, OPEN_TAG};
/// The user message's index for a turn that follows `committed_turns`.
#[must_use]
pub fn user_turn_index(committed_turns: usize) -> u32 {
- u32::try_from(committed_turns.saturating_mul(2)).unwrap_or(u32::MAX - 1)
+ native_turn::user_turn_index(committed_turns)
}
-/// The context a turn is given: one rendered pack and what it cites.
-#[derive(Debug, Clone, PartialEq, Serialize)]
+/// A native turn pack with the citation view used by OpenHuman's chat UI.
+#[derive(Debug, Clone, Serialize)]
pub struct TurnPack {
- /// The block, rendered by TinyMemory; never empty.
- pub markdown: String,
- /// Its estimated tokens.
- pub tokens: usize,
- /// The ids of every item it cites, in order.
- pub refs: Vec<String>,
- /// The engine that answered.
- pub engine: String,
- /// The cited items, for the chat's memory chips.
+ /// TinyMemory's authoritative pack and refusal state.
+ #[serde(flatten)]
+ pub native: NativeTurnPack,
+ /// The citation view attached to the chat reply, not serialized with the pack.
#[serde(skip)]
pub citations: Vec<crate::web_chat::TurnCitation>,
- /// Set when nothing was recalled because the engine refused the whole
- /// account (a `Error` code such as `INSUFFICIENT_CREDITS`): the
- /// block is then a notice saying so, not recalled memory.
- #[serde(skip_serializing_if = "Option::is_none")]
- pub refusal: Option<&'static str>,
}
impl TurnPack {
- fn from_pack(pack: ContextPack) -> Option<Self> {
- if pack.is_empty() {
- return None;
- }
- let citations = pack
- .sections
+ /// Adapts generic TinyMemory hits to the citation shape used by web chat.
+ #[must_use]
+ pub fn from_native(native: NativeTurnPack) -> Self {
+ let citations = native
+ .citations
.iter()
- .flat_map(|section| section.hits.iter())
- .filter(|hit| pack.refs.contains(&hit.id))
.map(crate::web_chat::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
- /// the model does not read an empty pack as "nothing is stored" and tell
- /// the user so (#6718). `None` for a failure that is not account-wide.
- fn refused(error: &Error, engine: String) -> Option<Self> {
- let why = match error {
- Error::InsufficientCredits(_) => {
- "the account is out of credits; topping up restores it"
- }
- Error::Unauthorized(_) => "the memory engine rejected the sign-in or API key",
- Error::Unavailable(_) => "the memory engine could not be reached",
- _ => return None,
- };
- let markdown = format!(
- "# Memory\n\nMemory could not be read for this turn: {why}. Nothing was \
- recalled, which does not mean nothing is stored. If the user refers to \
- something they told you before, say that memory is unavailable right now \
- and why, instead of saying you do not know it."
- );
- Some(Self {
- tokens: tinymemory_tools::recall::estimate_tokens(&markdown),
- markdown,
- refs: Vec::new(),
- engine,
- citations: Vec::new(),
- refusal: Some(error.code()),
- })
+ Self { native, citations }
}
/// The block as the model sees it.
#[must_use]
pub fn injection(&self) -> String {
- format!("{OPEN_TAG}\n{}\n{CLOSE_TAG}", self.markdown.trim())
+ self.native.injection()
}
}
-/// One turn's memory, carried on its run context: what the compaction hook
-/// needs to recall for this thread under this identity, and the pack the
-/// turn was given.
+/// One turn's memory, carried on its run context.
#[derive(Debug, Clone)]
pub struct MemoryTurn {
/// The config the session runs under.
- pub config: std::sync::Arc<Config>,
+ pub config: Arc<Config>,
/// Who the turn runs as.
pub identity: ResolvedIdentity,
/// The conversation thread.
pub thread_id: String,
/// The pack the turn was given, if any.
pub pack: Option<TurnPack>,
- /// The first turn of the thread still verbatim in the turn's prompt: the
- /// turns before it were compacted into a checkpoint (0 when nothing was).
- /// Live: a compaction during the turn moves it forward.
- pub in_prompt_from: std::sync::Arc<super::window::InPromptFrom>,
- /// The context the turn runs under, held weakly so a finished tenant's
- /// lease is not kept alive by a lingering turn handle.
- pub core: Option<std::sync::Weak<crate::core::runtime::CoreContext>>,
+ /// The first user turn still verbatim in this turn's prompt.
+ pub in_prompt_from: Arc<tinymemory_tools::lifecycle::window::InPromptFrom>,
+ /// The turn's core context, held weakly so a finished tenant's lease is not retained.
+ pub core: Option<Weak<CoreContext>>,
}
impl MemoryTurn {
- /// The thread's turns still verbatim in the turn's prompt, which the
- /// agent's own memory reads leave out (the compacted ones stay readable).
+ /// The thread's turns still verbatim in the prompt.
#[must_use]
- pub fn in_prompt(&self) -> tinymemory_api::ThreadWindow {
- tinymemory_api::ThreadWindow {
+ pub fn in_prompt(&self) -> ThreadWindow {
+ ThreadWindow {
thread_id: self.thread_id.clone(),
from_turn: self.in_prompt_from.get(),
}
}
- /// The dispatch context the turn's memory work runs under: its own, else
- /// the calling task's.
+ /// The dispatch context for this turn, falling back to the caller's context.
#[must_use]
- pub fn dispatch_ctx(&self) -> crate::core::runtime::DispatchCtx {
- crate::core::runtime::DispatchCtx::from_weak(self.core.as_ref())
+ pub fn dispatch_ctx(&self) -> DispatchCtx {
+ DispatchCtx::from_weak(self.core.as_ref())
}
}
-/// The direct lifecycle operation for bounded background workers. Unlike the
-/// manual timeout wrapper, its future owns all I/O and can be cancelled.
+/// A tool call paired with the one-line result included in the logged reply.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct ToolCallSummary {
+ /// The tool's name.
+ pub name: String,
+ /// The call id.
+ pub id: Option<String>,
+ /// The start of its result, if it produced one.
+ pub result: Option<String>,
+}
+
+fn native_tool_calls(calls: &[ToolCallSummary]) -> Vec<LoggedToolCall> {
+ calls
+ .iter()
+ .map(|call| LoggedToolCall {
+ call: ToolCallRef {
+ name: call.name.clone(),
+ id: call.id.clone(),
+ },
+ result: call.result.clone(),
+ })
+ .collect()
+}
+
+/// Formats the reply and one bounded result line per tool call.
+#[must_use]
+pub fn logged_reply(text: &str, calls: &[ToolCallSummary]) -> String {
+ native_turn::logged_reply(text, &native_tool_calls(calls))
+}
+
+struct HostEngineResolver {
+ config: Arc<Config>,
+ identity: ResolvedIdentity,
+}
+
+impl EngineResolver for HostEngineResolver {
+ fn resolve(&self) -> tinymemory_api::Result<AgentMemory> {
+ let bound = engine::resolve(&self.config).engine()?;
+ super::agent_memory_on(bound.engine, &self.config, &self.identity)
+ }
+}
+
+struct TokioClock {
+ origin: tokio::time::Instant,
+}
+
+impl Clock for TokioClock {
+ fn now(&self) -> Duration {
+ tokio::time::Instant::now().saturating_duration_since(self.origin)
+ }
+
+ fn sleep_until(&self, deadline: Duration) -> BoxFuture<'static, ()> {
+ let deadline = self.origin + deadline;
+ Box::pin(async move { tokio::time::sleep_until(deadline).await })
+ }
+}
+
+struct HostJobsSink {
+ config: Arc<Config>,
+ root: tinymemory_api::Namespace,
+}
+
+#[async_trait]
+impl JobsSink for HostJobsSink {
+ async fn enqueue(&self, jobs: Vec<BackgroundJob>) {
+ super::jobs::enqueue(&self.config, &self.root, jobs).await;
+ }
+}
+
+struct HostCitationSink {
+ ctx: DispatchCtx,
+ thread_id: String,
+}
+
+impl CitationSink for HostCitationSink {
+ fn deliver(&self, citations: Vec<Hit>) {
+ crate::web_chat::citations::record_pack_citations(
+ &self.ctx,
+ &self.thread_id,
+ citations
+ .iter()
+ .map(crate::web_chat::TurnCitation::from)
+ .collect(),
+ );
+ }
+}
+
+fn turn_hooks(
+ ctx: &DispatchCtx,
+ config: &Arc<Config>,
+ identity: &ResolvedIdentity,
+ thread_id: &str,
+) -> Arc<NativeTurnHooks> {
+ let resolver = Arc::new(HostEngineResolver {
+ config: config.clone(),
+ identity: identity.clone(),
+ });
+ let clock = Arc::new(TokioClock {
+ origin: tokio::time::Instant::now(),
+ });
+ let date_hint_model = Some(super::date_hint::model(ctx.clone(), config.clone()));
+ let jobs = Arc::new(HostJobsSink {
+ config: config.clone(),
+ root: identity.root(),
+ });
+ let citations = Arc::new(HostCitationSink {
+ ctx: ctx.clone(),
+ thread_id: thread_id.to_owned(),
+ });
+ Arc::new(NativeTurnHooks::new(
+ resolver,
+ clock,
+ date_hint_model,
+ jobs,
+ citations,
+ ))
+}
+
+/// Runs one bounded pre-turn operation through TinyMemory's lifecycle hooks.
+#[allow(clippy::too_many_arguments)]
pub(crate) async fn pre_turn_work(
- ctx: &crate::core::runtime::DispatchCtx,
+ ctx: &DispatchCtx,
config: &Config,
identity: &ResolvedIdentity,
thread_id: String,
@@ -170,197 +221,48 @@ pub(crate) async fn pre_turn_work(
in_prompt_from: u32,
at: DateTime<Utc>,
resumed_after_compaction: bool,
- observed_actor: Option<tinymemory_api::ObservedActor>,
+ observed_actor: Option<ObservedActor>,
channel: Option<String>,
) -> Option<TurnPack> {
+ let config = Arc::new(config.clone());
+ let mut turn = PreTurn::new(thread_id.clone(), turn_index, user_text);
+ turn.in_prompt_from = in_prompt_from;
+ turn.at = Some(at);
+ turn.resumed = resumed_after_compaction;
+ turn.observed_actor = observed_actor;
+ turn.channel = channel;
let logging = config.memory.conversations.enabled;
- if !logging && !identity.recall {
- return None;
- }
- let bound = match engine::resolve(config).engine() {
- Ok(bound) => bound,
- Err(error) => {
- tracing::debug!(%error, "[memory:hooks] pre_turn skipped: memory off");
- return None;
- }
- };
- let engine_id = bound.engine.descriptor().id.to_string();
- let memory = match agent_memory_on(bound.engine, config, identity) {
- Ok(memory) => memory,
- Err(error) => {
- tracing::warn!(%error, "[memory:hooks] pre_turn skipped: no agent memory");
- return None;
- }
- };
- let memory = if identity.recall {
- memory
- } else {
- let quiet = log_only(memory.policy().clone());
- memory.with_policy(quiet)
- };
let recall = identity.recall;
- let timeout = Duration::from_millis(config.memory.recall.pre_turn_timeout_ms.max(1));
- // Runs beside the turn log and the reads (tinymemory joins all three) and
- // answers by the turn's own deadline less a margin, counted from now, so
- // the pack is still ranked and returned before the turn stops waiting.
- let date_hint = (recall && logging && config.memory.recall.date_hint).then(|| {
- let config = config.clone();
- let ctx = ctx.clone();
- let text = user_text.clone();
- let deadline =
- tokio::time::Instant::now() + timeout.saturating_sub(Duration::from_millis(100));
- async move {
- let zone = config.time_zone();
- tokio::time::timeout_at(
- deadline,
- super::date_hint::extract(&ctx, &config, &text, &zone),
- )
- .await
- .ok()
- .flatten()
- }
- });
- 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 && resumed_after_compaction;
- let turn = async {
- if logging {
- 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();
- pre.channel = channel.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,
- None => memory.pre_turn(pre).await,
- };
- match context {
- Ok(context) => {
- if let Some(error) = &context.log_error {
- tracing::warn!(
- thread_id = %thread_id,
- error = %error,
- "[memory:hooks] user turn not logged"
- );
- }
- Ok(context.pack)
- }
- Err(error) => {
- tracing::warn!(%error, "[memory:hooks] pre_turn refused");
- Err(error)
- }
- }
- } else if resumed {
- memory
- .start_session(SessionStart {
- thread_id: Some(thread_id.clone()),
- focus: Some(user_text.clone()),
- })
- .await
- .map_err(|error| {
- tracing::warn!(%error, "[memory:hooks] recall failed");
- error
- })
- } else {
- memory.recall(&user_text).await.map_err(|error| {
- tracing::warn!(%error, "[memory:hooks] recall failed");
- error
- })
- }
- }
- .await;
- if !recall {
- return None;
- }
- let outcomes = [turn];
- let refusal = refusal_of(&outcomes);
- outcomes
- .into_iter()
- .find_map(Result::ok)
- .and_then(TurnPack::from_pack)
- .or_else(|| {
- let error = refusal?;
- tracing::warn!(
- code = error.code(),
- %error,
- "[memory:hooks] recall refused; the turn is told memory is unavailable"
- );
- TurnPack::refused(&error, engine_id)
- })
- }
- .await;
- pack
-}
-
-/// The account-wide refusal behind a recall that came back empty, if any:
-/// the first refusing error, else the first refusing skipped section.
-fn refusal_of(outcomes: &[std::result::Result<ContextPack, Error>]) -> Option<Error> {
- let failed = outcomes.iter().find_map(|outcome| {
- outcome
- .as_ref()
- .err()
- .filter(|error| error.is_account_wide())
- .cloned()
- });
- failed.or_else(|| {
- outcomes
- .iter()
- .filter_map(|outcome| outcome.as_ref().ok())
- .flat_map(|pack| pack.skipped.iter())
- .find_map(|skipped| account_wide_skip_reason(&skipped.reason).cloned())
- })
-}
-
-fn account_wide_skip_reason(reason: &SkipReason) -> Option<&Error> {
- match reason {
- SkipReason::Engine(error) if error.is_account_wide() => Some(error),
- SkipReason::Empty | SkipReason::Engine(_) => None,
- }
-}
-
-/// A tool call the reply made, with a one-line result.
-#[derive(Debug, Clone, PartialEq, Eq)]
-pub struct ToolCallSummary {
- /// The tool's name.
- pub name: String,
- /// The call id.
- pub id: Option<String>,
- /// The start of its result, if it produced one.
- pub result: Option<String>,
+ let hooks = turn_hooks(ctx, &config, identity, &thread_id);
+ let options = PreTurnOptions {
+ logging,
+ recall,
+ timeout: Duration::from_millis(config.memory.recall.pre_turn_timeout_ms.max(1)),
+ date_hint: logging && recall && config.memory.recall.date_hint,
+ zone: Some(config.time_zone()),
+ date_hint_margin: Duration::from_millis(100),
+ };
+ hooks
+ .pre_turn_work(turn, options)
+ .await
+ .map(TurnPack::from_native)
}
-/// 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.
-#[must_use]
-pub fn logged_reply(text: &str, calls: &[ToolCallSummary]) -> String {
- let lines: Vec<String> = calls
- .iter()
- .filter_map(|call| {
- let result = call
- .result
- .as_deref()?
- .split_whitespace()
- .collect::<Vec<_>>()
- .join(" ");
- (!result.is_empty()).then(|| {
- let result: String = result.chars().take(MAX_TOOL_LINE_CHARS).collect();
- format!("- {} → {result}", call.name)
- })
- })
- .collect();
- if lines.is_empty() {
- text.trim().to_string()
- } else {
- format!("{}\n\nTools:\n{}", text.trim(), lines.join("\n"))
- }
+/// Queues citations through TinyMemory's explicit shown-pack delivery hook.
+pub(crate) fn deliver_citations(
+ ctx: &DispatchCtx,
+ config: &Config,
+ identity: &ResolvedIdentity,
+ thread_id: &str,
+ pack: &TurnPack,
+) {
+ let hooks = turn_hooks(ctx, &Arc::new(config.clone()), identity, thread_id);
+ hooks.deliver_citations(&pack.native);
}
-/// Logs a committed reply and queues the belief builds TinyMemory hands
-/// back. Logs instead of failing.
+/// Logs a committed reply and awaits queuing the jobs returned by TinyMemory.
pub async fn post_turn(
+ ctx: &DispatchCtx,
config: &Config,
identity: &ResolvedIdentity,
thread_id: String,
@@ -373,89 +275,43 @@ pub async fn post_turn(
if !config.memory.conversations.enabled {
return;
}
- let text = logged_reply(&assistant_text, &tool_calls);
+ let native_calls = native_tool_calls(&tool_calls);
+ let text = native_turn::logged_reply(&assistant_text, &native_calls);
if text.is_empty() {
return;
}
- let bound = match engine::resolve(config).engine() {
- Ok(bound) => bound,
- Err(_) => return,
- };
- let memory = match agent_memory_on(bound.engine, config, identity) {
- Ok(memory) => memory,
- Err(error) => {
- tracing::warn!(%error, "[memory:hooks] post_turn skipped");
- return;
- }
- };
- let mut post = PostTurn::new(&thread_id, turn_index, text);
- post.channel = channel;
- post.at = Some(at);
- post.tool_calls = tool_calls
- .iter()
- .map(|call| ToolCallRef {
- name: call.name.clone(),
- id: call.id.clone(),
- })
- .collect();
- let started = std::time::Instant::now();
- let posted = memory.post_turn(post).await;
- let elapsed_ms = started.elapsed().as_millis() as u64;
- match posted {
- Ok(report) => {
- tracing::debug!(
- thread_id = %thread_id,
- agent_id = %identity.agent_id,
- turn = turn_index,
- jobs = report.jobs.len(),
- elapsed_ms,
- "[memory:hooks] reply logged"
- );
- jobs::enqueue(config, identity.root(), report.jobs).await;
- }
- Err(error) => {
- tracing::warn!(
- thread_id = %thread_id,
- %error,
- elapsed_ms,
- "[memory:hooks] reply not logged"
- );
- }
- }
+ let mut turn = PostTurn::new(thread_id.clone(), turn_index, text);
+ turn.channel = channel;
+ turn.at = Some(at);
+ turn.tool_calls = native_calls.into_iter().map(|call| call.call).collect();
+ turn_hooks(ctx, &Arc::new(config.clone()), identity, &thread_id)
+ .post_turn(turn, true)
+ .await;
}
/// Direct compaction recall, owned and cancelled by the background worker.
pub(crate) async fn compaction_work(
+ ctx: &DispatchCtx,
config: &Config,
identity: &ResolvedIdentity,
thread_id: &str,
dropped: Vec<Turn>,
) -> Option<TurnPack> {
- if !identity.recall || dropped.is_empty() || thread_id.trim().is_empty() {
- return None;
- }
- let bound = engine::resolve(config).engine().ok()?;
- let memory = agent_memory_on(bound.engine, config, identity).ok()?;
- let count = dropped.len();
- let request = Compaction {
- thread_id: thread_id.to_string(),
- dropped,
- focus: None,
- };
- let pack = match memory.recall_for_compaction(request).await {
- Ok(pack) => TurnPack::from_pack(pack),
- Err(error) => {
- tracing::warn!(%error, "[memory:hooks] compaction recall failed");
- None
- }
- };
- tracing::debug!(
- thread_id,
- dropped = count,
- recalled = pack.is_some(),
- "[memory:hooks] compaction"
- );
- pack
+ let hooks = turn_hooks(ctx, &Arc::new(config.clone()), identity, thread_id);
+ hooks
+ .compaction(
+ native_turn::Compaction {
+ thread_id: thread_id.to_owned(),
+ dropped,
+ focus: None,
+ },
+ CompactionOptions {
+ recall: identity.recall,
+ timeout: Duration::from_millis(config.memory.recall.compaction_timeout_ms.max(1)),
+ },
+ )
+ .await
+ .map(TurnPack::from_native)
}
#[cfg(test)]