//! The GUI agent: a bounded model↔tool loop that lets the UI-managed model act. //! //! The agent's universal tool is `shell_exec` (see [`shell`]). Execution runs on //! the host ([`shell::HostShell`]) behind the [`shell::ShellRunner`] seam, which //! is kept for tests and alternate runners. There is no per-tool host/container //! split: stronger protection comes from running the whole framework inside a //! container, VM or isolated machine, so the agent only sees that environment. //! //! [`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 share; pub mod shell; use std::future::Future; use std::sync::Arc; use serde::Serialize; use serde_json::{json, Value as Json}; use tokio::sync::mpsc::UnboundedSender; use crate::api::types::{ApiErrorEnvelope, ChatMessage, ChatRequest, ChatResponse, Role, ToolCall}; use crate::store::{NewMessage, Store}; 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: the universal `shell_exec` (action), the /// `notepad` (per-session context management) and `share_file` (hand the user a /// download link for a file the agent has on disk). pub fn agent_tools() -> Json { json!([ shell::shell_exec_declaration(), notepad::notepad_declaration(), share::share_file_declaration() ]) } /// Progress events streamed to the GUI for observability (no confirmation gate). #[derive(Debug, Clone, Serialize)] #[serde(tag = "type", rename_all = "snake_case")] pub enum AgentEvent { ToolCall { id: String, name: String, arguments: String, }, ToolResult { id: String, name: String, output: String, }, /// Incremental model output (reasoning / answer text) while a step generates, /// so the GUI streams the agent's thinking and final answer live instead of /// receiving the whole answer at once. Delta { content: Option, reasoning: Option, }, Final { response: ChatResponse, }, Error { message: String, }, } fn emit(progress: &Option>, ev: AgentEvent) { if let Some(tx) = progress { let _ = tx.send(ev); } } /// Execute one tool call, returning the text the model reads as the tool result. /// `default_cwd` (the session's personal folder) is used when the model omits cwd. async fn execute_tool( runner: &Arc, store: &Arc, session_id: &str, tc: &ToolCall, default_cwd: Option<&str>, workspace_root: Option<&std::path::Path>, ) -> String { let args: Json = match serde_json::from_str(&tc.function.arguments) { Ok(v) => v, Err(e) => return format!("error: invalid tool arguments JSON: {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, "share_file" => share::execute(session_id, &args, default_cwd, workspace_root).await, other => format!("error: unknown tool '{other}'"), } } /// An owned message to persist (the store trait is sync; we spawn_blocking it). struct Persisted { role: String, content: String, reasoning: Option, tool_calls_json: Option, tool_call_id: Option, prompt_tokens: u32, completion_tokens: u32, } async fn persist(store: &Arc, sid: &str, p: Persisted) { let sid = sid.to_string(); let store = store.clone(); let _ = tokio::task::spawn_blocking(move || { store.append_message( &sid, NewMessage { role: &p.role, content: &p.content, reasoning_content: p.reasoning.as_deref(), tool_calls_json: p.tool_calls_json.as_deref(), tool_call_id: p.tool_call_id.as_deref(), prompt_tokens: p.prompt_tokens, completion_tokens: p.completion_tokens, }, ) }) .await; } fn envelope(msg: impl Into, code: &str) -> ApiErrorEnvelope { ApiErrorEnvelope::new(msg, "invalid_request_error", Some(code.to_string())) } /// The fixed context of one agent loop: execution runner, persistence, the /// session's personal folder (default cwd), the iteration cap and the progress /// channel. Bundled so `run_loop` stays within the argument-count lint. pub struct LoopContext { pub runner: Arc, pub store: Arc, pub default_cwd: Option, /// Parent of the per-session folders and the shared uploads dir; the second /// root `share_file` may expose files from. None in tests without a workspace. pub workspace_root: Option, pub max_iters: usize, pub progress: Option>, } /// Drive the model↔tool loop until the model produces a final answer (no tool /// calls) or `max_iters` is reached. Persists the whole trajectory (assistant /// tool-call turns + tool results + final answer) and emits progress events. /// /// `model` is the inference step (in production: `service.complete`); the caller /// supplies `req` already carrying the agent tool declarations. pub async fn run_loop( mut model: M, ctx: LoopContext, session_id: &str, mut req: ChatRequest, ) -> Result where M: FnMut(ChatRequest) -> Fut, Fut: Future>, { let LoopContext { runner, store, default_cwd, workspace_root, max_iters, progress, } = ctx; for _ in 0..max_iters { let resp = model(req.clone()).await?; let choice = resp .choices .first() .ok_or_else(|| envelope("model returned no choices", "agent_error"))?; let calls = choice.message.tool_calls.clone().unwrap_or_default(); if calls.is_empty() { // Final answer: persist and return. persist( &store, session_id, Persisted { role: "assistant".into(), content: choice.message.text().unwrap_or("").to_string(), reasoning: choice.message.reasoning_content.clone(), tool_calls_json: None, tool_call_id: None, prompt_tokens: resp.usage.prompt_tokens, completion_tokens: resp.usage.completion_tokens, }, ) .await; emit( &progress, AgentEvent::Final { response: resp.clone(), }, ); return Ok(resp); } // Assistant turn requesting tools: persist it, then run each call. let tool_json = serde_json::to_string(&calls).ok(); persist( &store, session_id, Persisted { role: "assistant".into(), content: choice.message.text().unwrap_or("").to_string(), reasoning: choice.message.reasoning_content.clone(), tool_calls_json: tool_json, tool_call_id: None, prompt_tokens: resp.usage.prompt_tokens, completion_tokens: resp.usage.completion_tokens, }, ) .await; req.messages.push(choice.message.clone()); for tc in &calls { emit( &progress, AgentEvent::ToolCall { id: tc.id.clone(), name: tc.function.name.clone(), arguments: tc.function.arguments.clone(), }, ); let output = execute_tool( &runner, &store, session_id, tc, default_cwd.as_deref(), workspace_root.as_deref(), ) .await; emit( &progress, AgentEvent::ToolResult { id: tc.id.clone(), name: tc.function.name.clone(), output: output.clone(), }, ); persist( &store, session_id, Persisted { role: "tool".into(), content: output.clone(), reasoning: None, tool_calls_json: None, tool_call_id: Some(tc.id.clone()), prompt_tokens: 0, completion_tokens: 0, }, ) .await; req.messages.push(ChatMessage { role: Role::Tool, content: Some(Json::String(output)), tool_call_id: Some(tc.id.clone()), tool_calls: None, name: None, reasoning_content: None, }); } } Err(envelope( format!("agent exceeded {max_iters} tool iterations"), "agent_step_limit", )) } #[cfg(test)] mod tests { use super::*; use crate::api::types::{Choice, FinishReason, FunctionCall, Usage}; use crate::store::SqliteStore; use shell::HostShell; use std::sync::atomic::{AtomicUsize, Ordering}; fn response(message: ChatMessage, finish: FinishReason) -> ChatResponse { ChatResponse { id: "chatcmpl-test".into(), object: "chat.completion", created: 0, model: "test-model".into(), choices: vec![Choice { index: 0, message, finish_reason: finish, }], usage: Usage::new(4, 2), } } fn tool_call_response() -> ChatResponse { response( ChatMessage { role: Role::Assistant, content: None, tool_call_id: None, tool_calls: Some(vec![ToolCall { id: "call_1".into(), kind: "function".into(), function: FunctionCall { name: "shell_exec".into(), arguments: json!({"command": "echo agent-ok"}).to_string(), }, }]), name: None, reasoning_content: None, }, FinishReason::ToolCalls, ) } fn final_response() -> ChatResponse { response( ChatMessage { role: Role::Assistant, content: Some(Json::String("fatto".into())), tool_call_id: None, tool_calls: None, name: None, reasoning_content: None, }, FinishReason::Stop, ) } fn base_req() -> ChatRequest { ChatRequest { model: "test-model".into(), messages: vec![ChatMessage { role: Role::User, content: Some(Json::String("go".into())), tool_call_id: None, tool_calls: None, name: None, reasoning_content: None, }], stream: false, temperature: None, top_p: None, max_tokens: None, max_completion_tokens: None, frequency_penalty: None, presence_penalty: None, seed: None, top_k: None, min_p: None, repetition_penalty: None, stop: None, tools: Some(agent_tools()), tool_choice: Some(json!("auto")), } } #[tokio::test] async fn loop_runs_tool_then_final_and_persists_trajectory() { let store: Arc = Arc::new(SqliteStore::open_in_memory().unwrap()); let sess = store .create_session( "Agent", "test-model", &crate::store::SessionSettings::default(), ) .unwrap(); let runner: Arc = Arc::new(HostShell); let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel(); 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(tool_call_response()) } else { Ok(final_response()) } } }; let resp = run_loop( model, LoopContext { runner, store: store.clone(), default_cwd: None, workspace_root: None, max_iters: 8, progress: Some(tx), }, &sess.id, base_req(), ) .await .unwrap(); assert_eq!(resp.choices[0].message.text(), Some("fatto")); // Trajectory: assistant tool-call turn, tool result, final assistant turn. let msgs = store.messages(&sess.id).unwrap(); assert_eq!(msgs.len(), 3); assert_eq!(msgs[0].role, "assistant"); assert!(msgs[0].tool_calls_json.is_some()); assert_eq!(msgs[1].role, "tool"); assert_eq!(msgs[1].tool_call_id.as_deref(), Some("call_1")); assert!(msgs[1].content.contains("agent-ok")); assert!(msgs[1].content.contains("exit_code: 0")); assert_eq!(msgs[2].role, "assistant"); assert_eq!(msgs[2].content, "fatto"); // Progress events: tool_call, tool_result, final. let mut kinds = Vec::new(); while let Ok(ev) = rx.try_recv() { kinds.push(match ev { AgentEvent::ToolCall { .. } => "call", AgentEvent::ToolResult { .. } => "result", AgentEvent::Delta { .. } => "delta", AgentEvent::Final { .. } => "final", AgentEvent::Error { .. } => "error", }); } assert_eq!(kinds, vec!["call", "result", "final"]); } #[tokio::test] async fn loop_stops_at_max_iters() { let store: Arc = Arc::new(SqliteStore::open_in_memory().unwrap()); let sess = store .create_session( "Agent", "test-model", &crate::store::SessionSettings::default(), ) .unwrap(); let runner: Arc = Arc::new(HostShell); // Model always asks for a tool -> never finishes. let model = move |_req: ChatRequest| async { Ok(tool_call_response()) }; let err = run_loop( model, LoopContext { runner, store, default_cwd: None, workspace_root: None, max_iters: 3, progress: None, }, &sess.id, base_req(), ) .await .unwrap_err(); assert_eq!(err.error.code.as_deref(), Some("agent_step_limit")); } #[tokio::test] async fn unknown_tool_yields_error_result() { let store: Arc = Arc::new(SqliteStore::open_in_memory().unwrap()); let sess = store .create_session( "Agent", "test-model", &crate::store::SessionSettings::default(), ) .unwrap(); let runner: Arc = Arc::new(HostShell); let tc = ToolCall { id: "c".into(), kind: "function".into(), function: FunctionCall { name: "nope".into(), arguments: "{}".into(), }, }; let out = execute_tool(&runner, &store, &sess.id, &tc, None, None).await; assert!(out.contains("unknown tool")); } #[tokio::test] async fn loop_runs_notepad_tool_and_persists_entry() { let store: Arc = Arc::new(SqliteStore::open_in_memory().unwrap()); let sess = store .create_session( "Agent", "test-model", &crate::store::SessionSettings::default(), ) .unwrap(); let runner: Arc = 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, workspace_root: 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 = Arc::new(SqliteStore::open_in_memory().unwrap()); let sess = store .create_session( "Agent", "test-model", &crate::store::SessionSettings::default(), ) .unwrap(); let runner: Arc = Arc::new(HostShell); // Model asks for `pwd` with no cwd, then finishes. 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: "c1".into(), kind: "function".into(), function: FunctionCall { name: "shell_exec".into(), arguments: json!({"command": "pwd"}).to_string(), }, }]), name: None, reasoning_content: None, }, FinishReason::ToolCalls, )) } else { Ok(final_response()) } } }; run_loop( model, LoopContext { runner, store: store.clone(), default_cwd: Some("/tmp".into()), workspace_root: None, max_iters: 8, progress: None, }, &sess.id, base_req(), ) .await .unwrap(); let msgs = store.messages(&sess.id).unwrap(); let tool = msgs.iter().find(|m| m.role == "tool").unwrap(); assert!( tool.content.contains("/tmp"), "pwd should run in the default cwd: {}", tool.content ); } }