Skip to content

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

feat(memory): optionally date the pre-turn pack with a model call

M3gA-Minde97a3014a7c8
diff --git a/crates/openhuman-core/src/config/schema/memory.rs b/crates/openhuman-core/src/config/schema/memory.rs
index 134f20ad30..5d2b899864 100644
--- a/crates/openhuman-core/src/config/schema/memory.rs
+++ b/crates/openhuman-core/src/config/schema/memory.rs
@@ -21,6 +21,7 @@
//! team_limit = 3
//! build_beliefs_every = 10 # turns between belief builds; 0 turns them off
//! pre_turn_timeout_ms = 1500
+//! date_hint = false # a model call works out which days a turn is about
//! compaction_timeout_ms = 8000
//! build_delay_secs = 300 # how far belief builds run behind the writes
//!
@@ -246,6 +247,11 @@ pub struct MemoryRecallConfig {
pub build_beliefs_every: u32,
/// How long a turn waits for its pack before running without one.
pub pre_turn_timeout_ms: u64,
+ /// Whether a small model call, beside the recall, works out which days
+ /// the turn is about so the pack leads with memories from them. Off by
+ /// default: it costs a model call per turn and often misses the
+ /// pre-turn deadline.
+ pub date_hint: bool,
/// How long a compaction waits for its recalled context.
pub compaction_timeout_ms: u64,
/// How long a queued belief build waits before it runs, so the engine's
@@ -264,6 +270,7 @@ impl Default for MemoryRecallConfig {
team_limit: 3,
build_beliefs_every: 10,
pre_turn_timeout_ms: DEFAULT_PRE_TURN_TIMEOUT_MS,
+ date_hint: false,
compaction_timeout_ms: DEFAULT_COMPACTION_TIMEOUT_MS,
build_delay_secs: DEFAULT_BUILD_DELAY_SECS,
}
diff --git a/crates/openhuman-core/src/memory/lifecycle/date_hint.rs b/crates/openhuman-core/src/memory/lifecycle/date_hint.rs
new file mode 100644
index 0000000000..e572a5514d
--- /dev/null
+++ b/crates/openhuman-core/src/memory/lifecycle/date_hint.rs
@@ -0,0 +1,70 @@
+//! 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.
+
+use chrono::NaiveDate;
+use tinyinference_llm::message::Message;
+use tinyinference_llm::model::ModelRequest;
+use tinymemory_api::TimeHint;
+
+use crate::config::Config;
+
+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.";
+
+/// 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.
+pub async fn extract(config: &Config, user_text: &str, zone: &str) -> Option<TimeHint> {
+ let (model, model_id) =
+ match crate::inference::provider::create_chat_model_with_model_id("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
+ }
+ }
+}
+
+/// 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>,
+ }
+ 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/date_hint_tests.rs b/crates/openhuman-core/src/memory/lifecycle/date_hint_tests.rs
new file mode 100644
index 0000000000..8034ecb59d
--- /dev/null
+++ b/crates/openhuman-core/src/memory/lifecycle/date_hint_tests.rs
@@ -0,0 +1,33 @@
+use super::*;
+
+fn day(d: u32) -> NaiveDate {
+ NaiveDate::from_ymd_opt(2026, 10, d).unwrap()
+}
+
+#[test]
+fn a_range_in_the_answer_is_a_hint_in_the_users_zone() {
+ let hint = parse(
+ "```json\n{\"from\":\"2026-10-06\",\"to\":\"2026-10-08\"}\n```",
+ "Asia/Kolkata",
+ )
+ .expect("a hint");
+ assert_eq!(
+ hint,
+ TimeHint::new(day(6), day(8), Some("Asia/Kolkata".into())).unwrap()
+ );
+ let single = parse("{\"from\":\"2026-10-03\"}", "UTC").expect("one day");
+ assert_eq!((single.from, single.to), (day(3), day(3)));
+}
+
+#[test]
+fn no_date_or_nonsense_is_no_hint() {
+ for answer in [
+ "{\"from\":null,\"to\":null}",
+ "no date here",
+ "{\"from\":\"last Saturday\"}",
+ "{\"from\":\"2026-10-08\",\"to\":\"2026-10-06\"}",
+ "} {",
+ ] {
+ assert_eq!(parse(answer, "UTC"), None, "{answer}");
+ }
+}
diff --git a/crates/openhuman-core/src/memory/lifecycle/hooks.rs b/crates/openhuman-core/src/memory/lifecycle/hooks.rs
index 0d666341ec..4a10a28e72 100644
--- a/crates/openhuman-core/src/memory/lifecycle/hooks.rs
+++ b/crates/openhuman-core/src/memory/lifecycle/hooks.rs
@@ -216,6 +216,21 @@ pub async fn pre_turn(
let thread_id = input.thread_id.clone();
let agent_id = identity.agent_id.clone();
let started = std::time::Instant::now();
+ let timeout = Duration::from_millis(config.memory.recall.pre_turn_timeout_ms.max(1));
+ // Answers by the deadline less a margin, so the pack is still ranked and
+ // returned before the turn stops waiting for it.
+ let date_hint = (recall && logging && config.memory.recall.date_hint).then(|| {
+ let config = config.clone();
+ let text = input.user_text.clone();
+ let deadline = timeout.saturating_sub(Duration::from_millis(100));
+ async move {
+ let zone = config.time_zone();
+ tokio::time::timeout(deadline, super::date_hint::extract(&config, &text, &zone))
+ .await
+ .ok()
+ .flatten()
+ }
+ });
let task = tokio::spawn(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.
@@ -225,10 +240,10 @@ pub async fn pre_turn(
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);
- let context = if resumed {
- memory.pre_turn_resumed(pre).await
- } else {
- memory.pre_turn(pre).await
+ 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) => {
@@ -280,7 +295,6 @@ pub async fn pre_turn(
TurnPack::refused(&error, engine_id)
})
});
- let timeout = Duration::from_millis(config.memory.recall.pre_turn_timeout_ms.max(1));
let pack = match tokio::time::timeout(timeout, task).await {
Ok(Ok(pack)) => pack,
Ok(Err(error)) => {
diff --git a/crates/openhuman-core/src/memory/lifecycle/mod.rs b/crates/openhuman-core/src/memory/lifecycle/mod.rs
index b2ca9f1d3d..9caee01fe3 100644
--- a/crates/openhuman-core/src/memory/lifecycle/mod.rs
+++ b/crates/openhuman-core/src/memory/lifecycle/mod.rs
@@ -15,6 +15,7 @@
//! Every hook is bounded by a timeout and never fails a turn: an engine
//! outage degrades memory, it does not block the agent.
+pub mod date_hint;
pub mod hooks;
pub mod jobs;
pub mod views;
diff --git a/crates/openhuman-core/src/memory/schemas/defs.rs b/crates/openhuman-core/src/memory/schemas/defs.rs
index d5f7561e9e..405dfc15bb 100644
--- a/crates/openhuman-core/src/memory/schemas/defs.rs
+++ b/crates/openhuman-core/src/memory/schemas/defs.rs
@@ -202,7 +202,7 @@ pub fn schema(function: &str) -> ControllerSchema {
function: "policy_get",
description: "The memory lifecycle's policy: turn logging, the per-turn pack and its budgets, and the root and agent id work outside an agent resolves to.",
inputs: vec![],
- outputs: out("{log_conversations, recall: {enabled, budget_tokens, learnings_limit, brain_limit, history_limit, team_limit, build_beliefs_every, pre_turn_timeout_ms, compaction_timeout_ms, build_delay_secs}, root, agent_id, host_bound}"),
+ outputs: out("{log_conversations, recall: {enabled, budget_tokens, learnings_limit, brain_limit, history_limit, team_limit, build_beliefs_every, pre_turn_timeout_ms, date_hint, compaction_timeout_ms, build_delay_secs}, root, agent_id, host_bound}"),
},
"policy_set" => ControllerSchema {
namespace: "memory",