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:
adm committed 2026-11-25 17:01:06 +01:00
1 parent ebbd9e72e8
commit 5117ecad7a
5 files changed
+259 -40

No files matched your search

+121 -18
View File
@@ -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
);
}
}