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());