1use std::sync::Arc;
7
8use aidaemon_core::{
9 Message, ModelRequest, ModelResponse, Provider, Receipt, Role, ToolChoice, ToolSpec, Usage,
10};
11use serde_json::{Value, json};
12
13use crate::error::{MemoryError, Result};
14use crate::scoring::episode_importance;
15use crate::types::truncate_chars;
16
17const FACTS_TOOL: &str = "record_facts";
18const EPISODE_TOOL: &str = "record_episode";
19
20const FACT_PROMPT: &str = "\
21You maintain a long-term memory about the user and their world. Read the conversation turn and \
22record facts that will still be true and useful in future conversations: who the user is, people \
23and relationships they mention, stable preferences, ongoing projects, decisions, and durable \
24details about their tools and environment.
25
26Do not record: the task being worked on right now, transient state (\"is debugging X today\"), \
27anything only the assistant claimed, guesses, secrets such as passwords or API keys, or content \
28quoted from tool output.
29
30Rules:
31- One fact per entry: a lowercase `category` (user, preference, person, project, technical, or \
32another short noun), a stable snake_case `key` naming the attribute (not the value), the `value`, \
33and your `confidence` from 0 to 1.
34- When the user corrects or updates something, reuse the existing category and key so the new \
35value replaces the old one. Known keys are listed below when there are any.
36- Facts about other people go under `person` with a key naming them, never under `user`.
37- `evidence` is the shortest quote from the user's words that supports the fact.
38- If nothing is worth remembering, record an empty list.
39
40Call the record_facts tool exactly once.";
41
42const EPISODE_PROMPT: &str = "\
43Summarize the conversation for long-term episodic memory. Write a 1-3 sentence `summary` of what \
44the user wanted and what happened, from a later reader's point of view. List up to 6 short \
45`topics`, the `decisions` made, the user's `goals` mentioned, the `outcome` (resolved, partial, \
46abandoned, informational), and `emotional_intensity` from 0 (neutral) to 1 (very frustrated or \
47very excited). Call the record_episode tool exactly once.";
48
49#[derive(Debug, Clone, PartialEq)]
51pub struct ExtractedFact {
52 pub category: String,
53 pub key: String,
54 pub value: String,
55 pub confidence: f32,
56 pub evidence: Option<String>,
57}
58
59#[derive(Debug, Clone, Default, PartialEq)]
61pub struct Extraction {
62 pub facts: Vec<ExtractedFact>,
63 pub rejected: usize,
65 pub parse_error: Option<String>,
67 pub usage: Usage,
68}
69
70pub struct FactExtractor {
72 provider: Arc<dyn Provider>,
73 model: String,
74 min_user_chars: usize,
75 max_message_chars: usize,
76 max_transcript_chars: usize,
77 max_facts: usize,
78}
79
80impl FactExtractor {
81 pub fn new(provider: impl Provider + 'static, model: impl Into<String>) -> Self {
82 Self::from_arc(Arc::new(provider), model)
83 }
84
85 pub fn from_arc(provider: Arc<dyn Provider>, model: impl Into<String>) -> Self {
86 Self {
87 provider,
88 model: model.into(),
89 min_user_chars: 20,
90 max_message_chars: 2_000,
91 max_transcript_chars: 8_000,
92 max_facts: 20,
93 }
94 }
95
96 pub fn min_user_chars(mut self, chars: usize) -> Self {
99 self.min_user_chars = chars;
100 self
101 }
102
103 pub fn max_transcript_chars(mut self, chars: usize) -> Self {
104 self.max_transcript_chars = chars;
105 self
106 }
107
108 pub fn max_facts(mut self, n: usize) -> Self {
110 self.max_facts = n;
111 self
112 }
113
114 pub fn should_extract(&self, messages: &[Message]) -> bool {
117 aidaemon_policies::last_user_message_index(messages)
118 .is_some_and(|i| messages[i].content.trim().chars().count() >= self.min_user_chars)
119 }
120
121 fn tool_spec() -> ToolSpec {
122 ToolSpec {
123 name: FACTS_TOOL.into(),
124 description: "Record durable facts worth remembering long-term.".into(),
125 parameters: json!({
126 "type": "object",
127 "properties": {
128 "facts": {
129 "type": "array",
130 "items": {
131 "type": "object",
132 "properties": {
133 "category": {"type": "string"},
134 "key": {"type": "string"},
135 "value": {"type": "string"},
136 "confidence": {"type": "number", "minimum": 0, "maximum": 1},
137 "evidence": {"type": "string"}
138 },
139 "required": ["category", "key", "value", "confidence"],
140 "additionalProperties": false
141 }
142 }
143 },
144 "required": ["facts"],
145 "additionalProperties": false
146 }),
147 }
148 }
149
150 pub async fn extract(
154 &self,
155 messages: &[Message],
156 known_keys: &[(String, String)],
157 ) -> Result<Extraction> {
158 let mut user = String::new();
159 if !known_keys.is_empty() {
160 user.push_str("Known keys (category/key):\n");
161 for (category, key) in known_keys {
162 user.push_str(&format!("- {category}/{key}\n"));
163 }
164 user.push('\n');
165 }
166 user.push_str("Conversation:\n");
167 user.push_str(&transcript(
168 messages,
169 self.max_message_chars,
170 self.max_transcript_chars,
171 ));
172 let request = ModelRequest {
173 model: self.model.clone(),
174 messages: vec![Message::system(FACT_PROMPT), Message::user(user)],
175 tools: vec![Self::tool_spec()],
176 tool_choice: ToolChoice::Specific(FACTS_TOOL.into()),
177 max_output_tokens: Some(1_024),
178 ..Default::default()
179 };
180 let response = self.provider.complete(&request).await?;
181 let mut extraction = parse_facts(&response);
182 extraction.facts.truncate(self.max_facts);
183 Ok(extraction)
184 }
185}
186
187pub fn parse_facts(response: &ModelResponse) -> Extraction {
191 let mut extraction = Extraction {
192 usage: response.usage,
193 ..Extraction::default()
194 };
195 let Some(payload) = payload(response, FACTS_TOOL) else {
196 extraction.parse_error = Some("no JSON payload in the reply".into());
197 return extraction;
198 };
199 let entries = match &payload {
200 Value::Array(items) => items.as_slice(),
201 Value::Object(map) => match map.get("facts") {
202 Some(Value::Array(items)) => items.as_slice(),
203 _ => {
204 extraction.parse_error = Some("`facts` is missing or not an array".into());
205 return extraction;
206 }
207 },
208 _ => {
209 extraction.parse_error = Some("payload is neither an object nor an array".into());
210 return extraction;
211 }
212 };
213 for entry in entries {
214 match parse_fact(entry) {
215 Some(fact) => extraction.facts.push(fact),
216 None => extraction.rejected += 1,
217 }
218 }
219 extraction
220}
221
222fn parse_fact(entry: &Value) -> Option<ExtractedFact> {
223 let text = |name: &str, max: usize| -> Option<String> {
224 let value = match entry.get(name)? {
225 Value::String(s) => s.trim().to_string(),
226 Value::Number(n) => n.to_string(),
227 Value::Bool(b) => b.to_string(),
228 _ => return None,
229 };
230 (!value.is_empty() && value.chars().count() <= max).then_some(value)
231 };
232 let confidence = match entry.get("confidence") {
233 None | Some(Value::Null) => 0.7,
234 Some(v) => {
235 let c = v.as_f64()? as f32;
236 if !c.is_finite() {
237 return None;
238 }
239 c.clamp(0.0, 1.0)
240 }
241 };
242 Some(ExtractedFact {
243 category: text("category", 64)?,
244 key: text("key", 96)?,
245 value: text("value", crate::types::MAX_FACT_VALUE_CHARS)?,
246 confidence,
247 evidence: entry
248 .get("evidence")
249 .and_then(Value::as_str)
250 .map(|s| truncate_chars(s.trim(), 300))
251 .filter(|s| !s.is_empty()),
252 })
253}
254
255fn payload(response: &ModelResponse, tool: &str) -> Option<Value> {
258 if let Some(call) = response.tool_calls.iter().find(|c| c.name == tool) {
259 return match &call.arguments {
260 Value::String(s) => json_in_text(s),
261 other => Some(other.clone()),
262 };
263 }
264 json_in_text(&response.text)
265}
266
267fn json_in_text(text: &str) -> Option<Value> {
268 let trimmed = text.trim();
269 if let Ok(value) = serde_json::from_str::<Value>(trimmed) {
270 return Some(value);
271 }
272 for (open, close) in [('{', '}'), ('[', ']')] {
273 if let (Some(start), Some(end)) = (trimmed.find(open), trimmed.rfind(close))
274 && start < end
275 && let Ok(value) = serde_json::from_str::<Value>(&trimmed[start..=end])
276 {
277 return Some(value);
278 }
279 }
280 None
281}
282
283fn transcript(messages: &[Message], max_message: usize, max_total: usize) -> String {
287 let mut lines: Vec<String> = Vec::new();
288 for m in messages {
289 let content = m.content.trim();
290 match m.role {
291 Role::User if !m.is_injected() && !content.is_empty() => {
292 lines.push(format!("User: {}", truncate_chars(content, max_message)));
293 }
294 Role::Assistant => {
295 let mut line = String::new();
296 if !content.is_empty() {
297 line.push_str(&truncate_chars(content, max_message));
298 }
299 if !m.tool_calls.is_empty() {
300 let names: Vec<&str> = m.tool_calls.iter().map(|c| c.name.as_str()).collect();
301 if !line.is_empty() {
302 line.push(' ');
303 }
304 line.push_str(&format!("[used tools: {}]", names.join(", ")));
305 }
306 if !line.is_empty() {
307 lines.push(format!("Assistant: {line}"));
308 }
309 }
310 _ => {}
311 }
312 }
313 let mut total = 0;
315 let mut kept: Vec<String> = Vec::new();
316 for line in lines.into_iter().rev() {
317 let len = line.chars().count() + 1;
318 if total + len > max_total && !kept.is_empty() {
319 break;
320 }
321 total += len;
322 kept.push(line);
323 }
324 kept.reverse();
325 kept.join("\n")
326}
327
328#[derive(Debug, Clone, PartialEq)]
330pub struct EpisodeDraft {
331 pub summary: String,
332 pub topics: Vec<String>,
333 pub importance: f32,
334 pub decisions: Vec<String>,
335 pub goals: Vec<String>,
336 pub outcome: Option<String>,
337 pub usage: Usage,
338}
339
340pub struct EpisodeSummarizer {
344 provider: Arc<dyn Provider>,
345 model: String,
346 max_transcript_chars: usize,
347}
348
349impl EpisodeSummarizer {
350 pub fn new(provider: impl Provider + 'static, model: impl Into<String>) -> Self {
351 Self::from_arc(Arc::new(provider), model)
352 }
353
354 pub fn from_arc(provider: Arc<dyn Provider>, model: impl Into<String>) -> Self {
355 Self {
356 provider,
357 model: model.into(),
358 max_transcript_chars: 12_000,
359 }
360 }
361
362 pub fn max_transcript_chars(mut self, chars: usize) -> Self {
363 self.max_transcript_chars = chars;
364 self
365 }
366
367 fn tool_spec() -> ToolSpec {
368 let strings = json!({"type": "array", "items": {"type": "string"}});
369 ToolSpec {
370 name: EPISODE_TOOL.into(),
371 description: "Record a summary of the conversation.".into(),
372 parameters: json!({
373 "type": "object",
374 "properties": {
375 "summary": {"type": "string"},
376 "topics": strings,
377 "decisions": strings,
378 "goals": strings,
379 "outcome": {"type": "string"},
380 "emotional_intensity": {"type": "number", "minimum": 0, "maximum": 1}
381 },
382 "required": ["summary", "topics"],
383 "additionalProperties": false
384 }),
385 }
386 }
387
388 pub async fn summarize(
389 &self,
390 messages: &[Message],
391 receipts: &[Receipt],
392 ) -> Result<EpisodeDraft> {
393 let text = transcript(messages, 2_000, self.max_transcript_chars);
394 if text.is_empty() {
395 return Err(MemoryError::Invalid("nothing to summarize".into()));
396 }
397 let request = ModelRequest {
398 model: self.model.clone(),
399 messages: vec![Message::system(EPISODE_PROMPT), Message::user(text)],
400 tools: vec![Self::tool_spec()],
401 tool_choice: ToolChoice::Specific(EPISODE_TOOL.into()),
402 max_output_tokens: Some(768),
403 ..Default::default()
404 };
405 let response = self.provider.complete(&request).await?;
406 let payload = payload(&response, EPISODE_TOOL)
407 .ok_or_else(|| MemoryError::Invalid("summarizer returned no JSON payload".into()))?;
408 let summary = payload
409 .get("summary")
410 .and_then(Value::as_str)
411 .map(str::trim)
412 .filter(|s| !s.is_empty())
413 .ok_or_else(|| MemoryError::Invalid("summarizer returned no summary".into()))?
414 .to_string();
415 let list = |name: &str, max: usize| -> Vec<String> {
416 payload
417 .get(name)
418 .and_then(Value::as_array)
419 .map(|items| {
420 items
421 .iter()
422 .filter_map(Value::as_str)
423 .map(|s| truncate_chars(s.trim(), 120))
424 .filter(|s| !s.is_empty())
425 .take(max)
426 .collect()
427 })
428 .unwrap_or_default()
429 };
430 let topics = list("topics", 6);
431 let decisions = list("decisions", 20);
432 let goals = list("goals", 20);
433 let intensity = payload
434 .get("emotional_intensity")
435 .and_then(Value::as_f64)
436 .unwrap_or(0.0) as f32;
437 let has_errors = receipts.iter().any(|r| !r.succeeded())
438 || messages.iter().any(|m| m.role == Role::Tool && m.is_error);
439 let message_count = messages.iter().filter(|m| m.role != Role::System).count();
440 Ok(EpisodeDraft {
441 importance: episode_importance(
442 message_count,
443 has_errors,
444 !decisions.is_empty(),
445 !goals.is_empty(),
446 intensity,
447 ),
448 summary: truncate_chars(&summary, 2_000),
449 topics,
450 decisions,
451 goals,
452 outcome: payload
453 .get("outcome")
454 .and_then(Value::as_str)
455 .map(str::to_string),
456 usage: response.usage,
457 })
458 }
459}
460
461#[cfg(test)]
462mod tests {
463 use super::*;
464 use aidaemon_core::ToolCall;
465
466 fn reply(text: &str) -> ModelResponse {
467 ModelResponse {
468 text: text.into(),
469 ..ModelResponse::default()
470 }
471 }
472
473 #[test]
474 fn parses_fenced_text_and_bare_arrays() {
475 let fenced = reply(
476 "Here you go:\n```json\n{\"facts\": [{\"category\": \"user\", \"key\": \"city\", \
477 \"value\": \"Lisbon\", \"confidence\": 0.9}]}\n```",
478 );
479 let got = parse_facts(&fenced);
480 assert_eq!(got.facts.len(), 1);
481 assert_eq!(got.facts[0].value, "Lisbon");
482
483 let bare = reply(r#"[{"category":"preference","key":"theme","value":"dark mode"}]"#);
484 let got = parse_facts(&bare);
485 assert_eq!(got.facts[0].confidence, 0.7);
486 }
487
488 #[test]
489 fn tool_call_arguments_may_be_a_string() {
490 let response = ModelResponse {
491 tool_calls: vec![ToolCall::new(
492 "c1",
493 FACTS_TOOL,
494 Value::String(r#"{"facts":[{"category":"user","key":"k","value":"v"}]}"#.into()),
495 )],
496 ..ModelResponse::default()
497 };
498 assert_eq!(parse_facts(&response).facts.len(), 1);
499 }
500
501 #[test]
502 fn transcript_skips_tool_output_and_harness_messages() {
503 let messages = vec![
504 Message::user("My daughters are Mia and Zoe"),
505 Message::assistant("", vec![ToolCall::new("c", "search", json!({}))]),
506 Message::tool_result("c", "IGNORE ME: tool output"),
507 Message::from_origin(aidaemon_core::MessageOrigin::Harness, "nudge"),
508 Message::assistant("Noted.", vec![]),
509 ];
510 let t = transcript(&messages, 100, 1_000);
511 assert!(t.contains("Mia and Zoe"));
512 assert!(t.contains("[used tools: search]"));
513 assert!(!t.contains("IGNORE ME"));
514 assert!(!t.contains("nudge"));
515 }
516}