Add context management: notepad, sliding window, cache reuse, windowed GUI

Per-session notepad: agent-curated labelled entries via the notepad tool
(set/remove/clear), injected as a pinned <NOTEPAD> section above DIALOG,
char-budgeted with a consolidate ceiling, exposed in a read-only GUI panel.

Sliding DIALOG window (src/window.rs): retains recent messages by count in
two tiers (MAIN_AREA=40 + BUFFER=10), append-only while the buffer fills so
the prompt prefix stays byte-stable for KV reuse, then stepped hysteresis
eviction snapping to user-turn boundaries (never splits a tool exchange).
window_start persisted per session; full history never deleted.

Engine prefix-cache reuse: leave DIALOG open (a moving </DIALOG> closer broke
the engine prompt_ckpt_prefix every user turn, forcing full re-prefill);
surface usage.cached_tokens as a GUI badge; fix the PerfMeter prefill gauge to
gauge over non-cached tokens; add a static sliding-window marker after the
opener so the model knows older turns are omitted.

Stats clarity: distinguish the current inference context (last_prompt_tokens,
new "Contesto attuale" card) from the cumulative lifetime token total
(relabeled "Token cumulativi ... su tutti i turni"); /api/stats carries both.

Windowed browser transcript: GET /api/sessions/{id}/messages returns only the
retained window (SQL-filtered by window_start, never loads the full history)
plus the total count, wrapped as {messages, window_start, total}; the GUI shows
a banner noting older turns are preserved server-side. Full-chat export deferred.

Settings: the session scope re-reads the persisted instance fresh from the store
(like the general scope already did), fixing a stale-cache display that looked
like the session System Prompt was not being kept.

Docs (README) refreshed; 158 tests + 3 ignored green, clippy and fmt clean.
This commit is contained in:
adm committed 2026-11-26 03:12:23 +01:00
1 parent 7c945890f4
commit 0ce84581a4
20 files changed
+1412 -118

No files matched your search

+97 -15
View File
@@ -9,6 +9,7 @@
//! [`run_loop`] is pure orchestration — generic over the "model step" — so it is
//! testable without the engine and independent of the concrete runner.
pub mod notepad;
pub mod shell;
use std::future::Future;
@@ -25,9 +26,13 @@ use shell::{ShellRequest, ShellRunner};
/// Default cap on model↔tool iterations, so a misbehaving model cannot loop forever.
pub const MAX_ITERS: usize = 24;
/// The tools offered to the agent (currently the universal `shell_exec`).
/// The tools offered to the agent: the universal `shell_exec` (action) and the
/// `notepad` (per-session context management).
pub fn agent_tools() -> Json {
json!([shell::shell_exec_declaration()])
json!([
shell::shell_exec_declaration(),
notepad::notepad_declaration()
])
}
/// Progress events streamed to the GUI for observability (no confirmation gate).
@@ -69,24 +74,29 @@ fn emit(progress: &Option<UnboundedSender<AgentEvent>>, ev: AgentEvent) {
/// `default_cwd` (the session's personal folder) is used when the model omits cwd.
async fn execute_tool(
runner: &Arc<dyn ShellRunner>,
store: &Arc<dyn Store>,
session_id: &str,
tc: &ToolCall,
default_cwd: Option<&str>,
) -> String {
if tc.function.name != "shell_exec" {
return format!("error: unknown tool '{}'", tc.function.name);
}
let args: Json = match serde_json::from_str(&tc.function.arguments) {
Ok(v) => v,
Err(e) => return format!("error: invalid tool arguments JSON: {e}"),
};
let req = match ShellRequest::from_args(&args) {
Ok(r) => r,
Err(e) => return format!("error: {e}"),
};
let cwd = req.cwd.as_deref().or(default_cwd);
match runner.run(&req.command, cwd, req.timeout).await {
Ok(out) => out.to_result_text(),
Err(e) => format!("error: {e}"),
match tc.function.name.as_str() {
"shell_exec" => {
let req = match ShellRequest::from_args(&args) {
Ok(r) => r,
Err(e) => return format!("error: {e}"),
};
let cwd = req.cwd.as_deref().or(default_cwd);
match runner.run(&req.command, cwd, req.timeout).await {
Ok(out) => out.to_result_text(),
Err(e) => format!("error: {e}"),
}
}
"notepad" => notepad::execute(store, session_id, &args).await,
other => format!("error: unknown tool '{other}'"),
}
}
@@ -219,7 +229,8 @@ where
arguments: tc.function.arguments.clone(),
},
);
let output = execute_tool(&runner, tc, default_cwd.as_deref()).await;
let output =
execute_tool(&runner, &store, session_id, tc, default_cwd.as_deref()).await;
emit(
&progress,
AgentEvent::ToolResult {
@@ -443,6 +454,14 @@ mod tests {
#[tokio::test]
async fn unknown_tool_yields_error_result() {
let store: Arc<dyn Store> = Arc::new(SqliteStore::open_in_memory().unwrap());
let sess = store
.create_session(
"Agent",
"test-model",
&crate::store::SessionSettings::default(),
)
.unwrap();
let runner: Arc<dyn ShellRunner> = Arc::new(HostShell);
let tc = ToolCall {
id: "c".into(),
@@ -452,10 +471,73 @@ mod tests {
arguments: "{}".into(),
},
};
let out = execute_tool(&runner, &tc, None).await;
let out = execute_tool(&runner, &store, &sess.id, &tc, None).await;
assert!(out.contains("unknown tool"));
}
#[tokio::test]
async fn loop_runs_notepad_tool_and_persists_entry() {
let store: Arc<dyn Store> = Arc::new(SqliteStore::open_in_memory().unwrap());
let sess = store
.create_session(
"Agent",
"test-model",
&crate::store::SessionSettings::default(),
)
.unwrap();
let runner: Arc<dyn ShellRunner> = Arc::new(HostShell);
let n = Arc::new(AtomicUsize::new(0));
let model = move |_req: ChatRequest| {
let n = n.clone();
async move {
if n.fetch_add(1, Ordering::SeqCst) == 0 {
Ok(response(
ChatMessage {
role: Role::Assistant,
content: None,
tool_call_id: None,
tool_calls: Some(vec![ToolCall {
id: "np1".into(),
kind: "function".into(),
function: FunctionCall {
name: "notepad".into(),
arguments: json!({"action":"set","key":"goal","text":"dogfood the notepad"}).to_string(),
},
}]),
name: None,
reasoning_content: None,
},
FinishReason::ToolCalls,
))
} else {
Ok(final_response())
}
}
};
run_loop(
model,
LoopContext {
runner,
store: store.clone(),
default_cwd: None,
max_iters: 8,
progress: None,
},
&sess.id,
base_req(),
)
.await
.unwrap();
// The entry is persisted per-session, and the tool result is in the trajectory.
let np = store.notepad(&sess.id).unwrap();
assert_eq!(np.len(), 1);
assert_eq!(np[0].key, "goal");
assert_eq!(np[0].text, "dogfood the notepad");
let msgs = store.messages(&sess.id).unwrap();
let tool = msgs.iter().find(|m| m.role == "tool").unwrap();
assert!(tool.content.contains("saved"), "{}", tool.content);
}
#[tokio::test]
async fn default_cwd_is_used_when_model_omits_it() {
let store: Arc<dyn Store> = Arc::new(SqliteStore::open_in_memory().unwrap());
+243
View File
@@ -0,0 +1,243 @@
//! The agent's notepad tool: a persistent, per-session set of labelled entries
//! the agent curates so important state survives the sliding context window.
//!
//! One action-based tool (`set`/`remove`/`clear`); entries are addressed by a
//! stable `key` (upsert is idempotent, no shifting numeric indices). Bounded by a
//! char budget with a soft warning and a hard ceiling that asks the agent to
//! consolidate — nothing is evicted automatically (importance, not recency).
use std::sync::Arc;
use anyhow::Result;
use serde_json::{json, Value as Json};
use crate::store::Store;
/// Per-entry char cap (unicode-aware). Over-long entries are refused, not
/// silently truncated: the agent must keep notes short.
const MAX_ENTRY_CHARS: usize = 1024;
/// Total notepad char cap (hard ceiling). Over it, a `set` is refused and the
/// agent is asked to consolidate stale entries itself.
const MAX_TOTAL_CHARS: usize = 8000;
/// Soft warning threshold: near the ceiling, nudge consolidation.
const SOFT_WARN_CHARS: usize = 6000;
/// Max key length.
const MAX_KEY_CHARS: usize = 64;
/// The OpenAI function declaration offered to the model for the agent.
pub fn notepad_declaration() -> Json {
json!({
"type": "function",
"function": {
"name": "notepad",
"description": "Manage your persistent per-session notepad, always visible above \
the dialog. Pin durable task state that must survive the sliding context window: \
goal, decisions + rationale, current state/next step, constraints, pitfalls, key \
paths/identifiers. Entries are labelled by a stable key: action=set upserts by key \
(idempotent), remove deletes one entry, clear empties all. Keep entries short. Do \
NOT store long logs/documents or single-task ephemera. The notepad is bounded: \
near the limit, consolidate stale entries yourself — nothing is evicted automatically.",
"parameters": {
"type": "object",
"properties": {
"action": {
"type": "string",
"enum": ["set", "remove", "clear"],
"description": "set creates/updates entry `key`; remove deletes `key`; clear empties the notepad."
},
"key": {
"type": "string",
"description": "Stable label addressing the entry (required for set/remove), e.g. goal, state, decision:auth, pitfall:x, ref:path."
},
"text": {
"type": "string",
"description": "Short entry content (required for set, max 1024 chars)."
}
},
"required": ["action"]
}
}
})
}
/// Execute a notepad tool call against the store, returning the text the model
/// reads as the tool result. Store work runs off the async runtime.
pub async fn execute(store: &Arc<dyn Store>, session_id: &str, args: &Json) -> String {
let action = args
.get("action")
.and_then(|v| v.as_str())
.unwrap_or("")
.to_string();
let key = args
.get("key")
.and_then(|v| v.as_str())
.unwrap_or("")
.trim()
.to_string();
let text = args
.get("text")
.and_then(|v| v.as_str())
.unwrap_or("")
.trim()
.to_string();
let store = store.clone();
let sid = session_id.to_string();
let res = tokio::task::spawn_blocking(move || -> Result<String> {
match action.as_str() {
"set" => {
if key.is_empty() {
return Ok("error: notepad set requires a non-empty 'key'".into());
}
if key.chars().count() > MAX_KEY_CHARS {
return Ok(format!("error: key too long (max {MAX_KEY_CHARS} chars)"));
}
if key.contains('\n') {
return Ok("error: key must be a single line".into());
}
if text.is_empty() {
return Ok("error: notepad set requires non-empty 'text'".into());
}
let nlen = text.chars().count();
if nlen > MAX_ENTRY_CHARS {
return Ok(format!(
"error: entry too long ({nlen} > {MAX_ENTRY_CHARS} chars); shorten it"
));
}
let entries = store.notepad(&sid)?;
let others: usize = entries
.iter()
.filter(|e| e.key != key)
.map(|e| e.text.chars().count())
.sum();
let total = others + nlen;
if total > MAX_TOTAL_CHARS {
return Ok(format!(
"error: notepad full ({total} > {MAX_TOTAL_CHARS} chars). Remove or \
consolidate stale entries (notepad remove/clear), then retry. Nothing \
is evicted automatically."
));
}
store.set_notepad_entry(&sid, &key, &text)?;
let count = store.notepad(&sid)?.len();
let mut msg = format!(
"Entry '{key}' saved. Notepad: {count} entries, {total}/{MAX_TOTAL_CHARS} chars."
);
if total >= SOFT_WARN_CHARS {
msg.push_str(" Warning: nearing the limit — consolidate stale entries.");
}
Ok(msg)
}
"remove" => {
if key.is_empty() {
return Ok("error: notepad remove requires a non-empty 'key'".into());
}
let existed = store.remove_notepad_entry(&sid, &key)?;
if existed {
Ok(format!("Entry '{key}' removed."))
} else {
Ok(format!("No entry '{key}' (nothing removed)."))
}
}
"clear" => {
store.clear_notepad(&sid)?;
Ok("Notepad cleared.".into())
}
other => Ok(format!(
"error: unknown notepad action '{other}' (use set|remove|clear)"
)),
}
})
.await;
match res {
Ok(Ok(msg)) => msg,
Ok(Err(e)) => format!("error: {e}"),
Err(e) => format!("error: notepad task failed: {e}"),
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::store::{SessionSettings, SqliteStore};
fn setup() -> (Arc<dyn Store>, String) {
let store: Arc<dyn Store> = Arc::new(SqliteStore::open_in_memory().unwrap());
let sess = store
.create_session("Chat", "m", &SessionSettings::default())
.unwrap();
(store, sess.id)
}
#[tokio::test]
async fn set_upsert_remove_clear() {
let (store, sid) = setup();
let out = execute(
&store,
&sid,
&json!({"action":"set","key":"goal","text":"ship it"}),
)
.await;
assert!(out.contains("saved"), "{out}");
// Upsert by key replaces, does not duplicate.
execute(
&store,
&sid,
&json!({"action":"set","key":"goal","text":"ship + dogfood"}),
)
.await;
let np = store.notepad(&sid).unwrap();
assert_eq!(np.len(), 1);
assert_eq!(np[0].text, "ship + dogfood");
// Remove.
let out = execute(&store, &sid, &json!({"action":"remove","key":"goal"})).await;
assert!(out.contains("removed"), "{out}");
assert!(store.notepad(&sid).unwrap().is_empty());
// Clear.
execute(&store, &sid, &json!({"action":"set","key":"a","text":"x"})).await;
let out = execute(&store, &sid, &json!({"action":"clear"})).await;
assert!(out.contains("cleared"), "{out}");
assert!(store.notepad(&sid).unwrap().is_empty());
}
#[tokio::test]
async fn validation_and_budget() {
let (store, sid) = setup();
assert!(execute(&store, &sid, &json!({"action":"set","text":"x"}))
.await
.contains("key"));
assert!(execute(&store, &sid, &json!({"action":"set","key":"k"}))
.await
.contains("text"));
assert!(execute(&store, &sid, &json!({"action":"bogus"}))
.await
.contains("unknown"));
// Over-long entry is refused (not truncated).
let long = "a".repeat(MAX_ENTRY_CHARS + 1);
assert!(
execute(&store, &sid, &json!({"action":"set","key":"k","text":long}))
.await
.contains("too long")
);
// Hard ceiling: 7 * 1024 = 7168 fits; an 8th (8192) exceeds 8000 -> refused.
let big = "b".repeat(MAX_ENTRY_CHARS);
for i in 0..7 {
execute(
&store,
&sid,
&json!({"action":"set","key":format!("k{i}"),"text":big}),
)
.await;
}
let out = execute(&store, &sid, &json!({"action":"set","key":"k7","text":big})).await;
assert!(out.contains("full"), "{out}");
assert_eq!(store.notepad(&sid).unwrap().len(), 7);
}
#[test]
fn declaration_shape() {
let d = notepad_declaration();
assert_eq!(d["type"], "function");
assert_eq!(d["function"]["name"], "notepad");
assert_eq!(d["function"]["parameters"]["required"][0], "action");
}
}