From 930857bc80458ee4473f698abfb0bfd722d8aaf2 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Wed, 18 Nov 2026 00:23:41 +0000 Subject: [PATCH] Send hard invoice PDFs to Claude when an Anthropic key is set. ANTHROPIC_API_KEY selects the Messages API (claude-haiku-5-5 by default) ahead of OpenRouter and local ppmlx. The PDF goes up as a base64 document, the 12-field schema stays the same, and llm_attempts stays per model with token counts when the response includes them. Co-authored-by: wydrox --- README.md | 13 +- src/anthropic.rs | 317 ++++++++++++++++++++++++++++++++++++++ src/credentials.rs | 15 +- src/credentials_tests.rs | 23 ++- src/hardening.rs | 3 +- src/llm.rs | 138 +++++++++++++---- src/llm/llm_flow_tests.rs | 115 +++++++++++++- src/main.rs | 2 + src/onboard.rs | 80 +++++++++- src/openrouter.rs | 167 ++++++++++++++++++-- 10 files changed, 806 insertions(+), 67 deletions(-) create mode 100644 src/anthropic.rs diff --git a/README.md b/README.md index 262949a..739b0d9 100644 --- a/README.md +++ b/README.md @@ -38,21 +38,24 @@ Ustawienia przez zmienne środowiskowe lub `~/.config/jdg-cli/env`: - `JDG_OCR_PYTHON`: interpreter ze zainstalowanym `mlx_vlm`; domyślnie środowisko uv ppmlx, a jeśli go brak — `python3`. - `JDG_OCR_MAX_PAGES=10`, `JDG_OCR_TIMEOUT_SECS=180`: limity. Przekroczenie limitu nie daje częściowego wyniku. - `JDG_OCR_CACHE_DIR`: domyślnie `~/.cache/jdg-cli/ocr`. Cache jest powiązany z zawartością PDF, modelem i wersją adaptera. Tekst faktur jest zapisywany z uprawnieniami 600. -- `OPENROUTER_API_KEY`: jeśli ustawiony, jdg-cli wysyła sam plik PDF do OpenRouter (Gemini) przez zwykłe Chat Completions i żąda JSON według schematu 12 pól. Nie wysyła lokalnego tekstu Poppler/OCR i nie używa Batch API. Domyślny model: `google/gemini-3.8-flash`. Klucz zapisany przez `jdg-cli onboard` trafia do `.env`; Keychain jest opcjonalny (`JDG_USE_KEYCHAIN=1`). PDF chroniony hasłem jest pomijany: bez OCR, bez OpenRouter i bez zgadywania numeru z nazwy pliku. Gemini dostaje tylko trudne kandydatów faktur: brak numeru, daty albo kwoty brutto (albo niespójne kwoty) oraz sygnał faktury w numerze, NIP, KSeF, nazwie pliku albo temacie. Sam brak nazwy albo waluty nie uruchamia płatnego modelu. Wybrane wiersze w TUI (LLM) omijają ten filtr. Każdy PDF wysłany do modelu jest zapisywany w `llm_attempts.jsonl` (prawa 600) w katalogu poczty. Automatyczny sync nie wysyła ponownie PDF-a już wysłanego do tego samego modelu z tą samą wersją promptu, chyba że próba skończyła się błędem przejściowym (timeout, sieć, HTTP 429/5xx). Wiersze wybrane w TUI i `jdg-cli repair --llm` wysyłają zawsze. PDF, z którego nie udało się wyciągnąć tekstu (skan bez OCR), trafia do modelu, jeśli ma sygnał faktury w nazwie pliku albo temacie wiadomości; filtr ProductMesh (NIP albo nazwa firmy) działa dla niego dopiero po odpowiedzi modelu. Żądanie do OpenRoutera jest ponawiane tylko przy błędzie połączenia oraz HTTP 429/502/503/504; po przekroczeniu czasu odpowiedzi jdg-cli nie ponawia od razu (PDF mógł zostać przetworzony i rozliczony), a kolejna synchronizacja może spróbować ponownie. +- `ANTHROPIC_API_KEY`: jeśli ustawiony, jdg-cli wysyła sam plik PDF (base64, blok `document` w Messages API) do Claude i żąda JSON według schematu 12 pól. Nie podstawia tekstu z Poppler ani OCR. Domyślny model: `claude-haiku-5-5`. Klucz ma pierwszeństwo przed OpenRouter i lokalnym ppmlx. Zapis przez `jdg-cli onboard` trafia do `.env` (prawa 600); Keychain jest opcjonalny (`JDG_USE_KEYCHAIN=1`). `jdg-cli doctor` i `jdg-cli onboard --check` pokazują, że klucz jest ustawiony i skąd pochodzi, nigdy jego wartości. Obowiązuje ten sam filtr trudnych faktur, pomijanie PDF chronionego hasłem i rejestr `llm_attempts.jsonl` per model (odrzucona próba Gemini nie blokuje Claude). Wpis dostaje `input_tokens` i `output_tokens`, gdy odpowiedź je poda. Błąd przejściowy (timeout, sieć, HTTP 429/5xx, w tym 529) nie blokuje kolejnego syncu. Żądanie jest ponawiane od razu tylko przy błędzie połączenia oraz HTTP 429/502/503/504/529; po przekroczeniu czasu jdg-cli nie ponawia od razu, bo PDF mógł zostać przetworzony i rozliczony. +- `JDG_ANTHROPIC_MODEL`: nadpisuje model Anthropic. Postęp: `Anthropic N/M (xx%)`. +- `JDG_ANTHROPIC_TIMEOUT_SECS=120`. +- `OPENROUTER_API_KEY`: gdy brak `ANTHROPIC_API_KEY`, jdg-cli wysyła sam plik PDF do OpenRouter (Gemini) przez zwykłe Chat Completions i żąda JSON według schematu 12 pól. Nie wysyła lokalnego tekstu Poppler/OCR i nie używa Batch API. Domyślny model: `google/gemini-3.8-flash`. Klucz zapisany przez `jdg-cli onboard` trafia do `.env`; Keychain jest opcjonalny (`JDG_USE_KEYCHAIN=1`). PDF chroniony hasłem jest pomijany: bez OCR, bez OpenRouter i bez zgadywania numeru z nazwy pliku. Gemini dostaje tylko trudne kandydatów faktur: brak numeru, daty albo kwoty brutto (albo niespójne kwoty) oraz sygnał faktury w numerze, NIP, KSeF, nazwie pliku albo temacie. Sam brak nazwy albo waluty nie uruchamia płatnego modelu. Wybrane wiersze w TUI (LLM) omijają ten filtr. Każdy PDF wysłany do modelu jest zapisywany w `llm_attempts.jsonl` (prawa 600) w katalogu poczty. Wpis dostaje `input_tokens` i `output_tokens`, gdy dostawca je zwróci. Automatyczny sync nie wysyła ponownie PDF-a już wysłanego do tego samego modelu z tą samą wersją promptu, chyba że próba skończyła się błędem przejściowym (timeout, sieć, HTTP 429/5xx). Wiersze wybrane w TUI i `jdg-cli repair --llm` wysyłają zawsze. PDF, z którego nie udało się wyciągnąć tekstu (skan bez OCR), trafia do modelu, jeśli ma sygnał faktury w nazwie pliku albo temacie wiadomości; filtr ProductMesh (NIP albo nazwa firmy) działa dla niego dopiero po odpowiedzi modelu. Żądanie do OpenRoutera jest ponawiane tylko przy błędzie połączenia oraz HTTP 429/502/503/504/529; po przekroczeniu czasu odpowiedzi jdg-cli nie ponawia od razu (PDF mógł zostać przetworzony i rozliczony), a kolejna synchronizacja może spróbować ponownie. - `JDG_OPENROUTER_MODEL`: nadpisuje model OpenRouter. Sufiks `:batch` jest obcinany, żeby request szedł na Chat Completions. Postęp: `OpenRouter N/M (xx%)`. - `JDG_OPENROUTER_TIMEOUT_SECS=120`, `JDG_OPENROUTER_PDF_ENGINE=native`. -- `JDG_LLM_MODEL`: lokalny model tekstowy ppmlx, domyślnie `gemma-4-e4b-it-optiq`. Używany tylko gdy brak `OPENROUTER_API_KEY`. +- `JDG_LLM_MODEL`: lokalny model tekstowy ppmlx, domyślnie `gemma-4-e4b-it-optiq`. Używany tylko gdy brak `ANTHROPIC_API_KEY` i `OPENROUTER_API_KEY`. - `PPMLX_BASE_URL=http://127.0.0.1:6767`, `JDG_LLM_TIMEOUT_SECS=45`. -Gdy jest `OPENROUTER_API_KEY`, lokalny serwer LLM nie jest potrzebny. Bez klucza uruchom serwer osobno: +Gdy jest `ANTHROPIC_API_KEY` albo `OPENROUTER_API_KEY`, lokalny serwer LLM nie jest potrzebny. Bez obu kluczy uruchom serwer osobno: ```bash ppmlx serve --model gemma-4-e4b-it-optiq ``` -Sekrety tekstowe (`KSEF_TOKEN`, `SALDEO_USERNAME`, `SALDEO_PASSWORD`, `OPENROUTER_API_KEY`) trzyma plik `.env` z prawami 600. Lokalny `.env` jest wybierany automatycznie tylko w katalogu pakietu `jdg-cli`, gdy Git go ignoruje i nie śledzi. W pozostałych katalogach jdg-cli używa `~/.config/jdg-cli/.env`; `JDG_DOTENV` pozwala jawnie wskazać inny plik. Keychain jest wyłączony, chyba że `JDG_USE_KEYCHAIN=1`. Gdy sesja Saldeo wygaśnie, jdg-cli loguje Helium zapisanym `SALDEO_USERNAME`/`SALDEO_PASSWORD` (hasło idzie plikiem 600, nie listą argumentów). Bez loginu otwiera Helium do ręcznego logowania. 2FA i Captcha nadal wymagają Ciebie. Kolejność szukania: zmienna sesji → `.env` → plik 600 → opcjonalnie Keychain. `~/.config/jdg-cli/env` nie trzyma sekretów; znalezione tam klucze sekretów trafiają do `.env`. `jdg-cli onboard` zapisuje sekrety tekstowe w `.env`. Gdy brak `KSEF_TOKEN`, jdg-cli używa ważnego cache tokenu dostępu albo lokalnych metadanych KSeF; pełny Sync nie przerywa Gmail i Saldeo. Online bez cache wymaga tokenu z uprawnieniem InvoiceRead. `KSEF_TOKEN=... jdg-cli ...` nadpisuje Keychain na jeden proces i nie jest nigdzie zapisywane. Plik sekretu (`.env` — przy dowiązaniu symbolicznym sprawdzany i zapisywany jest jego cel — `~/.config/jdg-cli/env`, pliki tokenów) z prawami szerszymi niż 600 jest odrzucany z komunikatem podającym ścieżkę; `jdg-cli doctor` pokazuje wtedy `insecure`. Nieczytelny `.env` nie jest nadpisywany: zapis kończy się błędem. Przy `JDG_USE_KEYCHAIN=1` `jdg-cli onboard` zapisuje sekret w `.env` i kopiuje go do Keychain; wartości z Keychain nie są kopiowane z powrotem do `.env`. Klucz sekretu, który jest już w `.env`, nie jest nadpisywany starszą kopią z `~/.config/jdg-cli/env` — ta kopia jest tylko usuwana. Sekret ze znakiem nowej linii albo NUL nie jest zapisywany; jedno końcowe `\n` z Keychain albo wklejki jest obcinane. Sam `SALDEO_USERNAME` bez hasła oznacza logowanie ręczne (z ostrzeżeniem); `jdg-cli onboard` nie zapisze loginu bez hasła. +Sekrety tekstowe (`KSEF_TOKEN`, `SALDEO_USERNAME`, `SALDEO_PASSWORD`, `OPENROUTER_API_KEY`, `ANTHROPIC_API_KEY`) trzyma plik `.env` z prawami 600. Lokalny `.env` jest wybierany automatycznie tylko w katalogu pakietu `jdg-cli`, gdy Git go ignoruje i nie śledzi. W pozostałych katalogach jdg-cli używa `~/.config/jdg-cli/.env`; `JDG_DOTENV` pozwala jawnie wskazać inny plik. Keychain jest wyłączony, chyba że `JDG_USE_KEYCHAIN=1`. Gdy sesja Saldeo wygaśnie, jdg-cli loguje Helium zapisanym `SALDEO_USERNAME`/`SALDEO_PASSWORD` (hasło idzie plikiem 600, nie listą argumentów). Bez loginu otwiera Helium do ręcznego logowania. 2FA i Captcha nadal wymagają Ciebie. Kolejność szukania: zmienna sesji → `.env` → plik 600 → opcjonalnie Keychain. `~/.config/jdg-cli/env` nie trzyma sekretów; znalezione tam klucze sekretów trafiają do `.env`. `jdg-cli onboard` zapisuje sekrety tekstowe w `.env`. Gdy brak `KSEF_TOKEN`, jdg-cli używa ważnego cache tokenu dostępu albo lokalnych metadanych KSeF; pełny Sync nie przerywa Gmail i Saldeo. Online bez cache wymaga tokenu z uprawnieniem InvoiceRead. `KSEF_TOKEN=... jdg-cli ...` nadpisuje Keychain na jeden proces i nie jest nigdzie zapisywane. Plik sekretu (`.env` — przy dowiązaniu symbolicznym sprawdzany i zapisywany jest jego cel — `~/.config/jdg-cli/env`, pliki tokenów) z prawami szerszymi niż 600 jest odrzucany z komunikatem podającym ścieżkę; `jdg-cli doctor` pokazuje wtedy `insecure`. Nieczytelny `.env` nie jest nadpisywany: zapis kończy się błędem. Przy `JDG_USE_KEYCHAIN=1` `jdg-cli onboard` zapisuje sekret w `.env` i kopiuje go do Keychain; wartości z Keychain nie są kopiowane z powrotem do `.env`. Klucz sekretu, który jest już w `.env`, nie jest nadpisywany starszą kopią z `~/.config/jdg-cli/env` — ta kopia jest tylko usuwana. Sekret ze znakiem nowej linii albo NUL nie jest zapisywany; jedno końcowe `\n` z Keychain albo wklejki jest obcinane. Sam `SALDEO_USERNAME` bez hasła oznacza logowanie ręczne (z ostrzeżeniem); `jdg-cli onboard` nie zapisze loginu bez hasła. -Przy `JDG_USE_KEYCHAIN=1` zapis tokenów Gmail i sesji Saldeo do Keychain idzie przez Security.framework. Sekret nie jest argumentem procesu `security`. Tymczasowe pliki logowania Saldeo mają prawa 600 i są usuwane także przy błędzie instalacji lub uruchomienia procesu oraz przy przekroczeniu limitu czasu. Zapis tokenów, konfiguracji, cache i bazy używa uprawnień 600. Procesy `pdftotext`, `pdfinfo`, `pdftoppm`, `openssl` i OCR używają narzędzi z katalogów systemowych oraz środowiska bez `PYTHONPATH`. Narzędzie jest pomijane, gdy jego plik albo katalog — także po rozwinięciu dowiązań, jak w Homebrew — jest zapisywalny dla wszystkich albo należy do kogoś innego niż root i Ty; ta sama reguła dotyczy katalogów w `PATH` procesów potomnych, a pomocnik OCR dostaje ścieżki sprawdzonych `pdfinfo` i `pdftoppm`. Katalog zapisywalny dla grupy (np. `/opt/homebrew/bin` z grupą `admin`) jest dozwolony, ale `jdg-cli doctor` i `jdg-cli onboard --check` pokazują ostrzeżenie: inni członkowie tej grupy mogą podmienić narzędzia. `PPMLX_BASE_URL` musi wskazywać pętlę lokalną. OCR odrzuca PDF większy niż 40 MB i nie pobiera modeli. Wybór lokalnego `.env` używa Git z katalogów systemowych z wyłączonym `core.fsmonitor` i hookami. Pomocnik OCR działa w prywatnym katalogu cache OCR i dostaje ścieżki bezwzględne. `node`, `npm`, skrypt logowania i przeglądarka otwierana do autoryzacji Gmail nie dostają w środowisku `KSEF_TOKEN`, `SALDEO_*`, `OPENROUTER_API_KEY` ani tokenów Gmail; `npm install` instaluje przypiętą wersję `playwright@1.63.0` (nadpisanie: `JDG_PLAYWRIGHT_VERSION`, tylko litery, cyfry, `.` i `-`) z `--ignore-scripts`; już zainstalowany Playwright zostaje bez zmian. Ciasteczka Saldeo są wysyłane tylko do hosta Saldeo, zgodnie z domeną, ścieżką i flagą `secure`. Względny `downloadUrl` jest rozwiązywany względem `https://saldeo.brainshare.pl/`; jdg-cli pobiera dokumenty tylko przez https. +Przy `JDG_USE_KEYCHAIN=1` zapis tokenów Gmail i sesji Saldeo do Keychain idzie przez Security.framework. Sekret nie jest argumentem procesu `security`. Tymczasowe pliki logowania Saldeo mają prawa 600 i są usuwane także przy błędzie instalacji lub uruchomienia procesu oraz przy przekroczeniu limitu czasu. Zapis tokenów, konfiguracji, cache i bazy używa uprawnień 600. Procesy `pdftotext`, `pdfinfo`, `pdftoppm`, `openssl` i OCR używają narzędzi z katalogów systemowych oraz środowiska bez `PYTHONPATH`. Narzędzie jest pomijane, gdy jego plik albo katalog — także po rozwinięciu dowiązań, jak w Homebrew — jest zapisywalny dla wszystkich albo należy do kogoś innego niż root i Ty; ta sama reguła dotyczy katalogów w `PATH` procesów potomnych, a pomocnik OCR dostaje ścieżki sprawdzonych `pdfinfo` i `pdftoppm`. Katalog zapisywalny dla grupy (np. `/opt/homebrew/bin` z grupą `admin`) jest dozwolony, ale `jdg-cli doctor` i `jdg-cli onboard --check` pokazują ostrzeżenie: inni członkowie tej grupy mogą podmienić narzędzia. `PPMLX_BASE_URL` musi wskazywać pętlę lokalną. OCR odrzuca PDF większy niż 40 MB i nie pobiera modeli. Wybór lokalnego `.env` używa Git z katalogów systemowych z wyłączonym `core.fsmonitor` i hookami. Pomocnik OCR działa w prywatnym katalogu cache OCR i dostaje ścieżki bezwzględne. `node`, `npm`, skrypt logowania i przeglądarka otwierana do autoryzacji Gmail nie dostają w środowisku `KSEF_TOKEN`, `SALDEO_*`, `OPENROUTER_API_KEY`, `ANTHROPIC_API_KEY` ani tokenów Gmail; `npm install` instaluje przypiętą wersję `playwright@1.63.0` (nadpisanie: `JDG_PLAYWRIGHT_VERSION`, tylko litery, cyfry, `.` i `-`) z `--ignore-scripts`; już zainstalowany Playwright zostaje bez zmian. Ciasteczka Saldeo są wysyłane tylko do hosta Saldeo, zgodnie z domeną, ścieżką i flagą `secure`. Względny `downloadUrl` jest rozwiązywany względem `https://saldeo.brainshare.pl/`; jdg-cli pobiera dokumenty tylko przez https. jdg-cli nie uruchamia ukrytego procesu serwera. Brak serwera daje ostrzeżenie i nie blokuje synchronizacji pozostałych źródeł. LLM otrzymuje cały odczyt do 60000 znaków; większe dokumenty są odrzucane bez obcinania. Odpowiedzi ucięte limitem tokenów nie są stosowane. diff --git a/src/anthropic.rs b/src/anthropic.rs new file mode 100644 index 0000000..9993fde --- /dev/null +++ b/src/anthropic.rs @@ -0,0 +1,317 @@ +use crate::*; + +const ANTHROPIC_MESSAGES_URL: &str = "https://api.anthropic.com/v1/messages"; +/// Current Messages API version used by the PDF and structured-output examples. +pub(crate) const ANTHROPIC_VERSION: &str = "2026-10-21"; +pub(crate) const DEFAULT_ANTHROPIC_MODEL: &str = "claude-haiku-5-5"; + +pub(crate) fn anthropic_configured() -> bool { + secret_is_set(Secret::AnthropicApiKey) +} + +pub(crate) fn anthropic_model_from(configured: Option<&str>) -> String { + configured + .map(str::trim) + .filter(|value| !value.is_empty()) + .unwrap_or(DEFAULT_ANTHROPIC_MODEL) + .to_string() +} + +pub(crate) fn anthropic_model() -> String { + anthropic_model_from(jdg_config_var("JDG_ANTHROPIC_MODEL").as_deref()) +} + +pub(crate) fn anthropic_progress_line(processed: usize, todo: usize, filename: &str) -> String { + llm_progress_line("Anthropic", processed, todo, filename) +} + +fn anthropic_timeout() -> Duration { + Duration::from_secs( + jdg_config_var("JDG_ANTHROPIC_TIMEOUT_SECS") + .and_then(|value| value.parse().ok()) + .unwrap_or(120) + .clamp(15, 300), + ) +} + +/// Models after Claude Opus 4.6 reject every temperature except 1.0, so the +/// request omits it and structured output pins the JSON instead. +pub(crate) fn anthropic_invoice_request(model: &str, pdf_base64: &str) -> Value { + serde_json::json!({ + "model": model, + "max_tokens": 4000, + "messages": [{ + "role": "user", + "content": [ + { + "type": "document", + "source": { + "type": "base64", + "media_type": "application/pdf", + "data": pdf_base64 + }, + "citations": { "enabled": false } + }, + { + "type": "text", + "text": INVOICE_PDF_EXTRACTION_PROMPT + } + ] + }], + "output_config": { + "format": { + "type": "json_schema", + "schema": invoice_structured_schema() + } + } + }) +} + +pub(crate) fn redact_secret(text: &str, secret: &str) -> String { + if secret.len() < 8 { + return text.to_string(); + } + text.replace(secret, "********") +} + +pub(crate) fn anthropic_http_error(status: u16, body: &str, api_key: &str) -> anyhow::Error { + let message = redact_secret(&format!("Anthropic HTTP {status}: {body}"), api_key); + if http_status_is_transient(status) { + transient_llm_error(message) + } else { + anyhow!(message) + } +} + +fn anthropic_error_is_transient(error_type: &str) -> bool { + matches!( + error_type, + "overloaded_error" | "rate_limit_error" | "api_error" | "timeout_error" + ) +} + +pub(crate) fn anthropic_response_json(response: &Value) -> Result { + if response.get("type").and_then(Value::as_str) == Some("error") { + let error = response.get("error"); + let message = error + .and_then(|item| item.get("message")) + .and_then(Value::as_str) + .unwrap_or("błąd Anthropic"); + let kind = error + .and_then(|item| item.get("type")) + .and_then(Value::as_str) + .unwrap_or(""); + if anthropic_error_is_transient(kind) { + return Err(transient_llm_error(format!("Anthropic: {message}"))); + } + return Err(anyhow!("Anthropic: {message}")); + } + if response + .get("stop_reason") + .and_then(Value::as_str) + .is_none_or(|reason| reason != "end_turn") + { + return Err(anyhow!( + "Anthropic: odpowiedź nie została zakończona poprawnie; nie zapisuję częściowego JSON" + )); + } + let content = response + .get("content") + .and_then(Value::as_array) + .ok_or_else(|| anyhow!("Anthropic: brak treści odpowiedzi"))?; + let mut text = String::new(); + for block in content { + if block.get("type").and_then(Value::as_str) != Some("text") { + continue; + } + if let Some(piece) = block.get("text").and_then(Value::as_str) { + text.push_str(piece); + } + } + if text.is_empty() { + return Err(anyhow!("Anthropic: brak treści odpowiedzi")); + } + crate::parse_json_from_llm(&text) +} + +pub(crate) fn anthropic_extract_invoice_fields( + record: &mut InvoiceRecord, + path: &Path, + usage: &mut LlmTokenUsage, +) -> Result { + let pdf = load_paid_invoice_pdf(record, path, "Anthropic")?; + // Nothing is sent without a key, so these failures must not block a later try. + let api_key = secret_value(Secret::AnthropicApiKey) + .map_err(|err| transient_llm_error(format!("odczyt klucza Anthropic: {err:#}")))? + .ok_or_else(|| { + transient_llm_error( + "brak ANTHROPIC_API_KEY; ustaw klucz Anthropic albo użyj OpenRouter albo lokalnego LLM", + ) + })?; + let model = anthropic_model(); + let body = anthropic_invoice_request(&model, &pdf.pdf_base64); + let client = Client::builder().timeout(anthropic_timeout()).build()?; + let response = llm_send_with_retry( + "Anthropic", + || match client + .post(ANTHROPIC_MESSAGES_URL) + .header("x-api-key", &api_key) + .header("anthropic-version", ANTHROPIC_VERSION) + .json(&body) + .send() + { + Ok(resp) if resp.status().is_success() => resp + .json::() + .map_err(|err| (OpenRouterFailure::Other, anyhow::Error::from(err))), + Ok(resp) => { + let status = resp.status(); + let text = resp.text().unwrap_or_default(); + Err(( + OpenRouterFailure::Status(status.as_u16()), + anthropic_http_error(status.as_u16(), &text, &api_key), + )) + } + Err(err) => Err((openrouter_failure_kind(&err), anyhow::Error::from(err))), + }, + std::thread::sleep, + )?; + *usage = response_token_usage(&response); + let value = anthropic_response_json(&response)?; + invoice_validation::apply_normalized_invoice_json(record, &value) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn request_sends_the_pdf_and_the_same_invoice_schema() { + let body = anthropic_invoice_request(DEFAULT_ANTHROPIC_MODEL, "QQ=="); + assert_eq!(body["model"], DEFAULT_ANTHROPIC_MODEL); + assert_eq!(body["max_tokens"], 4000); + assert!(body.get("temperature").is_none()); + assert_eq!(body["output_config"]["format"]["type"], "json_schema"); + assert_eq!( + body["output_config"]["format"]["schema"], + invoice_structured_schema() + ); + let content = body["messages"][0]["content"].as_array().unwrap(); + assert_eq!(content[0]["type"], "document"); + assert_eq!(content[0]["source"]["type"], "base64"); + assert_eq!(content[0]["source"]["media_type"], "application/pdf"); + assert_eq!(content[0]["source"]["data"], "QQ=="); + assert_eq!(content[0]["citations"]["enabled"], false); + assert_eq!(content[1]["type"], "text"); + assert_eq!(content[1]["text"], INVOICE_PDF_EXTRACTION_PROMPT); + let openrouter = openrouter_invoice_request("m", "f.pdf", "QQ=="); + assert_eq!( + openrouter["messages"][0]["content"][0]["text"], + content[1]["text"] + ); + let encoded = serde_json::to_string(&body).unwrap(); + assert!(!encoded.contains("x-api-key")); + assert!(!encoded.contains("ANTHROPIC")); + assert!(!encoded.contains("sk-ant")); + assert!(!encoded.contains("Bearer")); + assert!(!encoded.contains("Tekst PDF")); + assert!(encoded.contains("application/pdf")); + } + + #[test] + fn model_override_trims_and_falls_back() { + assert_eq!(anthropic_model_from(None), DEFAULT_ANTHROPIC_MODEL); + assert_eq!(anthropic_model_from(Some(" ")), DEFAULT_ANTHROPIC_MODEL); + assert_eq!( + anthropic_model_from(Some(" claude-haiku-5-5 ")), + "claude-haiku-5-5" + ); + } + + #[test] + fn progress_line_matches_paid_provider_style() { + assert_eq!( + anthropic_progress_line(2, 8, "Invoice.pdf"), + "Anthropic 2/8 (25%) Invoice.pdf" + ); + } + + fn invoice_message(text: &str, stop_reason: &str) -> Value { + serde_json::json!({ + "type": "message", + "stop_reason": stop_reason, + "content": [ + {"type": "thinking", "thinking": "nie zapisuj"}, + {"type": "text", "text": text} + ], + "usage": {"input_tokens": 1500, "output_tokens": 42} + }) + } + + #[test] + fn complete_json_is_accepted_and_usage_is_separate_from_parsing() { + let ok = invoice_message("{\"seller_name\":\"Elocity\"}", "end_turn"); + assert_eq!( + anthropic_response_json(&ok).unwrap()["seller_name"], + "Elocity" + ); + assert_eq!( + response_token_usage(&ok), + LlmTokenUsage { + input_tokens: Some(1500), + output_tokens: Some(42) + } + ); + let truncated = invoice_message("{\"seller_name\":\"Elocity\"}", "max_tokens"); + assert!(anthropic_response_json(&truncated).is_err()); + assert_eq!(response_token_usage(&truncated).output_tokens, Some(42)); + let refusal = invoice_message("nie", "refusal"); + let err = anthropic_response_json(&refusal).unwrap_err(); + assert!(!llm_error_is_transient(&err)); + assert!(anthropic_response_json(&serde_json::json!({"content":[]})).is_err()); + } + + #[test] + fn api_errors_are_classified_and_do_not_echo_the_key() { + let overloaded = serde_json::json!({ + "type": "error", + "error": {"type": "overloaded_error", "message": "Overloaded"} + }); + assert!(llm_error_is_transient( + &anthropic_response_json(&overloaded).unwrap_err() + )); + let auth = serde_json::json!({ + "type": "error", + "error": {"type": "authentication_error", "message": "invalid x-api-key"} + }); + let err = anthropic_response_json(&auth).unwrap_err().to_string(); + assert!(err.contains("invalid x-api-key")); + assert!(!err.contains("sk-ant")); + assert!(!llm_error_is_transient( + &anthropic_response_json(&auth).unwrap_err() + )); + + let key = "sk-ant-usr-secret-value"; + let http = anthropic_http_error(529, &format!("overloaded {key}"), key); + assert!(llm_error_is_transient(&http)); + assert!(http.to_string().contains("529")); + assert!(!http.to_string().contains(key)); + let denied = anthropic_http_error(401, &format!("bad {key}"), key); + assert!(!llm_error_is_transient(&denied)); + assert!(!denied.to_string().contains(key)); + assert!(denied.to_string().contains("********")); + } + + #[test] + fn client_sends_the_key_only_as_a_header() { + let source = include_str!("anthropic.rs"); + let production = source.split("#[cfg(test)]").next().unwrap(); + assert!(production.contains(".header(\"x-api-key\"")); + assert!(production.contains("anthropic-version")); + assert!(production.contains("Secret::AnthropicApiKey")); + assert!(!production.contains("Authorization")); + assert!(!production.contains("Bearer ")); + assert!(!production.contains("Command::")); + assert!(!production.contains("eprintln!")); + assert!(!production.contains("std::env::var(\"ANTHROPIC_API_KEY\")")); + } +} diff --git a/src/credentials.rs b/src/credentials.rs index f23b1aa..f795ce4 100644 --- a/src/credentials.rs +++ b/src/credentials.rs @@ -9,14 +9,16 @@ pub(crate) const ACCOUNT_KSEF_ACCESS_TOKEN: &str = "ksef_access_token"; pub(crate) const ACCOUNT_SALDEO_USERNAME: &str = "saldeo_username"; pub(crate) const ACCOUNT_SALDEO_PASSWORD: &str = "saldeo_password"; pub(crate) const ACCOUNT_OPENROUTER_API_KEY: &str = "openrouter_api_key"; +pub(crate) const ACCOUNT_ANTHROPIC_API_KEY: &str = "anthropic_api_key"; /// Klucze, których jdg-cli nie zapisuje już w ~/.config/jdg-cli/env. -pub(crate) const SECRET_ENV_KEYS: [&str; 5] = [ +pub(crate) const SECRET_ENV_KEYS: [&str; 6] = [ "KSEF_TOKEN", "KSEF_CERT_PASSWORD", "SALDEO_USERNAME", "SALDEO_PASSWORD", "OPENROUTER_API_KEY", + "ANTHROPIC_API_KEY", ]; #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -29,6 +31,7 @@ pub(crate) enum Secret { SaldeoUsername, SaldeoPassword, OpenRouterApiKey, + AnthropicApiKey, } /// Skąd pochodzi sekret; bez wartości, do raportów `doctor` i `onboard`. @@ -131,6 +134,7 @@ impl Secret { Secret::SaldeoUsername => ACCOUNT_SALDEO_USERNAME, Secret::SaldeoPassword => ACCOUNT_SALDEO_PASSWORD, Secret::OpenRouterApiKey => ACCOUNT_OPENROUTER_API_KEY, + Secret::AnthropicApiKey => ACCOUNT_ANTHROPIC_API_KEY, } } @@ -142,6 +146,7 @@ impl Secret { Secret::SaldeoUsername => Some("SALDEO_USERNAME"), Secret::SaldeoPassword => Some("SALDEO_PASSWORD"), Secret::OpenRouterApiKey => Some("OPENROUTER_API_KEY"), + Secret::AnthropicApiKey => Some("ANTHROPIC_API_KEY"), _ => None, } } @@ -153,6 +158,7 @@ impl Secret { "SALDEO_USERNAME" => Some(Secret::SaldeoUsername), "SALDEO_PASSWORD" => Some(Secret::SaldeoPassword), "OPENROUTER_API_KEY" => Some(Secret::OpenRouterApiKey), + "ANTHROPIC_API_KEY" => Some(Secret::AnthropicApiKey), _ => None, } } @@ -168,6 +174,7 @@ impl Secret { Secret::SaldeoUsername => "SALDEO_USERNAME", Secret::SaldeoPassword => "SALDEO_PASSWORD", Secret::OpenRouterApiKey => "OPENROUTER_API_KEY", + Secret::AnthropicApiKey => "ANTHROPIC_API_KEY", } } @@ -185,7 +192,8 @@ impl Secret { | Secret::KsefCertPassword | Secret::SaldeoUsername | Secret::SaldeoPassword - | Secret::OpenRouterApiKey => None, + | Secret::OpenRouterApiKey + | Secret::AnthropicApiKey => None, } } @@ -199,7 +207,8 @@ impl Secret { | Secret::KsefCertPassword | Secret::SaldeoUsername | Secret::SaldeoPassword - | Secret::OpenRouterApiKey => None, + | Secret::OpenRouterApiKey + | Secret::AnthropicApiKey => None, } } } diff --git a/src/credentials_tests.rs b/src/credentials_tests.rs index a8dcfab..a6f030c 100644 --- a/src/credentials_tests.rs +++ b/src/credentials_tests.rs @@ -468,6 +468,7 @@ fn accounts_use_expected_names() { assert_eq!(Secret::SaldeoUsername.account(), "saldeo_username"); assert_eq!(Secret::SaldeoPassword.account(), "saldeo_password"); assert_eq!(Secret::OpenRouterApiKey.account(), "openrouter_api_key"); + assert_eq!(Secret::AnthropicApiKey.account(), "anthropic_api_key"); assert_eq!(Secret::from_env_key("KSEF_TOKEN"), Some(Secret::KsefToken)); assert_eq!( Secret::from_env_key("SALDEO_USERNAME"), @@ -481,13 +482,33 @@ fn accounts_use_expected_names() { "KSEF_CERT_PASSWORD", "SALDEO_USERNAME", "SALDEO_PASSWORD", - "OPENROUTER_API_KEY" + "OPENROUTER_API_KEY", + "ANTHROPIC_API_KEY" ] ); assert_eq!( Secret::from_env_key("OPENROUTER_API_KEY"), Some(Secret::OpenRouterApiKey) ); + assert_eq!( + Secret::from_env_key("ANTHROPIC_API_KEY"), + Some(Secret::AnthropicApiKey) + ); +} + +#[test] +fn anthropic_api_key_is_saved_in_dotenv() { + let (root, _store, _guard) = setup("anthropic-zapis", &[], StoreMode::Unavailable); + let saved = save_secret(Secret::AnthropicApiKey, "sk-ant-usr-dummy").unwrap(); + assert!(saved.file.is_some()); + assert!(!saved.keychain); + let text = dotenv_text(&root); + assert!(text.contains("ANTHROPIC_API_KEY='sk-ant-usr-dummy'")); + assert_eq!(secret_source(Secret::AnthropicApiKey), SecretSource::File); + assert_eq!( + secret_value(Secret::AnthropicApiKey).unwrap().as_deref(), + Some("sk-ant-usr-dummy") + ); } #[test] diff --git a/src/hardening.rs b/src/hardening.rs index 456e143..c10a6c4 100644 --- a/src/hardening.rs +++ b/src/hardening.rs @@ -548,13 +548,14 @@ pub(crate) fn apply_isolated_env(command: &mut Command) -> &mut Command { /// Zmienne z sekretami jdg-cli i tokenem Gmail; procesy potomne, które ich nie potrzebują /// (node, npm, skrypt logowania Saldeo), dostają środowisko bez nich. -pub(crate) const CHILD_SECRET_ENV_KEYS: [&str; 8] = [ +pub(crate) const CHILD_SECRET_ENV_KEYS: [&str; 9] = [ "KSEF_TOKEN", "KSEF_CERT_PASSWORD", "KSEF_ACCESS_TOKEN", "SALDEO_USERNAME", "SALDEO_PASSWORD", "OPENROUTER_API_KEY", + "ANTHROPIC_API_KEY", "GMAIL_ACCESS_TOKEN", "GMAIL_REFRESH_TOKEN", ]; diff --git a/src/llm.rs b/src/llm.rs index 43d44eb..3f7834c 100644 --- a/src/llm.rs +++ b/src/llm.rs @@ -52,6 +52,10 @@ struct LlmAttempt { attempted_at: DateTime, #[serde(default, skip_serializing_if = "Option::is_none")] pub(crate) detail: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub(crate) input_tokens: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub(crate) output_tokens: Option, } type LlmAttemptKey = (String, String, String); @@ -223,6 +227,73 @@ pub(crate) fn enrich_candidates_with_llm_explicit( ) } +/// Which model reads hard invoice PDFs. Anthropic wins when its key is set, +/// then OpenRouter, then the local ppmlx server. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum LlmProvider { + Anthropic, + OpenRouter, + Local, +} + +impl LlmProvider { + pub(crate) fn selected() -> Self { + if anthropic_configured() { + Self::Anthropic + } else if openrouter_configured() { + Self::OpenRouter + } else { + Self::Local + } + } + + pub(crate) fn is_paid(self) -> bool { + !matches!(self, Self::Local) + } + + pub(crate) fn as_str(self) -> &'static str { + match self { + Self::Anthropic => "anthropic", + Self::OpenRouter => "openrouter", + Self::Local => "local", + } + } + + pub(crate) fn model(self) -> String { + match self { + Self::Anthropic => anthropic_model(), + Self::OpenRouter => openrouter_chat_model(), + Self::Local => llm_model(), + } + } + + pub(crate) fn progress_line(self, processed: usize, todo: usize, filename: &str) -> String { + match self { + Self::Anthropic => anthropic_progress_line(processed, todo, filename), + Self::OpenRouter => openrouter_progress_line(processed, todo, filename), + Self::Local => format!("LLM: {processed}/{todo} {filename}"), + } + } +} + +pub(crate) fn llm_provider_status() -> Value { + let provider = LlmProvider::selected(); + serde_json::json!({ + "provider": provider.as_str(), + "model": provider.model(), + }) +} + +pub(crate) fn llm_provider_status_line() -> String { + let provider = LlmProvider::selected(); + let name = match provider { + LlmProvider::Anthropic => "Anthropic", + LlmProvider::OpenRouter => "OpenRouter", + LlmProvider::Local => "lokalny ppmlx", + }; + format!(" LLM faktur: {name} ({})", provider.model()) +} + pub(crate) fn enrich_candidates_with_gemma_with_hook( records: &mut [InvoiceRecord], skip_hashes: &HashSet, @@ -251,23 +322,19 @@ fn enrich_candidates_with_request( where F: FnMut(&[InvoiceRecord], usize) -> Result<()>, { - let use_openrouter = openrouter_configured(); + let provider = LlmProvider::selected(); let force = request == LlmRequest::Forced; - let model = if use_openrouter { - openrouter_chat_model() - } else { - llm_model() - }; + let model = provider.model(); let mut ledgers = LlmAttemptLedgers::default(); let queue = llm_queue( records, skip_hashes, - use_openrouter, + provider.is_paid(), request, &model, &mut ledgers, )?; - if use_openrouter && !force { + if provider.is_paid() && !force { let skipped = records .iter() .filter(|record| { @@ -276,25 +343,28 @@ where }) .count(); if skipped > 0 { - eprintln!( - " [Gmail/OpenRouter] pominięto {skipped} łatwych albo bez sygnału faktury; Gemini tylko dla trudnych" - ); + match provider { + LlmProvider::Anthropic => eprintln!( + " [Gmail/Anthropic] pominięto {skipped} łatwych albo bez sygnału faktury; Claude tylko dla trudnych" + ), + LlmProvider::OpenRouter => eprintln!( + " [Gmail/OpenRouter] pominięto {skipped} łatwych albo bez sygnału faktury; Gemini tylko dla trudnych" + ), + LlmProvider::Local => {} + } } } if queue.is_empty() { return Ok(()); } - let extract: fn(&mut InvoiceRecord, &Path) -> Result = if use_openrouter { - openrouter_extract_invoice_fields - } else { - gemma_extract_invoice_fields - }; eprintln!( " [Gmail/LLM] wzbogacanie {} kandydatów przez {}...", queue.len(), model ); - if !use_openrouter && let Err(err) = ensure_ppmlx_server() { + if provider == LlmProvider::Local + && let Err(err) = ensure_ppmlx_server() + { eprintln!(" [Gmail/LLM] pominięto wzbogacanie: {err}"); for idx in 0..records.len() { if !skip_hashes.contains(&records[idx].content_hash) @@ -313,10 +383,14 @@ where records, &queue, progress, - use_openrouter, + provider, &model, &mut ledgers, - extract, + |record, path, usage| match provider { + LlmProvider::Anthropic => anthropic_extract_invoice_fields(record, path, usage), + LlmProvider::OpenRouter => openrouter_extract_invoice_fields(record, path, usage), + LlmProvider::Local => gemma_extract_invoice_fields(record, path, usage), + }, after_record, )?; eprintln!(" [Gmail/LLM] gotowe"); @@ -328,10 +402,10 @@ fn run_llm_queue( records: &mut [InvoiceRecord], queue: &[usize], progress: Option>>, - use_openrouter: bool, + provider: LlmProvider, model: &str, ledgers: &mut LlmAttemptLedgers, - mut extract: impl FnMut(&mut InvoiceRecord, &Path) -> Result, + mut extract: impl FnMut(&mut InvoiceRecord, &Path, &mut LlmTokenUsage) -> Result, mut after_record: F, ) -> Result<()> where @@ -344,17 +418,14 @@ where }; let path = &resolve_jdg_source_path(&source_path); let fname = path.file_name().and_then(|n| n.to_str()).unwrap_or("PDF"); - let status = if use_openrouter { - openrouter_progress_line(processed + 1, todo, fname) - } else { - format!("LLM: {}/{} {}", processed + 1, todo, fname) - }; + let status = provider.progress_line(processed + 1, todo, fname); eprintln!(" [Gmail/LLM] {}", status); if let Some(ref p) = progress { set_progress(p, status); } let hash = llm_attempt_hash(&records[idx], path); - let result = extract(&mut records[idx], path); + let mut usage = LlmTokenUsage::default(); + let result = extract(&mut records[idx], path, &mut usage); let outcome = llm_attempt_outcome(&result); match &result { Ok(true) => { @@ -382,6 +453,8 @@ where .as_ref() .err() .map(|err| truncate(&format!("{err:#}"), 300)), + input_tokens: usage.input_tokens, + output_tokens: usage.output_tokens, }; // A lost entry only costs one repeated request; do not drop the // answer already received for this record. @@ -431,7 +504,11 @@ fn ensure_ppmlx_server() -> Result<()> { )) } -fn gemma_extract_invoice_fields(record: &mut InvoiceRecord, path: &Path) -> Result { +fn gemma_extract_invoice_fields( + record: &mut InvoiceRecord, + path: &Path, + usage: &mut LlmTokenUsage, +) -> Result { let (text, extraction_warnings) = extract_document_text(path)?; if text.chars().count() > 60_000 { return Err(anyhow!( @@ -477,7 +554,7 @@ Tekst PDF: ---"#, text ); - let value = ppmlx_extract_json(&prompt)?; + let value = ppmlx_extract_json(&prompt, usage)?; let changed = invoice_validation::apply_normalized_invoice_json(record, &value)?; for warning in extraction_warnings { if !record.warnings.contains(&warning) { @@ -487,7 +564,7 @@ Tekst PDF: Ok(changed) } -fn ppmlx_extract_json(prompt: &str) -> Result { +fn ppmlx_extract_json(prompt: &str, usage: &mut LlmTokenUsage) -> Result { let base = ppmlx_base_url()?; let model = llm_model(); let client = Client::builder().timeout(llm_timeout()).build()?; @@ -510,6 +587,7 @@ fn ppmlx_extract_json(prompt: &str) -> Result { { Ok(resp) if resp.status().is_success() => { let response: Value = resp.json()?; + *usage = response_token_usage(&response); return ppmlx_response_json(&response); } Ok(resp) if resp.status().as_u16() == 503 => { diff --git a/src/llm/llm_flow_tests.rs b/src/llm/llm_flow_tests.rs index f2ff188..4e5feda 100644 --- a/src/llm/llm_flow_tests.rs +++ b/src/llm/llm_flow_tests.rs @@ -124,10 +124,10 @@ fn run_once(records: &mut [InvoiceRecord], result: fn() -> Result) -> usiz records, &queued, None, - false, + LlmProvider::Local, "model-a", &mut ledgers, - |_, _| { + |_, _, _| { calls += 1; result() }, @@ -205,10 +205,10 @@ fn ledger_entries_are_keyed_by_hash_model_and_version() { &mut records, &[0], None, - false, + LlmProvider::Local, "model-a", &mut ledgers, - |_, _| Ok(true), + |_, _, _| Ok(true), |_, _| Ok(()), ) .unwrap(); @@ -346,6 +346,113 @@ fn filename_guessed_number_is_replaced_by_llm_number() { assert!(record_number_guessed_from_filename(&record)); } +#[test] +fn rejected_gemini_attempt_does_not_block_haiku() { + let dir = TempDir::new(); + let record = incomplete_pdf(&dir, "a.pdf"); + let line = serde_json::json!({ + "content_hash": record.content_hash, + "model": "google/gemini-3.8-flash", + "version": LLM_EXTRACTION_VERSION, + "outcome": "rejected", + "attempted_at": "2026-01-01T00:00:00Z" + }); + fs::write(dir.0.join(LLM_ATTEMPTS_FILE), format!("{line}\n")).unwrap(); + assert_eq!( + queue( + std::slice::from_ref(&record), + LlmRequest::Automatic, + "google/gemini-3.8-flash" + ), + Vec::::new() + ); + assert_eq!( + queue( + std::slice::from_ref(&record), + LlmRequest::Automatic, + DEFAULT_ANTHROPIC_MODEL + ), + vec![0] + ); +} + +#[test] +fn ledger_records_token_usage_even_when_rejected() { + let dir = TempDir::new(); + let mut records = vec![incomplete_pdf(&dir, "a.pdf")]; + let mut ledgers = LlmAttemptLedgers::default(); + run_llm_queue( + &mut records, + &[0], + None, + LlmProvider::Anthropic, + DEFAULT_ANTHROPIC_MODEL, + &mut ledgers, + |_, _, usage| { + usage.input_tokens = Some(1200); + usage.output_tokens = Some(80); + Err(anyhow!("LLM: kwoty są niespójne")) + }, + |_, _| Ok(()), + ) + .unwrap(); + let text = fs::read_to_string(dir.0.join(LLM_ATTEMPTS_FILE)).unwrap(); + assert!(text.contains("\"outcome\":\"rejected\""), "{text}"); + assert!(text.contains("\"input_tokens\":1200"), "{text}"); + assert!(text.contains("\"output_tokens\":80"), "{text}"); + assert!(!text.contains("sk-ant"), "{text}"); + let attempt: LlmAttempt = serde_json::from_str(text.trim()).unwrap(); + assert_eq!(attempt.model, DEFAULT_ANTHROPIC_MODEL); + assert_eq!(attempt.input_tokens, Some(1200)); + assert_eq!(attempt.output_tokens, Some(80)); + // The rejection is for Haiku only; another model can still be sent. + assert_eq!( + queue(&records, LlmRequest::Automatic, "google/gemini-3.8-flash"), + vec![0] + ); + assert_eq!( + queue(&records, LlmRequest::Automatic, DEFAULT_ANTHROPIC_MODEL), + Vec::::new() + ); +} + +#[test] +fn anthropic_key_is_preferred_over_openrouter_and_local() { + let dir = TempDir::new(); + let install = |env: &[(&str, &str)]| { + crate::credentials::testing::install( + dir.0.clone(), + env, + crate::credentials::testing::StoreMode::Unavailable, + ) + }; + { + let (_store, _guard) = install(&[ + ("ANTHROPIC_API_KEY", "sk-ant-usr-test-key"), + ("OPENROUTER_API_KEY", "sk-or-test-key"), + ]); + assert_eq!(LlmProvider::selected(), LlmProvider::Anthropic); + assert!(LlmProvider::selected().is_paid()); + let status = llm_provider_status(); + assert_eq!(status["provider"], "anthropic"); + assert_eq!(status["model"], anthropic_model()); + let rendered = format!("{status} {}", llm_provider_status_line()); + assert!(!rendered.contains("sk-ant-usr-test-key"), "{rendered}"); + assert!(!rendered.contains("sk-or-test-key"), "{rendered}"); + } + { + let (_store, _guard) = install(&[("OPENROUTER_API_KEY", "sk-or-test-key")]); + assert_eq!(LlmProvider::selected(), LlmProvider::OpenRouter); + assert_eq!(llm_provider_status()["provider"], "openrouter"); + } + { + let (_store, _guard) = install(&[]); + assert_eq!(LlmProvider::selected(), LlmProvider::Local); + assert!(!LlmProvider::selected().is_paid()); + assert_eq!(llm_provider_status()["provider"], "local"); + } +} + #[test] fn uppercase_pdf_extension_is_queued_and_sent() { let dir = TempDir::new(); diff --git a/src/main.rs b/src/main.rs index 693aea0..0d7e649 100644 --- a/src/main.rs +++ b/src/main.rs @@ -50,6 +50,8 @@ use invoice_validation::counterparty_name_is_placeholder; pub(crate) use jdg_root::*; mod openrouter; pub(crate) use openrouter::*; +mod anthropic; +pub(crate) use anthropic::*; #[cfg(test)] mod tests; diff --git a/src/onboard.rs b/src/onboard.rs index dfc5d32..e39c8b9 100644 --- a/src/onboard.rs +++ b/src/onboard.rs @@ -66,14 +66,15 @@ pub(crate) fn onboard( 5 => onboard_edit_env_secret("KSEF_CERT_PASSWORD")?, 6 => onboard_edit_env_secret("KSEF_TOKEN")?, 7 => onboard_edit_env_secret("OPENROUTER_API_KEY")?, - 8 => onboard_configure_ksef_data(status.year)?, - 9 => { + 8 => onboard_edit_env_secret("ANTHROPIC_API_KEY")?, + 9 => onboard_configure_ksef_data(status.year)?, + 10 => { open_db(db_path)?; eprintln!("✓ Baza gotowa: {}\n", db_path.display()); } - 10 => run_saldeo_auth_script()?, - 11 => {} - 12 => break, + 11 => run_saldeo_auth_script()?, + 12 => {} + 13 => break, _ => unreachable!(), } @@ -140,6 +141,10 @@ pub(crate) fn onboard_menu_items( "OPENROUTER_API_KEY — {}", display_secret_value(secret_is_set(Secret::OpenRouterApiKey)) ), + format!( + "ANTHROPIC_API_KEY — {}", + display_secret_value(secret_is_set(Secret::AnthropicApiKey)) + ), format!( "KSEF_DATA_DIR — {} {}", if status.ksef_data_exists { @@ -276,9 +281,18 @@ pub(crate) fn secrets_status_json(status: &OnboardStatus) -> Value { "ksef_cert_password": secret_status_entry(&status.ksef_password_source), "ksef_access_token": secret_status_entry(&status.ksef_access_source), "openrouter_api_key": secret_status_entry(&secret_source(Secret::OpenRouterApiKey)), + "anthropic_api_key": secret_status_entry(&secret_source(Secret::AnthropicApiKey)), }) } +pub(crate) fn anthropic_key_status_line() -> String { + format!( + " Anthropic: {}{}", + display_secret_value(secret_is_set(Secret::AnthropicApiKey)), + secret_source_suffix(&secret_source(Secret::AnthropicApiKey)) + ) +} + fn secret_status_entry(source: &SecretSource) -> Value { let mut entry = serde_json::json!({ "set": source.is_set(), "source": source.as_str() }); if let Some(problem) = source.problem() { @@ -330,11 +344,13 @@ pub(crate) fn print_onboard_status(status: &OnboardStatus, db_path: &Path) { "✗ (zainstaluj ppmlx i model gemma-4-e4b)" } ); + eprintln!("{}", anthropic_key_status_line()); eprintln!( " OpenRouter: {}{}", display_secret_value(secret_is_set(Secret::OpenRouterApiKey)), secret_source_suffix(&secret_source(Secret::OpenRouterApiKey)) ); + eprintln!("{}", llm_provider_status_line()); eprintln!( " openssl: {}", if status.openssl_ok { @@ -476,6 +492,7 @@ pub(crate) fn write_onboard_check_json(status: &OnboardStatus) -> Result<()> { "database": { "exists": status.db_exists }, "warnings": status.tool_warnings, "secrets": secrets_status_json(status), + "llm": llm_provider_status(), "next_steps": steps }); write_json(&status_json, None) @@ -1446,13 +1463,14 @@ pub(crate) fn doctor(db_path: &Path, token_env: &str) -> Result<()> { "jdg_root_source": jdg_root.source.as_str() }, "secrets": secrets_status_json(&status), + "llm": llm_provider_status(), "notes": [ "GmailFetch wymaga tokenu OAuth z zakresem gmail.readonly.", "PDF-y są parsowane przez pdftotext, potem PyMuPDF/pdfplumber/pypdf jako fallback.", "jdg-cli reconcile bez własnych --ksef/--saldeo pobiera online metadane KSeF i Saldeo przed porównaniem.", "KSeF online używa KSEF_TOKEN, KSEF_CONTEXT_NIP/KSEF_NIP i KSEF_BASE_URL/KSEF_ENV; metadane są cache'owane lokalnie w KSEF_DATA_DIR albo data/ksef-.", secrets_storage_note(), - "Jeśli OPENROUTER_API_KEY jest ustawiony, jdg-cli odczytuje brakujące PDF-y przez google/gemini-3.8-flash ze structured output. Lokalny Gemma zostaje jako zapas." + "Jeśli ANTHROPIC_API_KEY jest ustawiony, jdg-cli wysyła trudne PDF-y bezpośrednio do Claude (domyślnie claude-haiku-5-5). Bez tego klucza, gdy jest OPENROUTER_API_KEY, używa google/gemini-3.8-flash. Lokalny Gemma zostaje jako zapas." ], "next_steps": onboard_next_steps(&status, gmail_usable) }); @@ -1661,3 +1679,53 @@ mod saldeo_auth_temp_file_tests { Ok(()) } } + +#[cfg(test)] +mod anthropic_status_tests { + use super::*; + use crate::credentials::testing::{StoreMode, install}; + + #[test] + fn doctor_and_onboard_report_anthropic_source_without_the_key() { + let root = std::env::temp_dir().join(format!( + "jdg-cli-anthropic-status-{}-{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap_or_default() + .as_nanos() + )); + let _ = fs::remove_dir_all(&root); + fs::create_dir_all(&root).unwrap(); + let (_store, _guard) = install( + root.clone(), + &[("ANTHROPIC_API_KEY", "sk-ant-usr-do-not-print")], + StoreMode::Unavailable, + ); + let db = root.join("jdg.sqlite"); + let status = collect_onboard_status(&db).unwrap(); + let secrets = secrets_status_json(&status); + assert_eq!(secrets["anthropic_api_key"]["set"], true); + assert_eq!(secrets["anthropic_api_key"]["source"], "env"); + assert_eq!(secrets["openrouter_api_key"]["source"], "missing"); + let line = anthropic_key_status_line(); + assert!(line.contains("********"), "{line}"); + assert!(line.contains("zmienna sesji"), "{line}"); + let items = onboard_menu_items(&status, &db, None); + assert!(items[7].starts_with("OPENROUTER_API_KEY"), "{items:?}"); + assert!(items[8].starts_with("ANTHROPIC_API_KEY — ✓"), "{items:?}"); + assert!(items[9].starts_with("KSEF_DATA_DIR"), "{items:?}"); + let llm = llm_provider_status(); + assert_eq!(llm["provider"], "anthropic"); + if std::env::var("JDG_ANTHROPIC_MODEL") + .ok() + .is_none_or(|value| value.trim().is_empty()) + { + assert_eq!(llm["model"], DEFAULT_ANTHROPIC_MODEL); + } + let blob = format!("{secrets} {line} {llm} {}", items[8]); + assert!(!blob.contains("sk-ant-usr-do-not-print"), "{blob}"); + drop(_guard); + let _ = fs::remove_dir_all(&root); + } +} diff --git a/src/openrouter.rs b/src/openrouter.rs index 0d6c5f5..5c4ac9a 100644 --- a/src/openrouter.rs +++ b/src/openrouter.rs @@ -66,12 +66,50 @@ pub(crate) fn openrouter_chat_model() -> String { strip_openrouter_batch_variant(&openrouter_model()) } -pub(crate) fn openrouter_progress_line(processed: usize, todo: usize, filename: &str) -> String { +pub(crate) fn llm_progress_line( + label: &str, + processed: usize, + todo: usize, + filename: &str, +) -> String { let percent = processed .saturating_mul(100) .checked_div(todo) .unwrap_or(100); - format!("OpenRouter {processed}/{todo} ({percent}%) {filename}") + format!("{label} {processed}/{todo} ({percent}%) {filename}") +} + +pub(crate) fn openrouter_progress_line(processed: usize, todo: usize, filename: &str) -> String { + llm_progress_line("OpenRouter", processed, todo, filename) +} + +/// Token counts from a provider response, when the body includes them. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub(crate) struct LlmTokenUsage { + pub input_tokens: Option, + pub output_tokens: Option, +} + +pub(crate) fn json_object_u64(object: &Value, keys: &[&str]) -> Option { + keys.iter().find_map(|key| { + object.get(*key).and_then(|value| { + value + .as_u64() + .or_else(|| value.as_i64().and_then(|n| u64::try_from(n).ok())) + }) + }) +} + +/// Anthropic uses `input_tokens`/`output_tokens`; OpenRouter and ppmlx use the +/// Chat Completions names. Either shape is recorded. +pub(crate) fn response_token_usage(response: &Value) -> LlmTokenUsage { + let Some(usage) = response.get("usage") else { + return LlmTokenUsage::default(); + }; + LlmTokenUsage { + input_tokens: json_object_u64(usage, &["input_tokens", "prompt_tokens"]), + output_tokens: json_object_u64(usage, &["output_tokens", "completion_tokens"]), + } } fn openrouter_timeout() -> Duration { @@ -94,6 +132,10 @@ fn nullable_string(description: &str) -> Value { }) } +/// Same instruction for every paid PDF provider. Kept identical so the +/// extraction version does not have to change when a provider is added. +pub(crate) const INVOICE_PDF_EXTRACTION_PROMPT: &str = "Odczytaj fakturę z załączonego PDF. Zwróć tylko dane widoczne na dokumencie. Nie zgaduj i nie wyliczaj kwot. Jeśli pole nie jest pewne, użyj null. Daty: YYYY-MM-DD. Kwoty: kropka i dwa miejsca, bez waluty. Polski NIP: 10 cyfr. Zagraniczny VAT w polu NIP: null. Nazwy: pełna nazwa strony, nie nagłówek w stylu Nabywca albo DETAILS. Dla faktur zakupowych Productmesh nabywca to zwykle Productmesh, a sprzedawca to kontrahent."; + pub(crate) fn invoice_structured_schema() -> Value { let mut properties = serde_json::Map::new(); properties.insert( @@ -175,7 +217,7 @@ pub(crate) fn openrouter_invoice_request(model: &str, filename: &str, pdf_base64 "content": [ { "type": "text", - "text": "Odczytaj fakturę z załączonego PDF. Zwróć tylko dane widoczne na dokumencie. Nie zgaduj i nie wyliczaj kwot. Jeśli pole nie jest pewne, użyj null. Daty: YYYY-MM-DD. Kwoty: kropka i dwa miejsca, bez waluty. Polski NIP: 10 cyfr. Zagraniczny VAT w polu NIP: null. Nazwy: pełna nazwa strony, nie nagłówek w stylu Nabywca albo DETAILS. Dla faktur zakupowych Productmesh nabywca to zwykle Productmesh, a sprzedawca to kontrahent." + "text": INVOICE_PDF_EXTRACTION_PROMPT }, { "type": "file", @@ -224,10 +266,19 @@ pub(crate) fn openrouter_response_json(response: &Value) -> Result { crate::parse_json_from_llm(content) } -pub(crate) fn openrouter_extract_invoice_fields( +#[derive(Debug)] +pub(crate) struct PaidInvoicePdf { + pub filename: String, + pub pdf_base64: String, +} + +/// Shared gate for paid PDF providers: password-protected files and oversized +/// PDFs are never uploaded. `destination` is only the provider name in the error. +pub(crate) fn load_paid_invoice_pdf( record: &mut InvoiceRecord, path: &Path, -) -> Result { + destination: &str, +) -> Result { if record_is_password_protected(record) || pdf_is_password_protected(path) { if !record .warnings @@ -241,15 +292,27 @@ pub(crate) fn openrouter_extract_invoice_fields( let meta = fs::metadata(path).with_context(|| format!("stat {}", path.display()))?; if meta.len() > MAX_OCR_PDF_BYTES { return Err(anyhow!( - "PDF przekracza limit OCR {MAX_OCR_PDF_BYTES} bajtów; nie wysyłam do OpenRouter" + "PDF przekracza limit OCR {MAX_OCR_PDF_BYTES} bajtów; nie wysyłam do {destination}" )); } let bytes = fs::read(path).with_context(|| format!("odczyt {}", path.display()))?; let filename = path .file_name() .and_then(|name| name.to_str()) - .unwrap_or("invoice.pdf"); - let pdf_base64 = STANDARD.encode(&bytes); + .unwrap_or("invoice.pdf") + .to_string(); + Ok(PaidInvoicePdf { + filename, + pdf_base64: STANDARD.encode(&bytes), + }) +} + +pub(crate) fn openrouter_extract_invoice_fields( + record: &mut InvoiceRecord, + path: &Path, + usage: &mut LlmTokenUsage, +) -> Result { + let pdf = load_paid_invoice_pdf(record, path, "OpenRouter")?; // Nothing is sent without a key, so these failures must not block a later try. let api_key = secret_value(Secret::OpenRouterApiKey) .map_err(|err| transient_llm_error(format!("odczyt klucza OpenRouter: {err:#}")))? @@ -259,7 +322,7 @@ pub(crate) fn openrouter_extract_invoice_fields( ) })?; let model = openrouter_chat_model(); - let body = openrouter_invoice_request(&model, filename, &pdf_base64); + let body = openrouter_invoice_request(&model, &pdf.filename, &pdf.pdf_base64); let client = Client::builder().timeout(openrouter_timeout()).build()?; let response = openrouter_send_with_retry( || match client @@ -289,6 +352,7 @@ pub(crate) fn openrouter_extract_invoice_fields( }, std::thread::sleep, )?; + *usage = response_token_usage(&response); let value = openrouter_response_json(&response)?; invoice_validation::apply_normalized_invoice_json(record, &value) } @@ -320,16 +384,26 @@ pub(crate) fn openrouter_failure_kind(err: &reqwest::Error) -> OpenRouterFailure } /// Retry only when the request provably was not processed: no connection, rate -/// limit, or a gateway that did not reach the model. A timeout is not retried here; -/// the attempts ledger marks it transient so a later sync may try again. +/// limit, a gateway that did not reach the model, or Anthropic overloaded (529). +/// A timeout is not retried here; the attempts ledger marks it transient so a +/// later sync may try again. HTTP 500 stays transient for the ledger but is not +/// repeated immediately. pub(crate) fn openrouter_failure_is_retryable(failure: OpenRouterFailure) -> bool { matches!( failure, - OpenRouterFailure::Connect | OpenRouterFailure::Status(429 | 502 | 503 | 504) + OpenRouterFailure::Connect | OpenRouterFailure::Status(429 | 502 | 503 | 504 | 529) ) } pub(crate) fn openrouter_send_with_retry( + send: impl FnMut() -> std::result::Result, + wait: impl FnMut(Duration), +) -> Result { + llm_send_with_retry("OpenRouter", send, wait) +} + +pub(crate) fn llm_send_with_retry( + label: &str, mut send: impl FnMut() -> std::result::Result, mut wait: impl FnMut(Duration), ) -> Result { @@ -342,15 +416,15 @@ pub(crate) fn openrouter_send_with_retry( attempt += 1; if !openrouter_failure_is_retryable(failure) || attempt >= OPENROUTER_MAX_ATTEMPTS { return Err(match failure { - OpenRouterFailure::Timeout => err.context( - "OpenRouter nie odpowiedział w limicie czasu; nie ponawiam od razu, bo PDF mógł zostać przetworzony i rozliczony", - ), + OpenRouterFailure::Timeout => err.context(format!( + "{label} nie odpowiedział w limicie czasu; nie ponawiam od razu, bo PDF mógł zostać przetworzony i rozliczony" + )), _ => err, }); } let delay = Duration::from_secs(2u64.pow(attempt - 1)); eprintln!( - " [Gmail/OpenRouter] {}, ponawiam za {}s...", + " [Gmail/{label}] {}, ponawiam za {}s...", match failure { OpenRouterFailure::Status(status) => format!("HTTP {status}"), _ => "brak połączenia".to_string(), @@ -396,6 +470,7 @@ mod tests { assert_eq!(body["provider"]["require_parameters"], true); let content = body["messages"][0]["content"].as_array().unwrap(); assert_eq!(content[0]["type"], "text"); + assert_eq!(content[0]["text"], INVOICE_PDF_EXTRACTION_PROMPT); assert_eq!(content[1]["type"], "file"); let file = &content[1]["file"]; assert_eq!(file["filename"], "Invoice-M73SJH5X-0005.pdf"); @@ -444,7 +519,14 @@ mod tests { #[test] fn only_unprocessed_requests_are_retried() { use OpenRouterFailure::*; - for failure in [Connect, Status(429), Status(502), Status(503), Status(504)] { + for failure in [ + Connect, + Status(429), + Status(502), + Status(503), + Status(504), + Status(529), + ] { assert!(openrouter_failure_is_retryable(failure), "{failure:?}"); } for failure in [Timeout, Other, Status(500), Status(400), Status(402)] { @@ -501,4 +583,55 @@ mod tests { assert!(result.is_err()); assert_eq!(calls, 1); } + + #[test] + fn token_usage_reads_anthropic_and_chat_shapes() { + let anthropic = serde_json::json!({"usage": {"input_tokens": 1200, "output_tokens": 80}}); + assert_eq!( + response_token_usage(&anthropic), + LlmTokenUsage { + input_tokens: Some(1200), + output_tokens: Some(80) + } + ); + let chat = serde_json::json!({"usage": {"prompt_tokens": 9, "completion_tokens": 3}}); + assert_eq!( + response_token_usage(&chat), + LlmTokenUsage { + input_tokens: Some(9), + output_tokens: Some(3) + } + ); + assert_eq!( + response_token_usage( + &serde_json::json!({"usage": {"input_tokens": 0, "output_tokens": 0}}) + ), + LlmTokenUsage { + input_tokens: Some(0), + output_tokens: Some(0) + } + ); + assert_eq!( + response_token_usage(&serde_json::json!({})), + LlmTokenUsage::default() + ); + } + + #[test] + fn password_protected_record_is_not_read_for_paid_upload() { + let mut record = empty_record(SourceKind::Mail); + record.warnings.push(PDF_PASSWORD_WARNING.to_string()); + let err = + load_paid_invoice_pdf(&mut record, Path::new("/no/such.pdf"), "Anthropic").unwrap_err(); + assert!(is_pdf_password_error(&err)); + assert_eq!( + record + .warnings + .iter() + .filter(|warning| is_pdf_password_warning(warning)) + .count(), + 1, + "the existing password warning is not duplicated" + ); + } }