diff --git a/ROADMAP.md b/ROADMAP.md index 4f248d0..60e0242 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -20,7 +20,7 @@ Zeichen: ✓ fertig · ◐ teilweise · ✗ offen · ? nicht geprüft. | --- | --- | --- | --- | --- | | #1001 | F-01 Tauri-Grundgerüst, Datenordner, Config | SPEC 12 | ◐ | Umgesetzt: Gerüst, TOML-Config mit Standardanlage, Datenordner, Setup zeigt Pfade. `cargo test` 6/6, `npm run build` grün. Klicktests `start2app.1–.2` manuell noch nicht ✓ (→ #1018) | | #1002 | F-02 Aufgaben laden und validieren | SPEC 4, 12 | ◐ | Umgesetzt: Laden, Validierung (Pflichtdateien, TOML, Werte, `check.sh` ausführbar), Fehler im Setup. `cargo test` 13/13. Klicktests `aufgabe2validierung.1–.2` manuell offen (→ #1019) | -| #1003 | F-03 Agent-Loop gegen Ollama mit Tools und Fehlerklassen | SPEC 5, 12 | ✗ | noch nicht begonnen (→ #1021) | +| #1003 | F-03 Agent-Loop gegen Ollama mit Tools und Fehlerklassen | SPEC 5, 12 | ◐ | Loop, Tools, Pfadprüfung, Fehlerklassen und Metriken in `agent.rs`. 31 Unit-Tests grün (Mock-Modell). Werkzeuge gegen echte Sandbox grün. Echter Modelllauf gegen Ollama nicht möglich: Dienst läuft nicht, keine Modelle lokal. Klicktests `lauf2ergebnis.1–.3` offen (→ #1021) | | #1004 | F-04 Podman-Sandbox pro Lauf | SPEC 6, 12 | ◐ | Modul `sandbox.rs` steht: Start ohne Netz, Limits, Kopieren nach `/work`, `exec` mit Timeout, Export, Entfernen. Limits und Runtime kommen aus `config.toml`. Echter Lauf gegen Podman mit Image `cb-python:latest` bestanden (ignorierter Test). Noch nicht an den Runner angebunden (#1022); Klicktests `lauf2sandbox.1–.2` manuell offen (→ #1020) | | #1005 | F-05 Runner mit Wiederholungen, Abbruch, Fortsetzen | SPEC 7, 12 | ✗ | noch nicht begonnen (→ #1022) | | #1006 | F-06 SQLite inkl. Schritt-Log | SPEC 8, 12 | ✗ | noch nicht begonnen (→ #1023) | @@ -47,7 +47,7 @@ Zeichen: ✓ fertig · ◐ teilweise · ✗ offen · ? nicht geprüft. - [#1018] **Gerüst anlegen.** Tauri 2 mit Svelte und TypeScript, Rust-Backend, Datenordner, TOML-Config. Gerüst (`create-tauri-app`, svelte-ts) und Config-/Datenordner-Logik (`src-tauri/src/config.rs`) sind gebaut; `cargo test` 6/6 grün. Offen: die Klicktests `start2app.1–.2` vom Menschen manuell ausführen lassen. Erst dann gilt #1018 als fertig. Tests `start2app.1–.2`. → #1001 - [#1019] **Aufgaben laden und validieren.** Umgesetzt in `src-tauri/src/tasks.rs`, `cargo test` 13/13. Offen: Klicktests `aufgabe2validierung.1–.2` manuell ausführen lassen. Tests `aufgabe2validierung.1–.2`. → #1002 - [#1020] **Podman-Sandbox pro Lauf.** Modul gebaut (`src-tauri/src/sandbox.rs`). Echter Test `CB_TEST_IMAGE=docker.io/library/python:3.12-slim cargo test -- --ignored` grün: Startdatei in `/work`, Netz aus, Timeout erkannt, Export, Container entfernt. Limits und Runtime aus der Config. Image `cb-python` gebaut (`images/cb-python/Containerfile`, Python 3.12 und pytest). Der Test lief mit `CB_TEST_IMAGE=cb-python:latest` grün. Offen: Anbindung an den Runner (#1022), Klicktests `lauf2sandbox.1–.2` manuell. Tests `lauf2sandbox.1–.2`. → #1004 -- [#1021] **Agent-Loop gegen Ollama.** Tools `read_file`, `write_file`, `list_dir`, `run_shell`, `done`; Pfade auf `/work`; Fehlerklassen und Metriken. Tests `lauf2ergebnis.1–.3`. → #1003 +- [#1021] **Agent-Loop gegen Ollama.** Umgesetzt in `src-tauri/src/agent.rs`: fünf Tools, Pfade auf `/work`, Fehlerklassen, Schleifenerkennung, Metriken, Ollama-Client (`/api/chat`, ohne Streaming, Temperatur 0). Offen: echter Lauf gegen Ollama (Dienst starten, Modell laden), Klicktests `lauf2ergebnis.1–.3`. Tests `lauf2ergebnis.1–.3`. → #1003 - [#1022] **Runner.** Wiederholungen, sequentiell pro Modell, Aufwärmen, Abbruch und Fortsetzen. Tests `batch2fortsetzen.1–.2`. → #1005 - [#1023] **SQLite-Speicher.** Tabellen `batch`, `run`, `step` nach Abschnitt 8. Tests `lauf2ergebnis.2`. → #1006 - [#1024] **Aufgaben a-01 bis a-03, b-04 bis b-06 schreiben.** Mindestens je ein lauffähiges Beispiel, Mutation bei b-06. Tests: je Aufgabe ein Lauf mit Bericht. → #1007 diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index 59204e8..bdba3ef 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -219,6 +219,12 @@ version = "0.21.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9d297deb1925b89f2ccc13d7635fa0714f12c87adce1c75356b39ca9b7178567" +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + [[package]] name = "base64" version = "0.23.1" @@ -470,6 +476,8 @@ dependencies = [ name = "coding-bench" version = "0.1.0" dependencies = [ + "base64 0.22.1", + "reqwest 0.12.28", "serde", "serde_json", "tauri", @@ -507,6 +515,16 @@ dependencies = [ "version_check", ] +[[package]] +name = "core-foundation" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91e195e091a93c46f7102ec7818a2aa394e1e1771c3ab4825963fa03e45afb8f" +dependencies = [ + "core-foundation-sys", + "libc", +] + [[package]] name = "core-foundation" version = "0.10.1" @@ -530,9 +548,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "064badf302c3194842cf2c5d61f56cc88e54a759313879cdf03abdd27d0c3b97" dependencies = [ "bitflags 2.13.2", - "core-foundation", + "core-foundation 0.10.1", "core-graphics-types", - "foreign-types", + "foreign-types 0.5.0", "libc", ] @@ -543,10 +561,16 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3d44a101f213f6c4cdc1853d4b78aef6db6bdfa3468798cc1d9912f4735013eb" dependencies = [ "bitflags 2.13.2", - "core-foundation", + "core-foundation 0.10.1", "libc", ] +[[package]] +name = "core_detect" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48" + [[package]] name = "cpufeatures" version = "0.2.17" @@ -873,6 +897,20 @@ version = "1.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4ef6b89e5b37196644d8796de5268852ff179b44e96276cf4290264843743bb7" +[[package]] +name = "encoding_rs" +version = "0.8.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "89253175e704ab869b04f9db224d38630e0211a53841a79181deae0889e169f5" +dependencies = [ + "cfg-if", + "core_detect", + "multiversion_no_op", + "rustversion", + "scopeguard", + "simdutf8", +] + [[package]] name = "endi" version = "1.1.1" @@ -1001,6 +1039,15 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" +[[package]] +name = "foreign-types" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6f339eb8adc052cd2ca78910fda869aefa38d22d5cb648e6485e4d3fc06f3b1" +dependencies = [ + "foreign-types-shared 0.1.1", +] + [[package]] name = "foreign-types" version = "0.5.0" @@ -1008,7 +1055,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d737d9aa519fb7b749cbc3b962edcf310a8dd1f4b67c91c4f83975dbdd17d965" dependencies = [ "foreign-types-macros", - "foreign-types-shared", + "foreign-types-shared 0.3.1", ] [[package]] @@ -1022,6 +1069,12 @@ dependencies = [ "syn 3.0.9", ] +[[package]] +name = "foreign-types-shared" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b" + [[package]] name = "foreign-types-shared" version = "0.3.1" @@ -1044,6 +1097,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" dependencies = [ "futures-core", + "futures-sink", ] [[package]] @@ -1230,6 +1284,17 @@ dependencies = [ "version_check", ] +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + [[package]] name = "getrandom" version = "0.3.4" @@ -1401,6 +1466,25 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "h2" +version = "0.4.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d29020232d6aa3fb1daca64c1127cf662cf97f254ae16c18c05b8ab635fc118" +dependencies = [ + "atomic-waker", + "bytes", + "fnv", + "futures-core", + "futures-sink", + "http", + "indexmap 2.14.2", + "slab", + "tokio", + "tokio-util", + "tracing", +] + [[package]] name = "hashbrown" version = "0.12.3" @@ -1494,7 +1578,9 @@ checksum = "2c3e324da4c95177d6291d4c8730197c0d1822f8a9766814a4a44fa5ab797c9c" dependencies = [ "atomic-waker", "bytes", + "futures-channel", "futures-core", + "h2", "http", "http-body", "httparse", @@ -1505,6 +1591,37 @@ dependencies = [ "want", ] +[[package]] +name = "hyper-rustls" +version = "0.27.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dfa8e654703247911e29c23fbeaa261834bd9bb74efba2f9acddc37bfb127f53" +dependencies = [ + "http", + "hyper", + "hyper-util", + "rustls", + "tokio", + "tokio-rustls", + "tower-service", +] + +[[package]] +name = "hyper-tls" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "70206fc6890eaca9fde8a0bf71caa2ddfc9fe045ac9e5c70df101a7dbde866e0" +dependencies = [ + "bytes", + "http-body-util", + "hyper", + "hyper-util", + "native-tls", + "tokio", + "tokio-native-tls", + "tower-service", +] + [[package]] name = "hyper-util" version = "0.1.21" @@ -1524,9 +1641,11 @@ dependencies = [ "percent-encoding", "pin-project-lite", "socket2", + "system-configuration", "tokio", "tower-service", "tracing", + "windows-registry", ] [[package]] @@ -2069,6 +2188,29 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "multiversion_no_op" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "743fb55ba31b18fb1ecef6bdc9aa2743314978ac084044301a7eee33fb99a20d" + +[[package]] +name = "native-tls" +version = "0.2.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "465500e14ea162429d264d44189adc38b199b62b1c21eea9f69e4b73cb03bbf2" +dependencies = [ + "libc", + "log", + "openssl", + "openssl-probe", + "openssl-sys", + "schannel", + "security-framework", + "security-framework-sys", + "tempfile", +] + [[package]] name = "ndk" version = "0.9.0" @@ -2355,6 +2497,49 @@ dependencies = [ "libc", ] +[[package]] +name = "openssl" +version = "0.10.82" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4de8111e94a56adca7ebfe6c365b6d42f99deb69b74b6becacd4204e2f193aa2" +dependencies = [ + "bitflags 2.13.2", + "cfg-if", + "foreign-types 0.3.2", + "libc", + "openssl-macros", + "openssl-sys", +] + +[[package]] +name = "openssl-macros" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "openssl-probe" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e036b411754132fd6b74e94b74e9a13c5cf606fa93d1885c35860d3060820b1" + +[[package]] +name = "openssl-sys" +version = "0.9.118" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19c413d6ec9ebaf5e1c829d355cb3e9f783778d700f135be0921d52fce3c60ae" +dependencies = [ + "cc", + "libc", + "pkg-config", + "vcpkg", +] + [[package]] name = "option-ext" version = "0.2.0" @@ -2749,6 +2934,48 @@ version = "0.8.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" +[[package]] +name = "reqwest" +version = "0.12.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147" +dependencies = [ + "base64 0.22.1", + "bytes", + "encoding_rs", + "futures-channel", + "futures-core", + "futures-util", + "h2", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-rustls", + "hyper-tls", + "hyper-util", + "js-sys", + "log", + "mime", + "native-tls", + "percent-encoding", + "pin-project-lite", + "rustls-pki-types", + "serde", + "serde_json", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tokio-native-tls", + "tower", + "tower-http", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + [[package]] name = "reqwest" version = "0.13.5" @@ -2783,6 +3010,20 @@ dependencies = [ "web-sys", ] +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + [[package]] name = "rustc-hash" version = "2.1.3" @@ -2811,12 +3052,51 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "rustls" +version = "0.23.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" +dependencies = [ + "once_cell", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-pki-types" +version = "1.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96" +dependencies = [ + "zeroize", +] + +[[package]] +name = "rustls-webpki" +version = "0.103.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4443b1b6d39d7c663139942cc4558262562d2c84123bb6282ef177009ca8b281" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + [[package]] name = "rustversion" version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + [[package]] name = "same-file" version = "1.0.6" @@ -2826,6 +3106,15 @@ dependencies = [ "winapi-util", ] +[[package]] +name = "schannel" +version = "0.1.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9cb23c424d8ee841bb4d813677ca237e2a610067d594fec130f87d6093495ab5" +dependencies = [ + "windows-sys 0.61.2", +] + [[package]] name = "schemars" version = "0.8.22" @@ -2883,6 +3172,29 @@ version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" +[[package]] +name = "security-framework" +version = "3.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d" +dependencies = [ + "bitflags 2.13.2", + "core-foundation 0.10.1", + "core-foundation-sys", + "libc", + "security-framework-sys", +] + +[[package]] +name = "security-framework-sys" +version = "2.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3" +dependencies = [ + "core-foundation-sys", + "libc", +] + [[package]] name = "selectors" version = "0.38.0" @@ -3007,6 +3319,18 @@ dependencies = [ "serde_core", ] +[[package]] +name = "serde_urlencoded" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" +dependencies = [ + "form_urlencoded", + "itoa", + "ryu", + "serde", +] + [[package]] name = "serde_with" version = "3.24.0" @@ -3104,6 +3428,12 @@ version = "0.3.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" +[[package]] +name = "simdutf8" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" + [[package]] name = "siphasher" version = "1.0.4" @@ -3222,6 +3552,12 @@ version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + [[package]] name = "swift-rs" version = "1.0.9" @@ -3285,6 +3621,27 @@ dependencies = [ "syn 3.0.9", ] +[[package]] +name = "system-configuration" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a13f3d0daba03132c0aa9767f98351b3488edc2c100cda2d2ec2b04f3d8d3c8b" +dependencies = [ + "bitflags 2.13.2", + "core-foundation 0.9.4", + "system-configuration-sys", +] + +[[package]] +name = "system-configuration-sys" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e1d1b10ced5ca923a1fcb8d03e96b8d3268065d724548c0211415ff6ac6bac4" +dependencies = [ + "core-foundation-sys", + "libc", +] + [[package]] name = "system-deps" version = "6.2.2" @@ -3306,7 +3663,7 @@ checksum = "d5777b06fe6435126ae8d816eba269e050e1e10d302cf5461e9c49eccabc3548" dependencies = [ "bitflags 2.13.2", "block2", - "core-foundation", + "core-foundation 0.10.1", "core-graphics", "crossbeam-channel", "dbus", @@ -3385,7 +3742,7 @@ dependencies = [ "percent-encoding", "plist", "raw-window-handle", - "reqwest", + "reqwest 0.13.5", "serde", "serde_json", "serde_repr", @@ -3729,6 +4086,26 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "tokio-native-tls" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbae76ab933c85776efabc971569dd6119c580d8f5d448769dec1764bf796ef2" +dependencies = [ + "native-tls", + "tokio", +] + +[[package]] +name = "tokio-rustls" +version = "0.26.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9cc2678c2cdd569ef8215e2afd7954ada2ae20b4fdd2c5fe6139a3b02d105db" +dependencies = [ + "rustls", + "tokio", +] + [[package]] name = "tokio-util" version = "0.7.20" @@ -3738,6 +4115,7 @@ dependencies = [ "bytes", "futures-core", "futures-sink", + "libc", "pin-project-lite", "tokio", ] @@ -3977,6 +4355,12 @@ version = "1.13.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8" +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + [[package]] name = "url" version = "2.5.8" @@ -4029,6 +4413,12 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "vcpkg" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" + [[package]] name = "version-compare" version = "0.2.1" @@ -4403,6 +4793,17 @@ dependencies = [ "windows-link", ] +[[package]] +name = "windows-registry" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02752bf7fbdcce7f2a27a742f798510f3e5ad88dbe84871e5168e2120c3d5720" +dependencies = [ + "windows-link", + "windows-result", + "windows-strings", +] + [[package]] name = "windows-result" version = "0.4.1" @@ -4427,7 +4828,16 @@ version = "0.45.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "75283be5efb2831d37ea142365f009c02ec203cd29a3ebecbc093d52315b66d0" dependencies = [ - "windows-targets", + "windows-targets 0.42.2", +] + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets 0.52.6", ] [[package]] @@ -4445,13 +4855,29 @@ version = "0.42.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8e5180c00cd44c9b1c88adb3693291f1cd93605ded80c250a75d472756b4d071" dependencies = [ - "windows_aarch64_gnullvm", - "windows_aarch64_msvc", - "windows_i686_gnu", - "windows_i686_msvc", - "windows_x86_64_gnu", - "windows_x86_64_gnullvm", - "windows_x86_64_msvc", + "windows_aarch64_gnullvm 0.42.2", + "windows_aarch64_msvc 0.42.2", + "windows_i686_gnu 0.42.2", + "windows_i686_msvc 0.42.2", + "windows_x86_64_gnu 0.42.2", + "windows_x86_64_gnullvm 0.42.2", + "windows_x86_64_msvc 0.42.2", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm 0.52.6", + "windows_aarch64_msvc 0.52.6", + "windows_i686_gnu 0.52.6", + "windows_i686_gnullvm", + "windows_i686_msvc 0.52.6", + "windows_x86_64_gnu 0.52.6", + "windows_x86_64_gnullvm 0.52.6", + "windows_x86_64_msvc 0.52.6", ] [[package]] @@ -4478,42 +4904,90 @@ version = "0.42.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "597a5118570b68bc08d8d59125332c54f1ba9d9adeedeef5b99b02ba2b0698f8" +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + [[package]] name = "windows_aarch64_msvc" version = "0.42.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e08e8864a60f06ef0d0ff4ba04124db8b0fb3be5776a5cd47641e942e58c4d43" +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + [[package]] name = "windows_i686_gnu" version = "0.42.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c61d927d8da41da96a81f029489353e68739737d3beca43145c8afec9a31a84f" +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + [[package]] name = "windows_i686_msvc" version = "0.42.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "44d840b6ec649f480a41c8d80f9c65108b92d89345dd94027bfe06ac444d1060" +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + [[package]] name = "windows_x86_64_gnu" version = "0.42.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8de912b8b8feb55c064867cf047dda097f92d51efad5b491dfb98f6bbb70cb36" +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + [[package]] name = "windows_x86_64_gnullvm" version = "0.42.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "26d41b46a36d453748aedef1486d5c7a85db22e56aff34643984ea85514e94a3" +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + [[package]] name = "windows_x86_64_msvc" version = "0.42.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9aec5da331524158c6d1a4ac0ab1541149c0b9505fde06423b02f5ef0106b9f0" +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + [[package]] name = "winnow" version = "0.5.40" @@ -4732,6 +5206,12 @@ dependencies = [ "synstructure", ] +[[package]] +name = "zeroize" +version = "1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" + [[package]] name = "zerotrie" version = "0.2.5" diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index bdf1846..ce5441b 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -23,6 +23,8 @@ tauri-plugin-opener = "2" serde = { version = "1", features = ["derive"] } serde_json = "1" toml = "0.8" +reqwest = { version = "0.12", features = ["blocking", "json"] } +base64 = "0.22" # Read the optimization guideline for more details: https://tauri.app/concept/size/#cargo-configuration diff --git a/src-tauri/src/agent.rs b/src-tauri/src/agent.rs new file mode 100644 index 0000000..b2fc506 --- /dev/null +++ b/src-tauri/src/agent.rs @@ -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, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub tool_name: Option, +} + +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; +} + +/// 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; + fn write_file(&self, path: &str, content: &str) -> Result<(), String>; + fn list_dir(&self, path: &str) -> Result; + /// Liefert Ausgabe und Exit-Code als Text, oder einen Fehler bei Problemen mit dem Befehl selbst. + fn run_shell(&self, command: &str) -> Result; +} + +#[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, + pub steps: u32, + pub prompt_tokens: u32, + pub completion_tokens: u32, + pub duration_ms: u128, + pub time_to_first_tool_ms: Option, + pub transcript: Vec, +} + +/// 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 { + 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, Fatal> { + match v { + Value::Object(m) => Ok(m.clone()), + Value::String(s) => match serde_json::from_str::(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, key: &str) -> Result { + 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 { + 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 { + 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 { + 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 { + 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) -> 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 { + 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 + { + 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>>, + } + + impl MockModel { + fn new(script: Vec>) -> MockModel { + MockModel { script: RefCell::new(script.into()) } + } + } + + impl ModelClient for MockModel { + fn chat(&self, _m: &[Message], _t: &Value, _to: Duration) -> Result { + self.script + .borrow_mut() + .pop_front() + .unwrap_or(Err(ModelError::Endpoint("Skript leer".into()))) + } + } + + #[derive(Default)] + struct MockWs { + files: RefCell>, + } + + impl Workspace for MockWs { + fn read_file(&self, path: &str) -> Result { + 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 { + Ok("f a.txt".into()) + } + fn run_shell(&self, command: &str) -> Result { + 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) -> Result { + 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'"); + } +} diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index c9fd238..6ba747a 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -1,3 +1,4 @@ +mod agent; mod config; mod sandbox; mod tasks;