From 16bac983fe46f615859212c93b51cbca9c47a204 Mon Sep 17 00:00:00 2001 From: Lee Chapman Date: Fri, 20 Nov 2026 21:37:20 -0800 Subject: [PATCH 01/77] feat: add OpenRouter operator, API, and Freya UI Replace Compose/GPU UI default path with kube-rs studio, cloud+local generation router, and Civitai key install flow. Co-authored-by: Cursor --- .dockerignore | 8 - .env.example | 56 - .gitignore | 1 - Cargo.lock | 293 +- Cargo.toml | 4 +- Dockerfile | 12 +- Dockerfile.web | 4 +- Makefile | 122 +- README.md | 83 +- config/crd/freya.dataknife.ai_crds.yaml | 89 +- config/rbac/role.yaml | 5 +- ...1alpha1_freyadiffusionworker_external.yaml | 23 +- ...alpha1_freyadiffusionworker_incluster.yaml | 9 +- .../samples/freya_v1alpha1_freyastudio.yaml | 56 +- crates/freya-api/Cargo.toml | 1 - crates/freya-api/src/civitai.rs | 850 +- crates/freya-api/src/config.rs | 190 +- crates/freya-api/src/gallery.rs | 91 +- crates/freya-api/src/main.rs | 231 +- crates/freya-api/src/openrouter.rs | 1600 +--- crates/freya-api/src/routes.rs | 4927 +--------- crates/freya-api/src/state.rs | 237 +- crates/freya-api/src/styles.rs | 160 +- crates/freya-api/src/worker.rs | 535 +- crates/freya-crd/src/lib.rs | 110 +- crates/freya-operator/Cargo.toml | 1 - crates/freya-operator/src/reconcile/asset.rs | 240 +- .../src/reconcile/generation.rs | 71 +- crates/freya-operator/src/reconcile/mod.rs | 78 - crates/freya-operator/src/reconcile/studio.rs | 507 +- crates/freya-operator/src/reconcile/worker.rs | 60 +- crates/freya-worker/Cargo.toml | 3 +- crates/freya-worker/src/main.rs | 1779 +--- docs/ARCHITECTURE.md | 62 +- docs/CONCEPTS.md | 17 +- docs/LOCAL.md | 225 +- docs/OPENROUTER.md | 88 +- packs/instructions/chat.txt | 2 +- packs/instructions/plan.txt | 5 +- packs/instructions/prompt-prose.txt | 2 +- packs/styles/ethereal-moon.yaml | 4 +- packs/styles/local-lora-example.yaml | 4 +- web/index.html | 33 +- web/nginx.conf | 9 +- web/package.json | 1 - web/src/App.jsx | 8193 +---------------- web/src/styles.css | 1815 +--- 47 files changed, 951 insertions(+), 21945 deletions(-) diff --git a/.dockerignore b/.dockerignore index a1595f5..c59730f 100644 --- a/.dockerignore +++ b/.dockerignore @@ -12,11 +12,3 @@ swarmui/bin/ .git/ .env .env.* -target/ -web/node_modules/ -web/dist/ -data/ -legacy/ -*.png -*.md -.github/ diff --git a/.env.example b/.env.example index 551c6f9..28ba4c0 100644 --- a/.env.example +++ b/.env.example @@ -1,60 +1,4 @@ -# Freya local / operator stack (OpenRouter + optional worker) -# Copy: cp .env.example .env -# Then fill OPENROUTER_API_KEY (required for real API). Never commit .env. -# -# Single-system Docker Compose (no k8s): use deploy/compose/.env.example instead -# cp deploy/compose/.env.example deploy/compose/.env && make compose-up -# See docs/COMPOSE.md (distinct from legacy/docker-compose.yml). - -# --- Required for cloud chat + images --- OPENROUTER_API_KEY= - -# --- Optional integrations --- -# LoRA search / install onto a diffusion worker CIVITAI_API_KEY= -# Hugging Face (private/gated model downloads) HF_TOKEN= - -# --- Optional local auth (empty = open with warn; set for anything beyond localhost) --- -FREYA_API_TOKEN= -# Game-operator style admin login (UI Sign in). In-cluster: from Secret …-admin. -FREYA_ADMIN_USER=admin -FREYA_ADMIN_PASSWORD= -FREYA_WORKER_TOKEN= -# Comma-separated browser origins; empty = permissive when no API token -FREYA_CORS_ORIGINS= -# Vite UI bearer when FREYA_API_TOKEN is set (or Settings → Generate API token) -VITE_FREYA_API_TOKEN= -# Runtime secrets (UI keys + rotated API token). In-cluster: /data/gallery/.freya-runtime.json -# FREYA_SECRETS_FILE=./data/secrets.json - -# --- Optional diffusion worker (local stub or remote GPU) --- -# Local: host stub on :8091. In-cluster Studio may point at a remote -# FreyaDiffusionWorker (e.g. https://vllm.dataknife.net) via CR — separate from this. FREYA_DIFFUSION_WORKER_URL=http://127.0.0.1:8091 -FREYA_WORKER_PORT=8091 -# Prefer game-drive path for large weights (repo ./data/models may symlink here) -FREYA_MODELS_DIR=/mnt/game2/freya/models -# Local start/stop (Settings → Worker). Prefer docker when this container exists. -FREYA_WORKER_CONTAINER=freya-local-worker -# FREYA_WORKER_SYSTEMD_UNIT=freya-worker.service -# FREYA_WORKER_TLS_INSECURE=false - -# --- Optional API paths / models (defaults match freya-api) --- -FREYA_BIND=127.0.0.1:8080 -FREYA_GALLERY_DIR=./data/gallery -FREYA_PACKS_DIR=./packs -FREYA_SECRETS_FILE=./data/secrets.json -# OPENROUTER_BASE_URL=https://openrouter.ai/api/v1 -# FREYA_CHAT_MODEL=openrouter/auto -# FREYA_IMAGE_MODEL=auto -# FREYA_ROUTER_MODEL=auto - -# --- Optional Freya MCP (Streamable HTTP; make run-mcp) --- -# FREYA_MCP_BIND=127.0.0.1:8090 -# FREYA_API_URL=http://127.0.0.1:8080 -# FREYA_MCP_ALLOWED_HOSTS=localhost,127.0.0.1 # empty or * is loopback only -# (reuses FREYA_API_TOKEN above) - -# --- Container UI (nginx) — set by operator in-cluster; local Docker only if needed --- -# FREYA_API_UPSTREAM=http://127.0.0.1:8080 diff --git a/.gitignore b/.gitignore index 5fe2c0b..1777c1a 100644 --- a/.gitignore +++ b/.gitignore @@ -52,7 +52,6 @@ logs/ .env .env.* !.env.example -!deploy/compose/.env.example *.pem # .NET (legacy SwarmUI) diff --git a/Cargo.lock b/Cargo.lock index 4194f0c..9db3728 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -252,15 +252,6 @@ dependencies = [ "generic-array", ] -[[package]] -name = "block-buffer" -version = "0.12.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa" -dependencies = [ - "hybrid-array", -] - [[package]] name = "bumpalo" version = "3.20.4" @@ -366,12 +357,6 @@ version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" -[[package]] -name = "const-oid" -version = "0.10.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "be95d4a884358a21a199689323c29e9256b4a1b315e22f183d155422041d3a9a" - [[package]] name = "core-foundation" version = "0.10.1" @@ -422,33 +407,14 @@ dependencies = [ "typenum", ] -[[package]] -name = "crypto-common" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" -dependencies = [ - "hybrid-array", -] - [[package]] name = "darling" version = "0.20.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fc7f46116c46ff9ab3eb1597a45688b6715c6e628b5c133e288e709a29bcb4ee" dependencies = [ - "darling_core 0.20.11", - "darling_macro 0.20.11", -] - -[[package]] -name = "darling" -version = "0.24.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed17f5901b6630b993ca003def43f2f8ef4014fc13b047b57aad617ff32bc2ec" -dependencies = [ - "darling_core 0.24.1", - "darling_macro 0.24.1", + "darling_core", + "darling_macro", ] [[package]] @@ -465,60 +431,25 @@ dependencies = [ "syn 2.0.119", ] -[[package]] -name = "darling_core" -version = "0.24.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6837e2cf7485aaae18f86181d2f0e9a7ed297a025e220aeabf63fdebd3a2ddff" -dependencies = [ - "ident_case", - "proc-macro2", - "quote", - "strsim", - "syn 3.0.10", -] - [[package]] name = "darling_macro" version = "0.20.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fc34b93ccb385b40dc71c6fceac4b2ad23662c7eeb248cf10d529b7e055b6ead" dependencies = [ - "darling_core 0.20.11", + "darling_core", "quote", "syn 2.0.119", ] -[[package]] -name = "darling_macro" -version = "0.24.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2ac7135c3ef02b2f7833bbeb1be5ba7f966dcde8a87c6b87f65a778d71a02785" -dependencies = [ - "darling_core 0.24.1", - "quote", - "syn 3.0.10", -] - [[package]] name = "digest" version = "0.10.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" dependencies = [ - "block-buffer 0.10.4", - "crypto-common 0.1.7", -] - -[[package]] -name = "digest" -version = "0.11.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" -dependencies = [ - "block-buffer 0.12.1", - "const-oid", - "crypto-common 0.2.2", + "block-buffer", + "crypto-common", ] [[package]] @@ -662,7 +593,6 @@ dependencies = [ "base64 0.22.1", "chrono", "clap", - "libc", "reqwest", "serde", "serde_json", @@ -681,30 +611,11 @@ version = "0.1.0" dependencies = [ "k8s-openapi", "kube", - "schemars 0.8.22", + "schemars", "serde", "serde_json", ] -[[package]] -name = "freya-mcp" -version = "0.1.0" -dependencies = [ - "anyhow", - "axum", - "clap", - "reqwest", - "rmcp", - "serde", - "serde_json", - "tokio", - "tokio-util", - "tower-http", - "tracing", - "tracing-subscriber", - "urlencoding", -] - [[package]] name = "freya-operator" version = "0.1.0" @@ -722,7 +633,6 @@ dependencies = [ "tokio", "tracing", "tracing-subscriber", - "uuid", ] [[package]] @@ -733,7 +643,6 @@ dependencies = [ "axum", "base64 0.22.1", "clap", - "libc", "reqwest", "serde", "serde_json", @@ -999,15 +908,6 @@ version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" -[[package]] -name = "hybrid-array" -version = "0.4.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17" -dependencies = [ - "typenum", -] - [[package]] name = "hyper" version = "1.12.0" @@ -1244,8 +1144,6 @@ checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" dependencies = [ "equivalent", "hashbrown 0.17.1", - "serde", - "serde_core", ] [[package]] @@ -1396,7 +1294,7 @@ dependencies = [ "http", "json-patch", "k8s-openapi", - "schemars 0.8.22", + "schemars", "serde", "serde-value", "serde_json", @@ -1409,7 +1307,7 @@ version = "0.98.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "37745d8a4076b77e0b1952e94e358726866c8e14ec94baaca677d47dcdb98658" dependencies = [ - "darling 0.20.11", + "darling", "proc-macro2", "quote", "serde_json", @@ -1638,12 +1536,6 @@ dependencies = [ "windows-link", ] -[[package]] -name = "pastey" -version = "0.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2ee67f1008b1ba2321834326597b8e186293b049a023cdef258527550b9935b4" - [[package]] name = "pem" version = "3.0.6" @@ -1918,26 +1810,6 @@ dependencies = [ "bitflags", ] -[[package]] -name = "ref-cast" -version = "1.0.27" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7e440fb4e4b4147295338efb76001ab9e4efc0e5839df2c47fc5ac2381d365c3" -dependencies = [ - "ref-cast-impl", -] - -[[package]] -name = "ref-cast-impl" -version = "1.0.27" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "92ecd8964f8453721699a1ed72037b0db49ce2f5a5138486ee89bed6f67cdf3a" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.10", -] - [[package]] name = "regex" version = "1.13.2" @@ -2019,56 +1891,6 @@ dependencies = [ "windows-sys 0.52.0", ] -[[package]] -name = "rmcp" -version = "3.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "391f153431ab68664d946513ea0cb3edbca78eaf99c5a983036cacab6220d85b" -dependencies = [ - "async-trait", - "base64 0.23.1", - "bytes", - "chrono", - "futures", - "http", - "http-body", - "http-body-util", - "indexmap", - "libc", - "pastey", - "percent-encoding", - "pin-project-lite", - "rand 0.10.4", - "rmcp-macros", - "schemars 1.2.3", - "serde", - "serde_json", - "sha2", - "sse-stream", - "thiserror 2.0.21", - "tokio", - "tokio-stream", - "tokio-util", - "tower-service", - "tracing", - "unicode-general-category", - "unicode-normalization", - "uuid", -] - -[[package]] -name = "rmcp-macros" -version = "3.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3598e3f36f4af2b5219b133baf7d97a2197039225adc3d4acf3dd8805b5a2aef" -dependencies = [ - "darling 0.24.1", - "proc-macro2", - "quote", - "serde_json", - "syn 3.0.10", -] - [[package]] name = "rustc-hash" version = "2.1.3" @@ -2160,21 +1982,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3fbf2ae1b8bc8e02df939598064d22402220cd5bbcca1c76f7d6a310974d5615" dependencies = [ "dyn-clone", - "schemars_derive 0.8.22", - "serde", - "serde_json", -] - -[[package]] -name = "schemars" -version = "1.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ab508826f74a77ca9d5aba6ff19b522583ee3eaf28a19384ff3d0e5835fadf6e" -dependencies = [ - "chrono", - "dyn-clone", - "ref-cast", - "schemars_derive 1.2.3", + "schemars_derive", "serde", "serde_json", ] @@ -2187,22 +1995,10 @@ checksum = "32e265784ad618884abaea0600a9adf15393368d840e0222d101a072f3f7534d" dependencies = [ "proc-macro2", "quote", - "serde_derive_internals 0.29.1", + "serde_derive_internals", "syn 2.0.119", ] -[[package]] -name = "schemars_derive" -version = "1.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e1c3a92094fa7d61aa124645844facb6b554dfc797136d0f5fd1f890e2bffc69" -dependencies = [ - "proc-macro2", - "quote", - "serde_derive_internals 0.30.0", - "syn 3.0.10", -] - [[package]] name = "scopeguard" version = "1.2.0" @@ -2292,17 +2088,6 @@ dependencies = [ "syn 2.0.119", ] -[[package]] -name = "serde_derive_internals" -version = "0.30.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f852137cce035d6a4df67ccce505ff6b3e9fd3a10e3e52b24dc71e650bb1a9bd" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.10", -] - [[package]] name = "serde_json" version = "1.0.154" @@ -2360,18 +2145,7 @@ checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8" dependencies = [ "cfg-if", "cpufeatures 0.2.17", - "digest 0.10.7", -] - -[[package]] -name = "sha2" -version = "0.11.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "47d7069beb7d6ac7b9acd1039986e73443f24234f41074da099d6f994ac9ad19" -dependencies = [ - "cfg-if", - "cpufeatures 0.3.1", - "digest 0.11.3", + "digest", ] [[package]] @@ -2433,19 +2207,6 @@ version = "0.9.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3763264f6b73151db08c50ff20d7d8a0b8796e021cdea7ceedad07b80155fa0e" -[[package]] -name = "sse-stream" -version = "0.2.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c25ac7aff0abd1dbc474536e40416e1102c7dd9bfba0b9861c6d357f835dcfb4" -dependencies = [ - "bytes", - "futures-util", - "http-body", - "http-body-util", - "pin-project-lite", -] - [[package]] name = "stable_deref_trait" version = "1.2.1" @@ -2621,17 +2382,6 @@ dependencies = [ "tokio", ] -[[package]] -name = "tokio-stream" -version = "0.1.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a3d06f0b082ba57c26b79407372e57cf2a1e28124f78e9479fe80322cf53420b" -dependencies = [ - "futures-core", - "pin-project-lite", - "tokio", -] - [[package]] name = "tokio-util" version = "0.7.20" @@ -2791,27 +2541,12 @@ version = "2.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "357cc3acc6a036009fd6c973ed009037c732d60d0b4f6c673e9041497482a28f" -[[package]] -name = "unicode-general-category" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b993bddc193ae5bd0d623b49ec06ac3e9312875fdae725a975c51db1cc1677f" - [[package]] name = "unicode-ident" version = "1.0.27" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" -[[package]] -name = "unicode-normalization" -version = "0.1.26" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "75cd3fb03d5288b3ba9a1ee103ac7e9cbb59f0b03d64f8ddfcc04dd42758a85d" -dependencies = [ - "tinyvec", -] - [[package]] name = "unsafe-libyaml" version = "0.2.11" @@ -2836,12 +2571,6 @@ dependencies = [ "serde", ] -[[package]] -name = "urlencoding" -version = "2.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "daf8dba3b7eb870caf1ddeed7bc9d2a049f3cfdfae7cb521b087cc33ae4c49da" - [[package]] name = "utf8_iter" version = "1.1.0" diff --git a/Cargo.toml b/Cargo.toml index f30b7c1..7b0c9be 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -5,14 +5,12 @@ members = [ "crates/freya-operator", "crates/freya-api", "crates/freya-worker", - "crates/freya-mcp", ] default-members = [ "crates/freya-crd", "crates/freya-operator", "crates/freya-api", "crates/freya-worker", - "crates/freya-mcp", ] [workspace.package] @@ -30,7 +28,7 @@ serde_json = "1" serde_yaml = "0.9" schemars = "0.8" thiserror = "2" -tokio = { version = "1", features = ["macros", "rt-multi-thread", "signal", "fs", "io-util", "process"] } +tokio = { version = "1", features = ["macros", "rt-multi-thread", "signal", "fs", "io-util"] } tracing = "0.1" tracing-subscriber = { version = "0.3", features = ["env-filter"] } kube = { version = "0.98", default-features = true, features = ["runtime", "derive", "client"] } diff --git a/Dockerfile b/Dockerfile index 0d97a20..05a9f74 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,9 +1,9 @@ -FROM rust:1.88-bookworm AS builder +FROM rust:1.87-bookworm AS builder WORKDIR /src -COPY Cargo.toml Cargo.lock rust-toolchain.toml ./ +COPY Cargo.toml rust-toolchain.toml ./ COPY crates ./crates COPY packs ./packs -RUN cargo build --release -p freya-operator -p freya-api -p freya-worker -p freya-mcp +RUN cargo build --release -p freya-operator -p freya-api -p freya-worker FROM gcr.io/distroless/cc-debian12:nonroot AS operator COPY --from=builder /src/target/release/freya-operator /usr/local/bin/freya-operator @@ -21,9 +21,3 @@ FROM gcr.io/distroless/cc-debian12:nonroot AS worker COPY --from=builder /src/target/release/freya-worker /usr/local/bin/freya-worker USER nonroot:nonroot ENTRYPOINT ["/usr/local/bin/freya-worker"] - -FROM gcr.io/distroless/cc-debian12:nonroot AS mcp -COPY --from=builder /src/target/release/freya-mcp /usr/local/bin/freya-mcp -USER nonroot:nonroot -ENV FREYA_MCP_BIND=0.0.0.0:8090 -ENTRYPOINT ["/usr/local/bin/freya-mcp"] diff --git a/Dockerfile.web b/Dockerfile.web index 1021b44..d809041 100644 --- a/Dockerfile.web +++ b/Dockerfile.web @@ -6,8 +6,6 @@ COPY web/ ./ RUN npm run build FROM nginx:1.27-alpine -# Official image runs envsubst on /etc/nginx/templates/*.template → conf.d/ -ENV FREYA_API_UPSTREAM=http://freya-api:8080 -COPY web/nginx.conf /etc/nginx/templates/default.conf.template +COPY web/nginx.conf /etc/nginx/conf.d/default.conf COPY --from=build /web/dist /usr/share/nginx/html EXPOSE 80 diff --git a/Makefile b/Makefile index 7f7dee3..5556afb 100644 --- a/Makefile +++ b/Makefile @@ -2,15 +2,12 @@ IMG ?= harbor.dataknife.net/library/freya-operator:0.1.0 API_IMG ?= harbor.dataknife.net/library/freya-api:0.1.0 WEB_IMG ?= harbor.dataknife.net/library/freya-web:0.1.0 WORKER_IMG ?= harbor.dataknife.net/library/freya-diffusion-worker:0.1.0 -MCP_IMG ?= harbor.dataknife.net/library/freya-mcp:0.1.0 VERSION ?= 0.1.0 CARGO ?= cargo .PHONY: all help build release test fmt fmt-check lint vet ci run-api run-worker run-operator \ - run-mcp manifests install deploy up-local kind-hosts kind-tls clean docker-build \ - kind-load-mcp kind-bin-mcp kind-deploy-mcp kind-bin-api kind-bin-web kind-deploy-api-web \ - sync-api-token compose-up compose-up-gpu compose-up-mcp compose-down compose-logs compose-ps + manifests install deploy up-local clean docker-build all: build @@ -40,7 +37,7 @@ vet: fmt-check lint ## Static checks ci: vet test ## Local quality gate manifests: ## Generate CRD YAML into config/crd - bash -o pipefail -c '$(CARGO) run -q -p freya-operator --bin freya-crdgen | awk "BEGIN{p=0} /^apiVersion:/{p=1} p" > config/crd/freya.dataknife.ai_crds.yaml.tmp && test -s config/crd/freya.dataknife.ai_crds.yaml.tmp && mv config/crd/freya.dataknife.ai_crds.yaml.tmp config/crd/freya.dataknife.ai_crds.yaml || { rm -f config/crd/freya.dataknife.ai_crds.yaml.tmp; exit 1; }' + $(CARGO) run -p freya-operator --bin freya-crdgen > config/crd/freya.dataknife.ai_crds.yaml install: manifests ## Apply CRDs kubectl apply -f config/crd/freya.dataknife.ai_crds.yaml @@ -52,71 +49,17 @@ deploy: ## Deploy operator + sample studio (edit secrets first) run-api: ## Run Freya API locally $(CARGO) run -p freya-api -- --bind 127.0.0.1:8080 -run-worker: ## Run diffusion worker locally (stub PNG unless FREYA_ENGINE_URL set) +run-worker: ## Run diffusion worker stub locally $(CARGO) run -p freya-worker -- --port 8091 -.PHONY: run-local-worker -run-local-worker: ## Build/run Docker freya-local-worker with GPU + Diffusers - ./scripts/run-local-worker.sh - run-operator: ## Run operator (needs kubeconfig) $(CARGO) run -p freya-operator --bin freya-operator -run-mcp: ## Run Freya MCP Streamable HTTP locally (:8090/mcp) - $(CARGO) run -p freya-mcp -- --bind 127.0.0.1:8090 --api-url http://127.0.0.1:8080 - -up-local: ## API + notes for UI (copy .env.example → .env first) - @echo "cp .env.example .env # fill OPENROUTER_API_KEY (required)" - @echo "set -a && source .env && set +a" +up-local: ## API + notes for UI (OPENROUTER_API_KEY / CIVITAI_API_KEY in env) @echo "Terminal A: make run-api" @echo "Terminal B: cd web && npm install && npm run dev" - @echo "Optional MCP: make run-mcp # http://127.0.0.1:8090/mcp" - @echo "UI mock only: make mock-ui" - @echo "Optional worker: make run-worker then Settings → http://127.0.0.1:8091" - @echo "Optional: CIVITAI_API_KEY, FREYA_API_TOKEN, FREYA_WORKER_TOKEN, FREYA_CORS_ORIGINS" - @echo "Single-system Docker (no k8s): make compose-up # see docs/COMPOSE.md" - -# --- Docker Compose single-system (no k8s / operator; distinct from legacy/) --- -COMPOSE_FILE ?= deploy/compose/compose.yaml -COMPOSE_GPU_FILE ?= deploy/compose/compose.gpu.yaml -COMPOSE_ENV ?= deploy/compose/.env -COMPOSE := docker compose -f $(COMPOSE_FILE) --env-file $(COMPOSE_ENV) - -compose-up: ## Single-system Freya via Compose (api+web+worker) - @test -f $(COMPOSE_ENV) || (echo "Copy deploy/compose/.env.example → $(COMPOSE_ENV) and set keys"; exit 1) - $(COMPOSE) up -d --build - @echo "UI http://127.0.0.1:$${FREYA_UI_PORT:-8080} worker :$${FREYA_WORKER_PORT:-8091}" - @echo "Docs: docs/COMPOSE.md" - -compose-up-gpu: ## Compose + NVIDIA GPU for freya-worker - @test -f $(COMPOSE_ENV) || (echo "Copy deploy/compose/.env.example → $(COMPOSE_ENV) and set keys"; exit 1) - docker compose -f $(COMPOSE_FILE) -f $(COMPOSE_GPU_FILE) --env-file $(COMPOSE_ENV) up -d --build - @echo "UI http://127.0.0.1:$${FREYA_UI_PORT:-8080} worker :$${FREYA_WORKER_PORT:-8091} (GPU)" - -compose-up-mcp: ## Compose + optional freya-mcp (:8090) - @test -f $(COMPOSE_ENV) || (echo "Copy deploy/compose/.env.example → $(COMPOSE_ENV) and set keys"; exit 1) - COMPOSE_PROFILES=mcp $(COMPOSE) up -d --build - @echo "UI :8080 worker :8091 MCP http://127.0.0.1:$${FREYA_MCP_PORT:-8090}/mcp" - -compose-down: ## Stop Compose stack - @# No --env-file required for teardown; defaults in compose.yaml apply. - -docker compose -f $(COMPOSE_FILE) -f $(COMPOSE_GPU_FILE) --profile mcp down - -compose-logs: ## Follow Compose logs - $(COMPOSE) logs -f - -compose-ps: ## Compose service status - $(COMPOSE) ps - -.PHONY: mock-ui -mock-ui: ## Interactive Freya UI mock (no API / keys required) - cd web && npm install && npm run dev:mock - -kind-hosts: ## Map freya.dataknife.net → 127.0.0.1 for kind Ingress - ./scripts/kind-hosts.sh - -kind-tls: ## Sync LE *.dataknife.net wildcard into kind + nginx default cert - ./scripts/kind-sync-wildcard-tls.sh + @echo "Optional worker: make run-worker then set worker URL http://127.0.0.1:8091 in Settings" + @echo "Set OPENROUTER_API_KEY and optionally CIVITAI_API_KEY before run-api" clean: $(CARGO) clean @@ -125,57 +68,4 @@ docker-build: ## Build container images docker build -f Dockerfile -t $(IMG) --target operator . docker build -f Dockerfile -t $(API_IMG) --target api . docker build -f Dockerfile -t $(WORKER_IMG) --target worker . - docker build -f Dockerfile -t $(MCP_IMG) --target mcp . - docker build -f Dockerfile.web -t $(WEB_IMG) . - -KIND_CLUSTER ?= freya - -kind-load-mcp: ## Full Docker multi-stage build of operator+mcp → kind - docker build -f Dockerfile -t $(IMG) --target operator . - docker build -f Dockerfile -t $(MCP_IMG) --target mcp . - kind load docker-image $(IMG) --name $(KIND_CLUSTER) - kind load docker-image $(MCP_IMG) --name $(KIND_CLUSTER) - -# Fast kind path: host release binaries → distroless images (Dockerfile.bin). -kind-bin-mcp: ## cargo release + load operator/mcp images into kind - # freya-api binary required in context: legacy docker builds prior Dockerfile.bin stages. - $(CARGO) build --release -p freya-operator -p freya-mcp -p freya-api - @rm -rf /tmp/freya-bin-ctx && mkdir -p /tmp/freya-bin-ctx/target/release /tmp/freya-bin-ctx/packs - cp target/release/freya-operator target/release/freya-mcp target/release/freya-api /tmp/freya-bin-ctx/target/release/ - cp -a packs/. /tmp/freya-bin-ctx/packs/ - cp Dockerfile.bin /tmp/freya-bin-ctx/Dockerfile - docker build -f /tmp/freya-bin-ctx/Dockerfile -t $(IMG) --target operator /tmp/freya-bin-ctx - docker build -f /tmp/freya-bin-ctx/Dockerfile -t $(MCP_IMG) --target mcp /tmp/freya-bin-ctx - kind load docker-image $(IMG) --name $(KIND_CLUSTER) - kind load docker-image $(MCP_IMG) --name $(KIND_CLUSTER) - -kind-deploy-mcp: kind-bin-mcp manifests install ## Fast load + apply CRDs + restart operator - kubectl -n freya-system set image deploy/freya-operator manager=$(IMG) - kubectl -n freya-system rollout restart deploy/freya-operator - kubectl -n freya-system rollout status deploy/freya-operator --timeout=120s - @echo "MCP: https://freya.dataknife.net/mcp (after Studio reconcile)" - @echo "In-cluster: kubectl -n freya get freyastudio freya -o jsonpath='{.status.mcpEndpoint}'" - -kind-bin-api: ## cargo release freya-api → kind - $(CARGO) build --release -p freya-api -p freya-operator - @rm -rf /tmp/freya-bin-api && mkdir -p /tmp/freya-bin-api/target/release - # Legacy docker builder evaluates earlier Dockerfile.bin stages — include operator bin too. - cp target/release/freya-api target/release/freya-operator /tmp/freya-bin-api/target/release/ - cp -a packs /tmp/freya-bin-api/packs - cp Dockerfile.bin /tmp/freya-bin-api/Dockerfile - docker build -f /tmp/freya-bin-api/Dockerfile -t $(API_IMG) --target api /tmp/freya-bin-api - kind load docker-image $(API_IMG) --name $(KIND_CLUSTER) - -kind-bin-web: ## Build freya-web image → kind docker build -f Dockerfile.web -t $(WEB_IMG) . - kind load docker-image $(WEB_IMG) --name $(KIND_CLUSTER) - -kind-deploy-api-web: kind-bin-api kind-bin-web ## Load api+web into kind and restart Studio deploys - kubectl -n freya set image deploy/freya-api api=$(API_IMG) - kubectl -n freya set image deploy/freya-ui ui=$(WEB_IMG) - kubectl -n freya rollout restart deploy/freya-api deploy/freya-ui - kubectl -n freya rollout status deploy/freya-api --timeout=180s - kubectl -n freya rollout status deploy/freya-ui --timeout=120s - -sync-api-token: ## Align freya-api-token Secret with gallery PVC runtime token - ./scripts/sync-api-token-from-pvc.sh diff --git a/README.md b/README.md index fe25b68..7cb5d2e 100644 --- a/README.md +++ b/README.md @@ -6,76 +6,36 @@ Kubernetes operator and approachable NL image studio for [DataKnifeAI](https://d Freya removes the old “download GB → open Comfy/Swarm → click forever” loop: -1. **Describe** in natural language (no comma-tag recipes) -2. Optionally **ask for suggestions**; Freya **plans** and writes the model brief for you +1. **Describe** what you want +2. Freya **plans** (OpenRouter chat) and **enhances** the prompt 3. **Generate** via OpenRouter image models **or** a local/remote diffusion worker with LoRAs 4. Browse the **gallery** and remix The previous Compose/ComfyUI/SwarmUI/Ollama stack is preserved under [`legacy/`](legacy/) for reference — it is not required for the new path. -## Guidelines (required reading) - -**Freya is a tool.** It helps you plan prompts and call APIs you configure. It does not decide what is legal where you live. - -**You are liable.** Generated or downloaded content may be illegal or restricted under your country or state law. You alone are responsible for how you use Freya and what you publish — not Freya, DataKnifeAI, or the operators of an instance. - -**Bring your own keys and hardware.** You supply OpenRouter / Civitai / Hugging Face credentials and any local GPU worker. Freya only relays requests you initiate. - -**Follow third-party policies.** Freya does not replace those contracts. For any keys you configure and any prompts/assets you send or download: - -| Service | Policies | -|---------|----------| -| **OpenRouter** (chat / image / video) | [Terms](https://openrouter.ai/terms) · [Privacy](https://openrouter.ai/privacy) · [Data collection](https://openrouter.ai/docs/guides/privacy/data-collection) · [ZDR](https://openrouter.ai/docs/guides/features/zdr) | -| **Civitai** (search / LoRA install) | [Terms](https://civitai.com/content/tos) · [Privacy](https://civitai.com/content/privacy) · [Content moderation](https://civitai.com/content/moderation) · [Real-people rules](https://civitai.com/content/rules/real-people) | -| **Hugging Face** (optional HF token / Hub downloads) | [Terms](https://huggingface.co/terms-of-service) · [Privacy](https://huggingface.co/privacy) · [Content policy](https://huggingface.co/content-policy) | - -Studio **Guidelines** tab shows the full statement. First sign-in requires an acknowledgment (`localStorage` key `freya.guidelinesAck`). **Settings** links there and holds OpenRouter privacy / alignment prefs (ZDR, `data_collection`, provider allow/deny lists, model catalog filters). - ## Quick start (local) -**UI mock only** (no keys/API — for layout and flow tweaks): - ```bash -make mock-ui # or: cd web && npm i && npm run dev:mock -``` - -**Single-system Docker Compose** (no Kubernetes / operator — see [docs/COMPOSE.md](docs/COMPOSE.md)): - -```bash -cp deploy/compose/.env.example deploy/compose/.env -# OPENROUTER_API_KEY + FREYA_ADMIN_PASSWORD -make compose-up # UI :8080 (worker stays on the compose network) -# make compose-up-gpu # NVIDIA -# make compose-up-mcp # + MCP :8090 -``` - -**Full stack (cargo + Vite):** - -```bash -cp .env.example .env -# edit .env — set OPENROUTER_API_KEY=sk-or-... (required) -# optional: CIVITAI_API_KEY, FREYA_API_TOKEN, FREYA_WORKER_TOKEN, FREYA_CORS_ORIGINS -set -a && source .env && set +a +export OPENROUTER_API_KEY=sk-or-... +# optional — search/install Civitai LoRAs onto a worker +export CIVITAI_API_KEY=... make run-api # :8080 cd web && npm install && npm run dev # :5173 -# GPU worker on this host (recommended; stays out of cluster) +# optional GPU / remote worker stub make run-worker # :8091 -# then Worker tab → Host/Port → http://127.0.0.1:8091 (or LAN IP / FQDN from in-cluster Studio) +# then Settings → Diffusion worker URL → http://127.0.0.1:8091 ``` -In the UI: - -- **Settings** — OpenRouter + Civitai API keys -- **Worker** — diffusion host/port or full URL (local GPU process, not “must be in kind”) +In the UI **Settings** tab you can paste: -Sessions use **Plan / Auto / YOLO** automation (see [docs/LOCAL.md](docs/LOCAL.md)). Featured example prompt matches `freya.png` brand art. +- **OpenRouter API key** — chat + cloud images +- **Civitai API key** — search Civitai and **Install to worker** (LoRAs/checkpoints for the UI) +- **Diffusion worker URL** — in-cluster Service or a remote physical GPU host ## Cluster -Default story: **Studio + operator + Ingress in k8s** (shared cluster is fine); **GPU worker stays on the physical host** and is reached by URL. kind is a local **dev** path — production-shaped uses the same samples on shared k8s. See [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md). - ```bash make manifests install kubectl apply -k config/default @@ -83,45 +43,40 @@ kubectl apply -k config/default kubectl create ns freya kubectl -n freya create secret generic freya-openrouter --from-literal=apiKey="$OPENROUTER_API_KEY" kubectl -n freya create secret generic freya-civitai --from-literal=apiKey="$CIVITAI_API_KEY" -kubectl -n freya create secret generic freya-api-token --from-literal=token="$(openssl rand -hex 32)" -kubectl -n freya create secret generic freya-worker-token --from-literal=apiKey="$(openssl rand -hex 32)" -# recommended: external worker URL → local / LAN GPU host +# remote GPU box kubectl apply -f config/samples/freya_v1alpha1_freyadiffusionworker_external.yaml -# optional: only if the cluster itself has nvidia.com/gpu +# or in-cluster GPU # kubectl apply -f config/samples/freya_v1alpha1_freyadiffusionworker_incluster.yaml kubectl apply -f config/samples/freya_v1alpha1_freyastudio.yaml ``` -### Workers: external URL (recommended) or optional in-cluster GPU +### Workers: in-cluster or remote physical | Placement | Spec | Use when | |-----------|------|----------| -| `external` (**recommended**) | `externalEndpoint: https://host` or `http://ip:8091` | GPU box / `freya-local-worker` on the host; Studio points at it | -| `incluster` (optional) | GPU Deployment + models PVC | Cluster has `nvidia.com/gpu` — not required for Freya | +| `inCluster` | GPU Deployment + models PVC | Cluster has `nvidia.com/gpu` | +| `external` | `externalEndpoint: http://host:8091` | Physical box / bare-metal GPU | `FreyaModelAsset` (or UI **Civitai → Install to worker**) pushes LoRAs onto that worker so they show up for local generation. -Local GPU path: **Diffusers** via `./scripts/run-local-worker.sh` / `Dockerfile.worker` (checkpoints + Civitai LoRAs under `FREYA_MODELS_DIR`, on-demand VRAM). CRD label `engine: vllm-omni` still allows swapping to **[vLLM-Omni](https://github.com/vllm-project/vllm-omni)** on the same HTTP surface. Without `FREYA_ENGINE_URL`, freya-worker returns stub PNGs for wiring tests. +Preferred production engine: **[vLLM-Omni](https://github.com/vllm-project/vllm-omni)** (`/v1/images/generations` + LoRA). This repo includes a **freya-worker** stub for wiring tests. ## CRDs -- `FreyaStudio` — API + UI + gallery + **MCP** (`mcpEnabled`, default on); OpenRouter + **Civitai** + HF secret refs +- `FreyaStudio` — API + UI + gallery; OpenRouter + **Civitai** + HF secret refs - `FreyaGeneration` — declarative generate job - `FreyaStyle` — curated style packs -- `FreyaDiffusionWorker` — external URL (recommended) or optional in-cluster engine +- `FreyaDiffusionWorker` — in-cluster or external engine - `FreyaModelAsset` — install weights onto a worker -**MCP (agents):** Streamable HTTP at `https://freya.dataknife.net/mcp` (Ingress `/mcp` → `{studio}-mcp:8090`). Cursor: `{ "url": "https://freya.dataknife.net/mcp" }`. Local: `make run-mcp`. - ## Docs - [docs/CONCEPTS.md](docs/CONCEPTS.md) — map from legacy Freya - [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) — backends & secrets - [docs/OPENROUTER.md](docs/OPENROUTER.md) — cloud models - [docs/LOCAL.md](docs/LOCAL.md) — local runbook -- [docs/COMPOSE.md](docs/COMPOSE.md) — single-system Docker Compose (no k8s) ## License diff --git a/config/crd/freya.dataknife.ai_crds.yaml b/config/crd/freya.dataknife.ai_crds.yaml index dbadbbd..e4f96ad 100644 --- a/config/crd/freya.dataknife.ai_crds.yaml +++ b/config/crd/freya.dataknife.ai_crds.yaml @@ -26,17 +26,8 @@ spec: description: Auto-generated derived type for FreyaStudioSpec via `CustomResource` properties: spec: - description: 'Namespaced Freya studio: API + UI + gallery + optional MCP.' + description: 'Namespaced Freya studio: API + UI + gallery.' properties: - adminCredentialsSecretRef: - description: 'BYO admin credentials Secret (keys: `admin-password` required, `username` optional → `admin`). Used when `generateAdminSecrets` is false, or as the target name when generating.' - nullable: true - properties: - name: - type: string - required: - - name - type: object apiImage: description: Image reference for Freya components. nullable: true @@ -51,18 +42,6 @@ spec: nullable: true type: string type: object - apiTokenSecretRef: - description: Secret holding `FREYA_API_TOKEN` for the API (machine bearer for MCP/worker/UI after login). When unset and `generateAdminSecrets` is true, the operator creates `{name}-api-token`. - nullable: true - properties: - key: - default: token - type: string - name: - type: string - required: - - name - type: object chatBackend: default: kind: openrouter @@ -99,10 +78,6 @@ spec: description: Optional FreyaDiffusionWorker name in the same namespace. nullable: true type: string - generateAdminSecrets: - default: true - description: 'Game-operator style: ensure an admin login Secret (`username` + `admin-password`) and, when `apiTokenSecretRef` is unset, an API bearer Secret. Default true.' - type: boolean huggingFace: default: {} description: Optional Hugging Face token for gated checkpoints. @@ -133,35 +108,12 @@ spec: host: nullable: true type: string - tlsSecretName: - description: 'TLS Secret in the Studio namespace (e.g. `wildcard-dataknife-net-tls`). Fleet pattern: same Let''s Encrypt `*.dataknife.net` secret synced to `kube-system` as the ingress default cert; copy into this namespace when setting `tlsSecretName`. Omit to rely on the controller default cert only.' - nullable: true - type: string - type: object - mcpEnabled: - default: true - description: Deploy Freya MCP (`{name}-mcp`) and Ingress path `/mcp`. Default true. - type: boolean - mcpImage: - description: MCP Streamable HTTP server image (defaults to harbor freya-mcp). - nullable: true - properties: - pullPolicy: - nullable: true - type: string - repository: - nullable: true - type: string - tag: - nullable: true - type: string type: object openRouter: default: baseUrl: https://openrouter.ai/api/v1 - chatModel: auto - imageModel: auto - routerModel: auto + chatModel: openrouter/auto + imageModel: black-forest-labs/flux.2-klein-4b secretRef: key: apiKey name: freya-openrouter @@ -170,16 +122,12 @@ spec: default: https://openrouter.ai/api/v1 type: string chatModel: - default: auto - description: Default chat / plan model id. `auto` = Freya internal Auto (not `openrouter/auto`). + default: openrouter/auto + description: Default chat / plan model id (OpenRouter). type: string imageModel: - default: auto - description: Default cloud image model id. `auto` = Freya router / Flux NL default. - type: string - routerModel: - default: auto - description: Freya-owned light intent router model. `auto` = Llama 3.1 8B-class (dolphin3 spirit). + default: black-forest-labs/flux.2-klein-4b + description: Default cloud image model id (OpenRouter). type: string secretRef: description: Reference to a Secret key holding credentials. @@ -228,25 +176,9 @@ spec: status: nullable: true properties: - adminCredentialsGenerated: - description: True when the operator generated (or filled) the admin credentials Secret. - nullable: true - type: boolean - adminCredentialsSecretName: - description: Secret holding admin login (`username` + `admin-password`). Never includes the password. - nullable: true - type: string apiEndpoint: nullable: true type: string - apiTokenSecretName: - description: Secret holding the machine API bearer (`token` key). - nullable: true - type: string - mcpEndpoint: - description: In-cluster MCP Streamable HTTP base, e.g. `http://freya-mcp.freya.svc:8090/mcp`. - nullable: true - type: string observedGeneration: format: int64 nullable: true @@ -503,7 +435,7 @@ spec: description: |- Optional GPU worker for local SD / LoRA (vLLM-Omni by default). - Placement: - `external` (**recommended**) — point `externalEndpoint` at the GPU host running `freya-local-worker` / vLLM-Omni (or compatible `/v1/images/generations` + LoRA install). Studio stays in-cluster; the worker stays out-of-cluster via URL. - `incluster` (optional) — operator deploys the engine only when the cluster has GPUs. + Placement: - `inCluster` — operator deploys the engine on a GPU node when the cluster has GPUs. - `external` — point `externalEndpoint` at a remote physical system running vLLM-Omni (or compatible `/v1/images/generations` + LoRA install API). Freya UI/API use that endpoint; `FreyaModelAsset` installs LoRAs onto the remote worker for the UI catalog. properties: authSecretRef: description: Optional admin/API token Secret for remote LoRA install + generate. @@ -559,10 +491,7 @@ spec: type: object placement: default: incluster - description: |- - Where the diffusion / LoRA engine runs. - - CRD enum values are lowercase (`incluster`, `external`). The `inCluster` alias is accepted by Rust serde for convenience; kubectl/OpenAPI only allow `incluster`. + description: Where the diffusion / LoRA engine runs. enum: - incluster - external diff --git a/config/rbac/role.yaml b/config/rbac/role.yaml index 6cb35a7..713652a 100644 --- a/config/rbac/role.yaml +++ b/config/rbac/role.yaml @@ -20,10 +20,7 @@ rules: resources: ["deployments"] verbs: ["get", "list", "watch", "create", "update", "patch", "delete"] - apiGroups: [""] - resources: ["services", "persistentvolumeclaims", "pods", "configmaps", "secrets", "serviceaccounts"] - verbs: ["get", "list", "watch", "create", "update", "patch", "delete"] - - apiGroups: ["rbac.authorization.k8s.io"] - resources: ["roles", "rolebindings"] + resources: ["services", "persistentvolumeclaims", "pods", "configmaps", "secrets"] verbs: ["get", "list", "watch", "create", "update", "patch", "delete"] - apiGroups: ["batch"] resources: ["jobs"] diff --git a/config/samples/freya_v1alpha1_freyadiffusionworker_external.yaml b/config/samples/freya_v1alpha1_freyadiffusionworker_external.yaml index 81a5de4..7441038 100644 --- a/config/samples/freya_v1alpha1_freyadiffusionworker_external.yaml +++ b/config/samples/freya_v1alpha1_freyadiffusionworker_external.yaml @@ -1,29 +1,10 @@ -# Recommended: GPU worker stays on the physical host; Studio reaches it by URL. -# (Shared k8s for operator/Studio/MCP/Ingress is fine — Freya does not need in-cluster GPU.) -# -# Run on the GPU host: make run-worker OR Docker freya-local-worker (0.0.0.0:8091) -# Then pick an externalEndpoint the in-cluster API can dial: -# - FQDN / Ingress: https://vllm.dataknife.net (this lab; DNS → GPU host) -# - LAN IP + port: http://192.168.3.125:8091 (Worker tab Host/Port) -# - localhost: http://127.0.0.1:8091 (API hostNetwork / make run-api on same host) -# - k8s DNS bridge: http://freya-gpu-host.freya.svc.cluster.local:8091 -# (optional ExternalName / Endpoints Service → host) -# -# Worker tab Setup copy matches these forms. Optional alternate: *_incluster.yaml +# Remote physical GPU box (or any host running vLLM-Omni / freya-worker) apiVersion: freya.dataknife.ai/v1alpha1 kind: FreyaDiffusionWorker metadata: name: freya-gpu namespace: freya - # Do not set freya.dataknife.ai/tls-insecure on a public HTTPS endpoint. - # Studio verifies that certificate. The annotation only skips verify for - # loopback, private, link-local, and cluster DNS hosts. spec: placement: external - # Public / LAN URL of freya-local-worker (or vLLM-Omni-compatible) — not the Freya UI host. - externalEndpoint: https://vllm.dataknife.net + externalEndpoint: http://gpu-box.lan:8091 engine: vllm-omni - # Must match FREYA_WORKER_TOKEN on the remote worker process - authSecretRef: - name: freya-worker-token - key: apiKey diff --git a/config/samples/freya_v1alpha1_freyadiffusionworker_incluster.yaml b/config/samples/freya_v1alpha1_freyadiffusionworker_incluster.yaml index 9bfa0a4..8579b40 100644 --- a/config/samples/freya_v1alpha1_freyadiffusionworker_incluster.yaml +++ b/config/samples/freya_v1alpha1_freyadiffusionworker_incluster.yaml @@ -1,18 +1,13 @@ -# Optional alternate — only when the cluster itself has nvidia.com/gpu. -# Recommended default is *_external.yaml (local GPU host via URL). See docs/ARCHITECTURE.md. +# In-cluster GPU Deployment (requires nvidia.com/gpu) apiVersion: freya.dataknife.ai/v1alpha1 kind: FreyaDiffusionWorker metadata: name: freya-gpu namespace: freya spec: - placement: incluster + placement: inCluster engine: vllm-omni model: stabilityai/stable-diffusion-xl-base-1.0 gpuCount: 1 modelsPvcSize: 100Gi port: 8091 - # Same secret as FreyaStudio → FREYA_WORKER_TOKEN on API + worker - authSecretRef: - name: freya-worker-token - key: apiKey diff --git a/config/samples/freya_v1alpha1_freyastudio.yaml b/config/samples/freya_v1alpha1_freyastudio.yaml index 2a2edf0..ee630c6 100644 --- a/config/samples/freya_v1alpha1_freyastudio.yaml +++ b/config/samples/freya_v1alpha1_freyastudio.yaml @@ -5,28 +5,12 @@ metadata: namespace: freya spec: replicas: 1 - # MCP Streamable HTTP (default true) → Deployment freya-mcp + Ingress /mcp - mcpEnabled: true - # mcpImage: - # repository: harbor.dataknife.net/library/freya-mcp - # tag: "0.1.0" openRouter: secretRef: name: freya-openrouter key: apiKey - chatModel: auto - imageModel: auto - routerModel: auto - # Game-operator style: operator generates freya-admin (username + admin-password) - # and uses this bearer Secret for MCP/machine auth. UI: Sign in with admin password. - generateAdminSecrets: true - # Optional BYO admin Secret name (default: {studio}-admin). - # adminCredentialsSecretRef: - # name: freya-admin - # Machine bearer for MCP/API (UI obtains it via Sign in, or paste Apply token). - apiTokenSecretRef: - name: freya-api-token - key: token + chatModel: openrouter/auto + imageModel: black-forest-labs/flux.2-klein-4b # Optional — search Civitai + install LoRAs onto the worker for the UI civitai: secretRef: @@ -36,40 +20,12 @@ spec: secretRef: name: freya-hf key: token - # Points at FreyaDiffusionWorker/freya-gpu — apply *_external.yaml (recommended local GPU URL). diffusionWorkerRef: freya-gpu storage: gallerySize: 20Gi ingress: - enabled: true - className: nginx - host: freya.dataknife.net - # Fleet TLS: Let's Encrypt *.dataknife.net (same secret as Traefik/Harbor). - # Kind (dev): make kind-tls # copies kube-system/wildcard-dataknife-net-tls + sets nginx default - # Omit tlsSecretName to rely only on the ingress controller default cert. - tlsSecretName: wildcard-dataknife-net-tls + enabled: false --- -# Create Secrets first (see README Cluster section). Env equivalents for local: -# OPENROUTER_API_KEY, CIVITAI_API_KEY, HF_TOKEN, FREYA_API_TOKEN, FREYA_WORKER_TOKEN -# Cluster Secret names: -# freya-openrouter key=apiKey -# freya-civitai key=apiKey -# freya-hf key=token -# freya-api-token key=token (openssl rand -hex 32) -# freya-worker-token key=apiKey (openssl rand -hex 32) -# wildcard-dataknife-net-tls (TLS; make kind-tls or gitops cert-sync) -# Architecture: Studio/operator/MCP/Ingress in k8s (shared cluster OK); GPU worker on host via URL. -# kind is a local dev path — same CRs work production-shaped on shared k8s. See docs/ARCHITECTURE.md. -# Optional style pack sample: freya_v1alpha1_freyastyle.yaml (freya.png NL example) -# Public UI: https://freya.dataknife.net — for kind, run ./scripts/kind-hosts.sh -# Public MCP (Streamable HTTP): https://freya.dataknife.net/mcp -# Cursor MCP config example: -# { -# "mcpServers": { -# "freya": { -# "url": "https://freya.dataknife.net/mcp" -# } -# } -# } -# In-cluster: http://freya-mcp.freya.svc.cluster.local:8090/mcp -# (public DNS still points at prd-apps Traefik → plain-text "404 page not found") +# kubectl -n freya create secret generic freya-openrouter --from-literal=apiKey=sk-or-... +# kubectl -n freya create secret generic freya-civitai --from-literal=apiKey=YOUR_CIVITAI_KEY +# kubectl -n freya create secret generic freya-hf --from-literal=token=hf_... diff --git a/crates/freya-api/Cargo.toml b/crates/freya-api/Cargo.toml index 0cbc9d4..01c5222 100644 --- a/crates/freya-api/Cargo.toml +++ b/crates/freya-api/Cargo.toml @@ -25,4 +25,3 @@ tracing = { workspace = true } tracing-subscriber = { workspace = true } uuid = { workspace = true } thiserror = { workspace = true } -libc = "0.2" diff --git a/crates/freya-api/src/civitai.rs b/crates/freya-api/src/civitai.rs index 89b8789..2f64f21 100644 --- a/crates/freya-api/src/civitai.rs +++ b/crates/freya-api/src/civitai.rs @@ -4,41 +4,6 @@ use anyhow::{anyhow, Context, Result}; use serde::{Deserialize, Serialize}; use serde_json::Value; -/// Installable weight types Freya surfaces by default (not every Civitai ModelType). -pub const DEFAULT_SEARCH_TYPES: &[&str] = &[ - "LORA", - "LoCon", - "DoRA", - "Checkpoint", - "TextualInversion", - "VAE", -]; - -/// True when `model_type` is a Freya-supported installable asset. -pub fn is_freya_asset_type(model_type: &str) -> bool { - let t = model_type.trim(); - DEFAULT_SEARCH_TYPES - .iter() - .any(|allowed| t.eq_ignore_ascii_case(allowed)) - || t.eq_ignore_ascii_case("LyCORIS") -} - -/// Rank adapters ahead of checkpoints / embeddings / VAEs for Suggest. -pub fn asset_type_rank(model_type: &str) -> u8 { - let t = model_type.to_ascii_lowercase(); - if t == "lora" || t == "locon" || t == "dora" || t == "lycoris" || t.contains("lora") { - 0 - } else if t == "checkpoint" { - 1 - } else if t == "textualinversion" { - 2 - } else if t == "vae" { - 3 - } else { - 4 - } -} - #[derive(Clone)] pub struct CivitaiClient { http: reqwest::Client, @@ -58,690 +23,93 @@ impl CivitaiClient { } pub async fn search(&self, query: &str, limit: u32) -> Result> { - self.search_types(query, limit, DEFAULT_SEARCH_TYPES).await - } - - /// Search Civitai, optionally restricting to `types` (passed as repeated `types=` params). - pub async fn search_types( - &self, - query: &str, - limit: u32, - types: &[&str], - ) -> Result> { if !self.configured() { return Err(anyhow!( "Civitai API key not set — add it in Freya Settings or CIVITAI_API_KEY" )); } - let mut url = format!( + let url = format!( "https://civitai.com/api/v1/models?limit={limit}&query={}", urlencoding_lite(query) ); - for t in types { - let trimmed = t.trim(); - if !trimmed.is_empty() { - url.push_str("&types="); - url.push_str(&urlencoding_lite(trimmed)); - } - } - let v = self.get_json(&url).await.context("civitai search")?; - let mut out = Vec::new(); - if let Some(items) = v.get("items").and_then(|i| i.as_array()) { - for item in items { - out.push(parse_model_card(item, false)); - } - } - Ok(out) - } - - /// Full model detail (+ related checkpoints for non-checkpoint assets when baseModel is known). - pub async fn get_model(&self, id: i64) -> Result { - if !self.configured() { - return Err(anyhow!( - "Civitai API key not set — add it in Freya Settings or CIVITAI_API_KEY" - )); - } - let url = format!("https://civitai.com/api/v1/models/{id}"); - let v = self.get_json(&url).await.context("civitai get model")?; - if v.get("error").is_some() { - return Err(anyhow!( - "civitai model {}: {}", - id, - v.get("error") - .and_then(|e| e.as_str()) - .unwrap_or("not found") - )); - } - let mut detail = parse_model_detail(&v); - // Civitai has no first-class dependency graph; use version baseModel → popular checkpoints. - if !detail.model_type.eq_ignore_ascii_case("Checkpoint") { - if let Some(base) = detail - .base_model - .as_deref() - .filter(|b| !b.is_empty() && !b.eq_ignore_ascii_case("Other")) - { - match self.related_checkpoints(base, 4).await { - Ok(related) => { - detail.related = related - .into_iter() - .filter(|c| c.id != detail.id) - .collect(); - if detail.needs_base.is_none() { - detail.needs_base = Some(format!("Needs base model family: {base}")); - } - } - Err(_) => { - detail.needs_base = Some(format!("Needs base model family: {base}")); - } - } - } - } - Ok(detail) - } - - async fn related_checkpoints(&self, base_model: &str, limit: u32) -> Result> { - let url = format!( - "https://civitai.com/api/v1/models?limit={limit}&types=Checkpoint&baseModels={}&sort={}", - urlencoding_lite(base_model), - urlencoding_lite("Most Downloaded") - ); - let v = self.get_json(&url).await.context("civitai related checkpoints")?; - let mut out = Vec::new(); - if let Some(items) = v.get("items").and_then(|i| i.as_array()) { - for item in items { - out.push(parse_model_card(item, false)); - } - } - Ok(out) - } - - /// Resolve a download URL from a Civitai model version (+ optional file id). - pub async fn resolve_version_download( - &self, - version_id: i64, - file_id: Option, - ) -> Result { - if !self.configured() { - return Err(anyhow!( - "Civitai API key not set — add it in Freya Settings or CIVITAI_API_KEY" - )); - } - let url = format!("https://civitai.com/api/v1/model-versions/{version_id}"); - let v = self - .get_json(&url) - .await - .context("civitai get model version")?; - if v.get("error").is_some() { - return Err(anyhow!( - "civitai model version {}: {}", - version_id, - v.get("error") - .and_then(|e| e.as_str()) - .unwrap_or("not found") - )); - } - let version = parse_model_version(&v, 1); - let model_id = v.get("modelId").and_then(|x| x.as_i64()); - let file = if let Some(fid) = file_id { - version - .files - .iter() - .find(|f| f.id == Some(fid)) - .or_else(|| pick_primary_file(&version.files)) - } else { - pick_primary_file(&version.files) - } - .ok_or_else(|| anyhow!("civitai model version {version_id}: no files"))?; - let download_url = file - .download_url - .clone() - .ok_or_else(|| anyhow!("civitai model version {version_id}: file has no downloadUrl"))?; - Ok(ResolvedDownload { - download_url, - version_id: version.id, - version_name: Some(version.name), - base_model: version.base_model, - file_id: file.id, - file_name: file.name.clone(), - file_format: file.format.clone().or_else(|| file.file_type.clone()), - model_id, - thumbnail_url: version - .image_urls - .as_ref() - .and_then(|imgs| imgs.first().cloned()), - }) - } - - /// Resolve a version id → full model detail (for Installed cards that only have versionId). - pub async fn get_model_by_version(&self, version_id: i64) -> Result { - if !self.configured() { - return Err(anyhow!( - "Civitai API key not set — add it in Freya Settings or CIVITAI_API_KEY" - )); - } - let url = format!("https://civitai.com/api/v1/model-versions/{version_id}"); - let v = self - .get_json(&url) - .await - .context("civitai get model version")?; - if v.get("error").is_some() { - return Err(anyhow!( - "civitai model version {}: {}", - version_id, - v.get("error") - .and_then(|e| e.as_str()) - .unwrap_or("not found") - )); - } - let model_id = v - .get("modelId") - .and_then(|x| x.as_i64()) - .ok_or_else(|| anyhow!("civitai model version {version_id}: missing modelId"))?; - let mut detail = self.get_model(model_id).await?; - // Prefer the installed version when present on the model. - if detail - .model_versions - .iter() - .any(|ver| ver.id == version_id) - { - if let Some(ver) = detail - .model_versions - .iter() - .find(|ver| ver.id == version_id) - .cloned() - { - detail.version_id = Some(ver.id); - detail.version_name = Some(ver.name.clone()); - detail.base_model = ver.base_model.clone().or(detail.base_model); - detail.trained_words = ver.trained_words.clone().or(detail.trained_words); - detail.trigger_word = detail - .trained_words - .as_ref() - .and_then(|w| w.first().cloned()) - .or(detail.trigger_word); - if let Some(imgs) = &ver.image_urls { - if !imgs.is_empty() { - detail.image_urls = Some(imgs.clone()); - detail.thumbnail_url = Some(imgs[0].clone()); - } - } - if let Some(file) = pick_primary_file(&ver.files) { - detail.file_id = file.id; - detail.file_name = file.name.clone(); - detail.file_format = file.format.clone().or_else(|| file.file_type.clone()); - detail.download_url = file.download_url.clone(); - } - } - } - Ok(detail) - } - - async fn get_json(&self, url: &str) -> Result { let resp = self .http - .get(url) + .get(&url) .header("Authorization", format!("Bearer {}", self.api_key)) .send() .await - .context("civitai http")?; + .context("civitai search")?; let status = resp.status(); let text = resp.text().await.unwrap_or_default(); if !status.is_success() { return Err(anyhow!("civitai {status}: {text}")); } - serde_json::from_str(&text).context("civitai json") - } -} - -/// Download target resolved from a version (+ optional file) id. -#[derive(Debug, Clone)] -#[allow(dead_code)] -pub struct ResolvedDownload { - pub download_url: String, - pub version_id: i64, - pub version_name: Option, - pub base_model: Option, - pub file_id: Option, - pub file_name: Option, - pub file_format: Option, - pub model_id: Option, - pub thumbnail_url: Option, -} - -fn parse_trained_words(ver: &Value) -> Vec { - let mut trained_words = Vec::new(); - if let Some(words) = ver.get("trainedWords").and_then(|w| w.as_array()) { - for w in words { - if let Some(s) = w.as_str() { - let trimmed = s.trim().trim_end_matches(','); - if !trimmed.is_empty() { - trained_words.push(trimmed.to_string()); - } - } - } - } - trained_words -} - -fn parse_model_file(f: &Value) -> CivitaiModelFile { - let size_kb = f - .get("sizeKB") - .and_then(|x| x.as_f64()) - .or_else(|| f.get("sizeKB").and_then(|x| x.as_i64()).map(|n| n as f64)); - let size_bytes = size_kb.map(|kb| (kb * 1024.0).round() as i64).or_else(|| { - f.get("size") - .and_then(|x| x.as_i64()) - .or_else(|| f.get("sizeBytes").and_then(|x| x.as_i64())) - }); - let format = f - .pointer("/metadata/format") - .and_then(|x| x.as_str()) - .or_else(|| f.get("format").and_then(|x| x.as_str())) - .map(|s| s.to_string()); - let file_type = f - .get("type") - .and_then(|x| x.as_str()) - .map(|s| s.to_string()); - CivitaiModelFile { - id: f.get("id").and_then(|x| x.as_i64()), - name: f - .get("name") - .and_then(|x| x.as_str()) - .map(|s| s.to_string()), - size_kb, - size_bytes, - file_type, - format, - primary: f.get("primary").and_then(|p| p.as_bool()).unwrap_or(false), - download_url: f - .get("downloadUrl") - .and_then(|u| u.as_str()) - .map(|s| s.to_string()), - } -} - -fn parse_model_version(ver: &Value, image_limit: usize) -> CivitaiModelVersion { - let trained_words = parse_trained_words(ver); - let files: Vec = ver - .get("files") - .and_then(|f| f.as_array()) - .map(|arr| arr.iter().map(parse_model_file).collect()) - .unwrap_or_default(); - let mut image_urls = Vec::new(); - let mut example_prompt = None; - if let Some(images) = ver.get("images").and_then(|i| i.as_array()) { - for img in images.iter().take(image_limit) { - if let Some(u) = img.get("url").and_then(|u| u.as_str()) { - image_urls.push(u.to_string()); - if example_prompt.is_none() { - example_prompt = img - .pointer("/meta/prompt") - .and_then(|p| p.as_str()) - .map(|s| s.to_string()); - } - } - } - } - CivitaiModelVersion { - id: ver.get("id").and_then(|x| x.as_i64()).unwrap_or(0), - name: ver - .get("name") - .and_then(|x| x.as_str()) - .unwrap_or("untitled") - .to_string(), - base_model: ver - .get("baseModel") - .and_then(|x| x.as_str()) - .map(|s| s.to_string()), - created_at: ver - .get("createdAt") - .and_then(|x| x.as_str()) - .map(|s| s.to_string()), - trained_words: if trained_words.is_empty() { - None - } else { - Some(trained_words) - }, - files, - image_urls: if image_urls.is_empty() { - None - } else { - Some(image_urls) - }, - example_prompt, - } -} - -fn pick_primary_file(files: &[CivitaiModelFile]) -> Option<&CivitaiModelFile> { - files - .iter() - .find(|f| f.primary) - .or_else(|| files.first()) -} - -fn parse_model_card(item: &Value, detailed: bool) -> CivitaiModelCard { - let id = item.get("id").and_then(|x| x.as_i64()).unwrap_or(0); - let name = item - .get("name") - .and_then(|x| x.as_str()) - .unwrap_or("untitled") - .to_string(); - let model_type = item - .get("type") - .and_then(|x| x.as_str()) - .unwrap_or("Checkpoint") - .to_string(); - let creator = item - .pointer("/creator/username") - .and_then(|u| u.as_str()) - .map(|s| s.to_string()); - let download_count = item - .pointer("/stats/downloadCount") - .and_then(|x| x.as_i64()); - let thumbs_up = item - .pointer("/stats/thumbsUpCount") - .and_then(|x| x.as_i64()); - - let image_limit = if detailed { 12 } else { 1 }; - let model_versions: Vec = item - .get("modelVersions") - .and_then(|m| m.as_array()) - .map(|arr| { - arr.iter() - .map(|ver| parse_model_version(ver, image_limit)) - .collect() - }) - .unwrap_or_default(); - - // Default selection: first version + primary/first file (preserves prior behavior). - let mut download_url = None; - let mut version_id = None; - let mut version_name = None; - let mut file_id = None; - let mut file_name = None; - let mut file_format = None; - let mut example_prompt = None; - let mut thumbnail = None; - let mut base_model = None; - let mut trained_words: Vec = Vec::new(); - let mut image_urls: Vec = Vec::new(); - - if let Some(ver) = model_versions.first() { - version_id = Some(ver.id); - version_name = Some(ver.name.clone()); - base_model = ver.base_model.clone().or_else(|| { - item.get("baseModels") - .and_then(|b| b.as_array()) - .and_then(|a| a.first()) - .and_then(|x| x.as_str()) - .map(|s| s.to_string()) - }); - if let Some(words) = ver.trained_words.as_ref() { - trained_words = words.clone(); - } - if let Some(file) = pick_primary_file(&ver.files) { - download_url = file.download_url.clone(); - file_id = file.id; - file_name = file.name.clone(); - file_format = file.format.clone().or_else(|| file.file_type.clone()); - } - if let Some(imgs) = ver.image_urls.as_ref() { - for u in imgs { - if thumbnail.is_none() { - thumbnail = Some(u.clone()); + let v: Value = serde_json::from_str(&text)?; + let mut out = Vec::new(); + if let Some(items) = v.get("items").and_then(|i| i.as_array()) { + for item in items { + let id = item.get("id").and_then(|x| x.as_i64()).unwrap_or(0); + let name = item + .get("name") + .and_then(|x| x.as_str()) + .unwrap_or("untitled") + .to_string(); + let model_type = item + .get("type") + .and_then(|x| x.as_str()) + .unwrap_or("Checkpoint") + .to_string(); + let mut download_url = None; + let mut version_id = None; + let mut example_prompt = None; + let mut thumbnail = None; + if let Some(versions) = item.get("modelVersions").and_then(|m| m.as_array()) { + if let Some(ver) = versions.first() { + version_id = ver.get("id").and_then(|x| x.as_i64()); + if let Some(files) = ver.get("files").and_then(|f| f.as_array()) { + download_url = files + .first() + .and_then(|f| f.get("downloadUrl")) + .and_then(|u| u.as_str()) + .map(|s| s.to_string()); + } + if let Some(images) = ver.get("images").and_then(|i| i.as_array()) { + if let Some(img) = images.first() { + thumbnail = img + .get("url") + .and_then(|u| u.as_str()) + .map(|s| s.to_string()); + example_prompt = img + .pointer("/meta/prompt") + .and_then(|p| p.as_str()) + .map(|s| s.to_string()); + } + } + } } - image_urls.push(u.clone()); + out.push(CivitaiModelCard { + id, + name, + model_type, + version_id, + download_url, + thumbnail_url: thumbnail, + example_prompt, + }); } } - example_prompt = ver.example_prompt.clone(); - } - - let description = item - .get("description") - .and_then(|d| d.as_str()) - .map(strip_html_brief); - - let trigger_word = trained_words.first().cloned(); - let stats = if download_count.is_some() || thumbs_up.is_some() { - Some(CivitaiStats { - download_count, - thumbs_up_count: thumbs_up, - }) - } else { - None - }; - - let nsfw = item.get("nsfw").and_then(|x| x.as_bool()).unwrap_or(false) - || item - .get("nsfwLevel") - .and_then(|x| x.as_i64()) - .map(|n| n > 1) - .unwrap_or(false) - || crate::prefs::looks_nsfw_label(&name); - - CivitaiModelCard { - id, - name, - model_type, - version_id, - version_name, - file_id, - file_name, - file_format, - download_url, - thumbnail_url: thumbnail, - example_prompt, - base_model, - trained_words: if trained_words.is_empty() { - None - } else { - Some(trained_words) - }, - trigger_word, - description, - creator, - download_count, - thumbs_up, - stats, - image_urls: if image_urls.is_empty() { - None - } else { - Some(image_urls) - }, - civitai_url: Some(format!("https://civitai.com/models/{id}")), - nsfw, - model_versions, - } -} - -fn parse_model_detail(item: &Value) -> CivitaiModelDetail { - let card = parse_model_card(item, true); - let needs_base = card.base_model.as_ref().and_then(|b| { - if card.model_type.eq_ignore_ascii_case("Checkpoint") { - None - } else { - Some(format!("Needs base model family: {b}")) - } - }); - CivitaiModelDetail { - id: card.id, - name: card.name, - model_type: card.model_type, - version_id: card.version_id, - version_name: card.version_name, - file_id: card.file_id, - file_name: card.file_name, - file_format: card.file_format, - download_url: card.download_url, - thumbnail_url: card.thumbnail_url, - example_prompt: card.example_prompt, - base_model: card.base_model, - trained_words: card.trained_words, - trigger_word: card.trigger_word, - description: card.description, - creator: card.creator, - download_count: card.download_count, - thumbs_up: card.thumbs_up, - image_urls: card.image_urls, - civitai_url: card.civitai_url, - needs_base, - model_versions: card.model_versions, - related: Vec::new(), - } -} - -/// Strip HTML tags and collapse whitespace for a short plain-text blurb. -fn strip_html_brief(html: &str) -> String { - let mut out = String::with_capacity(html.len()); - let mut in_tag = false; - for ch in html.chars() { - match ch { - '<' => in_tag = true, - '>' => in_tag = false, - _ if !in_tag => out.push(ch), - _ => {} - } - } - let collapsed: String = out.split_whitespace().collect::>().join(" "); - if collapsed.chars().count() > 420 { - let trimmed: String = collapsed.chars().take(417).collect(); - format!("{trimmed}…") - } else { - collapsed + Ok(out) } } fn urlencoding_lite(s: &str) -> String { - // Percent-encode UTF-8 bytes (not truncated chars) for non-ASCII queries. - let mut out = String::with_capacity(s.len() * 3); - for &b in s.as_bytes() { - match b { - b'a'..=b'z' | b'A'..=b'Z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => { - out.push(b as char); - } - b' ' => out.push_str("%20"), - _ => out.push_str(&format!("%{b:02X}")), - } - } - out -} - -#[cfg(test)] -mod tests { - use super::*; - use serde_json::json; - - #[test] - fn parse_card_defaults_to_first_version_primary_file() { - let item = json!({ - "id": 42, - "name": "Test LoRA", - "type": "LORA", - "nsfw": false, - "creator": { "username": "alice" }, - "stats": { "downloadCount": 10, "thumbsUpCount": 2 }, - "modelVersions": [ - { - "id": 100, - "name": "v1", - "baseModel": "SDXL 1.0", - "createdAt": "2024-01-01T00:00:00.000Z", - "trainedWords": ["trigger"], - "files": [ - { - "id": 1, - "name": "model.ckpt", - "sizeKB": 100.0, - "type": "Model", - "metadata": { "format": "PickleTensor" }, - "primary": false, - "downloadUrl": "https://civitai.com/api/download/models/1" - }, - { - "id": 2, - "name": "model.safetensors", - "sizeKB": 90.0, - "type": "Model", - "metadata": { "format": "SafeTensor" }, - "primary": true, - "downloadUrl": "https://civitai.com/api/download/models/2" - } - ], - "images": [{ "url": "https://example.com/a.png", "meta": { "prompt": "hi" } }] - }, - { - "id": 101, - "name": "v2", - "baseModel": "Pony", - "files": [{ - "id": 3, - "name": "v2.safetensors", - "primary": true, - "downloadUrl": "https://civitai.com/api/download/models/3" - }] - } - ] - }); - let card = parse_model_card(&item, true); - assert_eq!(card.version_id, Some(100)); - assert_eq!(card.version_name.as_deref(), Some("v1")); - assert_eq!(card.file_id, Some(2)); - assert_eq!(card.file_name.as_deref(), Some("model.safetensors")); - assert_eq!(card.file_format.as_deref(), Some("SafeTensor")); - assert_eq!( - card.download_url.as_deref(), - Some("https://civitai.com/api/download/models/2") - ); - assert_eq!(card.base_model.as_deref(), Some("SDXL 1.0")); - assert_eq!(card.model_versions.len(), 2); - assert_eq!(card.model_versions[0].files.len(), 2); - assert_eq!(card.model_versions[1].base_model.as_deref(), Some("Pony")); - let detail = parse_model_detail(&item); - assert_eq!(detail.model_versions.len(), 2); - assert_eq!(detail.file_id, Some(2)); - } -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct CivitaiModelFile { - #[serde(skip_serializing_if = "Option::is_none")] - pub id: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub name: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub size_kb: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub size_bytes: Option, - /// Civitai file `type` (e.g. Model, Pruned Model, Training Data). - #[serde(rename = "type", skip_serializing_if = "Option::is_none")] - pub file_type: Option, - /// Format from metadata (SafeTensor, PickleTensor, …). - #[serde(skip_serializing_if = "Option::is_none")] - pub format: Option, - #[serde(default)] - pub primary: bool, - #[serde(skip_serializing_if = "Option::is_none")] - pub download_url: Option, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct CivitaiModelVersion { - pub id: i64, - pub name: String, - #[serde(skip_serializing_if = "Option::is_none")] - pub base_model: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub created_at: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub trained_words: Option>, - #[serde(default, skip_serializing_if = "Vec::is_empty")] - pub files: Vec, - #[serde(skip_serializing_if = "Option::is_none")] - pub image_urls: Option>, - #[serde(skip_serializing_if = "Option::is_none")] - pub example_prompt: Option, + s.chars() + .map(|c| match c { + 'a'..='z' | 'A'..='Z' | '0'..='9' | '-' | '_' | '.' | '~' => c.to_string(), + ' ' => "%20".into(), + _ => format!("%{:02X}", c as u8), + }) + .collect() } #[derive(Debug, Clone, Serialize, Deserialize)] @@ -753,103 +121,9 @@ pub struct CivitaiModelCard { #[serde(skip_serializing_if = "Option::is_none")] pub version_id: Option, #[serde(skip_serializing_if = "Option::is_none")] - pub version_name: Option, - /// Selected file within the default (or chosen) version. - #[serde(skip_serializing_if = "Option::is_none")] - pub file_id: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub file_name: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub file_format: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub download_url: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub thumbnail_url: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub example_prompt: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub base_model: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub trained_words: Option>, - #[serde(skip_serializing_if = "Option::is_none")] - pub trigger_word: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub description: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub creator: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub download_count: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub thumbs_up: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub stats: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub image_urls: Option>, - #[serde(skip_serializing_if = "Option::is_none")] - pub civitai_url: Option, - /// From Civitai `nsfw` / nsfwLevel — used when Freya NSFW filter is off. - #[serde(default)] - pub nsfw: bool, - /// All versions + file variants (present on search when Civitai returns them; always on detail). - #[serde(default, skip_serializing_if = "Vec::is_empty")] - pub model_versions: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct CivitaiStats { - #[serde(skip_serializing_if = "Option::is_none")] - pub download_count: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub thumbs_up_count: Option, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct CivitaiModelDetail { - pub id: i64, - pub name: String, - pub model_type: String, - #[serde(skip_serializing_if = "Option::is_none")] - pub version_id: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub version_name: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub file_id: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub file_name: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub file_format: Option, - #[serde(skip_serializing_if = "Option::is_none")] pub download_url: Option, #[serde(skip_serializing_if = "Option::is_none")] pub thumbnail_url: Option, #[serde(skip_serializing_if = "Option::is_none")] pub example_prompt: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub base_model: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub trained_words: Option>, - #[serde(skip_serializing_if = "Option::is_none")] - pub trigger_word: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub description: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub creator: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub download_count: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub thumbs_up: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub image_urls: Option>, - #[serde(skip_serializing_if = "Option::is_none")] - pub civitai_url: Option, - /// Human hint when adapters need a compatible checkpoint family. - #[serde(skip_serializing_if = "Option::is_none")] - pub needs_base: Option, - #[serde(default, skip_serializing_if = "Vec::is_empty")] - pub model_versions: Vec, - /// Popular checkpoints for the same baseModel family (best-effort related assets). - #[serde(default, skip_serializing_if = "Vec::is_empty")] - pub related: Vec, } diff --git a/crates/freya-api/src/config.rs b/crates/freya-api/src/config.rs index 633172c..b58e196 100644 --- a/crates/freya-api/src/config.rs +++ b/crates/freya-api/src/config.rs @@ -1,7 +1,4 @@ -use crate::prefs::{AlignmentPrefs, AutoFallbacksPrefs, ChatProvidersPrefs, PrivacyPrefs}; -use crate::studio::StudioPrefs; use clap::Parser; -use std::collections::HashMap; use std::path::PathBuf; #[derive(Debug, Clone, Parser)] @@ -20,18 +17,16 @@ pub struct Config { )] pub openrouter_base_url: String, - /// Agent / plan chat model. `auto` = Freya internal Auto (not OpenRouter's upstream router). - #[arg(long, env = "FREYA_CHAT_MODEL", default_value = "auto")] + #[arg(long, env = "FREYA_CHAT_MODEL", default_value = "openrouter/auto")] pub chat_model: String, - /// Still-image model. `auto` = Freya router / Flux NL default (legacy Flux alignment). - #[arg(long, env = "FREYA_IMAGE_MODEL", default_value = "auto")] + #[arg( + long, + env = "FREYA_IMAGE_MODEL", + default_value = "black-forest-labs/flux.2-klein-4b" + )] pub image_model: String, - /// Light Freya-owned intent router model. `auto` = Llama 3.1 8B-class (dolphin3 spirit). - #[arg(long, env = "FREYA_ROUTER_MODEL", default_value = "auto")] - pub router_model: String, - #[arg(long, env = "FREYA_CHAT_BACKEND", default_value = "openrouter")] pub chat_backend: String, @@ -61,174 +56,9 @@ pub struct Config { default_value = "./data/secrets.json" )] pub secrets_file: PathBuf, - - /// Optional bearer token for `/v1/*` routes. Empty = open (local/dev only). - #[arg(long, env = "FREYA_API_TOKEN", default_value = "")] - pub api_token: String, - - /// When set, `POST /v1/auth/token` also patches this Secret (in-cluster) so MCP/env stay aligned. - #[arg(long, env = "FREYA_API_TOKEN_SECRET_NAME", default_value = "")] - pub api_token_secret_name: String, - - /// Key inside `FREYA_API_TOKEN_SECRET_NAME` (default `token`). - #[arg(long, env = "FREYA_API_TOKEN_SECRET_KEY", default_value = "token")] - pub api_token_secret_key: String, - - /// Admin username for human UI login (game-operator style). Default `admin`. - #[arg(long, env = "FREYA_ADMIN_USER", default_value = "admin")] - pub admin_user: String, - - /// Admin password from operator-generated Secret (`admin-password`). Empty = no admin login. - #[arg(long, env = "FREYA_ADMIN_PASSWORD", default_value = "")] - pub admin_password: String, - - /// Bearer token the API sends to the diffusion worker (`FREYA_WORKER_TOKEN`). - #[arg(long, env = "FREYA_WORKER_TOKEN", default_value = "")] - pub worker_token: String, - - /// Accept invalid/self-signed TLS when calling the diffusion worker (local/dev Ingress). - #[arg(long, env = "FREYA_WORKER_TLS_INSECURE", default_value_t = false)] - pub worker_tls_insecure: bool, - - /// Docker container name for local start/stop (`docker start|stop`). - #[arg( - long, - env = "FREYA_WORKER_CONTAINER", - default_value = "freya-local-worker" - )] - pub worker_container: String, - - /// Optional systemd unit name if the worker is not a docker container. - #[arg( - long, - env = "FREYA_WORKER_SYSTEMD_UNIT", - default_value = "freya-worker.service" - )] - pub worker_systemd_unit: String, - - /// Comma-separated allowed CORS origins. Empty + no token → permissive (dev warning). - /// Empty + token set → same-origin only (no `*`). - #[arg(long, env = "FREYA_CORS_ORIGINS", default_value = "")] - pub cors_origins: String, - - /// OpenRouter per-request ZDR (`provider.zdr`). Persisted via Settings / secrets file. - #[arg(long, env = "FREYA_OPENROUTER_ZDR", default_value_t = false)] - pub openrouter_zdr: bool, - - /// OpenRouter `provider.data_collection`: allow|deny. - #[arg( - long, - env = "FREYA_OPENROUTER_DATA_COLLECTION", - default_value = "allow" - )] - pub openrouter_data_collection: String, - - /// Comma-separated chat vendors unchecked in Settings (Freya catalog filter). - #[arg(long, env = "FREYA_CHAT_PROVIDERS_EXCLUDED", default_value = "")] - pub chat_providers_excluded: String, - - /// Legacy comma-separated include-only vendors (from old `FREYA_OPENROUTER_PROVIDER_ONLY`). - #[arg(long, env = "FREYA_OPENROUTER_PROVIDER_ONLY", default_value = "")] - pub openrouter_provider_only: String, - - /// Legacy comma-separated ignore list (from old `FREYA_OPENROUTER_PROVIDER_IGNORE`). - #[arg(long, env = "FREYA_OPENROUTER_PROVIDER_IGNORE", default_value = "")] - pub openrouter_provider_ignore: String, - - /// Model catalog alignment: balanced|safety|uncensored (Freya-side filter). - #[arg(long, env = "FREYA_MODEL_ALIGNMENT", default_value = "balanced")] - pub model_alignment: String, - - /// When false, filter NSFW-looking local/Civitai assets from lists/search. - #[arg(long, env = "FREYA_ALLOW_NSFW_LOCAL", default_value_t = false)] - pub allow_nsfw_local: bool, - - /// System instruction tone: warm|direct|steerable. - #[arg(long, env = "FREYA_INSTRUCTION_TONE", default_value = "warm")] - pub instruction_tone: String, - - /// Per-mode system prompt overrides (Settings). Empty / missing → packs/instructions defaults. - /// Not a CLI flag — loaded from `FREYA_SECRETS_FILE`. - #[arg(skip)] - pub instruction_overrides: HashMap, - - /// Configurable Auto fallbacks (Models tab). Empty fields → Privacy/Alignment built-ins. - /// Not a CLI flag — loaded from `FREYA_SECRETS_FILE`. - #[arg(skip)] - pub auto_fallbacks: AutoFallbacksPrefs, - - /// One-shot: the old Auto sentinel `openrouter/auto` was rewritten to internal `auto`. - /// After this is set, an explicit upstream selection is kept. - #[arg(skip)] - pub legacy_upstream_auto_migrated: bool, - - /// Favorites, LoRA pins, composer backend, video pin, automation mode. - /// Not a CLI flag — loaded from `FREYA_SECRETS_FILE`. No API keys. - #[arg(skip)] - pub studio: StudioPrefs, } impl Config { - pub fn privacy_prefs(&self) -> PrivacyPrefs { - let excluded: Vec = self - .chat_providers_excluded - .split(|c: char| c == ',' || c.is_whitespace()) - .map(|s| s.trim().to_string()) - .filter(|s| !s.is_empty()) - .collect(); - PrivacyPrefs { - zero_data_retention: self.openrouter_zdr, - data_collection: self.openrouter_data_collection.clone(), - chat_providers: ChatProvidersPrefs { - excluded, - legacy_only: None, - }, - // Legacy env/secrets free-text — migrated inside normalize(). - provider_only: self.openrouter_provider_only.clone(), - provider_ignore: self.openrouter_provider_ignore.clone(), - } - .normalize() - } - - pub fn alignment_prefs(&self) -> AlignmentPrefs { - AlignmentPrefs { - model_alignment: self.model_alignment.clone(), - allow_nsfw_local: self.allow_nsfw_local, - instruction_tone: self.instruction_tone.clone(), - } - .normalize() - } - - pub fn apply_privacy(&mut self, p: PrivacyPrefs) { - let p = p.normalize(); - self.openrouter_zdr = p.zero_data_retention; - self.openrouter_data_collection = p.data_collection; - self.chat_providers_excluded = p.chat_providers.excluded.join(","); - // Persist legacy_only via provider_only until Settings clears it (checkbox save). - self.openrouter_provider_only = p - .chat_providers - .legacy_only - .as_ref() - .map(|v| v.join(",")) - .unwrap_or_default(); - self.openrouter_provider_ignore = String::new(); - } - - pub fn apply_alignment(&mut self, a: AlignmentPrefs) { - let a = a.normalize(); - self.model_alignment = a.model_alignment; - self.allow_nsfw_local = a.allow_nsfw_local; - self.instruction_tone = a.instruction_tone; - } - - pub fn auto_fallbacks_prefs(&self) -> AutoFallbacksPrefs { - self.auto_fallbacks.clone().normalize() - } - - pub fn apply_auto_fallbacks(&mut self, f: AutoFallbacksPrefs) { - self.auto_fallbacks = f.normalize(); - } - pub fn openrouter_configured(&self) -> bool { !self.openrouter_api_key.trim().is_empty() } @@ -237,14 +67,6 @@ impl Config { !self.civitai_api_key.trim().is_empty() } - pub fn admin_login_configured(&self) -> bool { - !self.admin_password.trim().is_empty() - } - - pub fn auth_required(&self) -> bool { - !self.api_token.trim().is_empty() || self.admin_login_configured() - } - pub fn chat_url(&self) -> String { if self.chat_backend == "vllm" { self.chat_base_url diff --git a/crates/freya-api/src/gallery.rs b/crates/freya-api/src/gallery.rs index 71d9aa2..2670ed2 100644 --- a/crates/freya-api/src/gallery.rs +++ b/crates/freya-api/src/gallery.rs @@ -41,7 +41,11 @@ impl Gallery { meta: &mut ArtifactMeta, ) -> Result { let id = Uuid::new_v4().to_string(); - let ext = mime_to_ext(mime); + let ext = if mime.contains("jpeg") || mime.contains("jpg") { + "jpg" + } else { + "png" + }; let filename = format!("{id}.{ext}"); meta.id = id.clone(); meta.filename = filename.clone(); @@ -74,9 +78,6 @@ impl Gallery { } pub async fn get(&self, id: &str) -> Result> { - let Some(id) = sanitize_gallery_id(id) else { - return Ok(None); - }; let path = self.root.join(format!("{id}.json")); if !path.exists() { return Ok(None); @@ -85,89 +86,7 @@ impl Gallery { Ok(Some(serde_json::from_slice(&raw)?)) } - /// Remove artifact bytes + metadata. Returns `false` if id is invalid or missing. - pub async fn delete(&self, id: &str) -> Result { - let Some(id) = sanitize_gallery_id(id) else { - return Ok(false); - }; - let Some(meta) = self.get(id).await? else { - return Ok(false); - }; - let img = self.image_path(&meta); - let meta_path = self.root.join(format!("{id}.json")); - if img.exists() { - fs::remove_file(&img) - .await - .with_context(|| format!("remove gallery image {}", img.display()))?; - } - fs::remove_file(&meta_path) - .await - .with_context(|| format!("remove gallery meta {}", meta_path.display()))?; - Ok(true) - } - pub fn image_path(&self, meta: &ArtifactMeta) -> PathBuf { self.root.join(&meta.filename) } } - -/// Gallery ids are UUIDs written by [`Gallery::save`]. Reject path traversal. -fn sanitize_gallery_id(id: &str) -> Option<&str> { - if Uuid::parse_str(id).is_ok() { - Some(id) - } else { - None - } -} - -fn mime_to_ext(mime: &str) -> &'static str { - let m = mime.to_ascii_lowercase(); - if m.contains("jpeg") || m.contains("jpg") { - "jpg" - } else if m.contains("webp") { - "webp" - } else if m.contains("gif") { - "gif" - } else if m.contains("webm") { - "webm" - } else if m.contains("mp4") || m.contains("mpeg") || m.contains("quicktime") { - "mp4" - } else if m.contains("png") { - "png" - } else { - "bin" - } -} - -/// Content-Type for serving a gallery artifact. -pub fn content_type_for_mime(mime: &str) -> &'static str { - let m = mime.to_ascii_lowercase(); - if m.contains("jpeg") || m.contains("jpg") { - "image/jpeg" - } else if m.contains("webp") { - "image/webp" - } else if m.contains("gif") { - "image/gif" - } else if m.contains("webm") { - "video/webm" - } else if m.contains("mp4") || m.contains("mpeg") || m.contains("quicktime") { - "video/mp4" - } else if m.contains("png") { - "image/png" - } else if !mime.is_empty() { - // Pass through unknown but non-empty mime when possible — fall back to octet-stream. - "application/octet-stream" - } else { - "application/octet-stream" - } -} - -pub fn is_video_mime(mime: &str) -> bool { - let m = mime.to_ascii_lowercase(); - m.contains("mp4") || m.contains("webm") || m.contains("quicktime") || m.starts_with("video/") -} - -pub fn is_animated_image_mime(mime: &str) -> bool { - let m = mime.to_ascii_lowercase(); - m.contains("gif") || m.contains("webp") -} diff --git a/crates/freya-api/src/main.rs b/crates/freya-api/src/main.rs index 403b0da..b5f09e8 100644 --- a/crates/freya-api/src/main.rs +++ b/crates/freya-api/src/main.rs @@ -1,34 +1,20 @@ -mod auto_matrix; -mod base_models; mod civitai; mod config; -mod disk; mod gallery; -mod gpu; -mod k8s_secret; mod openrouter; -mod prefs; -mod router; mod routes; mod state; -mod studio; mod styles; mod worker; -mod worker_ctl; -use axum::extract::Request; -use axum::http::{header, HeaderValue, Method, StatusCode}; -use axum::middleware::{self, Next}; -use axum::response::Response; use axum::routing::{get, post}; use axum::Router; -use base64::Engine; use clap::Parser; use config::Config; use state::AppState; -use tower_http::cors::{AllowOrigin, CorsLayer}; +use tower_http::cors::CorsLayer; use tower_http::trace::TraceLayer; -use tracing::{info, warn}; +use tracing::info; #[tokio::main] async fn main() -> anyhow::Result<()> { @@ -41,91 +27,27 @@ async fn main() -> anyhow::Result<()> { let cfg = Config::parse(); let bind = cfg.bind.clone(); - let cors = build_cors(&cfg); - let require_auth = cfg.auth_required(); - if !require_auth { - warn!( - "FREYA_API_TOKEN and FREYA_ADMIN_PASSWORD unset — /v1 routes are open (local/dev only). \ - Operator generateAdminSecrets (default) provisions admin login + API bearer in-cluster." - ); - } else if cfg.admin_login_configured() { - info!( - "admin login configured — UI sign-in or bearer required on /v1 (except auth status/login + gallery images)" - ); - } else { - info!("FREYA_API_TOKEN set — bearer auth required on /v1 routes (except gallery images)"); - } - let state = AppState::from_config(cfg).await?; - let protected = Router::new() + let app = Router::new() + .route("/healthz", get(routes::health)) + .route("/v1/health", get(routes::health)) .route("/v1/assist", post(routes::assist)) - .route("/v1/chat", post(routes::chat)) .route("/v1/generate", post(routes::generate)) - .route("/v1/series", post(routes::generate_series)) .route("/v1/run", post(routes::run)) .route("/v1/gallery", get(routes::gallery_list)) - .route( - "/v1/gallery/{id}", - get(routes::gallery_get).delete(routes::gallery_delete), - ) + .route("/v1/gallery/{id}", get(routes::gallery_get)) .route("/v1/gallery/{id}/image", get(routes::gallery_image)) .route("/v1/gallery/{id}/remix", post(routes::gallery_remix)) .route("/v1/models", get(routes::models)) .route("/v1/styles", get(routes::styles_list)) .route("/v1/civitai/search", get(routes::civitai_search)) - .route("/v1/civitai/models/{id}", get(routes::civitai_model)) - .route( - "/v1/civitai/model-versions/{id}", - get(routes::civitai_model_version), - ) .route("/v1/civitai/install", post(routes::civitai_install)) - .route("/v1/civitai/jobs", get(routes::civitai_jobs_list)) - .route("/v1/civitai/jobs/clear", post(routes::civitai_jobs_clear)) - .route("/v1/civitai/jobs/{id}", get(routes::civitai_job_get)) - .route( - "/v1/civitai/jobs/{id}/cancel", - post(routes::civitai_job_cancel), - ) .route( "/v1/settings", get(routes::settings_get).put(routes::settings_put), ) - .route( - "/v1/studio", - get(routes::studio_get).put(routes::studio_put), - ) - .route("/v1/metrics/openrouter", get(routes::openrouter_metrics)) - .route("/v1/auth/token", post(routes::auth_token_create)) - .route("/v1/worker/stats", get(routes::worker_stats)) - .route("/v1/worker/start", post(routes::worker_start)) - .route("/v1/worker/stop", post(routes::worker_stop)) - .route("/v1/worker/installed", get(routes::worker_installed)) - .route("/v1/worker/loras", get(routes::worker_loras)) - .route("/v1/worker/checkpoints", get(routes::worker_checkpoints)) - .route("/v1/worker/embeddings", get(routes::worker_embeddings)) - .route("/v1/worker/vae", get(routes::worker_vaes)) - .route( - "/v1/worker/assets", - axum::routing::delete(routes::worker_asset_delete), - ) - .route( - "/v1/worker/base-model", - get(routes::worker_base_model_get).put(routes::worker_base_model_put), - ) - .route("/v1/base-models", get(routes::base_models_catalog)) - .route_layer(middleware::from_fn_with_state( - state.clone(), - require_api_token, - )); - - let app = Router::new() - .route("/healthz", get(routes::health)) - .route("/v1/health", get(routes::health)) - .route("/v1/auth/status", get(routes::auth_status)) - .route("/v1/auth/login", post(routes::auth_login)) - .merge(protected) - .layer(cors) + .layer(CorsLayer::permissive()) .layer(TraceLayer::new_for_http()) .with_state(state); @@ -134,142 +56,3 @@ async fn main() -> anyhow::Result<()> { axum::serve(listener, app).await?; Ok(()) } - -fn build_cors(cfg: &Config) -> CorsLayer { - let origins = cfg.cors_origins.trim(); - let has_token = !cfg.api_token.trim().is_empty(); - if !origins.is_empty() { - let list: Vec = origins - .split(',') - .map(str::trim) - .filter(|s| !s.is_empty()) - .filter_map(|o| o.parse().ok()) - .collect(); - CorsLayer::new() - .allow_origin(AllowOrigin::list(list)) - .allow_methods([ - Method::GET, - Method::POST, - Method::PUT, - Method::DELETE, - Method::OPTIONS, - ]) - .allow_headers([header::AUTHORIZATION, header::CONTENT_TYPE]) - } else if has_token { - // Auth enabled, no explicit origins: do not use permissive `*`. - CorsLayer::new() - .allow_methods([ - Method::GET, - Method::POST, - Method::PUT, - Method::DELETE, - Method::OPTIONS, - ]) - .allow_headers([header::AUTHORIZATION, header::CONTENT_TYPE]) - } else { - CorsLayer::permissive() - } -} - -/// When API bearer and/or admin password is set, require auth on `/v1` methods -/// except OPTIONS (CORS) and gallery image GETs (`` cannot send Authorization). -/// Accepts `Authorization: Bearer ` or HTTP Basic (`admin` + admin-password), -/// matching game-operator Server Manager basic auth as a fallback. -async fn require_api_token( - axum::extract::State(state): axum::extract::State, - req: Request, - next: Next, -) -> Result { - let method = req.method().clone(); - if method == Method::OPTIONS { - return Ok(next.run(req).await); - } - // UUID gallery ids are unguessable; list/detail/search still require the bearer. - if matches!(method, Method::GET | Method::HEAD) && is_gallery_image_path(req.uri().path()) { - return Ok(next.run(req).await); - } - - let (api_token, admin_user, admin_password, auth_required) = { - let cfg = state.config.read().await; - ( - cfg.api_token.trim().to_string(), - cfg.admin_user.trim().to_string(), - cfg.admin_password.trim().to_string(), - cfg.auth_required(), - ) - }; - if !auth_required { - return Ok(next.run(req).await); - } - - let auth = req - .headers() - .get(header::AUTHORIZATION) - .and_then(|v| v.to_str().ok()) - .unwrap_or(""); - - if !api_token.is_empty() { - if let Some(t) = auth.strip_prefix("Bearer ") { - if const_eq(t.trim(), &api_token) { - return Ok(next.run(req).await); - } - } - } - - if !admin_password.is_empty() { - if let Some((user, pass)) = parse_basic_auth(auth) { - let expect_user = if admin_user.is_empty() { - "admin" - } else { - admin_user.as_str() - }; - if const_eq(&user, expect_user) && const_eq(&pass, &admin_password) { - return Ok(next.run(req).await); - } - } - } - - Err(StatusCode::UNAUTHORIZED) -} - -fn parse_basic_auth(header: &str) -> Option<(String, String)> { - let encoded = header.strip_prefix("Basic ")?.trim(); - let raw = base64::engine::general_purpose::STANDARD - .decode(encoded) - .ok()?; - let text = String::from_utf8(raw).ok()?; - let (user, pass) = text.split_once(':')?; - Some((user.to_string(), pass.to_string())) -} - -fn const_eq(a: &str, b: &str) -> bool { - if a.len() != b.len() { - return false; - } - a.bytes() - .zip(b.bytes()) - .fold(0u8, |acc, (x, y)| acc | (x ^ y)) - == 0 -} - -fn is_gallery_image_path(path: &str) -> bool { - let parts: Vec<&str> = path.trim_end_matches('/').split('/').collect(); - matches!( - parts.as_slice(), - ["", "v1", "gallery", id, "image"] if !id.is_empty() - ) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn gallery_image_path_match() { - assert!(is_gallery_image_path("/v1/gallery/abc-123/image")); - assert!(is_gallery_image_path("/v1/gallery/abc-123/image/")); - assert!(!is_gallery_image_path("/v1/gallery")); - assert!(!is_gallery_image_path("/v1/gallery/abc-123")); - assert!(!is_gallery_image_path("/v1/civitai/search")); - } -} diff --git a/crates/freya-api/src/openrouter.rs b/crates/freya-api/src/openrouter.rs index b03a30e..41c7175 100644 --- a/crates/freya-api/src/openrouter.rs +++ b/crates/freya-api/src/openrouter.rs @@ -1,8 +1,4 @@ use crate::config::Config; -use crate::prefs::{ - chat_model_matches_alignment, inject_provider, AlignmentPrefs, AutoFallbacksPrefs, - ChatProvidersPrefs, PrivacyPrefs, -}; use anyhow::{anyhow, Context, Result}; use serde::{Deserialize, Serialize}; use serde_json::Value; @@ -14,10 +10,6 @@ pub struct OpenRouterClient { api_key: String, chat_model: String, image_model: String, - router_model: String, - privacy: PrivacyPrefs, - alignment: AlignmentPrefs, - auto_fallbacks: AutoFallbacksPrefs, } impl OpenRouterClient { @@ -28,10 +20,6 @@ impl OpenRouterClient { api_key: cfg.openrouter_api_key.clone(), chat_model: cfg.chat_model.clone(), image_model: cfg.image_model.clone(), - router_model: cfg.router_model.clone(), - privacy: cfg.privacy_prefs(), - alignment: cfg.alignment_prefs(), - auto_fallbacks: cfg.auto_fallbacks_prefs(), } } @@ -40,57 +28,10 @@ impl OpenRouterClient { self } - #[allow(dead_code)] - pub fn privacy(&self) -> &PrivacyPrefs { - &self.privacy - } - - #[allow(dead_code)] - pub fn alignment(&self) -> &AlignmentPrefs { - &self.alignment - } - - pub fn default_image_model(&self) -> String { - if let Some(id) = canonical_image_model(&self.image_model) { - return id; - } - crate::router::resolve_auto_fallback( - crate::router::AutoFallbackKind::Image, - &self.privacy, - &self.alignment, - &self.auto_fallbacks, - ) - } - - /// ZDR Auto still-image default (Google image endpoints usually pass ZDR/safety retention). - pub fn zdr_fallback_image_model(&self) -> String { - let mut privacy = self.privacy.clone(); - privacy.zero_data_retention = true; - crate::router::resolve_auto_fallback( - crate::router::AutoFallbackKind::Image, - &privacy, - &self.alignment, - &self.auto_fallbacks, - ) - } - - pub fn auto_fallbacks(&self) -> &AutoFallbacksPrefs { - &self.auto_fallbacks - } - - pub fn configured_image_model(&self) -> &str { + pub fn default_image_model(&self) -> &str { &self.image_model } - pub fn configured_router_model(&self) -> &str { - &self.router_model - } - - #[allow(dead_code)] - pub fn configured_chat_model(&self) -> &str { - &self.chat_model - } - async fn auth_post(&self, path: &str, body: Value) -> Result { if self.api_key.is_empty() { return Err(anyhow!("OPENROUTER_API_KEY not configured")); @@ -109,104 +50,20 @@ impl OpenRouterClient { let status = resp.status(); let text = resp.text().await.unwrap_or_default(); if !status.is_success() { - return Err(anyhow!( - "{}", - humanize_openrouter_error(status.as_u16(), &text) - )); - } - serde_json::from_str(&text).context("parse openrouter json") - } - - async fn auth_get(&self, path: &str) -> Result { - if self.api_key.is_empty() { - return Err(anyhow!("OPENROUTER_API_KEY not configured")); - } - let url = format!("{}{path}", self.base); - let resp = self - .http - .get(&url) - .bearer_auth(&self.api_key) - .header("HTTP-Referer", "https://dataknife.ai/freya") - .header("X-Title", "Freya") - .send() - .await - .context("openrouter request")?; - let status = resp.status(); - let text = resp.text().await.unwrap_or_default(); - if !status.is_success() { - return Err(anyhow!( - "{}", - humanize_openrouter_error(status.as_u16(), &text) - )); + return Err(anyhow!("openrouter {status}: {text}")); } serde_json::from_str(&text).context("parse openrouter json") } - /// Per-key usage / spend caps via `GET /api/v1/key` (works with a normal completion key). - pub async fn key_usage(&self) -> Result { - let v = self.auth_get("/key").await?; - let data = v.get("data").cloned().unwrap_or(v); - Ok(OpenRouterKeyUsage { - label: data - .get("label") - .and_then(|x| x.as_str()) - .unwrap_or("") - .to_string(), - usage: data.get("usage").and_then(|x| x.as_f64()), - usage_daily: data.get("usage_daily").and_then(|x| x.as_f64()), - usage_weekly: data.get("usage_weekly").and_then(|x| x.as_f64()), - usage_monthly: data.get("usage_monthly").and_then(|x| x.as_f64()), - limit: data - .get("limit") - .and_then(|x| if x.is_null() { None } else { x.as_f64() }), - limit_remaining: data.get("limit_remaining").and_then(|x| { - if x.is_null() { - None - } else { - x.as_f64() - } - }), - limit_reset: data - .get("limit_reset") - .and_then(|x| x.as_str()) - .map(|s| s.to_string()), - is_free_tier: data.get("is_free_tier").and_then(|x| x.as_bool()), - is_management_key: data - .get("is_management_key") - .and_then(|x| x.as_bool()) - .unwrap_or(false), - }) - } - - /// Account credits via `GET /api/v1/credits` (requires a Management API key). - pub async fn account_credits(&self) -> Result { - let v = self.auth_get("/credits").await?; - let data = v.get("data").cloned().unwrap_or(v); - let total_credits = data - .get("total_credits") - .and_then(|x| x.as_f64()) - .unwrap_or(0.0); - let total_usage = data - .get("total_usage") - .and_then(|x| x.as_f64()) - .unwrap_or(0.0); - Ok(OpenRouterCredits { - total_credits, - total_usage, - remaining: total_credits - total_usage, - }) - } - pub async fn chat(&self, system: &str, user: &str, model: Option<&str>) -> Result { let model = model.unwrap_or(&self.chat_model); - let mut body = serde_json::json!({ + let body = serde_json::json!({ "model": model, "messages": [ {"role": "system", "content": system}, {"role": "user", "content": user} ] }); - inject_provider(&mut body, &self.privacy); let v = self.auth_post("/chat/completions", body).await?; v.pointer("/choices/0/message/content") .and_then(|c| c.as_str()) @@ -216,33 +73,8 @@ impl OpenRouterClient { pub async fn list_image_models(&self) -> Result> { if self.api_key.is_empty() { - return Ok(filter_fallback_image( - &fallback_models(), - self.privacy.zero_data_retention, - )); - } - // When Freya ZDR is on, list only models with ZDR-capable endpoints - // (`GET /models?output_modalities=image&zdr=true`). Dedicated /images/models - // does not expose the zdr query filter. - if self.privacy.zero_data_retention { - let url = format!("{}/models?output_modalities=image&zdr=true", self.base); - let resp = self - .http - .get(&url) - .bearer_auth(&self.api_key) - .send() - .await - .context("list image models (zdr)")?; - if resp.status().is_success() { - let v: Value = resp.json().await.unwrap_or(Value::Null); - let out = parse_image_models_from_catalog(&v); - if !out.is_empty() { - return Ok(out); - } - } - return Ok(filter_fallback_image(&fallback_models(), true)); + return Ok(fallback_models()); } - let url = format!("{}/images/models", self.base); let resp = self .http @@ -255,55 +87,9 @@ impl OpenRouterClient { return Ok(fallback_models()); } let v: Value = resp.json().await.unwrap_or(Value::Null); - let out = parse_image_models_from_catalog(&v); - if out.is_empty() { - return Ok(fallback_models()); - } - Ok(out) - } - - /// Discover chat/agent models via `GET /models`, filtered to text/chat - /// candidates (denylist: routing suffixes, non-text modalities, image/embed/…). - /// When ZDR is on, requests `?zdr=true` (OpenRouter catalog filter). - /// Alignment prefs further filter by `top_provider.is_moderated` / name heuristics. - /// User chat-provider checkboxes (Settings) filter vendor prefixes last. - #[allow(dead_code)] - pub async fn list_chat_models(&self) -> Result> { - Ok(self.list_chat_catalog().await?.models) - } - - /// Chat catalog plus the vendor prefixes present before checkbox filtering. - pub async fn list_chat_catalog(&self) -> Result { - let chat_providers = self.privacy.chat_providers.clone(); - if self.api_key.is_empty() { - return Ok(self.fallback_chat_catalog()); - } - let url = if self.privacy.zero_data_retention { - format!("{}/models?zdr=true", self.base) - } else { - format!("{}/models", self.base) - }; - let resp = self - .http - .get(&url) - .bearer_auth(&self.api_key) - .send() - .await - .context("list chat models")?; - if !resp.status().is_success() { - return Ok(self.fallback_chat_catalog()); - } - let v: Value = resp.json().await.unwrap_or(Value::Null); - let mut agent_scored: Vec<(i64, ImageModel)> = Vec::new(); - let mut router_scored: Vec<(i64, ImageModel)> = Vec::new(); - let mut available_set = std::collections::BTreeSet::new(); + let mut out = Vec::new(); if let Some(arr) = v.get("data").and_then(|d| d.as_array()) { for m in arr { - let agent_ok = is_agent_capable(m); - let router_ok = is_router_capable(m); - if !agent_ok && !router_ok { - continue; - } let id = m .get("id") .and_then(|x| x.as_str()) @@ -312,105 +98,22 @@ impl OpenRouterClient { if id.is_empty() { continue; } - available_set.insert(openrouter_vendor(&id).to_ascii_lowercase()); - if !chat_model_matches_alignment(m, &self.alignment) { - continue; - } - if !chat_providers.includes_model_id(&id) { - continue; - } - let name = display_name_for_catalog(m, &id); - let created = m.get("created").and_then(|c| c.as_i64()).unwrap_or(0); - let model = ImageModel { + let name = m + .get("name") + .and_then(|x| x.as_str()) + .unwrap_or(&id) + .to_string(); + out.push(ImageModel { id, name, backend: "openrouter".into(), - }; - if agent_ok { - agent_scored.push((created, model.clone())); - } - if router_ok { - router_scored.push((created, model)); - } - } - } - if agent_scored.is_empty() && router_scored.is_empty() && available_set.is_empty() { - return Ok(self.fallback_chat_catalog()); - } - let mut models = order_pinned(agent_scored); - let mut router = order_pinned(router_scored); - if crate::router::privacy_requires_strict(&self.privacy) { - // Upstream router is not on the ZDR catalog. - models.retain(|m| !is_upstream_router_id(&m.id)); - router.retain(|m| !is_upstream_router_id(&m.id)); - } else if let Some(existing) = models.iter_mut().find(|m| is_upstream_router_id(&m.id)) { - existing.name = "OpenRouter router (upstream)".into(); - } else { - // Catalog omitted it (or alignment hid it). Offer it only when privacy is not strict - // and alignment did not reject a row we already saw. Balanced always keeps it. - if self.alignment.model_alignment != "safety" { - ensure_upstream_agent(&mut models); - } - } - Ok(ChatCatalog { - models, - router, - available: available_set.into_iter().collect(), - }) - } - - /// Discover OpenRouter video models via `GET /videos/models`. - pub async fn list_video_models(&self) -> Result> { - if self.api_key.is_empty() { - return Ok(Vec::new()); - } - // When Freya ZDR is on, prefer the ZDR-filtered modality catalog. - if self.privacy.zero_data_retention { - let url = format!("{}/models?output_modalities=video&zdr=true", self.base); - let resp = self - .http - .get(&url) - .bearer_auth(&self.api_key) - .send() - .await - .context("list video models (zdr)")?; - if resp.status().is_success() { - let v: Value = resp.json().await.unwrap_or(Value::Null); - let out = parse_video_models(&v); - if !out.is_empty() { - return Ok(out); - } - } - } - // Prefer dedicated video catalog; fall back to modality filter on /models. - let url = format!("{}/videos/models", self.base); - let resp = self - .http - .get(&url) - .bearer_auth(&self.api_key) - .send() - .await - .context("list video models")?; - if resp.status().is_success() { - let v: Value = resp.json().await.unwrap_or(Value::Null); - let out = parse_video_models(&v); - if !out.is_empty() { - return Ok(out); + }); } } - let url = format!("{}/models?output_modalities=video", self.base); - let resp = self - .http - .get(&url) - .bearer_auth(&self.api_key) - .send() - .await - .context("list video models (modality)")?; - if !resp.status().is_success() { - return Ok(Vec::new()); + if out.is_empty() { + return Ok(fallback_models()); } - let v: Value = resp.json().await.unwrap_or(Value::Null); - Ok(parse_video_models(&v)) + Ok(out) } pub async fn generate_image( @@ -419,54 +122,7 @@ impl OpenRouterClient { model: Option<&str>, size: Option<&str>, ) -> Result { - let default_image = self.default_image_model(); - let model = resolve_image_model(model.unwrap_or(&default_image), &default_image); - match self.generate_image_once(prompt, &model, size).await { - Ok(img) => Ok(img), - Err(e) if self.privacy.zero_data_retention && is_zdr_routing_error(&e.to_string()) => { - let fallback = self.zdr_fallback_image_model(); - if model == fallback { - return Err(e); - } - tracing::warn!( - model = %model, - fallback = %fallback, - "image ZDR routing failed; retrying with ZDR-capable model" - ); - match self.generate_image_once(prompt, &fallback, size).await { - Ok(img) => Ok(img), - Err(e2) => { - if is_zdr_routing_error(&e2.to_string()) { - Err(anyhow!( - "{}", - humanize_openrouter_error(404, &e2.to_string()) - )) - } else { - Err(e2) - } - } - } - } - Err(e) => Err(e), - } - } - - async fn generate_image_once( - &self, - prompt: &str, - model: &str, - size: Option<&str>, - ) -> Result { - // Gemini / Nano Banana family: chat completions + modalities. - // Diffusion models (FLUX, GPT Image, …): dedicated /images API only — - // do not fall back to chat (wrong modalities error masks ZDR/credits). - if is_chat_image_model(model) { - return self - .generate_image_via_chat(prompt, model) - .await - .map_err(|e| anyhow!("{}", e)); - } - + let model = model.unwrap_or(&self.image_model); let mut body = serde_json::json!({ "model": model, "prompt": prompt, @@ -479,405 +135,21 @@ impl OpenRouterClient { body["size"] = Value::String(size.into()); } } - inject_provider(&mut body, &self.privacy); - - let v = self.auth_post("/images", body).await?; - extract_image(&self.http, &v).await - } - - async fn generate_image_via_chat(&self, prompt: &str, model: &str) -> Result { - let mut chat_body = serde_json::json!({ - "model": model, - "messages": [{"role": "user", "content": prompt}], - "modalities": ["image", "text"] - }); - inject_provider(&mut chat_body, &self.privacy); - let v = self.auth_post("/chat/completions", chat_body).await?; - extract_image_from_chat(&v) - } - - /// Async text-to-video: submit → poll → download bytes (mp4). - pub async fn generate_video( - &self, - prompt: &str, - model: Option<&str>, - duration_secs: Option, - aspect_ratio: Option<&str>, - ) -> Result { - if self.api_key.is_empty() { - return Err(anyhow!("OPENROUTER_API_KEY not configured")); - } - let default_video = crate::router::resolve_auto_fallback( - crate::router::AutoFallbackKind::Video, - &self.privacy, - &self.alignment, - &self.auto_fallbacks, - ); - let model = resolve_video_model(model.unwrap_or(""), &default_video); - let zdr_video_fallback = { - let mut privacy = self.privacy.clone(); - privacy.zero_data_retention = true; - crate::router::resolve_auto_fallback( - crate::router::AutoFallbackKind::Video, - &privacy, - &self.alignment, - &self.auto_fallbacks, - ) - }; - match self - .generate_video_once(prompt, &model, duration_secs, aspect_ratio) - .await - { - Ok(v) => Ok(v), - Err(e) - if self.privacy.zero_data_retention - && is_zdr_routing_error(&e.to_string()) - && model != zdr_video_fallback => - { - tracing::warn!( - model = %model, - fallback = %zdr_video_fallback, - "video ZDR routing failed; retrying with ZDR-capable model" - ); - self.generate_video_once(prompt, &zdr_video_fallback, duration_secs, aspect_ratio) - .await - .map_err(|e2| { - if is_zdr_routing_error(&e2.to_string()) { - anyhow!("{}", humanize_openrouter_error(404, &e2.to_string())) - } else { - e2 - } - }) - } - Err(e) => Err(e), - } - } - - async fn generate_video_once( - &self, - prompt: &str, - model: &str, - duration_secs: Option, - aspect_ratio: Option<&str>, - ) -> Result { - let mut body = serde_json::json!({ - "model": model, - "prompt": prompt, - }); - if let Some(d) = duration_secs.filter(|d| *d > 0) { - body["duration"] = Value::from(d); - } - if let Some(ar) = aspect_ratio.map(str::trim).filter(|s| !s.is_empty()) { - body["aspect_ratio"] = Value::String(ar.into()); - } - inject_provider(&mut body, &self.privacy); - - let submit = self.auth_post_status("/videos", body, &[202, 200]).await?; - let job_id = submit - .get("id") - .and_then(|x| x.as_str()) - .ok_or_else(|| anyhow!("video job missing id"))? - .to_string(); - let polling_url = submit - .get("polling_url") - .and_then(|x| x.as_str()) - .map(|u| { - if u.starts_with("http") { - u.to_string() - } else { - format!("{}{}", self.base.trim_end_matches("/api/v1"), u) - } - }) - .unwrap_or_else(|| format!("{}/videos/{job_id}", self.base)); - let completed = self.poll_video_job(&polling_url).await?; - let bytes = self.download_video_bytes(&job_id, &completed).await?; - let mime = sniff_video_mime(&bytes).unwrap_or("video/mp4").to_string(); - let _ = &job_id; // retained for logs / future job status API - tracing::info!(%job_id, %model, bytes = bytes.len(), "openrouter video ready"); - Ok(GeneratedVideo { - bytes, - mime, - model: model.to_string(), - job_id, - }) - } - - async fn auth_post_status(&self, path: &str, body: Value, ok: &[u16]) -> Result { - if self.api_key.is_empty() { - return Err(anyhow!("OPENROUTER_API_KEY not configured")); - } - let url = format!("{}{path}", self.base); - let resp = self - .http - .post(&url) - .bearer_auth(&self.api_key) - .header("HTTP-Referer", "https://dataknife.ai/freya") - .header("X-Title", "Freya") - .json(&body) - .send() - .await - .context("openrouter request")?; - let status = resp.status(); - let text = resp.text().await.unwrap_or_default(); - if !ok.contains(&status.as_u16()) { - return Err(anyhow!( - "{}", - humanize_openrouter_error(status.as_u16(), &text) - )); - } - serde_json::from_str(&text).context("parse openrouter json") - } - - async fn poll_video_job(&self, polling_url: &str) -> Result { - let deadline = std::time::Instant::now() + std::time::Duration::from_secs(600); - loop { - if std::time::Instant::now() > deadline { - return Err(anyhow!("video generation timed out")); - } - let resp = self - .http - .get(polling_url) - .bearer_auth(&self.api_key) - .send() - .await - .context("poll video job")?; - let status_code = resp.status(); - let text = resp.text().await.unwrap_or_default(); - if !status_code.is_success() { - return Err(anyhow!( - "{}", - humanize_openrouter_error(status_code.as_u16(), &text) - )); - } - let v: Value = serde_json::from_str(&text).context("parse video poll json")?; - let st = v - .get("status") - .and_then(|x| x.as_str()) - .unwrap_or("") - .to_ascii_lowercase(); - match st.as_str() { - "completed" => return Ok(v), - "failed" | "cancelled" | "expired" => { - let err = v - .get("error") - .map(|e| e.to_string()) - .unwrap_or_else(|| st.clone()); - return Err(anyhow!("video job {st}: {err}")); - } - _ => { - tokio::time::sleep(std::time::Duration::from_secs(8)).await; - } - } - } - } - - async fn download_video_bytes(&self, job_id: &str, completed: &Value) -> Result> { - // Prefer authenticated content proxy, then signed URLs. - let content_url = format!("{}/videos/{job_id}/content", self.base); - let resp = self - .http - .get(&content_url) - .bearer_auth(&self.api_key) - .send() - .await - .context("download video content")?; - if resp.status().is_success() { - return Ok(resp.bytes().await.context("video content body")?.to_vec()); - } - let urls = completed - .get("urls") - .and_then(|u| u.as_array()) - .into_iter() - .flatten() - .chain( - completed - .get("unsigned_urls") - .and_then(|u| u.as_array()) - .into_iter() - .flatten(), - ); - for u in urls { - let Some(url) = u.as_str() else { continue }; - let resp = self - .http - .get(url) - .bearer_auth(&self.api_key) - .send() - .await - .context("download video url")?; - if resp.status().is_success() { - return Ok(resp.bytes().await.context("video url body")?.to_vec()); + // Prefer dedicated images API; fall back to chat modalities if needed. + match self.auth_post("/images", body.clone()).await { + Ok(v) => extract_image(&v), + Err(_) => { + let chat_body = serde_json::json!({ + "model": model, + "messages": [{"role": "user", "content": prompt}], + "modalities": ["image", "text"] + }); + let v = self.auth_post("/chat/completions", chat_body).await?; + extract_image_from_chat(&v) } } - Err(anyhow!("video completed but no downloadable URL")) - } -} - -/// Default OpenRouter T2V model (text-to-video; not avatar/lip-sync). -pub const DEFAULT_AUTO_VIDEO_MODEL: &str = "bytedance/seedance-2.5-flash"; - -pub fn resolve_video_model(requested: &str, default_video: &str) -> String { - let m = requested.trim(); - if m.is_empty() || m.eq_ignore_ascii_case("auto") { - return default_video.to_string(); - } - // Avatar models need photo/audio — not a drop-in for text-to-video Auto. - if m.contains("heygen") || m.contains("avatar") { - return default_video.to_string(); - } - m.to_string() -} - -fn sniff_video_mime(bytes: &[u8]) -> Option<&'static str> { - if bytes.len() >= 12 && &bytes[4..8] == b"ftyp" { - return Some("video/mp4"); - } - if bytes.len() >= 4 && &bytes[0..4] == b"\x1aE\xdf\xa3" { - return Some("video/webm"); - } - if bytes.len() >= 6 && (&bytes[0..6] == b"GIF87a" || &bytes[0..6] == b"GIF89a") { - return Some("image/gif"); - } - None -} - -/// Catalog ids are `provider/model`. `openrouter/` in front of another provider -/// is a prefix to strip. A smashed vendor slug (`openrouter/google-gemini-…`) -/// is invented and dropped. A real first-party id (`openrouter/horizon-alpha`) -/// stays. `openrouter/auto` stays so the upstream-router check still sees it. -pub fn canonicalize_catalog_id(raw: &str) -> String { - let s = raw.trim(); - if s.is_empty() { - return String::new(); - } - let lower = s.to_ascii_lowercase(); - const PREFIX: &str = "openrouter/"; - if lower.starts_with(PREFIX) { - if lower == "openrouter/auto" || lower.starts_with("openrouter/auto:") { - return s.to_string(); - } - let rest = s[PREFIX.len()..].trim(); - if rest.contains('/') && !rest.starts_with('/') { - return rest.to_string(); - } - if rest.is_empty() || smashed_vendor_slug(rest) { - return String::new(); - } - return s.to_string(); - } - s.to_string() -} - -/// `google-gemini-pro-image-1` is a vendor name glued on without a slash. -fn smashed_vendor_slug(rest: &str) -> bool { - let l = rest.to_ascii_lowercase(); - const HEADS: &[&str] = &[ - "google", - "openai", - "anthropic", - "meta", - "meta-llama", - "mistral", - "mistralai", - "black-forest", - "qwen", - "deepseek", - "cohere", - "amazon", - "nvidia", - "stability", - "bytedance", - "x-ai", - "xai", - "flux", - ]; - HEADS - .iter() - .any(|v| l == *v || l.starts_with(&format!("{v}-")) || l.starts_with(&format!("{v}_"))) -} - -/// Real still-image catalog id, or `None` when the slug is Auto, prose, or invented. -pub fn canonical_image_model(requested: &str) -> Option { - let id = canonicalize_catalog_id(requested); - if id.is_empty() || !is_plausible_image_model(&id) { - None - } else { - Some(id) - } -} - -/// Reject chat-router ids and invented `openrouter/` slugs planners emit as image models. -/// Falls back to `default_image` when that id is a real catalog id, otherwise the -/// balanced medium still-image default. -pub fn resolve_image_model(requested: &str, default_image: &str) -> String { - if let Some(id) = canonical_image_model(requested) { - return id; } - if let Some(id) = canonical_image_model(default_image) { - return id; - } - crate::router::DEFAULT_AUTO_IMAGE_MODEL.to_string() -} - -fn is_plausible_image_model(model: &str) -> bool { - let raw = model.trim(); - let m = raw.to_ascii_lowercase(); - // `openrouter/` is never an image vendor. `openrouter/google-gemini-pro-image-1` - // contains "image" but is not a catalog id. - if m.is_empty() || m.starts_with("openrouter/") || crate::router::is_auto_image(raw) { - return false; - } - // Router / planner prose echoed as a model id (not a real HF/OpenRouter slug). - if raw.contains(char::is_whitespace) - || raw.contains(',') - || m == "none" - || m.starts_with("none,") - || m.contains("zdr-aware") - || m.contains("letting freya") - || m.contains("auto default") - { - return false; - } - // Catalog ids are provider/model. A bare token that merely contains "image" - // (`google-gemini-pro-image-1`) is not an OpenRouter id. - let Some((vendor, name)) = raw.split_once('/') else { - return false; - }; - if vendor.is_empty() || name.is_empty() || vendor.eq_ignore_ascii_case("openrouter") { - return false; - } - // Chat / LLM ids that planners often emit by mistake. - if m.starts_with("anthropic/") - || m.starts_with("openai/gpt-4") - || m.starts_with("openai/o1") - || m.starts_with("openai/o3") - || m.starts_with("meta-llama/") - || m.starts_with("qwen/qwen3") - || m.starts_with("qwen/qwen2") - || m.starts_with("deepseek/") - || m.starts_with("mistralai/") - || (m.starts_with("google/gemini") && !m.contains("image") && !m.contains("banana")) - { - return false; - } - // Video-only ids are not still-image models. - if m.contains("seedance") - || m.contains("veo") - || m.contains("kling") - || m.contains("hailuo") - || m.contains("t2v") - { - return false; - } - true -} - -fn is_chat_image_model(model: &str) -> bool { - let m = model.to_ascii_lowercase(); - m.contains("gemini") && m.contains("image") - || m.contains("nano-banana") - || m.contains("gemini-nano-banana") } fn size_to_aspect(size: &str) -> Option<&'static str> { @@ -889,83 +161,7 @@ fn size_to_aspect(size: &str) -> Option<&'static str> { } } -/// Per-key usage from OpenRouter `GET /api/v1/key` (USD credits). -#[derive(Debug, Clone, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct OpenRouterKeyUsage { - pub label: String, - #[serde(skip_serializing_if = "Option::is_none")] - pub usage: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub usage_daily: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub usage_weekly: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub usage_monthly: Option, - /// Key spend cap (USD), or null when unlimited. - #[serde(skip_serializing_if = "Option::is_none")] - pub limit: Option, - /// Remaining under the key cap (null when unlimited). - #[serde(skip_serializing_if = "Option::is_none")] - pub limit_remaining: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub limit_reset: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub is_free_tier: Option, - pub is_management_key: bool, -} - -/// Account-level purchased vs spent credits (`GET /api/v1/credits`, management key). -#[derive(Debug, Clone, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct OpenRouterCredits { - pub total_credits: f64, - pub total_usage: f64, - pub remaining: f64, -} - -/// True when OpenRouter refused routing because no ZDR/data-policy endpoint matched. -pub fn is_zdr_routing_error(msg: &str) -> bool { - let lower = msg.to_ascii_lowercase(); - lower.contains("zdr") - || lower.contains("zero data retention") - || lower.contains("data-policy") - || lower.contains("data policy") - || lower.contains("no endpoints matching") - || (lower.contains("guardrail") - && (lower.contains("endpoint") || lower.contains("excluded"))) -} - -fn humanize_openrouter_error(status: u16, text: &str) -> String { - let lower = text.to_ascii_lowercase(); - if lower.contains("zdr") - || lower.contains("zero data retention") - || lower.contains("no endpoints matching") - || (lower.contains("guardrail") - && (lower.contains("endpoint") || lower.contains("zdr") || lower.contains("data"))) - { - return format!( - "OpenRouter blocked media routing (ZDR/data-policy, HTTP {status}). \ - No Zero Data Retention endpoints matched this image/video model. \ - Fix options: (1) Freya Settings → Privacy → turn off “Zero Data Retention on Freya requests”, \ - or pick a ZDR-capable model (often Google image/video) from the Image picker; \ - (2) OpenRouter account privacy / model-group ZDR at https://openrouter.ai/settings/privacy \ - (Freya can only tighten ZDR, not loosen account guardrails). Details: {text}" - ); - } - if status == 402 - || lower.contains("insufficient credits") - || lower.contains("at least $1.00 in balance") - { - return format!( - "OpenRouter needs more credits for image output (HTTP {status}). \ - Add credits at https://openrouter.ai/settings/credits. Details: {text}" - ); - } - format!("openrouter {status}: {text}") -} - -async fn extract_image(http: &reqwest::Client, v: &Value) -> Result { +fn extract_image(v: &Value) -> Result { if let Some(b64) = v.pointer("/data/0/b64_json").and_then(|x| x.as_str()) { return Ok(GeneratedImage { b64: b64.to_string(), @@ -973,41 +169,13 @@ async fn extract_image(http: &reqwest::Client, v: &Value) -> Result Vec { backend: "openrouter".into(), }, ImageModel { - id: "google/gemini-2.5-flash-image".into(), - name: "Gemini 2.5 Flash Image".into(), - backend: "openrouter".into(), - }, - ImageModel { - id: "openai/gpt-image-1-mini".into(), - name: "GPT Image 1 Mini".into(), + id: "openai/gpt-image-2".into(), + name: "GPT Image 2".into(), backend: "openrouter".into(), }, ] } -fn filter_fallback_image(models: &[ImageModel], zdr: bool) -> Vec { - if !zdr { - return models.to_vec(); - } - // Heuristic when catalog fetch fails: prefer Google image models (Safety Retention / ZDR). - let google: Vec<_> = models - .iter() - .filter(|m| m.id.starts_with("google/")) - .cloned() - .collect(); - if !google.is_empty() { - return google; - } - vec![ImageModel { - id: crate::router::DEFAULT_AUTO_IMAGE_MODEL_ZDR.into(), - name: "Gemini 2.5 Flash Image (ZDR fallback)".into(), - backend: "openrouter".into(), - }] -} - -fn parse_image_models_from_catalog(v: &Value) -> Vec { - let mut out = Vec::new(); - let Some(arr) = v.get("data").and_then(|d| d.as_array()) else { - return out; - }; - for m in arr { - let id = m - .get("id") - .and_then(|x| x.as_str()) - .unwrap_or("") - .to_string(); - if id.is_empty() || is_upstream_router_id(&id) || !keeps_declared_output(m, "image") { - continue; - } - let name = m - .get("name") - .and_then(|x| x.as_str()) - .unwrap_or(&id) - .to_string(); - out.push(ImageModel { - id, - name, - backend: "openrouter".into(), - }); - } - out -} - -fn fallback_chat_models() -> Vec { - vec![ - ImageModel { - id: "anthropic/claude-sonnet-5.5".into(), - name: "Claude Sonnet 5.5".into(), - backend: "openrouter".into(), - }, - ImageModel { - id: "google/gemini-4-neon".into(), - name: "Gemini 4 Neon".into(), - backend: "openrouter".into(), - }, - ImageModel { - id: "openai/gpt-5.2".into(), - name: "GPT-5.2".into(), - backend: "openrouter".into(), - }, - ] -} - -fn filter_fallback_chat( - models: &[ImageModel], - alignment: &AlignmentPrefs, - chat_providers: &ChatProvidersPrefs, -) -> Vec { - models - .iter() - .filter(|m| { - if !chat_providers.includes_model_id(&m.id) { - return false; - } - if alignment.model_alignment == "balanced" { - return true; - } - let fake = serde_json::json!({ - "id": m.id, - "name": m.name, - }); - chat_model_matches_alignment(&fake, alignment) - }) - .cloned() - .collect() -} - -fn vendors_from_models(models: &[ImageModel]) -> Vec { - let mut set = std::collections::BTreeSet::new(); - for m in models { - let v = openrouter_vendor(&m.id).to_ascii_lowercase(); - if !v.is_empty() { - set.insert(v); - } - } - set.into_iter().collect() -} - -/// Agent (`models`) and router catalogs after capability / ZDR / alignment / vendor filters. -/// `available` is vendor prefixes seen before alignment and checkbox filters. -#[derive(Debug, Clone, Default)] -pub struct ChatCatalog { - /// Tool-calling text models for the Agent picker. - pub models: Vec, - /// Structured-JSON / tool-calling text models for the Router picker. - pub router: Vec, - pub available: Vec, -} - -fn display_name_for_catalog(m: &Value, id: &str) -> String { - if is_upstream_router_id(id) { - return "OpenRouter router (upstream)".into(); - } - m.get("name") - .and_then(|x| x.as_str()) - .unwrap_or(id) - .to_string() -} - -fn is_upstream_router_id(id: &str) -> bool { - let id = id.trim().to_ascii_lowercase(); - id == "openrouter/auto" || id.starts_with("openrouter/auto") -} - -fn order_pinned(mut scored: Vec<(i64, ImageModel)>) -> Vec { - scored.sort_by(|a, b| b.0.cmp(&a.0).then_with(|| a.1.name.cmp(&b.1.name))); - let mut out: Vec = Vec::new(); - let mut seen = std::collections::HashSet::new(); - for pin in CHAT_PINNED_IDS { - if let Some((_, model)) = scored.iter().find(|(_, m)| m.id == *pin) { - if seen.insert(model.id.clone()) { - out.push(model.clone()); - } - } - } - for (_, model) in scored { - if seen.insert(model.id.clone()) { - out.push(model); - } - } - out -} - -fn ensure_upstream_agent(models: &mut Vec) { - if let Some(existing) = models.iter_mut().find(|m| is_upstream_router_id(&m.id)) { - existing.name = "OpenRouter router (upstream)".into(); - return; - } - models.push(ImageModel { - id: "openrouter/auto".into(), - name: "OpenRouter router (upstream)".into(), - backend: "openrouter".into(), - }); -} - -impl OpenRouterClient { - fn fallback_chat_catalog(&self) -> ChatCatalog { - let chat_providers = self.privacy.chat_providers.clone(); - let mut models = - filter_fallback_chat(&fallback_chat_models(), &self.alignment, &chat_providers); - let router = models.clone(); - if !crate::router::privacy_requires_strict(&self.privacy) { - ensure_upstream_agent(&mut models); - } - let available = vendors_from_models(&fallback_chat_models()); - ChatCatalog { - models, - router, - available, - } - } -} - -fn supported_parameters(m: &Value) -> Option> { - let arr = m.get("supported_parameters")?.as_array()?; - let out: Vec = arr - .iter() - .filter_map(|x| x.as_str().map(|s| s.to_ascii_lowercase())) - .collect(); - if out.is_empty() { - None - } else { - Some(out) - } -} - -fn params_include(params: &[String], names: &[&str]) -> bool { - names.iter().any(|n| params.iter().any(|p| p == n)) -} - -/// Text-chat hygiene: drop routing suffixes, embeddings, image-gen ids. -/// Requires text output and a chat/completions endpoint when endpoints are listed. -/// Missing `supported_parameters` does not make a model agentic. -fn is_text_chat_candidate(m: &Value) -> bool { - let id = m.get("id").and_then(|x| x.as_str()).unwrap_or(""); - if id.is_empty() { - return false; - } - // Skip provider routing suffixes (:batch, :nitro, :free, …). - if id.contains(':') { - return false; - } - let id_l = id.to_ascii_lowercase(); - if id_l.contains("embed") - || id_l.contains("whisper") - || id_l.contains("tts") - || id_l.contains("moderation") - || id_l.contains("upscale") - { - return false; - } - // Image-generation oriented ids (even when they expose chat completions). - if id_l.contains("nano-banana") - || id_l.contains("gpt-image") - || id_l.contains("dall-e") - || id_l.contains("flux") - || id_l.contains("seedream") - || id_l.contains("imagen") - || id_l.contains("recraft") - || (id_l.contains("image") && !id_l.contains("chatgpt")) - { - return false; - } - - let arch = m.get("architecture").unwrap_or(&Value::Null); - let outs = arch - .get("output_modalities") - .and_then(|o| o.as_array()) - .map(|a| a.iter().filter_map(|x| x.as_str()).collect::>()) - .unwrap_or_default(); - if !outs.iter().any(|o| *o == "text") { - return false; - } - // Pure image (or image+audio) generators — not agent chat. - if outs.iter().all(|o| *o != "text") { - return false; - } - - if let Some(ends) = m.get("endpoints").and_then(|e| e.as_array()) { - if !ends.is_empty() { - let chat_ok = ends.iter().any(|e| { - e.as_str() - .map(|s| s.contains("chat/completions")) - .unwrap_or(false) - }); - if !chat_ok { - return false; - } - } - } - true -} - -/// Agent picker: text chat with an explicit tools signal. -/// `openrouter/auto` is included even without the flag (explicit upstream option, not Auto). -fn is_agent_capable(m: &Value) -> bool { - let id = m.get("id").and_then(|x| x.as_str()).unwrap_or(""); - if is_upstream_router_id(id) { - return true; - } - if !is_text_chat_candidate(m) { - return false; - } - match supported_parameters(m) { - Some(params) => params_include(¶ms, &["tools", "tool_choice"]), - None => false, - } -} - -/// Router picker: text chat that can return structured JSON or call tools. -/// Not the unfiltered chat dump. `openrouter/auto` is included only when it passes -/// (it is not the Auto sentinel). -fn is_router_capable(m: &Value) -> bool { - if is_upstream_router_id(m.get("id").and_then(|x| x.as_str()).unwrap_or("")) { - // Upstream router is a concrete option when the catalog lists it and it can do JSON/tools. - } - if !is_text_chat_candidate(m) { - return false; - } - match supported_parameters(m) { - Some(params) => params_include( - ¶ms, - &[ - "response_format", - "structured_outputs", - "json_schema", - "tools", - ], - ), - None => false, - } -} - -fn keeps_declared_output(m: &Value, modality: &str) -> bool { - let Some(arr) = m - .get("architecture") - .and_then(|a| a.get("output_modalities")) - .and_then(|o| o.as_array()) - else { - return true; - }; - if arr.is_empty() { - return true; - } - arr.iter() - .any(|x| x.as_str().is_some_and(|s| s.eq_ignore_ascii_case(modality))) -} - -/// Always surface these (when OpenRouter still lists them) ahead of the newest-N window. -const CHAT_PINNED_IDS: &[&str] = &[ - "anthropic/claude-sonnet-5.5", - "anthropic/claude-opus-5.5", - "google/gemini-4-neon", - "openai/gpt-5.2", - "openai/gpt-4.1-mini", -]; - #[derive(Debug, Clone, Serialize, Deserialize)] pub struct ImageModel { pub id: String, @@ -1390,383 +231,8 @@ pub struct ImageModel { pub backend: String, } -#[derive(Debug, Clone, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct VideoModel { - pub id: String, - pub name: String, - #[serde(default, skip_serializing_if = "Vec::is_empty")] - pub supported_durations: Vec, - #[serde(default, skip_serializing_if = "Vec::is_empty")] - pub supported_resolutions: Vec, - #[serde(default, skip_serializing_if = "Vec::is_empty")] - pub supported_aspect_ratios: Vec, -} - -/// OpenRouter vendor slug: id prefix before `/` (`openai/gpt-5.2` → `openai`). -pub fn openrouter_vendor(id: &str) -> &str { - id.split_once('/').map(|(v, _)| v).unwrap_or(id) -} - -/// Sort catalogs by vendor, then display name, then id (case-insensitive). -pub fn sort_models_by_vendor_name(models: &mut [ImageModel]) { - models.sort_by(|a, b| { - openrouter_vendor(&a.id) - .to_ascii_lowercase() - .cmp(&openrouter_vendor(&b.id).to_ascii_lowercase()) - .then_with(|| { - a.name - .to_ascii_lowercase() - .cmp(&b.name.to_ascii_lowercase()) - }) - .then_with(|| a.id.to_ascii_lowercase().cmp(&b.id.to_ascii_lowercase())) - }); -} - -pub fn sort_video_models_by_vendor_name(models: &mut [VideoModel]) { - models.sort_by(|a, b| { - openrouter_vendor(&a.id) - .to_ascii_lowercase() - .cmp(&openrouter_vendor(&b.id).to_ascii_lowercase()) - .then_with(|| { - a.name - .to_ascii_lowercase() - .cmp(&b.name.to_ascii_lowercase()) - }) - .then_with(|| a.id.to_ascii_lowercase().cmp(&b.id.to_ascii_lowercase())) - }); -} - -fn parse_video_models(v: &Value) -> Vec { - let mut out = Vec::new(); - let Some(arr) = v.get("data").and_then(|d| d.as_array()) else { - return out; - }; - for m in arr { - let id = m - .get("id") - .and_then(|x| x.as_str()) - .unwrap_or("") - .to_string(); - if id.is_empty() || is_upstream_router_id(&id) || !keeps_declared_output(m, "video") { - continue; - } - let name = m - .get("name") - .and_then(|x| x.as_str()) - .unwrap_or(&id) - .to_string(); - let supported_durations = m - .get("supported_durations") - .and_then(|a| a.as_array()) - .map(|a| a.iter().filter_map(|x| x.as_i64()).collect()) - .unwrap_or_default(); - let supported_resolutions = m - .get("supported_resolutions") - .and_then(|a| a.as_array()) - .map(|a| { - a.iter() - .filter_map(|x| x.as_str().map(str::to_string)) - .collect() - }) - .unwrap_or_default(); - let supported_aspect_ratios = m - .get("supported_aspect_ratios") - .and_then(|a| a.as_array()) - .map(|a| { - a.iter() - .filter_map(|x| x.as_str().map(str::to_string)) - .collect() - }) - .unwrap_or_default(); - out.push(VideoModel { - id, - name, - supported_durations, - supported_resolutions, - supported_aspect_ratios, - }); - } - out -} - #[derive(Debug, Clone)] pub struct GeneratedImage { pub b64: String, pub mime: String, } - -#[derive(Debug, Clone)] -pub struct GeneratedVideo { - pub bytes: Vec, - pub mime: String, - pub model: String, - pub job_id: String, -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn rejects_chat_router_as_image_model() { - assert_eq!( - resolve_image_model("openrouter/auto", "black-forest-labs/flux.2-klein-4b"), - "black-forest-labs/flux.2-klein-4b" - ); - assert_eq!( - resolve_image_model( - "None, letting Freya use Auto default (ZDR-aware).", - "black-forest-labs/flux.2-klein-4b" - ), - "black-forest-labs/flux.2-klein-4b" - ); - assert_eq!( - resolve_image_model("google/gemini-2.5-pro", "black-forest-labs/flux.2-klein-4b"), - "black-forest-labs/flux.2-klein-4b" - ); - assert_eq!( - resolve_image_model("openai/gpt-4o-mini", "black-forest-labs/flux.2-klein-4b"), - "black-forest-labs/flux.2-klein-4b" - ); - assert_eq!( - resolve_image_model( - "black-forest-labs/flux.2-klein-4b", - "black-forest-labs/flux.2-klein-4b" - ), - "black-forest-labs/flux.2-klein-4b" - ); - assert_eq!( - resolve_image_model( - "google/gemini-2.5-flash-image", - "black-forest-labs/flux.2-klein-4b" - ), - "google/gemini-2.5-flash-image" - ); - // Invented slug: openrouter/ prefixed onto a non-catalog name. - assert_eq!( - resolve_image_model( - "openrouter/google-gemini-pro-image-1", - "google/gemini-2.5-flash-image" - ), - "google/gemini-2.5-flash-image" - ); - assert_eq!( - resolve_image_model("google-gemini-pro-image-1", "google/gemini-3-pro-image"), - "google/gemini-3-pro-image" - ); - // Prefix stripped only when a real provider/model id follows. - assert_eq!( - resolve_image_model( - "openrouter/google/gemini-3-pro-image", - "black-forest-labs/flux.2-klein-4b" - ), - "google/gemini-3-pro-image" - ); - assert_eq!( - resolve_image_model( - "openrouter/google-gemini-pro-image-1", - "openrouter/google-gemini-pro-image-1" - ), - crate::router::DEFAULT_AUTO_IMAGE_MODEL - ); - // First-party chat ids stay. They are still not image models. - assert_eq!( - canonicalize_catalog_id("openrouter/horizon-alpha"), - "openrouter/horizon-alpha" - ); - assert_eq!( - canonicalize_catalog_id("openrouter/google-gemini-pro-image-1"), - "" - ); - assert_eq!( - resolve_image_model( - "openrouter/horizon-alpha", - "black-forest-labs/flux.2-klein-4b" - ), - "black-forest-labs/flux.2-klein-4b" - ); - } - - #[test] - fn detects_chat_image_models() { - assert!(is_chat_image_model("google/gemini-2.5-flash-image")); - assert!(!is_chat_image_model("black-forest-labs/flux.2-klein-4b")); - } - - #[test] - fn sorts_models_by_vendor_then_name() { - let mut models = vec![ - ImageModel { - id: "openai/gpt-5.2".into(), - name: "GPT-5.2".into(), - backend: "openrouter".into(), - }, - ImageModel { - id: "anthropic/claude-opus-5.5".into(), - name: "Claude Opus 5.5".into(), - backend: "openrouter".into(), - }, - ImageModel { - id: "anthropic/claude-sonnet-5.5".into(), - name: "Claude Sonnet 5.5".into(), - backend: "openrouter".into(), - }, - ImageModel { - id: "google/gemini-4-neon".into(), - name: "Gemini 4 Neon".into(), - backend: "openrouter".into(), - }, - ]; - sort_models_by_vendor_name(&mut models); - let ids: Vec<_> = models.iter().map(|m| m.id.as_str()).collect(); - assert_eq!( - ids, - vec![ - "anthropic/claude-opus-5.5", - "anthropic/claude-sonnet-5.5", - "google/gemini-4-neon", - "openai/gpt-5.2", - ] - ); - } - - #[test] - fn filters_agent_and_router_capabilities() { - let chat = serde_json::json!({ - "id": "anthropic/claude-sonnet-5.5", - "name": "Anthropic: Claude Sonnet 5.5", - "architecture": { "output_modalities": ["text"] }, - "endpoints": ["/api/v1/chat/completions"], - "supported_parameters": ["tools", "tool_choice", "response_format"] - }); - assert!(is_text_chat_candidate(&chat)); - assert!(is_agent_capable(&chat)); - assert!(is_router_capable(&chat)); - - // Tools missing and no JSON params → not agent, not router (do not guess). - let bare = serde_json::json!({ - "id": "writer/palmyra-x5", - "architecture": { "output_modalities": ["text"] }, - "endpoints": ["/api/v1/chat/completions"], - "supported_parameters": ["temperature", "max_tokens"] - }); - assert!(is_text_chat_candidate(&bare)); - assert!(!is_agent_capable(&bare)); - assert!(!is_router_capable(&bare)); - - // JSON without tools → router only (dolphin-class). - let dolphin = serde_json::json!({ - "id": "cognitivecomputations/dolphin-mistral-24b-venice-edition", - "name": "Dolphin Mistral 24B Venice", - "architecture": { "output_modalities": ["text"] }, - "endpoints": ["/api/v1/chat/completions"], - "supported_parameters": ["response_format", "temperature"] - }); - assert!(!is_agent_capable(&dolphin)); - assert!(is_router_capable(&dolphin)); - - // Missing supported_parameters → exclude from both. - let missing = serde_json::json!({ - "id": "meta-llama/llama-3.1-8b-instruct", - "architecture": { "output_modalities": ["text"] }, - "endpoints": ["/api/v1/chat/completions"] - }); - assert!(is_text_chat_candidate(&missing)); - assert!(!is_agent_capable(&missing)); - assert!(!is_router_capable(&missing)); - - // Live Llama 3.1 8B parameter set qualifies as router and agent. - let llama = serde_json::json!({ - "id": "meta-llama/llama-3.1-8b-instruct", - "architecture": { "output_modalities": ["text"] }, - "endpoints": ["/api/v1/chat/completions"], - "supported_parameters": ["response_format", "structured_outputs", "tools", "tool_choice", "temperature"] - }); - assert!(is_agent_capable(&llama)); - assert!(is_router_capable(&llama)); - - let batch = serde_json::json!({ - "id": "google/gemini-4-neon:batch", - "architecture": { "output_modalities": ["text"] }, - "endpoints": ["/api/v1/chat/completions"], - "supported_parameters": ["tools", "response_format"] - }); - assert!(!is_text_chat_candidate(&batch)); - assert!(!is_agent_capable(&batch)); - - let free = serde_json::json!({ - "id": "cognitivecomputations/dolphin-mistral-24b-venice-edition:free", - "architecture": { "output_modalities": ["text"] }, - "endpoints": ["/api/v1/chat/completions"], - "supported_parameters": ["tools"] - }); - assert!(!is_agent_capable(&free)); - - let image = serde_json::json!({ - "id": "google/gemini-2.5-flash-image", - "architecture": { "output_modalities": ["text", "image"] }, - "endpoints": ["/api/v1/chat/completions"], - "supported_parameters": ["tools"] - }); - assert!(!is_agent_capable(&image)); - assert!(!keeps_declared_output(&image, "video")); - assert!(keeps_declared_output(&image, "image")); - - let embed = serde_json::json!({ - "id": "openai/text-embedding-3-large", - "architecture": { "output_modalities": ["embeddings"] }, - "endpoints": ["/api/v1/embeddings"], - "supported_parameters": ["tools"] - }); - assert!(!is_agent_capable(&embed)); - - // Upstream router is an explicit agent option even with no tools flag. - let upstream = serde_json::json!({ - "id": "openrouter/auto", - "architecture": { "output_modalities": ["text", "image"] }, - "supported_parameters": ["temperature"] - }); - assert!(is_agent_capable(&upstream)); - assert!(!is_router_capable(&upstream)); - - let text_only = serde_json::json!({ - "id": "openai/gpt-4o-mini", - "architecture": { "output_modalities": ["text"] } - }); - assert!(!keeps_declared_output(&text_only, "image")); - assert!(!keeps_declared_output(&text_only, "video")); - } - - #[test] - fn humanizes_zdr() { - let msg = humanize_openrouter_error( - 404, - r#"{"error":{"message":"ZDR violation (guardrail): 1 endpoint excluded"}}"#, - ); - assert!(msg.contains("ZDR/data-policy") || msg.contains("ZDR")); - assert!(msg.contains("settings/privacy")); - assert!(msg.contains("Freya Settings")); - assert!(is_zdr_routing_error(&msg)); - } - - #[test] - fn detects_zdr_routing_errors() { - assert!(is_zdr_routing_error( - "OpenRouter blocked media routing (ZDR/data-policy, HTTP 404). No endpoints matching" - )); - assert!(is_zdr_routing_error( - r#"{"error":{"message":"No endpoints found that match your data policy (ZDR)"}}"# - )); - assert!(!is_zdr_routing_error( - "openrouter 402: insufficient credits" - )); - } - - #[test] - fn filters_fallback_image_for_zdr() { - let all = fallback_models(); - let zdr = filter_fallback_image(&all, true); - assert!(zdr.iter().all(|m| m.id.starts_with("google/"))); - } -} diff --git a/crates/freya-api/src/routes.rs b/crates/freya-api/src/routes.rs index bdb2699..e5091d8 100644 --- a/crates/freya-api/src/routes.rs +++ b/crates/freya-api/src/routes.rs @@ -1,5 +1,4 @@ use crate::gallery::ArtifactMeta; -use crate::prefs::{looks_nsfw_label, AlignmentPrefs, AutoFallbacksPrefs, PrivacyPrefs}; use crate::state::{AppState, RuntimeSecrets}; use crate::styles::{self, StylePack}; use crate::worker::LoraWeight; @@ -9,3494 +8,47 @@ use axum::response::{IntoResponse, Response}; use axum::Json; use base64::Engine; use serde::{Deserialize, Serialize}; -use serde_json::{json, Value}; +use serde_json::json; type ApiResult = Result; pub async fn health(State(state): State) -> impl IntoResponse { - let (open_router, civitai, worker_url) = { - let cfg = state.config.read().await; - ( - cfg.openrouter_configured(), - cfg.civitai_configured(), - cfg.diffusion_worker_url.clone(), - ) - }; + let cfg = state.config.read().await; let worker_ok = { let w = state.worker.read().await; match w.as_ref() { Some(c) => c.health().await, None => false, - } - }; - Json(json!({ - "ok": true, - "openRouter": open_router, - "civitai": civitai, - "diffusionWorker": worker_ok, - "workerConfigured": worker_url.is_some(), - })) -} - -/// Proxy worker GPU/runtime stats; enrich VRAM from host `nvidia-smi` when worker returns null. -pub async fn worker_stats(State(state): State) -> impl IntoResponse { - let (url, container, unit) = { - let cfg = state.config.read().await; - ( - cfg.diffusion_worker_url.clone(), - cfg.worker_container.clone(), - cfg.worker_systemd_unit.clone(), - ) - }; - let runtime = crate::worker_ctl::detect(&container, &unit).await; - let mut worker_payload = Value::Null; - let mut reachable = false; - let mut have_stats = false; - { - let w = state.worker.read().await; - if let Some(c) = w.as_ref() { - if let Some(detail) = c.stats_detail().await { - reachable = true; - have_stats = true; - worker_payload = detail; - } else if c.health().await { - reachable = true; - } - } - } - - let mut vram = worker_payload.get("vram").cloned().unwrap_or(Value::Null); - let mut host = worker_payload.get("host").cloned().unwrap_or(Value::Null); - // Host nvidia-smi fills a worker that reported stats with null VRAM - // (GPU-less container). A failed /v1/stats must not borrow the host GPU. - if have_stats && vram.is_null() { - let host_vram = crate::gpu::collect_host_vram().await; - if !host_vram.is_null() { - vram = host_vram; - if host.is_null() { - host = json!({ - "hostname": crate::gpu::hostname_string(), - "source": "host-nvidia-smi", - }); - } - } - } - - let gallery_dir = state.config.read().await.gallery_dir.clone(); - let gallery_disk = crate::disk::collect_path_disk(&gallery_dir); - let models_disk = worker_payload.get("disk").cloned().unwrap_or(Value::Null); - - Json(json!({ - "ok": true, - "configured": url.is_some(), - "url": url, - "reachable": reachable, - "runtime": runtime.to_json(), - "vram": vram, - "host": host, - "loras": worker_payload.get("loras").cloned().unwrap_or(Value::Null), - "checkpoints": worker_payload.get("checkpoints").cloned().unwrap_or(Value::Null), - "uptimeSec": worker_payload.get("uptimeSec").cloned().unwrap_or(Value::Null), - "modelLoaded": worker_payload.get("modelLoaded").cloned().unwrap_or(Value::Null), - "modelsDir": worker_payload.get("modelsDir").cloned().unwrap_or(Value::Null), - "modelsDirHost": worker_payload.get("modelsDirHost").cloned().unwrap_or(Value::Null), - "engine": worker_payload.get("engine").cloned().unwrap_or(Value::Null), - "vramBehavior": worker_payload - .get("vramBehavior") - .cloned() - .unwrap_or(Value::Null), - "layout": worker_payload.get("layout").cloned().unwrap_or(Value::Null), - "storage": { - "gallery": gallery_disk, - "models": models_disk, - }, - "worker": worker_payload, - })) -} - -fn local_asset_json(a: crate::worker::LocalAsset) -> Value { - json!({ - "id": a.id, - "name": a.name.unwrap_or_else(|| a.id.clone()), - "kind": a.kind, - "path": a.path, - "baseModel": a.base_model, - "modelType": a.model_type, - "versionId": a.version_id, - "modelId": a.model_id, - "sizeBytes": a.size_bytes, - "source": a.source, - "thumbnailUrl": a.thumbnail_url, - "backend": "local", - }) -} - -pub async fn worker_checkpoints(State(state): State) -> ApiResult> { - let worker = state.worker.read().await; - let client = worker.as_ref().ok_or(ApiError::NoWorker)?; - let items = client.list_checkpoints().await.map_err(ApiError::from)?; - Ok(Json(json!({ - "data": items.into_iter().map(local_asset_json).collect::>(), - }))) -} - -pub async fn worker_installed(State(state): State) -> ApiResult> { - installed_payload(&state).await.map(Json) -} - -async fn installed_payload(state: &AppState) -> ApiResult { - let worker = state.worker.read().await; - let client = worker.as_ref().ok_or(ApiError::NoWorker)?; - let loras = client.list_loras().await.map_err(ApiError::from)?; - let checkpoints = client.list_checkpoints().await.map_err(ApiError::from)?; - let embeddings = client.list_embeddings().await.unwrap_or_default(); - let vaes = client.list_vaes().await.unwrap_or_default(); - Ok(json!({ - "loras": loras.into_iter().map(local_asset_json).collect::>(), - "checkpoints": checkpoints.into_iter().map(local_asset_json).collect::>(), - "embeddings": embeddings.into_iter().map(local_asset_json).collect::>(), - "vaes": vaes.into_iter().map(local_asset_json).collect::>(), - })) -} - -pub async fn worker_loras(State(state): State) -> ApiResult> { - let worker = state.worker.read().await; - let client = worker.as_ref().ok_or(ApiError::NoWorker)?; - let items = client.list_loras().await.map_err(ApiError::from)?; - Ok(Json(json!({ - "data": items.into_iter().map(local_asset_json).collect::>(), - }))) -} - -pub async fn worker_embeddings(State(state): State) -> ApiResult> { - let worker = state.worker.read().await; - let client = worker.as_ref().ok_or(ApiError::NoWorker)?; - let items = client.list_embeddings().await.map_err(ApiError::from)?; - Ok(Json(json!({ - "data": items.into_iter().map(local_asset_json).collect::>(), - }))) -} - -pub async fn worker_vaes(State(state): State) -> ApiResult> { - let worker = state.worker.read().await; - let client = worker.as_ref().ok_or(ApiError::NoWorker)?; - let items = client.list_vaes().await.map_err(ApiError::from)?; - Ok(Json(json!({ - "data": items.into_iter().map(local_asset_json).collect::>(), - }))) -} - -#[derive(Debug, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct DeleteWorkerAsset { - pub path: String, -} - -pub async fn worker_asset_delete( - State(state): State, - Json(req): Json, -) -> ApiResult> { - let path = req.path.trim(); - if path.is_empty() { - return Err(ApiError::Msg("path required".into())); - } - let worker = state.worker.read().await; - let client = worker.as_ref().ok_or(ApiError::NoWorker)?; - let v = client.delete_asset(path).await.map_err(ApiError::from)?; - Ok(Json(v)) -} - -pub async fn civitai_jobs_list(State(state): State) -> ApiResult> { - let worker = state.worker.read().await; - let client = worker.as_ref().ok_or(ApiError::NoWorker)?; - let v = client.list_install_jobs().await.map_err(ApiError::from)?; - Ok(Json(v)) -} - -pub async fn civitai_job_get( - State(state): State, - axum::extract::Path(id): axum::extract::Path, -) -> ApiResult> { - let worker = state.worker.read().await; - let client = worker.as_ref().ok_or(ApiError::NoWorker)?; - let v = client.get_install_job(&id).await.map_err(|e| { - if e.to_string().contains("not found") { - ApiError::NotFound - } else { - ApiError::from(e) - } - })?; - Ok(Json(v)) -} - -pub async fn civitai_job_cancel( - State(state): State, - axum::extract::Path(id): axum::extract::Path, -) -> ApiResult> { - let worker = state.worker.read().await; - let client = worker.as_ref().ok_or(ApiError::NoWorker)?; - let v = client - .cancel_install_job(&id) - .await - .map_err(ApiError::from)?; - Ok(Json(v)) -} - -#[derive(Debug, Deserialize, Default)] -#[serde(rename_all = "camelCase")] -pub struct ClearCivitaiJobsRequest { - /// When true, also drop idle queued jobs. Active downloads are never cleared. - #[serde(default)] - pub include_queued: bool, -} - -pub async fn civitai_jobs_clear( - State(state): State, - body: Option>, -) -> ApiResult> { - let include_queued = body.map(|Json(b)| b.include_queued).unwrap_or(false); - let worker = state.worker.read().await; - let client = worker.as_ref().ok_or(ApiError::NoWorker)?; - let v = client - .clear_install_jobs(include_queued) - .await - .map_err(ApiError::from)?; - Ok(Json(v)) -} - -pub async fn worker_base_model_get(State(state): State) -> ApiResult> { - let worker = state.worker.read().await; - let client = worker.as_ref().ok_or(ApiError::NoWorker)?; - let v = client.get_active_base().await.map_err(ApiError::from)?; - Ok(Json(v)) -} - -#[derive(Debug, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct SetWorkerBaseModel { - pub model: String, - #[serde(default)] - pub base_model: Option, -} - -pub async fn worker_base_model_put( - State(state): State, - Json(req): Json, -) -> ApiResult> { - let worker = state.worker.read().await; - let client = worker.as_ref().ok_or(ApiError::NoWorker)?; - let v = client - .set_active_base(&req.model, req.base_model.as_deref()) - .await - .map_err(ApiError::from)?; - Ok(Json(v)) -} - -pub async fn base_models_catalog() -> Json { - Json(json!({ - "items": crate::base_models::catalog(), - "note": "Local GPU worker hosts SD/SDXL/Pony/Flux checkpoints under FREYA_MODELS_DIR. Remote LLM/vLLM text endpoints typically cannot run these.", - })) -} - -pub async fn worker_start(State(state): State) -> ApiResult> { - let (container, unit) = { - let cfg = state.config.read().await; - ( - cfg.worker_container.clone(), - cfg.worker_systemd_unit.clone(), - ) - }; - let runtime = crate::worker_ctl::start(&container, &unit) - .await - .map_err(ApiError::Msg)?; - // Brief wait so /health can come up before the UI polls. - tokio::time::sleep(std::time::Duration::from_millis(400)).await; - Ok(Json(json!({ "ok": true, "runtime": runtime.to_json() }))) -} - -pub async fn worker_stop(State(state): State) -> ApiResult> { - let (container, unit) = { - let cfg = state.config.read().await; - ( - cfg.worker_container.clone(), - cfg.worker_systemd_unit.clone(), - ) - }; - let runtime = crate::worker_ctl::stop(&container, &unit) - .await - .map_err(ApiError::Msg)?; - Ok(Json(json!({ "ok": true, "runtime": runtime.to_json() }))) -} - -#[derive(Debug, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct AssistRequest { - pub mode: String, - pub message: String, - #[serde(default)] - pub model: Option, - /// Optional prior turns for agentic session context. - #[serde(default)] - pub session: Option, -} - -fn strip_json_fence(raw: &str) -> &str { - raw.trim() - .trim_start_matches("```json") - .trim_start_matches("```") - .trim_end_matches("```") - .trim() -} - -pub async fn assist( - State(state): State, - Json(req): Json, -) -> ApiResult> { - let system = load_instruction_toned(&state, &req.mode).await; - let user_msg = if let Some(sess) = &req.session { - format!( - "{}\n\n--- session context ---\n{}", - req.message, - serde_json::to_string_pretty(sess).unwrap_or_default() - ) - } else { - req.message.clone() - }; - let or = state.openrouter.read().await; - let text = or - .chat(&system, &user_msg, req.model.as_deref()) - .await - .map_err(ApiError::from)?; - - let mut out = json!({ "mode": req.mode, "text": text }); - - // Structured modes: parse plan JSON and optionally search Civitai for LoRAs. - if matches!(req.mode.as_str(), "suggest" | "session" | "plan") { - if let Ok(parsed) = serde_json::from_str::(strip_json_fence(&text)) { - out["plan"] = parsed.clone(); - if let Some(ideas) = parsed.get("ideas") { - out["ideas"] = ideas.clone(); - } - if let Some(batch) = parsed.get("batchPrompts") { - out["batchPrompts"] = batch.clone(); - } - if let Some(note) = parsed.get("sessionNote").and_then(|n| n.as_str()) { - out["sessionNote"] = json!(note); - } - if let Some(goal) = parsed.get("goal") { - out["goal"] = goal.clone(); - } - if let Some(steps) = parsed.get("steps") { - out["steps"] = steps.clone(); - } - let query = parsed - .get("civitaiQuery") - .and_then(|q| q.as_str()) - .map(str::trim) - .filter(|q| !q.is_empty()); - if let Some(q) = query { - out["civitaiQuery"] = json!(q); - let civ = state.civitai.read().await; - if civ.configured() { - match civ.search(q, 12).await { - Ok(items) => { - let mut assets: Vec<_> = items - .into_iter() - .filter(|c| crate::civitai::is_freya_asset_type(&c.model_type)) - .collect(); - assets.sort_by_key(|c| crate::civitai::asset_type_rank(&c.model_type)); - assets.truncate(6); - out["loras"] = json!(assets); - } - Err(e) => { - out["civitaiError"] = json!(e.to_string()); - } - } - } - } - } - } - - Ok(Json(out)) -} - -// ——— Conversational chat with tool actions (Plan / Auto / YOLO) ——— - -#[derive(Debug, Deserialize, Clone)] -#[serde(rename_all = "camelCase")] -pub struct ChatMessageIn { - pub role: String, - pub content: String, -} - -#[derive(Debug, Deserialize, Clone)] -#[serde(rename_all = "camelCase")] -pub struct ChatActionIn { - #[serde(rename = "type")] - pub action_type: String, - #[serde(default)] - pub args: serde_json::Value, -} - -#[derive(Debug, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct ChatRequest { - pub message: String, - #[serde(default)] - pub messages: Vec, - #[serde(default)] - pub session: Option, - #[serde(default)] - pub automation_mode: Option, - #[serde(default)] - pub model: Option, - #[serde(default)] - pub image_model: Option, - /// Composer Cloud | Local preference: `openrouter` | `local` | `cloud` (optional). - #[serde(default)] - pub backend: Option, - /// Composer video model pin (`auto` or a provider/model id). Not an API key. - #[serde(default)] - pub video_model: Option, - /// When true, skip LLM planning and execute `actions` (Plan confirmation). - #[serde(default)] - pub confirm: bool, - #[serde(default)] - pub actions: Vec, - #[serde(default)] - pub loras: Vec, -} - -#[derive(Debug, Clone)] -struct PlannedAction { - action_type: String, - args: serde_json::Value, -} - -fn wants_image_intent(message: &str) -> bool { - crate::router::infer_modality(message) - .modality - .is_still_image() -} - -fn infer_chat_plan(message: &str) -> (String, Vec) { - let m = message.to_lowercase(); - let mut actions = Vec::new(); - - if m.contains("suggest") || m.contains("idea") || m.contains("brainstorm") { - actions.push(PlannedAction { - action_type: "suggest_ideas".into(), - args: json!({ "topic": message }), - }); - } - if m.contains("civitai") - || m.contains("search for lora") - || m.contains("find a lora") - || m.contains("find loras") - || m.contains("search civitai") - { - let query = message - .split_once("for ") - .map(|(_, rest)| rest.trim()) - .filter(|s| !s.is_empty()) - .unwrap_or(message); - actions.push(PlannedAction { - action_type: "search_civitai".into(), - args: json!({ "query": query.chars().take(80).collect::() }), - }); - } - - // Worker settings (Worker tab — safe API surface). - let asks_worker_status = (m.contains("worker") - && (m.contains("status") - || m.contains("reachable") - || m.contains("online") - || m.contains("running") - || m.contains("enabled") - || m.contains("on?") - || m.contains("off?"))) - || m.contains("is the worker") - || m.contains("worker ok"); - let asks_list_loras = m.contains("list lora") - || m.contains("list loras") - || m.contains("installed lora") - || m.contains("installed loras") - || m.contains("what loras") - || m.contains("which loras") - || (m.contains("lora") - && (m.contains("installed") || m.contains("on the worker") || m.contains("on disk"))); - let asks_list_checkpoints = m.contains("list checkpoint") - || m.contains("list checkpoints") - || m.contains("available checkpoint") - || m.contains("which checkpoints") - || m.contains("what checkpoints") - || (m.contains("checkpoint") - && (m.contains("list") || m.contains("show") || m.contains("available"))); - let asks_get_base = m.contains("active base") - || m.contains("current base") - || m.contains("what base") - || m.contains("which base") - || m.contains("base model") - || m.contains("active checkpoint") - || m.contains("current checkpoint"); - let asks_set_base = m.contains("set base") - || m.contains("switch base") - || m.contains("change base") - || m.contains("use checkpoint") - || m.contains("set checkpoint") - || m.contains("set active base") - || m.contains("switch checkpoint") - || m.contains("change checkpoint"); - if asks_set_base { - // Need a concrete path — list first so the user (or a follow-up) can pick. - actions.push(PlannedAction { - action_type: "list_checkpoints".into(), - args: json!({}), - }); - actions.push(PlannedAction { - action_type: "get_base_model".into(), - args: json!({}), - }); - } else if asks_get_base { - actions.push(PlannedAction { - action_type: "get_base_model".into(), - args: json!({}), - }); - } else if asks_list_checkpoints { - actions.push(PlannedAction { - action_type: "list_checkpoints".into(), - args: json!({}), - }); - } else if asks_list_loras { - actions.push(PlannedAction { - action_type: "list_loras".into(), - args: json!({}), - }); - } else if asks_worker_status { - actions.push(PlannedAction { - action_type: "worker_status".into(), - args: json!({}), - }); - } - - if wants_image_intent(message) { - if m.contains("run session") || m.contains("variations") || m.contains("batch") { - actions.push(PlannedAction { - action_type: "run_session".into(), - args: json!({ "goal": message }), - }); - } else { - actions.push(PlannedAction { - action_type: "generate_image".into(), - args: json!({ "prompt": message, "batch": false }), - }); - } - } - - let reply = if actions.is_empty() { - format!( - "Happy to talk through it. Tell me when you want me to generate, search Civitai, tweak the worker base, or suggest ideas — I’ll wait until you ask." - ) - } else if actions - .iter() - .any(|a| a.action_type == "generate_image" || a.action_type == "run_session") - { - "On it — I’ll make that image for you.".into() - } else if actions.iter().any(|a| a.action_type == "search_civitai") { - "I’ll search Civitai for matching assets.".into() - } else if actions.iter().any(|a| { - matches!( - a.action_type.as_str(), - "worker_status" - | "list_checkpoints" - | "list_loras" - | "get_base_model" - | "set_base_model" - ) - }) { - "Checking worker settings…".into() - } else { - "Here are some directions we could take.".into() - }; - (reply, actions) -} - -/// Cloud chat models often answer a refusal instead of a scene. That text must -/// not become the local diffusion prompt. -fn looks_like_model_refusal(text: &str) -> bool { - let l = text - .to_ascii_lowercase() - .replace(['\u{2019}', '\u{2018}', '`'], "'"); - // Phrase-shaped refusals. Bare "i can't" / "against my" show up in scene text. - const MARKERS: &[&str] = &[ - "i can't help", - "i cannot help", - "i can't assist", - "i cannot assist", - "can't help", - "cannot help", - "can't assist", - "cannot assist", - "can't create", - "cannot create", - "can't generate", - "cannot generate", - "won't generate", - "will not generate", - "i won't create", - "i will not create", - "i'm not able", - "i am not able", - "not able to generate", - "not able to create", - "against my guidelines", - "against my policy", - "against my programming", - "content policy", - "i must refuse", - "unable to create", - "unable to generate", - "as an ai", - ]; - MARKERS.iter().any(|m| l.contains(m)) -} - -/// Drop a label or fence so the worker sees the keyword prompt. -fn normalize_sd_rewrite(text: &str) -> String { - let mut t = text.trim().trim_matches('`').trim().to_string(); - if t.len() >= 2 { - let bytes = t.as_bytes(); - let wrap = (bytes[0] == b'"' && bytes[bytes.len() - 1] == b'"') - || (bytes[0] == b'\'' && bytes[bytes.len() - 1] == b'\''); - if wrap { - t = t[1..t.len() - 1].trim().to_string(); - } - } - let lower = t.to_ascii_lowercase(); - for prefix in ["positive prompt:", "sd prompt:", "prompt:"] { - if lower.starts_with(prefix) { - t = t[prefix.len()..].trim().to_string(); - break; - } - } - t -} - -fn sd_prompt_shape(text: &str) -> bool { - text.contains(',') || text.split_whitespace().count() >= 12 -} - -/// Adult local rewrite must be a scene prompt, not a refusal. -/// An echo of the user line counts only when that line is already checkpoint-shaped. -/// A short raw scene is not accepted in place of a rewrite. -fn adult_rewrite_ok(text: &str, original: &str) -> bool { - let t = text.trim(); - let original = original.trim(); - if t.is_empty() || looks_like_model_refusal(t) { - return false; - } - if t.eq_ignore_ascii_case(original) { - return sd_prompt_shape(original); - } - sd_prompt_shape(t) -} - -/// Second uncensored writer when the first cell refuses or errors. -/// Auto's first writer is already the matrix cell, so the other cost tier is the retry. -fn adult_retry_model( - first: &str, - privacy: &crate::prefs::PrivacyPrefs, - fallbacks: &crate::prefs::AutoFallbacksPrefs, -) -> Option { - let matrix = crate::router::local_adult_matrix_model(privacy, fallbacks); - if matrix != first { - return Some(matrix); - } - let mut other = fallbacks.clone(); - other.cost_tier = if fallbacks.cost_tier.eq_ignore_ascii_case("low") { - "medium".into() - } else { - "low".into() - }; - let alt = crate::router::local_adult_matrix_model(privacy, &other); - if alt == first { - None - } else { - Some(alt) - } -} - -fn restore_refused_local_prompt(action: &mut PlannedAction, user_message: &str) { - let key = match action.action_type.as_str() { - "generate_image" | "generate_video" => "prompt", - "run_session" => "goal", - _ => return, - }; - let current = action - .args - .get(key) - .and_then(|v| v.as_str()) - .unwrap_or("") - .trim(); - if current.is_empty() || looks_like_model_refusal(current) { - if let Some(obj) = action.args.as_object_mut() { - obj.insert(key.to_string(), json!(user_message)); - } - } -} - -fn parse_chat_plan(text: &str, fallback_message: &str) -> (String, Vec) { - if let Ok(parsed) = serde_json::from_str::(strip_json_fence(text)) { - let reply = parsed - .get("reply") - .and_then(|r| r.as_str()) - .unwrap_or(text) - .to_string(); - let mut actions = Vec::new(); - if let Some(arr) = parsed.get("actions").and_then(|a| a.as_array()) { - for a in arr { - let ty = a - .get("type") - .and_then(|t| t.as_str()) - .unwrap_or("") - .to_string(); - if ty.is_empty() { - continue; - } - let args = a.get("args").cloned().unwrap_or(json!({})); - actions.push(PlannedAction { - action_type: ty, - args, - }); - } - } - return (reply, actions); - } - // Model returned prose — keep it, infer tools from user intent. - let (fallback_reply, inferred) = infer_chat_plan(fallback_message); - if inferred.is_empty() { - (text.trim().to_string(), vec![]) - } else if text.trim().is_empty() { - (fallback_reply, inferred) - } else { - (text.trim().to_string(), inferred) - } -} - -fn is_side_effect_action(ty: &str) -> bool { - matches!( - ty, - "generate_image" - | "generate_video" - | "install_asset" - | "cancel_install_job" - | "clear_install_jobs" - | "delete_installed" - | "run_session" - | "set_base_model" - | "set_chat_models" - | "set_cost_tier" - | "set_alignment" - | "set_privacy" - | "set_generate_backend" - | "set_automation_mode" - | "favorite_asset" - | "unfavorite_asset" - | "pin_lora" - | "unpin_lora" - | "gallery_delete" - | "worker_start" - | "worker_stop" - ) -} - -fn style_ref_from_args(args: &Value) -> Option { - args.get("styleRef") - .or_else(|| args.get("style_ref")) - .and_then(|v| v.as_str()) - .map(str::trim) - .filter(|s| !s.is_empty()) - .map(str::to_string) -} - -fn short_model_id(id: &str) -> &str { - id.rsplit('/').next().unwrap_or(id) -} - -struct RouteFooter<'a> { - route: &'a crate::router::RouteDecision, - agent: Option<&'a str>, - router: &'a str, - image: &'a str, - video: &'a str, - /// Composer or executed backend: `local`, `openrouter`, or `cloud`. - backend: &'a str, - /// Active checkpoint display name (local only). - base: &'a str, - /// Pinned LoRA names, or `none`. - lora: &'a str, - /// Plan / Auto / YOLO. - mode: &'a str, -} - -fn footer_backend_kind(raw: &str) -> &'static str { - match raw.trim().to_ascii_lowercase().as_str() { - "local" => "local", - "cloud" | "openrouter" => "cloud", - _ => "cloud", - } -} - -fn automation_mode_label(mode: &str) -> &'static str { - match mode.trim().to_ascii_lowercase().as_str() { - "plan" => "Plan", - "yolo" => "YOLO", - _ => "Auto", - } -} - -fn format_route_visibility(f: &RouteFooter<'_>) -> String { - let modality = f.route.modality.as_str(); - let agent = f.agent.map(short_model_id).unwrap_or("auto"); - let router = short_model_id(f.router); - let kind = footer_backend_kind(f.backend); - if kind == "local" { - let base = if f.base.trim().is_empty() { - "none" - } else { - f.base.trim() - }; - let lora = if f.lora.trim().is_empty() { - "none" - } else { - f.lora.trim() - }; - format!( - "Route: {modality} · agent={agent} · router={router} · base={base} · lora={lora} · mode={} · backend=local", - automation_mode_label(f.mode) - ) - } else { - format!( - "Route: {modality} · agent={agent} · router={router} · image={} · video={} · backend=cloud", - short_model_id(f.image), - short_model_id(f.video) - ) - } -} - -fn enrich_reply_with_route( - reply: &str, - route: &crate::router::RouteDecision, - resolved_agent: Option<&str>, - resolved_router: &str, - resolved_image: &str, - resolved_video: &str, - action_results: &[Value], - preferred_backend: Option<&str>, - base: &str, - lora: &str, - mode: &str, -) -> String { - let backend_from_gen = action_results.iter().find_map(|ar| { - if ar.get("status").and_then(|s| s.as_str()) != Some("executed") { - return None; - } - if !matches!( - ar.get("type").and_then(|t| t.as_str()), - Some("generate_image" | "generate_video" | "run_session") - ) { - return None; - } - ar.get("result") - .and_then(|r| r.get("backend")) - .and_then(|b| b.as_str()) - .map(str::to_string) - }); - let preferred = preferred_backend - .map(str::trim) - .filter(|b| !b.is_empty() && *b != "auto"); - let backend = preferred.or(backend_from_gen.as_deref()).unwrap_or("cloud"); - let line = format_route_visibility(&RouteFooter { - route, - agent: resolved_agent, - router: resolved_router, - image: resolved_image, - video: resolved_video, - backend, - base, - lora, - mode, - }); - let trimmed = reply.trim(); - if trimmed.is_empty() { - line - } else if trimmed.contains("Route:") { - trimmed.to_string() - } else { - format!("{trimmed}\n\n{line}") - } -} - -fn format_worker_action_summary(ar: &Value) -> Option { - let ty = ar.get("type").and_then(|t| t.as_str()).unwrap_or(""); - let status = ar.get("status").and_then(|s| s.as_str()).unwrap_or(""); - if status == "error" { - let err = ar.get("error").and_then(|e| e.as_str()).unwrap_or("error"); - return Some(format!("{ty} failed: {err}")); - } - if status == "proposed" { - return Some(format!("Proposed: {ty}")); - } - let res = ar.get("result")?; - match ty { - "worker_status" => { - let configured = res.get("workerConfigured").and_then(|v| v.as_bool()); - let reachable = res.get("reachable").and_then(|v| v.as_bool()); - let mut parts = Vec::new(); - if let Some(c) = configured { - parts.push(if c { - "URL configured".into() - } else { - "no worker URL".into() - }); - } - if let Some(r) = reachable { - parts.push(if r { - "reachable".into() - } else { - "not reachable".into() - }); - } - if let Some(m) = res.get("modelLoaded").and_then(|v| v.as_str()) { - if !m.is_empty() { - parts.push(format!("loaded {m}")); - } - } - Some(if parts.is_empty() { - "Worker status checked.".into() - } else { - format!("Worker: {}.", parts.join(", ")) - }) - } - "list_checkpoints" | "list_loras" => { - let key = if ty == "list_loras" { - "loras" - } else { - "checkpoints" - }; - let label = if ty == "list_loras" { - "LoRAs" - } else { - "Checkpoints" - }; - let empty = if ty == "list_loras" { - "No LoRAs on the worker yet — install one from Civitai first." - } else { - "No checkpoints on the worker yet — install one from Civitai first." - }; - let items = res - .get(key) - .or_else(|| res.get("data")) - .and_then(|d| d.as_array()) - .cloned() - .unwrap_or_default(); - if items.is_empty() { - return Some(empty.into()); - } - let names: Vec = items - .iter() - .take(8) - .map(|c| { - let name = - c.get("name") - .and_then(|n| n.as_str()) - .unwrap_or(if ty == "list_loras" { - "lora" - } else { - "checkpoint" - }); - let path = c.get("path").and_then(|p| p.as_str()).unwrap_or(""); - let base = c.get("baseModel").and_then(|b| b.as_str()).unwrap_or(""); - if base.is_empty() { - format!("{name} ({path})") - } else { - format!("{name} [{base}] ({path})") - } - }) - .collect(); - let more = if items.len() > names.len() { - format!(" … +{} more", items.len() - names.len()) - } else { - String::new() - }; - Some(format!( - "{label} ({}): {}{}.", - items.len(), - names.join("; "), - more - )) - } - "get_base_model" | "set_base_model" => { - let model = res - .get("model") - .and_then(|m| m.as_str()) - .unwrap_or("(none)"); - let base = res.get("baseModel").and_then(|b| b.as_str()).unwrap_or(""); - let verb = if ty == "set_base_model" { - "Active base set to" - } else { - "Active base is" - }; - Some(if base.is_empty() { - format!("{verb} {model}.") - } else { - format!("{verb} {model} ({base}).") - }) - } - "gallery_list" => { - let n = res - .get("items") - .and_then(|i| i.as_array()) - .map(|a| a.len()) - .unwrap_or(0); - Some(format!("Gallery: {n} item(s).")) - } - "gallery_get" => { - let id = res.get("id").and_then(|i| i.as_str()).unwrap_or("?"); - let prompt = res - .get("prompt") - .and_then(|p| p.as_str()) - .unwrap_or("") - .chars() - .take(60) - .collect::(); - Some(if prompt.is_empty() { - format!("Gallery item {id}.") - } else { - format!("Gallery {id}: {prompt}…") - }) - } - "list_styles" => { - let n = res - .get("items") - .and_then(|i| i.as_array()) - .map(|a| a.len()) - .unwrap_or(0); - Some(format!("Styles: {n} pack(s).")) - } - "apply_style" => { - let id = res.get("id").and_then(|i| i.as_str()).unwrap_or("?"); - let name = res - .get("displayName") - .and_then(|n| n.as_str()) - .unwrap_or(id); - Some(format!( - "Style ready: {name} (pass styleRef={id} on generate)." - )) - } - "list_models" => { - let chat_n = res - .get("chat") - .and_then(|c| c.as_array()) - .map(|a| a.len()) - .unwrap_or(0); - let img_n = res - .get("openrouter") - .and_then(|c| c.as_array()) - .map(|a| a.len()) - .unwrap_or(0); - let vid_n = res - .get("video") - .and_then(|c| c.as_array()) - .map(|a| a.len()) - .unwrap_or(0); - let local_n = res - .get("local") - .and_then(|c| c.as_array()) - .map(|a| a.len()) - .unwrap_or(0); - Some(format!( - "Models: {chat_n} chat, {img_n} image, {vid_n} video, {local_n} local." - )) - } - "get_settings" => { - let zdr = res - .get("privacy") - .and_then(|p| p.get("zeroDataRetention")) - .and_then(|z| z.as_bool()) - .unwrap_or(false); - let chat = res.get("chatModel").and_then(|m| m.as_str()).unwrap_or("?"); - let image = res - .get("imageModel") - .and_then(|m| m.as_str()) - .unwrap_or("?"); - let router = res - .get("routerModel") - .and_then(|m| m.as_str()) - .unwrap_or("?"); - Some(format!( - "Settings: agent={chat}, image={image}, router={router}, ZDR={}.", - if zdr { "on" } else { "off" } - )) - } - "get_route_defaults" => { - let auto_img = res - .get("auto") - .and_then(|a| a.get("image")) - .and_then(|m| m.as_str()) - .unwrap_or("?"); - let auto_vid = res - .get("auto") - .and_then(|a| a.get("video")) - .and_then(|m| m.as_str()) - .unwrap_or("?"); - Some(format!( - "Route defaults (Auto): image={}, video={}. Use set_chat_models to pin.", - short_model_id(auto_img), - short_model_id(auto_vid) - )) - } - "set_chat_models" => { - let chat = res.get("chatModel").and_then(|m| m.as_str()).unwrap_or("?"); - let image = res - .get("imageModel") - .and_then(|m| m.as_str()) - .unwrap_or("?"); - let router = res - .get("routerModel") - .and_then(|m| m.as_str()) - .unwrap_or("?"); - Some(format!( - "Saved model prefs: agent={chat}, image={image}, router={router}." - )) - } - "openrouter_metrics" => { - if !res - .get("configured") - .and_then(|c| c.as_bool()) - .unwrap_or(false) - { - return Some("OpenRouter metrics: API key not configured.".into()); - } - let usage = res - .get("key") - .and_then(|k| k.get("usage")) - .and_then(|u| u.as_f64()); - let remaining = res - .get("key") - .and_then(|k| k.get("limitRemaining")) - .and_then(|u| u.as_f64()); - Some(match (usage, remaining) { - (Some(u), Some(r)) => format!("OpenRouter spend: ${u:.4} used, ${r:.4} remaining."), - (Some(u), None) => format!("OpenRouter spend: ${u:.4} used."), - _ => "OpenRouter metrics fetched.".into(), - }) - } - "gallery_delete" => { - let id = res.get("id").and_then(|i| i.as_str()).unwrap_or("?"); - Some(format!("Removed gallery item {id}.")) - } - "gallery_download" => { - let url = res.get("url").and_then(|u| u.as_str()).unwrap_or(""); - Some(if url.is_empty() { - "Gallery file is ready in the UI download control.".into() - } else { - format!("Download in the UI: {url}") - }) - } - "list_install_jobs" => { - let n = res - .get("data") - .or_else(|| res.get("jobs")) - .and_then(|d| d.as_array()) - .map(|a| a.len()) - .unwrap_or(0); - Some(format!("Download jobs: {n}.")) - } - "cancel_install_job" => Some("Cancelled that download.".into()), - "list_installed" => Some("Listed installed worker assets.".into()), - "favorite_asset" | "unfavorite_asset" => { - let n = res - .get("favorites") - .and_then(|f| f.as_array()) - .map(|a| a.len()) - .unwrap_or(0); - Some(format!("Favorites: {n}.")) - } - "pin_lora" | "unpin_lora" => { - let n = res - .get("pinnedLoras") - .and_then(|f| f.as_array()) - .map(|a| a.len()) - .unwrap_or(0); - Some(format!("Session LoRA pins: {n}.")) - } - "set_cost_tier" => { - let tier = res - .get("autoFallbacks") - .and_then(|a| a.get("costTier")) - .and_then(|t| t.as_str()) - .unwrap_or("?"); - Some(format!("Cost tier set to {tier}.")) - } - "set_privacy" | "set_alignment" | "set_generate_backend" | "set_automation_mode" => { - Some(format!("{ty} saved.")) - } - "generate_image" | "generate_video" => { - let backend = res.get("backend").and_then(|b| b.as_str()).unwrap_or("?"); - let model = res - .get("model") - .and_then(|m| m.as_str()) - .map(short_model_id) - .unwrap_or("?"); - let modality = - res.get("modality") - .and_then(|m| m.as_str()) - .unwrap_or(if ty == "generate_video" { - "video" - } else { - "picture" - }); - Some(format!("Generated {modality} via {backend} ({model}).")) - } - _ => None, - } -} - -fn enrich_reply_with_worker_results(reply: &str, action_results: &[Value]) -> String { - // ZDR/data-policy failures must replace optimistic "Generating…" replies. - if let Some(err) = action_results.iter().find_map(|ar| { - if ar.get("status").and_then(|s| s.as_str()) != Some("error") { - return None; - } - if !matches!( - ar.get("type").and_then(|t| t.as_str()), - Some("generate_image" | "generate_video") - ) { - return None; - } - let err = ar.get("error").and_then(|e| e.as_str())?; - if crate::openrouter::is_zdr_routing_error(err) { - Some(err.to_string()) - } else { - None - } - }) { - return format!( - "I couldn't generate that media because Zero Data Retention blocked OpenRouter routing.\n\n\ - {err}\n\n\ - Quick fixes: Freya Settings → Privacy → turn off “Zero Data Retention on Freya requests”, \ - or pick a ZDR-capable Image/Video model (often Google). \ - Account-wide / model-group ZDR: https://openrouter.ai/settings/privacy" - ); - } - - let summaries: Vec = action_results - .iter() - .filter_map(format_worker_action_summary) - .collect(); - if summaries.is_empty() { - return reply.to_string(); - } - let block = summaries.join(" "); - let trimmed = reply.trim(); - if trimmed.is_empty() - || trimmed == "Checking worker settings…" - || trimmed.eq_ignore_ascii_case("checking worker settings...") - { - block - } else { - format!("{trimmed}\n\n{block}") - } -} - -async fn chat_generate_backend( - state: &AppState, - pinned: &[LoraIn], - preferred: Option<&str>, -) -> String { - if let Some(b) = preferred - .map(str::trim) - .filter(|b| !b.is_empty() && *b != "auto") - { - return b.to_string(); - } - if !pinned.is_empty() && local_worker_ready(state).await { - return "local".into(); - } - "auto".into() -} - -/// Image model for chat generate actions: local never gets Auto/cloud/prose ids. -fn resolve_action_image_model(image_model: Option<&str>, backend: &str) -> Option { - let m = image_model.map(str::trim).filter(|s| !s.is_empty())?; - if crate::router::is_auto_image(m) { - return None; - } - if backend == "local" { - return crate::base_models::filter_local_model(Some(m)); - } - // OpenRouter path still rejects non-image prose via resolve_image_model later. - Some(m.to_string()) -} - -fn action_error(ty: &str, args: &Value, error: impl Into) -> Value { - json!({ - "type": ty, - "status": "error", - "args": args, - "error": error.into() - }) -} - -fn action_ok(ty: &str, args: &Value, result: Value) -> Value { - json!({ - "type": ty, - "status": "executed", - "args": args, - "result": result - }) -} - -fn api_err_msg(e: ApiError) -> String { - match e { - ApiError::Msg(m) => m, - ApiError::Unauthorized(m) | ApiError::Unavailable(m) => m, - ApiError::NoWorker => "No diffusion worker configured".into(), - ApiError::NotFound => "not found".into(), - } -} - -/// Refuse args whose names look like credentials. Values are never echoed. -fn reject_secret_fields(args: &Value) -> Option { - let obj = args.as_object()?; - for key in obj.keys() { - let l = key.to_ascii_lowercase().replace(['_', '-'], ""); - if l.contains("apikey") - || l.contains("apitoken") - || l.contains("password") - || l.contains("secret") - || l == "token" - || l.contains("admintoken") - || l.contains("bearertoken") - || l.contains("hftoken") - || l.contains("workertoken") - { - return Some(format!("refusing to read or set {key}")); - } - } - None -} - -fn with_gallery_url(meta: &ArtifactMeta) -> Value { - let mut v = serde_json::to_value(meta).unwrap_or_else(|_| json!({})); - if let Some(obj) = v.as_object_mut() { - obj.insert( - "url".into(), - json!(format!("/v1/gallery/{}/image", meta.id)), - ); - } - v -} - -async fn persist_prefs(state: &AppState) -> bool { - let persisted = state.persist_secrets().await.is_ok(); - let cfg = state.config.read().await; - let mut or = state.openrouter.write().await; - *or = crate::openrouter::OpenRouterClient::new(&cfg); - persisted -} - -async fn settings_value(state: &AppState) -> Value { - serde_json::to_value(settings_public_from_state(state).await).unwrap_or(json!({})) -} - -async fn execute_chat_action( - state: &AppState, - action: &PlannedAction, - pinned: &[LoraIn], - image_model: Option<&str>, - video_model: Option<&str>, - backend: Option<&str>, -) -> serde_json::Value { - let ty = action.action_type.as_str(); - match ty { - "suggest_ideas" => { - let topic = action - .args - .get("topic") - .and_then(|t| t.as_str()) - .unwrap_or("a memorable scene"); - let system = load_instruction_toned(&state, "suggest").await; - let or = state.openrouter.read().await; - match or.chat(&system, topic, None).await { - Ok(text) => { - let mut ideas = Vec::new(); - let mut note = String::new(); - if let Ok(parsed) = - serde_json::from_str::(strip_json_fence(&text)) - { - if let Some(arr) = parsed.get("ideas").and_then(|i| i.as_array()) { - ideas = arr - .iter() - .filter_map(|x| x.as_str().map(str::to_string)) - .collect(); - } - if let Some(n) = parsed.get("sessionNote").and_then(|n| n.as_str()) { - note = n.to_string(); - } - } - if ideas.is_empty() { - ideas = text - .lines() - .map(|l| { - l.trim() - .trim_start_matches(|c: char| { - c.is_ascii_digit() || c == '.' || c == ')' - }) - .trim() - }) - .filter(|l| !l.is_empty()) - .take(5) - .map(str::to_string) - .collect(); - } - json!({ - "type": ty, - "status": "executed", - "args": action.args, - "result": { "ideas": ideas, "sessionNote": note } - }) - } - Err(e) => json!({ - "type": ty, - "status": "error", - "args": action.args, - "error": e.to_string() - }), - } - } - "search_civitai" => { - let q = action - .args - .get("query") - .and_then(|q| q.as_str()) - .unwrap_or("") - .trim(); - if q.is_empty() { - return json!({ - "type": ty, - "status": "error", - "args": action.args, - "error": "missing query" - }); - } - let civ = state.civitai.read().await; - if !civ.configured() { - return json!({ - "type": ty, - "status": "error", - "args": action.args, - "error": "Civitai API key not configured" - }); - } - match civ.search(q, 12).await { - Ok(items) => { - let mut assets: Vec<_> = items - .into_iter() - .filter(|c| crate::civitai::is_freya_asset_type(&c.model_type)) - .collect(); - assets.sort_by_key(|c| crate::civitai::asset_type_rank(&c.model_type)); - assets.truncate(6); - json!({ - "type": ty, - "status": "executed", - "args": action.args, - "result": { "query": q, "loras": assets } - }) - } - Err(e) => json!({ - "type": ty, - "status": "error", - "args": action.args, - "error": e.to_string() - }), - } - } - "generate_image" => { - let prompt = action - .args - .get("prompt") - .and_then(|p| p.as_str()) - .unwrap_or("") - .trim(); - if prompt.is_empty() { - return json!({ - "type": ty, - "status": "error", - "args": action.args, - "error": "missing prompt" - }); - } - let backend_choice = chat_generate_backend(state, pinned, backend).await; - let req = GenerateRequest { - prompt: prompt.to_string(), - negative_prompt: None, - enhance: Some("auto".into()), - backend: Some(backend_choice.clone()), - model: resolve_action_image_model(image_model, &backend_choice), - style_ref: style_ref_from_args(&action.args), - loras: pinned.to_vec(), - size: None, - seed: None, - modality: Some("picture".into()), - duration: None, - }; - match run_generate(state, req).await { - Ok(result) => json!({ - "type": ty, - "status": "executed", - "args": action.args, - "result": result - }), - Err(e) => { - let msg = match e { - ApiError::Msg(m) => m, - ApiError::Unauthorized(m) | ApiError::Unavailable(m) => m, - ApiError::NoWorker => "No diffusion worker configured".into(), - ApiError::NotFound => "not found".into(), - }; - json!({ - "type": ty, - "status": "error", - "args": action.args, - "error": msg - }) - } - } - } - "generate_video" => { - let prompt = action - .args - .get("prompt") - .and_then(|p| p.as_str()) - .unwrap_or("") - .trim(); - if prompt.is_empty() { - return json!({ - "type": ty, - "status": "error", - "args": action.args, - "error": "missing prompt" - }); - } - let modality = action - .args - .get("modality") - .and_then(|m| m.as_str()) - .unwrap_or("video") - .to_string(); - let backend_choice = chat_generate_backend(state, pinned, backend).await; - let mut req = GenerateRequest { - prompt: prompt.to_string(), - negative_prompt: None, - enhance: Some("auto".into()), - backend: Some(backend_choice), - model: video_model.map(str::to_string), - style_ref: style_ref_from_args(&action.args), - loras: vec![], - size: None, - seed: None, - modality: Some(modality), - duration: action.args.get("duration").and_then(|d| d.as_i64()), - }; - if req.model.as_deref() == Some("auto") { - req.model = None; - } - match run_generate(state, req).await { - Ok(result) => json!({ - "type": ty, - "status": "executed", - "args": action.args, - "result": result - }), - Err(e) => { - let msg = match e { - ApiError::Msg(m) => m, - ApiError::Unauthorized(m) | ApiError::Unavailable(m) => m, - ApiError::NoWorker => "No diffusion worker configured".into(), - ApiError::NotFound => "not found".into(), - }; - json!({ - "type": ty, - "status": "error", - "args": action.args, - "error": msg - }) - } - } - } - "run_session" => { - let goal = action - .args - .get("goal") - .and_then(|g| g.as_str()) - .unwrap_or("explore the scene") - .trim(); - let backend_choice = chat_generate_backend(state, pinned, backend).await; - let local_passthrough = backend_choice.eq_ignore_ascii_case("local") - && state - .config - .read() - .await - .alignment_prefs() - .local_adult_passthrough(); - let batch: Vec = if local_passthrough { - Vec::new() - } else { - let system = load_instruction_toned(&state, "session").await; - let or = state.openrouter.read().await; - match or.chat(&system, goal, None).await { - Ok(text) => { - if let Ok(parsed) = - serde_json::from_str::(strip_json_fence(&text)) - { - parsed - .get("batchPrompts") - .and_then(|b| b.as_array()) - .map(|arr| { - arr.iter() - .filter_map(|x| x.as_str().map(str::to_string)) - .collect() - }) - .unwrap_or_default() - } else { - vec![] - } - } - Err(_) => vec![], - } - }; - let prompts = if batch.is_empty() { - vec![ - format!("{goal} — wide establishing shot."), - format!("{goal} — closer framing."), - format!("{goal} — quieter mood."), - ] - } else { - batch - }; - let session_style = style_ref_from_args(&action.args); - let mut results = Vec::new(); - for p in &prompts { - let req = GenerateRequest { - prompt: p.clone(), - negative_prompt: None, - enhance: Some("auto".into()), - backend: Some(backend_choice.clone()), - model: resolve_action_image_model(image_model, &backend_choice), - style_ref: session_style.clone(), - loras: pinned.to_vec(), - size: None, - seed: None, - modality: Some("picture".into()), - duration: None, - }; - match run_generate(state, req).await { - Ok(r) => results.push(r), - Err(e) => { - let msg = match e { - ApiError::Msg(m) => m, - ApiError::Unauthorized(m) | ApiError::Unavailable(m) => m, - ApiError::NoWorker => "No diffusion worker configured".into(), - ApiError::NotFound => "not found".into(), - }; - results.push(json!({ "error": msg, "prompt": p })); - } - } - } - let failed = results - .iter() - .filter_map(|r| r.get("error").and_then(|e| e.as_str())) - .collect::>(); - if !results.is_empty() && failed.len() == results.len() { - json!({ - "type": ty, - "status": "error", - "args": action.args, - "error": failed.first().copied().unwrap_or("series generation failed"), - "result": { "goal": goal, "batchPrompts": prompts, "results": results } - }) - } else { - json!({ - "type": ty, - "status": "executed", - "args": action.args, - "result": { "goal": goal, "batchPrompts": prompts, "results": results } - }) - } - } - "install_asset" => { - let download_url = action - .args - .get("downloadUrl") - .and_then(|u| u.as_str()) - .unwrap_or(""); - let version_id = action.args.get("versionId").and_then(|x| x.as_i64()); - let dest_path = action - .args - .get("destPath") - .and_then(|d| d.as_str()) - .unwrap_or("loras/asset.safetensors"); - let name = action - .args - .get("name") - .and_then(|n| n.as_str()) - .map(str::to_string); - if download_url.is_empty() && version_id.is_none() { - return json!({ - "type": ty, - "status": "error", - "args": action.args, - "error": "missing downloadUrl or versionId" - }); - } - let install_req = InstallCivitaiRequest { - download_url: download_url.to_string(), - dest_path: dest_path.to_string(), - name, - base_model: action - .args - .get("baseModel") - .and_then(|x| x.as_str()) - .map(str::to_string), - version_id, - model_id: action - .args - .get("modelId") - .and_then(|x| x.as_i64()) - .or_else(|| action.args.get("id").and_then(|x| x.as_i64())), - file_id: action.args.get("fileId").and_then(|x| x.as_i64()), - model_type: action - .args - .get("modelType") - .and_then(|x| x.as_str()) - .map(str::to_string), - thumbnail_url: action - .args - .get("thumbnailUrl") - .and_then(|x| x.as_str()) - .map(str::to_string), - }; - match civitai_install_inner(state, install_req).await { - Ok(v) => json!({ - "type": ty, - "status": "executed", - "args": action.args, - "result": v - }), - Err(e) => { - let msg = match e { - ApiError::Msg(m) => m, - ApiError::Unauthorized(m) | ApiError::Unavailable(m) => m, - ApiError::NoWorker => { - "LoRA install needs a diffusion worker — set the worker URL in Settings" - .into() - } - ApiError::NotFound => "not found".into(), - }; - json!({ - "type": ty, - "status": "error", - "args": action.args, - "error": msg - }) - } - } - } - "worker_status" => { - let worker_url = state.config.read().await.diffusion_worker_url.clone(); - let mut reachable = false; - let mut detail = Value::Null; - if let Some(client) = state.worker.read().await.as_ref() { - if let Some(v) = client.stats_detail().await { - reachable = true; - detail = v; - } else { - reachable = client.health().await; - } - } - json!({ - "type": ty, - "status": "executed", - "args": action.args, - "result": { - "workerConfigured": worker_url.is_some(), - "reachable": reachable, - "modelLoaded": detail.get("modelLoaded").cloned().unwrap_or(Value::Null), - "vram": detail.get("vram").cloned().unwrap_or(Value::Null), - "loras": detail.get("loras").cloned().unwrap_or(Value::Null), - "checkpoints": detail.get("checkpoints").cloned().unwrap_or(Value::Null), - "engine": detail.get("engine").cloned().unwrap_or(Value::Null), - } - }) - } - "list_checkpoints" => { - let worker = state.worker.read().await; - let Some(client) = worker.as_ref() else { - return json!({ - "type": ty, - "status": "error", - "args": action.args, - "error": "No diffusion worker configured" - }); - }; - match client.list_checkpoints().await { - Ok(items) => { - let checkpoints: Vec = items - .into_iter() - .map(|a| { - json!({ - "id": a.id, - "name": a.name.unwrap_or_else(|| a.id.clone()), - "kind": a.kind, - "path": a.path, - "baseModel": a.base_model, - "backend": "local", - }) - }) - .collect(); - json!({ - "type": ty, - "status": "executed", - "args": action.args, - "result": { "checkpoints": checkpoints } - }) - } - Err(e) => json!({ - "type": ty, - "status": "error", - "args": action.args, - "error": e.to_string() - }), - } - } - "list_loras" => { - let worker = state.worker.read().await; - let Some(client) = worker.as_ref() else { - return json!({ - "type": ty, - "status": "error", - "args": action.args, - "error": "No diffusion worker configured" - }); - }; - match client.list_loras().await { - Ok(items) => { - let loras: Vec = items - .into_iter() - .map(|a| { - json!({ - "id": a.id, - "name": a.name.unwrap_or_else(|| a.id.clone()), - "kind": a.kind, - "path": a.path, - "baseModel": a.base_model, - "backend": "local", - }) - }) - .collect(); - json!({ - "type": ty, - "status": "executed", - "args": action.args, - "result": { "loras": loras } - }) - } - Err(e) => json!({ - "type": ty, - "status": "error", - "args": action.args, - "error": e.to_string() - }), - } - } - "get_base_model" => { - let worker = state.worker.read().await; - let Some(client) = worker.as_ref() else { - return json!({ - "type": ty, - "status": "error", - "args": action.args, - "error": "No diffusion worker configured" - }); - }; - match client.get_active_base().await { - Ok(v) => json!({ - "type": ty, - "status": "executed", - "args": action.args, - "result": v - }), - Err(e) => json!({ - "type": ty, - "status": "error", - "args": action.args, - "error": e.to_string() - }), - } - } - "set_base_model" => { - let model = action - .args - .get("model") - .and_then(|m| m.as_str()) - .unwrap_or("") - .trim(); - if model.is_empty() { - return json!({ - "type": ty, - "status": "error", - "args": action.args, - "error": "missing model path — list_checkpoints first, then set_base_model with args.model" - }); - } - let base_model = action - .args - .get("baseModel") - .and_then(|b| b.as_str()) - .map(str::to_string); - let worker = state.worker.read().await; - let Some(client) = worker.as_ref() else { - return json!({ - "type": ty, - "status": "error", - "args": action.args, - "error": "No diffusion worker configured" - }); - }; - match client.set_active_base(model, base_model.as_deref()).await { - Ok(v) => json!({ - "type": ty, - "status": "executed", - "args": action.args, - "result": v - }), - Err(e) => json!({ - "type": ty, - "status": "error", - "args": action.args, - "error": e.to_string() - }), - } - } - "gallery_list" => { - let query = action - .args - .get("query") - .and_then(|q| q.as_str()) - .map(str::trim) - .filter(|s| !s.is_empty()) - .map(|s| s.to_ascii_lowercase()); - match state.gallery.list().await { - Ok(items) => { - let filtered: Vec<_> = match &query { - Some(q) => items - .into_iter() - .filter(|m| { - m.prompt.to_ascii_lowercase().contains(q) - || m.enhanced_prompt - .as_deref() - .map(|e| e.to_ascii_lowercase().contains(q)) - .unwrap_or(false) - || m.id.to_ascii_lowercase().contains(q) - }) - .take(24) - .collect(), - None => items.into_iter().take(24).collect(), - }; - let items: Vec = filtered.iter().map(with_gallery_url).collect(); - json!({ - "type": ty, - "status": "executed", - "args": action.args, - "result": { "items": items, "query": query } - }) - } - Err(e) => json!({ - "type": ty, - "status": "error", - "args": action.args, - "error": e.to_string() - }), - } - } - "gallery_get" => { - let id = action - .args - .get("id") - .and_then(|i| i.as_str()) - .unwrap_or("") - .trim(); - if id.is_empty() { - return json!({ - "type": ty, - "status": "error", - "args": action.args, - "error": "missing id" - }); - } - match state.gallery.get(id).await { - Ok(Some(meta)) => json!({ - "type": ty, - "status": "executed", - "args": action.args, - "result": with_gallery_url(&meta) - }), - Ok(None) => json!({ - "type": ty, - "status": "error", - "args": action.args, - "error": "not found" - }), - Err(e) => json!({ - "type": ty, - "status": "error", - "args": action.args, - "error": e.to_string() - }), - } - } - "list_styles" => match styles::load_styles(&state.packs_dir).await { - Ok(items) => json!({ - "type": ty, - "status": "executed", - "args": action.args, - "result": { "items": items } - }), - Err(e) => json!({ - "type": ty, - "status": "error", - "args": action.args, - "error": e.to_string() - }), - }, - "apply_style" => { - let style_ref = style_ref_from_args(&action.args).or_else(|| { - action - .args - .get("id") - .and_then(|i| i.as_str()) - .map(str::trim) - .filter(|s| !s.is_empty()) - .map(str::to_string) - }); - let Some(id) = style_ref else { - return json!({ - "type": ty, - "status": "error", - "args": action.args, - "error": "missing styleRef — list_styles first" - }); - }; - match styles::load_styles(&state.packs_dir).await { - Ok(items) => { - if let Some(pack) = items.into_iter().find(|s| s.id == id) { - json!({ - "type": ty, - "status": "executed", - "args": action.args, - "result": pack - }) - } else { - json!({ - "type": ty, - "status": "error", - "args": action.args, - "error": format!("unknown styleRef: {id}") - }) - } - } - Err(e) => json!({ - "type": ty, - "status": "error", - "args": action.args, - "error": e.to_string() - }), - } - } - "list_models" => match models_payload(state).await { - Ok(v) => json!({ - "type": ty, - "status": "executed", - "args": action.args, - "result": v - }), - Err(e) => { - let msg = match e { - ApiError::Msg(m) => m, - ApiError::Unauthorized(m) | ApiError::Unavailable(m) => m, - ApiError::NoWorker => "No diffusion worker configured".into(), - ApiError::NotFound => "not found".into(), - }; - json!({ - "type": ty, - "status": "error", - "args": action.args, - "error": msg - }) - } - }, - "get_settings" => { - let settings = settings_public_from_state(state).await; - json!({ - "type": ty, - "status": "executed", - "args": action.args, - "result": settings - }) - } - "get_route_defaults" => { - let (cfg_snap, privacy, alignment, auto_fallbacks) = { - let cfg = state.config.read().await; - let or = state.openrouter.read().await; - ( - ( - cfg.chat_model.clone(), - cfg.image_model.clone(), - cfg.router_model.clone(), - or.configured_chat_model().to_string(), - or.configured_image_model().to_string(), - or.configured_router_model().to_string(), - ), - or.privacy().clone(), - or.alignment().clone(), - or.auto_fallbacks().clone(), - ) - }; - let (chat_model, image_model, router_model, _or_chat, or_image, or_router) = cfg_snap; - let resolved_router = crate::router::resolve_router_model_prefs( - &or_router, - &privacy, - &alignment, - &auto_fallbacks, - ); - let auto_image = crate::router::resolve_auto_fallback( - crate::router::AutoFallbackKind::Image, - &privacy, - &alignment, - &auto_fallbacks, - ); - let auto_video = crate::router::resolve_auto_fallback( - crate::router::AutoFallbackKind::Video, - &privacy, - &alignment, - &auto_fallbacks, - ); - let auto_agent = crate::router::resolve_auto_fallback( - crate::router::AutoFallbackKind::Agent, - &privacy, - &alignment, - &auto_fallbacks, - ); - json!({ - "type": ty, - "status": "executed", - "args": action.args, - "result": { - "sentinels": { - "agent": crate::router::AUTO_AGENT, - "image": crate::router::AUTO_IMAGE, - "router": crate::router::AUTO_ROUTER, - }, - "configured": { - "chatModel": chat_model, - "imageModel": image_model, - "routerModel": router_model, - }, - "auto": { - "router": resolved_router.clone(), - "image": auto_image, - "video": auto_video, - "agent": auto_agent, - }, - "autoFallbacks": auto_fallbacks, - "resolved": { - "router": resolved_router, - "imageConfigured": or_image, - "zdr": privacy.zero_data_retention, - "alignment": alignment.model_alignment, - }, - "notes": [ - "Pin agent/image/router with set_chat_models (persists to Settings).", - "Cloud vs Local is the Studio composer switch (backend), not a chat model pref.", - "Pin video with set_chat_models videoModel (id only). Cloud vs Local is set_generate_backend.", - "Configure Auto fallbacks on the Models tab when the router does not pin a model.", - ], - } - }) - } - "set_chat_models" => { - let chat = action - .args - .get("chatModel") - .or_else(|| action.args.get("agentModel")) - .and_then(|m| m.as_str()) - .map(str::trim) - .filter(|s| !s.is_empty()) - .map(str::to_string); - let image = action - .args - .get("imageModel") - .and_then(|m| m.as_str()) - .map(str::trim) - .filter(|s| !s.is_empty()) - .map(str::to_string); - let router = action - .args - .get("routerModel") - .and_then(|m| m.as_str()) - .map(str::trim) - .filter(|s| !s.is_empty()) - .map(str::to_string); - let video = action - .args - .get("videoModel") - .and_then(|m| m.as_str()) - .map(str::trim) - .filter(|s| !s.is_empty()) - .map(str::to_string); - if chat.is_none() && image.is_none() && router.is_none() && video.is_none() { - return action_error( - ty, - &action.args, - "provide chatModel, imageModel, routerModel, and/or videoModel", - ); - } - if let Some(msg) = reject_secret_fields(&action.args) { - return action_error(ty, &action.args, msg); - } - let video_norm = if let Some(v) = video.as_deref() { - match crate::studio::normalize_video_model(v) { - Ok(id) => Some(id), - Err(e) => return action_error(ty, &action.args, e), - } - } else { - None - }; - { - let mut cfg = state.config.write().await; - if let Some(m) = chat { - cfg.chat_model = m; - } - if let Some(m) = image { - cfg.image_model = m; - } - if let Some(m) = router { - cfg.router_model = m; - } - if let Some(v) = video_norm { - cfg.studio.video_model = v; - } - } - let persisted = state.persist_secrets().await.is_ok(); - { - let cfg = state.config.read().await; - let mut or = state.openrouter.write().await; - *or = crate::openrouter::OpenRouterClient::new(&cfg); - } - let settings = settings_public_from_state(state).await; - let mut out = serde_json::to_value(&settings).unwrap_or(json!({})); - if let Some(obj) = out.as_object_mut() { - obj.insert("persisted".into(), json!(persisted)); - } - json!({ - "type": ty, - "status": "executed", - "args": action.args, - "result": out - }) - } - "openrouter_metrics" => match openrouter_metrics_payload(state).await { - Ok(v) => json!({ - "type": ty, - "status": "executed", - "args": action.args, - "result": v - }), - Err(e) => { - let msg = match e { - ApiError::Msg(m) => m, - ApiError::Unauthorized(m) | ApiError::Unavailable(m) => m, - ApiError::NoWorker => "No diffusion worker configured".into(), - ApiError::NotFound => "not found".into(), - }; - json!({ - "type": ty, - "status": "error", - "args": action.args, - "error": msg - }) - } - }, - "list_install_jobs" => { - let worker = state.worker.read().await; - let Some(client) = worker.as_ref() else { - return action_error(ty, &action.args, "No diffusion worker configured"); - }; - match client.list_install_jobs().await { - Ok(v) => action_ok(ty, &action.args, v), - Err(e) => action_error(ty, &action.args, e.to_string()), - } - } - "cancel_install_job" => { - let id = action - .args - .get("jobId") - .or_else(|| action.args.get("id")) - .and_then(|i| i.as_str()) - .unwrap_or("") - .trim() - .to_string(); - if id.is_empty() { - return action_error(ty, &action.args, "missing jobId"); - } - let worker = state.worker.read().await; - let Some(client) = worker.as_ref() else { - return action_error(ty, &action.args, "No diffusion worker configured"); - }; - match client.cancel_install_job(&id).await { - Ok(v) => action_ok(ty, &action.args, v), - Err(e) => action_error(ty, &action.args, e.to_string()), - } - } - "clear_install_jobs" => { - let include_queued = action - .args - .get("includeQueued") - .and_then(|v| v.as_bool()) - .unwrap_or(false); - let worker = state.worker.read().await; - let Some(client) = worker.as_ref() else { - return action_error(ty, &action.args, "No diffusion worker configured"); - }; - match client.clear_install_jobs(include_queued).await { - Ok(v) => action_ok(ty, &action.args, v), - Err(e) => action_error(ty, &action.args, e.to_string()), - } - } - "list_installed" => match installed_payload(state).await { - Ok(v) => action_ok(ty, &action.args, v), - Err(e) => action_error(ty, &action.args, api_err_msg(e)), - }, - "delete_installed" => { - let path = action - .args - .get("path") - .and_then(|p| p.as_str()) - .unwrap_or("") - .trim() - .to_string(); - if path.is_empty() || path.contains("..") { - return action_error(ty, &action.args, "missing worker path"); - } - let worker = state.worker.read().await; - let Some(client) = worker.as_ref() else { - return action_error(ty, &action.args, "No diffusion worker configured"); - }; - match client.delete_asset(&path).await { - Ok(v) => action_ok(ty, &action.args, v), - Err(e) => action_error(ty, &action.args, e.to_string()), - } - } - "favorite_asset" => { - if let Some(msg) = reject_secret_fields(&action.args) { - return action_error(ty, &action.args, msg); - } - let card = crate::studio::asset_from_action_args(&action.args); - let mut saved = None; - let mut err = None; - { - let mut cfg = state.config.write().await; - match crate::studio::favorite_add(&mut cfg.studio, &card) { - Ok(c) => saved = Some(c), - Err(e) => err = Some(e), - } - } - if let Some(e) = err { - return action_error(ty, &action.args, e); - } - let persisted = state.persist_secrets().await.is_ok(); - let favorites = state.config.read().await.studio.favorites.clone(); - action_ok( - ty, - &action.args, - json!({ "favorites": favorites, "favorite": saved, "persisted": persisted }), - ) - } - "unfavorite_asset" => { - let card = crate::studio::asset_from_action_args(&action.args); - let removed = { - let mut cfg = state.config.write().await; - crate::studio::favorite_remove(&mut cfg.studio, &card) - }; - let persisted = state.persist_secrets().await.is_ok(); - let favorites = state.config.read().await.studio.favorites.clone(); - action_ok( - ty, - &action.args, - json!({ "favorites": favorites, "removed": removed, "persisted": persisted }), - ) - } - "list_favorites" => { - let favorites = state.config.read().await.studio.favorites.clone(); - action_ok(ty, &action.args, json!({ "favorites": favorites })) - } - "pin_lora" => { - if let Some(msg) = reject_secret_fields(&action.args) { - return action_error(ty, &action.args, msg); - } - let card = crate::studio::asset_from_action_args(&action.args); - let mut err = None; - { - let mut cfg = state.config.write().await; - if let Err(e) = crate::studio::pin_add(&mut cfg.studio, &card) { - err = Some(e); - } - } - if let Some(e) = err { - return action_error(ty, &action.args, e); - } - let persisted = state.persist_secrets().await.is_ok(); - let pins = state.config.read().await.studio.pinned_loras.clone(); - action_ok( - ty, - &action.args, - json!({ "pinnedLoras": pins, "persisted": persisted }), - ) - } - "unpin_lora" => { - let card = crate::studio::asset_from_action_args(&action.args); - { - let mut cfg = state.config.write().await; - crate::studio::pin_remove(&mut cfg.studio, &card); - } - let persisted = state.persist_secrets().await.is_ok(); - let pins = state.config.read().await.studio.pinned_loras.clone(); - action_ok( - ty, - &action.args, - json!({ "pinnedLoras": pins, "persisted": persisted }), - ) - } - "list_pins" => { - let pins = state.config.read().await.studio.pinned_loras.clone(); - action_ok(ty, &action.args, json!({ "pinnedLoras": pins })) - } - "set_cost_tier" => { - let tier = action - .args - .get("costTier") - .or_else(|| action.args.get("tier")) - .and_then(|t| t.as_str()) - .unwrap_or("") - .trim() - .to_string(); - if tier.is_empty() { - return action_error(ty, &action.args, "missing costTier (low|medium|high|max)"); - } - { - let mut cfg = state.config.write().await; - let mut prefs = cfg.auto_fallbacks_prefs(); - prefs.cost_tier = tier; - cfg.apply_auto_fallbacks(prefs); - } - let persisted = persist_prefs(state).await; - let mut out = settings_value(state).await; - if let Some(obj) = out.as_object_mut() { - obj.insert("persisted".into(), json!(persisted)); - } - action_ok(ty, &action.args, out) - } - "set_privacy" => { - if let Some(msg) = reject_secret_fields(&action.args) { - return action_error(ty, &action.args, msg); - } - let zdr = action - .args - .get("zeroDataRetention") - .and_then(|v| v.as_bool()); - let data_collection = action - .args - .get("dataCollection") - .and_then(|v| v.as_str()) - .map(str::to_string); - if zdr.is_none() && data_collection.is_none() { - return action_error( - ty, - &action.args, - "provide zeroDataRetention and/or dataCollection (allow|deny)", - ); - } - { - let mut cfg = state.config.write().await; - let mut prefs = cfg.privacy_prefs(); - if let Some(z) = zdr { - prefs.zero_data_retention = z; - } - if let Some(dc) = data_collection { - prefs.data_collection = dc; - } - cfg.apply_privacy(prefs); - } - let persisted = persist_prefs(state).await; - let mut out = settings_value(state).await; - if let Some(obj) = out.as_object_mut() { - obj.insert("persisted".into(), json!(persisted)); - } - action_ok(ty, &action.args, out) - } - "set_alignment" => { - if let Some(msg) = reject_secret_fields(&action.args) { - return action_error(ty, &action.args, msg); - } - let alignment = action - .args - .get("modelAlignment") - .and_then(|v| v.as_str()) - .map(str::to_string); - let nsfw = action - .args - .get("allowNsfwLocal") - .or_else(|| action.args.get("showNsfw")) - .and_then(|v| v.as_bool()); - let tone = action - .args - .get("instructionTone") - .and_then(|v| v.as_str()) - .map(str::to_string); - if alignment.is_none() && nsfw.is_none() && tone.is_none() { - return action_error( - ty, - &action.args, - "provide modelAlignment, allowNsfwLocal, and/or instructionTone", - ); - } - { - let mut cfg = state.config.write().await; - let mut prefs = cfg.alignment_prefs(); - if let Some(a) = alignment { - prefs.model_alignment = a; - } - if let Some(n) = nsfw { - prefs.allow_nsfw_local = n; - } - if let Some(t) = tone { - prefs.instruction_tone = t; - } - cfg.apply_alignment(prefs); - } - let persisted = persist_prefs(state).await; - let mut out = settings_value(state).await; - if let Some(obj) = out.as_object_mut() { - obj.insert("persisted".into(), json!(persisted)); - } - action_ok(ty, &action.args, out) - } - "set_generate_backend" => { - let raw = action - .args - .get("backend") - .and_then(|b| b.as_str()) - .unwrap_or(""); - let backend = match crate::studio::normalize_backend(raw) { - Ok(b) => b, - Err(e) => return action_error(ty, &action.args, e), - }; - { - let mut cfg = state.config.write().await; - cfg.studio.generate_backend = backend.clone(); - } - let persisted = state.persist_secrets().await.is_ok(); - action_ok( - ty, - &action.args, - json!({ "backend": backend, "persisted": persisted }), - ) - } - "set_automation_mode" => { - let raw = action - .args - .get("mode") - .or_else(|| action.args.get("automationMode")) - .and_then(|m| m.as_str()) - .unwrap_or(""); - let mode = match crate::studio::normalize_mode(raw) { - Ok(m) => m, - Err(e) => return action_error(ty, &action.args, e), - }; - { - let mut cfg = state.config.write().await; - cfg.studio.automation_mode = mode.clone(); - } - let persisted = state.persist_secrets().await.is_ok(); - action_ok( - ty, - &action.args, - json!({ "automationMode": mode, "persisted": persisted }), - ) - } - "gallery_delete" => { - let id = action - .args - .get("id") - .and_then(|i| i.as_str()) - .unwrap_or("") - .trim() - .to_string(); - if id.is_empty() { - return action_error(ty, &action.args, "missing id"); - } - match state.gallery.delete(&id).await { - Ok(true) => action_ok(ty, &action.args, json!({ "ok": true, "id": id })), - Ok(false) => action_error(ty, &action.args, "not found"), - Err(e) => action_error(ty, &action.args, e.to_string()), - } - } - "gallery_download" => { - let id = action - .args - .get("id") - .and_then(|i| i.as_str()) - .unwrap_or("") - .trim() - .to_string(); - if id.is_empty() { - return action_error(ty, &action.args, "missing id"); - } - match state.gallery.get(&id).await { - Ok(Some(meta)) => { - let mut item = with_gallery_url(&meta); - if let Some(obj) = item.as_object_mut() { - obj.insert( - "note".into(), - json!("Client downloads this url. Bytes are not returned here."), - ); - } - action_ok(ty, &action.args, item) - } - Ok(None) => action_error(ty, &action.args, "not found"), - Err(e) => action_error(ty, &action.args, e.to_string()), - } - } - "worker_start" => { - let (container, unit) = { - let cfg = state.config.read().await; - ( - cfg.worker_container.clone(), - cfg.worker_systemd_unit.clone(), - ) - }; - match crate::worker_ctl::start(&container, &unit).await { - Ok(runtime) => action_ok( - ty, - &action.args, - json!({ "ok": true, "runtime": runtime.to_json() }), - ), - Err(e) => action_error(ty, &action.args, e), - } - } - "worker_stop" => { - let (container, unit) = { - let cfg = state.config.read().await; - ( - cfg.worker_container.clone(), - cfg.worker_systemd_unit.clone(), - ) - }; - match crate::worker_ctl::stop(&container, &unit).await { - Ok(runtime) => action_ok( - ty, - &action.args, - json!({ "ok": true, "runtime": runtime.to_json() }), - ), - Err(e) => action_error(ty, &action.args, e), - } - } - other => json!({ - "type": other, - "status": "error", - "args": action.args, - "error": format!("unknown action type: {other}") - }), - } -} - -async fn civitai_install_inner( - state: &AppState, - mut req: InstallCivitaiRequest, -) -> ApiResult { - let cfg = state.config.read().await; - if !cfg.civitai_configured() { - return Err(ApiError::Msg( - "Civitai API key required — set it in Settings".into(), - )); - } - drop(cfg); - - // Prefer client URL; otherwise resolve from versionId (+ optional fileId). - if req.download_url.trim().is_empty() { - let version_id = req - .version_id - .ok_or_else(|| ApiError::Msg("downloadUrl or versionId required to install".into()))?; - let civ = state.civitai.read().await; - let resolved = civ - .resolve_version_download(version_id, req.file_id) - .await - .map_err(ApiError::from)?; - req.download_url = resolved.download_url; - if req.version_id.is_none() { - req.version_id = Some(resolved.version_id); - } - if req.file_id.is_none() { - req.file_id = resolved.file_id; - } - if req.base_model.is_none() { - req.base_model = resolved.base_model; - } - if req.model_id.is_none() { - req.model_id = resolved.model_id; - } - if req.thumbnail_url.is_none() { - req.thumbnail_url = resolved.thumbnail_url; - } - } - // Backfill modelId / thumbnail from version when client had a URL but omitted them. - if req.model_id.is_none() || req.thumbnail_url.is_none() { - if let Some(version_id) = req.version_id { - let civ = state.civitai.read().await; - if let Ok(resolved) = civ.resolve_version_download(version_id, req.file_id).await { - if req.model_id.is_none() { - req.model_id = resolved.model_id; - } - if req.base_model.is_none() { - req.base_model = resolved.base_model; - } - if req.thumbnail_url.is_none() { - req.thumbnail_url = resolved.thumbnail_url; - } - } - } - } - if !civitai_download_url_ok(&req.download_url) { - return Err(ApiError::Msg( - "downloadUrl must be an http(s) civitai.com URL".into(), - )); - } - let worker = state.worker.read().await; - let client = worker.as_ref().ok_or(ApiError::NoWorker)?; - - // Reject duplicate dest: already on disk, or an active job targeting the same path. - { - let jobs_v = client.list_install_jobs().await.unwrap_or(Value::Null); - if let Some(arr) = jobs_v.get("data").and_then(|x| x.as_array()) { - for j in arr { - let st = j.get("status").and_then(|x| x.as_str()).unwrap_or(""); - let dp = j - .get("destPath") - .or_else(|| j.get("path")) - .and_then(|x| x.as_str()) - .unwrap_or(""); - if dp == req.dest_path && matches!(st, "queued" | "downloading") { - return Err(ApiError::Msg(format!( - "already downloading to {dp} — wait or cancel the existing job" - ))); - } - } - } - let mut on_disk = client.list_loras().await.unwrap_or_default(); - on_disk.extend(client.list_checkpoints().await.unwrap_or_default()); - if on_disk.iter().any(|a| a.path == req.dest_path) { - return Err(ApiError::Msg(format!( - "already installed at {} — delete it first", - req.dest_path - ))); - } - } - - let auth = { - let cfg = state.config.read().await; - cfg.civitai_api_key.clone() - }; - let url = req.download_url.clone(); - let meta = crate::worker::InstallMeta { - name: req.name.clone(), - base_model: req.base_model.clone(), - version_id: req.version_id, - model_id: req.model_id, - model_type: req.model_type.clone(), - thumbnail_url: req.thumbnail_url.clone(), - }; - let queued = client - .enqueue_install("civitai", &url, &req.dest_path, Some(&auth), Some(&meta)) - .await - .map_err(ApiError::from)?; - let job = queued.get("job").cloned().unwrap_or(Value::Null); - let job_id = queued - .get("jobId") - .and_then(|x| x.as_str()) - .unwrap_or("") - .to_string(); - let status = queued - .get("status") - .and_then(|x| x.as_str()) - .unwrap_or("queued"); - Ok(json!({ - "ok": true, - "queued": true, - "jobId": job_id, - "status": status, - "job": job, - "destPath": req.dest_path, - "name": req.name, - "baseModel": req.base_model, - "versionId": req.version_id, - "modelId": req.model_id, - "fileId": req.file_id, - "modelType": req.model_type, - })) -} - -struct ActionRun { - loras: Vec, - image_model: Option, - video_model: Option, - backend: Option, -} - -impl ActionRun { - async fn exec(&mut self, state: &AppState, action: &PlannedAction) -> Value { - let v = execute_chat_action( - state, - action, - &self.loras, - self.image_model.as_deref(), - self.video_model.as_deref(), - self.backend.as_deref(), - ) - .await; - self.absorb(action, &v); - v - } - - fn absorb(&mut self, action: &PlannedAction, v: &Value) { - if v.get("status").and_then(|s| s.as_str()) != Some("executed") { - return; - } - let ty = v.get("type").and_then(|t| t.as_str()).unwrap_or(""); - let Some(res) = v.get("result") else { - return; - }; - match ty { - "set_chat_models" => { - // The result is the full settings snapshot. Copy a model only - // when this action pinned it, so a chat pin does not replace - // the router-resolved image id with stored Auto. - if action_arg_present(&action.args, "imageModel") { - if let Some(m) = res.get("imageModel").and_then(|m| m.as_str()) { - if !m.is_empty() { - self.image_model = Some(m.to_string()); - } - } - } - if action_arg_present(&action.args, "videoModel") { - let video = res.get("videoModel").and_then(|m| m.as_str()).or_else(|| { - res.get("studio") - .and_then(|s| s.get("videoModel")) - .and_then(|m| m.as_str()) - }); - if let Some(m) = video { - if !m.is_empty() { - self.video_model = Some(m.to_string()); - } - } - } - } - "set_generate_backend" => { - if let Some(b) = res.get("backend").and_then(|b| b.as_str()) { - self.backend = Some(if b == "local" { - "local".into() - } else { - "cloud".into() - }); - } - } - "pin_lora" | "unpin_lora" => { - if let Some(arr) = res.get("pinnedLoras").and_then(|a| a.as_array()) { - self.loras = arr.iter().filter_map(lora_from_pin_value).collect(); - } - } - _ => {} - } - } -} - -fn action_arg_present(args: &Value, key: &str) -> bool { - args.get(key) - .and_then(|v| v.as_str()) - .is_some_and(|s| !s.trim().is_empty()) + } + }; + Json(json!({ + "ok": true, + "openRouter": cfg.openrouter_configured(), + "civitai": cfg.civitai_configured(), + "diffusionWorker": worker_ok, + })) } -fn lora_from_pin_value(v: &Value) -> Option { - if !crate::studio::is_pinnable(v) { - return None; - } - let name = v.get("name").and_then(|n| n.as_str()).unwrap_or("").trim(); - if name.is_empty() { - return None; - } - Some(LoraIn { - name: name.to_string(), - scale: v.get("scale").and_then(|s| s.as_f64()).unwrap_or(0.8) as f32, - path: v.get("path").and_then(|p| p.as_str()).map(str::to_string), - base_model: v - .get("baseModel") - .and_then(|b| b.as_str()) - .map(str::to_string), - }) +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AssistRequest { + pub mode: String, + pub message: String, + #[serde(default)] + pub model: Option, } -pub async fn chat( +pub async fn assist( State(state): State, - Json(mut req): Json, + Json(req): Json, ) -> ApiResult> { - req.loras = session_lora_pins(std::mem::take(&mut req.loras)); - let mode = req - .automation_mode - .as_deref() - .unwrap_or("auto") - .to_lowercase(); - let mode = match mode.as_str() { - "plan" | "auto" | "yolo" => mode, - _ => "auto".into(), - }; - - let hist_blob = if req.messages.is_empty() { - String::new() - } else { - req.messages - .iter() - .rev() - .take(8) - .rev() - .map(|m| format!("{}: {}", m.role, m.content)) - .collect::>() - .join("\n") - }; - - let media_ask = crate::router::direct_media_ask(&req.message); - - // Freya-owned light router (legacy modality alignment: chat / picture / gif / video). - let route_system = load_instruction_raw(&state, "route").await; - let (privacy, alignment, auto_fallbacks, router_cfg) = { - let or = state.openrouter.read().await; - ( - or.privacy().clone(), - or.alignment().clone(), - or.auto_fallbacks().clone(), - or.configured_router_model().to_string(), - ) - }; - let route = { - let or = state.openrouter.read().await; - crate::router::classify_prefs( - &or, - &route_system, - &req.message, - &hist_blob, - &router_cfg, - &privacy, - &alignment, - &auto_fallbacks, - ) + let system = styles::load_instruction(&state.packs_dir, &req.mode).await; + let or = state.openrouter.read().await; + let text = or + .chat(&system, &req.message, req.model.as_deref()) .await - }; - - let resolved_agent = crate::router::resolve_agent_model_prefs( - req.model.as_deref(), - &route, - &privacy, - &alignment, - &auto_fallbacks, - ); - let (configured_image, configured_router) = { - let or = state.openrouter.read().await; - ( - or.configured_image_model().to_string(), - or.configured_router_model().to_string(), - ) - }; - let resolved_router = crate::router::resolve_router_model_prefs( - &configured_router, - &privacy, - &alignment, - &auto_fallbacks, - ); - let resolved_image = crate::router::resolve_image_model_choice_prefs( - req.image_model.as_deref(), - &route, - &configured_image, - &privacy, - &alignment, - &auto_fallbacks, - ); - let video_default = crate::router::resolve_auto_fallback( - crate::router::AutoFallbackKind::Video, - &privacy, - &alignment, - &auto_fallbacks, - ); - let stored_video = { - let cfg = state.config.read().await; - let v = cfg.studio.video_model.trim().to_string(); - if v.is_empty() { - None - } else { - Some(v) - } - }; - let video_pin = req - .video_model - .as_deref() - .map(str::trim) - .filter(|s| !s.is_empty()) - .map(str::to_string) - .or(stored_video); - let resolved_video = crate::router::resolve_video_model_choice_prefs( - video_pin.as_deref(), - &route, - &video_default, - &privacy, - &alignment, - &auto_fallbacks, - ); - - let (mut reply, planned) = if req.confirm && !req.actions.is_empty() { - ( - "Running the confirmed actions.".to_string(), - req.actions - .iter() - .map(|a| PlannedAction { - action_type: a.action_type.clone(), - args: a.args.clone(), - }) - .collect::>(), - ) - } else if !req.confirm - && (route.modality.is_motion() - || matches!( - media_ask, - crate::router::DirectMedia::Gif | crate::router::DirectMedia::Video - )) - { - // Execute gif/video via OpenRouter, or the local worker when backend=local. - let modality = if route.modality.is_motion() { - route.modality.as_str() - } else if matches!(media_ask, crate::router::DirectMedia::Gif) { - "gif" - } else { - "video" - }; - let reply = if mode == "plan" { - format!("Ready to generate {modality} — press Generate to run it.") - } else { - format!( - "Generating {} — {}", - modality, - route.motion_backend_hint().unwrap_or(if modality == "gif" { - "local-gif" - } else { - "openrouter-video" - }) - ) - }; - ( - reply, - vec![PlannedAction { - action_type: "generate_video".into(), - args: json!({ - "prompt": req.message, - "modality": modality, - }), - }], - ) - } else if !req.confirm - && (matches!( - media_ask, - crate::router::DirectMedia::Picture | crate::router::DirectMedia::Series - ) || (route.modality.is_still_image() - && !crate::router::message_is_chat_not_media(&req.message))) - { - if matches!(media_ask, crate::router::DirectMedia::Series) { - let reply = if mode == "plan" { - "Ready to generate a short series — press Generate to run it.".to_string() - } else { - "On it — I’ll make a short series of images.".to_string() - }; - ( - reply, - vec![PlannedAction { - action_type: "run_session".into(), - args: json!({ "goal": req.message }), - }], - ) - } else { - let reply = if mode == "plan" { - "Ready to generate — press Generate to run it.".to_string() - } else { - "On it — I’ll make that image for you.".to_string() - }; - ( - reply, - vec![PlannedAction { - action_type: "generate_image".into(), - args: json!({ "prompt": req.message, "batch": false }), - }], - ) - } - } else { - let mut system = load_instruction_toned(&state, "converse").await; - if alignment.local_adult_passthrough() { - system.push_str(crate::prefs::LOCAL_ADULT_PASSTHROUGH_CLAUSE); - } - let mut user_blob = req.message.clone(); - if !hist_blob.is_empty() { - user_blob = format!( - "{}\n\n--- recent conversation ---\n{}", - req.message, hist_blob - ); - } - if let Some(sess) = &req.session { - user_blob = format!( - "{}\n\n--- session context ---\n{}", - user_blob, - serde_json::to_string_pretty(sess).unwrap_or_default() - ); - } - user_blob = format!( - "{}\n\n--- freya route ---\nmodality={} reason={}\nautomationMode={}", - user_blob, - route.modality.as_str(), - route.reason, - mode - ); - if !req.loras.is_empty() { - let pinned = req - .loras - .iter() - .map(|l| { - format!( - "{}{}", - l.name, - l.base_model - .as_deref() - .map(|b| format!(" ({b})")) - .unwrap_or_default() - ) - }) - .collect::>() - .join(", "); - user_blob = format!("{user_blob}\n\n--- pinned loras ---\n{pinned}"); - } - let or = state.openrouter.read().await; - match or - .chat(&system, &user_blob, resolved_agent.as_deref()) - .await - { - Ok(text) => parse_chat_plan(&text, &req.message), - Err(_) => infer_chat_plan(&req.message), - } - }; - - // Obvious guidance never renders. A scene or outfit does not need - // generate/draw/make — the router or the converse agent decides. - let mut planned: Vec = if req.confirm { - planned - } else { - planned - .into_iter() - .filter(|a| { - if matches!(a.action_type.as_str(), "generate_video") { - true - } else if matches!(a.action_type.as_str(), "generate_image" | "run_session") { - !crate::router::message_is_chat_not_media(&req.message) - } else { - true - } - }) - .collect() - }; - // Local + uncensored / Show NSFW: a refusal or empty tool prompt is not a - // substitute scene. The user's text is what the worker should see. - // That includes an explicit Local pin, Auto GIF, and Auto with pinned LoRAs - // (those still run on the worker). A cloud still does not. - let worker_ready = local_worker_ready(&state).await; - let backend_set = req - .backend - .as_deref() - .map(str::trim) - .filter(|s| !s.is_empty()); - let pinned_local = backend_set.is_some_and(|b| b.eq_ignore_ascii_case("local")); - let auto_backend = backend_set - .map(|b| b.eq_ignore_ascii_case("auto")) - .unwrap_or(true); - let lora_local = auto_backend && worker_ready && !req.loras.is_empty(); - let auto_gif = routes_to_local_worker( - req.backend.as_deref(), - crate::router::Modality::Gif, - worker_ready, - ) && crate::router::direct_media_ask(&req.message) - == crate::router::DirectMedia::Gif; - if alignment.local_adult_passthrough() && (pinned_local || auto_gif || lora_local) { - for action in &mut planned { - restore_refused_local_prompt(action, &req.message); - } - } - - // Prefer router-resolved image model when executing generates under Auto. - let mut env = ActionRun { - loras: req.loras.clone(), - image_model: Some(resolved_image.clone()), - video_model: Some(resolved_video.clone()), - backend: req.backend.clone(), - }; - - let side_effects: Vec<_> = planned - .iter() - .filter(|a| is_side_effect_action(&a.action_type)) - .collect(); - - // Plan mode: propose side effects; still run discovery tools. - let mut pending_confirmation = false; - let mut question: Option = None; - let mut action_results = Vec::new(); - - if mode == "plan" && !req.confirm && !side_effects.is_empty() { - pending_confirmation = true; - for a in &planned { - if is_side_effect_action(&a.action_type) { - action_results.push(json!({ - "type": a.action_type, - "status": "proposed", - "args": a.args, - })); - } else { - action_results.push(env.exec(&state, a).await); - } - } - if reply.is_empty() { - reply = - "Here’s what I’d do — confirm to run generate/install, or keep chatting.".into(); - } - } else if mode == "auto" && !req.confirm { - let install_count = planned - .iter() - .filter(|a| a.action_type == "install_asset") - .count(); - if install_count > 1 { - pending_confirmation = true; - question = Some(json!({ - "kind": "lora", - "text": "Several LoRA installs are queued — which should Freya install?", - })); - for a in &planned { - let status = if a.action_type == "install_asset" { - "proposed" - } else if is_side_effect_action(&a.action_type) { - // Hold generate until installs decided? Prefer propose generate too when installs ambiguous. - "proposed" - } else { - // execute discovery - action_results.push(env.exec(&state, a).await); - continue; - }; - action_results.push(json!({ - "type": a.action_type, - "status": status, - "args": a.args, - })); - } - } else { - for a in &planned { - action_results.push(env.exec(&state, a).await); - } - } - } else { - // YOLO, or confirm, or no side effects in plan with only discovery - for a in &planned { - if mode == "plan" && !req.confirm && is_side_effect_action(&a.action_type) { - action_results.push(json!({ - "type": a.action_type, - "status": "proposed", - "args": a.args, - })); - pending_confirmation = true; - } else { - action_results.push(env.exec(&state, a).await); - } - } - } - - // Aggregate convenience fields for the UI - let mut ideas = Vec::new(); - let mut loras = Vec::new(); - let mut artifacts = Vec::new(); - let mut civitai_query = String::new(); - for ar in &action_results { - if let Some(res) = ar.get("result") { - if let Some(arr) = res.get("ideas").and_then(|i| i.as_array()) { - for x in arr { - if let Some(s) = x.as_str() { - ideas.push(json!(s)); - } - } - } - if let Some(arr) = res.get("loras").and_then(|i| i.as_array()) { - loras.extend(arr.iter().cloned()); - } - if let Some(q) = res.get("query").and_then(|q| q.as_str()) { - civitai_query = q.to_string(); - } - if matches!( - ar.get("type").and_then(|t| t.as_str()), - Some("generate_image" | "generate_video") - ) { - artifacts.push(res.clone()); - } - if let Some(batch) = res.get("results").and_then(|r| r.as_array()) { - artifacts.extend(batch.iter().cloned()); - } - } - } - - // Tool results arrive after the LLM reply — fold worker summaries into reply. - let reply = enrich_reply_with_worker_results(&reply, &action_results); - let effective_backend = env.backend.as_deref().or(req.backend.as_deref()); - let local_backend = effective_backend.is_some_and(|b| b.eq_ignore_ascii_case("local")); - let base_name = if local_backend { - local_base_display(&state).await - } else { - String::new() - }; - let lora_line = if local_backend { - pinned_lora_footer(&env.loras) - } else { - String::new() - }; - let reply = enrich_reply_with_route( - &reply, - &route, - resolved_agent.as_deref(), - &resolved_router, - &resolved_image, - &resolved_video, - &action_results, - effective_backend, - &base_name, - &lora_line, - &mode, - ); - let footer_backend = if local_backend { "local" } else { "cloud" }; - - Ok(Json(json!({ - "reply": reply, - "actions": action_results, - "pendingConfirmation": pending_confirmation, - "question": question, - "ideas": ideas, - "loras": loras, - "civitaiQuery": if civitai_query.is_empty() { Value::Null } else { json!(civitai_query) }, - "artifacts": artifacts, - "automationMode": mode, - "route": route, - "routeContext": { - "backend": footer_backend, - "base": if local_backend { json!(base_name) } else { Value::Null }, - "lora": if local_backend { json!(lora_line) } else { Value::Null }, - "mode": automation_mode_label(&mode), - }, - "resolvedModels": { - "agent": resolved_agent, - "router": resolved_router, - "image": resolved_image, - "video": resolved_video, - }, - }))) -} - -fn pinned_lora_footer(loras: &[LoraIn]) -> String { - let names: Vec<&str> = loras - .iter() - .map(|l| l.name.trim()) - .filter(|s| !s.is_empty()) - .collect(); - if names.is_empty() { - "none".into() - } else { - names.join(", ") - } -} - -fn checkpoint_display_name(path: &str) -> String { - let file = path.rsplit(['/', '\\']).next().unwrap_or(path); - let stem = file - .trim_end_matches(".safetensors") - .trim_end_matches(".ckpt") - .trim_end_matches(".pt"); - if stem.is_empty() { - "none".into() - } else { - stem.replace('_', " ") - } -} - -async fn local_base_display(state: &AppState) -> String { - let worker = state.worker.read().await; - let Some(client) = worker.as_ref() else { - return "none".into(); - }; - let active = match client.get_active_base().await { - Ok(v) => v, - Err(_) => return "none".into(), - }; - let model_path = active - .get("model") - .and_then(|m| m.as_str()) - .unwrap_or("") - .trim() - .to_string(); - let family = active - .get("baseModel") - .and_then(|b| b.as_str()) - .unwrap_or("") - .trim() - .to_string(); - if model_path.is_empty() { - return if family.is_empty() { - "none".into() - } else { - family - }; - } - if let Ok(items) = client.list_checkpoints().await { - if let Some(hit) = items.iter().find(|c| c.path == model_path) { - if let Some(name) = hit.name.as_deref().map(str::trim).filter(|s| !s.is_empty()) { - return name.to_string(); - } - } - } - checkpoint_display_name(&model_path) + .map_err(ApiError::from)?; + Ok(Json(json!({ "mode": req.mode, "text": text }))) } #[derive(Debug, Deserialize)] @@ -3519,12 +71,6 @@ pub struct GenerateRequest { pub size: Option, #[serde(default)] pub seed: Option, - /// `picture` | `gif` | `video` — omit to infer from prompt. - #[serde(default)] - pub modality: Option, - /// Video duration seconds (OpenRouter), when supported. - #[serde(default)] - pub duration: Option, } #[derive(Debug, Deserialize, Serialize, Clone)] @@ -3533,33 +79,12 @@ pub struct LoraIn { pub name: String, #[serde(default = "one")] pub scale: f32, - /// Relative path on the worker (`loras/foo.safetensors`) when known. - #[serde(default)] - pub path: Option, - /// Civitai base family (SDXL 1.0, Pony, …) — used to pick a checkpoint. - #[serde(default)] - pub base_model: Option, } fn one() -> f32 { 1.0 } -/// Session pins are LoRA/adapter paths only — never treat checkpoints/VAE as LoRAs. -fn session_lora_pins(loras: Vec) -> Vec { - loras - .into_iter() - .filter(|l| { - let path = l.path.as_deref().unwrap_or("").to_ascii_lowercase(); - if path.starts_with("checkpoints/") || path.starts_with("vae/") { - return false; - } - let name = l.name.to_ascii_lowercase(); - !(name.contains("checkpoint") && path.is_empty()) - }) - .collect() -} - pub async fn generate( State(state): State, Json(req): Json, @@ -3567,89 +92,13 @@ pub async fn generate( run_generate(&state, req).await.map(Json) } -#[derive(Debug, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct SeriesRequest { - pub goal: String, - #[serde(default)] - pub style_ref: Option, - #[serde(default)] - pub backend: Option, - #[serde(default)] - pub loras: Vec, -} - -/// Short still series — same planner as the chat `run_session` action. -pub async fn generate_series( - State(state): State, - Json(req): Json, -) -> ApiResult> { - let goal = req.goal.trim(); - if goal.is_empty() { - return Err(ApiError::Msg("missing goal".into())); - } - let image = state.config.read().await.image_model.clone(); - let action = PlannedAction { - action_type: "run_session".into(), - args: json!({ - "goal": goal, - "styleRef": req.style_ref, - }), - }; - let pins = session_lora_pins(req.loras); - let v = execute_chat_action( - &state, - &action, - &pins, - Some(image.as_str()), - None, - req.backend.as_deref(), - ) - .await; - if v.get("status").and_then(|s| s.as_str()) == Some("error") { - let msg = v - .get("error") - .and_then(|e| e.as_str()) - .unwrap_or("series generation failed"); - return Err(ApiError::Msg(msg.to_string())); - } - Ok(Json(v)) -} - pub async fn run( State(state): State, Json(mut req): Json, ) -> ApiResult> { - let route_system = load_instruction_raw(&state, "route").await; - let (route, configured_image, privacy, alignment, auto_fallbacks) = { - let or = state.openrouter.read().await; - let router_cfg = or.configured_router_model().to_string(); - let configured_image = or.configured_image_model().to_string(); - let privacy = or.privacy().clone(); - let alignment = or.alignment().clone(); - let auto_fallbacks = or.auto_fallbacks().clone(); - let route = crate::router::classify_prefs( - &or, - &route_system, - &req.prompt, - "", - &router_cfg, - &privacy, - &alignment, - &auto_fallbacks, - ) - .await; - (route, configured_image, privacy, alignment, auto_fallbacks) - }; - if req.modality.is_none() && route.modality.is_motion() { - req.modality = Some(route.modality.as_str().into()); - } - - // Auto-plan when backend/model unset — still respect Freya router for image model. - // Skip cloud model fill when the client already pinned Local (use worker active base). - let pinned_local = req.backend.as_deref() == Some("local"); + // Auto-plan when backend/model unset. if req.backend.as_deref().unwrap_or("auto") == "auto" && req.model.is_none() { - let system = load_instruction_toned(&state, "plan").await; + let system = styles::load_instruction(&state.packs_dir, "plan").await; let or = state.openrouter.read().await; if let Ok(plan_txt) = or.chat(&system, &req.prompt, None).await { if let Ok(plan) = serde_json::from_str::( @@ -3664,23 +113,7 @@ pub async fn run( req.backend = Some(b.into()); } if let Some(m) = plan.get("model").and_then(|x| x.as_str()) { - let default_image = crate::router::resolve_image_model_choice_prefs( - None, - &route, - &configured_image, - &privacy, - &alignment, - &auto_fallbacks, - ); - let resolved = crate::openrouter::resolve_image_model(m, &default_image); - if resolved != m { - tracing::debug!( - planner_model = %m, - resolved = %resolved, - "ignored non-image planner model" - ); - } - req.model = Some(resolved); + req.model = Some(m.into()); } if let Some(s) = plan.get("styleId").and_then(|x| x.as_str()) { req.style_ref = Some(s.into()); @@ -3693,23 +126,10 @@ pub async fn run( } } } - // Local + Auto: leave model unset so run_generate uses the worker active checkpoint. - // OpenRouter path still needs a concrete image model id. - if req.model.is_none() && !pinned_local && req.backend.as_deref() != Some("local") { - req.model = Some(crate::router::resolve_image_model_choice_prefs( - None, - &route, - &configured_image, - &privacy, - &alignment, - &auto_fallbacks, - )); - } run_generate(&state, req).await.map(Json) } async fn run_generate(state: &AppState, mut req: GenerateRequest) -> ApiResult { - req.loras = session_lora_pins(std::mem::take(&mut req.loras)); let styles = styles::load_styles(&state.packs_dir) .await .unwrap_or_default(); @@ -3735,8 +155,6 @@ async fn run_generate(state: &AppState, mut req: GenerateRequest) -> ApiResult ApiResult Some(text), - Err(e) => { - tracing::debug!(error = %e, "prompt rewrite failed"); - None - } - }; - if let Some(p) = &path { - tracing::info!(adult = p.adult, model = %p.model, "local prompt-sd writer"); - if p.adult { - let accepted = rewritten - .as_deref() - .map(normalize_sd_rewrite) - .filter(|t| adult_rewrite_ok(t, &req.prompt)); - if let Some(text) = accepted { - final_prompt = text.clone(); - enhanced = Some(text); - } else if let Some(retry_model) = - adult_retry_model(&p.model, &privacy, &auto_fallbacks) - { - tracing::info!( - first = %p.model, - retry = %retry_model, - "local adult prompt rewrite retry" - ); - let retry = or.chat(&system, &req.prompt, Some(&retry_model)).await.ok(); - if let Some(text) = retry - .as_deref() - .map(normalize_sd_rewrite) - .filter(|t| adult_rewrite_ok(t, &req.prompt)) - { - final_prompt = text.clone(); - enhanced = Some(text); - } else { - // A failed or refused rewrite must not abort the generate. - // The worker still receives the user's scene. - tracing::warn!( - first = %p.model, - retry = %retry_model, - "local adult prompt rewrite unusable; using the original scene" - ); - } - } else { - tracing::warn!( - model = %p.model, - "local adult prompt rewrite unusable; using the original scene" - ); - } - } else if let Some(text) = rewritten.as_deref().map(normalize_sd_rewrite) { - if !text.is_empty() && !looks_like_model_refusal(&text) { - final_prompt = text.clone(); - enhanced = Some(text); - } - } - } else if let Some(text) = rewritten { + if let Ok(text) = or.chat(&system, &req.prompt, None).await { enhanced = Some(text.clone()); final_prompt = text; } } - let modality = resolve_generate_modality(&req); - let (bytes, mime, model_used, backend_used) = if modality.is_motion() { - run_motion_generate(state, &req, &final_prompt, modality).await? - } else if backend == "local" { + let (bytes, mime, model_used, backend_used) = if backend == "local" { let worker = state.worker.read().await; let client = worker.as_ref().ok_or(ApiError::NoWorker)?; - // Prefer installed basename for lora_request so it matches on-disk files. let loras: Vec = req .loras .iter() - .map(|l| { - let lora_name = l - .path - .as_deref() - .and_then(|p| std::path::Path::new(p).file_stem()) - .and_then(|s| s.to_str()) - .filter(|s| !s.is_empty()) - .unwrap_or(l.name.as_str()) - .to_string(); - LoraWeight { - lora_name, - lora_scale: l.scale, - } + .map(|l| LoraWeight { + lora_name: l.name.clone(), + lora_scale: l.scale, }) .collect(); - // Resolve base checkpoint: explicit local path → worker active → LoRA baseModel hint. - // Never forward Auto / OpenRouter cloud ids / router prose as Diffusers repo ids. - let mut model = crate::base_models::filter_local_model(req.model.as_deref()); - if model.is_none() { - if let Some(raw) = req - .model - .as_deref() - .map(str::trim) - .filter(|s| !s.is_empty()) - { - tracing::debug!( - ignored_model = %raw, - "local generate ignored non-checkpoint model; using worker active base" - ); - } - } - let mut active_base_label: Option = None; - if let Ok(active) = client.get_active_base().await { - active_base_label = active - .get("baseModel") - .and_then(|x| x.as_str()) - .map(str::to_string); - if model.is_none() { - if let Some(m) = active.get("model").and_then(|x| x.as_str()) { - if !m.is_empty() { - model = Some(m.to_string()); - } - } - } - } - if model.is_none() { - let hints: Vec<_> = req - .loras - .iter() - .map(|l| crate::base_models::LoraBaseHint { - base_model: l.base_model.clone(), - }) - .collect(); - model = crate::base_models::resolve_model_from_loras(&hints); - } - if let (Some(active_b), Some(lora_b)) = ( - active_base_label.as_deref(), - req.loras.iter().find_map(|l| l.base_model.as_deref()), - ) { - if !crate::base_models::bases_compatible(active_b, lora_b) { - tracing::warn!( - active = %active_b, - lora_base = %lora_b, - "active worker base may not match pinned LoRA baseModel" - ); - } - } let bytes = client .generate( &final_prompt, - model.as_deref(), + req.model.as_deref(), &loras, req.size.as_deref(), req.seed, @@ -3954,21 +211,13 @@ async fn run_generate(state: &AppState, mut req: GenerateRequest) -> ApiResult ApiResult ApiResult bool { - state.worker.read().await.is_some() -} - -/// Local stills when the composer pinned Local. Auto GIF uses the worker when one is up. -/// Cloud video and omitted-backend stills stay on OpenRouter. -fn routes_to_local_worker( - backend: Option<&str>, - modality: crate::router::Modality, - worker_ready: bool, -) -> bool { - let pinned = backend.map(str::trim).filter(|s| !s.is_empty()); - match pinned { - Some(s) if s.eq_ignore_ascii_case("local") => true, - Some(s) if s.eq_ignore_ascii_case("auto") => { - worker_ready && modality == crate::router::Modality::Gif - } - None => worker_ready && modality == crate::router::Modality::Gif, - _ => false, - } -} - -fn resolve_generate_modality(req: &GenerateRequest) -> crate::router::Modality { - if let Some(m) = req - .modality - .as_deref() - .and_then(crate::router::Modality::parse) - { - return m; - } - crate::router::infer_modality(&req.prompt).modality -} - -async fn run_motion_generate( - state: &AppState, - req: &GenerateRequest, - final_prompt: &str, - modality: crate::router::Modality, -) -> ApiResult<(Vec, String, String, String)> { - let want_gif = matches!(modality, crate::router::Modality::Gif); - let backend = req.backend.as_deref().unwrap_or("auto"); - let pinned_local = backend == "local"; - - // Local motion is a worker GIF (the engine has no mp4 T2V). Cloud video stays on OpenRouter. - // Do not fall through to OpenRouter when the composer pinned Local. - if pinned_local || (want_gif && backend == "auto") { - let worker = state.worker.read().await; - if let Some(client) = worker.as_ref() { - let gif_model = crate::base_models::filter_local_model(req.model.as_deref()); - match client - .generate_gif( - final_prompt, - gif_model.as_deref(), - req.size.as_deref(), - req.seed, - req.negative_prompt.as_deref(), - ) - .await - { - Ok(bytes) => { - return Ok(( - bytes, - "image/gif".into(), - gif_model.unwrap_or_else(|| "local-gif".into()), - "local".into(), - )); - } - Err(e) => { - if pinned_local { - return Err(ApiError::Msg(format!( - "local worker motion failed (GIF is the local video path): {e}" - ))); - } - tracing::warn!(error = %e, "local gif failed; falling back to OpenRouter video"); - } - } - } else if pinned_local { - return Err(ApiError::NoWorker); - } - } - - let or = state.openrouter.read().await; - let privacy = or.privacy().clone(); - let alignment = or.alignment().clone(); - let auto_fallbacks = or.auto_fallbacks().clone(); - let video_default = crate::router::resolve_auto_fallback( - crate::router::AutoFallbackKind::Video, - &privacy, - &alignment, - &auto_fallbacks, - ); - let model = crate::router::resolve_video_model_choice_prefs( - req.model.as_deref(), - &crate::router::RouteDecision { - modality, - reason: String::new(), - agent_model: None, - image_model: None, - source: "generate".into(), - }, - &video_default, - &privacy, - &alignment, - &auto_fallbacks, - ); - let duration = req.duration.or(if want_gif { Some(4) } else { Some(5) }); - let aspect = req.size.as_deref().and_then(size_to_video_aspect); - let vid = or - .generate_video(final_prompt, Some(&model), duration, aspect) - .await - .map_err(ApiError::from)?; - let (bytes, mime) = if want_gif { - match mp4_to_gif(&vid.bytes).await { - Ok(gif) => (gif, "image/gif".into()), - Err(e) => { - tracing::warn!(error = %e, "gif convert failed; serving mp4"); - (vid.bytes, vid.mime) - } - } - } else { - (vid.bytes, vid.mime) - }; - Ok((bytes, mime, vid.model, "openrouter".into())) -} - -fn size_to_video_aspect(size: &str) -> Option<&'static str> { - let s = size.to_ascii_lowercase(); - if s.contains("1024x1792") || s.contains("9:16") || s.contains("576x1024") { - Some("9:16") - } else if s.contains("1792x1024") || s.contains("16:9") || s.contains("1280x720") { - Some("16:9") - } else if s.contains("1024x1024") || s.contains("1:1") { - Some("1:1") - } else { - None - } -} - -async fn mp4_to_gif(mp4: &[u8]) -> Result, String> { - let id = uuid::Uuid::new_v4(); - let dir = std::env::temp_dir().join(format!("freya-gif-{id}")); - tokio::fs::create_dir_all(&dir) - .await - .map_err(|e| e.to_string())?; - let in_path = dir.join("in.mp4"); - let out_path = dir.join("out.gif"); - let result = async { - tokio::fs::write(&in_path, mp4) - .await - .map_err(|e| e.to_string())?; - let status = tokio::process::Command::new("ffmpeg") - .args([ - "-y", - "-i", - in_path.to_str().unwrap_or("in.mp4"), - "-vf", - "fps=8,scale=512:-1:flags=lanczos", - "-loop", - "0", - out_path.to_str().unwrap_or("out.gif"), - ]) - .output() - .await - .map_err(|e| format!("ffmpeg: {e}"))?; - if !status.status.success() { - return Err(format!( - "ffmpeg exit {}: {}", - status.status, - String::from_utf8_lossy(&status.stderr) - )); - } - tokio::fs::read(&out_path).await.map_err(|e| e.to_string()) - } - .await; - let _ = tokio::fs::remove_dir_all(&dir).await; - result + .await + .map_err(ApiError::from)?; + + Ok(json!({ + "artifactId": saved.id, + "backend": backend_used, + "model": model_used, + "enhancedPrompt": enhanced, + "url": format!("/v1/gallery/{}/image", saved.id), + "meta": saved, + })) } pub async fn gallery_list(State(state): State) -> ApiResult> { let items = state.gallery.list().await.map_err(ApiError::from)?; - let items: Vec = items.iter().map(with_gallery_url).collect(); Ok(Json(json!({ "items": items }))) } pub async fn gallery_get( State(state): State, Path(id): Path, -) -> ApiResult> { +) -> ApiResult> { let meta = state .gallery .get(&id) .await .map_err(ApiError::from)? .ok_or(ApiError::NotFound)?; - Ok(Json(with_gallery_url(&meta))) -} - -pub async fn gallery_delete( - State(state): State, - Path(id): Path, -) -> ApiResult> { - let removed = state.gallery.delete(&id).await.map_err(ApiError::from)?; - if !removed { - return Err(ApiError::NotFound); - } - Ok(Json(json!({ "ok": true, "id": id }))) + Ok(Json(meta)) } pub async fn gallery_image( @@ -4234,7 +292,11 @@ pub async fn gallery_image( let bytes = tokio::fs::read(state.gallery.image_path(&meta)) .await .map_err(ApiError::from)?; - let ct = crate::gallery::content_type_for_mime(&meta.mime); + let ct = if meta.mime.contains("jpeg") { + "image/jpeg" + } else { + "image/png" + }; Ok(([(axum::http::header::CONTENT_TYPE, ct)], bytes).into_response()) } @@ -4249,9 +311,7 @@ pub async fn gallery_remix( .map_err(ApiError::from)? .ok_or(ApiError::NotFound)?; Ok(Json(json!({ - // Prefer the user's natural-language prompt for remix; model brief is secondary - "prompt": meta.prompt.clone(), - "enhancedPrompt": meta.enhanced_prompt, + "prompt": meta.enhanced_prompt.clone().unwrap_or(meta.prompt.clone()), "backend": meta.backend, "model": meta.model, "styleRef": meta.style_ref, @@ -4259,114 +319,29 @@ pub async fn gallery_remix( }))) } -async fn models_payload(state: &AppState) -> ApiResult { - let (allow_nsfw, chat_providers) = { - let cfg = state.config.read().await; - ( - cfg.alignment_prefs().allow_nsfw_local, - cfg.privacy_prefs().chat_providers, - ) - }; +pub async fn models(State(state): State) -> ApiResult> { let or = state.openrouter.read().await; let mut cloud = or.list_image_models().await.unwrap_or_default(); - let chat_catalog = or.list_chat_catalog().await.unwrap_or_default(); - let mut chat = chat_catalog.models; - let mut router_models = chat_catalog.router; - let chat_available = chat_catalog.available; - let mut video = or.list_video_models().await.unwrap_or_default(); - // Consistent picker order: vendor (id prefix before `/`) → name → id. - crate::openrouter::sort_models_by_vendor_name(&mut cloud); - crate::openrouter::sort_models_by_vendor_name(&mut chat); - crate::openrouter::sort_models_by_vendor_name(&mut router_models); - crate::openrouter::sort_video_models_by_vendor_name(&mut video); let mut local = Vec::new(); - let mut active_base = Value::Null; if let Some(w) = state.worker.read().await.as_ref() { if let Ok(loras) = w.list_loras().await { for a in loras { - let name = a.name.clone().unwrap_or_else(|| a.id.clone()); - if !allow_nsfw - && (looks_nsfw_label(&a.id) - || looks_nsfw_label(&name) - || looks_nsfw_label(&a.path)) - { - continue; - } local.push(json!({ "id": a.id, - "name": name, + "name": a.id, "backend": "local", "kind": a.kind, "path": a.path, - "baseModel": a.base_model, - "sizeBytes": a.size_bytes, - "modelType": a.model_type, - })); - } - } - if let Ok(cps) = w.list_checkpoints().await { - for a in cps { - let name = a.name.clone().unwrap_or_else(|| a.id.clone()); - if !allow_nsfw - && (looks_nsfw_label(&a.id) - || looks_nsfw_label(&name) - || looks_nsfw_label(&a.path)) - { - continue; - } - local.push(json!({ - "id": a.id, - "name": name, - "backend": "local", - "kind": "checkpoint", - "path": a.path, - "baseModel": a.base_model, - "sizeBytes": a.size_bytes, - "modelType": a.model_type, })); } } - if let Ok(v) = w.get_active_base().await { - active_base = v; - } } - Ok(json!({ - // Image-capable cloud models (OpenRouter GET /images/models). + Ok(Json(json!({ "openrouter": cloud.drain(..).map(|m| json!({ - "id": m.id, "name": m.name, "backend": m.backend, "modality": "image" - })).collect::>(), - // Tool-calling text models for the Agent picker. - "chat": chat.drain(..).map(|m| json!({ - "id": m.id, "name": m.name, "backend": m.backend, "modality": "chat" - })).collect::>(), - // Structured-JSON / tool-calling text models for the Router picker. - "router": router_models.drain(..).map(|m| json!({ - "id": m.id, "name": m.name, "backend": m.backend, "modality": "chat" - })).collect::>(), - // Video: OpenRouter async POST /videos (+ poll). Freya generate/chat routes gif|video here. - "video": video.drain(..).map(|m| json!({ - "id": m.id, - "name": m.name, - "backend": "openrouter", - "modality": "video", - "supportedDurations": m.supported_durations, - "supportedResolutions": m.supported_resolutions, - "supportedAspectRatios": m.supported_aspect_ratios, + "id": m.id, "name": m.name, "backend": m.backend })).collect::>(), "local": local, - "activeBase": active_base, - "baseModelCatalog": crate::base_models::catalog(), - // Vendor prefixes from denylist-passing chat catalog + current checkbox prefs. - "chatProviders": { - "available": chat_available, - "excluded": chat_providers.excluded, - "legacyOnly": chat_providers.legacy_only, - }, - })) -} - -pub async fn models(State(state): State) -> ApiResult> { - models_payload(&state).await.map(Json) + }))) } pub async fn styles_list(State(state): State) -> ApiResult> { @@ -4381,140 +356,28 @@ pub struct CivitaiSearchQuery { pub q: String, #[serde(default = "default_limit")] pub limit: u32, - /// Optional comma-separated Civitai ModelTypes (e.g. `LORA,Checkpoint,VAE`). - /// Empty / omitted → Freya defaults (adapters, checkpoints, embeddings, VAE). - #[serde(default)] - pub types: Option, } fn default_limit() -> u32 { 20 } -fn parse_civitai_types(raw: Option<&str>) -> Vec { - let owned: Vec = raw - .unwrap_or("") - .split(',') - .map(str::trim) - .filter(|s| !s.is_empty()) - .map(str::to_string) - .collect(); - if owned.is_empty() { - crate::civitai::DEFAULT_SEARCH_TYPES - .iter() - .map(|s| (*s).to_string()) - .collect() - } else { - owned - } -} - pub async fn civitai_search( State(state): State, Query(q): Query, ) -> ApiResult> { - let allow_nsfw = { - let cfg = state.config.read().await; - cfg.alignment_prefs().allow_nsfw_local - }; let civ = state.civitai.read().await; - let types = parse_civitai_types(q.types.as_deref()); - let type_refs: Vec<&str> = types.iter().map(String::as_str).collect(); - let mut items = civ - .search_types(&q.q, q.limit, &type_refs) - .await - .map_err(ApiError::from)?; - if !allow_nsfw { - items.retain(|c| !looks_nsfw_label(&c.name) && !c.nsfw); - } + let items = civ.search(&q.q, q.limit).await.map_err(ApiError::from)?; Ok(Json(json!({ "items": items }))) } -fn civitai_detail_response(detail: crate::civitai::CivitaiModelDetail) -> Json { - // Nested shape for the UI modal: { model, related: [{ model, note }] }. - let related: Vec<_> = detail - .related - .iter() - .map(|r| { - json!({ - "relation": "compatible_checkpoint", - "note": detail.base_model.as_ref().map(|b| format!("Popular checkpoint for {b}")), - "model": r, - }) - }) - .collect(); - let mut model = serde_json::to_value(&detail).unwrap_or(json!({})); - if let Some(obj) = model.as_object_mut() { - // Keep related nested under the response envelope, not duplicated on model. - obj.remove("related"); - } - Json(json!({ "model": model, "related": related })) -} - -/// Full Civitai model detail + related compatible checkpoints (when applicable). -pub async fn civitai_model( - State(state): State, - axum::extract::Path(id): axum::extract::Path, -) -> ApiResult> { - let civ = state.civitai.read().await; - let detail = civ.get_model(id).await.map_err(ApiError::from)?; - Ok(civitai_detail_response(detail)) -} - -/// Resolve Installed assets that only stored `versionId` (no `modelId` in sidecar meta). -pub async fn civitai_model_version( - State(state): State, - axum::extract::Path(version_id): axum::extract::Path, -) -> ApiResult> { - let civ = state.civitai.read().await; - let detail = civ - .get_model_by_version(version_id) - .await - .map_err(ApiError::from)?; - Ok(civitai_detail_response(detail)) -} - #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase")] pub struct InstallCivitaiRequest { - /// Direct Civitai download URL. Optional when `versionId` is set (resolved server-side). - #[serde(default)] pub download_url: String, pub dest_path: String, #[serde(default)] pub name: Option, - /// Civitai base family — stored beside the weight for LoRA→checkpoint selection. - #[serde(default)] - pub base_model: Option, - #[serde(default)] - pub version_id: Option, - /// Civitai model id — stored in sidecar meta for Installed → detail. - #[serde(default)] - pub model_id: Option, - #[serde(default)] - pub file_id: Option, - #[serde(default)] - pub model_type: Option, - /// Preview URL persisted in sidecar for Installed card thumbs. - #[serde(default)] - pub thumbnail_url: Option, -} - -/// Allowlist Civitai hosts before attaching the API token (never send token to untrusted URLs). -fn civitai_download_url_ok(url: &str) -> bool { - let Ok(parsed) = reqwest::Url::parse(url) else { - return false; - }; - if !matches!(parsed.scheme(), "https" | "http") { - return false; - } - match parsed.host_str() { - Some(h) => { - h.eq_ignore_ascii_case("civitai.com") - || h.to_ascii_lowercase().ends_with(".civitai.com") - } - None => false, - } } /// Install a Civitai download onto the configured diffusion worker (remote or in-cluster URL). @@ -4522,407 +385,55 @@ pub async fn civitai_install( State(state): State, Json(req): Json, ) -> ApiResult> { - civitai_install_inner(&state, req).await.map(Json) -} - -#[derive(Debug, Clone, Serialize)] -#[serde(rename_all = "camelCase")] -pub struct InstructionSetting { - pub id: String, - pub label: String, - /// Effective text (override if set, else pack/builtin default). - pub text: String, - /// Pack / builtin default (for Reset UI). - pub default_text: String, - pub overridden: bool, + let cfg = state.config.read().await; + if !cfg.civitai_configured() { + return Err(ApiError::Msg( + "Civitai API key required — set it in Settings".into(), + )); + } + let worker = state.worker.read().await; + let client = worker.as_ref().ok_or(ApiError::NoWorker)?; + // Prefer authenticated Civitai URL; worker performs the fetch with Freya-provided source tag. + let url = if req.download_url.contains('?') { + format!("{}&token={}", req.download_url, cfg.civitai_api_key) + } else { + format!("{}?token={}", req.download_url, cfg.civitai_api_key) + }; + drop(cfg); + client + .install_asset("civitai", &url, &req.dest_path) + .await + .map_err(ApiError::from)?; + Ok(Json(json!({ + "ok": true, + "destPath": req.dest_path, + "name": req.name, + }))) } -#[derive(Debug, Clone, Serialize)] +#[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct SettingsPublic { pub open_router_configured: bool, pub civitai_configured: bool, pub hf_configured: bool, pub diffusion_worker_url: Option, - /// Agent model (`auto` = internal Auto; `openrouter/auto` is the explicit upstream router). pub chat_model: String, - /// Image model (`auto` = Auto → Flux NL default). pub image_model: String, - /// Freya intent router model (`auto` = Llama 3.1 8B-class). - pub router_model: String, - /// Whether `FREYA_API_TOKEN` / rotated runtime token is set (never returns the value). - pub api_token_configured: bool, - /// Whether operator admin login (`FREYA_ADMIN_PASSWORD`) is configured. - pub admin_login_configured: bool, - /// True when bearer and/or admin password is required for `/v1`. - pub auth_required: bool, - /// OpenRouter privacy (ZDR / data_collection) + Freya chat-provider checkboxes. - pub privacy: PrivacyPrefs, - /// Freya-side model catalog / tone prefs (not OpenRouter API flags). - pub alignment: AlignmentPrefs, - /// Configurable Auto fallbacks when the router does not pin a concrete model. - pub auto_fallbacks: AutoFallbacksPrefs, - /// Editable system prompts (packs defaults + Settings overrides). - pub instructions: Vec, - /// Favorites, LoRA pins, composer backend, video pin. No secrets. - pub studio: crate::studio::StudioPrefs, -} - -#[derive(Debug, Serialize)] -#[serde(rename_all = "camelCase")] -pub struct SettingsPutResponse { - #[serde(flatten)] - pub settings: SettingsPublic, - /// Whether the secrets snapshot was written to `FREYA_SECRETS_FILE`. - pub persisted: bool, -} - -async fn settings_public_from_state(state: &AppState) -> SettingsPublic { - let (base, overrides) = { - let cfg = state.config.read().await; - ( - SettingsPublic { - open_router_configured: cfg.openrouter_configured(), - civitai_configured: cfg.civitai_configured(), - hf_configured: !cfg.hf_token.is_empty(), - diffusion_worker_url: cfg.diffusion_worker_url.clone(), - chat_model: cfg.chat_model.clone(), - image_model: cfg.image_model.clone(), - router_model: cfg.router_model.clone(), - api_token_configured: !cfg.api_token.trim().is_empty(), - admin_login_configured: cfg.admin_login_configured(), - auth_required: cfg.auth_required(), - privacy: cfg.privacy_prefs(), - alignment: cfg.alignment_prefs(), - auto_fallbacks: cfg.auto_fallbacks_prefs(), - instructions: Vec::new(), - studio: cfg.studio.clone(), - }, - cfg.instruction_overrides.clone(), - ) - }; - let mut instructions = Vec::with_capacity(styles::EDITABLE_INSTRUCTION_MODES.len()); - for id in styles::EDITABLE_INSTRUCTION_MODES { - let default_text = styles::load_instruction_default(&state.packs_dir, id).await; - let overridden = overrides - .get(*id) - .map(|t| !t.trim().is_empty()) - .unwrap_or(false); - let text = if overridden { - overrides - .get(*id) - .cloned() - .unwrap_or_else(|| default_text.clone()) - } else { - default_text.clone() - }; - instructions.push(InstructionSetting { - id: (*id).to_string(), - label: styles::instruction_mode_label(id), - text, - default_text, - overridden, - }); - } - SettingsPublic { - instructions, - ..base - } -} - -async fn load_instruction_toned(state: &AppState, mode: &str) -> String { - let (tone, overrides) = { - let cfg = state.config.read().await; - (cfg.alignment_prefs(), cfg.instruction_overrides.clone()) - }; - let raw = styles::load_instruction(&state.packs_dir, mode, Some(&overrides)).await; - tone.apply_tone(&raw) -} - -async fn load_instruction_raw(state: &AppState, mode: &str) -> String { - let overrides = { - let cfg = state.config.read().await; - cfg.instruction_overrides.clone() - }; - styles::load_instruction(&state.packs_dir, mode, Some(&overrides)).await -} - -/// Public auth probe — no bearer required. Used by the UI to show Sign in / locked state. -#[derive(Debug, Serialize)] -#[serde(rename_all = "camelCase")] -pub struct AuthStatusResponse { - pub auth_required: bool, - pub admin_login_configured: bool, - pub api_token_configured: bool, - pub open_router_configured: bool, - pub admin_username: String, - pub note: String, } -pub async fn auth_status(State(state): State) -> Json { +pub async fn settings_get(State(state): State) -> Json { let cfg = state.config.read().await; - let admin_login = cfg.admin_login_configured(); - let note = if !cfg.auth_required() { - "API open (local/dev).".into() - } else if admin_login { - "Sign in required.".into() - } else { - "API token required.".into() - }; - Json(AuthStatusResponse { - auth_required: cfg.auth_required(), - admin_login_configured: admin_login, - api_token_configured: !cfg.api_token.trim().is_empty(), + Json(SettingsPublic { open_router_configured: cfg.openrouter_configured(), - admin_username: if cfg.admin_user.trim().is_empty() { - "admin".into() - } else { - cfg.admin_user.clone() - }, - note, - }) -} - -#[derive(Debug, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct AuthLoginRequest { - pub username: String, - pub password: String, -} - -#[derive(Debug, Serialize)] -#[serde(rename_all = "camelCase")] -pub struct AuthLoginResponse { - pub token: String, - pub username: String, - pub note: String, -} - -/// Exchange admin username/password for a browser session token. -pub async fn auth_login( - State(state): State, - Json(req): Json, -) -> ApiResult> { - let (admin_user, admin_password, mut token) = { - let cfg = state.config.read().await; - ( - if cfg.admin_user.trim().is_empty() { - "admin".to_string() - } else { - cfg.admin_user.trim().to_string() - }, - cfg.admin_password.trim().to_string(), - cfg.api_token.trim().to_string(), - ) - }; - if admin_password.is_empty() { - return Err(ApiError::Unavailable( - "Admin login is not configured on this Studio".into(), - )); - } - let user_ok = const_eq_str(req.username.trim(), &admin_user); - let pass_ok = const_eq_str(req.password.trim(), &admin_password); - if !user_ok || !pass_ok { - return Err(ApiError::Unauthorized( - "Invalid username or password".into(), - )); - } - if token.is_empty() { - // No machine bearer yet — mint one so the UI can stay on Bearer after login. - token = generate_api_token(); - { - let mut cfg = state.config.write().await; - cfg.api_token = token.clone(); - } - let _ = state.persist_secrets().await; - let _ = crate::k8s_secret::try_sync_api_token_secret(&token).await; - } - Ok(Json(AuthLoginResponse { - token, - username: admin_user, - note: "Signed in.".into(), - })) -} - -fn const_eq_str(a: &str, b: &str) -> bool { - if a.len() != b.len() { - return false; - } - a.bytes() - .zip(b.bytes()) - .fold(0u8, |acc, (x, y)| acc | (x ^ y)) - == 0 -} - -pub async fn settings_get(State(state): State) -> Json { - Json(settings_public_from_state(&state).await) -} - -pub async fn studio_get(State(state): State) -> Json { - Json(state.config.read().await.studio.clone()) -} - -pub async fn studio_put( - State(state): State, - Json(patch): Json, -) -> ApiResult> { - { - let mut cfg = state.config.write().await; - crate::studio::apply_patch(&mut cfg.studio, patch).map_err(ApiError::Msg)?; - } - let persisted = state.persist_secrets().await.is_ok(); - let studio = state.config.read().await.studio.clone(); - Ok(Json(json!({ "studio": studio, "persisted": persisted }))) -} - -/// OpenRouter usage / credits snapshot for the Metrics UI. -#[derive(Debug, Serialize)] -#[serde(rename_all = "camelCase")] -pub struct OpenRouterMetricsResponse { - pub configured: bool, - #[serde(skip_serializing_if = "Option::is_none")] - pub key: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub key_error: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub credits: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub credits_error: Option, - pub notes: Vec, -} - -async fn openrouter_metrics_payload(state: &AppState) -> ApiResult { - let configured = { - let cfg = state.config.read().await; - cfg.openrouter_configured() - }; - let notes = vec![ - "GET /api/v1/key works with Freya’s normal completion key: per-key spend (day/week/month) and optional key spend cap.".into(), - "GET /api/v1/credits (account purchased − used) requires an OpenRouter Management API key — unavailable with a normal key.".into(), - "OpenRouter does not expose a rich recent-transactions feed for completion keys; Freya shows lifetime + period usage from /key.".into(), - ]; - if !configured { - return Ok(OpenRouterMetricsResponse { - configured: false, - key: None, - key_error: Some("OpenRouter API key not configured".into()), - credits: None, - credits_error: None, - notes, - }); - } - - let or = state.openrouter.read().await; - let (key, key_error) = match or.key_usage().await { - Ok(k) => (Some(k), None), - Err(e) => (None, Some(e.to_string())), - }; - let (credits, credits_error) = match or.account_credits().await { - Ok(c) => (Some(c), None), - Err(e) => (None, Some(e.to_string())), - }; - - Ok(OpenRouterMetricsResponse { - configured: true, - key, - key_error, - credits, - credits_error, - notes, + civitai_configured: cfg.civitai_configured(), + hf_configured: !cfg.hf_token.is_empty(), + diffusion_worker_url: cfg.diffusion_worker_url.clone(), + chat_model: cfg.chat_model.clone(), + image_model: cfg.image_model.clone(), }) } -pub async fn openrouter_metrics( - State(state): State, -) -> ApiResult> { - openrouter_metrics_payload(&state).await.map(Json) -} - -/// Generate or rotate the studio API bearer. Shown once in the response; also stored in -/// `FREYA_SECRETS_FILE` so local/kind restarts keep it when that path is durable. -#[derive(Debug, Serialize)] -#[serde(rename_all = "camelCase")] -pub struct AuthTokenResponse { - pub token: String, - pub rotated: bool, - pub persisted: bool, - /// Whether the Kubernetes Secret named by `FREYA_API_TOKEN_SECRET_NAME` was patched. - pub secret_synced: bool, - pub note: String, - #[serde(skip_serializing_if = "Option::is_none")] - pub sync_commands: Option>, -} - -pub async fn auth_token_create( - State(state): State, -) -> ApiResult> { - let token = generate_api_token(); - let (had_token, secret_name, secret_key, ns_hint) = { - let cfg = state.config.read().await; - ( - !cfg.api_token.trim().is_empty(), - cfg.api_token_secret_name.clone(), - cfg.api_token_secret_key.clone(), - std::env::var("FREYA_NAMESPACE").unwrap_or_else(|_| "freya".into()), - ) - }; - { - let mut cfg = state.config.write().await; - cfg.api_token = token.clone(); - } - let persisted = state.persist_secrets().await.is_ok(); - let secret_synced = crate::k8s_secret::try_sync_api_token_secret(&token).await; - - let sec = if secret_name.trim().is_empty() { - "freya-api-token".to_string() - } else { - secret_name - }; - let key = if secret_key.trim().is_empty() { - "token".to_string() - } else { - secret_key - }; - let sync_commands = if secret_synced { - Some(vec![format!( - "kubectl -n {ns_hint} rollout restart deploy/freya-mcp # pick up Secret {sec}" - )]) - } else { - Some(vec![ - format!( - "kubectl -n {ns_hint} create secret generic {sec} --from-literal={key}='{token}' --dry-run=client -o yaml | kubectl apply -f -" - ), - format!("kubectl -n {ns_hint} rollout restart deploy/freya-mcp"), - "./scripts/sync-api-token-from-pvc.sh".into(), - ]) - }; - let note = match (persisted, secret_synced) { - (true, true) => "Machine API token rotated and synced.".into(), - (true, false) => { - "Machine API token rotated (secrets file). Sync freya-api-token if MCP needs it.".into() - } - (false, true) => "Machine API token rotated (in-memory + Secret).".into(), - (false, false) => "Machine API token rotated (in-memory only) — copy it now.".into(), - }; - Ok(Json(AuthTokenResponse { - token, - rotated: had_token, - persisted, - secret_synced, - note, - sync_commands, - })) -} - -fn generate_api_token() -> String { - // 64 hex chars ≈ openssl rand -hex 32 - format!( - "{}{}", - uuid::Uuid::new_v4().simple(), - uuid::Uuid::new_v4().simple() - ) -} - #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase")] pub struct SettingsUpdate { @@ -4939,35 +450,21 @@ pub struct SettingsUpdate { pub chat_model: Option, #[serde(default)] pub image_model: Option, - #[serde(default)] - pub router_model: Option, - #[serde(default)] - pub privacy: Option, - #[serde(default)] - pub alignment: Option, - #[serde(default)] - pub auto_fallbacks: Option, - /// Partial merge of system-prompt overrides. Empty string for a mode clears that override - /// (reset to pack default). Absent keys are left unchanged. - #[serde(default)] - pub instruction_overrides: Option>, } pub async fn settings_put( State(state): State, Json(upd): Json, -) -> ApiResult> { - let models_changed = - upd.chat_model.is_some() || upd.image_model.is_some() || upd.router_model.is_some(); - let prefs_changed = - upd.privacy.is_some() || upd.alignment.is_some() || upd.auto_fallbacks.is_some(); +) -> ApiResult> { { let mut cfg = state.config.write().await; if let Some(url) = upd.diffusion_worker_url { if url.is_empty() { cfg.diffusion_worker_url = None; + *state.worker.write().await = None; } else { - cfg.diffusion_worker_url = Some(url); + cfg.diffusion_worker_url = Some(url.clone()); + *state.worker.write().await = Some(crate::worker::DiffusionWorkerClient::new(url)); } } if let Some(m) = upd.chat_model { @@ -4976,73 +473,22 @@ pub async fn settings_put( if let Some(m) = upd.image_model { cfg.image_model = m; } - if let Some(m) = upd.router_model { - cfg.router_model = m; - } - if let Some(p) = upd.privacy.clone() { - cfg.apply_privacy(p); - } - if let Some(a) = upd.alignment.clone() { - cfg.apply_alignment(a); - } - if let Some(f) = upd.auto_fallbacks.clone() { - cfg.apply_auto_fallbacks(f); - } - if let Some(patch) = upd.instruction_overrides.clone() { - for (mode, text) in patch { - if !styles::is_editable_instruction_mode(&mode) { - continue; - } - if text.trim().is_empty() { - cfg.instruction_overrides.remove(&mode); - } else { - cfg.instruction_overrides.insert(mode, text); - } - } - } } let secrets = RuntimeSecrets { openrouter_api_key: upd.openrouter_api_key, civitai_api_key: upd.civitai_api_key, hf_token: upd.hf_token, - diffusion_worker_url: None, // URL already applied above; persist_secrets writes full snapshot - api_token: None, - chat_model: None, - image_model: None, - router_model: None, - privacy: None, - alignment: None, - auto_fallbacks: None, - legacy_upstream_auto_migrated: false, - instruction_overrides: None, // persist_secrets writes full snapshot from cfg - studio: None, }; state.apply_secrets(secrets).await; - state.rebuild_worker_client().await; - let persisted = state.persist_secrets().await.is_ok(); - if !persisted { - tracing::warn!("FREYA_SECRETS_FILE write failed — keys may not survive API restart"); - } - - // OpenRouterClient captures models + privacy/alignment at construction — rebuild after changes. - if models_changed || prefs_changed { - let cfg = state.config.read().await; - let mut or = state.openrouter.write().await; - *or = crate::openrouter::OpenRouterClient::new(&cfg); - } + let _ = state.persist_secrets().await; - Ok(Json(SettingsPutResponse { - settings: settings_public_from_state(&state).await, - persisted, - })) + Ok(settings_get(State(state)).await) } #[derive(Debug)] pub enum ApiError { Msg(String), - Unauthorized(String), - Unavailable(String), NotFound, NoWorker, } @@ -5068,167 +514,8 @@ impl IntoResponse for ApiError { "No diffusion worker configured — set worker URL or deploy FreyaDiffusionWorker" .into(), ), - ApiError::Unauthorized(m) => (StatusCode::UNAUTHORIZED, m), - ApiError::Unavailable(m) => (StatusCode::SERVICE_UNAVAILABLE, m), ApiError::Msg(m) => (StatusCode::BAD_REQUEST, m), }; (code, Json(json!({ "error": msg }))).into_response() } } - -#[cfg(test)] -mod route_footer_tests { - use super::*; - - fn decision(modality: crate::router::Modality) -> crate::router::RouteDecision { - crate::router::RouteDecision { - modality, - reason: "t".into(), - agent_model: None, - image_model: None, - source: "t".into(), - } - } - - #[test] - fn refusal_heuristic_ignores_scene_wording() { - assert!(looks_like_model_refusal( - "I can't create explicit images, but here is a tasteful portrait." - )); - assert!(!looks_like_model_refusal( - "she whispered i can't breathe, pressed against my chest" - )); - assert!(!looks_like_model_refusal( - "not able to stand, knees against my thighs" - )); - } - - #[test] - fn adult_rewrite_accepts_an_echo_of_a_checkpoint_prompt() { - let scene = "nude woman, on a bed, soft window light, detailed skin"; - assert!(adult_rewrite_ok(scene, scene)); - assert!(!adult_rewrite_ok("nude woman", "nude woman")); - assert!(adult_retry_model( - "thedrummer/cydonia-24b-v4.1", - &crate::prefs::PrivacyPrefs::default(), - &crate::prefs::AutoFallbacksPrefs { - cost_tier: "medium".into(), - ..Default::default() - }, - ) - .is_some_and(|id| id != "thedrummer/cydonia-24b-v4.1")); - } - - #[test] - fn chat_pin_does_not_replace_the_resolved_image_model() { - let mut run = ActionRun { - loras: vec![], - image_model: Some("google/gemini-2.5-flash-image".into()), - video_model: Some("google/veo-3.1".into()), - backend: None, - }; - let chat_only = PlannedAction { - action_type: "set_chat_models".into(), - args: json!({ "chatModel": "deepseek/deepseek-v4-pro" }), - }; - run.absorb( - &chat_only, - &json!({ - "status": "executed", - "type": "set_chat_models", - "result": { - "chatModel": "deepseek/deepseek-v4-pro", - "imageModel": "auto", - "videoModel": "auto" - } - }), - ); - assert_eq!( - run.image_model.as_deref(), - Some("google/gemini-2.5-flash-image") - ); - assert_eq!(run.video_model.as_deref(), Some("google/veo-3.1")); - let image_pin = PlannedAction { - action_type: "set_chat_models".into(), - args: json!({ "imageModel": "black-forest-labs/flux.2-klein-4b" }), - }; - run.absorb( - &image_pin, - &json!({ - "status": "executed", - "type": "set_chat_models", - "result": { "imageModel": "black-forest-labs/flux.2-klein-4b" } - }), - ); - assert_eq!( - run.image_model.as_deref(), - Some("black-forest-labs/flux.2-klein-4b") - ); - } - - #[test] - fn local_refusal_prompt_is_replaced_with_the_user_scene() { - let mut action = PlannedAction { - action_type: "generate_image".into(), - args: json!({ - "prompt": "I can't create explicit images, but here is a tasteful portrait." - }), - }; - restore_refused_local_prompt(&mut action, "adult scene as written"); - assert_eq!( - action.args.get("prompt").and_then(|p| p.as_str()), - Some("adult scene as written") - ); - let mut kept = PlannedAction { - action_type: "generate_image".into(), - args: json!({ "prompt": "adult scene as written, closer crop" }), - }; - restore_refused_local_prompt(&mut kept, "adult scene as written"); - assert_eq!( - kept.args.get("prompt").and_then(|p| p.as_str()), - Some("adult scene as written, closer crop") - ); - } - - #[test] - fn local_footer_uses_base_lora_and_mode() { - let line = format_route_visibility(&RouteFooter { - route: &decision(crate::router::Modality::Chat), - agent: Some("google/gemini-2.5-flash"), - router: "google/gemini-2.5-flash", - image: "google/gemini-2.5-flash-image", - video: "google/veo-3.1", - backend: "local", - base: "Pony Diffusion V6 XL", - lora: "none", - mode: "auto", - }); - assert_eq!( - line, - "Route: chat · agent=gemini-2.5-flash · router=gemini-2.5-flash · base=Pony Diffusion V6 XL · lora=none · mode=Auto · backend=local" - ); - assert!(!line.contains("image=")); - assert!(!line.contains("video=")); - } - - #[test] - fn cloud_footer_keeps_image_and_video_models() { - let line = format_route_visibility(&RouteFooter { - route: &decision(crate::router::Modality::Picture), - agent: Some("google/gemini-2.5-flash"), - router: "google/gemini-2.5-flash", - image: "google/gemini-2.5-flash-image", - video: "google/veo-3.1", - backend: "openrouter", - base: "", - lora: "", - mode: "yolo", - }); - assert_eq!( - line, - "Route: picture · agent=gemini-2.5-flash · router=gemini-2.5-flash · image=gemini-2.5-flash-image · video=veo-3.1 · backend=cloud" - ); - assert!(!line.contains("base=")); - assert!(!line.contains("lora=")); - } -} diff --git a/crates/freya-api/src/state.rs b/crates/freya-api/src/state.rs index 18cd2aa..1175f7f 100644 --- a/crates/freya-api/src/state.rs +++ b/crates/freya-api/src/state.rs @@ -2,11 +2,8 @@ use crate::civitai::CivitaiClient; use crate::config::Config; use crate::gallery::Gallery; use crate::openrouter::OpenRouterClient; -use crate::prefs::{AlignmentPrefs, AutoFallbacksPrefs, PrivacyPrefs}; -use crate::studio::StudioPrefs; use crate::worker::DiffusionWorkerClient; use serde::{Deserialize, Serialize}; -use std::collections::HashMap; use std::path::PathBuf; use std::sync::Arc; use tokio::sync::RwLock; @@ -30,51 +27,17 @@ pub struct RuntimeSecrets { pub civitai_api_key: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub hf_token: Option, - /// Persisted worker URL so Settings survive API restarts. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub diffusion_worker_url: Option, - /// Studio bearer (`FREYA_API_TOKEN`). Overrides env when present so UI rotate survives restarts - /// when the secrets file lives on durable storage (e.g. gallery PVC). - #[serde(default, skip_serializing_if = "Option::is_none")] - pub api_token: Option, - /// Persisted model picks (Auto sentinels allowed). - #[serde(default, skip_serializing_if = "Option::is_none")] - pub chat_model: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub image_model: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub router_model: Option, - /// OpenRouter privacy prefs (ZDR / data_collection) + Freya chat-provider checkboxes. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub privacy: Option, - /// Freya-side model alignment / NSFW / tone prefs. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub alignment: Option, - /// Configurable Auto fallbacks when the router does not pin a concrete model. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub auto_fallbacks: Option, - /// Set after the old `openrouter/auto` Auto sentinel is rewritten to internal `auto`. - #[serde(default)] - pub legacy_upstream_auto_migrated: bool, - /// Per-mode system prompt overrides (non-empty values only). Empty map omitted. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub instruction_overrides: Option>, - /// Studio UI prefs (favorites, pins, backend, video model). Never includes secrets. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub studio: Option, } impl AppState { pub async fn from_config(cfg: Config) -> anyhow::Result { - crate::auto_matrix::init(&cfg.packs_dir); let gallery = Gallery::open(cfg.gallery_dir.clone()).await?; let openrouter = OpenRouterClient::new(&cfg); let civitai = CivitaiClient::new(cfg.civitai_api_key.clone()); - // A configured URL attaches the worker client. Local vs Cloud chooses the generate path. - let worker = cfg.diffusion_worker_url.as_ref().map(|u| { - DiffusionWorkerClient::new_with_tls(u.clone(), cfg.worker_tls_insecure) - .with_token(cfg.worker_token.clone()) - }); + let worker = cfg + .diffusion_worker_url + .as_ref() + .map(|u| DiffusionWorkerClient::new(u.clone())); let packs_dir = cfg.packs_dir.clone(); let state = Self { config: Arc::new(RwLock::new(cfg)), @@ -85,7 +48,6 @@ impl AppState { worker: Arc::new(RwLock::new(worker)), }; state.load_secrets_file().await?; - state.migrate_legacy_upstream_auto().await?; Ok(state) } @@ -99,133 +61,27 @@ impl AppState { } let raw = tokio::fs::read(&path).await?; let secrets: RuntimeSecrets = serde_json::from_slice(&raw).unwrap_or_default(); - self.apply_secrets_inner(secrets, true).await; + self.apply_secrets(secrets).await; Ok(()) } pub async fn apply_secrets(&self, secrets: RuntimeSecrets) { - self.apply_secrets_inner(secrets, false).await; - } - - async fn apply_secrets_inner(&self, secrets: RuntimeSecrets, from_disk: bool) { let mut cfg = self.config.write().await; - if assign_secret( - &mut cfg.openrouter_api_key, - secrets.openrouter_api_key, - from_disk, - ) { - let key = cfg.openrouter_api_key.clone(); - let mut or = self.openrouter.write().await; - *or = OpenRouterClient::new(&cfg).with_key(key); - } - if assign_secret(&mut cfg.civitai_api_key, secrets.civitai_api_key, from_disk) { - let key = cfg.civitai_api_key.clone(); - let mut civ = self.civitai.write().await; - *civ = CivitaiClient::new(key); - } - let _ = assign_secret(&mut cfg.hf_token, secrets.hf_token, from_disk); - if let Some(url) = secrets.diffusion_worker_url { - if url.trim().is_empty() { - cfg.diffusion_worker_url = None; - } else { - cfg.diffusion_worker_url = Some(url); - } - } - if let Some(tok) = secrets.api_token { - // Empty string clears auth (local/dev). Non-empty overrides env / previous value. - cfg.api_token = tok; - } - let mut models_changed = false; - if let Some(m) = secrets.chat_model { - if !m.trim().is_empty() { - cfg.chat_model = m; - models_changed = true; - } - } - if let Some(m) = secrets.image_model { - if !m.trim().is_empty() { - cfg.image_model = m; - models_changed = true; - } - } - if let Some(m) = secrets.router_model { - if !m.trim().is_empty() { - cfg.router_model = m; - models_changed = true; - } - } - let mut prefs_changed = false; - if let Some(p) = secrets.privacy { - cfg.apply_privacy(p); - prefs_changed = true; - } - if let Some(a) = secrets.alignment { - cfg.apply_alignment(a); - prefs_changed = true; - } - if let Some(f) = secrets.auto_fallbacks { - cfg.apply_auto_fallbacks(f); - prefs_changed = true; - } - if secrets.legacy_upstream_auto_migrated { - cfg.legacy_upstream_auto_migrated = true; - } - if let Some(overrides) = secrets.instruction_overrides { - cfg.instruction_overrides = normalize_instruction_overrides(overrides); - } - if let Some(studio) = secrets.studio { - cfg.studio = studio; - } - if models_changed || prefs_changed { - let key = cfg.openrouter_api_key.clone(); - let mut or = self.openrouter.write().await; - *or = OpenRouterClient::new(&cfg).with_key(key); - } - drop(cfg); - self.rebuild_worker_client().await; - } - - /// Old Auto was stored as `openrouter/auto`. Rewrite that sentinel to internal `auto` once. - async fn migrate_legacy_upstream_auto(&self) -> anyhow::Result<()> { - let changed = { - let mut cfg = self.config.write().await; - if cfg.legacy_upstream_auto_migrated { - false - } else { - if cfg - .chat_model - .trim() - .eq_ignore_ascii_case("openrouter/auto") - { - cfg.chat_model = "auto".into(); - } - cfg.legacy_upstream_auto_migrated = true; - true + if let Some(k) = secrets.openrouter_api_key { + if !k.is_empty() { + cfg.openrouter_api_key = k.clone(); + let mut or = self.openrouter.write().await; + *or = OpenRouterClient::new(&cfg).with_key(k); } - }; - if !changed { - return Ok(()); } - { - let cfg = self.config.read().await; - let key = cfg.openrouter_api_key.clone(); - let mut or = self.openrouter.write().await; - *or = OpenRouterClient::new(&cfg).with_key(key); + if let Some(k) = secrets.civitai_api_key { + cfg.civitai_api_key = k.clone(); + let mut civ = self.civitai.write().await; + *civ = CivitaiClient::new(k); } - if let Err(e) = self.persist_secrets().await { - tracing::warn!(error = %e, "legacy auto migration could not persist"); + if let Some(k) = secrets.hf_token { + cfg.hf_token = k; } - Ok(()) - } - - /// Attach or clear the in-memory worker client from the configured URL. - pub async fn rebuild_worker_client(&self) { - let cfg = self.config.read().await; - let next = cfg.diffusion_worker_url.as_ref().map(|u| { - DiffusionWorkerClient::new_with_tls(u.clone(), cfg.worker_tls_insecure) - .with_token(cfg.worker_token.clone()) - }); - *self.worker.write().await = next; } pub async fn persist_secrets(&self) -> anyhow::Result<()> { @@ -234,67 +90,12 @@ impl AppState { tokio::fs::create_dir_all(parent).await?; } let secrets = RuntimeSecrets { - openrouter_api_key: none_if_blank(&cfg.openrouter_api_key), - civitai_api_key: none_if_blank(&cfg.civitai_api_key), - hf_token: none_if_blank(&cfg.hf_token), - diffusion_worker_url: cfg.diffusion_worker_url.clone(), - api_token: if cfg.api_token.trim().is_empty() { - None - } else { - Some(cfg.api_token.clone()) - }, - chat_model: Some(cfg.chat_model.clone()), - image_model: Some(cfg.image_model.clone()), - router_model: Some(cfg.router_model.clone()), - privacy: Some(cfg.privacy_prefs()), - alignment: Some(cfg.alignment_prefs()), - auto_fallbacks: Some(cfg.auto_fallbacks_prefs()), - legacy_upstream_auto_migrated: cfg.legacy_upstream_auto_migrated, - instruction_overrides: if cfg.instruction_overrides.is_empty() { - None - } else { - Some(cfg.instruction_overrides.clone()) - }, - studio: Some(cfg.studio.clone()), + openrouter_api_key: Some(cfg.openrouter_api_key.clone()), + civitai_api_key: Some(cfg.civitai_api_key.clone()), + hf_token: Some(cfg.hf_token.clone()), }; let raw = serde_json::to_vec_pretty(&secrets)?; tokio::fs::write(&cfg.secrets_file, raw).await?; Ok(()) } } - -fn none_if_blank(value: &str) -> Option { - let trimmed = value.trim(); - if trimmed.is_empty() { - None - } else { - Some(trimmed.to_string()) - } -} - -/// Disk loads must not replace an env/Secret key with a blank. A live Settings clear still applies. -fn assign_secret(current: &mut String, incoming: Option, from_disk: bool) -> bool { - match incoming { - Some(k) if k.trim().is_empty() => { - if from_disk || current.trim().is_empty() { - false - } else { - current.clear(); - true - } - } - Some(k) => { - *current = k; - true - } - None => false, - } -} - -/// Keep only safe mode ids with non-empty trimmed text. -pub fn normalize_instruction_overrides(raw: HashMap) -> HashMap { - raw.into_iter() - .filter(|(k, v)| crate::styles::is_editable_instruction_mode(k) && !v.trim().is_empty()) - .map(|(k, v)| (k, v)) - .collect() -} diff --git a/crates/freya-api/src/styles.rs b/crates/freya-api/src/styles.rs index 671bded..367d7c6 100644 --- a/crates/freya-api/src/styles.rs +++ b/crates/freya-api/src/styles.rs @@ -64,111 +64,24 @@ pub async fn load_styles(packs_dir: &Path) -> Result> { if out.is_empty() { return Ok(builtin_styles()); } - // Featured brand pack first so UI "Use example" matches freya.png NL seed. - out.sort_by(|a, b| { - let rank = |id: &str| if id == "freya-winged-warrior" { 0 } else { 1 }; - rank(&a.id).cmp(&rank(&b.id)).then_with(|| a.id.cmp(&b.id)) - }); Ok(out) } -/// Assist `mode` must be a single path segment (no `/`, `..`, or absolute paths). -pub fn is_safe_instruction_mode(mode: &str) -> bool { - !mode.is_empty() - && mode.len() <= 64 - && mode - .chars() - .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_') -} - -/// Modes exposed in Settings for view/edit (packs/instructions defaults + overrides). -pub const EDITABLE_INSTRUCTION_MODES: &[&str] = &[ - "converse", - "route", - "chat", - "plan", - "suggest", - "session", - "prompt-prose", - "prompt-sd", -]; - -pub fn is_editable_instruction_mode(mode: &str) -> bool { - is_safe_instruction_mode(mode) && EDITABLE_INSTRUCTION_MODES.contains(&mode) -} - -pub fn instruction_mode_label(mode: &str) -> String { - match mode { - "converse" => "Converse (chat agent)".into(), - "route" => "Route (intent classifier)".into(), - "chat" => "Chat (assist)".into(), - "plan" => "Plan".into(), - "suggest" => "Suggest".into(), - "session" => "Session".into(), - "prompt-prose" => "Enhance — prose brief".into(), - "prompt-sd" => "Enhance — SD keywords".into(), - _ => mode.to_string(), - } -} - -/// Pack / builtin default only (ignores Settings overrides). -pub async fn load_instruction_default(packs_dir: &Path, mode: &str) -> String { - if !is_safe_instruction_mode(mode) { - return builtin_instruction("chat").to_string(); - } - let dir = packs_dir.join("instructions"); - let path = dir.join(format!("{mode}.txt")); - // Containment: refuse anything that resolves outside the instructions dir. - if let (Ok(dir_c), Ok(path_c)) = (fs::canonicalize(&dir).await, fs::canonicalize(&path).await) { - if path_c.starts_with(&dir_c) { - if let Ok(s) = fs::read_to_string(path_c).await { - return s; - } - } - } else if let Ok(s) = fs::read_to_string(&path).await { - // Dir may not exist yet — safe basename already enforced above. +pub async fn load_instruction(packs_dir: &Path, mode: &str) -> String { + let path = packs_dir.join("instructions").join(format!("{mode}.txt")); + if let Ok(s) = fs::read_to_string(path).await { return s; } builtin_instruction(mode).to_string() } -/// Prefer a non-empty Settings override when present; else pack file / builtin. -pub async fn load_instruction( - packs_dir: &Path, - mode: &str, - overrides: Option<&std::collections::HashMap>, -) -> String { - if let Some(map) = overrides { - if let Some(text) = map.get(mode) { - if !text.trim().is_empty() { - return text.clone(); - } - } - } - load_instruction_default(packs_dir, mode).await -} - fn builtin_styles() -> Vec { - // NL examples (not SD tag soup). First entry seeds UI "Use example" — freya.png brand art. vec![ - StylePack { - id: "freya-winged-warrior".into(), - display_name: "Freya (brand art)".into(), - tags: vec!["character".into(), "fantasy".into(), "wings".into()], - example_prompt: "A young woman with large brown eagle wings and fantasy leather armor, standing in a green canyon with a waterfall behind her".into(), - backend: "openrouter".into(), - open_router_model: Some("black-forest-labs/flux.2-klein-4b".into()), - local_checkpoint: None, - loras: vec![], - trigger_words: None, - recommended_size: Some("1024x1024".into()), - thumbnail_url: None, - }, StylePack { id: "ethereal-moon".into(), display_name: "Ethereal Moon Landscape".into(), tags: vec!["landscape".into(), "fantasy".into(), "moon".into()], - example_prompt: "A mystical landscape under a radiant red moon — a twisted blossoming tree on rocky ground, misty mountains beyond a lake that mirrors the moonlight".into(), + example_prompt: "ethereal mystical landscape under a radiant red moon, twisted blossoming tree on rocky terrain, misty mountains, serene lake reflecting moonlight, magical atmosphere, highly detailed".into(), backend: "openrouter".into(), open_router_model: Some("black-forest-labs/flux.2-klein-4b".into()), local_checkpoint: None, @@ -181,7 +94,7 @@ fn builtin_styles() -> Vec { id: "anime-portrait".into(), display_name: "Anime Portrait (cloud)".into(), tags: vec!["anime".into(), "portrait".into()], - example_prompt: "An anime-style portrait with soft lighting, expressive eyes, and clean colorful linework".into(), + example_prompt: "anime style portrait, soft lighting, expressive eyes, detailed hair, clean linework, vibrant colors".into(), backend: "openrouter".into(), open_router_model: Some("black-forest-labs/flux.2-klein-4b".into()), local_checkpoint: None, @@ -196,10 +109,7 @@ fn builtin_styles() -> Vec { pub fn builtin_instruction(mode: &str) -> &'static str { match mode { "chat" => { - "You are Freya, a friendly image studio guide. Users describe scenes in everyday language — you handle model briefs, LoRA discovery, and planning. Prefer Installed base+LoRA combos before Civitai search; ask a short follow-up when character likeness is ambiguous. Never teach comma-separated tags unless a selected LoRA needs one trigger word. Help them iterate: suggest what to try next, not how to prompt engineer." - } - "converse" => { - "You are Freya, a friendly agentic image studio guide. Reply JSON only: {\"reply\":\"...\",\"actions\":[...]}. Respect freya route modality and automationMode (plan|auto|yolo). If modality is picture, gif, or video, or the message is a visual prompt (scene, meme, cartoon, illustration, quoted prompt, series), generate — the word generate is optional. Questions, LoRA/model clarification, and how-it-works stay chat with no generate. Prefer list_loras/list_checkpoints (Installed) before search_civitai. Session pins are for LoRAs/adapters/embeddings only — never pin Checkpoints; use set_base_model for active base. install_asset queues a download and does not auto-pin. Plan: propose side effects. Auto: act on clear intent, ask when installs are ambiguous. YOLO: pick and go." + "You are Freya, a friendly image-generation expert. Help with prompts, model choice (OpenRouter cloud vs local LoRA), and troubleshooting. Be warm and clear." } "vision" => { "You are Freya. Describe the image in first person as if you are inside the scene. Use \"I see\", \"I notice\". 150–300 words. Output only the description." @@ -211,63 +121,11 @@ pub fn builtin_instruction(mode: &str) -> &'static str { "You are Freya. Output ONLY an optimized positive prompt for Stable Diffusion. One continuous comma-separated keyword list. Keep trigger words and underscores intact. No negative prompt. No preamble." } "prompt-prose" => { - "You are Freya. Expand the user's natural-language description into a rich image brief for modern models: one continuous paragraph of vivid prose. Do NOT output comma-separated Stable Diffusion keyword lists. Output ONLY the prose brief." + "You are Freya. Rewrite the user's intent as a rich natural-language image prompt for modern models (Flux, GPT Image, Gemini). One paragraph, vivid and specific. Output only the prompt." } "plan" => { - "You are Freya's planner for agentic image sessions. Reply with JSON only: {\"backend\":\"openrouter\"|\"local\",\"model\":null|\"provider/model\",\"styleId\":null|\"...\",\"enhanceMode\":\"prompt-prose\"|\"prompt-sd\",\"civitaiQuery\":null|\"short search\",\"rationale\":\"short\"}. Prefer openrouter + prompt-prose. model is a real provider/model image id (black-forest-labs/flux.2-klein-4b, google/gemini-2.5-flash-image, or google/gemini-3-pro-image) or null. Never prefix openrouter/ onto an id. Never use openrouter/auto, chat-only ids, or invented ids such as openrouter/google-gemini-pro-image-1. Use local + prompt-sd for pinned/Installed LoRAs; set civitaiQuery only when Installed has no match." - } - "suggest" => { - "You are Freya. Reply with JSON only: {\"ideas\":[\"nl alt 1\",\"nl alt 2\"],\"civitaiQuery\":\"short LoRA search or empty\",\"sessionNote\":\"what to try next\"}. Ideas are everyday prose, never SD tags. civitaiQuery is 2–6 words for Civitai when weights would help." - } - "session" => { - "You are Freya running an agentic image session. Reply JSON only: {\"goal\":\"...\",\"steps\":[{\"kind\":\"search_loras\"|\"generate\"|\"iterate\",\"prompt\":\"nl\",\"note\":\"why\"}],\"civitaiQuery\":\"short or empty\",\"batchPrompts\":[\"nl 1\",\"nl 2\",\"nl 3\"],\"sessionNote\":\"next\"}. Prefer Installed weights; search Civitai only if needed. Clarify ambiguous character likeness before heavy search/generate. Never SD keyword soup." + "You are Freya's planner. Given user intent, reply with JSON only: {\"backend\":\"openrouter\"|\"local\",\"model\":\"...\",\"styleId\":null|\"...\",\"enhanceMode\":\"prompt-prose\"|\"prompt-sd\",\"rationale\":\"short\"}. Prefer openrouter unless the user needs a specific LoRA/checkpoint." } - "route" => { - "You are Freya's internal request router. Classify into chat|picture|gif|video. A pasted visual prompt (scene, meme, cartoon, illustration, quoted prompt, tag list, series of stills) is picture even without the word generate. gif/video when they describe motion. Chat only for questions, how-it-works, and LoRA/model clarification. Respect Privacy/Alignment/cost. Under uncensored leave agentModel null so Auto uses Dolphin or Cydonia. Do not suggest Llama-instruct, Claude, or GPT as uncensored. Suggest concrete provider/model ids (image: google/gemini-2.5-flash-image or google/gemini-3-pro-image). Never prefix openrouter/ onto an id. Never suggest openrouter/auto or invented ids such as openrouter/google-gemini-pro-image-1. Reply JSON only: {\"modality\":\"...\",\"reason\":\"...\",\"agentModel\":null,\"imageModel\":null}." - } - _ => "You are Freya, a helpful image studio agent.", - } -} - -#[cfg(test)] -mod tests { - use super::*; - use std::path::PathBuf; - - #[test] - fn instruction_mode_rejects_path_traversal() { - assert!(is_safe_instruction_mode("chat")); - assert!(is_safe_instruction_mode("prompt-prose")); - assert!(!is_safe_instruction_mode("../etc/passwd")); - assert!(!is_safe_instruction_mode("/etc/passwd")); - assert!(!is_safe_instruction_mode("foo/bar")); - assert!(!is_safe_instruction_mode("")); - } - - #[tokio::test] - async fn load_instruction_ignores_unsafe_mode() { - let packs = PathBuf::from("/nonexistent-packs-dir"); - let text = load_instruction(&packs, "../../etc/passwd", None).await; - assert_eq!(text, builtin_instruction("chat")); - } - - #[tokio::test] - async fn load_instruction_prefers_override() { - let packs = PathBuf::from("/nonexistent-packs-dir"); - let mut overrides = std::collections::HashMap::new(); - overrides.insert("chat".into(), "Custom chat system prompt.".into()); - let text = load_instruction(&packs, "chat", Some(&overrides)).await; - assert_eq!(text, "Custom chat system prompt."); - let empty = load_instruction(&packs, "chat", None).await; - assert_eq!(empty, builtin_instruction("chat")); - } - - #[test] - fn builtin_styles_feature_freya_brand_nl() { - let styles = builtin_styles(); - assert_eq!(styles[0].id, "freya-winged-warrior"); - assert!(styles[0].example_prompt.contains("eagle wings")); - // Prose NL, not SD tag soup (no weight syntax). - assert!(!styles[0].example_prompt.contains(":1.")); + _ => "You are Freya, a helpful image assistant.", } } diff --git a/crates/freya-api/src/worker.rs b/crates/freya-api/src/worker.rs index b86dcd5..ac1a73a 100644 --- a/crates/freya-api/src/worker.rs +++ b/crates/freya-api/src/worker.rs @@ -8,103 +8,32 @@ use serde_json::Value; pub struct DiffusionWorkerClient { http: reqwest::Client, base: String, - token: Option, } impl DiffusionWorkerClient { - #[allow(dead_code)] pub fn new(base: impl Into) -> Self { - Self::new_with_tls(base, false) - } - - pub fn new_with_tls(base: impl Into, tls_insecure: bool) -> Self { - let base = base.into().trim_end_matches('/').to_string(); - // Public HTTPS keeps verification. The flag only applies to loopback, - // private, link-local, and cluster DNS. Same rule as the operator. - let skip = tls_insecure && tls_skip_allowed(&base); - let http = reqwest::Client::builder() - .danger_accept_invalid_certs(skip) - .build() - .unwrap_or_else(|_| reqwest::Client::new()); Self { - http, - base, - token: None, - } - } - - pub fn with_token(mut self, token: impl Into) -> Self { - let t = token.into(); - self.token = if t.trim().is_empty() { None } else { Some(t) }; - self - } - - fn apply_auth(&self, req: reqwest::RequestBuilder) -> reqwest::RequestBuilder { - match &self.token { - Some(t) => req.bearer_auth(t), - None => req, + http: reqwest::Client::new(), + base: base.into().trim_end_matches('/').to_string(), } } pub async fn health(&self) -> bool { - self.health_detail().await.is_some() - } - - /// Fetch worker `/health` JSON when reachable. - pub async fn health_detail(&self) -> Option { - let resp = self - .http + self.http .get(format!("{}/health", self.base)) .send() .await - .ok()?; - if !resp.status().is_success() { - return None; - } - resp.json::().await.ok() - } - - /// Authenticated `/v1/stats`. A failed call is not replaced with `/health` - /// (`{ok:true}` has no GPU or inventory). Use [`Self::health`] for reachability. - pub async fn stats_detail(&self) -> Option { - let resp = self - .apply_auth(self.http.get(format!("{}/v1/stats", self.base))) - .send() - .await - .ok()?; - if !resp.status().is_success() { - return None; - } - let body = resp.json::().await.ok()?; - if inventory_stats(&body) { - Some(body) - } else { - None - } + .map(|r| r.status().is_success()) + .unwrap_or(false) } pub async fn list_loras(&self) -> Result> { - self.list_assets("/v1/loras").await - } - - pub async fn list_checkpoints(&self) -> Result> { - self.list_assets("/v1/checkpoints").await - } - - pub async fn list_embeddings(&self) -> Result> { - self.list_assets("/v1/embeddings").await - } - - pub async fn list_vaes(&self) -> Result> { - self.list_assets("/v1/vae").await - } - - async fn list_assets(&self, path: &str) -> Result> { let resp = self - .apply_auth(self.http.get(format!("{}{path}", self.base))) + .http + .get(format!("{}/v1/loras", self.base)) .send() .await - .with_context(|| format!("list assets {path}"))?; + .context("list loras")?; if !resp.status().is_success() { return Ok(Vec::new()); } @@ -129,67 +58,12 @@ impl DiffusionWorkerClient { .and_then(|x| x.as_str()) .unwrap_or("") .to_string(), - base_model: a - .get("baseModel") - .and_then(|x| x.as_str()) - .map(str::to_string), - name: a.get("name").and_then(|x| x.as_str()).map(str::to_string), - size_bytes: a.get("sizeBytes").and_then(|x| x.as_u64()).or_else(|| { - a.get("sizeBytes") - .and_then(|x| x.as_i64()) - .map(|n| n as u64) - }), - model_type: a - .get("modelType") - .and_then(|x| x.as_str()) - .map(str::to_string), - version_id: a.get("versionId").and_then(|x| x.as_i64()), - model_id: a.get("modelId").and_then(|x| x.as_i64()), - source: a.get("source").and_then(|x| x.as_str()).map(str::to_string), - thumbnail_url: a - .get("thumbnailUrl") - .and_then(|x| x.as_str()) - .map(str::to_string), }); } } Ok(out) } - pub async fn get_active_base(&self) -> Result { - let resp = self - .apply_auth(self.http.get(format!("{}/v1/base-model", self.base))) - .send() - .await - .context("get active base")?; - if !resp.status().is_success() { - let t = resp.text().await.unwrap_or_default(); - return Err(anyhow!("get base-model failed: {t}")); - } - Ok(resp.json().await.unwrap_or(Value::Null)) - } - - pub async fn set_active_base(&self, model: &str, base_model: Option<&str>) -> Result { - let mut body = serde_json::json!({ "model": model }); - if let Some(b) = base_model.map(str::trim).filter(|s| !s.is_empty()) { - body["baseModel"] = Value::String(b.into()); - } - let resp = self - .apply_auth( - self.http - .put(format!("{}/v1/base-model", self.base)) - .json(&body), - ) - .send() - .await - .context("set active base")?; - if !resp.status().is_success() { - let t = resp.text().await.unwrap_or_default(); - return Err(anyhow!("set base-model failed: {t}")); - } - Ok(resp.json().await.unwrap_or(Value::Null)) - } - pub async fn generate( &self, prompt: &str, @@ -221,11 +95,9 @@ impl DiffusionWorkerClient { } let resp = self - .apply_auth( - self.http - .post(format!("{}/v1/images/generations", self.base)) - .json(&body), - ) + .http + .post(format!("{}/v1/images/generations", self.base)) + .json(&body) .send() .await .context("worker generate")?; @@ -245,114 +117,16 @@ impl DiffusionWorkerClient { .context("decode worker image") } - /// Local multi-frame GIF via Diffusers engine (`POST /v1/videos/generations` format=gif). - pub async fn generate_gif( - &self, - prompt: &str, - model: Option<&str>, - size: Option<&str>, - seed: Option, - negative: Option<&str>, - ) -> Result> { - let mut body = serde_json::json!({ - "prompt": prompt, - "format": "gif", - "frames": 6, - }); - if let Some(m) = model { - body["model"] = Value::String(m.into()); - } - if let Some(s) = size { - body["size"] = Value::String(s.into()); - } - if let Some(seed) = seed { - body["seed"] = Value::from(seed); - } - if let Some(neg) = negative { - body["negative_prompt"] = Value::String(neg.into()); - } - let resp = self - .apply_auth( - self.http - .post(format!("{}/v1/videos/generations", self.base)) - .json(&body), - ) - .send() - .await - .context("worker gif generate")?; - let status = resp.status(); - let text = resp.text().await.unwrap_or_default(); - if !status.is_success() { - return Err(anyhow!("worker gif {status}: {text}")); - } - let v: Value = serde_json::from_str(&text)?; - let b64 = v - .pointer("/data/0/b64_json") - .and_then(|x| x.as_str()) - .ok_or_else(|| anyhow!("worker gif missing b64_json"))?; - use base64::Engine; - base64::engine::general_purpose::STANDARD - .decode(b64) - .context("decode worker gif") - } - - fn install_body( - &self, - source: &str, - url: &str, - dest_path: &str, - auth_token: Option<&str>, - meta: Option<&InstallMeta>, - r#async: bool, - ) -> Value { - let mut body = serde_json::json!({ + pub async fn install_asset(&self, source: &str, url: &str, dest_path: &str) -> Result<()> { + let body = serde_json::json!({ "source": source, "url": url, "destPath": dest_path, - "async": r#async, }); - if let Some(t) = auth_token.map(str::trim).filter(|t| !t.is_empty()) { - body["authToken"] = Value::String(t.into()); - } - if let Some(m) = meta { - if let Some(n) = m.name.as_deref().filter(|s| !s.is_empty()) { - body["name"] = Value::String(n.into()); - } - if let Some(b) = m.base_model.as_deref().filter(|s| !s.is_empty()) { - body["baseModel"] = Value::String(b.into()); - } - if let Some(v) = m.version_id { - body["versionId"] = Value::from(v); - } - if let Some(mid) = m.model_id { - body["modelId"] = Value::from(mid); - } - if let Some(t) = m.model_type.as_deref().filter(|s| !s.is_empty()) { - body["modelType"] = Value::String(t.into()); - } - if let Some(thumb) = m.thumbnail_url.as_deref().filter(|s| !s.is_empty()) { - body["thumbnailUrl"] = Value::String(thumb.into()); - } - } - body - } - - /// Synchronous install (blocks until complete). Prefer `enqueue_install` for UI/agent. - pub async fn install_asset( - &self, - source: &str, - url: &str, - dest_path: &str, - auth_token: Option<&str>, - meta: Option<&InstallMeta>, - ) -> Result<()> { - let body = self.install_body(source, url, dest_path, auth_token, meta, false); let resp = self - .apply_auth( - self.http - .post(format!("{}/v1/assets/install", self.base)) - .json(&body), - ) + .http + .post(format!("{}/v1/assets/install", self.base)) + .json(&body) .send() .await .context("worker install")?; @@ -362,128 +136,6 @@ impl DiffusionWorkerClient { } Ok(()) } - - /// Enqueue a background install job; returns worker JSON (`jobId`, `status`, `job`, …). - pub async fn enqueue_install( - &self, - source: &str, - url: &str, - dest_path: &str, - auth_token: Option<&str>, - meta: Option<&InstallMeta>, - ) -> Result { - let body = self.install_body(source, url, dest_path, auth_token, meta, true); - let resp = self - .apply_auth( - self.http - .post(format!("{}/v1/assets/jobs", self.base)) - .json(&body), - ) - .send() - .await - .context("worker enqueue install")?; - let status = resp.status(); - let text = resp.text().await.unwrap_or_default(); - if !status.is_success() { - return Err(anyhow!("enqueue failed: {text}")); - } - Ok(serde_json::from_str(&text).unwrap_or(Value::Null)) - } - - pub async fn list_install_jobs(&self) -> Result { - let resp = self - .apply_auth(self.http.get(format!("{}/v1/assets/jobs", self.base))) - .send() - .await - .context("list install jobs")?; - if !resp.status().is_success() { - let t = resp.text().await.unwrap_or_default(); - return Err(anyhow!("list jobs failed: {t}")); - } - Ok(resp.json().await.unwrap_or(Value::Null)) - } - - pub async fn get_install_job(&self, id: &str) -> Result { - let url = worker_job_url(&self.base, id, false)?; - let resp = self - .apply_auth(self.http.get(url)) - .send() - .await - .context("get install job")?; - let status = resp.status(); - let text = resp.text().await.unwrap_or_default(); - if status.as_u16() == 404 { - return Err(anyhow!("job not found")); - } - if !status.is_success() { - return Err(anyhow!("get job failed: {text}")); - } - Ok(serde_json::from_str(&text).unwrap_or(Value::Null)) - } - - pub async fn cancel_install_job(&self, id: &str) -> Result { - let url = worker_job_url(&self.base, id, true)?; - let resp = self - .apply_auth(self.http.post(url)) - .send() - .await - .context("cancel install job")?; - let status = resp.status(); - let text = resp.text().await.unwrap_or_default(); - if !status.is_success() { - return Err(anyhow!("cancel failed: {text}")); - } - Ok(serde_json::from_str(&text).unwrap_or(Value::Null)) - } - - /// Clear finished install jobs on the worker (succeeded/failed/cancelled). - pub async fn clear_install_jobs(&self, include_queued: bool) -> Result { - let body = serde_json::json!({ "includeQueued": include_queued }); - let resp = self - .apply_auth( - self.http - .post(format!("{}/v1/assets/jobs/clear", self.base)) - .json(&body), - ) - .send() - .await - .context("clear install jobs")?; - let status = resp.status(); - let text = resp.text().await.unwrap_or_default(); - if !status.is_success() { - return Err(anyhow!("clear jobs failed: {text}")); - } - Ok(serde_json::from_str(&text).unwrap_or(Value::Null)) - } - - pub async fn delete_asset(&self, path: &str) -> Result { - let body = serde_json::json!({ "path": path }); - let resp = self - .apply_auth( - self.http - .delete(format!("{}/v1/assets", self.base)) - .json(&body), - ) - .send() - .await - .context("delete asset")?; - let status = resp.status(); - let text = resp.text().await.unwrap_or_default(); - if !status.is_success() { - return Err(anyhow!("delete failed: {text}")); - } - Ok(serde_json::from_str(&text).unwrap_or(Value::Null)) - } -} - -#[derive(Debug, Clone, Default)] -pub struct InstallMeta { - pub name: Option, - pub base_model: Option, - pub version_id: Option, - pub model_id: Option, - pub model_type: Option, - pub thumbnail_url: Option, } #[derive(Debug, Clone, Serialize, Deserialize)] @@ -497,164 +149,9 @@ fn one() -> f32 { 1.0 } -/// Single path segment: UUID or `[A-Za-z0-9_-]+`. No `/ ? # % . ..`. -/// Same rule as freya-mcp. Does not percent-encode. -fn safe_path_segment(id: &str) -> Result<&str> { - let id = id.trim(); - if id.is_empty() - || id.contains('/') - || id.contains('?') - || id.contains('#') - || id.contains('%') - || id.contains('.') - || id.contains("..") - || !id - .chars() - .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-') - { - return Err(anyhow!("invalid job id")); - } - Ok(id) -} - -fn worker_job_url(base: &str, id: &str, cancel: bool) -> Result { - let id = safe_path_segment(id)?; - let base = base.trim_end_matches('/'); - let suffix = if cancel { - format!("/v1/assets/jobs/{id}/cancel") - } else { - format!("/v1/assets/jobs/{id}") - }; - let url = format!("{base}{suffix}"); - let parsed = reqwest::Url::parse(&url).context("parse worker job url")?; - if parsed.query().is_some() || parsed.fragment().is_some() || !parsed.path().ends_with(&suffix) - { - return Err(anyhow!("invalid job id")); - } - Ok(url) -} - #[derive(Debug, Clone, Serialize, Deserialize)] pub struct LocalAsset { pub id: String, pub kind: String, pub path: String, - #[serde(default)] - pub base_model: Option, - #[serde(default)] - pub name: Option, - #[serde(default)] - pub size_bytes: Option, - #[serde(default)] - pub model_type: Option, - #[serde(default)] - pub version_id: Option, - #[serde(default)] - pub model_id: Option, - #[serde(default)] - pub source: Option, - #[serde(default)] - pub thumbnail_url: Option, -} - -/// True when the JSON is worker inventory, not the liveness `{ok:true}` body. -pub(crate) fn inventory_stats(v: &Value) -> bool { - v.get("modelsDir").is_some() - || v.get("loras").is_some() - || v.get("checkpoints").is_some() - || v.get("vram").is_some() - || v.get("disk").is_some() -} - -/// Public HTTPS is verified. Skip only for loopback, private, link-local, or cluster DNS. -/// Keep in sync with `freya_operator::reconcile::tls_skip_allowed`. -pub(crate) fn tls_skip_allowed(endpoint: &str) -> bool { - let Ok(url) = reqwest::Url::parse(endpoint.trim()) else { - return false; - }; - let Some(host) = url.host_str() else { - return false; - }; - host_is_local_or_private(host) -} - -fn host_is_local_or_private(host: &str) -> bool { - let h = host - .trim() - .trim_matches(['[', ']']) - .trim_end_matches('.') - .to_ascii_lowercase(); - if h.is_empty() - || h == "localhost" - || h.ends_with(".localhost") - || h.ends_with(".local") - || h.ends_with(".cluster.local") - || h.ends_with(".svc") - || !h.contains('.') - { - return true; - } - match h.parse::() { - Ok(std::net::IpAddr::V4(ip)) => { - let [a, b, _, _] = ip.octets(); - ip.is_loopback() - || ip.is_link_local() - || ip.is_broadcast() - || a == 0 - || a == 10 - || (a == 172 && (16..=31).contains(&b)) - || (a == 192 && b == 168) - } - Ok(std::net::IpAddr::V6(ip)) => { - ip.is_loopback() || ip.is_unicast_link_local() || (ip.octets()[0] & 0xfe) == 0xfc - } - Err(_) => false, - } -} - -#[cfg(test)] -mod tls_tests { - use super::{inventory_stats, tls_skip_allowed, worker_job_url}; - - #[test] - fn health_ok_is_not_inventory() { - assert!(!inventory_stats(&serde_json::json!({ "ok": true }))); - assert!(!inventory_stats( - &serde_json::json!({ "ok": true, "service": "freya-worker" }) - )); - assert!(inventory_stats( - &serde_json::json!({ "ok": true, "vram": null, "loras": 0, "modelsDir": "/models" }) - )); - } - - #[test] - fn job_id_path_rejects_injection() { - for id in ["../auth/token", "x?x", "../../worker/start?"] { - assert!(worker_job_url("http://worker.internal", id, true).is_err()); - assert!(worker_job_url("http://worker.internal", id, false).is_err()); - } - let url = worker_job_url( - "http://worker.internal", - "550e8400-e29b-41d4-a716-446655440000", - true, - ) - .unwrap(); - let parsed = reqwest::Url::parse(&url).unwrap(); - assert_eq!( - parsed.path(), - "/v1/assets/jobs/550e8400-e29b-41d4-a716-446655440000/cancel" - ); - assert!(parsed.query().is_none()); - } - - #[test] - fn public_https_does_not_skip_verify() { - assert!(!tls_skip_allowed("https://vllm.dataknife.net")); - assert!(tls_skip_allowed("https://192.168.3.125:8091")); - assert!(tls_skip_allowed("https://127.0.0.1:8091")); - assert!(tls_skip_allowed( - "https://freya-gpu.freya.svc.cluster.local:8091" - )); - assert!(tls_skip_allowed("http://freya-worker:8091")); - } } diff --git a/crates/freya-crd/src/lib.rs b/crates/freya-crd/src/lib.rs index d8dc287..a5b20d8 100644 --- a/crates/freya-crd/src/lib.rs +++ b/crates/freya-crd/src/lib.rs @@ -32,28 +32,6 @@ fn default_api_key_key() -> String { "apiKey".into() } -fn default_api_token_key() -> String { - "token".into() -} - -/// Secret key for the machine API bearer. Defaults to `token`, matching the generated Secret. -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -#[serde(rename_all = "camelCase")] -pub struct ApiTokenSecretRef { - pub name: String, - #[serde(default = "default_api_token_key")] - pub key: String, -} - -impl From for SecretKeyRef { - fn from(v: ApiTokenSecretRef) -> Self { - Self { - name: v.name, - key: v.key, - } - } -} - /// Default Secret key name for Civitai tokens. pub fn default_civitai_key() -> String { "apiKey".into() @@ -63,29 +41,22 @@ pub fn default_civitai_key() -> String { #[serde(rename_all = "camelCase")] pub struct OpenRouterSpec { pub secret_ref: SecretKeyRef, - /// Default chat / plan model id. `auto` = Freya internal Auto (not `openrouter/auto`). + /// Default chat / plan model id (OpenRouter). #[serde(default = "default_chat_model")] pub chat_model: String, - /// Default cloud image model id. `auto` = Freya router / Flux NL default. + /// Default cloud image model id (OpenRouter). #[serde(default = "default_image_model")] pub image_model: String, - /// Freya-owned light intent router model. `auto` = Llama 3.1 8B-class (dolphin3 spirit). - #[serde(default = "default_router_model")] - pub router_model: String, #[serde(default = "default_openrouter_base")] pub base_url: String, } fn default_chat_model() -> String { - "auto".into() + "openrouter/auto".into() } fn default_image_model() -> String { - "auto".into() -} - -fn default_router_model() -> String { - "auto".into() + "black-forest-labs/flux.2-klein-4b".into() } fn default_openrouter_base() -> String { @@ -101,7 +72,6 @@ impl Default for OpenRouterSpec { }, chat_model: default_chat_model(), image_model: default_image_model(), - router_model: default_router_model(), base_url: default_openrouter_base(), } } @@ -134,12 +104,6 @@ pub struct IngressSpec { pub class_name: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub host: Option, - /// TLS Secret in the Studio namespace (e.g. `wildcard-dataknife-net-tls`). - /// Fleet pattern: same Let's Encrypt `*.dataknife.net` secret synced to - /// `kube-system` as the ingress default cert; copy into this namespace when - /// setting `tlsSecretName`. Omit to rely on the controller default cert only. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub tls_secret_name: Option, } #[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] @@ -181,7 +145,7 @@ pub struct HuggingFaceSpec { pub secret_ref: Option, } -/// Namespaced Freya studio: API + UI + gallery + optional MCP. +/// Namespaced Freya studio: API + UI + gallery. #[derive(CustomResource, Clone, Debug, Serialize, Deserialize, JsonSchema)] #[kube( group = "freya.dataknife.ai", @@ -209,12 +173,6 @@ pub struct FreyaStudioSpec { pub api_image: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub ui_image: Option, - /// MCP Streamable HTTP server image (defaults to harbor freya-mcp). - #[serde(default, skip_serializing_if = "Option::is_none")] - pub mcp_image: Option, - /// Deploy Freya MCP (`{name}-mcp`) and Ingress path `/mcp`. Default true. - #[serde(default = "default_mcp_enabled")] - pub mcp_enabled: bool, #[serde(default)] pub storage: StorageSpec, #[serde(default)] @@ -222,44 +180,10 @@ pub struct FreyaStudioSpec { /// Optional FreyaDiffusionWorker name in the same namespace. #[serde(default, skip_serializing_if = "Option::is_none")] pub diffusion_worker_ref: Option, - /// Secret holding `FREYA_API_TOKEN` for the API (machine bearer for MCP/worker/UI after login). - /// When unset and `generateAdminSecrets` is true, the operator creates `{name}-api-token`. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub api_token_secret_ref: Option, - /// Game-operator style: ensure an admin login Secret (`username` + `admin-password`) - /// and, when `apiTokenSecretRef` is unset, an API bearer Secret. Default true. - #[serde(default = "default_generate_admin_secrets")] - pub generate_admin_secrets: bool, - /// BYO admin credentials Secret (keys: `admin-password` required, `username` optional → `admin`). - /// Used when `generateAdminSecrets` is false, or as the target name when generating. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub admin_credentials_secret_ref: Option, #[serde(default = "default_replicas")] pub replicas: i32, } -/// Namespaced Secret reference (name only) — mirrors game-operator `credentialsSecretRef`. -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq, Default)] -#[serde(rename_all = "camelCase")] -pub struct LocalObjectRef { - pub name: String, -} - -/// Secret key for the Studio admin password (game-operator convention). -pub const SECRET_KEY_ADMIN_PASSWORD: &str = "admin-password"; -/// Secret key for the Studio admin username (default `admin` when absent). -pub const SECRET_KEY_ADMIN_USERNAME: &str = "username"; -/// Secret key for the machine API bearer. -pub const SECRET_KEY_API_TOKEN: &str = "token"; - -fn default_generate_admin_secrets() -> bool { - true -} - -fn default_mcp_enabled() -> bool { - true -} - fn default_replicas() -> i32 { 1 } @@ -273,18 +197,6 @@ pub struct FreyaStudioStatus { pub api_endpoint: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub ui_endpoint: Option, - /// In-cluster MCP Streamable HTTP base, e.g. `http://freya-mcp.freya.svc:8090/mcp`. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub mcp_endpoint: Option, - /// Secret holding admin login (`username` + `admin-password`). Never includes the password. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub admin_credentials_secret_name: Option, - /// True when the operator generated (or filled) the admin credentials Secret. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub admin_credentials_generated: Option, - /// Secret holding the machine API bearer (`token` key). - #[serde(default, skip_serializing_if = "Option::is_none")] - pub api_token_secret_name: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub observed_generation: Option, } @@ -420,15 +332,11 @@ pub enum DiffusionEngine { } /// Where the diffusion / LoRA engine runs. -/// -/// CRD enum values are lowercase (`incluster`, `external`). The `inCluster` alias -/// is accepted by Rust serde for convenience; kubectl/OpenAPI only allow `incluster`. #[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq, Default)] #[serde(rename_all = "lowercase")] pub enum WorkerPlacement { /// Operator creates a GPU Deployment in-cluster. #[default] - #[serde(alias = "inCluster")] InCluster, /// Reach a remote physical (or other) host Freya already can HTTP to. External, @@ -437,10 +345,10 @@ pub enum WorkerPlacement { /// Optional GPU worker for local SD / LoRA (vLLM-Omni by default). /// /// Placement: -/// - `external` (**recommended**) — point `externalEndpoint` at the GPU host running -/// `freya-local-worker` / vLLM-Omni (or compatible `/v1/images/generations` + LoRA install). -/// Studio stays in-cluster; the worker stays out-of-cluster via URL. -/// - `incluster` (optional) — operator deploys the engine only when the cluster has GPUs. +/// - `inCluster` — operator deploys the engine on a GPU node when the cluster has GPUs. +/// - `external` — point `externalEndpoint` at a remote physical system running vLLM-Omni +/// (or compatible `/v1/images/generations` + LoRA install API). Freya UI/API use that +/// endpoint; `FreyaModelAsset` installs LoRAs onto the remote worker for the UI catalog. #[derive(CustomResource, Clone, Debug, Serialize, Deserialize, JsonSchema)] #[kube( group = "freya.dataknife.ai", diff --git a/crates/freya-operator/Cargo.toml b/crates/freya-operator/Cargo.toml index 035c596..a84c05e 100644 --- a/crates/freya-operator/Cargo.toml +++ b/crates/freya-operator/Cargo.toml @@ -27,4 +27,3 @@ serde_yaml = { workspace = true } futures = { workspace = true } thiserror = { workspace = true } reqwest = { workspace = true } -uuid = { workspace = true } diff --git a/crates/freya-operator/src/reconcile/asset.rs b/crates/freya-operator/src/reconcile/asset.rs index b4f3ff4..1c8f0a3 100644 --- a/crates/freya-operator/src/reconcile/asset.rs +++ b/crates/freya-operator/src/reconcile/asset.rs @@ -13,7 +13,6 @@ use kube::api::{Patch, PatchParams}; use kube::runtime::controller::Action; use kube::{Api, Resource, ResourceExt}; use std::collections::BTreeMap; -use std::path::{Component, Path}; use std::sync::Arc; use std::time::Duration; use tracing::{info, warn}; @@ -22,9 +21,8 @@ pub async fn reconcile(asset: Arc, ctx: Arc) -> Result return Ok(Action::await_change()), - _ => {} + if asset.status.as_ref().and_then(|s| s.phase.as_deref()) == Some("Succeeded") { + return Ok(Action::await_change()); } patch_phase(&ctx, &ns, &name, "Installing", None).await?; @@ -47,7 +45,7 @@ pub async fn reconcile(asset: Arc, ctx: Arc) -> Result, ctx: Arc) -> Result { info!(%ns, asset = %name, "creating download Job into worker models PVC"); ensure_download_job(&ctx, &ns, &name, &asset, &worker, &owner).await?; - watch_download_job(&ctx, &ns, &name).await + patch_phase( + &ctx, + &ns, + &name, + "Succeeded", + Some("download Job applied".into()), + ) + .await?; } } + + Ok(Action::await_change()) } -async fn install_remote( - ctx: &Ctx, - ns: &str, - asset: &FreyaModelAsset, - worker: &FreyaDiffusionWorker, - endpoint: &str, -) -> Result<(), Error> { - sanitize_dest_path(&asset.spec.dest_path)?; - let tls_insecure = worker - .annotations() - .get("freya.dataknife.ai/tls-insecure") - .map(|v| v.eq_ignore_ascii_case("true") || v == "1") - .unwrap_or(false); +async fn install_remote(asset: &FreyaModelAsset, endpoint: &str) -> Result<(), Error> { let client = reqwest::Client::builder() .timeout(Duration::from_secs(600)) - .danger_accept_invalid_certs(tls_insecure && super::tls_skip_allowed(endpoint)) .build() .map_err(|e| Error::Http(e.to_string()))?; @@ -91,19 +84,15 @@ async fn install_remote( "destPath": asset.spec.dest_path, }); - let mut req = client + let resp = client .post(format!( "{}/v1/assets/install", endpoint.trim_end_matches('/') )) - .json(&body); - - if let Some(auth) = &worker.spec.auth_secret_ref { - let token = read_secret_key(ctx, ns, &auth.name, &auth.key).await?; - req = req.bearer_auth(token); - } - - let resp = req.send().await.map_err(|e| Error::Http(e.to_string()))?; + .json(&body) + .send() + .await + .map_err(|e| Error::Http(e.to_string()))?; if !resp.status().is_success() { let msg = resp.text().await.unwrap_or_default(); @@ -112,99 +101,6 @@ async fn install_remote( Ok(()) } -async fn read_secret_key(ctx: &Ctx, ns: &str, name: &str, key: &str) -> Result { - use k8s_openapi::api::core::v1::Secret; - let api: Api = Api::namespaced(ctx.client.clone(), ns); - let secret = api.get(name).await.map_err(Error::Kube)?; - let data = secret - .data - .ok_or_else(|| Error::Http(format!("secret {name} has no data")))?; - let bytes = data - .get(key) - .ok_or_else(|| Error::Http(format!("secret {name} missing key {key}")))?; - String::from_utf8(bytes.0.clone()) - .map_err(|e| Error::Http(format!("secret {name}/{key} not utf8: {e}"))) -} - -/// Same download hosts as freya-worker install — required before attaching `secretRef`. -fn asset_download_host_ok(host: &str) -> bool { - let h = host.to_ascii_lowercase(); - h == "civitai.com" - || h.ends_with(".civitai.com") - || h == "huggingface.co" - || h.ends_with(".huggingface.co") - || h == "hf.co" - || h.ends_with(".hf.co") -} - -fn asset_download_url_ok(url: &str) -> bool { - let Ok(parsed) = reqwest::Url::parse(url) else { - return false; - }; - if !matches!(parsed.scheme(), "https" | "http") { - return false; - } - parsed.host_str().is_some_and(asset_download_host_ok) -} - -fn sanitize_asset_url(url: &str) -> Result<(), Error> { - if !asset_download_url_ok(url) { - return Err(Error::BadUrl( - "url must be http(s) on civitai.com, huggingface.co, or hf.co".into(), - )); - } - Ok(()) -} - -/// Reject absolute / `..` / shell-metachar dest paths; must stay under `/models`. -fn sanitize_dest_path(dest: &str) -> Result<(), Error> { - if dest.is_empty() { - return Err(Error::BadDest("destPath is empty".into())); - } - let path = Path::new(dest); - if path.is_absolute() - || path - .components() - .any(|c| matches!(c, Component::ParentDir | Component::RootDir)) - { - return Err(Error::BadDest( - "destPath must be relative under /models (no '..')".into(), - )); - } - if dest.chars().any(|c| { - matches!( - c, - ';' | '|' - | '&' - | '$' - | '`' - | '\n' - | '\r' - | '"' - | '\'' - | '\\' - | '\0' - | '(' - | ')' - | '<' - | '>' - | '*' - | '?' - | '[' - | ']' - | '{' - | '}' - | '!' - | '#' - ) - }) { - return Err(Error::BadDest( - "destPath contains disallowed characters".into(), - )); - } - Ok(()) -} - async fn ensure_download_job( ctx: &Ctx, ns: &str, @@ -213,9 +109,6 @@ async fn ensure_download_job( worker: &FreyaDiffusionWorker, owner: &OwnerReference, ) -> Result<(), Error> { - sanitize_dest_path(&asset.spec.dest_path)?; - // Allowlist before mounting secretRef — prevents sending namespace secrets to attacker URLs. - sanitize_asset_url(&asset.spec.url)?; let job_name = format!("freya-asset-{name}"); let pvc = format!("{}-models", asset.spec.worker_ref); let mut env = vec![ @@ -236,7 +129,6 @@ async fn ensure_download_job( }, ]; - // Only mount secretRef after allowlist — never present namespace secrets to arbitrary hosts. if let Some(secret) = &asset.spec.secret_ref { env.push(EnvVar { name: "ASSET_TOKEN".into(), @@ -254,7 +146,6 @@ async fn ensure_download_job( let _ = worker; // model path layout shared via PVC - // No `eval`: curl argv stays literal; dest constrained under MODELS_DIR in-script + Rust. let job = Job { metadata: ObjectMeta { name: Some(job_name.clone()), @@ -284,37 +175,11 @@ async fn ensure_download_job( name: "download".into(), image: Some("curlimages/curl:8.11.1".into()), command: Some(vec!["/bin/sh".into(), "-c".into()]), - args: Some(vec![r#"set -eu -case "$DEST_PATH" in - /*|*..*) - echo "refusing unsafe DEST_PATH" >&2 - exit 1 - ;; -esac -DEST="$MODELS_DIR/$DEST_PATH" -case "$DEST" in - "$MODELS_DIR"/*) ;; - *) - echo "dest escapes models dir" >&2 - exit 1 - ;; -esac -# Defense in depth: refuse token attach / download outside allowlisted hosts. -case "$ASSET_URL" in - https://civitai.com/*|http://civitai.com/*|https://*.civitai.com/*|http://*.civitai.com/*) ;; - https://huggingface.co/*|http://huggingface.co/*|https://*.huggingface.co/*|http://*.huggingface.co/*) ;; - https://hf.co/*|http://hf.co/*|https://*.hf.co/*|http://*.hf.co/*) ;; - *) - echo "refusing non-allowlisted ASSET_URL" >&2 - exit 1 - ;; -esac -mkdir -p "$(dirname "$DEST")" -if [ -n "${ASSET_TOKEN:-}" ]; then - curl -fL --max-redirs 5 -H "Authorization: Bearer ${ASSET_TOKEN}" -o "$DEST" -- "$ASSET_URL" -else - curl -fL --max-redirs 5 -o "$DEST" -- "$ASSET_URL" -fi + args: Some(vec![r#"set -e +mkdir -p "$(dirname "$MODELS_DIR/$DEST_PATH")" +AUTH="" +if [ -n "${ASSET_TOKEN:-}" ]; then AUTH="-H Authorization:\ Bearer\ $ASSET_TOKEN"; fi +eval curl -fL $AUTH -o "$MODELS_DIR/$DEST_PATH" "$ASSET_URL" echo "installed $DEST_PATH" "# .into()]), @@ -353,41 +218,6 @@ echo "installed $DEST_PATH" Ok(()) } -async fn watch_download_job(ctx: &Ctx, ns: &str, name: &str) -> Result { - let job_name = format!("freya-asset-{name}"); - let api: Api = Api::namespaced(ctx.client.clone(), ns); - let job = api.get(&job_name).await.map_err(Error::Kube)?; - let status = job.status.as_ref(); - let succeeded = status.and_then(|s| s.succeeded).unwrap_or(0); - let failed = status.and_then(|s| s.failed).unwrap_or(0); - - if succeeded > 0 { - patch_phase( - ctx, - ns, - name, - "Succeeded", - Some("download Job completed".into()), - ) - .await?; - return Ok(Action::await_change()); - } - if failed > 0 { - patch_phase(ctx, ns, name, "Failed", Some("download Job failed".into())).await?; - return Ok(Action::await_change()); - } - - patch_phase( - ctx, - ns, - name, - "Installing", - Some("waiting for download Job".into()), - ) - .await?; - Ok(Action::requeue(Duration::from_secs(15))) -} - async fn patch_phase( ctx: &Ctx, ns: &str, @@ -413,24 +243,6 @@ pub fn error_policy(asset: Arc, err: &Error, _ctx: Arc) -> Action::requeue(Duration::from_secs(30)) } -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn allowlist_asset_download_hosts() { - assert!(asset_download_url_ok( - "https://civitai.com/api/download/models/1?token=x" - )); - assert!(asset_download_url_ok( - "https://huggingface.co/org/model/resolve/main/file.safetensors" - )); - assert!(sanitize_asset_url("https://hf.co/org/model").is_ok()); - assert!(sanitize_asset_url("https://evil.example/steal").is_err()); - assert!(sanitize_asset_url("file:///etc/passwd").is_err()); - } -} - #[derive(Debug, thiserror::Error)] pub enum Error { #[error("missing namespace")] @@ -439,10 +251,6 @@ pub enum Error { OwnerRef, #[error("worker has no endpoint")] MissingEndpoint, - #[error("bad destPath: {0}")] - BadDest(String), - #[error("bad url: {0}")] - BadUrl(String), #[error("kube: {0}")] Kube(#[from] kube::Error), #[error("http: {0}")] diff --git a/crates/freya-operator/src/reconcile/generation.rs b/crates/freya-operator/src/reconcile/generation.rs index d587e6b..455ea59 100644 --- a/crates/freya-operator/src/reconcile/generation.rs +++ b/crates/freya-operator/src/reconcile/generation.rs @@ -20,16 +20,7 @@ pub async fn reconcile(gen: Arc, ctx: Arc) -> Result, ctx: Arc) -> Result, } -#[derive(Default)] -struct StatusPatch { - phase: &'static str, +async fn patch_phase( + ctx: &Ctx, + ns: &str, + name: &str, + phase: &str, backend: Option, artifact: Option, - enhanced_prompt: Option, message: Option, -} - -async fn patch_status(ctx: &Ctx, ns: &str, name: &str, patch: StatusPatch) -> Result<(), Error> { +) -> Result<(), Error> { let api: Api = Api::namespaced(ctx.client.clone(), ns); let status = serde_json::json!({ "status": { - "phase": patch.phase, - "backend": patch.backend, - "artifactPath": patch.artifact, - "enhancedPrompt": patch.enhanced_prompt, - "message": patch.message, + "phase": phase, + "backend": backend, + "artifactPath": artifact, + "message": message, + "enhancedPrompt": serde_json::Value::Null, } }); + // Keep enhanced prompt if provided via message channel separately — simplify: + let status = if let Some(ref art) = artifact { + serde_json::json!({ + "status": { + "phase": phase, + "backend": backend, + "artifactPath": art, + "message": message, + } + }) + } else { + status + }; api.patch_status(name, &PatchParams::default(), &Patch::Merge(&status)) .await .map_err(Error::Kube)?; diff --git a/crates/freya-operator/src/reconcile/mod.rs b/crates/freya-operator/src/reconcile/mod.rs index 2f53b93..a2044fd 100644 --- a/crates/freya-operator/src/reconcile/mod.rs +++ b/crates/freya-operator/src/reconcile/mod.rs @@ -1,5 +1,4 @@ pub mod asset; -pub mod credentials; pub mod generation; pub mod studio; pub mod worker; @@ -24,86 +23,9 @@ pub fn default_ui_image() -> (String, String) { ) } -pub fn default_mcp_image() -> (String, String) { - ( - "harbor.dataknife.net/library/freya-mcp".into(), - "0.1.0".into(), - ) -} - pub fn default_worker_image() -> (String, String) { ( "harbor.dataknife.net/library/freya-diffusion-worker".into(), "0.1.0".into(), ) } - -/// True when a worker URL is loopback, private, link-local, or cluster DNS. -/// Public hostnames keep certificate verification. Same rule as freya-api. -pub fn tls_skip_allowed(endpoint: &str) -> bool { - let Ok(url) = reqwest::Url::parse(endpoint.trim()) else { - return false; - }; - let Some(host) = url.host_str() else { - return false; - }; - host_is_local_or_private(host) -} - -fn host_is_local_or_private(host: &str) -> bool { - let h = host - .trim() - .trim_matches(['[', ']']) - .trim_end_matches('.') - .to_ascii_lowercase(); - if h.is_empty() - || h == "localhost" - || h.ends_with(".localhost") - || h.ends_with(".local") - || h.ends_with(".cluster.local") - || h.ends_with(".svc") - || !h.contains('.') - { - return true; - } - match h.parse::() { - Ok(std::net::IpAddr::V4(ip)) => ipv4_local(ip), - Ok(std::net::IpAddr::V6(ip)) => ipv6_local(ip), - Err(_) => false, - } -} - -fn ipv4_local(ip: std::net::Ipv4Addr) -> bool { - let [a, b, _, _] = ip.octets(); - ip.is_loopback() - || ip.is_link_local() - || ip.is_broadcast() - || a == 0 - || a == 10 - || (a == 172 && (16..=31).contains(&b)) - || (a == 192 && b == 168) -} - -fn ipv6_local(ip: std::net::Ipv6Addr) -> bool { - if ip.is_loopback() || ip.is_unicast_link_local() { - return true; - } - let o = ip.octets(); - (o[0] & 0xfe) == 0xfc -} - -#[cfg(test)] -mod tests { - use super::tls_skip_allowed; - - #[test] - fn public_https_does_not_skip_verify() { - assert!(!tls_skip_allowed("https://vllm.dataknife.net")); - assert!(tls_skip_allowed("https://192.168.3.125:8091")); - assert!(tls_skip_allowed("https://127.0.0.1:8091")); - assert!(tls_skip_allowed( - "https://freya-gpu.freya.svc.cluster.local:8091" - )); - assert!(tls_skip_allowed("http://freya-worker:8091")); - } -} diff --git a/crates/freya-operator/src/reconcile/studio.rs b/crates/freya-operator/src/reconcile/studio.rs index 088dadb..de65770 100644 --- a/crates/freya-operator/src/reconcile/studio.rs +++ b/crates/freya-operator/src/reconcile/studio.rs @@ -1,22 +1,21 @@ -//! Reconcile FreyaStudio → API/UI/MCP Deployments, Services, gallery PVC, optional Ingress. +//! Reconcile FreyaStudio → API/UI Deployments, Services, gallery PVC, optional Ingress. use crate::reconcile::{ - default_api_image, default_mcp_image, default_ui_image, LABEL_COMPONENT, LABEL_INSTANCE, - LABEL_MANAGED, LABEL_NAME, MANAGED_BY, + default_api_image, default_ui_image, LABEL_COMPONENT, LABEL_INSTANCE, LABEL_MANAGED, + LABEL_NAME, MANAGED_BY, }; use crate::Ctx; -use freya_crd::{FreyaDiffusionWorker, FreyaStudio, WorkerPlacement}; +use freya_crd::FreyaStudio; use k8s_openapi::api::apps::v1::{Deployment, DeploymentSpec}; use k8s_openapi::api::core::v1::{ Container, ContainerPort, EnvVar, EnvVarSource, PersistentVolumeClaim, PersistentVolumeClaimSpec, PersistentVolumeClaimVolumeSource, PodSpec, PodTemplateSpec, - SecretKeySelector, Service, ServiceAccount, ServicePort, ServiceSpec, Volume, VolumeMount, + SecretKeySelector, Service, ServicePort, ServiceSpec, Volume, VolumeMount, }; use k8s_openapi::api::networking::v1::{ HTTPIngressPath, HTTPIngressRuleValue, Ingress, IngressBackend, IngressRule, - IngressServiceBackend, IngressSpec, IngressTLS, ServiceBackendPort, + IngressServiceBackend, IngressSpec, ServiceBackendPort, }; -use k8s_openapi::api::rbac::v1::{PolicyRule, Role, RoleBinding, RoleRef, Subject}; use k8s_openapi::apimachinery::pkg::apis::meta::v1::{LabelSelector, ObjectMeta, OwnerReference}; use k8s_openapi::apimachinery::pkg::util::intstr::IntOrString; use kube::api::{Patch, PatchParams}; @@ -33,106 +32,22 @@ pub async fn reconcile(studio: Arc, ctx: Arc) -> Result Result<(String, Option, bool), Error> { - let workers: Api = Api::namespaced(ctx.client.clone(), ns); - let worker = workers.get(worker_name).await.map_err(Error::Kube)?; - let url = match worker.spec.placement { - WorkerPlacement::External => worker - .spec - .external_endpoint - .clone() - .or_else(|| worker.status.as_ref().and_then(|s| s.endpoint.clone())) - .ok_or(Error::MissingWorkerEndpoint)?, - WorkerPlacement::InCluster => format!( - "http://{worker_name}.{ns}.svc.cluster.local:{}", - worker.spec.port - ), - }; - let tls_insecure = worker - .annotations() - .get(TLS_INSECURE_ANNOTATION) - .map(|v| v.eq_ignore_ascii_case("true") || v == "1") - .unwrap_or(false); - Ok((url, worker.spec.auth_secret_ref.clone(), tls_insecure)) -} - -/// Ingress host plus in-cluster Service DNS and port-forward loopback. -/// Empty or `*` on the MCP process is loopback only, so this list is explicit. -fn mcp_allowed_hosts(studio: &FreyaStudio, name: &str, ns: &str) -> String { - let svc = format!("{name}-mcp"); - let mut hosts = vec![ - svc.clone(), - format!("{svc}.{ns}"), - format!("{svc}.{ns}.svc"), - format!("{svc}.{ns}.svc.cluster.local"), - "localhost".into(), - "127.0.0.1".into(), - "::1".into(), - ]; - if let Some(host) = studio - .spec - .ingress - .host - .as_deref() - .map(str::trim) - .filter(|h| !h.is_empty()) - { - hosts.push(host.to_string()); - } - hosts.join(",") -} - fn labels(instance: &str, component: &str) -> BTreeMap { BTreeMap::from([ (LABEL_MANAGED.to_string(), MANAGED_BY.to_string()), @@ -227,7 +142,6 @@ async fn ensure_api_deployment( name: &str, studio: &FreyaStudio, owner: &OwnerReference, - creds: &crate::reconcile::credentials::StudioCredentials, ) -> Result<(), Error> { let (repo, tag, pull) = image_parts(&studio.spec.api_image, default_api_image()); let image = format!("{repo}:{tag}"); @@ -241,12 +155,6 @@ async fn ensure_api_deployment( value: Some("/data/gallery".into()), ..Default::default() }, - // Keep UI-rotated API token (+ provider keys) on the gallery PVC across pod restarts. - EnvVar { - name: "FREYA_SECRETS_FILE".into(), - value: Some("/data/gallery/.freya-runtime.json".into()), - ..Default::default() - }, EnvVar { name: "FREYA_PACKS_DIR".into(), value: Some("/packs".into()), @@ -267,86 +175,18 @@ async fn ensure_api_deployment( value: Some(studio.spec.open_router.image_model.clone()), ..Default::default() }, - EnvVar { - name: "FREYA_ROUTER_MODEL".into(), - value: Some(studio.spec.open_router.router_model.clone()), - ..Default::default() - }, secret_env("OPENROUTER_API_KEY", secret, false), ]; - if let Some(ref worker_name) = studio.spec.diffusion_worker_ref { + if let Some(ref worker) = studio.spec.diffusion_worker_ref { env.push(EnvVar { name: "FREYA_DIFFUSION_WORKER_REF".into(), - value: Some(worker_name.clone()), + value: Some(worker.clone()), ..Default::default() }); - let (worker_url, worker_auth, tls_insecure) = resolve_worker(ctx, ns, worker_name).await?; env.push(EnvVar { name: "FREYA_DIFFUSION_WORKER_URL".into(), - value: Some(worker_url.clone()), - ..Default::default() - }); - if tls_insecure && super::tls_skip_allowed(&worker_url) { - env.push(EnvVar { - name: "FREYA_WORKER_TLS_INSECURE".into(), - value: Some("true".into()), - ..Default::default() - }); - } else if tls_insecure { - warn!( - %worker_url, - "ignoring freya.dataknife.ai/tls-insecure on a public worker URL" - ); - } - if let Some(ref auth) = worker_auth { - env.push(secret_env("FREYA_WORKER_TOKEN", auth, true)); - } - } - - if let Some(ref admin_sec) = creds.admin_secret_name { - env.push(EnvVar { - name: "FREYA_ADMIN_USER".into(), - value_from: Some(EnvVarSource { - secret_key_ref: Some(SecretKeySelector { - name: admin_sec.clone(), - key: freya_crd::SECRET_KEY_ADMIN_USERNAME.into(), - optional: Some(true), - }), - ..Default::default() - }), - ..Default::default() - }); - env.push(EnvVar { - name: "FREYA_ADMIN_PASSWORD".into(), - value_from: Some(EnvVarSource { - secret_key_ref: Some(SecretKeySelector { - name: admin_sec.clone(), - key: freya_crd::SECRET_KEY_ADMIN_PASSWORD.into(), - optional: Some(false), - }), - ..Default::default() - }), - ..Default::default() - }); - } - - if let Some(ref api_tok) = creds.api_token { - env.push(secret_env("FREYA_API_TOKEN", api_tok, false)); - // POST /v1/auth/token patches this Secret so MCP/env stay aligned after UI rotate. - env.push(EnvVar { - name: "FREYA_API_TOKEN_SECRET_NAME".into(), - value: Some(api_tok.name.clone()), - ..Default::default() - }); - env.push(EnvVar { - name: "FREYA_API_TOKEN_SECRET_KEY".into(), - value: Some(api_tok.key.clone()), - ..Default::default() - }); - env.push(EnvVar { - name: "FREYA_NAMESPACE".into(), - value: Some(ns.to_string()), + value: Some(format!("http://{worker}.{ns}.svc.cluster.local:8091")), ..Default::default() }); } @@ -397,7 +237,6 @@ async fn ensure_api_deployment( ..Default::default() }), spec: Some(PodSpec { - service_account_name: Some(format!("{name}-api")), containers: vec![Container { name: "api".into(), image: Some(image), @@ -442,101 +281,6 @@ async fn ensure_api_deployment( Ok(()) } -/// ServiceAccount + Role so freya-api can patch `apiTokenSecretRef` after UI rotate. -async fn ensure_api_token_sync_rbac( - ctx: &Ctx, - ns: &str, - name: &str, - studio: &FreyaStudio, - owner: &OwnerReference, - api_tok: Option<&freya_crd::SecretKeyRef>, -) -> Result<(), Error> { - let _ = studio; - let sa_name = format!("{name}-api"); - let role_name = format!("{name}-api-token-sync"); - - let sa = ServiceAccount { - metadata: ObjectMeta { - name: Some(sa_name.clone()), - namespace: Some(ns.to_string()), - labels: Some(labels(name, "api")), - owner_references: Some(vec![owner.clone()]), - ..Default::default() - }, - ..Default::default() - }; - let sa_api: Api = Api::namespaced(ctx.client.clone(), ns); - sa_api - .patch( - &sa_name, - &PatchParams::apply(MANAGED_BY).force(), - &Patch::Apply(&sa), - ) - .await - .map_err(Error::Kube)?; - - let Some(api_tok) = api_tok else { - return Ok(()); - }; - - let role = Role { - metadata: ObjectMeta { - name: Some(role_name.clone()), - namespace: Some(ns.to_string()), - labels: Some(labels(name, "api")), - owner_references: Some(vec![owner.clone()]), - ..Default::default() - }, - rules: Some(vec![PolicyRule { - api_groups: Some(vec!["".into()]), - resources: Some(vec!["secrets".into()]), - resource_names: Some(vec![api_tok.name.clone()]), - verbs: vec!["get".into(), "patch".into(), "update".into()], - ..Default::default() - }]), - }; - let role_api: Api = Api::namespaced(ctx.client.clone(), ns); - role_api - .patch( - &role_name, - &PatchParams::apply(MANAGED_BY).force(), - &Patch::Apply(&role), - ) - .await - .map_err(Error::Kube)?; - - let binding = RoleBinding { - metadata: ObjectMeta { - name: Some(role_name.clone()), - namespace: Some(ns.to_string()), - labels: Some(labels(name, "api")), - owner_references: Some(vec![owner.clone()]), - ..Default::default() - }, - role_ref: RoleRef { - api_group: "rbac.authorization.k8s.io".into(), - kind: "Role".into(), - name: role_name.clone(), - }, - subjects: Some(vec![Subject { - kind: "ServiceAccount".into(), - name: sa_name, - namespace: Some(ns.to_string()), - ..Default::default() - }]), - }; - let rb_api: Api = Api::namespaced(ctx.client.clone(), ns); - rb_api - .patch( - &role_name, - &PatchParams::apply(MANAGED_BY).force(), - &Patch::Apply(&binding), - ) - .await - .map_err(Error::Kube)?; - Ok(()) -} - async fn ensure_ui_deployment( ctx: &Ctx, ns: &str, @@ -578,8 +322,7 @@ async fn ensure_ui_deployment( ..Default::default() }]), env: Some(vec![EnvVar { - // Consumed by nginx envsubst template → upstream for /v1/. - name: "FREYA_API_UPSTREAM".into(), + name: "FREYA_API_URL".into(), value: Some(format!("http://{name}-api:8080")), ..Default::default() }]), @@ -604,92 +347,6 @@ async fn ensure_ui_deployment( Ok(()) } -/// Stateless MCP proxy: Streamable HTTP at `/mcp`, talks to in-cluster API. -async fn ensure_mcp_deployment( - ctx: &Ctx, - ns: &str, - name: &str, - studio: &FreyaStudio, - owner: &OwnerReference, - api_tok: Option<&freya_crd::SecretKeyRef>, -) -> Result<(), Error> { - let (repo, tag, pull) = image_parts(&studio.spec.mcp_image, default_mcp_image()); - let image = format!("{repo}:{tag}"); - let dep_name = format!("{name}-mcp"); - - // Host allowlist is the Ingress host when one is set. Callers still need the API bearer. - let mut env = vec![ - EnvVar { - name: "FREYA_API_URL".into(), - value: Some(format!("http://{name}-api:8080")), - ..Default::default() - }, - EnvVar { - name: "FREYA_MCP_BIND".into(), - value: Some("0.0.0.0:8090".into()), - ..Default::default() - }, - EnvVar { - name: "FREYA_MCP_ALLOWED_HOSTS".into(), - value: Some(mcp_allowed_hosts(studio, name, ns)), - ..Default::default() - }, - ]; - if let Some(api_tok) = api_tok { - env.push(secret_env("FREYA_API_TOKEN", api_tok, false)); - } - - let dep = Deployment { - metadata: ObjectMeta { - name: Some(dep_name.clone()), - namespace: Some(ns.to_string()), - labels: Some(labels(name, "mcp")), - owner_references: Some(vec![owner.clone()]), - ..Default::default() - }, - spec: Some(DeploymentSpec { - replicas: Some(studio.spec.replicas), - selector: LabelSelector { - match_labels: Some(labels(name, "mcp")), - ..Default::default() - }, - template: PodTemplateSpec { - metadata: Some(ObjectMeta { - labels: Some(labels(name, "mcp")), - ..Default::default() - }), - spec: Some(PodSpec { - containers: vec![Container { - name: "mcp".into(), - image: Some(image), - image_pull_policy: Some(pull), - ports: Some(vec![ContainerPort { - container_port: 8090, - name: Some("http".into()), - ..Default::default() - }]), - env: Some(env), - ..Default::default() - }], - ..Default::default() - }), - }, - ..Default::default() - }), - ..Default::default() - }; - - let api: Api = Api::namespaced(ctx.client.clone(), ns); - api.patch( - &dep_name, - &PatchParams::apply(MANAGED_BY).force(), - &Patch::Apply(&dep), - ) - .await - .map_err(Error::Kube)?; - Ok(()) -} - async fn ensure_service( ctx: &Ctx, ns: &str, @@ -743,95 +400,50 @@ async fn ensure_ingress( .host .clone() .unwrap_or_else(|| format!("{name}.freya.local")); - let tls = studio.spec.ingress.tls_secret_name.as_ref().map(|secret| { - vec![IngressTLS { - hosts: Some(vec![host.clone()]), - secret_name: Some(secret.clone()), - }] - }); - - // SSE / Streamable HTTP: disable buffering and extend timeouts for MCP. - let mut annotations = BTreeMap::from([( - "nginx.ingress.kubernetes.io/ssl-redirect".into(), - "true".into(), - )]); - if studio.spec.mcp_enabled { - annotations.insert( - "nginx.ingress.kubernetes.io/proxy-buffering".into(), - "off".into(), - ); - annotations.insert( - "nginx.ingress.kubernetes.io/proxy-read-timeout".into(), - "3600".into(), - ); - annotations.insert( - "nginx.ingress.kubernetes.io/proxy-send-timeout".into(), - "3600".into(), - ); - } - - // Longest / most-specific Prefix paths first so `/mcp` is not swallowed by `/`. - let mut paths = Vec::new(); - if studio.spec.mcp_enabled { - paths.push(HTTPIngressPath { - path: Some("/mcp".into()), - path_type: "Prefix".into(), - backend: IngressBackend { - service: Some(IngressServiceBackend { - name: format!("{name}-mcp"), - port: Some(ServiceBackendPort { - number: Some(8090), - ..Default::default() - }), - }), - ..Default::default() - }, - }); - } - paths.push(HTTPIngressPath { - path: Some("/api".into()), - path_type: "Prefix".into(), - backend: IngressBackend { - service: Some(IngressServiceBackend { - name: format!("{name}-api"), - port: Some(ServiceBackendPort { - number: Some(8080), - ..Default::default() - }), - }), - ..Default::default() - }, - }); - paths.push(HTTPIngressPath { - path: Some("/".into()), - path_type: "Prefix".into(), - backend: IngressBackend { - service: Some(IngressServiceBackend { - name: format!("{name}-ui"), - port: Some(ServiceBackendPort { - number: Some(80), - ..Default::default() - }), - }), - ..Default::default() - }, - }); - let ing = Ingress { metadata: ObjectMeta { name: Some(name.to_string()), namespace: Some(ns.to_string()), labels: Some(labels(name, "ingress")), owner_references: Some(vec![owner.clone()]), - annotations: Some(annotations), ..Default::default() }, spec: Some(IngressSpec { ingress_class_name: studio.spec.ingress.class_name.clone(), - tls, rules: Some(vec![IngressRule { host: Some(host), - http: Some(HTTPIngressRuleValue { paths }), + http: Some(HTTPIngressRuleValue { + paths: vec![ + HTTPIngressPath { + path: Some("/api".into()), + path_type: "Prefix".into(), + backend: IngressBackend { + service: Some(IngressServiceBackend { + name: format!("{name}-api"), + port: Some(ServiceBackendPort { + number: Some(8080), + ..Default::default() + }), + }), + ..Default::default() + }, + }, + HTTPIngressPath { + path: Some("/".into()), + path_type: "Prefix".into(), + backend: IngressBackend { + service: Some(IngressServiceBackend { + name: format!("{name}-ui"), + port: Some(ServiceBackendPort { + number: Some(80), + ..Default::default() + }), + }), + ..Default::default() + }, + }, + ], + }), }]), ..Default::default() }), @@ -855,32 +467,15 @@ async fn patch_status( phase: &str, api_endpoint: &str, ui_endpoint: &str, - mcp_endpoint: Option<&str>, - creds: &crate::reconcile::credentials::StudioCredentials, ) -> Result<(), Error> { let api: Api = Api::namespaced(ctx.client.clone(), ns); - let mut status_body = serde_json::json!({ - "phase": phase, - "apiEndpoint": api_endpoint, - "uiEndpoint": ui_endpoint, - "adminCredentialsGenerated": creds.admin_generated, + let status = serde_json::json!({ + "status": { + "phase": phase, + "apiEndpoint": api_endpoint, + "uiEndpoint": ui_endpoint, + } }); - if let Some(mcp) = mcp_endpoint { - status_body["mcpEndpoint"] = serde_json::Value::String(mcp.to_string()); - } else { - status_body["mcpEndpoint"] = serde_json::Value::Null; - } - if let Some(ref admin) = creds.admin_secret_name { - status_body["adminCredentialsSecretName"] = serde_json::Value::String(admin.clone()); - } else { - status_body["adminCredentialsSecretName"] = serde_json::Value::Null; - } - if let Some(ref tok) = creds.api_token { - status_body["apiTokenSecretName"] = serde_json::Value::String(tok.name.clone()); - } else { - status_body["apiTokenSecretName"] = serde_json::Value::Null; - } - let status = serde_json::json!({ "status": status_body }); api.patch_status(name, &PatchParams::default(), &Patch::Merge(&status)) .await .map_err(Error::Kube)?; @@ -898,8 +493,6 @@ pub enum Error { MissingNamespace, #[error("owner reference")] OwnerRef, - #[error("diffusion worker missing externalEndpoint")] - MissingWorkerEndpoint, #[error("kube: {0}")] Kube(#[from] kube::Error), } diff --git a/crates/freya-operator/src/reconcile/worker.rs b/crates/freya-operator/src/reconcile/worker.rs index 48658d2..d312a21 100644 --- a/crates/freya-operator/src/reconcile/worker.rs +++ b/crates/freya-operator/src/reconcile/worker.rs @@ -1,4 +1,4 @@ -//! Reconcile FreyaDiffusionWorker — external URL (recommended) or optional in-cluster GPU. +//! Reconcile FreyaDiffusionWorker — in-cluster GPU Deployment or external remote endpoint. use crate::reconcile::{ default_worker_image, LABEL_COMPONENT, LABEL_INSTANCE, LABEL_MANAGED, LABEL_NAME, MANAGED_BY, @@ -161,47 +161,23 @@ async fn ensure_deployment( name: Some("http".into()), ..Default::default() }]), - env: Some({ - let mut env = vec![ - EnvVar { - name: "FREYA_WORKER_MODEL".into(), - value: Some(worker.spec.model.clone()), - ..Default::default() - }, - EnvVar { - name: "FREYA_WORKER_PORT".into(), - value: Some(port.to_string()), - ..Default::default() - }, - EnvVar { - name: "FREYA_MODELS_DIR".into(), - value: Some("/models".into()), - ..Default::default() - }, - ]; - if let Some(ref auth) = worker.spec.auth_secret_ref { - env.push(EnvVar { - name: "FREYA_WORKER_TOKEN".into(), - value_from: Some(k8s_openapi::api::core::v1::EnvVarSource { - secret_key_ref: Some( - k8s_openapi::api::core::v1::SecretKeySelector { - name: auth.name.clone(), - key: auth.key.clone(), - optional: Some(false), - }, - ), - ..Default::default() - }), - ..Default::default() - }); - } else { - warn!( - worker = %name, - "authSecretRef unset — worker /v1 routes are open on the cluster network" - ); - } - env - }), + env: Some(vec![ + EnvVar { + name: "FREYA_WORKER_MODEL".into(), + value: Some(worker.spec.model.clone()), + ..Default::default() + }, + EnvVar { + name: "FREYA_WORKER_PORT".into(), + value: Some(port.to_string()), + ..Default::default() + }, + EnvVar { + name: "FREYA_MODELS_DIR".into(), + value: Some("/models".into()), + ..Default::default() + }, + ]), resources: Some(resources), volume_mounts: Some(vec![VolumeMount { name: "models".into(), diff --git a/crates/freya-worker/Cargo.toml b/crates/freya-worker/Cargo.toml index dc068b9..2190d0d 100644 --- a/crates/freya-worker/Cargo.toml +++ b/crates/freya-worker/Cargo.toml @@ -3,7 +3,7 @@ name = "freya-worker" version.workspace = true edition.workspace = true license.workspace = true -description = "Freya diffusion worker (OpenAI images API + LoRA/checkpoint install; GPU via Diffusers engine)" +description = "Minimal Freya diffusion worker stub (OpenAI images API + LoRA install)" [[bin]] name = "freya-worker" @@ -22,4 +22,3 @@ tracing = { workspace = true } tracing-subscriber = { workspace = true } reqwest = { workspace = true } uuid = { workspace = true } -libc = "0.2" diff --git a/crates/freya-worker/src/main.rs b/crates/freya-worker/src/main.rs index 77b426f..3eb4999 100644 --- a/crates/freya-worker/src/main.rs +++ b/crates/freya-worker/src/main.rs @@ -1,30 +1,18 @@ -//! Freya diffusion worker: OpenAI-compatible images + asset install. -//! GPU path: Diffusers engine at `FREYA_ENGINE_URL` (see `deploy/worker/`, -//! `Dockerfile.worker`). Without an engine, generate falls back to a stub PNG -//! for wiring tests. vLLM-Omni remains the CRD engine label for external swaps. +//! Minimal diffusion worker: OpenAI-compatible images + asset install for Freya. +//! Production: replace with vLLM-Omni. This stub enables LoRA install + API wiring. -use axum::extract::{Path as PathParam, Request, State}; -use axum::http::{header, StatusCode}; -use axum::middleware::{self, Next}; -use axum::response::Response; -use axum::routing::{delete, get, post}; +use axum::extract::State; +use axum::routing::{get, post}; use axum::{Json, Router}; use base64::Engine; use clap::Parser; -use serde::{Deserialize, Serialize}; -use serde_json::{json, Value}; -use std::collections::{HashMap, VecDeque}; -use std::path::{Component, Path, PathBuf}; -use std::sync::atomic::{AtomicBool, Ordering}; +use serde::Deserialize; +use serde_json::json; +use std::path::PathBuf; use std::sync::Arc; -use std::time::{Instant, SystemTime, UNIX_EPOCH}; use tokio::fs; -use tokio::io::AsyncWriteExt; -use tokio::process::Command; -use tokio::sync::{mpsc, Mutex, RwLock, Semaphore}; use tower_http::trace::TraceLayer; -use tracing::{info, warn}; -use uuid::Uuid; +use tracing::info; #[derive(Parser, Clone)] struct Config { @@ -32,95 +20,11 @@ struct Config { port: u16, #[arg(long, env = "FREYA_MODELS_DIR", default_value = "./data/models")] models_dir: PathBuf, - /// Host path for the models bind-mount (UI hint). Empty = unknown. - #[arg(long, env = "FREYA_MODELS_HOST_DIR", default_value = "")] - models_dir_host: String, - /// Optional default / active base (HF id or relative path under models dir). - #[arg(long, env = "FREYA_WORKER_MODEL", default_value = "")] - model: String, - /// Optional bearer token for `/v1/*`. Empty = open (local/dev only). - #[arg(long, env = "FREYA_WORKER_TOKEN", default_value = "")] - token: String, - /// Diffusers (or compatible) engine base URL. Empty = stub PNG generate. - #[arg(long, env = "FREYA_ENGINE_URL", default_value = "")] - engine_url: String, } -#[derive(Clone, Debug, Serialize, Deserialize, Default)] -#[serde(rename_all = "camelCase")] -struct ActiveBase { - /// HF id or relative path e.g. `checkpoints/foo.safetensors`. - #[serde(default)] - model: String, - /// Civitai-style family label when known (SDXL 1.0, Pony, …). - #[serde(default)] - base_model: Option, -} - -#[derive(Clone, Debug, Serialize)] -#[serde(rename_all = "camelCase")] -struct InstallJob { - id: String, - status: String, - url: String, - dest_path: String, - #[serde(skip_serializing_if = "Option::is_none")] - name: Option, - #[serde(skip_serializing_if = "Option::is_none")] - base_model: Option, - #[serde(skip_serializing_if = "Option::is_none")] - model_type: Option, - #[serde(skip_serializing_if = "Option::is_none")] - source: Option, - bytes_done: u64, - #[serde(skip_serializing_if = "Option::is_none")] - bytes_total: Option, - #[serde(skip_serializing_if = "Option::is_none")] - percent: Option, - #[serde(skip_serializing_if = "Option::is_none")] - error: Option, - created_at: u64, - updated_at: u64, -} - -struct JobEntry { - job: InstallJob, - cancel: Arc, - /// Auth token kept out of serialized job state. - auth_token: Option, - version_id: Option, - model_id: Option, - thumbnail_url: Option, -} - -struct JobStore { - jobs: HashMap, - /// Newest-first ids for list (cap recent history). - recent: VecDeque, -} - -const JOB_HISTORY_CAP: usize = 100; - #[derive(Clone)] struct App { models_dir: PathBuf, - /// Optional host bind-mount path (FREYA_MODELS_HOST_DIR) for UI. - models_dir_host: Option, - token: String, - /// Empty = stub generate (no GPU). Set by GPU image entrypoint. - engine_url: String, - started: Instant, - active: Arc>, - http: reqwest::Client, - jobs: Arc>, - job_tx: mpsc::UnboundedSender, -} - -fn now_unix() -> u64 { - SystemTime::now() - .duration_since(UNIX_EPOCH) - .map(|d| d.as_secs()) - .unwrap_or(0) } #[tokio::main] @@ -132,857 +36,59 @@ async fn main() -> anyhow::Result<()> { ) .init(); let cfg = Config::parse(); - if cfg.token.trim().is_empty() { - warn!( - "FREYA_WORKER_TOKEN unset — /v1 routes are open (local/dev only). \ - Set FreyaDiffusionWorker authSecretRef in-cluster." - ); - } else { - info!("FREYA_WORKER_TOKEN set — bearer auth required on /v1 routes"); - } fs::create_dir_all(cfg.models_dir.join("loras")).await?; fs::create_dir_all(cfg.models_dir.join("checkpoints")).await?; - let active = load_active_base(&cfg.models_dir, cfg.model.trim()).await; - if !active.model.is_empty() { - info!( - model = %active.model, - base = ?active.base_model, - "active base model" - ); - } - let engine_url = cfg.engine_url.trim().trim_end_matches('/').to_string(); - let engine_label = if engine_url.is_empty() { - "stub" - } else { - "diffusers" - }; - if engine_url.is_empty() { - warn!("FREYA_ENGINE_URL unset — generate returns stub PNGs (no GPU weights)"); - } else { - info!(%engine_url, "FREYA_ENGINE_URL set — generate proxies to Diffusers engine"); - } - let models_dir_host = { - let h = cfg.models_dir_host.trim(); - if h.is_empty() { - None - } else { - Some(h.to_string()) - } - }; - let (job_tx, job_rx) = mpsc::unbounded_channel::(); - let jobs = Arc::new(Mutex::new(JobStore { - jobs: HashMap::new(), - recent: VecDeque::new(), - })); let state = Arc::new(App { models_dir: cfg.models_dir.clone(), - models_dir_host, - token: cfg.token.trim().to_string(), - engine_url, - started: Instant::now(), - active: Arc::new(RwLock::new(active)), - http: reqwest::Client::builder() - .timeout(std::time::Duration::from_secs(600)) - .build() - .expect("reqwest client"), - jobs: jobs.clone(), - job_tx, }); - spawn_job_worker(state.clone(), job_rx); - let protected = Router::new() + let app = Router::new() + .route("/health", get(|| async { Json(json!({"ok": true})) })) .route("/v1/loras", get(list_loras)) - .route("/v1/checkpoints", get(list_checkpoints)) - .route("/v1/embeddings", get(list_embeddings)) - .route("/v1/vae", get(list_vaes)) - .route( - "/v1/base-model", - get(get_base_model).put(put_base_model), - ) - .route("/v1/stats", get(stats)) .route("/v1/images/generations", post(generate)) - .route("/v1/videos/generations", post(generate_video)) .route("/v1/assets/install", post(install)) - .route("/v1/assets/jobs", get(list_jobs).post(enqueue_install)) - .route("/v1/assets/jobs/clear", post(clear_jobs)) - .route("/v1/assets/jobs/{id}", get(get_job)) - .route("/v1/assets/jobs/{id}/cancel", post(cancel_job)) - .route("/v1/assets", delete(delete_asset)) - .route_layer(middleware::from_fn_with_state( - state.clone(), - require_worker_token, - )); - let app = Router::new() - .route("/health", get(health)) - .merge(protected) .layer(TraceLayer::new_for_http()) .with_state(state); let bind = format!("0.0.0.0:{}", cfg.port); - info!( - %bind, - models = %cfg.models_dir.display(), - engine = %engine_label, - "freya-worker listening (checkpoints + LoRAs on disk; GPU via FREYA_ENGINE_URL)" - ); + info!(%bind, models = %cfg.models_dir.display(), "freya-worker listening (stub — swap for vLLM-Omni in prod)"); let listener = tokio::net::TcpListener::bind(&bind).await?; axum::serve(listener, app).await?; Ok(()) } -async fn load_active_base(models_dir: &Path, env_model: &str) -> ActiveBase { - let path = models_dir.join("active-base.json"); - if let Ok(bytes) = fs::read(&path).await { - if let Ok(mut a) = serde_json::from_slice::(&bytes) { - if a.model.is_empty() && !env_model.is_empty() { - a.model = env_model.to_string(); - } - return a; - } - } - ActiveBase { - model: env_model.to_string(), - base_model: None, - } -} - -async fn persist_active_base(models_dir: &Path, active: &ActiveBase) -> Result<(), String> { - let path = models_dir.join("active-base.json"); - let bytes = serde_json::to_vec_pretty(active).map_err(|e| e.to_string())?; - fs::write(&path, bytes) - .await - .map_err(|e| format!("write active-base.json: {e}")) -} - -/// Liveness for probes. GPU, disk, and inventory are on authenticated `GET /v1/stats`. -async fn health() -> Json { - Json(serde_json::json!({ "ok": true, "service": "freya-worker" })) -} - -/// GPU, disk, and model inventory. Requires the worker token when one is set. -async fn stats(State(app): State>) -> Json { - Json(build_stats(&app).await) -} - -async fn build_stats(app: &App) -> Value { - let loras = count_weight_files(&app.models_dir.join("loras")).await; - let checkpoints = count_weight_files(&app.models_dir.join("checkpoints")).await; - let (vram, host) = collect_gpu_stats().await; - let active = app.active.read().await.clone(); - let engine = engine_health(app).await; - let (loaded_in_vram, engine_name) = match &engine { - Some(e) => ( - e.get("loadedInVram").and_then(|v| v.as_bool()).unwrap_or(false), - e.get("engine") - .and_then(|v| v.as_str()) - .unwrap_or("diffusers") - .to_string(), - ), - None if !app.engine_url.is_empty() => (false, "diffusers-unreachable".into()), - None => (false, "stub".into()), - }; - let model_loaded = if active.model.is_empty() { - Value::Null - } else { - json!({ - "model": active.model, - "baseModel": active.base_model, - "loadedInVram": loaded_in_vram, - "engine": engine_name, - }) - }; - let disk = collect_path_disk(&app.models_dir); - json!({ - "ok": true, - "modelsDir": app.models_dir.display().to_string(), - "modelsDirHost": app.models_dir_host.clone(), - "loras": loras, - "checkpoints": checkpoints, - "uptimeSec": app.started.elapsed().as_secs(), - "modelLoaded": model_loaded, - "engine": engine, - "vram": vram, - "host": host, - "disk": disk, - "layout": { - "loras": "loras/*.safetensors (+ optional *.safetensors.meta.json)", - "checkpoints": "checkpoints/*.safetensors (+ optional *.meta.json)", - "activeBase": "active-base.json", - }, - "vramBehavior": "on-demand load during generate; unload after unless FREYA_ENGINE_KEEP_LOADED=1", - }) -} - -/// df-style capacity for `FREYA_MODELS_DIR` via statvfs. -fn collect_path_disk(path: &Path) -> Value { - use std::ffi::CString; - let probe = if path.exists() { - path.to_path_buf() - } else if let Some(parent) = path.parent() { - parent.to_path_buf() - } else { - return Value::Null; - }; - let Some(s) = probe.to_str() else { - return Value::Null; - }; - let Ok(c_path) = CString::new(s) else { - return Value::Null; - }; - unsafe { - let mut st: libc::statvfs = std::mem::zeroed(); - if libc::statvfs(c_path.as_ptr(), &mut st) != 0 { - return Value::Null; - } - let bsize = st.f_frsize as u64; - if bsize == 0 { - return Value::Null; - } - let total = (st.f_blocks as u64).saturating_mul(bsize); - let free = (st.f_bavail as u64).saturating_mul(bsize); - let free_root = (st.f_bfree as u64).saturating_mul(bsize); - let used = total.saturating_sub(free_root); - let pct = if total > 0 { - ((used as f64 / total as f64) * 100.0).round() as u64 - } else { - 0 - }; - json!({ - "path": path.display().to_string(), - "usedBytes": used, - "freeBytes": free, - "totalBytes": total, - "usedPercent": pct.min(100), - }) - } -} - -async fn engine_health(app: &App) -> Option { - if app.engine_url.is_empty() { - return None; - } - let url = format!("{}/health", app.engine_url); - match app.http.get(&url).send().await { - Ok(resp) if resp.status().is_success() => resp.json::().await.ok(), - _ => None, - } -} - -/// Query NVIDIA GPUs via `nvidia-smi`. Returns `(vram, host)` JSON values (null if unavailable). -async fn collect_gpu_stats() -> (Value, Value) { - let out = Command::new("nvidia-smi") - .args([ - "--query-gpu=index,name,memory.used,memory.total,utilization.gpu", - "--format=csv,noheader,nounits", - ]) - .output() - .await; - let Ok(out) = out else { - return (Value::Null, Value::Null); - }; - if !out.status.success() { - return (Value::Null, Value::Null); - } - let text = String::from_utf8_lossy(&out.stdout); - let mut gpus = Vec::new(); - let mut used_total = 0u64; - let mut mem_total = 0u64; - let mut util_sum = 0u64; - for line in text.lines() { - let parts: Vec<&str> = line.split(',').map(str::trim).collect(); - if parts.len() < 5 { - continue; - } - let index: u64 = parts[0].parse().unwrap_or(0); - let name = parts[1].to_string(); - let used: u64 = parts[2].parse().unwrap_or(0); - let total: u64 = parts[3].parse().unwrap_or(0); - let util: u64 = parts[4].parse().unwrap_or(0); - used_total += used; - mem_total += total; - util_sum += util; - gpus.push(json!({ - "index": index, - "name": name, - "usedMiB": used, - "totalMiB": total, - "utilPercent": util, - })); - } - if gpus.is_empty() { - return (Value::Null, Value::Null); - } - let n = gpus.len() as u64; - let hostname = hostname_string(); - ( - json!({ - "usedMiB": used_total, - "totalMiB": mem_total, - "utilPercent": util_sum / n.max(1), - "gpus": gpus, - }), - json!({ - "hostname": hostname, - "source": "nvidia-smi", - }), - ) -} - -fn hostname_string() -> String { - std::fs::read_to_string("/etc/hostname") - .ok() - .map(|s| s.trim().to_string()) - .filter(|s| !s.is_empty()) - .or_else(|| std::env::var("HOSTNAME").ok()) - .unwrap_or_else(|| "unknown".into()) -} - -async fn count_weight_files(dir: &Path) -> usize { - let dir = dir.to_path_buf(); - tokio::task::spawn_blocking(move || count_weight_files_depth(&dir, 0)) - .await - .unwrap_or(0) -} - -fn count_weight_files_depth(dir: &Path, depth: u32) -> usize { - let Ok(rd) = std::fs::read_dir(dir) else { - return 0; - }; - let mut n = 0usize; - for ent in rd.flatten() { - let name = ent.file_name().to_string_lossy().to_string(); - if name.ends_with(".meta.json") || name.starts_with('.') { - continue; - } - let Ok(ft) = ent.file_type() else { - continue; - }; - if ft.is_file() { - n += 1; - } else if ft.is_dir() && depth < 2 { - // e.g. checkpoints/swarmui/ from optional SwarmUI bind-mount - n += count_weight_files_depth(&ent.path(), depth + 1); - } - } - n -} - -async fn require_worker_token( - State(app): State>, - req: Request, - next: Next, -) -> Result { - if app.token.is_empty() { - return Ok(next.run(req).await); - } - let auth = req - .headers() - .get(header::AUTHORIZATION) - .and_then(|v| v.to_str().ok()) - .unwrap_or(""); - let ok = auth - .strip_prefix("Bearer ") - .map(|t| t == app.token) - .unwrap_or(false); - if !ok { - return Err(StatusCode::UNAUTHORIZED); - } - Ok(next.run(req).await) -} - -#[derive(Debug, Clone, Serialize, Deserialize, Default)] -#[serde(rename_all = "camelCase")] -struct AssetMeta { - #[serde(default)] - name: Option, - #[serde(default)] - base_model: Option, - #[serde(default)] - version_id: Option, - /// Civitai model id when known (distinct from on-disk file stem `id`). - #[serde(default)] - model_id: Option, - #[serde(default)] - model_type: Option, - #[serde(default)] - source: Option, - /// Preview image URL (Civitai) for Installed cards. - #[serde(default)] - thumbnail_url: Option, -} - -async fn read_meta_sidecar(weight_path: &Path) -> Option { - let meta_path = meta_path_for(weight_path); - let bytes = fs::read(&meta_path).await.ok()?; - serde_json::from_slice(&bytes).ok() -} - -fn meta_path_for(weight_path: &Path) -> PathBuf { - let mut s = weight_path.as_os_str().to_os_string(); - s.push(".meta.json"); - PathBuf::from(s) -} - -async fn list_dir_assets(app: &App, subdir: &str, kind: &str) -> Vec { +async fn list_loras(State(app): State>) -> Json { let mut data = Vec::new(); - let dir = app.models_dir.join(subdir); - let Ok(mut rd) = fs::read_dir(&dir).await else { - return data; - }; - while let Ok(Some(ent)) = rd.next_entry().await { - let name = ent.file_name().to_string_lossy().to_string(); - if name.ends_with(".meta.json") || name.starts_with('.') { - continue; + let lora_dir = app.models_dir.join("loras"); + if let Ok(mut rd) = fs::read_dir(&lora_dir).await { + while let Ok(Some(ent)) = rd.next_entry().await { + let name = ent.file_name().to_string_lossy().to_string(); + data.push(json!({ + "id": name, + "name": name, + "kind": "lora", + "path": format!("loras/{name}"), + })); } - let Ok(ft) = ent.file_type().await else { - continue; - }; - if !ft.is_file() { - continue; - } - let path = format!("{subdir}/{name}"); - let full = app.models_dir.join(&path); - let meta = read_meta_sidecar(&full).await.unwrap_or_default(); - let size_bytes = ent.metadata().await.ok().map(|m| m.len()); - let id = name.trim_end_matches(".safetensors").to_string(); - data.push(json!({ - "id": id, - "name": meta.name.unwrap_or_else(|| id.clone()), - "kind": kind, - "path": path, - "baseModel": meta.base_model, - "versionId": meta.version_id, - "modelId": meta.model_id, - "modelType": meta.model_type, - "sizeBytes": size_bytes, - "source": meta.source, - "thumbnailUrl": meta.thumbnail_url, - })); } - data.sort_by(|a, b| { - a.get("id") - .and_then(|x| x.as_str()) - .unwrap_or("") - .cmp(b.get("id").and_then(|x| x.as_str()).unwrap_or("")) - }); - data -} - -async fn list_loras(State(app): State>) -> Json { - Json(json!({ "data": list_dir_assets(&app, "loras", "lora").await })) -} - -async fn list_checkpoints(State(app): State>) -> Json { - Json(json!({ "data": list_dir_assets(&app, "checkpoints", "checkpoint").await })) -} - -async fn list_embeddings(State(app): State>) -> Json { - Json(json!({ "data": list_dir_assets(&app, "embeddings", "embedding").await })) -} - -async fn list_vaes(State(app): State>) -> Json { - Json(json!({ "data": list_dir_assets(&app, "vae", "vae").await })) -} - -async fn get_base_model(State(app): State>) -> Json { - let active = app.active.read().await.clone(); - Json(json!({ - "ok": true, - "model": if active.model.is_empty() { Value::Null } else { json!(active.model) }, - "baseModel": active.base_model, - "modelsDir": app.models_dir.display().to_string(), - "modelsDirHost": app.models_dir_host.clone(), - "note": "Active base for generate; Diffusers engine loads weights into VRAM on demand.", - })) + Json(json!({ "data": data })) } #[derive(Deserialize)] -#[serde(rename_all = "camelCase")] -struct SetBaseReq { - /// HF id or relative path under models dir (e.g. checkpoints/foo.safetensors). - model: String, - #[serde(default)] - base_model: Option, -} - -async fn put_base_model( - State(app): State>, - Json(req): Json, -) -> Result, (StatusCode, Json)> { - let model = req.model.trim().to_string(); - if model.is_empty() { - return Err(( - StatusCode::BAD_REQUEST, - Json(json!({ "error": "model must be non-empty" })), - )); - } - // If it looks like a relative checkpoint path, ensure it stays under models dir. - if model.contains('/') || model.ends_with(".safetensors") { - if let Err(e) = resolve_dest(&app.models_dir, &model) { - return Err((StatusCode::BAD_REQUEST, Json(json!({ "error": e })))); - } - } - let next = ActiveBase { - model: model.clone(), - base_model: req.base_model.filter(|s| !s.trim().is_empty()), - }; - persist_active_base(&app.models_dir, &next) - .await - .map_err(|e| { - ( - StatusCode::INTERNAL_SERVER_ERROR, - Json(json!({ "error": e })), - ) - })?; - *app.active.write().await = next.clone(); - // Drop any previously loaded weights so the next generate picks up the new base. - if !app.engine_url.is_empty() { - let url = format!("{}/v1/unload", app.engine_url); - let _ = app.http.post(&url).send().await; - } - info!(model = %next.model, base = ?next.base_model, "set active base model"); - let engine = if app.engine_url.is_empty() { - "stub" - } else { - "diffusers" - }; - Ok(Json(json!({ - "ok": true, - "model": next.model, - "baseModel": next.base_model, - "loadedInVram": false, - "engine": engine, - }))) -} - -#[derive(Deserialize)] -#[serde(rename_all = "camelCase")] struct GenReq { prompt: String, - #[serde(default)] - model: Option, - #[serde(default)] - lora_request: Option, - #[serde(default)] - size: Option, - #[serde(default)] - seed: Option, - #[serde(default)] - negative_prompt: Option, -} - -#[derive(Deserialize)] -#[serde(rename_all = "camelCase")] -struct VideoGenReq { - prompt: String, - #[serde(default)] - model: Option, - #[serde(default)] - size: Option, - #[serde(default)] - seed: Option, - #[serde(default)] - negative_prompt: Option, - #[serde(default)] - format: Option, - #[serde(default)] - frames: Option, -} - -/// Local motion: multi-frame GIF via Diffusers. True T2V (Wan/LTX) is OpenRouter / SwarmUI. -async fn generate_video( - State(app): State>, - Json(req): Json, -) -> Result, (StatusCode, Json)> { - let fmt = req - .format - .as_deref() - .unwrap_or("gif") - .to_ascii_lowercase(); - if fmt != "gif" { - return Err(( - StatusCode::NOT_IMPLEMENTED, - Json(json!({ - "error": "local worker video supports format=gif only; use OpenRouter for mp4 T2V" - })), - )); - } - let active = app.active.read().await.clone(); - let model = req - .model - .as_deref() - .map(str::trim) - .filter(|s| !s.is_empty()) - .map(|s| s.to_string()) - .or_else(|| { - if active.model.is_empty() { - None - } else { - Some(active.model.clone()) - } - }); - if app.engine_url.is_empty() { - return Err(( - StatusCode::SERVICE_UNAVAILABLE, - Json(json!({ "error": "FREYA_ENGINE_URL unset — no Diffusers engine for local gif" })), - )); - } - let Some(model) = model else { - return Err(( - StatusCode::BAD_REQUEST, - Json(json!({ "error": "no model for local gif" })), - )); - }; - let url = format!("{}/v1/generate_gif", app.engine_url); - let body = json!({ - "prompt": req.prompt, - "model": model, - "baseModel": active.base_model, - "size": req.size, - "seed": req.seed, - "negative_prompt": req.negative_prompt, - "frames": req.frames.unwrap_or(6), - "format": "gif", - }); - info!(model = %model, frames = ?req.frames, "engine gif generate"); - let resp = app - .http - .post(&url) - .json(&body) - .send() - .await - .map_err(|e| { - ( - StatusCode::BAD_GATEWAY, - Json(json!({ "error": format!("engine unreachable: {e}") })), - ) - })?; - let status = resp.status(); - let mut payload: Value = resp.json().await.map_err(|e| { - ( - StatusCode::BAD_GATEWAY, - Json(json!({ "error": format!("engine response: {e}") })), - ) - })?; - if !status.is_success() { - let detail = payload - .get("detail") - .cloned() - .unwrap_or_else(|| json!(payload.to_string())); - return Err(( - StatusCode::from_u16(status.as_u16()).unwrap_or(StatusCode::BAD_GATEWAY), - Json(json!({ "error": detail })), - )); - } - if let Some(obj) = payload.as_object_mut() { - obj.insert("stub".into(), json!(false)); - obj.insert("mime".into(), json!("image/gif")); - } - Ok(Json(payload)) -} - -async fn generate( - State(app): State>, - Json(req): Json, -) -> Result, (StatusCode, Json)> { - let active = app.active.read().await.clone(); - let model = req - .model - .as_deref() - .map(str::trim) - .filter(|s| !s.is_empty()) - .map(|s| s.to_string()) - .or_else(|| { - if active.model.is_empty() { - None - } else { - Some(active.model.clone()) - } - }); - let lora_names: Vec = req - .lora_request - .as_ref() - .and_then(|v| v.as_array()) - .map(|arr| { - arr.iter() - .filter_map(|x| { - x.get("lora_name") - .or_else(|| x.get("loraName")) - .and_then(|n| n.as_str()) - .map(str::to_string) - }) - .collect() - }) - .unwrap_or_default(); - - if !app.engine_url.is_empty() { - let Some(model) = model.clone() else { - return Err(( - StatusCode::BAD_REQUEST, - Json(json!({ - "error": "no model: set active base (PUT /v1/base-model) or pass model" - })), - )); - }; - let url = format!("{}/v1/generate", app.engine_url); - let body = json!({ - "prompt": req.prompt, - "model": model, - "baseModel": active.base_model, - "lora_request": req.lora_request, - "size": req.size, - "seed": req.seed, - "negative_prompt": req.negative_prompt, - }); - info!( - model = %model, - loras = ?lora_names, - size = ?req.size, - seed = ?req.seed, - "engine generate" - ); - let resp = app - .http - .post(&url) - .json(&body) - .send() - .await - .map_err(|e| { - ( - StatusCode::BAD_GATEWAY, - Json(json!({ "error": format!("engine unreachable: {e}") })), - ) - })?; - let status = resp.status(); - let mut payload: Value = resp.json().await.map_err(|e| { - ( - StatusCode::BAD_GATEWAY, - Json(json!({ "error": format!("engine response: {e}") })), - ) - })?; - if !status.is_success() { - let detail = payload - .get("detail") - .cloned() - .unwrap_or_else(|| json!(payload.to_string())); - return Err(( - StatusCode::from_u16(status.as_u16()).unwrap_or(StatusCode::BAD_GATEWAY), - Json(json!({ "error": detail })), - )); - } - if let Some(obj) = payload.as_object_mut() { - obj.entry("baseModel") - .or_insert_with(|| json!(active.base_model)); - obj.entry("stub").or_insert(json!(false)); - } - return Ok(Json(payload)); - } - - info!( - model = ?model, - loras = ?lora_names, - size = ?req.size, - seed = ?req.seed, - "stub generate (weights not applied)" - ); - // Visible stub PNG (no GPU) so gallery / local Generate can be smoke-tested. - let png = stub_png_from_prompt(&req.prompt, 256, 256); - let b64 = base64::engine::general_purpose::STANDARD.encode(&png); - Ok(Json(json!({ - "data": [{ "b64_json": b64 }], - "model": model, - "baseModel": active.base_model, - "loras": lora_names, - "negativePrompt": req.negative_prompt, - "stub": true, - }))) -} - -/// Build a valid RGB PNG whose colors derive from the prompt (deterministic stub). -fn stub_png_from_prompt(prompt: &str, w: u32, h: u32) -> Vec { - let mut hash: u32 = 2166136261; - for b in prompt.as_bytes() { - hash ^= u32::from(*b); - hash = hash.wrapping_mul(16777619); - } - let r0 = ((hash >> 16) & 0xff) as u8; - let g0 = ((hash >> 8) & 0xff) as u8; - let b0 = (hash & 0xff) as u8; - - let mut raw = Vec::with_capacity(((w * 3 + 1) * h) as usize); - for y in 0..h { - raw.push(0); // filter: none - for x in 0..w { - let t = (x + y) as u8; - raw.push(r0.wrapping_add(t)); - raw.push(g0.wrapping_add(t.wrapping_mul(3))); - raw.push(b0.wrapping_add(t.wrapping_mul(5))); - } - } - encode_png_rgb(w, h, &raw) -} - -fn encode_png_rgb(w: u32, h: u32, raw: &[u8]) -> Vec { - let mut out = Vec::new(); - out.extend_from_slice(&[0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]); - let mut ihdr = Vec::with_capacity(13); - ihdr.extend_from_slice(&w.to_be_bytes()); - ihdr.extend_from_slice(&h.to_be_bytes()); - ihdr.extend_from_slice(&[8, 2, 0, 0, 0]); // 8-bit RGB - write_png_chunk(&mut out, b"IHDR", &ihdr); - write_png_chunk(&mut out, b"IDAT", &deflate_zlib(raw)); - write_png_chunk(&mut out, b"IEND", &[]); - out -} - -fn write_png_chunk(out: &mut Vec, ctype: &[u8; 4], data: &[u8]) { - out.extend_from_slice(&(data.len() as u32).to_be_bytes()); - out.extend_from_slice(ctype); - out.extend_from_slice(data); - out.extend_from_slice(&crc32_ieee(ctype, data).to_be_bytes()); -} - -/// Stored-block zlib wrapper (no external compress crate). -fn deflate_zlib(data: &[u8]) -> Vec { - let mut out = Vec::with_capacity(data.len() + 16 + data.len().div_ceil(65535) * 5); - out.extend_from_slice(&[0x78, 0x01]); // zlib cmf/flg — no compression - let mut offset = 0; - while offset < data.len() { - let end = (offset + 65535).min(data.len()); - let chunk = &data[offset..end]; - let last = end == data.len(); - out.push(if last { 0x01 } else { 0x00 }); - let n = chunk.len() as u16; - out.extend_from_slice(&n.to_le_bytes()); - out.extend_from_slice(&(!n).to_le_bytes()); - out.extend_from_slice(chunk); - offset = end; - } - if data.is_empty() { - out.extend_from_slice(&[0x01, 0x00, 0x00, 0xff, 0xff]); - } - out.extend_from_slice(&adler32(data).to_be_bytes()); - out -} - -fn adler32(data: &[u8]) -> u32 { - let mut a: u32 = 1; - let mut b: u32 = 0; - for &x in data { - a = (a + u32::from(x)) % 65521; - b = (b + a) % 65521; - } - (b << 16) | a } -fn crc32_ieee(ctype: &[u8], data: &[u8]) -> u32 { - let mut crc: u32 = 0xffff_ffff; - for &x in ctype.iter().chain(data.iter()) { - crc ^= u32::from(x); - for _ in 0..8 { - let mask = (!(crc & 1)).wrapping_add(1); - crc = (crc >> 1) ^ (0xedb8_8320 & mask); - } - } - !crc +async fn generate(Json(req): Json) -> Json { + // 1x1 PNG stub so Freya gallery path works without a GPU. + let png: &[u8] = &[ + 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, + 0x52, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x08, 0x02, 0x00, 0x00, 0x00, 0x90, + 0x77, 0x53, 0xde, 0x00, 0x00, 0x00, 0x0c, 0x49, 0x44, 0x41, 0x54, 0x08, 0xd7, 0x63, 0xf8, + 0xcf, 0xc0, 0x00, 0x00, 0x00, 0x03, 0x00, 0x01, 0x00, 0x05, 0xfe, 0xd4, 0xef, 0x00, 0x00, + 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82, + ]; + let _ = req.prompt; + let b64 = base64::engine::general_purpose::STANDARD.encode(png); + Json(json!({ "data": [{ "b64_json": b64 }] })) } #[derive(Deserialize)] @@ -990,819 +96,30 @@ fn crc32_ieee(ctype: &[u8], data: &[u8]) -> u32 { struct InstallReq { url: String, dest_path: String, - /// Optional download credential (Civitai/HF). Never embed secrets in `url` — reqwest errors echo URLs. - #[serde(default)] - auth_token: Option, - #[serde(default)] - source: Option, - #[serde(default)] - name: Option, - #[serde(default)] - base_model: Option, - #[serde(default)] - version_id: Option, - #[serde(default)] - model_id: Option, - #[serde(default)] - model_type: Option, - #[serde(default)] - thumbnail_url: Option, - /// When true (default for `/v1/assets/jobs`), enqueue and return immediately. - /// `/v1/assets/install` defaults to false for operator/sync callers. - #[serde(default)] - r#async: Option, -} - -#[derive(Deserialize)] -#[serde(rename_all = "camelCase")] -struct ClearJobsReq { - /// When true, also remove queued jobs that have not started. Active downloads are never cleared. - #[serde(default)] - include_queued: bool, -} - -#[derive(Deserialize)] -#[serde(rename_all = "camelCase")] -struct DeleteAssetReq { - path: String, -} - -/// Resolve `dest_path` under `models_dir`, rejecting absolute paths and `..` escape. -fn resolve_dest(models_dir: &Path, dest_path: &str) -> Result { - let rel = Path::new(dest_path); - if dest_path.is_empty() || rel.is_absolute() { - return Err("destPath must be a non-empty relative path under models dir".into()); - } - if rel - .components() - .any(|c| matches!(c, Component::ParentDir | Component::RootDir)) - { - return Err("destPath must not contain '..' or absolute components".into()); - } - let models_root = models_dir - .canonicalize() - .map_err(|e| format!("models dir: {e}"))?; - let dest = models_root.join(rel); - // Ensure the joined path still lives under models_root (defense in depth). - if !dest.starts_with(&models_root) { - return Err("destPath escapes models dir".into()); - } - Ok(dest) -} - -fn install_host_ok(host: &str) -> bool { - let h = host.to_ascii_lowercase(); - h == "civitai.com" - || h.ends_with(".civitai.com") - || h == "huggingface.co" - || h.ends_with(".huggingface.co") - || h == "hf.co" - || h.ends_with(".hf.co") -} - -/// Civitai now serves some files from Cloudflare R2 -/// (`civitai-delivery-worker-prod..r2.cloudflarestorage.com`). Allow only as a -/// redirect target after an allowlisted civitai.com hop — never as a direct install URL. -fn civitai_r2_delivery_host(host: &str) -> bool { - let h = host.to_ascii_lowercase(); - h.contains("civitai") && h.ends_with(".r2.cloudflarestorage.com") -} - -fn redirect_came_from_civitai(previous: &[reqwest::Url]) -> bool { - previous.iter().any(|u| { - u.host_str() - .map(|h| { - let h = h.to_ascii_lowercase(); - h == "civitai.com" || h.ends_with(".civitai.com") - }) - .unwrap_or(false) - }) -} - -fn redirect_host_ok(host: &str, previous: &[reqwest::Url]) -> bool { - if install_host_ok(host) { - return true; - } - civitai_r2_delivery_host(host) && redirect_came_from_civitai(previous) -} - -fn install_url_ok(url: &str) -> bool { - let Ok(parsed) = reqwest::Url::parse(url) else { - return false; - }; - if !matches!(parsed.scheme(), "https" | "http") { - return false; - } - parsed.host_str().is_some_and(install_host_ok) -} - -fn download_client() -> Result { - reqwest::Client::builder() - .redirect(reqwest::redirect::Policy::custom(|attempt| { - if attempt.previous().len() >= 5 { - return attempt.error("too many redirects"); - } - match attempt.url().host_str() { - Some(h) if redirect_host_ok(h, attempt.previous()) => attempt.follow(), - _ => attempt.error("redirect to disallowed host"), - } - })) - .build() - .map_err(|e| e.to_string()) -} - -/// Client-facing and logged text for a failed download. -/// `raw_display` is used only to classify redirect-policy failures. It is never -/// returned or logged: reqwest's Display includes the request URL and query. -fn download_failure_message(raw_display: &str, status: Option) -> String { - if raw_display.contains("redirect to disallowed host") { - "download request failed: redirect to disallowed host".to_string() - } else if raw_display.contains("too many redirects") { - "download request failed: too many redirects".to_string() - } else if let Some(status) = status { - format!("download failed with HTTP {}", status.as_u16()) - } else { - "download request failed".to_string() - } -} - -/// Map reqwest transport errors to safe job messages (never echo URLs / query secrets). -fn download_request_err(e: reqwest::Error) -> String { - let message = download_failure_message(&e.to_string(), e.status()); - warn!(error = %message, "download request failed"); - message -} - -fn validate_install(app: &App, req: &InstallReq) -> Result)> { - let dest = resolve_dest(&app.models_dir, &req.dest_path).map_err(|e| { - ( - StatusCode::BAD_REQUEST, - Json(json!({ "error": e })), - ) - })?; - if !install_url_ok(&req.url) { - return Err(( - StatusCode::BAD_REQUEST, - Json(json!({ - "error": "url must be http(s) on civitai.com, huggingface.co, or hf.co" - })), - )); - } - Ok(dest) -} - -fn job_to_json(job: &InstallJob) -> Value { - serde_json::to_value(job).unwrap_or(Value::Null) -} - -async fn enqueue_job(app: &App, req: InstallReq) -> Result)> { - let dest = validate_install(app, &req)?; - if dest.exists() { - return Err(( - StatusCode::CONFLICT, - Json(json!({ - "error": format!("already installed at {} — delete it first", req.dest_path) - })), - )); - } - { - let store = app.jobs.lock().await; - for e in store.jobs.values() { - if e.job.dest_path == req.dest_path - && matches!(e.job.status.as_str(), "queued" | "downloading") - { - return Err(( - StatusCode::CONFLICT, - Json(json!({ - "error": format!( - "already downloading to {} — wait or cancel the existing job", - req.dest_path - ) - })), - )); - } - } - } - let id = Uuid::new_v4().to_string(); - let now = now_unix(); - let job = InstallJob { - id: id.clone(), - status: "queued".into(), - url: req.url.clone(), - dest_path: req.dest_path.clone(), - name: req.name.clone(), - base_model: req.base_model.clone(), - model_type: req.model_type.clone(), - source: req.source.clone(), - bytes_done: 0, - bytes_total: None, - percent: None, - error: None, - created_at: now, - updated_at: now, - }; - let entry = JobEntry { - job: job.clone(), - cancel: Arc::new(AtomicBool::new(false)), - auth_token: req - .auth_token - .as_deref() - .map(str::trim) - .filter(|t| !t.is_empty()) - .map(str::to_string), - version_id: req.version_id, - model_id: req.model_id, - thumbnail_url: req.thumbnail_url.clone(), - }; - { - let mut store = app.jobs.lock().await; - store.jobs.insert(id.clone(), entry); - store.recent.push_front(id.clone()); - while store.recent.len() > JOB_HISTORY_CAP { - if let Some(old) = store.recent.pop_back() { - if let Some(e) = store.jobs.get(&old) { - if matches!( - e.job.status.as_str(), - "succeeded" | "failed" | "cancelled" - ) { - store.jobs.remove(&old); - } else { - store.recent.push_back(old); - break; - } - } - } else { - break; - } - } - } - app.job_tx.send(id).map_err(|_| { - ( - StatusCode::INTERNAL_SERVER_ERROR, - Json(json!({ "error": "job queue closed" })), - ) - })?; - Ok(job) } -/// Sync install (operator / legacy). Prefer `POST /v1/assets/jobs` for UI/agent. async fn install( State(app): State>, Json(req): Json, -) -> Result, (StatusCode, Json)> { - if req.r#async.unwrap_or(false) { - let job = enqueue_job(&app, req).await?; - return Ok(Json(json!({ - "ok": true, - "queued": true, - "job": job_to_json(&job), - "jobId": job.id, - "status": job.status, - "path": job.dest_path, - "name": job.name, - "baseModel": job.base_model, - "modelType": job.model_type, - }))); - } - let dest = validate_install(&app, &req)?; - let cancel = Arc::new(AtomicBool::new(false)); - let result = run_download( - &app, - &req.url, - &req.dest_path, - &dest, - req.auth_token.as_deref(), - &AssetMeta { - name: req.name.clone(), - base_model: req.base_model.clone(), - version_id: req.version_id, - model_id: req.model_id, - model_type: req.model_type.clone(), - source: req.source.clone(), - thumbnail_url: req.thumbnail_url.clone(), - }, - cancel, - None, - ) - .await; - match result { - Ok(bytes) => { - info!( - path = %dest.display(), - bytes, - base = ?req.base_model, - "installed asset" - ); - Ok(Json(json!({ - "ok": true, - "path": req.dest_path, - "baseModel": req.base_model, - "name": req.name, - "versionId": req.version_id, - "modelId": req.model_id, - "modelType": req.model_type, - "bytes": bytes, - }))) - } - Err(e) => Err((StatusCode::BAD_REQUEST, Json(json!({ "error": e })))), - } -} - -async fn enqueue_install( - State(app): State>, - Json(req): Json, -) -> Result, (StatusCode, Json)> { - let job = enqueue_job(&app, req).await?; - Ok(Json(json!({ - "ok": true, - "queued": true, - "job": job_to_json(&job), - "jobId": job.id, - "status": job.status, - }))) -} - -async fn list_jobs(State(app): State>) -> Json { - let store = app.jobs.lock().await; - let jobs: Vec = store - .recent - .iter() - .filter_map(|id| store.jobs.get(id).map(|e| job_to_json(&e.job))) - .collect(); - Json(json!({ "data": jobs })) -} - -async fn get_job( - State(app): State>, - PathParam(id): PathParam, -) -> Result, (StatusCode, Json)> { - let store = app.jobs.lock().await; - let entry = store.jobs.get(&id).ok_or_else(|| { - ( - StatusCode::NOT_FOUND, - Json(json!({ "error": "job not found" })), - ) - })?; - Ok(Json(json!({ "job": job_to_json(&entry.job) }))) -} - -async fn cancel_job( - State(app): State>, - PathParam(id): PathParam, -) -> Result, (StatusCode, Json)> { - let mut store = app.jobs.lock().await; - let entry = store.jobs.get_mut(&id).ok_or_else(|| { - ( - StatusCode::NOT_FOUND, - Json(json!({ "error": "job not found" })), - ) - })?; - match entry.job.status.as_str() { - "queued" => { - entry.cancel.store(true, Ordering::SeqCst); - entry.job.status = "cancelled".into(); - entry.job.updated_at = now_unix(); - entry.job.error = Some("cancelled before download".into()); - } - "downloading" => { - entry.cancel.store(true, Ordering::SeqCst); - // Status flips to cancelled in the worker loop when it notices. - } - other => { - return Err(( - StatusCode::BAD_REQUEST, - Json(json!({ - "error": format!("cannot cancel job in status {other}") - })), - )); - } - } - Ok(Json(json!({ "ok": true, "job": job_to_json(&entry.job) }))) -} - -/// Drop finished (and optionally idle queued) jobs from the recent list. Never touches in-flight downloads. -async fn clear_jobs( - State(app): State>, - body: Option>, -) -> Json { - let include_queued = body.map(|Json(b)| b.include_queued).unwrap_or(false); - let mut store = app.jobs.lock().await; - let mut drop_ids: Vec = Vec::new(); - let mut keep = VecDeque::new(); - for id in store.recent.iter() { - let Some(entry) = store.jobs.get(id) else { - continue; - }; - let st = entry.job.status.as_str(); - let finished = matches!(st, "succeeded" | "failed" | "cancelled"); - let drop_queued = include_queued && st == "queued"; - if finished || drop_queued { - drop_ids.push(id.clone()); - } else { - keep.push_back(id.clone()); - } - } - for id in &drop_ids { - store.jobs.remove(id); - } - let removed = drop_ids.len(); - store.recent = keep; - let data: Vec = store - .recent - .iter() - .filter_map(|id| store.jobs.get(id).map(|e| job_to_json(&e.job))) - .collect(); - Json(json!({ "ok": true, "removed": removed, "data": data })) -} - -async fn delete_asset( - State(app): State>, - Json(req): Json, -) -> Result, (StatusCode, Json)> { - let dest = resolve_dest(&app.models_dir, &req.path).map_err(|e| { - ( - StatusCode::BAD_REQUEST, - Json(json!({ "error": e })), - ) - })?; - if !dest.exists() { - return Err(( - StatusCode::NOT_FOUND, - Json(json!({ "error": "asset not found" })), - )); - } - fs::remove_file(&dest).await.map_err(|e| { - ( - StatusCode::INTERNAL_SERVER_ERROR, - Json(json!({ "error": format!("delete failed: {e}") })), - ) - })?; - let meta = meta_path_for(&dest); - let _ = fs::remove_file(&meta).await; - // Clear active base if we removed it. - { - let mut active = app.active.write().await; - if active.model == req.path { - let next = ActiveBase { - model: String::new(), - base_model: None, - }; - let _ = persist_active_base(&app.models_dir, &next).await; - *active = next; - } - } - info!(path = %req.path, "deleted asset"); - Ok(Json(json!({ "ok": true, "path": req.path }))) -} - -/// Max concurrent Civitai/asset downloads (queue still accepts more; extras stay queued). -const MAX_CONCURRENT_DOWNLOADS: usize = 3; - -fn spawn_job_worker(app: Arc, mut rx: mpsc::UnboundedReceiver) { - tokio::spawn(async move { - let sem = Arc::new(Semaphore::new(MAX_CONCURRENT_DOWNLOADS)); - while let Some(id) = rx.recv().await { - let permit = match sem.clone().acquire_owned().await { - Ok(p) => p, - Err(_) => break, - }; - let app = app.clone(); - tokio::spawn(async move { - process_job(app, id).await; - drop(permit); - }); - } - }); -} - -async fn process_job(app: Arc, id: String) { - let (url, dest_path, auth, meta, cancel) = { - let mut store = app.jobs.lock().await; - let Some(entry) = store.jobs.get_mut(&id) else { - return; - }; - if entry.cancel.load(Ordering::SeqCst) || entry.job.status == "cancelled" { - entry.job.status = "cancelled".into(); - entry.job.updated_at = now_unix(); - return; - } - entry.job.status = "downloading".into(); - entry.job.updated_at = now_unix(); - ( - entry.job.url.clone(), - entry.job.dest_path.clone(), - entry.auth_token.clone(), - AssetMeta { - name: entry.job.name.clone(), - base_model: entry.job.base_model.clone(), - version_id: entry.version_id, - model_id: entry.model_id, - model_type: entry.job.model_type.clone(), - source: entry.job.source.clone(), - thumbnail_url: entry.thumbnail_url.clone(), - }, - entry.cancel.clone(), - ) - }; - let dest = match resolve_dest(&app.models_dir, &dest_path) { - Ok(p) => p, - Err(e) => { - update_job_failed(&app, &id, e).await; - return; - } - }; - let result = run_download( - &app, - &url, - &dest_path, - &dest, - auth.as_deref(), - &meta, - cancel.clone(), - Some(id.clone()), - ) - .await; - let mut store = app.jobs.lock().await; - let Some(entry) = store.jobs.get_mut(&id) else { - return; - }; - entry.job.updated_at = now_unix(); - match result { - Ok(bytes) => { - if cancel.load(Ordering::SeqCst) { - entry.job.status = "cancelled".into(); - entry.job.error = Some("cancelled".into()); - let _ = fs::remove_file(&dest).await; - } else { - entry.job.status = "succeeded".into(); - entry.job.bytes_done = bytes; - if let Some(total) = entry.job.bytes_total { - entry.job.percent = Some(100.0); - let _ = total; - } else { - entry.job.bytes_total = Some(bytes); - entry.job.percent = Some(100.0); - } - entry.job.error = None; - info!(job = %id, path = %dest_path, bytes, "install job succeeded"); - } - } - Err(e) => { - if cancel.load(Ordering::SeqCst) || e.contains("cancelled") { - entry.job.status = "cancelled".into(); - entry.job.error = Some("cancelled".into()); - } else { - entry.job.status = "failed".into(); - entry.job.error = Some(e); - } - } - } -} - -async fn update_job_failed(app: &App, id: &str, error: String) { - let mut store = app.jobs.lock().await; - if let Some(entry) = store.jobs.get_mut(id) { - entry.job.status = "failed".into(); - entry.job.error = Some(error); - entry.job.updated_at = now_unix(); - } -} - -async fn update_job_progress(app: &App, id: &str, done: u64, total: Option) { - let mut store = app.jobs.lock().await; - if let Some(entry) = store.jobs.get_mut(id) { - entry.job.bytes_done = done; - entry.job.bytes_total = total.or(entry.job.bytes_total); - entry.job.percent = entry.job.bytes_total.map(|t| { - if t == 0 { - 0.0 - } else { - (done as f64 / t as f64) * 100.0 - } - }); - entry.job.updated_at = now_unix(); - } -} - -/// Download to disk with optional progress + cancel. Returns bytes written. -#[allow(clippy::too_many_arguments)] -async fn run_download( - app: &App, - url: &str, - dest_path: &str, - dest: &Path, - auth_token: Option<&str>, - meta: &AssetMeta, - cancel: Arc, - job_id: Option, -) -> Result { +) -> Result, (axum::http::StatusCode, Json)> { + let dest = app.models_dir.join(&req.dest_path); if let Some(parent) = dest.parent() { - fs::create_dir_all(parent) - .await - .map_err(|_| "create dest dir failed".to_string())?; - } - let client = download_client().map_err(|_| "download client failed".to_string())?; - let mut req_builder = client.get(url); - if let Some(token) = auth_token.map(str::trim).filter(|t| !t.is_empty()) { - req_builder = req_builder.bearer_auth(token); - } - let mut resp = req_builder - .send() - .await - .map_err(download_request_err)?; - if !resp.status().is_success() { - return Err(format!("download failed with HTTP {}", resp.status())); - } - let total = resp.content_length(); - if let (Some(id), Some(t)) = (job_id.as_ref(), total) { - update_job_progress(app, id, 0, Some(t)).await; - } - let tmp = { - let mut s = dest.as_os_str().to_os_string(); - s.push(".partial"); - PathBuf::from(s) - }; - let mut file = fs::File::create(&tmp) - .await - .map_err(|_| "create temp file failed".to_string())?; - let mut done: u64 = 0; - let mut last_report = 0u64; - loop { - if cancel.load(Ordering::SeqCst) { - let _ = fs::remove_file(&tmp).await; - return Err("cancelled".into()); - } - match resp.chunk().await { - Ok(Some(chunk)) => { - file.write_all(&chunk) - .await - .map_err(|_| "write asset failed".to_string())?; - done += chunk.len() as u64; - if let Some(id) = job_id.as_ref() { - // Throttle progress updates (~256 KiB). - if done - last_report >= 256 * 1024 || total == Some(done) { - update_job_progress(app, id, done, total).await; - last_report = done; - } - } - } - Ok(None) => break, - Err(_) => { - let _ = fs::remove_file(&tmp).await; - return Err("download body failed".into()); - } - } + fs::create_dir_all(parent).await.map_err(internal)?; } - file.flush() + let bytes = reqwest::get(&req.url) .await - .map_err(|_| "flush asset failed".to_string())?; - drop(file); - if cancel.load(Ordering::SeqCst) { - let _ = fs::remove_file(&tmp).await; - return Err("cancelled".into()); - } - fs::rename(&tmp, dest) + .map_err(internal)? + .bytes() .await - .map_err(|_| "finalize asset failed".to_string())?; - - if meta.name.is_some() - || meta.base_model.is_some() - || meta.version_id.is_some() - || meta.model_id.is_some() - || meta.model_type.is_some() - || meta.source.is_some() - || meta.thumbnail_url.is_some() - { - let meta_path = meta_path_for(dest); - if let Ok(blob) = serde_json::to_vec_pretty(meta) { - let _ = fs::write(&meta_path, blob).await; - } - } - - let is_checkpoint = dest_path.starts_with("checkpoints/") - || meta - .model_type - .as_deref() - .map(|t| t.eq_ignore_ascii_case("checkpoint")) - .unwrap_or(false); - if is_checkpoint { - let mut active = app.active.write().await; - if active.model.is_empty() { - let next = ActiveBase { - model: dest_path.to_string(), - base_model: meta.base_model.clone(), - }; - let _ = persist_active_base(&app.models_dir, &next).await; - *active = next; - } - } - if let Some(id) = job_id.as_ref() { - update_job_progress(app, id, done, total.or(Some(done))).await; - } - Ok(done) + .map_err(internal)?; + fs::write(&dest, &bytes).await.map_err(internal)?; + info!(path = %dest.display(), bytes = bytes.len(), "installed asset"); + Ok(Json(json!({ "ok": true, "path": req.dest_path }))) } -/// Never return or log raw transport errors — reqwest Display includes the full URL. -#[allow(dead_code)] -fn internal(context: &str, _detail: impl std::fmt::Display) -> (StatusCode, Json) { - warn!(%context, error = "asset install failed", "asset install failed"); +fn internal(e: impl std::fmt::Display) -> (axum::http::StatusCode, Json) { ( - StatusCode::BAD_REQUEST, - Json(json!({ "error": format!("{context} failed") })), + axum::http::StatusCode::BAD_REQUEST, + Json(json!({ "error": e.to_string() })), ) } - -#[cfg(test)] -mod tests { - use super::*; - use std::fs; - - #[test] - fn reject_path_escape() { - let dir = tempfile_dir(); - assert!(resolve_dest(&dir, "../etc/passwd").is_err()); - assert!(resolve_dest(&dir, "/etc/passwd").is_err()); - assert!(resolve_dest(&dir, "loras/../../etc/passwd").is_err()); - assert!(resolve_dest(&dir, "loras/ok.safetensors").is_ok()); - } - - #[test] - fn download_failure_log_omits_url() { - let leaked = "error sending request for url (https://civitai.com/api/download/models/1?token=secret): connection reset"; - let msg = download_failure_message(leaked, None); - assert_eq!(msg, "download request failed"); - assert!(!msg.contains("token")); - assert!(!msg.contains("http")); - assert!(!msg.contains('?')); - - let redir = "error following redirect for url (https://evil.example/x?token=secret): redirect to disallowed host"; - let msg = download_failure_message(redir, None); - assert_eq!(msg, "download request failed: redirect to disallowed host"); - assert!(!msg.contains("token")); - assert!(!msg.contains("http")); - assert!(!msg.contains('?')); - - let many = "error following redirect for url (https://huggingface.co/x?token=hf): too many redirects"; - let msg = download_failure_message(many, None); - assert_eq!(msg, "download request failed: too many redirects"); - assert!(!msg.contains("token")); - assert!(!msg.contains("huggingface")); - - let msg = download_failure_message(leaked, Some(reqwest::StatusCode::FORBIDDEN)); - assert_eq!(msg, "download failed with HTTP 403"); - assert!(!msg.contains("token")); - assert!(!msg.contains("http")); - } - - #[test] - fn allowlist_install_hosts() { - assert!(install_url_ok( - "https://civitai.com/api/download/models/1?token=x" - )); - assert!(install_url_ok( - "https://huggingface.co/org/model/resolve/main/file.safetensors" - )); - assert!(!install_url_ok("https://evil.example/steal")); - assert!(!install_url_ok("file:///etc/passwd")); - // R2 delivery must not be accepted as a direct install URL (SSRF). - assert!(!install_url_ok( - "https://civitai-delivery-worker-prod.abc.r2.cloudflarestorage.com/file" - )); - } - - #[test] - fn allowlist_civitai_r2_redirect_only() { - let r2 = "civitai-delivery-worker-prod.5ac0637cfd0766c97916cefa3764fbdf.r2.cloudflarestorage.com"; - assert!(civitai_r2_delivery_host(r2)); - assert!(!civitai_r2_delivery_host( - "evil-delivery.abc.r2.cloudflarestorage.com" - )); - assert!(!redirect_host_ok(r2, &[])); - let from_civitai = vec![reqwest::Url::parse( - "https://civitai.com/api/download/models/1" - ) - .unwrap()]; - assert!(redirect_host_ok(r2, &from_civitai)); - assert!(redirect_host_ok("b2.civitai.com", &from_civitai)); - let from_evil = vec![reqwest::Url::parse("https://evil.example/x").unwrap()]; - assert!(!redirect_host_ok(r2, &from_evil)); - } - - #[test] - fn meta_sidecar_path() { - let p = PathBuf::from("/models/checkpoints/foo.safetensors"); - assert_eq!( - meta_path_for(&p), - PathBuf::from("/models/checkpoints/foo.safetensors.meta.json") - ); - } - - fn tempfile_dir() -> PathBuf { - let dir = std::env::temp_dir().join(format!("freya-worker-test-{}", std::process::id())); - let _ = fs::create_dir_all(dir.join("loras")); - let _ = dir.canonicalize(); - // canonicalize needs the dir to exist - let _ = fs::create_dir_all(&dir); - dir - } -} diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index a722ef1..a297a69 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -1,61 +1,25 @@ # Architecture ``` -User / agent - ├─ Freya UI → Freya API - └─ Freya MCP (Streamable HTTP /mcp) → Freya API - ├─ OpenRouter (chat + images) - ├─ Civitai API (search; authenticated downloads) - └─ Diffusion worker (local GPU host via URL — preferred for SD / LoRAs) - └─ /v1/images/generations (model + lora_request) - └─ /v1/assets/install (LoRAs + checkpoints + meta) - └─ /v1/loras | /v1/checkpoints - └─ /v1/base-model (active checkpoint selection) +User → Freya UI → Freya API + ├─ OpenRouter (chat + images) + ├─ Civitai API (search; authenticated downloads) + └─ Diffusion worker (in-cluster or remote) + └─ /v1/images/generations + └─ /v1/assets/install (LoRAs for UI) ``` -## Default deployment story - -Freya does **not** require a dedicated cluster or an in-cluster GPU. - -**Single-system without k8s:** Docker Compose under [`deploy/compose/`](../deploy/compose/) runs API + UI + worker (+ optional MCP) on one host — see [COMPOSE.md](COMPOSE.md). No operator or CRDs on that path. - -| Where | What | -|-------|------| -| **In cluster** (shared k8s is fine) | Operator, `FreyaStudio` (API + UI + MCP), Ingress | -| **Out of cluster** (GPU host) | `freya-local-worker` (`./scripts/run-local-worker.sh` / Diffusers+CUDA) or `make run-worker`; Studio reaches it by **URL** | - -Recommended worker CR: [`config/samples/freya_v1alpha1_freyadiffusionworker_external.yaml`](../config/samples/freya_v1alpha1_freyadiffusionworker_external.yaml) (`placement: external` + `externalEndpoint`). Point that URL at the GPU host (LAN IP, FQDN, or a cluster ExternalName/Endpoints bridge). The Worker tab Host/Port (or Advanced full URL) is the same surface for the API’s `FREYA_DIFFUSION_WORKER_URL`. - -**kind** is a **dev** path (local ports, hosts override, sample Ingress). Production-shaped is the **same CRs** on a shared cluster plus a local worker URL — not “Freya owns kind forever,” and not “GPU must live in the same cluster.” - -**MCP:** FreyaStudio reconciles `{studio}-mcp` Deployment+Service when `spec.mcpEnabled` (default `true`). Ingress Prefix `/mcp` → MCP `:8090` (path preserved; server mounts Streamable HTTP at `/mcp`). Public URL: `https:///mcp`. Auth: same `apiTokenSecretRef` → `FREYA_API_TOKEN`; `FREYA_API_URL` points at `{studio}-api:8080`. - -**Where bases live:** `FREYA_MODELS_DIR` on the **GPU worker host** (`loras/`, `checkpoints/`, `active-base.json`). Civitai `baseModel` is stored in `*.safetensors.meta.json` and used when the UI/API omits an explicit generate `model`. Remote LLM/vLLM text endpoints are often **not** SD-capable — keep multi-base diffusion on the local RTX worker. - -**Motion:** `gif` / `video` modalities use OpenRouter’s async `/videos` API (gallery stores `video/mp4` or converted `image/gif`). Local GPU worker can emit multi-frame **GIF** via Diffusers (`/v1/videos/generations`). Still images + LoRAs stay on the Diffusers engine (`FREYA_ENGINE_URL`); VRAM loads on demand and unloads after generate unless `FREYA_ENGINE_KEEP_LOADED=1`. - ## Secrets -| Secret | FreyaStudio / Worker field | Env | Notes | -|--------|----------------------------|-----|-------| -| OpenRouter | `spec.openRouter.secretRef` | `OPENROUTER_API_KEY` | Also editable in UI Settings | -| Civitai | `spec.civitai.secretRef` | `CIVITAI_API_KEY` | UI Settings | -| Hugging Face | `spec.huggingFace.secretRef` | `HF_TOKEN` | optional | -| API bearer | `FreyaStudio.spec.apiTokenSecretRef` | `FREYA_API_TOKEN` | UI sends bearer from Settings (not injected by nginx); also injected on MCP; required for Ingress | -| Worker bearer | `FreyaDiffusionWorker.spec.authSecretRef` | `FREYA_WORKER_TOKEN` | Injected on worker + API | +| Secret | FreyaStudio field | Env on API | UI Settings | +|--------|-------------------|------------|-------------| +| OpenRouter | `spec.openRouter.secretRef` | `OPENROUTER_API_KEY` | OpenRouter API key | +| Civitai | `spec.civitai.secretRef` | `CIVITAI_API_KEY` | Civitai API key | +| Hugging Face | `spec.huggingFace.secretRef` | `HF_TOKEN` | (API/env; optional later in UI) | Never put API keys in CRD string fields — only Secret references. ## Worker placement -- **external** (recommended) — `status.endpoint` = `spec.externalEndpoint`; API and `FreyaModelAsset` call that URL. Run the worker on the GPU host; do not assume in-cluster `nvidia.com/gpu`. -- **incluster** (optional) — operator creates Deployment + models PVC + Service when the cluster actually has GPUs. - -How Studio reaches an external worker from pods: - -| Form | Example | When | -|------|---------|------| -| Host IP + port | `http://192.168.3.125:8091` | API pods can route to the GPU host LAN | -| FQDN | `https://vllm.dataknife.net` | Ingress / DNS already fronts the worker on this host | -| `localhost` | `http://127.0.0.1:8091` | API with hostNetwork (or non-cluster `make run-api`) on the same machine as the worker | -| Cluster DNS bridge | `http://freya-gpu-host.freya.svc.cluster.local:8091` | Optional ExternalName / Endpoints Service pointing at the host | +- **inCluster** — operator creates Deployment + models PVC + Service; Job downloads for `FreyaModelAsset`. +- **external** — status.endpoint = `spec.externalEndpoint`; asset reconcile POSTs `/v1/assets/install` on the remote host. diff --git a/docs/CONCEPTS.md b/docs/CONCEPTS.md index 5fbec5e..bc1f68d 100644 --- a/docs/CONCEPTS.md +++ b/docs/CONCEPTS.md @@ -7,20 +7,7 @@ Source material lives in [`legacy/`](../legacy/) (Compose, ComfyUI, SwarmUI, Oll | MagicPrompt (Ollama) | `/v1/assist` + OpenRouter (or vLLM chat URL) | | ComfyUI / SwarmUI | Single Freya UI — no node graphs | | Civitai manual download | Settings **Civitai API key** + search/install onto worker | -| Ollama dolphin3 | OpenRouter chat models + Freya **router** (Llama 3.1 8B-class when Auto) | -| GPU UIs in-cluster | **External** `FreyaDiffusionWorker` URL → local GPU host (recommended); optional in-cluster GPU only if the cluster has one | - -### Modality routing (legacy alignment) - -Freya’s light **request router** classifies each chat/run/generate ask the way the old stack split work: - -| Modality | Legacy | Freya today | -|----------|--------|-------------| -| **chat** | MagicPrompt Chat / `make llm` (dolphin3) | Agent converse / assist — no generate | -| **picture** | ComfyUI stills (`make cui`); Flux for NL, SDXL ecosystem for LoRAs | OpenRouter `/images` or local worker | -| **gif** | SwarmUI **video** output (`gif-hd` / webp) — not still-image | Classified; clear “unsupported” (not silent image gen) | -| **video** | SwarmUI T2V/I2V (`make sui`; Wan / LTX) | Discovery via `GET /v1/models` → `video`; generate not wired yet | - -Settings defaults (all **Auto**): Agent `openrouter/auto`, Image `auto` → Flux NL default, Router `auto` → `meta-llama/llama-3.1-8b-instruct`. Pinned models always win over router suggestions. +| Ollama dolphin3 | OpenRouter chat models | +| GPU UIs in-cluster | Optional `FreyaDiffusionWorker` (vLLM-Omni) in-cluster **or** remote host | Automation north star: user provides intent (and optionally API keys); Freya installs LoRAs and generates without folder clicking. diff --git a/docs/LOCAL.md b/docs/LOCAL.md index 755bdd0..0c43e10 100644 --- a/docs/LOCAL.md +++ b/docs/LOCAL.md @@ -1,234 +1,17 @@ # Local development -## Single-system Docker Compose (no k8s) - -One machine, no operator/CRDs: API + nginx UI + local worker (+ optional MCP). - -```bash -cp deploy/compose/.env.example deploy/compose/.env -# set OPENROUTER_API_KEY + FREYA_ADMIN_PASSWORD -make compose-up # UI :8080 (worker stays on the compose network) -# make compose-up-gpu # NVIDIA overlay -# make compose-up-mcp # + MCP on 127.0.0.1:8090 (needs FREYA_API_TOKEN) -``` - -See **[COMPOSE.md](COMPOSE.md)** for volumes, auth, and Compose vs k8s+external-worker. Legacy Comfy/Swarm Compose remains under `legacy/` only. - -## Default story (shared k8s + local GPU worker) - -| In cluster | Out of cluster | -|------------|----------------| -| Operator, FreyaStudio (API / UI / MCP), Ingress | GPU worker on this host (`make run-worker` / Docker `freya-local-worker`) | - -Apply the **external** worker sample (`config/samples/freya_v1alpha1_freyadiffusionworker_external.yaml`) and point `externalEndpoint` (or the Worker tab Host/Port / Advanced URL) at the GPU process — LAN IP, FQDN, `localhost` when the API can see the host, or an ExternalName/Endpoints bridge. Freya does **not** need a dedicated cluster or an in-cluster GPU. **kind** below is a **dev** convenience; production-shaped is the same CRs on shared k8s + that worker URL. See [ARCHITECTURE.md](ARCHITECTURE.md). - -## Kind cluster UI (`freya.dataknife.net`) — local **dev** path - -Local kind maps host ports **80/443** to ingress-nginx (`kind-freya.yaml`). The FreyaStudio Ingress host is `freya.dataknife.net`. - -### TLS (`*.dataknife.net` wildcard) - -Same pattern as prd Traefik / Harbor / slashbay: Let's Encrypt secret `wildcard-dataknife-net-tls` (SANs `*.dataknife.net`, `dataknife.net`). - ```bash -make kind-tls # copies secret from ~/.kube/prd-apps-rke2.yaml → kube-system + freya; - # sets ingress-nginx --default-ssl-certificate; fixes freya-vllm tls -``` - -FreyaStudio sample sets `ingress.tlsSecretName: wildcard-dataknife-net-tls`. Without that field, HTTPS still works once nginx’s default cert is set (slashbay-style). Do **not** use a self-signed Ingress secret. - -**404 page not found** (plain text, `content-type: text/plain`) is **Traefik on prd-apps**, not Freya. Public DNS still CNAMEs `freya.dataknife.net` → `prd-apps-wk.dataknife.net` (192.168.14.x). Override on this machine: - -```bash -make kind-hosts # or ./scripts/kind-hosts.sh (rewrites /etc/hosts + resolvectl flush-caches) -``` - -This host’s `nsswitch` prefers `resolve` over `files`; systemd-resolved still honors `/etc/hosts` after a cache flush. Without the override you hit Traefik on prd-apps. - -### Brave (and other browsers) still 404 after hosts - -**Cause:** Brave **Secure DNS** (DNS-over-HTTPS) ignores `/etc/hosts` and resolves via Cloudflare/Google → prd-apps Traefik → `404 page not found`. - -**Fix (this machine):** - -1. Brave → **Settings** → **Privacy and security** → **Use secure DNS** → **turn Off** - (or use “OS default” / a resolver that does **not** bypass system hosts). -2. Hard-reload `https://freya.dataknife.net/` (or open a new private window after the change). - -`curl` and browsers that use system DNS already work once hosts is set. - -**Other device on the LAN:** kind publishes **80/443** on this host’s LAN IP (`192.168.3.125`). On that device, either: - -- Add hosts: `192.168.3.125 freya.dataknife.net` (and disable Secure DNS if the browser uses DoH), or -- Temporarily: `curl -H 'Host: freya.dataknife.net' http://192.168.3.125/` - -NodePort (`31026`/`30556`) is only inside the kind node network; use host **80/443**, not NodePort from outside. - -Working URLs after the hosts override (and Secure DNS off in Brave): - -| URL | Expected | -|-----|----------| -| https://freya.dataknife.net/ | Freya UI (200) | -| http://freya.dataknife.net/ | Freya UI (200) | -| https://freya.dataknife.net/v1/health | API health JSON | -| https://freya.dataknife.net/mcp | Freya MCP Streamable HTTP (POST JSON-RPC; GET may 405 — not a browser page) | -| https://vllm.dataknife.net/health | Local diffusion worker (DNS already → this host) | - -### Freya MCP (Cursor / agents) - -Operator deploys MCP with the Studio (`mcpEnabled: true` by default). Public endpoint: - -```text -https://freya.dataknife.net/mcp -``` - -Cursor MCP config (Streamable HTTP): - -```json -{ - "mcpServers": { - "freya": { - "url": "https://freya.dataknife.net/mcp" - } - } -} -``` - -Local without cluster: `make run-api` then `make run-mcp` → `http://127.0.0.1:8090/mcp` (set `FREYA_API_TOKEN` if the API requires it). Kind rebuild: `make kind-deploy-mcp`. Tools: `health`, `settings`, `generate_image`, `gallery_list`, `gallery_get`, `civitai_search`, `worker_stats`, `models`. - -Without hosts: `curl -H 'Host: freya.dataknife.net' http://127.0.0.1/` also serves the UI. Vite mock/dev remains at http://127.0.0.1:5173/. - -### Studio admin login (game-operator style) - -With `generateAdminSecrets: true` (default), the operator creates Secret `freya-admin` -(`username` + `admin-password`). Open the UI → **Sign in**, or: - -```bash -kubectl -n freya get secret freya-admin -o jsonpath='{.data.admin-password}' | base64 -d; echo -``` - -Machine MCP keeps using Secret `freya-api-token`. See [AUTH.md](AUTH.md). - -## Interactive UI mock (no API) - -Iterate on Freya UI without OpenRouter, Civitai, or a worker: - -```bash -make mock-ui -# or: cd web && npm i && npm run dev:mock -``` - -Also: open the normal UI with `?mock=1`, or click **Remember mock** in the banner (stores `localStorage.freya.mock=1`). - -Mock covers Generate, Enhance, Styles, Civitai search/install flow, Gallery remix, Settings, and agentic **Plan / Auto / YOLO** sessions — in-memory with SVG placeholders. Featured “Use example” is the `freya.png` brand NL prompt (winged warrior / canyon waterfall). - -## Full local stack - -```bash -cp .env.example .env # fill OPENROUTER_API_KEY (required); others optional -set -a && source .env && set +a +cp .env.example .env # fill keys +export $(grep -v '^#' .env | xargs) make run-api # other terminal cd web && npm i && npm run dev -# GPU worker on this host (recommended; out of cluster) +# optional make run-worker -# Worker tab → Host/Port → http://127.0.0.1:8091 (or LAN IP / FQDN from in-cluster Studio) +# Settings → worker URL http://127.0.0.1:8091 # Settings → paste Civitai API key → Civitai tab → Install to worker ``` -In the UI, session automation modes: - -| Mode | Behavior | -|------|----------| -| **Plan** | Steps, Civitai query, LoRAs, batch prompts only — no generate/install | -| **Auto** | Runs the plan; pauses on ambiguous / high-impact choices | -| **YOLO** | Full auto — search, install when a worker is set, else generate via OpenRouter | - -Worker is optional: cloud generate uses OpenRouter; LoRA install needs `FREYA_DIFFUSION_WORKER_URL` + Civitai. - -### Local GPU worker (recommended) vs optional in-cluster GPU - -| Path | URL / endpoint | Models | -|------|----------------|--------| -| **This machine (recommended)** | `make run-worker` / `freya-local-worker` → `http://127.0.0.1:8091` (binds `0.0.0.0:8091`); from in-cluster Studio use LAN IP, FQDN (`https://vllm.dataknife.net` on this lab), or ExternalName | `FREYA_MODELS_DIR=/mnt/game2/freya/models` (repo `data/models` → symlink); SD/SDXL/Pony/Flux live here | -| **Cluster Studio → external worker** | `FreyaDiffusionWorker` `placement: external` + `externalEndpoint` (sample YAML) — same URL the Worker tab saves | Operator sets `FREYA_DIFFUSION_WORKER_URL` from the CR; no in-cluster GPU required | -| **Optional in-cluster GPU** | `placement: incluster` sample — only when the cluster has `nvidia.com/gpu` | Operator Deployment + models PVC; **not** the default story | - -#### Models on disk (`FREYA_MODELS_DIR`) - -``` -models/ - loras/ *.safetensors + optional *.safetensors.meta.json (baseModel, versionId, …) - checkpoints/ *.safetensors + optional *.meta.json - (recommended Pony: checkpoints/pony-diffusion-v6-xl.safetensors) - embeddings/ (TextualInversion) - vae/ - active-base.json { "model": "checkpoints/pony-diffusion-v6-xl.safetensors", "baseModel": "Pony" } -``` - -Install from the Civitai UI writes into these folders. Sidecar `.meta.json` stores Civitai `baseModel` so generate can pick a compatible checkpoint. Only **one** active base is selected at a time (VRAM); swap via Settings or `PUT /v1/worker/base-model`. - -Worker health/stats: - -| Endpoint | Notes | -|----------|--------| -| Worker `GET /health` | Liveness only: `{ ok, service }`. No GPU, disk, or inventory | -| Worker `GET /v1/stats` | Authenticated inventory: `{ ok, modelsDir, loras, checkpoints, uptimeSec, vram, host, disk, modelLoaded, layout }` — VRAM from `nvidia-smi` when present (null in GPU-less containers) | -| Worker `GET /v1/checkpoints` | List installed checkpoints (+ `baseModel` from sidecar) | -| Worker `GET\|PUT /v1/base-model` | Active base selection (persisted as `active-base.json`) | -| API `GET /v1/worker/stats` | Proxies `/v1/stats`. A failed stats call is reachability via `/health` only and does not borrow host `nvidia-smi`. Host VRAM fills in only when stats returned null VRAM | -| API `GET /v1/worker/checkpoints` | Proxies checkpoint list | -| API `GET\|PUT /v1/worker/base-model` | Proxies active base | -| API `GET /v1/base-models` | Static family catalog (SD 1.5 / SDXL / Pony / Flux hints) — no Civitai traffic | -| API `POST /v1/worker/start\|stop` | Local docker (`FREYA_WORKER_CONTAINER`, default `freya-local-worker`) or systemd unit | - -**Worker tab** (not Settings): host/port (defaults `localhost`/`8091`), Setup copy for LAN / FQDN / k8s DNS bridge, Generate API token, VRAM bar, **active base** picker, Start / Stop. Local vs Cloud chooses whether generation uses the worker. A saved URL attaches the worker client. Settings keeps OpenRouter/Civitai keys only — the diffusion URL lives on Worker. - -**GPU engine (this host):** `./scripts/run-local-worker.sh` (or `make run-local-worker`) builds `Dockerfile.worker` and runs Docker `freya-local-worker` with `--gpus all`. Inside the container, freya-worker proxies generate to a **Diffusers** sidecar (`FREYA_ENGINE_URL=http://127.0.0.1:8092`). Checkpoints + Civitai LoRAs under `FREYA_MODELS_DIR` load **on demand** into VRAM and unload after each generate unless `FREYA_ENGINE_KEEP_LOADED=1`. Stats `modelLoaded.loadedInVram` reflects the engine; `nvidia-smi` VRAM appears when the container has GPU access. Compose: `make compose-up-gpu`. Without `FREYA_ENGINE_URL`, generate still returns a stub PNG for wiring tests. CRD `engine: vllm-omni` remains the label for swapping to vLLM-Omni on the same HTTP surface. - -### Civitai in the UI - -- Search/Suggest returns installable types (LoRA, LoCon, DoRA, Checkpoint, TextualInversion, VAE) with thumbnails and type badges — not LoRA-only. -- **Pin** = session-scoped (current generate). **★ Favorite** = persistent library in `localStorage` (`freya.civitaiFavorites`); Civitai tab → Favorites. -- Click a card for details (previews, triggers, base model, related checkpoints). Related assets are Freya-derived from `baseModel` (Civitai has no hard dependency graph). -- Install / pin now forward `baseModel` (+ `versionId` / `modelType`) to the worker; generate sends `path` + `baseModel` so the API can select a matching active base. -- API: `GET /v1/civitai/search`, `GET /v1/civitai/models/{id}`, `POST /v1/civitai/install`. - -### Intent router (picture / gif / video / chat) - -`POST /v1/chat`, `/v1/run`, and `/v1/generate` run Freya’s light router first (`packs/instructions/route.txt`). Defaults: Agent / Image / Video / Router pickers **Auto**. Router Auto → `meta-llama/llama-3.1-8b-instruct`; Image Auto → Flux NL; Video Auto → `bytedance/seedance-2.5-flash`. GIF/video asks **execute** (OpenRouter T2V and/or local Diffusers GIF) — they no longer hard-reject. See [CONCEPTS.md](CONCEPTS.md) and [OPENROUTER.md](OPENROUTER.md). - -### Video / GIF - -| Path | Behavior | -|------|----------| -| **OpenRouter video** | `POST /videos` → poll → gallery `video/mp4` (UI `