- 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.
441 lines
14 KiB
Rust
441 lines
14 KiB
Rust
//! Session-aware API for the web GUI: `/api/sessions...` and `/api/stats`.
|
|
//!
|
|
//! The standard `/v1` surface stays stateless; here the server owns the
|
|
//! conversation context (via the [`Store`]) so the GUI can be a thin client and
|
|
//! so multi-session, statistics and settings can grow on top. The chat endpoint
|
|
//! loads a session's history, reuses [`ChatService`] for inference (no duplicated
|
|
//! engine-driving), and persists the new turns with their token usage.
|
|
|
|
use std::collections::BTreeMap;
|
|
use std::sync::{Arc, Mutex};
|
|
|
|
use axum::extract::{Path, State};
|
|
use axum::http::StatusCode;
|
|
use axum::response::{sse::Event, sse::Sse, IntoResponse, Json};
|
|
use futures::StreamExt;
|
|
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>
|
|
where
|
|
F: FnOnce(Arc<dyn Store>) -> anyhow::Result<T> + Send + 'static,
|
|
T: Send + 'static,
|
|
{
|
|
let store = st
|
|
.store
|
|
.clone()
|
|
.ok_or_else(|| Error::internal("no store configured"))?;
|
|
tokio::task::spawn_blocking(move || f(store))
|
|
.await
|
|
.map_err(|e| Error::internal(format!("store task failed: {e}")))?
|
|
.map_err(|e| Error::internal(format!("store error: {e}")))
|
|
}
|
|
|
|
#[derive(Deserialize)]
|
|
pub(crate) struct CreateSession {
|
|
#[serde(default)]
|
|
title: Option<String>,
|
|
#[serde(default)]
|
|
model: Option<String>,
|
|
#[serde(default)]
|
|
system_prompt: Option<String>,
|
|
}
|
|
|
|
#[derive(Deserialize)]
|
|
pub(crate) struct Rename {
|
|
title: String,
|
|
}
|
|
|
|
#[derive(Deserialize)]
|
|
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)]
|
|
temperature: Option<f64>,
|
|
#[serde(default)]
|
|
top_p: Option<f64>,
|
|
}
|
|
|
|
pub(crate) async fn create_session(
|
|
State(st): State<AppState>,
|
|
Json(body): Json<CreateSession>,
|
|
) -> Result<Json<Session>, Error> {
|
|
let model = body
|
|
.model
|
|
.unwrap_or_else(|| st.service.model_name().to_string());
|
|
let title = body.title.unwrap_or_else(|| "Nuova chat".to_string());
|
|
let system = body.system_prompt;
|
|
let sess = with_store(&st, move |s| {
|
|
s.create_session(&title, &model, system.as_deref())
|
|
})
|
|
.await?;
|
|
Ok(Json(sess))
|
|
}
|
|
|
|
pub(crate) async fn list_sessions(State(st): State<AppState>) -> Result<Json<Vec<Session>>, Error> {
|
|
Ok(Json(with_store(&st, |s| s.list_sessions()).await?))
|
|
}
|
|
|
|
pub(crate) async fn get_session(
|
|
State(st): State<AppState>,
|
|
Path(id): Path<String>,
|
|
) -> Result<Json<Session>, Error> {
|
|
let sess = with_store(&st, move |s| s.get_session(&id)).await?;
|
|
sess.map(Json)
|
|
.ok_or_else(|| Error::not_found("session not found"))
|
|
}
|
|
|
|
pub(crate) async fn delete_session(
|
|
State(st): State<AppState>,
|
|
Path(id): Path<String>,
|
|
) -> Result<StatusCode, Error> {
|
|
with_store(&st, move |s| s.delete_session(&id)).await?;
|
|
Ok(StatusCode::NO_CONTENT)
|
|
}
|
|
|
|
pub(crate) async fn rename_session(
|
|
State(st): State<AppState>,
|
|
Path(id): Path<String>,
|
|
Json(body): Json<Rename>,
|
|
) -> Result<StatusCode, Error> {
|
|
with_store(&st, move |s| s.rename_session(&id, &body.title)).await?;
|
|
Ok(StatusCode::OK)
|
|
}
|
|
|
|
pub(crate) async fn get_messages(
|
|
State(st): State<AppState>,
|
|
Path(id): Path<String>,
|
|
) -> Result<Json<Vec<StoredMessage>>, Error> {
|
|
Ok(Json(with_store(&st, move |s| s.messages(&id)).await?))
|
|
}
|
|
|
|
pub(crate) async fn stats(State(st): State<AppState>) -> Result<Json<Stats>, Error> {
|
|
Ok(Json(with_store(&st, |s| s.stats()).await?))
|
|
}
|
|
|
|
fn role_of(s: &str) -> Role {
|
|
match s {
|
|
"system" | "developer" => Role::System,
|
|
"assistant" => Role::Assistant,
|
|
"tool" => Role::Tool,
|
|
_ => Role::User,
|
|
}
|
|
}
|
|
|
|
fn text_message(role: Role, text: String) -> ChatMessage {
|
|
ChatMessage {
|
|
role,
|
|
content: Some(serde_json::Value::String(text)),
|
|
tool_call_id: None,
|
|
tool_calls: None,
|
|
name: None,
|
|
reasoning_content: None,
|
|
}
|
|
}
|
|
|
|
/// Rebuild a stateless [`ChatRequest`] from the stored history plus the new turn.
|
|
/// Prior `reasoning_content` is deliberately NOT replayed into the prompt.
|
|
fn build_request(sess: &Session, history: &[StoredMessage], body: &SessionChat) -> ChatRequest {
|
|
let mut messages = Vec::new();
|
|
if let Some(sp) = &sess.system_prompt {
|
|
messages.push(text_message(Role::System, sp.clone()));
|
|
}
|
|
for m in history {
|
|
let mut msg = text_message(role_of(&m.role), m.content.clone());
|
|
msg.tool_calls = m
|
|
.tool_calls_json
|
|
.as_deref()
|
|
.and_then(|s| serde_json::from_str(s).ok());
|
|
messages.push(msg);
|
|
}
|
|
messages.push(text_message(Role::User, body.content.clone()));
|
|
ChatRequest {
|
|
model: sess.model.clone(),
|
|
messages,
|
|
stream: body.stream,
|
|
temperature: body.temperature,
|
|
top_p: body.top_p,
|
|
max_tokens: body.max_tokens,
|
|
max_completion_tokens: None,
|
|
frequency_penalty: None,
|
|
presence_penalty: None,
|
|
seed: None,
|
|
top_k: None,
|
|
min_p: None,
|
|
repetition_penalty: None,
|
|
stop: None,
|
|
tools: None,
|
|
tool_choice: None,
|
|
}
|
|
}
|
|
|
|
/// Accumulates the assistant turn while streaming, for persistence at the end.
|
|
#[derive(Default, Clone)]
|
|
struct Accum {
|
|
content: String,
|
|
reasoning: String,
|
|
tools: BTreeMap<u64, ToolCall>,
|
|
usage: Option<Usage>,
|
|
}
|
|
|
|
fn accumulate(a: &mut Accum, chunk: &ChatChunk) {
|
|
if let Some(u) = &chunk.usage {
|
|
a.usage = Some(u.clone());
|
|
}
|
|
let Some(ch) = chunk.choices.first() else {
|
|
return;
|
|
};
|
|
let d = &ch.delta;
|
|
if let Some(c) = &d.content {
|
|
a.content.push_str(c);
|
|
}
|
|
if let Some(r) = &d.reasoning_content {
|
|
a.reasoning.push_str(r);
|
|
}
|
|
if let Some(tc) = &d.tool_calls {
|
|
if let Some(arr) = tc.as_array() {
|
|
for item in arr {
|
|
let idx = item.get("index").and_then(|v| v.as_u64()).unwrap_or(0);
|
|
let entry = a.tools.entry(idx).or_insert_with(|| ToolCall {
|
|
id: String::new(),
|
|
kind: "function".to_string(),
|
|
function: FunctionCall {
|
|
name: String::new(),
|
|
arguments: String::new(),
|
|
},
|
|
});
|
|
if let Some(id) = item.get("id").and_then(|v| v.as_str()) {
|
|
if !id.is_empty() {
|
|
entry.id = id.to_string();
|
|
}
|
|
}
|
|
if let Some(f) = item.get("function") {
|
|
if let Some(n) = f.get("name").and_then(|v| v.as_str()) {
|
|
entry.function.name.push_str(n);
|
|
}
|
|
if let Some(args) = f.get("arguments").and_then(|v| v.as_str()) {
|
|
entry.function.arguments.push_str(args);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
/// `POST /api/sessions/{id}/chat` — append a user turn, run inference over the
|
|
/// stored context, persist the assistant turn (with usage), and reply (SSE when
|
|
/// `stream`).
|
|
pub(crate) async fn session_chat(
|
|
State(st): State<AppState>,
|
|
Path(id): Path<String>,
|
|
Json(body): Json<SessionChat>,
|
|
) -> axum::response::Response {
|
|
let store = match st.store.clone() {
|
|
Some(s) => s,
|
|
None => return Error::internal("no store configured").into_response(),
|
|
};
|
|
|
|
let sess = match with_store(&st, {
|
|
let id = id.clone();
|
|
move |s| s.get_session(&id)
|
|
})
|
|
.await
|
|
{
|
|
Ok(Some(s)) => s,
|
|
Ok(None) => return Error::not_found("session not found").into_response(),
|
|
Err(e) => return e.into_response(),
|
|
};
|
|
let history = match with_store(&st, {
|
|
let id = id.clone();
|
|
move |s| s.messages(&id)
|
|
})
|
|
.await
|
|
{
|
|
Ok(h) => h,
|
|
Err(e) => return e.into_response(),
|
|
};
|
|
|
|
let mut req = build_request(&sess, &history, &body);
|
|
|
|
// Persist the user turn before generating.
|
|
let user_content = body.content.clone();
|
|
if let Err(e) = with_store(&st, {
|
|
let id = id.clone();
|
|
move |s| {
|
|
s.append_message(
|
|
&id,
|
|
NewMessage {
|
|
role: "user",
|
|
content: &user_content,
|
|
reasoning_content: None,
|
|
tool_calls_json: None,
|
|
tool_call_id: None,
|
|
prompt_tokens: 0,
|
|
completion_tokens: 0,
|
|
},
|
|
)
|
|
}
|
|
})
|
|
.await
|
|
{
|
|
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)) => {
|
|
let acc = Arc::new(Mutex::new(Accum::default()));
|
|
let acc_map = acc.clone();
|
|
let events = stream.map(move |chunk| {
|
|
accumulate(&mut acc_map.lock().unwrap(), &chunk);
|
|
match Event::default().json_data(&chunk) {
|
|
Ok(ev) => Ok::<_, std::convert::Infallible>(ev),
|
|
Err(e) => {
|
|
tracing::error!(error = %e, "failed to serialize SSE chunk");
|
|
Ok(Event::default().data("{}"))
|
|
}
|
|
}
|
|
});
|
|
let acc_end = acc.clone();
|
|
let sid = id.clone();
|
|
let tail = futures::stream::once(async move {
|
|
let a = acc_end.lock().unwrap().clone();
|
|
persist_assistant(&store, &sid, &a, prompt_len).await;
|
|
Ok::<_, std::convert::Infallible>(Event::default().data("[DONE]"))
|
|
});
|
|
Sse::new(events.chain(tail))
|
|
.keep_alive(
|
|
axum::response::sse::KeepAlive::new()
|
|
.interval(std::time::Duration::from_secs(10))
|
|
.text("ping"),
|
|
)
|
|
.into_response()
|
|
}
|
|
Err(env) => Error::from_envelope(env).into_response(),
|
|
}
|
|
} else {
|
|
match st.service.complete(&req).await {
|
|
Ok(resp) => {
|
|
let msg = &resp.choices[0].message;
|
|
let a = Accum {
|
|
content: msg.text().unwrap_or("").to_string(),
|
|
reasoning: msg.reasoning_content.clone().unwrap_or_default(),
|
|
tools: msg
|
|
.tool_calls
|
|
.clone()
|
|
.unwrap_or_default()
|
|
.into_iter()
|
|
.enumerate()
|
|
.map(|(i, t)| (i as u64, t))
|
|
.collect(),
|
|
usage: Some(resp.usage.clone()),
|
|
};
|
|
persist_assistant(&store, &id, &a, resp.usage.prompt_tokens).await;
|
|
Json(resp).into_response()
|
|
}
|
|
Err(env) => Error::from_envelope(env).into_response(),
|
|
}
|
|
}
|
|
}
|
|
|
|
async fn persist_assistant(store: &Arc<dyn Store>, sid: &str, a: &Accum, prompt_len: u32) {
|
|
let tool_json = if a.tools.is_empty() {
|
|
None
|
|
} else {
|
|
serde_json::to_string(&a.tools.values().collect::<Vec<_>>()).ok()
|
|
};
|
|
let (pt, ct) = a
|
|
.usage
|
|
.as_ref()
|
|
.map(|u| (u.prompt_tokens, u.completion_tokens))
|
|
.unwrap_or((prompt_len, 0));
|
|
let content = a.content.clone();
|
|
let reasoning = if a.reasoning.is_empty() {
|
|
None
|
|
} else {
|
|
Some(a.reasoning.clone())
|
|
};
|
|
let sid = sid.to_string();
|
|
let store = store.clone();
|
|
let _ = tokio::task::spawn_blocking(move || {
|
|
store.append_message(
|
|
&sid,
|
|
NewMessage {
|
|
role: "assistant",
|
|
content: &content,
|
|
reasoning_content: reasoning.as_deref(),
|
|
tool_calls_json: tool_json.as_deref(),
|
|
tool_call_id: None,
|
|
prompt_tokens: pt,
|
|
completion_tokens: ct,
|
|
},
|
|
)
|
|
})
|
|
.await;
|
|
}
|