Add GUI agent mode: the model acts via a universal shell_exec tool

- agent:🐚 native shell_exec (bash -lc, cwd, timeout, 64 KiB output cap)
  behind a ShellRunner seam — base/host mode now; an isolated Docker-MCP runner
  plugs in later without touching the loop. OpenAI function declaration included.
- agent::run_loop: bounded model<->tool orchestration, generic over the model
  step so it is unit-testable without the engine. Persists the full trajectory
  (assistant tool-call turns + role:tool results + final answer) and emits
  tool_call / tool_result / final / error progress events.
- api::sessions: POST .../chat with agent:true drives the loop and streams the
  events as SSE; the GUI shows commands + output inline (observability, no gate).
- store: messages gains tool_call_id; an idempotent migration adds the column to
  pre-existing databases (CREATE TABLE IF NOT EXISTS does not alter them).
- web: robot agent toggle, tool-call/output blocks, history rendering of tool
  turns; inline favicon to silence the favicon 404.

Validated LIVE on engine 0.1.67: the model called shell_exec('uname -a'), the
host executed it, and the model reported the output; trajectory persisted; GUI
verified by browser (toggle, tool block, output, final answer). 106 tests +
2 ignored green, clippy/fmt clean. Isolated mode (user-provided Docker container)
is the next step.
This commit is contained in:
adm committed 2026-11-25 02:06:45 +01:00
1 parent e29878bb3d
commit 8979201139
10 files changed
+994 -43

No files matched your search

+405
View File
@@ -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<UnboundedSender<AgentEvent>>, 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<dyn ShellRunner>, 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<String>,
tool_calls_json: Option<String>,
tool_call_id: Option<String>,
prompt_tokens: u32,
completion_tokens: u32,
}
async fn persist(store: &Arc<dyn Store>, 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<String>, 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<M, Fut>(
mut model: M,
runner: Arc<dyn ShellRunner>,
store: Arc<dyn Store>,
session_id: &str,
mut req: ChatRequest,
max_iters: usize,
progress: Option<UnboundedSender<AgentEvent>>,
) -> Result<ChatResponse, ApiErrorEnvelope>
where
M: FnMut(ChatRequest) -> Fut,
Fut: Future<Output = Result<ChatResponse, ApiErrorEnvelope>>,
{
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<dyn Store> = Arc::new(SqliteStore::open_in_memory().unwrap());
let sess = store.create_session("Agent", "test-model", None).unwrap();
let runner: Arc<dyn ShellRunner> = 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<dyn Store> = Arc::new(SqliteStore::open_in_memory().unwrap());
let sess = store.create_session("Agent", "test-model", None).unwrap();
let runner: Arc<dyn ShellRunner> = 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<dyn ShellRunner> = 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"));
}
}
+268
View File
@@ -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<Box<dyn Future<Output = Result<ShellOutput>> + 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<dyn _>`.
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<ShellOutput> {
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<String>,
pub timeout: Duration,
}
impl ShellRequest {
pub fn from_args(args: &Json) -> Result<Self> {
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");
}
}