Add context compositor: named sections from SQLite + DIALOG region

The model context is now composed by a dedicated module (src/context.rs) from named sections wrapped in <NAME>...</NAME>. Static sections (SYSTEM_PROMPT, TOOL_USE) live in a new context_sections SQLite table (seeded once, editable/extensible without recompiling); SYSTEM_PROMPT injects identity/speaker-note/session-SP via placeholders. DIALOG wraps the real role messages (history + new turn) with opener/closer markers so the engine keeps turn structure. Provenance/time helpers moved into the compositor; build_request now only assembles sampling. +tests (140 green), clippy/fmt clean; live probe confirms the model sees the sections.
This commit is contained in:
adm committed 2026-11-25 21:40:31 +01:00
1 parent 77bfa72689
commit a4722b7379
4 files changed
+433 -238

No files matched your search

+87 -238
View File
@@ -24,10 +24,13 @@ use super::types::{
use super::uploads;
use crate::agent::shell::{HostShell, ShellRunner};
use crate::agent::{self, AgentEvent};
use crate::context;
use crate::i18n::t;
use crate::name;
use crate::render;
use crate::store::{NewMessage, Session, SessionSettings, Stats, Store, StoredMessage};
use crate::store::{
ContextSection, NewMessage, Session, SessionSettings, Stats, Store, StoredMessage,
};
use tokio_stream::wrappers::UnboundedReceiverStream;
/// Run a synchronous store operation off the async runtime.
@@ -205,7 +208,7 @@ pub(crate) async fn get_messages(
// The [SPEAKER] tag is model-context metadata; if a reply echoed it,
// hide it from the GUI (and from the rendered HTML).
if m.role == "assistant" {
m.content = strip_speaker_tags(&m.content);
m.content = context::strip_speaker_tags(&m.content);
}
let content_html = (m.role == "assistant" && !m.content.is_empty())
.then(|| render::markdown_to_safe_html(&m.content));
@@ -250,139 +253,6 @@ pub(crate) async fn stats(State(st): State<AppState>) -> Result<Json<StatsRespon
}))
}
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.
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<i64> {
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)
}
/// Rebuild a stateless [`ChatRequest`] from the stored history plus the new turn.
/// Prior `reasoning_content` is deliberately NOT replayed into the prompt.
fn build_request(
@@ -392,72 +262,10 @@ fn build_request(
extra: &str,
images: &[serde_json::Value],
user_name: &str,
sections: &[ContextSection],
) -> ChatRequest {
let mut messages = Vec::new();
// Server-local timezone offset, computed once for every turn in this request.
let tz_offset = server_utc_offset_secs();
// Structural identity reminder: always present, not an editable setting. It
// tells the agent its name and personal workspace folder.
let mut identity = t("identity.name", &[("name", &sess.title)]);
if let Some(folder) = &sess.folder {
identity.push_str(&t("identity.folder", &[("folder", folder)]));
}
identity.push_str(&t("speaker.note", &[]));
messages.push(text_message(Role::System, identity));
if let Some(sp) = &sess.settings.system_prompt {
messages.push(text_message(Role::System, sp.clone()));
}
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. This annotates the prompt only —
// stored content stays clean (the GUI shows its own timestamp).
// Strip any tag the model echoed into stored content so we never stack
// a second [SPEAKER] on top of one (the duplication feedback loop).
let clean = strip_speaker_tags(&m.content);
let content = 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,
};
let mut msg = text_message(role_of(&m.role), content);
msg.tool_calls = m
.tool_calls_json
.as_deref()
.and_then(|s| serde_json::from_str(s).ok());
messages.push(msg);
}
// The user turn: typed text + attachment context (inline files / path
// reminders / image markers). Images become multipart image_url parts that
// the Vision bridge materializes; without images it stays a plain string.
let user_text = format!(
"{}{}{}",
speaker_prefix(user_name, now_unix() as i64, tz_offset),
body.content,
extra
);
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,
});
}
let user_content = format!("{}{}", body.content, extra);
let messages = context::compose(sess, history, &user_content, images, user_name, sections);
ChatRequest {
model: sess.model.clone(),
messages,
@@ -612,7 +420,13 @@ pub(crate) async fn session_chat(
.map(|n| n.trim().to_string())
.filter(|n| !n.is_empty())
.unwrap_or_else(|| "User".to_string());
let mut req = build_request(&sess, &history, &body, &extra, &images, &user_name);
let sections = match with_store(&st, |s| s.context_sections()).await {
Ok(v) => v,
Err(e) => return e.into_response(),
};
let mut req = build_request(
&sess, &history, &body, &extra, &images, &user_name, &sections,
);
// Persist the user turn (text + attachment context) before generating.
let user_content = format!("{}{}", body.content, extra);
@@ -687,7 +501,9 @@ pub(crate) async fn session_chat(
message: ChatMessage {
role: Role::Assistant,
content: (!acc.content.is_empty()).then(|| {
serde_json::Value::String(strip_speaker_tags(&acc.content))
serde_json::Value::String(context::strip_speaker_tags(
&acc.content,
))
}),
tool_call_id: None,
tool_calls: has_tools.then_some(tools),
@@ -838,7 +654,7 @@ async fn persist_assistant(store: &Arc<dyn Store>, sid: &str, a: &Accum, prompt_
.as_ref()
.map(|u| (u.prompt_tokens, u.completion_tokens))
.unwrap_or((prompt_len, 0));
let content = strip_speaker_tags(&a.content);
let content = context::strip_speaker_tags(&a.content);
let reasoning = if a.reasoning.is_empty() {
None
} else {
@@ -891,17 +707,29 @@ mod tests {
temperature: None,
top_p: None,
};
let req = build_request(&sess, &[], &body, "", &[], "Federico");
// Identity reminder first (name + folder), then the session SP, then user.
let req = build_request(&sess, &[], &body, "", &[], "Federico", &[sp_section()]);
// SYSTEM_PROMPT section wraps identity + session SP; DIALOG markers around turns.
assert!(matches!(req.messages[0].role, Role::System));
let t0 = req.messages[0].text().unwrap();
assert!(t0.starts_with("<SYSTEM_PROMPT>"));
assert!(t0.contains("Pippo") && t0.contains("/tmp/pippo"));
assert_eq!(req.messages[1].text().unwrap(), "sii breve");
let last = req.messages.last().unwrap();
assert!(matches!(last.role, Role::User));
assert!(t0.contains("sii breve"));
assert!(t0.ends_with("</SYSTEM_PROMPT>"));
assert_eq!(req.messages[1].text().unwrap(), "<DIALOG>");
let user = &req.messages[req.messages.len() - 2];
assert!(matches!(user.role, Role::User));
// The new user turn carries the human speaker tag.
assert!(last.text().unwrap().starts_with("[SPEAKER: Federico - "));
assert!(last.text().unwrap().ends_with("ciao"));
assert!(user.text().unwrap().starts_with("[SPEAKER: Federico - "));
assert!(user.text().unwrap().ends_with("ciao"));
assert_eq!(req.messages.last().unwrap().text().unwrap(), "</DIALOG>");
}
fn sp_section() -> ContextSection {
ContextSection {
name: "SYSTEM_PROMPT".into(),
content: "{identity}{speaker_note}\n{session_prompt}".into(),
position: 0,
}
}
#[test]
@@ -949,29 +777,16 @@ mod tests {
temperature: None,
top_p: None,
};
let req = build_request(&sess, &history, &body, "", &[], "User");
// messages: [identity, user(history), assistant(history), user(new)]
let u = req.messages[1].text().unwrap();
let req = build_request(&sess, &history, &body, "", &[], "User", &[sp_section()]);
// messages: [SYSTEM_PROMPT, <DIALOG>, user(hist), assistant(hist), user(new), </DIALOG>]
let u = req.messages[2].text().unwrap();
assert!(u.starts_with("[SPEAKER: User - "));
assert!(u.ends_with("domanda"));
let a = req.messages[2].text().unwrap();
let a = req.messages[3].text().unwrap();
assert!(a.starts_with("[SPEAKER: Nebula - "));
assert!(a.ends_with("risposta"));
}
#[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 build_request_does_not_stack_echoed_speaker_tag() {
let sess = Session {
@@ -1004,21 +819,55 @@ mod tests {
temperature: None,
top_p: None,
};
let req = build_request(&sess, &history, &body, "", &[], "User");
let a = req.messages[1].text().unwrap();
let req = build_request(&sess, &history, &body, "", &[], "User", &[sp_section()]);
let a = req.messages[2].text().unwrap();
assert_eq!(a.matches("[SPEAKER:").count(), 1, "exactly one tag: {a}");
assert!(a.ends_with("risposta"));
}
#[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);
fn build_request_wraps_static_sections_and_dialog() {
let sess = Session {
id: "s".into(),
title: "Nebula".into(),
model: "m".into(),
settings: SessionSettings::default(),
name_locked: true,
folder: None,
created_at: 0,
updated_at: 0,
};
let body = SessionChat {
content: "ciao".into(),
stream: false,
agent: false,
attachments: Vec::new(),
max_tokens: None,
temperature: None,
top_p: None,
};
let sections = vec![
sp_section(),
ContextSection {
name: "TOOL_USE".into(),
content: "manuale".into(),
position: 1,
},
];
let req = build_request(&sess, &[], &body, "", &[], "User", &sections);
assert!(req.messages[0]
.text()
.unwrap()
.starts_with("<SYSTEM_PROMPT>"));
assert!(req.messages[0]
.text()
.unwrap()
.ends_with("</SYSTEM_PROMPT>"));
assert_eq!(
req.messages[1].text().unwrap(),
"<TOOL_USE>\nmanuale\n</TOOL_USE>"
);
assert_eq!(req.messages[2].text().unwrap(), "<DIALOG>");
assert_eq!(req.messages.last().unwrap().text().unwrap(), "</DIALOG>");
}
}