feat: Agent-Loop mit Tools und Fehlerklassen
agent.rs: fünf Tools (read_file, write_file, list_dir, run_shell, done), Pfadprüfung auf /work, Fehlerklassen nach SPEC 5, Schleifenerkennung, Limits für Schritte und Zeit, Metriken. Ollama-Client über /api/chat. 31 Unit-Tests mit Mock-Modell grün; Werkzeuge gegen echte Sandbox grün. Echter Modelllauf steht aus, weil Ollama nicht läuft und keine Modelle da sind. Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
This commit is contained in:
774
src-tauri/src/agent.rs
Normal file
774
src-tauri/src/agent.rs
Normal file
@ -0,0 +1,774 @@
|
||||
//! Agent-Loop (F-03, SPEC Abschnitt 5).
|
||||
//!
|
||||
//! Das Modell bekommt die Aufgabe und fünf Tools. Antwortet es mit Tool-Calls,
|
||||
//! werden sie ausgeführt und die Ergebnisse zurückgegeben. Der Lauf endet bei
|
||||
//! `done`, bei einer Antwort ohne Tool-Calls, bei Limits oder bei einem Fehler,
|
||||
//! der nach der Spec den Lauf beendet.
|
||||
//!
|
||||
//! Modell und Workspace sind Traits, damit der Loop ohne Ollama und ohne Podman
|
||||
//! testbar ist. Die echten Implementierungen sind `OllamaClient` und
|
||||
//! `SandboxWorkspace`.
|
||||
|
||||
use crate::sandbox::Sandbox;
|
||||
use base64::Engine;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{json, Value};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
pub const WORK_DIR: &str = "/work";
|
||||
pub const MAX_TOOL_OUTPUT_CHARS: usize = 20_000;
|
||||
pub const SHELL_TIMEOUT: Duration = Duration::from_secs(60);
|
||||
pub const LOOP_REPEATS: u32 = 3;
|
||||
|
||||
pub const SYSTEM_PROMPT: &str = "Du bist ein Coding-Agent. Dein Arbeitsverzeichnis ist /work. \
|
||||
Du hast die Werkzeuge read_file, write_file, list_dir und run_shell. \
|
||||
Wenn du fertig bist, rufe das Werkzeug done mit einer kurzen Zusammenfassung auf.";
|
||||
|
||||
/// Fehlerklassen eines Laufs (SPEC 5).
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum ErrorClass {
|
||||
Ok,
|
||||
InvalidToolJson,
|
||||
UnknownTool,
|
||||
BadArgs,
|
||||
LoopDetected,
|
||||
MaxSteps,
|
||||
Timeout,
|
||||
EndpointError,
|
||||
CheckFailed,
|
||||
}
|
||||
|
||||
/// Eine Nachricht im Verlauf (Ollama-Format).
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Message {
|
||||
pub role: String,
|
||||
#[serde(default, skip_serializing_if = "String::is_empty")]
|
||||
pub content: String,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub tool_calls: Vec<ToolCall>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub tool_name: Option<String>,
|
||||
}
|
||||
|
||||
impl Message {
|
||||
pub fn new(role: &str, content: &str) -> Message {
|
||||
Message {
|
||||
role: role.into(),
|
||||
content: content.into(),
|
||||
tool_calls: vec![],
|
||||
tool_name: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
pub struct ToolCall {
|
||||
pub function: FunctionCall,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
pub struct FunctionCall {
|
||||
pub name: String,
|
||||
pub arguments: Value,
|
||||
}
|
||||
|
||||
/// Antwort eines Modells mit Token-Zählern.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct ChatResponse {
|
||||
pub message: Message,
|
||||
pub prompt_tokens: u32,
|
||||
pub completion_tokens: u32,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum ModelError {
|
||||
Timeout,
|
||||
Endpoint(String),
|
||||
}
|
||||
|
||||
/// Ein Chat-Modell. Die Implementierung entscheidet, wie es erreicht wird.
|
||||
pub trait ModelClient {
|
||||
fn chat(&self, messages: &[Message], tools: &Value, timeout: Duration)
|
||||
-> Result<ChatResponse, ModelError>;
|
||||
}
|
||||
|
||||
/// Die Arbeitsumgebung der Tools. In der App ist das die Sandbox, in Tests eine Attrappe.
|
||||
pub trait Workspace {
|
||||
fn read_file(&self, path: &str) -> Result<String, String>;
|
||||
fn write_file(&self, path: &str, content: &str) -> Result<(), String>;
|
||||
fn list_dir(&self, path: &str) -> Result<String, String>;
|
||||
/// Liefert Ausgabe und Exit-Code als Text, oder einen Fehler bei Problemen mit dem Befehl selbst.
|
||||
fn run_shell(&self, command: &str) -> Result<String, String>;
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct AgentLimits {
|
||||
pub max_steps: u32,
|
||||
pub timeout: Duration,
|
||||
}
|
||||
|
||||
/// Ergebnis eines Agentenlaufs, vor der Bewertung durch `check.sh`.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct RunOutcome {
|
||||
pub class: ErrorClass,
|
||||
pub summary: Option<String>,
|
||||
pub steps: u32,
|
||||
pub prompt_tokens: u32,
|
||||
pub completion_tokens: u32,
|
||||
pub duration_ms: u128,
|
||||
pub time_to_first_tool_ms: Option<u128>,
|
||||
pub transcript: Vec<Message>,
|
||||
}
|
||||
|
||||
/// Werkzeug-Schema für Ollama.
|
||||
pub fn tool_schemas() -> Value {
|
||||
json!([
|
||||
tool("read_file", "Liest eine Datei unter /work.", json!({
|
||||
"path": {"type": "string", "description": "Pfad, relativ zu /work oder absolut unter /work"}
|
||||
}), &["path"]),
|
||||
tool("write_file", "Schreibt eine Datei unter /work, legt sie bei Bedarf an.", json!({
|
||||
"path": {"type": "string", "description": "Pfad unter /work"},
|
||||
"content": {"type": "string", "description": "Neuer Inhalt der Datei"}
|
||||
}), &["path", "content"]),
|
||||
tool("list_dir", "Listet Einträge eines Ordners unter /work mit Typ (d = Ordner, f = Datei).", json!({
|
||||
"path": {"type": "string", "description": "Ordner unter /work"}
|
||||
}), &["path"]),
|
||||
tool("run_shell", "Führt einen Shell-Befehl in /work aus (60 s Limit).", json!({
|
||||
"command": {"type": "string", "description": "Shell-Befehl"}
|
||||
}), &["command"]),
|
||||
tool("done", "Beendet den Lauf. Rufe es auf, wenn die Aufgabe erledigt ist.", json!({
|
||||
"summary": {"type": "string", "description": "Kurze Zusammenfassung"}
|
||||
}), &["summary"]),
|
||||
])
|
||||
}
|
||||
|
||||
fn tool(name: &str, description: &str, properties: Value, required: &[&str]) -> Value {
|
||||
json!({
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": name,
|
||||
"description": description,
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": properties,
|
||||
"required": required,
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Prüft einen Pfad und gibt den absoluten Pfad unter `/work` zurück.
|
||||
/// Erlaubt sind relative Pfade und absolute Pfade unter `/work`. `..` ist verboten.
|
||||
pub fn resolve_work_path(path: &str) -> Result<String, String> {
|
||||
let trimmed = path.trim();
|
||||
if trimmed.is_empty() {
|
||||
return Err("Pfad ist leer".into());
|
||||
}
|
||||
if trimmed.contains('\0') {
|
||||
return Err("Pfad enthält ein Nullbyte".into());
|
||||
}
|
||||
let rel = if let Some(rest) = trimmed.strip_prefix(WORK_DIR) {
|
||||
if !(rest.is_empty() || rest.starts_with('/')) {
|
||||
return Err(format!("Pfad liegt außerhalb von {WORK_DIR}"));
|
||||
}
|
||||
rest
|
||||
} else if trimmed.starts_with('/') {
|
||||
return Err(format!("Pfad liegt außerhalb von {WORK_DIR}"));
|
||||
} else {
|
||||
trimmed
|
||||
};
|
||||
let mut parts = Vec::new();
|
||||
for comp in rel.split('/') {
|
||||
match comp {
|
||||
"" | "." => {}
|
||||
".." => return Err("Pfad darf kein .. enthalten".into()),
|
||||
c => parts.push(c),
|
||||
}
|
||||
}
|
||||
if parts.is_empty() {
|
||||
Ok(WORK_DIR.into())
|
||||
} else {
|
||||
Ok(format!("{WORK_DIR}/{}", parts.join("/")))
|
||||
}
|
||||
}
|
||||
|
||||
fn truncate(text: &str) -> String {
|
||||
if text.chars().count() <= MAX_TOOL_OUTPUT_CHARS {
|
||||
return text.to_string();
|
||||
}
|
||||
let head: String = text.chars().take(MAX_TOOL_OUTPUT_CHARS).collect();
|
||||
format!("{head}\n[... gekürzt, {} Zeichen insgesamt]", text.chars().count())
|
||||
}
|
||||
|
||||
/// Fehler, die den Lauf beenden (Tool-Name unbekannt, Argumente kaputt).
|
||||
enum Fatal {
|
||||
Class(ErrorClass),
|
||||
}
|
||||
|
||||
/// Holt die Argumente als Objekt. Manche Modelle liefern sie als JSON-Text.
|
||||
fn arguments_object(v: &Value) -> Result<serde_json::Map<String, Value>, Fatal> {
|
||||
match v {
|
||||
Value::Object(m) => Ok(m.clone()),
|
||||
Value::String(s) => match serde_json::from_str::<Value>(s) {
|
||||
Ok(Value::Object(m)) => Ok(m),
|
||||
_ => Err(Fatal::Class(ErrorClass::InvalidToolJson)),
|
||||
},
|
||||
Value::Null => Ok(serde_json::Map::new()),
|
||||
_ => Err(Fatal::Class(ErrorClass::InvalidToolJson)),
|
||||
}
|
||||
}
|
||||
|
||||
fn required_str(args: &serde_json::Map<String, Value>, key: &str) -> Result<String, Fatal> {
|
||||
match args.get(key) {
|
||||
Some(Value::String(s)) => Ok(s.clone()),
|
||||
_ => Err(Fatal::Class(ErrorClass::BadArgs)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Führt einen Tool-Call aus. Gibt das Ergebnis als Text zurück, oder einen Fatal-Fehler.
|
||||
/// `done` gibt `Ok(Err(summary))`-artig über `Done` zurück.
|
||||
enum Step {
|
||||
Result(String),
|
||||
Done(String),
|
||||
}
|
||||
|
||||
fn execute(call: &FunctionCall, ws: &dyn Workspace) -> Result<Step, Fatal> {
|
||||
let args = arguments_object(&call.arguments)?;
|
||||
match call.name.as_str() {
|
||||
"read_file" => {
|
||||
let path = required_str(&args, "path")?;
|
||||
Ok(Step::Result(match resolve_work_path(&path) {
|
||||
Err(e) => format!("Fehler: {e}"),
|
||||
Ok(p) => match ws.read_file(&p) {
|
||||
Ok(text) => truncate(&text),
|
||||
Err(e) => format!("Fehler: {e}"),
|
||||
},
|
||||
}))
|
||||
}
|
||||
"write_file" => {
|
||||
let path = required_str(&args, "path")?;
|
||||
let content = required_str(&args, "content")?;
|
||||
Ok(Step::Result(match resolve_work_path(&path) {
|
||||
Err(e) => format!("Fehler: {e}"),
|
||||
Ok(p) => match ws.write_file(&p, &content) {
|
||||
Ok(()) => format!("geschrieben: {p}"),
|
||||
Err(e) => format!("Fehler: {e}"),
|
||||
},
|
||||
}))
|
||||
}
|
||||
"list_dir" => {
|
||||
let path = required_str(&args, "path")?;
|
||||
Ok(Step::Result(match resolve_work_path(&path) {
|
||||
Err(e) => format!("Fehler: {e}"),
|
||||
Ok(p) => match ws.list_dir(&p) {
|
||||
Ok(text) => truncate(&text),
|
||||
Err(e) => format!("Fehler: {e}"),
|
||||
},
|
||||
}))
|
||||
}
|
||||
"run_shell" => {
|
||||
let command = required_str(&args, "command")?;
|
||||
Ok(Step::Result(match ws.run_shell(&command) {
|
||||
Ok(out) => truncate(&out),
|
||||
Err(e) => format!("Fehler: {e}"),
|
||||
}))
|
||||
}
|
||||
"done" => {
|
||||
let summary = required_str(&args, "summary")?;
|
||||
Ok(Step::Done(summary))
|
||||
}
|
||||
_ => Err(Fatal::Class(ErrorClass::UnknownTool)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Führt den Agenten-Loop aus.
|
||||
pub fn run_agent(
|
||||
model: &dyn ModelClient,
|
||||
ws: &dyn Workspace,
|
||||
prompt: &str,
|
||||
limits: &AgentLimits,
|
||||
) -> RunOutcome {
|
||||
let started = Instant::now();
|
||||
let tools = tool_schemas();
|
||||
let mut messages = vec![Message::new("system", SYSTEM_PROMPT), Message::new("user", prompt)];
|
||||
|
||||
let mut out = RunOutcome {
|
||||
class: ErrorClass::Ok,
|
||||
summary: None,
|
||||
steps: 0,
|
||||
prompt_tokens: 0,
|
||||
completion_tokens: 0,
|
||||
duration_ms: 0,
|
||||
time_to_first_tool_ms: None,
|
||||
transcript: vec![],
|
||||
};
|
||||
|
||||
// Letzter Tool-Call und Anzahl gleicher Wiederholungen mit gleichem Ergebnis.
|
||||
let mut last: Option<(String, Value, String)> = None;
|
||||
let mut repeats: u32 = 0;
|
||||
|
||||
let class = loop {
|
||||
if out.steps >= limits.max_steps {
|
||||
break ErrorClass::MaxSteps;
|
||||
}
|
||||
let elapsed = started.elapsed();
|
||||
if elapsed >= limits.timeout {
|
||||
break ErrorClass::Timeout;
|
||||
}
|
||||
out.steps += 1;
|
||||
|
||||
let resp = match model.chat(&messages, &tools, limits.timeout - elapsed) {
|
||||
Ok(r) => r,
|
||||
Err(ModelError::Timeout) => break ErrorClass::Timeout,
|
||||
Err(ModelError::Endpoint(_)) => break ErrorClass::EndpointError,
|
||||
};
|
||||
out.prompt_tokens += resp.prompt_tokens;
|
||||
out.completion_tokens += resp.completion_tokens;
|
||||
messages.push(resp.message.clone());
|
||||
|
||||
// Keine Tool-Calls: implizites Ende.
|
||||
if resp.message.tool_calls.is_empty() {
|
||||
out.summary = Some(resp.message.content.clone());
|
||||
break ErrorClass::Ok;
|
||||
}
|
||||
|
||||
let mut finished = None;
|
||||
for call in &resp.message.tool_calls {
|
||||
if out.time_to_first_tool_ms.is_none() {
|
||||
out.time_to_first_tool_ms = Some(started.elapsed().as_millis());
|
||||
}
|
||||
match execute(&call.function, ws) {
|
||||
Err(Fatal::Class(c)) => {
|
||||
finished = Some(c);
|
||||
break;
|
||||
}
|
||||
Ok(Step::Done(summary)) => {
|
||||
finished = Some(ErrorClass::Ok);
|
||||
out.summary = Some(summary);
|
||||
break;
|
||||
}
|
||||
Ok(Step::Result(result)) => {
|
||||
let key = (
|
||||
call.function.name.clone(),
|
||||
call.function.arguments.clone(),
|
||||
result.clone(),
|
||||
);
|
||||
if last.as_ref() == Some(&key) {
|
||||
repeats += 1;
|
||||
} else {
|
||||
repeats = 1;
|
||||
}
|
||||
last = Some(key);
|
||||
if repeats >= LOOP_REPEATS {
|
||||
finished = Some(ErrorClass::LoopDetected);
|
||||
break;
|
||||
}
|
||||
messages.push(Message {
|
||||
role: "tool".into(),
|
||||
content: result,
|
||||
tool_calls: vec![],
|
||||
tool_name: Some(call.function.name.clone()),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(c) = finished {
|
||||
break c;
|
||||
}
|
||||
};
|
||||
|
||||
out.class = class;
|
||||
out.duration_ms = started.elapsed().as_millis();
|
||||
out.transcript = messages;
|
||||
out
|
||||
}
|
||||
|
||||
/// Workspace auf einer laufenden Sandbox. Dateioperationen laufen als Shell-Befehle im Container.
|
||||
pub struct SandboxWorkspace<'a> {
|
||||
pub sandbox: &'a Sandbox,
|
||||
}
|
||||
|
||||
fn sh_quote(s: &str) -> String {
|
||||
format!("'{}'", s.replace('\'', "'\\''"))
|
||||
}
|
||||
|
||||
impl Workspace for SandboxWorkspace<'_> {
|
||||
fn read_file(&self, path: &str) -> Result<String, String> {
|
||||
let out = self
|
||||
.sandbox
|
||||
.exec(&format!("cat -- {}", sh_quote(path)), SHELL_TIMEOUT)?;
|
||||
if out.exit_code == Some(0) {
|
||||
Ok(out.stdout)
|
||||
} else {
|
||||
Err(first_line(&out.stderr, out.exit_code))
|
||||
}
|
||||
}
|
||||
|
||||
fn write_file(&self, path: &str, content: &str) -> Result<(), String> {
|
||||
let encoded = base64::engine::general_purpose::STANDARD.encode(content);
|
||||
let parent = match path.rfind('/') {
|
||||
Some(0) | None => WORK_DIR,
|
||||
Some(i) => &path[..i],
|
||||
};
|
||||
let cmd = format!(
|
||||
"mkdir -p -- {} && printf %s {} | base64 -d > {}",
|
||||
sh_quote(parent),
|
||||
sh_quote(&encoded),
|
||||
sh_quote(path)
|
||||
);
|
||||
let out = self.sandbox.exec(&cmd, SHELL_TIMEOUT)?;
|
||||
if out.exit_code == Some(0) {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(first_line(&out.stderr, out.exit_code))
|
||||
}
|
||||
}
|
||||
|
||||
fn list_dir(&self, path: &str) -> Result<String, String> {
|
||||
let cmd = format!(
|
||||
"find {} -mindepth 1 -maxdepth 1 -printf '%y %f\\n' | sort",
|
||||
sh_quote(path)
|
||||
);
|
||||
let out = self.sandbox.exec(&cmd, SHELL_TIMEOUT)?;
|
||||
if out.exit_code == Some(0) {
|
||||
Ok(if out.stdout.is_empty() { "(leer)".into() } else { out.stdout })
|
||||
} else {
|
||||
Err(first_line(&out.stderr, out.exit_code))
|
||||
}
|
||||
}
|
||||
|
||||
fn run_shell(&self, command: &str) -> Result<String, String> {
|
||||
let out = self.sandbox.exec(command, SHELL_TIMEOUT)?;
|
||||
if out.timed_out {
|
||||
return Ok(format!("Befehl nach {} s abgebrochen.", SHELL_TIMEOUT.as_secs()));
|
||||
}
|
||||
let code = out.exit_code.map_or("?".to_string(), |c| c.to_string());
|
||||
Ok(format!(
|
||||
"exit {code}\n{}{}",
|
||||
out.stdout,
|
||||
if out.stderr.is_empty() {
|
||||
String::new()
|
||||
} else {
|
||||
format!("\nstderr:\n{}", out.stderr)
|
||||
}
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
fn first_line(stderr: &str, code: Option<i32>) -> String {
|
||||
let line = stderr.lines().next().unwrap_or("").trim();
|
||||
if line.is_empty() {
|
||||
format!("Exit {}", code.map_or("?".into(), |c| c.to_string()))
|
||||
} else {
|
||||
line.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
/// Modell über die Ollama-API `/api/chat` (ohne Streaming).
|
||||
pub struct OllamaClient {
|
||||
pub base_url: String,
|
||||
pub model: String,
|
||||
http: reqwest::blocking::Client,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct OllamaResponse {
|
||||
message: Message,
|
||||
#[serde(default)]
|
||||
prompt_eval_count: u32,
|
||||
#[serde(default)]
|
||||
eval_count: u32,
|
||||
}
|
||||
|
||||
impl OllamaClient {
|
||||
pub fn new(base_url: &str, model: &str) -> Result<OllamaClient, String> {
|
||||
let http = reqwest::blocking::Client::builder()
|
||||
.build()
|
||||
.map_err(|e| format!("HTTP-Client nicht baubar: {e}"))?;
|
||||
Ok(OllamaClient {
|
||||
base_url: base_url.trim_end_matches('/').into(),
|
||||
model: model.into(),
|
||||
http,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl ModelClient for OllamaClient {
|
||||
fn chat(&self, messages: &[Message], tools: &Value, timeout: Duration)
|
||||
-> Result<ChatResponse, ModelError>
|
||||
{
|
||||
let body = json!({
|
||||
"model": self.model,
|
||||
"messages": messages,
|
||||
"tools": tools,
|
||||
"stream": false,
|
||||
"options": { "temperature": 0 },
|
||||
});
|
||||
let resp = self
|
||||
.http
|
||||
.post(format!("{}/api/chat", self.base_url))
|
||||
.timeout(timeout)
|
||||
.json(&body)
|
||||
.send()
|
||||
.map_err(|e| {
|
||||
if e.is_timeout() {
|
||||
ModelError::Timeout
|
||||
} else {
|
||||
ModelError::Endpoint(e.to_string())
|
||||
}
|
||||
})?;
|
||||
if !resp.status().is_success() {
|
||||
let status = resp.status();
|
||||
let text = resp.text().unwrap_or_default();
|
||||
return Err(ModelError::Endpoint(format!("HTTP {status}: {text}")));
|
||||
}
|
||||
let parsed: OllamaResponse = resp
|
||||
.json()
|
||||
.map_err(|e| ModelError::Endpoint(format!("Antwort nicht lesbar: {e}")))?;
|
||||
Ok(ChatResponse {
|
||||
message: parsed.message,
|
||||
prompt_tokens: parsed.prompt_eval_count,
|
||||
completion_tokens: parsed.eval_count,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::cell::RefCell;
|
||||
use std::collections::{HashMap, VecDeque};
|
||||
|
||||
struct MockModel {
|
||||
script: RefCell<VecDeque<Result<ChatResponse, ModelError>>>,
|
||||
}
|
||||
|
||||
impl MockModel {
|
||||
fn new(script: Vec<Result<ChatResponse, ModelError>>) -> MockModel {
|
||||
MockModel { script: RefCell::new(script.into()) }
|
||||
}
|
||||
}
|
||||
|
||||
impl ModelClient for MockModel {
|
||||
fn chat(&self, _m: &[Message], _t: &Value, _to: Duration) -> Result<ChatResponse, ModelError> {
|
||||
self.script
|
||||
.borrow_mut()
|
||||
.pop_front()
|
||||
.unwrap_or(Err(ModelError::Endpoint("Skript leer".into())))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct MockWs {
|
||||
files: RefCell<HashMap<String, String>>,
|
||||
}
|
||||
|
||||
impl Workspace for MockWs {
|
||||
fn read_file(&self, path: &str) -> Result<String, String> {
|
||||
self.files
|
||||
.borrow()
|
||||
.get(path)
|
||||
.cloned()
|
||||
.ok_or_else(|| "No such file".to_string())
|
||||
}
|
||||
fn write_file(&self, path: &str, content: &str) -> Result<(), String> {
|
||||
self.files.borrow_mut().insert(path.into(), content.into());
|
||||
Ok(())
|
||||
}
|
||||
fn list_dir(&self, _path: &str) -> Result<String, String> {
|
||||
Ok("f a.txt".into())
|
||||
}
|
||||
fn run_shell(&self, command: &str) -> Result<String, String> {
|
||||
Ok(format!("exit 0\nran: {command}"))
|
||||
}
|
||||
}
|
||||
|
||||
fn call(name: &str, args: Value) -> ToolCall {
|
||||
ToolCall { function: FunctionCall { name: name.into(), arguments: args } }
|
||||
}
|
||||
|
||||
fn reply(calls: Vec<ToolCall>) -> Result<ChatResponse, ModelError> {
|
||||
Ok(ChatResponse {
|
||||
message: Message {
|
||||
role: "assistant".into(),
|
||||
content: String::new(),
|
||||
tool_calls: calls,
|
||||
tool_name: None,
|
||||
},
|
||||
prompt_tokens: 10,
|
||||
completion_tokens: 5,
|
||||
})
|
||||
}
|
||||
|
||||
fn limits() -> AgentLimits {
|
||||
AgentLimits { max_steps: 25, timeout: Duration::from_secs(60) }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn done_beendet_den_lauf_mit_zusammenfassung() {
|
||||
let m = MockModel::new(vec![reply(vec![call("done", json!({"summary": "fertig"}))])]);
|
||||
let out = run_agent(&m, &MockWs::default(), "Aufgabe", &limits());
|
||||
assert_eq!(out.class, ErrorClass::Ok);
|
||||
assert_eq!(out.summary.as_deref(), Some("fertig"));
|
||||
assert_eq!(out.steps, 1);
|
||||
assert_eq!(out.prompt_tokens, 10);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn datei_lesen_schreiben_und_done() {
|
||||
let ws = MockWs::default();
|
||||
let m = MockModel::new(vec![
|
||||
reply(vec![call("write_file", json!({"path": "out.txt", "content": "hi"}))]),
|
||||
reply(vec![call("read_file", json!({"path": "/work/out.txt"}))]),
|
||||
reply(vec![call("done", json!({"summary": "ok"}))]),
|
||||
]);
|
||||
let out = run_agent(&m, &ws, "Aufgabe", &limits());
|
||||
assert_eq!(out.class, ErrorClass::Ok);
|
||||
assert_eq!(ws.files.borrow().get("/work/out.txt").map(String::as_str), Some("hi"));
|
||||
assert!(out.transcript.iter().any(|m| m.role == "tool" && m.content == "hi"));
|
||||
assert!(out.time_to_first_tool_ms.is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tool_fehler_bricht_den_lauf_nicht_ab() {
|
||||
let m = MockModel::new(vec![
|
||||
reply(vec![call("read_file", json!({"path": "fehlt.txt"}))]),
|
||||
reply(vec![call("done", json!({"summary": "nichts gefunden"}))]),
|
||||
]);
|
||||
let out = run_agent(&m, &MockWs::default(), "Aufgabe", &limits());
|
||||
assert_eq!(out.class, ErrorClass::Ok);
|
||||
assert!(out.transcript.iter().any(|m| m.content.starts_with("Fehler: No such file")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unbekanntes_tool_ist_klassifiziert() {
|
||||
let m = MockModel::new(vec![reply(vec![call("fly", json!({}))])]);
|
||||
let out = run_agent(&m, &MockWs::default(), "A", &limits());
|
||||
assert_eq!(out.class, ErrorClass::UnknownTool);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fehlende_argumente_sind_bad_args() {
|
||||
let m = MockModel::new(vec![reply(vec![call("read_file", json!({}))])]);
|
||||
let out = run_agent(&m, &MockWs::default(), "A", &limits());
|
||||
assert_eq!(out.class, ErrorClass::BadArgs);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn argumente_als_kaputter_text_sind_invalid_tool_json() {
|
||||
let m = MockModel::new(vec![reply(vec![call("read_file", Value::String("{kaputt".into()))])]);
|
||||
let out = run_agent(&m, &MockWs::default(), "A", &limits());
|
||||
assert_eq!(out.class, ErrorClass::InvalidToolJson);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn argumente_als_json_text_werden_akzeptiert() {
|
||||
let ws = MockWs::default();
|
||||
ws.files.borrow_mut().insert("/work/a.txt".into(), "x".into());
|
||||
let m = MockModel::new(vec![
|
||||
reply(vec![call("read_file", Value::String("{\"path\": \"a.txt\"}".into()))]),
|
||||
reply(vec![call("done", json!({"summary": "ok"}))]),
|
||||
]);
|
||||
assert_eq!(run_agent(&m, &ws, "A", &limits()).class, ErrorClass::Ok);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gleicher_aufruf_dreimal_ist_schleife() {
|
||||
let c = || reply(vec![call("list_dir", json!({"path": "."}))]);
|
||||
let m = MockModel::new(vec![c(), c(), c(), c()]);
|
||||
let out = run_agent(&m, &MockWs::default(), "A", &limits());
|
||||
assert_eq!(out.class, ErrorClass::LoopDetected);
|
||||
assert_eq!(out.steps, 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn max_steps_endet_den_lauf() {
|
||||
let m = MockModel::new(
|
||||
(0..5).map(|i| reply(vec![call("run_shell", json!({"command": format!("echo {i}")}))])).collect(),
|
||||
);
|
||||
let lim = AgentLimits { max_steps: 2, timeout: Duration::from_secs(60) };
|
||||
let out = run_agent(&m, &MockWs::default(), "A", &lim);
|
||||
assert_eq!(out.class, ErrorClass::MaxSteps);
|
||||
assert_eq!(out.steps, 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn modell_timeout_und_endpoint_fehler() {
|
||||
let m = MockModel::new(vec![Err(ModelError::Timeout)]);
|
||||
assert_eq!(run_agent(&m, &MockWs::default(), "A", &limits()).class, ErrorClass::Timeout);
|
||||
let m = MockModel::new(vec![Err(ModelError::Endpoint("down".into()))]);
|
||||
assert_eq!(run_agent(&m, &MockWs::default(), "A", &limits()).class, ErrorClass::EndpointError);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn implizites_ende_ohne_tool_calls() {
|
||||
let m = MockModel::new(vec![Ok(ChatResponse {
|
||||
message: Message::new("assistant", "Ich bin fertig."),
|
||||
prompt_tokens: 1,
|
||||
completion_tokens: 1,
|
||||
})]);
|
||||
let out = run_agent(&m, &MockWs::default(), "A", &limits());
|
||||
assert_eq!(out.class, ErrorClass::Ok);
|
||||
assert_eq!(out.summary.as_deref(), Some("Ich bin fertig."));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pfade_bleiben_in_work() {
|
||||
assert_eq!(resolve_work_path("a/b.txt").unwrap(), "/work/a/b.txt");
|
||||
assert_eq!(resolve_work_path("./a.txt").unwrap(), "/work/a.txt");
|
||||
assert_eq!(resolve_work_path("/work/x").unwrap(), "/work/x");
|
||||
assert_eq!(resolve_work_path("/work").unwrap(), "/work");
|
||||
assert!(resolve_work_path("../etc/passwd").is_err());
|
||||
assert!(resolve_work_path("a/../../b").is_err());
|
||||
assert!(resolve_work_path("/etc/passwd").is_err());
|
||||
assert!(resolve_work_path("/workbench/x").is_err());
|
||||
assert!(resolve_work_path("").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ollama_antwort_wird_gelesen() {
|
||||
let text = r#"{"message":{"role":"assistant","content":"","tool_calls":[{"function":{"name":"done","arguments":{"summary":"ok"}}}]},"prompt_eval_count":12,"eval_count":7}"#;
|
||||
let parsed: OllamaResponse = serde_json::from_str(text).unwrap();
|
||||
assert_eq!(parsed.message.tool_calls[0].function.name, "done");
|
||||
assert_eq!(parsed.prompt_eval_count, 12);
|
||||
assert_eq!(parsed.eval_count, 7);
|
||||
}
|
||||
|
||||
/// Alle Tools gegen eine echte Sandbox. Braucht Podman und ein Image mit
|
||||
/// Python, sh, find und base64: `CB_TEST_IMAGE=cb-python:latest cargo test -- --ignored`.
|
||||
#[test]
|
||||
#[ignore]
|
||||
fn werkzeuge_gegen_echte_sandbox() {
|
||||
use crate::sandbox::{container_name, Limits};
|
||||
let image = std::env::var("CB_TEST_IMAGE").expect("CB_TEST_IMAGE setzen");
|
||||
let name = container_name(&format!("agent-{}", std::process::id()));
|
||||
let sb = Sandbox::start("podman", &name, &image, &Limits::default(), None).expect("Start");
|
||||
let ws = SandboxWorkspace { sandbox: &sb };
|
||||
|
||||
ws.write_file("/work/ordner/a.txt", "Hallo 'Welt'\n").unwrap();
|
||||
assert_eq!(ws.read_file("/work/ordner/a.txt").unwrap(), "Hallo 'Welt'\n");
|
||||
assert!(ws.read_file("/work/fehlt.txt").is_err());
|
||||
let listing = ws.list_dir("/work").unwrap();
|
||||
assert!(listing.contains("d ordner"), "{listing}");
|
||||
let out = ws.run_shell("cat ordner/a.txt | wc -l").unwrap();
|
||||
assert!(out.starts_with("exit 0"), "{out}");
|
||||
assert!(out.contains('1'), "{out}");
|
||||
|
||||
// Ende-zu-Ende mit Mock-Modell gegen die echte Sandbox.
|
||||
let m = MockModel::new(vec![
|
||||
reply(vec![call("run_shell", json!({"command": "python3 -c 'print(6*7)'"}))]),
|
||||
reply(vec![call("done", json!({"summary": "42"}))]),
|
||||
]);
|
||||
let out = run_agent(&m, &ws, "Rechne", &limits());
|
||||
assert_eq!(out.class, ErrorClass::Ok);
|
||||
assert!(out.transcript.iter().any(|m| m.content.contains("42")));
|
||||
drop(ws);
|
||||
sb.remove().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sh_quote_maskiert_apostrophe() {
|
||||
assert_eq!(sh_quote("a'b"), "'a'\\''b'");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user