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:
1 parent
77bfa72689
commit
a4722b7379
4 files changed
+433
-238
No files matched your search
+87
-238
@@ -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, §ions,
|
||||
);
|
||||
|
||||
// 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", §ions);
|
||||
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>");
|
||||
}
|
||||
}
|
||||
+262
@@ -0,0 +1,262 @@
|
||||
//! 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 `<NAME>…</NAME>`; the interactive `DIALOG` region wraps the
|
||||
//! real role messages (history + new turn) so the engine keeps its turn structure.
|
||||
//! 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, Session, StoredMessage};
|
||||
|
||||
/// 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],
|
||||
) -> Vec<ChatMessage> {
|
||||
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 (name + personal folder) and the speaker
|
||||
// convention are injected into the SYSTEM_PROMPT template via placeholders.
|
||||
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();
|
||||
// Static context sections live in the store (editable without recompiling);
|
||||
// each is emitted as a system message wrapped in its own <NAME> tag.
|
||||
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</{}>", sec.name, rendered, sec.name),
|
||||
));
|
||||
}
|
||||
// The interactive region is its own section: opener/closer markers around the
|
||||
// real role messages, which keep the engine's turn structure intact.
|
||||
messages.push(text_message(Role::System, "<DIALOG>".to_string()));
|
||||
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 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. 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.push(text_message(Role::System, "</DIALOG>".to_string()));
|
||||
messages
|
||||
}
|
||||
|
||||
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<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)
|
||||
}
|
||||
|
||||
#[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 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);
|
||||
}
|
||||
}
|
||||
@@ -6,10 +6,12 @@
|
||||
//! - [`store`]: persistent session/context store for the web GUI (SQLite behind
|
||||
//! a swappable `Store` trait).
|
||||
//! - [`render`]: safe Markdown + LaTeX → HTML for assistant messages.
|
||||
//! - [`context`]: the context compositor (named sections + DIALOG) for the prompt.
|
||||
|
||||
pub mod agent;
|
||||
pub mod api;
|
||||
pub mod config;
|
||||
pub mod context;
|
||||
pub mod engine;
|
||||
pub mod i18n;
|
||||
pub mod inkling;
|
||||
|
||||
@@ -171,6 +171,22 @@ pub struct UploadMeta {
|
||||
pub created_at: i64,
|
||||
}
|
||||
|
||||
/// One named, ordered section of the model context whose STATIC template lives
|
||||
/// in the store (editable without recompiling). Rendered wrapped in
|
||||
/// `<name>…</name>`; placeholders ({identity}, {speaker_note}, {session_prompt})
|
||||
/// are filled per request. The dynamic DIALOG region is not a stored section.
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct ContextSection {
|
||||
pub name: String,
|
||||
pub content: String,
|
||||
pub position: i64,
|
||||
}
|
||||
|
||||
/// Bootstrap templates for the static context sections (seeded once into SQLite;
|
||||
/// the DB rows are the source of truth afterwards).
|
||||
const SYSTEM_PROMPT_SECTION: &str = "{identity}{speaker_note}\n{session_prompt}";
|
||||
const TOOL_USE_SECTION: &str = "Strumenti: shell_exec(command, cwd?, timeout?) esegue un comando shell nell'ambiente host e restituisce stdout/stderr ed exit code; la cartella predefinita è la tua cartella personale. Usalo per ispezionare o modificare file e per verificare i risultati invece di inventarli. Fai riferimento alle dichiarazioni dei tool fornite per gli argomenti esatti.";
|
||||
|
||||
/// The storage interface. Synchronous; call via `spawn_blocking` from async code.
|
||||
pub trait Store: Send + Sync {
|
||||
fn create_session(
|
||||
@@ -192,6 +208,9 @@ pub trait Store: Send + Sync {
|
||||
/// The global default settings template (None until seeded).
|
||||
fn get_defaults(&self) -> Result<Option<SessionSettings>>;
|
||||
fn set_defaults(&self, settings: &SessionSettings) -> Result<()>;
|
||||
/// The static context sections, ordered (SYSTEM_PROMPT, TOOL_USE, ...).
|
||||
fn context_sections(&self) -> Result<Vec<ContextSection>>;
|
||||
fn set_context_section(&self, name: &str, content: &str, position: i64) -> Result<()>;
|
||||
fn save_upload(&self, meta: &UploadMeta) -> Result<()>;
|
||||
fn get_upload(&self, id: &str) -> Result<Option<UploadMeta>>;
|
||||
}
|
||||
@@ -252,6 +271,11 @@ CREATE TABLE IF NOT EXISTS uploads (
|
||||
size INTEGER NOT NULL DEFAULT 0,
|
||||
created_at INTEGER NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS context_sections (
|
||||
name TEXT PRIMARY KEY,
|
||||
content TEXT NOT NULL,
|
||||
position INTEGER NOT NULL
|
||||
);
|
||||
";
|
||||
|
||||
/// SQLite-backed store (bundled SQLite, compiled into the binary). WAL mode for
|
||||
@@ -284,6 +308,7 @@ impl SqliteStore {
|
||||
conn.pragma_update(None, "foreign_keys", "ON")?;
|
||||
conn.execute_batch(SCHEMA)?;
|
||||
migrate(&conn)?;
|
||||
seed_context_sections(&conn)?;
|
||||
Ok(Self {
|
||||
conn: Mutex::new(conn),
|
||||
})
|
||||
@@ -329,6 +354,20 @@ fn migrate(conn: &Connection) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Seed the static context sections once (idempotent); afterwards the stored
|
||||
/// rows are authoritative and editable.
|
||||
fn seed_context_sections(conn: &Connection) -> Result<()> {
|
||||
conn.execute(
|
||||
"INSERT OR IGNORE INTO context_sections (name, content, position) VALUES ('SYSTEM_PROMPT', ?1, 0)",
|
||||
params![SYSTEM_PROMPT_SECTION],
|
||||
)?;
|
||||
conn.execute(
|
||||
"INSERT OR IGNORE INTO context_sections (name, content, position) VALUES ('TOOL_USE', ?1, 1)",
|
||||
params![TOOL_USE_SECTION],
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn row_to_session(row: &rusqlite::Row<'_>) -> rusqlite::Result<Session> {
|
||||
let settings_json: Option<String> = row.get("settings_json")?;
|
||||
let settings = match settings_json {
|
||||
@@ -586,6 +625,30 @@ impl Store for SqliteStore {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn context_sections(&self) -> Result<Vec<ContextSection>> {
|
||||
let conn = self.lock();
|
||||
let mut stmt = conn.prepare(
|
||||
"SELECT name, content, position FROM context_sections ORDER BY position ASC, name ASC",
|
||||
)?;
|
||||
let rows = stmt.query_map([], |r| {
|
||||
Ok(ContextSection {
|
||||
name: r.get(0)?,
|
||||
content: r.get(1)?,
|
||||
position: r.get(2)?,
|
||||
})
|
||||
})?;
|
||||
Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?)
|
||||
}
|
||||
|
||||
fn set_context_section(&self, name: &str, content: &str, position: i64) -> Result<()> {
|
||||
let conn = self.lock();
|
||||
conn.execute(
|
||||
"INSERT OR REPLACE INTO context_sections (name, content, position) VALUES (?1, ?2, ?3)",
|
||||
params![name, content, position],
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn save_upload(&self, meta: &UploadMeta) -> Result<()> {
|
||||
let conn = self.lock();
|
||||
conn.execute(
|
||||
@@ -770,6 +833,25 @@ mod tests {
|
||||
assert!(s.get_session(&sess.id).unwrap().unwrap().name_locked);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn context_sections_seeded_editable_and_extensible() {
|
||||
let s = store();
|
||||
let secs = s.context_sections().unwrap();
|
||||
assert_eq!(secs.len(), 2);
|
||||
assert_eq!(secs[0].name, "SYSTEM_PROMPT");
|
||||
assert_eq!(secs[1].name, "TOOL_USE");
|
||||
// Edits persist and reorder by position; new sections can be added.
|
||||
s.set_context_section("SYSTEM_PROMPT", "custom {identity}", 5)
|
||||
.unwrap();
|
||||
s.set_context_section("EXTRA", "x", 2).unwrap();
|
||||
let secs = s.context_sections().unwrap();
|
||||
assert_eq!(secs.len(), 3);
|
||||
assert_eq!(secs[0].name, "TOOL_USE"); // position 1
|
||||
assert_eq!(secs[1].name, "EXTRA"); // position 2
|
||||
assert_eq!(secs[2].name, "SYSTEM_PROMPT"); // position 5
|
||||
assert_eq!(secs[2].content, "custom {identity}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn defaults_roundtrip_and_overlay() {
|
||||
let s = store();
|
||||
|
||||
Reference in new issue
Block a user