Compare commits
5 Commits
304a7a644c
...
c8290aeb94
| Author | SHA1 | Date | |
|---|---|---|---|
| c8290aeb94 | |||
| e69f3be35b | |||
| a02f57b469 | |||
| 173be01279 | |||
| e7e0ad558d |
16
ROADMAP.md
16
ROADMAP.md
@ -20,10 +20,10 @@ 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) |
|
||||
| #1004 | F-04 Podman-Sandbox pro Lauf | SPEC 6, 12 | ✗ | noch nicht begonnen (→ #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) |
|
||||
| #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 Lauf gegen Ollama auf srv04 mit `qwen3:0.6b` bestanden (ignorierter Test `ollama_lauf_schreibt_datei_und_beendet`: Datei geschrieben, `done` aufgerufen). Offen: größere Modelle, Klicktests `lauf2ergebnis.1–.3` (→ #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 | ◐ | `runner.rs`: Plan, Warm-up je Modell, Sandbox pro Lauf, `check.sh`, Abbruch, Fortsetzen über die DB. Ende-zu-Ende gegen srv04 mit `qwen3:0.6b` grün (2 Läufe, dann Fortsetzen überspringt beide). Abbruch im Lauf nicht real getestet. Noch nicht an Commands/GUI angebunden (→ #1022) |
|
||||
| #1006 | F-06 SQLite inkl. Schritt-Log | SPEC 8, 12 | ◐ | `store.rs`: Tabellen `batch`, `run`, `step` nach SPEC 8, Lauf und Schritte in einer Transaktion. Getestet in-memory. Datei-Datenbank im Datenordner noch nicht angebunden (→ #1023) |
|
||||
| #1007 | F-07 Tests a-01 bis a-03 und b-04 bis b-06 | SPEC 11, 12 | ✗ | noch nicht begonnen (→ #1024) |
|
||||
| #1008 | F-08 GUI: Setup, Batch starten, Live-Fortschritt | SPEC 10, 12 | ✗ | noch nicht begonnen (→ #1025) |
|
||||
| #1009 | F-09 Rangliste und Matrix | SPEC 9, 10, 12 | ✗ | noch nicht begonnen (→ #1026) |
|
||||
@ -46,10 +46,10 @@ Zeichen: ✓ fertig · ◐ teilweise · ✗ offen · ? nicht geprüft.
|
||||
**P1 – als Nächstes (Release 0.1.0, Phase 1 Kern)**
|
||||
- [#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.** Frischer Container, `--network none`, Speicher-/CPU-Limit, `/work` als Artefakt, Container entfernen. 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
|
||||
- [#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
|
||||
- [#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.** 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.** Umgesetzt in `src-tauri/src/runner.rs`. Offen: Abbruch über die GUI real prüfen, Anbindung an Tauri-Commands und Events, Modelle mit eigenem Endpunkt in der Config. Tests `batch2fortsetzen.1–.2`. → #1005
|
||||
- [#1023] **SQLite-Speicher.** Umgesetzt in `src-tauri/src/store.rs`, Schema nach SPEC 8. Offen: Datei-Datenbank im Datenordner anlegen und an den Runner anbinden. 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
|
||||
- [#1025] **GUI Setup und Batch.** Modelle, Podman-Status, Datenordner, Aufgabenauswahl, Start, Live-Fortschritt mit Schritt-Log. Tests `batch2fortsetzen.1`. → #1008
|
||||
- [#1026] **Rangliste und Matrix.** Gesamtscore mit Intervall, Matrix Modell × Test nach Erfolgsquote, Lauf-Detail. Tests `ergebnis2detail.1`. → #1009
|
||||
|
||||
8
images/cb-python/Containerfile
Normal file
8
images/cb-python/Containerfile
Normal file
@ -0,0 +1,8 @@
|
||||
# cb-python: Python 3 mit pytest für Aufgaben der Gruppen A bis C.
|
||||
# Bauen: podman build -t cb-python:latest images/cb-python
|
||||
FROM docker.io/library/python:3.12-slim
|
||||
|
||||
RUN pip install --no-cache-dir pytest \
|
||||
&& mkdir -p /work
|
||||
|
||||
WORKDIR /work
|
||||
597
src-tauri/Cargo.lock
generated
597
src-tauri/Cargo.lock
generated
@ -8,6 +8,18 @@ version = "2.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
|
||||
|
||||
[[package]]
|
||||
name = "ahash"
|
||||
version = "0.8.12"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"once_cell",
|
||||
"version_check",
|
||||
"zerocopy",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "aho-corasick"
|
||||
version = "1.1.5"
|
||||
@ -219,6 +231,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,12 +488,16 @@ dependencies = [
|
||||
name = "coding-bench"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"reqwest 0.12.28",
|
||||
"rusqlite",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"tauri",
|
||||
"tauri-build",
|
||||
"tauri-plugin-opener",
|
||||
"toml 0.8.2",
|
||||
"uuid",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@ -507,6 +529,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 +562,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 +575,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 +911,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"
|
||||
@ -947,6 +999,18 @@ dependencies = [
|
||||
"pin-project-lite",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fallible-iterator"
|
||||
version = "0.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2acce4a10f12dc2fb14a218589d4f1f62ef011b2d0cc4b3cb1bba8e94da14649"
|
||||
|
||||
[[package]]
|
||||
name = "fallible-streaming-iterator"
|
||||
version = "0.1.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a"
|
||||
|
||||
[[package]]
|
||||
name = "fastrand"
|
||||
version = "2.5.0"
|
||||
@ -1001,6 +1065,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 +1081,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 +1095,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 +1123,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4"
|
||||
dependencies = [
|
||||
"futures-core",
|
||||
"futures-sink",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@ -1230,6 +1310,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,18 +1492,55 @@ 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"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888"
|
||||
|
||||
[[package]]
|
||||
name = "hashbrown"
|
||||
version = "0.14.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1"
|
||||
dependencies = [
|
||||
"ahash",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hashbrown"
|
||||
version = "0.17.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
|
||||
|
||||
[[package]]
|
||||
name = "hashlink"
|
||||
version = "0.9.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6ba4ff7128dee98c7dc9794b6a411377e1404dba1c97deb8d1a55297bd25d8af"
|
||||
dependencies = [
|
||||
"hashbrown 0.14.5",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "heck"
|
||||
version = "0.4.1"
|
||||
@ -1494,7 +1622,9 @@ checksum = "2c3e324da4c95177d6291d4c8730197c0d1822f8a9766814a4a44fa5ab797c9c"
|
||||
dependencies = [
|
||||
"atomic-waker",
|
||||
"bytes",
|
||||
"futures-channel",
|
||||
"futures-core",
|
||||
"h2",
|
||||
"http",
|
||||
"http-body",
|
||||
"httparse",
|
||||
@ -1505,6 +1635,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 +1685,11 @@ dependencies = [
|
||||
"percent-encoding",
|
||||
"pin-project-lite",
|
||||
"socket2",
|
||||
"system-configuration",
|
||||
"tokio",
|
||||
"tower-service",
|
||||
"tracing",
|
||||
"windows-registry",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@ -1958,6 +2121,17 @@ dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "libsqlite3-sys"
|
||||
version = "0.30.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2e99fb7a497b1e3339bc746195567ed8d3e24945ecd636e3619d20b9de9e9149"
|
||||
dependencies = [
|
||||
"cc",
|
||||
"pkg-config",
|
||||
"vcpkg",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "linux-raw-sys"
|
||||
version = "0.12.1"
|
||||
@ -2069,6 +2243,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 +2552,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 +2989,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 +3065,34 @@ 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 = "rusqlite"
|
||||
version = "0.32.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7753b721174eb8ff87a9a0e799e2d7bc3749323e773db92e0984debb00019d6e"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"fallible-iterator",
|
||||
"fallible-streaming-iterator",
|
||||
"hashlink",
|
||||
"libsqlite3-sys",
|
||||
"smallvec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustc-hash"
|
||||
version = "2.1.3"
|
||||
@ -2811,12 +3121,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 +3175,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 +3241,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 +3388,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 +3497,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 +3621,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 +3690,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 +3732,7 @@ checksum = "d5777b06fe6435126ae8d816eba269e050e1e10d302cf5461e9c49eccabc3548"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"block2",
|
||||
"core-foundation",
|
||||
"core-foundation 0.10.1",
|
||||
"core-graphics",
|
||||
"crossbeam-channel",
|
||||
"dbus",
|
||||
@ -3385,7 +3811,7 @@ dependencies = [
|
||||
"percent-encoding",
|
||||
"plist",
|
||||
"raw-window-handle",
|
||||
"reqwest",
|
||||
"reqwest 0.13.5",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"serde_repr",
|
||||
@ -3729,6 +4155,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 +4184,7 @@ dependencies = [
|
||||
"bytes",
|
||||
"futures-core",
|
||||
"futures-sink",
|
||||
"libc",
|
||||
"pin-project-lite",
|
||||
"tokio",
|
||||
]
|
||||
@ -3977,6 +4424,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 +4482,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 +4862,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 +4897,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 +4924,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 +4973,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"
|
||||
@ -4711,6 +5254,26 @@ dependencies = [
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zerocopy"
|
||||
version = "0.8.63"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e5fe1f8f1b06191a00962174c61aa5005e0bb391a6d80d07e24d115c01a92ed8"
|
||||
dependencies = [
|
||||
"zerocopy-derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zerocopy-derive"
|
||||
version = "0.8.63"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "863ad3ac83293fb4d740aedbfdc9240dd8d1a50c1099acd76ce80ce7c7230c7f"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zerofrom"
|
||||
version = "0.1.8"
|
||||
@ -4732,6 +5295,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"
|
||||
|
||||
@ -23,6 +23,10 @@ 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"
|
||||
rusqlite = { version = "0.32", features = ["bundled"] }
|
||||
uuid = { version = "1", features = ["v4"] }
|
||||
|
||||
|
||||
# Read the optimization guideline for more details: https://tauri.app/concept/size/#cargo-configuration
|
||||
|
||||
823
src-tauri/src/agent.rs
Normal file
823
src-tauri/src/agent.rs
Normal file
@ -0,0 +1,823 @@
|
||||
//! 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,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[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 sh_quote_maskiert_apostrophe() {
|
||||
assert_eq!(sh_quote("a'b"), "'a'\\''b'");
|
||||
}
|
||||
}
|
||||
@ -4,6 +4,7 @@
|
||||
//! mit Standardwerten angelegt. Pfade in der Datei sind optional; ohne Angabe
|
||||
//! gilt der Standardordner der App bzw. `<datenordner>/tasks`.
|
||||
|
||||
use crate::sandbox::Limits;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
@ -11,13 +12,32 @@ use std::path::{Path, PathBuf};
|
||||
pub const CONFIG_FILE_NAME: &str = "config.toml";
|
||||
|
||||
/// Rohe Konfiguration, so wie sie in der Datei steht.
|
||||
#[derive(Debug, Default, Clone, PartialEq, Serialize, Deserialize)]
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default, deny_unknown_fields)]
|
||||
pub struct Config {
|
||||
/// Datenordner (Ergebnisse, Artefakte, Datenbank). Leer = Standard der App.
|
||||
pub data_dir: Option<PathBuf>,
|
||||
/// Aufgabenordner. Leer = `<datenordner>/tasks`.
|
||||
pub tasks_dir: Option<PathBuf>,
|
||||
/// Container-Programm für die Sandbox (Podman-CLI).
|
||||
pub container_runtime: String,
|
||||
/// Speicherlimit pro Lauf, Podman-Schreibweise.
|
||||
pub sandbox_memory: String,
|
||||
/// CPU-Anteil pro Lauf.
|
||||
pub sandbox_cpus: String,
|
||||
}
|
||||
|
||||
impl Default for Config {
|
||||
fn default() -> Self {
|
||||
let limits = Limits::default();
|
||||
Config {
|
||||
data_dir: None,
|
||||
tasks_dir: None,
|
||||
container_runtime: "podman".into(),
|
||||
sandbox_memory: limits.memory,
|
||||
sandbox_cpus: limits.cpus,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Aufgelöste Pfade, die die App tatsächlich verwendet.
|
||||
@ -34,6 +54,14 @@ impl Config {
|
||||
toml::from_str(text).map_err(|e| format!("config.toml ist ungültig: {e}"))
|
||||
}
|
||||
|
||||
/// Ressourcenlimits der Sandbox aus der Konfiguration.
|
||||
pub fn sandbox_limits(&self) -> Limits {
|
||||
Limits {
|
||||
memory: self.sandbox_memory.clone(),
|
||||
cpus: self.sandbox_cpus.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Löst die Pfade auf. `default_data_dir` ist der Standardordner der App.
|
||||
pub fn resolve(&self, config_file: &Path, default_data_dir: &Path) -> Paths {
|
||||
let data_dir = self
|
||||
@ -54,7 +82,7 @@ impl Config {
|
||||
|
||||
/// Lädt die Konfiguration aus `config_dir/config.toml`, legt die Datei bei Bedarf
|
||||
/// mit Standardwerten an und stellt sicher, dass der Datenordner existiert.
|
||||
pub fn load_or_create(config_dir: &Path, default_data_dir: &Path) -> Result<Paths, String> {
|
||||
pub fn load_or_create(config_dir: &Path, default_data_dir: &Path) -> Result<(Paths, Config), String> {
|
||||
fs::create_dir_all(config_dir)
|
||||
.map_err(|e| format!("Konfigurationsordner {} nicht anlegbar: {e}", config_dir.display()))?;
|
||||
|
||||
@ -75,7 +103,7 @@ pub fn load_or_create(config_dir: &Path, default_data_dir: &Path) -> Result<Path
|
||||
let paths = config.resolve(&config_file, default_data_dir);
|
||||
fs::create_dir_all(&paths.data_dir)
|
||||
.map_err(|e| format!("Datenordner {} nicht anlegbar: {e}", paths.data_dir.display()))?;
|
||||
Ok(paths)
|
||||
Ok((paths, config))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@ -95,6 +123,13 @@ mod tests {
|
||||
assert_eq!(c.tasks_dir, Some(PathBuf::from("/x/aufgaben")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sandbox_limits_werden_gelesen() {
|
||||
let c = Config::parse("sandbox_memory = \"4g\"\nsandbox_cpus = \"1\"\n").unwrap();
|
||||
assert_eq!(c.sandbox_limits(), Limits { memory: "4g".into(), cpus: "1".into() });
|
||||
assert_eq!(c.container_runtime, "podman");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unbekannter_schluessel_ist_fehler() {
|
||||
assert!(Config::parse("unbekannt = 1\n").is_err());
|
||||
@ -122,7 +157,7 @@ mod tests {
|
||||
let cfg_dir = base.join("cfg");
|
||||
let data_dir = base.join("data");
|
||||
|
||||
let paths = load_or_create(&cfg_dir, &data_dir).unwrap();
|
||||
let (paths, _) = load_or_create(&cfg_dir, &data_dir).unwrap();
|
||||
assert!(cfg_dir.join(CONFIG_FILE_NAME).exists());
|
||||
assert!(data_dir.is_dir());
|
||||
assert_eq!(paths.tasks_dir, data_dir.join("tasks"));
|
||||
|
||||
@ -1,4 +1,8 @@
|
||||
mod agent;
|
||||
mod config;
|
||||
mod runner;
|
||||
mod store;
|
||||
mod sandbox;
|
||||
mod tasks;
|
||||
|
||||
use config::Paths;
|
||||
@ -30,8 +34,9 @@ pub fn run() {
|
||||
.path()
|
||||
.app_data_dir()
|
||||
.map_err(|e| format!("Datenordner nicht ermittelbar: {e}"))?;
|
||||
let paths = config::load_or_create(&config_dir, &default_data_dir)?;
|
||||
let (paths, cfg) = config::load_or_create(&config_dir, &default_data_dir)?;
|
||||
app.manage(AppPaths(paths));
|
||||
app.manage(cfg);
|
||||
Ok(())
|
||||
})
|
||||
.invoke_handler(tauri::generate_handler![get_paths, load_tasks])
|
||||
|
||||
480
src-tauri/src/runner.rs
Normal file
480
src-tauri/src/runner.rs
Normal file
@ -0,0 +1,480 @@
|
||||
//! Runner: Batch aus Modellen, Aufgaben und Wiederholungen (F-05, SPEC Abschnitt 7).
|
||||
//!
|
||||
//! Die Modelle laufen nacheinander, weil ein Modell die GPU belegt. Jeder Lauf
|
||||
//! bekommt eine frische Sandbox, der Agent läuft, danach läuft `check.sh` im
|
||||
//! selben Container. Fertige Läufe stehen in der Datenbank und werden beim
|
||||
//! Fortsetzen übersprungen. Ein abgebrochener Lauf wird verworfen und nicht gespeichert.
|
||||
|
||||
use crate::agent::{
|
||||
run_agent_cancellable, AgentLimits, ErrorClass, Message, ModelClient, ModelError,
|
||||
OllamaClient, SandboxWorkspace,
|
||||
};
|
||||
use crate::sandbox::{container_name, remove_by_name, Limits, Sandbox};
|
||||
use crate::store::{RunRecord, Store};
|
||||
use crate::tasks::{Task, CHECK_FILE, START_DIR};
|
||||
use serde::Serialize;
|
||||
use serde_json::{json, Value};
|
||||
use std::path::PathBuf;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::time::Duration;
|
||||
|
||||
pub const CHECK_DIR: &str = "/checks";
|
||||
pub const WARMUP_TIMEOUT: Duration = Duration::from_secs(300);
|
||||
|
||||
/// Ein einzelner Lauf im Plan.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct Job {
|
||||
pub model: String,
|
||||
pub task: Task,
|
||||
pub repeat_idx: u32,
|
||||
}
|
||||
|
||||
/// Einstellungen für einen Batch.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct RunConfig {
|
||||
pub runtime: String,
|
||||
pub endpoint_url: String,
|
||||
pub data_dir: PathBuf,
|
||||
pub limits: Limits,
|
||||
}
|
||||
|
||||
/// Ereignisse für die Oberfläche.
|
||||
#[derive(Debug, Clone, PartialEq, Serialize)]
|
||||
#[serde(tag = "kind", rename_all = "snake_case")]
|
||||
pub enum Event {
|
||||
RunStarted { model: String, task: String, repeat: u32 },
|
||||
RunFinished { model: String, task: String, repeat: u32, class: ErrorClass, score: f64 },
|
||||
RunSkipped { model: String, task: String, repeat: u32 },
|
||||
ModelUnavailable { model: String, reason: String },
|
||||
Progress { done: usize, total: usize },
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Serialize)]
|
||||
pub struct BatchSummary {
|
||||
pub batch_id: i64,
|
||||
pub completed: usize,
|
||||
pub skipped: usize,
|
||||
pub cancelled: bool,
|
||||
}
|
||||
|
||||
/// Plan in fester Reihenfolge: Modell, dann Aufgabe, dann Wiederholung.
|
||||
pub fn plan(models: &[String], tasks: &[Task], repeats: u32) -> Vec<Job> {
|
||||
let mut jobs = Vec::new();
|
||||
for model in models {
|
||||
for task in tasks {
|
||||
for repeat_idx in 1..=repeats {
|
||||
jobs.push(Job {
|
||||
model: model.clone(),
|
||||
task: task.clone(),
|
||||
repeat_idx,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
jobs
|
||||
}
|
||||
|
||||
/// Ergebnis der Prüfung durch `check.sh`.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct CheckResult {
|
||||
pub score: f64,
|
||||
pub passed: bool,
|
||||
}
|
||||
|
||||
/// Wertet `check.sh` aus. Letzte Zeile als JSON `{"score": …}` gewinnt, sonst zählt der Exit-Code.
|
||||
pub fn evaluate_check(exit: Option<i32>, stdout: &str) -> CheckResult {
|
||||
let last = stdout.lines().rev().find(|l| !l.trim().is_empty()).unwrap_or("");
|
||||
if let Ok(Value::Object(obj)) = serde_json::from_str::<Value>(last.trim()) {
|
||||
if let Some(score) = obj.get("score").and_then(Value::as_f64) {
|
||||
let score = score.clamp(0.0, 1.0);
|
||||
return CheckResult { score, passed: score >= 1.0 };
|
||||
}
|
||||
}
|
||||
let passed = exit == Some(0);
|
||||
CheckResult { score: if passed { 1.0 } else { 0.0 }, passed }
|
||||
}
|
||||
|
||||
/// Fehlerklasse eines fertigen Laufs: zuerst die Agentenklasse, dann die Prüfung.
|
||||
pub fn final_class(agent: ErrorClass, check: &CheckResult) -> ErrorClass {
|
||||
if agent != ErrorClass::Ok {
|
||||
agent
|
||||
} else if !check.passed {
|
||||
ErrorClass::CheckFailed
|
||||
} else {
|
||||
ErrorClass::Ok
|
||||
}
|
||||
}
|
||||
|
||||
/// Startet einen Batch oder setzt einen bestehenden fort.
|
||||
/// `batch_id = None` legt einen neuen Batch an. Fertige Läufe werden übersprungen.
|
||||
pub fn run_batch(
|
||||
store: &mut Store,
|
||||
cfg: &RunConfig,
|
||||
batch_id: Option<i64>,
|
||||
note: &str,
|
||||
repeats: u32,
|
||||
jobs: &[Job],
|
||||
cancel: &AtomicBool,
|
||||
on_event: &dyn Fn(&Event),
|
||||
) -> Result<BatchSummary, String> {
|
||||
let config_json = json!({
|
||||
"runtime": cfg.runtime,
|
||||
"endpoint": cfg.endpoint_url,
|
||||
"limits": { "memory": cfg.limits.memory, "cpus": cfg.limits.cpus },
|
||||
"system_prompt": crate::agent::SYSTEM_PROMPT,
|
||||
"tool_output_chars": crate::agent::MAX_TOOL_OUTPUT_CHARS,
|
||||
"loop_repeats": crate::agent::LOOP_REPEATS,
|
||||
})
|
||||
.to_string();
|
||||
let batch_id = match batch_id {
|
||||
Some(id) => {
|
||||
if !store.batch_exists(id)? {
|
||||
return Err(format!("Batch {id} existiert nicht"));
|
||||
}
|
||||
id
|
||||
}
|
||||
None => store.create_batch(note, repeats, &config_json)?,
|
||||
};
|
||||
|
||||
let finished = store.finished_keys(batch_id)?;
|
||||
let total = jobs.len();
|
||||
let mut summary = BatchSummary { batch_id, completed: 0, skipped: 0, cancelled: false };
|
||||
let mut done = 0usize;
|
||||
|
||||
// Modelle in der Reihenfolge des Plans, jedes Modell nur einmal aufwärmen.
|
||||
let mut models: Vec<String> = Vec::new();
|
||||
for j in jobs {
|
||||
if !models.contains(&j.model) {
|
||||
models.push(j.model.clone());
|
||||
}
|
||||
}
|
||||
|
||||
'models: for model in &models {
|
||||
let client = OllamaClient::new(&cfg.endpoint_url, model)?;
|
||||
let warm = client.chat(
|
||||
&[Message::new("user", "ping")],
|
||||
&json!([]),
|
||||
WARMUP_TIMEOUT,
|
||||
);
|
||||
let unavailable = match warm {
|
||||
Ok(_) => None,
|
||||
Err(ModelError::Timeout) => Some("Aufwärmen hat das Zeitlimit überschritten".to_string()),
|
||||
Err(ModelError::Endpoint(e)) => Some(e),
|
||||
};
|
||||
if let Some(reason) = &unavailable {
|
||||
on_event(&Event::ModelUnavailable { model: model.clone(), reason: reason.clone() });
|
||||
}
|
||||
|
||||
for (i, job) in jobs.iter().enumerate().filter(|(_, j)| &j.model == model) {
|
||||
if cancel.load(Ordering::SeqCst) {
|
||||
summary.cancelled = true;
|
||||
break 'models;
|
||||
}
|
||||
let key = (job.model.clone(), job.task.meta.id.clone(), job.repeat_idx);
|
||||
if finished.contains(&key) {
|
||||
summary.skipped += 1;
|
||||
done += 1;
|
||||
on_event(&Event::RunSkipped {
|
||||
model: job.model.clone(),
|
||||
task: job.task.meta.id.clone(),
|
||||
repeat: job.repeat_idx,
|
||||
});
|
||||
on_event(&Event::Progress { done, total });
|
||||
continue;
|
||||
}
|
||||
|
||||
on_event(&Event::RunStarted {
|
||||
model: job.model.clone(),
|
||||
task: job.task.meta.id.clone(),
|
||||
repeat: job.repeat_idx,
|
||||
});
|
||||
|
||||
let fin = match &unavailable {
|
||||
// Modell nicht nutzbar: Lauf wird als endpoint_error gespeichert, ohne Container.
|
||||
Some(reason) => Finished {
|
||||
record: RunRecord {
|
||||
batch_id,
|
||||
model: job.model.clone(),
|
||||
task_id: job.task.meta.id.clone(),
|
||||
repeat_idx: job.repeat_idx,
|
||||
error_class: ErrorClass::EndpointError,
|
||||
score: 0.0,
|
||||
steps: 0,
|
||||
prompt_tokens: 0,
|
||||
completion_tokens: 0,
|
||||
duration_ms: 0,
|
||||
tps: None,
|
||||
ttft_tool_ms: None,
|
||||
artifact_path: None,
|
||||
summary: None,
|
||||
check_output: reason.clone(),
|
||||
},
|
||||
transcript: vec![],
|
||||
},
|
||||
None => match execute_job(cfg, batch_id, i, job, &client, cancel)? {
|
||||
JobResult::Cancelled => {
|
||||
summary.cancelled = true;
|
||||
break 'models;
|
||||
}
|
||||
JobResult::Finished(f) => f,
|
||||
},
|
||||
};
|
||||
|
||||
on_event(&Event::RunFinished {
|
||||
model: job.model.clone(),
|
||||
task: job.task.meta.id.clone(),
|
||||
repeat: job.repeat_idx,
|
||||
class: fin.record.error_class,
|
||||
score: fin.record.score,
|
||||
});
|
||||
store.insert_run(&fin.record, &fin.transcript)?;
|
||||
summary.completed += 1;
|
||||
done += 1;
|
||||
on_event(&Event::Progress { done, total });
|
||||
}
|
||||
}
|
||||
|
||||
if summary.cancelled {
|
||||
on_event(&Event::Progress { done, total });
|
||||
}
|
||||
Ok(summary)
|
||||
}
|
||||
|
||||
struct Finished {
|
||||
record: RunRecord,
|
||||
transcript: Vec<Message>,
|
||||
}
|
||||
|
||||
enum JobResult {
|
||||
Finished(Finished),
|
||||
Cancelled,
|
||||
}
|
||||
|
||||
fn execute_job(
|
||||
cfg: &RunConfig,
|
||||
batch_id: i64,
|
||||
seq: usize,
|
||||
job: &Job,
|
||||
client: &OllamaClient,
|
||||
cancel: &AtomicBool,
|
||||
) -> Result<JobResult, String> {
|
||||
let meta = &job.task.meta;
|
||||
let name = container_name(&format!("{batch_id}-{seq}"));
|
||||
remove_by_name(&cfg.runtime, &name);
|
||||
|
||||
let start_dir = job.task.dir.join(START_DIR);
|
||||
let start_arg = if start_dir.is_dir() { Some(start_dir.as_path()) } else { None };
|
||||
let sb = Sandbox::start(&cfg.runtime, &name, &meta.image, &cfg.limits, start_arg)?;
|
||||
let ws = SandboxWorkspace { sandbox: &sb };
|
||||
|
||||
let limits = AgentLimits {
|
||||
max_steps: meta.max_steps,
|
||||
timeout: Duration::from_secs(meta.timeout_s),
|
||||
};
|
||||
let prompt = std::fs::read_to_string(job.task.dir.join("prompt.md"))
|
||||
.map_err(|e| format!("prompt.md nicht lesbar: {e}"))?;
|
||||
let outcome = run_agent_cancellable(client, &ws, &prompt, &limits, cancel);
|
||||
if outcome.cancelled {
|
||||
sb.remove()?;
|
||||
return Ok(JobResult::Cancelled);
|
||||
}
|
||||
|
||||
// check.sh läuft im selben Container, aber außerhalb von /work.
|
||||
let check_output = sb
|
||||
.exec(&format!("mkdir -p {CHECK_DIR}"), Duration::from_secs(30))
|
||||
.and_then(|_| sb.copy_in(&job.task.dir.join(CHECK_FILE), &format!("{CHECK_DIR}/check.sh")))
|
||||
.and_then(|_| {
|
||||
sb.exec(
|
||||
&format!("cd /work && sh {CHECK_DIR}/check.sh"),
|
||||
Duration::from_secs(meta.check_timeout_s),
|
||||
)
|
||||
});
|
||||
let (check, check_text) = match check_output {
|
||||
Ok(out) => {
|
||||
let text = format!(
|
||||
"exit {}{}\n{}{}",
|
||||
out.exit_code.map_or("?".into(), |c| c.to_string()),
|
||||
if out.timed_out { " (Zeitlimit)" } else { "" },
|
||||
out.stdout,
|
||||
out.stderr
|
||||
);
|
||||
let check = if out.timed_out {
|
||||
CheckResult { score: 0.0, passed: false }
|
||||
} else {
|
||||
evaluate_check(out.exit_code, &out.stdout)
|
||||
};
|
||||
(check, text)
|
||||
}
|
||||
Err(e) => (CheckResult { score: 0.0, passed: false }, format!("Prüfung nicht ausführbar: {e}")),
|
||||
};
|
||||
|
||||
let artifact = cfg
|
||||
.data_dir
|
||||
.join("runs")
|
||||
.join(batch_id.to_string())
|
||||
.join(format!("{}-{}-{}", job.model.replace([':', '/'], "_"), meta.id, job.repeat_idx));
|
||||
let artifact_path = match sb.export_work(&artifact.join("work")) {
|
||||
Ok(()) => Some(artifact.join("work").display().to_string()),
|
||||
Err(_) => None,
|
||||
};
|
||||
sb.remove()?;
|
||||
|
||||
let class = final_class(outcome.class, &check);
|
||||
let secs = outcome.duration_ms as f64 / 1000.0;
|
||||
let tps = if outcome.completion_tokens > 0 && secs > 0.0 {
|
||||
Some(outcome.completion_tokens as f64 / secs)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let record = RunRecord {
|
||||
batch_id,
|
||||
model: job.model.clone(),
|
||||
task_id: meta.id.clone(),
|
||||
repeat_idx: job.repeat_idx,
|
||||
error_class: class,
|
||||
score: check.score,
|
||||
steps: outcome.steps,
|
||||
prompt_tokens: outcome.prompt_tokens,
|
||||
completion_tokens: outcome.completion_tokens,
|
||||
duration_ms: outcome.duration_ms,
|
||||
tps,
|
||||
ttft_tool_ms: outcome.time_to_first_tool_ms,
|
||||
artifact_path,
|
||||
summary: outcome.summary.clone(),
|
||||
check_output: check_text,
|
||||
};
|
||||
Ok(JobResult::Finished(Finished {
|
||||
record,
|
||||
transcript: outcome.transcript,
|
||||
}))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::tasks::TaskToml;
|
||||
|
||||
fn task(id: &str) -> Task {
|
||||
Task {
|
||||
meta: TaskToml {
|
||||
id: id.into(),
|
||||
title: id.into(),
|
||||
group: "A".into(),
|
||||
weight: 1.0,
|
||||
image: "cb-python:latest".into(),
|
||||
max_steps: 5,
|
||||
timeout_s: 60,
|
||||
check_timeout_s: 30,
|
||||
},
|
||||
dir: PathBuf::from("/x"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plan_reihenfolge_modell_aufgabe_wiederholung() {
|
||||
let jobs = plan(
|
||||
&["m1".into(), "m2".into()],
|
||||
&[task("a-01"), task("b-04")],
|
||||
2,
|
||||
);
|
||||
assert_eq!(jobs.len(), 8);
|
||||
let keys: Vec<(String, String, u32)> = jobs
|
||||
.iter()
|
||||
.map(|j| (j.model.clone(), j.task.meta.id.clone(), j.repeat_idx))
|
||||
.collect();
|
||||
assert_eq!(keys[0], ("m1".into(), "a-01".into(), 1));
|
||||
assert_eq!(keys[1], ("m1".into(), "a-01".into(), 2));
|
||||
assert_eq!(keys[2], ("m1".into(), "b-04".into(), 1));
|
||||
assert_eq!(keys[4], ("m2".into(), "a-01".into(), 1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn check_json_score_gewinnt() {
|
||||
let r = evaluate_check(Some(0), "viel text\n{\"score\": 0.5, \"notes\": \"halb\"}\n");
|
||||
assert_eq!(r, CheckResult { score: 0.5, passed: false });
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn check_ohne_json_zaehlt_exit_code() {
|
||||
assert_eq!(evaluate_check(Some(0), "ok"), CheckResult { score: 1.0, passed: true });
|
||||
assert_eq!(evaluate_check(Some(1), "fehler"), CheckResult { score: 0.0, passed: false });
|
||||
assert_eq!(evaluate_check(None, ""), CheckResult { score: 0.0, passed: false });
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn check_score_wird_begrenzt() {
|
||||
let r = evaluate_check(Some(0), "{\"score\": 3.0}");
|
||||
assert_eq!(r.score, 1.0);
|
||||
assert!(r.passed);
|
||||
}
|
||||
|
||||
/// Kleiner Batch end-to-end: echtes Modell, echte Sandbox, Fortsetzen über die Datenbank.
|
||||
/// `CB_OLLAMA_URL=… CB_OLLAMA_MODEL=… CB_TEST_IMAGE=cb-python:latest cargo test batch_end_zu_end -- --ignored --nocapture`
|
||||
#[test]
|
||||
#[ignore]
|
||||
fn batch_end_zu_end() {
|
||||
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 base = std::env::temp_dir().join(format!("cb-batch-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
let task_dir = base.join("tasks").join("A").join("a-test");
|
||||
std::fs::create_dir_all(task_dir.join("start")).unwrap();
|
||||
std::fs::write(
|
||||
task_dir.join("task.toml"),
|
||||
format!("id = \"a-test\"\ntitle = \"Datei schreiben\"\ngroup = \"A\"\nimage = \"{image}\"\nmax_steps = 6\ntimeout_s = 300\ncheck_timeout_s = 60\n"),
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::write(task_dir.join("prompt.md"), "Erstelle die Datei out.txt mit dem Inhalt hallo (ohne Zeilenumbruch). Rufe danach done auf.").unwrap();
|
||||
std::fs::write(task_dir.join("check.sh"), "#!/bin/sh\n[ \"$(cat /work/out.txt)\" = \"hallo\" ]\n").unwrap();
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
std::fs::set_permissions(task_dir.join("check.sh"), std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
}
|
||||
|
||||
let (tasks, errs) = {
|
||||
let r = crate::tasks::load_all(&base.join("tasks"));
|
||||
(r.tasks, r.errors)
|
||||
};
|
||||
assert!(errs.is_empty(), "{errs:?}");
|
||||
let jobs = plan(&[model.clone()], &tasks, 2);
|
||||
let cfg = RunConfig {
|
||||
runtime: "podman".into(),
|
||||
endpoint_url: url,
|
||||
data_dir: base.join("data"),
|
||||
limits: Limits::default(),
|
||||
};
|
||||
let mut store = Store::open_in_memory().unwrap();
|
||||
let cancel = AtomicBool::new(false);
|
||||
let events = std::cell::RefCell::new(Vec::new());
|
||||
let on = |e: &Event| events.borrow_mut().push(e.clone());
|
||||
|
||||
let first = run_batch(&mut store, &cfg, None, "e2e", 2, &jobs, &cancel, &on).unwrap();
|
||||
eprintln!("erster Lauf: {first:?}");
|
||||
assert_eq!(first.completed, 2);
|
||||
assert_eq!(first.skipped, 0);
|
||||
|
||||
// Fortsetzen mit demselben Batch: nichts läuft erneut.
|
||||
let second = run_batch(&mut store, &cfg, Some(first.batch_id), "", 2, &jobs, &cancel, &on).unwrap();
|
||||
eprintln!("zweiter Lauf: {second:?}");
|
||||
assert_eq!(second.completed, 0);
|
||||
assert_eq!(second.skipped, 2);
|
||||
assert_eq!(store.run_count(first.batch_id).unwrap(), 2);
|
||||
|
||||
for e in events.borrow().iter() {
|
||||
eprintln!("{}", serde_json::to_string(e).unwrap());
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn klasse_agent_vor_pruefung() {
|
||||
let ok = CheckResult { score: 1.0, passed: true };
|
||||
let bad = CheckResult { score: 0.0, passed: false };
|
||||
assert_eq!(final_class(ErrorClass::MaxSteps, &ok), ErrorClass::MaxSteps);
|
||||
assert_eq!(final_class(ErrorClass::Ok, &bad), ErrorClass::CheckFailed);
|
||||
assert_eq!(final_class(ErrorClass::Ok, &ok), ErrorClass::Ok);
|
||||
}
|
||||
}
|
||||
319
src-tauri/src/sandbox.rs
Normal file
319
src-tauri/src/sandbox.rs
Normal file
@ -0,0 +1,319 @@
|
||||
//! Sandbox pro Lauf (F-04, SPEC Abschnitt 6).
|
||||
//!
|
||||
//! Jeder Lauf bekommt einen frischen Podman-Container ohne Netzwerk. Die Aufgabe
|
||||
//! wird nach `/work` kopiert, Befehle laufen per `podman exec`, und am Ende wird
|
||||
//! `/work` herausgeholt und der Container entfernt. Podman wird über die CLI
|
||||
//! angesprochen (rootless, Docker-kompatible Befehle).
|
||||
|
||||
use std::io::Read;
|
||||
use std::path::Path;
|
||||
use std::process::{Command, Stdio};
|
||||
use std::thread;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
pub const WORK_DIR: &str = "/work";
|
||||
|
||||
/// Ressourcenlimits eines Containers.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct Limits {
|
||||
/// Speicherlimit, Podman-Schreibweise, z. B. `2g`.
|
||||
pub memory: String,
|
||||
/// CPU-Anteil, z. B. `2`.
|
||||
pub cpus: String,
|
||||
}
|
||||
|
||||
impl Default for Limits {
|
||||
fn default() -> Self {
|
||||
Limits {
|
||||
memory: "2g".into(),
|
||||
cpus: "2".into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Ergebnis eines Befehls im Container.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct ExecOutput {
|
||||
pub exit_code: Option<i32>,
|
||||
pub stdout: String,
|
||||
pub stderr: String,
|
||||
pub timed_out: bool,
|
||||
}
|
||||
|
||||
/// Argumente für `podman run`. Reine Funktion, damit sie testbar ist.
|
||||
pub fn run_args(name: &str, image: &str, limits: &Limits) -> Vec<String> {
|
||||
vec![
|
||||
"run".into(),
|
||||
"-d".into(),
|
||||
"--name".into(),
|
||||
name.into(),
|
||||
"--network".into(),
|
||||
"none".into(),
|
||||
"--memory".into(),
|
||||
limits.memory.clone(),
|
||||
"--cpus".into(),
|
||||
limits.cpus.clone(),
|
||||
"--pids-limit".into(),
|
||||
"512".into(),
|
||||
"--label".into(),
|
||||
"coding-bench=lauf".into(),
|
||||
image.into(),
|
||||
"sleep".into(),
|
||||
"infinity".into(),
|
||||
]
|
||||
}
|
||||
|
||||
/// Eindeutiger Containername pro Lauf.
|
||||
pub fn container_name(run_id: &str) -> String {
|
||||
format!("cb-{run_id}")
|
||||
}
|
||||
|
||||
/// Ein laufender Sandbox-Container. Wird beim Verwerfen entfernt.
|
||||
pub struct Sandbox {
|
||||
runtime: String,
|
||||
name: String,
|
||||
removed: bool,
|
||||
}
|
||||
|
||||
impl Sandbox {
|
||||
/// Startet den Container und kopiert optional das Startverzeichnis nach `/work`.
|
||||
pub fn start(
|
||||
runtime: &str,
|
||||
name: &str,
|
||||
image: &str,
|
||||
limits: &Limits,
|
||||
start_dir: Option<&Path>,
|
||||
) -> Result<Sandbox, String> {
|
||||
let sb = Sandbox {
|
||||
runtime: runtime.into(),
|
||||
name: name.into(),
|
||||
removed: false,
|
||||
};
|
||||
|
||||
let out = Command::new(runtime)
|
||||
.args(run_args(name, image, limits))
|
||||
.output()
|
||||
.map_err(|e| format!("{runtime} nicht startbar: {e}"))?;
|
||||
if !out.status.success() {
|
||||
return Err(format!(
|
||||
"Container konnte nicht gestartet werden: {}",
|
||||
String::from_utf8_lossy(&out.stderr).trim()
|
||||
));
|
||||
}
|
||||
// Ab hier räumt Drop den Container auf, auch wenn der Rest fehlschlägt.
|
||||
let mut sb = sb;
|
||||
|
||||
// Ohne `-w`, weil /work noch nicht existiert.
|
||||
let mkdir = sb.exec_in(None, &format!("mkdir -p {WORK_DIR}"), Duration::from_secs(30))?;
|
||||
if mkdir.exit_code != Some(0) {
|
||||
return Err(format!("{WORK_DIR} nicht anlegbar: {}", mkdir.stderr.trim()));
|
||||
}
|
||||
|
||||
if let Some(src) = start_dir {
|
||||
let src_spec = format!("{}/.", src.display());
|
||||
let dst_spec = format!("{}:{WORK_DIR}/", sb.name);
|
||||
let cp = Command::new(runtime)
|
||||
.args(["cp", &src_spec, &dst_spec])
|
||||
.output()
|
||||
.map_err(|e| format!("podman cp fehlgeschlagen: {e}"))?;
|
||||
if !cp.status.success() {
|
||||
return Err(format!(
|
||||
"Startdateien nicht kopierbar: {}",
|
||||
String::from_utf8_lossy(&cp.stderr).trim()
|
||||
));
|
||||
}
|
||||
}
|
||||
Ok(sb)
|
||||
}
|
||||
|
||||
pub fn name(&self) -> &str {
|
||||
&self.name
|
||||
}
|
||||
|
||||
/// Führt `command` per `sh -c` in `/work` aus. Nach `timeout` wird der
|
||||
/// Client-Prozess beendet und `timed_out` gesetzt.
|
||||
pub fn exec(&self, command: &str, timeout: Duration) -> Result<ExecOutput, String> {
|
||||
self.exec_in(Some(WORK_DIR), command, timeout)
|
||||
}
|
||||
|
||||
fn exec_in(&self, workdir: Option<&str>, command: &str, timeout: Duration) -> Result<ExecOutput, String> {
|
||||
let mut args: Vec<&str> = vec!["exec"];
|
||||
if let Some(w) = workdir {
|
||||
args.extend(["-w", w]);
|
||||
}
|
||||
args.extend([self.name.as_str(), "sh", "-c", command]);
|
||||
let mut child = Command::new(&self.runtime)
|
||||
.args(&args)
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.spawn()
|
||||
.map_err(|e| format!("podman exec fehlgeschlagen: {e}"))?;
|
||||
|
||||
// Pipes in eigenen Threads lesen, sonst blockiert ein volles Ausgabepuffer.
|
||||
let mut stdout = child.stdout.take().expect("stdout ist gepiped");
|
||||
let mut stderr = child.stderr.take().expect("stderr ist gepiped");
|
||||
let t_out = thread::spawn(move || {
|
||||
let mut s = String::new();
|
||||
let _ = stdout.read_to_string(&mut s);
|
||||
s
|
||||
});
|
||||
let t_err = thread::spawn(move || {
|
||||
let mut s = String::new();
|
||||
let _ = stderr.read_to_string(&mut s);
|
||||
s
|
||||
});
|
||||
|
||||
let start = Instant::now();
|
||||
let (status, timed_out) = loop {
|
||||
if let Some(status) = child.try_wait().map_err(|e| e.to_string())? {
|
||||
break (Some(status), false);
|
||||
}
|
||||
if start.elapsed() >= timeout {
|
||||
let _ = child.kill();
|
||||
let status = child.wait().ok();
|
||||
break (status, true);
|
||||
}
|
||||
thread::sleep(Duration::from_millis(50));
|
||||
};
|
||||
|
||||
Ok(ExecOutput {
|
||||
exit_code: status.and_then(|s| s.code()),
|
||||
stdout: t_out.join().unwrap_or_default(),
|
||||
stderr: t_err.join().unwrap_or_default(),
|
||||
timed_out,
|
||||
})
|
||||
}
|
||||
|
||||
/// Kopiert `/work` in den Zielordner (Artefakt).
|
||||
pub fn export_work(&self, dest: &Path) -> Result<(), String> {
|
||||
std::fs::create_dir_all(dest).map_err(|e| format!("Zielordner nicht anlegbar: {e}"))?;
|
||||
let src_spec = format!("{}:{WORK_DIR}/.", self.name);
|
||||
let dst_spec = dest.display().to_string();
|
||||
let out = Command::new(&self.runtime)
|
||||
.args(["cp", &src_spec, &dst_spec])
|
||||
.output()
|
||||
.map_err(|e| format!("podman cp fehlgeschlagen: {e}"))?;
|
||||
if !out.status.success() {
|
||||
return Err(format!(
|
||||
"/work nicht exportierbar: {}",
|
||||
String::from_utf8_lossy(&out.stderr).trim()
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Kopiert eine einzelne Datei in den Container (z. B. `check.sh`, nicht in `/work`).
|
||||
pub fn copy_in(&self, src: &Path, dst: &str) -> Result<(), String> {
|
||||
let dst_spec = format!("{}:{dst}", self.name);
|
||||
let out = Command::new(&self.runtime)
|
||||
.args(["cp", &src.display().to_string(), &dst_spec])
|
||||
.output()
|
||||
.map_err(|e| format!("podman cp fehlgeschlagen: {e}"))?;
|
||||
if out.status.success() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(String::from_utf8_lossy(&out.stderr).trim().to_string())
|
||||
}
|
||||
}
|
||||
|
||||
/// Entfernt den Container. Fehler werden zurückgegeben, nicht verschluckt.
|
||||
pub fn remove(mut self) -> Result<(), String> {
|
||||
self.remove_inner()
|
||||
}
|
||||
|
||||
fn remove_inner(&mut self) -> Result<(), String> {
|
||||
if self.removed {
|
||||
return Ok(());
|
||||
}
|
||||
self.removed = true;
|
||||
let out = Command::new(&self.runtime)
|
||||
.args(["rm", "-f", &self.name])
|
||||
.output()
|
||||
.map_err(|e| format!("podman rm fehlgeschlagen: {e}"))?;
|
||||
if out.status.success() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(String::from_utf8_lossy(&out.stderr).trim().to_string())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Entfernt einen Container nach Name, falls ein früherer Lauf ihn hinterlassen hat.
|
||||
pub fn remove_by_name(runtime: &str, name: &str) {
|
||||
let _ = Command::new(runtime).args(["rm", "-f", name]).output();
|
||||
}
|
||||
|
||||
impl Drop for Sandbox {
|
||||
fn drop(&mut self) {
|
||||
let _ = self.remove_inner();
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn run_args_enthalten_netzwerk_aus_und_limits() {
|
||||
let args = run_args("cb-x", "img:1", &Limits::default());
|
||||
let s = args.join(" ");
|
||||
assert!(s.contains("--network none"));
|
||||
assert!(s.contains("--memory 2g"));
|
||||
assert!(s.contains("--cpus 2"));
|
||||
assert!(s.ends_with("img:1 sleep infinity"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn containername_ist_praefixiert() {
|
||||
assert_eq!(container_name("42"), "cb-42");
|
||||
}
|
||||
|
||||
/// Echter Lauf gegen Podman. Braucht ein lokales Image mit `sleep` und `sh`
|
||||
/// und ist deshalb ignoriert. Ausführen mit:
|
||||
/// `CB_TEST_IMAGE=docker.io/library/python:3.12-slim cargo test -- --ignored`
|
||||
#[test]
|
||||
#[ignore]
|
||||
fn echter_lauf_ohne_netz_und_aufraeumen() {
|
||||
let image = std::env::var("CB_TEST_IMAGE").expect("CB_TEST_IMAGE setzen");
|
||||
let base = std::env::temp_dir().join(format!("cb-sandbox-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
let start_dir = base.join("start");
|
||||
std::fs::create_dir_all(&start_dir).unwrap();
|
||||
std::fs::write(start_dir.join("eingabe.txt"), "hallo").unwrap();
|
||||
|
||||
let name = container_name(&format!("test-{}", std::process::id()));
|
||||
let sb = Sandbox::start("podman", &name, &image, &Limits::default(), Some(&start_dir))
|
||||
.expect("Start");
|
||||
|
||||
// Startdatei liegt in /work.
|
||||
let r = sb.exec("cat eingabe.txt", Duration::from_secs(30)).unwrap();
|
||||
assert_eq!(r.stdout, "hallo");
|
||||
|
||||
// Kein Netz: Verbindung muss scheitern.
|
||||
let r = sb
|
||||
.exec(
|
||||
"python3 -c 'import socket; socket.create_connection((\"1.1.1.1\", 80), timeout=3)'",
|
||||
Duration::from_secs(30),
|
||||
)
|
||||
.unwrap();
|
||||
assert_ne!(r.exit_code, Some(0), "Netz sollte aus sein: {}", r.stderr);
|
||||
|
||||
// Timeout wird erkannt.
|
||||
let r = sb.exec("sleep 10", Duration::from_secs(1)).unwrap();
|
||||
assert!(r.timed_out);
|
||||
|
||||
// Artefakt herausholen.
|
||||
let art = base.join("artefakt");
|
||||
sb.export_work(&art).unwrap();
|
||||
assert_eq!(std::fs::read_to_string(art.join("eingabe.txt")).unwrap(), "hallo");
|
||||
|
||||
sb.remove().unwrap();
|
||||
let ps = Command::new("podman")
|
||||
.args(["ps", "-a", "--filter", &format!("name={name}"), "--format", "{{.Names}}"])
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(String::from_utf8_lossy(&ps.stdout).trim().is_empty(), "Container nicht entfernt");
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
}
|
||||
}
|
||||
257
src-tauri/src/store.rs
Normal file
257
src-tauri/src/store.rs
Normal file
@ -0,0 +1,257 @@
|
||||
//! SQLite-Speicher für Batches, Läufe und Schritte (F-06, SPEC Abschnitt 8).
|
||||
|
||||
use crate::agent::{ErrorClass, Message};
|
||||
use rusqlite::{params, Connection, OptionalExtension};
|
||||
use serde::Serialize;
|
||||
use std::collections::HashSet;
|
||||
use std::path::Path;
|
||||
|
||||
const SCHEMA: &str = "
|
||||
CREATE TABLE IF NOT EXISTS batch (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
created_at TEXT NOT NULL DEFAULT (datetime('now')),
|
||||
note TEXT NOT NULL DEFAULT '',
|
||||
repeats INTEGER NOT NULL,
|
||||
config_json TEXT NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS run (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
batch_id INTEGER NOT NULL REFERENCES batch(id),
|
||||
model TEXT NOT NULL,
|
||||
task_id TEXT NOT NULL,
|
||||
repeat_idx INTEGER NOT NULL,
|
||||
status TEXT NOT NULL,
|
||||
error_class TEXT NOT NULL,
|
||||
score REAL NOT NULL,
|
||||
steps INTEGER NOT NULL,
|
||||
prompt_tokens INTEGER NOT NULL,
|
||||
completion_tokens INTEGER NOT NULL,
|
||||
duration_ms INTEGER NOT NULL,
|
||||
tps REAL,
|
||||
ttft_tool_ms INTEGER,
|
||||
started_at TEXT NOT NULL DEFAULT (datetime('now')),
|
||||
artifact_path TEXT,
|
||||
summary TEXT,
|
||||
check_output TEXT
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS run_batch ON run(batch_id, model, task_id, repeat_idx);
|
||||
CREATE TABLE IF NOT EXISTS step (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
run_id INTEGER NOT NULL REFERENCES run(id),
|
||||
idx INTEGER NOT NULL,
|
||||
role TEXT NOT NULL,
|
||||
content TEXT NOT NULL,
|
||||
tool_name TEXT,
|
||||
tool_args_json TEXT,
|
||||
tool_result TEXT,
|
||||
tokens INTEGER,
|
||||
duration_ms INTEGER
|
||||
);
|
||||
";
|
||||
|
||||
/// Ein abgeschlossener Lauf, so wie er gespeichert wird.
|
||||
#[derive(Debug, Clone, PartialEq, Serialize)]
|
||||
pub struct RunRecord {
|
||||
pub batch_id: i64,
|
||||
pub model: String,
|
||||
pub task_id: String,
|
||||
pub repeat_idx: u32,
|
||||
pub error_class: ErrorClass,
|
||||
pub score: f64,
|
||||
pub steps: u32,
|
||||
pub prompt_tokens: u32,
|
||||
pub completion_tokens: u32,
|
||||
pub duration_ms: u128,
|
||||
pub tps: Option<f64>,
|
||||
pub ttft_tool_ms: Option<u128>,
|
||||
pub artifact_path: Option<String>,
|
||||
pub summary: Option<String>,
|
||||
pub check_output: String,
|
||||
}
|
||||
|
||||
pub struct Store {
|
||||
conn: Connection,
|
||||
}
|
||||
|
||||
impl Store {
|
||||
pub fn open(path: &Path) -> Result<Store, String> {
|
||||
let conn = Connection::open(path).map_err(|e| format!("Datenbank nicht öffenbar: {e}"))?;
|
||||
Self::init(conn)
|
||||
}
|
||||
|
||||
pub fn open_in_memory() -> Result<Store, String> {
|
||||
let conn = Connection::open_in_memory().map_err(|e| e.to_string())?;
|
||||
Self::init(conn)
|
||||
}
|
||||
|
||||
fn init(conn: Connection) -> Result<Store, String> {
|
||||
conn.execute_batch("PRAGMA foreign_keys = ON;")
|
||||
.and_then(|_| conn.execute_batch(SCHEMA))
|
||||
.map_err(|e| format!("Schema nicht anlegbar: {e}"))?;
|
||||
Ok(Store { conn })
|
||||
}
|
||||
|
||||
pub fn create_batch(&self, note: &str, repeats: u32, config_json: &str) -> Result<i64, String> {
|
||||
self.conn
|
||||
.execute(
|
||||
"INSERT INTO batch (note, repeats, config_json) VALUES (?1, ?2, ?3)",
|
||||
params![note, repeats, config_json],
|
||||
)
|
||||
.map_err(|e| e.to_string())?;
|
||||
Ok(self.conn.last_insert_rowid())
|
||||
}
|
||||
|
||||
pub fn batch_exists(&self, batch_id: i64) -> Result<bool, String> {
|
||||
self.conn
|
||||
.query_row("SELECT 1 FROM batch WHERE id = ?1", params![batch_id], |_| Ok(()))
|
||||
.optional()
|
||||
.map(|r| r.is_some())
|
||||
.map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// Schlüssel (Modell, Aufgabe, Wiederholung) aller bereits gespeicherten Läufe eines Batches.
|
||||
pub fn finished_keys(&self, batch_id: i64) -> Result<HashSet<(String, String, u32)>, String> {
|
||||
let mut stmt = self
|
||||
.conn
|
||||
.prepare("SELECT model, task_id, repeat_idx FROM run WHERE batch_id = ?1")
|
||||
.map_err(|e| e.to_string())?;
|
||||
let rows = stmt
|
||||
.query_map(params![batch_id], |r| {
|
||||
Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?, r.get::<_, u32>(2)?))
|
||||
})
|
||||
.map_err(|e| e.to_string())?;
|
||||
rows.collect::<Result<HashSet<_>, _>>().map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// Speichert einen Lauf mit seinen Schritten in einer Transaktion.
|
||||
pub fn insert_run(&mut self, rec: &RunRecord, transcript: &[Message]) -> Result<i64, String> {
|
||||
let tx = self.conn.transaction().map_err(|e| e.to_string())?;
|
||||
let class = serde_json::to_value(rec.error_class)
|
||||
.ok()
|
||||
.and_then(|v| v.as_str().map(String::from))
|
||||
.unwrap_or_default();
|
||||
tx.execute(
|
||||
"INSERT INTO run (batch_id, model, task_id, repeat_idx, status, error_class, score,
|
||||
steps, prompt_tokens, completion_tokens, duration_ms, tps, ttft_tool_ms,
|
||||
artifact_path, summary, check_output)
|
||||
VALUES (?1, ?2, ?3, ?4, 'done', ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15)",
|
||||
params![
|
||||
rec.batch_id,
|
||||
rec.model,
|
||||
rec.task_id,
|
||||
rec.repeat_idx,
|
||||
class,
|
||||
rec.score,
|
||||
rec.steps,
|
||||
rec.prompt_tokens,
|
||||
rec.completion_tokens,
|
||||
rec.duration_ms as i64,
|
||||
rec.tps,
|
||||
rec.ttft_tool_ms.map(|v| v as i64),
|
||||
rec.artifact_path,
|
||||
rec.summary,
|
||||
rec.check_output,
|
||||
],
|
||||
)
|
||||
.map_err(|e| e.to_string())?;
|
||||
let run_id = tx.last_insert_rowid();
|
||||
for (idx, m) in transcript.iter().enumerate() {
|
||||
let (args, tool_name) = match m.tool_calls.first() {
|
||||
Some(c) => (Some(c.function.arguments.to_string()), Some(c.function.name.clone())),
|
||||
None => (None, m.tool_name.clone()),
|
||||
};
|
||||
tx.execute(
|
||||
"INSERT INTO step (run_id, idx, role, content, tool_name, tool_args_json, tool_result)
|
||||
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
|
||||
params![
|
||||
run_id,
|
||||
idx as i64,
|
||||
m.role,
|
||||
m.content,
|
||||
tool_name,
|
||||
args,
|
||||
if m.role == "tool" { Some(m.content.clone()) } else { None },
|
||||
],
|
||||
)
|
||||
.map_err(|e| e.to_string())?;
|
||||
}
|
||||
tx.commit().map_err(|e| e.to_string())?;
|
||||
Ok(run_id)
|
||||
}
|
||||
|
||||
pub fn run_count(&self, batch_id: i64) -> Result<i64, String> {
|
||||
self.conn
|
||||
.query_row("SELECT COUNT(*) FROM run WHERE batch_id = ?1", params![batch_id], |r| r.get(0))
|
||||
.map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
pub fn step_count(&self, run_id: i64) -> Result<i64, String> {
|
||||
self.conn
|
||||
.query_row("SELECT COUNT(*) FROM step WHERE run_id = ?1", params![run_id], |r| r.get(0))
|
||||
.map_err(|e| e.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::agent::{FunctionCall, ToolCall};
|
||||
use serde_json::json;
|
||||
|
||||
fn rec(batch: i64, model: &str, task: &str, rep: u32) -> RunRecord {
|
||||
RunRecord {
|
||||
batch_id: batch,
|
||||
model: model.into(),
|
||||
task_id: task.into(),
|
||||
repeat_idx: rep,
|
||||
error_class: ErrorClass::Ok,
|
||||
score: 1.0,
|
||||
steps: 2,
|
||||
prompt_tokens: 10,
|
||||
completion_tokens: 5,
|
||||
duration_ms: 1234,
|
||||
tps: Some(4.0),
|
||||
ttft_tool_ms: Some(300),
|
||||
artifact_path: None,
|
||||
summary: Some("fertig".into()),
|
||||
check_output: "ok".into(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn batch_und_lauf_werden_gespeichert() {
|
||||
let mut s = Store::open_in_memory().unwrap();
|
||||
let b = s.create_batch("test", 3, "{}").unwrap();
|
||||
assert!(s.batch_exists(b).unwrap());
|
||||
let transcript = vec![
|
||||
Message::new("user", "Aufgabe"),
|
||||
Message {
|
||||
role: "assistant".into(),
|
||||
content: String::new(),
|
||||
tool_calls: vec![ToolCall {
|
||||
function: FunctionCall { name: "done".into(), arguments: json!({"summary": "x"}) },
|
||||
}],
|
||||
tool_name: None,
|
||||
},
|
||||
];
|
||||
let run_id = s.insert_run(&rec(b, "m1", "a-01", 1), &transcript).unwrap();
|
||||
assert_eq!(s.run_count(b).unwrap(), 1);
|
||||
assert_eq!(s.step_count(run_id).unwrap(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fertige_schluessel_werden_gelesen() {
|
||||
let mut s = Store::open_in_memory().unwrap();
|
||||
let b = s.create_batch("", 2, "{}").unwrap();
|
||||
s.insert_run(&rec(b, "m1", "a-01", 1), &[]).unwrap();
|
||||
let keys = s.finished_keys(b).unwrap();
|
||||
assert!(keys.contains(&("m1".to_string(), "a-01".to_string(), 1)));
|
||||
assert!(!keys.contains(&("m1".to_string(), "a-01".to_string(), 2)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unbekannter_batch_existiert_nicht() {
|
||||
let s = Store::open_in_memory().unwrap();
|
||||
assert!(!s.batch_exists(99).unwrap());
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user