diff --git a/.dockerignore b/.dockerignore index c59730f..a1595f5 100644 --- a/.dockerignore +++ b/.dockerignore @@ -12,3 +12,11 @@ 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 8614e42..551c6f9 100644 --- a/.env.example +++ b/.env.example @@ -1,9 +1,60 @@ +# 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 -# Optional: require Bearer on /v1 routes (empty = open local/dev) -# FREYA_API_TOKEN= -# FREYA_WORKER_TOKEN= # same value on freya-api + freya-worker -# FREYA_CORS_ORIGINS=http://127.0.0.1:5173 -# VITE_FREYA_API_TOKEN= # for local Vite UI when API token is set +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 1777c1a..5fe2c0b 100644 --- a/.gitignore +++ b/.gitignore @@ -52,6 +52,7 @@ logs/ .env .env.* !.env.example +!deploy/compose/.env.example *.pem # .NET (legacy SwarmUI) diff --git a/Cargo.lock b/Cargo.lock index 9db3728..4194f0c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -252,6 +252,15 @@ 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" @@ -357,6 +366,12 @@ 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" @@ -407,14 +422,33 @@ 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", - "darling_macro", + "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", ] [[package]] @@ -431,25 +465,60 @@ 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", + "darling_core 0.20.11", "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", - "crypto-common", + "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", ] [[package]] @@ -593,6 +662,7 @@ dependencies = [ "base64 0.22.1", "chrono", "clap", + "libc", "reqwest", "serde", "serde_json", @@ -611,11 +681,30 @@ version = "0.1.0" dependencies = [ "k8s-openapi", "kube", - "schemars", + "schemars 0.8.22", "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" @@ -633,6 +722,7 @@ dependencies = [ "tokio", "tracing", "tracing-subscriber", + "uuid", ] [[package]] @@ -643,6 +733,7 @@ dependencies = [ "axum", "base64 0.22.1", "clap", + "libc", "reqwest", "serde", "serde_json", @@ -908,6 +999,15 @@ 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" @@ -1144,6 +1244,8 @@ checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" dependencies = [ "equivalent", "hashbrown 0.17.1", + "serde", + "serde_core", ] [[package]] @@ -1294,7 +1396,7 @@ dependencies = [ "http", "json-patch", "k8s-openapi", - "schemars", + "schemars 0.8.22", "serde", "serde-value", "serde_json", @@ -1307,7 +1409,7 @@ version = "0.98.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "37745d8a4076b77e0b1952e94e358726866c8e14ec94baaca677d47dcdb98658" dependencies = [ - "darling", + "darling 0.20.11", "proc-macro2", "quote", "serde_json", @@ -1536,6 +1638,12 @@ 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" @@ -1810,6 +1918,26 @@ 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" @@ -1891,6 +2019,56 @@ 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" @@ -1982,7 +2160,21 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3fbf2ae1b8bc8e02df939598064d22402220cd5bbcca1c76f7d6a310974d5615" dependencies = [ "dyn-clone", - "schemars_derive", + "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", "serde", "serde_json", ] @@ -1995,10 +2187,22 @@ checksum = "32e265784ad618884abaea0600a9adf15393368d840e0222d101a072f3f7534d" dependencies = [ "proc-macro2", "quote", - "serde_derive_internals", + "serde_derive_internals 0.29.1", "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" @@ -2088,6 +2292,17 @@ 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" @@ -2145,7 +2360,18 @@ checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8" dependencies = [ "cfg-if", "cpufeatures 0.2.17", - "digest", + "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", ] [[package]] @@ -2207,6 +2433,19 @@ 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" @@ -2382,6 +2621,17 @@ 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" @@ -2541,12 +2791,27 @@ 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" @@ -2571,6 +2836,12 @@ 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 7b0c9be..f30b7c1 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -5,12 +5,14 @@ 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] @@ -28,7 +30,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"] } +tokio = { version = "1", features = ["macros", "rt-multi-thread", "signal", "fs", "io-util", "process"] } 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 05a9f74..0d97a20 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,9 +1,9 @@ -FROM rust:1.87-bookworm AS builder +FROM rust:1.88-bookworm AS builder WORKDIR /src -COPY Cargo.toml rust-toolchain.toml ./ +COPY Cargo.toml Cargo.lock rust-toolchain.toml ./ COPY crates ./crates COPY packs ./packs -RUN cargo build --release -p freya-operator -p freya-api -p freya-worker +RUN cargo build --release -p freya-operator -p freya-api -p freya-worker -p freya-mcp FROM gcr.io/distroless/cc-debian12:nonroot AS operator COPY --from=builder /src/target/release/freya-operator /usr/local/bin/freya-operator @@ -21,3 +21,9 @@ 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.bin b/Dockerfile.bin new file mode 100644 index 0000000..b4ac1e6 --- /dev/null +++ b/Dockerfile.bin @@ -0,0 +1,21 @@ +# Fast image packaging from host `cargo build --release` binaries (kind/dev). +# Prefer the multi-stage Dockerfile for CI/prod builds. +# Build context must include target/release/* and packs/ (see Makefile kind-bin-*). + +FROM gcr.io/distroless/cc-debian12:nonroot AS operator +COPY target/release/freya-operator /usr/local/bin/freya-operator +USER nonroot:nonroot +ENTRYPOINT ["/usr/local/bin/freya-operator"] + +FROM gcr.io/distroless/cc-debian12:nonroot AS api +COPY target/release/freya-api /usr/local/bin/freya-api +COPY packs /packs +USER nonroot:nonroot +ENV FREYA_PACKS_DIR=/packs +ENTRYPOINT ["/usr/local/bin/freya-api"] + +FROM gcr.io/distroless/cc-debian12:nonroot AS mcp +COPY 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.worker b/Dockerfile.worker new file mode 100644 index 0000000..6db809d --- /dev/null +++ b/Dockerfile.worker @@ -0,0 +1,49 @@ +# GPU diffusion worker: freya-worker HTTP facade + Diffusers/CUDA engine. +# Build: docker build -f Dockerfile.worker -t freya-diffusion-worker:local . +# Run: ./scripts/run-local-worker.sh +# +# Stub-only (no GPU) remains `Dockerfile` target `worker` for CI/wiring. + +FROM rust:1.88-bookworm AS builder +WORKDIR /src +COPY Cargo.toml Cargo.lock rust-toolchain.toml ./ +COPY crates ./crates +COPY packs ./packs +RUN cargo build --release -p freya-worker + +# PyTorch CUDA runtime — torch is preinstalled; we add Diffusers + FastAPI. +FROM pytorch/pytorch:2.5.1-cuda12.4-cudnn9-runtime + +USER root +ENV DEBIAN_FRONTEND=noninteractive \ + FREYA_MODELS_DIR=/models \ + FREYA_WORKER_PORT=8091 \ + FREYA_ENGINE_HOST=127.0.0.1 \ + FREYA_ENGINE_PORT=8092 \ + FREYA_ENGINE_URL=http://127.0.0.1:8092 \ + FREYA_ENGINE_KEEP_LOADED=0 \ + NVIDIA_VISIBLE_DEVICES=all \ + NVIDIA_DRIVER_CAPABILITIES=compute,utility \ + PIP_DISABLE_PIP_VERSION_CHECK=1 \ + HF_HOME=/models/.hf-cache + +RUN apt-get update && apt-get install -y --no-install-recommends \ + curl ca-certificates \ + && rm -rf /var/lib/apt/lists/* + +COPY deploy/worker/engine/requirements.txt /opt/freya/engine/requirements.txt +RUN pip install --no-cache-dir -r /opt/freya/engine/requirements.txt + +COPY deploy/worker/engine/server.py /opt/freya/engine/server.py +COPY deploy/worker/entrypoint.sh /opt/freya/entrypoint.sh +RUN chmod +x /opt/freya/entrypoint.sh + +COPY --from=builder /src/target/release/freya-worker /usr/local/bin/freya-worker + +WORKDIR /models +EXPOSE 8091 +HEALTHCHECK --interval=30s --timeout=5s --start-period=45s --retries=3 \ + CMD curl -sf http://127.0.0.1:8091/health || exit 1 + +ENTRYPOINT ["/opt/freya/entrypoint.sh"] +CMD ["--port", "8091", "--models-dir", "/models"] diff --git a/Makefile b/Makefile index 437a8ea..7f7dee3 100644 --- a/Makefile +++ b/Makefile @@ -2,12 +2,15 @@ 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 \ - manifests install deploy up-local clean docker-build + 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 all: build @@ -37,7 +40,7 @@ vet: fmt-check lint ## Static checks ci: vet test ## Local quality gate manifests: ## Generate CRD YAML into config/crd - $(CARGO) run -p freya-operator --bin freya-crdgen > config/crd/freya.dataknife.ai_crds.yaml + 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; }' install: manifests ## Apply CRDs kubectl apply -f config/crd/freya.dataknife.ai_crds.yaml @@ -49,23 +52,72 @@ 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 stub locally +run-worker: ## Run diffusion worker locally (stub PNG unless FREYA_ENGINE_URL set) $(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 -up-local: ## API + notes for UI (OPENROUTER_API_KEY / CIVITAI_API_KEY in env) +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" @echo "Terminal A: make run-api" @echo "Terminal B: cd web && npm install && npm run dev" - @echo "UI mock only: cd web && npm install && npm run dev:mock" - @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" + @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 + clean: $(CARGO) clean @@ -73,4 +125,57 @@ 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 2301ded..fe25b68 100644 --- a/README.md +++ b/README.md @@ -13,6 +13,24 @@ Freya removes the old “download GB → open Comfy/Swarm → click forever” l 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): @@ -21,29 +39,43 @@ The previous Compose/ComfyUI/SwarmUI/Ollama stack is preserved under [`legacy/`] make mock-ui # or: cd web && npm i && npm run dev:mock ``` -**Full stack:** +**Single-system Docker Compose** (no Kubernetes / operator — see [docs/COMPOSE.md](docs/COMPOSE.md)): ```bash -export OPENROUTER_API_KEY=sk-or-... -# optional — search/install Civitai LoRAs onto a worker -export CIVITAI_API_KEY=... +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 make run-api # :8080 cd web && npm install && npm run dev # :5173 -# optional GPU / remote worker stub +# GPU worker on this host (recommended; stays out of cluster) make run-worker # :8091 -# then Settings → Diffusion worker URL → http://127.0.0.1:8091 +# then Worker tab → Host/Port → http://127.0.0.1:8091 (or LAN IP / FQDN from in-cluster Studio) ``` -In the UI **Settings** tab you can paste: +In the UI: -- **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 +- **Settings** — OpenRouter + Civitai API keys +- **Worker** — diffusion host/port or full URL (local GPU process, not “must be in kind”) + +Sessions use **Plan / Auto / YOLO** automation (see [docs/LOCAL.md](docs/LOCAL.md)). Featured example prompt matches `freya.png` brand art. ## 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 @@ -54,39 +86,42 @@ kubectl -n freya create secret generic freya-civitai --from-literal=apiKey="$CIV 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)" -# remote GPU box +# recommended: external worker URL → local / LAN GPU host kubectl apply -f config/samples/freya_v1alpha1_freyadiffusionworker_external.yaml -# or in-cluster GPU +# optional: only if the cluster itself has nvidia.com/gpu # kubectl apply -f config/samples/freya_v1alpha1_freyadiffusionworker_incluster.yaml kubectl apply -f config/samples/freya_v1alpha1_freyastudio.yaml ``` -### Workers: in-cluster or remote physical +### Workers: external URL (recommended) or optional in-cluster GPU | Placement | Spec | Use when | |-----------|------|----------| -| `incluster` | GPU Deployment + models PVC | Cluster has `nvidia.com/gpu` | -| `external` | `externalEndpoint: http://host:8091` | Physical box / bare-metal GPU | +| `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 | `FreyaModelAsset` (or UI **Civitai → Install to worker**) pushes LoRAs onto that worker so they show up for local generation. -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. +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. ## CRDs -- `FreyaStudio` — API + UI + gallery; OpenRouter + **Civitai** + HF secret refs +- `FreyaStudio` — API + UI + gallery + **MCP** (`mcpEnabled`, default on); OpenRouter + **Civitai** + HF secret refs - `FreyaGeneration` — declarative generate job - `FreyaStyle` — curated style packs -- `FreyaDiffusionWorker` — in-cluster or external engine +- `FreyaDiffusionWorker` — external URL (recommended) or optional in-cluster 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 4b0d7ee..dbadbbd 100644 --- a/config/crd/freya.dataknife.ai_crds.yaml +++ b/config/crd/freya.dataknife.ai_crds.yaml @@ -26,8 +26,17 @@ spec: description: Auto-generated derived type for FreyaStudioSpec via `CustomResource` properties: spec: - description: 'Namespaced Freya studio: API + UI + gallery.' + description: 'Namespaced Freya studio: API + UI + gallery + optional MCP.' 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 @@ -43,11 +52,11 @@ spec: type: string type: object apiTokenSecretRef: - description: Secret holding `FREYA_API_TOKEN` for the API. Set for non-dev / Ingress; UI sends the bearer from Settings. + 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: apiKey + default: token type: string name: type: string @@ -90,6 +99,10 @@ 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. @@ -120,12 +133,35 @@ 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: openrouter/auto - imageModel: black-forest-labs/flux.2-klein-4b + chatModel: auto + imageModel: auto + routerModel: auto secretRef: key: apiKey name: freya-openrouter @@ -134,12 +170,16 @@ spec: default: https://openrouter.ai/api/v1 type: string chatModel: - default: openrouter/auto - description: Default chat / plan model id (OpenRouter). + default: auto + description: Default chat / plan model id. `auto` = Freya internal Auto (not `openrouter/auto`). type: string imageModel: - default: black-forest-labs/flux.2-klein-4b - description: Default cloud image model id (OpenRouter). + 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). type: string secretRef: description: Reference to a Secret key holding credentials. @@ -188,9 +228,25 @@ 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 @@ -447,7 +503,7 @@ spec: description: |- Optional GPU worker for local SD / LoRA (vLLM-Omni by default). - 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. + 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. properties: authSecretRef: description: Optional admin/API token Secret for remote LoRA install + generate. diff --git a/config/rbac/role.yaml b/config/rbac/role.yaml index 713652a..6cb35a7 100644 --- a/config/rbac/role.yaml +++ b/config/rbac/role.yaml @@ -20,7 +20,10 @@ rules: resources: ["deployments"] verbs: ["get", "list", "watch", "create", "update", "patch", "delete"] - apiGroups: [""] - resources: ["services", "persistentvolumeclaims", "pods", "configmaps", "secrets"] + resources: ["services", "persistentvolumeclaims", "pods", "configmaps", "secrets", "serviceaccounts"] + verbs: ["get", "list", "watch", "create", "update", "patch", "delete"] + - apiGroups: ["rbac.authorization.k8s.io"] + resources: ["roles", "rolebindings"] verbs: ["get", "list", "watch", "create", "update", "patch", "delete"] - apiGroups: ["batch"] resources: ["jobs"] diff --git a/config/samples/freya_mcp_standalone.yaml b/config/samples/freya_mcp_standalone.yaml new file mode 100644 index 0000000..d121f7b --- /dev/null +++ b/config/samples/freya_mcp_standalone.yaml @@ -0,0 +1,61 @@ +# Optional standalone MCP Deployment+Service (when not using FreyaStudio mcpEnabled). +# Prefer FreyaStudio.spec.mcpEnabled (default true) so the operator owns these + Ingress /mcp. +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: freya-mcp + namespace: freya + labels: + app.kubernetes.io/name: freya + app.kubernetes.io/component: mcp +spec: + replicas: 1 + selector: + matchLabels: + app.kubernetes.io/name: freya + app.kubernetes.io/component: mcp + template: + metadata: + labels: + app.kubernetes.io/name: freya + app.kubernetes.io/component: mcp + spec: + containers: + - name: mcp + image: harbor.dataknife.net/library/freya-mcp:0.1.0 + imagePullPolicy: IfNotPresent + ports: + - name: http + containerPort: 8090 + env: + - name: FREYA_API_URL + value: http://freya-api:8080 + - name: FREYA_MCP_BIND + value: 0.0.0.0:8090 + - name: FREYA_API_TOKEN + valueFrom: + secretKeyRef: + name: freya-api-token + key: token + # Empty or * is loopback only and does not disable the check. + # Service DNS, port-forward loopback, and the public Ingress host. + - name: FREYA_MCP_ALLOWED_HOSTS + value: freya.dataknife.net,freya-mcp,freya-mcp.freya,freya-mcp.freya.svc,freya-mcp.freya.svc.cluster.local,localhost,127.0.0.1,::1 +--- +apiVersion: v1 +kind: Service +metadata: + name: freya-mcp + namespace: freya + labels: + app.kubernetes.io/name: freya + app.kubernetes.io/component: mcp +spec: + selector: + app.kubernetes.io/name: freya + app.kubernetes.io/component: mcp + ports: + - name: http + port: 8090 + targetPort: 8090 diff --git a/config/samples/freya_v1alpha1_freyadiffusionworker_external.yaml b/config/samples/freya_v1alpha1_freyadiffusionworker_external.yaml index 12a3874..81a5de4 100644 --- a/config/samples/freya_v1alpha1_freyadiffusionworker_external.yaml +++ b/config/samples/freya_v1alpha1_freyadiffusionworker_external.yaml @@ -1,12 +1,27 @@ -# Remote physical GPU box (or any host running vLLM-Omni / freya-worker) +# 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 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 - externalEndpoint: http://gpu-box.lan:8091 + # Public / LAN URL of freya-local-worker (or vLLM-Omni-compatible) — not the Freya UI host. + externalEndpoint: https://vllm.dataknife.net engine: vllm-omni # Must match FREYA_WORKER_TOKEN on the remote worker process authSecretRef: diff --git a/config/samples/freya_v1alpha1_freyadiffusionworker_incluster.yaml b/config/samples/freya_v1alpha1_freyadiffusionworker_incluster.yaml index 83d6fd3..9bfa0a4 100644 --- a/config/samples/freya_v1alpha1_freyadiffusionworker_incluster.yaml +++ b/config/samples/freya_v1alpha1_freyadiffusionworker_incluster.yaml @@ -1,4 +1,5 @@ -# In-cluster GPU Deployment (requires nvidia.com/gpu) +# 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. apiVersion: freya.dataknife.ai/v1alpha1 kind: FreyaDiffusionWorker metadata: diff --git a/config/samples/freya_v1alpha1_freyastudio.yaml b/config/samples/freya_v1alpha1_freyastudio.yaml index 7714498..2a2edf0 100644 --- a/config/samples/freya_v1alpha1_freyastudio.yaml +++ b/config/samples/freya_v1alpha1_freyastudio.yaml @@ -5,13 +5,25 @@ 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: openrouter/auto - imageModel: black-forest-labs/flux.2-klein-4b - # Required for non-dev / Ingress — bearer on /v1 (paste into UI Settings). + 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 @@ -24,15 +36,40 @@ 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: false + 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 --- -# Create Secrets first (see README Cluster section). Example: +# 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") diff --git a/config/samples/freya_v1alpha1_freyastyle.yaml b/config/samples/freya_v1alpha1_freyastyle.yaml new file mode 100644 index 0000000..af4d579 --- /dev/null +++ b/config/samples/freya_v1alpha1_freyastyle.yaml @@ -0,0 +1,15 @@ +# Curated style pack — NL example from freya.png brand art (not SD tag soup) +apiVersion: freya.dataknife.ai/v1alpha1 +kind: FreyaStyle +metadata: + name: freya-winged-warrior + namespace: freya +spec: + displayName: Freya (brand art) + tags: [character, fantasy, wings] + examplePrompt: > + A young woman with large brown eagle wings and fantasy leather armor, + standing in a green canyon with a waterfall behind her + backend: openrouter + openRouterModel: black-forest-labs/flux.2-klein-4b + recommendedSize: "1024x1024" diff --git a/crates/freya-api/Cargo.toml b/crates/freya-api/Cargo.toml index 01c5222..0cbc9d4 100644 --- a/crates/freya-api/Cargo.toml +++ b/crates/freya-api/Cargo.toml @@ -25,3 +25,4 @@ tracing = { workspace = true } tracing-subscriber = { workspace = true } uuid = { workspace = true } thiserror = { workspace = true } +libc = "0.2" diff --git a/crates/freya-api/src/auto_matrix.rs b/crates/freya-api/src/auto_matrix.rs new file mode 100644 index 0000000..ea87b2f --- /dev/null +++ b/crates/freya-api/src/auto_matrix.rs @@ -0,0 +1,242 @@ +//! Built-in Auto fallback matrix, loaded from `packs/auto-models.json`. +//! +//! The packs file is the source of truth. A missing or invalid file does not +//! stop the process: a small built-in matrix (one id per alignment, every cost) +//! is used so routing still returns a model. + +use serde::Deserialize; +use std::path::{Path, PathBuf}; +use std::sync::OnceLock; +use tracing::warn; + +static MATRIX: OnceLock = OnceLock::new(); + +#[derive(Debug, Clone, Deserialize)] +struct CostSet { + low: String, + medium: String, + high: String, + max: String, +} + +#[derive(Debug, Clone, Deserialize)] +struct AlignSet { + balanced: CostSet, + safety: CostSet, + uncensored: CostSet, +} + +#[derive(Debug, Clone, Deserialize)] +struct PrivacySet { + default: AlignSet, + zdr: AlignSet, +} + +#[derive(Debug, Clone, Deserialize)] +struct AutoMatrix { + router: PrivacySet, + agent: PrivacySet, + image: PrivacySet, + video: PrivacySet, + #[serde(default)] + notes: Vec, +} + +/// Load `packs/auto-models.json` once. Later calls are no-ops. +pub fn init(packs_dir: &Path) { + let matrix = matrix_from_packs(packs_dir); + if MATRIX.set(matrix).is_err() { + warn!("auto matrix already installed; packs file was not applied"); + } +} + +/// Role × privacy × alignment × cost. Unknown alignment is balanced. +/// Unknown cost is medium. Empty cells cannot occur in a parsed file. +pub fn model_for(role: &str, strict: bool, alignment: &str, cost: &str) -> String { + let matrix = current(); + let privacy = match role { + "router" => &matrix.router, + "agent" => &matrix.agent, + "image" => &matrix.image, + "video" => &matrix.video, + _ => &matrix.agent, + }; + let align = if strict { &privacy.zdr } else { &privacy.default }; + let row = match alignment { + "safety" => &align.safety, + "uncensored" => &align.uncensored, + _ => &align.balanced, + }; + match cost { + "low" | "cheap" => row.low.clone(), + "high" => row.high.clone(), + "max" | "maximum" => row.max.clone(), + _ => row.medium.clone(), + } +} + +fn current() -> &'static AutoMatrix { + MATRIX.get_or_init(|| { + let bundled = repo_packs_file(); + if bundled.is_file() { + if let Some(matrix) = read_matrix(&bundled) { + return matrix; + } + } + small_fallback() + }) +} + +fn repo_packs_file() -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../packs/auto-models.json") +} + +fn matrix_from_packs(packs_dir: &Path) -> AutoMatrix { + let path = packs_dir.join("auto-models.json"); + if let Some(matrix) = read_matrix(&path) { + tracing::info!( + path = %path.display(), + notes = matrix.notes.len(), + "loaded auto fallback matrix" + ); + return matrix; + } + warn!( + path = %path.display(), + "auto-models.json missing or invalid; using the small built-in matrix" + ); + small_fallback() +} + +fn read_matrix(path: &Path) -> Option { + let text = std::fs::read_to_string(path).ok()?; + match serde_json::from_str::(&text) { + Ok(matrix) if matrix_complete(&matrix) => Some(matrix), + Ok(_) => { + warn!(path = %path.display(), "auto-models.json has an empty cell"); + None + } + Err(err) => { + warn!(path = %path.display(), %err, "auto-models.json did not parse"); + None + } + } +} + +fn matrix_complete(matrix: &AutoMatrix) -> bool { + [&matrix.router, &matrix.agent, &matrix.image, &matrix.video] + .into_iter() + .all(privacy_complete) +} + +fn privacy_complete(block: &PrivacySet) -> bool { + align_complete(&block.default) && align_complete(&block.zdr) +} + +fn align_complete(block: &AlignSet) -> bool { + cost_complete(&block.balanced) + && cost_complete(&block.safety) + && cost_complete(&block.uncensored) +} + +fn cost_complete(row: &CostSet) -> bool { + !row.low.trim().is_empty() + && !row.medium.trim().is_empty() + && !row.high.trim().is_empty() + && !row.max.trim().is_empty() +} + +/// One id per alignment so boot still routes when the packs file is absent. +/// Costs share that id. This is not the researched matrix. +fn small_fallback() -> AutoMatrix { + fn cost(id: &str) -> CostSet { + CostSet { + low: id.to_string(), + medium: id.to_string(), + high: id.to_string(), + max: id.to_string(), + } + } + fn align(balanced: &str, safety: &str, uncensored: &str) -> AlignSet { + AlignSet { + balanced: cost(balanced), + safety: cost(safety), + uncensored: cost(uncensored), + } + } + fn privacy(balanced: &str, safety: &str, uncensored: &str) -> PrivacySet { + let row = align(balanced, safety, uncensored); + PrivacySet { + default: row.clone(), + zdr: row, + } + } + AutoMatrix { + router: privacy( + "deepseek/deepseek-v4-pro", + "openai/gpt-5-mini", + "thedrummer/cydonia-24b-v4.1", + ), + agent: privacy( + "deepseek/deepseek-v4-pro", + "openai/gpt-5-mini", + "thedrummer/cydonia-24b-v4.1", + ), + image: privacy( + "bytedance-seed/seedream-4.5", + "openai/gpt-image-2", + "black-forest-labs/flux-3-image", + ), + video: privacy( + "bytedance/seedance-2.5-flash", + "google/veo-3.1-fast", + "x-ai/grok-imagine-video", + ), + notes: vec![ + "Small built-in matrix. packs/auto-models.json was missing or invalid.".into(), + ], + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn packs_file_fills_every_cell() { + let path = repo_packs_file(); + let matrix = read_matrix(&path).expect("packs/auto-models.json"); + assert!(matrix.notes.iter().any(|n| n.contains("video") && n.contains("ZDR"))); + let roles = [&matrix.router, &matrix.agent, &matrix.image, &matrix.video]; + assert_eq!(roles.len(), 4); + assert!(matrix_complete(&matrix)); + } + + #[test] + fn uncensored_chat_is_not_llama_claude_or_gpt() { + let _ = current(); + for role in ["router", "agent"] { + for strict in [false, true] { + for cost in ["low", "medium", "high", "max"] { + let id = model_for(role, strict, "uncensored", cost); + let l = id.to_ascii_lowercase(); + assert!( + l.contains("dolphin") || l.contains("cydonia"), + "{role} strict={strict} {cost} -> {id}" + ); + assert!(!l.contains("llama"), "{id}"); + assert!(!l.starts_with("anthropic/"), "{id}"); + assert!(!l.starts_with("openai/"), "{id}"); + } + } + } + } + + #[test] + fn missing_file_uses_small_fallback() { + let matrix = matrix_from_packs(Path::new("/tmp/freya-auto-matrix-missing")); + assert_eq!(matrix.agent.default.balanced.low, matrix.agent.default.balanced.max); + assert!(!matrix.video.default.safety.medium.is_empty()); + assert!(!matrix.video.zdr.uncensored.max.is_empty()); + } +} diff --git a/crates/freya-api/src/base_models.rs b/crates/freya-api/src/base_models.rs new file mode 100644 index 0000000..04c52ea --- /dev/null +++ b/crates/freya-api/src/base_models.rs @@ -0,0 +1,212 @@ +//! Civitai `baseModel` → local checkpoint / HF id hints for the diffusion worker. +//! +//! Remote vLLM image endpoints may not support SD checkpoints; the local GPU worker +//! (`FREYA_MODELS_DIR` on the game drive / PVC) is the path that hosts these bases. + +use serde_json::{json, Value}; + +/// Known Civitai base-family labels → preferred HuggingFace / engine model id. +/// Used when no local checkpoint is selected yet (hint only — stub worker echoes it). +pub fn suggest_hf_model(base_model: &str) -> Option<&'static str> { + let b = normalize_base(base_model); + Some(match b.as_str() { + "sd 1.5" | "sd1.5" | "stable diffusion 1.5" => "runwayml/stable-diffusion-v1-5", + "sd 2.1" | "sd2.1" => "stabilityai/stable-diffusion-2-1", + "sdxl" | "sdxl 1.0" | "stable diffusion xl 1.0" => { + "stabilityai/stable-diffusion-xl-base-1.0" + } + "sdxl turbo" | "sdxl-turbo" => "stabilityai/sdxl-turbo", + "pony" | "pony diffusion" => "checkpoints/pony-diffusion-v6-xl.safetensors", + "illustrious" => "checkpoints/illustrious.safetensors", + "flux" | "flux.1 d" | "flux.1 s" | "flux1" => "black-forest-labs/FLUX.1-dev", + "noobai" => "checkpoints/noobai.safetensors", + _ => return None, + }) +} + +/// Human family label for UI / compatibility checks. +pub fn family_label(base_model: &str) -> String { + let b = normalize_base(base_model); + match b.as_str() { + s if s.starts_with("sd 1.5") || s == "sd1.5" => "SD 1.5".into(), + s if s.starts_with("sd 2") => "SD 2.x".into(), + s if s.contains("sdxl") => "SDXL".into(), + s if s.contains("pony") => "Pony".into(), + s if s.contains("illustrious") => "Illustrious".into(), + s if s.contains("flux") => "Flux".into(), + s if s.contains("noobai") => "NoobAI".into(), + _ => base_model.trim().to_string(), + } +} + +/// True when two Civitai-ish base labels are compatible enough for LoRA apply. +pub fn bases_compatible(a: &str, b: &str) -> bool { + if a.trim().is_empty() || b.trim().is_empty() { + return true; + } + family_label(a).eq_ignore_ascii_case(&family_label(b)) +} + +fn normalize_base(s: &str) -> String { + s.trim().to_ascii_lowercase() +} + +/// Static catalog for UI / API discovery (does not hit Civitai). +pub fn catalog() -> Vec { + vec![ + entry("SD 1.5", "runwayml/stable-diffusion-v1-5", "~4GB VRAM"), + entry( + "SDXL 1.0", + "stabilityai/stable-diffusion-xl-base-1.0", + "~6–8GB VRAM", + ), + entry( + "Pony", + "checkpoints/pony-diffusion-v6-xl.safetensors", + "SDXL-family; install a Pony checkpoint under checkpoints/", + ), + entry( + "Illustrious", + "checkpoints/illustrious.safetensors", + "SDXL-family; install under checkpoints/", + ), + entry( + "Flux", + "black-forest-labs/FLUX.1-dev", + "~20GB+ VRAM; local 4090 may need offload / quantized build", + ), + ] +} + +fn entry(base: &str, model: &str, note: &str) -> Value { + json!({ + "baseModel": base, + "family": family_label(base), + "suggestedModel": model, + "note": note, + "localOnly": true, + }) +} + +/// Pick a generate `model` from pinned LoRA metadata when the client omitted one. +pub fn resolve_model_from_loras(loras: &[LoraBaseHint]) -> Option { + for l in loras { + if let Some(b) = l.base_model.as_deref().filter(|s| !s.is_empty()) { + if let Some(m) = suggest_hf_model(b) { + return Some(m.to_string()); + } + return Some(format!("checkpoints/{}.safetensors", sanitize_name(b))); + } + } + None +} + +/// True when `model` is a local checkpoint path the Diffusers worker can load as a file +/// (not an OpenRouter Auto sentinel, cloud id, or router prose). +/// +/// Local generate must never pass strings like `"None, letting Freya use Auto default +/// (ZDR-aware)."` or `black-forest-labs/flux…` when the user picked Auto — those become +/// invalid HF repo ids. Prefer the worker active base instead. +pub fn is_usable_local_model(model: &str) -> bool { + let m = model.trim(); + if m.is_empty() { + return false; + } + // Auto / cloud sentinels and router prose (spaces, commas, parentheses). + if crate::router::is_auto_image(m) { + return false; + } + if m.contains(char::is_whitespace) || m.contains(',') || m.contains('(') { + return false; + } + let lower = m.to_ascii_lowercase(); + if lower == "none" + || lower.starts_with("none,") + || lower.contains("zdr-aware") + || lower.contains("letting freya") + || lower.contains("auto default") + { + return false; + } + // Checkpoint file / relative path under models PVC. + if m.ends_with(".safetensors") + || m.starts_with("checkpoints/") + || m.starts_with("models/") + || (m.starts_with('/') && m.contains(".safetensors")) + { + return true; + } + false +} + +/// Keep only a local-usable checkpoint ref; otherwise `None` (worker active base). +pub fn filter_local_model(model: Option<&str>) -> Option { + model + .map(str::trim) + .filter(|s| !s.is_empty() && is_usable_local_model(s)) + .map(str::to_string) +} + +#[derive(Debug, Clone)] +pub struct LoraBaseHint { + pub base_model: Option, +} + +fn sanitize_name(s: &str) -> String { + s.chars() + .map(|c| { + if c.is_ascii_alphanumeric() || c == '.' || c == '_' || c == '-' { + c + } else { + '_' + } + }) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn sdxl_maps() { + assert_eq!( + suggest_hf_model("SDXL 1.0"), + Some("stabilityai/stable-diffusion-xl-base-1.0") + ); + assert!(bases_compatible("SDXL 1.0", "SDXL")); + assert!(!bases_compatible("SD 1.5", "Pony")); + } + + #[test] + fn resolve_from_lora() { + let hints = vec![LoraBaseHint { + base_model: Some("Pony".into()), + }]; + assert!(resolve_model_from_loras(&hints) + .unwrap() + .contains("pony")); + } + + #[test] + fn local_model_rejects_auto_prose_and_cloud() { + assert!(is_usable_local_model( + "checkpoints/pony-diffusion-v6-xl.safetensors" + )); + assert!(is_usable_local_model("checkpoints/foo.safetensors")); + assert!(!is_usable_local_model("auto")); + assert!(!is_usable_local_model("openrouter/auto")); + assert!(!is_usable_local_model( + "None, letting Freya use Auto default (ZDR-aware)." + )); + assert!(!is_usable_local_model( + "black-forest-labs/flux.2-klein-4b" + )); + assert!(!is_usable_local_model("google/gemini-2.5-flash-image")); + assert!(filter_local_model(Some("auto")).is_none()); + assert!(filter_local_model(Some( + "checkpoints/pony-diffusion-v6-xl.safetensors" + )) + .is_some()); + } +} diff --git a/crates/freya-api/src/civitai.rs b/crates/freya-api/src/civitai.rs index 6bfa41c..89b8789 100644 --- a/crates/freya-api/src/civitai.rs +++ b/crates/freya-api/src/civitai.rs @@ -4,6 +4,41 @@ 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, @@ -23,82 +58,556 @@ 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 url = format!( + let mut 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 search")?; + .context("civitai http")?; let status = resp.status(); let text = resp.text().await.unwrap_or_default(); if !status.is_success() { return Err(anyhow!("civitai {status}: {text}")); } - 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()); - } - } - } + 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()); } - out.push(CivitaiModelCard { - id, - name, - model_type, - version_id, - download_url, - thumbnail_url: thumbnail, - example_prompt, - }); } } - Ok(out) + } + 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()); + } + image_urls.push(u.clone()); + } + } + 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 } } @@ -117,6 +626,124 @@ fn urlencoding_lite(s: &str) -> String { 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, +} + #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct CivitaiModelCard { @@ -126,9 +753,103 @@ 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 ff2337f..633172c 100644 --- a/crates/freya-api/src/config.rs +++ b/crates/freya-api/src/config.rs @@ -1,4 +1,7 @@ +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)] @@ -17,16 +20,18 @@ pub struct Config { )] pub openrouter_base_url: String, - #[arg(long, env = "FREYA_CHAT_MODEL", default_value = "openrouter/auto")] + /// Agent / plan chat model. `auto` = Freya internal Auto (not OpenRouter's upstream router). + #[arg(long, env = "FREYA_CHAT_MODEL", default_value = "auto")] pub chat_model: String, - #[arg( - long, - env = "FREYA_IMAGE_MODEL", - default_value = "black-forest-labs/flux.2-klein-4b" - )] + /// Still-image model. `auto` = Freya router / Flux NL default (legacy Flux alignment). + #[arg(long, env = "FREYA_IMAGE_MODEL", default_value = "auto")] 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,17 +66,169 @@ pub struct Config { #[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() } @@ -80,6 +237,14 @@ 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/disk.rs b/crates/freya-api/src/disk.rs new file mode 100644 index 0000000..4eabeee --- /dev/null +++ b/crates/freya-api/src/disk.rs @@ -0,0 +1,49 @@ +//! Filesystem capacity for gallery PVC / data dirs (df-style via statvfs). + +use serde_json::{json, Value}; +use std::ffi::CString; +use std::path::Path; + +/// Return `{ path, usedBytes, freeBytes, totalBytes, usedPercent }` or `Null`. +pub fn collect_path_disk(path: &Path) -> Value { + 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), + }) + } +} diff --git a/crates/freya-api/src/gallery.rs b/crates/freya-api/src/gallery.rs index 5d7fed0..71d9aa2 100644 --- a/crates/freya-api/src/gallery.rs +++ b/crates/freya-api/src/gallery.rs @@ -41,11 +41,7 @@ impl Gallery { meta: &mut ArtifactMeta, ) -> Result { let id = Uuid::new_v4().to_string(); - let ext = if mime.contains("jpeg") || mime.contains("jpg") { - "jpg" - } else { - "png" - }; + let ext = mime_to_ext(mime); let filename = format!("{id}.{ext}"); meta.id = id.clone(); meta.filename = filename.clone(); @@ -89,6 +85,27 @@ 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) } @@ -102,3 +119,55 @@ fn sanitize_gallery_id(id: &str) -> Option<&str> { 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/gpu.rs b/crates/freya-api/src/gpu.rs new file mode 100644 index 0000000..e858ec5 --- /dev/null +++ b/crates/freya-api/src/gpu.rs @@ -0,0 +1,67 @@ +//! Host GPU stats via `nvidia-smi` (used when the worker cannot see the GPU). + +use serde_json::{json, Value}; +use tokio::process::Command; + +/// Parse `nvidia-smi` CSV into `{ usedMiB, totalMiB, utilPercent, gpus }` or `Null`. +pub async fn collect_host_vram() -> 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; + }; + if !out.status.success() { + return 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; + } + let n = gpus.len() as u64; + json!({ + "usedMiB": used_total, + "totalMiB": mem_total, + "utilPercent": util_sum / n.max(1), + "gpus": gpus, + "source": "host-nvidia-smi", + }) +} + +pub 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()) +} diff --git a/crates/freya-api/src/k8s_secret.rs b/crates/freya-api/src/k8s_secret.rs new file mode 100644 index 0000000..416d235 --- /dev/null +++ b/crates/freya-api/src/k8s_secret.rs @@ -0,0 +1,99 @@ +//! Best-effort sync of the rotated studio API token into a Kubernetes Secret. +//! +//! When `FREYA_API_TOKEN_SECRET_NAME` is set and the pod has an in-cluster service +//! account that can patch that Secret, UI rotates stay aligned with MCP / env clients. + +use anyhow::{anyhow, Context}; +use base64::Engine; +use tracing::{info, warn}; + +/// Patch `data.` on the named Secret. Returns `Ok(true)` when the Secret was updated, +/// `Ok(false)` when sync is not configured (no secret name), or `Err` on failure. +pub async fn sync_api_token_secret(token: &str) -> anyhow::Result { + let secret_name = std::env::var("FREYA_API_TOKEN_SECRET_NAME").unwrap_or_default(); + if secret_name.trim().is_empty() { + return Ok(false); + } + let secret_key = + std::env::var("FREYA_API_TOKEN_SECRET_KEY").unwrap_or_else(|_| "token".into()); + let namespace = resolve_namespace()?; + let sa_token = std::fs::read_to_string( + "/var/run/secrets/kubernetes.io/serviceaccount/token", + ) + .context("read in-cluster service account token")?; + let host = std::env::var("KUBERNETES_SERVICE_HOST") + .context("KUBERNETES_SERVICE_HOST (not in-cluster?)")?; + let port = std::env::var("KUBERNETES_SERVICE_PORT").unwrap_or_else(|_| "443".into()); + + let ca_pem = std::fs::read("/var/run/secrets/kubernetes.io/serviceaccount/ca.crt") + .context("read service account CA")?; + let cert = reqwest::Certificate::from_pem(&ca_pem).context("parse service account CA")?; + let client = reqwest::Client::builder() + .add_root_certificate(cert) + .use_rustls_tls() + .build() + .context("build kubernetes API client")?; + + let b64 = base64::engine::general_purpose::STANDARD.encode(token.as_bytes()); + let body = serde_json::json!({ + "data": { secret_key: b64 } + }); + let url = format!( + "https://{host}:{port}/api/v1/namespaces/{namespace}/secrets/{secret_name}" + ); + let res = client + .patch(&url) + .header( + reqwest::header::AUTHORIZATION, + format!("Bearer {}", sa_token.trim()), + ) + .header( + reqwest::header::CONTENT_TYPE, + "application/strategic-merge-patch+json", + ) + .json(&body) + .send() + .await + .context("patch secret")?; + let status = res.status(); + if !status.is_success() { + let text = res.text().await.unwrap_or_default(); + return Err(anyhow!( + "patch secret {namespace}/{secret_name}: HTTP {status}: {text}" + )); + } + info!( + %namespace, + secret = %secret_name, + "synced rotated API token into Kubernetes Secret" + ); + Ok(true) +} + +fn resolve_namespace() -> anyhow::Result { + if let Ok(ns) = std::env::var("FREYA_NAMESPACE") { + if !ns.trim().is_empty() { + return Ok(ns); + } + } + let ns = std::fs::read_to_string( + "/var/run/secrets/kubernetes.io/serviceaccount/namespace", + ) + .context("read in-cluster namespace")?; + let ns = ns.trim().to_string(); + if ns.is_empty() { + return Err(anyhow!("empty in-cluster namespace")); + } + Ok(ns) +} + +/// Run sync and log failures without failing the token rotate response. +pub async fn try_sync_api_token_secret(token: &str) -> bool { + match sync_api_token_secret(token).await { + Ok(synced) => synced, + Err(e) => { + warn!(error = %e, "could not sync API token to Kubernetes Secret — use sync commands or scripts/sync-api-token-from-pvc.sh"); + false + } + } +} diff --git a/crates/freya-api/src/main.rs b/crates/freya-api/src/main.rs index 45008a6..403b0da 100644 --- a/crates/freya-api/src/main.rs +++ b/crates/freya-api/src/main.rs @@ -1,11 +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}; @@ -13,6 +22,7 @@ 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; @@ -32,11 +42,15 @@ async fn main() -> anyhow::Result<()> { let cfg = Config::parse(); let bind = cfg.bind.clone(); let cors = build_cors(&cfg); - let require_auth = !cfg.api_token.trim().is_empty(); + let require_auth = cfg.auth_required(); if !require_auth { warn!( - "FREYA_API_TOKEN unset — /v1 routes are open (local/dev only). \ - Set FREYA_API_TOKEN (and FreyaStudio apiTokenSecretRef in-cluster) for non-dev." + "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)"); @@ -46,20 +60,60 @@ async fn main() -> anyhow::Result<()> { let protected = Router::new() .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)) + .route( + "/v1/gallery/{id}", + get(routes::gallery_get).delete(routes::gallery_delete), + ) .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, @@ -68,6 +122,8 @@ async fn main() -> anyhow::Result<()> { 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(TraceLayer::new_for_http()) @@ -91,20 +147,34 @@ fn build_cors(cfg: &Config) -> CorsLayer { .collect(); CorsLayer::new() .allow_origin(AllowOrigin::list(list)) - .allow_methods([Method::GET, Method::POST, Method::PUT, Method::OPTIONS]) + .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::OPTIONS]) + .allow_methods([ + Method::GET, + Method::POST, + Method::PUT, + Method::DELETE, + Method::OPTIONS, + ]) .allow_headers([header::AUTHORIZATION, header::CONTENT_TYPE]) } else { CorsLayer::permissive() } } -/// When `FREYA_API_TOKEN` is set, require `Authorization: Bearer ` on all `/v1` methods +/// 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, @@ -119,11 +189,16 @@ async fn require_api_token( return Ok(next.run(req).await); } - let expected = { + let (api_token, admin_user, admin_password, auth_required) = { let cfg = state.config.read().await; - cfg.api_token.trim().to_string() + ( + cfg.api_token.trim().to_string(), + cfg.admin_user.trim().to_string(), + cfg.admin_password.trim().to_string(), + cfg.auth_required(), + ) }; - if expected.is_empty() { + if !auth_required { return Ok(next.run(req).await); } @@ -132,14 +207,49 @@ async fn require_api_token( .get(header::AUTHORIZATION) .and_then(|v| v.to_str().ok()) .unwrap_or(""); - let ok = auth - .strip_prefix("Bearer ") - .map(|t| t == expected) - .unwrap_or(false); - if !ok { - return Err(StatusCode::UNAUTHORIZED); + + 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; } - Ok(next.run(req).await) + a.bytes() + .zip(b.bytes()) + .fold(0u8, |acc, (x, y)| acc | (x ^ y)) + == 0 } fn is_gallery_image_path(path: &str) -> bool { diff --git a/crates/freya-api/src/openrouter.rs b/crates/freya-api/src/openrouter.rs index 41c7175..b03a30e 100644 --- a/crates/freya-api/src/openrouter.rs +++ b/crates/freya-api/src/openrouter.rs @@ -1,4 +1,8 @@ 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; @@ -10,6 +14,10 @@ pub struct OpenRouterClient { api_key: String, chat_model: String, image_model: String, + router_model: String, + privacy: PrivacyPrefs, + alignment: AlignmentPrefs, + auto_fallbacks: AutoFallbacksPrefs, } impl OpenRouterClient { @@ -20,6 +28,10 @@ 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(), } } @@ -28,10 +40,57 @@ impl OpenRouterClient { self } - pub fn default_image_model(&self) -> &str { + #[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 { &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")); @@ -50,20 +109,104 @@ impl OpenRouterClient { let status = resp.status(); let text = resp.text().await.unwrap_or_default(); if !status.is_success() { - return Err(anyhow!("openrouter {status}: {text}")); + 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) + )); } 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 body = serde_json::json!({ + let mut 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()) @@ -73,8 +216,33 @@ impl OpenRouterClient { pub async fn list_image_models(&self) -> Result> { if self.api_key.is_empty() { - return Ok(fallback_models()); + 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)); } + let url = format!("{}/images/models", self.base); let resp = self .http @@ -87,9 +255,55 @@ impl OpenRouterClient { return Ok(fallback_models()); } let v: Value = resp.json().await.unwrap_or(Value::Null); - let mut out = Vec::new(); + 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(); 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()) @@ -98,22 +312,105 @@ impl OpenRouterClient { if id.is_empty() { continue; } - let name = m - .get("name") - .and_then(|x| x.as_str()) - .unwrap_or(&id) - .to_string(); - out.push(ImageModel { + 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 { id, name, backend: "openrouter".into(), - }); + }; + if agent_ok { + agent_scored.push((created, model.clone())); + } + if router_ok { + router_scored.push((created, model)); + } } } - if out.is_empty() { - return Ok(fallback_models()); + if agent_scored.is_empty() && router_scored.is_empty() && available_set.is_empty() { + return Ok(self.fallback_chat_catalog()); } - Ok(out) + 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()); + } + let v: Value = resp.json().await.unwrap_or(Value::Null); + Ok(parse_video_models(&v)) } pub async fn generate_image( @@ -122,7 +419,54 @@ impl OpenRouterClient { model: Option<&str>, size: Option<&str>, ) -> Result { - let model = model.unwrap_or(&self.image_model); + 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 mut body = serde_json::json!({ "model": model, "prompt": prompt, @@ -135,21 +479,405 @@ impl OpenRouterClient { body["size"] = Value::String(size.into()); } } + inject_provider(&mut body, &self.privacy); - // 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) + 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()); + } + } + 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> { @@ -161,7 +889,83 @@ fn size_to_aspect(size: &str) -> Option<&'static str> { } } -fn extract_image(v: &Value) -> Result { +/// 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 { if let Some(b64) = v.pointer("/data/0/b64_json").and_then(|x| x.as_str()) { return Ok(GeneratedImage { b64: b64.to_string(), @@ -169,13 +973,41 @@ fn extract_image(v: &Value) -> Result { }); } if let Some(url) = v.pointer("/data/0/url").and_then(|x| x.as_str()) { - if let Some(rest) = url.strip_prefix("data:image/png;base64,") { + if let Some(rest) = url + .strip_prefix("data:image/png;base64,") + .or_else(|| url.strip_prefix("data:image/jpeg;base64,")) + { + let mime = if url.contains("jpeg") { + "image/jpeg" + } else { + "image/png" + }; return Ok(GeneratedImage { b64: rest.to_string(), - mime: "image/png".into(), + mime: mime.into(), }); } - return Err(anyhow!("image url responses not downloaded yet: {url}")); + // Remote URL — download bytes. + let resp = http + .get(url) + .send() + .await + .context("download openrouter image url")?; + if !resp.status().is_success() { + return Err(anyhow!("image url download failed: {}", resp.status())); + } + let mime = resp + .headers() + .get(reqwest::header::CONTENT_TYPE) + .and_then(|v| v.to_str().ok()) + .unwrap_or("image/png") + .to_string(); + let bytes = resp.bytes().await.context("read image bytes")?; + use base64::Engine; + return Ok(GeneratedImage { + b64: base64::engine::general_purpose::STANDARD.encode(&bytes), + mime, + }); } Err(anyhow!("no image in openrouter response")) } @@ -217,13 +1049,340 @@ fn fallback_models() -> Vec { backend: "openrouter".into(), }, ImageModel { - id: "openai/gpt-image-2".into(), - name: "GPT Image 2".into(), + 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(), 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, @@ -231,8 +1390,383 @@ 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/prefs.rs b/crates/freya-api/src/prefs.rs new file mode 100644 index 0000000..dc03d39 --- /dev/null +++ b/crates/freya-api/src/prefs.rs @@ -0,0 +1,549 @@ +//! OpenRouter privacy prefs (real API `provider` knobs) + Freya-side alignment / chat-vendor filters. + +use serde::{Deserialize, Serialize}; +use serde_json::{json, Value}; + +/// Freya-side chat picker vendor inclusion (not OpenRouter `provider.only` / `provider.ignore`). +/// +/// Semantics: **unchecked = hidden**. Persist the unchecked set (`excluded`) so newly +/// discovered catalog vendors default to **checked** (opt-out). Legacy `providerOnly` +/// free-text migrates into `legacy_only` until the user saves checkboxes. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)] +#[serde(rename_all = "camelCase")] +pub struct ChatProvidersPrefs { + /// Vendor prefixes the user unchecked (hidden from `/v1/models` chat). Empty = all shown. + #[serde(default)] + pub excluded: Vec, + /// One-shot include list from old `providerOnly`. When set, only these vendors show + /// (new vendors stay hidden). Cleared when Settings saves an explicit checkbox set. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub legacy_only: Option>, +} + +impl ChatProvidersPrefs { + pub fn normalize(mut self) -> Self { + self.excluded = normalize_slug_list(self.excluded); + if let Some(only) = self.legacy_only.take() { + let only = normalize_slug_list(only); + self.legacy_only = if only.is_empty() { None } else { Some(only) }; + } + self + } + + /// Whether a model id's vendor prefix is included in the chat picker. + pub fn includes_vendor(&self, vendor: &str) -> bool { + let v = vendor.trim().to_ascii_lowercase(); + if v.is_empty() { + return false; + } + if let Some(ref only) = self.legacy_only { + return only.iter().any(|s| s == &v); + } + !self.excluded.iter().any(|s| s == &v) + } + + /// Whether a full OpenRouter model id passes the vendor checkbox filter. + pub fn includes_model_id(&self, model_id: &str) -> bool { + let vendor = model_id.split_once('/').map(|(v, _)| v).unwrap_or(model_id); + self.includes_vendor(vendor) + } +} + +/// Per-request OpenRouter `provider` preferences Freya can set. +/// See https://openrouter.ai/docs/guides/routing/provider-selection +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct PrivacyPrefs { + /// Restrict routing to ZDR endpoints (`provider.zdr: true`). Off by default. + /// Cannot loosen account-wide ZDR; only enforce it on Freya requests. + #[serde(default)] + pub zero_data_retention: bool, + /// `allow` (default) or `deny` — maps to `provider.data_collection`. + /// `deny` = only providers that do not collect/store user data for training. + #[serde(default = "default_data_collection")] + pub data_collection: String, + /// Chat picker vendor checkboxes (Freya catalog filter). + #[serde(default)] + pub chat_providers: ChatProvidersPrefs, + /// Legacy free-text allowlist — migrated into `chat_providers.legacy_only` on normalize. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub provider_only: String, + /// Legacy free-text denylist — migrated into `chat_providers.excluded` on normalize. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub provider_ignore: String, +} + +fn default_data_collection() -> String { + "allow".into() +} + +impl Default for PrivacyPrefs { + fn default() -> Self { + Self { + zero_data_retention: false, + data_collection: default_data_collection(), + chat_providers: ChatProvidersPrefs::default(), + provider_only: String::new(), + provider_ignore: String::new(), + } + } +} + +impl PrivacyPrefs { + pub fn normalize(mut self) -> Self { + let dc = self.data_collection.trim().to_ascii_lowercase(); + self.data_collection = if dc == "deny" { "deny" } else { "allow" }.into(); + self.chat_providers = self.chat_providers.normalize(); + + // Migrate legacy free-text once into the checkbox model. + let ignore = split_slugs(&self.provider_ignore); + if self.chat_providers.excluded.is_empty() && !ignore.is_empty() { + self.chat_providers.excluded = ignore; + } + let only = split_slugs(&self.provider_only); + if self.chat_providers.legacy_only.is_none() && !only.is_empty() { + self.chat_providers.legacy_only = Some(only); + } + self.provider_only.clear(); + self.provider_ignore.clear(); + self.chat_providers = self.chat_providers.normalize(); + self + } + + /// Build OpenRouter `provider` object, or `None` when all defaults (omit field). + /// Chat vendor checkboxes are Freya-side only — not sent as `provider.only`/`ignore`. + pub fn to_provider_json(&self) -> Option { + let mut obj = serde_json::Map::new(); + if self.zero_data_retention { + obj.insert("zdr".into(), Value::Bool(true)); + } + if self.data_collection.eq_ignore_ascii_case("deny") { + obj.insert("data_collection".into(), Value::String("deny".into())); + } + if obj.is_empty() { + None + } else { + Some(Value::Object(obj)) + } + } +} + +fn split_slugs(raw: &str) -> Vec { + normalize_slug_list( + raw.split(|c: char| c == ',' || c.is_whitespace()) + .map(|s| s.to_string()) + .collect(), + ) +} + +fn normalize_slug_list(raw: Vec) -> Vec { + let mut out = Vec::new(); + for s in raw { + let t = s.trim().to_ascii_lowercase(); + if t.is_empty() { + continue; + } + if !out.iter().any(|x| x == &t) { + out.push(t); + } + } + out.sort(); + out +} + +/// Freya-side refusal / alignment preferences (not OpenRouter API flags). +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AlignmentPrefs { + /// `balanced` (default) | `safety` | `uncensored` + #[serde(default = "default_model_alignment")] + pub model_alignment: String, + /// When false, hide local / Civitai assets that look NSFW by name or API flag. + #[serde(default)] + pub allow_nsfw_local: bool, + /// System-instruction tone: `warm` (default) | `direct` | `steerable` + #[serde(default = "default_instruction_tone")] + pub instruction_tone: String, +} + +/// Configurable Auto fallbacks when the Freya router does not pin a concrete model. +/// Empty fields → built-in Privacy/Alignment matrix in `router::builtin_auto_fallback`. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)] +#[serde(rename_all = "camelCase")] +pub struct AutoFallbacksPrefs { + /// Agent/chat fallback (non-ZDR). Empty = built-in. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub agent: String, + /// Agent/chat fallback when Freya ZDR (or deny-collection) is on. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub agent_zdr: String, + /// Still-image fallback (non-ZDR). + #[serde(default, skip_serializing_if = "String::is_empty")] + pub image: String, + /// Still-image fallback when ZDR / deny-collection. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub image_zdr: String, + /// Video/T2V fallback (non-ZDR). + #[serde(default, skip_serializing_if = "String::is_empty")] + pub video: String, + /// Video fallback when ZDR / deny-collection. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub video_zdr: String, + /// Light intent-router model when Settings router is Auto. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub router: String, + /// Which column of the built-in Auto matrix to use: low | medium | high | max. + #[serde(default = "default_cost_tier")] + pub cost_tier: String, +} + +impl AutoFallbacksPrefs { + pub fn normalize(mut self) -> Self { + self.agent = trim_model_id(&self.agent); + self.agent_zdr = trim_model_id(&self.agent_zdr); + self.image = trim_model_id(&self.image); + self.image_zdr = trim_model_id(&self.image_zdr); + self.video = trim_model_id(&self.video); + self.video_zdr = trim_model_id(&self.video_zdr); + self.router = trim_model_id(&self.router); + self.cost_tier = normalize_cost_tier(&self.cost_tier); + self + } +} + +fn default_cost_tier() -> String { + "medium".into() +} + +fn normalize_cost_tier(raw: &str) -> String { + match raw.trim().to_ascii_lowercase().as_str() { + "low" | "cheap" => "low".into(), + "high" => "high".into(), + "max" | "maximum" => "max".into(), + _ => "medium".into(), + } +} + +fn trim_model_id(s: &str) -> String { + let t = s.trim(); + if t.is_empty() { + return String::new(); + } + // Bare Auto sentinel → empty (use built-in matrix). Upstream router is a picker pin, not a fallback. + if t.eq_ignore_ascii_case("auto") || t.eq_ignore_ascii_case("openrouter/auto") { + return String::new(); + } + if t.contains(char::is_whitespace) { + return String::new(); + } + t.to_string() +} + +fn default_model_alignment() -> String { + "balanced".into() +} + +fn default_instruction_tone() -> String { + "warm".into() +} + +impl Default for AlignmentPrefs { + fn default() -> Self { + Self { + model_alignment: default_model_alignment(), + allow_nsfw_local: false, + instruction_tone: default_instruction_tone(), + } + } +} + +impl AlignmentPrefs { + pub fn normalize(mut self) -> Self { + let a = self.model_alignment.trim().to_ascii_lowercase(); + self.model_alignment = match a.as_str() { + "safety" | "safe" | "aligned" => "safety".into(), + "uncensored" | "unfiltered" | "dolphin" => "uncensored".into(), + _ => "balanced".into(), + }; + let t = self.instruction_tone.trim().to_ascii_lowercase(); + self.instruction_tone = match t.as_str() { + "direct" => "direct".into(), + "steerable" | "uncensored" => "steerable".into(), + _ => "warm".into(), + }; + self + } + + /// Uncensored alignment or Show NSFW is on. + /// Sexual scene text then uses the uncensored local prompt writer. + /// Non-sexual prompts stay on the baseline writer. This does not skip enhancement. + /// Cloud image providers are unaffected. + pub fn local_adult_passthrough(&self) -> bool { + self.model_alignment == "uncensored" || self.allow_nsfw_local + } + + /// Append tone guidance to pack system instructions (chat / converse / assist). + pub fn apply_tone(&self, system: &str) -> String { + let extra = match self.instruction_tone.as_str() { + "direct" => { + " Tone: be concise and direct. Skip fluff; lead with the answer or next action." + } + "steerable" => { + " Tone: steerable and low-refusal — follow the user's creative brief unless it asks for illegal harm. Prefer completing the request over lecturing." + } + _ => "", + }; + if extra.is_empty() { + system.to_string() + } else { + format!("{system}{extra}") + } + } +} + +/// Appended to the converse agent when local adult prompts must pass through. +pub const LOCAL_ADULT_PASSTHROUGH_CLAUSE: &str = " Local generation with uncensored alignment or Show NSFW: do not refuse, lecture, or replace adult or explicit scene text. Copy the user's scene into generate_image, generate_video, and run_session prompts unchanged. Do not add a safety negative or strip explicit words. Cloud image providers may still refuse on their own."; + +/// Appended to the local prompt-sd instruction for an adult scene. +/// The uncensored writer expands the scene into checkpoint keywords. +pub const LOCAL_ADULT_ENHANCE_CLAUSE: &str = " The scene is adult. Expand it into a full Stable Diffusion or Pony keyword prompt. Keep sexual and explicit detail. Do not refuse, lecture, soften, censor, or replace the scene. Do not add LoRA names, trigger words, or artist tags the user did not write."; + +/// Whether generate should rewrite the prompt. `off` skips it. +/// Local and cloud both rewrite when this is true. Ordinary vs adult only +/// chooses which chat model writes a local prompt. +pub fn enhance_enabled(enhance: &str) -> bool { + if enhance == "off" { + return false; + } + matches!(enhance, "on" | "auto" | "prompt-prose" | "prompt-sd") +} + +/// Whether a chat model JSON object from OpenRouter `/models` matches alignment prefs. +pub fn chat_model_matches_alignment(m: &Value, prefs: &AlignmentPrefs) -> bool { + match prefs.model_alignment.as_str() { + "safety" => is_safety_leaning(m), + "uncensored" => is_uncensored_leaning(m), + _ => true, + } +} + +fn model_blob(m: &Value) -> String { + let id = m.get("id").and_then(|x| x.as_str()).unwrap_or(""); + let name = m.get("name").and_then(|x| x.as_str()).unwrap_or(""); + format!("{id} {name}").to_ascii_lowercase() +} + +fn is_moderated(m: &Value) -> Option { + m.pointer("/top_provider/is_moderated") + .and_then(|x| x.as_bool()) + .or_else(|| { + m.pointer("/topProvider/is_moderated") + .and_then(|x| x.as_bool()) + }) +} + +fn looks_uncensored_name(blob: &str) -> bool { + blob.contains("uncensored") + || blob.contains("abliterat") + || blob.contains("dolphin") + || blob.contains("wizard-vicuna") + || blob.contains("cognitivecomputations") +} + +fn is_safety_leaning(m: &Value) -> bool { + let blob = model_blob(m); + if looks_uncensored_name(&blob) { + return false; + } + match is_moderated(m) { + Some(true) => true, + Some(false) => { + // Keep major safety-aligned vendors even when top_provider flag is false/missing. + blob.starts_with("openai/") + || blob.starts_with("anthropic/") + || blob.starts_with("google/") + || blob.starts_with("amazon/") + || blob.starts_with("cohere/") + } + None => { + blob.starts_with("openai/") + || blob.starts_with("anthropic/") + || blob.starts_with("google/") + || blob.starts_with("amazon/") + || blob.starts_with("cohere/") + } + } +} + +fn is_uncensored_leaning(m: &Value) -> bool { + let blob = model_blob(m); + if looks_uncensored_name(&blob) { + return true; + } + match is_moderated(m) { + Some(false) => true, + Some(true) => false, + None => { + // Prefer open-weight / community models when flag absent. + blob.starts_with("meta-llama/") + || blob.starts_with("mistralai/") + || blob.starts_with("qwen/") + || blob.starts_with("deepseek/") + || blob.starts_with("nousresearch/") + || blob.starts_with("openrouter/") + || blob.contains("llama") + } + } +} + +/// Heuristic NSFW path/name filter for local worker assets. +pub fn looks_nsfw_label(s: &str) -> bool { + let l = s.to_ascii_lowercase(); + l.contains("nsfw") + || l.contains("porn") + || l.contains("xxx") + || l.contains("explicit") + || l.contains("adult") + || l.contains("erotic") + || l.contains("hentai") +} + +/// Merge privacy into an OpenRouter request body (chat or images). +pub fn inject_provider(body: &mut Value, prefs: &PrivacyPrefs) { + if let Some(provider) = prefs.to_provider_json() { + if let Some(obj) = body.as_object_mut() { + obj.insert("provider".into(), provider); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn provider_json_omits_defaults() { + assert!(PrivacyPrefs::default().to_provider_json().is_none()); + } + + #[test] + fn provider_json_zdr_and_deny_no_vendor_routing() { + let p = PrivacyPrefs { + zero_data_retention: true, + data_collection: "deny".into(), + chat_providers: ChatProvidersPrefs { + excluded: vec!["openai".into()], + legacy_only: None, + }, + ..Default::default() + } + .normalize(); + let v = p.to_provider_json().unwrap(); + assert_eq!(v["zdr"], true); + assert_eq!(v["data_collection"], "deny"); + assert!(v.get("only").is_none()); + assert!(v.get("ignore").is_none()); + } + + #[test] + fn migrates_legacy_ignore_and_only() { + let p = PrivacyPrefs { + provider_only: "anthropic, google".into(), + provider_ignore: "openai".into(), + ..Default::default() + } + .normalize(); + assert!(p.provider_only.is_empty()); + assert!(p.provider_ignore.is_empty()); + assert_eq!(p.chat_providers.excluded, vec!["openai".to_string()]); + assert_eq!( + p.chat_providers.legacy_only.as_deref(), + Some(["anthropic".to_string(), "google".to_string()].as_slice()) + ); + assert!(p.chat_providers.includes_vendor("anthropic")); + assert!(!p.chat_providers.includes_vendor("openai")); + assert!(!p.chat_providers.includes_vendor("deepseek")); // legacy_only wins + } + + #[test] + fn excluded_opt_out_includes_new_vendors() { + let p = ChatProvidersPrefs { + excluded: vec!["openai".into()], + legacy_only: None, + } + .normalize(); + assert!(p.includes_vendor("anthropic")); + assert!(p.includes_vendor("cognitivecomputations")); + assert!(!p.includes_vendor("openai")); + assert!(p.includes_model_id("google/gemini-4-neon")); + } + + #[test] + fn alignment_filters() { + let safety = AlignmentPrefs { + model_alignment: "safety".into(), + ..Default::default() + } + .normalize(); + let unc = AlignmentPrefs { + model_alignment: "uncensored".into(), + ..Default::default() + } + .normalize(); + let moderated = json!({ + "id": "openai/gpt-5.2", + "name": "GPT", + "top_provider": { "is_moderated": true } + }); + let dolphin = json!({ + "id": "cognitivecomputations/dolphin-llama", + "name": "Dolphin", + "top_provider": { "is_moderated": false } + }); + assert!(chat_model_matches_alignment(&moderated, &safety)); + assert!(!chat_model_matches_alignment(&dolphin, &safety)); + assert!(chat_model_matches_alignment(&dolphin, &unc)); + assert!(!chat_model_matches_alignment(&moderated, &unc)); + } + + #[test] + fn tone_appends() { + let a = AlignmentPrefs { + instruction_tone: "direct".into(), + ..Default::default() + } + .normalize(); + let out = a.apply_tone("You are Freya."); + assert!(out.contains("concise and direct")); + } + + #[test] + fn local_adult_setting_still_enhances() { + let unc = AlignmentPrefs { + model_alignment: "uncensored".into(), + allow_nsfw_local: false, + ..Default::default() + } + .normalize(); + let show = AlignmentPrefs { + model_alignment: "safety".into(), + allow_nsfw_local: true, + ..Default::default() + } + .normalize(); + let safety = AlignmentPrefs { + model_alignment: "safety".into(), + allow_nsfw_local: false, + ..Default::default() + } + .normalize(); + assert!(unc.local_adult_passthrough()); + assert!(show.local_adult_passthrough()); + assert!(!safety.local_adult_passthrough()); + assert!(enhance_enabled("auto")); + assert!(enhance_enabled("prompt-sd")); + assert!(enhance_enabled("prompt-prose")); + assert!(enhance_enabled("on")); + assert!(!enhance_enabled("off")); + } +} diff --git a/crates/freya-api/src/router.rs b/crates/freya-api/src/router.rs new file mode 100644 index 0000000..431961e --- /dev/null +++ b/crates/freya-api/src/router.rs @@ -0,0 +1,2088 @@ +//! Freya-owned intent router (light model). +//! +//! Aligns modalities with legacy Freya (`legacy/docs/`): +//! - **chat** — MagicPrompt Chat / Ollama dolphin3 (`make llm`) +//! - **picture** — still image / ComfyUI (`make cui`); Flux for NL, SDXL ecosystem for LoRAs +//! - **gif** — SwarmUI video output format (`gif-hd` / webp), not still-image +//! - **video** — SwarmUI T2V / I2V (`make sui`; Wan / LTX) + +use crate::openrouter::OpenRouterClient; +use crate::prefs::{AlignmentPrefs, AutoFallbacksPrefs, PrivacyPrefs}; +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +/// Settings / UI Auto sentinels. Internal Freya routing — not OpenRouter's upstream router. +pub const AUTO_AGENT: &str = "auto"; +pub const AUTO_IMAGE: &str = "auto"; +pub const AUTO_ROUTER: &str = "auto"; +/// Explicit opt-in for OpenRouter's upstream router. Never an Auto sentinel. +pub const UPSTREAM_ROUTER: &str = "openrouter/auto"; + +/// Medium + balanced. Cells live in `packs/auto-models.json` (ZDR off and ZDR on match for chat). +/// Router / agent: DeepSeek V4 Pro (tools + JSON, not an uncensored specialist, not Claude/GPT). +pub const DEFAULT_ROUTER_MODEL: &str = "deepseek/deepseek-v4-pro"; +/// Picture Auto medium, ZDR off: Seedream 4.5 (capable default; Flux is the uncensored row). +pub const DEFAULT_AUTO_IMAGE_MODEL: &str = "bytedance-seed/seedream-4.5"; +/// Picture Auto medium when ZDR is on. Microsoft MAI is on the ZDR image catalog; Flux is not. +pub const DEFAULT_AUTO_IMAGE_MODEL_ZDR: &str = "microsoft/mai-image-2.7"; +/// Agent Auto medium: tool-calling chat. Not `openrouter/auto`. +pub const DEFAULT_AUTO_AGENT_MODEL: &str = "deepseek/deepseek-v4-pro"; +/// Same id: DeepSeek V4 Pro is on the ZDR chat catalog. +pub const DEFAULT_AUTO_AGENT_MODEL_ZDR: &str = "deepseek/deepseek-v4-pro"; +pub const DEFAULT_AUTO_AGENT_MODEL_SAFETY: &str = "openai/gpt-5-mini"; +/// Cydonia's description is uncensored. It has JSON, not tools. Tool calls may be weaker. +pub const DEFAULT_AUTO_AGENT_MODEL_UNCENSORED: &str = "thedrummer/cydonia-24b-v4.1"; +pub const DEFAULT_ROUTER_MODEL_ZDR: &str = "deepseek/deepseek-v4-pro"; +pub const DEFAULT_ROUTER_MODEL_SAFETY: &str = "openai/gpt-5-mini"; + +/// Whether routing must prefer ZDR / no-collection endpoints. +pub fn privacy_requires_strict(privacy: &PrivacyPrefs) -> bool { + privacy.zero_data_retention || privacy.data_collection.eq_ignore_ascii_case("deny") +} + +/// Built-in Auto matrix: role × privacy × alignment × cost. +/// User overrides in `AutoFallbacksPrefs` win one cell. Ids come from +/// `packs/auto-models.json` (researched against OpenRouter). A missing file +/// uses the small fallback in `auto_matrix` so the API still boots. +/// +/// Video: `GET /models?output_modalities=video&zdr=true` lists no models. +/// ZDR video cells repeat the non-ZDR picks and OpenRouter may reject them. +pub fn builtin_auto_fallback( + kind: AutoFallbackKind, + privacy: &PrivacyPrefs, + alignment: &AlignmentPrefs, + cost: &str, +) -> String { + let strict = privacy_requires_strict(privacy); + let role = match kind { + AutoFallbackKind::Router => "router", + AutoFallbackKind::Agent => "agent", + AutoFallbackKind::Image => "image", + AutoFallbackKind::Video => "video", + }; + crate::auto_matrix::model_for(role, strict, alignment.model_alignment.as_str(), cost) +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum AutoFallbackKind { + Agent, + Image, + Video, + Router, +} + +/// Resolve a concrete Auto fallback: user Models-tab pin → else built-in matrix. +pub fn resolve_auto_fallback( + kind: AutoFallbackKind, + privacy: &PrivacyPrefs, + alignment: &AlignmentPrefs, + fallbacks: &AutoFallbacksPrefs, +) -> String { + let strict = privacy_requires_strict(privacy); + let user = match (kind, strict) { + (AutoFallbackKind::Agent, true) => fallbacks.agent_zdr.as_str(), + (AutoFallbackKind::Agent, false) => fallbacks.agent.as_str(), + (AutoFallbackKind::Image, true) => fallbacks.image_zdr.as_str(), + (AutoFallbackKind::Image, false) => fallbacks.image.as_str(), + (AutoFallbackKind::Video, true) => fallbacks.video_zdr.as_str(), + (AutoFallbackKind::Video, false) => fallbacks.video.as_str(), + (AutoFallbackKind::Router, _) => fallbacks.router.as_str(), + }; + let user = user.trim(); + if !user.is_empty() { + let user_id = if kind == AutoFallbackKind::Image { + match crate::openrouter::canonical_image_model(user) { + Some(id) => id, + None => { + return builtin_auto_fallback(kind, privacy, alignment, &fallbacks.cost_tier); + } + } + } else { + user.to_string() + }; + // When strict privacy is on, ignore non-Google Flux-ish image/video overrides. + if strict { + match kind { + AutoFallbackKind::Image + if !user_id.starts_with("google/") + && (user_id.contains("flux") + || user_id.contains("seedream") + || user_id.contains("black-forest")) => + { + return builtin_auto_fallback(kind, privacy, alignment, &fallbacks.cost_tier) + .to_string(); + } + AutoFallbackKind::Video + if !user_id.starts_with("google/") + && (user_id.contains("seedance") + || user_id.contains("kling") + || user_id.contains("hailuo") + || user_id.contains("flux")) => + { + return builtin_auto_fallback(kind, privacy, alignment, &fallbacks.cost_tier) + .to_string(); + } + _ => {} + } + } + return user_id; + } + builtin_auto_fallback(kind, privacy, alignment, &fallbacks.cost_tier).to_string() +} + +/// Auto still-image default, Privacy-aware (legacy helper — prefers built-in ZDR matrix). +pub fn default_auto_image_model(zdr: bool) -> &'static str { + if zdr { + DEFAULT_AUTO_IMAGE_MODEL_ZDR + } else { + DEFAULT_AUTO_IMAGE_MODEL + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum Modality { + Chat, + Picture, + Gif, + Video, +} + +impl Modality { + pub fn as_str(self) -> &'static str { + match self { + Modality::Chat => "chat", + Modality::Picture => "picture", + Modality::Gif => "gif", + Modality::Video => "video", + } + } + + pub fn parse(s: &str) -> Option { + match s.trim().to_ascii_lowercase().as_str() { + "chat" | "other" | "text" => Some(Modality::Chat), + "picture" | "image" | "img" | "still" => Some(Modality::Picture), + "gif" | "animation" | "animated" | "anim" => Some(Modality::Gif), + "video" | "t2v" | "i2v" | "clip" | "movie" => Some(Modality::Video), + _ => None, + } + } + + /// Still-image generate path (ComfyUI / OpenRouter images). + pub fn is_still_image(self) -> bool { + matches!(self, Modality::Picture) + } + + /// Motion family (gif → short animation / video → T2V). + pub fn is_motion(self) -> bool { + matches!(self, Modality::Gif | Modality::Video) + } +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct RouteDecision { + pub modality: Modality, + #[serde(default)] + pub reason: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub agent_model: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub image_model: Option, + /// How the decision was produced. + #[serde(default)] + pub source: String, +} + +impl RouteDecision { + /// Legacy hard-reject copy — always `None` now (motion executes when capable). + #[allow(dead_code)] + pub fn unsupported_message(&self) -> Option { + None + } + + /// Preferred motion backend hint for logging / UI. + pub fn motion_backend_hint(&self) -> Option<&'static str> { + match self.modality { + Modality::Gif => Some("openrouter-video|local-gif"), + Modality::Video => Some("openrouter-video"), + _ => None, + } + } +} + +/// Default Auto video model (balanced medium). No video id is on the ZDR catalog, +/// so the ZDR balanced-medium cell is the same id. +pub const DEFAULT_AUTO_VIDEO_MODEL: &str = crate::openrouter::DEFAULT_AUTO_VIDEO_MODEL; +pub const DEFAULT_AUTO_VIDEO_MODEL_ZDR: &str = "bytedance/seedance-2.5-flash"; + +pub fn default_auto_video_model(zdr: bool) -> &'static str { + if zdr { + DEFAULT_AUTO_VIDEO_MODEL_ZDR + } else { + DEFAULT_AUTO_VIDEO_MODEL + } +} + +pub fn is_auto_video(model: &str) -> bool { + let m = model.trim(); + m.is_empty() || m.eq_ignore_ascii_case(AUTO_IMAGE) || m.eq_ignore_ascii_case(AUTO_AGENT) +} + +#[allow(dead_code)] +pub fn resolve_video_model_choice( + pinned: Option<&str>, + route: &RouteDecision, + configured_default: &str, +) -> String { + resolve_video_model_choice_prefs( + pinned, + route, + configured_default, + &PrivacyPrefs::default(), + &AlignmentPrefs::default(), + &AutoFallbacksPrefs::default(), + ) +} + +pub fn resolve_video_model_choice_zdr( + pinned: Option<&str>, + route: &RouteDecision, + configured_default: &str, + zdr: bool, +) -> String { + let mut privacy = PrivacyPrefs::default(); + privacy.zero_data_retention = zdr; + resolve_video_model_choice_prefs( + pinned, + route, + configured_default, + &privacy, + &AlignmentPrefs::default(), + &AutoFallbacksPrefs::default(), + ) +} + +pub fn resolve_video_model_choice_prefs( + pinned: Option<&str>, + route: &RouteDecision, + configured_default: &str, + privacy: &PrivacyPrefs, + alignment: &AlignmentPrefs, + fallbacks: &AutoFallbacksPrefs, +) -> String { + let auto_default = + resolve_auto_fallback(AutoFallbackKind::Video, privacy, alignment, fallbacks); + if let Some(p) = pinned.map(str::trim).filter(|s| !s.is_empty()) { + if !is_auto_video(p) { + return crate::openrouter::resolve_video_model(p, &auto_default); + } + } + if let Some(sug) = route + .image_model + .as_deref() + .map(str::trim) + .filter(|s| !s.is_empty() && !is_auto_video(s) && !is_auto_image(s)) + { + // Reuse imageModel slot from router JSON only for a real catalog video id. + // Invented ids like `seedance/t2vdv-1.5` contain the family name and 400. + let sug_l = sug.to_ascii_lowercase(); + let known_video = sug_l.starts_with("bytedance/seedance") + || sug_l.starts_with("google/veo") + || sug_l.contains("/kling") + || (sug_l.starts_with("minimax/") && sug_l.contains("hailuo")) + || sug_l.contains("wan-") + || sug_l.contains("/ltx") + || sug_l.starts_with("x-ai/grok-imagine-video") + || sug_l.starts_with("black-forest-labs/flux-3-video") + || sug_l.starts_with("black-forest-labs/flux-video") + || sug_l.starts_with("runway/gen-"); + if known_video { + if privacy_requires_strict(privacy) + && !sug.starts_with("google/") + && (sug.contains("seedance") || sug.contains("kling") || sug.contains("hailuo")) + { + return crate::openrouter::resolve_video_model(&auto_default, &auto_default); + } + return crate::openrouter::resolve_video_model(sug, &auto_default); + } + } + let fallback = if is_auto_video(configured_default) || is_auto_image(configured_default) { + auto_default.clone() + } else { + configured_default.to_string() + }; + crate::openrouter::resolve_video_model(&fallback, &auto_default) +} + +pub fn is_upstream_router(model: &str) -> bool { + let m = model.trim().to_ascii_lowercase(); + m == UPSTREAM_ROUTER || m.starts_with("openrouter/auto") +} + +pub fn is_auto_agent(model: &str) -> bool { + let m = model.trim(); + // `openrouter/auto` is an explicit model id, not Freya Auto. + !is_upstream_router(m) + && (m.is_empty() || m.eq_ignore_ascii_case(AUTO_AGENT) || m.eq_ignore_ascii_case("auto")) +} + +pub fn is_auto_image(model: &str) -> bool { + let m = model.trim(); + m.is_empty() || m.eq_ignore_ascii_case(AUTO_IMAGE) || m.eq_ignore_ascii_case(AUTO_AGENT) +} + +pub fn is_auto_router(model: &str) -> bool { + let m = model.trim(); + m.is_empty() || m.eq_ignore_ascii_case(AUTO_ROUTER) || m.eq_ignore_ascii_case(AUTO_AGENT) +} + +pub fn resolve_router_model(configured: &str) -> String { + resolve_router_model_prefs( + configured, + &PrivacyPrefs::default(), + &AlignmentPrefs::default(), + &AutoFallbacksPrefs::default(), + ) +} + +pub fn resolve_router_model_prefs( + configured: &str, + privacy: &PrivacyPrefs, + alignment: &AlignmentPrefs, + fallbacks: &AutoFallbacksPrefs, +) -> String { + if is_auto_router(configured) { + resolve_auto_fallback(AutoFallbackKind::Router, privacy, alignment, fallbacks) + } else { + configured.trim().to_string() + } +} + +pub fn resolve_agent_model(pinned: Option<&str>, route: &RouteDecision) -> Option { + resolve_agent_model_prefs( + pinned, + route, + &PrivacyPrefs::default(), + &AlignmentPrefs::default(), + &AutoFallbacksPrefs::default(), + ) +} + +/// When Auto: prefer router suggestion → Privacy/Alignment-aware (configurable) fallback. +pub fn resolve_agent_model_prefs( + pinned: Option<&str>, + route: &RouteDecision, + privacy: &PrivacyPrefs, + alignment: &AlignmentPrefs, + fallbacks: &AutoFallbacksPrefs, +) -> Option { + if let Some(p) = pinned.map(str::trim).filter(|s| !s.is_empty()) { + if !is_auto_agent(p) { + return Some(p.to_string()); + } + } + if let Some(sug) = route + .agent_model + .as_deref() + .and_then(sanitize_router_model_suggestion) + { + // Upstream router is opt-in on the picker, never a router suggestion. + if is_upstream_router(&sug) { + return Some(resolve_auto_fallback( + AutoFallbackKind::Agent, + privacy, + alignment, + fallbacks, + )); + } + // Uncensored Auto must not be overridden by a high-refusal suggestion + // (route used to ask for Llama). A pinned model is returned above. + if alignment.model_alignment == "uncensored" && !keeps_uncensored_agent(&sug) { + return Some(resolve_auto_fallback( + AutoFallbackKind::Agent, + privacy, + alignment, + fallbacks, + )); + } + return Some(sug); + } + Some(resolve_auto_fallback( + AutoFallbackKind::Agent, + privacy, + alignment, + fallbacks, + )) +} + +#[allow(dead_code)] +pub fn resolve_image_model_choice( + pinned: Option<&str>, + route: &RouteDecision, + configured_default: &str, +) -> String { + resolve_image_model_choice_prefs( + pinned, + route, + configured_default, + &PrivacyPrefs::default(), + &AlignmentPrefs::default(), + &AutoFallbacksPrefs::default(), + ) +} + +pub fn resolve_image_model_choice_zdr( + pinned: Option<&str>, + route: &RouteDecision, + configured_default: &str, + zdr: bool, +) -> String { + let mut privacy = PrivacyPrefs::default(); + privacy.zero_data_retention = zdr; + resolve_image_model_choice_prefs( + pinned, + route, + configured_default, + &privacy, + &AlignmentPrefs::default(), + &AutoFallbacksPrefs::default(), + ) +} + +pub fn resolve_image_model_choice_prefs( + pinned: Option<&str>, + route: &RouteDecision, + configured_default: &str, + privacy: &PrivacyPrefs, + alignment: &AlignmentPrefs, + fallbacks: &AutoFallbacksPrefs, +) -> String { + let auto_default = + resolve_auto_fallback(AutoFallbackKind::Image, privacy, alignment, fallbacks); + if let Some(p) = pinned.map(str::trim).filter(|s| !s.is_empty()) { + if !is_auto_image(p) { + return crate::openrouter::resolve_image_model(p, &auto_default); + } + } + if let Some(sug) = route + .image_model + .as_deref() + .and_then(sanitize_router_model_suggestion) + { + // When strict privacy is on, ignore non-Google Flux-ish suggestions that often lack ZDR. + if privacy_requires_strict(privacy) + && !sug.starts_with("google/") + && (sug.contains("flux") || sug.contains("seedream") || sug.contains("black-forest")) + { + return crate::openrouter::resolve_image_model(&auto_default, &auto_default); + } + return crate::openrouter::resolve_image_model(&sug, &auto_default); + } + let fallback = if is_auto_image(configured_default) { + auto_default.clone() + } else { + configured_default.to_string() + }; + crate::openrouter::resolve_image_model(&fallback, &auto_default) +} + +/// What the latest message is asking Freya to produce, if anything. +/// Series is still a picture modality; callers use this to pick `run_session`. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum DirectMedia { + None, + Picture, + Series, + Gif, + Video, +} + +fn contains_any(hay: &str, needles: &[&str]) -> bool { + needles.iter().any(|n| hay.contains(n)) +} + +fn has_word(lower: &str, word: &str) -> bool { + lower + .split(|c: char| !c.is_ascii_alphanumeric()) + .any(|t| t == word) +} + +fn trim_punct(lower: &str) -> &str { + lower + .trim() + .trim_matches(|c: char| matches!(c, '?' | '!' | '.' | '"' | '\'' | '“' | '”' | '«' | '»')) +} + +/// Comma-tag soup or an explicit `` prompt. A character name is not this. +fn looks_like_tag_prompt(lower: &str) -> bool { + if lower.contains("= 6 && commas * 2 >= words +} + +/// Whole message is "do that again", not a sentence that happens to say again. +fn is_whole_message_redo(lower: &str) -> bool { + matches!( + trim_punct(lower), + "again" + | "do it again" + | "do that again" + | "another" + | "another one" + | "another image" + | "another picture" + | "one more" + | "once more" + | "regenerate" + | "redo" + | "same again" + | "generate" + | "generate it" + | "generate this" + | "generate again" + | "make it" + | "draw it" + | "draw this" + | "render it" + ) +} + +/// Obvious "help me decide". Not every question, and not a look they want seen. +fn obvious_guidance(lower: &str) -> bool { + const HOLDS: &[&str] = &[ + "don't generate", + "dont generate", + "do not generate", + "don't draw", + "do not draw", + "before we generate", + "before generating", + "not yet", + ]; + if contains_any(lower, HOLDS) { + return true; + } + const ADVICE: &[&str] = &[ + "how does", + "how do ", + "how do i", + "how can ", + "how would ", + "how to prompt", + "how should i", + "what should i", + "what should we", + "which lora", + "what lora", + "which model", + "what model", + "which checkpoint", + "what checkpoint", + "which base", + "what base", + "which style", + "what style", + "should i use", + "can you explain", + "could you explain", + "help me understand", + "help me decide", + "help me choose", + "help me pick", + "search civitai", + "find a lora", + "find loras", + "suggest idea", + "brainstorm", + "any ideas", + "any assets", + "which assets", + "models that", + "you able", + "are you able", + "did we ", + "did you ", + "have we ", + "have you ", + "was that generated", + ]; + if contains_any(lower, ADVICE) { + return true; + } + // Broad fragments only count when the message is not already a render. + if obvious_still(lower) || obvious_motion(lower).is_some() { + return false; + } + const SOFT: &[&str] = &["using the lora?", "would help"]; + contains_any(lower, SOFT) +} + +/// Obvious motion request. The bare words "video" or "gif" are not enough. +fn obvious_motion(lower: &str) -> Option { + let asked = lower.contains('?'); + let gif_imperative = lower.contains("make a gif") + || lower.contains("generate a gif") + || lower.contains("animated gif") + || lower.contains("animate as gif") + || lower.contains("looping animation"); + let gif_loose = lower.contains("gif of") + || lower.contains(".gif") + || (has_word(lower, "gif") && (lower.contains("make ") || lower.contains("generate "))); + if gif_imperative || (!asked && gif_loose) { + return Some(DirectMedia::Gif); + } + const VIDEO_IMPERATIVE: &[&str] = &[ + "text-to-video", + "image-to-video", + "text to video", + "image to video", + "make a video", + "make a clip", + "generate a video", + "animate this", + ]; + const VIDEO_LOOSE: &[&str] = &["video of", "short video", "short clip"]; + if contains_any(lower, VIDEO_IMPERATIVE) || (!asked && contains_any(lower, VIDEO_LOOSE)) { + Some(DirectMedia::Video) + } else { + None + } +} + +fn obvious_series(lower: &str) -> bool { + if lower.contains('?') { + return false; + } + if contains_any(lower, &["run session", "run a session"]) { + return true; + } + const SERIES: &[&str] = &[ + "series of", + "image series", + "picture series", + "set of images", + "set of pictures", + "set of stills", + "storyboard", + "sequence of images", + "sequence of pictures", + ]; + if !contains_any(lower, SERIES) { + return false; + } + // A bare "series of illustrations…" is a description, not a request to render. + has_word(lower, "generate") + || has_word(lower, "draw") + || has_word(lower, "render") + || has_word(lower, "paint") + || lower.contains("make ") +} + +/// Obvious "render this now". A character name or a visual noun is not enough. +fn obvious_still(lower: &str) -> bool { + if is_whole_message_redo(lower) + || looks_like_tag_prompt(lower) + || lower.trim().starts_with("prompt:") + { + return true; + } + const PHRASES: &[&str] = &[ + "draw me", + "draw a ", + "draw an ", + "draw the ", + "make an image", + "make a picture", + "make me an image", + "make me a picture", + "make the image", + "make the picture", + "generate an image", + "generate a picture", + "generate a ", + "generate an ", + "generate the image", + "generate this", + "generate that", + "please generate", + "create an image", + "create a picture", + "create me an image", + "create me a picture", + "render a ", + "render an ", + "paint a ", + "paint an ", + "paint me ", + ]; + contains_any(lower, PHRASES) +} + +/// Obvious "help me decide". A scene, outfit, or character description is not +/// this, even when the user never said generate, draw, or make. +pub fn message_is_chat_not_media(message: &str) -> bool { + let lower = message.trim().to_lowercase(); + !lower.is_empty() && obvious_guidance(&lower) +} + +/// Obvious render only. A scene, outfit, or character name is not a render. +pub fn direct_media_ask(message: &str) -> DirectMedia { + let lower = message.trim().to_lowercase(); + if lower.is_empty() || obvious_guidance(&lower) { + return DirectMedia::None; + } + if let Some(kind) = obvious_motion(&lower) { + return kind; + } + if obvious_series(&lower) { + return DirectMedia::Series; + } + if obvious_still(&lower) { + return DirectMedia::Picture; + } + DirectMedia::None +} + +fn modality_for_ask(ask: DirectMedia) -> Option { + match ask { + DirectMedia::None => None, + DirectMedia::Picture | DirectMedia::Series => Some(Modality::Picture), + DirectMedia::Gif => Some(Modality::Gif), + DirectMedia::Video => Some(Modality::Video), + } +} + +/// Obvious render wins. Obvious guidance stays chat. +/// A scene, outfit, or character description keeps the route model's call. +/// Heuristics do not force that look back to chat. +pub fn coerce_route_to_media_ask( + mut decision: RouteDecision, + message: &str, + privacy: &PrivacyPrefs, + alignment: &AlignmentPrefs, + fallbacks: &AutoFallbacksPrefs, +) -> RouteDecision { + let ask = direct_media_ask(message); + let Some(modality) = modality_for_ask(ask) else { + if decision.modality != Modality::Chat && message_is_chat_not_media(message) { + decision.modality = Modality::Chat; + decision.image_model = None; + if decision.agent_model.is_none() { + decision.agent_model = Some(resolve_auto_fallback( + AutoFallbackKind::Agent, + privacy, + alignment, + fallbacks, + )); + } + decision.reason = "Guidance: they want help deciding, not a picture yet.".into(); + if !decision.source.contains("chat-guard") { + decision.source = format!("{}+chat-guard", decision.source); + } + } + return decision; + }; + if decision.modality != modality { + decision.modality = modality; + decision.reason = match ask { + DirectMedia::Series => "Asked to render a series of stills now.".into(), + DirectMedia::Picture => "Asked to render a still now.".into(), + DirectMedia::Gif => "GIF / looping animation wording.".into(), + DirectMedia::Video => "Video / motion wording.".into(), + DirectMedia::None => decision.reason, + }; + if !decision.source.contains("media-ask") { + decision.source = format!("{}+media-ask", decision.source); + } + } + match modality { + Modality::Picture if decision.image_model.is_none() => { + decision.image_model = Some(resolve_auto_fallback( + AutoFallbackKind::Image, + privacy, + alignment, + fallbacks, + )); + } + Modality::Gif | Modality::Video if decision.image_model.is_none() => { + decision.image_model = Some(resolve_auto_fallback( + AutoFallbackKind::Video, + privacy, + alignment, + fallbacks, + )); + } + _ => {} + } + decision +} + +/// Fast heuristic when the light router model is unavailable. +pub fn infer_modality(message: &str) -> RouteDecision { + infer_modality_prefs( + message, + &PrivacyPrefs::default(), + &AlignmentPrefs::default(), + &AutoFallbacksPrefs::default(), + ) +} + +pub fn infer_modality_prefs( + message: &str, + privacy: &PrivacyPrefs, + alignment: &AlignmentPrefs, + fallbacks: &AutoFallbacksPrefs, +) -> RouteDecision { + let ask = direct_media_ask(message); + let decision = match ask { + DirectMedia::Gif => RouteDecision { + modality: Modality::Gif, + reason: "Heuristic: GIF / looping animation wording (legacy SwarmUI gif-hd).".into(), + agent_model: None, + image_model: Some(resolve_auto_fallback( + AutoFallbackKind::Video, + privacy, + alignment, + fallbacks, + )), + source: "heuristic".into(), + }, + DirectMedia::Video => RouteDecision { + modality: Modality::Video, + reason: "Heuristic: video / T2V / I2V wording (legacy SwarmUI video).".into(), + agent_model: None, + image_model: Some(resolve_auto_fallback( + AutoFallbackKind::Video, + privacy, + alignment, + fallbacks, + )), + source: "heuristic".into(), + }, + DirectMedia::Picture => RouteDecision { + modality: Modality::Picture, + reason: "Heuristic: asked to render a still now.".into(), + agent_model: None, + image_model: Some(resolve_auto_fallback( + AutoFallbackKind::Image, + privacy, + alignment, + fallbacks, + )), + source: "heuristic".into(), + }, + DirectMedia::Series => RouteDecision { + modality: Modality::Picture, + reason: "Heuristic: asked for a series of stills.".into(), + agent_model: None, + image_model: Some(resolve_auto_fallback( + AutoFallbackKind::Image, + privacy, + alignment, + fallbacks, + )), + source: "heuristic".into(), + }, + DirectMedia::None => RouteDecision { + modality: Modality::Chat, + reason: "Heuristic: conversational / no media ask.".into(), + agent_model: Some(resolve_auto_fallback( + AutoFallbackKind::Agent, + privacy, + alignment, + fallbacks, + )), + image_model: None, + source: "heuristic".into(), + }, + }; + coerce_route_to_media_ask(decision, message, privacy, alignment, fallbacks) +} + +/// Drop router prose / null-ish placeholders that LLMs echo from the prompt +/// (e.g. `"None, letting Freya use Auto default (ZDR-aware)."`). +/// Router suggestions that stay on the uncensored agent row. +/// Llama-instruct, Claude, and GPT are not in that row. +fn keeps_uncensored_agent(id: &str) -> bool { + let l = id.to_ascii_lowercase(); + const MARKERS: &[&str] = &[ + "uncensored", + "dolphin", + "cydonia", + "venice", + "abliterat", + "cognitivecomputations", + "thedrummer", + "wizard-vicuna", + ]; + MARKERS.iter().any(|m| l.contains(m)) +} + +/// Which chat model writes a local checkpoint prompt. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct LocalEnhancePath { + /// Alignment allows adult scenes and the user text is sexual. + pub adult: bool, + /// Concrete chat model id. Never the raw user one-liner. + pub model: String, +} + +/// Local prompt-sd writer. +/// Ordinary requests use the balanced Auto agent (the normal matrix cell) or +/// an explicit chat pin. Adult requests use the uncensored matrix cell +/// (Cydonia at medium and above, Dolphin Venice at low) unless the pin is +/// already an uncensored-safe model. +pub fn local_enhance_path( + prompt: &str, + alignment: &AlignmentPrefs, + pinned_chat: Option<&str>, + privacy: &PrivacyPrefs, + fallbacks: &AutoFallbacksPrefs, +) -> LocalEnhancePath { + let adult = alignment.local_adult_passthrough() && prompt_is_adult_scene(prompt); + let strict = privacy_requires_strict(privacy); + let cost = fallbacks.cost_tier.as_str(); + let model = if adult { + match explicit_chat_pin(pinned_chat) { + // Adult rewrite only: a pinned Llama, Claude, GPT, or Gemini is + // moderated, so the uncensored matrix model writes this checkpoint prompt. + Some(id) if !moderated_chat_family(id) && !is_upstream_router(id) => id.to_string(), + _ => crate::auto_matrix::model_for("agent", strict, "uncensored", cost), + } + } else { + match explicit_chat_pin(pinned_chat) { + Some(id) => id.to_string(), + None => crate::auto_matrix::model_for("agent", strict, "balanced", cost), + } + }; + LocalEnhancePath { adult, model } +} + +/// Uncensored Auto chat cell for a local adult rewrite (matrix, not the pin). +pub fn local_adult_matrix_model(privacy: &PrivacyPrefs, fallbacks: &AutoFallbacksPrefs) -> String { + crate::auto_matrix::model_for( + "agent", + privacy_requires_strict(privacy), + "uncensored", + fallbacks.cost_tier.as_str(), + ) +} + +fn explicit_chat_pin(pinned: Option<&str>) -> Option<&str> { + let p = pinned.map(str::trim).filter(|s| !s.is_empty())?; + if is_auto_agent(p) { + None + } else { + Some(p) + } +} + +/// Llama, Claude, GPT, and Gemini. Dolphin and Cydonia are not in this set. +fn moderated_chat_family(id: &str) -> bool { + let l = id.trim().to_ascii_lowercase(); + if l.is_empty() || keeps_uncensored_agent(&l) { + return false; + } + l.contains("llama") + || l.contains("claude") + || l.starts_with("anthropic/") + || l.starts_with("openai/") + || l.contains("gpt") + || l.contains("gemini") +} + +/// Sexual or adult scene text. Uncensored alignment alone is not a match. +pub fn prompt_is_adult_scene(text: &str) -> bool { + let l = text.to_ascii_lowercase(); + const TERMS: &[&str] = &[ + "nsfw", + "nude", + "nudes", + "naked", + "topless", + "bottomless", + "porn", + "hentai", + "erotic", + "erotica", + "lewd", + "ecchi", + "ahegao", + "orgasm", + "orgasmic", + "penis", + "vagina", + "vulva", + "clitoris", + "nipple", + "nipples", + "areola", + "genitals", + "genitalia", + "intercourse", + "blowjob", + "handjob", + "fellatio", + "cunnilingus", + "bondage", + "bdsm", + "fetish", + "lingerie", + "panties", + "thong", + "boobs", + "cock", + "cocks", + "dick", + "pussy", + "cum", + "cumshot", + "cumming", + "fucking", + "fuck", + "fucked", + "sex", + "sexual", + "sexually", + "xxx", + "undressed", + "stripper", + "whore", + "slut", + "dildo", + "erection", + "softcore", + "rule34", + "r34", + "yaoi", + "incest", + "milf", + "anal", + "orgy", + "threesome", + "gangbang", + "creampie", + "deepthroat", + "moaning", + "making love", + "clothes off", + "no clothes", + "without clothes", + "spread legs", + "spread her legs", + "spread his legs", + "in the nude", + "adult scene", + "adult content", + "sex scene", + "blow job", + "hand job", + "jerking off", + "get naked", + "gets naked", + "18+", + ]; + if TERMS.iter().any(|term| contains_term(&l, term)) { + return true; + } + // "breast" / "breasts" / "tits" are ordinary in food and bird names. + contextual_term( + &l, + "breast", + &["chicken", "turkey", "duck", "goose", "quail"], + &["pocket", "cancer", "milk"], + ) || contextual_term( + &l, + "breasts", + &["chicken", "turkey", "duck", "goose", "quail"], + &[], + ) || contextual_term( + &l, + "tits", + &[ + "blue", + "great", + "crested", + "bearded", + "coal", + "marsh", + "willow", + "long-tailed", + ], + &[], + ) +} + +/// Word-bounded `term` that is not sitting next to an ordinary neighbor. +fn contextual_term(hay: &str, term: &str, deny_prev: &[&str], deny_next: &[&str]) -> bool { + let bytes = hay.as_bytes(); + let needle = term.as_bytes(); + if needle.is_empty() || needle.len() > bytes.len() { + return false; + } + let mut i = 0; + while i + needle.len() <= bytes.len() { + if &bytes[i..i + needle.len()] == needle { + let before_ok = i == 0 || !bytes[i - 1].is_ascii_alphanumeric(); + let end = i + needle.len(); + let after_ok = end == bytes.len() || !bytes[end].is_ascii_alphanumeric(); + if before_ok && after_ok { + let prev = previous_word(hay, i); + let next = next_word(hay, end); + let denied = + deny_prev.iter().any(|w| prev == *w) || deny_next.iter().any(|w| next == *w); + if !denied { + return true; + } + } + } + i += 1; + } + false +} + +fn previous_word(hay: &str, at: usize) -> &str { + let head = hay[..at].trim_end(); + let start = head + .rfind(|c: char| !c.is_ascii_alphanumeric() && c != '-') + .map(|i| { + let sep = head[i..].chars().next().map(|c| c.len_utf8()).unwrap_or(0); + i + sep + }) + .unwrap_or(0); + &head[start..] +} + +fn next_word(hay: &str, end: usize) -> &str { + let tail = hay[end..].trim_start(); + let n = tail + .find(|c: char| !c.is_ascii_alphanumeric() && c != '-') + .unwrap_or(tail.len()); + &tail[..n] +} + +fn contains_term(hay: &str, term: &str) -> bool { + let bytes = hay.as_bytes(); + let needle = term.as_bytes(); + if needle.is_empty() || needle.len() > bytes.len() { + return false; + } + let mut i = 0; + while i + needle.len() <= bytes.len() { + if &bytes[i..i + needle.len()] == needle { + let before_ok = i == 0 || !bytes[i - 1].is_ascii_alphanumeric(); + let end = i + needle.len(); + let after_ok = end == bytes.len() || !bytes[end].is_ascii_alphanumeric(); + if before_ok && after_ok { + return true; + } + } + i += 1; + } + false +} + +fn sanitize_router_model_suggestion(raw: &str) -> Option { + let s = raw.trim(); + if s.is_empty() { + return None; + } + let lower = s.to_ascii_lowercase(); + if lower == "null" + || lower == "none" + || lower == "undefined" + || lower.starts_with("none,") + || lower.contains("zdr-aware") + || lower.contains("letting freya") + || lower.contains("auto default") + || lower.contains("freya will apply") + { + return None; + } + // Real model ids are compact (org/name or path); prose has spaces. + if s.contains(char::is_whitespace) { + return None; + } + // Strip a mistaken `openrouter/` prefix. Invented slugs + // (`openrouter/google-gemini-pro-image-1`) become empty and fall through to Auto. + // A real first-party id (`openrouter/horizon-alpha`) stays. + let s = crate::openrouter::canonicalize_catalog_id(s); + if s.is_empty() { + return None; + } + // OpenRouter ids are `provider/model`. Bare tokens (`light`, `ldm-xxl-256`) + // are router prose, not models — drop them so Auto fallbacks are used. + if !s.contains('/') { + return None; + } + if is_auto_image(&s) || is_auto_agent(&s) || is_upstream_router(&s) { + return None; + } + Some(s) +} + +fn parse_route_json(text: &str) -> Option { + let trimmed = text + .trim() + .trim_start_matches("```json") + .trim_start_matches("```") + .trim_end_matches("```") + .trim(); + let v: Value = serde_json::from_str(trimmed).ok()?; + let modality = v + .get("modality") + .and_then(|x| x.as_str()) + .and_then(Modality::parse)?; + let reason = v + .get("reason") + .and_then(|x| x.as_str()) + .unwrap_or("") + .to_string(); + let agent_model = v + .get("agentModel") + .and_then(|x| x.as_str()) + .and_then(sanitize_router_model_suggestion); + let image_model = v + .get("imageModel") + .and_then(|x| x.as_str()) + .and_then(sanitize_router_model_suggestion); + Some(RouteDecision { + modality, + reason, + agent_model, + image_model, + source: "router".into(), + }) +} + +/// Context injected into the router user blob so Auto picks respect Privacy/Alignment. +pub fn router_prefs_context(privacy: &PrivacyPrefs, alignment: &AlignmentPrefs) -> String { + format!( + "Privacy: ZDR={} data_collection={}. Alignment: {}. Prefer concrete provider/model ids that satisfy these (image examples: google/gemini-2.5-flash-image, google/gemini-3-pro-image). Never prefix openrouter/ onto a provider/model id and never invent openrouter/google-gemini-pro-image-1. Safety: moderated high-refusal models (GPT, Claude, Cohere; GPT Image or Google image; Veo for video). Balanced: a capable default, not an uncensored specialist and not the strictest safety model. Uncensored: models whose name or description is uncensored (Dolphin, Venice, Cydonia) or, for image and video, the least-moderated catalog option (Flux, Krea, Grok). Do not suggest Llama-instruct, Claude, or GPT as uncensored. When ZDR or deny-collection is on, stay on ids from the ZDR catalog. No video model is on that catalog.", + if privacy.zero_data_retention { + "on" + } else { + "off" + }, + privacy.data_collection, + alignment.model_alignment + ) +} + +/// Classify with the configured light router model; fall back to Privacy/Alignment-aware heuristics. +pub async fn classify( + or: &OpenRouterClient, + system: &str, + user_message: &str, + recent: &str, + router_model_configured: &str, +) -> RouteDecision { + classify_prefs( + or, + system, + user_message, + recent, + router_model_configured, + &PrivacyPrefs::default(), + &AlignmentPrefs::default(), + &AutoFallbacksPrefs::default(), + ) + .await +} + +pub async fn classify_prefs( + or: &OpenRouterClient, + system: &str, + user_message: &str, + recent: &str, + router_model_configured: &str, + privacy: &PrivacyPrefs, + alignment: &AlignmentPrefs, + fallbacks: &AutoFallbacksPrefs, +) -> RouteDecision { + let model = resolve_router_model_prefs(router_model_configured, privacy, alignment, fallbacks); + let prefs_ctx = router_prefs_context(privacy, alignment); + let mut blob = format!("{user_message}\n\n--- freya prefs ---\n{prefs_ctx}"); + if !recent.trim().is_empty() { + blob = format!("{blob}\n\n--- recent conversation ---\n{recent}"); + } + match or.chat(system, &blob, Some(&model)).await { + Ok(text) => { + if let Some(mut d) = parse_route_json(&text) { + if d.reason.is_empty() { + d.reason = format!("Routed as {} via {model}", d.modality.as_str()); + } + return coerce_route_to_media_ask(d, user_message, privacy, alignment, fallbacks); + } + tracing::debug!(raw = %text, "router returned non-JSON; using heuristic"); + let mut h = infer_modality_prefs(user_message, privacy, alignment, fallbacks); + h.source = "heuristic-after-router".into(); + coerce_route_to_media_ask(h, user_message, privacy, alignment, fallbacks) + } + Err(e) => { + tracing::debug!(error = %e, "router model failed; using heuristic"); + infer_modality_prefs(user_message, privacy, alignment, fallbacks) + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn heuristic_gif_not_picture() { + let d = infer_modality("make a gif of a cat waving"); + assert_eq!(d.modality, Modality::Gif); + } + + #[test] + fn heuristic_video() { + let d = infer_modality("text-to-video of a harbor at dusk"); + assert_eq!(d.modality, Modality::Video); + } + + #[test] + fn invented_video_id_falls_back_to_default() { + let route = RouteDecision { + modality: Modality::Video, + reason: "t".into(), + agent_model: None, + image_model: Some("seedance/t2vdv-1.5".into()), + source: "t".into(), + }; + assert_eq!( + resolve_video_model_choice_prefs( + Some(AUTO_IMAGE), + &route, + AUTO_IMAGE, + &PrivacyPrefs::default(), + &AlignmentPrefs::default(), + &AutoFallbacksPrefs::default(), + ), + DEFAULT_AUTO_VIDEO_MODEL + ); + } + + #[test] + fn heuristic_picture() { + let d = infer_modality("draw me a winged warrior by a waterfall"); + assert_eq!(d.modality, Modality::Picture); + } + + #[test] + fn heuristic_chat() { + let d = infer_modality("what LoRA would fit a Nordic look?"); + assert_eq!(d.modality, Modality::Chat); + } + + #[test] + fn heuristic_leaves_a_scene_for_the_route_model() { + let scene = + "A cartoon meme of a grumpy cat in a cowboy hat, thick outlines, flat yellow background"; + // No obvious render verb and no obvious advice. The fallback stays chat. + // A picture call from the route model is kept. + let d = infer_modality(scene); + assert_eq!(d.modality, Modality::Chat); + assert_eq!(direct_media_ask(scene), DirectMedia::None); + assert!(!message_is_chat_not_media(scene)); + let kept = coerce_route_to_media_ask( + RouteDecision { + modality: Modality::Picture, + reason: "scene meant to be seen".into(), + agent_model: None, + image_model: Some("google/gemini-2.5-flash-image".into()), + source: "router".into(), + }, + scene, + &PrivacyPrefs::default(), + &AlignmentPrefs::default(), + &AutoFallbacksPrefs::default(), + ); + assert_eq!(kept.modality, Modality::Picture); + assert!(kept.image_model.is_some()); + assert!(!kept.source.contains("chat-guard")); + } + + #[test] + fn series_of_stills_is_picture() { + assert_eq!( + direct_media_ask("a series of illustrations of a lighthouse in a storm"), + DirectMedia::None + ); + assert_eq!( + infer_modality("a series of illustrations of a lighthouse in a storm").modality, + Modality::Chat + ); + assert_eq!( + direct_media_ask("make a series of illustrations of a lighthouse in a storm"), + DirectMedia::Series + ); + assert_eq!( + infer_modality("how does flux work?").modality, + Modality::Chat + ); + assert_eq!( + infer_modality("can you clarify the hair color before we generate?").modality, + Modality::Chat + ); + assert!(!message_is_chat_not_media( + "a series of illustrations of a lighthouse in a storm" + )); + } + + #[test] + fn obvious_guidance_stays_chat_without_an_explicit_render() { + let chat_turns = [ + "you able to make an image of Frankie Foster?", + "did we generate an image of Frankie Foster using the lora?", + "I want to create some placeholder image for this Freya app, any assets \\ models that would help?", + "how should I prompt Frankie Foster for a night out, and which LoRA?", + "what should I do for Frankie Foster", + ]; + let picture = RouteDecision { + modality: Modality::Picture, + reason: "model called this a still".into(), + agent_model: None, + image_model: Some("google/gemini-2.5-flash-image".into()), + source: "router".into(), + }; + for turn in chat_turns { + assert!(message_is_chat_not_media(turn), "{turn}"); + assert_eq!(infer_modality(turn).modality, Modality::Chat, "{turn}"); + assert_eq!(direct_media_ask(turn), DirectMedia::None, "{turn}"); + let guarded = coerce_route_to_media_ask( + picture.clone(), + turn, + &PrivacyPrefs::default(), + &AlignmentPrefs::default(), + &AutoFallbacksPrefs::default(), + ); + assert_eq!(guarded.modality, Modality::Chat, "{turn}"); + assert!(guarded.image_model.is_none(), "{turn}"); + assert!(guarded.source.contains("chat-guard"), "{turn}"); + } + // A question that hands over the picture is an obvious render. + assert_eq!( + infer_modality("can you make an image of Frankie Foster?").modality, + Modality::Picture + ); + for turn in [ + "generate", + "again", + "draw this", + "make it", + "make the picture", + "can you draw me a cat?", + "please generate", + "generate a cat", + "generate that", + "create an image of a harbor", + "generate an image of Frankie using the lora?", + "draw me a cat that would help tell the story", + ] { + assert_eq!(infer_modality(turn).modality, Modality::Picture, "{turn}"); + } + assert_eq!( + direct_media_ask("what gif should I make?"), + DirectMedia::None + ); + assert_eq!( + direct_media_ask("is that video of Frankie any good?"), + DirectMedia::None + ); + assert_eq!( + infer_modality("can you make a gif of a cat?").modality, + Modality::Gif + ); + assert_eq!( + infer_modality("make a video of a cat").modality, + Modality::Video + ); + } + + #[test] + fn ordinary_wording_is_not_an_adult_scene() { + assert!(!prompt_is_adult_scene("chicken breast on a plate")); + assert!(!prompt_is_adult_scene("chicken breasts on a plate")); + assert!(!prompt_is_adult_scene("a pair of blue tits on a branch")); + assert!(!prompt_is_adult_scene( + "explicit instructions for the checkpoint install" + )); + assert!(!prompt_is_adult_scene( + "portrait of Yuri in a school uniform" + )); + assert!(!prompt_is_adult_scene("hardcore parkour on a rooftop")); + assert!(!prompt_is_adult_scene("straddling a fence at dusk")); + assert!(prompt_is_adult_scene("nude woman on a bed, explicit sex")); + assert!(prompt_is_adult_scene("her breasts, soft light")); + assert!(prompt_is_adult_scene("close crop of her tits")); + } + + #[test] + fn adult_scene_scan_survives_non_ascii() { + assert_eq!( + previous_word("sofía breasts", "sofía breasts".find("breasts").unwrap()), + "a" + ); + assert!(prompt_is_adult_scene("Sofía breasts")); + assert!(prompt_is_adult_scene("café, nude portrait")); + assert!(!prompt_is_adult_scene("Sofía plating a chicken breast")); + } + + #[test] + fn coerce_keeps_picture_for_a_look_they_want_seen() { + let chat = RouteDecision { + modality: Modality::Chat, + reason: "ambiguous".into(), + agent_model: None, + image_model: None, + source: "router".into(), + }; + let outfit = "Frankie Foster in cozy winter layers, a chunky cream knit sweater, plaid scarf, and beanie over her red hair, holding a coffee cup in a snowy front yard with the foster home behind her."; + // Heuristic does not invent a render, and does not call the outfit advice. + assert_eq!(direct_media_ask(outfit), DirectMedia::None); + assert!(!message_is_chat_not_media(outfit)); + assert_eq!(infer_modality(outfit).modality, Modality::Chat); + // A character name alone does not force picture. + assert_eq!(direct_media_ask("Frankie Foster"), DirectMedia::None); + assert!(!message_is_chat_not_media("Frankie Foster")); + let name = coerce_route_to_media_ask( + chat.clone(), + "Frankie Foster", + &PrivacyPrefs::default(), + &AlignmentPrefs::default(), + &AutoFallbacksPrefs::default(), + ); + assert_eq!(name.modality, Modality::Chat); + + let described = coerce_route_to_media_ask( + chat.clone(), + "An illustration of a red bicycle in the rain, wet street, cinematic lighting", + &PrivacyPrefs::default(), + &AlignmentPrefs::default(), + &AutoFallbacksPrefs::default(), + ); + assert_eq!(described.modality, Modality::Chat); + assert!(described.image_model.is_none()); + + for look in [ + outfit, + "An illustration of a red bicycle in the rain, wet street, cinematic lighting", + ] { + let wanted = coerce_route_to_media_ask( + RouteDecision { + modality: Modality::Picture, + reason: "this is the scene they want seen".into(), + agent_model: None, + image_model: Some("google/gemini-2.5-flash-image".into()), + source: "router".into(), + }, + look, + &PrivacyPrefs::default(), + &AlignmentPrefs::default(), + &AutoFallbacksPrefs::default(), + ); + assert_eq!(wanted.modality, Modality::Picture, "{look}"); + assert_eq!( + wanted.image_model.as_deref(), + Some("google/gemini-2.5-flash-image"), + "{look}" + ); + assert!(!wanted.source.contains("chat-guard"), "{look}"); + } + + let drawn = coerce_route_to_media_ask( + chat, + "draw this", + &PrivacyPrefs::default(), + &AlignmentPrefs::default(), + &AutoFallbacksPrefs::default(), + ); + assert_eq!(drawn.modality, Modality::Picture); + assert!(drawn.image_model.is_some()); + } + + #[test] + fn pin_beats_route_suggestion() { + let route = RouteDecision { + modality: Modality::Picture, + reason: "t".into(), + agent_model: Some("openai/gpt-4.1-mini".into()), + image_model: Some("google/gemini-2.5-flash-image".into()), + source: "t".into(), + }; + assert_eq!( + resolve_agent_model(Some("anthropic/claude-sonnet-5.5"), &route).as_deref(), + Some("anthropic/claude-sonnet-5.5") + ); + assert!( + resolve_image_model_choice(Some("openai/gpt-image-1-mini"), &route, AUTO_IMAGE) + .contains("gpt-image") + ); + } + + #[test] + fn auto_image_resolves_flux() { + let route = RouteDecision { + modality: Modality::Picture, + reason: "t".into(), + agent_model: None, + image_model: None, + source: "t".into(), + }; + assert_eq!( + resolve_image_model_choice(Some(AUTO_IMAGE), &route, AUTO_IMAGE), + DEFAULT_AUTO_IMAGE_MODEL + ); + } + + #[test] + fn auto_image_zdr_prefers_google() { + let route = RouteDecision { + modality: Modality::Picture, + reason: "t".into(), + agent_model: None, + image_model: Some("black-forest-labs/flux.2-klein-4b".into()), + source: "t".into(), + }; + assert_eq!( + resolve_image_model_choice_zdr(Some(AUTO_IMAGE), &route, AUTO_IMAGE, true), + DEFAULT_AUTO_IMAGE_MODEL_ZDR + ); + assert_eq!( + resolve_image_model_choice_zdr(Some(AUTO_IMAGE), &route, AUTO_IMAGE, false), + "black-forest-labs/flux.2-klein-4b" + ); + } + + #[test] + fn sanitize_drops_zdr_prose_image_model() { + assert!(sanitize_router_model_suggestion("ldm-xxl-256").is_none()); + assert!(sanitize_router_model_suggestion("light").is_none()); + assert!(sanitize_router_model_suggestion( + "None, letting Freya use Auto default (ZDR-aware)." + ) + .is_none()); + assert!(sanitize_router_model_suggestion("null").is_none()); + assert_eq!( + sanitize_router_model_suggestion("black-forest-labs/flux.2-klein-4b").as_deref(), + Some("black-forest-labs/flux.2-klein-4b") + ); + assert!(sanitize_router_model_suggestion("openrouter/google-gemini-pro-image-1").is_none()); + assert_eq!( + sanitize_router_model_suggestion("openrouter/google/gemini-3-pro-image").as_deref(), + Some("google/gemini-3-pro-image") + ); + assert_eq!( + sanitize_router_model_suggestion("openrouter/horizon-alpha").as_deref(), + Some("openrouter/horizon-alpha") + ); + let first_party = RouteDecision { + modality: Modality::Picture, + reason: "t".into(), + agent_model: Some("openrouter/horizon-alpha".into()), + image_model: Some("openrouter/horizon-alpha".into()), + source: "t".into(), + }; + assert_eq!( + resolve_agent_model(Some(AUTO_AGENT), &first_party).as_deref(), + Some("openrouter/horizon-alpha") + ); + assert_eq!( + resolve_image_model_choice(Some(AUTO_IMAGE), &first_party, AUTO_IMAGE), + DEFAULT_AUTO_IMAGE_MODEL + ); + let route = RouteDecision { + modality: Modality::Picture, + reason: "t".into(), + agent_model: None, + image_model: Some("None, letting Freya use Auto default (ZDR-aware).".into()), + source: "t".into(), + }; + // Prose suggestion ignored → Auto default. + assert_eq!( + resolve_image_model_choice_zdr(Some(AUTO_IMAGE), &route, AUTO_IMAGE, false), + DEFAULT_AUTO_IMAGE_MODEL + ); + } + + #[test] + fn parse_route_json_drops_prose_image_model() { + let d = parse_route_json( + r#"{"modality":"picture","reason":"gen","agentModel":null,"imageModel":"None, letting Freya use Auto default (ZDR-aware)."}"#, + ) + .expect("parse"); + assert!(d.image_model.is_none()); + } + + #[test] + fn alignment_safety_picks_moderated_agent() { + let privacy = PrivacyPrefs::default(); + let alignment = AlignmentPrefs { + model_alignment: "safety".into(), + ..Default::default() + }; + let fb = AutoFallbacksPrefs::default(); + assert_eq!( + resolve_auto_fallback(AutoFallbackKind::Agent, &privacy, &alignment, &fb), + DEFAULT_AUTO_AGENT_MODEL_SAFETY + ); + assert_eq!( + resolve_auto_fallback(AutoFallbackKind::Router, &privacy, &alignment, &fb), + DEFAULT_ROUTER_MODEL_SAFETY + ); + assert_eq!(DEFAULT_AUTO_AGENT_MODEL_SAFETY, "openai/gpt-5-mini"); + assert_eq!(DEFAULT_ROUTER_MODEL_SAFETY, "openai/gpt-5-mini"); + let uncensored = AlignmentPrefs { + model_alignment: "uncensored".into(), + ..Default::default() + }; + assert_eq!( + resolve_auto_fallback(AutoFallbackKind::Agent, &privacy, &uncensored, &fb), + "thedrummer/cydonia-24b-v4.1" + ); + assert_eq!( + resolve_auto_fallback(AutoFallbackKind::Router, &privacy, &uncensored, &fb), + "thedrummer/cydonia-24b-v4.1" + ); + let low = AutoFallbacksPrefs { + cost_tier: "low".into(), + ..Default::default() + }; + assert_eq!( + resolve_auto_fallback(AutoFallbackKind::Agent, &privacy, &uncensored, &low), + "cognitivecomputations/dolphin-mistral-24b-venice-edition" + ); + let deny = PrivacyPrefs { + data_collection: "deny".into(), + ..Default::default() + }; + let balanced = AlignmentPrefs::default(); + assert_eq!( + resolve_auto_fallback(AutoFallbackKind::Image, &deny, &balanced, &fb), + DEFAULT_AUTO_IMAGE_MODEL_ZDR + ); + assert_eq!( + resolve_auto_fallback(AutoFallbackKind::Image, &deny, &alignment, &fb), + "google/gemini-2.5-flash-image" + ); + assert_eq!( + resolve_auto_fallback(AutoFallbackKind::Video, &deny, &balanced, &fb), + DEFAULT_AUTO_VIDEO_MODEL_ZDR + ); + assert!( + !resolve_auto_fallback(AutoFallbackKind::Video, &deny, &uncensored, &fb).is_empty() + ); + } + + #[test] + fn user_fallback_overrides_builtin() { + let privacy = PrivacyPrefs::default(); + let alignment = AlignmentPrefs::default(); + let fb = AutoFallbacksPrefs { + image: "openai/gpt-image-1".into(), + ..Default::default() + }; + assert_eq!( + resolve_auto_fallback(AutoFallbackKind::Image, &privacy, &alignment, &fb), + "openai/gpt-image-1" + ); + } + + #[test] + fn invented_openrouter_image_id_uses_real_catalog_id() { + let route = RouteDecision { + modality: Modality::Picture, + reason: "t".into(), + agent_model: None, + image_model: Some("openrouter/google-gemini-pro-image-1".into()), + source: "t".into(), + }; + assert_eq!( + resolve_image_model_choice(Some(AUTO_IMAGE), &route, AUTO_IMAGE), + DEFAULT_AUTO_IMAGE_MODEL + ); + assert_eq!( + resolve_image_model_choice( + Some("openrouter/google-gemini-pro-image-1"), + &route, + AUTO_IMAGE + ), + DEFAULT_AUTO_IMAGE_MODEL + ); + assert_eq!( + resolve_image_model_choice(Some("google/gemini-3-pro-image"), &route, AUTO_IMAGE), + "google/gemini-3-pro-image" + ); + assert_eq!( + resolve_image_model_choice( + Some("openrouter/google/gemini-3-pro-image"), + &route, + AUTO_IMAGE + ), + "google/gemini-3-pro-image" + ); + let privacy = PrivacyPrefs::default(); + let alignment = AlignmentPrefs::default(); + let fb = AutoFallbacksPrefs { + image: "openrouter/google-gemini-pro-image-1".into(), + ..Default::default() + }; + assert_eq!( + resolve_auto_fallback(AutoFallbackKind::Image, &privacy, &alignment, &fb), + DEFAULT_AUTO_IMAGE_MODEL + ); + let d = parse_route_json( + r#"{"modality":"picture","reason":"gen","agentModel":null,"imageModel":"openrouter/google-gemini-pro-image-1"}"#, + ) + .expect("parse"); + assert!(d.image_model.is_none()); + } + + #[test] + fn agent_auto_returns_concrete_fallback() { + let route = RouteDecision { + modality: Modality::Chat, + reason: "t".into(), + agent_model: None, + image_model: None, + source: "t".into(), + }; + let privacy = PrivacyPrefs::default(); + let alignment = AlignmentPrefs { + model_alignment: "uncensored".into(), + ..Default::default() + }; + let fb = AutoFallbacksPrefs::default(); + assert_eq!( + resolve_agent_model_prefs(Some(AUTO_AGENT), &route, &privacy, &alignment, &fb) + .as_deref(), + Some(DEFAULT_AUTO_AGENT_MODEL_UNCENSORED) + ); + } + + #[test] + fn uncensored_auto_ignores_llama_suggestion() { + let route = RouteDecision { + modality: Modality::Picture, + reason: "t".into(), + agent_model: Some("meta-llama/llama-3.1-8b-instruct".into()), + image_model: None, + source: "t".into(), + }; + let privacy = PrivacyPrefs { + zero_data_retention: true, + ..Default::default() + }; + let alignment = AlignmentPrefs { + model_alignment: "uncensored".into(), + ..Default::default() + }; + let fb = AutoFallbacksPrefs::default(); + assert_eq!( + resolve_agent_model_prefs(Some("auto"), &route, &privacy, &alignment, &fb).as_deref(), + Some(DEFAULT_AUTO_AGENT_MODEL_UNCENSORED) + ); + assert_eq!( + resolve_agent_model_prefs( + Some("meta-llama/llama-3.1-8b-instruct"), + &route, + &privacy, + &alignment, + &fb + ) + .as_deref(), + Some("meta-llama/llama-3.1-8b-instruct") + ); + let cydonia = RouteDecision { + agent_model: Some("thedrummer/cydonia-24b-v4.1".into()), + ..route + }; + assert_eq!( + resolve_agent_model_prefs(Some("auto"), &cydonia, &privacy, &alignment, &fb).as_deref(), + Some("thedrummer/cydonia-24b-v4.1") + ); + } + + #[test] + fn upstream_router_is_opt_in_and_cost_selects_column() { + assert_eq!(AUTO_AGENT, "auto"); + assert!(!is_auto_agent(UPSTREAM_ROUTER)); + assert!(is_auto_agent("auto")); + assert!(!is_auto_router(UPSTREAM_ROUTER)); + let privacy = PrivacyPrefs::default(); + let alignment = AlignmentPrefs::default(); + let fb = AutoFallbacksPrefs::default(); + assert_eq!( + resolve_auto_fallback(AutoFallbackKind::Router, &privacy, &alignment, &fb), + DEFAULT_ROUTER_MODEL + ); + assert_ne!( + resolve_auto_fallback(AutoFallbackKind::Agent, &privacy, &alignment, &fb), + UPSTREAM_ROUTER + ); + let low = AutoFallbacksPrefs { + cost_tier: "low".into(), + ..Default::default() + }; + assert_eq!( + resolve_auto_fallback(AutoFallbackKind::Router, &privacy, &alignment, &low), + "meta-llama/llama-3.1-8b-instruct" + ); + assert_eq!( + resolve_auto_fallback(AutoFallbackKind::Image, &privacy, &alignment, &low), + "bytedance-seed/seedream-5-0-flash" + ); + let route = RouteDecision { + modality: Modality::Chat, + reason: "t".into(), + agent_model: Some(UPSTREAM_ROUTER.into()), + image_model: None, + source: "t".into(), + }; + assert_eq!( + resolve_agent_model_prefs(Some("auto"), &route, &privacy, &alignment, &fb).as_deref(), + Some(DEFAULT_AUTO_AGENT_MODEL) + ); + assert_eq!( + resolve_agent_model_prefs(Some(UPSTREAM_ROUTER), &route, &privacy, &alignment, &fb) + .as_deref(), + Some(UPSTREAM_ROUTER) + ); + let strict = PrivacyPrefs { + zero_data_retention: true, + ..Default::default() + }; + assert_eq!( + resolve_auto_fallback(AutoFallbackKind::Agent, &strict, &alignment, &fb), + DEFAULT_AUTO_AGENT_MODEL_ZDR + ); + assert_eq!( + resolve_auto_fallback(AutoFallbackKind::Image, &strict, &alignment, &fb), + DEFAULT_AUTO_IMAGE_MODEL_ZDR + ); + assert_eq!(DEFAULT_AUTO_AGENT_MODEL, DEFAULT_AUTO_AGENT_MODEL_ZDR); + assert_eq!(DEFAULT_ROUTER_MODEL, DEFAULT_ROUTER_MODEL_ZDR); + } + + fn align(alignment: &str, nsfw: bool) -> AlignmentPrefs { + AlignmentPrefs { + model_alignment: alignment.into(), + allow_nsfw_local: nsfw, + ..Default::default() + } + .normalize() + } + + fn tier(cost: &str) -> AutoFallbacksPrefs { + AutoFallbacksPrefs { + cost_tier: cost.into(), + ..Default::default() + } + } + + #[test] + fn local_enhance_path_ordinary_vs_adult() { + let privacy = PrivacyPrefs::default(); + let medium = tier("medium"); + let low = tier("low"); + let unc = align("uncensored", false); + let show = align("safety", true); + let balanced = align("balanced", false); + let scene = "nude woman on a bed, explicit sex"; + let barn = "a red barn at sunset"; + + let ordinary = local_enhance_path(barn, &unc, Some("auto"), &privacy, &medium); + assert!(!ordinary.adult); + assert_eq!(ordinary.model, "deepseek/deepseek-v4-pro"); + + let ordinary_low = local_enhance_path(barn, &unc, None, &privacy, &low); + assert!(!ordinary_low.adult); + assert_eq!(ordinary_low.model, "meta-llama/llama-3.1-8b-instruct"); + + let show_landscape = local_enhance_path( + "portrait of a scientist in a lab coat", + &show, + Some("auto"), + &privacy, + &medium, + ); + assert!(!show_landscape.adult); + assert_eq!(show_landscape.model, "deepseek/deepseek-v4-pro"); + + let not_adult_words = local_enhance_path( + "essex countryside, cocktail on the patio, structural analysis", + &unc, + None, + &privacy, + &medium, + ); + assert!(!not_adult_words.adult); + assert_eq!(not_adult_words.model, "deepseek/deepseek-v4-pro"); + + let adult = local_enhance_path(scene, &unc, Some("auto"), &privacy, &medium); + assert!(adult.adult); + assert_eq!(adult.model, "thedrummer/cydonia-24b-v4.1"); + + let adult_low = local_enhance_path(scene, &show, None, &privacy, &low); + assert!(adult_low.adult); + assert_eq!( + adult_low.model, + "cognitivecomputations/dolphin-mistral-24b-venice-edition" + ); + assert_eq!(adult_low.model, local_adult_matrix_model(&privacy, &low)); + + let adult_high = local_enhance_path(scene, &unc, None, &privacy, &tier("high")); + assert_eq!(adult_high.model, "thedrummer/cydonia-24b-v4.1"); + + // Sexual text without Uncensored or Show NSFW stays on the baseline writer. + let gated = local_enhance_path(scene, &balanced, None, &privacy, &medium); + assert!(!gated.adult); + assert_eq!(gated.model, "deepseek/deepseek-v4-pro"); + + let pinned = local_enhance_path( + barn, + &unc, + Some("mistralai/mistral-small"), + &privacy, + &medium, + ); + assert!(!pinned.adult); + assert_eq!(pinned.model, "mistralai/mistral-small"); + + for moderated in [ + "meta-llama/llama-3.1-8b-instruct", + "anthropic/claude-sonnet-5.5", + "openai/gpt-5-mini", + "google/gemini-4-neon", + ] { + let path = local_enhance_path(scene, &unc, Some(moderated), &privacy, &medium); + assert!(path.adult, "{moderated}"); + assert_eq!(path.model, "thedrummer/cydonia-24b-v4.1", "{moderated}"); + } + + let dolphin_pin = local_enhance_path( + scene, + &unc, + Some("cognitivecomputations/dolphin-mistral-24b-venice-edition"), + &privacy, + &medium, + ); + assert!(dolphin_pin.adult); + assert_eq!( + dolphin_pin.model, + "cognitivecomputations/dolphin-mistral-24b-venice-edition" + ); + } +} diff --git a/crates/freya-api/src/routes.rs b/crates/freya-api/src/routes.rs index 2d93d08..bdb2699 100644 --- a/crates/freya-api/src/routes.rs +++ b/crates/freya-api/src/routes.rs @@ -1,4 +1,5 @@ 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; @@ -8,12 +9,19 @@ use axum::response::{IntoResponse, Response}; use axum::Json; use base64::Engine; use serde::{Deserialize, Serialize}; -use serde_json::json; +use serde_json::{json, Value}; type ApiResult = Result; pub async fn health(State(state): State) -> impl IntoResponse { - let cfg = state.config.read().await; + let (open_router, civitai, worker_url) = { + let cfg = state.config.read().await; + ( + cfg.openrouter_configured(), + cfg.civitai_configured(), + cfg.diffusion_worker_url.clone(), + ) + }; let worker_ok = { let w = state.worker.read().await; match w.as_ref() { @@ -23,12 +31,304 @@ pub async fn health(State(state): State) -> impl IntoResponse { }; Json(json!({ "ok": true, - "openRouter": cfg.openrouter_configured(), - "civitai": cfg.civitai_configured(), + "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 { @@ -41,92 +341,3162 @@ pub struct AssistRequest { pub session: Option, } -fn strip_json_fence(raw: &str) -> &str { - raw.trim() - .trim_start_matches("```json") - .trim_start_matches("```") - .trim_end_matches("```") - .trim() -} +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()) +} + +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), + }) +} + +pub async fn chat( + State(state): State, + Json(mut 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, + ) + .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, + ); -pub async fn assist( - State(state): State, - Json(req): Json, -) -> ApiResult> { - let system = styles::load_instruction(&state.packs_dir, &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() + 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 { - req.message.clone() + 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), + } }; - 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 }); + // 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); + } + } - // 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(); + // 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 let Some(note) = parsed.get("sessionNote").and_then(|n| n.as_str()) { - out["sessionNote"] = json!(note); + } + 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, + })); } - if let Some(goal) = parsed.get("goal") { - out["goal"] = goal.clone(); + } else { + for a in &planned { + action_results.push(env.exec(&state, a).await); } - if let Some(steps) = parsed.get("steps") { - out["steps"] = steps.clone(); + } + } 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); } - 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, 8).await { - Ok(items) => { - let loras: Vec<_> = items - .into_iter() - .filter(|c| { - c.model_type.eq_ignore_ascii_case("LORA") - || c.model_type.eq_ignore_ascii_case("LoCon") - || c.model_type.to_lowercase().contains("lora") - }) - .take(6) - .collect(); - out["loras"] = json!(if loras.is_empty() { - // fall back to whatever matched the vibe - civ.search(q, 6).await.unwrap_or_default() - } else { - loras - }); - } - Err(e) => { - out["civitaiError"] = json!(e.to_string()); - } + } + } + + // 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()); + } } } - Ok(Json(out)) + // 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) } #[derive(Debug, Deserialize)] @@ -149,6 +3519,12 @@ 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)] @@ -157,12 +3533,33 @@ 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, @@ -170,13 +3567,89 @@ 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> { - // Auto-plan when backend/model unset. + 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"); if req.backend.as_deref().unwrap_or("auto") == "auto" && req.model.is_none() { - let system = styles::load_instruction(&state.packs_dir, "plan").await; + let system = load_instruction_toned(&state, "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::( @@ -191,7 +3664,23 @@ pub async fn run( req.backend = Some(b.into()); } if let Some(m) = plan.get("model").and_then(|x| x.as_str()) { - req.model = Some(m.into()); + 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); } if let Some(s) = plan.get("styleId").and_then(|x| x.as_str()) { req.style_ref = Some(s.into()); @@ -204,10 +3693,23 @@ 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(); @@ -233,6 +3735,8 @@ 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 { enhanced = Some(text.clone()); final_prompt = text; } } - let (bytes, mime, model_used, backend_used) = if backend == "local" { + 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 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| LoraWeight { - lora_name: l.name.clone(), - lora_scale: l.scale, + .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, + } }) .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, - req.model.as_deref(), + model.as_deref(), &loras, req.size.as_deref(), req.seed, @@ -297,13 +3954,21 @@ 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 +} + 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(meta)) + 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 }))) } pub async fn gallery_image( @@ -378,11 +4234,7 @@ pub async fn gallery_image( let bytes = tokio::fs::read(state.gallery.image_path(&meta)) .await .map_err(ApiError::from)?; - let ct = if meta.mime.contains("jpeg") { - "image/jpeg" - } else { - "image/png" - }; + let ct = crate::gallery::content_type_for_mime(&meta.mime); Ok(([(axum::http::header::CONTENT_TYPE, ct)], bytes).into_response()) } @@ -407,29 +4259,114 @@ pub async fn gallery_remix( }))) } -pub async fn models(State(state): State) -> ApiResult> { +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, + ) + }; 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": a.id, + "name": name, "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(json!({ + Ok(json!({ + // Image-capable cloud models (OpenRouter GET /images/models). "openrouter": cloud.drain(..).map(|m| json!({ - "id": m.id, "name": m.name, "backend": m.backend + "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, })).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> { @@ -444,28 +4381,123 @@ 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 items = civ.search(&q.q, q.limit).await.map_err(ApiError::from)?; + 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); + } 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). @@ -490,58 +4522,407 @@ pub async fn civitai_install( State(state): State, Json(req): Json, ) -> ApiResult> { - let cfg = state.config.read().await; - if !cfg.civitai_configured() { - return Err(ApiError::Msg( - "Civitai API key required — set it in Settings".into(), - )); - } - 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)?; - // Pass the key as authToken (Bearer on download) — never append to the URL - // (reqwest errors include the full URL and would leak the secret). - let auth = cfg.civitai_api_key.clone(); - let url = req.download_url.clone(); - drop(cfg); - client - .install_asset("civitai", &url, &req.dest_path, Some(&auth)) - .await - .map_err(ApiError::from)?; - Ok(Json(json!({ - "ok": true, - "destPath": req.dest_path, - "name": req.name, - }))) + civitai_install_inner(&state, req).await.map(Json) } -#[derive(Debug, Serialize)] +#[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, +} + +#[derive(Debug, Clone, 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, } -pub async fn settings_get(State(state): State) -> Json { +#[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 { let cfg = state.config.read().await; - Json(SettingsPublic { + 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(), 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(), + 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, }) } +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 { @@ -558,25 +4939,35 @@ 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(); +) -> 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(); { 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.clone()); - *state.worker.write().await = Some( - crate::worker::DiffusionWorkerClient::new(url) - .with_token(cfg.worker_token.clone()), - ); + cfg.diffusion_worker_url = Some(url); } } if let Some(m) = upd.chat_model { @@ -585,29 +4976,73 @@ 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; - let _ = state.persist_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 chat/image model at construction — rebuild after changes. - if models_changed { + // 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); } - Ok(settings_get(State(state)).await) + Ok(Json(SettingsPutResponse { + settings: settings_public_from_state(&state).await, + persisted, + })) } #[derive(Debug)] pub enum ApiError { Msg(String), + Unauthorized(String), + Unavailable(String), NotFound, NoWorker, } @@ -633,8 +5068,167 @@ 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 54d5ed6..18cd2aa 100644 --- a/crates/freya-api/src/state.rs +++ b/crates/freya-api/src/state.rs @@ -2,8 +2,11 @@ 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; @@ -27,17 +30,51 @@ 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()); - let worker = cfg - .diffusion_worker_url - .as_ref() - .map(|u| DiffusionWorkerClient::new(u.clone()).with_token(cfg.worker_token.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 packs_dir = cfg.packs_dir.clone(); let state = Self { config: Arc::new(RwLock::new(cfg)), @@ -48,6 +85,7 @@ impl AppState { worker: Arc::new(RwLock::new(worker)), }; state.load_secrets_file().await?; + state.migrate_legacy_upstream_auto().await?; Ok(state) } @@ -61,31 +99,133 @@ impl AppState { } let raw = tokio::fs::read(&path).await?; let secrets: RuntimeSecrets = serde_json::from_slice(&raw).unwrap_or_default(); - self.apply_secrets(secrets).await; + self.apply_secrets_inner(secrets, true).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 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 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(k) = secrets.civitai_api_key { - if !k.is_empty() { - cfg.civitai_api_key = k.clone(); - let mut civ = self.civitai.write().await; - *civ = CivitaiClient::new(k); + if let Some(m) = secrets.router_model { + if !m.trim().is_empty() { + cfg.router_model = m; + models_changed = true; } } - if let Some(k) = secrets.hf_token { - if !k.is_empty() { - cfg.hf_token = k; + 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 !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 Err(e) = self.persist_secrets().await { + tracing::warn!(error = %e, "legacy auto migration could not persist"); + } + 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<()> { @@ -94,12 +234,67 @@ impl AppState { tokio::fs::create_dir_all(parent).await?; } let secrets = RuntimeSecrets { - 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()), + 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()), }; 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/studio.rs b/crates/freya-api/src/studio.rs new file mode 100644 index 0000000..ef7c97f --- /dev/null +++ b/crates/freya-api/src/studio.rs @@ -0,0 +1,414 @@ +//! Non-secret Studio UI state: favorites, session LoRA pins, backend, video pin, mode. +//! +//! API keys, tokens, and passwords never belong here. Cards drop those fields. + +use serde::{Deserialize, Serialize}; +use serde_json::{json, Map, Value}; + +const CARD_KEYS: &[&str] = &[ + "id", + "name", + "modelType", + "kind", + "downloadUrl", + "destPath", + "triggerWord", + "baseModel", + "path", + "versionId", + "modelId", + "fileId", + "thumbnailUrl", + "civitaiUrl", + "scale", +]; + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct StudioPrefs { + /// `cloud` | `local`. Empty = UI has not synced a choice. + #[serde(default)] + pub generate_backend: String, + /// Video model id, or `auto`. Empty = unset. + #[serde(default)] + pub video_model: String, + /// `plan` | `auto` | `yolo`. Empty = unset. + #[serde(default)] + pub automation_mode: String, + #[serde(default)] + pub favorites: Vec, + #[serde(default)] + pub pinned_loras: Vec, +} + +impl Default for StudioPrefs { + fn default() -> Self { + Self { + generate_backend: String::new(), + video_model: String::new(), + automation_mode: String::new(), + favorites: Vec::new(), + pinned_loras: Vec::new(), + } + } +} + +#[derive(Debug, Clone, Deserialize, Default)] +#[serde(rename_all = "camelCase")] +pub struct StudioPatch { + #[serde(default)] + pub generate_backend: Option, + #[serde(default)] + pub video_model: Option, + #[serde(default)] + pub automation_mode: Option, + #[serde(default)] + pub favorites: Option>, + #[serde(default)] + pub pinned_loras: Option>, +} + +pub fn normalize_backend(raw: &str) -> Result { + match raw.trim().to_ascii_lowercase().as_str() { + "local" => Ok("local".into()), + "cloud" | "openrouter" => Ok("cloud".into()), + other => Err(format!("backend must be cloud or local (got {other})")), + } +} + +pub fn normalize_mode(raw: &str) -> Result { + match raw.trim().to_ascii_lowercase().as_str() { + "plan" => Ok("plan".into()), + "yolo" => Ok("yolo".into()), + "auto" => Ok("auto".into()), + other => Err(format!("mode must be plan, auto, or yolo (got {other})")), + } +} + +pub fn normalize_video_model(raw: &str) -> Result { + let t = raw.trim(); + if t.is_empty() || t.eq_ignore_ascii_case("auto") { + return Ok("auto".into()); + } + if t.contains(char::is_whitespace) || t.len() > 160 { + return Err("videoModel must be a model id".into()); + } + if looks_secret_text(t) { + return Err("videoModel must be an id, not a key".into()); + } + Ok(t.to_string()) +} + +/// Merge a patch. Favorites and pins are replaced only when the field is present. +pub fn apply_patch(prefs: &mut StudioPrefs, patch: StudioPatch) -> Result<(), String> { + if let Some(b) = patch.generate_backend { + prefs.generate_backend = normalize_backend(&b)?; + } + if let Some(v) = patch.video_model { + prefs.video_model = normalize_video_model(&v)?; + } + if let Some(m) = patch.automation_mode { + prefs.automation_mode = normalize_mode(&m)?; + } + if let Some(favs) = patch.favorites { + prefs.favorites = sanitize_list(&favs, false)?; + } + if let Some(pins) = patch.pinned_loras { + prefs.pinned_loras = sanitize_list(&pins, true)?; + } + Ok(()) +} + +pub fn favorite_add(prefs: &mut StudioPrefs, card: &Value) -> Result { + let card = sanitize_card(card, false)?; + let key = card_key(&card); + prefs.favorites.retain(|c| card_key(c) != key); + prefs.favorites.insert(0, card.clone()); + prefs.favorites.truncate(200); + Ok(card) +} + +pub fn favorite_remove(prefs: &mut StudioPrefs, card: &Value) -> bool { + let key = card_key(card); + let before = prefs.favorites.len(); + prefs + .favorites + .retain(|c| card_key(c) != key && !same_loose(c, card)); + before != prefs.favorites.len() +} + +pub fn pin_add(prefs: &mut StudioPrefs, card: &Value) -> Result { + let card = sanitize_card(card, true)?; + let key = card_key(&card); + prefs.pinned_loras.retain(|c| card_key(c) != key); + prefs.pinned_loras.push(card.clone()); + prefs.pinned_loras.truncate(24); + Ok(card) +} + +pub fn pin_remove(prefs: &mut StudioPrefs, card: &Value) -> bool { + let before = prefs.pinned_loras.len(); + prefs + .pinned_loras + .retain(|c| card_key(c) != card_key(card) && !same_loose(c, card)); + before != prefs.pinned_loras.len() +} + +fn sanitize_list(items: &[Value], pins: bool) -> Result, String> { + let mut out = Vec::new(); + for item in items { + let card = sanitize_card(item, pins)?; + let key = card_key(&card); + if out.iter().any(|c| card_key(c) == key) { + continue; + } + out.push(card); + if out.len() >= if pins { 24 } else { 200 } { + break; + } + } + Ok(out) +} + +pub fn sanitize_card(card: &Value, pin: bool) -> Result { + let obj = card + .as_object() + .ok_or_else(|| "asset must be an object".to_string())?; + if pin && !is_pinnable(card) { + return Err( + "session pins are LoRAs and embeddings — set checkpoints with set_base_model".into(), + ); + } + let mut out = Map::new(); + for key in CARD_KEYS { + let Some(val) = obj.get(*key) else { + continue; + }; + if val.is_null() { + continue; + } + match *key { + "downloadUrl" | "thumbnailUrl" | "civitaiUrl" => { + if let Some(url) = val.as_str().and_then(clean_http_url) { + out.insert((*key).to_string(), json!(url)); + } + } + "path" | "destPath" => { + if let Some(path) = val.as_str().and_then(clean_rel_path) { + out.insert((*key).to_string(), json!(path)); + } + } + "name" | "modelType" | "kind" | "triggerWord" | "baseModel" => { + if let Some(s) = val.as_str() { + let s = s.trim(); + if !s.is_empty() && !looks_secret_text(s) && s.len() <= 240 { + out.insert((*key).to_string(), json!(s)); + } + } + } + "id" => { + if let Some(s) = val.as_str() { + let s = s.trim(); + if !s.is_empty() && !looks_secret_text(s) && s.len() <= 160 { + out.insert("id".into(), json!(s)); + } + } else if let Some(n) = val.as_i64() { + out.insert("id".into(), json!(n)); + } + } + "versionId" | "modelId" | "fileId" => { + if let Some(n) = val.as_i64() { + out.insert((*key).to_string(), json!(n)); + } + } + "scale" => { + if let Some(n) = val.as_f64() { + if (0.0..=2.0).contains(&n) { + out.insert("scale".into(), json!(n)); + } + } + } + _ => {} + } + } + if !out.contains_key("scale") && pin { + out.insert("scale".into(), json!(0.8)); + } + let has_id = out.contains_key("id") || out.contains_key("path") || out.contains_key("name"); + if !has_id { + return Err("asset needs a name, id, or path".into()); + } + Ok(Value::Object(out)) +} + +pub fn is_pinnable(item: &Value) -> bool { + let path = item.get("path").and_then(|p| p.as_str()).unwrap_or(""); + let path_l = path.to_ascii_lowercase(); + if path_l.starts_with("checkpoints/") || path_l.starts_with("vae/") { + return false; + } + let t = item + .get("modelType") + .or_else(|| item.get("kind")) + .and_then(|v| v.as_str()) + .unwrap_or("") + .to_ascii_lowercase() + .replace([' ', '_', '-'], ""); + if t.is_empty() { + if path_l.starts_with("loras/") || path_l.starts_with("embeddings/") { + return true; + } + return path.is_empty(); + } + if matches!(t.as_str(), "checkpoint" | "vae" | "model") { + return false; + } + matches!( + t.as_str(), + "lora" + | "locon" + | "dora" + | "lycoris" + | "textualinversion" + | "embedding" + | "hypernet" + | "hypernetwork" + ) +} + +pub fn card_key(card: &Value) -> String { + if let Some(p) = card.get("path").and_then(|p| p.as_str()) { + let p = p.trim(); + if !p.is_empty() { + return format!("path:{p}"); + } + } + if let Some(s) = card.get("id").and_then(|i| i.as_str()) { + let s = s.trim(); + if !s.is_empty() { + return s.to_string(); + } + } + if let Some(n) = card.get("id").and_then(|i| i.as_i64()) { + return n.to_string(); + } + card.get("name") + .and_then(|n| n.as_str()) + .unwrap_or("") + .trim() + .to_string() +} + +fn same_loose(stored: &Value, query: &Value) -> bool { + let sk = card_key(stored); + let qk = card_key(query); + if !sk.is_empty() && sk == qk { + return true; + } + let sn = stored.get("name").and_then(|n| n.as_str()).unwrap_or(""); + let qn = query.get("name").and_then(|n| n.as_str()).unwrap_or(""); + !sn.is_empty() && sn.eq_ignore_ascii_case(qn) +} + +fn clean_rel_path(raw: &str) -> Option { + let t = raw.trim().trim_start_matches('/'); + if t.is_empty() || t.contains("..") || t.contains('\\') || t.contains('\0') { + return None; + } + let ok = t.starts_with("loras/") + || t.starts_with("checkpoints/") + || t.starts_with("embeddings/") + || t.starts_with("vae/") + || t.starts_with("textual_inversion/"); + if !ok { + return None; + } + Some(t.to_string()) +} + +fn clean_http_url(raw: &str) -> Option { + let raw = raw.trim(); + if !(raw.starts_with("https://") || raw.starts_with("http://")) { + return None; + } + if raw.contains('@') { + return None; + } + let (base, query) = raw.split_once('?').unwrap_or((raw, "")); + let kept: Vec<&str> = query + .split('&') + .filter(|p| !p.is_empty()) + .filter(|p| { + let k = p.split('=').next().unwrap_or("").to_ascii_lowercase(); + !matches!( + k.as_str(), + "token" | "key" | "api_key" | "apikey" | "access_token" | "secret" + ) + }) + .collect(); + let cleaned = if kept.is_empty() { + base.to_string() + } else { + format!("{base}?{}", kept.join("&")) + }; + if looks_secret_text(&cleaned) { + return None; + } + Some(cleaned) +} + +fn looks_secret_text(raw: &str) -> bool { + let l = raw.to_ascii_lowercase(); + l.contains("api_key") + || l.contains("apikey") + || l.contains("api-key") + || l.contains("secret") + || l.contains("password") + || l.contains("bearer ") + || l.contains("sk-or-") + || l.contains("hf_") +} + +pub fn asset_from_action_args(args: &Value) -> Value { + args.get("asset") + .filter(|a| a.is_object()) + .cloned() + .unwrap_or_else(|| args.clone()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn pin_rejects_checkpoint_and_strips_token() { + let ckpt = json!({"name": "Pony", "modelType": "Checkpoint", "path": "checkpoints/pony.safetensors"}); + assert!(sanitize_card(&ckpt, true).is_err()); + let lora = json!({ + "name": "Style", + "modelType": "LORA", + "path": "loras/style.safetensors", + "downloadUrl": "https://civitai.com/api/download/models/5?token=secret&type=Model", + "apiKey": "nope", + }); + let clean = sanitize_card(&lora, true).unwrap(); + assert_eq!( + clean.get("downloadUrl").and_then(|u| u.as_str()), + Some("https://civitai.com/api/download/models/5?type=Model") + ); + assert!(clean.get("apiKey").is_none()); + let mut prefs = StudioPrefs::default(); + pin_add(&mut prefs, &lora).unwrap(); + assert!(pin_add(&mut prefs, &ckpt).is_err()); + assert_eq!(prefs.pinned_loras.len(), 1); + } + + #[test] + fn backend_and_mode_normalize() { + assert_eq!(normalize_backend("openrouter").unwrap(), "cloud"); + assert_eq!(normalize_backend("local").unwrap(), "local"); + assert!(normalize_backend("http://evil").is_err()); + assert_eq!(normalize_mode("YOLO").unwrap(), "yolo"); + assert!(normalize_video_model("sk-or-v1-abc").is_err()); + } +} diff --git a/crates/freya-api/src/styles.rs b/crates/freya-api/src/styles.rs index df48341..671bded 100644 --- a/crates/freya-api/src/styles.rs +++ b/crates/freya-api/src/styles.rs @@ -64,11 +64,16 @@ 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). -fn is_safe_instruction_mode(mode: &str) -> bool { +pub fn is_safe_instruction_mode(mode: &str) -> bool { !mode.is_empty() && mode.len() <= 64 && mode @@ -76,7 +81,38 @@ fn is_safe_instruction_mode(mode: &str) -> bool { .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_') } -pub async fn load_instruction(packs_dir: &Path, mode: &str) -> String { +/// 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(); } @@ -96,13 +132,43 @@ pub async fn load_instruction(packs_dir: &Path, mode: &str) -> String { 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: "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(), + 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(), backend: "openrouter".into(), open_router_model: Some("black-forest-labs/flux.2-klein-4b".into()), local_checkpoint: None, @@ -115,7 +181,7 @@ fn builtin_styles() -> Vec { id: "anime-portrait".into(), display_name: "Anime Portrait (cloud)".into(), tags: vec!["anime".into(), "portrait".into()], - example_prompt: "anime style portrait, soft lighting, expressive eyes, detailed hair, clean linework, vibrant colors".into(), + example_prompt: "An anime-style portrait with soft lighting, expressive eyes, and clean colorful linework".into(), backend: "openrouter".into(), open_router_model: Some("black-forest-labs/flux.2-klein-4b".into()), local_checkpoint: None, @@ -130,7 +196,10 @@ fn builtin_styles() -> Vec { pub fn builtin_instruction(mode: &str) -> &'static str { match mode { "chat" => { - "You are Freya, a friendly image studio agent. Users describe goals in everyday language — you plan, find LoRAs, write model briefs, and iterate like an agentic coding session but for images. Never teach comma-separated tags unless a pinned LoRA needs one trigger word." + "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." } "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." @@ -145,13 +214,16 @@ pub fn builtin_instruction(mode: &str) -> &'static str { "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." } "plan" => { - "You are Freya's planner for agentic image sessions. Reply with JSON only: {\"backend\":\"openrouter\"|\"local\",\"model\":\"...\",\"styleId\":null|\"...\",\"enhanceMode\":\"prompt-prose\"|\"prompt-sd\",\"civitaiQuery\":null|\"short search\",\"rationale\":\"short\"}. Prefer openrouter + prompt-prose. Use local + prompt-sd only for pinned LoRAs." + "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\",\"sessionNote\":\"what to try next\"}. Ideas are everyday prose, never SD tags. civitaiQuery is 2–6 words for Civitai." + "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 (like agentic coding, for images). Given the user's goal and optional session history, reply with JSON only: {\"goal\":\"restated goal\",\"steps\":[{\"kind\":\"search_loras\"|\"generate\"|\"iterate\",\"prompt\":\"natural language\",\"note\":\"why\"}],\"civitaiQuery\":\"short search or empty\",\"batchPrompts\":[\"nl 1\",\"nl 2\",\"nl 3\"],\"sessionNote\":\"friendly next step\"}. batchPrompts are 2–4 natural-language variations to generate as a set. Never use SD keyword soup." + "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." + } + "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.", } @@ -175,7 +247,27 @@ mod tests { #[tokio::test] async fn load_instruction_ignores_unsafe_mode() { let packs = PathBuf::from("/nonexistent-packs-dir"); - let text = load_instruction(&packs, "../../etc/passwd").await; + 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.")); + } } diff --git a/crates/freya-api/src/worker.rs b/crates/freya-api/src/worker.rs index 6ee12a5..b86dcd5 100644 --- a/crates/freya-api/src/worker.rs +++ b/crates/freya-api/src/worker.rs @@ -12,10 +12,23 @@ pub struct DiffusionWorkerClient { } 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: reqwest::Client::new(), - base: base.into().trim_end_matches('/').to_string(), + http, + base, token: None, } } @@ -34,20 +47,64 @@ impl DiffusionWorkerClient { } pub async fn health(&self) -> bool { - self.http + self.health_detail().await.is_some() + } + + /// Fetch worker `/health` JSON when reachable. + pub async fn health_detail(&self) -> Option { + let resp = self + .http .get(format!("{}/health", self.base)) .send() .await - .map(|r| r.status().is_success()) - .unwrap_or(false) + .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 + } } 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!("{}/v1/loras", self.base))) + .apply_auth(self.http.get(format!("{}{path}", self.base))) .send() .await - .context("list loras")?; + .with_context(|| format!("list assets {path}"))?; if !resp.status().is_success() { return Ok(Vec::new()); } @@ -72,12 +129,67 @@ 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, @@ -133,21 +245,108 @@ impl DiffusionWorkerClient { .context("decode worker image") } - pub async fn install_asset( + /// 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>, - ) -> Result<()> { + meta: Option<&InstallMeta>, + r#async: bool, + ) -> Value { let mut 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 @@ -163,6 +362,128 @@ 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)] @@ -176,9 +497,164 @@ 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-api/src/worker_ctl.rs b/crates/freya-api/src/worker_ctl.rs new file mode 100644 index 0000000..0a35c7b --- /dev/null +++ b/crates/freya-api/src/worker_ctl.rs @@ -0,0 +1,175 @@ +//! Local worker process control (docker preferred, systemd fallback). + +use serde_json::{json, Value}; +use tokio::process::Command; +use tracing::warn; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum RuntimeKind { + Docker, + Systemd, + None, +} + +#[derive(Debug, Clone)] +pub struct RuntimeStatus { + pub kind: RuntimeKind, + pub name: String, + pub running: Option, + pub detail: String, +} + +impl RuntimeStatus { + pub fn to_json(&self) -> Value { + json!({ + "kind": match self.kind { + RuntimeKind::Docker => "docker", + RuntimeKind::Systemd => "systemd", + RuntimeKind::None => "none", + }, + "name": self.name, + "running": self.running, + "detail": self.detail, + }) + } +} + +/// Prefer docker when the named container exists; else systemd unit if active/loaded. +pub async fn detect(container: &str, unit: &str) -> RuntimeStatus { + if let Some(st) = docker_status(container).await { + return st; + } + if let Some(st) = systemd_status(unit).await { + return st; + } + RuntimeStatus { + kind: RuntimeKind::None, + name: container.to_string(), + running: None, + detail: format!( + "no docker container `{container}` and no systemd unit `{unit}` — start/stop unavailable for remote workers" + ), + } +} + +async fn docker_status(name: &str) -> Option { + let out = Command::new("docker") + .args(["inspect", "-f", "{{.State.Running}}", name]) + .output() + .await + .ok()?; + if !out.status.success() { + return None; + } + let running = String::from_utf8_lossy(&out.stdout).trim() == "true"; + Some(RuntimeStatus { + kind: RuntimeKind::Docker, + name: name.to_string(), + running: Some(running), + detail: if running { + "docker container running".into() + } else { + "docker container stopped".into() + }, + }) +} + +async fn systemd_status(unit: &str) -> Option { + let out = Command::new("systemctl") + .args(["show", unit, "-p", "ActiveState", "--value"]) + .output() + .await + .ok()?; + if !out.status.success() { + return None; + } + let state = String::from_utf8_lossy(&out.stdout).trim().to_string(); + if state.is_empty() || state == "not-found" || state == "inactive" { + // Distinguish "unit exists but inactive" vs missing: try is-enabled / list-unit-files. + let check = Command::new("systemctl") + .args(["cat", unit]) + .output() + .await + .ok()?; + if !check.status.success() { + return None; + } + } + let running = state == "active"; + Some(RuntimeStatus { + kind: RuntimeKind::Systemd, + name: unit.to_string(), + running: Some(running), + detail: format!("systemd ActiveState={state}"), + }) +} + +pub async fn start(container: &str, unit: &str) -> Result { + let detected = detect(container, unit).await; + match detected.kind { + RuntimeKind::Docker => { + let out = Command::new("docker") + .args(["start", container]) + .output() + .await + .map_err(|e| format!("docker start failed: {e}"))?; + if !out.status.success() { + let err = String::from_utf8_lossy(&out.stderr); + return Err(format!("docker start: {err}")); + } + Ok(docker_status(container) + .await + .unwrap_or(detected)) + } + RuntimeKind::Systemd => { + let out = Command::new("systemctl") + .args(["start", unit]) + .output() + .await + .map_err(|e| format!("systemctl start failed: {e}"))?; + if !out.status.success() { + let err = String::from_utf8_lossy(&out.stderr); + return Err(format!("systemctl start: {err}")); + } + Ok(systemd_status(unit).await.unwrap_or(detected)) + } + RuntimeKind::None => Err(detected.detail), + } +} + +pub async fn stop(container: &str, unit: &str) -> Result { + let detected = detect(container, unit).await; + match detected.kind { + RuntimeKind::Docker => { + // Short grace period so UI/proxy don't hang on the default 10s SIGTERM wait. + let out = Command::new("docker") + .args(["stop", "-t", "2", container]) + .output() + .await + .map_err(|e| format!("docker stop failed: {e}"))?; + if !out.status.success() { + let err = String::from_utf8_lossy(&out.stderr); + return Err(format!("docker stop: {err}")); + } + Ok(docker_status(container) + .await + .unwrap_or(detected)) + } + RuntimeKind::Systemd => { + let out = Command::new("systemctl") + .args(["stop", unit]) + .output() + .await + .map_err(|e| format!("systemctl stop failed: {e}"))?; + if !out.status.success() { + let err = String::from_utf8_lossy(&out.stderr); + return Err(format!("systemctl stop: {err}")); + } + Ok(systemd_status(unit).await.unwrap_or(detected)) + } + RuntimeKind::None => { + warn!(%detected.detail, "worker stop requested but no local runtime"); + Err(detected.detail) + } + } +} diff --git a/crates/freya-crd/src/lib.rs b/crates/freya-crd/src/lib.rs index 99e2dcd..d8dc287 100644 --- a/crates/freya-crd/src/lib.rs +++ b/crates/freya-crd/src/lib.rs @@ -32,6 +32,28 @@ 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() @@ -41,22 +63,29 @@ pub fn default_civitai_key() -> String { #[serde(rename_all = "camelCase")] pub struct OpenRouterSpec { pub secret_ref: SecretKeyRef, - /// Default chat / plan model id (OpenRouter). + /// Default chat / plan model id. `auto` = Freya internal Auto (not `openrouter/auto`). #[serde(default = "default_chat_model")] pub chat_model: String, - /// Default cloud image model id (OpenRouter). + /// Default cloud image model id. `auto` = Freya router / Flux NL default. #[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 { - "openrouter/auto".into() + "auto".into() } fn default_image_model() -> String { - "black-forest-labs/flux.2-klein-4b".into() + "auto".into() +} + +fn default_router_model() -> String { + "auto".into() } fn default_openrouter_base() -> String { @@ -72,6 +101,7 @@ impl Default for OpenRouterSpec { }, chat_model: default_chat_model(), image_model: default_image_model(), + router_model: default_router_model(), base_url: default_openrouter_base(), } } @@ -104,6 +134,12 @@ 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)] @@ -145,7 +181,7 @@ pub struct HuggingFaceSpec { pub secret_ref: Option, } -/// Namespaced Freya studio: API + UI + gallery. +/// Namespaced Freya studio: API + UI + gallery + optional MCP. #[derive(CustomResource, Clone, Debug, Serialize, Deserialize, JsonSchema)] #[kube( group = "freya.dataknife.ai", @@ -173,6 +209,12 @@ 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)] @@ -180,13 +222,44 @@ 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. Set for non-dev / Ingress; UI sends the bearer from Settings. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub api_token_secret_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 } @@ -200,6 +273,18 @@ 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, } @@ -352,10 +437,10 @@ pub enum WorkerPlacement { /// Optional GPU worker for local SD / LoRA (vLLM-Omni by default). /// /// 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. +/// - `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. #[derive(CustomResource, Clone, Debug, Serialize, Deserialize, JsonSchema)] #[kube( group = "freya.dataknife.ai", diff --git a/crates/freya-mcp/Cargo.toml b/crates/freya-mcp/Cargo.toml new file mode 100644 index 0000000..efda355 --- /dev/null +++ b/crates/freya-mcp/Cargo.toml @@ -0,0 +1,29 @@ +[package] +name = "freya-mcp" +version.workspace = true +edition.workspace = true +license.workspace = true +description = "Freya MCP server — thin Streamable HTTP proxy over freya-api" + +[[bin]] +name = "freya-mcp" +path = "src/main.rs" + +[dependencies] +anyhow = { workspace = true } +axum = { workspace = true } +clap = { workspace = true } +reqwest = { workspace = true } +rmcp = { version = "3.11", default-features = false, features = [ + "server", + "macros", + "transport-streamable-http-server", +] } +serde = { workspace = true } +serde_json = { workspace = true } +tokio = { workspace = true } +tokio-util = "0.7" +tower-http = { workspace = true } +tracing = { workspace = true } +tracing-subscriber = { workspace = true } +urlencoding = "2" diff --git a/crates/freya-mcp/src/api.rs b/crates/freya-mcp/src/api.rs new file mode 100644 index 0000000..1053828 --- /dev/null +++ b/crates/freya-mcp/src/api.rs @@ -0,0 +1,257 @@ +//! Thin HTTP client for freya-api. + +use anyhow::{anyhow, Context, Result}; +use reqwest::header::{AUTHORIZATION, CONTENT_TYPE}; +use reqwest::{Client, Method, StatusCode}; +use serde_json::Value; +use std::time::Duration; + +#[derive(Clone)] +pub struct FreyaApiClient { + http: Client, + base: String, + token: String, +} + +impl FreyaApiClient { + pub fn new(base_url: &str, token: &str) -> Result { + let base = base_url.trim_end_matches('/').to_string(); + if base.is_empty() { + return Err(anyhow!("FREYA_API_URL must not be empty")); + } + let http = Client::builder() + .timeout(Duration::from_secs(180)) + .build() + .context("build HTTP client")?; + Ok(Self { + http, + base, + token: token.to_string(), + }) + } + + pub async fn get_json(&self, path: &str) -> Result { + self.request(Method::GET, path, None).await + } + + pub async fn get_json_query(&self, path: &str, query: &[(String, String)]) -> Result { + let mut url = join_api_url(&self.base, path)?; + if !query.is_empty() { + let qs: Vec = query + .iter() + .map(|(k, v)| format!("{}={}", urlencoding::encode(k), urlencoding::encode(v))) + .collect(); + url.push('?'); + url.push_str(&qs.join("&")); + } + self.request_url(Method::GET, &url, None).await + } + + pub async fn post_json(&self, path: &str, body: &Value) -> Result { + self.request(Method::POST, path, Some(body.clone())).await + } + + pub async fn put_json(&self, path: &str, body: &Value) -> Result { + self.request(Method::PUT, path, Some(body.clone())).await + } + + pub async fn delete_json(&self, path: &str, body: &Value) -> Result { + self.request(Method::DELETE, path, Some(body.clone())).await + } + + async fn request(&self, method: Method, path: &str, body: Option) -> Result { + let url = join_api_url(&self.base, path)?; + self.request_url(method, &url, body).await + } + + async fn request_url(&self, method: Method, url: &str, body: Option) -> Result { + let mut req = self.http.request(method.clone(), url); + if !self.token.is_empty() { + req = req.header(AUTHORIZATION, format!("Bearer {}", self.token)); + } + if body.is_some() { + req = req.header(CONTENT_TYPE, "application/json"); + } + if let Some(b) = body { + req = req.json(&b); + } + let resp = req + .send() + .await + .with_context(|| format!("{method} {url}"))?; + let status = resp.status(); + let text = resp.text().await.unwrap_or_default(); + if status == StatusCode::UNAUTHORIZED { + return Err(anyhow!( + "freya-api returned 401 Unauthorized — check FREYA_API_TOKEN matches Studio apiTokenSecretRef" + )); + } + if !status.is_success() { + return Err(anyhow!("freya-api {status}: {text}")); + } + if text.trim().is_empty() { + return Ok(Value::Null); + } + serde_json::from_str(&text).with_context(|| format!("parse JSON from {url}")) + } +} + +/// Single path segment: a UUID (hyphenated or simple) or `[A-Za-z0-9_-]+`. +/// Rejects `/`, `?`, `#`, `%`, `.`, and `..`. Does not percent-encode. +fn is_safe_path_segment(id: &str) -> bool { + !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 == '-') +} + +pub(crate) fn safe_path_segment(id: &str) -> Result<&str> { + let id = id.trim(); + if !is_safe_path_segment(id) { + return Err(anyhow!("invalid id")); + } + Ok(id) +} + +/// Join a fixed route around one tool-supplied id. Errors before a URL exists +/// when the id is not a single safe segment. +pub(crate) fn bind_path_segment(prefix: &str, id: &str, suffix: &str) -> Result { + let id = safe_path_segment(id)?; + reject_unsafe_api_path(prefix)?; + if !suffix.is_empty() { + reject_unsafe_api_path(suffix)?; + } + let path = format!("{prefix}/{id}{suffix}"); + reject_unsafe_api_path(&path)?; + Ok(path) +} + +fn reject_unsafe_api_path(path: &str) -> Result<()> { + if !path.starts_with('/') || path.contains("//") { + return Err(anyhow!("refusing API path")); + } + for seg in path.split('/') { + if seg.is_empty() { + continue; + } + if !is_safe_path_segment(seg) { + return Err(anyhow!("refusing API path")); + } + } + Ok(()) +} + +/// Build `base + path` only when every segment is safe and URL parsing keeps +/// the path on that route (no dot-segment or query rewrite). +fn join_api_url(base: &str, path: &str) -> Result { + reject_unsafe_api_path(path)?; + let url = format!("{base}{path}"); + let parsed = reqwest::Url::parse(&url).context("parse API url")?; + if parsed.query().is_some() || parsed.fragment().is_some() { + return Err(anyhow!("refusing API path")); + } + let base_parsed = reqwest::Url::parse(base).context("parse API base")?; + let base_path = base_parsed.path().trim_end_matches('/'); + let expected = format!("{base_path}{path}"); + if parsed.path() != expected || parsed.host_str() != base_parsed.host_str() { + return Err(anyhow!("refusing API path that leaves the intended route")); + } + Ok(url) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn rejects_mcp_path_injection() { + let base = "http://freya-api.internal"; + for id in [ + "../auth/token", + "x?x", + "../../auth/token?", + "../../worker/start?", + ] { + assert!( + bind_path_segment("/v1/civitai/jobs", id, "/cancel").is_err(), + "{id}" + ); + assert!(bind_path_segment("/v1/gallery", id, "").is_err(), "{id}"); + assert!( + bind_path_segment("/v1/gallery", id, "/image").is_err(), + "{id}" + ); + let raw_path = format!("/v1/civitai/jobs/{id}/cancel"); + assert!( + join_api_url(base, &raw_path).is_err(), + "{id} must not become a request URL" + ); + let parsed = reqwest::Url::parse(&format!("{base}{raw_path}")).unwrap(); + let intended = format!("/v1/civitai/jobs/{id}/cancel"); + assert_ne!( + parsed.path(), + intended, + "{id} should leave the cancel route when interpolated raw" + ); + assert!( + parsed.query().is_some() + || !parsed.path().starts_with("/v1/civitai/jobs/") + || !parsed.path().ends_with("/cancel"), + "raw URL still on the cancel route: {parsed}" + ); + } + + for id in [ + "", + ".", + "..", + "a/b", + "a%2e%2e", + "a#b", + "a.b", + "a b", + "urn:uuid:550e8400-e29b-41d4-a716-446655440000", + ] { + assert!( + bind_path_segment("/v1/civitai/jobs", id, "/cancel").is_err(), + "{id}" + ); + } + + let id = "550e8400-e29b-41d4-a716-446655440000"; + let path = bind_path_segment("/v1/civitai/jobs", id, "/cancel").unwrap(); + assert_eq!(path, format!("/v1/civitai/jobs/{id}/cancel")); + assert!(!path.contains('%')); + let url = join_api_url(base, &path).unwrap(); + let parsed = reqwest::Url::parse(&url).unwrap(); + assert_eq!(parsed.path(), path); + assert!(parsed.query().is_none()); + assert!(parsed.fragment().is_none()); + + let gallery = bind_path_segment("/v1/gallery", "job_42-OK", "").unwrap(); + let gurl = join_api_url(base, &gallery).unwrap(); + assert_eq!( + reqwest::Url::parse(&gurl).unwrap().path(), + "/v1/gallery/job_42-OK" + ); + + // Fixed routes, including worker start/stop, stay on their path. + for path in [ + "/v1/health", + "/v1/worker/start", + "/v1/worker/stop", + "/v1/worker/base-model", + "/v1/civitai/jobs/clear", + "/v1/metrics/openrouter", + ] { + let url = join_api_url(base, path).unwrap_or_else(|e| panic!("{path}: {e}")); + assert_eq!(reqwest::Url::parse(&url).unwrap().path(), path); + } + } +} diff --git a/crates/freya-mcp/src/main.rs b/crates/freya-mcp/src/main.rs new file mode 100644 index 0000000..1320bec --- /dev/null +++ b/crates/freya-mcp/src/main.rs @@ -0,0 +1,203 @@ +//! Freya MCP server — Streamable HTTP at `/mcp`, proxying freya-api `/v1/*`. + +mod api; +mod tools; + +use anyhow::Context; +use axum::body::Body; +use axum::extract::State; +use axum::http::{header, Request, StatusCode}; +use axum::middleware::{self, Next}; +use axum::response::Response; +use axum::routing::get; +use axum::{Json, Router}; +use clap::Parser; +use rmcp::transport::streamable_http_server::session::local::LocalSessionManager; +use rmcp::transport::streamable_http_server::{StreamableHttpServerConfig, StreamableHttpService}; +use serde_json::json; +use std::net::SocketAddr; +use std::sync::Arc; +use tokio_util::sync::CancellationToken; +use tracing::info; + +use crate::api::FreyaApiClient; +use crate::tools::FreyaMcp; + +#[derive(Debug, Parser)] +#[command(name = "freya-mcp", about = "Freya MCP Streamable HTTP server")] +struct Args { + /// Listen address (host:port). + #[arg(long, env = "FREYA_MCP_BIND", default_value = "0.0.0.0:8090")] + bind: String, + + /// In-cluster Freya API base URL (no trailing slash). + #[arg(long, env = "FREYA_API_URL", default_value = "http://127.0.0.1:8080")] + api_url: String, + + /// Bearer token for freya-api (same Secret as Studio `apiTokenSecretRef`). + /// Required. `/mcp` returns 401 when this is empty unless + /// `--allow-unauthenticated` is set. + #[arg(long, env = "FREYA_API_TOKEN", default_value = "")] + api_token: String, + + /// Accept `/mcp` with no bearer. Off by default. Local dev only. + #[arg(long, env = "FREYA_MCP_ALLOW_UNAUTHENTICATED", default_value_t = false)] + allow_unauthenticated: bool, + + /// Comma-separated Host headers allowed by Streamable HTTP (DNS-rebinding guard). + /// Empty or `*` means loopback only. It does not disable the check. + #[arg(long, env = "FREYA_MCP_ALLOWED_HOSTS", default_value = "")] + allowed_hosts: String, +} + +#[tokio::main] +async fn main() -> anyhow::Result<()> { + tracing_subscriber::fmt() + .with_env_filter( + tracing_subscriber::EnvFilter::try_from_default_env() + .unwrap_or_else(|_| "info,freya_mcp=debug".into()), + ) + .init(); + + let args = Args::parse(); + let api = FreyaApiClient::new(&args.api_url, &args.api_token)?; + let api = Arc::new(api); + + let ct = CancellationToken::new(); + let mut config = StreamableHttpServerConfig::default() + .with_legacy_session_mode(false) + .with_json_response(true) + .with_cancellation_token(ct.child_token()); + let hosts = parse_allowed_hosts(&args.allowed_hosts); + let raw_hosts = args.allowed_hosts.trim(); + if raw_hosts.is_empty() || raw_hosts == "*" { + info!( + ?hosts, + "MCP Host allowlist defaulted to loopback (empty or * does not disable it)" + ); + } else { + info!(?hosts, "MCP Host header allowlist"); + } + config = config.with_allowed_hosts(hosts); + + let api_for_factory = api.clone(); + let mcp = StreamableHttpService::new( + move || Ok(FreyaMcp::new(api_for_factory.clone())), + LocalSessionManager::default().into(), + config, + ); + + let mcp_auth = McpAuth { + token: args.api_token.clone(), + allow_unauthenticated: args.allow_unauthenticated, + }; + let protected = Router::new() + .nest_service("/mcp", mcp) + .layer(middleware::from_fn_with_state(mcp_auth, require_mcp_token)); + let app = Router::new() + .route("/healthz", get(healthz)) + .merge(protected); + + let addr: SocketAddr = args + .bind + .parse() + .with_context(|| format!("invalid FREYA_MCP_BIND / --bind: {}", args.bind))?; + info!( + %addr, + api = %args.api_url, + token_configured = !args.api_token.is_empty(), + "freya-mcp listening (Streamable HTTP at /mcp)" + ); + + let listener = tokio::net::TcpListener::bind(addr).await?; + axum::serve(listener, app) + .with_graceful_shutdown(async move { + let _ = tokio::signal::ctrl_c().await; + ct.cancel(); + }) + .await?; + Ok(()) +} + +#[derive(Clone)] +struct McpAuth { + token: String, + allow_unauthenticated: bool, +} + +async fn require_mcp_token( + State(auth): State, + req: Request, + next: Next, +) -> Result { + if auth.token.is_empty() { + if auth.allow_unauthenticated { + tracing::warn!( + "FREYA_MCP_ALLOW_UNAUTHENTICATED is set; /mcp is accepting unauthenticated calls" + ); + return Ok(next.run(req).await); + } + return Err(StatusCode::UNAUTHORIZED); + } + let presented = req + .headers() + .get(header::AUTHORIZATION) + .and_then(|v| v.to_str().ok()) + .and_then(|h| h.strip_prefix("Bearer ")) + .unwrap_or(""); + if presented == auth.token { + Ok(next.run(req).await) + } else { + Err(StatusCode::UNAUTHORIZED) + } +} + +async fn healthz() -> Json { + Json(json!({ "ok": true, "service": "freya-mcp" })) +} + +fn loopback_hosts() -> Vec { + vec!["localhost".into(), "127.0.0.1".into(), "::1".into()] +} + +fn parse_allowed_hosts(raw: &str) -> Vec { + let raw = raw.trim(); + if raw.is_empty() || raw == "*" { + return loopback_hosts(); + } + let hosts: Vec = raw + .split(',') + .map(str::trim) + .filter(|s| !s.is_empty() && *s != "*") + .map(str::to_string) + .collect(); + if hosts.is_empty() { + loopback_hosts() + } else { + hosts + } +} + +#[cfg(test)] +mod tests { + use super::parse_allowed_hosts; + + #[test] + fn empty_or_star_stays_on_loopback() { + let loopback = || vec!["localhost".to_string(), "127.0.0.1".into(), "::1".into()]; + assert_eq!(parse_allowed_hosts(""), loopback()); + assert_eq!(parse_allowed_hosts("*"), loopback()); + assert_eq!( + parse_allowed_hosts(" freya.example, localhost "), + vec!["freya.example".to_string(), "localhost".into()] + ); + // A star in a real list does not open the check or drop the Ingress host. + assert_eq!( + parse_allowed_hosts("freya.dataknife.net, freya-mcp.freya.svc, *"), + vec![ + "freya.dataknife.net".to_string(), + "freya-mcp.freya.svc".into() + ] + ); + } +} diff --git a/crates/freya-mcp/src/tools.rs b/crates/freya-mcp/src/tools.rs new file mode 100644 index 0000000..1d1ea19 --- /dev/null +++ b/crates/freya-mcp/src/tools.rs @@ -0,0 +1,843 @@ +//! MCP tools wrapping freya-api `/v1/*` routes. + +use crate::api::FreyaApiClient; +use rmcp::handler::server::router::tool::ToolRouter; +use rmcp::handler::server::wrapper::Parameters; +use rmcp::model::{ + CallToolResult, ContentBlock, Implementation, ProtocolVersion, ServerCapabilities, ServerConfig, +}; +use rmcp::{schemars, tool, tool_handler, tool_router, ErrorData as McpError, ServerHandler}; +use serde::Deserialize; +use serde_json::{json, Value}; +use std::sync::Arc; + +fn json_ok(value: Value) -> Result { + let text = serde_json::to_string_pretty(&value).unwrap_or_else(|_| value.to_string()); + Ok(CallToolResult::success(vec![ContentBlock::text(text)])) +} + +fn map_err(err: impl std::fmt::Display) -> McpError { + McpError::internal_error(err.to_string(), None) +} + +#[derive(Clone)] +pub struct FreyaMcp { + api: Arc, + #[allow(dead_code)] // read by #[tool_handler] macro + tool_router: ToolRouter, +} + +#[derive(Debug, Deserialize, schemars::JsonSchema)] +#[serde(rename_all = "camelCase")] +pub struct GenerateArgs { + /// Image prompt (natural language). + pub prompt: String, + #[serde(default)] + pub negative_prompt: Option, + /// `auto` | `on` | `off` | `prompt-prose` | `prompt-sd` + #[serde(default)] + pub enhance: Option, + /// `openrouter` | `local` | `auto` + #[serde(default)] + pub backend: Option, + #[serde(default)] + pub model: Option, + #[serde(default)] + pub style_ref: Option, + #[serde(default)] + pub size: Option, + #[serde(default)] + pub seed: Option, +} + +#[derive(Debug, Deserialize, schemars::JsonSchema)] +#[serde(rename_all = "camelCase")] +pub struct GalleryGetArgs { + /// Artifact UUID from gallery_list / generate_image. + pub id: String, +} + +#[derive(Debug, Deserialize, schemars::JsonSchema)] +#[serde(rename_all = "camelCase")] +pub struct CivitaiSearchArgs { + /// Search query. + pub q: String, + #[serde(default)] + pub limit: Option, + /// Comma-separated types, e.g. `LORA,Checkpoint`. + #[serde(default)] + pub types: Option, +} + +#[derive(Debug, Deserialize, schemars::JsonSchema)] +#[serde(rename_all = "camelCase")] +pub struct SetBaseModelArgs { + /// Worker checkpoint path, e.g. `checkpoints/foo.safetensors`. + pub model: String, + /// Optional Civitai-style base family label (SDXL 1.0, Pony, …). + #[serde(default)] + pub base_model: Option, +} + +#[derive(Debug, Deserialize, schemars::JsonSchema)] +#[serde(rename_all = "camelCase")] +pub struct VideoArgs { + pub prompt: String, + /// `gif` or `video`. + #[serde(default)] + pub modality: Option, + #[serde(default)] + pub duration: Option, + /// `openrouter` | `local` | `cloud` | `auto` + #[serde(default)] + pub backend: Option, + /// Model id only, never an API key. + #[serde(default)] + pub model: Option, + #[serde(default)] + pub style_ref: Option, +} + +#[derive(Debug, Deserialize, schemars::JsonSchema)] +#[serde(rename_all = "camelCase")] +pub struct SeriesArgs { + pub goal: String, + #[serde(default)] + pub style_ref: Option, + /// `openrouter` | `local` | `cloud` | `auto` + #[serde(default)] + pub backend: Option, +} + +#[derive(Debug, Deserialize, schemars::JsonSchema)] +#[serde(rename_all = "camelCase")] +pub struct InstallArgs { + #[serde(default)] + pub download_url: Option, + #[serde(default)] + pub version_id: Option, + #[serde(default)] + pub file_id: Option, + pub dest_path: String, + #[serde(default)] + pub name: Option, + #[serde(default)] + pub base_model: Option, + #[serde(default)] + pub model_type: Option, + #[serde(default)] + pub model_id: Option, +} + +#[derive(Debug, Deserialize, schemars::JsonSchema)] +#[serde(rename_all = "camelCase")] +pub struct JobIdArgs { + pub job_id: String, +} + +#[derive(Debug, Deserialize, schemars::JsonSchema)] +#[serde(rename_all = "camelCase")] +pub struct ClearJobsArgs { + /// Also drop idle queued jobs. Active downloads stay. + #[serde(default)] + pub include_queued: Option, +} + +#[derive(Debug, Deserialize, schemars::JsonSchema)] +#[serde(rename_all = "camelCase")] +pub struct AssetPathArgs { + /// Worker-relative path such as `loras/foo.safetensors`. + pub path: String, +} + +#[derive(Debug, Deserialize, schemars::JsonSchema)] +#[serde(rename_all = "camelCase")] +pub struct AssetCardArgs { + #[serde(default)] + pub id: Option, + #[serde(default)] + pub name: String, + /// `LORA`, `LoCon`, `TextualInversion`, … Checkpoints cannot be pinned. + #[serde(default)] + pub model_type: Option, + #[serde(default)] + pub path: Option, + #[serde(default)] + pub download_url: Option, + #[serde(default)] + pub version_id: Option, + #[serde(default)] + pub model_id: Option, + #[serde(default)] + pub base_model: Option, + #[serde(default)] + pub trigger_word: Option, +} + +#[derive(Debug, Deserialize, schemars::JsonSchema)] +#[serde(rename_all = "camelCase")] +pub struct CostTierArgs { + /// `low` | `medium` | `high` | `max` + pub cost_tier: String, +} + +#[derive(Debug, Deserialize, schemars::JsonSchema)] +#[serde(rename_all = "camelCase")] +pub struct PrivacyArgs { + #[serde(default)] + pub zero_data_retention: Option, + /// `allow` or `deny` + #[serde(default)] + pub data_collection: Option, +} + +#[derive(Debug, Deserialize, schemars::JsonSchema)] +#[serde(rename_all = "camelCase")] +pub struct AlignmentArgs { + /// `balanced` | `safety` | `uncensored` + #[serde(default)] + pub model_alignment: Option, + /// Show NSFW local / Civitai assets. + #[serde(default)] + pub allow_nsfw_local: Option, + /// `warm` | `direct` | `steerable` + #[serde(default)] + pub instruction_tone: Option, +} + +#[derive(Debug, Deserialize, schemars::JsonSchema)] +#[serde(rename_all = "camelCase")] +pub struct BackendArgs { + /// `cloud` or `local` + pub backend: String, +} + +#[derive(Debug, Deserialize, schemars::JsonSchema)] +#[serde(rename_all = "camelCase")] +pub struct ModeArgs { + /// `plan` | `auto` | `yolo` + pub mode: String, +} + +#[derive(Debug, Deserialize, schemars::JsonSchema)] +#[serde(rename_all = "camelCase")] +pub struct ModelPinArgs { + /// Agent/chat model id, or `auto`. + #[serde(default)] + pub chat_model: Option, + #[serde(default)] + pub image_model: Option, + #[serde(default)] + pub router_model: Option, + #[serde(default)] + pub video_model: Option, +} + +fn card_key(card: &Value) -> String { + if let Some(p) = card.get("path").and_then(|p| p.as_str()) { + let p = p.trim(); + if !p.is_empty() { + return format!("path:{p}"); + } + } + if let Some(s) = card.get("id").and_then(|i| i.as_str()) { + let s = s.trim(); + if !s.is_empty() { + return s.to_string(); + } + } + if let Some(n) = card.get("id").and_then(|i| i.as_i64()) { + return n.to_string(); + } + card.get("name") + .and_then(|n| n.as_str()) + .unwrap_or("") + .trim() + .to_string() +} + +fn same_name(stored: &Value, query: &Value) -> bool { + let a = stored.get("name").and_then(|n| n.as_str()).unwrap_or(""); + let b = query.get("name").and_then(|n| n.as_str()).unwrap_or(""); + !a.is_empty() && a.eq_ignore_ascii_case(b) +} + +fn asset_card_json(args: &AssetCardArgs) -> Value { + json!({ + "id": args.id, + "name": args.name, + "modelType": args.model_type, + "path": args.path, + "downloadUrl": args.download_url, + "versionId": args.version_id, + "modelId": args.model_id, + "baseModel": args.base_model, + "triggerWord": args.trigger_word, + }) +} + +#[tool_router] +impl FreyaMcp { + pub fn new(api: Arc) -> Self { + Self { + api, + tool_router: Self::tool_router(), + } + } + + #[tool(description = "Freya API health summary (OpenRouter / Civitai / worker flags)")] + async fn health(&self) -> Result { + let v = self.api.get_json("/v1/health").await.map_err(map_err)?; + json_ok(v) + } + + #[tool(description = "Freya settings summary (models, flags; never returns secret values)")] + async fn settings(&self) -> Result { + let v = self.api.get_json("/v1/settings").await.map_err(map_err)?; + json_ok(v) + } + + #[tool( + description = "Generate an image via Freya (OpenRouter by default, or local worker when backend=local)" + )] + async fn generate_image( + &self, + Parameters(args): Parameters, + ) -> Result { + let body = json!({ + "prompt": args.prompt, + "negativePrompt": args.negative_prompt, + "enhance": args.enhance, + "backend": args.backend, + "model": args.model, + "styleRef": args.style_ref, + "size": args.size, + "seed": args.seed, + }); + let v = self + .api + .post_json("/v1/generate", &body) + .await + .map_err(map_err)?; + json_ok(v) + } + + #[tool(description = "List Freya gallery artifacts (newest first)")] + async fn gallery_list(&self) -> Result { + let v = self.api.get_json("/v1/gallery").await.map_err(map_err)?; + json_ok(v) + } + + #[tool(description = "Get one Freya gallery artifact metadata by id")] + async fn gallery_get( + &self, + Parameters(args): Parameters, + ) -> Result { + let path = crate::api::bind_path_segment("/v1/gallery", &args.id, "").map_err(map_err)?; + let v = self.api.get_json(&path).await.map_err(map_err)?; + json_ok(v) + } + + #[tool(description = "Search Civitai models/LoRAs via Freya API")] + async fn civitai_search( + &self, + Parameters(args): Parameters, + ) -> Result { + let mut q = vec![("q".into(), args.q)]; + if let Some(limit) = args.limit { + q.push(("limit".into(), limit.to_string())); + } + if let Some(types) = args.types { + q.push(("types".into(), types)); + } + let v = self + .api + .get_json_query("/v1/civitai/search", &q) + .await + .map_err(map_err)?; + json_ok(v) + } + + #[tool(description = "Diffusion worker stats/status via Freya API")] + async fn worker_stats(&self) -> Result { + let v = self + .api + .get_json("/v1/worker/stats") + .await + .map_err(map_err)?; + json_ok(v) + } + + #[tool(description = "List local checkpoints on the diffusion worker")] + async fn worker_checkpoints(&self) -> Result { + let v = self + .api + .get_json("/v1/worker/checkpoints") + .await + .map_err(map_err)?; + json_ok(v) + } + + #[tool(description = "Read the worker's active base checkpoint / base model")] + async fn worker_get_base_model(&self) -> Result { + let v = self + .api + .get_json("/v1/worker/base-model") + .await + .map_err(map_err)?; + json_ok(v) + } + + #[tool(description = "Set the worker's active base checkpoint (Worker tab)")] + async fn worker_set_base_model( + &self, + Parameters(args): Parameters, + ) -> Result { + let body = json!({ + "model": args.model, + "baseModel": args.base_model, + }); + let v = self + .api + .put_json("/v1/worker/base-model", &body) + .await + .map_err(map_err)?; + json_ok(v) + } + + #[tool(description = "List available Freya models (OpenRouter + local discovery)")] + async fn models(&self) -> Result { + let v = self.api.get_json("/v1/models").await.map_err(map_err)?; + json_ok(v) + } + + #[tool( + description = "List Freya style packs (id / displayName / tags); pass styleRef to generate_image)" + )] + async fn list_styles(&self) -> Result { + let v = self.api.get_json("/v1/styles").await.map_err(map_err)?; + json_ok(v) + } + + #[tool( + description = "Generate a gif or video (modality gif|video). Model id only, never a key." + )] + async fn generate_video( + &self, + Parameters(args): Parameters, + ) -> Result { + let body = json!({ + "prompt": args.prompt, + "modality": args.modality.unwrap_or_else(|| "video".into()), + "duration": args.duration, + "backend": args.backend, + "model": args.model, + "styleRef": args.style_ref, + }); + let v = self + .api + .post_json("/v1/generate", &body) + .await + .map_err(map_err)?; + json_ok(v) + } + + #[tool(description = "Generate a short series of stills for one goal")] + async fn generate_series( + &self, + Parameters(args): Parameters, + ) -> Result { + let body = json!({ + "goal": args.goal, + "styleRef": args.style_ref, + "backend": args.backend, + }); + let v = self + .api + .post_json("/v1/series", &body) + .await + .map_err(map_err)?; + json_ok(v) + } + + #[tool(description = "Enqueue a Civitai install (downloadUrl or versionId, plus destPath)")] + async fn civitai_install( + &self, + Parameters(args): Parameters, + ) -> Result { + let body = json!({ + "downloadUrl": args.download_url.unwrap_or_default(), + "versionId": args.version_id, + "fileId": args.file_id, + "destPath": args.dest_path, + "name": args.name, + "baseModel": args.base_model, + "modelType": args.model_type, + "modelId": args.model_id, + }); + let v = self + .api + .post_json("/v1/civitai/install", &body) + .await + .map_err(map_err)?; + json_ok(v) + } + + #[tool(description = "List Civitai download jobs on the worker")] + async fn civitai_jobs(&self) -> Result { + let v = self + .api + .get_json("/v1/civitai/jobs") + .await + .map_err(map_err)?; + json_ok(v) + } + + #[tool(description = "Cancel one queued or active Civitai download by jobId")] + async fn civitai_cancel_job( + &self, + Parameters(args): Parameters, + ) -> Result { + let path = crate::api::bind_path_segment("/v1/civitai/jobs", &args.job_id, "/cancel") + .map_err(map_err)?; + let v = self + .api + .post_json(&path, &json!({})) + .await + .map_err(map_err)?; + json_ok(v) + } + + #[tool(description = "Clear finished Civitai jobs. includeQueued also drops idle queued jobs.")] + async fn civitai_clear_jobs( + &self, + Parameters(args): Parameters, + ) -> Result { + let body = json!({ "includeQueued": args.include_queued.unwrap_or(false) }); + let v = self + .api + .post_json("/v1/civitai/jobs/clear", &body) + .await + .map_err(map_err)?; + json_ok(v) + } + + #[tool(description = "List installed LoRAs, checkpoints, embeddings, and VAEs")] + async fn list_installed(&self) -> Result { + let v = self + .api + .get_json("/v1/worker/installed") + .await + .map_err(map_err)?; + json_ok(v) + } + + #[tool(description = "Delete one installed worker file by relative path")] + async fn delete_installed( + &self, + Parameters(args): Parameters, + ) -> Result { + let v = self + .api + .delete_json("/v1/worker/assets", &json!({ "path": args.path })) + .await + .map_err(map_err)?; + json_ok(v) + } + + #[tool(description = "Delete one gallery generation by id when the user asked to remove it")] + async fn gallery_delete( + &self, + Parameters(args): Parameters, + ) -> Result { + let path = crate::api::bind_path_segment("/v1/gallery", &args.id, "").map_err(map_err)?; + let v = self + .api + .delete_json(&path, &json!({})) + .await + .map_err(map_err)?; + json_ok(v) + } + + #[tool( + description = "Return the gallery file URL and filename the UI download button uses. Does not return image bytes." + )] + async fn gallery_download( + &self, + Parameters(args): Parameters, + ) -> Result { + let path = crate::api::bind_path_segment("/v1/gallery", &args.id, "").map_err(map_err)?; + let image = + crate::api::bind_path_segment("/v1/gallery", &args.id, "/image").map_err(map_err)?; + let mut v = self.api.get_json(&path).await.map_err(map_err)?; + if let Some(obj) = v.as_object_mut() { + obj.entry("url".to_string()).or_insert_with(|| json!(image)); + obj.insert( + "note".into(), + json!("The Studio download button saves this file. Bytes are not in this tool result."), + ); + } + json_ok(v) + } + + #[tool( + description = "Read Studio favorites, LoRA pins, backend, video pin, and mode. No secrets." + )] + async fn studio(&self) -> Result { + let v = self.api.get_json("/v1/studio").await.map_err(map_err)?; + json_ok(v) + } + + #[tool(description = "Favorite a Civitai or installed asset card (not a secret)")] + async fn favorite_asset( + &self, + Parameters(args): Parameters, + ) -> Result { + self.merge_studio_list("favorites", &asset_card_json(&args), true) + .await + } + + #[tool(description = "Remove an asset from favorites by id, path, or name")] + async fn unfavorite_asset( + &self, + Parameters(args): Parameters, + ) -> Result { + self.merge_studio_list("favorites", &asset_card_json(&args), false) + .await + } + + #[tool(description = "Pin a LoRA or embedding for the session. Checkpoints are rejected.")] + async fn pin_lora( + &self, + Parameters(args): Parameters, + ) -> Result { + self.merge_studio_list("pinnedLoras", &asset_card_json(&args), true) + .await + } + + #[tool(description = "Unpin a session LoRA by id, path, or name")] + async fn unpin_lora( + &self, + Parameters(args): Parameters, + ) -> Result { + self.merge_studio_list("pinnedLoras", &asset_card_json(&args), false) + .await + } + + #[tool(description = "Set Auto cost tier: low, medium, high, or max")] + async fn set_cost_tier( + &self, + Parameters(args): Parameters, + ) -> Result { + let mut st = self.api.get_json("/v1/settings").await.map_err(map_err)?; + let fallbacks = st + .get_mut("autoFallbacks") + .and_then(|v| v.as_object_mut()) + .ok_or_else(|| map_err("settings missing autoFallbacks"))?; + fallbacks.insert("costTier".into(), json!(args.cost_tier)); + let body = + json!({ "autoFallbacks": st.get("autoFallbacks").cloned().unwrap_or(json!({})) }); + let v = self + .api + .put_json("/v1/settings", &body) + .await + .map_err(map_err)?; + json_ok(v) + } + + #[tool( + description = "Set privacy toggles: zeroDataRetention and/or dataCollection allow|deny. Not API keys." + )] + async fn set_privacy( + &self, + Parameters(args): Parameters, + ) -> Result { + let mut st = self.api.get_json("/v1/settings").await.map_err(map_err)?; + let privacy = st + .get_mut("privacy") + .and_then(|v| v.as_object_mut()) + .ok_or_else(|| map_err("settings missing privacy"))?; + if let Some(z) = args.zero_data_retention { + privacy.insert("zeroDataRetention".into(), json!(z)); + } + if let Some(dc) = args.data_collection { + privacy.insert("dataCollection".into(), json!(dc)); + } + let body = json!({ "privacy": st.get("privacy").cloned().unwrap_or(json!({})) }); + let v = self + .api + .put_json("/v1/settings", &body) + .await + .map_err(map_err)?; + json_ok(v) + } + + #[tool(description = "Set alignment, Show NSFW (allowNsfwLocal), and/or instruction tone")] + async fn set_alignment( + &self, + Parameters(args): Parameters, + ) -> Result { + let mut st = self.api.get_json("/v1/settings").await.map_err(map_err)?; + let alignment = st + .get_mut("alignment") + .and_then(|v| v.as_object_mut()) + .ok_or_else(|| map_err("settings missing alignment"))?; + if let Some(a) = args.model_alignment { + alignment.insert("modelAlignment".into(), json!(a)); + } + if let Some(n) = args.allow_nsfw_local { + alignment.insert("allowNsfwLocal".into(), json!(n)); + } + if let Some(t) = args.instruction_tone { + alignment.insert("instructionTone".into(), json!(t)); + } + let body = json!({ "alignment": st.get("alignment").cloned().unwrap_or(json!({})) }); + let v = self + .api + .put_json("/v1/settings", &body) + .await + .map_err(map_err)?; + json_ok(v) + } + + #[tool(description = "Set the composer backend to cloud or local")] + async fn set_generate_backend( + &self, + Parameters(args): Parameters, + ) -> Result { + let v = self + .api + .put_json("/v1/studio", &json!({ "generateBackend": args.backend })) + .await + .map_err(map_err)?; + json_ok(v) + } + + #[tool(description = "Set Plan / Auto / YOLO")] + async fn set_automation_mode( + &self, + Parameters(args): Parameters, + ) -> Result { + let v = self + .api + .put_json("/v1/studio", &json!({ "automationMode": args.mode })) + .await + .map_err(map_err)?; + json_ok(v) + } + + #[tool(description = "Pin agent, router, image, and/or video model ids. Never pass API keys.")] + async fn set_model_pins( + &self, + Parameters(args): Parameters, + ) -> Result { + let mut body = serde_json::Map::new(); + if let Some(m) = args.chat_model { + body.insert("chatModel".into(), json!(m)); + } + if let Some(m) = args.image_model { + body.insert("imageModel".into(), json!(m)); + } + if let Some(m) = args.router_model { + body.insert("routerModel".into(), json!(m)); + } + let mut out = json!({}); + if !body.is_empty() { + out = self + .api + .put_json("/v1/settings", &Value::Object(body)) + .await + .map_err(map_err)?; + } + if let Some(m) = args.video_model { + let studio = self + .api + .put_json("/v1/studio", &json!({ "videoModel": m })) + .await + .map_err(map_err)?; + if let Some(obj) = out.as_object_mut() { + obj.insert("studio".into(), studio); + } else { + out = studio; + } + } + json_ok(out) + } + + #[tool(description = "Start the local diffusion worker container or unit")] + async fn worker_start(&self) -> Result { + let v = self + .api + .post_json("/v1/worker/start", &json!({})) + .await + .map_err(map_err)?; + json_ok(v) + } + + #[tool(description = "Stop the local diffusion worker container or unit")] + async fn worker_stop(&self) -> Result { + let v = self + .api + .post_json("/v1/worker/stop", &json!({})) + .await + .map_err(map_err)?; + json_ok(v) + } + + async fn merge_studio_list( + &self, + field: &str, + card: &Value, + add: bool, + ) -> Result { + let studio = self.api.get_json("/v1/studio").await.map_err(map_err)?; + let mut list = studio + .get(field) + .and_then(|v| v.as_array()) + .cloned() + .unwrap_or_default(); + let key = card_key(card); + list.retain(|item| card_key(item) != key && !same_name(item, card)); + if add { + list.insert(0, card.clone()); + } + let body = json!({ field: list }); + let v = self + .api + .put_json("/v1/studio", &body) + .await + .map_err(map_err)?; + json_ok(v) + } + + #[tool(description = "OpenRouter key spend / credits snapshot (GET /v1/metrics/openrouter)")] + async fn openrouter_metrics(&self) -> Result { + let v = self + .api + .get_json("/v1/metrics/openrouter") + .await + .map_err(map_err)?; + json_ok(v) + } +} + +#[tool_handler] +impl ServerHandler for FreyaMcp { + fn get_info(&self) -> ServerConfig { + ServerConfig::new( + ServerCapabilities::builder() + .enable_tools() + .build(), + ) + .with_server_info(Implementation::new("freya-mcp", env!("CARGO_PKG_VERSION"))) + .with_protocol_version(ProtocolVersion::V_2025_03_26) + .with_instructions( + "Freya image studio MCP. Tools proxy freya-api for generate, gallery, Civitai \ + install/jobs, installed assets, favorites, LoRA pins, cost/privacy/alignment, \ + cloud vs local, and model id pins. Never read or set API keys, tokens, or passwords. \ + gallery_download returns the URL the UI saves; it does not return image bytes. \ + Pin LoRAs only — checkpoints use worker_set_base_model. Do not change the worker host URL." + .to_string(), + ) + } +} diff --git a/crates/freya-operator/Cargo.toml b/crates/freya-operator/Cargo.toml index a84c05e..035c596 100644 --- a/crates/freya-operator/Cargo.toml +++ b/crates/freya-operator/Cargo.toml @@ -27,3 +27,4 @@ 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 ed10d44..b4f3ff4 100644 --- a/crates/freya-operator/src/reconcile/asset.rs +++ b/crates/freya-operator/src/reconcile/asset.rs @@ -74,8 +74,14 @@ async fn install_remote( 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); 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()))?; diff --git a/crates/freya-operator/src/reconcile/credentials.rs b/crates/freya-operator/src/reconcile/credentials.rs new file mode 100644 index 0000000..a5a3cbf --- /dev/null +++ b/crates/freya-operator/src/reconcile/credentials.rs @@ -0,0 +1,258 @@ +//! Game-operator style admin + API token Secret bootstrap for FreyaStudio. +//! +//! Mirrors satisfactory/dragonwilds/palworld: `generateSecrets` fills missing +//! `admin-password` (and username) without overwriting existing non-empty keys. +//! Also ensures a machine API bearer Secret when `apiTokenSecretRef` is unset. + +use freya_crd::{ + FreyaStudio, LocalObjectRef, SecretKeyRef, SECRET_KEY_ADMIN_PASSWORD, + SECRET_KEY_ADMIN_USERNAME, SECRET_KEY_API_TOKEN, +}; +use k8s_openapi::api::core::v1::Secret; +use k8s_openapi::apimachinery::pkg::apis::meta::v1::{ObjectMeta, OwnerReference}; +use kube::api::{Patch, PatchParams}; +use kube::Error as KubeError; +use kube::{Api, ResourceExt}; +use std::collections::BTreeMap; +use tracing::info; + +use super::studio::Error; +use super::{LABEL_COMPONENT, LABEL_INSTANCE, LABEL_MANAGED, LABEL_NAME, MANAGED_BY}; +use crate::Ctx; + +/// Resolved credential wiring for API/MCP Deployments + status. +#[derive(Clone, Debug)] +pub struct StudioCredentials { + pub admin_secret_name: Option, + pub admin_generated: bool, + pub api_token: Option, + pub api_token_generated: bool, +} + +pub async fn ensure_studio_credentials( + ctx: &Ctx, + ns: &str, + studio: &FreyaStudio, + owner: &OwnerReference, +) -> Result { + let name = studio.name_any(); + let labels = BTreeMap::from([ + (LABEL_MANAGED.to_string(), MANAGED_BY.to_string()), + (LABEL_NAME.to_string(), "freya".to_string()), + (LABEL_INSTANCE.to_string(), name.clone()), + (LABEL_COMPONENT.to_string(), "credentials".to_string()), + ]); + + let mut out = StudioCredentials { + admin_secret_name: None, + // Same meaning as game-operator status.credentialsGenerated: operator-managed bootstrap. + admin_generated: studio.spec.generate_admin_secrets, + api_token: studio.spec.api_token_secret_ref.clone().map(Into::into), + api_token_generated: false, + }; + + let admin_name = admin_secret_name(studio); + if studio.spec.generate_admin_secrets { + let _ = ensure_admin_secret(ctx, ns, &admin_name, &labels, owner).await?; + out.admin_secret_name = Some(admin_name); + } else if let Some(LocalObjectRef { name: ref n }) = studio.spec.admin_credentials_secret_ref { + out.admin_secret_name = Some(n.clone()); + out.admin_generated = false; + } + + if out.api_token.is_none() && studio.spec.generate_admin_secrets { + let token_name = format!("{name}-api-token"); + let created = ensure_api_token_secret(ctx, ns, &token_name, &labels, owner).await?; + out.api_token = Some(SecretKeyRef { + name: token_name, + key: SECRET_KEY_API_TOKEN.into(), + }); + out.api_token_generated = created; + } + + Ok(out) +} + +fn admin_secret_name(studio: &FreyaStudio) -> String { + if let Some(LocalObjectRef { name }) = &studio.spec.admin_credentials_secret_ref { + return name.clone(); + } + format!("{}-admin", studio.name_any()) +} + +async fn ensure_admin_secret( + ctx: &Ctx, + ns: &str, + secret_name: &str, + labels: &BTreeMap, + owner: &OwnerReference, +) -> Result { + let api: Api = Api::namespaced(ctx.client.clone(), ns); + let existing = match api.get(secret_name).await { + Ok(secret) => Some(secret), + Err(KubeError::Api(err)) if err.code == 404 => None, + Err(err) => return Err(Error::Kube(err)), + }; + if let Some(secret) = &existing { + if !secret_owned_by_studio(secret, owner) { + info!( + %secret_name, + "leaving pre-existing admin Secret unchanged (not owned by this FreyaStudio)" + ); + return Ok(false); + } + } + let mut data = existing + .as_ref() + .and_then(|s| s.data.clone()) + .unwrap_or_default(); + + let mut generated = false; + if !data.contains_key(SECRET_KEY_ADMIN_USERNAME) + || data + .get(SECRET_KEY_ADMIN_USERNAME) + .map(|b| b.0.is_empty()) + .unwrap_or(true) + { + data.insert( + SECRET_KEY_ADMIN_USERNAME.into(), + k8s_openapi::ByteString(b"admin".to_vec()), + ); + generated = true; + } + if !data.contains_key(SECRET_KEY_ADMIN_PASSWORD) + || data + .get(SECRET_KEY_ADMIN_PASSWORD) + .map(|b| b.0.is_empty()) + .unwrap_or(true) + { + let pw = generate_password(); + data.insert( + SECRET_KEY_ADMIN_PASSWORD.into(), + k8s_openapi::ByteString(pw.into_bytes()), + ); + generated = true; + info!(%secret_name, "generated admin-password for FreyaStudio admin login"); + } + + let secret = Secret { + metadata: ObjectMeta { + name: Some(secret_name.to_string()), + namespace: Some(ns.to_string()), + labels: Some(labels.clone()), + owner_references: Some(vec![owner.clone()]), + ..Default::default() + }, + type_: Some("Opaque".into()), + data: Some(data), + ..Default::default() + }; + api.patch( + secret_name, + &PatchParams::apply(MANAGED_BY).force(), + &Patch::Apply(&secret), + ) + .await + .map_err(Error::Kube)?; + Ok(generated) +} + +async fn ensure_api_token_secret( + ctx: &Ctx, + ns: &str, + secret_name: &str, + labels: &BTreeMap, + owner: &OwnerReference, +) -> Result { + let api: Api = Api::namespaced(ctx.client.clone(), ns); + let existing = match api.get(secret_name).await { + Ok(secret) => Some(secret), + Err(KubeError::Api(err)) if err.code == 404 => None, + Err(err) => return Err(Error::Kube(err)), + }; + if let Some(secret) = &existing { + if !secret_owned_by_studio(secret, owner) { + info!( + %secret_name, + "leaving pre-existing API token Secret unchanged (not owned by this FreyaStudio)" + ); + return Ok(false); + } + } + let mut data = existing + .as_ref() + .and_then(|s| s.data.clone()) + .unwrap_or_default(); + + let mut generated = false; + if !data.contains_key(SECRET_KEY_API_TOKEN) + || data + .get(SECRET_KEY_API_TOKEN) + .map(|b| b.0.is_empty()) + .unwrap_or(true) + { + let token = generate_api_token(); + data.insert( + SECRET_KEY_API_TOKEN.into(), + k8s_openapi::ByteString(token.into_bytes()), + ); + generated = true; + info!(%secret_name, "generated API bearer token Secret for FreyaStudio"); + } + + let secret = Secret { + metadata: ObjectMeta { + name: Some(secret_name.to_string()), + namespace: Some(ns.to_string()), + labels: Some(labels.clone()), + owner_references: Some(vec![owner.clone()]), + ..Default::default() + }, + type_: Some("Opaque".into()), + data: Some(data), + ..Default::default() + }; + api.patch( + secret_name, + &PatchParams::apply(MANAGED_BY).force(), + &Patch::Apply(&secret), + ) + .await + .map_err(Error::Kube)?; + Ok(generated) +} + +/// Operator-created Secrets carry this Studio's ownerRef, or the credentials labels +/// from an earlier reconcile. A caller-named Secret that already exists is read-only. +fn secret_owned_by_studio(secret: &Secret, owner: &OwnerReference) -> bool { + if secret + .metadata + .owner_references + .as_ref() + .is_some_and(|refs| refs.iter().any(|r| r.uid == owner.uid)) + { + return true; + } + let Some(labels) = secret.metadata.labels.as_ref() else { + return false; + }; + labels.get(LABEL_MANAGED).map(String::as_str) == Some(MANAGED_BY) + && labels.get(LABEL_INSTANCE).map(String::as_str) == Some(owner.name.as_str()) + && labels.get(LABEL_COMPONENT).map(String::as_str) == Some("credentials") +} + +fn generate_password() -> String { + // 24 hex chars ≈ game-operator 18 random bytes (URL-safe). + format!("{}", uuid::Uuid::new_v4().simple()) + .chars() + .take(24) + .collect() +} + +fn generate_api_token() -> String { + format!( + "{}{}", + uuid::Uuid::new_v4().simple(), + uuid::Uuid::new_v4().simple() + ) +} diff --git a/crates/freya-operator/src/reconcile/mod.rs b/crates/freya-operator/src/reconcile/mod.rs index a2044fd..2f53b93 100644 --- a/crates/freya-operator/src/reconcile/mod.rs +++ b/crates/freya-operator/src/reconcile/mod.rs @@ -1,4 +1,5 @@ pub mod asset; +pub mod credentials; pub mod generation; pub mod studio; pub mod worker; @@ -23,9 +24,86 @@ 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 38e4f19..088dadb 100644 --- a/crates/freya-operator/src/reconcile/studio.rs +++ b/crates/freya-operator/src/reconcile/studio.rs @@ -1,8 +1,8 @@ -//! Reconcile FreyaStudio → API/UI Deployments, Services, gallery PVC, optional Ingress. +//! Reconcile FreyaStudio → API/UI/MCP Deployments, Services, gallery PVC, optional Ingress. use crate::reconcile::{ - default_api_image, default_ui_image, LABEL_COMPONENT, LABEL_INSTANCE, LABEL_MANAGED, - LABEL_NAME, MANAGED_BY, + default_api_image, default_mcp_image, default_ui_image, LABEL_COMPONENT, LABEL_INSTANCE, + LABEL_MANAGED, LABEL_NAME, MANAGED_BY, }; use crate::Ctx; use freya_crd::{FreyaDiffusionWorker, FreyaStudio, WorkerPlacement}; @@ -10,12 +10,13 @@ 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, ServicePort, ServiceSpec, Volume, VolumeMount, + SecretKeySelector, Service, ServiceAccount, ServicePort, ServiceSpec, Volume, VolumeMount, }; use k8s_openapi::api::networking::v1::{ HTTPIngressPath, HTTPIngressRuleValue, Ingress, IngressBackend, IngressRule, - IngressServiceBackend, IngressSpec, ServiceBackendPort, + IngressServiceBackend, IngressSpec, IngressTLS, 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}; @@ -32,16 +33,29 @@ pub async fn reconcile(studio: Arc, ctx: Arc) -> Result, ctx: Arc) -> Result Result<(String, Option), Error> { +) -> 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 { @@ -73,7 +99,38 @@ async fn resolve_worker( worker.spec.port ), }; - Ok((url, worker.spec.auth_secret_ref.clone())) + 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 { @@ -170,6 +227,7 @@ 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}"); @@ -183,6 +241,12 @@ 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()), @@ -203,6 +267,11 @@ 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), ]; @@ -212,19 +281,74 @@ async fn ensure_api_deployment( value: Some(worker_name.clone()), ..Default::default() }); - let (worker_url, worker_auth) = resolve_worker(ctx, ns, worker_name).await?; + 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), + 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 api_tok) = studio.spec.api_token_secret_ref { + 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()), + ..Default::default() + }); } if let Some(ref civ) = studio.spec.civitai.secret_ref { @@ -273,6 +397,7 @@ 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), @@ -317,6 +442,101 @@ 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, @@ -384,6 +604,92 @@ 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, @@ -437,50 +743,95 @@ 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: 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() - }, - }, - ], - }), + http: Some(HTTPIngressRuleValue { paths }), }]), ..Default::default() }), @@ -504,15 +855,32 @@ 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 status = serde_json::json!({ - "status": { - "phase": phase, - "apiEndpoint": api_endpoint, - "uiEndpoint": ui_endpoint, - } + let mut status_body = serde_json::json!({ + "phase": phase, + "apiEndpoint": api_endpoint, + "uiEndpoint": ui_endpoint, + "adminCredentialsGenerated": creds.admin_generated, }); + 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)?; diff --git a/crates/freya-operator/src/reconcile/worker.rs b/crates/freya-operator/src/reconcile/worker.rs index f85bcf6..48658d2 100644 --- a/crates/freya-operator/src/reconcile/worker.rs +++ b/crates/freya-operator/src/reconcile/worker.rs @@ -1,4 +1,4 @@ -//! Reconcile FreyaDiffusionWorker — in-cluster GPU Deployment or external remote endpoint. +//! Reconcile FreyaDiffusionWorker — external URL (recommended) or optional in-cluster GPU. use crate::reconcile::{ default_worker_image, LABEL_COMPONENT, LABEL_INSTANCE, LABEL_MANAGED, LABEL_NAME, MANAGED_BY, diff --git a/crates/freya-worker/Cargo.toml b/crates/freya-worker/Cargo.toml index 2190d0d..dc068b9 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 = "Minimal Freya diffusion worker stub (OpenAI images API + LoRA install)" +description = "Freya diffusion worker (OpenAI images API + LoRA/checkpoint install; GPU via Diffusers engine)" [[bin]] name = "freya-worker" @@ -22,3 +22,4 @@ 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 6cd4da2..77b426f 100644 --- a/crates/freya-worker/src/main.rs +++ b/crates/freya-worker/src/main.rs @@ -1,21 +1,30 @@ -//! Minimal diffusion worker: OpenAI-compatible images + asset install for Freya. -//! Production: replace with vLLM-Omni. This stub enables LoRA install + API wiring. +//! 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. -use axum::extract::{Request, State}; +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::{get, post}; +use axum::routing::{delete, get, post}; use axum::{Json, Router}; use base64::Engine; use clap::Parser; -use serde::Deserialize; -use serde_json::json; +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 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; #[derive(Parser, Clone)] struct Config { @@ -23,15 +32,95 @@ 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] @@ -53,30 +142,329 @@ async fn main() -> anyhow::Result<()> { } 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() .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(|| async { Json(json!({"ok": true})) })) + .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(), "freya-worker listening (stub — swap for vLLM-Omni in prod)"); + info!( + %bind, + models = %cfg.models_dir.display(), + engine = %engine_label, + "freya-worker listening (checkpoints + LoRAs on disk; GPU via FREYA_ENGINE_URL)" + ); 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, @@ -100,40 +488,501 @@ async fn require_worker_token( Ok(next.run(req).await) } -async fn list_loras(State(app): State>) -> Json { +#[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 { let mut data = Vec::new(); - 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 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 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.", + })) +} + +#[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 })))); } } - Json(json!({ "data": data })) + 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, } -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)] +#[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 } #[derive(Deserialize)] @@ -144,6 +993,38 @@ struct InstallReq { /// 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. @@ -179,6 +1060,32 @@ fn install_host_ok(host: &str) -> bool { || 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; @@ -196,7 +1103,7 @@ fn download_client() -> Result { return attempt.error("too many redirects"); } match attempt.url().host_str() { - Some(h) if install_host_ok(h) => attempt.follow(), + Some(h) if redirect_host_ok(h, attempt.previous()) => attempt.follow(), _ => attempt.error("redirect to disallowed host"), } })) @@ -204,70 +1111,603 @@ fn download_client() -> Result { .map_err(|e| e.to_string()) } -async fn install( - State(app): State>, - Json(req): Json, -) -> Result, (axum::http::StatusCode, Json)> { +/// 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| { ( - axum::http::StatusCode::BAD_REQUEST, + StatusCode::BAD_REQUEST, Json(json!({ "error": e })), ) })?; if !install_url_ok(&req.url) { return Err(( - axum::http::StatusCode::BAD_REQUEST, + 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 { if let Some(parent) = dest.parent() { fs::create_dir_all(parent) .await - .map_err(|e| internal("create dest dir", e))?; + .map_err(|_| "create dest dir failed".to_string())?; } - let client = download_client().map_err(|e| internal("download client", e))?; - let mut req_builder = client.get(&req.url); - if let Some(token) = req - .auth_token - .as_deref() - .map(str::trim) - .filter(|t| !t.is_empty()) - { + 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 resp = req_builder + let mut resp = req_builder .send() .await - .map_err(|e| internal("download request", e))?; + .map_err(download_request_err)?; if !resp.status().is_success() { - return Err(( - axum::http::StatusCode::BAD_REQUEST, - Json(json!({ - "error": format!("download failed with HTTP {}", resp.status()) - })), - )); + 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()); + } + } } - let bytes = resp - .bytes() + file.flush() .await - .map_err(|e| internal("download body", e))?; - fs::write(&dest, &bytes) + .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) .await - .map_err(|e| internal("write asset", e))?; - info!(path = %dest.display(), bytes = bytes.len(), "installed asset"); - Ok(Json(json!({ "ok": true, "path": req.dest_path }))) + .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) } -/// Never return raw transport errors — reqwest Display includes the full URL (and query secrets). -fn internal( - context: &str, - e: impl std::fmt::Display, -) -> (axum::http::StatusCode, Json) { - warn!(%context, error = %e, "asset install failed"); +/// 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"); ( - axum::http::StatusCode::BAD_REQUEST, + StatusCode::BAD_REQUEST, Json(json!({ "error": format!("{context} failed") })), ) } @@ -286,6 +1726,34 @@ mod tests { 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( @@ -296,11 +1764,45 @@ mod tests { )); 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/deploy/compose/.env.example b/deploy/compose/.env.example new file mode 100644 index 0000000..1001fe3 --- /dev/null +++ b/deploy/compose/.env.example @@ -0,0 +1,55 @@ +# Freya Docker Compose (single-system). Copy to .env next to compose.yaml: +# cp deploy/compose/.env.example deploy/compose/.env +# Never commit .env. Distinct from legacy/ Comfy/Swarm stack. + +# --- Required for cloud chat + images --- +OPENROUTER_API_KEY= + +# --- Admin login (compose path — no operator CRD) --- +# Generate: openssl rand -base64 24 +FREYA_ADMIN_USER=admin +FREYA_ADMIN_PASSWORD=changeme + +# --- Machine bearer (MCP / curl). MCP returns 401 when this is empty. --- +# Generate: openssl rand -hex 32 +FREYA_API_TOKEN= +FREYA_WORKER_TOKEN= + +# --- Optional integrations --- +CIVITAI_API_KEY= +HF_TOKEN= + +# --- Host paths (lab defaults; portable: use ./data/... under this directory) --- +FREYA_GALLERY_DIR=/mnt/game2/freya/gallery +FREYA_MODELS_DIR=/mnt/game2/freya/models +FREYA_SECRETS_DIR=/mnt/game2/freya/secrets +# Portable example (paths relative to deploy/compose/): +# FREYA_GALLERY_DIR=./data/gallery +# FREYA_MODELS_DIR=./data/models +# FREYA_SECRETS_DIR=./data/secrets + +# --- Ports --- +# UI is published. The worker is not (API uses the compose network). +# MCP profile binds 127.0.0.1 only. +FREYA_UI_PORT=8080 +FREYA_WORKER_PORT=8091 +FREYA_MCP_PORT=8090 + +# --- In-compose worker URL (API → worker on shared network) --- +FREYA_DIFFUSION_WORKER_URL=http://freya-worker:8091 + +# Browser origins for CORS (UI on :8080) +FREYA_CORS_ORIGINS=http://127.0.0.1:8080,http://localhost:8080 + +# MCP Host allowlist (profile mcp). Empty or * stays on loopback; it does not disable the check. +FREYA_MCP_ALLOWED_HOSTS=localhost,127.0.0.1 + +# --- Optional image tags (defaults build locally) --- +# FREYA_API_IMAGE=freya-api:local +# FREYA_WEB_IMAGE=freya-web:local +# FREYA_WORKER_IMAGE=freya-worker:local +# FREYA_MCP_IMAGE=freya-mcp:local + +# GPU overlay (compose.gpu.yaml / make compose-up-gpu) +# FREYA_GPU_COUNT=1 +# NVIDIA_VISIBLE_DEVICES=all diff --git a/deploy/compose/compose.gpu.yaml b/deploy/compose/compose.gpu.yaml new file mode 100644 index 0000000..83934da --- /dev/null +++ b/deploy/compose/compose.gpu.yaml @@ -0,0 +1,27 @@ +# Optional GPU overlay for freya-worker (nvidia-container-toolkit required). +# Switches worker image to Dockerfile.worker (Diffusers + CUDA) and reserves a GPU. +# Usage: make compose-up-gpu +# or: docker compose -f deploy/compose/compose.yaml -f deploy/compose/compose.gpu.yaml --env-file deploy/compose/.env up -d --build +# +# Standalone GPU host (kind/prd Studio → this box): ./scripts/run-local-worker.sh + +services: + freya-worker: + build: + context: ../.. + dockerfile: Dockerfile.worker + image: ${FREYA_WORKER_IMAGE:-freya-diffusion-worker:local} + environment: + NVIDIA_VISIBLE_DEVICES: ${NVIDIA_VISIBLE_DEVICES:-all} + NVIDIA_DRIVER_CAPABILITIES: compute,utility + FREYA_ENGINE_URL: http://127.0.0.1:8092 + FREYA_ENGINE_KEEP_LOADED: ${FREYA_ENGINE_KEEP_LOADED:-0} + HF_TOKEN: ${HF_TOKEN:-} + HUGGING_FACE_HUB_TOKEN: ${HF_TOKEN:-} + deploy: + resources: + reservations: + devices: + - driver: nvidia + count: ${FREYA_GPU_COUNT:-1} + capabilities: [gpu] diff --git a/deploy/compose/compose.yaml b/deploy/compose/compose.yaml new file mode 100644 index 0000000..6077bd6 --- /dev/null +++ b/deploy/compose/compose.yaml @@ -0,0 +1,114 @@ +# Freya single-system stack (no Kubernetes / operator). +# Distinct from legacy/docker-compose.yml (ComfyUI / SwarmUI / Ollama). +# +# Quick start: +# cp deploy/compose/.env.example deploy/compose/.env +# # edit .env — OPENROUTER_API_KEY + FREYA_ADMIN_PASSWORD +# make compose-up +# # UI http://127.0.0.1:8080 worker stays on the compose network optional MCP 127.0.0.1:8090 +# +# Docs: docs/COMPOSE.md + +name: freya + +services: + freya-api: + build: + context: ../.. + dockerfile: Dockerfile + target: api + image: ${FREYA_API_IMAGE:-freya-api:local} + container_name: freya-api + restart: unless-stopped + environment: + FREYA_BIND: 0.0.0.0:8080 + FREYA_GALLERY_DIR: /data/gallery + FREYA_SECRETS_FILE: /data/secrets/.freya-runtime.json + FREYA_PACKS_DIR: /packs + FREYA_DIFFUSION_WORKER_URL: ${FREYA_DIFFUSION_WORKER_URL:-http://freya-worker:8091} + FREYA_WORKER_CONTAINER: freya-worker + FREYA_CORS_ORIGINS: ${FREYA_CORS_ORIGINS:-http://127.0.0.1:8080,http://localhost:8080} + OPENROUTER_API_KEY: ${OPENROUTER_API_KEY:-} + OPENROUTER_BASE_URL: ${OPENROUTER_BASE_URL:-https://openrouter.ai/api/v1} + CIVITAI_API_KEY: ${CIVITAI_API_KEY:-} + HF_TOKEN: ${HF_TOKEN:-} + FREYA_ADMIN_USER: ${FREYA_ADMIN_USER:-admin} + FREYA_ADMIN_PASSWORD: ${FREYA_ADMIN_PASSWORD:-} + FREYA_API_TOKEN: ${FREYA_API_TOKEN:-} + FREYA_WORKER_TOKEN: ${FREYA_WORKER_TOKEN:-} + FREYA_CHAT_MODEL: ${FREYA_CHAT_MODEL:-auto} + FREYA_IMAGE_MODEL: ${FREYA_IMAGE_MODEL:-black-forest-labs/flux.2-klein-4b} + volumes: + - ${FREYA_GALLERY_DIR:-/mnt/game2/freya/gallery}:/data/gallery + - ${FREYA_SECRETS_DIR:-/mnt/game2/freya/secrets}:/data/secrets + networks: + - freya + depends_on: + - freya-worker + # Distroless nonroot (UID 65532). Host dirs must be writable by that UID + # (see docs/COMPOSE.md). No operator / CRDs on this path. + + freya-web: + build: + context: ../.. + dockerfile: Dockerfile.web + image: ${FREYA_WEB_IMAGE:-freya-web:local} + container_name: freya-web + restart: unless-stopped + environment: + FREYA_API_UPSTREAM: http://freya-api:8080 + ports: + - "${FREYA_UI_PORT:-8080}:80" + networks: + - freya + depends_on: + - freya-api + + freya-worker: + build: + context: ../.. + dockerfile: Dockerfile + target: worker + image: ${FREYA_WORKER_IMAGE:-freya-worker:local} + container_name: freya-worker + restart: unless-stopped + environment: + FREYA_WORKER_PORT: "8091" + FREYA_MODELS_DIR: /data/models + FREYA_WORKER_TOKEN: ${FREYA_WORKER_TOKEN:-} + volumes: + - ${FREYA_MODELS_DIR:-/mnt/game2/freya/models}:/data/models + # Not published on the host. The API reaches the worker at freya-worker:8091. + # Publishing 8091 with an empty FREYA_WORKER_TOKEN exposes generate and deletes. + networks: + - freya + # GPU Diffusers engine: `make compose-up-gpu` (compose.gpu.yaml / Dockerfile.worker). + # Default image is the Rust stub (no VRAM). Host GPU path: ./scripts/run-local-worker.sh + + # Optional: `make compose-up-mcp` or COMPOSE_PROFILES=mcp + freya-mcp: + profiles: ["mcp"] + build: + context: ../.. + dockerfile: Dockerfile + target: mcp + image: ${FREYA_MCP_IMAGE:-freya-mcp:local} + container_name: freya-mcp + restart: unless-stopped + environment: + FREYA_MCP_BIND: 0.0.0.0:8090 + FREYA_API_URL: http://freya-api:8080 + FREYA_API_TOKEN: ${FREYA_API_TOKEN:-} + # Loopback only. Empty or * does not disable the Host check. + FREYA_MCP_ALLOWED_HOSTS: ${FREYA_MCP_ALLOWED_HOSTS:-localhost,127.0.0.1} + ports: + - "127.0.0.1:${FREYA_MCP_PORT:-8090}:8090" + networks: + - freya + depends_on: + - freya-api + +networks: + freya: + name: freya-compose + driver: bridge diff --git a/deploy/worker/engine/requirements.txt b/deploy/worker/engine/requirements.txt new file mode 100644 index 0000000..32104fc --- /dev/null +++ b/deploy/worker/engine/requirements.txt @@ -0,0 +1,14 @@ +# Runtime deps on top of a CUDA PyTorch base image (torch already installed). +fastapi==0.115.12 +uvicorn[standard]==0.34.2 +diffusers==0.32.2 +transformers==4.49.0 +accelerate==1.5.2 +safetensors==0.5.3 +Pillow==11.1.0 +sentencepiece==0.2.0 +protobuf==5.29.4 +huggingface-hub==0.29.3 +peft==0.14.0 +# Optional: quieter single-file SDXL loads +omegaconf==2.3.0 diff --git a/deploy/worker/engine/server.py b/deploy/worker/engine/server.py new file mode 100644 index 0000000..5e3586c --- /dev/null +++ b/deploy/worker/engine/server.py @@ -0,0 +1,449 @@ +#!/usr/bin/env python3 +"""Freya local diffusion engine (Diffusers + CUDA). + +Speaks a tiny HTTP API on FREYA_ENGINE_PORT (default 8092). freya-worker proxies +/v1/images/generations here. Loads checkpoints/LoRAs from FREYA_MODELS_DIR on +demand; unloads after each generate unless FREYA_ENGINE_KEEP_LOADED=1. +""" + +from __future__ import annotations + +import base64 +import gc +import io +import logging +import os +import threading +from pathlib import Path +from typing import Any + +import torch +import uvicorn +from fastapi import FastAPI, HTTPException +from fastapi.responses import JSONResponse +from pydantic import BaseModel, Field + +LOG = logging.getLogger("freya-engine") + +MODELS_DIR = Path(os.environ.get("FREYA_MODELS_DIR", "/models")).resolve() +KEEP_LOADED = os.environ.get("FREYA_ENGINE_KEEP_LOADED", "0").strip() in ( + "1", + "true", + "yes", +) +DEFAULT_STEPS = int(os.environ.get("FREYA_ENGINE_STEPS", "20")) +DEFAULT_GUIDANCE = float(os.environ.get("FREYA_ENGINE_GUIDANCE", "7.0")) +HF_HOME = os.environ.get("HF_HOME") or os.environ.get("HUGGINGFACE_HUB_CACHE") + +app = FastAPI(title="freya-diffusers-engine", version="0.1.0") +_lock = threading.Lock() +_pipe: Any = None +_loaded_model: str | None = None +_loaded_loras: list[str] = [] + + +class GenerateReq(BaseModel): + prompt: str + model: str | None = None + negative_prompt: str | None = None + size: str | None = None + seed: int | None = None + steps: int | None = None + guidance_scale: float | None = None + lora_request: list[dict[str, Any]] | None = Field(default=None) + base_model: str | None = Field(default=None, alias="baseModel") + frames: int | None = None + format: str | None = None + + model_config = {"populate_by_name": True} + + +def _device() -> str: + return "cuda" if torch.cuda.is_available() else "cpu" + + +def _dtype(): + if torch.cuda.is_available(): + return torch.float16 + return torch.float32 + + +def _parse_size(size: str | None) -> tuple[int, int]: + if not size: + return 1024, 1024 + s = size.lower().replace("*", "x") + if "x" in s: + a, b = s.split("x", 1) + return max(64, int(a)), max(64, int(b)) + n = max(64, int(s)) + return n, n + + +def _looks_xl(model: str, base_model: str | None) -> bool: + blob = f"{model} {base_model or ''}".lower() + keys = ( + "xl", + "sdxl", + "pony", + "illustrious", + "noobai", + "juggernaut", + "realvis", + "hassaku", + "wai-", + ) + return any(k in blob for k in keys) + + +def _looks_sd15(model: str, base_model: str | None) -> bool: + blob = f"{model} {base_model or ''}".lower() + if _looks_xl(model, base_model): + return False + return any(k in blob for k in ("sd 1.5", "sd1.5", "1.5", "dreamshaper_8", "dreamshaper_-_8")) + + +def _resolve_model_path(model: str) -> str: + """Return HF id or absolute path under MODELS_DIR.""" + m = model.strip() + if not m: + raise HTTPException(status_code=400, detail="model is required") + if m.endswith(".safetensors") or m.startswith("checkpoints/") or "/" in m and not m.startswith("http"): + # Relative under models dir, or absolute path already in tree. + p = Path(m) + if not p.is_absolute(): + p = MODELS_DIR / m + p = p.resolve() + if not str(p).startswith(str(MODELS_DIR)): + raise HTTPException(status_code=400, detail="model path escapes models dir") + if not p.is_file(): + raise HTTPException(status_code=404, detail=f"checkpoint not found: {m}") + return str(p) + # Hugging Face repo id (org/name) + return m + + +def _resolve_lora_path(name: str) -> Path: + """Accept lora id, filename, or loras/... path.""" + raw = name.strip() + candidates: list[Path] = [] + if raw.startswith("loras/") or raw.endswith(".safetensors"): + candidates.append(MODELS_DIR / raw if not Path(raw).is_absolute() else Path(raw)) + else: + candidates.append(MODELS_DIR / "loras" / f"{raw}.safetensors") + candidates.append(MODELS_DIR / "loras" / raw) + if not raw.endswith(".safetensors"): + candidates.append(MODELS_DIR / "loras" / f"{raw}.safetensors") + for c in candidates: + try: + p = c.resolve() + except OSError: + continue + if str(p).startswith(str(MODELS_DIR)) and p.is_file(): + return p + raise HTTPException(status_code=404, detail=f"lora not found: {name}") + + +def _unload_locked() -> None: + global _pipe, _loaded_model, _loaded_loras + if _pipe is not None: + try: + del _pipe + except Exception: + pass + _pipe = None + _loaded_model = None + _loaded_loras = [] + gc.collect() + if torch.cuda.is_available(): + torch.cuda.empty_cache() + + +def _load_pipeline(model: str, base_model: str | None) -> Any: + from diffusers import ( + StableDiffusionPipeline, + StableDiffusionXLPipeline, + ) + + resolved = _resolve_model_path(model) + dtype = _dtype() + device = _device() + LOG.info("loading pipeline model=%s resolved=%s device=%s", model, resolved, device) + + common = { + "torch_dtype": dtype, + "safety_checker": None, + "requires_safety_checker": False, + } + + is_file = os.path.isfile(resolved) + use_xl = _looks_xl(model, base_model) or ( + is_file and Path(resolved).stat().st_size > 4_000_000_000 + ) + + if is_file: + if use_xl and not _looks_sd15(model, base_model): + pipe = StableDiffusionXLPipeline.from_single_file(resolved, **common) + else: + pipe = StableDiffusionPipeline.from_single_file(resolved, **common) + else: + if use_xl: + pipe = StableDiffusionXLPipeline.from_pretrained(resolved, **common) + else: + pipe = StableDiffusionPipeline.from_pretrained(resolved, **common) + + pipe = pipe.to(device) + if device == "cuda": + try: + pipe.enable_attention_slicing() + except Exception: + pass + return pipe + + +def _apply_loras(pipe: Any, lora_request: list[dict[str, Any]] | None) -> list[str]: + names: list[str] = [] + if not lora_request: + return names + adapters: list[str] = [] + weights: list[float] = [] + for i, item in enumerate(lora_request): + name = ( + item.get("lora_name") + or item.get("loraName") + or item.get("name") + or item.get("path") + or "" + ) + if not name: + continue + path = _resolve_lora_path(str(name)) + scale = float(item.get("strength") or item.get("scale") or item.get("weight") or 1.0) + adapter = f"lora_{i}" + LOG.info("load_lora %s -> %s scale=%s", name, path, scale) + pipe.load_lora_weights(str(path.parent), weight_name=path.name, adapter_name=adapter) + adapters.append(adapter) + weights.append(scale) + names.append(path.stem) + if adapters: + pipe.set_adapters(adapters, adapter_weights=weights) + return names + + +def _ensure_pipe( + model: str, + base_model: str | None, + lora_request: list[dict[str, Any]] | None, +) -> tuple[Any, list[str]]: + global _pipe, _loaded_model, _loaded_loras + want_loras = [] + if lora_request: + for item in lora_request: + n = item.get("lora_name") or item.get("loraName") or item.get("name") or item.get("path") + if n: + want_loras.append(str(n)) + same = ( + _pipe is not None + and _loaded_model == model + and _loaded_loras == want_loras + ) + if same: + return _pipe, list(_loaded_loras) + _unload_locked() + pipe = _load_pipeline(model, base_model) + applied = _apply_loras(pipe, lora_request) + _pipe = pipe + _loaded_model = model + _loaded_loras = want_loras + return pipe, applied + + +@app.get("/health") +def health() -> dict[str, Any]: + cuda = torch.cuda.is_available() + vram = None + if cuda: + try: + free, total = torch.cuda.mem_get_info() + vram = { + "usedMiB": int((total - free) / (1024 * 1024)), + "totalMiB": int(total / (1024 * 1024)), + } + except Exception: + vram = None + return { + "ok": True, + "engine": "diffusers", + "cuda": cuda, + "device": _device(), + "loadedInVram": _pipe is not None, + "model": _loaded_model, + "loras": list(_loaded_loras), + "keepLoaded": KEEP_LOADED, + "modelsDir": str(MODELS_DIR), + "vram": vram, + } + + +@app.post("/v1/unload") +def unload() -> dict[str, Any]: + with _lock: + _unload_locked() + return {"ok": True, "loadedInVram": False} + + +@app.post("/v1/generate_gif") +def generate_gif(req: GenerateReq) -> JSONResponse: + """Multi-frame SDXL animation → GIF (local motion path for gif modality).""" + if not req.prompt.strip(): + raise HTTPException(status_code=400, detail="prompt is required") + model = (req.model or "").strip() + if not model: + raise HTTPException(status_code=400, detail="model is required") + frames = max(2, min(int(req.frames or 6), 12)) + width, height = _parse_size(req.size or "768x768") + # Keep GIF frames modest for VRAM/time. + width = min(width, 768) + height = min(height, 768) + steps = min(req.steps or 15, 20) + guidance = req.guidance_scale if req.guidance_scale is not None else DEFAULT_GUIDANCE + base_seed = int(req.seed if req.seed is not None else 42) & 0xFFFFFFFF + device = _device() + + with _lock: + try: + pipe, lora_names = _ensure_pipe(model, req.base_model, req.lora_request) + images = [] + for i in range(frames): + gen = torch.Generator(device=device).manual_seed((base_seed + i * 17) & 0xFFFFFFFF) + kwargs: dict[str, Any] = { + "prompt": req.prompt, + "num_inference_steps": steps, + "guidance_scale": guidance, + "width": width, + "height": height, + "generator": gen, + } + if req.negative_prompt: + kwargs["negative_prompt"] = req.negative_prompt + out = pipe(**kwargs) + images.append(out.images[0]) + buf = io.BytesIO() + images[0].save( + buf, + format="GIF", + save_all=True, + append_images=images[1:], + duration=120, + loop=0, + ) + b64 = base64.b64encode(buf.getvalue()).decode("ascii") + if not KEEP_LOADED: + _unload_locked() + return JSONResponse( + { + "data": [{"b64_json": b64}], + "model": model, + "loras": lora_names, + "engine": "diffusers", + "format": "gif", + "frames": frames, + "stub": False, + "mime": "image/gif", + } + ) + except HTTPException: + raise + except Exception as e: + LOG.exception("gif generate failed") + _unload_locked() + raise HTTPException(status_code=500, detail=f"gif generate failed: {e}") from e + + +@app.post("/v1/generate") +def generate(req: GenerateReq) -> JSONResponse: + if not req.prompt.strip(): + raise HTTPException(status_code=400, detail="prompt is required") + model = (req.model or "").strip() + if not model: + raise HTTPException(status_code=400, detail="model is required") + + width, height = _parse_size(req.size) + steps = req.steps or DEFAULT_STEPS + guidance = req.guidance_scale if req.guidance_scale is not None else DEFAULT_GUIDANCE + seed = req.seed + device = _device() + generator = None + if seed is not None: + generator = torch.Generator(device=device).manual_seed(int(seed) & 0xFFFFFFFF) + + with _lock: + try: + pipe, lora_names = _ensure_pipe(model, req.base_model, req.lora_request) + kwargs: dict[str, Any] = { + "prompt": req.prompt, + "num_inference_steps": steps, + "guidance_scale": guidance, + "width": width, + "height": height, + } + if req.negative_prompt: + kwargs["negative_prompt"] = req.negative_prompt + if generator is not None: + kwargs["generator"] = generator + LOG.info( + "generate model=%s size=%sx%s steps=%s loras=%s", + model, + width, + height, + steps, + lora_names, + ) + out = pipe(**kwargs) + image = out.images[0] + buf = io.BytesIO() + image.save(buf, format="PNG") + b64 = base64.b64encode(buf.getvalue()).decode("ascii") + if not KEEP_LOADED: + _unload_locked() + return JSONResponse( + { + "data": [{"b64_json": b64}], + "model": model, + "loras": lora_names, + "engine": "diffusers", + "stub": False, + "width": width, + "height": height, + "steps": steps, + } + ) + except HTTPException: + raise + except Exception as e: + LOG.exception("generate failed") + _unload_locked() + raise HTTPException(status_code=500, detail=f"generate failed: {e}") from e + + +def main() -> None: + logging.basicConfig( + level=os.environ.get("FREYA_ENGINE_LOG", "INFO"), + format="%(asctime)s %(levelname)s %(name)s %(message)s", + ) + host = os.environ.get("FREYA_ENGINE_HOST", "127.0.0.1") + port = int(os.environ.get("FREYA_ENGINE_PORT", "8092")) + LOG.info( + "freya diffusers engine listening on %s:%s models=%s cuda=%s keep_loaded=%s", + host, + port, + MODELS_DIR, + torch.cuda.is_available(), + KEEP_LOADED, + ) + if torch.cuda.is_available(): + LOG.info("GPU: %s", torch.cuda.get_device_name(0)) + uvicorn.run(app, host=host, port=port, log_level="info") + + +if __name__ == "__main__": + main() diff --git a/deploy/worker/entrypoint.sh b/deploy/worker/entrypoint.sh new file mode 100755 index 0000000..9a90043 --- /dev/null +++ b/deploy/worker/entrypoint.sh @@ -0,0 +1,38 @@ +#!/usr/bin/env bash +# Start Diffusers engine (8092) then freya-worker (8091). +set -euo pipefail + +MODELS_DIR="${FREYA_MODELS_DIR:-/models}" +ENGINE_HOST="${FREYA_ENGINE_HOST:-127.0.0.1}" +ENGINE_PORT="${FREYA_ENGINE_PORT:-8092}" +export FREYA_MODELS_DIR="$MODELS_DIR" +export FREYA_ENGINE_URL="${FREYA_ENGINE_URL:-http://${ENGINE_HOST}:${ENGINE_PORT}}" + +# Empty model trees only — do not seed Freya demo / Civitai assets on first run. +mkdir -p "$MODELS_DIR/loras" "$MODELS_DIR/checkpoints" + +echo "freya-worker entrypoint: models=$MODELS_DIR engine=$FREYA_ENGINE_URL" + +python3 /opt/freya/engine/server.py & +ENGINE_PID=$! + +cleanup() { + kill "$ENGINE_PID" 2>/dev/null || true +} +trap cleanup EXIT INT TERM + +# Wait for engine health (up to ~60s) +for _ in $(seq 1 60); do + if curl -sf "http://${ENGINE_HOST}:${ENGINE_PORT}/health" >/dev/null 2>&1; then + echo "diffusers engine ready" + break + fi + if ! kill -0 "$ENGINE_PID" 2>/dev/null; then + echo "diffusers engine exited early" >&2 + wait "$ENGINE_PID" || true + exit 1 + fi + sleep 1 +done + +exec /usr/local/bin/freya-worker "$@" diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 86b99e0..a722ef1 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -1,14 +1,39 @@ # Architecture ``` -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) +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) ``` +## 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 | @@ -16,12 +41,21 @@ User → Freya UI → Freya API | 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); required for Ingress | +| 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 | Never put API keys in CRD string fields — only Secret references. ## Worker placement -- **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. +- **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 | diff --git a/docs/AUTH.md b/docs/AUTH.md new file mode 100644 index 0000000..1dd52d2 --- /dev/null +++ b/docs/AUTH.md @@ -0,0 +1,36 @@ +# Freya authentication + +Studio (API / UI / MCP) and auth Secrets live **in cluster** for the k8s path. The diffusion worker is usually **out of cluster** on the GPU host and authenticates with `FREYA_WORKER_TOKEN` / `FreyaDiffusionWorker.spec.authSecretRef` over its URL — see [ARCHITECTURE.md](ARCHITECTURE.md). + +**Compose (single-system):** no operator or admin Secret CRD. Set `FREYA_ADMIN_USER` / `FREYA_ADMIN_PASSWORD` (and optional `FREYA_API_TOKEN` / `FREYA_WORKER_TOKEN`) in `deploy/compose/.env`. See [COMPOSE.md](COMPOSE.md). + +## Default / fallback (game-operator style) + +Game operators (Palworld / Dragonwilds / Satisfactory Server Manager) provision an +**admin login** Secret (`admin` + `admin-password`) and protect the UI with HTTP Basic. + +Freya mirrors that as the human default: + +| Piece | Behavior | +|-------|----------| +| `FreyaStudio.spec.generateAdminSecrets` | Default **true**. Operator ensures `{name}-admin` Secret (`username`, `admin-password`) and, if `apiTokenSecretRef` is unset, `{name}-api-token` (`token`). | +| Status | `adminCredentialsSecretName`, `adminCredentialsGenerated`, `apiTokenSecretName` (never the password). | +| API | `FREYA_ADMIN_USER` / `FREYA_ADMIN_PASSWORD` from the admin Secret. Public `GET /v1/auth/status`, `POST /v1/auth/login`. Protected `/v1/*` accepts **Bearer** (machine token) or **Basic** (admin). | +| UI | Login modal + locked banner when unauthenticated; Send / Suggest / Run disabled with reason. | +| Machine clients | MCP / workers keep using the API bearer Secret — not the admin password. | + +Read the admin password (operators only): + +```bash +kubectl -n freya get secret freya-admin -o jsonpath='{.data.admin-password}' | base64 -d; echo +``` + +BYO: set `generateAdminSecrets: false` and `adminCredentialsSecretRef.name`, plus `apiTokenSecretRef`. + +## Longer-term: Authentik + Stoat + +- **Authentik** (`https://auth.dataknife.net`) is the lab IdP (gitops-tools). Most DockFire “Sign in” apps use it. +- **Stoat** (`stoat.dataknife.net`) is self-hosted chat (stoat-operator). Its **admin panel** already uses Authentik OIDC (`authentikId` / `authentikSecret` / `authentikIssuer` Secret) — not Traefik forward-auth on the chat UI itself. +- **Next Freya SSO step** (not implemented here): Authentik OAuth2/OIDC app for `freya.dataknife.net`, CRD fields `spec.oidc.secretRef` + issuer/client, API routes `/v1/auth/oidc/start|callback`, UI “Sign in with Authentik”. Keep admin password + machine bearer as fallback (same split as Stoat admin SSO vs game-operator basic). + +Do not invent a Freya-only IdP flow; follow Stoat-admin’s Authentik OIDC provider pattern when SSO lands. diff --git a/docs/COMPOSE.md b/docs/COMPOSE.md new file mode 100644 index 0000000..ab7048d --- /dev/null +++ b/docs/COMPOSE.md @@ -0,0 +1,121 @@ +# Single-system Docker Compose + +Run Freya on **one machine** without Kubernetes, kind, or the Freya operator. API + UI (+ optional MCP) and a local GPU worker share a Compose network. Host directories hold gallery, models, and secrets. + +The old ComfyUI / SwarmUI / Ollama stack stays under [`legacy/docker-compose.yml`](../legacy/docker-compose.yml) — do not mix the two. + +## Compose vs k8s + external worker + +| Path | What runs where | When to use | +|------|-----------------|-------------| +| **Compose (this doc)** | API, nginx UI, worker (+ optional MCP) on one host via `deploy/compose/` | Laptop / single GPU box; no cluster | +| **k8s + external worker** | Operator + FreyaStudio (API/UI/MCP/Ingress) in cluster; worker on the GPU host by URL | Shared cluster + lab GPU; see [LOCAL.md](LOCAL.md) / [ARCHITECTURE.md](ARCHITECTURE.md) | +| **Local cargo + Vite** | `make run-api` + `npm run dev` (+ `make run-worker`) | Day-to-day UI/API development | + +Compose does **not** use FreyaStudio / FreyaDiffusionWorker CRDs. Admin login is env-based (`FREYA_ADMIN_USER` / `FREYA_ADMIN_PASSWORD`). + +## Quick start + +```bash +cp deploy/compose/.env.example deploy/compose/.env +# edit: OPENROUTER_API_KEY, FREYA_ADMIN_PASSWORD (openssl rand -base64 24) +# optional: CIVITAI_API_KEY, FREYA_API_TOKEN, FREYA_WORKER_TOKEN + +# Host data dirs (lab defaults). Distroless images run as UID 65532. +mkdir -p /mnt/game2/freya/{gallery,models,secrets} +sudo chown -R 65532:65532 /mnt/game2/freya/gallery /mnt/game2/freya/secrets /mnt/game2/freya/models + +make compose-up # build + start api, web, worker +# make compose-up-gpu # same + nvidia device reservation +# make compose-up-mcp # also start freya-mcp (:8090) +``` + +Equivalent without Make: + +```bash +docker compose -f deploy/compose/compose.yaml --env-file deploy/compose/.env up -d --build +``` + +Stop: + +```bash +make compose-down +# or: docker compose -f deploy/compose/compose.yaml --env-file deploy/compose/.env down +``` + +## Ports + +| Service | Host port (default) | Notes | +|---------|---------------------|--------| +| **freya-web** (nginx UI) | **8080** | Proxies `/v1/` → `freya-api:8080` | +| **freya-worker** | (not published) | API uses `http://freya-worker:8091` on the Compose network | +| **freya-mcp** (profile `mcp`) | **127.0.0.1:8090** | Streamable HTTP at `/mcp`. Requires `FREYA_API_TOKEN` | +| freya-api | (internal only) | Reachable as `http://freya-api:8080` on the Compose network | + +Open **http://127.0.0.1:8080/** → Sign in with `FREYA_ADMIN_USER` / `FREYA_ADMIN_PASSWORD`. The API already has `FREYA_DIFFUSION_WORKER_URL=http://freya-worker:8091`. The worker port is not published on the host. + +## Volumes / host paths + +| Env | Default (lab) | Container mount | +|-----|---------------|-----------------| +| `FREYA_GALLERY_DIR` | `/mnt/game2/freya/gallery` | `/data/gallery` | +| `FREYA_MODELS_DIR` | `/mnt/game2/freya/models` | `/data/models` | +| `FREYA_SECRETS_DIR` | `/mnt/game2/freya/secrets` | `/data/secrets` (runtime → `.freya-runtime.json`) | + +Portable: set those to `./data/gallery`, `./data/models`, `./data/secrets` in `deploy/compose/.env` (paths relative to `deploy/compose/`). + +## Auth (no operator) + +| Mechanism | Compose | +|-----------|---------| +| Admin UI login | Set `FREYA_ADMIN_PASSWORD` in `.env` (and optional `FREYA_ADMIN_USER`) | +| Machine bearer | `FREYA_API_TOKEN` — required for MCP (`/mcp` returns 401 when empty). UI can also rotate via Worker → Generate API token (persists under secrets dir) | +| Worker bearer | Optional `FREYA_WORKER_TOKEN` — same value on API + worker | + +Empty tokens + empty admin password leave `/v1` open (local/dev warning). Prefer at least an admin password for anything beyond loopback. + +## GPU + +Default `make compose-up` runs the **stub** worker (no NVIDIA devices; generate returns placeholder PNGs; VRAM may be null). + +With [nvidia-container-toolkit](https://docs.nvidia.com/datacenter/cloud-native/container-toolkit/latest/install-guide.html): + +```bash +make compose-up-gpu +``` + +That merges [`deploy/compose/compose.gpu.yaml`](../deploy/compose/compose.gpu.yaml), builds [`Dockerfile.worker`](../Dockerfile.worker) (Diffusers + CUDA), and reserves a GPU. Weights load on demand from `FREYA_MODELS_DIR` and unload after generate unless `FREYA_ENGINE_KEEP_LOADED=1`. + +Standalone GPU host (Studio elsewhere): `./scripts/run-local-worker.sh` → container `freya-local-worker` on `:8091`. + +## MCP (optional) + +```bash +make compose-up-mcp +# Cursor / agents: http://127.0.0.1:8090/mcp +# Set FREYA_API_TOKEN in .env. Empty token is rejected. Host check stays on localhost. +``` + +## Images + +Compose builds from repo Dockerfiles: + +| Service | Dockerfile | Target | +|---------|------------|--------| +| freya-api | `Dockerfile` | `api` | +| freya-worker | `Dockerfile` (`worker`) or `Dockerfile.worker` with GPU overlay | stub / Diffusers+CUDA | +| freya-mcp | `Dockerfile` | `mcp` | +| freya-web | `Dockerfile.web` | (nginx) | + +First build compiles the Rust workspace and is slow; later rebuilds use Docker layer cache. + +## Makefile targets + +| Target | Action | +|--------|--------| +| `compose-up` | Build + start api, web, worker | +| `compose-up-gpu` | Same + GPU overlay | +| `compose-up-mcp` | Same + MCP profile | +| `compose-down` | Stop and remove containers | +| `compose-logs` | Follow logs | +| `compose-ps` | `docker compose ps` | diff --git a/docs/CONCEPTS.md b/docs/CONCEPTS.md index bc1f68d..5fbec5e 100644 --- a/docs/CONCEPTS.md +++ b/docs/CONCEPTS.md @@ -7,7 +7,20 @@ 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 | -| GPU UIs in-cluster | Optional `FreyaDiffusionWorker` (vLLM-Omni) in-cluster **or** remote host | +| 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. 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 17faf6e..755bdd0 100644 --- a/docs/LOCAL.md +++ b/docs/LOCAL.md @@ -1,5 +1,114 @@ # 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: @@ -11,39 +120,115 @@ make mock-ui 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, and Settings — in-memory with SVG placeholders. +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 keys -export $(grep -v '^#' .env | xargs) +cp .env.example .env # fill OPENROUTER_API_KEY (required); others optional +set -a && source .env && set +a make run-api # other terminal cd web && npm i && npm run dev -# optional +# GPU worker on this host (recommended; out of cluster) make run-worker -# Settings → worker URL http://127.0.0.1:8091 +# Worker tab → Host/Port → http://127.0.0.1:8091 (or LAN IP / FQDN from in-cluster Studio) # 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 `