feat(agent): tools on by default, personal-folder cwd, streamed final answer
- 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/<name>)
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/<name>, correct answer.
- 122 tests + 2 ignored; clippy/fmt clean.
This commit is contained in:
1 parent
ebbd9e72e8
commit
5117ecad7a
5 files changed
+259
-40
No files matched your search
+121
-18
@@ -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<String>,
|
||||
reasoning: Option<String>,
|
||||
},
|
||||
Final {
|
||||
response: ChatResponse,
|
||||
},
|
||||
@@ -58,7 +65,12 @@ fn emit(progress: &Option<UnboundedSender<AgentEvent>>, ev: AgentEvent) {
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
/// `default_cwd` (the session's personal folder) is used when the model omits cwd.
|
||||
async fn execute_tool(
|
||||
runner: &Arc<dyn ShellRunner>,
|
||||
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<dyn ShellRunner>, 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<String>, 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<dyn ShellRunner>,
|
||||
pub store: Arc<dyn Store>,
|
||||
pub default_cwd: Option<String>,
|
||||
pub max_iters: usize,
|
||||
pub progress: Option<UnboundedSender<AgentEvent>>,
|
||||
}
|
||||
|
||||
/// 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<String>, code: &str) -> ApiErrorEnvelope {
|
||||
/// 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>,
|
||||
ctx: LoopContext,
|
||||
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>>,
|
||||
{
|
||||
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<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();
|
||||
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<dyn Store> = Arc::new(SqliteStore::open_in_memory().unwrap());
|
||||
let sess = store
|
||||
.create_session(
|
||||
"Agent",
|
||||
"test-model",
|
||||
&crate::store::SessionSettings::default(),
|
||||
)
|
||||
.unwrap();
|
||||
let runner: Arc<dyn ShellRunner> = 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
|
||||
);
|
||||
}
|
||||
}
|
||||
+3
-2
@@ -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": {
|
||||
|
||||
+67
-7
@@ -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<ToolCall> = 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<dyn ShellRunner> = 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
|
||||
{
|
||||
|
||||
Reference in new issue
Block a user