From 5117ecad7ae1c6cbd6ecafab9e411e54f4b2decf Mon Sep 17 00:00:00 2001 From: iz0eyj Date: Wed, 25 Nov 2026 17:01:06 +0100 Subject: [PATCH] feat(agent): tools on by default, personal-folder cwd, streamed final answer MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - GUI: agent mode (tools) enabled by default; the πŸ€– toggle still turns it off. - shell_exec defaults to the session's personal folder (~/.strata-ctl/sessions/) when the model omits cwd, so the agent's home base matches its identity reminder; full host access retained (cd / absolute paths). run_loop gains a LoopContext (runner/store/default_cwd/max_iters/progress) to stay within the arg-count lint. - Agent final answer now streams live: the model step uses service.stream, emits AgentEvent::Delta (reasoning + content) while generating, and returns the accumulated response for tool detection + persistence. The GUI renders a live assistant bubble (thinking auto-opens, folds when the answer starts) instead of receiving the whole final answer at once. - Verified live: 76 delta events over 10.75s, pwd -> sessions/, correct answer. - 122 tests + 2 ignored; clippy/fmt clean. --- README.md | 23 ++++---- src/agent/mod.rs | 139 ++++++++++++++++++++++++++++++++++++++------ src/agent/shell.rs | 5 +- src/api/sessions.rs | 74 ++++++++++++++++++++--- web/assets/app.js | 58 +++++++++++++++++- 5 files changed, 259 insertions(+), 40 deletions(-) diff --git a/README.md b/README.md index 05d685a..7e1406e 100644 --- a/README.md +++ b/README.md @@ -144,20 +144,23 @@ copied into `data/` once on first run (the original is left in place). ## 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**. +The GUI model can **act**, not just chat. Tools are **on by default** (the πŸ€– button +toggles them): the framework is meant to act, not just chat. The agent has 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 β€” `delta` (the model's thinking and final +answer, token by token), `tool_call` / `tool_result` (every command and its output +inline) and `final` β€” so the wait is always visible progress, **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. + `bash -lc`, starting in the session's **personal folder** by default (override with + `cwd`), with 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 @@ -229,7 +232,7 @@ later adaptation round. ## Status -Working and tested (121 tests, plus 2 real-file tests run on demand). Text, images, +Working and tested (122 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, **file/image upload**) and **agent mode** (the model using `shell_exec` on the host) have been validated live against the real Inkling diff --git a/src/agent/mod.rs b/src/agent/mod.rs index 9f4045b..ae31280 100644 --- a/src/agent/mod.rs +++ b/src/agent/mod.rs @@ -43,6 +43,13 @@ pub enum AgentEvent { name: String, output: String, }, + /// Incremental model output (reasoning / answer text) while a step generates, + /// so the GUI streams the agent's thinking and final answer live instead of + /// receiving the whole answer at once. + Delta { + content: Option, + reasoning: Option, + }, Final { response: ChatResponse, }, @@ -58,7 +65,12 @@ fn emit(progress: &Option>, ev: AgentEvent) { } /// Execute one tool call, returning the text the model reads as the tool result. -async fn execute_tool(runner: &Arc, tc: &ToolCall) -> String { +/// `default_cwd` (the session's personal folder) is used when the model omits cwd. +async fn execute_tool( + runner: &Arc, + tc: &ToolCall, + default_cwd: Option<&str>, +) -> String { if tc.function.name != "shell_exec" { return format!("error: unknown tool '{}'", tc.function.name); } @@ -70,10 +82,8 @@ async fn execute_tool(runner: &Arc, tc: &ToolCall) -> String { Ok(r) => r, Err(e) => return format!("error: {e}"), }; - match runner - .run(&req.command, req.cwd.as_deref(), req.timeout) - .await - { + let cwd = req.cwd.as_deref().or(default_cwd); + match runner.run(&req.command, cwd, req.timeout).await { Ok(out) => out.to_result_text(), Err(e) => format!("error: {e}"), } @@ -114,6 +124,17 @@ fn envelope(msg: impl Into, code: &str) -> ApiErrorEnvelope { ApiErrorEnvelope::new(msg, "invalid_request_error", Some(code.to_string())) } +/// The fixed context of one agent loop: execution runner, persistence, the +/// session's personal folder (default cwd), the iteration cap and the progress +/// channel. Bundled so `run_loop` stays within the argument-count lint. +pub struct LoopContext { + pub runner: Arc, + pub store: Arc, + pub default_cwd: Option, + pub max_iters: usize, + pub progress: Option>, +} + /// 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. @@ -122,17 +143,21 @@ fn envelope(msg: impl Into, code: &str) -> ApiErrorEnvelope { /// supplies `req` already carrying the agent tool declarations. pub async fn run_loop( mut model: M, - runner: Arc, - store: Arc, + ctx: LoopContext, session_id: &str, mut req: ChatRequest, - max_iters: usize, - progress: Option>, ) -> Result where M: FnMut(ChatRequest) -> Fut, Fut: Future>, { + let LoopContext { + runner, + store, + default_cwd, + max_iters, + progress, + } = ctx; for _ in 0..max_iters { let resp = model(req.clone()).await?; let choice = resp @@ -193,7 +218,7 @@ where arguments: tc.function.arguments.clone(), }, ); - let output = execute_tool(&runner, tc).await; + let output = execute_tool(&runner, tc, default_cwd.as_deref()).await; emit( &progress, AgentEvent::ToolResult { @@ -345,12 +370,15 @@ mod tests { let resp = run_loop( model, - runner, - store.clone(), + LoopContext { + runner, + store: store.clone(), + default_cwd: None, + max_iters: 8, + progress: Some(tx), + }, &sess.id, base_req(), - 8, - Some(tx), ) .await .unwrap(); @@ -374,6 +402,7 @@ mod tests { kinds.push(match ev { AgentEvent::ToolCall { .. } => "call", AgentEvent::ToolResult { .. } => "result", + AgentEvent::Delta { .. } => "delta", AgentEvent::Final { .. } => "final", AgentEvent::Error { .. } => "error", }); @@ -394,9 +423,20 @@ mod tests { 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(); + let err = run_loop( + model, + LoopContext { + runner, + store, + default_cwd: None, + max_iters: 3, + progress: None, + }, + &sess.id, + base_req(), + ) + .await + .unwrap_err(); assert_eq!(err.error.code.as_deref(), Some("agent_step_limit")); } @@ -411,7 +451,70 @@ mod tests { arguments: "{}".into(), }, }; - let out = execute_tool(&runner, &tc).await; + let out = execute_tool(&runner, &tc, None).await; assert!(out.contains("unknown tool")); } + + #[tokio::test] + async fn default_cwd_is_used_when_model_omits_it() { + let store: Arc = Arc::new(SqliteStore::open_in_memory().unwrap()); + let sess = store + .create_session( + "Agent", + "test-model", + &crate::store::SessionSettings::default(), + ) + .unwrap(); + let runner: Arc = Arc::new(HostShell); + // Model asks for `pwd` with no cwd, then finishes. + 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(response( + ChatMessage { + role: Role::Assistant, + content: None, + tool_call_id: None, + tool_calls: Some(vec![ToolCall { + id: "c1".into(), + kind: "function".into(), + function: FunctionCall { + name: "shell_exec".into(), + arguments: json!({"command": "pwd"}).to_string(), + }, + }]), + name: None, + reasoning_content: None, + }, + FinishReason::ToolCalls, + )) + } else { + Ok(final_response()) + } + } + }; + run_loop( + model, + LoopContext { + runner, + store: store.clone(), + default_cwd: Some("/tmp".into()), + max_iters: 8, + progress: None, + }, + &sess.id, + base_req(), + ) + .await + .unwrap(); + let msgs = store.messages(&sess.id).unwrap(); + let tool = msgs.iter().find(|m| m.role == "tool").unwrap(); + assert!( + tool.content.contains("/tmp"), + "pwd should run in the default cwd: {}", + tool.content + ); + } } diff --git a/src/agent/shell.rs b/src/agent/shell.rs index 54a295c..b0a401e 100644 --- a/src/agent/shell.rs +++ b/src/agent/shell.rs @@ -168,8 +168,9 @@ pub fn shell_exec_declaration() -> Json { "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.", + && or ;. Commands start in your personal session folder by default. State \ + (working directory, environment) does NOT persist between calls: pass cwd or \ + use absolute paths.", "parameters": { "type": "object", "properties": { diff --git a/src/api/sessions.rs b/src/api/sessions.rs index 424a93e..71acb0b 100644 --- a/src/api/sessions.rs +++ b/src/api/sessions.rs @@ -16,7 +16,10 @@ use futures::StreamExt; use serde::Deserialize; use super::routes::{AppState, Error}; -use super::types::{ChatChunk, ChatMessage, ChatRequest, FunctionCall, Role, ToolCall, Usage}; +use super::types::{ + completion_id, now_unix, ChatChunk, ChatMessage, ChatRequest, ChatResponse, Choice, + FinishReason, FunctionCall, Role, ToolCall, Usage, +}; use super::uploads; use crate::agent::shell::{HostShell, ShellRunner}; use crate::agent::{self, AgentEvent}; @@ -433,22 +436,79 @@ pub(crate) async fn session_chat( let svc = st.service.clone(); let store2 = store.clone(); let sid = id.clone(); + let folder = sess.folder.clone(); + let tx_model = tx.clone(); tokio::spawn(async move { + // Streaming model step: emit Delta events while generating (so the GUI + // shows thinking + final answer live), then return the accumulated + // response for the loop's tool detection and persistence. let model = move |r: ChatRequest| { let svc = svc.clone(); - async move { svc.complete(&r).await } + let tx = tx_model.clone(); + async move { + let (mut stream, prompt_len) = svc.stream(&r).await?; + let mut acc = Accum::default(); + let mut finish = FinishReason::Stop; + while let Some(chunk) = stream.next().await { + if let Some(ch) = chunk.choices.first() { + let d = &ch.delta; + if d.content.is_some() || d.reasoning_content.is_some() { + let _ = tx.send(AgentEvent::Delta { + content: d.content.clone(), + reasoning: d.reasoning_content.clone(), + }); + } + if let Some(f) = &ch.finish_reason { + finish = *f; + } + } + accumulate(&mut acc, &chunk); + } + let tools: Vec = acc.tools.values().cloned().collect(); + let has_tools = !tools.is_empty(); + let usage = acc.usage.unwrap_or_else(|| Usage::new(prompt_len, 0)); + Ok(ChatResponse { + id: completion_id(), + object: "chat.completion", + created: now_unix(), + model: r.model.clone(), + choices: vec![Choice { + index: 0, + message: ChatMessage { + role: Role::Assistant, + content: (!acc.content.is_empty()) + .then_some(serde_json::Value::String(acc.content)), + tool_call_id: None, + tool_calls: has_tools.then_some(tools), + name: None, + reasoning_content: (!acc.reasoning.is_empty()) + .then_some(acc.reasoning), + }, + finish_reason: if has_tools { + FinishReason::ToolCalls + } else { + finish + }, + }], + usage, + }) + } }; // Base mode: the host shell. Isolated mode will swap in a Docker-MCP - // runner behind the same ShellRunner seam. + // runner behind the same ShellRunner seam. Commands default to the + // session's personal folder (its home base). let runner: Arc = Arc::new(HostShell); if let Err(env) = agent::run_loop( model, - runner, - store2, + agent::LoopContext { + runner, + store: store2, + default_cwd: folder, + max_iters: agent::MAX_ITERS, + progress: Some(tx.clone()), + }, &sid, req, - agent::MAX_ITERS, - Some(tx.clone()), ) .await { diff --git a/web/assets/app.js b/web/assets/app.js index 81413dc..02d13de 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, agent: false, attachments: [] }; +const state = { sessions: [], current: null, busy: false, agent: true, attachments: [] }; // ---- i18n: new user-facing strings go through t(key, params) -------------- // Catalogs are served at /assets/locales/.json; language follows the @@ -405,6 +405,30 @@ async function agentTurn(content, t, attachments) { const dec = new TextDecoder(); let buf = ""; const toolNodes = {}; + let live = null; // the assistant bubble currently being streamed + + function ensureLive() { + if (live) return live; + const wrap = el("div", "msg assistant"); + wrap.appendChild(el("div", "role", "Assistente")); + const bubble = el("div", "bubble"); + const det = el("details", "thinking"); + det.appendChild(el("summary", null, "Pensiero")); + const reasoningNode = el("div", "reasoning", ""); + det.appendChild(reasoningNode); + det.hidden = true; + const contentNode = el("div", "content", ""); + bubble.appendChild(det); + bubble.appendChild(contentNode); + wrap.appendChild(bubble); + t.appendChild(wrap); + live = { bubble, det, reasoningNode, contentNode, reasoning: "", text: "" }; + return live; + } + function closeLive() { + if (live) { live.det.open = false; live = null; } + } + for (;;) { const { done, value } = await reader.read(); if (done) break; @@ -419,7 +443,21 @@ async function agentTurn(content, t, attachments) { if (data === "[DONE]") return; let ev; try { ev = JSON.parse(data); } catch { continue; } - if (ev.type === "tool_call") { + if (ev.type === "delta") { + const L = ensureLive(); + if (ev.reasoning) { + L.reasoning += ev.reasoning; + L.reasoningNode.textContent = L.reasoning; + L.det.hidden = false; + L.det.open = true; + } + if (ev.content) { + if (!L.text) L.det.open = false; + L.text += ev.content; + L.contentNode.textContent = L.text; + } + } else if (ev.type === "tool_call") { + closeLive(); const n = toolCallNode(ev.name, ev.arguments); toolNodes[ev.id] = n; t.appendChild(n); @@ -427,9 +465,19 @@ async function agentTurn(content, t, attachments) { const n = toolNodes[ev.id]; if (n) n._out.textContent = ev.output; } else if (ev.type === "final") { + const L = ensureLive(); const m = ev.response.choices[0].message; - t.appendChild(messageNode("assistant", m.content || "", m.reasoning_content, usageText(ev.response.usage))); + if (!L.text && m.content) { L.text = m.content; L.contentNode.textContent = m.content; } + if (!L.reasoning && m.reasoning_content) { + L.reasoning = m.reasoning_content; + L.reasoningNode.textContent = m.reasoning; + L.det.hidden = false; + } + L.det.open = false; + if (ev.response.usage) L.bubble.appendChild(el("div", "usage", usageText(ev.response.usage))); + live = null; } else if (ev.type === "error") { + closeLive(); t.appendChild(messageNode("assistant", `Errore agent: ${ev.message}`)); } scrollDown(); @@ -652,6 +700,10 @@ function wire() { b.classList.toggle("active", state.agent); b.setAttribute("aria-pressed", String(state.agent)); }); + // Tools are on by default: the framework is meant to act, not just chat. + const ab = $("#agent-toggle"); + ab.classList.toggle("active", state.agent); + ab.setAttribute("aria-pressed", String(state.agent)); $("#show-stats").addEventListener("click", showStats); $("#close-stats").addEventListener("click", () => { $("#stats-modal").hidden = true; }); $("#show-settings").addEventListener("click", () => openSettings("session"));