diff --git a/README.md b/README.md index 48ab71c..e37fa83 100644 --- a/README.md +++ b/README.md @@ -110,6 +110,27 @@ indexes) or complemented by another DBMS for advanced analytics later, without touching the API or the GUI. This is the foundation for multi-session, statistics and advanced settings to grow on top. +## Agent mode + +The GUI model can **act**, not just chat. Toggle the 🤖 button and the model runs as +an agent with a single universal tool, **`shell_exec`** (a shell is universal: file +ops, programs, system inspection, web via curl, git, …). A bounded server-side loop +drives `model → shell_exec → result → model → … → final answer`, persisting the whole +trajectory and streaming progress events (`tool_call` / `tool_result` / `final`) so +the GUI shows every command and its output inline — **observability without a +confirmation gate**. + +Two operating modes are planned, separated by the *environment* rather than per-call +approval: + +- **Base / host mode** (implemented): `shell_exec` runs directly on the host via + `bash -lc` (with `cwd`, a timeout and an output cap). This is a trusted machine; + the agent has the same freedom you would give a local operator. +- **Isolated mode** (planned): the same tool routes to a sandboxed runner — the + team's Docker-container MCP server. The user supplies the container; provisioning + is on them. Execution sits behind a `ShellRunner` trait, so the isolated runner + plugs in without touching the agent loop. + ## Architecture ``` @@ -159,17 +180,19 @@ unknown keys never break startup. ## Status -Working and tested (94 tests, plus 2 real-file tests run on demand). Text, images, -the full client-side tool loop, the Anthropic endpoint and the web GUI (session -context, streaming, stats) have been validated live against the real Inkling engine. +Working and tested (106 tests, plus 2 real-file tests run on demand). Text, images, +the full client-side tool loop, the Anthropic endpoint, the web GUI (session +context, streaming, stats) and **agent mode** (the model using `shell_exec` on the +host) have been validated live against the real Inkling engine. Not yet implemented (honest gaps): forced `tool_choice` (`required` / named function returns a clear 400), multi-slot batching, logprobs / structured output, automatic engine restart after a crash, a full SSRF guard against DNS rebinding, and the OpenAI Responses native endpoint. The Anthropic adapter covers the core cases but not yet the `defer_loading` / `tool_addition` / `tool_reference` tool machinery, the -thinking `budget_tokens` mapping, or prompt-cache token accounting. The GUI is -text-chat first: images, tools and advanced settings in the GUI are still to come. +thinking `budget_tokens` mapping, or prompt-cache token accounting. The GUI agent's +**isolated mode** (Docker-container runner) and GUI images / advanced settings are +still to come; base/host agent mode works. ## License and credits diff --git a/src/agent/mod.rs b/src/agent/mod.rs new file mode 100644 index 0000000..51ea169 --- /dev/null +++ b/src/agent/mod.rs @@ -0,0 +1,405 @@ +//! 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`]). The execution mode +//! is chosen by the [`shell::ShellRunner`] implementation: base mode runs on the +//! host ([`shell::HostShell`]); the isolated mode will route to a sandboxed runner +//! (e.g. the team's Docker-container MCP server) behind the same seam. +//! +//! [`run_loop`] is pure orchestration — generic over the "model step" — so it is +//! testable without the engine and independent of the execution mode. + +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 (currently the universal `shell_exec`). +pub fn agent_tools() -> Json { + json!([shell::shell_exec_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, + }, + 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. +async fn execute_tool(runner: &Arc, tc: &ToolCall) -> 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}"), + }; + match runner + .run(&req.command, req.cwd.as_deref(), req.timeout) + .await + { + Ok(out) => out.to_result_text(), + Err(e) => format!("error: {e}"), + } +} + +/// 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())) +} + +/// 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, + runner: Arc, + store: Arc, + session_id: &str, + mut req: ChatRequest, + max_iters: usize, + progress: Option>, +) -> Result +where + M: FnMut(ChatRequest) -> Fut, + Fut: Future>, +{ + 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, tc).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", None).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, + runner, + store.clone(), + &sess.id, + base_req(), + 8, + Some(tx), + ) + .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::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", None).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, runner, store, &sess.id, base_req(), 3, None) + .await + .unwrap_err(); + assert_eq!(err.error.code.as_deref(), Some("agent_step_limit")); + } + + #[tokio::test] + async fn unknown_tool_yields_error_result() { + 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, &tc).await; + assert!(out.contains("unknown tool")); + } +} diff --git a/src/agent/shell.rs b/src/agent/shell.rs new file mode 100644 index 0000000..54a295c --- /dev/null +++ b/src/agent/shell.rs @@ -0,0 +1,268 @@ +//! The agent's universal tool: `shell_exec` runs a command and returns its +//! output. A shell is a universal tool — with it the agent can do file ops, run +//! programs, inspect the system, fetch the web via curl, git, etc. +//! +//! Execution sits behind the [`ShellRunner`] seam. Base mode ([`HostShell`]) runs +//! directly on the host (a trusted machine); an isolated/sandboxed runner can +//! implement the same trait later without touching the agent loop. + +use std::future::Future; +use std::pin::Pin; +use std::process::Stdio; +use std::time::Duration; + +use anyhow::{Context, Result}; +use serde_json::{json, Value as Json}; + +/// Max bytes of stdout/stderr handed back to the model, so a verbose command +/// cannot flood the context window. +const MAX_OUTPUT: usize = 64 * 1024; +/// Default per-command timeout. +pub const DEFAULT_TIMEOUT_SECS: u64 = 120; + +/// The result of one shell command. +#[derive(Debug, Clone)] +pub struct ShellOutput { + pub stdout: String, + pub stderr: String, + pub exit_code: i32, + pub timed_out: bool, + pub truncated: bool, +} + +impl ShellOutput { + /// Render as the tool-result text the model reads. + pub fn to_result_text(&self) -> String { + let mut s = format!("exit_code: {}\n", self.exit_code); + if self.timed_out { + s.push_str("timed_out: true\n"); + } + if !self.stdout.is_empty() { + s.push_str("stdout:\n"); + s.push_str(&self.stdout); + s.push('\n'); + } + if !self.stderr.is_empty() { + s.push_str("stderr:\n"); + s.push_str(&self.stderr); + s.push('\n'); + } + if self.truncated { + s.push_str("(output truncated to 64 KiB per stream)\n"); + } + s + } +} + +type ShellFuture<'a> = Pin> + Send + 'a>>; + +/// The execution seam: base mode runs on the host; a sandboxed runner replaces it +/// for the isolated mode. Dyn-compatible so the agent loop can hold `Arc`. +pub trait ShellRunner: Send + Sync { + fn run<'a>( + &'a self, + command: &'a str, + cwd: Option<&'a str>, + timeout: Duration, + ) -> ShellFuture<'a>; +} + +/// Base mode: execute directly on the host via `bash -lc`. +pub struct HostShell; + +impl ShellRunner for HostShell { + fn run<'a>( + &'a self, + command: &'a str, + cwd: Option<&'a str>, + timeout: Duration, + ) -> ShellFuture<'a> { + Box::pin(async move { host_run(command, cwd, timeout).await }) + } +} + +async fn host_run(command: &str, cwd: Option<&str>, timeout: Duration) -> Result { + let mut cmd = tokio::process::Command::new("bash"); + cmd.arg("-lc") + .arg(command) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .kill_on_drop(true); + if let Some(d) = cwd { + cmd.current_dir(d); + } + let child = cmd.spawn().context("spawning bash for shell_exec")?; + match tokio::time::timeout(timeout, child.wait_with_output()).await { + Ok(Ok(out)) => { + let mut stdout = String::from_utf8_lossy(&out.stdout).into_owned(); + let mut stderr = String::from_utf8_lossy(&out.stderr).into_owned(); + let truncated = stdout.len() > MAX_OUTPUT || stderr.len() > MAX_OUTPUT; + truncate(&mut stdout); + truncate(&mut stderr); + Ok(ShellOutput { + stdout, + stderr, + exit_code: out.status.code().unwrap_or(-1), + timed_out: false, + truncated, + }) + } + Ok(Err(e)) => Err(anyhow::anyhow!("shell_exec failed: {e}")), + // Timeout: dropping the future drops the child, and kill_on_drop reaps it. + Err(_) => Ok(ShellOutput { + stdout: String::new(), + stderr: String::new(), + exit_code: -1, + timed_out: true, + truncated: false, + }), + } +} + +fn truncate(s: &mut String) { + if s.len() > MAX_OUTPUT { + let mut end = MAX_OUTPUT; + while !s.is_char_boundary(end) { + end -= 1; + } + s.truncate(end); + } +} + +/// A parsed `shell_exec` invocation. +pub struct ShellRequest { + pub command: String, + pub cwd: Option, + pub timeout: Duration, +} + +impl ShellRequest { + pub fn from_args(args: &Json) -> Result { + let command = args + .get("command") + .and_then(|v| v.as_str()) + .filter(|s| !s.trim().is_empty()) + .ok_or_else(|| anyhow::anyhow!("shell_exec requires a non-empty 'command'"))? + .to_string(); + let cwd = args.get("cwd").and_then(|v| v.as_str()).map(str::to_string); + let secs = args + .get("timeout_secs") + .and_then(|v| v.as_u64()) + .unwrap_or(DEFAULT_TIMEOUT_SECS) + .clamp(1, 3600); + Ok(Self { + command, + cwd, + timeout: Duration::from_secs(secs), + }) + } +} + +/// The OpenAI function declaration offered to the model for the agent. +pub fn shell_exec_declaration() -> Json { + json!({ + "type": "function", + "function": { + "name": "shell_exec", + "description": "Execute a shell command on the host with bash -lc and return its \ + stdout, stderr and exit code. Use it for file operations, running programs, \ + inspecting the system, web requests via curl, git, and so on. Chain steps with \ + && or ;. State (working directory, environment) does NOT persist between calls: \ + pass cwd or use absolute paths.", + "parameters": { + "type": "object", + "properties": { + "command": { "type": "string", "description": "The shell command to execute." }, + "cwd": { "type": "string", "description": "Optional working directory for this command." }, + "timeout_secs": { "type": "integer", "description": "Optional timeout in seconds (default 120)." } + }, + "required": ["command"] + } + } + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn run(cmd: &str) -> ShellOutput { + let rt = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .unwrap(); + rt.block_on(HostShell.run(cmd, None, Duration::from_secs(10))) + .unwrap() + } + + #[test] + fn echo_stdout_and_exit_zero() { + let out = run("echo hello-agent"); + assert_eq!(out.exit_code, 0); + assert!(out.stdout.contains("hello-agent")); + assert!(!out.timed_out); + assert!(out.to_result_text().contains("exit_code: 0")); + } + + #[test] + fn exit_code_and_stderr_are_captured() { + let out = run("echo oops >&2; exit 3"); + assert_eq!(out.exit_code, 3); + assert!(out.stderr.contains("oops")); + } + + #[test] + fn cwd_is_honored() { + let rt = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .unwrap(); + let out = rt + .block_on(HostShell.run("pwd", Some("/tmp"), Duration::from_secs(10))) + .unwrap(); + assert!(out.stdout.trim().ends_with("/tmp")); + } + + #[test] + fn timeout_is_reported() { + let rt = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .unwrap(); + let out = rt + .block_on(HostShell.run("sleep 5", None, Duration::from_millis(300))) + .unwrap(); + assert!(out.timed_out); + assert_eq!(out.exit_code, -1); + } + + #[test] + fn large_output_is_truncated() { + // ~200 KB of output -> capped at 64 KiB. + let out = run("head -c 200000 /dev/zero | tr '\\0' 'a'"); + assert!(out.truncated); + assert!(out.stdout.len() <= MAX_OUTPUT); + } + + #[test] + fn args_parse_and_validate() { + let ok = ShellRequest::from_args(&json!({"command":"ls","cwd":"/tmp","timeout_secs":5})) + .unwrap(); + assert_eq!(ok.command, "ls"); + assert_eq!(ok.cwd.as_deref(), Some("/tmp")); + assert_eq!(ok.timeout, Duration::from_secs(5)); + assert!(ShellRequest::from_args(&json!({"command":" "})).is_err()); + assert!(ShellRequest::from_args(&json!({})).is_err()); + let default = ShellRequest::from_args(&json!({"command":"ls"})).unwrap(); + assert_eq!(default.timeout, Duration::from_secs(DEFAULT_TIMEOUT_SECS)); + } + + #[test] + fn declaration_shape() { + let d = shell_exec_declaration(); + assert_eq!(d["type"], "function"); + assert_eq!(d["function"]["name"], "shell_exec"); + assert_eq!(d["function"]["parameters"]["required"][0], "command"); + } +} diff --git a/src/api/sessions.rs b/src/api/sessions.rs index acdeab0..f14dc0d 100644 --- a/src/api/sessions.rs +++ b/src/api/sessions.rs @@ -17,7 +17,10 @@ use serde::Deserialize; use super::routes::{AppState, Error}; use super::types::{ChatChunk, ChatMessage, ChatRequest, FunctionCall, Role, ToolCall, Usage}; +use crate::agent::shell::{HostShell, ShellRunner}; +use crate::agent::{self, AgentEvent}; use crate::store::{NewMessage, Session, Stats, Store, StoredMessage}; +use tokio_stream::wrappers::UnboundedReceiverStream; /// Run a synchronous store operation off the async runtime. async fn with_store(st: &AppState, f: F) -> Result @@ -55,6 +58,9 @@ pub(crate) struct SessionChat { content: String, #[serde(default)] stream: bool, + /// Run the model as an agent with the `shell_exec` tool (host mode). + #[serde(default)] + agent: bool, #[serde(default)] max_tokens: Option, #[serde(default)] @@ -262,7 +268,7 @@ pub(crate) async fn session_chat( Err(e) => return e.into_response(), }; - let req = build_request(&sess, &history, &body); + let mut req = build_request(&sess, &history, &body); // Persist the user turn before generating. let user_content = body.content.clone(); @@ -276,6 +282,7 @@ pub(crate) async fn session_chat( content: &user_content, reasoning_content: None, tool_calls_json: None, + tool_call_id: None, prompt_tokens: 0, completion_tokens: 0, }, @@ -287,6 +294,58 @@ pub(crate) async fn session_chat( return e.into_response(); } + // Agent mode: drive the model↔shell_exec loop, streaming progress events. + if body.agent { + req.tools = Some(agent::agent_tools()); + req.tool_choice = Some(serde_json::json!("auto")); + let (tx, rx) = tokio::sync::mpsc::unbounded_channel::(); + let svc = st.service.clone(); + let store2 = store.clone(); + let sid = id.clone(); + tokio::spawn(async move { + let model = move |r: ChatRequest| { + let svc = svc.clone(); + async move { svc.complete(&r).await } + }; + // Base mode: the host shell. Isolated mode will swap in a Docker-MCP + // runner behind the same ShellRunner seam. + let runner: Arc = Arc::new(HostShell); + if let Err(env) = agent::run_loop( + model, + runner, + store2, + &sid, + req, + agent::MAX_ITERS, + Some(tx.clone()), + ) + .await + { + let _ = tx.send(AgentEvent::Error { + message: env.error.message, + }); + } + }); + let events = UnboundedReceiverStream::new(rx) + .map(|ev| match Event::default().json_data(&ev) { + Ok(e) => Ok::<_, std::convert::Infallible>(e), + Err(e) => { + tracing::error!(error = %e, "failed to serialize agent event"); + Ok(Event::default().data("{}")) + } + }) + .chain(futures::stream::once(async { + Ok::<_, std::convert::Infallible>(Event::default().data("[DONE]")) + })); + return Sse::new(events) + .keep_alive( + axum::response::sse::KeepAlive::new() + .interval(std::time::Duration::from_secs(10)) + .text("ping"), + ) + .into_response(); + } + if body.stream { match st.service.stream(&req).await { Ok((stream, prompt_len)) => { @@ -371,6 +430,7 @@ async fn persist_assistant(store: &Arc, sid: &str, a: &Accum, prompt_ content: &content, reasoning_content: reasoning.as_deref(), tool_calls_json: tool_json.as_deref(), + tool_call_id: None, prompt_tokens: pt, completion_tokens: ct, }, diff --git a/src/lib.rs b/src/lib.rs index 5c52188..ded3c4f 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -6,6 +6,7 @@ //! - [`store`]: persistent session/context store for the web GUI (SQLite behind //! a swappable `Store` trait). +pub mod agent; pub mod api; pub mod config; pub mod engine; diff --git a/src/store.rs b/src/store.rs index de2f6f6..1cd0bf6 100644 --- a/src/store.rs +++ b/src/store.rs @@ -35,6 +35,7 @@ pub struct StoredMessage { pub content: String, pub reasoning_content: Option, pub tool_calls_json: Option, + pub tool_call_id: Option, pub prompt_tokens: u32, pub completion_tokens: u32, pub created_at: i64, @@ -46,6 +47,7 @@ pub struct NewMessage<'a> { pub content: &'a str, pub reasoning_content: Option<&'a str>, pub tool_calls_json: Option<&'a str>, + pub tool_call_id: Option<&'a str>, pub prompt_tokens: u32, pub completion_tokens: u32, } @@ -110,6 +112,7 @@ CREATE TABLE IF NOT EXISTS messages ( content TEXT NOT NULL, reasoning_content TEXT, tool_calls_json TEXT, + tool_call_id TEXT, prompt_tokens INTEGER NOT NULL DEFAULT 0, completion_tokens INTEGER NOT NULL DEFAULT 0, created_at INTEGER NOT NULL @@ -146,6 +149,7 @@ impl SqliteStore { conn.pragma_update(None, "synchronous", "NORMAL")?; conn.pragma_update(None, "foreign_keys", "ON")?; conn.execute_batch(SCHEMA)?; + migrate(&conn)?; Ok(Self { conn: Mutex::new(conn), }) @@ -156,6 +160,19 @@ impl SqliteStore { } } +/// Idempotent schema migrations for databases created by older versions. +/// `CREATE TABLE IF NOT EXISTS` never alters an existing table, so new columns +/// must be added explicitly when missing. +fn migrate(conn: &Connection) -> Result<()> { + let has_tool_call_id: i64 = conn + .prepare("SELECT COUNT(*) FROM pragma_table_info('messages') WHERE name = 'tool_call_id'")? + .query_row([], |r| r.get(0))?; + if has_tool_call_id == 0 { + conn.execute_batch("ALTER TABLE messages ADD COLUMN tool_call_id TEXT;")?; + } + Ok(()) +} + fn row_to_session(row: &rusqlite::Row<'_>) -> rusqlite::Result { Ok(Session { id: row.get("id")?, @@ -233,6 +250,7 @@ impl Store for SqliteStore { content: row.get("content")?, reasoning_content: row.get("reasoning_content")?, tool_calls_json: row.get("tool_calls_json")?, + tool_call_id: row.get("tool_call_id")?, prompt_tokens: row.get::<_, i64>("prompt_tokens")? as u32, completion_tokens: row.get::<_, i64>("completion_tokens")? as u32, created_at: row.get("created_at")?, @@ -247,14 +265,15 @@ impl Store for SqliteStore { conn.execute( "INSERT INTO messages (session_id, role, content, reasoning_content, tool_calls_json, - prompt_tokens, completion_tokens, created_at) - VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)", + tool_call_id, prompt_tokens, completion_tokens, created_at) + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)", params![ session_id, msg.role, msg.content, msg.reasoning_content, msg.tool_calls_json, + msg.tool_call_id, msg.prompt_tokens as i64, msg.completion_tokens as i64, now @@ -271,6 +290,7 @@ impl Store for SqliteStore { content: msg.content.to_string(), reasoning_content: msg.reasoning_content.map(str::to_string), tool_calls_json: msg.tool_calls_json.map(str::to_string), + tool_call_id: msg.tool_call_id.map(str::to_string), prompt_tokens: msg.prompt_tokens, completion_tokens: msg.completion_tokens, created_at: now, @@ -318,6 +338,7 @@ mod tests { content: "ciao", reasoning_content: None, tool_calls_json: None, + tool_call_id: None, prompt_tokens: 3, completion_tokens: 0, }, @@ -330,6 +351,7 @@ mod tests { content: "ciao!", reasoning_content: Some("think"), tool_calls_json: None, + tool_call_id: None, prompt_tokens: 3, completion_tokens: 5, }, @@ -366,4 +388,25 @@ mod tests { let b = new_id("sess"); assert_ne!(a, b); } + + #[test] + fn migration_adds_tool_call_id_to_old_schema() { + // Simulate a pre-existing database without the tool_call_id column. + let conn = Connection::open_in_memory().unwrap(); + conn.execute_batch( + "CREATE TABLE messages (id INTEGER PRIMARY KEY, session_id TEXT, role TEXT, + content TEXT, reasoning_content TEXT, tool_calls_json TEXT, + prompt_tokens INTEGER, completion_tokens INTEGER, created_at INTEGER);", + ) + .unwrap(); + migrate(&conn).unwrap(); + let n: i64 = conn + .prepare("SELECT COUNT(*) FROM pragma_table_info('messages') WHERE name='tool_call_id'") + .unwrap() + .query_row([], |r| r.get(0)) + .unwrap(); + assert_eq!(n, 1); + // Idempotent: running again does not error. + migrate(&conn).unwrap(); + } } diff --git a/tests/api_sessions.rs b/tests/api_sessions.rs index 614fbc2..4226a55 100644 --- a/tests/api_sessions.rs +++ b/tests/api_sessions.rs @@ -265,3 +265,37 @@ async fn unknown_session_is_404() { .await; assert_eq!(st, StatusCode::NOT_FOUND); } + +#[tokio::test] +async fn agent_mode_streams_events_and_persists() { + let (app, store) = build_app().await; + let id = create_session(&app).await; + // The mock answers directly (no tool calls), exercising the agent final path. + let (st, text) = req( + &app, + Method::POST, + &format!("/api/sessions/{id}/chat"), + Some(serde_json::json!({"content": "hi", "agent": true})), + ) + .await; + assert_eq!(st, StatusCode::OK, "{text}"); + let data: Vec<&str> = text + .lines() + .filter(|l| l.starts_with("data: ")) + .map(|l| &l["data: ".len()..]) + .collect(); + assert_eq!(data.last().copied(), Some("[DONE]")); + let mut saw_final = false; + for line in &data[..data.len() - 1] { + let v: serde_json::Value = serde_json::from_str(line).unwrap(); + if v["type"] == "final" { + saw_final = true; + assert_eq!(v["response"]["choices"][0]["message"]["content"], "efghi"); + } + } + assert!(saw_final, "no final agent event: {text}"); + // The final assistant turn is persisted. + let msgs = store.messages(&id).unwrap(); + assert_eq!(msgs.last().unwrap().role, "assistant"); + assert_eq!(msgs.last().unwrap().content, "efghi"); +} diff --git a/web/assets/app.css b/web/assets/app.css index 74a332e..414b9e8 100644 --- a/web/assets/app.css +++ b/web/assets/app.css @@ -138,6 +138,21 @@ details.thinking .reasoning { } .usage { color: var(--muted); font-size: 0.72rem; margin-top: 6px; } +/* ---- Agent tool blocks ---- */ +.msg.tool .bubble { + background: var(--panel-2); border: 1px solid var(--border); + border-radius: var(--radius); padding: 10px 14px; width: 100%; + font-family: ui-monospace, SFMono-Regular, Menlo, monospace; +} +.tool-cmd { display: block; white-space: pre-wrap; word-wrap: break-word; font-size: 0.9rem; } +.tool-out { + margin: 8px 0 0; max-height: 300px; overflow: auto; + white-space: pre-wrap; word-wrap: break-word; color: var(--muted); + font-size: 0.82rem; background: var(--bg); border-radius: 8px; padding: 8px; +} +.tool-out:empty { display: none; } +#agent-toggle.active { background: var(--accent); border-color: var(--accent); color: #fff; } + /* ---- Composer ---- */ #composer { display: flex; gap: 8px; align-items: flex-end; diff --git a/web/assets/app.js b/web/assets/app.js index 2a32e57..0adfb24 100644 --- a/web/assets/app.js +++ b/web/assets/app.js @@ -5,7 +5,7 @@ const $ = (sel) => document.querySelector(sel); -const state = { sessions: [], current: null, busy: false }; +const state = { sessions: [], current: null, busy: false, agent: false }; // ---- API helpers ---------------------------------------------------------- async function getJSON(url) { @@ -81,6 +81,37 @@ function scrollDown() { t.scrollTop = t.scrollHeight; } +function usageText(u) { + return u ? `${u.prompt_tokens} + ${u.completion_tokens} token` : null; +} + +// A tool-call block (command + an output area filled when the result arrives). +function toolCallNode(name, argsJson) { + let cmd = argsJson; + try { + const a = JSON.parse(argsJson); + if (a && a.command !== undefined) cmd = a.command; + } catch { /* keep raw */ } + const wrap = el("div", "msg tool"); + wrap.appendChild(el("div", "role", `\u{1F527} ${name || "tool"}`)); + const bubble = el("div", "bubble"); + bubble.appendChild(el("code", "tool-cmd", cmd)); + const out = el("pre", "tool-out", ""); + bubble.appendChild(out); + wrap.appendChild(bubble); + wrap._out = out; + return wrap; +} + +function toolResultNode(output) { + const wrap = el("div", "msg tool"); + wrap.appendChild(el("div", "role", "\u{1F527} output")); + const bubble = el("div", "bubble"); + bubble.appendChild(el("pre", "tool-out", output)); + wrap.appendChild(bubble); + return wrap; +} + // ---- Rendering ------------------------------------------------------------ function renderSessions() { const list = $("#session-list"); @@ -95,15 +126,31 @@ function renderSessions() { function renderTranscript(messages) { const t = $("#transcript"); t.textContent = ""; - const visible = messages.filter((m) => m.role === "user" || m.role === "assistant"); - if (visible.length === 0) { + if (!messages.length) { t.appendChild(el("div", "empty", "Inizia una conversazione: scrivi un messaggio qui sotto.")); return; } - for (const m of visible) { - const usage = m.role === "assistant" && m.completion_tokens - ? `${m.prompt_tokens} + ${m.completion_tokens} token` : null; - t.appendChild(messageNode(m.role, m.content, m.reasoning_content, usage)); + for (const m of messages) { + if (m.role === "user") { + t.appendChild(messageNode("user", m.content)); + } else if (m.role === "tool") { + t.appendChild(toolResultNode(m.content)); + } else if (m.role === "assistant") { + if (m.tool_calls_json) { + let calls = []; + try { calls = JSON.parse(m.tool_calls_json); } catch { /* ignore */ } + for (const tc of calls) { + const f = tc.function || {}; + t.appendChild(toolCallNode(f.name, f.arguments)); + } + } + if (m.content) { + const usage = m.completion_tokens + ? usageText({ prompt_tokens: m.prompt_tokens, completion_tokens: m.completion_tokens }) + : null; + t.appendChild(messageNode("assistant", m.content, m.reasoning_content, usage)); + } + } } scrollDown(); } @@ -160,8 +207,25 @@ async function sendMessage() { const empty = t.querySelector(".empty"); if (empty) empty.remove(); t.appendChild(messageNode("user", content)); + scrollDown(); - // Live assistant bubble. + try { + if (state.agent) await agentTurn(content, t); + else await chatTurn(content, t); + state.sessions = await getJSON("/api/sessions"); + renderSessions(); + } catch (e) { + t.appendChild(messageNode("assistant", `Errore: ${e.message}`)); + } finally { + state.busy = false; + $("#send").disabled = false; + input.focus(); + scrollDown(); + } +} + +// Plain chat: stream OpenAI chunks into a live assistant bubble. +async function chatTurn(content, t) { const wrap = el("div", "msg assistant"); wrap.appendChild(el("div", "role", "Assistente")); const bubble = el("div", "bubble"); @@ -178,35 +242,65 @@ async function sendMessage() { scrollDown(); let reasoning = "", text = "", usage = null; - try { - await streamChat(state.current, content, (chunk) => { - const d = chunk.choices && chunk.choices[0] && chunk.choices[0].delta; - if (d && d.reasoning_content) { - reasoning += d.reasoning_content; - reasoningNode.textContent = reasoning; - det.hidden = false; - } - if (d && d.content) { - text += d.content; - contentNode.textContent = text; - } - if (chunk.usage) usage = chunk.usage; - scrollDown(); - }); - if (usage) { - bubble.appendChild(el("div", "usage", - `${usage.prompt_tokens} + ${usage.completion_tokens} token`)); + await streamChat(state.current, content, (chunk) => { + const d = chunk.choices && chunk.choices[0] && chunk.choices[0].delta; + if (d && d.reasoning_content) { + reasoning += d.reasoning_content; + reasoningNode.textContent = reasoning; + det.hidden = false; } - // Refresh ordering/titles without losing the live transcript. - state.sessions = await getJSON("/api/sessions"); - renderSessions(); - } catch (e) { - contentNode.textContent = text || `Errore: ${e.message}`; - } finally { - state.busy = false; - $("#send").disabled = false; - input.focus(); + if (d && d.content) { + text += d.content; + contentNode.textContent = text; + } + if (chunk.usage) usage = chunk.usage; scrollDown(); + }); + if (usage) bubble.appendChild(el("div", "usage", usageText(usage))); +} + +// Agent mode: stream tool_call / tool_result / final events (observability, no gate). +async function agentTurn(content, t) { + const r = await fetch(`/api/sessions/${state.current}/chat`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ content, agent: true }), + }); + if (!r.ok) throw new Error(await r.text()); + const reader = r.body.getReader(); + const dec = new TextDecoder(); + let buf = ""; + const toolNodes = {}; + for (;;) { + const { done, value } = await reader.read(); + if (done) break; + buf += dec.decode(value, { stream: true }); + let idx; + while ((idx = buf.indexOf("\n\n")) >= 0) { + const block = buf.slice(0, idx); + buf = buf.slice(idx + 2); + for (const line of block.split("\n")) { + if (!line.startsWith("data:")) continue; + const data = line.slice(5).trim(); + if (data === "[DONE]") return; + let ev; + try { ev = JSON.parse(data); } catch { continue; } + if (ev.type === "tool_call") { + const n = toolCallNode(ev.name, ev.arguments); + toolNodes[ev.id] = n; + t.appendChild(n); + } else if (ev.type === "tool_result") { + const n = toolNodes[ev.id]; + if (n) n._out.textContent = ev.output; + } else if (ev.type === "final") { + const m = ev.response.choices[0].message; + t.appendChild(messageNode("assistant", m.content || "", m.reasoning_content, usageText(ev.response.usage))); + } else if (ev.type === "error") { + t.appendChild(messageNode("assistant", `Errore agent: ${ev.message}`)); + } + scrollDown(); + } + } } } @@ -290,6 +384,12 @@ function wire() { $("#new-session").addEventListener("click", newSession); $("#delete-session").addEventListener("click", deleteSession); $("#send").addEventListener("click", sendMessage); + $("#agent-toggle").addEventListener("click", () => { + state.agent = !state.agent; + const b = $("#agent-toggle"); + b.classList.toggle("active", state.agent); + b.setAttribute("aria-pressed", String(state.agent)); + }); $("#show-stats").addEventListener("click", showStats); $("#close-stats").addEventListener("click", () => { $("#stats-modal").hidden = true; }); const input = $("#input"); diff --git a/web/index.html b/web/index.html index 9ae03b2..79cf8ad 100644 --- a/web/index.html +++ b/web/index.html @@ -5,6 +5,7 @@ strata-ctl + @@ -38,6 +39,7 @@