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:
1 parent
e29878bb3d
commit
8979201139
10 files changed
+994
-43
No files matched your search
+61
-1
@@ -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<T, F>(st: &AppState, f: F) -> Result<T, Error>
|
||||
@@ -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<u32>,
|
||||
#[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::<AgentEvent>();
|
||||
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<dyn ShellRunner> = 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<dyn Store>, 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,
|
||||
},
|
||||
|
||||
Reference in new issue
Block a user