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"));
}
}