strata verlangt nach dem Start mit --access lan einen Schlüssel (HTTP 401). Der Client liest ihn aus der Umgebungsvariable STRATA_API_KEY (Name in config.toml änderbar) und sendet ihn als Bearer-Token. Der Schlüssel steht weder in der Konfiguration noch im Repo. Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
1023 lines
36 KiB
Rust
1023 lines
36 KiB
Rust
//! 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::sync::atomic::{AtomicBool, Ordering};
|
|
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>,
|
|
/// Gesetzt, wenn der Lauf von außen abgebrochen wurde. Dann ist das Ergebnis nicht gültig.
|
|
pub cancelled: bool,
|
|
}
|
|
|
|
/// 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 {
|
|
run_agent_cancellable(model, ws, prompt, limits, &AtomicBool::new(false))
|
|
}
|
|
|
|
/// Wie `run_agent`, bricht aber ab, sobald `cancel` gesetzt ist. Der Lauf gilt dann als `cancelled`.
|
|
pub fn run_agent_cancellable(
|
|
model: &dyn ModelClient,
|
|
ws: &dyn Workspace,
|
|
prompt: &str,
|
|
limits: &AgentLimits,
|
|
cancel: &AtomicBool,
|
|
) -> 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![],
|
|
cancelled: false,
|
|
};
|
|
|
|
// 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 cancel.load(Ordering::SeqCst) {
|
|
out.cancelled = true;
|
|
break ErrorClass::Ok;
|
|
}
|
|
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,
|
|
})
|
|
}
|
|
}
|
|
|
|
/// Modell über einen OpenAI-kompatiblen Endpunkt (`/v1/chat/completions`), z. B. strata.
|
|
/// Die internen Nachrichten werden ins OpenAI-Format umgeschrieben: Argumente als Text,
|
|
/// jeder Tool-Call mit ID, Tool-Antworten mit passender `tool_call_id`.
|
|
pub struct OpenAiClient {
|
|
pub url: String,
|
|
pub model: String,
|
|
api_key: Option<String>,
|
|
http: reqwest::blocking::Client,
|
|
}
|
|
|
|
#[derive(Deserialize)]
|
|
struct OpenAiResponse {
|
|
choices: Vec<OpenAiChoice>,
|
|
#[serde(default)]
|
|
usage: Option<OpenAiUsage>,
|
|
}
|
|
|
|
#[derive(Deserialize)]
|
|
struct OpenAiChoice {
|
|
message: OpenAiMessage,
|
|
}
|
|
|
|
#[derive(Deserialize)]
|
|
struct OpenAiMessage {
|
|
#[serde(default)]
|
|
content: Option<String>,
|
|
#[serde(default)]
|
|
tool_calls: Vec<OpenAiToolCall>,
|
|
}
|
|
|
|
#[derive(Deserialize)]
|
|
struct OpenAiToolCall {
|
|
function: OpenAiFunction,
|
|
}
|
|
|
|
#[derive(Deserialize)]
|
|
struct OpenAiFunction {
|
|
name: String,
|
|
#[serde(default)]
|
|
arguments: String,
|
|
}
|
|
|
|
#[derive(Deserialize)]
|
|
struct OpenAiUsage {
|
|
#[serde(default)]
|
|
prompt_tokens: u32,
|
|
#[serde(default)]
|
|
completion_tokens: u32,
|
|
}
|
|
|
|
/// Wandelt den Verlauf ins OpenAI-Format um. Jeder Tool-Call bekommt eine ID; eine
|
|
/// Tool-Antwort erhält die ID des nächsten offenen Calls mit gleichem Namen.
|
|
pub fn to_openai_messages(messages: &[Message]) -> Vec<Value> {
|
|
let mut out = Vec::new();
|
|
// Offene Calls: (id, name)
|
|
let mut open: Vec<(String, String)> = Vec::new();
|
|
let mut counter = 0usize;
|
|
for m in messages {
|
|
match m.role.as_str() {
|
|
"assistant" if !m.tool_calls.is_empty() => {
|
|
let mut calls = Vec::new();
|
|
for c in &m.tool_calls {
|
|
counter += 1;
|
|
let id = format!("call_{counter}");
|
|
let args = match &c.function.arguments {
|
|
Value::String(s) => s.clone(),
|
|
other => other.to_string(),
|
|
};
|
|
calls.push(json!({
|
|
"id": id,
|
|
"type": "function",
|
|
"function": { "name": c.function.name, "arguments": args }
|
|
}));
|
|
open.push((id, c.function.name.clone()));
|
|
}
|
|
out.push(json!({ "role": "assistant", "content": m.content, "tool_calls": calls }));
|
|
}
|
|
"tool" => {
|
|
let name = m.tool_name.clone().unwrap_or_default();
|
|
let id = match open.iter().position(|(_, n)| *n == name) {
|
|
Some(i) => open.remove(i).0,
|
|
None => format!("call_orphan_{counter}"),
|
|
};
|
|
out.push(json!({ "role": "tool", "tool_call_id": id, "content": m.content }));
|
|
}
|
|
role => out.push(json!({ "role": role, "content": m.content })),
|
|
}
|
|
}
|
|
out
|
|
}
|
|
|
|
impl OpenAiClient {
|
|
pub fn new(url: &str, model: &str, api_key: Option<String>) -> Result<OpenAiClient, String> {
|
|
let http = reqwest::blocking::Client::builder()
|
|
.build()
|
|
.map_err(|e| format!("HTTP-Client nicht baubar: {e}"))?;
|
|
Ok(OpenAiClient {
|
|
url: url.trim_end_matches('/').into(),
|
|
model: model.into(),
|
|
api_key,
|
|
http,
|
|
})
|
|
}
|
|
}
|
|
|
|
impl ModelClient for OpenAiClient {
|
|
fn chat(&self, messages: &[Message], tools: &Value, timeout: Duration)
|
|
-> Result<ChatResponse, ModelError>
|
|
{
|
|
let body = json!({
|
|
"model": self.model,
|
|
"messages": to_openai_messages(messages),
|
|
"tools": tools,
|
|
"stream": false,
|
|
"temperature": 0,
|
|
});
|
|
let mut req = self.http.post(&self.url).timeout(timeout).json(&body);
|
|
if let Some(key) = &self.api_key {
|
|
req = req.bearer_auth(key);
|
|
}
|
|
let resp = req
|
|
.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: OpenAiResponse = resp
|
|
.json()
|
|
.map_err(|e| ModelError::Endpoint(format!("Antwort nicht lesbar: {e}")))?;
|
|
let choice = parsed
|
|
.choices
|
|
.into_iter()
|
|
.next()
|
|
.ok_or_else(|| ModelError::Endpoint("Antwort ohne choices".into()))?;
|
|
let tool_calls = choice
|
|
.message
|
|
.tool_calls
|
|
.into_iter()
|
|
.map(|c| {
|
|
// Argumente kommen als JSON-Text. Ungültiges JSON bleibt als Text,
|
|
// der Agent meldet es dann als invalid_tool_json.
|
|
let arguments = serde_json::from_str::<Value>(&c.function.arguments)
|
|
.unwrap_or(Value::String(c.function.arguments.clone()));
|
|
ToolCall {
|
|
function: FunctionCall { name: c.function.name, arguments },
|
|
}
|
|
})
|
|
.collect();
|
|
let usage = parsed.usage.unwrap_or(OpenAiUsage { prompt_tokens: 0, completion_tokens: 0 });
|
|
Ok(ChatResponse {
|
|
message: Message {
|
|
role: "assistant".into(),
|
|
content: choice.message.content.unwrap_or_default(),
|
|
tool_calls,
|
|
tool_name: None,
|
|
},
|
|
prompt_tokens: usage.prompt_tokens,
|
|
completion_tokens: usage.completion_tokens,
|
|
})
|
|
}
|
|
}
|
|
|
|
#[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();
|
|
}
|
|
|
|
/// Echter Modelllauf gegen Ollama und Podman. Braucht laufenden Ollama-Dienst
|
|
/// mit dem Modell und ein Image: `CB_OLLAMA_URL=http://host:11434 CB_OLLAMA_MODEL=qwen3:0.6b
|
|
/// CB_TEST_IMAGE=cb-python:latest cargo test ollama_lauf -- --ignored`.
|
|
#[test]
|
|
#[ignore]
|
|
fn ollama_lauf_schreibt_datei_und_beendet() {
|
|
use crate::sandbox::{container_name, Limits};
|
|
let url = std::env::var("CB_OLLAMA_URL").expect("CB_OLLAMA_URL setzen");
|
|
let model = std::env::var("CB_OLLAMA_MODEL").expect("CB_OLLAMA_MODEL setzen");
|
|
let image = std::env::var("CB_TEST_IMAGE").expect("CB_TEST_IMAGE setzen");
|
|
let name = container_name(&format!("ollama-{}", std::process::id()));
|
|
let sb = Sandbox::start("podman", &name, &image, &Limits::default(), None).expect("Start");
|
|
let ws = SandboxWorkspace { sandbox: &sb };
|
|
let client = OllamaClient::new(&url, &model).unwrap();
|
|
let lim = AgentLimits { max_steps: 10, timeout: Duration::from_secs(600) };
|
|
|
|
let prompt = "Erstelle die Datei out.txt mit dem Inhalt hallo (ohne Zeilenumbruch). \
|
|
Rufe danach das Werkzeug done auf.";
|
|
let out = run_agent(&client, &ws, prompt, &lim);
|
|
eprintln!("Lauf: {:?} Schritte={} Tokens={}/{} Dauer={}ms", out.class, out.steps,
|
|
out.prompt_tokens, out.completion_tokens, out.duration_ms);
|
|
for m in &out.transcript {
|
|
eprintln!("[{}] {} {:?}", m.role, m.content.chars().take(200).collect::<String>(), m.tool_calls);
|
|
}
|
|
let content = ws.read_file("/work/out.txt").unwrap_or_default();
|
|
sb.remove().unwrap();
|
|
assert_eq!(out.class, ErrorClass::Ok, "Lauf endete mit {:?}", out.class);
|
|
assert_eq!(content.trim(), "hallo", "out.txt: {content:?}");
|
|
}
|
|
|
|
#[test]
|
|
fn openai_format_ordnet_tool_antworten_zu() {
|
|
let msgs = vec![
|
|
Message::new("system", "s"),
|
|
Message::new("user", "u"),
|
|
Message {
|
|
role: "assistant".into(),
|
|
content: String::new(),
|
|
tool_calls: vec![ToolCall {
|
|
function: FunctionCall { name: "read_file".into(), arguments: json!({"path": "a"}) },
|
|
}],
|
|
tool_name: None,
|
|
},
|
|
Message {
|
|
role: "tool".into(),
|
|
content: "inhalt".into(),
|
|
tool_calls: vec![],
|
|
tool_name: Some("read_file".into()),
|
|
},
|
|
];
|
|
let out = to_openai_messages(&msgs);
|
|
assert_eq!(out.len(), 4);
|
|
let call = &out[2]["tool_calls"][0];
|
|
assert_eq!(call["type"], "function");
|
|
assert_eq!(call["function"]["arguments"], "{\"path\":\"a\"}");
|
|
assert_eq!(out[3]["role"], "tool");
|
|
assert_eq!(out[3]["tool_call_id"], call["id"]);
|
|
}
|
|
|
|
#[test]
|
|
fn sh_quote_maskiert_apostrophe() {
|
|
assert_eq!(sh_quote("a'b"), "'a'\\''b'");
|
|
}
|
|
}
|