//! The context compositor: assembles the model prompt from named sections. //! //! Static sections (`SYSTEM_PROMPT`, `TOOL_USE`, …) live in the store and are //! emitted wrapped in `…`; the interactive `DIALOG` region is an open //! tail (opener ``, no moving closer) around the real role messages, so the //! engine keeps its turn structure and the prompt prefix stays stable for KV reuse. //! Per-turn `[SPEAKER]` provenance and the server-local stamp are applied here, //! prompt-only (stored content stays clean). Adding a section = adding a store row. use crate::api::types::{now_unix, ChatMessage, Role}; use crate::i18n::t; use crate::store::{ContextSection, NotepadEntry, Session, StoredMessage, TodoItem}; /// Compose the full context message list: static sections, then the DIALOG region. /// `user_content` is the new turn's typed text plus attachment context. pub fn compose( sess: &Session, history: &[StoredMessage], user_content: &str, images: &[serde_json::Value], user_name: &str, sections: &[ContextSection], notepad: &[NotepadEntry], ) -> Vec { // Server-local timezone offset, computed once for every turn in this request. let tz_offset = server_utc_offset_secs(); // The shared prefix (pinned + DIALOG + history), then the new user turn. let mut messages = prefix_messages(sess, history, user_name, sections, notepad, tz_offset); // The user turn: typed text + attachment context. Images become multipart // image_url parts that the Vision bridge materializes; else a plain string. let user_text = format!( "{}{}", speaker_prefix(user_name, now_unix() as i64, tz_offset), user_content ); if images.is_empty() { messages.push(text_message(Role::User, user_text)); } else { let mut parts = vec![serde_json::json!({"type": "text", "text": user_text})]; parts.extend(images.iter().cloned()); messages.push(ChatMessage { role: Role::User, content: Some(serde_json::Value::Array(parts)), tool_call_id: None, tool_calls: None, name: None, reasoning_content: None, }); } messages } /// The prompt prefix WITHOUT the new user turn: pinned sections + notepad + the /// open DIALOG region + the retained history (with `[SPEAKER]` stamps). This is /// exactly what [`compose`] builds before appending the user turn, so a cache /// pre-warm (`GEN 0`) over `compose_prefix` is a byte-exact token prefix of the /// real turn's prompt and the engine's `RESUME` hits. The real turn must reuse /// this same prefix (it does, via [`compose`]) — never a parallel rebuild. pub fn compose_prefix( sess: &Session, history: &[StoredMessage], user_name: &str, sections: &[ContextSection], notepad: &[NotepadEntry], ) -> Vec { prefix_messages( sess, history, user_name, sections, notepad, server_utc_offset_secs(), ) } /// The shared prefix builder: pinned prefix + the open DIALOG region + the /// retained history. `tz_offset` is the server UTC offset, passed in so [`compose`] /// stamps the history and the new user turn with one consistent offset. fn prefix_messages( sess: &Session, history: &[StoredMessage], user_name: &str, sections: &[ContextSection], notepad: &[NotepadEntry], tz_offset: i64, ) -> Vec { // Pinned prefix: static sections + notepad, always present above the window. let mut messages = pinned_messages(sess, sections, notepad); // The interactive region opens with and is left OPEN: a trailing // after the last user turn would move every turn and break the // engine's prefix checkpoint (RESUME 0). Role messages keep turn structure. messages.push(text_message(Role::System, "\n".to_string())); // Static sliding-window marker: tells the model this is a window (older turns // omitted), so it doesn't mistake the first visible turn for the chat's first // message. STATIC text (no counts) -> stable prefix, cache-safe. messages.push(text_message( Role::System, format!("{}\n\n", t("dialog.window_note", &[])), )); for m in history { // Per-turn provenance for the model: [SPEAKER: name - datetime]. The // human uses the global user name; the assistant uses the session name. // Tool/system turns stay untagged. Strip any tag the model echoed into // stored content so we never stack a second one (duplication loop). let clean = strip_speaker_tags(&m.content); let tool_calls = m .tool_calls_json .as_deref() .and_then(|s| serde_json::from_str(s).ok()); // A tool-call-only assistant turn carries no text: keep content None to // match `agent::run_loop` (which pushed the model's message verbatim). // Stamping a bare [SPEAKER] here would emit a spurious <|content_text|> // block, priming empty speaker tags and diverging from the cached prefix. let tool_only = m.role == "assistant" && clean.is_empty() && tool_calls.is_some(); let content = if tool_only { None } else { let text = match m.role.as_str() { "user" => format!( "{}{}", speaker_prefix(user_name, m.created_at, tz_offset), clean ), "assistant" => format!( "{}{}", speaker_prefix(&sess.title, m.created_at, tz_offset), clean ), _ => clean, }; Some(serde_json::Value::String(text)) }; messages.push(ChatMessage { role: role_of(&m.role), content, // Restore the tool-call id so the template resolves the tool name from // the preceding assistant turn (and the prefix matches run_loop). tool_call_id: m.tool_call_id.clone(), tool_calls, name: None, reasoning_content: None, }); } messages } /// The pinned prefix: static sections (placeholders rendered) + the notepad /// block. Always present above the sliding DIALOG window. Extracted from /// `compose` so the pinned prefix is a single reusable unit. pub fn pinned_messages( sess: &Session, sections: &[ContextSection], notepad: &[NotepadEntry], ) -> Vec { let mut messages = Vec::new(); let mut identity = t("identity.name", &[("name", &sess.title)]); if let Some(folder) = &sess.folder { identity.push_str(&t("identity.folder", &[("folder", folder)])); } let speaker_note = t("speaker.note", &[]); let session_prompt = sess.settings.system_prompt.clone().unwrap_or_default(); for sec in sections { let rendered = sec .content .replace("{identity}", &identity) .replace("{speaker_note}", &speaker_note) .replace("{session_prompt}", &session_prompt); messages.push(text_message( Role::System, format!("<{}>\n{}\n\n\n", sec.name, rendered, sec.name), )); } if !notepad.is_empty() { let body = notepad_fingerprint(notepad); messages.push(text_message( Role::System, format!("\n{body}\n\n\n"), )); } messages } /// The rendered `` body: one `key: text` line per entry (newlines in text /// normalized to spaces), in store order. This is exactly what the header injects, /// so it doubles as a fingerprint: if it is unchanged across a turn, the notepad /// header is byte-identical and the prefix cache still holds (no pre-warm needed). /// `updated_at` is deliberately excluded — it does not affect the rendered header, /// so re-setting identical text does not trigger a wasted pre-warm. pub fn notepad_fingerprint(notepad: &[NotepadEntry]) -> String { notepad .iter() .map(|e| format!("{}: {}", e.key, e.text.replace('\n', " "))) .collect::>() .join("\n") } /// The rendered `` body: one `seq [status] content` line per OPEN item /// (pending/doing), in store order (seq). Done items stay in the Store for /// history/GUI but never enter the prompt. Like the notepad fingerprint this is /// exactly the injected header body, so it doubles as the pre-warm-on-change /// trigger; `updated_at` is excluded (an identical re-set is not a change). pub fn todo_fingerprint(todos: &[TodoItem]) -> String { todos .iter() .filter(|i| i.status != "done") .map(|i| format!("{} [{}] {}", i.seq, i.status, i.content.replace('\n', " "))) .collect::>() .join("\n") } /// The dynamic `` pinned section, built from the session's open tasks /// (None when there are none). Appended to the static sections like the MCP /// surface, so the real turn and the cache pre-warm share a byte-identical /// prefix with no extra compositor parameter. pub fn todo_section(todos: &[TodoItem]) -> Option { let body = todo_fingerprint(todos); if body.is_empty() { return None; } Some(ContextSection { name: "TODO".into(), content: body, position: 3, }) } fn role_of(s: &str) -> Role { match s { "system" | "developer" => Role::System, "assistant" => Role::Assistant, "tool" => Role::Tool, _ => Role::User, } } fn text_message(role: Role, text: String) -> ChatMessage { ChatMessage { role, content: Some(serde_json::Value::String(text)), tool_call_id: None, tool_calls: None, name: None, reasoning_content: None, } } /// The `[SPEAKER: name - datetime]` line prefixed to a turn's content in the /// model prompt (provenance), followed by a newline. `offset` is the server's /// UTC offset in seconds, so the stamp is in the server's local timezone. fn speaker_prefix(name: &str, secs: i64, offset: i64) -> String { format!( "{}\n", t( "speaker.tag", &[("name", name), ("when", &format_stamp(secs, offset))] ) ) } /// Remove leading `[SPEAKER: name - YYYY-MM-DD HH:MM]` tag(s) a model may have /// echoed into its own reply. The tag is framework metadata for the prompt, not /// reply text: stripping keeps stored/displayed content clean and breaks the /// history feedback loop that would otherwise stack a second tag each turn. pub fn strip_speaker_tags(content: &str) -> String { let mut rest = content; let mut stripped = false; loop { let t = rest.trim_start(); if !t.starts_with("[SPEAKER:") { break; } let Some(end) = t.find(']') else { break }; let inner = &t[..end]; let Some(dash) = inner.rfind(" - ") else { break; }; if !looks_like_stamp(&inner[dash + 3..]) { break; } rest = &t[end + 1..]; stripped = true; } if stripped { rest.trim_start().to_string() } else { content.to_string() } } /// Whether `s` is exactly `YYYY-MM-DD HH:MM` (the speaker tag's stamp shape). fn looks_like_stamp(s: &str) -> bool { let b = s.as_bytes(); if b.len() != 16 { return false; } b.iter().enumerate().all(|(i, c)| match i { 4 | 7 => *c == b'-', 10 => *c == b' ', 13 => *c == b':', _ => c.is_ascii_digit(), }) } /// Format unix seconds as `YYYY-MM-DD HH:MM` in the server's local timezone /// (`offset` seconds east of UTC). Dependency-free civil-date arithmetic. fn format_stamp(secs: i64, offset: i64) -> String { let local = secs + offset; let days = local.div_euclid(86400); let tod = local.rem_euclid(86400); let (y, m, d) = civil_from_days(days); format!( "{y:04}-{m:02}-{d:02} {:02}:{:02}", tod / 3600, (tod % 3600) / 60 ) } /// The server's current UTC offset in seconds, from the OS `date +%z` (reads the /// system timezone incl. DST). One cheap call per request build; 0 (UTC) on fail. fn server_utc_offset_secs() -> i64 { std::process::Command::new("date") .arg("+%z") .output() .ok() .and_then(|o| String::from_utf8(o.stdout).ok()) .and_then(|s| parse_utc_offset(s.trim())) .unwrap_or(0) } /// Parse `date +%z` output ("+0100", "-0500") into seconds east of UTC. fn parse_utc_offset(s: &str) -> Option { let b = s.as_bytes(); if b.len() != 5 { return None; } let sign = match b[0] { b'+' => 1, b'-' => -1, _ => return None, }; let hh: i64 = s.get(1..3)?.parse().ok()?; let mm: i64 = s.get(3..5)?.parse().ok()?; Some(sign * (hh * 3600 + mm * 60)) } /// Days since 1970-01-01 -> (year, month, day). Howard Hinnant's algorithm. fn civil_from_days(z: i64) -> (i64, u32, u32) { let z = z + 719468; let era = if z >= 0 { z } else { z - 146096 } / 146097; let doe = z - era * 146097; let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365; let y = yoe + era * 400; let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); let mp = (5 * doy + 2) / 153; let d = doy - (153 * mp + 2) / 5 + 1; let m = if mp < 10 { mp + 3 } else { mp - 9 }; (if m <= 2 { y + 1 } else { y }, m as u32, d as u32) } #[cfg(test)] mod tests { use super::*; #[test] fn strip_speaker_tags_removes_echoed_prefixes() { let tag = "[SPEAKER: prato-rapido - 2026-11-25 21:09]"; assert_eq!(strip_speaker_tags(&format!("{tag} {tag} Certo.")), "Certo."); assert_eq!(strip_speaker_tags(&format!("{tag}\nCerto.")), "Certo."); assert_eq!(strip_speaker_tags("Certo."), "Certo."); assert_eq!(strip_speaker_tags("[nota] testo"), "[nota] testo"); assert_eq!( strip_speaker_tags("[SPEAKER: x - not-a-date] testo"), "[SPEAKER: x - not-a-date] testo" ); } #[test] fn history_restores_tool_call_id_and_skips_speaker_on_tool_only_turns() { let sess = Session { id: "s".into(), title: "Nebula".into(), model: "m".into(), settings: crate::store::SessionSettings::default(), name_locked: true, folder: None, created_at: 0, updated_at: 0, }; let calls = serde_json::json!([{ "id": "call_1", "type": "function", "function": {"name": "shell_exec", "arguments": "{\"command\":\"ls\"}"} }]); let history = vec![ StoredMessage { id: 1, role: "user".into(), content: "lista i file".into(), reasoning_content: None, tool_calls_json: None, tool_call_id: None, prompt_tokens: 0, completion_tokens: 0, created_at: 1_700_000_000, }, StoredMessage { id: 2, role: "assistant".into(), content: "".into(), reasoning_content: Some("penso".into()), tool_calls_json: Some(calls.to_string()), tool_call_id: None, prompt_tokens: 0, completion_tokens: 0, created_at: 1_700_000_001, }, StoredMessage { id: 3, role: "tool".into(), content: "file.txt".into(), reasoning_content: None, tool_calls_json: None, tool_call_id: Some("call_1".into()), prompt_tokens: 0, completion_tokens: 0, created_at: 1_700_000_002, }, ]; let prefix = compose_prefix(&sess, &history, "Federico", &[], &[]); // BUG-05: the tool-only assistant turn has no text (no bare [SPEAKER] block). let asst = prefix .iter() .find(|m| matches!(m.role, Role::Assistant)) .unwrap(); assert!( asst.content.is_none(), "tool-only turn must not carry a [SPEAKER] text block" ); assert!(asst.tool_calls.is_some()); // BUG-04: the tool result keeps its id so the template resolves the name. let tool = prefix .iter() .find(|m| matches!(m.role, Role::Tool)) .unwrap(); assert_eq!(tool.tool_call_id.as_deref(), Some("call_1")); } #[test] fn format_stamp_known_dates_and_offset() { assert_eq!(format_stamp(0, 0), "1970-01-01 00:00"); assert_eq!(format_stamp(1_000_000_000, 0), "2001-09-09 01:46"); assert_eq!(format_stamp(951_782_400, 0), "2000-02-29 00:00"); // leap day assert_eq!(format_stamp(0, 3600), "1970-01-01 01:00"); // +1h server offset assert_eq!(parse_utc_offset("+0100"), Some(3600)); assert_eq!(parse_utc_offset("-0500"), Some(-18000)); assert_eq!(parse_utc_offset("+0000"), Some(0)); assert_eq!(parse_utc_offset("nope"), None); } #[test] fn compose_places_notepad_above_dialog() { let sess = Session { id: "s".into(), title: "Nebula".into(), model: "m".into(), settings: crate::store::SessionSettings::default(), name_locked: true, folder: None, created_at: 0, updated_at: 0, }; let sections = vec![ContextSection { name: "TOOL_USE".into(), content: "manuale".into(), position: 1, }]; let notepad = vec![ NotepadEntry { key: "goal".into(), text: "ship it".into(), updated_at: 0, }, NotepadEntry { key: "state".into(), text: "coding\nnow".into(), updated_at: 0, }, ]; let texts = |msgs: Vec| -> Vec { msgs.iter() .map(|m| { m.content .as_ref() .and_then(|c| c.as_str()) .unwrap_or("") .to_string() }) .collect() }; let t = texts(compose( &sess, &[], "ciao", &[], "Federico", §ions, ¬epad, )); let tool = t.iter().position(|x| x.starts_with("")).unwrap(); let np = t.iter().position(|x| x.starts_with("")).unwrap(); let dlg = t.iter().position(|x| x == "\n").unwrap(); assert!( tool < np && np < dlg, "notepad must sit between TOOL_USE and DIALOG" ); assert!(t[np].contains("goal: ship it")); assert!(t[np].contains("state: coding now")); // newline normalized to one line assert!(t[np].ends_with("\n\n")); // Empty notepad emits no section. let t2 = texts(compose(&sess, &[], "ciao", &[], "Federico", §ions, &[])); assert!(!t2.iter().any(|x| x.starts_with(""))); } #[test] fn dialog_window_marker_is_static() { let sess = Session { id: "s".into(), title: "Nebula".into(), model: "m".into(), settings: crate::store::SessionSettings::default(), name_locked: true, folder: None, created_at: 0, updated_at: 0, }; let sections = vec![ContextSection { name: "TOOL_USE".into(), content: "manuale".into(), position: 1, }]; let a = compose(&sess, &[], "ciao", &[], "Federico", §ions, &[]); let b = compose(&sess, &[], "altro turno", &[], "Federico", §ions, &[]); let da = a .iter() .position(|m| m.text().unwrap_or("") == "\n") .unwrap(); let db = b .iter() .position(|m| m.text().unwrap_or("") == "\n") .unwrap(); // A static system marker sits right after the opener, identical across turns. assert!(matches!(a[da + 1].role, Role::System)); assert!(a[da + 1].text().unwrap().ends_with("\n\n")); assert_eq!(a[da + 1].text().unwrap(), b[db + 1].text().unwrap()); } #[test] fn compose_prefix_is_exact_prefix_of_compose() { let sess = Session { id: "s".into(), title: "Nebula".into(), model: "m".into(), settings: crate::store::SessionSettings::default(), name_locked: true, folder: None, created_at: 0, updated_at: 0, }; let sections = vec![ContextSection { name: "TOOL_USE".into(), content: "manuale".into(), position: 1, }]; let notepad = vec![NotepadEntry { key: "goal".into(), text: "ship it".into(), updated_at: 0, }]; let history = vec![ StoredMessage { id: 1, role: "user".into(), content: "ciao".into(), reasoning_content: None, tool_calls_json: None, tool_call_id: None, prompt_tokens: 0, completion_tokens: 0, created_at: 1_700_000_000, }, StoredMessage { id: 2, role: "assistant".into(), content: "ciao a te".into(), reasoning_content: None, tool_calls_json: None, tool_call_id: None, prompt_tokens: 0, completion_tokens: 0, created_at: 1_700_000_001, }, ]; let prefix = compose_prefix(&sess, &history, "Federico", §ions, ¬epad); let full = compose( &sess, &history, "nuovo turno", &[], "Federico", §ions, ¬epad, ); // compose == prefix + exactly one new user turn: the pre-warm prefix is a // byte-exact prefix of the real turn (ChatMessage has no PartialEq, so // compare the serialized form, which is what the template renders). assert_eq!(full.len(), prefix.len() + 1); let pj: Vec = prefix .iter() .map(|m| serde_json::to_value(m).unwrap()) .collect(); let fj: Vec = full[..prefix.len()] .iter() .map(|m| serde_json::to_value(m).unwrap()) .collect(); assert_eq!(pj, fj, "pre-warm prefix must equal the real turn's prefix"); assert!(matches!(full.last().unwrap().role, Role::User)); assert!(full .last() .unwrap() .text() .unwrap() .ends_with("nuovo turno")); } #[test] fn notepad_fingerprint_tracks_header_not_updated_at() { let a = vec![NotepadEntry { key: "goal".into(), text: "ship it".into(), updated_at: 1, }]; let b = vec![NotepadEntry { key: "goal".into(), text: "ship it".into(), updated_at: 999, }]; // updated_at differs but the rendered header is identical -> same fingerprint // (re-setting identical text must not trigger a wasted pre-warm). assert_eq!(notepad_fingerprint(&a), notepad_fingerprint(&b)); let c = vec![NotepadEntry { key: "goal".into(), text: "ship it now".into(), updated_at: 1, }]; assert_ne!(notepad_fingerprint(&a), notepad_fingerprint(&c)); // newline normalization matches the header body exactly. let d = vec![NotepadEntry { key: "state".into(), text: "coding\nnow".into(), updated_at: 0, }]; assert_eq!(notepad_fingerprint(&d), "state: coding now"); assert_eq!(notepad_fingerprint(&[]), ""); } #[test] fn todo_section_renders_open_items_only_and_fingerprint_ignores_done() { let item = |seq: i64, status: &str, content: &str, updated_at: i64| TodoItem { seq, content: content.into(), status: status.into(), created_at: 0, updated_at, }; let todos = vec![ item(1, "doing", "wire the tool", 1), item(2, "done", "design the schema", 5), item(3, "pending", "write\ntests", 1), ]; let sec = todo_section(&todos).unwrap(); assert_eq!(sec.name, "TODO"); assert_eq!( sec.content, "1 [doing] wire the tool\n3 [pending] write tests" ); // updated_at does not affect the rendered body (no wasted pre-warm). let bumped = vec![ item(1, "doing", "wire the tool", 999), item(3, "pending", "write\ntests", 999), ]; assert_eq!(todo_fingerprint(&todos), todo_fingerprint(&bumped)); // A status change IS a change. let moved = vec![ item(1, "done", "wire the tool", 1), item(3, "pending", "write\ntests", 1), ]; assert_ne!(todo_fingerprint(&todos), todo_fingerprint(&moved)); // All done (or empty) -> no section at all. assert!(todo_section(&[item(2, "done", "x", 0)]).is_none()); assert!(todo_section(&[]).is_none()); } }